diff --git a/.env.example b/.env.example index bd3a8150..2bbe9bff 100644 --- a/.env.example +++ b/.env.example @@ -1,9 +1,12 @@ # ============================================================== # Study Bot environment configuration # -# Quick start: run `npm run setup` — it copies this file to .env, +# Quick start: run `npm run setup`. It copies this file to .env, # generates the secrets marked "auto-filled" below, starts the # database via Docker, and applies migrations. +# +# The defaults run fully offline: mock AI, console email, and a +# fake Google Calendar client. # ============================================================== # --- Database ------------------------------------------------- @@ -12,62 +15,78 @@ # If you run your own Postgres instead of Docker, point this at it. DATABASE_URL="postgresql://postgres:postgres@localhost:5433/studybot?schema=public" -# --- App URLs ------------------------------------------------- -BASE_URL="http://localhost:3000" -NEXT_PUBLIC_APP_URL="http://localhost:3000" +# --- App URL -------------------------------------------------- +BASE_URL="http://localhost:3000" # public origin; used in session links, emails, and OAuth redirects # --- Authentication (NextAuth) -------------------------------- -NEXTAUTH_URL="http://localhost:3000" +NEXTAUTH_URL="http://localhost:3000" # must match the origin you browse to; https enables secure cookies NEXTAUTH_SECRET="" # auto-filled by `npm run setup` (or: openssl rand -base64 32) +# AUTH_SECRET="" # read only when NEXTAUTH_SECRET is empty (next-auth accepts either name) + +# Require users to verify their email address before signing in. +# Leave off unless real SMTP is configured below; with the console +# provider, verification links only appear in the server logs. +# REQUIRE_EMAIL_VERIFICATION="true" # --- Admin & Security ----------------------------------------- -ADMIN_USER_IDS="" # comma-separated user UUIDs allowed to access /admin +ADMIN_USER_IDS="" # comma-separated user IDs allowed to call the /api/admin/* endpoints (there is no admin page) # WARNING: ALLOW_TEST_AUTH makes the app trust the X-User-Id header -# as the authenticated identity. It exists ONLY for automated tests. -# It must NEVER be set in production — leave it commented out. +# as the signed-in user. It exists ONLY for automated tests, and a +# production build ignores it unless CI=true. It also needs NEXTAUTH_URL +# on a loopback host (localhost, 127.0.0.1). Leave it commented out. # ALLOW_TEST_AUTH="true" +# Sign-in and sign-up limits key on the client's address. In production run +# behind a reverse proxy that appends X-Forwarded-For, and set this to the +# number of proxies that append to it (for example 2 for a CDN plus nginx). +# TRUSTED_PROXY_HOPS="1" + # --- Logging -------------------------------------------------- -LOG_LEVEL="info" # debug | info | warn | error +LOG_LEVEL="info" # debug | info | warn | error | silent # --- Email ---------------------------------------------------- -EMAIL_PROVIDER="console" # console | smtp -SMTP_HOST="" -SMTP_PORT="587" -SMTP_USER="" -SMTP_PASS="" -SMTP_FROM="Study Bot " +EMAIL_PROVIDER="console" # console (print to server logs outside production) | smtp; production without smtp turns reset links off +SMTP_HOST="" # SMTP server host, required when EMAIL_PROVIDER="smtp" +SMTP_PORT="587" # SMTP port; 465 uses TLS from the start +SMTP_USER="" # SMTP username +SMTP_PASS="" # SMTP password +SMTP_FROM="Study Bot " # From header on outgoing mail -# Require users to verify their email address before signing in. -# Default: off (unset/false) — new accounts can sign in immediately. -# Only enable this with a real SMTP provider configured above; with the -# console provider, verification links are only printed to the server logs. -# REQUIRE_EMAIL_VERIFICATION="true" +# --- Uploads -------------------------------------------------- +UPLOAD_DIR="./data/uploads" # where uploaded documents are stored, relative to the project root # --- Google Calendar Integration ------------------------------ -GOOGLE_CLIENT_ID="" -GOOGLE_CLIENT_SECRET="" -GOOGLE_REDIRECT_URI="" # defaults to BASE_URL + /api/integrations/google/callback -TOKEN_ENC_KEY="" # auto-filled by `npm run setup` — 32 bytes: 64 hex chars or 44 base64 chars (required in production) -GOOGLE_PROVIDER="fake" # fake | real — use "fake" in test/CI, "real" in production -GOOGLE_SYNC_CONCURRENCY="3" # max concurrent Google API calls during publish +GOOGLE_PROVIDER="fake" # fake (in-memory, for dev and tests) | real (calls Google) +GOOGLE_CLIENT_ID="" # OAuth client ID, required when GOOGLE_PROVIDER="real" +GOOGLE_CLIENT_SECRET="" # OAuth client secret, required when GOOGLE_PROVIDER="real" +GOOGLE_REDIRECT_URI="" # defaults to BASE_URL + /api/integrations/google/callback +TOKEN_ENC_KEY="" # auto-filled by `npm run setup`; encrypts stored OAuth tokens (32 bytes: 64 hex or 44 base64 chars) +GOOGLE_SYNC_CONCURRENCY="3" # max concurrent Google Calendar calls while publishing or unpublishing a plan # --- AI Control Plane ----------------------------------------- -AI_PROVIDER="mock" # mock | openai -OPENAI_API_KEY="" # required when AI_PROVIDER="openai" -AI_MODEL_ANSWER="gpt-4o-mini" -AI_MODEL_EMBED="text-embedding-3-small" +AI_PROVIDER="mock" # mock (canned output, for tests) | openai +OPENAI_API_KEY="" # required when AI_PROVIDER="openai" +AI_MODEL_ANSWER="gpt-4o-mini" # model for questions, feedback, chat, and plans +AI_MODEL_EMBED="text-embedding-3-small" # model for document embeddings AI_REQUEST_TIMEOUT_MS="60000" # abort AI provider requests after this many ms -AI_CACHE_TTL_SECONDS="3600" -AI_DAILY_COST_CAP_USD="1.0" # max spend per user per day (default $1) -AI_MONTHLY_COST_CAP_USD="10.0" # max spend per user per month (default $10) -AI_DISABLED="false" # emergency kill switch — set "true" to block all AI calls -# MOCK_AI_MALFORMED="1" # test-only: makes the mock provider emit malformed output (never set outside tests) +AI_CACHE_TTL_SECONDS="3600" # how long identical AI responses are reused +AI_DAILY_COST_CAP_USD="1.0" # max spend per user per day +AI_DAILY_EMBED_COST_CAP_USD="0.10" # max spend per user per day on embedding uploaded files +AI_MONTHLY_COST_CAP_USD="10.0" # max spend per user per month +# AI_GLOBAL_DAILY_COST_CAP_USD="25.0" # max spend per day across every account (unset: no ceiling) +AI_DISABLED="false" # emergency kill switch; "true" blocks all AI calls +# MOCK_AI_MALFORMED="1" # test-only: makes the mock provider emit malformed output -# --- Background Worker ---------------------------------------- -JOB_WORKER_CONCURRENCY="2" -JOB_POLL_INTERVAL_MS="2000" +# --- Background Worker (npm run worker) ----------------------- +JOB_WORKER_CONCURRENCY="2" # jobs processed in parallel +JOB_POLL_INTERVAL_MS="2000" # how often the worker checks for new jobs # --- Hybrid Search -------------------------------------------- -HYBRID_SEARCH_ENABLED="false" +HYBRID_SEARCH_ENABLED="false" # "true" adds embedding search to full-text search (needs pgvector and the worker) + +# --- Set by tooling; do not set these here -------------------- +# NODE_ENV set by next dev / next build / next start +# CI set by CI runners; lets ALLOW_TEST_AUTH work in a production build +# VITEST set by the test runner; silences the logger unless LOG_LEVEL is set +# NEXT_PHASE set by next build; the missing-email warning stays quiet during the build diff --git a/.eslintrc.json b/.eslintrc.json deleted file mode 100644 index addcaf2e..00000000 --- a/.eslintrc.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "extends": "next/core-web-vitals", - "rules": { - "@typescript-eslint/no-require-imports": "off" - } -} diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 00000000..04ebf190 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,22 @@ +version: 2 +updates: + - package-ecosystem: npm + directory: / + schedule: + interval: weekly + open-pull-requests-limit: 5 + groups: + # One PR a week for routine updates; major versions still get their own + npm-minor-and-patch: + update-types: + - minor + - patch + + - package-ecosystem: github-actions + directory: / + schedule: + interval: monthly + groups: + github-actions: + patterns: + - "*" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d75d1234..e758e390 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -5,6 +5,10 @@ on: branches: [main] pull_request: branches: [main] + workflow_dispatch: + +permissions: + contents: read concurrency: group: ci-${{ github.ref }} @@ -13,36 +17,45 @@ concurrency: env: NEXT_TELEMETRY_DISABLED: "1" +# npm ci runs `prisma generate` through the postinstall script, so no job +# needs a separate generate step. + jobs: lint-and-build: - name: Lint & Build + name: Lint, Typecheck & Build runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v7 - - uses: actions/setup-node@v4 + - uses: actions/setup-node@v7 with: - node-version: 22 + node-version-file: .nvmrc cache: npm + - uses: actions/cache@v6 + with: + path: .next/cache + key: nextjs-${{ runner.os }}-${{ hashFiles('package-lock.json') }}-${{ hashFiles('src/**', 'next.config.js', 'tsconfig.json') }} + restore-keys: | + nextjs-${{ runner.os }}-${{ hashFiles('package-lock.json') }}- + - run: npm ci - - run: npx prisma generate - run: npm run lint + - run: npm run typecheck - run: npm run build unit-tests: name: Unit Tests runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v7 - - uses: actions/setup-node@v4 + - uses: actions/setup-node@v7 with: - node-version: 22 + node-version-file: .nvmrc cache: npm - run: npm ci - - run: npx prisma generate - run: npm run test:unit integration-tests: @@ -69,25 +82,31 @@ jobs: DATABASE_URL: postgresql://postgres:postgres@localhost:5432/studybot_test?schema=public steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v7 - - uses: actions/setup-node@v4 + - uses: actions/setup-node@v7 with: - node-version: 22 + node-version-file: .nvmrc cache: npm - run: npm ci - - run: npx prisma generate - name: Apply migration history to test DB run: npx prisma migrate deploy - name: Apply pgvector migration - run: psql "${DATABASE_URL%%\?*}" -f prisma/manual-scripts/001_pgvector.sql + run: npx prisma db execute --file prisma/manual-scripts/001_pgvector.sql - run: npm run test:integration e2e-tests: - name: E2E Tests + name: E2E Tests (shard ${{ matrix.shard }} of 2) runs-on: ubuntu-latest needs: [lint-and-build, unit-tests, integration-tests] + timeout-minutes: 20 + # Each shard builds the app and runs half the tests against its own + # server and database. The setup project runs in both. + strategy: + fail-fast: false + matrix: + shard: [1, 2] services: postgres: @@ -104,32 +123,50 @@ jobs: --health-timeout 5s --health-retries 5 + # playwright.config.ts builds the app and starts `next start -p $E2E_PORT` + # with the offline providers (mock AI, fake Google, console email) and + # ALLOW_TEST_AUTH=true. GitHub sets CI=true, which is what lets the + # production build trust the specs' X-User-Id header. The suite runs the + # setup, chromium (Desktop Chrome) and mobile (Pixel 7, @mobile tests) + # projects; all of them use Chromium. DATABASE_URL is set for the test + # runner too: a few tests write rows the API can't reach. env: DATABASE_URL: postgresql://postgres:postgres@localhost:5432/studybot_e2e?schema=public - BASE_URL: http://localhost:3000 + E2E_PORT: "3000" steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v7 - - uses: actions/setup-node@v4 + - uses: actions/setup-node@v7 with: - node-version: 22 + node-version-file: .nvmrc cache: npm + - uses: actions/cache@v6 + with: + path: .next/cache + key: nextjs-${{ runner.os }}-${{ hashFiles('package-lock.json') }}-${{ hashFiles('src/**', 'next.config.js', 'tsconfig.json') }} + restore-keys: | + nextjs-${{ runner.os }}-${{ hashFiles('package-lock.json') }}- + - run: npm ci - - run: npx prisma generate - name: Apply migration history to test DB run: npx prisma migrate deploy - name: Apply pgvector migration - run: psql "${DATABASE_URL%%\?*}" -f prisma/manual-scripts/001_pgvector.sql + run: npx prisma db execute --file prisma/manual-scripts/001_pgvector.sql - run: npx playwright install --with-deps chromium - - run: npm run test:e2e + - run: npm run test:e2e -- --shard=${{ matrix.shard }}/2 + + - uses: actions/upload-artifact@v7 + if: ${{ !cancelled() }} + with: + name: playwright-report-${{ matrix.shard }} + path: playwright-report/ + retention-days: 14 - - uses: actions/upload-artifact@v4 + - uses: actions/upload-artifact@v7 if: failure() with: - name: playwright-report - path: | - playwright-report/ - test-results/ + name: playwright-test-results-${{ matrix.shard }} + path: test-results/ retention-days: 7 diff --git a/.gitignore b/.gitignore index c88c119e..55d5e17f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,41 +1,41 @@ -# dependencies +# Dependencies /node_modules /.pnp .pnp.js -# testing -/coverage -/test-results -/playwright-report - -# next.js +# Build output /.next/ /out/ - -# production /build +*.tsbuildinfo +next-env.d.ts -# misc -.DS_Store -*.pem +# Generated code +/generated/prisma -# debug -npm-debug.log* -yarn-debug.log* -yarn-error.log* +# Tests +/coverage +playwright-report/ +test-results/ +# Signed-in browser state saved by the e2e setup project +e2e/.auth/ -# local env files -.env*.local -.env +# Local data (uploads and other runtime files) +data/ -# vercel -.vercel +# Environment and secrets +.env +.env*.local +*.pem -# typescript -*.tsbuildinfo -next-env.d.ts +# Logs +*.log -/generated/prisma +# Editors, OS files and local tool state +.idea/ +.vscode/ +.DS_Store +Thumbs.db -# uploaded content -/data/uploads +# Vercel +.vercel diff --git a/DESIGN.md b/DESIGN.md new file mode 100644 index 00000000..035a404e --- /dev/null +++ b/DESIGN.md @@ -0,0 +1,827 @@ +--- +name: Study Bot +description: Plan for your exams and practice from your own course files. +colors: + # Shell roles, light theme (:root) + surface: "#f8fafd" + surface-container-lowest: "#ffffff" + surface-container-low: "#f8fafd" + surface-container: "#f0f4f9" + surface-container-high: "#e9eef6" + surface-container-highest: "#dde3ea" + on-surface: "#1f1f1f" + on-surface-variant: "#444746" + outline: "#747775" + outline-variant: "#c4c7c5" + primary: "#0b57d0" + on-primary: "#ffffff" + primary-container: "#d3e3fd" + on-primary-container: "#041e49" + secondary-container: "#c2e7ff" + on-secondary-container: "#001d35" + tertiary: "#146c2e" + on-tertiary: "#ffffff" + tertiary-container: "#c4eed0" + on-tertiary-container: "#072711" + error: "#b3261e" + on-error: "#ffffff" + error-container: "#f9dedc" + on-error-container: "#410e0b" + warning: "#995c00" + on-warning: "#ffffff" + warning-container: "#feefc3" + on-warning-container: "#5c3d00" + inverse-surface: "#303030" + inverse-on-surface: "#f2f2f2" + inverse-primary: "#a8c7fa" + scrim: "#000000" + chart-1: "#0b57d0" + chart-2: "#146c2e" + chart-3: "#995c00" + chart-4: "#b3261e" + chart-5: "#6e4bc0" + # Lesson palette, light theme (inside .lesson only) + lesson-surface: "#ffffff" + lesson-on-surface: "#1f1f1f" + lesson-muted: "#5f6368" + lesson-option: "#ffffff" + lesson-option-border: "#dadce0" + lesson-option-hover: "#f8f9fa" + lesson-selected: "#e8f0fe" + lesson-selected-border: "#1a73e8" + lesson-selected-lip: "#185abc" + lesson-on-selected: "#174ea6" + lesson-primary: "#1a73e8" + lesson-primary-hover: "#1967d2" + lesson-primary-lip: "#185abc" + lesson-on-primary: "#ffffff" + lesson-check: "#188038" + lesson-check-hover: "#137333" + lesson-check-lip: "#0d652d" + lesson-on-check: "#ffffff" + lesson-correct: "#e6f4ea" + lesson-on-correct: "#137333" + lesson-wrong: "#fce8e6" + lesson-on-wrong: "#a50e0e" + lesson-wrong-button: "#c5221f" + lesson-wrong-button-hover: "#b31412" + lesson-wrong-lip: "#a50e0e" + lesson-on-wrong-button: "#ffffff" + lesson-neutral-text: "#3c4043" + lesson-disabled: "#e8eaed" + lesson-on-disabled: "#80868b" + lesson-progress-track: "#e8eaed" + lesson-progress-fill: "#1e8e3e" + # Shell roles, dark theme (.dark) + surface-dark: "#131314" + surface-container-lowest-dark: "#0e0e0e" + surface-container-low-dark: "#1b1b1b" + surface-container-dark: "#1e1f20" + surface-container-high-dark: "#282a2c" + surface-container-highest-dark: "#333537" + on-surface-dark: "#e3e3e3" + on-surface-variant-dark: "#c4c7c5" + outline-dark: "#8e918f" + outline-variant-dark: "#444746" + primary-dark: "#a8c7fa" + on-primary-dark: "#062e6f" + primary-container-dark: "#0842a0" + on-primary-container-dark: "#d3e3fd" + secondary-container-dark: "#004a77" + on-secondary-container-dark: "#c2e7ff" + tertiary-dark: "#6dd58c" + on-tertiary-dark: "#0a3818" + tertiary-container-dark: "#0f5223" + on-tertiary-container-dark: "#c4eed0" + error-dark: "#f2b8b5" + on-error-dark: "#601410" + error-container-dark: "#8c1d18" + on-error-container-dark: "#f9dedc" + warning-dark: "#fdd663" + on-warning-dark: "#3d2e00" + warning-container-dark: "#5a4300" + on-warning-container-dark: "#feefc3" + inverse-surface-dark: "#e3e3e3" + inverse-on-surface-dark: "#303030" + inverse-primary-dark: "#0b57d0" + chart-1-dark: "#a8c7fa" + chart-2-dark: "#6dd58c" + chart-3-dark: "#fdd663" + chart-4-dark: "#f2b8b5" + chart-5-dark: "#d0bcff" + # Lesson palette, dark theme + lesson-surface-dark: "#131314" + lesson-on-surface-dark: "#e3e3e3" + lesson-muted-dark: "#bdc1c6" + lesson-option-dark: "#131314" + lesson-option-border-dark: "#3c4043" + lesson-option-hover-dark: "#1e1f20" + lesson-selected-dark: "#1c2b41" + lesson-selected-border-dark: "#8ab4f8" + lesson-selected-lip-dark: "#669df6" + lesson-on-selected-dark: "#d2e3fc" + lesson-primary-dark: "#8ab4f8" + lesson-primary-hover-dark: "#aecbfa" + lesson-primary-lip-dark: "#5e97f6" + lesson-on-primary-dark: "#062e6f" + lesson-check-dark: "#81c995" + lesson-check-hover-dark: "#a8dab5" + lesson-check-lip-dark: "#4ca866" + lesson-on-check-dark: "#0d3a1f" + lesson-correct-dark: "#122a1b" + lesson-on-correct-dark: "#81c995" + lesson-wrong-dark: "#3a1a18" + lesson-on-wrong-dark: "#f28b82" + lesson-wrong-button-dark: "#f28b82" + lesson-wrong-button-hover-dark: "#f6aea9" + lesson-wrong-lip-dark: "#d9655b" + lesson-on-wrong-button-dark: "#601410" + lesson-neutral-text-dark: "#e8eaed" + lesson-disabled-dark: "#282a2c" + lesson-on-disabled-dark: "#9aa0a6" + lesson-progress-track-dark: "#3c4043" + lesson-progress-fill-dark: "#81c995" +typography: + display-l: + fontFamily: '"Google Sans Flex Variable", "Google Sans", ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif' + fontSize: "3.5625rem" + fontWeight: 400 + lineHeight: "4rem" + letterSpacing: "-0.25px" + fontVariation: "'ROND' 0" + display-m: + fontFamily: '"Google Sans Flex Variable", "Google Sans", ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif' + fontSize: "2.8125rem" + fontWeight: 400 + lineHeight: "3.25rem" + letterSpacing: "0" + fontVariation: "'ROND' 0" + display-s: + fontFamily: '"Google Sans Flex Variable", "Google Sans", ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif' + fontSize: "2.25rem" + fontWeight: 400 + lineHeight: "2.75rem" + letterSpacing: "0" + fontVariation: "'ROND' 0" + headline-l: + fontFamily: '"Google Sans Flex Variable", "Google Sans", ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif' + fontSize: "2rem" + fontWeight: 400 + lineHeight: "2.5rem" + letterSpacing: "0" + fontVariation: "'ROND' 0" + headline-m: + fontFamily: '"Google Sans Flex Variable", "Google Sans", ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif' + fontSize: "1.75rem" + fontWeight: 400 + lineHeight: "2.25rem" + letterSpacing: "0" + fontVariation: "'ROND' 0" + headline-s: + fontFamily: '"Google Sans Flex Variable", "Google Sans", ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif' + fontSize: "1.5rem" + fontWeight: 400 + lineHeight: "2rem" + letterSpacing: "0" + fontVariation: "'ROND' 0" + title-l: + fontFamily: '"Google Sans Flex Variable", "Google Sans", ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif' + fontSize: "1.375rem" + fontWeight: 400 + lineHeight: "1.75rem" + letterSpacing: "0" + fontVariation: "'ROND' 0" + title-m: + fontFamily: '"Google Sans Flex Variable", "Google Sans", ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif' + fontSize: "1rem" + fontWeight: 500 + lineHeight: "1.5rem" + letterSpacing: "0.15px" + fontVariation: "'ROND' 0" + title-s: + fontFamily: '"Google Sans Flex Variable", "Google Sans", ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif' + fontSize: "0.875rem" + fontWeight: 500 + lineHeight: "1.25rem" + letterSpacing: "0.1px" + fontVariation: "'ROND' 0" + body-l: + fontFamily: '"Google Sans Flex Variable", "Google Sans", ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif' + fontSize: "1rem" + fontWeight: 400 + lineHeight: "1.5rem" + letterSpacing: "0.5px" + fontVariation: "'ROND' 0" + body-m: + fontFamily: '"Google Sans Flex Variable", "Google Sans", ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif' + fontSize: "0.875rem" + fontWeight: 400 + lineHeight: "1.25rem" + letterSpacing: "0.25px" + fontVariation: "'ROND' 0" + body-s: + fontFamily: '"Google Sans Flex Variable", "Google Sans", ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif' + fontSize: "0.75rem" + fontWeight: 400 + lineHeight: "1rem" + letterSpacing: "0.4px" + fontVariation: "'ROND' 0" + label-l: + fontFamily: '"Google Sans Flex Variable", "Google Sans", ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif' + fontSize: "0.875rem" + fontWeight: 500 + lineHeight: "1.25rem" + letterSpacing: "0.1px" + fontVariation: "'ROND' 0" + label-m: + fontFamily: '"Google Sans Flex Variable", "Google Sans", ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif' + fontSize: "0.75rem" + fontWeight: 500 + lineHeight: "1rem" + letterSpacing: "0.5px" + fontVariation: "'ROND' 0" + label-s: + fontFamily: '"Google Sans Flex Variable", "Google Sans", ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif' + fontSize: "0.6875rem" + fontWeight: 500 + lineHeight: "1rem" + letterSpacing: "0.5px" + fontVariation: "'ROND' 0" + lesson-question: + fontFamily: '"Google Sans Flex Variable", "Google Sans", ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif' + fontSize: "1.75rem" + fontWeight: 700 + lineHeight: "2.25rem" + letterSpacing: "0" + fontVariation: "'ROND' 100" + lesson-question-compact: + fontFamily: '"Google Sans Flex Variable", "Google Sans", ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif' + fontSize: "1.5rem" + fontWeight: 700 + lineHeight: "2rem" + letterSpacing: "0" + fontVariation: "'ROND' 100" + lesson-body: + fontFamily: '"Google Sans Flex Variable", "Google Sans", ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif' + fontSize: "0.875rem" + fontWeight: 500 + lineHeight: "1.25rem" + letterSpacing: "0.25px" + fontVariation: "'ROND' 100" + lesson-option: + fontFamily: '"Google Sans Flex Variable", "Google Sans", ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif' + fontSize: "1.125rem" + fontWeight: 500 + lineHeight: "1.75rem" + letterSpacing: "0" + fontVariation: "'ROND' 100" + lesson-button: + fontFamily: '"Google Sans Flex Variable", "Google Sans", ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif' + fontSize: "1rem" + fontWeight: 700 + lineHeight: "1.5rem" + letterSpacing: "0.2px" + fontVariation: "'ROND' 100" + code: + fontFamily: '"Google Sans Code Variable", ui-monospace, "Cascadia Code", Menlo, Consolas, monospace' + fontSize: "0.875rem" + fontWeight: 400 + lineHeight: "1.25rem" +rounded: + xs: "4px" + sm: "4px" + md: "8px" + lg: "12px" + xl: "12px" + 2xl: "16px" + 3xl: "24px" + 4xl: "28px" + full: "9999px" +spacing: + unit: "4px" + gutter-compact: "16px" + gutter-medium: "24px" + gutter-expanded: "32px" + section-gap: "24px" + stack-gap: "12px" + card-padding: "24px" + card-padding-sm: "16px" + page-bottom: "40px" + lesson-gutter-compact: "16px" + lesson-gutter: "32px" +components: + button-filled: + backgroundColor: "{colors.primary}" + textColor: "{colors.on-primary}" + typography: "{typography.label-l}" + rounded: "{rounded.full}" + height: "40px" + padding: "0 24px" + button-tonal: + backgroundColor: "{colors.secondary-container}" + textColor: "{colors.on-secondary-container}" + typography: "{typography.label-l}" + rounded: "{rounded.full}" + height: "40px" + padding: "0 24px" + button-outlined: + backgroundColor: "transparent" + textColor: "{colors.primary}" + typography: "{typography.label-l}" + rounded: "{rounded.full}" + height: "40px" + padding: "0 24px" + button-text: + backgroundColor: "transparent" + textColor: "{colors.primary}" + typography: "{typography.label-l}" + rounded: "{rounded.full}" + height: "40px" + padding: "0 24px" + button-destructive: + backgroundColor: "{colors.error}" + textColor: "{colors.on-error}" + typography: "{typography.label-l}" + rounded: "{rounded.full}" + height: "40px" + padding: "0 24px" + button-icon: + backgroundColor: "transparent" + textColor: "{colors.on-surface-variant}" + rounded: "{rounded.full}" + size: "40px" + badge-success: + backgroundColor: "{colors.tertiary-container}" + textColor: "{colors.on-tertiary-container}" + typography: "{typography.label-m}" + rounded: "{rounded.full}" + height: "24px" + padding: "0 10px" + badge-warning: + backgroundColor: "{colors.warning-container}" + textColor: "{colors.on-warning-container}" + typography: "{typography.label-m}" + rounded: "{rounded.full}" + height: "24px" + padding: "0 10px" + badge-error: + backgroundColor: "{colors.error-container}" + textColor: "{colors.on-error-container}" + typography: "{typography.label-m}" + rounded: "{rounded.full}" + height: "24px" + padding: "0 10px" + card: + backgroundColor: "{colors.surface-container-lowest}" + textColor: "{colors.on-surface}" + rounded: "{rounded.2xl}" + padding: "24px" + card-sm: + backgroundColor: "{colors.surface-container-lowest}" + textColor: "{colors.on-surface}" + rounded: "{rounded.2xl}" + padding: "16px" + countdown-card-featured: + backgroundColor: "{colors.primary-container}" + textColor: "{colors.on-primary-container}" + rounded: "{rounded.2xl}" + padding: "20px" + alert-info: + backgroundColor: "{colors.primary-container}" + textColor: "{colors.on-primary-container}" + typography: "{typography.body-m}" + rounded: "{rounded.lg}" + padding: "12px 16px" + text-field: + backgroundColor: "transparent" + textColor: "{colors.on-surface}" + rounded: "{rounded.md}" + height: "48px" + padding: "8px 16px" + textarea: + backgroundColor: "transparent" + textColor: "{colors.on-surface}" + rounded: "{rounded.md}" + height: "96px" + padding: "12px 16px" + top-app-bar: + backgroundColor: "{colors.surface}" + textColor: "{colors.on-surface}" + typography: "{typography.title-l}" + height: "64px" + navigation-rail: + backgroundColor: "{colors.surface}" + textColor: "{colors.on-surface-variant}" + width: "80px" + nav-indicator-active: + backgroundColor: "{colors.secondary-container}" + textColor: "{colors.on-secondary-container}" + rounded: "{rounded.full}" + width: "56px" + height: "32px" + bottom-navigation: + backgroundColor: "{colors.surface-container}" + textColor: "{colors.on-surface-variant}" + height: "80px" + session-fab: + backgroundColor: "{colors.primary-container}" + textColor: "{colors.on-primary-container}" + rounded: "{rounded.2xl}" + size: "56px" + dialog: + backgroundColor: "{colors.surface-container-high}" + textColor: "{colors.on-surface}" + rounded: "{rounded.4xl}" + padding: "24px" + bottom-sheet: + backgroundColor: "{colors.surface-container-low}" + textColor: "{colors.on-surface}" + rounded: "{rounded.4xl}" + padding: "24px" + tooltip: + backgroundColor: "{colors.inverse-surface}" + textColor: "{colors.inverse-on-surface}" + typography: "{typography.body-s}" + rounded: "{rounded.sm}" + padding: "4px 8px" + snackbar: + backgroundColor: "{colors.inverse-surface}" + textColor: "{colors.inverse-on-surface}" + typography: "{typography.body-m}" + rounded: "{rounded.sm}" + progress-linear: + backgroundColor: "{colors.primary}" + rounded: "{rounded.full}" + height: "4px" + mastery-bar-track: + backgroundColor: "{colors.surface-container-highest}" + rounded: "{rounded.full}" + height: "8px" + lesson-progress: + backgroundColor: "{colors.lesson-progress-fill}" + rounded: "{rounded.full}" + height: "16px" + lesson-progress-track: + backgroundColor: "{colors.lesson-progress-track}" + rounded: "{rounded.full}" + height: "16px" + lesson-button-check: + backgroundColor: "{colors.lesson-check}" + textColor: "{colors.lesson-on-check}" + typography: "{typography.lesson-button}" + rounded: "{rounded.2xl}" + height: "48px" + padding: "8px 24px" + lesson-button-check-hover: + backgroundColor: "{colors.lesson-check-hover}" + textColor: "{colors.lesson-on-check}" + lesson-button-primary: + backgroundColor: "{colors.lesson-primary}" + textColor: "{colors.lesson-on-primary}" + typography: "{typography.lesson-button}" + rounded: "{rounded.2xl}" + height: "48px" + padding: "8px 24px" + lesson-button-primary-hover: + backgroundColor: "{colors.lesson-primary-hover}" + textColor: "{colors.lesson-on-primary}" + lesson-button-wrong: + backgroundColor: "{colors.lesson-wrong-button}" + textColor: "{colors.lesson-on-wrong-button}" + typography: "{typography.lesson-button}" + rounded: "{rounded.2xl}" + height: "48px" + padding: "8px 24px" + lesson-button-wrong-hover: + backgroundColor: "{colors.lesson-wrong-button-hover}" + textColor: "{colors.lesson-on-wrong-button}" + lesson-button-neutral: + backgroundColor: "{colors.lesson-option}" + textColor: "{colors.lesson-neutral-text}" + typography: "{typography.lesson-button}" + rounded: "{rounded.2xl}" + height: "48px" + padding: "8px 24px" + lesson-button-neutral-hover: + backgroundColor: "{colors.lesson-option-hover}" + textColor: "{colors.lesson-neutral-text}" + lesson-button-disabled: + backgroundColor: "{colors.lesson-disabled}" + textColor: "{colors.lesson-on-disabled}" + answer-option: + backgroundColor: "{colors.lesson-option}" + textColor: "{colors.lesson-on-surface}" + typography: "{typography.lesson-option}" + rounded: "{rounded.2xl}" + height: "64px" + padding: "12px 16px" + answer-option-hover: + backgroundColor: "{colors.lesson-option-hover}" + textColor: "{colors.lesson-on-surface}" + answer-option-selected: + backgroundColor: "{colors.lesson-selected}" + textColor: "{colors.lesson-on-selected}" + answer-option-correct: + backgroundColor: "{colors.lesson-correct}" + textColor: "{colors.lesson-on-correct}" + answer-option-wrong: + backgroundColor: "{colors.lesson-wrong}" + textColor: "{colors.lesson-on-wrong}" + confidence-chip: + backgroundColor: "{colors.lesson-option}" + textColor: "{colors.lesson-on-surface}" + typography: "{typography.lesson-button}" + rounded: "{rounded.2xl}" + height: "48px" + padding: "8px 12px" + confidence-chip-selected: + backgroundColor: "{colors.lesson-selected}" + textColor: "{colors.lesson-on-selected}" + free-recall-input: + backgroundColor: "{colors.lesson-option}" + textColor: "{colors.lesson-on-surface}" + typography: "{typography.lesson-option}" + rounded: "{rounded.2xl}" + height: "112px" + padding: "12px 16px" + feedback-sheet-correct: + backgroundColor: "{colors.lesson-correct}" + textColor: "{colors.lesson-on-correct}" + padding: "24px 32px" + feedback-sheet-wrong: + backgroundColor: "{colors.lesson-wrong}" + textColor: "{colors.lesson-on-wrong}" + padding: "24px 32px" + feedback-sheet-neutral: + backgroundColor: "{colors.surface-container}" + textColor: "{colors.on-surface}" + padding: "24px 32px" +--- + +# Design system: Study Bot + +## Overview + +North star: a Google app that turns into a lesson when you start studying. + +Study Bot has two visual modes. The shell covers Home, Plan, Study, Cards, Guides, Chat, Progress, Settings and the sign-in pages. It follows Google Material 3 the way Google's own web apps use it: cool white surfaces, pale blue-grey tonal containers, one blue for actions, pill-shaped buttons, 16px cards, and a navigation rail with pill indicators. The aim is the category standard done carefully, so the shell never competes with what it shows, which is mostly exam countdowns and the things the student still gets wrong. + +A study session or a flashcard review is the second mode. It takes the whole screen, the rail and app bar slide away, and the screen follows the grammar of a Duolingo lesson: one question at a time, a thick progress bar, answer cards with a 2px border and a 4px bottom lip that presses down, and a feedback bar that slides up after each answer. The colours switch to a separate lesson palette drawn from Google's product blue, green and red. The type changes too. Google Sans Flex has a roundness axis (ROND), and the session scope turns it from 0 to 100 while the weight steps up. This document calls that the roundness dial. It is the one moment of motion the system builds around. + +Both modes come in a light and a dark theme that follow the system setting, with a manual switch in the top bar, Settings and the More sheet. The old dark slate dashboard of stat tiles and the later chalkboard theme are retired and are not references. There are no mascots, confetti, cartoon badges, emoji, or game currency like hearts and gems. XP and streaks exist, but they sit in one line of small text. + +Motion is short and only reports state. State layers, colour changes and presses take 150ms, progress and sheets 250ms, the feedback sheet and the returning shell 350ms, and the roundness dial 600ms. State changes use the M3 standard curve, entrances the emphasized curve, and exits the emphasized accelerate curve. Under `prefers-reduced-motion` every animation and transition drops to 0.01ms and view transitions to zero, and the type is simply rounded on arrival. + +In development, `/design` renders every token, component and lesson primitive in both themes, with contrast measured live. It returns 404 in production. + +What holds across both modes: + +- Depth comes from tonal surfaces and hairlines. Shadows appear only on things that float. +- Each group of actions has at most one filled button. +- Type comes from a fixed M3 scale in Google Sans Flex. Nothing is fluid. +- Lesson controls feel physical: 2px borders, a 4px lip, a 2px press. +- A state is never shown by colour alone. There is always a word, a number or an icon. +- All motion stops under reduced motion. + +## Colors + +The shell uses Material 3 colour roles at Google's web baseline values, and sessions add their own palette of Google product colours. + +Every colour is a custom property in `src/app/globals.css`, with light values on `:root` and dark values on `.dark` (next-themes sets the class). Components reach them through semantic Tailwind classes such as `bg-surface-container` and `text-on-surface-variant`, so a component never needs a `dark:` override. In the frontmatter, keys ending in `-dark` are the `.dark` values. The shadcn names map onto the roles: background is surface, card is surface container lowest, popover is surface container low (high in dark), muted is surface container, accent is surface container high, border is outline variant, input is outline, and ring is primary. + +### Primary + +- Primary blue, `primary` (#0b57d0, #a8c7fa in dark): filled buttons, text and outlined button labels, links, the selected tab indicator, the focus ring, the text caret and the first chart series. +- Primary container, `primary-container` (#d3e3fd, #0842a0 in dark): the featured countdown card for the nearest exam, info alerts, and the Start session button in the rail and on phones. + +### Secondary + +- Secondary container, `secondary-container` (#c2e7ff, #004a77 in dark): the active navigation indicator, tonal buttons, the selected segment in segmented buttons, text selection, and the track of the linear progress indicator. + +### Tertiary + +- Success green, `tertiary` (#146c2e, #6dd58c in dark): success and high mastery. Its container (#c4eed0, #0f5223 in dark) backs success badges and success alerts. + +### Neutral + +- Surface (#f8fafd, #131314 in dark): the page, the top app bar and the rail. It is also the browser theme colour. +- Surface container lowest (#ffffff, #0e0e0e in dark): cards and the sign-in card. +- Surface container (#f0f4f9, #1e1f20 in dark): the bottom navigation bar, default alerts, the sign-in page behind its card, and neutral feedback in sessions. +- Surface container high (#e9eef6, #282a2c in dark): dialogs, hover accents and the student's chat bubbles. +- Surface container highest (#dde3ea, #333537 in dark): the mastery bar track and the off state of switches. +- On surface (#1f1f1f, #e3e3e3 in dark) for primary text, and on surface variant (#444746, #c4c7c5 in dark) for secondary text, icons and inactive navigation. +- Outline (#747775, #8e918f in dark): text field borders and outlined buttons. Outline variant (#c4c7c5, #444746 in dark): card hairlines, dividers and the scrollbar thumb. +- Inverse surface (#303030, #e3e3e3 in dark) for tooltips and snackbars, with inverse primary for snackbar actions. +- Scrim, black at 32% behind dialogs and sheets. + +### Status + +- Error red, `error` (#b3261e, #f2b8b5 in dark), and its container (#f9dedc, #8c1d18 in dark): destructive buttons, invalid fields and failure alerts. +- Warning amber, `warning` (#995c00, #fdd663 in dark), and its container (#feefc3, #5a4300 in dark): missed sessions, due states, low mastery and the "1 missed" chip. + +### Charts + +Five series roles: blue, green, amber, red and purple (`chart-1` to `chart-5`), with lighter steps in dark. + +### Lesson palette + +Inside a session the surface is plain white (#ffffff, #131314 in dark), and controls take the `lesson-*` tokens. + +- Neutral options: white fill, #dadce0 border and lip, #f8f9fa on hover, with #3c4043 for neutral button labels and #5f6368 for muted text such as the question counter. +- Selected: #e8f0fe fill, #1a73e8 border, #185abc lip and #174ea6 text. +- Primary lesson button (#1a73e8, #1967d2 on hover, #185abc lip): Start session, Resume session, and Continue after neutral feedback. +- Check green (#188038, #137333 on hover, #0d652d lip): the Check button and Continue after a correct answer. A correct answer card and the correct feedback sheet use #e6f4ea with #137333 text. +- Wrong red (#c5221f, #b31412 on hover, #a50e0e lip): Continue after a wrong answer. A wrong card and the wrong feedback sheet use #fce8e6 with #a50e0e text. +- Disabled: #e8eaed with #80868b text. +- Progress: a #e8eaed track and a #1e8e3e fill. + +Hover fills step away from the label colour. They get darker under white labels in light and lighter under dark labels in dark, so contrast goes up on hover. Sessions use blue, green and red; the warning amber stays in the shell. + +### Named rules + +**The lesson scope rule.** `lesson-*` tokens appear only inside `.lesson`, which wraps the `/s/[sessionId]` layout and the flashcard review layout. Menus, dialogs and toasts that open during a session portal out to `` and keep the shell colours. + +**The words first rule.** Colour never carries a state alone. Badges print their word, mastery bars print the percentage, and answer cards add a check or a cross. In forced colours mode, selected and current states switch to a Highlight border or fill so they stay visible. + +## Typography + +Google Sans Flex sets everything. It loads as a variable font from `@fontsource-variable/google-sans-flex` with the ROND axis file and falls back to Google Sans, then the system UI stack. Google Sans Code sets inline code and preformatted text. The key hint chips stay in Google Sans Flex at 11px. The heading font token points at the same family, so headings differ only by size and weight. One family reads like a Google product in the shell and turns softer and friendlier in sessions, without a second typeface. + +Sizes come from fifteen `type-*` utilities that copy the M3 type scale in fixed rem. There is no fluid type. A few headings step up one size at 600px instead; the lesson question goes from headline-s to headline-m. Body text defaults to body-m. Times, counts and scores use tabular figures. + +### Hierarchy + +| Role | Size / line height | Weight | Tracking | Used for | +| --- | --- | --- | --- | --- | +| display-l | 57 / 64px | 400 | -0.25px | The break timer in sessions | +| display-m | 45 / 52px | 400 | 0 | Days left on a countdown card | +| display-s | 36 / 44px | 400 | 0 | The sign-in card title on wide windows | +| headline-l | 32 / 40px | 400 | 0 | The end screen heading from 600px, status words in countdown cards | +| headline-m | 28 / 36px | 400 | 0 | The lesson question from 600px (700 in sessions), session screen headings | +| headline-s | 24 / 32px | 400 | 0 | View headlines, dialog titles, the feedback sheet title, the lesson question on phones | +| title-l | 22 / 28px | 400 | 0 | The top app bar title, sheet titles, settings sections | +| title-m | 16 / 24px | 500 | 0.15px | Section titles and card titles | +| title-s | 14 / 20px | 500 | 0.1px | Small titles, alert titles, tabs | +| body-l | 16 / 24px | 400 | 0.5px | Reading text, explanations, page header descriptions | +| body-m | 14 / 20px | 400 | 0.25px | Default UI text | +| body-s | 12 / 16px | 400 | 0.4px | Helper text, captions, tooltips | +| label-l | 14 / 20px | 500 | 0.1px | Buttons and field labels | +| label-m | 12 / 16px | 500 | 0.5px | Navigation labels, badges | +| label-s | 11 / 16px | 500 | 0.5px | Citation pills, heatmap and agenda labels; key hints use the same size | + +Running text sits at body-l with a measure of 65 to 75 characters (`max-w-prose`). + +### The roundness dial + +The shell sets `font-variation-settings: "ROND" 0` on `html`, with weights 400 and 500. The `.lesson` scope sets ROND 100 and a base weight of 500. Questions, headings, lesson buttons and confidence chips are 700, and answer text is 500. On entry the change animates through `@starting-style`: 600ms on `cubic-bezier(0.4, 0, 0.2, 1)` after a 120ms delay, so the first frame paints square and the turn is visible. While the session's loading skeleton is on screen the dial waits at 0, which means the student sees the real question's glyphs round. Moving between session screens afterwards keeps it at 100. Portaled menus, tooltips, dialogs and toasts get ROND 100 through a rule on `body:has(.lesson)`. + +### Named rules + +**The scale rule.** Use the `type-*` utilities for text size, never Tailwind's `text-*` sizes. The `text-*` sizes share a prefix with the `text-*` colour classes, and `cn()` can drop one of the two when both appear on an element. The `type-*` utilities don't collide. + +## Layout + +The shell follows M3 window size classes, set as the Tailwind breakpoints in place of Tailwind's defaults: compact under 600px, medium from 600px (`sm`), expanded from 840px (`md`), large from 1200px (`lg`) and extra large from 1600px (`xl`). + +Under 600px a fixed bottom navigation bar, 80px tall, holds Home, Plan, Study and Cards. More opens a bottom sheet with Guides, Chat, Progress, Settings and the theme switch. From 600px a fixed navigation rail, 80px wide, holds the app mark, the Start session button when a session is due today, the seven destinations, and Settings at the bottom. A fixed top app bar, 64px tall, carries the page title as the page's only h1, the theme toggle and the account menu. Its title lines up with the content column. + +Content sits in `PageContainer`. Gutters are 16px, 24px from 600px and 32px from 840px. Sections sit 24px apart, and the page ends with 40px of space. There are three widths: narrow (48rem) for forms, chat and guides, default (72rem), and wide (80rem) for the plan grid. All three start at the same left edge, where the wide column starts, and only the right edge moves, so shared controls like the course switcher stay in place between destinations. + +Spacing runs on Tailwind's 4px step. Inside a section, items usually sit 12px apart, and cards pad 24px (16px in the small size). On phones the exam countdown cards scroll sideways with snap points, 12px apart. From 600px they form a grid of two columns with 16px gaps, and four columns from 1200px. + +Short windows (at most 32rem tall, which covers a phone in landscape and a laptop at 200 to 400% zoom) are their own variant, `short:`. Sticky and fixed bars go static there so they never cover the focused control, the floating Start session button hides, and the shell metrics that clear the bottom bar drop to zero. Everywhere else, focused elements scroll clear of the bars through scroll margins built from `--app-bar-height` and `--bottom-bar-height`. On phones the floating Start session button sits 16px above the bottom bar and the page leaves room for it. In grids, a child that holds truncating text or a scroller gets `min-w-0`, or it overflows at 390px. + +Entering a session or a card review, the shell recedes through React view transitions. The rail slides out to the left, the app bar up and the bottom bar down, over 250ms on the emphasized accelerate curve. Coming back, they slide in over 350ms on the emphasized curve. + +A session has no rail or app bar. `LessonFrame` puts a sticky top bar (close button, progress bar, question counter and phase) in a 56rem column, the question and answer area in a 42rem column with 16px gutters (32px from 600px), and a sticky footer for the actions, which the feedback sheet replaces after an answer. The frame publishes the footer's height as `--lesson-footer-h`, so a field scrolled into view stops above it. On phones the footer stacks Skip above Check, which puts the main action nearest the thumb; from 600px they sit side by side. + +The sign-in and account pages show one card on a surface container page, up to 30rem wide from 600px and 65rem with two columns from 840px. Under 600px the page itself is the card. + +## Elevation & Depth + +Depth is tonal first. Surfaces separate by stepping through the surface container ramp, and a resting card gets a 1px outline variant ring instead of a shadow. A shadow means something is hovered, open or floating. The shadows are the M3 elevation levels, each a tight key shadow plus a softer ambient one. + +### Shadow vocabulary + +- Flat, `shadow-xs` (`0 0 #0000`): inputs and resting cards. +- Level 1, `shadow-sm` (`0 1px 2px 0 rgb(0 0 0 / 0.3), 0 1px 3px 1px rgb(0 0 0 / 0.15)`): a hovered countdown card, hovered filled and tonal buttons, and the rail's Start session button on hover. +- Level 2, `shadow-md` (`0 1px 2px 0 rgb(0 0 0 / 0.3), 0 2px 6px 2px rgb(0 0 0 / 0.15)`): menus, popovers, select lists and the floating Start session button on phones. +- Level 3, `shadow-lg` (`0 1px 3px 0 rgb(0 0 0 / 0.3), 0 4px 8px 3px rgb(0 0 0 / 0.15)`): dialogs, sheets, the snackbar, and the floating button on hover. +- `shadow-xl` and `shadow-2xl` are defined at levels 4 and 5. Only the chart tooltip uses `shadow-xl`. + +Dialogs and sheets also sit over the scrim at 32%. + +Sessions add one depth device of their own, the lip. Every answer card, confidence chip and lesson button carries a solid `box-shadow: 0 4px 0` in a darker shade of its own colour, set through `--lip`. Pressing moves the control down 2px and shrinks the lip to 2px, like a key going down, over 150ms. Disabled and busy controls don't press. + +### Named rules + +**The tonal first rule.** Nothing at rest has a shadow. A shadow appears only when something is hovered, open or floating, and the lesson lip is the one exception because it is the press affordance. + +## Shapes + +Corners follow the M3 shape scale, pinned to the Tailwind radius steps the components use. + +- Pills (`rounded-full`): every shell button, badges, chips, navigation indicators, switches, progress bars and the scrollbar thumb. +- 4px (`rounded-sm`): tooltips, the snackbar, key hints and inline code. +- 8px (`rounded-md`): text fields, textareas, select triggers and menus. +- 12px (`rounded-lg`): alerts, list rows, and the key hint marker inside an answer card. +- 16px (`rounded-2xl`): cards, countdown cards, the focus shape of navigation destinations, and every lesson control (buttons, answer cards, confidence chips, the recall box). The Start session button is a 56px square at 16px, the M3 FAB shape. +- 24px (`rounded-3xl`): chat bubbles, with the corner on the student's side cut to 8px. +- 28px (`rounded-4xl`): dialogs, the top corners of bottom sheets, and the sign-in card. Side sheets round only their inner corners, at 16px. + +The shell draws edges with 1px lines: an outline variant ring around cards and dividers, and an outline border on text fields and outlined buttons. Lesson controls use 2px borders, and the session footer has a 2px top border. + +Focus is a 2px solid outline in the ring colour at a 2px offset on every button, link, tab and other action. Inside a clipping container a component sets `--focus-ring-offset: -2px` to draw it inside. Answer cards, confidence chips and lesson buttons draw it 6px outside the control, around the lip. Text fields don't take the outline; their border turns primary and thickens to 2px instead. + +## Components + +Components live in `src/components/ui` (shadcn/ui on Radix, restyled to M3), `src/components/app` (app-level pieces), `src/components/shell` (the frame) and `src/components/lesson` (session primitives). + +### Buttons + +Shell buttons are M3 pills with label-l text. The default is 40px tall with a 48px touch target drawn by an invisible `::after`; there are 28, 32 and 48px sizes, and icon buttons at the same sizes. Filled (primary) is the one main action in a group. Tonal (secondary container) is the softer alternative, outlined (a 1px outline border with primary text) sits beside a filled button, text (primary text) is for dialog actions and links like "All sessions", ghost is neutral for icon buttons and toolbars, and destructive is filled error for confirming a delete. + +Hover, focus and press come from the state layer, an overlay in the content colour at 8% on hover and 10% on focus and press, fading over 150ms on the standard curve. Filled, tonal and destructive buttons also take `shadow-sm` on hover. Disabled buttons drop to 38% text on a 12% fill. A disabled button that holds a spinner is busy, so it keeps its colours and shows an in-progress label that reuses the verb, such as "Saving…". + +### Chips and badges + +Badges are 24px pills with label-m text in one tonal container per meaning: default (primary), secondary, success, warning, destructive (error container), outline and ghost. The text carries the meaning. The "AI-written" tag that sits beside every block of AI-written text is an outline badge with a sparkle icon; inside a session it takes the colour of the text around it. + +Segmented choices, such as the theme switch in Settings, use the toggle group in its outline variant with no spacing. The selected segment fills with secondary container and shows a check. + +### Cards and containers + +Cards are surface container lowest with a 1px outline variant ring, 16px corners, 24px padding (16px in the small size) and title-m titles. An image at the top or bottom takes the card's corners. + +The countdown card is one exam: the days left in display-m, the date, plan progress on a linear indicator, and a "1 missed" warning badge with Reschedule. The nearest exam is the featured variant, in primary container with no ring and 20px padding. The whole card is the link to its plan, so the card takes `shadow-sm` on hover and draws the focus ring itself. + +Alerts are 12px containers with 12px by 16px padding in five tones: default (surface container), info, success, warning and destructive. Only destructive announces itself as an alert by default. + +### Inputs and fields + +Text fields are outlined: 48px tall, 8px corners, a 1px outline border, a transparent fill, and 16px text with 16px side padding. Hover darkens the border to on surface. Focus turns it primary and 2px wide. An invalid field turns the border error and shows its message beside the field. Disabled fields drop to 38% opacity. Textareas grow with their content from 96px. Labels always sit above the field, and placeholders are realistic examples or nothing. + +Switches are the M3 52 by 32px switch. The thumb grows from 16px to 24px when it turns on, and the track fills with primary. + +### Navigation + +Each destination is a 24px icon in a 56 by 32px pill indicator, with a label-m label under it. The current destination fills its indicator with secondary container and draws its icon with a heavier stroke (2.25 against 1.75). Hover and focus lay the state layer on the indicator. The rail is surface, the bottom bar is surface container, and the More sheet opens from the bottom bar with the remaining destinations in a grid of four. + +Tabs are M3 primary tabs: title-s labels, 48px tall, inactive labels in on surface variant, and a 3px primary indicator with rounded top corners under the active one. The `line` variant is the M3 secondary tab with a 2px square indicator. + +### Dialogs, sheets, tooltips and toasts + +Dialogs are surface container high with 28px corners, 24px padding, headline-s titles and `shadow-lg`. They fade and zoom in from 95% over 200ms on the emphasized curve. The cancel action is a text button, and the confirming action is filled, or destructive for a delete. Bottom sheets are surface container low with 28px top corners and scroll inside a cap of 85% of the viewport height. + +Tooltips are the M3 plain tooltip: inverse surface, 4px corners and body-s text, after a 300ms delay. Toasts are M3 snackbars at the bottom centre, above the bottom bar: inverse surface, 4px corners, `shadow-lg`, actions in inverse primary, and a 32px close button inside the trailing edge. + +### Progress and stats + +The M3 linear indicator (`ProgressLinear`) is 4px tall: an active bar, a 4px gap, the rest of the track in secondary container, and a stop dot at the end. Without a value it sweeps as an indeterminate bar, which stops under reduced motion. `MasteryBar` is an 8px meter on surface container highest with its percentage always printed and its fill in warning, primary or success by level. `StatLine` is the stats row on Home: one line of body-m text in on surface variant, with values in on surface and decorative dot separators. + +### Icons + +Icons come from lucide-react only, usually at 16, 20 or 24px. Most keep lucide's default 2px stroke. Navigation icons use 1.75 (2.25 for the current destination), and the check and cross marks in sessions use 3. Icons are `aria-hidden` and sit beside a text label, and icon-only buttons are named for their action. + +### Lesson primitives + +These are the signature components, in `src/components/lesson`. The screen handles the keyboard (1 to 4 for options, Q, W and E for confidence, Enter to check and continue); the primitives only draw the key hints, and only on fine pointers. + +`LessonFrame` is the full-screen frame described under Layout. Its close button is a 44px circle with an X, and the counter beside the progress bar reads "Question 3 of 12" in label-l at 700, followed by the phase in exam simulation. The question is the page's h1, the largest thing on screen. The frame also holds the polite live region that announces each result. + +`LessonProgress` is the thick bar: 16px tall and fully rounded, with a grey track, a green fill that eases its width over 350ms on the emphasized curve, and a 5px white highlight at 30% along the top of the fill. + +`LessonButton` is at least 48px tall and 128px wide, with 16px corners, a 2px border and the lip, and 16px text at 700 with 0.2px tracking. Its variants are check (green, submits an answer), correct (green, continues), wrong (red, continues), primary (blue, starts or resumes a session) and neutral (white with a grey border, for Skip and secondary actions). Disabled is flat grey. Loading keeps the colours and shows a spinner beside its loading label. An Enter key hint sits inside on fine pointers. + +`AnswerOption` is a real radio input inside a card at least 64px tall, with 16px corners, a 2px border, the lip, and 18/28px text at 500. A 32px marker at the start shows the key hint on fine pointers and a radio dot on touch screens. Selecting a card turns it blue and fills the marker. After checking, the right answer turns green with a check and a wrong pick turns red with a cross, and the other cards dim to 60%. + +`ConfidencePicker` is three equal chips, Guessing, Unsure and Sure, built like answer options at 48px tall with a check on the chosen one. + +`FreeRecallInput` is the answer box: a 2px border, 16px corners and 18/28px text at 500. It grows from 112px (128px from 840px), and focus turns its border selected blue. + +`FeedbackSheet` replaces the footer after an answer and slides up from the bottom over 350ms on the emphasized curve. Correct is pale green with a green check badge, wrong is pale red with a red cross badge, and neutral (a pretest, or a model answer to score against) uses the shell's surface container with an info badge. The title is headline-s at 700 with a short note under it. Continue is the one action, in the tone's button colour, and it takes focus so Enter moves on. The sheet caps at 60% of the viewport height (35% from 840px) and scrolls. Longer feedback reads in the page under the answered question, which stays on screen. + +## Do's and Don'ts + +### Do + +- Do use the semantic role classes (`bg-surface-container`, `text-on-surface-variant`, `border-outline-variant`) and let the theme switch them. +- Do keep one filled button per group, and make the others tonal, outlined or text. +- Do set every text size with a `type-*` utility, and use `tabular-nums` for times, counts and scores. +- Do give every pressable lesson control the lip (`lesson-lip` with `--lip` set to a darker shade of its colour). +- Do save shadows for hovered, open and floating things (`shadow-sm`, `shadow-md`, `shadow-lg`). +- Do pair every status colour with a word, a printed number or an icon. +- Do keep the focus ring visible: 2px at a 2px offset, -2px inside clipping containers, 6px around lesson cards. +- Do check text pairs at 4.5:1 and other UI parts at 3:1 in both themes on `/design`. + +### Don't + +- Don't use raw palette classes such as `bg-blue-500`, or `dark:` colour overrides. +- Don't use `lesson-*` tokens outside `.lesson`. +- Don't use Tailwind's `text-*` sizes or `clamp()` for UI text. +- Don't put a shadow on a resting card or an input. +- Don't add mascots, confetti, cartoon badges, emoji, or game currency such as hearts, gems or coins. +- Don't show a running score or the navigation during a session. The close button is the only way out. +- Don't type check marks, crosses or arrows as text icons. Use a lucide icon with `aria-hidden` beside a text label. +- Don't bring back the dark slate dashboard of stat tiles or the chalkboard theme. +- Don't ship motion that keeps running under `prefers-reduced-motion`. diff --git a/Dockerfile b/Dockerfile deleted file mode 100644 index 04fe90fa..00000000 --- a/Dockerfile +++ /dev/null @@ -1,38 +0,0 @@ -# ── Stage 1: Install dependencies ───────────────────────────────── -FROM node:20-alpine AS deps -WORKDIR /app -COPY package.json package-lock.json ./ -RUN npm ci --omit=dev - -# ── Stage 2: Build the application ─────────────────────────────── -FROM node:20-alpine AS builder -WORKDIR /app -COPY --from=deps /app/node_modules ./node_modules -COPY . . -RUN npx prisma generate -RUN npm run build - -# ── Stage 3: Production runner ─────────────────────────────────── -FROM node:20-alpine AS runner -WORKDIR /app - -ENV NODE_ENV=production -ENV NEXT_TELEMETRY_DISABLED=1 - -RUN addgroup --system --gid 1001 nodejs && \ - adduser --system --uid 1001 nextjs - -COPY --from=builder /app/public ./public -COPY --from=builder /app/prisma ./prisma -COPY --from=builder /app/generated ./generated - -# Standalone output includes server.js and required node_modules -COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./ -COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static - -USER nextjs -EXPOSE 3000 -ENV PORT=3000 -ENV HOSTNAME="0.0.0.0" - -CMD ["node", "server.js"] diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..03963b5e --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Ben Jordan + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index 7598fd8a..9c81fd16 100644 --- a/README.md +++ b/README.md @@ -1,194 +1,263 @@ # Study Bot -A studying platform built on the cognitive science of learning. Upload your course materials, and it turns them into retrieval practice with instant graded feedback, spaced review scheduled around your exam date, and error repair that follows you until a mistake is genuinely fixed. +Study Bot plans studying around real exam dates and turns your own lecture files into practice. A session asks one question at a time, gives feedback as soon as you answer, and logs every miss so it keeps coming back until you get it right on two different days. I built it for my own prelims and finals, so the defaults fit one student with several courses and dated exams.

- Answering a multiple choice question and receiving instant graded feedback + + + Home: countdown cards for four exams, unresolved errors and low-mastery topics with Repair and Practice buttons, and today's Retrieval session with a Resume session button +

-

The core loop: rate your confidence, answer, and get graded feedback with the reasoning behind the trap you picked. All in seconds.

+## What it does -## Why it works +- Plans a week of sessions for a course and exam inside your study hours, exports the plan as .ics or publishes it to Google Calendar, and previews new times before it moves a missed session. +- Runs sessions like short lessons: a start screen, one question per screen, then an end screen with accuracy, confidence results and follow-up dates. The modes are Retrieval, Interleaved practice, Exam simulation, Error repair and Worked examples. +- Gives feedback right after each answer. Multiple choice is checked against the answer key; you score free recall against a model answer. Feedback cites numbered passages from your uploaded files when the search finds one, and says so when it doesn't. +- Logs each miss with a correction rule in your words and brings it back as a repair question, later in the session and in later ones, until you answer it correctly on two different days. +- Reviews topics and flashcards on an SM-2 schedule that tightens as the exam gets closer. +- Includes flashcards (with a deck built from your errors), study guides, chat over your files with cited sources, and a Progress page with mastery by topic, streaks, XP and achievements. +- Works from the keyboard: 1 to 4 pick, Q, W and E rate how sure you are, Enter submits and moves on, ? lists the rest. Answers save as you go, so a refresh mid-session loses nothing. -Every mechanic traces to a specific finding in the learning science literature, including the boundary conditions where a technique is deliberately not applied. The five minute version: +## Why it works -* **Testing beats rereading.** Practice testing outperforms restudying by about half again at a week of delay, so every session is a question deck, never a page of notes. Roediger and Karpicke (2006); meta analysis by Adesope and colleagues (2017); rated a top technique by Dunlosky and colleagues (2013). -* **Feedback speed and quality are the engine.** The active ingredient of deliberate practice is a tight loop: attempt, immediate informative feedback, corrected attempt. Ericsson and colleagues (1993). Immediate feedback is the right default in applied settings per Kulik and Kulik (1988), and elaborated explanation produces roughly ten times the effect of a bare right or wrong mark per Van der Kleij and colleagues (2015). -* **Your most fixable errors are the confident ones.** Errors made with high confidence, once corrected emphatically, are remembered best. Butterfield and Metcalfe (2001). They also resurface after a delay, so they get their own intensified review schedule. Butler, Fazio, and Marsh (2011). -* **One correct answer is not mastery.** Durable learning requires successive relearning: correct retrievals spaced across separate days. Rawson and Dunlosky (2011). -* **Mixed practice feels worse and works better.** Interleaving related topics roughly doubled delayed test scores versus blocked practice in mathematics. It feels harder, and that difficulty is the mechanism. Rohrer and Taylor (2007); classroom trial by Rohrer and colleagues (2020). -* **Struggling before studying helps.** Attempting questions on material you have not studied yet primes later encoding, even when you answer wrong. Richland, Kornell, and Kao (2009). -* **Spacing is scheduled for you.** An SM2 scheduler spaces each objective and compresses intervals as the exam approaches, following the optimal retention ridgeline of Cepeda and colleagues (2008). +Each mechanic comes from a result in the learning research. [docs/LEARNING_SCIENCE.md](docs/LEARNING_SCIENCE.md) has the effect sizes, full references, and the cases where the app deliberately skips a technique. -The full treatment, with effect sizes, primary citations, and the failure modes each feature is designed around, lives in [docs/LEARNING_SCIENCE.md](docs/LEARNING_SCIENCE.md). +- Practice testing beats rereading on delayed tests (Roediger & Karpicke 2006; Adesope, Trevisan & Sundararajan 2017). Sessions are questions, and the server holds back the answer key, model answer and sources until you commit to an answer. +- Immediate feedback that explains the error helps more than a bare right or wrong (Kulik & Kulik 1988; Van der Kleij, Feskens & Eggen 2015), and feedback aimed at the person can backfire (Kluger & DeNisi 1996). The feedback prompts stick to what was wrong and why. +- Confident errors get corrected well right after feedback (Butterfield & Metcalfe 2001) and then tend to return (Butler, Fazio & Marsh 2011). The app asks how sure you are before it reveals anything, flags a wrong answer marked Sure, and puts those first in Error repair. +- The best gap between reviews depends on how far off the test is (Cepeda et al. 2006, 2008). Intervals are capped by the days left, with daily review in the last three days. +- Durable learning takes correct answers spread over several sessions (Rawson & Dunlosky 2011), hence the two-different-days rule. +- Mixing related topics works better than practicing them in blocks when they are easy to confuse (Rohrer & Taylor 2007; Brunmair & Richter 2019), so Interleaved practice deals questions round-robin across one course's topics. +- A failed attempt before studying still helps later learning (Richland, Kornell & Kao 2009). In Retrieval and Interleaved practice, a topic you haven't studied yet opens with a pretest question that doesn't count toward accuracy. +- Students tend to be overconfident (Dunlosky & Rawson 2012). The end screen and Progress show how often you were right at each confidence level. ## Quick start -Prerequisites: Node 20.19 or newer, plus Docker Desktop (or your own PostgreSQL server). +You need Node 20.19 or newer (`.nvmrc` says 22) and Docker, or your own PostgreSQL 16. -``` -git clone && cd Study-Bot +```sh +git clone https://github.com/Ben-K-Jordan/Study-Bot.git +cd Study-Bot npm install npm run setup npm run dev ``` -Then open http://localhost:3000. The defaults need no API keys or external accounts: the AI provider is a deterministic mock, email logs to the console, and calendar sync uses a local fake. Signing up logs you straight in and drops you on the dashboard with a two step welcome. - -To be blunt about the default: mock mode exists for tests. With `AI_PROVIDER` set to `mock`, sessions get canned questions and canned feedback, which exercises the machinery but teaches you nothing. To actually study, set `AI_PROVIDER` to `openai` and add an `OPENAI_API_KEY` in `.env`. The settings page tells you which provider is active. - -What `npm run setup` does: copies `.env.example` to `.env`, generates `NEXTAUTH_SECRET` and `TOKEN_ENC_KEY`, starts PostgreSQL through Docker, and applies all migrations. It is idempotent and never overwrites a value you set yourself. - -Notes: - -* No Docker? Setup says so and keeps going. Point `DATABASE_URL` in `.env` at your own PostgreSQL and run `npx prisma migrate deploy`. -* The Docker database listens on host port 5433 to avoid clashing with a local PostgreSQL on 5432. Start it with `npm run db:up`, watch it with `npm run db:logs`, and stop the compose stack with `npm run db:down`. -* Optional: `npm run worker` starts the background job worker for document embedding. -* Full stack alternative: `docker compose up` builds and runs the app and database together. It reads `NEXTAUTH_SECRET` from `.env`, so run `npm run setup` first. - -## What it looks like - -Every session opens with a preflight card stating the contract: mode, scope, prompt count, deck composition, and break protocol. One button starts it. - -

- Session preflight screen with mode, scope, deck composition, and break protocol -

- -During a session the interface recedes: the navigation collapses to a single quiet exit link, the question is the largest thing on screen, and there is no running score to watch. Multiple choice is graded by the server, and the answer key never reaches your browser before you commit. Rate your confidence first with one tap or one key. - -

- A multiple choice question with a confidence selector and keyboard hints -

+`npm run setup` copies `.env.example` to `.env`, generates `NEXTAUTH_SECRET` and `TOKEN_ENC_KEY`, starts PostgreSQL in Docker on port 5433, and applies the migrations and `prisma/manual-scripts/001_pgvector.sql`. It is safe to rerun and never overwrites a value you set. Without Docker, point `DATABASE_URL` at your own database and run `npx prisma migrate deploy`. -Miss a question you were sure about, and the app names the moment. That is the hypercorrection effect, and the review that follows is engineered around it: the question you just answered stays on screen with its feedback, the correction is the only highlighted element, and feedback generation starts the instant your answer lands so the explanation is usually waiting before you finish reading the verdict. +Open http://localhost:3000 and create an account. The defaults need no keys: a mock AI provider, email printed to the server log, and a fake Google Calendar. The mock provider is for development and tests, so sessions use built-in question templates and AI-written text is placeholder. -

- Review panel flagging a high confidence miss with the correct answer and the reasoning behind the trap -

+### Demo data -Free recall questions make you answer from memory before anything is revealed, with confidence collected while you still cannot see the answer. +The seed only touches a database whose name contains `demo`, and it doesn't read `.env`: -

- A free recall question with a typed answer and a confidence rating -

- -Then you score yourself against an explicit model answer and key points, not a feeling. Accurate self assessment requires a reference standard, and the model answer stays visible, dimmed, while you write the correction rule for an error log. +```sh +docker compose exec db psql -U postgres -c "CREATE DATABASE studybot_demo" +export DATABASE_URL=postgresql://postgres:postgres@localhost:5433/studybot_demo +npx prisma migrate deploy +npm run db:seed-demo +npm run dev +``` -

- Model answer with key points shown before self scoring -

+Sign in as `demo@studybot.local` with `study-bot-demo`. You get four courses with exams 7 to 60 days out, plans, three weeks of finished sessions, flashcards, guides and a chat, dated relative to the day you seed. Rerunning the seed resets only that account. -The end screen shows accuracy, time, and a calibration chart of your confidence against your outcomes, then recommends spaced follow up dates computed from how you actually did. One tap schedules them into your plan. +### Real AI and Google Calendar -

- End screen with stats, confidence calibration, and recommended follow up sessions with a schedule button -

+For real questions and feedback, set `AI_PROVIDER="openai"` and `OPENAI_API_KEY` in `.env` and restart. The model is `AI_MODEL_ANSWER` (`gpt-4o-mini` by default), and each account is capped at $1 a day and $10 a month unless you change the caps. Settings, under AI features, says which mode the server is in. -Your plan is a fixture, not a popup: it greets you with a countdown to the exam, real dated day groups with a focus line per session, an exam day marker, a reschedule button for missed sessions, and calendar export. Creating a new plan for the same course replaces the old one after a confirmation, so plans never silently stack. +For Google Calendar, enable the Calendar API in Google Cloud, create a Web application OAuth client with the redirect URI `http://localhost:3000/api/integrations/google/callback` (`BASE_URL` plus that path), set `GOOGLE_PROVIDER="real"`, `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET`, and connect from Settings. Tokens are stored encrypted with `TOKEN_ENC_KEY`. -

- Plan page with days until exam, dated sessions, focus lines, and reschedule and calendar export controls -

+## Screenshot tour -The dashboard leads with today: your scheduled sessions and one primary start button. Streak, XP, accuracy, and the activity heatmap are there, but demoted to a quiet strip and the bottom of the page so they never compete with starting the work. +All from the demo account on the mock provider. The mock provider only writes free-recall templates, so the two multiple-choice shots use a known deck written into the run, the same way the e2e suite seeds one.

- Dashboard with today's sessions first, a quiet stats strip, achievements, and activity heatmap + Animation of one repair question: an answer is typed, Unsure is picked, the answer is submitted, the correction rule appears, Correct is chosen, the green feedback sheet slides up, and the next question loads

-## Study modes - -* **Retrieval** is the default: free recall plus multiple choice generated from your materials, scored immediately with elaborated feedback. -* **Interleaved practice** runs the same loop with prompts mixed across objectives, never more than two in a row from one topic. Use it when topics are similar enough to confuse, because telling them apart is the skill. -* **Exam simulation** withholds all feedback until the end, then walks you through review: multiple choice is scored objectively from the answer key, and free recall is scored by you against the model answer. This is the one place delayed feedback is intentional. -* **Error repair** builds a deck from your unresolved mistakes, confident misses first. Each error resolves only after two correct recalls on different days, and decks stay within the course you are studying. -* **Worked examples** teach procedural material by fading: study a fully worked solution with the reasoning behind each step, then solve versions with the final step missing, then the final two, then a full transfer problem. +The answer loop: answer, rate, submit, score yourself against your earlier correction rule, continue. + + + + Start screen of an Interleaved practice session on four INFO 1300 topics: 10 questions (7 new, 1 due for review and 2 repair), 50 minutes planned, 80% target accuracy, and a Start session button + + +Every session opens by saying what it will ask. + + + + A review question about grid template areas with a typed answer and Sure selected under How sure are you, and a Submit answer button + + +One question per screen, rated before anything is revealed. + + + + A multiple-choice repair question about which CSS selector wins, with the first choice selected, Sure picked under How sure are you, and a green Submit answer button + + +Multiple choice works from the keyboard: 1 to 4 picks an answer, Q, W and E set how sure you are, and Enter submits. + + + + After a wrong pick marked Sure: the chosen answer in red, the correct answer in green, a Confident error note, and a red Incorrect sheet showing the correct answer and a Next question button + + +The server checks the pick against the answer key, which never reaches the browser before you commit. + + + + A repair question about class and ID selectors with a wrong typed answer above the student's earlier correction rule, and Correct, Partly correct and Incorrect buttons + + +A repair question is scored against the correction rule you wrote the first time. + + + + Feedback after a wrong answer marked Sure: the answer, the correction rule, a Confident error note, and a red Incorrect sheet with a Next question button + + +A wrong answer marked Sure gets the Confident error note. The numbered sources sit below it. + + + + Session complete screen with 58% accuracy over 12 questions, a Confidence section with a chart of accuracy at Guessing, Unsure and Sure, and a suggested follow-up Retrieval session + + +The end screen compares confidence with results and spaces follow-ups by accuracy. + + + + Plan page for INFO 1300 Prelim 2: a list of plans with days until each exam, progress through the plan, and dated sessions with their mode, topics and status, plus Reschedule sessions and Export calendar buttons + + +A plan lists sessions by day with mode, topics and status. + + + + + + + + + + + + + + + + + + +
+ + + Study page recommending an Error repair session for 9 unresolved errors, with the five modes, a length picker and today's planned session + + Study recommends the next session. + + + + Flashcard review with the answer shown and Again, Hard, Good and Easy buttons with their next intervals + + Flashcard review. +
+ + + Chat answer about srcset and sizes with numbered citations and one source opened to show the quoted passage + + Chat with one source opened. + + + + Progress page with mastery by topic for four courses, weakest first, with a Practice button on each topic + + Progress, weakest topics first. +
+ + + Settings with sections for profile, study preferences, appearance, Google Calendar, AI features, data and account + + Settings. + + + + Sign-in card with email and password fields, Forgot password, Create account and Sign in + + Sign in. +
+ + + Home on a phone with an exam countdown card, today's session and a bottom navigation bar + +
Home on a phone. +
+ + + Feedback on a phone after a wrong answer marked Sure, showing the Confident error note, one numbered source and the student's correction above an Incorrect sheet + +
Feedback on a phone. +
+ +## Tech stack + +- Next.js 16 (App Router), React 19, TypeScript +- Tailwind CSS 4 and shadcn/ui on Radix, restyled to Material 3 colour roles; Google Sans Flex via Fontsource +- PostgreSQL 16 through Prisma 7, with optional pgvector embedding search +- next-auth 4 (email and password), zod on the API routes +- One AI gateway for every model call, with caching, spending caps, timeouts, a circuit breaker and a kill switch; OpenAI in real use, a mock provider offline +- A PostgreSQL job queue for embedding work (`npm run worker`) +- Vitest, Playwright and axe-core + +## Project layout -Every mode shares the same spine: pretest diagnostics for never studied objectives (quarantined from grading), warm ups for objectives due for review, timed work and break cycles, variant questions injected after misses (announced with a quiet note, and the progress bar never moves backward), and full resumability. A refresh or crash loses nothing, including an answer you typed but had not scored yet. - -## The feedback loop - -1. You commit an answer, and optionally a confidence rating, before anything is revealed. No hints, excerpts, or answers leak beforehand; this is enforced server side and covered by an end to end test. Committed retrieval attempts enhance learning even when they fail, per Kornell, Hays, and Bjork (2009). -2. Multiple choice answers are graded server side instantly, including why the distractor you picked was tempting. Free recall answers are scored by you against a revealed model answer with key points. -3. Elaborated feedback cites exact excerpts from your own uploaded materials, and generation starts the moment your attempt lands so the wait is minimal. It persists with the attempt and never regenerates or disappears. When your materials contain nothing relevant, it says so plainly instead of pretending. -4. A miss creates an error log and injects a retry variant later in the same session. The error resolves only after two correct retrievals on different days, and a wrong retry resets the streak. -5. The whole loop runs from the keyboard: number keys answer and score, Enter advances. More feedback cycles per hour is the entire point. - -## Techniques and the research behind them - -Each technique below is implemented in the product. Citations are shortened here; the full bibliography with paper titles and effect sizes is in [docs/LEARNING_SCIENCE.md](docs/LEARNING_SCIENCE.md). +``` +src/app pages and API routes; s/[sessionId] holds the session screens +src/components shell, lesson (session building blocks), ui (shadcn), one folder per screen +src/services plans, session runs, feedback, flashcards, progress +src/lib spacing, mastery and question rules, AI gateway, search, jobs, auth, email +src/__tests__ Vitest tests; integration/ needs PostgreSQL +prisma schema, migrations, manual-scripts/001_pgvector.sql +e2e Playwright specs and helpers +scripts setup, worker, seed scripts, screenshot harness +docs LEARNING_SCIENCE.md and these screenshots +``` -* **Retrieval practice.** All five modes are built on active recall of your materials. Roediger and Karpicke (2006); Adesope and colleagues (2017); Dunlosky and colleagues (2013). -* **Deliberate practice loops.** Immediate informative feedback on every attempt, with difficulty adapting toward a band slightly above your current level. Ericsson and colleagues (1993); Kulik and Kulik (1988); Corbett and Anderson (2001); Bjork and Bjork on desirable difficulties. -* **Elaborated, task focused feedback.** Misses always get the correct answer plus an explanation grounded in your own course materials, never a bare mark, and the framing targets the task rather than the person. Van der Kleij and colleagues (2015); Shute (2008); Kluger and DeNisi (1996). -* **Hypercorrection.** Confidence is captured before the answer is revealed; confident misses get flagged, receive the fullest correction, and jump the queue in error repair decks. Butterfield and Metcalfe (2001); Butler, Fazio, and Marsh (2011); Fazio and Marsh (2009). -* **Spaced repetition with exam awareness.** Objective mastery and flashcards both run on an SM2 scheduler whose intervals compress as the exam approaches, and inside the final days the app deliberately lets you cram. Cepeda and colleagues (2006, 2008). -* **Successive relearning.** Error logs resolve only after two correct retrievals on different calendar days in your timezone, and follow up session dates come from the actual scheduler rather than a fixed table. Rawson and Dunlosky (2011); Rawson, Dunlosky, and Sciartelli (2013). -* **Interleaving.** Mixed practice decks alternate objectives, and AI generated decks are reinterleaved so they never collapse into blocked practice. Rohrer and Taylor (2007); Rohrer and colleagues (2020); Kornell and Bjork (2008); boundary conditions from Brunmair and Richter (2019). -* **Pretesting.** New objectives get a diagnostic question before study. Wrong answers there are expected, framed supportively, and quarantined from your grades and error logs. Richland, Kornell, and Kao (2009); Pan and Sana (2021). -* **Worked examples with backward fading.** Study a stepped solution, then complete progressively less scaffolded problems, because novices learn more from studying solutions than from unassisted problem solving, while experts should skip ahead. Sweller and Cooper (1985); Renkl and colleagues (2002); Kalyuga and colleagues (2003). -* **Multiple choice done safely.** Answer keys are withheld from the client until you answer, correct answer confirmation always closes the loop to prevent lure learning, and distractors are built from documented misconceptions. Roediger and Marsh (2005); Butler and Roediger (2008). -* **Self explanation and generation.** After feedback you can restate the concept in your own words, invent your own example, and answer a Socratic follow up, all saved with the attempt and tucked behind a single quiet link so they never crowd the screen. Chi and colleagues (1989); Bisra and colleagues (2018). -* **Calibration.** Your confidence ratings are charted against your actual outcomes, and only ratings you actually gave are counted. Overconfidence produces underachievement. Dunlosky and Rawson (2012); Nelson and Dunlosky (1991). -* **A cognitive load minimal interface.** One question at a time, the question is the largest thing on screen, navigation recedes to an exit link during sessions, status chrome sits in low contrast, and decoration is omitted. Sweller (1988); Sundararajan and Adesope (2020) on seductive details. +## Testing -## Feature map +- `npm run test:unit`: Vitest, no database. +- `npm run test:integration`: needs a migrated test database in `DATABASE_URL`, set in the shell because Vitest doesn't read `.env`. Without it those files skip. +- `npm run test:e2e`: Playwright starts its own server with the offline providers on `E2E_PORT` (default 3000, so pick another while `npm run dev` runs), against a database whose name contains `e2e`. It runs every spec on desktop Chrome and the `@mobile` ones on a Pixel 7; `@a11y` tests run axe with the WCAG A and AA rules through 2.2. Setup steps are in [e2e/README.md](e2e/README.md). +- `npm run lint` and `npm run typecheck`. -The navigation is four destinations: Dashboard, Learn, Plan, and Settings. Flashcards, study guides, and chat live one tap away inside Learn. +[CI](.github/workflows/ci.yml) runs on pushes and pull requests to `main`: lint, typecheck and build in one job, unit tests in another, then integration tests against a pgvector PostgreSQL service, then the e2e suite split into two shards, each with its own database and production build. -* **Study planner.** Sessions scheduled backwards from your exam date around your availability, with pre exam tapering, a live countdown, Google Calendar sync (including free and busy detection), ICS export, and deterministic rescheduling of missed sessions with a preview before anything moves. -* **Learn.** A recommendation engine that reads your mastery and unresolved errors, tells you which session to run next and why, and starts it in one tap. -* **Content upload and search.** PDFs and notes are chunked and searched with PostgreSQL full text search, and every generated question and piece of feedback cites its exact source chunks. Optional embedding based hybrid search sits behind `HYBRID_SEARCH_ENABLED`. Each document also gets an AI summary. -* **Chat.** Ask questions against your own materials and get answers with citations that quote the exact source passages. -* **Flashcards.** Decks you create, plus cards auto generated from your errors with the correction as the answer, scheduled by the same exam aware SM2. -* **Study guides.** Key concepts, FAQ, and cheat sheet formats generated per course from your materials. -* **Progress.** XP with an adjustable daily goal, streaks with earned freezes, achievements, per objective mastery, and a calibration dashboard. Session XP is awarded only at session boundaries so it never intrudes on the answer loop. -* **Account.** Full data export and account deletion, password reset by email, and a timezone setting with one tap detection so streaks roll over at your actual midnight. +`npm run screenshots -- --base http://localhost:3000 --out ` captures every page of the demo account in both themes at desktop and phone sizes. Options are listed at the top of `scripts/screenshots.ts`. ## Configuration -`npm run setup` produces a working `.env`, and `.env.example` documents every variable inline. The ones that matter most: - -* `DATABASE_URL` is the PostgreSQL connection string. The default targets the Docker database on port 5433. -* `NEXTAUTH_SECRET` signs sessions. Generated by setup. -* `AI_PROVIDER` is `mock` by default (fully offline) or `openai`, which requires `OPENAI_API_KEY`. -* `AI_MODEL_ANSWER` picks the generation model and `AI_MODEL_EMBED` the embedding model. -* `AI_DAILY_COST_CAP_USD` and `AI_MONTHLY_COST_CAP_USD` are hard per user spending caps, and `AI_DISABLED` set to true is the emergency kill switch. -* `TOKEN_ENC_KEY` encrypts stored Google OAuth tokens. Generated by setup and required in production. -* `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET`, and `GOOGLE_PROVIDER` control calendar sync. The default `fake` provider stubs it; use `real` in production. -* `EMAIL_PROVIDER` is `console` by default, or `smtp` with the SMTP variables for real mail. -* `REQUIRE_EMAIL_VERIFICATION` is off by default so you can sign in immediately; turn it on only once real SMTP can deliver the links. -* `LOG_LEVEL` accepts debug, info, warn, or error. - -One warning: `ALLOW_TEST_AUTH` makes the app trust a header as the authenticated identity. It exists only for automated tests and must never be set in production. - -## Deployment and ops notes +`.env.example` documents every variable. The ones that matter most: -* **Auth gates.** `REQUIRE_EMAIL_VERIFICATION` is off by default, so new accounts can sign in immediately; enable it only once real SMTP is configured, because the console email provider prints verification links to server logs only. `ALLOW_TEST_AUTH` must never be set in production. `TOKEN_ENC_KEY` is required in production (setup generates one for local use). -* **One long lived Node process.** The app is not serverless safe. Feedback is generated eagerly when an attempt lands, and the AI rate limiter and circuit breaker hold their state in process, so run it as a single persistent Node server via `npm start` rather than as per request functions. -* **The port 3000 trap.** If something else already holds port 3000, Next silently starts on 3001 while `NEXTAUTH_URL` still points at 3000, and sign in breaks with baffling redirects. Free port 3000, or update `NEXTAUTH_URL` (plus `BASE_URL` and `NEXT_PUBLIC_APP_URL`) to the port actually in use. -* **Admin endpoints.** The admin APIs (job queue, search health, AI usage) are gated by `ADMIN_USER_IDS`, a comma separated list of user UUIDs. Until you set it, nobody is an admin. There is no admin UI. +- `DATABASE_URL`, plus `NEXTAUTH_URL` and `BASE_URL`, which must match the origin you browse to. If port 3000 is taken, Next moves to 3001 and sign-in breaks until they match. +- `AI_PROVIDER`, `OPENAI_API_KEY`, the `AI_*_COST_CAP_USD` caps, and `AI_DISABLED`. +- `GOOGLE_PROVIDER` (`fake` or `real`) with `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET`. +- `EMAIL_PROVIDER` (`console` or `smtp`) with the `SMTP_*` settings. Without SMTP, a production server turns password reset off. Leave `REQUIRE_EMAIL_VERIFICATION` off until mail works. +- `ADMIN_USER_IDS` for the `/api/admin/*` endpoints, and `TRUSTED_PROXY_HOPS` when running behind a proxy. -## Development +`ALLOW_TEST_AUTH` makes the server trust an `X-User-Id` header. It is for the e2e suite only; never set it on a real server. -* `npm run dev`, `npm run build`, and `npm start` cover the dev server and production. -* `npm test` runs everything vitest knows. `npm run test:unit` needs no database. -* `npm run test:integration` needs PostgreSQL reachable through `DATABASE_URL`. -* `npm run test:e2e` runs Playwright: against your dev server locally, or against a production build when `CI` is set. Run `npx playwright install chromium` once first. -* `npm run worker` processes background jobs, `npm run db:migrate` creates new migrations, and `npm run db:seed-research` loads the research evidence base that grounds plan generation. +Rate limits and the AI circuit breaker live in memory, so run the app as one long-lived Node process (`npm run build`, then `npm start`). -Integration and e2e tests read `DATABASE_URL`; point it at a dedicated test database rather than your dev one. +## Design -Layout, briefly: `src/app` holds pages and API routes, `src/services` holds domain logic, `src/lib` holds the science (prompt generation, spacing, mastery) and infrastructure (AI gateway, jobs, search), `src/ui` holds shared components, `prisma` holds schema and migrations, `e2e` holds Playwright specs, `scripts` holds setup and the worker, and `docs` holds the learning science foundation with the source papers in `research-papers/`. +[DESIGN.md](DESIGN.md) covers the colour roles, type scale, shapes, motion and components. The shell (Home, Plan, Study, Cards, Guides, Chat, Progress, Settings) follows Material 3 the way Google's own web apps do: white and pale blue-grey surfaces, one blue for actions, a navigation rail. A session or card review hides the shell and switches to a lesson layout modelled on Duolingo, with one question per screen, a thick progress bar, answer cards that press down, and a feedback sheet that slides up. The type changes too: the session screens turn Google Sans Flex's roundness axis from 0 to 100 and step the weight up, so the same family reads square in the shell and rounder in a session. Both modes have light and dark themes. In development, `/design` renders every token and component. -## Architecture notes +## Security -* Next.js App Router with TypeScript and zod validation at every API boundary. -* PostgreSQL through Prisma. The bundled image ships pgvector, so hybrid search can turn on without repaving the database. -* Background jobs run through a PostgreSQL backed queue with row locking. No Redis or external broker to operate. -* One AI gateway is the choke point for all model calls, with response caching, per user cost caps, request timeouts, a circuit breaker, and an emergency kill switch. Providers are pluggable, and the mock provider keeps the whole app usable offline and in CI. -* Feedback is generated eagerly at submit time, claimed atomically so concurrent requests never double spend, and persisted with the attempt. +See [SECURITY.md](SECURITY.md) for reporting a problem. -## References +## License -The complete bibliography with paper titles, journals, and the mapping from each finding to a feature: [docs/LEARNING_SCIENCE.md](docs/LEARNING_SCIENCE.md). Works cited in this README: Adesope, Trevisan, and Sundararajan (2017); Bisra and colleagues (2018); Bjork and Bjork (1992, 2011); Brunmair and Richter (2019); Butler, Fazio, and Marsh (2011); Butler and Roediger (2008); Butterfield and Metcalfe (2001); Cepeda and colleagues (2006, 2008); Chi and colleagues (1989); Corbett and Anderson (2001); Dunlosky and Rawson (2012); Dunlosky and colleagues (2013); Ericsson and colleagues (1993); Fazio and Marsh (2009); Kalyuga and colleagues (2003); Kluger and DeNisi (1996); Kornell and Bjork (2008); Kornell, Hays, and Bjork (2009); Kulik and Kulik (1988); Nelson and Dunlosky (1991); Pan and Sana (2021); Rawson and Dunlosky (2011); Rawson, Dunlosky, and Sciartelli (2013); Renkl and colleagues (2002); Richland, Kornell, and Kao (2009); Roediger and Karpicke (2006); Roediger and Marsh (2005); Rohrer and Taylor (2007); Rohrer and colleagues (2020); Shute (2008); Sundararajan and Adesope (2020); Sweller (1988); Sweller and Cooper (1985); Van der Kleij and colleagues (2015). +MIT. See [LICENSE](LICENSE). diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 00000000..6e88dda4 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,17 @@ +# Security policy + +## Reporting a vulnerability + +Please report security problems privately, not in a public issue. + +Open a private advisory at +[github.com/Ben-K-Jordan/Study-Bot/security/advisories/new](https://github.com/Ben-K-Jordan/Study-Bot/security/advisories/new) +(Security tab, then "Report a vulnerability"). Include the steps to reproduce +it and what an attacker could do with it. + +Once a fix ships, the advisory is published with credit to you, unless +you'd rather stay anonymous. + +## Supported versions + +Only the latest commit on `main` gets security fixes. diff --git a/components.json b/components.json new file mode 100644 index 00000000..78c192f2 --- /dev/null +++ b/components.json @@ -0,0 +1,25 @@ +{ + "$schema": "https://ui.shadcn.com/schema.json", + "style": "radix-maia", + "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/design/exports-raw/btn-primary.png b/design/exports-raw/btn-primary.png deleted file mode 100644 index 438678e7..00000000 Binary files a/design/exports-raw/btn-primary.png and /dev/null differ diff --git a/design/exports-raw/btn-primary@2x.png b/design/exports-raw/btn-primary@2x.png deleted file mode 100644 index 6011f480..00000000 Binary files a/design/exports-raw/btn-primary@2x.png and /dev/null differ diff --git a/design/exports-raw/icon-check.svg b/design/exports-raw/icon-check.svg deleted file mode 100644 index 83e810ec..00000000 --- a/design/exports-raw/icon-check.svg +++ /dev/null @@ -1,5 +0,0 @@ - - - Created in Photoshop - - diff --git a/design/exports-raw/icon-phone-off.svg b/design/exports-raw/icon-phone-off.svg deleted file mode 100644 index e8c1e439..00000000 --- a/design/exports-raw/icon-phone-off.svg +++ /dev/null @@ -1,7 +0,0 @@ - - - Created in Photoshop - Phone off reminder - - - diff --git a/design/exports-raw/icon-session.png b/design/exports-raw/icon-session.png deleted file mode 100644 index ef0fe3e9..00000000 Binary files a/design/exports-raw/icon-session.png and /dev/null differ diff --git a/docker-compose.yml b/docker-compose.yml index ecf19551..dfe837d0 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,13 +1,16 @@ +# Local PostgreSQL for development. The app itself runs on the host with +# `npm run dev` (or `npm run build && npm start`). services: db: - # pgvector/pgvector is the official postgres image + the pgvector extension - # (a drop-in superset of postgres:16 — needed for the hybrid-search roadmap). + # The official postgres:16 image plus the pgvector extension, which + # prisma/manual-scripts/001_pgvector.sql needs for embedding search. image: pgvector/pgvector:pg16 environment: POSTGRES_USER: ${POSTGRES_USER:-postgres} POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-postgres} POSTGRES_DB: ${POSTGRES_DB:-studybot} ports: + # Host port 5433 avoids clashing with a locally installed Postgres on 5432. - "5433:5432" volumes: - pgdata:/var/lib/postgresql/data @@ -17,23 +20,5 @@ services: timeout: 5s retries: 10 - app: - build: . - ports: - - "3000:3000" - environment: - DATABASE_URL: "postgresql://${POSTGRES_USER:-postgres}:${POSTGRES_PASSWORD:-postgres}@db:5432/${POSTGRES_DB:-studybot}?schema=public" - BASE_URL: ${BASE_URL:-http://localhost:3000} - NEXTAUTH_URL: ${NEXTAUTH_URL:-http://localhost:3000} - NEXTAUTH_SECRET: ${NEXTAUTH_SECRET:?Set NEXTAUTH_SECRET in .env or environment} - ADMIN_USER_IDS: ${ADMIN_USER_IDS:-} - GOOGLE_PROVIDER: ${GOOGLE_PROVIDER:-fake} - AI_PROVIDER: ${AI_PROVIDER:-mock} - EMAIL_PROVIDER: ${EMAIL_PROVIDER:-console} - NODE_ENV: "production" - depends_on: - db: - condition: service_healthy - volumes: pgdata: diff --git a/docs/LEARNING_SCIENCE.md b/docs/LEARNING_SCIENCE.md index 2333a576..685b4eb0 100644 --- a/docs/LEARNING_SCIENCE.md +++ b/docs/LEARNING_SCIENCE.md @@ -1,18 +1,18 @@ -# The Learning Science Behind Study-Bot - -Study-Bot is built on a specific claim: most studying fails not because students -don't work hard, but because the default techniques (rereading, highlighting, -passive review) are among the worst-performing strategies in the experimental -literature, while the best-performing ones (retrieval practice, spacing, -interleaving) feel worse than they work and so are rarely chosen voluntarily. - -This document exists so you don't have to take that claim on faith. Each -section covers one principle: the research (who showed it, when, and how big -the effect is), how Study-Bot implements it at the feature level, and the -boundary conditions — the situations where the principle stops helping and -where the app deliberately does *not* apply it. The boundary conditions are -not fine print; most of these techniques have well-documented failure modes, -and a tool that ignores them implements the citation, not the finding. +# The learning science behind Study Bot + +Study Bot is built on one claim. Students who work hard still fall short when +they use the default techniques (rereading, highlighting, passive review), +which are among the worst-performing strategies in the experimental +literature. The best-performing ones (retrieval practice, spacing, +interleaving) feel less effective than they are, so students rarely choose +them on their own. + +This document lays out the evidence for that claim. Each section covers one +principle: the research (who showed it, when, and how big the effect is), how +Study Bot implements it, and the boundary conditions, meaning the situations +where the principle stops helping and the app deliberately doesn't apply it. +Most of these techniques have documented failure modes, so the boundary +conditions get as much space as the benefits. Contents: @@ -38,71 +38,82 @@ Contents: **The research.** Actively recalling information strengthens memory far more than re-exposure to it. Roediger & Karpicke (2006) showed practice testing beat repeated studying by roughly 50% in relative retention at a one-week -delay — even though the restudy group *predicted* they would do better. +delay, even though the restudy group *predicted* they would do better. Dunlosky, Rawson, Marsh, Nathan & Willingham (2013, *Psychological Science in the Public Interest*) rated practice testing one of only two "high utility" techniques out of ten reviewed. Meta-analytically, Adesope, Trevisan & Sundararajan (2017, *Review of Educational Research*; 272 effects across 188 experiments) found g = 0.61 overall, and +0.51 against restudy specifically. -The benefit is largest on *delayed* tests — which is what an exam is. - -**In Study-Bot.** Retrieval is the default interaction everywhere. Study -sessions are decks of questions, not pages of notes: free-recall prompts and -multiple-choice questions generated from your uploaded course materials (with -misconception-based distractors), or deterministic prompt templates when no -materials are uploaded. The answer is never shown before a committed attempt — -there is no "flip to reveal" without answering first, and the runner's -no-leakage guardrail ensures no excerpts, hints, or citations from your -materials render before you submit (verified by an end-to-end test). Because -MCQ practice without feedback actively teaches the distractors as facts -(Roediger & Marsh 2005; Butler & Roediger 2008, *Memory & Cognition*), every -MCQ item closes with confirmation of the correct answer plus a rationale for -why the chosen distractor is wrong — including in exam simulation, where the -review phase is a forced step, not an optional screen. +The benefit is largest on *delayed* tests, and an exam is a delayed test. + +**In Study Bot.** Retrieval is the default interaction everywhere. A study +session is a set of questions: free recall and multiple choice questions +generated from your uploaded course materials, with distractors built from +common misconceptions and from your own unresolved errors. When your +materials have fewer than two passages on the session's topics, or no AI +provider is set, the session uses deterministic question templates instead. +The answer is never shown before a committed attempt. There is no "flip to +reveal" without answering first, and the server withholds the answer key, the +model answer, and any passages from your materials until you submit. Unit +tests of the reveal gate, an integration test of the attempt response, and an +end-to-end test of what the browser receives before an answer check this +guardrail. Multiple choice practice without feedback teaches the distractors +as facts (Roediger & Marsh 2005; Butler & Roediger 2008, *Memory & +Cognition*), so every multiple choice miss closes with the correct answer. In +the modes that score right away, the feedback also explains why the option +you picked was tempting, when the question carries a note for it. In Exam +simulation, scoring is a required phase: the session doesn't finish until you +have scored every answer, and each multiple choice question shows its correct +answer there. **Boundary conditions.** The testing effect shrinks when retrieval success is -very low — failing constantly with no support is not practice, it's noise. -Study-Bot counteracts this with adaptive difficulty (section 12), warm-up -review of due material at session start, and worked examples (section 9) for -first exposure to procedural topics. Corrective feedback is treated as -non-optional: an unanswered or unconfirmed question never ends an item. +very low, because failing over and over with no support isn't practice. Study +Bot works against this with adaptive difficulty (section 12), review +questions on due topics at the start of Retrieval and Interleaved practice +sessions, and worked examples (section 9) for first exposure to procedural +topics. Corrective feedback is treated as non-optional: there is no Skip, and +a question ends only after you answer it. ## 2. Deliberate practice and the feedback loop **The research.** Ericsson, Krampe & Tesch-Römer (1993, *Psychological Review* -100(3), 363–406) defined deliberate practice as well-defined tasks slightly +100(3), 363-406) defined deliberate practice as well-defined tasks slightly beyond current ability, with informative feedback and opportunities for repetition and error correction. The popularized "10,000 hours" framing drops the load-bearing part: hours only count when structured as feedback-bearing loops. On timing, Kulik & Kulik's (1988, *Review of Educational Research* -58(1), 79–97) meta-analysis of 53 studies found that in applied settings with +58(1), 79-97) meta-analysis of 53 studies found that in applied settings with real materials, *immediate* feedback wins; the oft-cited lab advantage for delayed feedback is largely a methodological artifact of artificial list-learning paradigms. Corbett & Anderson's cognitive-tutor experiments (CHI 2001) showed immediate feedback minimizes time-to-mastery at no cost to -final performance. Shute (2008, *Review of Educational Research* 78, 153–189) +final performance. Shute (2008, *Review of Educational Research* 78, 153-189) adds the moderators: immediate feedback is most valuable for difficult tasks and struggling learners, and feedback should come in small, focused units. -**In Study-Bot.** Every practice item is a closed loop: a committed attempt, a -score, elaborated feedback in the same interaction, and then an active -correction step — a miss requires you to write a correction rule in your own -words, and a variant question testing the same point is injected later into -the same session (capped at four injected variants per session so the deck -stays bounded). Feedback is generated and persisted per attempt, so it -survives page refresh instead of being regenerated or lost. Prompt selection -targets a difficulty band of roughly 70–85% success (section 12), which is -the "slightly beyond current ability" condition made operational. - -**Boundary conditions.** Delayed feedback is used in exactly one place: -`EXAM_SIM` mode, where scoring is withheld until the review phase because the -point of that mode is simulating test conditions and exercising -self-monitoring — not because delay helps learning. The genuine benefit that -delayed feedback shows in some studies is spacing in disguise (Butler & -Roediger 2008; Metcalfe, Kornell & Finn 2009), and Study-Bot captures that -benefit the honest way: immediate feedback on every attempt *plus* scheduled -re-encounters of missed items (variants in-session, repair prompts and due -warm-ups in later sessions) rather than by withholding answers. +**In Study Bot.** Every question is a closed loop: a committed attempt, a +score, elaborated feedback on the same screen, and then a correction step +after a miss. A free recall miss asks you to write a correction rule in your +own words; a multiple choice miss records the correct answer as its rule +automatically. Either way, a repair question on the same point is added to +the end of the session (at most four per session, so the session stays +bounded), and missing a repair question adds another. Error repair sessions +skip this step, since every question in them already retests an error. +Feedback is generated and saved with each attempt, so it survives a page +refresh instead of being regenerated or lost. From the second scored answer +on, the runner also reorders the questions that are left by difficulty +(section 12), a rough working version of the "slightly beyond current +ability" condition. + +**Boundary conditions.** Delayed feedback is used in exactly one place, Exam +simulation (`EXAM_SIM`). You answer every question first (the Answering +phase), then score each answer against its model answer (the Scoring phase). +That delay is there to simulate test conditions and to exercise +self-monitoring. The benefit delayed feedback shows in some studies looks +like spacing in disguise (Butler & Roediger 2008; Metcalfe, Kornell & Finn +2009), and Study Bot gets that benefit through immediate feedback on every +attempt plus scheduled returns to missed items: repair questions in the same +session, then repair questions and reviews of due topics in later sessions. ## 3. Elaborated feedback @@ -110,63 +121,74 @@ warm-ups in later sessions) rather than by withholding answers. Van der Kleij, Feskens & Eggen's (2015, *Review of Educational Research* 85(4)) meta-analysis of computer-based learning found elaborated feedback (explaining *why*) produced g = 0.49, versus 0.32 for showing the correct -answer and only 0.05 for bare right/wrong verification — roughly an order of +answer and only 0.05 for bare right/wrong verification, roughly an order of magnitude difference between explanation and verification. Shute (2008) reaches the same conclusion. Kluger & DeNisi (1996, *Psychological Bulletin* -119, 254–284; 607 effect sizes) supply the critical warning: over a third of +119, 254-284; 607 effect sizes) supply the critical warning: over a third of feedback interventions *decrease* performance, reliably the ones that direct attention to the self (praise, grades, person-level judgment) rather than the task. -**In Study-Bot.** A wrong or partial answer never gets a bare "incorrect." -The feedback panel stacks: cited excerpts retrieved from your own uploaded -course materials (with source and page), an explanation of the specific gap -in your answer, a key takeaway, a memory aid when the concept is easily -confused, and — for MCQ — the rationale for the specific distractor you chose. -If you show a repeated pattern of similar errors, the feedback addresses the -pattern directly. All templates are task-focused by design: what was wrong, -why, what to do differently — no personality praise, no normative comparison. -Correct answers get lighter treatment (brief reinforcement and a concept -connection) rather than a full explanation. +**In Study Bot.** A wrong or partly correct answer never gets a bare +"Incorrect." The sheet that slides up after the answer gives the verdict and +a one-line takeaway. Under the answered question, the feedback has an +explanation of the specific gap in your answer, labeled AI-written, with +citations to numbered sources from your own uploaded materials ("Source 2: +Lecture 5, page 3") and the cited passages listed below it. Short notes +follow when they apply (More context, Connection, Memory aid, Pattern), then +your own correction. A multiple choice miss also gets a note on why the +option you picked was tempting. When at least three of your recent errors in +the course share an error type, the Pattern note addresses that pattern +directly. The feedback prompts are task-focused by design: what was wrong, +why, and what to do differently, with no praise of the person and no +comparison with other students. A correct answer gets lighter treatment, a +short "Why it's correct" note and a connection to related ideas, instead of +a full explanation. **Boundary conditions.** Elaboration's advantage is largest for conceptual, higher-order material, so the explanation budget is spent on misses and partial answers; confirming a correct simple fact does not trigger the full apparatus. Feedback is grounded in retrieved excerpts from your materials and cites them precisely so you can check the explanation against the source -rather than trusting generated text. +rather than trusting generated text. That grounding depends on the search +finding a matching passage. When it finds none, the panel says your materials +don't cover the question and shows no sources, and no unsourced explanation +is presented as sourced. ## 4. Hypercorrection: confident errors are the highest-value corrections **The research.** Butterfield & Metcalfe (2001, *JEP: Learning, Memory & -Cognition* 27, 1491–1494) found that errors committed with *high* confidence -are, after corrective feedback, better corrected than low-confidence errors — +Cognition* 27, 1491-1494) found that errors committed with *high* confidence +are, after corrective feedback, better corrected than low-confidence errors: the surprise of being confidently wrong captures attention and makes the correction salient (Fazio & Marsh 2009). But there is a catch: Butler, Fazio -& Marsh (2011, *Psychonomic Bulletin & Review* 18, 1238–1244) showed that at -a delay, the original high-confidence errors tend to re-intrude — a single +& Marsh (2011, *Psychonomic Bulletin & Review* 18, 1238-1244) showed that at +a delay, the original high-confidence errors tend to re-intrude, so a single successful correction is not durable repair. -**In Study-Bot.** The app captures a 1–5 confidence rating before you see the -answer. Confidence is stored on the attempt and, when the answer is wrong, on -the resulting error log, and it flows through three mechanisms. First, -feedback framing: when you were confident (4–5) and wrong, the explanation -opens by explicitly flagging the mismatch and delivers the fullest, most -memorable correction — that is the hypercorrection window, used on purpose. -Low-confidence misses are framed as expected gap-filling instead. Second, -prioritization: confident misses are ordered first when building -`ERROR_REPAIR` decks and when the per-session variant cap forces a choice -about which errors get re-tested. Third, the SM-2 mastery engine penalizes -the confident-but-wrong pattern (a "blind spot") so the objective resurfaces -sooner. +**In Study Bot.** Before you see the answer, the app asks "How sure are +you?" on a three-level scale: Guessing, Unsure, or Sure, stored as 1, 3, and +5. The rating is optional. Confidence is stored on the attempt and, when the +answer is wrong, on the resulting error log, and it feeds three mechanisms. +First, feedback framing: when you marked Sure and were wrong, the screen +shows a "Confident error" note, and the explanation opens by naming the +mismatch and gives the fullest correction, using the hypercorrection window +on purpose. A miss marked Guessing is framed as a gap to fill instead. +Second, prioritization: errors marked Sure come first in Error repair +sessions and in the repair questions added to later Retrieval and +Interleaved practice sessions. Third, the SM-2 mastery engine penalizes the +confident-but-wrong pattern (a "blind spot"). When a topic scores under 50% +in a session and your average confidence on it is above 3.4 on the 1 to 5 +scale, its quality score drops by one, so the topic comes back sooner. **Boundary conditions.** Because hypercorrected errors resurface at a delay, -a confident miss is never considered fixed after one correction — it enters +a confident miss is never considered fixed after one correction. It enters the same successive-relearning criterion as every other error (two correct retrievals on different days, section 6), and its priority ordering means it actually receives those re-encounters. Confidence is never fabricated: if you skip the rating, no default is invented, because a made-up value would corrupt -both the calibration dashboard and the mastery adjustment. +both the confidence results (on the end screen and on Progress) and the +mastery adjustment. ## 5. Spacing (distributed practice) @@ -174,34 +196,39 @@ both the calibration dashboard and the mastery adjustment. (2013) two "high utility" techniques. Cepeda, Pashler, Vul, Wixted & Rohrer's (2006) meta-analysis found spaced practice beats massed practice across 254 studies. Cepeda et al. (2008, *Psychological Science*) established the -practical rule: the optimal gap between sessions is roughly 10–20% of the +practical rule: the optimal gap between sessions is roughly 10 to 20% of the desired retention interval, gaps that are too short cost more than gaps that -are too long — and, importantly, if the test is within about a day, +are too long, and if the test is within about a day, compressed review actually wins. -**In Study-Bot.** Spacing runs on an SM-2-style scheduler at the level of -learning objectives: each objective tracks ease factor, interval, and -repetitions, updated from your per-objective accuracy after every run (with -confidence-weighted quality adjustment — see section 11). The scheduler is -exam-aware, implementing Cepeda's compression directly: with more than two -weeks to the exam, intervals are capped at ~20% of the remaining days; inside -two weeks the cap tightens to 3 days, inside a week to 2 days, and with 1–3 -days left everything reviews daily. Objectives that come due resurface -automatically as warm-up prompts at the start of your next run. Flashcard -decks (including cards auto-generated from your errors) run their own SM-2 -schedule under the same exam-aware compression policy, with one addition: a -failed card returns in 10 minutes within the same sitting. Each completed -session ends with concrete follow-up recommendations derived from the actual -SM-2 due dates of the objectives you just studied; when no mastery data -exists yet, they fall back to accuracy brackets (below 70%: return in 1 and 2 -days; 70–85%: 2 and 4 days; above 85%: 3 and 6 days). The week planner -schedules sessions from the exam date backwards on the same logic. +**In Study Bot.** Spacing runs on an SM-2-style scheduler at the level of +topics (learning objectives). Each topic tracks an ease factor, an interval, +and a repetition count, updated at the end of every session from your +accuracy on that topic, with a confidence adjustment (section 11). The +scheduler is exam-aware and implements Cepeda's compression directly: with +more than two weeks to the exam, intervals are capped at about 20% of the +remaining days; inside two weeks the cap tightens to 3 days, inside a week to +2 days, and with 1 to 3 days left everything reviews daily. Topics that come +due return as review questions at the start of your next Retrieval or +Interleaved practice session in that course. Flashcard decks (including cards +generated from your errors) run their own SM-2 schedule under the same +exam-aware compression, with one addition: a card you rate Again comes back +in 10 minutes within the same sitting. The end screen of a session suggests +two follow-up Retrieval sessions spaced by that session's accuracy: below +70%, in 1 and 2 days; from 70% to 85%, in 2 and 4 days; above 85%, in 3 and 6 +days. Add follow-ups to plan puts them into your plan's daily study hours and +skips any day that has passed or falls after the exam. A plan covers the +seven days from the day you create it, within your daily study hours, and +drops anything on or after exam day. When the exam falls inside that week, +the plan tapers the last two days before it: sessions in the final 48 hours +become Retrieval at 60% of their planned length, and the final 24 hours keep +a single Retrieval session of at most 25 minutes. None of the papers below +tested that taper; the rule is adapted from athletic training research. **Boundary conditions.** Spacing is deliberately abandoned when it would hurt: the exam-aware compression means that the night before a test the -scheduler stops stretching intervals and pulls everything into daily review — -cramming genuinely wins for a test within ~24 hours, and pretending otherwise -would be ideology, not science. A gap so long that retrieval fails outright +scheduler stops stretching intervals and pulls everything into daily review, +because cramming wins for a test within about 24 hours. A gap so long that retrieval fails outright is wasted time unless followed by relearning, which is why failed reviews reset to short intervals rather than continuing to stretch. @@ -216,23 +243,24 @@ order of a letter grade on targeted exam content, at low added time cost. The key insight is that mastery is defined by correct retrievals across separate sessions, not by items seen or minutes spent. -**In Study-Bot.** Errors are governed by a cross-day criterion: an error log -is only marked resolved after **two correct retrievals on different days**. -Each error tracks a correct streak with the date of the last success; a -correct answer on the same calendar day as the previous one doesn't advance -the streak, and the streak resets if you miss the item again. Until resolved, -the error keeps feeding the repair machinery: an in-session variant question -after the initial miss, cross-session repair prompts prepended to later runs, -dedicated `ERROR_REPAIR` sessions, and an auto-generated flashcard. Objective -mastery similarly requires at least three successful spaced repetitions -before an objective is reported as mastered. +**In Study Bot.** Errors follow a cross-day criterion: an error log is marked +resolved only after two correct retrievals on different days. Each error +tracks a correct streak and the date of its last success, counted in +calendar days in your time zone. A correct answer on the same day as the +previous one doesn't advance the streak, and a wrong answer on a repair +question resets it. Until it is resolved, the error keeps coming back: as a +repair question later in the same session, as one of up to two repair +questions at the start of later Retrieval and Interleaved practice sessions +in the course, in Error repair sessions, and as a flashcard generated from +it. Topic mastery has a similar bar: a topic shows as Mastered only after +three passing reviews in a row with an ease factor of at least 2.0. **Boundary conditions.** Piling extra correct recalls into a *single* session (overlearning) yields sharply diminishing returns (Rohrer & Taylor 2006), so -Study-Bot does not demand within-session drilling to high streaks — the -criterion is deliberately spent across days, where the payoff is. The -same-day guard exists precisely so you cannot "resolve" an error by answering -it twice in one sitting. +Study Bot doesn't drill an error to a high streak within one session. The +criterion is spread across days, where the payoff is. The same-day guard +exists precisely so you cannot "resolve" an error by answering it twice in +one sitting. ## 7. Interleaving @@ -241,24 +269,29 @@ blocking them (AAA-BBB-CCC), forces the learner to *choose* the right approach rather than just execute the obvious one. Rohrer & Taylor (2007) found interleaved math practice roughly doubled delayed test scores versus blocked practice; a classroom randomized controlled trial (Rohrer, Dedrick, Hartwig & -Cheung 2020, *JEP: Applied*) found d = 0.83. Brunmair & Richter's (2019, +Cheung 2020, *Journal of Educational Psychology*) found d = 0.83. Brunmair & Richter's (2019, *Psychological Bulletin*) meta-analysis puts the overall effect at g = 0.42, strongest for confusable, similar categories. Kornell & Bjork (2008, *Psychological Science*) documented the trap: learners judge blocked practice as more effective even while interleaving produces better learning. -**In Study-Bot.** `INTERLEAVED_PRACTICE` mode distributes prompts round-robin -across the session's objectives using a deterministic seeded shuffle, with a -hard guarantee of no more than two consecutive prompts from the same objective -(when the session has two or more objectives). AI-generated decks — which -arrive grouped by objective and would otherwise be blocked practice — are -re-interleaved through the same machinery before the run starts, so the -guarantee holds regardless of how the deck was produced. +**In Study Bot.** Interleaved practice (`INTERLEAVED_PRACTICE`) deals the +session's questions round-robin across its topics, after a deterministic +seeded shuffle within each topic. When the questions come from templates and +the session has two or more topics, no two questions in a row share a topic. +AI-generated question sets arrive grouped by topic and would otherwise be +blocked practice, so they go through the same round-robin before the session +starts. Topics alternate until the smaller ones run out, so when the +generator returns more questions for one topic than for the others, the +extras end up together at the end. The review, pretest and repair questions +added at the start sit outside the rotation. When adaptive difficulty swaps +in a different question (section 12), it prefers one whose topic differs from +the question before it. **Boundary conditions.** Interleaving helps discrimination between *similar* -categories and does nothing (or harms) for unrelated content, so Study-Bot -interleaves within a session's related objectives — it never shuffles across -unrelated courses. Expect interleaved sessions to feel harder and produce +categories and does nothing (or harms) for unrelated content, so Study Bot +interleaves only among a session's own topics, which all come from one +course. Expect interleaved sessions to feel harder and produce lower in-session accuracy than blocked practice would; that is the mechanism working, not the feature failing, and delayed retention is the metric that matters. @@ -266,18 +299,24 @@ matters. ## 8. Pretesting **The research.** Attempting to answer questions *before* studying the -material — even when the guesses are wrong — improves subsequent learning +material, even when the guesses are wrong, improves subsequent learning compared to spending the same time studying (Richland, Kornell & Kao 2009, -*JEP: Applied* 15, 243–257; Kornell, Hays & Bjork 2009, *JEP: LMC* 35, -989–998). The failed attempt appears to prime the learner for the correct +*JEP: Applied* 15, 243-257; Kornell, Hays & Bjork 2009, *JEP: LMC* 35, +989-998). The failed attempt appears to prime the learner for the correct answer. The technique depends entirely on prompt corrective feedback: errorful guessing without seeing the right answer is risky. -**In Study-Bot.** When a run includes objectives you have never studied, up -to two diagnostic pretest prompts are prepended to the deck, marked -internally as pretest items. Wrong answers on them are the expected outcome, -and they are treated accordingly — the item closes with the correct-answer -framing so the loop still ends on the right information. +**In Study Bot.** When a Retrieval or Interleaved practice session covers +topics you have never studied (no mastery record yet), up to two pretest +questions on them go at the front of the session, marked as pretest items on +the server. Pretests, reviews of due topics and repair questions share a +budget inside the session's question count (about a quarter of it, at most +three), and repairs win when it's tight. The question screen says wrong +answers are expected and don't count toward accuracy. Afterwards the result +reads "Pretest done" in place of a score. When the question has a model +answer, the screen points you to it; otherwise the correct information comes +from the sourced feedback under the question, as long as your materials +cover the topic. **Boundary conditions.** Pretest items are **quarantined from grading**: they do not require an error log (there is no misconception to repair in material @@ -285,26 +324,27 @@ you've never seen), and they are excluded from the accuracy metrics that drive adaptive difficulty and from the mastery/scheduling machinery. The quarantine is enforced server-side against the stored prompt metadata, not trusted from the client. Without this quarantine, pretesting would punish -exactly the productive errors it depends on — dragging difficulty down, +exactly the productive errors it depends on: dragging difficulty down, minting spurious flashcards, and teaching users that pretesting "hurts their score," a misjudgment learners are already prone to (Pan & Sana 2021). ## 9. Worked examples with backward fading **The research.** For novices learning procedures, studying a fully worked -solution beats solving the equivalent problem — the worked-example effect +solution beats solving the equivalent problem. This is the worked-example effect (Sweller & Cooper 1985), a core prediction of cognitive load theory. Renkl, -Atkinson & Große (2002–2004) showed the best transition off examples is +Atkinson and colleagues (2002, 2004) showed the best transition off examples is *backward fading*: remove the final solution step first and have the learner -supply it, then the final two, and so on — rather than jumping abruptly from +supply it, then the final two, and so on, instead of jumping abruptly from example to full problem. Kalyuga, Ayres, Chandler & Sweller (2003, *Educational Psychologist*) documented the expertise-reversal effect: the same worked examples that help novices actively *hurt* learners with higher prior knowledge, for whom retrieval and problem solving are superior. -**In Study-Bot.** `WORKED_EXAMPLES` mode generates example sets grounded in -your uploaded course materials. Each set follows the backward-fading sequence -in full: (1) a complete worked example with 3–5 ordered solution steps, each +**In Study Bot.** The Worked examples mode (`WORKED_EXAMPLES`) generates +example sets grounded in your uploaded course materials, up to three sets per +session. Each set follows the backward-fading sequence +in full: (1) a complete worked example with 3 to 5 ordered solution steps, each stating both the action and the principle from the material that licenses it; (2) a completion problem of the same structure with the *final* step missing; (3) a completion problem with the final *two* steps missing; (4) a novel @@ -312,10 +352,12 @@ near-transfer problem with no steps given, checked against a model answer. Completion problems reuse the same problem structure with different surface values, so what fades is support, not the concept. Steps pair with self-explanation prompts (section 10), because passively read examples lose -most of their benefit. +most of their benefit. Without an AI provider, or when your materials have +fewer than two passages on the session's topics, the mode falls back to +Retrieval questions so the session still runs. -**Boundary conditions.** Worked examples are a novice-phase tool, not a -review mode — this is the expertise-reversal boundary taken seriously. The +**Boundary conditions.** Worked examples are a novice-phase tool. The +expertise-reversal effect is why they are not a review mode. The fading sequence itself walks you off the scaffolding within a single session, ending at unaided problem solving; and once material has been studied, retrieval-based modes remain the default for review. The mode targets @@ -330,22 +372,25 @@ the ones who spontaneously explained each step to themselves; Chi et al. (1994) showed that *prompting* self-explanation confers the benefit on everyone else. Bisra, Liu, Nesbit, Salimi & Winne's (2018, *Educational Psychology Review*) meta-analysis estimates g ≈ 0.55. Dunlosky et al. (2013) -rate it moderate utility — promising, with the caveat that it is -time-expensive. - -**In Study-Bot.** The post-answer review panel invites two generative acts, -both persisted on the attempt: an explain-back ("restate the key concept as -if teaching a friend") and creating your own example of the concept. The -feedback for conceptual items also poses a Socratic follow-up question — and -it has an answer field, so the elaboration loop closes with your own words -rather than ending at a rhetorical question. In `WORKED_EXAMPLES` mode, -solution steps carry "why does this step follow?" prompts. +rate it moderate utility: promising, but time-expensive. + +**In Study Bot.** Under the feedback, a link reads "Explain it in your own +words." It opens optional fields that are saved with the attempt when you +move on: your explanation of the idea "as if you were teaching it," an answer +to a follow-up question written for the item (shown as "Question to +consider" and labeled AI-written), and, after a correct answer, your own +example of a case where the idea applies. The follow-up question has its own +answer field, so the elaboration ends in your own words. In Worked examples, +each step states why it follows, the study problem asks why the last step +follows from the ones before it, and each completion problem asks you to say +why the steps you write follow. **Boundary conditions.** Self-explanation prompts are hidden until after the attempt (an explanation you can copy from visible text is transcription, not -generation). Because the technique is time-expensive, it is positioned in the -review phase and kept optional — it is worth the minutes on conceptual -material and first-time errors, not on every flashcard flip. +generation). Because the technique is time-expensive, it sits behind one +link after the feedback and stays optional. It is worth the minutes on +conceptual material and first-time errors, and flashcard reviews don't ask +for it. ## 11. Calibration and metacognition @@ -358,29 +403,38 @@ delayed ones (Nelson & Dunlosky 1991, *Psychological Science*), and the weakest performers are the most miscalibrated (Kruger & Dunning 1999). Self-scoring without an answer standard is systematically lenient. -**In Study-Bot.** Three mechanisms. First, confidence ratings are collected -*before* the answer is revealed, so the judgment cannot be contaminated by -hindsight. Second, generated prompts carry a model answer and explicit key -points, surfaced after your answer is committed and before you self-score — -you grade yourself against a standard, point by point, not against a feeling. -Third, the end-of-session screen includes a calibration dashboard comparing -your stated confidence to your actual accuracy, counting overconfident and -underconfident answers, so the gap is visible and trackable over time. The -gap also feeds the scheduler: confident-but-wrong objectives are penalized in -SM-2 quality (resurfacing sooner), and correct-but-unsure answers advance more -slowly, since hesitant knowledge is fragile knowledge. +**In Study Bot.** Three mechanisms. First, confidence ratings are collected +*before* the answer is revealed, so hindsight can't contaminate the +judgment. Second, generated free recall questions carry a model answer and a +list of "Points to check," shown after your answer is committed and before +you score yourself, so you grade against a written standard point by point. +Third, the end screen has a Confidence section that charts how often you +were right at each level. An answer marked Sure that wasn't fully correct +counts as overconfident, and Unsure never counts as a mismatch. Correct +answers marked Guessing count as underconfidence only as a pattern (at least +three guesses, half or more of them right), since one lucky guess shows +nothing. The section summarizes nothing until at least three answers are +rated; Progress charts the same comparison week by week. The gap also feeds +the scheduler. A topic you got mostly wrong while leaning Sure loses a point of +SM-2 quality and comes back sooner. A topic you got mostly right while mostly +guessing (an average rating under 2.2) also loses a point, but never below a +passing grade, so it advances more slowly instead of resetting, since +hesitant knowledge is fragile knowledge. **Boundary conditions.** Calibration data is only as honest as the inputs, so -the app refuses to invent a confidence value when you skip the rating. MCQ -attempts are graded by the server against the stored answer key rather than -self-scored at all. Self-scoring of free recall remains self-scoring — the -model-answer standard makes leniency harder, not impossible (see section 14). +the app refuses to invent a confidence value when you skip the rating. +Outside Exam simulation, the server grades multiple choice answers against +the stored answer key, so they aren't self-scored at all. In Exam simulation +the key reaches the browser only after your last answer is saved, and the +scoring screen marks each saved pick against it. Self-scoring of free recall +remains self-scoring: the model-answer standard makes leniency harder but +still possible (see section 14). ## 12. Desirable difficulties **The research.** Bjork & Bjork's desirable-difficulties framework (1992, -2011) holds that conditions that slow apparent learning — spacing, -interleaving, testing, generation — often improve long-term retention, while +2011) holds that conditions that slow apparent learning (spacing, +interleaving, testing, generation) often improve long-term retention, while conditions that feel fluent (rereading, blocked drill) inflate confidence without durable learning. Roediger & Karpicke (2006) captured it directly: the restudy group predicted better performance and did worse. Learners @@ -388,22 +442,27 @@ misread effort as ineffectiveness and abandon what works (Kirk-Johnson, Galla & Fraundorf 2019). Ericsson's difficulty condition (section 2) supplies the target: practice slightly beyond current ability. -**In Study-Bot.** The app aims to keep you in a success band of roughly -70–85% — hard enough to be worth doing, achievable enough that feedback loops -close on success. When your running accuracy climbs past 85%, follow-up -sessions stretch further out; when it exceeds 80% in-session, the runner -swaps upcoming prompts for harder variants of the same objectives. Every -structural choice in the app — questions before notes, mixed rather than -blocked decks, gaps rather than cramming, generation rather than recognition -— is a difficulty chosen on purpose. +**In Study Bot.** Sessions from a plan or a follow-up carry a target +accuracy, 80% (70% for Exam simulation), which the start screen shows: hard +enough to be worth doing, achievable enough that feedback loops close on +success. Two mechanisms push toward it. Inside a session, from the second +scored answer on, the runner reorders the questions that are left by their +difficulty rating: harder ones when your running accuracy is 80% or above, +middling ones from 50% to 80%, and easier ones below 50%. It only moves +questions the session already has, and Exam simulation keeps its order. +Across sessions, follow-ups stretch further out as accuracy rises (3 and 6 +days above 85%). The app's structural choices are difficulties picked on +purpose: questions before notes, mixed topics over blocked ones, gaps over +cramming, and generation over recognition. **Boundary conditions.** Difficulty is only desirable when the learner can -eventually succeed and gets feedback. When accuracy falls, the app eases off -rather than doubling down: below 70%, follow-up gaps compress to 1–2 days; -failed objectives reset to short intervals; warm-ups re-expose due material -before new questions; and worked examples exist precisely for the case where -retrieval-first would mean drowning. Difficulty caused by confusing materials -or near-zero success is not desirable — it is just failure. +eventually succeed and gets feedback. When accuracy falls, the app eases off: +below 50% the runner moves easier questions forward, below 70% follow-ups +come back after 1 and 2 days, failed topics reset to a 1-day interval, +reviews bring due topics back before new questions, and worked examples +exist precisely for the case where retrieval first would mean drowning. +Difficulty caused by confusing materials or near-zero success is just +failure. ## 13. A cognitive-load-minimal interface @@ -417,26 +476,31 @@ contiguity); visually cueing the essential structure, d = 0.46 (signaling). Seductive-details meta-analyses (Rey 2012; Sundararajan & Adesope 2020) show decorations and asides measurably reduce retention and transfer. -**In Study-Bot.** The practice screen is built around the question: one -prompt per screen, the question stem at the top of the visual hierarchy, a -thin progress indicator ("k of N" with a bar) at the edge, and no decorative -elements between question and answer. Feedback obeys spatial contiguity — -your answer, the model answer, the explanation, and the cited excerpts stack -in one vertical block in the same region, not in a modal or a separate -results page. The loop is built for repetition: answers submit from the -keyboard, progress persists after every attempt so a refresh or crash loses -nothing, and the next prompt follows without interstitials. Gamification -exists (XP, achievements, streak-based milestones) but is awarded at -completion boundaries — a finished session, a completed deck — and none of it -renders inside the question–answer loop, where it would compete for exactly -the attention retrieval needs. - -**Boundary conditions.** Session-level structure that serves the pedagogy is -kept even though it adds elements: the preflight screen's closed-book -commitments, break screens on the Pomodoro-style protocols (work/break cycles -that gate attempt submission), and the end-of-session dashboard with score -breakdown and calibration — all deliberately placed *outside* the answer -loop, before or after, never during. +**In Study Bot.** The question screen is built around the question. There is +one question per screen, and it is the page heading and the largest text on +it. The app navigation goes away during a session. What's left is a close +button, a progress bar with "Question 3 of 12," and the question, with +nothing decorative between question and answer. Feedback follows spatial +contiguity: the answered question stays on screen, the verdict slides up +from the bottom in a short sheet, and your answer, the model answer, the +explanation and its numbered sources read in one column under the question, +with no modal and no separate results page. The loop is built for +repetition: answers submit from the keyboard, progress is saved after every +attempt so a refresh or crash loses nothing, and the next question follows +without interstitials. XP, achievements and streaks exist, but none of them +render inside the question and answer loop, where they would compete for the +attention retrieval needs. A session's XP is awarded when it finishes. A +flashcard review earns a little per card, and the total shows only in the +summary at the end of the review. + +**Boundary conditions.** Some session structure serves the pedagogy and stays +even though it adds elements. The start screen lists the questions, the +planned time, the target accuracy, and the rule that notes stay closed until +you check each answer. Sessions with a break pattern show a break screen +between work blocks, and an answer can't be submitted until the break ends. +The end screen shows accuracy, the score breakdown, and the Confidence +section. All of it sits before, between, or after questions, never inside +one. ## 14. Honest limitations @@ -448,15 +512,17 @@ implementation do not support. materials, and delays. Your mileage will vary with course, prior knowledge, and honesty of use. - **Free-recall self-scoring is still self-scoring.** The model-answer - standard and calibration dashboard make lenient grading visible and harder, - but a student determined to grade "correct" on a vague answer can. MCQ - items are server-graded; free recall is not. + standard and the Confidence section make lenient grading visible and harder, + but a student determined to grade "correct" on a vague answer can. + Multiple choice is graded against the answer key; free recall is not. - **Generated content should be spot-checked.** Questions, model answers, - worked-example steps, and feedback are grounded in retrieved excerpts from - your uploaded materials and cite their sources precisely so you can verify - them. Grounding sharply reduces, but does not eliminate, the possibility of - a generated error — the citations exist so you never have to take the - explanation's word for it. + worked-example steps, and feedback are written from passages of your + uploaded materials. Model answers and feedback carry an AI-written label, + and feedback explanations cite their passages as numbered sources so you + can check them; questions and model answers don't list sources on screen. + Grounding lowers the chance of a generated error without ruling one out, + and the numbered sources let you check an explanation against the passage + it came from. - **The scheduler proposes; you dispose.** Spacing only works if the later sessions happen. The planner, calendar sync, and follow-up recommendations lower the friction of showing up on schedule, but no algorithm retrieves a @@ -468,39 +534,64 @@ implementation do not support. ## References -Adesope, O. O., Trevisan, D. A., & Sundararajan, N. (2017). Rethinking the use of tests: A meta-analysis of practice testing. *Review of Educational Research*, 87(3). -Bisra, K., Liu, Q., Nesbit, J. C., Salimi, F., & Winne, P. H. (2018). Inducing self-explanation: A meta-analysis. *Educational Psychology Review*, 30. -Bjork, R. A., & Bjork, E. L. (1992; 2011). Desirable difficulties in theory and practice. -Brunmair, M., & Richter, T. (2019). Similarity matters: A meta-analysis of interleaved learning. *Psychological Bulletin*, 145(11). -Butler, A. C., Fazio, L. K., & Marsh, E. J. (2011). The hypercorrection effect persists over a week, but high-confidence errors return. *Psychonomic Bulletin & Review*, 18, 1238–1244. -Butler, A. C., & Roediger, H. L. (2008). Feedback enhances the positive effects and reduces the negative effects of multiple-choice testing. *Memory & Cognition*, 36, 604–616. -Butterfield, B., & Metcalfe, J. (2001). Errors committed with high confidence are hypercorrected. *JEP: Learning, Memory, and Cognition*, 27, 1491–1494. -Cepeda, N. J., Pashler, H., Vul, E., Wixted, J. T., & Rohrer, D. (2006). Distributed practice in verbal recall tasks: A review and quantitative synthesis. *Psychological Bulletin*, 132(3). -Cepeda, N. J., Vul, E., Rohrer, D., Wixted, J. T., & Pashler, H. (2008). Spacing effects in learning: A temporal ridgeline of optimal retention. *Psychological Science*, 19(11). -Chi, M. T. H., Bassok, M., Lewis, M. W., Reimann, P., & Glaser, R. (1989). Self-explanations: How students study and use examples in learning to solve problems. *Cognitive Science*, 13. -Corbett, A. T., & Anderson, J. R. (2001). Locus of feedback control in computer-based tutoring. *Proceedings of CHI 2001*. -Dunlosky, J., & Rawson, K. A. (2012). Overconfidence produces underachievement. *Learning and Instruction*, 22. -Dunlosky, J., Rawson, K. A., Marsh, E. J., Nathan, M. J., & Willingham, D. T. (2013). Improving students' learning with effective learning techniques. *Psychological Science in the Public Interest*, 14(1). -Ericsson, K. A., Krampe, R. T., & Tesch-Römer, C. (1993). The role of deliberate practice in the acquisition of expert performance. *Psychological Review*, 100(3), 363–406. -Fazio, L. K., & Marsh, E. J. (2009). Surprising feedback improves later memory. *Psychonomic Bulletin & Review*, 16. -Kalyuga, S., Ayres, P., Chandler, P., & Sweller, J. (2003). The expertise reversal effect. *Educational Psychologist*, 38(1). -Kluger, A. N., & DeNisi, A. (1996). The effects of feedback interventions on performance. *Psychological Bulletin*, 119, 254–284. -Kornell, N., & Bjork, R. A. (2008). Learning concepts and categories: Is spacing the "enemy of induction"? *Psychological Science*, 19(6). -Kornell, N., Hays, M. J., & Bjork, R. A. (2009). Unsuccessful retrieval attempts enhance subsequent learning. *JEP: Learning, Memory, and Cognition*, 35, 989–998. -Kulik, J. A., & Kulik, C.-L. C. (1988). Timing of feedback and verbal learning. *Review of Educational Research*, 58(1), 79–97. -Metcalfe, J., Kornell, N., & Finn, B. (2009). Delayed versus immediate feedback in children's and adults' vocabulary learning. *Memory & Cognition*, 37, 1077–1087. -Nelson, T. O., & Dunlosky, J. (1991). The delayed-JOL effect. *Psychological Science*, 2(4). -Pan, S. C., & Sana, F. (2021). Pretesting versus posttesting: Comparing the pedagogical benefits of errorful generation and retrieval practice. *JEP: Applied*, 27(2). -Rawson, K. A., & Dunlosky, J. (2011). Optimizing schedules of retrieval practice for durable and efficient learning: How much is enough? *JEP: General*, 140(3). -Rawson, K. A., Dunlosky, J., & Sciartelli, S. M. (2013). The power of successive relearning. *Educational Psychology Review*, 25. -Renkl, A., Atkinson, R. K., & Große, C. S. (2002–2004). Backward fading of worked-out solution steps. -Richland, L. E., Kornell, N., & Kao, L. S. (2009). The pretesting effect: Do unsuccessful retrieval attempts enhance learning? *JEP: Applied*, 15, 243–257. -Roediger, H. L., & Karpicke, J. D. (2006). Test-enhanced learning: Taking memory tests improves long-term retention. *Psychological Science*, 17(3). -Roediger, H. L., & Marsh, E. J. (2005). The positive and negative consequences of multiple-choice testing. *JEP: Learning, Memory, and Cognition*, 31. -Rohrer, D., Dedrick, R. F., Hartwig, M. K., & Cheung, C.-N. (2020). A randomized controlled trial of interleaved mathematics practice. *JEP: Applied*, 26(1). -Rohrer, D., & Taylor, K. (2007). The shuffling of mathematics problems improves learning. *Instructional Science*, 35. -Shute, V. J. (2008). Focus on formative feedback. *Review of Educational Research*, 78, 153–189. -Sundararajan, N., & Adesope, O. (2020). Keep it coherent: A meta-analysis of the seductive details effect. *Educational Psychology Review*, 32. -Sweller, J. (1988). Cognitive load during problem solving. *Cognitive Science*, 12. -Sweller, J., & Cooper, G. A. (1985). The use of worked examples as a substitute for problem solving in learning algebra. *Cognition and Instruction*, 2(1). -Van der Kleij, F. M., Feskens, R. C. W., & Eggen, T. J. H. M. (2015). Effects of feedback in a computer-based learning environment on students' learning outcomes: A meta-analysis. *Review of Educational Research*, 85(4). +Links point to each paper's DOI. Book chapters without a DOI are cited +without a link. + +- Adesope, O. O., Trevisan, D. A., & Sundararajan, N. (2017). Rethinking the use of tests: A meta-analysis of practice testing. *Review of Educational Research*, 87(3), 659-701. https://doi.org/10.3102/0034654316689306 +- Bisra, K., Liu, Q., Nesbit, J. C., Salimi, F., & Winne, P. H. (2018). Inducing self-explanation: A meta-analysis. *Educational Psychology Review*, 30(3), 703-725. https://doi.org/10.1007/s10648-018-9434-x +- Bjork, E. L., & Bjork, R. A. (2011). Making things hard on yourself, but in a good way: Creating desirable difficulties to enhance learning. In M. A. Gernsbacher, R. W. Pew, L. M. Hough, & J. R. Pomerantz (Eds.), *Psychology and the real world* (pp. 56-64). Worth. +- Bjork, R. A., & Bjork, E. L. (1992). A new theory of disuse and an old theory of stimulus fluctuation. In A. F. Healy, S. M. Kosslyn, & R. M. Shiffrin (Eds.), *From learning processes to cognitive processes: Essays in honor of William K. Estes* (Vol. 2, pp. 35-67). Erlbaum. +- Brunmair, M., & Richter, T. (2019). Similarity matters: A meta-analysis of interleaved learning and its moderators. *Psychological Bulletin*, 145(11), 1029-1052. https://doi.org/10.1037/bul0000209 +- Butler, A. C., Fazio, L. K., & Marsh, E. J. (2011). The hypercorrection effect persists over a week, but high-confidence errors return. *Psychonomic Bulletin & Review*, 18(6), 1238-1244. https://doi.org/10.3758/s13423-011-0173-y +- Butler, A. C., & Roediger, H. L. (2008). Feedback enhances the positive effects and reduces the negative effects of multiple-choice testing. *Memory & Cognition*, 36(3), 604-616. https://doi.org/10.3758/MC.36.3.604 +- Butterfield, B., & Metcalfe, J. (2001). Errors committed with high confidence are hypercorrected. *Journal of Experimental Psychology: Learning, Memory, and Cognition*, 27(6), 1491-1494. https://doi.org/10.1037/0278-7393.27.6.1491 +- Cepeda, N. J., Pashler, H., Vul, E., Wixted, J. T., & Rohrer, D. (2006). Distributed practice in verbal recall tasks: A review and quantitative synthesis. *Psychological Bulletin*, 132(3), 354-380. https://doi.org/10.1037/0033-2909.132.3.354 +- Cepeda, N. J., Vul, E., Rohrer, D., Wixted, J. T., & Pashler, H. (2008). Spacing effects in learning: A temporal ridgeline of optimal retention. *Psychological Science*, 19(11), 1095-1102. https://doi.org/10.1111/j.1467-9280.2008.02209.x +- Chi, M. T. H., Bassok, M., Lewis, M. W., Reimann, P., & Glaser, R. (1989). Self-explanations: How students study and use examples in learning to solve problems. *Cognitive Science*, 13(2), 145-182. https://doi.org/10.1207/s15516709cog1302_1 +- Chi, M. T. H., de Leeuw, N., Chiu, M.-H., & LaVancher, C. (1994). Eliciting self-explanations improves understanding. *Cognitive Science*, 18(3), 439-477. https://doi.org/10.1207/s15516709cog1803_3 +- Corbett, A. T., & Anderson, J. R. (2001). Locus of feedback control in computer-based tutoring: Impact on learning rate, achievement and attitudes. *Proceedings of the SIGCHI Conference on Human Factors in Computing Systems (CHI 2001)*, 245-252. https://doi.org/10.1145/365024.365111 +- Cowan, N. (2001). The magical number 4 in short-term memory: A reconsideration of mental storage capacity. *Behavioral and Brain Sciences*, 24(1), 87-114. https://doi.org/10.1017/S0140525X01003922 +- Dunlosky, J., & Rawson, K. A. (2012). Overconfidence produces underachievement: Inaccurate self evaluations undermine students' learning and retention. *Learning and Instruction*, 22(4), 271-280. https://doi.org/10.1016/j.learninstruc.2011.08.003 +- Dunlosky, J., Rawson, K. A., Marsh, E. J., Nathan, M. J., & Willingham, D. T. (2013). Improving students' learning with effective learning techniques: Promising directions from cognitive and educational psychology. *Psychological Science in the Public Interest*, 14(1), 4-58. https://doi.org/10.1177/1529100612453266 +- Ericsson, K. A., Krampe, R. T., & Tesch-Römer, C. (1993). The role of deliberate practice in the acquisition of expert performance. *Psychological Review*, 100(3), 363-406. https://doi.org/10.1037/0033-295X.100.3.363 +- Fazio, L. K., & Marsh, E. J. (2009). Surprising feedback improves later memory. *Psychonomic Bulletin & Review*, 16(1), 88-92. https://doi.org/10.3758/PBR.16.1.88 +- Kalyuga, S., Ayres, P., Chandler, P., & Sweller, J. (2003). The expertise reversal effect. *Educational Psychologist*, 38(1), 23-31. https://doi.org/10.1207/S15326985EP3801_4 +- Kirk-Johnson, A., Galla, B. M., & Fraundorf, S. H. (2019). Perceiving effort as poor learning: The misinterpreted-effort hypothesis of how experienced effort and perceived learning relate to study strategy choice. *Cognitive Psychology*, 115, 101237. https://doi.org/10.1016/j.cogpsych.2019.101237 +- Kluger, A. N., & DeNisi, A. (1996). The effects of feedback interventions on performance: A historical review, a meta-analysis, and a preliminary feedback intervention theory. *Psychological Bulletin*, 119(2), 254-284. https://doi.org/10.1037/0033-2909.119.2.254 +- Kornell, N., & Bjork, R. A. (2008). Learning concepts and categories: Is spacing the "enemy of induction"? *Psychological Science*, 19(6), 585-592. https://doi.org/10.1111/j.1467-9280.2008.02127.x +- Kornell, N., Hays, M. J., & Bjork, R. A. (2009). Unsuccessful retrieval attempts enhance subsequent learning. *Journal of Experimental Psychology: Learning, Memory, and Cognition*, 35(4), 989-998. https://doi.org/10.1037/a0015729 +- Kruger, J., & Dunning, D. (1999). Unskilled and unaware of it: How difficulties in recognizing one's own incompetence lead to inflated self-assessments. *Journal of Personality and Social Psychology*, 77(6), 1121-1134. https://doi.org/10.1037/0022-3514.77.6.1121 +- Kulik, J. A., & Kulik, C.-L. C. (1988). Timing of feedback and verbal learning. *Review of Educational Research*, 58(1), 79-97. https://doi.org/10.3102/00346543058001079 +- Metcalfe, J., Kornell, N., & Finn, B. (2009). Delayed versus immediate feedback in children's and adults' vocabulary learning. *Memory & Cognition*, 37(8), 1077-1087. https://doi.org/10.3758/MC.37.8.1077 +- Nelson, T. O., & Dunlosky, J. (1991). When people's judgments of learning (JOLs) are extremely accurate at predicting subsequent recall: The "delayed-JOL effect." *Psychological Science*, 2(4), 267-271. https://doi.org/10.1111/j.1467-9280.1991.tb00147.x +- Pan, S. C., & Sana, F. (2021). Pretesting versus posttesting: Comparing the pedagogical benefits of errorful generation and retrieval practice. *Journal of Experimental Psychology: Applied*, 27(2), 237-257. https://doi.org/10.1037/xap0000345 +- Rawson, K. A., & Dunlosky, J. (2011). Optimizing schedules of retrieval practice for durable and efficient learning: How much is enough? *Journal of Experimental Psychology: General*, 140(3), 283-302. https://doi.org/10.1037/a0023956 +- Rawson, K. A., Dunlosky, J., & Sciartelli, S. M. (2013). The power of successive relearning: Improving performance on course exams and long-term retention. *Educational Psychology Review*, 25(4), 523-548. https://doi.org/10.1007/s10648-013-9240-4 +- Renkl, A., Atkinson, R. K., & Große, C. S. (2004). How fading worked solution steps works: A cognitive load perspective. *Instructional Science*, 32(1-2), 59-82. https://doi.org/10.1023/B:TRUC.0000021815.74806.f6 +- Renkl, A., Atkinson, R. K., Maier, U. H., & Staley, R. (2002). From example study to problem solving: Smooth transitions help learning. *The Journal of Experimental Education*, 70(4), 293-315. https://doi.org/10.1080/00220970209599510 +- Rey, G. D. (2012). A review of research and a meta-analysis of the seductive detail effect. *Educational Research Review*, 7(3), 216-237. https://doi.org/10.1016/j.edurev.2012.05.003 +- Richland, L. E., Kornell, N., & Kao, L. S. (2009). The pretesting effect: Do unsuccessful retrieval attempts enhance learning? *Journal of Experimental Psychology: Applied*, 15(3), 243-257. https://doi.org/10.1037/a0016496 +- Roediger, H. L., & Karpicke, J. D. (2006). Test-enhanced learning: Taking memory tests improves long-term retention. *Psychological Science*, 17(3), 249-255. https://doi.org/10.1111/j.1467-9280.2006.01693.x +- Roediger, H. L., & Marsh, E. J. (2005). The positive and negative consequences of multiple-choice testing. *Journal of Experimental Psychology: Learning, Memory, and Cognition*, 31(5), 1155-1159. https://doi.org/10.1037/0278-7393.31.5.1155 +- Rohrer, D., Dedrick, R. F., Hartwig, M. K., & Cheung, C.-N. (2020). A randomized controlled trial of interleaved mathematics practice. *Journal of Educational Psychology*, 112(1), 40-52. https://doi.org/10.1037/edu0000367 +- Rohrer, D., & Taylor, K. (2006). The effects of overlearning and distributed practise on the retention of mathematics knowledge. *Applied Cognitive Psychology*, 20(9), 1209-1224. https://doi.org/10.1002/acp.1266 +- Rohrer, D., & Taylor, K. (2007). The shuffling of mathematics problems improves learning. *Instructional Science*, 35(6), 481-498. https://doi.org/10.1007/s11251-007-9015-8 +- Shute, V. J. (2008). Focus on formative feedback. *Review of Educational Research*, 78(1), 153-189. https://doi.org/10.3102/0034654307313795 +- Sundararajan, N., & Adesope, O. (2020). Keep it coherent: A meta-analysis of the seductive details effect. *Educational Psychology Review*, 32(3), 707-734. https://doi.org/10.1007/s10648-020-09522-4 +- Sweller, J. (1988). Cognitive load during problem solving: Effects on learning. *Cognitive Science*, 12(2), 257-285. https://doi.org/10.1207/s15516709cog1202_4 +- Sweller, J., & Cooper, G. A. (1985). The use of worked examples as a substitute for problem solving in learning algebra. *Cognition and Instruction*, 2(1), 59-89. https://doi.org/10.1207/s1532690xci0201_3 +- Van der Kleij, F. M., Feskens, R. C. W., & Eggen, T. J. H. M. (2015). Effects of feedback in a computer-based learning environment on students' learning outcomes: A meta-analysis. *Review of Educational Research*, 85(4), 475-511. https://doi.org/10.3102/0034654314564881 + +### Further reading + +The text above does not cite these papers, but `scripts/seed-research.ts` +summarizes them for the plan generator's research context. + +- Agarwal, P. K., Nunes, L. D., & Blunt, J. R. (2021). Retrieval practice consistently benefits student learning: A systematic review of applied research in schools and classrooms. *Educational Psychology Review*, 33(4), 1409-1453. https://doi.org/10.1007/s10648-021-09595-9 +- Gollwitzer, P. M. (1999). Implementation intentions: Strong effects of simple plans. *American Psychologist*, 54(7), 493-503. https://doi.org/10.1037/0003-066X.54.7.493 +- Gollwitzer, P. M., & Brandstätter, V. (1997). Implementation intentions and effective goal pursuit. *Journal of Personality and Social Psychology*, 73(1), 186-199. https://doi.org/10.1037/0022-3514.73.1.186 +- Karpicke, J. D. (2025). Retrieval-based learning. In *Learning and memory: A comprehensive reference* (3rd ed., pp. 411-441). Elsevier. https://doi.org/10.1016/B978-0-443-15754-7.00074-2 +- Karpicke, J. D., & Blunt, J. R. (2011). Retrieval practice produces more learning than elaborative studying with concept mapping. *Science*, 331(6018), 772-775. https://doi.org/10.1126/science.1199327 +- Pan, S. C., & Rickard, T. C. (2018). Transfer of test-enhanced learning: Meta-analytic review and synthesis. *Psychological Bulletin*, 144(7), 710-756. https://doi.org/10.1037/bul0000151 +- Steel, P. (2007). The nature of procrastination: A meta-analytic and theoretical review of quintessential self-regulatory failure. *Psychological Bulletin*, 133(1), 65-94. https://doi.org/10.1037/0033-2909.133.1.65 +- Zimmerman, B. J. (2002). Becoming a self-regulated learner: An overview. *Theory Into Practice*, 41(2), 64-70. https://doi.org/10.1207/s15430421tip4102_2 diff --git a/docs/images/answer-loop.gif b/docs/images/answer-loop.gif new file mode 100644 index 00000000..ddc5f78a Binary files /dev/null and b/docs/images/answer-loop.gif differ diff --git a/docs/images/answer_loop.gif b/docs/images/answer_loop.gif deleted file mode 100644 index e2ac2342..00000000 Binary files a/docs/images/answer_loop.gif and /dev/null differ diff --git a/docs/images/cards-review-dark.png b/docs/images/cards-review-dark.png new file mode 100644 index 00000000..1d7371c8 Binary files /dev/null and b/docs/images/cards-review-dark.png differ diff --git a/docs/images/cards-review-light.png b/docs/images/cards-review-light.png new file mode 100644 index 00000000..8e3b2f8a Binary files /dev/null and b/docs/images/cards-review-light.png differ diff --git a/docs/images/chat-dark.png b/docs/images/chat-dark.png new file mode 100644 index 00000000..f46e3377 Binary files /dev/null and b/docs/images/chat-dark.png differ diff --git a/docs/images/chat-light.png b/docs/images/chat-light.png new file mode 100644 index 00000000..dd4999d8 Binary files /dev/null and b/docs/images/chat-light.png differ diff --git a/docs/images/end_screen.png b/docs/images/end_screen.png deleted file mode 100644 index 806acbe2..00000000 Binary files a/docs/images/end_screen.png and /dev/null differ diff --git a/docs/images/home-dark.png b/docs/images/home-dark.png new file mode 100644 index 00000000..59ada346 Binary files /dev/null and b/docs/images/home-dark.png differ diff --git a/docs/images/home-light.png b/docs/images/home-light.png new file mode 100644 index 00000000..12b2c4c5 Binary files /dev/null and b/docs/images/home-light.png differ diff --git a/docs/images/home-phone-dark.png b/docs/images/home-phone-dark.png new file mode 100644 index 00000000..7c24b50e Binary files /dev/null and b/docs/images/home-phone-dark.png differ diff --git a/docs/images/home-phone-light.png b/docs/images/home-phone-light.png new file mode 100644 index 00000000..825cf4ab Binary files /dev/null and b/docs/images/home-phone-light.png differ diff --git a/docs/images/home.png b/docs/images/home.png deleted file mode 100644 index 1b78e230..00000000 Binary files a/docs/images/home.png and /dev/null differ diff --git a/docs/images/model_answer.png b/docs/images/model_answer.png deleted file mode 100644 index 43d5be00..00000000 Binary files a/docs/images/model_answer.png and /dev/null differ diff --git a/docs/images/plan-dark.png b/docs/images/plan-dark.png new file mode 100644 index 00000000..196f8b27 Binary files /dev/null and b/docs/images/plan-dark.png differ diff --git a/docs/images/plan-light.png b/docs/images/plan-light.png new file mode 100644 index 00000000..a2af7739 Binary files /dev/null and b/docs/images/plan-light.png differ diff --git a/docs/images/plan.png b/docs/images/plan.png deleted file mode 100644 index b572b4de..00000000 Binary files a/docs/images/plan.png and /dev/null differ diff --git a/docs/images/preflight.png b/docs/images/preflight.png deleted file mode 100644 index 9b4b41fc..00000000 Binary files a/docs/images/preflight.png and /dev/null differ diff --git a/docs/images/progress-dark.png b/docs/images/progress-dark.png new file mode 100644 index 00000000..bdc4c0d0 Binary files /dev/null and b/docs/images/progress-dark.png differ diff --git a/docs/images/progress-light.png b/docs/images/progress-light.png new file mode 100644 index 00000000..b3aeae8f Binary files /dev/null and b/docs/images/progress-light.png differ diff --git a/docs/images/review_hypercorrection.png b/docs/images/review_hypercorrection.png deleted file mode 100644 index 1923ada4..00000000 Binary files a/docs/images/review_hypercorrection.png and /dev/null differ diff --git a/docs/images/runner_free_recall.png b/docs/images/runner_free_recall.png deleted file mode 100644 index 52dd2e30..00000000 Binary files a/docs/images/runner_free_recall.png and /dev/null differ diff --git a/docs/images/runner_mcq.png b/docs/images/runner_mcq.png deleted file mode 100644 index 3c5cf98f..00000000 Binary files a/docs/images/runner_mcq.png and /dev/null differ diff --git a/docs/images/session-end-dark.png b/docs/images/session-end-dark.png new file mode 100644 index 00000000..c381b71d Binary files /dev/null and b/docs/images/session-end-dark.png differ diff --git a/docs/images/session-end-light.png b/docs/images/session-end-light.png new file mode 100644 index 00000000..03957fb3 Binary files /dev/null and b/docs/images/session-end-light.png differ diff --git a/docs/images/session-feedback-dark.png b/docs/images/session-feedback-dark.png new file mode 100644 index 00000000..a176efda Binary files /dev/null and b/docs/images/session-feedback-dark.png differ diff --git a/docs/images/session-feedback-light.png b/docs/images/session-feedback-light.png new file mode 100644 index 00000000..ea352217 Binary files /dev/null and b/docs/images/session-feedback-light.png differ diff --git a/docs/images/session-feedback-phone-dark.png b/docs/images/session-feedback-phone-dark.png new file mode 100644 index 00000000..c53d805c Binary files /dev/null and b/docs/images/session-feedback-phone-dark.png differ diff --git a/docs/images/session-feedback-phone-light.png b/docs/images/session-feedback-phone-light.png new file mode 100644 index 00000000..0912908f Binary files /dev/null and b/docs/images/session-feedback-phone-light.png differ diff --git a/docs/images/session-mcq-feedback-dark.png b/docs/images/session-mcq-feedback-dark.png new file mode 100644 index 00000000..12d9724e Binary files /dev/null and b/docs/images/session-mcq-feedback-dark.png differ diff --git a/docs/images/session-mcq-feedback-light.png b/docs/images/session-mcq-feedback-light.png new file mode 100644 index 00000000..0b27de39 Binary files /dev/null and b/docs/images/session-mcq-feedback-light.png differ diff --git a/docs/images/session-mcq-selected-dark.png b/docs/images/session-mcq-selected-dark.png new file mode 100644 index 00000000..bfe43376 Binary files /dev/null and b/docs/images/session-mcq-selected-dark.png differ diff --git a/docs/images/session-mcq-selected-light.png b/docs/images/session-mcq-selected-light.png new file mode 100644 index 00000000..1744dfd5 Binary files /dev/null and b/docs/images/session-mcq-selected-light.png differ diff --git a/docs/images/session-question-dark.png b/docs/images/session-question-dark.png new file mode 100644 index 00000000..16f43fc7 Binary files /dev/null and b/docs/images/session-question-dark.png differ diff --git a/docs/images/session-question-light.png b/docs/images/session-question-light.png new file mode 100644 index 00000000..de890362 Binary files /dev/null and b/docs/images/session-question-light.png differ diff --git a/docs/images/session-scoring-dark.png b/docs/images/session-scoring-dark.png new file mode 100644 index 00000000..5bcea154 Binary files /dev/null and b/docs/images/session-scoring-dark.png differ diff --git a/docs/images/session-scoring-light.png b/docs/images/session-scoring-light.png new file mode 100644 index 00000000..44c98420 Binary files /dev/null and b/docs/images/session-scoring-light.png differ diff --git a/docs/images/session-start-dark.png b/docs/images/session-start-dark.png new file mode 100644 index 00000000..6d81ea96 Binary files /dev/null and b/docs/images/session-start-dark.png differ diff --git a/docs/images/session-start-light.png b/docs/images/session-start-light.png new file mode 100644 index 00000000..95d1e239 Binary files /dev/null and b/docs/images/session-start-light.png differ diff --git a/docs/images/settings-dark.png b/docs/images/settings-dark.png new file mode 100644 index 00000000..f796f39f Binary files /dev/null and b/docs/images/settings-dark.png differ diff --git a/docs/images/settings-light.png b/docs/images/settings-light.png new file mode 100644 index 00000000..9e963eff Binary files /dev/null and b/docs/images/settings-light.png differ diff --git a/docs/images/signin-dark.png b/docs/images/signin-dark.png new file mode 100644 index 00000000..de61140c Binary files /dev/null and b/docs/images/signin-dark.png differ diff --git a/docs/images/signin-light.png b/docs/images/signin-light.png new file mode 100644 index 00000000..f2482783 Binary files /dev/null and b/docs/images/signin-light.png differ diff --git a/docs/images/study-dark.png b/docs/images/study-dark.png new file mode 100644 index 00000000..e5c6a990 Binary files /dev/null and b/docs/images/study-dark.png differ diff --git a/docs/images/study-light.png b/docs/images/study-light.png new file mode 100644 index 00000000..7f608584 Binary files /dev/null and b/docs/images/study-light.png differ diff --git a/e2e/README.md b/e2e/README.md new file mode 100644 index 00000000..353e696a --- /dev/null +++ b/e2e/README.md @@ -0,0 +1,74 @@ +# e2e tests + +Playwright tests against a running Study Bot. They use the offline providers (mock AI, fake Google Calendar, console email), and the test runner never reads `.env`. + +## Run them + +1. Start Postgres (`npm run db:up`) and make an e2e database. Its name must contain `e2e`, so the suite can't run against your development data. + + ```sh + docker exec study-bot-db-1 psql -U postgres -c "DROP DATABASE IF EXISTS studybot_e2e WITH (FORCE)" + docker exec study-bot-db-1 psql -U postgres -c "CREATE DATABASE studybot_e2e" + DATABASE_URL=postgresql://postgres:postgres@localhost:5433/studybot_e2e npx prisma migrate deploy + ``` + +2. Install the browser once: `npx playwright install chromium`. + +3. Pick a port that nothing else uses (`npm run dev` already has 3000) and run: + + ```sh + # Build, then test against `next start`, like CI + CI=true E2E_PORT=3300 DATABASE_URL=postgresql://postgres:postgres@localhost:5433/studybot_e2e npx playwright test + + # Or test against `next dev`. Next allows one dev server per folder, + # so stop any other `npm run dev` in this checkout first. + E2E_PORT=3300 DATABASE_URL=postgresql://postgres:postgres@localhost:5433/studybot_e2e npx playwright test + ``` + + The config starts the server with the right settings (`AI_PROVIDER=mock`, `GOOGLE_PROVIDER=fake`, `ALLOW_TEST_AUTH=true`, and the URLs for the port), listening on 127.0.0.1 only, and stops it afterwards. `next` still reads `.env` for anything the config doesn't set. + +### Against a server you started + +To run the suite many times without rebuilding, start `next start` yourself and set `E2E_REUSE_SERVER=1`. The suite then only checks that the server answers. Give the test runner the same `DATABASE_URL` as the server: a few tests write rows the API can't reach (see below) and skip without it. + +```sh +npm run build # once, with the env below +AI_PROVIDER=mock GOOGLE_PROVIDER=fake EMAIL_PROVIDER=console OPENAI_API_KEY=dummy \ +NEXTAUTH_SECRET=e2e-test-secret TOKEN_ENC_KEY=0000000000000000000000000000000000000000000000000000000000000000 \ +ALLOW_TEST_AUTH=true CI=true NEXTAUTH_URL=http://localhost:3300 BASE_URL=http://localhost:3300 \ +DATABASE_URL=postgresql://postgres:postgres@localhost:5433/studybot_e2e \ +npx next start -H 127.0.0.1 -p 3300 + +E2E_PORT=3300 E2E_REUSE_SERVER=1 DATABASE_URL=postgresql://postgres:postgres@localhost:5433/studybot_e2e npx playwright test +``` + +`CI=true` on the server is what lets a production build accept the test header. Leave it off the test runner here, which would otherwise switch to CI behaviour (2 workers, a retry, the GitHub reporter). `GOOGLE_PROVIDER=fake` shows the Google Calendar controls and answers every call in memory, so nothing reaches Google. Test auth also needs `NEXTAUTH_URL` on a loopback host, and `-H 127.0.0.1` keeps a server that trusts the test header off the network. + +Rate limits live in the server's memory. Each test sends its own made-up client address, so the per-address limits on sign-in and sign-up don't cross between tests; restarting the server resets them all. + +## Projects and tags + +| Project | What it runs | +| --- | --- | +| `setup` | `auth.setup.ts`: creates the e2e account through `POST /api/auth/signup` and signs in on `/auth/signin`. Saves the session to `e2e/.auth//user.json` (ignored by git) and keeps it while it still works. | +| `chromium` | Every spec on Desktop Chrome, signed in as the e2e account. | +| `mobile` | Tests tagged `@mobile`, on a Pixel 7 (Chromium), signed in the same way. | + +Tags: `@mobile` (also run on the phone layout), `@a11y` (runs axe with the WCAG 2.0, 2.1 and 2.2 A and AA rules). Filter with `--grep @a11y`, a project with `--project=chromium`, or one file by naming it. + +CI splits the suite into two shards (`--shard=1/2` and `--shard=2/2`), each with its own database and server. + +## Writing tests + +Import `test`, `expect` and every helper from `./fixtures`, never from `@playwright/test`. The comment at the top of `fixtures.ts` says which fixture to use when: + +- `page` and `request` are the shared e2e account. Give every test its own data, usually a `unique(...)` course name, so tests run in parallel. +- `testUser` and `testUserPage` are a fresh identity per test (through the `X-User-Id` test header), for screens that show the whole account and for tests that need their own AI rate limit. +- `account` is a real account of the test's own, for anything that changes or deletes an account, and for Chat. +- `seedSession` gives a session whose run holds a known deck (multiple choice, model answers), which the mock AI never writes. + +The helpers live in `support/`: `api.ts` (sessions, runs, plans, materials, guides, decks), `time.ts` (calendar days in the suite's zone), `page.ts` (`hydrated`, `openMenu`, `toasts`, `pick`, `settled`, `openWhen`), `lesson.ts` (the session screen's locators), `auth.ts` (sign-in and Settings) and `db.ts` (link tokens, seeded decks and chat history, written straight to the database; these tests need `DATABASE_URL` and skip without it). + +Locate by role and label, assert with web-first `expect`, and never sleep. Wait for a server-rendered control to hydrate (`hydrated(locator)`) before typing into it or clicking it right after a page load. Run axe with `expectNoAxeViolations(page, "the state")`, which waits for loading states and animations first. The fixtures fail a test on any console error; allow an expected one with `test.use({ allowConsoleErrors: [loggedStatus(404)] })`. + +Reports: the list reporter locally; in CI the GitHub reporter and an HTML report in `playwright-report/e2e-`. Traces (first retry), screenshots and videos (failures) go to `test-results/e2e-`. diff --git a/e2e/a11y-app.spec.ts b/e2e/a11y-app.spec.ts new file mode 100644 index 00000000..fab5a398 --- /dev/null +++ b/e2e/a11y-app.spec.ts @@ -0,0 +1,273 @@ +/** + * Accessibility of the filled screens: axe (WCAG 2.0, 2.1 and 2.2, A and + * AA) on Home, Plan, New plan, Materials, Study, Study guides and Progress + * with real data, in the light and the dark theme, on both projects, and + * with their dialogs open. Then keyboard use of the shell: the skip link, + * the navigation rail, and the bottom bar's More sheet on phones. + * + * Already covered elsewhere: every destination's empty state with axe in + * shell.spec.ts, and the session screens in session-runner.spec.ts. + */ +import type { Page } from "@playwright/test"; +import { + test, + expect, + answerRun, + createGuide, + createPlan, + createSession, + expectNoAxeViolations, + finishSession, + hydrated, + morningZone, + openWhen, + setItemStatus, + unique, + uploadMaterial, +} from "./fixtures"; + +const THEMES = ["light", "dark"] as const; +type Theme = (typeof THEMES)[number]; + +/** The app follows the system theme by default. */ +async function emulateTheme(page: Page, colorScheme: Theme) { + await page.emulateMedia({ colorScheme }); +} + +/** Check the theme took before axe looks. */ +async function expectTheme(page: Page, colorScheme: Theme) { + await expect + .poll(() => page.evaluate(() => document.documentElement.classList.contains("dark"))) + .toBe(colorScheme === "dark"); +} + +/** Opens `path` in the given theme. */ +async function openIn(page: Page, path: string, colorScheme: Theme) { + await emulateTheme(page, colorScheme); + await page.goto(path); + await expectTheme(page, colorScheme); +} + +test.describe("filled screens pass axe in both themes", () => { + test("Home", { tag: ["@a11y", "@mobile"] }, async ({ testUserPage: page, testUser }) => { + const course = unique("E2E A11y Home"); + await createPlan(testUser.api, { + course_name: course, + objectives: ["Recursion", "Linked lists", "Hash tables"], + time_zone: morningZone(), + all_day: true, + }); + const session = await createSession(testUser.api, { + course_name: course, + topic_scope: "Recursion", + objectives: [{ id: "recursion", title: "Recursion" }], + }); + // Two wrong answers marked Sure, then the rest correct and Unsure. + await answerRun(testUser.api, session.id, [ + { score: "INCORRECT", confidence: 5 }, + { score: "INCORRECT", confidence: 5 }, + { score: "CORRECT", confidence: 3 }, + ]); + + for (const theme of THEMES) { + await test.step(theme, async () => { + await openIn(page, "/", theme); + await expect(page.getByRole("button", { name: `Repair ${course} errors` })).toBeVisible(); + await expect(page.getByRole("region", { name: "Today" }).getByRole("link", { name: "Start session" })).toBeVisible(); + await expectNoAxeViolations(page, `Home (${theme})`); + }); + } + }); + + test("Plan, with the reschedule preview open", { tag: ["@a11y", "@mobile"] }, async ({ testUserPage: page, testUser }) => { + const course = unique("E2E A11y Plan"); + const plan = await createPlan(testUser.api, { course_name: course, objectives: ["Recursion", "Linked lists", "Hash tables"] }); + await setItemStatus(testUser.api, plan.id, plan.items[0].id, "DONE"); + await setItemStatus(testUser.api, plan.id, plan.items[1].id, "MISSED"); + await uploadMaterial(testUser.api, { course, text: "Linked lists: nodes that point to the next node." }); + + for (const theme of THEMES) { + await test.step(theme, async () => { + await openIn(page, `/plan?plan=${plan.id}`, theme); + await expect(page.getByRole("button", { name: /^Reschedule missed session: / })).toBeVisible(); + await expectNoAxeViolations(page, `Plan (${theme})`); + + await hydrated(page.getByRole("button", { name: "Reschedule sessions" })); + await page.getByRole("button", { name: "Reschedule sessions" }).click(); + const dialog = page.getByRole("dialog", { name: "Reschedule sessions" }); + await expect(dialog.getByRole("button", { name: "Move 1 session" })).toBeVisible(); + await expectNoAxeViolations(page, `the reschedule preview (${theme})`); + }); + } + }); + + test("New plan, with its field errors showing", { tag: ["@a11y", "@mobile"] }, async ({ testUserPage: page }) => { + for (const theme of THEMES) { + await test.step(theme, async () => { + await openIn(page, "/plan/new", theme); + await hydrated(page.getByRole("button", { name: "Create plan" })); + await page.getByRole("button", { name: "Create plan" }).click(); + await expect(page.getByRole("alert").filter({ hasText: "Check the highlighted fields." })).toBeVisible(); + await expectNoAxeViolations(page, `New plan with field errors (${theme})`); + }); + } + }); + + test("Materials, with the delete confirmation open", { tag: ["@a11y", "@mobile"] }, async ({ + testUserPage: page, + testUser, + }) => { + const course = unique("E2E A11y Files"); + await uploadMaterial(testUser.api, { course, text: "Hash tables: keys map to buckets." }); + await uploadMaterial(testUser.api, { course, fileName: "raw.md", text: "Heaps.", process: false }); + + for (const theme of THEMES) { + await test.step(theme, async () => { + await openIn(page, "/plan/materials", theme); + await hydrated(page.getByRole("button", { name: "Summary of notes.txt" })); + await page.getByRole("button", { name: "Summary of notes.txt" }).click(); + await expect(page.getByText("No summary for this file.", { exact: false })).toBeVisible(); + await expectNoAxeViolations(page, `Materials with a summary open (${theme})`); + + await page.getByRole("button", { name: "Delete notes.txt" }).click(); + await expect(page.getByRole("alertdialog", { name: "Delete notes.txt?" })).toBeVisible(); + await expectNoAxeViolations(page, `the Delete file dialog (${theme})`); + }); + } + }); + + test("Study", { tag: ["@a11y", "@mobile"] }, async ({ testUserPage: page, testUser }) => { + const course = unique("E2E A11y Study"); + await uploadMaterial(testUser.api, { course, text: "Sorting: merge sort splits, sorts and merges." }); + const session = await createSession(testUser.api, { course_name: course }); + await finishSession(testUser.api, session.id, { incorrect: 3 }); + + for (const theme of THEMES) { + await test.step(theme, async () => { + await openIn(page, "/learn", theme); + await expect(page.getByRole("heading", { level: 2, name: "Error repair" })).toBeVisible(); + await expect(page.getByRole("region", { name: "Course tools" }).getByRole("link", { name: /^Materials/ })).toContainText( + "1 file ready", + ); + await expectNoAxeViolations(page, `Study (${theme})`); + }); + } + }); + + test("Study guides, with the delete confirmation open", { tag: ["@a11y", "@mobile"] }, async ({ + testUserPage: page, + testUser, + }) => { + const course = unique("E2E A11y Guides"); + await uploadMaterial(testUser.api, { course, text: "Graphs: vertices joined by edges." }); + await createGuide(testUser.api, course); + + for (const theme of THEMES) { + await test.step(theme, async () => { + await openIn(page, "/guides", theme); + await expect(page.getByRole("article", { name: `Key concepts for ${course}` })).toBeVisible(); + await expectNoAxeViolations(page, `Study guides (${theme})`); + + await page.getByRole("button", { name: "Delete guide" }).click(); + await expect(page.getByRole("alertdialog", { name: `Delete Key concepts for ${course}?` })).toBeVisible(); + await expectNoAxeViolations(page, `the Delete guide dialog (${theme})`); + }); + } + }); + + test("Progress", { tag: ["@a11y", "@mobile"] }, async ({ testUserPage: page, testUser }) => { + const course = unique("E2E A11y Progress"); + await createPlan(testUser.api, { course_name: course, objectives: ["Recursion", "Linked lists", "Hash tables"] }); + const session = await createSession(testUser.api, { + course_name: course, + topic_scope: "Recursion", + objectives: [{ id: "recursion", title: "Recursion" }], + }); + // One wrong answer marked Sure, then the rest correct and Unsure. + await answerRun(testUser.api, session.id, [ + { score: "INCORRECT", confidence: 5 }, + { score: "CORRECT", confidence: 3 }, + ]); + + for (const theme of THEMES) { + await test.step(theme, async () => { + // Mastery and XP are written just after the run completes. + await emulateTheme(page, theme); + await openWhen(page, "/achievements", page.getByRole("meter", { name: "Recursion mastery" })); + await expectTheme(page, theme); + await expect(page.getByRole("region", { name: "Confidence" }).getByRole("table")).toBeVisible(); + await hydrated(page.getByRole("button", { name: "Show study days as a list" })); + await page.getByRole("button", { name: "Show study days as a list" }).click(); + await expect(page.getByRole("button", { name: "Hide the list" })).toBeVisible(); + await expectNoAxeViolations(page, `Progress (${theme})`); + }); + } + }); +}); + +test.describe("keyboard use of the shell", () => { + test("the skip link is the first stop and moves focus to the page", { tag: ["@a11y", "@mobile"] }, async ({ + testUserPage: page, + }) => { + await page.goto("/"); + await page.keyboard.press("Tab"); + const skip = page.getByRole("link", { name: "Skip to main content" }); + await expect(skip).toBeFocused(); + await expect(skip).toBeInViewport(); + + await page.keyboard.press("Enter"); + await expect(page.getByRole("main")).toBeFocused(); + // The next stop is the page's own first control, past the navigation and the top app bar. + await page.keyboard.press("Tab"); + await expect(page.getByRole("main").getByRole("link", { name: "New plan" })).toBeFocused(); + }); + + // Untagged, so only the desktop project runs it: the rail shows from 600px. + test("the navigation rail takes Tab in order and opens a destination with Enter", async ({ testUserPage: page }) => { + await page.goto("/"); + const rail = page.getByRole("navigation", { name: "Main" }); + await expect(rail.getByRole("link", { name: "Home", exact: true })).toHaveAttribute("aria-current", "page"); + + await page.keyboard.press("Tab"); + await expect(page.getByRole("link", { name: "Skip to main content" })).toBeFocused(); + for (const name of ["Home", "Plan", "Study", "Cards", "Guides", "Chat", "Progress", "Settings"]) { + await page.keyboard.press("Tab"); + await expect(rail.getByRole("link", { name, exact: true })).toBeFocused(); + } + + await page.keyboard.press("Shift+Tab"); + await expect(rail.getByRole("link", { name: "Progress", exact: true })).toBeFocused(); + await page.keyboard.press("Enter"); + await expect(page).toHaveURL(/\/achievements$/); + await expect(page.getByRole("heading", { level: 1 })).toHaveText("Progress"); + await expect(rail.getByRole("link", { name: "Progress", exact: true })).toHaveAttribute("aria-current", "page"); + }); + + test("the bottom bar's More sheet opens, closes and navigates from the keyboard", { tag: ["@a11y", "@mobile"] }, async ({ + testUserPage: page, + isMobile, + }) => { + test.skip(!isMobile, "The bottom bar shows under 600px"); + await page.goto("/"); + const bar = page.getByRole("navigation", { name: "Main" }); + await expect(bar.getByRole("link")).toHaveText(["Home", "Plan", "Study", "Cards"]); + + const more = bar.getByRole("button", { name: "More" }); + const sheet = page.getByRole("dialog", { name: "More" }); + await hydrated(more); + await more.press("Enter"); + await expect(sheet.getByRole("link")).toHaveText(["Guides", "Chat", "Progress", "Settings"]); + await expectNoAxeViolations(page, "the More sheet"); + + await page.keyboard.press("Escape"); + await expect(sheet).toBeHidden(); + await expect(more).toBeFocused(); + + await more.press("Enter"); + await sheet.getByRole("link", { name: "Progress" }).press("Enter"); + await expect(page).toHaveURL(/\/achievements$/); + await expect(sheet).toBeHidden(); + await expect(page.getByRole("heading", { level: 1 })).toHaveText("Progress"); + await expect(more).toHaveAttribute("aria-current", "page"); + }); +}); diff --git a/e2e/a11y-auth-settings.spec.ts b/e2e/a11y-auth-settings.spec.ts new file mode 100644 index 00000000..78194137 --- /dev/null +++ b/e2e/a11y-auth-settings.spec.ts @@ -0,0 +1,204 @@ +/** + * Accessibility of the auth screens and Settings. axe (WCAG 2.0, 2.1 and + * 2.2 at A and AA) runs in the light and dark themes, on desktop and on the + * phone layout, over each screen's main states: empty, with field errors, a + * link that doesn't work, a sent link, and the Delete account dialog. Then + * the keyboard paths axe can't check: signing in without a mouse, and focus + * going back to Delete account when its dialog closes with Escape. + */ +import type { Page } from "@playwright/test"; +import { + test, + expect, + NEEDS_DATABASE, + SIGNED_OUT, + expectNoAxeViolations, + hasDatabase, + insertToken, + newEmail, + openSettings, + openSignIn, +} from "./fixtures"; + +const SCHEMES = ["light", "dark"] as const; + +/** The theme follows the emulated system setting; check it took before axe looks. */ +async function expectScheme(page: Page, scheme: (typeof SCHEMES)[number]): Promise { + await expect(page.locator("html")).toHaveClass(new RegExp(`\\b${scheme}\\b`)); +} + +for (const scheme of SCHEMES) { + test.describe(`${scheme} theme`, () => { + test.use({ colorScheme: scheme }); + + test.describe("auth screens", () => { + test.use({ storageState: SIGNED_OUT }); + + for (const { path, heading } of [ + { path: "/auth/signin", heading: "Sign in" }, + { path: "/auth/signup", heading: "Create account" }, + { path: "/auth/forgot-password", heading: "Reset password" }, + { path: "/auth/reset-password?token=not-a-real-token", heading: "This reset link doesn't work" }, + { path: "/auth/verify-email?email=ada%40studybot.test", heading: "Verify your email" }, + { path: "/auth/verify-email?status=invalid", heading: "This verification link doesn't work" }, + ]) { + test(`${heading} (${path}) passes axe`, { tag: ["@a11y", "@mobile"] }, async ({ page }) => { + await page.goto(path); + await expect(page.getByRole("heading", { level: 1, name: heading })).toBeVisible(); + // WCAG 2.4.2: the title names this screen, a broken link included. + await expect(page).toHaveTitle(`${heading} · Study Bot`); + await expectScheme(page, scheme); + await expectNoAxeViolations(page, `${heading} (${scheme})`); + }); + } + + test("the forms with their errors and the sent screen pass axe", { tag: ["@a11y", "@mobile"] }, async ({ page }) => { + await test.step("Create account, every field in error", async () => { + await page.goto("/auth/signup"); + await expect(page.getByRole("textbox", { name: "Name" })).toBeFocused(); + await page.getByRole("button", { name: "Create account" }).click(); + await expect(page.getByRole("group", { name: "Fix 4 fields to continue" })).toBeFocused(); + await expectScheme(page, scheme); + await expectNoAxeViolations(page, "Create account with every field in error"); + }); + + await test.step("Sign in, both fields in error", async () => { + await openSignIn(page); + await page.getByRole("button", { name: "Sign in" }).click(); + await expect(page.getByRole("group", { name: "Fix 2 fields to continue" })).toBeFocused(); + await expectNoAxeViolations(page, "Sign in with both fields in error"); + }); + + await test.step("Reset password, then Check your email", async () => { + await page.goto("/auth/forgot-password"); + const email = page.getByRole("textbox", { name: "Email" }); + await expect(email).toBeFocused(); + await page.getByRole("button", { name: "Send reset link" }).click(); + await expect(email).toHaveAccessibleDescription("Enter your email address."); + await expectNoAxeViolations(page, "Reset password with its field in error"); + + // Reset links are limited per address (5 an hour), so each run asks for a new one. + await email.fill(newEmail()); + await page.getByRole("button", { name: "Send reset link" }).click(); + await expect(page.getByRole("heading", { level: 1, name: "Check your email" })).toBeFocused(); + await expectNoAxeViolations(page, "Check your email"); + }); + }); + + test("Choose a new password, from a working reset link, passes axe", { tag: ["@a11y", "@mobile"] }, async ({ page, account }) => { + test.skip(!hasDatabase, NEEDS_DATABASE); + const token = await insertToken(account.email, "PASSWORD_RESET"); + await page.goto(`/auth/reset-password?token=${token}`); + await expect(page.getByRole("heading", { level: 1, name: "Choose a new password" })).toBeVisible(); + await expect(page.getByRole("textbox", { name: "New password", exact: true })).toBeFocused(); + await expectScheme(page, scheme); + await expectNoAxeViolations(page, "Choose a new password"); + }); + }); + + test.describe("Settings", () => { + test("Settings passes axe", { tag: ["@a11y", "@mobile"] }, async ({ account }) => { + const page = account.page; + await openSettings(page); + await expectScheme(page, scheme); + await expectNoAxeViolations(page, "Settings"); + }); + + test("Settings with a field error and a Google Calendar banner passes axe", { tag: ["@a11y", "@mobile"] }, async ({ account }) => { + const page = account.page; + await openSettings(page, "/settings?google=error&reason=access_denied"); + await expect(page.getByRole("alert").filter({ hasText: "Google Calendar not connected" })).toBeVisible(); + await page.getByRole("textbox", { name: "Daily end time" }).fill("08:00"); + await page.getByRole("button", { name: "Save settings" }).click(); + await expect(page.getByRole("textbox", { name: "Daily end time" })).toHaveAccessibleDescription( + "Choose an end time after the start time.", + ); + await expectScheme(page, scheme); + await expectNoAxeViolations(page, "Settings with a field error and a banner"); + }); + + test("the Delete account dialog passes axe", { tag: ["@a11y", "@mobile"] }, async ({ account }) => { + const page = account.page; + await openSettings(page, "/settings#account"); + await page.getByRole("button", { name: "Delete account" }).click(); + const dialog = page.getByRole("alertdialog", { name: "Delete your account?" }); + await expect(dialog.getByLabel("Enter your password to confirm")).toBeFocused(); + await expectScheme(page, scheme); + await expectNoAxeViolations(page, "the Delete account dialog"); + }); + }); + }); +} + +test.describe("keyboard", () => { + test.describe(() => { + test.use({ storageState: SIGNED_OUT }); + + test("a student can sign in with the keyboard alone", { tag: "@a11y" }, async ({ page, account }) => { + await openSignIn(page); + const password = page.getByLabel("Password", { exact: true }); + + await page.keyboard.type(account.email); + await page.keyboard.press("Tab"); + await expect(password).toBeFocused(); + await page.keyboard.type(account.password); + + await page.keyboard.press("Tab"); + const show = page.getByRole("checkbox", { name: "Show password" }); + await expect(show).toBeFocused(); + await page.keyboard.press("Space"); + await expect(show).toBeChecked(); + await expect(password).toHaveAttribute("type", "text"); + + await page.keyboard.press("Tab"); + await expect(page.getByRole("link", { name: "Forgot password?" })).toBeFocused(); + await page.keyboard.press("Tab"); + await expect(page.getByRole("link", { name: "Create account" })).toBeFocused(); + await page.keyboard.press("Tab"); + await expect(page.getByRole("button", { name: "Sign in" })).toBeFocused(); + await page.keyboard.press("Enter"); + + await expect(page).toHaveURL("/"); + await expect(page.getByRole("heading", { level: 1, name: "Home" })).toBeVisible(); + }); + }); + + test("Escape closes the Delete account dialog and focus goes back to its button", { tag: "@a11y" }, async ({ account }) => { + const page = account.page; + await openSettings(page, "/settings#account"); + const trigger = page.getByRole("button", { name: "Delete account" }); + const dialog = page.getByRole("alertdialog", { name: "Delete your account?" }); + const password = dialog.getByLabel("Enter your password to confirm"); + + await trigger.focus(); + await page.keyboard.press("Enter"); + await expect(password).toBeFocused(); + await page.keyboard.type("half-typed"); + + await test.step("Tab stays inside the dialog", async () => { + // Delete account is disabled until a password is typed, so with one + // typed the order is the field, the reset link in its hint, Cancel, + // Delete account, then the field. + await page.keyboard.press("Tab"); + await expect(dialog.getByRole("link", { name: "Reset your password" })).toBeFocused(); + await page.keyboard.press("Tab"); + await expect(dialog.getByRole("button", { name: "Cancel" })).toBeFocused(); + await page.keyboard.press("Tab"); + await expect(dialog.getByRole("button", { name: "Delete account" })).toBeFocused(); + await page.keyboard.press("Tab"); + await expect(password).toBeFocused(); + }); + + await page.keyboard.press("Escape"); + await expect(dialog).toBeHidden(); + await expect(trigger).toBeFocused(); + + await test.step("reopened, the dialog starts empty", async () => { + await page.keyboard.press("Enter"); + await expect(password).toBeFocused(); + await expect(password).toHaveValue(""); + await page.keyboard.press("Escape"); + await expect(trigger).toBeFocused(); + }); + }); +}); diff --git a/e2e/a11y-lesson.spec.ts b/e2e/a11y-lesson.spec.ts new file mode 100644 index 00000000..476e98e6 --- /dev/null +++ b/e2e/a11y-lesson.spec.ts @@ -0,0 +1,233 @@ +/** + * Axe (WCAG 2.0 to 2.2, A and AA) on the lesson, card and chat screens in + * each state a student sees, in the light and the dark theme, on desktop + * and on a phone: the session intro, a written question, its scoring, the + * feedback sheet, the results; a multiple-choice question and its + * feedback after a wrong pick; a deck page, the card review (front, + * answer, completion); and Chat, empty and answered. It also checks that + * popovers and dialogs give focus back to their button when Escape + * closes them. + * + * session-runner.spec.ts runs axe on the intro, a question, the error log + * and the results in the light theme on desktop; shell.spec.ts on every + * destination's empty state. + * + * Multiple-choice questions come from a seeded deck (the `seedSession` + * fixture), because the mock AI never writes a deck; that test needs + * DATABASE_URL and skips without it (see support/db.ts). + */ +import { + test, + expect, + QUESTIONS, + answerBox, + confidenceRadio, + createDeck, + createSession, + expectNoAxeViolations, + feedbackSheet, + pick, + scoreAs, + unique, + uploadMaterial, +} from "./fixtures"; + +const { overflow: OVERFLOW, recursiveCase: RECURSIVE_CASE } = QUESTIONS; + +const NOTES = [ + "Recursion: a function that calls itself on a smaller input.", + "A base case stops the recursion before the call stack overflows.", + "Each recursive call gets its own frame on the call stack.", +].join("\n\n"); + +for (const theme of ["light", "dark"] as const) { + test.describe(`${theme} theme`, () => { + test.use({ colorScheme: theme }); + + test("the intro, a written question, its scoring, the feedback sheet and the results pass axe", { tag: ["@a11y", "@mobile"] }, async ({ + page, + request, + }) => { + test.slow(); + const session = await createSession(request, { course_name: unique("E2E A11y"), questions: 2, target_accuracy: 0.8 }); + await page.goto(session.url); + // The app follows the system theme, which test.use() sets. + if (theme === "dark") await expect(page.locator("html")).toHaveClass(/\bdark\b/); + else await expect(page.locator("html")).not.toHaveClass(/\bdark\b/); + await expect(page.getByRole("button", { name: "Start session" })).toBeVisible(); + await expectNoAxeViolations(page, "the intro"); + + await page.getByRole("button", { name: "Start session" }).click(); + await expect(answerBox(page)).toBeVisible(); + await expectNoAxeViolations(page, "a written question"); + + for (const n of [1, 2]) { + await answerBox(page).fill(`Answer ${n} from memory`); + await pick(confidenceRadio(page, "Unsure")); + await page.getByRole("button", { name: "Submit answer" }).click(); + await expect(page.getByRole("group", { name: "Score your answer" })).toBeVisible(); + if (n === 1) await expectNoAxeViolations(page, "scoring a written answer"); + await scoreAs(page, "Correct"); + const sheet = feedbackSheet(page, "Correct"); + await expect(sheet).toBeVisible(); + if (n === 1) { + await expectNoAxeViolations(page, "the Correct feedback sheet"); + await sheet.getByRole("button", { name: "Next question" }).click(); + } else { + await sheet.getByRole("button", { name: "See results" }).click(); + } + } + + await expect(page.getByRole("heading", { level: 1, name: "Session complete" })).toBeVisible(); + await expect(page).toHaveTitle(`Session complete · ${session.course} · Study Bot`); + // Finishing refreshes the page's server data in the background (router.refresh), and + // the is swapped when that lands, so axe could catch the page between titles. + // The results the page serves from then on are the same screen. + await page.reload(); + await expect(page.getByRole("region", { name: "Follow-up sessions" })).toBeVisible(); + await expectNoAxeViolations(page, "the results"); + }); + + test("a multiple-choice question, its feedback after a wrong pick, and a model answer pass axe", { tag: ["@a11y", "@mobile"] }, async ({ + page, + seedSession, + }) => { + const session = await seedSession({ course_name: unique("E2E A11y"), deck: [OVERFLOW, RECURSIVE_CASE] }); + await page.goto(session.url); + await page.getByRole("button", { name: "Resume session" }).click(); + const options = page.getByRole("group", { name: OVERFLOW.text }); + await expect(options.getByRole("radio")).toHaveCount(4); + await expectNoAxeViolations(page, "a multiple-choice question"); + + await pick(options.getByRole("radio", { name: "The function returned too early" })); + await pick(confidenceRadio(page, "Sure")); + await page.getByRole("button", { name: "Submit answer" }).click(); + const sheet = feedbackSheet(page, "Incorrect"); + await expect(sheet).toContainText("Correct answer: The base case is never reached"); + // Focus lands on the continue button, so it carries the correction with it. + await expect(sheet.getByRole("button", { name: "Next question" })).toHaveAccessibleDescription( + /Correct answer: The base case is never reached/ + ); + await expect(page.getByRole("region", { name: "Why your answer is tempting" })).toBeVisible(); + await expectNoAxeViolations(page, "the Incorrect feedback sheet"); + + await sheet.getByRole("button", { name: "Next question" }).click(); + await answerBox(page).fill("It calls itself on a smaller input"); + await page.getByRole("button", { name: "Submit answer" }).click(); + await expect(page.getByRole("region", { name: "Model answer" })).toContainText(RECURSIVE_CASE.modelAnswer); + await expectNoAxeViolations(page, "a model answer to score against"); + }); + + test("a deck page and the card review pass axe", { tag: ["@a11y", "@mobile"] }, async ({ testUser, testUserPage: page }) => { + const deck = await createDeck(testUser.api); + await page.goto(`/flashcards/${deck.id}`); + await expect(page.getByRole("heading", { level: 2, name: deck.title })).toBeVisible(); + await expect(page.getByRole("region", { name: "Cards", exact: true }).getByRole("listitem")).toHaveCount(3); + await expectNoAxeViolations(page, "the deck page"); + + await page.goto(`/flashcards/${deck.id}/review`); + const front = page.getByRole("heading", { level: 1 }); + await expect(front).toHaveText(deck.cards[0].front); + await expectNoAxeViolations(page, "a card's front"); + + for (const [i, card] of deck.cards.entries()) { + await expect(front).toHaveText(card.front); + await page.getByRole("button", { name: "Show answer" }).click(); + await expect(page.getByRole("region", { name: "Answer" })).toBeVisible(); + if (i === 0) await expectNoAxeViolations(page, "a card's answer and the ratings"); + await page.getByRole("group", { name: "How well did you know it?" }).getByRole("button", { name: /^Good\b/ }).click(); + } + await expect(page.getByRole("heading", { level: 1, name: "Deck reviewed" })).toBeVisible(); + await expectNoAxeViolations(page, "the completion screen"); + }); + + test("Chat passes axe, empty and with an answer", { tag: ["@a11y", "@mobile"] }, async ({ account }) => { + const { page, api } = account; + const course = unique("E2E Chat"); + await uploadMaterial(api, { course, fileName: "recursion.txt", text: NOTES }); + await page.goto("/chat"); + const box = page.getByRole("textbox", { name: `Ask about your ${course} materials` }); + await expect(page.getByRole("heading", { level: 2, name: `No questions about ${course} yet` })).toBeVisible(); + await expectNoAxeViolations(page, "an empty chat"); + + await box.fill("What is recursion?"); + await box.press("Enter"); + const answer = page.getByRole("article", { name: "Study Bot answered" }); + await expect(answer.getByRole("group", { name: "Sources (1)" })).toBeVisible(); + await answer.getByRole("button", { name: "Source 1: recursion.txt" }).click(); + await expectNoAxeViolations(page, "an answer with a source open"); + }); + }); +} + +test.describe("Escape gives focus back", () => { + test("the session's keyboard shortcuts close on Escape, back to their button", { tag: "@a11y" }, async ({ page, request }) => { + const session = await createSession(request, { course_name: unique("E2E A11y") }); + await page.goto(session.url); + await page.getByRole("button", { name: "Start session" }).click(); + await expect(page.getByRole("textbox", { name: "Your answer" })).toBeFocused(); + + const help = page.getByRole("button", { name: "Keyboard shortcuts" }); + await help.click(); + const popover = page.getByRole("dialog", { name: "Keyboard shortcuts" }); + await expect(popover).toBeVisible(); + await expectNoAxeViolations(page, "the keyboard shortcuts popover"); + await page.keyboard.press("Escape"); + await expect(popover).toBeHidden(); + await expect(help).toBeFocused(); + }); + + test("the deck page's dialogs close on Escape, back to what opened them", { tag: "@a11y" }, async ({ testUser, testUserPage: page }) => { + const deck = await createDeck(testUser.api); + await page.goto(`/flashcards/${deck.id}`); + await expect(page.getByRole("region", { name: "Cards", exact: true }).getByRole("listitem")).toHaveCount(3); + + await test.step("Add cards", async () => { + const add = page.getByRole("main").getByRole("button", { name: "Add cards" }); + await add.click(); + const dialog = page.getByRole("dialog", { name: "Add cards" }); + await expect(dialog).toBeVisible(); + await expectNoAxeViolations(page, "the Add cards dialog"); + await page.keyboard.press("Escape"); + await expect(dialog).toBeHidden(); + await expect(add).toBeFocused(); + }); + + await test.step("Delete card", async () => { + const remove = page.getByRole("button", { name: "Delete card 1" }); + await remove.click(); + const dialog = page.getByRole("alertdialog", { name: "Delete this card?" }); + await expect(dialog).toContainText("This deletes the card and its review history."); + await expectNoAxeViolations(page, "the Delete card dialog"); + await page.keyboard.press("Escape"); + await expect(dialog).toBeHidden(); + await expect(remove).toBeFocused(); + await expect(page.getByRole("region", { name: "Cards", exact: true }).getByRole("listitem")).toHaveCount(3); + }); + + await test.step("Delete deck, from the actions menu", async () => { + const more = page.getByRole("button", { name: `More actions for ${deck.title}` }); + await more.click(); + await page.getByRole("menuitem", { name: "Delete deck" }).click(); + const dialog = page.getByRole("alertdialog", { name: `Delete ${deck.title}?` }); + await expect(dialog).toContainText("This deletes the deck and its 3 cards, with their review history."); + await page.keyboard.press("Escape"); + await expect(dialog).toBeHidden(); + await expect(more).toBeFocused(); + }); + }); + + test("the card review's keyboard shortcuts close on Escape, back to their button", { tag: "@a11y" }, async ({ testUser, testUserPage: page }) => { + const deck = await createDeck(testUser.api); + await page.goto(`/flashcards/${deck.id}/review`); + await expect(page.getByRole("heading", { level: 1 })).toBeFocused(); + const help = page.getByRole("button", { name: "Keyboard shortcuts" }); + await help.click(); + const popover = page.getByRole("dialog", { name: "Keyboard shortcuts" }); + await expect(popover).toBeVisible(); + await expectNoAxeViolations(page, "the review's keyboard shortcuts popover"); + await page.keyboard.press("Escape"); + await expect(popover).toBeHidden(); + await expect(help).toBeFocused(); + }); +}); diff --git a/e2e/access-control.spec.ts b/e2e/access-control.spec.ts new file mode 100644 index 00000000..4b04e4b1 --- /dev/null +++ b/e2e/access-control.spec.ts @@ -0,0 +1,131 @@ +/** + * Who can see what, through the proxy and the route handlers: signed-out + * visitors, revoked sessions, another student's data, unknown ids and + * cross-site writes. + * The services' own ownership checks are covered by the integration tests; + * these check the HTTP answers and the pages a browser lands on. + */ +import { test, expect, createPlan, createSession, startRun, unique, SIGNED_OUT } from "./fixtures"; + +test.describe("signed out", () => { + test.use({ storageState: SIGNED_OUT }); + + test("a page sends the visitor to sign in and keeps the address", async ({ page }) => { + await page.goto("/plan?plan=abc"); + await expect(page).toHaveURL("/auth/signin?callbackUrl=%2Fplan%3Fplan%3Dabc"); + await expect(page.getByRole("heading", { level: 1, name: "Sign in" })).toBeVisible(); + }); + + test("the API answers 401 with a code", async ({ request }) => { + for (const [method, url] of [ + ["GET", "/api/plans"], + ["POST", "/api/sessions"], + ["GET", "/api/stats/game"], + ] as const) { + const response = await request.fetch(url, { method, data: method === "POST" ? {} : undefined }); + expect(response.status(), `${method} ${url}`).toBe(401); + expect(await response.json()).toMatchObject({ code: "UNAUTHORIZED" }); + } + }); + + test("the test header is ignored when it is empty", async ({ request }) => { + const response = await request.get("/api/plans", { headers: { "X-User-Id": "" } }); + expect(response.status()).toBe(401); + }); +}); + +test.describe("another student's data", () => { + // The owner is a fresh test identity; the intruder is the signed-in e2e account. + + test.describe(() => { + // Chromium logs the 404 document response as a console error. + test.use({ allowConsoleErrors: [/the server responded with a status of 404/] }); + + test("their session page is not found", async ({ page, testUser }) => { + const session = await createSession(testUser.api, { course_name: unique("E2E Private") }); + + const response = await page.goto(session.url); + expect(response?.status()).toBe(404); + await expect(page.getByRole("heading", { name: "Session not found" })).toBeVisible(); + await expect(page.getByRole("link", { name: "Go to Home" })).toBeVisible(); + + // The owner still opens it. + const owner = await testUser.api.get(session.url); + expect(owner.status()).toBe(200); + }); + }); + + test("their run and its attempts answer 403", async ({ request, testUser }) => { + const session = await createSession(testUser.api, { course_name: unique("E2E Private") }); + const run = await startRun(testUser.api, session.id); + + expect((await request.get(`/api/runs/${run.run_id}`)).status()).toBe(403); + const attempt = await request.post(`/api/runs/${run.run_id}/attempt`, { + data: { prompt_index: 0, user_answer: "Not mine", self_score: "CORRECT" }, + }); + expect(attempt.status()).toBe(403); + }); + + test("their plan and its calendar file answer 403", async ({ request, testUser }) => { + const plan = await createPlan(testUser.api, { course_name: unique("E2E Private plan") }); + + expect((await request.get(`/api/plans/${plan.id}`)).status()).toBe(403); + expect((await request.get(`/api/plans/${plan.id}/ics`)).status()).toBe(403); + expect((await testUser.api.get(`/api/plans/${plan.id}`)).status()).toBe(200); + }); +}); + +test("unknown ids answer 404", async ({ request }) => { + for (const url of ["/api/sessions/nonexistent_id", "/api/runs/nonexistent_run", "/api/plans/nonexistent_plan"]) { + expect((await request.get(url)).status(), url).toBe(404); + } +}); + +test("a write from another site answers 403", async ({ request }) => { + const response = await request.post("/api/sessions", { + headers: { Origin: "https://evil.example" }, + data: { course_name: "X", exam_name: "Y", mode: "RETRIEVAL", topic_scope: "Z", planned_minutes: 15 }, + }); + expect(response.status()).toBe(403); + expect(await response.json()).toMatchObject({ code: "CROSS_SITE_REQUEST" }); +}); + +test.describe("a revoked session", () => { + // The cookie still decodes, so the proxy lets it through and each route + // finds no user. That 401 must read the same as the proxy's own. + test("routes answer 401 with the proxy's body", async ({ playwright, baseURL, account }) => { + const storageState = await account.api.storageState(); + const deleted = await account.api.delete("/api/account/delete", { + data: { confirm: "DELETE MY ACCOUNT", password: account.password }, + }); + expect(deleted.ok(), await deleted.text()).toBe(true); + + const stale = await playwright.request.newContext({ baseURL, storageState }); + try { + for (const [method, url] of [ + ["GET", "/api/plans"], + ["POST", "/api/plans"], + ["GET", "/api/flashcards"], + ["GET", "/api/guides"], + ["GET", "/api/learn"], + ["GET", "/api/content/documents"], + ["GET", "/api/runs/no-such-run"], + ["GET", "/api/runs/no-such-run/prompt?index=0"], + ["GET", "/api/settings"], + ["GET", "/api/account/export"], + ["GET", "/api/integrations/google/status"], + ["GET", "/api/stats/game"], + ["GET", "/api/onboarding"], + ] as const) { + const response = await stale.fetch(url, { method, data: method === "POST" ? {} : undefined }); + expect(response.status(), `${method} ${url}`).toBe(401); + expect(await response.json(), `${method} ${url}`).toEqual({ + error: "Your sign-in expired. Sign in again.", + code: "UNAUTHORIZED", + }); + } + } finally { + await stale.dispose(); + } + }); +}); diff --git a/e2e/api-contract.spec.ts b/e2e/api-contract.spec.ts new file mode 100644 index 00000000..143ded3e --- /dev/null +++ b/e2e/api-contract.spec.ts @@ -0,0 +1,120 @@ +/** + * HTTP answers the screens rely on that the service-level integration tests + * can't see: status codes for out-of-order answers, request bounds, no answer + * key before an answer, and the calendar file's headers. API only, no + * browser page. + */ +import { + test, + expect, + QUESTIONS, + answerQuestion, + createPlan, + createSession, + getJson, + startRun, + unique, +} from "./fixtures"; + +/** Fields that would give the answer away, in either spelling the code uses. */ +const ANSWER_FIELDS = new Set([ + "correctIndex", + "correct_index", + "model_answer", + "modelAnswer", + "key_points", + "keyPoints", + "distractorRationales", + "distractor_rationales", + "excerpts", +]); + +/** Paths of every answer field anywhere in a JSON body. */ +function answerFields(value: unknown, path = "$"): string[] { + if (Array.isArray(value)) return value.flatMap((item, i) => answerFields(item, `${path}[${i}]`)); + if (!value || typeof value !== "object") return []; + return Object.entries(value).flatMap(([key, child]) => + ANSWER_FIELDS.has(key) && child != null ? [`${path}.${key}`] : answerFields(child, `${path}.${key}`) + ); +} + +test("answers out of order or after the end answer 409", async ({ testUser }) => { + const session = await createSession(testUser.api, { course_name: unique("E2E State"), questions: 2 }); + const run = await startRun(testUser.api, session.id); + + const skipAhead = await testUser.api.post(`/api/runs/${run.run_id}/attempt`, { + data: { prompt_index: 1, user_answer: "Out of order", self_score: "CORRECT" }, + }); + expect(skipAhead.status()).toBe(409); + + await answerQuestion(testUser.api, run.run_id, 0); + const last = await answerQuestion(testUser.api, run.run_id, 1); + expect(last.status).toBe("COMPLETED"); + + const afterEnd = await testUser.api.post(`/api/runs/${run.run_id}/attempt`, { + data: { prompt_index: 2, user_answer: "Too late", self_score: "CORRECT" }, + }); + expect(afterEnd.status()).toBe(409); +}); + +test("a question reaches the browser without its answer until it is answered", async ({ request, seedSession }) => { + const { overflow, recursiveCase } = QUESTIONS; + const session = await seedSession({ course_name: unique("E2E Answer key"), deck: [overflow, recursiveCase] }); + const secrets = [ + overflow.modelAnswer, + ...overflow.rationales, + ...overflow.keyPoints, + recursiveCase.modelAnswer, + ...recursiveCase.keyPoints, + ]; + + // Every way the browser reads a question before answering it: resuming + // the run, the run itself, and the question on its own. + const bodies = { + "start (resume)": await startRun(request, session.id), + run: await getJson<unknown>(request, `/api/runs/${session.runId}`), + prompt: await getJson<unknown>(request, `/api/runs/${session.runId}/prompt?index=0`), + }; + for (const [label, body] of Object.entries(bodies)) { + expect(answerFields(body), label).toEqual([]); + const text = JSON.stringify(body); + for (const secret of secrets) expect(text, `${label} leaks "${secret}"`).not.toContain(secret); + } + // The question itself is there. + expect(JSON.stringify(bodies.prompt)).toContain(overflow.text); +}); + +test("a session holds 1 to 60 questions", async ({ testUser }) => { + // The run builds the whole deck in memory, so an unbounded count could take + // the server down for everyone; 0 left a run with no first question. + const session = { + course_name: unique("E2E Bounds"), + exam_name: "Final exam", + mode: "RETRIEVAL", + topic_scope: "End-to-end testing", + planned_minutes: 30, + }; + for (const prompt_count of [0, -1, 2.5, 61, 50_000_000]) { + const response = await testUser.api.post("/api/sessions", { data: { ...session, target_outcome: { prompt_count } } }); + expect(response.status(), `prompt_count ${prompt_count}`).toBe(400); + expect(await response.json()).toMatchObject({ issues: [{ path: ["target_outcome", "prompt_count"] }] }); + } + + const atLimit = await testUser.api.post("/api/sessions", { data: { ...session, target_outcome: { prompt_count: 60 } } }); + expect(atLimit.status(), await atLimit.text()).toBe(201); +}); + +test("the plan's calendar file downloads as .ics with a link to every session", async ({ testUser }) => { + const plan = await createPlan(testUser.api, { course_name: unique("E2E Calendar") }); + + const response = await testUser.api.get(`/api/plans/${plan.id}/ics`); + expect(response.status()).toBe(200); + expect(response.headers()["content-type"]).toContain("text/calendar"); + expect(response.headers()["content-disposition"]).toMatch(/^attachment; filename=".+\.ics"$/); + + // Unfold the 75-octet lines so links can be matched whole. + const body = (await response.text()).replace(/\r\n[ \t]/g, ""); + expect(body).toMatch(/^BEGIN:VCALENDAR/); + expect(body.match(/BEGIN:VEVENT/g)).toHaveLength(plan.items.length); + for (const item of plan.items) expect(body).toContain(`/s/${item.session_id}`); +}); diff --git a/e2e/auth.setup.ts b/e2e/auth.setup.ts new file mode 100644 index 00000000..839e5d32 --- /dev/null +++ b/e2e/auth.setup.ts @@ -0,0 +1,48 @@ +/** + * Setup project: make sure the e2e account exists, sign in through the real + * /auth/signin page, and save the session for the chromium and mobile + * projects. + * + * Production builds limit sign-ups (3 an hour) and sign-ins (10 every 15 + * minutes) per network, in memory. So when the saved session still works + * against this server, it is kept, and repeated runs on a server you + * started yourself don't use those up. + */ +import fs from "node:fs"; +import path from "node:path"; +import { test as setup, expect, SIGNED_OUT } from "./fixtures"; +import { AUTH_FILE, E2E_USER } from "./support/env"; + +setup.use({ storageState: SIGNED_OUT }); + +setup("sign in as the e2e account", async ({ page, request, playwright, baseURL }) => { + if (fs.existsSync(AUTH_FILE)) { + // A recreated database or another NEXTAUTH_SECRET ends the saved session. + const saved = await playwright.request.newContext({ baseURL, storageState: AUTH_FILE }); + const session = await (await saved.get("/api/auth/session")).json().catch(() => null); + await saved.dispose(); + if (session?.user?.email === E2E_USER.email) return; + } + + await setup.step("create the account through the sign-up API", async () => { + // A taken email gets the same 201, so this is safe on a used database. + const response = await request.post("/api/auth/signup", { + data: { name: E2E_USER.name, email: E2E_USER.email, password: E2E_USER.password }, + }); + expect(response.status(), await response.text()).toBe(201); + }); + + await setup.step("sign in on /auth/signin", async () => { + await page.goto("/auth/signin"); + await expect(page.getByRole("heading", { level: 1, name: "Sign in" })).toBeVisible(); + await page.getByLabel("Email").fill(E2E_USER.email); + await page.getByLabel("Password", { exact: true }).fill(E2E_USER.password); + await page.getByRole("button", { name: "Sign in" }).click(); + await expect(page).toHaveURL("/"); + // The signed-in shell: Home's title in the top app bar. + await expect(page.getByRole("heading", { level: 1, name: "Home" })).toBeVisible(); + }); + + fs.mkdirSync(path.dirname(AUTH_FILE), { recursive: true }); + await page.context().storageState({ path: AUTH_FILE }); +}); diff --git a/e2e/auth.spec.ts b/e2e/auth.spec.ts new file mode 100644 index 00000000..62b1db79 --- /dev/null +++ b/e2e/auth.spec.ts @@ -0,0 +1,532 @@ +/** + * The auth screens as a student uses them: create account, sign in and its + * errors, where sign-in sends you, signing out, forgot and reset password, + * and email verification links. Every test has its own account (the + * `account` fixture or the form) and its own client address, so the + * per-address limits never cross between tests. + * + * Unit tests already cover the route rules and messages + * (auth-routes, auth-messages, auth-callback-url, auth-signin-limits and + * auth-credentials-sign-in); these check what reaches the screen. + * Tests that follow a reset or verification link need DATABASE_URL (see + * support/db.ts). + */ +import { + test, + expect, + DETAILS_DONT_MATCH, + NEEDS_DATABASE, + SIGNED_OUT, + emailVerifiedAt, + hasDatabase, + hydrated, + insertToken, + latestToken, + loggedStatus, + newEmail, + openMenu, + openSignIn, + signInWith, + takeOverToken, +} from "./fixtures"; + +const NEW_PASSWORD = "e2e-only-NewPassw0rd"; + +test.describe("signed out", () => { + test.use({ storageState: SIGNED_OUT }); + + test.describe("create account", () => { + test("each field's error shows beside it and in a summary at the top", { tag: "@mobile" }, async ({ page }) => { + await page.goto("/auth/signup"); + await expect(page).toHaveTitle("Create account · Study Bot"); + const name = page.getByRole("textbox", { name: "Name" }); + const email = page.getByRole("textbox", { name: "Email" }); + const password = page.getByRole("textbox", { name: "Password", exact: true }); + const confirm = page.getByRole("textbox", { name: "Confirm password" }); + await expect(name).toBeFocused(); + + await test.step("the password rule shows before anything is typed", async () => { + await expect(password).toHaveAccessibleDescription("Use at least 8 characters."); + }); + + await test.step("an empty form names all four fields", async () => { + await page.getByRole("button", { name: "Create account" }).click(); + const summary = page.getByRole("group", { name: "Fix 4 fields to continue" }); + await expect(summary).toBeFocused(); + await expect(summary.getByRole("link")).toHaveText([ + "Enter your name.", + "Enter your email address.", + "Enter a password.", + "Enter the password again.", + ]); + await expect(name).toHaveAccessibleDescription("Enter your name."); + await expect(email).toHaveAccessibleDescription("Enter your email address."); + await expect(password).toHaveAccessibleDescription("Enter a password."); + await expect(confirm).toHaveAccessibleDescription("Enter the password again."); + for (const field of [name, email, password, confirm]) { + await expect(field).toHaveAttribute("aria-invalid", "true"); + } + }); + + await test.step("a summary link moves focus to its field", async () => { + await page.getByRole("link", { name: "Enter a password." }).click(); + await expect(password).toBeFocused(); + }); + + await test.step("each rule has its own message, and a fixed field clears", async () => { + await name.fill("Ada"); + await expect(name).not.toHaveAttribute("aria-invalid"); + await email.fill("ada@"); + await password.fill("short"); + await confirm.fill("shorter"); + await page.getByRole("button", { name: "Create account" }).click(); + + await expect(page.getByRole("group", { name: "Fix 3 fields to continue" })).toBeFocused(); + await expect(email).toHaveAccessibleDescription("Enter an email address like name@example.com."); + await expect(password).toHaveAccessibleDescription("Use at least 8 characters."); + await expect(confirm).toHaveAccessibleDescription("Enter the same password in both fields."); + await expect(page).toHaveURL("/auth/signup"); + }); + + await test.step("a password past bcrypt's 72 bytes is refused, not cut short", async () => { + // 37 accented letters: under 40 characters, but 74 bytes. + const long = "\u00e9".repeat(37); + await password.fill(long); + await confirm.fill(long); + await page.getByRole("button", { name: "Create account" }).click(); + await expect(password).toHaveAccessibleDescription("Use a shorter password."); + await expect(page).toHaveURL("/auth/signup"); + }); + }); + + test("Show password reveals both passwords, and a pasted password is accepted", async ({ page, baseURL }) => { + const secret = "e2e-only-Pasted-Passw0rd"; + await page.context().grantPermissions(["clipboard-read", "clipboard-write"], { origin: baseURL }); + await page.goto("/auth/signup"); + await expect(page.getByRole("textbox", { name: "Name" })).toBeFocused(); + const password = page.getByRole("textbox", { name: "Password", exact: true }); + const confirm = page.getByRole("textbox", { name: "Confirm password" }); + + await test.step("paste into both password fields", async () => { + await page.evaluate((text) => navigator.clipboard.writeText(text), secret); + await password.click(); + await page.keyboard.press("ControlOrMeta+V"); + await confirm.click(); + await page.keyboard.press("ControlOrMeta+V"); + await expect(password).toHaveValue(secret); + await expect(confirm).toHaveValue(secret); + }); + + await test.step("one checkbox shows and hides both", async () => { + await expect(password).toHaveAttribute("type", "password"); + await expect(confirm).toHaveAttribute("type", "password"); + const show = page.getByRole("checkbox", { name: "Show password" }); + await show.check(); + await expect(password).toHaveAttribute("type", "text"); + await expect(confirm).toHaveAttribute("type", "text"); + await show.uncheck(); + await expect(password).toHaveAttribute("type", "password"); + await expect(confirm).toHaveAttribute("type", "password"); + }); + }); + + test("a new account is signed in and lands on the page that asked for sign-in", { tag: "@mobile" }, async ({ page }) => { + const email = newEmail(); + await page.goto("/plan/new"); + await expect(page).toHaveURL("/auth/signin?callbackUrl=%2Fplan%2Fnew"); + + await page.getByRole("link", { name: "Create account" }).click(); + await expect(page).toHaveURL("/auth/signup?callbackUrl=%2Fplan%2Fnew"); + await expect(page.getByRole("textbox", { name: "Name" })).toBeFocused(); + await page.getByRole("textbox", { name: "Name" }).fill("Ada Lovelace"); + await page.getByRole("textbox", { name: "Email" }).fill(email); + await page.getByRole("textbox", { name: "Password", exact: true }).fill(NEW_PASSWORD); + await page.getByRole("textbox", { name: "Confirm password" }).fill(NEW_PASSWORD); + await page.getByRole("button", { name: "Create account" }).click(); + + await expect(page).toHaveURL("/plan/new"); + await expect(page.getByRole("heading", { level: 1, name: "New plan" })).toBeVisible(); + + const menu = await openMenu(page, "Open account menu"); + await expect(menu).toContainText("Ada Lovelace"); + await expect(menu).toContainText(email); + }); + + test.describe(() => { + // Signing in with the new password answers 401. + test.use({ allowConsoleErrors: [loggedStatus(401)] }); + + test("an email that already has an account gets a way to sign in, not a second account", async ({ page, account }) => { + await page.goto("/auth/signup"); + await expect(page.getByRole("textbox", { name: "Name" })).toBeFocused(); + await page.getByRole("textbox", { name: "Name" }).fill("Someone Else"); + await page.getByRole("textbox", { name: "Email" }).fill(account.email); + await page.getByRole("textbox", { name: "Password", exact: true }).fill(NEW_PASSWORD); + await page.getByRole("textbox", { name: "Confirm password" }).fill(NEW_PASSWORD); + await page.getByRole("button", { name: "Create account" }).click(); + + const summary = page.getByRole("group", { + name: "This email already has an account. Sign in with its password, or reset the password.", + }); + await expect(summary).toBeFocused(); + await expect(summary.getByRole("link", { name: "Sign in" })).toHaveAttribute("href", "/auth/signin"); + await expect(page).toHaveURL("/auth/signup"); + + // The existing account and its session are untouched. + expect((await account.api.get("/api/settings")).status()).toBe(200); + }); + }); + }); + + test.describe("sign in", () => { + // Wrong passwords answer 401 and the rate limit 429, on purpose. + test.use({ allowConsoleErrors: [loggedStatus(401, 429)] }); + + test("empty fields and a wrong password are explained, then the right one signs in", { tag: "@mobile" }, async ({ page, account }) => { + // Each password check takes the server about 2 s (bcrypt at cost 12), and this test makes several. + test.slow(); + await openSignIn(page); + await expect(page).toHaveTitle("Sign in · Study Bot"); + const email = page.getByRole("textbox", { name: "Email" }); + const password = page.getByLabel("Password", { exact: true }); + + await test.step("empty fields", async () => { + await page.getByRole("button", { name: "Sign in" }).click(); + await expect(page.getByRole("group", { name: "Fix 2 fields to continue" })).toBeFocused(); + await expect(email).toHaveAccessibleDescription("Enter your email address."); + await expect(password).toHaveAccessibleDescription("Enter your password."); + }); + + await test.step("a wrong password", async () => { + await signInWith(page, account.email, "not-the-password"); + await expect(page.getByRole("group", { name: DETAILS_DONT_MATCH })).toBeFocused(); + await expect(page.getByRole("button", { name: "Sign in" })).toBeEnabled(); + await expect(page).toHaveURL("/auth/signin"); + }); + + await test.step("the right password", async () => { + await password.fill(account.password); + await page.getByRole("button", { name: "Sign in" }).click(); + await expect(page).toHaveURL("/"); + await expect(page.getByRole("heading", { level: 1, name: "Home" })).toBeVisible(); + }); + }); + + test("too many attempts from one network say when to retry", async ({ page, account, playwright, baseURL, clientAddress }) => { + // Each network gets 10 sign-in attempts every 15 minutes. Use them up + // from this test's address with posts that carry no CSRF token: the + // limit counts them, and next-auth turns them away before it checks a + // password, so they don't load the server with password hashing. + const api = await playwright.request.newContext({ + baseURL, + storageState: SIGNED_OUT, + extraHTTPHeaders: { "X-Forwarded-For": clientAddress }, + }); + for (let attempt = 1; attempt <= 10; attempt++) { + const response = await api.post("/api/auth/callback/credentials", { + form: { email: account.email, password: `wrong-${attempt}`, json: "true" }, + }); + expect(response.status(), `attempt ${attempt}`).not.toBe(429); + } + await api.dispose(); + + await openSignIn(page); + await signInWith(page, account.email, account.password); + await expect(page.getByRole("group", { name: /^Too many sign-in attempts\. Retry in \d+ minutes?\.$/ })).toBeFocused(); + await expect(page.getByRole("button", { name: "Sign in" })).toBeEnabled(); + await expect(page).toHaveURL("/auth/signin"); + // The right password was never checked, so the session didn't start. + expect((await (await page.request.get("/api/auth/session")).json())?.user).toBeUndefined(); + }); + + test("sign in returns to the deep link that asked for it", async ({ page, account }) => { + await page.goto("/achievements?view=list"); + await expect(page).toHaveURL("/auth/signin?callbackUrl=%2Fachievements%3Fview%3Dlist"); + await expect(page.getByRole("textbox", { name: "Email" })).toBeFocused(); + await signInWith(page, account.email, account.password); + await expect(page).toHaveURL("/achievements?view=list"); + await expect(page.getByRole("heading", { level: 1, name: "Progress" })).toBeVisible(); + }); + + test("a callbackUrl to another site is ignored", async ({ page, account }) => { + await openSignIn(page, `/auth/signin?callbackUrl=${encodeURIComponent("https://evil.example/phish")}`); + // Nothing carries the address on to the other auth screens either. + await expect(page.getByRole("link", { name: "Create account" })).toHaveAttribute("href", "/auth/signup"); + await signInWith(page, account.email, account.password); + await expect(page).toHaveURL("/"); + await expect(page.getByRole("heading", { level: 1, name: "Home" })).toBeVisible(); + }); + }); + + test.describe("forgot and reset password", () => { + // The old password answers 401 once the new one is set. + test.use({ allowConsoleErrors: [loggedStatus(401)] }); + + test("Forgot password sends a link, and the link sets a new password once", async ({ page, account }) => { + // Each password check takes the server about 2 s (bcrypt at cost 12), and this test makes several. + test.slow(); + test.skip(!hasDatabase, NEEDS_DATABASE); + let link = ""; + + await test.step("ask for a link from sign in", async () => { + await openSignIn(page); + await page.getByRole("link", { name: "Forgot password?" }).click(); + await expect(page.getByRole("heading", { level: 1, name: "Reset password" })).toBeVisible(); + const email = page.getByRole("textbox", { name: "Email" }); + await expect(email).toBeFocused(); + await email.fill("name@"); + await page.getByRole("button", { name: "Send reset link" }).click(); + await expect(email).toHaveAccessibleDescription("Enter an email address like name@example.com."); + + await email.fill(account.email); + await page.getByRole("button", { name: "Send reset link" }).click(); + await expect(page.getByRole("heading", { level: 1, name: "Check your email" })).toBeFocused(); + // The tab title follows the screen, not the page it started on. + await expect(page).toHaveTitle("Check your email · Study Bot"); + await expect(page.getByRole("main")).toContainText( + `If an account uses ${account.email}, a password reset link is on its way. The link lasts 1 hour.`, + ); + }); + + await test.step("the app stores a link that lasts 1 hour", async () => { + // The email goes out after the response, so the row can lag the screen. + await expect.poll(() => latestToken(account.email, "PASSWORD_RESET")).toMatchObject({ used: false }); + const row = (await latestToken(account.email, "PASSWORD_RESET"))!; + expect(row.minutes_left).toBeGreaterThan(55); + expect(row.minutes_left).toBeLessThanOrEqual(60); + link = `/auth/reset-password?token=${await takeOverToken(row.id)}`; + }); + + await test.step("the link asks for the new password twice", async () => { + await page.goto(link); + await expect(page.getByRole("heading", { level: 1, name: "Choose a new password" })).toBeVisible(); + await expect(page).toHaveTitle("Choose a new password · Study Bot"); + const password = page.getByRole("textbox", { name: "New password", exact: true }); + const confirm = page.getByRole("textbox", { name: "Confirm new password" }); + await expect(password).toBeFocused(); + await expect(password).toHaveAccessibleDescription("Use at least 8 characters."); + await password.fill(NEW_PASSWORD); + await confirm.fill(`${NEW_PASSWORD}-typo`); + await page.getByRole("button", { name: "Reset password" }).click(); + await expect(confirm).toHaveAccessibleDescription("Enter the same password in both fields."); + + await confirm.fill(NEW_PASSWORD); + await page.getByRole("button", { name: "Reset password" }).click(); + await expect(page.getByRole("heading", { level: 1, name: "Password updated" })).toBeFocused(); + await expect(page).toHaveTitle("Password updated · Study Bot"); + }); + + await test.step("sessions signed in with the old password end", async () => { + expect((await account.api.get("/api/settings")).status()).toBe(401); + }); + + await test.step("only the new password signs in", async () => { + await page.getByRole("link", { name: "Sign in" }).click(); + await expect(page.getByRole("textbox", { name: "Email" })).toBeFocused(); + await signInWith(page, account.email, account.password); + await expect(page.getByRole("group", { name: DETAILS_DONT_MATCH })).toBeFocused(); + await page.getByLabel("Password", { exact: true }).fill(NEW_PASSWORD); + await page.getByRole("button", { name: "Sign in" }).click(); + await expect(page).toHaveURL("/"); + }); + + await test.step("the link works once", async () => { + await page.goto(link); + await expect(page.getByRole("heading", { level: 1, name: "Reset link already used" })).toBeVisible(); + await expect(page).toHaveTitle("Reset link already used · Study Bot"); + await expect(page.getByRole("link", { name: "Request a new link" })).toHaveAttribute("href", "/auth/forgot-password"); + }); + }); + + test("an expired reset link says so and leads to a new one", async ({ page, account }) => { + test.skip(!hasDatabase, NEEDS_DATABASE); + const token = await insertToken(account.email, "PASSWORD_RESET", { expiresInMinutes: -5 }); + + await page.goto(`/auth/reset-password?token=${token}`); + await expect(page.getByRole("heading", { level: 1, name: "Reset link expired" })).toBeVisible(); + await expect(page).toHaveTitle("Reset link expired · Study Bot"); + await expect(page.getByRole("main")).toContainText("Reset links last 1 hour. Request a new link to choose a new password."); + await expect(page.getByRole("textbox", { name: "New password" })).toHaveCount(0); + + await page.getByRole("link", { name: "Request a new link" }).click(); + await expect(page).toHaveURL("/auth/forgot-password"); + const email = page.getByRole("textbox", { name: "Email" }); + await expect(email).toBeFocused(); + await email.fill(account.email); + await page.getByRole("button", { name: "Send reset link" }).click(); + await expect(page.getByRole("heading", { level: 1, name: "Check your email" })).toBeFocused(); + + // The new link replaces the expired one and lasts the next hour. + await expect.poll(async () => (await latestToken(account.email, "PASSWORD_RESET"))?.minutes_left ?? 0).toBeGreaterThan(55); + }); + + test("a reset link with a missing or made-up token says it doesn't work", async ({ page }) => { + for (const path of ["/auth/reset-password?token=not-a-real-token", "/auth/reset-password"]) { + await test.step(path, async () => { + await page.goto(path); + await expect(page.getByRole("heading", { level: 1, name: "This reset link doesn't work" })).toBeVisible(); + // The tab title is the first thing a screen reader reads; it matches the heading. + await expect(page).toHaveTitle("This reset link doesn't work · Study Bot"); + await expect(page.getByRole("main")).toContainText( + "The link may be incomplete. Copy the whole link from the email, or request a new one.", + ); + await expect(page.getByRole("link", { name: "Request a new link" })).toHaveAttribute("href", "/auth/forgot-password"); + await expect(page.getByRole("link", { name: "Back to sign in" })).toHaveAttribute("href", "/auth/signin"); + }); + } + }); + }); + + test.describe("email verification", () => { + test("a verification link verifies the email once and opens sign in", async ({ page, account }) => { + test.skip(!hasDatabase, NEEDS_DATABASE); + + await test.step("an expired link says so", async () => { + const expired = await insertToken(account.email, "EMAIL_VERIFY", { expiresInMinutes: -5 }); + await page.goto(`/api/auth/verify-email?token=${expired}`); + await expect(page).toHaveURL("/auth/verify-email?status=expired"); + await expect(page.getByRole("heading", { level: 1, name: "Verification link expired" })).toBeVisible(); + expect(await emailVerifiedAt(account.email)).toBeNull(); + }); + + const token = await insertToken(account.email, "EMAIL_VERIFY", { expiresInMinutes: 24 * 60 }); + for (const visit of ["first", "second"]) { + await test.step(`the working link, ${visit} visit`, async () => { + await page.goto(`/api/auth/verify-email?token=${token}`); + await expect(page).toHaveURL("/auth/signin?verified=true"); + await expect(page.getByRole("status").filter({ hasText: "Email verified" })).toContainText("Sign in to continue."); + expect(await emailVerifiedAt(account.email)).not.toBeNull(); + }); + } + }); + + test("a link that doesn't work explains itself and sends a new one", async ({ page }) => { + const email = newEmail(); + await page.goto("/api/auth/verify-email?token=not-a-real-token"); + await expect(page).toHaveURL("/auth/verify-email?status=invalid"); + await expect(page.getByRole("heading", { level: 1, name: "This verification link doesn't work" })).toBeVisible(); + + const field = page.getByRole("textbox", { name: "Email" }); + const send = page.getByRole("button", { name: "Send a new link" }); + await hydrated(send); + await send.click(); + await expect(field).toHaveAccessibleDescription("Enter your email address."); + + await field.fill(email); + await send.click(); + await expect(page.getByRole("status").filter({ hasText: "Link sent" })).toContainText( + `If ${email} has an account waiting for verification, a new link is on its way. It lasts 24 hours.`, + ); + }); + + test("the verify email page explains each status", async ({ page }) => { + const main = page.getByRole("main"); + const sendButton = page.getByRole("button", { name: "Send a new link" }); + const emailField = page.getByRole("textbox", { name: "Email" }); + + await test.step("sent, with the address", async () => { + await page.goto("/auth/verify-email?email=ada%40studybot.test"); + await expect(page.getByRole("heading", { level: 1, name: "Verify your email" })).toBeVisible(); + await expect(page).toHaveTitle("Verify your email · Study Bot"); + await expect(main).toContainText("A verification link went to ada@studybot.test. Open it to finish creating your account."); + await expect(sendButton).toBeVisible(); + await expect(emailField).toHaveCount(0); + }); + + await test.step("sent, with something that isn't an address", async () => { + await page.goto(`/auth/verify-email?email=${encodeURIComponent("<b>not an address</b>")}`); + await expect(main).toContainText("A verification link went to the email you signed up with."); + await expect(main).not.toContainText("not an address"); + await expect(emailField).toBeVisible(); + }); + + for (const { status, title, description, canResend } of [ + { + status: "expired", + title: "Verification link expired", + description: "Verification links last 24 hours. Send a new one to finish creating your account.", + canResend: true, + }, + { + status: "busy", + title: "Too many attempts", + description: "Wait a few minutes, then open the link in your email again.", + canResend: false, + }, + { + status: "failed", + title: "Email not verified yet", + description: "The link couldn't be checked just now. Open it again in a few minutes.", + canResend: false, + }, + ]) { + await test.step(status, async () => { + await page.goto(`/auth/verify-email?status=${status}`); + await expect(page.getByRole("heading", { level: 1, name: title })).toBeVisible(); + await expect(page).toHaveTitle(`${title} · Study Bot`); + await expect(main).toContainText(description); + await expect(sendButton).toHaveCount(canResend ? 1 : 0); + await expect(page.getByRole("link", { name: "Back to sign in" })).toBeVisible(); + }); + } + }); + }); + + test.describe("before the page's script runs", () => { + // What a student on a slow connection gets when they submit before the + // form has hydrated: the browser submits the server-rendered form itself. + test.use({ javaScriptEnabled: false }); + + test("submitting sign in or create account never puts the password in the address", async ({ page }) => { + const secret = "e2e-only-NotInTheUrl"; + + await test.step("sign in", async () => { + await page.goto("/auth/signin"); + await page.getByRole("textbox", { name: "Email" }).fill("ada@studybot.test"); + await page.getByLabel("Password", { exact: true }).fill(secret); + await page.getByRole("button", { name: "Sign in" }).click(); + await expect(page.getByRole("heading", { level: 1, name: "Sign in" })).toBeVisible(); + await expect(page).toHaveURL("/auth/signin"); + }); + + await test.step("create account", async () => { + await page.goto("/auth/signup?callbackUrl=%2Fplan"); + await page.getByRole("textbox", { name: "Name" }).fill("Ada"); + await page.getByRole("textbox", { name: "Email" }).fill("ada@studybot.test"); + await page.getByRole("textbox", { name: "Password", exact: true }).fill(secret); + await page.getByRole("textbox", { name: "Confirm password" }).fill(secret); + await page.getByRole("button", { name: "Create account" }).click(); + await expect(page.getByRole("heading", { level: 1, name: "Create account" })).toBeVisible(); + await expect(page).toHaveURL("/auth/signup?callbackUrl=%2Fplan"); + }); + }); + }); +}); + +test.describe("signed in", () => { + test("the sign-in and create account pages send a signed-in student on", async ({ page }) => { + // The shared account; this only reads. + await page.goto("/auth/signin"); + await expect(page).toHaveURL("/"); + await expect(page.getByRole("heading", { level: 1, name: "Home" })).toBeVisible(); + + await page.goto("/auth/signup?callbackUrl=%2Fachievements"); + await expect(page).toHaveURL("/achievements"); + await expect(page.getByRole("heading", { level: 1, name: "Progress" })).toBeVisible(); + }); + + test("Sign out in the account menu ends the session", { tag: "@mobile" }, async ({ account }) => { + const page = account.page; + await page.goto("/"); + await expect(page.getByRole("heading", { level: 1, name: "Home" })).toBeVisible(); + + const menu = await openMenu(page, "Open account menu"); + await expect(menu).toContainText(account.email); + await menu.getByRole("menuitem", { name: "Sign out" }).click(); + + await expect(page).toHaveURL("/auth/signin"); + await expect(page.getByRole("heading", { level: 1, name: "Sign in" })).toBeVisible(); + await page.goto("/settings"); + await expect(page).toHaveURL("/auth/signin?callbackUrl=%2Fsettings"); + }); +}); diff --git a/e2e/calendar-ui.spec.ts b/e2e/calendar-ui.spec.ts deleted file mode 100644 index 1360f386..00000000 --- a/e2e/calendar-ui.spec.ts +++ /dev/null @@ -1,203 +0,0 @@ -/** - * Playwright E2E tests for Google Calendar UI flows. - * - * Requires GOOGLE_PROVIDER=fake so the server uses FakeGoogleCalendarClient. - * Uses the __test-seed endpoint to create/cleanup GoogleIntegration records. - */ -import { test, expect } from "@playwright/test"; - -const BASE = process.env.BASE_URL || "http://localhost:3000"; -const userId = "e2e_ui_gcal_user"; - -// ── Settings Page ────────────────────────────────────────────────────── - -test.describe("Settings Page - Calendar UI", () => { - test.use({ extraHTTPHeaders: { "X-User-Id": userId } }); - - test.beforeEach(async ({ request }) => { - // Seed a connected GoogleIntegration - const res = await request.post(`${BASE}/api/integrations/google/__test-seed`, { - data: { connected_email: "e2e@example.com" }, - }); - // If seed endpoint not available (GOOGLE_PROVIDER != fake), skip - if (res.status() === 404) { - test.skip(true, "GOOGLE_PROVIDER is not fake — skipping UI E2E"); - } - expect(res.status()).toBe(200); - }); - - test.afterEach(async ({ request }) => { - await request.delete(`${BASE}/api/integrations/google/__test-seed`); - }); - - test("shows connected status and account email", async ({ page }) => { - await page.goto(`${BASE}/settings/calendar`); - - // Wait for status to load - await expect(page.locator("text=Connected")).toBeVisible({ timeout: 10_000 }); - await expect(page.locator("text=e2e@example.com")).toBeVisible(); - - // Test Connection and Disconnect buttons should be visible - await expect(page.locator("button", { hasText: "Test Connection" })).toBeVisible(); - await expect(page.locator("button", { hasText: "Disconnect" })).toBeVisible(); - }); - - test("displays calendar preferences when connected", async ({ page }) => { - await page.goto(`${BASE}/settings/calendar`); - - // Wait for calendars to load (fake client returns "Primary" calendar) - await expect(page.locator("text=Calendar Preferences")).toBeVisible({ timeout: 10_000 }); - await expect(page.locator("text=Default calendar")).toBeVisible(); - await expect(page.locator("text=Busy calendars")).toBeVisible(); - }); - - test("save preferences updates successfully", async ({ page }) => { - await page.goto(`${BASE}/settings/calendar`); - - // Wait for preferences to appear - await expect(page.locator("text=Calendar Preferences")).toBeVisible({ timeout: 10_000 }); - - // Click Save Preferences - await page.locator("button", { hasText: "Save Preferences" }).click(); - - // Should show success message - await expect(page.locator("text=Preferences saved")).toBeVisible({ timeout: 5_000 }); - }); - - test("test connection shows success message", async ({ page }) => { - await page.goto(`${BASE}/settings/calendar`); - - await expect(page.locator("button", { hasText: "Test Connection" })).toBeVisible({ timeout: 10_000 }); - await page.locator("button", { hasText: "Test Connection" }).click(); - - // Should show success - await expect(page.locator("text=Connection test passed")).toBeVisible({ timeout: 10_000 }); - }); - - test("disconnect removes connection", async ({ page }) => { - await page.goto(`${BASE}/settings/calendar`); - - await expect(page.locator("button", { hasText: "Disconnect" })).toBeVisible({ timeout: 10_000 }); - await page.locator("button", { hasText: "Disconnect" }).click(); - - // Status should switch to "Not connected" - await expect(page.locator("text=Not connected")).toBeVisible({ timeout: 5_000 }); - - // Connect button should now appear - await expect(page.locator("button", { hasText: "Connect Google Calendar" })).toBeVisible(); - }); - - test("shows not connected state for unknown user", async ({ page, context }) => { - // Use a different user ID that has no integration - await context.setExtraHTTPHeaders({ "X-User-Id": "e2e_unknown_user_no_gcal" }); - await page.goto(`${BASE}/settings/calendar`); - - await expect(page.locator("text=Not connected")).toBeVisible({ timeout: 10_000 }); - await expect(page.locator("button", { hasText: "Connect Google Calendar" })).toBeVisible(); - }); -}); - -// ── Plan Page: Publish Flow ──────────────────────────────────────────── - -test.describe("Plan Page - Publish Flow", () => { - test.use({ extraHTTPHeaders: { "X-User-Id": userId } }); - - let planId: string; - - test.beforeAll(async ({ request }) => { - // Seed Google integration - const seedRes = await request.post(`${BASE}/api/integrations/google/__test-seed`, { - data: { connected_email: "e2e@example.com" }, - }); - if (seedRes.status() === 404) { - test.skip(true, "GOOGLE_PROVIDER is not fake — skipping UI E2E"); - } - - // Create a plan via API - const planRes = await request.post(`${BASE}/api/plans`, { - data: { - course_name: "E2E UI Calendar", - exam_name: "Final Exam", - exam_date: "2026-06-15", - objectives: ["Topic A", "Topic B", "Topic C", "Topic D", "Topic E"], - availability: Array.from({ length: 7 }, () => ({ start: "09:00", end: "17:00" })), - daily_study_cap_minutes: 120, - break_protocol_default: "50_10", - }, - }); - expect(planRes.status()).toBe(201); - const plan = await planRes.json(); - planId = plan.plan_id; - }); - - test.afterAll(async ({ request }) => { - await request.delete(`${BASE}/api/integrations/google/__test-seed`); - }); - - test("publish to Google Calendar shows success counts", async ({ request }) => { - // Publish via API (since the plan page UI requires navigating through form creation) - const pubRes = await request.post(`${BASE}/api/plans/${planId}/publish/google`, { - data: {}, - }); - expect(pubRes.status()).toBe(200); - const pubBody = await pubRes.json(); - - expect(pubBody.status).toBe("OK"); - expect(pubBody.summary.total).toBeGreaterThan(0); - expect(pubBody.summary.created).toBe(pubBody.summary.total); - expect(pubBody.summary.updated).toBe(0); - expect(pubBody.summary.unchanged).toBe(0); - expect(pubBody.summary.failed).toBe(0); - expect(pubBody.duration_ms).toBeGreaterThanOrEqual(0); - expect(pubBody.item_results.length).toBe(pubBody.summary.total); - - // All items should be CREATED - for (const item of pubBody.item_results) { - expect(item.action).toBe("CREATED"); - expect(item.event_id).toBeTruthy(); - } - }); - - test("republish shows unchanged counts", async ({ request }) => { - // Republish the same plan — events should be unchanged - const pubRes = await request.post(`${BASE}/api/plans/${planId}/publish/google`, { - data: {}, - }); - expect(pubRes.status()).toBe(200); - const pubBody = await pubRes.json(); - - expect(pubBody.status).toBe("OK"); - // On republish with fake client, events get UPDATED (not UNCHANGED) because - // fake client doesn't persist extended properties for hash comparison - expect(pubBody.summary.total).toBeGreaterThan(0); - expect(pubBody.summary.failed).toBe(0); - }); - - test("publish status shows published state", async ({ request }) => { - const statusRes = await request.get(`${BASE}/api/plans/${planId}/publish/google`); - expect(statusRes.status()).toBe(200); - const status = await statusRes.json(); - - expect(status.publication).not.toBeNull(); - expect(status.publication.status).toBe("PUBLISHED"); - expect(status.publication.published_at).toBeTruthy(); - expect(status.items.length).toBeGreaterThan(0); - }); - - test("unpublish removes events", async ({ request }) => { - const unpubRes = await request.post(`${BASE}/api/plans/${planId}/unpublish/google`, { - data: {}, - }); - expect(unpubRes.status()).toBe(200); - const unpubBody = await unpubRes.json(); - - expect(unpubBody.status).toBe("OK"); - expect(unpubBody.duration_ms).toBeGreaterThanOrEqual(0); - - // Verify status is now unpublished - const statusRes = await request.get(`${BASE}/api/plans/${planId}/publish/google`); - const status = await statusRes.json(); - expect(status.publication).toBeNull(); - expect(status.items).toEqual([]); - }); -}); diff --git a/e2e/cards.spec.ts b/e2e/cards.spec.ts new file mode 100644 index 00000000..0be10ab1 --- /dev/null +++ b/e2e/cards.spec.ts @@ -0,0 +1,303 @@ +/** + * Flashcards: the deck list with each deck's counts by status, a deck's + * own page, a missing deck, and the card review at + * /flashcards/[deckId]/review: Show answer, rating with keys 1 to 4 (which + * do nothing before the answer shows or once the review is done), "?" and + * the switch that turns single-key shortcuts off, the tab title following + * the screen, the completion screen, the review scope surviving a reload, + * and a review by touch on a small phone. + * + * Every test has its own identity (testUser) with one deck generated by + * the mock AI from one uploaded file, so counts never include another + * test's cards and the AI rate limit is per test. Scheduling (SM-2, + * intervals, exam caps) is covered by the spaced-repetition and + * flashcard-review unit tests. + */ +import type { APIRequestContext, Page } from "@playwright/test"; +import { test, expect, createDeck, getJson, loggedStatus } from "./fixtures"; + +type Rating = "AGAIN" | "HARD" | "GOOD" | "EASY"; + +interface StudyData { + cards: { id: string; front: string; back: string }[]; + stats: { newCount: number; learningCount: number; reviewCount: number; masteredCount: number; dueCount: number }; +} + +const studyData = (api: APIRequestContext, deckId: string) => + getJson<StudyData>(api, `/api/flashcards/${deckId}/study?scope=all`); + +async function rate(api: APIRequestContext, deckId: string, cardId: string, rating: Rating) { + const response = await api.post(`/api/flashcards/${deckId}/review`, { data: { card_id: cardId, rating } }); + expect(response.status(), await response.text()).toBe(200); +} + +/** The review's progress bar; its value counts cards rated Hard or better. */ +const progress = (page: Page) => page.getByRole("progressbar", { name: "Review progress" }); + +const front = (page: Page) => page.getByRole("heading", { level: 1 }); + +const ratings = (page: Page) => page.getByRole("group", { name: "How well did you know it?" }); + +/** A rating button, named "Good, next review in 1 day". */ +const ratingButton = (page: Page, label: "Again" | "Hard" | "Good" | "Easy") => + ratings(page).getByRole("button", { name: new RegExp(`^${label}\\b`) }); + +/** Every rating the page sends, in order. */ +function recordRatings(page: Page): Rating[] { + const sent: Rating[] = []; + page.on("request", (request) => { + if (request.method() === "POST" && /\/api\/flashcards\/[^/]+\/review$/.test(request.url())) { + sent.push(request.postDataJSON().rating); + } + }); + return sent; +} + +test("the deck list counts cards by status, and a deck opens on its cards", { tag: "@mobile" }, async ({ testUser, testUserPage: page }) => { + const deck = await createDeck(testUser.api); + await rate(testUser.api, deck.id, deck.cards[0].id, "GOOD"); + + await page.goto("/flashcards"); + await expect(page.getByRole("heading", { level: 2, name: "2 cards due today" })).toBeVisible(); + const card = page.getByRole("region", { name: deck.course }).getByRole("article", { name: deck.title }); + await expect(card).toContainText("3 cards"); + await expect(card).toContainText("AI-written"); + const counts = ` + - term: New + - definition: "2" + - term: Learning + - definition: "0" + - term: Reviewing + - definition: "1" + - term: Mastered + - definition: "0" + `; + await expect(card).toMatchAriaSnapshot(counts); + await expect(card.getByText("2 due today")).toBeVisible(); + await expect(card.getByRole("link", { name: "Review due cards" })).toHaveAttribute("href", `/flashcards/${deck.id}/review`); + + await card.getByRole("link", { name: deck.title }).click(); + await expect(page).toHaveURL(`/flashcards/${deck.id}`); + await expect(page).toHaveTitle(`${deck.title} · Study Bot`); + await expect(page.getByRole("heading", { level: 2, name: deck.title })).toBeVisible(); + await expect(page.getByRole("region", { name: "Cards by status" })).toMatchAriaSnapshot(counts); + const rows = page.getByRole("region", { name: "Cards", exact: true }).getByRole("listitem"); + await expect(rows).toHaveCount(3); + for (const [i, { front: text }] of deck.cards.entries()) await expect(rows.nth(i)).toContainText(text); + await expect(rows.first()).toContainText("Reviewing"); + await expect(rows.nth(1)).toContainText("New"); +}); + +test.describe(() => { + // Chromium logs the 404 document response as a console error. + test.use({ allowConsoleErrors: [loggedStatus(404)] }); + + test("a missing deck says so, in the page and the tab", async ({ testUserPage: page }) => { + // The review checks the deck before it streams, so the status is a real 404 + const review = await page.goto("/flashcards/no-such-deck/review"); + expect(review?.status()).toBe(404); + await expect(page.getByRole("heading", { name: "Deck not found" })).toBeVisible(); + await expect(page).toHaveTitle("Deck not found · Study Bot"); + await expect(page.getByRole("link", { name: "Go to Flashcards" })).toHaveAttribute("href", "/flashcards"); + + // So does the deck page: no loading boundary streams ahead of its check + const deck = await page.goto("/flashcards/no-such-deck"); + expect(deck?.status()).toBe(404); + await expect(page.getByRole("heading", { level: 2, name: "Deck not found" })).toBeVisible(); + await expect(page).toHaveTitle("Deck not found · Study Bot"); + }); +}); + +test("Show answer, then keys 1 to 4 rate; keys do nothing before the answer or after the last card", async ({ + testUser, + testUserPage: page, +}) => { + test.slow(); + const deck = await createDeck(testUser.api); + const [c1, c2, c3] = deck.cards; + const sent = recordRatings(page); + await page.goto(`/flashcards/${deck.id}/review`); + await expect(page).toHaveTitle(`Card 1 of 3 · ${deck.title} · Study Bot`); + + await test.step("before the answer shows, number keys do nothing", async () => { + await expect(front(page)).toHaveText(c1.front); + await expect(front(page)).toBeFocused(); + for (const key of ["1", "2", "3", "4"]) await page.keyboard.press(key); + await expect(page.getByRole("button", { name: "Show answer" })).toBeVisible(); + await expect(page.getByRole("region", { name: "Answer" })).toHaveCount(0); + await expect(progress(page)).toHaveAttribute("aria-valuenow", "0"); + }); + + await test.step("Space shows the answer and each rating shows its key", async () => { + await page.keyboard.press("Space"); + const answer = page.getByRole("region", { name: "Answer" }); + await expect(answer).toBeFocused(); + await expect(answer).toContainText(c1.back); + await expect(answer).toContainText("AI-written"); + for (const [label, key] of [["Again", "1"], ["Hard", "2"], ["Good", "3"], ["Easy", "4"]] as const) { + await expect(ratingButton(page, label).getByText(key, { exact: true })).toBeVisible(); + } + }); + + await test.step("1 is Again: the card comes back at the end", async () => { + await expect(ratingButton(page, "Again")).toHaveAccessibleName("Again, next review in 10 min"); + await page.keyboard.press("1"); + await expect(front(page)).toHaveText(c2.front); + await expect(front(page)).toBeFocused(); + await expect(progress(page)).toHaveAttribute("aria-valuenow", "0"); + // No card is done yet, so the tab still counts the first + await expect(page).toHaveTitle(`Card 1 of 3 · ${deck.title} · Study Bot`); + }); + + await test.step("2, 3 and 4 rate Hard, Good and Easy", async () => { + for (const [key, next, done] of [ + ["2", c3.front, "1"], + ["3", c1.front, "2"], + ] as const) { + await page.keyboard.press("Space"); + await expect(page.getByRole("region", { name: "Answer" })).toBeFocused(); + await page.keyboard.press(key); + await expect(front(page)).toHaveText(next); + await expect(progress(page)).toHaveAttribute("aria-valuenow", done); + await expect(page).toHaveTitle(`Card ${Number(done) + 1} of 3 · ${deck.title} · Study Bot`); + } + await page.keyboard.press("Space"); + await expect(page.getByRole("region", { name: "Answer" })).toBeFocused(); + await page.keyboard.press("4"); + }); + + await test.step("the completion screen sums up the review and ignores the keys", async () => { + const done = page.getByRole("heading", { level: 1, name: "Deck reviewed" }); + await expect(done).toBeFocused(); + await expect(page).toHaveTitle(`Deck reviewed · ${deck.title} · Study Bot`); + const main = page.getByRole("main"); + await expect(main.getByText(`3 cards reviewed in ${deck.title}.`)).toBeVisible(); + const summary = ` + - term: Again + - definition: "1" + - term: Hard + - definition: "1" + - term: Good + - definition: "1" + - term: Easy + - definition: "1" + `; + await expect(main).toMatchAriaSnapshot(summary); + await expect(progress(page)).toHaveAttribute("aria-valuenow", "3"); + + for (const key of ["1", "2", "3", "4", "Space"]) await page.keyboard.press(key); + await expect(done).toBeVisible(); + await expect(main).toMatchAriaSnapshot(summary); + expect(sent).toEqual(["AGAIN", "HARD", "GOOD", "EASY"]); + await expect(main.getByRole("link", { name: "Go to Flashcards" })).toHaveAttribute("href", "/flashcards"); + }); + + await test.step("the ratings are saved: nothing is new or due", async () => { + const { stats } = await studyData(testUser.api, deck.id); + expect(stats).toMatchObject({ newCount: 0, dueCount: 0 }); + }); +}); + +test("? and the switch for single-key shortcuts: the keys turn off, and they stay off", async ({ + testUser, + testUserPage: page, +}) => { + const deck = await createDeck(testUser.api); + const sent = recordRatings(page); + await page.goto(`/flashcards/${deck.id}/review`); + await expect(front(page)).toBeFocused(); + + const help = page.getByRole("button", { name: "Keyboard shortcuts" }); + const popover = page.getByRole("dialog", { name: "Keyboard shortcuts" }); + const single = popover.getByRole("switch", { name: "Single-key shortcuts" }); + + // ? opens the shortcuts from the keyboard, switch included + await page.keyboard.press("?"); + await expect(single).toBeVisible(); + await page.keyboard.press("Escape"); + await expect(popover).toBeHidden(); + + await help.click(); + await expect(popover).toContainText("The same setting applies in study sessions."); + await expect(single).toBeChecked(); + await single.click(); + await expect(single).not.toBeChecked(); + await page.keyboard.press("Escape"); + await expect(popover).toBeHidden(); + await expect(help).toBeFocused(); + // ? is a single key too, so it's off now; the button still opens the help + await page.keyboard.press("?"); + await expect(popover).toBeHidden(); + + await page.getByRole("button", { name: "Show answer" }).click(); + await expect(ratingButton(page, "Good")).toBeVisible(); + await expect(ratingButton(page, "Good").getByText("3", { exact: true })).toHaveCount(0); + await page.keyboard.press("3"); + await expect(progress(page)).toHaveAttribute("aria-valuenow", "0"); + await expect(front(page)).toHaveText(deck.cards[0].front); + expect(sent).toEqual([]); + + // The buttons still rate, and Space still shows the answer. + await ratingButton(page, "Good").click(); + await expect(front(page)).toHaveText(deck.cards[1].front); + await expect(front(page)).toBeFocused(); + await page.keyboard.press("Space"); + await expect(page.getByRole("region", { name: "Answer" })).toContainText(deck.cards[1].back); + expect(sent).toEqual(["GOOD"]); + + await page.reload(); + await expect(front(page)).toBeFocused(); + await help.click(); + await expect(single).not.toBeChecked(); +}); + +test("the review scope in the URL survives a reload", async ({ testUser, testUserPage: page }) => { + const deck = await createDeck(testUser.api); + for (const card of deck.cards) await rate(testUser.api, deck.id, card.id, "GOOD"); + + await page.goto(`/flashcards/${deck.id}/review`); + await expect(front(page)).toHaveText(`Nothing due in ${deck.title}`); + await expect(page).toHaveTitle(`Nothing due · ${deck.title} · Study Bot`); + await page.getByRole("button", { name: "Review deck" }).click(); + + // Reviewing the whole deck puts ?scope=all in the URL, so a reload keeps it. + await expect(page).toHaveURL(`/flashcards/${deck.id}/review?scope=all`); + await expect(front(page)).toHaveText(deck.cards[0].front); + await expect(progress(page)).toHaveAttribute("aria-valuemax", "3"); + + await page.reload(); + await expect(page).toHaveURL(`/flashcards/${deck.id}/review?scope=all`); + await expect(front(page)).toHaveText(deck.cards[0].front); + await expect(progress(page)).toHaveAttribute("aria-valuemax", "3"); +}); + +test("a review by touch on a small phone", { tag: "@mobile" }, async ({ isMobile, testUser, testUserPage: page }) => { + test.skip(!isMobile, "Phone layout only"); + // 320px wide, where the counts used to wrap in the top bar and push the question under it + await page.setViewportSize({ width: 320, height: 568 }); + const deck = await createDeck(testUser.api); + await page.goto(`/flashcards/${deck.id}/review`); + await expect(front(page)).toHaveText(deck.cards[0].front); + // A phone or tablet can have a keyboard (or switch software that sends keys), so the + // shortcuts and their off switch stay one tap away. + await expect(page.getByRole("button", { name: "Keyboard shortcuts" })).toBeVisible(); + // The counts sit under the card, once + await expect(page.getByRole("term").filter({ hasText: "Mastered" })).toHaveCount(1); + const leave = page.getByRole("link", { name: "Leave review" }); + + for (const card of deck.cards) { + await expect(front(page)).toHaveText(card.front); + await page.getByRole("button", { name: "Show answer" }).tap(); + await expect(page.getByRole("region", { name: "Answer" })).toContainText(card.back); + // The question stays clear of the top bar (the close button's row) when the answer shows + const bar = await leave.boundingBox(); + const question = await front(page).boundingBox(); + expect(question!.y).toBeGreaterThanOrEqual(bar!.y + bar!.height); + await ratingButton(page, "Good").tap(); + } + + await expect(page.getByRole("heading", { level: 1, name: "Deck reviewed" })).toBeVisible(); + await page.getByRole("link", { name: "Go to Flashcards" }).tap(); + await expect(page).toHaveURL("/flashcards"); + await expect(page.getByRole("heading", { level: 2, name: "Nothing due today" })).toBeVisible(); +}); diff --git a/e2e/chat.spec.ts b/e2e/chat.spec.ts new file mode 100644 index 00000000..17f48094 --- /dev/null +++ b/e2e/chat.spec.ts @@ -0,0 +1,286 @@ +/** + * Chat over a course's materials: the empty state with no materials, a + * question answered by the mock AI (Markdown citations and numbered + * sources), a question worded differently from the file still finding it, + * Enter and Shift+Enter in the question box, focus staying in it, Retry + * after a failed answer storing the question once, Delete chat history with + * its confirmation, and older history loading above the newest 50 messages, + * with Retry when a page fails. + * + * Chat stores messages against a users row, so the tests use the + * `account` fixture (a real account each, which also gives each test its + * own AI rate limit). The answer route's retrieval and source numbering + * are covered by its unit tests (assistant-answer, chat-sources). + */ +import type { APIRequestContext, Page } from "@playwright/test"; +import { + test, + expect, + NEEDS_DATABASE, + getJson, + hasDatabase, + insertChatMessages, + loggedStatus, + toasts, + unique, + uploadMaterial, +} from "./fixtures"; + +const NOTES = [ + "Recursion: a function that calls itself on a smaller input.", + "A base case stops the recursion before the call stack overflows.", + "Each recursive call gets its own frame on the call stack.", +].join("\n\n"); + +interface History { + messages: { role: "user" | "assistant"; content: string }[]; + has_more: boolean; + total: number; +} + +const history = (api: APIRequestContext, course: string) => + getJson<History>(api, `/api/chat/messages?courseKey=${encodeURIComponent(course)}&limit=100`); + +/** Store a chat message through the API. */ +async function postMessage(api: APIRequestContext, course: string, role: "user" | "assistant", content: string) { + const response = await api.post("/api/chat/messages", { data: { courseKey: course, role, content } }); + expect(response.status(), await response.text()).toBe(201); +} + +/** A course with one uploaded file, so Chat offers it. */ +async function courseWithMaterials(api: APIRequestContext): Promise<string> { + const course = unique("E2E Chat"); + await uploadMaterial(api, { course, fileName: "recursion.txt", text: NOTES }); + return course; +} + +const questionBox = (page: Page, course: string) => + page.getByRole("textbox", { name: `Ask about your ${course} materials` }); + +const asked = (page: Page) => page.getByRole("article", { name: "You asked" }); +const answered = (page: Page) => page.getByRole("article", { name: "Study Bot answered" }); + +test("with no materials, Chat says what it needs and links to Upload materials", { tag: "@mobile" }, async ({ testUserPage: page }) => { + await page.goto("/chat"); + await expect(page.getByRole("heading", { level: 1 })).toHaveText("Chat"); + await expect(page.getByRole("heading", { level: 2, name: "No materials yet" })).toBeVisible(); + const upload = page.getByRole("main").getByRole("link", { name: "Upload materials" }); + await expect(upload).toHaveAttribute("href", "/plan/materials"); + await upload.click(); + await expect(page).toHaveURL("/plan/materials"); + await expect(page.getByRole("heading", { level: 1 })).toHaveText("Materials"); +}); + +test("a question gets an AI-written answer with numbered sources", { tag: "@mobile" }, async ({ account }) => { + const { page, api } = account; + const course = await courseWithMaterials(api); + await page.goto("/chat"); + const box = questionBox(page, course); + await expect(page.getByRole("heading", { level: 2, name: `No questions about ${course} yet` })).toBeVisible(); + + await test.step("Shift+Enter adds a line, Enter asks, and focus stays in the box", async () => { + await box.click(); + await page.keyboard.type("What is recursion?"); + await page.keyboard.press("Shift+Enter"); + await page.keyboard.type("What does the base case do?"); + await expect(box).toHaveValue("What is recursion?\nWhat does the base case do?"); + await expect(asked(page)).toHaveCount(0); + + await page.keyboard.press("Enter"); + await expect(asked(page)).toHaveText(["What is recursion?\nWhat does the base case do?"]); + await expect(box).toHaveValue(""); + await expect(box).toBeFocused(); + }); + + await test.step("the answer renders its citation as a link to numbered source 1", async () => { + const answer = answered(page); + await expect(answer).toContainText("AI-written"); + // Headings run day (h2), reply (h3), then the reply's own sections (h4) + await expect(answer.getByRole("heading", { level: 3, name: "Study Bot" })).toBeVisible(); + await expect(answer.getByRole("heading", { level: 4, name: "Sources (1)" })).toBeVisible(); + const citation = answer.getByRole("link", { name: "Source 1: recursion.txt" }); + await expect(citation).toHaveText("1"); + await expect(answer).not.toContainText("[1]"); + // A labelled group, not a landmark: a long chat would list dozens of them + await expect(answer.getByRole("region")).toHaveCount(0); + const source = answer.getByRole("group", { name: "Sources (1)" }).getByRole("button", { name: "Source 1: recursion.txt" }); + await expect(source).toHaveAttribute("aria-expanded", "false"); + + await citation.click(); + await expect(source).toHaveAttribute("aria-expanded", "true"); + await expect(source).toBeFocused(); + await expect(page.getByRole("status").filter({ hasText: "Answer ready." })).toBeAttached(); + }); + + await test.step("the question and answer are stored once", async () => { + const stored = await history(api, course); + expect(stored.messages.map((m) => m.role)).toEqual(["user", "assistant"]); + await page.reload(); + await expect(asked(page)).toHaveCount(1); + await expect(answered(page)).toHaveCount(1); + }); +}); + +test("a question worded differently from the file still finds it", async ({ account }) => { + const { api } = account; + const course = await courseWithMaterials(api); + const ask = async (question: string) => { + const response = await api.post("/api/assistant/answer", { data: { question, course_name: course } }); + expect(response.status(), await response.text()).toBe(200); + return (await response.json()) as { kind: string; sources: { title: string | null }[] }; + }; + + // The notes never say "need", so a search for every word finds nothing; most of the words still match + const covered = await ask("Why does each recursive call need its own frame on the stack?"); + expect(covered.kind).toBe("answer"); + expect(covered.sources.map((s) => s.title)).toEqual(["recursion.txt"]); + + // A question the notes don't touch still gets the plain notice + const uncovered = await ask("What is the capital of France?"); + expect(uncovered.kind).toBe("notice"); + expect(uncovered.sources).toEqual([]); +}); + +test.describe("when an answer fails", () => { + // The simulated failure is a 503, which Chromium logs as a failed resource. + test.use({ allowConsoleErrors: [/status of 503/] }); + + test("Retry asks again without storing the question twice", async ({ account }) => { + const { page, api } = account; + const course = await courseWithMaterials(api); + // The first answer request fails before it reaches the server. + await page.route( + "**/api/assistant/answer", + (route) => route.fulfill({ status: 503, json: { error: "Answer not generated. Retry.", code: "AI_UNAVAILABLE" } }), + { times: 1 }, + ); + await page.goto("/chat"); + await questionBox(page, course).fill("What is recursion?"); + await page.getByRole("button", { name: "Ask" }).click(); + + const failed = page.getByRole("alert").filter({ hasText: "Answer not generated." }); + await expect(failed).toContainText("The server didn't respond. Retry in a minute."); + await expect(asked(page)).toHaveText(["What is recursion?"]); + + await failed.getByRole("button", { name: "Retry" }).click(); + await expect(answered(page)).toBeVisible(); + await expect(failed).toHaveCount(0); + await expect(asked(page)).toHaveText(["What is recursion?"]); + + const stored = await history(api, course); + expect(stored.total).toBe(2); + expect(stored.messages.map((m) => [m.role, m.role === "user" ? m.content : "answer"])).toEqual([ + ["user", "What is recursion?"], + ["assistant", "answer"], + ]); + await page.reload(); + await expect(asked(page)).toHaveText(["What is recursion?"]); + await expect(answered(page)).toHaveCount(1); + }); +}); + +test("Delete chat history asks first, then empties the course's chat", async ({ account }) => { + const { page, api } = account; + const course = await courseWithMaterials(api); + await postMessage(api, course, "user", "What does a call stack hold?"); + await postMessage(api, course, "assistant", "One frame for each call that hasn't returned yet."); + await page.goto("/chat"); + await expect(asked(page)).toHaveText(["What does a call stack hold?"]); + + const remove = page.getByRole("button", { name: "Delete chat history" }); + const dialog = page.getByRole("alertdialog", { name: `Delete all ${course} chat messages?` }); + + await test.step("Escape cancels and returns focus to the button", async () => { + await remove.click(); + await expect(dialog).toContainText("This deletes 2 messages. Your materials stay."); + await page.keyboard.press("Escape"); + await expect(dialog).toBeHidden(); + await expect(remove).toBeFocused(); + await expect(asked(page)).toHaveCount(1); + }); + + await test.step("Delete messages empties the chat and puts focus in the question box", async () => { + await remove.click(); + await dialog.getByRole("button", { name: "Delete messages" }).click(); + await expect(dialog).toBeHidden(); + await expect(toasts(page)).toContainText("Chat history deleted"); + await expect(page.getByRole("heading", { level: 2, name: `No questions about ${course} yet` })).toBeVisible(); + await expect(questionBox(page, course)).toBeFocused(); + await expect(remove).toHaveCount(0); + + expect((await history(api, course)).total).toBe(0); + await page.reload(); + await expect(page.getByRole("heading", { level: 2, name: `No questions about ${course} yet` })).toBeVisible(); + }); +}); + +test("older messages load above the newest 50", async ({ account }) => { + // 52 messages: written straight to the database, since the chat routes allow 30 requests a minute. + test.skip(!hasDatabase, NEEDS_DATABASE); + const { page, api } = account; + const course = await courseWithMaterials(api); + await insertChatMessages( + account.email, + course, + Array.from({ length: 26 }, (_, i) => [ + { role: "user" as const, content: `Question ${i + 1} about recursion` }, + { role: "assistant" as const, content: `Answer ${i + 1} about recursion` }, + ]).flat(), + ); + expect((await history(api, course)).total).toBe(52); + + await page.goto("/chat"); + const questions = (from: number) => Array.from({ length: 27 - from }, (_, i) => `Question ${from + i} about recursion`); + // The newest page holds 50 messages: questions 2 to 26 and their answers. + await expect(asked(page)).toHaveText(questions(2)); + await expect(answered(page)).toHaveCount(25); + + const older = page.getByRole("button", { name: "Load older messages" }); + await older.click(); + await expect(asked(page)).toHaveText(questions(1)); + await expect(answered(page)).toHaveCount(26); + await expect(older).toHaveCount(0); +}); + +test.describe("when older messages fail", () => { + // The simulated failure is a 400 (SWR doesn't retry it), which Chromium logs as a failed resource. + test.use({ allowConsoleErrors: [loggedStatus(400)] }); + + test("Retry loads the page that failed, and only that page", async ({ account }) => { + test.skip(!hasDatabase, NEEDS_DATABASE); + const { page, api } = account; + const course = await courseWithMaterials(api); + // 102 messages: three pages, so a Retry that also loaded the next page would show + await insertChatMessages( + account.email, + course, + Array.from({ length: 51 }, (_, i) => [ + { role: "user" as const, content: `Question ${i + 1} about recursion` }, + { role: "assistant" as const, content: `Answer ${i + 1} about recursion` }, + ]).flat(), + ); + let olderRequests = 0; + await page.route(/\/api\/chat\/messages\?.*before=/, async (route) => { + olderRequests++; + if (olderRequests === 1) await route.fulfill({ status: 400, json: { error: "Bad request" } }); + else await route.continue(); + }); + + await page.goto("/chat"); + const questions = (from: number, to: number) => + Array.from({ length: to - from + 1 }, (_, i) => `Question ${from + i} about recursion`); + await expect(asked(page)).toHaveText(questions(27, 51)); + + await page.getByRole("button", { name: "Load older messages" }).click(); + const failed = page.getByRole("alert").filter({ hasText: "Older messages didn't load." }); + await expect(failed).toBeVisible(); + // The failure takes the button's place, so nothing stays stuck on "Loading older messages…" + await expect(page.getByRole("button", { name: /older messages/ })).toHaveCount(0); + + await failed.getByRole("button", { name: "Retry" }).click(); + await expect(asked(page)).toHaveText(questions(2, 51)); + await expect(failed).toHaveCount(0); + await expect(page.getByRole("button", { name: "Load older messages" })).toBeEnabled(); + expect(olderRequests).toBe(2); + }); +}); diff --git a/e2e/fixtures.ts b/e2e/fixtures.ts new file mode 100644 index 00000000..ac5a36d9 --- /dev/null +++ b/e2e/fixtures.ts @@ -0,0 +1,256 @@ +/** + * The suite's `test` and `expect`, and every helper the specs share. Import + * from here, never from @playwright/test, so every page gets the console + * guard: + * + * import { test, expect, createSession, unique } from "./fixtures"; + * + * Fixtures: + * - page: the signed-in e2e account (storageState from the setup project). + * Fails the test on any console error or uncaught page error, apart from + * CONSOLE_ALLOWLIST and the test's own `allowConsoleErrors`. + * - request: API calls as the same signed-in account. + * - clientAddress: the made-up client address (X-Forwarded-For) that `page` + * and `request` send. Each test gets its own, so the per-address limits on + * sign-in, sign-up and email links never cross between tests. + * - makeAxeBuilder(): AxeBuilder for `page`, limited to WCAG 2.2 A and AA + * (WCAG_TAGS). For another page, call axeBuilder(thatPage), or + * expectNoAxeViolations(page), which also waits for the page to settle. + * - testUser: a fresh identity for this test only, through the X-User-Id + * test header. `testUser.api` calls the API as it; `testUserPage` is a + * page signed in as it. Use these when a screen shows account-wide data + * (Home, Progress, Study) or the test needs its own AI rate limit. A test + * identity has no account row, so Chat (which stores messages against the + * account) and anything that changes the account need `account`. + * - account: a real account of its own, created through the sign-up API + * and signed in through next-auth's credentials endpoint: + * `{ email, password, api, page }`. For tests that need a row in the + * users table and may change or delete it (password, settings, account + * deletion, export, chat). Never change or delete the shared e2e account. + * - seedSession({ deck, ...session }): a session on the shared account whose + * started run holds a known deck (multiple choice, model answers), which + * the mock AI never writes. Skips the test without DATABASE_URL. + * - allowConsoleErrors (option): extra patterns one test expects, such as + * the 404 it navigates to on purpose. Give it one pattern: Playwright reads + * a two-item array whose second item is an object (a RegExp is one) as + * [value, options], so combine statuses with loggedStatus(401, 429). + */ +import { randomBytes } from "node:crypto"; +import AxeBuilder from "@axe-core/playwright"; +import { + test as base, + expect, + type APIRequestContext, + type ConsoleMessage, + type Page, +} from "@playwright/test"; +import { createSession, startRun, type CreatedSession, type SessionInput } from "./support/api"; +import { NEEDS_DATABASE, hasDatabase, seedDeck, type SeedQuestion } from "./support/db"; +import { settled } from "./support/page"; + +export { expect }; +export * from "./support/api"; +export * from "./support/auth"; +export * from "./support/db"; +export { TIME_ZONE } from "./support/env"; +export * from "./support/lesson"; +export * from "./support/page"; +export * from "./support/time"; + +/** WCAG 2.0, 2.1 and 2.2 at levels A and AA. */ +export const WCAG_TAGS = ["wcag2a", "wcag2aa", "wcag21a", "wcag21aa", "wcag22aa"]; + +/** AxeBuilder for any page (such as `testUserPage`), limited to WCAG_TAGS. */ +export function axeBuilder(page: Page): AxeBuilder { + return new AxeBuilder({ page }).withTags(WCAG_TAGS); +} + +/** + * Run axe (WCAG_TAGS) once the page has settled (no "Loading…" status, no + * animation running), and fail with each violation's rule and elements. + * `state` names the screen in the failure message. + */ +export async function expectNoAxeViolations(page: Page, state = "the page"): Promise<void> { + await settled(page); + const { violations } = await axeBuilder(page).analyze(); + expect( + violations.map((v) => ({ rule: v.id, impact: v.impact, nodes: v.nodes.map((n) => n.target.join(" ")) })), + `axe violations on ${state}`, + ).toEqual([]); +} + +/** storageState for signed-out tests: `test.use({ storageState: SIGNED_OUT })`. */ +export const SIGNED_OUT = { cookies: [], origins: [] }; + +/** + * Console output any test may produce. Keep it short; each entry says why. + * A pattern that hides a real failure belongs in one test's + * `allowConsoleErrors`, not here. + */ +export const CONSOLE_ALLOWLIST: RegExp[] = []; + +/** + * Chromium logs every 4xx and 5xx response as a console error. A test that + * causes them on purpose (a wrong password answers 401) allows them with + * `test.use({ allowConsoleErrors: [loggedStatus(401, 429)] })`. + */ +export function loggedStatus(...statuses: number[]): RegExp { + return new RegExp(`the server responded with a status of (${statuses.join("|")}) `); +} + +/** + * A random address in 2001:db8::/32, the IPv6 documentation range (RFC 3849), + * for X-Forwarded-For. Production builds limit sign-ups (3 an hour), + * sign-ins (10 every 15 minutes) and email links per address, and with no + * proxy in front, `next start` takes the address from X-Forwarded-For. The + * range is far too large for two tests to share an address by chance. + */ +export function documentationAddress(): string { + const hex = () => randomBytes(2).toString("hex"); + return `2001:db8:${hex()}:${hex()}::${hex()}`; +} + +export interface TestUser { + /** The X-User-Id value. */ + id: string; + headers: Record<string, string>; + /** API calls as this user. */ + api: APIRequestContext; +} + +export interface TestAccount { + email: string; + password: string; + /** API calls with the account's session cookie. */ + api: APIRequestContext; + /** A page signed in as the account, with the console guard. */ + page: Page; +} + +export type SeededSession = CreatedSession & { runId: string }; + +type Options = { + allowConsoleErrors: RegExp[]; +}; + +type Fixtures = { + clientAddress: string; + makeAxeBuilder: () => AxeBuilder; + testUser: TestUser; + testUserPage: Page; + account: TestAccount; + seedSession: (input: Omit<SessionInput, "questions"> & { deck: readonly SeedQuestion[] }) => Promise<SeededSession>; +}; + +/** Password for accounts made by the `account` fixture. Test-only. */ +const ACCOUNT_PASSWORD = "e2e-only-Passw0rd"; + +/** Collect console errors and page errors; returns the list to check after the test. */ +function guardConsole(page: Page, allowed: RegExp[]): string[] { + const problems: string[] = []; + const isAllowed = (text: string) => allowed.some((pattern) => pattern.test(text)); + page.on("console", (message: ConsoleMessage) => { + if (message.type() !== "error" || isAllowed(message.text())) return; + const { url, lineNumber } = message.location(); + problems.push(`console.error: ${message.text()}${url ? ` (${url}:${lineNumber})` : ""}`); + }); + page.on("pageerror", (error) => { + if (isAllowed(error.message)) return; + problems.push(`pageerror: ${error.message}`); + }); + return problems; +} + +function assertNoConsoleProblems(problems: string[]): void { + if (problems.length > 0) { + throw new Error(`The page logged ${problems.length} unexpected error(s):\n${problems.join("\n")}`); + } +} + +// The fixture callback is named `provide` (Playwright's docs call it `use`) +// so the React hooks lint rule doesn't mistake it for React's use(). +export const test = base.extend<Options & Fixtures>({ + allowConsoleErrors: [[], { option: true }], + + // Every context and request context the test's own `page` and `request` + // come from sends this test's address. + extraHTTPHeaders: async ({ extraHTTPHeaders }, provide) => { + await provide({ ...extraHTTPHeaders, "X-Forwarded-For": documentationAddress() }); + }, + + clientAddress: async ({ extraHTTPHeaders }, provide) => { + await provide(extraHTTPHeaders?.["X-Forwarded-For"] ?? ""); + }, + + page: async ({ page, allowConsoleErrors }, provide) => { + const problems = guardConsole(page, [...CONSOLE_ALLOWLIST, ...allowConsoleErrors]); + await provide(page); + assertNoConsoleProblems(problems); + }, + + makeAxeBuilder: async ({ page }, provide) => { + await provide(() => axeBuilder(page)); + }, + + testUser: async ({ playwright, baseURL }, provide, testInfo) => { + const id = `e2e-${testInfo.workerIndex}-${randomBytes(4).toString("hex")}`; + const headers = { "X-User-Id": id }; + const api = await playwright.request.newContext({ baseURL, extraHTTPHeaders: headers, storageState: SIGNED_OUT }); + await provide({ id, headers, api }); + await api.dispose(); + }, + + testUserPage: async ({ browser, testUser, allowConsoleErrors }, provide) => { + // browser.newContext() in a test starts from the project's `use` options: + // the device, baseURL, and the signed-in storageState, which would win + // over the test header. So drop the session cookie explicitly. + const context = await browser.newContext({ storageState: SIGNED_OUT, extraHTTPHeaders: testUser.headers }); + const page = await context.newPage(); + const problems = guardConsole(page, [...CONSOLE_ALLOWLIST, ...allowConsoleErrors]); + await provide(page); + await context.close(); + assertNoConsoleProblems(problems); + }, + + // Its own timeout: signing up and signing in hash the password twice (about + // 2 s each with bcryptjs at cost 12), which shouldn't eat into the test's time. + account: [ + async ({ playwright, browser, baseURL, allowConsoleErrors }, provide) => { + const email = `e2e-${randomBytes(5).toString("hex")}@studybot.test`; + // An address of its own, apart from the test's clientAddress, so creating + // the account never uses up the test's sign-in attempts. + const headers = { "X-Forwarded-For": documentationAddress() }; + const api = await playwright.request.newContext({ baseURL, extraHTTPHeaders: headers, storageState: SIGNED_OUT }); + + const signUp = await api.post("/api/auth/signup", { data: { name: "E2E Account", email, password: ACCOUNT_PASSWORD } }); + expect(signUp.status(), await signUp.text()).toBe(201); + const { csrfToken } = await (await api.get("/api/auth/csrf")).json(); + const signIn = await api.post("/api/auth/callback/credentials", { + form: { csrfToken, email, password: ACCOUNT_PASSWORD, json: "true" }, + }); + expect(signIn.ok(), await signIn.text()).toBe(true); + const session = await (await api.get("/api/auth/session")).json(); + expect(session?.user?.email).toBe(email); + + // The project's device and baseURL, with this account's session instead of the shared one. + const context = await browser.newContext({ extraHTTPHeaders: headers, storageState: await api.storageState() }); + const page = await context.newPage(); + const problems = guardConsole(page, [...CONSOLE_ALLOWLIST, ...allowConsoleErrors]); + await provide({ email, password: ACCOUNT_PASSWORD, api, page }); + await context.close(); + await api.dispose(); + assertNoConsoleProblems(problems); + }, + { timeout: 30_000 }, + ], + + seedSession: async ({ request }, provide, testInfo) => { + testInfo.skip(!hasDatabase, NEEDS_DATABASE); + await provide(async ({ deck, ...input }) => { + const session = await createSession(request, { ...input, questions: deck.length }); + const run = await startRun(request, session.id); + await seedDeck(run.run_id, deck); + return { ...session, runId: run.run_id }; + }); + }, +}); diff --git a/e2e/google-calendar.spec.ts b/e2e/google-calendar.spec.ts deleted file mode 100644 index 7cb0b8d2..00000000 --- a/e2e/google-calendar.spec.ts +++ /dev/null @@ -1,201 +0,0 @@ -/** - * E2E tests for Google Calendar integration. - * - * Tests API-level flows: status, freebusy, calendars, publish/unpublish. - * Uses FakeGoogleCalendarClient injected at server level. - */ -import { test, expect } from "@playwright/test"; - -const BASE = process.env.BASE_URL || "http://localhost:3000"; -const userId = "e2e_gcal_user"; - -// E2E tests run against the actual server — these test API responses -test.describe("Google Calendar API", () => { - test.use({ extraHTTPHeaders: { "X-User-Id": userId } }); - - test("GET /api/integrations/google/status returns not connected for unknown user", async ({ - request, - }) => { - const res = await request.get(`${BASE}/api/integrations/google/status`); - expect(res.status()).toBe(200); - const body = await res.json(); - expect(body.connected).toBe(false); - expect(body.scopes).toEqual([]); - }); - - test("POST /api/integrations/google/freebusy returns 400 when not connected", async ({ - request, - }) => { - const res = await request.post(`${BASE}/api/integrations/google/freebusy`, { - data: { - timeMin: "2026-04-01T00:00:00Z", - timeMax: "2026-04-01T23:59:59Z", - }, - }); - expect(res.status()).toBe(400); - const body = await res.json(); - expect(body.error).toContain("not connected"); - }); - - test("GET /api/integrations/google/calendars returns 400 when not connected", async ({ - request, - }) => { - const res = await request.get(`${BASE}/api/integrations/google/calendars`); - expect(res.status()).toBe(400); - }); - - test("POST /api/integrations/google/disconnect succeeds even when not connected", async ({ - request, - }) => { - const res = await request.post( - `${BASE}/api/integrations/google/disconnect` - ); - expect(res.status()).toBe(200); - const body = await res.json(); - expect(body.disconnected).toBe(true); - }); -}); - -test.describe("Google Calendar - Plan with availability", () => { - test.use({ extraHTTPHeaders: {} }); - - test("POST /api/plans returns 401 without user id", async ({ request }) => { - const res = await request.post(`${BASE}/api/plans`, { - data: { - course_name: "Test", - exam_name: "Test", - exam_date: "2026-06-15", - objectives: ["A", "B", "C"], - availability: Array.from({ length: 7 }, () => ({ - start: "09:00", - end: "17:00", - })), - use_google_availability: true, - }, - }); - expect(res.status()).toBe(401); - }); -}); - -test.describe("Google Calendar - Plan with user", () => { - test.use({ extraHTTPHeaders: { "X-User-Id": userId } }); - - test("POST /api/plans with use_google_availability works (no integration = fallback)", async ({ - request, - }) => { - const res = await request.post(`${BASE}/api/plans`, { - data: { - course_name: "E2E GCAL", - exam_name: "Final", - exam_date: "2026-06-15", - objectives: [ - "OAuth flow", - "Calendar API", - "Free busy", - "Scheduling", - "UI integration", - ], - availability: Array.from({ length: 7 }, () => ({ - start: "09:00", - end: "17:00", - })), - daily_study_cap_minutes: 120, - break_protocol_default: "50_10", - use_google_availability: true, - }, - }); - expect(res.status()).toBe(201); - const body = await res.json(); - expect(body.plan_id).toBeTruthy(); - expect(body.items.length).toBeGreaterThan(0); - }); -}); - -test.describe("Google Calendar - Publish/Unpublish", () => { - test.use({ extraHTTPHeaders: { "X-User-Id": userId } }); - - test("POST publish returns 409 when Google not connected", async ({ request }) => { - // First create a plan - const planRes = await request.post(`${BASE}/api/plans`, { - data: { - course_name: "E2E Publish", - exam_name: "Final", - exam_date: "2026-06-15", - objectives: ["Publish test", "Unpublish test", "Status test"], - availability: Array.from({ length: 7 }, () => ({ start: "09:00", end: "17:00" })), - daily_study_cap_minutes: 120, - break_protocol_default: "50_10", - }, - }); - expect(planRes.status()).toBe(201); - const plan = await planRes.json(); - - // Publish should fail — no Google integration for this user - const pubRes = await request.post(`${BASE}/api/plans/${plan.plan_id}/publish/google`, { - data: {}, - }); - expect(pubRes.status()).toBe(409); - const pubBody = await pubRes.json(); - expect(pubBody.error).toBe("GOOGLE_NOT_CONNECTED"); - }); - - test("GET publish status returns null publication when not published", async ({ request }) => { - const planRes = await request.post(`${BASE}/api/plans`, { - data: { - course_name: "E2E Status", - exam_name: "Final", - exam_date: "2026-06-15", - objectives: ["Status check A", "Status check B", "Status check C"], - availability: Array.from({ length: 7 }, () => ({ start: "09:00", end: "17:00" })), - daily_study_cap_minutes: 120, - break_protocol_default: "50_10", - }, - }); - const plan = await planRes.json(); - - const statusRes = await request.get(`${BASE}/api/plans/${plan.plan_id}/publish/google`); - expect(statusRes.status()).toBe(200); - const status = await statusRes.json(); - expect(status.publication).toBeNull(); - expect(status.items).toEqual([]); - }); - - test("POST publish returns 404 for nonexistent plan", async ({ request }) => { - const res = await request.post(`${BASE}/api/plans/nonexistent/publish/google`, { - data: {}, - }); - expect(res.status()).toBe(404); - }); - - test("POST unpublish returns 409 when Google not connected", async ({ request }) => { - const planRes = await request.post(`${BASE}/api/plans`, { - data: { - course_name: "E2E Unpub", - exam_name: "Final", - exam_date: "2026-06-15", - objectives: ["Unpublish A", "Unpublish B", "Unpublish C"], - availability: Array.from({ length: 7 }, () => ({ start: "09:00", end: "17:00" })), - daily_study_cap_minutes: 120, - break_protocol_default: "50_10", - }, - }); - const plan = await planRes.json(); - - const res = await request.post(`${BASE}/api/plans/${plan.plan_id}/unpublish/google`, { - data: {}, - }); - expect(res.status()).toBe(409); - }); - -}); - -test.describe("Google Calendar - Auth enforcement", () => { - test.use({ extraHTTPHeaders: {} }); - - test("POST publish returns 401 without auth header", async ({ request }) => { - const res = await request.post(`${BASE}/api/plans/some-plan/publish/google`, { - data: {}, - }); - expect(res.status()).toBe(401); - }); -}); diff --git a/e2e/guides.spec.ts b/e2e/guides.spec.ts new file mode 100644 index 00000000..dbebe0bf --- /dev/null +++ b/e2e/guides.spec.ts @@ -0,0 +1,181 @@ +/** + * Study guides (/guides): Generate guide with the mock AI, the three format + * tabs (keyboard included) with their sections rendered as headings and + * text, the ?format= deep link, Export guide (.md), Delete guide with its + * confirmation, and the course it opens on when none is chosen. Each test + * seeds its own identity, which also gives it its own AI rate limit (5 a + * minute). + * + * Already covered elsewhere: section cleanup, Markdown export and file + * names in src/__tests__/guide-format.test.ts, and listing in + * study-guides-list.test.ts. The mock AI's guides hold plain text only, so + * Markdown lists and tables inside a section can't be reached here. + */ +import { readFile } from "node:fs/promises"; +import type { APIRequestContext } from "@playwright/test"; +import { test, expect, createGuide, createPlan, toasts, unique, uploadMaterial } from "./fixtures"; + +const NOTES = "Recursion: a function that calls itself on a smaller input until it reaches a base case."; + +async function listGuides(api: APIRequestContext, course: string): Promise<{ id: string; guide_type: string }[]> { + const response = await api.get(`/api/guides?course_name=${encodeURIComponent(course)}`); + expect(response.status()).toBe(200); + return (await response.json()).guides; +} + +test("Generate guide writes a key concepts guide from the course's materials", { tag: "@mobile" }, async ({ + testUserPage: page, + testUser, +}) => { + const course = unique("E2E Guides"); + await uploadMaterial(testUser.api, { course, text: NOTES }); + + await page.goto("/guides"); + await expect(page.getByRole("tab", { name: "Key concepts" })).toHaveAttribute("aria-selected", "true"); + const panel = page.getByRole("tabpanel", { name: "Key concepts" }); + await expect(panel.getByRole("heading", { level: 2, name: `No key concepts guide for ${course} yet` })).toBeVisible(); + + await panel.getByRole("button", { name: "Generate guide" }).click(); + const article = panel.getByRole("article", { name: `Key concepts for ${course}` }); + // The new guide takes focus at its title. + await expect(article.getByRole("heading", { level: 2 })).toBeFocused(); + await expect(article).toContainText("AI-written"); + await expect(article).toContainText(`Written by AI from your ${course} materials. Check it against your files.`); + await expect(article.getByRole("heading", { level: 3 })).toHaveText(["Core principles", "Applied methods"]); + await expect(article.getByText("Why it matters: Every later topic assumes them.")).toBeVisible(); + await expect(page).toHaveURL(/\/guides\?format=key-concepts&guide=[\w-]+$/); + expect((await listGuides(testUser.api, course)).map((g) => g.guide_type)).toEqual(["KEY_CONCEPTS"]); +}); + +test("each format has its own tab, reachable with the arrow keys and by link", async ({ + testUserPage: page, + testUser, +}) => { + test.slow(); + const course = unique("E2E Formats"); + await uploadMaterial(testUser.api, { course, text: NOTES }); + await page.goto("/guides"); + const tabs = page.getByRole("tablist", { name: "Guide format" }); + await expect(tabs.getByRole("tab")).toHaveText(["Key concepts", "FAQ", "Cheat sheet"]); + + await test.step("FAQ", async () => { + await tabs.getByRole("tab", { name: "Key concepts" }).press("ArrowRight"); + await expect(tabs.getByRole("tab", { name: "FAQ" })).toBeFocused(); + await expect(tabs.getByRole("tab", { name: "FAQ" })).toHaveAttribute("aria-selected", "true"); + const panel = page.getByRole("tabpanel", { name: "FAQ" }); + await expect(panel.getByRole("heading", { level: 2, name: `No FAQ for ${course} yet` })).toBeVisible(); + await panel.getByRole("button", { name: "Generate guide" }).click(); + const article = panel.getByRole("article", { name: `FAQ for ${course}` }); + await expect(article.getByRole("heading", { level: 3 })).toHaveText([ + "What are the core concepts?", + "How are these concepts applied?", + ]); + }); + + await test.step("Cheat sheet", async () => { + await tabs.getByRole("tab", { name: "FAQ" }).press("ArrowRight"); + await expect(tabs.getByRole("tab", { name: "Cheat sheet" })).toHaveAttribute("aria-selected", "true"); + const panel = page.getByRole("tabpanel", { name: "Cheat sheet" }); + await panel.getByRole("button", { name: "Generate guide" }).click(); + const article = panel.getByRole("article", { name: `Cheat sheet for ${course}` }); + await expect(article.getByRole("heading", { level: 3 })).toHaveText(["Key definitions", "Formulas"]); + await expect(article.getByText("Term 1: Definition of the first key concept")).toBeVisible(); + await expect(article.getByText("Formula 2: X = Y * Z")).toBeVisible(); + }); + + await test.step("the link opens the same tab and guide", async () => { + await expect(page).toHaveURL(/\?format=cheat-sheet&guide=[\w-]+$/); + await page.reload(); + await expect(tabs.getByRole("tab", { name: "Cheat sheet" })).toHaveAttribute("aria-selected", "true"); + await expect( + page.getByRole("tabpanel", { name: "Cheat sheet" }).getByRole("heading", { level: 2, name: `Cheat sheet for ${course}` }), + ).toBeVisible(); + }); + expect((await listGuides(testUser.api, course)).map((g) => g.guide_type).sort()).toEqual(["CHEAT_SHEET", "FAQ"]); +}); + +test("Export guide (.md) downloads the guide as Markdown", async ({ testUserPage: page, testUser }) => { + const course = unique("E2E Export guide"); + await uploadMaterial(testUser.api, { course, text: NOTES }); + await createGuide(testUser.api, course, "KEY_CONCEPTS"); + + await page.goto("/guides"); + const article = page.getByRole("article", { name: `Key concepts for ${course}` }); + const download = page.waitForEvent("download"); + await article.getByRole("button", { name: "Export guide (.md)" }).click(); + const file = await download; + const slug = `key concepts for ${course}`.toLowerCase().replace(/\s+/g, "-"); + expect(file.suggestedFilename()).toBe(`${slug}.md`); + + const markdown = await readFile(await file.path(), "utf8"); + expect(markdown.startsWith(`# Key concepts for ${course}\n`)).toBe(true); + expect(markdown).toContain("## Core principles\nThe ideas the rest of the course material builds on."); + expect(markdown).toContain("_Why it matters: Every later topic assumes them._"); + expect(markdown).toContain("\n---\n\n## Applied methods"); +}); + +test("Delete guide asks first and removes the guide", { tag: "@mobile" }, async ({ testUserPage: page, testUser }) => { + const course = unique("E2E Delete guide"); + await uploadMaterial(testUser.api, { course, text: NOTES }); + await createGuide(testUser.api, course, "KEY_CONCEPTS"); + + await page.goto("/guides"); + const panel = page.getByRole("tabpanel", { name: "Key concepts" }); + const remove = panel.getByRole("button", { name: "Delete guide" }); + const dialog = page.getByRole("alertdialog", { name: `Delete Key concepts for ${course}?` }); + + await test.step("Cancel keeps it", async () => { + await remove.click(); + await expect(dialog).toContainText("This deletes the guide and its 2 sections. Your materials and other guides stay."); + await dialog.getByRole("button", { name: "Cancel" }).click(); + await expect(dialog).toBeHidden(); + expect(await listGuides(testUser.api, course)).toHaveLength(1); + }); + + await remove.click(); + await dialog.getByRole("button", { name: "Delete guide" }).click(); + await expect(dialog).toBeHidden(); + await expect(toasts(page)).toContainText("Guide deleted"); + await expect(panel.getByRole("heading", { level: 2, name: `No key concepts guide for ${course} yet` })).toBeVisible(); + // The opener left with the guide, so focus lands on the panel. + await expect(panel).toBeFocused(); + await expect(page).not.toHaveURL(/guide=/); + expect(await listGuides(testUser.api, course)).toEqual([]); +}); + +test("Cancel or Escape on Delete guide returns focus to the Delete guide button", async ({ testUserPage: page, testUser }) => { + const course = unique("E2E Guide focus"); + await uploadMaterial(testUser.api, { course, text: NOTES }); + await createGuide(testUser.api, course, "KEY_CONCEPTS"); + + await page.goto("/guides"); + const remove = page.getByRole("tabpanel", { name: "Key concepts" }).getByRole("button", { name: "Delete guide" }); + const dialog = page.getByRole("alertdialog", { name: `Delete Key concepts for ${course}?` }); + await remove.click(); + await dialog.getByRole("button", { name: "Cancel" }).click(); + await expect(dialog).toBeHidden(); + await expect(remove).toBeFocused(); + + await remove.press("Enter"); + await expect(dialog).toBeVisible(); + await page.keyboard.press("Escape"); + await expect(dialog).toBeHidden(); + await expect(remove).toBeFocused(); +}); + +test("with no course chosen, Study guides open on the course with the nearest exam, not the latest upload", async ({ + testUserPage: page, + testUser, +}) => { + const examCourse = unique("E2E Exam soon"); + const latestCourse = unique("E2E Latest upload"); + await uploadMaterial(testUser.api, { course: examCourse, text: NOTES }); + await createPlan(testUser.api, { course_name: examCourse, exam_in_days: 7 }); + // Uploaded last, so it heads the course list. + await uploadMaterial(testUser.api, { course: latestCourse, text: NOTES }); + + await page.goto("/guides"); + await expect(page.getByRole("combobox", { name: "Course" })).toHaveText(examCourse); + const panel = page.getByRole("tabpanel", { name: "Key concepts" }); + await expect(panel.getByRole("heading", { level: 2, name: `No key concepts guide for ${examCourse} yet` })).toBeVisible(); +}); diff --git a/e2e/home.spec.ts b/e2e/home.spec.ts new file mode 100644 index 00000000..8e01f74b --- /dev/null +++ b/e2e/home.spec.ts @@ -0,0 +1,173 @@ +/** + * Home for one student: the first-run card, exam countdowns with plan + * progress, the Today card and the shell's Start session button, weak + * spots, and the quiet stats line. Each test seeds its own identity through + * the API, because Home shows everything on the account. + * + * Already covered elsewhere: the countdown and today maths in + * src/__tests__/home-model.test.ts, and Home's empty-state axe scan in + * shell.spec.ts. The filled Home is scanned in a11y-app.spec.ts. + */ +import { + test, + expect, + MODE_LABELS, + answerRun, + createPlan, + createSession, + finishSession, + hydrated, + morningZone, + openWhen, + setItemStatus, + unique, +} from "./fixtures"; + +test("a new student's Home leads to materials and a first plan", { tag: "@mobile" }, async ({ testUserPage: page }) => { + await page.goto("/"); + const firstRun = page.getByRole("region", { name: "Plan for your first exam" }); + // The steps follow the form the one link opens: course and exam first, then materials. + await expect(firstRun.getByRole("listitem")).toHaveText([ + /^Create a plan/, + /^Upload your materials\s*On the same form/, + /^Answer from memory/, + ]); + // No countdowns or weak spots before there is anything to count. + await expect(page.getByRole("region", { name: "Exams" })).toHaveCount(0); + + // "New plan" is the link to the form; "Create plan" is only the form's submit button. + await expect(firstRun.getByRole("link")).toHaveText(["New plan"]); + await firstRun.getByRole("link", { name: "New plan" }).click(); + await expect(page).toHaveURL(/\/plan\/new$/); + await expect(page.getByRole("heading", { level: 1 })).toHaveText("New plan"); + await expect(page.getByRole("button", { name: "Create plan" })).toBeVisible(); + await expect(page.getByRole("group", { name: "Upload materials" })).toBeVisible(); +}); + +test("exam countdowns show the days left and plan progress, nearest exam first", async ({ + testUserPage: page, + testUser, +}) => { + const later = await createPlan(testUser.api, { course_name: unique("E2E Home"), exam_name: "Final", exam_in_days: 20 }); + await createPlan(testUser.api, { course_name: unique("E2E Home"), exam_name: "Prelim 2", exam_in_days: 3 }); + // One session done and one missed in the later plan. + await setItemStatus(testUser.api, later.id, later.items[0].id, "DONE"); + await setItemStatus(testUser.api, later.id, later.items[1].id, "MISSED"); + + await page.goto("/"); + const exams = page.getByRole("region", { name: "Exams" }); + await expect(exams).toMatchAriaSnapshot(` + - list: + - listitem: + - article "Prelim 2 is in 3 days" + - listitem: + - article "Final is in 20 days" + `); + + const final = exams.getByRole("article", { name: "Final is in 20 days" }); + await expect(final.getByText(later.course, { exact: true })).toBeVisible(); + await expect(final.getByRole("progressbar", { name: "Final plan progress" })).toHaveAttribute( + "aria-valuetext", + `1 of ${later.items.length} sessions done`, + ); + await expect(final.getByText("1 missed", { exact: true })).toBeVisible(); + + // Reschedule on the card opens the plan's preview. + await final.getByRole("link", { name: "Reschedule" }).click(); + await expect(page).toHaveURL(new RegExp(`/plan\\?plan=${later.id}&reschedule=1$`)); + await expect(page.getByRole("dialog", { name: "Reschedule sessions" })).toBeVisible(); +}); + +test("the Today card starts today's first session", { tag: "@mobile" }, async ({ testUserPage: page, testUser }) => { + const plan = await createPlan(testUser.api, { + course_name: unique("E2E Today"), + exam_name: "Prelim 1", + time_zone: morningZone(), + all_day: true, + }); + const first = plan.items[0]; + + await page.goto("/"); + const today = page.getByRole("region", { name: "Today" }); + await expect(today.getByRole("heading", { level: 3, name: MODE_LABELS[first.mode] })).toBeVisible(); + await expect(today.getByText(`${plan.course}, ${plan.exam}`)).toBeVisible(); + await expect(today.getByRole("link", { name: "Open plan" })).toHaveAttribute("href", "/plan"); + + await today.getByRole("link", { name: "Start session" }).click(); + await expect(page).toHaveURL(new RegExp(`/s/${first.session_id}$`)); + await expect(page.getByRole("heading", { level: 1 })).toContainText(`${MODE_LABELS[first.mode]}:`); + await expect(page.getByRole("button", { name: "Start session" })).toBeEnabled(); +}); + +test("the Start button opens today's session from other screens", { tag: "@mobile" }, async ({ + testUserPage: page, + testUser, + isMobile, +}) => { + const plan = await createPlan(testUser.api, { course_name: unique("E2E Start"), time_zone: morningZone(), all_day: true }); + const first = plan.items[0]; + const start = page.getByRole("link", { name: "Start today's session" }); + + await page.goto("/"); + // Wide screens keep it in the rail; phones leave Home's corner to the Today card. + await expect(start).toHaveCount(isMobile ? 0 : 1); + + await page.goto("/guides"); + await expect(page.getByRole("heading", { level: 1 })).toHaveText("Study guides"); + await expect(start).toHaveAttribute("data-placement", isMobile ? "floating" : "rail"); + await expect(start).toHaveAttribute("href", `/s/${first.session_id}`); + await start.click(); + await expect(page).toHaveURL(new RegExp(`/s/${first.session_id}$`)); + await expect(page.getByRole("heading", { level: 1 })).toContainText(`${MODE_LABELS[first.mode]}:`); +}); + +test("weak spots offer a repair session and practice for a weak topic", async ({ testUserPage: page, testUser }) => { + test.slow(); + const course = unique("E2E Weak"); + await createPlan(testUser.api, { course_name: course, objectives: ["Recursion", "Arrays", "Sorting"] }); + // Every answer on Recursion wrong: its errors stay unresolved and its mastery drops. + const session = await createSession(testUser.api, { + course_name: course, + topic_scope: "Recursion", + objectives: [{ id: "recursion", title: "Recursion" }], + }); + await answerRun(testUser.api, session.id, [{ score: "INCORRECT" }]); + + const weakSpots = page.getByRole("region", { name: "Weak spots" }); + // Mastery is written just after the run completes. + await openWhen(page, "/", weakSpots.getByRole("meter", { name: "Recursion mastery" })); + const repair = page.getByRole("button", { name: `Repair ${course} errors` }); + const errorRow = weakSpots.getByRole("listitem").filter({ has: repair }); + await expect(errorRow).toContainText(course); + await expect(errorRow).toContainText(/\d+ unresolved errors?/); + const topicRow = weakSpots.getByRole("listitem").filter({ has: page.getByRole("button", { name: "Practice Recursion" }) }); + await expect(topicRow.getByRole("meter", { name: "Recursion mastery" })).toBeVisible(); + await expect(topicRow).toContainText(course); + + const repairButton = errorRow.getByRole("button", { name: `Repair ${course} errors` }); + await hydrated(repairButton); + await repairButton.click(); + await expect(page).toHaveURL(/\/s\/[\w-]+$/); + await expect(page.getByRole("heading", { level: 1 })).toHaveText("Error repair: Unresolved errors"); +}); + +test("the stats line reports the streak, accuracy and time from the last 7 days", async ({ + testUserPage: page, + testUser, +}) => { + const course = unique("E2E Stats"); + await createPlan(testUser.api, { course_name: course }); + const session = await createSession(testUser.api, { course_name: course }); + await finishSession(testUser.api, session.id); + + const stats = page.getByRole("region", { name: "Study stats" }); + // XP, and with it the streak, is written just after the run completes. + await openWhen(page, "/", stats.getByText("1-day streak")); + await expect(stats).toMatchAriaSnapshot(` + - list: + - listitem: 1-day streak + - listitem: /100%\\s*accuracy, last 7 days/ + - listitem: /Under 1 min\\s*answering questions, last 7 days/ + - link "See progress" + `); +}); diff --git a/e2e/knowledge-layer.spec.ts b/e2e/knowledge-layer.spec.ts deleted file mode 100644 index 84a640db..00000000 --- a/e2e/knowledge-layer.spec.ts +++ /dev/null @@ -1,211 +0,0 @@ -import { test, expect } from "@playwright/test"; -import pg from "pg"; - -const BASE_URL = process.env.BASE_URL || "http://localhost:3000"; -const USER_ID = "e2e_test_user"; -const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL }); - -// Playwright context headers ride on every browser request, so app fetches -// authenticate as the test user (clients no longer send identity headers). -test.use({ extraHTTPHeaders: { "X-User-Id": USER_ID } }); - -test.describe.serial("Knowledge Layer — Leak Prevention", () => { - const COURSE = "E2E_CS_KL"; - const RECOGNIZABLE = "Dijkstra shortest path algorithm uses a priority queue to greedily select minimum distance vertices"; - let sessionId: string; - - test.afterAll(async () => { - await pool.end(); - }); - - test("setup: upload doc, create session, start run", async ({ request }) => { - // Deterministic deck: seed mastery so the new objective doesn't get a - // PRE_TEST diagnostic prepended (pretest prompts skip the error-log form - // by design, which this spec's INCORRECT flow depends on), and purge any - // error logs left by a previous attempt (retries keep the DB). - await pool.query( - `INSERT INTO objective_mastery (id, user_id, course_name, objective_key, updated_at) - VALUES (gen_random_uuid(), $1, $2, $3, NOW()) - ON CONFLICT (user_id, course_name, objective_key) DO NOTHING`, - [USER_ID, COURSE, "obj_graphs"] - ); - await pool.query(`DELETE FROM session_error_logs WHERE user_id = $1`, [USER_ID]); - - // Upload a doc with recognizable content - const docContent = `Introduction to Graph Algorithms\n\n${RECOGNIZABLE}\n\nThe algorithm maintains a set of visited vertices and relaxes edges.\n\nBellman-Ford handles negative weights but is slower.\n\nFloyd-Warshall computes all-pairs shortest paths.`; - - const uploadRes = await request.post(`${BASE_URL}/api/content/documents`, { - headers: { "X-User-Id": USER_ID }, - multipart: { - file: { - name: "graphs.txt", - mimeType: "text/plain", - buffer: Buffer.from(docContent), - }, - namespace: "COURSE", - course_name: COURSE, - }, - }); - expect([200, 201]).toContain(uploadRes.status()); - const uploadData = await uploadRes.json(); - const docId = uploadData.document_id; - - // Process - const processRes = await request.post(`${BASE_URL}/api/content/documents/${docId}/process`, { - headers: { "Content-Type": "application/json", "X-User-Id": USER_ID }, - }); - expect(processRes.status()).toBe(200); - - // Create a RETRIEVAL session - const sessionRes = await request.post(`${BASE_URL}/api/sessions`, { - headers: { "Content-Type": "application/json", "X-User-Id": USER_ID }, - data: { - course_name: COURSE, - exam_name: "Final", - mode: "RETRIEVAL", - topic_scope: "Graph algorithms", - planned_minutes: 30, - objectives: [{ id: "obj_graphs", title: "Dijkstra shortest path" }], - target_outcome: { prompt_count: 3 }, - }, - }); - expect(sessionRes.status()).toBe(201); - const sessionData = await sessionRes.json(); - sessionId = sessionData.session_id; - }); - - test("review panel NOT visible before submitting answer", async ({ page }) => { - const sessionUrl = `${BASE_URL}/s/${sessionId}`; - await page.goto(sessionUrl); - - await page.getByRole("button", { name: /start session|resume session/i }).click(); - - // Wait for the prompt to appear - await expect(page.locator("textarea")).toBeVisible({ timeout: 10000 }); - - // Assert: review panel is NOT visible (strict no-leakage) - await expect(page.locator('[data-testid="review-panel"]')).not.toBeVisible(); - // Also assert no text from our recognizable doc is shown - const pageText = await page.textContent("body"); - expect(pageText).not.toContain("priority queue"); - }); - - test("review panel appears after INCORRECT scoring with deferred feedback", async ({ page }) => { - const sessionUrl = `${BASE_URL}/s/${sessionId}`; - await page.goto(sessionUrl); - - await page.getByRole("button", { name: /start session|resume session/i }).click(); - - // Wait for prompt - await expect(page.locator("textarea")).toBeVisible({ timeout: 10000 }); - - // Type answer - await page.locator("textarea").first().fill("I think Dijkstra uses BFS"); - await page.getByRole("button", { name: /submit answer/i }).click(); - - // Score as INCORRECT - await page.getByRole("button", { name: "✗ Incorrect" }).click(); - - // Fill correction rule (required) - const textareas = page.locator("textarea"); - await textareas.nth(0).fill("Dijkstra uses a priority queue not plain BFS"); - - // Submit error log - await page.getByRole("button", { name: /save/i }).click(); - - // The review panel should appear with deferred feedback loading - const reviewPanel = page.locator('[data-testid="review-panel"]'); - const visible = await reviewPanel.isVisible({ timeout: 8000 }).catch(() => false); - - if (visible) { - // Phase 1: deferred feedback — check for loading state or excerpts - const panelText = await reviewPanel.textContent(); - expect(panelText).toBeTruthy(); - // Should contain the review header - expect(panelText).toContain("REVIEW"); - } - // If not visible, that's acceptable — feedback is best-effort - }); - - test("attempt response does not leak feedback data (API-level check)", async ({ request }) => { - // Create a fresh session for this test - const sessionRes = await request.post(`${BASE_URL}/api/sessions`, { - headers: { "Content-Type": "application/json", "X-User-Id": USER_ID }, - data: { - course_name: COURSE, - exam_name: "Final", - mode: "RETRIEVAL", - topic_scope: "Graph algorithms", - planned_minutes: 30, - target_outcome: { prompt_count: 2 }, - }, - }); - expect(sessionRes.status()).toBe(201); - const sessData = await sessionRes.json(); - - // Start run - const startRes = await request.post(`${BASE_URL}/api/sessions/${sessData.session_id}/runs/start`, { - headers: { "Content-Type": "application/json", "X-User-Id": USER_ID }, - }); - expect(startRes.status()).toBe(201); - const runData = await startRes.json(); - - // Phase 2: verify current_prompt and prompt_count - expect(runData.current_prompt).toBeDefined(); - expect(runData.prompt_count).toBeDefined(); - expect(runData.current_prompt.text).toBeTruthy(); - - // Submit INCORRECT attempt - const attemptRes = await request.post(`${BASE_URL}/api/runs/${runData.run_id}/attempt`, { - headers: { "Content-Type": "application/json", "X-User-Id": USER_ID }, - data: { - prompt_index: 0, - user_answer: "wrong", - self_score: "INCORRECT", - time_to_answer_seconds: 3, - error_log: { - error_type: "MEMORY", - correction_rule: "The correct approach is...", - }, - }, - }); - expect(attemptRes.status()).toBe(200); - const attemptData = await attemptRes.json(); - - // Phase 1: verify deferred feedback fields - expect(attemptData.attempt_id).toBeTruthy(); - expect(attemptData.feedback_status).toBe("PENDING"); - - // No-leakage: response MUST NOT contain feedback excerpts - const raw = JSON.stringify(attemptData); - expect(raw).not.toContain('"snippets"'); - expect(raw).not.toContain('"doc_title"'); - - // Phase 1: now call the deferred feedback endpoint. Generation starts - // eagerly at submit time, so PENDING is a valid transient state — poll - // like the client does. - let feedbackData: { status: string } = { status: "PENDING" }; - for (let i = 0; i < 30; i++) { - const feedbackRes = await request.get( - `${BASE_URL}/api/attempts/${attemptData.attempt_id}/feedback`, - { headers: { "X-User-Id": USER_ID } } - ); - expect(feedbackRes.status()).toBe(200); - feedbackData = await feedbackRes.json(); - if (feedbackData.status !== "PENDING") break; - await new Promise((r) => setTimeout(r, 300)); - } - expect(["OK", "UNAVAILABLE"]).toContain(feedbackData.status); - - // Phase 2: verify prompt endpoint works - const promptRes = await request.get( - `${BASE_URL}/api/runs/${runData.run_id}/prompt?index=1`, - { headers: { "X-User-Id": USER_ID } } - ); - expect(promptRes.status()).toBe(200); - const promptData = await promptRes.json(); - expect(promptData.text).toBeTruthy(); - expect(promptData.prompt_index).toBe(1); - }); -}); - diff --git a/e2e/lesson-keyboard.spec.ts b/e2e/lesson-keyboard.spec.ts new file mode 100644 index 00000000..811c7a33 --- /dev/null +++ b/e2e/lesson-keyboard.spec.ts @@ -0,0 +1,244 @@ +/** + * The lesson by keyboard alone: a whole short session, number keys for + * the choices and Q, W and E for confidence (as the key hints show), + * Ctrl+Enter for written answers and corrections, 1 to 3 to score, Enter + * to move on, keys typed into an answer staying in the answer, and the + * keyboard shortcuts popover with its switch for single-key shortcuts. + * + * The key map itself is unit-tested (src/components/session/runner/hotkeys + * and use-question-hotkeys); this spec checks the keys reach the real + * screens. Before any key press the test waits for the focus the screen + * sets on mount, which also means its key listener is in place. + * + * Multiple-choice questions come from a seeded deck (the `seedSession` + * fixture), because the mock AI never writes a deck; those tests need + * DATABASE_URL and skip without it (see support/db.ts). + */ +import type { APIRequestContext, Locator, Page } from "@playwright/test"; +import { + test, + expect, + QUESTIONS, + answerBox, + confidenceRadio, + createSession, + getJson, + hydrated, + questionCounter, + unique, + type SeedQuestion, +} from "./fixtures"; + +const { baseCase: BASE_CASE, overflow: OVERFLOW, recursiveCase: RECURSIVE_CASE } = QUESTIONS; + +interface StoredAttempt { + self_score: string | null; + confidence_rating: number | null; +} + +/** The run's stored attempts. */ +async function storedAttempts(api: APIRequestContext, runId: string): Promise<StoredAttempt[]> { + return (await getJson<{ attempts: StoredAttempt[] }>(api, `/api/runs/${runId}`)).attempts; +} + +const options = (page: Page, question: SeedQuestion) => page.getByRole("group", { name: question.text }); + +const shortcutsDialog = (page: Page) => page.getByRole("dialog", { name: "Keyboard shortcuts" }); + +/** Press Tab once per stop, checking that each one takes focus in turn. */ +async function tabTo(page: Page, stops: Locator[]) { + for (const stop of stops) { + await page.keyboard.press("Tab"); + await expect(stop).toBeFocused(); + } +} + +test("a whole short session by keyboard alone", async ({ page, request, seedSession }) => { + test.slow(); + const session = await seedSession({ course_name: unique("E2E Keys"), deck: [BASE_CASE, RECURSIVE_CASE] }); + await page.goto(session.url); + await hydrated(page.getByRole("button", { name: "Resume session" })); + + await test.step("Tab reaches Resume session after the skip link and Leave session", async () => { + await tabTo(page, [ + page.getByRole("link", { name: "Skip to main content" }), + page.getByRole("link", { name: "Leave session" }), + page.getByRole("button", { name: "Resume session" }), + ]); + await page.keyboard.press("Enter"); + }); + + await test.step("multiple choice: 1 picks, W rates Unsure, Enter submits and Enter moves on", async () => { + await expect(options(page, BASE_CASE).getByRole("radio").first()).toBeFocused(); + await page.keyboard.press("1"); + await page.keyboard.press("w"); + await expect(options(page, BASE_CASE).getByRole("radio", { name: "The base case" })).toBeChecked(); + await expect(confidenceRadio(page, "Unsure")).toBeChecked(); + await page.keyboard.press("Enter"); + + const next = page.getByRole("region", { name: "Correct", exact: true }).getByRole("button", { name: "Next question" }); + await expect(next).toBeFocused(); + await page.keyboard.press("Enter"); + }); + + await test.step("free recall: type, Ctrl+Enter shows the model answer, 1 scores it Correct", async () => { + await expect(questionCounter(page, 2, 2)).toBeVisible(); + await expect(answerBox(page)).toBeFocused(); + await page.keyboard.type("It calls itself on a smaller input"); + await page.keyboard.press("ControlOrMeta+Enter"); + await expect(page.getByRole("region", { name: "Model answer" })).toBeVisible(); + await page.keyboard.press("1"); + + const results = page.getByRole("region", { name: "Correct", exact: true }).getByRole("button", { name: "See results" }); + await expect(results).toBeFocused(); + await page.keyboard.press("Enter"); + }); + + await test.step("the results take focus, and Enter on the intro starts the session again", async () => { + const heading = page.getByRole("heading", { level: 1, name: "Session complete" }); + await expect(heading).toBeFocused(); + await expect(page.getByRole("region", { name: "Session stats" })).toMatchAriaSnapshot(` + - term: Accuracy + - definition: 100% + `); + const attempts = await storedAttempts(request, session.runId); + expect(attempts.map((a) => [a.self_score, a.confidence_rating])).toEqual([ + ["CORRECT", 3], + ["CORRECT", null], + ]); + + // No plan in this course, so the follow-ups offer New plan before the footer. + await tabTo(page, [ + page.getByRole("region", { name: "Follow-up sessions" }).getByRole("link", { name: "New plan" }), + page.getByRole("button", { name: "Start session again" }), + ]); + await page.keyboard.press("Enter"); + await expect(page.getByRole("heading", { level: 1 })).toBeFocused(); + await expect(page.getByRole("button", { name: "Start session" })).toBeVisible(); + // Enter anywhere on the intro (here the focused heading) starts it. + await page.keyboard.press("Enter"); + await expect(questionCounter(page, 1, 2)).toBeVisible(); + }); +}); + +test("number keys pick the option their hint shows, and Q, W and E rate how sure you are", async ({ page, request, seedSession }) => { + const session = await seedSession({ course_name: unique("E2E Keys"), deck: [BASE_CASE] }); + await page.goto(session.url); + await page.getByRole("button", { name: "Resume session" }).click(); + const group = options(page, BASE_CASE); + const sure = page.getByRole("group", { name: "How sure are you?" }); + await expect(group.getByRole("radio").first()).toBeFocused(); + + // Each option shows its number key, and each confidence level its letter. + for (const hint of ["1", "2", "3", "4"]) await expect(group.getByText(hint, { exact: true })).toBeVisible(); + for (const hint of ["Q", "W", "E"]) await expect(sure.getByText(hint, { exact: true })).toBeVisible(); + + for (const [key, choice] of [ + ["3", "The return type"], + ["4", "The parameter list"], + ["2", "The recursive call"], + ["1", "The base case"], + ] as const) { + await page.keyboard.press(key); + const radio = group.getByRole("radio", { name: choice }); + await expect(radio).toBeChecked(); + await expect(radio).toBeFocused(); + } + for (const [key, level] of [ + ["q", "Guessing"], + ["e", "Sure"], + ] as const) { + await page.keyboard.press(key); + await expect(confidenceRadio(page, level)).toBeChecked(); + } + + await page.keyboard.press("Enter"); + await expect(page.getByRole("region", { name: "Correct", exact: true })).toBeVisible(); + expect(await storedAttempts(request, session.runId)).toEqual([ + expect.objectContaining({ self_score: "CORRECT", confidence_rating: 5 }), + ]); +}); + +test("keys typed into an answer stay there; Ctrl+Enter submits and saves the correction", async ({ page, request }) => { + const session = await createSession(request, { course_name: unique("E2E Keys") }); + await page.goto(session.url); + await page.getByRole("button", { name: "Start session" }).click(); + await expect(answerBox(page)).toBeFocused(); + + await page.keyboard.type("1 2 3 q w e ?"); + await expect(answerBox(page)).toHaveValue("1 2 3 q w e ?"); + for (const level of ["Guessing", "Unsure", "Sure"] as const) await expect(confidenceRadio(page, level)).not.toBeChecked(); + await expect(shortcutsDialog(page)).toBeHidden(); + + await page.keyboard.press("ControlOrMeta+Enter"); + await expect(page.getByRole("group", { name: "Score your answer" })).toBeVisible(); + await page.keyboard.press("3"); + + const rule = page.getByRole("region", { name: "Log the error" }).getByRole("textbox", { name: "Correction rule" }); + await expect(rule).toBeFocused(); + await page.keyboard.type("Answer from the notes, not from guesses"); + await page.keyboard.press("ControlOrMeta+Enter"); + + const next = page.getByRole("region", { name: "Incorrect", exact: true }).getByRole("button", { name: "Next question" }); + await expect(next).toBeFocused(); + await page.keyboard.press("Enter"); + await expect(questionCounter(page, 2, 4)).toBeVisible(); +}); + +test("? opens the keyboard shortcuts, and turning off single-key shortcuts stops the number keys", async ({ page, seedSession }) => { + test.slow(); + const session = await seedSession({ course_name: unique("E2E Keys"), deck: [BASE_CASE, OVERFLOW] }); + await page.goto(session.url); + await page.getByRole("button", { name: "Resume session" }).click(); + const first = options(page, BASE_CASE).getByRole("radio").first(); + await expect(first).toBeFocused(); + + await test.step("? opens the list, Escape closes it and focus goes back to the answer", async () => { + await page.keyboard.press("?"); + await expect(shortcutsDialog(page)).toBeVisible(); + await expect(shortcutsDialog(page).getByRole("definition")).toContainText([ + "Choose an answer", + "Rate how sure you are: Guessing, Unsure, Sure", + "Submit your choice, then go to the next question", + ]); + await page.keyboard.press("Escape"); + await expect(shortcutsDialog(page)).toBeHidden(); + await expect(first).toBeFocused(); + }); + + await test.step("the switch turns off single-key shortcuts", async () => { + const help = page.getByRole("button", { name: "Keyboard shortcuts" }); + await help.click(); + const single = shortcutsDialog(page).getByRole("switch", { name: "Single-key shortcuts" }); + await expect(single).toBeChecked(); + await single.click(); + await expect(single).not.toBeChecked(); + await page.keyboard.press("Escape"); + await expect(help).toBeFocused(); + + // The number hints go, and the keys do nothing. + await expect(options(page, BASE_CASE).getByText("1", { exact: true })).toHaveCount(0); + await first.focus(); + await page.keyboard.press("2"); + await page.keyboard.press("e"); + await page.keyboard.press("?"); + await expect(options(page, BASE_CASE).getByRole("radio", { checked: true })).toHaveCount(0); + await expect(confidenceRadio(page, "Sure")).not.toBeChecked(); + await expect(shortcutsDialog(page)).toBeHidden(); + }); + + await test.step("Space and Enter still work, and the choice is remembered", async () => { + await page.keyboard.press("Space"); + await expect(first).toBeChecked(); + await page.keyboard.press("Enter"); + await page.getByRole("region", { name: "Correct", exact: true }).getByRole("button", { name: "Next question" }).click(); + await expect(questionCounter(page, 2, 2)).toBeVisible(); + + await page.reload(); + await page.getByRole("button", { name: "Resume session" }).click(); + await expect(options(page, OVERFLOW).getByRole("radio").first()).toBeFocused(); + await expect(options(page, OVERFLOW).getByText("1", { exact: true })).toHaveCount(0); + await page.getByRole("button", { name: "Keyboard shortcuts" }).click(); + await expect(shortcutsDialog(page).getByRole("switch", { name: "Single-key shortcuts" })).not.toBeChecked(); + }); +}); diff --git a/e2e/lesson.spec.ts b/e2e/lesson.spec.ts new file mode 100644 index 00000000..f15b8a91 --- /dev/null +++ b/e2e/lesson.spec.ts @@ -0,0 +1,525 @@ +/** + * The lesson at /s/[sessionId], screen by screen: the intro, multiple + * choice, free recall with its model answer and error log, the repair + * question an error adds, the last answer's feedback and the results + * (confidence, follow-up sessions), leaving, resuming after a reload, + * exam simulation, and one question on a phone. + * + * session-runner.spec.ts already covers the basic free-recall loop and the + * results stats; session-results.spec.ts the results of each mode. The + * scoring, grading and deck rules are covered by the integration tests + * (full-flow, mode-parity, exam-sim). Keyboard use is in + * lesson-keyboard.spec.ts and axe in a11y-lesson.spec.ts. + * + * Multiple choice and model answers come from a seeded deck (the + * `seedSession` fixture), because the mock AI never writes a deck; those + * tests need DATABASE_URL and skip without it (see support/db.ts). + */ +import type { APIRequestContext, Page } from "@playwright/test"; +import { + test, + expect, + QUESTIONS, + answerBox, + answerQuestion, + confidenceRadio, + createPlan, + createSession, + feedbackSheet, + getJson, + hydrated, + pick, + questionCounter, + scoreAs, + startRun, + unique, +} from "./fixtures"; + +const { baseCase: BASE_CASE, overflow: OVERFLOW, recursiveCase: RECURSIVE_CASE, whyBaseCase: WHY_BASE_CASE } = QUESTIONS; + +/** The exam simulation phase beside the counter: "Answering" or "Scoring". */ +const phase = (page: Page, label: "Answering" | "Scoring") => page.getByRole("main").getByText(label, { exact: true }); + +interface StoredRun { + attempts: { prompt_index: number; user_answer: string; self_score: string | null; confidence_rating: number | null }[]; + error_logs: { prompt_index: number; error_type: string; correction_rule: string; variant_question: string | null }[]; +} + +/** The run as the server stored it: attempts and error logs. */ +const storedRun = (api: APIRequestContext, runId: string) => getJson<StoredRun>(api, `/api/runs/${runId}`); + +test.describe("the session intro", () => { + test("shows the mode, topics, question count and Start session", { tag: "@mobile" }, async ({ page, request }) => { + const session = await createSession(request, { + course_name: unique("E2E Intro"), + exam_name: "Prelim 1", + mode: "INTERLEAVED_PRACTICE", + topic_scope: "Recursion and stacks", + planned_minutes: 25, + questions: 4, + target_accuracy: 0.8, + objectives: [ + { id: "recursion", title: "Recursion" }, + { id: "stacks", title: "Stacks" }, + ], + }); + await page.goto(session.url); + + const main = page.getByRole("main"); + await expect(page.getByRole("heading", { level: 1 })).toHaveText("Interleaved practice: Recursion and stacks"); + await expect(main.getByText("Questions from different topics, mixed together.")).toBeVisible(); + await expect(main.getByText(session.course)).toBeVisible(); + await expect(main.getByRole("definition").filter({ hasText: /^4 questions/ })).toBeVisible(); + await expect(main.getByRole("definition").filter({ hasText: "25 min" })).toBeVisible(); + await expect(main.getByRole("definition").filter({ hasText: "80%" })).toBeVisible(); + await expect(main.getByRole("term").filter({ hasText: "Topics" })).toBeVisible(); + await expect(main.getByRole("definition").filter({ hasText: "Recursion and Stacks" })).toBeVisible(); + // Topics nobody has studied yet open the deck with a pretest question, and the intro says so first. + await expect(main.getByRole("note")).toContainText("1 pretest question"); + + await page.getByRole("button", { name: "Start session" }).click(); + await expect(questionCounter(page, 1, 4)).toBeVisible(); + await expect(main.getByText(/^Pretest\. You haven't studied this topic yet/)).toBeVisible(); + }); +}); + +test.describe("answering", () => { + test("multiple choice says Correct for the right pick and shows the answer after a wrong one", async ({ + page, + request, + seedSession, + }) => { + const session = await seedSession({ course_name: unique("E2E Choice"), deck: [BASE_CASE, OVERFLOW] }); + await page.goto(session.url); + await expect(page.getByText("0 of 2 questions answered. Your answers are saved.")).toBeVisible(); + await page.getByRole("button", { name: "Resume session" }).click(); + + await test.step("a right pick", async () => { + await expect(page.getByRole("heading", { level: 1 })).toHaveText(BASE_CASE.text); + const options = page.getByRole("group", { name: BASE_CASE.text }); + await expect(options.getByRole("radio")).toHaveCount(4); + await expect(page.getByRole("button", { name: "Submit answer" })).toBeDisabled(); + + await pick(options.getByRole("radio", { name: "The base case" })); + await page.getByRole("button", { name: "Submit answer" }).click(); + + await expect(feedbackSheet(page, "Correct")).toBeVisible(); + await expect(feedbackSheet(page, "Correct")).not.toContainText("Correct answer:"); + await expect(options.getByRole("radio", { name: "The base case Correct answer" })).toBeChecked(); + await feedbackSheet(page, "Correct").getByRole("button", { name: "Next question" }).click(); + }); + + await test.step("a wrong pick marked Sure", async () => { + await expect(questionCounter(page, 2, 2)).toBeVisible(); + const options = page.getByRole("group", { name: OVERFLOW.text }); + await pick(options.getByRole("radio", { name: "The function returned too early" })); + await pick(confidenceRadio(page, "Sure")); + await page.getByRole("button", { name: "Submit answer" }).click(); + + const wrong = feedbackSheet(page, "Incorrect"); + await expect(wrong).toContainText("Correct answer: The base case is never reached"); + await expect(options.getByRole("radio", { name: "The base case is never reached Correct answer" })).toBeVisible(); + await expect(options.getByRole("radio", { name: "The function returned too early Incorrect" })).toBeChecked(); + + // Below the question: why the pick tempts (AI-written) and the confident-error note. + const feedback = page.getByRole("region", { name: "Feedback from your materials" }); + const tempting = feedback.getByRole("region", { name: "Why your answer is tempting" }); + await expect(tempting).toContainText("AI-written"); + await expect(tempting).toContainText(OVERFLOW.rationales[0]); + await expect(feedback.getByRole("heading", { name: "Confident error" })).toBeVisible(); + + // The error brings a repair question to the end of the deck. + await expect(questionCounter(page, 2, 3)).toBeVisible(); + await expect(page.getByRole("main").getByText("1 repair question added")).toBeVisible(); + }); + + await test.step("the server graded both picks and logged the error", async () => { + const run = await storedRun(request, session.runId); + expect(run.attempts.map((a) => [a.self_score, a.confidence_rating])).toEqual([ + ["CORRECT", null], + ["INCORRECT", 5], + ]); + expect(run.error_logs).toHaveLength(1); + expect(run.error_logs[0].correction_rule).toContain('The correct answer is "The base case is never reached".'); + }); + }); + + test("free recall shows the model answer, and a partial score logs the error and adds a repair question", async ({ + page, + request, + seedSession, + }) => { + test.slow(); + const session = await seedSession({ course_name: unique("E2E Recall"), deck: [RECURSIVE_CASE, WHY_BASE_CASE] }); + await page.goto(session.url); + await page.getByRole("button", { name: "Resume session" }).click(); + + await test.step("Submit answer reveals the model answer to score against", async () => { + await expect(page.getByRole("heading", { level: 1 })).toHaveText(RECURSIVE_CASE.text); + await expect(page.getByRole("button", { name: "Submit answer" })).toBeDisabled(); + await answerBox(page).fill("It calls the function again with less input"); + await page.getByRole("button", { name: "Submit answer" }).click(); + + await expect(page.getByRole("region", { name: "Your answer" })).toContainText("It calls the function again with less input"); + const model = page.getByRole("region", { name: "Model answer" }); + await expect(model).toContainText("AI-written"); + await expect(model).toContainText(RECURSIVE_CASE.modelAnswer); + await expect(model.getByRole("list", { name: "Points to check" }).getByRole("listitem")).toHaveText(RECURSIVE_CASE.keyPoints); + + await scoreAs(page, "Correct"); + await expect(feedbackSheet(page, "Correct")).toBeVisible(); + await feedbackSheet(page, "Correct").getByRole("button", { name: "Next question" }).click(); + }); + + await test.step("Partly correct asks for the error type and a correction rule", async () => { + await expect(questionCounter(page, 2, 2)).toBeVisible(); + await answerBox(page).fill("So the function knows when to stop"); + await page.getByRole("button", { name: "Submit answer" }).click(); + await scoreAs(page, "Partly correct"); + + const errorLog = page.getByRole("region", { name: "Log the error" }); + await expect(errorLog).toContainText("You scored this partly correct."); + await pick(errorLog.getByRole("group", { name: "Error type" }).getByRole("radio", { name: "Memory gap" })); + await errorLog.getByRole("textbox", { name: "Correction rule" }).fill("A base case stops the calls before the stack overflows"); + await errorLog.getByRole("textbox", { name: "Similar question (optional)" }).fill("What happens without a base case?"); + await page.getByRole("button", { name: "Save correction" }).click(); + + await expect(feedbackSheet(page, "Partly correct")).toBeVisible(); + const correction = page.getByRole("region", { name: "Your correction" }); + await expect(correction).toContainText("A base case stops the calls before the stack overflows"); + await expect(correction).toContainText("Similar question: What happens without a base case?"); + await expect(questionCounter(page, 2, 3)).toBeVisible(); + }); + + await test.step("the repair question says what it retests", async () => { + await feedbackSheet(page, "Partly correct").getByRole("button", { name: "Next question" }).click(); + await expect(questionCounter(page, 3, 3)).toBeVisible(); + await expect(page.getByText("Repair question. It retests an error from earlier in this session.")).toBeVisible(); + // A memory gap is retested by explaining the idea again. + await expect(page.getByRole("heading", { level: 1 })).toHaveText(WHY_BASE_CASE.text); + await expect(page.getByRole("main")).toContainText("From memory: explain the idea behind this question"); + const original = page.getByRole("button", { name: "Show the original question" }); + await original.click(); + await expect(original).toHaveAttribute("aria-expanded", "true"); + }); + + await test.step("the server stored the scores and the error log", async () => { + const run = await storedRun(request, session.runId); + expect(run.attempts.map((a) => a.self_score)).toEqual(["CORRECT", "PARTIAL"]); + expect(run.error_logs).toEqual([ + expect.objectContaining({ + prompt_index: 1, + error_type: "MEMORY", + correction_rule: "A base case stops the calls before the stack overflows", + variant_question: "What happens without a base case?", + }), + ]); + }); + }); +}); + +test.describe("finishing", () => { + test("the last answer's feedback comes before See results, then the results and follow-ups", async ({ page, request }) => { + test.slow(); + const course = unique("E2E Results"); + const plan = await createPlan(request, { course_name: course }); + const session = await createSession(request, { course_name: course, questions: 3 }); + await page.goto(session.url); + await page.getByRole("button", { name: "Start session" }).click(); + + await test.step("answer all 3, each marked Sure and scored Correct", async () => { + for (let n = 1; n <= 3; n++) { + await expect(questionCounter(page, n, 3)).toBeVisible(); + await answerBox(page).fill(`Answer ${n} from memory`); + await pick(confidenceRadio(page, "Sure")); + await page.getByRole("button", { name: "Submit answer" }).click(); + await scoreAs(page, "Correct"); + await expect(feedbackSheet(page, "Correct")).toBeVisible(); + if (n < 3) await feedbackSheet(page, "Correct").getByRole("button", { name: "Next question" }).click(); + } + }); + + await test.step("the last answer's feedback shows, with See results instead of Next question", async () => { + await expect(page.getByRole("region", { name: "Your answer" })).toContainText("Answer 3 from memory"); + await expect(feedbackSheet(page, "Correct").getByRole("button", { name: "Next question" })).toHaveCount(0); + await feedbackSheet(page, "Correct").getByRole("button", { name: "See results" }).click(); + }); + + await test.step("the results: stats, confidence and follow-up sessions", async () => { + await expect(page.getByRole("heading", { level: 1, name: "Session complete" })).toBeVisible(); + await expect(page.getByRole("region", { name: "Session stats" })).toMatchAriaSnapshot(` + - term: Accuracy + - definition: 100% + - term: Questions + - definition: "3" + `); + const confidenceSection = page.getByRole("region", { name: "Confidence" }); + await expect(confidenceSection).toContainText("Your confidence matched your result on 3 of 3 rated questions."); + await expect(confidenceSection.getByRole("listitem")).toContainText(["Sure: 3 of 3 correct (100%)"]); + // The table sits behind a disclosure. + await hydrated(confidenceSection.getByRole("button", { name: "Show as a table" })); + await confidenceSection.getByRole("button", { name: "Show as a table" }).click(); + await expect(confidenceSection.getByRole("row", { name: "Sure 3 3 (100%)" })).toBeVisible(); + + const followups = page.getByRole("region", { name: "Follow-up sessions" }); + await expect(followups.getByRole("listitem")).toHaveText([ + /^Retrieval session, \w{3}, \w{3} \d{1,2} \(in \d+ days\)$/, + /^Retrieval session, \w{3}, \w{3} \d{1,2} \(in \d+ days\)$/, + ]); + }); + + await test.step("Add follow-ups to plan puts them in the course's plan", async () => { + const followups = page.getByRole("region", { name: "Follow-up sessions" }); + await followups.getByRole("button", { name: "Add follow-ups to plan" }).click(); + await expect(followups.getByRole("status")).toContainText(/^Added to your plan: \w{3}, \w{3} \d{1,2} and \w{3}, \w{3} \d{1,2}\./); + await expect(followups.getByRole("link", { name: "Open plan" })).toHaveAttribute("href", `/plan?plan=${plan.id}`); + const links = followups.getByRole("link", { name: /^Retrieval session, / }); + await expect(links).toHaveCount(2); + + const stored = await getJson<{ items: { session_id: string }[] }>(request, `/api/plans/${plan.id}`); + const planSessions = stored.items.map((item) => `/s/${item.session_id}`); + expect(stored.items).toHaveLength(plan.items.length + 2); + for (const href of await links.evaluateAll((els) => els.map((el) => el.getAttribute("href")))) { + expect(planSessions).toContain(href); + } + + // The results remember it, and still link to the plan. + await page.reload(); + await expect(followups.getByRole("status")).toContainText("Added to your plan:"); + await expect(followups.getByRole("button", { name: "Add follow-ups to plan" })).toHaveCount(0); + await expect(followups.getByRole("link", { name: "Open plan" })).toHaveAttribute("href", `/plan?plan=${plan.id}`); + }); + }); + + test("Leave session goes to Home and keeps the session open to resume", { tag: "@mobile" }, async ({ page, request }) => { + const session = await createSession(request, { course_name: unique("E2E Leave") }); + await page.goto(session.url); + await page.getByRole("button", { name: "Start session" }).click(); + await expect(questionCounter(page, 1, 3)).toBeVisible(); + + await page.getByRole("link", { name: "Leave session" }).click(); + await expect(page).toHaveURL("/"); + await expect(page.getByRole("heading", { level: 1 })).toHaveText("Home"); + + await page.goto(session.url); + await expect(page.getByText("0 of 3 questions answered. Your answers are saved.")).toBeVisible(); + await expect(page.getByRole("button", { name: "Resume session" })).toBeVisible(); + }); + + test("a reload mid-question resumes on the same question with the typed answer kept", async ({ page, request }) => { + const session = await createSession(request, { course_name: unique("E2E Draft") }); + const run = await startRun(request, session.id); + await answerQuestion(request, run.run_id, 0, "CORRECT"); + + await page.goto(session.url); + await expect(page.getByText("1 of 3 questions answered. Your answers are saved.")).toBeVisible(); + await page.getByRole("button", { name: "Resume session" }).click(); + await expect(questionCounter(page, 2, 3)).toBeVisible(); + await answerBox(page).fill("Half of my answer, still being written"); + await pick(confidenceRadio(page, "Unsure")); + // The draft is kept in the browser as it's typed. + await expect + .poll(() => page.evaluate(() => Object.values(window.localStorage).join("\n"))) + .toContain("Half of my answer, still being written"); + + await page.reload(); + await page.getByRole("button", { name: "Resume session" }).click(); + await expect(questionCounter(page, 2, 3)).toBeVisible(); + await expect(answerBox(page)).toHaveValue("Half of my answer, still being written"); + await expect(confidenceRadio(page, "Unsure")).toBeChecked(); + }); +}); + +test.describe("exam simulation", () => { + /** Answer both questions (a wrong pick, then a written answer) and open scoring. */ + async function answerTheExam(page: Page) { + await page.getByRole("button", { name: "Resume session" }).click(); + await expect(questionCounter(page, 1, 2)).toBeVisible(); + await expect(phase(page, "Answering")).toBeVisible(); + await pick(page.getByRole("group", { name: BASE_CASE.text }).getByRole("radio", { name: "The recursive call" })); + await page.getByRole("button", { name: "Submit answer" }).click(); + + // No feedback while answering: the next question replaces this one. + await expect(page.getByRole("heading", { level: 1 })).toHaveText(RECURSIVE_CASE.text); + await expect(questionCounter(page, 2, 2)).toBeVisible(); + await expect(phase(page, "Answering")).toBeVisible(); + await expect(page.getByRole("region", { name: "Feedback from your materials" })).toHaveCount(0); + await answerBox(page).fill("It calls itself on a smaller piece of the problem"); + await page.getByRole("button", { name: "Submit answer" }).click(); + + await expect(page.getByRole("heading", { level: 1 })).toHaveText("All answers saved"); + await expect(questionCounter(page, 1, 2)).toBeVisible(); + await expect(phase(page, "Scoring")).toBeVisible(); + await page.getByRole("button", { name: "Start scoring" }).click(); + } + + test("saves every answer without feedback, then scores each one", async ({ page, request, seedSession }) => { + test.slow(); + const session = await seedSession({ course_name: unique("E2E Exam"), mode: "EXAM_SIM", deck: [BASE_CASE, RECURSIVE_CASE] }); + await page.goto(session.url); + await answerTheExam(page); + + await test.step("a multiple-choice answer is scored for you", async () => { + await expect(questionCounter(page, 1, 2)).toBeVisible(); + await expect(phase(page, "Scoring")).toBeVisible(); + await expect(page.getByRole("main").getByText("Correct answer: The base case", { exact: true })).toBeVisible(); + await expect(page.getByRole("radio", { name: "The recursive call (your answer) Incorrect" })).toBeChecked(); + await page.getByRole("button", { name: "Save score" }).click(); + await expect(feedbackSheet(page, "Incorrect")).toContainText("Correct answer: The base case"); + await feedbackSheet(page, "Incorrect").getByRole("button", { name: "Next question" }).click(); + }); + + await test.step("a written answer is scored against its model answer", async () => { + await expect(questionCounter(page, 2, 2)).toBeVisible(); + await expect(phase(page, "Scoring")).toBeVisible(); + await expect(page.getByRole("region", { name: "Your answer" })).toContainText("It calls itself on a smaller piece of the problem"); + await expect(page.getByRole("region", { name: "Model answer" })).toContainText(RECURSIVE_CASE.modelAnswer); + await scoreAs(page, "Correct"); + await feedbackSheet(page, "Correct").getByRole("button", { name: "See results" }).click(); + }); + + await test.step("the results count both scores", async () => { + await expect(page.getByRole("heading", { level: 1, name: "Session complete" })).toBeVisible(); + await expect(page.getByRole("region", { name: "Session stats" })).toMatchAriaSnapshot(` + - term: Accuracy + - definition: 50% + - term: Questions + - definition: "2" + - term: Time answering + - definition: /.+/ + - term: Errors logged + - definition: "1" + - term: Repair questions + - definition: "0" + - term: Scored + - definition: 2 of 2 + `); + const run = await storedRun(request, session.runId); + expect(run.attempts.map((a) => [a.prompt_index, a.self_score])).toEqual([ + [0, "INCORRECT"], + [1, "CORRECT"], + ]); + }); + }); + + test("no score is recorded while the saved exam answers are still loading", async ({ page, request, seedSession }) => { + const session = await seedSession({ course_name: unique("E2E Exam"), mode: "EXAM_SIM", deck: [BASE_CASE, RECURSIVE_CASE] }); + // Hold the saved answers (GET /api/runs/{id}) until the checks below are done. + let release!: () => void; + const held = new Promise<void>((resolve) => (release = resolve)); + await page.route(`**/api/runs/${session.runId}`, async (route) => { + if (route.request().method() === "GET") await held; + await route.fallback(); + }); + await page.goto(session.url); + await answerTheExam(page); + + const bar = page.getByRole("group", { name: "Loading your saved answer…" }); + await expect(bar).toBeVisible(); + for (const name of ["Correct", "Partly correct", "Incorrect"]) { + await expect(bar.getByRole("button", { name, exact: true })).toBeDisabled(); + } + await expect(page.getByRole("main")).not.toContainText("has no model answer"); + await page.keyboard.press("1"); + await page.keyboard.press("Enter"); + expect((await storedRun(request, session.runId)).attempts.map((a) => a.self_score)).toEqual([null, null]); + + release(); + await expect(page.getByRole("main").getByText("Correct answer: The base case", { exact: true })).toBeVisible(); + await expect(page.getByRole("button", { name: "Save score" })).toBeEnabled(); + }); + + test("the last exam answer stays on screen after it is scored", async ({ page, seedSession }) => { + const session = await seedSession({ course_name: unique("E2E Exam"), mode: "EXAM_SIM", deck: [BASE_CASE, RECURSIVE_CASE] }); + await page.goto(session.url); + await answerTheExam(page); + await page.getByRole("button", { name: "Save score" }).click(); + await feedbackSheet(page, "Incorrect").getByRole("button", { name: "Next question" }).click(); + + const yourAnswer = page.getByRole("region", { name: "Your answer" }); + await expect(yourAnswer).toContainText("It calls itself on a smaller piece of the problem"); + await scoreAs(page, "Correct"); + await expect(feedbackSheet(page, "Correct")).toBeVisible(); + await expect(yourAnswer).toContainText("It calls itself on a smaller piece of the problem"); + }); +}); + +/** The top of the sticky footer that holds `el` (the score bar, Save correction). */ +const footerTop = (el: HTMLElement): number => { + let node: HTMLElement | null = el; + while (node && getComputedStyle(node).position !== "sticky") node = node.parentElement; + return node ? node.getBoundingClientRect().top : window.innerHeight; +}; + +test("on a small phone the score bar is one row and the correction rule stays above the footer", { tag: "@mobile" }, async ({ + page, + seedSession, +}) => { + await page.setViewportSize({ width: 375, height: 667 }); + const session = await seedSession({ course_name: unique("E2E Small phone"), deck: [RECURSIVE_CASE] }); + await page.goto(session.url); + await page.getByRole("button", { name: "Resume session" }).click(); + await answerBox(page).fill("It calls the function again"); + await page.getByRole("button", { name: "Submit answer" }).click(); + + await test.step("the three scores sit in one row, under the model answer they're scored against", async () => { + const bar = page.getByRole("group", { name: "Score your answer" }); + // The bar replaces Submit answer once the model answer arrives. + await expect(bar.getByRole("button")).toHaveCount(3); + const tops = await bar.getByRole("button").evaluateAll((buttons) => buttons.map((b) => Math.round(b.getBoundingClientRect().top))); + expect(new Set(tops).size).toBe(1); + const barTop = await bar.evaluate(footerTop); + const modelTop = await page.getByRole("region", { name: "Model answer" }).evaluate((el) => el.getBoundingClientRect().top); + // At least the heading and a few lines of the model answer show above the bar. + expect(barTop - modelTop).toBeGreaterThan(120); + }); + + await test.step("the focused correction rule field, and its error, are not hidden by the footer", async () => { + await scoreAs(page, "Incorrect"); + const rule = page.getByRole("textbox", { name: "Correction rule" }); + await expect(rule).toBeFocused(); + const save = page.getByRole("button", { name: "Save correction" }); + const limit = await save.evaluate(footerTop); + expect(await rule.evaluate((el) => el.getBoundingClientRect().bottom)).toBeLessThanOrEqual(limit); + // Change score and Save correction share one row. + const changeTop = await page.getByRole("button", { name: "Change score" }).evaluate((el) => Math.round(el.getBoundingClientRect().top)); + expect(await save.evaluate((el) => Math.round(el.getBoundingClientRect().top))).toBe(changeTop); + + await save.click(); + const error = page.getByText("Write the correction rule first."); + await expect(error).toBeVisible(); + await expect(rule).toBeFocused(); + expect(await error.evaluate((el) => el.getBoundingClientRect().bottom)).toBeLessThanOrEqual(await save.evaluate(footerTop)); + }); +}); + +test("one multiple-choice question by touch on a phone", { tag: "@mobile" }, async ({ page, isMobile, seedSession }) => { + test.skip(!isMobile, "Phone layout only"); + const session = await seedSession({ course_name: unique("E2E Phone"), deck: [BASE_CASE] }); + await page.goto(session.url); + await page.getByRole("button", { name: "Resume session" }).tap(); + + await expect(page.getByRole("heading", { level: 1 })).toHaveText(BASE_CASE.text); + // A phone can have a keyboard paired, and its keys run the single-key + // shortcuts, so their off switch is in the top bar on the row with Leave + // session, not in a footer row of its own (WCAG 2.1.4). + const help = page.getByRole("button", { name: "Keyboard shortcuts" }); + await expect(help).toBeVisible(); + const leave = page.getByRole("link", { name: "Leave session" }); + const rowTop = (el: HTMLElement) => Math.round(el.getBoundingClientRect().top); + expect(await help.evaluate(rowTop)).toBe(await leave.evaluate(rowTop)); + await help.tap(); + const shortcuts = page.getByRole("dialog", { name: "Keyboard shortcuts" }); + await expect(shortcuts.getByRole("switch", { name: "Single-key shortcuts" })).toBeChecked(); + await page.keyboard.press("Escape"); + await expect(shortcuts).toBeHidden(); + await pick(page.getByRole("radio", { name: "The base case" })); + await pick(confidenceRadio(page, "Sure")); + await page.getByRole("button", { name: "Submit answer" }).tap(); + + await expect(feedbackSheet(page, "Correct")).toBeInViewport(); + // Feedback replaces the footer; the shortcuts stay in the top bar. + await expect(help).toBeVisible(); + await feedbackSheet(page, "Correct").getByRole("button", { name: "See results" }).tap(); + await expect(page.getByRole("heading", { level: 1, name: "Session complete" })).toBeVisible(); +}); diff --git a/e2e/materials.spec.ts b/e2e/materials.spec.ts new file mode 100644 index 00000000..73fb4b1c --- /dev/null +++ b/e2e/materials.spec.ts @@ -0,0 +1,174 @@ +/** + * Materials (/plan/materials): files grouped by course with their status in + * words, Finish processing, dropping files on the upload zone (and the + * type check before anything is sent), the summary toggle, and Delete with + * its confirmation. Each test seeds its own identity, so the list holds only + * its own files. + * + * Already covered elsewhere: upload, dedupe and processing rules in + * src/__tests__/content-upload.test.ts and content-process-claim.test.ts, + * and picking a file with the keyboard in plan.spec.ts. + */ +import type { APIRequestContext, Page } from "@playwright/test"; +import { test, expect, hydrated, toasts, unique, uploadMaterial } from "./fixtures"; + +interface Doc { + document_id: string; + course_name: string | null; + exam_name: string | null; + original_filename: string; + status: string; +} + +async function listDocs(api: APIRequestContext): Promise<Doc[]> { + const response = await api.get("/api/content/documents?namespace=COURSE"); + expect(response.status()).toBe(200); + return (await response.json()).documents; +} + +function courseGroup(page: Page, course: string) { + return page.getByRole("region", { name: "Your materials" }).getByRole("region", { name: course }); +} + +test("files are listed by course with their status in plain words", { tag: "@mobile" }, async ({ + testUserPage: page, + testUser, +}) => { + const course = unique("E2E Files"); + await uploadMaterial(testUser.api, { course, text: "Recursion: a function that calls itself until a base case." }); + await uploadMaterial(testUser.api, { course, fileName: "raw.md", text: "Hash tables map keys to buckets.", process: false }); + + await page.goto("/plan/materials"); + const group = courseGroup(page, course); + await expect(group.getByRole("heading", { level: 3, name: course })).toBeVisible(); + await expect(group.getByText("2 files", { exact: true })).toBeVisible(); + + const ready = group.getByRole("listitem").filter({ hasText: "notes.txt" }); + await expect(ready).toContainText(/Text, added \w{3} \d{1,2}/); + await expect(ready).toContainText("Ready"); + const waiting = group.getByRole("listitem").filter({ hasText: "raw.md" }); + await expect(waiting).toContainText(/Markdown, added \w{3} \d{1,2}/); + await expect(waiting).toContainText("Uploaded"); + // Statuses are words, never the stored codes. + await expect(group).not.toContainText(/PROCESSED|UPLOADED|PROCESSING|FAILED/); + + const finish = waiting.getByRole("button", { name: "Finish processing raw.md" }); + await hydrated(finish); + await finish.click(); + await expect(waiting).toContainText("Ready"); + await expect(toasts(page)).toContainText("raw.md ready"); + await expect(waiting.getByRole("button", { name: "Summary of raw.md" })).toBeVisible(); + expect((await listDocs(testUser.api)).map((d) => d.status)).toEqual(["PROCESSED", "PROCESSED"]); +}); + +test("files dropped on the upload zone are checked, uploaded and processed", async ({ + testUserPage: page, + testUser, +}) => { + const course = unique("E2E Drop"); + await page.goto("/plan/materials"); + const uploads = page.getByRole("region", { name: "Upload materials" }); + // The zone's name changes while files are dragged over it, so find it by its button. + const zone = uploads.getByRole("group").filter({ has: page.getByRole("button", { name: "Choose files" }) }); + await expect(zone.getByRole("button", { name: "Choose files" })).toBeDisabled(); + await expect(zone).toHaveAccessibleDescription(/Enter the course name first\./); + + await hydrated(uploads.getByRole("combobox", { name: "Course" })); + await uploads.getByRole("combobox", { name: "Course" }).fill(course); + await uploads.getByRole("textbox", { name: "Exam (optional)" }).fill("Prelim 2"); + await expect(zone.getByRole("button", { name: "Choose files" })).toBeEnabled(); + + const dataTransfer = await page.evaluateHandle(() => { + const transfer = new DataTransfer(); + transfer.items.add(new File(["# Hash tables\n\nKeys map to buckets through a hash function."], "lecture-2.md", { type: "text/markdown" })); + transfer.items.add(new File(["not a document"], "slides.png", { type: "image/png" })); + return transfer; + }); + await zone.dispatchEvent("dragenter", { dataTransfer }); + await expect(zone).toHaveAccessibleName("Drop to upload"); + await zone.dispatchEvent("drop", { dataTransfer }); + await expect(zone).toHaveAccessibleName("Course files"); + + const accepted = uploads.getByRole("listitem").filter({ hasText: "lecture-2.md" }); + await expect(accepted).toContainText(`Saved to ${course}, Prelim 2`); + await expect(accepted).toContainText("Ready"); + const rejected = uploads.getByRole("listitem").filter({ hasText: "slides.png" }); + await expect(rejected).toContainText("Not uploaded"); + await expect(rejected).toContainText("Upload a PDF, text, or Markdown file up to 10 MB."); + + const listed = courseGroup(page, course).getByRole("listitem").filter({ hasText: "lecture-2.md" }); + await expect(listed).toContainText(/Markdown, added \w{3} \d{1,2}, for Prelim 2/); + await expect(listed).toContainText("Ready"); + const docs = await listDocs(testUser.api); + expect(docs.map((d) => [d.original_filename, d.course_name, d.exam_name, d.status])).toEqual([ + ["lecture-2.md", course, "Prelim 2", "PROCESSED"], + ]); +}); + +test("a ready file's summary opens under its row", async ({ testUserPage: page, testUser }) => { + const course = unique("E2E Summary"); + await uploadMaterial(testUser.api, { course, text: "Sorting: merge sort splits the list, sorts each half, then merges." }); + + await page.goto("/plan/materials"); + const row = courseGroup(page, course).getByRole("listitem").filter({ hasText: "notes.txt" }); + const toggle = row.getByRole("button", { name: "Summary of notes.txt" }); + await expect(toggle).toHaveAttribute("aria-expanded", "false"); + + await hydrated(toggle); + await toggle.click(); + await expect(toggle).toHaveAttribute("aria-expanded", "true"); + // The mock AI writes no summaries, so the row says what still uses the file. + const note = row.getByText("No summary for this file. Chat, flashcards, and guides still use its text."); + await expect(note).toBeVisible(); + + await toggle.click(); + await expect(toggle).toHaveAttribute("aria-expanded", "false"); + await expect(note).toBeHidden(); +}); + +test("Delete file asks first and removes the file", { tag: "@mobile" }, async ({ testUserPage: page, testUser }) => { + const course = unique("E2E Remove"); + await uploadMaterial(testUser.api, { course, text: "Graphs: vertices joined by edges." }); + + await page.goto("/plan/materials"); + const remove = courseGroup(page, course).getByRole("button", { name: "Delete notes.txt" }); + const dialog = page.getByRole("alertdialog", { name: "Delete notes.txt?" }); + + await test.step("Cancel keeps it", async () => { + await hydrated(remove); + await remove.click(); + await expect(dialog).toContainText( + `It comes out of your ${course} materials, so new session questions, chat, new flashcards, and new guides stop using it. Plans, decks, and guides already made from it stay.`, + ); + await dialog.getByRole("button", { name: "Cancel" }).click(); + await expect(dialog).toBeHidden(); + await expect(remove).toBeFocused(); + expect(await listDocs(testUser.api)).toHaveLength(1); + }); + + await remove.click(); + await dialog.getByRole("button", { name: "Delete file" }).click(); + await expect(dialog).toBeHidden(); + await expect(toasts(page)).toContainText("File deleted"); + await expect(page.getByRole("heading", { name: "No materials yet" })).toBeVisible(); + // The row and its button are gone, so focus moves to the list's heading. + await expect(page.getByRole("heading", { level: 2, name: "Your materials" })).toBeFocused(); + expect(await listDocs(testUser.api)).toEqual([]); +}); + +test("after Delete file with other files left, focus moves to the materials list heading", async ({ + testUserPage: page, + testUser, +}) => { + const course = unique("E2E Focus"); + await uploadMaterial(testUser.api, { course, text: "Trees: nodes with children." }); + await uploadMaterial(testUser.api, { course, fileName: "more.txt", text: "Heaps: a tree with an order rule." }); + + await page.goto("/plan/materials"); + const remove = courseGroup(page, course).getByRole("button", { name: "Delete notes.txt" }); + await hydrated(remove); + await remove.click(); + await page.getByRole("alertdialog", { name: "Delete notes.txt?" }).getByRole("button", { name: "Delete file" }).click(); + await expect(toasts(page)).toContainText("File deleted"); + await expect(page.getByRole("heading", { level: 2, name: "Your materials" })).toBeFocused(); +}); diff --git a/e2e/mode-parity.spec.ts b/e2e/mode-parity.spec.ts deleted file mode 100644 index b0df58c3..00000000 --- a/e2e/mode-parity.spec.ts +++ /dev/null @@ -1,488 +0,0 @@ -import { test, expect } from "@playwright/test"; -import pg from "pg"; - -const BASE_URL = process.env.BASE_URL || "http://localhost:3000"; -const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL }); - -/** Seed mastery records so pre-test diagnostic prompts are not prepended */ -async function seedMastery(userId: string, courseName: string, objectiveKeys: string[]) { - for (const key of objectiveKeys) { - await pool.query( - `INSERT INTO objective_mastery (id, user_id, course_name, objective_key, updated_at) - VALUES (gen_random_uuid(), $1, $2, $3, NOW()) - ON CONFLICT (user_id, course_name, objective_key) DO NOTHING`, - [userId, courseName, key] - ); - } - // Purge error logs from any previous attempt of this spec (retries restart - // the worker but keep the DB). Unresolved logs — which now survive a single - // correct retrieval by design (successive relearning criterion) — would - // otherwise inject CROSS_SESSION_REPAIR prompts into the new run's deck and - // shift the exact prompt counts these tests assert. - await pool.query(`DELETE FROM session_error_logs WHERE user_id = $1`, [userId]); -} - -async function cleanupMastery(userId: string) { - await pool.query(`DELETE FROM objective_mastery WHERE user_id = $1`, [userId]); -} - -// ============================================================ -// E2E: Interleaved Practice runner -// ============================================================ - -test.describe.serial("E2E: Interleaved Practice runner", () => { - const USER_ID = "e2e_interleaved_user"; - let sessionId: string; - let runId: string; - let promptCount: number; - - test.beforeAll(async () => { - await seedMastery(USER_ID, "E2E Interleaved", ["obj_a", "obj_b"]); - }); - - test.afterAll(async () => { - await cleanupMastery(USER_ID); - }); - - test("create INTERLEAVED_PRACTICE session", async ({ request }) => { - const res = await request.post(`${BASE_URL}/api/sessions`, { - headers: { "Content-Type": "application/json", "X-User-Id": USER_ID }, - data: { - course_name: "E2E Interleaved", - exam_name: "Test 1", - mode: "INTERLEAVED_PRACTICE", - topic_scope: "Ch1-Ch2", - planned_minutes: 30, - objectives: [ - { id: "obj_a", title: "Loops and iteration" }, - { id: "obj_b", title: "Array manipulation" }, - ], - target_outcome: { prompt_count: 6 }, - break_protocol: { type: "TEST_3_2", cycles: 1 }, - }, - }); - expect(res.status()).toBe(201); - const body = await res.json(); - sessionId = body.session_id; - }); - - test("start run returns mode=INTERLEAVED_PRACTICE, prompts alternate objectives", async ({ request }) => { - const res = await request.post( - `${BASE_URL}/api/sessions/${sessionId}/runs/start`, - { headers: { "X-User-Id": USER_ID } } - ); - expect(res.status()).toBe(201); - const body = await res.json(); - - expect(body.mode).toBe("INTERLEAVED_PRACTICE"); - expect(body.phase).toBe("ACTIVE"); - expect(body.policies.scoring).toBe("IMMEDIATE"); - expect(body.prompts.length).toBe(6); - - // Verify first two prompts have different objective_ids - expect(body.prompts[0].objective_id).not.toBe(body.prompts[1].objective_id); - - runId = body.run_id; - promptCount = body.prompts.length; - }); - - test("complete all prompts with immediate scoring", async ({ request }) => { - let lastBody: any; - for (let i = 0; i < promptCount; i++) { - const res = await request.post( - `${BASE_URL}/api/runs/${runId}/attempt`, - { - headers: { "Content-Type": "application/json", "X-User-Id": USER_ID }, - data: { - prompt_index: i, - user_answer: `Interleaved answer ${i}`, - self_score: i % 3 === 0 ? "INCORRECT" : "CORRECT", - time_to_answer_seconds: 10, - ...(i % 3 === 0 - ? { - error_log: { - error_type: "MEMORY", - correction_rule: "Remember the rule", - }, - } - : {}), - }, - } - ); - expect(res.status()).toBe(200); - lastBody = await res.json(); - } - - // INCORRECT answers inject variant repair prompts. Submit them to complete. - while (lastBody.status === "ACTIVE") { - const idx = lastBody.current_index; - const res = await request.post( - `${BASE_URL}/api/runs/${runId}/attempt`, - { - headers: { "Content-Type": "application/json", "X-User-Id": USER_ID }, - data: { - prompt_index: idx, - user_answer: `Variant repair answer ${idx}`, - self_score: "CORRECT", - time_to_answer_seconds: 10, - }, - } - ); - expect(res.status()).toBe(200); - lastBody = await res.json(); - } - - expect(lastBody.status).toBe("COMPLETED"); - }); - - test("session page renders in browser", async ({ page }) => { - await page.goto(`/s/${sessionId}`); - await expect(page.getByText("E2E Interleaved")).toBeVisible(); - await expect(page.getByText("Interleaved Practice")).toBeVisible(); - }); -}); - -// ============================================================ -// E2E: Exam Sim runner -// ============================================================ - -test.describe.serial("E2E: Exam Sim runner", () => { - const USER_ID = "e2e_examsim_user"; - let sessionId: string; - let runId: string; - - test.beforeAll(async () => { - await seedMastery(USER_ID, "E2E ExamSim", ["obj_1", "obj_2"]); - }); - - test.afterAll(async () => { - await cleanupMastery(USER_ID); - }); - - test("create EXAM_SIM session with 3 prompts", async ({ request }) => { - const res = await request.post(`${BASE_URL}/api/sessions`, { - headers: { "Content-Type": "application/json", "X-User-Id": USER_ID }, - data: { - course_name: "E2E ExamSim", - exam_name: "Final", - mode: "EXAM_SIM", - topic_scope: "All", - planned_minutes: 60, - objectives: [ - { id: "obj_1", title: "Topic A" }, - { id: "obj_2", title: "Topic B" }, - ], - target_outcome: { prompt_count: 3 }, - break_protocol: { type: "TEST_3_2", cycles: 1 }, - }, - }); - expect(res.status()).toBe(201); - sessionId = (await res.json()).session_id; - }); - - test("start run returns phase=EXAM with DELAYED scoring", async ({ request }) => { - const res = await request.post( - `${BASE_URL}/api/sessions/${sessionId}/runs/start`, - { headers: { "X-User-Id": USER_ID } } - ); - expect(res.status()).toBe(201); - const body = await res.json(); - - expect(body.mode).toBe("EXAM_SIM"); - expect(body.phase).toBe("EXAM"); - expect(body.policies.scoring).toBe("DELAYED"); - expect(body.prompts).toHaveLength(3); - expect(body.answered_count).toBe(0); - expect(body.scored_count).toBe(0); - runId = body.run_id; - }); - - test("SCORE rejected during EXAM phase (409)", async ({ request }) => { - const res = await request.post( - `${BASE_URL}/api/runs/${runId}/attempt`, - { - headers: { "Content-Type": "application/json", "X-User-Id": USER_ID }, - data: { prompt_index: 0, kind: "SCORE", self_score: "CORRECT" }, - } - ); - expect(res.status()).toBe(409); - }); - - test("answer all 3 prompts, last answer transitions to REVIEW", async ({ request }) => { - for (let i = 0; i < 3; i++) { - const res = await request.post( - `${BASE_URL}/api/runs/${runId}/attempt`, - { - headers: { "Content-Type": "application/json", "X-User-Id": USER_ID }, - data: { - prompt_index: i, - kind: "ANSWER", - user_answer: `Exam answer ${i}`, - time_to_answer_seconds: 20, - }, - } - ); - expect(res.status()).toBe(200); - const body = await res.json(); - - if (i < 2) { - expect(body.phase).toBe("EXAM"); - expect(body.answered_count).toBe(i + 1); - } else { - // Last answer transitions to REVIEW - expect(body.phase).toBe("REVIEW"); - expect(body.current_index).toBe(0); - expect(body.answered_count).toBe(3); - } - } - }); - - test("ANSWER rejected during REVIEW phase (409)", async ({ request }) => { - const res = await request.post( - `${BASE_URL}/api/runs/${runId}/attempt`, - { - headers: { "Content-Type": "application/json", "X-User-Id": USER_ID }, - data: { prompt_index: 0, kind: "ANSWER", user_answer: "should fail" }, - } - ); - expect(res.status()).toBe(409); - }); - - test("score all prompts with one INCORRECT + error log, run completes", async ({ request }) => { - // Score prompt 0: CORRECT - const r0 = await request.post( - `${BASE_URL}/api/runs/${runId}/attempt`, - { - headers: { "Content-Type": "application/json", "X-User-Id": USER_ID }, - data: { prompt_index: 0, kind: "SCORE", self_score: "CORRECT" }, - } - ); - expect(r0.status()).toBe(200); - expect((await r0.json()).scored_count).toBe(1); - - // Score prompt 1: INCORRECT with error log - const r1 = await request.post( - `${BASE_URL}/api/runs/${runId}/attempt`, - { - headers: { "Content-Type": "application/json", "X-User-Id": USER_ID }, - data: { - prompt_index: 1, - kind: "SCORE", - self_score: "INCORRECT", - error_log: { - error_type: "MISCONCEPTION", - correction_rule: "The correct approach is XYZ", - variant_question: "Why does XYZ work?", - }, - }, - } - ); - expect(r1.status()).toBe(200); - expect((await r1.json()).scored_count).toBe(2); - - // Score prompt 2: CORRECT — should complete - const r2 = await request.post( - `${BASE_URL}/api/runs/${runId}/attempt`, - { - headers: { "Content-Type": "application/json", "X-User-Id": USER_ID }, - data: { prompt_index: 2, kind: "SCORE", self_score: "CORRECT" }, - } - ); - expect(r2.status()).toBe(200); - const body = await r2.json(); - expect(body.status).toBe("COMPLETED"); - expect(body.phase).toBe("COMPLETE"); - expect(body.scored_count).toBe(3); - expect(body.metrics.accuracy).toBeCloseTo(2 / 3, 2); - expect(body.metrics.recommended_followups).toBeDefined(); - }); - - test("GET run shows all attempts with scores", async ({ request }) => { - const res = await request.get(`${BASE_URL}/api/runs/${runId}`, { - headers: { "X-User-Id": USER_ID }, - }); - const body = await res.json(); - expect(body.status).toBe("COMPLETED"); - expect(body.mode).toBe("EXAM_SIM"); - expect(body.attempts).toHaveLength(3); - // All should now have self_score set - expect(body.attempts[0].self_score).toBe("CORRECT"); - expect(body.attempts[1].self_score).toBe("INCORRECT"); - expect(body.attempts[2].self_score).toBe("CORRECT"); - }); - - test("session page renders exam sim label", async ({ page }) => { - await page.goto(`/s/${sessionId}`); - await expect(page.getByText("E2E ExamSim")).toBeVisible(); - await expect(page.getByText("Exam Sim")).toBeVisible(); - }); -}); - -// ============================================================ -// E2E: Error Repair runner -// ============================================================ - -test.describe.serial("E2E: Error Repair runner", () => { - const USER_ID = "e2e_errorrepair_user"; - let retrievalSessionId: string; - let retrievalRunId: string; - let repairSessionId: string; - let repairRunId: string; - - test.beforeAll(async () => { - await seedMastery(USER_ID, "E2E Repair", ["obj_1"]); - }); - - test.afterAll(async () => { - await cleanupMastery(USER_ID); - await pool.end(); - }); - - // Step 1: Create retrieval session and generate error log - test("create retrieval session and submit INCORRECT with error log", async ({ request }) => { - // Create session - const sessRes = await request.post(`${BASE_URL}/api/sessions`, { - headers: { "Content-Type": "application/json", "X-User-Id": USER_ID }, - data: { - course_name: "E2E Repair", - exam_name: "Quiz", - mode: "RETRIEVAL", - topic_scope: "Errors", - planned_minutes: 15, - objectives: [{ id: "obj_1", title: "Exception handling" }], - target_outcome: { prompt_count: 2 }, - break_protocol: { type: "TEST_3_2", cycles: 1 }, - }, - }); - expect(sessRes.status()).toBe(201); - retrievalSessionId = (await sessRes.json()).session_id; - - // Start run - const startRes = await request.post( - `${BASE_URL}/api/sessions/${retrievalSessionId}/runs/start`, - { headers: { "X-User-Id": USER_ID } } - ); - expect(startRes.status()).toBe(201); - retrievalRunId = (await startRes.json()).run_id; - - // Submit INCORRECT with error log - const a0 = await request.post( - `${BASE_URL}/api/runs/${retrievalRunId}/attempt`, - { - headers: { "Content-Type": "application/json", "X-User-Id": USER_ID }, - data: { - prompt_index: 0, - user_answer: "Wrong approach to exceptions", - self_score: "INCORRECT", - time_to_answer_seconds: 20, - error_log: { - error_type: "MISCONCEPTION", - correction_rule: "Always use try-catch for recoverable errors", - variant_question: "When should you use checked vs unchecked exceptions?", - }, - }, - } - ); - expect(a0.status()).toBe(200); - - // Complete the second original prompt - const a1 = await request.post( - `${BASE_URL}/api/runs/${retrievalRunId}/attempt`, - { - headers: { "Content-Type": "application/json", "X-User-Id": USER_ID }, - data: { - prompt_index: 1, - user_answer: "Correct answer", - self_score: "CORRECT", - time_to_answer_seconds: 10, - }, - } - ); - expect(a1.status()).toBe(200); - - // Force-complete the run. Variant prompt (injected by INCORRECT) is skipped - // so the error log stays UNRESOLVED for the ERROR_REPAIR test below. - const completeRes = await request.post( - `${BASE_URL}/api/runs/${retrievalRunId}/complete`, - { headers: { "X-User-Id": USER_ID } } - ); - expect(completeRes.status()).toBe(200); - expect((await completeRes.json()).status).toBe("COMPLETED"); - }); - - // Step 2: Create ERROR_REPAIR session and start it - test("create ERROR_REPAIR session and start run with repair prompts", async ({ request }) => { - const sessRes = await request.post(`${BASE_URL}/api/sessions`, { - headers: { "Content-Type": "application/json", "X-User-Id": USER_ID }, - data: { - course_name: "E2E Repair", - exam_name: "Quiz", - mode: "ERROR_REPAIR", - topic_scope: "Errors", - planned_minutes: 15, - target_outcome: { prompt_count: 5 }, - break_protocol: { type: "TEST_3_2", cycles: 1 }, - }, - }); - expect(sessRes.status()).toBe(201); - repairSessionId = (await sessRes.json()).session_id; - - // Start repair run - const startRes = await request.post( - `${BASE_URL}/api/sessions/${repairSessionId}/runs/start`, - { headers: { "X-User-Id": USER_ID } } - ); - expect(startRes.status()).toBe(201); - const body = await startRes.json(); - - expect(body.mode).toBe("ERROR_REPAIR"); - expect(body.phase).toBe("ACTIVE"); - expect(body.prompts.length).toBeGreaterThanOrEqual(1); - - // First prompt should be a repair prompt referencing the error - expect(body.prompts[0].meta?.source_error_log_id).toBeDefined(); - expect(body.prompts[0].text).toContain("From memory"); - - repairRunId = body.run_id; - }); - - // Step 3: Score CORRECT and verify completion + error log resolved - test("CORRECT repair completes run", async ({ request }) => { - // Get prompts to know how many to answer - const runRes = await request.get(`${BASE_URL}/api/runs/${repairRunId}`, { - headers: { "X-User-Id": USER_ID }, - }); - const run = await runRes.json(); - const prompts = run.prompts; - - for (let i = 0; i < prompts.length; i++) { - const res = await request.post( - `${BASE_URL}/api/runs/${repairRunId}/attempt`, - { - headers: { "Content-Type": "application/json", "X-User-Id": USER_ID }, - data: { - prompt_index: i, - user_answer: "Correct repair: always use try-catch", - self_score: "CORRECT", - time_to_answer_seconds: 15, - }, - } - ); - expect(res.status()).toBe(200); - } - - // Verify completed - const finalRes = await request.get(`${BASE_URL}/api/runs/${repairRunId}`, { - headers: { "X-User-Id": USER_ID }, - }); - const finalRun = await finalRes.json(); - expect(finalRun.status).toBe("COMPLETED"); - expect(finalRun.metrics.accuracy).toBe(1); - }); - - test("session page renders error repair label", async ({ page }) => { - await page.goto(`/s/${repairSessionId}`); - await expect(page.getByText("E2E Repair")).toBeVisible(); - await expect(page.getByText("Error Repair")).toBeVisible(); - }); -}); diff --git a/e2e/plan-calendar.spec.ts b/e2e/plan-calendar.spec.ts new file mode 100644 index 00000000..4d83b073 --- /dev/null +++ b/e2e/plan-calendar.spec.ts @@ -0,0 +1,156 @@ +/** + * Google Calendar from the plan: Add to Google Calendar, Update Google + * Calendar, Remove from Google Calendar behind its confirmation (focus goes + * back to the plan menu), and the alert when Google needs the student to + * sign in again. The server runs GOOGLE_PROVIDER=fake, so nothing reaches + * Google, and each test connects its own identity through + * /api/integrations/google/test-seed. + * + * Already covered elsewhere: publish, update and reconcile rules in + * src/__tests__/integration/google-calendar.test.ts, and Connect and + * Disconnect in settings.spec.ts. + */ +import type { APIRequestContext } from "@playwright/test"; +import { test, expect, createPlan, expectNoAxeViolations, hydrated, toasts, unique, type CreatedPlan } from "./fixtures"; + +const EXAM = "Prelim 1"; + +interface Publication { + publication: { status: string } | null; + items: { plan_item_id: string }[]; +} + +/** Connect Google Calendar for this identity, or mark the connection as needing a new sign-in ("ERROR"). */ +async function seedGoogle(api: APIRequestContext, status: "CONNECTED" | "ERROR" = "CONNECTED"): Promise<void> { + const response = await api.post("/api/integrations/google/test-seed", { data: { status } }); + expect(response.status(), "the server needs GOOGLE_PROVIDER=fake and test auth").toBe(200); +} + +async function publication(api: APIRequestContext, planId: string): Promise<Publication> { + const response = await api.get(`/api/plans/${planId}/publish/google`); + expect(response.status(), await response.text()).toBe(200); + return response.json(); +} + +async function seedPlan(api: APIRequestContext, label: string): Promise<CreatedPlan> { + return createPlan(api, { course_name: unique(label), exam_name: EXAM }); +} + +test.beforeEach(async ({ testUser }) => { + const config = await (await testUser.api.get("/api/config")).json(); + test.skip(!config.google_configured, "The plan shows Google Calendar only when the server can connect it (GOOGLE_PROVIDER=fake here)."); +}); + +test("Add to Google Calendar adds every session, and Update keeps them there", async ({ + testUserPage: page, + testUser, +}) => { + await seedGoogle(testUser.api); + const plan = await seedPlan(testUser.api, "E2E Calendar add"); + expect((await publication(testUser.api, plan.id)).publication).toBeNull(); + + await page.goto(`/plan?plan=${plan.id}`); + const add = page.getByRole("button", { name: "Add to Google Calendar" }); + await hydrated(add); + await add.click(); + + await expect(toasts(page)).toContainText("Added to Google Calendar"); + await expect(page.getByText("In Google Calendar", { exact: true })).toBeVisible(); + await expect(add).toBeHidden(); + const added = await publication(testUser.api, plan.id); + expect(added.publication?.status).toBe("PUBLISHED"); + expect(added.items).toHaveLength(plan.items.length); + + await test.step("Update Google Calendar from the plan menu", async () => { + await page.getByRole("button", { name: `More actions for the ${EXAM} plan` }).click(); + const update = page.waitForResponse( + (response) => response.request().method() === "POST" && response.url().endsWith(`/api/plans/${plan.id}/publish/google`), + ); + await page.getByRole("menuitem", { name: "Update Google Calendar" }).click(); + expect((await update).status()).toBe(200); + await expect(page.getByText("In Google Calendar", { exact: true })).toBeVisible(); + const updated = await publication(testUser.api, plan.id); + expect(updated.publication?.status).toBe("PUBLISHED"); + expect(updated.items).toHaveLength(plan.items.length); + }); +}); + +test("Remove from Google Calendar asks first, then takes the events out", { tag: "@mobile" }, async ({ + testUserPage: page, + testUser, +}) => { + await seedGoogle(testUser.api); + const plan = await seedPlan(testUser.api, "E2E Calendar remove"); + const published = await testUser.api.post(`/api/plans/${plan.id}/publish/google`, { data: {} }); + expect(published.status(), await published.text()).toBe(200); + + await page.goto(`/plan?plan=${plan.id}`); + const more = page.getByRole("button", { name: `More actions for the ${EXAM} plan` }); + const dialog = page.getByRole("alertdialog", { + name: `Remove the ${plan.course} ${EXAM} sessions from Google Calendar?`, + }); + const openRemove = async () => { + await more.click(); + await page.getByRole("menuitem", { name: "Remove from Google Calendar" }).click(); + }; + await hydrated(more); + + await test.step("Cancel keeps the events", async () => { + await openRemove(); + await expect(dialog).toContainText( + `This removes the plan's ${plan.items.length} events from Google Calendar. The plan and its sessions stay here.`, + ); + await dialog.getByRole("button", { name: "Cancel" }).click(); + await expect(dialog).toBeHidden(); + // The menu item is gone with the menu, so focus goes back to the menu button + await expect(more).toBeFocused(); + expect((await publication(testUser.api, plan.id)).items).toHaveLength(plan.items.length); + }); + + await openRemove(); + await dialog.getByRole("button", { name: "Remove events" }).click(); + await expect(dialog).toBeHidden(); + await expect(toasts(page)).toContainText("Removed from Google Calendar"); + await expect(more).toBeFocused(); + await expect(page.getByRole("button", { name: "Add to Google Calendar" })).toBeVisible(); + await expect(page.getByText("In Google Calendar", { exact: true })).toHaveCount(0); + + const removed = await publication(testUser.api, plan.id); + expect(removed.publication?.status).toBe("UNPUBLISHED"); + expect(removed.items).toEqual([]); +}); + +test("a plan in Google Calendar asks to reconnect when the sign-in expired", { tag: "@a11y" }, async ({ + testUserPage: page, + testUser, +}) => { + await seedGoogle(testUser.api); + const plan = await seedPlan(testUser.api, "E2E Calendar reconnect"); + const published = await testUser.api.post(`/api/plans/${plan.id}/publish/google`, { data: {} }); + expect(published.status(), await published.text()).toBe(200); + await seedGoogle(testUser.api, "ERROR"); + + await page.goto(`/plan?plan=${plan.id}`); + // A notice that is there on arrival, so it isn't announced as an alert + const notice = page + .getByRole("main") + .locator('[data-slot="alert"]') + .filter({ hasText: "Google Calendar needs you to sign in again." }); + await expect(notice).toContainText("Until then, changes to this plan don't reach Google Calendar."); + await expect(notice.getByRole("link", { name: "Reconnect Google Calendar" })).toHaveAttribute( + "href", + "/settings#calendar", + ); + // Nothing to add while the events are still there + await expect(page.getByRole("button", { name: "Add to Google Calendar" })).toHaveCount(0); + + const more = page.getByRole("button", { name: `More actions for the ${EXAM} plan` }); + await hydrated(more); + await more.click(); + await expect(page.getByRole("menuitem", { name: "Update Google Calendar" })).toBeDisabled(); + await expect(page.getByRole("menuitem", { name: "Remove from Google Calendar" })).toBeDisabled(); + await page.keyboard.press("Escape"); + await expect(more).toBeFocused(); + + await expectNoAxeViolations(page, "the plan with a Google Calendar sign-in to renew"); +}); diff --git a/e2e/plan-to-run.spec.ts b/e2e/plan-to-run.spec.ts deleted file mode 100644 index 27456d11..00000000 --- a/e2e/plan-to-run.spec.ts +++ /dev/null @@ -1,244 +0,0 @@ -import { test, expect } from "@playwright/test"; - -const BASE_URL = process.env.BASE_URL || "http://localhost:3000"; -const USER_ID = "e2e_plan_user"; - -const PLAN_PAYLOAD = { - course_name: "E2E Plan 101", - exam_name: "Final Exam", - exam_date: "2025-12-15", - objectives: [ - "Page navigation", - "Form validation", - "API integration", - "Error handling", - "State management", - ], - availability: Array.from({ length: 7 }, () => ({ - start: "09:00", - end: "17:00", - })), - daily_study_cap_minutes: 180, - break_protocol_default: "50_10", -}; - -let planId: string; -let firstSessionId: string; - -test.describe.serial("E2E: Plan → Session → Run continuity", () => { - test("create plan via API", async ({ request }) => { - const response = await request.post(`${BASE_URL}/api/plans`, { - headers: { - "Content-Type": "application/json", - "X-User-Id": USER_ID, - }, - data: PLAN_PAYLOAD, - }); - - expect(response.status()).toBe(201); - const body = await response.json(); - expect(body.plan_id).toBeDefined(); - expect(body.items.length).toBeGreaterThanOrEqual(5); - - planId = body.plan_id; - firstSessionId = body.items[0].session_id; - - // Verify all required session types exist - const modes = body.items.map((i: any) => i.mode); - expect(modes).toContain("RETRIEVAL"); - expect(modes).toContain("INTERLEAVED_PRACTICE"); - expect(modes).toContain("EXAM_SIM"); - expect(modes).toContain("ERROR_REPAIR"); - - // Verify first session is RETRIEVAL (diagnostic) - expect(body.items[0].mode).toBe("RETRIEVAL"); - }); - - test("GET plan returns correct items", async ({ request }) => { - const response = await request.get(`${BASE_URL}/api/plans/${planId}`, { - headers: { "X-User-Id": USER_ID }, - }); - - expect(response.status()).toBe(200); - const body = await response.json(); - expect(body.plan_id).toBe(planId); - expect(body.course_name).toBe("E2E Plan 101"); - expect(body.items.length).toBeGreaterThanOrEqual(5); - - for (const item of body.items) { - expect(item.session_url).toContain("/s/"); - expect(item.calendar).toBeTruthy(); - } - }); - - test("GET plan ICS returns valid calendar file", async ({ request }) => { - const response = await request.get(`${BASE_URL}/api/plans/${planId}/ics`, { - headers: { "X-User-Id": USER_ID }, - }); - - expect(response.status()).toBe(200); - const contentType = response.headers()["content-type"]; - expect(contentType).toContain("text/calendar"); - - const body = await response.text(); - expect(body).toContain("BEGIN:VCALENDAR"); - expect(body).toContain("END:VCALENDAR"); - - const eventCount = (body.match(/BEGIN:VEVENT/g) || []).length; - expect(eventCount).toBeGreaterThanOrEqual(5); - - expect(body).toContain("UID:"); - expect(body).toContain("DTSTART:"); - expect(body).toContain("DTEND:"); - expect(body).toContain("SUMMARY:"); - expect(body).toContain("DESCRIPTION:"); - expect(body).toContain("/s/"); - - // No duplicate UIDs - const uidMatches = body.match(/UID:.+/g) || []; - const uids = uidMatches.map((m: string) => m.trim()); - expect(new Set(uids).size).toBe(uids.length); - }); - - test("ICS content-disposition has filename", async ({ request }) => { - const response = await request.get(`${BASE_URL}/api/plans/${planId}/ics`, { - headers: { "X-User-Id": USER_ID }, - }); - - const disposition = response.headers()["content-disposition"]; - expect(disposition).toContain("attachment"); - expect(disposition).toContain(".ics"); - }); - - test("session page renders for plan-created session", async ({ page }) => { - await page.goto(`/s/${firstSessionId}`); - await expect(page.getByText("E2E Plan 101")).toBeVisible(); - await expect(page.getByText("Final Exam")).toBeVisible(); - }); - - test("start run on plan-created session via API", async ({ request }) => { - const response = await request.post( - `${BASE_URL}/api/sessions/${firstSessionId}/runs/start`, - { headers: { "X-User-Id": USER_ID } } - ); - - expect(response.status()).toBe(201); - const body = await response.json(); - expect(body.status).toBe("ACTIVE"); - expect(body.current_index).toBe(0); - expect(body.prompts.length).toBeGreaterThan(0); - expect(body.break_state).toBeDefined(); - }); - - test("submit attempt on plan-created session", async ({ request }) => { - // Resume run to get run_id - const startRes = await request.post( - `${BASE_URL}/api/sessions/${firstSessionId}/runs/start`, - { headers: { "X-User-Id": USER_ID } } - ); - expect(startRes.status()).toBe(200); - const run = await startRes.json(); - expect(run.resumed).toBe(true); - - // Submit attempt - const attemptRes = await request.post( - `${BASE_URL}/api/runs/${run.run_id}/attempt`, - { - headers: { - "Content-Type": "application/json", - "X-User-Id": USER_ID, - }, - data: { - prompt_index: 0, - user_answer: "Page navigation uses routing and URL matching", - self_score: "CORRECT", - time_to_answer_seconds: 30, - }, - } - ); - - expect(attemptRes.status()).toBe(200); - const result = await attemptRes.json(); - expect(result.current_index).toBe(1); - // Plan-created sessions carry never-studied objectives, so the deck may - // start with a PRE_TEST diagnostic — quarantined from graded metrics by - // design (Richland 2009) and tracked separately. - const firstPrompt = (run.prompts as { meta?: { pack?: string } }[])[0]; - if (firstPrompt?.meta?.pack === "PRE_TEST") { - expect(result.metrics.pretest_count).toBe(1); - expect(result.metrics.pretest_correct).toBe(1); - expect(result.metrics.correct_count).toBe(0); - } else { - expect(result.metrics.correct_count).toBe(1); - expect(result.metrics.attempts_count).toBe(1); - } - }); - - test("resume preserves state after attempt", async ({ request }) => { - const response = await request.post( - `${BASE_URL}/api/sessions/${firstSessionId}/runs/start`, - { headers: { "X-User-Id": USER_ID } } - ); - - expect(response.status()).toBe(200); - const body = await response.json(); - expect(body.resumed).toBe(true); - expect(body.current_index).toBe(1); - // One attempt exists either way; it counts toward graded metrics only - // when it wasn't a pretest diagnostic. - const m = body.metrics as { attempts_count: number; pretest_count?: number }; - expect(m.attempts_count + (m.pretest_count ?? 0)).toBe(1); - }); -}); - -test.describe("E2E: Plan security", () => { - test.use({ extraHTTPHeaders: {} }); - let planId: string; - - test.beforeAll(async ({ request }) => { - const res = await request.post(`${BASE_URL}/api/plans`, { - headers: { - "Content-Type": "application/json", - "X-User-Id": "plan_owner_sec", - }, - data: { - ...PLAN_PAYLOAD, - course_name: "SEC Plan", - }, - }); - const body = await res.json(); - planId = body.plan_id; - }); - - test("other user cannot view plan (403)", async ({ request }) => { - const res = await request.get(`${BASE_URL}/api/plans/${planId}`, { - headers: { "X-User-Id": "intruder" }, - }); - expect(res.status()).toBe(403); - }); - - test("other user cannot export ICS (403)", async ({ request }) => { - const res = await request.get(`${BASE_URL}/api/plans/${planId}/ics`, { - headers: { "X-User-Id": "intruder" }, - }); - expect(res.status()).toBe(403); - }); - - test("unknown plan_id returns 404", async ({ request }) => { - const res = await request.get(`${BASE_URL}/api/plans/nonexistent_plan`, { - headers: { "X-User-Id": "anyone" }, - }); - expect(res.status()).toBe(404); - }); - - test("missing auth returns 401", async ({ request }) => { - const res = await request.post(`${BASE_URL}/api/plans`, { - headers: { - "Content-Type": "application/json", - "X-User-Id": "", - }, - data: PLAN_PAYLOAD, - }); - expect(res.status()).toBe(401); - }); -}); diff --git a/e2e/plan-to-session.spec.ts b/e2e/plan-to-session.spec.ts new file mode 100644 index 00000000..75e14428 --- /dev/null +++ b/e2e/plan-to-session.spec.ts @@ -0,0 +1,28 @@ +/** + * A plan's sessions open from the Plan page. Plan scheduling and the .ics + * file are covered by src/__tests__/integration/plan-flow.test.ts and + * api-contract.spec.ts. + */ +import { test, expect, createPlan, unique } from "./fixtures"; + +test("a session in a plan opens from the Plan page", { tag: "@mobile" }, async ({ page, request }) => { + const plan = await createPlan(request, { course_name: unique("E2E Plan"), exam_name: "Prelim 1", exam_in_days: 14 }); + + await page.goto(`/plan?plan=${plan.id}`); + const main = page.getByRole("main"); + await expect(main.getByRole("heading", { level: 2, name: `${plan.course} Prelim 1` })).toBeVisible(); + await expect(main.getByText("Prelim 1 is in 14 days", { exact: false })).toBeVisible(); + + const sessions = main.getByRole("list", { name: "Prelim 1 sessions by day" }); + const firstSession = sessions.getByRole("link").first(); + const mode = (await firstSession.innerText()).trim(); + await firstSession.click(); + + await expect(page).toHaveURL(/\/s\/[\w-]+$/); + await expect(page.getByRole("heading", { level: 1 })).toContainText(`${mode}:`); + // A link into a session moves focus to its heading, so a screen reader names + // the session even though its tab title is still streaming in. + await expect(page.getByRole("heading", { level: 1 })).toBeFocused(); + await expect(page.getByRole("main").getByText(plan.course)).toBeVisible(); + await expect(page.getByRole("button", { name: "Start session" })).toBeEnabled(); +}); diff --git a/e2e/plan.spec.ts b/e2e/plan.spec.ts new file mode 100644 index 00000000..fd6afb0a --- /dev/null +++ b/e2e/plan.spec.ts @@ -0,0 +1,362 @@ +/** + * Plan screens: New plan (upload through the keyboard file picker, + * validation, typed topics), the plan as dated days with statuses, + * Reschedule sessions, Export calendar (.ics), Replace plan and Delete + * plan. Each test seeds its own identity, so Plan's default plan and its + * empty state belong to the test. + * + * Already covered elsewhere: scheduling, replace-after-create and reflow + * rules in src/__tests__/integration/plan-flow.test.ts and + * reflow-api.test.ts, the .ics headers and links in api-contract.spec.ts, + * and opening a session from the list in plan-to-session.spec.ts. + */ +import { readFile } from "node:fs/promises"; +import type { APIRequestContext } from "@playwright/test"; +import { + test, + expect, + MODE_LABELS, + TIME_ZONE, + createPlan, + isoDay, + hydrated, + setItemStatus, + toasts, + unique, + type CreatedPlan, + type PlanItem, +} from "./fixtures"; + +const EXAM = "Prelim 1"; + +/** "Friday, October 16": how the plan names a day (calendar keys are read at noon UTC). */ +function dayHeading(value: string | Date, timeZone: string): string { + return new Intl.DateTimeFormat("en-US", { weekday: "long", month: "long", day: "numeric", timeZone }).format( + new Date(value), + ); +} + +/** "Retrieval, 9:00 – 9:30 AM", the session link's name, as a pattern (Intl puts thin spaces in ranges). */ +function sessionLinkName(item: PlanItem): RegExp { + const parts = (value: string) => + new Intl.DateTimeFormat("en-US", { hour: "numeric", minute: "2-digit", timeZone: TIME_ZONE }) + .format(new Date(value)) + .split(/\s/); + const [startTime, startHalf] = parts(item.start_time); + const [endTime, endHalf] = parts(item.end_time); + return new RegExp(`^${MODE_LABELS[item.mode]}, ${startTime}(\\s${startHalf})?\\s–\\s${endTime}\\s${endHalf}$`); +} + +async function listPlans(api: APIRequestContext): Promise<{ plan_id: string; course_name: string; items: PlanItem[] }[]> { + const response = await api.get("/api/plans"); + expect(response.status()).toBe(200); + return (await response.json()).plans; +} + +/** A Prelim 1 plan in New York, 9:00 to 17:00 every day, with at least 3 sessions. */ +async function seedPlan(api: APIRequestContext, course: string): Promise<CreatedPlan> { + const plan = await createPlan(api, { course_name: course, exam_name: EXAM }); + expect(plan.items.length).toBeGreaterThan(2); + return plan; +} + +test("Create plan uses a file chosen with the keyboard and opens the new plan", { tag: "@mobile" }, async ({ + testUserPage: page, +}) => { + test.slow(); + const course = unique("E2E New plan"); + await page.goto("/plan/new"); + await expect(page.getByRole("heading", { level: 2, name: "Plan for an exam" })).toBeVisible(); + + const dropzone = page.getByRole("group", { name: "Upload materials" }); + const chooseFiles = dropzone.getByRole("button", { name: "Choose files" }); + // Files are saved to a course, so the picker waits for one. + await expect(chooseFiles).toBeDisabled(); + await expect(dropzone).toContainText("Enter the course name first. Files are saved to that course."); + + await hydrated(page.getByRole("combobox", { name: "Course" })); + await page.getByRole("combobox", { name: "Course" }).fill(course); + await page.getByRole("textbox", { name: "Exam", exact: true }).fill("Prelim 1"); + await page.getByRole("textbox", { name: "Exam date" }).fill(isoDay(10)); + await expect(chooseFiles).toBeEnabled(); + + await test.step("choose a file with the keyboard", async () => { + const chooser = page.waitForEvent("filechooser"); + await chooseFiles.press("Enter"); + await (await chooser).setFiles({ + name: "lecture-1.md", + mimeType: "text/markdown", + buffer: Buffer.from("# Recursion\n\nA recursive function calls itself on a smaller input until it reaches a base case."), + }); + const row = page.getByRole("listitem").filter({ hasText: "lecture-1.md" }); + await expect(row).toContainText(`Saved to ${course}, Prelim 1`); + await expect(row).toContainText("Ready"); + }); + + await page.getByRole("button", { name: "Create plan" }).click(); + await expect(page).toHaveURL(/\/plan\?plan=[\w-]+$/); + await expect(page.getByRole("heading", { level: 2, name: `${course} Prelim 1` })).toBeVisible(); + await expect(page.getByRole("main").getByText(/^Prelim 1 is in 10 days: /)).toBeVisible(); + await expect(toasts(page)).toContainText(/Plan created\. \d+ sessions? between today and Prelim 1/); + const materials = page.getByRole("region", { name: "Materials" }); + await expect(materials.getByRole("listitem").filter({ hasText: "lecture-1.md" })).toContainText("Ready"); +}); + +test("New plan names each missing field and sends nothing until they are fixed", async ({ testUserPage: page }) => { + const course = unique("E2E Checks"); + const creates: string[] = []; + page.on("request", (request) => { + if (request.method() === "POST" && new URL(request.url()).pathname === "/api/plans") creates.push(request.url()); + }); + await page.goto("/plan/new"); + const create = page.getByRole("button", { name: "Create plan" }); + const problem = page.getByRole("alert").filter({ hasText: "Check the highlighted fields." }); + const courseBox = page.getByRole("combobox", { name: "Course" }); + + await test.step("an empty form", async () => { + await hydrated(create); + await create.click(); + await expect(problem).toBeVisible(); + await expect(courseBox).toBeFocused(); + await expect(courseBox).toHaveAttribute("aria-invalid", "true"); + await expect(courseBox).toHaveAccessibleDescription(/Enter a course name\./); + await expect(page.getByRole("textbox", { name: "Exam", exact: true })).toHaveAccessibleDescription( + /Enter an exam name\./, + ); + await expect(page.getByRole("textbox", { name: "Exam date" })).toHaveAccessibleDescription(/Choose the exam date\./); + }); + + await test.step("no materials and no topics", async () => { + await courseBox.fill(course); + await page.getByRole("textbox", { name: "Exam", exact: true }).fill("Prelim 1"); + await page.getByRole("textbox", { name: "Exam date" }).fill(isoDay(12)); + await create.click(); + await expect(page.getByRole("main").getByText("Upload materials, or type at least 3 topics instead.")).toBeVisible(); + }); + + await test.step("too few typed topics", async () => { + await page.getByRole("checkbox", { name: "Type topics instead" }).check(); + const topics = page.getByRole("textbox", { name: "Topics" }); + await topics.fill("Recursion\nGraphs"); + await expect(topics).toHaveAccessibleDescription(/2 typed\./); + await create.click(); + await expect(topics).toBeFocused(); + await expect(topics).toHaveAccessibleDescription(/Type at least 3 topics, one per line\./); + expect(creates).toHaveLength(0); + }); + + await page.getByRole("textbox", { name: "Topics" }).fill("Recursion\nGraphs\nSorting"); + await create.click(); + await expect(page.getByRole("heading", { level: 2, name: `${course} Prelim 1` })).toBeVisible(); + expect(creates).toHaveLength(1); +}); + +test("the plan lists its sessions by day with each one's status", { tag: "@mobile" }, async ({ + testUserPage: page, + testUser, +}) => { + const plan = await seedPlan(testUser.api, unique("E2E Days")); + const [done, missed] = plan.items; + await setItemStatus(testUser.api, plan.id, done.id, "DONE"); + await setItemStatus(testUser.api, plan.id, missed.id, "MISSED"); + const total = plan.items.length; + + await page.goto(`/plan?plan=${plan.id}`); + const main = page.getByRole("main"); + await expect(main.getByRole("heading", { level: 2, name: `${plan.course} Prelim 1` })).toBeVisible(); + await expect(main.getByText(/^Prelim 1 is in 14 days: \w{3}, \w{3} \d{1,2}\.$/)).toBeVisible(); + + const progress = main.getByRole("region", { name: "Progress" }); + await expect(progress.getByRole("progressbar", { name: "Plan progress" })).toHaveAttribute( + "aria-valuetext", + `1 of ${total} sessions done`, + ); + await expect(progress.getByRole("listitem")).toHaveText(["1 done", "1 missed", `${total - 2} scheduled`]); + + const sessions = main.getByRole("region", { name: "Sessions" }); + await expect(sessions.getByText(`${total} sessions in this plan`)).toBeVisible(); + const days = sessions.getByRole("list", { name: "Prelim 1 sessions by day" }); + + const doneDay = days.getByRole("listitem", { name: new RegExp(`^${dayHeading(done.start_time, TIME_ZONE)}`) }); + const doneRow = doneDay.getByRole("listitem").filter({ has: page.getByRole("link", { name: sessionLinkName(done) }) }); + await expect(doneRow).toContainText("Done"); + + const missedDay = days.getByRole("listitem", { name: new RegExp(`^${dayHeading(missed.start_time, TIME_ZONE)}`) }); + const missedRow = missedDay + .getByRole("listitem") + .filter({ has: page.getByRole("link", { name: sessionLinkName(missed) }) }); + await expect(missedRow).toContainText("Missed"); + await expect(missedRow.getByRole("button", { name: /^Reschedule missed session: / })).toBeVisible(); + + const examDay = days.getByRole("listitem", { + name: `${dayHeading(`${plan.examDate}T12:00:00Z`, "UTC")}, exam day`, + }); + await expect(examDay).toContainText("Exam day: Prelim 1"); +}); + +test("Reschedule sessions previews the move and applies it after confirming", { tag: "@mobile" }, async ({ + testUserPage: page, + testUser, +}) => { + const plan = await seedPlan(testUser.api, unique("E2E Reschedule")); + const missed = plan.items[1]; + await setItemStatus(testUser.api, plan.id, missed.id, "MISSED"); + const statusOf = async () => + (await listPlans(testUser.api)).find((p) => p.plan_id === plan.id)?.items.find((i) => i.id === missed.id)?.status; + + await page.goto(`/plan?plan=${plan.id}`); + const reschedule = page.getByRole("button", { name: "Reschedule sessions" }); + await hydrated(reschedule); + await reschedule.click(); + + const dialog = page.getByRole("dialog", { name: "Reschedule sessions" }); + await expect(dialog).toContainText("Nothing changes until you confirm."); + await expect(dialog.getByRole("status").filter({ hasText: /^1 session moves and \d+ stays?\.$/ })).toBeVisible(); + const moves = dialog.getByRole("region", { name: "New times" }); + await expect(moves.getByRole("listitem")).toHaveCount(1); + await expect(moves.getByRole("listitem")).toContainText(MODE_LABELS[missed.mode]); + await expect(moves.getByRole("listitem")).toContainText("Missed"); + // The preview moves nothing. + expect(await statusOf()).toBe("MISSED"); + + await dialog.getByRole("button", { name: "Move 1 session" }).click(); + await expect(dialog).toBeHidden(); + await expect(toasts(page)).toContainText("1 session moved"); + await expect(reschedule).toBeFocused(); + await expect(page.getByRole("region", { name: "Progress" }).getByRole("listitem")).toHaveText([ + "0 done", + `${plan.items.length} scheduled`, + ]); + expect(await statusOf()).toBe("RESCHEDULED"); +}); + +test("Reschedule sessions previews afresh after leaving the plan and coming back", async ({ + testUserPage: page, + testUser, +}) => { + // Each visit to a plan used to restart the preview's cache key, so coming + // back served the first visit's preview from the cache. + const plan = await seedPlan(testUser.api, unique("E2E Fresh preview")); + const other = await seedPlan(testUser.api, unique("E2E Other plan")); + await setItemStatus(testUser.api, plan.id, plan.items[1].id, "MISSED"); + + await page.goto(`/plan?plan=${plan.id}`); + const reschedule = page.getByRole("button", { name: "Reschedule sessions" }); + const dialog = page.getByRole("dialog", { name: "Reschedule sessions" }); + const summary = dialog.getByRole("status").filter({ hasText: /sessions? moves?/ }); + await hydrated(reschedule); + await reschedule.click(); + await expect(summary).toHaveText(/^1 session moves and \d+ stays?\.$/); + await dialog.getByRole("button", { name: "Cancel" }).click(); + await expect(dialog).toBeHidden(); + + await test.step("open the other plan, miss another session, and come back", async () => { + const plans = page.getByRole("navigation", { name: "Plans" }); + await plans.getByRole("link", { name: new RegExp(other.course) }).click(); + await expect(page.getByRole("heading", { level: 2, name: `${other.course} Prelim 1` })).toBeVisible(); + await setItemStatus(testUser.api, plan.id, plan.items[2].id, "MISSED"); + await plans.getByRole("link", { name: new RegExp(plan.course) }).click(); + await expect(page.getByRole("heading", { level: 2, name: `${plan.course} Prelim 1` })).toBeVisible(); + }); + + await hydrated(reschedule); + await reschedule.click(); + await expect(summary).toHaveText(/^2 sessions move and \d+ stays?\.$/); + await expect(dialog.getByRole("region", { name: "New times" }).getByRole("listitem")).toHaveCount(2); + await expect(dialog.getByRole("button", { name: "Move 2 sessions" })).toBeVisible(); +}); + +test("Export calendar downloads the plan as an .ics file", async ({ testUserPage: page, testUser }) => { + const plan = await seedPlan(testUser.api, unique("E2E Export")); + await page.goto(`/plan?plan=${plan.id}`); + + const exportButton = page.getByRole("button", { name: "Export calendar (.ics)" }); + await hydrated(exportButton); + const download = page.waitForEvent("download"); + await exportButton.click(); + const file = await download; + expect(file.suggestedFilename()).toMatch(/-plan\.ics$/); + await expect(toasts(page)).toContainText("Calendar file exported"); + + // Unfold the 75-octet lines before matching. + const ics = (await readFile(await file.path(), "utf8")).replace(/\r\n[ \t]/g, ""); + expect(ics).toMatch(/^BEGIN:VCALENDAR/); + expect(ics.match(/BEGIN:VEVENT/g)).toHaveLength(plan.items.length); + expect(ics.match(new RegExp(`^SUMMARY:.*${plan.course} Prelim 1$`, "gm"))).toHaveLength(plan.items.length); + for (const item of plan.items) expect(ics).toContain(`/s/${item.session_id}`); +}); + +test("Replace plan asks first, then swaps the old plan for the new one", async ({ testUserPage: page, testUser }) => { + test.slow(); + const plan = await seedPlan(testUser.api, unique("E2E Replace")); + const plansFor = async () => + (await listPlans(testUser.api)).filter((p) => p.course_name === plan.course).map((p) => p.plan_id); + + await page.goto(`/plan?plan=${plan.id}`); + const more = page.getByRole("button", { name: "More actions for the Prelim 1 plan" }); + await hydrated(more); + await more.click(); + await page.getByRole("menuitem", { name: "Replace plan" }).click(); + + await expect(page).toHaveURL(new RegExp(`/plan/new\\?replace=${plan.id}$`)); + await expect(page.getByRole("heading", { level: 2, name: `Replace the ${plan.course} Prelim 1 plan` })).toBeVisible(); + await expect(page).toHaveTitle(`Replace ${plan.course} Prelim 1 plan · Study Bot`); + await expect(page.getByRole("combobox", { name: "Course" })).toHaveValue(plan.course); + await expect(page.getByRole("textbox", { name: "Exam", exact: true })).toHaveValue("Prelim 1"); + await expect(page.getByRole("textbox", { name: "Exam date" })).toHaveValue(plan.examDate); + await hydrated(page.getByRole("checkbox", { name: "Type topics instead" })); + await page.getByRole("checkbox", { name: "Type topics instead" }).check(); + await page.getByRole("textbox", { name: "Topics" }).fill("Recursion\nGraphs\nSorting"); + + const create = page.getByRole("button", { name: "Create plan" }); + const dialog = page.getByRole("alertdialog", { name: `Replace your ${plan.course} plan?` }); + await test.step("Cancel keeps the current plan", async () => { + await create.click(); + await expect(dialog).toContainText( + `Creating this plan deletes the current one for Prelim 1 and its ${plan.items.length} remaining sessions.`, + ); + await dialog.getByRole("button", { name: "Cancel" }).click(); + await expect(dialog).toBeHidden(); + await expect(create).toBeFocused(); + expect(await plansFor()).toEqual([plan.id]); + }); + + await create.click(); + await dialog.getByRole("button", { name: "Replace plan" }).click(); + await expect(page).toHaveURL(/\/plan\?plan=[\w-]+$/); + await expect(page).not.toHaveURL(new RegExp(plan.id)); + await expect(page.getByRole("heading", { level: 2, name: `${plan.course} Prelim 1` })).toBeVisible(); + const remaining = await plansFor(); + expect(remaining).toHaveLength(1); + expect(remaining[0]).not.toBe(plan.id); + + await page.goto(`/plan?plan=${plan.id}`); + await expect(page.getByRole("main").getByText("This plan doesn't exist anymore.")).toBeVisible(); +}); + +test("Delete plan asks first and removes the plan", { tag: "@mobile" }, async ({ testUserPage: page, testUser }) => { + const plan = await seedPlan(testUser.api, unique("E2E Delete")); + await page.goto(`/plan?plan=${plan.id}`); + const more = page.getByRole("button", { name: "More actions for the Prelim 1 plan" }); + const dialog = page.getByRole("alertdialog", { name: "Delete the Prelim 1 plan?" }); + + await test.step("Cancel keeps it", async () => { + await hydrated(more); + await more.click(); + await page.getByRole("menuitem", { name: "Delete plan" }).click(); + await expect(dialog).toContainText( + `Its ${plan.items.length} remaining sessions come off your schedule. Your answers and progress stay, and so do events already in Google Calendar.`, + ); + await dialog.getByRole("button", { name: "Cancel" }).click(); + await expect(dialog).toBeHidden(); + await expect(more).toBeFocused(); + }); + + await more.click(); + await page.getByRole("menuitem", { name: "Delete plan" }).click(); + await dialog.getByRole("button", { name: "Delete plan" }).click(); + await expect(toasts(page)).toContainText("Prelim 1 plan deleted"); + await expect(page).toHaveURL(/\/plan$/); + await expect(page.getByRole("heading", { level: 2, name: "No plan yet" })).toBeVisible(); + expect(await listPlans(testUser.api)).toEqual([]); +}); diff --git a/e2e/progress.spec.ts b/e2e/progress.spec.ts new file mode 100644 index 00000000..d586dec6 --- /dev/null +++ b/e2e/progress.spec.ts @@ -0,0 +1,152 @@ +/** + * Progress (/achievements): mastery by topic (weakest first, A to Z), the + * Confidence section and its table, the streak and XP cards, the activity + * heatmap's text summary and day list, and achievements. Each test seeds + * its own identity through the API, because Progress shows the whole + * account. + * + * Already covered elsewhere: calibration and heatmap maths in + * src/__tests__/progress-model.test.ts, mastery in mastery.test.ts, XP and + * streak rules in gamification.test.ts, and Progress's empty-state axe scan + * in shell.spec.ts. + */ +import { test, expect, answerRun, createPlan, createSession, finishSession, hydrated, openWhen, unique } from "./fixtures"; + +test("mastery lists the weakest topic first and sorts A to Z on request", { tag: "@mobile" }, async ({ + testUserPage: page, + testUser, +}) => { + test.slow(); + const course = unique("E2E Mastery"); + await createPlan(testUser.api, { course_name: course, exam_name: "Prelim 1", objectives: ["Arrays", "Hashing", "Recursion"] }); + const arrays = await createSession(testUser.api, { + course_name: course, + topic_scope: "Arrays", + objectives: [{ id: "arrays", title: "Arrays" }], + }); + await answerRun(testUser.api, arrays.id, [{ score: "CORRECT" }]); + const recursion = await createSession(testUser.api, { + course_name: course, + topic_scope: "Recursion", + objectives: [{ id: "recursion", title: "Recursion" }], + }); + await answerRun(testUser.api, recursion.id, [{ score: "INCORRECT" }]); + + const mastery = page.getByRole("region", { name: "Mastery by topic" }); + const card = mastery.getByRole("group", { name: course }); + // Mastery is written just after the run completes. + await openWhen(page, "/achievements", card.getByRole("meter", { name: "Recursion mastery" })); + await expect(card).toContainText("Prelim 1 is in 14 days"); + await expect(card).toContainText("0 of 3 topics mastered"); + await expect(card.getByRole("meter", { name: "Arrays mastery" })).toHaveAttribute("aria-valuenow", "100"); + + const rows = card.getByRole("listitem"); + await expect(mastery.getByRole("radio", { name: "Weakest first" })).toBeChecked(); + await expect(rows).toHaveText([/^Recursion/, /^Arrays/, /^Hashing\s*Not practiced/]); + await expect(card.getByRole("button", { name: "Practice Hashing" })).toBeVisible(); + + await hydrated(mastery.getByRole("radio", { name: "A to Z" })); + await mastery.getByRole("radio", { name: "A to Z" }).click(); + await expect(mastery.getByRole("radio", { name: "A to Z" })).toBeChecked(); + await expect(rows).toHaveText([/^Arrays/, /^Hashing/, /^Recursion/]); +}); + +test("Confidence compares how sure the student was with how often they were correct", async ({ + testUserPage: page, + testUser, +}) => { + const session = await createSession(testUser.api, { course_name: unique("E2E Confidence") }); + // Sure and correct, Sure and wrong, Guessing and correct. + await answerRun(testUser.api, session.id, [ + { score: "CORRECT", confidence: 5 }, + { score: "INCORRECT", confidence: 5 }, + { score: "CORRECT", confidence: 1 }, + ]); + + await page.goto("/achievements"); + const confidence = page.getByRole("region", { name: "Confidence" }); + await expect(confidence.getByRole("heading", { level: 3, name: "All rated questions, last 12 weeks" })).toBeVisible(); + const table = confidence.getByRole("table"); + await expect(table.getByRole("columnheader")).toHaveText(["How sure", "Questions", "Correct"]); + await expect(table.getByRole("rowheader")).toHaveText(["Sure", "Unsure", "Guessing"]); + await expect(table.getByRole("row", { name: /^Sure/ }).getByRole("cell")).toHaveText(["2", /50%$/]); + await expect(table.getByRole("row", { name: /^Unsure/ }).getByRole("cell")).toHaveText(["0", "No questions"]); + await expect(table.getByRole("row", { name: /^Guessing/ }).getByRole("cell")).toHaveText(["1", /100%$/]); + await expect(table.getByRole("progressbar", { name: "Correct when Sure" })).toHaveAttribute("aria-valuetext", "50%"); + + await expect(confidence).toContainText( + "Overconfident on 1 question: you marked it Sure and it wasn't fully correct. Errors you marked Sure come first in Error repair.", + ); + await expect(confidence).toContainText("Underconfident on 1 question: you marked it Guessing and it was correct."); + await expect(confidence).toContainText( + "The weekly trend appears once you have rated questions from 2 different weeks.", + ); +}); + +test("a finished session shows in the streak, XP, activity and achievements", { tag: "@mobile" }, async ({ + testUserPage: page, + testUser, + isMobile, +}) => { + const session = await createSession(testUser.api, { course_name: unique("E2E Streak") }); + await finishSession(testUser.api, session.id); + + const streakXp = page.getByRole("region", { name: "Streak and XP" }); + // XP, and with it the streak, is written just after the run completes. + await openWhen(page, "/achievements", streakXp.getByText("1-day streak", { exact: true })); + + await test.step("streak and XP", async () => { + await expect(streakXp.getByRole("status")).toHaveText("Today counts. Study tomorrow to keep it going."); + await expect(streakXp.getByRole("progressbar", { name: "Daily XP goal" })).toHaveAttribute( + "aria-valuetext", + /^10 of \d+ XP today$/, + ); + await expect(streakXp).toContainText("10 XP in total."); + }); + + await test.step("activity", async () => { + const activity = page.getByRole("region", { name: "Activity" }); + // The squares are hidden from assistive technology; the sentence and the list carry the data. + await expect(activity.getByText("Active on 1 day in the last 12 months.")).toBeVisible(); + const showList = activity.getByRole("button", { name: "Show study days as a list" }); + await hydrated(showList); + + const heatmap = activity.getByRole("region", { name: "Activity heatmap, last 12 months" }); + if (isMobile) { + // A phone is narrower than the year, so the scroller is a tab stop. Focusing it + // reads the summary and points to the list, since the squares themselves are silent. + await expect(heatmap).toHaveAccessibleDescription( + /^Active on 1 day in the last 12 months\. Each square is a day\..*show the study days as a list\.$/, + ); + await heatmap.focus(); + await expect(heatmap).toBeFocused(); + } else { + // At desktop width the whole year fits: no empty region and no extra tab stop. + await expect(heatmap).toHaveCount(0); + } + + await showList.click(); + await expect(activity.getByRole("button", { name: "Hide the list" })).toHaveAttribute("aria-expanded", "true"); + // A new identity has no plan or saved zone, so its days are UTC days: "Fri, Oct 16: 1 session". + const today = new Intl.DateTimeFormat("en-US", { weekday: "short", month: "short", day: "numeric", timeZone: "UTC" }).format( + new Date(), + ); + await expect(activity.getByRole("listitem")).toHaveText([`${today}: 1 session`]); + }); + + await test.step("achievements", async () => { + const achievements = page.getByRole("region", { name: "Achievements" }); + await expect(achievements).toContainText( + "No achievements yet. The first comes with a 3-day streak or your first card review.", + ); + await expect(achievements.getByRole("heading", { level: 3 })).toHaveText(["Streaks", "Flashcards", "XP"]); + await expect(achievements.getByRole("progressbar", { name: "3-day streak progress" })).toHaveAttribute( + "aria-valuetext", + "1 of 3 days", + ); + await expect(achievements.getByRole("progressbar", { name: "100 XP progress" })).toHaveAttribute( + "aria-valuetext", + "10 of 100 XP", + ); + }); +}); diff --git a/e2e/reflow-ui.spec.ts b/e2e/reflow-ui.spec.ts deleted file mode 100644 index bd2d6c70..00000000 --- a/e2e/reflow-ui.spec.ts +++ /dev/null @@ -1,170 +0,0 @@ -/** - * Playwright E2E tests for Reflow workflow UI. - * - * Flow: - * 1) Create plan via API - * 2) Publish to Google Calendar via API - * 3) Mark one item MISSED via API - * 4) Navigate to plan page, trigger Preview Reflow - * 5) Verify preview shows moved items - * 6) Apply reflow - * 7) Verify "Reflow applied" banner with calendar update summary - * - * Requires GOOGLE_PROVIDER=fake. - */ -import { test, expect } from "@playwright/test"; - -const BASE = process.env.BASE_URL || "http://localhost:3000"; -const userId = "e2e_reflow_user"; - -test.describe("Reflow UI Workflow", () => { - test.use({ extraHTTPHeaders: { "X-User-Id": userId } }); - - let planId: string; - let planItems: { id: string; session_id: string; day_index: number; start_time: string; end_time: string; status: string }[]; - - test.beforeAll(async ({ request }) => { - // Seed Google integration - const seedRes = await request.post(`${BASE}/api/integrations/google/__test-seed`, { - data: { connected_email: "reflow-e2e@example.com" }, - }); - if (seedRes.status() === 404) { - test.skip(true, "GOOGLE_PROVIDER is not fake — skipping reflow E2E"); - } - - // Create a plan via API - const planRes = await request.post(`${BASE}/api/plans`, { - data: { - course_name: "E2E Reflow Course", - exam_name: "Final Exam", - exam_date: "2026-06-15", - objectives: ["Reflow topic A", "Reflow topic B", "Reflow topic C", "Reflow topic D", "Reflow topic E"], - availability: Array.from({ length: 7 }, () => ({ start: "09:00", end: "17:00" })), - daily_study_cap_minutes: 180, - break_protocol_default: "50_10", - }, - }); - expect(planRes.status()).toBe(201); - const plan = await planRes.json(); - planId = plan.plan_id; - planItems = plan.items; - expect(planItems.length).toBeGreaterThan(2); - - // Publish to Google Calendar - const pubRes = await request.post(`${BASE}/api/plans/${planId}/publish/google`, { - data: {}, - }); - expect(pubRes.status()).toBe(200); - const pubBody = await pubRes.json(); - expect(pubBody.status).toBe("OK"); - - // Mark the first item as MISSED - const firstItem = planItems[0]; - const statusRes = await request.post(`${BASE}/api/plans/${planId}/items/${firstItem.id}/status`, { - data: { status: "MISSED" }, - }); - expect(statusRes.status()).toBe(200); - const statusBody = await statusRes.json(); - expect(statusBody.status).toBe("MISSED"); - }); - - test.afterAll(async ({ request }) => { - await request.delete(`${BASE}/api/integrations/google/__test-seed`); - }); - - test("preview reflow shows moved items after marking one MISSED", async ({ request }) => { - // Call preview endpoint directly - const previewRes = await request.post(`${BASE}/api/plans/${planId}/reflow/preview`, { - data: { reason: "MANUAL", respect_google_busy: false }, - }); - expect(previewRes.status()).toBe(200); - const preview = await previewRes.json(); - - expect(preview.summary.total_items).toBe(planItems.length); - // With one item MISSED, the remaining SCHEDULED items get reflowed - // There should be at least some changes (MOVED or KEPT) - expect(preview.changes.length).toBeGreaterThan(0); - }); - - test("apply reflow moves items and returns audit_id + calendar summary", async ({ request }) => { - const applyRes = await request.post(`${BASE}/api/plans/${planId}/reflow/apply`, { - data: { - reason: "MANUAL", - respect_google_busy: false, - calendar_update: "REPUBLISH", - }, - }); - expect(applyRes.status()).toBe(200); - const applyBody = await applyRes.json(); - - // Should have applied changes - expect(applyBody.applied).toBe(true); - expect(applyBody.audit_id).toBeTruthy(); - expect(applyBody.summary).toBeDefined(); - expect(typeof applyBody.summary.moved).toBe("number"); - expect(typeof applyBody.summary.kept).toBe("number"); - - // Should include calendar republish result - expect(applyBody.calendar).toBeDefined(); - expect(applyBody.calendar.status).toMatch(/OK|PARTIAL/); - if (applyBody.calendar.summary) { - expect(typeof applyBody.calendar.summary.updated).toBe("number"); - } - }); - - test("plan items have updated times and RESCHEDULED status after apply", async ({ request }) => { - // Reload the plan - const planRes = await request.get(`${BASE}/api/plans/${planId}`); - expect(planRes.status()).toBe(200); - const planData = await planRes.json(); - - // The missed item should still be MISSED - const missedItem = planData.items.find((i: { id: string }) => i.id === planItems[0].id); - expect(missedItem).toBeDefined(); - expect(missedItem.status).toBe("MISSED"); - - // Some items should be RESCHEDULED (those that were moved) - const rescheduled = planData.items.filter((i: { status: string }) => i.status === "RESCHEDULED"); - // It's possible no items needed moving if they were already optimal - // but with a MISSED item blocking a slot, at least one should have been rescheduled - // (this depends on the algorithm; let's just verify the statuses are valid) - for (const item of planData.items) { - expect(["SCHEDULED", "RESCHEDULED", "MISSED", "DONE", "SKIPPED", "IN_PROGRESS"]).toContain(item.status); - } - }); - - test("publish status shows published after reflow+republish", async ({ request }) => { - const statusRes = await request.get(`${BASE}/api/plans/${planId}/publish/google`); - expect(statusRes.status()).toBe(200); - const status = await statusRes.json(); - - expect(status.publication).not.toBeNull(); - expect(status.publication.status).toBe("PUBLISHED"); - expect(status.items.length).toBeGreaterThan(0); - }); - - test("locked items are not moved by reflow", async ({ request }) => { - // Lock the second item - const secondItem = planItems[1]; - const lockRes = await request.post(`${BASE}/api/plans/${planId}/items/${secondItem.id}/status`, { - data: { status: "SCHEDULED", locked: true }, - }); - expect(lockRes.status()).toBe(200); - expect((await lockRes.json()).locked).toBe(true); - - // Record its current position - const planBefore = await (await request.get(`${BASE}/api/plans/${planId}`)).json(); - const itemBefore = planBefore.items.find((i: { id: string }) => i.id === secondItem.id); - - // Preview reflow - const previewRes = await request.post(`${BASE}/api/plans/${planId}/reflow/preview`, { - data: { reason: "MANUAL", respect_google_busy: false }, - }); - expect(previewRes.status()).toBe(200); - const preview = await previewRes.json(); - - // Locked item should NOT appear in changes (it's excluded as fixed) - const lockedChange = preview.changes.find((c: { itemId: string }) => c.itemId === secondItem.id); - expect(lockedChange).toBeUndefined(); - }); -}); diff --git a/e2e/session-feedback.spec.ts b/e2e/session-feedback.spec.ts new file mode 100644 index 00000000..c6a0a4d8 --- /dev/null +++ b/e2e/session-feedback.spec.ts @@ -0,0 +1,54 @@ +/** + * Feedback from the student's materials: nothing from them shows before + * the answer is scored, and the feedback section appears after it, citing + * the file that covers the topic. + */ +import { test, expect, createSession, uploadMaterial, unique } from "./fixtures"; + +const NOTES = [ + "Introduction to graph algorithms", + "Dijkstra's shortest path algorithm uses a priority queue to pick the closest unvisited vertex.", + "Bellman-Ford handles negative edge weights but is slower.", +].join("\n\n"); + +test("feedback stays hidden until the answer is scored", async ({ page, request }) => { + const course = unique("E2E Graphs"); + await uploadMaterial(request, { course, fileName: "graphs.txt", text: NOTES }); + const session = await createSession(request, { course_name: course, topic_scope: "Dijkstra's algorithm" }); + + await page.goto(session.url); + await page.getByRole("button", { name: "Start session" }).click(); + const main = page.getByRole("main"); + await expect(main.getByRole("textbox", { name: "Your answer" })).toBeVisible(); + + await test.step("before an answer: no feedback and no text from the materials", async () => { + await expect(main.getByRole("region", { name: "Feedback from your materials" })).toHaveCount(0); + await expect(main).not.toContainText("priority queue"); + }); + + await test.step("after an incorrect answer and its correction: the feedback section", async () => { + await main.getByRole("textbox", { name: "Your answer" }).fill("Dijkstra explores vertices in plain BFS order"); + await page.getByRole("button", { name: "Submit answer" }).click(); + // Scoring shows the answer, still without feedback. + await expect(page.getByRole("group", { name: "Score your answer" })).toBeVisible(); + await expect(main.getByRole("region", { name: "Feedback from your materials" })).toHaveCount(0); + + await page.getByRole("button", { name: "Incorrect", exact: true }).click(); + await main.getByRole("textbox", { name: "Correction rule" }).fill("Dijkstra picks the closest vertex from a priority queue"); + await page.getByRole("button", { name: "Save correction" }).click(); + + const feedback = main.getByRole("region", { name: "Feedback from your materials" }); + await expect(feedback).toBeVisible(); + await expect(feedback.getByRole("region", { name: "Your correction" })).toContainText( + "Dijkstra picks the closest vertex from a priority queue", + ); + // The deferred feedback finishes loading. The uploaded notes cover + // Dijkstra's algorithm, so it cites them: the search matches any of the + // question's words, not all of them, and never claims they don't cover it. + await expect(feedback.getByText("Loading feedback…")).toHaveCount(0); + const sources = feedback.getByRole("region", { name: "Sources" }); + await expect(sources).toBeVisible(); + await expect(sources).toContainText("priority queue"); + await expect(feedback).not.toContainText("Your materials don't cover this question"); + }); +}); diff --git a/e2e/session-results.spec.ts b/e2e/session-results.spec.ts new file mode 100644 index 00000000..46a68d67 --- /dev/null +++ b/e2e/session-results.spec.ts @@ -0,0 +1,71 @@ +/** + * Each mode's finished session opens on its results, named the way the + * student saw it. The runs are finished through the API; the deck rules for + * each mode are covered by src/__tests__/integration/mode-parity.test.ts. + */ +import { test, expect, createPlan, createSession, finishSession, hydrated, unique, type SessionMode } from "./fixtures"; + +const MODES: { mode: SessionMode; label: string; incorrect: number; accuracy: string }[] = [ + { mode: "INTERLEAVED_PRACTICE", label: "Interleaved practice", incorrect: 0, accuracy: "100%" }, + // Exam simulation scores after the last answer, so a wrong score adds no repair question. + { mode: "EXAM_SIM", label: "Exam simulation", incorrect: 1, accuracy: "67%" }, +]; + +for (const { mode, label, incorrect, accuracy } of MODES) { + test(`a finished ${label} session shows its results`, async ({ page, request }) => { + const session = await createSession(request, { course_name: unique(`E2E ${label}`), mode }); + await finishSession(request, session.id, { incorrect }); + + await page.goto(session.url); + const main = page.getByRole("main"); + await expect(main.getByRole("heading", { level: 1, name: "Session complete" })).toBeVisible(); + await expect(main.getByText(`${label}: End-to-end testing`, { exact: true })).toBeVisible(); + await expect(main.getByText(session.course)).toBeVisible(); + await expect(main.getByRole("region", { name: "Session stats" })).toMatchAriaSnapshot(` + - term: Accuracy + - definition: ${accuracy} + `); + await expect(page).toHaveTitle(`Session complete · ${session.course} · Study Bot`); + }); +} + +test("an Error repair session retests the course's unresolved errors", async ({ page, request }) => { + // Two sessions finished through the API plus two page loads. + test.slow(); + const course = unique("E2E Repair"); + // One wrong answer leaves an unresolved error: it resolves only after + // correct answers on 2 different days. + const retrieval = await createSession(request, { course_name: course, questions: 2 }); + await finishSession(request, retrieval.id, { incorrect: 1 }); + + const repair = await createSession(request, { course_name: course, mode: "ERROR_REPAIR", topic_scope: "Unresolved errors" }); + await page.goto(repair.url); + await expect(page.getByRole("heading", { level: 1 })).toHaveText("Error repair: Unresolved errors"); + await page.getByRole("button", { name: "Start session" }).click(); + await expect(page.getByRole("main").getByText(/^Question 1 of 1\b/)).toBeVisible(); + await expect(page.getByRole("heading", { level: 1 })).toContainText("From memory"); + + await finishSession(request, repair.id); + await page.reload(); + await expect(page.getByRole("heading", { level: 1, name: "Session complete" })).toBeVisible(); + await expect(page.getByRole("main").getByText("Error repair: Unresolved errors", { exact: true })).toBeVisible(); +}); + +test("adding follow-ups by keyboard leaves focus on the Follow-up sessions heading", async ({ page, request }) => { + const course = unique("E2E Follow-ups"); + await createPlan(request, { course_name: course }); + const session = await createSession(request, { course_name: course }); + await finishSession(request, session.id); + + await page.goto(session.url); + const followups = page.getByRole("region", { name: "Follow-up sessions" }); + const add = followups.getByRole("button", { name: "Add follow-ups to plan" }); + await hydrated(add); + await add.focus(); + await page.keyboard.press("Enter"); + + await expect(followups.getByRole("status")).toContainText("Added to your plan:"); + await expect(add).toHaveCount(0); + // The button is gone, so focus moves to the section, not back to the top of the page. + await expect(followups.getByRole("heading", { level: 2, name: "Follow-up sessions" })).toBeFocused(); +}); diff --git a/e2e/session-runner.spec.ts b/e2e/session-runner.spec.ts index a40b55d8..0a6b3072 100644 --- a/e2e/session-runner.spec.ts +++ b/e2e/session-runner.spec.ts @@ -1,366 +1,159 @@ -import { test, expect } from "@playwright/test"; -import pg from "pg"; - -const BASE_URL = process.env.BASE_URL || "http://localhost:3000"; -const USER_ID = "e2e_test_user"; -const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL }); - -const SESSION_PAYLOAD = { - course_name: "E2E 101", - exam_name: "Final Exam", - mode: "RETRIEVAL", - topic_scope: "End-to-end testing", - planned_minutes: 30, - objectives: [ - { id: "obj_1", title: "Page navigation" }, - { id: "obj_2", title: "Form submission" }, - ], - target_outcome: { prompt_count: 3, target_accuracy: 0.7 }, - // cycles: 1 ⇒ no break can trigger (already on last cycle). Breaks are not under test here. - break_protocol: { type: "TEST_3_2", cycles: 1 }, -}; - -let sessionId: string; -let sessionUrl: string; - -// Playwright context headers ride on every browser request, so app fetches -// authenticate as the test user (clients no longer send identity headers). -test.use({ extraHTTPHeaders: { "X-User-Id": USER_ID } }); - -test.describe.serial("E2E: Full Retrieval Session Runner", () => { - test.beforeAll(async () => { - for (const key of ["obj_1", "obj_2"]) { - await pool.query( - `INSERT INTO objective_mastery (id, user_id, course_name, objective_key, updated_at) - VALUES (gen_random_uuid(), $1, $2, $3, NOW()) - ON CONFLICT (user_id, course_name, objective_key) DO NOTHING`, - [USER_ID, "E2E 101", key] - ); - } - // Purge error logs from any previous attempt (retries keep the DB). - // Unresolved logs survive a single correct retrieval by design and would - // inject CROSS_SESSION_REPAIR prompts, shifting the exact "PROMPT k / N" - // labels these tests assert. - await pool.query(`DELETE FROM session_error_logs WHERE user_id = $1`, [USER_ID]); - }); - - test.afterAll(async () => { - await pool.query(`DELETE FROM objective_mastery WHERE user_id = $1`, [USER_ID]); - await pool.end(); - }); - - test("create session via API", async ({ request }) => { - const response = await request.post(`${BASE_URL}/api/sessions`, { - headers: { - "Content-Type": "application/json", - "X-User-Id": USER_ID, - }, - data: SESSION_PAYLOAD, - }); - - expect(response.status()).toBe(201); - const body = await response.json(); - expect(body.session_id).toBeDefined(); - expect(body.session_url).toContain("/s/"); - expect(body.calendar.title).toContain("E2E 101"); - - sessionId = body.session_id; - sessionUrl = `/s/${sessionId}`; - }); - - test("preflight screen shows session details", async ({ page }) => { - await page.goto(sessionUrl); - await expect(page.getByText("E2E 101")).toBeVisible(); - await expect(page.getByText("Final Exam")).toBeVisible(); - await expect(page.getByText(/Retrieval: End-to-end testing/)).toBeVisible(); - - const startBtn = page.getByRole("button", { name: /start session/i }); - await expect(startBtn).toBeEnabled(); - }); - - test("start session and see first prompt", async ({ page }) => { - await page.goto(sessionUrl); - - await page.getByRole("button", { name: /start session/i }).click(); - - // Should see the first prompt - await expect(page.getByText("PROMPT 1 / 3")).toBeVisible({ timeout: 5000 }); - await expect(page.locator("textarea")).toBeVisible(); - }); - - test("submit a CORRECT answer", async ({ page }) => { - await page.goto(sessionUrl); - - await page.getByRole("button", { name: /start session|resume session/i }).click(); - - // Should be on prompt 1 (or wherever we left off) - await expect(page.locator("textarea")).toBeVisible({ timeout: 5000 }); - - // Type answer and submit - await page.locator("textarea").fill("Page navigation involves routing between views"); - await page.getByRole("button", { name: /submit answer/i }).click(); - - // Should see scoring buttons - await expect(page.getByRole("button", { name: "✓ Correct" })).toBeVisible(); - - // Click Correct and wait for the attempt API call to complete - await Promise.all([ - page.waitForResponse((res) => res.url().includes("/attempt") && res.status() === 200), - page.getByRole("button", { name: "✓ Correct" }).click(), - ]); - - // The review panel keeps the just-answered prompt on the card — the - // prompt advances only when the student moves on. - await expect(page.getByText("PROMPT 1 / 3")).toBeVisible({ timeout: 10_000 }); - await page.getByRole("button", { name: /next prompt/i }).click(); - await expect(page.getByText("PROMPT 2 / 3")).toBeVisible({ timeout: 10_000 }); - }); - - test("submit an INCORRECT answer with error log", async ({ page }) => { - await page.goto(sessionUrl); - - await page.getByRole("button", { name: /start session|resume session/i }).click(); - await expect(page.locator("textarea")).toBeVisible({ timeout: 5000 }); - - // Type answer and submit - await page.locator("textarea").first().fill("Wrong answer about forms"); - await page.getByRole("button", { name: /submit answer/i }).click(); - - // Score as incorrect - await page.getByRole("button", { name: "✗ Incorrect" }).click(); - - // Should show error log form - await expect(page.getByText(/log the error/i)).toBeVisible(); - - // Fill correction rule (required) - const textareas = page.locator("textarea"); - // The correction rule textarea - await textareas.nth(0).fill("Forms need proper validation before submission"); - - // Submit error log and wait for the attempt API call to complete - await Promise.all([ - page.waitForResponse((res) => res.url().includes("/attempt") && res.status() === 200), - page.getByRole("button", { name: /save.*next/i }).click(), - ]); - - // The review panel keeps the just-answered prompt (snapshotted at submit - // time, before variant injection grew the deck) on the card. - await expect(page.getByText("PROMPT 2 / 3")).toBeVisible({ timeout: 10_000 }); - await page.getByRole("button", { name: /next prompt/i }).click(); - // Prompt should advance — variant injection extends deck from 3 to 4, - // and the runner names the growth instead of changing the count silently. - await expect(page.getByText("PROMPT 3 / 4")).toBeVisible({ timeout: 10_000 }); - await expect(page.getByText("+1 repair added to this session")).toBeVisible(); - }); - - test("refresh page mid-run preserves progress", async ({ page }) => { - await page.goto(sessionUrl); - - // Should show Resume (not Start) since we have an active run - await expect(page.getByRole("button", { name: /resume session/i })).toBeVisible({ - timeout: 5000, - }); - - await page.getByRole("button", { name: /resume session/i }).click(); - - // Should be on prompt 3 (variant injection extended deck from 3 to 4) - await expect(page.getByText("PROMPT 3 / 4")).toBeVisible({ timeout: 5000 }); - }); - - test("complete final prompt and see end screen", async ({ page }) => { - await page.goto(sessionUrl); - - await page.getByRole("button", { name: /start session|resume session/i }).click(); - // The review panel renders reflection textareas too, so target the - // answer box by its placeholder. - const answerBox = page.getByPlaceholder("Type your answer from memory..."); - await expect(answerBox).toBeVisible({ timeout: 5000 }); - - // Submit remaining prompts (original + variant injected by earlier INCORRECT) - for (let i = 0; i < 2; i++) { - await answerBox.fill(`Answer ${i}`); - await page.getByRole("button", { name: /submit answer/i }).click(); - await page.getByRole("button", { name: "✓ Correct" }).click(); - - // The last CORRECT completes the run and jumps straight to the end - // screen; otherwise a review panel appears and Next Prompt advances. - if (i < 1) { - await page.getByRole("button", { name: /next prompt/i }).click(); - await expect(answerBox).toBeVisible({ timeout: 5000 }); - } - } - - // Should show end screen - await expect(page.getByText("SESSION COMPLETE")).toBeVisible({ timeout: 5000 }); - // Should show accuracy - await expect(page.getByText("Accuracy", { exact: true })).toBeVisible(); - // Should show recommended follow-ups - await expect(page.getByText(/RECOMMENDED FOLLOW-UPS/i)).toBeVisible(); - }); - - test("verify final metrics via API", async ({ request }) => { - // Start endpoint on a completed session should create a new run or show completed state - // Instead, let's verify the session's run data via the start endpoint - const startRes = await request.post( - `${BASE_URL}/api/sessions/${sessionId}/runs/start`, - { - headers: { "X-User-Id": USER_ID }, - } - ); - // Since run is completed, it should create a new run (201) - // or we can check the run directly. Let's just verify the API works. - expect([200, 201]).toContain(startRes.status()); - }); +/** + * The study loop in /s/[sessionId]: the session intro, answering and + * scoring questions, logging an error, resuming after a reload, and the + * results screen. Each test makes its own session in its own course, so a + * logged error never turns up as a repair question in another test. + */ +import type { Page } from "@playwright/test"; +import { + test as base, + expect, + answerBox, + answerQuestion, + createSession, + expectNoAxeViolations, + questionCounter, + scoreAs, + startRun, + unique, + type CreatedSession, +} from "./fixtures"; + +/** A new 3-question Retrieval session in its own course, for each test. */ +const test = base.extend<{ session: CreatedSession }>({ + session: async ({ request }, provide) => { + await provide(await createSession(request, { course_name: unique("E2E 101"), target_accuracy: 0.7 })); + }, }); -test.describe("E2E: Security", () => { - test.use({ extraHTTPHeaders: {} }); - test("different user cannot access another user's run", async ({ request }) => { - // Create a session as user A - const createRes = await request.post(`${BASE_URL}/api/sessions`, { - headers: { - "Content-Type": "application/json", - "X-User-Id": "user_A_security", - }, - data: { - course_name: "SEC 101", - exam_name: "Test", - mode: "RETRIEVAL", - topic_scope: "Security", - planned_minutes: 15, - }, +async function answerAndScore(page: Page, answer: string, score: "Correct" | "Partly correct" | "Incorrect") { + await answerBox(page).fill(answer); + await page.getByRole("button", { name: "Submit answer" }).click(); + await scoreAs(page, score); +} + +test.describe("study session", () => { + test("the intro names the session and starts on question 1", { tag: "@mobile" }, async ({ page, session }) => { + await page.goto(session.url); + + await expect(page.getByRole("heading", { level: 1 })).toHaveText("Retrieval: End-to-end testing"); + const main = page.getByRole("main"); + await expect(main.getByText(session.course)).toBeVisible(); + await expect(main.getByText("Final exam")).toBeVisible(); + await expect(main.getByRole("definition").filter({ hasText: "3 questions" })).toBeVisible(); + await expect(page).toHaveTitle(`Retrieval · ${session.course} · Study Bot`); + + await page.getByRole("button", { name: "Start session" }).click(); + await expect(questionCounter(page, 1, 3)).toBeVisible(); + await expect(answerBox(page)).toBeFocused(); + await expect(page.getByRole("button", { name: "Submit answer" })).toBeDisabled(); + await expect(page).toHaveTitle(`Question 1 of 3 · ${session.course} · Study Bot`); + }); + + test("answer, log an error, resume after a reload and see the results", { tag: "@mobile" }, async ({ page, session }) => { + // One student going through one session: every step needs the last. + test.slow(); + await page.goto(session.url); + await page.getByRole("button", { name: "Start session" }).click(); + + await test.step("a correct answer keeps question 1 on screen until Next question", async () => { + await answerAndScore(page, "Page navigation routes between views", "Correct"); + const sheet = page.getByRole("region", { name: "Correct", exact: true }); + await expect(sheet).toBeVisible(); + await expect(questionCounter(page, 1, 3)).toBeVisible(); + await sheet.getByRole("button", { name: "Next question" }).click(); + await expect(questionCounter(page, 2, 3)).toBeVisible(); }); - const session = await createRes.json(); - // Start run as user A - const startRes = await request.post( - `${BASE_URL}/api/sessions/${session.session_id}/runs/start`, - { headers: { "X-User-Id": "user_A_security" } } - ); - const run = await startRes.json(); + await test.step("an incorrect answer asks for a correction rule and adds a repair question", async () => { + await answerAndScore(page, "Forms submit themselves", "Incorrect"); + const errorLog = page.getByRole("region", { name: "Log the error" }); + await expect(errorLog).toBeVisible(); - // User B tries to GET the run → 403 - const getRes = await request.get(`${BASE_URL}/api/runs/${run.run_id}`, { - headers: { "X-User-Id": "user_B_intruder" }, - }); - expect(getRes.status()).toBe(403); + // Saving without a rule says what's missing beside the field. + const rule = errorLog.getByRole("textbox", { name: "Correction rule" }); + await page.getByRole("button", { name: "Save correction" }).click(); + await expect(rule).toHaveAttribute("aria-invalid", "true"); + await expect(rule).toHaveAccessibleDescription(/Write the correction rule first\./); - // User B tries to submit attempt → 403 - const attemptRes = await request.post( - `${BASE_URL}/api/runs/${run.run_id}/attempt`, - { - headers: { - "Content-Type": "application/json", - "X-User-Id": "user_B_intruder", - }, - data: { - prompt_index: 0, - user_answer: "Hacked", - self_score: "CORRECT", - }, - } - ); - expect(attemptRes.status()).toBe(403); - }); + await rule.fill("Forms need validation before they submit"); + await page.getByRole("button", { name: "Save correction" }).click(); - test("unknown IDs return 404", async ({ request }) => { - const res1 = await request.get(`${BASE_URL}/api/sessions/nonexistent_id`, { - headers: { "X-User-Id": "anyone" }, + const sheet = page.getByRole("region", { name: "Incorrect", exact: true }); + await expect(sheet).toBeVisible(); + await expect(page.getByRole("region", { name: "Your correction" })).toContainText( + "Forms need validation before they submit", + ); + // The deck grows by one and says so; the answered question stays on screen. + await expect(questionCounter(page, 2, 4)).toBeVisible(); + await expect(page.getByRole("main").getByText("1 repair question added")).toBeVisible(); + await sheet.getByRole("button", { name: "Next question" }).click(); + await expect(questionCounter(page, 3, 4)).toBeVisible(); + await expect(page.getByText("Repair question. It retests an error from earlier in this session.")).toBeVisible(); }); - expect(res1.status()).toBe(404); - const res2 = await request.get(`${BASE_URL}/api/runs/nonexistent_run`, { - headers: { "X-User-Id": "anyone" }, + await test.step("a reload offers Resume session and returns to the same question", async () => { + await page.reload(); + await expect(page.getByText("2 of 4 questions answered. Your answers are saved.")).toBeVisible(); + await page.getByRole("button", { name: "Resume session" }).click(); + await expect(questionCounter(page, 3, 4)).toBeVisible(); }); - expect(res2.status()).toBe(404); - }); - test("missing auth header returns 401", async ({ request }) => { - const res = await request.post(`${BASE_URL}/api/sessions`, { - headers: { - "Content-Type": "application/json", - "X-User-Id": "", - }, - data: { course_name: "X", exam_name: "Y", mode: "RETRIEVAL", topic_scope: "Z", planned_minutes: 15 }, + await test.step("the last answer offers See results instead of Next question", async () => { + await answerAndScore(page, "The rule is to validate first", "Correct"); + await page.getByRole("button", { name: "Next question" }).click(); + await expect(questionCounter(page, 4, 4)).toBeVisible(); + await answerAndScore(page, "Steps: plan, act, check", "Correct"); + await expect(page.getByRole("button", { name: "Next question" })).toBeHidden(); + await page.getByRole("button", { name: "See results" }).click(); }); - expect(res.status()).toBe(401); - }); -}); -test.describe("E2E: State validation", () => { - let sessionId: string; - let runId: string; - const uid = "state_test_user"; - - test.beforeAll(async ({ request }) => { - const res = await request.post(`${BASE_URL}/api/sessions`, { - headers: { "Content-Type": "application/json", "X-User-Id": uid }, - data: { - course_name: "STATE 101", - exam_name: "Quiz", - mode: "RETRIEVAL", - topic_scope: "State machines", - planned_minutes: 15, - target_outcome: { prompt_count: 2 }, - }, + await test.step("the results screen shows accuracy and follow-up sessions", async () => { + await expect(page.getByRole("heading", { level: 1, name: "Session complete" })).toBeVisible(); + // 3 of 4 graded questions correct, one error, one repair question. + await expect(page.getByRole("region", { name: "Session stats" })).toMatchAriaSnapshot(` + - term: Accuracy + - definition: 75% + - term: Questions + - definition: "4" + - term: Time answering + - definition: /.+/ + - term: Errors logged + - definition: "1" + - term: Repair questions + - definition: "1" + `); + await expect(page.getByRole("heading", { level: 2, name: "Follow-up sessions" })).toBeVisible(); + await expect(page).toHaveTitle(`Session complete · ${session.course} · Study Bot`); }); - const body = await res.json(); - sessionId = body.session_id; - - const startRes = await request.post( - `${BASE_URL}/api/sessions/${sessionId}/runs/start`, - { headers: { "X-User-Id": uid } } - ); - const startBody = await startRes.json(); - runId = startBody.run_id; }); - test("cannot submit wrong prompt_index (409)", async ({ request }) => { - const res = await request.post(`${BASE_URL}/api/runs/${runId}/attempt`, { - headers: { "Content-Type": "application/json", "X-User-Id": uid }, - data: { - prompt_index: 5, - user_answer: "Out of order", - self_score: "CORRECT", - }, - }); - expect(res.status()).toBe(409); - }); - - test("complete all prompts then reject further attempts (409)", async ({ request }) => { - // Submit prompt 0 - await request.post(`${BASE_URL}/api/runs/${runId}/attempt`, { - headers: { "Content-Type": "application/json", "X-User-Id": uid }, - data: { prompt_index: 0, user_answer: "A", self_score: "CORRECT" }, - }); - // Submit prompt 1 (last) - await request.post(`${BASE_URL}/api/runs/${runId}/attempt`, { - headers: { "Content-Type": "application/json", "X-User-Id": uid }, - data: { prompt_index: 1, user_answer: "B", self_score: "CORRECT" }, - }); + test("a finished session opens on its results", { tag: "@a11y" }, async ({ page, request, session }) => { + const run = await startRun(request, session.id); + for (let i = 0; i < 3; i++) await answerQuestion(request, run.run_id, i, "CORRECT"); - // Try prompt 2 — should be 409 (run completed) - const res = await request.post(`${BASE_URL}/api/runs/${runId}/attempt`, { - headers: { "Content-Type": "application/json", "X-User-Id": uid }, - data: { prompt_index: 2, user_answer: "C", self_score: "CORRECT" }, - }); - expect(res.status()).toBe(409); + await page.goto(session.url); + await expect(page.getByRole("heading", { level: 1, name: "Session complete" })).toBeVisible(); + await expect(page.getByRole("region", { name: "Session stats" })).toMatchAriaSnapshot(` + - term: Accuracy + - definition: 100% + `); + await expect(page.getByRole("button", { name: "Start session again" })).toBeVisible(); + await expect(page.getByRole("link", { name: "Go to Home" })).toHaveAttribute("href", "/"); + await expectNoAxeViolations(page, "the results"); }); - test("complete endpoint is idempotent", async ({ request }) => { - const res1 = await request.post(`${BASE_URL}/api/runs/${runId}/complete`, { - headers: { "X-User-Id": uid }, - }); - expect(res1.status()).toBe(200); + test("the intro, a question and the error log pass axe", { tag: "@a11y" }, async ({ page, session }) => { + await page.goto(session.url); + await expect(page.getByRole("button", { name: "Start session" })).toBeVisible(); + await expectNoAxeViolations(page, "the intro"); - const res2 = await request.post(`${BASE_URL}/api/runs/${runId}/complete`, { - headers: { "X-User-Id": uid }, - }); - expect(res2.status()).toBe(200); + await page.getByRole("button", { name: "Start session" }).click(); + await expect(answerBox(page)).toBeVisible(); + await expectNoAxeViolations(page, "a question"); - const body1 = await res1.json(); - const body2 = await res2.json(); - expect(body1.status).toBe("COMPLETED"); - expect(body2.status).toBe("COMPLETED"); + await answerAndScore(page, "An answer", "Incorrect"); + await expect(page.getByRole("region", { name: "Log the error" })).toBeVisible(); + await expectNoAxeViolations(page, "the error log"); }); }); diff --git a/e2e/settings.spec.ts b/e2e/settings.spec.ts new file mode 100644 index 00000000..96865916 --- /dev/null +++ b/e2e/settings.spec.ts @@ -0,0 +1,411 @@ +/** + * Settings as a student uses it: saving the profile time zone and study + * preferences (with the Saving… and Settings saved states), the unsaved + * changes bar at 400% zoom, "Use this device's time zone", the theme, + * Google Calendar in fake mode and the connect result banners, Export data, + * Reset password, and Delete account. + * + * Tests that save or delete use the `account` fixture (a real account of + * their own); the theme and the banners only need a fresh test identity. + * The rules and routes are covered by the unit tests (settings-route, + * settings-schema, account-delete-route, account-export-route and the + * google-* route tests); these check the screen and what it saved. + */ +import { readFile } from "node:fs/promises"; +import type { APIRequestContext, Page } from "@playwright/test"; +import { test, expect, DETAILS_DONT_MATCH, loggedStatus, openSettings, signInWith } from "./fixtures"; + +async function savedSettings(api: APIRequestContext) { + const response = await api.get("/api/settings"); + expect(response.status()).toBe(200); + return response.json(); +} + +/** + * Pick an option from one of the Settings selects with the keyboard: open + * it, type the start of the option (the list's typeahead moves to it) and + * press Enter. The time zone list has hundreds of options, and clicking one + * deep in the list races the list's own scrolling. + */ +async function choose(page: Page, select: string, option: string): Promise<void> { + const trigger = page.getByRole("combobox", { name: select }); + await trigger.focus(); + await page.keyboard.press("Enter"); + const listbox = page.getByRole("listbox"); + await expect(listbox).toBeVisible(); + await page.keyboard.type(option); + await expect(listbox.getByRole("option", { name: option, exact: true })).toBeFocused(); + await page.keyboard.press("Enter"); + await expect(listbox).toBeHidden(); + await expect(trigger).toContainText(option); +} + +test.describe("profile and study preferences", () => { + test("Save settings shows Saving… then Settings saved, and the time zone stays after a reload", { tag: "@mobile" }, async ({ account }) => { + const page = account.page; + await openSettings(page); + const zone = page.getByRole("combobox", { name: "Time zone" }); + await expect(zone).toHaveText("Choose a time zone"); + await expect(page.getByText("Not set, so days follow UTC.")).toBeVisible(); + + await choose(page, "Time zone", "Chicago"); + await expect(zone).toHaveText("Chicago (Central Time)"); + await expect(page.getByText(/^Now in this time zone: /)).toBeVisible(); + await expect(page.getByRole("status").filter({ hasText: "Unsaved changes" })).toBeVisible(); + + await test.step("Saving… while the request is out", async () => { + // Hold the real request (its response is the server's) so the + // in-progress state is on screen long enough to check. + let release = () => {}; + const held = new Promise<void>((resolve) => (release = resolve)); + await page.route("**/api/settings", async (route) => { + if (route.request().method() === "PUT") await held; + await route.continue(); + }); + + await page.getByRole("button", { name: "Save settings" }).click(); + await expect(page.getByRole("button", { name: "Saving…" })).toBeDisabled(); + await expect(page.getByRole("status").filter({ hasText: "Saving…" })).toBeVisible(); + await expect(zone).toBeDisabled(); + + release(); + await expect(page.getByRole("status").filter({ hasText: "Settings saved" })).toBeVisible(); + await expect(page.getByRole("button", { name: "Save settings" })).toBeEnabled(); + await page.unrouteAll({ behavior: "wait" }); + }); + + await test.step("saved on the server and shown after a reload", async () => { + expect(await savedSettings(account.api)).toMatchObject({ timezone: "America/Chicago" }); + await page.reload(); + await expect(zone).toHaveText("Chicago (Central Time)"); + }); + }); + + test.describe("on a device in Tokyo", () => { + test.use({ timezoneId: "Asia/Tokyo" }); + + test("Use this device's time zone picks the device's zone", async ({ account }) => { + const page = account.page; + await openSettings(page); + const zone = page.getByRole("combobox", { name: "Time zone" }); + const useDevice = page.getByRole("button", { name: "Use this device's time zone" }); + + await useDevice.click(); + await expect(zone).toHaveText("Tokyo (Japan Standard Time)"); + await expect(page.getByText("Matches this device")).toBeVisible(); + await expect(useDevice).toHaveCount(0); + + await page.getByRole("button", { name: "Save settings" }).click(); + await expect(page.getByRole("status").filter({ hasText: "Settings saved" })).toBeVisible(); + expect(await savedSettings(account.api)).toMatchObject({ timezone: "Asia/Tokyo" }); + }); + }); + + test("study preferences stay saved after a reload", { tag: "@mobile" }, async ({ account }) => { + const page = account.page; + await openSettings(page); + const start = page.getByRole("textbox", { name: "Daily start time" }); + const end = page.getByRole("textbox", { name: "Daily end time" }); + const limit = page.getByRole("combobox", { name: "Daily study limit" }); + const xpGoal = page.getByRole("combobox", { name: "Daily XP goal" }); + await expect(start).toHaveValue("09:00"); + await expect(limit).toHaveText("3 hr"); + + await start.fill("08:30"); + await end.fill("20:00"); + await choose(page, "Daily study limit", "2 hr"); + await choose(page, "Daily XP goal", "100 XP"); + await page.getByRole("button", { name: "Save settings" }).click(); + await expect(page.getByRole("status").filter({ hasText: "Settings saved" })).toBeVisible(); + + expect(await savedSettings(account.api)).toMatchObject({ + studyStart: "08:30", + studyEnd: "20:00", + dailyCap: 120, + dailyXpGoal: 100, + }); + await page.reload(); + await expect(start).toHaveValue("08:30"); + await expect(end).toHaveValue("20:00"); + await expect(limit).toHaveText("2 hr"); + await expect(xpGoal).toHaveText("100 XP"); + }); + + test("an end time before the start time is caught before saving, and Discard changes restores the form", async ({ account }) => { + const page = account.page; + await openSettings(page); + const end = page.getByRole("textbox", { name: "Daily end time" }); + await end.fill("08:00"); + await page.getByRole("button", { name: "Save settings" }).click(); + + await expect(page.getByRole("alert").filter({ hasText: "Settings not saved. Check the highlighted fields." })).toBeVisible(); + await expect(end).toHaveAttribute("aria-invalid", "true"); + await expect(end).toHaveAccessibleDescription("Choose an end time after the start time."); + await expect(end).toBeFocused(); + await expect(page.getByRole("status").filter({ hasText: "Unsaved changes" })).toBeVisible(); + expect(await savedSettings(account.api)).toMatchObject({ studyStart: "09:00", studyEnd: "17:00" }); + + await page.getByRole("button", { name: "Discard changes" }).click(); + await expect(end).toHaveValue("17:00"); + await expect(end).not.toHaveAttribute("aria-invalid"); + await expect(page.getByRole("alert").filter({ hasText: "Settings not saved" })).toHaveCount(0); + await expect(page.getByRole("button", { name: "Discard changes" })).toHaveCount(0); + }); + + test("with unsaved changes, the save bar stays in view on a phone and never covers the field you're editing at 400% zoom", async ({ testUserPage: page }) => { + const start = page.getByRole("textbox", { name: "Daily start time" }); + const end = page.getByRole("textbox", { name: "Daily end time" }); + const save = page.getByRole("button", { name: "Save settings" }); + /** Whether the middle of the field is the field itself, not a bar drawn over it. */ + const uncovered = () => + end.evaluate((el) => { + const box = el.getBoundingClientRect(); + const top = document.elementFromPoint(box.left + box.width / 2, box.top + box.height / 2); + return top !== null && (top === el || el.contains(top)); + }); + + await test.step("on a phone the bar follows you up the page", async () => { + await page.setViewportSize({ width: 375, height: 667 }); + await openSettings(page); + await start.fill("08:30"); + await page.evaluate(() => window.scrollTo(0, 0)); + await expect(save).toBeInViewport(); + }); + + await test.step("at 320 by 256 (1280 by 1024 at 400%) it waits at the end of the form", async () => { + await page.setViewportSize({ width: 320, height: 256 }); + await end.focus(); + await expect(end).toBeInViewport({ ratio: 1 }); + expect(await uncovered()).toBe(true); + await expect(save).not.toBeInViewport(); + await save.scrollIntoViewIfNeeded(); + await expect(save).toBeInViewport(); + await expect(page.getByRole("status").filter({ hasText: "Unsaved changes" })).toBeVisible(); + }); + }); +}); + +test.describe("appearance", () => { + test("Light, Dark and System change the page's theme and stay after a reload", { tag: "@mobile" }, async ({ testUserPage: page }) => { + await page.emulateMedia({ colorScheme: "light" }); + await openSettings(page); + const theme = page.getByRole("radiogroup", { name: "Theme" }); + const html = page.locator("html"); + await expect(theme.getByRole("radio", { name: "System" })).toBeChecked(); + await expect(html).toHaveClass(/\blight\b/); + + await test.step("Dark, kept after a reload", async () => { + await theme.getByRole("radio", { name: "Dark" }).click(); + await expect(html).toHaveClass(/\bdark\b/); + await page.reload(); + await expect(theme.getByRole("radio", { name: "Dark" })).toBeChecked(); + await expect(html).toHaveClass(/\bdark\b/); + }); + + await test.step("Light", async () => { + await theme.getByRole("radio", { name: "Light" }).click(); + await expect(html).toHaveClass(/\blight\b/); + await expect(html).not.toHaveClass(/\bdark\b/); + }); + + await test.step("System follows the device", async () => { + await theme.getByRole("radio", { name: "System" }).click(); + await page.emulateMedia({ colorScheme: "dark" }); + await expect(html).toHaveClass(/\bdark\b/); + await page.emulateMedia({ colorScheme: "light" }); + await expect(html).toHaveClass(/\blight\b/); + await page.reload(); + await expect(theme.getByRole("radio", { name: "System" })).toBeChecked(); + }); + }); +}); + +test.describe("Google Calendar", () => { + test("Connect Google Calendar in fake mode connects, and Disconnect asks first", async ({ account, request }) => { + const config = await (await request.get("/api/config")).json(); + test.skip(!config.google_configured, "Settings shows Google Calendar only when it can connect (GOOGLE_PROVIDER=fake or a client id)."); + const page = account.page; + await openSettings(page); + const section = page.getByRole("region", { name: "Google Calendar" }); + await expect(section).toContainText("Not connected"); + + await test.step("Connect lands back on Settings with a banner", async () => { + // With GOOGLE_PROVIDER=fake the connect route connects the fake + // calendar itself and redirects where Google's callback would. + await section.getByRole("link", { name: "Connect Google Calendar" }).click(); + const banner = page.getByRole("status").filter({ hasText: "Google Calendar connected" }); + await expect(banner).toContainText("Add a plan's sessions to it from the Plan page."); + await expect(banner.getByText("Google Calendar connected", { exact: true })).toBeFocused(); + await expect(page).toHaveURL("/settings"); + }); + + await test.step("the section shows the account and its calendars", async () => { + await expect(section).toContainText("test@example.com"); + await expect(section.getByText("Connected", { exact: true })).toBeVisible(); + await expect(section.getByRole("combobox", { name: "Calendar for sessions" })).toHaveText("Primary (primary)"); + const busy = section.getByRole("checkbox", { name: "Primary (primary)" }); + await expect(busy).toBeChecked(); + // The last busy calendar can't be unchecked. + await expect(busy).toBeDisabled(); + expect(await (await account.api.get("/api/integrations/google/status")).json()).toMatchObject({ connected: true }); + }); + + await test.step("Disconnect asks first, then offers Connect again", async () => { + await section.getByRole("button", { name: "Disconnect" }).click(); + const dialog = page.getByRole("alertdialog", { name: "Disconnect Google Calendar?" }); + await expect(dialog).toContainText("Events already in Google Calendar stay there."); + await dialog.getByRole("button", { name: "Disconnect Google Calendar" }).click(); + await expect(dialog).toBeHidden(); + await expect(section.getByRole("status").filter({ hasText: "Google Calendar disconnected" })).toBeVisible(); + await expect(section.getByRole("link", { name: "Connect Google Calendar" })).toBeVisible(); + expect(await (await account.api.get("/api/integrations/google/status")).json()).toMatchObject({ connected: false }); + }); + }); + + test("after Disconnect, focus moves to Connect Google Calendar", async ({ account, request }) => { + const config = await (await request.get("/api/config")).json(); + test.skip(!config.google_configured, "Settings shows Google Calendar only when it can connect (GOOGLE_PROVIDER=fake or a client id)."); + const seeded = await account.api.post("/api/integrations/google/test-seed", { data: { connected_email: account.email } }); + expect(seeded.status()).toBe(200); + const page = account.page; + await openSettings(page, "/settings#calendar"); + const section = page.getByRole("region", { name: "Google Calendar" }); + + await section.getByRole("button", { name: "Disconnect" }).click(); + await page.getByRole("alertdialog", { name: "Disconnect Google Calendar?" }).getByRole("button", { name: "Disconnect Google Calendar" }).click(); + await expect(section.getByRole("status").filter({ hasText: "Google Calendar disconnected" })).toBeVisible(); + await expect(section.getByRole("link", { name: "Connect Google Calendar" })).toBeFocused(); + }); + + test("the result of connecting shows as a banner, and Dismiss hands focus to the page", async ({ testUserPage: page }) => { + await test.step("connected", async () => { + await page.goto("/settings?google=connected"); + const banner = page.getByRole("status").filter({ hasText: "Google Calendar connected" }); + await expect(banner).toContainText("Add a plan's sessions to it from the Plan page."); + await expect(banner.getByText("Google Calendar connected", { exact: true })).toBeFocused(); + // The query goes, so a reload doesn't repeat the banner. + await expect(page).toHaveURL("/settings"); + await banner.getByRole("button", { name: "Dismiss" }).click(); + await expect(banner).toHaveCount(0); + await expect(page.getByRole("main")).toBeFocused(); + }); + + for (const [reason, description] of [ + ["access_denied", "Study Bot needs your permission to add sessions to your calendar. Connect again and allow access on Google's page."], + ["invalid_state", "The connection request expired. Connect again."], + ["no_refresh_token", "Google didn't grant lasting access."], + ["something_unexpected", "The connection didn't finish. Connect again in a minute."], + ]) { + await test.step(`error: ${reason}`, async () => { + await page.goto(`/settings?google=error&reason=${reason}`); + const banner = page.getByRole("alert").filter({ hasText: "Google Calendar not connected" }); + await expect(banner).toContainText(description); + await expect(banner).not.toContainText(reason); + await expect(page).toHaveURL("/settings"); + }); + } + }); +}); + +test.describe("data and account", () => { + test("Export data downloads a JSON file of the account", async ({ account }) => { + const saved = await account.api.put("/api/settings", { data: { dailyXpGoal: 100 } }); + expect(saved.status()).toBe(200); + const page = account.page; + await openSettings(page); + + const downloading = page.waitForEvent("download"); + await page.getByRole("button", { name: "Export data (.json)" }).click(); + const download = await downloading; + expect(download.suggestedFilename()).toMatch(/^study-bot-export-\d+\.json$/); + await expect(page.getByRole("status").filter({ hasText: "Data exported. Check your downloads." })).toBeVisible(); + + const data = JSON.parse(await readFile(await download.path(), "utf8")); + expect(data.user).toMatchObject({ email: account.email, name: "E2E Account" }); + expect(data.user).not.toHaveProperty("passwordHash"); + expect(data.userGameState).toMatchObject({ dailyXpGoal: 100 }); + }); + + test("Reset password is offered only when a reset link can reach you", async ({ testUserPage: page, request }) => { + // A production server without SMTP has nowhere to send the link, so + // Settings says so instead of promising an email. + const config = await (await request.get("/api/config")).json(); + expect(typeof config.email_links_available).toBe("boolean"); + await openSettings(page, "/settings#account"); + const section = page.getByRole("region", { name: "Account" }); + if (config.email_links_available) { + await expect(section).toContainText("Study Bot emails you a link to choose a new password. The link expires in 1 hour."); + await expect(section.getByRole("link", { name: "Reset password" })).toHaveAttribute("href", "/auth/forgot-password"); + } else { + await expect(section).toContainText( + "Password reset by email isn't set up on this server. Ask the person who runs this Study Bot to reset your password.", + ); + await expect(section.getByRole("link", { name: "Reset password" })).toHaveCount(0); + } + }); + + test.describe(() => { + // A wrong password answers 403, and signing in to the deleted account 401. + test.use({ allowConsoleErrors: [loggedStatus(401, 403)] }); + + test("Delete account needs the password, then lands on sign in and the account is gone", { tag: "@mobile" }, async ({ account }) => { + // Each password check takes the server about 2 s (bcrypt at cost 12), and this test makes several. + test.slow(); + const page = account.page; + + await test.step("the API also needs the confirmation phrase", async () => { + const response = await account.api.delete("/api/account/delete", { data: { password: account.password } }); + expect(response.status()).toBe(400); + expect((await account.api.get("/api/settings")).status()).toBe(200); + }); + + const config = await (await account.api.get("/api/config")).json(); + const forgotHint = config.email_links_available + ? "Forgot it? Reset your password first." + : "Forgot it? Ask the person who runs this Study Bot to reset your password."; + + await openSettings(page, "/settings#account"); + await page.getByRole("button", { name: "Delete account" }).click(); + const dialog = page.getByRole("alertdialog", { name: "Delete your account?" }); + await expect(dialog).toContainText( + "This permanently deletes your plans, sessions, answers, materials, decks, guides, and chat history", + ); + const password = dialog.getByLabel("Enter your password to confirm"); + const confirm = dialog.getByRole("button", { name: "Delete account" }); + + await test.step("nothing happens without the right password", async () => { + await expect(password).toBeFocused(); + await expect(confirm).toBeDisabled(); + // A way out for a student who doesn't know the password. + await expect(password).toHaveAccessibleDescription(forgotHint); + if (config.email_links_available) { + await expect(dialog.getByRole("link", { name: "Reset your password" })).toHaveAttribute("href", "/auth/forgot-password"); + } + await password.fill("not-the-password"); + await confirm.click(); + await expect(password).toHaveAccessibleDescription( + `That password doesn't match your account. Check it and retry. ${forgotHint}`, + ); + await expect(password).toHaveAttribute("aria-invalid", "true"); + await expect(dialog).toBeVisible(); + expect((await account.api.get("/api/settings")).status()).toBe(200); + }); + + await test.step("the right password deletes the account and signs out", async () => { + await password.fill(account.password); + await confirm.click(); + await expect(page).toHaveURL("/auth/signin?account=deleted"); + await expect(page.getByRole("status").filter({ hasText: "Account deleted" })).toContainText( + "Your plans, sessions, materials, and chat history are gone.", + ); + }); + + await test.step("the account can't sign in, and its other sessions end", async () => { + await expect(page.getByRole("textbox", { name: "Email" })).toBeFocused(); + await signInWith(page, account.email, account.password); + await expect(page.getByRole("group", { name: DETAILS_DONT_MATCH })).toBeFocused(); + expect((await account.api.get("/api/settings")).status()).toBe(401); + }); + }); + }); +}); diff --git a/e2e/shell.spec.ts b/e2e/shell.spec.ts new file mode 100644 index 00000000..8cc48262 --- /dev/null +++ b/e2e/shell.spec.ts @@ -0,0 +1,188 @@ +/** + * Every destination in the app shell loads for a new student: its title + * in the top app bar and the tab, no console errors (the fixture fails the + * test on any), and no WCAG 2.2 A or AA violations axe can find. A new test + * identity keeps the screens in their empty states, so the checks don't + * depend on what other tests created. + */ +import type { Page } from "@playwright/test"; +import { test, expect, createPlan, expectNoAxeViolations, hydrated, morningZone, unique } from "./fixtures"; + +const DESTINATIONS = [ + { path: "/", title: "Home" }, + { path: "/plan", title: "Plan" }, + { path: "/plan/new", title: "New plan" }, + { path: "/plan/materials", title: "Materials" }, + { path: "/learn", title: "Study" }, + { path: "/flashcards", title: "Flashcards" }, + { path: "/guides", title: "Study guides" }, + { path: "/chat", title: "Chat" }, + { path: "/achievements", title: "Progress" }, + { path: "/settings", title: "Settings" }, +]; + +for (const { path, title } of DESTINATIONS) { + test(`${title} (${path}) loads and passes axe`, { tag: ["@a11y", "@mobile"] }, async ({ testUserPage: page }) => { + await page.goto(path); + await expect(page.getByRole("heading", { level: 1 })).toHaveText(title); + await expect(page).toHaveTitle(`${title} · Study Bot`); + // Waits for loading states ("Loading chat history…") to give way to the + // page's own content before axe looks. + await expectNoAxeViolations(page, title); + }); +} + +/** A plan whose first session is today, so the shell shows the Start button. */ +async function planWithSessionToday(api: Parameters<typeof createPlan>[0]) { + return createPlan(api, { course_name: unique("E2E Shell"), time_zone: morningZone(), all_day: true }); +} + +/** Clicks `selector` in the page and returns the named animations seen in the next few seconds. */ +function animationsAfterClick(page: Page, selector: string, until: string[]): Promise<string[]> { + return page.evaluate( + async ([sel, wanted]) => { + const seen = new Set<string>(); + (document.querySelector(sel) as HTMLElement).click(); + const end = performance.now() + 10_000; + while (performance.now() < end) { + for (const animation of document.getAnimations()) { + if (animation instanceof CSSAnimation) seen.add(animation.animationName); + } + if (wanted.every((name) => seen.has(name))) break; + await new Promise((resolve) => requestAnimationFrame(resolve)); + } + return [...seen]; + }, + [selector, until] as const, + ); +} + +test("the app bar title starts where the page content starts", async ({ testUserPage: page, isMobile }) => { + test.skip(isMobile, "wide windows only"); + for (const width of [1440, 1000]) { + await page.setViewportSize({ width, height: 900 }); + await page.goto("/plan"); + const title = page.getByRole("heading", { level: 1 }); + await expect(title).toHaveText("Plan"); + const content = page.locator('[data-slot="page-container"]').first(); + const contentX = await content.evaluate((node) => node.getBoundingClientRect().x + parseFloat(getComputedStyle(node).paddingLeft)); + expect((await title.boundingBox())!.x, `at ${width}px`).toBeCloseTo(contentX, 0); + } +}); + +test("opening a session, the rail and the app bar recede, and they come back after", async ({ + testUserPage: page, + testUser, + isMobile, +}) => { + test.skip(isMobile, "the rail shows from 600px"); + const plan = await planWithSessionToday(testUser.api); + await page.goto("/plan"); + const start = page.locator('[data-slot="session-fab"][data-placement="rail"]'); + await hydrated(start); + + const entering = await animationsAfterClick(page, '[data-slot="session-fab"][data-placement="rail"]', ["shell-rail-out", "shell-bar-out"]); + expect(entering).toEqual(expect.arrayContaining(["shell-rail-out", "shell-bar-out"])); + await expect(page).toHaveURL(new RegExp(`/s/${plan.items[0].session_id}$`)); + + const leave = page.getByRole("link", { name: "Leave session" }); + await hydrated(leave); + const leaving = await animationsAfterClick(page, 'a[aria-label="Leave session"]', ["shell-rail-out", "shell-bar-out"]); + expect(leaving).toEqual(expect.arrayContaining(["shell-rail-out", "shell-bar-out"])); +}); + +test("a control that takes focus scrolls clear of the floating Start button", { tag: "@mobile" }, async ({ + testUserPage: page, + testUser, +}) => { + await planWithSessionToday(testUser.api); + await page.setViewportSize({ width: 375, height: 667 }); + await page.goto("/plan"); + const fab = page.locator('[data-slot="session-fab"][data-placement="floating"]'); + await expect(fab).toBeVisible(); + // The plan streams in after its skeleton; wait for its controls. + await expect(page.getByRole("main").getByRole("link", { name: "New plan" })).toBeVisible(); + + // Move the page's first control down behind the button: clear of the + // bottom bar, so without the button's own scroll margin focusing it + // wouldn't scroll it out from under the button. + await page.evaluate(() => { + const main = document.getElementById("main-content")!; + // The first control on screen (the wide layout's side column is hidden here). + const first = [...main.querySelectorAll("a[href], button, input, select, textarea")].find( + (el) => el.getClientRects().length > 0 + )!; + const fabTop = document.querySelector('[data-slot="session-fab"][data-placement="floating"]')!.getBoundingClientRect().top; + const spacer = document.createElement("div"); + spacer.style.height = `${fabTop + 45 - first.getBoundingClientRect().bottom}px`; + spacer.style.flexShrink = "0"; + main.prepend(spacer); + window.scrollTo(0, 0); + }); + const inMain = () => page.evaluate(() => Boolean(document.activeElement?.closest("#main-content"))); + for (let presses = 0; presses < 10 && !(await inMain()); presses++) await page.keyboard.press("Tab"); + expect(await inMain()).toBe(true); + + const focused = await page.evaluate(() => document.activeElement!.getBoundingClientRect().bottom); + const fabTop = (await fab.boundingBox())!.y; + expect(focused, "the focused control ends above the Start button").toBeLessThanOrEqual(fabTop); +}); + +test("in a short window (400% zoom) the bars and the Start button stop covering the page", { tag: "@mobile" }, async ({ + testUserPage: page, + testUser, +}) => { + await planWithSessionToday(testUser.api); + await page.setViewportSize({ width: 320, height: 256 }); + await page.goto("/plan"); + await expect(page.getByRole("heading", { level: 1 })).toHaveText("Plan"); + + const nav = page.getByRole("navigation", { name: "Main" }); + await expect(nav).toHaveCSS("position", "static"); + await expect(page.locator("header").filter({ has: page.getByRole("heading", { level: 1 }) })).toHaveCSS( + "position", + "absolute", + ); + await expect(page.locator('[data-slot="session-fab"][data-placement="floating"]')).toBeHidden(); + + // The More sheet scrolls inside its height cap, so the theme control is reachable + const more = nav.getByRole("button", { name: "More", exact: true }); + await hydrated(more); + await more.click(); + const system = page.getByRole("dialog", { name: "More" }).getByRole("radio", { name: "System" }); + await system.scrollIntoViewIfNeeded(); + await expect(system).toBeInViewport({ ratio: 1 }); +}); + +test("in forced colours the current destination keeps its indicator", { tag: "@mobile" }, async ({ + testUserPage: page, +}) => { + await page.emulateMedia({ forcedColors: "active" }); + await page.goto("/plan"); + // The pill's fill disappears in forced colours; a Highlight outline replaces it + const indicator = page.getByRole("navigation", { name: "Main" }).getByRole("link", { name: "Plan" }).locator("span").first(); + await expect(indicator).toHaveCSS("outline-style", "solid"); + await expect(indicator).toHaveCSS("outline-width", "2px"); +}); + +test("the sign-in refresh also runs on client navigation and when the tab returns", { tag: "@mobile" }, async ({ page }) => { + const KEY = "study-bot:session-refreshed-at"; + // Refreshed just now as the page loads, so the load itself asks for nothing + await page.addInitScript((key) => localStorage.setItem(key, String(Date.now())), KEY); + await page.goto("/"); + const plan = page.getByRole("navigation", { name: "Main" }).getByRole("link", { name: "Plan" }); + await hydrated(plan); + + // A day since the last refresh, in a tab that stays open + await page.evaluate((key) => localStorage.setItem(key, "0"), KEY); + const onNavigation = page.waitForRequest((request) => new URL(request.url()).pathname === "/api/auth/session"); + await plan.click(); + await expect(page.getByRole("heading", { level: 1 })).toHaveText("Plan"); + await onNavigation; + await expect.poll(() => page.evaluate((key) => Number(localStorage.getItem(key)), KEY)).toBeGreaterThan(0); + + await page.evaluate((key) => localStorage.setItem(key, "0"), KEY); + const onReturn = page.waitForRequest((request) => new URL(request.url()).pathname === "/api/auth/session"); + await page.evaluate(() => document.dispatchEvent(new Event("visibilitychange"))); + await onReturn; +}); diff --git a/e2e/study.spec.ts b/e2e/study.spec.ts new file mode 100644 index 00000000..fdcea8c4 --- /dev/null +++ b/e2e/study.spec.ts @@ -0,0 +1,182 @@ +/** + * Study (/learn): the recommended session card with its mode and reason in + * plain words, the mode and length pickers, Start session (one session + * even on a double click), the course it opens on when none is chosen, and + * Resume session on a planned session that is under way. + * Each test seeds its own identity, because Study picks its course from the + * account's materials and plans. + * + * Already covered elsewhere: the recommendation rules and reason copy in + * src/__tests__/study-recommendations.test.ts, and the session screens in + * the session-*.spec.ts files. + */ +import type { Page, Request } from "@playwright/test"; +import { + test, + expect, + MODE_LABELS, + createPlan, + createSession, + finishSession, + morningZone, + startRun, + unique, + uploadMaterial, +} from "./fixtures"; + +/** The recommendation card: the one section with the Start session button. */ +function sessionCard(page: Page) { + return page + .getByRole("main") + .getByRole("region") + .filter({ has: page.getByRole("button", { name: /^Start(ing)? session/ }) }); +} + +function isStart(request: Request): boolean { + return request.method() === "POST" && new URL(request.url()).pathname === "/api/learn/start"; +} + +test("the recommendation names its mode and reason in plain words", { tag: "@mobile" }, async ({ + testUserPage: page, + testUser, +}) => { + const course = unique("E2E Study"); + await uploadMaterial(testUser.api, { course, text: "Recursion: a function that calls itself until a base case." }); + // Three wrong answers leave three unresolved errors, so Error repair comes first. + const session = await createSession(testUser.api, { course_name: course }); + await finishSession(testUser.api, session.id, { incorrect: 3 }); + + await page.goto("/learn"); + await expect(page.getByRole("combobox", { name: "Course" })).toHaveText(course); + const card = sessionCard(page); + await expect(card.getByRole("heading", { level: 2 })).toHaveText("Error repair"); + await expect(card.getByText("Recommended", { exact: true })).toBeVisible(); + await expect(card).toContainText("Retests your 3 unresolved errors"); + await expect(card).toContainText( + "All are memory gaps. An error is resolved after you answer it correctly on 2 different days.", + ); + // No stored codes or keys reach the student. + await expect(card).not.toContainText(/\b[A-Z]{2,}(_[A-Z]+)+\b|\bMEMORY\b/); + await expect(card).not.toContainText(/\b[a-z0-9]+_[a-z0-9_]+\b/); + await expect(page.getByRole("main").getByText("3 unresolved errors", { exact: true })).toBeVisible(); +}); + +test("the mode and length can change before the session starts", async ({ testUserPage: page, testUser }) => { + test.slow(); + const course = unique("E2E Modes"); + await uploadMaterial(testUser.api, { course, text: "Sorting: merge sort splits, sorts and merges." }); + const session = await createSession(testUser.api, { course_name: course }); + await finishSession(testUser.api, session.id, { incorrect: 3 }); + + await page.goto("/learn"); + const card = sessionCard(page); + await expect(card.getByRole("heading", { level: 2 })).toHaveText("Error repair"); + + await card.getByRole("radio", { name: "Retrieval", exact: true }).check(); + await expect(card.getByRole("heading", { level: 2 })).toHaveText("Retrieval"); + // The recommendation stays visible beside the mode it names. + await expect(card.getByRole("radio", { name: "Error repair Recommended" })).not.toBeChecked(); + await expect(card).toContainText("Error repair is the recommended mode."); + + const length = card.getByRole("radiogroup", { name: "Length" }); + await expect(length.getByRole("radio", { name: "30 min" })).toBeChecked(); + await length.getByRole("radio", { name: "15 min" }).click(); + await expect(length.getByRole("radio", { name: "15 min" })).toBeChecked(); + await expect(card).toContainText("About 5 questions."); + await expect(card).toContainText("Retrieval, 15 min"); + + await card.getByRole("button", { name: "Start session" }).click(); + await expect(page).toHaveURL(/\/s\/[\w-]+$/); + await expect(page.getByRole("heading", { level: 1 })).toContainText("Retrieval:"); + await expect(page.getByRole("main")).toMatchAriaSnapshot(` + - term: Planned time + - definition: 15 min + `); +}); + +test("Start session makes one session on a double click and opens it", { tag: "@mobile" }, async ({ + testUserPage: page, + testUser, +}) => { + const course = unique("E2E Start"); + await uploadMaterial(testUser.api, { course, text: "Graphs: vertices joined by edges." }); + const starts: Request[] = []; + page.on("request", (request) => { + if (isStart(request)) starts.push(request); + }); + + await page.goto("/learn"); + const card = sessionCard(page); + await expect(card.getByRole("heading", { level: 2 })).toHaveText("Retrieval"); + await expect(card).toContainText(`You haven't practiced ${course} yet.`); + + await card.getByRole("button", { name: "Start session" }).dblclick(); + await expect(page).toHaveURL(/\/s\/[\w-]+$/); + await expect(page.getByRole("heading", { level: 1 })).toContainText("Retrieval:"); + await expect(page.getByRole("button", { name: "Start session" })).toBeEnabled(); + expect(starts).toHaveLength(1); + + // The server hands back the same unstarted session for the same request. + const sessionId = new URL(page.url()).pathname.split("/").pop(); + const again = await testUser.api.post("/api/learn/start", { + data: { course_name: course, mode: "RETRIEVAL", minutes: 30 }, + }); + expect(again.status(), await again.text()).toBe(200); + expect(await again.json()).toMatchObject({ session_id: sessionId, reused: true }); +}); + +test("with no course chosen, Study opens on the course with the nearest exam, not the latest upload", async ({ + testUserPage: page, + testUser, +}) => { + test.slow(); + const examCourse = unique("E2E Exam soon"); + const latestCourse = unique("E2E Latest upload"); + await uploadMaterial(testUser.api, { course: examCourse, text: "Recursion: a function that calls itself." }); + await createPlan(testUser.api, { course_name: examCourse, exam_in_days: 7 }); + // Uploaded last, so it heads the course list. + await uploadMaterial(testUser.api, { course: latestCourse, text: "Supply and demand set the price." }); + + await page.goto("/learn"); + const switcher = page.getByRole("combobox", { name: "Course" }); + await expect(switcher).toHaveText(examCourse); + await expect(page.getByRole("main")).toContainText("Final exam is in 7 days"); + + // A course the student picks wins from then on. + await switcher.click(); + await page.getByRole("option", { name: latestCourse }).click(); + await expect(switcher).toHaveText(latestCourse); + await page.reload(); + await expect(page.getByRole("combobox", { name: "Course" })).toHaveText(latestCourse); +}); + +test("a planned session with a run under way offers Resume session, as Home does", async ({ + testUserPage: page, + testUser, +}) => { + const course = unique("E2E Resume"); + await uploadMaterial(testUser.api, { course, text: "Hash tables: keys map to buckets through a hash function." }); + // A morning zone and an all-day window, so sessions are left today whenever the suite runs. + const plan = await createPlan(testUser.api, { course_name: course, time_zone: morningZone(), all_day: true }); + const first = plan.items[0]; + const label = MODE_LABELS[first.mode]; + // Starting the run doesn't touch the plan item; the run is what Study has to read. + await startRun(testUser.api, first.session_id); + + await page.goto("/learn"); + await expect(page.getByRole("combobox", { name: "Course" })).toHaveText(course); + const planned = page.getByRole("region", { name: "Planned for today" }); + const resume = planned.getByRole("link", { name: new RegExp(`^Resume session: ${label}, `) }); + await expect(resume).toHaveText("Resume session"); + await expect(resume).toHaveAttribute("href", `/s/${first.session_id}`); + await expect(planned.locator(`a[href="/s/${first.session_id}"]`)).toHaveCount(1); + + await page.goto("/"); + await expect(page.getByRole("region", { name: "Today" }).getByRole("link", { name: "Resume session" })).toHaveAttribute( + "href", + `/s/${first.session_id}`, + ); + + await page.goto(`/s/${first.session_id}`); + await expect(page.getByRole("button", { name: "Resume session" })).toBeVisible(); +}); diff --git a/e2e/support/api.ts b/e2e/support/api.ts new file mode 100644 index 00000000..e179527e --- /dev/null +++ b/e2e/support/api.ts @@ -0,0 +1,364 @@ +/** + * Test data through the app's own HTTP API. Every helper takes the + * APIRequestContext of the user who should own the data: the fixture + * `request` (the signed-in e2e account), `testUser.api` (a fresh X-User-Id + * identity) or `account.api` (a real account of the test's own). + * + * Give each test its own course name (see `unique`), so tests never see + * each other's sessions, errors or plans and can run in parallel. + */ +import { randomBytes } from "node:crypto"; +import { expect, type APIRequestContext } from "@playwright/test"; +import { TIME_ZONE } from "./env"; +import { dayIn } from "./time"; + +/** "E2E 101 k3f9a2": a label no other test or run will reuse. */ +export function unique(label: string): string { + return `${label} ${randomBytes(3).toString("hex")}`; +} + +/** + * GET an API route as JSON, retried until it answers 200. A request + * context's keep-alive connection can be reset by the server after the + * seconds a test spends in the browser (ECONNRESET), which says nothing about + * the app. Use it for reads after browser steps; never for writes. + */ +export async function getJson<T>(api: APIRequestContext, path: string): Promise<T> { + let body: T | undefined; + await expect(async () => { + const response = await api.get(path); + expect(response.status(), path).toBe(200); + body = (await response.json()) as T; + }).toPass({ timeout: 10_000 }); + return body as T; +} + +export type SessionMode = "RETRIEVAL" | "INTERLEAVED_PRACTICE" | "EXAM_SIM" | "ERROR_REPAIR" | "WORKED_EXAMPLES"; + +/** Each mode as the screens name it. */ +export const MODE_LABELS: Record<SessionMode, string> = { + RETRIEVAL: "Retrieval", + INTERLEAVED_PRACTICE: "Interleaved practice", + EXAM_SIM: "Exam simulation", + ERROR_REPAIR: "Error repair", + WORKED_EXAMPLES: "Worked examples", +}; + +export interface SessionInput { + course_name: string; + exam_name?: string; + mode?: SessionMode; + topic_scope?: string; + planned_minutes?: number; + /** + * Topics the deck draws from. A topic with no mastery yet gets a pretest + * question at the start of the deck (up to 2), which has no error log. + * Leave this out for a predictable deck of `questions` plain questions. + */ + objectives?: { id: string; title: string }[]; + questions?: number; + target_accuracy?: number; +} + +export interface CreatedSession { + id: string; + url: string; + course: string; + exam: string; + topic: string; +} + +/** + * Create a study session. Defaults: Retrieval, 3 questions, one block (so a + * break never starts), no topics (so no pretest questions). + */ +export async function createSession(api: APIRequestContext, input: SessionInput): Promise<CreatedSession> { + const exam = input.exam_name ?? "Final exam"; + const topic = input.topic_scope ?? "End-to-end testing"; + const response = await api.post("/api/sessions", { + data: { + course_name: input.course_name, + exam_name: exam, + mode: input.mode ?? "RETRIEVAL", + topic_scope: topic, + planned_minutes: input.planned_minutes ?? 30, + ...(input.objectives ? { objectives: input.objectives } : {}), + target_outcome: { + prompt_count: input.questions ?? 3, + ...(input.target_accuracy != null ? { target_accuracy: input.target_accuracy } : {}), + }, + break_protocol: { type: "TEST_3_2", cycles: 1 }, + }, + }); + expect(response.status(), await response.text()).toBe(201); + const body = await response.json(); + return { id: body.session_id, url: `/s/${body.session_id}`, course: input.course_name, exam, topic }; +} + +export interface StartedRun { + run_id: string; + status: string; + phase: string; + current_index: number; + prompts: { text: string; objective_id?: string; meta?: Record<string, unknown> }[]; + [key: string]: unknown; +} + +/** Start (or resume) the session's run. */ +export async function startRun(api: APIRequestContext, sessionId: string): Promise<StartedRun> { + const response = await api.post(`/api/sessions/${sessionId}/runs/start`); + expect([200, 201], await response.text()).toContain(response.status()); + return response.json(); +} + +export type SelfScore = "CORRECT" | "PARTIAL" | "INCORRECT"; + +/** Answer and score one question in a Retrieval-style run (immediate scoring). */ +export async function answerQuestion( + api: APIRequestContext, + runId: string, + index: number, + score: SelfScore = "CORRECT", +): Promise<{ status: string; current_index: number; phase?: string; [key: string]: unknown }> { + const response = await api.post(`/api/runs/${runId}/attempt`, { + data: { + prompt_index: index, + user_answer: `Answer ${index + 1}`, + self_score: score, + time_to_answer_seconds: 10, + ...(score === "CORRECT" + ? {} + : { error_log: { error_type: "MEMORY", correction_rule: `Correction rule ${index + 1}` } }), + }, + }); + expect(response.status(), await response.text()).toBe(200); + return response.json(); +} + +/** + * Finish a session through the API: answer every question correctly (the + * first `incorrect` ones wrong, with a correction rule), then answer any + * repair questions those added. Exam simulation answers everything, then + * scores it. Returns the finished run's id. + */ +export async function finishSession( + api: APIRequestContext, + sessionId: string, + { incorrect = 0 }: { incorrect?: number } = {}, +): Promise<string> { + const run = await startRun(api, sessionId); + const count = run.prompts.length; + + if (run.phase === "EXAM") { + for (let i = 0; i < count; i++) { + const answered = await api.post(`/api/runs/${run.run_id}/attempt`, { + data: { prompt_index: i, kind: "ANSWER", user_answer: `Answer ${i + 1}`, time_to_answer_seconds: 10 }, + }); + expect(answered.status(), await answered.text()).toBe(200); + } + for (let i = 0; i < count; i++) { + const wrong = i < incorrect; + const scored = await api.post(`/api/runs/${run.run_id}/attempt`, { + data: { + prompt_index: i, + kind: "SCORE", + self_score: wrong ? "INCORRECT" : "CORRECT", + ...(wrong ? { error_log: { error_type: "MEMORY", correction_rule: `Correction rule ${i + 1}` } } : {}), + }, + }); + expect(scored.status(), await scored.text()).toBe(200); + } + return run.run_id; + } + + let last = { status: run.status, current_index: run.current_index }; + for (let i = 0; i < count; i++) { + last = await answerQuestion(api, run.run_id, i, i < incorrect ? "INCORRECT" : "CORRECT"); + } + // A wrong answer adds a repair question to the end of the deck. + while (last.status === "ACTIVE") { + last = await answerQuestion(api, run.run_id, last.current_index, "CORRECT"); + } + expect(last.status).toBe("COMPLETED"); + return run.run_id; +} + +/** How sure the student was: Guessing, Unsure and Sure are stored as 1, 3 and 5. */ +export type Confidence = 1 | 3 | 5; + +export interface RunAnswer { + score: Exclude<SelfScore, "PARTIAL">; + confidence?: Confidence; +} + +/** + * Answer a whole Retrieval-style run through the API, including the pretest + * questions a session with `objectives` opens with and the repair questions + * wrong answers add. The deck's own questions take `answers` in order (the + * last one repeats); pretest and repair questions are answered correctly, + * with no rating. Unlike finishSession, this can rate confidence and handles + * pretest questions. Returns the finished run's id. + */ +export async function answerRun(api: APIRequestContext, sessionId: string, answers: RunAnswer[]): Promise<string> { + const run = await startRun(api, sessionId); + let state = { status: run.status, current_index: run.current_index }; + let own = 0; + while (state.status === "ACTIVE") { + const index = state.current_index; + const pretest = run.prompts[index]?.meta?.pack === "PRE_TEST"; + const repair = index >= run.prompts.length; + const answer: RunAnswer = pretest || repair ? { score: "CORRECT" } : answers[Math.min(own++, answers.length - 1)]; + const wrong = answer.score === "INCORRECT"; + const response = await api.post(`/api/runs/${run.run_id}/attempt`, { + data: { + prompt_index: index, + user_answer: `Answer ${index + 1}`, + self_score: answer.score, + time_to_answer_seconds: 10, + ...(answer.confidence ? { confidence_rating: answer.confidence } : {}), + ...(pretest ? { is_pretest: true } : {}), + ...(wrong ? { error_log: { error_type: "MEMORY", correction_rule: `Correction rule ${index + 1}` } } : {}), + }, + }); + expect(response.status(), await response.text()).toBe(200); + state = await response.json(); + } + expect(state.status).toBe("COMPLETED"); + return run.run_id; +} + +export interface PlanInput { + course_name: string; + exam_name?: string; + /** Days from today in the plan's zone. Defaults to 14. */ + exam_in_days?: number; + objectives?: string[]; + /** The plan's zone. Defaults to the suite's (America/New_York). */ + time_zone?: string; + /** Free all day (00:00 to 23:45) instead of 9:00 to 17:00. */ + all_day?: boolean; +} + +export interface PlanItem { + id: string; + session_id: string; + start_time: string; + end_time: string; + status: string; + mode: SessionMode; +} + +export interface CreatedPlan { + id: string; + course: string; + exam: string; + /** The exam's calendar day, YYYY-MM-DD. */ + examDate: string; + timeZone: string; + /** The plan's sessions, earliest first. */ + items: PlanItem[]; +} + +/** A plan's sessions, earliest first, with their ids and statuses. */ +export async function planItems(api: APIRequestContext, planId: string): Promise<PlanItem[]> { + const { items } = await getJson<{ items: PlanItem[] }>(api, `/api/plans/${planId}`); + return [...items].sort((a, b) => a.start_time.localeCompare(b.start_time)); +} + +/** + * Create a plan with free time every day (9:00 to 17:00 unless `all_day`). + * The exam date is counted in the plan's own zone. + */ +export async function createPlan(api: APIRequestContext, input: PlanInput): Promise<CreatedPlan> { + const exam = input.exam_name ?? "Final exam"; + const timeZone = input.time_zone ?? TIME_ZONE; + const examDate = dayIn(timeZone, input.exam_in_days ?? 14); + const window = input.all_day ? { start: "00:00", end: "23:45" } : { start: "09:00", end: "17:00" }; + const response = await api.post("/api/plans", { + data: { + course_name: input.course_name, + exam_name: exam, + exam_date: examDate, + timezone: timeZone, + objectives: input.objectives ?? ["Recursion", "Linked lists", "Hash tables", "Sorting", "Graphs"], + availability: Array.from({ length: 7 }, () => window), + daily_study_cap_minutes: 180, + break_protocol_default: "50_10", + }, + }); + expect(response.status(), await response.text()).toBe(201); + const { plan_id: id } = await response.json(); + const items = await planItems(api, id); + expect(items.length, "the plan has sessions").toBeGreaterThan(0); + return { id, course: input.course_name, exam, examDate, timeZone, items }; +} + +/** Mark one of a plan's sessions done or missed. */ +export async function setItemStatus(api: APIRequestContext, planId: string, itemId: string, status: "DONE" | "MISSED") { + const response = await api.post(`/api/plans/${planId}/items/${itemId}/status`, { data: { status } }); + expect(response.status(), await response.text()).toBe(200); +} + +/** + * Upload a text file as course material and process it, so feedback, + * decks, guides and chat have something to cite. With `process: false` the + * file stays "Uploaded". Returns the document id. + */ +export async function uploadMaterial( + api: APIRequestContext, + { + course, + fileName = "notes.txt", + text, + process = true, + }: { course: string; fileName?: string; text: string; process?: boolean }, +): Promise<string> { + const upload = await api.post("/api/content/documents", { + multipart: { + file: { name: fileName, mimeType: "text/plain", buffer: Buffer.from(text) }, + namespace: "COURSE", + course_name: course, + }, + }); + expect([200, 201], await upload.text()).toContain(upload.status()); + const { document_id: documentId } = await upload.json(); + + if (process) { + const processed = await api.post(`/api/content/documents/${documentId}/process`); + expect(processed.status(), await processed.text()).toBe(200); + } + return documentId; +} + +export type GuideType = "KEY_CONCEPTS" | "FAQ" | "CHEAT_SHEET"; + +/** Generate a study guide for a course that has materials (the mock AI writes 2 sections). */ +export async function createGuide(api: APIRequestContext, course: string, type: GuideType = "KEY_CONCEPTS") { + const response = await api.post("/api/guides", { data: { course_name: course, guide_type: type } }); + expect(response.status(), await response.text()).toBe(201); +} + +export interface CreatedDeck { + id: string; + title: string; + course: string; + /** The cards in review order (new cards by position). */ + cards: { id: string; front: string; back: string }[]; +} + +const DECK_NOTES = [ + "Recursion: a function that calls itself on a smaller input.", + "A base case stops the recursion before the call stack overflows.", + "Each recursive call gets its own frame on the call stack.", +].join("\n\n"); + +/** Upload one file (recursion.txt) to a new course and generate its deck; the mock AI writes 3 cards. */ +export async function createDeck(api: APIRequestContext, course = unique("E2E Cards")): Promise<CreatedDeck> { + await uploadMaterial(api, { course, fileName: "recursion.txt", text: DECK_NOTES }); + const response = await api.post("/api/flashcards", { data: { course_name: course } }); + expect(response.status(), await response.text()).toBe(201); + const { id, title } = (await response.json()) as { id: string; title: string }; + const { cards } = await getJson<{ cards: CreatedDeck["cards"] }>(api, `/api/flashcards/${id}/study?scope=all`); + expect(cards).toHaveLength(3); + return { id, title, course, cards }; +} diff --git a/e2e/support/auth.ts b/e2e/support/auth.ts new file mode 100644 index 00000000..816e972b --- /dev/null +++ b/e2e/support/auth.ts @@ -0,0 +1,47 @@ +/** + * Helpers for the auth screens and Settings: opening them once their forms + * have hydrated, signing in through the form, and the copy several specs + * assert. + */ +import { randomBytes } from "node:crypto"; +import { expect, type Page } from "@playwright/test"; + +/** Copy the sign-in page shows for a wrong email or password. */ +export const DETAILS_DONT_MATCH = + "That email and password don't match an account. Check both, or reset your password."; + +/** A unique address for an account a test creates through the UI. */ +export function newEmail(): string { + return `e2e-${randomBytes(5).toString("hex")}@studybot.test`; +} + +/** + * Open the sign-in page. The Email field takes focus when the form has + * hydrated (autoFocus runs in the browser), which is also the cue that + * typing and submitting reach the form's own handlers. + */ +export async function openSignIn(page: Page, path = "/auth/signin"): Promise<void> { + await page.goto(path); + await expect(page.getByRole("textbox", { name: "Email" })).toBeFocused(); +} + +/** Fill the sign-in form and submit it. */ +export async function signInWith(page: Page, email: string, password: string): Promise<void> { + await page.getByRole("textbox", { name: "Email" }).fill(email); + await page.getByLabel("Password", { exact: true }).fill(password); + await page.getByRole("button", { name: "Sign in" }).click(); +} + +/** + * Open Settings and wait for the form to hydrate. The time zone field + * learns the device's zone in the browser, so its "Use this device's time + * zone" button (or "Matches this device") is the cue that the form's own + * handlers are live. + */ +export async function openSettings(page: Page, path = "/settings"): Promise<void> { + await page.goto(path); + await expect(page.getByRole("heading", { level: 1, name: "Settings" })).toBeVisible(); + await expect( + page.getByRole("button", { name: "Use this device's time zone" }).or(page.getByText("Matches this device")), + ).toBeVisible(); +} diff --git a/e2e/support/db.ts b/e2e/support/db.ts new file mode 100644 index 00000000..a2d107a1 --- /dev/null +++ b/e2e/support/db.ts @@ -0,0 +1,241 @@ +/** + * Rows the HTTP API can't reach (or can't write fast enough), read and + * written straight in the e2e database: link tokens (stored as a SHA-256 + * digest, so a test can't read the raw token from the row the app wrote), a + * known question deck (the mock AI never writes one; see seedDeck), and a + * long chat history (the chat routes allow 30 requests a minute). + * + * These need DATABASE_URL in the Playwright process, pointing at the + * database the server uses. CI sets it for the whole job. Without it the + * tests that need it skip with NEEDS_DATABASE. + */ +import { createHash, randomBytes, randomUUID } from "node:crypto"; +import { Client } from "pg"; +import { expect } from "@playwright/test"; +import { assertE2eDatabase } from "./env"; + +const DATABASE_URL = process.env.DATABASE_URL; + +export const hasDatabase = Boolean(DATABASE_URL); + +/** Skip reason for tests that read or write rows directly. */ +export const NEEDS_DATABASE = + "Needs DATABASE_URL set to the server's e2e database, for rows the API can't reach (hashed link tokens, a seeded deck, a long chat history)."; + +/** Run `work` with a connection to the e2e database. */ +async function withDatabase<T>(work: (db: Client) => Promise<T>): Promise<T> { + const db = new Client({ connectionString: assertE2eDatabase(DATABASE_URL) }); + await db.connect(); + try { + return await work(db); + } finally { + await db.end(); + } +} + +async function query<Row>(sql: string, params: unknown[]): Promise<Row[]> { + return withDatabase(async (db) => (await db.query(sql, params)).rows as Row[]); +} + +// --------------------------------------------------------------------------- +// Link tokens (reset password, verify email) + +export type TokenType = "PASSWORD_RESET" | "EMAIL_VERIFY"; + +/** A raw link token and the digest the app stores for it (src/lib/tokens.ts). */ +function newTokenSecret(): { raw: string; digest: string } { + const raw = randomBytes(32).toString("base64url"); + return { raw, digest: createHash("sha256").update(raw).digest("hex") }; +} + +export interface TokenRow { + id: string; + /** Minutes until the link expires (negative once it has). */ + minutes_left: number; + used: boolean; +} + +/** The newest link token of `type` for the account, or undefined. */ +export async function latestToken(email: string, type: TokenType): Promise<TokenRow | undefined> { + const rows = await query<TokenRow>( + // The columns are UTC timestamps without a zone, so compare them with + // UTC "now" in SQL rather than reading them as local dates in Node. + `SELECT t.id, + EXTRACT(EPOCH FROM t.expires_at - timezone('utc', now()))::float / 60 AS minutes_left, + t.used_at IS NOT NULL AS used + FROM verification_tokens t JOIN users u ON u.id = t.user_id + WHERE u.email = $1 AND t.type = $2 + ORDER BY t.created_at DESC + LIMIT 1`, + [email.toLowerCase(), type], + ); + return rows[0]; +} + +/** + * Give the token row a secret the test knows, as if the test had read the + * email, and return the raw token for the link. + */ +export async function takeOverToken(id: string): Promise<string> { + const { raw, digest } = newTokenSecret(); + await query("UPDATE verification_tokens SET token = $1 WHERE id = $2", [digest, id]); + return raw; +} + +/** Write a link token for the account, expiring in `expiresInMinutes` (negative: already expired), and return its raw value. */ +export async function insertToken(email: string, type: TokenType, { expiresInMinutes = 60 } = {}): Promise<string> { + const { raw, digest } = newTokenSecret(); + const inserted = await query( + `INSERT INTO verification_tokens (id, user_id, token, type, expires_at, created_at) + SELECT $1, u.id, $2, $3, timezone('utc', now()) + make_interval(mins => $4::int), timezone('utc', now()) + FROM users u WHERE u.email = $5 + RETURNING id`, + [randomUUID(), digest, type, expiresInMinutes, email.toLowerCase()], + ); + expect(inserted, `no account for ${email}`).toHaveLength(1); + return raw; +} + +/** When the account's email was verified, or null. */ +export async function emailVerifiedAt(email: string): Promise<Date | null> { + const rows = await query<{ email_verified: Date | null }>("SELECT email_verified FROM users WHERE email = $1", [ + email.toLowerCase(), + ]); + expect(rows, `no account for ${email}`).toHaveLength(1); + return rows[0].email_verified; +} + +// --------------------------------------------------------------------------- +// Chat history + +/** + * Store a chat history for the account in one go, oldest first, a second + * apart. POST /api/chat/messages allows 30 requests a minute, so a history + * long enough to page would otherwise take minutes to build. + */ +export async function insertChatMessages( + email: string, + courseKey: string, + messages: readonly { role: "user" | "assistant"; content: string }[], +): Promise<void> { + await withDatabase(async (db) => { + const users = await db.query("SELECT id FROM users WHERE email = $1", [email.toLowerCase()]); + expect(users.rows, `no account for ${email}`).toHaveLength(1); + const userId = users.rows[0].id as string; + for (const [i, message] of messages.entries()) { + await db.query( + `INSERT INTO chat_messages (id, user_id, course_key, role, content, created_at) + VALUES ($1, $2, $3, $4, $5, timezone('utc', now()) - make_interval(secs => $6::int))`, + [randomUUID(), userId, courseKey, message.role, message.content, messages.length - i], + ); + } + }); +} + +// --------------------------------------------------------------------------- +// Seeded question decks + +/** + * One question for seedDeck. With AI_PROVIDER=mock the server never asks + * the AI for a deck (src/services/run.ts skips the AI gateway in mock mode), + * so every run gets template free-recall questions with no model answer and + * no multiple choice. Tests that need those write a known deck into the run. + */ +export interface SeedQuestion { + text: string; + modelAnswer: string; + keyPoints: readonly string[]; + /** Multiple choice: four choices and the zero-based index of the right one. */ + choices?: readonly string[]; + correct?: number; + /** Why each choice tempts, one per choice; shown after a wrong pick. */ + rationales?: readonly string[]; +} + +/** + * Replace a started run's template questions with `deck`, in both places the + * server reads them, as scripts/seed-demo.ts does. The run must have exactly + * `deck.length` questions. The server still grades the real choices and + * reveals the real model answers. + */ +export async function seedDeck(runId: string, deck: readonly SeedQuestion[]): Promise<void> { + await withDatabase(async (db) => { + const found = await db.query("SELECT prompts FROM session_runs WHERE run_id = $1", [runId]); + expect(found.rowCount, `run ${runId} isn't in DATABASE_URL's database; point it at the server's`).toBe(1); + const stored = found.rows[0].prompts as { id: string; objective_id?: string }[]; + expect(stored).toHaveLength(deck.length); + + const prompts = deck.map((q, i) => ({ + id: stored[i].id, + objective_id: stored[i].objective_id, + text: q.text, + // One difficulty for the whole deck, so adaptive difficulty never reorders it. + difficulty: 2, + format: q.choices ? "MCQ" : "FREE_RECALL", + ...(q.choices ? { choices: q.choices, correctIndex: q.correct ?? 0 } : {}), + meta: { + model_answer: q.modelAnswer, + key_points: q.keyPoints, + ...(q.rationales ? { distractorRationales: q.rationales } : {}), + }, + })); + for (const [i, p] of prompts.entries()) { + const meta = p.format === "MCQ" ? { ...p.meta, format: "MCQ", choices: p.choices, correctIndex: p.correctIndex } : p.meta; + const updated = await db.query( + "UPDATE session_run_prompts SET text = $1, difficulty = $2, meta = $3 WHERE run_id = $4 AND prompt_index = $5", + [p.text, p.difficulty, JSON.stringify(meta), runId, i], + ); + expect(updated.rowCount, `question ${i + 1} of run ${runId}`).toBe(1); + } + await db.query("UPDATE session_runs SET prompts = $1 WHERE run_id = $2", [JSON.stringify(prompts), runId]); + }); +} + +/** Questions for seeded decks, about recursion. */ +export const QUESTIONS = { + /** Multiple choice; the right pick is "The base case". */ + baseCase: { + text: "Which part of a recursive function stops the recursion?", + choices: ["The base case", "The recursive call", "The return type", "The parameter list"], + correct: 0, + rationales: [ + "The base case returns without calling the function again.", + "The recursive call is what keeps the recursion going.", + "The return type says what comes back, not when the calls stop.", + "The parameters carry the input, but nothing in them ends the calls.", + ], + modelAnswer: "The base case stops the recursion.", + keyPoints: ["returns without recursing"], + }, + /** Multiple choice; the right pick is "The base case is never reached". */ + overflow: { + text: "What does a stack overflow in a recursive function usually mean?", + choices: [ + "The function returned too early", + "The input was already sorted", + "The base case is never reached", + "The compiler ran out of disk space", + ], + correct: 2, + rationales: [ + "Returning early ends the calls, so the stack shrinks instead.", + "Sorted input changes the work, not whether the calls end.", + "Without a reachable base case the calls never stop.", + "Disk space has nothing to do with the call stack.", + ], + modelAnswer: "The base case is never reached, so the calls never stop.", + keyPoints: ["unreachable base case", "calls never stop"], + }, + /** Free recall, with a model answer. */ + recursiveCase: { + text: "Explain what the recursive case of a function does.", + modelAnswer: "It calls the function again on a smaller input, moving toward the base case.", + keyPoints: ["calls itself on a smaller input", "moves toward the base case"], + }, + /** Free recall, with a model answer. */ + whyBaseCase: { + text: "Why does every recursive function need a base case?", + modelAnswer: "Without a base case the calls never stop and the stack overflows.", + keyPoints: ["the calls must stop", "otherwise the stack overflows"], + }, +} satisfies Record<string, SeedQuestion>; diff --git a/e2e/support/env.ts b/e2e/support/env.ts new file mode 100644 index 00000000..c1772a7b --- /dev/null +++ b/e2e/support/env.ts @@ -0,0 +1,81 @@ +/** + * Where the e2e suite points and who it signs in as. Shared by + * playwright.config.ts, the setup project and the fixtures. + * + * Everything comes from explicit environment variables. The suite never + * reads .env: that file can hold live keys and the development database. + */ +import path from "node:path"; + +/** Port of the app under test. Each parallel run uses its own. */ +export const E2E_PORT = Number(process.env.E2E_PORT ?? 3000); + +export const BASE_URL = `http://localhost:${E2E_PORT}`; + +/** The browser's time zone, and the zone plans are made in unless a test picks another. */ +export const TIME_ZONE = "America/New_York"; + +/** + * Signed-in browser state from the setup project. One file per port, so + * runs against different servers (and databases) never share a cookie. + */ +export const AUTH_FILE = path.join(__dirname, "..", ".auth", String(E2E_PORT), "user.json"); + +/** + * The dedicated e2e account. The setup project creates it through the + * sign-up API (a repeat sign-up for the same email is a no-op) and signs + * in with it on /auth/signin. Override with E2E_USER_EMAIL and + * E2E_USER_PASSWORD; never use a real account. + */ +export const E2E_USER = { + name: "E2E Student", + email: process.env.E2E_USER_EMAIL ?? "e2e-student@studybot.test", + password: process.env.E2E_USER_PASSWORD ?? "e2e-only-Passw0rd", +} as const; + +const AI_FREE_KEY = "dummy"; +const ZERO_KEY = "0".repeat(64); + +/** + * Environment for a server the suite starts itself: offline providers, + * test auth, and URLs that match the port. DATABASE_URL must be set by the + * caller and name an e2e database (see assertE2eDatabase). + */ +export function serverEnv(databaseUrl: string): Record<string, string> { + return { + AI_PROVIDER: "mock", + // Answers every Google Calendar call in memory, and shows the controls. + GOOGLE_PROVIDER: "fake", + EMAIL_PROVIDER: "console", + OPENAI_API_KEY: AI_FREE_KEY, + NEXTAUTH_SECRET: "e2e-test-secret", + TOKEN_ENC_KEY: ZERO_KEY, + // Trust the X-User-Id header. A production build also needs CI=true. + ALLOW_TEST_AUTH: "true", + NEXTAUTH_URL: BASE_URL, + BASE_URL, + DATABASE_URL: databaseUrl, + NEXT_TELEMETRY_DISABLED: "1", + }; +} + +/** + * Refuse to start a server against a database that isn't an e2e one, so a + * missing DATABASE_URL can't fall back to the development database in + * .env. Set E2E_ALLOW_ANY_DB=1 to skip the name check. + */ +export function assertE2eDatabase(databaseUrl: string | undefined): string { + if (!databaseUrl) { + throw new Error( + "Set DATABASE_URL to an e2e database (for example postgresql://postgres:postgres@localhost:5433/studybot_e2e) " + + "before the suite starts a server. See e2e/README.md.", + ); + } + const name = new URL(databaseUrl).pathname.replace(/^\//, ""); + if (!name.includes("e2e") && process.env.E2E_ALLOW_ANY_DB !== "1") { + throw new Error( + `DATABASE_URL points at "${name}", which isn't an e2e database. Use one whose name contains "e2e", or set E2E_ALLOW_ANY_DB=1.`, + ); + } + return databaseUrl; +} diff --git a/e2e/support/lesson.ts b/e2e/support/lesson.ts new file mode 100644 index 00000000..298ee64e --- /dev/null +++ b/e2e/support/lesson.ts @@ -0,0 +1,32 @@ +/** + * Locators for the lesson at /s/[sessionId], shared by the session specs. + * Pick a choice or a confidence level with `pick` (support/page.ts). + */ +import type { Page } from "@playwright/test"; + +export type Verdict = "Correct" | "Partly correct" | "Incorrect"; + +/** "Question 2 of 4" in the top bar; it may carry the exam phase or ", 1 repair question added". */ +export function questionCounter(page: Page, shown: number, total: number) { + return page.getByRole("main").getByText(new RegExp(`^Question ${shown} of ${total}\\b`)); +} + +/** The answer box on a written question. */ +export function answerBox(page: Page) { + return page.getByRole("textbox", { name: "Your answer" }); +} + +/** A confidence level under "How sure are you?". */ +export function confidenceRadio(page: Page, level: "Guessing" | "Unsure" | "Sure") { + return page.getByRole("group", { name: "How sure are you?" }).getByRole("radio", { name: level, exact: true }); +} + +/** The feedback sheet, named for its verdict ("Correct" is inside the other two, hence exact). */ +export function feedbackSheet(page: Page, verdict: Verdict) { + return page.getByRole("region", { name: verdict, exact: true }); +} + +/** Score a written answer with one of the three buttons under "Score your answer". */ +export async function scoreAs(page: Page, verdict: Verdict): Promise<void> { + await page.getByRole("group", { name: "Score your answer" }).getByRole("button", { name: verdict, exact: true }).click(); +} diff --git a/e2e/support/page.ts b/e2e/support/page.ts new file mode 100644 index 00000000..ef111870 --- /dev/null +++ b/e2e/support/page.ts @@ -0,0 +1,75 @@ +/** + * Page helpers shared by the specs: waiting for a control to hydrate, + * menus, toasts, the lesson's tactile radios, and waiting for a screen to + * settle before axe looks at it. + */ +import { expect, type Locator, type Page } from "@playwright/test"; + +/** + * Wait until React has hydrated `control`. Server-rendered controls show + * before the page's script runs, and a click or a typed value then never + * reaches the app's handlers (a menu stays shut, a form submits natively, a + * typed value is lost). React attaches its props to a DOM node when it + * hydrates it, which also covers content inside a Suspense boundary that + * hydrates after the rest of the page. + */ +export async function hydrated(control: Locator): Promise<void> { + await expect + .poll(() => control.evaluate((node) => Object.keys(node).some((key) => key.startsWith("__reactProps$")))) + .toBe(true); +} + +/** Open the menu behind a button once the button has hydrated, and return the menu. */ +export async function openMenu(page: Page, triggerName: string): Promise<Locator> { + const trigger = page.getByRole("button", { name: triggerName }); + await hydrated(trigger); + await trigger.click(); + const menu = page.getByRole("menu"); + await expect(menu).toBeVisible(); + return menu; +} + +/** The toast region (Sonner). Toasts last 8 s, so assert on them soon after the action. */ +export function toasts(page: Page): Locator { + return page.getByRole("region", { name: "Notifications alt+T" }); +} + +/** + * Pick a choice or a confidence level in the lesson. The radios are visually + * hidden inside their tactile cards, which take the click. + */ +export async function pick(radio: Locator): Promise<void> { + await radio.check({ force: true }); +} + +/** + * Wait until the page is still: no "Loading…" status left in the main + * region, and no finite animation running (a dialog or an answer fading in). + * Mid fade-in, text is partly transparent and axe would measure its contrast + * against the wrong colour. + */ +export async function settled(page: Page): Promise<void> { + await expect(page.getByRole("main").getByRole("status").filter({ hasText: /^Loading/ })).toHaveCount(0); + await expect + .poll(() => + page.evaluate( + () => + document + .getAnimations() + .filter((a) => a.playState === "running" && a.effect?.getTiming().iterations !== Infinity).length, + ), + ) + .toBe(0); +} + +/** + * Open `path`, and open it again until `ready` shows. For data the server + * writes just after it answers (mastery, XP and the streak land just after + * a run completes), so the first load can come a moment early. + */ +export async function openWhen(page: Page, path: string, ready: Locator): Promise<void> { + await expect(async () => { + await page.goto(path); + await expect(ready).toBeVisible({ timeout: 1_000 }); + }).toPass({ timeout: 15_000 }); +} diff --git a/e2e/support/time.ts b/e2e/support/time.ts new file mode 100644 index 00000000..44f8461a --- /dev/null +++ b/e2e/support/time.ts @@ -0,0 +1,37 @@ +/** + * Calendar days and time zones for test data. The browser runs in TIME_ZONE + * (America/New_York), and so do plans unless a test picks another zone, so + * days are counted there rather than in the zone of the machine running the + * suite (a CI runner in UTC is a day ahead of New York every evening). + */ +import { TIME_ZONE } from "./env"; + +/** The calendar day `days` from today in `timeZone`, as the API's YYYY-MM-DD. */ +export function dayIn(timeZone: string, days: number): string { + const today = new Intl.DateTimeFormat("en-CA", { + timeZone, + year: "numeric", + month: "2-digit", + day: "2-digit", + }).format(new Date()); + const date = new Date(`${today}T12:00:00Z`); + date.setUTCDate(date.getUTCDate() + days); + return date.toISOString().slice(0, 10); +} + +/** The calendar day `days` from today in the suite's time zone. */ +export function isoDay(days: number): string { + return dayIn(TIME_ZONE, days); +} + +/** + * A fixed-offset zone where it is now between 10:00 and 11:00. A plan made in + * it with an all-day study window always has sessions left today, so the + * Today card and the Start button don't depend on when the suite runs. + */ +export function morningZone(): string { + const offset = ((10 - new Date().getUTCHours() + 36) % 24) - 12; + if (offset === 0) return "Etc/GMT"; + // Etc/GMT names are sign-inverted: Etc/GMT-8 is UTC+8. + return `Etc/GMT${offset > 0 ? "-" : "+"}${Math.abs(offset)}`; +} diff --git a/eslint.config.mjs b/eslint.config.mjs new file mode 100644 index 00000000..03d61675 --- /dev/null +++ b/eslint.config.mjs @@ -0,0 +1,64 @@ +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, + { + rules: { + // A leading underscore marks a value as deliberately unused, e.g. a + // field pulled out of an object so the rest can be passed on. + "@typescript-eslint/no-unused-vars": [ + "warn", + { + argsIgnorePattern: "^_", + varsIgnorePattern: "^_", + caughtErrorsIgnorePattern: "^_", + destructuredArrayIgnorePattern: "^_", + ignoreRestSiblings: true, + }, + ], + }, + }, + { + // Server code and shared libraries never reach into the UI: rules a + // screen shares with a service or a route live in src/lib. + files: ["src/services/**", "src/lib/**", "src/app/api/**"], + rules: { + "no-restricted-imports": [ + "error", + { + patterns: [ + { + group: ["@/components/*", "@/hooks/*"], + message: "Server code can't depend on UI modules. Move the shared code into src/lib.", + }, + ], + }, + ], + }, + }, + { + // Tests import services lazily behind a database check and inspect + // untyped JSON payloads, so `any` stays allowed there. + files: ["src/__tests__/**", "e2e/**"], + rules: { + "@typescript-eslint/no-explicit-any": "off", + }, + }, + globalIgnores([ + // Defaults of eslint-config-next, restated because globalIgnores replaces them + ".next/**", + "out/**", + "build/**", + "next-env.d.ts", + // Generated code and tool output + "generated/**", + "coverage/**", + "playwright-report/**", + "test-results/**", + ]), +]); + +export default eslintConfig; diff --git a/next.config.js b/next.config.js index e1da177b..c6f26afe 100644 --- a/next.config.js +++ b/next.config.js @@ -1,6 +1,16 @@ +// next dev needs eval for fast refresh; production builds do not. +const isDev = process.env.NODE_ENV !== "production" + /** @type {import('next').NextConfig} */ const nextConfig = { - output: process.env.NO_STANDALONE ? undefined : "standalone", + poweredByHeader: false, + // pdf-parse v1 picks its pdf.js build with a dynamic require, which a bundler + // cannot follow, so it is loaded from node_modules at runtime instead. + serverExternalPackages: ["pdf-parse"], + // Keep `next dev` from writing an AGENTS.md file into the project root. + agentRules: false, + // The dev-mode badge overlaps the navigation rail in screenshots. + devIndicators: false, headers: async () => [ { source: "/:path*", @@ -15,11 +25,21 @@ const nextConfig = { key: "Content-Security-Policy", value: [ "default-src 'self'", - "script-src 'self' 'unsafe-inline' 'unsafe-eval'", - "style-src 'self' 'unsafe-inline' https://fonts.googleapis.com", - "font-src 'self' https://fonts.gstatic.com", + // 'unsafe-inline' stays only because Next.js streams page data as + // inline scripts and next-themes adds one, and without a + // per-request nonce nothing else lets them run. A + // Content-Security-Policy that src/proxy.ts sets on a response + // replaces this whole header for that response. + `script-src 'self' 'unsafe-inline'${isDev ? " 'unsafe-eval'" : ""}`, + // Radix, sonner and the chart component set inline styles, and + // fonts are self-hosted from @fontsource packages. + "style-src 'self' 'unsafe-inline'", + "font-src 'self'", "img-src 'self' data: blob:", - "connect-src 'self' https://www.googleapis.com https://oauth2.googleapis.com", + // Google Calendar and OAuth calls run in server routes only; the + // browser reaches Google's consent page by navigation. + "connect-src 'self'", + "object-src 'none'", "frame-ancestors 'none'", "base-uri 'self'", "form-action 'self'", diff --git a/package-lock.json b/package-lock.json index 93df98ec..0717bb2c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7,32 +7,52 @@ "": { "name": "study-bot", "version": "1.0.0", + "hasInstallScript": true, + "license": "MIT", "dependencies": { - "@prisma/adapter-pg": "^7.6.0", - "@prisma/client": "^7.6.0", + "@fontsource-variable/google-sans-code": "^5.3.2", + "@fontsource-variable/google-sans-flex": "^5.3.2", + "@prisma/adapter-pg": "^7.10.0", + "@prisma/client": "^7.10.0", "bcryptjs": "^3.0.3", - "nanoid": "^3.3.11", - "next": "^14.2.35", - "next-auth": "^4.24.13", + "class-variance-authority": "^0.7.1", + "cmdk": "^1.1.1", + "cn": "^0.4.0", + "lucide-react": "^1.55.0", + "nanoid": "^3.3.20", + "next": "^16.4.0", + "next-auth": "^4.24.15", + "next-themes": "^0.4.6", "nodemailer": "^7.0.13", "pdf-parse": "^1.1.1", "pg": "^8.20.0", - "react": "^18.3.1", - "react-dom": "^18.3.1", - "zod": "^4.3.6" + "radix-ui": "^1.8.0", + "react": "^19.3.0", + "react-dom": "^19.3.0", + "react-markdown": "^10.1.0", + "recharts": "^3.8.0", + "remark-gfm": "^4.0.1", + "shadcn": "^4.21.4", + "sonner": "^2.0.8", + "swr": "^2.5.1", + "tw-animate-css": "^1.4.0", + "zod": "^4.6.6" }, "devDependencies": { - "@eslint/eslintrc": "^3.3.5", - "@playwright/test": "^1.58.2", - "@types/node": "^25.5.0", + "@axe-core/playwright": "^4.14.0", + "@playwright/test": "^1.64.0", + "@tailwindcss/postcss": "^4.3.3", + "@types/node": "^22.20.5", "@types/nodemailer": "^8.0.0", "@types/pg": "^8.20.0", - "@types/react": "^19.2.14", - "@vitejs/plugin-react": "^6.0.1", + "@types/react": "^19.3.0", + "@types/react-dom": "^19.3.0", "dotenv": "^17.4.2", - "eslint": "^8.57.1", - "eslint-config-next": "^14.2.35", - "prisma": "^7.6.0", + "eslint": "^9.39.5", + "eslint-config-next": "^16.4.0", + "postcss": "^8.5.29", + "prisma": "^7.10.0", + "tailwindcss": "^4.3.3", "tsx": "^4.21.0", "typescript": "^6.0.2", "vitest": "^4.1.2" @@ -41,2754 +61,13014 @@ "node": ">=20.19.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==", + "node_modules/@alloc/quick-lru": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@alloc/quick-lru/-/quick-lru-5.3.0.tgz", + "integrity": "sha512-U4+70Pc5ZS9osnCBCE5Jha/ciHM+Yp+CNMNC/7HvYbNRk1Ldd+f7qO65W5qfhu/TCv+/ozljlXXe9Nj8419DMA==", + "dev": true, "license": "MIT", "engines": { - "node": ">=6.9.0" + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "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", + "node_modules/@axe-core/playwright": { + "version": "4.14.0", + "resolved": "https://registry.npmjs.org/@axe-core/playwright/-/playwright-4.14.0.tgz", + "integrity": "sha512-SGUhG5PIHd2eMdpgBF2PyQLOhX+qyDR2PT4cmoS4Qk2ak+jX/rrSvst9l0PGv5WTHolKpUMvVmoHpr4cZgf1RQ==", + "dev": true, + "license": "MPL-2.0", "dependencies": { - "picocolors": "^1.0.0", - "sisteransi": "^1.0.5" + "axe-core": "~4.14.0" + }, + "engines": { + "node": ">=22.12.0" + }, + "peerDependencies": { + "playwright-core": ">= 1.0.0" } }, - "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, + "node_modules/@babel/code-frame": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", + "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==", "license": "MIT", "dependencies": { - "@clack/core": "0.5.0", - "picocolors": "^1.0.0", - "sisteransi": "^1.0.5" - } - }, - "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" + "@babel/helper-validator-identifier": "^7.29.7", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" }, - "peerDependencies": { - "@electric-sql/pglite": "0.4.1" + "engines": { + "node": ">=6.9.0" } }, - "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/@babel/compat-data": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.7.tgz", + "integrity": "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" } }, - "node_modules/@emnapi/core": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.9.1.tgz", - "integrity": "sha512-mukuNALVsoix/w1BJwFzwXBN/dHeejQtuVzcDsfOEsdpCumXb/E9j8w11h5S54tT1xhifGfbbSm/ICrObRb3KA==", - "dev": true, + "node_modules/@babel/core": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.7.tgz", + "integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==", "license": "MIT", - "optional": true, "dependencies": { - "@emnapi/wasi-threads": "1.2.0", - "tslib": "^2.4.0" + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.7", + "@babel/helper-compilation-targets": "^7.29.7", + "@babel/helper-module-transforms": "^7.29.7", + "@babel/helpers": "^7.29.7", + "@babel/parser": "^7.29.7", + "@babel/template": "^7.29.7", + "@babel/traverse": "^7.29.7", + "@babel/types": "^7.29.7", + "@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/@emnapi/runtime": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.9.1.tgz", - "integrity": "sha512-VYi5+ZVLhpgK4hQ0TAjiQiZ6ol0oe4mBx7mVv7IflsiEp0OWoVsp/+f9Vc1hOhE0TtkORVrI1GvzyreqpgWtkA==", - "dev": true, + "node_modules/@babel/core/node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", "license": "MIT", - "optional": true, "dependencies": { - "tslib": "^2.4.0" + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } } }, - "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, + "node_modules/@babel/generator": { + "version": "7.29.8", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.8.tgz", + "integrity": "sha512-gZbepsdh3WDtgZKWL+vTPh71LSBrm/Y4/QDZBVCcYfmeTEEuoOYwlSy+G1StfJg+/Zy550u/3TATbm7qDbbMtg==", "license": "MIT", - "optional": true, "dependencies": { - "tslib": "^2.4.0" + "@babel/parser": "^7.29.8", + "@babel/types": "^7.29.8", + "@jridgewell/gen-mapping": "^0.3.12", + "@jridgewell/trace-mapping": "^0.3.28", + "jsesc": "^3.0.2" + }, + "engines": { + "node": ">=6.9.0" } }, - "node_modules/@esbuild/aix-ppc64": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.7.tgz", - "integrity": "sha512-EKX3Qwmhz1eMdEJokhALr0YiD0lhQNwDqkPYyPhiSwKrh7/4KRjQc04sZ8db+5DVVnZ1LmbNDI1uAMPEUBnQPg==", - "cpu": [ - "ppc64" - ], - "dev": true, + "node_modules/@babel/helper-annotate-as-pure": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-annotate-as-pure/-/helper-annotate-as-pure-7.29.7.tgz", + "integrity": "sha512-OoK6239jHPuSQOoS0kfTVKn0b/rVTk0seKq4Gd2UMLtmOVLjDC0ki3e+c90Trqv2gMfvJFqkiljrr568+qddiw==", "license": "MIT", - "optional": true, - "os": [ - "aix" - ], + "dependencies": { + "@babel/types": "^7.29.7" + }, "engines": { - "node": ">=18" + "node": ">=6.9.0" } }, - "node_modules/@esbuild/android-arm": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.7.tgz", - "integrity": "sha512-jbPXvB4Yj2yBV7HUfE2KHe4GJX51QplCN1pGbYjvsyCZbQmies29EoJbkEc+vYuU5o45AfQn37vZlyXy4YJ8RQ==", - "cpu": [ - "arm" - ], - "dev": true, + "node_modules/@babel/helper-compilation-targets": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.7.tgz", + "integrity": "sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g==", "license": "MIT", - "optional": true, - "os": [ - "android" - ], + "dependencies": { + "@babel/compat-data": "^7.29.7", + "@babel/helper-validator-option": "^7.29.7", + "browserslist": "^4.24.0", + "lru-cache": "^5.1.1", + "semver": "^6.3.1" + }, "engines": { - "node": ">=18" + "node": ">=6.9.0" } }, - "node_modules/@esbuild/android-arm64": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.7.tgz", - "integrity": "sha512-62dPZHpIXzvChfvfLJow3q5dDtiNMkwiRzPylSCfriLvZeq0a1bWChrGx/BbUbPwOrsWKMn8idSllklzBy+dgQ==", - "cpu": [ - "arm64" - ], - "dev": true, + "node_modules/@babel/helper-create-class-features-plugin": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-create-class-features-plugin/-/helper-create-class-features-plugin-7.29.7.tgz", + "integrity": "sha512-IY3ZD9Tmooqr3TUhc3DUWxiuo8xx1DWLhd5M7hQ+ZWJamqM2BbalrBJb2MisSLoYorOj75U03qULCxQTY9r3hg==", "license": "MIT", - "optional": true, - "os": [ - "android" - ], + "dependencies": { + "@babel/helper-annotate-as-pure": "^7.29.7", + "@babel/helper-member-expression-to-functions": "^7.29.7", + "@babel/helper-optimise-call-expression": "^7.29.7", + "@babel/helper-replace-supers": "^7.29.7", + "@babel/helper-skip-transparent-expression-wrappers": "^7.29.7", + "@babel/traverse": "^7.29.7", + "semver": "^6.3.1" + }, "engines": { - "node": ">=18" + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" } }, - "node_modules/@esbuild/android-x64": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.7.tgz", - "integrity": "sha512-x5VpMODneVDb70PYV2VQOmIUUiBtY3D3mPBG8NxVk5CogneYhkR7MmM3yR/uMdITLrC1ml/NV1rj4bMJuy9MCg==", - "cpu": [ - "x64" - ], - "dev": true, + "node_modules/@babel/helper-globals": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.29.7.tgz", + "integrity": "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==", "license": "MIT", - "optional": true, - "os": [ - "android" - ], "engines": { - "node": ">=18" + "node": ">=6.9.0" } }, - "node_modules/@esbuild/darwin-arm64": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.7.tgz", - "integrity": "sha512-5lckdqeuBPlKUwvoCXIgI2D9/ABmPq3Rdp7IfL70393YgaASt7tbju3Ac+ePVi3KDH6N2RqePfHnXkaDtY9fkw==", - "cpu": [ - "arm64" - ], - "dev": true, + "node_modules/@babel/helper-member-expression-to-functions": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-7.29.7.tgz", + "integrity": "sha512-j+7JYmk1JYDtACIGj0QJqqWZjoUpMoEikQGADMaHgCMCSDqd2+P32rfcibUNrGOMWrlzK1WJBdxrB3JJQZwWtg==", "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], + "dependencies": { + "@babel/traverse": "^7.29.7", + "@babel/types": "^7.29.7" + }, "engines": { - "node": ">=18" + "node": ">=6.9.0" } }, - "node_modules/@esbuild/darwin-x64": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.7.tgz", - "integrity": "sha512-rYnXrKcXuT7Z+WL5K980jVFdvVKhCHhUwid+dDYQpH+qu+TefcomiMAJpIiC2EM3Rjtq0sO3StMV/+3w3MyyqQ==", - "cpu": [ - "x64" - ], - "dev": true, + "node_modules/@babel/helper-module-imports": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.29.7.tgz", + "integrity": "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==", "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], + "dependencies": { + "@babel/traverse": "^7.29.7", + "@babel/types": "^7.29.7" + }, "engines": { - "node": ">=18" + "node": ">=6.9.0" } }, - "node_modules/@esbuild/freebsd-arm64": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.7.tgz", - "integrity": "sha512-B48PqeCsEgOtzME2GbNM2roU29AMTuOIN91dsMO30t+Ydis3z/3Ngoj5hhnsOSSwNzS+6JppqWsuhTp6E82l2w==", - "cpu": [ - "arm64" - ], - "dev": true, + "node_modules/@babel/helper-module-transforms": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.7.tgz", + "integrity": "sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg==", "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], + "dependencies": { + "@babel/helper-module-imports": "^7.29.7", + "@babel/helper-validator-identifier": "^7.29.7", + "@babel/traverse": "^7.29.7" + }, "engines": { - "node": ">=18" + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" } }, - "node_modules/@esbuild/freebsd-x64": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.7.tgz", - "integrity": "sha512-jOBDK5XEjA4m5IJK3bpAQF9/Lelu/Z9ZcdhTRLf4cajlB+8VEhFFRjWgfy3M1O4rO2GQ/b2dLwCUGpiF/eATNQ==", - "cpu": [ - "x64" - ], - "dev": true, + "node_modules/@babel/helper-optimise-call-expression": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-optimise-call-expression/-/helper-optimise-call-expression-7.29.7.tgz", + "integrity": "sha512-+kmGVjcT9RGYzoDwdwEqEvGgKe3BYq+O1iGzjFubaNgZHwYHP6lsF2Yghf4kEuv9BV7tYDZ913aBW9am6YKong==", "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], + "dependencies": { + "@babel/types": "^7.29.7" + }, "engines": { - "node": ">=18" + "node": ">=6.9.0" } }, - "node_modules/@esbuild/linux-arm": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.7.tgz", - "integrity": "sha512-RkT/YXYBTSULo3+af8Ib0ykH8u2MBh57o7q/DAs3lTJlyVQkgQvlrPTnjIzzRPQyavxtPtfg0EopvDyIt0j1rA==", - "cpu": [ - "arm" - ], - "dev": true, + "node_modules/@babel/helper-plugin-utils": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.29.7.tgz", + "integrity": "sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw==", "license": "MIT", - "optional": true, - "os": [ - "linux" - ], "engines": { - "node": ">=18" + "node": ">=6.9.0" } }, - "node_modules/@esbuild/linux-arm64": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.7.tgz", - "integrity": "sha512-RZPHBoxXuNnPQO9rvjh5jdkRmVizktkT7TCDkDmQ0W2SwHInKCAV95GRuvdSvA7w4VMwfCjUiPwDi0ZO6Nfe9A==", - "cpu": [ - "arm64" - ], - "dev": true, + "node_modules/@babel/helper-replace-supers": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-replace-supers/-/helper-replace-supers-7.29.7.tgz", + "integrity": "sha512-atfGXWSeCiF4DnKZIfmJfQRkSw9b9gNNXR1kqKjbhG4pGYCOnkp8OcTB8E3NXjBu8NpheSnOeNKz8KT7UNFTmQ==", "license": "MIT", - "optional": true, - "os": [ - "linux" - ], + "dependencies": { + "@babel/helper-member-expression-to-functions": "^7.29.7", + "@babel/helper-optimise-call-expression": "^7.29.7", + "@babel/traverse": "^7.29.7" + }, "engines": { - "node": ">=18" + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" } }, - "node_modules/@esbuild/linux-ia32": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.7.tgz", - "integrity": "sha512-GA48aKNkyQDbd3KtkplYWT102C5sn/EZTY4XROkxONgruHPU72l+gW+FfF8tf2cFjeHaRbWpOYa/uRBz/Xq1Pg==", - "cpu": [ - "ia32" - ], - "dev": true, + "node_modules/@babel/helper-skip-transparent-expression-wrappers": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-skip-transparent-expression-wrappers/-/helper-skip-transparent-expression-wrappers-7.29.7.tgz", + "integrity": "sha512-brcMGQaVzIeUb+6/bs1Av0f8YuNNjKY2JyvfRCsFuFsdKccEQ5Ges2y74D74NZ1Rz8lKJ9ksJkfqwQFJ/iNEyQ==", "license": "MIT", - "optional": true, - "os": [ - "linux" - ], + "dependencies": { + "@babel/traverse": "^7.29.7", + "@babel/types": "^7.29.7" + }, "engines": { - "node": ">=18" + "node": ">=6.9.0" } }, - "node_modules/@esbuild/linux-loong64": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.7.tgz", - "integrity": "sha512-a4POruNM2oWsD4WKvBSEKGIiWQF8fZOAsycHOt6JBpZ+JN2n2JH9WAv56SOyu9X5IqAjqSIPTaJkqN8F7XOQ5Q==", - "cpu": [ - "loong64" - ], - "dev": true, + "node_modules/@babel/helper-string-parser": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz", + "integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==", "license": "MIT", - "optional": true, - "os": [ - "linux" - ], "engines": { - "node": ">=18" + "node": ">=6.9.0" } }, - "node_modules/@esbuild/linux-mips64el": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.7.tgz", - "integrity": "sha512-KabT5I6StirGfIz0FMgl1I+R1H73Gp0ofL9A3nG3i/cYFJzKHhouBV5VWK1CSgKvVaG4q1RNpCTR2LuTVB3fIw==", - "cpu": [ - "mips64el" - ], - "dev": true, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", "license": "MIT", - "optional": true, - "os": [ - "linux" - ], "engines": { - "node": ">=18" + "node": ">=6.9.0" } }, - "node_modules/@esbuild/linux-ppc64": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.7.tgz", - "integrity": "sha512-gRsL4x6wsGHGRqhtI+ifpN/vpOFTQtnbsupUF5R5YTAg+y/lKelYR1hXbnBdzDjGbMYjVJLJTd2OFmMewAgwlQ==", - "cpu": [ - "ppc64" - ], - "dev": true, + "node_modules/@babel/helper-validator-option": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.29.7.tgz", + "integrity": "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==", "license": "MIT", - "optional": true, - "os": [ - "linux" - ], "engines": { - "node": ">=18" + "node": ">=6.9.0" } }, - "node_modules/@esbuild/linux-riscv64": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.7.tgz", - "integrity": "sha512-hL25LbxO1QOngGzu2U5xeXtxXcW+/GvMN3ejANqXkxZ/opySAZMrc+9LY/WyjAan41unrR3YrmtTsUpwT66InQ==", - "cpu": [ - "riscv64" - ], - "dev": true, + "node_modules/@babel/helpers": { + "version": "7.29.10", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.10.tgz", + "integrity": "sha512-EMCx3AGZ3WfAl6ht7AyQoPm2Lh+BGYEMdc4Q6Hf7uSCDOZFuLq44qNwL+iaim8VlyYhRAo4X43+weadK8ZB4Yg==", "license": "MIT", - "optional": true, - "os": [ - "linux" - ], + "dependencies": { + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.8" + }, "engines": { - "node": ">=18" + "node": ">=6.9.0" } }, - "node_modules/@esbuild/linux-s390x": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.7.tgz", - "integrity": "sha512-2k8go8Ycu1Kb46vEelhu1vqEP+UeRVj2zY1pSuPdgvbd5ykAw82Lrro28vXUrRmzEsUV0NzCf54yARIK8r0fdw==", - "cpu": [ - "s390x" - ], - "dev": true, + "node_modules/@babel/parser": { + "version": "7.29.9", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.9.tgz", + "integrity": "sha512-CjXrNHTnvqBVqHgdBysY3vk2T8tpJHb5/RMeHJBTyVa9xgugCB0CJTx/3oO8RV2QRQP391RWpB7D6hLjm8V9uA==", "license": "MIT", - "optional": true, - "os": [ - "linux" - ], + "dependencies": { + "@babel/types": "^7.29.8" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, "engines": { - "node": ">=18" + "node": ">=6.0.0" } }, - "node_modules/@esbuild/linux-x64": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.7.tgz", - "integrity": "sha512-hzznmADPt+OmsYzw1EE33ccA+HPdIqiCRq7cQeL1Jlq2gb1+OyWBkMCrYGBJ+sxVzve2ZJEVeePbLM2iEIZSxA==", - "cpu": [ - "x64" - ], - "dev": true, + "node_modules/@babel/plugin-syntax-jsx": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.29.7.tgz", + "integrity": "sha512-TSu8+mHCoEaaCDEZ0I3+6mvTBYR4PCxQwf2z9/r5Tbztv6NaLR3B9thGTTxX2WGuGHJqRiAbKPeGTJ5XWXVg6A==", "license": "MIT", - "optional": true, - "os": [ - "linux" - ], + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.7" + }, "engines": { - "node": ">=18" + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" } }, - "node_modules/@esbuild/netbsd-arm64": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.7.tgz", - "integrity": "sha512-b6pqtrQdigZBwZxAn1UpazEisvwaIDvdbMbmrly7cDTMFnw/+3lVxxCTGOrkPVnsYIosJJXAsILG9XcQS+Yu6w==", - "cpu": [ - "arm64" - ], - "dev": true, + "node_modules/@babel/plugin-syntax-typescript": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-typescript/-/plugin-syntax-typescript-7.29.7.tgz", + "integrity": "sha512-ngr+82Sh0xMz25TPCZi+nC2iTzjfCdWS2ONXTp/PtSCHCgaCNBpdMqgvJ2ccdLlClVZ7sisIgB914j/JFe+RZA==", "license": "MIT", - "optional": true, - "os": [ - "netbsd" - ], + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.7" + }, "engines": { - "node": ">=18" + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" } }, - "node_modules/@esbuild/netbsd-x64": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.7.tgz", - "integrity": "sha512-OfatkLojr6U+WN5EDYuoQhtM+1xco+/6FSzJJnuWiUw5eVcicbyK3dq5EeV/QHT1uy6GoDhGbFpprUiHUYggrw==", - "cpu": [ - "x64" - ], - "dev": true, + "node_modules/@babel/plugin-transform-modules-commonjs": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-commonjs/-/plugin-transform-modules-commonjs-7.29.7.tgz", + "integrity": "sha512-j0vCldybPC5b5dwCQOJ21uKtHzt7hxLygJTg9eF1ScfaikEDNfzn94XoW5Fi+seBR0nCyL23xaBFFkq7dTM8XQ==", "license": "MIT", - "optional": true, - "os": [ - "netbsd" - ], + "dependencies": { + "@babel/helper-module-transforms": "^7.29.7", + "@babel/helper-plugin-utils": "^7.29.7" + }, "engines": { - "node": ">=18" + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" } }, - "node_modules/@esbuild/openbsd-arm64": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.7.tgz", - "integrity": "sha512-AFuojMQTxAz75Fo8idVcqoQWEHIXFRbOc1TrVcFSgCZtQfSdc1RXgB3tjOn/krRHENUB4j00bfGjyl2mJrU37A==", - "cpu": [ - "arm64" - ], - "dev": true, + "node_modules/@babel/plugin-transform-typescript": { + "version": "7.29.9", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-typescript/-/plugin-transform-typescript-7.29.9.tgz", + "integrity": "sha512-FFwIwzU+7SCOuxxV4YtJql6T9981ZVTm+FHO5GhVsRqCTdy0WwrEZh3l42ARpXruJUDGOptdduHW6Zr7pNPLNg==", "license": "MIT", - "optional": true, - "os": [ - "openbsd" - ], + "dependencies": { + "@babel/helper-annotate-as-pure": "^7.29.7", + "@babel/helper-create-class-features-plugin": "^7.29.7", + "@babel/helper-plugin-utils": "^7.29.7", + "@babel/helper-skip-transparent-expression-wrappers": "^7.29.7", + "@babel/plugin-syntax-typescript": "^7.29.7" + }, "engines": { - "node": ">=18" + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" } }, - "node_modules/@esbuild/openbsd-x64": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.7.tgz", - "integrity": "sha512-+A1NJmfM8WNDv5CLVQYJ5PshuRm/4cI6WMZRg1by1GwPIQPCTs1GLEUHwiiQGT5zDdyLiRM/l1G0Pv54gvtKIg==", - "cpu": [ - "x64" - ], - "dev": true, + "node_modules/@babel/preset-typescript": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/preset-typescript/-/preset-typescript-7.29.7.tgz", + "integrity": "sha512-/Foi8vKY2EVbed/1eZx0gJEEwHAIxogrySI7rULcRIvhZzbvoE/b5qG5Ghc0WKAFKOHA9SD1x7RsFlOYdutIiQ==", "license": "MIT", - "optional": true, - "os": [ - "openbsd" - ], + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.7", + "@babel/helper-validator-option": "^7.29.7", + "@babel/plugin-syntax-jsx": "^7.29.7", + "@babel/plugin-transform-modules-commonjs": "^7.29.7", + "@babel/plugin-transform-typescript": "^7.29.7" + }, "engines": { - "node": ">=18" + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" } }, - "node_modules/@esbuild/openharmony-arm64": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.7.tgz", - "integrity": "sha512-+KrvYb/C8zA9CU/g0sR6w2RBw7IGc5J2BPnc3dYc5VJxHCSF1yNMxTV5LQ7GuKteQXZtspjFbiuW5/dOj7H4Yw==", - "cpu": [ - "arm64" - ], - "dev": true, + "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", - "optional": true, - "os": [ - "openharmony" - ], "engines": { - "node": ">=18" + "node": ">=6.9.0" } }, - "node_modules/@esbuild/sunos-x64": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.7.tgz", - "integrity": "sha512-ikktIhFBzQNt/QDyOL580ti9+5mL/YZeUPKU2ivGtGjdTYoqz6jObj6nOMfhASpS4GU4Q/Clh1QtxWAvcYKamA==", - "cpu": [ - "x64" - ], - "dev": true, + "node_modules/@babel/template": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz", + "integrity": "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==", "license": "MIT", - "optional": true, - "os": [ - "sunos" - ], + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/parser": "^7.29.7", + "@babel/types": "^7.29.7" + }, "engines": { - "node": ">=18" + "node": ">=6.9.0" } }, - "node_modules/@esbuild/win32-arm64": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.7.tgz", - "integrity": "sha512-7yRhbHvPqSpRUV7Q20VuDwbjW5kIMwTHpptuUzV+AA46kiPze5Z7qgt6CLCK3pWFrHeNfDd1VKgyP4O+ng17CA==", - "cpu": [ - "arm64" - ], - "dev": true, + "node_modules/@babel/traverse": { + "version": "7.29.10", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.10.tgz", + "integrity": "sha512-B3lYAs2nkKskbgQ1nfy8Ma9ao9Q1rntTAQHrzzyDuj+TSO+X3le6PfWwqDvodsb+OumE10eMFfuMCTQSQ5iuIQ==", "license": "MIT", - "optional": true, - "os": [ - "win32" - ], + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.8", + "@babel/helper-globals": "^7.29.7", + "@babel/parser": "^7.29.9", + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.8", + "debug": "^4.3.1" + }, "engines": { - "node": ">=18" + "node": ">=6.9.0" } }, - "node_modules/@esbuild/win32-ia32": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.7.tgz", - "integrity": "sha512-SmwKXe6VHIyZYbBLJrhOoCJRB/Z1tckzmgTLfFYOfpMAx63BJEaL9ExI8x7v0oAO3Zh6D/Oi1gVxEYr5oUCFhw==", - "cpu": [ - "ia32" - ], - "dev": true, + "node_modules/@babel/traverse/node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", "license": "MIT", - "optional": true, - "os": [ - "win32" - ], + "dependencies": { + "ms": "^2.1.3" + }, "engines": { - "node": ">=18" + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } } }, - "node_modules/@esbuild/win32-x64": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.7.tgz", - "integrity": "sha512-56hiAJPhwQ1R4i+21FVF7V8kSD5zZTdHcVuRFMW0hn753vVfQN8xlx4uOPT4xoGH0Z/oVATuR82AiqSTDIpaHg==", - "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, + "node_modules/@babel/types": { + "version": "7.29.8", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.8.tgz", + "integrity": "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==", "license": "MIT", "dependencies": { - "eslint-visitor-keys": "^3.4.3" + "@babel/helper-string-parser": "^7.29.7", + "@babel/helper-validator-identifier": "^7.29.7" }, "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": ">=6.9.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" + "node_modules/@dotenvx/dotenvx": { + "version": "1.75.1", + "resolved": "https://registry.npmjs.org/@dotenvx/dotenvx/-/dotenvx-1.75.1.tgz", + "integrity": "sha512-/BITOC9dmS/edY2zQwZNicQ059O6RKabtQfyEafV0nGtfYRNHYy1DIPiYVcov40+tob9hfmBnbR963dS+EQ1DQ==", + "license": "BSD-3-Clause", + "dependencies": { + "@dotenvx/primitives": "^0.8.0", + "commander": "^11.1.0", + "conf": "^10.2.0", + "dotenv": "^17.2.1", + "enquirer": "^2.4.1", + "env-paths": "^2.2.1", + "execa": "^5.1.1", + "fdir": "^6.2.0", + "ignore": "^5.3.0", + "object-treeify": "1.1.33", + "open": "^8.4.2", + "picomatch": "^4.0.4", + "systeminformation": "^5.22.11", + "undici": "^7.11.0", + "which": "^4.0.0", + "yocto-spinner": "^1.1.0" + }, + "bin": { + "dotenvx": "src/cli/dotenvx.js" }, "funding": { - "url": "https://opencollective.com/eslint" + "url": "https://dotenvx.com" } }, - "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, + "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": "^12.0.0 || ^14.0.0 || >=16.0.0" + "node": ">=16" } }, - "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, + "node_modules/@dotenvx/dotenvx/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", - "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": ">=8" } }, - "node_modules/@eslint/eslintrc/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, + "node_modules/@dotenvx/dotenvx/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", - "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" + "engines": { + "node": ">=6" } }, - "node_modules/@eslint/eslintrc/node_modules/debug": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", - "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", - "dev": true, + "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": { - "ms": "^2.1.3" + "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": ">=6.0" + "node": ">=10" }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } + "funding": { + "url": "https://github.com/sindresorhus/execa?sponsor=1" } }, - "node_modules/@eslint/eslintrc/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, + "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": ">=18" + "node": ">=10" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/@eslint/eslintrc/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/@eslint/js": { - "version": "8.57.1", - "resolved": "https://registry.npmjs.org/@eslint/js/-/js-8.57.1.tgz", - "integrity": "sha512-d9zaMRSTIKDLhctzH12MtXvJKSSUhaHcjV+2Z+GK+EEY7XKpP5yR4x+N3TAcHTcu963nIr+TMcCb4DBCYX1z6Q==", - "dev": true, - "license": "MIT", + "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": "^12.22.0 || ^14.17.0 || >=16.0.0" + "node": ">=10.17.0" } }, - "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, + "node_modules/@dotenvx/dotenvx/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": ">=18.14.1" + "node": ">=8" }, - "peerDependencies": { - "hono": "^4" + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/@humanwhocodes/config-array": { - "version": "0.13.0", - "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.13.0.tgz", - "integrity": "sha512-DZLEEqFWQFiyK6h5YIeynKx7JlvCYWL0cImfSRXZ9l4Sg2efkFGTuFf6vzXjK1cq6IYkU+Eg/JizXw+TD2vRNw==", - "deprecated": "Use @eslint/config-array instead", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@humanwhocodes/object-schema": "^2.0.3", - "debug": "^4.3.1", - "minimatch": "^3.0.5" - }, + "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": ">=10.10.0" + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/@humanwhocodes/config-array/node_modules/debug": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", - "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", - "dev": true, + "node_modules/@dotenvx/dotenvx/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": { - "ms": "^2.1.3" + "is-docker": "^2.0.0" }, "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } + "node": ">=8" } }, - "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", + "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": ">=12.22" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/nzakas" + "node": ">=18" } }, - "node_modules/@humanwhocodes/object-schema": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/@humanwhocodes/object-schema/-/object-schema-2.0.3.tgz", - "integrity": "sha512-93zYdMES/c1D69yZiKDBj0V24vqNzB/koF26KPaagAfd3P/4gUlh3Dys5ogAK+Exi9QyzlD8x/08Zt7wIKcDcA==", - "deprecated": "Use @eslint/object-schema instead", - "dev": true, - "license": "BSD-3-Clause" - }, - "node_modules/@isaacs/cliui": { - "version": "8.0.2", - "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", - "integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==", - "dev": true, - "license": "ISC", + "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": { - "string-width": "^5.1.2", - "string-width-cjs": "npm:string-width@^4.2.0", - "strip-ansi": "^7.0.1", - "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", - "wrap-ansi": "^8.1.0", - "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" + "path-key": "^3.0.0" }, "engines": { - "node": ">=12" + "node": ">=8" } }, - "node_modules/@isaacs/cliui/node_modules/ansi-regex": { - "version": "6.2.2", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz", - "integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==", - "dev": true, + "node_modules/@dotenvx/dotenvx/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/chalk/ansi-regex?sponsor=1" + "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/@isaacs/cliui/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==", - "dev": true, + "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": { - "ansi-regex": "^6.2.2" + "isexe": "^3.1.1" }, - "engines": { - "node": ">=12" + "bin": { + "node-which": "bin/which.js" }, - "funding": { - "url": "https://github.com/chalk/strip-ansi?sponsor=1" + "engines": { + "node": "^16.13.0 || >=18.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==", - "dev": true, - "license": "MIT" + "node_modules/@dotenvx/primitives": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/@dotenvx/primitives/-/primitives-0.8.0.tgz", + "integrity": "sha512-VYJy0uhFm9zTJ1TxBaW/pA8bjbOM/OttaNMwZ1RHG4JKyRG7DhSdiqD1ipQoAyoD22olUtxbP78W9xY3Wd11bg==", + "license": "BSD-3-Clause" }, - "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==", + "node_modules/@electric-sql/pglite": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/@electric-sql/pglite/-/pglite-0.4.3.tgz", + "integrity": "sha512-ichuWTgtd4mOM1G4SpyGJa5trT03lWbMypDV0fUXUCXg5hiHqVAz/bZyV68NqmkLB7WcYmj1RMJVSp8HV/v/ZQ==", "devOptional": true, - "license": "MIT" + "license": "Apache-2.0" }, - "node_modules/@napi-rs/wasm-runtime": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.2.tgz", - "integrity": "sha512-sNXv5oLJ7ob93xkZ1XnxisYhGYXfaG9f65/ZgYuAu3qt7b3NadcOEhLvx28hv31PgX8SZJRYrAIPQilQmFpLVw==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "@tybys/wasm-util": "^0.10.1" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/Brooooooklyn" + "node_modules/@electric-sql/pglite-socket": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/@electric-sql/pglite-socket/-/pglite-socket-0.1.3.tgz", + "integrity": "sha512-LAciWM0M1dCL8hlsxu2venbVZcdxema0BtDfpWYVqr+Y468UADw0pFWidhKw1M8sfJ8rdLT71tjMmnirf/IZRQ==", + "devOptional": true, + "license": "Apache-2.0", + "bin": { + "pglite-server": "dist/scripts/server.js" }, "peerDependencies": { - "@emnapi/core": "^1.7.1", - "@emnapi/runtime": "^1.7.1" + "@electric-sql/pglite": "0.4.3" } }, - "node_modules/@next/env": { - "version": "14.2.35", - "resolved": "https://registry.npmjs.org/@next/env/-/env-14.2.35.tgz", - "integrity": "sha512-DuhvCtj4t9Gwrx80dmz2F4t/zKQ4ktN8WrMwOuVzkJfBilwAwGr6v16M5eI8yCuZ63H9TTuEU09Iu2HqkzFPVQ==", - "license": "MIT" + "node_modules/@electric-sql/pglite-tools": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/@electric-sql/pglite-tools/-/pglite-tools-0.3.3.tgz", + "integrity": "sha512-AlzLJTRJ8+UFgK8CmxIpyIpJ0+YaFw02IiOSdYrqxwPXdSyeIShz8aa9Tq+tYFXdPwcaMp/Fc80mQZ1dkOQ/wg==", + "devOptional": true, + "license": "Apache-2.0", + "peerDependencies": { + "@electric-sql/pglite": "0.4.3" + } }, - "node_modules/@next/eslint-plugin-next": { - "version": "14.2.35", - "resolved": "https://registry.npmjs.org/@next/eslint-plugin-next/-/eslint-plugin-next-14.2.35.tgz", - "integrity": "sha512-Jw9A3ICz2183qSsqwi7fgq4SBPiNfmOLmTPXKvlnzstUwyvBrtySiY+8RXJweNAs9KThb1+bYhZh9XWcNOr2zQ==", + "node_modules/@emnapi/core": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.9.1.tgz", + "integrity": "sha512-mukuNALVsoix/w1BJwFzwXBN/dHeejQtuVzcDsfOEsdpCumXb/E9j8w11h5S54tT1xhifGfbbSm/ICrObRb3KA==", "dev": true, "license": "MIT", + "optional": true, "dependencies": { - "glob": "10.3.10" + "@emnapi/wasi-threads": "1.2.0", + "tslib": "^2.4.0" } }, - "node_modules/@next/eslint-plugin-next/node_modules/brace-expansion": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.3.tgz", - "integrity": "sha512-MCV/fYJEbqx68aE58kv2cA/kiky1G8vux3OR6/jbS+jIMe/6fJWa0DTzJU7dqijOWYwHi1t29FlfYI9uytqlpA==", - "dev": true, + "node_modules/@emnapi/runtime": { + "version": "1.11.3", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz", + "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==", "license": "MIT", + "optional": true, "dependencies": { - "balanced-match": "^1.0.0" + "tslib": "^2.4.0" } }, - "node_modules/@next/eslint-plugin-next/node_modules/glob": { - "version": "10.3.10", - "resolved": "https://registry.npmjs.org/glob/-/glob-10.3.10.tgz", - "integrity": "sha512-fa46+tv1Ak0UPK1TOy/pZrIybNNt4HCv7SDzwyfiOZkvZLEbjsZkJBPtDHVshZjbecAoAGSC20MjLDG/qr679g==", - "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", + "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": "ISC", + "license": "MIT", + "optional": true, "dependencies": { - "foreground-child": "^3.1.0", - "jackspeak": "^2.3.5", - "minimatch": "^9.0.1", - "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0", - "path-scurry": "^1.10.1" - }, - "bin": { - "glob": "dist/esm/bin.mjs" - }, + "tslib": "^2.4.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.7.tgz", + "integrity": "sha512-EKX3Qwmhz1eMdEJokhALr0YiD0lhQNwDqkPYyPhiSwKrh7/4KRjQc04sZ8db+5DVVnZ1LmbNDI1uAMPEUBnQPg==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], "engines": { - "node": ">=16 || 14 >=14.17" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" + "node": ">=18" } }, - "node_modules/@next/eslint-plugin-next/node_modules/minimatch": { - "version": "9.0.9", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.9.tgz", - "integrity": "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==", + "node_modules/@esbuild/android-arm": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.7.tgz", + "integrity": "sha512-jbPXvB4Yj2yBV7HUfE2KHe4GJX51QplCN1pGbYjvsyCZbQmies29EoJbkEc+vYuU5o45AfQn37vZlyXy4YJ8RQ==", + "cpu": [ + "arm" + ], "dev": true, - "license": "ISC", - "dependencies": { - "brace-expansion": "^2.0.2" - }, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], "engines": { - "node": ">=16 || 14 >=14.17" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" + "node": ">=18" } }, - "node_modules/@next/swc-darwin-arm64": { - "version": "14.2.33", - "resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-14.2.33.tgz", - "integrity": "sha512-HqYnb6pxlsshoSTubdXKu15g3iivcbsMXg4bYpjL2iS/V6aQot+iyF4BUc2qA/J/n55YtvE4PHMKWBKGCF/+wA==", + "node_modules/@esbuild/android-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.7.tgz", + "integrity": "sha512-62dPZHpIXzvChfvfLJow3q5dDtiNMkwiRzPylSCfriLvZeq0a1bWChrGx/BbUbPwOrsWKMn8idSllklzBy+dgQ==", "cpu": [ "arm64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ - "darwin" + "android" ], "engines": { - "node": ">= 10" + "node": ">=18" } }, - "node_modules/@next/swc-darwin-x64": { - "version": "14.2.33", - "resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-14.2.33.tgz", - "integrity": "sha512-8HGBeAE5rX3jzKvF593XTTFg3gxeU4f+UWnswa6JPhzaR6+zblO5+fjltJWIZc4aUalqTclvN2QtTC37LxvZAA==", + "node_modules/@esbuild/android-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.7.tgz", + "integrity": "sha512-x5VpMODneVDb70PYV2VQOmIUUiBtY3D3mPBG8NxVk5CogneYhkR7MmM3yR/uMdITLrC1ml/NV1rj4bMJuy9MCg==", "cpu": [ "x64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ - "darwin" + "android" ], "engines": { - "node": ">= 10" + "node": ">=18" } }, - "node_modules/@next/swc-linux-arm64-gnu": { - "version": "14.2.33", - "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-14.2.33.tgz", - "integrity": "sha512-JXMBka6lNNmqbkvcTtaX8Gu5by9547bukHQvPoLe9VRBx1gHwzf5tdt4AaezW85HAB3pikcvyqBToRTDA4DeLw==", + "node_modules/@esbuild/darwin-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.7.tgz", + "integrity": "sha512-5lckdqeuBPlKUwvoCXIgI2D9/ABmPq3Rdp7IfL70393YgaASt7tbju3Ac+ePVi3KDH6N2RqePfHnXkaDtY9fkw==", "cpu": [ "arm64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ - "linux" + "darwin" ], "engines": { - "node": ">= 10" + "node": ">=18" } }, - "node_modules/@next/swc-linux-arm64-musl": { - "version": "14.2.33", - "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-14.2.33.tgz", - "integrity": "sha512-Bm+QulsAItD/x6Ih8wGIMfRJy4G73tu1HJsrccPW6AfqdZd0Sfm5Imhgkgq2+kly065rYMnCOxTBvmvFY1BKfg==", + "node_modules/@esbuild/darwin-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.7.tgz", + "integrity": "sha512-rYnXrKcXuT7Z+WL5K980jVFdvVKhCHhUwid+dDYQpH+qu+TefcomiMAJpIiC2EM3Rjtq0sO3StMV/+3w3MyyqQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.7.tgz", + "integrity": "sha512-B48PqeCsEgOtzME2GbNM2roU29AMTuOIN91dsMO30t+Ydis3z/3Ngoj5hhnsOSSwNzS+6JppqWsuhTp6E82l2w==", "cpu": [ "arm64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ - "linux" + "freebsd" ], "engines": { - "node": ">= 10" + "node": ">=18" } }, - "node_modules/@next/swc-linux-x64-gnu": { - "version": "14.2.33", - "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-14.2.33.tgz", - "integrity": "sha512-FnFn+ZBgsVMbGDsTqo8zsnRzydvsGV8vfiWwUo1LD8FTmPTdV+otGSWKc4LJec0oSexFnCYVO4hX8P8qQKaSlg==", + "node_modules/@esbuild/freebsd-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.7.tgz", + "integrity": "sha512-jOBDK5XEjA4m5IJK3bpAQF9/Lelu/Z9ZcdhTRLf4cajlB+8VEhFFRjWgfy3M1O4rO2GQ/b2dLwCUGpiF/eATNQ==", "cpu": [ "x64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ - "linux" + "freebsd" ], "engines": { - "node": ">= 10" + "node": ">=18" } }, - "node_modules/@next/swc-linux-x64-musl": { - "version": "14.2.33", - "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-14.2.33.tgz", - "integrity": "sha512-345tsIWMzoXaQndUTDv1qypDRiebFxGYx9pYkhwY4hBRaOLt8UGfiWKr9FSSHs25dFIf8ZqIFaPdy5MljdoawA==", + "node_modules/@esbuild/linux-arm": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.7.tgz", + "integrity": "sha512-RkT/YXYBTSULo3+af8Ib0ykH8u2MBh57o7q/DAs3lTJlyVQkgQvlrPTnjIzzRPQyavxtPtfg0EopvDyIt0j1rA==", "cpu": [ - "x64" + "arm" ], + "dev": true, "license": "MIT", "optional": true, "os": [ "linux" ], "engines": { - "node": ">= 10" + "node": ">=18" } }, - "node_modules/@next/swc-win32-arm64-msvc": { - "version": "14.2.33", - "resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-14.2.33.tgz", - "integrity": "sha512-nscpt0G6UCTkrT2ppnJnFsYbPDQwmum4GNXYTeoTIdsmMydSKFz9Iny2jpaRupTb+Wl298+Rh82WKzt9LCcqSQ==", + "node_modules/@esbuild/linux-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.7.tgz", + "integrity": "sha512-RZPHBoxXuNnPQO9rvjh5jdkRmVizktkT7TCDkDmQ0W2SwHInKCAV95GRuvdSvA7w4VMwfCjUiPwDi0ZO6Nfe9A==", "cpu": [ "arm64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ - "win32" + "linux" ], "engines": { - "node": ">= 10" + "node": ">=18" } }, - "node_modules/@next/swc-win32-ia32-msvc": { - "version": "14.2.33", - "resolved": "https://registry.npmjs.org/@next/swc-win32-ia32-msvc/-/swc-win32-ia32-msvc-14.2.33.tgz", - "integrity": "sha512-pc9LpGNKhJ0dXQhZ5QMmYxtARwwmWLpeocFmVG5Z0DzWq5Uf0izcI8tLc+qOpqxO1PWqZ5A7J1blrUIKrIFc7Q==", + "node_modules/@esbuild/linux-ia32": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.7.tgz", + "integrity": "sha512-GA48aKNkyQDbd3KtkplYWT102C5sn/EZTY4XROkxONgruHPU72l+gW+FfF8tf2cFjeHaRbWpOYa/uRBz/Xq1Pg==", "cpu": [ "ia32" ], + "dev": true, "license": "MIT", "optional": true, "os": [ - "win32" + "linux" ], "engines": { - "node": ">= 10" + "node": ">=18" } }, - "node_modules/@next/swc-win32-x64-msvc": { - "version": "14.2.33", - "resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-14.2.33.tgz", - "integrity": "sha512-nOjfZMy8B94MdisuzZo9/57xuFVLHJaDj5e/xrduJp9CV2/HrfxTRH2fbyLe+K9QT41WBLUd4iXX3R7jBp0EUg==", + "node_modules/@esbuild/linux-loong64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.7.tgz", + "integrity": "sha512-a4POruNM2oWsD4WKvBSEKGIiWQF8fZOAsycHOt6JBpZ+JN2n2JH9WAv56SOyu9X5IqAjqSIPTaJkqN8F7XOQ5Q==", "cpu": [ - "x64" + "loong64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ - "win32" + "linux" ], "engines": { - "node": ">= 10" + "node": ">=18" } }, - "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==", + "node_modules/@esbuild/linux-mips64el": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.7.tgz", + "integrity": "sha512-KabT5I6StirGfIz0FMgl1I+R1H73Gp0ofL9A3nG3i/cYFJzKHhouBV5VWK1CSgKvVaG4q1RNpCTR2LuTVB3fIw==", + "cpu": [ + "mips64el" + ], "dev": true, "license": "MIT", - "dependencies": { - "@nodelib/fs.stat": "2.0.5", - "run-parallel": "^1.1.9" - }, + "optional": true, + "os": [ + "linux" + ], "engines": { - "node": ">= 8" + "node": ">=18" } }, - "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==", + "node_modules/@esbuild/linux-ppc64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.7.tgz", + "integrity": "sha512-gRsL4x6wsGHGRqhtI+ifpN/vpOFTQtnbsupUF5R5YTAg+y/lKelYR1hXbnBdzDjGbMYjVJLJTd2OFmMewAgwlQ==", + "cpu": [ + "ppc64" + ], "dev": true, "license": "MIT", + "optional": true, + "os": [ + "linux" + ], "engines": { - "node": ">= 8" + "node": ">=18" } }, - "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==", + "node_modules/@esbuild/linux-riscv64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.7.tgz", + "integrity": "sha512-hL25LbxO1QOngGzu2U5xeXtxXcW+/GvMN3ejANqXkxZ/opySAZMrc+9LY/WyjAan41unrR3YrmtTsUpwT66InQ==", + "cpu": [ + "riscv64" + ], "dev": true, "license": "MIT", - "dependencies": { - "@nodelib/fs.scandir": "2.1.5", - "fastq": "^1.6.0" - }, + "optional": true, + "os": [ + "linux" + ], "engines": { - "node": ">= 8" + "node": ">=18" } }, - "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==", + "node_modules/@esbuild/linux-s390x": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.7.tgz", + "integrity": "sha512-2k8go8Ycu1Kb46vEelhu1vqEP+UeRVj2zY1pSuPdgvbd5ykAw82Lrro28vXUrRmzEsUV0NzCf54yARIK8r0fdw==", + "cpu": [ + "s390x" + ], "dev": true, "license": "MIT", + "optional": true, + "os": [ + "linux" + ], "engines": { - "node": ">=12.4.0" + "node": ">=18" } }, - "node_modules/@oxc-project/types": { - "version": "0.122.0", - "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.122.0.tgz", - "integrity": "sha512-oLAl5kBpV4w69UtFZ9xqcmTi+GENWOcPF7FCrczTiBbmC0ibXxCwyvZGbO39rCVEuLGAZM84DH0pUIyyv/YJzA==", + "node_modules/@esbuild/linux-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.7.tgz", + "integrity": "sha512-hzznmADPt+OmsYzw1EE33ccA+HPdIqiCRq7cQeL1Jlq2gb1+OyWBkMCrYGBJ+sxVzve2ZJEVeePbLM2iEIZSxA==", + "cpu": [ + "x64" + ], "dev": true, "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/Boshen" - } - }, - "node_modules/@panva/hkdf": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/@panva/hkdf/-/hkdf-1.2.1.tgz", - "integrity": "sha512-6oclG6Y3PiDFcoyk8srjLfVKyMfVCKJ27JwNPViuXziFpmdz+MZnZN/aKY0JGXgYuO/VghU0jcOAZgWXZ1Dmrw==", - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/panva" + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" } }, - "node_modules/@pkgjs/parseargs": { - "version": "0.11.0", - "resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz", - "integrity": "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==", + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.7.tgz", + "integrity": "sha512-b6pqtrQdigZBwZxAn1UpazEisvwaIDvdbMbmrly7cDTMFnw/+3lVxxCTGOrkPVnsYIosJJXAsILG9XcQS+Yu6w==", + "cpu": [ + "arm64" + ], "dev": true, "license": "MIT", "optional": true, + "os": [ + "netbsd" + ], "engines": { - "node": ">=14" + "node": ">=18" } }, - "node_modules/@playwright/test": { - "version": "1.58.2", - "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.58.2.tgz", - "integrity": "sha512-akea+6bHYBBfA9uQqSYmlJXn61cTa+jbO87xVLCWbTqbWadRVmhxlXATaOjOgcBaWU4ePo0wB41KMFv3o35IXA==", - "devOptional": true, - "license": "Apache-2.0", - "dependencies": { - "playwright": "1.58.2" - }, - "bin": { - "playwright": "cli.js" - }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.7.tgz", + "integrity": "sha512-OfatkLojr6U+WN5EDYuoQhtM+1xco+/6FSzJJnuWiUw5eVcicbyK3dq5EeV/QHT1uy6GoDhGbFpprUiHUYggrw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], "engines": { "node": ">=18" } }, - "node_modules/@prisma/adapter-pg": { - "version": "7.6.0", - "resolved": "https://registry.npmjs.org/@prisma/adapter-pg/-/adapter-pg-7.6.0.tgz", - "integrity": "sha512-BjHNmJqqa42NqJSDPnXUfwUofWo8LJY7Ui2gqxN4DmAOb+H/gGKv+hln2Xq/1kSJXPW5AXMXuNiPDMpywvyIOw==", - "license": "Apache-2.0", - "dependencies": { - "@prisma/driver-adapter-utils": "7.6.0", - "@types/pg": "^8.16.0", - "pg": "^8.16.3", - "postgres-array": "3.0.4" + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.7.tgz", + "integrity": "sha512-AFuojMQTxAz75Fo8idVcqoQWEHIXFRbOc1TrVcFSgCZtQfSdc1RXgB3tjOn/krRHENUB4j00bfGjyl2mJrU37A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" } }, - "node_modules/@prisma/client": { - "version": "7.6.0", - "resolved": "https://registry.npmjs.org/@prisma/client/-/client-7.6.0.tgz", - "integrity": "sha512-7Pe/1ayh3GgWPEg4mmT4ax77LJ1wC+XlnIFvQ94bLP2DsUnOpnruQQR3Jw7r+Frthk94QqDNxo3FjSg8h9PXeQ==", - "license": "Apache-2.0", - "dependencies": { - "@prisma/client-runtime-utils": "7.6.0" - }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.7.tgz", + "integrity": "sha512-+A1NJmfM8WNDv5CLVQYJ5PshuRm/4cI6WMZRg1by1GwPIQPCTs1GLEUHwiiQGT5zDdyLiRM/l1G0Pv54gvtKIg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], "engines": { - "node": "^20.19 || ^22.12 || >=24.0" - }, - "peerDependencies": { - "prisma": "*", - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "prisma": { - "optional": true - }, - "typescript": { - "optional": true - } + "node": ">=18" } }, - "node_modules/@prisma/client-runtime-utils": { - "version": "7.6.0", - "resolved": "https://registry.npmjs.org/@prisma/client-runtime-utils/-/client-runtime-utils-7.6.0.tgz", - "integrity": "sha512-fD7jlqubsZvVODKvsp9lOpXVecx2aWGxC2l35Ioz2t+teUJ5CfR0SAMsi7UkU1VvaZmmm+DS6BdujF622nY7tQ==", - "license": "Apache-2.0" + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.7.tgz", + "integrity": "sha512-+KrvYb/C8zA9CU/g0sR6w2RBw7IGc5J2BPnc3dYc5VJxHCSF1yNMxTV5LQ7GuKteQXZtspjFbiuW5/dOj7H4Yw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } }, - "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/@esbuild/sunos-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.7.tgz", + "integrity": "sha512-ikktIhFBzQNt/QDyOL580ti9+5mL/YZeUPKU2ivGtGjdTYoqz6jObj6nOMfhASpS4GU4Q/Clh1QtxWAvcYKamA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" } }, - "node_modules/@prisma/debug": { - "version": "7.6.0", - "resolved": "https://registry.npmjs.org/@prisma/debug/-/debug-7.6.0.tgz", - "integrity": "sha512-LpHr3qos4lQZ6sxwjStf59YBht7m9/QF7NSQsMH6qGENWZu2w3UkQUGn1h5iRkDjnWRj3VHykOu9qFhps4ADvA==", - "license": "Apache-2.0" + "node_modules/@esbuild/win32-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.7.tgz", + "integrity": "sha512-7yRhbHvPqSpRUV7Q20VuDwbjW5kIMwTHpptuUzV+AA46kiPze5Z7qgt6CLCK3pWFrHeNfDd1VKgyP4O+ng17CA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } }, - "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/@esbuild/win32-ia32": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.7.tgz", + "integrity": "sha512-SmwKXe6VHIyZYbBLJrhOoCJRB/Z1tckzmgTLfFYOfpMAx63BJEaL9ExI8x7v0oAO3Zh6D/Oi1gVxEYr5oUCFhw==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" } }, - "node_modules/@prisma/driver-adapter-utils": { - "version": "7.6.0", - "resolved": "https://registry.npmjs.org/@prisma/driver-adapter-utils/-/driver-adapter-utils-7.6.0.tgz", - "integrity": "sha512-D8j3p0RnhLuufMaRLX6QqtGgPC5Ao3l5oFP6Q5AL0rTHi4vna+NzGEipwCsfvcSvaGFCbsH3lsTMbb4WvY+ovA==", - "license": "Apache-2.0", + "node_modules/@esbuild/win32-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.7.tgz", + "integrity": "sha512-56hiAJPhwQ1R4i+21FVF7V8kSD5zZTdHcVuRFMW0hn753vVfQN8xlx4uOPT4xoGH0Z/oVATuR82AiqSTDIpaHg==", + "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": { - "@prisma/debug": "7.6.0" + "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/@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, + "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", - "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" + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" } }, - "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/@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/@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, + "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": { - "@prisma/debug": "7.6.0" + "@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/@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", + "node_modules/@eslint/config-array/node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", "dependencies": { - "@prisma/debug": "7.6.0", - "@prisma/engines-version": "7.6.0-1.75cbdc1eb7150937890ad5465d861175c6624711", - "@prisma/get-platform": "7.6.0" + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } } }, - "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, + "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": { - "@prisma/debug": "7.6.0" + "@eslint/core": "^0.17.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.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, + "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": { - "ajv": "^8.12.0", - "better-result": "^2.7.0", - "env-paths": "^3.0.0", - "proper-lockfile": "^4.1.2" + "@types/json-schema": "^7.0.15" }, "engines": { - "bun": ">=1.3.6", - "node": ">=22.0.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" } }, - "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", + "node_modules/@eslint/eslintrc": { + "version": "3.3.7", + "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-3.3.7.tgz", + "integrity": "sha512-F42g89Qd5oAWtp0k0nnSrjziAKza7w8SVT4mStc18LZMaRb4J1HQAHLCalEtDCxrTuksx7NU9qsmeLwpOfPqWw==", + "dev": true, + "license": "MIT", "dependencies": { - "@radix-ui/react-toggle": "1.1.10", - "chart.js": "4.5.1" + "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.3.2", + "minimatch": "^3.1.5", + "strip-json-comments": "^3.1.1" }, "engines": { - "node": "^20.19 || ^22.12 || >=24.0", - "pnpm": "8" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, - "peerDependencies": { - "@types/react": "^18.0.0 || ^19.0.0", - "react": "^18.0.0 || ^19.0.0", - "react-dom": "^18.0.0 || ^19.0.0" + "funding": { + "url": "https://opencollective.com/eslint" } }, - "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, + "node_modules/@eslint/eslintrc/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", - "peerDependencies": { - "@types/react": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + "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" }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - } + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" } }, - "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, + "node_modules/@eslint/eslintrc/node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, "license": "MIT", "dependencies": { - "@radix-ui/react-slot": "1.2.3" + "ms": "^2.1.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" + "engines": { + "node": ">=6.0" }, "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { + "supports-color": { "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, + "node_modules/@eslint/eslintrc/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", - "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" + "engines": { + "node": ">=18" }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - } + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "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, + "node_modules/@eslint/eslintrc/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/@eslint/js": { + "version": "9.39.5", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.39.5.tgz", + "integrity": "sha512-QywQuszQh77pIXCsq998c8hbhSTI/azTty1Z6N53dmAudKHhy573j3yvRLsX2BSp8YpLtoCEG8E9DJe+8zUh4A==", + "dev": 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" + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, - "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" + "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" }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" } }, - "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, + "node_modules/@floating-ui/core": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.8.0.tgz", + "integrity": "sha512-0CIZ5itps/8x7BG8dEIhs53BvCUH2PCoogtakwRTut+Arm58sJooJ0AuZhLw2HJYIR5cMLNPBSS728sPho2khQ==", "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 - } + "@floating-ui/utils": "^0.2.12" } }, - "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, + "node_modules/@floating-ui/dom": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.8.0.tgz", + "integrity": "sha512-yXSrzeHZBTZadLOlfyhCkJHNeLJnHRnRInwdZ40L7ZiaAtrBwoYlsDrX3v5zB1Utk7CLfzcOVnVVWoXEky7Ceg==", "license": "MIT", "dependencies": { - "@radix-ui/react-use-layout-effect": "1.1.1" + "@floating-ui/core": "^1.8.0", + "@floating-ui/utils": "^0.2.12" + } + }, + "node_modules/@floating-ui/react-dom": { + "version": "2.1.9", + "resolved": "https://registry.npmjs.org/@floating-ui/react-dom/-/react-dom-2.1.9.tgz", + "integrity": "sha512-JDjEFGCpImxDCA7JJKviA0M9+RtmJdj0m/NVU5IMgBK+AmZouAQQ7/+2GLH0GXXY0YMw9oXPB8hKdbPYg5QLYg==", + "license": "MIT", + "dependencies": { + "@floating-ui/dom": "^1.8.0" }, "peerDependencies": { - "@types/react": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - } + "react": ">=16.8.0", + "react-dom": ">=16.8.0" } }, - "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, + "node_modules/@floating-ui/utils": { + "version": "0.2.12", + "resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.12.tgz", + "integrity": "sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==", + "license": "MIT" + }, + "node_modules/@fontsource-variable/google-sans-code": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/@fontsource-variable/google-sans-code/-/google-sans-code-5.3.2.tgz", + "integrity": "sha512-kW4RcfoTTObtUWAhlh6hzs8LCDsBNLwVRPqjUIKMkEiabfR3SRGP0Y6erFKd9k1yaRppTSCLSVkxhPKpEW3QPg==", + "license": "OFL-1.1", + "funding": { + "url": "https://github.com/sponsors/ayuhito" + } + }, + "node_modules/@fontsource-variable/google-sans-flex": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/@fontsource-variable/google-sans-flex/-/google-sans-flex-5.3.2.tgz", + "integrity": "sha512-y7k6vuO6ib6GdOns4Da7NungIK7W5PXblS+ObXyaHPcKNKNSmJrEFMzsMsIL2SINGjV3+knXzyGnyfcj4X44qw==", + "license": "OFL-1.1", + "funding": { + "url": "https://github.com/sponsors/ayuhito" + } + }, + "node_modules/@hono/node-server": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-2.1.4.tgz", + "integrity": "sha512-2g1qeHl4BduwDn6L8nkAvDrPUWPMlkQ//a5NhP/zIyaXKMjZNRV+cG9Csu+BiJFf6+68pqzjf4Hi5sJGKHuS1g==", "license": "MIT", - "peerDependencies": { - "@types/react": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + "engines": { + "node": ">=20" }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - } + "peerDependencies": { + "hono": "^4 || ^5.0.0-0" } }, - "node_modules/@rolldown/binding-android-arm64": { - "version": "1.0.0-rc.12", - "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.0.0-rc.12.tgz", - "integrity": "sha512-pv1y2Fv0JybcykuiiD3qBOBdz6RteYojRFY1d+b95WVuzx211CRh+ytI/+9iVyWQ6koTh5dawe4S/yRfOFjgaA==", - "cpu": [ - "arm64" - ], + "node_modules/@humanfs/core": { + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz", + "integrity": "sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==", "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], + "license": "Apache-2.0", + "dependencies": { + "@humanfs/types": "^0.15.0" + }, "engines": { - "node": "^20.19.0 || >=22.12.0" + "node": ">=18.18.0" } }, - "node_modules/@rolldown/binding-darwin-arm64": { - "version": "1.0.0-rc.12", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.0.0-rc.12.tgz", - "integrity": "sha512-cFYr6zTG/3PXXF3pUO+umXxt1wkRK/0AYT8lDwuqvRC+LuKYWSAQAQZjCWDQpAH172ZV6ieYrNnFzVVcnSflAg==", + "node_modules/@humanfs/node": { + "version": "0.16.8", + "resolved": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.8.tgz", + "integrity": "sha512-gE1eQNZ3R++kTzFUpdGlpmy8kDZD/MLyHqDwqjkVQI0JMdI1D51sy1H958PNXYkM2rAac7e5/CnIKZrHtPh3BQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@humanfs/core": "^0.19.2", + "@humanfs/types": "^0.15.0", + "@humanwhocodes/retry": "^0.4.0" + }, + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanfs/types": { + "version": "0.15.0", + "resolved": "https://registry.npmjs.org/@humanfs/types/-/types-0.15.0.tgz", + "integrity": "sha512-ZZ1w0aoQkwuUuC7Yf+7sdeaNfqQiiLcSRbfI08oAxqLtpXQr9AIVX7Ay7HLDuiLYAaFPu8oBYNq/QIi9URHJ3Q==", + "dev": true, + "license": "Apache-2.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.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.5.tgz", + "integrity": "sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==", "cpu": [ "arm64" ], - "dev": true, - "license": "MIT", + "license": "Apache-2.0", "optional": true, "os": [ "darwin" ], "engines": { - "node": "^20.19.0 || >=22.12.0" + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-arm64": "1.3.4" } }, - "node_modules/@rolldown/binding-darwin-x64": { - "version": "1.0.0-rc.12", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.0.0-rc.12.tgz", - "integrity": "sha512-ZCsYknnHzeXYps0lGBz8JrF37GpE9bFVefrlmDrAQhOEi4IOIlcoU1+FwHEtyXGx2VkYAvhu7dyBf75EJQffBw==", + "node_modules/@img/sharp-darwin-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.5.tgz", + "integrity": "sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==", "cpu": [ "x64" ], - "dev": true, - "license": "MIT", + "license": "Apache-2.0", "optional": true, "os": [ "darwin" ], "engines": { - "node": "^20.19.0 || >=22.12.0" + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-x64": "1.3.4" } }, - "node_modules/@rolldown/binding-freebsd-x64": { - "version": "1.0.0-rc.12", - "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.0.0-rc.12.tgz", - "integrity": "sha512-dMLeprcVsyJsKolRXyoTH3NL6qtsT0Y2xeuEA8WQJquWFXkEC4bcu1rLZZSnZRMtAqwtrF/Ib9Ddtpa/Gkge9Q==", + "node_modules/@img/sharp-freebsd-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.5.tgz", + "integrity": "sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==", + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "dependencies": { + "@img/sharp-wasm32": "0.35.5" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.4.tgz", + "integrity": "sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==", + "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.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.4.tgz", + "integrity": "sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==", "cpu": [ "x64" ], - "dev": true, - "license": "MIT", + "license": "LGPL-3.0-or-later", "optional": true, "os": [ - "freebsd" + "darwin" ], - "engines": { - "node": "^20.19.0 || >=22.12.0" + "funding": { + "url": "https://opencollective.com/libvips" } }, - "node_modules/@rolldown/binding-linux-arm-gnueabihf": { - "version": "1.0.0-rc.12", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.0.0-rc.12.tgz", - "integrity": "sha512-YqWjAgGC/9M1lz3GR1r1rP79nMgo3mQiiA+Hfo+pvKFK1fAJ1bCi0ZQVh8noOqNacuY1qIcfyVfP6HoyBRZ85Q==", + "node_modules/@img/sharp-libvips-linux-arm": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.4.tgz", + "integrity": "sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==", "cpu": [ "arm" ], - "dev": true, - "license": "MIT", + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", "optional": true, "os": [ "linux" ], - "engines": { - "node": "^20.19.0 || >=22.12.0" + "funding": { + "url": "https://opencollective.com/libvips" } }, - "node_modules/@rolldown/binding-linux-arm64-gnu": { - "version": "1.0.0-rc.12", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.0.0-rc.12.tgz", - "integrity": "sha512-/I5AS4cIroLpslsmzXfwbe5OmWvSsrFuEw3mwvbQ1kDxJ822hFHIx+vsN/TAzNVyepI/j/GSzrtCIwQPeKCLIg==", + "node_modules/@img/sharp-libvips-linux-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.4.tgz", + "integrity": "sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==", "cpu": [ "arm64" ], - "dev": true, - "license": "MIT", + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", "optional": true, "os": [ "linux" ], - "engines": { - "node": "^20.19.0 || >=22.12.0" + "funding": { + "url": "https://opencollective.com/libvips" } }, - "node_modules/@rolldown/binding-linux-arm64-musl": { - "version": "1.0.0-rc.12", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.0.0-rc.12.tgz", - "integrity": "sha512-V6/wZztnBqlx5hJQqNWwFdxIKN0m38p8Jas+VoSfgH54HSj9tKTt1dZvG6JRHcjh6D7TvrJPWFGaY9UBVOaWPw==", + "node_modules/@img/sharp-libvips-linux-ppc64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.4.tgz", + "integrity": "sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==", "cpu": [ - "arm64" + "ppc64" ], - "dev": true, - "license": "MIT", + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", "optional": true, "os": [ "linux" ], - "engines": { - "node": "^20.19.0 || >=22.12.0" + "funding": { + "url": "https://opencollective.com/libvips" } }, - "node_modules/@rolldown/binding-linux-ppc64-gnu": { - "version": "1.0.0-rc.12", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.0.0-rc.12.tgz", - "integrity": "sha512-AP3E9BpcUYliZCxa3w5Kwj9OtEVDYK6sVoUzy4vTOJsjPOgdaJZKFmN4oOlX0Wp0RPV2ETfmIra9x1xuayFB7g==", + "node_modules/@img/sharp-libvips-linux-riscv64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.4.tgz", + "integrity": "sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==", "cpu": [ - "ppc64" + "riscv64" ], - "dev": true, - "license": "MIT", + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", "optional": true, "os": [ "linux" ], - "engines": { - "node": "^20.19.0 || >=22.12.0" + "funding": { + "url": "https://opencollective.com/libvips" } }, - "node_modules/@rolldown/binding-linux-s390x-gnu": { - "version": "1.0.0-rc.12", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.0.0-rc.12.tgz", - "integrity": "sha512-nWwpvUSPkoFmZo0kQazZYOrT7J5DGOJ/+QHHzjvNlooDZED8oH82Yg67HvehPPLAg5fUff7TfWFHQS8IV1n3og==", + "node_modules/@img/sharp-libvips-linux-s390x": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.4.tgz", + "integrity": "sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==", "cpu": [ "s390x" ], - "dev": true, - "license": "MIT", + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", "optional": true, "os": [ "linux" ], - "engines": { - "node": "^20.19.0 || >=22.12.0" + "funding": { + "url": "https://opencollective.com/libvips" } }, - "node_modules/@rolldown/binding-linux-x64-gnu": { - "version": "1.0.0-rc.12", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.0.0-rc.12.tgz", - "integrity": "sha512-RNrafz5bcwRy+O9e6P8Z/OCAJW/A+qtBczIqVYwTs14pf4iV1/+eKEjdOUta93q2TsT/FI0XYDP3TCky38LMAg==", + "node_modules/@img/sharp-libvips-linux-x64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.4.tgz", + "integrity": "sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==", "cpu": [ "x64" ], - "dev": true, - "license": "MIT", + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", "optional": true, "os": [ "linux" ], - "engines": { - "node": "^20.19.0 || >=22.12.0" + "funding": { + "url": "https://opencollective.com/libvips" } }, - "node_modules/@rolldown/binding-linux-x64-musl": { - "version": "1.0.0-rc.12", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.0.0-rc.12.tgz", - "integrity": "sha512-Jpw/0iwoKWx3LJ2rc1yjFrj+T7iHZn2JDg1Yny1ma0luviFS4mhAIcd1LFNxK3EYu3DHWCps0ydXQ5i/rrJ2ig==", + "node_modules/@img/sharp-libvips-linuxmusl-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.4.tgz", + "integrity": "sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==", + "cpu": [ + "arm64" + ], + "libc": [ + "musl" + ], + "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.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.4.tgz", + "integrity": "sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==", "cpu": [ "x64" ], - "dev": true, - "license": "MIT", + "libc": [ + "musl" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-linux-arm": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.5.tgz", + "integrity": "sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==", + "cpu": [ + "arm" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", "optional": true, "os": [ "linux" ], "engines": { - "node": "^20.19.0 || >=22.12.0" + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm": "1.3.4" } }, - "node_modules/@rolldown/binding-openharmony-arm64": { - "version": "1.0.0-rc.12", - "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.0.0-rc.12.tgz", - "integrity": "sha512-vRugONE4yMfVn0+7lUKdKvN4D5YusEiPilaoO2sgUWpCvrncvWgPMzK00ZFFJuiPgLwgFNP5eSiUlv2tfc+lpA==", + "node_modules/@img/sharp-linux-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.5.tgz", + "integrity": "sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==", "cpu": [ "arm64" ], - "dev": true, - "license": "MIT", + "libc": [ + "glibc" + ], + "license": "Apache-2.0", "optional": true, "os": [ - "openharmony" + "linux" ], "engines": { - "node": "^20.19.0 || >=22.12.0" + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm64": "1.3.4" } }, - "node_modules/@rolldown/binding-wasm32-wasi": { - "version": "1.0.0-rc.12", - "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.0.0-rc.12.tgz", - "integrity": "sha512-ykGiLr/6kkiHc0XnBfmFJuCjr5ZYKKofkx+chJWDjitX+KsJuAmrzWhwyOMSHzPhzOHOy7u9HlFoa5MoAOJ/Zg==", + "node_modules/@img/sharp-linux-ppc64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.5.tgz", + "integrity": "sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==", "cpu": [ - "wasm32" + "ppc64" ], - "dev": true, - "license": "MIT", + "libc": [ + "glibc" + ], + "license": "Apache-2.0", "optional": true, - "dependencies": { - "@napi-rs/wasm-runtime": "^1.1.1" + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" }, + "optionalDependencies": { + "@img/sharp-libvips-linux-ppc64": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-riscv64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.5.tgz", + "integrity": "sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==", + "cpu": [ + "riscv64" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], "engines": { - "node": ">=14.0.0" + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-riscv64": "1.3.4" } }, - "node_modules/@rolldown/binding-win32-arm64-msvc": { - "version": "1.0.0-rc.12", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.0.0-rc.12.tgz", - "integrity": "sha512-5eOND4duWkwx1AzCxadcOrNeighiLwMInEADT0YM7xeEOOFcovWZCq8dadXgcRHSf3Ulh1kFo/qvzoFiCLOL1Q==", + "node_modules/@img/sharp-linux-s390x": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.5.tgz", + "integrity": "sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==", "cpu": [ - "arm64" + "s390x" ], - "dev": true, - "license": "MIT", + "libc": [ + "glibc" + ], + "license": "Apache-2.0", "optional": true, "os": [ - "win32" + "linux" ], "engines": { - "node": "^20.19.0 || >=22.12.0" + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-s390x": "1.3.4" } }, - "node_modules/@rolldown/binding-win32-x64-msvc": { - "version": "1.0.0-rc.12", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.0.0-rc.12.tgz", - "integrity": "sha512-PyqoipaswDLAZtot351MLhrlrh6lcZPo2LSYE+VDxbVk24LVKAGOuE4hb8xZQmrPAuEtTZW8E6D2zc5EUZX4Lw==", + "node_modules/@img/sharp-linux-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.5.tgz", + "integrity": "sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==", "cpu": [ "x64" ], - "dev": true, - "license": "MIT", + "libc": [ + "glibc" + ], + "license": "Apache-2.0", "optional": true, "os": [ - "win32" + "linux" ], "engines": { - "node": "^20.19.0 || >=22.12.0" + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.3.4" } }, - "node_modules/@rolldown/pluginutils": { - "version": "1.0.0-rc.7", - "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.7.tgz", - "integrity": "sha512-qujRfC8sFVInYSPPMLQByRh7zhwkGFS4+tyMQ83srV1qrxL4g8E2tyxVVyxd0+8QeBM1mIk9KbWxkegRr76XzA==", - "dev": true, - "license": "MIT" + "node_modules/@img/sharp-linuxmusl-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.5.tgz", + "integrity": "sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==", + "cpu": [ + "arm64" + ], + "libc": [ + "musl" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-arm64": "1.3.4" + } }, - "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/@rushstack/eslint-patch": { - "version": "1.16.1", - "resolved": "https://registry.npmjs.org/@rushstack/eslint-patch/-/eslint-patch-1.16.1.tgz", - "integrity": "sha512-TvZbIpeKqGQQ7X0zSCvPH9riMSFQFSggnfBjFZ1mEoILW+UuXCKwOoPcgjMwiUtRqFZ8jWhPJc4um14vC6I4ag==", - "dev": true, - "license": "MIT" - }, - "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==", - "devOptional": true, - "license": "MIT" - }, - "node_modules/@swc/counter": { - "version": "0.1.3", - "resolved": "https://registry.npmjs.org/@swc/counter/-/counter-0.1.3.tgz", - "integrity": "sha512-e2BR4lsJkkRlKZ/qCHPw9ZaSxc0MVUd7gtbtaB7aMvHeJVYe8sOB8DBZkP2DtISHGSku9sCK6T6cnY0CtXrOCQ==", - "license": "Apache-2.0" - }, - "node_modules/@swc/helpers": { - "version": "0.5.5", - "resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.5.tgz", - "integrity": "sha512-KGYxvIOXcceOAbEk4bi/dVLEK9z8sZ0uBB3Il5b1rhfClSpcX0yfRO0KmTkqR2cnQDymwLB+25ZyMzICg/cm/A==", + "node_modules/@img/sharp-linuxmusl-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.5.tgz", + "integrity": "sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==", + "cpu": [ + "x64" + ], + "libc": [ + "musl" + ], "license": "Apache-2.0", - "dependencies": { - "@swc/counter": "^0.1.3", - "tslib": "^2.4.0" + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-x64": "1.3.4" } }, - "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", + "node_modules/@img/sharp-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.5.tgz", + "integrity": "sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==", + "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", "optional": true, "dependencies": { - "tslib": "^2.4.0" + "@emnapi/runtime": "^1.11.3" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" } }, - "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", + "node_modules/@img/sharp-webcontainers-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.5.tgz", + "integrity": "sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==", + "cpu": [ + "wasm32" + ], + "license": "Apache-2.0", + "optional": true, "dependencies": { - "@types/deep-eql": "*", - "assertion-error": "^2.0.1" + "@img/sharp-wasm32": "0.35.5" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" } }, - "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/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": "25.5.0", - "resolved": "https://registry.npmjs.org/@types/node/-/node-25.5.0.tgz", - "integrity": "sha512-jp2P3tQMSxWugkCUKLRPVUpGaL5MVFwF8RDuSRztfwgN1wmqJeMSbKlnEtQqU8UrhTmzEmZdu2I6v2dpp7XIxw==", - "license": "MIT", - "dependencies": { - "undici-types": "~7.18.0" + "node_modules/@img/sharp-win32-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.5.tgz", + "integrity": "sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" } }, - "node_modules/@types/nodemailer": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@types/nodemailer/-/nodemailer-8.0.0.tgz", - "integrity": "sha512-fyf8jWULsCo0d0BuoQ75i6IeoHs47qcqxWc7yUdUcV0pOZGjUTTOvwdG1PRXUDqN/8A64yQdQdnA2pZgcdi+cA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*" + "node_modules/@img/sharp-win32-ia32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.5.tgz", + "integrity": "sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==", + "cpu": [ + "ia32" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" } }, - "node_modules/@types/pg": { - "version": "8.20.0", - "resolved": "https://registry.npmjs.org/@types/pg/-/pg-8.20.0.tgz", - "integrity": "sha512-bEPFOaMAHTEP1EzpvHTbmwR8UsFyHSKsRisLIHVMXnpNefSbGA1bD6CVy+qKjGSqmZqNqBDV2azOBo8TgkcVow==", - "license": "MIT", - "dependencies": { - "@types/node": "*", - "pg-protocol": "*", - "pg-types": "^2.2.0" + "node_modules/@img/sharp-win32-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.5.tgz", + "integrity": "sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" } }, - "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, + "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": { - "csstype": "^3.2.2" + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" } }, - "node_modules/@typescript-eslint/eslint-plugin": { - "version": "8.58.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.58.0.tgz", - "integrity": "sha512-RLkVSiNuUP1C2ROIWfqX+YcUfLaSnxGE/8M+Y57lopVwg9VTYYfhuz15Yf1IzCKgZj6/rIbYTmJCUSqr76r0Wg==", - "dev": true, + "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": { - "@eslint-community/regexpp": "^4.12.2", - "@typescript-eslint/scope-manager": "8.58.0", - "@typescript-eslint/type-utils": "8.58.0", - "@typescript-eslint/utils": "8.58.0", - "@typescript-eslint/visitor-keys": "8.58.0", - "ignore": "^7.0.5", - "natural-compare": "^1.4.0", - "ts-api-utils": "^2.5.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.58.0", - "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", - "typescript": ">=4.8.4 <6.1.0" + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" } }, - "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, + "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": ">= 4" + "node": ">=6.0.0" } }, - "node_modules/@typescript-eslint/parser": { - "version": "8.58.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.58.0.tgz", - "integrity": "sha512-rLoGZIf9afaRBYsPUMtvkDWykwXwUPL60HebR4JgTI8mxfFe2cQTu3AGitANp4b9B2QlVru6WzjgB2IzJKiCSA==", - "dev": true, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "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": { - "@typescript-eslint/scope-manager": "8.58.0", - "@typescript-eslint/types": "8.58.0", - "@typescript-eslint/typescript-estree": "8.58.0", - "@typescript-eslint/visitor-keys": "8.58.0", - "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.1.0" + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" } }, - "node_modules/@typescript-eslint/parser/node_modules/debug": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", - "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", - "dev": true, + "node_modules/@modelcontextprotocol/sdk": { + "version": "1.32.1", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.32.1.tgz", + "integrity": "sha512-2DdE+SJDtzLEEWzY1ZjY7Q+VcPhcV1KisD3zI4u0XZyktsjHum1mwbMI+JaulUBi2OZk+KJAi2uPXzxichPkdw==", "license": "MIT", "dependencies": { - "ms": "^2.1.3" + "@hono/node-server": "^1.19.9 || ^2.0.5", + "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": ">=6.0" + "node": ">=18" + }, + "peerDependencies": { + "@cfworker/json-schema": "^4.1.1", + "zod": "^3.25 || ^4.0" }, "peerDependenciesMeta": { - "supports-color": { + "@cfworker/json-schema": { "optional": true + }, + "zod": { + "optional": false } } }, - "node_modules/@typescript-eslint/project-service": { - "version": "8.58.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.58.0.tgz", - "integrity": "sha512-8Q/wBPWLQP1j16NxoPNIKpDZFMaxl7yWIoqXWYeWO+Bbd2mjgvoF0dxP2jKZg5+x49rgKdf7Ck473M8PC3V9lg==", - "dev": true, + "node_modules/@modelcontextprotocol/sdk/node_modules/jose": { + "version": "6.2.12", + "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.12.tgz", + "integrity": "sha512-9NiFmJEex0sy2Dk58j2UGBSHgUs2ypF9eZSu4L6vjOX3Dp96Sw1F3uL+H+D1sx02jZZdzUT0HgvCy59CuvXcWw==", "license": "MIT", - "dependencies": { - "@typescript-eslint/tsconfig-utils": "^8.58.0", - "@typescript-eslint/types": "^8.58.0", - "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.1.0" + "url": "https://github.com/sponsors/panva" } }, - "node_modules/@typescript-eslint/project-service/node_modules/debug": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", - "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "node_modules/@next/env": { + "version": "16.4.0", + "resolved": "https://registry.npmjs.org/@next/env/-/env-16.4.0.tgz", + "integrity": "sha512-pyLlT5oafGlX8X7xjgGNXz5dNIDSxREm+qD6i9VLSZiZFopA/XWl8NM/KPmLx/8EG/++c49iid3gNWSQW1+2dQ==", + "license": "MIT" + }, + "node_modules/@next/eslint-plugin-next": { + "version": "16.4.0", + "resolved": "https://registry.npmjs.org/@next/eslint-plugin-next/-/eslint-plugin-next-16.4.0.tgz", + "integrity": "sha512-ffeflB/dL8RrvWejQximw01pOpKHN692Y3FjDB82DCd0YVvXvBD6vY7mcZp27yvSVFVM6wA73xVodEKF4spizA==", "dev": true, "license": "MIT", "dependencies": { - "ms": "^2.1.3" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } + "@eslint-community/eslint-utils": "4.9.1", + "fast-glob": "3.3.1" } }, - "node_modules/@typescript-eslint/scope-manager": { - "version": "8.58.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.58.0.tgz", - "integrity": "sha512-W1Lur1oF50FxSnNdGp3Vs6P+yBRSmZiw4IIjEeYxd8UQJwhUF0gDgDD/W/Tgmh73mxgEU3qX0Bzdl/NGuSPEpQ==", - "dev": true, + "node_modules/@next/swc-darwin-arm64": { + "version": "16.4.0", + "resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-16.4.0.tgz", + "integrity": "sha512-yyZ+9MgViAKLLb5l1gPBGjRwnq3teNLb5Zx6JEw8LzNSTjlsnp+baUHFxTgl7PpjCmKf48VQfyipG1eBflb48Q==", + "cpu": [ + "arm64" + ], "license": "MIT", - "dependencies": { - "@typescript-eslint/types": "8.58.0", - "@typescript-eslint/visitor-keys": "8.58.0" - }, + "optional": true, + "os": [ + "darwin" + ], "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" + "node": ">= 10" } }, - "node_modules/@typescript-eslint/tsconfig-utils": { - "version": "8.58.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.58.0.tgz", - "integrity": "sha512-doNSZEVJsWEu4htiVC+PR6NpM+pa+a4ClH9INRWOWCUzMst/VA9c4gXq92F8GUD1rwhNvRLkgjfYtFXegXQF7A==", - "dev": true, + "node_modules/@next/swc-darwin-x64": { + "version": "16.4.0", + "resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-16.4.0.tgz", + "integrity": "sha512-RePEEejEj1Auf5s9qEcG0JbcDP3ceNUS/ofNX8AhxzgIjTVlZIHMatlp16YplcSMpsVo/ZMQHJTjbMYJznjGUg==", + "cpu": [ + "x64" + ], "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], "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.1.0" + "node": ">= 10" } }, - "node_modules/@typescript-eslint/type-utils": { - "version": "8.58.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.58.0.tgz", - "integrity": "sha512-aGsCQImkDIqMyx1u4PrVlbi/krmDsQUs4zAcCV6M7yPcPev+RqVlndsJy9kJ8TLihW9TZ0kbDAzctpLn5o+lOg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typescript-eslint/types": "8.58.0", - "@typescript-eslint/typescript-estree": "8.58.0", - "@typescript-eslint/utils": "8.58.0", - "debug": "^4.4.3", - "ts-api-utils": "^2.5.0" - }, + "node_modules/@next/swc-linux-arm64-gnu": { + "version": "16.4.0", + "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-16.4.0.tgz", + "integrity": "sha512-HhsyCqd+NpmvDDVY/LqkAN24f+QVvXh3ie+PfcwKinWL2Mu826JymQxJXGjAIfmJ4VlHjp4Pe/nZtXtUoEMAqw==", + "cpu": [ + "arm64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], "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.1.0" + "node": ">= 10" } }, - "node_modules/@typescript-eslint/type-utils/node_modules/debug": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", - "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", - "dev": true, + "node_modules/@next/swc-linux-arm64-musl": { + "version": "16.4.0", + "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-16.4.0.tgz", + "integrity": "sha512-sN9Pf+Zh+RpZAOmbR7d8KAA8T61CVhawtbEJ2Bk6QrRzx6Z/6haaF4UiwBzytM96GRRRWZh9/WALIEO3npMamA==", + "cpu": [ + "arm64" + ], + "libc": [ + "musl" + ], "license": "MIT", - "dependencies": { - "ms": "^2.1.3" - }, + "optional": true, + "os": [ + "linux" + ], "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } + "node": ">= 10" } }, - "node_modules/@typescript-eslint/types": { - "version": "8.58.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.58.0.tgz", - "integrity": "sha512-O9CjxypDT89fbHxRfETNoAnHj/i6IpRK0CvbVN3qibxlLdo5p5hcLmUuCCrHMpxiWSwKyI8mCP7qRNYuOJ0Uww==", - "dev": true, + "node_modules/@next/swc-linux-x64-gnu": { + "version": "16.4.0", + "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-16.4.0.tgz", + "integrity": "sha512-D5M5xLWQVd1CvR+L7BickM1weRfmM41x3L1NWcnKY/oyJJqr1qwaCgmu3dMAhLBOMdZwSuDCRV6DJRRpiUkbDQ==", + "cpu": [ + "x64" + ], + "libc": [ + "glibc" + ], "license": "MIT", + "optional": true, + "os": [ + "linux" + ], "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" + "node": ">= 10" } }, - "node_modules/@typescript-eslint/typescript-estree": { - "version": "8.58.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.58.0.tgz", - "integrity": "sha512-7vv5UWbHqew/dvs+D3e1RvLv1v2eeZ9txRHPnEEBUgSNLx5ghdzjHa0sgLWYVKssH+lYmV0JaWdoubo0ncGYLA==", - "dev": true, + "node_modules/@next/swc-linux-x64-musl": { + "version": "16.4.0", + "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-16.4.0.tgz", + "integrity": "sha512-8d5WLS6a9YalqpOgXdlbvonFu+sIgjA+CO6tGzetrpPVcUL56foa7B7664h41rAlbLi5fJwK4vWji3zf4QDy+w==", + "cpu": [ + "x64" + ], + "libc": [ + "musl" + ], "license": "MIT", - "dependencies": { - "@typescript-eslint/project-service": "8.58.0", - "@typescript-eslint/tsconfig-utils": "8.58.0", - "@typescript-eslint/types": "8.58.0", - "@typescript-eslint/visitor-keys": "8.58.0", - "debug": "^4.4.3", - "minimatch": "^10.2.2", - "semver": "^7.7.3", - "tinyglobby": "^0.2.15", - "ts-api-utils": "^2.5.0" - }, + "optional": true, + "os": [ + "linux" + ], "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.1.0" + "node": ">= 10" } }, - "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, + "node_modules/@next/swc-win32-arm64-msvc": { + "version": "16.4.0", + "resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-16.4.0.tgz", + "integrity": "sha512-sQuOIiW3snb48UwrBcDMvFA/u03qtw2LeuSIxFIQ9AJuW9UG/4Ddsfo+eV73PnZwBhyncMtsKVh7PrzMol2/fA==", + "cpu": [ + "arm64" + ], "license": "MIT", + "optional": true, + "os": [ + "win32" + ], "engines": { - "node": "18 || 20 || >=22" + "node": ">= 10" } }, - "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, + "node_modules/@next/swc-win32-x64-msvc": { + "version": "16.4.0", + "resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-16.4.0.tgz", + "integrity": "sha512-6/33lCuxpdHUy27RegyGM/5uTpF7YZd3UR4D0gpkOA/tWY5YR7msbQjqPgCZmSmxrrTLGCXYA4A8vT2H5DPGTQ==", + "cpu": [ + "x64" + ], "license": "MIT", - "dependencies": { - "balanced-match": "^4.0.2" - }, + "optional": true, + "os": [ + "win32" + ], "engines": { - "node": "18 || 20 || >=22" + "node": ">= 10" } }, - "node_modules/@typescript-eslint/typescript-estree/node_modules/debug": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", - "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", - "dev": true, + "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": { - "ms": "^2.1.3" + "@nodelib/fs.stat": "2.0.5", + "run-parallel": "^1.1.9" }, "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } + "node": ">= 8" } }, - "node_modules/@typescript-eslint/typescript-estree/node_modules/minimatch": { - "version": "10.2.5", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz", - "integrity": "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==", - "dev": true, - "license": "BlueOak-1.0.0", + "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": { - "brace-expansion": "^5.0.5" + "@nodelib/fs.scandir": "2.1.5", + "fastq": "^1.6.0" }, "engines": { - "node": "18 || 20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" + "node": ">= 8" } }, - "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==", + "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": "ISC", - "bin": { - "semver": "bin/semver.js" - }, + "license": "MIT", "engines": { - "node": ">=10" + "node": ">=12.4.0" } }, - "node_modules/@typescript-eslint/utils": { - "version": "8.58.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.58.0.tgz", - "integrity": "sha512-RfeSqcFeHMHlAWzt4TBjWOAtoW9lnsAGiP3GbaX9uVgTYYrMbVnGONEfUCiSss+xMHFl+eHZiipmA8WkQ7FuNA==", + "node_modules/@oxc-project/types": { + "version": "0.153.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.153.0.tgz", + "integrity": "sha512-jSNrRIyvPVLL5E1z/tS5zLAprosGz/FuI1PWwEOz59j3E4TTTzSpqKb/RDGqJhhW0QHYISGXxq582wGx6T11Tw==", "dev": true, "license": "MIT", - "dependencies": { - "@eslint-community/eslint-utils": "^4.9.1", - "@typescript-eslint/scope-manager": "8.58.0", - "@typescript-eslint/types": "8.58.0", - "@typescript-eslint/typescript-estree": "8.58.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.1.0" + "url": "https://github.com/sponsors/oxc-project" } }, - "node_modules/@typescript-eslint/visitor-keys": { - "version": "8.58.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.58.0.tgz", - "integrity": "sha512-XJ9UD9+bbDo4a4epraTwG3TsNPeiB9aShrUneAVXy8q4LuwowN+qu89/6ByLMINqvIMeI9H9hOHQtg/ijrYXzQ==", - "dev": true, + "node_modules/@panva/hkdf": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@panva/hkdf/-/hkdf-1.2.1.tgz", + "integrity": "sha512-6oclG6Y3PiDFcoyk8srjLfVKyMfVCKJ27JwNPViuXziFpmdz+MZnZN/aKY0JGXgYuO/VghU0jcOAZgWXZ1Dmrw==", "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, + "node_modules/@playwright/test": { + "version": "1.64.0", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.64.0.tgz", + "integrity": "sha512-oTN9FNYuN6bqQMwiho6jJKLCG2/QOYCixGXuCjRmzOq23eODeukuY2XiAVoVpAECbuezMt1MHQjAiQxK8F+Y+g==", + "devOptional": true, + "license": "Apache-2.0", "dependencies": { - "@typescript-eslint/types": "8.58.0", - "eslint-visitor-keys": "^5.0.0" + "playwright": "1.64.0" }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + "bin": { + "playwright": "cli.js" }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" + "engines": { + "node": ">=20" } }, - "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, + "node_modules/@prisma/adapter-pg": { + "version": "7.10.0", + "resolved": "https://registry.npmjs.org/@prisma/adapter-pg/-/adapter-pg-7.10.0.tgz", + "integrity": "sha512-N7nwSor0HO1Kz6xBv0TPAjAPysKK0fac6p4fVN3ensLOuzc/83Fgmln5k92eK/cvzqdkSR/2kkAqlbcdwVrwpw==", + "license": "Apache-2.0", + "dependencies": { + "@prisma/driver-adapter-utils": "7.10.0", + "@types/pg": "^8.16.0", + "pg": "^8.16.3", + "postgres-array": "3.0.4" + } + }, + "node_modules/@prisma/client": { + "version": "7.10.0", + "resolved": "https://registry.npmjs.org/@prisma/client/-/client-7.10.0.tgz", + "integrity": "sha512-Ubw/QS9JGIBSBUsyxAUQuK/Jcu0Tsva7le7QbLd91Kix9yJvYDdj5QkwgEbbZniH80dd+sziQcALPc+HnvQC8Q==", "license": "Apache-2.0", + "dependencies": { + "@prisma/client-runtime-utils": "7.10.0" + }, "engines": { - "node": "^20.19.0 || ^22.13.0 || >=24" + "node": "^20.19 || ^22.12 || >=24.0" }, - "funding": { - "url": "https://opencollective.com/eslint" + "peerDependencies": { + "prisma": "*", + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "prisma": { + "optional": true + }, + "typescript": { + "optional": true + } } }, - "node_modules/@ungap/structured-clone": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.3.0.tgz", - "integrity": "sha512-WmoN8qaIAo7WTYWbAZuG8PYEhn5fkz7dZrqTBZ7dtt//lL2Gwms1IcnQ5yHqjDfX8Ft5j4YzDM23f87zBfDe9g==", - "dev": true, - "license": "ISC" + "node_modules/@prisma/client-runtime-utils": { + "version": "7.10.0", + "resolved": "https://registry.npmjs.org/@prisma/client-runtime-utils/-/client-runtime-utils-7.10.0.tgz", + "integrity": "sha512-cnCy7lUV8/CctgKVEmqAbSLAmwqJdE/qAlqTBk/0NDk59zEb2cZ0M0M0E4vVPnqbSEYudRroQDvOWfUZH6RIfw==", + "license": "Apache-2.0" }, - "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", + "node_modules/@prisma/config": { + "version": "7.10.0", + "resolved": "https://registry.npmjs.org/@prisma/config/-/config-7.10.0.tgz", + "integrity": "sha512-Rcg828gIRE3HOQ3pOATFjV5d/P0U9OIobxhd/IMxlfWjA4vru0eGwb0AIwFw0rmcLMVShohZYWPixVxkBHsxUA==", + "devOptional": true, + "license": "Apache-2.0", + "dependencies": { + "c12": "3.3.4", + "deepmerge-ts": "7.1.5", + "effect": "3.20.0", + "empathic": "2.0.0" + } + }, + "node_modules/@prisma/debug": { + "version": "7.10.0", + "resolved": "https://registry.npmjs.org/@prisma/debug/-/debug-7.10.0.tgz", + "integrity": "sha512-caygJKtltmRIgdJ3jRpkOr7yM4DW6zxo5uOmojKWFb3asnxWoRkQOwZmXBgD8FZp4htrX+nMpcWqDwzlQ1+Y4g==", + "license": "Apache-2.0" + }, + "node_modules/@prisma/dev": { + "version": "0.24.17", + "resolved": "https://registry.npmjs.org/@prisma/dev/-/dev-0.24.17.tgz", + "integrity": "sha512-UvdZzmpFwknnfreh6Jije84ekkYGPYEJhXG1tFzCsCfQyzJifrOo38eZc0qajzvaC6OLUOrN9ML5XfCnEZL9DA==", + "devOptional": true, + "license": "ISC", + "dependencies": { + "@electric-sql/pglite": "0.4.3", + "@electric-sql/pglite-socket": "0.1.3", + "@electric-sql/pglite-tools": "0.3.3", + "@prisma/get-platform": "7.2.0", + "@prisma/query-plan-executor": "7.2.0", + "@prisma/streams-local": "0.1.11", + "find-my-way": "9.7.0", + "foreground-child": "3.3.1", + "get-port-please": "3.2.0", + "pathe": "2.0.3", + "proper-lockfile": "4.1.2", + "remeda": "2.33.4", + "std-env": "3.10.0", + "valibot": "1.4.2", + "zeptomatch": "2.1.0" + } + }, + "node_modules/@prisma/driver-adapter-utils": { + "version": "7.10.0", + "resolved": "https://registry.npmjs.org/@prisma/driver-adapter-utils/-/driver-adapter-utils-7.10.0.tgz", + "integrity": "sha512-u8zkcRLlaryO652T4qavBg0HmzNW5tSKdsCn6hc1PhWAp/J6k0vrxLuUs+b9o+HcjsK7Dfa01o4OFSn0frauJA==", + "license": "Apache-2.0", + "dependencies": { + "@prisma/debug": "7.10.0" + } + }, + "node_modules/@prisma/engines": { + "version": "7.10.0", + "resolved": "https://registry.npmjs.org/@prisma/engines/-/engines-7.10.0.tgz", + "integrity": "sha512-KNumN6NHFwybvfdYzTee9pqwx5PvknpWAaHn6L5NsbrKdl+SQrsVZs9opKs6U6SAsvB26HDt3WybRjOhgoWOYQ==", + "devOptional": true, + "hasInstallScript": true, + "license": "Apache-2.0", + "dependencies": { + "@prisma/debug": "7.10.0", + "@prisma/engines-version": "7.10.0-4.0edf323efd1d98336f3f0a68684b56f689b900d3", + "@prisma/fetch-engine": "7.10.0", + "@prisma/get-platform": "7.10.0" + } + }, + "node_modules/@prisma/engines-version": { + "version": "7.10.0-4.0edf323efd1d98336f3f0a68684b56f689b900d3", + "resolved": "https://registry.npmjs.org/@prisma/engines-version/-/engines-version-7.10.0-4.0edf323efd1d98336f3f0a68684b56f689b900d3.tgz", + "integrity": "sha512-8OJ6RuZTZ06eFUOtBwxVmv8XMmOW6HWN5F+uxUbZkGxR0Bfab1dfAdXaHPmR5mb59E+fmUo8IOzXlbLY1SClbw==", + "devOptional": true, + "license": "Apache-2.0" + }, + "node_modules/@prisma/engines/node_modules/@prisma/get-platform": { + "version": "7.10.0", + "resolved": "https://registry.npmjs.org/@prisma/get-platform/-/get-platform-7.10.0.tgz", + "integrity": "sha512-0bra1LFYi8xNw0yqV62bHJNQk4BKleOngZiqPWIQc7a3+9q6rqsnqJ15BuepP8943PFMvtmgnP52juZsyYkA6w==", + "devOptional": true, + "license": "Apache-2.0", + "dependencies": { + "@prisma/debug": "7.10.0" + } + }, + "node_modules/@prisma/fetch-engine": { + "version": "7.10.0", + "resolved": "https://registry.npmjs.org/@prisma/fetch-engine/-/fetch-engine-7.10.0.tgz", + "integrity": "sha512-Zqyu8DY14t6W/xwmAxUYWCXtHrvQnSvT644EAZSsdM8NSmCS74vJJbBKdVsK3ucFpnUWkEpbO1a0CxJXrg130g==", + "devOptional": true, + "license": "Apache-2.0", + "dependencies": { + "@prisma/debug": "7.10.0", + "@prisma/engines-version": "7.10.0-4.0edf323efd1d98336f3f0a68684b56f689b900d3", + "@prisma/get-platform": "7.10.0" + } + }, + "node_modules/@prisma/fetch-engine/node_modules/@prisma/get-platform": { + "version": "7.10.0", + "resolved": "https://registry.npmjs.org/@prisma/get-platform/-/get-platform-7.10.0.tgz", + "integrity": "sha512-0bra1LFYi8xNw0yqV62bHJNQk4BKleOngZiqPWIQc7a3+9q6rqsnqJ15BuepP8943PFMvtmgnP52juZsyYkA6w==", + "devOptional": true, + "license": "Apache-2.0", + "dependencies": { + "@prisma/debug": "7.10.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.11", + "resolved": "https://registry.npmjs.org/@prisma/streams-local/-/streams-local-0.1.11.tgz", + "integrity": "sha512-0TcebL559MByKqTJ+SsrFIEg228iw8UCVRFckzgfRSiJqczhs+MuAgWOF9lnOIV/IVqvu+KMnFTH0eDeTQMpUg==", + "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.2.0", + "node": ">=22.0.0" + } + }, + "node_modules/@prisma/studio-core": { + "version": "0.33.0", + "resolved": "https://registry.npmjs.org/@prisma/studio-core/-/studio-core-0.33.0.tgz", + "integrity": "sha512-V2fX/nKEymNTrHXwfP26PGjoLStO35Ogu+ex7CFJbLrMYEcZxxZpiSNOs7px23Hk5mzLWvM5RsqG6Ka+rha+wg==", + "devOptional": true, + "license": "Apache-2.0", + "dependencies": { + "@radix-ui/react-toggle": "1.1.10", + "@visx/curve": "4.0.1-alpha.0", + "@visx/event": "4.0.1-alpha.0", + "@visx/grid": "4.0.1-alpha.0", + "@visx/group": "4.0.1-alpha.0", + "@visx/responsive": "4.0.1-alpha.0", + "@visx/scale": "4.0.1-alpha.0", + "@visx/shape": "4.0.1-alpha.0", + "d3-array": "3.2.4", + "d3-shape": "3.2.0", + "elkjs": "0.11.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/number": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/@radix-ui/number/-/number-1.1.3.tgz", + "integrity": "sha512-Road2bidD0uu/1BGDOWNdPI06g0lIRy6IF9GZcIrDK2KGItfor8IQwQa+yM2ERgHM1MmHxaxpTzk0/Jp42lNfA==", + "license": "MIT" + }, + "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-accessible-icon": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-accessible-icon/-/react-accessible-icon-1.2.0.tgz", + "integrity": "sha512-BB4+HHkFl3HipEAhm/mLhrpXV+2kRX7MvY4AaImUcQVeWQt5KhV1JEByNs8NGfJOcr95RcQGijt9+OrCo68xGA==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-visually-hidden": "1.2.13" + }, + "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-accordion": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-accordion/-/react-accordion-1.3.0.tgz", + "integrity": "sha512-fXMUup+0dkQwonCCriE5ITI8uPxAJCrfWB/oBDtSF2zKMAEgbkmWi4LixKddsyfhH+x8TlJQxmu3Sf4HLJnHag==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-collapsible": "1.2.0", + "@radix-ui/react-collection": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-direction": "1.2.0", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-controllable-state": "1.3.0" + }, + "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-accordion/node_modules/@radix-ui/primitive": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.2.0.tgz", + "integrity": "sha512-KABY+VMIRPJL+Vyzv/335FEhXXD/xDv8BMb1kl48/aXJZMH0LtHCTx5ga5RnxaEP3nZHtmTLf1P9vanmFX46bw==", + "license": "MIT" + }, + "node_modules/@radix-ui/react-accordion/node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.5.tgz", + "integrity": "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==", + "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-accordion/node_modules/@radix-ui/react-primitive": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.2.0.tgz", + "integrity": "sha512-HCTSPMNqv55Qk0IX4geJbpyXazmqulcimwuyjxTkKi29v+QZbG2Zho9BnbBq4YS2PF+KlNb2CXoLz66uUmblkg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.5.0" + }, + "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-accordion/node_modules/@radix-ui/react-slot": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.5.0.tgz", + "integrity": "sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5" + }, + "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-accordion/node_modules/@radix-ui/react-use-controllable-state": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-controllable-state/-/react-use-controllable-state-1.3.0.tgz", + "integrity": "sha512-TAcBI7bw2ljYCbv4+zuTSd6zICu8pRt6SDN2vJ/Z06K2MXh6I9WYFe/A9ovlFDtR5HVHGm5iDxDoABm/++dbKg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-use-effect-event": "0.0.5", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-accordion/node_modules/@radix-ui/react-use-effect-event": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-effect-event/-/react-use-effect-event-0.0.5.tgz", + "integrity": "sha512-7cshFL8HGS/7HEiHH+9kL9HBwp2sa9yX18Knwek6KYWmXwM7pegMgta2AXMQKI+rq3JnfSj9x8wYqFMTdG1Jgg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-accordion/node_modules/@radix-ui/react-use-layout-effect": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.4.tgz", + "integrity": "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw==", + "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-alert-dialog": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-alert-dialog/-/react-alert-dialog-1.2.0.tgz", + "integrity": "sha512-f6ozGN4sF5KEA/d/CAWnwLWyqS4ZsZ6GdhQN68U1BqbRnfQUzkjxjcU+Rq6vFq9FPpfkIKXE7LOyfEdxorirfw==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-dialog": "1.3.0", + "@radix-ui/react-primitive": "2.2.0" + }, + "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-alert-dialog/node_modules/@radix-ui/primitive": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.2.0.tgz", + "integrity": "sha512-KABY+VMIRPJL+Vyzv/335FEhXXD/xDv8BMb1kl48/aXJZMH0LtHCTx5ga5RnxaEP3nZHtmTLf1P9vanmFX46bw==", + "license": "MIT" + }, + "node_modules/@radix-ui/react-alert-dialog/node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.5.tgz", + "integrity": "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==", + "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-alert-dialog/node_modules/@radix-ui/react-primitive": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.2.0.tgz", + "integrity": "sha512-HCTSPMNqv55Qk0IX4geJbpyXazmqulcimwuyjxTkKi29v+QZbG2Zho9BnbBq4YS2PF+KlNb2CXoLz66uUmblkg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.5.0" + }, + "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-alert-dialog/node_modules/@radix-ui/react-slot": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.5.0.tgz", + "integrity": "sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5" + }, + "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-arrow": { + "version": "1.1.17", + "resolved": "https://registry.npmjs.org/@radix-ui/react-arrow/-/react-arrow-1.1.17.tgz", + "integrity": "sha512-67jjcVvxjXCCStnTW3Z+M7jmaFMuMR7M2JgpDzH4w7JSRrikmzhjfYgP/09ECb8n7whnsgh1ifJ+Ie96qEj+pQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-primitive": "2.2.0" + }, + "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-arrow/node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.5.tgz", + "integrity": "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==", + "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-arrow/node_modules/@radix-ui/react-primitive": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.2.0.tgz", + "integrity": "sha512-HCTSPMNqv55Qk0IX4geJbpyXazmqulcimwuyjxTkKi29v+QZbG2Zho9BnbBq4YS2PF+KlNb2CXoLz66uUmblkg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.5.0" + }, + "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-arrow/node_modules/@radix-ui/react-slot": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.5.0.tgz", + "integrity": "sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5" + }, + "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-aspect-ratio": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-aspect-ratio/-/react-aspect-ratio-1.2.0.tgz", + "integrity": "sha512-gHEU+Lx8DlT/FYIjZQvvBJrFSwUngXTjh7FeL9QvJaNALDLez6pgDj2axCUihBjtPBy82LN0gNb25+sTcSXNmA==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-primitive": "2.2.0" + }, + "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-aspect-ratio/node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.5.tgz", + "integrity": "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==", + "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-aspect-ratio/node_modules/@radix-ui/react-primitive": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.2.0.tgz", + "integrity": "sha512-HCTSPMNqv55Qk0IX4geJbpyXazmqulcimwuyjxTkKi29v+QZbG2Zho9BnbBq4YS2PF+KlNb2CXoLz66uUmblkg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.5.0" + }, + "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-aspect-ratio/node_modules/@radix-ui/react-slot": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.5.0.tgz", + "integrity": "sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5" + }, + "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-avatar": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-avatar/-/react-avatar-1.3.0.tgz", + "integrity": "sha512-+5qkmjyTW6z49NRiheyVGK8QVcGKBc0puL/B3+vW/LKy1UDESw2Dhw+pd33KA8KTinw9k1l3Oz8flNjBRa3CpQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-callback-ref": "1.1.5", + "@radix-ui/react-use-is-hydrated": "0.1.3", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-avatar/node_modules/@radix-ui/primitive": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.2.0.tgz", + "integrity": "sha512-KABY+VMIRPJL+Vyzv/335FEhXXD/xDv8BMb1kl48/aXJZMH0LtHCTx5ga5RnxaEP3nZHtmTLf1P9vanmFX46bw==", + "license": "MIT" + }, + "node_modules/@radix-ui/react-avatar/node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.5.tgz", + "integrity": "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==", + "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-avatar/node_modules/@radix-ui/react-primitive": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.2.0.tgz", + "integrity": "sha512-HCTSPMNqv55Qk0IX4geJbpyXazmqulcimwuyjxTkKi29v+QZbG2Zho9BnbBq4YS2PF+KlNb2CXoLz66uUmblkg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.5.0" + }, + "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-avatar/node_modules/@radix-ui/react-slot": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.5.0.tgz", + "integrity": "sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5" + }, + "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-avatar/node_modules/@radix-ui/react-use-layout-effect": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.4.tgz", + "integrity": "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw==", + "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-checkbox": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-checkbox/-/react-checkbox-1.4.0.tgz", + "integrity": "sha512-SPKgf33lCk/ijvaat+S1ejZw+r9+s/BvhHLRMrKA0u/A3LNvTVFA+ftPNyNMdLEbxPp4k+wb6VZQLZmb8BXd1g==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-size": "1.1.5" + }, + "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-checkbox/node_modules/@radix-ui/primitive": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.2.0.tgz", + "integrity": "sha512-KABY+VMIRPJL+Vyzv/335FEhXXD/xDv8BMb1kl48/aXJZMH0LtHCTx5ga5RnxaEP3nZHtmTLf1P9vanmFX46bw==", + "license": "MIT" + }, + "node_modules/@radix-ui/react-checkbox/node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.5.tgz", + "integrity": "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==", + "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-checkbox/node_modules/@radix-ui/react-primitive": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.2.0.tgz", + "integrity": "sha512-HCTSPMNqv55Qk0IX4geJbpyXazmqulcimwuyjxTkKi29v+QZbG2Zho9BnbBq4YS2PF+KlNb2CXoLz66uUmblkg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.5.0" + }, + "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-checkbox/node_modules/@radix-ui/react-slot": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.5.0.tgz", + "integrity": "sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5" + }, + "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-checkbox/node_modules/@radix-ui/react-use-controllable-state": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-controllable-state/-/react-use-controllable-state-1.3.0.tgz", + "integrity": "sha512-TAcBI7bw2ljYCbv4+zuTSd6zICu8pRt6SDN2vJ/Z06K2MXh6I9WYFe/A9ovlFDtR5HVHGm5iDxDoABm/++dbKg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-use-effect-event": "0.0.5", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-checkbox/node_modules/@radix-ui/react-use-effect-event": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-effect-event/-/react-use-effect-event-0.0.5.tgz", + "integrity": "sha512-7cshFL8HGS/7HEiHH+9kL9HBwp2sa9yX18Knwek6KYWmXwM7pegMgta2AXMQKI+rq3JnfSj9x8wYqFMTdG1Jgg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-checkbox/node_modules/@radix-ui/react-use-layout-effect": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.4.tgz", + "integrity": "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw==", + "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-collapsible": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-collapsible/-/react-collapsible-1.2.0.tgz", + "integrity": "sha512-AHwGMRBV44I3z+5G/+uRNr/RedPKxzxvbynSfrjoE7xY/lK4Rk980MC/YAPiBJHO0+URFnfOvVZwtYPPRsH5tA==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-collapsible/node_modules/@radix-ui/primitive": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.2.0.tgz", + "integrity": "sha512-KABY+VMIRPJL+Vyzv/335FEhXXD/xDv8BMb1kl48/aXJZMH0LtHCTx5ga5RnxaEP3nZHtmTLf1P9vanmFX46bw==", + "license": "MIT" + }, + "node_modules/@radix-ui/react-collapsible/node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.5.tgz", + "integrity": "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==", + "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-collapsible/node_modules/@radix-ui/react-primitive": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.2.0.tgz", + "integrity": "sha512-HCTSPMNqv55Qk0IX4geJbpyXazmqulcimwuyjxTkKi29v+QZbG2Zho9BnbBq4YS2PF+KlNb2CXoLz66uUmblkg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.5.0" + }, + "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-collapsible/node_modules/@radix-ui/react-slot": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.5.0.tgz", + "integrity": "sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5" + }, + "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-collapsible/node_modules/@radix-ui/react-use-controllable-state": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-controllable-state/-/react-use-controllable-state-1.3.0.tgz", + "integrity": "sha512-TAcBI7bw2ljYCbv4+zuTSd6zICu8pRt6SDN2vJ/Z06K2MXh6I9WYFe/A9ovlFDtR5HVHGm5iDxDoABm/++dbKg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-use-effect-event": "0.0.5", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-collapsible/node_modules/@radix-ui/react-use-effect-event": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-effect-event/-/react-use-effect-event-0.0.5.tgz", + "integrity": "sha512-7cshFL8HGS/7HEiHH+9kL9HBwp2sa9yX18Knwek6KYWmXwM7pegMgta2AXMQKI+rq3JnfSj9x8wYqFMTdG1Jgg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-collapsible/node_modules/@radix-ui/react-use-layout-effect": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.4.tgz", + "integrity": "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw==", + "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-collection": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-collection/-/react-collection-1.2.0.tgz", + "integrity": "sha512-+yiQzqcc7Sy7/5s0jrMCjpPRFB3538VNrXPWdTLZhE/SCfgEws4aI6lHWN/vvcnyhHndROWBzqmqB4QBrITZ9Q==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-slot": "1.5.0", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-collection/node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.5.tgz", + "integrity": "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==", + "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-collection/node_modules/@radix-ui/react-primitive": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.2.0.tgz", + "integrity": "sha512-HCTSPMNqv55Qk0IX4geJbpyXazmqulcimwuyjxTkKi29v+QZbG2Zho9BnbBq4YS2PF+KlNb2CXoLz66uUmblkg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.5.0" + }, + "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-collection/node_modules/@radix-ui/react-slot": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.5.0.tgz", + "integrity": "sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5" + }, + "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-collection/node_modules/@radix-ui/react-use-layout-effect": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.4.tgz", + "integrity": "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw==", + "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-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==", + "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-context": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-context/-/react-context-1.3.0.tgz", + "integrity": "sha512-v5AYEocMISkbJ+1fTXzZpiFv7NRr3D2WiYbLIKf+FkmJ8VkP6d503eV2n34MFussHXY1pcoq3yfJiQH77dc4Mg==", + "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-context-menu": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-context-menu/-/react-context-menu-2.4.0.tgz", + "integrity": "sha512-sJ+Bjq0KPMJUDyu7NuCq7oKm6xRLxTiw1ZWfK7OS4Tj6924nx4XtDMAlN2R99DdgjU/T4rJk9KO9QLZmHVwQMQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-menu": "2.2.0", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-controllable-state": "1.3.0" + }, + "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-context-menu/node_modules/@radix-ui/primitive": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.2.0.tgz", + "integrity": "sha512-KABY+VMIRPJL+Vyzv/335FEhXXD/xDv8BMb1kl48/aXJZMH0LtHCTx5ga5RnxaEP3nZHtmTLf1P9vanmFX46bw==", + "license": "MIT" + }, + "node_modules/@radix-ui/react-context-menu/node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.5.tgz", + "integrity": "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==", + "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-context-menu/node_modules/@radix-ui/react-primitive": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.2.0.tgz", + "integrity": "sha512-HCTSPMNqv55Qk0IX4geJbpyXazmqulcimwuyjxTkKi29v+QZbG2Zho9BnbBq4YS2PF+KlNb2CXoLz66uUmblkg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.5.0" + }, + "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-context-menu/node_modules/@radix-ui/react-slot": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.5.0.tgz", + "integrity": "sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5" + }, + "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-context-menu/node_modules/@radix-ui/react-use-controllable-state": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-controllable-state/-/react-use-controllable-state-1.3.0.tgz", + "integrity": "sha512-TAcBI7bw2ljYCbv4+zuTSd6zICu8pRt6SDN2vJ/Z06K2MXh6I9WYFe/A9ovlFDtR5HVHGm5iDxDoABm/++dbKg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-use-effect-event": "0.0.5", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-context-menu/node_modules/@radix-ui/react-use-effect-event": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-effect-event/-/react-use-effect-event-0.0.5.tgz", + "integrity": "sha512-7cshFL8HGS/7HEiHH+9kL9HBwp2sa9yX18Knwek6KYWmXwM7pegMgta2AXMQKI+rq3JnfSj9x8wYqFMTdG1Jgg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-context-menu/node_modules/@radix-ui/react-use-layout-effect": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.4.tgz", + "integrity": "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw==", + "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-dialog": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-dialog/-/react-dialog-1.3.0.tgz", + "integrity": "sha512-bQUKIf2+/vGpJFCmX2pkxnQVT2Od3gkGGURs+bWCIdQ5JbzyTsItcDL25Y5nlwn2T+m/6utZJL+sEs9g7NfR/Q==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-dismissable-layer": "1.2.0", + "@radix-ui/react-focus-guards": "1.2.0", + "@radix-ui/react-focus-scope": "1.3.0", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-portal": "1.2.0", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-slot": "1.5.0", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-layout-effect": "1.1.4", + "aria-hidden": "^1.2.4", + "react-remove-scroll": "^2.7.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-dialog/node_modules/@radix-ui/primitive": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.2.0.tgz", + "integrity": "sha512-KABY+VMIRPJL+Vyzv/335FEhXXD/xDv8BMb1kl48/aXJZMH0LtHCTx5ga5RnxaEP3nZHtmTLf1P9vanmFX46bw==", + "license": "MIT" + }, + "node_modules/@radix-ui/react-dialog/node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.5.tgz", + "integrity": "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==", + "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-dialog/node_modules/@radix-ui/react-primitive": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.2.0.tgz", + "integrity": "sha512-HCTSPMNqv55Qk0IX4geJbpyXazmqulcimwuyjxTkKi29v+QZbG2Zho9BnbBq4YS2PF+KlNb2CXoLz66uUmblkg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.5.0" + }, + "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-dialog/node_modules/@radix-ui/react-slot": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.5.0.tgz", + "integrity": "sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5" + }, + "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-dialog/node_modules/@radix-ui/react-use-controllable-state": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-controllable-state/-/react-use-controllable-state-1.3.0.tgz", + "integrity": "sha512-TAcBI7bw2ljYCbv4+zuTSd6zICu8pRt6SDN2vJ/Z06K2MXh6I9WYFe/A9ovlFDtR5HVHGm5iDxDoABm/++dbKg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-use-effect-event": "0.0.5", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-dialog/node_modules/@radix-ui/react-use-effect-event": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-effect-event/-/react-use-effect-event-0.0.5.tgz", + "integrity": "sha512-7cshFL8HGS/7HEiHH+9kL9HBwp2sa9yX18Knwek6KYWmXwM7pegMgta2AXMQKI+rq3JnfSj9x8wYqFMTdG1Jgg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-dialog/node_modules/@radix-ui/react-use-layout-effect": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.4.tgz", + "integrity": "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw==", + "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-direction": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-direction/-/react-direction-1.2.0.tgz", + "integrity": "sha512-FtRA52a/r+LKStFT+neLUm+8vSe7wbzkbQGGeU8ixFiwC8NU14Evoq9ATECqL3eGbcUzJR4fyfA4KkK/q6dfqg==", + "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-dismissable-layer": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-dismissable-layer/-/react-dismissable-layer-1.2.0.tgz", + "integrity": "sha512-oO7RhkUS9cwOjK4DGOWU19g9mk1h9h0ErEcNlVg832rgpBq8PGtQn7xyUJnuIO6EEhw6AbXx6/CGfqNEG0LW0Q==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-callback-ref": "1.1.5", + "@radix-ui/react-use-effect-event": "0.0.5" + }, + "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-dismissable-layer/node_modules/@radix-ui/primitive": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.2.0.tgz", + "integrity": "sha512-KABY+VMIRPJL+Vyzv/335FEhXXD/xDv8BMb1kl48/aXJZMH0LtHCTx5ga5RnxaEP3nZHtmTLf1P9vanmFX46bw==", + "license": "MIT" + }, + "node_modules/@radix-ui/react-dismissable-layer/node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.5.tgz", + "integrity": "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==", + "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-dismissable-layer/node_modules/@radix-ui/react-primitive": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.2.0.tgz", + "integrity": "sha512-HCTSPMNqv55Qk0IX4geJbpyXazmqulcimwuyjxTkKi29v+QZbG2Zho9BnbBq4YS2PF+KlNb2CXoLz66uUmblkg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.5.0" + }, + "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-dismissable-layer/node_modules/@radix-ui/react-slot": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.5.0.tgz", + "integrity": "sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5" + }, + "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-dismissable-layer/node_modules/@radix-ui/react-use-effect-event": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-effect-event/-/react-use-effect-event-0.0.5.tgz", + "integrity": "sha512-7cshFL8HGS/7HEiHH+9kL9HBwp2sa9yX18Knwek6KYWmXwM7pegMgta2AXMQKI+rq3JnfSj9x8wYqFMTdG1Jgg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-dismissable-layer/node_modules/@radix-ui/react-use-layout-effect": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.4.tgz", + "integrity": "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw==", + "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-dropdown-menu": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-dropdown-menu/-/react-dropdown-menu-2.2.0.tgz", + "integrity": "sha512-9xH3a5pEetuwmAWTRYlHfUmeDAD4MgBHm6JnD7cUqeGwnGi05CwTyfMCPi4VAtzz0IFxmpHGIg1/WVcjspLYiw==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-menu": "2.2.0", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-controllable-state": "1.3.0" + }, + "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-dropdown-menu/node_modules/@radix-ui/primitive": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.2.0.tgz", + "integrity": "sha512-KABY+VMIRPJL+Vyzv/335FEhXXD/xDv8BMb1kl48/aXJZMH0LtHCTx5ga5RnxaEP3nZHtmTLf1P9vanmFX46bw==", + "license": "MIT" + }, + "node_modules/@radix-ui/react-dropdown-menu/node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.5.tgz", + "integrity": "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==", + "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-dropdown-menu/node_modules/@radix-ui/react-primitive": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.2.0.tgz", + "integrity": "sha512-HCTSPMNqv55Qk0IX4geJbpyXazmqulcimwuyjxTkKi29v+QZbG2Zho9BnbBq4YS2PF+KlNb2CXoLz66uUmblkg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.5.0" + }, + "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-dropdown-menu/node_modules/@radix-ui/react-slot": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.5.0.tgz", + "integrity": "sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5" + }, + "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-dropdown-menu/node_modules/@radix-ui/react-use-controllable-state": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-controllable-state/-/react-use-controllable-state-1.3.0.tgz", + "integrity": "sha512-TAcBI7bw2ljYCbv4+zuTSd6zICu8pRt6SDN2vJ/Z06K2MXh6I9WYFe/A9ovlFDtR5HVHGm5iDxDoABm/++dbKg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-use-effect-event": "0.0.5", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-dropdown-menu/node_modules/@radix-ui/react-use-effect-event": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-effect-event/-/react-use-effect-event-0.0.5.tgz", + "integrity": "sha512-7cshFL8HGS/7HEiHH+9kL9HBwp2sa9yX18Knwek6KYWmXwM7pegMgta2AXMQKI+rq3JnfSj9x8wYqFMTdG1Jgg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-dropdown-menu/node_modules/@radix-ui/react-use-layout-effect": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.4.tgz", + "integrity": "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw==", + "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-focus-guards": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-focus-guards/-/react-focus-guards-1.2.0.tgz", + "integrity": "sha512-MPm5R0iRGUDrDnPNxmLBkv+X7pN4XKzt+MbWJEuJQsH3NFH4omrbpXpucyYCCKTSt+na/ZxGhEWQrWTZ0285cA==", + "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-focus-scope": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-focus-scope/-/react-focus-scope-1.3.0.tgz", + "integrity": "sha512-kWTz59QlCFoE5Q05juX/HljYia4IaKAj5Hdx+WWgEznSVUzw4qZrpRFmV6xvqd9xhqWAFVJ4zQI/Gr/QDblc7w==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-callback-ref": "1.1.5" + }, + "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-focus-scope/node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.5.tgz", + "integrity": "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==", + "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-focus-scope/node_modules/@radix-ui/react-primitive": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.2.0.tgz", + "integrity": "sha512-HCTSPMNqv55Qk0IX4geJbpyXazmqulcimwuyjxTkKi29v+QZbG2Zho9BnbBq4YS2PF+KlNb2CXoLz66uUmblkg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.5.0" + }, + "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-focus-scope/node_modules/@radix-ui/react-slot": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.5.0.tgz", + "integrity": "sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5" + }, + "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-form": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-form/-/react-form-0.3.0.tgz", + "integrity": "sha512-KnmrCM27m7Jo1R8S6cFDPrEeq20Jfn5dqde0SZrJr2lVXlj6/QZSUCyFoYh1d8ti0uUrMNK5Lx6dUDuINT+f4Q==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-label": "2.1.17", + "@radix-ui/react-primitive": "2.2.0" + }, + "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-form/node_modules/@radix-ui/primitive": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.2.0.tgz", + "integrity": "sha512-KABY+VMIRPJL+Vyzv/335FEhXXD/xDv8BMb1kl48/aXJZMH0LtHCTx5ga5RnxaEP3nZHtmTLf1P9vanmFX46bw==", + "license": "MIT" + }, + "node_modules/@radix-ui/react-form/node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.5.tgz", + "integrity": "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==", + "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-form/node_modules/@radix-ui/react-primitive": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.2.0.tgz", + "integrity": "sha512-HCTSPMNqv55Qk0IX4geJbpyXazmqulcimwuyjxTkKi29v+QZbG2Zho9BnbBq4YS2PF+KlNb2CXoLz66uUmblkg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.5.0" + }, + "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-form/node_modules/@radix-ui/react-slot": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.5.0.tgz", + "integrity": "sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5" + }, + "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-hover-card": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-hover-card/-/react-hover-card-1.2.0.tgz", + "integrity": "sha512-MBsj35v9BJsLLmK2NjkYygpgi+D3lzeL3Ab9LQVSfu2R37wzSGwar3liRnsewSv8Pm36BTCGjmcrpMWscRuO9Q==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-dismissable-layer": "1.2.0", + "@radix-ui/react-focus-scope": "1.3.0", + "@radix-ui/react-popper": "1.4.0", + "@radix-ui/react-portal": "1.2.0", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-controllable-state": "1.3.0" + }, + "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-hover-card/node_modules/@radix-ui/primitive": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.2.0.tgz", + "integrity": "sha512-KABY+VMIRPJL+Vyzv/335FEhXXD/xDv8BMb1kl48/aXJZMH0LtHCTx5ga5RnxaEP3nZHtmTLf1P9vanmFX46bw==", + "license": "MIT" + }, + "node_modules/@radix-ui/react-hover-card/node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.5.tgz", + "integrity": "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==", + "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-hover-card/node_modules/@radix-ui/react-primitive": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.2.0.tgz", + "integrity": "sha512-HCTSPMNqv55Qk0IX4geJbpyXazmqulcimwuyjxTkKi29v+QZbG2Zho9BnbBq4YS2PF+KlNb2CXoLz66uUmblkg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.5.0" + }, + "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-hover-card/node_modules/@radix-ui/react-slot": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.5.0.tgz", + "integrity": "sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5" + }, + "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-hover-card/node_modules/@radix-ui/react-use-controllable-state": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-controllable-state/-/react-use-controllable-state-1.3.0.tgz", + "integrity": "sha512-TAcBI7bw2ljYCbv4+zuTSd6zICu8pRt6SDN2vJ/Z06K2MXh6I9WYFe/A9ovlFDtR5HVHGm5iDxDoABm/++dbKg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-use-effect-event": "0.0.5", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-hover-card/node_modules/@radix-ui/react-use-effect-event": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-effect-event/-/react-use-effect-event-0.0.5.tgz", + "integrity": "sha512-7cshFL8HGS/7HEiHH+9kL9HBwp2sa9yX18Knwek6KYWmXwM7pegMgta2AXMQKI+rq3JnfSj9x8wYqFMTdG1Jgg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-hover-card/node_modules/@radix-ui/react-use-layout-effect": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.4.tgz", + "integrity": "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw==", + "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-id": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-id/-/react-id-1.1.4.tgz", + "integrity": "sha512-TMQp2llA+RYn7JcjnrMnz7wN4pcVttPZnRZo52PLQsoLVKzNlVwUeHmfePgTgRluXFvlD3GD5g5MOVVTJCO0qA==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-id/node_modules/@radix-ui/react-use-layout-effect": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.4.tgz", + "integrity": "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw==", + "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-label": { + "version": "2.1.17", + "resolved": "https://registry.npmjs.org/@radix-ui/react-label/-/react-label-2.1.17.tgz", + "integrity": "sha512-xmj7MN/drx1oUAXkfiFIvyDmGNUIN/omGobvA5oAoNqu9zO2MkISYGZOkBcqSzs/UZXXwV+/3ACRE7q7mGcmkA==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-primitive": "2.2.0" + }, + "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-label/node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.5.tgz", + "integrity": "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==", + "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-label/node_modules/@radix-ui/react-primitive": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.2.0.tgz", + "integrity": "sha512-HCTSPMNqv55Qk0IX4geJbpyXazmqulcimwuyjxTkKi29v+QZbG2Zho9BnbBq4YS2PF+KlNb2CXoLz66uUmblkg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.5.0" + }, + "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-label/node_modules/@radix-ui/react-slot": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.5.0.tgz", + "integrity": "sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5" + }, + "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-menu": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-menu/-/react-menu-2.2.0.tgz", + "integrity": "sha512-I+EEFgEiyUq7krju8Nr8vzSXV/2yAbqBX2Xhz6ypTklz8CzqkGiOUfnnAoslGOsc++nx3Ym6qYRCpgqj6O3SjQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-collection": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-direction": "1.2.0", + "@radix-ui/react-dismissable-layer": "1.2.0", + "@radix-ui/react-focus-guards": "1.2.0", + "@radix-ui/react-focus-scope": "1.3.0", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-popper": "1.4.0", + "@radix-ui/react-portal": "1.2.0", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-roving-focus": "1.2.0", + "@radix-ui/react-slot": "1.5.0", + "@radix-ui/react-use-callback-ref": "1.1.5", + "aria-hidden": "^1.2.4", + "react-remove-scroll": "^2.7.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-menu/node_modules/@radix-ui/primitive": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.2.0.tgz", + "integrity": "sha512-KABY+VMIRPJL+Vyzv/335FEhXXD/xDv8BMb1kl48/aXJZMH0LtHCTx5ga5RnxaEP3nZHtmTLf1P9vanmFX46bw==", + "license": "MIT" + }, + "node_modules/@radix-ui/react-menu/node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.5.tgz", + "integrity": "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==", + "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-menu/node_modules/@radix-ui/react-primitive": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.2.0.tgz", + "integrity": "sha512-HCTSPMNqv55Qk0IX4geJbpyXazmqulcimwuyjxTkKi29v+QZbG2Zho9BnbBq4YS2PF+KlNb2CXoLz66uUmblkg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.5.0" + }, + "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-menu/node_modules/@radix-ui/react-slot": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.5.0.tgz", + "integrity": "sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5" + }, + "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-menubar": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-menubar/-/react-menubar-1.2.0.tgz", + "integrity": "sha512-LvIrB6oqt3hMPI/TS7y9uBsKZnF1YTlVIadSC96DeYpEpp86uX3CjjEe8UjtG2YgJEVRcr+YoH3VEjoqnQ+IyQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-collection": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-direction": "1.2.0", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-menu": "2.2.0", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-roving-focus": "1.2.0", + "@radix-ui/react-use-controllable-state": "1.3.0" + }, + "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-menubar/node_modules/@radix-ui/primitive": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.2.0.tgz", + "integrity": "sha512-KABY+VMIRPJL+Vyzv/335FEhXXD/xDv8BMb1kl48/aXJZMH0LtHCTx5ga5RnxaEP3nZHtmTLf1P9vanmFX46bw==", + "license": "MIT" + }, + "node_modules/@radix-ui/react-menubar/node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.5.tgz", + "integrity": "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==", + "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-menubar/node_modules/@radix-ui/react-primitive": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.2.0.tgz", + "integrity": "sha512-HCTSPMNqv55Qk0IX4geJbpyXazmqulcimwuyjxTkKi29v+QZbG2Zho9BnbBq4YS2PF+KlNb2CXoLz66uUmblkg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.5.0" + }, + "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-menubar/node_modules/@radix-ui/react-slot": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.5.0.tgz", + "integrity": "sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5" + }, + "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-menubar/node_modules/@radix-ui/react-use-controllable-state": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-controllable-state/-/react-use-controllable-state-1.3.0.tgz", + "integrity": "sha512-TAcBI7bw2ljYCbv4+zuTSd6zICu8pRt6SDN2vJ/Z06K2MXh6I9WYFe/A9ovlFDtR5HVHGm5iDxDoABm/++dbKg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-use-effect-event": "0.0.5", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-menubar/node_modules/@radix-ui/react-use-effect-event": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-effect-event/-/react-use-effect-event-0.0.5.tgz", + "integrity": "sha512-7cshFL8HGS/7HEiHH+9kL9HBwp2sa9yX18Knwek6KYWmXwM7pegMgta2AXMQKI+rq3JnfSj9x8wYqFMTdG1Jgg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-menubar/node_modules/@radix-ui/react-use-layout-effect": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.4.tgz", + "integrity": "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw==", + "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-navigation-menu": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-navigation-menu/-/react-navigation-menu-1.4.0.tgz", + "integrity": "sha512-V8Q+n6681BrtUVuaWY0hHSbW2welxbrcMK++9pGyqNSHAgQwgCK+nbpwOhrZal7yyIWcRZcnz/1YFc7ck3Ma4w==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-collection": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-direction": "1.2.0", + "@radix-ui/react-dismissable-layer": "1.2.0", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-slot": "1.5.0", + "@radix-ui/react-use-callback-ref": "1.1.5", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-layout-effect": "1.1.4", + "@radix-ui/react-use-previous": "1.1.4", + "@radix-ui/react-visually-hidden": "1.2.13" + }, + "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-navigation-menu/node_modules/@radix-ui/primitive": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.2.0.tgz", + "integrity": "sha512-KABY+VMIRPJL+Vyzv/335FEhXXD/xDv8BMb1kl48/aXJZMH0LtHCTx5ga5RnxaEP3nZHtmTLf1P9vanmFX46bw==", + "license": "MIT" + }, + "node_modules/@radix-ui/react-navigation-menu/node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.5.tgz", + "integrity": "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==", + "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-navigation-menu/node_modules/@radix-ui/react-primitive": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.2.0.tgz", + "integrity": "sha512-HCTSPMNqv55Qk0IX4geJbpyXazmqulcimwuyjxTkKi29v+QZbG2Zho9BnbBq4YS2PF+KlNb2CXoLz66uUmblkg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.5.0" + }, + "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-navigation-menu/node_modules/@radix-ui/react-slot": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.5.0.tgz", + "integrity": "sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5" + }, + "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-navigation-menu/node_modules/@radix-ui/react-use-controllable-state": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-controllable-state/-/react-use-controllable-state-1.3.0.tgz", + "integrity": "sha512-TAcBI7bw2ljYCbv4+zuTSd6zICu8pRt6SDN2vJ/Z06K2MXh6I9WYFe/A9ovlFDtR5HVHGm5iDxDoABm/++dbKg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-use-effect-event": "0.0.5", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-navigation-menu/node_modules/@radix-ui/react-use-effect-event": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-effect-event/-/react-use-effect-event-0.0.5.tgz", + "integrity": "sha512-7cshFL8HGS/7HEiHH+9kL9HBwp2sa9yX18Knwek6KYWmXwM7pegMgta2AXMQKI+rq3JnfSj9x8wYqFMTdG1Jgg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-navigation-menu/node_modules/@radix-ui/react-use-layout-effect": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.4.tgz", + "integrity": "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw==", + "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-one-time-password-field": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-one-time-password-field/-/react-one-time-password-field-0.2.0.tgz", + "integrity": "sha512-PLxGB1jAFqhNZuLM0WhisNpczRg8ybAGa25loUWGUZWJF6hpGwuOSGk1nLgwhUYIESqIq/rlKG7WdcIPatF44A==", + "license": "MIT", + "dependencies": { + "@radix-ui/number": "1.1.3", + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-collection": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-direction": "1.2.0", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-roving-focus": "1.2.0", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-effect-event": "0.0.5", + "@radix-ui/react-use-is-hydrated": "0.1.3", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-one-time-password-field/node_modules/@radix-ui/primitive": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.2.0.tgz", + "integrity": "sha512-KABY+VMIRPJL+Vyzv/335FEhXXD/xDv8BMb1kl48/aXJZMH0LtHCTx5ga5RnxaEP3nZHtmTLf1P9vanmFX46bw==", + "license": "MIT" + }, + "node_modules/@radix-ui/react-one-time-password-field/node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.5.tgz", + "integrity": "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==", + "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-one-time-password-field/node_modules/@radix-ui/react-primitive": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.2.0.tgz", + "integrity": "sha512-HCTSPMNqv55Qk0IX4geJbpyXazmqulcimwuyjxTkKi29v+QZbG2Zho9BnbBq4YS2PF+KlNb2CXoLz66uUmblkg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.5.0" + }, + "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-one-time-password-field/node_modules/@radix-ui/react-slot": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.5.0.tgz", + "integrity": "sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5" + }, + "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-one-time-password-field/node_modules/@radix-ui/react-use-controllable-state": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-controllable-state/-/react-use-controllable-state-1.3.0.tgz", + "integrity": "sha512-TAcBI7bw2ljYCbv4+zuTSd6zICu8pRt6SDN2vJ/Z06K2MXh6I9WYFe/A9ovlFDtR5HVHGm5iDxDoABm/++dbKg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-use-effect-event": "0.0.5", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-one-time-password-field/node_modules/@radix-ui/react-use-effect-event": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-effect-event/-/react-use-effect-event-0.0.5.tgz", + "integrity": "sha512-7cshFL8HGS/7HEiHH+9kL9HBwp2sa9yX18Knwek6KYWmXwM7pegMgta2AXMQKI+rq3JnfSj9x8wYqFMTdG1Jgg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-one-time-password-field/node_modules/@radix-ui/react-use-layout-effect": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.4.tgz", + "integrity": "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw==", + "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-password-toggle-field": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-password-toggle-field/-/react-password-toggle-field-0.2.0.tgz", + "integrity": "sha512-+WoAic0sls1ErVU92aa9CF3nMon5Mt8h+Ulha19n/BHJTE4sG7ONFOmXaD2/8pT48uF7PbQGG5cI4X7BYYLCNA==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-effect-event": "0.0.5", + "@radix-ui/react-use-is-hydrated": "0.1.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-password-toggle-field/node_modules/@radix-ui/primitive": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.2.0.tgz", + "integrity": "sha512-KABY+VMIRPJL+Vyzv/335FEhXXD/xDv8BMb1kl48/aXJZMH0LtHCTx5ga5RnxaEP3nZHtmTLf1P9vanmFX46bw==", + "license": "MIT" + }, + "node_modules/@radix-ui/react-password-toggle-field/node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.5.tgz", + "integrity": "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==", + "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-password-toggle-field/node_modules/@radix-ui/react-primitive": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.2.0.tgz", + "integrity": "sha512-HCTSPMNqv55Qk0IX4geJbpyXazmqulcimwuyjxTkKi29v+QZbG2Zho9BnbBq4YS2PF+KlNb2CXoLz66uUmblkg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.5.0" + }, + "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-password-toggle-field/node_modules/@radix-ui/react-slot": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.5.0.tgz", + "integrity": "sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5" + }, + "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-password-toggle-field/node_modules/@radix-ui/react-use-controllable-state": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-controllable-state/-/react-use-controllable-state-1.3.0.tgz", + "integrity": "sha512-TAcBI7bw2ljYCbv4+zuTSd6zICu8pRt6SDN2vJ/Z06K2MXh6I9WYFe/A9ovlFDtR5HVHGm5iDxDoABm/++dbKg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-use-effect-event": "0.0.5", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-password-toggle-field/node_modules/@radix-ui/react-use-effect-event": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-effect-event/-/react-use-effect-event-0.0.5.tgz", + "integrity": "sha512-7cshFL8HGS/7HEiHH+9kL9HBwp2sa9yX18Knwek6KYWmXwM7pegMgta2AXMQKI+rq3JnfSj9x8wYqFMTdG1Jgg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-password-toggle-field/node_modules/@radix-ui/react-use-layout-effect": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.4.tgz", + "integrity": "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw==", + "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-popover": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-popover/-/react-popover-1.3.0.tgz", + "integrity": "sha512-rQ7ZgB0hhxHInjcvdnsXj4i9G+Cba+AZFztxDYdi5OXAK9qc5qBXnc3qsbVvnHmx/EP58mQ1QGZqmKvdUmBJOw==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-dismissable-layer": "1.2.0", + "@radix-ui/react-focus-guards": "1.2.0", + "@radix-ui/react-focus-scope": "1.3.0", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-popper": "1.4.0", + "@radix-ui/react-portal": "1.2.0", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-slot": "1.5.0", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-layout-effect": "1.1.4", + "aria-hidden": "^1.2.4", + "react-remove-scroll": "^2.7.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-popover/node_modules/@radix-ui/primitive": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.2.0.tgz", + "integrity": "sha512-KABY+VMIRPJL+Vyzv/335FEhXXD/xDv8BMb1kl48/aXJZMH0LtHCTx5ga5RnxaEP3nZHtmTLf1P9vanmFX46bw==", + "license": "MIT" + }, + "node_modules/@radix-ui/react-popover/node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.5.tgz", + "integrity": "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==", + "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-popover/node_modules/@radix-ui/react-primitive": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.2.0.tgz", + "integrity": "sha512-HCTSPMNqv55Qk0IX4geJbpyXazmqulcimwuyjxTkKi29v+QZbG2Zho9BnbBq4YS2PF+KlNb2CXoLz66uUmblkg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.5.0" + }, + "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-popover/node_modules/@radix-ui/react-slot": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.5.0.tgz", + "integrity": "sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5" + }, + "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-popover/node_modules/@radix-ui/react-use-controllable-state": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-controllable-state/-/react-use-controllable-state-1.3.0.tgz", + "integrity": "sha512-TAcBI7bw2ljYCbv4+zuTSd6zICu8pRt6SDN2vJ/Z06K2MXh6I9WYFe/A9ovlFDtR5HVHGm5iDxDoABm/++dbKg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-use-effect-event": "0.0.5", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-popover/node_modules/@radix-ui/react-use-effect-event": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-effect-event/-/react-use-effect-event-0.0.5.tgz", + "integrity": "sha512-7cshFL8HGS/7HEiHH+9kL9HBwp2sa9yX18Knwek6KYWmXwM7pegMgta2AXMQKI+rq3JnfSj9x8wYqFMTdG1Jgg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-popover/node_modules/@radix-ui/react-use-layout-effect": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.4.tgz", + "integrity": "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw==", + "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-popper": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-popper/-/react-popper-1.4.0.tgz", + "integrity": "sha512-yCWRvLeGv9Pz3+efwHqGPp70mZ56r3kfIgQVF56Oj2aAa4uP/Tb+IE59wNcc+758rctqbCKx4LbK8II/r7Bn0Q==", + "license": "MIT", + "dependencies": { + "@floating-ui/react-dom": "^2.0.0", + "@radix-ui/react-arrow": "1.1.17", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-callback-ref": "1.1.5", + "@radix-ui/react-use-layout-effect": "1.1.4", + "@radix-ui/react-use-rect": "1.1.4", + "@radix-ui/react-use-size": "1.1.5", + "@radix-ui/rect": "1.1.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-popper/node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.5.tgz", + "integrity": "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==", + "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-popper/node_modules/@radix-ui/react-primitive": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.2.0.tgz", + "integrity": "sha512-HCTSPMNqv55Qk0IX4geJbpyXazmqulcimwuyjxTkKi29v+QZbG2Zho9BnbBq4YS2PF+KlNb2CXoLz66uUmblkg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.5.0" + }, + "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-popper/node_modules/@radix-ui/react-slot": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.5.0.tgz", + "integrity": "sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5" + }, + "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-popper/node_modules/@radix-ui/react-use-layout-effect": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.4.tgz", + "integrity": "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw==", + "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-portal": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-portal/-/react-portal-1.2.0.tgz", + "integrity": "sha512-StX7xXnaRU41VvFtMm9zlhVGz8XF6GmWWTXftkQaY+tqVkbs/R9UmAp5mLzHHapk5hM9RMZQvO/3usyIP/g42g==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-portal/node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.5.tgz", + "integrity": "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==", + "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-portal/node_modules/@radix-ui/react-primitive": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.2.0.tgz", + "integrity": "sha512-HCTSPMNqv55Qk0IX4geJbpyXazmqulcimwuyjxTkKi29v+QZbG2Zho9BnbBq4YS2PF+KlNb2CXoLz66uUmblkg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.5.0" + }, + "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-portal/node_modules/@radix-ui/react-slot": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.5.0.tgz", + "integrity": "sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5" + }, + "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-portal/node_modules/@radix-ui/react-use-layout-effect": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.4.tgz", + "integrity": "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw==", + "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-presence": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/@radix-ui/react-presence/-/react-presence-1.1.11.tgz", + "integrity": "sha512-Z7/atlkab36Z8hm+V8zYc79r0W+tiOB1o0tun1By94JyadkekLQmtEAnBSP9XKXBNQsStoStS4+gX10JpS5akA==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-presence/node_modules/@radix-ui/react-use-layout-effect": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.4.tgz", + "integrity": "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw==", + "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==", + "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-progress": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-progress/-/react-progress-1.2.0.tgz", + "integrity": "sha512-HrBP6U3E7c+DgaeBOq/Qfgh1MZifKda5Evn0UXunSZvYTr0gf2nbTILLQ9ux7XZeoqKKh2YLm86cAhjVvHUbjw==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-primitive": "2.2.0" + }, + "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-progress/node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.5.tgz", + "integrity": "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==", + "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-progress/node_modules/@radix-ui/react-primitive": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.2.0.tgz", + "integrity": "sha512-HCTSPMNqv55Qk0IX4geJbpyXazmqulcimwuyjxTkKi29v+QZbG2Zho9BnbBq4YS2PF+KlNb2CXoLz66uUmblkg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.5.0" + }, + "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-progress/node_modules/@radix-ui/react-slot": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.5.0.tgz", + "integrity": "sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5" + }, + "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-radio-group": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-radio-group/-/react-radio-group-1.5.0.tgz", + "integrity": "sha512-/n8Z0nH/1IiJ3xYdeCKTloamVxzLS7XecvCqqPNDYfUWDuzoKcTOMHPT55GN1XLtfXKdps+eZfkp/1c1rceMCg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-direction": "1.2.0", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-roving-focus": "1.2.0", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-size": "1.1.5" + }, + "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-radio-group/node_modules/@radix-ui/primitive": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.2.0.tgz", + "integrity": "sha512-KABY+VMIRPJL+Vyzv/335FEhXXD/xDv8BMb1kl48/aXJZMH0LtHCTx5ga5RnxaEP3nZHtmTLf1P9vanmFX46bw==", + "license": "MIT" + }, + "node_modules/@radix-ui/react-radio-group/node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.5.tgz", + "integrity": "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==", + "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-radio-group/node_modules/@radix-ui/react-primitive": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.2.0.tgz", + "integrity": "sha512-HCTSPMNqv55Qk0IX4geJbpyXazmqulcimwuyjxTkKi29v+QZbG2Zho9BnbBq4YS2PF+KlNb2CXoLz66uUmblkg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.5.0" + }, + "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-radio-group/node_modules/@radix-ui/react-slot": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.5.0.tgz", + "integrity": "sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5" + }, + "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-radio-group/node_modules/@radix-ui/react-use-controllable-state": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-controllable-state/-/react-use-controllable-state-1.3.0.tgz", + "integrity": "sha512-TAcBI7bw2ljYCbv4+zuTSd6zICu8pRt6SDN2vJ/Z06K2MXh6I9WYFe/A9ovlFDtR5HVHGm5iDxDoABm/++dbKg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-use-effect-event": "0.0.5", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-radio-group/node_modules/@radix-ui/react-use-effect-event": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-effect-event/-/react-use-effect-event-0.0.5.tgz", + "integrity": "sha512-7cshFL8HGS/7HEiHH+9kL9HBwp2sa9yX18Knwek6KYWmXwM7pegMgta2AXMQKI+rq3JnfSj9x8wYqFMTdG1Jgg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-radio-group/node_modules/@radix-ui/react-use-layout-effect": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.4.tgz", + "integrity": "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw==", + "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-roving-focus": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-roving-focus/-/react-roving-focus-1.2.0.tgz", + "integrity": "sha512-gjVxnM4Y9U+8Lam0cybtPx27CwL4nkW2m1db7gJD3yvGOViKl/FAU3kiz8mfGsF5JPj036YOU3J3/PLUvTCEqw==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-collection": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-direction": "1.2.0", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-callback-ref": "1.1.5", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-is-hydrated": "0.1.3", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-roving-focus/node_modules/@radix-ui/primitive": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.2.0.tgz", + "integrity": "sha512-KABY+VMIRPJL+Vyzv/335FEhXXD/xDv8BMb1kl48/aXJZMH0LtHCTx5ga5RnxaEP3nZHtmTLf1P9vanmFX46bw==", + "license": "MIT" + }, + "node_modules/@radix-ui/react-roving-focus/node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.5.tgz", + "integrity": "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==", + "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-roving-focus/node_modules/@radix-ui/react-primitive": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.2.0.tgz", + "integrity": "sha512-HCTSPMNqv55Qk0IX4geJbpyXazmqulcimwuyjxTkKi29v+QZbG2Zho9BnbBq4YS2PF+KlNb2CXoLz66uUmblkg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.5.0" + }, + "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-roving-focus/node_modules/@radix-ui/react-slot": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.5.0.tgz", + "integrity": "sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5" + }, + "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-roving-focus/node_modules/@radix-ui/react-use-controllable-state": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-controllable-state/-/react-use-controllable-state-1.3.0.tgz", + "integrity": "sha512-TAcBI7bw2ljYCbv4+zuTSd6zICu8pRt6SDN2vJ/Z06K2MXh6I9WYFe/A9ovlFDtR5HVHGm5iDxDoABm/++dbKg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-use-effect-event": "0.0.5", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-roving-focus/node_modules/@radix-ui/react-use-effect-event": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-effect-event/-/react-use-effect-event-0.0.5.tgz", + "integrity": "sha512-7cshFL8HGS/7HEiHH+9kL9HBwp2sa9yX18Knwek6KYWmXwM7pegMgta2AXMQKI+rq3JnfSj9x8wYqFMTdG1Jgg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-roving-focus/node_modules/@radix-ui/react-use-layout-effect": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.4.tgz", + "integrity": "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw==", + "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-scroll-area": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-scroll-area/-/react-scroll-area-1.4.0.tgz", + "integrity": "sha512-CFrLqHNejWq5FhKAcj9V/WPGRsol76HBQto81NdOBVFEOqIEkJkKIJt0Z824A/9hHLCtoiR/Kw3euRgzXP2pxg==", + "license": "MIT", + "dependencies": { + "@radix-ui/number": "1.1.3", + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-direction": "1.2.0", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-slot": "1.5.0", + "@radix-ui/react-use-callback-ref": "1.1.5", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-scroll-area/node_modules/@radix-ui/primitive": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.2.0.tgz", + "integrity": "sha512-KABY+VMIRPJL+Vyzv/335FEhXXD/xDv8BMb1kl48/aXJZMH0LtHCTx5ga5RnxaEP3nZHtmTLf1P9vanmFX46bw==", + "license": "MIT" + }, + "node_modules/@radix-ui/react-scroll-area/node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.5.tgz", + "integrity": "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==", + "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-scroll-area/node_modules/@radix-ui/react-primitive": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.2.0.tgz", + "integrity": "sha512-HCTSPMNqv55Qk0IX4geJbpyXazmqulcimwuyjxTkKi29v+QZbG2Zho9BnbBq4YS2PF+KlNb2CXoLz66uUmblkg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.5.0" + }, + "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-scroll-area/node_modules/@radix-ui/react-slot": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.5.0.tgz", + "integrity": "sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5" + }, + "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-scroll-area/node_modules/@radix-ui/react-use-layout-effect": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.4.tgz", + "integrity": "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw==", + "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-select": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-select/-/react-select-2.4.0.tgz", + "integrity": "sha512-MfylDcwPAdeD6lELhuv3s2kwgdQkEzXwvYGBIPifV/lMfUodW44a+KAgaG7LWR1X/rhYM5C/0za5llkMyLz0Yg==", + "license": "MIT", + "dependencies": { + "@radix-ui/number": "1.1.3", + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-collection": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-direction": "1.2.0", + "@radix-ui/react-dismissable-layer": "1.2.0", + "@radix-ui/react-focus-guards": "1.2.0", + "@radix-ui/react-focus-scope": "1.3.0", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-popper": "1.4.0", + "@radix-ui/react-portal": "1.2.0", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-slot": "1.5.0", + "@radix-ui/react-use-callback-ref": "1.1.5", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-layout-effect": "1.1.4", + "@radix-ui/react-visually-hidden": "1.2.13", + "aria-hidden": "^1.2.4", + "react-remove-scroll": "^2.7.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-select/node_modules/@radix-ui/primitive": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.2.0.tgz", + "integrity": "sha512-KABY+VMIRPJL+Vyzv/335FEhXXD/xDv8BMb1kl48/aXJZMH0LtHCTx5ga5RnxaEP3nZHtmTLf1P9vanmFX46bw==", + "license": "MIT" + }, + "node_modules/@radix-ui/react-select/node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.5.tgz", + "integrity": "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==", + "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-select/node_modules/@radix-ui/react-primitive": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.2.0.tgz", + "integrity": "sha512-HCTSPMNqv55Qk0IX4geJbpyXazmqulcimwuyjxTkKi29v+QZbG2Zho9BnbBq4YS2PF+KlNb2CXoLz66uUmblkg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.5.0" + }, + "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-select/node_modules/@radix-ui/react-slot": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.5.0.tgz", + "integrity": "sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5" + }, + "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-select/node_modules/@radix-ui/react-use-controllable-state": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-controllable-state/-/react-use-controllable-state-1.3.0.tgz", + "integrity": "sha512-TAcBI7bw2ljYCbv4+zuTSd6zICu8pRt6SDN2vJ/Z06K2MXh6I9WYFe/A9ovlFDtR5HVHGm5iDxDoABm/++dbKg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-use-effect-event": "0.0.5", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-select/node_modules/@radix-ui/react-use-effect-event": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-effect-event/-/react-use-effect-event-0.0.5.tgz", + "integrity": "sha512-7cshFL8HGS/7HEiHH+9kL9HBwp2sa9yX18Knwek6KYWmXwM7pegMgta2AXMQKI+rq3JnfSj9x8wYqFMTdG1Jgg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-select/node_modules/@radix-ui/react-use-layout-effect": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.4.tgz", + "integrity": "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw==", + "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-separator": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-separator/-/react-separator-1.2.0.tgz", + "integrity": "sha512-1jUAap0wZEqVP05Ou7kJgRxe/W+Qftng+rUNWGa0qkKbv9r5pWTG3E7a3ELKo2eJoHKMECnzuYrZpSyO1YgcYQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-primitive": "2.2.0" + }, + "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-separator/node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.5.tgz", + "integrity": "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==", + "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-separator/node_modules/@radix-ui/react-primitive": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.2.0.tgz", + "integrity": "sha512-HCTSPMNqv55Qk0IX4geJbpyXazmqulcimwuyjxTkKi29v+QZbG2Zho9BnbBq4YS2PF+KlNb2CXoLz66uUmblkg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.5.0" + }, + "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-separator/node_modules/@radix-ui/react-slot": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.5.0.tgz", + "integrity": "sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5" + }, + "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-slider": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slider/-/react-slider-1.6.0.tgz", + "integrity": "sha512-0WkXQfNMp6uyg4TLSN8FaF+vypphoLnCZDTF57In0TORWRaWOyRNSJbSqyfcwLi0ktDiBWSHfKI8Dncaf7+9MQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/number": "1.1.3", + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-collection": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-direction": "1.2.0", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-layout-effect": "1.1.4", + "@radix-ui/react-use-size": "1.1.5" + }, + "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-slider/node_modules/@radix-ui/primitive": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.2.0.tgz", + "integrity": "sha512-KABY+VMIRPJL+Vyzv/335FEhXXD/xDv8BMb1kl48/aXJZMH0LtHCTx5ga5RnxaEP3nZHtmTLf1P9vanmFX46bw==", + "license": "MIT" + }, + "node_modules/@radix-ui/react-slider/node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.5.tgz", + "integrity": "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==", + "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-slider/node_modules/@radix-ui/react-primitive": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.2.0.tgz", + "integrity": "sha512-HCTSPMNqv55Qk0IX4geJbpyXazmqulcimwuyjxTkKi29v+QZbG2Zho9BnbBq4YS2PF+KlNb2CXoLz66uUmblkg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.5.0" + }, + "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-slider/node_modules/@radix-ui/react-slot": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.5.0.tgz", + "integrity": "sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5" + }, + "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-slider/node_modules/@radix-ui/react-use-controllable-state": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-controllable-state/-/react-use-controllable-state-1.3.0.tgz", + "integrity": "sha512-TAcBI7bw2ljYCbv4+zuTSd6zICu8pRt6SDN2vJ/Z06K2MXh6I9WYFe/A9ovlFDtR5HVHGm5iDxDoABm/++dbKg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-use-effect-event": "0.0.5", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-slider/node_modules/@radix-ui/react-use-effect-event": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-effect-event/-/react-use-effect-event-0.0.5.tgz", + "integrity": "sha512-7cshFL8HGS/7HEiHH+9kL9HBwp2sa9yX18Knwek6KYWmXwM7pegMgta2AXMQKI+rq3JnfSj9x8wYqFMTdG1Jgg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-slider/node_modules/@radix-ui/react-use-layout-effect": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.4.tgz", + "integrity": "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw==", + "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-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==", + "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-switch": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-switch/-/react-switch-1.4.0.tgz", + "integrity": "sha512-QuLr6GSEYKPlr4vkZ+vrTVDaJ7IeFlEpIpE9jWHUrQ6GNiNUxUwezLQ4NdcMkHE6KJ/YgKrR+nrCLps+JZH1mw==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-size": "1.1.5" + }, + "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-switch/node_modules/@radix-ui/primitive": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.2.0.tgz", + "integrity": "sha512-KABY+VMIRPJL+Vyzv/335FEhXXD/xDv8BMb1kl48/aXJZMH0LtHCTx5ga5RnxaEP3nZHtmTLf1P9vanmFX46bw==", + "license": "MIT" + }, + "node_modules/@radix-ui/react-switch/node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.5.tgz", + "integrity": "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==", + "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-switch/node_modules/@radix-ui/react-primitive": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.2.0.tgz", + "integrity": "sha512-HCTSPMNqv55Qk0IX4geJbpyXazmqulcimwuyjxTkKi29v+QZbG2Zho9BnbBq4YS2PF+KlNb2CXoLz66uUmblkg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.5.0" + }, + "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-switch/node_modules/@radix-ui/react-slot": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.5.0.tgz", + "integrity": "sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5" + }, + "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-switch/node_modules/@radix-ui/react-use-controllable-state": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-controllable-state/-/react-use-controllable-state-1.3.0.tgz", + "integrity": "sha512-TAcBI7bw2ljYCbv4+zuTSd6zICu8pRt6SDN2vJ/Z06K2MXh6I9WYFe/A9ovlFDtR5HVHGm5iDxDoABm/++dbKg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-use-effect-event": "0.0.5", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-switch/node_modules/@radix-ui/react-use-effect-event": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-effect-event/-/react-use-effect-event-0.0.5.tgz", + "integrity": "sha512-7cshFL8HGS/7HEiHH+9kL9HBwp2sa9yX18Knwek6KYWmXwM7pegMgta2AXMQKI+rq3JnfSj9x8wYqFMTdG1Jgg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-switch/node_modules/@radix-ui/react-use-layout-effect": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.4.tgz", + "integrity": "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw==", + "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-tabs": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-tabs/-/react-tabs-1.2.0.tgz", + "integrity": "sha512-Jusj5fsLHgEgzTnBy0YB/ZnE21bn8kjOr8v9ZgqxAR0buLIGcTu/U/Q19gp/UL7Jz5COX2qfEXENF6I6wWMRPg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-direction": "1.2.0", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-roving-focus": "1.2.0", + "@radix-ui/react-use-controllable-state": "1.3.0" + }, + "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-tabs/node_modules/@radix-ui/primitive": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.2.0.tgz", + "integrity": "sha512-KABY+VMIRPJL+Vyzv/335FEhXXD/xDv8BMb1kl48/aXJZMH0LtHCTx5ga5RnxaEP3nZHtmTLf1P9vanmFX46bw==", + "license": "MIT" + }, + "node_modules/@radix-ui/react-tabs/node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.5.tgz", + "integrity": "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==", + "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-tabs/node_modules/@radix-ui/react-primitive": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.2.0.tgz", + "integrity": "sha512-HCTSPMNqv55Qk0IX4geJbpyXazmqulcimwuyjxTkKi29v+QZbG2Zho9BnbBq4YS2PF+KlNb2CXoLz66uUmblkg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.5.0" + }, + "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-tabs/node_modules/@radix-ui/react-slot": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.5.0.tgz", + "integrity": "sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5" + }, + "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-tabs/node_modules/@radix-ui/react-use-controllable-state": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-controllable-state/-/react-use-controllable-state-1.3.0.tgz", + "integrity": "sha512-TAcBI7bw2ljYCbv4+zuTSd6zICu8pRt6SDN2vJ/Z06K2MXh6I9WYFe/A9ovlFDtR5HVHGm5iDxDoABm/++dbKg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-use-effect-event": "0.0.5", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-tabs/node_modules/@radix-ui/react-use-effect-event": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-effect-event/-/react-use-effect-event-0.0.5.tgz", + "integrity": "sha512-7cshFL8HGS/7HEiHH+9kL9HBwp2sa9yX18Knwek6KYWmXwM7pegMgta2AXMQKI+rq3JnfSj9x8wYqFMTdG1Jgg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-tabs/node_modules/@radix-ui/react-use-layout-effect": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.4.tgz", + "integrity": "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw==", + "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-toast": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-toast/-/react-toast-1.3.0.tgz", + "integrity": "sha512-PFuYC+RK4cH22CD2xwNYmNdjE49SLmdYCHLNkCaelndLuAzldc0t7FYklElsLpigHUo5xjN+J4oSYN3JsRaS7w==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-collection": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-dismissable-layer": "1.2.0", + "@radix-ui/react-portal": "1.2.0", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-callback-ref": "1.1.5", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-layout-effect": "1.1.4", + "@radix-ui/react-visually-hidden": "1.2.13" + }, + "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-toast/node_modules/@radix-ui/primitive": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.2.0.tgz", + "integrity": "sha512-KABY+VMIRPJL+Vyzv/335FEhXXD/xDv8BMb1kl48/aXJZMH0LtHCTx5ga5RnxaEP3nZHtmTLf1P9vanmFX46bw==", + "license": "MIT" + }, + "node_modules/@radix-ui/react-toast/node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.5.tgz", + "integrity": "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==", + "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-toast/node_modules/@radix-ui/react-primitive": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.2.0.tgz", + "integrity": "sha512-HCTSPMNqv55Qk0IX4geJbpyXazmqulcimwuyjxTkKi29v+QZbG2Zho9BnbBq4YS2PF+KlNb2CXoLz66uUmblkg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.5.0" + }, + "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-toast/node_modules/@radix-ui/react-slot": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.5.0.tgz", + "integrity": "sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5" + }, + "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-toast/node_modules/@radix-ui/react-use-controllable-state": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-controllable-state/-/react-use-controllable-state-1.3.0.tgz", + "integrity": "sha512-TAcBI7bw2ljYCbv4+zuTSd6zICu8pRt6SDN2vJ/Z06K2MXh6I9WYFe/A9ovlFDtR5HVHGm5iDxDoABm/++dbKg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-use-effect-event": "0.0.5", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-toast/node_modules/@radix-ui/react-use-effect-event": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-effect-event/-/react-use-effect-event-0.0.5.tgz", + "integrity": "sha512-7cshFL8HGS/7HEiHH+9kL9HBwp2sa9yX18Knwek6KYWmXwM7pegMgta2AXMQKI+rq3JnfSj9x8wYqFMTdG1Jgg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-toast/node_modules/@radix-ui/react-use-layout-effect": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.4.tgz", + "integrity": "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw==", + "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-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-toggle-group": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-toggle-group/-/react-toggle-group-1.2.0.tgz", + "integrity": "sha512-nbc90Rql9pu1L2UzS6MlvA7abUO3V9AOStKBzIqe5BzsEtP0amm++b+fNtZWSTXzUrAv/6oi0QhA+/UXDDdg4Q==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-direction": "1.2.0", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-roving-focus": "1.2.0", + "@radix-ui/react-toggle": "1.2.0", + "@radix-ui/react-use-controllable-state": "1.3.0" + }, + "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-toggle-group/node_modules/@radix-ui/primitive": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.2.0.tgz", + "integrity": "sha512-KABY+VMIRPJL+Vyzv/335FEhXXD/xDv8BMb1kl48/aXJZMH0LtHCTx5ga5RnxaEP3nZHtmTLf1P9vanmFX46bw==", + "license": "MIT" + }, + "node_modules/@radix-ui/react-toggle-group/node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.5.tgz", + "integrity": "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==", + "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-toggle-group/node_modules/@radix-ui/react-primitive": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.2.0.tgz", + "integrity": "sha512-HCTSPMNqv55Qk0IX4geJbpyXazmqulcimwuyjxTkKi29v+QZbG2Zho9BnbBq4YS2PF+KlNb2CXoLz66uUmblkg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.5.0" + }, + "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-toggle-group/node_modules/@radix-ui/react-slot": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.5.0.tgz", + "integrity": "sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5" + }, + "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-group/node_modules/@radix-ui/react-toggle": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-toggle/-/react-toggle-1.2.0.tgz", + "integrity": "sha512-/of2DdH8CyZBURA70jNEG5sEcliMX/hA8seXcUnqG7s7p3gNzrZJtJEQbiMmE8n+VAeuEW9DY5HyemqF8OfvOA==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-controllable-state": "1.3.0" + }, + "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-toggle-group/node_modules/@radix-ui/react-use-controllable-state": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-controllable-state/-/react-use-controllable-state-1.3.0.tgz", + "integrity": "sha512-TAcBI7bw2ljYCbv4+zuTSd6zICu8pRt6SDN2vJ/Z06K2MXh6I9WYFe/A9ovlFDtR5HVHGm5iDxDoABm/++dbKg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-use-effect-event": "0.0.5", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-group/node_modules/@radix-ui/react-use-effect-event": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-effect-event/-/react-use-effect-event-0.0.5.tgz", + "integrity": "sha512-7cshFL8HGS/7HEiHH+9kL9HBwp2sa9yX18Knwek6KYWmXwM7pegMgta2AXMQKI+rq3JnfSj9x8wYqFMTdG1Jgg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-group/node_modules/@radix-ui/react-use-layout-effect": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.4.tgz", + "integrity": "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw==", + "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-toolbar": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-toolbar/-/react-toolbar-1.2.0.tgz", + "integrity": "sha512-SpTvoC7VyGBo7ESinaugRCeT1LixwbyLWYPn1fzcPPS+em/Y2J/ISt9xqlGiab0lpgQThXbP38rrjYrH0qdi1g==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-direction": "1.2.0", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-roving-focus": "1.2.0", + "@radix-ui/react-separator": "1.2.0", + "@radix-ui/react-toggle-group": "1.2.0" + }, + "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-toolbar/node_modules/@radix-ui/primitive": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.2.0.tgz", + "integrity": "sha512-KABY+VMIRPJL+Vyzv/335FEhXXD/xDv8BMb1kl48/aXJZMH0LtHCTx5ga5RnxaEP3nZHtmTLf1P9vanmFX46bw==", + "license": "MIT" + }, + "node_modules/@radix-ui/react-toolbar/node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.5.tgz", + "integrity": "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==", + "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-toolbar/node_modules/@radix-ui/react-primitive": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.2.0.tgz", + "integrity": "sha512-HCTSPMNqv55Qk0IX4geJbpyXazmqulcimwuyjxTkKi29v+QZbG2Zho9BnbBq4YS2PF+KlNb2CXoLz66uUmblkg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.5.0" + }, + "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-toolbar/node_modules/@radix-ui/react-slot": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.5.0.tgz", + "integrity": "sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5" + }, + "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-tooltip": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-tooltip/-/react-tooltip-1.4.0.tgz", + "integrity": "sha512-cyPkPCqiagEam0LgqH0I/oPKdYzs2DylMDpvPbNA/Am12QaIfn4kSnXanjjqDPCQw17xY90GatufMek8XJEH8g==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-dismissable-layer": "1.2.0", + "@radix-ui/react-focus-scope": "1.3.0", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-popper": "1.4.0", + "@radix-ui/react-portal": "1.2.0", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-slot": "1.5.0", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-layout-effect": "1.1.4", + "@radix-ui/react-visually-hidden": "1.2.13" + }, + "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-tooltip/node_modules/@radix-ui/primitive": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.2.0.tgz", + "integrity": "sha512-KABY+VMIRPJL+Vyzv/335FEhXXD/xDv8BMb1kl48/aXJZMH0LtHCTx5ga5RnxaEP3nZHtmTLf1P9vanmFX46bw==", + "license": "MIT" + }, + "node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.5.tgz", + "integrity": "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==", + "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-tooltip/node_modules/@radix-ui/react-primitive": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.2.0.tgz", + "integrity": "sha512-HCTSPMNqv55Qk0IX4geJbpyXazmqulcimwuyjxTkKi29v+QZbG2Zho9BnbBq4YS2PF+KlNb2CXoLz66uUmblkg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.5.0" + }, + "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-tooltip/node_modules/@radix-ui/react-slot": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.5.0.tgz", + "integrity": "sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5" + }, + "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-tooltip/node_modules/@radix-ui/react-use-controllable-state": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-controllable-state/-/react-use-controllable-state-1.3.0.tgz", + "integrity": "sha512-TAcBI7bw2ljYCbv4+zuTSd6zICu8pRt6SDN2vJ/Z06K2MXh6I9WYFe/A9ovlFDtR5HVHGm5iDxDoABm/++dbKg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-use-effect-event": "0.0.5", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-tooltip/node_modules/@radix-ui/react-use-effect-event": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-effect-event/-/react-use-effect-event-0.0.5.tgz", + "integrity": "sha512-7cshFL8HGS/7HEiHH+9kL9HBwp2sa9yX18Knwek6KYWmXwM7pegMgta2AXMQKI+rq3JnfSj9x8wYqFMTdG1Jgg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-tooltip/node_modules/@radix-ui/react-use-layout-effect": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.4.tgz", + "integrity": "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw==", + "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-use-callback-ref": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-callback-ref/-/react-use-callback-ref-1.1.5.tgz", + "integrity": "sha512-Y5GBf4NKeADoXI1geiMlMuMoURT3k9MizzzKhGb/m55H94aGigZ01PIpkvsO6lML13BA6XYAXSJ6gza7vTn5nw==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-callback-ref/node_modules/@radix-ui/react-use-layout-effect": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.4.tgz", + "integrity": "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw==", + "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-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-escape-keydown": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-escape-keydown/-/react-use-escape-keydown-1.1.6.tgz", + "integrity": "sha512-9cRullnQRv+kqnRmFlmh0WC3kAPuGmHiQ9VwsXdrYk//sBhgCKEttcpPEPgIQbyx6TGUmooVEHYTyohwz/lSJg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-callback-ref": "1.1.5" + }, + "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-is-hydrated": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-is-hydrated/-/react-use-is-hydrated-0.1.3.tgz", + "integrity": "sha512-umO/aJ+82CpOnhDZUTbILCQf7kU/g0iv+oGs/Q8jw7IkhWBzaEP4sA268PhFAJTFetbwp3ICc6ktpI4TqtxcIw==", + "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-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/@radix-ui/react-use-previous": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-previous/-/react-use-previous-1.1.4.tgz", + "integrity": "sha512-XoSLhbRbqxFtgJoi2fNHA3C6pDlY34x508vUpUGoFZfvePfHXHbE1lC4FYFMnJWgiCRroSTw6fOsXQoVS9RwZg==", + "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-use-rect": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-rect/-/react-use-rect-1.1.4.tgz", + "integrity": "sha512-cSOCh6JlkmfjLyNcLiu2nB4v+nm+dkZ+Q5KHWk/soo4U7ZLiEQFKHK9/YmtBHjfCEaU43IBKQOc4/uJmCaiCTQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/rect": "1.1.3" + }, + "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-size": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-size/-/react-use-size-1.1.5.tgz", + "integrity": "sha512-V1McDQkMGzgivwqdu7u96APs7oi0Jvj9LTzgq3WWrDZqxWdAqU9yZnZQqk5OizGFR8badUQwZsrlao7MOlWYOA==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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-size/node_modules/@radix-ui/react-use-layout-effect": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.4.tgz", + "integrity": "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw==", + "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-visually-hidden": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@radix-ui/react-visually-hidden/-/react-visually-hidden-1.2.13.tgz", + "integrity": "sha512-feijiN1oPk4rck4u9Dm9tsU4mT6Wp9oeEEhaz1WUEs1VuqLf8xzsFG+Qk+uWq6TnMH9O+WRECRg0NftyP9E4Fw==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-primitive": "2.2.0" + }, + "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-visually-hidden/node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.5.tgz", + "integrity": "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==", + "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-visually-hidden/node_modules/@radix-ui/react-primitive": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.2.0.tgz", + "integrity": "sha512-HCTSPMNqv55Qk0IX4geJbpyXazmqulcimwuyjxTkKi29v+QZbG2Zho9BnbBq4YS2PF+KlNb2CXoLz66uUmblkg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.5.0" + }, + "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-visually-hidden/node_modules/@radix-ui/react-slot": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.5.0.tgz", + "integrity": "sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5" + }, + "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/rect": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/@radix-ui/rect/-/rect-1.1.3.tgz", + "integrity": "sha512-JtyZR+mqgBibTo8xea3B6ZRmzZiM/YeVBtUkas6zMuXjAlfIFIW2FgqeM9eLyvEaYX66vr6DJMK+4U6LV0KhNw==", + "license": "MIT" + }, + "node_modules/@reduxjs/toolkit": { + "version": "2.13.0", + "resolved": "https://registry.npmjs.org/@reduxjs/toolkit/-/toolkit-2.13.0.tgz", + "integrity": "sha512-f6jwVRfwW30+tnllz4YcsHHpPYYOE7abcHkyUCovD+P7DyhdAI5prz2Fh/8TLhakjpN+7aIEion1s5L/tvlYlA==", + "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.21", + "resolved": "https://registry.npmjs.org/immer/-/immer-11.1.21.tgz", + "integrity": "sha512-bZSadeCPGdaY5/qRLgr6mDSH1ra21rD3rqpiWk7+QTr4ayYPTE9qZYdLh/NdPhMe0wSrTvHD/Lk8q5EwhUs0aw==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/immer" + } + }, + "node_modules/@rolldown/binding-android-arm-eabi": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.13.tgz", + "integrity": "sha512-Vu/NICrgdRvUOeaJZIyB2FP63s6fO/4ud5l8dXmxDx9yDyn+mN0y+gsvsVviSli+T361Aqo0h46EuMoobrwawA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-android-arm64": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.13.tgz", + "integrity": "sha512-6LEoIrGy5vvCd2boNnv2soPSUZj/PRvhp8R/t9KlX+mIZxThIE/ZqxrGXxmuNX0FuvQFvLdZr7S4HrYpYBVhEQ==", + "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.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.13.tgz", + "integrity": "sha512-CaJSRzlQ6Q+zkDMVA9OkVxBjVoPRCDEE3v0FSJ9kIQBgRjFApA3Si4ijhbNVUji7ZJt+PfO0e46qy4nPInHUPA==", + "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.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.13.tgz", + "integrity": "sha512-e4r340I5hxSzJkD3YJBxgzq/rJ3wwxwdLLb2FPt1Zpyem20nrQPT11DDEEkazwxaHumH8wpglsp/Ozgj/wT6mw==", + "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.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.13.tgz", + "integrity": "sha512-hoBWDZ4/K/mJKVMbsgUd1jfpA2DiOrJ54mpegObU9TBHBBrtX4FLIXJJQRDPZ/2Dn91GvPob+Z2hwKJzf4E5SQ==", + "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.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.13.tgz", + "integrity": "sha512-oF9fZu3vTWnTiVAkDFxU9PJLt1nh20K9RRpuHsR7ZnE2L7XookBbDBVLojCVSLGbvtSlxeUNnjAj6DbNsKyzbg==", + "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.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.13.tgz", + "integrity": "sha512-DTpb/+jMiqWMPgphn4ksW1zW+XLJ6dJJ9FMvnIk9I291LhCctMPhMYJrP5t9p6C9qa3KXadDdUEZHBaPh3kNxQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-musl": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.13.tgz", + "integrity": "sha512-xU+Kvv9N2A3SY35zFh1FWWNjxbadE/BKeqnkXe7vScU4GZsw757BlVmDLITZEq8DPpk6m7uoDYkK7P+x/uU5Ow==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-ppc64-gnu": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.13.tgz", + "integrity": "sha512-XMk/hnhh25oQ756Lclb1Q11h4ll0xC0Esa5w4Vzp+mAE2S3AGJgeM0SonrIgY8fHhjarb6hcoTuwoFG0VVP2ig==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-s390x-gnu": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.13.tgz", + "integrity": "sha512-U1BoTHYmlywE2n3HUWjzZ+8EQsKr+OwpxYuDWaubx42tUL8QSL7nOqRz/NVHanibbFP3M1Rxuprz/wNcbMKjqw==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-gnu": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.13.tgz", + "integrity": "sha512-J4cm80Pc6wEwV5AZ42o62sIQgDk+Y7R2s646jIwuvO+4V46QB58N4vVuMPWCBaNgursXLpmUWJV//WQAkPvHBQ==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-musl": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.13.tgz", + "integrity": "sha512-W0euZS40U4V6JkmEnVCIX9mcsL6cbXQ4X8c2w+MMOIjFg68TXUW+u3RT+2e1t1pv9mg/EP3pDtK3POXdQ7Rxyw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-openharmony-arm64": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.13.tgz", + "integrity": "sha512-do/AF/4n9MRshia3a5aXoy8xM2c6mgfT6D7H/dY6my5z+hfCIR4ab7mk4IRj++nsEQpKy39kd0DQnDq+r692tw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-arm64-msvc": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.13.tgz", + "integrity": "sha512-6FtUf2cJZobutJdxnGYX8z0vtbgqU0b2v8vfBhkXb9wp2MppMFtkunE+IaOntyi01rkIQoPW2GHABtfzsC0BRQ==", + "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.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.13.tgz", + "integrity": "sha512-UKhFaZTeTcbKrb3iU82m17jVcPEAoqDkCN5MBqgPyZSwp/cQmib21crTS0DdH7T1B7wZRWEI89YQAOJMet5yhg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "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/@shadcn/registry": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/@shadcn/registry/-/registry-0.1.3.tgz", + "integrity": "sha512-82/OmKAVM9pChDHFVAsDP9PcimPGSKZGdbcdwdGGGcSI69ImpN4ZnqsfZ4hkOFEMal92t3y9djYJHMjO4PcVZA==", + "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", + "cn": "^0.2.4", + "code-block-writer": "^13.0.3", + "deepmerge": "^4.3.1", + "execa": "^9.6.0", + "fast-glob": "^3.3.3", + "fs-extra": "^11.3.1", + "fuzzysort": "^3.1.0", + "kleur": "^4.1.5", + "ora": "^8.2.0", + "postcss": "^8.5.23", + "prompts": "^2.4.2", + "recast": "^0.23.11", + "socks": "^2.8.8", + "stringify-object": "^5.0.0", + "tsconfig-paths": "^4.2.0", + "type-fest": "^4.41.0", + "undici": "^7.29.0", + "zod": "^3.24.1" + }, + "engines": { + "node": ">=20.18.1" + } + }, + "node_modules/@shadcn/registry/node_modules/cn": { + "version": "0.2.6", + "resolved": "https://registry.npmjs.org/cn/-/cn-0.2.6.tgz", + "integrity": "sha512-+i4L0zUGgRcEnhsxueVrP7iBGxBx5iD0WOTYg1MwFEu2ZyCmH5Ov2V1cul2Ht5UchRQQgftCf4be/RxspuW6QQ==", + "license": "MIT", + "bin": { + "cn": "bin/cn.mjs" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@shadcn/registry/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/registry/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/registry/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/registry/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/@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.23", + "resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.23.tgz", + "integrity": "sha512-5lSsMOTXURePglDfvuAQUqkGek9Hg2kksOYay2m0+XR++b2NWYL/4sWyuvVBIs8oKnJaxkdi9whaL/sqN13afw==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.8.0" + } + }, + "node_modules/@tailwindcss/node": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.3.3.tgz", + "integrity": "sha512-/T8IKEsf9VTU6tLjgC7+sv2mOPtQxzE2jMw7u4Tt40Tx+QSZxpzh95/H6cMKoja9XuW7iMdLJYBB0o9G1CaAgg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/remapping": "^2.3.5", + "enhanced-resolve": "^5.24.1", + "jiti": "^2.7.0", + "lightningcss": "1.32.0", + "magic-string": "^0.30.21", + "source-map-js": "^1.2.1", + "tailwindcss": "4.3.3" + } + }, + "node_modules/@tailwindcss/node/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/@tailwindcss/node/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/@tailwindcss/node/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/@tailwindcss/node/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/@tailwindcss/node/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/@tailwindcss/node/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/@tailwindcss/node/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, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@tailwindcss/node/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, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@tailwindcss/node/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, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@tailwindcss/node/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, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@tailwindcss/node/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/@tailwindcss/node/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/@tailwindcss/oxide": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide/-/oxide-4.3.3.tgz", + "integrity": "sha512-krXjAikiaFSPaK/FkAQT5UTx3VormQaiZ5hBFlJZ9UFQGB/rwg1MZIhHAG9smMQRTdyJxP6Qt5MwMtdyU5FWrA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 20" + }, + "optionalDependencies": { + "@tailwindcss/oxide-android-arm64": "4.3.3", + "@tailwindcss/oxide-darwin-arm64": "4.3.3", + "@tailwindcss/oxide-darwin-x64": "4.3.3", + "@tailwindcss/oxide-freebsd-x64": "4.3.3", + "@tailwindcss/oxide-linux-arm-gnueabihf": "4.3.3", + "@tailwindcss/oxide-linux-arm64-gnu": "4.3.3", + "@tailwindcss/oxide-linux-arm64-musl": "4.3.3", + "@tailwindcss/oxide-linux-x64-gnu": "4.3.3", + "@tailwindcss/oxide-linux-x64-musl": "4.3.3", + "@tailwindcss/oxide-wasm32-wasi": "4.3.3", + "@tailwindcss/oxide-win32-arm64-msvc": "4.3.3", + "@tailwindcss/oxide-win32-x64-msvc": "4.3.3" + } + }, + "node_modules/@tailwindcss/oxide-android-arm64": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-android-arm64/-/oxide-android-arm64-4.3.3.tgz", + "integrity": "sha512-Y85A2gmPSkl5Ve5qR86GL4HT509cFqQh1aes9p3sSkyTPwt0Pppf3GkwGe4JPACcRYjgJIEhQgM6dBClnr0NYw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-darwin-arm64": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-arm64/-/oxide-darwin-arm64-4.3.3.tgz", + "integrity": "sha512-BiaWatpBcERQFDlOjRDpIVXuFK5PJez5SA4JMg6VYZdBYU+qKfV/vqjcIs+IYmtitf1xYQZTwXvU/8y4lfZUGw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-darwin-x64": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-x64/-/oxide-darwin-x64-4.3.3.tgz", + "integrity": "sha512-fAeUqfV5ndhxRwai8cXGzdLvul9utWOmeTkv69unv4ZXixjn61Z+p9lCWdwOwA3TYboG3BwdVuN/RDjhBRl0mw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-freebsd-x64": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-freebsd-x64/-/oxide-freebsd-x64-4.3.3.tgz", + "integrity": "sha512-iyf5bV6+wnAlflVeEy7R25dupxTNECZN5QMI0qNT6eT+EgaGdZcKhGkr5SdoaWiLJ3spLqIY9VCeSGrwmtg4kw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm-gnueabihf": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm-gnueabihf/-/oxide-linux-arm-gnueabihf-4.3.3.tgz", + "integrity": "sha512-aAYUprJAJQWWbRrPvtjdroZ56Md+JM8pMiopS6xGEwDfLhqj+2ver2p4nU4Mb3CRqcMmNBjo8KkUgcxhkzVQGQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm64-gnu": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-gnu/-/oxide-linux-arm64-gnu-4.3.3.tgz", + "integrity": "sha512-nDxldcEENOxZRzC2uu9jrutZdAAQtb+8WWDCSnWL1zvBk1+FN+x6MtDViPB5AJMfttVCUhehGWus3XBPgatM/w==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm64-musl": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-musl/-/oxide-linux-arm64-musl-4.3.3.tgz", + "integrity": "sha512-Md44bD6veX/PC5iyF8cDVnw4HBIANZepRZZ7a8DQOvkfo5WUBwcp6iAuCUz23u+4SUkhJlD3eL7hNdW8ezd/kA==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-x64-gnu": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-gnu/-/oxide-linux-x64-gnu-4.3.3.tgz", + "integrity": "sha512-tx7us1muwOKAKWao2v/GaafFeQboE6aj88vC6ziN2NCGcRm8gWUhwjzg+YdVB1e4boAtdtma4L43onunI6NS4w==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-x64-musl": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-musl/-/oxide-linux-x64-musl-4.3.3.tgz", + "integrity": "sha512-SJxX60smvHgasZoBy11dX6YRjXJFovwWBoedhbQPOBzgFWBHGB+TVPWB9BxzR7TTxU8FQZAI2AyiNCMzFm8Img==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-wasm32-wasi/-/oxide-wasm32-wasi-4.3.3.tgz", + "integrity": "sha512-jx1+rPhY/5Ympkktd656HBWEBLxP7dH06losBLjjf5vgCODXvi9KhtftWcMIwTFIDqBr7cRnQkdLnAG+IOlGvQ==", + "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.11.1", + "@emnapi/runtime": "^1.11.1", + "@emnapi/wasi-threads": "^1.2.2", + "@napi-rs/wasm-runtime": "^1.1.4", + "@tybys/wasm-util": "^0.10.2", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@tailwindcss/oxide-win32-arm64-msvc": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.3.3.tgz", + "integrity": "sha512-3rc292Ca2ceK6Ulcc/bAVnTs/3nDtoPhyEKlgPv+yQJQi/JS/AMJlqzxvlDacL1nekbrcf6bTqp/jV4qgnPxNQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-win32-x64-msvc": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-x64-msvc/-/oxide-win32-x64-msvc-4.3.3.tgz", + "integrity": "sha512-yJ0pwIVc/nYeGoV02WtsN8KYyLQv7kyI2wDnkezyJlGGjkd4QLwDGAwl47YpPJeuI0M0ObaXGSPjvWDPeTPggw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/postcss": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/@tailwindcss/postcss/-/postcss-4.3.3.tgz", + "integrity": "sha512-JTSZZGQi1AyKirbLN3azmjVzef92tcX7h+iSqPdaeStyFpGpDlKvvpxeOE8njhbUanbRwr3z8DyzhICWnMtQeg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@alloc/quick-lru": "^5.2.0", + "@tailwindcss/node": "4.3.3", + "@tailwindcss/oxide": "4.3.3", + "postcss": "^8.5.16", + "tailwindcss": "4.3.3" + } + }, + "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.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", + "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "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.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", + "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.8" + }, + "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.0.3", + "resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.0.3.tgz", + "integrity": "sha512-Reoy+pKnvsksN0lQUlcH6dOGjRZ/3WRwXR//m+/8lt1BXeI4xyaUZoqULNjyXXRuh0Mj4LNpkCvhUpQlY3X5xQ==", + "license": "MIT" + }, + "node_modules/@types/d3-color": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@types/d3-color/-/d3-color-3.1.0.tgz", + "integrity": "sha512-HKuicPHJuvPgCD+np6Se9MQvS6OCbJmOjGvylzMJRlDwUXjKTTXs6Pwgk79O09Vj/ho3u1ofXnhFOaEWWPrlwA==", + "license": "MIT" + }, + "node_modules/@types/d3-delaunay": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/@types/d3-delaunay/-/d3-delaunay-6.0.1.tgz", + "integrity": "sha512-tLxQ2sfT0p6sxdG75c6f/ekqxjyYR0+LwPrsO1mbC9YDBzPJhs2HbJJRrn8Ez1DBoHRo2yx7YEATI+8V1nGMnQ==", + "devOptional": true, + "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-format": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/@types/d3-format/-/d3-format-3.0.1.tgz", + "integrity": "sha512-5KY70ifCCzorkLuIkDe0Z9YTf9RR2CjBX1iaJG+rgM/cPP+sO+q9YdQ9WdhQcgPj1EQiJ2/0+yUkkziTG6Lubg==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/@types/d3-geo": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@types/d3-geo/-/d3-geo-3.1.0.tgz", + "integrity": "sha512-856sckF0oP/diXtS4jNsiQw/UuK5fQG8l/a9VVLeSouf1/PPbBE1i1W852zVwKwYCBkFJJB7nCFTbk6UMEXBOQ==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "@types/geojson": "*" + } + }, + "node_modules/@types/d3-interpolate": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/@types/d3-interpolate/-/d3-interpolate-3.0.1.tgz", + "integrity": "sha512-jx5leotSeac3jr0RePOH1KdR9rISG91QIE4Q2PYTu4OymLTZfA3SrnURSLzKH48HmXVUru50b8nje4E79oQSQw==", + "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.2", + "resolved": "https://registry.npmjs.org/@types/d3-scale/-/d3-scale-4.0.2.tgz", + "integrity": "sha512-Yk4htunhPAwN0XGlIwArRomOjdoBFXC3+kCxK2Ubg7I9shQlVSJy/pG/Ht5ASN+gdMIalpk8TJ5xV74jFsetLA==", + "license": "MIT", + "dependencies": { + "@types/d3-time": "*" + } + }, + "node_modules/@types/d3-shape": { + "version": "3.1.7", + "resolved": "https://registry.npmjs.org/@types/d3-shape/-/d3-shape-3.1.7.tgz", + "integrity": "sha512-VLvUQ33C+3J+8p+Daf+nYSOsjB4GXp19/S/aGo60m9h1v6XaxjiT82lKVWJCfzhtuZ3yD7i/TPeC/fuKLLOSmg==", + "license": "MIT", + "dependencies": { + "@types/d3-path": "*" + } + }, + "node_modules/@types/d3-time": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@types/d3-time/-/d3-time-3.0.0.tgz", + "integrity": "sha512-sZLCdHvBUcNby1cB6Fd3ZBrABbjz3v1Vm90nysCQ6Vt7vd6e/h9Lt7SiJUoEX0l4Dzc7P5llKyhqSi1ycSf1Hg==", + "license": "MIT" + }, + "node_modules/@types/d3-time-format": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@types/d3-time-format/-/d3-time-format-2.1.0.tgz", + "integrity": "sha512-/myT3I7EwlukNOX2xVdMzb8FRgNzRMpsZddwst9Ld/VFe6LyJyRp0s32l/V9XoUzk+Gqu56F/oGk6507+8BxrA==", + "devOptional": true, + "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/debug": { + "version": "4.1.13", + "resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.13.tgz", + "integrity": "sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw==", + "license": "MIT", + "dependencies": { + "@types/ms": "*" + } + }, + "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.9", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "license": "MIT" + }, + "node_modules/@types/estree-jsx": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/@types/estree-jsx/-/estree-jsx-1.0.5.tgz", + "integrity": "sha512-52CcUVNFyfb1A2ALocQw/Dd1BQFNmSdkuC3BkZ6iqhdMfQz7JWOFRuJFloOzjk+6WijU56m9oKXFAXc7o3Towg==", + "license": "MIT", + "dependencies": { + "@types/estree": "*" + } + }, + "node_modules/@types/geojson": { + "version": "7946.0.16", + "resolved": "https://registry.npmjs.org/@types/geojson/-/geojson-7946.0.16.tgz", + "integrity": "sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/@types/hast": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/@types/hast/-/hast-3.0.5.tgz", + "integrity": "sha512-rp/ezSWaD1m44dPKICGhiskI13nVr7qTloFwDa/IYkhhf5nzwP+zIQcIJh3WIFSBOy/H1PzB40jPjMDksN4F+g==", + "license": "MIT", + "dependencies": { + "@types/unist": "*" + } + }, + "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/lodash": { + "version": "4.17.26", + "resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.17.26.tgz", + "integrity": "sha512-48NWfiY6oNcKOh47Z4h+sIvwcQR91h6KPhaYKgeMIrkT2jV82Gy90SErj60vW8jQbeMSOSbhIv3bZ7JoqPPVhA==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/@types/mdast": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/@types/mdast/-/mdast-4.0.4.tgz", + "integrity": "sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA==", + "license": "MIT", + "dependencies": { + "@types/unist": "*" + } + }, + "node_modules/@types/ms": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@types/ms/-/ms-2.1.0.tgz", + "integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==", + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "22.20.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz", + "integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==", + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/@types/nodemailer": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/@types/nodemailer/-/nodemailer-8.0.0.tgz", + "integrity": "sha512-fyf8jWULsCo0d0BuoQ75i6IeoHs47qcqxWc7yUdUcV0pOZGjUTTOvwdG1PRXUDqN/8A64yQdQdnA2pZgcdi+cA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/pg": { + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/@types/pg/-/pg-8.20.0.tgz", + "integrity": "sha512-bEPFOaMAHTEP1EzpvHTbmwR8UsFyHSKsRisLIHVMXnpNefSbGA1bD6CVy+qKjGSqmZqNqBDV2azOBo8TgkcVow==", + "license": "MIT", + "dependencies": { + "@types/node": "*", + "pg-protocol": "*", + "pg-types": "^2.2.0" + } + }, + "node_modules/@types/react": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz", + "integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==", + "license": "MIT", + "dependencies": { + "csstype": "^3.2.2" + } + }, + "node_modules/@types/react-dom": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.3.0.tgz", + "integrity": "sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==", + "devOptional": true, + "license": "MIT", + "peerDependencies": { + "@types/react": "^19.3.0" + } + }, + "node_modules/@types/unist": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz", + "integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==", + "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/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/@typescript-eslint/eslint-plugin": { + "version": "8.71.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.71.1.tgz", + "integrity": "sha512-nNlBf6HuotqMgZvSkWD5hNdemiBIxQ2NmrlgfcUIeZRs+BbakjscCQRq/Hb74EFVnFiSWWdL12JruqwBy3ERDw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/regexpp": "^4.12.2", + "@typescript-eslint/scope-manager": "8.71.1", + "@typescript-eslint/type-utils": "8.71.1", + "@typescript-eslint/utils": "8.71.1", + "@typescript-eslint/visitor-keys": "8.71.1", + "ignore": "^7.0.5", + "natural-compare": "^1.4.0", + "ts-api-utils": "^2.5.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.71.1", + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/eslint-plugin/node_modules/ignore": { + "version": "7.0.12", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.12.tgz", + "integrity": "sha512-/8UvqAPU9DGTI9k4mxtf49U37Isfwr8Uts96+SBHIkFxPJnHS0Ew4f00sM4Scd8V8EjM0jUNtVDdv1kPdt35lg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/@typescript-eslint/parser": { + "version": "8.71.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.71.1.tgz", + "integrity": "sha512-oM/5sAqz/l1v/zYK1qTOPrn2+JIrBGC1V6uNYucRO5gh6eT9vWJ/RhPbGE59byvZEUQ4VP6XkLBaS5Jti5jpvw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/scope-manager": "8.71.1", + "@typescript-eslint/types": "8.71.1", + "@typescript-eslint/typescript-estree": "8.71.1", + "@typescript-eslint/visitor-keys": "8.71.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.1.0" + } + }, + "node_modules/@typescript-eslint/parser/node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/@typescript-eslint/project-service": { + "version": "8.71.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.71.1.tgz", + "integrity": "sha512-Oijc9RUsohHjncg6iGi7gCtjnEjYt9FWv9u6ygK8uKcHK5eLjLAkqERQ9BaytbpceOFdk6kifPCS/zAZE+A99g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/tsconfig-utils": "^8.71.1", + "@typescript-eslint/types": "^8.71.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.1.0" + } + }, + "node_modules/@typescript-eslint/project-service/node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/@typescript-eslint/scope-manager": { + "version": "8.71.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.71.1.tgz", + "integrity": "sha512-1YUDZXdTnXLlob03SFHBipdyMBsDVm7zoSz0ytTJ39dk5J1TgsTK03VlR/dLXG/RLLUrPcYbD4rp23BmHxHP0w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.71.1", + "@typescript-eslint/visitor-keys": "8.71.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.71.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.71.1.tgz", + "integrity": "sha512-oTvkml5SxXhgg+WWKhod5qWQICDXtOB+/Hi9VdPKFAANJ2b7YOgMffgvzXuqog7R6A/JtrzRf128dsxummyWhg==", + "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.1.0" + } + }, + "node_modules/@typescript-eslint/type-utils": { + "version": "8.71.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.71.1.tgz", + "integrity": "sha512-kH3t3jZCYv2PZSBEWPKTariLrCaoF1CLoPitYFBJOhAGEwWnSRAtGEifrfrpBa4K9JlwWNZotgA5w3/wLSk/FQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.71.1", + "@typescript-eslint/typescript-estree": "8.71.1", + "@typescript-eslint/utils": "8.71.1", + "debug": "^4.4.3", + "ts-api-utils": "^2.5.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.1.0" + } + }, + "node_modules/@typescript-eslint/type-utils/node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/@typescript-eslint/types": { + "version": "8.71.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.71.1.tgz", + "integrity": "sha512-ybYnPTUwg3VQQOFEiBPLs8Jxl1ry2vXdn1kVKguomBbvxpetdu3MKTNDqFNUrlG8ylP9MpZosmXMFYlGQHk1oQ==", + "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.71.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.71.1.tgz", + "integrity": "sha512-pSKSEK1JJpHs6KiKVtABCE4iJK5d7FLFzDXQNBQ2oRY7LEd3UwOt3TZemTgu9syTIf56dJWlTn/pdmrO9oKUXQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/project-service": "8.71.1", + "@typescript-eslint/tsconfig-utils": "8.71.1", + "@typescript-eslint/types": "8.71.1", + "@typescript-eslint/visitor-keys": "8.71.1", + "debug": "^4.4.3", + "minimatch": "^10.2.2", + "semver": "^7.7.3", + "tinyglobby": "^0.2.15", + "ts-api-utils": "^2.5.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.1.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.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", + "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/@typescript-eslint/typescript-estree/node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/@typescript-eslint/typescript-estree/node_modules/minimatch": { + "version": "10.2.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", + "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.8" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@typescript-eslint/typescript-estree/node_modules/semver": { + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@typescript-eslint/utils": { + "version": "8.71.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.71.1.tgz", + "integrity": "sha512-CBjT6gfAz3DW2j9Q4moFnqt208Aq+506sVGXfpRcyAeqn0EpayL0mjdWoCO2t3RC7GewNrFxdeehuEaPg6DMzQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/eslint-utils": "^4.9.1", + "@typescript-eslint/scope-manager": "8.71.1", + "@typescript-eslint/types": "8.71.1", + "@typescript-eslint/typescript-estree": "8.71.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.1.0" + } + }, + "node_modules/@typescript-eslint/visitor-keys": { + "version": "8.71.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.71.1.tgz", + "integrity": "sha512-0GxiUGqMU0qXJt58cBsiG3DP8lUmBaFo2vChtUX+CT7PnR3v/VGLLrzVP4K9r1lNiZXjHYefMBbPunplr09v6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.71.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/@ungap/structured-clone": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.4.0.tgz", + "integrity": "sha512-1mEZtMKPM09vDmQt5y7YvmN2+DFTP7Tg0EWXdic8/C6VRnpb33e4ghisCIE3WZjsE2N8mf+QV1Zqh7ZFYLWInQ==", + "license": "ISC" + }, + "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" + "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-wasm32-wasi/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/@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/@visx/curve": { + "version": "4.0.1-alpha.0", + "resolved": "https://registry.npmjs.org/@visx/curve/-/curve-4.0.1-alpha.0.tgz", + "integrity": "sha512-jRu61Uz274pV1zyioXmboyrLutYbnKsgjj4njSGCnhdXj5GkZvZbg+ThDb6oOzoAnJOBRLz4rzPlWvNJOzuVMg==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "@visx/vendor": "4.0.0-alpha.0" + } + }, + "node_modules/@visx/event": { + "version": "4.0.1-alpha.0", + "resolved": "https://registry.npmjs.org/@visx/event/-/event-4.0.1-alpha.0.tgz", + "integrity": "sha512-EQqCMSv/s8NbFjo+hz3FKsvvYfP+2QslsFJ/24/O5l/W+7UC6J6aAvO0ujVwrTwdYbuQ+vhxKi1xdPdKR/qj1g==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "@types/react": "*", + "@visx/point": "4.0.1-alpha.0" + } + }, + "node_modules/@visx/grid": { + "version": "4.0.1-alpha.0", + "resolved": "https://registry.npmjs.org/@visx/grid/-/grid-4.0.1-alpha.0.tgz", + "integrity": "sha512-rycutGmTHO+znNdPumheWMglm7YfpffvRwUkVy5zy4WoORIuKTMkDxwnOzHG2xMxU3EE/YCd37xFV5AxA30yeg==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "@types/react": "*", + "@visx/curve": "4.0.1-alpha.0", + "@visx/group": "4.0.1-alpha.0", + "@visx/point": "4.0.1-alpha.0", + "@visx/scale": "4.0.1-alpha.0", + "@visx/shape": "4.0.1-alpha.0", + "classnames": "^2.3.1" + }, + "peerDependencies": { + "react": "^16.14.0 || ^17.0.0-0 || ^18.0.0-0 || ^19.0.0-0" + } + }, + "node_modules/@visx/group": { + "version": "4.0.1-alpha.0", + "resolved": "https://registry.npmjs.org/@visx/group/-/group-4.0.1-alpha.0.tgz", + "integrity": "sha512-V19l7iQ7jccBv8kao/EByuI6o4xtxzzLV9nqVI1hRvmdzTVsuLpqlwzYCZUXJaTVvUWf8s4D2SQFjGkj/Nw+0w==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "@types/react": "*", + "classnames": "^2.3.1" + }, + "peerDependencies": { + "react": "^16.14.0 || ^17.0.0-0 || ^18.0.0-0 || ^19.0.0-0" + } + }, + "node_modules/@visx/point": { + "version": "4.0.1-alpha.0", + "resolved": "https://registry.npmjs.org/@visx/point/-/point-4.0.1-alpha.0.tgz", + "integrity": "sha512-ijTfr/Nx09f03vIj9nyTr3z4Xth4Y75427UaogJh6dnIRLMEFHQOwNu791sbfiNj0a+ZXuaE32h0vKrFe4/8Qg==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/@visx/responsive": { + "version": "4.0.1-alpha.0", + "resolved": "https://registry.npmjs.org/@visx/responsive/-/responsive-4.0.1-alpha.0.tgz", + "integrity": "sha512-o+1zGywQZY0+yOx3Iw87wc4bbPJRr/HnIukTwfOz4UVyj9pB1OQNVHB7OORO1+LBHJceWpB31co/ZV9KHncKrA==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "@types/lodash": "^4.17.13", + "@types/react": "*", + "lodash": "^4.17.21" + }, + "peerDependencies": { + "react": "^16.14.0 || ^17.0.0-0 || ^18.0.0-0 || ^19.0.0-0" + } + }, + "node_modules/@visx/scale": { + "version": "4.0.1-alpha.0", + "resolved": "https://registry.npmjs.org/@visx/scale/-/scale-4.0.1-alpha.0.tgz", + "integrity": "sha512-nzjeE87vFSAXGWFiiNfBpNLAf0Q8Qmf6syvKLjqNi4kGZkdhbUll3E/59YsgWXmjM8+llPLWzGsP+JPvo5eq1A==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "@visx/vendor": "4.0.0-alpha.0" + } + }, + "node_modules/@visx/shape": { + "version": "4.0.1-alpha.0", + "resolved": "https://registry.npmjs.org/@visx/shape/-/shape-4.0.1-alpha.0.tgz", + "integrity": "sha512-62QeiVNmPlterQGwhkEDcbq7M0MqY0lBsK5QKXtM9ZoPZWkuGV3aykA3+Xu20B2FAvyJq4LqJzBc7Sxr+EAdbA==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "@types/lodash": "^4.17.13", + "@types/react": "*", + "@visx/curve": "4.0.1-alpha.0", + "@visx/group": "4.0.1-alpha.0", + "@visx/scale": "4.0.1-alpha.0", + "@visx/vendor": "4.0.0-alpha.0", + "classnames": "^2.3.1", + "lodash": "^4.17.21" + }, + "peerDependencies": { + "react": "^16.14.0 || ^17.0.0-0 || ^18.0.0-0 || ^19.0.0-0" + } + }, + "node_modules/@visx/vendor": { + "version": "4.0.0-alpha.0", + "resolved": "https://registry.npmjs.org/@visx/vendor/-/vendor-4.0.0-alpha.0.tgz", + "integrity": "sha512-6I+MuqXBcv9jnlcVowHoHKSdk9gXTWkHLKyqBwRWg7LY6A3Ei8SHfubpqGV5rBUSppxMq2RszPJUS6w+H0YgmQ==", + "devOptional": true, + "license": "MIT and ISC", + "dependencies": { + "@types/d3-array": "3.0.3", + "@types/d3-color": "3.1.0", + "@types/d3-delaunay": "6.0.1", + "@types/d3-format": "3.0.1", + "@types/d3-geo": "3.1.0", + "@types/d3-interpolate": "3.0.1", + "@types/d3-path": "3.1.1", + "@types/d3-scale": "4.0.2", + "@types/d3-shape": "3.1.7", + "@types/d3-time": "3.0.0", + "@types/d3-time-format": "2.1.0", + "d3-array": "3.2.1", + "d3-color": "3.1.0", + "d3-delaunay": "6.0.2", + "d3-format": "3.1.0", + "d3-geo": "3.1.0", + "d3-interpolate": "3.0.1", + "d3-path": "3.1.0", + "d3-scale": "4.0.2", + "d3-shape": "3.2.0", + "d3-time": "3.1.0", + "d3-time-format": "4.1.0", + "internmap": "2.0.3" + } + }, + "node_modules/@visx/vendor/node_modules/d3-array": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.1.tgz", + "integrity": "sha512-gUY/qeHq/yNqqoCKNq4vtpFLdoCdvyNpWoC/KNjhGbhDuQpAM9sIQQKkXSNpXa9h5KySs/gzm7R88WkUutgwWQ==", + "devOptional": true, + "license": "ISC", + "dependencies": { + "internmap": "1 - 2" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@vitest/expect": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.11.tgz", + "integrity": "sha512-VX2x5vNJXET47KAFzwERI+KRMtTTCSWTfSMKsW7JsUsXV4psq++e3DvZpuTDOpHcxytiDs6p2nhVb2tVDiiUYw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@standard-schema/spec": "^1.1.0", + "@types/chai": "^5.2.2", + "@vitest/spy": "4.1.11", + "@vitest/utils": "4.1.11", + "chai": "^6.2.2", + "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/mocker": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.11.tgz", + "integrity": "sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/spy": "4.1.11", + "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" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/pretty-format": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.11.tgz", + "integrity": "sha512-yiZzPbGTS9Sr/JpFl8zHrcIkAofNbFV6k21vIgQN/cY/oxZeXhJv5sc/MBJ5jFKWmWs+oJHw0UXLZjmf931+Vw==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/runner": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.11.tgz", + "integrity": "sha512-LztvUgdwMNJMIkj3hQnnxiC2Xy1zNxq928W/xhjCLaNCzqTZOudjwbQf6v9IntZGPw132i2Lq2rgTRZHD3JHNw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/utils": "4.1.11", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/snapshot": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.11.tgz", + "integrity": "sha512-pN7ikn1ON7h8ee4gIAp4AzyK+zBtJPzVbqOgu5LCEh4VaJVbPQcgYQYJIMGQPXVeJJq1fnfazis7a5pFNPahog==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "4.1.11", + "@vitest/utils": "4.1.11", + "magic-string": "^0.30.21", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/spy": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.11.tgz", + "integrity": "sha512-apNa/prQy2qCeywhnixOHPRCgGNhvg7T4Dapfl1GahLp/R+uhBm5cPyFoNVyqsNd2h1nJxL6BqqdIjiABL60YA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/utils": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.11.tgz", + "integrity": "sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "4.1.11", + "convert-source-map": "^2.0.0", + "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "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/ajv": { + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", + "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", + "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": { + "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/ansi-colors": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/ansi-colors/-/ansi-colors-4.1.3.tgz", + "integrity": "sha512-/6w/C21Pm1A7aZitlI5Ni/2J6FFQN8i1Cvz3kHABAAbw93v/NlvKdVOqz7CCWz/3iv/JplRSEEZ83XION15ovw==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "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/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "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==", + "dev": true, + "license": "Python-2.0" + }, + "node_modules/aria-hidden": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/aria-hidden/-/aria-hidden-1.2.6.tgz", + "integrity": "sha512-ik3ZgC9dY/lYVVM++OISsaYDeg1tb0VtP5uL3ouh1koGOaUMDPpbFIei4JkFimWUFPn90sbMNMXQAIVOlnYKJA==", + "license": "MIT", + "dependencies": { + "tslib": "^2.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "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.3", + "resolved": "https://registry.npmjs.org/ast-types/-/ast-types-0.16.3.tgz", + "integrity": "sha512-FvWoWYfSCM6kRxCSH+MGLHIKKGRL6A6AW7Zek2O32REPQRdg131428uRTKMBYAeRd3XXAaHDS60Wpri7CdKDrA==", + "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/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/atomically": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/atomically/-/atomically-1.7.0.tgz", + "integrity": "sha512-Xcz9l0z7y9yQ9rdDaxlmaI4uJHf/T8g9hOEzJcsEqX2SjCj4J20uK7+ldkDHMbpJDK76wF7xEIgxc/vSlsfw5w==", + "license": "MIT", + "engines": { + "node": ">=10.12.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.14.0", + "resolved": "https://registry.npmjs.org/axe-core/-/axe-core-4.14.0.tgz", + "integrity": "sha512-9WTZxEjsZ7b13TH8JPmbV2z8CHbl80/2hm3XPEG4JgNdQLK81IBRXmSxHfMAOkSqQeRxT/0dwNDz2GOm3zzpcQ==", + "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/bail": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/bail/-/bail-2.0.2.tgz", + "integrity": "sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "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/baseline-browser-mapping": { + "version": "2.11.28", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.28.tgz", + "integrity": "sha512-br0LOmjJqr6Rt4AEkadbcNf67Zpo7EPwKsWbjnRrJIa1QYFHQBqM4C7F2WTbV8ahTEcg1Eo+Y0aWjjORInYFyA==", + "license": "Apache-2.0", + "bin": { + "baseline-browser-mapping": "dist/cli.cjs" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/bcryptjs": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/bcryptjs/-/bcryptjs-3.0.3.tgz", + "integrity": "sha512-GlF5wPWnSa/X5LKM1o0wz0suXIINz1iHRLvTS+sLyi7XPbe5ycmYI3DlZqVGZZtDgl4DmasFg7gOB3JYbphV5g==", + "license": "BSD-3-Clause", + "bin": { + "bcrypt": "bin/bcrypt" + } + }, + "node_modules/better-result": { + "version": "2.10.0", + "resolved": "https://registry.npmjs.org/better-result/-/better-result-2.10.0.tgz", + "integrity": "sha512-oQhh0y1qo2/ZKdAAEvHZAqKKiHOFU5k/bW96fE2ScgQOVkJRiHwB+nOS1SgFsYqRlxMDWvefXi9Q3px7QvgNDw==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/body-parser": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz", + "integrity": "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==", + "license": "MIT", + "dependencies": { + "bytes": "^3.1.2", + "content-type": "^2.0.0", + "debug": "^4.4.3", + "http-errors": "^2.0.1", + "iconv-lite": "^0.7.2", + "on-finished": "^2.4.1", + "qs": "^6.15.2", + "raw-body": "^3.0.2", + "type-is": "^2.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/body-parser/node_modules/content-type": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/body-parser/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/brace-expansion": { + "version": "1.1.21", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", + "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", + "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.29.3", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.3.tgz", + "integrity": "sha512-1R4kiYKXGViqEN0CnoDrXc1StD9niAwu+j2dukWzrD4bJgsD4lDmEp0CRbc6E/vYJIfTHwPmwyaKtVSudICdPA==", + "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.11.26", + "caniuse-lite": "^1.0.30001813", + "electron-to-chromium": "^1.5.439", + "node-releases": "^2.0.57", + "update-browserslist-db": "^1.3.3" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/bundle-name": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/bundle-name/-/bundle-name-4.1.1.tgz", + "integrity": "sha512-DdH81/zPLVS11EUgWq3tEu/xn+EzljlMYooDNdzWEnFha3R3NBMpMV1UqYIpjYHV/SgpFKMIX1Oh7o06SjM/oA==", + "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.3.4", + "resolved": "https://registry.npmjs.org/c12/-/c12-3.3.4.tgz", + "integrity": "sha512-cM0ApFQSBXuourJejzwv/AuPRvAxordTyParRVcHjjtXirtkzM0uK2L9TTn9s0cXZbG7E55jCivRQzoxYmRAlA==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "chokidar": "^5.0.0", + "confbox": "^0.2.4", + "defu": "^6.1.6", + "dotenv": "^17.3.1", + "exsolve": "^1.0.8", + "giget": "^3.2.0", + "jiti": "^2.6.1", + "ohash": "^2.0.11", + "pathe": "^2.0.3", + "perfect-debounce": "^2.1.0", + "pkg-types": "^2.3.0", + "rc9": "^3.0.1" + }, + "peerDependencies": { + "magicast": "*" + }, + "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==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001815", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001815.tgz", + "integrity": "sha512-uDybUEyfgbyJJ93J1vikTylBX31AkdVYeVPeffMQpf8XN7hSfr0oZOn4VFOIMNvtU5+rHvC5Udg2TgtJKHm23Q==", + "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/ccount": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/ccount/-/ccount-2.0.1.tgz", + "integrity": "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/chai": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/chai/-/chai-6.3.0.tgz", + "integrity": "sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==", + "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/character-entities": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/character-entities/-/character-entities-2.0.2.tgz", + "integrity": "sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/character-entities-html4": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/character-entities-html4/-/character-entities-html4-2.1.0.tgz", + "integrity": "sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/character-entities-legacy": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/character-entities-legacy/-/character-entities-legacy-3.0.0.tgz", + "integrity": "sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/character-reference-invalid": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/character-reference-invalid/-/character-reference-invalid-2.0.1.tgz", + "integrity": "sha512-iBZ4F4wRbyORVsu0jPV7gXkOsGYjGHPmAyv+HiHG8gi5PtC9KI2j1+v8/tlibRvjoWX027ypmG/n0HtO5t7unw==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/chokidar": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-5.0.0.tgz", + "integrity": "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "readdirp": "^5.0.0" + }, + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "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/classnames": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/classnames/-/classnames-2.5.1.tgz", + "integrity": "sha512-saHYOzhIQs6wy2sVxTM6bUDsQO4F50V9RQ22qBpEdCW+I+/Wmke2HOl6lS6dTpdxVhb88/I6+Hs+438c3lfUow==", + "devOptional": true, + "license": "MIT" + }, + "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/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/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/cmdk": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/cmdk/-/cmdk-1.1.1.tgz", + "integrity": "sha512-Vsv7kFaXm+ptHDMZ7izaRsP70GgrW9NBNGswt9OZaVBLlE0SNpDq8eu/VGXyF9r7M0azK3Wy7OlYXsuyYLFzHg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "^1.1.1", + "@radix-ui/react-dialog": "^1.1.6", + "@radix-ui/react-id": "^1.1.0", + "@radix-ui/react-primitive": "^2.0.2" + }, + "peerDependencies": { + "react": "^18 || ^19 || ^19.0.0-rc", + "react-dom": "^18 || ^19 || ^19.0.0-rc" + } + }, + "node_modules/cn": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/cn/-/cn-0.4.0.tgz", + "integrity": "sha512-qOAeUhPwPzBxx6jaeQdo646XIKliKHc2j1ZF7Ngb1o0pJZKH5gq8FkA0aVdUdPFUDXNXyUCXpCtoJISo6dhizg==", + "license": "MIT", + "bin": { + "cn": "bin/cn.mjs" + }, + "engines": { + "node": ">=20" + } + }, + "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==", + "dev": true, + "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==", + "dev": true, + "license": "MIT" + }, + "node_modules/comma-separated-tokens": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-2.0.3.tgz", + "integrity": "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "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/conf": { + "version": "10.2.0", + "resolved": "https://registry.npmjs.org/conf/-/conf-10.2.0.tgz", + "integrity": "sha512-8fLl9F04EJqjSqH+QjITQfJF8BrOVaYr1jewVgSRAEWePfxT0sku4w2hrGQ60BC/TNLGQ2pgxNlTbWQmMPFvXg==", + "license": "MIT", + "dependencies": { + "ajv": "^8.6.3", + "ajv-formats": "^2.1.1", + "atomically": "^1.7.0", + "debounce-fn": "^4.0.0", + "dot-prop": "^6.0.1", + "env-paths": "^2.2.1", + "json-schema-typed": "^7.0.3", + "onetime": "^5.1.2", + "pkg-up": "^3.1.0", + "semver": "^7.3.5" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/conf/node_modules/ajv-formats": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-2.1.1.tgz", + "integrity": "sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA==", + "license": "MIT", + "dependencies": { + "ajv": "^8.0.0" + }, + "peerDependencies": { + "ajv": "^8.0.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + } + }, + "node_modules/conf/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/conf/node_modules/json-schema-typed": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/json-schema-typed/-/json-schema-typed-7.0.3.tgz", + "integrity": "sha512-7DE8mpG+/fVw+dTpjbxnx47TaMnDfOI1jwft9g1VybltZCduyRQPJPvc+zzKY9WPHxhPWczyFuYa6I8Mw4iU5A==", + "license": "BSD-2-Clause" + }, + "node_modules/conf/node_modules/semver": { + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "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/content-disposition": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-2.0.1.tgz", + "integrity": "sha512-e+H0ZXHSWYrENhQzw1LPuP4oF5MzVKmDU6d3hxlvaPEYLLg62MxtQNPRx4SYSuYJSBUgnQIG4HIN2tEtNv7Dog==", + "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/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==", + "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-delaunay": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/d3-delaunay/-/d3-delaunay-6.0.2.tgz", + "integrity": "sha512-IMLNldruDQScrcfT+MWnazhHbDJhcRJyOEBAJfwQnHle1RPh6WDuLvxNArUju2VSMSUuKlY5BGHRJ2cYyoFLQQ==", + "devOptional": true, + "license": "ISC", + "dependencies": { + "delaunator": "5" + }, + "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.0", + "resolved": "https://registry.npmjs.org/d3-format/-/d3-format-3.1.0.tgz", + "integrity": "sha512-YyUI6AEuY/Wpt8KWLgZHsIU86atmikuoOmCfommt0LYHiQSPjvX2AcFc38PX0CBpr2RCyZhjex+NS/LPOv6YqA==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-geo": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/d3-geo/-/d3-geo-3.1.0.tgz", + "integrity": "sha512-JEo5HxXDdDYXCaWdwLRt79y7giK8SbhZJbFWXqbRTolCHFI5jRqteLzCsq51NKbUoX0PjBVSohxrx+NoOUujYA==", + "devOptional": true, + "license": "ISC", + "dependencies": { + "d3-array": "2.5.0 - 3" + }, + "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-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/debounce-fn": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/debounce-fn/-/debounce-fn-4.0.0.tgz", + "integrity": "sha512-8pYCQiL9Xdcg0UPSD3d+0KMlOjp+KGU5EPwYddgzQ7DATsg4fuUDjQtsYLmWjnk2obnNHgV3vE2Y4jejSOJVBQ==", + "license": "MIT", + "dependencies": { + "mimic-fn": "^3.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/debug": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", + "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.1" + } + }, + "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/decode-named-character-reference": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/decode-named-character-reference/-/decode-named-character-reference-1.3.0.tgz", + "integrity": "sha512-GtpQYB283KrPp6nRw50q3U9/VfOutZOe103qlN7BPP6Ad27xYnOIWv4lPzo8HCAL+mMZofJ9KEy30fq6MfaK6Q==", + "license": "MIT", + "dependencies": { + "character-entities": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "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.1", + "resolved": "https://registry.npmjs.org/default-browser/-/default-browser-5.5.1.tgz", + "integrity": "sha512-m1pAzaJgZ/gssEqlOhJkPJp8Xly7QyW6xcrkUa2KKcDeDSEMP7X8xipU3snUcfisTQx0w1AGae+9UtJSfVnXGw==", + "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.7", + "resolved": "https://registry.npmjs.org/defu/-/defu-6.1.7.tgz", + "integrity": "sha512-7z22QmUWiQ/2d0KkdYmANbRUVABpZ9SNYyH5vx6PZ+nE5bcC0l7uFvEfHlyld/HcGBFTL536ClDt3DEcSlEJAQ==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/delaunator": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/delaunator/-/delaunator-5.1.0.tgz", + "integrity": "sha512-AGrQ4QSgssa1NGmWmLPqN5NY2KajF5MqxetNEO+o0n3ZwZZeTmt7bBnvzHWrmkZFxGgr4HdyFgelzgi06otLuQ==", + "devOptional": true, + "license": "ISC", + "dependencies": { + "robust-predicates": "^3.0.2" + } + }, + "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/dequal": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", + "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "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/detect-node-es": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/detect-node-es/-/detect-node-es-1.1.0.tgz", + "integrity": "sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ==", + "license": "MIT" + }, + "node_modules/devlop": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/devlop/-/devlop-1.1.0.tgz", + "integrity": "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==", + "license": "MIT", + "dependencies": { + "dequal": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/diff": { + "version": "8.0.4", + "resolved": "https://registry.npmjs.org/diff/-/diff-8.0.4.tgz", + "integrity": "sha512-DPi0FmjiSU5EvQV0++GFDOJ9ASQUVFh5kD+OzOnYdi7n3Wpm9hWWGfB/O2blfHcMVTL5WkQXSnRiK9makhrcnw==", + "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/dot-prop": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/dot-prop/-/dot-prop-6.0.1.tgz", + "integrity": "sha512-tE7ztYzXHIeyvc7N+hR3oi7FIbf/NIjVP9hmAt3yMXzrQ072/fpjGLx2GxNxGxUl5V73MEqYzioOMoVhGMJ5cA==", + "license": "MIT", + "dependencies": { + "is-obj": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/dotenv": { + "version": "17.4.2", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.4.2.tgz", + "integrity": "sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw==", + "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/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.452", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.452.tgz", + "integrity": "sha512-cVvk1YBSj6571VmV6hdJTqj94Y79xSu8cj6Y9t6ae4Y4431z8/7EJFvu3rVp90xhfuv9BpPKUmaLfTo4+FOGBg==", + "license": "ISC" + }, + "node_modules/elkjs": { + "version": "0.11.1", + "resolved": "https://registry.npmjs.org/elkjs/-/elkjs-0.11.1.tgz", + "integrity": "sha512-zxxR9k+rx5ktMwT/FwyLdPCrq7xN6e4VGGHH8hA01vVYKjTFik7nHOxBnAYtrgYUB1RpAiLvA1/U2YraWxyKKg==", + "devOptional": true, + "license": "EPL-2.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.26.0", + "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.26.0.tgz", + "integrity": "sha512-9vhedylFonb2YGogzUKX6+Ja72gOJbN1QHAqdrvqLwhdl/QWbKopzoUC9EbQNVsAns/bx/4uyqalrQAoy1IByw==", + "dev": true, + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.4", + "tapable": "^2.3.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/enquirer": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/enquirer/-/enquirer-2.4.1.tgz", + "integrity": "sha512-rRqJg/6gd538VHvR3PSrdRBb/1Vy2YfzHqzvbhGIQpDRKIa4FgV/54b5Q1xYSxOOwKvjXweS26E0Q+nAMwp2pQ==", + "license": "MIT", + "dependencies": { + "ansi-colors": "^4.1.1", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8.6" + } + }, + "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/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.52.0", + "resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.52.0.tgz", + "integrity": "sha512-XTNEJQh1tY1ZJVcf6ayP/2n4ZPyaHlW2FWs7xvw5ddPuhUVjLD3olQVQS7kf58JbAB48iL0uL/jerTrjtV3lDA==", + "license": "MIT", + "workspaces": [ + "docs", + "benchmarks", + "tests/types", + "tests/browser-compat" + ] + }, + "node_modules/esbuild": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.7.tgz", + "integrity": "sha512-IxpibTjyVnmrIQo5aqNpCgoACA/dTKLTlhMHihVHhdkxKyPO1uBBthumT0rdHmcsk9uMonIWS0m4FljWzILh3w==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.27.7", + "@esbuild/android-arm": "0.27.7", + "@esbuild/android-arm64": "0.27.7", + "@esbuild/android-x64": "0.27.7", + "@esbuild/darwin-arm64": "0.27.7", + "@esbuild/darwin-x64": "0.27.7", + "@esbuild/freebsd-arm64": "0.27.7", + "@esbuild/freebsd-x64": "0.27.7", + "@esbuild/linux-arm": "0.27.7", + "@esbuild/linux-arm64": "0.27.7", + "@esbuild/linux-ia32": "0.27.7", + "@esbuild/linux-loong64": "0.27.7", + "@esbuild/linux-mips64el": "0.27.7", + "@esbuild/linux-ppc64": "0.27.7", + "@esbuild/linux-riscv64": "0.27.7", + "@esbuild/linux-s390x": "0.27.7", + "@esbuild/linux-x64": "0.27.7", + "@esbuild/netbsd-arm64": "0.27.7", + "@esbuild/netbsd-x64": "0.27.7", + "@esbuild/openbsd-arm64": "0.27.7", + "@esbuild/openbsd-x64": "0.27.7", + "@esbuild/openharmony-arm64": "0.27.7", + "@esbuild/sunos-x64": "0.27.7", + "@esbuild/win32-arm64": "0.27.7", + "@esbuild/win32-ia32": "0.27.7", + "@esbuild/win32-x64": "0.27.7" + } + }, + "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.5", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-9.39.5.tgz", + "integrity": "sha512-DgZS62aPLXKlnxILS/AYCoRvHaZeXceIzlXPkkGGzJWSow1aEk0lbTlxUSlyjC8jcaKxAdOnTDz+o1JFSBsyjw==", + "deprecated": "This version is no longer supported. Please see https://eslint.org/version-support for other options.", + "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.6", + "@eslint/js": "9.39.5", + "@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.4.0", + "resolved": "https://registry.npmjs.org/eslint-config-next/-/eslint-config-next-16.4.0.tgz", + "integrity": "sha512-2RHLYswzc+hNRktWAjIL6XAvwb1cKcjLawJ5KWywAxn/JivNHtG42ZigL1yobVXDqsimuuL2F9jcEcnHFzbppQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@next/eslint-plugin-next": "16.4.0", + "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.1.0", + "globals": "16.4.0", + "typescript-eslint": "^8.56.0" + }, + "peerDependencies": { + "eslint": ">=9.0.0", + "typescript": ">=3.3.1" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "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-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-import-resolver-typescript/node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "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-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-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.1.1", + "resolved": "https://registry.npmjs.org/eslint-plugin-react-hooks/-/eslint-plugin-react-hooks-7.1.1.tgz", + "integrity": "sha512-f2I7Gw6JbvCexzIInuSbZpfdQ44D7iqdWX01FKLvrPgqxoE7oMj8clOfto8U6vYiz4yd5oKu39rRSVOe1zRu0g==", + "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 || ^10.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/eslint/node_modules/ajv": { + "version": "6.15.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.15.0.tgz", + "integrity": "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==", + "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/eslint/node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", "dev": true, "license": "MIT", - "optional": true, - "os": [ - "android" - ] + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } }, - "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" - ], + "node_modules/eslint/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", - "optional": true, - "os": [ - "android" - ] + "license": "MIT" }, - "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" - ], + "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": "MIT", - "optional": true, - "os": [ - "darwin" - ] + "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/@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" - ], + "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": "MIT", - "optional": true, - "os": [ - "darwin" - ] + "license": "BSD-3-Clause", + "dependencies": { + "estraverse": "^5.1.0" + }, + "engines": { + "node": ">=0.10" + } }, - "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" - ], + "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": "MIT", - "optional": true, - "os": [ - "freebsd" - ] + "license": "BSD-2-Clause", + "dependencies": { + "estraverse": "^5.2.0" + }, + "engines": { + "node": ">=4.0" + } }, - "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" - ], + "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-util-is-identifier-name": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/estree-util-is-identifier-name/-/estree-util-is-identifier-name-3.0.0.tgz", + "integrity": "sha512-hFtqIDZTIUZ9BXLb8y4pYGyk6+wekIivNVTcmvk8NoOh+VeRn5y6cEHzbURrWbfp1fIqdVipilzj+lfaadNZmg==", "license": "MIT", - "optional": true, - "os": [ - "linux" - ] + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } }, - "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" - ], + "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", - "optional": true, - "os": [ - "linux" - ] + "dependencies": { + "@types/estree": "^1.0.0" + } }, - "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" - ], + "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", - "optional": true, - "os": [ - "linux" - ] + "engines": { + "node": ">= 0.6" + } }, - "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, + "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", - "optional": true, - "os": [ - "linux" - ] + "dependencies": { + "eventsource-parser": "^3.0.1" + }, + "engines": { + "node": ">=18.0.0" + } }, - "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, + "node_modules/eventsource-parser": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.1.1.tgz", + "integrity": "sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==", "license": "MIT", - "optional": true, - "os": [ - "linux" - ] + "engines": { + "node": ">=18.0.0" + } }, - "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" - ], + "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.3.0", + "resolved": "https://registry.npmjs.org/express/-/express-5.3.0.tgz", + "integrity": "sha512-qCqy1xSoaugxOD4IVHb1ZWdkvCF2W3aE2okKouWj8VwJ+ztskSiXoBnCSJqfKT+cVPJhuJqe9YLbY425+Zh00g==", + "license": "MIT", + "dependencies": { + "accepts": "^2.0.0", + "body-parser": "^2.3.0", + "content-disposition": "^2.0.1", + "content-type": "^2.0.0", + "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.8", + "qs": "^6.16.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.1.0", + "vary": "^1.1.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/express-rate-limit": { + "version": "8.7.1", + "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.7.1.tgz", + "integrity": "sha512-2FXbqkygil3mZiXzEtM0IjE/UBmBNot0J1GEVrJT4JbrvwOSoEtqtO+wHbiMQELWe1eNvHoYRg2dkjOid+6JkA==", "license": "MIT", - "optional": true, - "os": [ - "linux" - ] + "dependencies": { + "debug": "^4.4.3", + "ip-address": "^10.2.0" + }, + "engines": { + "node": ">= 16" + }, + "funding": { + "url": "https://github.com/sponsors/express-rate-limit" + }, + "peerDependencies": { + "express": ">= 4.11" + } }, - "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, + "node_modules/express-rate-limit/node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", "license": "MIT", - "optional": true, - "os": [ - "linux" - ] + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } }, - "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, + "node_modules/express/node_modules/content-type": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", "license": "MIT", - "optional": true, - "os": [ - "linux" - ] + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } }, - "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, + "node_modules/express/node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", "license": "MIT", - "optional": true, - "os": [ - "linux" - ] + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } }, - "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" + "node_modules/exsolve": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/exsolve/-/exsolve-1.1.3.tgz", + "integrity": "sha512-kuzL9zherLQoqDeQaS55AiiIg1kb4KYXaSusTtgZTPlvKP2gGCI82LNmBNh5RjDVUXIcmgx+/Mx7vPwRzBbhJA==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/extend": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", + "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==", + "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" + } ], - "dev": true, "license": "MIT", - "optional": true, - "os": [ - "linux" - ] + "dependencies": { + "pure-rand": "^6.1.0" + }, + "engines": { + "node": ">=8.0.0" + } }, - "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" - ], + "node_modules/fast-decode-uri-component": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/fast-decode-uri-component/-/fast-decode-uri-component-1.0.1.tgz", + "integrity": "sha512-WKgKWg5eUxvRZGwW8FvfbaH7AXSh2cL+3j5fMGzUMCxWBJ3dV3a7Wz8y2f/uQ0e3B6WmodD3oS54jTQ9HVTIIg==", + "devOptional": true, + "license": "MIT" + }, + "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", - "optional": true, "dependencies": { - "@napi-rs/wasm-runtime": "^0.2.11" + "@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": ">=14.0.0" + "node": ">=8.6.0" } }, - "node_modules/@unrs/resolver-binding-wasm32-wasi/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==", + "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": "MIT", - "optional": true, + "license": "ISC", "dependencies": { - "@emnapi/core": "^1.4.3", - "@emnapi/runtime": "^1.4.3", - "@tybys/wasm-util": "^0.10.0" + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" } }, - "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" - ], + "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", - "optional": true, - "os": [ - "win32" - ] + "license": "MIT" }, - "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" - ], + "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-querystring": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/fast-querystring/-/fast-querystring-1.1.2.tgz", + "integrity": "sha512-g6KuKWmFXc0fID8WWH0jit4g0AGBoJhCkJMb1RmbsSEUNvQ+ZC8D6CUZ+GtF8nMzSPXnhiePyyqqipzNNEnHjg==", + "devOptional": true, "license": "MIT", - "optional": true, - "os": [ - "win32" - ] + "dependencies": { + "fast-decode-uri-component": "^1.0.1" + } }, - "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" + "node_modules/fast-uri": { + "version": "3.1.8", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.8.tgz", + "integrity": "sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } ], - "dev": true, + "license": "BSD-3-Clause" + }, + "node_modules/fastq": { + "version": "1.20.3", + "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.20.3.tgz", + "integrity": "sha512-XKv5nnLs6nLF71NgiKJLIZFLkPyIEuOselLG7ujZnGrRfQK8HpvY+WqKhAJUAdLomwVHErVS4LfxFlPq0/FTAw==", + "license": "ISC", + "dependencies": { + "reusify": "^1.0.4" + } + }, + "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", - "optional": true, - "os": [ - "win32" - ] + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } }, - "node_modules/@vitejs/plugin-react": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-6.0.1.tgz", - "integrity": "sha512-l9X/E3cDb+xY3SWzlG1MOGt2usfEHGMNIaegaUGFsLkb3RCn/k8/TOXBcab+OndDI4TBtktT8/9BwwW8Vi9KUQ==", + "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": { - "@rolldown/pluginutils": "1.0.0-rc.7" + "flat-cache": "^4.0.0" }, "engines": { - "node": "^20.19.0 || >=22.12.0" - }, - "peerDependencies": { - "@rolldown/plugin-babel": "^0.1.7 || ^0.2.0", - "babel-plugin-react-compiler": "^1.0.0", - "vite": "^8.0.0" - }, - "peerDependenciesMeta": { - "@rolldown/plugin-babel": { - "optional": true - }, - "babel-plugin-react-compiler": { - "optional": true - } + "node": ">=16.0.0" } }, - "node_modules/@vitest/expect": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.2.tgz", - "integrity": "sha512-gbu+7B0YgUJ2nkdsRJrFFW6X7NTP44WlhiclHniUhxADQJH5Szt9mZ9hWnJPJ8YwOK5zUOSSlSvyzRf0u1DSBQ==", - "dev": true, + "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": { - "@standard-schema/spec": "^1.1.0", - "@types/chai": "^5.2.2", - "@vitest/spy": "4.1.2", - "@vitest/utils": "4.1.2", - "chai": "^6.2.2", - "tinyrainbow": "^3.1.0" + "to-regex-range": "^5.0.1" }, - "funding": { - "url": "https://opencollective.com/vitest" + "engines": { + "node": ">=8" } }, - "node_modules/@vitest/mocker": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.2.tgz", - "integrity": "sha512-Ize4iQtEALHDttPRCmN+FKqOl2vxTiNUhzobQFFt/BM1lRUTG7zRCLOykG/6Vo4E4hnUdfVLo5/eqKPukcWW7Q==", - "dev": true, + "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": { - "@vitest/spy": "4.1.2", - "estree-walker": "^3.0.3", - "magic-string": "^0.30.21" + "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": { - "url": "https://opencollective.com/vitest" + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/finalhandler/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" }, - "peerDependencies": { - "msw": "^2.4.9", - "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + "engines": { + "node": ">=6.0" }, "peerDependenciesMeta": { - "msw": { - "optional": true - }, - "vite": { + "supports-color": { "optional": true } } }, - "node_modules/@vitest/pretty-format": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.2.tgz", - "integrity": "sha512-dwQga8aejqeuB+TvXCMzSQemvV9hNEtDDpgUKDzOmNQayl2OG241PSWeJwKRH3CiC+sESrmoFd49rfnq7T4RnA==", - "dev": true, + "node_modules/find-my-way": { + "version": "9.7.0", + "resolved": "https://registry.npmjs.org/find-my-way/-/find-my-way-9.7.0.tgz", + "integrity": "sha512-f2JHn75x2JlwUwLenZypgczR7YWMb/uO9BvUXtus+JMgkbIkLADd38cI4EiV+OQqrGo1Zlq6V8wnqMJ8e62wUQ==", + "devOptional": true, "license": "MIT", "dependencies": { - "tinyrainbow": "^3.1.0" + "fast-deep-equal": "^3.1.3", + "fast-querystring": "^1.0.0", + "safe-regex2": "^5.0.0" }, - "funding": { - "url": "https://opencollective.com/vitest" + "engines": { + "node": ">=20" } }, - "node_modules/@vitest/runner": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.2.tgz", - "integrity": "sha512-Gr+FQan34CdiYAwpGJmQG8PgkyFVmARK8/xSijia3eTFgVfpcpztWLuP6FttGNfPLJhaZVP/euvujeNYar36OQ==", + "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": { - "@vitest/utils": "4.1.2", - "pathe": "^2.0.3" + "locate-path": "^6.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=10" }, "funding": { - "url": "https://opencollective.com/vitest" + "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/@vitest/snapshot": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.2.tgz", - "integrity": "sha512-g7yfUmxYS4mNxk31qbOYsSt2F4m1E02LFqO53Xpzg3zKMhLAPZAjjfyl9e6z7HrW6LvUdTwAQR3HHfLjpko16A==", + "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": { - "@vitest/pretty-format": "4.1.2", - "@vitest/utils": "4.1.2", - "magic-string": "^0.30.21", - "pathe": "^2.0.3" + "flatted": "^3.2.9", + "keyv": "^4.5.4" }, - "funding": { - "url": "https://opencollective.com/vitest" + "engines": { + "node": ">=16" } }, - "node_modules/@vitest/spy": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.2.tgz", - "integrity": "sha512-DU4fBnbVCJGNBwVA6xSToNXrkZNSiw59H8tcuUspVMsBDBST4nfvsPsEHDHGtWRRnqBERBQu7TrTKskmjqTXKA==", + "node_modules/flatted": { + "version": "3.4.4", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.4.4.tgz", + "integrity": "sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q==", + "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://opencollective.com/vitest" + "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/@vitest/utils": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.2.tgz", - "integrity": "sha512-xw2/TiX82lQHA06cgbqRKFb5lCAy3axQ4H4SoUFhUsg+wztiet+co86IAMDtF6Vm1hc7J6j09oh/rgDn+JdKIQ==", - "dev": true, - "license": "MIT", + "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": { - "@vitest/pretty-format": "4.1.2", - "convert-source-map": "^2.0.0", - "tinyrainbow": "^3.1.0" + "cross-spawn": "^7.0.6", + "signal-exit": "^4.0.1" + }, + "engines": { + "node": ">=14" }, "funding": { - "url": "https://opencollective.com/vitest" + "url": "https://github.com/sponsors/isaacs" } }, - "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, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", "license": "MIT", - "bin": { - "acorn": "bin/acorn" - }, "engines": { - "node": ">=0.4.0" + "node": ">= 0.6" } }, - "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, + "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", - "peerDependencies": { - "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" + "engines": { + "node": ">= 0.8" } }, - "node_modules/ajv": { - "version": "8.18.0", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz", - "integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==", - "devOptional": true, + "node_modules/fs-extra": { + "version": "11.4.1", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.4.1.tgz", + "integrity": "sha512-KYAb4c9BJQI6QqGKthV68OHe0badztdXJWKo0WtBA9IuCFPTKvE5ZdUBglP833aMjhaSPNO4A5j/EkzZtGlKjA==", "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" + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/epoberezkin" + "engines": { + "node": ">=14.14" } }, - "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==", + "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" + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, - "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==", - "dev": true, + "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", - "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==", - "dev": true, - "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" + "url": "https://github.com/sponsors/ljharb" } }, - "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==", + "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", - "is-array-buffer": "^3.0.5" + "define-properties": "^1.2.1", + "functions-have-names": "^1.2.3", + "hasown": "^2.0.2", + "is-callable": "^1.2.7" }, "engines": { "node": ">= 0.4" @@ -2797,64 +13077,79 @@ "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==", + "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": { - "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" - }, + "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": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" + "node": ">=6.9.0" } }, - "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, + "node_modules/get-east-asian-width": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.7.0.tgz", + "integrity": "sha512-XjH1AECxf0giL2V1aU8vKyRR2ppRUb5c0EvT7zuJTokQ74bNo52zOtghqdWIqrhUD79fo3x0WfKZdOqxF6LG1Q==", "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" + "node": ">=18" }, "funding": { - "url": "https://github.com/sponsors/ljharb" + "url": "https://github.com/sponsors/sindresorhus" } }, - "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, + "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": "^1.0.8", - "call-bound": "^1.0.4", - "define-properties": "^1.2.1", - "es-abstract": "^1.23.9", + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", "es-errors": "^1.3.0", "es-object-atoms": "^1.1.1", - "es-shim-unscopables": "^1.1.0" + "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" @@ -2863,75 +13158,73 @@ "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, + "node_modules/get-nonce": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-nonce/-/get-nonce-1.0.1.tgz", + "integrity": "sha512-FJhYRoDaiatfEkUK8HKlicmu/3SGFD51q3itKDGoSTysQJBnfOcxU5GxnhE1E6soB76MbT0MBtnKJuXyAx+96Q==", "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" + "node": ">=6" + } + }, + "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/ljharb" + "url": "https://github.com/sponsors/sindresorhus" } }, - "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, + "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": { - "call-bind": "^1.0.8", - "define-properties": "^1.2.1", - "es-abstract": "^1.23.5", - "es-shim-unscopables": "^1.0.2" + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" }, "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, + "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": { - "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" + "@sec-ant/readable-stream": "^0.4.1", + "is-stream": "^4.0.1" }, "engines": { - "node": ">= 0.4" + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "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==", + "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": { - "array-buffer-byte-length": "^1.0.1", - "call-bind": "^1.0.8", - "define-properties": "^1.2.1", - "es-abstract": "^1.23.5", + "call-bound": "^1.0.3", "es-errors": "^1.3.0", - "get-intrinsic": "^1.2.6", - "is-array-buffer": "^3.0.4" + "get-intrinsic": "^1.2.6" }, "engines": { "node": ">= 0.4" @@ -2940,41 +13233,64 @@ "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==", + "node_modules/get-tsconfig": { + "version": "4.13.7", + "resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.13.7.tgz", + "integrity": "sha512-7tN6rFgBlMgpBML5j8typ92BKFi2sFQvIdpAqLA2beia5avZDrMs0FLZiM5etShWq5irVyGcGMEA1jcDaK7A/Q==", "dev": true, "license": "MIT", - "engines": { - "node": ">=12" + "dependencies": { + "resolve-pkg-maps": "^1.0.0" + }, + "funding": { + "url": "https://github.com/privatenumber/get-tsconfig?sponsor=1" } }, - "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==", + "node_modules/giget": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/giget/-/giget-3.3.1.tgz", + "integrity": "sha512-r+mvuDjrjMpsdw46Kmeydb8bdHm7wOKw8wNBtTndkjbPjgAp5oUJUxRE76wZFknxIPokfWvep2qSXK37aXE6zg==", + "devOptional": true, + "license": "MIT", + "bin": { + "giget": "dist/cli.mjs" + } + }, + "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": "MIT" + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.3" + }, + "engines": { + "node": ">=10.13.0" + } }, - "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==", + "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": ">= 0.4" + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "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==", + "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": { - "possible-typed-array-names": "^1.0.0" + "define-properties": "^1.2.1", + "gopd": "^1.0.1" }, "engines": { "node": ">= 0.4" @@ -2983,140 +13299,110 @@ "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, + "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": ">= 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" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "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/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/bcryptjs": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/bcryptjs/-/bcryptjs-3.0.3.tgz", - "integrity": "sha512-GlF5wPWnSa/X5LKM1o0wz0suXIINz1iHRLvTS+sLyi7XPbe5ycmYI3DlZqVGZZtDgl4DmasFg7gOB3JYbphV5g==", - "license": "BSD-3-Clause", - "bin": { - "bcrypt": "bin/bcrypt" - } + "node_modules/grammex": { + "version": "3.1.13", + "resolved": "https://registry.npmjs.org/grammex/-/grammex-3.1.13.tgz", + "integrity": "sha512-LnPnhOBLEJEVKS8WFDVaA397L9Kq55Q9oSITJiVLHVdhAclfUkWzQv74KhvZHKL2Q09Pb1XdsrOsZ4LfTFFTEg==", + "devOptional": true, + "license": "MIT" }, - "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==", + "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/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", - "dependencies": { - "@clack/prompts": "^0.11.0" + "engines": { + "node": ">= 0.4" }, - "bin": { - "better-result": "bin/cli.mjs" + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "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==", + "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", - "dependencies": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" + "engines": { + "node": ">=8" } }, - "node_modules/busboy": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz", - "integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==", + "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": { - "streamsearch": "^1.1.0" + "es-define-property": "^1.0.0" }, - "engines": { - "node": ">=10.16.0" + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "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, + "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": { - "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" + "dunder-proto": "^1.0.0" }, - "peerDependencies": { - "magicast": "^0.3.5" + "engines": { + "node": ">= 0.4" }, - "peerDependenciesMeta": { - "magicast": { - "optional": true - } + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/c12/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", + "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": ">=12" + "node": ">= 0.4" }, "funding": { - "url": "https://dotenvx.com" + "url": "https://github.com/sponsors/ljharb" } }, - "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==", + "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": { - "call-bind-apply-helpers": "^1.0.0", - "es-define-property": "^1.0.0", - "get-intrinsic": "^1.2.4", - "set-function-length": "^1.2.2" + "has-symbols": "^1.0.3" }, "engines": { "node": ">= 0.4" @@ -3125,238 +13411,273 @@ "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==", - "dev": true, + "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": { - "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==", - "dev": true, + "node_modules/hast-util-to-jsx-runtime": { + "version": "2.3.6", + "resolved": "https://registry.npmjs.org/hast-util-to-jsx-runtime/-/hast-util-to-jsx-runtime-2.3.6.tgz", + "integrity": "sha512-zl6s8LwNyo1P9uw+XJGvZtdFF1GdAkOg8ujOw+4Pyb76874fLps4ueHXDhXWdk6YHQ6OgUtinliG7RsYvCbbBg==", + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0", + "@types/hast": "^3.0.0", + "@types/unist": "^3.0.0", + "comma-separated-tokens": "^2.0.0", + "devlop": "^1.0.0", + "estree-util-is-identifier-name": "^3.0.0", + "hast-util-whitespace": "^3.0.0", + "mdast-util-mdx-expression": "^2.0.0", + "mdast-util-mdx-jsx": "^3.0.0", + "mdast-util-mdxjs-esm": "^2.0.0", + "property-information": "^7.0.0", + "space-separated-tokens": "^2.0.0", + "style-to-js": "^1.0.0", + "unist-util-position": "^5.0.0", + "vfile-message": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-whitespace": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/hast-util-whitespace/-/hast-util-whitespace-3.0.0.tgz", + "integrity": "sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==", "license": "MIT", "dependencies": { - "call-bind-apply-helpers": "^1.0.2", - "get-intrinsic": "^1.3.0" - }, - "engines": { - "node": ">= 0.4" + "@types/hast": "^3.0.0" }, "funding": { - "url": "https://github.com/sponsors/ljharb" + "type": "opencollective", + "url": "https://opencollective.com/unified" } }, - "node_modules/callsites": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", - "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", + "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", - "engines": { - "node": ">=6" + "dependencies": { + "hermes-estree": "0.25.1" } }, - "node_modules/caniuse-lite": { - "version": "1.0.30001781", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001781.tgz", - "integrity": "sha512-RdwNCyMsNBftLjW6w01z8bKEvT6e/5tpPVEgtn22TiLGlstHOVecsX2KHFkD5e/vRnIE4EGzpuIODb3mtswtkw==", - "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, + "node_modules/hono": { + "version": "4.13.13", + "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.13.tgz", + "integrity": "sha512-CQ46U0ZkAGmbT/4UxdzzGJpacP2IeKgY4a5/tOI9AABbpOMfK739wfDXmv1usCk+3RkKj1hQy4/fjhiwa2xlrA==", "license": "MIT", "engines": { - "node": ">=18" + "node": ">=16.9.0" } }, - "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, + "node_modules/html-url-attributes": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/html-url-attributes/-/html-url-attributes-3.0.1.tgz", + "integrity": "sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "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": { - "ansi-styles": "^4.1.0", - "supports-color": "^7.1.0" + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" }, "engines": { - "node": ">=10" + "node": ">= 0.8" }, "funding": { - "url": "https://github.com/chalk/chalk?sponsor=1" + "type": "opencollective", + "url": "https://opencollective.com/express" } }, - "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" - }, + "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": { - "pnpm": ">=8" + "node": ">=18.18.0" } }, - "node_modules/chokidar": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz", - "integrity": "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==", - "devOptional": true, + "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": { - "readdirp": "^4.0.1" + "safer-buffer": ">= 2.1.2 < 3.0.0" }, "engines": { - "node": ">= 14.16.0" + "node": ">=0.10.0" }, "funding": { - "url": "https://paulmillr.com/funding/" + "type": "opencollective", + "url": "https://opencollective.com/express" } }, - "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, + "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", - "dependencies": { - "consola": "^3.2.3" + "engines": { + "node": ">= 4" } }, - "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/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/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==", + "node_modules/import-fresh": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz", + "integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==", "dev": true, "license": "MIT", "dependencies": { - "color-name": "~1.1.4" + "parent-module": "^1.0.0", + "resolve-from": "^4.0.0" }, "engines": { - "node": ">=7.0.0" + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "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==", + "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" + "license": "MIT", + "engines": { + "node": ">=0.8.19" + } }, - "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/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/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, + "node_modules/inline-style-parser": { + "version": "0.2.7", + "resolved": "https://registry.npmjs.org/inline-style-parser/-/inline-style-parser-0.2.7.tgz", + "integrity": "sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA==", "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, + "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": "^14.18.0 || >=16.10.0" + "node": ">= 0.4" } }, - "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==", - "dev": true, - "license": "MIT" + "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/cookie": { - "version": "0.7.2", - "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", - "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "node_modules/ip-address": { + "version": "10.7.4", + "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.4.tgz", + "integrity": "sha512-DWBMKyeM25D70nrIiTkgQth59/G+naKOTep6huF9j+GmeK3DMD60Zvxg5d5qQnz+38AHgou6ean2LECX+lrKDg==", "license": "MIT", "engines": { - "node": ">= 0.6" + "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-alphabetical": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-alphabetical/-/is-alphabetical-2.0.1.tgz", + "integrity": "sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" } }, - "node_modules/cross-spawn": { - "version": "7.0.6", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", - "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", - "devOptional": true, + "node_modules/is-alphanumerical": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-alphanumerical/-/is-alphanumerical-2.0.1.tgz", + "integrity": "sha512-hmbYhX/9MUMF5uh7tOXyK/n0ZvWpad5caBA17GsC6vyuCqaWliRG5K1qS9inmUhEMaOBIW7/whAnSwveW/LtZw==", "license": "MIT", "dependencies": { - "path-key": "^3.1.0", - "shebang-command": "^2.0.0", - "which": "^2.0.1" + "is-alphabetical": "^2.0.0", + "is-decimal": "^2.0.0" }, - "engines": { - "node": ">= 8" + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" } }, - "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/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-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==", + "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", - "es-errors": "^1.3.0", - "is-data-view": "^1.0.2" + "get-intrinsic": "^1.2.6" }, "engines": { "node": ">= 0.4" @@ -3365,34 +13686,34 @@ "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==", + "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", - "es-errors": "^1.3.0", - "is-data-view": "^1.0.2" + "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/inspect-js" + "url": "https://github.com/sponsors/ljharb" } }, - "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==", + "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": { - "call-bound": "^1.0.2", - "es-errors": "^1.3.0", - "is-data-view": "^1.0.1" + "has-bigints": "^1.0.2" }, "engines": { "node": ">= 0.4" @@ -3401,43 +13722,52 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/debug": { - "version": "3.2.7", - "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", - "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "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": { - "ms": "^2.1.1" + "call-bound": "^1.0.3", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "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==", + "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" + "license": "MIT", + "dependencies": { + "semver": "^7.7.1" + } }, - "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", + "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": ">=16.0.0" + "node": ">=10" } }, - "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==", + "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", - "dependencies": { - "es-define-property": "^1.0.0", - "es-errors": "^1.3.0", - "gopd": "^1.0.1" - }, "engines": { "node": ">= 0.4" }, @@ -3445,16 +13775,14 @@ "url": "https://github.com/sponsors/ljharb" } }, - "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==", + "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": { - "define-data-property": "^1.0.1", - "has-property-descriptors": "^1.0.0", - "object-keys": "^1.1.1" + "hasown": "^2.0.2" }, "engines": { "node": ">= 0.4" @@ -3463,190 +13791,103 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/defu": { - "version": "6.1.4", - "resolved": "https://registry.npmjs.org/defu/-/defu-6.1.4.tgz", - "integrity": "sha512-mEQCMmwJu317oSz8CwdIOdwf3xMif1ttiM8LTufzc3g6kR+9Pe236twL8j3IYT1F7GfRgGcW6MWxzZjLIkuHIg==", - "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/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==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">=8" - } - }, - "node_modules/doctrine": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz", - "integrity": "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==", + "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": "Apache-2.0", + "license": "MIT", "dependencies": { - "esutils": "^2.0.2" + "call-bound": "^1.0.2", + "get-intrinsic": "^1.2.6", + "is-typed-array": "^1.1.13" }, "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/dotenv": { - "version": "17.4.2", - "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.4.2.tgz", - "integrity": "sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=12" + "node": ">= 0.4" }, "funding": { - "url": "https://dotenvx.com" + "url": "https://github.com/sponsors/ljharb" } }, - "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==", + "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-bind-apply-helpers": "^1.0.1", - "es-errors": "^1.3.0", - "gopd": "^1.2.0" + "call-bound": "^1.0.2", + "has-tostringtag": "^1.0.2" }, "engines": { "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/eastasianwidth": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", - "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==", - "dev": true, - "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, + "node_modules/is-decimal": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-decimal/-/is-decimal-2.0.1.tgz", + "integrity": "sha512-AAB9hiomQs5DXWcRB1rqsxGUstbRroFOPPVAomNk/3XHR5JyEZChOyTWe2oayKnsSsr/kcGqF+z6yuH6HHpN0A==", "license": "MIT", - "dependencies": { - "@standard-schema/spec": "^1.0.0", - "fast-check": "^3.23.1" + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" } }, - "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/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/empathic": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/empathic/-/empathic-2.0.0.tgz", - "integrity": "sha512-i6UzDscO/XfAcNYD75CfICkmfLedpyPDdozrLMmQc5ORaQcdMoc21OnlEylMIqI7U8eniKrPMxxtj8k0vhmJhA==", - "devOptional": true, + "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": ">=14" + "node": ">=0.10.0" } }, - "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, + "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": "^12.20.0 || ^14.13.1 || >=16.0.0" + "node": ">= 0.4" }, "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "url": "https://github.com/sponsors/ljharb" } }, - "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==", + "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": { - "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", + "generator-function": "^2.0.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" + "has-tostringtag": "^1.0.2", + "safe-regex-test": "^1.1.0" }, "engines": { "node": ">= 0.4" @@ -3655,114 +13896,114 @@ "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==", - "dev": true, + "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.4" + "node": ">=0.10.0" } }, - "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==", - "dev": true, + "node_modules/is-hexadecimal": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-hexadecimal/-/is-hexadecimal-2.0.1.tgz", + "integrity": "sha512-DgZQp241c8oO6cA1SbTEWiXeoxV42vlcJxgH+B3hi1AiqqKruZR3ZGF8In3fj4+/y/7rHvlOZLZtgJ/4ttYGZg==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "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": ">= 0.4" + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "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, + "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": { - "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" + "is-docker": "^3.0.0" + }, + "bin": { + "is-inside-container": "cli.js" }, "engines": { - "node": ">= 0.4" + "node": ">=14.16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/es-module-lexer": { + "node_modules/is-interactive": { "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" + "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/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==", + "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", - "dependencies": { - "es-errors": "^1.3.0" - }, "engines": { "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "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==", + "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", - "dependencies": { - "es-errors": "^1.3.0", - "get-intrinsic": "^1.2.6", - "has-tostringtag": "^1.0.2", - "hasown": "^2.0.2" - }, "engines": { "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "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, + "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", - "dependencies": { - "hasown": "^2.0.2" - }, "engines": { - "node": ">= 0.4" + "node": ">=0.12.0" } }, - "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==", + "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": { - "is-callable": "^1.2.7", - "is-date-object": "^1.0.5", - "is-symbol": "^1.0.4" + "call-bound": "^1.0.3", + "has-tostringtag": "^1.0.2" }, "engines": { "node": ">= 0.4" @@ -3771,355 +14012,196 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/esbuild": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.7.tgz", - "integrity": "sha512-IxpibTjyVnmrIQo5aqNpCgoACA/dTKLTlhMHihVHhdkxKyPO1uBBthumT0rdHmcsk9uMonIWS0m4FljWzILh3w==", - "dev": true, - "hasInstallScript": true, + "node_modules/is-obj": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-obj/-/is-obj-2.0.0.tgz", + "integrity": "sha512-drqDG3cbczxxEJRoOXcOjtdp1J/lyp1mNn0xaznRs8+muBhgQcrnbspox5X5fOw0HnMnbfDzvnEMEtqDEJEo8w==", "license": "MIT", - "bin": { - "esbuild": "bin/esbuild" - }, "engines": { - "node": ">=18" - }, - "optionalDependencies": { - "@esbuild/aix-ppc64": "0.27.7", - "@esbuild/android-arm": "0.27.7", - "@esbuild/android-arm64": "0.27.7", - "@esbuild/android-x64": "0.27.7", - "@esbuild/darwin-arm64": "0.27.7", - "@esbuild/darwin-x64": "0.27.7", - "@esbuild/freebsd-arm64": "0.27.7", - "@esbuild/freebsd-x64": "0.27.7", - "@esbuild/linux-arm": "0.27.7", - "@esbuild/linux-arm64": "0.27.7", - "@esbuild/linux-ia32": "0.27.7", - "@esbuild/linux-loong64": "0.27.7", - "@esbuild/linux-mips64el": "0.27.7", - "@esbuild/linux-ppc64": "0.27.7", - "@esbuild/linux-riscv64": "0.27.7", - "@esbuild/linux-s390x": "0.27.7", - "@esbuild/linux-x64": "0.27.7", - "@esbuild/netbsd-arm64": "0.27.7", - "@esbuild/netbsd-x64": "0.27.7", - "@esbuild/openbsd-arm64": "0.27.7", - "@esbuild/openbsd-x64": "0.27.7", - "@esbuild/openharmony-arm64": "0.27.7", - "@esbuild/sunos-x64": "0.27.7", - "@esbuild/win32-arm64": "0.27.7", - "@esbuild/win32-ia32": "0.27.7", - "@esbuild/win32-x64": "0.27.7" + "node": ">=8" } }, - "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, + "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": ">=10" + "node": ">=12" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/eslint": { - "version": "8.57.1", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.57.1.tgz", - "integrity": "sha512-ypowyDxpVSYpkXr9WPv2PAZCtNip1Mv5KTW0SCurXv/9iOpcrH9PaqUElksqEB6pChqHGDRCFTyrZlGhnLNGiA==", - "deprecated": "This version is no longer supported. Please see https://eslint.org/version-support for other options.", + "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": { - "@eslint-community/eslint-utils": "^4.2.0", - "@eslint-community/regexpp": "^4.6.1", - "@eslint/eslintrc": "^2.1.4", - "@eslint/js": "8.57.1", - "@humanwhocodes/config-array": "^0.13.0", - "@humanwhocodes/module-importer": "^1.0.1", - "@nodelib/fs.walk": "^1.2.8", - "@ungap/structured-clone": "^1.2.0", - "ajv": "^6.12.4", - "chalk": "^4.0.0", - "cross-spawn": "^7.0.2", - "debug": "^4.3.2", - "doctrine": "^3.0.0", - "escape-string-regexp": "^4.0.0", - "eslint-scope": "^7.2.2", - "eslint-visitor-keys": "^3.4.3", - "espree": "^9.6.1", - "esquery": "^1.4.2", - "esutils": "^2.0.2", - "fast-deep-equal": "^3.1.3", - "file-entry-cache": "^6.0.1", - "find-up": "^5.0.0", - "glob-parent": "^6.0.2", - "globals": "^13.19.0", - "graphemer": "^1.4.0", - "ignore": "^5.2.0", - "imurmurhash": "^0.1.4", - "is-glob": "^4.0.0", - "is-path-inside": "^3.0.3", - "js-yaml": "^4.1.0", - "json-stable-stringify-without-jsonify": "^1.0.1", - "levn": "^0.4.1", - "lodash.merge": "^4.6.2", - "minimatch": "^3.1.2", - "natural-compare": "^1.4.0", - "optionator": "^0.9.3", - "strip-ansi": "^6.0.1", - "text-table": "^0.2.0" - }, - "bin": { - "eslint": "bin/eslint.js" + "call-bound": "^1.0.2", + "gopd": "^1.2.0", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" }, "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + "node": ">= 0.4" }, "funding": { - "url": "https://opencollective.com/eslint" + "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/eslint-config-next": { - "version": "14.2.35", - "resolved": "https://registry.npmjs.org/eslint-config-next/-/eslint-config-next-14.2.35.tgz", - "integrity": "sha512-BpLsv01UisH193WyT/1lpHqq5iJ/Orfz9h/NOOlAmTUq4GY349PextQ62K4XpnaM9supeiEn3TaOTeQO07gURg==", - "dev": true, + "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", - "dependencies": { - "@next/eslint-plugin-next": "14.2.35", - "@rushstack/eslint-patch": "^1.3.3", - "@typescript-eslint/eslint-plugin": "^5.4.2 || ^6.0.0 || ^7.0.0 || ^8.0.0", - "@typescript-eslint/parser": "^5.4.2 || ^6.0.0 || ^7.0.0 || ^8.0.0", - "eslint-import-resolver-node": "^0.3.6", - "eslint-import-resolver-typescript": "^3.5.2", - "eslint-plugin-import": "^2.28.1", - "eslint-plugin-jsx-a11y": "^6.7.1", - "eslint-plugin-react": "^7.33.2", - "eslint-plugin-react-hooks": "^4.5.0 || 5.0.0-canary-7118f5dd7-20230705" - }, - "peerDependencies": { - "eslint": "^7.23.0 || ^8.0.0", - "typescript": ">=3.3.1" + "engines": { + "node": ">=12" }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } + "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==", + "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", - "dependencies": { - "debug": "^3.2.7", - "is-core-module": "^2.13.0", - "resolve": "^1.22.4" + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "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==", + "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": "ISC", + "license": "MIT", "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" + "call-bound": "^1.0.3" }, "engines": { - "node": "^14.18.0 || >=16.0.0" + "node": ">= 0.4" }, "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 - } + "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/eslint-import-resolver-typescript/node_modules/debug": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", - "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", - "dev": true, + "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", - "dependencies": { - "ms": "^2.1.3" - }, "engines": { - "node": ">=6.0" + "node": ">=18" }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "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==", + "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": { - "debug": "^3.2.7" + "call-bound": "^1.0.3", + "has-tostringtag": "^1.0.2" }, "engines": { - "node": ">=4" + "node": ">= 0.4" }, - "peerDependenciesMeta": { - "eslint": { - "optional": true - } + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "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==", + "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": { - "@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" + "call-bound": "^1.0.2", + "has-symbols": "^1.1.0", + "safe-regex-test": "^1.1.0" }, "engines": { - "node": ">=4" + "node": ">= 0.4" }, - "peerDependencies": { - "eslint": "^2 || ^3 || ^4 || ^5 || ^6 || ^7.2.0 || ^8 || ^9" + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "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==", + "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": { - "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" + "which-typed-array": "^1.1.16" }, "engines": { - "node": ">=4.0" + "node": ">= 0.4" }, - "peerDependencies": { - "eslint": "^3 || ^4 || ^5 || ^6 || ^7 || ^8 || ^9" + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "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, + "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", - "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" + "node": ">=18" }, - "peerDependencies": { - "eslint": "^3 || ^4 || ^5 || ^6 || ^7 || ^8 || ^9.7" + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/eslint-plugin-react-hooks": { - "version": "5.0.0-canary-7118f5dd7-20230705", - "resolved": "https://registry.npmjs.org/eslint-plugin-react-hooks/-/eslint-plugin-react-hooks-5.0.0-canary-7118f5dd7-20230705.tgz", - "integrity": "sha512-AZYbMo/NW9chdL7vk6HQzQhT+PvTAEVqWk9ziruUoW2kAOcN5qNyelv70e0F1VNQAbvutOC9oc+xfWycI9FxDw==", + "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": ">=10" + "node": ">= 0.4" }, - "peerDependencies": { - "eslint": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0" + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "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==", + "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": { - "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" + "call-bound": "^1.0.3" }, "engines": { "node": ">= 0.4" @@ -4128,364 +14210,529 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/eslint-scope": { - "version": "7.2.2", - "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-7.2.2.tgz", - "integrity": "sha512-dOt21O7lTMhDM+X9mB4GX+DZrZtCUJPL/wlcTqxyrx5IvO0IYtILdtrQGQp+8n5S0gwSVmOf9NQrjMOgfQZlIg==", + "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": "BSD-2-Clause", + "license": "MIT", "dependencies": { - "esrecurse": "^4.3.0", - "estraverse": "^5.2.0" + "call-bound": "^1.0.3", + "get-intrinsic": "^1.2.6" }, "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + "node": ">= 0.4" }, "funding": { - "url": "https://opencollective.com/eslint" + "url": "https://github.com/sponsors/ljharb" } }, - "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", + "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": "^18.18.0 || ^20.9.0 || >=21.1.0" + "node": ">=16" }, "funding": { - "url": "https://opencollective.com/eslint" + "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/eslint/node_modules/@eslint/eslintrc": { - "version": "2.1.4", - "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-2.1.4.tgz", - "integrity": "sha512-269Z39MS6wVJtsoUl10L60WdkhJVdPG24Q4eZTH3nnF6lpvSShEK3wQjDX9JRWAUPvPh7COouPpU9IrqaZFvtQ==", + "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": { - "ajv": "^6.12.4", - "debug": "^4.3.2", - "espree": "^9.6.0", - "globals": "^13.19.0", - "ignore": "^5.2.0", - "import-fresh": "^3.2.1", - "js-yaml": "^4.1.0", - "minimatch": "^3.1.2", - "strip-json-comments": "^3.1.1" + "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": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, + "node": ">= 0.4" + } + }, + "node_modules/jiti": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz", + "integrity": "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==", + "devOptional": true, + "license": "MIT", + "bin": { + "jiti": "lib/jiti-cli.mjs" + } + }, + "node_modules/jose": { + "version": "4.15.9", + "resolved": "https://registry.npmjs.org/jose/-/jose-4.15.9.tgz", + "integrity": "sha512-1vUQX+IdDMVPj4k8kOxgUqlcK518yluMuGZwqlr44FS1ppZB/5GWh4rZG89erpOBOJjU/OBsnCVFfapsRz6nEA==", + "license": "MIT", "funding": { - "url": "https://opencollective.com/eslint" + "url": "https://github.com/sponsors/panva" } }, - "node_modules/eslint/node_modules/ajv": { - "version": "6.14.0", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.14.0.tgz", - "integrity": "sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw==", + "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.3.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz", + "integrity": "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==", "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/nodeca" + } + ], "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" + "argparse": "^2.0.1" }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/epoberezkin" + "bin": { + "js-yaml": "bin/js-yaml.js" } }, - "node_modules/eslint/node_modules/debug": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", - "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", - "dev": true, + "node_modules/jsesc": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", + "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", "license": "MIT", - "dependencies": { - "ms": "^2.1.3" + "bin": { + "jsesc": "bin/jsesc" }, "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } + "node": ">=6" } }, - "node_modules/eslint/node_modules/doctrine": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-3.0.0.tgz", - "integrity": "sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==", + "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": "Apache-2.0", - "dependencies": { - "esutils": "^2.0.2" + "license": "MIT" + }, + "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/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.0.0" + "node": ">=6" } }, - "node_modules/eslint/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" + "node_modules/jsonfile": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz", + "integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==", + "license": "MIT", + "dependencies": { + "universalify": "^2.0.0" }, - "funding": { - "url": "https://opencollective.com/eslint" + "optionalDependencies": { + "graceful-fs": "^4.1.6" } }, - "node_modules/eslint/node_modules/espree": { - "version": "9.6.1", - "resolved": "https://registry.npmjs.org/espree/-/espree-9.6.1.tgz", - "integrity": "sha512-oruZaFkjorTpF32kDSI5/75ViwGeZginGGy2NoOSg3Q9bnwlnmDm4HLnkl0RE3n+njDXR037aY1+x58Z/zFdwQ==", + "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": "BSD-2-Clause", + "license": "MIT", "dependencies": { - "acorn": "^8.9.0", - "acorn-jsx": "^5.3.2", - "eslint-visitor-keys": "^3.4.1" + "array-includes": "^3.1.6", + "array.prototype.flat": "^1.3.1", + "object.assign": "^4.1.4", + "object.values": "^1.1.6" }, "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" + "node": ">=4.0" } }, - "node_modules/eslint/node_modules/globals": { - "version": "13.24.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-13.24.0.tgz", - "integrity": "sha512-AhO5QUcj8llrbG09iWhPU2B204J1xnPeL8kQmVorSsy+Sjj1sk8gIyh6cUocGmH4L0UuhAJy+hJMRA4mgA4mFQ==", + "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": { - "type-fest": "^0.20.2" - }, + "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": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "node": ">=6" } }, - "node_modules/eslint/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==", + "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": "MIT" + "license": "CC0-1.0" }, - "node_modules/espree": { - "version": "10.4.0", - "resolved": "https://registry.npmjs.org/espree/-/espree-10.4.0.tgz", - "integrity": "sha512-j6PAQ2uUr79PZhBjP5C5fhl8e39FmRnOjsD5lGnWrFU8i2G776tBK7+nP8KuQUTTyAZUwfQqXAgrVH5MbH9CYQ==", + "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": "BSD-2-Clause", + "license": "MIT", "dependencies": { - "acorn": "^8.15.0", - "acorn-jsx": "^5.3.2", - "eslint-visitor-keys": "^4.2.1" + "language-subtag-registry": "^0.3.20" }, "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" + "node": ">=0.10" } }, - "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==", + "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": "BSD-3-Clause", + "license": "MIT", "dependencies": { - "estraverse": "^5.1.0" + "prelude-ls": "^1.2.1", + "type-check": "~0.4.0" }, "engines": { - "node": ">=0.10" + "node": ">= 0.8.0" } }, - "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==", + "node_modules/lightningcss": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", + "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", "dev": true, - "license": "BSD-2-Clause", + "license": "MPL-2.0", "dependencies": { - "estraverse": "^5.2.0" + "detect-libc": "^2.0.3" }, "engines": { - "node": ">=4.0" + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.33.0", + "lightningcss-darwin-arm64": "1.33.0", + "lightningcss-darwin-x64": "1.33.0", + "lightningcss-freebsd-x64": "1.33.0", + "lightningcss-linux-arm-gnueabihf": "1.33.0", + "lightningcss-linux-arm64-gnu": "1.33.0", + "lightningcss-linux-arm64-musl": "1.33.0", + "lightningcss-linux-x64-gnu": "1.33.0", + "lightningcss-linux-x64-musl": "1.33.0", + "lightningcss-win32-arm64-msvc": "1.33.0", + "lightningcss-win32-x64-msvc": "1.33.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==", + "node_modules/lightningcss-android-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", + "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", + "cpu": [ + "arm64" + ], "dev": true, - "license": "BSD-2-Clause", + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], "engines": { - "node": ">=4.0" + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" } }, - "node_modules/estree-walker": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", - "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "node_modules/lightningcss-darwin-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", + "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", + "cpu": [ + "arm64" + ], "dev": true, - "license": "MIT", - "dependencies": { - "@types/estree": "^1.0.0" + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" } }, - "node_modules/esutils": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", - "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", + "node_modules/lightningcss-darwin-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", + "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", + "cpu": [ + "x64" + ], "dev": true, - "license": "BSD-2-Clause", + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], "engines": { - "node": ">=0.10.0" + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" } }, - "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==", + "node_modules/lightningcss-freebsd-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", + "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", + "cpu": [ + "x64" + ], "dev": true, - "license": "Apache-2.0", + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], "engines": { - "node": ">=12.0.0" + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" } }, - "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" - } + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", + "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" ], - "license": "MIT", - "dependencies": { - "pure-rand": "^6.1.0" - }, "engines": { - "node": ">=8.0.0" + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" } }, - "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==", - "devOptional": true, - "license": "MIT" - }, - "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==", + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", + "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", + "cpu": [ + "arm64" + ], "dev": true, - "license": "MIT" + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } }, - "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==", + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", + "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", + "cpu": [ + "arm64" + ], "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==", - "devOptional": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/fastify" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fastify" - } + "libc": [ + "musl" ], - "license": "BSD-3-Clause" + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } }, - "node_modules/fastq": { - "version": "1.20.1", - "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.20.1.tgz", - "integrity": "sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw==", + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", + "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", + "cpu": [ + "x64" + ], "dev": true, - "license": "ISC", - "dependencies": { - "reusify": "^1.0.4" + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" } }, - "node_modules/fdir": { - "version": "6.5.0", - "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", - "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", + "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", + "cpu": [ + "x64" + ], "dev": true, - "license": "MIT", + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], "engines": { - "node": ">=12.0.0" + "node": ">= 12.0.0" }, - "peerDependencies": { - "picomatch": "^3 || ^4" + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", + "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" }, - "peerDependenciesMeta": { - "picomatch": { - "optional": true - } + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" } }, - "node_modules/file-entry-cache": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-6.0.1.tgz", - "integrity": "sha512-7Gps/XWymbLk2QLYK4NzpMOrYjMhdIxXuIvy2QBsLE6ljuodKvdkWs/cpyJJ3CVIVpH0Oi1Hvg1ovbMzLdFBBg==", + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", + "cpu": [ + "x64" + ], "dev": true, - "license": "MIT", - "dependencies": { - "flat-cache": "^3.0.4" - }, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], "engines": { - "node": "^10.12.0 || >=12.0.0" + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" } }, - "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==", + "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": { - "locate-path": "^6.0.0", - "path-exists": "^4.0.0" + "p-locate": "^5.0.0" }, "engines": { "node": ">=10" @@ -4494,2577 +14741,3085 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/flat-cache": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-3.2.0.tgz", - "integrity": "sha512-CYcENa+FtcUKLmhhqyctpclsq7QF38pKjZHsGNiSQF5r4FtoKDWabFDl3hzaEQMvT1LHEysw5twgLvpYYb4vbw==", - "dev": true, - "license": "MIT", - "dependencies": { - "flatted": "^3.2.9", - "keyv": "^4.5.3", - "rimraf": "^3.0.2" - }, - "engines": { - "node": "^10.12.0 || >=12.0.0" - } + "node_modules/lodash": { + "version": "4.18.1", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz", + "integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==", + "devOptional": true, + "license": "MIT" }, - "node_modules/flatted": { - "version": "3.4.2", - "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.4.2.tgz", - "integrity": "sha512-PjDse7RzhcPkIJwy5t7KPWQSZ9cAbzQXcafsetQoD7sOJRQlGikNbx7yZp2OotDnJyrDcbyRq3Ttb18iYOqkxA==", + "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": "ISC" + "license": "MIT" }, - "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, + "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": { - "is-callable": "^1.2.7" + "chalk": "^5.3.0", + "is-unicode-supported": "^1.3.0" }, "engines": { - "node": ">= 0.4" + "node": ">=18" }, "funding": { - "url": "https://github.com/sponsors/ljharb" + "url": "https://github.com/sponsors/sindresorhus" } }, - "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" - }, + "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": ">=14" + "node": "^12.17.0 || ^14.13 || >=16.0.0" }, "funding": { - "url": "https://github.com/sponsors/isaacs" + "url": "https://github.com/chalk/chalk?sponsor=1" } }, - "node_modules/fs.realpath": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", - "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", - "dev": true, - "license": "ISC" - }, - "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, + "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", - "optional": true, - "os": [ - "darwin" - ], "engines": { - "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "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==", - "dev": true, + "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/longest-streak": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/longest-streak/-/longest-streak-3.1.0.tgz", + "integrity": "sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g==", "license": "MIT", "funding": { - "url": "https://github.com/sponsors/ljharb" + "type": "github", + "url": "https://github.com/sponsors/wooorm" } }, - "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==", + "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": { - "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" + "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-cache/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/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": { - "node": ">= 0.4" + "bun": ">=1.0.0", + "deno": ">=1.30.0", + "node": ">=8.0.0" }, "funding": { - "url": "https://github.com/sponsors/ljharb" + "type": "github", + "url": "https://github.com/sponsors/wellwelwel" } }, - "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==", + "node_modules/lucide-react": { + "version": "1.55.0", + "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-1.55.0.tgz", + "integrity": "sha512-bSozQHiI3/8q7JvgoqVRGOYUi7fYT3siAZwmZsljjsOH2Husp/2ODdFf/leD+ZC/2yKfn7r8oh6yeoR3ITR5vA==", + "license": "ISC", + "peerDependencies": { + "@types/react": "*", + "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "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", - "funding": { - "url": "https://github.com/sponsors/ljharb" + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" } }, - "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, + "node_modules/markdown-table": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/markdown-table/-/markdown-table-3.0.4.tgz", + "integrity": "sha512-wiYz4+JrLyb/DqW2hkFJxP7Vd7JuTDm77fvbM8VfEQdmSMqcImWeeRbHwZjBjIFki/VaMK2BhFi7oUUZeM5bqw==", "license": "MIT", - "dependencies": { - "is-property": "^1.0.2" + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" } }, - "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, + "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/get-intrinsic": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", - "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", - "dev": true, + "node_modules/mdast-util-find-and-replace": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/mdast-util-find-and-replace/-/mdast-util-find-and-replace-3.0.3.tgz", + "integrity": "sha512-xPgpDNl0/OXHsI7TlaIs22lWnH3KlpvZdXG1ET/m/YT2Hhdkx8lJV4kLphE6l9simyM4KPDFBwas08BgEob6Jw==", "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" + "@types/mdast": "^4.0.0", + "escape-string-regexp": "^5.0.0", + "unist-util-is": "^6.0.0", + "unist-util-visit-parents": "^6.0.0" }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdast-util-find-and-replace/node_modules/escape-string-regexp": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-5.0.0.tgz", + "integrity": "sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw==", + "license": "MIT", "engines": { - "node": ">= 0.4" + "node": ">=12" }, "funding": { - "url": "https://github.com/sponsors/ljharb" + "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/mdast-util-from-markdown": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mdast-util-from-markdown/-/mdast-util-from-markdown-2.1.0.tgz", + "integrity": "sha512-KRLgmPaP2H1ul2bpoJkOS+9pAcDAAj9Nu1mqLnh8NLeJG5tlvj42TH80PIGBpROWlRXLk0lDrWNuZCFy/tsB4A==", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "@types/unist": "^3.0.0", + "decode-named-character-reference": "^1.0.0", + "devlop": "^1.0.0", + "mdast-util-to-string": "^4.0.0", + "micromark": "^4.0.0", + "micromark-util-decode-numeric-character-reference": "^2.0.0", + "micromark-util-decode-string": "^2.0.0", + "micromark-util-normalize-identifier": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0", + "unist-util-stringify-position": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } }, - "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==", - "dev": true, + "node_modules/mdast-util-gfm": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/mdast-util-gfm/-/mdast-util-gfm-3.1.0.tgz", + "integrity": "sha512-0ulfdQOM3ysHhCJ1p06l0b0VKlhU0wuQs3thxZQagjcjPrlFRqY215uZGHHJan9GEAXd9MbfPjFJz+qMkVR6zQ==", + "license": "MIT", + "dependencies": { + "mdast-util-from-markdown": "^2.0.0", + "mdast-util-gfm-autolink-literal": "^2.0.0", + "mdast-util-gfm-footnote": "^2.0.0", + "mdast-util-gfm-strikethrough": "^2.0.0", + "mdast-util-gfm-table": "^2.0.0", + "mdast-util-gfm-task-list-item": "^2.0.0", + "mdast-util-to-markdown": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdast-util-gfm-autolink-literal": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/mdast-util-gfm-autolink-literal/-/mdast-util-gfm-autolink-literal-2.0.1.tgz", + "integrity": "sha512-5HVP2MKaP6L+G6YaxPNjuL0BPrq9orG3TsrZ9YXbA3vDw/ACI4MEsnoDpn6ZNm7GnZgtAcONJyPhOP8tNJQavQ==", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "ccount": "^2.0.0", + "devlop": "^1.0.0", + "mdast-util-find-and-replace": "^3.0.0", + "micromark-util-character": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdast-util-gfm-footnote": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mdast-util-gfm-footnote/-/mdast-util-gfm-footnote-2.1.0.tgz", + "integrity": "sha512-sqpDWlsHn7Ac9GNZQMeUzPQSMzR6Wv0WKRNvQRg0KqHh02fpTz69Qc1QSseNX29bhz1ROIyNyxExfawVKTm1GQ==", "license": "MIT", "dependencies": { - "dunder-proto": "^1.0.1", - "es-object-atoms": "^1.0.0" + "@types/mdast": "^4.0.0", + "devlop": "^1.1.0", + "mdast-util-from-markdown": "^2.0.0", + "mdast-util-to-markdown": "^2.0.0", + "micromark-util-normalize-identifier": "^2.0.0" }, - "engines": { - "node": ">= 0.4" + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" } }, - "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, + "node_modules/mdast-util-gfm-strikethrough": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/mdast-util-gfm-strikethrough/-/mdast-util-gfm-strikethrough-2.0.1.tgz", + "integrity": "sha512-OuJHqvr455pwu2OaOrir7dbzqs4jlWKOtlu9L6GjcIjjQwNyw02VntQsr/Ek6/A13vgnXfUhBekWRUP1OkNivw==", "license": "MIT", "dependencies": { - "call-bound": "^1.0.3", - "es-errors": "^1.3.0", - "get-intrinsic": "^1.2.6" - }, - "engines": { - "node": ">= 0.4" + "@types/mdast": "^4.0.0", + "mdast-util-from-markdown": "^2.0.0", + "mdast-util-to-markdown": "^2.0.0" }, "funding": { - "url": "https://github.com/sponsors/ljharb" + "type": "opencollective", + "url": "https://opencollective.com/unified" } }, - "node_modules/get-tsconfig": { - "version": "4.13.7", - "resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.13.7.tgz", - "integrity": "sha512-7tN6rFgBlMgpBML5j8typ92BKFi2sFQvIdpAqLA2beia5avZDrMs0FLZiM5etShWq5irVyGcGMEA1jcDaK7A/Q==", - "dev": true, + "node_modules/mdast-util-gfm-table": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/mdast-util-gfm-table/-/mdast-util-gfm-table-2.0.0.tgz", + "integrity": "sha512-78UEvebzz/rJIxLvE7ZtDd/vIQ0RHv+3Mh5DR96p7cS7HsBhYIICDBCu8csTNWNO6tBWfqXPWekRuj2FNOGOZg==", "license": "MIT", "dependencies": { - "resolve-pkg-maps": "^1.0.0" + "@types/mdast": "^4.0.0", + "devlop": "^1.0.0", + "markdown-table": "^3.0.0", + "mdast-util-from-markdown": "^2.0.0", + "mdast-util-to-markdown": "^2.0.0" }, "funding": { - "url": "https://github.com/privatenumber/get-tsconfig?sponsor=1" + "type": "opencollective", + "url": "https://opencollective.com/unified" } }, - "node_modules/giget": { + "node_modules/mdast-util-gfm-task-list-item": { "version": "2.0.0", - "resolved": "https://registry.npmjs.org/giget/-/giget-2.0.0.tgz", - "integrity": "sha512-L5bGsVkxJbJgdnwyuheIunkGatUF/zssUoxxjACCseZYAVbaqdh9Tsmmlkl8vYan09H7sbvKt4pS8GqKLBrEzA==", - "devOptional": true, + "resolved": "https://registry.npmjs.org/mdast-util-gfm-task-list-item/-/mdast-util-gfm-task-list-item-2.0.0.tgz", + "integrity": "sha512-IrtvNvjxC1o06taBAVJznEnkiHxLFTzgonUdy8hzFVeDun0uTjxxrRGVaNFqkU1wJR3RBPEfsxmU6jDWPofrTQ==", "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" + "@types/mdast": "^4.0.0", + "devlop": "^1.0.0", + "mdast-util-from-markdown": "^2.0.0", + "mdast-util-to-markdown": "^2.0.0" }, - "bin": { - "giget": "dist/cli.mjs" + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" } }, - "node_modules/glob": { - "version": "7.2.3", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", - "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", - "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", - "dev": true, - "license": "ISC", + "node_modules/mdast-util-mdx-expression": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/mdast-util-mdx-expression/-/mdast-util-mdx-expression-2.0.1.tgz", + "integrity": "sha512-J6f+9hUp+ldTZqKRSg7Vw5V6MqjATc+3E4gf3CFNcuZNWD8XdyI6zQ8GqH7f8169MM6P7hMBRDVGnn7oHB9kXQ==", + "license": "MIT", "dependencies": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.1.1", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - }, - "engines": { - "node": "*" + "@types/estree-jsx": "^1.0.0", + "@types/hast": "^3.0.0", + "@types/mdast": "^4.0.0", + "devlop": "^1.0.0", + "mdast-util-from-markdown": "^2.0.0", + "mdast-util-to-markdown": "^2.0.0" }, "funding": { - "url": "https://github.com/sponsors/isaacs" + "type": "opencollective", + "url": "https://opencollective.com/unified" } }, - "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" + "node_modules/mdast-util-mdx-jsx": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/mdast-util-mdx-jsx/-/mdast-util-mdx-jsx-3.2.0.tgz", + "integrity": "sha512-lj/z8v0r6ZtsN/cGNNtemmmfoLAFZnjMbNyLzBafjzikOM+glrjNHPlf6lQDOTccj9n5b0PPihEBbhneMyGs1Q==", + "license": "MIT", + "dependencies": { + "@types/estree-jsx": "^1.0.0", + "@types/hast": "^3.0.0", + "@types/mdast": "^4.0.0", + "@types/unist": "^3.0.0", + "ccount": "^2.0.0", + "devlop": "^1.1.0", + "mdast-util-from-markdown": "^2.0.0", + "mdast-util-to-markdown": "^2.0.0", + "parse-entities": "^4.0.0", + "stringify-entities": "^4.0.0", + "unist-util-stringify-position": "^4.0.0", + "vfile-message": "^4.0.0" }, - "engines": { - "node": ">=10.13.0" + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" } }, - "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, + "node_modules/mdast-util-mdxjs-esm": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/mdast-util-mdxjs-esm/-/mdast-util-mdxjs-esm-2.0.1.tgz", + "integrity": "sha512-EcmOpxsZ96CvlP03NghtH1EsLtr0n9Tm4lPUJUBccV9RwUOneqSycg19n5HGzCf+10LozMRSObtVr3ee1WoHtg==", "license": "MIT", "dependencies": { - "define-properties": "^1.2.1", - "gopd": "^1.0.1" - }, - "engines": { - "node": ">= 0.4" + "@types/estree-jsx": "^1.0.0", + "@types/hast": "^3.0.0", + "@types/mdast": "^4.0.0", + "devlop": "^1.0.0", + "mdast-util-from-markdown": "^2.0.0", + "mdast-util-to-markdown": "^2.0.0" }, "funding": { - "url": "https://github.com/sponsors/ljharb" + "type": "opencollective", + "url": "https://opencollective.com/unified" } }, - "node_modules/gopd": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", - "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", - "dev": true, + "node_modules/mdast-util-phrasing": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/mdast-util-phrasing/-/mdast-util-phrasing-4.1.0.tgz", + "integrity": "sha512-TqICwyvJJpBwvGAMZjj4J2n0X8QWp21b9l0o7eXyVJ25YNWYbJDVIyD1bZXE6WtV6RmKJVYmQAKWa0zWOABz2w==", "license": "MIT", - "engines": { - "node": ">= 0.4" + "dependencies": { + "@types/mdast": "^4.0.0", + "unist-util-is": "^6.0.0" }, "funding": { - "url": "https://github.com/sponsors/ljharb" + "type": "opencollective", + "url": "https://opencollective.com/unified" } }, - "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/graphemer": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/graphemer/-/graphemer-1.4.0.tgz", - "integrity": "sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==", - "dev": 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/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, + "node_modules/mdast-util-to-hast": { + "version": "13.2.1", + "resolved": "https://registry.npmjs.org/mdast-util-to-hast/-/mdast-util-to-hast-13.2.1.tgz", + "integrity": "sha512-cctsq2wp5vTsLIcaymblUriiTcZd0CwWtCbLvrOzYCDZoWyMNV8sZ7krj09FSnsiJi3WVsHLM4k6Dq/yaPyCXA==", "license": "MIT", - "engines": { - "node": ">= 0.4" + "dependencies": { + "@types/hast": "^3.0.0", + "@types/mdast": "^4.0.0", + "@ungap/structured-clone": "^1.0.0", + "devlop": "^1.0.0", + "micromark-util-sanitize-uri": "^2.0.0", + "trim-lines": "^3.0.0", + "unist-util-position": "^5.0.0", + "unist-util-visit": "^5.0.0", + "vfile": "^6.0.0" }, "funding": { - "url": "https://github.com/sponsors/ljharb" + "type": "opencollective", + "url": "https://opencollective.com/unified" } }, - "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/mdast-util-to-markdown": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/mdast-util-to-markdown/-/mdast-util-to-markdown-2.2.0.tgz", + "integrity": "sha512-2Jn/ADrHFFyyniBMi0bncTbJqU78K3/TEYvzvwrWWzD9MYPUa/Gm4r3nOeKFQg/PDM5BsbDYdc8ackW4NTY6NA==", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "@types/unist": "^3.0.0", + "longest-streak": "^3.0.0", + "mdast-util-phrasing": "^4.0.0", + "mdast-util-to-string": "^4.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-classify-character": "^2.0.0", + "micromark-util-decode-string": "^2.0.0", + "micromark-util-html-tag-name": "^2.0.0", + "unist-util-visit": "^5.0.0", + "zwitch": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" } }, - "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, + "node_modules/mdast-util-to-string": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/mdast-util-to-string/-/mdast-util-to-string-4.0.0.tgz", + "integrity": "sha512-0H44vDimn51F0YwvxSJSm0eCDOJTRlmN0R1yBh4HLj9wiV1Dn0QoXGbvFAWj2hSItVTlCmBF1hqKlIyUBVFLPg==", "license": "MIT", "dependencies": { - "es-define-property": "^1.0.0" + "@types/mdast": "^4.0.0" }, "funding": { - "url": "https://github.com/sponsors/ljharb" + "type": "opencollective", + "url": "https://opencollective.com/unified" } }, - "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, + "node_modules/media-typer": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.1.tgz", + "integrity": "sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ==", "license": "MIT", - "dependencies": { - "dunder-proto": "^1.0.0" - }, "engines": { - "node": ">= 0.4" + "node": ">= 0.8" }, "funding": { - "url": "https://github.com/sponsors/ljharb" + "type": "opencollective", + "url": "https://opencollective.com/express" } }, - "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==", - "dev": true, + "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": ">= 0.4" + "node": ">=18" }, "funding": { - "url": "https://github.com/sponsors/ljharb" + "url": "https://github.com/sponsors/sindresorhus" } }, - "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, + "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", - "dependencies": { - "has-symbols": "^1.0.3" - }, "engines": { - "node": ">= 0.4" + "node": ">= 8" + } + }, + "node_modules/micromark": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/micromark/-/micromark-4.0.3.tgz", + "integrity": "sha512-oGYfQzHSG5dOMovQcJ3fyTmZlWAWpi0XA0sJwJs+i6OT88o1+Jtw/8z0CmdowSLxGhhFK89rQ/oXph/wN02PNw==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "@types/debug": "^4.0.0", + "debug": "^4.0.0", + "decode-named-character-reference": "^1.0.0", + "devlop": "^1.0.0", + "micromark-core-commonmark": "^2.0.0", + "micromark-factory-space": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-chunked": "^2.0.0", + "micromark-util-combine-extensions": "^2.0.0", + "micromark-util-decode-numeric-character-reference": "^2.0.0", + "micromark-util-edit-map": "^1.0.0", + "micromark-util-encode": "^2.0.0", + "micromark-util-normalize-identifier": "^2.0.0", + "micromark-util-resolve-all": "^2.0.0", + "micromark-util-sanitize-uri": "^2.0.0", + "micromark-util-subtokenize": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-core-commonmark": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/micromark-core-commonmark/-/micromark-core-commonmark-2.0.4.tgz", + "integrity": "sha512-wxEeE8v8XVvOrxn1TZj74qYhAtTQsSqufHVS3uNVyT1MupXxhyaHk8/9xDNPh9BmL77QNDgWTkZ3RsYHB2ry7w==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "decode-named-character-reference": "^1.0.0", + "devlop": "^1.0.0", + "micromark-factory-destination": "^2.0.0", + "micromark-factory-label": "^2.0.0", + "micromark-factory-space": "^2.1.0", + "micromark-factory-title": "^2.0.0", + "micromark-factory-whitespace": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-chunked": "^2.0.0", + "micromark-util-classify-character": "^2.0.0", + "micromark-util-edit-map": "^1.0.0", + "micromark-util-html-tag-name": "^2.0.0", + "micromark-util-normalize-identifier": "^2.0.0", + "micromark-util-resolve-all": "^2.0.0", + "micromark-util-subtokenize": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.3" + } + }, + "node_modules/micromark-extension-gfm": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/micromark-extension-gfm/-/micromark-extension-gfm-3.0.0.tgz", + "integrity": "sha512-vsKArQsicm7t0z2GugkCKtZehqUm31oeGBV/KVSorWSy8ZlNAv7ytjFhvaryUiCUJYqs+NoE6AFhpQvBTM6Q4w==", + "license": "MIT", + "dependencies": { + "micromark-extension-gfm-autolink-literal": "^2.0.0", + "micromark-extension-gfm-footnote": "^2.0.0", + "micromark-extension-gfm-strikethrough": "^2.0.0", + "micromark-extension-gfm-table": "^2.0.0", + "micromark-extension-gfm-tagfilter": "^2.0.0", + "micromark-extension-gfm-task-list-item": "^2.0.0", + "micromark-util-combine-extensions": "^2.0.0", + "micromark-util-types": "^2.0.0" }, "funding": { - "url": "https://github.com/sponsors/ljharb" + "type": "opencollective", + "url": "https://opencollective.com/unified" } }, - "node_modules/hasown": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", - "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", - "dev": true, + "node_modules/micromark-extension-gfm-autolink-literal": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/micromark-extension-gfm-autolink-literal/-/micromark-extension-gfm-autolink-literal-2.1.0.tgz", + "integrity": "sha512-oOg7knzhicgQ3t4QCjCWgTmfNhvQbDDnJeVu9v81r7NltNCVmhPy1fJRX27pISafdjL+SVc4d3l48Gb6pbRypw==", "license": "MIT", "dependencies": { - "function-bind": "^1.1.2" + "micromark-util-character": "^2.0.0", + "micromark-util-sanitize-uri": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" }, - "engines": { - "node": ">= 0.4" + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" } }, - "node_modules/hono": { - "version": "4.12.9", - "resolved": "https://registry.npmjs.org/hono/-/hono-4.12.9.tgz", - "integrity": "sha512-wy3T8Zm2bsEvxKZM5w21VdHDDcwVS1yUFFY6i8UobSsKfFceT7TOwhbhfKsDyx7tYQlmRM5FLpIuYvNFyjctiA==", - "devOptional": true, + "node_modules/micromark-extension-gfm-footnote": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/micromark-extension-gfm-footnote/-/micromark-extension-gfm-footnote-2.1.0.tgz", + "integrity": "sha512-/yPhxI1ntnDNsiHtzLKYnE3vf9JZ6cAisqVDauhp4CEHxlb4uoOTxOCJ+9s51bIB8U1N1FJ1RXOKTIlD5B/gqw==", "license": "MIT", - "engines": { - "node": ">=16.9.0" + "dependencies": { + "devlop": "^1.0.0", + "micromark-core-commonmark": "^2.0.0", + "micromark-factory-space": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-normalize-identifier": "^2.0.0", + "micromark-util-sanitize-uri": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" } }, - "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/iconv-lite": { - "version": "0.7.2", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz", - "integrity": "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==", - "devOptional": true, + "node_modules/micromark-extension-gfm-strikethrough": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/micromark-extension-gfm-strikethrough/-/micromark-extension-gfm-strikethrough-2.1.0.tgz", + "integrity": "sha512-ADVjpOOkjz1hhkZLlBiYA9cR2Anf8F4HqZUO6e5eDcPQd0Txw5fxLzzxnEkSkfnD0wziSGiv7sYhk/ktvbf1uw==", "license": "MIT", "dependencies": { - "safer-buffer": ">= 2.1.2 < 3.0.0" - }, - "engines": { - "node": ">=0.10.0" + "devlop": "^1.0.0", + "micromark-util-chunked": "^2.0.0", + "micromark-util-classify-character": "^2.0.0", + "micromark-util-resolve-all": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" }, "funding": { "type": "opencollective", - "url": "https://opencollective.com/express" + "url": "https://opencollective.com/unified" } }, - "node_modules/ignore": { - "version": "5.3.2", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", - "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", - "dev": true, + "node_modules/micromark-extension-gfm-table": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/micromark-extension-gfm-table/-/micromark-extension-gfm-table-2.1.2.tgz", + "integrity": "sha512-pRzm4kDTu0MjlmBkxmS9yYhw60nncfcEwu9NNdPFSQEFXS95ZKyIIyTSHu/o3ReBUrLKYEq+7YaXCRn/bPB4MA==", "license": "MIT", - "engines": { - "node": ">= 4" + "dependencies": { + "devlop": "^1.0.0", + "micromark-factory-space": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" } }, - "node_modules/import-fresh": { - "version": "3.3.1", - "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz", - "integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==", - "dev": true, + "node_modules/micromark-extension-gfm-tagfilter": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/micromark-extension-gfm-tagfilter/-/micromark-extension-gfm-tagfilter-2.0.0.tgz", + "integrity": "sha512-xHlTOmuCSotIA8TW1mDIM6X2O1SiX5P9IuDtqGonFhEK0qgRI4yeC6vMxEV2dgyr2TiD+2PQ10o+cOhdVAcwfg==", + "license": "MIT", + "dependencies": { + "micromark-util-types": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/micromark-extension-gfm-task-list-item": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/micromark-extension-gfm-task-list-item/-/micromark-extension-gfm-task-list-item-2.1.0.tgz", + "integrity": "sha512-qIBZhqxqI6fjLDYFTBIa4eivDMnP+OZqsNwmQ3xNLE4Cxwc+zfQEfbs6tzAo2Hjq+bh6q5F+Z8/cksrLFYWQQw==", "license": "MIT", "dependencies": { - "parent-module": "^1.0.0", - "resolve-from": "^4.0.0" - }, - "engines": { - "node": ">=6" + "devlop": "^1.0.0", + "micromark-factory-space": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" }, "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "type": "opencollective", + "url": "https://opencollective.com/unified" } }, - "node_modules/imurmurhash": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", - "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", - "dev": true, + "node_modules/micromark-factory-destination": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-factory-destination/-/micromark-factory-destination-2.0.1.tgz", + "integrity": "sha512-Xe6rDdJlkmbFRExpTOmRj9N3MaWmbAgdpSrBQvCFqhezUn4AHqJHbaEnfbVYYiexVSs//tqOdY/DxhjdCiJnIA==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], "license": "MIT", - "engines": { - "node": ">=0.8.19" + "dependencies": { + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" } }, - "node_modules/inflight": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", - "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", - "deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.", - "dev": true, - "license": "ISC", + "node_modules/micromark-factory-label": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-factory-label/-/micromark-factory-label-2.0.1.tgz", + "integrity": "sha512-VFMekyQExqIW7xIChcXn4ok29YE3rnuyveW3wZQWWqF4Nv9Wk5rgJ99KzPvHjkmPXF93FXIbBp6YdW3t71/7Vg==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", "dependencies": { - "once": "^1.3.0", - "wrappy": "1" + "devlop": "^1.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" } }, - "node_modules/inherits": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "dev": true, - "license": "ISC" - }, - "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, + "node_modules/micromark-factory-space": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/micromark-factory-space/-/micromark-factory-space-2.1.0.tgz", + "integrity": "sha512-fS8hnLIjnjvdQIj39Geug8wWsR0HrYZ43KShKxNfwT7t2LOHo/LbWZEzEaSOjwtjdCsjoE6syHhonEzW0zv0+Q==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], "license": "MIT", "dependencies": { - "es-errors": "^1.3.0", - "hasown": "^2.0.2", - "side-channel": "^1.1.0" - }, - "engines": { - "node": ">= 0.4" + "micromark-util-character": "^2.0.0", + "micromark-util-types": "^2.0.0" } }, - "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, + "node_modules/micromark-factory-title": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-factory-title/-/micromark-factory-title-2.0.1.tgz", + "integrity": "sha512-5bZ+3CjhAd9eChYTHsjy6TGxpOFSKgKKJPJxr293jTbfry2KDoWkhBb6TcPVB4NmzaPhMs1Frm9AZH7OD4Cjzw==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], "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" + "micromark-factory-space": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" } }, - "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, + "node_modules/micromark-factory-whitespace": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-factory-whitespace/-/micromark-factory-whitespace-2.0.1.tgz", + "integrity": "sha512-Ob0nuZ3PKt/n0hORHyvoD9uZhr+Za8sFoP+OnMcnWK5lngSzALgQYKMr9RJVOWLqQYuyn6ulqGWSXdwf6F80lQ==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], "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" + "micromark-factory-space": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" } }, - "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, + "node_modules/micromark-util-character": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/micromark-util-character/-/micromark-util-character-2.1.1.tgz", + "integrity": "sha512-wv8tdUTJ3thSFFFJKtpYKOYiGP2+v96Hvk4Tu8KpCAsTMs6yi+nVmGh1syvSCsaxz45J6Jbw+9DD6g97+NV67Q==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], "license": "MIT", "dependencies": { - "has-bigints": "^1.0.2" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" } }, - "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, + "node_modules/micromark-util-chunked": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-chunked/-/micromark-util-chunked-2.0.1.tgz", + "integrity": "sha512-QUNFEOPELfmvv+4xiNg2sRYeS/P84pTW0TCgP5zc9FpXetHY0ab7SxKyAQCNCc1eK0459uoLI1y5oO5Vc1dbhA==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], "license": "MIT", "dependencies": { - "call-bound": "^1.0.3", - "has-tostringtag": "^1.0.2" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" + "micromark-util-symbol": "^2.0.0" } }, - "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, + "node_modules/micromark-util-classify-character": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-classify-character/-/micromark-util-classify-character-2.0.1.tgz", + "integrity": "sha512-K0kHzM6afW/MbeWYWLjoHQv1sgg2Q9EccHEDzSkxiP/EaagNzCm7T/WMKZ3rjMbvIpvBiZgwR3dKMygtA4mG1Q==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], "license": "MIT", "dependencies": { - "semver": "^7.7.1" + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" } }, - "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/micromark-util-combine-extensions": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-combine-extensions/-/micromark-util-combine-extensions-2.0.1.tgz", + "integrity": "sha512-OnAnH8Ujmy59JcyZw8JSbK9cGpdVY44NKgSM7E9Eh7DiLS2E9RNQf0dONaGDzEG9yjEl5hcqeIsj4hfRkLH/Bg==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-chunked": "^2.0.0", + "micromark-util-types": "^2.0.0" } }, - "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, + "node_modules/micromark-util-decode-numeric-character-reference": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/micromark-util-decode-numeric-character-reference/-/micromark-util-decode-numeric-character-reference-2.0.2.tgz", + "integrity": "sha512-ccUbYk6CwVdkmCQMyr64dXz42EfHGkPQlBj5p7YVGzq8I7CtjXZJrubAYezf7Rp+bjPseiROqe7G6foFd+lEuw==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" + "dependencies": { + "micromark-util-symbol": "^2.0.0" } }, - "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, + "node_modules/micromark-util-decode-string": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-decode-string/-/micromark-util-decode-string-2.0.1.tgz", + "integrity": "sha512-nDV/77Fj6eH1ynwscYTOsbK7rR//Uj0bZXBwJZRfaLEJ1iGBR6kIfNmlNqaqJf649EP0F3NWNdeJi03elllNUQ==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], "license": "MIT", "dependencies": { - "hasown": "^2.0.2" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" + "decode-named-character-reference": "^1.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-decode-numeric-character-reference": "^2.0.0", + "micromark-util-symbol": "^2.0.0" } }, - "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, + "node_modules/micromark-util-edit-map": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/micromark-util-edit-map/-/micromark-util-edit-map-1.0.0.tgz", + "integrity": "sha512-Pa2ljlsEL6sVwFaYeyrOLSYbQt73JvGbPOYFq+9AElXiSnfI5Q4465RRZ1sHv7lDjDOnGRDDaqPXqClqWK/q1Q==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], "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" + "micromark-util-types": "^2.0.0" } }, - "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, + "node_modules/micromark-util-encode": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-encode/-/micromark-util-encode-2.0.1.tgz", + "integrity": "sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-util-html-tag-name": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-html-tag-name/-/micromark-util-html-tag-name-2.0.1.tgz", + "integrity": "sha512-2cNEiYDhCWKI+Gs9T0Tiysk136SnR13hhO8yW6BGNyhOC4qYFnwF1nKfD3HFAIXA5c45RrIG1ub11GiXeYd1xA==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-util-normalize-identifier": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-normalize-identifier/-/micromark-util-normalize-identifier-2.0.1.tgz", + "integrity": "sha512-sxPqmo70LyARJs0w2UclACPUUEqltCkJ6PhKdMIDuJ3gSf/Q+/GIe3WKl0Ijb/GyH9lOpUkRAO2wp0GVkLvS9Q==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], "license": "MIT", "dependencies": { - "call-bound": "^1.0.2", - "has-tostringtag": "^1.0.2" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" + "micromark-util-symbol": "^2.0.0" } }, - "node_modules/is-extglob": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", - "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", - "dev": true, + "node_modules/micromark-util-resolve-all": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-resolve-all/-/micromark-util-resolve-all-2.0.1.tgz", + "integrity": "sha512-VdQyxFWFT2/FGJgwQnJYbe1jjQoNTS4RjglmSjTUlpUMa95Htx9NHeYW4rGDJzbjvCsl9eLjMQwGeElsqmzcHg==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], "license": "MIT", - "engines": { - "node": ">=0.10.0" + "dependencies": { + "micromark-util-types": "^2.0.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, + "node_modules/micromark-util-sanitize-uri": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-sanitize-uri/-/micromark-util-sanitize-uri-2.0.1.tgz", + "integrity": "sha512-9N9IomZ/YuGGZZmQec1MbgxtlgougxTodVwDzzEouPKo3qFWvymFHWcnDi2vzV1ff6kas9ucW+o3yzJK9YB1AQ==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], "license": "MIT", "dependencies": { - "call-bound": "^1.0.3" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" + "micromark-util-character": "^2.0.0", + "micromark-util-encode": "^2.0.0", + "micromark-util-symbol": "^2.0.0" } }, - "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==", - "dev": true, + "node_modules/micromark-util-subtokenize": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/micromark-util-subtokenize/-/micromark-util-subtokenize-2.1.0.tgz", + "integrity": "sha512-XQLu552iSctvnEcgXw6+Sx75GflAPNED1qx7eBJ+wydBb2KCbRZe+NwvIEEMM83uml1+2WSXpBAcp9IUCgCYWA==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], "license": "MIT", - "engines": { - "node": ">=8" + "dependencies": { + "devlop": "^1.0.0", + "micromark-util-chunked": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" } }, - "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, + "node_modules/micromark-util-symbol": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-symbol/-/micromark-util-symbol-2.0.1.tgz", + "integrity": "sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-util-types": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/micromark-util-types/-/micromark-util-types-2.0.3.tgz", + "integrity": "sha512-oxB2Ik03hI0gv+VNn9tnh1t1YEe9MDPptViAEgfdf3YQHsn0pzGTgCdlSCJXcwhqm8phaEuM7zeEu3QQzVBrPg==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark/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": { - "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" + "ms": "^2.1.3" }, "engines": { - "node": ">= 0.4" + "node": ">=6.0" }, - "funding": { - "url": "https://github.com/sponsors/ljharb" + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } } }, - "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==", - "dev": true, + "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": { - "is-extglob": "^2.1.1" + "braces": "^3.0.3", + "picomatch": "^2.3.1" }, "engines": { - "node": ">=0.10.0" + "node": ">=8.6" } }, - "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, + "node_modules/micromatch/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": ">= 0.4" + "node": ">=8.6" }, "funding": { - "url": "https://github.com/sponsors/ljharb" + "url": "https://github.com/sponsors/jonschlinkert" } }, - "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, + "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.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" + "node": ">= 0.6" } }, - "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, + "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": { - "call-bound": "^1.0.3", - "has-tostringtag": "^1.0.2" + "mime-db": "^1.54.0" }, "engines": { - "node": ">= 0.4" + "node": ">=18" }, "funding": { - "url": "https://github.com/sponsors/ljharb" + "type": "opencollective", + "url": "https://opencollective.com/express" } }, - "node_modules/is-path-inside": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-3.0.3.tgz", - "integrity": "sha512-Fd4gABb+ycGAmKou8eMftCupSir5lRxqf4aD/vd0cD2qc4HL07OjCeuHMr8Ro4CoMaeCKDB0/ECBOVWjTwUvPQ==", - "dev": true, + "node_modules/mimic-fn": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-3.1.0.tgz", + "integrity": "sha512-Ysbi9uYW9hFyfrThdDEQuykN4Ey6BuwPD2kpI5ES/nFTDn/98yxYNLZJcgUAKPT/mcrLLKaGzJR9YVxJrIdASQ==", "license": "MIT", "engines": { "node": ">=8" } }, - "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, + "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", - "dependencies": { - "call-bound": "^1.0.2", - "gopd": "^1.2.0", - "has-tostringtag": "^1.0.2", - "hasown": "^2.0.2" - }, "engines": { - "node": ">= 0.4" + "node": ">=18" }, "funding": { - "url": "https://github.com/sponsors/ljharb" + "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==", + "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": "MIT", - "engines": { - "node": ">= 0.4" + "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/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, + "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/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": { - "call-bound": "^1.0.3" + "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": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" + "node": ">= 8.0" } }, - "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, + "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": { - "call-bound": "^1.0.3", - "has-tostringtag": "^1.0.2" + "lru.min": "^1.1.0" }, "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" + "node": ">=8.0.0" } }, - "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==", + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "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", - "dependencies": { - "call-bound": "^1.0.2", - "has-symbols": "^1.1.0", - "safe-regex-test": "^1.1.0" + "bin": { + "napi-postinstall": "lib/cli.js" }, "engines": { - "node": ">= 0.4" + "node": "^12.20.0 || ^14.18.0 || >=16.0.0" }, "funding": { - "url": "https://github.com/sponsors/ljharb" + "url": "https://opencollective.com/napi-postinstall" } }, - "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==", + "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.1.0", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.1.0.tgz", + "integrity": "sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg==", "license": "MIT", "dependencies": { - "which-typed-array": "^1.1.16" + "content-type": "^2.1.0" }, "engines": { - "node": ">= 0.4" + "node": ">=18" }, "funding": { - "url": "https://github.com/sponsors/ljharb" + "type": "opencollective", + "url": "https://opencollective.com/express" } }, - "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, + "node_modules/negotiator/node_modules/content-type": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", "license": "MIT", "engines": { - "node": ">= 0.4" + "node": ">=18" }, "funding": { - "url": "https://github.com/sponsors/ljharb" + "type": "opencollective", + "url": "https://opencollective.com/express" } }, - "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, + "node_modules/next": { + "version": "16.4.0", + "resolved": "https://registry.npmjs.org/next/-/next-16.4.0.tgz", + "integrity": "sha512-N2C+9q89Z/oLrsepSRS4jRMtwmUZAoZuAHU0e9T6+sAB5DdhADmrnOW+zjYijlrYFmVfmQhGVGy9eMFoB7UgKg==", "license": "MIT", "dependencies": { - "call-bound": "^1.0.3" + "@next/env": "16.4.0", + "@swc/helpers": "0.5.23", + "baseline-browser-mapping": "^2.9.19", + "caniuse-lite": "^1.0.30001579", + "postcss": "8.5.23", + "styled-jsx": "5.1.6" + }, + "bin": { + "next": "dist/bin/next" }, "engines": { - "node": ">= 0.4" + "node": ">=20.9.0" }, - "funding": { - "url": "https://github.com/sponsors/ljharb" + "optionalDependencies": { + "@next/swc-darwin-arm64": "16.4.0", + "@next/swc-darwin-x64": "16.4.0", + "@next/swc-linux-arm64-gnu": "16.4.0", + "@next/swc-linux-arm64-musl": "16.4.0", + "@next/swc-linux-x64-gnu": "16.4.0", + "@next/swc-linux-x64-musl": "16.4.0", + "@next/swc-win32-arm64-msvc": "16.4.0", + "@next/swc-win32-x64-msvc": "16.4.0", + "sharp": "^0.35.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/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", + "node_modules/next-auth": { + "version": "4.24.15", + "resolved": "https://registry.npmjs.org/next-auth/-/next-auth-4.24.15.tgz", + "integrity": "sha512-NnjYtjrSOAx/TIVFGTX4IfI/9yHnNpi4B7FuLUwuV20v2Zxgr2OGP/YN0ynJuI7y8QOnTBPitfOdEXZrVvhIuA==", + "license": "ISC", "dependencies": { - "call-bound": "^1.0.3", - "get-intrinsic": "^1.2.6" + "@babel/runtime": "^7.20.13", + "@panva/hkdf": "^1.0.2", + "cookie": "^0.7.0", + "jose": "^4.15.5", + "oauth": "^0.9.15", + "openid-client": "^5.4.0", + "preact": "^10.6.3", + "preact-render-to-string": "^5.1.19", + "uuid": "^11.1.1" }, - "engines": { - "node": ">= 0.4" + "peerDependencies": { + "@auth/core": "0.34.3", + "next": "^12.2.5 || ^13 || ^14 || ^15 || ^16", + "nodemailer": "^7.0.7", + "react": "^17.0.2 || ^18 || ^19", + "react-dom": "^17.0.2 || ^18 || ^19" }, - "funding": { - "url": "https://github.com/sponsors/ljharb" + "peerDependenciesMeta": { + "@auth/core": { + "optional": true + }, + "nodemailer": { + "optional": true + } } }, - "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==", - "devOptional": true, - "license": "ISC" + "node_modules/next-themes": { + "version": "0.4.6", + "resolved": "https://registry.npmjs.org/next-themes/-/next-themes-0.4.6.tgz", + "integrity": "sha512-pZvgD5L0IEvX5/9GWyHMf3m8BKiVQwsCMHfoFosXtXBMnaS0ZnIJ9ST4b4NqLVKDEm8QBxoNNGNaBv2JNF6XNA==", + "license": "MIT", + "peerDependencies": { + "react": "^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc" + } }, - "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, + "node_modules/next/node_modules/postcss": { + "version": "8.5.23", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.23.tgz", + "integrity": "sha512-g50586zr4bZmwFiTlflMu8E0bDTb5I5gertgwAKmsdUlTQIhZtunzUlD1WSzwcVWPoAVpsrA6vlfCD7oXvRwgg==", + "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": { - "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" + "nanoid": "^3.3.16", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" }, "engines": { - "node": ">= 0.4" + "node": "^10 || ^12 || >=14" } }, - "node_modules/jackspeak": { - "version": "2.3.6", - "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-2.3.6.tgz", - "integrity": "sha512-N3yCS/NegsOBokc8GAdM8UcmfsKiSS8cipheD/nivzr700H+nsMOxJjQnvwOcRYVuFkdH0wGUvW2WbXGmrZGbQ==", + "node_modules/node-ensure": { + "version": "0.0.0", + "resolved": "https://registry.npmjs.org/node-ensure/-/node-ensure-0.0.0.tgz", + "integrity": "sha512-DRI60hzo2oKN1ma0ckc6nQWlHU69RH6xN0sjQTjMpChPfTYvKZdcQFfdYK2RWbJcKyUizSIy/l8OTGxMAM1QDw==", + "license": "MIT" + }, + "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": "BlueOak-1.0.0", + "license": "MIT", "dependencies": { - "@isaacs/cliui": "^8.0.2" + "array.prototype.flatmap": "^1.3.3", + "es-errors": "^1.3.0", + "object.entries": "^1.1.9", + "semver": "^6.3.1" }, "engines": { - "node": ">=14" + "node": ">= 0.4" }, "funding": { - "url": "https://github.com/sponsors/isaacs" - }, - "optionalDependencies": { - "@pkgjs/parseargs": "^0.11.0" + "url": "https://github.com/sponsors/ljharb" } }, - "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, + "node_modules/node-releases": { + "version": "2.0.58", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.58.tgz", + "integrity": "sha512-BdiKAgbfRlvfMq/XzO/AF9NPmaA8a+YpLAyAFTVFBj3gARrAIfWvNq7Q7NE4se3KgFu0KkrvQMxTS0XVnsGzHg==", "license": "MIT", - "bin": { - "jiti": "lib/jiti-cli.mjs" + "engines": { + "node": ">=18" } }, - "node_modules/jose": { - "version": "4.15.9", - "resolved": "https://registry.npmjs.org/jose/-/jose-4.15.9.tgz", - "integrity": "sha512-1vUQX+IdDMVPj4k8kOxgUqlcK518yluMuGZwqlr44FS1ppZB/5GWh4rZG89erpOBOJjU/OBsnCVFfapsRz6nEA==", + "node_modules/nodemailer": { + "version": "7.0.13", + "resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-7.0.13.tgz", + "integrity": "sha512-PNDFSJdP+KFgdsG3ZzMXCgquO7I6McjY2vlqILjtJd0hy8wEvtugS9xKRF2NWlPNGxvLCXlTNIae4serI7dinw==", + "license": "MIT-0", + "engines": { + "node": ">=6.0.0" + } + }, + "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/panva" + "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/js-tokens": { + "node_modules/npm-run-path/node_modules/path-key": { "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==", - "dev": true, + "resolved": "https://registry.npmjs.org/path-key/-/path-key-4.0.0.tgz", + "integrity": "sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ==", "license": "MIT", - "dependencies": { - "argparse": "^2.0.1" + "engines": { + "node": ">=12" }, - "bin": { - "js-yaml": "bin/js-yaml.js" + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "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, + "node_modules/oauth": { + "version": "0.9.15", + "resolved": "https://registry.npmjs.org/oauth/-/oauth-0.9.15.tgz", + "integrity": "sha512-a5ERWK1kh38ExDEfoO6qUHJb32rd7aYmPHuyCu3Fta/cnICvYmgd2uhuKXvPD+PXB+gCEYYEaQdIRAjCOwAKNA==", "license": "MIT" }, - "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/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/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/object-hash": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/object-hash/-/object-hash-2.2.0.tgz", + "integrity": "sha512-gScRMn0bS5fH+IuwyIFgnh9zBdo4DV+6GhygmWM9HyNJSgS0hScp1f5vjtm7oIIOiT9trXrShAkLFSc2IqKNgw==", + "license": "MIT", + "engines": { + "node": ">= 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, + "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", - "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": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "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==", + "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", - "dependencies": { - "json-buffer": "3.0.1" + "engines": { + "node": ">= 0.4" } }, - "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/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/language-tags": { - "version": "1.0.9", - "resolved": "https://registry.npmjs.org/language-tags/-/language-tags-1.0.9.tgz", - "integrity": "sha512-MbjN408fEndfiQXbFQ1vnd+1NoLDsnQW41410oQBXiyXDMYH5z505juWa4KUE1LqxRC7DgOgZDbKLxHIwm27hA==", + "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": { - "language-subtag-registry": "^0.3.20" + "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.10" + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "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==", + "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": { - "prelude-ls": "^1.2.1", - "type-check": "~0.4.0" + "call-bind": "^1.0.8", + "call-bound": "^1.0.4", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.1.1" }, "engines": { - "node": ">= 0.8.0" + "node": ">= 0.4" } }, - "node_modules/lightningcss": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz", - "integrity": "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==", + "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": "MPL-2.0", + "license": "MIT", "dependencies": { - "detect-libc": "^2.0.3" + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.2", + "es-object-atoms": "^1.0.0" }, "engines": { - "node": ">= 12.0.0" + "node": ">= 0.4" }, "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" + "url": "https://github.com/sponsors/ljharb" } }, - "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" - ], + "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": "MPL-2.0", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">= 12.0.0" + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.2" }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" + "engines": { + "node": ">= 0.4" } }, - "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" - ], + "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": "MPL-2.0", - "optional": true, - "os": [ - "darwin" - ], + "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": ">= 12.0.0" + "node": ">= 0.4" }, "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" + "url": "https://github.com/sponsors/ljharb" } }, - "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" - ], + "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, - "license": "MPL-2.0", - "optional": true, - "os": [ - "darwin" + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" ], + "license": "MIT" + }, + "node_modules/ohash": { + "version": "2.0.12", + "resolved": "https://registry.npmjs.org/ohash/-/ohash-2.0.12.tgz", + "integrity": "sha512-65S/5gk9YSsaRjcyf7Nfa6h/d3E8/1gslpXfI4W7Dxn/oap8IKRuNT5VXkLQ1YFKIEg4apRY4Pj6aiwFzrDdmw==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/oidc-token-hash": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/oidc-token-hash/-/oidc-token-hash-5.2.0.tgz", + "integrity": "sha512-6gj2m8cJZ+iSW8bm0FXdGF0YhIQbKrfP4yWTNzxc31U6MOjfEmB1rHvlYvxI1B7t7BCi1F2vYTT6YhtQRG4hxw==", + "license": "MIT", "engines": { - "node": ">= 12.0.0" + "node": "^10.13.0 || >=12.0.0" + } + }, + "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" }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" + "engines": { + "node": ">= 0.8" } }, - "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" - ], + "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": "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": ">= 12.0.0" + "node": ">=6" }, "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" + "url": "https://github.com/sponsors/sindresorhus" } }, - "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" - ], + "node_modules/onetime/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": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" + "node": ">=6" } }, - "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" - ], + "node_modules/open": { + "version": "11.0.4", + "resolved": "https://registry.npmjs.org/open/-/open-11.0.4.tgz", + "integrity": "sha512-++Zlftm0kVLPmzC06t6epuWmcRMDbI4z5P3NNX979WA/k23+NtSOynEGzsVfZwguKw2mi5umVgnBlJQMwRz4Pg==", + "license": "MIT", + "dependencies": { + "default-browser": "^5.5.1", + "define-lazy-prop": "^3.0.0", + "is-in-ssh": "^1.0.0", + "is-inside-container": "^1.0.0", + "powershell-utils": "^0.2.1", + "wsl-utils": "^1.0.0" + }, "engines": { - "node": ">= 12.0.0" + "node": ">=20" }, "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" + "url": "https://github.com/sponsors/sindresorhus" } }, - "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" + "node_modules/openid-client": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/openid-client/-/openid-client-5.7.1.tgz", + "integrity": "sha512-jDBPgSVfTnkIh71Hg9pRvtJc6wTwqjRkN88+gCFtYWrlP4Yx2Dsrow8uPi3qLr/aeymPF3o2+dS+wOpglK04ew==", + "license": "MIT", + "dependencies": { + "jose": "^4.15.9", + "lru-cache": "^6.0.0", + "object-hash": "^2.2.0", + "oidc-token-hash": "^5.0.3" }, "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" + "url": "https://github.com/sponsors/panva" } }, - "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" + "node_modules/openid-client/node_modules/lru-cache": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", + "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", + "license": "ISC", + "dependencies": { + "yallist": "^4.0.0" }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" + "engines": { + "node": ">=10" } }, - "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" - ], + "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": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], + "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": ">= 12.0.0" + "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": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" + "url": "https://github.com/sponsors/sindresorhus" } }, - "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" - ], + "node_modules/ora/node_modules/ansi-regex": { + "version": "6.4.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.4.0.tgz", + "integrity": "sha512-KzTVk2tCWAHtYrvvvaP8bJKJq2pVinhLcGEQdtLIYPbmNGNyYe8QwNaTUYQp2J7/vIsUKt5QCqAfUkYyG9DkOw==", + "license": "MIT", "engines": { - "node": ">= 12.0.0" + "node": ">=12" }, "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" + "url": "https://github.com/chalk/ansi-regex?sponsor=1" } }, - "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" - ], + "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.0.0" + "node": "^12.17.0 || ^14.13 || >=16.0.0" }, "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" + "url": "https://github.com/chalk/chalk?sponsor=1" } }, - "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, + "node_modules/ora/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": { - "p-locate": "^5.0.0" + "ansi-regex": "^6.2.2" }, "engines": { - "node": ">=10" + "node": ">=12" }, "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "url": "https://github.com/chalk/strip-ansi?sponsor=1" } }, - "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==", + "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" - }, - "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==", "license": "MIT", "dependencies": { - "js-tokens": "^3.0.0 || ^4.0.0" + "get-intrinsic": "^1.2.6", + "object-keys": "^1.1.1", + "safe-push-apply": "^1.0.0" }, - "bin": { - "loose-envify": "cli.js" + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/lru-cache": { - "version": "10.4.3", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", - "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", + "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": "ISC" - }, - "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", + "dependencies": { + "yocto-queue": "^0.1.0" + }, "engines": { - "bun": ">=1.0.0", - "deno": ">=1.30.0", - "node": ">=8.0.0" + "node": ">=10" }, "funding": { - "type": "github", - "url": "https://github.com/sponsors/wellwelwel" + "url": "https://github.com/sponsors/sindresorhus" } }, - "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==", + "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": { - "@jridgewell/sourcemap-codec": "^1.5.5" + "p-limit": "^3.0.2" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "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==", - "dev": true, + "node_modules/p-try": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", "license": "MIT", "engines": { - "node": ">= 0.4" + "node": ">=6" } }, - "node_modules/minimatch": { - "version": "3.1.5", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", - "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "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==", "dev": true, - "license": "ISC", + "license": "MIT", "dependencies": { - "brace-expansion": "^1.1.7" + "callsites": "^3.0.0" }, "engines": { - "node": "*" + "node": ">=6" } }, - "node_modules/minimist": { - "version": "1.2.8", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", - "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", - "dev": true, + "node_modules/parse-entities": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/parse-entities/-/parse-entities-4.0.2.tgz", + "integrity": "sha512-GG2AQYWoLgL877gQIKeRPGO1xF9+eG1ujIb5soS5gPvLQ1y2o8FL90w2QWNdf9I361Mpp7726c+lj3U0qK1uGw==", "license": "MIT", + "dependencies": { + "@types/unist": "^2.0.0", + "character-entities-legacy": "^3.0.0", + "character-reference-invalid": "^2.0.0", + "decode-named-character-reference": "^1.0.0", + "is-alphanumerical": "^2.0.0", + "is-decimal": "^2.0.0", + "is-hexadecimal": "^2.0.0" + }, "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==", - "dev": true, - "license": "BlueOak-1.0.0", - "engines": { - "node": ">=16 || 14 >=14.17" + "type": "github", + "url": "https://github.com/sponsors/wooorm" } }, - "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==", + "node_modules/parse-entities/node_modules/@types/unist": { + "version": "2.0.11", + "resolved": "https://registry.npmjs.org/@types/unist/-/unist-2.0.11.tgz", + "integrity": "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA==", "license": "MIT" }, - "node_modules/mysql2": { - "version": "3.15.3", - "resolved": "https://registry.npmjs.org/mysql2/-/mysql2-3.15.3.tgz", - "integrity": "sha512-FBrGau0IXmuqg4haEZRBfHNWB5mUARw6hNwPDXXGg0XzVJ50mr/9hb267lvpVMnhZ1FON3qNd4Xfcez1rbFwSg==", - "devOptional": true, + "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", - "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": ">=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": ">= 8.0" + "node": ">= 0.8" } }, - "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, + "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", - "dependencies": { - "lru.min": "^1.1.0" - }, "engines": { - "node": ">=8.0.0" + "node": ">=8" } }, - "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" - } - ], + "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", - "bin": { - "nanoid": "bin/nanoid.cjs" - }, "engines": { - "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + "node": ">=8" } }, - "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==", + "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-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", - "bin": { - "napi-postinstall": "lib/cli.js" - }, - "engines": { - "node": "^12.20.0 || ^14.18.0 || >=16.0.0" - }, "funding": { - "url": "https://opencollective.com/napi-postinstall" + "type": "opencollective", + "url": "https://opencollective.com/express" } }, - "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, + "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/next": { - "version": "14.2.35", - "resolved": "https://registry.npmjs.org/next/-/next-14.2.35.tgz", - "integrity": "sha512-KhYd2Hjt/O1/1aZVX3dCwGXM1QmOV4eNM2UTacK5gipDdPN/oHHK/4oVGy7X8GMfPMsUTUEmGlsy0EY1YGAkig==", + "node_modules/pdf-parse": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/pdf-parse/-/pdf-parse-1.1.1.tgz", + "integrity": "sha512-v6ZJ/efsBpGrGGknjtq9J/oC8tZWq0KWL5vQrk2GlzLEQPUDB1ex+13Rmidl1neNN358Jn9EHZw5y07FFtaC7A==", "license": "MIT", "dependencies": { - "@next/env": "14.2.35", - "@swc/helpers": "0.5.5", - "busboy": "1.6.0", - "caniuse-lite": "^1.0.30001579", - "graceful-fs": "^4.2.11", - "postcss": "8.4.31", - "styled-jsx": "5.1.1" + "debug": "^3.1.0", + "node-ensure": "^0.0.0" }, - "bin": { - "next": "dist/bin/next" + "engines": { + "node": ">=6.8.1" + } + }, + "node_modules/perfect-debounce": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/perfect-debounce/-/perfect-debounce-2.1.0.tgz", + "integrity": "sha512-LjgdTytVFXeUgtHZr9WYViYSM/g8MkcTPYDlPa3cDqMirHjKiSZPYd6DoL7pK8AJQr+uWkQvCjHNdiMqsrJs+g==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/pg": { + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/pg/-/pg-8.20.0.tgz", + "integrity": "sha512-ldhMxz2r8fl/6QkXnBD3CR9/xg694oT6DZQ2s6c/RI28OjtSOpxnPrUCGOBJ46RCUxcWdx3p6kw/xnDHjKvaRA==", + "license": "MIT", + "dependencies": { + "pg-connection-string": "^2.12.0", + "pg-pool": "^3.13.0", + "pg-protocol": "^1.13.0", + "pg-types": "2.2.0", + "pgpass": "1.0.5" }, "engines": { - "node": ">=18.17.0" + "node": ">= 16.0.0" }, "optionalDependencies": { - "@next/swc-darwin-arm64": "14.2.33", - "@next/swc-darwin-x64": "14.2.33", - "@next/swc-linux-arm64-gnu": "14.2.33", - "@next/swc-linux-arm64-musl": "14.2.33", - "@next/swc-linux-x64-gnu": "14.2.33", - "@next/swc-linux-x64-musl": "14.2.33", - "@next/swc-win32-arm64-msvc": "14.2.33", - "@next/swc-win32-ia32-msvc": "14.2.33", - "@next/swc-win32-x64-msvc": "14.2.33" + "pg-cloudflare": "^1.3.0" }, "peerDependencies": { - "@opentelemetry/api": "^1.1.0", - "@playwright/test": "^1.41.2", - "react": "^18.2.0", - "react-dom": "^18.2.0", - "sass": "^1.3.0" + "pg-native": ">=3.0.1" }, "peerDependenciesMeta": { - "@opentelemetry/api": { - "optional": true - }, - "@playwright/test": { - "optional": true - }, - "sass": { + "pg-native": { "optional": true } } }, - "node_modules/next-auth": { - "version": "4.24.13", - "resolved": "https://registry.npmjs.org/next-auth/-/next-auth-4.24.13.tgz", - "integrity": "sha512-sgObCfcfL7BzIK76SS5TnQtc3yo2Oifp/yIpfv6fMfeBOiBJkDWF3A2y9+yqnmJ4JKc2C+nMjSjmgDeTwgN1rQ==", - "license": "ISC", - "dependencies": { - "@babel/runtime": "^7.20.13", - "@panva/hkdf": "^1.0.2", - "cookie": "^0.7.0", - "jose": "^4.15.5", - "oauth": "^0.9.15", - "openid-client": "^5.4.0", - "preact": "^10.6.3", - "preact-render-to-string": "^5.1.19", - "uuid": "^8.3.2" - }, - "peerDependencies": { - "@auth/core": "0.34.3", - "next": "^12.2.5 || ^13 || ^14 || ^15 || ^16", - "nodemailer": "^7.0.7", - "react": "^17.0.2 || ^18 || ^19", - "react-dom": "^17.0.2 || ^18 || ^19" - }, - "peerDependenciesMeta": { - "@auth/core": { - "optional": true - }, - "nodemailer": { - "optional": true - } - } + "node_modules/pg-cloudflare": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.3.0.tgz", + "integrity": "sha512-6lswVVSztmHiRtD6I8hw4qP/nDm1EJbKMRhf3HCYaqud7frGysPv7FYJ5noZQdhQtN2xJnimfMtvQq21pdbzyQ==", + "license": "MIT", + "optional": true }, - "node_modules/node-ensure": { - "version": "0.0.0", - "resolved": "https://registry.npmjs.org/node-ensure/-/node-ensure-0.0.0.tgz", - "integrity": "sha512-DRI60hzo2oKN1ma0ckc6nQWlHU69RH6xN0sjQTjMpChPfTYvKZdcQFfdYK2RWbJcKyUizSIy/l8OTGxMAM1QDw==", + "node_modules/pg-connection-string": { + "version": "2.12.0", + "resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.12.0.tgz", + "integrity": "sha512-U7qg+bpswf3Cs5xLzRqbXbQl85ng0mfSV/J0nnA31MCLgvEaAo7CIhmeyrmJpOr7o+zm0rXK+hNnT5l9RHkCkQ==", "license": "MIT" }, - "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" - }, + "node_modules/pg-int8": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz", + "integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==", + "license": "ISC", "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" + "node": ">=4.0.0" } }, - "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/nodemailer": { - "version": "7.0.13", - "resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-7.0.13.tgz", - "integrity": "sha512-PNDFSJdP+KFgdsG3ZzMXCgquO7I6McjY2vlqILjtJd0hy8wEvtugS9xKRF2NWlPNGxvLCXlTNIae4serI7dinw==", - "license": "MIT-0", - "engines": { - "node": ">=6.0.0" + "node_modules/pg-pool": { + "version": "3.13.0", + "resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.13.0.tgz", + "integrity": "sha512-gB+R+Xud1gLFuRD/QgOIgGOBE2KCQPaPwkzBBGC9oG69pHTkhQeIuejVIk3/cnDyX39av2AxomQiyPT13WKHQA==", + "license": "MIT", + "peerDependencies": { + "pg": ">=8.0" } }, - "node_modules/nypm": { - "version": "0.6.5", - "resolved": "https://registry.npmjs.org/nypm/-/nypm-0.6.5.tgz", - "integrity": "sha512-K6AJy1GMVyfyMXRVB88700BJqNUkByijGJM8kEHpLdcAt+vSQAVfkWWHYzuRXHSY6xA2sNc5RjTj0p9rE2izVQ==", - "devOptional": true, + "node_modules/pg-protocol": { + "version": "1.13.0", + "resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.13.0.tgz", + "integrity": "sha512-zzdvXfS6v89r6v7OcFCHfHlyG/wvry1ALxZo4LqgUoy7W9xhBDMaqOuMiF3qEV45VqsN6rdlcehHrfDtlCPc8w==", + "license": "MIT" + }, + "node_modules/pg-types": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz", + "integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==", "license": "MIT", "dependencies": { - "citty": "^0.2.0", - "pathe": "^2.0.3", - "tinyexec": "^1.0.2" - }, - "bin": { - "nypm": "dist/cli.mjs" + "pg-int8": "1.0.1", + "postgres-array": "~2.0.0", + "postgres-bytea": "~1.0.0", + "postgres-date": "~1.0.4", + "postgres-interval": "^1.1.0" }, "engines": { - "node": ">=18" + "node": ">=4" } }, - "node_modules/nypm/node_modules/citty": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/citty/-/citty-0.2.1.tgz", - "integrity": "sha512-kEV95lFBhQgtogAPlQfJJ0WGVSokvLr/UEoFPiKKOXF7pl98HfUVUD0ejsuTCld/9xH9vogSywZ5KqHzXrZpqg==", - "devOptional": true, - "license": "MIT" - }, - "node_modules/oauth": { - "version": "0.9.15", - "resolved": "https://registry.npmjs.org/oauth/-/oauth-0.9.15.tgz", - "integrity": "sha512-a5ERWK1kh38ExDEfoO6qUHJb32rd7aYmPHuyCu3Fta/cnICvYmgd2uhuKXvPD+PXB+gCEYYEaQdIRAjCOwAKNA==", - "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==", - "dev": true, + "node_modules/pg-types/node_modules/postgres-array": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz", + "integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==", "license": "MIT", "engines": { - "node": ">=0.10.0" + "node": ">=4" } }, - "node_modules/object-hash": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/object-hash/-/object-hash-2.2.0.tgz", - "integrity": "sha512-gScRMn0bS5fH+IuwyIFgnh9zBdo4DV+6GhygmWM9HyNJSgS0hScp1f5vjtm7oIIOiT9trXrShAkLFSc2IqKNgw==", + "node_modules/pgpass": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.5.tgz", + "integrity": "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==", "license": "MIT", - "engines": { - "node": ">= 6" + "dependencies": { + "split2": "^4.1.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==", - "dev": true, + "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": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", "license": "MIT", "engines": { - "node": ">= 0.4" + "node": ">=12" }, "funding": { - "url": "https://github.com/sponsors/ljharb" + "url": "https://github.com/sponsors/jonschlinkert" } }, - "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, + "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": ">= 0.4" + "node": ">=16.20.0" } }, - "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, + "node_modules/pkg-types": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-2.3.3.tgz", + "integrity": "sha512-j/lCFdcppV0JxWpCEITdbDltBxPP6cHT+yNJ6Go2OgoSA9518X847X9z0p6LtA4Nc16+eQzCZjRrWanTGvHJ5w==", + "devOptional": 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" + "confbox": "^0.3.1", + "exsolve": "^1.1.1", + "pathe": "^2.0.3" } }, - "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, + "node_modules/pkg-types/node_modules/confbox": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.3.1.tgz", + "integrity": "sha512-cKUSoKa8YxFZZSmraVi7onONx3amu77ngK3kGpsYHDH7drPwCRkQE1RYMPlLRrMtnciRj274XNRxcHxnKmDSnA==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/pkg-up": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/pkg-up/-/pkg-up-3.1.0.tgz", + "integrity": "sha512-nDywThFk1i4BQK4twPQ6TA4RT8bDY96yeuCVBWL3ePARCiEKDRSrNGbFIgUJpLp+XeIR65v8ra7WuJOFUBtkMA==", "license": "MIT", "dependencies": { - "call-bind": "^1.0.8", - "call-bound": "^1.0.4", - "define-properties": "^1.2.1", - "es-object-atoms": "^1.1.1" + "find-up": "^3.0.0" }, "engines": { - "node": ">= 0.4" + "node": ">=8" } }, - "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, + "node_modules/pkg-up/node_modules/find-up": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz", + "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==", "license": "MIT", "dependencies": { - "call-bind": "^1.0.7", - "define-properties": "^1.2.1", - "es-abstract": "^1.23.2", - "es-object-atoms": "^1.0.0" + "locate-path": "^3.0.0" }, "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" + "node": ">=6" } }, - "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, + "node_modules/pkg-up/node_modules/locate-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz", + "integrity": "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==", "license": "MIT", "dependencies": { - "call-bind": "^1.0.7", - "define-properties": "^1.2.1", - "es-abstract": "^1.23.2" + "p-locate": "^3.0.0", + "path-exists": "^3.0.0" }, "engines": { - "node": ">= 0.4" + "node": ">=6" } }, - "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, + "node_modules/pkg-up/node_modules/p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", "license": "MIT", "dependencies": { - "call-bind": "^1.0.8", - "call-bound": "^1.0.3", - "define-properties": "^1.2.1", - "es-object-atoms": "^1.0.0" + "p-try": "^2.0.0" }, "engines": { - "node": ">= 0.4" + "node": ">=6" }, "funding": { - "url": "https://github.com/sponsors/ljharb" + "url": "https://github.com/sponsors/sindresorhus" } }, - "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/oidc-token-hash": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/oidc-token-hash/-/oidc-token-hash-5.2.0.tgz", - "integrity": "sha512-6gj2m8cJZ+iSW8bm0FXdGF0YhIQbKrfP4yWTNzxc31U6MOjfEmB1rHvlYvxI1B7t7BCi1F2vYTT6YhtQRG4hxw==", + "node_modules/pkg-up/node_modules/p-locate": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-3.0.0.tgz", + "integrity": "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==", "license": "MIT", + "dependencies": { + "p-limit": "^2.0.0" + }, "engines": { - "node": "^10.13.0 || >=12.0.0" + "node": ">=6" } }, - "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==", - "dev": true, - "license": "ISC", - "dependencies": { - "wrappy": "1" + "node_modules/pkg-up/node_modules/path-exists": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-3.0.0.tgz", + "integrity": "sha512-bpC7GYwiDYQ4wYLe+FA8lhRjhQCMcQGuSgGGqDkg/QerRWw9CmGRT0iSOVRSZJ29NMLZgIzqaljJ63oaL4NIJQ==", + "license": "MIT", + "engines": { + "node": ">=4" } }, - "node_modules/openid-client": { - "version": "5.7.1", - "resolved": "https://registry.npmjs.org/openid-client/-/openid-client-5.7.1.tgz", - "integrity": "sha512-jDBPgSVfTnkIh71Hg9pRvtJc6wTwqjRkN88+gCFtYWrlP4Yx2Dsrow8uPi3qLr/aeymPF3o2+dS+wOpglK04ew==", - "license": "MIT", + "node_modules/playwright": { + "version": "1.64.0", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.64.0.tgz", + "integrity": "sha512-kVzTnYFYEyQ9RGzBjNCd2+yEqWmVbxl3AHPynv3qQ6JTjv4a+kwRcnqQwIpuP3NnrnIrE/Q6wWAIAvMfIE2/Yg==", + "devOptional": true, + "license": "Apache-2.0", "dependencies": { - "jose": "^4.15.9", - "lru-cache": "^6.0.0", - "object-hash": "^2.2.0", - "oidc-token-hash": "^5.0.3" + "playwright-core": "1.64.0" }, - "funding": { - "url": "https://github.com/sponsors/panva" + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" } }, - "node_modules/openid-client/node_modules/lru-cache": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", - "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", - "license": "ISC", - "dependencies": { - "yallist": "^4.0.0" + "node_modules/playwright-core": { + "version": "1.64.0", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.64.0.tgz", + "integrity": "sha512-T9r+MZkTECl2+oUcZ26YgZzTrYidTsIhYYkJix+6iDOymOb1FB2RLLSOxRGnZGv5DStt+aduIVbt+E8WygXYpg==", + "devOptional": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" }, "engines": { - "node": ">=10" + "node": ">=20" } }, - "node_modules/optionator": { - "version": "0.9.4", - "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", - "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==", + "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", - "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": ">= 0.4" } }, - "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, + "node_modules/postcss": { + "version": "8.5.29", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.29.tgz", + "integrity": "sha512-49cGhUbXj8Qenv0iTMxA1cFBzxXoctpC9Ujd77t1WcbJIr6nF/eI7g/8MgxrYldFRuAXvja7xQRwavoW7kgrxQ==", + "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": { - "get-intrinsic": "^1.2.6", - "object-keys": "^1.1.1", - "safe-push-apply": "^1.0.0" + "nanoid": "^3.3.19", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" }, "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" + "node": "^10 || ^12 || >=14" } - }, - "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, + }, + "node_modules/postcss-selector-parser": { + "version": "7.1.6", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.6.tgz", + "integrity": "sha512-7qASPzhKF2l2KLboRZux8CCTRMdGiV08vWmyKzPz22qZ7ZjQBOeY7rNzNoCLSUiftJ7HUq0GERHmxw/t0dCdMw==", "license": "MIT", "dependencies": { - "yocto-queue": "^0.1.0" + "cssesc": "^3.0.0", + "util-deprecate": "^1.0.2" }, "engines": { - "node": ">=10" + "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": { - "url": "https://github.com/sponsors/sindresorhus" + "type": "individual", + "url": "https://github.com/sponsors/porsager" } }, - "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, + "node_modules/postgres-array": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-3.0.4.tgz", + "integrity": "sha512-nAUSGfSDGOaOAEGwqsRY27GPOea7CNipJPOA7lPbdEpx5Kg3qzdP0AaWC5MlhTWV9s4hFX39nomVZ+C4tnGOJQ==", "license": "MIT", - "dependencies": { - "p-limit": "^3.0.2" - }, "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "node": ">=12" } }, - "node_modules/parent-module": { + "node_modules/postgres-bytea": { "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==", - "dev": true, + "resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.1.tgz", + "integrity": "sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==", "license": "MIT", - "dependencies": { - "callsites": "^3.0.0" - }, "engines": { - "node": ">=6" + "node": ">=0.10.0" } }, - "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, + "node_modules/postgres-date": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz", + "integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==", "license": "MIT", "engines": { - "node": ">=8" + "node": ">=0.10.0" } }, - "node_modules/path-is-absolute": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", - "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", - "dev": true, + "node_modules/postgres-interval": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz", + "integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==", "license": "MIT", + "dependencies": { + "xtend": "^4.0.0" + }, "engines": { "node": ">=0.10.0" } }, - "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==", - "devOptional": true, + "node_modules/powershell-utils": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/powershell-utils/-/powershell-utils-0.2.1.tgz", + "integrity": "sha512-C+y9x90UElAddDZmV4qOx9W53B61PO7cIqWz2dQsWlwswuq4mr8NEwytdGKboYbQlGZ3awrkTeNvcZiZNHnQ8A==", "license": "MIT", "engines": { - "node": ">=8" + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "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/preact": { + "version": "10.29.1", + "resolved": "https://registry.npmjs.org/preact/-/preact-10.29.1.tgz", + "integrity": "sha512-gQCLc/vWroE8lIpleXtdJhTFDogTdZG9AjMUpVkDf2iTCNwYNWA+u16dL41TqUDJO4gm2IgrcMv3uTpjd4Pwmg==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/preact" + } }, - "node_modules/path-scurry": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-1.11.1.tgz", - "integrity": "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==", - "dev": true, - "license": "BlueOak-1.0.0", + "node_modules/preact-render-to-string": { + "version": "5.2.6", + "resolved": "https://registry.npmjs.org/preact-render-to-string/-/preact-render-to-string-5.2.6.tgz", + "integrity": "sha512-JyhErpYOvBV1hEPwIxc/fHWXPfnEGdRKxc8gFdAZ7XV4tlzyzG847XAyEZqoDnynP88akM4eaHcSOzNcLWFguw==", + "license": "MIT", "dependencies": { - "lru-cache": "^10.2.0", - "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" + "pretty-format": "^3.8.0" }, + "peerDependencies": { + "preact": ">=10" + } + }, + "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": ">=16 || 14 >=14.18" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" + "node": ">= 0.8.0" } }, - "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, + "node_modules/pretty-format": { + "version": "3.8.0", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-3.8.0.tgz", + "integrity": "sha512-WuxUnVtlWL1OfZFQFuqvnvs6MiAGk9UNsBostyBOB0Is9wb5uRESevA6rnl/rkksXaGX3GzZhPup5d6Vp1nFew==", "license": "MIT" }, - "node_modules/pdf-parse": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/pdf-parse/-/pdf-parse-1.1.1.tgz", - "integrity": "sha512-v6ZJ/efsBpGrGGknjtq9J/oC8tZWq0KWL5vQrk2GlzLEQPUDB1ex+13Rmidl1neNN358Jn9EHZw5y07FFtaC7A==", + "node_modules/pretty-ms": { + "version": "9.3.1", + "resolved": "https://registry.npmjs.org/pretty-ms/-/pretty-ms-9.3.1.tgz", + "integrity": "sha512-HzMy3Geq23nVALD/M2LliU+F+M+gVNsvkQWWqeBZ8HDiCgzo6YPJ/Omrmtq24EFrIsk0a3EkQGEd7bDOo+IhGA==", "license": "MIT", "dependencies": { - "debug": "^3.1.0", - "node-ensure": "^0.0.0" + "parse-ms": "^4.0.0" }, "engines": { - "node": ">=6.8.1" + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "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==", + "node_modules/prisma": { + "version": "7.10.0", + "resolved": "https://registry.npmjs.org/prisma/-/prisma-7.10.0.tgz", + "integrity": "sha512-o0ornyJOWgygVAzGCpr8PdXV8EJLHyVGDDUr/voBQt8Azzw8cYTByzzPGcA/m4tCkPcnJA8raEOv2CslsKhPEw==", "devOptional": true, - "license": "MIT" - }, - "node_modules/pg": { - "version": "8.20.0", - "resolved": "https://registry.npmjs.org/pg/-/pg-8.20.0.tgz", - "integrity": "sha512-ldhMxz2r8fl/6QkXnBD3CR9/xg694oT6DZQ2s6c/RI28OjtSOpxnPrUCGOBJ46RCUxcWdx3p6kw/xnDHjKvaRA==", - "license": "MIT", + "hasInstallScript": true, + "license": "Apache-2.0", "dependencies": { - "pg-connection-string": "^2.12.0", - "pg-pool": "^3.13.0", - "pg-protocol": "^1.13.0", - "pg-types": "2.2.0", - "pgpass": "1.0.5" + "@prisma/config": "7.10.0", + "@prisma/dev": "0.24.17", + "@prisma/engines": "7.10.0", + "@prisma/studio-core": "0.33.0", + "mysql2": "3.15.3", + "postgres": "3.4.7" }, - "engines": { - "node": ">= 16.0.0" + "bin": { + "prisma": "build/index.js" }, - "optionalDependencies": { - "pg-cloudflare": "^1.3.0" + "engines": { + "node": "^20.19 || ^22.12 || >=24.0" }, "peerDependencies": { - "pg-native": ">=3.0.1" + "better-sqlite3": ">=9.0.0", + "typescript": ">=5.4.0" }, "peerDependenciesMeta": { - "pg-native": { + "better-sqlite3": { + "optional": true + }, + "typescript": { "optional": true } } }, - "node_modules/pg-cloudflare": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.3.0.tgz", - "integrity": "sha512-6lswVVSztmHiRtD6I8hw4qP/nDm1EJbKMRhf3HCYaqud7frGysPv7FYJ5noZQdhQtN2xJnimfMtvQq21pdbzyQ==", + "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", - "optional": true - }, - "node_modules/pg-connection-string": { - "version": "2.12.0", - "resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.12.0.tgz", - "integrity": "sha512-U7qg+bpswf3Cs5xLzRqbXbQl85ng0mfSV/J0nnA31MCLgvEaAo7CIhmeyrmJpOr7o+zm0rXK+hNnT5l9RHkCkQ==", - "license": "MIT" - }, - "node_modules/pg-int8": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz", - "integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==", - "license": "ISC", + "dependencies": { + "kleur": "^3.0.3", + "sisteransi": "^1.0.5" + }, "engines": { - "node": ">=4.0.0" - } - }, - "node_modules/pg-pool": { - "version": "3.13.0", - "resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.13.0.tgz", - "integrity": "sha512-gB+R+Xud1gLFuRD/QgOIgGOBE2KCQPaPwkzBBGC9oG69pHTkhQeIuejVIk3/cnDyX39av2AxomQiyPT13WKHQA==", - "license": "MIT", - "peerDependencies": { - "pg": ">=8.0" + "node": ">= 6" } }, - "node_modules/pg-protocol": { - "version": "1.13.0", - "resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.13.0.tgz", - "integrity": "sha512-zzdvXfS6v89r6v7OcFCHfHlyG/wvry1ALxZo4LqgUoy7W9xhBDMaqOuMiF3qEV45VqsN6rdlcehHrfDtlCPc8w==", - "license": "MIT" - }, - "node_modules/pg-types": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz", - "integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==", + "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", - "dependencies": { - "pg-int8": "1.0.1", - "postgres-array": "~2.0.0", - "postgres-bytea": "~1.0.0", - "postgres-date": "~1.0.4", - "postgres-interval": "^1.1.0" - }, "engines": { - "node": ">=4" + "node": ">=6" } }, - "node_modules/pg-types/node_modules/postgres-array": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz", - "integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==", + "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", - "engines": { - "node": ">=4" + "dependencies": { + "loose-envify": "^1.4.0", + "object-assign": "^4.1.1", + "react-is": "^16.13.1" } }, - "node_modules/pgpass": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.5.tgz", - "integrity": "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==", + "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": { - "split2": "^4.1.0" + "graceful-fs": "^4.2.4", + "retry": "^0.12.0", + "signal-exit": "^3.0.2" } }, - "node_modules/picocolors": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", - "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "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/picomatch": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz", - "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", - "dev": true, + "node_modules/property-information": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/property-information/-/property-information-7.2.0.tgz", + "integrity": "sha512-IAtzIB6sUiWaJYrX9smp3V46pBGbBeLFRGdh25kg1334VcBlD8HzhPeNIWQH9zhGmo2itIe25EHt9dQP7G5hmg==", "license": "MIT", - "engines": { - "node": ">=12" - }, "funding": { - "url": "https://github.com/sponsors/jonschlinkert" + "type": "github", + "url": "https://github.com/sponsors/wooorm" } }, - "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, + "node_modules/proxy-addr": { + "version": "2.0.8", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz", + "integrity": "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==", "license": "MIT", "dependencies": { - "confbox": "^0.2.2", - "exsolve": "^1.0.7", - "pathe": "^2.0.3" - } - }, - "node_modules/playwright": { - "version": "1.58.2", - "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.58.2.tgz", - "integrity": "sha512-vA30H8Nvkq/cPBnNw4Q8TWz1EJyqgpuinBcHET0YVJVFldr8JDNiU9LaWAE1KqSkRYazuaBhTpB5ZzShOezQ6A==", - "devOptional": true, - "license": "Apache-2.0", - "dependencies": { - "playwright-core": "1.58.2" - }, - "bin": { - "playwright": "cli.js" + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" }, "engines": { - "node": ">=18" - }, - "optionalDependencies": { - "fsevents": "2.3.2" - } - }, - "node_modules/playwright-core": { - "version": "1.58.2", - "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.58.2.tgz", - "integrity": "sha512-yZkEtftgwS8CsfYo7nm0KE8jsvm6i/PTgVtB8DL726wNf6H2IMsDuxCpJj59KDaxCtSnrWan2AeDqM7JBaultg==", - "devOptional": true, - "license": "Apache-2.0", - "bin": { - "playwright-core": "cli.js" + "node": ">= 0.10" }, - "engines": { - "node": ">=18" + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" } }, - "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==", + "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, - "hasInstallScript": true, "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], "engines": { - "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + "node": ">=6" } }, - "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", + "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.16.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.16.0.tgz", + "integrity": "sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA==", + "license": "BSD-3-Clause", + "dependencies": { + "es-define-property": "^1.0.1", + "side-channel": "^1.1.1" + }, "engines": { - "node": ">= 0.4" + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/postcss": { - "version": "8.4.31", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.31.tgz", - "integrity": "sha512-PS08Iboia9mts/2ygV3eLpY5ghnUcfLV/EXTOW1E2qYxJKGGBUtNjN76FYHnMs36RmARn41bC0AZmn+rR0OVpQ==", + "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": "opencollective", - "url": "https://opencollective.com/postcss/" + "type": "github", + "url": "https://github.com/sponsors/feross" }, { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/postcss" + "type": "patreon", + "url": "https://www.patreon.com/feross" }, { - "type": "github", - "url": "https://github.com/sponsors/ai" + "type": "consulting", + "url": "https://feross.org/support" } ], + "license": "MIT" + }, + "node_modules/radix-ui": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/radix-ui/-/radix-ui-1.8.0.tgz", + "integrity": "sha512-d2p7l6XzZ9agJABImQYTFSbALCqaieTEXs2TmVNpT4cFam6RD91rsucu0VhMs45Oe35rQVWJk8PoDej0z/w3yg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-accessible-icon": "1.2.0", + "@radix-ui/react-accordion": "1.3.0", + "@radix-ui/react-alert-dialog": "1.2.0", + "@radix-ui/react-arrow": "1.1.17", + "@radix-ui/react-aspect-ratio": "1.2.0", + "@radix-ui/react-avatar": "1.3.0", + "@radix-ui/react-checkbox": "1.4.0", + "@radix-ui/react-collapsible": "1.2.0", + "@radix-ui/react-collection": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-context-menu": "2.4.0", + "@radix-ui/react-dialog": "1.3.0", + "@radix-ui/react-direction": "1.2.0", + "@radix-ui/react-dismissable-layer": "1.2.0", + "@radix-ui/react-dropdown-menu": "2.2.0", + "@radix-ui/react-focus-guards": "1.2.0", + "@radix-ui/react-focus-scope": "1.3.0", + "@radix-ui/react-form": "0.3.0", + "@radix-ui/react-hover-card": "1.2.0", + "@radix-ui/react-label": "2.1.17", + "@radix-ui/react-menu": "2.2.0", + "@radix-ui/react-menubar": "1.2.0", + "@radix-ui/react-navigation-menu": "1.4.0", + "@radix-ui/react-one-time-password-field": "0.2.0", + "@radix-ui/react-password-toggle-field": "0.2.0", + "@radix-ui/react-popover": "1.3.0", + "@radix-ui/react-popper": "1.4.0", + "@radix-ui/react-portal": "1.2.0", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-progress": "1.2.0", + "@radix-ui/react-radio-group": "1.5.0", + "@radix-ui/react-roving-focus": "1.2.0", + "@radix-ui/react-scroll-area": "1.4.0", + "@radix-ui/react-select": "2.4.0", + "@radix-ui/react-separator": "1.2.0", + "@radix-ui/react-slider": "1.6.0", + "@radix-ui/react-slot": "1.5.0", + "@radix-ui/react-switch": "1.4.0", + "@radix-ui/react-tabs": "1.2.0", + "@radix-ui/react-toast": "1.3.0", + "@radix-ui/react-toggle": "1.2.0", + "@radix-ui/react-toggle-group": "1.2.0", + "@radix-ui/react-toolbar": "1.2.0", + "@radix-ui/react-tooltip": "1.4.0", + "@radix-ui/react-use-callback-ref": "1.1.5", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-effect-event": "0.0.5", + "@radix-ui/react-use-escape-keydown": "1.1.6", + "@radix-ui/react-use-is-hydrated": "0.1.3", + "@radix-ui/react-use-layout-effect": "1.1.4", + "@radix-ui/react-use-size": "1.1.5", + "@radix-ui/react-visually-hidden": "1.2.13" + }, + "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/node_modules/@radix-ui/primitive": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.2.0.tgz", + "integrity": "sha512-KABY+VMIRPJL+Vyzv/335FEhXXD/xDv8BMb1kl48/aXJZMH0LtHCTx5ga5RnxaEP3nZHtmTLf1P9vanmFX46bw==", + "license": "MIT" + }, + "node_modules/radix-ui/node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.5.tgz", + "integrity": "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==", + "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/node_modules/@radix-ui/react-primitive": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.2.0.tgz", + "integrity": "sha512-HCTSPMNqv55Qk0IX4geJbpyXazmqulcimwuyjxTkKi29v+QZbG2Zho9BnbBq4YS2PF+KlNb2CXoLz66uUmblkg==", "license": "MIT", "dependencies": { - "nanoid": "^3.3.6", - "picocolors": "^1.0.0", - "source-map-js": "^1.0.2" + "@radix-ui/react-slot": "1.5.0" }, - "engines": { - "node": "^10 || ^12 || >=14" + "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/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" + "node_modules/radix-ui/node_modules/@radix-ui/react-slot": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.5.0.tgz", + "integrity": "sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5" }, - "funding": { - "type": "individual", - "url": "https://github.com/sponsors/porsager" + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } } }, - "node_modules/postgres-array": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-3.0.4.tgz", - "integrity": "sha512-nAUSGfSDGOaOAEGwqsRY27GPOea7CNipJPOA7lPbdEpx5Kg3qzdP0AaWC5MlhTWV9s4hFX39nomVZ+C4tnGOJQ==", + "node_modules/radix-ui/node_modules/@radix-ui/react-toggle": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-toggle/-/react-toggle-1.2.0.tgz", + "integrity": "sha512-/of2DdH8CyZBURA70jNEG5sEcliMX/hA8seXcUnqG7s7p3gNzrZJtJEQbiMmE8n+VAeuEW9DY5HyemqF8OfvOA==", "license": "MIT", - "engines": { - "node": ">=12" + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-controllable-state": "1.3.0" + }, + "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/postgres-bytea": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.1.tgz", - "integrity": "sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==", + "node_modules/radix-ui/node_modules/@radix-ui/react-use-controllable-state": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-controllable-state/-/react-use-controllable-state-1.3.0.tgz", + "integrity": "sha512-TAcBI7bw2ljYCbv4+zuTSd6zICu8pRt6SDN2vJ/Z06K2MXh6I9WYFe/A9ovlFDtR5HVHGm5iDxDoABm/++dbKg==", "license": "MIT", - "engines": { - "node": ">=0.10.0" + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-use-effect-event": "0.0.5", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } } }, - "node_modules/postgres-date": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz", - "integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==", + "node_modules/radix-ui/node_modules/@radix-ui/react-use-effect-event": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-effect-event/-/react-use-effect-event-0.0.5.tgz", + "integrity": "sha512-7cshFL8HGS/7HEiHH+9kL9HBwp2sa9yX18Knwek6KYWmXwM7pegMgta2AXMQKI+rq3JnfSj9x8wYqFMTdG1Jgg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "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/node_modules/@radix-ui/react-use-layout-effect": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.4.tgz", + "integrity": "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw==", + "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/range-parser": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.3.0.tgz", + "integrity": "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==", "license": "MIT", "engines": { - "node": ">=0.10.0" + "node": ">= 0.6" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" } }, - "node_modules/postgres-interval": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz", - "integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==", + "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": { - "xtend": "^4.0.0" + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.7.0", + "unpipe": "~1.0.0" }, "engines": { - "node": ">=0.10.0" + "node": ">= 0.10" + } + }, + "node_modules/rc9": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/rc9/-/rc9-3.1.0.tgz", + "integrity": "sha512-ufjkNVzbRHKcCOmTahZkmVsyc3W+MSk3jY03m+a7tGHkIsdVMG9l10/3HvFbWkkKzY5VFp3pkRsIo/UYgmFL7Q==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "defu": "^6.1.7", + "destr": "^2.0.5" } }, - "node_modules/preact": { - "version": "10.29.1", - "resolved": "https://registry.npmjs.org/preact/-/preact-10.29.1.tgz", - "integrity": "sha512-gQCLc/vWroE8lIpleXtdJhTFDogTdZG9AjMUpVkDf2iTCNwYNWA+u16dL41TqUDJO4gm2IgrcMv3uTpjd4Pwmg==", + "node_modules/react": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/react/-/react-19.3.0.tgz", + "integrity": "sha512-E8LUcbtBWt20bbl2YoHfx4ZDBdxVTfOKtCZn9cDSJ4l6/nuoApcpIBcj47t2wZoVX8g2ZHuMHbiShgCR1T5Sog==", "license": "MIT", - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/preact" + "engines": { + "node": ">=0.10.0" } }, - "node_modules/preact-render-to-string": { - "version": "5.2.6", - "resolved": "https://registry.npmjs.org/preact-render-to-string/-/preact-render-to-string-5.2.6.tgz", - "integrity": "sha512-JyhErpYOvBV1hEPwIxc/fHWXPfnEGdRKxc8gFdAZ7XV4tlzyzG847XAyEZqoDnynP88akM4eaHcSOzNcLWFguw==", + "node_modules/react-dom": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.3.0.tgz", + "integrity": "sha512-JDk8dgif51OjFoDE70+OT9ICyYr+69HlmihNwp1+Nsfbna3t5sIiCa9ZJktDmQ4/1b/rn26hIAR2uYXDMr5r0Q==", "license": "MIT", "dependencies": { - "pretty-format": "^3.8.0" + "scheduler": "^0.28.0" }, "peerDependencies": { - "preact": ">=10" - } - }, - "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" + "react": "^19.3.0" } }, - "node_modules/pretty-format": { - "version": "3.8.0", - "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-3.8.0.tgz", - "integrity": "sha512-WuxUnVtlWL1OfZFQFuqvnvs6MiAGk9UNsBostyBOB0Is9wb5uRESevA6rnl/rkksXaGX3GzZhPup5d6Vp1nFew==", + "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/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", + "node_modules/react-markdown": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/react-markdown/-/react-markdown-10.1.0.tgz", + "integrity": "sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ==", + "license": "MIT", "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" + "@types/hast": "^3.0.0", + "@types/mdast": "^4.0.0", + "devlop": "^1.0.0", + "hast-util-to-jsx-runtime": "^2.0.0", + "html-url-attributes": "^3.0.0", + "mdast-util-to-hast": "^13.0.0", + "remark-parse": "^11.0.0", + "remark-rehype": "^11.0.0", + "unified": "^11.0.0", + "unist-util-visit": "^5.0.0", + "vfile": "^6.0.0" }, - "bin": { - "prisma": "build/index.js" + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" }, - "engines": { - "node": "^20.19 || ^22.12 || >=24.0" + "peerDependencies": { + "@types/react": ">=18", + "react": ">=18" + } + }, + "node_modules/react-redux": { + "version": "9.3.0", + "resolved": "https://registry.npmjs.org/react-redux/-/react-redux-9.3.0.tgz", + "integrity": "sha512-KQopgqFo/p/fgmAs5qz6p5RWaNAzq40WAu7fJIXnQpYxFPbJYtsJPWvGeF2rOBaY/kEuV77AVsX8TsQzKm+A/g==", + "license": "MIT", + "dependencies": { + "@types/use-sync-external-store": "^0.0.6", + "use-sync-external-store": "^1.4.0" }, "peerDependencies": { - "better-sqlite3": ">=9.0.0", - "typescript": ">=5.4.0" + "@types/react": "^18.2.25 || ^19", + "react": "^18.0 || ^19", + "redux": "^5.0.0" }, "peerDependenciesMeta": { - "better-sqlite3": { + "@types/react": { "optional": true }, - "typescript": { + "redux": { "optional": true } } }, - "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, + "node_modules/react-remove-scroll": { + "version": "2.7.2", + "resolved": "https://registry.npmjs.org/react-remove-scroll/-/react-remove-scroll-2.7.2.tgz", + "integrity": "sha512-Iqb9NjCCTt6Hf+vOdNIZGdTiH1QSqr27H/Ek9sv/a97gfueI/5h1s3yRi1nngzMUaOOToin5dI1dXKdXiF+u0Q==", "license": "MIT", "dependencies": { - "loose-envify": "^1.4.0", - "object-assign": "^4.1.1", - "react-is": "^16.13.1" + "react-remove-scroll-bar": "^2.3.7", + "react-style-singleton": "^2.2.3", + "tslib": "^2.1.0", + "use-callback-ref": "^1.3.3", + "use-sidecar": "^1.1.3" + }, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } } }, - "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, + "node_modules/react-remove-scroll-bar": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/react-remove-scroll-bar/-/react-remove-scroll-bar-2.3.8.tgz", + "integrity": "sha512-9r+yi9+mgU33AKcj6IbT9oRCO78WriSj6t/cF8DWBZJ9aOGPOTEDvdUDz1FwKim7QXWwmHqtdHnRJfhAxEG46Q==", "license": "MIT", "dependencies": { - "graceful-fs": "^4.2.4", - "retry": "^0.12.0", - "signal-exit": "^3.0.2" + "react-style-singleton": "^2.2.2", + "tslib": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } } }, - "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/punycode": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", - "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", - "dev": true, + "node_modules/react-style-singleton": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/react-style-singleton/-/react-style-singleton-2.2.3.tgz", + "integrity": "sha512-b6jSvxvVnyptAiLjbkWLE/lOnR4lfTtDAl+eUC7RZy+QQWc6wRzIV2CE6xBuMmDxc2qIihtDCZD5NPOFl7fRBQ==", "license": "MIT", + "dependencies": { + "get-nonce": "^1.0.0", + "tslib": "^2.0.0" + }, "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/queue-microtask": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", - "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" + "node": ">=10" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true } - ], - "license": "MIT" + } }, - "node_modules/rc9": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/rc9/-/rc9-2.1.2.tgz", - "integrity": "sha512-btXCnMmRIBINM2LDZoEmOogIZU7Qe7zn4BpomSKZ/ykbLObuBdvG+mFq11DL6fjH1DRwHhrlgtYWG96bJiC7Cg==", + "node_modules/readdirp": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-5.1.1.tgz", + "integrity": "sha512-Kko+Y5XQ6fM+Ce3dq3m9YGxnacYZYl9cA1wZjaF3Vbry2L3i1qVg8+CAgNPsXRArPMUMCaOR7oa9Nqntc43JKA==", "devOptional": true, "license": "MIT", - "dependencies": { - "defu": "^6.1.4", - "destr": "^2.0.3" + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "type": "individual", + "url": "https://paulmillr.com/funding/" } }, - "node_modules/react": { - "version": "18.3.1", - "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz", - "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==", + "node_modules/recast": { + "version": "0.23.21", + "resolved": "https://registry.npmjs.org/recast/-/recast-0.23.21.tgz", + "integrity": "sha512-mFAyJq9vUbSTARLZUvAEf1z3YxlvAwswbmxMx2mPA/MSm4KmpwvwvhsH/NIrZhyOuwD60Lzyw2qh83uCbgTPYw==", "license": "MIT", "dependencies": { - "loose-envify": "^1.1.0" + "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": ">=0.10.0" + "node": ">= 4" } }, - "node_modules/react-dom": { - "version": "18.3.1", - "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz", - "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==", + "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": { - "loose-envify": "^1.1.0", - "scheduler": "^0.23.2" + "@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": "^18.3.1" + "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/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==", - "dev": true, + "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/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, + "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", - "engines": { - "node": ">= 14.18.0" - }, - "funding": { - "type": "individual", - "url": "https://paulmillr.com/funding/" + "peerDependencies": { + "redux": "^5.0.0" } }, "node_modules/reflect.getprototypeof": { @@ -7111,6 +17866,72 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/remark-gfm": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/remark-gfm/-/remark-gfm-4.0.1.tgz", + "integrity": "sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg==", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "mdast-util-gfm": "^3.0.0", + "micromark-extension-gfm": "^3.0.0", + "remark-parse": "^11.0.0", + "remark-stringify": "^11.0.0", + "unified": "^11.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/remark-parse": { + "version": "11.0.0", + "resolved": "https://registry.npmjs.org/remark-parse/-/remark-parse-11.0.0.tgz", + "integrity": "sha512-FCxlKLNGknS5ba/1lmpYijMUzX2esxW5xQqjWxw2eHFfS2MSdaHVINFmhjo+qN1WhZhNimq0dZATN9pH0IDrpA==", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "mdast-util-from-markdown": "^2.0.0", + "micromark-util-types": "^2.0.0", + "unified": "^11.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/remark-rehype": { + "version": "11.1.2", + "resolved": "https://registry.npmjs.org/remark-rehype/-/remark-rehype-11.1.2.tgz", + "integrity": "sha512-Dh7l57ianaEoIpzbp0PC9UKAdCSVklD8E5Rpw7ETfbTl3FqcOOgq5q2LVDhgGCkaBv7p24JXikPdvhhmHvKMsw==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "@types/mdast": "^4.0.0", + "mdast-util-to-hast": "^13.0.0", + "unified": "^11.0.0", + "vfile": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/remark-stringify": { + "version": "11.0.0", + "resolved": "https://registry.npmjs.org/remark-stringify/-/remark-stringify-11.0.0.tgz", + "integrity": "sha512-1OSmLd3awB/t8qdoEOMazZkNsfVTeY4fTsgzcQFdXNq8ToTN4ZGwrMnlda4K6smTFKD+GRV6O48i6Z4iKgPPpw==", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "mdast-util-to-markdown": "^2.0.0", + "unified": "^11.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, "node_modules/remeda": { "version": "2.33.4", "resolved": "https://registry.npmjs.org/remeda/-/remeda-2.33.4.tgz", @@ -7125,12 +17946,17 @@ "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==", - "devOptional": true, "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", @@ -7159,17 +17985,58 @@ "dev": true, "license": "MIT", "engines": { - "node": ">=4" + "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/restore-cursor/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/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, + "node_modules/ret": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/ret/-/ret-0.5.0.tgz", + "integrity": "sha512-I1XxrZSQ+oErkRR4jYbAyEEu2I0avBvvMM5JN+6EBprOGRCs63ENqZ3vjavq8fBw2+62G5LF5XelKwuJpcvcxw==", + "devOptional": true, "license": "MIT", - "funding": { - "url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1" + "engines": { + "node": ">=10" } }, "node_modules/retry": { @@ -7186,39 +18053,28 @@ "version": "1.1.0", "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz", "integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==", - "dev": true, "license": "MIT", "engines": { "iojs": ">=1.0.0", "node": ">=0.10.0" } }, - "node_modules/rimraf": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", - "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", - "deprecated": "Rimraf versions prior to v4 are no longer supported", - "dev": true, - "license": "ISC", - "dependencies": { - "glob": "^7.1.3" - }, - "bin": { - "rimraf": "bin.js" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } + "node_modules/robust-predicates": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/robust-predicates/-/robust-predicates-3.0.3.tgz", + "integrity": "sha512-NS3levdsRIUOmiJ8FZWCP7LG3QpJyrs/TE0Zpf1yvZu8cAJJ6QMW92H1c7kWpdIHo8RvmLxN/o2JXTKHp74lUA==", + "devOptional": true, + "license": "Unlicense" }, "node_modules/rolldown": { - "version": "1.0.0-rc.12", - "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.0.0-rc.12.tgz", - "integrity": "sha512-yP4USLIMYrwpPHEFB5JGH1uxhcslv6/hL0OyvTuY+3qlOSJvZ7ntYnoWpehBxufkgN0cvXxppuTu5hHa/zPh+A==", + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.13.tgz", + "integrity": "sha512-/5apOkwWxtACcQtZ5WlrAsKS4JwXVThQPJZ3RqIruRY9UG9M8e0VlXN068xum/JRKA4aIUoJ13ghe/kGCvidiQ==", "dev": true, "license": "MIT", "dependencies": { - "@oxc-project/types": "=0.122.0", - "@rolldown/pluginutils": "1.0.0-rc.12" + "@oxc-project/types": "=0.153.0", + "@rolldown/pluginutils": "^1.0.0" }, "bin": { "rolldown": "bin/cli.mjs" @@ -7227,35 +18083,79 @@ "node": "^20.19.0 || >=22.12.0" }, "optionalDependencies": { - "@rolldown/binding-android-arm64": "1.0.0-rc.12", - "@rolldown/binding-darwin-arm64": "1.0.0-rc.12", - "@rolldown/binding-darwin-x64": "1.0.0-rc.12", - "@rolldown/binding-freebsd-x64": "1.0.0-rc.12", - "@rolldown/binding-linux-arm-gnueabihf": "1.0.0-rc.12", - "@rolldown/binding-linux-arm64-gnu": "1.0.0-rc.12", - "@rolldown/binding-linux-arm64-musl": "1.0.0-rc.12", - "@rolldown/binding-linux-ppc64-gnu": "1.0.0-rc.12", - "@rolldown/binding-linux-s390x-gnu": "1.0.0-rc.12", - "@rolldown/binding-linux-x64-gnu": "1.0.0-rc.12", - "@rolldown/binding-linux-x64-musl": "1.0.0-rc.12", - "@rolldown/binding-openharmony-arm64": "1.0.0-rc.12", - "@rolldown/binding-wasm32-wasi": "1.0.0-rc.12", - "@rolldown/binding-win32-arm64-msvc": "1.0.0-rc.12", - "@rolldown/binding-win32-x64-msvc": "1.0.0-rc.12" + "@rolldown/binding-android-arm-eabi": "1.2.13", + "@rolldown/binding-android-arm64": "1.2.13", + "@rolldown/binding-darwin-arm64": "1.2.13", + "@rolldown/binding-darwin-x64": "1.2.13", + "@rolldown/binding-freebsd-x64": "1.2.13", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.13", + "@rolldown/binding-linux-arm64-gnu": "1.2.13", + "@rolldown/binding-linux-arm64-musl": "1.2.13", + "@rolldown/binding-linux-ppc64-gnu": "1.2.13", + "@rolldown/binding-linux-s390x-gnu": "1.2.13", + "@rolldown/binding-linux-x64-gnu": "1.2.13", + "@rolldown/binding-linux-x64-musl": "1.2.13", + "@rolldown/binding-openharmony-arm64": "1.2.13", + "@rolldown/binding-win32-arm64-msvc": "1.2.13", + "@rolldown/binding-win32-x64-msvc": "1.2.13" } }, "node_modules/rolldown/node_modules/@rolldown/pluginutils": { - "version": "1.0.0-rc.12", - "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.12.tgz", - "integrity": "sha512-HHMwmarRKvoFsJorqYlFeFRzXZqCt2ETQlEDOb9aqssrnVBB1/+xgTGtuTrIk5vzLNX1MjMtTf7W9z3tsSbrxw==", + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz", + "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==", "dev": true, "license": "MIT" }, + "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/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/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==", - "dev": true, "funding": [ { "type": "github", @@ -7330,38 +18230,118 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/safe-regex2": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-regex2/-/safe-regex2-5.1.2.tgz", + "integrity": "sha512-tAtCGFPPP02VroDVzp4daGi6bC7jWG+41D47GKf18FeH/ubvKQHT9VmhAkvtjNOmJwqtApzWeUpEhkyEYULvmw==", + "devOptional": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "ret": "~0.5.0" + }, + "bin": { + "safe-regex2": "bin/safe-regex2.js" + } + }, "node_modules/safer-buffer": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", - "devOptional": true, "license": "MIT" }, "node_modules/scheduler": { - "version": "0.23.2", - "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz", - "integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==", - "license": "MIT", - "dependencies": { - "loose-envify": "^1.1.0" - } + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz", + "integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==", + "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==", - "dev": true, "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/send/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/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", @@ -7411,11 +18391,189 @@ "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.21.4", + "resolved": "https://registry.npmjs.org/shadcn/-/shadcn-4.21.4.tgz", + "integrity": "sha512-YYfn/hsHbRH2mGwnKBx9tk+DjTQH+RUMS5iCxjKzwzuJ5uoHPqLOFUCJSeX0sXfrcBSfgQaXiOLGKNLjlIQxxw==", + "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", + "@shadcn/registry": "0.1.3", + "@types/validate-npm-package-name": "^4.0.2", + "browserslist": "^4.26.2", + "cn": "^0.2.4", + "commander": "^14.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", + "kleur": "^4.1.5", + "open": "^11.0.0", + "ora": "^8.2.0", + "postcss": "^8.5.23", + "postcss-selector-parser": "^7.1.3", + "prompts": "^2.4.2", + "recast": "^0.23.11", + "socks": "^2.8.8", + "stringify-object": "^5.0.0", + "ts-morph": "^26.0.0", + "tsconfig-paths": "^4.2.0", + "undici": "^7.29.0", + "validate-npm-package-name": "^7.0.1", + "zod": "^3.24.1", + "zod-to-json-schema": "^3.24.6" + }, + "bin": { + "shadcn": "dist/index.js" + }, + "engines": { + "node": ">=20.18.1" + } + }, + "node_modules/shadcn/node_modules/cn": { + "version": "0.2.6", + "resolved": "https://registry.npmjs.org/cn/-/cn-0.2.6.tgz", + "integrity": "sha512-+i4L0zUGgRcEnhsxueVrP7iBGxBx5iD0WOTYg1MwFEu2ZyCmH5Ov2V1cul2Ht5UchRQQgftCf4be/RxspuW6QQ==", + "license": "MIT", + "bin": { + "cn": "bin/cn.mjs" + }, + "engines": { + "node": ">=20" + } + }, + "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.35.5", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.5.tgz", + "integrity": "sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@img/colour": "^1.1.0", + "detect-libc": "^2.1.2", + "semver": "^7.8.5" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-darwin-arm64": "0.35.5", + "@img/sharp-darwin-x64": "0.35.5", + "@img/sharp-freebsd-wasm32": "0.35.5", + "@img/sharp-libvips-darwin-arm64": "1.3.4", + "@img/sharp-libvips-darwin-x64": "1.3.4", + "@img/sharp-libvips-linux-arm": "1.3.4", + "@img/sharp-libvips-linux-arm64": "1.3.4", + "@img/sharp-libvips-linux-ppc64": "1.3.4", + "@img/sharp-libvips-linux-riscv64": "1.3.4", + "@img/sharp-libvips-linux-s390x": "1.3.4", + "@img/sharp-libvips-linux-x64": "1.3.4", + "@img/sharp-libvips-linuxmusl-arm64": "1.3.4", + "@img/sharp-libvips-linuxmusl-x64": "1.3.4", + "@img/sharp-linux-arm": "0.35.5", + "@img/sharp-linux-arm64": "0.35.5", + "@img/sharp-linux-ppc64": "0.35.5", + "@img/sharp-linux-riscv64": "0.35.5", + "@img/sharp-linux-s390x": "0.35.5", + "@img/sharp-linux-x64": "0.35.5", + "@img/sharp-linuxmusl-arm64": "0.35.5", + "@img/sharp-linuxmusl-x64": "0.35.5", + "@img/sharp-webcontainers-wasm32": "0.35.5", + "@img/sharp-win32-arm64": "0.35.5", + "@img/sharp-win32-ia32": "0.35.5", + "@img/sharp-win32-x64": "0.35.5" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/sharp/node_modules/semver": { + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "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==", - "devOptional": true, "license": "MIT", "dependencies": { "shebang-regex": "^3.0.0" @@ -7428,22 +18586,20 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", - "devOptional": true, "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==", - "dev": true, + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz", + "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==", "license": "MIT", "dependencies": { "es-errors": "^1.3.0", - "object-inspect": "^1.13.3", - "side-channel-list": "^1.0.0", + "object-inspect": "^1.13.4", + "side-channel-list": "^1.0.1", "side-channel-map": "^1.0.1", "side-channel-weakmap": "^1.0.2" }, @@ -7455,14 +18611,13 @@ } }, "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==", - "dev": true, + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", + "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", "license": "MIT", "dependencies": { "es-errors": "^1.3.0", - "object-inspect": "^1.13.3" + "object-inspect": "^1.13.4" }, "engines": { "node": ">= 0.4" @@ -7475,7 +18630,6 @@ "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==", - "dev": true, "license": "MIT", "dependencies": { "call-bound": "^1.0.2", @@ -7494,7 +18648,6 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", - "dev": true, "license": "MIT", "dependencies": { "call-bound": "^1.0.2", @@ -7521,7 +18674,6 @@ "version": "4.1.0", "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", - "devOptional": true, "license": "ISC", "engines": { "node": ">=14" @@ -7534,18 +18686,76 @@ "version": "1.0.5", "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz", "integrity": "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==", - "devOptional": true, "license": "MIT" }, + "node_modules/smart-buffer": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz", + "integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==", + "license": "MIT", + "engines": { + "node": ">= 6.0.0", + "npm": ">= 3.0.0" + } + }, + "node_modules/socks": { + "version": "2.8.10", + "resolved": "https://registry.npmjs.org/socks/-/socks-2.8.10.tgz", + "integrity": "sha512-e0VyvkVTwVYViNovRkZ9aodhxVlyoMn7eJhVUPxZ+eK9P/7CBkxvvsBOHqFPEH416726W8tLXXXjKwqgTErrCQ==", + "license": "MIT", + "dependencies": { + "ip-address": "^10.1.1", + "smart-buffer": "^4.2.0" + }, + "engines": { + "node": ">= 10.0.0", + "npm": ">= 3.0.0" + } + }, + "node_modules/sonner": { + "version": "2.0.8", + "resolved": "https://registry.npmjs.org/sonner/-/sonner-2.0.8.tgz", + "integrity": "sha512-UM/ByIoFra8yzV75n1o0Puu0bw5U/9UNnDacrJNspekBewIfsQ3D6ez1nvlWpt7aTsO6rujQtifBpycwIivqlg==", + "license": "MIT", + "peerDependencies": { + "@types/react": "^18.0.0 || ^19.0.0", + "react": "^18.0.0 || ^19.0.0 || ^19.0.0-rc", + "react-dom": "^18.0.0 || ^19.0.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "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==", + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", "license": "BSD-3-Clause", "engines": { "node": ">=0.10.0" } }, + "node_modules/space-separated-tokens": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/space-separated-tokens/-/space-separated-tokens-2.0.2.tgz", + "integrity": "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/split2": { "version": "4.2.0", "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz", @@ -7579,6 +18789,15 @@ "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", @@ -7586,6 +18805,18 @@ "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", @@ -7600,60 +18831,27 @@ "node": ">= 0.4" } }, - "node_modules/streamsearch": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz", - "integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==", - "engines": { - "node": ">=10.0.0" - } - }, "node_modules/string-width": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz", - "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==", - "dev": true, + "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": { - "eastasianwidth": "^0.2.0", - "emoji-regex": "^9.2.2", - "strip-ansi": "^7.0.1" + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" }, "engines": { - "node": ">=12" + "node": ">=18" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/string-width-cjs": { - "name": "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==", - "dev": true, - "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/string-width-cjs/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==", - "dev": true, - "license": "MIT" - }, "node_modules/string-width/node_modules/ansi-regex": { - "version": "6.2.2", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz", - "integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==", - "dev": true, + "version": "6.4.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.4.0.tgz", + "integrity": "sha512-KzTVk2tCWAHtYrvvvaP8bJKJq2pVinhLcGEQdtLIYPbmNGNyYe8QwNaTUYQp2J7/vIsUKt5QCqAfUkYyG9DkOw==", "license": "MIT", "engines": { "node": ">=12" @@ -7662,11 +18860,16 @@ "url": "https://github.com/chalk/ansi-regex?sponsor=1" } }, + "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-width/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==", - "dev": true, "license": "MIT", "dependencies": { "ansi-regex": "^6.2.2" @@ -7791,25 +18994,53 @@ "url": "https://github.com/sponsors/ljharb" } }, - "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==", - "dev": true, + "node_modules/stringify-entities": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/stringify-entities/-/stringify-entities-4.0.4.tgz", + "integrity": "sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg==", "license": "MIT", "dependencies": { - "ansi-regex": "^5.0.1" + "character-entities-html4": "^2.0.0", + "character-entities-legacy": "^3.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "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": ">=8" + "node": ">=14.16" + }, + "funding": { + "url": "https://github.com/yeoman/stringify-object?sponsor=1" + } + }, + "node_modules/stringify-object/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/strip-ansi-cjs": { - "name": "strip-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==", - "dev": true, "license": "MIT", "dependencies": { "ansi-regex": "^5.0.1" @@ -7822,12 +19053,23 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", "integrity": "sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==", - "dev": true, "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", @@ -7841,10 +19083,28 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/style-to-js": { + "version": "1.1.21", + "resolved": "https://registry.npmjs.org/style-to-js/-/style-to-js-1.1.21.tgz", + "integrity": "sha512-RjQetxJrrUJLQPHbLku6U/ocGtzyjbJMP9lCNK7Ag0CNh690nSH8woqWH9u16nMjYBAok+i7JO1NP2pOy8IsPQ==", + "license": "MIT", + "dependencies": { + "style-to-object": "1.0.14" + } + }, + "node_modules/style-to-object": { + "version": "1.0.14", + "resolved": "https://registry.npmjs.org/style-to-object/-/style-to-object-1.0.14.tgz", + "integrity": "sha512-LIN7rULI0jBscWQYaSswptyderlarFkjQ+t79nzty8tcIAceVomEVlLzH5VP4Cmsv6MtKhs7qaAiwlcp+Mgaxw==", + "license": "MIT", + "dependencies": { + "inline-style-parser": "0.2.7" + } + }, "node_modules/styled-jsx": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/styled-jsx/-/styled-jsx-5.1.1.tgz", - "integrity": "sha512-pW7uC1l4mBZ8ugbiZrcIsiIvVx1UmTfw7UkC3Um2tmfUq9Bhk8IiyEIPl6F8agHgjzku6j0xQEZbfA5uSgSaCw==", + "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" @@ -7853,7 +19113,7 @@ "node": ">= 12.0.0" }, "peerDependencies": { - "react": ">= 16.8.0 || 17.x.x || ^18.0.0-0" + "react": ">= 16.8.0 || 17.x.x || ^18.0.0-0 || ^19.0.0-0" }, "peerDependenciesMeta": { "@babel/core": { @@ -7890,13 +19150,72 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/text-table": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", - "integrity": "sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw==", + "node_modules/swr": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/swr/-/swr-2.5.1.tgz", + "integrity": "sha512-BRw55e8r0B7SpDN20CAzoQAHl7y1yP7/Zt7oqUjMv0vSt2u2Xnkm88Ws+VypbV9BXHQVuSuyVq7zMjO16wSExw==", + "license": "MIT", + "dependencies": { + "dequal": "^2.0.3", + "use-sync-external-store": "^1.6.0" + }, + "peerDependencies": { + "react": "^16.11.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, + "node_modules/systeminformation": { + "version": "5.33.15", + "resolved": "https://registry.npmjs.org/systeminformation/-/systeminformation-5.33.15.tgz", + "integrity": "sha512-s5RloL0F7xhN0ZjfHtLGnbf7EW74EI0N8NFL+1xR7Oxz9QA33obNZsl7lyfnJOhN04E/kGFPoJPlvY7TZ5fzmw==", + "license": "MIT", + "os": [ + "darwin", + "linux", + "win32", + "freebsd", + "openbsd", + "netbsd", + "sunos", + "android" + ], + "bin": { + "systeminformation": "lib/cli.js" + }, + "engines": { + "node": ">=10.0.0" + }, + "funding": { + "type": "Buy me a coffee", + "url": "https://www.buymeacoffee.com/systeminfo" + } + }, + "node_modules/tailwindcss": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.3.3.tgz", + "integrity": "sha512-gOhV3P7ufE62QDGg1zVaTgCR+EtPv92k2nIhVcVKcLmxT1sUBsQGhnZj175j+MqRt4zLF7ic+sCYjfhxMxj7YQ==", "dev": true, "license": "MIT" }, + "node_modules/tapable": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.3.3.tgz", + "integrity": "sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + }, + "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", @@ -7908,21 +19227,21 @@ "version": "1.0.4", "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.0.4.tgz", "integrity": "sha512-u9r3uZC0bdpGOXtlxUIdwf9pkmvhqJdrVCH9fapQtgy/OeTTMZ1nqH7agtvEfmGui6e1XxjcdrlxvxJvc3sMqw==", - "devOptional": true, + "dev": 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==", + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", "dev": true, "license": "MIT", "dependencies": { "fdir": "^6.5.0", - "picomatch": "^4.0.3" + "picomatch": "^4.0.4" }, "engines": { "node": ">=12.0.0" @@ -7932,15 +19251,56 @@ } }, "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==", + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.2.0.tgz", + "integrity": "sha512-LgO3D9yZJjApUiuUfl9iFAwrtaX4+lok3wJIqttGoKCHlWUqHqbQpnxCf82L8FjgKsh4iGo78hqJwgL8F6To2A==", "dev": true, "license": "MIT", "engines": { "node": ">=14.0.0" } }, + "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/trim-lines": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/trim-lines/-/trim-lines-3.0.1.tgz", + "integrity": "sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/trough": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/trough/-/trough-2.2.0.tgz", + "integrity": "sha512-tmMpK00BjZiUyVyvrBK7knerNgmgvcV/KLVyuma/SC+TQN167GrMRciANTz09+k3zW8L8t60jWO1GpfkZdjTaw==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/ts-api-utils": { "version": "2.5.0", "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.5.0.tgz", @@ -7954,6 +19314,16 @@ "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", @@ -8006,6 +19376,15 @@ "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", @@ -8020,18 +19399,48 @@ } }, "node_modules/type-fest": { - "version": "0.20.2", - "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", - "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", - "dev": true, + "version": "4.41.0", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-4.41.0.tgz", + "integrity": "sha512-TeTSQ6H5YHvpqVwBRcnLDCBnDOHWYu7IvGbHT6N8AOymcr9PJGjc1GTtiWZTYg0NCgYwvnYWEkVChQAr9bjfwA==", "license": "(MIT OR CC0-1.0)", "engines": { - "node": ">=10" + "node": ">=16" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/type-is": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz", + "integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==", + "license": "MIT", + "dependencies": { + "content-type": "^2.0.0", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/type-is/node_modules/content-type": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/typed-array-buffer": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/typed-array-buffer/-/typed-array-buffer-1.0.3.tgz", @@ -8124,30 +19533,180 @@ "node": ">=14.17" } }, - "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, + "node_modules/typescript-eslint": { + "version": "8.71.1", + "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.71.1.tgz", + "integrity": "sha512-oiNVPC3/NbV1FpaHU07l8O6ynqG9v4PAiW2WvTrAmZdR0f2HI/gE668ElMLCK7Xbsu5k2fK5C4fXNiq05j7/nQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/eslint-plugin": "8.71.1", + "@typescript-eslint/parser": "8.71.1", + "@typescript-eslint/typescript-estree": "8.71.1", + "@typescript-eslint/utils": "8.71.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.1.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": { + "version": "7.30.0", + "resolved": "https://registry.npmjs.org/undici/-/undici-7.30.0.tgz", + "integrity": "sha512-dkrQXeHSaoamnItlYbmzG0wFYrM0ZwDxCIg0A7aKjTyyhh9svRzCNFEzV+Vm05/yehjCzjDZ31KXfGEjYSztDQ==", + "license": "MIT", + "engines": { + "node": ">=20.18.1" + } + }, + "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/unified": { + "version": "11.0.5", + "resolved": "https://registry.npmjs.org/unified/-/unified-11.0.5.tgz", + "integrity": "sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA==", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "bail": "^2.0.0", + "devlop": "^1.0.0", + "extend": "^3.0.0", + "is-plain-obj": "^4.0.0", + "trough": "^2.0.0", + "vfile": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-is": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/unist-util-is/-/unist-util-is-6.0.1.tgz", + "integrity": "sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g==", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-position": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/unist-util-position/-/unist-util-position-5.0.0.tgz", + "integrity": "sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA==", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-stringify-position": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/unist-util-stringify-position/-/unist-util-stringify-position-4.0.0.tgz", + "integrity": "sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ==", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-visit": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/unist-util-visit/-/unist-util-visit-5.1.0.tgz", + "integrity": "sha512-m+vIdyeCOpdr/QeQCu2EzxX/ohgS8KbnPDgFni4dQsfSCtpz8UqDyY5GjRru8PDKuYn7Fq19j1CQ+nJSsGKOzg==", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "unist-util-is": "^6.0.0", + "unist-util-visit-parents": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-visit-parents": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-6.0.2.tgz", + "integrity": "sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ==", "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" + "@types/unist": "^3.0.0", + "unist-util-is": "^6.0.0" }, "funding": { - "url": "https://github.com/sponsors/ljharb" + "type": "opencollective", + "url": "https://opencollective.com/unified" } }, - "node_modules/undici-types": { - "version": "7.18.2", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.18.2.tgz", - "integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==", - "license": "MIT" + "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", @@ -8184,6 +19743,36 @@ "@unrs/resolver-binding-win32-x64-msvc": "1.11.1" } }, + "node_modules/update-browserslist-db": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.4.tgz", + "integrity": "sha512-t8wonIOdQyOjtPd2VktlBu6QjTVTks6v8bSi7kd0r2Vll8TK1JYDZtRRdbmCHOAMphkZgrzK+L+vXK4pyZ8t4A==", + "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", @@ -8194,19 +19783,81 @@ "punycode": "^2.1.0" } }, + "node_modules/use-callback-ref": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/use-callback-ref/-/use-callback-ref-1.3.3.tgz", + "integrity": "sha512-jQL3lRnocaFtu3V00JToYz/4QkNWswxijDaCVNZRiRTO3HQDLsdu1ZtmIUvV4yPp+rvWm5j0y0TG/S61cuijTg==", + "license": "MIT", + "dependencies": { + "tslib": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/use-sidecar": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/use-sidecar/-/use-sidecar-1.1.3.tgz", + "integrity": "sha512-Fedw0aZvkhynoPYlA5WXrMCAMm+nSWdZt6lzJQ7Ok8S6Q+VsHmHpRWndVRJ8Be0ZbkfPc5LRYH+5XrzXcEeLRQ==", + "license": "MIT", + "dependencies": { + "detect-node-es": "^1.1.0", + "tslib": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/use-sync-external-store": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.7.0.tgz", + "integrity": "sha512-6L+EeigHMQhdaIPNIFUKwfWJSwWFQ8gJbJ2DLOs5sDIegTwR9fRxvnM3uciHKjIZhFz+KAv2emhWMRvDmMcY8A==", + "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": "8.3.2", - "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", - "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", + "version": "11.1.1", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-11.1.1.tgz", + "integrity": "sha512-vIYxrBCC/N/K+Js3qSN88go7kIfNPssr/hHCesKCQNAjmgvYS2oqr69kIufEG+O4+PfezOH4EbIeHCfFov8ZgQ==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], "license": "MIT", "bin": { - "uuid": "dist/bin/uuid" + "uuid": "dist/esm/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==", + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/valibot/-/valibot-1.4.2.tgz", + "integrity": "sha512-gjdCvJ6d3RyHAneqxMYMW9QMCwYMb3jpOO0IyHZV1bnRHFBHrX3VkIILt5XYR0WhwHiH7Mty8ovuPZ/O3gamrg==", "devOptional": true, "license": "MIT", "peerDependencies": { @@ -8218,18 +19869,86 @@ } } }, + "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/vfile": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/vfile/-/vfile-6.0.3.tgz", + "integrity": "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q==", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "vfile-message": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/vfile-message": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/vfile-message/-/vfile-message-4.0.3.tgz", + "integrity": "sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw==", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "unist-util-stringify-position": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "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.3", - "resolved": "https://registry.npmjs.org/vite/-/vite-8.0.3.tgz", - "integrity": "sha512-B9ifbFudT1TFhfltfaIPgjo9Z3mDynBTJSUYxTjOQruf/zHH+ezCQKcoqO+h7a9Pw9Nm/OtlXAiGT1axBgwqrQ==", + "version": "8.3.4", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.4.tgz", + "integrity": "sha512-IftLE8phJhdNRIGNEV4JCCvfNScoZQVfcXaN8TQropWGJtOHcu+iAB9pHcuGvmEb/kddw0LBe/jS8ztdC6xdiQ==", "dev": true, "license": "MIT", "dependencies": { - "lightningcss": "^1.32.0", - "picomatch": "^4.0.4", - "postcss": "^8.5.8", - "rolldown": "1.0.0-rc.12", - "tinyglobby": "^0.2.15" + "lightningcss": "^1.33.0", + "picomatch": "^4.0.7", + "postcss": "^8.5.29", + "rolldown": "~1.2.12", + "tinyglobby": "^0.2.17" }, "bin": { "vite": "bin/vite.js" @@ -8245,8 +19964,8 @@ }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", - "@vitejs/devtools": "^0.1.0", - "esbuild": "^0.27.0", + "@vitejs/devtools": "^0.7.1", + "esbuild": "^0.27.0 || ^0.28.0", "jiti": ">=1.21.0", "less": "^4.0.0", "sass": "^1.70.0", @@ -8296,49 +20015,20 @@ } } }, - "node_modules/vite/node_modules/postcss": { - "version": "8.5.8", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.8.tgz", - "integrity": "sha512-OW/rX8O/jXnm82Ey1k44pObPtdblfiuWnrd8X7GJ7emImCOstunGbXUpp7HdBrFQX6rJzn3sPT397Wp5aCwCHg==", - "dev": true, - "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/vitest": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.2.tgz", - "integrity": "sha512-xjR1dMTVHlFLh98JE3i/f/WePqJsah4A0FK9cc8Ehp9Udk0AZk6ccpIZhh1qJ/yxVWRZ+Q54ocnD8TXmkhspGg==", + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.11.tgz", + "integrity": "sha512-fhACrNXUidIbGSBr5FlbuBkO7VWC1ZyLl0DO4CU2DrQoAPxX84Ysxs+HeGQpii5lZWV1Q4gBZTTu49mF+A6Edw==", "dev": true, "license": "MIT", "dependencies": { - "@vitest/expect": "4.1.2", - "@vitest/mocker": "4.1.2", - "@vitest/pretty-format": "4.1.2", - "@vitest/runner": "4.1.2", - "@vitest/snapshot": "4.1.2", - "@vitest/spy": "4.1.2", - "@vitest/utils": "4.1.2", + "@vitest/expect": "4.1.11", + "@vitest/mocker": "4.1.11", + "@vitest/pretty-format": "4.1.11", + "@vitest/runner": "4.1.11", + "@vitest/snapshot": "4.1.11", + "@vitest/spy": "4.1.11", + "@vitest/utils": "4.1.11", "es-module-lexer": "^2.0.0", "expect-type": "^1.3.0", "magic-string": "^0.30.21", @@ -8366,10 +20056,12 @@ "@edge-runtime/vm": "*", "@opentelemetry/api": "^1.9.0", "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", - "@vitest/browser-playwright": "4.1.2", - "@vitest/browser-preview": "4.1.2", - "@vitest/browser-webdriverio": "4.1.2", - "@vitest/ui": "4.1.2", + "@vitest/browser-playwright": "4.1.11", + "@vitest/browser-preview": "4.1.11", + "@vitest/browser-webdriverio": "4.1.11", + "@vitest/coverage-istanbul": "4.1.11", + "@vitest/coverage-v8": "4.1.11", + "@vitest/ui": "4.1.11", "happy-dom": "*", "jsdom": "*", "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" @@ -8393,6 +20085,12 @@ "@vitest/browser-webdriverio": { "optional": true }, + "@vitest/coverage-istanbul": { + "optional": true + }, + "@vitest/coverage-v8": { + "optional": true + }, "@vitest/ui": { "optional": true }, @@ -8418,7 +20116,6 @@ "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", - "devOptional": true, "license": "ISC", "dependencies": { "isexe": "^2.0.0" @@ -8546,114 +20243,28 @@ "node": ">=0.10.0" } }, - "node_modules/wrap-ansi": { - "version": "8.1.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz", - "integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-styles": "^6.1.0", - "string-width": "^5.0.1", - "strip-ansi": "^7.0.1" - }, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/wrap-ansi?sponsor=1" - } - }, - "node_modules/wrap-ansi-cjs": { - "name": "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==", - "dev": true, - "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/wrap-ansi-cjs/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==", - "dev": true, - "license": "MIT" - }, - "node_modules/wrap-ansi-cjs/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==", - "dev": true, - "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/ansi-regex": { - "version": "6.2.2", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz", - "integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/ansi-regex?sponsor=1" - } - }, - "node_modules/wrap-ansi/node_modules/ansi-styles": { - "version": "6.2.3", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", - "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" - } + "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/wrap-ansi/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==", - "dev": true, + "node_modules/wsl-utils": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/wsl-utils/-/wsl-utils-1.0.1.tgz", + "integrity": "sha512-c16PKLIRxBYpR3jSWsdS7SFp0COm5SOQdiFjY818dYFHJbMGuLBszpF07LBWmOS1uzrHa9VGdynsEgoeKy0oOQ==", "license": "MIT", "dependencies": { - "ansi-regex": "^6.2.2" + "is-wsl": "^3.1.0", + "powershell-utils": "^0.2.0" }, "engines": { - "node": ">=12" + "node": ">=20" }, "funding": { - "url": "https://github.com/chalk/strip-ansi?sponsor=1" + "url": "https://github.com/sponsors/sindresorhus" } }, - "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==", - "dev": true, - "license": "ISC" - }, "node_modules/xtend": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", @@ -8682,6 +20293,33 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/yocto-spinner": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/yocto-spinner/-/yocto-spinner-1.2.2.tgz", + "integrity": "sha512-DODGl1wJjA/s5pnJFKau9lIYHT81lnhob1i3e1TjxZRxEhWRKl74nTbWE6H5KlkViQQTo/Z29YFdxzTZAMY3ng==", + "license": "MIT", + "dependencies": { + "yoctocolors": "^2.1.1" + }, + "engines": { + "node": ">=18.19" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/yoctocolors": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/yoctocolors/-/yoctocolors-2.2.0.tgz", + "integrity": "sha512-xYqdZFUK/VYazNl/oCDYN+3WloWQwMfZxBoiNt6qNyk+xfOdi598muWE42rNZFp1kNOiqW936q5RhUdnpqElSg==", + "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", @@ -8694,13 +20332,45 @@ } }, "node_modules/zod": { - "version": "4.3.6", - "resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz", - "integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==", + "version": "4.6.6", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.6.tgz", + "integrity": "sha512-4UmzQUF5fxvfcYHlbjBmejU+w+hbDnWFx4aS8kBx7nPBHcO2SqPbpAG8snbdg+Xse4pRefR98hgjFgIMCI/UhA==", "license": "MIT", "funding": { "url": "https://github.com/sponsors/colinhacks" } + }, + "node_modules/zod-to-json-schema": { + "version": "3.25.2", + "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.25.2.tgz", + "integrity": "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==", + "license": "ISC", + "peerDependencies": { + "zod": "^3.25.28 || ^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" + } + }, + "node_modules/zwitch": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz", + "integrity": "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } } } } diff --git a/package.json b/package.json index a07101bc..d0ae0060 100644 --- a/package.json +++ b/package.json @@ -2,15 +2,35 @@ "name": "study-bot", "version": "1.0.0", "private": true, + "description": "Exam planning and retrieval practice from your own course files, with spaced review scheduled back from each exam date.", + "keywords": [ + "study", + "retrieval-practice", + "spaced-repetition", + "flashcards", + "learning-science", + "nextjs" + ], + "homepage": "https://github.com/Ben-K-Jordan/Study-Bot#readme", + "bugs": { + "url": "https://github.com/Ben-K-Jordan/Study-Bot/issues" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/Ben-K-Jordan/Study-Bot.git" + }, + "license": "MIT", "engines": { "node": ">=20.19.0" }, "scripts": { "setup": "node scripts/setup.mjs", + "postinstall": "prisma generate", "dev": "next dev", "build": "next build", "start": "next start", - "lint": "next lint", + "lint": "eslint .", + "typecheck": "tsc --noEmit", "test": "vitest run", "test:unit": "vitest run --exclude 'src/__tests__/integration/**'", "test:integration": "vitest run src/__tests__/integration/", @@ -23,34 +43,54 @@ "db:migrate": "prisma migrate dev", "db:push": "prisma db push", "db:generate": "prisma generate", - "db:seed-research": "tsx scripts/seed-research.ts" + "db:seed-research": "tsx scripts/seed-research.ts", + "db:seed-demo": "tsx scripts/seed-demo.ts", + "screenshots": "tsx scripts/screenshots.ts" }, "dependencies": { - "@prisma/adapter-pg": "^7.6.0", - "@prisma/client": "^7.6.0", + "@fontsource-variable/google-sans-code": "^5.3.2", + "@fontsource-variable/google-sans-flex": "^5.3.2", + "@prisma/adapter-pg": "^7.10.0", + "@prisma/client": "^7.10.0", "bcryptjs": "^3.0.3", - "nanoid": "^3.3.11", - "next": "^14.2.35", - "next-auth": "^4.24.13", + "class-variance-authority": "^0.7.1", + "cmdk": "^1.1.1", + "cn": "^0.4.0", + "lucide-react": "^1.55.0", + "nanoid": "^3.3.20", + "next": "^16.4.0", + "next-auth": "^4.24.15", + "next-themes": "^0.4.6", "nodemailer": "^7.0.13", "pdf-parse": "^1.1.1", "pg": "^8.20.0", - "react": "^18.3.1", - "react-dom": "^18.3.1", - "zod": "^4.3.6" + "radix-ui": "^1.8.0", + "react": "^19.3.0", + "react-dom": "^19.3.0", + "react-markdown": "^10.1.0", + "recharts": "^3.8.0", + "remark-gfm": "^4.0.1", + "shadcn": "^4.21.4", + "sonner": "^2.0.8", + "swr": "^2.5.1", + "tw-animate-css": "^1.4.0", + "zod": "^4.6.6" }, "devDependencies": { - "@eslint/eslintrc": "^3.3.5", - "@playwright/test": "^1.58.2", - "@types/node": "^25.5.0", + "@axe-core/playwright": "^4.14.0", + "@playwright/test": "^1.64.0", + "@tailwindcss/postcss": "^4.3.3", + "@types/node": "^22.20.5", "@types/nodemailer": "^8.0.0", "@types/pg": "^8.20.0", - "@types/react": "^19.2.14", - "@vitejs/plugin-react": "^6.0.1", + "@types/react": "^19.3.0", + "@types/react-dom": "^19.3.0", "dotenv": "^17.4.2", - "eslint": "^8.57.1", - "eslint-config-next": "^14.2.35", - "prisma": "^7.6.0", + "eslint": "^9.39.5", + "eslint-config-next": "^16.4.0", + "postcss": "^8.5.29", + "prisma": "^7.10.0", + "tailwindcss": "^4.3.3", "tsx": "^4.21.0", "typescript": "^6.0.2", "vitest": "^4.1.2" diff --git a/playwright.config.ts b/playwright.config.ts index 1777f68f..d1e2434d 100644 --- a/playwright.config.ts +++ b/playwright.config.ts @@ -1,43 +1,90 @@ import { defineConfig, devices } from "@playwright/test"; -import dotenv from "dotenv"; - -// Load .env for DATABASE_URL (used by pg.Pool in tests). -// Force BASE_URL to port 3000 to match the Playwright webServer. -const savedBaseUrl = process.env.BASE_URL; -dotenv.config(); -process.env.BASE_URL = savedBaseUrl || "http://localhost:3000"; +import { AUTH_FILE, BASE_URL, E2E_PORT, TIME_ZONE, assertE2eDatabase, serverEnv } from "./e2e/support/env"; +/** + * e2e suite. See e2e/README.md for running it locally. + * + * - E2E_PORT (default 3000) picks the app's port; the base URL follows it. + * - CI=true: builds the app and runs `next start`, as CI does. Otherwise + * `next dev`. + * - E2E_REUSE_SERVER=1: use a server already listening on E2E_PORT (one you + * started with the env in e2e/README.md) instead of starting one. + * + * The suite never loads .env. A server it starts gets explicit offline + * settings and the DATABASE_URL you pass, which must name an e2e database. + */ const isCI = !!process.env.CI; +const reuseServer = process.env.E2E_REUSE_SERVER === "1"; export default defineConfig({ testDir: "./e2e", - fullyParallel: false, // Sequential since tests depend on state + // One folder per port, so parallel runs on different ports don't wipe + // each other's traces. + outputDir: `test-results/e2e-${E2E_PORT}`, + // Tests own their data (a unique course, plan or user per test), so they + // can run in any order and in parallel. + fullyParallel: true, forbidOnly: isCI, retries: isCI ? 1 : 0, - workers: 1, + // One Next server serves every worker; more than this slows each test + // down more than it saves. Override with --workers. + workers: isCI ? 2 : 4, reporter: isCI - ? [["github"], ["html", { open: "never" }]] - : "list", + ? [["github"], ["html", { open: "never", outputFolder: `playwright-report/e2e-${E2E_PORT}` }]] + : [["list"]], timeout: 30_000, + expect: { timeout: 10_000 }, use: { - baseURL: process.env.BASE_URL || "http://localhost:3000", + baseURL: BASE_URL, + actionTimeout: 15_000, + navigationTimeout: 30_000, trace: "on-first-retry", - extraHTTPHeaders: { - "X-User-Id": "e2e_test_user", - }, + screenshot: "only-on-failure", + video: "retain-on-failure", + locale: "en-US", + timezoneId: TIME_ZONE, }, projects: [ { - name: "chromium", + // Creates the e2e account and signs in through /auth/signin. + name: "setup", + testMatch: /auth\.setup\.ts/, use: { ...devices["Desktop Chrome"] }, }, + { + name: "chromium", + use: { ...devices["Desktop Chrome"], storageState: AUTH_FILE }, + dependencies: ["setup"], + }, + { + // Phone layout (bottom navigation, floating start button). Runs only + // tests tagged @mobile. + name: "mobile", + use: { ...devices["Pixel 7"], storageState: AUTH_FILE }, + grep: /@mobile/, + dependencies: ["setup"], + }, ], - webServer: { - command: isCI - ? "NO_STANDALONE=1 npm run build && ALLOW_TEST_AUTH=true NEXTAUTH_SECRET=e2e-test-secret npm run start" - : "ALLOW_TEST_AUTH=true npm run dev", - url: "http://localhost:3000", - reuseExistingServer: !isCI, - timeout: isCI ? 120_000 : 30_000, - }, + webServer: reuseServer + ? { + // Started by you; Playwright only waits for it. + command: `echo "Expecting a server on ${BASE_URL}"`, + url: `${BASE_URL}/api/health`, + reuseExistingServer: true, + timeout: 30_000, + } + : { + // Loopback only: the server trusts the X-User-Id test header. + command: isCI + ? `npm run build && npm run start -- -H 127.0.0.1 -p ${E2E_PORT}` + : `npm run dev -- -H 127.0.0.1 -p ${E2E_PORT}`, + url: `${BASE_URL}/api/health`, + // Playwright merges this over its own environment. CI=true comes from + // the runner and is what lets `next start` accept test auth. + env: serverEnv(assertE2eDatabase(process.env.DATABASE_URL)), + reuseExistingServer: false, + timeout: isCI ? 300_000 : 120_000, + stdout: "ignore", + stderr: "pipe", + }, }); diff --git a/postcss.config.mjs b/postcss.config.mjs new file mode 100644 index 00000000..61e36849 --- /dev/null +++ b/postcss.config.mjs @@ -0,0 +1,7 @@ +const config = { + plugins: { + "@tailwindcss/postcss": {}, + }, +}; + +export default config; diff --git a/prisma/indexes.sql b/prisma/indexes.sql deleted file mode 100644 index 9d4602bb..00000000 --- a/prisma/indexes.sql +++ /dev/null @@ -1,14 +0,0 @@ --- Phase 4: Performance indexes (run via prisma db execute or manually) --- These cannot be expressed in Prisma schema. - --- FTS GIN expression index on content_chunks.text -CREATE INDEX CONCURRENTLY IF NOT EXISTS content_chunks_text_fts_idx - ON content_chunks USING GIN (to_tsvector('english', text)); - --- Partial index for active runs (hot-path lookup) -CREATE INDEX CONCURRENTLY IF NOT EXISTS session_runs_active_idx - ON session_runs (user_id, status) WHERE status = 'ACTIVE'; - --- Partial index for unresolved error logs -CREATE INDEX CONCURRENTLY IF NOT EXISTS session_error_logs_unresolved_idx - ON session_error_logs (user_id, created_at DESC) WHERE resolved_at IS NULL; diff --git a/prisma/schema.prisma b/prisma/schema.prisma index fcd6cda9..79a1ac6d 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -565,7 +565,7 @@ model CardReview { model XpEvent { id String @id @default(uuid()) userId String @map("user_id") - action String // FLASHCARD_REVIEW | GUIDE_GENERATED | CHAT_QUESTION | SESSION_COMPLETED | PERFECT_DECK | STREAK_MILESTONE + action String // FLASHCARD_REVIEW | SESSION_COMPLETED | PERFECT_DECK | STREAK_MILESTONE | STREAK_FREEZE_AWARD | STREAK_FREEZE_USED (older rows may hold GUIDE_GENERATED or CHAT_QUESTION) xpAmount Int @map("xp_amount") sourceId String? @map("source_id") createdAt DateTime @default(now()) @map("created_at") diff --git a/public/icon-maskable.svg b/public/icon-maskable.svg new file mode 100644 index 00000000..53ce8505 --- /dev/null +++ b/public/icon-maskable.svg @@ -0,0 +1,8 @@ +<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48"> + <rect width="48" height="48" fill="#0b57d0"/> + <g transform="translate(24 24.4) scale(0.72) translate(-24 -24.4)"> + <path d="M22.8 15.9c-3.2-2-7.4-2.7-11.6-2.1v19.4c4.2-.6 8.4.1 11.6 2.1Z" fill="#fff"/> + <path d="M25.2 15.9c3.2-2 7.4-2.7 11.6-2.1v19.4c-4.2-.6-8.4.1-11.6 2.1Z" fill="#fff"/> + <path d="m28 24.6 2.4 2.4 4.1-4.6" fill="none" stroke="#0b57d0" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"/> + </g> +</svg> diff --git a/public/manifest.json b/public/manifest.json index ac300fd1..563675fb 100644 --- a/public/manifest.json +++ b/public/manifest.json @@ -1,8 +1,15 @@ { + "id": "/", "name": "Study Bot", - "short_name": "StudyBot", + "short_name": "Study Bot", + "description": "Plan for your exams and practice from your own course files.", "start_url": "/", + "scope": "/", "display": "standalone", - "background_color": "#2a3d2a", - "theme_color": "#f0dc4e" + "background_color": "#f8fafd", + "theme_color": "#f8fafd", + "icons": [ + { "src": "/icon.svg", "sizes": "any", "type": "image/svg+xml", "purpose": "any" }, + { "src": "/icon-maskable.svg", "sizes": "any", "type": "image/svg+xml", "purpose": "maskable" } + ] } diff --git a/research-papers/2018 Test Questions JITT PART 1_0.pdf b/research-papers/2018 Test Questions JITT PART 1_0.pdf deleted file mode 100644 index 22c285a1..00000000 Binary files a/research-papers/2018 Test Questions JITT PART 1_0.pdf and /dev/null differ diff --git a/research-papers/2025_Karpicke_Retrieval_Based_Learning_Review.pdf b/research-papers/2025_Karpicke_Retrieval_Based_Learning_Review.pdf deleted file mode 100644 index b5fdd28d..00000000 Binary files a/research-papers/2025_Karpicke_Retrieval_Based_Learning_Review.pdf and /dev/null differ diff --git a/research-papers/99Goll_ImpInt.pdf b/research-papers/99Goll_ImpInt.pdf deleted file mode 100644 index 6e8585a1..00000000 Binary files a/research-papers/99Goll_ImpInt.pdf and /dev/null differ diff --git a/research-papers/Agarwal_etal_2021_EDPR.pdf b/research-papers/Agarwal_etal_2021_EDPR.pdf deleted file mode 100644 index ae8cfae6..00000000 Binary files a/research-papers/Agarwal_etal_2021_EDPR.pdf and /dev/null differ diff --git a/research-papers/Becoming_20a_20Self-Regulated_20Learner_20_20An_20Overview.pdf b/research-papers/Becoming_20a_20Self-Regulated_20Learner_20_20An_20Overview.pdf deleted file mode 100644 index 7cfef937..00000000 Binary files a/research-papers/Becoming_20a_20Self-Regulated_20Learner_20_20An_20Overview.pdf and /dev/null differ diff --git a/research-papers/Brunmair_Richter_in_press__2019_META-ANALYSIS_OF_INTERLEAVED_LEARNING.pdf b/research-papers/Brunmair_Richter_in_press__2019_META-ANALYSIS_OF_INTERLEAVED_LEARNING.pdf deleted file mode 100644 index ce8e2a08..00000000 Binary files a/research-papers/Brunmair_Richter_in_press__2019_META-ANALYSIS_OF_INTERLEAVED_LEARNING.pdf and /dev/null differ diff --git a/research-papers/EBjork_RBjork_2011.pdf b/research-papers/EBjork_RBjork_2011.pdf deleted file mode 100644 index 2deecd9f..00000000 Binary files a/research-papers/EBjork_RBjork_2011.pdf and /dev/null differ diff --git a/research-papers/EJ1016653.pdf b/research-papers/EJ1016653.pdf deleted file mode 100644 index 145888e1..00000000 Binary files a/research-papers/EJ1016653.pdf and /dev/null differ diff --git a/research-papers/Handout-Module6.pdf b/research-papers/Handout-Module6.pdf deleted file mode 100644 index d31bf36a..00000000 Binary files a/research-papers/Handout-Module6.pdf and /dev/null differ diff --git a/research-papers/Karpicke & Blunt (2011) - Pre-Data Collection Replication Report.pdf b/research-papers/Karpicke & Blunt (2011) - Pre-Data Collection Replication Report.pdf deleted file mode 100644 index e2d99e09..00000000 Binary files a/research-papers/Karpicke & Blunt (2011) - Pre-Data Collection Replication Report.pdf and /dev/null differ diff --git a/research-papers/Pan_Rickard_2018.pdf b/research-papers/Pan_Rickard_2018.pdf deleted file mode 100644 index 493f2a6b..00000000 Binary files a/research-papers/Pan_Rickard_2018.pdf and /dev/null differ diff --git a/research-papers/Procrastination_2.pdf b/research-papers/Procrastination_2.pdf deleted file mode 100644 index f9aea159..00000000 Binary files a/research-papers/Procrastination_2.pdf and /dev/null differ diff --git a/research-papers/adesope-et-al-2017-rethinking-the-use-of-tests-a-meta-analysis-of-practice-testing.pdf b/research-papers/adesope-et-al-2017-rethinking-the-use-of-tests-a-meta-analysis-of-practice-testing.pdf deleted file mode 100644 index 132b76a3..00000000 Binary files a/research-papers/adesope-et-al-2017-rethinking-the-use-of-tests-a-meta-analysis-of-practice-testing.pdf and /dev/null differ diff --git a/research-papers/betteritems.pdf b/research-papers/betteritems.pdf deleted file mode 100644 index 599d2173..00000000 Binary files a/research-papers/betteritems.pdf and /dev/null differ diff --git a/research-papers/dunloskiimprovingstudentlearning.pdf b/research-papers/dunloskiimprovingstudentlearning.pdf deleted file mode 100644 index a941f7d3..00000000 Binary files a/research-papers/dunloskiimprovingstudentlearning.pdf and /dev/null differ diff --git a/research-papers/gollwitzer_brandstatter_1997_-_implementation_intentions_effective_goal_pursuit.pdf b/research-papers/gollwitzer_brandstatter_1997_-_implementation_intentions_effective_goal_pursuit.pdf deleted file mode 100644 index fab50efd..00000000 Binary files a/research-papers/gollwitzer_brandstatter_1997_-_implementation_intentions_effective_goal_pursuit.pdf and /dev/null differ diff --git a/research-papers/roediger-karpicke-2006-test-enhanced-learning.pdf b/research-papers/roediger-karpicke-2006-test-enhanced-learning.pdf deleted file mode 100644 index fb37c61c..00000000 Binary files a/research-papers/roediger-karpicke-2006-test-enhanced-learning.pdf and /dev/null differ diff --git a/research-papers/the-shuffling-of-mathematics-problems-improves-learning-25hfx6b6ra.pdf b/research-papers/the-shuffling-of-mathematics-problems-improves-learning-25hfx6b6ra.pdf deleted file mode 100644 index 34801d42..00000000 Binary files a/research-papers/the-shuffling-of-mathematics-problems-improves-learning-25hfx6b6ra.pdf and /dev/null differ diff --git a/scripts/screenshots.ts b/scripts/screenshots.ts new file mode 100644 index 00000000..23d2f67e --- /dev/null +++ b/scripts/screenshots.ts @@ -0,0 +1,636 @@ +#!/usr/bin/env tsx +/** + * Screenshot harness for reviewing the app with realistic data. + * + * Signs in as the demo user through the real sign-in page, then captures + * every route at each viewport and color scheme with animations disabled. + * It does not start the app: run `npm run dev` (or `npm start`) against the + * demo database first, seeded with scripts/seed-demo.ts. + * + * Usage: + * npx tsx scripts/screenshots.ts --base http://localhost:3000 --out <dir> + * [--routes /,/plan,/learn] signed-in routes (default: every app page) + * [--signed-out-routes /auth/signin] captured without a session ("" to skip) + * [--themes light,dark] [--viewports desktop,mobile] [--full-page] + * [--email demo@studybot.local] [--password study-bot-demo] + * [--test-auth <userId>] fall back to the X-User-Id header if sign-in + * fails (server needs ALLOW_TEST_AUTH=true and a + * localhost NEXTAUTH_URL; start it with -H 127.0.0.1) + * [--no-signin] skip the sign-in page, use --test-auth only + * [--session] [--session-id <id>] also capture today's session: preflight, + * then the first question (this starts a run; + * reseed afterwards to reset the demo) + * [--theme-key <key>] also write the theme to localStorage[key] + * [--dpr <n>] [--settle <ms>] [--timeout <ms>] [--headed] + * + * Files are written as <out>/<route-slug>-<viewport>-<theme>.png, with a + * manifest.json listing each capture, its HTTP status and console errors. + * + * Exit codes: 0 all captured, 1 some captures failed, 2 sign-in failed, + * 64 bad arguments. + */ +import { mkdir, writeFile } from "fs/promises"; +import { join, resolve } from "path"; +import { chromium, type Browser, type BrowserContext, type Locator, type Page } from "@playwright/test"; + +type Theme = "light" | "dark"; +type StorageState = Awaited<ReturnType<BrowserContext["storageState"]>>; + +interface ViewportSpec { + width: number; + height: number; + deviceScaleFactor: number; + isMobile: boolean; + hasTouch: boolean; +} + +const VIEWPORTS: Record<string, ViewportSpec> = { + desktop: { width: 1440, height: 900, deviceScaleFactor: 1, isMobile: false, hasTouch: false }, + mobile: { width: 390, height: 844, deviceScaleFactor: 2, isMobile: true, hasTouch: true }, +}; + +const DEFAULT_ROUTES = ["/", "/plan", "/learn", "/flashcards", "/guides", "/chat", "/achievements", "/settings"]; +const DEFAULT_SIGNED_OUT_ROUTES = ["/auth/signin", "/auth/signup", "/auth/forgot-password"]; +const DEMO_TIMEZONE = "America/New_York"; + +const NO_MOTION_CSS = [ + "*, *::before, *::after {", + " animation-duration: 0s !important;", + " animation-delay: 0s !important;", + " animation-iteration-count: 1 !important;", + " transition-duration: 0s !important;", + " transition-delay: 0s !important;", + " scroll-behavior: auto !important;", + " caret-color: transparent !important;", + "}", +].join("\n"); + +// --------------------------------------------------------------------------- +// Arguments +// --------------------------------------------------------------------------- + +interface Options { + base: string; + out: string; + routes: string[]; + signedOutRoutes: string[]; + themes: Theme[]; + viewports: string[]; + fullPage: boolean; + email: string; + password: string; + testAuth: string | null; + noSignin: boolean; + session: boolean; + sessionId: string | null; + themeKey: string | null; + dpr: number | null; + settle: number; + timeout: number; + headed: boolean; +} + +function usageError(message: string): never { + console.error(`screenshots: ${message}\nRun with --help for usage.`); + process.exit(64); +} + +function splitList(value: string): string[] { + return value + .split(",") + .map((s) => s.trim()) + .filter(Boolean); +} + +/** + * Git Bash on Windows rewrites arguments that start with "/" into Windows + * paths ("/plan" arrives as "C:/Program Files/Git/plan"). Undo that, and + * accept routes written without the leading slash. + */ +function normalizeRoute(raw: string): string { + const msys = raw.match(/^[A-Za-z]:[\\/](?:.*[\\/])?Git([\\/].*)?$/i); + const route = msys ? (msys[1] ?? "/").replace(/\\/g, "/") : raw; + return route.startsWith("/") ? route : `/${route}`; +} + +function parseArgs(argv: string[]): Options { + const flags = new Set(["--full-page", "--no-signin", "--session", "--headed", "--help"]); + const values = new Map<string, string>(); + const seen = new Set<string>(); + for (let i = 0; i < argv.length; i++) { + const arg = argv[i]; + if (!arg.startsWith("--")) usageError(`unexpected argument "${arg}"`); + const eq = arg.indexOf("="); + const name = eq > 0 ? arg.slice(0, eq) : arg; + if (flags.has(name)) { + seen.add(name); + continue; + } + const value = eq > 0 ? arg.slice(eq + 1) : argv[++i]; + if (value === undefined) usageError(`${name} needs a value`); + values.set(name, value); + } + if (seen.has("--help")) { + console.log( + "Usage: npx tsx scripts/screenshots.ts --base http://localhost:3000 --out <dir> " + + "[--routes /,/plan] [--signed-out-routes /auth/signin] [--themes light,dark] " + + "[--viewports desktop,mobile] [--full-page] [--email <email>] [--password <password>] " + + "[--test-auth <userId>] [--no-signin] [--session] [--session-id <id>] [--theme-key <key>] " + + "[--dpr <n>] [--settle <ms>] [--timeout <ms>] [--headed]", + ); + process.exit(0); + } + + const known = new Set([ + "--base", "--out", "--routes", "--signed-out-routes", "--themes", "--viewports", "--email", + "--password", "--test-auth", "--session-id", "--theme-key", "--dpr", "--settle", "--timeout", + ]); + for (const name of values.keys()) if (!known.has(name)) usageError(`unknown option ${name}`); + + const base = (values.get("--base") ?? "http://localhost:3000").replace(/\/+$/, ""); + try { + new URL(base); + } catch { + usageError(`--base "${base}" is not a URL`); + } + + const routes = values.has("--routes") ? splitList(values.get("--routes")!).map(normalizeRoute) : DEFAULT_ROUTES; + const signedOutRoutes = values.has("--signed-out-routes") + ? splitList(values.get("--signed-out-routes")!).map(normalizeRoute) + : DEFAULT_SIGNED_OUT_ROUTES; + + const themes = splitList(values.get("--themes") ?? "light,dark"); + for (const t of themes) if (t !== "light" && t !== "dark") usageError(`unknown theme "${t}" (use light, dark)`); + + const viewports = splitList(values.get("--viewports") ?? "desktop,mobile"); + for (const v of viewports) { + if (!VIEWPORTS[v]) usageError(`unknown viewport "${v}" (use ${Object.keys(VIEWPORTS).join(", ")})`); + } + + const num = (name: string, fallback: number) => { + const raw = values.get(name); + if (raw === undefined) return fallback; + const n = Number(raw); + if (!Number.isFinite(n) || n < 0) usageError(`${name} must be a non-negative number`); + return n; + }; + + const testAuth = values.get("--test-auth") ?? null; + const noSignin = seen.has("--no-signin"); + if (noSignin && !testAuth) usageError("--no-signin needs --test-auth <userId>"); + + return { + base, + out: resolve(values.get("--out") ?? join("test-results", "screenshots")), + routes, + signedOutRoutes, + themes: themes as Theme[], + viewports, + fullPage: seen.has("--full-page"), + email: values.get("--email") ?? "demo@studybot.local", + password: values.get("--password") ?? "study-bot-demo", + testAuth, + noSignin, + session: seen.has("--session") || values.has("--session-id"), + sessionId: values.get("--session-id") ?? null, + themeKey: values.get("--theme-key") ?? null, + dpr: values.has("--dpr") ? num("--dpr", 1) || 1 : null, + settle: num("--settle", 400), + timeout: num("--timeout", 30_000), + headed: seen.has("--headed"), + }; +} + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +function routeSlug(route: string): string { + if (route === "/" || route === "") return "home"; + const slug = route + .replace(/^\/+|\/+$/g, "") + .replace(/[^a-zA-Z0-9]+/g, "-") + .replace(/^-+|-+$/g, "") + .toLowerCase(); + return slug || "home"; +} + +async function firstVisible(candidates: Locator[], timeoutMs: number): Promise<Locator | null> { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + for (const c of candidates) { + const first = c.first(); + if ((await first.count()) > 0 && (await first.isVisible().catch(() => false))) return first; + } + await new Promise((r) => setTimeout(r, 200)); + } + return null; +} + +interface AuthMode { + kind: "session" | "header"; + storageState?: StorageState; + userId?: string; +} + +interface CaptureRecord { + name: string; + route: string; + viewport: string; + theme: Theme; + file: string | null; + status: number | null; + finalUrl: string | null; + consoleErrors: string[]; + pageErrors: string[]; + warnings: string[]; + error: string | null; + ms: number; +} + +class Harness { + readonly records: CaptureRecord[] = []; + + constructor( + private readonly browser: Browser, + private readonly opts: Options, + ) {} + + async newContext(viewport: string, theme: Theme, auth: AuthMode | null): Promise<BrowserContext> { + const vp = VIEWPORTS[viewport]; + const context = await this.browser.newContext({ + viewport: { width: vp.width, height: vp.height }, + deviceScaleFactor: this.opts.dpr ?? vp.deviceScaleFactor, + isMobile: vp.isMobile, + hasTouch: vp.hasTouch, + colorScheme: theme, + reducedMotion: "reduce", + locale: "en-US", + timezoneId: DEMO_TIMEZONE, + storageState: auth?.kind === "session" ? auth.storageState : undefined, + extraHTTPHeaders: auth?.kind === "header" && auth.userId ? { "X-User-Id": auth.userId } : undefined, + }); + // Passed as source text, not a function: tsx compiles named functions with + // a __name() helper that doesn't exist in the page. + await context.addInitScript({ + content: `(() => { + const css = ${JSON.stringify(NO_MOTION_CSS)}; + const themeKey = ${JSON.stringify(this.opts.themeKey)}; + if (themeKey) { + try { localStorage.setItem(themeKey, ${JSON.stringify(theme)}); } catch (e) {} + } + const add = () => { + if (document.getElementById("__screenshot_no_motion")) return; + const style = document.createElement("style"); + style.id = "__screenshot_no_motion"; + style.textContent = css; + (document.head || document.documentElement).appendChild(style); + }; + if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", add); + else add(); + })();`, + }); + return context; + } + + /** Navigate, let the page settle, and save one screenshot. */ + async capture( + context: BrowserContext, + name: string, + route: string, + viewport: string, + theme: Theme, + options: { expectSignedIn: boolean; prepare?: (page: Page) => Promise<string[]> }, + ): Promise<CaptureRecord> { + const started = Date.now(); + const record: CaptureRecord = { + name, + route, + viewport, + theme, + file: null, + status: null, + finalUrl: null, + consoleErrors: [], + pageErrors: [], + warnings: [], + error: null, + ms: 0, + }; + const page = await context.newPage(); + page.on("console", (msg) => { + if (msg.type() === "error") record.consoleErrors.push(msg.text().slice(0, 500)); + }); + page.on("pageerror", (err) => record.pageErrors.push(String(err).slice(0, 500))); + try { + await page.emulateMedia({ colorScheme: theme, reducedMotion: "reduce" }); + const response = await page.goto(this.opts.base + route, { waitUntil: "load", timeout: this.opts.timeout }); + record.status = response?.status() ?? null; + await page + .waitForLoadState("networkidle", { timeout: this.opts.timeout }) + .catch(() => record.warnings.push("network did not go idle")); + record.finalUrl = page.url(); + if (options.expectSignedIn && new URL(page.url()).pathname.startsWith("/auth/")) { + throw new Error(`redirected to ${new URL(page.url()).pathname}: the session was not accepted`); + } + if (options.prepare) record.warnings.push(...(await options.prepare(page))); + // Source text again (see newContext): wait for web fonts, and confirm + // the no-motion stylesheet made it into the page. + const motionOff = await page.evaluate( + "document.fonts.ready.then(() => Boolean(document.getElementById('__screenshot_no_motion')))", + ); + if (!motionOff) record.warnings.push("animation-disabling stylesheet missing"); + if (this.opts.settle > 0) await page.waitForTimeout(this.opts.settle); + const file = join(this.opts.out, `${name}-${viewport}-${theme}.png`); + await page.screenshot({ + path: file, + fullPage: this.opts.fullPage, + animations: "disabled", + caret: "hide", + timeout: this.opts.timeout, + }); + record.file = file; + } catch (err) { + record.error = err instanceof Error ? err.message.split("\n")[0] : String(err); + } finally { + record.ms = Date.now() - started; + await page.close().catch(() => {}); + } + this.records.push(record); + const status = record.error + ? `FAILED: ${record.error}` + : `${record.status ?? "-"}${record.consoleErrors.length ? `, ${record.consoleErrors.length} console errors` : ""}${ + record.warnings.length ? `, ${record.warnings.join("; ")}` : "" + }`; + console.log(` ${name}-${viewport}-${theme}.png ${status}`); + return record; + } +} + +// --------------------------------------------------------------------------- +// Sign-in +// --------------------------------------------------------------------------- + +async function signIn(browser: Browser, opts: Options): Promise<{ state: StorageState } | { reason: string }> { + const context = await browser.newContext({ viewport: { width: 1280, height: 800 }, locale: "en-US" }); + const page = await context.newPage(); + try { + const response = await page.goto(`${opts.base}/auth/signin`, { waitUntil: "load", timeout: opts.timeout }); + if (!response || response.status() >= 400) { + return { reason: `/auth/signin returned HTTP ${response?.status() ?? "no response"}` }; + } + await page.waitForLoadState("networkidle", { timeout: opts.timeout }).catch(() => {}); + + const emailField = await firstVisible( + [page.getByLabel(/^email( address)?$/i), page.locator('input[type="email"]'), page.locator('input[name="email"]')], + opts.timeout / 2, + ); + const passwordField = await firstVisible( + [page.getByLabel(/^password$/i), page.locator('input[type="password"]')], + opts.timeout / 4, + ); + if (!emailField || !passwordField) { + return { reason: "couldn't find the email and password fields on /auth/signin" }; + } + await emailField.fill(opts.email); + await passwordField.fill(opts.password); + + const submit = page.getByRole("button", { name: /^sign in$/i }); + if ((await submit.count()) > 0) await submit.first().click(); + else await passwordField.press("Enter"); + + try { + await page.waitForURL((url) => !url.pathname.startsWith("/auth/"), { timeout: opts.timeout }); + } catch { + const alert = await page + .getByRole("alert") + .first() + .textContent({ timeout: 1000 }) + .catch(() => null); + return { + reason: `still on ${new URL(page.url()).pathname} after submitting${alert?.trim() ? ` ("${alert.trim()}")` : ""}`, + }; + } + + const session = await context.request + .get(`${opts.base}/api/auth/session`) + .then((r) => r.json() as Promise<{ user?: { email?: string } }>) + .catch(() => null); + if (!session?.user) return { reason: "signed in, but /api/auth/session has no user" }; + return { state: await context.storageState() }; + } catch (err) { + return { reason: err instanceof Error ? err.message.split("\n")[0] : String(err) }; + } finally { + await context.close(); + } +} + +async function checkHeaderAuth(browser: Browser, opts: Options, userId: string): Promise<string | null> { + const context = await browser.newContext({ extraHTTPHeaders: { "X-User-Id": userId } }); + try { + const res = await context.request.get(`${opts.base}/api/stats/game`); + if (res.ok()) return null; + return `GET /api/stats/game returned ${res.status()} with X-User-Id (the server needs ALLOW_TEST_AUTH=true)`; + } catch (err) { + return err instanceof Error ? err.message.split("\n")[0] : String(err); + } finally { + await context.close(); + } +} + +// --------------------------------------------------------------------------- +// Session screens +// --------------------------------------------------------------------------- + +interface PlanListItem { + status: string; + start_time: string; + session_id: string; + course_name: string; +} + +async function findTodaySession(context: BrowserContext, opts: Options): Promise<string | null> { + if (opts.sessionId) return opts.sessionId; + const res = await context.request.get(`${opts.base}/api/plans`); + if (!res.ok()) return null; + const body = (await res.json()) as { plans?: { items: PlanListItem[] }[] }; + const dayKey = (d: Date) => + new Intl.DateTimeFormat("en-CA", { timeZone: DEMO_TIMEZONE, year: "numeric", month: "2-digit", day: "2-digit" }).format(d); + const today = dayKey(new Date()); + const items = (body.plans ?? []) + .flatMap((p) => p.items) + .filter((i) => i.status === "SCHEDULED") + .sort((a, b) => Date.parse(a.start_time) - Date.parse(b.start_time)); + const todays = items.find((i) => dayKey(new Date(i.start_time)) === today); + return (todays ?? items.find((i) => Date.parse(i.start_time) > Date.now()) ?? null)?.session_id ?? null; +} + +/** Start or resume the session and wait until a question is on screen. */ +async function openFirstQuestion(page: Page, timeout: number): Promise<string[]> { + const warnings: string[] = []; + const questionCandidates = () => [ + page.getByRole("textbox"), + page.getByRole("radio"), + page.getByText(/question \d+ of \d+|prompt \d+ \/ \d+/i), + ]; + // A resumed run may already show the question; otherwise start or resume it. + if (!(await firstVisible(questionCandidates(), 1000))) { + const start = page.getByRole("button", { name: /start session|resume session/i }); + if ((await start.count()) > 0) await start.first().click(); + else warnings.push("no Start or Resume button found"); + if (!(await firstVisible(questionCandidates(), timeout))) warnings.push("no question appeared"); + } + await page.waitForLoadState("networkidle", { timeout }).catch(() => {}); + return warnings; +} + +// --------------------------------------------------------------------------- +// Main +// --------------------------------------------------------------------------- + +async function main() { + const opts = parseArgs(process.argv.slice(2)); + await mkdir(opts.out, { recursive: true }); + + const browser = await chromium.launch({ headless: !opts.headed }); + const harness = new Harness(browser, opts); + let exitCode = 0; + let auth: AuthMode | null = null; + + try { + // Reachability first, so a missing server fails with a clear message. + const probe = await browser.newContext(); + const health = await probe.request.get(`${opts.base}/api/health`, { timeout: opts.timeout }).catch((err: unknown) => err); + await probe.close(); + if (health instanceof Error) { + console.error(`screenshots: can't reach ${opts.base} (${health.message.split("\n")[0]}). Is the app running?`); + process.exitCode = 2; + return; + } + + console.log(`Capturing ${opts.base} into ${opts.out}`); + + // Signed-out pages first: they also show what the sign-in step is about to use. + if (opts.signedOutRoutes.length > 0) { + console.log("Signed out"); + for (const viewport of opts.viewports) { + for (const theme of opts.themes) { + const context = await harness.newContext(viewport, theme, null); + for (const route of opts.signedOutRoutes) { + await harness.capture(context, routeSlug(route), route, viewport, theme, { expectSignedIn: false }); + } + await context.close(); + } + } + } + + // Sign in through the real page, falling back to the test-auth header. + if (!opts.noSignin) { + const result = await signIn(browser, opts); + if ("state" in result) { + auth = { kind: "session", storageState: result.state }; + console.log(`Signed in as ${opts.email}`); + } else if (opts.testAuth) { + console.warn(`Sign-in failed (${result.reason}); falling back to the X-User-Id header.`); + } else { + console.error( + `screenshots: sign-in as ${opts.email} failed: ${result.reason}.\n` + + "Check that the app is running against the seeded demo database " + + "(scripts/seed-demo.ts), or pass --test-auth <userId> with ALLOW_TEST_AUTH=true on the server.", + ); + process.exitCode = 2; + return; + } + } + if (!auth && opts.testAuth) { + const problem = await checkHeaderAuth(browser, opts, opts.testAuth); + if (problem) { + console.error(`screenshots: test auth for ${opts.testAuth} failed: ${problem}.`); + process.exitCode = 2; + return; + } + auth = { kind: "header", userId: opts.testAuth }; + console.log(`Using X-User-Id ${opts.testAuth}`); + } + if (!auth) { + process.exitCode = 2; + return; + } + + console.log("Signed-in pages"); + for (const viewport of opts.viewports) { + for (const theme of opts.themes) { + const context = await harness.newContext(viewport, theme, auth); + for (const route of opts.routes) { + await harness.capture(context, routeSlug(route), route, viewport, theme, { expectSignedIn: true }); + } + await context.close(); + } + } + + if (opts.session) { + const lookup = await harness.newContext(opts.viewports[0], opts.themes[0], auth); + const sessionId = await findTodaySession(lookup, opts); + await lookup.close(); + if (!sessionId) { + console.error(" session: no scheduled session found in /api/plans (pass --session-id)"); + exitCode = 1; + } else { + console.log(`Session /s/${sessionId}`); + const route = `/s/${sessionId}`; + // Every preflight first: starting the session below changes what it shows. + for (const viewport of opts.viewports) { + for (const theme of opts.themes) { + const context = await harness.newContext(viewport, theme, auth); + await harness.capture(context, "session-preflight", route, viewport, theme, { expectSignedIn: true }); + await context.close(); + } + } + for (const viewport of opts.viewports) { + for (const theme of opts.themes) { + const context = await harness.newContext(viewport, theme, auth); + await harness.capture(context, "session-question", route, viewport, theme, { + expectSignedIn: true, + prepare: (page) => openFirstQuestion(page, opts.timeout), + }); + await context.close(); + } + } + console.log(" note: this started a run for that session; rerun scripts/seed-demo.ts to reset the demo."); + } + } + } finally { + await browser.close(); + const failed = harness.records.filter((r) => r.error); + await writeFile( + join(opts.out, "manifest.json"), + JSON.stringify( + { + base: opts.base, + generatedAt: new Date().toISOString(), + auth: auth?.kind ?? "none", + fullPage: opts.fullPage, + captures: harness.records.map((r) => ({ + ...r, + file: r.file ? r.file.slice(opts.out.length + 1) : null, + })), + }, + null, + 2, + ), + ); + const withErrors = harness.records.filter((r) => r.consoleErrors.length > 0 || r.pageErrors.length > 0); + console.log( + `${harness.records.length - failed.length} of ${harness.records.length} screenshots saved` + + (withErrors.length ? `, ${withErrors.length} with console or page errors` : "") + + ` (manifest.json in ${opts.out})`, + ); + if (failed.length > 0) exitCode = 1; + if (!process.exitCode) process.exitCode = exitCode; + } +} + +main().catch((err) => { + console.error(err); + process.exit(1); +}); diff --git a/scripts/seed-demo-content.ts b/scripts/seed-demo-content.ts new file mode 100644 index 00000000..5c4ca763 --- /dev/null +++ b/scripts/seed-demo-content.ts @@ -0,0 +1,1667 @@ +/** + * Content for the demo account created by scripts/seed-demo.ts: lecture + * notes, question banks, flashcard decks, study guides and a chat history. + * + * Everything here is original writing for demo purposes. Dates are day + * offsets from "today" in the demo user's timezone plus a local wall-clock + * time, so the seed can place them relative to the day it runs. + */ + +export type ErrorType = "MISCONCEPTION" | "PROCEDURE" | "CARELESS" | "MEMORY" | "UNKNOWN"; + +/** [day offset from today, "HH:MM" local time] */ +export type When = [number, string]; + +export interface DemoObjective { + /** Short code used in this file to refer to the objective. */ + code: string; + /** Title as the student typed it; the app derives the objective id from it. */ + title: string; + /** A solid answer from memory (pretest and review questions). */ + recall: string; + /** A shaky answer from memory. */ + weak: string; +} + +export interface DemoQuestion { + key: string; + obj: string; + text: string; + difficulty: number; + /** Multiple choice: the app grades the choice and writes the error log itself. */ + mcq?: { choices: string[]; correct: number; trap: number; rationales: string[] }; + model: string; + points: string[]; + good: string; + bad: string; + partial?: string; + errorType: ErrorType; + /** The correction rule the student writes after a miss. */ + rule: string; + /** AI-written explanation stored with the feedback for a miss. */ + explain: string; +} + +export interface DemoDoc { + file: string; + title: string; + uploaded: When; + summary: string; + questions: string[]; + body: string; +} + +export interface DemoCourse { + name: string; + exam: string; + examOffset: number; + objectives: DemoObjective[]; + docs: DemoDoc[]; + questions: DemoQuestion[]; +} + +// --------------------------------------------------------------------------- +// INFO 1300: Web Design +// --------------------------------------------------------------------------- + +const INFO1300_DOCS: DemoDoc[] = [ + { + file: "info1300-lecture-14-specificity-and-box-model.md", + title: "Lecture 14: Specificity, the cascade, and the box model", + uploaded: [-13, "21:40"], + summary: + "How the cascade resolves conflicting rules, how to score selector specificity column by column, and how padding, border, margin and box-sizing determine an element's rendered size.", + questions: [ + "Why does one ID selector beat any number of class selectors?", + "When does source order decide which rule wins?", + "How wide is a 300px box with 20px padding under content-box and border-box?", + ], + body: `# Lecture 14: Specificity, the cascade, and the box model + +## How the CSS cascade picks a winner + +When two CSS rules set the same property on the same element, the browser resolves the conflict in a fixed order: origin and importance first, then specificity, then source order. A rule later in the stylesheet only wins when the competing rules tie on everything before it. + +## Calculating specificity + +CSS specificity is a three-part score written as (IDs, classes, types). Count each ID selector in the first column; each class, attribute selector and pseudo-class in the second; and each type selector and pseudo-element in the third. Compare the columns left to right. The first column that differs decides the winner, so #nav a (1,0,1) beats .menu .item .link (0,3,0) even though the second selector is longer. There is no carrying between columns: eleven classes never add up to an ID. + +The universal selector and the combinators (child, sibling and descendant) add nothing. Inline style attributes beat any selector in the stylesheet, and !important beats both, which is why it is reserved for utility overrides rather than everyday styling. + +:is() and :not() take the specificity of their most specific argument. :where() always contributes zero, which makes it useful for low-priority defaults that are easy to override. + +## Worked example + +Given p.intro { color: gray } and #story p { color: black }, a paragraph with class intro inside #story renders black. The first selector scores (0,1,1); the second scores (1,0,1). The ID column decides before the class column is ever compared. + +## The box model + +Every element is a rectangular box made of content, padding, border and margin. With the default box-sizing: content-box, width sets only the content area, so a 300px box with 20px padding and a 2px border takes up 344px horizontally. With box-sizing: border-box, width includes padding and border, and the content area shrinks to fit. Most projects set border-box on every element so that declared widths match what appears on screen. + +Vertical margins between block elements collapse: two stacked paragraphs with 24px and 16px margins end up 24px apart, not 40px. Padding and borders never collapse, and margins do not collapse inside flex or grid containers. +`, + }, + { + file: "info1300-lecture-16-flexbox-and-grid.md", + title: "Lecture 16: Flexbox and grid layout", + uploaded: [-13, "21:42"], + summary: + "Flexbox main and cross axes, alignment with justify-content and align-items, the flex shorthand, and two-dimensional page layouts with named grid template areas.", + questions: [ + "Which property centers flex items along the cross axis?", + "What does flex: 1 expand to?", + "Why does an L-shaped grid area invalidate grid-template-areas?", + ], + body: `# Lecture 16: Flexbox and grid layout + +## Flexbox axes + +A flex container lays out its children along a main axis set by flex-direction (row by default) and a cross axis perpendicular to it. justify-content distributes space along the main axis: flex-start, center, space-between, space-around and space-evenly. align-items positions items on the cross axis: stretch (the default), flex-start, center and baseline. When flex-direction is column, the axes swap, so justify-content centers vertically and align-items centers horizontally. + +To center one element both ways, make the parent a flex container and set justify-content: center and align-items: center. align-self overrides align-items for a single item. + +## Growing and shrinking + +flex: 1 is shorthand for flex-grow: 1, flex-shrink: 1 and flex-basis: 0%. Items with flex: 1 share free space equally regardless of their content. gap adds space between items without adding it to the outer edges. + +## Grid template areas + +CSS grid lays out items in two dimensions. grid-template-areas lets you name regions with strings, one string per row: + +.page { + display: grid; + grid-template-columns: 220px 1fr; + grid-template-areas: + "header header" + "sidebar main" + "footer footer"; +} + +Each child then claims a region with grid-area: header, grid-area: main, and so on. Every string must have the same number of cells, and each named area must form a rectangle. An L-shaped area makes the whole declaration invalid, and the browser ignores it. A period (.) marks an empty cell. + +Areas make responsive layouts readable. Inside a media query you can redefine grid-template-areas, for example stacking "header" "main" "sidebar" "footer" in a single column, without touching the HTML order. + +## Flexbox or grid? + +Use flexbox when content flows in one direction and items should size themselves, like a nav bar or a row of buttons. Use grid when you are placing items into rows and columns at the same time, like a page layout or a photo gallery. +`, + }, + { + file: "info1300-lecture-18-responsive-images.md", + title: "Lecture 18: Responsive images and media queries", + uploaded: [-5, "22:15"], + summary: + "Serving the right image file with srcset and sizes, density descriptors for fixed-size images, art direction with the picture element, and mobile-first media queries.", + questions: [ + "What does the w descriptor in srcset describe?", + "What happens if an img with w descriptors has no sizes attribute?", + "When do you need picture instead of srcset alone?", + ], + body: `# Lecture 18: Responsive images and media queries + +## Why srcset + +A single 2400px hero image wastes bandwidth on a phone, and a 600px image looks blurry on a large high-density screen. The srcset attribute lists candidate files and lets the browser choose. + +## Width descriptors and sizes + +<img src="hero-800.jpg" + srcset="hero-400.jpg 400w, hero-800.jpg 800w, hero-1600.jpg 1600w" + sizes="(max-width: 600px) 100vw, 50vw" + alt="Students on the Arts Quad"> + +The w descriptor states each file's intrinsic width in pixels. The sizes attribute tells the browser how wide the image will be displayed, because the browser picks an image before CSS has loaded. In the example, the image fills the viewport on screens up to 600px and half the viewport above that. The browser multiplies the slot width by the device pixel ratio and picks the smallest candidate that covers it. If you use w descriptors and leave out sizes, the browser assumes 100vw and often downloads a much larger file than needed. + +## Density descriptors + +For images shown at a fixed size, like a 64px avatar, density descriptors are simpler: srcset="avatar-64.png 1x, avatar-128.png 2x". Do not mix x and w descriptors in the same srcset. + +## Art direction with picture + +srcset only switches between resolutions of the same image. When you need a different crop on small screens, use picture with source elements that carry a media attribute. The browser uses the first source whose media query matches, and the img inside is the fallback and carries the alt text. + +## Media queries + +A media query applies rules only when a condition is true: + +@media (min-width: 768px) { + .gallery { grid-template-columns: repeat(3, 1fr); } +} + +Mobile-first stylesheets write the base styles for small screens and add min-width queries as space grows. Choose breakpoints where the content breaks, not at the widths of particular phones. The viewport meta tag, <meta name="viewport" content="width=device-width, initial-scale=1">, is required, or mobile browsers render the page at a desktop width and scale it down. +`, + }, +]; + +const INFO1300_OBJECTIVES: DemoObjective[] = [ + { + code: "S", + title: "CSS specificity", + recall: + "Specificity is scored as IDs, classes, types. You compare the columns left to right and the first difference wins. Source order only matters on a tie.", + weak: "More specific selectors win. I think longer selectors count as more specific? Not totally sure how IDs compare.", + }, + { + code: "B", + title: "Box model", + recall: + "Content, padding, border, margin from the inside out. With content-box the width is just the content; border-box includes padding and border.", + weak: "Every element is a box with padding and margin around it. Not sure what box-sizing changes.", + }, + { + code: "F", + title: "Flexbox alignment", + recall: + "justify-content works on the main axis and align-items on the cross axis. With flex-direction column they swap directions.", + weak: "justify-content centers horizontally and align-items centers vertically, I think always.", + }, + { + code: "G", + title: "Grid template areas", + recall: + "You name regions on the container with grid-template-areas strings, one per row, and children claim them with grid-area. Areas have to be rectangles.", + weak: "grid-template-areas lets you name parts of the grid. I don't remember the exact syntax.", + }, + { + code: "R", + title: "Responsive images and srcset", + recall: + "srcset lists files with their real widths (w) and sizes says how wide the slot will be, so the browser can pick the smallest file that covers it.", + weak: "srcset gives the browser different image sizes for different screens. sizes sets how big the image shows up?", + }, + { + code: "M", + title: "Media queries", + recall: + "Media queries apply CSS only when a condition is true. Mobile first means base styles for small screens, then min-width queries as the screen grows.", + weak: "@media lets you change styles for phones. You use max-width for mobile I think.", + }, +]; + +const INFO1300_QUESTIONS: DemoQuestion[] = [ + // CSS specificity + { + key: "s1", + obj: "S", + difficulty: 2, + text: "A link sits inside <nav id=\"main\"> and has the class active. Which rule sets its color: #main a { color: navy } or .nav .links a.active { color: red }?", + mcq: { + choices: [ + "#main a, because one ID outranks any number of classes", + ".nav .links a.active, because it has more selectors", + "Whichever rule appears later in the stylesheet", + "Neither: the selectors tie and the browser default applies", + ], + correct: 0, + trap: 1, + rationales: [ + "Correct. (1,0,1) beats (0,3,1) because the ID column is compared first.", + "Length doesn't matter. Three classes, (0,3,1), still lose to one ID.", + "Source order only breaks ties, and these selectors don't tie.", + "The scores differ in the ID column, so one rule wins outright.", + ], + }, + model: "#main a wins. Its specificity is (1,0,1); the other rule is (0,3,1), and the ID column is compared first.", + points: ["#main a is (1,0,1)", ".nav .links a.active is (0,3,1)", "the first column that differs decides"], + good: "#main a wins because it has an ID, and the ID column is compared before classes.", + bad: "The red one, because it has more selectors in it.", + errorType: "MISCONCEPTION", + rule: "Compare specificity column by column. One ID beats any number of classes.", + explain: + "Specificity is compared column by column from the left. #main a scores (1,0,1) and .nav .links a.active scores (0,3,1). The first column already differs, so the class count never comes into play.", + }, + { + key: "s2", + obj: "S", + difficulty: 3, + text: "Write the specificity of #story p.intro::first-line and explain how you counted it.", + model: "(1,1,2): one ID (#story), one class (.intro), and two in the type column (p and the ::first-line pseudo-element).", + points: ["#story counts as 1 ID", ".intro counts as 1 class", "p and ::first-line both count as types"], + good: "(1,1,2). #story is the ID, .intro is the class, and p plus the ::first-line pseudo-element go in the type column.", + bad: "(1,1,1). One ID, one class, one element. Pseudo-elements don't count.", + errorType: "MEMORY", + rule: "Pseudo-elements like ::first-line count in the type column, the same as element selectors.", + explain: + "The type column counts element selectors and pseudo-elements. p and ::first-line are both in that column, so the score is (1,1,2), not (1,1,1).", + }, + { + key: "s3", + obj: "S", + difficulty: 3, + text: "Why doesn't .card .title override #sidebar h2, even though the .card rule comes later in the file?", + model: "Source order only breaks ties. #sidebar h2 is (1,0,1) and .card .title is (0,2,0), so the ID rule wins wherever it appears.", + points: ["source order only matters when specificity ties", "#sidebar h2 is (1,0,1)", ".card .title is (0,2,0)"], + good: "Because the later rule only wins on a tie. #sidebar h2 has an ID so it's (1,0,1) against (0,2,0).", + bad: "Later rules always win in CSS, so the class name must be misspelled or the file is cached.", + partial: "Something about IDs being stronger, but I thought the later rule should still win.", + errorType: "MISCONCEPTION", + rule: "Source order only breaks ties. Compare specificity first; here the ID column decides.", + explain: + "The cascade checks specificity before source order. #sidebar h2 scores (1,0,1) and .card .title scores (0,2,0). They don't tie, so it doesn't matter which rule comes later in the file.", + }, + { + key: "s4", + obj: "S", + difficulty: 4, + text: "What is the specificity of :where(#hero) .button?", + mcq: { + choices: ["(0,1,0)", "(1,1,0)", "(0,2,0)", "(1,0,0)"], + correct: 0, + trap: 1, + rationales: [ + "Correct. :where() always adds zero, so only .button counts.", + "This treats :where() like :is(), which takes its argument's specificity.", + ":where() is not a class; it contributes nothing.", + "The ID inside :where() is discarded, and .button still counts.", + ], + }, + model: "(0,1,0). :where() contributes zero specificity, so only the .button class counts.", + points: [":where() always adds zero", ".button adds one class"], + good: ":where() adds nothing, so it's just .button: (0,1,0).", + bad: "(1,1,0), the ID inside still counts.", + errorType: "MISCONCEPTION", + rule: ":where() always contributes zero; :is() and :not() take their most specific argument.", + explain: + ":where() was designed for low-priority defaults: whatever is inside it contributes zero. Only .button counts, so the score is (0,1,0). :is(#hero) .button would be (1,1,0).", + }, + { + key: "s5", + obj: "S", + difficulty: 3, + text: "A rule chains eleven class selectors. Does it beat a rule with a single ID selector? Explain.", + model: "No. Specificity columns never carry over, so (0,11,0) still loses to (1,0,0).", + points: ["columns don't carry", "(0,11,0) loses to (1,0,0)"], + good: "No. Eleven classes is (0,11,0) and the columns don't carry, so (1,0,0) still wins.", + bad: "Yes. Eleven classes add up to more than ten, which carries over into the ID column.", + errorType: "MISCONCEPTION", + rule: "Specificity columns never carry. Any number of classes loses to one ID.", + explain: + "Specificity is not a base-10 number. Each column is compared separately, so no number of classes can reach the ID column. (1,0,0) beats (0,11,0).", + }, + // Box model + { + key: "b1", + obj: "B", + difficulty: 2, + text: "A div has width: 300px, padding: 20px, a 2px border and the default box-sizing. How wide is it on screen?", + mcq: { + choices: ["344px", "300px", "340px", "322px"], + correct: 0, + trap: 1, + rationales: [ + "Correct. 300 + 20 + 20 + 2 + 2 = 344.", + "That would be true with border-box, not the default content-box.", + "This leaves out the border on both sides.", + "This counts padding and border on one side only.", + ], + }, + model: "344px: the 300px content plus 20px padding and 2px border on each side.", + points: ["content-box is the default", "add padding and border on both sides"], + good: "344px, because content-box adds the padding and border on both sides to the 300.", + bad: "300px, that's the width you set.", + errorType: "MISCONCEPTION", + rule: "With content-box, rendered width = width + left and right padding + left and right border.", + explain: + "The default box-sizing is content-box, so width only sets the content area. Padding and border are added on both sides: 300 + 40 + 4 = 344px.", + }, + { + key: "b2", + obj: "B", + difficulty: 2, + text: "What changes when you set box-sizing: border-box on an element with a declared width?", + model: "The declared width now includes padding and border, so the box renders at exactly that width and the content area shrinks.", + points: ["width includes padding and border", "content area shrinks"], + good: "The width includes the padding and border now, so the box is exactly the width you set and the content gets smaller.", + bad: "It puts the border outside the box so the element gets bigger.", + errorType: "MISCONCEPTION", + rule: "border-box means width includes padding and border; the content area shrinks to fit.", + explain: + "border-box moves padding and border inside the declared width. The element's outer size matches the CSS, and the content area gets whatever is left.", + }, + { + key: "b3", + obj: "B", + difficulty: 3, + text: "Two stacked paragraphs have margin-bottom: 24px and margin-top: 16px. How far apart are they, and why?", + model: "24px. Adjacent vertical margins between blocks collapse to the larger of the two.", + points: ["vertical margins collapse", "the larger margin wins"], + good: "24px. The vertical margins collapse and you get the bigger one.", + bad: "40px, the two margins add up.", + partial: "They collapse, so maybe 16px?", + errorType: "MISCONCEPTION", + rule: "Adjacent vertical margins collapse to the larger value; they don't add.", + explain: + "Vertical margins between adjacent block elements collapse into one margin equal to the larger of the two, so the gap is 24px. This doesn't happen inside flex or grid containers.", + }, + { + key: "b4", + obj: "B", + difficulty: 1, + text: "Name the four layers of the box model from the inside out.", + model: "Content, padding, border, margin.", + points: ["content", "padding", "border", "margin"], + good: "Content, padding, border, margin.", + bad: "Content, border, padding, margin.", + errorType: "CARELESS", + rule: "Padding sits inside the border; margin sits outside it.", + explain: "Padding is the space between the content and the border. Margin is outside the border and separates the box from its neighbors.", + }, + // Flexbox alignment + { + key: "f1", + obj: "F", + difficulty: 2, + text: "In a flex container with flex-direction: column, which property centers the children horizontally?", + mcq: { + choices: ["align-items: center", "justify-content: center", "text-align: center", "align-content: center"], + correct: 0, + trap: 1, + rationales: [ + "Correct. In a column the cross axis is horizontal, and align-items works on the cross axis.", + "justify-content works on the main axis, which is vertical in a column.", + "text-align centers inline content, not flex items.", + "align-content spaces wrapped lines, not individual items.", + ], + }, + model: "align-items: center. With flex-direction: column, the cross axis is horizontal.", + points: ["column makes the main axis vertical", "align-items works on the cross axis"], + good: "align-items: center, because in a column the cross axis is the horizontal one.", + bad: "justify-content: center.", + errorType: "MISCONCEPTION", + rule: "justify-content follows the main axis and align-items the cross axis; flex-direction: column swaps them.", + explain: "flex-direction: column makes the main axis vertical, so the horizontal direction is the cross axis, which align-items controls.", + }, + { + key: "f2", + obj: "F", + difficulty: 1, + text: "How do you center a single child both horizontally and vertically inside its parent with flexbox?", + model: "Set the parent to display: flex with justify-content: center and align-items: center.", + points: ["display: flex on the parent", "justify-content: center", "align-items: center"], + good: "Parent gets display: flex, justify-content: center and align-items: center.", + bad: "Put margin: auto and text-align: center on the child.", + errorType: "PROCEDURE", + rule: "Center both ways with display: flex plus justify-content: center and align-items: center on the parent.", + explain: "Both alignment properties go on the flex container. justify-content handles the main axis and align-items the cross axis.", + }, + { + key: "f3", + obj: "F", + difficulty: 3, + text: "What does flex: 1 expand to, and what happens when three siblings all have it?", + model: "flex-grow: 1, flex-shrink: 1, flex-basis: 0%. The three items split the free space equally regardless of their content.", + points: ["grow 1, shrink 1, basis 0%", "equal shares of free space"], + good: "flex-grow 1, flex-shrink 1, flex-basis 0%, so all three take equal widths no matter what's in them.", + bad: "It means flex-grow: 1 only, so bigger items stay bigger.", + errorType: "MEMORY", + rule: "flex: 1 is grow 1, shrink 1, basis 0%, which splits space equally.", + explain: "Because flex-basis is 0%, no item starts with a content-based size, so the free space is split evenly between the three.", + }, + { + key: "f4", + obj: "F", + difficulty: 2, + text: "Which justify-content value puts equal space between items but none at the outer edges?", + mcq: { + choices: ["space-between", "space-around", "space-evenly", "center"], + correct: 0, + trap: 1, + rationales: [ + "Correct. space-between puts the first and last items flush with the edges.", + "space-around adds half-size gaps at the edges.", + "space-evenly makes the edge gaps the same as the gaps between items.", + "center groups the items in the middle with no space between them.", + ], + }, + model: "space-between.", + points: ["first and last items touch the edges"], + good: "space-between.", + bad: "space-around.", + errorType: "CARELESS", + rule: "space-between: no edge space; space-around: half gaps at the edges; space-evenly: equal everywhere.", + explain: "space-between pins the first and last items to the container edges and spreads the rest of the space between items.", + }, + // Grid template areas + { + key: "g1", + obj: "G", + difficulty: 3, + text: "Write grid-template-areas for a two-column layout with a header across the top, a sidebar and main area in the middle, and a footer across the bottom.", + model: "grid-template-areas: \"header header\" \"sidebar main\" \"footer footer\";", + points: ["one string per row", "two cells per row", "repeat a name to span both columns"], + good: "\"header header\" \"sidebar main\" \"footer footer\"", + bad: "\"header\" \"sidebar main\" \"footer\"", + errorType: "PROCEDURE", + rule: "Every row string needs the same number of cells; repeat a name to span columns.", + explain: + "Each string is one row, and every row must have the same number of cells. To make the header and footer span both columns, repeat the name: \"header header\".", + }, + { + key: "g2", + obj: "G", + difficulty: 3, + text: "What happens if a named area in grid-template-areas forms an L shape?", + mcq: { + choices: [ + "The whole declaration is invalid and ignored", + "The browser fills the L shape anyway", + "Only the L-shaped area is ignored", + "The area becomes the smallest rectangle around it", + ], + correct: 0, + trap: 2, + rationales: [ + "Correct. Named areas must be rectangles, or the whole property is invalid.", + "Grid areas can only be rectangles.", + "The browser drops the entire declaration, not just one area.", + "There is no automatic correction to a bounding rectangle.", + ], + }, + model: "The whole grid-template-areas declaration is invalid and the browser ignores it.", + points: ["areas must be rectangles", "the entire declaration is dropped"], + good: "The whole declaration becomes invalid, so none of the areas apply.", + bad: "Only that area is ignored and the rest still work.", + errorType: "MISCONCEPTION", + rule: "A non-rectangular area invalidates the entire grid-template-areas declaration.", + explain: + "Named grid areas must be rectangles. If any area isn't, the browser treats the whole grid-template-areas value as invalid and ignores it, so every area falls back to auto-placement.", + }, + { + key: "g3", + obj: "G", + difficulty: 2, + text: "How does a child element claim a named region of the grid?", + model: "With grid-area set to the region's name, for example grid-area: sidebar.", + points: ["grid-area on the child", "value is the area name"], + good: "Set grid-area on the child to the name, like grid-area: sidebar.", + bad: "Put grid-template-areas on the child with its name.", + errorType: "PROCEDURE", + rule: "grid-template-areas goes on the container; children claim a region with grid-area.", + explain: "The container defines the named regions. Each child opts into one with grid-area and the area's name.", + }, + { + key: "g4", + obj: "G", + difficulty: 2, + text: "What does a period (.) mean inside a grid-template-areas string?", + model: "An empty cell that no named area occupies.", + points: ["empty cell"], + good: "It's an empty cell with no area in it.", + bad: "It ends the row, like a semicolon.", + partial: "Something like a placeholder?", + errorType: "MEMORY", + rule: "A period in grid-template-areas marks an empty cell.", + explain: "Periods fill cells that belong to no named area. Several periods in a row are several empty cells.", + }, + { + key: "g5", + obj: "G", + difficulty: 3, + text: "How can you move the sidebar below the main content on small screens without changing the HTML?", + model: "Redefine grid-template-areas inside a media query so the rows stack: \"header\" \"main\" \"sidebar\" \"footer\" with a single column.", + points: ["media query", "redefine grid-template-areas", "HTML order stays the same"], + good: "Inside a media query, change grid-template-areas to one column: header, main, sidebar, footer.", + bad: "Move the sidebar div after main in the HTML.", + errorType: "PROCEDURE", + rule: "Redefine grid-template-areas in a media query; the HTML order stays the same.", + explain: "Areas decouple visual placement from source order. Redefining the template in a media query moves regions without touching the markup.", + }, + { + key: "g6", + obj: "G", + difficulty: 3, + text: "Can two rows in grid-template-areas have different numbers of cells?", + model: "No. Each string is a row and every row must have the same number of cells, or the declaration is invalid.", + points: ["same number of cells in every row", "otherwise invalid"], + good: "No, every row string needs the same number of cells or it's invalid.", + bad: "Yes, the grid fills the short rows with empty cells.", + errorType: "MISCONCEPTION", + rule: "All rows in grid-template-areas must have the same number of cells.", + explain: "Unlike auto-placement, grid-template-areas does not pad short rows. Mismatched rows make the whole value invalid.", + }, + { + key: "g7", + obj: "G", + difficulty: 2, + text: "In a two-column grid, which row string makes main span both columns?", + mcq: { + choices: ["\"main main\"", "\"main .\"", "\"main\"", "\"main span 2\""], + correct: 0, + trap: 2, + rationales: [ + "Correct. Repeating the name across both cells spans the row.", + "This puts main in the first column and leaves the second empty.", + "A one-cell row doesn't match a two-column grid, so the declaration is invalid.", + "span is not valid inside grid-template-areas strings.", + ], + }, + model: "\"main main\": repeat the name in every cell the area should cover.", + points: ["repeat the area name"], + good: "\"main main\", you repeat the name for each column.", + bad: "\"main\", one name for the whole row.", + errorType: "PROCEDURE", + rule: "To span columns, repeat the area name in each cell.", + explain: "An area covers every cell that carries its name. A two-column row needs two cells, so main appears twice.", + }, + // Responsive images and srcset + { + key: "r1", + obj: "R", + difficulty: 2, + text: "What does the w descriptor in srcset=\"hero-800.jpg 800w\" tell the browser?", + model: "The file's intrinsic width: hero-800.jpg is 800 pixels wide.", + points: ["intrinsic width of the file", "not the display width"], + good: "That the file itself is 800 pixels wide.", + bad: "That the image should be displayed 800px wide.", + errorType: "MISCONCEPTION", + rule: "w states the file's real pixel width; display width comes from sizes and CSS.", + explain: "Width descriptors describe the candidate files, not the layout. The browser combines them with sizes and the pixel ratio to pick a file.", + }, + { + key: "r2", + obj: "R", + difficulty: 3, + text: "Why does an img that uses w descriptors need a sizes attribute?", + model: "The browser chooses a file before CSS loads, so sizes tells it how wide the image slot will be. Without sizes it assumes 100vw.", + points: ["the choice happens before CSS loads", "sizes describes the slot width", "default is 100vw"], + good: "Because the browser picks the file before it knows the CSS, so sizes tells it the slot width. Without it, it assumes 100vw.", + bad: "sizes sets the displayed width of the image, like CSS width.", + partial: "So the browser knows which file to pick? Not sure what happens without it.", + errorType: "MISCONCEPTION", + rule: "sizes is a hint about slot width for choosing a file; it doesn't style the image. Without it the browser assumes 100vw.", + explain: + "Image selection happens during HTML parsing, before layout is known. sizes gives the browser the slot width up front. It doesn't change how wide the image renders; CSS still does that.", + }, + { + key: "r3", + obj: "R", + difficulty: 4, + text: "With sizes=\"(max-width: 600px) 100vw, 50vw\", a laptop window is 1200px wide at 2x density. How many device pixels wide is the slot the browser plans for?", + mcq: { + choices: ["1200", "600", "2400", "800"], + correct: 0, + trap: 1, + rationales: [ + "Correct. 50vw of 1200px is 600 CSS pixels, times 2 for the density.", + "600 is the slot in CSS pixels; the browser also multiplies by the pixel ratio.", + "This uses 100vw, but the window is wider than 600px.", + "There is no 800px rule in this sizes value.", + ], + }, + model: "1200: the slot is 50vw = 600 CSS pixels, and 600 x 2 = 1200 device pixels.", + points: ["the 50vw branch applies above 600px", "multiply by the device pixel ratio"], + good: "50vw is 600 CSS pixels, times 2 for retina, so 1200.", + bad: "600, half the screen.", + errorType: "PROCEDURE", + rule: "Slot width in device pixels = sizes width in CSS pixels times the device pixel ratio.", + explain: "The browser resolves sizes to CSS pixels first (50vw = 600px here), then multiplies by the device pixel ratio to decide which file is big enough.", + }, + { + key: "r4", + obj: "R", + difficulty: 3, + text: "When should you use picture with source media attributes instead of srcset alone?", + model: "For art direction: when small screens need a different crop or a different image, not just a different resolution.", + points: ["art direction", "srcset only switches resolutions of the same image"], + good: "When you want a different crop or image on small screens. srcset only swaps resolutions of the same picture.", + bad: "Whenever you have more than one file size.", + partial: "When the image needs to change on mobile, I think.", + errorType: "MISCONCEPTION", + rule: "picture is for art direction (different crops); srcset is for resolution switching.", + explain: "srcset assumes every candidate is the same image at different resolutions. picture with media conditions lets you serve a different composition at each breakpoint.", + }, + { + key: "r5", + obj: "R", + difficulty: 2, + text: "Write a srcset for a 64px avatar that stays sharp on 2x screens.", + model: "srcset=\"avatar-64.png 1x, avatar-128.png 2x\"", + points: ["density descriptors for fixed-size images", "don't mix x and w"], + good: "srcset=\"avatar-64.png 1x, avatar-128.png 2x\"", + bad: "srcset=\"avatar-64.png 64w, avatar-128.png 2x\"", + errorType: "PROCEDURE", + rule: "Use density descriptors for fixed-size images, and never mix x and w in one srcset.", + explain: "A fixed-size image only needs one file per pixel density. Mixing x and w descriptors in the same srcset is invalid.", + }, + // Media queries + { + key: "m1", + obj: "M", + difficulty: 2, + text: "In a mobile-first stylesheet, which kind of media query do you add as screens get wider?", + model: "min-width queries. The base styles target small screens, and min-width queries add rules as space grows.", + points: ["base styles are for small screens", "add min-width queries"], + good: "min-width queries, because the base styles are already for phones.", + bad: "max-width queries for each phone size.", + errorType: "MISCONCEPTION", + rule: "Mobile first means base styles for small screens plus min-width queries.", + explain: "Mobile-first CSS starts from the smallest layout and layers on changes with min-width queries as the viewport grows.", + }, + { + key: "m2", + obj: "M", + difficulty: 2, + text: "What happens on a phone if the viewport meta tag is missing?", + model: "The browser renders the page at a desktop width (about 980px) and scales it down, so small-screen media queries never apply.", + points: ["renders at desktop width", "scales down", "media queries for small screens don't match"], + good: "The phone pretends it's about 980px wide and zooms out, so the mobile media queries never kick in.", + bad: "Nothing changes, it's just for SEO.", + errorType: "MEMORY", + rule: "Without the viewport meta tag, mobile browsers lay out at desktop width and media queries for small screens don't match.", + explain: "Mobile browsers default to a virtual viewport around 980px wide. width=device-width tells them to use the real screen width.", + }, + { + key: "m3", + obj: "M", + difficulty: 2, + text: "How should you choose breakpoints?", + model: "Where the content starts to break or look cramped, not at specific device widths.", + points: ["content-driven", "not device-driven"], + good: "Resize until the layout looks bad and put a breakpoint there, not at specific phone widths.", + bad: "Use the exact widths of popular phones like 375 and 414.", + errorType: "MISCONCEPTION", + rule: "Pick breakpoints where the content breaks, not at device widths.", + explain: "Device widths change every year. Breakpoints tied to the content keep working on screens you didn't test.", + }, + { + key: "m4", + obj: "M", + difficulty: 2, + text: "Which query applies a three-column gallery only at 768px and wider?", + mcq: { + choices: [ + "@media (min-width: 768px)", + "@media (max-width: 768px)", + "@media (width: 768px)", + "@media (min-device-width: 768px)", + ], + correct: 0, + trap: 1, + rationales: [ + "Correct. min-width matches 768px and anything wider.", + "max-width matches 768px and narrower, the opposite.", + "This matches exactly 768px only.", + "Device-width queries are deprecated and ignore the window size.", + ], + }, + model: "@media (min-width: 768px).", + points: ["min-width means this width and up"], + good: "@media (min-width: 768px).", + bad: "@media (max-width: 768px).", + errorType: "CARELESS", + rule: "min-width means this width and wider; max-width means this width and narrower.", + explain: "min-width: 768px is true for viewports 768px wide or more, which is what a wide-screen gallery needs.", + }, +]; + +// --------------------------------------------------------------------------- +// AEM 2210: Financial Accounting +// --------------------------------------------------------------------------- + +const AEM2210_DOCS: DemoDoc[] = [ + { + file: "aem2210-week-3-accrual-vs-cash.md", + title: "Week 3: Accrual versus cash basis accounting", + uploaded: [-21, "17:20"], + summary: + "The difference between cash and accrual timing, when revenue is recognized, unearned revenue as a liability, and the matching principle for expenses.", + questions: [ + "When is revenue recognized under the accrual basis?", + "Why is cash received in advance a liability?", + "How does the matching principle treat December wages paid in January?", + ], + body: `# Week 3: Accrual versus cash basis accounting + +## Two ways to time revenue and expenses + +Under the cash basis, a business records revenue when cash is received and expenses when cash is paid. Under the accrual basis, revenue is recorded when it is earned and expenses when they are incurred, regardless of when cash changes hands. US GAAP requires the accrual basis for financial statements because it matches the effort of a period with the results of that period. + +## Revenue recognition + +Revenue is recognized when the company satisfies a performance obligation by transferring a good or service to the customer. A landscaping company that mows a lawn on March 28 and is paid on April 5 records March revenue under accrual accounting and April revenue under cash accounting. Cash received in advance is not revenue yet: it is a liability called unearned (deferred) revenue until the work is done. + +## The matching principle + +Expenses are recorded in the same period as the revenue they helped produce. Wages earned by employees in the last week of December are a December expense even if payday is January 3. Supplies bought in bulk are an asset until they are used; only the portion consumed becomes supplies expense. + +## Example + +On December 1, Ithaca Bikes receives $1,200 for a 12-month service plan. Cash basis: $1,200 of revenue in December. Accrual basis: $100 of revenue in December and an $1,100 unearned revenue liability at year end. Accrual net income is smaller this year and larger next year, but total revenue over the 12 months is the same under both methods. + +## Why it matters + +The cash basis is simpler and is allowed for some small businesses for tax purposes. The accrual basis gives investors a better picture of performance, because a large prepayment or a delayed bill does not distort a single period. +`, + }, + { + file: "aem2210-week-4-journal-entries.md", + title: "Week 4: Journal entries, T-accounts, and adjusting entries", + uploaded: [-21, "17:22"], + summary: + "Debit and credit rules for each account type, recording journal entries, posting to T-accounts, the four common adjusting entries, and depreciation.", + questions: [ + "Which account types increase with a debit?", + "What are the four common adjusting entries?", + "Why does an adjusting entry never involve Cash?", + ], + body: `# Week 4: Journal entries, T-accounts, and adjusting entries + +## Debits and credits + +Every transaction affects at least two accounts, and total debits equal total credits. Debits increase assets, expenses and dividends; credits increase liabilities, equity and revenue. A quick way to remember it: assets are on the left of the accounting equation (Assets = Liabilities + Equity), so they grow on the left, or debit, side of a T-account. + +## Recording a journal entry + +List the debited account first, then the credited account, indented. Paying $500 of rent in cash: + +Dr. Rent Expense 500 + Cr. Cash 500 + +Buying $2,000 of equipment on account: + +Dr. Equipment 2,000 + Cr. Accounts Payable 2,000 + +## T-accounts + +A T-account shows one account's debits on the left and credits on the right. The balance is the difference, on the side with the larger total. Posting each journal entry to its T-accounts makes errors easier to spot before preparing a trial balance. + +## Adjusting entries + +At the end of a period, adjusting entries bring accounts up to date under the accrual basis. There are four common types: + +1. Accrued revenue: earned but not yet billed or collected (Dr. Accounts Receivable, Cr. Service Revenue). +2. Accrued expense: incurred but not yet paid, such as wages (Dr. Wages Expense, Cr. Wages Payable). +3. Deferred revenue earned: part of a prepayment is now earned (Dr. Unearned Revenue, Cr. Service Revenue). +4. Prepaid expense used up: part of an asset is consumed, such as insurance or supplies (Dr. Insurance Expense, Cr. Prepaid Insurance). + +Adjusting entries never involve Cash. If an entry you are calling an adjustment touches Cash, it is a regular transaction. + +## Depreciation + +Equipment is spread over its useful life with Dr. Depreciation Expense, Cr. Accumulated Depreciation. Accumulated Depreciation is a contra-asset account, so its normal balance is a credit. +`, + }, +]; + +const AEM2210_OBJECTIVES: DemoObjective[] = [ + { + code: "A", + title: "Accrual versus cash basis", + recall: "Cash basis records revenue and expenses when cash moves. Accrual records them when they're earned or incurred.", + weak: "Accrual is when you record things before you get paid? Cash is when you get paid.", + }, + { + code: "RR", + title: "Revenue recognition", + recall: "Revenue is recognized when the performance obligation is satisfied. Cash received early is unearned revenue, a liability.", + weak: "You recognize revenue when you get the money, unless it's a big contract.", + }, + { + code: "D", + title: "Debits and credits", + recall: "Debits increase assets, expenses and dividends. Credits increase liabilities, equity and revenue. Debits always equal credits.", + weak: "Debit is left and credit is right. Debits are good for assets I think.", + }, + { + code: "J", + title: "Adjusting entries", + recall: "Adjusting entries update accrued revenue, accrued expenses, deferred revenue and prepaid expenses at period end, and never touch Cash.", + weak: "You adjust accounts at the end of the month so they're right. Not sure which accounts.", + }, +]; + +const AEM2210_QUESTIONS: DemoQuestion[] = [ + { + key: "a1", + obj: "A", + difficulty: 1, + text: "A landscaper mows a lawn on March 28 and is paid April 5. In which month is the revenue recorded under each basis?", + model: "Accrual: March, when the work is done. Cash: April, when the payment arrives.", + points: ["accrual records when earned", "cash records when received"], + good: "Accrual puts it in March because that's when it was earned; cash basis puts it in April.", + bad: "April under both, since that's when they got paid.", + errorType: "MISCONCEPTION", + rule: "Accrual records revenue when it's earned, not when cash arrives.", + explain: "The service was performed in March, so accrual accounting records March revenue. Only the cash basis waits for the April payment.", + }, + { + key: "a2", + obj: "A", + difficulty: 2, + text: "Why does US GAAP require the accrual basis for financial statements?", + model: "It matches revenue with the expenses that produced it in the same period, so one period's results aren't distorted by when cash moved.", + points: ["matching", "performance not distorted by cash timing"], + good: "Because it matches revenue and expenses to the period they belong to, so a big prepayment doesn't distort one month.", + bad: "Because it's easier to audit cash.", + errorType: "MEMORY", + rule: "Accrual is required because it matches revenue and expenses to the period of the activity.", + explain: "Accrual accounting ties results to the period the work happened, which makes performance comparable across periods.", + }, + { + key: "a3", + obj: "A", + difficulty: 3, + text: "On December 1 a shop receives $1,200 for a 12-month service plan. How much December revenue does it report under each basis?", + model: "Cash basis: $1,200. Accrual basis: $100, with $1,100 of unearned revenue at year end.", + points: ["cash: all $1,200", "accrual: one month, $100", "$1,100 unearned revenue"], + good: "Cash: $1,200. Accrual: $100 for one month, and the other $1,100 is unearned revenue.", + bad: "$1,200 under both because the cash came in December.", + errorType: "PROCEDURE", + rule: "Under accrual, recognize only the portion earned in the period; the rest stays in unearned revenue.", + explain: "One of twelve months of service was delivered in December, so accrual revenue is $1,200 / 12 = $100. The remaining $1,100 is still owed to the customer as service.", + }, + { + key: "rr1", + obj: "RR", + difficulty: 2, + text: "A customer pays $600 in September for tutoring sessions held in October. How is the September receipt classified?", + mcq: { + choices: [ + "As unearned revenue, a liability", + "As September service revenue", + "As October service revenue, recorded in September", + "As accounts receivable", + ], + correct: 0, + trap: 1, + rationales: [ + "Correct. The service hasn't been delivered, so the company owes it: a liability.", + "Revenue needs the obligation to be satisfied, and nothing was delivered in September.", + "Revenue can't be recorded before it's earned, even with a future label.", + "Receivables are amounts customers owe; here the customer already paid.", + ], + }, + model: "Unearned revenue, a liability, until the October sessions happen.", + points: ["cash in advance is a liability", "revenue when the service is delivered"], + good: "It's unearned revenue, a liability, until the sessions actually happen in October.", + bad: "It's revenue in September because the cash came in.", + errorType: "MISCONCEPTION", + rule: "Cash received before the work is done is unearned revenue, a liability, not revenue.", + explain: "Revenue is recognized when the performance obligation is satisfied. Until the October sessions happen, the company owes the customer service, so the cash sits in unearned revenue.", + }, + { + key: "rr2", + obj: "RR", + difficulty: 2, + text: "When is revenue recognized under the accrual basis?", + model: "When the company satisfies a performance obligation by transferring the good or service to the customer.", + points: ["performance obligation satisfied", "good or service transferred"], + good: "When the company actually delivers the good or service, which satisfies the performance obligation.", + bad: "When the invoice is sent.", + errorType: "MEMORY", + rule: "Revenue is recognized when the performance obligation is satisfied.", + explain: "Billing and collecting are separate events. Recognition is tied to delivering what was promised.", + }, + { + key: "rr3", + obj: "RR", + difficulty: 3, + text: "Employees earn $3,000 of wages in the last week of December, paid January 3. When is the expense recorded under accrual, and why?", + model: "December, under the matching principle: the wages helped produce December revenue.", + points: ["December expense", "matching principle", "wages payable at year end"], + good: "December, because of matching. It's an accrued expense with wages payable until January.", + bad: "January 3, when the cash goes out.", + errorType: "MISCONCEPTION", + rule: "Expenses go in the period they help produce revenue, not when they're paid.", + explain: "The matching principle puts the wages in December, with a Wages Payable liability until payday.", + }, + { + key: "d1", + obj: "D", + difficulty: 1, + text: "Which account types increase with a debit?", + model: "Assets, expenses and dividends.", + points: ["assets", "expenses", "dividends"], + good: "Assets, expenses and dividends.", + bad: "Assets and revenue.", + errorType: "MEMORY", + rule: "Debits increase assets, expenses and dividends; credits increase liabilities, equity and revenue.", + explain: "Accounts on the left of the equation, plus the accounts that reduce equity (expenses and dividends), grow with debits.", + }, + { + key: "d2", + obj: "D", + difficulty: 2, + text: "Write the journal entry for buying $2,000 of equipment on account.", + model: "Dr. Equipment 2,000; Cr. Accounts Payable 2,000.", + points: ["debit Equipment", "credit Accounts Payable"], + good: "Dr. Equipment 2,000, Cr. Accounts Payable 2,000.", + bad: "Dr. Equipment 2,000, Cr. Cash 2,000.", + errorType: "CARELESS", + rule: "On account means a payable, not cash.", + explain: "Buying on account creates a liability. Cash is untouched until the bill is paid.", + }, + { + key: "d3", + obj: "D", + difficulty: 2, + text: "What is the normal balance of Accumulated Depreciation, and why?", + model: "Credit. It's a contra-asset account that offsets the equipment's debit balance.", + points: ["credit balance", "contra-asset"], + good: "Credit, because it's a contra-asset that reduces equipment.", + bad: "Debit, because it's an asset account.", + errorType: "MISCONCEPTION", + rule: "Contra accounts carry the opposite normal balance of the account they offset.", + explain: "Accumulated Depreciation sits with assets but reduces them, so its normal balance is a credit.", + }, + { + key: "j1", + obj: "J", + difficulty: 3, + text: "Half of a $1,200 prepaid insurance policy has expired at month end. Write the adjusting entry.", + model: "Dr. Insurance Expense 600; Cr. Prepaid Insurance 600.", + points: ["expense the used portion", "reduce the prepaid asset"], + good: "Dr. Insurance Expense 600, Cr. Prepaid Insurance 600.", + bad: "Dr. Prepaid Insurance 600, Cr. Cash 600.", + errorType: "PROCEDURE", + rule: "A used-up prepaid moves from the asset to expense: Dr. Expense, Cr. Prepaid. No cash.", + explain: "The policy was paid earlier. At month end, the expired half becomes expense and the asset shrinks by the same amount.", + }, + { + key: "j2", + obj: "J", + difficulty: 3, + text: "Why does an adjusting entry never involve Cash?", + model: "Adjustments record what was earned or incurred without a cash event; any entry that moves cash is a regular transaction.", + points: ["adjustments are non-cash", "cash entries are transactions"], + good: "Because adjustments catch up on things earned or used that didn't have a cash event. If cash moves it's a normal transaction.", + bad: "They can, like paying wages at the end of the month.", + partial: "Because cash is already up to date? Not sure.", + errorType: "MISCONCEPTION", + rule: "Adjusting entries never touch Cash; if cash moves, it's a regular transaction.", + explain: "Cash is recorded when it moves, so it's always current. Adjustments fix the accrual-based accounts that changed without cash moving.", + }, + { + key: "j3", + obj: "J", + difficulty: 2, + text: "A company earned $800 of service revenue in June but won't bill the client until July. What is the June adjusting entry?", + model: "Dr. Accounts Receivable 800; Cr. Service Revenue 800.", + points: ["accrued revenue", "debit receivable", "credit revenue"], + good: "Dr. Accounts Receivable 800, Cr. Service Revenue 800.", + bad: "No entry until the bill goes out.", + errorType: "PROCEDURE", + rule: "Accrued revenue: Dr. Accounts Receivable, Cr. Revenue in the period it's earned.", + explain: "The work is done in June, so June gets the revenue even though the invoice comes later.", + }, +]; + +// --------------------------------------------------------------------------- +// INFO 4340: Web Prototyping +// --------------------------------------------------------------------------- + +const INFO4340_DOCS: DemoDoc[] = [ + { + file: "info4340-lecture-5-components-props-events.md", + title: "Lecture 5: Vue components, props, and events", + uploaded: [-17, "20:05"], + summary: + "Single-file components with script setup and scoped styles, one-way data flow with props, emitting events to parents, v-model on components, and keys in v-for lists.", + questions: [ + "Why are props read-only in the child?", + "What does v-model expand to on a custom component?", + "Why is the array index a bad key for v-for?", + ], + body: `# Lecture 5: Vue components, props, and events + +## Single-file components + +A Vue single-file component (.vue) keeps a component's template, script and styles together. With script setup, every top-level binding in the script is available in the template, so there is no need to return values from a setup() function. + +<script setup> +import { ref } from "vue"; +const count = ref(0); +</script> + +<template> + <button @click="count++">Clicked {{ count }} times</button> +</template> + +The scoped attribute on a style block limits its rules to this component by adding a unique data attribute to its elements. + +## Props flow down + +A parent passes data to a child through props. In the child, declare them with defineProps: + +const props = defineProps({ title: String, done: Boolean }); + +Props are read-only in the child. If a child needs to change a value it received, it should emit an event and let the parent update its own state. This one-way data flow keeps it clear which component owns each piece of state. + +## Events flow up + +Declare events with defineEmits and fire them with emit: + +const emit = defineEmits(["toggle"]); +function onClick() { emit("toggle", props.id); } + +The parent listens with @toggle="handleToggle". For two-way binding on a custom component, v-model is shorthand for a modelValue prop plus an update:modelValue event. + +## Lists and keys + +v-for renders a list, and each item needs a unique, stable :key so Vue can track which element is which when the list changes. Using the array index as the key causes bugs when items are inserted or reordered, because state sticks to the position instead of the item. +`, + }, + { + file: "info4340-lecture-6-reactive-state.md", + title: "Lecture 6: Reactive state with ref, reactive, and computed", + uploaded: [-17, "20:06"], + summary: + "ref and reactive for state, why destructuring breaks reactivity, cached computed properties, watch for side effects, and onMounted for DOM work.", + questions: [ + "When do you need .value on a ref?", + "Why does destructuring a reactive object break reactivity?", + "When should you use computed instead of watch?", + ], + body: `# Lecture 6: Reactive state with ref, reactive, and computed + +## ref + +ref() wraps a value in a reactive object. In the script you read and write it through .value; in the template Vue unwraps it automatically, so you write {{ count }}, not {{ count.value }}. ref works for any type, including primitives like numbers and strings. + +## reactive + +reactive() makes an object deeply reactive without .value. It only works with objects, and destructuring a reactive object breaks reactivity: const { total } = cart copies the current value into a plain variable. Use toRefs(cart) if you need to destructure. + +## computed + +A computed property derives a value from other reactive state and caches it until one of its dependencies changes: + +const remaining = computed(() => todos.value.filter(t => !t.done).length); + +Computed getters should be pure: no API calls and no changes to other state. If a value can be calculated from existing state, make it computed instead of storing a copy that can drift out of sync. + +## watch + +watch runs a side effect when a source changes, such as saving to localStorage or fetching data when a search term changes: + +watch(query, async (q) => { results.value = await search(q); }); + +Use computed for values and watch for effects. A common mistake is using watch to keep a second piece of state in sync with the first, which a computed property does with less code and no risk of stale values. + +## Lifecycle + +onMounted runs after the component is inserted into the DOM, which makes it the right place for code that needs real elements, like measuring a chart container. Data fetching can start in setup itself. +`, + }, +]; + +const INFO4340_OBJECTIVES: DemoObjective[] = [ + { + code: "C", + title: "Single-file components", + recall: "A .vue file has template, script and style together. With script setup, top-level bindings are usable in the template directly.", + weak: "A .vue file has the HTML and JS in one place. Not sure what setup changes.", + }, + { + code: "P", + title: "Props and emits", + recall: "Props go down from parent to child and are read-only. The child emits events up and the parent changes its own state.", + weak: "Props pass data to children. I think the child can change them if needed?", + }, + { + code: "RF", + title: "ref and reactive", + recall: "ref wraps any value and needs .value in script; reactive makes objects reactive without .value but breaks if you destructure.", + weak: "ref and reactive both make state reactive. Not sure when to pick which.", + }, + { + code: "CW", + title: "computed and watch", + recall: "computed derives cached values from state; watch runs side effects when something changes.", + weak: "Both react to changes. watch is maybe more powerful?", + }, +]; + +const INFO4340_QUESTIONS: DemoQuestion[] = [ + { + key: "c1", + obj: "C", + difficulty: 1, + text: "With script setup, how does the template get access to a variable declared in the script?", + model: "Every top-level binding in script setup is available in the template automatically; nothing needs to be returned.", + points: ["top-level bindings are exposed", "no return statement"], + good: "Anything declared at the top level of script setup is automatically usable in the template.", + bad: "You have to return it from setup().", + errorType: "MEMORY", + rule: "In script setup, top-level bindings are exposed to the template automatically.", + explain: "script setup compiles the component so that its top-level variables, imports and functions are in template scope.", + }, + { + key: "c2", + obj: "C", + difficulty: 2, + text: "What does the scoped attribute on a style block do?", + model: "It limits the styles to this component by adding a unique data attribute to its elements and to the selectors.", + points: ["styles apply only to this component", "unique data attribute"], + good: "It keeps the CSS inside the component by adding a unique data attribute to its elements.", + bad: "It makes the styles load only when the component is visible.", + errorType: "MISCONCEPTION", + rule: "scoped rewrites selectors with a unique data attribute so styles only match this component.", + explain: "Vue adds a data-v attribute to the component's elements and to each selector, so the rules can't leak to other components.", + }, + { + key: "c3", + obj: "C", + difficulty: 2, + text: "Why is the array index a bad :key for a v-for list that can be reordered?", + model: "State sticks to the position instead of the item, so inserting or reordering items attaches state to the wrong element.", + points: ["keys must be stable and unique", "index changes on reorder"], + good: "Because the index changes when items move, so Vue reuses the wrong element and state ends up on the wrong item.", + bad: "Index keys are fine, they're unique.", + errorType: "MISCONCEPTION", + rule: "Use a stable unique id as the key; the index changes when items move.", + explain: "Vue matches elements to data by key. If keys follow positions, a reorder makes Vue patch elements in place and their state stays behind.", + }, + { + key: "p1", + obj: "P", + difficulty: 2, + text: "A child component receives a done prop and needs to toggle it when clicked. What should it do?", + model: "Emit an event, for example emit(\"toggle\", id), and let the parent update its own state; props are read-only in the child.", + points: ["props are read-only", "emit an event", "the parent owns the state"], + good: "Emit a toggle event with the id and let the parent change done, since props are read-only.", + bad: "Set props.done = !props.done inside the child.", + errorType: "MISCONCEPTION", + rule: "Props are read-only. The child emits an event and the parent updates its own state.", + explain: "One-way data flow keeps one owner for each piece of state. Mutating a prop from the child would be overwritten on the parent's next render.", + }, + { + key: "p2", + obj: "P", + difficulty: 2, + text: "What does v-model expand to on a custom component?", + model: "A modelValue prop plus an update:modelValue event.", + points: ["modelValue prop", "update:modelValue event"], + good: "A modelValue prop and an update:modelValue event.", + bad: "A value prop and an input event.", + errorType: "MEMORY", + rule: "On components, v-model = modelValue prop + update:modelValue event.", + explain: "Vue 3 changed the defaults from Vue 2's value and input to modelValue and update:modelValue.", + }, + { + key: "p3", + obj: "P", + difficulty: 1, + text: "How does a child declare the events it can emit with script setup?", + model: "With defineEmits, for example const emit = defineEmits([\"toggle\"]).", + points: ["defineEmits"], + good: "const emit = defineEmits([\"toggle\"]).", + bad: "With this.$emit, no declaration needed.", + errorType: "MEMORY", + rule: "Declare events with defineEmits in script setup.", + explain: "defineEmits declares the component's events and returns the emit function used to fire them.", + }, +]; + +export const COURSES: Record<string, DemoCourse> = { + INFO1300: { + name: "INFO 1300", + exam: "Prelim 2", + examOffset: 7, + objectives: INFO1300_OBJECTIVES, + docs: INFO1300_DOCS, + questions: INFO1300_QUESTIONS, + }, + AEM2210: { + name: "AEM 2210", + exam: "Prelim 1", + examOffset: 17, + objectives: AEM2210_OBJECTIVES, + docs: AEM2210_DOCS, + questions: AEM2210_QUESTIONS, + }, + INFO4340: { + name: "INFO 4340", + exam: "Midterm", + examOffset: 22, + objectives: INFO4340_OBJECTIVES, + docs: INFO4340_DOCS, + questions: INFO4340_QUESTIONS, + }, + ECON1110: { + name: "ECON 1110", + exam: "Final", + examOffset: 60, + objectives: [ + { + code: "SM", + title: "Shifts and movements along a curve", + recall: "A price change moves along the curve; anything else that affects buyers or sellers shifts it.", + weak: "Demand goes up when price goes down, so the curve shifts.", + }, + { + code: "EQ", + title: "Market equilibrium", + recall: "Equilibrium is where quantity supplied equals quantity demanded; a surplus pushes price down and a shortage pushes it up.", + weak: "Where supply and demand cross.", + }, + { + code: "EL", + title: "Price elasticity of demand", + recall: "Percent change in quantity demanded over percent change in price, using the midpoint method.", + weak: "How much demand changes when price changes.", + }, + ], + docs: [ + { + file: "econ1110-lecture-4-supply-and-demand.md", + title: "Lecture 4: Supply, demand, and equilibrium", + uploaded: [-2, "12:40"], + summary: + "What moves along versus shifts the demand and supply curves, how surpluses and shortages push a market to equilibrium, and how to solve for it.", + questions: [ + "What is the difference between a change in demand and a change in quantity demanded?", + "What happens to price and quantity when demand shifts right?", + "How do you solve for equilibrium from two linear equations?", + ], + body: `# Lecture 4: Supply, demand, and equilibrium + +## Demand + +The demand curve shows the quantity buyers want at each price, holding everything else constant. It slopes down: as the price of coffee rises, people buy less of it. A change in the good's own price moves along the curve. A change in anything else that affects buyers, such as income, the price of a substitute like tea, tastes or expectations, shifts the whole curve. + +## Supply + +The supply curve shows the quantity sellers offer at each price. It slopes up because higher prices cover higher marginal costs. A change in input costs, technology, the number of sellers or expectations shifts supply. + +## Movement versus shift + +"Demand increased" means the whole curve shifted right. "Quantity demanded increased" means a movement along the curve, caused by a lower price. Mixing these up is the most common mistake on prelim questions. + +## Equilibrium + +The market clears where quantity supplied equals quantity demanded. Above the equilibrium price there is a surplus, which pushes the price down; below it there is a shortage, which pushes the price up. + +Example: Qd = 100 - 2P and Qs = 20 + 2P. Setting them equal gives 100 - 2P = 20 + 2P, so P = 20 and Q = 60. + +## Shifts and the new equilibrium + +If demand shifts right while supply is unchanged, both the equilibrium price and quantity rise. If supply shifts right while demand is unchanged, price falls and quantity rises. When both curves shift at once, one of the two outcomes is ambiguous unless you know the size of each shift. +`, + }, + { + file: "econ1110-lecture-5-elasticity.md", + title: "Lecture 5: Elasticity", + uploaded: [-2, "12:41"], + summary: + "Price elasticity of demand with the midpoint method, what makes demand elastic, how elasticity predicts the effect of a price change on total revenue, and income and cross-price elasticity.", + questions: [ + "How do you compute elasticity with the midpoint method?", + "Why does raising the price of an inelastic good raise total revenue?", + "What sign does cross-price elasticity have for complements?", + ], + body: `# Lecture 5: Elasticity + +## Price elasticity of demand + +Price elasticity of demand measures how much quantity demanded responds to a change in price: + +Ed = (% change in quantity demanded) / (% change in price) + +Economists usually report the absolute value. Demand is elastic when |Ed| > 1, inelastic when |Ed| < 1, and unit elastic when |Ed| = 1. + +## The midpoint method + +To get the same answer whether the price rises or falls, compute percentage changes using the average of the two values. If the price of a ticket rises from $8 to $12 and quantity falls from 110 to 90, the percentage change in quantity is -20/100 = -20% and the percentage change in price is 4/10 = 40%, so |Ed| = 0.5: inelastic. + +## What makes demand elastic + +Demand is more elastic when close substitutes exist, when the good is a luxury rather than a necessity, when the market is narrowly defined (a brand of cereal rather than food), and over longer time horizons. + +## Elasticity and total revenue + +Total revenue is price times quantity. When demand is inelastic, raising the price raises total revenue, because quantity falls by a smaller percentage. When demand is elastic, raising the price lowers total revenue. At unit elasticity, total revenue does not change. + +## Other elasticities + +Income elasticity is positive for normal goods and negative for inferior goods. Cross-price elasticity is positive for substitutes and negative for complements. +`, + }, + ], + questions: [], + }, +}; + +// --------------------------------------------------------------------------- +// Flashcard decks +// --------------------------------------------------------------------------- + +export interface DemoCard { + front: string; + back: string; + tags: string[]; + /** 0 = easy card, 1 = card this student keeps missing. */ + hardness: number; +} + +export interface DemoDeck { + course: string; + title: string; + docFile: string; + created: When; + cards: DemoCard[]; + /** Review days: when, how many new cards to introduce, and a cap on reviews. */ + sessions: { at: When; newCards: number; maxDue: number }[]; +} + +export const DECKS: DemoDeck[] = [ + { + course: "AEM2210", + title: "Debits, credits, and adjusting entries", + docFile: "aem2210-week-4-journal-entries.md", + created: [-21, "17:40"], + cards: [ + { front: "Which account types increase with a debit?", back: "Assets, expenses, and dividends.", tags: ["Debits and credits"], hardness: 0.2 }, + { front: "Which account types increase with a credit?", back: "Liabilities, equity, and revenue.", tags: ["Debits and credits"], hardness: 0.2 }, + { front: "Journal entry: pay $500 of rent in cash", back: "Dr. Rent Expense 500\nCr. Cash 500", tags: ["Debits and credits"], hardness: 0.1 }, + { front: "Journal entry: buy $2,000 of equipment on account", back: "Dr. Equipment 2,000\nCr. Accounts Payable 2,000", tags: ["Debits and credits"], hardness: 0.3 }, + { front: "Accrued revenue adjusting entry", back: "Dr. Accounts Receivable\nCr. Service Revenue", tags: ["Adjusting entries"], hardness: 0.5 }, + { front: "Accrued expense (wages) adjusting entry", back: "Dr. Wages Expense\nCr. Wages Payable", tags: ["Adjusting entries"], hardness: 0.5 }, + { front: "Deferred revenue earned: adjusting entry", back: "Dr. Unearned Revenue\nCr. Service Revenue", tags: ["Adjusting entries"], hardness: 0.8 }, + { front: "Prepaid insurance used up: adjusting entry", back: "Dr. Insurance Expense\nCr. Prepaid Insurance", tags: ["Adjusting entries"], hardness: 0.6 }, + { front: "Do adjusting entries ever touch Cash?", back: "No. If an entry moves cash, it's a regular transaction, not an adjustment.", tags: ["Adjusting entries"], hardness: 0.4 }, + { front: "Normal balance of Accumulated Depreciation", back: "Credit. It's a contra-asset account.", tags: ["Debits and credits"], hardness: 0.7 }, + ], + sessions: [ + { at: [-20, "17:10"], newCards: 6, maxDue: 0 }, + { at: [-19, "18:00"], newCards: 2, maxDue: 8 }, + { at: [-17, "17:30"], newCards: 2, maxDue: 8 }, + { at: [-2, "13:50"], newCards: 0, maxDue: 3 }, + { at: [-1, "17:40"], newCards: 0, maxDue: 3 }, + ], + }, + { + course: "INFO1300", + title: "Layout and specificity", + docFile: "info1300-lecture-16-flexbox-and-grid.md", + created: [-11, "08:30"], + cards: [ + { front: "Specificity of #nav a", back: "(1,0,1): one ID, one type.", tags: ["CSS specificity"], hardness: 0.6 }, + { front: "Do eleven classes beat one ID?", back: "No. Specificity columns never carry: (0,11,0) loses to (1,0,0).", tags: ["CSS specificity"], hardness: 0.9 }, + { front: "When does source order decide between two rules?", back: "Only when origin, importance, and specificity all tie.", tags: ["CSS specificity"], hardness: 0.8 }, + { front: "Specificity added by :where()", back: "Zero, whatever is inside it.", tags: ["CSS specificity"], hardness: 0.7 }, + { front: "content-box width of width: 300px, padding: 20px, border: 2px", back: "344px on screen.", tags: ["Box model"], hardness: 0.3 }, + { front: "What does box-sizing: border-box change?", back: "Width includes padding and border; the content area shrinks.", tags: ["Box model"], hardness: 0.2 }, + { front: "Flexbox: center a child both ways", back: "Parent: display: flex; justify-content: center; align-items: center.", tags: ["Flexbox alignment"], hardness: 0.1 }, + { front: "flex: 1 expands to", back: "flex-grow: 1; flex-shrink: 1; flex-basis: 0%.", tags: ["Flexbox alignment"], hardness: 0.3 }, + { front: "grid-template-areas for header, sidebar + main, footer", back: "\"header header\"\n\"sidebar main\"\n\"footer footer\"", tags: ["Grid template areas"], hardness: 0.7 }, + { front: "What makes a grid-template-areas value invalid?", back: "A non-rectangular area, or rows with different numbers of cells.", tags: ["Grid template areas"], hardness: 0.8 }, + { front: "What does 800w mean in srcset?", back: "The file is 800 pixels wide (intrinsic width), not the display width.", tags: ["Responsive images and srcset"], hardness: 0.8 }, + { front: "What does the browser assume if sizes is missing?", back: "100vw, so it often downloads a larger file than needed.", tags: ["Responsive images and srcset"], hardness: 0.9 }, + ], + sessions: [ + { at: [-11, "08:45"], newCards: 7, maxDue: 0 }, + { at: [-9, "12:30"], newCards: 3, maxDue: 8 }, + { at: [-4, "13:10"], newCards: 2, maxDue: 4 }, + { at: [-1, "12:40"], newCards: 0, maxDue: 3 }, + ], + }, +]; + +// --------------------------------------------------------------------------- +// Study guides (INFO 1300, Prelim 2) +// --------------------------------------------------------------------------- + +export const GUIDES: { + course: string; + type: "KEY_CONCEPTS" | "FAQ" | "CHEAT_SHEET"; + title: string; + created: When; + sections: Record<string, string>[]; +}[] = [ + { + course: "INFO1300", + type: "KEY_CONCEPTS", + title: "Prelim 2 key concepts", + created: [-2, "21:20"], + sections: [ + { + concept: "Specificity", + explanation: + "Selectors are scored as (IDs, classes, types) and compared column by column from the left. The first column that differs decides; columns never carry, so one ID beats any number of classes.", + importance: "Most cascade questions come down to scoring two selectors correctly before thinking about source order.", + }, + { + concept: "The cascade order", + explanation: + "Origin and importance are checked first, then specificity, then source order. A later rule only wins when everything before it ties.", + importance: "Explains why moving a rule lower in the file often changes nothing.", + }, + { + concept: "Box sizing", + explanation: + "content-box adds padding and border to the declared width; border-box includes them in it. Vertical margins between blocks collapse to the larger value.", + importance: "Width arithmetic shows up in layout questions and in debugging overflow.", + }, + { + concept: "Flexbox axes", + explanation: + "justify-content aligns along the main axis and align-items along the cross axis. flex-direction: column swaps which direction each one controls.", + importance: "Centering and spacing questions depend on knowing which axis is which.", + }, + { + concept: "Grid template areas", + explanation: + "Name regions on the container with one string per row; every row needs the same number of cells and every area must be a rectangle. Children claim regions with grid-area.", + importance: "An invalid template silently drops the whole layout, which is easy to miss.", + }, + { + concept: "srcset and sizes", + explanation: + "w descriptors give each file's real width, and sizes gives the slot width the browser should plan for. The browser multiplies the slot by the pixel ratio and picks the smallest file that covers it.", + importance: "Without sizes the browser assumes 100vw and over-downloads on wide layouts.", + }, + ], + }, + { + course: "INFO1300", + type: "FAQ", + title: "Prelim 2 questions and answers", + created: [-2, "21:22"], + sections: [ + { + question: "Why doesn't my later rule override an earlier one?", + answer: + "Source order only breaks ties. If the earlier rule has a higher specificity, for example because it uses an ID, it wins wherever it appears.", + }, + { + question: "Do I need sizes if I already have srcset?", + answer: + "Yes when srcset uses w descriptors. For a fixed-size image with x descriptors, sizes isn't needed.", + }, + { + question: "When should I use picture instead of srcset?", + answer: + "When small screens need a different crop or image (art direction). srcset only switches between resolutions of the same image.", + }, + { + question: "Flexbox or grid for a page layout?", + answer: + "Grid, because you are placing regions in rows and columns at once. Flexbox suits one-directional rows like a nav bar.", + }, + { + question: "Why is my grid layout ignored completely?", + answer: + "grid-template-areas is invalid if any area isn't a rectangle or if rows have different numbers of cells, and the browser drops the whole declaration.", + }, + ], + }, + { + course: "INFO1300", + type: "CHEAT_SHEET", + title: "Prelim 2 cheat sheet", + created: [-2, "21:25"], + sections: [ + { + topic: "Specificity", + content: + "ID = (1,0,0)\nclass, attribute, pseudo-class = (0,1,0)\ntype, pseudo-element = (0,0,1)\n:where() = 0; :is() and :not() = most specific argument\ninline style beats selectors; !important beats inline", + }, + { + topic: "Box model", + content: + "content-box: rendered width = width + padding + border\nborder-box: rendered width = width\nAdjacent vertical margins collapse to the larger one", + }, + { + topic: "Flexbox and grid", + content: + "justify-content: main axis; align-items: cross axis\nflex: 1 = 1 1 0%\ngrid-template-areas: one string per row, same cell count, rectangles only\n. = empty cell; children use grid-area: name", + }, + { + topic: "Responsive images", + content: + "srcset w = file width; sizes = slot width (default 100vw)\nx descriptors for fixed-size images; don't mix x and w\npicture + source media for art direction\nMobile first: min-width queries; viewport meta tag required", + }, + ], + }, +]; + +// --------------------------------------------------------------------------- +// Chat history +// --------------------------------------------------------------------------- + +export interface DemoChatMessage { + role: "user" | "assistant"; + at: When; + content: string; + /** Citations point at a phrase inside one of the course's documents. */ + cites?: { docFile: string; phrase: string; reason: string }[]; +} + +export const CHATS: { course: string; messages: DemoChatMessage[] }[] = [ + { + course: "INFO1300", + messages: [ + { + role: "user", + at: [-3, "21:12"], + content: "Why does an ID beat a bunch of classes even when the class selector is longer?", + }, + { + role: "assistant", + at: [-3, "21:12"], + content: + "Specificity is compared column by column, left to right: IDs, then classes, then types. The first column that differs decides, and the columns never carry over. So #nav a scores (1,0,1) and beats .menu .item .link at (0,3,0), even though the second selector is longer [1].\n\nSource order only matters when every column ties [1].", + cites: [ + { + docFile: "info1300-lecture-14-specificity-and-box-model.md", + phrase: "Compare the columns left to right", + reason: "Defines the column-by-column comparison and the no-carry rule", + }, + ], + }, + { + role: "user", + at: [-2, "20:41"], + content: "Do I need sizes if I already have srcset?", + }, + { + role: "assistant", + at: [-2, "20:41"], + content: + "If the srcset uses w descriptors, yes. The browser picks a file before CSS loads, so sizes tells it how wide the image slot will be. Without sizes it assumes 100vw and often downloads a much larger file than needed [1].\n\nFor an image shown at a fixed size, like a 64px avatar, use x descriptors instead and leave sizes out [2].", + cites: [ + { + docFile: "info1300-lecture-18-responsive-images.md", + phrase: "If you use w descriptors and leave out sizes", + reason: "Explains what happens without sizes", + }, + { + docFile: "info1300-lecture-18-responsive-images.md", + phrase: "density descriptors are simpler", + reason: "Covers density descriptors for fixed-size images", + }, + ], + }, + ], + }, + { + course: "AEM2210", + messages: [ + { + role: "user", + at: [-1, "19:05"], + content: "Is unearned revenue a liability or revenue?", + }, + { + role: "assistant", + at: [-1, "19:05"], + content: + "A liability. Cash received before the work is done is owed back to the customer as service, so it sits in Unearned Revenue until it's earned [1]. When part of it is earned, an adjusting entry moves that part: Dr. Unearned Revenue, Cr. Service Revenue [2].", + cites: [ + { + docFile: "aem2210-week-3-accrual-vs-cash.md", + phrase: "Cash received in advance is not revenue yet", + reason: "States that prepayments are a liability", + }, + { + docFile: "aem2210-week-4-journal-entries.md", + phrase: "Deferred revenue earned", + reason: "Gives the adjusting entry when the revenue is earned", + }, + ], + }, + ], + }, +]; diff --git a/scripts/seed-demo.ts b/scripts/seed-demo.ts new file mode 100644 index 00000000..cefba664 --- /dev/null +++ b/scripts/seed-demo.ts @@ -0,0 +1,1537 @@ +#!/usr/bin/env tsx +/** + * Demo account seed. + * + * Creates (or recreates) one demo user with three weeks of realistic, + * internally consistent study history placed relative to today, so + * screenshots and reviews never go stale: + * + * - 4 courses with exams 7, 17, 22 and 60 days out + * - 9 lecture notes run through the real upload and chunking pipeline + * - 4 plans; INFO 1300 has 6 sessions done, 1 missed yesterday, 1 today at + * 2:00 PM and 3 more before Prelim 2 + * - completed sessions replayed with the app's own rules: deck injection + * (pretest, review, repair questions), variant retries after misses, error + * logs that resolve after correct answers on 2 different days, SM-2 + * mastery, follow-ups, XP and plan completion + * - 2 flashcard decks with SM-2 review history and cards due today + * - 3 study guides, a short chat history with sources, and the achievements + * the app would have awarded for this activity + * + * Only the demo user's rows are deleted and recreated, so running it twice + * gives the same shape of data. It refuses to run unless the database name + * contains "demo" (or --force is passed), and never when NODE_ENV=production. + * + * Usage: + * DATABASE_URL=postgresql://postgres:postgres@localhost:5433/studybot_demo \ + * npx tsx scripts/seed-demo.ts [--force] [--verbose] + * + * Run it from the repository root: uploads are written under UPLOAD_DIR + * (default ./data/uploads), the same place the app reads them from. + */ +import { randomUUID } from "crypto"; +import { rm } from "fs/promises"; +import type { Prisma } from "../generated/prisma/client"; +import { + CHATS, + COURSES, + DECKS, + GUIDES, + type DemoCourse, + type DemoObjective, + type DemoQuestion, + type When, +} from "./seed-demo-content"; + +// --------------------------------------------------------------------------- +// Demo identity +// --------------------------------------------------------------------------- + +/** Fixed so the screenshot harness and test-auth header can rely on it. */ +const DEMO_USER_ID = "5eed0000-de70-4000-8000-000000000001"; +const DEMO_EMAIL = "demo@studybot.local"; +const DEMO_PASSWORD = "study-bot-demo"; +const DEMO_NAME = "Ben"; +const TZ = "America/New_York"; + +// --------------------------------------------------------------------------- +// Plans and session history +// --------------------------------------------------------------------------- + +type Mode = "RETRIEVAL" | "INTERLEAVED_PRACTICE" | "EXAM_SIM" | "ERROR_REPAIR" | "WORKED_EXAMPLES"; + +/** + * Outcome shorthand: score letter plus optional confidence. + * "C3" = correct, rated Unsure; "I5" = incorrect, rated Sure; "P" = partly + * correct, not rated. Confidence uses the app's 1 / 3 / 5 scale. + */ +type Outcome = string; + +interface RunSpec { + /** Question keys for the generated part of the deck, in deck order. */ + base: string[]; + /** Outcome per base question key (required for every base question used). */ + out: Record<string, Outcome>; + /** Pretest outcomes by objective code (default "P1"). */ + pretest?: Record<string, Outcome>; + /** Review question outcomes by objective code (default "C3"). */ + warmup?: Record<string, Outcome>; + /** Repair question outcomes by the source error's question key (default "C3"). */ + repair?: Record<string, Outcome>; + /** Retry question outcomes in order of appearance, by source question key (default "C3"). */ + variants?: Record<string, Outcome[]>; +} + +interface SessionSpec { + mode: Mode; + objs: string[]; + at: When; + minutes: number; + prompts: number; + type?: string; + status: "DONE" | "MISSED" | "SCHEDULED"; + missedMarkedAt?: When; + run?: RunSpec; +} + +interface PlanSpec { + course: keyof typeof COURSES; + created: When; + window: { start: string; end: string }; + chronotype: "morning" | "evening" | "flexible"; + sessions: SessionSpec[]; +} + +const PLANS: PlanSpec[] = [ + { + course: "INFO1300", + created: [-12, "09:05"], + window: { start: "14:00", end: "22:00" }, + chronotype: "evening", + sessions: [ + { + mode: "RETRIEVAL", objs: ["S", "B"], at: [-12, "16:00"], minutes: 30, prompts: 6, type: "diagnostic", status: "DONE", + run: { + base: ["s1", "b1", "s2", "b2", "s5", "b4"], + out: { s1: "C3", b1: "C5", s2: "I3", b2: "C" }, + pretest: { S: "P1", B: "C3" }, + variants: { s2: ["C3"] }, + }, + }, + { + mode: "RETRIEVAL", objs: ["F", "G"], at: [-10, "16:00"], minutes: 40, prompts: 8, status: "DONE", + run: { + base: ["f1", "g1", "f2", "g2", "f3", "g3", "f4", "g4"], + out: { f1: "C5", g1: "I3", f2: "C5", g2: "C3", f3: "C5", g3: "P1" }, + pretest: { F: "C3" }, + repair: { s2: "C3" }, + variants: { g1: ["C3"], g3: ["C3"] }, + }, + }, + { + mode: "INTERLEAVED_PRACTICE", objs: ["S", "B", "F", "G"], at: [-8, "16:30"], minutes: 40, prompts: 8, status: "DONE", + run: { + base: ["s3", "f4", "b3", "g4", "s4", "b4", "f2", "g5"], + out: { s3: "C5", f4: "C5", b3: "P3", g4: "C", s4: "I3", b4: "C5" }, + repair: { g1: "C3", g3: "C3" }, + variants: { b3: ["C3"], s4: ["I3", "C3"] }, + }, + }, + { + mode: "RETRIEVAL", objs: ["G"], at: [-4, "16:30"], minutes: 45, prompts: 10, status: "DONE", + run: { + base: ["g1", "g2", "g3", "g4", "g5", "g6", "g7"], + out: { g1: "C3", g2: "C3", g3: "I3", g4: "P3", g5: "C5", g6: "I1", g7: "I3" }, + repair: { s4: "C3", b3: "C3" }, + warmup: { S: "C3" }, + variants: { g3: ["C3"], g4: ["I3"], g6: ["C3"], g7: ["I3"] }, + }, + }, + { + mode: "RETRIEVAL", objs: ["R"], at: [-3, "16:00"], minutes: 30, prompts: 6, status: "DONE", + run: { + base: ["r1", "r2", "r3", "r4", "r5"], + out: { r1: "C", r2: "I3", r3: "I5", r4: "P3" }, + variants: { r2: ["C3"], r3: ["I3", "I3"], r4: ["C3"] }, + }, + }, + { + mode: "INTERLEAVED_PRACTICE", objs: ["S", "B", "F", "M"], at: [-2, "16:30"], minutes: 40, prompts: 8, status: "DONE", + run: { + base: ["s3", "m1", "b2", "s5", "f3", "m4", "b1", "m2"], + out: { s3: "I5", m1: "C3", b2: "C5", s5: "I5", f3: "C5", m4: "I1" }, + variants: { s3: ["I3", "C3"], s5: ["I3"], m4: ["C3"] }, + }, + }, + { + mode: "ERROR_REPAIR", objs: ["S", "B", "F", "G", "R", "M"], at: [-1, "16:00"], minutes: 30, prompts: 8, + status: "MISSED", missedMarkedAt: [-1, "21:15"], + }, + { mode: "RETRIEVAL", objs: ["S", "B"], at: [0, "14:00"], minutes: 40, prompts: 8, status: "SCHEDULED" }, + { mode: "INTERLEAVED_PRACTICE", objs: ["F", "G", "R", "M"], at: [2, "16:00"], minutes: 50, prompts: 10, status: "SCHEDULED" }, + { mode: "EXAM_SIM", objs: ["S", "B", "F", "G", "R", "M"], at: [4, "16:00"], minutes: 60, prompts: 12, status: "SCHEDULED" }, + { mode: "ERROR_REPAIR", objs: ["S", "B", "F", "G", "R", "M"], at: [6, "16:00"], minutes: 30, prompts: 8, status: "SCHEDULED" }, + ], + }, + { + course: "AEM2210", + created: [-7, "20:30"], + window: { start: "13:00", end: "21:00" }, + chronotype: "flexible", + sessions: [ + { + mode: "RETRIEVAL", objs: ["A", "RR"], at: [-6, "15:00"], minutes: 30, prompts: 6, type: "diagnostic", status: "DONE", + run: { + base: ["a1", "rr1", "a2", "rr2", "a3", "rr3"], + out: { a1: "C3", rr1: "I5", a2: "C5", rr2: "C3" }, + pretest: { A: "C3", RR: "P1" }, + variants: { rr1: ["C3"] }, + }, + }, + { + mode: "RETRIEVAL", objs: ["D", "J"], at: [-1, "15:00"], minutes: 30, prompts: 6, status: "DONE", + run: { + base: ["d1", "j1", "d2", "j2", "d3", "j3"], + out: { d1: "C", j1: "I3", d2: "C5", j2: "P3" }, + pretest: { D: "C3" }, + repair: { rr1: "C5" }, + variants: { j1: ["C3"], j2: ["I3", "C3"] }, + }, + }, + { mode: "WORKED_EXAMPLES", objs: ["J"], at: [1, "15:00"], minutes: 30, prompts: 8, status: "SCHEDULED" }, + { mode: "INTERLEAVED_PRACTICE", objs: ["A", "RR", "D", "J"], at: [5, "15:00"], minutes: 40, prompts: 10, status: "SCHEDULED" }, + { mode: "RETRIEVAL", objs: ["RR", "J"], at: [10, "15:00"], minutes: 30, prompts: 8, status: "SCHEDULED" }, + { mode: "EXAM_SIM", objs: ["A", "RR", "D", "J"], at: [15, "15:00"], minutes: 60, prompts: 12, status: "SCHEDULED" }, + ], + }, + { + course: "INFO4340", + created: [-10, "21:00"], + window: { start: "17:00", end: "23:00" }, + chronotype: "evening", + sessions: [ + { + mode: "RETRIEVAL", objs: ["C", "P"], at: [-9, "17:00"], minutes: 30, prompts: 6, type: "diagnostic", status: "DONE", + run: { + base: ["c1", "p1", "c2", "p2", "c3", "p3"], + out: { c1: "C3", p1: "I3", c2: "C5", p2: "C3" }, + pretest: { C: "C3", P: "P1" }, + variants: { p1: ["C3"] }, + }, + }, + { mode: "RETRIEVAL", objs: ["RF", "CW"], at: [3, "19:00"], minutes: 30, prompts: 6, status: "SCHEDULED" }, + { mode: "INTERLEAVED_PRACTICE", objs: ["C", "P", "RF", "CW"], at: [11, "19:00"], minutes: 40, prompts: 10, status: "SCHEDULED" }, + { mode: "EXAM_SIM", objs: ["C", "P", "RF", "CW"], at: [19, "19:00"], minutes: 60, prompts: 12, status: "SCHEDULED" }, + ], + }, + { + course: "ECON1110", + created: [-2, "13:05"], + window: { start: "10:00", end: "20:00" }, + chronotype: "morning", + sessions: [ + { mode: "RETRIEVAL", objs: ["SM", "EQ"], at: [5, "11:00"], minutes: 30, prompts: 6, type: "diagnostic", status: "SCHEDULED" }, + { mode: "RETRIEVAL", objs: ["EL"], at: [19, "11:00"], minutes: 30, prompts: 6, status: "SCHEDULED" }, + { mode: "INTERLEAVED_PRACTICE", objs: ["SM", "EQ", "EL"], at: [40, "11:00"], minutes: 40, prompts: 10, status: "SCHEDULED" }, + { mode: "EXAM_SIM", objs: ["SM", "EQ", "EL"], at: [55, "11:00"], minutes: 60, prompts: 12, status: "SCHEDULED" }, + ], + }, +]; + +// --------------------------------------------------------------------------- +// Small helpers +// --------------------------------------------------------------------------- + +function fail(message: string): never { + console.error(`seed-demo: ${message}`); + process.exit(1); +} + +/** Deterministic PRNG so answer times and card ratings repeat run to run. */ +function rngFor(seed: string): () => number { + let h = 1779033703 ^ seed.length; + for (let i = 0; i < seed.length; i++) { + h = Math.imul(h ^ seed.charCodeAt(i), 3432918353); + h = (h << 13) | (h >>> 19); + } + let a = h >>> 0; + return () => { + a = (a + 0x6d2b79f5) >>> 0; + let t = a; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +function parseOutcome(o: string): { s: "CORRECT" | "PARTIAL" | "INCORRECT"; conf: number | null } { + const letter = o[0]; + const s = letter === "C" ? "CORRECT" : letter === "P" ? "PARTIAL" : letter === "I" ? "INCORRECT" : null; + if (!s) throw new Error(`Bad outcome "${o}"`); + const c = o.slice(1); + const conf = c === "" ? null : Number(c); + if (conf !== null && ![1, 3, 5].includes(conf)) throw new Error(`Bad confidence in "${o}" (use 1, 3 or 5)`); + return { s, conf }; +} + +function json(value: unknown): Prisma.InputJsonValue { + return JSON.parse(JSON.stringify(value)) as Prisma.InputJsonValue; +} + +function checkSafety(): { dbName: string; host: string; verbose: boolean } { + const args = process.argv.slice(2); + const force = args.includes("--force"); + const verbose = args.includes("--verbose"); + if (process.env.NODE_ENV === "production") { + fail("refusing to run with NODE_ENV=production."); + } + const url = process.env.DATABASE_URL; + if (!url) { + fail( + "DATABASE_URL is not set. Point it at the demo database, for example\n" + + " DATABASE_URL=postgresql://postgres:postgres@localhost:5433/studybot_demo npx tsx scripts/seed-demo.ts", + ); + } + let parsed: URL; + try { + parsed = new URL(url); + } catch { + fail("DATABASE_URL is not a valid connection URL."); + } + const dbName = decodeURIComponent(parsed.pathname.replace(/^\//, "")); + if (!dbName.toLowerCase().includes("demo") && !force) { + fail( + `refusing to seed database "${dbName}" because its name doesn't contain "demo". ` + + "Pass --force to seed it anyway.", + ); + } + return { dbName, host: parsed.host, verbose }; +} + +// --------------------------------------------------------------------------- +// Main +// --------------------------------------------------------------------------- + +async function main() { + const { dbName, host, verbose } = checkSafety(); + + // The seed never needs a real AI provider: summaries and AI text are + // written here, and processing must not call out to OpenAI. + process.env.AI_PROVIDER = "mock"; + process.env.LOG_LEVEL ??= "warn"; + + console.log(`Seeding demo data into ${dbName} on ${host}`); + + // Imported after the safety checks so nothing touches the database first. + const { prisma } = await import("../src/lib/db"); + const bcrypt = (await import("bcryptjs")).default; + const { addDays, dayKey, daysBetween, zonedTimeToUtc } = await import("../src/lib/timezone"); + const { generateSessionId } = await import("../src/lib/session-id"); + const { slugifyObjectiveTitle } = await import("../src/lib/plan-generator"); + const { accuracyToQuality, confidenceAdjustedQuality, sm2Next, getMasterySummary } = await import("../src/lib/mastery"); + const { computeFollowups, followupsFromDueDates } = await import("../src/lib/spacing"); + const { generateVariantQuestion, MAX_VARIANTS_PER_SESSION } = await import("../src/lib/variant-questions"); + const { initBreakState } = await import("../src/lib/breaks"); + const { buildFeedbackQuery, searchChunks } = await import("../src/lib/search"); + const { resolveStoragePath } = await import("../src/lib/storage"); + const { prependBudget, pretestQuestionText, reviewQuestionText, crossSessionRepairText, humanizeObjectiveKey } = + await import("../src/services/run"); + const { uploadDocument, processDocument } = await import("../src/services/content"); + const { buildObjectiveAnchors } = await import("../src/services/anchors"); + const { computeSM2 } = await import("../src/services/spaced-repetition"); + const { XP_AMOUNTS, getGameState } = await import("../src/services/gamification"); + const { getStudyRecommendations } = await import("../src/services/study-recommendations"); + const { ALL_BADGES } = await import("../src/lib/badge-data"); + type Prompt = import("../src/lib/prompts").Prompt; + + const now = new Date(); + const todayKey = dayKey(now, TZ); + const at = (w: When): Date => zonedTimeToUtc(addDays(todayKey, w[0]), w[1], TZ); + const plusSeconds = (d: Date, s: number) => new Date(d.getTime() + s * 1000); + /** A calendar date as Prisma stores @db.Date columns (UTC midnight). */ + const calendarDate = (offset: number) => new Date(`${addDays(todayKey, offset)}T00:00:00.000Z`); + + // ------------------------------------------------------------------------- + // 1. Remove the previous demo user and everything that belongs to it + // ------------------------------------------------------------------------- + + const existing = await prisma.user.findMany({ + where: { OR: [{ id: DEMO_USER_ID }, { email: DEMO_EMAIL }] }, + select: { id: true }, + }); + const staleIds = Array.from(new Set([DEMO_USER_ID, ...existing.map((u) => u.id)])); + + await prisma.$transaction( + async (tx) => { + const userId = { in: staleIds }; + await tx.attemptCitation.deleteMany({ where: { attempt: { run: { userId } } } }); + await tx.sessionAttempt.deleteMany({ where: { run: { userId } } }); + await tx.sessionRunPrompt.deleteMany({ where: { run: { userId } } }); + await tx.sessionErrorLog.deleteMany({ where: { userId } }); + await tx.sessionRun.deleteMany({ where: { userId } }); + await tx.session.deleteMany({ where: { userId } }); + await tx.planItemExternalEvent.deleteMany({ where: { userId } }); + await tx.planCalendarPublication.deleteMany({ where: { userId } }); + await tx.studyPlanItem.deleteMany({ where: { plan: { userId } } }); + await tx.studyPlan.deleteMany({ where: { userId } }); + await tx.planReflowAudit.deleteMany({ where: { userId } }); + await tx.objectiveAnchor.deleteMany({ where: { userId } }); + await tx.cardReview.deleteMany({ where: { userId } }); + await tx.flashcard.deleteMany({ where: { deck: { userId } } }); + await tx.flashcardDeck.deleteMany({ where: { userId } }); + await tx.evidenceCard.deleteMany({ where: { paper: { userId } } }); + await tx.evidencePaper.deleteMany({ where: { userId } }); + await tx.contentChunk.deleteMany({ where: { document: { userId } } }); + await tx.contentDocument.deleteMany({ where: { userId } }); + await tx.objectiveMastery.deleteMany({ where: { userId } }); + await tx.studyGuide.deleteMany({ where: { userId } }); + await tx.xpEvent.deleteMany({ where: { userId } }); + await tx.achievement.deleteMany({ where: { userId } }); + await tx.userGameState.deleteMany({ where: { userId } }); + await tx.chatMessage.deleteMany({ where: { userId } }); + await tx.verificationToken.deleteMany({ where: { userId } }); + await tx.googleIntegration.deleteMany({ where: { userId } }); + await tx.oAuthState.deleteMany({ where: { userId } }); + await tx.aiCallLog.deleteMany({ where: { userId } }); + await tx.$executeRawUnsafe( + `DELETE FROM job_queue WHERE payload->>'userId' = ANY($1::text[])`, + staleIds, + ); + await tx.user.deleteMany({ where: { id: userId } }); + }, + { timeout: 60_000 }, + ); + for (const id of staleIds) { + // Uploaded files live under UPLOAD_DIR/<userId>/; resolveStoragePath keeps + // the path inside UPLOAD_DIR. + await rm(resolveStoragePath(id), { recursive: true, force: true }); + } + + // ------------------------------------------------------------------------- + // 2. User and settings + // ------------------------------------------------------------------------- + + const accountCreated = at([-22, "19:30"]); + await prisma.user.create({ + data: { + id: DEMO_USER_ID, + email: DEMO_EMAIL, + name: DEMO_NAME, + passwordHash: await bcrypt.hash(DEMO_PASSWORD, 12), + emailVerified: plusSeconds(accountCreated, 240), + createdAt: accountCreated, + updatedAt: accountCreated, + }, + }); + await prisma.userGameState.create({ + data: { + userId: DEMO_USER_ID, + dailyXpGoal: 50, + studyStartTime: "14:00", + studyEndTime: "22:00", + dailyStudyCap: 120, + onboardingComplete: true, + timezone: TZ, + createdAt: accountCreated, + updatedAt: plusSeconds(accountCreated, 600), + }, + }); + + // ------------------------------------------------------------------------- + // 3. Materials through the real upload and processing pipeline + // ------------------------------------------------------------------------- + + const docIdByFile = new Map<string, string>(); + for (const course of Object.values(COURSES)) { + for (const doc of course.docs) { + const upload = await uploadDocument( + DEMO_USER_ID, + "COURSE", + course.name, + course.exam, + doc.title, + doc.file, + "text/markdown", + Buffer.from(doc.body, "utf-8"), + ); + const processed = await processDocument(DEMO_USER_ID, upload.document_id); + if ("error" in processed || processed.data.status !== "PROCESSED") { + throw new Error(`Processing failed for ${doc.file}`); + } + const uploadedAt = at(doc.uploaded); + await prisma.contentDocument.update({ + where: { id: upload.document_id }, + data: { + summary: doc.summary, + suggestedQuestions: doc.questions, + createdAt: uploadedAt, + updatedAt: plusSeconds(uploadedAt, 20), + }, + }); + await prisma.contentChunk.updateMany({ + where: { documentId: upload.document_id }, + data: { createdAt: plusSeconds(uploadedAt, 5) }, + }); + docIdByFile.set(doc.file, upload.document_id); + } + } + // Processing queues embedding jobs. The demo runs on full-text search, so + // drop the jobs instead of leaving them for a worker that may hold a real + // OpenAI key, and record the chunks as not embedded. + await prisma.$executeRawUnsafe(`DELETE FROM job_queue WHERE payload->>'userId' = $1`, DEMO_USER_ID); + await prisma.contentChunk.updateMany({ + where: { document: { userId: DEMO_USER_ID } }, + data: { embeddingStatus: "NONE" }, + }); + + // ------------------------------------------------------------------------- + // 4. Replay the session history in memory with the app's rules + // ------------------------------------------------------------------------- + + interface ObjectiveInfo extends DemoObjective { + id: string; + } + const objectiveInfo = (course: DemoCourse, code: string): ObjectiveInfo => { + const o = course.objectives.find((x) => x.code === code); + if (!o) throw new Error(`Unknown objective ${code} in ${course.name}`); + return { ...o, id: slugifyObjectiveTitle(o.title) }; + }; + const questionByKey = (course: DemoCourse, key: string): DemoQuestion => { + const q = course.questions.find((x) => x.key === key); + if (!q) throw new Error(`Unknown question ${key} in ${course.name}`); + return q; + }; + + interface MasteryState { + courseName: string; + key: string; + easeFactor: number; + intervalDays: number; + repetitions: number; + lastAccuracy: number | null; + lastStudiedAt: Date | null; + nextDueAt: Date | null; + updatedAt: Date; + order: number; + } + interface ErrorState { + id: string; + runId: string; + promptIndex: number; + errorType: string; + correctionRule: string; + confidenceRating: number | null; + correctStreak: number; + lastCorrectAt: Date | null; + resolvedAt: Date | null; + resolvedByRunId: string | null; + createdAt: Date; + courseName: string; + qKey: string; + promptText: string; + } + interface PromptRow { + id: string; + runId: string; + promptIndex: number; + objectiveId: string | null; + text: string; + difficulty: number; + sourceType: string; + sourceRefId: string | null; + meta: Record<string, unknown> | null; + createdAt: Date; + prompt: Prompt; + /** Question key the prompt traces back to (base, repair source, or retry source). */ + srcKey: string | null; + kind: "BASE" | "PRE_TEST" | "WARMUP" | "CROSS_SESSION_REPAIR" | "VARIANT_REPAIR"; + } + interface AttemptRow { + id: string; + runId: string; + promptIndex: number; + promptId: string; + promptText: string; + userAnswer: string; + selfScore: string; + timeToAnswerSeconds: number; + confidenceRating: number | null; + createdAt: Date; + /** Feedback is written for misses on generated questions. */ + feedbackFor?: { question: DemoQuestion; objectiveId: string | null; course: DemoCourse; rule: string }; + } + interface RunMetrics { + attempts_count: number; + correct_count: number; + partial_count: number; + incorrect_count: number; + accuracy: number; + time_spent_seconds: number; + pretest_count?: number; + pretest_correct?: number; + recommended_followups?: unknown; + } + + const mastery = new Map<string, MasteryState>(); // `${course}||${key}` + const errors: ErrorState[] = []; + const sessionRows: Prisma.SessionCreateManyInput[] = []; + const planRows: Prisma.StudyPlanCreateManyInput[] = []; + const itemRows: Prisma.StudyPlanItemCreateManyInput[] = []; + const runRows: Prisma.SessionRunCreateManyInput[] = []; + const promptRows: PromptRow[] = []; + const attemptRows: AttemptRow[] = []; + const xpRows: Prisma.XpEventCreateManyInput[] = []; + const sessionIdByCourseDay = new Map<string, string>(); + let todaySession: { sessionId: string; course: string; time: Date } | null = null; + + // Schedule every DONE session across all plans in time order, since + // mastery, errors and repair questions carry across sessions of a course. + const allSessions: { plan: PlanSpec; spec: SessionSpec; sessionId: string; start: Date }[] = []; + + for (const plan of PLANS) { + const course = COURSES[plan.course]; + const created = at(plan.created); + const planId = generateSessionId(); + const startKey = dayKey(created, TZ); + const lastSession = plan.sessions[plan.sessions.length - 1]; + planRows.push({ + planId, + userId: DEMO_USER_ID, + courseId: "", + courseName: course.name, + examId: "", + examName: course.exam, + examDate: calendarDate(course.examOffset), + timezone: TZ, + startDate: created, + endDate: zonedTimeToUtc(addDays(todayKey, lastSession.at[0]), "23:59", TZ), + config: json({ + objectives: course.objectives.map((o) => o.title), + availability: Array.from({ length: 7 }, () => plan.window), + daily_study_cap_minutes: 120, + break_protocol_default: "50_10", + chronotype: plan.chronotype, + preferred_session_minutes: 45, + study_style: "balanced", + }), + createdAt: created, + updatedAt: created, + }); + + for (const spec of plan.sessions) { + const sessionId = generateSessionId(); + const objectives = spec.objs.map((c) => objectiveInfo(course, c)); + const start = at(spec.at); + sessionRows.push({ + sessionId, + userId: DEMO_USER_ID, + courseId: "", + courseName: course.name, + examId: "", + examName: course.exam, + mode: spec.mode, + topicScope: objectives.map((o) => o.title).join(", "), + objectives: json(objectives.map((o) => ({ id: o.id, title: o.title }))), + targetOutcome: json({ + ...(spec.type ? { type: spec.type } : {}), + prompt_count: spec.prompts, + target_accuracy: spec.mode === "EXAM_SIM" ? 0.7 : 0.8, + closed_book_required: spec.mode === "RETRIEVAL" || spec.mode === "EXAM_SIM", + }), + breakProtocol: json({ type: "50_10", cycles: 1 }), + plannedMinutes: spec.minutes, + createdAt: created, + updatedAt: created, + }); + itemRows.push({ + id: randomUUID(), + planId, + sessionId, + dayIndex: daysBetween(startKey, addDays(todayKey, spec.at[0])), + startTime: start, + endTime: plusSeconds(start, spec.minutes * 60), + status: spec.status === "MISSED" ? "MISSED" : "SCHEDULED", + missedAt: spec.missedMarkedAt ? at(spec.missedMarkedAt) : null, + createdAt: created, + }); + sessionIdByCourseDay.set(`${plan.course}|${spec.at[0]}`, sessionId); + if (spec.at[0] === 0 && spec.status === "SCHEDULED" && plan.course === "INFO1300") { + todaySession = { sessionId, course: course.name, time: start }; + } + if (spec.status === "DONE") allSessions.push({ plan, spec, sessionId, start }); + } + } + allSessions.sort((a, b) => a.start.getTime() - b.start.getTime()); + + const DAY_MS = 86_400_000; + + for (const { plan, spec, sessionId, start } of allSessions) { + const course = COURSES[plan.course]; + const run = spec.run; + if (!run) throw new Error(`DONE session without a run spec (${course.name} day ${spec.at[0]})`); + const rng = rngFor(`${plan.course}|${spec.at[0]}`); + const runId = generateSessionId(); + const objectives = spec.objs.map((c) => objectiveInfo(course, c)); + const objCodeById = new Map(course.objectives.map((o) => [slugifyObjectiveTitle(o.title), o.code])); + const objTitleById = new Map(course.objectives.map((o) => [slugifyObjectiveTitle(o.title), o.title])); + const examDate = calendarDate(course.examOffset); + const startedAt = plusSeconds(start, 60 + Math.floor(rng() * 120)); + + // Generated part of the deck (what the content-aware generator returns). + const basePrompts: { prompt: Prompt; q: DemoQuestion }[] = run.base.map((key, i) => { + const q = questionByKey(course, key); + const objectiveId = objectiveInfo(course, q.obj).id; + const prompt: Prompt = { + id: `p_${i}`, + objective_id: objectiveId, + text: q.text, + difficulty: q.difficulty, + format: q.mcq ? "MCQ" : "FREE_RECALL", + ...(q.mcq ? { choices: q.mcq.choices, correctIndex: q.mcq.correct } : {}), + meta: { + model_answer: q.model, + key_points: q.points, + ...(q.mcq ? { distractorRationales: q.mcq.rationales } : {}), + }, + }; + return { prompt, q }; + }); + + // Deck injection, mirroring startOrResumeRun: repair > pretest > review + // questions within the budget, ordered pretest, review, repair. + type Injected = { prompt: Prompt; kind: PromptRow["kind"]; srcKey: string | null }; + let ordered: Injected[] = []; + if (spec.mode !== "EXAM_SIM" && spec.mode !== "ERROR_REPAIR" && spec.mode !== "WORKED_EXAMPLES") { + const budget = prependBudget(spec.prompts); + if (budget > 0) { + const courseMastery = [...mastery.values()].filter((m) => m.courseName === course.name); + const masteredKeys = new Set(courseMastery.map((m) => m.key)); + const pretests: Injected[] = objectives + .filter((o) => !masteredKeys.has(o.id)) + .slice(0, 2) + .map((o, i) => ({ + kind: "PRE_TEST", + srcKey: o.code, + prompt: { + id: `pretest_${i}`, + objective_id: o.id, + text: pretestQuestionText(o.title), + difficulty: 2, + meta: { pack: "PRE_TEST" }, + }, + })); + const warmups: Injected[] = courseMastery + .filter((m) => m.nextDueAt && m.nextDueAt <= startedAt) + .sort((a, b) => a.nextDueAt!.getTime() - b.nextDueAt!.getTime() || a.order - b.order) + .slice(0, 5) + .slice(0, 3) + .map((m, i) => { + const daysSince = m.lastStudiedAt + ? Math.floor((startedAt.getTime() - m.lastStudiedAt.getTime()) / DAY_MS) + : null; + // Same lookup order as generateWarmupPrompts: the course's own + // topic title, and only then the key made readable. + const title = objTitleById.get(m.key) ?? humanizeObjectiveKey(m.key); + return { + kind: "WARMUP", + srcKey: objCodeById.get(m.key) ?? m.key, + prompt: { + id: `warmup_${i}`, + objective_id: m.key, + text: reviewQuestionText(title, daysSince), + difficulty: Math.min(m.repetitions + 1, 3), + meta: { pack: "WARMUP" }, + }, + }; + }); + const repairs: Injected[] = errors + .filter((e) => e.courseName === course.name && !e.resolvedAt) + .sort( + (a, b) => + (b.confidenceRating ?? -1) - (a.confidenceRating ?? -1) || + b.createdAt.getTime() - a.createdAt.getTime(), + ) + .slice(0, 4) + .slice(0, 2) + .map((e, i) => { + const daysSince = Math.floor((startedAt.getTime() - e.createdAt.getTime()) / DAY_MS); + return { + kind: "CROSS_SESSION_REPAIR", + srcKey: e.qKey, + prompt: { + id: `repair_${i}`, + objective_id: undefined, + text: crossSessionRepairText({ daysSince, originalText: e.promptText }), + difficulty: 2, + meta: { + pack: "CROSS_SESSION_REPAIR", + source_error_log_id: e.id, + original_prompt_text: e.promptText, + expected_correction_rule: e.correctionRule, + }, + }, + }; + }); + const selected: Injected[] = []; + for (const list of [repairs, pretests, warmups]) { + for (const p of list) if (selected.length < budget) selected.push(p); + } + ordered = [ + ...selected.filter((p) => p.kind === "PRE_TEST"), + ...selected.filter((p) => p.kind === "WARMUP"), + ...selected.filter((p) => p.kind === "CROSS_SESSION_REPAIR"), + ]; + } + } + const remainder = Math.max(1, spec.prompts - ordered.length); + if (basePrompts.length < remainder) { + throw new Error( + `${course.name} day ${spec.at[0]}: deck needs ${remainder} generated questions but the spec lists ${basePrompts.length}`, + ); + } + const deck: Injected[] = [ + ...ordered, + ...basePrompts.slice(0, remainder).map((b) => ({ prompt: b.prompt, kind: "BASE" as const, srcKey: b.q.key })), + ]; + + const rows: PromptRow[] = deck.map((d, i) => { + const p = d.prompt; + const storedMeta: Record<string, unknown> = p.meta ? { ...p.meta } : {}; + if (p.format === "MCQ" && p.choices && p.correctIndex != null) { + storedMeta.format = p.format; + storedMeta.choices = p.choices; + storedMeta.correctIndex = p.correctIndex; + } + return { + id: randomUUID(), + runId, + promptIndex: i, + objectiveId: p.objective_id ?? null, + text: p.text, + difficulty: p.difficulty ?? 1, + sourceType: p.meta?.source_error_log_id ? "ERROR_LOG" : "GENERATED", + sourceRefId: p.meta?.source_error_log_id ?? null, + meta: Object.keys(storedMeta).length > 0 ? storedMeta : null, + createdAt: startedAt, + prompt: p, + srcKey: d.srcKey, + kind: d.kind, + }; + }); + + // Answer the deck in order. Misses inject retry questions at the end. + const metrics: RunMetrics = { + attempts_count: 0, + correct_count: 0, + partial_count: 0, + incorrect_count: 0, + accuracy: 0, + time_spent_seconds: 0, + }; + const variantSeen = new Map<string, number>(); + const runAttempts: AttemptRow[] = []; + let t = startedAt; + let variantCount = 0; + const trace: string[] = []; + + for (let idx = 0; idx < rows.length; idx++) { + const row = rows[idx]; + const p = row.prompt; + const srcKey = row.srcKey ?? ""; + let outcomeCode: string; + switch (row.kind) { + case "BASE": + outcomeCode = run.out[srcKey] ?? fail(`${course.name} day ${spec.at[0]}: no outcome for question ${srcKey}`); + break; + case "PRE_TEST": + outcomeCode = run.pretest?.[srcKey] ?? "P1"; + break; + case "WARMUP": + outcomeCode = run.warmup?.[srcKey] ?? "C3"; + break; + case "CROSS_SESSION_REPAIR": + outcomeCode = run.repair?.[srcKey] ?? "C3"; + break; + case "VARIANT_REPAIR": { + const n = variantSeen.get(srcKey) ?? 0; + variantSeen.set(srcKey, n + 1); + outcomeCode = run.variants?.[srcKey]?.[n] ?? "C3"; + break; + } + } + const outcome = parseOutcome(outcomeCode); + const q = srcKey && row.kind !== "PRE_TEST" && row.kind !== "WARMUP" ? questionByKey(course, srcKey) : null; + const isMcq = row.kind === "BASE" && !!q?.mcq; + let score = outcome.s; + if (isMcq && score === "PARTIAL") score = "INCORRECT"; + const correct = score === "CORRECT"; + + // Answer text and timing + let userAnswer: string; + let seconds: number; + if (row.kind === "PRE_TEST" || row.kind === "WARMUP") { + const obj = objectiveInfo(course, srcKey); + userAnswer = correct ? obj.recall : obj.weak; + seconds = 35 + Math.floor(rng() * 60); + } else if (isMcq && q?.mcq) { + const choice = correct ? q.mcq.correct : q.mcq.trap; + userAnswer = `[${String.fromCharCode(65 + choice)}] ${q.mcq.choices[choice]}`; + seconds = 12 + Math.floor(rng() * 35); + } else { + userAnswer = correct ? q!.good : score === "PARTIAL" ? q!.partial ?? q!.bad : q!.bad; + seconds = 40 + Math.floor(rng() * (40 + 25 * (q?.difficulty ?? 2))); + } + t = plusSeconds(t, seconds + 8 + Math.floor(rng() * 20)); + + const attemptId = randomUUID(); + const attempt: AttemptRow = { + id: attemptId, + runId, + promptIndex: row.promptIndex, + promptId: row.id, + promptText: p.text, + userAnswer, + selfScore: score, + timeToAnswerSeconds: seconds, + confidenceRating: outcome.conf, + createdAt: t, + }; + + // Metrics (pretest questions are tracked apart from accuracy) + const isPretest = row.kind === "PRE_TEST"; + metrics.time_spent_seconds += seconds; + if (isPretest) { + metrics.pretest_count = (metrics.pretest_count ?? 0) + 1; + metrics.pretest_correct = (metrics.pretest_correct ?? 0) + (correct ? 1 : 0); + } else { + metrics.attempts_count += 1; + metrics.correct_count += correct ? 1 : 0; + metrics.partial_count += score === "PARTIAL" ? 1 : 0; + metrics.incorrect_count += score === "INCORRECT" ? 1 : 0; + metrics.accuracy = metrics.correct_count / metrics.attempts_count; + } + + // Error log for a miss on a generated question + const sourceErrorLogId = p.meta?.source_error_log_id; + let errorLog: { type: string; rule: string } | undefined; + let newErrorId: string | undefined; + if (!correct && !isPretest && row.kind === "BASE" && q) { + if (isMcq && q.mcq) { + const rationale = q.mcq.rationales[q.mcq.trap]; + errorLog = { + type: "MISCONCEPTION", + rule: `The correct answer is "${q.mcq.choices[q.mcq.correct]}".${rationale ? ` Common trap: ${rationale}` : ""}`, + }; + } else { + errorLog = { type: q.errorType, rule: q.rule }; + } + newErrorId = randomUUID(); + errors.push({ + id: newErrorId, + runId, + promptIndex: row.promptIndex, + errorType: errorLog.type, + correctionRule: errorLog.rule, + confidenceRating: outcome.conf, + correctStreak: 0, + lastCorrectAt: null, + resolvedAt: null, + resolvedByRunId: null, + createdAt: t, + courseName: course.name, + qKey: q.key, + promptText: p.text, + }); + attempt.feedbackFor = { question: q, objectiveId: row.objectiveId, course, rule: errorLog.rule }; + } + + // Successive relearning: a source error resolves after correct answers + // on 2 different days; a miss resets the streak. + if (sourceErrorLogId && !isPretest) { + const src = errors.find((e) => e.id === sourceErrorLogId); + if (src && !src.resolvedAt) { + if (correct) { + const today = dayKey(t, TZ); + const lastDay = src.lastCorrectAt ? dayKey(src.lastCorrectAt, TZ) : null; + if (lastDay !== today) { + src.correctStreak += 1; + src.lastCorrectAt = t; + if (src.correctStreak >= 2) { + src.resolvedAt = t; + src.resolvedByRunId = runId; + } + } + } else { + src.correctStreak = 0; + } + } + } + + // In-session retry question after a miss + if (!correct && (errorLog || sourceErrorLogId) && !isPretest && spec.mode !== "ERROR_REPAIR") { + if (variantCount < MAX_VARIANTS_PER_SESSION) { + const repairSourceId = sourceErrorLogId ?? newErrorId; + const sourceText = + isMcq && q?.mcq + ? `${p.text} (Correct answer: "${q.mcq.choices[q.mcq.correct]}"; you chose "${q.mcq.choices[q.mcq.trap]}")` + : p.text; + const promptIndex = rows.length; + const variant = generateVariantQuestion( + promptIndex, + sourceText, + errorLog?.type ?? "MISCONCEPTION", + errorLog?.rule ?? p.meta?.expected_correction_rule ?? "", + p.objective_id, + repairSourceId, + ); + rows.push({ + id: randomUUID(), + runId, + promptIndex, + objectiveId: variant.objective_id ?? null, + text: variant.text, + difficulty: variant.difficulty, + sourceType: "VARIANT_REPAIR", + sourceRefId: repairSourceId ?? null, + meta: (variant.meta as Record<string, unknown>) ?? null, + createdAt: t, + prompt: variant, + srcKey: srcKey || null, + kind: "VARIANT_REPAIR", + }); + variantCount += 1; + } + } + + runAttempts.push(attempt); + trace.push(`${row.promptIndex}:${row.kind === "BASE" ? srcKey : `${row.kind}(${srcKey})`}=${score[0]}${outcome.conf ?? "-"}`); + } + + const endedAt = plusSeconds(t, 15); + + // SM-2 mastery per objective, as updateObjectiveMastery does it + const byObjective = new Map<string, { correct: number; total: number; confSum: number; confCount: number }>(); + for (const a of runAttempts) { + const row = rows[a.promptIndex]; + if (!row.objectiveId || row.kind === "PRE_TEST") continue; + const e = byObjective.get(row.objectiveId) ?? { correct: 0, total: 0, confSum: 0, confCount: 0 }; + e.total += 1; + if (a.selfScore === "CORRECT") e.correct += 1; + if (a.confidenceRating != null) { + e.confSum += a.confidenceRating; + e.confCount += 1; + } + byObjective.set(row.objectiveId, e); + } + for (const [key, e] of byObjective) { + const mapKey = `${course.name}||${key}`; + const current = mastery.get(mapKey); + const accuracy = e.total > 0 ? e.correct / e.total : 0; + const avgConfidence = e.confCount > 0 ? e.confSum / e.confCount : null; + const quality = confidenceAdjustedQuality(accuracyToQuality(accuracy), accuracy, avgConfidence); + const next = sm2Next( + current + ? { easeFactor: current.easeFactor, intervalDays: current.intervalDays, repetitions: current.repetitions } + : { easeFactor: 2.5, intervalDays: 0, repetitions: 0 }, + quality, + endedAt, + examDate, + ); + mastery.set(mapKey, { + courseName: course.name, + key, + easeFactor: next.easeFactor, + intervalDays: next.intervalDays, + repetitions: next.repetitions, + lastAccuracy: accuracy, + lastStudiedAt: endedAt, + nextDueAt: next.nextDueAt, + updatedAt: endedAt, + order: current?.order ?? mastery.size, + }); + } + + // Follow-ups come from the SM-2 due dates, else the fixed ladder + const dueDates = [...mastery.values()] + .filter((m) => m.courseName === course.name && m.nextDueAt) + .sort((a, b) => a.nextDueAt!.getTime() - b.nextDueAt!.getTime()) + .slice(0, 3) + .map((m) => m.nextDueAt!); + const followups = followupsFromDueDates(dueDates, endedAt); + const finalMetrics: RunMetrics = { + ...metrics, + recommended_followups: followups.length > 0 ? followups : computeFollowups(metrics.accuracy, endedAt), + }; + + const breakState = initBreakState({ type: "50_10", cycles: 1 }); + runRows.push({ + runId, + sessionId, + userId: DEMO_USER_ID, + mode: spec.mode, + phase: "COMPLETE", + status: "COMPLETED", + startedAt, + endedAt, + currentIndex: rows.length, + promptCount: rows.length, + answeredCount: null, + scoredCount: null, + prompts: json(deck.map((d) => d.prompt)), + policies: json({ + scoring: "IMMEDIATE", + requiresErrorLogOn: ["PARTIAL", "INCORRECT"], + allowHintsBeforeAnswer: false, + allowEndBreakEarly: true, + }), + metrics: json(finalMetrics), + breakState: json({ ...breakState, work_started_at: startedAt.toISOString() }), + createdAt: startedAt, + updatedAt: endedAt, + }); + promptRows.push(...rows); + attemptRows.push(...runAttempts); + xpRows.push({ + userId: DEMO_USER_ID, + action: "SESSION_COMPLETED", + xpAmount: XP_AMOUNTS.SESSION_COMPLETED, + sourceId: runId, + createdAt: plusSeconds(endedAt, 1), + }); + const item = itemRows.find((i) => i.sessionId === sessionId)!; + item.status = "DONE"; + item.completedRunId = runId; + item.completedAt = plusSeconds(endedAt, 1); + + if (verbose) { + const perObjective = [...byObjective.entries()] + .map(([k, e]) => `${k} ${e.correct}/${e.total}`) + .join(", "); + console.log( + ` ${course.name} ${addDays(todayKey, spec.at[0])} ${spec.mode}: ${trace.join(" ")}\n` + + ` accuracy ${Math.round(metrics.accuracy * 100)}% | ${perObjective}`, + ); + } + } + + // ------------------------------------------------------------------------- + // 5. Persist sessions, plans and history + // ------------------------------------------------------------------------- + + await prisma.session.createMany({ data: sessionRows }); + await prisma.studyPlan.createMany({ data: planRows }); + await prisma.studyPlanItem.createMany({ data: itemRows }); + await prisma.sessionRun.createMany({ data: runRows }); + await prisma.sessionRunPrompt.createMany({ + data: promptRows.map((r) => ({ + id: r.id, + runId: r.runId, + promptIndex: r.promptIndex, + objectiveId: r.objectiveId, + text: r.text, + difficulty: r.difficulty, + sourceType: r.sourceType, + sourceRefId: r.sourceRefId, + meta: r.meta ? json(r.meta) : undefined, + createdAt: r.createdAt, + })), + }); + await prisma.sessionAttempt.createMany({ + data: attemptRows.map((a) => ({ + id: a.id, + runId: a.runId, + promptIndex: a.promptIndex, + promptId: a.promptId, + promptText: a.promptText, + userAnswer: a.userAnswer, + selfScore: a.selfScore, + timeToAnswerSeconds: a.timeToAnswerSeconds, + confidenceRating: a.confidenceRating, + createdAt: a.createdAt, + })), + }); + await prisma.sessionErrorLog.createMany({ + data: errors.map((e) => ({ + id: e.id, + runId: e.runId, + userId: DEMO_USER_ID, + promptIndex: e.promptIndex, + errorType: e.errorType, + correctionRule: e.correctionRule, + confidenceRating: e.confidenceRating, + correctStreak: e.correctStreak, + lastCorrectAt: e.lastCorrectAt, + resolvedAt: e.resolvedAt, + resolvedByRunId: e.resolvedByRunId, + createdAt: e.createdAt, + })), + }); + await prisma.objectiveMastery.createMany({ + data: [...mastery.values()].map((m) => ({ + userId: DEMO_USER_ID, + courseName: m.courseName, + objectiveKey: m.key, + easeFactor: m.easeFactor, + intervalDays: m.intervalDays, + repetitions: m.repetitions, + lastAccuracy: m.lastAccuracy, + lastStudiedAt: m.lastStudiedAt, + nextDueAt: m.nextDueAt, + updatedAt: m.updatedAt, + })), + }); + + // Objective anchors through the real service (full-text search per topic), + // as plan creation does. + for (const course of Object.values(COURSES)) { + await buildObjectiveAnchors( + DEMO_USER_ID, + course.name, + course.exam, + course.objectives.map((o) => ({ id: slugifyObjectiveTitle(o.title), title: o.title })), + ); + } + + // Stored feedback for misses: numbered sources from the anchors (or a + // full-text fallback), the AI explanation, and the citation rows. + let feedbackCount = 0; + for (const a of attemptRows) { + if (!a.feedbackFor) continue; + const { question, objectiveId, course, rule } = a.feedbackFor; + let sources: { chunk_id: string; doc_title: string; page_number: number | null; snippet: string }[] = []; + if (objectiveId) { + const anchors = await prisma.objectiveAnchor.findMany({ + where: { userId: DEMO_USER_ID, courseName: course.name, examName: course.exam, objectiveId }, + orderBy: { rank: "asc" }, + take: 5, + include: { chunk: { include: { document: { select: { title: true } } } } }, + }); + sources = anchors.map((x) => ({ + chunk_id: x.chunkId, + doc_title: x.chunk.document.title, + page_number: x.chunk.pageNumber, + snippet: x.chunk.text.slice(0, 300), + })); + } + if (sources.length === 0) { + const objective = course.objectives.find((o) => o.code === question.obj); + sources = await searchChunks({ + userId: DEMO_USER_ID, + q: buildFeedbackQuery(a.promptText, rule, objective?.title), + namespace: "COURSE", + courseName: course.name, + examName: course.exam, + topK: 5, + }); + } + const excerpts = sources.map((s, i) => ({ ...s, rank: i + 1 })); + await prisma.sessionAttempt.update({ + where: { id: a.id }, + data: { + feedbackStatus: "READY", + feedbackJson: json({ + status: "OK", + excerpts, + ...(excerpts.length === 0 ? { no_sources: true } : {}), + explanation: question.explain, + key_takeaway: rule, + }), + }, + }); + if (excerpts.length > 0) { + await prisma.attemptCitation.createMany({ + data: excerpts.map((x) => ({ + attemptId: a.id, + chunkId: x.chunk_id, + rank: x.rank, + snippet: x.snippet, + createdAt: a.createdAt, + })), + }); + } + feedbackCount += 1; + } + + // ------------------------------------------------------------------------- + // 6. Flashcards with SM-2 review history + // ------------------------------------------------------------------------- + + let reviewCount = 0; + const dueByDeck: { title: string; due: number; total: number }[] = []; + for (const deck of DECKS) { + const course = COURSES[deck.course]; + const created = at(deck.created); + const deckId = randomUUID(); + await prisma.flashcardDeck.create({ + data: { + id: deckId, + userId: DEMO_USER_ID, + courseName: course.name, + examName: course.exam, + documentId: docIdByFile.get(deck.docFile) ?? null, + title: deck.title, + cardCount: deck.cards.length, + createdAt: created, + }, + }); + const cards = deck.cards.map((c, i) => ({ + ...c, + id: randomUUID(), + ordinal: i, + easeFactor: 2.5, + intervalDays: 0, + repetitions: 0, + nextDueAt: null as Date | null, + introduced: false, + })); + const reviews: Prisma.CardReviewCreateManyInput[] = []; + const rng = rngFor(`deck|${deck.title}`); + const rate = (hardness: number): "AGAIN" | "HARD" | "GOOD" | "EASY" => { + const r = rng(); + if (r < 0.3 * hardness) return "AGAIN"; + if (r < 0.65 * hardness) return "HARD"; + if (hardness < 0.35 && r > 0.8) return "EASY"; + return "GOOD"; + }; + const review = (card: (typeof cards)[number], rating: "AGAIN" | "HARD" | "GOOD" | "EASY", when: Date) => { + const next = computeSM2(card.easeFactor, card.intervalDays, card.repetitions, rating); + card.easeFactor = next.easeFactor; + card.intervalDays = next.intervalDays; + card.repetitions = next.repetitions; + if (next.intervalDays === 0) { + card.nextDueAt = new Date(when.getTime() + 10 * 60_000); + } else { + // Same rule as computeSM2, anchored at the review time: due at 4am + // (server local time) the given number of days later. + const due = new Date(when); + due.setDate(due.getDate() + next.intervalDays); + due.setHours(4, 0, 0, 0); + card.nextDueAt = due; + } + reviews.push({ + cardId: card.id, + userId: DEMO_USER_ID, + rating, + easeFactor: next.easeFactor, + intervalDays: next.intervalDays, + repetitions: next.repetitions, + createdAt: when, + }); + xpRows.push({ + userId: DEMO_USER_ID, + action: "FLASHCARD_REVIEW", + xpAmount: XP_AMOUNTS.FLASHCARD_REVIEW, + sourceId: card.id, + createdAt: when, + }); + }; + + for (const s of deck.sessions) { + let when = at(s.at); + const due = cards + .filter((c) => c.introduced && c.nextDueAt && c.nextDueAt <= when) + .sort((a, b) => a.nextDueAt!.getTime() - b.nextDueAt!.getTime()) + .slice(0, s.maxDue); + const fresh = cards.filter((c) => !c.introduced).slice(0, s.newCards); + // Never review a whole deck in one day: the app would award a perfect + // deck bonus (and an achievement) that this history doesn't include. + const queue = [...due, ...fresh].slice(0, cards.length - 1); + const again: typeof cards = []; + for (const card of queue) { + card.introduced = true; + const rating = rate(card.hardness); + review(card, rating, when); + if (rating === "AGAIN") again.push(card); + when = plusSeconds(when, 15 + Math.floor(rng() * 25)); + } + for (const card of again) { + review(card, rng() < 0.6 ? "GOOD" : "HARD", when); + when = plusSeconds(when, 15 + Math.floor(rng() * 20)); + } + } + + await prisma.flashcard.createMany({ + data: cards.map((c) => ({ + id: c.id, + deckId, + front: c.front, + back: c.back, + tags: c.tags, + ordinal: c.ordinal, + easeFactor: c.easeFactor, + intervalDays: c.intervalDays, + repetitions: c.repetitions, + nextDueAt: c.nextDueAt, + createdAt: created, + })), + }); + await prisma.cardReview.createMany({ data: reviews }); + reviewCount += reviews.length; + dueByDeck.push({ + title: deck.title, + due: cards.filter((c) => (c.nextDueAt ? c.nextDueAt <= now : c.repetitions === 0)).length, + total: cards.length, + }); + } + + await prisma.xpEvent.createMany({ data: xpRows }); + + // ------------------------------------------------------------------------- + // 7. Study guides and chat + // ------------------------------------------------------------------------- + + for (const g of GUIDES) { + const course = COURSES[g.course]; + const created = at(g.created); + await prisma.studyGuide.create({ + data: { + userId: DEMO_USER_ID, + courseName: course.name, + examName: course.exam, + guideType: g.type, + title: g.title, + content: json(g.sections), + createdAt: created, + updatedAt: created, + }, + }); + } + + let chatCount = 0; + for (const chat of CHATS) { + const course = COURSES[chat.course]; + const courseKey = `${course.name}||${course.exam}`; + let offset = 0; + for (const m of chat.messages) { + let citations: { chunk_id: string; reason: string; quote_snippet: string }[] | undefined; + if (m.cites) { + citations = []; + for (const c of m.cites) { + const documentId = docIdByFile.get(c.docFile); + const chunk = documentId + ? await prisma.contentChunk.findFirst({ where: { documentId, text: { contains: c.phrase } } }) + : null; + if (!chunk) throw new Error(`Chat citation not found: "${c.phrase}" in ${c.docFile}`); + const start = chunk.text.indexOf(c.phrase); + const end = chunk.text.indexOf(".", start + c.phrase.length); + const quote = chunk.text.slice(start, end > 0 ? Math.min(end + 1, start + 240) : start + 200); + citations.push({ chunk_id: chunk.id, reason: c.reason, quote_snippet: quote }); + } + } + // Assistant replies land a few seconds after the question. + offset = m.role === "assistant" ? offset + 6 : 0; + await prisma.chatMessage.create({ + data: { + userId: DEMO_USER_ID, + courseKey, + role: m.role, + content: m.content, + citations: citations ? json(citations) : undefined, + createdAt: plusSeconds(at(m.at), offset), + }, + }); + chatCount += 1; + } + } + + // ------------------------------------------------------------------------- + // 8. Achievements the app would have awarded for this activity + // ------------------------------------------------------------------------- + + const events = [...xpRows].sort((a, b) => (a.createdAt as Date).getTime() - (b.createdAt as Date).getTime()); + const activeDays = new Set<string>(); + const earned = new Map<string, Date>(); + let totalXp = 0; + let reviews = 0; + for (const e of events) { + const when = e.createdAt as Date; + const day = dayKey(when, TZ); + activeDays.add(day); + totalXp += e.xpAmount; + if (e.action === "FLASHCARD_REVIEW") reviews += 1; + let streak = 0; + for (let d = day; activeDays.has(d); d = addDays(d, -1)) streak += 1; + for (const badge of ALL_BADGES) { + if (earned.has(badge.key) || badge.key === "FIRST_PERFECT") continue; + const value = badge.category === "streak" ? streak : badge.category === "xp" ? totalXp : reviews; + if (value >= badge.threshold) earned.set(badge.key, when); + } + } + await prisma.achievement.createMany({ + data: [...earned.entries()].map(([badgeType, earnedAt]) => ({ userId: DEMO_USER_ID, badgeType, earnedAt })), + }); + + // ------------------------------------------------------------------------- + // 9. Check the result through the app's own read paths and report + // ------------------------------------------------------------------------- + + const game = await getGameState(DEMO_USER_ID); + if (game.newAchievements.length > 0) { + console.warn(` warning: the app awarded extra achievements on read: ${game.newAchievements.join(", ")}`); + } + const recs = await getStudyRecommendations(DEMO_USER_ID, COURSES.INFO1300.name); + const masterySummary = await getMasterySummary(DEMO_USER_ID, COURSES.INFO1300.name); + + const counts = { + documents: await prisma.contentDocument.count({ where: { userId: DEMO_USER_ID } }), + chunks: await prisma.contentChunk.count({ where: { document: { userId: DEMO_USER_ID } } }), + plans: await prisma.studyPlan.count({ where: { userId: DEMO_USER_ID } }), + planItems: await prisma.studyPlanItem.count({ where: { plan: { userId: DEMO_USER_ID } } }), + sessions: await prisma.session.count({ where: { userId: DEMO_USER_ID } }), + completedRuns: await prisma.sessionRun.count({ where: { userId: DEMO_USER_ID } }), + questions: await prisma.sessionRunPrompt.count({ where: { run: { userId: DEMO_USER_ID } } }), + attempts: await prisma.sessionAttempt.count({ where: { run: { userId: DEMO_USER_ID } } }), + citations: await prisma.attemptCitation.count({ where: { attempt: { run: { userId: DEMO_USER_ID } } } }), + errorLogs: await prisma.sessionErrorLog.count({ where: { userId: DEMO_USER_ID } }), + unresolvedErrors: await prisma.sessionErrorLog.count({ where: { userId: DEMO_USER_ID, resolvedAt: null } }), + masteryRows: await prisma.objectiveMastery.count({ where: { userId: DEMO_USER_ID } }), + anchors: await prisma.objectiveAnchor.count({ where: { userId: DEMO_USER_ID } }), + decks: await prisma.flashcardDeck.count({ where: { userId: DEMO_USER_ID } }), + cards: await prisma.flashcard.count({ where: { deck: { userId: DEMO_USER_ID } } }), + cardReviews: await prisma.cardReview.count({ where: { userId: DEMO_USER_ID } }), + guides: await prisma.studyGuide.count({ where: { userId: DEMO_USER_ID } }), + chatMessages: await prisma.chatMessage.count({ where: { userId: DEMO_USER_ID } }), + xpEvents: await prisma.xpEvent.count({ where: { userId: DEMO_USER_ID } }), + achievements: await prisma.achievement.count({ where: { userId: DEMO_USER_ID } }), + }; + + const pct = (v: number | null) => (v == null ? "n/a" : `${Math.round(v * 100)}%`); + console.log(""); + console.log("Demo data ready"); + console.log(` Sign in: ${DEMO_EMAIL} / ${DEMO_PASSWORD}`); + console.log(` User id: ${DEMO_USER_ID}`); + console.log(` Today: ${todayKey} (${TZ})`); + if (todaySession) { + console.log(` Today's session: /s/${todaySession.sessionId} (${todaySession.course}, 2:00 PM)`); + } + console.log(""); + console.log(" Counts"); + for (const [k, v] of Object.entries(counts)) console.log(` ${k.padEnd(18)} ${v}`); + console.log(` feedback stored ${feedbackCount}`); + console.log(` chat inserted ${chatCount}`); + console.log(""); + console.log(" Progress (read back through the app's services)"); + console.log(` streak ${game.streak} days, ${game.xpTotal} XP total, ${game.xpToday} XP today, ${game.reviewCount} card reviews`); + console.log(` achievements: ${game.achievements.map((x) => x.badgeType).join(", ")}`); + console.log(` INFO 1300 recommendation: ${recs.next_session.mode}, ${recs.unresolved_errors.count} unresolved errors, plan nudge ${recs.plan_nudge ? "yes" : "no"}`); + console.log( + ` INFO 1300 mastery: ${masterySummary.objectives + .map((o) => `${o.objective_key} ${pct(o.last_accuracy)}${o.is_due ? " (due)" : ""}`) + .join(", ")}`, + ); + for (const d of dueByDeck) console.log(` deck "${d.title}": ${d.due} of ${d.total} cards due now`); + console.log(` total card reviews seeded: ${reviewCount}`); + + await prisma.$disconnect(); +} + +main().catch(async (err) => { + console.error(err); + try { + const { prisma } = await import("../src/lib/db"); + await prisma.$disconnect(); + } catch { + // ignore + } + process.exit(1); +}); diff --git a/scripts/seed-research.ts b/scripts/seed-research.ts index c87846b0..8443b690 100644 --- a/scripts/seed-research.ts +++ b/scripts/seed-research.ts @@ -10,7 +10,11 @@ * decisions (spacing, interleaving, retrieval practice timing, etc.) * * Usage: npx tsx scripts/seed-research.ts + * + * tsx does not read .env the way Next does, so it is loaded first. Variables + * already set in the environment win over .env values. */ +import "dotenv/config"; import { prisma } from "../src/lib/db"; import { sha256 } from "../src/lib/storage"; import { enqueueJob } from "../src/lib/jobs/queue"; diff --git a/scripts/setup.mjs b/scripts/setup.mjs index dab1dc54..a4fd5a58 100644 --- a/scripts/setup.mjs +++ b/scripts/setup.mjs @@ -10,7 +10,8 @@ * are empty (user-set values are never touched). * 3. Starts the Postgres container via Docker Compose (if Docker is * available) and waits for its healthcheck. - * 4. Applies Prisma migrations and generates the Prisma client. + * 4. Applies Prisma migrations, then prisma/manual-scripts/001_pgvector.sql + * (safe to re-run), and generates the Prisma client. * * Cross-platform (macOS / Linux / Windows), no dependencies beyond Node. */ @@ -26,12 +27,12 @@ const envPath = join(root, ".env"); const examplePath = join(root, ".env.example"); // --------------------------------------------------------------------------- -// 0. Node version check (Next.js 14 + this script need Node 20.19+) +// 0. Node version check (Prisma 7 and this script need Node 20.19+) // --------------------------------------------------------------------------- const [nodeMajor, nodeMinor] = process.versions.node.split(".").map(Number); if (nodeMajor < 20 || (nodeMajor === 20 && nodeMinor < 19)) { console.error( - `Setup failed: Node ${process.versions.node} is too old — this project requires Node 20.19 or newer, so install a current Node LTS and re-run npm run setup.`, + `Setup failed: Node ${process.versions.node} is too old. This project needs Node 20.19 or newer, so install a current Node LTS and re-run npm run setup.`, ); process.exit(1); } @@ -67,16 +68,16 @@ function sleep(ms) { // --------------------------------------------------------------------------- step("Environment file"); if (existsSync(envPath)) { - ok(".env already exists — leaving your values untouched"); + ok(".env already exists, so your values stay as they are"); } else { - if (!existsSync(examplePath)) die(".env.example not found — cannot create .env"); + if (!existsSync(examplePath)) die(".env.example not found, so .env can't be created"); copyFileSync(examplePath, envPath); ok("created .env from .env.example"); } // --------------------------------------------------------------------------- // 2. Fill in generated secrets where the value is empty -// (matches `KEY=""`, `KEY=''` or `KEY=` — never a user-set value) +// (matches `KEY=""`, `KEY=''` or `KEY=`, never a user-set value) // --------------------------------------------------------------------------- const SECRET_GENERATORS = { NEXTAUTH_SECRET: () => randomBytes(32).toString("base64"), @@ -94,9 +95,9 @@ for (const [key, generate] of Object.entries(SECRET_GENERATORS)) { ); ok(`generated ${key}`); } else if (new RegExp(`^${key}=`, "m").test(envText)) { - ok(`${key} already set — keeping your value`); + ok(`${key} already set, keeping your value`); } else { - warn(`${key} not found in .env — add it manually if you need it`); + warn(`${key} not found in .env; add it by hand if you need it`); } } try { @@ -159,7 +160,7 @@ function waitForHealthy(timeoutMs) { if (ps.status === 0 && ps.stdout) { const text = ps.stdout.trim(); // Compose emits either a single JSON object, an array, or NDJSON lines - // depending on version — handle all three. + // depending on version. Handle all three. let entries = []; try { const parsed = JSON.parse(text); @@ -196,19 +197,19 @@ const composeCheck = run("docker", ["compose", "version"], { stdio: ["ignore", "pipe", "pipe"], }); if (composeCheck.status !== 0 || composeCheck.error) { - explainNoDocker("Docker Compose not found — skipping database startup."); + explainNoDocker("Docker Compose not found, so the database isn't started."); } else { const up = run("docker", ["compose", "up", "-d", "db"], { stdio: ["ignore", "pipe", "pipe"], }); if (up.status !== 0) { const detail = (up.stderr || "").trim().split(/\r?\n/).pop() || "unknown error"; - explainNoDocker(`Docker is installed but not usable (${detail}) — skipping database startup.`); + explainNoDocker(`Docker is installed but not usable (${detail}), so the database isn't started.`); } else { ok("started the db container (host port 5433)"); dbHealthy = waitForHealthy(60_000); if (!dbHealthy) { - warn("Postgres did not report healthy in time — check: npm run db:logs"); + warn("Postgres did not report healthy in time. Check: npm run db:logs"); } } } @@ -222,7 +223,27 @@ const migrated = migrate.status === 0; if (migrated) { ok("migrations applied"); } else { - warn("database not reachable — start Postgres and run: npx prisma migrate deploy"); + warn("database not reachable. Start Postgres and run: npx prisma migrate deploy"); +} + +// The embedding column and its index live outside the Prisma schema because +// Prisma cannot model the vector type. Every statement in the script uses +// IF NOT EXISTS, so re-running setup is safe. Without pgvector the app still +// works; only embedding jobs and hybrid search stay unavailable. +const PGVECTOR_SCRIPT = "prisma/manual-scripts/001_pgvector.sql"; +let vectorReady = false; +if (migrated) { + step("pgvector extension and embedding column"); + const vector = run("npx", ["prisma", "db", "execute", "--file", PGVECTOR_SCRIPT], { + stdio: ["ignore", "pipe", "pipe"], + }); + vectorReady = vector.status === 0; + if (vectorReady) { + ok(`applied ${PGVECTOR_SCRIPT}`); + } else { + warn(`could not apply ${PGVECTOR_SCRIPT}; is the pgvector extension installed?`); + warn("the Docker database (npm run db:up) ships with pgvector"); + } } step("Prisma client (prisma generate)"); @@ -231,7 +252,7 @@ const generated = generate.status === 0; if (generated) { ok("Prisma client generated"); } else { - warn("prisma generate failed — run it manually: npx prisma generate"); + warn("prisma generate failed. Run it by hand: npx prisma generate"); } // --------------------------------------------------------------------------- @@ -249,9 +270,14 @@ if (!migrated || !generated) { } if (!generated) log(" - npx prisma generate"); } +if (migrated && !vectorReady) { + log(""); + log("Optional, for npm run worker and embedding search: install pgvector,"); + log(`then run: npx prisma db execute --file ${PGVECTOR_SCRIPT}`); +} if (parsedEnv.AI_PROVIDER === "mock") { log(""); - log("Heads up: AI_PROVIDER is \"mock\" in .env. Mock mode exists for tests —"); + log("Heads up: AI_PROVIDER is \"mock\" in .env. Mock mode exists for tests:"); log("sessions get template questions and canned feedback. For real studying,"); log("set AI_PROVIDER=openai and add an OPENAI_API_KEY in .env."); } diff --git a/scripts/worker.ts b/scripts/worker.ts index fbee6b80..9eabd451 100644 --- a/scripts/worker.ts +++ b/scripts/worker.ts @@ -9,7 +9,11 @@ * JOB_WORKER_CONCURRENCY — max concurrent jobs (default: 2) * JOB_POLL_INTERVAL_MS — poll interval in ms (default: 2000) * AI_PROVIDER — "mock" for testing, "openai" for production + * + * tsx does not read .env the way Next does, so it is loaded first. Variables + * already set in the environment win over .env values. */ +import "dotenv/config"; import { claimJobs, succeedJob, failJob, recoverStaleJobs, type ClaimedJob } from "../src/lib/jobs/queue"; import { handleEmbedChunkBatch } from "../src/lib/jobs/handlers/embed-chunks"; import { createProvider } from "../src/lib/ai/provider-factory"; diff --git a/src/__tests__/account-delete-route.test.ts b/src/__tests__/account-delete-route.test.ts new file mode 100644 index 00000000..732f849c --- /dev/null +++ b/src/__tests__/account-delete-route.test.ts @@ -0,0 +1,222 @@ +/** + * DELETE /api/account/delete: the confirmation phrase and password contract, + * the best-effort Google revoke once the data is gone (never before a + * failed delete), and the uploaded files removed after it. + */ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import type { NextRequest } from "next/server"; +import bcrypt from "bcryptjs"; + +vi.mock("@/lib/auth", () => ({ + getUserId: vi.fn(async (request: Request) => request.headers.get("x-user-id")), +})); + +vi.mock("@/lib/crypto/token-vault", () => ({ + decryptToken: vi.fn((value: string) => `plain-${value}`), +})); + +const deleteMany = () => vi.fn(async () => ({ count: 0 })); +const tx = { + cardReview: { deleteMany: deleteMany() }, + xpEvent: { deleteMany: deleteMany() }, + achievement: { deleteMany: deleteMany() }, + objectiveMastery: { deleteMany: deleteMany() }, + aiCallLog: { updateMany: deleteMany() }, + oAuthState: { deleteMany: deleteMany() }, + studyGuide: { deleteMany: deleteMany() }, + planItemExternalEvent: { deleteMany: deleteMany() }, + planCalendarPublication: { deleteMany: deleteMany() }, + planReflowAudit: { deleteMany: deleteMany() }, + objectiveAnchor: { deleteMany: deleteMany() }, + sessionErrorLog: { deleteMany: deleteMany() }, + chatMessage: { deleteMany: deleteMany() }, + verificationToken: { deleteMany: deleteMany() }, + jobQueue: { deleteMany: deleteMany() }, + sessionAttempt: { deleteMany: deleteMany() }, + studyPlanItem: { deleteMany: deleteMany() }, + evidencePaper: { deleteMany: deleteMany() }, + flashcardDeck: { deleteMany: deleteMany() }, + sessionRun: { deleteMany: deleteMany() }, + googleIntegration: { deleteMany: deleteMany() }, + userGameState: { deleteMany: deleteMany() }, + session: { deleteMany: deleteMany() }, + contentDocument: { deleteMany: deleteMany() }, + studyPlan: { deleteMany: deleteMany() }, + user: { delete: vi.fn(async () => ({})) }, +}; + +vi.mock("@/lib/db", () => ({ + prisma: { + googleIntegration: { findUnique: vi.fn() }, + user: { findUnique: vi.fn() }, + $transaction: vi.fn(async (fn: (t: typeof tx) => Promise<unknown>) => fn(tx)), + }, +})); + +vi.mock("@/services/account", async (importOriginal) => ({ + ...(await importOriginal<typeof import("@/services/account")>()), + deleteUserFiles: vi.fn(async () => {}), +})); + +import { DELETE } from "@/app/api/account/delete/route"; +import { DELETE_ACCOUNT_PHRASE } from "@/lib/account"; +import { decryptToken } from "@/lib/crypto/token-vault"; +import { prisma } from "@/lib/db"; +import { accountDeleteLimiter, deleteUserFiles } from "@/services/account"; + +const findIntegration = vi.mocked(prisma.googleIntegration.findUnique); +const findUser = vi.mocked(prisma.user.findUnique); +const removeFiles = vi.mocked(deleteUserFiles); + +const PASSWORD = "correct horse"; +const PASSWORD_HASH = bcrypt.hashSync(PASSWORD, 4); +const confirmed = { confirm: DELETE_ACCOUNT_PHRASE, password: PASSWORD }; + +function request(body: unknown, userId: string | null = "u1"): NextRequest { + return new Request("http://localhost:3000/api/account/delete", { + method: "DELETE", + headers: { "content-type": "application/json", ...(userId ? { "x-user-id": userId } : {}) }, + body: JSON.stringify(body), + }) as unknown as NextRequest; +} + +describe("DELETE /api/account/delete", () => { + const fetchMock = vi.fn(async () => new Response(null, { status: 200 })); + + beforeEach(() => { + vi.clearAllMocks(); + accountDeleteLimiter.reset(); + vi.stubGlobal("fetch", fetchMock); + findUser.mockResolvedValue({ passwordHash: PASSWORD_HASH } as never); + }); + + afterEach(() => { + vi.unstubAllGlobals(); + }); + + it("keeps the confirmation phrase the client sends", () => { + expect(DELETE_ACCOUNT_PHRASE).toBe("DELETE MY ACCOUNT"); + }); + + it("refuses without the phrase, with a sentence instead of a schema dump", async () => { + const res = await DELETE(request({ confirm: "delete", password: PASSWORD })); + expect(res.status).toBe(400); + expect((await res.json()).error).toBe("Account not deleted. Confirm in the dialog and retry."); + expect(tx.user.delete).not.toHaveBeenCalled(); + }); + + it("refuses the phrase alone, so a session without the password can't delete", async () => { + const res = await DELETE(request({ confirm: DELETE_ACCOUNT_PHRASE })); + expect(res.status).toBe(400); + expect(findUser).not.toHaveBeenCalled(); + expect(tx.user.delete).not.toHaveBeenCalled(); + }); + + it("answers 403 with a password issue when the password is wrong, and keeps everything", async () => { + findIntegration.mockResolvedValue({ accessTokenEncrypted: "a", refreshTokenEncrypted: "r" } as never); + const res = await DELETE(request({ confirm: DELETE_ACCOUNT_PHRASE, password: "wrong" })); + expect(res.status).toBe(403); + const body = await res.json(); + expect(body.code).toBe("WRONG_PASSWORD"); + expect(body.error).toBe("That password doesn't match your account. Check it and retry."); + expect(body.issues).toEqual([{ path: ["password"], message: body.error }]); + expect(fetchMock).not.toHaveBeenCalled(); + expect(tx.user.delete).not.toHaveBeenCalled(); + expect(removeFiles).not.toHaveBeenCalled(); + }); + + it("limits password attempts per student", async () => { + let res: Response | undefined; + for (let i = 0; i < 60; i++) { + res = await DELETE(request({ confirm: DELETE_ACCOUNT_PHRASE, password: "wrong" })); + if (res.status === 429) break; + } + expect(res?.status).toBe(429); + expect(res?.headers.get("Retry-After")).toBeTruthy(); + // Another student isn't affected. + const other = await DELETE(request({ confirm: DELETE_ACCOUNT_PHRASE, password: "wrong" }, "u2")); + expect(other.status).toBe(403); + }); + + it("answers 401 when signed out", async () => { + const res = await DELETE(request(confirmed, null)); + expect(res.status).toBe(401); + }); + + it("answers 401 when the session's account no longer exists", async () => { + findUser.mockResolvedValue(null); + const res = await DELETE(request(confirmed)); + expect(res.status).toBe(401); + expect(tx.user.delete).not.toHaveBeenCalled(); + }); + + it("deletes everything, then revokes Google access and removes the uploaded files", async () => { + findIntegration.mockResolvedValue({ accessTokenEncrypted: "a", refreshTokenEncrypted: "r" } as never); + const res = await DELETE(request(confirmed)); + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ deleted: true }); + expect(fetchMock).toHaveBeenCalledTimes(1); + const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit]; + expect(url).toBe("https://oauth2.googleapis.com/revoke"); + expect(String(init.body)).toBe("token=plain-r"); + expect(tx.user.delete).toHaveBeenCalledWith({ where: { id: "u1" } }); + // AI spend stays counted toward the cap across accounts, detached from the account. + expect(tx.aiCallLog.updateMany).toHaveBeenCalledWith({ where: { userId: "u1" }, data: { userId: "deleted" } }); + // The revoke can't be undone, so it waits for the deletion to commit. + expect(fetchMock.mock.invocationCallOrder[0]).toBeGreaterThan(tx.user.delete.mock.invocationCallOrder[0]); + expect(tx.jobQueue.deleteMany).toHaveBeenCalledWith({ + where: { payload: { path: ["userId"], equals: "u1" }, status: { not: "RUNNING" } }, + }); + expect(removeFiles).toHaveBeenCalledWith("u1"); + expect(removeFiles.mock.invocationCallOrder[0]).toBeGreaterThan( + tx.user.delete.mock.invocationCallOrder[0], + ); + }); + + it("keeps the files when the database deletion fails", async () => { + findIntegration.mockResolvedValue(null); + tx.user.delete.mockRejectedValueOnce(new Error("db down")); + const res = await DELETE(request(confirmed)); + expect(res.status).toBe(500); + expect(removeFiles).not.toHaveBeenCalled(); + }); + + it("keeps the Google connection working when the database deletion fails", async () => { + // Revoking first would leave the kept account with a calendar that shows + // as connected but answers invalid_grant. + findIntegration.mockResolvedValue({ accessTokenEncrypted: "a", refreshTokenEncrypted: "r" } as never); + tx.user.delete.mockRejectedValueOnce(new Error("db down")); + const res = await DELETE(request(confirmed)); + expect(res.status).toBe(500); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it("deletes without calling Google when the stored token can't be read", async () => { + findIntegration.mockResolvedValue({ accessTokenEncrypted: null, refreshTokenEncrypted: "r" } as never); + vi.mocked(decryptToken).mockImplementationOnce(() => { + throw new Error("bad key"); + }); + const res = await DELETE(request(confirmed)); + expect(res.status).toBe(200); + expect(tx.user.delete).toHaveBeenCalled(); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it("still answers deleted when removing the files fails", async () => { + findIntegration.mockResolvedValue(null); + removeFiles.mockRejectedValueOnce(new Error("EBUSY")); + const res = await DELETE(request(confirmed)); + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ deleted: true }); + }); + + it("still deletes when the revoke fails or there is no integration", async () => { + findIntegration.mockResolvedValue(null); + expect((await DELETE(request(confirmed))).status).toBe(200); + expect(fetchMock).not.toHaveBeenCalled(); + + findIntegration.mockResolvedValue({ accessTokenEncrypted: "a", refreshTokenEncrypted: null } as never); + fetchMock.mockRejectedValueOnce(new Error("offline")); + expect((await DELETE(request(confirmed))).status).toBe(200); + }); +}); diff --git a/src/__tests__/account-export-route.test.ts b/src/__tests__/account-export-route.test.ts new file mode 100644 index 00000000..8891af89 --- /dev/null +++ b/src/__tests__/account-export-route.test.ts @@ -0,0 +1,70 @@ +/** + * GET /api/account/export: BigInt columns serialize, and the route has its + * own rate limit with a readable 429. + */ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import type { NextRequest } from "next/server"; + +vi.mock("@/lib/auth", () => ({ + getUserId: vi.fn(async (request: Request) => request.headers.get("x-user-id")), +})); + +// Every model answers empty, except the two with BigInt columns. +vi.mock("@/lib/db", () => { + const model = (overrides: Record<string, unknown> = {}) => ({ + findMany: vi.fn(async () => []), + findUnique: vi.fn(async () => null), + ...overrides, + }); + const prisma = new Proxy( + { + aiCallLog: model({ + findMany: vi.fn(async () => [{ id: "a1", costUsdMicros: BigInt("12345678901234567") }]), + }), + googleIntegration: model({ + findUnique: vi.fn(async () => ({ id: "g1", tokenExpiryMs: BigInt(42) })), + }), + } as Record<string, unknown>, + { + get(target, key: string) { + if (!(key in target)) target[key] = model(); + return target[key]; + }, + }, + ); + return { prisma }; +}); + +import { GET } from "@/app/api/account/export/route"; + +function request(userId: string | null): NextRequest { + return new Request("http://localhost:3000/api/account/export", { + headers: userId ? { "x-user-id": userId } : {}, + }) as unknown as NextRequest; +} + +describe("GET /api/account/export", () => { + beforeEach(() => vi.clearAllMocks()); + + it("exports BigInt columns as strings in a JSON attachment", async () => { + const res = await GET(request("export-user-1")); + expect(res.status).toBe(200); + expect(res.headers.get("content-disposition")).toMatch(/^attachment; filename="study-bot-export-\d+\.json"$/); + const body = JSON.parse(await res.text()); + expect(body.aiCallLogs[0].costUsdMicros).toBe("12345678901234567"); + expect(body.googleIntegration.tokenExpiryMs).toBe("42"); + }); + + it("allows 3 exports a minute, then answers 429 with a wait in seconds", async () => { + for (let i = 0; i < 3; i++) expect((await GET(request("export-user-2"))).status).toBe(200); + const limited = await GET(request("export-user-2")); + expect(limited.status).toBe(429); + const body = await limited.json(); + expect(body.error).toMatch(/^Too many exports\. Retry in \d+ seconds?\.$/); + expect(Number(limited.headers.get("retry-after"))).toBeGreaterThan(0); + }); + + it("answers 401 when signed out", async () => { + expect((await GET(request(null))).status).toBe(401); + }); +}); diff --git a/src/__tests__/account-files.test.ts b/src/__tests__/account-files.test.ts new file mode 100644 index 00000000..0b2bca14 --- /dev/null +++ b/src/__tests__/account-files.test.ts @@ -0,0 +1,65 @@ +/** + * deleteUserFiles: account deletion removes the student's upload folder and + * nothing else. + */ +import { describe, it, expect, beforeAll, afterAll, vi } from "vitest"; +import { mkdir, mkdtemp, rm, stat, writeFile } from "fs/promises"; +import { tmpdir } from "os"; +import { join } from "path"; + +let base: string; +let root: string; +let storage: typeof import("@/lib/storage"); +let account: typeof import("@/services/account"); + +async function exists(path: string) { + return stat(path).then( + () => true, + () => false, + ); +} + +beforeAll(async () => { + base = await mkdtemp(join(tmpdir(), "sb-account-files-")); + root = join(base, "uploads"); + await mkdir(root, { recursive: true }); + vi.stubEnv("UPLOAD_DIR", root); + vi.resetModules(); + storage = await import("@/lib/storage"); + account = await import("@/services/account"); +}); + +afterAll(async () => { + vi.unstubAllEnvs(); + await rm(base, { recursive: true, force: true }); +}); + +describe("deleteUserFiles", () => { + it("removes the student's folder with every document in it, and leaves other students alone", async () => { + await storage.saveFile("user-a", "doc-1", "lecture-1.pdf", Buffer.from("a")); + await storage.saveFile("user-a", "doc-2", "notes.md", Buffer.from("b")); + await storage.saveFile("user-b", "doc-3", "notes.md", Buffer.from("c")); + + await account.deleteUserFiles("user-a"); + + expect(await exists(join(root, "user-a"))).toBe(false); + expect(await exists(join(root, "user-b", "doc-3", "notes.md"))).toBe(true); + expect(await exists(root)).toBe(true); + }); + + it("is fine when the student never uploaded anything", async () => { + await expect(account.deleteUserFiles("user-without-files")).resolves.toBeUndefined(); + }); + + it("refuses ids that would reach outside the student's own folder", async () => { + await writeFile(join(base, "outside.txt"), "keep me"); + await storage.saveFile("user-c", "doc-4", "notes.md", Buffer.from("d")); + + for (const id of ["", ".", "..", "../uploads", "user-c/doc-4", "user-c\\doc-4"]) { + await expect(account.deleteUserFiles(id)).rejects.toThrow(); + } + + expect(await exists(join(base, "outside.txt"))).toBe(true); + expect(await exists(join(root, "user-c", "doc-4", "notes.md"))).toBe(true); + }); +}); diff --git a/src/__tests__/active-course.test.ts b/src/__tests__/active-course.test.ts new file mode 100644 index 00000000..860f6412 --- /dev/null +++ b/src/__tests__/active-course.test.ts @@ -0,0 +1,78 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +function memoryStorage(initial: Record<string, string> = {}) { + const map = new Map(Object.entries(initial)); + return { + getItem: (k: string) => (map.has(k) ? map.get(k)! : null), + setItem: (k: string, v: string) => void map.set(k, v), + removeItem: (k: string) => void map.delete(k), + dump: () => Object.fromEntries(map), + }; +} + +async function loadWith(storage: ReturnType<typeof memoryStorage> | { getItem: () => never }) { + vi.resetModules(); + vi.stubGlobal("window", { + localStorage: storage, + addEventListener: () => {}, + removeEventListener: () => {}, + }); + return import("@/hooks/use-active-course"); +} + +describe("course keys", () => { + it("joins and splits Course||Exam", async () => { + const { courseKey, parseCourseKey } = await import("@/hooks/use-active-course"); + expect(courseKey("CS 2110", "Prelim 1")).toBe("CS 2110||Prelim 1"); + expect(courseKey("CS 2110", null)).toBe("CS 2110"); + expect(parseCourseKey("CS 2110||Prelim 1")).toEqual({ courseName: "CS 2110", examName: "Prelim 1" }); + expect(parseCourseKey("CS 2110")).toEqual({ courseName: "CS 2110", examName: null }); + }); +}); + +describe("stored active course", () => { + beforeEach(() => vi.unstubAllGlobals()); + afterEach(() => vi.unstubAllGlobals()); + + it("migrates the old key once and removes it", async () => { + const storage = memoryStorage({ study_bot_active_course: "Bio||Midterm" }); + const mod = await loadWith(storage); + expect(mod.getStoredActiveCourse()).toBe("Bio||Midterm"); + expect(storage.dump()).toEqual({ + [mod.ACTIVE_COURSE_KEY]: JSON.stringify({ course: "Bio||Midterm" }), + }); + }); + + it("prefers the versioned key over the old one", async () => { + const storage = memoryStorage({ + "study-bot:active-course:v1": JSON.stringify({ course: "CS 2110" }), + study_bot_active_course: "Old course", + }); + const mod = await loadWith(storage); + expect(mod.getStoredActiveCourse()).toBe("CS 2110"); + }); + + it("writes through the setter and clears with null", async () => { + const storage = memoryStorage(); + const mod = await loadWith(storage); + mod.storeActiveCourse("Chem||Final"); + expect(mod.getStoredActiveCourse()).toBe("Chem||Final"); + expect(JSON.parse(storage.getItem(mod.ACTIVE_COURSE_KEY)!)).toEqual({ course: "Chem||Final" }); + mod.storeActiveCourse(null); + expect(storage.getItem(mod.ACTIVE_COURSE_KEY)).toBeNull(); + }); + + it("survives blocked or corrupt storage", async () => { + const blocked = { + getItem: () => { + throw new Error("blocked"); + }, + }; + const mod = await loadWith(blocked); + expect(mod.getStoredActiveCourse()).toBeNull(); + + const corrupt = memoryStorage({ "study-bot:active-course:v1": "{not json" }); + const again = await loadWith(corrupt); + expect(again.getStoredActiveCourse()).toBeNull(); + }); +}); diff --git a/src/__tests__/admin.test.ts b/src/__tests__/admin.test.ts new file mode 100644 index 00000000..da94af47 --- /dev/null +++ b/src/__tests__/admin.test.ts @@ -0,0 +1,48 @@ +/** + * Unit tests for requireAdmin, the gate on /api/admin routes. + */ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; + +vi.mock("@/lib/auth", () => ({ + getUserId: vi.fn(async (request: Request) => request.headers.get("x-user-id")), +})); + +import { requireAdmin } from "@/lib/admin"; +import { UNAUTHORIZED_BODY } from "@/lib/http"; + +function req(userId?: string) { + return new Request("http://localhost/api/admin/jobs", { + headers: userId ? { "x-user-id": userId } : {}, + }); +} + +describe("requireAdmin", () => { + beforeEach(() => { + vi.stubEnv("ADMIN_USER_IDS", "admin-1, admin-2"); + }); + + afterEach(() => { + vi.unstubAllEnvs(); + }); + + it("answers 401 without a user, with the proxy's body", async () => { + const result = await requireAdmin(req()); + expect("response" in result && result.response.status).toBe(401); + if ("response" in result) expect(await result.response.json()).toEqual(UNAUTHORIZED_BODY); + }); + + it("answers 403 for a user not in ADMIN_USER_IDS", async () => { + const result = await requireAdmin(req("someone")); + expect("response" in result && result.response.status).toBe(403); + }); + + it("returns the admin's ID, trimming list entries", async () => { + expect(await requireAdmin(req("admin-2"))).toEqual({ userId: "admin-2" }); + }); + + it("treats an empty list as no admins", async () => { + vi.stubEnv("ADMIN_USER_IDS", ""); + const result = await requireAdmin(req("admin-1")); + expect("response" in result && result.response.status).toBe(403); + }); +}); diff --git a/src/__tests__/ai-gateway-global-cap.test.ts b/src/__tests__/ai-gateway-global-cap.test.ts new file mode 100644 index 00000000..6b7f1dfe --- /dev/null +++ b/src/__tests__/ai-gateway-global-cap.test.ts @@ -0,0 +1,133 @@ +/** + * The optional daily AI ceiling across every account + * (AI_GLOBAL_DAILY_COST_CAP_USD). Sign-up is open, so the per-account caps + * (ai-gateway.test.ts) alone don't bound what the operator pays. The gateway + * reads its caps when it loads, so this file sets the ceiling first. + */ +import { describe, it, expect, vi, beforeEach, afterAll } from "vitest"; + +vi.hoisted(() => { + vi.stubEnv("AI_GLOBAL_DAILY_COST_CAP_USD", "5"); +}); + +vi.mock("@/lib/db", () => ({ + prisma: { + aiCallLog: { + create: vi.fn(async () => ({})), + aggregate: vi.fn(), + }, + aiCache: { + findFirst: vi.fn(async () => null), + upsert: vi.fn(async () => ({})), + update: vi.fn(async () => ({})), + deleteMany: vi.fn(async () => ({ count: 0 })), + }, + }, +})); + +import { runTask, embed, resetCircuitBreaker, GatewayError } from "@/lib/ai/gateway"; +import { MockProvider } from "@/lib/ai/providers/mock"; +import { AiTask } from "@/lib/ai/types"; +import { getPrompt } from "@/lib/ai/prompt-registry"; +import { prisma } from "@/lib/db"; + +type AggregateArgs = { where: Record<string, unknown> }; + +const aggregate = vi.mocked(prisma.aiCallLog.aggregate); + +/** Spend in dollars: today's total across accounts, and any one account's. */ +let spend = { allAccounts: 0, oneAccount: 0 }; + +function micros(usd: number) { + return { _sum: { costUsdMicros: BigInt(Math.round(usd * 1_000_000)) } }; +} + +/** Aggregate calls without a userId filter, the ones that sum every account. */ +function globalReads(): AggregateArgs[] { + return aggregate.mock.calls.map((call) => call[0] as AggregateArgs).filter((args) => !("userId" in args.where)); +} + +const prompt = getPrompt(AiTask.SUGGEST_ERROR_TYPE); +const spec = { + task: AiTask.SUGGEST_ERROR_TYPE, + promptVersion: prompt.version, + model: "test-model", + input: { question: "Q", userAnswer: "A", correctConcept: "C" }, + parseOutput: (raw: unknown) => raw, +}; + +async function budgetError(promise: Promise<unknown>): Promise<GatewayError> { + const err = await promise.then( + () => null, + (e: unknown) => e, + ); + expect(err).toBeInstanceOf(GatewayError); + return err as GatewayError; +} + +describe("AI ceiling across every account", () => { + let provider: MockProvider; + + beforeEach(() => { + provider = new MockProvider(); + resetCircuitBreaker(); + vi.clearAllMocks(); + spend = { allAccounts: 0, oneAccount: 0 }; + aggregate.mockImplementation((async (args: AggregateArgs) => + micros("userId" in args.where ? spend.oneAccount : spend.allAccounts)) as never); + }); + + afterAll(() => { + vi.unstubAllEnvs(); + }); + + it("stops every account once today's total reaches the ceiling", async () => { + spend = { allAccounts: 5, oneAccount: 0 }; + const completeJson = vi.spyOn(provider, "completeJson"); + + for (const userId of ["fresh-account-1", "fresh-account-2"]) { + const err = await budgetError(runTask({ userId, provider }, spec, { skipCache: true })); + expect(err.code).toBe("BUDGET_EXCEEDED"); + expect(err.message).toBe("Daily AI budget for all accounts reached: $5.00 of $5.00 spent."); + } + expect(completeJson).not.toHaveBeenCalled(); + }); + + it("sums today's spend with no account filter, once a minute", async () => { + spend = { allAccounts: 4.99, oneAccount: 0 }; + + await runTask({ userId: "account-a", provider }, spec, { skipCache: true }); + await runTask({ userId: "account-b", provider }, spec, { skipCache: true }); + + const reads = globalReads(); + expect(reads).toHaveLength(1); + const startOfDay = new Date(); + startOfDay.setUTCHours(0, 0, 0, 0); + expect(reads[0].where).toEqual({ createdAt: { gte: startOfDay }, status: "OK" }); + }); + + it("covers embedding uploads and search queries too", async () => { + spend = { allAccounts: 6, oneAccount: 0 }; + + const upload = await budgetError(embed({ userId: "u1", provider }, ["chunk"], "text-embedding-3-small", { budget: "upload" })); + expect(upload.code).toBe("BUDGET_EXCEEDED"); + const search = await budgetError(embed({ userId: "u1", provider }, ["query"], "text-embedding-3-small")); + expect(search.code).toBe("BUDGET_EXCEEDED"); + }); + + it("still applies each account's own cap under the ceiling", async () => { + spend = { allAccounts: 2, oneAccount: 1_000 }; + + const err = await budgetError(runTask({ userId: "busy-account", provider }, spec, { skipCache: true })); + expect(err.code).toBe("BUDGET_EXCEEDED"); + expect(err.message).toMatch(/^(Daily|Monthly) AI budget reached/); + }); + + it("asks the database again after a failed read", async () => { + aggregate.mockRejectedValueOnce(new Error("connection reset")); + await expect(runTask({ userId: "u1", provider }, spec, { skipCache: true })).rejects.toThrow("connection reset"); + + await expect(runTask({ userId: "u1", provider }, spec, { skipCache: true })).resolves.toBeDefined(); + expect(globalReads()).toHaveLength(2); + }); +}); diff --git a/src/__tests__/ai-gateway.test.ts b/src/__tests__/ai-gateway.test.ts index 656b021c..e4b61a8f 100644 --- a/src/__tests__/ai-gateway.test.ts +++ b/src/__tests__/ai-gateway.test.ts @@ -34,6 +34,10 @@ vi.mock("@/lib/db", () => { return create; }), update: vi.fn(async () => ({})), + deleteMany: vi.fn(async ({ where }: { where: { keyHash: string } }) => { + aiCacheEntries.delete(where.keyHash); + return { count: 1 }; + }), }, _test: { aiCallLogs, aiCacheEntries }, }, @@ -41,6 +45,7 @@ vi.mock("@/lib/db", () => { }); import { runTask, embed, resetCircuitBreaker, GatewayError } from "@/lib/ai/gateway"; +import { ProviderRequestError } from "@/lib/ai/provider"; import { prisma } from "@/lib/db"; const testPrisma = (prisma as unknown as { _test: { aiCallLogs: unknown[]; aiCacheEntries: Map<string, unknown> } })._test; @@ -104,6 +109,32 @@ describe("AI Gateway", () => { expect(provider.callLog).toHaveLength(1); }); + it("treats a cached entry that no longer parses as a miss and evicts it", async () => { + const prompt = getPrompt(AiTask.SUGGEST_ERROR_TYPE); + const base = { + task: AiTask.SUGGEST_ERROR_TYPE, + promptVersion: prompt.version, + model: "test-model", + input: { question: "Q", userAnswer: "A", correctConcept: "C" }, + }; + const ctx = { userId: "user1", provider }; + + await runTask(ctx, { ...base, parseOutput: (raw: unknown) => raw as { error_type: string } }); + expect(testPrisma.aiCacheEntries.size).toBe(1); + + let calls = 0; + const strict = (raw: unknown) => { + calls++; + if (calls === 1) throw new Error("stale shape"); + return raw as { error_type: string }; + }; + const r2 = await runTask(ctx, { ...base, parseOutput: strict }); + + expect(r2.meta.cacheHit).toBe(false); + expect(provider.callLog).toHaveLength(2); + expect(vi.mocked(prisma.aiCache.deleteMany)).toHaveBeenCalledTimes(1); + }); + it("skips cache when skipCache is true", async () => { const prompt = getPrompt(AiTask.SUGGEST_ERROR_TYPE); const spec = { @@ -175,6 +206,84 @@ describe("AI Gateway", () => { // 6th call should be blocked by circuit breaker await expect(runTask(ctx, spec, { skipCache: true, skipBudget: true })).rejects.toThrow("circuit breaker"); }); + + it("doesn't count requests the provider refused for their content", async () => { + const tooLong = new ProviderRequestError("OpenAI API error 400: context_length_exceeded", 400); + const refusingProvider = { + embed: vi.fn().mockRejectedValue(tooLong), + completeJson: vi.fn().mockRejectedValue(tooLong), + }; + const prompt = getPrompt(AiTask.SUGGEST_ERROR_TYPE); + const spec = { + task: AiTask.SUGGEST_ERROR_TYPE, + promptVersion: prompt.version, + model: "m", + input: { question: "Q", userAnswer: "A", correctConcept: "C" }, + parseOutput: (raw: unknown) => raw, + }; + + for (let i = 0; i < 8; i++) { + const err = await runTask({ userId: "attacker", provider: refusingProvider }, spec, { + skipCache: true, + skipBudget: true, + }).catch((e: unknown) => e); + expect(err).toBeInstanceOf(GatewayError); + expect((err as GatewayError).code).toBe("PROVIDER_ERROR"); + expect((err as GatewayError).retryable).toBe(false); + } + + // Another student's request still reaches the provider + const result = await runTask({ userId: "user2", provider }, spec, { skipCache: true, skipBudget: true }); + expect(result.meta.cacheHit).toBe(false); + expect(provider.callLog).toHaveLength(1); + }); + }); + + describe("embed budget", () => { + const aggregateMock = () => vi.mocked(prisma.aiCallLog.aggregate); + const spent = (usd: number) => + ({ _sum: { costUsdMicros: BigInt(Math.round(usd * 1_000_000)) } }) as never; + + it("checks uploads against today's embedding spend, not all AI spend", async () => { + await embed({ userId: "user1", provider }, ["chunk"], "text-embedding-3-small", { budget: "upload" }); + + const wheres = aggregateMock().mock.calls.map((c) => (c[0] as { where: Record<string, unknown> }).where); + expect(wheres).toHaveLength(2); + expect(wheres[0]).toMatchObject({ userId: "user1", task: "EMBED_TEXTS", status: "OK" }); + expect(wheres[1]).not.toHaveProperty("task"); + expect(provider.callLog).toHaveLength(1); + }); + + it("stops an upload once today's embedding cap is spent", async () => { + aggregateMock().mockResolvedValueOnce(spent(0.5)).mockResolvedValueOnce(spent(0.5)); + + const err = await embed({ userId: "user1", provider }, ["chunk"], "text-embedding-3-small", { + budget: "upload", + }).catch((e: unknown) => e); + + expect(err).toBeInstanceOf(GatewayError); + expect((err as GatewayError).code).toBe("BUDGET_EXCEEDED"); + expect((err as GatewayError).message).toMatch(/^Daily embedding budget reached/); + expect(provider.callLog).toHaveLength(0); + }); + + it("stops an upload once the monthly AI cap is spent", async () => { + aggregateMock().mockResolvedValueOnce(spent(0)).mockResolvedValueOnce(spent(50)); + + const err = await embed({ userId: "user1", provider }, ["chunk"], "text-embedding-3-small", { + budget: "upload", + }).catch((e: unknown) => e); + + expect((err as GatewayError).code).toBe("BUDGET_EXCEEDED"); + expect((err as GatewayError).message).toMatch(/^Monthly embedding budget reached/); + }); + + it("re-reads spend for every upload slice instead of caching it", async () => { + const ctx = { userId: "user1", provider }; + await embed(ctx, ["a"], "text-embedding-3-small", { budget: "upload" }); + await embed(ctx, ["b"], "text-embedding-3-small", { budget: "upload" }); + expect(aggregateMock()).toHaveBeenCalledTimes(4); + }); }); describe("embed", () => { diff --git a/src/__tests__/ai-voice.test.ts b/src/__tests__/ai-voice.test.ts new file mode 100644 index 00000000..d4fbe05b --- /dev/null +++ b/src/__tests__/ai-voice.test.ts @@ -0,0 +1,144 @@ +/** + * AI text follows VOICE.md: the system prompts teach the model the app's + * voice, the mock provider (what the demo shows) already writes in it, and + * student-written text is capped before it reaches a prompt. + */ +import { describe, it, expect } from "vitest"; +import { AiTask } from "@/lib/ai/types"; +import { MAX_STUDENT_TEXT_CHARS, PROMPTS, STUDENT_VOICE, getPrompt } from "@/lib/ai/prompt-registry"; +import { MockProvider } from "@/lib/ai/providers/mock"; + +/** Tasks whose output a student reads. SUGGEST_ERROR_TYPE returns an enum, the plan returns blocks. */ +const STUDENT_FACING = [ + AiTask.ANSWER_WITH_CITATIONS, + AiTask.GENERATE_VARIANT_QUESTION, + AiTask.GENERATE_PROMPTS, + AiTask.GENERATE_FEEDBACK, + AiTask.REINFORCE_CORRECT, + AiTask.SOCRATIC_FOLLOWUP, + AiTask.EXTRACT_OBJECTIVES, + AiTask.SUMMARIZE_DOCUMENT, + AiTask.GENERATE_STUDY_GUIDE, + AiTask.GENERATE_FLASHCARDS, + AiTask.GENERATE_WORKED_EXAMPLES, +]; + +const DASH = /[–—]/; + +/** Every string inside a JSON value. */ +function strings(value: unknown): string[] { + if (typeof value === "string") return [value]; + if (Array.isArray(value)) return value.flatMap(strings); + if (value && typeof value === "object") return Object.values(value).flatMap(strings); + return []; +} + +/** Sentence case: no word after the first starts with a capital, unless it is an acronym. */ +function isSentenceCase(title: string): boolean { + return title + .split(/\s+/) + .slice(1) + .every((word) => !/^[A-Z][a-z]/.test(word)); +} + +describe("system prompts", () => { + it.each(STUDENT_FACING)("%s carries the student voice block", (task) => { + expect(getPrompt(task).systemPrompt).toContain(STUDENT_VOICE); + }); + + it("never casts the model as a person or uses dashes", () => { + for (const prompt of Object.values(PROMPTS)) { + const own = prompt.systemPrompt.replace(STUDENT_VOICE, ""); + expect(own, prompt.task).not.toMatch(/professor|office hours|\blet's\b/i); + expect(prompt.systemPrompt, prompt.task).not.toMatch(DASH); + } + }); + + it("asks for sentence-case topic titles", () => { + expect(getPrompt(AiTask.EXTRACT_OBJECTIVES).systemPrompt).toMatch(/sentence case/); + }); + + it("still routes every task in the mock provider", async () => { + const provider = new MockProvider(); + const answer = await provider.completeJson(getPrompt(AiTask.ANSWER_WITH_CITATIONS).systemPrompt, "q", "m"); + expect(answer.json).toHaveProperty("answer_markdown"); + const feedback = await provider.completeJson(getPrompt(AiTask.GENERATE_FEEDBACK).systemPrompt, "q", "m"); + expect(feedback.json).toHaveProperty("explanation"); + const objectives = await provider.completeJson(getPrompt(AiTask.EXTRACT_OBJECTIVES).systemPrompt, "q", "m"); + expect(objectives.json).toHaveProperty("objectives"); + const cards = await provider.completeJson(getPrompt(AiTask.GENERATE_FLASHCARDS).systemPrompt, "q", "m"); + expect(cards.json).toHaveProperty("cards"); + }); +}); + +describe("student text in prompts", () => { + const huge = "a".repeat(MAX_STUDENT_TEXT_CHARS * 3); + + it("caps the fenced answer and correction in feedback prompts", () => { + const prompt = getPrompt(AiTask.GENERATE_FEEDBACK).buildUserPrompt({ + question: "Q", + userAnswer: huge, + selfScore: "INCORRECT", + correctionRule: huge, + chunks: [], + }); + expect(prompt.length).toBeLessThan(MAX_STUDENT_TEXT_CHARS * 2 + 1_000); + }); + + it.each([AiTask.SUGGEST_ERROR_TYPE, AiTask.REINFORCE_CORRECT, AiTask.SOCRATIC_FOLLOWUP])( + "caps the fenced answer in %s", + (task) => { + const prompt = getPrompt(task).buildUserPrompt({ + question: "Q", + userAnswer: huge, + correctConcept: "C", + selfScore: "CORRECT", + chunks: [], + }); + expect(prompt.length).toBeLessThan(MAX_STUDENT_TEXT_CHARS + 1_000); + }, + ); +}); + +describe("mock provider text", () => { + const provider = new MockProvider(); + const run = async (task: AiTask, userPrompt = "Course: CS 2110 | Exam: Prelim 1") => + (await provider.completeJson(getPrompt(task).systemPrompt, userPrompt, "m")).json; + + it("has no dashes, three-dot ellipses or exclamation marks", async () => { + const outputs = await Promise.all([ + ...STUDENT_FACING.map((task) => run(task)), + run(AiTask.GENERATE_STUDY_GUIDE, "Course: CS 2110\nGuide type: FAQ\nGenerate the faq study guide."), + run(AiTask.GENERATE_STUDY_GUIDE, "Course: CS 2110\nGuide type: CHEAT_SHEET\nGenerate the cheat sheet study guide."), + ]); + for (const text of outputs.flatMap(strings)) { + expect(text).not.toMatch(DASH); + expect(text).not.toContain("..."); + expect(text).not.toContain("!"); + } + }); + + it("writes topic titles in sentence case", async () => { + const { objectives } = (await run(AiTask.EXTRACT_OBJECTIVES)) as { objectives: { title: string }[] }; + for (const { title } of objectives) expect(isSentenceCase(title), title).toBe(true); + }); + + it("writes guide titles and headings in sentence case", async () => { + const guides = await Promise.all( + ["KEY_CONCEPTS", "FAQ", "CHEAT_SHEET"].map((type) => + run( + AiTask.GENERATE_STUDY_GUIDE, + `Course: CS 2110\nGuide type: ${type}\nGenerate the ${type.replace(/_/g, " ").toLowerCase()} study guide.`, + ), + ), + ); + const titles = guides.map((g) => (g as { title: string }).title); + expect(titles).toEqual(["Key concepts for CS 2110", "FAQ for CS 2110", "Cheat sheet for CS 2110"]); + for (const guide of guides) { + const { sections } = guide as { sections: { concept?: string; topic?: string }[] }; + for (const heading of sections.map((s) => s.concept ?? s.topic).filter(Boolean) as string[]) { + expect(isSentenceCase(heading), heading).toBe(true); + } + } + }); +}); diff --git a/src/__tests__/auth-callback-url.test.ts b/src/__tests__/auth-callback-url.test.ts new file mode 100644 index 00000000..d0de6c5b --- /dev/null +++ b/src/__tests__/auth-callback-url.test.ts @@ -0,0 +1,67 @@ +import { describe, it, expect } from "vitest"; +import { safeCallbackUrl, withCallbackUrl } from "@/components/auth/callback-url"; + +describe("safeCallbackUrl", () => { + it("keeps same-origin paths with their query and hash", () => { + expect(safeCallbackUrl("/plan")).toBe("/plan"); + expect(safeCallbackUrl("/plan?range=all#today")).toBe("/plan?range=all#today"); + expect(safeCallbackUrl("/s/abc123")).toBe("/s/abc123"); + expect(safeCallbackUrl(["/learn", "/plan"])).toBe("/learn"); + }); + + it("falls back to Home for anything missing or not a string", () => { + expect(safeCallbackUrl(undefined)).toBe("/"); + expect(safeCallbackUrl(null)).toBe("/"); + expect(safeCallbackUrl("")).toBe("/"); + expect(safeCallbackUrl(42)).toBe("/"); + expect(safeCallbackUrl([])).toBe("/"); + }); + + it("rejects other origins and protocol tricks", () => { + const attempts = [ + "https://evil.example/plan", + "//evil.example/plan", + "/\\evil.example", + "\\\\evil.example", + "javascript:alert(1)", + "http:evil.example", + "plan", + "/plan\nLocation: https://evil.example", + "/\tevil", + ]; + for (const raw of attempts) { + expect(safeCallbackUrl(raw), raw).toBe("/"); + } + }); + + it("keeps encoded characters encoded", () => { + expect(safeCallbackUrl("/%0d%0aSet-Cookie:x")).toBe("/%0d%0aSet-Cookie:x"); + }); + + it("never sends someone back to an auth screen or an API route", () => { + expect(safeCallbackUrl("/auth/signin")).toBe("/"); + expect(safeCallbackUrl("/auth/signin?callbackUrl=%2Fauth%2Fsignin")).toBe("/"); + expect(safeCallbackUrl("/api/auth/signout")).toBe("/"); + expect(safeCallbackUrl("/auth")).toBe("/"); + expect(safeCallbackUrl("/authors")).toBe("/authors"); + }); + + it("rejects absurdly long values", () => { + expect(safeCallbackUrl(`/${"a".repeat(3000)}`)).toBe("/"); + }); +}); + +describe("withCallbackUrl", () => { + it("leaves the default destination off", () => { + expect(withCallbackUrl("/auth/signup", "/")).toBe("/auth/signup"); + }); + + it("appends an encoded callback URL", () => { + expect(withCallbackUrl("/auth/signup", "/plan?range=all")).toBe( + "/auth/signup?callbackUrl=%2Fplan%3Frange%3Dall", + ); + expect(withCallbackUrl("/auth/signin?verified=true", "/plan")).toBe( + "/auth/signin?verified=true&callbackUrl=%2Fplan", + ); + }); +}); diff --git a/src/__tests__/auth-credentials-sign-in.test.ts b/src/__tests__/auth-credentials-sign-in.test.ts new file mode 100644 index 00000000..9a65db3b --- /dev/null +++ b/src/__tests__/auth-credentials-sign-in.test.ts @@ -0,0 +1,93 @@ +import { describe, it, expect } from "vitest"; +import { interpretSignInResponse } from "@/components/auth/credentials-sign-in"; +import { interpretAuthError } from "@/components/auth/auth-request"; +import { ApiError } from "@/lib/client-api"; + +describe("interpretSignInResponse", () => { + it("treats a callback URL without an error as signed in", () => { + expect(interpretSignInResponse(200, null, { url: "http://localhost:3000/plan" })).toEqual({ status: "ok" }); + }); + + it("maps wrong credentials and an unverified email", () => { + expect( + interpretSignInResponse(401, null, { + url: "http://localhost:3000/api/auth/error?error=CredentialsSignin&provider=credentials", + }), + ).toEqual({ status: "invalid" }); + expect( + interpretSignInResponse(401, null, { url: "http://localhost:3000/api/auth/error?error=EmailNotVerified" }), + ).toEqual({ status: "unverified" }); + }); + + it("reads the rate limit and its Retry-After instead of hanging", () => { + expect(interpretSignInResponse(429, "720", { error: "Too many requests. Please try again later." })).toEqual({ + status: "rate-limited", + retryAfterSeconds: 720, + }); + expect(interpretSignInResponse(429, null, null)).toEqual({ status: "rate-limited", retryAfterSeconds: null }); + }); + + it("doesn't mistake a CSRF rejection for a sign-in", () => { + expect(interpretSignInResponse(200, null, { url: "http://localhost:3000/auth/signin?csrf=true" })).toEqual({ + status: "unavailable", + }); + }); + + it("calls anything else unavailable", () => { + expect(interpretSignInResponse(500, null, null)).toEqual({ status: "unavailable" }); + expect(interpretSignInResponse(200, null, { error: "x" })).toEqual({ status: "unavailable" }); + expect(interpretSignInResponse(500, null, { url: "http://localhost:3000/" })).toEqual({ status: "unavailable" }); + expect( + interpretSignInResponse(401, null, { url: "http://localhost:3000/api/auth/error?error=Configuration" }), + ).toEqual({ status: "unavailable" }); + }); +}); + +describe("interpretAuthError", () => { + it("maps field issues by field", () => { + const error = new ApiError("Enter your name.", 400, { + error: "Enter your name.", + code: "INVALID_FIELDS", + issues: [ + { field: "name", message: "Enter your name." }, + { field: "email", message: "Enter an email address like name@example.com." }, + ], + }); + expect(interpretAuthError(error)).toEqual({ + ok: false, + kind: "fields", + issues: { name: "Enter your name.", email: "Enter an email address like name@example.com." }, + }); + }); + + it("passes on a 429 the route worded, and rewords the old default", () => { + expect(interpretAuthError(new ApiError("Too many reset requests. Retry in 3 minutes.", 429))).toEqual({ + ok: false, + kind: "rate-limited", + message: "Too many reset requests. Retry in 3 minutes.", + }); + expect(interpretAuthError(new ApiError("Too many requests. Please try again later.", 429))).toEqual({ + ok: false, + kind: "rate-limited", + message: "Too many requests. Retry in a few minutes.", + }); + }); + + it("returns known codes and hides server failures", () => { + expect(interpretAuthError(new ApiError("x", 400, { error: "x", code: "TOKEN_EXPIRED" }))).toEqual({ + ok: false, + kind: "code", + code: "TOKEN_EXPIRED", + }); + expect(interpretAuthError(new ApiError("x", 400, { code: "INVALID_BODY" }))).toEqual({ ok: false, kind: "failed" }); + expect(interpretAuthError(new ApiError("Failed", 500, { error: "Failed" }))).toEqual({ ok: false, kind: "failed" }); + expect(interpretAuthError(new TypeError("Failed to fetch"))).toEqual({ ok: false, kind: "failed" }); + }); + + it("passes on the 503 for a server that can't send email, so the form can say why", () => { + const error = new ApiError("Reset link not sent.", 503, { error: "Reset link not sent.", code: "EMAIL_NOT_CONFIGURED" }); + expect(interpretAuthError(error)).toEqual({ ok: false, kind: "code", code: "EMAIL_NOT_CONFIGURED" }); + // Any other 5xx code still reads as a failed request. + expect(interpretAuthError(new ApiError("x", 503, { code: "SOMETHING_ELSE" }))).toEqual({ ok: false, kind: "failed" }); + }); +}); diff --git a/src/__tests__/auth-messages.test.ts b/src/__tests__/auth-messages.test.ts new file mode 100644 index 00000000..17b318f1 --- /dev/null +++ b/src/__tests__/auth-messages.test.ts @@ -0,0 +1,159 @@ +import { describe, it, expect } from "vitest"; +import { + parseRetryAfter, + retryAfterText, + signInErrorBanner, + signInFailureFromCode, + signInFailureMessage, + SIGN_IN_MESSAGES, + REQUEST_FAILED, +} from "@/lib/auth-messages"; +import { + FIELD_MESSAGES, + collectErrors, + hasErrors, + validateCurrentPassword, + validateEmail, + validateName, + passwordTooLong, + validateNewPassword, + validatePasswordConfirmation, +} from "@/lib/auth-validation"; +import { + RESET_LINK_PROBLEMS, + parseVerifyEmailStatus, + resetPasswordTitle, + verifyEmailTitle, +} from "@/components/auth/link-copy"; + +describe("retryAfterText", () => { + it("uses whole seconds under a minute and whole minutes after", () => { + expect(retryAfterText(1)).toBe("Retry in 1 second."); + expect(retryAfterText(30)).toBe("Retry in 30 seconds."); + expect(retryAfterText(59.2)).toBe("Retry in 1 minute."); + expect(retryAfterText(60)).toBe("Retry in 1 minute."); + expect(retryAfterText(61)).toBe("Retry in 2 minutes."); + expect(retryAfterText(720)).toBe("Retry in 12 minutes."); + }); + + it("has a fallback when the wait is unknown", () => { + expect(retryAfterText(null)).toBe("Retry in a few minutes."); + expect(retryAfterText(undefined)).toBe("Retry in a few minutes."); + expect(retryAfterText(0)).toBe("Retry in a few minutes."); + expect(retryAfterText(Number.NaN)).toBe("Retry in a few minutes."); + }); +}); + +describe("parseRetryAfter", () => { + it("reads delta-seconds and HTTP dates", () => { + expect(parseRetryAfter("120")).toBe(120); + expect(parseRetryAfter(" 5 ")).toBe(5); + const now = Date.parse("2026-10-15T12:00:00Z"); + expect(parseRetryAfter("Thu, 15 Oct 2026 12:01:30 GMT", now)).toBe(90); + expect(parseRetryAfter("Thu, 15 Oct 2026 11:00:00 GMT", now)).toBe(0); + }); + + it("returns null for missing or unreadable values", () => { + expect(parseRetryAfter(null)).toBeNull(); + expect(parseRetryAfter("")).toBeNull(); + expect(parseRetryAfter("soon")).toBeNull(); + }); +}); + +describe("sign-in messages", () => { + it("maps next-auth codes without ever showing the code", () => { + expect(signInFailureFromCode("CredentialsSignin")).toEqual({ status: "invalid" }); + expect(signInFailureFromCode("EmailNotVerified")).toEqual({ status: "unverified" }); + expect(signInFailureFromCode("Configuration")).toEqual({ status: "unavailable" }); + expect(signInErrorBanner("Configuration")).toBe(SIGN_IN_MESSAGES.notAvailable); + expect(signInErrorBanner("<script>alert(1)</script>")).toBe(SIGN_IN_MESSAGES.notAvailable); + expect(signInErrorBanner("CredentialsSignin")).toBe(SIGN_IN_MESSAGES.invalid); + expect(signInErrorBanner("SessionRequired")).toBeNull(); + expect(signInErrorBanner(undefined)).toBeNull(); + }); + + it("words a rate limit with the wait", () => { + expect(signInFailureMessage({ status: "rate-limited", retryAfterSeconds: 720 })).toBe( + "Too many sign-in attempts. Retry in 12 minutes.", + ); + expect(signInFailureMessage({ status: "unavailable" })).toBe(SIGN_IN_MESSAGES.unavailable); + }); + + it("follows the voice rules: full sentences, no dashes, exclamation marks or 'please'", () => { + const all = [ + ...Object.values(SIGN_IN_MESSAGES), + ...Object.values(FIELD_MESSAGES), + ...Object.values(REQUEST_FAILED), + ]; + for (const text of all) { + expect(text).not.toMatch(/[—–!]|please|oops|successfully|something went wrong/i); + expect(text.endsWith(".")).toBe(true); + } + }); +}); + +describe("field validation", () => { + it("checks email presence and shape", () => { + expect(validateEmail("")).toBe(FIELD_MESSAGES.emailMissing); + expect(validateEmail(" ")).toBe(FIELD_MESSAGES.emailMissing); + expect(validateEmail("a@b")).toBe(FIELD_MESSAGES.emailInvalid); + expect(validateEmail("name@example")).toBe(FIELD_MESSAGES.emailInvalid); + expect(validateEmail(" name@example.com ")).toBeNull(); + }); + + it("only requires a password on sign-in, and 8 characters for a new one", () => { + expect(validateCurrentPassword("")).toBe(FIELD_MESSAGES.passwordMissing); + expect(validateCurrentPassword("short")).toBeNull(); + expect(validateNewPassword("")).toBe(FIELD_MESSAGES.newPasswordMissing); + expect(validateNewPassword("1234567")).toBe(FIELD_MESSAGES.passwordShort); + expect(validateNewPassword("12345678")).toBeNull(); + }); + + it("refuses a new password bcrypt would cut short, counting bytes, not characters", () => { + expect(validateNewPassword("a".repeat(72))).toBeNull(); + expect(validateNewPassword("a".repeat(73))).toBe(FIELD_MESSAGES.passwordLong); + // 37 accented letters are 74 bytes; 18 four-byte emoji are exactly 72. + expect(passwordTooLong("é".repeat(37))).toBe(true); + expect(passwordTooLong("\u{1F512}".repeat(18))).toBe(false); + expect(passwordTooLong("\u{1F512}".repeat(19))).toBe(true); + // A lone surrogate counts 3 bytes, as bcryptjs counts it. + expect(passwordTooLong("a".repeat(69) + "\uD800")).toBe(false); + expect(passwordTooLong("a".repeat(70) + "\uD800")).toBe(true); + // Sign-in still takes any password an account already has. + expect(validateCurrentPassword("a".repeat(200))).toBeNull(); + }); + + it("checks the confirmation and the name", () => { + expect(validatePasswordConfirmation("abcdefgh", "")).toBe(FIELD_MESSAGES.confirmMissing); + expect(validatePasswordConfirmation("abcdefgh", "abcdefgx")).toBe(FIELD_MESSAGES.passwordMismatch); + expect(validatePasswordConfirmation("abcdefgh", "abcdefgh")).toBeNull(); + expect(validateName(" ")).toBe(FIELD_MESSAGES.nameMissing); + expect(validateName("x".repeat(51))).toBe(FIELD_MESSAGES.nameLong); + expect(validateName("Ben")).toBeNull(); + }); + + it("collects only the failed checks", () => { + const errors = collectErrors({ email: null, password: "Enter your password." }); + expect(errors).toEqual({ password: "Enter your password." }); + expect(hasErrors(errors)).toBe(true); + expect(hasErrors(collectErrors({ email: null }))).toBe(false); + }); +}); + +describe("link screen titles", () => { + it("names the reset screen after the link's problem", () => { + expect(resetPasswordTitle(null)).toBe("Choose a new password"); + expect(resetPasswordTitle("invalid")).toBe("This reset link doesn't work"); + expect(resetPasswordTitle("expired")).toBe(RESET_LINK_PROBLEMS.expired.title); + expect(resetPasswordTitle("used")).toBe("Reset link already used"); + }); + + it("reads the verify page's status and titles it like its heading", () => { + expect(parseVerifyEmailStatus(undefined)).toBe("sent"); + expect(parseVerifyEmailStatus("toString")).toBe("sent"); + expect(parseVerifyEmailStatus("expired")).toBe("expired"); + expect(verifyEmailTitle("sent")).toBe("Verify your email"); + expect(verifyEmailTitle("expired")).toBe("Verification link expired"); + expect(verifyEmailTitle("invalid")).toBe("This verification link doesn't work"); + }); +}); diff --git a/src/__tests__/auth-options.test.ts b/src/__tests__/auth-options.test.ts new file mode 100644 index 00000000..a8f7e353 --- /dev/null +++ b/src/__tests__/auth-options.test.ts @@ -0,0 +1,189 @@ +/** + * Unit tests for the credentials sign-in in src/lib/auth-options.ts: + * wrong details return null (next-auth's CredentialsSignin), an unverified + * email throws a code the sign-in form explains, an unknown email costs a + * full bcrypt compare, next-auth errors land on the styled sign-in page, and + * a session ends once its account is deleted or its password changes. + */ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; + +const { findUnique, compare } = vi.hoisted(() => ({ + findUnique: vi.fn(), + compare: vi.fn(async (password: string) => password === "right-password"), +})); +vi.mock("@/lib/db", () => ({ prisma: { user: { findUnique } } })); +// Real hashing (for the dummy hash), stubbed compare (for speed and control). +vi.mock("bcryptjs", async (importOriginal) => { + const actual = await importOriginal<typeof import("bcryptjs")>(); + return { default: { ...actual.default, compare } }; +}); + +import bcrypt from "bcryptjs"; +import { encode, type JWT } from "next-auth/jwt"; +import { getServerSession } from "next-auth"; +import { + BCRYPT_COST, + SESSION_RECHECK_MS, + SESSION_REVOKED, + authOptions, + forgetSessionCheck, + getDummyHash, + passwordFingerprint, + refreshSessionToken, +} from "@/lib/auth-options"; +import { EMAIL_NOT_VERIFIED } from "@/lib/auth-messages"; + +type Authorize = (credentials: Record<string, string> | undefined) => Promise<unknown>; + +function authorize(credentials: Record<string, string> | undefined) { + const provider = authOptions.providers[0] as unknown as { options: { authorize: Authorize } }; + return provider.options.authorize(credentials); +} + +const user = { + id: "u1", + email: "me@example.com", + name: "Me", + passwordHash: "hash", + emailVerified: null as Date | null, +}; + +beforeEach(() => { + findUnique.mockReset(); + compare.mockClear(); + forgetSessionCheck("u1"); +}); + +afterEach(() => { + vi.unstubAllEnvs(); +}); + +describe("credentials authorize", () => { + it("returns the user and a password fingerprint for the right password", async () => { + findUnique.mockResolvedValue(user); + expect(await authorize({ email: " Me@Example.com ", password: "right-password" })).toEqual({ + id: "u1", + email: "me@example.com", + name: "Me", + pv: passwordFingerprint("hash"), + }); + expect(findUnique).toHaveBeenCalledWith({ where: { email: "me@example.com" } }); + }); + + it("returns null for a wrong password, an unknown email or missing fields", async () => { + findUnique.mockResolvedValue(user); + expect(await authorize({ email: "me@example.com", password: "wrong" })).toBeNull(); + findUnique.mockResolvedValue(null); + expect(await authorize({ email: "nobody@example.com", password: "right-password" })).toBeNull(); + expect(await authorize(undefined)).toBeNull(); + }); + + it("throws EmailNotVerified only when verification is required and the password matched", async () => { + vi.stubEnv("REQUIRE_EMAIL_VERIFICATION", "true"); + findUnique.mockResolvedValue(user); + await expect(authorize({ email: "me@example.com", password: "right-password" })).rejects.toThrow( + EMAIL_NOT_VERIFIED, + ); + expect(await authorize({ email: "me@example.com", password: "wrong" })).toBeNull(); + + findUnique.mockResolvedValue({ ...user, emailVerified: new Date() }); + expect(await authorize({ email: "me@example.com", password: "right-password" })).toMatchObject({ id: "u1" }); + }); +}); + +describe("unknown emails", () => { + it("compare against a real bcrypt hash at the stored cost", async () => { + const dummy = await getDummyHash(); + expect(bcrypt.getRounds(dummy)).toBe(BCRYPT_COST); + expect(dummy).toHaveLength(60); + expect(await getDummyHash()).toBe(dummy); + }, 20_000); + + it("run the full compare, not a shortcut", async () => { + findUnique.mockResolvedValue(null); + await authorize({ email: "nobody@example.com", password: "guess" }); + expect(compare).toHaveBeenCalledWith("guess", await getDummyHash()); + }, 20_000); +}); + +describe("refreshSessionToken", () => { + const NOW = 1_800_000_000_000; + const token = (pv: string = passwordFingerprint("hash")): JWT => ({ id: "u1", pv }) as JWT; + + it("ends sessions with no account id or fingerprint (tokens from before the check)", async () => { + await expect(refreshSessionToken({} as JWT, NOW)).rejects.toThrow(SESSION_REVOKED); + await expect(refreshSessionToken({ id: "u1" } as JWT, NOW)).rejects.toThrow(SESSION_REVOKED); + expect(findUnique).not.toHaveBeenCalled(); + }); + + it("keeps a session while the password is unchanged, re-reading at most every 5 minutes", async () => { + findUnique.mockResolvedValue({ passwordHash: "hash" }); + expect(await refreshSessionToken(token(), NOW)).toMatchObject({ id: "u1" }); + await refreshSessionToken(token(), NOW + SESSION_RECHECK_MS - 1); + expect(findUnique).toHaveBeenCalledOnce(); + await refreshSessionToken(token(), NOW + SESSION_RECHECK_MS); + expect(findUnique).toHaveBeenCalledTimes(2); + }); + + it("ends a session after a password change or account deletion", async () => { + findUnique.mockResolvedValueOnce({ passwordHash: "new-hash" }); + await expect(refreshSessionToken(token(), NOW)).rejects.toThrow(SESSION_REVOKED); + findUnique.mockResolvedValueOnce(null); + await expect(refreshSessionToken(token(), NOW)).rejects.toThrow(SESSION_REVOKED); + }); + + it("re-reads at once after forgetSessionCheck", async () => { + findUnique.mockResolvedValueOnce({ passwordHash: "hash" }); + await refreshSessionToken(token(), NOW); + forgetSessionCheck("u1"); + findUnique.mockResolvedValueOnce({ passwordHash: "new-hash" }); + await expect(refreshSessionToken(token(), NOW + 1000)).rejects.toThrow(SESSION_REVOKED); + }); + + it("keeps the session through a database failure and checks again next time", async () => { + findUnique.mockRejectedValueOnce(new Error("db down")); + expect(await refreshSessionToken(token(), NOW)).toMatchObject({ id: "u1" }); + findUnique.mockResolvedValueOnce({ passwordHash: "hash" }); + await refreshSessionToken(token(), NOW + 1000); + expect(findUnique).toHaveBeenCalledTimes(2); + }); +}); + +describe("getServerSession with a revoked token", () => { + const SECRET = "test-secret-for-session-revocation"; + const COOKIE = "next-auth.session-token"; + + async function readSession(pv: string) { + vi.stubEnv("NEXTAUTH_SECRET", SECRET); + const jwe = await encode({ token: { sub: "u1", id: "u1", pv, email: "me@example.com" }, secret: SECRET }); + const headers = new Map<string, string[]>(); + const res = { + getHeader: (name: string) => headers.get(name.toLowerCase()), + setHeader: (name: string, value: string[]) => headers.set(name.toLowerCase(), value), + }; + const req = { headers: { host: "localhost:3000" }, cookies: { [COOKIE]: jwe } }; + const session = await getServerSession(req as never, res as never, authOptions); + return { session, setCookies: headers.get("set-cookie") ?? [] }; + } + + it("returns the session while the password matches", async () => { + findUnique.mockResolvedValue({ passwordHash: "hash" }); + const { session } = await readSession(passwordFingerprint("hash")); + expect(session?.user).toMatchObject({ id: "u1" }); + }); + + it("returns null and clears the cookie once the password changed", async () => { + findUnique.mockResolvedValue({ passwordHash: "new-hash" }); + const { session, setCookies } = await readSession(passwordFingerprint("hash")); + expect(session).toBeNull(); + const cleared = setCookies.find((cookie) => cookie.startsWith(`${COOKIE}=;`)); + expect(cleared).toMatch(/Max-Age=0/i); + }); +}); + +describe("pages", () => { + it("sends next-auth errors to the sign-in page", () => { + expect(authOptions.pages?.signIn).toBe("/auth/signin"); + expect(authOptions.pages?.error).toBe("/auth/signin"); + }); +}); diff --git a/src/__tests__/auth-routes.test.ts b/src/__tests__/auth-routes.test.ts new file mode 100644 index 00000000..06e22a69 --- /dev/null +++ b/src/__tests__/auth-routes.test.ts @@ -0,0 +1,400 @@ +/** + * Unit tests for the auth API routes: field issues the forms map onto + * fields, rate-limit wording, reset-link codes, anti-enumeration answers + * (emails go out after the response, so both answers take the same time), + * and verification links that always land on a page instead of JSON. + */ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { NextRequest } from "next/server"; + +const { prisma, afterTasks } = vi.hoisted(() => ({ + prisma: { + user: { findUnique: vi.fn(), update: vi.fn(), create: vi.fn() }, + userGameState: { create: vi.fn() }, + $transaction: vi.fn(), + }, + afterTasks: [] as Array<() => unknown>, +})); + +vi.mock("@/lib/db", () => ({ prisma })); +// after() needs a request scope; collect the tasks and run them by hand. +vi.mock("next/server", async (importOriginal) => ({ + ...(await importOriginal<typeof import("next/server")>()), + after: (task: () => unknown) => { + afterTasks.push(task); + }, +})); +vi.mock("@/lib/tokens", () => ({ + inspectToken: vi.fn(), + redeemToken: vi.fn(), + createPasswordResetToken: vi.fn(async () => "reset-token"), + createEmailVerificationToken: vi.fn(async () => "verify-token"), +})); +vi.mock("@/lib/email/provider", () => ({ emailProvider: { send: vi.fn(async () => undefined) } })); +vi.mock("bcryptjs", () => ({ default: { hash: vi.fn(async () => "hashed") } })); + +import { inspectToken, redeemToken } from "@/lib/tokens"; +import { emailProvider } from "@/lib/email/provider"; +import bcrypt from "bcryptjs"; +import { authEmailLimiter, authTokenLimiter, signupLimiter } from "@/lib/rate-limit"; +import { authEmailAddressLimiter, signInFailureLimiter } from "@/app/api/auth/_lib/limits"; +import { POST as signup } from "@/app/api/auth/signup/route"; +import { POST as forgotPassword } from "@/app/api/auth/forgot-password/route"; +import { POST as resendVerification } from "@/app/api/auth/resend-verification/route"; +import { POST as resetPassword } from "@/app/api/auth/reset-password/route"; +import { GET as verifyEmail } from "@/app/api/auth/verify-email/route"; + +const redeemTokenMock = vi.mocked(redeemToken); +const inspectTokenMock = vi.mocked(inspectToken); + +let ipCounter = 0; +function post(path: string, body: unknown, ip = `10.0.0.${++ipCounter}`) { + return new NextRequest(`http://localhost:3000${path}`, { + method: "POST", + headers: { "content-type": "application/json", "x-real-ip": ip }, + body: typeof body === "string" ? body : JSON.stringify(body), + }); +} + +function get(path: string, ip = `10.0.1.${++ipCounter}`) { + return new NextRequest(`http://localhost:3000${path}`, { headers: { "x-real-ip": ip } }); +} + +/** Run what the routes deferred until after their response. */ +async function runAfterTasks() { + const tasks = afterTasks.splice(0); + for (const task of tasks) await task(); +} + +beforeEach(() => { + vi.clearAllMocks(); + afterTasks.length = 0; + authEmailLimiter.reset(); + authEmailAddressLimiter.reset(); + authTokenLimiter.reset(); + signupLimiter.reset(); +}); + +afterEach(() => { + vi.unstubAllEnvs(); +}); + +describe("POST /api/auth/signup", () => { + it("returns one issue per field in the forms' words", async () => { + const res = await signup(post("/api/auth/signup", { name: " ", email: "a@b", password: "short" })); + expect(res.status).toBe(400); + const body = await res.json(); + expect(body.code).toBe("INVALID_FIELDS"); + expect(body.issues).toEqual([ + { field: "name", message: "Enter your name." }, + { field: "email", message: "Enter an email address like name@example.com." }, + { field: "password", message: "Use at least 8 characters." }, + ]); + }); + + it("answers 400 for a body that isn't JSON", async () => { + const res = await signup(post("/api/auth/signup", "not json")); + expect(res.status).toBe(400); + expect((await res.json()).code).toBe("INVALID_BODY"); + }); + + it("gives the same 201 for a new and a taken email, and sends the link after answering", async () => { + vi.stubEnv("REQUIRE_EMAIL_VERIFICATION", "true"); + prisma.$transaction.mockResolvedValueOnce({ id: "u1", email: "new@example.com", name: "New" }); + const created = await signup(post("/api/auth/signup", { name: "New", email: "New@Example.com", password: "12345678" })); + expect(created.status).toBe(201); + expect(emailProvider.send).not.toHaveBeenCalled(); + await runAfterTasks(); + expect(emailProvider.send).toHaveBeenCalledOnce(); + + prisma.$transaction.mockRejectedValueOnce(Object.assign(new Error("unique"), { code: "P2002" })); + const taken = await signup(post("/api/auth/signup", { name: "Old", email: "old@example.com", password: "12345678" })); + expect(taken.status).toBe(201); + expect(await taken.json()).toEqual(await created.json()); + expect(afterTasks).toHaveLength(0); + // Both paths hash the password, so a taken email isn't the faster answer. + expect(bcrypt.hash).toHaveBeenCalledTimes(2); + expect(bcrypt.hash).toHaveBeenCalledWith("12345678", 12); + }); + + it("sends no verification email when sign-in doesn't require one", async () => { + prisma.$transaction.mockResolvedValueOnce({ id: "u1", email: "new@example.com", name: "New" }); + const res = await signup(post("/api/auth/signup", { name: "New", email: "new@example.com", password: "12345678" })); + expect(res.status).toBe(201); + await runAfterTasks(); + expect(emailProvider.send).not.toHaveBeenCalled(); + }); + + it("hides server failures behind a plain message", async () => { + prisma.$transaction.mockRejectedValueOnce(new Error("connection refused")); + const res = await signup(post("/api/auth/signup", { name: "A", email: "a@example.com", password: "12345678" })); + expect(res.status).toBe(500); + expect((await res.json()).error).toBe("Account not created. Check your connection and retry."); + }); +}); + +describe("POST /api/auth/forgot-password", () => { + it("rejects a malformed email with a field issue instead of claiming success", async () => { + const res = await forgotPassword(post("/api/auth/forgot-password", { email: "a@b" })); + expect(res.status).toBe(400); + expect((await res.json()).issues).toEqual([ + { field: "email", message: "Enter an email address like name@example.com." }, + ]); + }); + + it("answers the same whether or not the account exists, and sends after answering", async () => { + prisma.user.findUnique.mockResolvedValueOnce(null); + const missing = await forgotPassword(post("/api/auth/forgot-password", { email: "nobody@example.com" })); + prisma.user.findUnique.mockResolvedValueOnce({ id: "u1", email: "me@example.com", name: "Me" }); + const found = await forgotPassword(post("/api/auth/forgot-password", { email: "Me@Example.com" })); + expect(missing.status).toBe(200); + expect(await missing.json()).toEqual(await found.json()); + expect(prisma.user.findUnique).toHaveBeenLastCalledWith( + expect.objectContaining({ where: { email: "me@example.com" } }), + ); + expect(emailProvider.send).not.toHaveBeenCalled(); + await runAfterTasks(); + expect(emailProvider.send).toHaveBeenCalledOnce(); + expect(vi.mocked(emailProvider.send).mock.calls[0][0]).toBe("me@example.com"); + }); + + it("limits requests per address across networks", async () => { + prisma.user.findUnique.mockResolvedValue(null); + let res: Response | undefined; + for (let i = 0; i < 200; i++) { + res = await forgotPassword(post("/api/auth/forgot-password", { email: "target@example.com" })); + if (res.status === 429) break; + } + expect(res?.status).toBe(429); + expect((await res!.json()).error).toMatch(/^Too many reset requests\. Retry in \d+ minutes?\.$/); + // Another address is unaffected. + expect((await forgotPassword(post("/api/auth/forgot-password", { email: "other@example.com" }))).status).toBe(200); + }); + + it("says no link went out, for every address, when a production server can't send email", async () => { + vi.stubEnv("NODE_ENV", "production"); + vi.stubEnv("EMAIL_PROVIDER", "console"); + vi.stubEnv("ALLOW_TEST_AUTH", ""); + prisma.user.findUnique.mockResolvedValue({ id: "u1", email: "me@example.com", name: "Me" }); + const known = await forgotPassword(post("/api/auth/forgot-password", { email: "me@example.com" })); + const unknown = await forgotPassword(post("/api/auth/forgot-password", { email: "nobody@example.com" })); + expect(known.status).toBe(503); + const body = await known.json(); + expect(body).toEqual({ + code: "EMAIL_NOT_CONFIGURED", + error: "Reset link not sent. Email isn't set up on this Study Bot server. Ask whoever runs the server to turn on email.", + }); + expect(await unknown.json()).toEqual(body); + expect(prisma.user.findUnique).not.toHaveBeenCalled(); + expect(afterTasks).toHaveLength(0); + + // SMTP delivers, so the usual answer comes back. + vi.stubEnv("EMAIL_PROVIDER", "smtp"); + expect((await forgotPassword(post("/api/auth/forgot-password", { email: "me@example.com" }))).status).toBe(200); + }); + + it("words its rate limit with the wait", async () => { + const ip = "10.9.9.9"; + let res: Response | undefined; + for (let i = 0; i < 200; i++) { + res = await forgotPassword(post("/api/auth/forgot-password", { email: "x" }, ip)); + if (res.status === 429) break; + } + expect(res?.status).toBe(429); + expect(res?.headers.get("Retry-After")).toMatch(/^\d+$/); + expect((await res!.json()).error).toMatch(/^Too many reset requests\. Retry in \d+ minutes?\.$/); + }); +}); + +describe("POST /api/auth/resend-verification", () => { + it("validates the email and never says whether an account exists", async () => { + expect((await resendVerification(post("/api/auth/resend-verification", {}))).status).toBe(400); + + prisma.user.findUnique.mockResolvedValueOnce(null); + const missing = await resendVerification(post("/api/auth/resend-verification", { email: "x@example.com" })); + prisma.user.findUnique.mockResolvedValueOnce({ id: "u1", email: "y@example.com", name: "Y", emailVerified: null }); + const pending = await resendVerification(post("/api/auth/resend-verification", { email: "y@example.com" })); + prisma.user.findUnique.mockResolvedValueOnce({ id: "u2", email: "z@example.com", name: "Z", emailVerified: new Date() }); + const verified = await resendVerification(post("/api/auth/resend-verification", { email: "z@example.com" })); + const answer = await pending.json(); + expect(await missing.json()).toEqual(answer); + expect(await verified.json()).toEqual(answer); + expect(emailProvider.send).not.toHaveBeenCalled(); + await runAfterTasks(); + expect(emailProvider.send).toHaveBeenCalledOnce(); + expect(vi.mocked(emailProvider.send).mock.calls[0][0]).toBe("y@example.com"); + }); + + it("says no link went out when a production server can't send email", async () => { + vi.stubEnv("NODE_ENV", "production"); + vi.stubEnv("EMAIL_PROVIDER", "console"); + vi.stubEnv("ALLOW_TEST_AUTH", ""); + const res = await resendVerification(post("/api/auth/resend-verification", { email: "y@example.com" })); + expect(res.status).toBe(503); + expect(await res.json()).toEqual({ + code: "EMAIL_NOT_CONFIGURED", + error: "New link not sent. Email isn't set up on this Study Bot server. Ask whoever runs the server to turn on email.", + }); + expect(prisma.user.findUnique).not.toHaveBeenCalled(); + + // A CI e2e server reads links from the database, so it still makes them. + vi.stubEnv("ALLOW_TEST_AUTH", "true"); + vi.stubEnv("CI", "true"); + vi.stubEnv("NEXTAUTH_URL", "http://localhost:3000"); + prisma.user.findUnique.mockResolvedValueOnce(null); + expect((await resendVerification(post("/api/auth/resend-verification", { email: "y@example.com" }))).status).toBe(200); + }); +}); + +describe("POST /api/auth/reset-password", () => { + // The transaction's client: the claim and the password write both go through it. + const tx = { user: { update: vi.fn() } }; + + beforeEach(() => { + signInFailureLimiter.reset(); + prisma.$transaction.mockImplementation(async (work: (client: typeof tx) => unknown) => work(tx)); + tx.user.update.mockReset(); + tx.user.update.mockResolvedValue({ email: "me@example.com" }); + }); + + afterEach(() => { + prisma.$transaction.mockReset(); + }); + + it("maps a short password to the password field", async () => { + const res = await resetPassword(post("/api/auth/reset-password", { token: "t", password: "short" })); + expect(res.status).toBe(400); + expect((await res.json()).issues).toEqual([{ field: "password", message: "Use at least 8 characters." }]); + expect(redeemTokenMock).not.toHaveBeenCalled(); + }); + + it("refuses a password longer than bcrypt hashes, rather than cutting it short", async () => { + // 37 accented letters: 37 characters, 74 bytes. + const res = await resetPassword(post("/api/auth/reset-password", { token: "t", password: "\u00e9".repeat(37) })); + expect(res.status).toBe(400); + expect((await res.json()).issues).toEqual([{ field: "password", message: "Use a shorter password." }]); + expect(inspectTokenMock).not.toHaveBeenCalled(); + }); + + it("returns a code for each kind of bad link, before any bcrypt work", async () => { + for (const [status, code] of [ + ["expired", "TOKEN_EXPIRED"], + ["used", "TOKEN_USED"], + ["invalid", "TOKEN_INVALID"], + ] as const) { + inspectTokenMock.mockResolvedValueOnce(status === "invalid" ? { status } : { status, userId: "u1" }); + const res = await resetPassword(post("/api/auth/reset-password", { token: "t", password: "12345678" })); + expect(res.status).toBe(400); + expect((await res.json()).code).toBe(code); + } + expect(bcrypt.hash).not.toHaveBeenCalled(); + expect(redeemTokenMock).not.toHaveBeenCalled(); + expect(tx.user.update).not.toHaveBeenCalled(); + }); + + it("treats a missing token as an invalid link", async () => { + inspectTokenMock.mockResolvedValueOnce({ status: "invalid" }); + const res = await resetPassword(post("/api/auth/reset-password", { password: "12345678" })); + expect((await res.json()).code).toBe("TOKEN_INVALID"); + expect(inspectTokenMock).toHaveBeenCalledWith("", "PASSWORD_RESET"); + }); + + it("claims the link and saves the password in one transaction", async () => { + inspectTokenMock.mockResolvedValueOnce({ status: "valid", userId: "u1" }); + redeemTokenMock.mockResolvedValueOnce({ status: "valid", userId: "u1" }); + const res = await resetPassword(post("/api/auth/reset-password", { token: "t", password: "12345678" })); + expect(res.status).toBe(200); + expect(redeemTokenMock).toHaveBeenCalledWith("t", "PASSWORD_RESET", tx); + expect(tx.user.update).toHaveBeenCalledWith({ + where: { id: "u1" }, + data: { passwordHash: "hashed" }, + select: { email: true }, + }); + expect(prisma.user.update).not.toHaveBeenCalled(); + // The hash is ready before the transaction starts. + expect(vi.mocked(bcrypt.hash).mock.invocationCallOrder[0]).toBeLessThan( + prisma.$transaction.mock.invocationCallOrder[0], + ); + }); + + it("answers 500 when the password isn't saved, with the claim inside the transaction that failed", async () => { + inspectTokenMock.mockResolvedValueOnce({ status: "valid", userId: "u1" }); + redeemTokenMock.mockResolvedValueOnce({ status: "valid", userId: "u1" }); + tx.user.update.mockRejectedValueOnce(new Error("connection reset")); + const res = await resetPassword(post("/api/auth/reset-password", { token: "t", password: "12345678" })); + expect(res.status).toBe(500); + expect((await res.json()).error).toBe("Password not changed. Check your connection and retry."); + // The claim ran on the transaction's client, so the database rolls it + // back with the failed write and the same link works for a retry. + expect(redeemTokenMock).toHaveBeenCalledWith("t", "PASSWORD_RESET", tx); + }); + + it("says the link was used when another request claimed it first", async () => { + inspectTokenMock.mockResolvedValueOnce({ status: "valid", userId: "u1" }); + redeemTokenMock.mockResolvedValueOnce({ status: "used", userId: "u1" }); + const res = await resetPassword(post("/api/auth/reset-password", { token: "t", password: "12345678" })); + expect(res.status).toBe(400); + expect((await res.json()).code).toBe("TOKEN_USED"); + expect(tx.user.update).not.toHaveBeenCalled(); + }); + + it("lifts the sign-in lock on the account, so the new password works at once", async () => { + for (let i = 0; i < 400; i++) signInFailureLimiter.start("me@example.com"); + expect(signInFailureLimiter.start("me@example.com").allowed).toBe(false); + + inspectTokenMock.mockResolvedValueOnce({ status: "valid", userId: "u1" }); + redeemTokenMock.mockResolvedValueOnce({ status: "valid", userId: "u1" }); + tx.user.update.mockResolvedValueOnce({ email: "Me@Example.com" }); + expect((await resetPassword(post("/api/auth/reset-password", { token: "t", password: "12345678" }))).status).toBe(200); + expect(signInFailureLimiter.start("me@example.com").allowed).toBe(true); + }); +}); + +describe("GET /api/auth/verify-email", () => { + function location(res: Response) { + return res.headers.get("location"); + } + + it("lands on sign-in with a banner when the link works", async () => { + redeemTokenMock.mockResolvedValueOnce({ status: "valid", userId: "u1" }); + const res = await verifyEmail(get("/api/auth/verify-email?token=t")); + expect(res.status).toBe(303); + expect(location(res)).toBe("http://localhost:3000/auth/signin?verified=true"); + }); + + it("lands on the verify page, never JSON, when the link is missing, bad or expired", async () => { + const missing = await verifyEmail(get("/api/auth/verify-email")); + expect(location(missing)).toBe("http://localhost:3000/auth/verify-email?status=invalid"); + + redeemTokenMock.mockResolvedValueOnce({ status: "invalid" }); + expect(location(await verifyEmail(get("/api/auth/verify-email?token=t")))).toBe( + "http://localhost:3000/auth/verify-email?status=invalid", + ); + + redeemTokenMock.mockResolvedValueOnce({ status: "expired", userId: "u1" }); + expect(location(await verifyEmail(get("/api/auth/verify-email?token=t")))).toBe( + "http://localhost:3000/auth/verify-email?status=expired", + ); + }); + + it("sends an already verified account to sign-in when the link is reused", async () => { + redeemTokenMock.mockResolvedValueOnce({ status: "used", userId: "u1" }); + prisma.user.findUnique.mockResolvedValueOnce({ emailVerified: new Date() }); + expect(location(await verifyEmail(get("/api/auth/verify-email?token=t")))).toBe( + "http://localhost:3000/auth/signin?verified=true", + ); + + redeemTokenMock.mockResolvedValueOnce({ status: "used", userId: "u1" }); + prisma.user.findUnique.mockResolvedValueOnce({ emailVerified: null }); + expect(location(await verifyEmail(get("/api/auth/verify-email?token=t")))).toBe( + "http://localhost:3000/auth/verify-email?status=invalid", + ); + }); + + it("lands on a page when the server fails", async () => { + redeemTokenMock.mockRejectedValueOnce(new Error("db down")); + expect(location(await verifyEmail(get("/api/auth/verify-email?token=t")))).toBe( + "http://localhost:3000/auth/verify-email?status=failed", + ); + }); +}); diff --git a/src/__tests__/auth-signin-limits.test.ts b/src/__tests__/auth-signin-limits.test.ts new file mode 100644 index 00000000..99dd24b0 --- /dev/null +++ b/src/__tests__/auth-signin-limits.test.ts @@ -0,0 +1,289 @@ +/** + * Unit tests for the sign-in limits in src/app/api/auth/[...nextauth]/route.ts + * and src/app/api/auth/_lib/limits.ts: wrong passwords count per account + * from any network, right passwords and sign-out never use up attempts, + * the limiter reads the same email next-auth checks, and a browser that + * signed in to the account before (known-device.ts) can't be locked out. + */ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { NextRequest } from "next/server"; + +const { handler } = vi.hoisted(() => ({ handler: vi.fn() })); +vi.mock("next-auth", () => ({ default: () => handler })); +vi.mock("@/lib/auth-options", () => ({ + authOptions: {}, + SECURE_COOKIES: false, + SESSION_COOKIE_NAME: "next-auth.session-token", +})); + +import { POST } from "@/app/api/auth/[...nextauth]/route"; +import { + createFailureLimiter, + readSignInEmail, + signInErrorCode, + signInFailureLimiter, +} from "@/app/api/auth/_lib/limits"; +import { + KNOWN_DEVICE_COOKIE, + KNOWN_DEVICE_MAX_AGE_S, + isKnownDevice, + knownDeviceValue, +} from "@/app/api/auth/_lib/known-device"; +import { authLimiter } from "@/lib/rate-limit"; + +const BASE = "http://localhost:3000/api/auth"; +const FAILED = `${BASE}/error?error=CredentialsSignin&provider=credentials`; + +function nextAuthAnswer(url: string, status: number) { + return new Response(JSON.stringify({ url }), { status, headers: { "content-type": "application/json" } }); +} + +let ipCounter = 0; +function signInRequest( + email: string, + ip = `10.1.${Math.floor(++ipCounter / 250)}.${ipCounter % 250}`, + cookie?: string, +) { + return new NextRequest(`${BASE}/callback/credentials`, { + method: "POST", + headers: { + "content-type": "application/x-www-form-urlencoded", + "x-real-ip": ip, + ...(cookie ? { cookie } : {}), + }, + body: new URLSearchParams({ email, password: "guess", csrfToken: "t", json: "true" }), + }); +} + +/** next-auth's answer to a right password: the session cookie and the callback URL. */ +function signedInAnswer() { + const headers = new Headers({ "content-type": "application/json" }); + headers.append("Set-Cookie", "next-auth.session-token=jwt; Path=/; HttpOnly; SameSite=Lax"); + headers.append("Set-Cookie", "next-auth.callback-url=%2F; Path=/; SameSite=Lax"); + return new Response(JSON.stringify({ url: "http://localhost:3000/" }), { status: 200, headers }); +} + +/** The known-device cookie a response set, as a request Cookie header. */ +function knownDeviceFrom(response: Response): string | undefined { + const header = response.headers.getSetCookie().find((c) => c.startsWith(`${KNOWN_DEVICE_COOKIE}=`)); + return header?.split(";", 1)[0]; +} + +function context(...nextauth: string[]) { + return { params: Promise.resolve({ nextauth }) }; +} + +beforeEach(() => { + handler.mockReset(); + authLimiter.reset(); + signInFailureLimiter.reset(); + vi.stubEnv("NEXTAUTH_SECRET", "unit-test-secret"); +}); + +afterEach(() => { + vi.unstubAllEnvs(); +}); + +describe("createFailureLimiter", () => { + const WINDOW = 1000; + + it("blocks a key at its cap until the oldest failure leaves the window", () => { + const limiter = createFailureLimiter({ maxFailures: 2, windowMs: WINDOW }); + expect(limiter.start("a", 0).allowed).toBe(true); + expect(limiter.start("a", 100).allowed).toBe(true); + expect(limiter.start("a", 200)).toEqual({ allowed: false, retryAfterMs: 800 }); + expect(limiter.start("b", 200).allowed).toBe(true); + expect(limiter.start("a", 1001).allowed).toBe(true); + }); + + it("takes back a forgiven attempt", () => { + const limiter = createFailureLimiter({ maxFailures: 1, windowMs: WINDOW }); + const first = limiter.start("a", 0); + expect(first.allowed).toBe(true); + if (first.allowed) limiter.forgive("a", first.stamp); + expect(limiter.start("a", 10).allowed).toBe(true); + expect(limiter.start("a", 20).allowed).toBe(false); + }); + + it("clears one key and leaves the others", () => { + const limiter = createFailureLimiter({ maxFailures: 1, windowMs: WINDOW }); + limiter.start("a", 0); + limiter.start("b", 0); + limiter.clear("a"); + expect(limiter.start("a", 10).allowed).toBe(true); + expect(limiter.start("b", 10).allowed).toBe(false); + }); + + it("counts an attempt while it runs, so parallel guesses can't pass the cap", () => { + const limiter = createFailureLimiter({ maxFailures: 3, windowMs: WINDOW }); + const started = [0, 0, 0, 0, 0].map(() => limiter.start("a", 5)); + expect(started.filter((attempt) => attempt.allowed)).toHaveLength(3); + }); +}); + +describe("readSignInEmail", () => { + it("reads the last email in a form body, as next-auth does", async () => { + const request = new Request(`${BASE}/callback/credentials`, { + method: "POST", + headers: { "content-type": "application/x-www-form-urlencoded" }, + body: "email=decoy%40example.com&email=%20Me%40Example.com%20&password=x", + }); + expect(await readSignInEmail(request)).toBe("me@example.com"); + // The body is still there for next-auth. + expect(await request.text()).toContain("password=x"); + }); + + it("reads a JSON body and ignores anything that isn't an email string", async () => { + const json = (body: string) => + new Request(BASE, { method: "POST", headers: { "content-type": "application/json" }, body }); + expect(await readSignInEmail(json('{"email":"A@B.co"}'))).toBe("a@b.co"); + expect(await readSignInEmail(json('{"email":["a@b.co"]}'))).toBeNull(); + expect(await readSignInEmail(json("not json"))).toBeNull(); + }); +}); + +describe("signInErrorCode", () => { + it("reads the code from a JSON answer or a redirect", async () => { + expect(await signInErrorCode(nextAuthAnswer(FAILED, 401))).toBe("CredentialsSignin"); + expect(await signInErrorCode(nextAuthAnswer("http://localhost:3000/", 200))).toBeNull(); + const redirect = new Response(null, { status: 302, headers: { location: `${BASE}/error?error=EmailNotVerified` } }); + expect(await signInErrorCode(redirect)).toBe("EmailNotVerified"); + }); +}); + +describe("POST /api/auth/[...nextauth]", () => { + it("never limits sign-out or session updates", async () => { + handler.mockResolvedValue(new Response(null, { status: 200 })); + for (let i = 0; i < 150; i++) { + const res = await POST(signInRequest("me@example.com", "10.2.0.1"), context("signout")); + expect(res.status).toBe(200); + } + const res = await POST(signInRequest("me@example.com", "10.2.0.1"), context("session")); + expect(res.status).toBe(200); + expect(handler).toHaveBeenCalledTimes(151); + }); + + it("limits wrong passwords per account across networks, with a wait", async () => { + handler.mockImplementation(async () => nextAuthAnswer(FAILED, 401)); + let res: Response | undefined; + let attempts = 0; + for (; attempts < 1000; attempts++) { + const answer: Response = await POST(signInRequest("victim@example.com"), context("callback", "credentials")); + res = answer; + if (answer.status === 429) break; + } + expect(res?.status).toBe(429); + expect(Number(res?.headers.get("Retry-After"))).toBeGreaterThan(0); + expect((await res!.json()).code).toBe("RATE_LIMITED"); + expect(handler).toHaveBeenCalledTimes(attempts); + + // The same email typed differently is the same account. + expect((await POST(signInRequest(" VICTIM@example.com "), context("callback", "credentials"))).status).toBe(429); + // Another account is unaffected. + expect((await POST(signInRequest("me@example.com"), context("callback", "credentials"))).status).toBe(401); + }); + + it("doesn't count right passwords or unverified emails", async () => { + handler.mockImplementation(async () => nextAuthAnswer("http://localhost:3000/", 200)); + for (let i = 0; i < 400; i++) { + const res = await POST(signInRequest("me@example.com"), context("callback", "credentials")); + expect(res.status).toBe(200); + } + handler.mockImplementation(async () => nextAuthAnswer(`${BASE}/error?error=EmailNotVerified`, 401)); + for (let i = 0; i < 400; i++) { + const res = await POST(signInRequest("me@example.com"), context("callback", "credentials")); + expect(res.status).toBe(401); + } + }); +}); + +describe("known-device cookies", () => { + const NOW = Date.parse("2026-10-16T12:00:00Z"); + + it("verifies only for the account and server it was made for, and only for 90 days", () => { + const value = knownDeviceValue("me@example.com", NOW)!; + expect(value).toMatch(/^v1\.\d+\.[\w-]+$/); + expect(isKnownDevice(value, "me@example.com", NOW)).toBe(true); + expect(isKnownDevice(value, "me@example.com", NOW + (KNOWN_DEVICE_MAX_AGE_S - 60) * 1000)).toBe(true); + expect(isKnownDevice(value, "me@example.com", NOW + (KNOWN_DEVICE_MAX_AGE_S + 60) * 1000)).toBe(false); + expect(isKnownDevice(value, "victim@example.com", NOW)).toBe(false); + + const [version, issued, mac] = value.split("."); + // A changed issue time breaks the signature, so the 90 days can't be stretched. + expect(isKnownDevice(`${version}.${Number(issued) + 1}.${mac}`, "me@example.com", NOW)).toBe(false); + expect(isKnownDevice(`${version}.${issued}.${mac.slice(0, -2)}AA`, "me@example.com", NOW)).toBe(false); + expect(isKnownDevice("v1.1.x", "me@example.com", NOW)).toBe(false); + expect(isKnownDevice(undefined, "me@example.com", NOW)).toBe(false); + + vi.stubEnv("NEXTAUTH_SECRET", "another-server"); + expect(isKnownDevice(value, "me@example.com", NOW)).toBe(false); + }); + + it("does nothing without a secret", () => { + vi.stubEnv("NEXTAUTH_SECRET", ""); + vi.stubEnv("AUTH_SECRET", ""); + expect(knownDeviceValue("me@example.com", NOW)).toBeNull(); + expect(isKnownDevice("v1.1.abc", "me@example.com", NOW)).toBe(false); + }); +}); + +describe("POST /api/auth/[...nextauth] with a known device", () => { + /** Trip the account's limit from many networks, as an attacker would. */ + async function lockOut(email: string) { + handler.mockImplementation(async () => nextAuthAnswer(FAILED, 401)); + for (let i = 0; i < 1000; i++) { + const res = await POST(signInRequest(email), context("callback", "credentials")); + if (res.status === 429) return; + } + throw new Error("the limit never tripped"); + } + + it("marks the browser after a right password, and only then", async () => { + handler.mockImplementation(async () => signedInAnswer()); + const res: Response = await POST(signInRequest(" Me@Example.com "), context("callback", "credentials")); + expect(res.status).toBe(200); + // next-auth's own cookies and body come through untouched. + expect(res.headers.getSetCookie().filter((c) => c.startsWith("next-auth."))).toHaveLength(2); + expect((await res.json()).url).toBe("http://localhost:3000/"); + const set = res.headers.getSetCookie().find((c) => c.startsWith(`${KNOWN_DEVICE_COOKIE}=`))!; + expect(set).toMatch(/; Path=\/api\/auth; Max-Age=7776000; HttpOnly; SameSite=Lax$/); + expect(isKnownDevice(knownDeviceFrom(res)!.split("=")[1], "me@example.com")).toBe(true); + + handler.mockImplementation(async () => nextAuthAnswer(FAILED, 401)); + const wrong = await POST(signInRequest("me@example.com"), context("callback", "credentials")); + expect(knownDeviceFrom(wrong)).toBeUndefined(); + }); + + it("lets the student's own browser sign in while a stranger keeps the account limit tripped", async () => { + handler.mockImplementation(async () => signedInAnswer()); + const cookie = knownDeviceFrom(await POST(signInRequest("victim@example.com"), context("callback", "credentials")))!; + + await lockOut("victim@example.com"); + // A stranger, or a browser that never signed in, still gets 429. + handler.mockImplementation(async () => signedInAnswer()); + expect((await POST(signInRequest("victim@example.com"), context("callback", "credentials"))).status).toBe(429); + + // The student's browser goes through to the password check. + const own: Response = await POST(signInRequest("victim@example.com", undefined, cookie), context("callback", "credentials")); + expect(own.status).toBe(200); + // Its cookie starts another 90 days. + expect(knownDeviceFrom(own)).toBeDefined(); + + // The cookie names one account: it doesn't lift another account's limit. + await lockOut("other@example.com"); + handler.mockImplementation(async () => signedInAnswer()); + expect((await POST(signInRequest("other@example.com", undefined, cookie), context("callback", "credentials"))).status).toBe(429); + }); + + it("keeps the per-network limit for a known device", async () => { + handler.mockImplementation(async () => signedInAnswer()); + const cookie = knownDeviceFrom(await POST(signInRequest("me@example.com"), context("callback", "credentials")))!; + handler.mockImplementation(async () => nextAuthAnswer(FAILED, 401)); + let status = 0; + for (let i = 0; i < 1000 && status !== 429; i++) { + const res: Response = await POST(signInRequest("me@example.com", "10.3.0.1", cookie), context("callback", "credentials")); + status = res.status; + } + expect(status).toBe(429); + }); +}); diff --git a/src/__tests__/auto-flashcards.test.ts b/src/__tests__/auto-flashcards.test.ts index a683b477..99c98fdf 100644 --- a/src/__tests__/auto-flashcards.test.ts +++ b/src/__tests__/auto-flashcards.test.ts @@ -1,7 +1,9 @@ /** - * Unit tests for createFlashcardsFromErrors — transactional deck handling, - * ordinal derivation from real card data, race recovery, answerable-front - * transforms, correction-first backs, and recurrence refresh. + * Unit tests for createFlashcardsFromErrors — deck lookup and race recovery + * (outside the transaction, since a failed statement aborts a PostgreSQL + * transaction), transactional card writes, ordinal derivation from real card + * data, answerable-front transforms, correction-first backs, and recurrence + * refresh. * * Uses an in-memory Prisma mock with an interactive $transaction. */ @@ -11,8 +13,6 @@ import { describe, it, expect, vi, beforeEach } from "vitest"; vi.mock("@/lib/db", () => { const tx = { flashcardDeck: { - findFirst: vi.fn(), - create: vi.fn(), update: vi.fn(async () => ({})), }, flashcard: { @@ -27,6 +27,11 @@ vi.mock("@/lib/db", () => { }, }; const prisma = { + flashcardDeck: { + findMany: vi.fn(async () => []), + create: vi.fn(), + update: vi.fn(async () => ({})), + }, sessionAttempt: { findMany: vi.fn(async () => []) }, sessionErrorLog: { findMany: vi.fn(async () => []) }, $transaction: vi.fn(async (fn: (t: typeof tx) => Promise<unknown>) => fn(tx)), @@ -35,14 +40,12 @@ vi.mock("@/lib/db", () => { return { prisma }; }); -import { createFlashcardsFromErrors } from "@/lib/auto-flashcards"; +import { buildBack, buildFront, createFlashcardsFromErrors } from "@/lib/auto-flashcards"; import { prisma } from "@/lib/db"; const tx = (prisma as unknown as { _tx: { flashcardDeck: { - findFirst: ReturnType<typeof vi.fn>; - create: ReturnType<typeof vi.fn>; update: ReturnType<typeof vi.fn>; }; flashcard: { @@ -55,6 +58,11 @@ const tx = (prisma as unknown as { }; })._tx; +const decks = prisma.flashcardDeck as unknown as { + findMany: ReturnType<typeof vi.fn>; + create: ReturnType<typeof vi.fn>; + update: ReturnType<typeof vi.fn>; +}; const attemptsMock = prisma.sessionAttempt.findMany as ReturnType<typeof vi.fn>; const errorLogsMock = prisma.sessionErrorLog.findMany as ReturnType<typeof vi.fn>; const transactionMock = prisma.$transaction as ReturnType<typeof vi.fn>; @@ -72,7 +80,10 @@ function makeAttempt(index: number, promptText: string) { describe("createFlashcardsFromErrors", () => { beforeEach(() => { vi.clearAllMocks(); - tx.flashcardDeck.findFirst.mockResolvedValue({ id: "deck-1" }); + decks.findMany.mockResolvedValue([{ id: "deck-1", title: "Session errors" }]); + decks.create.mockReset(); + decks.update.mockReset(); + decks.update.mockResolvedValue({}); tx.flashcardDeck.update.mockResolvedValue({}); tx.flashcard.findMany.mockResolvedValue([]); tx.flashcard.aggregate.mockResolvedValue({ _max: { ordinal: null } }); @@ -141,7 +152,7 @@ describe("createFlashcardsFromErrors", () => { data: Record<string, unknown>; }; expect(updateArg.where).toEqual({ id: "card-q1" }); - expect(updateArg.data.back).toContain("Correction: Newest correction for Q1"); + expect(updateArg.data.back).toContain("Correction rule: Newest correction for Q1"); expect(updateArg.data).not.toHaveProperty("ordinal"); }); @@ -166,7 +177,8 @@ describe("createFlashcardsFromErrors", () => { expect(created).toBe(1); const data = tx.flashcard.create.mock.calls[0][0].data; - expect(data.back).toContain("Correction: Osmosis moves water"); + expect(data.back).toContain("Correction rule: Osmosis moves water"); + expect(data.back).toContain("Error type: Concept"); expect(data.tags).toEqual(["concept", "auto-repair"]); }); @@ -187,11 +199,9 @@ describe("createFlashcardsFromErrors", () => { expect(created).toBe(1); const data = tx.flashcard.create.mock.calls[0][0].data; - expect(data.front).toBe( - `From memory: state the correct answer to — "${stem}" (answer without options)`, - ); + expect(data.front).toBe(`From memory, with no options shown, give the correct answer to "${stem}"`); // The correction (with the actual answer) leads the back - expect((data.back as string).startsWith("Correction: The correct answer is")).toBe(true); + expect((data.back as string).startsWith("Correction rule: The correct answer is")).toBe(true); }); it("leaves an MCQ stem untouched when the correction lacks the correct-answer marker", async () => { @@ -225,7 +235,7 @@ describe("createFlashcardsFromErrors", () => { it("matches recurring MCQ errors against the transformed front and refreshes them", async () => { const stem = "Which of the following best describes osmosis?"; - const wrapped = `From memory: state the correct answer to — "${stem}" (answer without options)`; + const wrapped = `From memory, with no options shown, give the correct answer to "${stem}"`; attemptsMock.mockResolvedValue([makeAttempt(0, stem)]); errorLogsMock.mockResolvedValue([ { @@ -264,11 +274,10 @@ describe("createFlashcardsFromErrors", () => { const back = tx.flashcard.create.mock.calls[0][0].data.back as string; const lines = back.split("\n"); - expect(lines[0]).toBe("Correction: Osmosis moves water"); - expect(lines[lines.length - 1]).toBe("Previously confused with: the wrong thing"); + expect(lines[0]).toBe("Correction rule: Osmosis moves water"); + expect(lines[lines.length - 1]).toBe("Your earlier answer: the wrong thing"); // The wrong answer never appears before the correction - expect(back.indexOf("Correction:")).toBeLessThan(back.indexOf("Previously confused with:")); - expect(back).not.toContain("Your answer:"); + expect(back.indexOf("Correction rule:")).toBeLessThan(back.indexOf("Your earlier answer:")); }); it("omits the wrong-answer line when the attempt has no recorded answer", async () => { @@ -289,15 +298,15 @@ describe("createFlashcardsFromErrors", () => { await createFlashcardsFromErrors("user-1", "run-1", "Biology"); const back = tx.flashcard.create.mock.calls[0][0].data.back as string; - expect(back).not.toContain("Previously confused with:"); + expect(back).not.toContain("Your earlier answer:"); }); - it("recovers from a P2002 on deck creation by re-fetching the deck", async () => { + it("recovers from a P2002 on deck creation by reading the deck again, outside the transaction", async () => { attemptsMock.mockResolvedValue([makeAttempt(0, "Q1")]); - tx.flashcardDeck.findFirst - .mockResolvedValueOnce(null) // initial lookup misses - .mockResolvedValueOnce({ id: "deck-2" }); // re-fetch after P2002 - tx.flashcardDeck.create.mockRejectedValueOnce( + decks.findMany + .mockResolvedValueOnce([]) // initial lookup misses + .mockResolvedValueOnce([{ id: "deck-2", title: "Session errors" }]); // read again after P2002 + decks.create.mockRejectedValueOnce( Object.assign(new Error("Unique constraint failed"), { code: "P2002" }), ); tx.flashcard.count.mockResolvedValue(1); @@ -305,31 +314,60 @@ describe("createFlashcardsFromErrors", () => { const created = await createFlashcardsFromErrors("user-1", "run-1", "Biology"); expect(created).toBe(1); - expect(tx.flashcardDeck.findFirst).toHaveBeenCalledTimes(2); + expect(decks.findMany).toHaveBeenCalledTimes(2); + // The failed insert never ran inside the card transaction + expect(decks.create.mock.invocationCallOrder[0]).toBeLessThan(transactionMock.mock.invocationCallOrder[0]); expect(tx.flashcard.create.mock.calls[0][0].data.deckId).toBe("deck-2"); }); - it("creates the deck inside the transaction when none exists", async () => { + it("creates the deck before the transaction when none exists", async () => { attemptsMock.mockResolvedValue([makeAttempt(0, "Q1")]); - tx.flashcardDeck.findFirst.mockResolvedValue(null); - tx.flashcardDeck.create.mockResolvedValue({ id: "deck-new" }); + decks.findMany.mockResolvedValue([]); + decks.create.mockResolvedValue({ id: "deck-new" }); tx.flashcard.count.mockResolvedValue(1); const created = await createFlashcardsFromErrors("user-1", "run-1", "Biology"); expect(created).toBe(1); - expect(tx.flashcardDeck.create).toHaveBeenCalledWith({ + expect(decks.create).toHaveBeenCalledWith({ data: { userId: "user-1", courseName: "Biology", - title: "Error Repair — Biology", + title: "Session errors", cardCount: 0, }, select: { id: true }, }); + expect(tx.flashcard.create.mock.calls[0][0].data.deckId).toBe("deck-new"); expect(tx.flashcard.create.mock.calls[0][0].data.ordinal).toBe(0); }); + it("locks the deck row before reading ordinals, so concurrent runs take turns", async () => { + attemptsMock.mockResolvedValue([makeAttempt(0, "Q1")]); + tx.flashcard.count.mockResolvedValue(1); + + await createFlashcardsFromErrors("user-1", "run-1", "Biology"); + + expect(tx.flashcardDeck.update.mock.calls[0][0]).toEqual({ + where: { id: "deck-1" }, + data: { cardCount: { increment: 0 } }, + }); + expect(tx.flashcardDeck.update.mock.invocationCallOrder[0]).toBeLessThan( + tx.flashcard.aggregate.mock.invocationCallOrder[0], + ); + }); + + it("returns 0 when the deck can't be created for a reason other than a race", async () => { + attemptsMock.mockResolvedValue([makeAttempt(0, "Q1")]); + decks.findMany.mockResolvedValue([]); + decks.create.mockRejectedValueOnce(new Error("connection lost")); + + const created = await createFlashcardsFromErrors("user-1", "run-1", "Biology"); + + expect(created).toBe(0); + expect(transactionMock).not.toHaveBeenCalled(); + }); + it("returns 0 when the transaction fails", async () => { attemptsMock.mockResolvedValue([makeAttempt(0, "Q1")]); transactionMock.mockRejectedValueOnce(new Error("deadlock detected")); @@ -338,4 +376,102 @@ describe("createFlashcardsFromErrors", () => { expect(created).toBe(0); }); + it("finds a recurring MCQ card saved with the earlier wording and rewrites its front", async () => { + const stem = "Which of the following best describes osmosis?"; + const legacy = `From memory: state the correct answer to \u2014 "${stem}" (answer without options)`; + attemptsMock.mockResolvedValue([makeAttempt(0, stem)]); + errorLogsMock.mockResolvedValue([ + { promptIndex: 0, errorType: "MISCONCEPTION", correctionRule: 'The correct answer is "Passive water movement".' }, + ]); + tx.flashcard.findMany.mockResolvedValue([{ id: "card-old", front: legacy }]); + + const created = await createFlashcardsFromErrors("user-1", "run-1", "Biology"); + + expect(created).toBe(0); + expect(tx.flashcard.create).not.toHaveBeenCalled(); + const update = tx.flashcard.update.mock.calls[0][0] as { where: { id: string }; data: Record<string, string> }; + expect(update.where).toEqual({ id: "card-old" }); + expect(update.data.front).toBe(`From memory, with no options shown, give the correct answer to "${stem}"`); + expect(update.data.back).toContain("Error type: Misconception"); + }); + + it("reuses and renames a deck with the earlier title", async () => { + attemptsMock.mockResolvedValue([makeAttempt(0, "Q1")]); + decks.findMany.mockResolvedValue([{ id: "deck-legacy", title: "Error Repair \u2014 Biology" }]); + tx.flashcard.count.mockResolvedValue(1); + + const created = await createFlashcardsFromErrors("user-1", "run-1", "Biology"); + + expect(created).toBe(1); + expect(decks.findMany.mock.calls[0][0]).toEqual({ + where: { userId: "user-1", courseName: "Biology", title: { in: ["Session errors", "Error Repair \u2014 Biology"] } }, + select: { id: true, title: true }, + }); + expect(decks.update).toHaveBeenCalledWith({ + where: { id: "deck-legacy" }, + data: { title: "Session errors" }, + }); + expect(tx.flashcard.create.mock.calls[0][0].data.deckId).toBe("deck-legacy"); + }); + + it("uses the current deck when a legacy deck exists beside it, whatever order they come back in", async () => { + attemptsMock.mockResolvedValue([makeAttempt(0, "Q1")]); + decks.findMany.mockResolvedValue([ + { id: "deck-legacy", title: "Error Repair \u2014 Biology" }, + { id: "deck-current", title: "Session errors" }, + ]); + tx.flashcard.count.mockResolvedValue(1); + + const created = await createFlashcardsFromErrors("user-1", "run-1", "Biology"); + + expect(created).toBe(1); + expect(decks.update).not.toHaveBeenCalled(); + expect(tx.flashcard.create.mock.calls[0][0].data.deckId).toBe("deck-current"); + }); + + it("keeps going when renaming the legacy deck collides with a new one", async () => { + attemptsMock.mockResolvedValue([makeAttempt(0, "Q1")]); + decks.findMany + .mockResolvedValueOnce([{ id: "deck-legacy", title: "Error Repair \u2014 Biology" }]) + .mockResolvedValueOnce([ + { id: "deck-legacy", title: "Error Repair \u2014 Biology" }, + { id: "deck-current", title: "Session errors" }, + ]); + decks.update.mockRejectedValueOnce(Object.assign(new Error("Unique constraint failed"), { code: "P2002" })); + tx.flashcard.count.mockResolvedValue(1); + + const created = await createFlashcardsFromErrors("user-1", "run-1", "Biology"); + + expect(created).toBe(1); + expect(tx.flashcard.create.mock.calls[0][0].data.deckId).toBe("deck-current"); + }); + + it("names error types in the app's words", async () => { + attemptsMock.mockResolvedValue([makeAttempt(0, "Q1"), makeAttempt(1, "Q2")]); + errorLogsMock.mockResolvedValue([ + { promptIndex: 0, errorType: "PROCEDURE", correctionRule: "Rule A" }, + { promptIndex: 1, errorType: "CARELESS", correctionRule: "Rule B" }, + ]); + tx.flashcard.count.mockResolvedValue(2); + + await createFlashcardsFromErrors("user-1", "run-1", "Biology"); + + expect(tx.flashcard.create.mock.calls[0][0].data.back).toContain("Error type: Wrong steps"); + expect(tx.flashcard.create.mock.calls[1][0].data.back).toContain("Error type: Careless slip"); + }); +}); + +describe("card text from older correction rules", () => { + const stem = "Which of the following best describes osmosis?"; + + it("wraps MCQ stems whose rule reads \"The right answer is X.\"", () => { + expect(buildFront(stem, "The right answer is Passive water movement.")).toBe( + `From memory, with no options shown, give the correct answer to "${stem}"`, + ); + }); + + it("drops the stored choice letter from the earlier answer", () => { + const back = buildBack({ errorType: "MISCONCEPTION", correctionRule: "Water moves." }, "[B] Active transport"); + expect(back.endsWith("Your earlier answer: Active transport")).toBe(true); + }); }); diff --git a/src/__tests__/breaks-display.test.ts b/src/__tests__/breaks-display.test.ts new file mode 100644 index 00000000..37f3d8b0 --- /dev/null +++ b/src/__tests__/breaks-display.test.ts @@ -0,0 +1,88 @@ +import { describe, it, expect } from "vitest"; +import { + breakEndsAt, + breakRemainingSeconds, + breakSchedule, + checkBreakNeeded, + hasBreaks, + initBreakState, +} from "@/lib/breaks"; + +const NOW = new Date("2026-10-15T18:00:00Z"); + +describe("hasBreaks and breakSchedule", () => { + it("treats one work block as no breaks", () => { + expect(hasBreaks({ type: "25_5", cycles: 1 })).toBe(false); + expect(hasBreaks(null)).toBe(false); + expect(breakSchedule({ type: "25_5", cycles: 1 })).toBeNull(); + }); + + it("describes a protocol with breaks in whole minutes", () => { + expect(breakSchedule({ type: "25_5", cycles: 2 })).toEqual({ blocks: 2, workMinutes: 25, breakMinutes: 5 }); + expect(breakSchedule({ type: "50_10", cycles: 3 })).toEqual({ blocks: 3, workMinutes: 50, breakMinutes: 10 }); + }); + + it("never shows a test protocol as zero minutes", () => { + expect(breakSchedule({ type: "TEST_3_2", cycles: 2 })).toEqual({ blocks: 2, workMinutes: 1, breakMinutes: 1 }); + }); +}); + +describe("breakEndsAt and breakRemainingSeconds", () => { + function onBreak(startedSecondsAgo: number) { + const state = initBreakState({ type: "25_5", cycles: 2 }); + return { + ...state, + on_break: true, + break_started_at: new Date(NOW.getTime() - startedSecondsAgo * 1000).toISOString(), + }; + } + + it("counts down from the break's server start time", () => { + const state = onBreak(60); + expect(breakEndsAt(state)?.toISOString()).toBe("2026-10-15T18:04:00.000Z"); + expect(breakRemainingSeconds(state, NOW)).toBe(240); + }); + + it("stops at zero once the break is over", () => { + expect(breakRemainingSeconds(onBreak(600), NOW)).toBe(0); + }); + + it("is zero and has no end when not on a break", () => { + const state = initBreakState({ type: "25_5", cycles: 2 }); + expect(breakEndsAt(state)).toBeNull(); + expect(breakRemainingSeconds(state, NOW)).toBe(0); + }); +}); + +describe("checkBreakNeeded after a long time away", () => { + it("still starts a break right after a work block", () => { + const state = initBreakState({ type: "25_5", cycles: 2 }); + state.work_started_at = new Date(NOW.getTime() - 26 * 60 * 1000).toISOString(); + const next = checkBreakNeeded(state, NOW); + expect(next.on_break).toBe(true); + expect(next.break_started_at).toBe(NOW.toISOString()); + }); + + it("still starts the break when a long question runs past the block end", () => { + const state = initBreakState({ type: "25_5", cycles: 2 }); + state.work_started_at = new Date(NOW.getTime() - 40 * 60 * 1000).toISOString(); + expect(checkBreakNeeded(state, NOW).on_break).toBe(true); + }); + + it("counts a long time away as the break", () => { + const state = initBreakState({ type: "25_5", cycles: 2 }); + state.work_started_at = new Date(NOW.getTime() - 3 * 60 * 60 * 1000).toISOString(); + const next = checkBreakNeeded(state, NOW); + expect(next.on_break).toBe(false); + expect(next.current_cycle).toBe(1); + expect(next.work_started_at).toBe(NOW.toISOString()); + expect(next.completed_breaks).toHaveLength(1); + }); + + it("does nothing on the last block", () => { + const state = initBreakState({ type: "25_5", cycles: 2 }); + state.current_cycle = 1; + state.work_started_at = new Date(NOW.getTime() - 3 * 60 * 60 * 1000).toISOString(); + expect(checkBreakNeeded(state, NOW)).toBe(state); + }); +}); diff --git a/src/__tests__/breaks-test-protocol.test.ts b/src/__tests__/breaks-test-protocol.test.ts index 46d4d548..02a944b5 100644 --- a/src/__tests__/breaks-test-protocol.test.ts +++ b/src/__tests__/breaks-test-protocol.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from "vitest"; -import { getBreakConfig, initBreakState, checkBreakNeeded, checkBreakEnded } from "@/lib/breaks"; +import { getBreakConfig, initBreakState, checkBreakNeeded } from "@/lib/breaks"; describe("test break protocols (TEST_1_1, TEST_3_2)", () => { it("maps TEST_1_1 to ~1 second work / ~1 second break", () => { @@ -21,15 +21,4 @@ describe("test break protocols (TEST_1_1, TEST_3_2)", () => { const result = checkBreakNeeded(state, futureDate); expect(result.on_break).toBe(true); }); - - it("ends break after 1 second with TEST_1_1", () => { - const state = initBreakState({ type: "TEST_1_1", cycles: 2 }); - state.on_break = true; - state.break_started_at = new Date().toISOString(); - // Simulate 1.5 seconds passing - const futureDate = new Date(Date.now() + 1500); - const result = checkBreakEnded(state, futureDate); - expect(result.on_break).toBe(false); - expect(result.current_cycle).toBe(1); - }); }); diff --git a/src/__tests__/breaks.test.ts b/src/__tests__/breaks.test.ts index fc74f1ae..de07f63d 100644 --- a/src/__tests__/breaks.test.ts +++ b/src/__tests__/breaks.test.ts @@ -3,10 +3,7 @@ import { getBreakConfig, initBreakState, checkBreakNeeded, - checkBreakEnded, endBreakEarly, - breakRemainingSeconds, - workRemainingSeconds, } from "@/lib/breaks"; describe("getBreakConfig", () => { @@ -78,31 +75,6 @@ describe("checkBreakNeeded", () => { }); }); -describe("checkBreakEnded", () => { - it("advances cycle when break duration exceeded", () => { - const breakStart = new Date(Date.now() - 11 * 60 * 1000); // 11 min ago - const state = initBreakState({ type: "50_10", cycles: 2 }); - state.on_break = true; - state.break_started_at = breakStart.toISOString(); - state.current_cycle = 0; - - const result = checkBreakEnded(state); - expect(result.on_break).toBe(false); - expect(result.current_cycle).toBe(1); - expect(result.completed_breaks).toHaveLength(1); - }); - - it("keeps break active if not yet elapsed", () => { - const breakStart = new Date(Date.now() - 5 * 60 * 1000); // 5 min ago - const state = initBreakState({ type: "50_10", cycles: 2 }); - state.on_break = true; - state.break_started_at = breakStart.toISOString(); - - const result = checkBreakEnded(state); - expect(result.on_break).toBe(true); - }); -}); - describe("endBreakEarly", () => { it("ends break and advances cycle", () => { const state = initBreakState({ type: "50_10", cycles: 2 }); @@ -115,32 +87,3 @@ describe("endBreakEarly", () => { expect(result.completed_breaks).toHaveLength(1); }); }); - -describe("breakRemainingSeconds", () => { - it("returns remaining seconds during break", () => { - const state = initBreakState({ type: "50_10", cycles: 2 }); - state.on_break = true; - const twoMinAgo = new Date(Date.now() - 2 * 60 * 1000); - state.break_started_at = twoMinAgo.toISOString(); - - const remaining = breakRemainingSeconds(state); - // Should be ~8 minutes (480 seconds) ± 1s - expect(remaining).toBeGreaterThan(470); - expect(remaining).toBeLessThanOrEqual(481); - }); - - it("returns 0 when not on break", () => { - const state = initBreakState({ type: "50_10", cycles: 2 }); - expect(breakRemainingSeconds(state)).toBe(0); - }); -}); - -describe("workRemainingSeconds", () => { - it("returns remaining work time", () => { - const state = initBreakState({ type: "25_5", cycles: 2 }); - // work_started_at is "now" - const remaining = workRemainingSeconds(state); - expect(remaining).toBeGreaterThan(24 * 60 - 2); - expect(remaining).toBeLessThanOrEqual(25 * 60 + 1); - }); -}); diff --git a/src/__tests__/calendar-hash.test.ts b/src/__tests__/calendar-hash.test.ts deleted file mode 100644 index 582d5d5d..00000000 --- a/src/__tests__/calendar-hash.test.ts +++ /dev/null @@ -1,95 +0,0 @@ -/** - * Unit tests for calendar event hashing. - * - * Tests: - * - Stable hash for same object regardless of key insertion order - * - Hash changes when content changes - * - hashUserId produces consistent short hashes - */ -import { describe, it, expect } from "vitest"; -import { computeEventHash, stableHash, hashUserId } from "@/lib/calendar/hash"; -import type { CalendarEventPayload } from "@/lib/calendar/types"; - -describe("computeEventHash", () => { - const basePayload: CalendarEventPayload = { - summary: "CS101 | Midterm | Retrieval: Linked lists", - description: "StudyBot session: http://localhost:3000/s/abc", - start: "2025-06-01T09:00:00Z", - end: "2025-06-01T10:00:00Z", - timeZone: "America/New_York", - transparency: "opaque", - extendedProperties: { sb_plan: "plan-1", sb_item: "item-1" }, - }; - - it("produces identical hash for identical input", () => { - const a = computeEventHash(basePayload); - const b = computeEventHash(basePayload); - expect(a).toBe(b); - expect(a).toHaveLength(64); // SHA-256 hex - }); - - it("changes hash when summary changes", () => { - const modified = { ...basePayload, summary: "Different title" }; - expect(computeEventHash(modified)).not.toBe(computeEventHash(basePayload)); - }); - - it("changes hash when start time changes", () => { - const modified = { ...basePayload, start: "2025-06-01T10:00:00Z" }; - expect(computeEventHash(modified)).not.toBe(computeEventHash(basePayload)); - }); - - it("changes hash when description changes", () => { - const modified = { ...basePayload, description: "Different description" }; - expect(computeEventHash(modified)).not.toBe(computeEventHash(basePayload)); - }); - - it("changes hash when extended properties change", () => { - const modified = { ...basePayload, extendedProperties: { sb_plan: "plan-2", sb_item: "item-1" } }; - expect(computeEventHash(modified)).not.toBe(computeEventHash(basePayload)); - }); - - it("is stable regardless of key insertion order in extended properties", () => { - const a: CalendarEventPayload = { - ...basePayload, - extendedProperties: { sb_plan: "plan-1", sb_item: "item-1", sb_sess: "sess-1" }, - }; - const b: CalendarEventPayload = { - ...basePayload, - extendedProperties: { sb_sess: "sess-1", sb_item: "item-1", sb_plan: "plan-1" }, - }; - expect(computeEventHash(a)).toBe(computeEventHash(b)); - }); -}); - -describe("stableHash", () => { - it("produces same hash regardless of key insertion order", () => { - const a = { z: 1, a: 2, m: 3 }; - const b = { a: 2, m: 3, z: 1 }; - expect(stableHash(a)).toBe(stableHash(b)); - }); - - it("handles nested objects", () => { - const a = { outer: { z: 1, a: 2 }, b: 3 }; - const b = { b: 3, outer: { a: 2, z: 1 } }; - expect(stableHash(a)).toBe(stableHash(b)); - }); - - it("different values produce different hashes", () => { - expect(stableHash({ a: 1 })).not.toBe(stableHash({ a: 2 })); - }); -}); - -describe("hashUserId", () => { - it("produces consistent 16-char hex string", () => { - const hash = hashUserId("user-123"); - expect(hash).toHaveLength(16); - expect(/^[0-9a-f]{16}$/.test(hash)).toBe(true); - - // Same input → same output - expect(hashUserId("user-123")).toBe(hash); - }); - - it("different users produce different hashes", () => { - expect(hashUserId("user-1")).not.toBe(hashUserId("user-2")); - }); -}); diff --git a/src/__tests__/calendar.test.ts b/src/__tests__/calendar.test.ts index 1c729b69..c863c1fa 100644 --- a/src/__tests__/calendar.test.ts +++ b/src/__tests__/calendar.test.ts @@ -1,101 +1,152 @@ import { describe, it, expect } from "vitest"; -import { buildCalendarTitle, buildCalendarDescription } from "@/lib/calendar"; +import { breaksText, buildCalendarTitle, buildCalendarDescription, sessionTopics } from "@/lib/calendar"; describe("buildCalendarTitle", () => { - it("formats a retrieval session title", () => { + it("leads with the mode and topics, then the course and exam", () => { const title = buildCalendarTitle({ courseName: "CS 2110", examName: "Prelim 1", mode: "RETRIEVAL", - topicScope: "L3–L4", + topicScope: "Recursion, Stacks", }); - expect(title).toBe("CS 2110 | Prelim 1 | Retrieval: L3–L4"); + expect(title).toBe("Retrieval: Recursion and Stacks · CS 2110 Prelim 1"); }); - it("formats an interleaved practice title", () => { + it("keeps a topic scope without commas whole", () => { const title = buildCalendarTitle({ courseName: "CHEM 2070", examName: "Prelim 2", mode: "INTERLEAVED_PRACTICE", topicScope: "Buffers + Titrations", }); - expect(title).toBe( - "CHEM 2070 | Prelim 2 | Interleaved Practice: Buffers + Titrations" - ); + expect(title).toBe("Interleaved practice: Buffers + Titrations · CHEM 2070 Prelim 2"); }); - it("formats all mode labels correctly", () => { + it("uses every mode label from VOICE.md", () => { const modes = [ - ["ERROR_REPAIR", "Error Repair"], - ["EXAM_SIM", "Exam Sim"], - ["WORKED_EXAMPLES", "Worked Examples"], + ["ERROR_REPAIR", "Error repair"], + ["EXAM_SIM", "Exam simulation"], + ["WORKED_EXAMPLES", "Worked examples"], ] as const; for (const [mode, label] of modes) { - const title = buildCalendarTitle({ - courseName: "TEST", - examName: "E1", - mode, - topicScope: "T1", - }); - expect(title).toBe(`TEST | E1 | ${label}: T1`); + const title = buildCalendarTitle({ courseName: "TEST", examName: "E1", mode, topicScope: "T1" }); + expect(title).toBe(`${label}: T1 · TEST E1`); } }); + + it("reads the objectives before the scope, and caps the title at 3 topics", () => { + const title = buildCalendarTitle({ + courseName: "CS 2110", + examName: "Prelim 1", + mode: "INTERLEAVED_PRACTICE", + topicScope: "ignored", + objectives: [{ title: "Recursion" }, { title: "Stacks" }, { title: "Queues" }, { title: "Graphs" }], + }); + expect(title).toBe("Interleaved practice: Recursion, Stacks, Queues, and 1 more · CS 2110 Prelim 1"); + }); + + it("drops the topics part when there are none", () => { + expect(buildCalendarTitle({ courseName: "CS 2110", examName: "Final", mode: "EXAM_SIM", topicScope: "" })).toBe( + "Exam simulation · CS 2110 Final", + ); + }); +}); + +describe("sessionTopics", () => { + it("reads stored objectives, strings or { title } objects", () => { + expect(sessionTopics([{ id: "a", title: "Recursion" }, "Stacks", { id: "c" }])).toEqual(["Recursion", "Stacks"]); + }); + + it("falls back to the comma-separated scope", () => { + expect(sessionTopics(null, "Recursion, Stacks , ")).toEqual(["Recursion", "Stacks"]); + }); + + it("drops the marker older follow-up sessions stored in their scope", () => { + expect(sessionTopics(null, "Follow-up: Recursion, Stacks")).toEqual(["Recursion", "Stacks"]); + expect(sessionTopics(null, "Follow-up: Follow-up: Unit tests")).toEqual(["Unit tests"]); + }); +}); + +describe("breaksText", () => { + it("says nothing for a single block", () => { + expect(breaksText({ type: "25_5", cycles: 1 })).toBeNull(); + expect(breaksText(null)).toBeNull(); + }); + + it("names the blocks and the break in words", () => { + expect(breaksText({ type: "25_5", cycles: 2 })).toBe("2 blocks of 25 min, with a 5 min break in between."); + expect(breaksText({ type: "50_10", cycles: 3 })).toBe("3 blocks of 50 min, with a 10 min break between blocks."); + }); }); describe("buildCalendarDescription", () => { - it("includes outcome checkboxes", () => { + const sessionUrl = "http://localhost:3000/s/abc"; + + it("is plain text a new plan's event can show in any calendar", () => { const desc = buildCalendarDescription({ - outcome: { - target_accuracy: 0.8, - prompt_count: 20, - closed_book_required: true, - deliverables: ["error_log_entries>=5"], - }, - sessionUrl: "http://localhost:3000/s/abc123", + courseName: "CS 2110", + examName: "Prelim 1", + mode: "RETRIEVAL", + topics: [ + { id: "recursion", title: "Recursion" }, + { id: "stacks", title: "Stacks" }, + ], + outcome: { prompt_count: 8, target_accuracy: 0.8, closed_book_required: true }, + // What every new plan sends: one block, so no break + breaks: { type: "25_5", cycles: 1 }, + sessionUrl, }); - expect(desc).toContain("- [ ] Score >= 80% on 20 prompts"); - expect(desc).toContain("- [ ] Complete closed-book first pass"); - expect(desc).toContain("error log_entries >= 5"); + expect(desc).toBe( + [ + "Retrieval session for CS 2110 Prelim 1", + "Topics: Recursion and Stacks", + "8 questions. Target accuracy: 80%. Answer from memory before you open your notes.", + "", + `Open the session: ${sessionUrl}`, + "", + "Added by Study Bot", + ].join("\n"), + ); }); - it("includes the session URL", () => { + it("never carries Markdown, raw enums, glyphs or developer labels", () => { const desc = buildCalendarDescription({ - sessionUrl: "http://localhost:3000/s/xyz", + courseName: "CS 2110", + examName: "Prelim 1", + mode: "EXAM_SIM", + topics: ["A", "B", "C"], + outcome: { prompt_count: 1, target_accuracy: 0.7, deliverables: ["error_log_entries>=5"] }, + breaks: { type: "25_5", cycles: 2 }, + sessionUrl, }); - expect(desc).toContain("http://localhost:3000/s/xyz"); - expect(desc).toContain("**Terminal session:**"); + expect(desc).not.toMatch(/\*\*|- \[ \]|>=|25_5|Terminal|cycle\(s\)|prompts?\b|Score|[—–]/); + expect(desc).toContain("1 question. Target accuracy: 70%."); + expect(desc).toContain("Error log entries: at least 5."); + expect(desc).toContain("2 blocks of 25 min, with a 5 min break in between."); }); - it("includes break protocol", () => { - const desc = buildCalendarDescription({ - breaks: { type: "50_10", cycles: 2 }, - sessionUrl: "http://localhost:3000/s/abc", - }); - expect(desc).toContain("50 min work / 10 min break"); - expect(desc).toContain("2 cycle(s)"); + it("names the first topics and counts the rest", () => { + const topics = Array.from({ length: 8 }, (_, i) => `Topic ${i + 1}`); + const desc = buildCalendarDescription({ topics, sessionUrl }); + expect(desc).toContain("Topics: Topic 1, Topic 2, Topic 3, Topic 4, Topic 5, Topic 6, and 2 more"); + expect(desc).not.toContain("Topic 7"); }); - it("includes resources", () => { - const desc = buildCalendarDescription({ - sessionUrl: "http://localhost:3000/s/abc", - resources: [ - { type: "slides", ref: "slides_week2.pdf", range: "pp. 8-22" }, - ], - }); - expect(desc).toContain("slides: slides_week2.pdf (pp. 8-22)"); + it("works with only the session link", () => { + expect(buildCalendarDescription({ sessionUrl })).toBe(`Open the session: ${sessionUrl}\n\nAdded by Study Bot`); }); - it("includes plan steps and rules", () => { + it("lists steps, rules and materials as plain lines", () => { const desc = buildCalendarDescription({ - planSteps: ["0–5 min: Setup", "5–50 min: Practice"], - rules: ["No phone", "Closed book"], - sessionUrl: "http://localhost:3000/s/abc", + planSteps: ["Setup", "Practice"], + rules: ["Notes closed"], + resources: [{ type: "slides", ref: "slides_week2.pdf", range: "pp. 8-22" }], + sessionUrl, }); - expect(desc).toContain("**Plan (how):**"); - expect(desc).toContain("- 0–5 min: Setup"); - expect(desc).toContain("**Rules:**"); - expect(desc).toContain("- No phone"); + expect(desc).toContain("Steps\n- Setup\n- Practice"); + expect(desc).toContain("Rules\n- Notes closed"); + expect(desc).toContain("Materials\n- slides: slides_week2.pdf (pp. 8-22)"); }); }); diff --git a/src/__tests__/card-format.test.ts b/src/__tests__/card-format.test.ts new file mode 100644 index 00000000..10209833 --- /dev/null +++ b/src/__tests__/card-format.test.ts @@ -0,0 +1,40 @@ +/** + * Exam dates on the Cards pages: a calendar date reads the same in every + * time zone, and the countdown counts calendar days from today on the + * student's clock, east of UTC+12 included. + */ +import { describe, it, expect } from "vitest"; + +import { examCountdown, examDateLabel } from "@/components/cards/card-format"; + +describe("examDateLabel", () => { + it("shows the stored calendar date", () => { + expect(examDateLabel("2026-10-22")).toBe("Thu, Oct 22"); + expect(examDateLabel("2026-10-22T00:00:00.000Z")).toBe("Thu, Oct 22"); + }); +}); + +describe("examCountdown", () => { + it("counts days on the student's clock in Auckland during NZDT (UTC+13)", () => { + // 9:00 AM Thu, Oct 15 in Auckland + const now = new Date("2026-10-14T20:00:00Z"); + expect(examCountdown("Prelim 1", "2026-10-22", { timeZone: "Pacific/Auckland", now })).toBe( + "Prelim 1 is in 7 days" + ); + expect(examCountdown("Prelim 1", "2026-10-15", { timeZone: "Pacific/Auckland", now })).toBe("Prelim 1 is today"); + }); + + it("counts days on the student's clock west of UTC", () => { + // 8:00 PM Wed, Oct 14 in Honolulu (UTC-10), already Oct 15 in UTC + const now = new Date("2026-10-15T06:00:00Z"); + expect(examCountdown("Prelim 1", "2026-10-15", { timeZone: "Pacific/Honolulu", now })).toBe( + "Prelim 1 is tomorrow" + ); + expect(examCountdown("Final", "2026-10-12", { timeZone: "Pacific/Honolulu", now })).toBe("Final was 2 days ago"); + }); + + it("counts in UTC without a zone", () => { + const now = new Date("2026-10-15T23:30:00Z"); + expect(examCountdown("Prelim 1", "2026-10-16", { now })).toBe("Prelim 1 is tomorrow"); + }); +}); diff --git a/src/__tests__/card-review-state.test.ts b/src/__tests__/card-review-state.test.ts new file mode 100644 index 00000000..ef777122 --- /dev/null +++ b/src/__tests__/card-review-state.test.ts @@ -0,0 +1,178 @@ +/** + * The flashcard review state machine and its keyboard rules. + */ +import { describe, it, expect } from "vitest"; +import { + currentCard, + initialReviewState, + keyIntent, + reviewReducer, + reviewTitle, + type ReviewState, +} from "@/components/cards/review/review-state"; +import type { StudyCard, StudyStats } from "@/services/spaced-repetition"; + +function card(id: string, status: StudyCard["status"] = "new"): StudyCard { + return { + id, + front: `Front ${id}`, + back: `Back ${id}`, + tags: ["topic", "auto-repair"], + ordinal: 0, + easeFactor: 2.5, + intervalDays: 0, + repetitions: 0, + nextDueAt: null, + status, + due: true, + previews: { AGAIN: 0, HARD: 1, GOOD: 1, EASY: 4 }, + }; +} + +const stats: StudyStats = { newCount: 2, learningCount: 0, reviewCount: 3, masteredCount: 0, dueCount: 2 }; + +function rate(state: ReviewState, rating: "AGAIN" | "HARD" | "GOOD" | "EASY", status: StudyCard["status"] = "review") { + let s = reviewReducer(state, { type: "reveal" }); + s = reviewReducer(s, { type: "rate-start", rating }); + return reviewReducer(s, { + type: "rate-success", + rating, + result: { + status: rating === "AGAIN" ? "learning" : status, + intervalDays: rating === "AGAIN" ? 0 : 1, + nextDueAt: rating === "AGAIN" ? "2026-10-15T18:10:00Z" : "2026-10-16T08:00:00Z", + previews: { AGAIN: 0, HARD: 1, GOOD: 2, EASY: 4 }, + xpEarned: 2, + }, + }); +} + +describe("reviewReducer", () => { + it("shows the answer before rating and ignores ratings on the question side", () => { + const start = initialReviewState([card("a"), card("b")], stats); + expect(start.phase).toBe("question"); + expect(reviewReducer(start, { type: "rate-start", rating: "GOOD" })).toBe(start); + expect(reviewReducer(start, { type: "reveal" }).phase).toBe("answer"); + }); + + it("re-queues a card rated Again and finishes after every card passes", () => { + let s = initialReviewState([card("a"), card("b")], stats); + s = rate(s, "AGAIN"); + expect(s.queue).toEqual(["a", "b", "a"]); + expect(s.finished).toBe(0); + expect(currentCard(s)?.id).toBe("b"); + s = rate(s, "GOOD"); + expect(currentCard(s)?.id).toBe("a"); + expect(currentCard(s)?.status).toBe("learning"); + s = rate(s, "EASY"); + expect(s.phase).toBe("done"); + expect(s.finished).toBe(2); + expect(s.ratings).toEqual({ AGAIN: 1, HARD: 0, GOOD: 1, EASY: 1 }); + expect(s.xp).toBe(6); + }); + + it("keeps the counts current as cards change status", () => { + let s = initialReviewState([card("a"), card("b")], stats); + s = rate(s, "AGAIN"); + expect(s.stats).toMatchObject({ newCount: 1, learningCount: 1, dueCount: 2 }); + s = rate(s, "GOOD"); + expect(s.stats).toMatchObject({ newCount: 0, learningCount: 1, reviewCount: 4, dueCount: 1 }); + s = rate(s, "GOOD"); + expect(s.stats).toMatchObject({ learningCount: 0, reviewCount: 5, dueCount: 0 }); + expect(s.earliestNext).toBe("2026-10-16T08:00:00Z"); + }); + + it("keeps the answer up after a failed rating so it can be retried", () => { + let s = initialReviewState([card("a")], stats); + s = reviewReducer(s, { type: "reveal" }); + s = reviewReducer(s, { type: "rate-start", rating: "GOOD" }); + s = reviewReducer(s, { type: "rate-failure", message: "Rating not saved." }); + expect(s.phase).toBe("answer"); + expect(s.submitting).toBeNull(); + expect(s.error).toBe("Rating not saved."); + }); + + it("starts an empty deck on the done screen without a card", () => { + const s = initialReviewState([], stats); + expect(s.phase).toBe("done"); + expect(currentCard(s)).toBeNull(); + }); + + it("drops the internal auto-repair tag", () => { + expect(initialReviewState([card("a")], stats).cards.a.tags).toEqual(["topic"]); + }); +}); + +describe("keyIntent", () => { + const press = (key: string, extra: Partial<{ repeat: boolean; ctrlKey: boolean; altKey: boolean; metaKey: boolean }> = {}) => ({ + key, + repeat: false, + altKey: false, + ctrlKey: false, + metaKey: false, + ...extra, + }); + const on = (selector: string | null) => ({ closest: (s: string) => (selector && s.includes(selector) ? {} : null) }); + const body = on(null); + + it("reveals with Space or Enter on the question side unless a control has focus", () => { + expect(keyIntent(press(" "), body, { phase: "question", submitting: null })).toEqual({ type: "reveal" }); + expect(keyIntent(press("Enter"), body, { phase: "question", submitting: null })).toEqual({ type: "reveal" }); + expect(keyIntent(press("Enter"), on("button"), { phase: "question", submitting: null })).toBeNull(); + expect(keyIntent(press(" "), on("a[href]"), { phase: "question", submitting: null })).toBeNull(); + }); + + it("rates with 1 to 4 only after the answer is shown", () => { + expect(keyIntent(press("3"), body, { phase: "question", submitting: null })).toBeNull(); + expect(keyIntent(press("1"), body, { phase: "answer", submitting: null })).toEqual({ type: "rate", rating: "AGAIN" }); + expect(keyIntent(press("4"), on("button"), { phase: "answer", submitting: null })).toEqual({ type: "rate", rating: "EASY" }); + expect(keyIntent(press("5"), body, { phase: "answer", submitting: null })).toBeNull(); + }); + + it("ignores number keys when single-key shortcuts are off, but Space still reveals", () => { + const off = { singleKeys: false }; + expect(keyIntent(press("3"), body, { phase: "answer", submitting: null }, off)).toBeNull(); + expect(keyIntent(press(" "), body, { phase: "question", submitting: null }, off)).toEqual({ type: "reveal" }); + expect(keyIntent(press("3"), body, { phase: "answer", submitting: null }, { singleKeys: true })).toEqual({ + type: "rate", + rating: "GOOD", + }); + }); + + it("opens the shortcuts help with ? on either side, unless single-key shortcuts are off", () => { + expect(keyIntent(press("?"), body, { phase: "question", submitting: null })).toEqual({ type: "help" }); + expect(keyIntent(press("?"), on("button"), { phase: "answer", submitting: null })).toEqual({ type: "help" }); + expect(keyIntent(press("?"), body, { phase: "answer", submitting: null }, { singleKeys: false })).toBeNull(); + expect(keyIntent(press("?"), on("[role=\"dialog\"]"), { phase: "answer", submitting: null })).toBeNull(); + }); + + it("does nothing on the done screen, while saving, in fields, on repeat, or with modifiers", () => { + expect(keyIntent(press("3"), body, { phase: "done", submitting: null })).toBeNull(); + expect(keyIntent(press(" "), body, { phase: "done", submitting: null })).toBeNull(); + expect(keyIntent(press("3"), body, { phase: "answer", submitting: "GOOD" })).toBeNull(); + expect(keyIntent(press("3"), on("textarea"), { phase: "answer", submitting: null })).toBeNull(); + expect(keyIntent(press("3", { repeat: true }), body, { phase: "answer", submitting: null })).toBeNull(); + expect(keyIntent(press("3", { ctrlKey: true }), body, { phase: "answer", submitting: null })).toBeNull(); + }); +}); + +describe("reviewTitle", () => { + it("names the card on screen, counting cards rated Hard or better", () => { + let s = initialReviewState([card("a"), card("b"), card("c")], stats); + expect(reviewTitle(s, "Recursion")).toBe("Card 1 of 3 · Recursion"); + s = rate(s, "AGAIN"); + // Card b is on screen, but no card is done yet + expect(reviewTitle(s, "Recursion")).toBe("Card 1 of 3 · Recursion"); + s = rate(s, "GOOD"); + expect(reviewTitle(s, "Recursion")).toBe("Card 2 of 3 · Recursion"); + }); + + it("names the summary and the two empty screens", () => { + let s = initialReviewState([card("a")], stats); + s = rate(s, "GOOD"); + expect(reviewTitle(s, "Recursion")).toBe("Deck reviewed · Recursion"); + expect(reviewTitle(initialReviewState([], stats), "Recursion")).toBe("Nothing due · Recursion"); + const none = { newCount: 0, learningCount: 0, reviewCount: 0, masteredCount: 0, dueCount: 0 }; + expect(reviewTitle(initialReviewState([], none), "Recursion")).toBe("No cards · Recursion"); + }); +}); diff --git a/src/__tests__/chat-history-append.test.ts b/src/__tests__/chat-history-append.test.ts new file mode 100644 index 00000000..4af233cc --- /dev/null +++ b/src/__tests__/chat-history-append.test.ts @@ -0,0 +1,68 @@ +/** + * Adding a saved question and answer to a course's chat history cache, and + * fetching the history again when it hasn't loaded (so an answer received + * while it was loading, or after it failed, still shows). + */ +import { describe, it, expect, vi } from "vitest"; +import { unstable_serialize } from "swr/infinite"; + +import { appendToHistory, appendToPages, historyKey } from "@/components/chat/use-chat-history"; +import type { ChatMessage, HistoryPage } from "@/components/chat/chat-types"; + +function message(id: string, role: "user" | "assistant"): ChatMessage { + return { + id, + role, + kind: role === "user" ? "question" : "answer", + content: `${role} ${id}`, + sources: [], + createdAt: "2026-10-15T12:00:00.000Z", + } as unknown as ChatMessage; +} + +const page = (ids: string[], total = ids.length): HistoryPage => + ({ messages: ids.map((id) => message(id, "user")), has_more: false, total }) as HistoryPage; + +describe("appendToPages", () => { + it("adds new messages to the end of the newest page and counts them", () => { + const pages = [page(["a", "b"], 5), page(["older"])]; + const next = appendToPages(pages, [message("b", "user"), message("c", "assistant")]); + expect(next?.[0].messages.map((m) => m.id)).toEqual(["a", "b", "c"]); + expect(next?.[0].total).toBe(6); + expect(next?.[1]).toBe(pages[1]); + }); + + it("leaves a history that hasn't loaded as it is", () => { + expect(appendToPages(undefined, [message("c", "user")])).toBeUndefined(); + }); +}); + +describe("appendToHistory", () => { + it("updates the course's history without a fetch when it's loaded", () => { + const mutate = vi.fn(); + appendToHistory(mutate as never, "CS 2110||Prelim 1", [message("q", "user"), message("a", "assistant")]); + + expect(mutate).toHaveBeenCalledTimes(1); + const [key, update, options] = mutate.mock.calls[0]; + expect(key).toBe(unstable_serialize(historyKey("CS 2110||Prelim 1"))); + const updated = update([page(["x"])]) as HistoryPage[]; + expect(updated[0].messages.map((m) => m.id)).toEqual(["x", "q", "a"]); + expect(options.revalidate(updated)).toBe(false); + }); + + it("fetches the history again when it's still loading or failed", () => { + const mutate = vi.fn(); + appendToHistory(mutate as never, "CS 2110||Prelim 1", [message("q", "user")]); + + const [, update, options] = mutate.mock.calls[0]; + const updated = update(undefined); + expect(updated).toBeUndefined(); + expect(options.revalidate(updated)).toBe(true); + }); + + it("does nothing with no messages", () => { + const mutate = vi.fn(); + appendToHistory(mutate as never, "CS 2110||Prelim 1", []); + expect(mutate).not.toHaveBeenCalled(); + }); +}); diff --git a/src/__tests__/chat-routes.test.ts b/src/__tests__/chat-routes.test.ts new file mode 100644 index 00000000..4820f916 --- /dev/null +++ b/src/__tests__/chat-routes.test.ts @@ -0,0 +1,284 @@ +/** + * Chat history paging (newest first, limit and before honoured) and the + * answer route storing a question once, retries included. + */ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import type { NextRequest } from "next/server"; + +vi.mock("@/lib/auth", () => ({ + getUserId: vi.fn(async (request: Request) => request.headers.get("x-user-id")), +})); + +vi.mock("@/lib/rate-limit", () => ({ + chatLimiter: { check: () => ({ allowed: true, retryAfterMs: 0 }) }, + aiLimiter: { check: () => ({ allowed: true, retryAfterMs: 0 }) }, +})); + +interface Row { + id: string; + userId: string; + courseKey: string; + role: string; + content: string; + citations: unknown; + createdAt: Date; +} + +const rows: Row[] = []; + +vi.mock("@/lib/db", () => { + const matches = (row: Row, where: Record<string, unknown>): boolean => { + for (const [key, value] of Object.entries(where)) { + if (key === "OR") { + if (!(value as Record<string, unknown>[]).some((w) => matches(row, w))) return false; + continue; + } + const field = row[key as keyof Row]; + if (value && typeof value === "object" && !(value instanceof Date)) { + const ops = value as { lt?: unknown }; + if (ops.lt !== undefined) { + if (field instanceof Date) { + if (!(field.getTime() < (ops.lt as Date).getTime())) return false; + } else if (!(String(field) < String(ops.lt))) return false; + } + continue; + } + if (value instanceof Date) { + if ((field as Date).getTime() !== value.getTime()) return false; + continue; + } + if (field !== value) return false; + } + return true; + }; + return { + prisma: { + chatMessage: { + findMany: vi.fn(async ({ where, take }: { where: Record<string, unknown>; take: number }) => + rows + .filter((r) => matches(r, where)) + .sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime() || (a.id < b.id ? 1 : -1)) + .slice(0, take), + ), + findFirst: vi.fn(async ({ where }: { where: Record<string, unknown> }) => rows.find((r) => matches(r, where)) ?? null), + count: vi.fn(async ({ where }: { where: Record<string, unknown> }) => rows.filter((r) => matches(r, where)).length), + create: vi.fn(async ({ data }: { data: Omit<Row, "id" | "createdAt"> }) => { + const row = { ...data, citations: data.citations ?? null, id: `m${rows.length + 100}`, createdAt: new Date(Date.now() + rows.length) }; + rows.push(row); + return row; + }), + }, + contentChunk: { findMany: vi.fn(async () => []) }, + contentDocument: { count: vi.fn(async () => 1) }, + }, + }; +}); + +const hybridSearch = vi.fn(); +vi.mock("@/lib/search", () => ({ hybridSearch: (...args: unknown[]) => hybridSearch(...args) })); + +const runTask = vi.fn(); +const embed = vi.fn(async () => ({ embeddings: [[0.1]] })); +vi.mock("@/lib/ai/gateway", () => { + class GatewayError extends Error { + constructor( + public readonly code: string, + message: string, + public readonly retryable: boolean, + ) { + super(message); + } + } + return { + GatewayError, + runTask: (...args: unknown[]) => runTask(...args), + embed: (...args: unknown[]) => embed(...(args as [])), + }; +}); +vi.mock("@/lib/ai/provider-factory", () => ({ createProvider: () => ({}) })); + +import { GET } from "@/app/api/chat/messages/route"; +import { POST as ANSWER } from "@/app/api/assistant/answer/route"; +import { GatewayError } from "@/lib/ai/gateway"; + +function seed(count: number) { + rows.length = 0; + for (let i = 0; i < count; i++) { + rows.push({ + id: `m${String(i).padStart(3, "0")}`, + userId: "u1", + courseKey: "INFO 1300||Prelim 2", + role: i % 2 === 0 ? "user" : "assistant", + content: `message ${i}`, + citations: null, + createdAt: new Date(Date.UTC(2026, 9, 1, 0, i)), + }); + } +} + +function get(query: string) { + return GET( + Object.assign(new Request(`http://localhost/api/chat/messages?${query}`, { headers: { "x-user-id": "u1" } }), { + nextUrl: new URL(`http://localhost/api/chat/messages?${query}`), + }) as unknown as NextRequest, + ); +} + +function answer(body: unknown) { + return ANSWER( + new Request("http://localhost/api/assistant/answer", { + method: "POST", + headers: { "content-type": "application/json", "x-user-id": "u1" }, + body: JSON.stringify(body), + }) as unknown as NextRequest, + ); +} + +const KEY = encodeURIComponent("INFO 1300||Prelim 2"); + +describe("GET /api/chat/messages", () => { + beforeEach(() => seed(120)); + + it("returns the newest page, oldest first, with has_more and the total", async () => { + const json = await (await get(`courseKey=${KEY}&limit=50`)).json(); + expect(json.messages).toHaveLength(50); + expect(json.messages[0].content).toBe("message 70"); + expect(json.messages[49].content).toBe("message 119"); + expect(json.has_more).toBe(true); + expect(json.total).toBe(120); + }); + + it("pages back with before and stops at the oldest", async () => { + const second = await (await get(`courseKey=${KEY}&limit=50&before=m070`)).json(); + expect(second.messages[0].content).toBe("message 20"); + expect(second.messages[49].content).toBe("message 69"); + expect(second.has_more).toBe(true); + + const third = await (await get(`courseKey=${KEY}&limit=50&before=m020`)).json(); + expect(third.messages.map((m: { content: string }) => m.content)).toEqual( + Array.from({ length: 20 }, (_, i) => `message ${i}`), + ); + expect(third.has_more).toBe(false); + }); + + it("labels questions and answers, and rejects a bad limit", async () => { + const json = await (await get(`courseKey=${KEY}&limit=2`)).json(); + expect(json.messages.map((m: { kind: string }) => m.kind)).toEqual(["question", "answer"]); + expect((await get(`courseKey=${KEY}&limit=500`)).status).toBe(400); + }); +}); + +describe("POST /api/assistant/answer with save", () => { + beforeEach(() => { + rows.length = 0; + hybridSearch.mockReset(); + runTask.mockReset(); + embed.mockClear(); + hybridSearch.mockResolvedValue([ + { chunk_id: "c1", doc_id: "d1", doc_title: "Lecture 14", page_number: 3, rank_score: 1, snippet: "Compare the columns left to right." }, + ]); + }); + + it("stores the question before answering and keeps it when the answer fails", async () => { + runTask.mockRejectedValueOnce(new GatewayError("PROVIDER_ERROR", "boom", true)); + + const failed = await answer({ question: "Why?", course_name: "INFO 1300", exam_name: "Prelim 2", save: true }); + const failedJson = await failed.json(); + + expect(failed.status).toBe(502); + expect(failedJson.question.id).toBeTruthy(); + expect(failedJson.error).not.toMatch(/boom/); + expect(rows.filter((r) => r.role === "user")).toHaveLength(1); + + runTask.mockResolvedValueOnce({ + output: { answer_markdown: "Columns decide [1].", citations: [{ chunk_id: "c1", reason: "r", quote_snippet: "Compare the columns" }] }, + meta: { cacheHit: false, latencyMs: 5 }, + }); + const retried = await ( + await answer({ question: "Why?", course_name: "INFO 1300", exam_name: "Prelim 2", save: true, question_id: failedJson.question.id }) + ).json(); + + // Retrying reuses the stored question: still one question, now one answer. + expect(rows.filter((r) => r.role === "user")).toHaveLength(1); + expect(rows.filter((r) => r.role === "assistant")).toHaveLength(1); + expect(retried.answer.kind).toBe("answer"); + expect(retried.answer.sources).toHaveLength(1); + expect(retried.answer.sources[0]).toMatchObject({ n: 1, page: 3 }); + }); + + it("answers plainly, without AI text, when the materials have nothing", async () => { + hybridSearch.mockResolvedValue([]); + const json = await (await answer({ question: "Why?", course_name: "INFO 1300", save: true })).json(); + expect(json.kind).toBe("notice"); + expect(json.answer.kind).toBe("notice"); + expect(json.answer_markdown).toBe( + "Your INFO 1300 materials don't cover this. Upload the file that does, or ask it a different way.", + ); + expect(runTask).not.toHaveBeenCalled(); + }); + + it("searches for any of the question's words when no passage has them all", async () => { + // "Why does an ID selector beat any number of class selectors?": no lecture says "beat" + hybridSearch.mockReset(); + hybridSearch.mockResolvedValueOnce([]).mockResolvedValueOnce([ + { chunk_id: "c1", doc_id: "d1", doc_title: "Lecture 14", page_number: 3, rank_score: 2, snippet: "An ID selector outranks classes." }, + ]); + runTask.mockResolvedValueOnce({ + output: { answer_markdown: "IDs outrank classes [1].", citations: [{ chunk_id: "c1", reason: "r", quote_snippet: "An ID selector outranks classes" }] }, + meta: { cacheHit: false, latencyMs: 5 }, + }); + + const json = await ( + await answer({ question: "Why does an ID selector beat any number of class selectors?", course_name: "INFO 1300", save: true }) + ).json(); + + expect(json.kind).toBe("answer"); + expect(json.answer.sources[0]).toMatchObject({ n: 1, title: "Lecture 14" }); + expect(hybridSearch.mock.calls.map(([params]) => (params as { match: string }).match)).toEqual(["all", "any"]); + }); + + it("keeps an answer that every word finds, without searching again or embedding in FTS mode", async () => { + vi.stubEnv("HYBRID_SEARCH_ENABLED", "false"); + runTask.mockResolvedValueOnce({ + output: { answer_markdown: "Columns decide [1].", citations: [{ chunk_id: "c1", reason: "r", quote_snippet: "Compare the columns" }] }, + meta: { cacheHit: false, latencyMs: 5 }, + }); + + const json = await (await answer({ question: "How do columns compare?", course_name: "INFO 1300" })).json(); + + expect(json.kind).toBe("answer"); + expect(hybridSearch).toHaveBeenCalledTimes(1); + expect(hybridSearch.mock.calls[0][0]).toMatchObject({ match: "all", mode: "FTS" }); + // HYBRID_SEARCH_ENABLED is off, so the vector half never runs and the embedding isn't needed + expect(embed).not.toHaveBeenCalled(); + vi.unstubAllEnvs(); + }); + + it("shows the model's 'Your materials don't cover this.' as the notice, not as an AI answer", async () => { + runTask.mockResolvedValueOnce({ + output: { answer_markdown: "Your materials don’t cover this.", citations: [] }, + meta: { cacheHit: false, latencyMs: 5 }, + }); + + const json = await (await answer({ question: "How do I bake sourdough?", course_name: "INFO 1300", save: true })).json(); + + expect(json.kind).toBe("notice"); + expect(json.answer.kind).toBe("notice"); + expect(json.answer_markdown).toBe( + "Your INFO 1300 materials don't cover this. Upload the file that does, or ask it a different way.", + ); + expect(rows.find((r) => r.role === "assistant")?.citations).toEqual({ notice: "no_match" }); + }); + + it("refuses a retry for a question that isn't stored", async () => { + const res = await answer({ question: "Why?", course_name: "INFO 1300", save: true, question_id: "nope" }); + expect(res.status).toBe(404); + expect(rows).toHaveLength(0); + }); + + it("explains an over-long question", async () => { + const res = await answer({ question: "x".repeat(2001), course_name: "INFO 1300" }); + expect(res.status).toBe(400); + expect((await res.json()).error).toBe("Shorten your question to 2,000 characters."); + }); +}); diff --git a/src/__tests__/chat-sources.test.ts b/src/__tests__/chat-sources.test.ts new file mode 100644 index 00000000..25fd6271 --- /dev/null +++ b/src/__tests__/chat-sources.test.ts @@ -0,0 +1,121 @@ +/** + * Numbered chat sources: inline [n] must point at the source shown as n. + */ +import { describe, it, expect } from "vitest"; +import { + inlineMarkerNumbers, + isLegacyNoMatch, + normalizeAnswer, + noticeText, + storedNotice, + toSources, + verifiedQuote, + type RetrievedExcerpt, +} from "@/app/api/chat/_lib/sources"; + +const retrieved: RetrievedExcerpt[] = [ + { chunk_id: "a", doc_title: "Lecture 14", page_number: 3, snippet: "Compare the columns left to right. The first difference decides." }, + { chunk_id: "b", doc_title: "Lecture 18", page_number: null, snippet: "If you use w descriptors and leave out sizes, the browser assumes 100vw." }, + { chunk_id: "c", doc_title: "Lecture 16", page_number: 7, snippet: "Grid places items on explicit tracks." }, +]; + +describe("normalizeAnswer", () => { + it("renumbers by first mention so [n] matches sources[n - 1]", () => { + const { markdown, citations } = normalizeAnswer( + "Sizes matters [2]. Columns decide [1]. Again sizes [2].", + [ + { chunk_id: "a", reason: "r", quote_snippet: "Compare the columns left to right" }, + { chunk_id: "b", reason: "r", quote_snippet: "leave out sizes" }, + ], + retrieved, + ); + expect(markdown).toBe("Sizes matters [1]. Columns decide [2]. Again sizes [1]."); + expect(citations.map((c) => c.chunk_id)).toEqual(["b", "a"]); + expect(citations[0].doc_title).toBe("Lecture 18"); + expect(citations[1].page_number).toBe(3); + }); + + it("reads markers in the model's own citation order when excerpt numbers don't fit", () => { + // The model cited c then a, and wrote [1] for c and [2] for a. + const { markdown, citations } = normalizeAnswer( + "Grid uses tracks [1]. Columns decide [2].", + [ + { chunk_id: "c", quote_snippet: "Grid places items" }, + { chunk_id: "a", quote_snippet: "Compare the columns" }, + ], + retrieved, + ); + expect(citations.map((c) => c.chunk_id)).toEqual(["c", "a"]); + expect(markdown).toBe("Grid uses tracks [1]. Columns decide [2]."); + }); + + it("drops citations to chunks that weren't retrieved and markers that point nowhere", () => { + const { markdown, citations } = normalizeAnswer( + "Answer [9] text.", + [{ chunk_id: "mock_chunk_1", quote_snippet: "x" }], + retrieved, + ); + expect(citations).toEqual([]); + expect(markdown).toBe("Answer text."); + }); + + it("lists cited excerpts the text never mentions after the mentioned ones", () => { + const { citations } = normalizeAnswer("Only one [3].", [{ chunk_id: "a" }, { chunk_id: "c" }], retrieved); + expect(citations.map((c) => c.chunk_id)).toEqual(["c", "a"]); + }); + + it("leaves markers inside code alone", () => { + const md = "Use `arr[2]` here [2].\n\n```\nx = y[1]\n```"; + expect(inlineMarkerNumbers(md)).toEqual([2]); + const { markdown } = normalizeAnswer(md, [{ chunk_id: "b" }], retrieved); + expect(markdown).toBe("Use `arr[2]` here [1].\n\n```\nx = y[1]\n```"); + }); + + it("splits grouped markers", () => { + const { markdown } = normalizeAnswer("Both [1, 3].", [{ chunk_id: "a" }, { chunk_id: "c" }], retrieved); + expect(markdown).toBe("Both [1][2]."); + }); + + it("does not treat Markdown links as markers", () => { + expect(inlineMarkerNumbers("See [1](https://example.com) and [2].")).toEqual([2]); + }); +}); + +describe("verifiedQuote", () => { + it("keeps a quote that appears in the excerpt", () => { + expect(verifiedQuote("Compare the columns left to right", retrieved[0].snippet)).toBe( + "Compare the columns left to right", + ); + }); + + it("replaces an invented quote with the excerpt's opening, without search highlights", () => { + expect(verifiedQuote("Something the file never says", "<<Grid>> places items on tracks.")).toBe( + "Grid places items on tracks.", + ); + }); +}); + +describe("stored messages", () => { + it("reads notices and legacy no-match answers", () => { + expect(storedNotice({ notice: "processing" })).toBe("processing"); + expect(storedNotice([{ chunk_id: "a" }])).toBeNull(); + expect(isLegacyNoMatch("I couldn't find any relevant materials in your course documents to answer this question.")).toBe(true); + expect(noticeText("no_match", "INFO 1300")).toBe( + "Your INFO 1300 materials don't cover this. Upload the file that does, or ask it a different way.", + ); + }); + + it("numbers sources with titles and pages from the chunk lookup", () => { + const sources = toSources( + [ + { chunk_id: "a", quote_snippet: "q1" }, + { chunk_id: "gone", quote_snippet: "q2", doc_title: "Old file", page_number: 2 }, + ], + new Map([["a", { title: "Lecture 14", page: 3 }]]), + ); + expect(sources).toEqual([ + { n: 1, chunk_id: "a", title: "Lecture 14", page: 3, quote: "q1", missing: false }, + { n: 2, chunk_id: "gone", title: "Old file", page: 2, quote: "q2", missing: true }, + ]); + }); +}); diff --git a/src/__tests__/client-api.test.ts b/src/__tests__/client-api.test.ts new file mode 100644 index 00000000..ce3eaa97 --- /dev/null +++ b/src/__tests__/client-api.test.ts @@ -0,0 +1,122 @@ +import { afterEach, describe, expect, it, vi } from "vitest" + +import { + ApiError, + SIGNED_OUT_MESSAGE, + apiDelete, + apiGet, + apiPatch, + apiPost, + apiRequest, + failureMessage, + retryAfterSeconds, + sharedFailureReason, +} from "@/lib/client-api" + +type Call = { url: string; init: RequestInit } + +/** Stub fetch with one response; returns the calls it saw. */ +function stubFetch(body: unknown, init: ResponseInit = {}): Call[] { + const calls: Call[] = [] + vi.stubGlobal( + "fetch", + vi.fn(async (url: string, requestInit: RequestInit) => { + calls.push({ url, init: requestInit }) + return new Response(body === undefined ? null : JSON.stringify(body), init) + }) + ) + return calls +} + +async function rejection(promise: Promise<unknown>): Promise<unknown> { + try { + await promise + } catch (error) { + return error + } + throw new Error("expected the request to fail") +} + +afterEach(() => vi.unstubAllGlobals()) + +describe("apiRequest and its helpers", () => { + it("sends JSON with the method and returns the parsed answer", async () => { + const calls = stubFetch({ ok: true }) + await expect(apiPatch("/api/flashcards/d1", { title: "Recursion" })).resolves.toEqual({ ok: true }) + expect(calls[0].url).toBe("/api/flashcards/d1") + expect(calls[0].init.method).toBe("PATCH") + expect(calls[0].init.headers).toEqual({ "Content-Type": "application/json" }) + expect(calls[0].init.body).toBe(JSON.stringify({ title: "Recursion" })) + expect(calls[0].init.signal).toBeInstanceOf(AbortSignal) + }) + + it("sends no body or content type without a body", async () => { + const calls = stubFetch({ deleted: true }) + await apiDelete("/api/guides/g1") + await apiGet("/api/plans") + expect(calls.map((call) => call.init.method)).toEqual(["DELETE", "GET"]) + for (const call of calls) { + expect(call.init.body).toBeUndefined() + expect(call.init.headers).toBeUndefined() + } + }) + + it("sends a DELETE with a body and PUT through apiRequest", async () => { + const calls = stubFetch({}) + await apiRequest("DELETE", "/api/account", { confirm: "DELETE MY ACCOUNT" }) + await apiRequest("PUT", "/api/settings", { timezone: "America/New_York" }) + expect(calls[0].init.body).toBe(JSON.stringify({ confirm: "DELETE MY ACCOUNT" })) + expect(calls[1].init.method).toBe("PUT") + }) + + it("rejects with ApiError carrying status, code and the server's sentence", async () => { + stubFetch({ error: "This deck isn't there anymore.", code: "DECK_NOT_FOUND" }, { status: 404 }) + const error = await rejection(apiPost("/api/flashcards/d1/review", {})) + expect(error).toBeInstanceOf(ApiError) + expect(error).toMatchObject({ status: 404, code: "DECK_NOT_FOUND", message: "This deck isn't there anymore." }) + }) + + it("keeps Retry-After with a 429, so the message can say how long to wait", async () => { + stubFetch({ error: "RATE_LIMITED" }, { status: 429, headers: { "Retry-After": "30" } }) + const error = await rejection(apiPost("/api/chat", { message: "Hi" })) + expect(retryAfterSeconds(error)).toBe(30) + expect(failureMessage(error, "Answer not generated.")).toBe("Too many requests. Retry in 30 seconds.") + }) + + it("prefers the wait the server put in the body", async () => { + stubFetch({ error: "Too many requests.", retry_after_seconds: 120 }, { status: 429, headers: { "Retry-After": "5" } }) + const error = await rejection(apiGet("/api/plans")) + expect(retryAfterSeconds(error)).toBe(120) + expect(sharedFailureReason(error)).toBe("Too many requests. Retry in 2 minutes.") + }) +}) + +describe("shared failure copy", () => { + it("says the sign-in expired on a 401", () => { + expect(sharedFailureReason(new ApiError("Unauthorized", 401))).toBe(SIGNED_OUT_MESSAGE) + }) + + it("uses the server's own 429 sentence without a wait, and never a raw code", () => { + const sentence = new ApiError("x", 429, { error: "Too many sign-in attempts. Retry in 15 minutes." }) + expect(sharedFailureReason(sentence)).toBe("Too many sign-in attempts. Retry in 15 minutes.") + const code = new ApiError("RATE_LIMITED", 429, { error: "RATE_LIMITED" }) + expect(sharedFailureReason(code)).toBe("Too many requests. Retry in a minute.") + }) + + it("names a timeout and a lost connection", () => { + expect(sharedFailureReason(new DOMException("timed out", "TimeoutError"))).toBe( + "The server took too long to answer. Retry." + ) + expect(sharedFailureReason(new TypeError("Failed to fetch"))).toBe("Check your connection and retry.") + }) + + it("leaves everything else to the screen", () => { + const missing = new ApiError("Not found", 404, { code: "DECK_NOT_FOUND" }) + expect(sharedFailureReason(missing)).toBeNull() + expect(failureMessage(missing, "Deck not deleted. Reload the page and retry.")).toBe( + "Deck not deleted. Reload the page and retry." + ) + // The student's own cancel is not a failure to report + expect(sharedFailureReason(new DOMException("aborted", "AbortError"))).toBeNull() + }) +}) diff --git a/src/__tests__/confidence.test.ts b/src/__tests__/confidence.test.ts new file mode 100644 index 00000000..8e20c032 --- /dev/null +++ b/src/__tests__/confidence.test.ts @@ -0,0 +1,35 @@ +import { describe, it, expect } from "vitest"; +import { CONFIDENCE_SCALE, confidenceLabel, confidenceLevel, isSureRating } from "@/lib/confidence"; + +/** One confidence scale for every screen: Guessing, Unsure, Sure, stored as 1, 3 and 5. */ +describe("confidence scale", () => { + it("stores Guessing, Unsure and Sure as 1, 3 and 5, in picker order", () => { + expect(CONFIDENCE_SCALE.map((entry) => [entry.value, entry.label])).toEqual([ + [1, "Guessing"], + [3, "Unsure"], + [5, "Sure"], + ]); + for (const entry of CONFIDENCE_SCALE) expect(confidenceLevel(entry.value)).toBe(entry.level); + }); + + // The old five steps were Guessing, Unsure, Somewhat, Confident and Very sure. + it("reads the older five-step ratings by what they meant", () => { + expect(confidenceLevel(2)).toBe("unsure"); + expect(confidenceLevel(4)).toBe("sure"); + expect(isSureRating(4)).toBe(true); + expect(isSureRating(3)).toBe(false); + }); + + it("treats missing and out-of-range ratings as not rated", () => { + for (const rating of [null, undefined, 0, 6, Number.NaN]) { + expect(confidenceLevel(rating)).toBeNull(); + expect(isSureRating(rating)).toBe(false); + } + }); + + it("labels each level", () => { + expect(confidenceLabel("guessing")).toBe("Guessing"); + expect(confidenceLabel("unsure")).toBe("Unsure"); + expect(confidenceLabel("sure")).toBe("Sure"); + }); +}); diff --git a/src/__tests__/content-context.test.ts b/src/__tests__/content-context.test.ts new file mode 100644 index 00000000..203227f8 --- /dev/null +++ b/src/__tests__/content-context.test.ts @@ -0,0 +1,117 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; + +/** + * The passages a session's questions are written from. Full-text search ANDs + * every word of its query, so searching all objective titles at once found + * almost nothing and sessions fell back to template questions. Each + * objective is searched on its own now. Search and Prisma are mocked: a + * chunk "matches" when it contains every word of the query. + */ +const search = vi.hoisted(() => ({ searchChunks: vi.fn() })); +vi.mock("@/lib/search", () => search); +const db = vi.hoisted(() => ({ contentChunk: { count: vi.fn() } })); +vi.mock("@/lib/db", () => ({ prisma: db })); + +import { fallbackWords, getContentContextForSession, mergeRoundRobin } from "@/services/content-plan"; +import type { SearchParams, SearchResult } from "@/lib/search"; + +interface Chunk { + id: string; + exam?: string; + text: string; +} + +const CHUNKS: Chunk[] = [ + { id: "rec-1", exam: "Prelim 1", text: "recursion base case and recursive call" }, + { id: "rec-2", exam: "Prelim 1", text: "recursion on linked structures" }, + { id: "stack-1", exam: "Prelim 1", text: "stacks push pop last in first out" }, + { id: "stack-2", text: "stacks hold the call frames of a recursion" }, + { id: "graph-1", text: "graphs breadth first search uses a queue" }, + { id: "sort-1", exam: "Final", text: "merge sort splits the array" }, +]; + +function result(chunk: Chunk, rank = 1): SearchResult { + return { chunk_id: chunk.id, doc_id: "doc", doc_title: "Lecture", page_number: 1, rank_score: rank, snippet: chunk.text }; +} + +beforeEach(() => { + vi.clearAllMocks(); + db.contentChunk.count.mockResolvedValue(CHUNKS.length); + search.searchChunks.mockImplementation(async (params: SearchParams) => { + const words = params.q.toLowerCase().split(/\s+/).filter(Boolean); + return CHUNKS.filter((c) => !params.examName || c.exam === params.examName) + .filter((c) => words.every((w) => c.text.includes(w))) + .slice(0, params.topK ?? 5) + .map((c) => result(c)); + }); +}); + +const queries = () => search.searchChunks.mock.calls.map(([p]) => (p as SearchParams).q); + +describe("getContentContextForSession", () => { + it("searches each objective on its own and takes from each in turn", async () => { + const context = await getContentContextForSession("u1", "CS 2110", "INTERLEAVED_PRACTICE", ["Recursion", "Stacks"], 4); + + // Never one query holding every title, and no mode words + expect(queries()).toEqual(["Recursion", "Stacks"]); + expect(context.snippets.map((s) => s.chunk_id)).toEqual(["rec-1", "stack-1", "rec-2", "stack-2"]); + expect(context.totalChunks).toBe(CHUNKS.length); + }); + + it("asks each objective for at least 2 chunks, and caps the total at topK", async () => { + await getContentContextForSession("u1", "CS 2110", "EXAM_SIM", ["Recursion", "Stacks", "Graphs", "Sorting"], 5); + for (const [params] of search.searchChunks.mock.calls) expect((params as SearchParams).topK).toBe(2); + + const context = await getContentContextForSession("u1", "CS 2110", "EXAM_SIM", ["Recursion", "Stacks"], 3); + expect(context.snippets).toHaveLength(3); + }); + + it("finds an objective through its main words when the whole title matches nothing", async () => { + const context = await getContentContextForSession("u1", "CS 2110", "RETRIEVAL", ["Understanding graphs and queues"], 5); + + expect(queries()[0]).toBe("Understanding graphs and queues"); + // Then its main words one at a time; "Understanding" and "and" are never searched + expect(queries().slice(1).sort()).toEqual(["graphs", "queues"]); + expect(context.snippets.map((s) => s.chunk_id)).toEqual(["graph-1"]); + }); + + it("prefers the exam's files and uses the whole course when they have nothing on an objective", async () => { + const context = await getContentContextForSession("u1", "CS 2110", "RETRIEVAL", ["Stacks", "Graphs"], 6, { + examName: "Prelim 1", + }); + + const ids = context.snippets.map((s) => s.chunk_id); + // Stacks: Prelim 1 has a chunk, so the untagged one is not used + expect(ids).toContain("stack-1"); + expect(ids).not.toContain("stack-2"); + // Graphs: nothing for Prelim 1, so the course-wide chunk stands in + expect(ids).toContain("graph-1"); + }); + + it("returns no passages and runs no search without objectives", async () => { + const context = await getContentContextForSession("u1", "CS 2110", "RETRIEVAL", [" ", ""], 5); + expect(context.snippets).toEqual([]); + expect(search.searchChunks).not.toHaveBeenCalled(); + }); +}); + +describe("mergeRoundRobin", () => { + it("skips a chunk two objectives share", () => { + const [a, b, c] = CHUNKS; + expect(mergeRoundRobin([[result(a), result(b)], [result(a), result(c)]], 5).map((r) => r.chunk_id)).toEqual([ + "rec-1", + "rec-2", + "stack-1", + ]); + }); +}); + +describe("fallbackWords", () => { + it("keeps the 3 longest distinct words and drops filler", () => { + expect(fallbackWords("Explain the call stack and the call frames of recursion")).toEqual([ + "recursion", + "frames", + "stack", + ]); + }); +}); diff --git a/src/__tests__/content-process-claim.test.ts b/src/__tests__/content-process-claim.test.ts new file mode 100644 index 00000000..b9e61bf9 --- /dev/null +++ b/src/__tests__/content-process-claim.test.ts @@ -0,0 +1,134 @@ +/** + * processDocument claims a file before reading it, so a second request (a + * double click, another tab) never runs a second extraction, and a claim + * from a run that died lapses. + */ +import { describe, it, expect, vi, beforeEach } from "vitest"; + +vi.mock("@/lib/db", () => ({ + prisma: { + contentDocument: { + findUnique: vi.fn(), + updateMany: vi.fn(), + update: vi.fn(), + }, + contentChunk: { count: vi.fn() }, + $transaction: vi.fn(), + }, +})); + +vi.mock("@/lib/storage", () => ({ + sha256: vi.fn(), + saveFile: vi.fn(), + deleteStoredFile: vi.fn(), + resolveStoragePath: vi.fn((key: string) => `/uploads/${key}`), +})); + +vi.mock("@/lib/extractor", async (importOriginal) => ({ + ...(await importOriginal<typeof import("@/lib/extractor")>()), + extractDocumentText: vi.fn(), +})); + +vi.mock("@/lib/error-reporter", () => ({ captureException: vi.fn() })); + +import { PROCESSING_CLAIM_MS, processDocument, visibleDocumentStatus } from "@/services/content"; +import { prisma } from "@/lib/db"; +import { DocumentTooLongError, extractDocumentText } from "@/lib/extractor"; +import { captureException } from "@/lib/error-reporter"; + +const findUnique = prisma.contentDocument.findUnique as ReturnType<typeof vi.fn>; +const updateMany = prisma.contentDocument.updateMany as ReturnType<typeof vi.fn>; +const chunkCount = prisma.contentChunk.count as ReturnType<typeof vi.fn>; +const extract = extractDocumentText as ReturnType<typeof vi.fn>; + +const DOC = { + id: "doc-1", + userId: "user-1", + status: "UPLOADED", + storageKey: "user-1/doc-1/notes.txt", + mimeType: "text/plain", + title: "Notes", + courseName: "CS 2110", + examName: null, +}; + +describe("processDocument", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("answers PROCESSING without extracting when another request holds the claim", async () => { + findUnique.mockResolvedValueOnce({ ...DOC, status: "PROCESSING" }).mockResolvedValueOnce({ status: "PROCESSING" }); + updateMany.mockResolvedValueOnce({ count: 0 }); + + const result = await processDocument("user-1", "doc-1"); + + expect(result).toEqual({ data: { document_id: "doc-1", status: "PROCESSING", chunk_count: 0 } }); + expect(extract).not.toHaveBeenCalled(); + }); + + it("answers PROCESSED when the other request finished in the meantime", async () => { + findUnique.mockResolvedValueOnce(DOC).mockResolvedValueOnce({ status: "PROCESSED" }); + updateMany.mockResolvedValueOnce({ count: 0 }); + chunkCount.mockResolvedValueOnce(4); + + const result = await processDocument("user-1", "doc-1"); + + expect(result).toEqual({ data: { document_id: "doc-1", status: "PROCESSED", chunk_count: 4 } }); + expect(extract).not.toHaveBeenCalled(); + }); + + it("claims only uploaded or failed files, or a claim that lapsed", async () => { + findUnique.mockResolvedValueOnce(DOC); + updateMany.mockResolvedValueOnce({ count: 1 }); + extract.mockRejectedValueOnce(new Error("unreadable")); + + await processDocument("user-1", "doc-1"); + + const where = updateMany.mock.calls[0][0].where; + expect(where.id).toBe("doc-1"); + expect(where.OR[0]).toEqual({ status: { in: ["UPLOADED", "FAILED"] } }); + expect(where.OR[1].status).toBe("PROCESSING"); + expect(Date.now() - where.OR[1].updatedAt.lt.getTime()).toBeGreaterThanOrEqual(PROCESSING_CLAIM_MS - 1000); + expect(updateMany.mock.calls[0][0].data.status).toBe("PROCESSING"); + expect(extract).toHaveBeenCalledTimes(1); + }); + + it("marks a file over the reading limits FAILED with reason too_long, not as a fault", async () => { + findUnique.mockResolvedValueOnce(DOC); + updateMany.mockResolvedValueOnce({ count: 1 }); + extract.mockRejectedValueOnce(new DocumentTooLongError()); + + const result = await processDocument("user-1", "doc-1"); + + expect(result).toEqual({ + data: { document_id: "doc-1", status: "FAILED", chunk_count: 0, reason: "too_long" }, + }); + expect(prisma.contentDocument.update).toHaveBeenCalledWith({ + where: { id: "doc-1" }, + data: { status: "FAILED", errorMessage: "This file is too long to read. Split it into smaller files." }, + }); + expect(captureException).not.toHaveBeenCalled(); + }); + + it("reports any other extraction failure as unreadable", async () => { + findUnique.mockResolvedValueOnce(DOC); + updateMany.mockResolvedValueOnce({ count: 1 }); + extract.mockRejectedValueOnce(new Error("bad XRef entry")); + + const result = await processDocument("user-1", "doc-1"); + + expect(result).toMatchObject({ data: { status: "FAILED", reason: "unreadable" } }); + expect(captureException).toHaveBeenCalledTimes(1); + }); +}); + +describe("visibleDocumentStatus", () => { + const now = new Date("2026-10-15T20:00:00Z"); + + it("shows a fresh claim as processing and a lapsed one as uploaded", () => { + expect(visibleDocumentStatus("PROCESSING", new Date(now.getTime() - 60_000), now)).toBe("PROCESSING"); + expect(visibleDocumentStatus("PROCESSING", new Date(now.getTime() - PROCESSING_CLAIM_MS - 1), now)).toBe("UPLOADED"); + expect(visibleDocumentStatus("PROCESSED", new Date(0), now)).toBe("PROCESSED"); + }); +}); diff --git a/src/__tests__/content-upload.test.ts b/src/__tests__/content-upload.test.ts index d4b69ab7..335cf67b 100644 --- a/src/__tests__/content-upload.test.ts +++ b/src/__tests__/content-upload.test.ts @@ -70,6 +70,24 @@ describe("uploadDocument", () => { expect(createMock).not.toHaveBeenCalled(); }); + it("says which course an existing file belongs to on a dedupe hit", async () => { + findUniqueMock.mockResolvedValueOnce({ + id: "doc-existing", + status: "PROCESSED", + courseName: "AEM 2210", + examName: "Prelim 1", + }); + + const result = await upload(); + + expect(result).toMatchObject({ + document_id: "doc-existing", + deduped: true, + course_name: "AEM 2210", + exam_name: "Prelim 1", + }); + }); + it("saves the file before creating the row and stores the real storage key", async () => { findUniqueMock.mockResolvedValueOnce(null); diff --git a/src/__tests__/crypto.test.ts b/src/__tests__/crypto.test.ts index e912033c..edc64e5f 100644 --- a/src/__tests__/crypto.test.ts +++ b/src/__tests__/crypto.test.ts @@ -11,10 +11,10 @@ describe("crypto encrypt/decrypt", () => { let decrypt: (encoded: string) => string; beforeAll(async () => { - process.env.GOOGLE_TOKEN_ENC_KEY = TEST_KEY_HEX; - const mod = await import("@/lib/crypto"); - encrypt = mod.encrypt; - decrypt = mod.decrypt; + process.env.TOKEN_ENC_KEY = TEST_KEY_HEX; + const mod = await import("@/lib/crypto/token-vault"); + encrypt = mod.encryptToken; + decrypt = mod.decryptToken; }); it("roundtrips a simple string", () => { diff --git a/src/__tests__/email-provider.test.ts b/src/__tests__/email-provider.test.ts new file mode 100644 index 00000000..1ba6b1cb --- /dev/null +++ b/src/__tests__/email-provider.test.ts @@ -0,0 +1,91 @@ +/** + * Email links without SMTP: the console provider prints reset and + * verification links only where a developer or the e2e suite reads them, + * never in a production log, and the public config tells screens whether + * an email can reach the student at all. + */ +import { afterEach, beforeEach, describe, expect, it, vi, type MockInstance } from "vitest"; + +import { areEmailLinksAvailable, isEmailDeliveryConfigured, mayPrintEmailLinks } from "@/lib/email/delivery"; +import { ConsoleProvider, createEmailProvider } from "@/lib/email/provider"; +import { publicConfig } from "@/lib/public-config"; + +const TOKEN = "raw-reset-token-1234567890"; +const RESET_URL = `https://studybot.example/auth/reset-password?token=${TOKEN}`; +const HTML = `<p>Choose a new password.</p><a href="${RESET_URL}">Reset password</a>`; + +/** Every line the provider wrote to stdout, joined. */ +function printed(spy: MockInstance<typeof console.log>): string { + return spy.mock.calls.map((args) => args.map(String).join(" ")).join("\n"); +} + +describe("email links without SMTP", () => { + let log: MockInstance<typeof console.log>; + + beforeEach(() => { + vi.stubEnv("EMAIL_PROVIDER", "console"); + vi.stubEnv("ALLOW_TEST_AUTH", ""); + vi.stubEnv("CI", ""); + // The logger is silent under vitest unless a level is set. + vi.stubEnv("LOG_LEVEL", "info"); + log = vi.spyOn(console, "log").mockImplementation(() => {}); + }); + + afterEach(() => { + vi.unstubAllEnvs(); + vi.restoreAllMocks(); + }); + + it("prints the full link in development, so the developer can follow it", async () => { + vi.stubEnv("NODE_ENV", "development"); + await new ConsoleProvider().send("student@example.com", "Reset your Study Bot password", HTML); + expect(printed(log)).toContain(RESET_URL); + }); + + it("never writes the link or the token to a production log", async () => { + vi.stubEnv("NODE_ENV", "production"); + await new ConsoleProvider().send("student@example.com", "Reset your Study Bot password", HTML); + const out = printed(log); + expect(out).not.toContain(TOKEN); + expect(out).not.toContain("reset-password"); + // The operator still learns that an email didn't go out. + expect(out).toContain("email_not_delivered"); + expect(out).toContain("Reset your Study Bot password"); + }); + + it("prints links on the CI e2e server, which already trusts test sign-in", async () => { + vi.stubEnv("NODE_ENV", "production"); + vi.stubEnv("ALLOW_TEST_AUTH", "true"); + vi.stubEnv("CI", "true"); + vi.stubEnv("NEXTAUTH_URL", "http://localhost:3000"); + expect(mayPrintEmailLinks()).toBe(true); + await new ConsoleProvider().send("student@example.com", "Reset your Study Bot password", HTML); + expect(printed(log)).toContain(RESET_URL); + }); + + it("warns once at startup when a production server can't send email", () => { + vi.stubEnv("NODE_ENV", "production"); + createEmailProvider(); + expect(printed(log)).toContain("email.not_configured"); + + log.mockClear(); + vi.stubEnv("NODE_ENV", "development"); + createEmailProvider(); + expect(printed(log)).not.toContain("email.not_configured"); + }); + + it("offers email links in development and with SMTP, and not on a production server without SMTP", () => { + vi.stubEnv("NODE_ENV", "development"); + expect(areEmailLinksAvailable()).toBe(true); + expect(publicConfig()).toMatchObject({ email_configured: false, email_links_available: true }); + + vi.stubEnv("NODE_ENV", "production"); + expect(isEmailDeliveryConfigured()).toBe(false); + expect(areEmailLinksAvailable()).toBe(false); + expect(publicConfig()).toMatchObject({ email_configured: false, email_links_available: false }); + + vi.stubEnv("EMAIL_PROVIDER", "smtp"); + expect(areEmailLinksAvailable()).toBe(true); + expect(publicConfig()).toMatchObject({ email_configured: true, email_links_available: true }); + }); +}); diff --git a/src/__tests__/email-templates.test.ts b/src/__tests__/email-templates.test.ts new file mode 100644 index 00000000..3bd8d5bd --- /dev/null +++ b/src/__tests__/email-templates.test.ts @@ -0,0 +1,60 @@ +/** + * Account emails: copy per VOICE.md, escaping, and no dead settings links. + */ +import { describe, it, expect, beforeEach, vi } from "vitest"; +import { emailVerification, passwordReset } from "@/lib/email/templates"; + +function visibleText(html: string): string { + return html + .replace(/<[^>]+>/g, " ") + .replace(/ /g, " ") + .replace(/\s+/g, " ") + .trim(); +} + +describe("account email templates", () => { + beforeEach(() => { + vi.stubEnv("BASE_URL", "https://studybot.example"); + }); + + const emails = [ + emailVerification("Ben", "https://studybot.example/api/auth/verify-email?token=abc"), + passwordReset("Ben", "https://studybot.example/auth/reset-password?token=xyz"), + ]; + + it("keeps the subjects", () => { + expect(emails[0].subject).toBe("Verify your Study Bot account"); + expect(emails[1].subject).toBe("Reset your Study Bot password"); + }); + + it("states the link expiry and carries the link twice (button and fallback)", () => { + expect(visibleText(emails[0].html)).toContain("This link expires in 24 hours."); + expect(visibleText(emails[1].html)).toContain("This link expires in 1 hour."); + expect(emails[0].html.match(/verify-email\?token=abc/g)).toHaveLength(3); + expect(emails[1].html.match(/reset-password\?token=xyz/g)).toHaveLength(3); + }); + + it("drops the jokes, the notification footer, dashes, exclamation marks and 'we'", () => { + for (const { html } of emails) { + const text = visibleText(html); + expect(html).not.toContain("#notifications"); + expect(text).not.toMatch(/reminders|unsubscribe/i); + expect(text).not.toMatch(/[–—!]/); + expect(text).not.toMatch(/\b(we|we're|we've|our)\b/i); + expect(text).not.toMatch(/journey|robot|hopefully/i); + } + }); + + it("uses the new palette, not the chalkboard one", () => { + for (const { html } of emails) { + expect(html).toContain("#0B57D0"); + expect(html).not.toMatch(/#2a3d2a|#f0dc4e/i); + } + }); + + it("escapes the name and falls back when it is blank", () => { + const { html } = emailVerification("<b>Ben</b>", "https://x.test/v"); + expect(html).toContain("Hi <b>Ben</b>,"); + expect(visibleText(emailVerification(" ", "https://x.test/v").html)).toContain("Hi,"); + }); +}); diff --git a/src/__tests__/embed-chunks.test.ts b/src/__tests__/embed-chunks.test.ts index 38e51b98..eda63afd 100644 --- a/src/__tests__/embed-chunks.test.ts +++ b/src/__tests__/embed-chunks.test.ts @@ -57,18 +57,31 @@ vi.mock("@/lib/db", () => { }; }); -// Mock the AI gateway so no provider/budget/circuit logic runs -vi.mock("@/lib/ai/gateway", () => ({ +// Mock the AI gateway's embed so no provider/budget/circuit logic runs +// (GatewayError stays real so the handler can recognize budget errors) +vi.mock("@/lib/ai/gateway", async (importOriginal) => ({ + ...(await importOriginal<typeof import("@/lib/ai/gateway")>()), embed: vi.fn(), })); -import { handleEmbedChunkBatch } from "@/lib/jobs/handlers/embed-chunks"; -import { embed } from "@/lib/ai/gateway"; +vi.mock("@/lib/jobs/queue", () => ({ + enqueueJob: vi.fn(async () => "job_deferred"), +})); + +import { + handleEmbedChunkBatch, + sliceForEmbedding, + estimateTokens, + MAX_INPUTS_PER_REQUEST, +} from "@/lib/jobs/handlers/embed-chunks"; +import { embed, GatewayError } from "@/lib/ai/gateway"; +import { enqueueJob } from "@/lib/jobs/queue"; import { prisma } from "@/lib/db"; import { MockProvider } from "@/lib/ai/providers/mock"; const chunkStore = (prisma as unknown as { _test: { chunks: ChunkRow[] } })._test.chunks; const embedMock = vi.mocked(embed); +const enqueueMock = vi.mocked(enqueueJob); const executeRawMock = prisma.$executeRawUnsafe as unknown as Mock; function seedChunks(...rows: ChunkRow[]) { @@ -191,4 +204,85 @@ describe("handleEmbedChunkBatch", () => { expect(embedMock).not.toHaveBeenCalled(); }); + + it("embeds a large document in request-sized slices, against the upload budget", async () => { + const ids = Array.from({ length: 600 }, (_, i) => `c${i}`); + seedChunks(...ids.map((id) => ({ id, text: `text ${id}`, embeddingStatus: "PENDING" }))); + + await handleEmbedChunkBatch({ chunkIds: ids, userId: "u1" }, provider); + + expect(embedMock.mock.calls.map((c) => c[1].length)).toEqual([ + MAX_INPUTS_PER_REQUEST, + MAX_INPUTS_PER_REQUEST, + 600 - 2 * MAX_INPUTS_PER_REQUEST, + ]); + for (const call of embedMock.mock.calls) expect(call[3]).toEqual({ budget: "upload" }); + expect(ids.every((id) => statusOf(id) === "DONE")).toBe(true); + }); + + it("defers the rest to the next budget day when the upload budget runs out", async () => { + const ids = Array.from({ length: MAX_INPUTS_PER_REQUEST + 3 }, (_, i) => `c${i}`); + seedChunks(...ids.map((id) => ({ id, text: `text ${id}`, embeddingStatus: "PENDING" }))); + embedMock + .mockImplementationOnce(async (_ctx, texts) => ({ embeddings: texts.map(() => [1, 2, 3]) })) + .mockRejectedValueOnce(new GatewayError("BUDGET_EXCEEDED", "Daily embedding budget reached.", false)); + + const before = Date.now(); + await handleEmbedChunkBatch({ chunkIds: ids, userId: "u1" }, provider); + + const firstSlice = ids.slice(0, MAX_INPUTS_PER_REQUEST); + const rest = ids.slice(MAX_INPUTS_PER_REQUEST); + expect(firstSlice.every((id) => statusOf(id) === "DONE")).toBe(true); + // Not FAILED: the deferred job picks them up after the budget resets + expect(rest.map(statusOf)).toEqual(["PENDING", "PENDING", "PENDING"]); + + expect(enqueueMock).toHaveBeenCalledTimes(1); + const [type, payload, opts] = enqueueMock.mock.calls[0]; + expect(type).toBe("EMBED_CHUNK_BATCH"); + expect(payload).toEqual({ chunkIds: rest, userId: "u1" }); + const runAfter = (opts as { runAfter: Date }).runAfter; + expect(runAfter.getTime()).toBeGreaterThan(before); + expect(runAfter.getUTCHours()).toBe(0); + }); + + it("fails the batch when the provider returns the wrong number of vectors", async () => { + seedChunks( + { id: "c1", text: "alpha", embeddingStatus: "PENDING" }, + { id: "c2", text: "beta", embeddingStatus: "PENDING" }, + ); + embedMock.mockResolvedValueOnce({ embeddings: [[1, 2, 3]] }); + + await expect( + handleEmbedChunkBatch({ chunkIds: ["c1", "c2"], userId: "u1" }, provider), + ).rejects.toThrow(/count mismatch/); + + expect(statusOf("c1")).toBe("FAILED"); + expect(statusOf("c2")).toBe("FAILED"); + expect(enqueueMock).not.toHaveBeenCalled(); + }); +}); + +describe("sliceForEmbedding", () => { + const items = (n: number, chars: number) => + Array.from({ length: n }, (_, i) => ({ id: `c${i}`, text: "x".repeat(chars) })); + + it("caps inputs per request and keeps the order", () => { + const slices = sliceForEmbedding(items(5, 10), 2, 1_000); + expect(slices.map((s) => s.map((c) => c.id))).toEqual([["c0", "c1"], ["c2", "c3"], ["c4"]]); + }); + + it("caps estimated tokens per request", () => { + const perItem = estimateTokens("x".repeat(1_600)); + const slices = sliceForEmbedding(items(10, 1_600), 100, perItem * 4); + expect(slices.map((s) => s.length)).toEqual([4, 4, 2]); + }); + + it("gives an oversized item a request of its own", () => { + const slices = sliceForEmbedding([{ text: "x".repeat(900) }, { text: "y" }], 10, 100); + expect(slices.map((s) => s.length)).toEqual([1, 1]); + }); + + it("returns no slices for no items", () => { + expect(sliceForEmbedding([])).toEqual([]); + }); }); diff --git a/src/__tests__/event-builder.test.ts b/src/__tests__/event-builder.test.ts index 4212235b..2e2cdca6 100644 --- a/src/__tests__/event-builder.test.ts +++ b/src/__tests__/event-builder.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from "vitest"; -import { buildEventPayload, computeEventHash, _hashUserIdForTest } from "@/lib/google/event-builder"; +import { buildEventPayload, computeEventHash, hashUserId } from "@/lib/google/event-builder"; import type { CalendarEventInput } from "@/lib/google/calendar-client"; const baseInput = { @@ -30,7 +30,7 @@ describe("buildEventPayload", () => { expect(input.summary).toContain("CS 2110"); expect(input.summary).toContain("Prelim 1"); expect(input.summary).toContain("Retrieval"); - expect(input.summary).toContain("Loops and invariants"); + expect(input.summary).toContain("Understand loop invariants"); expect(input.start).toBe("2026-04-10T14:00:00Z"); expect(input.end).toBe("2026-04-10T15:20:00Z"); expect(input.transparency).toBe("opaque"); @@ -40,31 +40,66 @@ describe("buildEventPayload", () => { it("includes session deep link in description", () => { const { input } = buildEventPayload(baseInput); - expect(input.description).toContain("https://studybot.example.com/s/sess_ghi789"); - expect(input.description).toContain("StudyBot session:"); + expect(input.description).toContain("Open the session: https://studybot.example.com/s/sess_ghi789"); }); - it("includes objectives with truncation", () => { + it("titles the event mode first, then the topics, course and exam", () => { + const { input } = buildEventPayload(baseInput); + // The same topics as the description, from the objectives + expect(input.summary).toBe( + "Retrieval: Understand loop invariants, Write correct loop bounds, and Prove termination · CS 2110 Prelim 1", + ); + }); + + it("names the first 3 topics in the title and counts the rest", () => { + const manyObjectives = Array.from({ length: 6 }, (_, i) => `Topic ${i + 1}`); + const { input } = buildEventPayload({ ...baseInput, mode: "EXAM_SIM", objectives: manyObjectives }); + expect(input.summary).toBe("Exam simulation: Topic 1, Topic 2, Topic 3, and 3 more · CS 2110 Prelim 1"); + }); + + it("titles a follow-up stored with the old marker by its topics alone", () => { + const { input } = buildEventPayload({ + ...baseInput, + topicScope: "Follow-up: Recursion, Stacks", + objectives: null, + }); + expect(input.summary).toBe("Retrieval: Recursion and Stacks · CS 2110 Prelim 1"); + expect(input.description).toContain("Topics: Recursion and Stacks"); + }); + + it("lists the first topics and counts the rest", () => { const manyObjectives = Array.from({ length: 8 }, (_, i) => `Objective ${i + 1}`); const { input } = buildEventPayload({ ...baseInput, objectives: manyObjectives }); expect(input.description).toContain("Objective 1"); - expect(input.description).toContain("Objective 5"); - expect(input.description).not.toContain("Objective 6"); - expect(input.description).toContain("+3 more"); + expect(input.description).toContain("Objective 6"); + expect(input.description).not.toContain("Objective 7"); + expect(input.description).toContain("and 2 more"); }); - it("includes mode, target, and break protocol", () => { + it("reads objectives stored as { id, title } objects", () => { + const { input } = buildEventPayload({ + ...baseInput, + objectives: [ + { id: "loops", title: "Loop invariants" }, + { id: "bounds", title: "Loop bounds" }, + ], + }); + expect(input.description).toContain("Topics: Loop invariants and Loop bounds"); + expect(input.description).not.toContain("[object Object]"); + }); + + it("states the mode, questions and target in plain words", () => { const { input } = buildEventPayload(baseInput); - expect(input.description).toContain("Mode: Retrieval"); - expect(input.description).toContain("10 prompts"); - expect(input.description).toContain("target 80%"); - expect(input.description).toContain("Protocol: 50/10"); - expect(input.description).toContain("phone away"); + expect(input.description).toContain("Retrieval session for CS 2110 Prelim 1"); + expect(input.description).toContain("10 questions. Target accuracy: 80%."); + // One block: no break line + expect(input.description).not.toContain("break"); + expect(input.description).not.toMatch(/StudyBot|Protocol|prompts|\+\d+ more/); }); - it("includes 'Created by Study Bot' footer", () => { + it("includes 'Added by Study Bot' footer", () => { const { input } = buildEventPayload(baseInput); - expect(input.description).toContain("Created by Study Bot"); + expect(input.description).toContain("Added by Study Bot"); }); it("sets sb_* extended properties", () => { @@ -73,7 +108,7 @@ describe("buildEventPayload", () => { expect(ext.sb_plan).toBe("plan_abc123"); expect(ext.sb_item).toBe("item_def456"); expect(ext.sb_sess).toBe("sess_ghi789"); - expect(ext.sb_uid).toBe(_hashUserIdForTest("user_42")); + expect(ext.sb_uid).toBe(hashUserId("user_42")); // sb_uid should be 16 hex chars expect(ext.sb_uid).toHaveLength(16); expect(ext.sb_uid).toMatch(/^[0-9a-f]+$/); @@ -86,10 +121,10 @@ describe("buildEventPayload", () => { targetOutcome: null, breakProtocol: null, }); - expect(input.description).toContain("StudyBot session:"); - expect(input.description).not.toContain("Objectives:"); - expect(input.description).not.toContain("Target:"); - expect(input.description).not.toContain("Protocol:"); + expect(input.description).toContain("Open the session:"); + expect(input.description).toContain("Topics: Loops and invariants"); + expect(input.description).not.toContain("questions"); + expect(input.description).not.toContain("Target accuracy"); }); }); @@ -154,3 +189,15 @@ describe("computeEventHash", () => { expect(computeEventHash(base)).toBe(computeEventHash(modified)); }); }); + +describe("hashUserId", () => { + it("produces a consistent 16-char hex string", () => { + const hash = hashUserId("user-123"); + expect(hash).toMatch(/^[0-9a-f]{16}$/); + expect(hashUserId("user-123")).toBe(hash); + }); + + it("gives different users different hashes", () => { + expect(hashUserId("user-1")).not.toBe(hashUserId("user-2")); + }); +}); diff --git a/src/__tests__/extractor.test.ts b/src/__tests__/extractor.test.ts new file mode 100644 index 00000000..6af1f432 --- /dev/null +++ b/src/__tests__/extractor.test.ts @@ -0,0 +1,132 @@ +/** + * Unit tests for document text extraction, including a real PDF parse. + * + * The PDF fixture is generated in memory (one page per string, Helvetica + * text, a correct xref table) so the repo carries no binary test files. + */ +import { describe, it, expect, beforeAll, afterAll } from "vitest"; +import { mkdtemp, rm, writeFile } from "fs/promises"; +import { tmpdir } from "os"; +import { join } from "path"; +import { DocumentTooLongError, EXTRACTION_LIMITS, extractDocumentText } from "@/lib/extractor"; + +/** Build a minimal valid PDF with one line of text per page. */ +function buildPdf(pageTexts: string[]): Buffer { + const objects: string[] = []; + const pageCount = pageTexts.length; + // 1: catalog, 2: page tree, 3: font, then a (page, content) pair per page + const pageIds = pageTexts.map((_, i) => 4 + i * 2); + objects.push("<< /Type /Catalog /Pages 2 0 R >>"); + objects.push(`<< /Type /Pages /Kids [${pageIds.map((id) => `${id} 0 R`).join(" ")}] /Count ${pageCount} >>`); + objects.push("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>"); + for (const [i, text] of pageTexts.entries()) { + const stream = `BT /F1 18 Tf 72 720 Td (${text}) Tj ET`; + objects.push( + `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 3 0 R >> >> /Contents ${pageIds[i] + 1} 0 R >>`, + ); + objects.push(`<< /Length ${stream.length} >>\nstream\n${stream}\nendstream`); + } + + let pdf = "%PDF-1.4\n"; + const offsets: number[] = []; + objects.forEach((body, i) => { + offsets.push(pdf.length); + pdf += `${i + 1} 0 obj\n${body}\nendobj\n`; + }); + const xrefStart = pdf.length; + pdf += `xref\n0 ${objects.length + 1}\n0000000000 65535 f \n`; + for (const offset of offsets) pdf += `${String(offset).padStart(10, "0")} 00000 n \n`; + pdf += `trailer\n<< /Size ${objects.length + 1} /Root 1 0 R >>\nstartxref\n${xrefStart}\n%%EOF\n`; + return Buffer.from(pdf, "latin1"); +} + +describe("extractDocumentText", () => { + let dir: string; + + beforeAll(async () => { + dir = await mkdtemp(join(tmpdir(), "studybot-extractor-")); + }); + + afterAll(async () => { + await rm(dir, { recursive: true, force: true }); + }); + + it("extracts the text of a small PDF page by page", async () => { + // Under 4 KB, which used to trip pdf.js when handed a pooled Buffer + const file = join(dir, "notes.pdf"); + await writeFile(file, buildPdf(["Spacing beats cramming", "Retrieval practice works"])); + + const result = await extractDocumentText(file, "application/pdf"); + + expect(result.fullText).toContain("Spacing beats cramming"); + expect(result.fullText).toContain("Retrieval practice works"); + expect(result.pages).toEqual([ + { pageNumber: 1, text: "Spacing beats cramming" }, + { pageNumber: 2, text: "Retrieval practice works" }, + ]); + }); + + it("keeps real page numbers when a page has no text", async () => { + const file = join(dir, "gap.pdf"); + await writeFile(file, buildPdf(["First page", "", "Third page"])); + + const result = await extractDocumentText(file, "application/pdf"); + + expect(result.pages).toEqual([ + { pageNumber: 1, text: "First page" }, + { pageNumber: 3, text: "Third page" }, + ]); + }); + + describe("reading limits", () => { + const pdf = async (name: string, pages: string[]) => { + const file = join(dir, name); + await writeFile(file, buildPdf(pages)); + return file; + }; + + it("refuses a PDF with more pages than the limit instead of reading part of it", async () => { + const file = await pdf("long.pdf", ["One", "Two", "Three"]); + await expect(extractDocumentText(file, "application/pdf", { ...EXTRACTION_LIMITS, maxPages: 2 })).rejects.toThrow( + DocumentTooLongError, + ); + // At the limit it reads normally + const result = await extractDocumentText(file, "application/pdf", { ...EXTRACTION_LIMITS, maxPages: 3 }); + expect(result.pages).toHaveLength(3); + }); + + it("stops reading once the text passes the character limit", async () => { + const file = await pdf("dense.pdf", ["Retrieval practice beats rereading", "Spacing beats cramming"]); + const error = await extractDocumentText(file, "application/pdf", { ...EXTRACTION_LIMITS, maxChars: 20 }).catch( + (e: unknown) => e, + ); + expect(error).toBeInstanceOf(DocumentTooLongError); + expect((error as Error).message).toBe("This file is too long to read. Split it into smaller files."); + }); + + it("stops reading once the time budget is spent", async () => { + const file = await pdf("slow.pdf", ["First page", "Second page"]); + await expect(extractDocumentText(file, "application/pdf", { ...EXTRACTION_LIMITS, maxMs: -1 })).rejects.toThrow( + DocumentTooLongError, + ); + }); + + it("refuses a text file over the character limit", async () => { + const file = join(dir, "huge.md"); + await writeFile(file, "word ".repeat(10), "utf-8"); + await expect(extractDocumentText(file, "text/markdown", { ...EXTRACTION_LIMITS, maxChars: 20 })).rejects.toThrow( + DocumentTooLongError, + ); + }); + }); + + it("reads text files as UTF-8 and normalizes whitespace", async () => { + const file = join(dir, "notes.md"); + await writeFile(file, "# Title\r\n\r\n\r\n\r\nSome text\twith gaps\n", "utf-8"); + + const result = await extractDocumentText(file, "text/markdown"); + + expect(result.fullText).toBe("# Title\n\nSome text with gaps"); + expect(result.pages).toBeUndefined(); + }); +}); diff --git a/src/__tests__/fake-calendar-client.test.ts b/src/__tests__/fake-calendar-client.test.ts deleted file mode 100644 index d3e856a9..00000000 --- a/src/__tests__/fake-calendar-client.test.ts +++ /dev/null @@ -1,270 +0,0 @@ -/** - * Unit tests for FakeCalendarClient. - * - * Tests: - * - insert/update/delete lifecycle - * - 404 delete treated as notFound (not error) - * - upsertEvent skip-unchanged - * - upsertEvent reconciliation via extended property - * - freeBusy query filtering - * - error injection (401, invalid_grant, 429) - * - call log tracking - * - healthCheck - */ -import { describe, it, expect, beforeEach } from "vitest"; -import { FakeCalendarClient, FakeApiError, FakeReconnectError } from "@/lib/calendar/google/fake-google"; -import { computeEventHash } from "@/lib/calendar/hash"; -import type { CalendarEventPayload } from "@/lib/calendar/types"; - -const testPayload: CalendarEventPayload = { - summary: "Test Event", - start: "2025-06-01T09:00:00Z", - end: "2025-06-01T10:00:00Z", - timeZone: "America/New_York", - extendedProperties: { sb_item: "item-1" }, -}; - -describe("FakeCalendarClient", () => { - let client: FakeCalendarClient; - - beforeEach(() => { - client = new FakeCalendarClient({ seed: 100 }); - }); - - describe("listCalendars", () => { - it("returns default calendars (primary + work)", async () => { - const cals = await client.listCalendars(); - expect(cals).toHaveLength(2); - expect(cals[0].id).toBe("primary"); - expect(cals[0].primary).toBe(true); - expect(cals[1].id).toBe("work"); - }); - }); - - describe("event lifecycle: create → update → delete", () => { - it("creates, updates, and deletes an event", async () => { - // Create - const created = await client.createEvent("primary", testPayload); - expect(created.id).toBe("fake_event_100"); - expect(created.summary).toBe("Test Event"); - - // Update - const updated = await client.updateEvent("primary", created.id, { summary: "Updated" }); - expect(updated.id).toBe(created.id); - expect(updated.summary).toBe("Updated"); - - // Delete - const result = await client.deleteEvent("primary", created.id); - expect(result.ok).toBe(true); - expect(result.notFound).toBeUndefined(); - - // Verify gone - expect(client.getEvents()).toHaveLength(0); - }); - }); - - describe("deleteEvent — missing event", () => { - it("returns ok=true with notFound=true for nonexistent event", async () => { - const result = await client.deleteEvent("primary", "nonexistent"); - expect(result.ok).toBe(true); - expect(result.notFound).toBe(true); - }); - }); - - describe("updateEvent — missing event", () => { - it("throws FakeApiError(404) for nonexistent event", async () => { - await expect( - client.updateEvent("primary", "nonexistent", { summary: "X" }), - ).rejects.toThrow(FakeApiError); - try { - await client.updateEvent("primary", "nonexistent", { summary: "X" }); - } catch (err) { - expect((err as FakeApiError).status).toBe(404); - } - }); - }); - - describe("upsertEvent", () => { - it("creates new event when no existing event", async () => { - const result = await client.upsertEvent("primary", "sb_item=item-1", testPayload); - expect(result.action).toBe("CREATED"); - expect(result.eventId).toBeTruthy(); - }); - - it("updates existing event by existingEventId", async () => { - const created = await client.createEvent("primary", testPayload); - const modified = { ...testPayload, summary: "Updated" }; - const result = await client.upsertEvent("primary", "sb_item=item-1", modified, { - existingEventId: created.id, - }); - expect(result.action).toBe("UPDATED"); - expect(result.eventId).toBe(created.id); - }); - - it("skips when hash is unchanged", async () => { - const created = await client.createEvent("primary", testPayload); - const hash = computeEventHash(testPayload); - const result = await client.upsertEvent("primary", "sb_item=item-1", testPayload, { - existingEventId: created.id, - lastHash: hash, - newHash: hash, - }); - expect(result.action).toBe("UNCHANGED"); - }); - - it("reconciles by extended property when no existingEventId", async () => { - await client.createEvent("primary", testPayload); - const modified = { ...testPayload, summary: "Reconciled" }; - const result = await client.upsertEvent("primary", "sb_item=item-1", modified); - expect(result.action).toBe("UPDATED"); - }); - - it("recreates when existingEventId was externally deleted", async () => { - const created = await client.createEvent("primary", testPayload); - client.simulateManualDelete(created.id); - const result = await client.upsertEvent("primary", "sb_item=item-1", testPayload, { - existingEventId: created.id, - }); - expect(result.action).toBe("CREATED"); - }); - }); - - describe("freeBusy", () => { - it("returns busy blocks within time range", async () => { - client.setBusy([ - { calendarId: "primary", start: "2025-06-01T10:00:00Z", end: "2025-06-01T11:00:00Z" }, - { calendarId: "primary", start: "2025-06-02T10:00:00Z", end: "2025-06-02T11:00:00Z" }, - { calendarId: "work", start: "2025-06-01T12:00:00Z", end: "2025-06-01T13:00:00Z" }, - ]); - - const result = await client.freeBusy({ - timeMin: "2025-06-01T00:00:00Z", - timeMax: "2025-06-01T23:59:59Z", - calendarIds: ["primary"], - }); - - expect(result).toHaveLength(1); - expect(result[0].calendarId).toBe("primary"); - }); - }); - - describe("listEvents", () => { - it("filters by calendarId", async () => { - await client.createEvent("primary", testPayload); - const results = await client.listEvents({ calendarId: "work" }); - expect(results).toHaveLength(0); - - const results2 = await client.listEvents({ calendarId: "primary" }); - expect(results2).toHaveLength(1); - }); - - it("filters by privateExtendedProperty", async () => { - await client.createEvent("primary", testPayload); - await client.createEvent("primary", { ...testPayload, extendedProperties: { sb_item: "item-2" } }); - - const results = await client.listEvents({ - calendarId: "primary", - privateExtendedProperty: "sb_item=item-1", - }); - expect(results).toHaveLength(1); - }); - }); - - describe("healthCheck", () => { - it("returns ok by default", async () => { - const result = await client.healthCheck(); - expect(result.ok).toBe(true); - }); - - it("returns failure when error injected", async () => { - client.simulateErrors.push({ - method: "healthCheck", - error: new FakeReconnectError("invalid_grant"), - }); - await expect(client.healthCheck()).rejects.toThrow("invalid_grant"); - }); - }); - - describe("error injection", () => { - it("simulates 429 rate limit then success (once=true)", async () => { - client.simulateErrors.push({ - method: "createEvent", - error: new FakeApiError("Rate limit", 429), - once: true, - }); - - // First call throws - await expect(client.createEvent("primary", testPayload)).rejects.toThrow("Rate limit"); - - // Second call succeeds (error was once) - const event = await client.createEvent("primary", testPayload); - expect(event.id).toBeTruthy(); - }); - - it("simulates invalid_grant reconnect error", async () => { - client.simulateErrors.push({ - method: "listCalendars", - error: new FakeReconnectError("invalid_grant"), - }); - - await expect(client.listCalendars()).rejects.toThrow("invalid_grant"); - // Error persists (once not set) - await expect(client.listCalendars()).rejects.toThrow("invalid_grant"); - }); - - it("simulates 401 then refresh success scenario", async () => { - client.simulateErrors.push({ - method: "listCalendars", - error: new FakeApiError("Unauthorized", 401), - once: true, - }); - - // First call fails - await expect(client.listCalendars()).rejects.toThrow("Unauthorized"); - - // After "refresh" (simulated by once=true removal), next call works - const cals = await client.listCalendars(); - expect(cals.length).toBeGreaterThan(0); - }); - }); - - describe("call log", () => { - it("tracks all method calls", async () => { - await client.listCalendars(); - await client.createEvent("primary", testPayload); - await client.healthCheck(); - - expect(client.callLog).toHaveLength(3); - expect(client.callLog[0].method).toBe("listCalendars"); - expect(client.callLog[1].method).toBe("createEvent"); - expect(client.callLog[2].method).toBe("healthCheck"); - }); - - it("clearCallLog resets the log", async () => { - await client.listCalendars(); - expect(client.callLog).toHaveLength(1); - client.clearCallLog(); - expect(client.callLog).toHaveLength(0); - }); - }); - - describe("deterministic event IDs", () => { - it("generates predictable IDs from seed", async () => { - const a = await client.createEvent("primary", testPayload); - const b = await client.createEvent("primary", testPayload); - expect(a.id).toBe("fake_event_100"); - expect(b.id).toBe("fake_event_101"); - }); - }); - - describe("reset", () => { - it("clears all state", async () => { - await client.createEvent("primary", testPayload); - client.simulateErrors.push({ method: "test", error: new Error("x") }); - client.reset(); - expect(client.getEvents()).toHaveLength(0); - expect(client.callLog).toHaveLength(0); - expect(client.simulateErrors).toHaveLength(0); - }); - }); -}); diff --git a/src/__tests__/feedback-polling.test.ts b/src/__tests__/feedback-polling.test.ts deleted file mode 100644 index 6cc03f9a..00000000 --- a/src/__tests__/feedback-polling.test.ts +++ /dev/null @@ -1,106 +0,0 @@ -/** - * Unit tests for the client-side feedback poll loop (pollFeedback). - * - * The live-audit bug: an empty/failed feedback generation left the review - * panel spinning forever. The contract under test: PENDING is the ONLY - * non-terminal status — any other result (OK with content, OK + no_sources, - * UNAVAILABLE) resolves the poll immediately, the poll budget yields null - * instead of spinning, and cancellation stops the loop without a result. - */ -import { describe, it, expect, vi, beforeEach } from "vitest"; -import { pollFeedback } from "@/app/s/[sessionId]/feedback-poll"; - -const fetchMock = vi.fn(); -vi.stubGlobal("fetch", fetchMock); - -function jsonResponse(body: unknown, ok = true) { - return { ok, json: async () => body }; -} - -const notCancelled = () => false; - -describe("pollFeedback terminal semantics", () => { - beforeEach(() => { - fetchMock.mockReset(); - }); - - it("resolves on the first non-PENDING result (single fetch)", async () => { - const payload = { status: "OK", excerpts: [], explanation: "because osmosis" }; - fetchMock.mockResolvedValue(jsonResponse(payload)); - - const result = await pollFeedback("attempt-1", notCancelled, 5, 1); - - expect(result).toEqual(payload); - expect(fetchMock).toHaveBeenCalledTimes(1); - }); - - it("treats the explicit no-sources state as terminal — no further polling", async () => { - const payload = { status: "OK", excerpts: [], no_sources: true }; - fetchMock.mockResolvedValue(jsonResponse(payload)); - - const result = await pollFeedback("attempt-1", notCancelled, 5, 1); - - expect(result).toEqual(payload); - expect(fetchMock).toHaveBeenCalledTimes(1); - }); - - it("treats UNAVAILABLE (generation failure) as terminal", async () => { - const payload = { status: "UNAVAILABLE", excerpts: [] }; - fetchMock.mockResolvedValue(jsonResponse(payload)); - - const result = await pollFeedback("attempt-1", notCancelled, 5, 1); - - expect(result).toEqual(payload); - expect(fetchMock).toHaveBeenCalledTimes(1); - }); - - it("keeps polling through PENDING, then returns the terminal result", async () => { - const terminal = { status: "OK", excerpts: [], no_sources: true }; - fetchMock - .mockResolvedValueOnce(jsonResponse({ status: "PENDING", excerpts: [] })) - .mockResolvedValueOnce(jsonResponse({ status: "PENDING", excerpts: [] })) - .mockResolvedValueOnce(jsonResponse(terminal)); - - const result = await pollFeedback("attempt-1", notCancelled, 5, 1); - - expect(result).toEqual(terminal); - expect(fetchMock).toHaveBeenCalledTimes(3); - }); - - it("returns null (not an infinite spin) when the poll budget is exhausted", async () => { - fetchMock.mockResolvedValue(jsonResponse({ status: "PENDING", excerpts: [] })); - - const result = await pollFeedback("attempt-1", notCancelled, 3, 1); - - expect(result).toBeNull(); - expect(fetchMock).toHaveBeenCalledTimes(3); - }); - - it("returns null without fetching when already cancelled", async () => { - const result = await pollFeedback("attempt-1", () => true, 5, 1); - - expect(result).toBeNull(); - expect(fetchMock).not.toHaveBeenCalled(); - }); - - it("stops mid-loop when cancellation flips during a PENDING stretch", async () => { - let cancelled = false; - fetchMock.mockImplementation(async () => { - cancelled = true; // cancel after the first response comes back - return jsonResponse({ status: "PENDING", excerpts: [] }); - }); - - const result = await pollFeedback("attempt-1", () => cancelled, 5, 1); - - expect(result).toBeNull(); - expect(fetchMock).toHaveBeenCalledTimes(1); - }); - - it("propagates a fetch error so the caller can settle into a fallback", async () => { - fetchMock.mockResolvedValue(jsonResponse({ error: "Internal server error" }, false)); - - await expect(pollFeedback("attempt-1", notCancelled, 5, 1)).rejects.toThrow( - "Internal server error", - ); - }); -}); diff --git a/src/__tests__/feedback-route.test.ts b/src/__tests__/feedback-route.test.ts index baa4d712..7265deb3 100644 --- a/src/__tests__/feedback-route.test.ts +++ b/src/__tests__/feedback-route.test.ts @@ -27,7 +27,7 @@ function makeRequest(userId: string | null = "user-1"): NextRequest { }) as unknown as NextRequest; } -const PARAMS = { params: { attemptId: "attempt-1" } }; +const PARAMS = { params: Promise.resolve({ attemptId: "attempt-1" }) }; describe("GET /api/attempts/[attemptId]/feedback", () => { beforeEach(() => { @@ -77,6 +77,6 @@ describe("GET /api/attempts/[attemptId]/feedback", () => { const res = await GET(makeRequest(), PARAMS); expect(res.status).toBe(500); - expect(await res.json()).toEqual({ error: "Internal server error" }); + expect(await res.json()).toEqual({ error: "Feedback didn't load. Retry." }); }); }); diff --git a/src/__tests__/feedback-sources.test.ts b/src/__tests__/feedback-sources.test.ts new file mode 100644 index 00000000..c9fd626b --- /dev/null +++ b/src/__tests__/feedback-sources.test.ts @@ -0,0 +1,196 @@ +/** + * Feedback is written from the student's materials and says where from. + * + * - A correct answer's "why it's correct" note comes with the passages it + * was written from, saved as citations like a wrong answer's explanation. + * - With no passage, there is no note at all (never general knowledge shown + * as sourced), and the result is marked no_sources. + * - The fallback search matches any of the query's words and puts the topic + * title first. + */ +import { describe, it, expect, vi, beforeEach, afterAll } from "vitest" + +interface AttemptRow { + id: string + runId: string + promptIndex: number + promptText: string + userAnswer: string + selfScore: string | null + confidenceRating: number | null + feedbackStatus: string + feedbackJson: Record<string, unknown> | null + run: { + userId: string + session: { courseName: string; examName: string; objectives: { id: string; title: string }[] } + } +} + +const store: { row: AttemptRow | null } = { row: null } + +vi.mock("@/lib/db", () => { + const prisma = { + sessionAttempt: { + findUnique: vi.fn(async ({ where }: { where: { id: string } }) => + store.row && store.row.id === where.id ? store.row : null + ), + updateMany: vi.fn(async ({ data }: { data: Record<string, unknown> }) => { + if (!store.row) return { count: 0 } + Object.assign(store.row, data) + return { count: 1 } + }), + }, + sessionErrorLog: { + findFirst: vi.fn(async () => ({ correctionRule: "Water moves toward higher solute concentration", errorType: "MISCONCEPTION" })), + findMany: vi.fn(async () => []), + }, + sessionRunPrompt: { findUnique: vi.fn(async () => null) }, + objectiveAnchor: { findMany: vi.fn(async () => []) }, + attemptCitation: { upsert: vi.fn(async () => ({})) }, + $transaction: vi.fn(async (ops: Promise<unknown>[]) => Promise.all(ops)), + } + return { prisma } +}) + +const SEARCH_RESULT = { + chunk_id: "chunk-1", + doc_id: "doc-1", + doc_title: "Cell Biology Notes", + page_number: 3, + rank_score: 2.4, + snippet: "<<Osmosis>> is the diffusion of water across a membrane.", +} + +vi.mock("@/lib/search", async (importOriginal) => { + const actual = await importOriginal<typeof import("@/lib/search")>() + return { ...actual, searchChunks: vi.fn(async () => [SEARCH_RESULT]) } +}) + +vi.mock("@/lib/ai/provider-factory", () => ({ createProvider: vi.fn(() => ({})) })) + +vi.mock("@/lib/ai/gateway", () => ({ + runTask: vi.fn(async (_ctx: unknown, spec: { task: string }) => { + if (spec.task === "REINFORCE_CORRECT") { + return { output: { reinforcement: "Water follows solute [1].", deeper_insight: "", concept_connection: null } } + } + if (spec.task === "SOCRATIC_FOLLOWUP") { + return { output: { followup_question: "What if the membrane were impermeable?", purpose: "probe" } } + } + if (spec.task === "GENERATE_FEEDBACK") { + return { + output: { + explanation: "Osmosis moves water [1].", + key_takeaway: "", + concept_connection: null, + mnemonic: null, + pattern_advice: null, + referenced_chunk_ids: [], + }, + } + } + return { output: {} } + }), +})) + +import { generateFeedback } from "@/services/feedback" +import { prisma } from "@/lib/db" +import { searchChunks } from "@/lib/search" +import { runTask } from "@/lib/ai/gateway" + +const searchChunksMock = vi.mocked(searchChunks) +const runTaskMock = vi.mocked(runTask) +const upsertMock = vi.mocked(prisma.attemptCitation.upsert) + +function makeAttempt(overrides: Partial<AttemptRow> = {}): AttemptRow { + return { + id: "attempt-1", + runId: "run-1", + promptIndex: 0, + promptText: "From memory: explain Osmosis in 3 to 5 bullets.", + userAnswer: "Water moves across a membrane", + selfScore: "CORRECT", + confidenceRating: 5, + feedbackStatus: "NONE", + feedbackJson: null, + run: { + userId: "user-1", + session: { courseName: "Biology", examName: "Midterm 1", objectives: [{ id: "obj-1", title: "Cell transport" }] }, + }, + ...overrides, + } +} + +const ORIGINAL_AI_PROVIDER = process.env.AI_PROVIDER + +describe("feedback sources", () => { + beforeEach(() => { + vi.clearAllMocks() + store.row = makeAttempt() + process.env.AI_PROVIDER = "openai" + searchChunksMock.mockImplementation(async () => [SEARCH_RESULT]) + }) + + afterAll(() => { + if (ORIGINAL_AI_PROVIDER === undefined) delete process.env.AI_PROVIDER + else process.env.AI_PROVIDER = ORIGINAL_AI_PROVIDER + }) + + it("returns and saves the passages a correct answer's note was written from", async () => { + const result = await generateFeedback("user-1", "attempt-1") + + expect(result.reinforcement).toBe("Water follows solute [1].") + expect(result.excerpts).toEqual([ + { + chunk_id: "chunk-1", + doc_title: "Cell Biology Notes", + page_number: 3, + snippet: SEARCH_RESULT.snippet, + rank: 1, + }, + ]) + expect(result.no_sources).toBeUndefined() + expect(upsertMock).toHaveBeenCalledTimes(1) + // The note's AI call got the same passages + const reinforce = runTaskMock.mock.calls.find(([, spec]) => (spec as { task: string }).task === "REINFORCE_CORRECT") + expect((reinforce?.[1] as { input: { chunks: { chunk_id: string }[] } }).input.chunks).toEqual([ + expect.objectContaining({ chunk_id: "chunk-1" }), + ]) + }) + + it("writes no correct-answer note when no passage matches, and says there are no sources", async () => { + searchChunksMock.mockResolvedValue([]) + + const result = await generateFeedback("user-1", "attempt-1") + + expect(result.reinforcement).toBeUndefined() + expect(result.deeper_insight).toBeUndefined() + expect(result.excerpts).toEqual([]) + expect(result.no_sources).toBe(true) + expect(runTaskMock.mock.calls.map(([, spec]) => (spec as { task: string }).task)).not.toContain("REINFORCE_CORRECT") + // The follow-up question is still asked; it isn't presented as sourced. + expect(result.socratic_followup).toBe("What if the membrane were impermeable?") + }) + + it("searches any of the words, topic title first, without the question template's wording", async () => { + store.row = makeAttempt({ selfScore: "INCORRECT" }) + + await generateFeedback("user-1", "attempt-1") + + expect(searchChunksMock).toHaveBeenCalled() + for (const [params] of searchChunksMock.mock.calls) { + expect(params.match).toBe("any") + expect(params.q.startsWith("Cell transport Water moves toward higher solute concentration")).toBe(true) + expect(params.q).not.toMatch(/From memory|3 to 5 bullets/) + } + }) + + it("asks the follow-up question from the passages already found, without searching again", async () => { + store.row = makeAttempt({ selfScore: "INCORRECT" }) + + const result = await generateFeedback("user-1", "attempt-1") + + expect(result.explanation).toBe("Osmosis moves water [1].") + // One scoped and one course-wide search, nothing more + expect(searchChunksMock).toHaveBeenCalledTimes(2) + }) +}) diff --git a/src/__tests__/flashcard-decks.test.ts b/src/__tests__/flashcard-decks.test.ts new file mode 100644 index 00000000..56efda7c --- /dev/null +++ b/src/__tests__/flashcard-decks.test.ts @@ -0,0 +1,45 @@ +/** + * Deck titles, kinds, and cleaning AI-generated cards. + */ +import { describe, it, expect, vi } from "vitest"; + +vi.mock("@/lib/db", () => ({ prisma: {} })); + +import { cleanGeneratedCards, deckKind, displayDeckTitle } from "@/services/flashcards"; + +describe("deck titles", () => { + it("shows titles from earlier builds without dashes", () => { + expect(displayDeckTitle("Error Repair \u2014 Biology", "Biology")).toBe("Session errors"); + expect(displayDeckTitle("Lecture 4: Stacks \u2014 Flashcards", "CS 2110")).toBe("Lecture 4: Stacks"); + expect(displayDeckTitle("CS 2110 \u2014 Prelim 1 Flashcards", "CS 2110")).toBe("All Prelim 1 materials"); + expect(displayDeckTitle("CS 2110 Flashcards", "CS 2110")).toBe("All CS 2110 materials"); + expect(displayDeckTitle("Layout and specificity", "INFO 1300")).toBe("Layout and specificity"); + }); + + it("tells session-error decks from AI-written ones", () => { + expect(deckKind("Session errors")).toBe("errors"); + expect(deckKind("Error Repair \u2014 Biology")).toBe("errors"); + expect(deckKind("All Prelim 2 materials")).toBe("generated"); + }); +}); + +describe("cleanGeneratedCards", () => { + it("drops malformed and empty cards and trims the rest", () => { + const cards = cleanGeneratedCards([ + { front: " Q1 ", back: " A1 ", tags: ["css", 3] }, + { front: "", back: "A" }, + { front: "Q", back: null }, + "nonsense", + { front: "Q3", back: "A3" }, + ]); + expect(cards).toEqual([ + { front: "Q1", back: "A1", tags: ["css"] }, + { front: "Q3", back: "A3", tags: undefined }, + ]); + }); + + it("returns nothing for output that isn't a list", () => { + expect(cleanGeneratedCards(undefined)).toEqual([]); + expect(cleanGeneratedCards({ front: "Q" })).toEqual([]); + }); +}); diff --git a/src/__tests__/flashcard-generation.test.ts b/src/__tests__/flashcard-generation.test.ts new file mode 100644 index 00000000..a2c814d5 --- /dev/null +++ b/src/__tests__/flashcard-generation.test.ts @@ -0,0 +1,88 @@ +/** + * Generating a deck when the AI's output has no usable card: the parse + * fails (so the gateway doesn't cache the empty list and Retry asks the + * model again), and the student gets the NO_CARDS error. + */ +import { describe, it, expect, vi, beforeEach } from "vitest"; + +vi.mock("@/lib/db", () => ({ + prisma: { + contentChunk: { findMany: vi.fn(async () => [{ text: "Chunk one" }, { text: "Chunk two" }]) }, + contentDocument: { count: vi.fn(async () => 1) }, + flashcardDeck: { findMany: vi.fn(async () => []) }, + $transaction: vi.fn(), + }, +})); + +vi.mock("@/lib/ai/provider-factory", () => ({ createProvider: vi.fn(() => ({})) })); +vi.mock("@/lib/ai/prompt-registry", () => ({ getPrompt: vi.fn(() => ({ version: "test" })) })); + +// The gateway's contract, reduced: parse the provider's output, and only a +// successful parse is returned (and cached). +const providerOutput = vi.fn<() => unknown>(); +const cached: unknown[] = []; +vi.mock("@/lib/ai/gateway", () => ({ + runTask: vi.fn(async (_ctx: unknown, spec: { parseOutput: (raw: unknown) => unknown }) => { + const raw = providerOutput(); + let output: unknown; + try { + output = spec.parseOutput(raw); + } catch (err) { + throw Object.assign(new Error(`Failed to parse AI output: ${String(err)}`), { code: "PARSE_ERROR" }); + } + cached.push(raw); + return { output, meta: {} }; + }), +})); + +import { FlashcardError, generateFlashcardsFromCourse } from "@/services/flashcards"; +import { prisma } from "@/lib/db"; + +beforeEach(() => { + vi.clearAllMocks(); + cached.length = 0; +}); + +describe("generateFlashcardsFromCourse with an empty AI card list", () => { + it("fails the parse, so nothing is cached, and reports NO_CARDS", async () => { + providerOutput.mockReturnValue({ cards: [{ front: "", back: "" }, "nonsense"] }); + + const error = await generateFlashcardsFromCourse("user-1", "CS 2110").catch((err: unknown) => err); + + expect(error).toBeInstanceOf(FlashcardError); + expect((error as FlashcardError).code).toBe("NO_CARDS"); + expect(cached).toEqual([]); + expect(prisma.$transaction).not.toHaveBeenCalled(); + }); + + it("asks the model again on retry", async () => { + providerOutput.mockReturnValueOnce({ cards: [] }); + await expect(generateFlashcardsFromCourse("user-1", "CS 2110")).rejects.toMatchObject({ code: "NO_CARDS" }); + + providerOutput.mockReturnValueOnce({ cards: [{ front: "Q1", back: "A1" }] }); + vi.mocked(prisma.$transaction).mockResolvedValueOnce({ + id: "deck-1", + userId: "user-1", + courseName: "CS 2110", + examName: null, + documentId: null, + title: "All CS 2110 materials", + cardCount: 1, + createdAt: new Date("2026-10-15T12:00:00Z"), + } as never); + + const deck = await generateFlashcardsFromCourse("user-1", "CS 2110"); + + expect(providerOutput).toHaveBeenCalledTimes(2); + expect(deck.card_count).toBe(1); + expect(cached).toHaveLength(1); + }); + + it("passes other gateway failures through unchanged", async () => { + providerOutput.mockReturnValue("not json at all"); + const { runTask } = await import("@/lib/ai/gateway"); + vi.mocked(runTask).mockRejectedValueOnce(Object.assign(new Error("AI provider failed"), { code: "PROVIDER_ERROR" })); + + await expect(generateFlashcardsFromCourse("user-1", "CS 2110")).rejects.toMatchObject({ code: "PROVIDER_ERROR" }); + }); +}); diff --git a/src/__tests__/flashcard-review-route.test.ts b/src/__tests__/flashcard-review-route.test.ts index 9d99e01a..24c79fb6 100644 --- a/src/__tests__/flashcard-review-route.test.ts +++ b/src/__tests__/flashcard-review-route.test.ts @@ -25,20 +25,26 @@ vi.mock("@/services/spaced-repetition", () => ({ isDeckPerfect: vi.fn(), })); -vi.mock("@/services/gamification", () => ({ - awardXp: vi.fn(), -})); +vi.mock("@/services/gamification", async () => { + const { zonedTimeToUtc, dayKey } = await import("@/lib/timezone"); + return { + awardXp: vi.fn(), + resolveTimeZone: vi.fn(async () => "UTC"), + startOfDay: (now: Date, timeZone: string) => zonedTimeToUtc(dayKey(now, timeZone), "00:00", timeZone), + }; +}); import { POST } from "@/app/api/flashcards/[deckId]/review/route"; import { prisma } from "@/lib/db"; import { reviewCard, isDeckPerfect } from "@/services/spaced-repetition"; -import { awardXp } from "@/services/gamification"; +import { awardXp, resolveTimeZone } from "@/services/gamification"; const mockedFindDeck = vi.mocked(prisma.flashcardDeck.findUnique); const mockedFindXpEvent = vi.mocked(prisma.xpEvent.findFirst); const mockedReviewCard = vi.mocked(reviewCard); const mockedIsDeckPerfect = vi.mocked(isDeckPerfect); const mockedAwardXp = vi.mocked(awardXp); +const mockedResolveTimeZone = vi.mocked(resolveTimeZone); const REVIEW_RESULT = { cardId: "card1", @@ -47,6 +53,8 @@ const REVIEW_RESULT = { repetitions: 1, nextDueAt: "2026-07-16T04:00:00.000Z", rating: "GOOD", + status: "review" as const, + previews: { AGAIN: 0, HARD: 1, GOOD: 2, EASY: 3 }, }; function makeRequest( @@ -167,6 +175,65 @@ describe("POST /api/flashcards/[deckId]/review", () => { }); }); + it("counts today in the student's time zone", async () => { + mockDeck("user1", true); + mockedIsDeckPerfect.mockResolvedValue(true); + mockedResolveTimeZone.mockResolvedValueOnce("America/New_York"); + + await callRoute({ card_id: "card1", rating: "GOOD" }); + + expect(mockedIsDeckPerfect).toHaveBeenCalledWith("user1", "deck1", "America/New_York", expect.any(Date)); + // 2026-07-15 starts at 04:00 UTC in New York (EDT) + expect(mockedFindXpEvent).toHaveBeenCalledWith( + expect.objectContaining({ + where: expect.objectContaining({ createdAt: { gte: new Date("2026-07-15T04:00:00.000Z") } }), + }), + ); + }); + + it("looks up the zone once, alongside the deck check, and schedules the card in it", async () => { + let deckChecked = false; + mockedFindDeck.mockImplementation((async () => { + deckChecked = true; + return { userId: "user1", cards: [{ id: "card1" }] }; + }) as never); + mockedResolveTimeZone.mockImplementationOnce(async () => { + // Started before the deck query has answered + expect(deckChecked).toBe(false); + return "America/New_York"; + }); + + await callRoute({ card_id: "card1", rating: "GOOD" }); + + expect(mockedResolveTimeZone).toHaveBeenCalledTimes(1); + const zone = mockedReviewCard.mock.calls[0][3]; + await expect(zone).resolves.toBe("America/New_York"); + expect(mockedIsDeckPerfect).toHaveBeenCalledWith("user1", "deck1", "America/New_York", expect.any(Date)); + }); + + it("answers a missing deck even when the zone lookup fails", async () => { + mockedFindDeck.mockResolvedValue(null as never); + mockedResolveTimeZone.mockRejectedValueOnce(new Error("db down")); + + const res = await callRoute({ card_id: "card1", rating: "GOOD" }); + + expect(res.status).toBe(404); + }); + + it("does not save a rating it can't schedule when the zone lookup fails", async () => { + mockDeck("user1", true); + mockedResolveTimeZone.mockRejectedValueOnce(new Error("db down")); + mockedReviewCard.mockImplementationOnce(async (_u, _c, _r, zone) => { + await zone; + return REVIEW_RESULT; + }); + + const res = await callRoute({ card_id: "card1", rating: "GOOD" }); + + expect(res.status).toBe(500); + expect(mockedAwardXp).not.toHaveBeenCalled(); + }); + it("does not re-award the bonus when it was already granted today", async () => { mockDeck("user1", true); mockedIsDeckPerfect.mockResolvedValue(true); @@ -203,6 +270,25 @@ describe("POST /api/flashcards/[deckId]/review", () => { expect((await callRoute({ card_id: "card1", rating: "GOOD" })).status).toBe(403); }); + it("returns the card's new status and next interval previews", async () => { + mockDeck("user1", true); + + const json = await (await callRoute({ card_id: "card1", rating: "GOOD" })).json(); + + expect(json.status).toBe("review"); + expect(json.previews).toEqual({ AGAIN: 0, HARD: 1, GOOD: 2, EASY: 3 }); + expect(json.nextDueAt).toBe("2026-07-16T04:00:00.000Z"); + }); + + it("answers errors with copy for the student and a code", async () => { + mockedFindDeck.mockResolvedValue(null as never); + + const json = await (await callRoute({ card_id: "card1", rating: "GOOD" })).json(); + + expect(json.code).toBe("DECK_NOT_FOUND"); + expect(json.error).not.toMatch(/not found$/); + }); + it("returns 400 for an invalid body", async () => { const res = await callRoute({ card_id: "card1", rating: "MEDIUM" }); expect(res.status).toBe(400); diff --git a/src/__tests__/flashcard-scheduling.test.ts b/src/__tests__/flashcard-scheduling.test.ts new file mode 100644 index 00000000..bec8b650 --- /dev/null +++ b/src/__tests__/flashcard-scheduling.test.ts @@ -0,0 +1,242 @@ +/** + * Flashcard scheduling: statuses, due-today on the student's clock, interval + * previews, and reviewCard capping intervals with the deck's exam date. + */ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; + +vi.mock("@/lib/db", () => { + const tx = { + flashcard: { findUnique: vi.fn(), update: vi.fn(async () => ({})) }, + cardReview: { create: vi.fn(async () => ({})) }, + }; + return { + prisma: { + flashcard: { findUnique: vi.fn() }, + studyPlan: { findMany: vi.fn(async () => []), findFirst: vi.fn(async () => null) }, + userGameState: { findUnique: vi.fn(async () => ({ timezone: "America/New_York" })) }, + $transaction: vi.fn(async (fn: (t: typeof tx) => Promise<unknown>) => fn(tx)), + _tx: tx, + }, + }; +}); + +import { prisma } from "@/lib/db"; +import { + cardStatus, + computeSM2, + deckStats, + endOfToday, + findUpcomingExam, + intervalPreviews, + isDueToday, + nextDueAfterToday, + reviewCard, +} from "@/services/spaced-repetition"; + +const db = prisma as unknown as { + flashcard: { findUnique: ReturnType<typeof vi.fn> }; + studyPlan: { findMany: ReturnType<typeof vi.fn>; findFirst: ReturnType<typeof vi.fn> }; + userGameState: { findUnique: ReturnType<typeof vi.fn> }; + _tx: { + flashcard: { findUnique: ReturnType<typeof vi.fn>; update: ReturnType<typeof vi.fn> }; + cardReview: { create: ReturnType<typeof vi.fn> }; + }; +}; + +const NOW = new Date("2026-10-15T18:00:00Z"); // 2:00 PM in New York + +beforeEach(() => { + vi.useFakeTimers(); + vi.setSystemTime(NOW); + vi.clearAllMocks(); + db.studyPlan.findMany.mockResolvedValue([]); + db.studyPlan.findFirst.mockResolvedValue(null); + db.userGameState.findUnique.mockResolvedValue({ timezone: "America/New_York" }); +}); + +afterEach(() => { + vi.useRealTimers(); +}); + +describe("cardStatus", () => { + it("names the four statuses", () => { + expect(cardStatus({ repetitions: 0, intervalDays: 0, nextDueAt: null })).toBe("new"); + expect(cardStatus({ repetitions: 0, intervalDays: 0, nextDueAt: NOW })).toBe("learning"); + expect(cardStatus({ repetitions: 2, intervalDays: 6, nextDueAt: NOW })).toBe("review"); + expect(cardStatus({ repetitions: 5, intervalDays: 21, nextDueAt: NOW })).toBe("mastered"); + }); +}); + +describe("computeSM2 with a time zone", () => { + it("brings day intervals due at 4:00 AM on the student's clock", () => { + const result = computeSM2(2.5, 0, 0, "GOOD", null, { timeZone: "America/New_York", now: NOW }); + expect(result.intervalDays).toBe(1); + // Oct 16, 4:00 AM EDT is 08:00 UTC + expect(result.nextDueAt.toISOString()).toBe("2026-10-16T08:00:00.000Z"); + }); + + it("falls back to 4:00 AM UTC without a zone, never the server clock", () => { + const result = computeSM2(2.5, 0, 0, "GOOD", null, { timeZone: null, now: new Date("2026-10-15T21:30:00Z") }); + expect(result.nextDueAt.toISOString()).toBe("2026-10-16T04:00:00.000Z"); + }); + + it("keeps the 10-minute learning step for Again", () => { + const result = computeSM2(2.5, 6, 2, "AGAIN", null, { timeZone: "America/New_York", now: NOW }); + expect(result.nextDueAt.getTime()).toBe(NOW.getTime() + 10 * 60 * 1000); + }); +}); + +describe("intervalPreviews", () => { + it("previews each rating with the exam cap applied", () => { + const card = { easeFactor: 2.5, intervalDays: 6, repetitions: 2 }; + expect(intervalPreviews(card, null, NOW)).toEqual({ AGAIN: 0, HARD: 14, GOOD: 15, EASY: 16 }); + const examInFive = new Date(NOW.getTime() + 5 * 86_400_000); + expect(intervalPreviews(card, examInFive, NOW)).toEqual({ AGAIN: 0, HARD: 2, GOOD: 2, EASY: 2 }); + }); +}); + +describe("due today", () => { + const todayEnds = endOfToday("America/New_York", NOW); + + it("ends today at midnight on the student's clock", () => { + expect(todayEnds.toISOString()).toBe("2026-10-16T04:00:00.000Z"); + }); + + it("counts new cards and cards due before midnight", () => { + expect(isDueToday({ repetitions: 0, intervalDays: 0, nextDueAt: null }, todayEnds)).toBe(true); + expect(isDueToday({ repetitions: 1, intervalDays: 1, nextDueAt: "2026-10-15T08:00:00Z" }, todayEnds)).toBe(true); + expect(isDueToday({ repetitions: 1, intervalDays: 1, nextDueAt: "2026-10-16T08:00:00Z" }, todayEnds)).toBe(false); + }); + + it("totals statuses and due cards, and finds the next review after today", () => { + const cards = [ + { repetitions: 0, intervalDays: 0, nextDueAt: null }, + { repetitions: 0, intervalDays: 0, nextDueAt: new Date("2026-10-15T18:10:00Z") }, + { repetitions: 2, intervalDays: 6, nextDueAt: new Date("2026-10-18T08:00:00Z") }, + { repetitions: 6, intervalDays: 30, nextDueAt: new Date("2026-10-17T08:00:00Z") }, + ]; + expect(deckStats(cards, todayEnds)).toEqual({ + newCount: 1, + learningCount: 1, + reviewCount: 1, + masteredCount: 1, + dueCount: 2, + }); + expect(nextDueAfterToday(cards, todayEnds)).toBe("2026-10-17T08:00:00.000Z"); + }); +}); + +describe("findUpcomingExam", () => { + it("prefers the deck's own exam, else the course's nearest", async () => { + db.studyPlan.findMany.mockResolvedValue([ + { examName: "Prelim 2", examDate: new Date("2026-10-22T00:00:00Z") }, + { examName: "Final", examDate: new Date("2026-12-14T00:00:00Z") }, + ]); + expect((await findUpcomingExam("u1", "INFO 1300", "Final", NOW))?.examName).toBe("Final"); + expect((await findUpcomingExam("u1", "INFO 1300", "Prelim 9", NOW))?.examName).toBe("Prelim 2"); + expect((await findUpcomingExam("u1", "INFO 1300", null, NOW))?.examName).toBe("Prelim 2"); + // Exams today still count: the query starts at today's calendar date + expect(db.studyPlan.findMany.mock.calls[0][0].where.examDate.gte.toISOString()).toBe("2026-10-15T00:00:00.000Z"); + }); + + it("compares exam dates with today on the student's clock, not UTC's", async () => { + plansOn("2026-10-15", "2026-10-16"); + // 7:00 AM on Oct 17 in Shanghai, still Oct 16 in UTC: both exams are over + const morningEast = new Date("2026-10-16T23:00:00Z"); + expect(await findUpcomingExam("u1", "INFO 1300", null, morningEast, "Asia/Shanghai")).toBeNull(); + // 7:00 PM on Oct 16 in New York: the Oct 16 exam is today + expect((await findUpcomingExam("u1", "INFO 1300", null, morningEast, "America/New_York"))?.examDate.toISOString()).toBe( + "2026-10-16T00:00:00.000Z", + ); + // 8:30 PM on Oct 15 in New York, already Oct 16 in UTC: the Oct 15 exam is today + const eveningWest = new Date("2026-10-16T00:30:00Z"); + expect((await findUpcomingExam("u1", "INFO 1300", null, eveningWest, "America/New_York"))?.examDate.toISOString()).toBe( + "2026-10-15T00:00:00.000Z", + ); + }); +}); + +/** Plans for INFO 1300 with exams on these days; findMany applies the examDate filter. */ +function plansOn(...days: string[]) { + const plans = days.map((day, i) => ({ examName: `Prelim ${i + 1}`, examDate: new Date(`${day}T00:00:00Z`) })); + db.studyPlan.findMany.mockImplementation(async ({ where }: { where: { examDate: { gte: Date } } }) => + plans.filter((p) => p.examDate.getTime() >= where.examDate.gte.getTime()), + ); +} + +describe("reviewCard", () => { + function mockCard(state: { easeFactor: number; intervalDays: number; repetitions: number }) { + db.flashcard.findUnique.mockResolvedValue({ + deck: { userId: "u1", courseName: "INFO 1300", examName: "Prelim 2" }, + }); + db._tx.flashcard.findUnique.mockResolvedValue({ id: "c1", ...state, deck: { userId: "u1" } }); + } + + it("caps the interval with the deck's exam date", async () => { + mockCard({ easeFactor: 2.5, intervalDays: 6, repetitions: 2 }); + db.studyPlan.findMany.mockResolvedValue([ + { examName: "Prelim 2", examDate: new Date("2026-10-22T00:00:00Z") }, + ]); + + const result = await reviewCard("u1", "c1", "GOOD"); + + // Without the exam this would be 15 days; 6 days out caps it at 2. + expect(result.intervalDays).toBe(2); + expect(result.status).toBe("review"); + expect(db._tx.flashcard.update.mock.calls[0][0].data.intervalDays).toBe(2); + // Due at 4:00 AM New York time, two days on + expect(result.nextDueAt).toBe("2026-10-17T08:00:00.000Z"); + expect(result.previews.GOOD).toBeLessThanOrEqual(2); + }); + + it("schedules normally when the course has no upcoming exam", async () => { + mockCard({ easeFactor: 2.5, intervalDays: 6, repetitions: 2 }); + + const result = await reviewCard("u1", "c1", "GOOD"); + + expect(result.intervalDays).toBe(15); + }); + + it("uses the newest plan's zone when Settings has none, like streaks and Study", async () => { + mockCard({ easeFactor: 2.5, intervalDays: 0, repetitions: 0 }); + db.userGameState.findUnique.mockResolvedValue({ timezone: null }); + db.studyPlan.findFirst.mockResolvedValue({ timezone: "America/New_York" }); + vi.setSystemTime(new Date("2026-10-15T21:30:00Z")); // 5:30 PM in New York + + const result = await reviewCard("u1", "c1", "GOOD"); + + // Tomorrow at 4:00 AM New York time, so it isn't due again this evening + expect(result.nextDueAt).toBe("2026-10-16T08:00:00.000Z"); + const eveningEnds = endOfToday("America/New_York", new Date("2026-10-16T00:30:00Z")); + expect(isDueToday({ repetitions: 1, intervalDays: 1, nextDueAt: result.nextDueAt }, eveningEnds)).toBe(false); + }); + + it("takes a zone the caller already looked up", async () => { + mockCard({ easeFactor: 2.5, intervalDays: 0, repetitions: 0 }); + + const result = await reviewCard("u1", "c1", "GOOD", Promise.resolve("Asia/Tokyo")); + + // It's 3:00 AM on Oct 16 in Tokyo; one day on is Oct 17 at 4:00 AM JST + expect(result.nextDueAt).toBe("2026-10-16T19:00:00.000Z"); + expect(db.userGameState.findUnique).not.toHaveBeenCalled(); + }); + + it("stops capping intervals once the exam is over on the student's clock", async () => { + mockCard({ easeFactor: 2.5, intervalDays: 6, repetitions: 2 }); + plansOn("2026-10-16"); + // 7:00 AM on Oct 17 in Shanghai: yesterday's exam would cap this to 1 day if UTC's date (Oct 16) were used + vi.setSystemTime(new Date("2026-10-16T23:00:00Z")); + + const result = await reviewCard("u1", "c1", "GOOD", "Asia/Shanghai"); + + expect(result.intervalDays).toBe(15); + }); + + it("refuses another user's card", async () => { + db.flashcard.findUnique.mockResolvedValue({ + deck: { userId: "someone-else", courseName: "INFO 1300", examName: null }, + }); + await expect(reviewCard("u1", "c1", "GOOD")).rejects.toThrow("Forbidden"); + expect(db._tx.flashcard.update).not.toHaveBeenCalled(); + }); +}); diff --git a/src/__tests__/followups.test.ts b/src/__tests__/followups.test.ts index 55f3c2fa..fb13e125 100644 --- a/src/__tests__/followups.test.ts +++ b/src/__tests__/followups.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from "vitest"; -import { computeFollowupSchedule } from "@/services/followups"; +import { activePlan, computeFollowupSchedule } from "@/services/followups"; /** * Unit tests for the pure follow-up scheduling core: deterministic mapping @@ -16,6 +16,7 @@ const AVAILABILITY = Array.from({ length: 7 }, () => ({ // 2026-07-16 15:00:00 UTC = 11:00 in America/New_York (EDT) const ENDED_AT = new Date("2026-07-16T15:00:00Z"); +/** The results are read the moment the run ends, unless a test says when. */ function baseInput(overrides: Partial<Parameters<typeof computeFollowupSchedule>[0]> = {}) { return { accuracy: 0.75, @@ -24,6 +25,7 @@ function baseInput(overrides: Partial<Parameters<typeof computeFollowupSchedule> examDate: "2026-08-15", planStartDate: "2026-07-16", availability: AVAILABILITY, + now: overrides.endedAt ?? ENDED_AT, ...overrides, }; } @@ -133,11 +135,83 @@ describe("computeFollowupSchedule", () => { expect(planned[0].start_time.toISOString()).toBe("2026-03-08T13:00:00.000Z"); }); - it("falls back to server-local wall time for an invalid timezone", () => { + describe("when the results are opened later", () => { + // Accuracy 0.6: follow-ups 1 and 2 days after the run, Jul 17 and Jul 18 + const late = (now: string, overrides: Partial<Parameters<typeof computeFollowupSchedule>[0]> = {}) => + computeFollowupSchedule(baseInput({ accuracy: 0.6, now: new Date(now), ...overrides })); + + it("skips days that are over instead of adding sessions that are already missed", () => { + // Two days after the run: Jul 18, 8:00 AM in New York + const { planned, skipped } = late("2026-07-18T12:00:00Z"); + expect(skipped).toEqual([{ date: "2026-07-17", days_from_now: 1, reason: "past" }]); + expect(planned.map((p) => p.date)).toEqual(["2026-07-18"]); + // Today's window hasn't opened yet, so the session keeps its 9:00 AM start + expect(planned[0].start_time.toISOString()).toBe("2026-07-18T13:00:00.000Z"); + }); + + it("adds nothing once every day has passed", () => { + const { planned, skipped } = late("2026-07-20T12:00:00Z"); + expect(planned).toEqual([]); + expect(skipped.map((s) => [s.date, s.reason])).toEqual([ + ["2026-07-17", "past"], + ["2026-07-18", "past"], + ]); + }); + + it("starts a follow-up today at the next quarter hour once the window is under way", () => { + // Jul 18, 2:07 PM in New York + const { planned } = late("2026-07-18T18:07:33Z"); + expect(planned.map((p) => p.date)).toEqual(["2026-07-18"]); + expect(planned[0].start_time.toISOString()).toBe("2026-07-18T18:15:00.000Z"); + expect(planned[0].end_time.toISOString()).toBe("2026-07-18T18:45:00.000Z"); + }); + + it("skips today when the session no longer fits before the window closes", () => { + // Jul 18, 4:40 PM in New York: 4:45 to 5:15 runs past the 5:00 PM close + const { planned, skipped } = late("2026-07-18T20:40:00Z"); + expect(planned).toEqual([]); + expect(skipped.map((s) => [s.date, s.reason])).toEqual([ + ["2026-07-17", "past"], + ["2026-07-18", "past"], + ]); + }); + + it("still reports a day after the exam as past_exam", () => { + const { skipped } = late("2026-07-18T12:00:00Z", { examDate: "2026-07-17" }); + expect(skipped.map((s) => [s.date, s.reason])).toEqual([ + ["2026-07-17", "past"], + ["2026-07-18", "past_exam"], + ]); + }); + }); + + it("falls back to UTC wall time for an invalid timezone", () => { const { planned } = computeFollowupSchedule(baseInput({ timezone: "Not/AZone" })); expect(planned).toHaveLength(2); const d = planned[0].start_time; - expect(d.getHours()).toBe(9); - expect(d.getMinutes()).toBe(0); + expect(d.getUTCHours()).toBe(9); + expect(d.getUTCMinutes()).toBe(0); + }); +}); + +describe("activePlan", () => { + const plan = (id: string, examDate: string, timezone = "America/New_York") => ({ + id, + examDate: new Date(`${examDate}T00:00:00.000Z`), + timezone, + }); + // Thu 2026-10-15, 4:00 PM in New York (already Oct 15 evening in UTC) + const now = new Date("2026-10-15T20:00:00Z"); + + it("keeps an exam that is today on the plan's calendar", () => { + expect(activePlan([plan("today", "2026-10-15"), plan("later", "2026-10-22")], now)?.id).toBe("today"); + }); + + it("skips exams that are over in the plan's zone", () => { + expect(activePlan([plan("yesterday", "2026-10-14"), plan("later", "2026-10-22")], now)?.id).toBe("later"); + // 11 PM in New York is already the 16th in Tokyo + const late = new Date("2026-10-16T03:00:00Z"); + expect(activePlan([plan("tokyo", "2026-10-15", "Asia/Tokyo")], late)).toBeUndefined(); + expect(activePlan([plan("ny", "2026-10-15")], late)?.id).toBe("ny"); }); }); diff --git a/src/__tests__/format.test.ts b/src/__tests__/format.test.ts new file mode 100644 index 00000000..cdb61d83 --- /dev/null +++ b/src/__tests__/format.test.ts @@ -0,0 +1,153 @@ +import { describe, expect, it } from "vitest"; +import { + calendarDay, + daysUntil, + formatCountdown, + formatDate, + formatDateFull, + formatDateShort, + formatDateTime, + formatDateWeekday, + formatDayHeading, + formatDuration, + formatList, + formatNumber, + formatPercent, + formatRelativeDay, + formatTime, + formatTimeRange, + plural, +} from "@/lib/format"; + +const NY = { timeZone: "America/New_York" }; +// Wednesday, Oct 14 2026, 2:00 PM in New York (18:00 UTC) +const WED_2PM = new Date("2026-10-14T18:00:00Z"); + +describe("times", () => { + it("formats a time without a leading zero", () => { + expect(formatTime(WED_2PM, NY)).toMatch(/^2:00\sPM$/); + expect(formatTime(new Date("2026-10-14T13:05:00Z"), NY)).toMatch(/^9:05\sAM$/); + }); + + it("formats a range with one meridiem", () => { + const end = new Date("2026-10-14T18:30:00Z"); + expect(formatTimeRange(WED_2PM, end, NY)).toMatch(/^2:00\s*\u2013\s*2:30\sPM$/); + }); + + it("writes the same spaces on every runtime", () => { + const end = new Date("2026-10-14T18:30:00Z"); + expect(formatTimeRange(WED_2PM, end, NY)).toBe("2:00\u2009\u2013\u20092:30\u00a0PM"); + expect(formatTime(WED_2PM, NY)).toBe("2:00\u00a0PM"); + }); + + it("keeps both meridiems when the range crosses noon", () => { + const start = new Date("2026-10-14T15:30:00Z"); + expect(formatTimeRange(start, WED_2PM, NY)).toMatch(/^11:30\sAM\s*\u2013\s*2:00\sPM$/); + }); +}); + +describe("dates", () => { + it("formats the VOICE date styles", () => { + expect(formatDateShort(WED_2PM, NY)).toBe("Oct 14"); + expect(formatDateWeekday(WED_2PM, NY)).toBe("Wed, Oct 14"); + expect(formatDayHeading(WED_2PM, NY)).toBe("Wednesday, October 14"); + expect(formatDateFull(WED_2PM, NY)).toBe("Oct 14, 2026"); + expect(formatDateTime(WED_2PM, NY)).toMatch(/^Wed, Oct 14 at 2:00\sPM$/); + }); + + it("adds the year only for other years", () => { + const now = new Date("2026-12-01T12:00:00Z"); + expect(formatDate(WED_2PM, { ...NY, now })).toBe("Oct 14"); + expect(formatDate(new Date("2025-03-02T12:00:00Z"), { ...NY, now })).toBe("Mar 2, 2025"); + }); + + it("uses the time zone to pick the calendar day", () => { + // 02:00 UTC on Oct 15 is still Oct 14 in New York + const lateEvening = new Date("2026-10-15T02:00:00Z"); + expect(calendarDay(lateEvening, "America/New_York")).toEqual({ year: 2026, month: 10, day: 14 }); + expect(calendarDay(lateEvening, "UTC")).toEqual({ year: 2026, month: 10, day: 15 }); + }); + + it("accepts ISO strings and timestamps", () => { + expect(formatDateShort("2026-10-14T18:00:00Z", NY)).toBe("Oct 14"); + expect(formatDateShort(WED_2PM.getTime(), NY)).toBe("Oct 14"); + }); +}); + +describe("relative days", () => { + const now = new Date("2026-10-14T16:00:00Z"); // noon in New York + + it("counts calendar days, not 24-hour blocks", () => { + // 11:30 PM tonight in New York is still today + expect(daysUntil(new Date("2026-10-15T03:30:00Z"), { ...NY, now })).toBe(0); + // 12:30 AM tomorrow is one day away even though it is 12.5 hours off + expect(daysUntil(new Date("2026-10-15T04:30:00Z"), { ...NY, now })).toBe(1); + }); + + it("crosses a daylight saving change cleanly", () => { + const beforeChange = new Date("2026-10-31T16:00:00Z"); + const afterChange = new Date("2026-11-02T17:00:00Z"); + expect(daysUntil(afterChange, { ...NY, now: beforeChange })).toBe(2); + }); + + it("reads today, tomorrow, yesterday and counts", () => { + expect(formatRelativeDay(now, { ...NY, now })).toBe("today"); + expect(formatRelativeDay(new Date("2026-10-15T16:00:00Z"), { ...NY, now })).toBe("tomorrow"); + expect(formatRelativeDay(new Date("2026-10-13T16:00:00Z"), { ...NY, now })).toBe("yesterday"); + expect(formatRelativeDay(new Date("2026-10-21T16:00:00Z"), { ...NY, now })).toBe("in 7 days"); + expect(formatRelativeDay(new Date("2026-10-11T16:00:00Z"), { ...NY, now })).toBe("3 days ago"); + }); +}); + +describe("countdowns", () => { + const now = new Date("2026-10-14T16:00:00Z"); + + it("writes each of the four messages", () => { + expect(formatCountdown("Prelim 1", now, { ...NY, now })).toBe("Prelim 1 is today"); + expect(formatCountdown("Prelim 1", "2026-10-15T16:00:00Z", { ...NY, now })).toBe("Prelim 1 is tomorrow"); + expect(formatCountdown("Prelim 1", "2026-10-23T16:00:00Z", { ...NY, now })).toBe("Prelim 1 is in 9 days"); + expect(formatCountdown("Prelim 1", "2026-10-12T16:00:00Z", { ...NY, now })).toBe("Prelim 1 was 2 days ago"); + expect(formatCountdown("Prelim 1", "2026-10-13T16:00:00Z", { ...NY, now })).toBe("Prelim 1 was 1 day ago"); + }); +}); + +describe("numbers", () => { + it("formats counts, percentages and durations", () => { + expect(formatNumber(1234)).toBe("1,234"); + expect(formatPercent(0.834)).toBe("83%"); + expect(formatPercent(1)).toBe("100%"); + expect(formatDuration(25)).toBe("25 min"); + expect(formatDuration(119)).toBe("119 min"); + expect(formatDuration(150)).toBe("2.5 hr"); + expect(formatDuration(120)).toBe("2 hr"); + expect(formatDuration(0.4)).toBe("Under 1 min"); + }); +}); + +describe("plural", () => { + const sessions = { zero: "No sessions today", one: "# session today", other: "# sessions today" }; + + it("picks one whole message per count", () => { + expect(plural(0, sessions)).toBe("No sessions today"); + expect(plural(1, sessions)).toBe("1 session today"); + expect(plural(2, sessions)).toBe("2 sessions today"); + expect(plural(1500, sessions)).toBe("1,500 sessions today"); + }); + + it("falls back to other for zero when no zero form is given", () => { + expect(plural(0, { one: "# card", other: "# cards" })).toBe("0 cards"); + }); + + it("never writes '1 sessions'", () => { + expect(plural(1, { one: "# session", other: "# sessions" })).not.toMatch(/1 sessions/); + }); +}); + +describe("lists", () => { + it("uses the serial comma", () => { + expect(formatList(["Recursion", "Stacks", "Big-O"])).toBe("Recursion, Stacks, and Big-O"); + expect(formatList(["Recursion", "Stacks"])).toBe("Recursion and Stacks"); + expect(formatList(["Recursion"])).toBe("Recursion"); + expect(formatList(["Sure", "Unsure"], "disjunction")).toBe("Sure or Unsure"); + }); +}); diff --git a/src/__tests__/gamification.test.ts b/src/__tests__/gamification.test.ts index b93df372..0604347b 100644 --- a/src/__tests__/gamification.test.ts +++ b/src/__tests__/gamification.test.ts @@ -11,6 +11,16 @@ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; // but local midnight serializes to the PREVIOUS UTC day. process.env.TZ = "Asia/Tokyo"; +// next/server's after() throws outside a request scope, as in scripts and +// tests. A test can switch `inRequest` on to collect the scheduled work. +const nextServer = vi.hoisted(() => ({ inRequest: false, tasks: [] as Array<() => Promise<void>> })); +vi.mock("next/server", () => ({ + after: (task: () => Promise<void>) => { + if (!nextServer.inRequest) throw new Error("`after` was called outside a request scope."); + nextServer.tasks.push(task); + }, +})); + interface XpEventRow { id: string; userId: string; @@ -34,6 +44,8 @@ type Where = Record<string, unknown>; vi.mock("@/lib/db", () => { const xpEvents: XpEventRow[] = []; const gameStates = new Map<string, GameStateRow>(); + const planZones: string[] = []; + const achievements: string[] = []; let nextId = 1; // Prisma's scalar `not:` filter is NULL-excluding — reproduce that here so @@ -73,11 +85,19 @@ vi.mock("@/lib/db", () => { function matchesXpWhere(row: XpEventRow, where: Where): boolean { if (where.userId !== undefined && row.userId !== where.userId) return false; - if (where.action !== undefined && row.action !== where.action) return false; + if (where.action !== undefined) { + const cond = where.action as string | { in?: string[]; notIn?: string[] }; + if (typeof cond === "string") { + if (row.action !== cond) return false; + } else if (cond.notIn?.includes(row.action) || (cond.in && !cond.in.includes(row.action))) { + return false; + } + } if (where.sourceId !== undefined && row.sourceId !== where.sourceId) return false; if (where.createdAt !== undefined) { - const cond = where.createdAt as { gte?: Date }; + const cond = where.createdAt as { gte?: Date; lt?: Date }; if (cond.gte !== undefined && row.createdAt < cond.gte) return false; + if (cond.lt !== undefined && row.createdAt >= cond.lt) return false; } return true; } @@ -157,24 +177,46 @@ vi.mock("@/lib/db", () => { studyPlanItem: { findMany: vi.fn(async () => []), }, + studyPlan: { + // Newest plan first, as the service asks for it. + findFirst: vi.fn(async () => (planZones.length > 0 ? { timezone: planZones[0] } : null)), + }, achievement: { - findMany: vi.fn(async () => []), - createMany: vi.fn(async ({ data }: { data: unknown[] }) => ({ count: data.length })), + findMany: vi.fn(async () => achievements.map((badgeType) => ({ badgeType, earnedAt: new Date() }))), + createMany: vi.fn(async ({ data }: { data: { badgeType: string }[] }) => { + for (const row of data) if (!achievements.includes(row.badgeType)) achievements.push(row.badgeType); + return { count: data.length }; + }), }, cardReview: { count: vi.fn(async () => 0), }, - _test: { xpEvents, gameStates }, + _test: { xpEvents, gameStates, planZones, achievements }, }, }; }); -import { consumeStreakFreeze, computeStreak, getGameState } from "@/services/gamification"; +import { + awardXp, + bucketActivity, + consumeStreakFreeze, + computeStreak, + getGameState, + getStreak, + resolveTimeZone, + streakFromDays, + syncProgress, +} from "@/services/gamification"; import { prisma } from "@/lib/db"; const testPrisma = ( prisma as unknown as { - _test: { xpEvents: XpEventRow[]; gameStates: Map<string, GameStateRow> }; + _test: { + xpEvents: XpEventRow[]; + gameStates: Map<string, GameStateRow>; + planZones: string[]; + achievements: string[]; + }; } )._test; @@ -209,6 +251,8 @@ beforeEach(() => { vi.setSystemTime(NOW); testPrisma.xpEvents.length = 0; testPrisma.gameStates.clear(); + testPrisma.planZones.length = 0; + testPrisma.achievements.length = 0; vi.clearAllMocks(); }); @@ -216,6 +260,7 @@ afterEach(() => { vi.useRealTimers(); }); + describe("consumeStreakFreeze", () => { it("consumes a freeze when streakFreezeUsedDate is NULL (never used before)", async () => { setGameState({ streakFreezes: 2, streakFreezeUsedDate: null }); @@ -239,7 +284,7 @@ describe("consumeStreakFreeze", () => { const result = await consumeStreakFreeze("user1"); - expect(result).toEqual({ success: false, freezesRemaining: 2 }); + expect(result).toEqual({ success: false, freezesRemaining: 2, reason: "already_used_today" }); expect(testPrisma.xpEvents).toHaveLength(0); }); @@ -248,10 +293,20 @@ describe("consumeStreakFreeze", () => { const result = await consumeStreakFreeze("user1"); - expect(result).toEqual({ success: false, freezesRemaining: 0 }); + expect(result).toEqual({ success: false, freezesRemaining: 0, reason: "no_freezes" }); expect(testPrisma.xpEvents).toHaveLength(0); }); + it("refuses when the student already studied today, keeping the freeze", async () => { + setGameState({ streakFreezes: 1 }); + addXpEvent({ createdAt: new Date("2026-07-15T08:00:00Z") }); + + const result = await consumeStreakFreeze("user1"); + + expect(result).toEqual({ success: false, freezesRemaining: 1, reason: "already_active" }); + expect(testPrisma.gameStates.get("user1")?.streakFreezes).toBe(1); + }); + it("records the bridged day as a durable zero-XP STREAK_FREEZE_USED event", async () => { setGameState({ streakFreezes: 2, streakFreezeUsedDate: null }); @@ -264,11 +319,31 @@ describe("consumeStreakFreeze", () => { }); }); +describe("streakFromDays", () => { + it("counts back from today when today is active", () => { + expect(streakFromDays(new Set(["2026-07-15", "2026-07-14", "2026-07-13"]), "2026-07-15")).toBe(3); + }); + + it("counts back from yesterday when today has no activity yet", () => { + expect(streakFromDays(new Set(["2026-07-14", "2026-07-13"]), "2026-07-15")).toBe(2); + }); + + it("is 0 when neither today nor yesterday is active", () => { + expect(streakFromDays(new Set(["2026-07-13"]), "2026-07-15")).toBe(0); + }); + + it("walks across month and daylight saving boundaries by calendar day", () => { + // US clocks fall back on 2026-11-01. + const days = new Set(["2026-11-02", "2026-11-01", "2026-10-31", "2026-10-30"]); + expect(streakFromDays(days, "2026-11-02")).toBe(4); + }); +}); + describe("computeStreak", () => { it("counts today's activity even under a positive UTC offset", async () => { // Regression: the walk previously started from LOCAL midnight, which - // serializes to yesterday's UTC key in Tokyo — streak showed 0 right - // after studying. + // serializes to yesterday's UTC key in Tokyo, so the streak showed 0 + // right after studying. addXpEvent({ createdAt: new Date("2026-07-15T09:00:00Z") }); expect(await computeStreak("user1", NO_FREEZE_STATE)).toBe(1); @@ -302,6 +377,30 @@ describe("computeStreak", () => { expect(await computeStreak("user1", NO_FREEZE_STATE)).toBe(0); }); + it("counts streaks longer than 90 days", async () => { + for (let i = 0; i < 120; i++) { + addXpEvent({ createdAt: new Date(NOW.getTime() - i * 86_400_000) }); + } + + expect(await computeStreak("user1", NO_FREEZE_STATE)).toBe(120); + }); + + it("reads only the recent window for a short streak", async () => { + for (let i = 0; i < 5; i++) addXpEvent({ createdAt: new Date(NOW.getTime() - i * 86_400_000) }); + // An older run of study outside the short window doesn't matter here. + for (let i = 60; i < 70; i++) addXpEvent({ createdAt: new Date(NOW.getTime() - i * 86_400_000) }); + + expect(await computeStreak("user1", NO_FREEZE_STATE)).toBe(5); + expect(prisma.xpEvent.findMany).toHaveBeenCalledTimes(1); + }); + + it("reads further back when the streak reaches the edge of the short window", async () => { + for (let i = 0; i < 45; i++) addXpEvent({ createdAt: new Date(NOW.getTime() - i * 86_400_000) }); + + expect(await computeStreak("user1", NO_FREEZE_STATE)).toBe(45); + expect(prisma.xpEvent.findMany).toHaveBeenCalledTimes(2); + }); + it("bridges gaps using durable STREAK_FREEZE_USED events (sourceId = bridged date)", async () => { addXpEvent({ createdAt: new Date("2026-07-15T09:00:00Z") }); addXpEvent({ createdAt: new Date("2026-07-13T09:00:00Z") }); @@ -328,9 +427,6 @@ describe("computeStreak", () => { }); it("preserves days bridged by earlier freezes when a second freeze is consumed", async () => { - // Freeze bridged 2026-07-13; user studied on the 14th; a second freeze - // was consumed on the 15th, overwriting streakFreezeUsedDate. The durable - // event keeps the 13th active. addXpEvent({ createdAt: new Date("2026-07-14T09:00:00Z") }); addXpEvent({ createdAt: new Date("2026-07-12T09:00:00Z") }); addXpEvent({ @@ -348,6 +444,17 @@ describe("computeStreak", () => { expect(streak).toBe(4); }); + it("does not count a day that holds only retired guide or chat XP", async () => { + // Before guides and chat stopped earning XP, they wrote these rows. They + // still count toward XP totals, but a day with nothing else isn't study. + addXpEvent({ createdAt: new Date("2026-07-15T09:00:00Z") }); + addXpEvent({ action: "GUIDE_GENERATED", xpAmount: 5, createdAt: new Date("2026-07-14T09:00:00Z") }); + addXpEvent({ action: "CHAT_QUESTION", xpAmount: 1, createdAt: new Date("2026-07-13T09:00:00Z") }); + addXpEvent({ createdAt: new Date("2026-07-12T09:00:00Z") }); + + expect(await computeStreak("user1", NO_FREEZE_STATE)).toBe(1); + }); + it("does not treat STREAK_FREEZE_AWARD marker events as study activity", async () => { addXpEvent({ createdAt: new Date("2026-07-14T09:00:00Z") }); addXpEvent({ @@ -357,7 +464,6 @@ describe("computeStreak", () => { createdAt: new Date("2026-07-15T09:00:00Z"), }); - // Only yesterday is genuinely active — the award marker must not extend it expect(await computeStreak("user1", NO_FREEZE_STATE)).toBe(1); }); }); @@ -366,9 +472,6 @@ describe("computeStreak with a user timezone", () => { const NY_STATE = { ...NO_FREEZE_STATE, timezone: "America/New_York" }; it("keys a 9pm ET session to the local day 2026-07-15, not the UTC day 2026-07-16", async () => { - // 2026-07-16T01:00:00Z is 9pm on July 15 in New York. At NOW (July 15 - // UTC/ET) the ET user sees today's activity; UTC keys file the same - // event under the 16th — tomorrow — so the streak would read 0. addXpEvent({ createdAt: new Date("2026-07-16T01:00:00Z") }); expect(await computeStreak("user1", NY_STATE)).toBe(1); @@ -378,23 +481,38 @@ describe("computeStreak with a user timezone", () => { it("keeps a two-day local streak unbroken when a late-night session crosses the UTC boundary", async () => { vi.setSystemTime(new Date("2026-07-16T01:30:00Z")); // 9:30pm July 15 ET - addXpEvent({ createdAt: new Date("2026-07-16T01:00:00Z") }); // 9pm Jul 15 ET (UTC day Jul 16) - addXpEvent({ createdAt: new Date("2026-07-14T15:00:00Z") }); // 11am Jul 14 ET (UTC day Jul 14) + addXpEvent({ createdAt: new Date("2026-07-16T01:00:00Z") }); + addXpEvent({ createdAt: new Date("2026-07-14T15:00:00Z") }); - // ET days: Jul 14 + Jul 15 — consecutive expect(await computeStreak("user1", NY_STATE)).toBe(2); - // UTC days: Jul 14 + Jul 16 — broken at Jul 15 expect(await computeStreak("user1", NO_FREEZE_STATE)).toBe(1); }); it("reads the timezone from the game state row when none is passed in", async () => { setGameState({ timezone: "America/New_York" }); - addXpEvent({ createdAt: new Date("2026-07-16T01:00:00Z") }); // 9pm Jul 15 ET + addXpEvent({ createdAt: new Date("2026-07-16T01:00:00Z") }); expect(await computeStreak("user1")).toBe(1); }); }); +describe("getStreak", () => { + it("counts days in the newest plan's zone when Settings has none, like getGameState", async () => { + vi.setSystemTime(new Date("2026-07-16T01:30:00Z")); // 9:30pm July 15 ET + setGameState({ timezone: null }); + testPrisma.planZones.push("America/New_York"); + addXpEvent({ createdAt: new Date("2026-07-16T01:00:00Z") }); // July 15 ET + addXpEvent({ createdAt: new Date("2026-07-14T15:00:00Z") }); // July 14 ET + + expect(await getStreak("user1")).toBe(2); + expect((await getGameState("user1")).streak).toBe(2); + }); + + it("is 0 for a student with no activity", async () => { + expect(await getStreak("user1")).toBe(0); + }); +}); + describe("consumeStreakFreeze with a user timezone", () => { it("stamps the bridged day in the user's local day, not the UTC day", async () => { vi.setSystemTime(new Date("2026-07-16T01:00:00Z")); // 9pm July 15 ET @@ -411,28 +529,88 @@ describe("consumeStreakFreeze with a user timezone", () => { }); it("refuses a second freeze on the same LOCAL day even after the UTC date rolls over", async () => { - vi.setSystemTime(new Date("2026-07-16T01:00:00Z")); // still July 15 in ET + vi.setSystemTime(new Date("2026-07-16T01:00:00Z")); setGameState({ streakFreezes: 2, streakFreezeUsedDate: "2026-07-15", timezone: "America/New_York" }); const result = await consumeStreakFreeze("user1"); - expect(result).toEqual({ success: false, freezesRemaining: 2 }); + expect(result).toEqual({ success: false, freezesRemaining: 2, reason: "already_used_today" }); expect(testPrisma.xpEvents).toHaveLength(0); }); + + it("falls back to the newest plan's zone when Settings has none", async () => { + vi.setSystemTime(new Date("2026-07-16T01:00:00Z")); // still July 15 in New York + setGameState({ streakFreezes: 1, timezone: null }); + testPrisma.planZones.push("America/New_York"); + + await consumeStreakFreeze("user1"); + + expect(testPrisma.gameStates.get("user1")?.streakFreezeUsedDate).toBe("2026-07-15"); + }); }); -describe("streak freeze milestone award (via getGameState)", () => { - function seedSevenDayStreak(): void { +describe("resolveTimeZone", () => { + it("prefers the Settings zone", async () => { + testPrisma.planZones.push("Europe/Paris"); + expect(await resolveTimeZone("user1", "America/Chicago")).toBe("America/Chicago"); + }); + + it("uses the newest plan's zone when Settings has none", async () => { + testPrisma.planZones.push("Europe/Paris"); + expect(await resolveTimeZone("user1", null)).toBe("Europe/Paris"); + }); + + it("ignores an invalid zone and ends at UTC", async () => { + expect(await resolveTimeZone("user1", "Not/AZone")).toBe("UTC"); + }); +}); + +describe("getGameState", () => { + it("counts XP today from the student's midnight, not the server's", async () => { + // The server runs in Tokyo (TZ above). At 9:30pm July 15 in New York, + // Tokyo midnight was 11am ET, so a server-local "today" would drop the + // 8am ET review. + vi.setSystemTime(new Date("2026-07-16T01:30:00Z")); + setGameState({ timezone: "America/New_York" }); + addXpEvent({ createdAt: new Date("2026-07-15T12:00:00Z"), xpAmount: 2 }); // 8am ET Jul 15 + addXpEvent({ createdAt: new Date("2026-07-15T03:00:00Z"), xpAmount: 2 }); // 11pm ET Jul 14 + + const state = await getGameState("user1"); + + expect(state.timeZone).toBe("America/New_York"); + expect(state.xpToday).toBe(2); + expect(state.xpTotal).toBe(4); + expect(state.activeToday).toBe(true); + expect(state.streak).toBe(2); + }); + + it("never writes: no game state row, freeze or achievement is created on read", async () => { for (let i = 0; i < 7; i++) { addXpEvent({ createdAt: new Date(NOW.getTime() - i * 86_400_000) }); } + + const state = await getGameState("user1"); + + expect(state.streak).toBe(7); + expect(state.newAchievements).toEqual([]); + expect(testPrisma.gameStates.size).toBe(0); + expect(testPrisma.achievements).toEqual([]); + expect(testPrisma.xpEvents.filter((e) => e.action === "STREAK_FREEZE_AWARD")).toHaveLength(0); + }); +}); + +describe("syncProgress (the write path)", () => { + function seedDays(count: number): void { + for (let i = 0; i < count; i++) { + addXpEvent({ createdAt: new Date(NOW.getTime() - i * 86_400_000) }); + } } it("awards exactly one freeze per milestone across repeated calls", async () => { - seedSevenDayStreak(); + seedDays(7); setGameState({ streakFreezes: 0 }); - const first = await getGameState("user1"); + const first = await syncProgress("user1"); expect(first.streak).toBe(7); expect(first.streakFreezes).toBe(1); @@ -440,35 +618,224 @@ describe("streak freeze milestone award (via getGameState)", () => { expect(awards()).toHaveLength(1); expect(awards()[0]).toMatchObject({ xpAmount: 0, sourceId: "7" }); - // Opening the dashboard again on the same milestone day must not re-award - const second = await getGameState("user1"); - expect(second.streak).toBe(7); + const second = await syncProgress("user1"); expect(second.streakFreezes).toBe(1); expect(awards()).toHaveLength(1); - - const third = await getGameState("user1"); - expect(third.streakFreezes).toBe(1); - expect(awards()).toHaveLength(1); }); - it("does not award on non-milestone days", async () => { - for (let i = 0; i < 5; i++) { - addXpEvent({ createdAt: new Date(NOW.getTime() - i * 86_400_000) }); + it("awards a freeze again when a later streak reaches 7 days", async () => { + // First streak: June 1 to 7, then a missed day (June 8). + for (let day = 1; day <= 7; day++) { + addXpEvent({ createdAt: new Date(`2026-06-0${day}T09:00:00Z`) }); } + vi.setSystemTime(new Date("2026-06-07T10:00:00Z")); setGameState({ streakFreezes: 0 }); - const state = await getGameState("user1"); - expect(state.streak).toBe(5); - expect(state.streakFreezes).toBe(0); - expect(testPrisma.xpEvents.filter((e) => e.action === "STREAK_FREEZE_AWARD")).toHaveLength(0); + const first = await syncProgress("user1"); + expect(first).toMatchObject({ streak: 7, streakFreezes: 1 }); + + // Second streak: June 9 to 15. The June 7 marker belongs to the old streak. + for (let day = 9; day <= 15; day++) { + addXpEvent({ createdAt: new Date(`2026-06-${String(day).padStart(2, "0")}T09:00:00Z`) }); + } + vi.setSystemTime(new Date("2026-06-15T10:00:00Z")); + + const second = await syncProgress("user1"); + expect(second).toMatchObject({ streak: 7, streakFreezes: 2 }); + expect(testPrisma.xpEvents.filter((e) => e.action === "STREAK_FREEZE_AWARD")).toHaveLength(2); + + // Still one award per milestone within the second streak. + const again = await syncProgress("user1"); + expect(again.streakFreezes).toBe(2); + }); + + it("still finds a milestone marker written earlier in the same streak", async () => { + // Rows written before markers were scoped to a streak keep blocking a repeat award. + seedDays(7); + addXpEvent({ action: "STREAK_FREEZE_AWARD", xpAmount: 0, sourceId: "7", createdAt: new Date(NOW.getTime() - 60 * 60_000) }); + setGameState({ streakFreezes: 1 }); + + const result = await syncProgress("user1"); + expect(result.streakFreezes).toBe(1); + expect(testPrisma.xpEvents.filter((e) => e.action === "STREAK_FREEZE_AWARD")).toHaveLength(1); + }); + + it("does not award a freeze on non-milestone days", async () => { + seedDays(5); + setGameState({ streakFreezes: 0 }); + + const result = await syncProgress("user1"); + expect(result.streak).toBe(5); + expect(result.streakFreezes).toBe(0); }); it("does not award beyond the cap of 3", async () => { - seedSevenDayStreak(); + seedDays(7); setGameState({ streakFreezes: 3 }); - const state = await getGameState("user1"); - expect(state.streakFreezes).toBe(3); + const result = await syncProgress("user1"); + expect(result.streakFreezes).toBe(3); expect(testPrisma.xpEvents.filter((e) => e.action === "STREAK_FREEZE_AWARD")).toHaveLength(0); }); + + it("awards each reached achievement once", async () => { + seedDays(3); + + const first = await syncProgress("user1"); + expect(first.newAchievements).toEqual(["STREAK_3"]); + + const second = await syncProgress("user1"); + expect(second.newAchievements).toEqual([]); + expect(testPrisma.achievements).toEqual(["STREAK_3"]); + }); + + it("awards the perfect-deck achievement from PERFECT_DECK events, not review counts", async () => { + addXpEvent({ action: "PERFECT_DECK", xpAmount: 3, createdAt: NOW }); + + const result = await syncProgress("user1"); + expect(result.newAchievements).toContain("FIRST_PERFECT"); + }); + + it("skips the streak work when the event isn't the first study of the day", async () => { + // Six earlier days plus a review this morning: the 7-day milestone was + // reached by this morning's review, so a second one changes nothing. + for (let i = 1; i < 7; i++) addXpEvent({ createdAt: new Date(NOW.getTime() - i * 86_400_000) }); + addXpEvent({ createdAt: new Date(NOW.getTime() - 60 * 60_000) }); + addXpEvent({ createdAt: NOW }); + setGameState({ streakFreezes: 0 }); + + const result = await syncProgress("user1", { createdAt: NOW }); + expect(result.streak).toBeNull(); + expect(result.streakFreezes).toBe(0); + expect(result.newAchievements).not.toContain("STREAK_7"); + expect(prisma.studyPlanItem.findMany).not.toHaveBeenCalled(); + }); + + it("checks the streak on the first study of the day", async () => { + for (let i = 0; i < 7; i++) addXpEvent({ createdAt: new Date(NOW.getTime() - i * 86_400_000) }); + setGameState({ streakFreezes: 0 }); + + const result = await syncProgress("user1", { createdAt: NOW }); + expect(result.streak).toBe(7); + expect(result.streakFreezes).toBe(1); + expect(result.newAchievements).toContain("STREAK_7"); + }); + + it("still checks the streak when only a freeze came earlier today", async () => { + addXpEvent({ action: "STREAK_FREEZE_USED", xpAmount: 0, sourceId: "2026-07-14", createdAt: new Date(NOW.getTime() - 86_400_000) }); + addXpEvent({ action: "STREAK_FREEZE_USED", xpAmount: 0, sourceId: "2026-07-15", createdAt: new Date(NOW.getTime() - 60 * 60_000) }); + addXpEvent({ createdAt: new Date(NOW.getTime() - 2 * 86_400_000) }); + addXpEvent({ createdAt: NOW }); + + const result = await syncProgress("user1", { createdAt: NOW }); + expect(result.streak).toBe(3); + expect(result.newAchievements).toContain("STREAK_3"); + }); +}); + +describe("awardXp", () => { + it("records the event and awards what it unlocks", async () => { + addXpEvent({ createdAt: new Date(NOW.getTime() - 86_400_000) }); + addXpEvent({ createdAt: new Date(NOW.getTime() - 2 * 86_400_000) }); + + // Outside a Next request there is no response to wait for, so the + // awarding finishes before awardXp returns. + await awardXp("user1", "FLASHCARD_REVIEW", undefined, "card-1"); + + expect(testPrisma.xpEvents.filter((e) => e.sourceId === "card-1")).toHaveLength(1); + expect(testPrisma.achievements).toContain("STREAK_3"); + }); + + it("awards after the response when called inside a request", async () => { + addXpEvent({ createdAt: new Date(NOW.getTime() - 86_400_000) }); + addXpEvent({ createdAt: new Date(NOW.getTime() - 2 * 86_400_000) }); + nextServer.inRequest = true; + nextServer.tasks.length = 0; + try { + const result = await awardXp("user1", "FLASHCARD_REVIEW", undefined, "card-2"); + + // The XP is recorded before the response; the awarding waits for after(). + expect(result.xpAmount).toBe(2); + expect(testPrisma.xpEvents.filter((e) => e.sourceId === "card-2")).toHaveLength(1); + expect(testPrisma.achievements).not.toContain("STREAK_3"); + expect(nextServer.tasks).toHaveLength(1); + + await nextServer.tasks[0](); + expect(testPrisma.achievements).toContain("STREAK_3"); + } finally { + nextServer.inRequest = false; + nextServer.tasks.length = 0; + } + }); + + it("gives no XP for guides or chat, which aren't practice", async () => { + expect(await awardXp("user1", "GUIDE_GENERATED")).toEqual({ id: "", xpAmount: 0 }); + expect(await awardXp("user1", "CHAT_QUESTION")).toEqual({ id: "", xpAmount: 0 }); + expect(testPrisma.xpEvents).toHaveLength(0); + }); + + it("skips zero amounts", async () => { + const result = await awardXp("user1", "STREAK_MILESTONE"); + expect(result).toEqual({ id: "", xpAmount: 0 }); + expect(testPrisma.xpEvents).toHaveLength(0); + }); +}); + +describe("bucketActivity", () => { + const ZONE = "America/New_York"; + + it("files each event under the student's day and counts what it is", () => { + const days = bucketActivity( + [ + { action: "SESSION_COMPLETED", xpAmount: 10, sourceId: "run-1", createdAt: new Date("2026-07-15T01:00:00Z") }, + { action: "FLASHCARD_REVIEW", xpAmount: 2, sourceId: "c1", createdAt: new Date("2026-07-15T02:00:00Z") }, + { action: "FLASHCARD_REVIEW", xpAmount: 2, sourceId: "c2", createdAt: new Date("2026-07-15T14:00:00Z") }, + { action: "STREAK_FREEZE_AWARD", xpAmount: 0, sourceId: "7", createdAt: new Date("2026-07-15T14:00:00Z") }, + ], + [], + ZONE, + ); + + // 9pm and 10pm ET on July 14; 10am ET on July 15 + expect(days.get("2026-07-14")).toMatchObject({ sessions: 1, reviews: 1, xp: 12 }); + expect(days.get("2026-07-15")).toMatchObject({ sessions: 0, reviews: 1, xp: 2 }); + }); + + it("does not count a finished plan item twice when its run has an event", () => { + const days = bucketActivity( + [{ action: "SESSION_COMPLETED", xpAmount: 10, sourceId: "run-1", createdAt: new Date("2026-07-15T15:00:00Z") }], + [ + { completedAt: new Date("2026-07-15T15:00:00Z"), startTime: new Date("2026-07-15T14:30:00Z"), completedRunId: "run-1" }, + { completedAt: new Date("2026-07-15T18:00:00Z"), startTime: new Date("2026-07-15T17:30:00Z"), completedRunId: null }, + ], + ZONE, + ); + + expect(days.get("2026-07-15")?.sessions).toBe(2); + }); + + it("leaves retired guide and chat XP off the heatmap", () => { + const days = bucketActivity( + [ + { action: "GUIDE_GENERATED", xpAmount: 5, sourceId: "g1", createdAt: new Date("2026-07-13T15:00:00Z") }, + { action: "CHAT_QUESTION", xpAmount: 1, sourceId: null, createdAt: new Date("2026-07-14T15:00:00Z") }, + { action: "FLASHCARD_REVIEW", xpAmount: 2, sourceId: "c1", createdAt: new Date("2026-07-14T16:00:00Z") }, + ], + [], + ZONE, + ); + + expect(days.has("2026-07-13")).toBe(false); + expect(days.get("2026-07-14")).toMatchObject({ reviews: 1, xp: 2 }); + }); + + it("marks days a freeze bridged without counting them as study", () => { + const days = bucketActivity( + [{ action: "STREAK_FREEZE_USED", xpAmount: 0, sourceId: "2026-07-13", createdAt: new Date("2026-07-14T02:00:00Z") }], + [], + ZONE, + ); + + expect(days.get("2026-07-13")).toMatchObject({ freezeUsed: true, sessions: 0, reviews: 0, xp: 0 }); + }); }); diff --git a/src/__tests__/gcal-hardening.test.ts b/src/__tests__/gcal-hardening.test.ts index 4d4f91af..2192cbd3 100644 --- a/src/__tests__/gcal-hardening.test.ts +++ b/src/__tests__/gcal-hardening.test.ts @@ -21,13 +21,12 @@ describe("token encryption", () => { it("fails without TOKEN_ENC_KEY in production", async () => { const origEnv = { ...process.env }; delete process.env.TOKEN_ENC_KEY; - delete process.env.GOOGLE_TOKEN_ENC_KEY; vi.stubEnv("NODE_ENV", "production"); // Dynamic import to get fresh module vi.resetModules(); try { - const { encrypt } = await import("@/lib/crypto"); + const { encryptToken: encrypt } = await import("@/lib/crypto/token-vault"); expect(() => encrypt("test")).toThrow("TOKEN_ENC_KEY"); } finally { vi.unstubAllEnvs(); @@ -38,12 +37,11 @@ describe("token encryption", () => { it("accepts TOKEN_ENC_KEY as primary env var", async () => { const origEnv = { ...process.env }; - delete process.env.GOOGLE_TOKEN_ENC_KEY; process.env.TOKEN_ENC_KEY = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; vi.resetModules(); try { - const { encrypt, decrypt } = await import("@/lib/crypto"); + const { encryptToken: encrypt, decryptToken: decrypt } = await import("@/lib/crypto/token-vault"); const enc = encrypt("hello"); expect(decrypt(enc)).toBe("hello"); } finally { diff --git a/src/__tests__/google-availability.test.ts b/src/__tests__/google-availability.test.ts new file mode 100644 index 00000000..f2b3be7d --- /dev/null +++ b/src/__tests__/google-availability.test.ts @@ -0,0 +1,32 @@ +/** + * Google Calendar availability: the fake provider connects without any + * client id (as the connect route does), so a default development setup + * shows the calendar instead of asking for real OAuth credentials. + */ +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { isGoogleCalendarAvailable } from "@/lib/google/availability"; +import { publicConfig } from "@/lib/public-config"; + +describe("isGoogleCalendarAvailable", () => { + afterEach(() => { + vi.unstubAllEnvs(); + }); + + it("is available with the fake provider and no client id", () => { + vi.stubEnv("GOOGLE_PROVIDER", "fake"); + vi.stubEnv("GOOGLE_CLIENT_ID", ""); + expect(isGoogleCalendarAvailable()).toBe(true); + expect(publicConfig().google_configured).toBe(true); + }); + + it("needs a client id for the real provider", () => { + vi.stubEnv("GOOGLE_PROVIDER", "real"); + vi.stubEnv("GOOGLE_CLIENT_ID", ""); + expect(isGoogleCalendarAvailable()).toBe(false); + expect(publicConfig().google_configured).toBe(false); + + vi.stubEnv("GOOGLE_CLIENT_ID", "client-id.apps.googleusercontent.com"); + expect(isGoogleCalendarAvailable()).toBe(true); + }); +}); diff --git a/src/__tests__/google-callback-route.test.ts b/src/__tests__/google-callback-route.test.ts new file mode 100644 index 00000000..4875e943 --- /dev/null +++ b/src/__tests__/google-callback-route.test.ts @@ -0,0 +1,124 @@ +/** + * Unit tests for GET /api/integrations/google/callback redirects. + * + * Every outcome of the OAuth callback lands back on /settings with a + * `google` query parameter, and the provider's error value is URL-encoded. + * The tokens are stored for the signed-in user, and only when the state was + * issued to that same user. + */ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import type { NextRequest } from "next/server"; + +vi.mock("@/lib/db", () => ({ + prisma: { + oAuthState: { deleteMany: vi.fn() }, + googleIntegration: { upsert: vi.fn() }, + }, +})); + +vi.mock("@/lib/auth", () => ({ getUserId: vi.fn() })); + +import { GET } from "@/app/api/integrations/google/callback/route"; +import { prisma } from "@/lib/db"; +import { getUserId } from "@/lib/auth"; + +const claimState = vi.mocked(prisma.oAuthState.deleteMany); +const upsert = vi.mocked(prisma.googleIntegration.upsert); +const sessionUser = vi.mocked(getUserId); + +function callback(query: string): NextRequest { + return new Request( + `http://localhost:3000/api/integrations/google/callback${query}`, + ) as unknown as NextRequest; +} + +function location(res: Response): URL { + return new URL(res.headers.get("location") ?? ""); +} + +describe("GET /api/integrations/google/callback", () => { + beforeEach(() => { + vi.clearAllMocks(); + vi.unstubAllGlobals(); + vi.stubEnv("BASE_URL", "http://localhost:3000"); + vi.stubEnv("GOOGLE_CLIENT_ID", "client-id"); + vi.stubEnv("GOOGLE_CLIENT_SECRET", "client-secret"); + vi.stubEnv("TOKEN_ENC_KEY", "a".repeat(64)); + sessionUser.mockResolvedValue("user-b"); + }); + + it("redirects provider errors to /settings with the reason encoded", async () => { + const res = await GET(callback("?error=access_denied%26x%3D1")); + expect(res.status).toBe(302); + const url = location(res); + expect(url.pathname).toBe("/settings"); + expect(url.searchParams.get("google")).toBe("error"); + expect(url.searchParams.get("reason")).toBe("access_denied&x=1"); + expect(url.searchParams.has("x")).toBe(false); + }); + + it("redirects to /settings when code or state is missing", async () => { + const url = location(await GET(callback("?code=abc"))); + expect(url.pathname).toBe("/settings"); + expect(url.searchParams.get("reason")).toBe("missing_params"); + expect(claimState).not.toHaveBeenCalled(); + }); + + it("redirects to /settings when the state is unknown", async () => { + claimState.mockResolvedValue({ count: 0 }); + const url = location(await GET(callback("?code=abc&state=nope"))); + expect(url.pathname).toBe("/settings"); + expect(url.searchParams.get("google")).toBe("error"); + expect(url.searchParams.get("reason")).toBe("invalid_state"); + }); + + it("rejects a callback with no signed-in user before touching the state", async () => { + sessionUser.mockResolvedValue(null); + const url = location(await GET(callback("?code=abc&state=s1"))); + expect(url.searchParams.get("reason")).toBe("invalid_state"); + expect(claimState).not.toHaveBeenCalled(); + expect(upsert).not.toHaveBeenCalled(); + }); + + it("claims the state only for the signed-in user, unexpired, in one statement", async () => { + claimState.mockResolvedValue({ count: 0 }); + await GET(callback("?code=abc&state=s1")); + expect(claimState).toHaveBeenCalledTimes(1); + const where = claimState.mock.calls[0][0]?.where; + expect(where).toMatchObject({ state: "s1", userId: "user-b" }); + expect(where?.expiresAt).toEqual({ gt: expect.any(Date) }); + }); + + it("refuses user A's state in user B's session and stores no tokens", async () => { + // State "a-state" was issued to user-a; the claim scoped to user-b finds nothing. + claimState.mockImplementation((async (args: { where: { userId: string } }) => ({ + count: args.where.userId === "user-a" ? 1 : 0, + })) as never); + const fetchSpy = vi.fn(); + vi.stubGlobal("fetch", fetchSpy); + + const url = location(await GET(callback("?code=victim-code&state=a-state"))); + expect(url.searchParams.get("reason")).toBe("invalid_state"); + expect(fetchSpy).not.toHaveBeenCalled(); + expect(upsert).not.toHaveBeenCalled(); + }); + + it("stores the tokens under the signed-in user once the state is claimed", async () => { + claimState.mockResolvedValue({ count: 1 }); + vi.stubGlobal( + "fetch", + vi.fn(async (input: string | URL) => + String(input).includes("/token") + ? Response.json({ access_token: "at", refresh_token: "rt", expires_in: 3600, scope: "s" }) + : Response.json({ email: "b@example.com" }), + ), + ); + + const url = location(await GET(callback("?code=abc&state=s1"))); + expect(url.searchParams.get("google")).toBe("connected"); + expect(upsert).toHaveBeenCalledTimes(1); + const args = upsert.mock.calls[0][0]; + expect(args.where).toEqual({ userId: "user-b" }); + expect(args.create).toMatchObject({ userId: "user-b", connectedEmail: "b@example.com" }); + }); +}); diff --git a/src/__tests__/google-connect-route.test.ts b/src/__tests__/google-connect-route.test.ts new file mode 100644 index 00000000..5002fb58 --- /dev/null +++ b/src/__tests__/google-connect-route.test.ts @@ -0,0 +1,86 @@ +/** + * GET /api/integrations/google/connect: signed-out students go to sign-in, + * the fake provider connects straight away (no real consent page), and the + * real flow stores a state for this student before sending them to Google. + */ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import type { NextRequest } from "next/server"; + +vi.mock("@/lib/db", () => ({ + prisma: { + oAuthState: { deleteMany: vi.fn(async () => ({ count: 0 })), create: vi.fn(async () => ({})) }, + googleIntegration: { upsert: vi.fn(async () => ({})) }, + }, +})); + +vi.mock("@/lib/auth", () => ({ getUserId: vi.fn() })); + +import { GET } from "@/app/api/integrations/google/connect/route"; +import { prisma } from "@/lib/db"; +import { getUserId } from "@/lib/auth"; + +const sessionUser = vi.mocked(getUserId); +const createState = vi.mocked(prisma.oAuthState.create); +const upsert = vi.mocked(prisma.googleIntegration.upsert); + +function connect(): NextRequest { + return new Request("http://localhost:3000/api/integrations/google/connect") as unknown as NextRequest; +} + +function location(res: Response): URL { + return new URL(res.headers.get("location") ?? ""); +} + +describe("GET /api/integrations/google/connect", () => { + beforeEach(() => { + vi.clearAllMocks(); + vi.stubEnv("BASE_URL", "http://localhost:3000"); + vi.stubEnv("GOOGLE_CLIENT_ID", "client-id"); + vi.stubEnv("GOOGLE_PROVIDER", "real"); + sessionUser.mockResolvedValue("user-a"); + }); + + afterEach(() => { + vi.unstubAllEnvs(); + }); + + it("sends a signed-out visitor to sign in, back to the calendar section", async () => { + sessionUser.mockResolvedValue(null); + const url = location(await GET(connect())); + expect(url.pathname).toBe("/auth/signin"); + expect(url.searchParams.get("callbackUrl")).toBe("/settings#calendar"); + expect(createState).not.toHaveBeenCalled(); + }); + + it("connects the fake calendar directly instead of opening Google's consent page", async () => { + vi.stubEnv("GOOGLE_PROVIDER", "fake"); + const res = await GET(connect()); + const url = location(res); + expect(url.origin).toBe("http://localhost:3000"); + expect(url.pathname).toBe("/settings"); + expect(url.searchParams.get("google")).toBe("connected"); + expect(upsert).toHaveBeenCalledTimes(1); + const args = upsert.mock.calls[0][0] as { where: unknown; create: Record<string, unknown> }; + expect(args.where).toEqual({ userId: "user-a" }); + expect(args.create).toMatchObject({ userId: "user-a", status: "CONNECTED" }); + expect(createState).not.toHaveBeenCalled(); + }); + + it("stores a state for the signed-in student and redirects to Google", async () => { + const url = location(await GET(connect())); + expect(url.origin).toBe("https://accounts.google.com"); + const state = url.searchParams.get("state"); + expect(state).toMatch(/^[0-9a-f]{64}$/); + expect(createState).toHaveBeenCalledWith({ + data: { state, userId: "user-a", expiresAt: expect.any(Date) }, + }); + expect(upsert).not.toHaveBeenCalled(); + }); + + it("goes back to Settings with a reason when Google isn't configured", async () => { + vi.stubEnv("GOOGLE_CLIENT_ID", ""); + const url = location(await GET(connect())); + expect(url.pathname).toBe("/settings"); + expect(url.searchParams.get("reason")).toBe("not_configured"); + }); +}); diff --git a/src/__tests__/google-disconnect-route.test.ts b/src/__tests__/google-disconnect-route.test.ts new file mode 100644 index 00000000..4fa55b4f --- /dev/null +++ b/src/__tests__/google-disconnect-route.test.ts @@ -0,0 +1,95 @@ +/** + * POST /api/integrations/google/disconnect: revokes the grant at Google with + * the refresh token (the access token has usually expired), with a timeout, + * then clears the stored tokens even when the revoke fails. + */ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import type { NextRequest } from "next/server"; + +vi.mock("@/lib/auth", () => ({ + getUserId: vi.fn(async (request: Request) => request.headers.get("x-user-id")), +})); + +vi.mock("@/lib/crypto/token-vault", () => ({ + decryptToken: vi.fn((value: string) => `plain-${value}`), +})); + +vi.mock("@/lib/db", () => ({ + prisma: { + googleIntegration: { findUnique: vi.fn(), update: vi.fn(async () => ({})) }, + }, +})); + +import { POST } from "@/app/api/integrations/google/disconnect/route"; +import { prisma } from "@/lib/db"; + +const findIntegration = vi.mocked(prisma.googleIntegration.findUnique); +const updateIntegration = vi.mocked(prisma.googleIntegration.update); + +function request(userId: string | null = "u1"): NextRequest { + return new Request("http://localhost:3000/api/integrations/google/disconnect", { + method: "POST", + headers: userId ? { "x-user-id": userId } : {}, + }) as unknown as NextRequest; +} + +describe("POST /api/integrations/google/disconnect", () => { + const fetchMock = vi.fn(async () => new Response(null, { status: 200 })); + + beforeEach(() => { + vi.clearAllMocks(); + vi.stubGlobal("fetch", fetchMock); + }); + + afterEach(() => { + vi.unstubAllGlobals(); + }); + + it("answers 401 when signed out", async () => { + expect((await POST(request(null))).status).toBe(401); + expect(findIntegration).not.toHaveBeenCalled(); + }); + + it("revokes the refresh token, not the expired access token, with a timeout", async () => { + findIntegration.mockResolvedValue({ id: "g1", accessTokenEncrypted: "a", refreshTokenEncrypted: "r" } as never); + const res = await POST(request()); + expect(res.status).toBe(200); + expect(fetchMock).toHaveBeenCalledTimes(1); + const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit]; + expect(url).toBe("https://oauth2.googleapis.com/revoke"); + expect(String(init.body)).toBe("token=plain-r"); + expect(init.signal).toBeInstanceOf(AbortSignal); + expect(updateIntegration).toHaveBeenCalledWith({ + where: { id: "g1" }, + data: expect.objectContaining({ + status: "DISCONNECTED", + accessTokenEncrypted: null, + refreshTokenEncrypted: null, + }), + }); + }); + + it("falls back to the access token when there is no refresh token", async () => { + findIntegration.mockResolvedValue({ id: "g1", accessTokenEncrypted: "a", refreshTokenEncrypted: null } as never); + await POST(request()); + const [, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit]; + expect(String(init.body)).toBe("token=plain-a"); + }); + + it("still clears the tokens when the revoke fails", async () => { + findIntegration.mockResolvedValue({ id: "g1", accessTokenEncrypted: null, refreshTokenEncrypted: "r" } as never); + fetchMock.mockRejectedValueOnce(new Error("timeout")); + const res = await POST(request()); + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ disconnected: true, status: "DISCONNECTED" }); + expect(updateIntegration).toHaveBeenCalledTimes(1); + }); + + it("answers disconnected without calling Google when nothing is connected", async () => { + findIntegration.mockResolvedValue(null); + const res = await POST(request()); + expect(res.status).toBe(200); + expect(fetchMock).not.toHaveBeenCalled(); + expect(updateIntegration).not.toHaveBeenCalled(); + }); +}); diff --git a/src/__tests__/google-messages.test.ts b/src/__tests__/google-messages.test.ts new file mode 100644 index 00000000..1633abef --- /dev/null +++ b/src/__tests__/google-messages.test.ts @@ -0,0 +1,82 @@ +/** + * User-facing Google Calendar copy: OAuth landing results and API codes. + */ +import { describe, it, expect } from "vitest"; +import { GOOGLE_COPY, googleConnectResult, googleErrorMessage } from "@/lib/google/messages"; + +const REASONS = [ + "access_denied", + "invalid_state", + "missing_params", + "not_configured", + "token_exchange_failed", + "no_refresh_token", + "internal", + "something_new", +]; + +describe("googleConnectResult", () => { + it("reports a connection", () => { + expect(googleConnectResult("connected", null)).toMatchObject({ + tone: "success", + title: "Google Calendar connected", + }); + }); + + it("returns null when the page wasn't reached from the callback", () => { + expect(googleConnectResult(undefined, undefined)).toBeNull(); + expect(googleConnectResult("weird", "access_denied")).toBeNull(); + }); + + it("gives every failure reason a title and a next step", () => { + for (const reason of REASONS) { + const result = googleConnectResult("error", reason); + expect(result?.tone).toBe("error"); + expect(result?.title).toBe("Google Calendar not connected"); + expect(result?.description).toMatch(/\.$/); + } + }); + + it("never shows raw codes, dashes or exclamation marks", () => { + for (const reason of REASONS) { + for (const dev of [false, true]) { + const result = googleConnectResult("error", reason, { dev }); + const text = `${result?.title} ${result?.description}`; + expect(text).not.toContain(reason); + expect(text).not.toMatch(/[–—!]/); + } + } + }); + + it("keeps setup details for development", () => { + expect(googleConnectResult("error", "not_configured")?.description).not.toContain("GOOGLE_CLIENT_ID"); + expect(googleConnectResult("error", "not_configured", { dev: true })?.description).toContain( + "GOOGLE_CLIENT_ID", + ); + }); +}); + +describe("googleErrorMessage", () => { + it("maps API codes to sentences", () => { + expect(googleErrorMessage("GOOGLE_RECONNECT_REQUIRED")).toBe(GOOGLE_COPY.reconnect); + expect(googleErrorMessage("INVALID_GRANT")).toBe(GOOGLE_COPY.reconnect); + expect(googleErrorMessage("GOOGLE_NOT_CONNECTED")).toBe(GOOGLE_COPY.notConnected); + expect(googleErrorMessage("ALREADY_PUBLISHED_DIFFERENT_CALENDAR")).toBe(GOOGLE_COPY.differentCalendar); + expect(googleErrorMessage("not_found")).toBe("This plan doesn't exist anymore."); + expect(googleErrorMessage("forbidden")).toBe("This plan belongs to another account."); + expect(googleErrorMessage(undefined)).toBe(GOOGLE_COPY.unavailable); + }); + + it("has one fallback sentence for every other failure", () => { + expect(GOOGLE_COPY.unavailable).toBe("Google Calendar didn't respond. Retry in a minute."); + for (const code of ["GOOGLE_API_ERROR", "RATE_LIMITED", "", null]) { + expect(googleErrorMessage(code)).toBe(GOOGLE_COPY.unavailable); + } + }); + + it("never shows a raw code, a dash or an exclamation mark", () => { + for (const text of Object.values(GOOGLE_COPY)) { + expect(text).not.toMatch(/[A-Z]{2,}_[A-Z_]+|[–—!]/); + } + }); +}); diff --git a/src/__tests__/google-status-dto.test.ts b/src/__tests__/google-status-dto.test.ts new file mode 100644 index 00000000..5a61964a --- /dev/null +++ b/src/__tests__/google-status-dto.test.ts @@ -0,0 +1,60 @@ +/** + * The Google Calendar status the Settings and plan pages read. + */ +import { describe, it, expect, vi } from "vitest"; + +vi.mock("@/lib/db", () => ({ prisma: {} })); + +import { toGoogleStatus } from "@/services/google-status"; + +const row = { + status: "CONNECTED", + connectedEmail: "ben@example.com", + scopeString: "a b", + calendarIdSelected: "primary", + busyCalendarIds: "primary, work@group.calendar.google.com", + timezone: "America/New_York", + lastHealthyAt: new Date("2026-10-14T12:00:00Z"), + lastErrorCode: null, + lastErrorMessage: null, + tokenExpiryMs: BigInt(1000), +}; + +describe("toGoogleStatus", () => { + it("reports no integration as disconnected, with the e2e-visible defaults", () => { + expect(toGoogleStatus(null)).toEqual({ + status: "DISCONNECTED", + connected: false, + needs_reconnect: false, + scopes: [], + default_calendar_id: "primary", + busy_calendar_ids: ["primary"], + }); + }); + + it("reports a connected integration with its calendars", () => { + const status = toGoogleStatus(row); + expect(status.connected).toBe(true); + expect(status.needs_reconnect).toBe(false); + expect(status.connected_email).toBe("ben@example.com"); + expect(status.busy_calendar_ids).toEqual(["primary", "work@group.calendar.google.com"]); + expect(status.scopes).toEqual(["a", "b"]); + }); + + it("asks for a reconnect when Google revoked access", () => { + const status = toGoogleStatus({ ...row, status: "DISCONNECTED", lastErrorCode: "INVALID_GRANT" }); + expect(status).toMatchObject({ connected: false, needs_reconnect: true, connected_email: "ben@example.com" }); + }); + + it("doesn't ask for a reconnect after a deliberate disconnect", () => { + expect(toGoogleStatus({ ...row, status: "DISCONNECTED" }).needs_reconnect).toBe(false); + }); + + it("treats an ERROR status as needing a reconnect", () => { + expect(toGoogleStatus({ ...row, status: "ERROR" })).toMatchObject({ + status: "ERROR", + connected: false, + needs_reconnect: true, + }); + }); +}); diff --git a/src/__tests__/guide-format.test.ts b/src/__tests__/guide-format.test.ts new file mode 100644 index 00000000..0a72ae13 --- /dev/null +++ b/src/__tests__/guide-format.test.ts @@ -0,0 +1,110 @@ +import { describe, expect, it } from "vitest"; +import { + guideFileName, + guideTitle, + guideToMarkdown, + guideTypeFromSlug, + normalizeGuideSections, + toGuideText, +} from "@/lib/guide-format"; + +describe("toGuideText", () => { + it("keeps strings and stringifies scalars", () => { + expect(toGuideText(" a ")).toBe("a"); + expect(toGuideText(3)).toBe("3"); + expect(toGuideText(null)).toBe(""); + }); + + it("turns a list into Markdown bullets", () => { + expect(toGuideText(["First", "Second"])).toBe("- First\n- Second"); + }); + + it("turns rows of cells into a Markdown table", () => { + expect( + toGuideText([ + ["Term", "Meaning"], + ["ID", "(1,0,0)"], + ["a|b", "pipe"], + ]), + ).toBe("| Term | Meaning |\n| --- | --- |\n| ID | (1,0,0) |\n| a\\|b | pipe |"); + }); + + it("turns an object into key: value lines", () => { + expect(toGuideText({ formula: "E = mc^2", note: ["one", "two"] })).toBe( + "formula: E = mc^2\nnote:\n- one\n- two", + ); + }); +}); + +describe("normalizeGuideSections", () => { + it("never returns non-string fields, whatever the stored shape", () => { + const sections = normalizeGuideSections([ + { topic: "Box model", content: ["content-box", "border-box"] }, + { concept: "Specificity", explanation: { ids: 1, classes: 2 }, importance: 7 }, + "A loose paragraph", + null, + 42, + { unknown: "dropped" }, + ]); + expect(sections).toEqual([ + { topic: "Box model", content: "- content-box\n- border-box" }, + { concept: "Specificity", explanation: "ids: 1\nclasses: 2", importance: "7" }, + { content: "A loose paragraph" }, + ]); + for (const s of sections) { + for (const value of Object.values(s)) expect(typeof value).toBe("string"); + } + }); + + it("accepts an object wrapper or an object of sections", () => { + expect(normalizeGuideSections({ sections: [{ question: "Q", answer: "A" }] })).toEqual([ + { question: "Q", answer: "A" }, + ]); + expect(normalizeGuideSections({ a: { topic: "T", content: "C" } })).toEqual([{ topic: "T", content: "C" }]); + expect(normalizeGuideSections(undefined)).toEqual([]); + expect(normalizeGuideSections("text")).toEqual([]); + }); +}); + +describe("guide titles and files", () => { + it("replaces the old enum fallback titles", () => { + expect(guideTitle("KEY CONCEPTS Guide", "KEY_CONCEPTS", "Prelim 2")).toBe("Key concepts for Prelim 2"); + expect(guideTitle("", "CHEAT_SHEET", "INFO 1300")).toBe("Cheat sheet for INFO 1300"); + expect(guideTitle("Prelim 2 cheat sheet", "CHEAT_SHEET", "x")).toBe("Prelim 2 cheat sheet"); + }); + + it("slugs the file name and never returns a bare .md", () => { + expect(guideFileName("Prelim 2 cheat sheet")).toBe("prelim-2-cheat-sheet.md"); + expect(guideFileName("Big-O: the basics!")).toBe("bigo-the-basics.md"); + expect(guideFileName("¿?")).toBe("study-guide.md"); + }); + + it("reads format slugs from the URL", () => { + expect(guideTypeFromSlug("cheat-sheet")).toBe("CHEAT_SHEET"); + expect(guideTypeFromSlug("FAQ")).toBe("FAQ"); + expect(guideTypeFromSlug("nope")).toBeNull(); + expect(guideTypeFromSlug(null)).toBeNull(); + }); +}); + +describe("guideToMarkdown", () => { + it("keeps the export layout", () => { + expect( + guideToMarkdown({ + title: "Prelim 2 key concepts", + sections: [ + { concept: "Specificity", explanation: "IDs beat classes.", importance: "Most cascade questions." }, + { question: "Why?", answer: "Because." }, + { topic: "Box model", content: "content-box\nborder-box" }, + ], + }), + ).toBe( + "# Prelim 2 key concepts\n\n" + + "## Specificity\nIDs beat classes.\n_Why it matters: Most cascade questions._" + + "\n\n---\n\n" + + "**Q: Why?**\nBecause." + + "\n\n---\n\n" + + "## Box model\ncontent-box\nborder-box", + ); + }); +}); diff --git a/src/__tests__/home-model.test.ts b/src/__tests__/home-model.test.ts new file mode 100644 index 00000000..fd6a704a --- /dev/null +++ b/src/__tests__/home-model.test.ts @@ -0,0 +1,190 @@ +/** + * Home's exam countdowns and today's sessions: every "today" is the + * student's day, whatever zone the server runs in. + */ +import { describe, expect, it } from "vitest" + +import { + examCountdowns, + examInstant, + isOpenPlanStatus, + missedItems, + todayPlan, + type PlanLike, +} from "@/lib/home-model" +import { statItems } from "@/components/home/stat-items" +import { daysUntil } from "@/lib/format" + +const ZONE = "America/New_York" +// 9:30pm on Thursday Oct 15 in New York, already Friday Oct 16 in UTC. +const NOW = new Date("2026-10-16T01:30:00Z") + +function item(id: string, start: string, minutes: number, status = "SCHEDULED") { + const startTime = new Date(start) + return { + id, + sessionId: `s-${id}`, + startTime, + endTime: new Date(startTime.getTime() + minutes * 60_000), + status, + } +} + +function plan(overrides: Partial<PlanLike> = {}): PlanLike { + return { + planId: "p1", + courseName: "INFO 1300", + examName: "Prelim 2", + examDateKey: "2026-10-22", + items: [], + lastRescheduledAt: null, + ...overrides, + } +} + +describe("examInstant", () => { + it("counts whole days to the exam's calendar date in the student's zone", () => { + // A @db.Date exam stored as 2026-10-22T00:00Z is Oct 21 at 8pm in New + // York; read naively it would count one day short. + expect(daysUntil(new Date("2026-10-22T00:00:00Z"), { timeZone: ZONE, now: NOW })).toBe(6) + expect(daysUntil(examInstant("2026-10-22", ZONE), { timeZone: ZONE, now: NOW })).toBe(7) + }) +}) + +describe("examCountdowns", () => { + it("lists upcoming exams nearest first and drops past ones", () => { + const exams = examCountdowns( + [ + plan({ planId: "later", examDateKey: "2026-12-14", courseName: "ECON 1110", examName: "Final" }), + plan({ planId: "past", examDateKey: "2026-10-14" }), + plan({ planId: "soon", examDateKey: "2026-10-22" }), + plan({ planId: "today", examDateKey: "2026-10-15", courseName: "AEM 2210", examName: "Quiz" }), + ], + ZONE, + NOW + ) + expect(exams.map((e) => e.planId)).toEqual(["today", "soon", "later"]) + }) + + it("counts done and total sessions, leaving skipped ones out", () => { + const [exam] = examCountdowns( + [ + plan({ + items: [ + item("a", "2026-10-13T18:00:00Z", 30, "DONE"), + item("b", "2026-10-14T18:00:00Z", 30, "SKIPPED"), + item("c", "2026-10-20T18:00:00Z", 30), + ], + }), + ], + ZONE, + NOW + ) + expect(exam).toMatchObject({ sessionsDone: 1, sessionsTotal: 2 }) + }) +}) + +describe("missedItems", () => { + it("counts sessions marked missed and scheduled ones whose day has ended", () => { + const p = plan({ + items: [ + item("missed", "2026-10-13T18:00:00Z", 30, "MISSED"), + item("stale", "2026-10-14T18:00:00Z", 30), // yesterday, never started + item("tonight", "2026-10-15T23:00:00Z", 30), // 7pm today in New York + ], + }) + expect(missedItems(p, "2026-10-15", ZONE).map((i) => i.id)).toEqual(["missed", "stale"]) + }) + + it("stops counting a missed session once the plan is rescheduled after it", () => { + const p = plan({ + items: [item("missed", "2026-10-13T18:00:00Z", 30, "MISSED")], + lastRescheduledAt: new Date("2026-10-14T12:00:00Z"), + }) + expect(missedItems(p, "2026-10-15", ZONE)).toEqual([]) + }) + + it("counts a rescheduled session that was missed again on its new day", () => { + const p = plan({ + // Moved on Oct 13 to Oct 14, then not started on Oct 14 either. + items: [item("moved", "2026-10-14T18:00:00Z", 30, "RESCHEDULED")], + lastRescheduledAt: new Date("2026-10-13T12:00:00Z"), + }) + expect(missedItems(p, "2026-10-15", ZONE).map((i) => i.id)).toEqual(["moved"]) + }) +}) + +describe("todayPlan", () => { + it("uses the student's day, not the UTC day", () => { + // 7pm Oct 15 in New York is Oct 16 in UTC: still today for the student. + const tonight = item("tonight", "2026-10-15T23:00:00Z", 30) + // 10am Oct 16 in New York: tomorrow. + const tomorrow = item("tomorrow", "2026-10-16T14:00:00Z", 30) + const result = todayPlan([plan({ items: [tomorrow, tonight] })], ZONE, NOW) + expect(result.today.map((i) => i.id)).toEqual(["tonight"]) + expect(result.current?.id).toBe("tonight") + expect(result.next).toBeNull() + }) + + it("offers the next scheduled session when nothing is open today", () => { + const done = item("done", "2026-10-15T18:00:00Z", 30, "DONE") + const next = item("next", "2026-10-17T14:00:00Z", 30) + const result = todayPlan([plan({ items: [next, done] })], ZONE, NOW) + expect(result.current).toBeNull() + expect(result.today.map((i) => i.id)).toEqual(["done"]) + expect(result.next?.id).toBe("next") + }) + + it("puts a session left in progress on an earlier day first", () => { + const carried = item("carried", "2026-10-14T18:00:00Z", 30, "IN_PROGRESS") + const later = item("later", "2026-10-15T23:00:00Z", 30) + const result = todayPlan([plan({ items: [later, carried] })], ZONE, NOW) + expect(result.current?.id).toBe("carried") + }) + + it("offers a session moved to today by Reschedule as the one to start", () => { + const done = item("done", "2026-10-15T14:00:00Z", 30, "DONE") + const moved = item("moved", "2026-10-15T19:00:00Z", 30, "RESCHEDULED") // 3pm today + const result = todayPlan([plan({ items: [moved, done] })], ZONE, NOW) + expect(result.current?.id).toBe("moved") + expect(result.next).toBeNull() + }) + + it("offers a session moved to a later day as the next one", () => { + const moved = item("moved", "2026-10-17T14:00:00Z", 30, "RESCHEDULED") + const result = todayPlan([plan({ items: [moved] })], ZONE, NOW) + expect(result.current).toBeNull() + expect(result.next?.id).toBe("moved") + }) +}) + +describe("isOpenPlanStatus", () => { + it("treats scheduled, rescheduled and in-progress sessions as startable", () => { + expect(["SCHEDULED", "RESCHEDULED", "IN_PROGRESS"].every(isOpenPlanStatus)).toBe(true) + expect(["DONE", "MISSED", "SKIPPED"].some(isOpenPlanStatus)).toBe(false) + }) +}) + +describe("statItems", () => { + const week = { answers: 0, correct: 0, answeringSeconds: 0, plannedMinutes: 0, sessions: 0 } + + it("reports accuracy and the time spent answering", () => { + const items = statItems(4, { ...week, answers: 49, correct: 29, answeringSeconds: 4419, sessions: 5 }) + expect(items.map((i) => [i.value, i.label])).toEqual([ + ["4-day streak", undefined], + ["59%", "accuracy, last 7 days"], + ["74 min", "answering questions, last 7 days"], + ]) + }) + + it("labels planned minutes honestly when sessions have no answer timers", () => { + const items = statItems(0, { ...week, answers: 10, correct: 5, plannedMinutes: 30, sessions: 1 }) + expect(items[0].value).toBe("No current streak") + expect(items[2]).toMatchObject({ value: "30 min", label: "of completed sessions, last 7 days" }) + }) + + it("says so when there are no answers instead of showing a dash", () => { + const items = statItems(1, week) + expect(items.map((i) => i.value)).toEqual(["1-day streak", "No answers in the last 7 days"]) + }) +}) diff --git a/src/__tests__/integration/efficiency-sprint.test.ts b/src/__tests__/integration/efficiency-sprint.test.ts index 263d962f..9a79d041 100644 --- a/src/__tests__/integration/efficiency-sprint.test.ts +++ b/src/__tests__/integration/efficiency-sprint.test.ts @@ -207,17 +207,18 @@ The loop invariant for binary search is that the target element, if present, mus result = await generateFeedback(USER, attemptId); } expect(result.status).toBe("OK"); - // We have course docs, should get results - if (result.excerpts.length > 0) { - expect(result.excerpts[0].snippet).toBeTruthy(); - expect(result.excerpts[0].doc_title).toBeTruthy(); - - // Citations should be stored in DB - const citations = await prisma.attemptCitation.findMany({ - where: { attemptId }, - }); - expect(citations.length).toBeGreaterThan(0); - } + // The uploaded file covers loop invariants, so the feedback must cite it + // (no anchors exist yet, so this goes through the full-text fallback). + expect(result.no_sources).toBeUndefined(); + expect(result.excerpts.length).toBeGreaterThan(0); + expect(result.excerpts[0].snippet).toBeTruthy(); + expect(result.excerpts[0].doc_title).toBeTruthy(); + + // Citations should be stored in DB + const citations = await prisma.attemptCitation.findMany({ + where: { attemptId }, + }); + expect(citations.length).toBeGreaterThan(0); }); it("GET feedback is idempotent (returns cached citations)", async () => { @@ -256,13 +257,13 @@ The loop invariant for binary search is that the target element, if present, mus }); it("anchor results are idempotent (upsert)", async () => { - const result1 = await buildObjectiveAnchors( + await buildObjectiveAnchors( USER, COURSE, undefined, [{ id: "obj_1", title: "Loop invariants" }] ); - const result2 = await buildObjectiveAnchors( + await buildObjectiveAnchors( USER, COURSE, undefined, diff --git a/src/__tests__/integration/full-flow.test.ts b/src/__tests__/integration/full-flow.test.ts index 559c713b..5f81b56c 100644 --- a/src/__tests__/integration/full-flow.test.ts +++ b/src/__tests__/integration/full-flow.test.ts @@ -8,7 +8,7 @@ * * If no DATABASE_URL is available, tests are skipped automatically. */ -import { describe, it, expect, beforeAll, afterAll, beforeEach } from "vitest"; +import { describe, it, expect, beforeAll, afterAll } from "vitest"; const hasDb = !!process.env.DATABASE_URL; @@ -79,7 +79,7 @@ describe.skipIf(!hasDb)("Integration: full session flow", () => { expect(result.session_id).toBeDefined(); expect(result.session_url).toContain(`/s/${result.session_id}`); - expect(result.calendar.title).toBe("TEST 101 | Exam 1 | Retrieval: Unit Tests"); + expect(result.calendar.title).toBe("Retrieval: Unit Tests · TEST 101 Exam 1"); sessionId = result.session_id; }); diff --git a/src/__tests__/integration/google-calendar.test.ts b/src/__tests__/integration/google-calendar.test.ts index 30db6025..4818ae85 100644 --- a/src/__tests__/integration/google-calendar.test.ts +++ b/src/__tests__/integration/google-calendar.test.ts @@ -11,6 +11,7 @@ import { resetGoogleClientFactory, type BusyInterval, } from "@/lib/google/calendar-client"; +import { addDays, dayKey, zonedTimeToUtc } from "@/lib/timezone"; const hasDb = !!process.env.DATABASE_URL; @@ -114,22 +115,23 @@ describe.skipIf(!hasDb)("Integration: Google Calendar", () => { }); it("avoids busy slots when use_google_availability is true", async () => { - const tomorrow = new Date(); - tomorrow.setDate(tomorrow.getDate() + 1); - tomorrow.setHours(9, 0, 0, 0); - const busyEnd = new Date(tomorrow); - busyEnd.setHours(13, 0, 0, 0); + // Busy 09:00-13:00 on plan day 1, as wall-clock times in the plan's zone + const timeZone = "America/New_York"; + const tomorrow = addDays(dayKey(new Date(), timeZone), 1); + const busyStart = zonedTimeToUtc(tomorrow, "09:00", timeZone); + const busyEnd = zonedTimeToUtc(tomorrow, "13:00", timeZone); fakeClient.setBusy([ { calendarId: "primary", - start: tomorrow.toISOString(), + start: busyStart.toISOString(), end: busyEnd.toISOString(), }, ]); const result = await createPlan(userId, { ...basePlanInput, + timezone: timeZone, use_google_availability: true, }); diff --git a/src/__tests__/integration/knowledge-layer.test.ts b/src/__tests__/integration/knowledge-layer.test.ts index 3100703e..db30a971 100644 --- a/src/__tests__/integration/knowledge-layer.test.ts +++ b/src/__tests__/integration/knowledge-layer.test.ts @@ -12,7 +12,6 @@ let prisma: any; let uploadDocument: any; let processDocument: any; let listDocuments: any; -let fetchFeedbackExcerpts: any; let searchChunks: any; let createSession: any; let startOrResumeRun: any; @@ -53,7 +52,6 @@ The outer loop invariant must account for the inner loop's effect. uploadDocument = contentService.uploadDocument; processDocument = contentService.processDocument; listDocuments = contentService.listDocuments; - fetchFeedbackExcerpts = contentService.fetchFeedbackExcerpts; const searchModule = await import("@/lib/search"); searchChunks = searchModule.searchChunks; const sessionService = await import("@/services/session"); diff --git a/src/__tests__/integration/mode-parity.test.ts b/src/__tests__/integration/mode-parity.test.ts index af19b626..834cb92e 100644 --- a/src/__tests__/integration/mode-parity.test.ts +++ b/src/__tests__/integration/mode-parity.test.ts @@ -14,7 +14,6 @@ let startOrResumeRun: any; let submitAttempt: any; let completeRun: any; let getRun: any; -let endBreak: any; // ============================================================ // INTERLEAVED_PRACTICE diff --git a/src/__tests__/payload-budget.test.ts b/src/__tests__/integration/payload-budget.test.ts similarity index 90% rename from src/__tests__/payload-budget.test.ts rename to src/__tests__/integration/payload-budget.test.ts index 8b6f425e..59147016 100644 --- a/src/__tests__/payload-budget.test.ts +++ b/src/__tests__/integration/payload-budget.test.ts @@ -35,19 +35,19 @@ describe.skipIf(!hasDb)("Payload Size Budget", () => { await prisma.$disconnect(); }); - it("start response with prompt_count=100 stays under 50KB when prompts field is excluded", async () => { + it("start response with the most questions a session allows stays under 50KB when prompts field is excluded", async () => { const sess = await createSession(USER, { course_name: COURSE, exam_name: "Big Exam", mode: "RETRIEVAL", topic_scope: "Comprehensive review", planned_minutes: 120, - target_outcome: { prompt_count: 100 }, + target_outcome: { prompt_count: 60 }, }); const result = await startOrResumeRun(USER, sess.session_id); expect("data" in result).toBe(true); - expect(result.data.prompt_count).toBe(100); + expect(result.data.prompt_count).toBe(60); expect(result.data.current_prompt).toBeDefined(); expect(result.data.current_prompt.prompt_index).toBe(0); diff --git a/src/__tests__/integration/plan-flow.test.ts b/src/__tests__/integration/plan-flow.test.ts index dbd24939..34d65e75 100644 --- a/src/__tests__/integration/plan-flow.test.ts +++ b/src/__tests__/integration/plan-flow.test.ts @@ -16,7 +16,6 @@ let getPlan: any; let generatePlanIcs: any; let startOrResumeRun: any; let submitAttempt: any; -let getRun: any; describe.skipIf(!hasDb)("Integration: plan creation and retrieval", () => { const userId = "test_user_plan"; @@ -58,7 +57,6 @@ describe.skipIf(!hasDb)("Integration: plan creation and retrieval", () => { const runService = await import("@/services/run"); startOrResumeRun = runService.startOrResumeRun; submitAttempt = runService.submitAttempt; - getRun = runService.getRun; }); afterAll(async () => { diff --git a/src/__tests__/integration/reflow-api.test.ts b/src/__tests__/integration/reflow-api.test.ts index 73d0ee6b..85a1145d 100644 --- a/src/__tests__/integration/reflow-api.test.ts +++ b/src/__tests__/integration/reflow-api.test.ts @@ -16,6 +16,8 @@ import { setGoogleClientFactory, resetGoogleClientFactory, } from "@/lib/google/calendar-client"; +import { dateColumnKey } from "@/lib/plan-dates"; +import { zonedTimeToUtc } from "@/lib/timezone"; const hasDb = !!process.env.DATABASE_URL; @@ -106,6 +108,13 @@ describe.skipIf(!hasDb)("Integration: Reflow API", () => { break_protocol_default: "50_10", }; + // The reflow routes pass noon of the plan's first day in its timezone and + // read availability in that zone. startDate is a DATE column, so read it as + // a calendar day (plan-dates.ts), not as midnight UTC. + function planStartInstant(plan: { startDate: Date; timezone: string }) { + return zonedTimeToUtc(dateColumnKey(plan.startDate), "12:00", plan.timezone); + } + // Helper: create a plan and return its ID + items async function createTestPlan() { const result = await createPlan(userId, basePlanInput); @@ -174,7 +183,7 @@ describe.skipIf(!hasDb)("Integration: Reflow API", () => { const earlyNow = new Date(plan.startDate); earlyNow.setDate(earlyNow.getDate() - 1); - const result = computeReflow(reflowItems, reflowConfig, plan.startDate, earlyNow); + const result = computeReflow(reflowItems, reflowConfig, planStartInstant(plan), earlyNow, [], plan.timezone); // The MISSED item should NOT be in the movable set (it's terminal) // Only SCHEDULED items should be in changes @@ -243,7 +252,7 @@ describe.skipIf(!hasDb)("Integration: Reflow API", () => { const earlyNow = new Date(plan.startDate); earlyNow.setDate(earlyNow.getDate() - 1); - const result = computeReflow(reflowItems, reflowConfig, plan.startDate, earlyNow); + const result = computeReflow(reflowItems, reflowConfig, planStartInstant(plan), earlyNow, [], plan.timezone); const movedChanges = result.changes.filter((c: { action: string }) => c.action === "MOVED"); const droppedChanges = result.changes.filter((c: { action: string }) => c.action === "DROPPED"); @@ -425,7 +434,7 @@ describe.skipIf(!hasDb)("Integration: Reflow API", () => { const earlyNow = new Date(plan.startDate); earlyNow.setDate(earlyNow.getDate() - 1); - const result = computeReflow(reflowItems, reflowConfig, plan.startDate, earlyNow); + const result = computeReflow(reflowItems, reflowConfig, planStartInstant(plan), earlyNow, [], plan.timezone); // The locked item should NOT appear in the changes at all // (it's classified as "fixed" and excluded from movable) @@ -446,7 +455,7 @@ describe.skipIf(!hasDb)("Integration: Reflow API", () => { // ---- Test 5: Item status endpoint behavior ---- it("DONE sets completedAt, MISSED sets missedAt", async () => { - const { planId, items } = await createTestPlan(); + const { items } = await createTestPlan(); // Mark first item DONE const doneItem = await prisma.studyPlanItem.update({ diff --git a/src/__tests__/integration/research.test.ts b/src/__tests__/integration/research.test.ts index cc48ba46..a812872d 100644 --- a/src/__tests__/integration/research.test.ts +++ b/src/__tests__/integration/research.test.ts @@ -1,174 +1,180 @@ /** - * Unit tests for the research evidence card query service. + * Integration tests for the research evidence card query service. * - * Uses the real database — requires Postgres with seeded research data. - * Run `npm run db:seed-research` before running these tests. + * Needs Postgres through DATABASE_URL and is skipped without it, like the + * other integration files. The file creates its own paper and three cards and + * removes them afterwards. Every query uses tags unique to this run, so + * research data loaded by `npm run db:seed-research` can't change the results. */ import { describe, it, expect, beforeAll, afterAll } from "vitest"; -import { prisma } from "@/lib/db"; -import { - queryEvidenceCards, - listEvidenceTags, - buildResearchContext, -} from "@/services/research"; -const SYSTEM_USER_ID = "__system__"; +const hasDb = !!process.env.DATABASE_URL; -// ---- Test Data Setup ---- - -let testPaperId: string; -let testDocId: string; - -beforeAll(async () => { - // Create a minimal test document + paper + cards - const doc = await prisma.contentDocument.create({ - data: { - userId: SYSTEM_USER_ID, - namespace: "RESEARCH", - title: "Test Paper for Research Service", - originalFilename: "test-paper.txt", - mimeType: "text/plain", - storageKey: "__test__/research/test-paper.txt", - contentHash: `test-hash-${Date.now()}`, - status: "PROCESSED", - }, - }); - testDocId = doc.id; - - const paper = await prisma.evidencePaper.create({ - data: { - userId: SYSTEM_USER_ID, - title: "Test Paper for Research Service", - authors: "Test Author", - year: 2024, - venue: "Test Journal", - documentId: doc.id, - tags: ["spacing", "test-tag"], - }, - }); - testPaperId = paper.id; - - await prisma.evidenceCard.createMany({ - data: [ - { - evidencePaperId: paper.id, - claim: "Spacing improves retention", - recommendation: "Space sessions 1-2 days apart", - boundaryConditions: "Only for declarative knowledge", - strength: "STRONG", - tags: ["spacing", "scheduling"], - }, - { - evidencePaperId: paper.id, - claim: "Retrieval practice is effective", - recommendation: "Use active recall", - boundaryConditions: null, - strength: "MODERATE", - tags: ["retrieval-practice", "active-learning"], +// Type-only references: the modules load in beforeAll. +let prisma: typeof import("@/lib/db").prisma | undefined; +let queryEvidenceCards: typeof import("@/services/research").queryEvidenceCards; +let buildResearchContext: typeof import("@/services/research").buildResearchContext; + +const SYSTEM_USER_ID = "__system__"; +const STAMP = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`; +/** On the STRONG and WEAK cards. */ +const TAG_A = `test-tag-a-${STAMP}`; +/** On the MODERATE card only. */ +const TAG_B = `test-tag-b-${STAMP}`; +const MISSING_TAG = `test-tag-missing-${STAMP}`; + +const STRONG_CLAIM = "Spacing improves retention"; +const MODERATE_CLAIM = "Retrieval practice is effective"; +const WEAK_CLAIM = "Weak finding about font size"; + +describe.skipIf(!hasDb)("Integration: research evidence cards", () => { + let testPaperId: string | undefined; + let testDocId: string | undefined; + + beforeAll(async () => { + // Imported here so nothing touches the database when the suite is skipped. + const db = (await import("@/lib/db")).prisma; + prisma = db; + ({ queryEvidenceCards, buildResearchContext } = await import("@/services/research")); + + const doc = await db.contentDocument.create({ + data: { + userId: SYSTEM_USER_ID, + namespace: "RESEARCH", + title: "Test Paper for Research Service", + originalFilename: "test-paper.txt", + mimeType: "text/plain", + storageKey: `__test__/research/test-paper-${STAMP}.txt`, + contentHash: `test-hash-${STAMP}`, + status: "PROCESSED", }, - { - evidencePaperId: paper.id, - claim: "Weak finding about font size", - recommendation: "Use larger fonts maybe", - boundaryConditions: "Very limited evidence", - strength: "WEAK", - tags: ["font-size", "test-tag"], + }); + testDocId = doc.id; + + const paper = await db.evidencePaper.create({ + data: { + userId: SYSTEM_USER_ID, + title: "Test Paper for Research Service", + authors: "Test Author", + year: 2024, + venue: "Test Journal", + documentId: doc.id, + tags: ["spacing", TAG_A, TAG_B], }, - ], - }); -}); - -afterAll(async () => { - // Clean up test data - await prisma.evidenceCard.deleteMany({ where: { evidencePaperId: testPaperId } }); - await prisma.evidencePaper.delete({ where: { id: testPaperId } }); - await prisma.contentDocument.delete({ where: { id: testDocId } }); -}); - -// ---- Tests ---- - -describe("queryEvidenceCards", () => { - it("returns cards matching any of the given tags", async () => { - const results = await queryEvidenceCards(["spacing"]); - expect(results.length).toBeGreaterThanOrEqual(1); - for (const card of results) { - expect(card.tags).toContain("spacing"); - } - }); - - it("returns empty array for no matching tags", async () => { - const results = await queryEvidenceCards(["nonexistent-tag-xyz"]); - expect(results).toEqual([]); - }); - - it("returns empty array for empty tags input", async () => { - const results = await queryEvidenceCards([]); - expect(results).toEqual([]); - }); - - it("sorts STRONG cards before MODERATE before WEAK", async () => { - const results = await queryEvidenceCards(["spacing", "retrieval-practice", "font-size", "test-tag"]); - expect(results.length).toBeGreaterThanOrEqual(3); - - // Find our test cards - const strong = results.findIndex((c) => c.claim === "Spacing improves retention"); - const moderate = results.findIndex((c) => c.claim === "Retrieval practice is effective"); - const weak = results.findIndex((c) => c.claim === "Weak finding about font size"); - - if (strong !== -1 && moderate !== -1) expect(strong).toBeLessThan(moderate); - if (moderate !== -1 && weak !== -1) expect(moderate).toBeLessThan(weak); - }); - - it("filters by strength when specified", async () => { - const results = await queryEvidenceCards(["spacing", "test-tag"], { strength: "STRONG" }); - for (const card of results) { - expect(card.strength).toBe("STRONG"); - } + }); + testPaperId = paper.id; + + // The cards keep realistic tags such as "spacing" too; the tests never + // query those, because seeded research cards share them. + await db.evidenceCard.createMany({ + data: [ + { + evidencePaperId: paper.id, + claim: STRONG_CLAIM, + recommendation: "Space sessions 1-2 days apart", + boundaryConditions: "Only for declarative knowledge", + strength: "STRONG", + tags: ["spacing", "scheduling", TAG_A], + }, + { + evidencePaperId: paper.id, + claim: MODERATE_CLAIM, + recommendation: "Use active recall", + boundaryConditions: null, + strength: "MODERATE", + tags: ["retrieval-practice", "active-learning", TAG_B], + }, + { + evidencePaperId: paper.id, + claim: WEAK_CLAIM, + recommendation: "Use larger fonts maybe", + boundaryConditions: "Very limited evidence", + strength: "WEAK", + tags: ["font-size", TAG_A], + }, + ], + }); }); - it("respects limit option", async () => { - const results = await queryEvidenceCards(["spacing", "retrieval-practice", "test-tag"], { limit: 1 }); - expect(results.length).toBe(1); - }); - - it("includes paper metadata in results", async () => { - const results = await queryEvidenceCards(["spacing"]); - const testCard = results.find((c) => c.claim === "Spacing improves retention"); - expect(testCard).toBeDefined(); - expect(testCard!.paper.title).toBe("Test Paper for Research Service"); - expect(testCard!.paper.authors).toBe("Test Author"); - expect(testCard!.paper.year).toBe(2024); - }); -}); - -describe("listEvidenceTags", () => { - it("returns sorted unique tags", async () => { - const tags = await listEvidenceTags(); - expect(tags.length).toBeGreaterThanOrEqual(1); - // Check sorted - for (let i = 1; i < tags.length; i++) { - expect(tags[i] >= tags[i - 1]).toBe(true); + afterAll(async () => { + if (!prisma) return; + if (testPaperId) { + await prisma.evidenceCard.deleteMany({ where: { evidencePaperId: testPaperId } }); + await prisma.evidencePaper.delete({ where: { id: testPaperId } }); } + if (testDocId) await prisma.contentDocument.delete({ where: { id: testDocId } }); }); - it("includes tags from test data", async () => { - const tags = await listEvidenceTags(); - expect(tags).toContain("spacing"); - expect(tags).toContain("test-tag"); - }); -}); - -describe("buildResearchContext", () => { - it("returns formatted context string for matching concerns", async () => { - const context = await buildResearchContext(["spacing"]); - expect(context).toContain("Research-Based Scheduling Evidence"); - expect(context).toContain("Spacing improves retention"); - expect(context).toContain("[STRONG]"); - expect(context).toContain("Recommendation:"); + describe("queryEvidenceCards", () => { + it("returns every card matching any of the given tags, and only those", async () => { + const both = await queryEvidenceCards([TAG_A, TAG_B]); + expect(both.map((c) => c.claim).sort()).toEqual([MODERATE_CLAIM, STRONG_CLAIM, WEAK_CLAIM].sort()); + + const onlyB = await queryEvidenceCards([TAG_B]); + expect(onlyB.map((c) => c.claim)).toEqual([MODERATE_CLAIM]); + expect(onlyB[0].tags).toContain(TAG_B); + }); + + it("returns an empty array for a tag no card has", async () => { + expect(await queryEvidenceCards([MISSING_TAG])).toEqual([]); + }); + + it("returns an empty array for empty tags input", async () => { + expect(await queryEvidenceCards([])).toEqual([]); + }); + + it("sorts STRONG cards before MODERATE before WEAK", async () => { + const results = await queryEvidenceCards([TAG_A, TAG_B]); + const strong = results.findIndex((c) => c.claim === STRONG_CLAIM); + const moderate = results.findIndex((c) => c.claim === MODERATE_CLAIM); + const weak = results.findIndex((c) => c.claim === WEAK_CLAIM); + + // All three must be present before their order means anything. + expect(strong).not.toBe(-1); + expect(moderate).not.toBe(-1); + expect(weak).not.toBe(-1); + expect(strong).toBeLessThan(moderate); + expect(moderate).toBeLessThan(weak); + expect(results.map((c) => c.strength)).toEqual(["STRONG", "MODERATE", "WEAK"]); + }); + + it("filters by strength when specified", async () => { + const results = await queryEvidenceCards([TAG_A, TAG_B], { strength: "STRONG" }); + expect(results.map((c) => c.claim)).toEqual([STRONG_CLAIM]); + expect(results[0].strength).toBe("STRONG"); + }); + + it("respects the limit option, keeping the strongest card", async () => { + const results = await queryEvidenceCards([TAG_A, TAG_B], { limit: 1 }); + expect(results.map((c) => c.claim)).toEqual([STRONG_CLAIM]); + }); + + it("includes paper metadata in results", async () => { + const results = await queryEvidenceCards([TAG_A]); + const testCard = results.find((c) => c.claim === STRONG_CLAIM); + expect(testCard).toBeDefined(); + expect(testCard!.paper).toEqual({ + title: "Test Paper for Research Service", + authors: "Test Author", + year: 2024, + }); + }); }); - it("returns empty string when no cards match", async () => { - const context = await buildResearchContext(["nonexistent-tag-xyz"]); - expect(context).toBe(""); + describe("buildResearchContext", () => { + it("formats the matching cards, strongest first", async () => { + const context = await buildResearchContext([TAG_A]); + expect(context).toContain("Research-Based Scheduling Evidence"); + expect(context).toContain(STRONG_CLAIM); + expect(context).toContain(WEAK_CLAIM); + expect(context).not.toContain(MODERATE_CLAIM); + expect(context).toContain("[STRONG]"); + expect(context).toContain("Recommendation:"); + expect(context.indexOf(STRONG_CLAIM)).toBeLessThan(context.indexOf(WEAK_CLAIM)); + }); + + it("returns an empty string when no cards match", async () => { + expect(await buildResearchContext([MISSING_TAG])).toBe(""); + }); }); }); diff --git a/src/__tests__/integration/search-match.test.ts b/src/__tests__/integration/search-match.test.ts new file mode 100644 index 00000000..e8c98766 --- /dev/null +++ b/src/__tests__/integration/search-match.test.ts @@ -0,0 +1,103 @@ +/** + * Integration tests for full-text search match modes. + * + * match "all" needs every query word in one chunk, so a natural question + * whose answer is in the materials still found nothing ("Your materials + * don't cover this" when they did). match "any" finds it, and its floor + * keeps an off-topic question, or one that shares a single stray word, + * from turning up a citation. Requires a running PostgreSQL database: set + * DATABASE_URL to a test database before running. + */ +import { describe, it, expect, beforeAll, afterAll } from "vitest"; + +const hasDb = !!process.env.DATABASE_URL; + +let prisma: any; +let searchChunks: any; +let buildFeedbackQuery: any; + +const USER = "test_search_match_" + Date.now(); +const COURSE = "SEARCH_CS_" + Date.now(); + +const DOC_CONTENT = ` +Introduction to Loop Invariants + +A loop invariant is a condition that is true before and after each iteration of a loop. + +To prove a loop is correct, you must show three things: +1. Initialization: The invariant is true before the first iteration. +2. Maintenance: If the invariant is true before an iteration, it remains true after. +3. Termination: When the loop terminates, the invariant gives a useful property. + +Example: Binary Search +The loop invariant for binary search is that the target element, if present, must be between low and high. +`.trim(); + +describe.skipIf(!hasDb)("searchChunks match modes", () => { + beforeAll(async () => { + prisma = (await import("@/lib/db")).prisma; + const search = await import("@/lib/search"); + searchChunks = search.searchChunks; + buildFeedbackQuery = search.buildFeedbackQuery; + const content = await import("@/services/content"); + const upload = await content.uploadDocument( + USER, "COURSE", COURSE, undefined, + "loops.txt", "loops.txt", "text/plain", + Buffer.from(DOC_CONTENT), + ); + await content.processDocument(USER, upload.document_id); + }); + + afterAll(async () => { + if (!prisma) return; + await prisma.contentChunk.deleteMany({ where: { document: { userId: USER } } }); + await prisma.contentDocument.deleteMany({ where: { userId: USER } }); + await prisma.$disconnect(); + }); + + const search = (q: string, match?: "all" | "any") => + searchChunks({ userId: USER, q, namespace: "COURSE", courseName: COURSE, match }); + + it("finds the passage that answers a question even when it lacks some of the question's words", async () => { + // "guarantee" is nowhere in the file, so requiring every word misses. + const question = "What does a loop invariant guarantee when the loop terminates?"; + expect(await search(question, "all")).toEqual([]); + + const results = await search(question, "any"); + expect(results.length).toBeGreaterThan(0); + expect(results[0].doc_title).toBeTruthy(); + expect(results[0].snippet).toMatch(/<<\w+>>/); + }); + + it("finds sources for a feedback query built from a templated question", async () => { + const q = buildFeedbackQuery( + "From memory: explain Loop invariants in 3 to 5 bullets.", + "An invariant must hold before the first iteration and after every iteration", + "Loop invariants", + ); + expect(await search(q, "all")).toEqual([]); + expect((await search(q, "any")).length).toBeGreaterThan(0); + }); + + it("returns nothing for an off-topic question", async () => { + expect(await search("How do I bake sourdough bread at home?", "any")).toEqual([]); + expect(await search("quantum chromodynamics", "any")).toEqual([]); + }); + + it("does not cite a passage that shares one stray word with a longer question", async () => { + expect(await search("Which loop do Olympic runners run on the outdoor track?", "any")).toEqual([]); + }); + + it("returns nothing for a query of only stop words", async () => { + expect(await search("the and of", "any")).toEqual([]); + }); + + it("keeps every result a match-all search finds", async () => { + const all = await search("loop invariant", "all"); + const any = await search("loop invariant", "any"); + expect(all.length).toBeGreaterThan(0); + expect(any.map((r: { chunk_id: string }) => r.chunk_id)).toEqual( + expect.arrayContaining(all.map((r: { chunk_id: string }) => r.chunk_id)), + ); + }); +}); diff --git a/src/__tests__/lesson-primitives.test.tsx b/src/__tests__/lesson-primitives.test.tsx new file mode 100644 index 00000000..8d4df6be --- /dev/null +++ b/src/__tests__/lesson-primitives.test.tsx @@ -0,0 +1,88 @@ +import { renderToStaticMarkup } from "react-dom/server" +import { describe, expect, it } from "vitest" + +import { AnswerOption } from "@/components/lesson/answer-option" +import { ConfidencePicker } from "@/components/lesson/confidence-picker" +import { FeedbackSheet } from "@/components/lesson/feedback-sheet" +import { LessonButton } from "@/components/lesson/lesson-button" + +/** Server markup: the node test environment has no DOM, so tests read attributes from it. */ +function markup(element: React.ReactElement): string { + return renderToStaticMarkup(element) +} + +/** The opening tag of the first element whose attributes include `marker`. */ +function tagWith(html: string, marker: string): string { + const at = html.indexOf(marker) + expect(at, `no element with ${marker}`).toBeGreaterThan(-1) + return html.slice(html.lastIndexOf("<", at), html.indexOf(">", at) + 1) +} + +function attribute(tag: string, name: string): string | null { + return new RegExp(`\\s${name}="([^"]*)"`).exec(tag)?.[1] ?? null +} + +describe("FeedbackSheet", () => { + it("describes Continue with the note, so the correction is read on the way", () => { + const html = markup( + <FeedbackSheet tone="wrong" title="Incorrect" continueLabel="Next question" onContinue={() => {}}> + <p>Correct answer: A binary heap</p> + </FeedbackSheet> + ) + const button = tagWith(html, 'data-slot="lesson-button"') + const describedBy = attribute(button, "aria-describedby") + expect(describedBy).toBeTruthy() + const note = tagWith(html, `id="${describedBy}"`) + const noteText = html.slice(html.indexOf(note) + note.length, html.indexOf("</div>", html.indexOf(note))) + expect(noteText).toContain("Correct answer: A binary heap") + }) + + it("has no description without a note", () => { + const html = markup(<FeedbackSheet tone="correct" title="Correct" onContinue={() => {}} />) + expect(attribute(tagWith(html, 'data-slot="lesson-button"'), "aria-describedby")).toBeNull() + }) + + it("draws the secondary action before Continue in the DOM and on screen", () => { + const html = markup( + <FeedbackSheet + tone="wrong" + title="Incorrect" + onContinue={() => {}} + secondaryAction={<LessonButton variant="neutral">Log the error</LessonButton>} + /> + ) + expect(html.indexOf("Log the error")).toBeLessThan(html.indexOf("Continue")) + // flex-col-reverse would put Continue on top while Tab reaches it second + expect(html).not.toContain("flex-col-reverse") + }) +}) + +describe("selected state beyond colour", () => { + const option = ({ checked, hint }: { checked: boolean; hint?: string }) => + markup( + <AnswerOption name="q" value="0" checked={checked} hint={hint} onSelect={() => {}}> + A binary heap + </AnswerOption> + ) + + it("gives every answer option a marker that fills when selected", () => { + for (const hint of ["1", undefined]) { + const selected = option({ checked: true, hint }) + expect(attribute(tagWith(selected, 'data-slot="answer-option"'), "data-state")).toBe("selected") + // A radio dot on touch screens (and when hints are off) … + expect(selected).toContain('data-slot="answer-option-radio"') + expect(selected).toContain("group-data-[state=selected]/option:scale-100") + } + // … and the key hint chip, inverted when selected, on fine pointers + const hinted = tagWith(option({ checked: true, hint: "1" }), 'data-slot="answer-option-hint"') + expect(hinted).toContain("group-data-[state=selected]/option:bg-lesson-on-selected") + }) + + it("marks the chosen confidence with a check, and only that one", () => { + const html = markup(<ConfidencePicker value={5} onChange={() => {}} hints={["Q", "W", "E"]} />) + expect(html.match(/data-check=""/g)).toHaveLength(1) + const sure = html.slice(html.lastIndexOf('data-state="selected"')) + expect(sure.indexOf("data-check")).toBeLessThan(sure.indexOf("Sure")) + expect(markup(<ConfidencePicker value={null} onChange={() => {}} />)).not.toContain("data-check") + }) +}) diff --git a/src/__tests__/log-redaction.test.ts b/src/__tests__/log-redaction.test.ts new file mode 100644 index 00000000..6a585b7b --- /dev/null +++ b/src/__tests__/log-redaction.test.ts @@ -0,0 +1,96 @@ +/** + * Token redaction in logs: sanitizeForLog's patterns, and the logger running + * every string it writes through it. + */ +import { describe, it, expect, vi, beforeAll, afterAll, afterEach } from "vitest"; +import { sanitizeForLog } from "@/lib/crypto/redact"; +import { logger } from "@/lib/logger"; + +const TEST_KEY_HEX = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; + +describe("sanitizeForLog", () => { + let encryptToken: (plain: string) => string; + + beforeAll(async () => { + vi.stubEnv("TOKEN_ENC_KEY", TEST_KEY_HEX); + encryptToken = (await import("@/lib/crypto/token-vault")).encryptToken; + }); + + afterAll(() => { + vi.unstubAllEnvs(); + }); + + it("redacts OAuth access tokens", () => { + const result = sanitizeForLog("token: ya29.A0AfH6SMBx_long_access_token_here"); + expect(result).not.toContain("A0AfH6SMBx"); + expect(result).toContain("ya29.[REDACTED]"); + }); + + it("redacts refresh tokens", () => { + const result = sanitizeForLog("refresh: 1//0eXyz_long_refresh_token"); + expect(result).not.toContain("0eXyz"); + expect(result).toContain("1//[REDACTED]"); + }); + + it("redacts encrypted tokens", () => { + for (const plain of ["secret", "ya29.a-much-longer-access-token-value-0123456789"]) { + const enc = encryptToken(plain); + const result = sanitizeForLog(`encrypted token: ${enc}`); + expect(result).not.toContain(enc); + expect(result).toContain("[ENCRYPTED_REDACTED]"); + } + }); + + it("redacts bearer headers, OAuth fields and JWTs", () => { + expect(sanitizeForLog("Authorization: Bearer abc.DEF-123_xyz")).toBe("Authorization: Bearer [REDACTED]"); + expect(sanitizeForLog("POST /token?client_secret=s3cr3t&grant_type=refresh_token")).toBe( + "POST /token?client_secret=[REDACTED]&grant_type=refresh_token", + ); + expect(sanitizeForLog('{"access_token": "opaque-value", "expires_in": 3599}')).toBe( + '{"access_token": "[REDACTED]", "expires_in": 3599}', + ); + expect(sanitizeForLog("cookie eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1MSJ9.c2lnbmF0dXJl end")).toBe( + "cookie [JWT_REDACTED] end", + ); + }); + + it("keeps ids, paths, URLs and digests readable", () => { + for (const safe of [ + "user_id=abc123", + "/api/plans/cmg5x2abc0001qwertyzxcv1234/items/cmg5x2abc0002qwertyzxcv5678/status", + "GET https://www.googleapis.com/calendar/v3/calendars/primary/events failed with 503", + "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08", + "Missing required parameter: refresh_token", + "5eed0000-de70-4000-8000-000000000001", + ]) { + expect(sanitizeForLog(safe)).toBe(safe); + } + }); +}); + +describe("logger", () => { + afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllEnvs(); + }); + + it("redacts tokens in every string it writes, nested ones included", () => { + vi.stubEnv("LOG_LEVEL", "debug"); + const out = vi.spyOn(console, "log").mockImplementation(() => {}); + const err = vi.spyOn(console, "error").mockImplementation(() => {}); + + logger.warn("google.retry", { error: "401 for ya29.leaked-access-token", detail: { body: ["1//leaked-refresh"] } }); + logger.error("google.publish.item", { error: "Bearer leaked.token.value rejected", plan_item_id: "item_1" }); + + const lines = [...out.mock.calls, ...err.mock.calls].map((call) => String(call[0])); + const written = lines.join("\n"); + expect(written).not.toContain("leaked"); + expect(JSON.parse(lines[0])).toMatchObject({ + level: "warn", + event: "google.retry", + error: "401 for ya29.[REDACTED]", + detail: { body: ["1//[REDACTED]"] }, + }); + expect(JSON.parse(lines[1])).toMatchObject({ event: "google.publish.item", plan_item_id: "item_1" }); + }); +}); diff --git a/src/__tests__/logger.test.ts b/src/__tests__/logger.test.ts index 5ae5e243..b95d3db5 100644 --- a/src/__tests__/logger.test.ts +++ b/src/__tests__/logger.test.ts @@ -73,4 +73,14 @@ describe("logger", () => { const infoLogged = JSON.parse((console.log as ReturnType<typeof vi.fn>).mock.calls[0][0]); expect(infoLogged.event).toBe("test.garbage.info"); }); + + it("stays silent under vitest when LOG_LEVEL is unset", async () => { + delete process.env.LOG_LEVEL; + const { logger } = await import("@/lib/logger"); + logger.error("test.silent.error"); + logger.info("test.silent.info"); + + expect(console.error).not.toHaveBeenCalled(); + expect(console.log).not.toHaveBeenCalled(); + }); }); diff --git a/src/__tests__/materials-requests.test.ts b/src/__tests__/materials-requests.test.ts new file mode 100644 index 00000000..e9a9d51c --- /dev/null +++ b/src/__tests__/materials-requests.test.ts @@ -0,0 +1,139 @@ +import { afterEach, describe, it, expect, vi } from "vitest"; +import { anySignal, processUntilSettled, sleep, unreadableNote } from "@/components/materials/requests"; +import { busyDocumentIds, dedupeNoteFor, type UploadEntry } from "@/components/materials/use-material-uploads"; +import { lastCalendarAction } from "@/components/plan/calendar-types"; + +afterEach(() => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + vi.useRealTimers(); +}); + +describe("anySignal", () => { + it("aborts with the reason of whichever signal aborts first", () => { + const a = new AbortController(); + const b = new AbortController(); + const signal = anySignal(a.signal, b.signal); + expect(signal.aborted).toBe(false); + b.abort("timeout"); + expect(signal.aborted).toBe(true); + expect(signal.reason).toBe("timeout"); + }); + + it("works where AbortSignal.any is missing (Safari before 17.4, Firefox before 124)", () => { + const original = AbortSignal.any; + // @ts-expect-error simulate an older browser + AbortSignal.any = undefined; + try { + const a = new AbortController(); + const b = new AbortController(); + const signal = anySignal(a.signal, b.signal); + expect(signal.aborted).toBe(false); + a.abort("left"); + expect(signal.aborted).toBe(true); + expect(signal.reason).toBe("left"); + + const done = new AbortController(); + done.abort("already"); + expect(anySignal(new AbortController().signal, done.signal).reason).toBe("already"); + } finally { + AbortSignal.any = original; + } + }); +}); + +describe("sleep", () => { + it("rejects as soon as the signal aborts", async () => { + const controller = new AbortController(); + const waiting = sleep(60_000, controller.signal); + controller.abort(); + await expect(waiting).rejects.toMatchObject({ name: "AbortError" }); + }); +}); + +function json(status: number, body: unknown, headers: Record<string, string> = {}) { + return new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json", ...headers } }); +} + +describe("processUntilSettled", () => { + it("tells a file that is too long apart from one that can't be read", async () => { + vi.stubGlobal("fetch", vi.fn().mockResolvedValueOnce(json(200, { status: "FAILED", reason: "too_long" }))); + const tooLong = await processUntilSettled("doc-1", new AbortController().signal); + expect(tooLong).toBe("TOO_LONG"); + expect(unreadableNote("textbook.pdf", "TOO_LONG")).toBe( + "textbook.pdf is too long to read. Split it into smaller files, then upload those.", + ); + + vi.stubGlobal("fetch", vi.fn().mockResolvedValueOnce(json(200, { status: "FAILED", reason: "unreadable" }))); + const failed = await processUntilSettled("doc-2", new AbortController().signal); + expect(failed).toBe("FAILED"); + expect(unreadableNote("scan.pdf", "FAILED")).toBe("Couldn't read scan.pdf. Check that it has selectable text, then retry."); + }); + + it("checks back while another request is processing the file, without failing it", async () => { + vi.useFakeTimers(); + const fetchMock = vi + .fn() + .mockResolvedValueOnce(json(200, { status: "PROCESSING" })) + .mockResolvedValueOnce(json(200, { status: "PROCESSED" })); + vi.stubGlobal("fetch", fetchMock); + const outcome = processUntilSettled("doc-1", new AbortController().signal); + await vi.advanceTimersByTimeAsync(5_000); + await expect(outcome).resolves.toBe("PROCESSED"); + expect(fetchMock).toHaveBeenCalledTimes(2); + }); + + it("waits out a 429 and says so", async () => { + vi.useFakeTimers(); + vi.stubGlobal( + "fetch", + vi + .fn() + .mockResolvedValueOnce(json(429, { error: "Too many files at once." }, { "Retry-After": "2" })) + .mockResolvedValueOnce(json(200, { status: "FAILED" })) + ); + const onWait = vi.fn(); + const onResume = vi.fn(); + const outcome = processUntilSettled("doc-1", new AbortController().signal, { onWait, onResume }); + await vi.advanceTimersByTimeAsync(2_000); + await expect(outcome).resolves.toBe("FAILED"); + expect(onWait).toHaveBeenCalledWith(2); + expect(onResume).toHaveBeenCalledTimes(1); + }); +}); + +describe("upload rows", () => { + const entry = (phase: UploadEntry["phase"], documentId?: string): UploadEntry => ({ + key: `k-${phase}-${documentId}`, + name: "lecture.pdf", + phase, + courseName: "CS 2110", + documentId, + }); + + it("lists the files still uploading or processing, so their materials rows offer no second run", () => { + const ids = busyDocumentIds([ + entry("processing", "a"), + entry("waiting", "b"), + entry("ready", "c"), + entry("failed", "d"), + entry("queued"), + ]); + expect([...ids].sort()).toEqual(["a", "b"]); + }); + + it("words the duplicate note by where the file already is", () => { + expect(dedupeNoteFor("AEM 2210", "CS 2110")).toBe("Already in your AEM 2210 materials, so it stays there."); + expect(dedupeNoteFor("cs 2110", "CS 2110")).toBe("Already in your materials."); + expect(dedupeNoteFor(null, "CS 2110")).toBe("Already in your materials."); + }); +}); + +describe("lastCalendarAction", () => { + it("reads an add when both stamps match and a removal when only the sync moved", () => { + const at = "2026-10-15T20:00:00.000Z"; + expect(lastCalendarAction({ published_at: at, last_synced_at: at })).toBe("add"); + expect(lastCalendarAction({ published_at: at, last_synced_at: "2026-10-15T20:05:00.000Z" })).toBe("remove"); + expect(lastCalendarAction({ published_at: null, last_synced_at: null })).toBe("add"); + }); +}); diff --git a/src/__tests__/materials-rules.test.ts b/src/__tests__/materials-rules.test.ts new file mode 100644 index 00000000..22283706 --- /dev/null +++ b/src/__tests__/materials-rules.test.ts @@ -0,0 +1,67 @@ +import { describe, it, expect } from "vitest"; +import { FILE_RULE, MAX_FILE_BYTES, fileKind, fileProblem } from "@/components/materials/file-rules"; +import { errorCode, errorMessage, fieldIssues } from "@/components/plan/api-errors"; +import { ApiError } from "@/lib/client-api"; + +describe("fileProblem", () => { + it("accepts PDF, text and Markdown up to 10 MB, by type or extension", () => { + expect(fileProblem({ name: "lecture.pdf", size: 1000, type: "application/pdf" })).toBeNull(); + expect(fileProblem({ name: "notes.md", size: 1000, type: "" })).toBeNull(); + expect(fileProblem({ name: "NOTES.TXT", size: 1000, type: "" })).toBeNull(); + expect(fileProblem({ name: "big.pdf", size: MAX_FILE_BYTES, type: "application/pdf" })).toBeNull(); + }); + + it("names the rule for other types and larger files", () => { + expect(fileProblem({ name: "slides.pptx", size: 1000, type: "application/vnd.ms-powerpoint" })).toBe(FILE_RULE); + expect(fileProblem({ name: "big.pdf", size: MAX_FILE_BYTES + 1, type: "application/pdf" })).toBe(FILE_RULE); + }); + + it("refuses an empty file", () => { + expect(fileProblem({ name: "empty.md", size: 0, type: "text/markdown" })).toMatch(/empty/); + }); + + it("names the kind of file", () => { + expect(fileKind("a.pdf")).toBe("PDF"); + expect(fileKind("a.markdown")).toBe("Markdown"); + expect(fileKind("a.txt", "text/plain")).toBe("Text"); + }); +}); + +describe("api errors", () => { + it("never shows a raw code, preferring the server's sentence", () => { + const publish = new ApiError("GOOGLE_RECONNECT_REQUIRED", 409, { + error: "GOOGLE_RECONNECT_REQUIRED", + code: "GOOGLE_RECONNECT_REQUIRED", + message: "Google Calendar needs you to sign in again.", + }); + expect(errorMessage(publish, "Not added.")).toBe("Google Calendar needs you to sign in again."); + expect(errorCode(publish)).toBe("GOOGLE_RECONNECT_REQUIRED"); + + const bare = new ApiError("not_found", 404, { error: "not_found" }); + expect(errorMessage(bare, "Plan not deleted.")).toBe("Plan not deleted."); + expect(errorCode(bare)).toBe("not_found"); + }); + + it("chooses copy by status when the server sent none", () => { + expect(errorMessage(new ApiError("Unauthorized", 401, { error: "Unauthorized" }), "x")).toBe( + "Your sign-in expired. Sign in again." + ); + expect(errorMessage(new ApiError("Request failed", 503, null), "Plan not created.")).toBe( + "Plan not created. Retry in a minute." + ); + expect(errorMessage(new TypeError("Failed to fetch"), "Plan not created.")).toBe( + "Plan not created. Check your connection and retry." + ); + }); + + it("maps validation issues to fields by their first path segment", () => { + const error = new ApiError("Check the highlighted fields.", 400, { + issues: [ + { path: ["availability"], message: "Choose an end time after the start time." }, + { path: ["availability", 2, "end"], message: "Choose an end time." }, + { path: [], message: "ignored" }, + ], + }); + expect(fieldIssues(error)).toEqual({ availability: "Choose an end time after the start time." }); + }); +}); diff --git a/src/__tests__/next-config-headers.test.ts b/src/__tests__/next-config-headers.test.ts new file mode 100644 index 00000000..29157449 --- /dev/null +++ b/src/__tests__/next-config-headers.test.ts @@ -0,0 +1,70 @@ +/** + * Unit tests for the static security headers in next.config.js, mainly the + * baseline Content-Security-Policy every response gets. + */ +import { createRequire } from "node:module"; +import type { NextConfig } from "next"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +const require = createRequire(import.meta.url); +const CONFIG_PATH = require.resolve("../../next.config.js"); + +/** Loads next.config.js fresh, since it reads NODE_ENV when it is required. */ +async function loadHeaders(nodeEnv: string): Promise<Map<string, string>> { + vi.stubEnv("NODE_ENV", nodeEnv); + delete require.cache[CONFIG_PATH]; + const config = require(CONFIG_PATH) as NextConfig; + const rules = (await config.headers?.()) ?? []; + const all = rules.find((rule) => rule.source === "/:path*"); + return new Map((all?.headers ?? []).map((h) => [h.key, h.value])); +} + +/** Splits a policy into directive name and its sources. */ +async function loadCsp(nodeEnv: string): Promise<Map<string, string[]>> { + const policy = (await loadHeaders(nodeEnv)).get("Content-Security-Policy") ?? ""; + return new Map( + policy.split(";").map((directive) => { + const [name, ...sources] = directive.trim().split(/\s+/); + return [name, sources]; + }), + ); +} + +afterEach(() => { + vi.unstubAllEnvs(); + delete require.cache[CONFIG_PATH]; +}); + +describe("next.config.js Content-Security-Policy", () => { + it("keeps every connection same-origin", async () => { + const csp = await loadCsp("production"); + expect(csp.get("connect-src")).toEqual(["'self'"]); + }); + + it("names no other origin in any directive", async () => { + const csp = await loadCsp("production"); + const sources = [...csp.values()].flat(); + expect(sources.filter((s) => /^(https?:|wss?:|\*)/.test(s) || s.includes("."))).toEqual([]); + }); + + it("allows eval only under next dev", async () => { + expect((await loadCsp("production")).get("script-src")).not.toContain("'unsafe-eval'"); + expect((await loadCsp("development")).get("script-src")).toContain("'unsafe-eval'"); + }); + + it("blocks plugins, framing, base rewrites and off-site form posts", async () => { + const csp = await loadCsp("production"); + expect(csp.get("object-src")).toEqual(["'none'"]); + expect(csp.get("frame-ancestors")).toEqual(["'none'"]); + expect(csp.get("base-uri")).toEqual(["'self'"]); + expect(csp.get("form-action")).toEqual(["'self'"]); + }); +}); + +describe("next.config.js security headers", () => { + it("sends the clickjacking and sniffing headers", async () => { + const headers = await loadHeaders("production"); + expect(headers.get("X-Frame-Options")).toBe("DENY"); + expect(headers.get("X-Content-Type-Options")).toBe("nosniff"); + }); +}); diff --git a/src/__tests__/objective-keys.test.ts b/src/__tests__/objective-keys.test.ts new file mode 100644 index 00000000..3c9c1514 --- /dev/null +++ b/src/__tests__/objective-keys.test.ts @@ -0,0 +1,47 @@ +/** + * Topic keys: one slug rule and one way back to a readable title, shared by + * the plan generator, Home and Progress, sessions and recommendations. + */ +import { describe, expect, it } from "vitest"; + +import { humanizeObjectiveKey, slugifyObjectiveTitle } from "@/lib/objective-keys"; +import { slugifyObjectiveTitle as planGeneratorSlug } from "@/lib/plan-generator"; + +describe("slugifyObjectiveTitle", () => { + it("derives keys exactly like the plan generator", () => { + const long = "A very long objective title that goes well past the sixty character limit for keys"; + for (const title of ["CSS specificity", "Responsive images and srcset", "ref and reactive", " Big-O! ", "!!!", long]) { + expect(slugifyObjectiveTitle(title)).toBe(planGeneratorSlug(title)); + } + }); + + it("lowercases, joins words with underscores and falls back to a fixed key", () => { + expect(slugifyObjectiveTitle("Photosynthesis: Light Reactions!")).toBe("photosynthesis_light_reactions"); + expect(slugifyObjectiveTitle(" --Weird spacing-- ")).toBe("weird_spacing"); + expect(slugifyObjectiveTitle("!!!")).toBe("objective"); + }); +}); + +describe("humanizeObjectiveKey", () => { + it("reads a slug back in sentence case", () => { + expect(humanizeObjectiveKey("photosynthesis_light_reactions")).toBe("Photosynthesis light reactions"); + expect(humanizeObjectiveKey("grid_template_areas")).toBe("Grid template areas"); + expect(humanizeObjectiveKey("big-o")).toBe("Big o"); + }); + + it("splits camelCase and keeps words written in capitals", () => { + expect(humanizeObjectiveKey("bigO-notation")).toBe("Big O notation"); + expect(humanizeObjectiveKey("CSS_specificity")).toBe("CSS specificity"); + expect(humanizeObjectiveKey("HTMLParser_basics")).toBe("HTML parser basics"); + expect(humanizeObjectiveKey("Photosynthesis_Light_Reactions")).toBe("Photosynthesis light reactions"); + }); + + it("names a key with no words", () => { + expect(humanizeObjectiveKey("__")).toBe("Untitled topic"); + expect(humanizeObjectiveKey("")).toBe("Untitled topic"); + }); + + it("round-trips a slug from a title", () => { + expect(humanizeObjectiveKey(slugifyObjectiveTitle("Dynamic programming"))).toBe("Dynamic programming"); + }); +}); diff --git a/src/__tests__/openai-provider.test.ts b/src/__tests__/openai-provider.test.ts index 696aa13b..32c7db26 100644 --- a/src/__tests__/openai-provider.test.ts +++ b/src/__tests__/openai-provider.test.ts @@ -5,6 +5,7 @@ */ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; import { OpenAIProvider } from "@/lib/ai/providers/openai"; +import { ProviderRequestError } from "@/lib/ai/provider"; import { logger } from "@/lib/logger"; // Mock the API key @@ -83,6 +84,23 @@ describe("OpenAIProvider", () => { ).rejects.toThrow("OpenAI API error 429"); }); + it("types a rejected request apart from outages", async () => { + vi.spyOn(globalThis, "fetch") + .mockResolvedValueOnce(new Response("context_length_exceeded", { status: 400 })) + .mockResolvedValueOnce(new Response("Rate limited", { status: 429 })) + .mockResolvedValueOnce(new Response("Server error", { status: 500 })); + + const provider = new OpenAIProvider(); + const tooLong = await provider.completeJson("system", "user", "gpt-4o-mini").catch((e: unknown) => e); + expect(tooLong).toBeInstanceOf(ProviderRequestError); + expect((tooLong as ProviderRequestError).status).toBe(400); + + const limited = await provider.completeJson("system", "user", "gpt-4o-mini").catch((e: unknown) => e); + expect(limited).not.toBeInstanceOf(ProviderRequestError); + const down = await provider.embed(["text"], "text-embedding-3-small").catch((e: unknown) => e); + expect(down).not.toBeInstanceOf(ProviderRequestError); + }); + it("throws on invalid JSON response", async () => { const mockResponse = { choices: [{ message: { content: "not json" } }], diff --git a/src/__tests__/plan-generator.test.ts b/src/__tests__/plan-generator.test.ts index 1bebbb93..8bd1150c 100644 --- a/src/__tests__/plan-generator.test.ts +++ b/src/__tests__/plan-generator.test.ts @@ -4,6 +4,10 @@ import { PlanBlock, slugifyObjectiveTitle, buildObjectiveIdMap, + isCalendarDay, + layoutBlocks, + nextQuarterHour, + rollBlocksForward, } from "@/lib/plan-generator"; // --------------------------------------------------------------------------- @@ -310,3 +314,153 @@ describe("plan-generator: edge cases", () => { expect(blocks.length).toBeGreaterThan(0); }); }); + +// --------------------------------------------------------------------------- +// Laying blocks out in time +// --------------------------------------------------------------------------- + +describe("nextQuarterHour", () => { + it("rounds up to the next quarter hour and keeps exact ones", () => { + expect(new Date(nextQuarterHour(Date.parse("2026-10-15T20:01:00Z"))).toISOString()).toBe("2026-10-15T20:15:00.000Z"); + expect(new Date(nextQuarterHour(Date.parse("2026-10-15T20:15:00Z"))).toISOString()).toBe("2026-10-15T20:15:00.000Z"); + }); +}); + +describe("layoutBlocks", () => { + const HOUR = 3_600_000; + const DAY0 = Date.parse("2026-10-15T13:00:00Z"); // 9:00 AM New York + // 09:00 to 17:00 every day + const window = (day: number) => ({ start: DAY0 + day * 24 * HOUR, end: DAY0 + day * 24 * HOUR + 8 * HOUR }); + const block = (dayIndex: number, plannedMinutes: number) => ({ dayIndex, plannedMinutes }); + // Day 0 always opens with a 20 and a 70 minute block + const blocks = [block(0, 20), block(0, 70), block(1, 30), block(1, 60)]; + const iso = (ms: number) => new Date(ms).toISOString(); + + it("lays a morning plan end to end from the window start", () => { + const placed = layoutBlocks(blocks, { window, earliest: DAY0 - HOUR, dailyCapMinutes: 180 }); + expect(placed.map((p) => p && [p.dayIndex, iso(p.start)])).toEqual([ + [0, "2026-10-15T13:00:00.000Z"], + [0, "2026-10-15T13:20:00.000Z"], + [1, "2026-10-16T13:00:00.000Z"], + [1, "2026-10-16T13:30:00.000Z"], + ]); + }); + + it("starts today's blocks no earlier than now in the afternoon", () => { + const earliest = nextQuarterHour(Date.parse("2026-10-15T18:05:00Z")); // 2:05 PM + const placed = layoutBlocks(blocks, { window, earliest, dailyCapMinutes: 180 }); + expect(iso(placed[0]!.start)).toBe("2026-10-15T18:15:00.000Z"); + expect(iso(placed[1]!.start)).toBe("2026-10-15T18:35:00.000Z"); + }); + + it("moves today's blocks to tomorrow, after tomorrow's own, when the plan is made in the evening", () => { + const earliest = nextQuarterHour(Date.parse("2026-10-16T00:00:00Z")); // 8:00 PM + const placed = layoutBlocks(blocks, { window, earliest, dailyCapMinutes: 180 }); + for (const p of placed) expect(p!.start).toBeGreaterThanOrEqual(earliest); + expect(placed.map((p) => p && [p.dayIndex, iso(p.start)])).toEqual([ + [1, "2026-10-16T14:30:00.000Z"], + [1, "2026-10-16T14:50:00.000Z"], + [1, "2026-10-16T13:00:00.000Z"], + [1, "2026-10-16T13:30:00.000Z"], + ]); + }); + + it("goes past a full day to the next one with room, and drops what fits nowhere", () => { + const earliest = Date.parse("2026-10-16T00:00:00Z"); + // Day 1 is already at its 90 minute cap; day 2 has room for one more block + const placed = layoutBlocks([block(0, 20), block(0, 70), block(1, 90), block(2, 60)], { + window, + earliest, + dailyCapMinutes: 90, + lastDayIndex: 2, + }); + expect(placed[0]).toMatchObject({ dayIndex: 2, start: Date.parse("2026-10-17T14:00:00Z") }); + expect(placed[1]).toBeNull(); + }); + + it("never overlaps two blocks on one day", () => { + const earliest = Date.parse("2026-10-15T20:30:00Z"); // 4:30 PM: the 20 fits today, the 70 doesn't + const placed = layoutBlocks(blocks, { window, earliest, dailyCapMinutes: 180 }); + expect(placed[0]!.dayIndex).toBe(0); + expect(placed[1]!.dayIndex).toBe(1); + const day1 = placed.filter((p) => p!.dayIndex === 1).sort((a, b) => a!.start - b!.start); + for (let i = 1; i < day1.length; i++) expect(day1[i]!.start).toBeGreaterThanOrEqual(day1[i - 1]!.end); + }); +}); + +describe("rollBlocksForward", () => { + const HOUR = 3_600_000; + const DAY0 = Date.parse("2026-10-15T13:00:00Z"); + type Block = { id: string; dayIndex: number; plannedMinutes: number }; + const block = (id: string, dayIndex: number, plannedMinutes: number): Block => ({ id, dayIndex, plannedMinutes }); + + /** + * Each day has `free[day]` minutes of free time from 9:00, filled first come + * first served (Google Calendar free time, busy events already taken out). + * Records which blocks each day was asked to fit. + */ + function fitter(free: Record<number, number>) { + const asked: Record<number, string[]> = {}; + const fitDay = (day: number, dayBlocks: readonly Block[]) => { + asked[day] = dayBlocks.map((b) => b.id); + let cursor = DAY0 + day * 24 * HOUR; + let left = free[day] ?? 0; + return dayBlocks.map((b) => { + if (b.plannedMinutes > left) return null; + const slot = { start: cursor, end: cursor + b.plannedMinutes * 60_000 }; + cursor = slot.end; + left -= b.plannedMinutes; + return slot; + }); + }; + return { fitDay, asked }; + } + + it("moves a block from any busy day to the next day with room instead of dropping it", () => { + // Day 3 is fully booked; days 0 to 2 and 4 have room + const { fitDay, asked } = fitter({ 0: 180, 1: 180, 2: 180, 3: 0, 4: 180 }); + const blocks = [block("a", 0, 50), block("b", 3, 50), block("c", 4, 50)]; + const placed = rollBlocksForward(blocks, { lastDayIndex: 6, dailyCapMinutes: 180, fitDay }); + expect(placed.map((p) => p?.dayIndex)).toEqual([0, 4, 4]); + // Day 4's own block goes first; the one that rolled follows it + expect(asked[4]).toEqual(["c", "b"]); + expect(placed[1]!.start).toBe(placed[2]!.end); + }); + + it("keeps rolling past full days within the daily cap", () => { + // Day 1 has free time but is already at its 90 minute cap + const { fitDay } = fitter({ 0: 0, 1: 300, 2: 300 }); + const blocks = [block("a", 0, 50), block("b", 1, 90)]; + const placed = rollBlocksForward(blocks, { lastDayIndex: 6, dailyCapMinutes: 90, fitDay }); + expect(placed.map((p) => p?.dayIndex)).toEqual([2, 1]); + }); + + it("leaves out what fits nowhere up to the last day", () => { + const { fitDay, asked } = fitter({ 0: 30, 1: 30, 2: 30 }); + const blocks = [block("a", 0, 50), block("b", 1, 20)]; + const placed = rollBlocksForward(blocks, { lastDayIndex: 2, dailyCapMinutes: 180, fitDay }); + expect(placed[0]).toBeNull(); + expect(placed[1]).toMatchObject({ dayIndex: 1 }); + // Never asks about a day after the last one (the exam day) + expect(Object.keys(asked)).toEqual(["0", "1", "2"]); + }); + + it("tries the earliest rolled block first", () => { + const { fitDay, asked } = fitter({ 0: 0, 1: 0, 2: 60 }); + const blocks = [block("a", 0, 50), block("b", 1, 50)]; + const placed = rollBlocksForward(blocks, { lastDayIndex: 2, dailyCapMinutes: 180, fitDay }); + expect(asked[2]).toEqual(["a", "b"]); + expect(placed.map((p) => p?.dayIndex ?? null)).toEqual([2, null]); + }); +}); + +describe("isCalendarDay", () => { + it("accepts real days only", () => { + expect(isCalendarDay("2026-10-15")).toBe(true); + expect(isCalendarDay("2028-02-29")).toBe(true); + expect(isCalendarDay("2026-02-31")).toBe(false); + expect(isCalendarDay("2026-13-01")).toBe(false); + expect(isCalendarDay("2026-00-10")).toBe(false); + expect(isCalendarDay("10/15/2026")).toBe(false); + }); +}); diff --git a/src/__tests__/plan-model.test.ts b/src/__tests__/plan-model.test.ts new file mode 100644 index 00000000..76925cb3 --- /dev/null +++ b/src/__tests__/plan-model.test.ts @@ -0,0 +1,187 @@ +import { describe, it, expect } from "vitest"; +import { + buildAgenda, + canReschedule, + examCountdown, + examRelative, + formatDayKey, + keyOf, + modeLabel, + previewSentence, + rescheduleToast, + samePlanTarget, + sortPlans, +} from "@/components/plan/plan-model"; +import type { PlanViewItem } from "@/services/plan"; + +const NY = "America/New_York"; +const NOW = new Date("2026-10-15T20:00:00Z"); // Thu Oct 15, 4:00 PM New York + +function item(id: string, start: string, minutes: number, state: PlanViewItem["state"]): PlanViewItem { + const startMs = Date.parse(start); + return { + id, + session_id: `s-${id}`, + start_time: new Date(startMs).toISOString(), + end_time: new Date(startMs + minutes * 60_000).toISOString(), + state, + status: "SCHEDULED", + locked: false, + mode: "RETRIEVAL", + topics: [], + planned_minutes: minutes, + original_start_time: null, + }; +} + +describe("buildAgenda", () => { + it("groups by the day in the zone and places the exam day in date order", () => { + const agenda = buildAgenda( + { + exam_date: "2026-10-18", + items: [ + // 11:30 PM New York on the 16th is the 17th in UTC: it belongs to the 16th + item("late", "2026-10-17T03:30:00Z", 30, "scheduled"), + item("after", "2026-10-20T20:00:00Z", 30, "scheduled"), + item("today", "2026-10-15T22:00:00Z", 30, "scheduled"), + ], + }, + { timeZone: NY, now: NOW } + ); + expect(agenda.days.map((d) => d.key)).toEqual(["2026-10-15", "2026-10-16", "2026-10-18", "2026-10-20"]); + const exam = agenda.days.find((d) => d.isExamDay)!; + expect(exam.sessions).toHaveLength(0); + expect(agenda.days[0].isToday).toBe(true); + expect(agenda.days[0].sessions[0].display).toBe("today"); + expect(agenda.days[3].sessions[0].afterExam).toBe(true); + expect(agenda.days[1].sessions[0].afterExam).toBe(false); + }); + + it("folds only the leading run of finished past days", () => { + const agenda = buildAgenda( + { + exam_date: "2026-10-22", + items: [ + item("a", "2026-10-10T20:00:00Z", 30, "done"), + item("b", "2026-10-11T20:00:00Z", 30, "skipped"), + item("c", "2026-10-12T20:00:00Z", 30, "missed"), + item("d", "2026-10-13T20:00:00Z", 30, "done"), + item("e", "2026-10-16T20:00:00Z", 30, "scheduled"), + ], + }, + { timeZone: NY, now: NOW } + ); + expect(agenda.earlier.map((d) => d.key)).toEqual(["2026-10-10", "2026-10-11"]); + expect(agenda.days.map((d) => d.key)).toEqual(["2026-10-12", "2026-10-13", "2026-10-16", "2026-10-22"]); + }); + + it("never folds the exam day", () => { + const agenda = buildAgenda( + { exam_date: "2026-10-12", items: [item("a", "2026-10-10T20:00:00Z", 30, "done")] }, + { timeZone: NY, now: NOW } + ); + expect(agenda.earlier.map((d) => d.key)).toEqual(["2026-10-10"]); + expect(agenda.days.map((d) => d.key)).toEqual(["2026-10-12"]); + }); +}); + +describe("sortPlans", () => { + it("lists upcoming exams soonest first, then past exams newest first", () => { + const plans = [ + { id: "far", exam_date: "2026-12-14", created_at: "2026-10-01T00:00:00Z" }, + { id: "past-old", exam_date: "2026-09-01", created_at: "2026-08-01T00:00:00Z" }, + { id: "today", exam_date: "2026-10-15", created_at: "2026-10-01T00:00:00Z" }, + { id: "past-new", exam_date: "2026-10-10", created_at: "2026-09-01T00:00:00Z" }, + { id: "soon", exam_date: "2026-10-22", created_at: "2026-10-01T00:00:00Z" }, + ]; + expect(sortPlans(plans, { timeZone: NY, now: NOW }).map((p) => p.id)).toEqual([ + "today", + "soon", + "far", + "past-new", + "past-old", + ]); + }); +}); + +describe("plan helpers", () => { + it("matches a replace target on course and exam, ignoring case and spacing", () => { + const plan = { course_name: "INFO 1300", exam_name: "Prelim 2" }; + expect(samePlanTarget(plan, { course_name: " info 1300 ", exam_name: "prelim 2" })).toBe(true); + expect(samePlanTarget(plan, { course_name: "INFO 1300", exam_name: "Final" })).toBe(false); + expect(samePlanTarget(plan, { course_name: "INFO 4340", exam_name: "Prelim 2" })).toBe(false); + }); + + it("offers rescheduling only before the exam and only with sessions to move", () => { + const counts = { total: 3, done: 1, in_progress: 0, missed: 1, scheduled: 1, skipped: 0 }; + expect(canReschedule({ exam_date: "2026-10-22", counts }, NY, NOW)).toBe(true); + expect(canReschedule({ exam_date: "2026-10-15", counts }, NY, NOW)).toBe(false); + expect( + canReschedule({ exam_date: "2026-10-22", counts: { ...counts, missed: 0, scheduled: 0 } }, NY, NOW) + ).toBe(false); + }); + + it("formats calendar-day keys the same in every zone", () => { + expect(formatDayKey("2026-10-22")).toBe("Thu, Oct 22"); + expect(examCountdown("Prelim 2", "2026-10-22", "2026-10-15")).toBe("Prelim 2 is in 7 days"); + expect(examCountdown("Prelim 2", "2026-10-16", "2026-10-15")).toBe("Prelim 2 is tomorrow"); + expect(examRelative("2026-10-22", "2026-10-15")).toBe("in 7 days"); + expect(examRelative("2026-10-13", "2026-10-15")).toBe("2 days ago"); + expect(keyOf(new Date("2026-10-16T03:30:00Z"), NY)).toBe("2026-10-15"); + }); + + it("names modes in sentence case", () => { + expect(modeLabel("EXAM_SIM")).toBe("Exam simulation"); + expect(modeLabel("INTERLEAVED_PRACTICE")).toBe("Interleaved practice"); + expect(modeLabel("")).toBe("Session"); + }); +}); + +describe("previewSentence", () => { + it("says what moves, what stays and what will be skipped, with real plurals", () => { + expect(previewSentence({ moved: 3, kept: 5, dropped: 2 }, "Prelim 1")).toBe( + "3 sessions move and 5 stay. 2 don't fit before Prelim 1 and will be skipped." + ); + expect(previewSentence({ moved: 1, kept: 1, dropped: 0 }, "Prelim 1")).toBe("1 session moves and 1 stays."); + expect(previewSentence({ moved: 0, kept: 0, dropped: 1 }, "Final")).toBe( + "1 doesn't fit before Final and will be skipped." + ); + }); +}); + +describe("rescheduleToast", () => { + const applied = (moved: number, dropped: number, calendar: { status?: string; code?: string } | null = null) => ({ + applied: true, + summary: { moved, dropped }, + calendar, + }) + + it("says what moved and what was skipped in one message", () => { + expect(rescheduleToast(applied(3, 2)).title).toBe("3 sessions moved and 2 skipped") + expect(rescheduleToast(applied(1, 1)).title).toBe("1 session moved and 1 skipped") + expect(rescheduleToast(applied(2, 0)).title).toBe("2 sessions moved") + expect(rescheduleToast(applied(0, 1)).title).toBe("1 session skipped") + expect(rescheduleToast({ applied: false, calendar: null }).title).toBe("Nothing to reschedule") + }) + + it("adds one whole sentence about Google Calendar, with the way to fix it", () => { + expect(rescheduleToast(applied(3, 0, { status: "OK" }))).toEqual({ + title: "3 sessions moved", + description: "Google Calendar updated.", + }) + expect(rescheduleToast(applied(3, 2, { status: "PARTIAL" }))).toEqual({ + title: "3 sessions moved and 2 skipped", + description: "Some Google Calendar events weren't updated. Update them from the plan menu.", + calendarAction: "update", + }) + expect(rescheduleToast(applied(3, 0, { status: "FAILED", code: "unknown" }))).toEqual({ + title: "3 sessions moved", + description: "Google Calendar wasn't updated. Update it from the plan menu.", + calendarAction: "update", + }) + expect(rescheduleToast(applied(3, 0, { status: "FAILED", code: "GOOGLE_RECONNECT_REQUIRED" })).calendarAction).toBe( + "reconnect" + ) + expect(rescheduleToast(applied(3, 0, { status: "NOT_PUBLISHED" })).description).toBeUndefined() + }) +}) diff --git a/src/__tests__/plan-status.test.ts b/src/__tests__/plan-status.test.ts new file mode 100644 index 00000000..f62da3cd --- /dev/null +++ b/src/__tests__/plan-status.test.ts @@ -0,0 +1,104 @@ +import { describe, it, expect } from "vitest"; +import { + RUN_UNDER_WAY_STATUSES, + classifyPlanItem, + countPlanItems, + runStateFromStatuses, + withRunUnderWay, +} from "@/lib/plan-status"; +import { dateColumnKey, dateColumnValue } from "@/lib/plan-dates"; + +const NOW = new Date("2026-10-15T20:00:00Z"); // 4:00 PM in New York +const NY = "America/New_York"; + +describe("runStateFromStatuses", () => { + it("prefers a completed run, then an active or paused one", () => { + expect(runStateFromStatuses([])).toBe("none"); + expect(runStateFromStatuses(["CREATED"])).toBe("none"); + expect(runStateFromStatuses(["PAUSED"])).toBe("in_progress"); + expect(runStateFromStatuses(["ACTIVE", "COMPLETED"])).toBe("completed"); + }); +}); + +describe("withRunUnderWay", () => { + const underWay = new Set(["s1"]); + + it("reads a session with a run under way as IN_PROGRESS, whatever the item stored", () => { + for (const status of ["SCHEDULED", "RESCHEDULED", "MISSED", "SKIPPED", "IN_PROGRESS"]) { + expect(withRunUnderWay({ sessionId: "s1", status }, underWay).status).toBe("IN_PROGRESS"); + } + }); + + it("leaves done sessions and sessions without a run as they are", () => { + const done = { sessionId: "s1", status: "DONE" }; + const other = { sessionId: "s2", status: "SCHEDULED" }; + expect(withRunUnderWay(done, underWay)).toBe(done); + expect(withRunUnderWay(other, underWay)).toBe(other); + }); + + it("counts the same run statuses as under way that Plan counts as in progress", () => { + for (const status of RUN_UNDER_WAY_STATUSES) expect(runStateFromStatuses([status])).toBe("in_progress"); + }); +}); + +describe("classifyPlanItem", () => { + const future = { status: "SCHEDULED", endTime: "2026-10-16T21:00:00Z" }; + const earlierToday = { status: "SCHEDULED", endTime: "2026-10-15T18:40:00Z" }; // 2:40 PM NY + const yesterday = { status: "SCHEDULED", endTime: "2026-10-14T20:30:00Z" }; + + it("reads stored terminal statuses first", () => { + expect(classifyPlanItem({ ...future, status: "SKIPPED" }, "none", NOW)).toBe("skipped"); + expect(classifyPlanItem({ ...future, status: "DONE" }, "none", NOW)).toBe("done"); + expect(classifyPlanItem({ ...future, status: "MISSED" }, "none", NOW)).toBe("missed"); + }); + + it("counts a completed run as done even when the item was rescheduled", () => { + expect(classifyPlanItem({ ...future, status: "RESCHEDULED" }, "completed", NOW)).toBe("done"); + }); + + it("lets a skipped session's runs win: finished from its link, it reads done", () => { + expect(classifyPlanItem({ ...future, status: "SKIPPED" }, "completed", NOW)).toBe("done"); + expect(classifyPlanItem({ ...future, status: "SKIPPED" }, "in_progress", NOW)).toBe("in_progress"); + }); + + it("marks a started session as in progress", () => { + expect(classifyPlanItem(yesterday, "in_progress", NOW)).toBe("in_progress"); + }); + + it("keeps future sessions scheduled and past unstarted ones missed", () => { + expect(classifyPlanItem(future, "none", NOW)).toBe("scheduled"); + expect(classifyPlanItem(yesterday, "none", NOW, NY)).toBe("missed"); + }); + + it("keeps today's unstarted session open until the day ends in the zone", () => { + expect(classifyPlanItem(earlierToday, "none", NOW, NY)).toBe("scheduled"); + // Without a zone only the time counts + expect(classifyPlanItem(earlierToday, "none", NOW)).toBe("missed"); + }); +}); + +describe("countPlanItems", () => { + it("counts each state and leaves skipped out of the total", () => { + expect(countPlanItems(["done", "done", "missed", "scheduled", "skipped", "in_progress"])).toEqual({ + total: 5, + done: 2, + in_progress: 1, + missed: 1, + scheduled: 1, + skipped: 1, + }); + }); +}); + +describe("DATE columns", () => { + it("reads the stored calendar day, not the evening before in a zone west of UTC", () => { + // Prisma returns a DATE as midnight UTC + const stored = new Date("2026-10-15T00:00:00.000Z"); + expect(dateColumnKey(stored)).toBe("2026-10-15"); + }); + + it("writes the calendar day itself", () => { + expect(dateColumnValue("2026-10-15").toISOString()).toBe("2026-10-15T00:00:00.000Z"); + expect(() => dateColumnValue("Oct 15")).toThrow(); + }); +}); diff --git a/src/__tests__/progress-data.test.ts b/src/__tests__/progress-data.test.ts new file mode 100644 index 00000000..a5b79267 --- /dev/null +++ b/src/__tests__/progress-data.test.ts @@ -0,0 +1,97 @@ +/** + * Server reads shared by Home and Progress. loadPlans keeps a fixed number + * of plans; a long-time student with more than that must still see the + * upcoming exams and today's sessions. + */ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +vi.mock("server-only", () => ({})); +vi.mock("@/lib/auth", () => ({ getCurrentUserId: vi.fn(async () => "user1") })); +vi.mock("@/services/gamification", () => ({ + getActivityByDay: vi.fn(), + getGameState: vi.fn(), + resolveTimeZone: vi.fn(async () => "UTC"), +})); + +interface PlanFixture { + planId: string; + courseName: string; + examName: string; + examDate: Date; + createdAt: Date; + config: unknown; + items: never[]; +} + +type OrderBy = Array<Partial<Record<"examDate" | "createdAt", "asc" | "desc">>>; + +const db = vi.hoisted(() => ({ plans: [] as PlanFixture[] })); + +vi.mock("@/lib/db", () => ({ + prisma: { + studyPlan: { + // Applies orderBy and take the way Postgres would. + findMany: vi.fn(async ({ orderBy, take }: { orderBy: OrderBy; take?: number }) => { + const sorted = [...db.plans].sort((a, b) => { + for (const clause of orderBy) { + const [field, direction] = Object.entries(clause)[0] as ["examDate" | "createdAt", "asc" | "desc"]; + const diff = a[field].getTime() - b[field].getTime(); + if (diff !== 0) return direction === "asc" ? diff : -diff; + } + return 0; + }); + return take === undefined ? sorted : sorted.slice(0, take); + }), + }, + planReflowAudit: { findMany: vi.fn(async () => []) }, + sessionRun: { findMany: vi.fn(async () => []) }, + }, +})); + +import { PLAN_LIMIT, loadPlans } from "@/services/progress-data"; + +function plan(id: string, examDate: string, createdAt: string): PlanFixture { + return { + planId: id, + courseName: "CS 2110", + examName: id, + examDate: new Date(`${examDate}T00:00:00Z`), + createdAt: new Date(createdAt), + config: null, + items: [], + }; +} + +beforeEach(() => { + db.plans.length = 0; +}); + +describe("loadPlans", () => { + it("keeps upcoming exams when a student has more plans than the limit", async () => { + // Old semesters fill the limit with exams that are long over. + for (let i = 0; i < PLAN_LIMIT; i++) { + const day = String((i % 28) + 1).padStart(2, "0"); + db.plans.push(plan(`old-${i}`, `2024-0${(i % 9) + 1}-${day}`, "2024-01-01T00:00:00Z")); + } + db.plans.push(plan("prelim-1", "2026-10-22", "2026-10-01T00:00:00Z")); + + const plans = await loadPlans("user1"); + + expect(plans).toHaveLength(PLAN_LIMIT); + expect(plans.at(-1)?.planId).toBe("prelim-1"); + expect(plans.some((p) => p.planId === "old-0")).toBe(false); + }); + + it("lists the soonest exam first, and the newest plan first on the same date", async () => { + db.plans.push( + plan("final", "2026-12-10", "2026-09-01T00:00:00Z"), + plan("prelim-older", "2026-10-22", "2026-09-01T00:00:00Z"), + plan("prelim-newer", "2026-10-22", "2026-10-01T00:00:00Z"), + ); + + const plans = await loadPlans("user1"); + + expect(plans.map((p) => p.planId)).toEqual(["prelim-newer", "prelim-older", "final"]); + expect(plans[0].examDateKey).toBe("2026-10-22"); + }); +}); diff --git a/src/__tests__/progress-model.test.ts b/src/__tests__/progress-model.test.ts new file mode 100644 index 00000000..27053e63 --- /dev/null +++ b/src/__tests__/progress-model.test.ts @@ -0,0 +1,245 @@ +/** + * Progress models: topics and mastery, confidence calibration, the activity + * heatmap and achievement progress. + */ +import { describe, expect, it } from "vitest" + +import { + achievementViews, + buildHeatmap, + calibrate, + confidenceLevel, + dayLabel, + describeDay, + heatLevel, + pretestKey, + splitRatedAnswers, + weekStart, +} from "@/lib/progress-model" +import { + buildTopics, + compareWeakestFirst, + isWeakTopic, + topicStatus, +} from "@/components/progress/topics" +import { ALL_BADGES, badgesReached } from "@/lib/badge-data" +import { slugifyObjectiveTitle } from "@/lib/objective-keys" +import type { DayActivity } from "@/services/gamification" + +const NOW = new Date("2026-10-15T19:00:00Z") + +function day(overrides: Partial<DayActivity> = {}): DayActivity { + return { sessions: 0, reviews: 0, freezeUsed: false, xp: 0, ...overrides } +} + +describe("topics", () => { + it("titles topics from the plans, falling back to a readable key", () => { + const topics = buildTopics( + [ + { courseName: "INFO 1300", objectiveKey: "css_specificity", lastAccuracy: 0.2, repetitions: 0, easeFactor: 1.3, lastStudiedAt: NOW, nextDueAt: null }, + { courseName: "INFO 1300", objectiveKey: "media_queries", lastAccuracy: 0.9, repetitions: 1, easeFactor: 2.5, lastStudiedAt: NOW, nextDueAt: null }, + // A key written outside the plan generator keeps its acronym. + { courseName: "INFO 1300", objectiveKey: "HTML_forms", lastAccuracy: 0.8, repetitions: 1, easeFactor: 2.5, lastStudiedAt: NOW, nextDueAt: null }, + ], + [{ courseName: "INFO 1300", titles: ["CSS specificity", "The box model"] }], + NOW + ) + expect(topics.map((t) => [t.title, t.status])).toEqual([ + ["CSS specificity", "practiced"], + ["Media queries", "practiced"], + ["HTML forms", "practiced"], + ["The box model", "not-practiced"], + ]) + }) + + it("marks mastered and due topics with the server's rules", () => { + const base = { lastAccuracy: 1, lastStudiedAt: NOW, nextDueAt: null } + expect(topicStatus({ ...base, repetitions: 3, easeFactor: 2.1 }, NOW)).toBe("mastered") + expect(topicStatus({ ...base, repetitions: 1, easeFactor: 2.5, nextDueAt: new Date("2026-10-14T00:00:00Z") }, NOW)).toBe("due") + }) + + it("sorts weakest first with never-practiced topics last, and finds weak spots", () => { + const t = (title: string, value: number | null, status: "practiced" | "mastered" | "not-practiced" = "practiced") => ({ + courseName: "C", + key: slugifyObjectiveTitle(title), + title, + value, + status, + lastStudiedAt: null, + }) + const sorted = [t("B", 0.5), t("A", null, "not-practiced"), t("C", 0.2), t("D", 0.9)].sort(compareWeakestFirst) + expect(sorted.map((x) => x.title)).toEqual(["C", "B", "D", "A"]) + expect(isWeakTopic(t("B", 0.5))).toBe(true) + expect(isWeakTopic(t("D", 0.9))).toBe(false) + expect(isWeakTopic(t("A", null, "not-practiced"))).toBe(false) + }) +}) + +describe("calibrate", () => { + const at = (iso: string) => new Date(iso) + const answers = [ + { confidence: 5, correct: true, createdAt: at("2026-10-05T18:00:00Z") }, + { confidence: 5, correct: true, createdAt: at("2026-10-06T18:00:00Z") }, + { confidence: 5, correct: false, createdAt: at("2026-10-07T18:00:00Z") }, // incorrect + { confidence: 4, correct: false, createdAt: at("2026-10-13T18:00:00Z") }, // partly correct + { confidence: 3, correct: true, createdAt: at("2026-10-13T18:00:00Z") }, + { confidence: 1, correct: true, createdAt: at("2026-10-14T18:00:00Z") }, + { confidence: 2, correct: false, createdAt: at("2026-10-14T18:00:00Z") }, + ] + + it("maps old five-step ratings onto the three levels, as the end screen does", () => { + // The old 2 was labelled Unsure, and 4 Confident. + expect([1, 2, 3, 4, 5].map((rating) => confidenceLevel(rating))).toEqual(["guessing", "unsure", "unsure", "sure", "sure"]) + }) + + it("summarizes each level and counts over- and underconfidence", () => { + const result = calibrate(answers, "America/New_York") + expect(result.levels).toEqual([ + { level: "sure", answers: 4, correct: 2, rate: 0.5 }, + { level: "unsure", answers: 2, correct: 1, rate: 0.5 }, + { level: "guessing", answers: 1, correct: 1, rate: 1 }, + ]) + // Sure and not fully correct, as on the end screen: the incorrect and the partly correct one. + expect(result.overconfident).toBe(2) + expect(result.underconfident).toBe(1) + }) + + it("groups answers into Sunday-first weeks in the student's zone", () => { + const result = calibrate(answers, "America/New_York") + expect(result.weeks.map((w) => [w.weekKey, w.label, w.answers])).toEqual([ + ["2026-10-04", "Oct 4", 3], + ["2026-10-11", "Oct 11", 4], + ]) + expect(result.weeks[0].sure).toBeCloseTo(2 / 3) + expect(result.weeks[0].unsure).toBeNull() + }) + + it("leaves pretest answers out and counts unrated ones", () => { + const attempt = (promptIndex: number, confidenceRating: number | null, selfScore: string | null) => ({ + runId: "run-1", + promptIndex, + confidenceRating, + selfScore, + createdAt: at("2026-10-14T18:00:00Z"), + }) + const { rated, unrated } = splitRatedAnswers( + [ + attempt(0, 5, "INCORRECT"), // pretest: wrong answers are expected + attempt(1, null, "CORRECT"), // pretest, unrated + attempt(2, 5, "PARTIAL"), + attempt(3, null, "INCORRECT"), + attempt(4, 1, null), // not scored yet (exam simulation) + ], + new Set([pretestKey("run-1", 0), pretestKey("run-1", 1)]) + ) + expect(rated.map((a) => [a.confidence, a.correct])).toEqual([[5, false]]) + expect(unrated).toBe(1) + }) + + it("finds the week start across a month boundary", () => { + expect(weekStart("2026-11-03")).toBe("2026-11-01") + expect(weekStart("2026-11-01")).toBe("2026-11-01") + }) +}) + +describe("heatmap", () => { + it("steps darker with XP", () => { + expect([0, 1, 9, 10, 25, 50].map(heatLevel)).toEqual([0, 1, 1, 2, 3, 4]) + }) + + it("describes what a day held, counting sessions and reviews separately", () => { + expect(describeDay(day({ sessions: 1, reviews: 8, xp: 26 }))).toBe("1 session and 8 card reviews") + expect(describeDay(day({ reviews: 1, xp: 2 }))).toBe("1 card review") + expect(describeDay(day({ freezeUsed: true }))).toBe("Streak freeze used") + // A day with study XP but no session or review (a perfect-deck bonus) still says what it held. + expect(describeDay(day({ xp: 5 }))).toBe("5 XP") + expect(describeDay(undefined)).toBe("No study") + }) + + it("ends on today with full weeks before it and nothing after", () => { + const days = new Map([ + ["2026-10-15", day({ sessions: 1, xp: 10 })], + ["2026-10-14", day({ reviews: 2, xp: 4 })], + ["2026-10-12", day({ reviews: 1, xp: 2 })], + ]) + const map = buildHeatmap(days, "2026-10-15") + expect(map.columns).toHaveLength(53) + const last = map.columns[52] + // Oct 15, 2026 is a Thursday: Sunday to Thursday filled, Friday and Saturday empty. + expect(last.map((c) => c?.key ?? null)).toEqual([ + "2026-10-11", + "2026-10-12", + "2026-10-13", + "2026-10-14", + "2026-10-15", + null, + null, + ]) + expect(last[4]).toMatchObject({ level: 2, label: "Thu, Oct 15: 1 session" }) + expect(map.activeDays).toBe(3) + expect(map.longestStreak).toBe(2) + expect(map.columns[0][0]?.key).toBe("2025-10-12") + }) + + it("drops a partial first month label that would collide with the next", () => { + const map = buildHeatmap(new Map(), "2026-10-15") + // The grid opens on Sun, Oct 12, 2025; Nov 1 falls in the third column. + expect(map.months[0]).toEqual({ label: "Nov", column: 2 }) + expect(map.months.at(-1)?.label).toBe("Oct") + for (let i = 1; i < map.months.length; i++) { + expect(map.months[i].column - map.months[i - 1].column).toBeGreaterThanOrEqual(3) + } + }) + + it("dates days from another year with the year", () => { + expect(dayLabel("2025-10-14", "2026-10-15")).toBe("Oct 14, 2025") + expect(dayLabel("2026-10-14", "2026-10-15")).toBe("Wed, Oct 14") + }) +}) + +describe("achievements", () => { + it("measures the perfect-deck achievement in perfect decks, not reviews", () => { + const views = achievementViews({ streak: 4, xp: 202, reviews: 56, perfectDecks: 0 }, []) + const perfect = views.find((v) => v.key === "FIRST_PERFECT") + expect(perfect).toMatchObject({ current: 0, threshold: 1, progressText: "0 of 1 perfect deck" }) + const week = views.find((v) => v.key === "STREAK_7") + expect(week?.progressText).toBe("4 of 7 days") + const xp = views.find((v) => v.key === "XP_1000") + expect(xp?.progressText).toBe("202 of 1,000 XP") + }) + + it("caps progress at the threshold and keeps earned dates", () => { + const views = achievementViews({ streak: 9, xp: 0, reviews: 0, perfectDecks: 0 }, [ + { badgeType: "STREAK_3", earnedAt: "2026-10-05T20:17:42.000Z" }, + ]) + expect(views.find((v) => v.key === "STREAK_3")).toMatchObject({ + current: 3, + earnedAt: "2026-10-05T20:17:42.000Z", + }) + }) + + it("awards only what the values reach and skips earned ones", () => { + expect(badgesReached({ streak: 7, xp: 120, reviews: 1, perfectDecks: 0 }, new Set(["STREAK_3"]))).toEqual([ + "STREAK_7", + "FIRST_REVIEW", + "XP_100", + ]) + }) + + it("keeps every stored badge key", () => { + expect(ALL_BADGES.map((b) => b.key)).toEqual([ + "STREAK_3", + "STREAK_7", + "STREAK_14", + "STREAK_30", + "STREAK_60", + "STREAK_100", + "FIRST_REVIEW", + "REVIEWS_100", + "REVIEWS_500", + "FIRST_PERFECT", + "XP_100", + "XP_1000", + ]) + }) +}) diff --git a/src/__tests__/prompts-modes.test.ts b/src/__tests__/prompts-modes.test.ts index aca02686..e32404e2 100644 --- a/src/__tests__/prompts-modes.test.ts +++ b/src/__tests__/prompts-modes.test.ts @@ -100,10 +100,7 @@ describe("generateInterleavedPrompts", () => { }; const a = generateInterleavedPrompts({ ...base, seed: "seed_1" }); const b = generateInterleavedPrompts({ ...base, seed: "seed_2" }); - // With different seeds, at least some prompt texts should differ in ordering - const aTexts = a.map((p) => p.text).join("|"); - const bTexts = b.map((p) => p.text).join("|"); - // They might be different; but at minimum both should have the right length + // Different seeds may reorder the prompts; either way both keep the right length expect(a).toHaveLength(12); expect(b).toHaveLength(12); }); @@ -232,7 +229,8 @@ describe("generateErrorRepairPrompts", () => { it("uses fallback text when no variant_question", () => { const prompts = generateErrorRepairPrompts(sampleLogs, 3); - expect(prompts[1].text).toContain("near-transfer example"); + expect(prompts[1].text).toContain("new example where it applies"); + expect(prompts[1].text).toMatch(/From memory/); }); it("references the original question when no variant_question exists", () => { diff --git a/src/__tests__/prompts.test.ts b/src/__tests__/prompts.test.ts index 591f4c4b..b1f3a1ad 100644 --- a/src/__tests__/prompts.test.ts +++ b/src/__tests__/prompts.test.ts @@ -1,5 +1,11 @@ import { describe, it, expect } from "vitest"; -import { generateRetrievalPrompts, shuffleMcqChoices, type Prompt } from "@/lib/prompts"; +import { + generateInterleavedPrompts, + generateRetrievalPrompts, + inSentence, + shuffleMcqChoices, + type Prompt, +} from "@/lib/prompts"; describe("generateRetrievalPrompts", () => { it("generates the exact number of prompts from target_outcome.prompt_count", () => { @@ -122,3 +128,42 @@ describe("shuffleMcqChoices", () => { expect(shuffleMcqChoices(freeRecall, "seed-f")).toBe(freeRecall); }); }); + +describe("inSentence", () => { + it("lower-cases a leading article only", () => { + expect(inSentence("The box model")).toBe("the box model"); + expect(inSentence("A linked list")).toBe("a linked list"); + expect(inSentence("An array")).toBe("an array"); + expect(inSentence("The French Revolution")).toBe("the French Revolution"); + }); + + it("leaves titles without a leading article as written", () => { + expect(inSentence("CSS specificity")).toBe("CSS specificity"); + expect(inSentence("Theory of mind")).toBe("Theory of mind"); + expect(inSentence("Anatomy")).toBe("Anatomy"); + expect(inSentence("A* search")).toBe("A* search"); + }); + + it("is applied where the question templates put a topic mid-sentence", () => { + const objectives = [ + { id: "o1", title: "The box model" }, + { id: "o2", title: "CSS specificity" }, + ]; + const retrieval = generateRetrievalPrompts({ + objectives, + target_outcome: { prompt_count: 6 }, + topic_scope: "INFO 1300", + }); + const interleaved = generateInterleavedPrompts({ + objectives, + target_outcome: { prompt_count: 6 }, + topic_scope: "INFO 1300", + seed: "s", + }); + for (const p of [...retrieval, ...interleaved]) { + expect(p.text).not.toContain("The box model"); + } + expect(retrieval.map((p) => p.text)).toContain("Define CSS specificity and give one concrete example."); + expect(retrieval[0].text).toBe("From memory: explain the box model in 3 to 5 bullets."); + }); +}); diff --git a/src/__tests__/proxy.test.ts b/src/__tests__/proxy.test.ts new file mode 100644 index 00000000..136bef85 --- /dev/null +++ b/src/__tests__/proxy.test.ts @@ -0,0 +1,209 @@ +/** + * Unit tests for the request proxy (src/proxy.ts): which paths skip auth, + * when the test-auth header is trusted, and cross-site write rejection. + */ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { NextRequest } from "next/server"; + +vi.mock("next-auth/jwt", () => ({ getToken: vi.fn() })); + +import { getToken } from "next-auth/jwt"; +import { proxy } from "@/proxy"; +import { isTestAuthEnabled, testAuthUserId } from "@/lib/test-auth"; +import { UNAUTHORIZED_BODY } from "@/lib/http"; + +const getTokenMock = vi.mocked(getToken); + +function req(path: string, init: { method?: string; headers?: Record<string, string> } = {}) { + return new NextRequest(`http://localhost:3000${path}`, { + method: init.method ?? "GET", + headers: { host: "localhost:3000", ...init.headers }, + }); +} + +/** "pass" when the proxy lets the request through, else the status code. */ +async function outcome(request: NextRequest): Promise<"pass" | number> { + const res = await proxy(request); + return res.headers.get("x-middleware-next") === "1" ? "pass" : res.status; +} + +beforeEach(() => { + getTokenMock.mockReset(); + getTokenMock.mockResolvedValue(null); + vi.stubEnv("ALLOW_TEST_AUTH", ""); + vi.stubEnv("CI", ""); + vi.stubEnv("NODE_ENV", "test"); + vi.stubEnv("NEXTAUTH_URL", ""); +}); + +afterEach(() => { + vi.unstubAllEnvs(); +}); + +describe("test-auth gate", () => { + it("is off unless ALLOW_TEST_AUTH=true", () => { + expect(isTestAuthEnabled()).toBe(false); + vi.stubEnv("ALLOW_TEST_AUTH", "true"); + expect(isTestAuthEnabled()).toBe(true); + }); + + it("is off in production builds unless CI=true", () => { + vi.stubEnv("ALLOW_TEST_AUTH", "true"); + vi.stubEnv("NEXTAUTH_URL", "http://localhost:3000"); + vi.stubEnv("NODE_ENV", "production"); + expect(isTestAuthEnabled()).toBe(false); + vi.stubEnv("CI", "true"); + expect(isTestAuthEnabled()).toBe(true); + }); + + // The header carries no secret, so a deployment that sets ALLOW_TEST_AUTH + // by mistake must still ignore it. A deployment's address is never local. + it("is off when the app's address is not on this machine", () => { + vi.stubEnv("ALLOW_TEST_AUTH", "true"); + for (const url of ["https://studybot.example.com", "http://192.168.1.20:3000", "http://localhost.example.com", "not a url"]) { + vi.stubEnv("NEXTAUTH_URL", url); + vi.stubEnv("NODE_ENV", "development"); + expect(isTestAuthEnabled(), url).toBe(false); + vi.stubEnv("NODE_ENV", "production"); + vi.stubEnv("CI", "true"); + expect(isTestAuthEnabled(), `${url} in CI`).toBe(false); + vi.stubEnv("CI", ""); + } + expect(testAuthUserId(new Headers({ "x-user-id": "u1" }))).toBeNull(); + }); + + it("accepts loopback addresses", () => { + vi.stubEnv("ALLOW_TEST_AUTH", "true"); + for (const url of ["http://localhost:3000", "http://127.0.0.1:3100", "http://[::1]:3000", "http://e2e.localhost:3000"]) { + vi.stubEnv("NEXTAUTH_URL", url); + expect(isTestAuthEnabled(), url).toBe(true); + } + }); + + it("needs NEXTAUTH_URL in a production build", () => { + vi.stubEnv("ALLOW_TEST_AUTH", "true"); + vi.stubEnv("NODE_ENV", "production"); + vi.stubEnv("CI", "true"); + expect(isTestAuthEnabled()).toBe(false); + vi.stubEnv("NODE_ENV", "development"); + expect(isTestAuthEnabled()).toBe(true); + }); + + it("reads the first value of a duplicated header", () => { + vi.stubEnv("ALLOW_TEST_AUTH", "true"); + expect(testAuthUserId(new Headers({ "x-user-id": "u1, u1" }))).toBe("u1"); + expect(testAuthUserId(new Headers())).toBeNull(); + }); +}); + +describe("proxy auth", () => { + it("redirects signed-out page requests to sign in", async () => { + const res = await proxy(req("/plan")); + expect(res.status).toBe(307); + expect(res.headers.get("location")).toContain("/auth/signin?callbackUrl=%2Fplan"); + }); + + it("keeps the query string in the callback URL", async () => { + const res = await proxy(req("/plan?plan=abc&reschedule=1")); + const location = new URL(res.headers.get("location")!); + expect(location.searchParams.get("callbackUrl")).toBe("/plan?plan=abc&reschedule=1"); + }); + + it("requires sign-in for session pages", async () => { + expect(await outcome(req("/s/abc123"))).toBe(307); + }); + + it("answers 401 for signed-out API requests", async () => { + expect(await outcome(req("/api/plans"))).toBe(401); + }); + + it("lets public paths and static files through", async () => { + expect(await outcome(req("/auth/signin"))).toBe("pass"); + expect(await outcome(req("/api/health"))).toBe("pass"); + expect(await outcome(req("/manifest.json"))).toBe("pass"); + expect(await outcome(req("/icon.svg"))).toBe("pass"); + }); + + it("answers signed-out API requests with the shared 401 body", async () => { + const res = await proxy(req("/api/plans")); + expect(await res.json()).toEqual(UNAUTHORIZED_BODY); + }); + + it("only skips auth for static files at the top level", async () => { + // A page under a dynamic segment whose id happens to end in an extension + expect(await outcome(req("/flashcards/abc.json"))).toBe(307); + expect(await outcome(req("/s/abc.js"))).toBe(307); + expect(await outcome(req("/plan/x/y.svg"))).toBe(307); + expect(await outcome(req("/icon-maskable.svg"))).toBe("pass"); + }); + + it("does not treat a dotted API path or page path as a static file", async () => { + expect(await outcome(req("/api/plans/x.json"))).toBe(401); + expect(await outcome(req("/settings.bak"))).toBe(307); + expect(await outcome(req("/api/healthcheck"))).toBe(401); + }); + + it("lets signed-in requests through", async () => { + getTokenMock.mockResolvedValue({ sub: "u1" }); + expect(await outcome(req("/api/plans"))).toBe("pass"); + expect(await outcome(req("/s/abc123"))).toBe("pass"); + }); + + it("ignores the X-User-Id header unless test auth is enabled", async () => { + const withHeader = { headers: { "x-user-id": "u1" } }; + expect(await outcome(req("/api/plans", withHeader))).toBe(401); + + vi.stubEnv("ALLOW_TEST_AUTH", "true"); + expect(await outcome(req("/api/plans", withHeader))).toBe("pass"); + + vi.stubEnv("NODE_ENV", "production"); + expect(await outcome(req("/api/plans", withHeader))).toBe(401); + }); +}); + +describe("cross-site writes", () => { + beforeEach(() => { + getTokenMock.mockResolvedValue({ sub: "u1" }); + }); + + it("rejects API writes from another origin, with a code the client can map", async () => { + const res = await proxy( + req("/api/plans", { method: "POST", headers: { origin: "https://evil.example" } }), + ); + expect(res.status).toBe(403); + expect(await res.json()).toEqual({ + error: "Request blocked because it came from another site. Reload the page and retry.", + code: "CROSS_SITE_REQUEST", + }); + }); + + it("rejects an opaque origin and cross-site fetch metadata", async () => { + expect(await outcome(req("/api/plans", { method: "POST", headers: { origin: "null" } }))).toBe(403); + expect( + await outcome(req("/api/plans", { method: "DELETE", headers: { "sec-fetch-site": "cross-site" } })), + ).toBe(403); + }); + + it("covers the public auth endpoints too", async () => { + expect( + await outcome(req("/api/auth/signup", { method: "POST", headers: { origin: "https://evil.example" } })), + ).toBe(403); + }); + + it("allows same-origin writes, writes without an Origin, and reads", async () => { + expect( + await outcome(req("/api/plans", { method: "POST", headers: { origin: "http://localhost:3000" } })), + ).toBe("pass"); + expect(await outcome(req("/api/plans", { method: "POST" }))).toBe("pass"); + expect(await outcome(req("/api/plans", { headers: { origin: "https://evil.example" } }))).toBe("pass"); + }); + + it("allows the configured BASE_URL origin behind a proxy", async () => { + vi.stubEnv("BASE_URL", "https://study.example.edu"); + const request = req("/api/plans", { + method: "PUT", + headers: { origin: "https://study.example.edu", host: "127.0.0.1:3000" }, + }); + expect(await outcome(request)).toBe("pass"); + }); +}); diff --git a/src/__tests__/publish-skipped.test.ts b/src/__tests__/publish-skipped.test.ts new file mode 100644 index 00000000..341ebf73 --- /dev/null +++ b/src/__tests__/publish-skipped.test.ts @@ -0,0 +1,108 @@ +/** + * Sessions Reschedule skipped leave Google Calendar on the next publish: + * their events are deleted once, and no event is created for them. + */ +import { describe, it, expect, vi, beforeEach } from "vitest"; + +const client = { + createEvent: vi.fn(), + updateEvent: vi.fn(), + deleteEvent: vi.fn(), + listEvents: vi.fn(), +}; + +vi.mock("@/lib/google/calendar-client", async (importOriginal) => { + const actual = await importOriginal<typeof import("@/lib/google/calendar-client")>(); + return { ...actual, getGoogleClient: () => client }; +}); + +vi.mock("@/lib/db", () => ({ + prisma: { + studyPlan: { findUnique: vi.fn() }, + googleIntegration: { findUnique: vi.fn() }, + planCalendarPublication: { findUnique: vi.fn(), upsert: vi.fn() }, + planItemExternalEvent: { findMany: vi.fn(), delete: vi.fn(), create: vi.fn(), update: vi.fn() }, + session: { findMany: vi.fn() }, + }, +})); + +import { publishPlanToGoogle } from "@/services/publish"; +import { GoogleApiError } from "@/lib/google/calendar-client"; +import { prisma } from "@/lib/db"; + +const mock = <T>(fn: T) => fn as unknown as ReturnType<typeof vi.fn>; + +const item = (id: string, status: string) => ({ + id, + sessionId: `s-${id}`, + dayIndex: 0, + status, + startTime: new Date("2026-10-16T13:00:00Z"), + endTime: new Date("2026-10-16T14:00:00Z"), +}); + +const session = (id: string) => ({ + sessionId: `s-${id}`, + courseName: "CS 2110", + examName: "Prelim 1", + mode: "RETRIEVAL", + topicScope: "Recursion", + plannedMinutes: 60, + objectives: [{ id: "recursion", title: "Recursion" }], + targetOutcome: { prompt_count: 8, target_accuracy: 0.8 }, + breakProtocol: { type: "25_5", cycles: 1 }, +}); + +const mapping = (itemId: string) => ({ + id: `m-${itemId}`, + planItemId: itemId, + calendarId: "primary", + eventId: `e-${itemId}`, + htmlLink: null, + lastSyncedHash: "old", +}); + +describe("publishPlanToGoogle with skipped sessions", () => { + beforeEach(() => { + vi.clearAllMocks(); + mock(prisma.studyPlan.findUnique).mockResolvedValue({ + planId: "plan-1", + userId: "user-1", + timezone: "America/New_York", + items: [item("kept", "SCHEDULED"), item("skipped", "SKIPPED"), item("new-skip", "SKIPPED")], + }); + mock(prisma.googleIntegration.findUnique).mockResolvedValue({ + status: "CONNECTED", + calendarIdSelected: "primary", + }); + mock(prisma.planCalendarPublication.findUnique).mockResolvedValue({ calendarId: "primary", status: "PUBLISHED" }); + // "new-skip" never had an event + mock(prisma.planItemExternalEvent.findMany).mockResolvedValue([mapping("kept"), mapping("skipped")]); + mock(prisma.session.findMany).mockResolvedValue([session("kept"), session("skipped"), session("new-skip")]); + client.updateEvent.mockImplementation(async (_cal: string, eventId: string) => ({ id: eventId })); + client.deleteEvent.mockResolvedValue(undefined); + }); + + it("deletes the skipped session's event and creates none for skipped sessions", async () => { + const result = await publishPlanToGoogle("user-1", "plan-1"); + if (!("data" in result)) throw new Error("expected data"); + + expect(client.deleteEvent).toHaveBeenCalledWith("primary", "e-skipped"); + expect(mock(prisma.planItemExternalEvent.delete)).toHaveBeenCalledWith({ where: { id: "m-skipped" } }); + expect(client.createEvent).not.toHaveBeenCalled(); + expect(client.updateEvent).toHaveBeenCalledTimes(1); + expect(result.data.status).toBe("OK"); + expect(result.data.summary).toMatchObject({ updated: 1, removed: 1, failed: 0, total: 1 }); + }); + + it("keeps the mapping when the delete fails, without failing the publish", async () => { + client.deleteEvent.mockRejectedValueOnce(new GoogleApiError("Backend Error", 500)); + const result = await publishPlanToGoogle("user-1", "plan-1"); + if (!("data" in result)) throw new Error("expected data"); + + expect(mock(prisma.planItemExternalEvent.delete)).not.toHaveBeenCalled(); + expect(result.data.status).toBe("OK"); + expect(result.data.summary).toMatchObject({ removed: 0, total: 1 }); + expect(result.data.warnings?.length).toBe(1); + }); +}); diff --git a/src/__tests__/rate-limit.test.ts b/src/__tests__/rate-limit.test.ts index 8e2374e4..89bf2623 100644 --- a/src/__tests__/rate-limit.test.ts +++ b/src/__tests__/rate-limit.test.ts @@ -1,12 +1,30 @@ -import { describe, it, expect } from "vitest"; +import { describe, it, expect, afterEach, vi } from "vitest"; import type { NextRequest } from "next/server"; -import { getClientIp } from "@/lib/rate-limit"; +import { createRateLimiter, getClientIp, tooManyRequests } from "@/lib/rate-limit"; function makeRequest(headers: Record<string, string>): NextRequest { return new Request("http://localhost/api/test", { headers }) as unknown as NextRequest; } describe("getClientIp", () => { + afterEach(() => { + vi.unstubAllEnvs(); + }); + + it("counts TRUSTED_PROXY_HOPS entries from the right when several proxies append", () => { + vi.stubEnv("TRUSTED_PROXY_HOPS", "2"); + const request = makeRequest({ + "x-forwarded-for": "198.51.100.1, 203.0.113.7, 192.0.2.44", + }); + expect(getClientIp(request)).toBe("203.0.113.7"); + }); + + it("falls back to one hop when TRUSTED_PROXY_HOPS isn't a positive whole number", () => { + vi.stubEnv("TRUSTED_PROXY_HOPS", "zero"); + const request = makeRequest({ "x-forwarded-for": "198.51.100.1, 192.0.2.44" }); + expect(getClientIp(request)).toBe("192.0.2.44"); + }); + it("returns the single X-Forwarded-For entry when there is only one", () => { const request = makeRequest({ "x-forwarded-for": "203.0.113.7" }); expect(getClientIp(request)).toBe("203.0.113.7"); @@ -56,3 +74,39 @@ describe("getClientIp", () => { expect(getClientIp(request)).toBe("unknown"); }); }); + +describe("tooManyRequests", () => { + it("sets Retry-After in whole seconds and says how long to wait by default", async () => { + const res = tooManyRequests(1500); + expect(res.status).toBe(429); + expect(res.headers.get("Retry-After")).toBe("2"); + const body = await res.json(); + expect(body.error).toBe("Too many requests. Retry in 2 seconds."); + expect(body.code).toBe("RATE_LIMITED"); + expect(body.retry_after).toBe(2); + }); + + it("rounds longer waits up to whole minutes", async () => { + const res = tooManyRequests(90_000); + expect((await res.json()).error).toBe("Too many requests. Retry in 2 minutes."); + }); + + it("takes a message that names the limited action", async () => { + const res = tooManyRequests(60_000, "Too many reset requests. Retry in 1 minute."); + expect((await res.json()).error).toBe("Too many reset requests. Retry in 1 minute."); + }); +}); + +describe("createRateLimiter", () => { + it("allows up to the limit, then reports the wait", () => { + const limiter = createRateLimiter("test-limit", { maxRequests: 2, windowMs: 60_000 }); + expect(limiter.check("ip").allowed).toBe(true); + expect(limiter.check("ip").allowed).toBe(true); + const blocked = limiter.check("ip"); + expect(blocked.allowed).toBe(false); + expect(blocked.retryAfterMs).toBeGreaterThan(0); + expect(limiter.check("other-ip").allowed).toBe(true); + limiter.reset(); + expect(limiter.check("ip").allowed).toBe(true); + }); +}); diff --git a/src/__tests__/reflow.test.ts b/src/__tests__/reflow.test.ts index 909bf5ed..992955d3 100644 --- a/src/__tests__/reflow.test.ts +++ b/src/__tests__/reflow.test.ts @@ -15,6 +15,8 @@ import { describe, it, expect } from "vitest"; import { computeReflow, + isMissedItem, + subtractIntervals, ReflowItem, ReflowConfig, ALGORITHM_VERSION, @@ -351,7 +353,6 @@ describe("computeReflow", () => { for (const change of result.changes) { if (change.after) { const start = new Date(change.after.startTime).getTime(); - const doneEnd = new Date("2025-06-02T10:00:00Z").getTime(); const missedEnd = new Date("2025-06-02T11:00:00Z").getTime(); // Should not overlap with fixed intervals on day 0 if (change.after.dayIndex === 0) { @@ -424,4 +425,423 @@ describe("computeReflow", () => { .toBeGreaterThanOrEqual(new Date("2025-06-02T12:00:00Z").getTime()); }); }); + + describe("plan timezone", () => { + it("reads availability windows as wall-clock times in the plan's timezone", () => { + // Plan day 0 is 2025-06-02 in New York (EDT, UTC-4), so the 09:00-17:00 + // window is 13:00-21:00 UTC wherever the server runs. + const items: ReflowItem[] = [ + makeItem({ + id: "1", + sessionId: "s1", + dayIndex: 0, + startTime: new Date("2025-06-02T22:00:00Z"), + endTime: new Date("2025-06-02T23:00:00Z"), + plannedMinutes: 60, + }), + ]; + + const result = computeReflow( + items, + defaultConfig, + new Date("2025-06-02T12:00:00Z"), + earlyNow, + [], + "America/New_York", + ); + + expect(result.changes).toHaveLength(1); + expect(result.changes[0].action).toBe("MOVED"); + expect(result.changes[0].after).toEqual({ + dayIndex: 0, + startTime: "2025-06-02T13:00:00.000Z", + endTime: "2025-06-02T14:00:00.000Z", + }); + }); + + it("counts day indices by calendar day in the plan's timezone", () => { + // 01:00 UTC on 06-03 is still 06-02 (21:00) in New York, so a fixed item + // there uses day 0's cap, not day 1's. + const config: ReflowConfig = { + availability: Array.from({ length: 7 }, () => ({ start: "09:00", end: "23:00" })), + daily_study_cap_minutes: 60, + }; + const items: ReflowItem[] = [ + makeItem({ + id: "fixed", + sessionId: "s-fixed", + dayIndex: 0, + startTime: new Date("2025-06-03T01:00:00Z"), + endTime: new Date("2025-06-03T02:00:00Z"), + status: "DONE", + }), + makeItem({ + id: "1", + sessionId: "s1", + dayIndex: 0, + startTime: new Date("2025-06-02T14:00:00Z"), + endTime: new Date("2025-06-02T15:00:00Z"), + plannedMinutes: 60, + }), + ]; + + const result = computeReflow( + items, + config, + new Date("2025-06-02T12:00:00Z"), + earlyNow, + [], + "America/New_York", + ); + + const moved = result.changes.find((c) => c.itemId === "1"); + expect(moved?.action).toBe("MOVED"); + // Day 0's 60 minute cap is used up, so the item moves to day 1 at 09:00 EDT + expect(moved?.after).toEqual({ + dayIndex: 1, + startTime: "2025-06-03T13:00:00.000Z", + endTime: "2025-06-03T14:00:00.000Z", + }); + }); + }); +}); + +describe("missed sessions and the horizon", () => { + const NY = "America/New_York"; + // Plan day 0 is 2025-06-02 in New York; noon there is inside that day + const start = new Date("2025-06-02T16:00:00Z"); + // Wed 2025-06-04, 10:00 New York + const now = new Date("2025-06-04T14:00:00Z"); + + it("leaves missed sessions alone by default", () => { + const items: ReflowItem[] = [ + makeItem({ + id: "missed", + sessionId: "sm", + startTime: new Date("2025-06-02T13:00:00Z"), + endTime: new Date("2025-06-02T14:00:00Z"), + status: "MISSED", + }), + makeItem({ + id: "past", + sessionId: "sp", + startTime: new Date("2025-06-03T13:00:00Z"), + endTime: new Date("2025-06-03T14:00:00Z"), + }), + ]; + const result = computeReflow(items, defaultConfig, start, now, [], NY); + expect(result.changes).toHaveLength(0); + }); + + it("moves missed and unstarted past sessions into free time with includeMissed", () => { + const items: ReflowItem[] = [ + makeItem({ + id: "missed", + sessionId: "sm", + startTime: new Date("2025-06-02T13:00:00Z"), + endTime: new Date("2025-06-02T14:00:00Z"), + status: "MISSED", + }), + makeItem({ + id: "past", + sessionId: "sp", + startTime: new Date("2025-06-03T13:00:00Z"), + endTime: new Date("2025-06-03T14:00:00Z"), + }), + makeItem({ + id: "done", + sessionId: "sd", + startTime: new Date("2025-06-03T15:00:00Z"), + endTime: new Date("2025-06-03T16:00:00Z"), + status: "DONE", + }), + ]; + const result = computeReflow(items, defaultConfig, start, now, [], NY, { includeMissed: true }); + const byId = new Map(result.changes.map((c) => [c.itemId, c])); + expect(byId.has("done")).toBe(false); + for (const id of ["missed", "past"]) { + const change = byId.get(id)!; + expect(change.action).toBe("MOVED"); + expect(change.missed).toBe(true); + expect(new Date(change.after!.startTime).getTime()).toBeGreaterThanOrEqual(now.getTime()); + } + }); + + it("starts a session moved into today's window at the next quarter hour", () => { + // Wed 2025-06-04, 2:07:33 PM New York, inside the 9:00 to 17:00 window + const midWindow = new Date("2025-06-04T18:07:33Z"); + const items: ReflowItem[] = [ + makeItem({ + id: "missed", + sessionId: "sm", + startTime: new Date("2025-06-03T13:00:00Z"), + endTime: new Date("2025-06-03T13:50:00Z"), + plannedMinutes: 50, + status: "MISSED", + }), + makeItem({ + id: "missed-2", + sessionId: "sm2", + startTime: new Date("2025-06-03T14:00:00Z"), + endTime: new Date("2025-06-03T14:30:00Z"), + plannedMinutes: 30, + status: "MISSED", + }), + ]; + const result = computeReflow(items, defaultConfig, start, midWindow, [], NY, { includeMissed: true }); + const after = (id: string) => result.changes.find((c) => c.itemId === id)!.after!; + // 2:15 PM, not 2:07:33; the next session follows on the same grid + expect(after("missed")).toMatchObject({ + startTime: "2025-06-04T18:15:00.000Z", + endTime: "2025-06-04T19:05:00.000Z", + }); + expect(after("missed-2").startTime).toBe("2025-06-04T19:05:00.000Z"); + }); + + it("skips today when the rest of its window is under a quarter hour", () => { + // 4:50 PM New York: the next quarter hour is 5:00 PM, when the window closes + const lateNow = new Date("2025-06-04T20:50:00Z"); + const items: ReflowItem[] = [ + makeItem({ + id: "missed", + sessionId: "sm", + startTime: new Date("2025-06-03T13:00:00Z"), + endTime: new Date("2025-06-03T13:30:00Z"), + plannedMinutes: 30, + status: "MISSED", + }), + ]; + const result = computeReflow(items, defaultConfig, start, lateNow, [], NY, { includeMissed: true }); + // Thursday 9:00 AM New York + expect(result.changes[0].after!.startTime).toBe("2025-06-05T13:00:00.000Z"); + }); + + it("schedules past day 6 for plans older than a week", () => { + // Plan started 10 days before now: the first 7 days are all in the past + const oldStart = new Date("2025-05-25T16:00:00Z"); + const items: ReflowItem[] = [ + makeItem({ + id: "future", + sessionId: "sf", + dayIndex: 12, + startTime: new Date("2025-06-06T22:00:00Z"), + endTime: new Date("2025-06-06T23:00:00Z"), + }), + ]; + const result = computeReflow(items, defaultConfig, oldStart, now, [], NY); + expect(result.changes).toHaveLength(1); + expect(result.changes[0].action).not.toBe("DROPPED"); + expect(result.warnings).toHaveLength(0); + }); + + it("keeps sessions before lastDay and skips those that don't fit", () => { + const tight: ReflowConfig = { + availability: Array.from({ length: 7 }, () => ({ start: "09:00", end: "10:00" })), + daily_study_cap_minutes: 60, + }; + const items: ReflowItem[] = ["a", "b", "c"].map((id, i) => + makeItem({ + id, + sessionId: `s-${id}`, + dayIndex: 3 + i, + startTime: new Date(`2025-06-0${5 + i}T13:00:00Z`), + endTime: new Date(`2025-06-0${5 + i}T14:00:00Z`), + }) + ); + // Only Jun 5 and Jun 6 are allowed (the exam is Jun 7) + const result = computeReflow(items, tight, start, now, [], NY, { + includeMissed: true, + lastDay: "2025-06-06", + }); + const dropped = result.changes.filter((c) => c.action === "DROPPED") + const placed = result.changes.filter((c) => c.action !== "DROPPED") + expect(placed).toHaveLength(2); + expect(dropped.map((c) => c.itemId)).toEqual(["c"]); + for (const change of placed) { + expect(change.after!.startTime < "2025-06-07").toBe(true); + } + }); + + it("repeats the weekly availability past day 6", () => { + const config: ReflowConfig = { + availability: [ + { start: "09:00", end: "10:00" }, + ...Array.from({ length: 6 }, () => ({ start: "18:00", end: "19:00" })), + ], + daily_study_cap_minutes: 60, + }; + const items: ReflowItem[] = [ + makeItem({ + id: "x", + sessionId: "sx", + dayIndex: 7, + startTime: new Date("2025-06-09T20:00:00Z"), + endTime: new Date("2025-06-09T21:00:00Z"), + }), + ]; + // Busy every evening, so only the 09:00 windows (day 0, 7, 14) are open + const busy = Array.from({ length: 14 }, (_, d) => { + const day = new Date(Date.UTC(2025, 5, 2 + d, 22, 0)); + return { start: day.getTime(), end: day.getTime() + 60 * 60_000 }; + }); + const result = computeReflow(items, config, start, now, busy, NY, { lastDay: "2025-06-10" }); + expect(result.changes[0].after?.startTime).toBe("2025-06-09T13:00:00.000Z"); + }); + + it("keeps future sessions where they are with includeMissed, unless busy time covers them", () => { + const NY2 = "America/New_York"; + const start2 = new Date("2025-06-02T16:00:00Z"); + const now2 = new Date("2025-06-04T14:00:00Z"); + const items: ReflowItem[] = [ + makeItem({ + id: "missed", + sessionId: "sm", + startTime: new Date("2025-06-03T13:00:00Z"), + endTime: new Date("2025-06-03T14:00:00Z"), + status: "MISSED", + }), + makeItem({ + id: "stays", + sessionId: "ss", + dayIndex: 4, + startTime: new Date("2025-06-06T20:00:00Z"), + endTime: new Date("2025-06-06T21:00:00Z"), + }), + makeItem({ + id: "clash", + sessionId: "sc", + dayIndex: 5, + startTime: new Date("2025-06-07T14:00:00Z"), + endTime: new Date("2025-06-07T15:00:00Z"), + }), + ]; + const busy = [{ start: Date.parse("2025-06-07T13:30:00Z"), end: Date.parse("2025-06-07T16:00:00Z") }]; + const result = computeReflow(items, defaultConfig, start2, now2, busy, NY2, { includeMissed: true }); + const byId = new Map(result.changes.map((c) => [c.itemId, c])); + expect(byId.get("stays")?.action).toBe("KEPT"); + expect(byId.get("missed")?.action).toBe("MOVED"); + expect(byId.get("clash")?.action).toBe("MOVED"); + // The missed session doesn't land on top of the one that stays + const moved = byId.get("missed")!.after!; + const overlaps = + Date.parse(moved.startTime) < Date.parse("2025-06-06T21:00:00Z") && + Date.parse(moved.endTime) > Date.parse("2025-06-06T20:00:00Z"); + expect(overlaps).toBe(false); + }); +}); + +describe("the plan's own Google Calendar events", () => { + const NY = "America/New_York"; + // Plan day 0 is Mon 2026-10-12 in New York + const start = new Date("2026-10-12T16:00:00Z"); + // Thu 2026-10-15, 10:00 New York + const now = new Date("2026-10-15T14:00:00Z"); + const items: ReflowItem[] = [ + makeItem({ + id: "missed", + sessionId: "sm", + dayIndex: 2, + startTime: new Date("2026-10-14T13:00:00Z"), + endTime: new Date("2026-10-14T14:00:00Z"), + }), + makeItem({ + id: "future1", + sessionId: "s1", + dayIndex: 4, + startTime: new Date("2026-10-16T13:00:00Z"), + endTime: new Date("2026-10-16T14:00:00Z"), + }), + // Back to back with future1's day: 20 + 70 minutes, like day 0 of a new plan + makeItem({ + id: "future2", + sessionId: "s2", + dayIndex: 4, + startTime: new Date("2026-10-16T14:00:00Z"), + endTime: new Date("2026-10-16T15:10:00Z"), + plannedMinutes: 70, + }), + ]; + // Free/busy returns the published sessions themselves, merged into one block + const freeBusy = [{ start: Date.parse("2026-10-16T13:00:00Z"), end: Date.parse("2026-10-16T15:10:00Z") }]; + const buffer = 10 * 60_000; + + it("keeps future sessions once their own events are cut out of free/busy", () => { + const own = items.slice(1).map((i) => ({ start: i.startTime.getTime(), end: i.endTime.getTime() })); + const raw = subtractIntervals(freeBusy, own); + expect(raw).toEqual([]); + const buffered = raw.map((b) => ({ start: b.start - buffer, end: b.end + buffer })); + const result = computeReflow(items, defaultConfig, start, now, buffered, NY, { + includeMissed: true, + lastDay: "2026-10-21", + clashIntervals: raw, + }); + const byId = new Map(result.changes.map((c) => [c.itemId, c])); + expect(byId.get("missed")?.action).toBe("MOVED"); + expect(byId.get("future1")?.action).toBe("KEPT"); + expect(byId.get("future2")?.action).toBe("KEPT"); + }); + + it("moves them all when they aren't cut out (the old behavior)", () => { + const buffered = freeBusy.map((b) => ({ start: b.start - buffer, end: b.end + buffer })); + const result = computeReflow(items, defaultConfig, start, now, buffered, NY, { includeMissed: true }); + expect(result.changes.filter((c) => c.action === "MOVED").map((c) => c.itemId).sort()).toEqual([ + "future1", + "future2", + "missed", + ]); + }); + + it("moves a kept session only for a real overlap, not for the buffer around a neighbouring event", () => { + // A real event ends exactly when future1 starts + const raw = [{ start: Date.parse("2026-10-16T12:00:00Z"), end: Date.parse("2026-10-16T13:00:00Z") }]; + const buffered = raw.map((b) => ({ start: b.start - buffer, end: b.end + buffer })); + const result = computeReflow(items, defaultConfig, start, now, buffered, NY, { + includeMissed: true, + clashIntervals: raw, + }); + expect(result.changes.find((c) => c.itemId === "future1")?.action).toBe("KEPT"); + }); +}); + +describe("subtractIntervals", () => { + const iv = (start: number, end: number) => ({ start, end }); + + it("cuts own slots out of merged busy blocks", () => { + expect(subtractIntervals([iv(0, 100)], [iv(20, 40), iv(60, 80)])).toEqual([iv(0, 20), iv(40, 60), iv(80, 100)]); + }); + + it("removes a block an own slot covers and leaves the rest alone", () => { + expect(subtractIntervals([iv(0, 10), iv(20, 30)], [iv(-5, 15)])).toEqual([iv(20, 30)]); + }); + + it("ignores slots outside every block", () => { + expect(subtractIntervals([iv(10, 20)], [iv(0, 5), iv(25, 30)])).toEqual([iv(10, 20)]); + }); +}); + +describe("a session from earlier today", () => { + const NY = "America/New_York"; + const start = new Date("2026-10-12T16:00:00Z"); + // Thu 2026-10-15, 4:00 PM New York + const now = new Date("2026-10-15T20:00:00Z"); + const earlierToday = makeItem({ + id: "today", + sessionId: "st", + dayIndex: 3, + startTime: new Date("2026-10-15T13:00:00Z"), + endTime: new Date("2026-10-15T14:00:00Z"), + }); + + it("isn't missed until its day ends in the plan's zone, as the Plan screen shows it", () => { + expect(isMissedItem(earlierToday, now, NY)).toBe(false); + expect(isMissedItem(earlierToday, new Date("2026-10-16T05:00:00Z"), NY)).toBe(true); + // Without a zone only the time counts + expect(isMissedItem(earlierToday, now)).toBe(true); + }); + + it("stays put on Reschedule, so its Start session button still works", () => { + const result = computeReflow([earlierToday], defaultConfig, start, now, [], NY, { includeMissed: true }); + expect(result.changes).toHaveLength(1); + expect(result.changes[0].action).toBe("KEPT"); + }); }); diff --git a/src/__tests__/reveal-route.test.ts b/src/__tests__/reveal-route.test.ts index 10c29dca..679eef80 100644 --- a/src/__tests__/reveal-route.test.ts +++ b/src/__tests__/reveal-route.test.ts @@ -1,11 +1,11 @@ /** - * Unit tests for GET /api/runs/[runId]/reveal — the answer-standard reveal - * used at self-score time for free-recall prompts. + * Unit tests for /api/runs/[runId]/reveal, the model answer shown at + * self-score time. * - * Contract: authenticated owner only, index validated, service errors map to - * 404/403/409, and the model_answer/key_points payload passes through for - * the happy path (the MCQ pre-answer guard lives in the service and returns - * a null payload — never the answer key). + * Contract: authenticated owner only, index and answer validated, service + * errors map to 404/403/409 with readable messages, GET passes the index + * only (it can never commit an answer), and POST passes the student's + * answer so the service can commit it before revealing. */ import { describe, it, expect, vi, beforeEach } from "vitest"; import type { NextRequest } from "next/server"; @@ -18,12 +18,12 @@ vi.mock("@/services/run", () => ({ getAnswerReveal: vi.fn(), })); -import { GET } from "@/app/api/runs/[runId]/reveal/route"; +import { GET, POST } from "@/app/api/runs/[runId]/reveal/route"; import { getAnswerReveal } from "@/services/run"; const getAnswerRevealMock = vi.mocked(getAnswerReveal); -function makeRequest(index: string | null = "0", userId: string | null = "user-1"): NextRequest { +function makeGet(index: string | null = "0", userId: string | null = "user-1"): NextRequest { const headers: Record<string, string> = {}; if (userId) headers["x-user-id"] = userId; const qs = index === null ? "" : `?index=${index}`; @@ -32,7 +32,17 @@ function makeRequest(index: string | null = "0", userId: string | null = "user-1 }) as unknown as NextRequest; } -const PARAMS = { params: { runId: "run-1" } }; +function makePost(body: unknown, userId: string | null = "user-1"): NextRequest { + const headers: Record<string, string> = { "content-type": "application/json" }; + if (userId) headers["x-user-id"] = userId; + return new Request("http://localhost/api/runs/run-1/reveal", { + method: "POST", + headers, + body: typeof body === "string" ? body : JSON.stringify(body), + }) as unknown as NextRequest; +} + +const PARAMS = { params: Promise.resolve({ runId: "run-1" }) }; describe("GET /api/runs/[runId]/reveal", () => { beforeEach(() => { @@ -40,71 +50,128 @@ describe("GET /api/runs/[runId]/reveal", () => { }); it("returns 401 without a user", async () => { - const res = await GET(makeRequest("0", null), PARAMS); + const res = await GET(makeGet("0", null), PARAMS); expect(res.status).toBe(401); expect(getAnswerRevealMock).not.toHaveBeenCalled(); }); - it("returns 400 for a missing or negative index", async () => { - expect((await GET(makeRequest(null), PARAMS)).status).toBe(400); - expect((await GET(makeRequest("-1"), PARAMS)).status).toBe(400); - expect((await GET(makeRequest("abc"), PARAMS)).status).toBe(400); + it("returns 400 for a missing, negative or non-integer index", async () => { + expect((await GET(makeGet(null), PARAMS)).status).toBe(400); + expect((await GET(makeGet("-1"), PARAMS)).status).toBe(400); + expect((await GET(makeGet("abc"), PARAMS)).status).toBe(400); + expect((await GET(makeGet("1.5"), PARAMS)).status).toBe(400); expect(getAnswerRevealMock).not.toHaveBeenCalled(); }); it("maps not_found to 404 and forbidden to 403", async () => { getAnswerRevealMock.mockResolvedValue({ error: "not_found" }); - expect((await GET(makeRequest(), PARAMS)).status).toBe(404); + expect((await GET(makeGet(), PARAMS)).status).toBe(404); getAnswerRevealMock.mockResolvedValue({ error: "forbidden" }); - expect((await GET(makeRequest(), PARAMS)).status).toBe(403); + expect((await GET(makeGet(), PARAMS)).status).toBe(403); }); it("maps wrong_phase (EXAM) and wrong_index to 409", async () => { getAnswerRevealMock.mockResolvedValue({ error: "wrong_phase", - message: "Answers are revealed after the exam phase", + message: "Model answers appear after the last question of an exam simulation.", }); - expect((await GET(makeRequest(), PARAMS)).status).toBe(409); + expect((await GET(makeGet(), PARAMS)).status).toBe(409); getAnswerRevealMock.mockResolvedValue({ error: "wrong_index", expected: 2 }); - const res = await GET(makeRequest("5"), PARAMS); + const res = await GET(makeGet("5"), PARAMS); + expect(res.status).toBe(409); + expect(await res.json()).toEqual({ + error: "This question was answered in another tab. Reload to continue.", + code: "wrong_index", + expected: 2, + }); + }); + + it("answers 409 answer_required for an unanswered free-recall question", async () => { + getAnswerRevealMock.mockResolvedValue({ error: "answer_required" }); + + const res = await GET(makeGet(), PARAMS); + expect(res.status).toBe(409); - expect(await res.json()).toEqual({ error: "Wrong prompt index", expected: 2 }); + const body = await res.json(); + expect(body.code).toBe("answer_required"); + expect(body).not.toHaveProperty("model_answer"); }); - it("returns model_answer and key_points for the authenticated owner", async () => { + it("never passes an answer to the service, so GET can't commit one", async () => { getAnswerRevealMock.mockResolvedValue({ - data: { model_answer: "Water moves toward solute.", key_points: ["gradient", "membrane"] }, + data: { model_answer: "Water moves toward solute.", key_points: ["gradient"], committed_answer: "x" }, }); - const res = await GET(makeRequest(), PARAMS); + const res = await GET(makeGet(), PARAMS); expect(res.status).toBe(200); - expect(await res.json()).toEqual({ - model_answer: "Water moves toward solute.", - key_points: ["gradient", "membrane"], - }); expect(getAnswerRevealMock).toHaveBeenCalledWith("user-1", "run-1", 0); }); - it("passes through a graceful-absence payload (prompt without key points)", async () => { + it("returns 500 with a readable message when the service throws", async () => { + getAnswerRevealMock.mockRejectedValue(new Error("boom")); + + const res = await GET(makeGet(), PARAMS); + + expect(res.status).toBe(500); + expect(await res.json()).toEqual({ error: "The model answer didn't load. Retry." }); + }); +}); + +describe("POST /api/runs/[runId]/reveal", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("returns 401 without a user", async () => { + const res = await POST(makePost({ index: 0, user_answer: "osmosis" }, null), PARAMS); + expect(res.status).toBe(401); + expect(getAnswerRevealMock).not.toHaveBeenCalled(); + }); + + it("rejects malformed JSON, a blank answer and a bad index", async () => { + expect((await POST(makePost("{not json"), PARAMS)).status).toBe(400); + + const blank = await POST(makePost({ index: 0, user_answer: " " }), PARAMS); + expect(blank.status).toBe(400); + expect((await blank.json()).error).toBe("Write an answer before you check it."); + + const badIndex = await POST(makePost({ index: -1, user_answer: "osmosis" }), PARAMS); + expect(badIndex.status).toBe(400); + expect((await badIndex.json()).error).toBe("This question isn't in the session. Reload to continue."); + + expect(getAnswerRevealMock).not.toHaveBeenCalled(); + }); + + it("passes the trimmed answer to the service and returns the reveal", async () => { getAnswerRevealMock.mockResolvedValue({ - data: { model_answer: null, key_points: null }, + data: { + model_answer: "Water moves toward the higher solute concentration.", + key_points: ["gradient", "membrane"], + committed_answer: "osmosis moves water", + }, }); - const res = await GET(makeRequest(), PARAMS); + const res = await POST(makePost({ index: 3, user_answer: " osmosis moves water " }), PARAMS); expect(res.status).toBe(200); - expect(await res.json()).toEqual({ model_answer: null, key_points: null }); + expect(getAnswerRevealMock).toHaveBeenCalledWith("user-1", "run-1", 3, { + userAnswer: "osmosis moves water", + }); + expect(await res.json()).toEqual({ + model_answer: "Water moves toward the higher solute concentration.", + key_points: ["gradient", "membrane"], + committed_answer: "osmosis moves water", + }); }); - it("returns 500 when the service throws", async () => { - getAnswerRevealMock.mockRejectedValue(new Error("boom")); - - const res = await GET(makeRequest(), PARAMS); + it("maps service errors the same way as GET", async () => { + getAnswerRevealMock.mockResolvedValue({ error: "forbidden" }); + expect((await POST(makePost({ index: 0, user_answer: "a" }), PARAMS)).status).toBe(403); - expect(res.status).toBe(500); - expect(await res.json()).toEqual({ error: "Internal server error" }); + getAnswerRevealMock.mockResolvedValue({ error: "wrong_index", expected: 1 }); + expect((await POST(makePost({ index: 0, user_answer: "a" }), PARAMS)).status).toBe(409); }); }); diff --git a/src/__tests__/run-deck.test.ts b/src/__tests__/run-deck.test.ts new file mode 100644 index 00000000..2e8480a1 --- /dev/null +++ b/src/__tests__/run-deck.test.ts @@ -0,0 +1,52 @@ +/** + * The deck a run starts with: added questions (repairs, pretests, reviews) + * go in front of the mode's own questions, inside the requested count. + */ +import { describe, it, expect } from "vitest"; + +import type { Prompt } from "@/lib/prompts"; +import { assembleDeck, prependBudget } from "@/services/run"; + +const q = (id: string, pack?: string): Prompt => ({ id, text: id, difficulty: 1, meta: pack ? { pack } : undefined }); +const base = Array.from({ length: 10 }, (_, i) => q(`base_${i}`)); +const ids = (prompts: Prompt[]) => prompts.map((p) => p.id); + +describe("assembleDeck", () => { + it("returns the mode's deck unchanged when nothing is added", () => { + const deck = assembleDeck(base, { repairs: [], pretests: [], warmups: [] }, 10); + expect(deck.prompts).toBe(base); + expect(deck.counts).toEqual({ pretests: 0, warmups: 0, repairs: 0 }); + }); + + it("keeps the requested count: added questions replace the deck's last ones", () => { + const deck = assembleDeck( + base, + { repairs: [q("repair_0", "CROSS_SESSION_REPAIR")], pretests: [q("pre_0", "PRE_TEST")], warmups: [q("warm_0", "WARMUP")] }, + 10, + ); + expect(deck.prompts).toHaveLength(10); + expect(ids(deck.prompts).slice(0, 3)).toEqual(["pre_0", "warm_0", "repair_0"]); + expect(ids(deck.prompts).slice(3)).toEqual(ids(base.slice(0, 7))); + expect(deck.counts).toEqual({ pretests: 1, warmups: 1, repairs: 1 }); + }); + + it("fills a tight budget with repairs first, then pretests, then reviews, but orders pretests first", () => { + const budget = prependBudget(10); + const repairs = Array.from({ length: budget }, (_, i) => q(`repair_${i}`, "CROSS_SESSION_REPAIR")); + const deck = assembleDeck( + base, + { repairs: repairs.slice(0, budget - 1), pretests: [q("pre_0", "PRE_TEST"), q("pre_1", "PRE_TEST")], warmups: [q("warm_0", "WARMUP")] }, + 10, + ); + expect(deck.counts).toEqual({ pretests: 1, warmups: 0, repairs: budget - 1 }); + expect(deck.prompts[0].id).toBe("pre_0"); + expect(ids(deck.prompts)).not.toContain("warm_0"); + }); + + it("keeps at least one of the mode's own questions, and adds nothing to a one-question session", () => { + const pretests = [q("pre_0", "PRE_TEST"), q("pre_1", "PRE_TEST")]; + const two = assembleDeck(base, { repairs: [], pretests, warmups: [] }, 2); + expect(ids(two.prompts)).toEqual(["pre_0", "base_0"]); + expect(assembleDeck(base, { repairs: [], pretests, warmups: [] }, 1).prompts).toBe(base); + }); +}); diff --git a/src/__tests__/run-reveal-and-copy.test.ts b/src/__tests__/run-reveal-and-copy.test.ts new file mode 100644 index 00000000..be30b43d --- /dev/null +++ b/src/__tests__/run-reveal-and-copy.test.ts @@ -0,0 +1,256 @@ +/** + * The run service's reveal gate and the question text it writes. + * + * - The model answer is never returned for an unanswered free-recall + * question unless the student's answer comes with the request; that + * answer is committed on the question (first answer wins). + * - Unanswered multiple-choice questions never reveal. + * - Pretest, repair and review questions read as plain sentences: no typed + * dashes, no snake_case topic keys, no repair quoting another repair. + */ +import { describe, it, expect, vi, beforeEach } from "vitest"; + +interface PromptRow { + id: string; + runId: string; + promptIndex: number; + meta: Record<string, unknown> | null; +} + +const store: { + run: { userId: string; currentIndex: number; phase: string; status: string; promptCount: number } | null; + row: PromptRow | null; + attempt: { id: string; userAnswer: string } | null; +} = { run: null, row: null, attempt: null }; + +const updateRow = vi.fn(async ({ where, data }: { where: { id: string }; data: { meta: Record<string, unknown> } }) => { + if (store.row && store.row.id === where.id) store.row = { ...store.row, meta: data.meta }; + return store.row; +}); + +vi.mock("@/lib/db", () => ({ + prisma: { + sessionRun: { findUnique: vi.fn(async () => store.run) }, + sessionRunPrompt: { + findUnique: vi.fn(async () => store.row), + update: (args: { where: { id: string }; data: { meta: Record<string, unknown> } }) => updateRow(args), + }, + sessionAttempt: { findUnique: vi.fn(async () => store.attempt) }, + }, +})); + +import { + getAnswerReveal, + revealGate, + committedAnswerOf, + variantSourceFor, + pretestQuestionText, + crossSessionRepairText, + reviewQuestionText, + humanizeObjectiveKey, +} from "@/services/run"; +import { generateVariantQuestion } from "@/lib/variant-questions"; + +const DASHES = /[\u2013\u2014]/; + +function freeRecallRow(meta: Record<string, unknown> = {}): PromptRow { + return { + id: "row-1", + runId: "run-1", + promptIndex: 0, + meta: { model_answer: "Water moves toward solute.", key_points: ["gradient"], ...meta }, + }; +} + +beforeEach(() => { + vi.clearAllMocks(); + store.run = { userId: "user-1", currentIndex: 0, phase: "ACTIVE", status: "ACTIVE", promptCount: 3 }; + store.row = freeRecallRow(); + store.attempt = null; +}); + +describe("revealGate", () => { + const base = { phase: "ACTIVE", currentIndex: 2, index: 2, isMcq: false, answered: false, committedAnswer: null }; + + it("withholds during the exam phase and for another question", () => { + expect(revealGate({ ...base, phase: "EXAM", userAnswer: "x" })).toEqual({ kind: "wrong_phase" }); + expect(revealGate({ ...base, index: 1, userAnswer: "x" })).toEqual({ kind: "wrong_index", expected: 2 }); + }); + + it("requires an answer before revealing an unanswered free-recall question", () => { + expect(revealGate(base)).toEqual({ kind: "answer_required" }); + expect(revealGate({ ...base, userAnswer: " " })).toEqual({ kind: "answer_required" }); + }); + + it("commits the answer sent with the request", () => { + expect(revealGate({ ...base, userAnswer: " osmosis " })).toEqual({ kind: "reveal", commit: "osmosis" }); + }); + + it("keeps the first committed answer", () => { + expect(revealGate({ ...base, committedAnswer: "first", userAnswer: "second" })).toEqual({ + kind: "reveal", + commit: null, + }); + }); + + it("never reveals an unanswered multiple-choice question", () => { + expect(revealGate({ ...base, isMcq: true, userAnswer: "[A] x" })).toEqual({ kind: "withhold" }); + }); + + it("reveals once an attempt is recorded (exam scoring, answered MCQ)", () => { + expect(revealGate({ ...base, phase: "REVIEW", answered: true })).toEqual({ kind: "reveal", commit: null }); + expect(revealGate({ ...base, isMcq: true, answered: true })).toEqual({ kind: "reveal", commit: null }); + }); +}); + +describe("getAnswerReveal", () => { + it("returns answer_required, not the model answer, when nothing was answered", async () => { + const result = await getAnswerReveal("user-1", "run-1", 0); + expect(result).toEqual({ error: "answer_required" }); + expect(updateRow).not.toHaveBeenCalled(); + }); + + it("commits the answer and reveals the model answer", async () => { + const result = await getAnswerReveal("user-1", "run-1", 0, { userAnswer: "osmosis" }); + + expect(result).toEqual({ + data: { + model_answer: "Water moves toward solute.", + key_points: ["gradient"], + committed_answer: "osmosis", + }, + }); + expect(updateRow).toHaveBeenCalledTimes(1); + expect(store.row?.meta?.committed_answer).toBe("osmosis"); + // The rest of the question's meta survives the commit + expect(store.row?.meta?.model_answer).toBe("Water moves toward solute."); + }); + + it("keeps the first committed answer on a second request", async () => { + await getAnswerReveal("user-1", "run-1", 0, { userAnswer: "first" }); + const again = await getAnswerReveal("user-1", "run-1", 0, { userAnswer: "edited after seeing it" }); + + expect(updateRow).toHaveBeenCalledTimes(1); + expect((again as { data?: { committed_answer?: string | null } }).data?.committed_answer).toBe("first"); + }); + + it("reveals a committed answer's model answer again without an answer (refresh)", async () => { + store.row = freeRecallRow({ committed_answer: "first" }); + const result = await getAnswerReveal("user-1", "run-1", 0); + expect((result as { data?: { model_answer?: string | null } }).data?.model_answer).toBe("Water moves toward solute."); + }); + + it("withholds an unanswered MCQ even with an answer in the request", async () => { + store.row = { ...freeRecallRow(), meta: { format: "MCQ", model_answer: "B names the right choice" } }; + const result = await getAnswerReveal("user-1", "run-1", 0, { userAnswer: "[A] something" }); + expect(result).toEqual({ data: { model_answer: null, key_points: null, committed_answer: null } }); + expect(updateRow).not.toHaveBeenCalled(); + }); + + it("reveals during exam scoring, where the attempt exists", async () => { + store.run = { ...store.run!, phase: "REVIEW" }; + store.attempt = { id: "att-1", userAnswer: "saved in the exam" }; + const result = await getAnswerReveal("user-1", "run-1", 0); + expect(result).toEqual({ + data: { model_answer: "Water moves toward solute.", key_points: ["gradient"], committed_answer: "saved in the exam" }, + }); + }); + + it("refuses during the exam phase and for other users", async () => { + store.run = { ...store.run!, phase: "EXAM" }; + expect(await getAnswerReveal("user-1", "run-1", 0, { userAnswer: "x" })).toMatchObject({ error: "wrong_phase" }); + + store.run = { ...store.run!, phase: "ACTIVE" }; + expect(await getAnswerReveal("someone-else", "run-1", 0, { userAnswer: "x" })).toEqual({ error: "forbidden" }); + }); +}); + +describe("committedAnswerOf", () => { + it("reads only a non-empty string", () => { + expect(committedAnswerOf({ committed_answer: "a" })).toBe("a"); + expect(committedAnswerOf({ committed_answer: " " })).toBeNull(); + expect(committedAnswerOf({ committed_answer: 3 })).toBeNull(); + expect(committedAnswerOf(null)).toBeNull(); + }); +}); + +describe("question text", () => { + it("writes the pretest question from VOICE, without quotes or dashes", () => { + const text = pretestQuestionText("Recursion"); + expect(text).toBe("Pretest: what do you already know about Recursion? Explain as much as you can from memory."); + expect(text).not.toMatch(DASHES); + expect(text).not.toContain("Diagnostic"); + }); + + it("puts the repair question first and keeps From memory", () => { + const withVariant = crossSessionRepairText({ daysSince: 3, variantQuestion: "What is a base case?" }); + expect(withVariant.startsWith("What is a base case?")).toBe(true); + expect(withVariant).toContain("From memory"); + expect(withVariant).toContain("3 days ago"); + + const withOriginal = crossSessionRepairText({ daysSince: 1, originalText: "Define recursion." }); + expect(withOriginal.startsWith("Define recursion.")).toBe(true); + expect(withOriginal).toContain("1 day ago"); + + const today = crossSessionRepairText({ daysSince: 0, originalText: "Define recursion." }); + expect(today).toContain("earlier today"); + + // VOICE: an incorrect answer is an error, and the student wrote a "correction rule". + expect(withOriginal).toContain("You answered this incorrectly 1 day ago."); + expect(crossSessionRepairText({ daysSince: 2 })).toContain("state the correction rule"); + + for (const t of [withVariant, withOriginal, today, crossSessionRepairText({ daysSince: 2 })]) { + expect(t).not.toMatch(/\b(missed|mistake|correct rule)\b/i); + expect(t).not.toMatch(DASHES); + expect(t).not.toMatch(/\b(MISCONCEPTION|misconception error|\d+d ago)\b/); + } + }); + + it("lower-cases a topic's leading article mid-sentence and keeps other capitals", () => { + expect(pretestQuestionText("The box model")).toBe( + "Pretest: what do you already know about the box model? Explain as much as you can from memory." + ); + expect(reviewQuestionText("The French Revolution", null)).toBe( + "From memory: explain the French Revolution and what matters most to remember about it." + ); + expect(pretestQuestionText("CSS specificity")).toContain("about CSS specificity?"); + expect(pretestQuestionText("Theory of mind")).toContain("about Theory of mind?"); + }); + + it("names review topics, never snake_case keys", () => { + expect(humanizeObjectiveKey("photosynthesis_light_reactions")).toBe("Photosynthesis light reactions"); + expect(humanizeObjectiveKey("bigO-notation")).toBe("Big O notation"); + const text = reviewQuestionText(humanizeObjectiveKey("photosynthesis_light_reactions"), 4); + expect(text).toContain("Photosynthesis light reactions"); + expect(text).not.toContain("_"); + expect(text).toContain("4 days ago"); + expect(reviewQuestionText("Stacks", 0)).toContain("earlier today"); + expect(reviewQuestionText("Stacks", null)).not.toContain("last studied"); + }); +}); + +describe("repair variants", () => { + it("retest the original question, not the text of an earlier repair", () => { + const first = generateVariantQuestion(3, "What does a stack frame hold?", "MISCONCEPTION", "Locals and return address"); + // A wrong answer on the repair: its source is the repair's original question + const source = variantSourceFor({ text: first.text, meta: first.meta }); + expect(source).toBe("What does a stack frame hold?"); + + const second = generateVariantQuestion(4, source, "MEMORY", "Locals and return address"); + expect(second.text.startsWith("What does a stack frame hold?")).toBe(true); + expect(second.text.match(/What does a stack frame hold\?/g)).toHaveLength(1); + expect(second.text).toContain("From memory"); + expect(second.text).not.toMatch(DASHES); + }); + + it("carries MCQ choices without naming the right one", () => { + const source = variantSourceFor({ + text: "Which structure is LIFO?", + format: "MCQ", + choices: ["Queue", "Stack", "Heap", "Tree"], + meta: undefined, + }); + expect(source).toBe("Which structure is LIFO? (Choices: A. Queue; B. Stack; C. Heap; D. Tree)"); + expect(source).not.toMatch(/correct/i); + }); +}); diff --git a/src/__tests__/runner-logic.test.ts b/src/__tests__/runner-logic.test.ts new file mode 100644 index 00000000..c6a2d034 --- /dev/null +++ b/src/__tests__/runner-logic.test.ts @@ -0,0 +1,625 @@ +/** + * The study loop's pure logic: attempt payloads, question kinds, the + * keyboard map and the per-question state machine. + */ +import { describe, it, expect } from "vitest" + +import { + MAX_ANSWER_SECONDS, + answerSeconds, + buildErrorLog, + buildExamAnswer, + buildExamScore, + buildMcqAttempt, + buildRecallAttempt, + formatMcqAnswer, + isConfidentError, + mcqCorrectionRule, + needsErrorLog, + parseMcqAnswer, +} from "@/components/session/runner/attempt-payload" +import { + highlightSnippet, + isMcqPrompt, + linkCitations, + parseWorkedExample, + questionKind, + sourceLabel, + splitQuestion, + stripCompletionTrailer, +} from "@/components/session/runner/question-kind" +import { isTypingTarget, matchHotkey, type Binding, type HotkeyEventLike } from "@/components/session/runner/hotkeys" +import { + draftOf, + initialQuestionState, + questionReducer, + type QuestionAction, + type QuestionState, +} from "@/components/session/runner/question-reducer" +import { draftKey, parseDraft } from "@/components/session/runner/storage" +import { needsSavedAnswers, repairsAdded, resultCompletesRun, resultStartsBreak } from "@/components/session/runner/types" +import { feedbackSummary, plainSummaryText } from "@/components/session/runner/question-kind" +import { feedbackStatus } from "@/components/session/runner/use-feedback" +import { questionBindings, type QuestionHotkeys } from "@/components/session/runner/use-question-hotkeys" +import { submitFailure } from "@/components/session/runner/use-question-actions" +import { needsReload, promptUrl } from "@/components/session/runner/api" +import { RichText } from "@/components/session/runner/rich-text" +import { rehypeKeepCitationsWithText } from "@/lib/rehype-keep-citations" +import { renderToStaticMarkup } from "react-dom/server" +import { ApiError } from "@/lib/client-api" + +describe("answer timing", () => { + it("counts whole seconds and stays under the server's 7200 limit", () => { + expect(answerSeconds(1_000, 31_400)).toBe(30) + expect(answerSeconds(0, 3 * 60 * 60 * 1000)).toBe(MAX_ANSWER_SECONDS) + expect(MAX_ANSWER_SECONDS).toBeLessThan(7200) + expect(answerSeconds(5_000, 1_000)).toBe(0) + expect(answerSeconds(Number.NaN, 1_000)).toBe(0) + }) +}) + +describe("multiple-choice answers", () => { + it("are stored as [A] text and parsed back", () => { + expect(formatMcqAnswer(1, "The heap")).toBe("[B] The heap") + expect(parseMcqAnswer("[B] The heap")).toBe(1) + expect(parseMcqAnswer("[D] x")).toBe(3) + expect(parseMcqAnswer("free text")).toBeNull() + expect(parseMcqAnswer(null)).toBeNull() + }) + + it("send the index for server grading, never a score", () => { + const payload = buildMcqAttempt({ index: 4, choiceIndex: 2, choiceText: "Stack", seconds: 12, confidence: null }) + expect(payload).toEqual({ + prompt_index: 4, + user_answer: "[C] Stack", + time_to_answer_seconds: 12, + mcq_choice_index: 2, + }) + expect(payload).not.toHaveProperty("self_score") + }) +}) + +describe("confidence", () => { + it("is sent only when the student rated it", () => { + const unrated = buildRecallAttempt({ + index: 0, answer: "a", score: "CORRECT", seconds: 3, confidence: null, + isPretest: false, isRepair: false, errorLog: null, + }) + expect(unrated).not.toHaveProperty("confidence_rating") + const rated = buildExamAnswer({ index: 0, answer: "a", seconds: 3, confidence: 5 }) + expect(rated.confidence_rating).toBe(5) + }) +}) + +describe("error logs", () => { + it("are needed for misses, except pretest and repair questions outside exam scoring", () => { + expect(needsErrorLog({ score: "CORRECT", isPretest: false, isRepair: false, examScoring: false })).toBe(false) + expect(needsErrorLog({ score: "PARTIAL", isPretest: false, isRepair: false, examScoring: false })).toBe(true) + expect(needsErrorLog({ score: "INCORRECT", isPretest: true, isRepair: false, examScoring: false })).toBe(false) + expect(needsErrorLog({ score: "INCORRECT", isPretest: false, isRepair: true, examScoring: false })).toBe(false) + // The exam score schema always requires one for a miss. + expect(needsErrorLog({ score: "INCORRECT", isPretest: true, isRepair: true, examScoring: true })).toBe(true) + }) + + it("trim the rule and drop an empty similar question", () => { + expect(buildErrorLog({ errorType: "MEMORY", correctionRule: " rule ", similarQuestion: " " })).toEqual({ + error_type: "MEMORY", + correction_rule: "rule", + }) + }) + + it("ride on free recall misses only when the question isn't a pretest or repair", () => { + const log = buildErrorLog({ errorType: "MISCONCEPTION", correctionRule: "r", similarQuestion: "q?" }) + const miss = buildRecallAttempt({ + index: 1, answer: "a", score: "INCORRECT", seconds: 9, confidence: 1, + isPretest: false, isRepair: false, errorLog: log, + }) + expect(miss.error_log).toEqual(log) + const pretest = buildRecallAttempt({ + index: 1, answer: "a", score: "INCORRECT", seconds: 9, confidence: null, + isPretest: true, isRepair: false, errorLog: log, + }) + expect(pretest).not.toHaveProperty("error_log") + expect(pretest.is_pretest).toBe(true) + }) + + it("for exam scoring carry the score kind and no answer", () => { + expect(buildExamScore({ index: 2, score: "CORRECT", errorLog: null })).toEqual({ + prompt_index: 2, + kind: "SCORE", + self_score: "CORRECT", + }) + expect(buildExamScore({ index: 2, score: "INCORRECT", errorLog: mcqCorrectionRule(" Stack ") }).error_log).toEqual({ + error_type: "MISCONCEPTION", + correction_rule: 'The correct answer is "Stack".', + }) + }) + + it("word an exam multiple-choice correction like the server, so error cards stay answerable", () => { + // src/lib/auto-flashcards.ts wraps a "Which of the following" stem only + // when the correction carries this marker; services/run.ts writes the same. + const marker = /the correct answer is\s*"[^"]+"/i + expect(mcqCorrectionRule("A hash table keyed by vertex").correction_rule).toMatch(marker) + expect(mcqCorrectionRule("A hash table keyed by vertex").correction_rule).toBe( + 'The correct answer is "A hash table keyed by vertex".' + ) + }) +}) + +describe("confident errors", () => { + it("need a Sure rating on a miss, never on a pretest", () => { + expect(isConfidentError({ score: "INCORRECT", confidence: 5, isPretest: false })).toBe(true) + expect(isConfidentError({ score: "PARTIAL", confidence: 5, isPretest: false })).toBe(true) + expect(isConfidentError({ score: "INCORRECT", confidence: 4, isPretest: false })).toBe(true) + expect(isConfidentError({ score: "INCORRECT", confidence: 3, isPretest: false })).toBe(false) + expect(isConfidentError({ score: "CORRECT", confidence: 5, isPretest: false })).toBe(false) + expect(isConfidentError({ score: "INCORRECT", confidence: 5, isPretest: true })).toBe(false) + expect(isConfidentError({ score: null, confidence: 5, isPretest: false })).toBe(false) + }) +}) + +describe("question kinds", () => { + const base = { prompt_index: 0, text: "Q" } + + it("reads pack and source markers", () => { + expect(questionKind({ ...base, meta: { pack: "PRE_TEST" } }).type).toBe("pretest") + expect(questionKind({ ...base, source_type: "VARIANT_REPAIR", meta: { original_prompt_text: "Orig" } })).toEqual({ + type: "repair", + original: "Orig", + inSession: true, + }) + expect(questionKind({ ...base, source_type: "ERROR_LOG" })).toMatchObject({ type: "repair", inSession: false }) + expect(questionKind({ ...base, meta: { pack: "WARMUP" } }).type).toBe("review") + expect(questionKind({ ...base, meta: { pack: "WE_COMPLETION_2", step_count: 4 } })).toEqual({ + type: "worked-completion", + missing: 2, + stepCount: 4, + }) + expect(questionKind(base).type).toBe("standard") + }) + + it("treats a choice list it can't draw as free recall", () => { + expect(isMcqPrompt({ ...base, format: "MCQ", choices: ["a", "b", "c", "d"] })).toBe(true) + expect(isMcqPrompt({ ...base, format: "MCQ", choices: [] })).toBe(false) + expect(isMcqPrompt({ ...base, format: "MCQ" })).toBe(false) + }) + + it("splits the question from the instruction after it", () => { + expect(splitQuestion("What is a base case?\n\nFrom memory: answer it.")).toEqual({ + heading: "What is a base case?", + body: "From memory: answer it.", + }) + expect(splitQuestion("One line").body).toBe("") + }) + + it("parses worked examples in the old and new step formats", () => { + const fresh = parseWorkedExample( + "Solve 2x = 4.\n\nStep 1: Divide by 2. Why: Undo the product.\nStep 2: Read x = 2. Why: That is the result.\n\nIn your own words, why does step 2 follow from the steps before it?" + ) + expect(fresh.problem).toBe("Solve 2x = 4.") + expect(fresh.steps).toEqual([ + { action: "Divide by 2", why: "Undo the product" }, + { action: "Read x = 2", why: "That is the result" }, + ]) + expect(fresh.question).toContain("why does step 2 follow") + + const old = parseWorkedExample("P\n\nStep 1: A action \u2014 why: A reason\n\nQ?") + expect(old.steps).toEqual([{ action: "A action", why: "A reason" }]) + }) + + it("removes the missing-steps line the screen draws itself", () => { + expect(stripCompletionTrailer("Problem\n(The final step is missing \u2014 supply it and state why it follows.)")).toBe( + "Problem" + ) + expect(stripCompletionTrailer("Problem\n\nThe last two steps are missing. Write them and say why each follows.")).toBe( + "Problem" + ) + }) +}) + +describe("sources", () => { + it("split highlight marks into segments without HTML", () => { + expect(highlightSnippet("## Heading\nA <<priority queue>> holds **items**")).toEqual([ + { text: "Heading\nA ", mark: false }, + { text: "priority queue", mark: true }, + { text: " holds items", mark: false }, + ]) + const injected = highlightSnippet("<img src=x onerror=alert(1)> <<x>>") + expect(injected[0]).toEqual({ text: "<img src=x onerror=alert(1)> ", mark: false }) + }) + + it("link only citations that have a source", () => { + expect(linkCitations("See [1] and [3].", 2)).toBe("See [1](#source-1) and [3].") + expect(linkCitations("See [1].", 0)).toBe("See [1].") + }) + + it("keep a citation on the line of the word before it", () => { + const tree = { + type: "root", + children: [ + { + type: "element", + tagName: "p", + children: [ + { type: "text", value: "finds that minimum quickly " }, + { type: "element", tagName: "a", properties: { href: "#source-1" }, children: [{ type: "text", value: "1" }] }, + { type: "text", value: " " }, + { type: "element", tagName: "a", properties: { href: "#source-2" }, children: [{ type: "text", value: "2" }] }, + { type: "text", value: ". A FIFO queue " }, + { type: "element", tagName: "a", properties: { href: "https://example.com" }, children: [] }, + ], + }, + ], + } + rehypeKeepCitationsWithText()(tree) + const p = tree.children[0] as { children: { type: string; value?: string; tagName?: string; children?: unknown[] }[] } + expect(p.children.map((c) => c.value ?? c.tagName)).toEqual(["finds that minimum ", "span", ". A FIFO queue ", "a"]) + const span = p.children[1] as unknown as { properties: { className: string[] }; children: { value?: string; tagName?: string }[] } + expect(span.properties.className).toEqual(["whitespace-nowrap"]) + expect(span.children.map((c) => c.value ?? c.tagName)).toEqual(["quickly ", "a", " ", "a"]) + }) + + it("render citations inside a nowrap span with the word before them", () => { + const html = renderToStaticMarkup( + // RichText has no hooks, so calling it directly gives the element to render. + RichText({ + citations: { count: 1, label: () => "Source 1: Lecture 4", active: null, onCite: () => undefined }, + children: "A binary heap finds that minimum quickly [1]. A FIFO queue does not.", + }) + ) + expect(html).toMatch(/minimum <span class="whitespace-nowrap">quickly <button[^>]*aria-label="Source 1: Lecture 4"[^>]*>1<\/button><\/span>\. A FIFO/) + // Without sources nothing is wrapped. + expect(renderToStaticMarkup(RichText({ children: "Plain [1] text." }))).not.toContain("whitespace-nowrap") + }) + + it("label sources with title and page, skipping page 0", () => { + expect(sourceLabel(2, { doc_title: "Lecture 5", page_number: 3 })).toBe("Source 2: Lecture 5, page 3") + expect(sourceLabel(1, { doc_title: "Notes", page_number: 0 })).toBe("Source 1: Notes") + }) +}) + +describe("keyboard map", () => { + const ran: string[] = [] + const bindings: Binding[] = [ + { key: "1", run: () => ran.push("1") }, + { key: "enter", run: () => ran.push("enter") }, + { key: "enter", mod: true, run: () => ran.push("mod-enter") }, + ] + const textarea = { tagName: "TEXTAREA" } as unknown as EventTarget + const button = { tagName: "BUTTON", getAttribute: () => null } as unknown as EventTarget + const radio = { tagName: "INPUT", type: "radio" } as unknown as EventTarget + const press = (over: Partial<HotkeyEventLike>): HotkeyEventLike => ({ + key: "1", + ctrlKey: false, + metaKey: false, + altKey: false, + target: null, + ...over, + }) + + it("ignores single keys while typing, but not Ctrl+Enter", () => { + expect(matchHotkey(press({ key: "1", target: textarea }), bindings)).toBeNull() + expect(matchHotkey(press({ key: "Enter", ctrlKey: true, target: textarea }), bindings)?.key).toBe("enter") + expect(matchHotkey(press({ key: "Enter", ctrlKey: true, target: textarea }), bindings)?.mod).toBe(true) + }) + + it("leaves Enter on a focused button to the button (no double action)", () => { + expect(matchHotkey(press({ key: "Enter", target: button }), bindings)).toBeNull() + expect(matchHotkey(press({ key: "1", target: button }), bindings)?.key).toBe("1") + }) + + it("treats a focused radio as a place for shortcuts", () => { + expect(isTypingTarget(radio)).toBe(false) + expect(matchHotkey(press({ key: "1", target: radio }), bindings)?.key).toBe("1") + }) + + it("skips handled, repeated, composing and Alt presses", () => { + expect(matchHotkey(press({ defaultPrevented: true }), bindings)).toBeNull() + expect(matchHotkey(press({ repeat: true }), bindings)).toBeNull() + expect(matchHotkey(press({ isComposing: true }), bindings)).toBeNull() + expect(matchHotkey(press({ altKey: true }), bindings)).toBeNull() + expect(matchHotkey(press({ key: "1", ctrlKey: true }), bindings)).toBeNull() + }) +}) + +describe("question state", () => { + const run = (state: QuestionState, ...actions: QuestionAction[]) => actions.reduce(questionReducer, state) + const fresh = () => initialQuestionState({ examScoring: false }) + + it("restores a draft into empty fields", () => { + const state = initialQuestionState({ + examScoring: false, + draft: { answer: "typed", correction_rule: "rule", error_type: "MEMORY" }, + }) + expect(state.answer).toBe("typed") + expect(state.correctionRule).toBe("rule") + expect(state.errorType).toBe("MEMORY") + expect(initialQuestionState({ examScoring: false, draft: { error_type: "BOGUS" } }).errorType).toBe("MISCONCEPTION") + }) + + it("starts exam scoring in the scoring step", () => { + expect(initialQuestionState({ examScoring: true, draft: { answer: "x" } })).toMatchObject({ step: "scoring", answer: "" }) + }) + + it("reveals, scores, logs the error and lands on feedback", () => { + const outcome = { score: "INCORRECT" as const, mcq: null, attemptId: "a1", completes: false, startsBreak: false } + const state = run( + fresh(), + { type: "answer", text: "my answer" }, + { type: "rate", value: 5 }, + { type: "reveal_start", seconds: 40 }, + { type: "reveal_done", reveal: { model_answer: " Model ", key_points: ["a", " "], committed_answer: "my answer" } }, + { type: "score", score: "INCORRECT", errorLog: true }, + { type: "correction", text: "The rule" }, + { type: "submit_start" }, + { type: "submit_done", outcome } + ) + expect(state.step).toBe("feedback") + expect(state.seconds).toBe(40) + expect(state.reveal).toEqual({ status: "ready", modelAnswer: "Model", keyPoints: ["a"] }) + expect(state.confidence).toBe(5) + expect(state.outcome).toEqual(outcome) + expect(draftOf(state)).toBeNull() + }) + + it("uses the answer the server committed", () => { + const state = run( + fresh(), + { type: "answer", text: "edited" }, + { type: "reveal_start", seconds: 1 }, + { type: "reveal_done", reveal: { model_answer: null, key_points: null, committed_answer: "first" } } + ) + expect(state.answer).toBe("first") + }) + + it("ignores a second submit while one is in flight", () => { + const pending = run(fresh(), { type: "answer", text: "a" }, { type: "submit_start", seconds: 3 }) + expect(run(pending, { type: "submit_start", seconds: 9 })).toBe(pending) + expect(run(pending, { type: "answer", text: "changed" }).answer).toBe("a") + }) + + it("keeps everything typed when a break blocks the save", () => { + const state = run(fresh(), { type: "answer", text: "keep me" }, { type: "submit_start" }, { type: "submit_blocked" }) + expect(state.pending).toBeNull() + expect(state.answer).toBe("keep me") + expect(draftOf(state)).toEqual({ answer: "keep me" }) + }) + + it("keeps the input and shows the failure when the save fails", () => { + const state = run(fresh(), { type: "answer", text: "a" }, { type: "submit_start" }, { type: "failed", message: "Answer not saved." }) + expect(state).toMatchObject({ pending: null, error: "Answer not saved.", answer: "a", step: "answering" }) + }) + + it("keeps a multiple-choice pick and its rating across a break or refresh", () => { + const picked = run( + initialQuestionState({ examScoring: false, choiceCount: 4 }), + { type: "choose", index: 2 }, + { type: "rate", value: 5 } + ) + const saved = draftOf(picked) + expect(saved).toEqual({ choice: 2, confidence: 5 }) + // Through localStorage and back. + const restored = initialQuestionState({ examScoring: false, draft: parseDraft(JSON.stringify(saved)), choiceCount: 4 }) + expect(restored).toMatchObject({ choice: 2, confidence: 5 }) + // A pick that no longer fits the question, or a rating off the scale, is dropped. + expect(initialQuestionState({ examScoring: false, draft: { choice: 5, confidence: 4 }, choiceCount: 4 })).toMatchObject({ + choice: null, + confidence: null, + }) + // Exam scoring reads the answer saved during the exam, never a draft. + expect(initialQuestionState({ examScoring: true, draft: { choice: 1 }, choiceCount: 4 }).choice).toBeNull() + }) + + it("shows an empty correction rule beside the field and clears it on typing", () => { + const logging = run( + fresh(), + { type: "answer", text: "a" }, + { type: "reveal_start", seconds: 1 }, + { type: "reveal_done", reveal: { model_answer: "m", key_points: null } }, + { type: "score", score: "INCORRECT", errorLog: true }, + { type: "field_error", error: { field: "correction", message: "Write the correction rule first." } } + ) + expect(logging.fieldError).toEqual({ field: "correction", message: "Write the correction rule first." }) + expect(run(logging, { type: "correction", text: "r" }).fieldError).toBeNull() + expect(run(logging, { type: "similar", text: "q" }).fieldError).not.toBeNull() + }) + + it("remembers when only a reload helps, until the next try", () => { + const failed = run( + fresh(), + { type: "answer", text: "a" }, + { type: "submit_start" }, + { type: "failed", message: "x", reload: true } + ) + expect(failed.errorReload).toBe(true) + expect(run(failed, { type: "submit_start" }).errorReload).toBe(false) + expect(run(fresh(), { type: "submit_start" }, { type: "failed", message: "x" }).errorReload).toBe(false) + }) + + it("lets the student change the score from the error log", () => { + const state = run( + fresh(), + { type: "answer", text: "a" }, + { type: "reveal_start", seconds: 1 }, + { type: "reveal_done", reveal: { model_answer: "m", key_points: null } }, + { type: "score", score: "PARTIAL", errorLog: true }, + { type: "change_score" } + ) + expect(state).toMatchObject({ step: "scoring", score: null }) + }) +}) + +describe("submit results", () => { + it("say when the run finished or a break is due", () => { + expect(resultCompletesRun({ status: "COMPLETED" })).toBe(true) + expect(resultCompletesRun({ status: "ACTIVE" })).toBe(false) + expect(resultStartsBreak({ break_state: { on_break: true } })).toBe(true) + expect(resultStartsBreak({ break_state: { on_break: false } })).toBe(false) + expect(resultStartsBreak(null)).toBe(false) + }) +}) + +describe("draft keys", () => { + it("keep the existing localStorage contract", () => { + expect(draftKey("run-1", "ACTIVE", 3)).toBe("draft:run-1:ACTIVE:3") + }) +}) + +describe("stored drafts", () => { + it("keep only fields of the right type", () => { + expect(parseDraft(JSON.stringify({ answer: "a", choice: "2", confidence: 3, error_type: "MEMORY" }))).toEqual({ + answer: "a", + confidence: 3, + error_type: "MEMORY", + }) + expect(parseDraft("not json")).toBeNull() + expect(parseDraft(null)).toBeNull() + }) +}) + +describe("feedback status", () => { + const ok = { status: "OK", excerpts: [], explanation: "x" } + const pending = { status: "PENDING", excerpts: [] } + it("tells a slow poll, a failed load and unavailable feedback apart", () => { + expect(feedbackStatus({ attemptId: null, error: null, data: undefined, polls: 0 })).toEqual({ + status: "idle", + failure: null, + }) + expect(feedbackStatus({ attemptId: "a", error: null, data: undefined, polls: 0 }).status).toBe("loading") + expect(feedbackStatus({ attemptId: "a", error: null, data: pending, polls: 3 }).status).toBe("loading") + expect(feedbackStatus({ attemptId: "a", error: null, data: pending, polls: 25 })).toEqual({ + status: "failed", + failure: "slow", + }) + expect(feedbackStatus({ attemptId: "a", error: new Error("x"), data: undefined, polls: 0 }).failure).toBe("load") + expect( + feedbackStatus({ attemptId: "a", error: null, data: { status: "UNAVAILABLE", excerpts: [] }, polls: 0 }).failure + ).toBe("unavailable") + expect(feedbackStatus({ attemptId: "a", error: null, data: ok, polls: 0 }).status).toBe("ready") + expect(feedbackStatus({ attemptId: "a", error: null, data: { status: "OK", excerpts: [] }, polls: 0 }).status).toBe( + "empty" + ) + }) +}) + +describe("feedback sheet summary", () => { + it("prefers the takeaway, else the explanation's first sentence, without markdown or citations", () => { + expect(feedbackSummary({ key_takeaway: "Use a **priority queue** [1].", explanation: "Long." }, false)).toEqual({ + kind: "takeaway", + text: "Use a priority queue.", + }) + expect( + feedbackSummary({ explanation: "Dijkstra always takes the closest vertex [1]. So it needs a heap [2]." }, false) + ).toEqual({ kind: "explanation", text: "Dijkstra always takes the closest vertex." }) + expect(feedbackSummary({ explanation: "Use a `heap` here. More." }, false)).toEqual({ + kind: "explanation", + text: "Use a heap here.", + }) + // A correct answer shows only a takeaway; its explanation reads in full above. + expect(feedbackSummary({ explanation: "Why it works." }, true)).toBeNull() + expect(feedbackSummary({ key_takeaway: "Keep it." }, true)).toEqual({ kind: "takeaway", text: "Keep it." }) + expect(feedbackSummary({ explanation: " " }, false)).toBeNull() + expect(feedbackSummary(null, false)).toBeNull() + }) + + it("strips links, headings and list markers", () => { + expect(plainSummaryText("## Why\n- See [the notes](http://x) for *more*")).toBe("Why See the notes for more") + }) +}) + +describe("question keys", () => { + const noop = () => undefined + const base: QuestionHotkeys = { + step: "answering", + mcq: true, + choiceCount: 3, + examMcqScorable: false, + shortcutsEnabled: true, + helpOpen: false, + onToggleHelp: noop, + onChoose: noop, + onRate: noop, + onSubmit: noop, + onScore: noop, + onSaveExamMcqScore: noop, + onSaveCorrection: noop, + onContinue: noop, + } + const keys = (input: QuestionHotkeys) => questionBindings(input).map((b) => `${b.mod ? "mod+" : ""}${b.key}`) + + it("pick, rate and submit a multiple-choice answer", () => { + expect(keys(base)).toEqual(["?", "1", "2", "3", "enter", "q", "w", "e"]) + const chosen: number[] = [] + const rated: number[] = [] + const all = questionBindings({ ...base, onChoose: (i) => chosen.push(i), onRate: (v) => rated.push(v) }) + for (const binding of all) if (binding.key !== "?" && binding.key !== "enter") binding.run() + expect(chosen).toEqual([0, 1, 2]) + expect(rated).toEqual([1, 3, 5]) + }) + + it("record no score from the keyboard until the saved exam answer has loaded", () => { + expect(keys({ ...base, step: "scoring", mcq: false, scoringReady: false })).toEqual(["?"]) + expect(keys({ ...base, step: "scoring", examMcqScorable: true, scoringReady: false })).toEqual(["?"]) + expect(keys({ ...base, step: "scoring", examMcqScorable: true, scoringReady: true })).toEqual(["?", "enter"]) + expect(keys({ ...base, step: "scoring", mcq: false, scoringReady: true })).toEqual(["?", "1", "2", "3"]) + }) + + it("keep only Enter bindings when single-key shortcuts are off", () => { + expect(keys({ ...base, shortcutsEnabled: false })).toEqual(["enter"]) + expect(keys({ ...base, mcq: false, shortcutsEnabled: false })).toEqual(["mod+enter"]) + expect(keys({ ...base, step: "scoring", mcq: false })).toEqual(["?", "1", "2", "3"]) + expect(keys({ ...base, step: "error_log" })).toEqual(["?", "mod+enter"]) + expect(keys({ ...base, step: "feedback", shortcutsEnabled: false })).toEqual(["enter"]) + }) +}) + +describe("failed saves", () => { + it("offer Reload instead of Retry when the server already moved on", () => { + const saved = new ApiError("This session changed in another tab. Reload to continue.", 409, { + code: "duplicate_attempt", + }) + expect(submitFailure(saved)).toEqual({ message: "This answer is already saved. Reload to continue.", reload: true }) + const otherTab = new ApiError("This question was answered in another tab. Reload to continue.", 409, { + code: "wrong_index", + }) + expect(submitFailure(otherTab)).toEqual({ message: otherTab.message, reload: true }) + const server = new ApiError("Answer not saved. Retry in a moment.", 500, null) + expect(submitFailure(server)).toEqual({ message: server.message, reload: false }) + expect(needsReload(new ApiError("This question isn't in the session. Reload to continue.", 400, null))).toBe(true) + expect(needsReload(new TypeError("Failed to fetch"))).toBe(false) + }) +}) + +describe("question URLs", () => { + it("give exam scoring its own key, so a copy loaded while answering (no answer key) is never reused", () => { + expect(promptUrl("r 1", 2)).toBe("/api/runs/r%201/prompt?index=2") + expect(promptUrl("r1", 2, "EXAM")).toBe("/api/runs/r1/prompt?index=2") + expect(promptUrl("r1", 2, "ACTIVE")).toBe("/api/runs/r1/prompt?index=2") + expect(promptUrl("r1", 2, "REVIEW")).toBe("/api/runs/r1/prompt?index=2&phase=review") + expect(promptUrl("r1", 2, "REVIEW")).not.toBe(promptUrl("r1", 2, "EXAM")) + }) +}) + +describe("saved exam answers", () => { + it("load while the run is scoring and the payload lacks them", () => { + expect(needsSavedAnswers({ runPhase: "REVIEW", shownPhase: null, hasAttempts: false })).toBe(true) + expect(needsSavedAnswers({ runPhase: "REVIEW", shownPhase: "REVIEW", hasAttempts: true })).toBe(false) + expect(needsSavedAnswers({ runPhase: "EXAM", shownPhase: "EXAM", hasAttempts: false })).toBe(false) + }) + + it("stay loaded while the last scored question shows its feedback", () => { + // The last score completes the run, which leaves REVIEW, but the scored + // question stays on screen until See results. + expect(needsSavedAnswers({ runPhase: "COMPLETE", shownPhase: "REVIEW", hasAttempts: false })).toBe(true) + expect(needsSavedAnswers({ runPhase: "COMPLETE", shownPhase: undefined, hasAttempts: false })).toBe(false) + }) +}) + +describe("repair questions added", () => { + it("count from the starting deck, so a refresh keeps the number", () => { + expect(repairsAdded({ prompt_count: 7, prompts: [1, 2, 3, 4, 5] }, 7)).toBe(2) + expect(repairsAdded({ prompt_count: 5, prompts: [1, 2, 3, 4, 5] }, 5)).toBe(0) + // No deck in the payload: growth since the screen opened. + expect(repairsAdded({ prompt_count: 6 }, 5)).toBe(1) + }) +}) diff --git a/src/__tests__/schedule-intelligence.test.ts b/src/__tests__/schedule-intelligence.test.ts index 4a0d337b..01db35bf 100644 --- a/src/__tests__/schedule-intelligence.test.ts +++ b/src/__tests__/schedule-intelligence.test.ts @@ -5,7 +5,6 @@ import { adjustDurationByMode, fitBlocksScored, estimateBedtime, - findIntradaySpacingViolations, isClassEvent, isRelatedClass, MAX_DURATION_BY_MODE, @@ -355,48 +354,6 @@ describe("estimateBedtime", () => { }); }); -// --------------------------------------------------------------------------- -// findIntradaySpacingViolations -// --------------------------------------------------------------------------- - -describe("findIntradaySpacingViolations", () => { - it("detects same-topic sessions within 1 hour on same day", () => { - const blocks = [ - { dayIndex: 0, topicScope: "Linear Algebra, Matrices", startMinuteOfDay: 540 }, - { dayIndex: 0, topicScope: "Matrices, Determinants", startMinuteOfDay: 570 }, // 30 min gap - ]; - const violations = findIntradaySpacingViolations(blocks, 60); - expect(violations.length).toBeGreaterThan(0); - }); - - it("allows same-topic sessions with sufficient gap", () => { - const blocks = [ - { dayIndex: 0, topicScope: "Linear Algebra", startMinuteOfDay: 540 }, - { dayIndex: 0, topicScope: "Linear Algebra", startMinuteOfDay: 660 }, // 2h gap - ]; - const violations = findIntradaySpacingViolations(blocks, 60); - expect(violations).toHaveLength(0); - }); - - it("ignores different topics on the same day", () => { - const blocks = [ - { dayIndex: 0, topicScope: "Calculus", startMinuteOfDay: 540 }, - { dayIndex: 0, topicScope: "Chemistry", startMinuteOfDay: 570 }, - ]; - const violations = findIntradaySpacingViolations(blocks, 60); - expect(violations).toHaveLength(0); - }); - - it("ignores same-topic sessions on different days", () => { - const blocks = [ - { dayIndex: 0, topicScope: "Linear Algebra", startMinuteOfDay: 540 }, - { dayIndex: 1, topicScope: "Linear Algebra", startMinuteOfDay: 540 }, - ]; - const violations = findIntradaySpacingViolations(blocks, 60); - expect(violations).toHaveLength(0); - }); -}); - // --------------------------------------------------------------------------- // isClassEvent // --------------------------------------------------------------------------- diff --git a/src/__tests__/scripts-hygiene.test.ts b/src/__tests__/scripts-hygiene.test.ts new file mode 100644 index 00000000..d6a33bab --- /dev/null +++ b/src/__tests__/scripts-hygiene.test.ts @@ -0,0 +1,62 @@ +/** + * Guards for the tsx scripts under scripts/. They run outside Next, so they + * neither load .env on their own nor share the app's question templates + * unless they import them. These checks read the source, so they need no + * database and run in `npm run test:unit`. + */ +import { describe, it, expect } from "vitest"; +import { readFileSync } from "fs"; +import path from "path"; + +const root = path.resolve(__dirname, "../.."); +const read = (file: string) => readFileSync(path.join(root, file), "utf8"); + +/** The first `import` statement in a file, ignoring comments and the shebang. */ +function firstImport(source: string): string | undefined { + return source + .split(/\r?\n/) + .map((line) => line.trim()) + .find((line) => line.startsWith("import ")); +} + +describe("scripts that read the database load .env first", () => { + // tsx does not read .env the way Next does. Without dotenv these scripts + // saw DATABASE_URL and AI_PROVIDER as unset, and Prisma fell back to + // libpq defaults instead of the configured database. + it.each(["scripts/worker.ts", "scripts/seed-research.ts"])("%s", (file) => { + expect(firstImport(read(file))).toBe('import "dotenv/config";'); + }); + + it("seed-demo.ts still requires an explicit DATABASE_URL", () => { + // It refuses any database whose name lacks "demo", so it must not pick + // up the dev database from .env. + expect(read("scripts/seed-demo.ts")).not.toMatch(/dotenv/); + }); +}); + +describe("seed-demo.ts writes the app's own question text", () => { + const source = read("scripts/seed-demo.ts"); + + it("uses the shared pretest, review and repair templates", () => { + for (const fn of ["pretestQuestionText(", "reviewQuestionText(", "crossSessionRepairText("]) { + expect(source).toContain(fn); + } + }); + + it("keeps none of the pre-redesign templates", () => { + for (const legacy of [ + "Diagnostic:", + "Before we dive in", + "Quick review", + "Error repair (from", + "key concept behind", + "You missed this question", + ]) { + expect(source).not.toContain(legacy); + } + }); + + it("names review topics by title, falling back to the readable key", () => { + expect(source).toContain("humanizeObjectiveKey(m.key)"); + }); +}); diff --git a/src/__tests__/search-query.test.ts b/src/__tests__/search-query.test.ts index 98801218..cf32e920 100644 --- a/src/__tests__/search-query.test.ts +++ b/src/__tests__/search-query.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from "vitest"; -import { buildFeedbackQuery } from "@/lib/search"; +import { buildFeedbackQuery, questionSearchText } from "@/lib/search"; describe("buildFeedbackQuery", () => { it("combines prompt text and correction rule", () => { @@ -13,6 +13,24 @@ describe("buildFeedbackQuery", () => { expect(q).toContain("Algorithms"); }); + it("puts the topic title first, then the correction rule, then the question", () => { + const q = buildFeedbackQuery("Why does the loop stop?", "The guard turns false", "Loop invariants"); + expect(q).toBe("Loop invariants The guard turns false Why does the loop stop?"); + }); + + it("keeps the topic title when a long question fills the cap", () => { + const question = "Explain in detail ".repeat(30); + const q = buildFeedbackQuery(question, "rule", "CSS specificity"); + expect(q.startsWith("CSS specificity rule")).toBe(true); + expect(q.length).toBeLessThanOrEqual(200); + }); + + it("cuts at a word boundary, so no half word becomes a search term", () => { + const q = buildFeedbackQuery("alpha ".repeat(40) + "omegaomegaomega"); + expect(q.length).toBeLessThanOrEqual(200); + expect(q.endsWith("alpha")).toBe(true); + }); + it("handles missing optional params", () => { const q = buildFeedbackQuery("prompt only"); expect(q).toBe("prompt only"); @@ -28,4 +46,37 @@ describe("buildFeedbackQuery", () => { const q = buildFeedbackQuery(""); expect(q).toBe(""); }); + + it("drops the question templates' own wording", () => { + expect(buildFeedbackQuery("From memory: explain Recursion in 3 to 5 bullets.", null, "Recursion")).toBe( + "Recursion explain Recursion ." + ); + expect( + buildFeedbackQuery( + "Pretest: what do you already know about stacks? Explain as much as you can from memory.", + undefined, + "Stacks" + ) + ).toBe("Stacks stacks?"); + }); +}); + +describe("questionSearchText", () => { + it("keeps a repair question and drops its instructions", () => { + expect( + questionSearchText( + "Why does a binary search need a sorted array?\n\nYou answered this incorrectly 2 days ago. From memory: state the correction rule, say why the error happens, and give a new example where the rule applies." + ) + ).toBe("Why does a binary search need a sorted array?") + }); + + it("drops the review question's reminder of when the topic was studied", () => { + expect( + questionSearchText("From memory: explain Big-O and what matters most to remember about it. You last studied it 3 days ago.") + ).toBe("explain Big-O .") + }); + + it("leaves an ordinary question alone", () => { + expect(questionSearchText("What is the specificity of #nav a?")).toBe("What is the specificity of #nav a?") + }); }); diff --git a/src/__tests__/session-calibration.test.ts b/src/__tests__/session-calibration.test.ts new file mode 100644 index 00000000..1323f51f --- /dev/null +++ b/src/__tests__/session-calibration.test.ts @@ -0,0 +1,124 @@ +import { describe, it, expect } from "vitest"; +import { + answerFit, + confidenceLevel, + MIN_RATED, + summarizeCalibration, +} from "@/components/session/calibration"; +import type { RatedAnswer, SelfScore } from "@/lib/session-types"; + +function answer(index: number, confidence: number | null, score: SelfScore): RatedAnswer { + return { prompt_index: index, confidence, score }; +} + +describe("confidenceLevel", () => { + it("reads the one scale stored as 1, 3 and 5", () => { + expect(confidenceLevel(1)).toBe("guessing"); + expect(confidenceLevel(3)).toBe("unsure"); + expect(confidenceLevel(5)).toBe("sure"); + }); + + it("maps the older five-step values to the nearest level", () => { + expect(confidenceLevel(2)).toBe("unsure"); + expect(confidenceLevel(4)).toBe("sure"); + }); + + it("treats missing and out-of-range values as not rated", () => { + expect(confidenceLevel(null)).toBeNull(); + expect(confidenceLevel(undefined)).toBeNull(); + expect(confidenceLevel(0)).toBeNull(); + expect(confidenceLevel(6)).toBeNull(); + expect(confidenceLevel(Number.NaN)).toBeNull(); + }); +}); + +describe("answerFit", () => { + it("never flags Unsure, whatever the result", () => { + expect(answerFit("unsure", "CORRECT")).toBe("matched"); + expect(answerFit("unsure", "PARTIAL")).toBe("matched"); + expect(answerFit("unsure", "INCORRECT")).toBe("matched"); + }); + + it("calls Sure on an answer that wasn't fully correct overconfident", () => { + expect(answerFit("sure", "CORRECT")).toBe("matched"); + expect(answerFit("sure", "PARTIAL")).toBe("overconfident"); + expect(answerFit("sure", "INCORRECT")).toBe("overconfident"); + }); + + it("does not call a single right guess underconfident", () => { + expect(answerFit("guessing", "CORRECT")).toBe("guessed-right"); + expect(answerFit("guessing", "INCORRECT")).toBe("matched"); + expect(answerFit("guessing", "PARTIAL")).toBe("matched"); + }); +}); + +describe("summarizeCalibration", () => { + it("gives no summary below the minimum number of rated answers", () => { + const summary = summarizeCalibration([answer(0, 5, "INCORRECT"), answer(1, null, "CORRECT")]); + expect(MIN_RATED).toBeGreaterThan(1); + expect(summary.rated).toBe(1); + expect(summary.unrated).toBe(1); + expect(summary.enough).toBe(false); + }); + + it("counts matches, overconfident answers and per-level correct rates", () => { + const summary = summarizeCalibration([ + answer(0, 5, "CORRECT"), + answer(1, 5, "INCORRECT"), + answer(2, 5, "PARTIAL"), + answer(3, 3, "INCORRECT"), + answer(4, 1, "INCORRECT"), + answer(5, null, "CORRECT"), + ]); + expect(summary.enough).toBe(true); + expect(summary.rated).toBe(5); + expect(summary.unrated).toBe(1); + expect(summary.matched).toBe(3); + expect(summary.overconfident).toBe(2); + expect(summary.overconfidentQuestions).toEqual([1, 2]); + expect(summary.underconfident).toBe(0); + + const sure = summary.levels.find((l) => l.level === "sure")!; + expect(sure).toMatchObject({ count: 3, correct: 1, partial: 1, incorrect: 1 }); + expect(sure.correctRate).toBeCloseTo(1 / 3); + const unsure = summary.levels.find((l) => l.level === "unsure")!; + expect(unsure.correctRate).toBe(0); + }); + + it("leaves an unused level without a rate", () => { + const summary = summarizeCalibration([answer(0, 5, "CORRECT"), answer(1, 5, "CORRECT"), answer(2, 3, "CORRECT")]); + expect(summary.levels.find((l) => l.level === "guessing")!.correctRate).toBeNull(); + }); + + it("does not report one or two right guesses as underconfidence", () => { + const summary = summarizeCalibration([ + answer(0, 1, "CORRECT"), + answer(1, 1, "INCORRECT"), + answer(2, 5, "CORRECT"), + ]); + expect(summary.guessedRight).toBe(1); + expect(summary.underconfident).toBe(0); + expect(summary.matched).toBe(2); + }); + + it("reports underconfidence when right guesses form a pattern", () => { + const summary = summarizeCalibration([ + answer(0, 1, "CORRECT"), + answer(1, 1, "CORRECT"), + answer(2, 1, "INCORRECT"), + answer(3, 5, "CORRECT"), + ]); + expect(summary.guessedRight).toBe(2); + expect(summary.underconfident).toBe(2); + }); + + it("keeps guesses below half right out of the underconfident count", () => { + const summary = summarizeCalibration([ + answer(0, 1, "CORRECT"), + answer(1, 1, "INCORRECT"), + answer(2, 1, "INCORRECT"), + answer(3, 1, "INCORRECT"), + ]); + expect(summary.underconfident).toBe(0); + }); +}); diff --git a/src/__tests__/session-create.test.ts b/src/__tests__/session-create.test.ts new file mode 100644 index 00000000..f1abbe08 --- /dev/null +++ b/src/__tests__/session-create.test.ts @@ -0,0 +1,83 @@ +import { afterEach, describe, it, expect, vi } from "vitest"; +import { z } from "zod"; + +/** + * POST /api/sessions: the test break patterns (seconds-long work blocks) + * exist for the test suites only. A deployment rejects them, and treats any + * already stored as the default pattern. Prisma is mocked. + */ +const db = vi.hoisted(() => ({ session: { create: vi.fn() } })); +vi.mock("@/lib/db", () => ({ prisma: db })); +vi.mock("@/services/run", () => ({ getDeckPreview: vi.fn() })); + +import { getBreakConfig, initBreakState, isAllowedBreakType, MAX_BREAK_CYCLES } from "@/lib/breaks"; +import { createSession } from "@/services/session"; + +function body(breakProtocol: { type?: string; cycles?: number }) { + return { + course_name: "CS 2110", + exam_name: "Prelim 1", + mode: "RETRIEVAL", + topic_scope: "Recursion", + planned_minutes: 30, + break_protocol: breakProtocol, + }; +} + +/** A production server, with or without the e2e suite's test auth. */ +function production(testAuth: boolean) { + vi.stubEnv("NODE_ENV", "production"); + vi.stubEnv("ALLOW_TEST_AUTH", testAuth ? "true" : ""); + vi.stubEnv("CI", testAuth ? "true" : ""); + vi.stubEnv("NEXTAUTH_URL", "http://localhost:3300"); +} + +afterEach(() => { + vi.unstubAllEnvs(); + vi.clearAllMocks(); +}); + +describe("break patterns on new sessions", () => { + it("rejects a test pattern in production", async () => { + production(false); + const error = await createSession("user-1", body({ type: "TEST_1_1", cycles: 2 })).catch((e: unknown) => e); + expect(error).toBeInstanceOf(z.ZodError); + expect((error as z.ZodError).issues[0]).toMatchObject({ path: ["break_protocol", "type"] }); + expect(db.session.create).not.toHaveBeenCalled(); + }); + + it("rejects an unknown pattern anywhere", async () => { + await expect(createSession("user-1", body({ type: "1_1" }))).rejects.toBeInstanceOf(z.ZodError); + }); + + it("accepts the real patterns in production", async () => { + production(false); + db.session.create.mockResolvedValue({ sessionId: "s1" }); + await expect(createSession("user-1", body({ type: "25_5", cycles: 2 }))).resolves.toMatchObject({ session_id: "s1" }); + }); + + it("accepts a test pattern while the e2e suite's test auth is on", async () => { + production(true); + db.session.create.mockResolvedValue({ sessionId: "s2" }); + await expect(createSession("user-1", body({ type: "TEST_3_2", cycles: 1 }))).resolves.toMatchObject({ session_id: "s2" }); + }); +}); + +describe("break pattern lookup", () => { + it("honours the test patterns in development and unit tests", () => { + expect(isAllowedBreakType("TEST_1_1")).toBe(true); + expect(getBreakConfig("TEST_1_1").workMinutes).toBeCloseTo(1 / 60, 5); + }); + + it("treats a stored test pattern as the default in production", () => { + production(false); + expect(isAllowedBreakType("TEST_1_1")).toBe(false); + expect(getBreakConfig("TEST_1_1")).toEqual({ workMinutes: 50, breakMinutes: 10 }); + expect(initBreakState({ type: "TEST_3_2", cycles: 2 }).work_duration_seconds).toBe(50 * 60); + }); + + it("caps a stored cycle count", () => { + expect(initBreakState({ type: "25_5", cycles: 1_000_000_000 }).total_cycles).toBe(MAX_BREAK_CYCLES); + expect(initBreakState({ type: "25_5", cycles: 0 }).total_cycles).toBe(1); + }); +}); diff --git a/src/__tests__/session-errors.test.ts b/src/__tests__/session-errors.test.ts new file mode 100644 index 00000000..c4877ccc --- /dev/null +++ b/src/__tests__/session-errors.test.ts @@ -0,0 +1,107 @@ +import { describe, it, expect } from "vitest"; +import { ApiError } from "@/lib/client-api"; +import { + breakStateFromRejection, + sessionErrorCopy, + sessionErrorMessage, + toSessionError, +} from "@/components/session/errors"; + +const BANNED = /Forbidden|Unauthorized|Internal server error|run_not_completed|Request failed|Wrong prompt index|[—–]|!/; + +describe("sessionErrorCopy", () => { + it("never passes the server's raw text through", () => { + const raw = [ + new ApiError("Forbidden", 403), + new ApiError("Unauthorized", 401), + new ApiError("Internal server error", 500), + new ApiError("run_not_completed", 409, { error: "run_not_completed" }), + new ApiError("Wrong prompt index", 409, { error: "Wrong prompt index", expected: 2 }), + new ApiError("Request failed", 502), + ]; + for (const error of raw) { + for (const action of ["start", "submit", "finish", "endBreak", "results", "followups"] as const) { + expect(sessionErrorMessage(error, action)).not.toMatch(BANNED); + } + } + }); + + it("says what didn't happen, then the fix", () => { + const copy = sessionErrorCopy(new ApiError("x", 500), "submit"); + expect(copy.title).toBe("Answer not saved."); + expect(copy.description).toBe("Your answer is still here. Retry in a moment."); + }); + + it("offers sign-in when the session expired", () => { + const copy = sessionErrorCopy(new ApiError("x", 401), "start"); + expect(copy.signIn).toBe(true); + expect(copy.title).toBe("Your sign-in expired."); + }); + + it("explains a start that timed out", () => { + const timeout = Object.assign(new Error("signal timed out"), { name: "TimeoutError" }); + const copy = sessionErrorCopy(timeout, "start"); + expect(copy.title).toBe("Session not started."); + expect(copy.description).toMatch(/longer than a minute/); + }); + + it("treats a network failure as a connection problem", () => { + const copy = sessionErrorCopy(new TypeError("Failed to fetch"), "finish"); + expect(copy.description).toBe("Your answers are saved. Check your connection and retry."); + }); + + it("asks for a reload when another tab answered the question", () => { + const copy = sessionErrorCopy(new ApiError("x", 409, { expected: 3 }), "submit"); + expect(copy.reload).toBe(true); + expect(copy.description).toBe("This question was answered in another tab. Reload to continue."); + }); + + it("says whose session it is on a 403 and that it is gone on a 404", () => { + expect(sessionErrorCopy(new ApiError("x", 403), "results").description).toBe( + "This session belongs to another account." + ); + expect(sessionErrorCopy(new ApiError("x", 404), "results").description).toBe( + "This session doesn't exist anymore. It may have been deleted." + ); + }); + + it("maps the follow-ups conflict to finishing first", () => { + const copy = sessionErrorCopy(new ApiError("run_not_completed", 409), "followups"); + expect(copy.description).toBe("Finish the session before adding follow-ups."); + }); +}); + +describe("toSessionError", () => { + it("keeps status, code and body with the student-facing message", () => { + const original = new ApiError("Forbidden", 403, { error: "Forbidden", code: "forbidden" }); + const mapped = toSessionError(original, "submit"); + expect(mapped).toBeInstanceOf(ApiError); + expect(mapped.status).toBe(403); + expect(mapped.code).toBe("forbidden"); + expect(mapped.message).not.toMatch(/Forbidden/); + }); +}); + +describe("breakStateFromRejection", () => { + const breakState = { + on_break: true, + work_started_at: "2026-10-15T14:00:00Z", + break_started_at: "2026-10-15T14:25:00Z", + current_cycle: 0, + total_cycles: 2, + work_duration_seconds: 1500, + break_duration_seconds: 300, + completed_breaks: [], + }; + + it("reads the break from the 409 body, not from the message text", () => { + const error = new ApiError("Anything at all", 409, { error: "Anything at all", break_state: breakState }); + expect(breakStateFromRejection(error)).toEqual(breakState); + }); + + it("ignores other conflicts and other statuses", () => { + expect(breakStateFromRejection(new ApiError("Cannot submit during break", 409, { expected: 1 }))).toBeNull(); + expect(breakStateFromRejection(new ApiError("x", 400, { break_state: breakState }))).toBeNull(); + expect(breakStateFromRejection(new Error("break"))).toBeNull(); + }); +}); diff --git a/src/__tests__/session-followup-copy.test.ts b/src/__tests__/session-followup-copy.test.ts new file mode 100644 index 00000000..de4df7b5 --- /dev/null +++ b/src/__tests__/session-followup-copy.test.ts @@ -0,0 +1,66 @@ +import { describe, it, expect } from "vitest"; +import { fillMessage, skippedText } from "@/components/session/followup-copy"; + +/** + * Why follow-up days fall away: one whole sentence per plural form, with the + * exam name filled in after the plural is chosen. + */ +const ZONE = "America/New_York"; +const day = (date: string) => ({ date, at: `${date}T16:00:00.000Z`, days_from_now: null }); + +describe("skippedText", () => { + it("names one skipped day in a singular sentence", () => { + const text = skippedText({ exam_name: "Prelim 2", items: [day("2026-10-18")], skipped: [day("2026-10-21")] }, ZONE); + expect(text).toBe("Wed, Oct 21 falls after Prelim 2, so it isn't added."); + }); + + it("lists several skipped days in a plural sentence", () => { + const text = skippedText( + { exam_name: "Prelim 2", items: [day("2026-10-18")], skipped: [day("2026-10-21"), day("2026-10-24")] }, + ZONE + ); + expect(text).toBe("Wed, Oct 21 and Sat, Oct 24 fall after Prelim 2, so they aren't added."); + }); + + it("says there's nothing to add when every day is skipped", () => { + expect(skippedText({ exam_name: null, items: [], skipped: [day("2026-10-21")] }, ZONE)).toBe( + "The follow-up date falls after your exam, so there's nothing to add." + ); + expect( + skippedText({ exam_name: "Final", items: [], skipped: [day("2026-10-21"), day("2026-10-24")] }, ZONE) + ).toBe("The follow-up dates fall after Final, so there's nothing to add."); + }); + + it("says a passed day has passed, not that it falls after the exam", () => { + const past = { ...day("2026-10-14"), reason: "past" as const }; + expect(skippedText({ exam_name: "Prelim 2", items: [day("2026-10-18")], skipped: [past] }, ZONE)).toBe( + "Wed, Oct 14 has passed, so it isn't added." + ); + expect(skippedText({ exam_name: "Prelim 2", items: [], skipped: [past, { ...day("2026-10-16"), reason: "past" }] }, ZONE)).toBe( + "The follow-up dates have passed, so there's nothing to add." + ); + }); + + it("gives each reason its own sentence", () => { + const text = skippedText( + { + exam_name: "Prelim 2", + items: [], + skipped: [{ ...day("2026-10-14"), reason: "past" }, { ...day("2026-10-21"), reason: "past_exam" }], + }, + ZONE + ); + expect(text).toBe("Wed, Oct 21 falls after Prelim 2, so it isn't added. Wed, Oct 14 has passed, so it isn't added."); + }); + + it("keeps a # in the exam name", () => { + const text = skippedText({ exam_name: "Prelim #2", items: [day("2026-10-18")], skipped: [day("2026-10-21")] }, ZONE); + expect(text).toBe("Wed, Oct 21 falls after Prelim #2, so it isn't added."); + }); +}); + +describe("fillMessage", () => { + it("fills each placeholder once and leaves unknown ones", () => { + expect(fillMessage("{a} and {b}", { a: "{b}" })).toBe("{b} and {b}"); + }); +}); diff --git a/src/__tests__/session-heading.test.ts b/src/__tests__/session-heading.test.ts new file mode 100644 index 00000000..8f40a59d --- /dev/null +++ b/src/__tests__/session-heading.test.ts @@ -0,0 +1,75 @@ +import { describe, it, expect } from "vitest"; +import { objectiveTitles, sessionHeading, topicListText } from "@/components/session/session-heading"; + +/** + * The intro and results headings name a session's topics the way the Topics + * row, Home and Plan do (one Intl list), and keep any wording that isn't the + * plan's plain comma join. + */ +describe("sessionHeading", () => { + it("rebuilds a plan's comma-joined scope as an Intl list", () => { + expect(sessionHeading("Retrieval", "CSS specificity, The box model", ["CSS specificity", "The box model"])).toEqual({ + text: "Retrieval: CSS specificity and The box model", + namesAllTopics: true, + }); + expect( + sessionHeading("Interleaved practice", "Recursion, Stacks, Big-O, Queues", ["Recursion", "Stacks", "Big-O", "Queues"]) + .text + ).toBe("Interleaved practice: Recursion, Stacks, Big-O, and Queues"); + }); + + it("names the first three of a long list and counts the rest", () => { + const topics = [ + "CSS specificity", + "The box model", + "Flexbox alignment", + "Grid template areas", + "Responsive images and srcset", + "Media queries", + ]; + expect(sessionHeading("Exam simulation", topics.join(", "), topics)).toEqual({ + text: "Exam simulation: CSS specificity, The box model, Flexbox alignment, and 3 more", + namesAllTopics: false, + }); + }); + + it("keeps a scope that isn't the plain join of the topics", () => { + expect(sessionHeading("Error repair", "Unresolved errors", [])).toEqual({ + text: "Error repair: Unresolved errors", + namesAllTopics: false, + }); + expect(sessionHeading("Interleaved practice", "Recursion and stacks", ["Recursion", "Stacks"]).text).toBe( + "Interleaved practice: Recursion and stacks" + ); + // A scope the server already wrote as a list stays as written. + expect(sessionHeading("Retrieval", "A, B, and C", ["A", "B", "C"]).text).toBe("Retrieval: A, B, and C"); + }); + + it("reads an older follow-up's scope without its Follow-up marker", () => { + expect(sessionHeading("Retrieval", "Follow-up: Recursion, Stacks", ["Recursion", "Stacks"]).text).toBe( + "Retrieval: Recursion and Stacks" + ); + expect(sessionHeading("Retrieval", "Follow-up: Follow-up: Unit tests", []).text).toBe("Retrieval: Unit tests"); + }); + + it("names one topic as it is", () => { + expect(sessionHeading("Retrieval", "End-to-end testing", ["End-to-end testing"])).toEqual({ + text: "Retrieval: End-to-end testing", + namesAllTopics: true, + }); + }); +}); + +describe("topicListText", () => { + it("names one topic past the cap instead of counting it", () => { + expect(topicListText(["A", "B", "C", "D"])).toBe("A, B, C, and D"); + expect(topicListText(["A", "B", "C", "D", "E"])).toBe("A, B, C, and 2 more"); + }); +}); + +describe("objectiveTitles", () => { + it("keeps the non-empty titles, trimmed", () => { + expect(objectiveTitles([{ title: " Recursion " }, { title: "" }, { title: "Stacks" }])).toEqual(["Recursion", "Stacks"]); + expect(objectiveTitles(null)).toEqual([]); + }); +}); diff --git a/src/__tests__/session-next-loads.test.ts b/src/__tests__/session-next-loads.test.ts new file mode 100644 index 00000000..afb7597c --- /dev/null +++ b/src/__tests__/session-next-loads.test.ts @@ -0,0 +1,57 @@ +import { describe, it, expect } from "vitest"; +import { nextLoads } from "@/components/session/next-loads"; + +/** + * After an answer is saved: feedback never waits on the next question, + * except in exam answering, which shows no feedback. + */ +describe("nextLoads", () => { + it("loads the next question in the background after an answer with feedback", () => { + expect(nextLoads({ completed: false, index: 3, promptCount: 8, phase: "ACTIVE", previousPhase: "ACTIVE" })).toEqual({ + nextIndex: 3, + awaitNext: false, + scoringBegins: false, + deckFallback: false, + }); + }); + + it("waits for the next question while answering an exam simulation", () => { + expect(nextLoads({ completed: false, index: 3, promptCount: 8, phase: "EXAM", previousPhase: "EXAM" })).toEqual({ + nextIndex: 3, + awaitNext: true, + scoringBegins: false, + deckFallback: true, + }); + }); + + it("starts scoring after the last exam answer without waiting", () => { + expect(nextLoads({ completed: false, index: 0, promptCount: 8, phase: "REVIEW", previousPhase: "EXAM" })).toEqual({ + nextIndex: 0, + awaitNext: false, + scoringBegins: true, + deckFallback: false, + }); + }); + + it("loads nothing once the run is done with questions", () => { + expect(nextLoads({ completed: true, index: 7, promptCount: 8, phase: "COMPLETE", previousPhase: "ACTIVE" }).nextIndex).toBeNull(); + expect(nextLoads({ completed: false, index: 8, promptCount: 8, phase: "ACTIVE", previousPhase: "ACTIVE" })).toEqual({ + nextIndex: null, + awaitNext: false, + scoringBegins: false, + deckFallback: false, + }); + }); + + // The start-time deck has no answer keys, and adaptation can swap the + // question the server grades, so it may stand in for a failed load only + // while answering an exam simulation. + it("never falls back to the start-time deck outside exam answering", () => { + const scoring = nextLoads({ completed: false, index: 1, promptCount: 8, phase: "REVIEW", previousPhase: "REVIEW" }); + expect(scoring.deckFallback).toBe(false); + const retrieval = nextLoads({ completed: false, index: 4, promptCount: 8, phase: "ACTIVE", previousPhase: "ACTIVE" }); + expect(retrieval.deckFallback).toBe(false); + const exam = nextLoads({ completed: false, index: 4, promptCount: 8, phase: "EXAM", previousPhase: "EXAM" }); + expect(exam).toMatchObject({ awaitNext: true, deckFallback: true }); + }); +}); diff --git a/src/__tests__/session-results-route.test.ts b/src/__tests__/session-results-route.test.ts new file mode 100644 index 00000000..dc775f56 --- /dev/null +++ b/src/__tests__/session-results-route.test.ts @@ -0,0 +1,78 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import type { NextRequest } from "next/server"; + +vi.mock("@/lib/auth", () => ({ + getUserId: vi.fn(async (request: Request) => request.headers.get("x-user-id")), +})); + +vi.mock("@/services/session", () => ({ + getSessionResults: vi.fn(), +})); + +import { GET } from "@/app/api/sessions/[sessionId]/runs/[runId]/results/route"; +import { getSessionResults } from "@/services/session"; + +const getSessionResultsMock = vi.mocked(getSessionResults); + +function call(sessionId: string, runId: string, userId: string | null = "user-1") { + const headers: Record<string, string> = {}; + if (userId) headers["x-user-id"] = userId; + const request = new Request(`http://localhost/api/sessions/${sessionId}/runs/${runId}/results`, { + headers, + }) as unknown as NextRequest; + return GET(request, { params: Promise.resolve({ sessionId, runId }) }); +} + +beforeEach(() => { + getSessionResultsMock.mockReset(); +}); + +describe("GET /api/sessions/:sessionId/runs/:runId/results", () => { + it("needs a signed-in student", async () => { + const res = await call("sess-1", "run-1", null); + expect(res.status).toBe(401); + const body = await res.json(); + expect(body.code).toBe("UNAUTHORIZED"); + expect(body.error).toBe("Your sign-in expired. Sign in again."); + }); + + it("answers malformed IDs with not found, without a lookup", async () => { + const res = await call("sess-1", "../etc"); + expect(res.status).toBe(404); + expect(getSessionResultsMock).not.toHaveBeenCalled(); + }); + + it("maps service errors to statuses and readable messages", async () => { + getSessionResultsMock.mockResolvedValueOnce({ error: "forbidden" }); + expect((await call("sess-1", "run-1")).status).toBe(403); + + getSessionResultsMock.mockResolvedValueOnce({ error: "not_completed" }); + const open = await call("sess-1", "run-1"); + expect(open.status).toBe(409); + expect(await open.json()).toEqual({ + error: "Finish the session to see its results.", + code: "run_not_completed", + }); + + getSessionResultsMock.mockResolvedValueOnce({ error: "not_found" }); + expect((await call("sess-1", "run-1")).status).toBe(404); + }); + + it("returns the results for the owner", async () => { + const data = { run_id: "run-1", session_id: "sess-1" } as never; + getSessionResultsMock.mockResolvedValueOnce({ data }); + const res = await call("sess-1", "run-1"); + expect(res.status).toBe(200); + expect(await res.json()).toEqual(data); + expect(getSessionResultsMock).toHaveBeenCalledWith("user-1", "sess-1", "run-1"); + }); + + it("reports an unexpected failure without the raw error", async () => { + getSessionResultsMock.mockRejectedValueOnce(new Error("connection reset")); + const res = await call("sess-1", "run-1"); + expect(res.status).toBe(500); + const body = await res.json(); + expect(body.error).toBe("Results didn't load. Retry in a moment."); + expect(JSON.stringify(body)).not.toMatch(/connection reset/); + }); +}); diff --git a/src/__tests__/session-results.test.ts b/src/__tests__/session-results.test.ts new file mode 100644 index 00000000..d7fb369b --- /dev/null +++ b/src/__tests__/session-results.test.ts @@ -0,0 +1,387 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; + +/** + * The end screen's data: follow-up dates from the scheduler (anchored to + * when the run ended, so they don't drift after a reload), honest counts + * (pretest and repair questions), and owner checks. Prisma is mocked. + */ +const db = vi.hoisted(() => ({ + session: { findMany: vi.fn(), findUnique: vi.fn() }, + sessionRun: { findUnique: vi.fn(), findFirst: vi.fn() }, + studyPlan: { findMany: vi.fn() }, + studyPlanItem: { findMany: vi.fn(), findFirst: vi.fn() }, + userGameState: { findUnique: vi.fn() }, +})); + +vi.mock("@/lib/db", () => ({ prisma: db })); +const run = vi.hoisted(() => ({ getDeckPreview: vi.fn() })); +vi.mock("@/services/run", () => run); + +import { + compositionFromDeck, + findFollowupPlan, + getFollowupPreview, + getSessionDeckPreview, + getSessionResults, + getSessionScreen, +} from "@/services/session"; + +const USER = "user-1"; +// 2026-10-15 19:00 UTC = 3:00 PM in New York +const ENDED_AT = new Date("2026-10-15T19:00:00Z"); + +beforeEach(() => { + vi.clearAllMocks(); + // Which follow-up days can still be added depends on the current time. + vi.useFakeTimers({ toFake: ["Date"] }); + vi.setSystemTime(ENDED_AT); + db.userGameState.findUnique.mockResolvedValue({ timezone: "America/New_York" }); +}); + +afterEach(() => { + vi.useRealTimers(); +}); + +describe("getFollowupPreview", () => { + it("recommends days in the student's zone when there is no plan", async () => { + db.session.findMany.mockResolvedValue([]); + db.studyPlan.findMany.mockResolvedValue([]); + + const preview = await getFollowupPreview( + USER, + { runId: "run-1", endedAt: ENDED_AT, accuracy: 0.5 }, + "INFO 1300", + "America/New_York", + ); + + expect(preview.status).toBe("no_plan"); + expect(preview.plan_id).toBeNull(); + expect(preview.timezone).toBe("America/New_York"); + // Accuracy under 70% brings follow-ups 1 and 2 days after the run ended. + expect(preview.items.map((i) => i.date)).toEqual(["2026-10-16", "2026-10-17"]); + expect(preview.items[0].at).toBe("2026-10-16T16:00:00.000Z"); + }); + + it("uses the scheduler's plan dates and skips days after the exam", async () => { + db.session.findMany.mockResolvedValue([]); + db.studyPlan.findMany.mockResolvedValue([ + { + planId: "plan-1", + examName: "Prelim 2", + examDate: new Date("2026-10-19T00:00:00Z"), + startDate: new Date("2026-10-10T00:00:00Z"), + timezone: "America/New_York", + config: { availability: Array.from({ length: 7 }, () => ({ start: "14:00", end: "18:00" })) }, + }, + ]); + + const preview = await getFollowupPreview( + USER, + { runId: "run-1", endedAt: ENDED_AT, accuracy: 0.95 }, + "INFO 1300", + "America/New_York", + ); + + expect(preview.status).toBe("not_scheduled"); + expect(preview.exam_name).toBe("Prelim 2"); + // "Open plan" links to the plan the follow-ups would go into. + expect(preview.plan_id).toBe("plan-1"); + // 95% gives days 3 and 6: Oct 18 fits, Oct 21 falls after the exam on Oct 19. + expect(preview.items.map((i) => i.date)).toEqual(["2026-10-18"]); + expect(preview.items[0].at).toBe("2026-10-18T18:00:00.000Z"); + expect(preview.skipped.map((i) => i.date)).toEqual(["2026-10-21"]); + }); + + it("sends instants, not UTC days, when there is no zone and no plan", async () => { + db.session.findMany.mockResolvedValue([]); + db.studyPlan.findMany.mockResolvedValue([]); + // 9:30 PM in New York is already the next day in UTC. + const lateEvening = new Date("2026-10-16T01:30:00Z"); + + const preview = await getFollowupPreview( + USER, + { runId: "run-1", endedAt: lateEvening, accuracy: 0.5 }, + "INFO 1300", + null, + ); + + expect(preview.timezone).toBeNull(); + // The browser formats these in its own zone: Oct 16 and 17 in New York. + expect(preview.items.map((i) => i.at)).toEqual(["2026-10-17T01:30:00.000Z", "2026-10-18T01:30:00.000Z"]); + }); + + it("reads the plan's start as the stored day, so per-day windows line up", async () => { + db.session.findMany.mockResolvedValue([]); + // Day i of the plan starts at 8 AM plus i hours, so each day has its own window. + const availability = Array.from({ length: 14 }, (_, i) => ({ + start: `${String(8 + i).padStart(2, "0")}:00`, + end: "22:00", + })); + db.studyPlan.findMany.mockResolvedValue([ + { + planId: "plan-1", + examName: "Prelim 2", + examDate: new Date("2026-10-25T00:00:00Z"), + startDate: new Date("2026-10-13T00:00:00Z"), + timezone: "America/New_York", + config: { availability }, + }, + ]); + + const preview = await getFollowupPreview( + USER, + { runId: "run-1", endedAt: ENDED_AT, accuracy: 0.5 }, + "INFO 1300", + "America/New_York", + ); + + // Oct 16 is day 3 of a plan that starts Oct 13: 11:00 AM in New York. + // Reading the start through the zone gave Oct 12, day 4 and 12:00 PM. + expect(preview.items[0].date).toBe("2026-10-16"); + expect(preview.items[0].at).toBe("2026-10-16T15:00:00.000Z"); + }); + + it("returns the sessions already in the plan, with links", async () => { + db.session.findMany.mockResolvedValue([ + { sessionId: "fu-1", resources: { followup_of_run_id: "run-1", followup_days_from_now: 2 } }, + ]); + db.studyPlanItem.findMany.mockResolvedValue([ + { + sessionId: "fu-1", + startTime: new Date("2026-10-17T13:00:00Z"), + plan: { planId: "plan-1", timezone: "America/New_York", examName: "Prelim 2" }, + }, + ]); + + const preview = await getFollowupPreview( + USER, + { runId: "run-1", endedAt: ENDED_AT, accuracy: 0.8 }, + "INFO 1300", + "America/New_York", + ); + + expect(preview.status).toBe("scheduled"); + // A reload still links "Open plan" to the plan that holds them. + expect(preview.plan_id).toBe("plan-1"); + expect(preview.items).toEqual([ + { date: "2026-10-17", at: "2026-10-17T13:00:00.000Z", days_from_now: 2, session_id: "fu-1" }, + ]); + expect(db.studyPlan.findMany).not.toHaveBeenCalled(); + }); +}); + +describe("findFollowupPlan", () => { + const plan = (id: string, examDay: string, timezone: string) => ({ + planId: id, + examDate: new Date(`${examDay}T00:00:00Z`), + timezone, + }); + + it("keeps a plan whose exam is today in the plan's zone", async () => { + // 10 PM on Oct 15 in New York, already Oct 16 in UTC. + const now = new Date("2026-10-16T02:00:00Z"); + db.studyPlan.findMany.mockResolvedValue([ + plan("today", "2026-10-15", "America/New_York"), + plan("later", "2026-10-30", "America/New_York"), + ]); + + expect((await findFollowupPlan(USER, "INFO 1300", now))?.planId).toBe("today"); + // The query reaches back one UTC day, the earliest "today" in any zone. + expect(db.studyPlan.findMany.mock.calls[0][0].where.examDate.gte).toEqual(new Date("2026-10-15T00:00:00Z")); + }); + + it("skips a plan whose exam day has passed in its zone", async () => { + const now = new Date("2026-10-16T02:00:00Z"); + db.studyPlan.findMany.mockResolvedValue([ + plan("past", "2026-10-15", "Europe/London"), + plan("later", "2026-10-30", "Europe/London"), + ]); + + expect((await findFollowupPlan(USER, "INFO 1300", now))?.planId).toBe("later"); + }); +}); + +describe("getSessionResults", () => { + function completedRun(overrides: Record<string, unknown> = {}) { + return { + runId: "run-1", + sessionId: "sess-1", + userId: USER, + status: "COMPLETED", + mode: "RETRIEVAL", + metrics: { + attempts_count: 3, + correct_count: 2, + partial_count: 0, + incorrect_count: 1, + accuracy: 2 / 3, + time_spent_seconds: 95, + pretest_count: 1, + }, + prompts: [], + answeredCount: null, + scoredCount: null, + startedAt: new Date("2026-10-15T18:40:00Z"), + endedAt: ENDED_AT, + session: { courseName: "INFO 1300" }, + attempts: [ + { promptIndex: 0, selfScore: "INCORRECT", confidenceRating: 1 }, + { promptIndex: 1, selfScore: "CORRECT", confidenceRating: 5 }, + { promptIndex: 2, selfScore: "INCORRECT", confidenceRating: 5 }, + { promptIndex: 3, selfScore: "CORRECT", confidenceRating: null }, + ], + runPrompts: [ + { promptIndex: 0, sourceType: "GENERATED", meta: { pack: "PRE_TEST" } }, + { promptIndex: 1, sourceType: "GENERATED", meta: null }, + { promptIndex: 2, sourceType: "ERROR_LOG", meta: { pack: "CROSS_SESSION_REPAIR" } }, + { promptIndex: 3, sourceType: "GENERATED", meta: { pack: "WARMUP" } }, + ], + _count: { errorLogs: 1 }, + ...overrides, + }; + } + + it("leaves pretest answers out of the rated answers and counts repairs", async () => { + db.sessionRun.findUnique.mockResolvedValue(completedRun()); + db.session.findMany.mockResolvedValue([]); + db.studyPlan.findMany.mockResolvedValue([]); + + const result = await getSessionResults(USER, "sess-1", "run-1"); + if ("error" in result) throw new Error(result.error); + + expect(result.data.question_count).toBe(4); + expect(result.data.pretest_count).toBe(1); + expect(result.data.repair_count).toBe(1); + expect(result.data.errors_logged).toBe(1); + expect(result.data.answers.map((a) => a.prompt_index)).toEqual([1, 2, 3]); + expect(result.data.followups?.status).toBe("no_plan"); + }); + + it("keeps exam simulation counts", async () => { + db.sessionRun.findUnique.mockResolvedValue( + completedRun({ mode: "EXAM_SIM", answeredCount: 4, scoredCount: 4 }), + ); + db.session.findMany.mockResolvedValue([]); + db.studyPlan.findMany.mockResolvedValue([]); + + const result = await getSessionResults(USER, "sess-1", "run-1"); + if ("error" in result) throw new Error(result.error); + expect(result.data.answered_count).toBe(4); + expect(result.data.scored_count).toBe(4); + }); + + it("refuses other students, other sessions and open runs", async () => { + db.sessionRun.findUnique.mockResolvedValue(completedRun({ userId: "someone-else" })); + expect(await getSessionResults(USER, "sess-1", "run-1")).toEqual({ error: "forbidden" }); + + db.sessionRun.findUnique.mockResolvedValue(completedRun()); + expect(await getSessionResults(USER, "another-session", "run-1")).toEqual({ error: "not_found" }); + + db.sessionRun.findUnique.mockResolvedValue(completedRun({ status: "ACTIVE" })); + expect(await getSessionResults(USER, "sess-1", "run-1")).toEqual({ error: "not_completed" }); + + db.sessionRun.findUnique.mockResolvedValue(null); + expect(await getSessionResults(USER, "sess-1", "run-1")).toEqual({ error: "not_found" }); + }); + + it("skips follow-ups when no answer counted", async () => { + db.sessionRun.findUnique.mockResolvedValue( + completedRun({ metrics: { attempts_count: 0, correct_count: 0, partial_count: 0, incorrect_count: 0, accuracy: 0, time_spent_seconds: 0 } }), + ); + const result = await getSessionResults(USER, "sess-1", "run-1"); + if ("error" in result) throw new Error(result.error); + expect(result.data.followups).toBeNull(); + expect(db.studyPlan.findMany).not.toHaveBeenCalled(); + }); +}); + +describe("deck preview", () => { + const session = { + sessionId: "sess-1", + userId: USER, + courseName: "INFO 1300", + examName: "Prelim 2", + mode: "RETRIEVAL", + topicScope: "Forms", + plannedMinutes: 30, + targetOutcome: { prompt_count: 6 }, + breakProtocol: null, + objectives: null, + runs: [], + }; + const composition = { total: 6, new_count: 6, diagnostic_count: 0, review_count: 0, repair_count: 0 }; + + it("is skipped when the page opens on results", async () => { + db.session.findUnique.mockResolvedValue(session); + db.sessionRun.findFirst.mockResolvedValue({ runId: "run-1", metrics: {}, endedAt: ENDED_AT }); + db.studyPlanItem.findFirst.mockResolvedValue(null); + db.sessionRun.findUnique.mockResolvedValue(null); + + const screen = await getSessionScreen(USER, "sess-1"); + if ("error" in screen) throw new Error(screen.error); + expect(await screen.data.deckPreview).toBeNull(); + expect(run.getDeckPreview).not.toHaveBeenCalled(); + }); + + it("is predicted when the page opens on the intro", async () => { + db.session.findUnique.mockResolvedValue(session); + db.sessionRun.findFirst.mockResolvedValue(null); + db.studyPlanItem.findFirst.mockResolvedValue(null); + run.getDeckPreview.mockResolvedValue(composition); + + const screen = await getSessionScreen(USER, "sess-1"); + if ("error" in screen) throw new Error(screen.error); + expect(await screen.data.deckPreview).toEqual(composition); + expect(run.getDeckPreview).toHaveBeenCalledWith(USER, expect.objectContaining({ promptCount: 6 })); + }); + + it("loads on its own for the owner only", async () => { + db.session.findUnique.mockResolvedValue(session); + run.getDeckPreview.mockResolvedValue(composition); + expect(await getSessionDeckPreview(USER, "sess-1")).toEqual({ data: composition }); + + db.session.findUnique.mockResolvedValue({ ...session, userId: "someone-else" }); + expect(await getSessionDeckPreview(USER, "sess-1")).toEqual({ error: "not_found" }); + }); + + it("reads an open run's deck instead of predicting", async () => { + db.session.findUnique.mockResolvedValue({ + ...session, + runs: [{ prompts: [{ meta: { pack: "PRE_TEST" } }, {}], promptCount: 2 }], + }); + expect(await getSessionDeckPreview(USER, "sess-1")).toEqual({ + data: { total: 2, new_count: 1, diagnostic_count: 1, review_count: 0, repair_count: 0 }, + }); + expect(run.getDeckPreview).not.toHaveBeenCalled(); + }); +}); + +describe("compositionFromDeck", () => { + it("reads an open run's deck the way the preview predicts it", () => { + const deck = [ + { meta: { pack: "PRE_TEST" } }, + { meta: { pack: "WARMUP" } }, + { meta: { pack: "CROSS_SESSION_REPAIR" } }, + { meta: { source_error_log_id: "err-1" } }, + { meta: {} }, + {}, + ]; + expect(compositionFromDeck(deck, 6)).toEqual({ + total: 6, + new_count: 2, + diagnostic_count: 1, + review_count: 1, + repair_count: 2, + }); + }); + + it("copes with a missing deck", () => { + expect(compositionFromDeck(null, 8)).toEqual({ + total: 8, + new_count: 8, + diagnostic_count: 0, + review_count: 0, + repair_count: 0, + }); + }); +}); diff --git a/src/__tests__/settings-request.test.ts b/src/__tests__/settings-request.test.ts new file mode 100644 index 00000000..29dc08ef --- /dev/null +++ b/src/__tests__/settings-request.test.ts @@ -0,0 +1,48 @@ +/** + * Settings write failures: which sentence the student sees, and where a + * failed account deletion is reported (beside the password or below it). + */ +import { describe, it, expect } from "vitest"; +import { ApiError } from "@/lib/client-api"; +import { deleteAccountFailure, failureMessage } from "@/components/settings/request"; + +describe("failureMessage", () => { + it("says the sign-in expired on a 401", () => { + expect(failureMessage(new ApiError("x", 401), "Not saved.")).toBe("Your sign-in expired. Sign in again."); + }); + + it("says how long to wait on a 429", () => { + const error = new ApiError("x", 429, { retry_after_seconds: 1 }); + expect(failureMessage(error, "Not saved.")).toBe("Too many requests. Retry in 1 second."); + }); + + it("falls back to the caller's sentence otherwise", () => { + expect(failureMessage(new TypeError("Failed to fetch"), "Not saved.")).toBe("Not saved."); + }); +}); + +describe("deleteAccountFailure", () => { + it("puts a wrong password beside the password field", () => { + const message = "That password doesn't match your account. Check it and retry."; + const error = new ApiError(message, 403, { error: message, code: "WRONG_PASSWORD" }); + expect(deleteAccountFailure(error)).toEqual({ field: message, general: null }); + }); + + it("reports anything else as a general failure with a fix", () => { + expect(deleteAccountFailure(new TypeError("Failed to fetch"))).toEqual({ + field: null, + general: "Account not deleted. Check your connection and retry.", + }); + expect(deleteAccountFailure(new ApiError("Forbidden", 403))).toEqual({ + field: null, + general: "Account not deleted. Check your connection and retry.", + }); + }); + + it("keeps the shared wording for an expired sign-in and rate limits", () => { + expect(deleteAccountFailure(new ApiError("x", 401)).general).toBe("Your sign-in expired. Sign in again."); + expect(deleteAccountFailure(new ApiError("x", 429, { retry_after_seconds: 30 })).general).toBe( + "Too many requests. Retry in 30 seconds.", + ); + }); +}); diff --git a/src/__tests__/settings-route.test.ts b/src/__tests__/settings-route.test.ts new file mode 100644 index 00000000..7b7e7293 --- /dev/null +++ b/src/__tests__/settings-route.test.ts @@ -0,0 +1,137 @@ +/** + * GET and PUT /api/settings: defaults without writes, merged validation, + * field errors instead of "Validation failed". + */ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import type { NextRequest } from "next/server"; + +vi.mock("@/lib/auth", () => ({ + getUserId: vi.fn(async (request: Request) => request.headers.get("x-user-id")), +})); + +vi.mock("@/lib/db", () => ({ + prisma: { + userGameState: { + findUnique: vi.fn(), + upsert: vi.fn(), + create: vi.fn(), + }, + }, +})); + +import { GET, PUT } from "@/app/api/settings/route"; +import { SETTINGS_FIELD_MESSAGES } from "@/app/api/settings/schema"; +import { prisma } from "@/lib/db"; + +const findState = vi.mocked(prisma.userGameState.findUnique); +const upsertState = vi.mocked(prisma.userGameState.upsert); +const createState = vi.mocked(prisma.userGameState.create); + +const STORED = { + studyStartTime: "14:00", + studyEndTime: "22:00", + dailyStudyCap: 120, + dailyXpGoal: 50, + timezone: "America/New_York", +}; + +function request(method: string, body?: unknown, userId: string | null = "u1"): NextRequest { + return new Request("http://localhost:3000/api/settings", { + method, + headers: { + ...(userId ? { "x-user-id": userId } : {}), + ...(body !== undefined ? { "content-type": "application/json" } : {}), + }, + body: body === undefined ? undefined : typeof body === "string" ? body : JSON.stringify(body), + }) as unknown as NextRequest; +} + +describe("/api/settings", () => { + beforeEach(() => { + vi.clearAllMocks(); + vi.stubEnv("GOOGLE_CLIENT_ID", "client-id"); + }); + + it("answers 401 with a sentence when signed out", async () => { + const res = await GET(request("GET", undefined, null)); + expect(res.status).toBe(401); + expect((await res.json()).error).toBe("Your sign-in expired. Sign in again."); + }); + + it("returns defaults for a student with no row, without creating one", async () => { + findState.mockResolvedValue(null); + const res = await GET(request("GET")); + expect(await res.json()).toEqual({ + studyStart: "09:00", + studyEnd: "17:00", + dailyCap: 180, + dailyXpGoal: 50, + timezone: null, + google_configured: true, + }); + expect(createState).not.toHaveBeenCalled(); + expect(upsertState).not.toHaveBeenCalled(); + }); + + it("returns 500 with a retry sentence when the read fails", async () => { + findState.mockRejectedValue(new Error("db down")); + const res = await GET(request("GET")); + expect(res.status).toBe(500); + expect((await res.json()).error).toBe("Settings didn't load. Retry."); + }); + + it("saves a valid update and returns the saved settings", async () => { + findState.mockResolvedValue(STORED as never); + upsertState.mockImplementation((async ({ update }: { update: Record<string, unknown> }) => ({ + ...STORED, + ...update, + })) as never); + const res = await PUT(request("PUT", { dailyXpGoal: 100, timezone: "Europe/Paris" })); + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ + studyStart: "14:00", + studyEnd: "22:00", + dailyCap: 120, + dailyXpGoal: 100, + timezone: "Europe/Paris", + }); + }); + + it("rejects an end time before the saved start time, per field", async () => { + findState.mockResolvedValue(STORED as never); + const res = await PUT(request("PUT", { studyEnd: "13:00" })); + expect(res.status).toBe(400); + const body = await res.json(); + expect(body.error).toBe("Settings not saved. Check the highlighted fields."); + expect(body.fields).toEqual({ studyEnd: SETTINGS_FIELD_MESSAGES.studyOrder }); + expect(upsertState).not.toHaveBeenCalled(); + }); + + it("maps schema failures and unknown zones to field messages", async () => { + findState.mockResolvedValue(STORED as never); + const bad = await PUT(request("PUT", { studyStart: "", dailyCap: 5 })); + expect((await bad.json()).fields).toEqual({ + studyStart: SETTINGS_FIELD_MESSAGES.studyStart, + dailyCap: SETTINGS_FIELD_MESSAGES.dailyCap, + }); + const zone = await PUT(request("PUT", { timezone: "Not/AZone" })); + expect(zone.status).toBe(400); + expect((await zone.json()).fields).toEqual({ timezone: SETTINGS_FIELD_MESSAGES.timezone }); + }); + + it("clears the zone with an empty string", async () => { + findState.mockResolvedValue(STORED as never); + upsertState.mockImplementation((async ({ update }: { update: Record<string, unknown> }) => ({ + ...STORED, + ...update, + })) as never); + const res = await PUT(request("PUT", { timezone: "" })); + expect((await res.json()).timezone).toBeNull(); + }); + + it("rejects a body that isn't JSON without a raw message", async () => { + const res = await PUT(request("PUT", "{nope")); + expect(res.status).toBe(400); + expect((await res.json()).error).toBe("Settings not saved. Retry."); + }); +}); diff --git a/src/__tests__/settings-schema.test.ts b/src/__tests__/settings-schema.test.ts new file mode 100644 index 00000000..72bf1c2e --- /dev/null +++ b/src/__tests__/settings-schema.test.ts @@ -0,0 +1,101 @@ +/** + * Study settings validation shared by PUT /api/settings and the Settings form. + */ +import { describe, it, expect } from "vitest"; +import { + SETTINGS_DEFAULTS, + SETTINGS_FIELD_MESSAGES, + fieldErrorsFromIssues, + mergeSettings, + normalizeTimezone, + settingsUpdateSchema, + validateSettings, +} from "@/app/api/settings/schema"; + +const valid = { ...SETTINGS_DEFAULTS, timezone: "America/New_York" }; + +describe("validateSettings", () => { + it("accepts the defaults and a known zone", () => { + expect(validateSettings(SETTINGS_DEFAULTS)).toEqual({}); + expect(validateSettings(valid)).toEqual({}); + }); + + it("asks for an end time after the start time", () => { + expect(validateSettings({ ...valid, studyStart: "14:00", studyEnd: "13:00" })).toEqual({ + studyEnd: SETTINGS_FIELD_MESSAGES.studyOrder, + }); + expect(validateSettings({ ...valid, studyStart: "14:00", studyEnd: "14:00" }).studyEnd).toBe( + SETTINGS_FIELD_MESSAGES.studyOrder, + ); + }); + + it("asks for a time when a field is empty, without the order error", () => { + expect(validateSettings({ ...valid, studyStart: "" })).toEqual({ + studyStart: SETTINGS_FIELD_MESSAGES.studyStart, + }); + expect(validateSettings({ ...valid, studyEnd: "" })).toEqual({ + studyEnd: SETTINGS_FIELD_MESSAGES.studyEnd, + }); + }); + + it("keeps the limit and goal inside the server's ranges", () => { + expect(validateSettings({ ...valid, dailyCap: 20 }).dailyCap).toBe(SETTINGS_FIELD_MESSAGES.dailyCap); + expect(validateSettings({ ...valid, dailyCap: 481 }).dailyCap).toBe(SETTINGS_FIELD_MESSAGES.dailyCap); + expect(validateSettings({ ...valid, dailyXpGoal: 5 }).dailyXpGoal).toBe(SETTINGS_FIELD_MESSAGES.dailyXpGoal); + expect(validateSettings({ ...valid, dailyXpGoal: 500 })).toEqual({}); + }); + + it("rejects an unknown time zone with an instruction", () => { + expect(validateSettings({ ...valid, timezone: "Mars/Olympus_Mons" })).toEqual({ + timezone: SETTINGS_FIELD_MESSAGES.timezone, + }); + }); + + it("writes every message as an instruction without dashes or exclamation marks", () => { + for (const message of Object.values(SETTINGS_FIELD_MESSAGES)) { + expect(message).toMatch(/^(Enter|Choose) /); + expect(message).not.toMatch(/[–—!]/); + } + }); +}); + +describe("mergeSettings", () => { + it("applies only the fields sent and treats a blank zone as not set", () => { + expect(mergeSettings(valid, { studyEnd: "20:00" })).toEqual({ ...valid, studyEnd: "20:00" }); + expect(mergeSettings(valid, { timezone: "" }).timezone).toBeNull(); + expect(mergeSettings(valid, { timezone: null }).timezone).toBeNull(); + expect(mergeSettings(valid, {}).timezone).toBe("America/New_York"); + }); + + it("catches an end time that only conflicts with the saved start time", () => { + const current = { ...valid, studyStart: "18:00" }; + expect(validateSettings(mergeSettings(current, { studyEnd: "17:00" })).studyEnd).toBe( + SETTINGS_FIELD_MESSAGES.studyOrder, + ); + }); +}); + +describe("settingsUpdateSchema and fieldErrorsFromIssues", () => { + it("maps zod issues to one message per field", () => { + const parsed = settingsUpdateSchema.safeParse({ studyStart: "9am", dailyCap: 10, dailyXpGoal: "x" }); + expect(parsed.success).toBe(false); + if (parsed.success) return; + expect(fieldErrorsFromIssues(parsed.error.issues)).toEqual({ + studyStart: SETTINGS_FIELD_MESSAGES.studyStart, + dailyCap: SETTINGS_FIELD_MESSAGES.dailyCap, + dailyXpGoal: SETTINGS_FIELD_MESSAGES.dailyXpGoal, + }); + }); + + it("ignores issues on unknown paths", () => { + expect(fieldErrorsFromIssues([{ path: ["other"] }, { path: [] }])).toEqual({}); + }); +}); + +describe("normalizeTimezone", () => { + it("trims and turns blanks into null", () => { + expect(normalizeTimezone(" Europe/Paris ")).toBe("Europe/Paris"); + expect(normalizeTimezone(" ")).toBeNull(); + expect(normalizeTimezone(undefined)).toBeNull(); + }); +}); diff --git a/src/__tests__/shared-shell.test.ts b/src/__tests__/shared-shell.test.ts new file mode 100644 index 00000000..eed8ea2d --- /dev/null +++ b/src/__tests__/shared-shell.test.ts @@ -0,0 +1,172 @@ +import { describe, expect, it } from "vitest" + +import { buildCourseOptions } from "@/hooks/use-course-options" +import { closeFocusOrder, firstConnected, resolveOpener, type FocusTarget } from "@/components/app/return-focus" +import { lessonProgressText } from "@/components/lesson/lesson-frame" +import { ROUTE_TITLES, titleFor } from "@/components/shell/nav-items" +import { sessionFabLabel, showsFloatingFab } from "@/components/shell/session-fab" + +describe("titleFor (the app bar h1)", () => { + it("uses the destination title", () => { + expect(titleFor("/")).toBe("Home") + expect(titleFor("/plan")).toBe("Plan") + expect(titleFor("/flashcards/abc")).toBe("Flashcards") + expect(titleFor("/guides")).toBe("Study guides") + }) + + it("uses the more specific route title, so the server HTML already has it", () => { + expect(titleFor("/plan/new")).toBe("New plan") + expect(titleFor("/plan/materials")).toBe("Materials") + expect(titleFor("/plan/materials/")).toBe("Materials") + expect(titleFor("/design")).toBe("Design system") + expect(Object.keys(ROUTE_TITLES)).toContain("/plan/new") + }) + + it("falls back to the app name outside the destinations", () => { + expect(titleFor("/somewhere")).toBe("Study Bot") + }) +}) + +describe("sessionFabLabel", () => { + it("starts today's session or resumes one under way", () => { + expect(sessionFabLabel(false)).toBe("Start today's session") + expect(sessionFabLabel(true)).toBe("Resume session") + }) +}) + +describe("showsFloatingFab", () => { + it("stays off Home, Chat and Settings on phones, where it would cover their own controls", () => { + expect(showsFloatingFab("/")).toBe(false) + expect(showsFloatingFab("/chat")).toBe(false) + expect(showsFloatingFab("/settings")).toBe(false) + expect(showsFloatingFab("/settings-other")).toBe(true) + expect(showsFloatingFab("/plan")).toBe(true) + expect(showsFloatingFab("/flashcards/abc")).toBe(true) + }) + + it("stays off pages with their own start or save action: Study and the plan forms", () => { + // Study's Start session starts the mode it sets up, not today's session + expect(showsFloatingFab("/learn")).toBe(false) + // The button would sit over the form's fields at 320px + expect(showsFloatingFab("/plan/new")).toBe(false) + expect(showsFloatingFab("/plan/materials")).toBe(false) + expect(showsFloatingFab("/plan")).toBe(true) + expect(showsFloatingFab("/learning")).toBe(true) + }) +}) + +describe("lessonProgressText", () => { + it("uses the singular for one question", () => { + expect(lessonProgressText(0, 1)).toBe("0 of 1 question done") + expect(lessonProgressText(1, 1)).toBe("1 of 1 question done") + }) + + it("uses the plural otherwise", () => { + expect(lessonProgressText(3, 12)).toBe("3 of 12 questions done") + expect(lessonProgressText(0, 0)).toBe("0 of 0 questions done") + }) +}) + +describe("buildCourseOptions", () => { + it("lists courses with a ready file first, then by the latest upload", () => { + const options = buildCourseOptions([ + { course_name: "ECON 1110", exam_name: "Prelim 1", status: "PENDING", created_at: "2026-10-14T10:00:00Z" }, + { course_name: "CS 2110", exam_name: "Prelim 1", status: "PROCESSED", created_at: "2026-10-01T10:00:00Z" }, + { course_name: "INFO 1300", exam_name: null, status: "PROCESSED", created_at: "2026-10-10T10:00:00Z" }, + { course_name: "CS 2110", exam_name: "Prelim 1", status: "FAILED", created_at: "2026-10-02T10:00:00Z" }, + ]) + expect(options.map((o) => o.key)).toEqual(["INFO 1300", "CS 2110||Prelim 1", "ECON 1110||Prelim 1"]) + expect(options[1]).toEqual({ + key: "CS 2110||Prelim 1", + course_name: "CS 2110", + exam_name: "Prelim 1", + doc_count: 2, + ready_count: 1, + }) + expect(options[2].ready_count).toBe(0) + }) + + it("skips files with no course and orders ties by name", () => { + const options = buildCourseOptions([ + { course_name: null, exam_name: null }, + { course_name: "B course", exam_name: null }, + { course_name: "A course", exam_name: null }, + ]) + expect(options.map((o) => o.key)).toEqual(["A course", "B course"]) + }) +}) + +function fakeElement( + connected: boolean, + menuLabelledBy?: string +): FocusTarget & { focused: boolean } { + return { + isConnected: connected, + focused: false, + focus() { + this.focused = true + }, + closest: (selector) => + selector === "[role='menu']" && menuLabelledBy + ? { getAttribute: (name) => (name === "aria-labelledby" ? menuLabelledBy : null) } + : null, + } +} + +describe("return focus after a dialog", () => { + it("returns to the element that had focus", () => { + const button = fakeElement(true) + expect(resolveOpener(button, {}, () => null)).toBe(button) + }) + + it("returns to a menu's trigger when the dialog was opened from a menu item", () => { + const trigger = fakeElement(true) + const item = fakeElement(true, "radix-trigger-1") + expect(resolveOpener(item, {}, (id) => (id === "radix-trigger-1" ? trigger : null))).toBe(trigger) + }) + + it("keeps the item when the menu's trigger can't be found", () => { + const item = fakeElement(true, "missing") + expect(resolveOpener(item, {}, () => null)).toBe(item) + }) + + it("has no opener when focus was on <body>", () => { + const body = fakeElement(true) + expect(resolveOpener(body, body, () => null)).toBeNull() + expect(resolveOpener(null, body, () => null)).toBeNull() + }) + + it("skips an opener that left the page (a deleted row) for the fallback", () => { + const gone = fakeElement(false) + const heading = fakeElement(true) + const main = fakeElement(true) + expect(firstConnected([gone, heading, main])).toBe(heading) + expect(firstConnected([gone, null, main])).toBe(main) + expect(firstConnected([gone, undefined])).toBeNull() + }) + + it("returns to the opener after Cancel or Escape, even when an after-action target exists", () => { + const opener = fakeElement(true) + const heading = fakeElement(true) + const main = fakeElement(true) + const order = closeFocusOrder({ confirmed: false, opener, afterAction: heading, main }) + expect(firstConnected(order)).toBe(opener) + }) + + it("prefers the after-action target once the action ran, though the opener is still on the page", () => { + const opener = fakeElement(true) + const heading = fakeElement(true) + const main = fakeElement(true) + expect(firstConnected(closeFocusOrder({ confirmed: true, opener, afterAction: heading, main }))).toBe(heading) + }) + + it("falls back past a deleted opener, even when the dialog closes before the action settles", () => { + // A row's own dialog unmounts with the row, so its close can run before + // the action is marked as done: the after-action target still wins. + const gone = fakeElement(false) + const heading = fakeElement(true) + const main = fakeElement(true) + expect(firstConnected(closeFocusOrder({ confirmed: false, opener: gone, afterAction: heading, main }))).toBe(heading) + expect(firstConnected(closeFocusOrder({ confirmed: false, opener: gone, afterAction: null, main }))).toBe(main) + }) +}) diff --git a/src/__tests__/storage-delete.test.ts b/src/__tests__/storage-delete.test.ts new file mode 100644 index 00000000..b320f3cd --- /dev/null +++ b/src/__tests__/storage-delete.test.ts @@ -0,0 +1,90 @@ +import { describe, it, expect, beforeAll, afterAll, vi } from "vitest"; +import { mkdtemp, mkdir, rm, stat, writeFile } from "fs/promises"; +import { tmpdir } from "os"; +import { join } from "path"; + +let root: string; +let storage: typeof import("@/lib/storage"); + +async function exists(path: string) { + return stat(path).then( + () => true, + () => false, + ); +} + +beforeAll(async () => { + root = await mkdtemp(join(tmpdir(), "sb-storage-")); + vi.stubEnv("UPLOAD_DIR", root); + vi.resetModules(); + storage = await import("@/lib/storage"); +}); + +afterAll(async () => { + vi.unstubAllEnvs(); + await rm(root, { recursive: true, force: true }); +}); + +describe("deleteStoredFile", () => { + it("removes the document's own folder", async () => { + const key = await storage.saveFile("user-1", "doc-1", "notes.md", Buffer.from("x")); + await storage.deleteStoredFile(key, "doc-1"); + expect(await exists(join(root, "user-1", "doc-1"))).toBe(false); + expect(await exists(join(root, "user-1"))).toBe(true); + }); + + it("refuses a key whose folder isn't that document's", async () => { + await mkdir(join(root, "user-2"), { recursive: true }); + await writeFile(join(root, "user-2", "other.md"), "keep me"); + await expect(storage.deleteStoredFile(join("user-2", "other.md"), "doc-9")).rejects.toThrow(); + await expect(storage.deleteStoredFile("../outside/doc-9/x.md", "doc-9")).rejects.toThrow(); + expect(await exists(join(root, "user-2", "other.md"))).toBe(true); + }); + + it("ignores a missing folder", async () => { + await expect(storage.deleteStoredFile(join("user-3", "doc-3", "gone.pdf"), "doc-3")).resolves.toBeUndefined(); + }); +}); + +describe("saveFile", () => { + it("stores the file under its own folder with a safe name", async () => { + const key = await storage.saveFile("user-4", "doc-4", "Lecture 3 (final).pdf", Buffer.from("x")); + expect(key).toBe(join("user-4", "doc-4", "Lecture_3__final_.pdf")); + expect(await exists(join(root, "user-4", "doc-4", "Lecture_3__final_.pdf"))).toBe(true); + }); + + it("drops folder parts of the name, so ../ can't write outside the document's folder", async () => { + const key = await storage.saveFile("user-5", "doc-5", "../../victim/doc/notes.txt", Buffer.from("x")); + expect(key).toBe(join("user-5", "doc-5", "notes.txt")); + expect(await exists(join(root, "victim"))).toBe(false); + const windowsKey = await storage.saveFile("user-5", "doc-6", "..\\..\\..\\uploads-x\\a.txt", Buffer.from("x")); + expect(windowsKey).toBe(join("user-5", "doc-6", "a.txt")); + }); + + it("refuses ids that would leave the upload folder", async () => { + await expect(storage.saveFile("..", "..", "a.txt", Buffer.from("x"))).rejects.toThrow(); + await expect(storage.saveFile("user-6", "../../outside", "a.txt", Buffer.from("x"))).rejects.toThrow(); + }); +}); + +describe("storedFileName", () => { + it("keeps a plain name and never returns an empty or dot name", () => { + expect(storage.storedFileName("notes.md")).toBe("notes.md"); + expect(storage.storedFileName("..")).toBe("file"); + expect(storage.storedFileName(".env")).toBe("env"); + expect(storage.storedFileName("a/")).toBe("file"); + }); + + it("keeps the end of a very long name, extension included", () => { + const name = storage.storedFileName(`${"x".repeat(300)}.pdf`); + expect(name.length).toBe(120); + expect(name.endsWith(".pdf")).toBe(true); + }); +}); + +describe("resolveStoragePath", () => { + it("refuses keys outside the upload folder, sibling folders included", () => { + expect(() => storage.resolveStoragePath("../uploads-x/a.txt")).toThrow(); + expect(() => storage.resolveStoragePath("")).toThrow(); + }); +}); diff --git a/src/__tests__/study-course-preference.test.ts b/src/__tests__/study-course-preference.test.ts new file mode 100644 index 00000000..508fd660 --- /dev/null +++ b/src/__tests__/study-course-preference.test.ts @@ -0,0 +1,117 @@ +/** + * Which course Study and Study guides open on when the student hasn't + * chosen one (today's session, else the nearest exam, never just the latest + * upload), and the "Planned for today" line when nothing is left to start. + */ +import { describe, expect, it } from "vitest" + +import type { PlanLike } from "@/lib/home-model" +import { coursePreferences } from "@/components/study/course-preference" +import { nothingLeftTodayLine } from "@/lib/study-copy" +import { preferredCourseKey } from "@/components/study/use-preferred-course" + +const ZONE = "America/New_York" +// 9:30pm on Thursday Oct 15 in New York, already Friday Oct 16 in UTC. +const NOW = new Date("2026-10-16T01:30:00Z") + +function item(id: string, start: string, status = "SCHEDULED") { + const startTime = new Date(start) + return { id, sessionId: `s-${id}`, startTime, endTime: new Date(startTime.getTime() + 30 * 60_000), status } +} + +function plan(courseName: string, examName: string, examDateKey: string, items: PlanLike["items"] = []): PlanLike { + return { planId: `${courseName} ${examName}`, courseName, examName, examDateKey, items, lastRescheduledAt: null } +} + +describe("coursePreferences", () => { + it("puts the course with today's open session first, then exams nearest first", () => { + const plans = [ + plan("ECON 1110", "Final", "2026-12-14"), + plan("CS 2110", "Prelim 1", "2026-10-20"), + // 10:30pm Oct 15 in New York: still today there. + plan("INFO 1300", "Prelim 2", "2026-10-22", [item("a", "2026-10-16T02:30:00Z")]), + ] + expect(coursePreferences(plans, ZONE, NOW)).toEqual([ + { courseName: "INFO 1300", examName: "Prelim 2" }, + { courseName: "CS 2110", examName: "Prelim 1" }, + { courseName: "ECON 1110", examName: "Final" }, + ]) + }) + + it("falls back to the nearest exam when today's sessions are done, and drops exams that have passed", () => { + const plans = [ + plan("INFO 1300", "Prelim 2", "2026-10-22", [item("a", "2026-10-15T14:00:00Z", "DONE")]), + plan("CS 2110", "Prelim 1", "2026-10-20"), + plan("BIO 1010", "Prelim 1", "2026-10-14"), + ] + expect(coursePreferences(plans, ZONE, NOW)).toEqual([ + { courseName: "CS 2110", examName: "Prelim 1" }, + { courseName: "INFO 1300", examName: "Prelim 2" }, + ]) + }) + + it("is empty without plans", () => { + expect(coursePreferences([], ZONE, NOW)).toEqual([]) + }) +}) + +describe("preferredCourseKey", () => { + // Ordered as the course switcher lists them: the latest upload first. + const keys = ["ECON 1110||Final", "INFO 1300||Prelim 2", "CS 2110"] + + it("picks the first preference the student has materials for", () => { + expect( + preferredCourseKey(keys, [ + { courseName: "MATH 1920", examName: "Prelim 1" }, + { courseName: "INFO 1300", examName: "Prelim 2" }, + { courseName: "ECON 1110", examName: "Final" }, + ]), + ).toBe("INFO 1300||Prelim 2") + }) + + it("matches materials filed under the course alone", () => { + expect(preferredCourseKey(keys, [{ courseName: "CS 2110", examName: "Prelim 1" }])).toBe("CS 2110") + }) + + it("returns null when no preference has materials, so the first course stays the default", () => { + expect(preferredCourseKey(keys, [{ courseName: "MATH 1920", examName: "Final" }])).toBeNull() + expect(preferredCourseKey(keys, [])).toBeNull() + }) +}) + +describe("nothingLeftTodayLine", () => { + const next = "Retrieval, Wed, Oct 21 at 11:00 AM" + + it("says no sessions today when none were planned today", () => { + expect(nothingLeftTodayLine("ECON 1110", { planned: 0, done: 0 }, next)).toBe( + "No ECON 1110 sessions today. Next: Retrieval, Wed, Oct 21 at 11:00 AM.", + ) + }) + + it("says today's sessions are done when every one is done", () => { + expect(nothingLeftTodayLine("ECON 1110", { planned: 1, done: 1 }, next)).toBe( + "Today's ECON 1110 session is done. Next: Retrieval, Wed, Oct 21 at 11:00 AM.", + ) + expect(nothingLeftTodayLine("ECON 1110", { planned: 2, done: 2 }, null)).toBe( + "Today's ECON 1110 sessions are done, and nothing else is scheduled.", + ) + }) + + it("says none are left when today's were missed or skipped", () => { + expect(nothingLeftTodayLine("ECON 1110", { planned: 2, done: 1 }, next)).toBe( + "No ECON 1110 sessions left today. Next: Retrieval, Wed, Oct 21 at 11:00 AM.", + ) + }) + + it("says the plan has nothing more when nothing comes next", () => { + expect(nothingLeftTodayLine("ECON 1110", { planned: 0, done: 0 }, null)).toBe( + "No more sessions planned for ECON 1110.", + ) + }) + + it("keeps a # in the course name", () => { + expect(nothingLeftTodayLine("C# 101", { planned: 1, done: 1 }, null)).toBe( + "Today's C# 101 session is done, and nothing else is scheduled.", + ) + }) +}) diff --git a/src/__tests__/study-guides-list.test.ts b/src/__tests__/study-guides-list.test.ts new file mode 100644 index 00000000..19e5c05d --- /dev/null +++ b/src/__tests__/study-guides-list.test.ts @@ -0,0 +1,126 @@ +/** + * The guide list stays small however often a guide is regenerated: only the + * newest guide of each format carries its sections, and any one guide loads + * on its own through getStudyGuide. + */ +import { describe, it, expect, vi, beforeEach } from "vitest"; + +interface GuideRow { + id: string; + userId: string; + courseName: string; + examName: string | null; + guideType: string; + title: string; + createdAt: Date; + content: unknown; +} + +vi.mock("@/lib/db", () => { + const state = { rows: [] as GuideRow[] }; + const pick = (row: GuideRow, select?: Record<string, boolean>) => + select ? Object.fromEntries(Object.keys(select).map((k) => [k, row[k as keyof GuideRow]])) : row; + return { + prisma: { + studyGuide: { + findMany: vi.fn( + async (args: { where: { userId: string; id?: { in: string[] } }; select?: Record<string, boolean> }) => + state.rows + .filter((r) => r.userId === args.where.userId) + .filter((r) => !args.where.id || args.where.id.in.includes(r.id)) + .sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime()) + .map((r) => pick(r, args.select)), + ), + findFirst: vi.fn( + async (args: { where: { id: string; userId: string }; select?: Record<string, boolean> }) => { + const row = state.rows.find((r) => r.id === args.where.id && r.userId === args.where.userId); + return row ? pick(row, args.select) : null; + }, + ), + }, + _test: state, + }, + }; +}); + +// Generation isn't under test here. +vi.mock("@/lib/ai/gateway", () => ({ runTask: vi.fn() })); +vi.mock("@/lib/ai/prompt-registry", () => ({ getPrompt: vi.fn() })); +vi.mock("@/lib/ai/provider-factory", () => ({ createProvider: vi.fn() })); + +import { prisma } from "@/lib/db"; +import { getStudyGuide, listStudyGuides } from "@/services/study-guides"; + +const state = (prisma as unknown as { _test: { rows: GuideRow[] } })._test; + +function row(id: string, guideType: string, day: number, userId = "user1"): GuideRow { + return { + id, + userId, + courseName: "INFO 1300", + examName: "Prelim 2", + guideType, + title: `${guideType} ${id}`, + createdAt: new Date(`2026-10-${String(day).padStart(2, "0")}T15:00:00Z`), + content: [{ concept: `Concept from ${id}`, explanation: "Text" }], + }; +} + +beforeEach(() => { + vi.clearAllMocks(); + state.rows = [ + row("kc-old", "KEY_CONCEPTS", 1), + row("faq", "FAQ", 2), + row("kc-new", "KEY_CONCEPTS", 3), + row("kc-mid", "KEY_CONCEPTS", 2), + row("bogus", "MIND_MAP", 4), + row("theirs", "CHEAT_SHEET", 5, "user2"), + ]; +}); + +describe("listStudyGuides", () => { + it("lists every version, newest first, with sections only on the newest of each format", async () => { + const guides = await listStudyGuides("user1", "INFO 1300", "Prelim 2"); + + expect(guides.map((g) => g.id)).toEqual(["kc-new", "faq", "kc-mid", "kc-old"]); + expect(guides.map((g) => g.sections !== undefined)).toEqual([true, true, false, false]); + expect(guides[0].sections).toEqual([{ concept: "Concept from kc-new", explanation: "Text" }]); + expect(guides[2]).not.toHaveProperty("sections"); + expect(guides[0]).toMatchObject({ + guide_type: "KEY_CONCEPTS", + course_name: "INFO 1300", + exam_name: "Prelim 2", + created_at: "2026-10-03T15:00:00.000Z", + }); + }); + + it("reads content only for the guides that carry it", async () => { + await listStudyGuides("user1", "INFO 1300"); + const calls = vi.mocked(prisma.studyGuide.findMany).mock.calls as unknown as [ + { where: { id?: { in: string[] } }; select: Record<string, boolean> }, + ][]; + expect(calls).toHaveLength(2); + expect(calls[0][0].select).not.toHaveProperty("content"); + expect(calls[1][0].where.id?.in.sort()).toEqual(["faq", "kc-new"]); + }); + + it("skips the content query when there are no guides", async () => { + state.rows = []; + expect(await listStudyGuides("user1", "INFO 1300")).toEqual([]); + expect(prisma.studyGuide.findMany).toHaveBeenCalledTimes(1); + }); +}); + +describe("getStudyGuide", () => { + it("returns one guide with its sections", async () => { + const guide = await getStudyGuide("user1", "kc-old"); + expect(guide?.id).toBe("kc-old"); + expect(guide?.sections).toEqual([{ concept: "Concept from kc-old", explanation: "Text" }]); + }); + + it("returns null for another account's guide, a missing one, or an unknown format", async () => { + expect(await getStudyGuide("user1", "theirs")).toBeNull(); + expect(await getStudyGuide("user1", "nope")).toBeNull(); + expect(await getStudyGuide("user1", "bogus")).toBeNull(); + }); +}); diff --git a/src/__tests__/study-recommendations.test.ts b/src/__tests__/study-recommendations.test.ts index 25fe8f5e..dd4ee5cf 100644 --- a/src/__tests__/study-recommendations.test.ts +++ b/src/__tests__/study-recommendations.test.ts @@ -1,5 +1,7 @@ /** - * Unit tests for the study recommendations service — study streak computation. + * Unit tests for the study recommendations service: the streak, the + * recommended session (mode, topic titles, reason copy), planned sessions + * in the student's time zone, and starting a session from the Study screen. */ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; @@ -9,34 +11,91 @@ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; process.env.TZ = "Asia/Tokyo"; interface RunRow { - endedAt: Date | null; + sessionId: string; + status: string; } -interface GameStateHolder { - row: { timezone: string | null } | null; +interface PlanItemRow { + sessionId: string; + status: string; + dayIndex: number; + startTime: Date; + endTime: Date; +} + +interface PlanRow { + planId: string; + examName: string; + examDate: Date; + timezone: string; + config: unknown; + items: PlanItemRow[]; +} + +interface TestState { + /** Session runs in any status; the service asks for the ones under way. */ + runs: RunRow[]; + gameState: { row: { timezone: string | null } | null }; + errors: { runId: string; promptIndex: number; errorType: string }[]; + plan: PlanRow | null; + /** More plans for the same course (other exams). */ + otherPlans: PlanRow[]; + sessions: { objectives: unknown }[]; + nudgeSessions: { sessionId: string; mode: string; topicScope: string; objectives?: unknown }[]; + prompts: { runId: string; promptIndex: number; objectiveId: string | null }[]; + docs: { examName: string | null; status: string }[]; + existingSession: { sessionId: string } | null; + plannedItem: { id: string } | null; } // Mock prisma before importing the service vi.mock("@/lib/db", () => { - const completedRuns: RunRow[] = []; - const gameState: GameStateHolder = { row: null }; + const state: TestState = { + runs: [], + gameState: { row: null }, + errors: [], + plan: null, + otherPlans: [], + sessions: [], + nudgeSessions: [], + prompts: [], + docs: [], + existingSession: null, + plannedItem: null, + }; return { prisma: { sessionRun: { - findMany: vi.fn(async () => completedRuns), - }, - sessionErrorLog: { - findMany: vi.fn(async () => []), + findMany: vi.fn( + async (args: { where?: { sessionId?: { in?: string[] }; status?: { in?: string[] } } }) => + state.runs.filter( + (run) => + (!args?.where?.sessionId?.in || args.where.sessionId.in.includes(run.sessionId)) && + (!args?.where?.status?.in || args.where.status.in.includes(run.status)), + ), + ), }, + sessionErrorLog: { findMany: vi.fn(async () => state.errors) }, + // Plans whose exam is today or later, nearest exam first (findActivePlan). studyPlan: { - findFirst: vi.fn(async () => null), + findMany: vi.fn(async (args: { where?: { examDate?: { gte?: Date } } }) => { + const from = args?.where?.examDate?.gte ?? new Date(0); + return [...(state.plan ? [state.plan] : []), ...state.otherPlans] + .filter((p) => p.examDate >= from) + .sort((a, b) => a.examDate.getTime() - b.examDate.getTime()); + }), }, - userGameState: { - // getUserTimezone reads UserGameState.timezone; null row = no timezone (UTC) - findUnique: vi.fn(async () => gameState.row), + session: { + findMany: vi.fn(async (args: { where?: { sessionId?: unknown } }) => + args?.where?.sessionId ? state.nudgeSessions : state.sessions, + ), + findFirst: vi.fn(async () => state.existingSession), }, - _test: { completedRuns, gameState }, + sessionRunPrompt: { findMany: vi.fn(async () => state.prompts) }, + contentDocument: { findMany: vi.fn(async () => state.docs) }, + studyPlanItem: { findFirst: vi.fn(async () => state.plannedItem) }, + _test: state, }, }; }); @@ -46,22 +105,92 @@ vi.mock("@/lib/mastery", () => ({ getMasterySummary: vi.fn(async () => ({ total: 0, objectives: [] })), })); -import { getStudyRecommendations } from "@/services/study-recommendations"; +// The streak and the zone come from gamification (covered in gamification.test.ts) +vi.mock("@/services/gamification", () => ({ + getStreak: vi.fn(async () => 0), + resolveTimeZone: vi.fn(async () => "UTC"), +})); + +vi.mock("@/services/session", () => ({ + createSession: vi.fn(async () => ({ + session_id: "new-session", + session_url: "http://elsewhere.example/s/new-session", + calendar: { title: "", description: "" }, + })), +})); + +import { + buildTopicScope, + dominantErrorPhrase, + errorRepairReason, + getStudyRecommendations, + readableTopicScope, + sessionTopicLine, + startStudySession, + StudyStartError, +} from "@/services/study-recommendations"; +import { humanizeObjectiveKey } from "@/lib/objective-keys"; import { prisma } from "@/lib/db"; +import { getDueObjectives, getMasterySummary } from "@/lib/mastery"; +import { createSession } from "@/services/session"; +import { getStreak, resolveTimeZone } from "@/services/gamification"; -const testPrisma = ( - prisma as unknown as { - _test: { completedRuns: RunRow[]; gameState: GameStateHolder }; - } -)._test; +const state = (prisma as unknown as { _test: TestState })._test; const NOW = new Date("2026-07-15T10:00:00Z"); // UTC day 2026-07-15, Tokyo 19:00 -function addCompletedRun(endedAt: Date): void { - testPrisma.completedRuns.push({ endedAt }); +type MasteryRow = { + objective_key: string; + ease_factor: number; + interval_days: number; + repetitions: number; + last_accuracy: number | null; + last_studied_at: string | null; + next_due_at: string | null; + is_due: boolean; +}; + +function mastery(key: string, repetitions: number, lastAccuracy: number | null): MasteryRow { + return { + objective_key: key, + ease_factor: 2.5, + interval_days: 1, + repetitions, + last_accuracy: lastAccuracy, + last_studied_at: null, + next_due_at: null, + is_due: false, + }; +} + +function setMastery(rows: MasteryRow[]) { + vi.mocked(getMasterySummary).mockResolvedValue({ + total: rows.length, + due: 0, + mastered: 0, + objectives: rows, + }); } -async function getStreak(): Promise<number> { +function setDue(rows: { key: string; daysOverdue: number }[]) { + vi.mocked(getDueObjectives).mockResolvedValue( + rows.map((r) => ({ + id: r.key, + userId: "user1", + courseName: "Biology", + objectiveKey: r.key, + easeFactor: 2.5, + intervalDays: 1, + repetitions: 1, + lastAccuracy: 0.5, + lastStudiedAt: null, + nextDueAt: new Date(NOW.getTime() - r.daysOverdue * 86_400_000 - 3_600_000), + updatedAt: NOW, + })), + ); +} + +async function getStreak_(): Promise<number> { const result = await getStudyRecommendations("user1", "Biology"); return result.streak; } @@ -69,84 +198,541 @@ async function getStreak(): Promise<number> { beforeEach(() => { vi.useFakeTimers(); vi.setSystemTime(NOW); - testPrisma.completedRuns.length = 0; - testPrisma.gameState.row = null; vi.clearAllMocks(); + state.runs = []; + state.gameState.row = null; + state.errors = []; + state.plan = null; + state.otherPlans = []; + state.sessions = []; + state.nudgeSessions = []; + state.prompts = []; + state.docs = []; + state.existingSession = null; + state.plannedItem = null; + vi.mocked(getDueObjectives).mockResolvedValue([]); + setMastery([]); + // Settings, else the newest plan's zone, else UTC, as resolveTimeZone does. + vi.mocked(resolveTimeZone).mockImplementation( + async () => state.gameState.row?.timezone ?? state.plan?.timezone ?? "UTC", + ); }); afterEach(() => { vi.useRealTimers(); }); -describe("study streak (via getStudyRecommendations)", () => { - it("returns 0 with no completed runs", async () => { - expect(await getStreak()).toBe(0); +describe("streak", () => { + it("shows the same streak as Home and Progress", async () => { + vi.mocked(getStreak).mockResolvedValueOnce(4); + expect(await getStreak_()).toBe(4); + expect(getStreak).toHaveBeenCalledWith("user1"); + }); + + it("is 0 when the student has no streak", async () => { + expect(await getStreak_()).toBe(0); + }); +}); + +describe("topic titles", () => { + it("humanizes keys", () => { + expect(humanizeObjectiveKey("photosynthesis_light_reactions")).toBe("Photosynthesis light reactions"); + expect(humanizeObjectiveKey("big-o")).toBe("Big o"); + expect(humanizeObjectiveKey("__")).toBe("Untitled topic"); + }); + + it("joins up to three titles and counts the rest", () => { + expect(buildTopicScope([])).toBe("General review"); + expect(buildTopicScope(["Specificity"])).toBe("Specificity"); + expect(buildTopicScope(["A", "B", "C"])).toBe("A, B, and C"); + expect(buildTopicScope(["A", "B", "C", "D", "E"])).toBe("A, B, C, and 2 more"); + }); + + it("rewrites stored key scopes as one list", () => { + const titles = new Map([["css_specificity", "CSS specificity"]]); + expect(readableTopicScope("css_specificity, box_model (+2 more)", titles)).toBe( + "CSS specificity, Box model, and 2 more", + ); + expect(readableTopicScope("", titles)).toBe("General review"); + }); + + it("lists comma-joined titles the way Home and Plan do", () => { + const titles = new Map<string, string>(); + // Plans store titles joined with ", " (research-plan-generator). + expect(readableTopicScope("CSS specificity, The box model", titles)).toBe("CSS specificity and The box model"); + expect(readableTopicScope("Specificity, Box sizing, Flexbox", titles)).toBe( + "Specificity, Box sizing, and Flexbox", + ); + // Already a list, or a single title: unchanged. + expect(readableTopicScope("A, B, and C", titles)).toBe("A, B, and C"); + expect(readableTopicScope("Recursion and stacks", titles)).toBe("Recursion and stacks"); + expect(readableTopicScope("Big-O", titles)).toBe("Big-O"); + }); + + it("prefers the titles stored on the session", () => { + const titles = new Map([["cell_cycle", "Cell cycle"]]); + expect( + sessionTopicLine( + [ + { id: "css_specificity", title: "CSS specificity" }, + { id: "box_model", title: "The box model" }, + ], + "css_specificity, box_model", + titles, + ), + ).toBe("CSS specificity and The box model"); + expect(sessionTopicLine([{ id: "cell_cycle", title: "cell_cycle" }], "", titles)).toBe("Cell cycle"); + expect(sessionTopicLine(["Recursion", "Stacks"], "", titles)).toBe("Recursion and Stacks"); + expect(sessionTopicLine(null, "Recursion, Stacks", titles)).toBe("Recursion and Stacks"); + }); + + it("maps mastery keys to plan and session titles in the recommendation", async () => { + state.plan = { + planId: "plan1", + examName: "Prelim 1", + examDate: new Date("2026-07-30T00:00:00Z"), + timezone: "America/New_York", + config: { objectives: ["CSS specificity", "Box model"] }, + items: [], + }; + state.sessions = [{ objectives: [{ id: "flexbox_axes", title: "Flexbox axes" }] }]; + setMastery([ + mastery("css_specificity", 0, null), + mastery("flexbox_axes", 1, 0.4), + mastery("grid_template_areas", 2, 0.6), + ]); + + const recs = await getStudyRecommendations("user1", "INFO 1300"); + expect(recs.next_session.mode).toBe("RETRIEVAL"); + expect(recs.next_session.topics).toEqual([ + { key: "css_specificity", title: "CSS specificity" }, + { key: "flexbox_axes", title: "Flexbox axes" }, + { key: "grid_template_areas", title: "Grid template areas" }, + ]); + expect(recs.next_session.objectives).toEqual(["css_specificity", "flexbox_axes", "grid_template_areas"]); + expect(recs.next_session.topic_scope).toBe("CSS specificity, Flexbox axes, and Grid template areas"); + expect(recs.exam).toEqual({ name: "Prelim 1", date: "2026-07-30", days_until: 15 }); }); +}); - it("counts today's completed run even under a positive UTC offset", async () => { - // Regression: the walk previously started from LOCAL midnight, which - // serializes to yesterday's UTC key in Tokyo — a run completed today - // produced a streak of 0. - addCompletedRun(new Date("2026-07-15T09:00:00Z")); +describe("recommendation reasons", () => { + it("recommends error repair with the topics the errors came from", async () => { + state.errors = [ + { runId: "r1", promptIndex: 0, errorType: "MISCONCEPTION" }, + { runId: "r1", promptIndex: 1, errorType: "MISCONCEPTION" }, + { runId: "r2", promptIndex: 0, errorType: "PROCEDURE" }, + { runId: "r2", promptIndex: 3, errorType: "MISCONCEPTION" }, + ]; + state.prompts = [ + { runId: "r1", promptIndex: 0, objectiveId: "css_specificity" }, + { runId: "r1", promptIndex: 1, objectiveId: "css_specificity" }, + { runId: "r2", promptIndex: 0, objectiveId: "box_model" }, + { runId: "r2", promptIndex: 3, objectiveId: null }, + ]; - expect(await getStreak()).toBe(1); + const recs = await getStudyRecommendations("user1", "INFO 1300"); + expect(recs.next_session.mode).toBe("ERROR_REPAIR"); + expect(recs.next_session.objectives).toEqual(["css_specificity", "box_model"]); + expect(recs.next_session.reason).toBe( + "4 unresolved errors, mostly misconceptions. An error is resolved after you answer it correctly on 2 different days.", + ); + // For the card, whose heading line already gives the count. + expect(recs.next_session.reason_without_count).toBe( + "Most are misconceptions. An error is resolved after you answer it correctly on 2 different days.", + ); + expect(recs.unresolved_errors.count).toBe(4); }); - it("counts consecutive UTC days", async () => { - addCompletedRun(new Date("2026-07-15T09:00:00Z")); - addCompletedRun(new Date("2026-07-14T23:30:00Z")); - addCompletedRun(new Date("2026-07-13T01:00:00Z")); + it("can leave the count out of the error repair reason", () => { + const rule = "An error is resolved after you answer it correctly on 2 different days."; + expect(errorRepairReason(["MEMORY", "MEMORY", "MEMORY"], { withCount: false })).toBe(`All are memory gaps. ${rule}`); + expect(errorRepairReason(["PROCEDURE", "PROCEDURE", "CARELESS"], { withCount: false })).toBe( + `Most are wrong steps. ${rule}`, + ); + expect(errorRepairReason(["CARELESS", "PROCEDURE", "MEMORY"], { withCount: false })).toBe(rule); + expect(errorRepairReason(["MEMORY"], { withCount: false })).toBe(rule); + }); - expect(await getStreak()).toBe(3); + it("keeps the same reason with and without a count for other modes", async () => { + const recs = await getStudyRecommendations("user1", "Biology"); + expect(recs.next_session.reason_without_count).toBe(recs.next_session.reason); }); - it("stops at a gap", async () => { - addCompletedRun(new Date("2026-07-15T09:00:00Z")); - addCompletedRun(new Date("2026-07-13T09:00:00Z")); + it("names the dominant error type only when it is more than half", () => { + expect(dominantErrorPhrase(["MEMORY", "MEMORY", "MEMORY"])).toBe("all memory gaps"); + expect(dominantErrorPhrase(["CARELESS", "PROCEDURE"])).toBeNull(); + expect(dominantErrorPhrase(["UNKNOWN", "UNKNOWN", "PROCEDURE"])).toBeNull(); + }); - expect(await getStreak()).toBe(1); + it("recommends retrieval for overdue topics with the oldest delay", async () => { + setDue([ + { key: "a_topic", daysOverdue: 4 }, + { key: "b_topic", daysOverdue: 2 }, + { key: "c_topic", daysOverdue: 1 }, + { key: "d_topic", daysOverdue: 0 }, + { key: "e_topic", daysOverdue: 0 }, + { key: "f_topic", daysOverdue: 0 }, + ]); + const recs = await getStudyRecommendations("user1", "Biology"); + expect(recs.next_session.mode).toBe("RETRIEVAL"); + expect(recs.next_session.reason).toBe("6 topics are due for review, the oldest by 4 days."); + expect(recs.next_session.topic_scope).toBe("A topic, B topic, C topic, and 2 more"); }); - it("starts from yesterday when today has no completed run", async () => { - addCompletedRun(new Date("2026-07-14T09:00:00Z")); - addCompletedRun(new Date("2026-07-13T09:00:00Z")); + it("recommends an exam simulation when the exam is 3 or fewer days away", async () => { + state.gameState.row = { timezone: "America/New_York" }; + state.plan = { + planId: "plan1", + examName: "Prelim 1", + examDate: new Date("2026-07-17T00:00:00Z"), + timezone: "America/New_York", + config: {}, + items: [], + }; + setMastery([mastery("cell_cycle", 1, 0.5)]); + const recs = await getStudyRecommendations("user1", "Biology"); + expect(recs.next_session.mode).toBe("EXAM_SIM"); + expect(recs.next_session.reason).toBe( + "Prelim 1 is in 2 days. A full practice exam now shows what you still miss while there's time to fix it.", + ); + }); - expect(await getStreak()).toBe(2); + it("recommends interleaved practice once every topic has been practiced", async () => { + setMastery([mastery("a_topic", 2, 0.9), mastery("b_topic", 1, 0.8)]); + const recs = await getStudyRecommendations("user1", "Biology"); + expect(recs.next_session.mode).toBe("INTERLEAVED_PRACTICE"); + expect(recs.next_session.reason).toBe( + "You've practiced every topic at least once. Mixing topics helps you tell similar problems apart.", + ); }); - it("returns 0 when neither today nor yesterday has a completed run", async () => { - addCompletedRun(new Date("2026-07-12T09:00:00Z")); + it("says so plainly when there is no practice yet", async () => { + const recs = await getStudyRecommendations("user1", "Biology"); + expect(recs.next_session.topics).toEqual([]); + expect(recs.next_session.topic_scope).toBe("General review"); + expect(recs.next_session.reason).toBe( + "You haven't practiced Biology yet. A first session from memory shows where you stand.", + ); + }); - expect(await getStreak()).toBe(0); + it("never returns dashes, enum names or snake_case keys in visible text", async () => { + state.errors = [ + { runId: "r1", promptIndex: 0, errorType: "PROCEDURE" }, + { runId: "r1", promptIndex: 1, errorType: "CARELESS" }, + { runId: "r1", promptIndex: 2, errorType: "MEMORY" }, + ]; + const recs = await getStudyRecommendations("user1", "Biology"); + const visible = [recs.next_session.reason, recs.next_session.topic_scope].join(" "); + expect(visible).not.toMatch(/[–—]| -- /); + expect(visible).not.toMatch(/\b[A-Z]{2,}_[A-Z_]+\b|\b[a-z]+_[a-z_]+\b/); + expect(visible).not.toMatch(/research|robust/i); }); }); -describe("study streak with a user timezone", () => { - it("keys a 9pm ET run to the local day 2026-07-15, not the UTC day 2026-07-16", async () => { - // 2026-07-16T01:00:00Z is 9pm on July 15 in New York. At NOW (July 15 - // UTC/ET) the ET user sees today's activity; UTC keys file the same run - // under the 16th — tomorrow — so the streak would read 0. - addCompletedRun(new Date("2026-07-16T01:00:00Z")); +describe("planned sessions", () => { + function planWith(items: PlanItemRow[]): PlanRow { + return { + planId: "plan1", + examName: "Prelim 1", + examDate: new Date("2026-08-01T00:00:00Z"), + timezone: "America/New_York", + config: {}, + items, + }; + } - testPrisma.gameState.row = { timezone: "America/New_York" }; - expect(await getStreak()).toBe(1); + it("finds today's sessions in the student's time zone and writes readable messages", async () => { + state.gameState.row = { timezone: "America/New_York" }; + state.plan = planWith([ + // 11pm Jul 14 in New York: yesterday there + { + sessionId: "s-yesterday", + status: "SCHEDULED", + dayIndex: 0, + startTime: new Date("2026-07-15T03:00:00Z"), + endTime: new Date("2026-07-15T03:30:00Z"), + }, + // 9pm Jul 15 in New York: today there, though it is Jul 16 in UTC + { + sessionId: "s-today", + status: "SCHEDULED", + dayIndex: 1, + startTime: new Date("2026-07-16T01:00:00Z"), + endTime: new Date("2026-07-16T01:30:00Z"), + }, + ]); + state.nudgeSessions = [ + { sessionId: "s-today", mode: "RETRIEVAL", topicScope: "photosynthesis_light_reactions" }, + ]; - testPrisma.gameState.row = null; // UTC day keys - expect(await getStreak()).toBe(0); + const recs = await getStudyRecommendations("user1", "Biology"); + expect(recs.plan_nudge?.items.map((i) => i.session_id)).toEqual(["s-today"]); + const item = recs.plan_nudge!.items[0]; + expect(item.mode_label).toBe("Retrieval"); + expect(item.topic_scope).toBe("Photosynthesis light reactions"); + expect(item.message).toMatch(/^Today at 9:00\sPM: Retrieval on Photosynthesis light reactions$/); + expect(recs.next_planned).toBeNull(); + expect(recs.time_zone).toBe("America/New_York"); }); - it("keeps a two-day local streak unbroken when a late-night run crosses the UTC boundary", async () => { - vi.setSystemTime(new Date("2026-07-16T01:30:00Z")); // 9:30pm July 15 ET + it("offers the next planned session when none is left today", async () => { + state.gameState.row = { timezone: "America/New_York" }; + state.plan = planWith([ + { + sessionId: "s-done", + status: "DONE", + dayIndex: 0, + startTime: new Date("2026-07-15T14:00:00Z"), + endTime: new Date("2026-07-15T14:30:00Z"), + }, + { + sessionId: "s-later", + status: "SCHEDULED", + dayIndex: 2, + startTime: new Date("2026-07-17T18:00:00Z"), + endTime: new Date("2026-07-17T18:30:00Z"), + }, + ]); + state.nudgeSessions = [{ sessionId: "s-later", mode: "EXAM_SIM", topicScope: "Cell cycle" }]; + + const recs = await getStudyRecommendations("user1", "Biology"); + expect(recs.plan_nudge).toBeNull(); + expect(recs.next_planned?.session_id).toBe("s-later"); + expect(recs.next_planned?.mode_label).toBe("Exam simulation"); + expect(recs.next_planned?.message).toBe("Exam simulation on Cell cycle"); + // Today had a session and it is done, so Study says so instead of "none today". + expect(recs.today_planned).toBe(1); + expect(recs.today_done).toBe(1); + }); + + it("counts today's sessions in every status, so none planned differs from none left", async () => { + state.gameState.row = { timezone: "America/New_York" }; + state.plan = planWith([ + // 10am Jul 15 in New York: today, missed + { + sessionId: "s-missed", + status: "MISSED", + dayIndex: 0, + startTime: new Date("2026-07-15T14:00:00Z"), + endTime: new Date("2026-07-15T14:30:00Z"), + }, + { + sessionId: "s-later", + status: "SCHEDULED", + dayIndex: 2, + startTime: new Date("2026-07-17T18:00:00Z"), + endTime: new Date("2026-07-17T18:30:00Z"), + }, + ]); + state.nudgeSessions = [{ sessionId: "s-later", mode: "RETRIEVAL", topicScope: "Cell cycle" }]; + + const missed = await getStudyRecommendations("user1", "Biology"); + expect(missed.plan_nudge).toBeNull(); + expect(missed.next_planned?.session_id).toBe("s-later"); + expect([missed.today_planned, missed.today_done]).toEqual([1, 0]); + + // Nothing on today's date at all. + state.plan = planWith(state.plan.items.filter((i) => i.sessionId === "s-later")); + const none = await getStudyRecommendations("user1", "Biology"); + expect(none.next_planned?.session_id).toBe("s-later"); + expect([none.today_planned, none.today_done]).toEqual([0, 0]); + }); + + it("lists a planned session's topics with Intl, as Home and Plan do", async () => { + state.gameState.row = { timezone: "America/New_York" }; + state.plan = planWith([ + { + sessionId: "s-today", + status: "SCHEDULED", + dayIndex: 0, + startTime: new Date("2026-07-15T18:00:00Z"), + endTime: new Date("2026-07-15T18:30:00Z"), + }, + ]); + // A plan session: titles comma-joined in the scope, objectives stored too. + state.nudgeSessions = [ + { + sessionId: "s-today", + mode: "RETRIEVAL", + topicScope: "CSS specificity, The box model", + objectives: [ + { id: "css_specificity", title: "CSS specificity" }, + { id: "the_box_model", title: "The box model" }, + ], + }, + ]; + + const recs = await getStudyRecommendations("user1", "INFO 1300"); + const item = recs.plan_nudge!.items[0]; + expect(item.topic_scope).toBe("CSS specificity and The box model"); + expect(item.message).toMatch(/^Today at 2:00\sPM: Retrieval on CSS specificity and The box model$/); + }); + + it("counts rescheduled sessions as still to do", async () => { + state.gameState.row = { timezone: "America/New_York" }; + state.plan = planWith([ + { + sessionId: "s-moved", + status: "RESCHEDULED", + dayIndex: 3, + startTime: new Date("2026-07-18T14:00:00Z"), + endTime: new Date("2026-07-18T14:30:00Z"), + }, + ]); + state.nudgeSessions = [{ sessionId: "s-moved", mode: "RETRIEVAL", topicScope: "Cell cycle" }]; + + const recs = await getStudyRecommendations("user1", "Biology"); + expect(recs.next_planned?.session_id).toBe("s-moved"); + }); + + it("marks a session with a run under way IN_PROGRESS, so Study offers Resume session as Home does", async () => { + state.gameState.row = { timezone: "America/New_York" }; + const today = (sessionId: string, hour: number, status = "SCHEDULED"): PlanItemRow => ({ + sessionId, + status, + dayIndex: 0, + startTime: new Date(`2026-07-15T${hour}:00:00Z`), + endTime: new Date(`2026-07-15T${hour}:30:00Z`), + }); + state.plan = planWith([ + today("s-started", 14), + // Missed, then opened from its link and started: resumable, as on Home + today("s-missed", 15, "MISSED"), + today("s-done", 16, "DONE"), + today("s-open", 17), + ]); + state.nudgeSessions = ["s-started", "s-missed", "s-open"].map((sessionId) => ({ + sessionId, + mode: "RETRIEVAL", + topicScope: "Cell cycle", + })); + // Starting a run doesn't write the plan item; the runs say what is under way. + state.runs = [ + { sessionId: "s-started", status: "ACTIVE" }, + { sessionId: "s-missed", status: "PAUSED" }, + // A finished session's later run doesn't reopen it. + { sessionId: "s-done", status: "ACTIVE" }, + { sessionId: "s-open", status: "COMPLETED" }, + { sessionId: "s-elsewhere", status: "ACTIVE" }, + ]; + + const recs = await getStudyRecommendations("user1", "Biology"); + expect(recs.plan_nudge?.items.map((i) => [i.session_id, i.status])).toEqual([ + ["s-started", "IN_PROGRESS"], + ["s-missed", "IN_PROGRESS"], + ["s-open", "SCHEDULED"], + ]); + expect([recs.today_planned, recs.today_done]).toEqual([4, 1]); + // Only the plan's own sessions are looked up, by the statuses Home and Plan count. + expect(vi.mocked(prisma.sessionRun.findMany)).toHaveBeenCalledWith({ + where: { + userId: "user1", + sessionId: { in: ["s-started", "s-missed", "s-done", "s-open"] }, + status: { in: ["ACTIVE", "PAUSED"] }, + }, + select: { sessionId: true }, + }); + }); - addCompletedRun(new Date("2026-07-16T01:00:00Z")); // 9pm Jul 15 ET (UTC day Jul 16) - addCompletedRun(new Date("2026-07-14T15:00:00Z")); // 11am Jul 14 ET (UTC day Jul 14) + it("skips the run lookup when the course has no plan", async () => { + await getStudyRecommendations("user1", "Biology"); + expect(vi.mocked(prisma.sessionRun.findMany)).not.toHaveBeenCalled(); + }); +}); + +describe("the course's exam", () => { + function plan(planId: string, examName: string, examDate: string): PlanRow { + return { + planId, + examName, + examDate: new Date(`${examDate}T00:00:00Z`), + timezone: "America/New_York", + config: {}, + items: [], + }; + } + + it("uses the plan for the exam chosen in the course switcher", async () => { + state.plan = plan("p1", "Prelim 1", "2026-07-20"); + state.otherPlans = [plan("p2", "Prelim 2", "2026-08-10")]; + + expect((await getStudyRecommendations("user1", "CS 2110", "Prelim 2")).exam?.name).toBe("Prelim 2"); + // No exam chosen, or one without a plan: the nearest exam ahead. + expect((await getStudyRecommendations("user1", "CS 2110")).exam?.name).toBe("Prelim 1"); + expect((await getStudyRecommendations("user1", "CS 2110", "Final")).exam?.name).toBe("Prelim 1"); + }); + + it("drops a plan once its exam has passed, and keeps one whose exam is today", async () => { + state.gameState.row = { timezone: "America/New_York" }; + state.plan = plan("old", "Prelim 1", "2026-07-14"); + expect((await getStudyRecommendations("user1", "CS 2110")).exam).toBeNull(); + + state.plan = plan("today", "Prelim 1", "2026-07-15"); + expect((await getStudyRecommendations("user1", "CS 2110")).exam).toEqual({ + name: "Prelim 1", + date: "2026-07-15", + days_until: 0, + }); + }); +}); + +describe("startStudySession", () => { + beforeEach(() => { + state.docs = [{ examName: "Prelim 1", status: "PROCESSED" }]; + setMastery([mastery("cell_cycle", 0, null)]); + }); + + it("creates a session with titled topics, a relative URL and a length-based question count", async () => { + const result = await startStudySession("user1", { courseName: "Biology", mode: "RETRIEVAL", minutes: 30 }); + expect(result).toEqual({ session_id: "new-session", url: "/s/new-session", reused: false }); + expect(createSession).toHaveBeenCalledTimes(1); + expect(vi.mocked(createSession).mock.calls[0][1]).toEqual({ + course_name: "Biology", + exam_name: "Prelim 1", + mode: "RETRIEVAL", + topic_scope: "Cell cycle", + planned_minutes: 30, + objectives: [{ id: "cell_cycle", title: "Cell cycle" }], + target_outcome: { prompt_count: 10 }, + break_protocol: { type: "50_10", cycles: 1 }, + }); + }); + + it("uses the picked mode and length", async () => { + await startStudySession("user1", { courseName: "Biology", examName: "Final", mode: "WORKED_EXAMPLES", minutes: 15 }); + const payload = vi.mocked(createSession).mock.calls[0][1] as Record<string, unknown>; + expect(payload.mode).toBe("WORKED_EXAMPLES"); + expect(payload.exam_name).toBe("Final"); + expect(payload.planned_minutes).toBe(15); + expect(payload.target_outcome).toEqual({ prompt_count: 5 }); + }); + + it("reuses an identical session that was never started", async () => { + state.existingSession = { sessionId: "earlier" }; + const result = await startStudySession("user1", { courseName: "Biology", mode: "RETRIEVAL", minutes: 30 }); + expect(result).toEqual({ session_id: "earlier", url: "/s/earlier", reused: true }); + expect(createSession).not.toHaveBeenCalled(); + }); + + it("never reuses a planned session", async () => { + state.existingSession = { sessionId: "planned" }; + state.plannedItem = { id: "item1" }; + const result = await startStudySession("user1", { courseName: "Biology", mode: "RETRIEVAL", minutes: 30 }); + expect(result.session_id).toBe("new-session"); + }); - // ET days: Jul 14 + Jul 15 — consecutive - testPrisma.gameState.row = { timezone: "America/New_York" }; - expect(await getStreak()).toBe(2); + it("refuses a course with no materials or none ready", async () => { + state.docs = []; + await expect( + startStudySession("user1", { courseName: "Biology", mode: "RETRIEVAL", minutes: 30 }), + ).rejects.toMatchObject({ code: "COURSE_NOT_FOUND" }); - // UTC days: Jul 14 + Jul 16 — broken at Jul 15 - testPrisma.gameState.row = null; - expect(await getStreak()).toBe(1); + state.docs = [{ examName: null, status: "UPLOADED" }]; + const err = await startStudySession("user1", { courseName: "Biology", mode: "RETRIEVAL", minutes: 30 }).catch( + (e: unknown) => e, + ); + expect(err).toBeInstanceOf(StudyStartError); + expect((err as StudyStartError).code).toBe("NO_MATERIALS"); + expect(createSession).not.toHaveBeenCalled(); }); }); diff --git a/src/__tests__/timezone.test.ts b/src/__tests__/timezone.test.ts new file mode 100644 index 00000000..a80d26c4 --- /dev/null +++ b/src/__tests__/timezone.test.ts @@ -0,0 +1,170 @@ +/** + * Unit tests for the pure helpers in lib/timezone. Every expectation is an + * absolute instant or a day key, so the results must not depend on the + * timezone of the machine running the tests. + */ +import { describe, it, expect, vi, beforeEach } from "vitest"; + +const db = vi.hoisted(() => ({ + settingsZone: null as string | null, + planZone: null as string | null, + settingsReads: 0, + planReads: 0, +})); + +vi.mock("@/lib/db", () => ({ + prisma: { + userGameState: { + findUnique: async () => { + db.settingsReads++; + return { timezone: db.settingsZone }; + }, + }, + studyPlan: { + findFirst: async () => { + db.planReads++; + return db.planZone === null ? null : { timezone: db.planZone }; + }, + }, + }, +})); + +import { + addDays, + dayKey, + daysBetween, + getStoredTimezone, + getUserTimezone, + hourOfDay, + isValidTimezone, + resolveTimeZone, + zonedTimeToUtc, +} from "@/lib/timezone"; + +describe("zonedTimeToUtc", () => { + it("converts a wall-clock time in a zone to the UTC instant", () => { + // 09:00 EDT (UTC-4) + expect(zonedTimeToUtc("2026-07-16", "09:00", "America/New_York").toISOString()).toBe( + "2026-07-16T13:00:00.000Z", + ); + // 09:00 JST (UTC+9) is the previous UTC day + expect(zonedTimeToUtc("2026-07-16", "09:00", "Asia/Tokyo").toISOString()).toBe( + "2026-07-16T00:00:00.000Z", + ); + }); + + it("follows DST on both sides of a transition", () => { + // US clocks spring forward on 2026-03-08 + expect(zonedTimeToUtc("2026-03-07", "09:00", "America/New_York").toISOString()).toBe( + "2026-03-07T14:00:00.000Z", + ); + expect(zonedTimeToUtc("2026-03-08", "09:00", "America/New_York").toISOString()).toBe( + "2026-03-08T13:00:00.000Z", + ); + }); + + it("treats a null or invalid zone as UTC", () => { + expect(zonedTimeToUtc("2026-07-16", "09:30", null).toISOString()).toBe( + "2026-07-16T09:30:00.000Z", + ); + expect(zonedTimeToUtc("2026-07-16", "09:30", "Not/AZone").toISOString()).toBe( + "2026-07-16T09:30:00.000Z", + ); + }); +}); + +describe("day arithmetic", () => { + it("adds days across month and year ends", () => { + expect(addDays("2026-01-31", 1)).toBe("2026-02-01"); + expect(addDays("2026-12-31", 1)).toBe("2027-01-01"); + expect(addDays("2026-03-01", -1)).toBe("2026-02-28"); + }); + + it("counts calendar days between day keys", () => { + expect(daysBetween("2026-03-07", "2026-03-09")).toBe(2); + expect(daysBetween("2026-03-09", "2026-03-07")).toBe(-2); + }); + + it("reads the calendar day and hour in the given zone", () => { + const instant = new Date("2026-07-17T02:30:00Z"); + expect(dayKey(instant, "America/New_York")).toBe("2026-07-16"); + expect(dayKey(instant, null)).toBe("2026-07-17"); + expect(hourOfDay(instant, "America/New_York")).toBe(22.5); + expect(hourOfDay(instant, null)).toBe(2.5); + }); +}); + +describe("formatter reuse", () => { + it("gives the same answers when a zone's formatter is reused", () => { + const instants = Array.from({ length: 48 }, (_, i) => new Date(Date.UTC(2026, 2, 7, i))); + const first = instants.map((d) => dayKey(d, "America/New_York")); + const again = instants.map((d) => dayKey(d, "America/New_York")); + expect(again).toEqual(first); + // Midnight in New York is 05:00 UTC on both days: clocks change at 2am on March 8 + expect(first[4]).toBe("2026-03-06"); + expect(first[5]).toBe("2026-03-07"); + expect(first[24 + 4]).toBe("2026-03-07"); + expect(first[24 + 5]).toBe("2026-03-08"); + }); + + it("keeps zones apart", () => { + const instant = new Date("2026-07-16T23:30:00Z"); + expect(dayKey(instant, "Asia/Tokyo")).toBe("2026-07-17"); + expect(dayKey(instant, "America/Los_Angeles")).toBe("2026-07-16"); + expect(hourOfDay(instant, "Asia/Tokyo")).toBe(8.5); + expect(hourOfDay(instant, "America/Los_Angeles")).toBe(16.5); + }); + + it("reads midnight as hour 0", () => { + expect(hourOfDay(new Date("2026-07-16T04:00:00Z"), "America/New_York")).toBe(0); + }); + + it("validates zones, valid or not, any number of times", () => { + for (let i = 0; i < 3; i++) { + expect(isValidTimezone("Europe/Paris")).toBe(true); + expect(isValidTimezone("UTC")).toBe(true); + expect(isValidTimezone("Not/AZone")).toBe(false); + expect(isValidTimezone("")).toBe(false); + } + expect(dayKey(new Date("2026-07-17T02:30:00Z"), "Not/AZone")).toBe("2026-07-17"); + }); +}); + +describe("the student's zone", () => { + beforeEach(() => { + db.settingsZone = null; + db.planZone = null; + db.settingsReads = 0; + db.planReads = 0; + }); + + it("prefers the Settings zone", async () => { + db.settingsZone = "America/Chicago"; + db.planZone = "Europe/Paris"; + expect(await resolveTimeZone("u1")).toBe("America/Chicago"); + expect(await getUserTimezone("u1")).toBe("America/Chicago"); + expect(db.planReads).toBe(0); + }); + + it("uses the newest plan's zone when Settings has none", async () => { + db.planZone = "Europe/Paris"; + expect(await resolveTimeZone("u1")).toBe("Europe/Paris"); + expect(await getUserTimezone("u1")).toBe("Europe/Paris"); + // Settings itself stays empty + expect(await getStoredTimezone("u1")).toBeNull(); + }); + + it("ends at UTC, or null, with no valid zone anywhere", async () => { + db.settingsZone = "Not/AZone"; + db.planZone = "Also/Not"; + expect(await resolveTimeZone("u1")).toBe("UTC"); + expect(await getUserTimezone("u1")).toBeNull(); + }); + + it("skips the Settings query when the caller passes the value", async () => { + db.planZone = "Europe/Paris"; + expect(await resolveTimeZone("u1", "Asia/Tokyo")).toBe("Asia/Tokyo"); + expect(await resolveTimeZone("u1", null)).toBe("Europe/Paris"); + expect(db.settingsReads).toBe(0); + }); +}); diff --git a/src/__tests__/token-vault.test.ts b/src/__tests__/token-vault.test.ts index 2066efdf..f07f4ab4 100644 --- a/src/__tests__/token-vault.test.ts +++ b/src/__tests__/token-vault.test.ts @@ -5,8 +5,8 @@ * - encrypt→decrypt roundtrip * - tampered authTag fails * - missing key behavior in production throws - * - isTokenEncryptedFormat detection - * - sanitizeForLog redaction + * + * Log redaction (sanitizeForLog) is in log-redaction.test.ts. */ import { describe, it, expect, vi, beforeAll, afterAll } from "vitest"; @@ -15,8 +15,6 @@ const TEST_KEY_HEX = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789 describe("token-vault", () => { let encryptToken: (plain: string) => string; let decryptToken: (enc: string) => string; - let isTokenEncryptedFormat: (s: string) => boolean; - let sanitizeForLog: (input: string) => string; const origEnv = { ...process.env }; @@ -25,8 +23,6 @@ describe("token-vault", () => { const mod = await import("@/lib/crypto/token-vault"); encryptToken = mod.encryptToken; decryptToken = mod.decryptToken; - isTokenEncryptedFormat = mod.isTokenEncryptedFormat; - sanitizeForLog = mod.sanitizeForLog; }); afterAll(() => { @@ -80,8 +76,6 @@ describe("token-vault", () => { it("fails without TOKEN_ENC_KEY in production", async () => { const savedEnv = { ...process.env }; delete process.env.TOKEN_ENC_KEY; - delete process.env.GOOGLE_TOKEN_ENC_KEY; - delete process.env.TEST_TOKEN_ENC_KEY; (process.env as Record<string, string>).NODE_ENV = "production"; vi.resetModules(); @@ -93,72 +87,5 @@ describe("token-vault", () => { vi.resetModules(); } }); - - it("accepts TEST_TOKEN_ENC_KEY in non-production", async () => { - const savedEnv = { ...process.env }; - delete process.env.TOKEN_ENC_KEY; - delete process.env.GOOGLE_TOKEN_ENC_KEY; - process.env.TEST_TOKEN_ENC_KEY = TEST_KEY_HEX; - (process.env as Record<string, string>).NODE_ENV = "test"; - - vi.resetModules(); - try { - const { encryptToken: enc, decryptToken: dec } = await import("@/lib/crypto/token-vault"); - expect(dec(enc("hello"))).toBe("hello"); - } finally { - Object.assign(process.env, savedEnv); - vi.resetModules(); - } - }); - }); - - describe("isTokenEncryptedFormat", () => { - it("returns true for encrypted tokens", () => { - const enc = encryptToken("test-token"); - expect(isTokenEncryptedFormat(enc)).toBe(true); - }); - - it("returns false for plain text", () => { - expect(isTokenEncryptedFormat("ya29.plaintext-token")).toBe(false); - }); - - it("returns false for empty/null", () => { - expect(isTokenEncryptedFormat("")).toBe(false); - expect(isTokenEncryptedFormat(null as unknown as string)).toBe(false); - expect(isTokenEncryptedFormat(undefined as unknown as string)).toBe(false); - }); - - it("returns false for short base64", () => { - expect(isTokenEncryptedFormat("aGVsbG8=")).toBe(false); // "hello" in base64 - }); - }); - - describe("sanitizeForLog", () => { - it("redacts OAuth access tokens", () => { - const input = 'token: ya29.A0AfH6SMBx_long_access_token_here'; - const result = sanitizeForLog(input); - expect(result).not.toContain("A0AfH6SMBx"); - expect(result).toContain("ya29.[REDACTED]"); - }); - - it("redacts refresh tokens", () => { - const input = 'refresh: 1//0eXyz_long_refresh_token'; - const result = sanitizeForLog(input); - expect(result).not.toContain("0eXyz"); - expect(result).toContain("1//[REDACTED]"); - }); - - it("redacts long base64 strings", () => { - const enc = encryptToken("secret"); - const input = `encrypted token: ${enc}`; - const result = sanitizeForLog(input); - expect(result).not.toContain(enc); - expect(result).toContain("[ENCRYPTED_REDACTED]"); - }); - - it("leaves short safe strings unchanged", () => { - const input = "user_id=abc123"; - expect(sanitizeForLog(input)).toBe(input); - }); }); }); diff --git a/src/__tests__/tokens.test.ts b/src/__tests__/tokens.test.ts new file mode 100644 index 00000000..b7646a63 --- /dev/null +++ b/src/__tests__/tokens.test.ts @@ -0,0 +1,155 @@ +/** + * Unit tests for src/lib/tokens.ts: link tokens are stored only as hashes, + * are used at most once, report why a link didn't work (expired, used, + * invalid), and expired rows get purged. + */ +import { describe, it, expect, vi, beforeEach } from "vitest"; + +const { verificationToken } = vi.hoisted(() => ({ + verificationToken: { updateMany: vi.fn(), findUnique: vi.fn(), create: vi.fn(), deleteMany: vi.fn() }, +})); + +vi.mock("@/lib/db", () => ({ prisma: { verificationToken } })); + +import { + classifyToken, + createEmailVerificationToken, + createPasswordResetToken, + hashToken, + inspectToken, + purgeExpiredTokens, + redeemToken, +} from "@/lib/tokens"; + +const NOW = new Date("2026-10-15T12:00:00Z"); +const HOUR = 60 * 60 * 1000; + +function record(overrides: Partial<{ type: string; expiresAt: Date; usedAt: Date | null }> = {}) { + return { + userId: "user-1", + type: "PASSWORD_RESET", + expiresAt: new Date(NOW.getTime() + HOUR), + usedAt: null, + ...overrides, + }; +} + +beforeEach(() => { + vi.clearAllMocks(); +}); + +describe("classifyToken", () => { + it("sorts a record into valid, expired, used or invalid", () => { + expect(classifyToken(record(), "PASSWORD_RESET", NOW)).toEqual({ status: "valid", userId: "user-1" }); + expect(classifyToken(record({ expiresAt: new Date(NOW.getTime() - 1) }), "PASSWORD_RESET", NOW)).toEqual({ + status: "expired", + userId: "user-1", + }); + expect(classifyToken(record({ usedAt: NOW }), "PASSWORD_RESET", NOW)).toEqual({ + status: "used", + userId: "user-1", + }); + expect(classifyToken(record(), "EMAIL_VERIFY", NOW)).toEqual({ status: "invalid" }); + expect(classifyToken(null, "PASSWORD_RESET", NOW)).toEqual({ status: "invalid" }); + }); + + it("reports used before expired", () => { + const stale = record({ usedAt: NOW, expiresAt: new Date(NOW.getTime() - HOUR) }); + expect(classifyToken(stale, "PASSWORD_RESET", NOW).status).toBe("used"); + }); +}); + +describe("redeemToken", () => { + it("claims an unused, unexpired token with one conditional update", async () => { + verificationToken.updateMany.mockResolvedValue({ count: 1 }); + verificationToken.findUnique.mockResolvedValue(record({ usedAt: NOW })); + + expect(await redeemToken("tok", "PASSWORD_RESET")).toEqual({ status: "valid", userId: "user-1" }); + const where = verificationToken.updateMany.mock.calls[0][0].where; + expect(where).toMatchObject({ token: hashToken("tok"), type: "PASSWORD_RESET", usedAt: null }); + expect(verificationToken.findUnique).toHaveBeenCalledWith({ where: { token: hashToken("tok") } }); + expect(where.expiresAt.gt).toBeInstanceOf(Date); + }); + + it("explains why a token couldn't be claimed", async () => { + verificationToken.updateMany.mockResolvedValue({ count: 0 }); + + verificationToken.findUnique.mockResolvedValueOnce(record({ usedAt: NOW })); + expect((await redeemToken("tok", "PASSWORD_RESET")).status).toBe("used"); + + verificationToken.findUnique.mockResolvedValueOnce(record({ expiresAt: new Date(Date.now() - HOUR) })); + expect((await redeemToken("tok", "PASSWORD_RESET")).status).toBe("expired"); + + verificationToken.findUnique.mockResolvedValueOnce(null); + expect((await redeemToken("tok", "PASSWORD_RESET")).status).toBe("invalid"); + }); + + it("never lets an unclaimed token through as valid", async () => { + verificationToken.updateMany.mockResolvedValue({ count: 0 }); + verificationToken.findUnique.mockResolvedValue(record({ expiresAt: new Date(Date.now() + HOUR) })); + expect((await redeemToken("tok", "PASSWORD_RESET")).status).toBe("used"); + }); + + it("rejects an empty token without a query", async () => { + expect(await redeemToken("", "EMAIL_VERIFY")).toEqual({ status: "invalid" }); + expect(verificationToken.updateMany).not.toHaveBeenCalled(); + }); + + it("claims through a transaction's client when given one, so a rollback undoes the claim", async () => { + const tx = { verificationToken: { updateMany: vi.fn(), findUnique: vi.fn() } }; + tx.verificationToken.updateMany.mockResolvedValue({ count: 1 }); + tx.verificationToken.findUnique.mockResolvedValue(record({ usedAt: NOW })); + + expect(await redeemToken("tok", "PASSWORD_RESET", tx as never)).toEqual({ status: "valid", userId: "user-1" }); + expect(tx.verificationToken.updateMany).toHaveBeenCalledOnce(); + expect(verificationToken.updateMany).not.toHaveBeenCalled(); + expect(verificationToken.findUnique).not.toHaveBeenCalled(); + }); +}); + +describe("inspectToken", () => { + it("reads by hash without writing", async () => { + verificationToken.findUnique.mockResolvedValue(record({ expiresAt: new Date(Date.now() - HOUR) })); + expect((await inspectToken("tok", "PASSWORD_RESET")).status).toBe("expired"); + expect(verificationToken.findUnique).toHaveBeenCalledWith({ where: { token: hashToken("tok") } }); + expect(verificationToken.updateMany).not.toHaveBeenCalled(); + }); +}); + +describe("creating tokens", () => { + beforeEach(() => { + verificationToken.updateMany.mockResolvedValue({ count: 0 }); + verificationToken.create.mockResolvedValue({}); + verificationToken.deleteMany.mockResolvedValue({ count: 0 }); + }); + + it("stores only the SHA-256 of the token the link carries", async () => { + const token = await createPasswordResetToken("user-1"); + const { data } = verificationToken.create.mock.calls[0][0]; + expect(data).toMatchObject({ userId: "user-1", type: "PASSWORD_RESET", token: hashToken(token) }); + expect(data.token).not.toBe(token); + expect(hashToken(token)).toMatch(/^[0-9a-f]{64}$/); + }); + + it("ends the user's unused links of the same type first", async () => { + await createEmailVerificationToken("user-1"); + expect(verificationToken.updateMany).toHaveBeenCalledWith({ + where: { userId: "user-1", type: "EMAIL_VERIFY", usedAt: null }, + data: { usedAt: expect.any(Date) }, + }); + const { data } = verificationToken.create.mock.calls[0][0]; + const hours = (data.expiresAt.getTime() - Date.now()) / HOUR; + expect(hours).toBeGreaterThan(23.9); + expect(hours).toBeLessThanOrEqual(24); + }); +}); + +describe("purgeExpiredTokens", () => { + it("deletes rows that expired more than a day ago", async () => { + verificationToken.deleteMany.mockResolvedValue({ count: 3 }); + expect(await purgeExpiredTokens(NOW)).toBe(3); + expect(verificationToken.deleteMany).toHaveBeenCalledWith({ + where: { expiresAt: { lt: new Date(NOW.getTime() - 24 * HOUR) } }, + }); + }); +}); diff --git a/src/__tests__/validation-attempt.test.ts b/src/__tests__/validation-attempt.test.ts index 162b5adc..1f030c52 100644 --- a/src/__tests__/validation-attempt.test.ts +++ b/src/__tests__/validation-attempt.test.ts @@ -1,5 +1,10 @@ import { describe, it, expect } from "vitest"; -import { submitAttemptSchema, updateAttemptMetaSchema } from "@/lib/validation"; +import { + examAnswerSchema, + MAX_ANSWER_CHARS, + submitAttemptSchema, + updateAttemptMetaSchema, +} from "@/lib/validation"; describe("submitAttemptSchema", () => { it("accepts a valid CORRECT attempt without error_log", () => { @@ -121,6 +126,48 @@ describe("submitAttemptSchema", () => { expect(result.success).toBe(false); }); + // Answers go into AI prompts in full, so they share the reveal route's cap. + describe("length caps", () => { + const base = { prompt_index: 0, self_score: "CORRECT" as const }; + + it("accepts an answer of exactly MAX_ANSWER_CHARS", () => { + const answer = "x".repeat(MAX_ANSWER_CHARS); + expect(submitAttemptSchema.safeParse({ ...base, user_answer: answer }).success).toBe(true); + }); + + it("rejects a longer answer with a fixable message", () => { + const result = submitAttemptSchema.safeParse({ ...base, user_answer: "x".repeat(MAX_ANSWER_CHARS + 1) }); + expect(result.success).toBe(false); + expect(result.error?.issues[0]).toMatchObject({ + path: ["user_answer"], + message: "Shorten your answer to 20,000 characters.", + }); + }); + + it("caps exam-simulation answers the same way", () => { + const result = examAnswerSchema.safeParse({ + prompt_index: 0, + kind: "ANSWER", + user_answer: "x".repeat(MAX_ANSWER_CHARS + 1), + }); + expect(result.success).toBe(false); + }); + + it("caps the correction rule and similar question", () => { + const long = "x".repeat(MAX_ANSWER_CHARS + 1); + const attempt = (error_log: Record<string, unknown>) => + submitAttemptSchema.safeParse({ + prompt_index: 0, + user_answer: "Answer", + self_score: "INCORRECT", + error_log: { error_type: "MEMORY", ...error_log }, + }); + expect(attempt({ correction_rule: long }).success).toBe(false); + expect(attempt({ correction_rule: "Rule", variant_question: long }).success).toBe(false); + expect(attempt({ correction_rule: "Rule", variant_question: "Similar?" }).success).toBe(true); + }); + }); + // MCQ attempts: the server grades the choice and builds the error log, // so neither self_score nor error_log is required from the client. describe("MCQ attempts", () => { diff --git a/src/__tests__/validation-content.test.ts b/src/__tests__/validation-content.test.ts index 1dbf17f4..0c1b5bd3 100644 --- a/src/__tests__/validation-content.test.ts +++ b/src/__tests__/validation-content.test.ts @@ -1,7 +1,6 @@ import { describe, it, expect } from "vitest"; import { uploadDocumentSchema, - searchContentSchema, } from "@/lib/validation-content"; describe("uploadDocumentSchema", () => { @@ -34,39 +33,3 @@ describe("uploadDocumentSchema", () => { expect(result.success).toBe(false); }); }); - -describe("searchContentSchema", () => { - it("accepts valid search", () => { - const result = searchContentSchema.safeParse({ - q: "loop invariant", - namespace: "COURSE", - top_k: 3, - }); - expect(result.success).toBe(true); - }); - - it("defaults top_k to 5", () => { - const result = searchContentSchema.parse({ - q: "test", - namespace: "COURSE", - }); - expect(result.top_k).toBe(5); - }); - - it("rejects empty query", () => { - const result = searchContentSchema.safeParse({ - q: "", - namespace: "COURSE", - }); - expect(result.success).toBe(false); - }); - - it("rejects top_k > 10", () => { - const result = searchContentSchema.safeParse({ - q: "test", - namespace: "COURSE", - top_k: 20, - }); - expect(result.success).toBe(false); - }); -}); diff --git a/src/__tests__/validation-plan.test.ts b/src/__tests__/validation-plan.test.ts index 989a068f..e8eb4d1f 100644 --- a/src/__tests__/validation-plan.test.ts +++ b/src/__tests__/validation-plan.test.ts @@ -23,7 +23,8 @@ describe("createPlanSchema", () => { const result = createPlanSchema.parse(rest); expect(result.daily_study_cap_minutes).toBe(180); expect(result.break_protocol_default).toBe("50_10"); - expect(result.timezone).toBe("America/New_York"); + // No default here: createPlan falls back to the user's timezone setting + expect(result.timezone).toBeUndefined(); }); it("rejects fewer than 3 objectives", () => { @@ -75,3 +76,45 @@ describe("createPlanSchema", () => { ).toThrow(); }); }); + +describe("createPlanSchema messages and replace fields", () => { + function issues(input: unknown) { + const result = createPlanSchema.safeParse(input); + expect(result.success).toBe(false); + return result.success ? [] : result.error.issues.map((i) => ({ path: i.path.join("."), message: i.message })); + } + + it("names the field and the fix for each rule", () => { + expect(issues({ ...validInput, course_name: " " })).toContainEqual({ + path: "course_name", + message: "Enter a course name.", + }); + expect(issues({ ...validInput, exam_date: "" })).toContainEqual({ + path: "exam_date", + message: "Choose the exam date.", + }); + expect( + issues({ ...validInput, availability: Array.from({ length: 7 }, () => ({ start: "17:00", end: "09:00" })) }) + ).toContainEqual({ path: "availability", message: "Choose an end time after the start time." }); + expect(issues({ ...validInput, objectives: ["A"] })).toContainEqual({ + path: "objectives", + message: "Upload materials or type at least 3 topics, one per line.", + }); + }); + + it("trims names and accepts a plan to replace", () => { + const result = createPlanSchema.parse({ + ...validInput, + course_name: " CS 2110 ", + replace_plan_id: "plan-1", + remove_replaced_calendar_events: true, + }); + expect(result.course_name).toBe("CS 2110"); + expect(result.replace_plan_id).toBe("plan-1"); + expect(result.remove_replaced_calendar_events).toBe(true); + }); + + it("does not remove calendar events unless asked", () => { + expect(createPlanSchema.parse(validInput).remove_replaced_calendar_events).toBe(false); + }); +}); diff --git a/src/__tests__/validation.test.ts b/src/__tests__/validation.test.ts index 97c44ae9..1e4c6fe9 100644 --- a/src/__tests__/validation.test.ts +++ b/src/__tests__/validation.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from "vitest"; -import { createSessionSchema } from "@/lib/validation"; +import { MAX_PROMPT_COUNT, clampPromptCount, createSessionSchema } from "@/lib/validation"; const validPayload = { course_id: "CS2110", @@ -63,4 +63,56 @@ describe("createSessionSchema", () => { }); expect(result.success).toBe(true); }); + // The run builds the whole deck in memory, so an unbounded count could + // take the shared server down; 0 or less left a run with no questions. + it("takes 1 to 60 whole questions", () => { + const withCount = (prompt_count: number) => + createSessionSchema.safeParse({ ...validPayload, target_outcome: { prompt_count } }).success; + expect(withCount(1)).toBe(true); + expect(withCount(MAX_PROMPT_COUNT)).toBe(true); + for (const bad of [0, -3, 2.5, MAX_PROMPT_COUNT + 1, 50_000_000, 1e308]) { + expect(withCount(bad), String(bad)).toBe(false); + } + }); + + it("bounds the free-form fields", () => { + const tooLong = (field: string, length: number) => + createSessionSchema.safeParse({ ...validPayload, [field]: "x".repeat(length) }).success; + expect(tooLong("course_name", 200)).toBe(true); + expect(tooLong("course_name", 201)).toBe(false); + expect(tooLong("exam_name", 201)).toBe(false); + expect(tooLong("topic_scope", 2001)).toBe(false); + + const objectives = (count: number) => + Array.from({ length: count }, (_, i) => ({ id: `obj_${i}`, title: `Topic ${i}` })); + expect(createSessionSchema.safeParse({ ...validPayload, objectives: objectives(50) }).success).toBe(true); + expect(createSessionSchema.safeParse({ ...validPayload, objectives: objectives(51) }).success).toBe(false); + expect( + createSessionSchema.safeParse({ ...validPayload, objectives: [{ id: "a", title: "x".repeat(501) }] }).success, + ).toBe(false); + + const resources = Array.from({ length: 21 }, () => ({ type: "slides", ref: "week2.pdf" })); + expect(createSessionSchema.safeParse({ ...validPayload, resources }).success).toBe(false); + }); }); + +describe("clampPromptCount", () => { + it("keeps a stored count between 1 and the maximum", () => { + expect(clampPromptCount(8)).toBe(8); + expect(clampPromptCount(50_000_000)).toBe(MAX_PROMPT_COUNT); + expect(clampPromptCount(1e308)).toBe(MAX_PROMPT_COUNT); + expect(clampPromptCount(0)).toBe(1); + expect(clampPromptCount(-4)).toBe(1); + expect(clampPromptCount(7.9)).toBe(7); + }); + + it("falls back when the count is missing or not a number", () => { + expect(clampPromptCount(undefined)).toBe(10); + expect(clampPromptCount(null)).toBe(10); + expect(clampPromptCount("12")).toBe(10); + expect(clampPromptCount(Number.NaN)).toBe(10); + expect(clampPromptCount(Number.POSITIVE_INFINITY)).toBe(10); + expect(clampPromptCount(undefined, 3)).toBe(3); + }); +}); + diff --git a/src/__tests__/worked-examples.test.ts b/src/__tests__/worked-examples.test.ts index 4a123560..61e738a9 100644 --- a/src/__tests__/worked-examples.test.ts +++ b/src/__tests__/worked-examples.test.ts @@ -138,21 +138,25 @@ describe("generateWorkedExampleDeck", () => { // STUDY prompt: problem, numbered steps with rationale, self-explanation const study = deck[0]; expect(study.text).toContain("A problem"); - expect(study.text).toContain("Step 1: A action 1 — why: A why 1"); - expect(study.text).toContain("Step 3: A action 3 — why: A why 3"); + expect(study.text).toContain("Step 1: A action 1. Why: A why 1."); + expect(study.text).toContain("Step 3: A action 3. Why: A why 3."); expect(study.text).toContain( - "In your own words: why does step 3 follow from the previous steps?", + "In your own words, why does step 3 follow from the steps before it?", ); + // No typed dashes in text the student reads + expect(deck.every((p) => !/[\u2013\u2014]/.test(p.text))).toBe(true); - // COMPLETION 1: last step missing + // COMPLETION 1: last step missing, with the solution's step count expect(deck[1].text).toContain("A completion 1"); - expect(deck[1].text).toContain( - "(The final step is missing — supply it and state why it follows.)", - ); + expect(deck[1].text).toContain("The last step is missing. Write it and say why it follows."); + expect(deck[1].meta?.step_count).toBe(3); // COMPLETION 2: last two steps missing expect(deck[2].text).toContain("A completion 2"); - expect(deck[2].text).toContain("(The final two steps are missing — supply them.)"); + expect(deck[2].text).toContain( + "The last two steps are missing. Write them and say why each follows.", + ); + expect(deck[2].meta?.step_count).toBe(3); // FULL: bare problem, model answer stashed in meta for post-answer reveal expect(deck[3].text).toBe("A full problem"); @@ -184,6 +188,8 @@ describe("generateWorkedExampleDeck", () => { "WORKED_EXAMPLES", ["Projectile motion", "Free fall"], 15, + // The exam's own files rank first in the search. + { examName: "Midterm 1" }, ); const spec = runTaskMock.mock.calls[0][1] as { diff --git a/src/app/(app)/(home)/loading.tsx b/src/app/(app)/(home)/loading.tsx new file mode 100644 index 00000000..66741cc9 --- /dev/null +++ b/src/app/(app)/(home)/loading.tsx @@ -0,0 +1,15 @@ +import { PageContainer } from "@/components/app/page-container"; +import { PageSkeleton } from "@/components/app/skeletons"; + +/** + * Home's skeleton. It lives in Home's own route group so it doesn't wrap the + * other (app) pages: a page with no loading boundary above it (the deck + * page) can still answer a missing record with a real 404. + */ +export default function HomeLoading() { + return ( + <PageContainer> + <PageSkeleton /> + </PageContainer> + ); +} diff --git a/src/app/(app)/(home)/page.tsx b/src/app/(app)/(home)/page.tsx new file mode 100644 index 00000000..e036d02b --- /dev/null +++ b/src/app/(app)/(home)/page.tsx @@ -0,0 +1,86 @@ +import { Suspense } from "react" + +import { PageContainer } from "@/components/app/page-container" +import { ExamsSection } from "@/components/home/exams-section" +import { FirstRun } from "@/components/home/first-run" +import { + ExamsSkeleton, + HomeSkeleton, + StatsSkeleton, + TodaySkeleton, + WeakSpotsSkeleton, +} from "@/components/home/home-skeleton" +import { HomeStats } from "@/components/home/stats-line" +import { TodaySection } from "@/components/home/today-section" +import { WeakSpotsSection } from "@/components/home/weak-spots-section" +import { + loadGameState, + loadMastery, + loadMaterialCount, + loadPlans, + loadSafely, + loadTimeZone, + loadUnresolvedErrors, + requireUserId, +} from "@/services/progress-data" + +/** + * Home: exam countdowns first, then weak spots beside today's session, then + * one quiet line of stats. Server-rendered from the services layer; each + * section streams and fails on its own. + */ +export default function HomePage() { + return ( + <PageContainer> + <Suspense fallback={<HomeSkeleton />}> + <Home /> + </Suspense> + </PageContainer> + ) +} + +async function Home() { + const userId = await requireUserId("/") + + // Start every query now; sections await the cached results. + const ignore = () => {} + loadTimeZone(userId).catch(ignore) + loadGameState(userId).catch(ignore) + loadUnresolvedErrors(userId).catch(ignore) + loadMastery(userId).catch(ignore) + + const firstRun = await loadSafely("home.first_run_check_failed", userId, async () => { + const [plans, materials] = await Promise.all([loadPlans(userId), loadMaterialCount(userId)]) + return plans.length === 0 && materials === 0 + }) + if (firstRun) return <FirstRun /> + + const now = new Date() + return ( + <div className="flex flex-col gap-8"> + <Suspense fallback={<ExamsSkeleton />}> + <ExamsSection userId={userId} now={now} /> + </Suspense> + + {/* Today comes first in reading order so phones reach it before weak spots; + from 840px it sits on the right, as the direction contract draws it, so + laptop widths don't stretch one session card across the page. */} + <div className="grid gap-8 md:grid-cols-[3fr_2fr] md:gap-6"> + <div className="min-w-0 md:col-start-2 md:row-start-1"> + <Suspense fallback={<TodaySkeleton />}> + <TodaySection userId={userId} now={now} /> + </Suspense> + </div> + <div className="min-w-0 md:col-start-1 md:row-start-1"> + <Suspense fallback={<WeakSpotsSkeleton />}> + <WeakSpotsSection userId={userId} now={now} /> + </Suspense> + </div> + </div> + + <Suspense fallback={<StatsSkeleton />}> + <HomeStats userId={userId} /> + </Suspense> + </div> + ) +} diff --git a/src/app/(app)/achievements/layout.tsx b/src/app/(app)/achievements/layout.tsx new file mode 100644 index 00000000..91e8102f --- /dev/null +++ b/src/app/(app)/achievements/layout.tsx @@ -0,0 +1,9 @@ +import type { Metadata } from "next"; + +export const metadata: Metadata = { + title: "Progress", +}; + +export default function Layout({ children }: { children: React.ReactNode }) { + return children; +} diff --git a/src/app/(app)/achievements/loading.tsx b/src/app/(app)/achievements/loading.tsx new file mode 100644 index 00000000..8f904047 --- /dev/null +++ b/src/app/(app)/achievements/loading.tsx @@ -0,0 +1,10 @@ +import { PageContainer } from "@/components/app/page-container" +import { ProgressSkeleton } from "@/components/progress/progress-skeleton" + +export default function ProgressLoading() { + return ( + <PageContainer> + <ProgressSkeleton /> + </PageContainer> + ) +} diff --git a/src/app/(app)/achievements/page.tsx b/src/app/(app)/achievements/page.tsx new file mode 100644 index 00000000..51a1f370 --- /dev/null +++ b/src/app/(app)/achievements/page.tsx @@ -0,0 +1,67 @@ +import { Suspense } from "react" + +import { PageContainer } from "@/components/app/page-container" +import { AchievementsSection } from "@/components/progress/achievements-section" +import { ActivitySection } from "@/components/progress/activity-section" +import { ConfidenceSection } from "@/components/progress/confidence-section" +import { MasterySection } from "@/components/progress/mastery-section" +import { BlockSkeleton, MasterySkeleton, ProgressSkeleton } from "@/components/progress/progress-skeleton" +import { StreakXpSection } from "@/components/progress/streak-xp-section" +import { + loadGameState, + loadMastery, + loadPlans, + loadRatedAnswers, + loadTimeZone, + loadYearOfActivity, + requireUserId, +} from "@/services/progress-data" + +/** + * Progress: mastery by topic, confidence against results, streak and XP, + * activity by day, and achievements. Read-only; nothing here awards XP. + */ +export default function ProgressPage() { + return ( + <PageContainer> + <Suspense fallback={<ProgressSkeleton />}> + <Progress /> + </Suspense> + </PageContainer> + ) +} + +async function Progress() { + const userId = await requireUserId("/achievements") + + // Start every query now; sections await the cached results. + const ignore = () => {} + loadPlans(userId).catch(ignore) + loadMastery(userId).catch(ignore) + loadGameState(userId).catch(ignore) + loadRatedAnswers(userId).catch(ignore) + loadTimeZone(userId) + .then((timeZone) => loadYearOfActivity(userId, timeZone)) + .catch(ignore) + + const now = new Date() + return ( + <div className="flex flex-col gap-10"> + <Suspense fallback={<MasterySkeleton />}> + <MasterySection userId={userId} now={now} /> + </Suspense> + <Suspense fallback={<BlockSkeleton lines={5} />}> + <ConfidenceSection userId={userId} /> + </Suspense> + <Suspense fallback={<BlockSkeleton lines={3} double />}> + <StreakXpSection userId={userId} /> + </Suspense> + <Suspense fallback={<BlockSkeleton lines={4} />}> + <ActivitySection userId={userId} /> + </Suspense> + <Suspense fallback={<BlockSkeleton lines={4} />}> + <AchievementsSection userId={userId} /> + </Suspense> + </div> + ) +} diff --git a/src/app/(app)/chat/layout.tsx b/src/app/(app)/chat/layout.tsx new file mode 100644 index 00000000..b91c4b4b --- /dev/null +++ b/src/app/(app)/chat/layout.tsx @@ -0,0 +1,9 @@ +import type { Metadata } from "next"; + +export const metadata: Metadata = { + title: "Chat", +}; + +export default function Layout({ children }: { children: React.ReactNode }) { + return children; +} diff --git a/src/app/(app)/chat/loading.tsx b/src/app/(app)/chat/loading.tsx new file mode 100644 index 00000000..5215c83a --- /dev/null +++ b/src/app/(app)/chat/loading.tsx @@ -0,0 +1,33 @@ +import { PageContainer } from "@/components/app/page-container" +import { LoadingRegion } from "@/components/app/skeletons" +import { Skeleton } from "@/components/ui/skeleton" + +/** Chat skeleton: course picker, a few messages, and the question box. */ +export default function Loading() { + return ( + <PageContainer size="narrow" className="flex-1"> + <LoadingRegion label="Loading chat…" className="flex flex-1 flex-col gap-6"> + <div aria-hidden="true" className="flex flex-1 flex-col gap-6"> + <div className="flex flex-col gap-2"> + <Skeleton className="h-4 w-16" /> + <Skeleton className="h-10 w-56 rounded-md" /> + <Skeleton className="mt-1 h-4 w-80 max-w-full" /> + </div> + <div className="flex justify-end"> + <Skeleton className="h-11 w-3/5 rounded-3xl" /> + </div> + <div className="flex flex-col gap-2.5"> + <Skeleton className="h-5 w-32" /> + <Skeleton className="h-4 w-full" /> + <Skeleton className="h-4 w-11/12" /> + <Skeleton className="h-4 w-2/3" /> + </div> + <div className="mt-auto flex flex-col gap-2"> + <Skeleton className="h-4 w-52" /> + <Skeleton className="h-24 w-full rounded-md" /> + </div> + </div> + </LoadingRegion> + </PageContainer> + ) +} diff --git a/src/app/(app)/chat/page.tsx b/src/app/(app)/chat/page.tsx new file mode 100644 index 00000000..54dab6a9 --- /dev/null +++ b/src/app/(app)/chat/page.tsx @@ -0,0 +1,49 @@ +import { redirect } from "next/navigation" + +import { getCurrentUserId } from "@/lib/auth" +import { logger } from "@/lib/logger" +import { listDocuments } from "@/services/content" +import { loadPlans, loadTimeZone } from "@/services/progress-data" +import { PageContainer } from "@/components/app/page-container" +import { ChatScreen } from "@/components/chat/chat-screen" +import { SwrFallback } from "@/components/chat/swr-fallback" +import { coursePreferences } from "@/components/study/course-preference" + +const DOCUMENTS_KEY = "/api/content/documents?namespace=COURSE" + +/** + * Chat over one course's materials. The course list is read here, on the + * server, and handed to the client cache, so the history request starts as + * soon as the page hydrates (the active course lives in the browser). + * + * With no course chosen, Chat opens on the course of today's session, else + * the nearest exam, like Study. The shell's Start button reads the same + * plans in this request, so they cost no extra query. + */ +export default async function ChatPage() { + const userId = await getCurrentUserId() + if (!userId) redirect("/auth/signin?callbackUrl=/chat") + + const [documents, timeZone, plans] = await Promise.all([ + listDocuments(userId, "COURSE").catch((err) => { + logger.error("chat.page_documents_failed", { userId, error: String(err) }) + return null + }), + loadTimeZone(userId), + loadPlans(userId).catch((err) => { + logger.error("chat.page_plans_failed", { userId, error: String(err) }) + return null + }), + ]) + + return ( + <PageContainer size="narrow" className="flex-1 pb-0"> + <SwrFallback fallback={documents ? { [DOCUMENTS_KEY]: { documents } } : {}}> + <ChatScreen + timeZone={timeZone} + coursePreferences={plans ? coursePreferences(plans, timeZone) : undefined} + /> + </SwrFallback> + </PageContainer> + ) +} diff --git a/src/app/(app)/design/_showcase/app-components.tsx b/src/app/(app)/design/_showcase/app-components.tsx new file mode 100644 index 00000000..24fba246 --- /dev/null +++ b/src/app/(app)/design/_showcase/app-components.tsx @@ -0,0 +1,227 @@ +"use client" + +import * as React from "react" +import { FlameIcon, LayersIcon, PlusIcon, SearchXIcon, TargetIcon, ZapIcon } from "lucide-react" + +import { Button } from "@/components/ui/button" +import { AccountMenu } from "@/components/app/account-menu" +import { CountdownCard } from "@/components/app/countdown-card" +import { CourseSwitcher } from "@/components/app/course-switcher" +import { EmptyState } from "@/components/app/empty-state" +import { ErrorBoundary } from "@/components/app/error-boundary" +import { ErrorState } from "@/components/app/error-state" +import { KbdHint } from "@/components/app/kbd-hint" +import { MasteryBar } from "@/components/app/mastery-bar" +import { PageHeader } from "@/components/app/page-header" +import { ProgressLinear } from "@/components/app/progress-linear" +import { SectionHeader } from "@/components/app/section-header" +import { CardSkeleton, ListSkeleton, PageHeaderSkeleton } from "@/components/app/skeletons" +import { StatLine } from "@/components/app/stat-line" +import { StatusScreen } from "@/components/app/status-screen" +import { ThemeToggle } from "@/components/app/theme-toggle" + +import { Block, ShowcaseSection } from "./helpers" + +// Fixed dates so every reviewer sees the same countdowns. +const NOW = new Date("2026-10-12T16:00:00Z") +const ZONE = "America/New_York" + +function Thrower(): React.ReactNode { + throw new Error("Demo render failure") +} + +export function AppComponents() { + const [broken, setBroken] = React.useState(false) + const [retrying, setRetrying] = React.useState(false) + + return ( + <ShowcaseSection + id="app" + title="App components" + description="Shared pieces in src/components/app. Screens compose these instead of styling their own." + > + <Block title="PageHeader" description="The app bar already shows the destination name as the h1; PageHeader names the specific object."> + <PageHeader + title="Prelim 1 plan" + description="14 sessions between today and Thu, Oct 22. Sessions fall between 9:00 AM and 9:00 PM." + actions={ + <> + <Button variant="outline">Export calendar (.ics)</Button> + <Button> + <PlusIcon data-icon="inline-start" aria-hidden="true" /> + New plan + </Button> + </> + } + /> + </Block> + + <Block title="SectionHeader"> + <div className="flex flex-col gap-4"> + <SectionHeader title="Weak spots" description="Unresolved errors and low-mastery topics." action={{ href: "/achievements", label: "All topics" }} /> + <SectionHeader as="h3" title="Follow-up sessions" action={<Button variant="outline" size="sm">Add follow-ups to plan</Button>} /> + </div> + </Block> + + <Block title="CountdownCard" description="The nearest exam is featured in the primary container. Pass the student's time zone."> + <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4"> + <CountdownCard + featured + examName="Prelim 1" + courseName="CS 2110" + examDate="2026-10-21T14:00:00Z" + timeZone={ZONE} + now={NOW} + sessionsDone={9} + sessionsTotal={14} + missedCount={1} + rescheduleHref="/plan" + href="/plan" + /> + <CountdownCard + examName="Midterm" + courseName="MATH 1920" + examDate="2026-10-13T14:00:00Z" + timeZone={ZONE} + now={NOW} + sessionsDone={11} + sessionsTotal={12} + /> + <CountdownCard + examName="Final" + courseName="INFO 1300" + examDate="2026-10-12T20:00:00Z" + timeZone={ZONE} + now={NOW} + /> + <CountdownCard + examName="Quiz 3" + courseName="ECON 1110" + examDate="2026-10-09T20:00:00Z" + timeZone={ZONE} + now={NOW} + sessionsDone={4} + sessionsTotal={4} + /> + </div> + </Block> + + <div className="grid gap-6 lg:grid-cols-2"> + <Block title="ProgressLinear" description="M3 linear indicator with a gap and stop dot."> + <div className="flex flex-col gap-5"> + {[0, 35, 64, 100].map((v) => ( + <div key={v} className="flex items-center gap-4"> + <span className="w-10 font-mono text-xs text-on-surface-variant tabular-nums">{v}%</span> + <ProgressLinear value={v} label={`Example at ${v}%`} /> + </div> + ))} + <div className="flex items-center gap-4"> + <span className="w-10 font-mono text-xs text-on-surface-variant">busy</span> + <ProgressLinear value={null} label="Uploading lecture-4.pdf" /> + </div> + <div className="flex items-center gap-4"> + <span className="w-10 font-mono text-xs text-on-surface-variant">tones</span> + <div className="flex flex-1 flex-col gap-3"> + <ProgressLinear value={80} tone="tertiary" label="Success tone" /> + <ProgressLinear value={30} tone="warning" label="Warning tone" /> + <ProgressLinear value={15} tone="error" label="Error tone" /> + </div> + </div> + </div> + </Block> + <Block title="MasteryBar" description="Low in warning, middle in primary, high in success. The number is always printed."> + <div className="flex flex-col gap-4"> + <MasteryBar label="Recursion" value={0.22} /> + <MasteryBar label="Stacks and queues" value={0.58} /> + <MasteryBar label="Big-O notation" value={0.86} status="Mastered" /> + <MasteryBar label="Amortized analysis of dynamic arrays and hash tables" value={0} /> + </div> + </Block> + </div> + + <div className="grid gap-6 lg:grid-cols-2"> + <Block title="StatLine" description="The quiet stats row. Never inside a session."> + <div className="flex flex-col gap-4"> + <StatLine + items={[ + { value: "12-day streak", icon: FlameIcon }, + { value: "83%", label: "accuracy", icon: TargetIcon }, + { value: "340 XP", icon: ZapIcon }, + ]} + /> + <StatLine items={[{ value: "No accuracy yet" }, { value: "0 XP" }]} /> + </div> + </Block> + <Block title="Shell controls" description="CourseSwitcher reads your real course list; the theme control is live, and the account menu shows a sample student."> + <div className="flex flex-col gap-5"> + <CourseSwitcher /> + <div className="flex flex-wrap items-center gap-3"> + <ThemeToggle /> + <ThemeToggle variant="segmented" /> + <AccountMenu account={{ name: "Sample Student", email: "student@example.com" }} /> + </div> + <div className="flex items-center gap-2 type-body-m text-on-surface-variant"> + <KbdHint keys={["Mod", "Enter"]} /> KbdHint resolves Mod to Ctrl or Cmd + </div> + </div> + </Block> + </div> + + <div className="grid gap-6 lg:grid-cols-2"> + <Block title="EmptyState" description="What this place is, how to fill it, one action."> + <EmptyState + bordered + icon={LayersIcon} + title="No decks for CS 2110 yet" + description="Generate one from your CS 2110 materials." + action={<Button>Generate deck</Button>} + /> + </Block> + <Block title="ErrorState" description="A failed load is never an empty state."> + <div className="flex flex-col gap-4"> + <ErrorState + title="Decks didn't load." + onRetry={() => { + setRetrying(true) + setTimeout(() => setRetrying(false), 1200) + }} + retrying={retrying} + /> + <ErrorState + title="Plans didn't load." + description="Your sign-in expired. Sign in again." + reference="a1b2c3d4" + /> + <ErrorBoundary title="This card didn't load."> + {broken ? <Thrower /> : ( + <Button variant="outline" onClick={() => setBroken(true)}> + Break this card (ErrorBoundary) + </Button> + )} + </ErrorBoundary> + </div> + </Block> + </div> + + <div className="grid gap-6 lg:grid-cols-2"> + <Block title="Skeleton layouts"> + <div className="flex flex-col gap-4"> + <PageHeaderSkeleton /> + <CardSkeleton /> + <ListSkeleton rows={2} /> + </div> + </Block> + <Block title="StatusScreen" description="Not-found and failed pages."> + <StatusScreen + headingLevel="h2" + icon={SearchXIcon} + title="Session not found" + description="This link doesn't match a session. It may have been deleted." + actions={<Button>Go to Home</Button>} + className="py-6" + /> + </Block> + </div> + </ShowcaseSection> + ) +} diff --git a/src/app/(app)/design/_showcase/controls.tsx b/src/app/(app)/design/_showcase/controls.tsx new file mode 100644 index 00000000..bbc87dd8 --- /dev/null +++ b/src/app/(app)/design/_showcase/controls.tsx @@ -0,0 +1,351 @@ +"use client" + +import * as React from "react" +import { + BoldIcon, + CalendarPlusIcon, + ChevronRightIcon, + ItalicIcon, + PlusIcon, + SearchIcon, + Trash2Icon, + UnderlineIcon, +} from "lucide-react" + +import { Badge } from "@/components/ui/badge" +import { Button } from "@/components/ui/button" +import { Checkbox } from "@/components/ui/checkbox" +import { + Field, + FieldDescription, + FieldError, + FieldGroup, + FieldLabel, + FieldLegend, + FieldSet, +} from "@/components/ui/field" +import { Input } from "@/components/ui/input" +import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from "@/components/ui/input-group" +import { Kbd, KbdGroup } from "@/components/ui/kbd" +import { Label } from "@/components/ui/label" +import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group" +import { + Select, + SelectContent, + SelectGroup, + SelectItem, + SelectLabel, + SelectTrigger, + SelectValue, +} from "@/components/ui/select" +import { Spinner } from "@/components/ui/spinner" +import { Switch } from "@/components/ui/switch" +import { Textarea } from "@/components/ui/textarea" +import { Toggle } from "@/components/ui/toggle" +import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group" +import { AiTag } from "@/components/app/ai-tag" +import { KbdHint } from "@/components/app/kbd-hint" + +import { Block, ShowcaseSection, StateMatrix, previewState } from "./helpers" + +const BUTTON_VARIANTS = ["default", "secondary", "outline", "text", "ghost", "destructive", "link"] as const +const BUTTON_LABELS: Record<(typeof BUTTON_VARIANTS)[number], string> = { + default: "Create plan", + secondary: "Review deck", + outline: "Cancel", + text: "Show answer", + ghost: "Skip", + destructive: "Delete plan", + link: "Upload materials", +} + +export function Actions() { + return ( + <ShowcaseSection + id="actions" + title="Actions" + description="Pill buttons with an M3 state layer. One filled button per group; outlined or text for the rest." + > + <Block title="Button" description="Variants by state. Loading reuses the verb with a spinner."> + <StateMatrix + rows={BUTTON_VARIANTS} + states={["default", "hover", "focus", "active", "disabled", "loading"]} + render={(variant, state) => + state === "loading" ? ( + <Button variant={variant} disabled> + <Spinner data-icon="inline-start" aria-hidden="true" role={undefined} /> + Saving… + </Button> + ) : ( + <Button variant={variant} {...previewState(state)}> + {BUTTON_LABELS[variant]} + </Button> + ) + } + /> + </Block> + + <div className="grid gap-6 lg:grid-cols-2"> + <Block title="Sizes and icons"> + <div className="flex flex-col gap-4"> + <div className="flex flex-wrap items-center gap-3"> + <Button size="xs">Extra small</Button> + <Button size="sm">Small</Button> + <Button>Default</Button> + <Button size="lg">Large</Button> + </div> + <div className="flex flex-wrap items-center gap-3"> + <Button> + <PlusIcon data-icon="inline-start" aria-hidden="true" /> + New plan + </Button> + <Button variant="outline"> + <CalendarPlusIcon data-icon="inline-start" aria-hidden="true" /> + Add to Google Calendar + </Button> + <Button variant="text"> + All sessions + <ChevronRightIcon data-icon="inline-end" aria-hidden="true" /> + </Button> + </div> + <div className="flex flex-wrap items-center gap-3"> + <Button size="icon" variant="ghost" aria-label="Search"> + <SearchIcon aria-hidden="true" /> + </Button> + <Button size="icon" variant="secondary" aria-label="New plan"> + <PlusIcon aria-hidden="true" /> + </Button> + <Button size="icon" aria-label="New plan"> + <PlusIcon aria-hidden="true" /> + </Button> + <Button size="icon-sm" variant="ghost" aria-label="Delete Linked lists guide"> + <Trash2Icon aria-hidden="true" /> + </Button> + </div> + <div className="max-w-60"> + <Button className="w-full"> + <span className="truncate">Reschedule 3 sessions before Prelim 1 in CS 2110</span> + </Button> + </div> + </div> + </Block> + + <Block title="Badge" description="Status chips. The words carry the meaning; colour reinforces it."> + <div className="flex flex-col gap-4"> + <div className="flex flex-wrap items-center gap-2"> + <Badge>Due today</Badge> + <Badge variant="secondary">Learning</Badge> + <Badge variant="success">Mastered</Badge> + <Badge variant="warning">1 missed</Badge> + <Badge variant="destructive">3 unresolved</Badge> + <AiTag /> + </div> + <div className="max-w-48"> + <Badge variant="outline" className="max-w-full"> + <span className="truncate">Introduction to algorithms and data structures</span> + </Badge> + </div> + </div> + </Block> + </div> + + <div className="grid gap-6 lg:grid-cols-2"> + <Block title="Toggle group" description="2 to 7 options, one choice: an M3 segmented button."> + <div className="flex flex-col gap-4"> + <ToggleGroup type="single" variant="outline" spacing={0} defaultValue="week" aria-label="Range"> + <ToggleGroupItem value="day">Day</ToggleGroupItem> + <ToggleGroupItem value="week">Week</ToggleGroupItem> + <ToggleGroupItem value="month">Month</ToggleGroupItem> + </ToggleGroup> + <ToggleGroup type="multiple" spacing={1} defaultValue={["bold"]} aria-label="Formatting"> + <ToggleGroupItem value="bold" aria-label="Bold"> + <BoldIcon aria-hidden="true" /> + </ToggleGroupItem> + <ToggleGroupItem value="italic" aria-label="Italic"> + <ItalicIcon aria-hidden="true" /> + </ToggleGroupItem> + <ToggleGroupItem value="underline" aria-label="Underline"> + <UnderlineIcon aria-hidden="true" /> + </ToggleGroupItem> + </ToggleGroup> + <div className="flex items-center gap-2"> + <Toggle aria-label="Show answers" defaultPressed> + Show answers + </Toggle> + <Toggle variant="outline" disabled aria-label="Shuffle"> + Shuffle + </Toggle> + </div> + </div> + </Block> + <Block title="Keys" description="Key hints are aria-hidden and hidden on touch screens."> + <div className="flex flex-wrap items-center gap-4 type-body-m text-on-surface-variant"> + <span className="flex items-center gap-2"> + <Kbd>1</Kbd> + <Kbd>2</Kbd> + <Kbd>3</Kbd> + <Kbd>4</Kbd> answer + </span> + <span className="flex items-center gap-2"> + <Kbd>Enter</Kbd> continue + </span> + <span className="flex items-center gap-2"> + <KbdGroup> + <Kbd>Ctrl</Kbd> + <Kbd>Enter</Kbd> + </KbdGroup> + submit + </span> + <span className="flex items-center gap-2"> + <KbdHint keys={["Mod", "K"]} /> KbdHint with Mod + </span> + </div> + </Block> + </div> + </ShowcaseSection> + ) +} + +export function Inputs() { + const [course, setCourse] = React.useState("cs2110") + return ( + <ShowcaseSection + id="inputs" + title="Inputs" + description="Outlined fields at 48px with 16px text: 1px outline, on-surface on hover, 2px primary on focus. Labels sit above, helper text below." + > + <Block title="Text field" description="Default, hover, focus, disabled and invalid."> + <StateMatrix + rows={["input"] as const} + states={["default", "hover", "focus", "disabled", "invalid"]} + render={(_, state) => ( + <Input + aria-label={`Course, ${state}`} + defaultValue={state === "default" ? "" : "CS 2110"} + placeholder="CS 2110" + aria-invalid={state === "invalid" || undefined} + className="w-44" + {...previewState(state)} + /> + )} + /> + </Block> + + <div className="grid gap-6 lg:grid-cols-2"> + <Block title="Form fields"> + <FieldGroup> + <Field> + <FieldLabel htmlFor="ds-course">Course</FieldLabel> + <Input id="ds-course" placeholder="CS 2110" /> + </Field> + <Field data-invalid> + <FieldLabel htmlFor="ds-exam">Exam name</FieldLabel> + <Input id="ds-exam" aria-invalid aria-describedby="ds-exam-error" /> + <FieldError id="ds-exam-error">Enter an exam name, like Prelim 1.</FieldError> + </Field> + <Field> + <FieldLabel htmlFor="ds-rule">Correction rule</FieldLabel> + <FieldDescription id="ds-rule-help"> + The rule or fact that makes the answer right, in your own words. It comes back in repair questions. + </FieldDescription> + <Textarea id="ds-rule" aria-describedby="ds-rule-help" /> + </Field> + <Field data-disabled> + <FieldLabel htmlFor="ds-email">Email</FieldLabel> + <Input id="ds-email" disabled defaultValue="name@example.com" /> + </Field> + </FieldGroup> + </Block> + + <Block title="Choices"> + <FieldGroup> + <Field> + <FieldLabel htmlFor="ds-select">Course</FieldLabel> + <Select value={course} onValueChange={setCourse}> + <SelectTrigger id="ds-select" className="w-full"> + <SelectValue placeholder="Choose a course" /> + </SelectTrigger> + <SelectContent position="popper"> + <SelectGroup> + <SelectLabel>Courses</SelectLabel> + <SelectItem value="cs2110">CS 2110</SelectItem> + <SelectItem value="math1920">MATH 1920</SelectItem> + <SelectItem value="info1300">INFO 1300</SelectItem> + </SelectGroup> + </SelectContent> + </Select> + </Field> + <FieldSet> + <FieldLegend variant="label">Study modes</FieldLegend> + <FieldDescription>Choose every mode this plan can use.</FieldDescription> + <FieldGroup className="gap-3"> + <Field orientation="horizontal"> + <Checkbox id="ds-m1" defaultChecked /> + <FieldLabel htmlFor="ds-m1" className="font-normal"> + Retrieval + </FieldLabel> + </Field> + <Field orientation="horizontal"> + <Checkbox id="ds-m2" /> + <FieldLabel htmlFor="ds-m2" className="font-normal"> + Interleaved practice + </FieldLabel> + </Field> + <Field orientation="horizontal" data-disabled> + <Checkbox id="ds-m3" disabled /> + <FieldLabel htmlFor="ds-m3" className="font-normal"> + Exam simulation + </FieldLabel> + </Field> + </FieldGroup> + </FieldSet> + <FieldSet> + <FieldLegend variant="label">Session length</FieldLegend> + <RadioGroup defaultValue="30"> + {["20", "30", "45"].map((v) => ( + <Field key={v} orientation="horizontal"> + <RadioGroupItem value={v} id={`ds-len-${v}`} /> + <FieldLabel htmlFor={`ds-len-${v}`} className="font-normal"> + {v} min + </FieldLabel> + </Field> + ))} + </RadioGroup> + </FieldSet> + <Field orientation="horizontal"> + <Switch id="ds-sw" defaultChecked /> + <FieldLabel htmlFor="ds-sw" className="font-normal"> + Email reminders + </FieldLabel> + </Field> + <Field orientation="horizontal"> + <Switch id="ds-sw2" /> + <Label htmlFor="ds-sw2" className="font-normal"> + Add sessions to Google Calendar + </Label> + </Field> + </FieldGroup> + </Block> + </div> + + <Block title="Input group" description="Buttons and icons inside a field use InputGroup."> + <div className="flex max-w-xl flex-col gap-4"> + <InputGroup> + <InputGroupAddon> + <SearchIcon aria-hidden="true" /> + </InputGroupAddon> + <InputGroupInput aria-label="Search your materials" placeholder="Recursion" /> + </InputGroup> + <InputGroup> + <InputGroupInput aria-label="Ask about CS 2110" placeholder="What is a base case?" /> + <InputGroupAddon align="inline-end"> + <InputGroupButton variant="default" size="sm"> + Ask + </InputGroupButton> + </InputGroupAddon> + </InputGroup> + </div> + </Block> + </ShowcaseSection> + ) +} diff --git a/src/app/(app)/design/_showcase/design-system.tsx b/src/app/(app)/design/_showcase/design-system.tsx new file mode 100644 index 00000000..e99183c8 --- /dev/null +++ b/src/app/(app)/design/_showcase/design-system.tsx @@ -0,0 +1,65 @@ +"use client" + +import { PageContainer } from "@/components/app/page-container" +import { PageHeader } from "@/components/app/page-header" +import { ThemeToggle } from "@/components/app/theme-toggle" + +import { AppComponents } from "./app-components" +import { Actions, Inputs } from "./controls" +import { Foundations } from "./foundations" +import { LessonPrimitives } from "./lesson" +import { HomeRecipe, Rules } from "./recipes" +import { DataDisplay, Feedback, Navigation, Overlays } from "./surfaces" + +const SECTIONS = [ + { id: "foundations", label: "Foundations" }, + { id: "actions", label: "Actions" }, + { id: "inputs", label: "Inputs" }, + { id: "navigation", label: "Navigation" }, + { id: "data", label: "Data display" }, + { id: "feedback", label: "Feedback" }, + { id: "overlays", label: "Overlays" }, + { id: "app", label: "App components" }, + { id: "lesson", label: "Lesson" }, + { id: "rules", label: "Do and don't" }, + { id: "recipe", label: "Recipe" }, +] + +export function DesignSystem() { + return ( + <PageContainer size="wide" className="gap-12"> + <div className="flex flex-col gap-4"> + <PageHeader + title="Study Bot design system" + description="Every token, the type scale, the shared components and the lesson primitives, in both themes. Development only." + actions={<ThemeToggle variant="segmented" />} + /> + <nav aria-label="Sections" className="-mx-1 overflow-x-auto no-scrollbar"> + <ul className="flex w-max gap-2 px-1 py-1"> + {SECTIONS.map((s) => ( + <li key={s.id}> + <a + href={`#${s.id}`} + className="state-layer relative isolate inline-flex h-8 items-center rounded-lg border border-outline-variant px-3 type-label-l text-on-surface-variant" + > + {s.label} + </a> + </li> + ))} + </ul> + </nav> + </div> + <Foundations /> + <Actions /> + <Inputs /> + <Navigation /> + <DataDisplay /> + <Feedback /> + <Overlays /> + <AppComponents /> + <LessonPrimitives /> + <Rules /> + <HomeRecipe /> + </PageContainer> + ) +} diff --git a/src/app/(app)/design/_showcase/foundations.tsx b/src/app/(app)/design/_showcase/foundations.tsx new file mode 100644 index 00000000..4893fb41 --- /dev/null +++ b/src/app/(app)/design/_showcase/foundations.tsx @@ -0,0 +1,287 @@ +"use client" + +import { + BookOpenTextIcon, + CalendarDaysIcon, + ChartColumnIcon, + CheckIcon, + CircleAlertIcon, + GraduationCapIcon, + HouseIcon, + LayersIcon, + MessagesSquareIcon, + SettingsIcon, +} from "lucide-react" + +import { formatPercent, formatTimeRange } from "@/lib/format" + +import { Block, ColorPair, ShowcaseSection } from "./helpers" + +const SHELL_PAIRS: { name: string; bg: string; fg: string; min?: number }[] = [ + { name: "Page", bg: "background", fg: "foreground" }, + { name: "Card", bg: "card", fg: "card-foreground" }, + { name: "Menu and popover", bg: "popover", fg: "popover-foreground" }, + { name: "Filled button", bg: "primary", fg: "primary-foreground" }, + { name: "Tonal button, active nav", bg: "secondary", fg: "secondary-foreground" }, + { name: "Muted surface", bg: "muted", fg: "muted-foreground" }, + { name: "Hover and selected", bg: "accent", fg: "accent-foreground" }, + { name: "Primary container", bg: "primary-container", fg: "on-primary-container" }, + { name: "Success container", bg: "tertiary-container", fg: "on-tertiary-container" }, + { name: "Warning container", bg: "warning-container", fg: "on-warning-container" }, + { name: "Error container", bg: "error-container", fg: "on-error-container" }, + { name: "Snackbar and tooltip", bg: "inverse-surface", fg: "inverse-on-surface" }, + { name: "Secondary text on page", bg: "surface", fg: "on-surface-variant" }, + { name: "Secondary text, highest", bg: "surface-container-highest", fg: "on-surface-variant" }, + { name: "Link on page", bg: "surface", fg: "primary" }, + { name: "Success text", bg: "surface", fg: "tertiary" }, + { name: "Warning text", bg: "surface", fg: "warning" }, + { name: "Error text", bg: "surface", fg: "error" }, + { name: "Field border (UI, 3:1)", bg: "surface-container-lowest", fg: "outline", min: 3 }, + { name: "Focus ring (UI, 3:1)", bg: "surface", fg: "ring", min: 3 }, +] + +const LESSON_PAIRS: { name: string; bg: string; fg: string; min?: number }[] = [ + { name: "Lesson page", bg: "lesson-surface", fg: "lesson-on-surface" }, + { name: "Counter and hints", bg: "lesson-surface", fg: "lesson-muted" }, + { name: "Selected option", bg: "lesson-selected", fg: "lesson-on-selected" }, + { name: "Check button", bg: "lesson-check", fg: "lesson-on-check" }, + { name: "Start button", bg: "lesson-primary", fg: "lesson-on-primary" }, + { name: "Correct feedback", bg: "lesson-correct", fg: "lesson-on-correct" }, + { name: "Wrong feedback", bg: "lesson-wrong", fg: "lesson-on-wrong" }, + { name: "Wrong continue", bg: "lesson-wrong-button", fg: "lesson-on-wrong-button" }, + { name: "Progress fill (UI, 3:1)", bg: "lesson-progress-track", fg: "lesson-progress-fill", min: 3 }, +] + +const SURFACES = [ + "surface", + "surface-container-lowest", + "surface-container-low", + "surface-container", + "surface-container-high", + "surface-container-highest", +] + +const SWATCHES: { group: string; tokens: string[] }[] = [ + { group: "Surfaces", tokens: SURFACES }, + { + group: "Lines and focus", + tokens: ["outline", "outline-variant", "ring", "scrim"], + }, + { + group: "Accents", + tokens: ["primary", "primary-container", "secondary-container", "tertiary", "tertiary-container", "warning", "warning-container", "error", "error-container", "inverse-primary"], + }, + { group: "Charts", tokens: ["chart-1", "chart-2", "chart-3", "chart-4", "chart-5"] }, + { + group: "Lesson", + tokens: [ + "lesson-option-border", + "lesson-option-hover", + "lesson-selected", + "lesson-selected-border", + "lesson-check", + "lesson-check-lip", + "lesson-correct", + "lesson-wrong", + "lesson-wrong-button", + "lesson-primary", + "lesson-disabled", + "lesson-progress-track", + "lesson-progress-fill", + ], + }, +] + +const TYPE_SCALE: { token: string; spec: string; use: string; sample: string }[] = [ + { token: "type-display-l", spec: "57/64 · 400 · -0.25px", use: "Rare: a single hero figure", sample: "14 days" }, + { token: "type-display-m", spec: "45/52 · 400", use: "Countdown days on the featured exam", sample: "9 days" }, + { token: "type-display-s", spec: "36/44 · 400", use: "End-screen accuracy", sample: "83% accuracy" }, + { token: "type-headline-l", spec: "32/40 · 400", use: "Status words in big cards", sample: "Today" }, + { token: "type-headline-m", spec: "28/36 · 400", use: "Lesson question (700 in sessions)", sample: "What does a stack frame hold?" }, + { token: "type-headline-s", spec: "24/32 · 400", use: "View headlines, dialog titles", sample: "Prelim 1 plan" }, + { token: "type-title-l", spec: "22/28 · 400", use: "Top app bar title", sample: "Study guides" }, + { token: "type-title-m", spec: "16/24 · 500 · 0.15px", use: "Section and card titles", sample: "Weak spots" }, + { token: "type-title-s", spec: "14/20 · 500 · 0.1px", use: "Small titles, table heads", sample: "Follow-up sessions" }, + { token: "type-body-l", spec: "16/24 · 400 · 0.5px", use: "Reading text, explanations", sample: "Answer from memory, then check against the model answer." }, + { token: "type-body-m", spec: "14/20 · 400 · 0.25px", use: "Default UI text", sample: "Sessions in this plan fall between these times each day." }, + { token: "type-body-s", spec: "12/16 · 400 · 0.4px", use: "Helper text, captions", sample: "Use at least 8 characters." }, + { token: "type-label-l", spec: "14/20 · 500 · 0.1px", use: "Buttons, field labels", sample: "Create plan" }, + { token: "type-label-m", spec: "12/16 · 500 · 0.5px", use: "Nav labels, chips", sample: "Progress" }, + { token: "type-label-s", spec: "11/16 · 500 · 0.5px", use: "Key hints", sample: "Ctrl+Enter" }, +] + +const RADII = [ + { token: "rounded-sm", value: "4px", use: "Tooltips, key hints, snackbar" }, + { token: "rounded-md", value: "8px", use: "Text fields, menus, selects" }, + { token: "rounded-lg", value: "12px", use: "Alerts, list rows" }, + { token: "rounded-2xl", value: "16px", use: "Cards, answer options, lesson buttons" }, + { token: "rounded-4xl", value: "28px", use: "Dialogs, bottom sheets" }, + { token: "rounded-full", value: "pill", use: "Buttons, chips, nav indicators" }, +] + +const ELEVATION = [ + { token: "flat", className: "ring-1 ring-border", use: "Cards at rest: tonal, hairline" }, + { token: "shadow-sm", className: "shadow-sm", use: "Hovered card, filled button hover" }, + { token: "shadow-md", className: "shadow-md", use: "Menus, popovers, selects" }, + { token: "shadow-lg", className: "shadow-lg", use: "Dialogs, sheets, snackbar" }, +] + +const MOTION = [ + { token: "--duration-short", value: "150ms", use: "State layers, colour changes, presses" }, + { token: "--duration-medium", value: "250ms", use: "Progress, sheets opening" }, + { token: "--duration-long", value: "350ms", use: "Feedback sheet sliding up" }, + { token: "--duration-dial", value: "600ms after 120ms", use: "The roundness dial entering a session" }, + { token: "ease-standard", value: "cubic-bezier(0.2, 0, 0, 1)", use: "State changes" }, + { token: "ease-emphasized", value: "cubic-bezier(0.05, 0.7, 0.1, 1)", use: "Entrances" }, +] + +const ICONS = [HouseIcon, CalendarDaysIcon, GraduationCapIcon, LayersIcon, BookOpenTextIcon, MessagesSquareIcon, ChartColumnIcon, SettingsIcon, CheckIcon, CircleAlertIcon] + +export function Foundations() { + return ( + <ShowcaseSection + id="foundations" + title="Foundations" + description="Google Material 3 roles for the shell, Google's product colours in Duolingo's grammar for sessions. Each pair shows the contrast measured live in the current theme." + > + <Block title="Colour roles: shell" description="Text pairs need 4.5:1, UI parts 3:1."> + <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4"> + {SHELL_PAIRS.map((p) => ( + <ColorPair key={p.name} name={p.name} background={p.bg} foreground={p.fg} min={p.min} /> + ))} + </div> + </Block> + + <Block title="Colour roles: lessons" description="Used only inside the .lesson scope of /s/[sessionId]."> + <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4"> + {LESSON_PAIRS.map((p) => ( + <ColorPair key={p.name} name={p.name} background={p.bg} foreground={p.fg} min={p.min} /> + ))} + </div> + </Block> + + <Block title="Palette"> + <div className="flex flex-col gap-6"> + {SWATCHES.map((group) => ( + <div key={group.group} className="flex flex-col gap-2"> + <h4 className="type-title-s text-on-surface-variant">{group.group}</h4> + <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-5 lg:grid-cols-7"> + {group.tokens.map((token) => ( + <div key={token} className="flex flex-col gap-1.5"> + <div + className="h-12 rounded-lg ring-1 ring-border" + style={{ backgroundColor: `var(--${token})` }} + /> + <span className="truncate font-mono text-[0.6875rem] text-on-surface-variant">{token}</span> + </div> + ))} + </div> + </div> + ))} + </div> + </Block> + + <Block title="Type scale" description="Google Sans Flex. Fixed rem sizes as type-* utilities, never text-* sizes."> + <div className="flex flex-col divide-y divide-border"> + {TYPE_SCALE.map((row) => ( + <div key={row.token} className="grid gap-1 py-3 md:grid-cols-[11rem_12rem_1fr] md:items-baseline md:gap-4"> + <code className="font-mono text-xs text-on-surface">{row.token}</code> + <span className="type-body-s text-on-surface-variant"> + {row.spec} + <span className="block">{row.use}</span> + </span> + <span className={`${row.token} min-w-0 truncate text-on-surface`}>{row.sample}</span> + </div> + ))} + </div> + <p className="mt-4 max-w-prose type-body-l text-on-surface"> + Running text sits at body-l with a 65 to 75 character measure.{" "} + <a href="#lesson" className="text-primary underline"> + Links + </a>{" "} + underline, and code such as <code className="rounded-sm bg-surface-container px-1 font-mono text-sm">useActiveCourse()</code>{" "} + uses Google Sans Code. Times and scores use tabular figures: <span className="tabular-nums"> + {formatTimeRange("2026-10-12T18:00:00Z", "2026-10-12T18:30:00Z", { timeZone: "America/New_York" })},{" "} + {formatPercent(0.83)} + </span>. + </p> + </Block> + + <Block + title="The roundness dial" + description="The shell sets ROND 0 with weights 400 and 500. Sessions set ROND 100 and step the weight up to 500 for body and 700 for questions and buttons." + > + <div className="grid gap-4 md:grid-cols-2"> + <div className="flex flex-col gap-2 rounded-xl bg-surface-container p-4"> + <span className="type-label-m text-on-surface-variant">Shell · ROND 0</span> + <span className="type-headline-s text-on-surface">What does a stack frame hold?</span> + <span className="type-body-m text-on-surface-variant">Answer from memory before you check anything.</span> + </div> + <div className="lesson flex flex-col gap-2 rounded-xl p-4 ring-1 ring-lesson-option-border"> + <span className="type-label-m text-lesson-muted">Session · ROND 100</span> + <span className="type-headline-s font-bold">What does a stack frame hold?</span> + <span className="type-body-m text-lesson-muted">Answer from memory before you check anything.</span> + </div> + </div> + </Block> + + <div className="grid gap-6 lg:grid-cols-2"> + <Block title="Shape"> + <div className="grid grid-cols-2 gap-4 sm:grid-cols-3"> + {RADII.map((r) => ( + <div key={r.token} className="flex flex-col gap-2"> + <div className={`h-14 border-2 border-primary bg-primary-container ${r.token}`} /> + <span className="font-mono text-xs text-on-surface"> + {r.token} · {r.value} + </span> + <span className="type-body-s text-on-surface-variant">{r.use}</span> + </div> + ))} + </div> + </Block> + <Block title="Elevation" description="Tonal first. Shadows only where something floats."> + <div className="grid grid-cols-2 gap-4"> + {ELEVATION.map((e) => ( + <div key={e.token} className="flex flex-col gap-2"> + <div className={`h-14 rounded-2xl bg-surface-container-lowest ${e.className}`} /> + <span className="font-mono text-xs text-on-surface">{e.token}</span> + <span className="type-body-s text-on-surface-variant">{e.use}</span> + </div> + ))} + </div> + </Block> + </div> + + <div className="grid gap-6 lg:grid-cols-2"> + <Block title="Motion" description="Motion only conveys state, and all of it stops under reduced motion."> + <div className="flex flex-col divide-y divide-border"> + {MOTION.map((m) => ( + <div key={m.token} className="grid grid-cols-[9.5rem_1fr] gap-3 py-2"> + <code className="font-mono text-xs text-on-surface">{m.token}</code> + <span className="type-body-s text-on-surface-variant"> + <span className="text-on-surface">{m.value}</span> · {m.use} + </span> + </div> + ))} + </div> + </Block> + <Block title="Icons" description="lucide-react only, stroke 2, rounded joins, aria-hidden beside a text label."> + <div className="flex flex-col gap-4"> + {[ + { cls: "size-4 text-on-surface", label: "16px" }, + { cls: "size-5 text-on-surface", label: "20px" }, + { cls: "size-6 text-on-surface-variant", label: "24px" }, + ].map((row) => ( + <div key={row.label} className="flex flex-wrap items-center gap-4"> + <span className="w-10 font-mono text-xs text-on-surface-variant">{row.label}</span> + {ICONS.map((Icon, i) => ( + <Icon key={i} className={row.cls} aria-hidden="true" /> + ))} + </div> + ))} + </div> + </Block> + </div> + </ShowcaseSection> + ) +} diff --git a/src/app/(app)/design/_showcase/helpers.tsx b/src/app/(app)/design/_showcase/helpers.tsx new file mode 100644 index 00000000..73148711 --- /dev/null +++ b/src/app/(app)/design/_showcase/helpers.tsx @@ -0,0 +1,203 @@ +"use client" + +import * as React from "react" + +import { cn } from "@/lib/utils" + +// Resolves any CSS colour to sRGB by painting one pixel, compositing +// translucent colours over the backdrop as the browser would. +function toRgb(color: string, backdrop = "#fff") { + const canvas = document.createElement("canvas") + canvas.width = canvas.height = 1 + const context = canvas.getContext("2d", { willReadFrequently: true }) + if (!context) return null + context.fillStyle = backdrop + context.fillRect(0, 0, 1, 1) + context.fillStyle = color + context.fillRect(0, 0, 1, 1) + const [r, g, b] = context.getImageData(0, 0, 1, 1).data + return [r, g, b] +} + +function toHex(rgb: number[]) { + return `#${rgb.map((v) => v.toString(16).padStart(2, "0")).join("")}` +} + +function luminance([r, g, b]: number[]) { + const [R, G, B] = [r, g, b].map((v) => { + const c = v / 255 + return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4 + }) + return 0.2126 * R + 0.7152 * G + 0.0722 * B +} + +function contrast(a: number[], b: number[]) { + const [light, dark] = [luminance(a), luminance(b)].sort((x, y) => y - x) + return (light + 0.05) / (dark + 0.05) +} + +/** A surface with "Aa" in its foreground colour and the live contrast ratio. */ +export function ColorPair({ + name, + background, + foreground, + min = 4.5, +}: { + name: string + background: string + foreground: string + /** 4.5 for text, 3 for UI parts and large text. */ + min?: number +}) { + const ref = React.useRef<HTMLDivElement>(null) + const [info, setInfo] = React.useState<{ ratio: number; bg: string; fg: string } | null>(null) + + React.useEffect(() => { + const element = ref.current + if (!element) return + const measure = () => { + const style = getComputedStyle(element) + const page = getComputedStyle(document.body).backgroundColor + const bg = toRgb(style.backgroundColor, page) + if (!bg) return + const fg = toRgb(style.color, toHex(bg)) + if (fg) setInfo({ ratio: contrast(bg, fg), bg: toHex(bg), fg: toHex(fg) }) + } + measure() + const observer = new MutationObserver(() => requestAnimationFrame(measure)) + observer.observe(document.documentElement, { attributes: true, attributeFilter: ["class"] }) + return () => observer.disconnect() + }, []) + + const pass = info ? info.ratio >= min : true + + return ( + <div className="flex flex-col overflow-hidden rounded-xl ring-1 ring-border"> + <div + ref={ref} + style={{ backgroundColor: `var(--${background})`, color: `var(--${foreground})` }} + className="flex h-20 items-end justify-between p-3" + > + <span className="type-headline-s">Aa</span> + {info ? ( + <span className="rounded-full border border-current/30 px-2 py-0.5 font-mono text-xs tabular-nums"> + {info.ratio.toFixed(2)} + {pass ? "" : " below " + min} + </span> + ) : null} + </div> + <div className="flex flex-col gap-0.5 bg-card p-3"> + <span className="type-label-l text-on-surface">{name}</span> + <span className="truncate font-mono text-[0.6875rem] text-on-surface-variant"> + {foreground} on {background} + </span> + {info ? ( + <span className="font-mono text-[0.6875rem] text-on-surface-variant"> + {info.fg} on {info.bg} + </span> + ) : null} + </div> + </div> + ) +} + +const defaultStates = ["default", "hover", "focus", "active", "disabled"] as const + +/** A labelled variant by state table; each cell renders one pinned state. */ +export function StateMatrix<Row extends string>({ + rows, + states = defaultStates, + render, + className, +}: { + rows: readonly Row[] + states?: readonly string[] + render: (row: Row, state: string) => React.ReactNode + className?: string +}) { + return ( + <div className={cn("w-full overflow-x-auto", className)}> + <table className="border-separate border-spacing-x-3 border-spacing-y-4"> + <thead> + <tr> + <th /> + {states.map((state) => ( + <th key={state} scope="col" className="text-left font-mono text-xs font-normal text-on-surface-variant"> + {state} + </th> + ))} + </tr> + </thead> + <tbody> + {rows.map((row) => ( + <tr key={row}> + <th scope="row" className="pr-2 text-left font-mono text-xs font-normal text-on-surface-variant"> + {row} + </th> + {states.map((state) => ( + <td key={state} className="align-middle"> + {render(row, state)} + </td> + ))} + </tr> + ))} + </tbody> + </table> + </div> + ) +} + +/** Spread onto a component to pin a state without interaction. */ +export function previewState(state: string): Record<string, unknown> { + if (state === "disabled") return { disabled: true } + if (["hover", "focus", "active"].includes(state)) return { "data-preview": state } + return {} +} + +/** One section of the page, with an anchor and an h2. */ +export function ShowcaseSection({ + id, + title, + description, + children, +}: { + id: string + title: string + description?: string + children: React.ReactNode +}) { + return ( + <section id={id} aria-labelledby={`${id}-title`} className="flex scroll-mt-24 flex-col gap-6"> + <div className="flex flex-col gap-1 border-b border-border pb-3"> + <h2 id={`${id}-title`} className="type-headline-s text-on-surface"> + {title} + </h2> + {description ? <p className="max-w-prose type-body-m text-on-surface-variant">{description}</p> : null} + </div> + {children} + </section> + ) +} + +/** A labelled block inside a section. */ +export function Block({ + title, + description, + children, + className, +}: { + title: string + description?: string + children: React.ReactNode + className?: string +}) { + return ( + <div className={cn("flex min-w-0 flex-col gap-3", className)}> + <div className="flex flex-col gap-0.5"> + <h3 className="type-title-m text-on-surface">{title}</h3> + {description ? <p className="max-w-prose type-body-m text-on-surface-variant">{description}</p> : null} + </div> + <div className="rounded-2xl bg-card p-5 ring-1 ring-border">{children}</div> + </div> + ) +} diff --git a/src/app/(app)/design/_showcase/lesson.tsx b/src/app/(app)/design/_showcase/lesson.tsx new file mode 100644 index 00000000..99b631b9 --- /dev/null +++ b/src/app/(app)/design/_showcase/lesson.tsx @@ -0,0 +1,247 @@ +"use client" + +import * as React from "react" + +import { AnswerOption, AnswerOptionGroup } from "@/components/lesson/answer-option" +import { ConfidencePicker, type ConfidenceValue } from "@/components/lesson/confidence-picker" +import { FeedbackSheet } from "@/components/lesson/feedback-sheet" +import { FreeRecallInput } from "@/components/lesson/free-recall-input" +import { LessonButton } from "@/components/lesson/lesson-button" +import { LessonFrame, LessonProgress } from "@/components/lesson/lesson-frame" + +import { ShowcaseSection, StateMatrix, previewState } from "./helpers" + +const BUTTON_VARIANTS = ["check", "correct", "wrong", "neutral", "primary"] as const +const BUTTON_LABELS: Record<(typeof BUTTON_VARIANTS)[number], string> = { + check: "Check", + correct: "Continue", + wrong: "Continue", + neutral: "Skip", + primary: "Start session", +} + +const OPTION_STATES = ["idle", "hover", "focus", "selected", "pending", "correct", "wrong", "disabled"] as const + +const CHOICES = [ + "The function's local variables, parameters and return address", + "Every object the program has allocated so far", + "The compiled bytecode of the method", + "Only the value the function returns", +] + +function LessonBlock({ title, children }: { title: string; children: React.ReactNode }) { + return ( + <div className="flex flex-col gap-3"> + <h3 className="type-title-m text-on-surface">{title}</h3> + <div className="lesson rounded-2xl p-5 ring-1 ring-border">{children}</div> + </div> + ) +} + +/** A working one-question lesson: pick, check, read feedback, continue. */ +function LiveLesson() { + const [selected, setSelected] = React.useState<string | null>(null) + const [confidence, setConfidence] = React.useState<ConfidenceValue | null>(null) + const [checked, setChecked] = React.useState(false) + const [done, setDone] = React.useState(0) + const correct = "0" + const isCorrect = selected === correct + + function reset() { + setSelected(null) + setConfidence(null) + setChecked(false) + setDone((d) => (d + 1) % 5) + } + + return ( + <div className="lesson h-[46rem] overflow-hidden rounded-2xl ring-1 ring-border"> + <LessonFrame + className="min-h-0 h-full overflow-y-auto" + current={done} + total={5} + status="Retrieval" + onClose={reset} + question="What does a stack frame hold?" + questionId="ds-live-question" + headingLevel="h2" + footer={ + <> + <LessonButton variant="neutral" onClick={reset} kbd="Esc"> + Skip + </LessonButton> + <LessonButton + variant="check" + disabled={selected === null} + onClick={() => setChecked(true)} + kbd="Enter" + className="sm:min-w-40" + > + Check + </LessonButton> + </> + } + feedback={ + checked ? ( + <FeedbackSheet + tone={isCorrect ? "correct" : "wrong"} + title={isCorrect ? "Correct" : "Incorrect"} + onContinue={reset} + > + <p> + {isCorrect + ? "Each call gets its own frame with its locals, parameters and return address." + : "A frame holds one call's locals, parameters and return address. Objects live on the heap."} + </p> + <p className="type-body-m opacity-90">Source 2: Lecture 5, page 3</p> + </FeedbackSheet> + ) : null + } + > + <AnswerOptionGroup labelledBy="ds-live-question"> + {CHOICES.map((choice, i) => ( + <AnswerOption + key={choice} + name="ds-live" + value={String(i)} + hint={String(i + 1)} + checked={selected === String(i)} + onSelect={setSelected} + disabled={checked} + result={checked ? (String(i) === correct ? "correct" : selected === String(i) ? "wrong" : undefined) : undefined} + > + {choice} + </AnswerOption> + ))} + </AnswerOptionGroup> + <ConfidencePicker value={confidence} onChange={setConfidence} hints={["Q", "W", "E"]} disabled={checked} /> + </LessonFrame> + </div> + ) +} + +export function LessonPrimitives() { + const [recall, setRecall] = React.useState("") + return ( + <ShowcaseSection + id="lesson" + title="Lesson primitives" + description="src/components/lesson, inside the .lesson scope: rounded type, heavier weights, Google's green, red and blue in Duolingo's grammar. Number keys belong to the screen; primitives only draw the hints." + > + <LessonBlock title="LessonButton"> + <StateMatrix + rows={BUTTON_VARIANTS} + states={["default", "hover", "focus", "active", "disabled", "loading"]} + render={(variant, state) => + state === "loading" ? ( + <LessonButton variant={variant} loading loadingLabel="Checking…"> + {BUTTON_LABELS[variant]} + </LessonButton> + ) : ( + <LessonButton variant={variant} {...previewState(state)}> + {BUTTON_LABELS[variant]} + </LessonButton> + ) + } + /> + </LessonBlock> + + <LessonBlock title="AnswerOption"> + <div className="grid gap-x-6 gap-y-4 md:grid-cols-2"> + {OPTION_STATES.map((state) => ( + <div key={state} className="flex flex-col gap-1.5"> + <span className="font-mono text-xs text-lesson-muted">{state}</span> + <AnswerOption + name={`ds-option-${state}`} + value="a" + hint="2" + checked={state === "selected" || state === "pending" || state === "focus"} + onSelect={() => undefined} + pending={state === "pending"} + result={state === "correct" ? "correct" : state === "wrong" ? "wrong" : undefined} + disabled={state === "disabled"} + {...(state === "hover" || state === "focus" ? { "data-preview": state } : {})} + > + {state === "idle" + ? "A stack frame holds the function's local variables, parameters and the return address, which can run onto a second line." + : CHOICES[0]} + </AnswerOption> + </div> + ))} + </div> + </LessonBlock> + + <div className="grid gap-6 lg:grid-cols-2"> + <LessonBlock title="ConfidencePicker"> + <div className="flex flex-col gap-6"> + <ConfidencePicker value={null} onChange={() => undefined} hints={["Q", "W", "E"]} /> + <ConfidencePicker value={5} onChange={() => undefined} description="Selected: Sure." /> + <ConfidencePicker value={3} onChange={() => undefined} disabled description="Disabled after checking." /> + </div> + </LessonBlock> + <LessonBlock title="FreeRecallInput"> + <div className="flex flex-col gap-6"> + <FreeRecallInput value={recall} onChange={(e) => setRecall(e.target.value)} /> + <FreeRecallInput + label="Correction rule" + description="The rule or fact that makes the answer right, in your own words." + defaultValue="A base case returns without calling itself" + error="Write the correction rule first." + showSubmitHint={false} + /> + <FreeRecallInput label="Your answer (disabled)" defaultValue="Locals and the return address" disabled /> + </div> + </LessonBlock> + </div> + + <LessonBlock title="LessonProgress"> + <div className="flex flex-col gap-4"> + {[0, 3, 9, 12].map((n) => ( + <div key={n} className="flex items-center gap-4"> + <span className="w-16 shrink-0 font-mono text-xs text-lesson-muted tabular-nums"> + {n} of 12 + </span> + <LessonProgress current={n} total={12} /> + </div> + ))} + </div> + </LessonBlock> + + <div className="flex flex-col gap-3"> + <h3 className="type-title-m text-on-surface">FeedbackSheet</h3> + <div className="lesson flex flex-col overflow-hidden rounded-2xl ring-1 ring-border"> + <FeedbackSheet tone="correct" title="Correct" onContinue={() => undefined} autoFocusContinue={false}> + <p>Each call gets its own frame with its locals, parameters and return address.</p> + </FeedbackSheet> + <FeedbackSheet + tone="wrong" + title="Incorrect" + onContinue={() => undefined} + autoFocusContinue={false} + secondaryAction={<LessonButton variant="neutral">Log the error</LessonButton>} + > + <p>Correct answer: the function's local variables, parameters and return address.</p> + </FeedbackSheet> + <FeedbackSheet + tone="neutral" + title="Model answer shown. Score your answer against it." + continueLabel="Next question" + onContinue={() => undefined} + autoFocusContinue={false} + continueLoading + > + <p>Points to check: base case, smaller input each call.</p> + </FeedbackSheet> + </div> + </div> + + <div className="flex flex-col gap-3"> + <h3 className="type-title-m text-on-surface">LessonFrame, working example</h3> + <p className="max-w-prose type-body-m text-on-surface-variant"> + Pick an answer and press Check. The footer turns into the feedback sheet; Continue moves on. + </p> + <LiveLesson /> + </div> + </ShowcaseSection> + ) +} diff --git a/src/app/(app)/design/_showcase/recipes.tsx b/src/app/(app)/design/_showcase/recipes.tsx new file mode 100644 index 00000000..9381f29d --- /dev/null +++ b/src/app/(app)/design/_showcase/recipes.tsx @@ -0,0 +1,183 @@ +"use client" + +import { CircleAlertIcon, FlameIcon, PlayIcon, TargetIcon, WrenchIcon, ZapIcon } from "lucide-react" + +import { Badge } from "@/components/ui/badge" +import { Button } from "@/components/ui/button" +import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card" +import { CountdownCard } from "@/components/app/countdown-card" +import { EmptyState } from "@/components/app/empty-state" +import { ErrorState } from "@/components/app/error-state" +import { MasteryBar } from "@/components/app/mastery-bar" +import { SectionHeader } from "@/components/app/section-header" +import { StatLine } from "@/components/app/stat-line" +import { formatTimeRange, plural } from "@/lib/format" + +import { ShowcaseSection } from "./helpers" + +const NOW = new Date("2026-10-12T16:00:00Z") +const ZONE = "America/New_York" + +function Pair({ rule, good, bad }: { rule: string; good: React.ReactNode; bad: React.ReactNode }) { + return ( + <div className="flex flex-col gap-3"> + <p className="type-title-s text-on-surface">{rule}</p> + <div className="grid gap-3 sm:grid-cols-2"> + <div className="flex flex-col gap-2 rounded-2xl bg-card p-4 ring-1 ring-border"> + <span className="type-label-m text-tertiary">Do</span> + {good} + </div> + <div className="flex flex-col gap-2 rounded-2xl bg-card p-4 ring-1 ring-border"> + <span className="type-label-m text-destructive">Don't</span> + {bad} + </div> + </div> + </div> + ) +} + +export function Rules() { + return ( + <ShowcaseSection id="rules" title="Do and don't" description="The rules screens break most easily."> + <div className="grid gap-8 lg:grid-cols-2"> + <Pair + rule="One filled button per group." + good={ + <div className="flex flex-wrap gap-2"> + <Button variant="text">Cancel</Button> + <Button>Create plan</Button> + </div> + } + bad={ + <div className="flex flex-wrap gap-2"> + <Button>Cancel</Button> + <Button>Create plan</Button> + </div> + } + /> + <Pair + rule="A failed load says so; it never borrows empty-state copy." + good={<ErrorState title="Decks didn't load." onRetry={() => undefined} />} + bad={<EmptyState title="No decks yet" description="Generate one from your materials." />} + /> + <Pair + rule="Status is words plus colour, never colour alone." + good={ + <div className="flex gap-2"> + <Badge variant="warning">1 missed</Badge> + <Badge variant="success">Mastered</Badge> + </div> + } + bad={ + <div className="flex gap-2" aria-hidden="true"> + <span className="size-4 rounded-full bg-warning" /> + <span className="size-4 rounded-full bg-tertiary" /> + </div> + } + /> + <Pair + rule="Icons come from lucide, beside a text label. No glyphs or emoji." + good={ + <Button variant="outline"> + <WrenchIcon data-icon="inline-start" aria-hidden="true" /> + Repair + </Button> + } + bad={<Button variant="outline">Repair →</Button>} + /> + </div> + </ShowcaseSection> + ) +} + +/** The Home first viewport, rebuilt from tokens and shared components only. */ +export function HomeRecipe() { + return ( + <ShowcaseSection + id="recipe" + title="Recipe: Home" + description="Exam countdowns lead, weak spots and today's session follow, and the stats sit in one quiet line." + > + <div className="flex flex-col gap-6 rounded-3xl bg-surface p-4 ring-1 ring-border sm:p-6"> + <section aria-labelledby="recipe-exams" className="flex flex-col gap-3"> + <SectionHeader id="recipe-exams" title="Exams" action={{ href: "/plan", label: "All plans" }} /> + <div className="grid gap-4 md:grid-cols-3"> + <CountdownCard + featured + examName="Prelim 1" + courseName="CS 2110" + examDate="2026-10-21T14:00:00Z" + timeZone={ZONE} + now={NOW} + sessionsDone={9} + sessionsTotal={14} + missedCount={1} + rescheduleHref="/plan" + /> + <CountdownCard examName="Midterm" courseName="MATH 1920" examDate="2026-10-27T14:00:00Z" timeZone={ZONE} now={NOW} sessionsDone={3} sessionsTotal={12} /> + <CountdownCard examName="Final" courseName="INFO 1300" examDate="2026-12-10T14:00:00Z" timeZone={ZONE} now={NOW} /> + </div> + </section> + + <div className="grid gap-6 lg:grid-cols-[3fr_2fr]"> + <section aria-labelledby="recipe-weak" className="flex flex-col gap-3"> + <SectionHeader id="recipe-weak" title="Weak spots" action={{ href: "/achievements", label: "All topics" }} /> + <Card> + <CardContent className="flex flex-col gap-5"> + {[ + { topic: "Recursion", value: 0.22, errors: 3 }, + { topic: "Linked lists", value: 0.41, errors: 1 }, + { topic: "Big-O notation", value: 0.55, errors: 0 }, + ].map((row) => ( + <div key={row.topic} className="flex items-end gap-4"> + <MasteryBar label={row.topic} value={row.value} className="flex-1" /> + {row.errors > 0 ? ( + <Button variant="outline" size="sm" aria-label={`Repair ${row.topic}`}> + <WrenchIcon data-icon="inline-start" aria-hidden="true" /> + Repair + </Button> + ) : null} + </div> + ))} + <p className="flex items-center gap-2 type-body-m text-on-surface-variant"> + <CircleAlertIcon className="size-4" aria-hidden="true" /> + 4 unresolved errors, mostly misconceptions. + </p> + </CardContent> + </Card> + </section> + + <section aria-labelledby="recipe-today" className="flex flex-col gap-3"> + <SectionHeader id="recipe-today" title="Today" /> + <Card> + <CardHeader> + <CardTitle>Retrieval: Recursion</CardTitle> + <CardDescription className="tabular-nums"> + {formatTimeRange("2026-10-12T18:00:00Z", "2026-10-12T18:30:00Z", { timeZone: ZONE })}{" "} + <span aria-hidden="true">·</span> {plural(10, { one: "# question", other: "# questions" })} + </CardDescription> + </CardHeader> + <CardContent className="type-body-m text-on-surface-variant"> + Topics: Recursion, Base cases, and the call stack. + </CardContent> + <CardFooter> + <Button className="w-full sm:w-auto"> + <PlayIcon data-icon="inline-start" aria-hidden="true" /> + Start session + </Button> + </CardFooter> + </Card> + </section> + </div> + + <StatLine + items={[ + { value: "12-day streak", icon: FlameIcon }, + { value: "83%", label: "accuracy", icon: TargetIcon }, + { value: "340 XP", icon: ZapIcon }, + ]} + /> + </div> + </ShowcaseSection> + ) +} diff --git a/src/app/(app)/design/_showcase/surfaces.tsx b/src/app/(app)/design/_showcase/surfaces.tsx new file mode 100644 index 00000000..bae3cb6c --- /dev/null +++ b/src/app/(app)/design/_showcase/surfaces.tsx @@ -0,0 +1,487 @@ +"use client" + +import * as React from "react" +import { + CalendarDaysIcon, + ChevronsUpDownIcon, + CircleCheckIcon, + FileTextIcon, + InfoIcon, + LayersIcon, + MoreVerticalIcon, + PencilIcon, + Trash2Icon, + TriangleAlertIcon, +} from "lucide-react" +import { toast } from "sonner" + +import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from "@/components/ui/accordion" +import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert" +import { Avatar, AvatarFallback } from "@/components/ui/avatar" +import { + Breadcrumb, + BreadcrumbItem, + BreadcrumbLink, + BreadcrumbList, + BreadcrumbPage, + BreadcrumbSeparator, +} from "@/components/ui/breadcrumb" +import { Button } from "@/components/ui/button" +import { Card, CardAction, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card" +import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible" +import { + Command, + CommandEmpty, + CommandGroup, + CommandInput, + CommandItem, + CommandList, + CommandSeparator, +} from "@/components/ui/command" +import { + Dialog, + DialogClose, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, + DialogTrigger, +} from "@/components/ui/dialog" +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuGroup, + DropdownMenuItem, + DropdownMenuLabel, + DropdownMenuSeparator, + DropdownMenuShortcut, + DropdownMenuTrigger, +} from "@/components/ui/dropdown-menu" +import { Empty, EmptyContent, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "@/components/ui/empty" +import { Field, FieldLabel } from "@/components/ui/field" +import { Input } from "@/components/ui/input" +import { Popover, PopoverContent, PopoverDescription, PopoverHeader, PopoverTitle, PopoverTrigger } from "@/components/ui/popover" +import { Progress } from "@/components/ui/progress" +import { ScrollArea } from "@/components/ui/scroll-area" +import { Separator } from "@/components/ui/separator" +import { Sheet, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetTitle, SheetTrigger } from "@/components/ui/sheet" +import { Skeleton } from "@/components/ui/skeleton" +import { Spinner } from "@/components/ui/spinner" +import { Table, TableBody, TableCaption, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table" +import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs" +import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip" +import { ConfirmDialog } from "@/components/app/confirm-dialog" +import { formatDateWeekday, formatTimeRange } from "@/lib/format" + +import { Block, ShowcaseSection } from "./helpers" + +const ZONE = { timeZone: "America/New_York" } +const SESSIONS = [ + { start: "2026-10-12T18:00:00Z", end: "2026-10-12T18:30:00Z", mode: "Retrieval", topic: "Recursion" }, + { start: "2026-10-14T13:00:00Z", end: "2026-10-14T13:30:00Z", mode: "Interleaved practice", topic: "Stacks, queues, and lists" }, + { start: "2026-10-15T20:30:00Z", end: "2026-10-15T21:00:00Z", mode: "Error repair", topic: "Big-O" }, +].map((s) => ({ ...s, day: formatDateWeekday(s.start, ZONE), time: formatTimeRange(s.start, s.end, ZONE) })) + +export function Navigation() { + return ( + <ShowcaseSection id="navigation" title="Navigation" description="M3 tabs: primary tabs with a 3px indicator, secondary tabs with a full-width line."> + <div className="grid gap-6 lg:grid-cols-2"> + <Block title="Tabs"> + <div className="flex flex-col gap-6"> + <Tabs defaultValue="concepts"> + <TabsList aria-label="Guide sections"> + <TabsTrigger value="concepts">Key concepts</TabsTrigger> + <TabsTrigger value="faq">FAQ</TabsTrigger> + <TabsTrigger value="cheat">Cheat sheet</TabsTrigger> + <TabsTrigger value="off" disabled> + Archived + </TabsTrigger> + </TabsList> + <TabsContent value="concepts" className="pt-3 type-body-m text-on-surface-variant"> + Recursion, base cases and the call stack. + </TabsContent> + <TabsContent value="faq" className="pt-3 type-body-m text-on-surface-variant"> + Questions students ask about this topic. + </TabsContent> + <TabsContent value="cheat" className="pt-3 type-body-m text-on-surface-variant"> + One page to review before the exam. + </TabsContent> + </Tabs> + <Tabs defaultValue="week"> + <TabsList variant="line" aria-label="Plan range"> + <TabsTrigger value="week">This week</TabsTrigger> + <TabsTrigger value="all">All sessions</TabsTrigger> + </TabsList> + <TabsContent value="week" className="pt-3 type-body-m text-on-surface-variant"> + 3 sessions this week. + </TabsContent> + <TabsContent value="all" className="pt-3 type-body-m text-on-surface-variant"> + 14 sessions until Prelim 1. + </TabsContent> + </Tabs> + </div> + </Block> + <Block title="Breadcrumb"> + <Breadcrumb> + <BreadcrumbList> + <BreadcrumbItem> + <BreadcrumbLink href="#navigation">Guides</BreadcrumbLink> + </BreadcrumbItem> + <BreadcrumbSeparator /> + <BreadcrumbItem> + <BreadcrumbLink href="#navigation">CS 2110</BreadcrumbLink> + </BreadcrumbItem> + <BreadcrumbSeparator /> + <BreadcrumbItem> + <BreadcrumbPage>Linked lists</BreadcrumbPage> + </BreadcrumbItem> + </BreadcrumbList> + </Breadcrumb> + </Block> + </div> + </ShowcaseSection> + ) +} + +export function DataDisplay() { + const [open, setOpen] = React.useState(false) + return ( + <ShowcaseSection id="data" title="Data display" description="Cards are white on the page in light and darker panels in dark, with a hairline. No nested cards."> + <div className="grid gap-6 lg:grid-cols-2"> + <Card> + <CardHeader> + <CardTitle>Today</CardTitle> + <CardDescription>Retrieval on Recursion, {SESSIONS[0].time}</CardDescription> + <CardAction> + <Button variant="ghost" size="icon-sm" aria-label="More actions for this session"> + <MoreVerticalIcon aria-hidden="true" /> + </Button> + </CardAction> + </CardHeader> + <CardContent className="type-body-m text-on-surface-variant"> + 10 questions from Lecture 5 and Lecture 6. 2 are repair questions for errors you logged last week. + </CardContent> + <CardFooter className="justify-end"> + <Button variant="text">Reschedule</Button> + <Button>Start session</Button> + </CardFooter> + </Card> + + <Card size="sm"> + <CardHeader> + <CardTitle>Small card</CardTitle> + <CardDescription>16px padding for dense lists.</CardDescription> + </CardHeader> + <CardContent className="flex flex-col gap-3"> + <div className="flex items-center gap-3"> + <Avatar> + <AvatarFallback>B</AvatarFallback> + </Avatar> + <Avatar size="lg"> + <AvatarFallback>CS</AvatarFallback> + </Avatar> + <Avatar size="sm"> + <AvatarFallback>M</AvatarFallback> + </Avatar> + </div> + <Separator /> + <Collapsible open={open} onOpenChange={setOpen} className="flex flex-col gap-2"> + <div className="flex items-center justify-between"> + <span className="type-title-s">Points to check</span> + <CollapsibleTrigger asChild> + <Button variant="ghost" size="icon-sm" aria-label={open ? "Hide points to check" : "Show points to check"}> + <ChevronsUpDownIcon aria-hidden="true" /> + </Button> + </CollapsibleTrigger> + </div> + <CollapsibleContent className="type-body-m text-on-surface-variant"> + The base case stops the recursion; each call works on a smaller input. + </CollapsibleContent> + </Collapsible> + </CardContent> + </Card> + </div> + + <Block title="Table"> + <Table> + <TableCaption>Sessions this week for Prelim 1.</TableCaption> + <TableHeader> + <TableRow> + <TableHead>Day</TableHead> + <TableHead>Time</TableHead> + <TableHead>Mode</TableHead> + <TableHead>Topics</TableHead> + </TableRow> + </TableHeader> + <TableBody> + {SESSIONS.map((s) => ( + <TableRow key={s.day}> + <TableCell>{s.day}</TableCell> + <TableCell className="tabular-nums">{s.time}</TableCell> + <TableCell>{s.mode}</TableCell> + <TableCell className="max-w-48 truncate">{s.topic}</TableCell> + </TableRow> + ))} + </TableBody> + </Table> + </Block> + + <div className="grid gap-6 lg:grid-cols-2"> + <Block title="Accordion"> + <Accordion type="single" collapsible defaultValue="a"> + <AccordionItem value="a"> + <AccordionTrigger>What counts as an unresolved error?</AccordionTrigger> + <AccordionContent> + A logged wrong answer. It is resolved after you answer it correctly on 2 different days. + </AccordionContent> + </AccordionItem> + <AccordionItem value="b"> + <AccordionTrigger>Why do follow-ups come sooner after a low score?</AccordionTrigger> + <AccordionContent>Lower accuracy brings follow-ups sooner.</AccordionContent> + </AccordionItem> + </Accordion> + </Block> + <Block title="Scroll area"> + <ScrollArea className="h-40 rounded-lg ring-1 ring-border"> + <ul className="flex flex-col divide-y divide-border"> + {["Lecture 1.pdf", "Lecture 2.pdf", "Lecture 3.pdf", "Lecture 4.pdf", "Lecture 5.pdf", "Lecture 6.pdf", "Notes week 3.md"].map((f) => ( + <li key={f} className="flex items-center gap-3 px-4 py-2.5 type-body-m"> + <FileTextIcon className="size-4 text-on-surface-variant" aria-hidden="true" /> + {f} + </li> + ))} + </ul> + </ScrollArea> + </Block> + </div> + </ShowcaseSection> + ) +} + +export function Feedback() { + return ( + <ShowcaseSection id="feedback" title="Feedback" description="Tonal banners for callouts, a snackbar for finished actions whose result isn't visible, skeletons while loading."> + <div className="grid gap-4 lg:grid-cols-2"> + <Alert role="status"> + <InfoIcon aria-hidden="true" /> + <AlertTitle>AI features are paused.</AlertTitle> + <AlertDescription>Existing decks and guides still work.</AlertDescription> + </Alert> + <Alert variant="info" role="status"> + <CalendarDaysIcon aria-hidden="true" /> + <AlertTitle>Sessions in this plan fall between these times each day.</AlertTitle> + </Alert> + <Alert variant="success" role="status"> + <CircleCheckIcon aria-hidden="true" /> + <AlertTitle>Added to Google Calendar</AlertTitle> + <AlertDescription>14 sessions between today and Prelim 1.</AlertDescription> + </Alert> + <Alert variant="warning" role="status"> + <TriangleAlertIcon aria-hidden="true" /> + <AlertTitle>8 of 10 sessions added.</AlertTitle> + <AlertDescription>2 sessions conflict with events in your calendar.</AlertDescription> + </Alert> + <Alert variant="destructive"> + <TriangleAlertIcon aria-hidden="true" /> + <AlertTitle>Answer not saved.</AlertTitle> + <AlertDescription>Your text is still here. Check your connection and retry.</AlertDescription> + </Alert> + </div> + + <div className="grid gap-6 lg:grid-cols-2"> + <Block title="Snackbar" description="Object plus past verb, no period, at most one action."> + <div className="flex flex-wrap gap-3"> + <Button variant="outline" onClick={() => toast("Deck deleted")}> + Show snackbar + </Button> + <Button + variant="outline" + onClick={() => + toast("Plan created", { + action: { label: "View plan", onClick: () => undefined }, + }) + } + > + With an action + </Button> + </div> + </Block> + <Block title="Progress, spinner and skeleton"> + <div className="flex flex-col gap-4"> + <Progress value={64} aria-label="Upload progress" /> + <div className="flex items-center gap-3 type-body-m text-on-surface-variant"> + <Spinner /> Generating deck… This can take up to a minute. + </div> + <div className="flex items-center gap-4"> + <Skeleton className="size-10 rounded-full" /> + <div className="flex flex-1 flex-col gap-2"> + <Skeleton className="h-4 w-2/5" /> + <Skeleton className="h-3 w-3/5" /> + </div> + </div> + </div> + </Block> + </div> + + <Block title="Empty (shadcn)"> + <Empty> + <EmptyHeader> + <EmptyMedia variant="icon"> + <LayersIcon aria-hidden="true" /> + </EmptyMedia> + <EmptyTitle>No decks for CS 2110 yet</EmptyTitle> + <EmptyDescription>Generate one from your CS 2110 materials.</EmptyDescription> + </EmptyHeader> + <EmptyContent> + <Button>Generate deck</Button> + </EmptyContent> + </Empty> + </Block> + </ShowcaseSection> + ) +} + +export function Overlays() { + const [command, setCommand] = React.useState("none") + return ( + <ShowcaseSection id="overlays" title="Overlays" description="Each trigger opens the real component. Dialogs and sheets use 28px corners on a 32% scrim."> + <Block title="Triggers"> + <div className="flex flex-wrap items-center gap-3"> + <Dialog> + <DialogTrigger asChild> + <Button variant="outline">Open dialog</Button> + </DialogTrigger> + <DialogContent> + <DialogHeader> + <DialogTitle>Rename deck</DialogTitle> + <DialogDescription>The new name shows on the Cards page and in your plan.</DialogDescription> + </DialogHeader> + <Field> + <FieldLabel htmlFor="ds-deck-name">Deck name</FieldLabel> + <Input id="ds-deck-name" defaultValue="Recursion basics" /> + </Field> + <DialogFooter> + <DialogClose asChild> + <Button variant="text">Cancel</Button> + </DialogClose> + <Button>Save name</Button> + </DialogFooter> + </DialogContent> + </Dialog> + + <ConfirmDialog + trigger={<Button variant="outline">Open confirm dialog</Button>} + title="Delete the Prelim 1 plan?" + description="Its 12 scheduled sessions come off your schedule. Your answers and progress stay, and so do events already in Google Calendar." + confirmLabel="Delete plan" + pendingLabel="Deleting plan…" + onConfirm={() => new Promise((resolve) => setTimeout(resolve, 800))} + /> + + <ConfirmDialog + trigger={<Button variant="outline">Typed confirmation</Button>} + title="Delete your account?" + description="This permanently deletes your plans, sessions, answers, materials, decks, guides, and chat history. Export your data first if you want a copy." + confirmLabel="Delete account" + confirmText="name@example.com" + confirmTextLabel="Type your email address to confirm" + onConfirm={() => new Promise((_, reject) => setTimeout(() => reject(new Error("demo")), 600))} + /> + + <Sheet> + <SheetTrigger asChild> + <Button variant="outline">Open side sheet</Button> + </SheetTrigger> + <SheetContent> + <SheetHeader> + <SheetTitle>Session details</SheetTitle> + <SheetDescription>Retrieval on Recursion, Wed, Oct 14.</SheetDescription> + </SheetHeader> + <div className="px-6 type-body-m text-on-surface-variant">10 questions, about 30 min.</div> + <SheetFooter> + <Button>Start session</Button> + </SheetFooter> + </SheetContent> + </Sheet> + + <Popover> + <PopoverTrigger asChild> + <Button variant="outline">Open popover</Button> + </PopoverTrigger> + <PopoverContent> + <PopoverHeader> + <PopoverTitle>Confident error</PopoverTitle> + <PopoverDescription> + You marked this Sure. This question comes back on another day. + </PopoverDescription> + </PopoverHeader> + </PopoverContent> + </Popover> + + <Tooltip> + <TooltipTrigger asChild> + <Button variant="ghost" size="icon" aria-label="Edit deck"> + <PencilIcon aria-hidden="true" /> + </Button> + </TooltipTrigger> + <TooltipContent>Edit deck</TooltipContent> + </Tooltip> + + <DropdownMenu> + <DropdownMenuTrigger asChild> + <Button variant="ghost" size="icon" aria-label="Open deck menu"> + <MoreVerticalIcon aria-hidden="true" /> + </Button> + </DropdownMenuTrigger> + <DropdownMenuContent align="start"> + <DropdownMenuGroup> + <DropdownMenuLabel>Recursion basics</DropdownMenuLabel> + <DropdownMenuItem> + <PencilIcon aria-hidden="true" /> + Rename deck + <DropdownMenuShortcut>R</DropdownMenuShortcut> + </DropdownMenuItem> + <DropdownMenuItem> + <LayersIcon aria-hidden="true" /> + Review deck + </DropdownMenuItem> + </DropdownMenuGroup> + <DropdownMenuSeparator /> + <DropdownMenuGroup> + <DropdownMenuItem variant="destructive"> + <Trash2Icon aria-hidden="true" /> + Delete deck + </DropdownMenuItem> + </DropdownMenuGroup> + </DropdownMenuContent> + </DropdownMenu> + </div> + </Block> + + <Block title="Command" description="Inline, controlled so it doesn't scroll the page on mount."> + <Command value={command} onValueChange={setCommand} className="max-w-md ring-1 ring-border"> + <CommandInput placeholder="Recursion" aria-label="Search pages and actions" /> + <CommandList> + <CommandEmpty>Nothing matches.</CommandEmpty> + <CommandGroup heading="Pages"> + <CommandItem value="plan"> + <CalendarDaysIcon aria-hidden="true" /> + Plan + </CommandItem> + <CommandItem value="cards"> + <LayersIcon aria-hidden="true" /> + Flashcards + </CommandItem> + </CommandGroup> + <CommandSeparator /> + <CommandGroup heading="Actions"> + <CommandItem value="new plan">New plan</CommandItem> + <CommandItem value="upload">Upload materials</CommandItem> + </CommandGroup> + </CommandList> + </Command> + </Block> + </ShowcaseSection> + ) +} diff --git a/src/app/(app)/design/page.tsx b/src/app/(app)/design/page.tsx new file mode 100644 index 00000000..239e6f29 --- /dev/null +++ b/src/app/(app)/design/page.tsx @@ -0,0 +1,15 @@ +import type { Metadata } from "next"; +import { notFound } from "next/navigation"; + +import { DesignSystem } from "./_showcase/design-system"; + +export const metadata: Metadata = { + title: "Design system", + robots: { index: false }, +}; + +/** Development-only reference page for the tokens and components. */ +export default function DesignPage() { + if (process.env.NODE_ENV === "production") notFound(); + return <DesignSystem />; +} diff --git a/src/app/(app)/error.tsx b/src/app/(app)/error.tsx new file mode 100644 index 00000000..ea6d3af5 --- /dev/null +++ b/src/app/(app)/error.tsx @@ -0,0 +1,44 @@ +"use client"; + +import { useEffect } from "react"; +import Link from "next/link"; +import { CloudOffIcon, RotateCcwIcon } from "lucide-react"; + +import { StatusScreen } from "@/components/app/status-screen"; +import { Button } from "@/components/ui/button"; + +/** A page inside the app shell failed to render; the shell stays usable. */ +export default function AppError({ + error, + retry, +}: { + error: Error & { digest?: string }; + /** Refetches and re-renders the segment (reset would only re-render the failed payload). */ + retry: () => void; +}) { + useEffect(() => { + console.error(error); + }, [error]); + + return ( + <StatusScreen + icon={CloudOffIcon} + tone="error" + headingLevel="h2" + title="This page didn't load." + description="Your saved work is safe. Retry, or go back to Home." + actions={ + <> + <Button onClick={() => retry()}> + <RotateCcwIcon data-icon="inline-start" aria-hidden="true" /> + Retry + </Button> + <Button asChild variant="outline"> + <Link href="/">Go to Home</Link> + </Button> + </> + } + footnote={error.digest ? `Reference: ${error.digest}` : undefined} + /> + ); +} diff --git a/src/app/(app)/flashcards/(library)/loading.tsx b/src/app/(app)/flashcards/(library)/loading.tsx new file mode 100644 index 00000000..0ae65345 --- /dev/null +++ b/src/app/(app)/flashcards/(library)/loading.tsx @@ -0,0 +1,31 @@ +import { PageContainer } from "@/components/app/page-container" +import { CardSkeleton, LoadingRegion, PageHeaderSkeleton } from "@/components/app/skeletons" +import { Skeleton } from "@/components/ui/skeleton" + +/** Deck library skeleton: the due summary, then course sections with deck cards. */ +export default function Loading() { + return ( + <PageContainer> + <LoadingRegion label="Loading decks…" className="flex flex-col gap-6"> + <PageHeaderSkeleton /> + <div className="flex flex-col gap-10"> + {[0, 1].map((section) => ( + <div key={section} aria-hidden="true" className="flex flex-col gap-4"> + <div className="flex min-h-10 items-center justify-between gap-4"> + <div className="flex flex-col gap-2"> + <Skeleton className="h-5 w-32" /> + <Skeleton className="h-4 w-44" /> + </div> + <Skeleton className="h-8 w-36 rounded-full" /> + </div> + <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3"> + <CardSkeleton lines={2} /> + <CardSkeleton lines={2} className="hidden md:flex" /> + </div> + </div> + ))} + </div> + </LoadingRegion> + </PageContainer> + ) +} diff --git a/src/app/(app)/flashcards/(library)/page.tsx b/src/app/(app)/flashcards/(library)/page.tsx new file mode 100644 index 00000000..f8bcfc48 --- /dev/null +++ b/src/app/(app)/flashcards/(library)/page.tsx @@ -0,0 +1,31 @@ +import { redirect } from "next/navigation" + +import { getCurrentUserId } from "@/lib/auth" +import { logger } from "@/lib/logger" +import { getDeckLibrary, type DeckLibrary } from "@/services/flashcards" +import { PageContainer } from "@/components/app/page-container" +import { DeckLibraryView } from "@/components/cards/deck-library" +import { RefreshErrorState } from "@/components/cards/refresh-error" + +/** + * Cards: every course with materials or decks, nearest exam first, with each + * deck's counts by status and what's due today. Rendered on the server; the + * generate, delete and review actions are client islands. + */ +export default async function FlashcardsPage() { + const userId = await getCurrentUserId() + if (!userId) redirect("/auth/signin?callbackUrl=/flashcards") + + let library: DeckLibrary | null = null + try { + library = await getDeckLibrary(userId) + } catch (err) { + logger.error("flashcards.page_load_failed", { userId, error: String(err) }) + } + + return ( + <PageContainer> + {library ? <DeckLibraryView library={library} /> : <RefreshErrorState title="Decks didn't load." />} + </PageContainer> + ) +} diff --git a/src/app/(app)/flashcards/[deckId]/not-found.tsx b/src/app/(app)/flashcards/[deckId]/not-found.tsx new file mode 100644 index 00000000..29b6d91d --- /dev/null +++ b/src/app/(app)/flashcards/[deckId]/not-found.tsx @@ -0,0 +1,21 @@ +import Link from "next/link" +import { LayersIcon } from "lucide-react" + +import { StatusScreen } from "@/components/app/status-screen" +import { Button } from "@/components/ui/button" + +export default function DeckNotFound() { + return ( + <StatusScreen + icon={LayersIcon} + headingLevel="h2" + title="Deck not found" + description="This link doesn't match one of your decks. It may have been deleted." + actions={ + <Button asChild> + <Link href="/flashcards">Go to Flashcards</Link> + </Button> + } + /> + ) +} diff --git a/src/app/(app)/flashcards/[deckId]/page.tsx b/src/app/(app)/flashcards/[deckId]/page.tsx new file mode 100644 index 00000000..87169e66 --- /dev/null +++ b/src/app/(app)/flashcards/[deckId]/page.tsx @@ -0,0 +1,81 @@ +import { cache, Suspense } from "react" +import type { Metadata } from "next" +import { notFound, redirect } from "next/navigation" + +import { getCurrentUserId } from "@/lib/auth" +import { logger } from "@/lib/logger" +import { getDeckDetail, isDeckOwner, type DeckDetail } from "@/services/flashcards" +import { PageContainer } from "@/components/app/page-container" +import { DeckDetailView } from "@/components/cards/deck-detail" +import { RefreshErrorState } from "@/components/cards/refresh-error" +import { DeckSkeleton } from "@/components/cards/skeletons" + +type Props = { params: Promise<{ deckId: string }> } + +type Loaded = { deck: DeckDetail | null; failed: boolean } + +/** One load per request, shared by the metadata and the page. */ +const loadDeck = cache(async (deckId: string): Promise<Loaded> => { + const userId = await getCurrentUserId() + if (!userId) return { deck: null, failed: false } + try { + return { deck: await getDeckDetail(userId, deckId), failed: false } + } catch (err) { + logger.error("flashcards.deck_page_load_failed", { userId, deckId, error: String(err) }) + return { deck: null, failed: true } + } +}) + +export async function generateMetadata({ params }: Props): Promise<Metadata> { + const { deckId } = await params + const { deck, failed } = await loadDeck(deckId) + if (deck) return { title: deck.title } + return { title: failed ? "Deck didn't load" : "Deck not found" } +} + +/** + * A deck's cards: status and next review for each, with add, edit and delete. + * + * The deck is checked before anything streams, so a missing deck or another + * account's deck answers with a real 404 (like /s/[sessionId]). That is why + * this segment has no loading.tsx; the skeleton comes from the Suspense + * boundary below, after the check. + */ +export default async function DeckPage({ params }: Props) { + const { deckId } = await params + const userId = await getCurrentUserId() + if (!userId) redirect(`/auth/signin?callbackUrl=${encodeURIComponent(`/flashcards/${deckId}`)}`) + + let owned: boolean + try { + owned = await isDeckOwner(userId, deckId) + } catch (err) { + logger.error("flashcards.deck_page_check_failed", { userId, deckId, error: String(err) }) + return <DeckFailed /> + } + if (!owned) notFound() + + return ( + <PageContainer size="narrow"> + <Suspense fallback={<DeckSkeleton />}> + <DeckContent deckId={deckId} /> + </Suspense> + </PageContainer> + ) +} + +async function DeckContent({ deckId }: { deckId: string }) { + const { deck, failed } = await loadDeck(deckId) + if (failed) return <RefreshErrorState title="Deck didn't load." /> + // Deleted between the check and this load + if (!deck) notFound() + return <DeckDetailView deck={deck} /> +} + +function DeckFailed() { + return ( + <PageContainer size="narrow"> + <RefreshErrorState title="Deck didn't load." /> + </PageContainer> + ) +} diff --git a/src/app/(app)/flashcards/layout.tsx b/src/app/(app)/flashcards/layout.tsx new file mode 100644 index 00000000..1f79b225 --- /dev/null +++ b/src/app/(app)/flashcards/layout.tsx @@ -0,0 +1,11 @@ +import type { Metadata } from "next"; +import { TITLE_TEMPLATE } from "@/lib/metadata"; + +export const metadata: Metadata = { + // Pages below set their own titles, so pass the template on + title: { default: "Flashcards", template: TITLE_TEMPLATE }, +}; + +export default function Layout({ children }: { children: React.ReactNode }) { + return children; +} diff --git a/src/app/(app)/guides/layout.tsx b/src/app/(app)/guides/layout.tsx new file mode 100644 index 00000000..41e2b73d --- /dev/null +++ b/src/app/(app)/guides/layout.tsx @@ -0,0 +1,9 @@ +import type { Metadata } from "next"; + +export const metadata: Metadata = { + title: "Study guides", +}; + +export default function Layout({ children }: { children: React.ReactNode }) { + return children; +} diff --git a/src/app/(app)/guides/loading.tsx b/src/app/(app)/guides/loading.tsx new file mode 100644 index 00000000..969b9d6b --- /dev/null +++ b/src/app/(app)/guides/loading.tsx @@ -0,0 +1,10 @@ +import { PageContainer } from "@/components/app/page-container" +import { GuidesSkeleton } from "@/components/guides/guides-skeleton" + +export default function Loading() { + return ( + <PageContainer size="narrow"> + <GuidesSkeleton /> + </PageContainer> + ) +} diff --git a/src/app/(app)/guides/page.tsx b/src/app/(app)/guides/page.tsx new file mode 100644 index 00000000..8f873fb0 --- /dev/null +++ b/src/app/(app)/guides/page.tsx @@ -0,0 +1,58 @@ +import { redirect } from "next/navigation" + +import { getCurrentUserId } from "@/lib/auth" +import { logger } from "@/lib/logger" +import { listDocuments } from "@/services/content" +import { loadPlans, loadTimeZone } from "@/services/progress-data" +import { SwrFallback } from "@/components/chat/swr-fallback" +import { guideTypeFromSlug } from "@/lib/guide-format" +import { GuidesView } from "@/components/guides/guides-view" +import { coursePreferences } from "@/components/study/course-preference" + +const DOCUMENTS_KEY = "/api/content/documents?namespace=COURSE" + +function first(value: string | string[] | undefined): string | null { + return (Array.isArray(value) ? value[0] : value) ?? null +} + +/** + * Study guides (/guides). Takes ?format=key-concepts|faq|cheat-sheet and + * ?guide=<id> so a guide can be linked to. The course list is read here and + * handed to the client cache, so the guides request for the active course + * (which lives in the browser) starts as soon as the page hydrates. The + * plans (shared with the shell's Start button in this request) pick the + * course to open on when none is chosen: today's session, else the nearest + * exam. + */ +export default async function GuidesPage({ + searchParams, +}: { + searchParams: Promise<Record<string, string | string[] | undefined>> +}) { + const [params, userId] = await Promise.all([searchParams, getCurrentUserId()]) + if (!userId) redirect("/auth/signin?callbackUrl=/guides") + + const [documents, timeZone, plans] = await Promise.all([ + listDocuments(userId, "COURSE").catch((err) => { + logger.error("guides.page_documents_failed", { userId, error: String(err) }) + return null + }), + loadTimeZone(userId), + loadPlans(userId).catch((err) => { + logger.error("guides.page_plans_failed", { userId, error: String(err) }) + return null + }), + ]) + const guideId = first(params.guide) + + return ( + <SwrFallback fallback={documents ? { [DOCUMENTS_KEY]: { documents } } : {}}> + <GuidesView + initialType={guideTypeFromSlug(first(params.format)) ?? "KEY_CONCEPTS"} + initialGuideId={guideId && guideId.length <= 64 ? guideId : null} + timeZone={timeZone} + coursePreferences={plans ? coursePreferences(plans, timeZone) : undefined} + /> + </SwrFallback> + ) +} diff --git a/src/app/(app)/layout.tsx b/src/app/(app)/layout.tsx new file mode 100644 index 00000000..5b576e6f --- /dev/null +++ b/src/app/(app)/layout.tsx @@ -0,0 +1,47 @@ +import { Suspense } from "react"; +import type { Metadata } from "next"; +import { getServerSession } from "next-auth"; + +import type { Account } from "@/components/app/account-menu"; +import { AppShell } from "@/components/shell/app-shell"; +import { TodaySessionFab } from "@/components/shell/today-session-fab"; +import { authOptions } from "@/lib/auth-options"; +import { TITLE_TEMPLATE } from "@/lib/metadata"; + +// Home has no segment of its own, so the group carries its title; every +// other destination sets its own in its layout and keeps the template. +export const metadata: Metadata = { + title: { default: "Home", template: TITLE_TEMPLATE }, +}; + +/** Name and email for the account menu; empty when there is no session. */ +async function loadAccount(): Promise<Account> { + try { + const session = await getServerSession(authOptions); + return { name: session?.user?.name ?? null, email: session?.user?.email ?? null }; + } catch { + // The menu still offers Settings and Sign out without a name. + return { name: null, email: null }; + } +} + +export default async function AppLayout({ children }: { children: React.ReactNode }) { + const account = await loadAccount(); + return ( + <AppShell + account={account} + railFab={ + <Suspense fallback={null}> + <TodaySessionFab placement="rail" /> + </Suspense> + } + floatingFab={ + <Suspense fallback={null}> + <TodaySessionFab placement="floating" /> + </Suspense> + } + > + {children} + </AppShell> + ); +} diff --git a/src/app/(app)/learn/layout.tsx b/src/app/(app)/learn/layout.tsx new file mode 100644 index 00000000..64eab0a3 --- /dev/null +++ b/src/app/(app)/learn/layout.tsx @@ -0,0 +1,9 @@ +import type { Metadata } from "next"; + +export const metadata: Metadata = { + title: "Study", +}; + +export default function Layout({ children }: { children: React.ReactNode }) { + return children; +} diff --git a/src/app/(app)/learn/loading.tsx b/src/app/(app)/learn/loading.tsx new file mode 100644 index 00000000..eb61551f --- /dev/null +++ b/src/app/(app)/learn/loading.tsx @@ -0,0 +1,10 @@ +import { PageContainer } from "@/components/app/page-container" +import { StudySkeleton } from "@/components/study/study-skeleton" + +export default function Loading() { + return ( + <PageContainer> + <StudySkeleton /> + </PageContainer> + ) +} diff --git a/src/app/(app)/learn/page.tsx b/src/app/(app)/learn/page.tsx new file mode 100644 index 00000000..a8a07461 --- /dev/null +++ b/src/app/(app)/learn/page.tsx @@ -0,0 +1,59 @@ +import { redirect } from "next/navigation" + +import { getCurrentUserId } from "@/lib/auth" +import { logger } from "@/lib/logger" +import { listDocuments } from "@/services/content" +import { loadPlans, loadTimeZone } from "@/services/progress-data" +import { getStudyCourses } from "@/services/study-recommendations" +import { SwrFallback } from "@/components/chat/swr-fallback" +import { coursePreferences } from "@/components/study/course-preference" +import { StudyView } from "@/components/study/study-view" + +const DOCUMENTS_KEY = "/api/content/documents?namespace=COURSE" +const LEARN_KEY = "/api/learn" + +/** + * Study (/learn). The course list and per-course counts are read here and + * handed to the client cache, so at hydration only the active course's + * recommendation is left to load (the active course lives in the browser). + * A failed read here just leaves that request to the client. + * + * The plans pick the course to open on when none is chosen (today's + * session, else the nearest exam). The shell's Start button reads the same + * plans in this request, so they cost no extra query. If they fail, Study + * opens on the first course in the switcher. + */ +export default async function StudyPage() { + const userId = await getCurrentUserId() + if (!userId) redirect("/auth/signin?callbackUrl=/learn") + + // The course counts need the zone (cards due today); the documents don't wait for it. + const zone = loadTimeZone(userId) + const [timeZone, documents, courses, plans] = await Promise.all([ + zone, + listDocuments(userId, "COURSE").catch((err) => { + logger.error("learn.page_documents_failed", { userId, error: String(err) }) + return null + }), + zone + .then((z) => getStudyCourses(userId, z)) + .catch((err) => { + logger.error("learn.page_courses_failed", { userId, error: String(err) }) + return null + }), + loadPlans(userId).catch((err) => { + logger.error("learn.page_plans_failed", { userId, error: String(err) }) + return null + }), + ]) + + const fallback: Record<string, unknown> = {} + if (documents) fallback[DOCUMENTS_KEY] = { documents } + if (courses) fallback[LEARN_KEY] = { courses, hasCourses: courses.length > 0 } + + return ( + <SwrFallback fallback={fallback}> + <StudyView timeZone={timeZone} coursePreferences={plans ? coursePreferences(plans, timeZone) : undefined} /> + </SwrFallback> + ) +} diff --git a/src/app/(app)/plan/_lib/load.ts b/src/app/(app)/plan/_lib/load.ts new file mode 100644 index 00000000..ce530a45 --- /dev/null +++ b/src/app/(app)/plan/_lib/load.ts @@ -0,0 +1,182 @@ +/** + * Server-side reads for the Plan screens. Everything goes through the + * services layer with the signed-in user's id; nothing here runs in the + * browser. + */ +import { prisma } from "@/lib/db" +import { isGoogleCalendarAvailable } from "@/lib/google/availability" +import { getUserTimezone, isValidTimezone } from "@/lib/timezone" +import { getPlanView, listPlanSummaries, type PlanSummary, type PlanView } from "@/services/plan" +import { listDocuments } from "@/services/content" +import { getPublishStatus } from "@/services/publish" +import { sortPlans } from "@/components/plan/plan-model" +import { lastCalendarAction, type CalendarState } from "@/components/plan/calendar-types" +import type { MaterialDoc } from "@/components/materials/types" + +const FALLBACK_ZONE = "America/New_York" + +/** The zone dates are shown in: the student's setting, else the given plan's zone. */ +export async function displayTimeZone(userId: string, planZone?: string | null): Promise<string> { + const setting = await getUserTimezone(userId) + for (const zone of [setting, planZone]) { + if (zone && isValidTimezone(zone)) return zone + } + return FALLBACK_ZONE +} + +async function googleConnection(userId: string): Promise<CalendarState["connection"]> { + const integration = await prisma.googleIntegration.findUnique({ + where: { userId }, + select: { status: true }, + }) + if (!integration) return "not_connected" + return integration.status === "CONNECTED" ? "connected" : "reconnect" +} + +async function calendarState(userId: string, view: PlanView): Promise<CalendarState> { + const [connection, status] = await Promise.all([ + googleConnection(userId), + getPublishStatus(userId, view.plan_id), + ]) + const publication = "data" in status ? status.data.publication : null + const added = "data" in status ? status.data.items.length : 0 + return { + // Hide Google options on a server that can't connect Google Calendar, + // unless the student already connected (so existing events stay manageable). + configured: isGoogleCalendarAvailable() || connection !== "not_connected", + connection, + publication: publication + ? { + status: publication.status as NonNullable<CalendarState["publication"]>["status"], + added, + // Skipped sessions don't belong in the calendar + total: view.counts.total, + last_action: lastCalendarAction(publication), + last_error: publication.last_error, + } + : null, + } +} + +export type PlanPageData = + | { kind: "empty"; timeZone: string } + | { + kind: "plan" + timeZone: string + plans: PlanSummary[] + view: PlanView + calendar: CalendarState + materials: MaterialDoc[] + } + | { kind: "missing"; timeZone: string; plans: PlanSummary[] } + +/** Everything /plan shows: the plan list, the chosen plan, its calendar status and materials. */ +export async function loadPlanPage(userId: string, planId: string | undefined): Promise<PlanPageData> { + const now = new Date() + // Start the selected plan's read with the list when the URL names it + const [summaries, requested, userZone] = await Promise.all([ + listPlanSummaries(userId, now), + planId ? getPlanView(userId, planId, now) : Promise.resolve(null), + getUserTimezone(userId), + ]) + + const zoneFor = (planZone?: string) => + [userZone, planZone].find((z): z is string => !!z && isValidTimezone(z)) ?? FALLBACK_ZONE + + if (summaries.length === 0) return { kind: "empty", timeZone: zoneFor() } + + const listZone = zoneFor(summaries[0].timezone) + const plans = sortPlans(summaries, { timeZone: listZone, now }) + + let result = requested + if (!planId) result = await getPlanView(userId, plans[0].plan_id, now) + if (!result || "error" in result) return { kind: "missing", timeZone: listZone, plans } + + const view = result.data + const [calendar, documents] = await Promise.all([ + calendarState(userId, view), + listDocuments(userId, "COURSE", view.course_name), + ]) + + return { + kind: "plan", + timeZone: zoneFor(view.timezone), + plans, + view, + calendar, + materials: documents.map(toMaterialDoc), + } +} + +export function toMaterialDoc(doc: Awaited<ReturnType<typeof listDocuments>>[number]): MaterialDoc { + return { + document_id: doc.document_id, + course_name: doc.course_name, + exam_name: doc.exam_name, + title: doc.title, + original_filename: doc.original_filename, + mime_type: doc.mime_type, + status: doc.status, + chunk_count: doc.chunk_count, + summary: doc.summary, + suggested_questions: doc.suggested_questions, + created_at: doc.created_at, + } +} + +/** + * The New plan form's defaults: study hours from Settings, known courses, + * existing plans, and the time zone saved in Settings (null when there is + * none, so the form sends the browser's instead). + */ +export async function loadNewPlanDefaults(userId: string) { + const [state, summaries, documents, setting] = await Promise.all([ + prisma.userGameState.findUnique({ + where: { userId }, + select: { studyStartTime: true, studyEndTime: true, dailyStudyCap: true }, + }), + listPlanSummaries(userId), + listDocuments(userId, "COURSE"), + getUserTimezone(userId), + ]) + const savedTimeZone = setting && isValidTimezone(setting) ? setting : null + + return { + timeZone: savedTimeZone ?? FALLBACK_ZONE, + savedTimeZone, + studyStart: state?.studyStartTime ?? "09:00", + studyEnd: state?.studyEndTime ?? "17:00", + dailyCap: state?.dailyStudyCap ?? 180, + plans: summaries, + materials: documents.map(toMaterialDoc), + } +} + +/** The Materials screen: every course file, plus course names from plans with no files yet. */ +export async function loadMaterials(userId: string) { + const [documents, summaries, timeZone] = await Promise.all([ + listDocuments(userId, "COURSE"), + listPlanSummaries(userId), + displayTimeZone(userId), + ]) + return { + timeZone, + materials: documents.map(toMaterialDoc), + plans: sortPlans(summaries, { timeZone }), + } +} + +/** + * The course and exam of a plan the student owns, for the Replace plan tab + * title. Null when the id names no plan of theirs. + */ +export async function planName( + userId: string, + planId: string +): Promise<{ course_name: string; exam_name: string } | null> { + const plan = await prisma.studyPlan.findFirst({ + where: { planId, userId }, + select: { courseName: true, examName: true }, + }) + return plan ? { course_name: plan.courseName, exam_name: plan.examName } : null +} diff --git a/src/app/(app)/plan/layout.tsx b/src/app/(app)/plan/layout.tsx new file mode 100644 index 00000000..52bfd82f --- /dev/null +++ b/src/app/(app)/plan/layout.tsx @@ -0,0 +1,11 @@ +import type { Metadata } from "next"; +import { TITLE_TEMPLATE } from "@/lib/metadata"; + +export const metadata: Metadata = { + // Pages below set their own titles, so pass the template on + title: { default: "Plan", template: TITLE_TEMPLATE }, +}; + +export default function Layout({ children }: { children: React.ReactNode }) { + return children; +} diff --git a/src/app/(app)/plan/loading.tsx b/src/app/(app)/plan/loading.tsx new file mode 100644 index 00000000..b87bb758 --- /dev/null +++ b/src/app/(app)/plan/loading.tsx @@ -0,0 +1,5 @@ +import { PlanPageSkeleton } from "@/components/plan/plan-skeletons" + +export default function PlanLoading() { + return <PlanPageSkeleton /> +} diff --git a/src/app/(app)/plan/materials/layout.tsx b/src/app/(app)/plan/materials/layout.tsx new file mode 100644 index 00000000..aeecf0a0 --- /dev/null +++ b/src/app/(app)/plan/materials/layout.tsx @@ -0,0 +1,9 @@ +import type { Metadata } from "next" + +export const metadata: Metadata = { + title: "Materials", +} + +export default function MaterialsLayout({ children }: { children: React.ReactNode }) { + return children +} diff --git a/src/app/(app)/plan/materials/loading.tsx b/src/app/(app)/plan/materials/loading.tsx new file mode 100644 index 00000000..5a6bdafa --- /dev/null +++ b/src/app/(app)/plan/materials/loading.tsx @@ -0,0 +1,5 @@ +import { PlanPageSkeleton } from "@/components/plan/plan-skeletons" + +export default function MaterialsLoading() { + return <PlanPageSkeleton variant="materials" /> +} diff --git a/src/app/(app)/plan/materials/page.tsx b/src/app/(app)/plan/materials/page.tsx new file mode 100644 index 00000000..7906919a --- /dev/null +++ b/src/app/(app)/plan/materials/page.tsx @@ -0,0 +1,49 @@ +import { redirect } from "next/navigation" + +import { getCurrentUserId } from "@/lib/auth" +import { logger } from "@/lib/logger" +import { PageContainer } from "@/components/app/page-container" +import { MaterialsManager } from "@/components/materials/materials-manager" +import { PlanLoadError } from "@/components/plan/plan-load-error" +import { PlanWorkspace } from "@/components/plan/plan-workspace" +import { loadMaterials } from "../_lib/load" + +/** + * /plan/materials[?course={course name}] + * + * Every course file: upload (drag and drop or Choose files), status in + * words, summary, Retry and Delete. Flashcards, Guides and Chat link here. + */ +export default async function MaterialsPage() { + const userId = await getCurrentUserId() + if (!userId) redirect("/auth/signin?callbackUrl=%2Fplan%2Fmaterials") + + let data: Awaited<ReturnType<typeof loadMaterials>> + try { + data = await loadMaterials(userId) + } catch (error) { + logger.error("materials_page.load_failed", { user_id: userId, error: String(error) }) + return ( + <PageContainer size="wide"> + <PlanLoadError title="Materials didn't load." description="Your files are safe. Retry, or check your connection." /> + </PageContainer> + ) + } + + const knownCourses = [ + ...new Set([ + ...data.plans.map((p) => p.course_name), + ...data.materials.flatMap((m) => (m.course_name ? [m.course_name] : [])), + ]), + ] + + return ( + <PlanWorkspace + plans={data.plans} + section="materials" + timeZone={data.timeZone} + > + <MaterialsManager initialMaterials={data.materials} knownCourses={knownCourses} timeZone={data.timeZone} /> + </PlanWorkspace> + ) +} diff --git a/src/app/(app)/plan/new/layout.tsx b/src/app/(app)/plan/new/layout.tsx new file mode 100644 index 00000000..bc06b570 --- /dev/null +++ b/src/app/(app)/plan/new/layout.tsx @@ -0,0 +1,11 @@ +import type { Metadata } from "next" +import { TITLE_TEMPLATE } from "@/lib/metadata" + +export const metadata: Metadata = { + // The page titles itself while replacing a plan, so pass the template on + title: { default: "New plan", template: TITLE_TEMPLATE }, +} + +export default function NewPlanLayout({ children }: { children: React.ReactNode }) { + return children +} diff --git a/src/app/(app)/plan/new/loading.tsx b/src/app/(app)/plan/new/loading.tsx new file mode 100644 index 00000000..7632b4e9 --- /dev/null +++ b/src/app/(app)/plan/new/loading.tsx @@ -0,0 +1,5 @@ +import { PlanPageSkeleton } from "@/components/plan/plan-skeletons" + +export default function NewPlanLoading() { + return <PlanPageSkeleton variant="form" /> +} diff --git a/src/app/(app)/plan/new/page.tsx b/src/app/(app)/plan/new/page.tsx new file mode 100644 index 00000000..e26d2a3e --- /dev/null +++ b/src/app/(app)/plan/new/page.tsx @@ -0,0 +1,94 @@ +import type { Metadata } from "next" +import { redirect } from "next/navigation" + +import { getCurrentUserId } from "@/lib/auth" +import { logger } from "@/lib/logger" +import { PageContainer } from "@/components/app/page-container" +import { PageHeader } from "@/components/app/page-header" +import { NewPlanForm } from "@/components/plan/new-plan-form" +import { PlanLoadError } from "@/components/plan/plan-load-error" +import { PlanWorkspace } from "@/components/plan/plan-workspace" +import { keyOf, sortPlans } from "@/components/plan/plan-model" +import { loadNewPlanDefaults, planName } from "../_lib/load" + +type SearchParams = Promise<Record<string, string | string[] | undefined>> + +function param(value: string | string[] | undefined): string | undefined { + return typeof value === "string" && value.trim() ? value.trim().slice(0, 120) : undefined +} + +/** "Replace CS 2110 Prelim 1 plan" while replacing a plan, else the layout's "New plan". */ +export async function generateMetadata({ searchParams }: { searchParams: SearchParams }): Promise<Metadata> { + const replaceId = param((await searchParams).replace) + if (!replaceId) return {} + try { + const userId = await getCurrentUserId() + const plan = userId ? await planName(userId, replaceId) : null + return plan ? { title: `Replace ${plan.course_name} ${plan.exam_name} plan` } : {} + } catch (error) { + // The page reports its own load failures; the tab keeps "New plan" + logger.warn("new_plan_page.title_failed", { error: String(error) }) + return {} + } +} + +/** + * /plan/new[?replace={planId}][?course=&exam=] + * + * The New plan form. ?replace fills in that plan's course, exam and date + * (creating it then replaces that plan, after asking); ?course and ?exam + * prefill the fields from other screens. + */ +export default async function NewPlanPage({ searchParams }: { searchParams: SearchParams }) { + const params = await searchParams + const userId = await getCurrentUserId() + if (!userId) redirect("/auth/signin?callbackUrl=%2Fplan%2Fnew") + + let data: Awaited<ReturnType<typeof loadNewPlanDefaults>> + try { + data = await loadNewPlanDefaults(userId) + } catch (error) { + logger.error("new_plan_page.load_failed", { user_id: userId, error: String(error) }) + return ( + <PageContainer size="wide"> + <PlanLoadError + title="The new plan form didn't load." + description="Your existing plans are safe. Retry, or check your connection." + /> + </PageContainer> + ) + } + + const plans = sortPlans(data.plans, { timeZone: data.timeZone }) + const replaceId = param(params.replace) + const replacing = replaceId ? plans.find((p) => p.plan_id === replaceId) : undefined + const initial = replacing + ? { course: replacing.course_name, exam: replacing.exam_name, examDate: replacing.exam_date } + : { course: param(params.course), exam: param(params.exam) } + + return ( + <PlanWorkspace plans={plans} section="new" timeZone={data.timeZone}> + <div className="flex w-full max-w-3xl flex-col gap-6"> + <PageHeader + title={replacing ? `Replace the ${replacing.course_name} ${replacing.exam_name} plan` : "Plan for an exam"} + description={ + replacing + ? "Creating this plan replaces the current one once it's ready. Change the course or exam to make a separate plan instead." + : "Study Bot schedules practice sessions from your course files, from today up to the exam." + } + /> + {/* Keyed by what prefilled it: going from ?replace= to plain /plan/new + keeps client state otherwise, with the replaced plan's values */} + <NewPlanForm + key={replacing ? `replace:${replacing.plan_id}` : `new:${initial.course ?? ""}|${initial.exam ?? ""}`} + todayKey={keyOf(new Date(), data.timeZone)} + savedTimeZone={data.savedTimeZone} + defaults={{ studyStart: data.studyStart, studyEnd: data.studyEnd, dailyCap: data.dailyCap }} + plans={plans} + materials={data.materials} + initial={initial} + /> + </div> + </PlanWorkspace> + ) +} diff --git a/src/app/(app)/plan/page.tsx b/src/app/(app)/plan/page.tsx new file mode 100644 index 00000000..49e068ab --- /dev/null +++ b/src/app/(app)/plan/page.tsx @@ -0,0 +1,127 @@ +import Link from "next/link" +import { redirect } from "next/navigation" +import { CalendarDaysIcon, CircleAlertIcon, PlusIcon } from "lucide-react" + +import { getCurrentUserId } from "@/lib/auth" +import { logger } from "@/lib/logger" +import { EmptyState } from "@/components/app/empty-state" +import { PageContainer } from "@/components/app/page-container" +import { PageHeader } from "@/components/app/page-header" +import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert" +import { Button } from "@/components/ui/button" +import { CalendarNotice, PlanActionsProvider, PlanToolbar } from "@/components/plan/plan-actions" +import { PlanAgenda } from "@/components/plan/plan-agenda" +import { PlanLoadError } from "@/components/plan/plan-load-error" +import { PlanMaterials } from "@/components/plan/plan-materials" +import { canReschedule, examCountdown, formatDayKey, keyOf, planName } from "@/components/plan/plan-model" +import { PlanProgress } from "@/components/plan/plan-progress" +import { PlanWorkspace } from "@/components/plan/plan-workspace" +import { loadPlanPage, type PlanPageData } from "./_lib/load" + +type SearchParams = Promise<Record<string, string | string[] | undefined>> + +/** + * /plan[?plan={planId}][&reschedule=1] + * + * The selected plan (default: the soonest upcoming exam) as dated days, with + * its progress, Google Calendar status, actions and materials. Read on the + * server through the services layer; the interactive parts are client + * islands that refresh this page after they change something. + */ +export default async function PlanPage({ searchParams }: { searchParams: SearchParams }) { + const params = await searchParams + const requested = typeof params.plan === "string" && params.plan.trim() ? params.plan.trim() : undefined + + const userId = await getCurrentUserId() + if (!userId) redirect("/auth/signin?callbackUrl=%2Fplan") + + let data: PlanPageData + try { + data = await loadPlanPage(userId, requested) + } catch (error) { + logger.error("plan_page.load_failed", { user_id: userId, error: String(error) }) + return ( + <PageContainer size="wide"> + <PlanLoadError + title="Plans didn't load." + description="Your plans and sessions are safe. Retry, or check your connection." + /> + </PageContainer> + ) + } + + if (data.kind === "empty") { + return ( + <PlanWorkspace plans={[]} section="plan" timeZone={data.timeZone}> + <EmptyState + icon={CalendarDaysIcon} + headingLevel="h2" + title="No plan yet" + description="A plan schedules practice sessions from your course files up to your exam date." + action={ + <Button asChild> + <Link href="/plan/new"> + <PlusIcon data-icon="inline-start" aria-hidden="true" /> + New plan + </Link> + </Button> + } + bordered + /> + </PlanWorkspace> + ) + } + + if (data.kind === "missing") { + return ( + <PlanWorkspace plans={data.plans} section="plan" timeZone={data.timeZone}> + <Alert variant="warning"> + <CircleAlertIcon aria-hidden="true" /> + <AlertTitle>This plan doesn't exist anymore.</AlertTitle> + <AlertDescription> + It may have been deleted or replaced. + <div className="mt-2"> + <Button asChild size="sm" variant="outline"> + <Link href="/plan">Go to Plan</Link> + </Button> + </div> + </AlertDescription> + </Alert> + </PlanWorkspace> + ) + } + + const { view, timeZone, plans, calendar, materials } = data + const now = new Date() + const todayKey = keyOf(now, timeZone) + const reschedulable = canReschedule(view, timeZone, now) + const upcoming = view.counts.scheduled + view.counts.missed + view.counts.in_progress + + return ( + <PlanWorkspace plans={plans} selectedPlanId={view.plan_id} section="plan" timeZone={timeZone}> + {/* Keyed by plan: ?plan= changes keep client state, and one plan's + calendar error or pending request must not carry over to another */} + <PlanActionsProvider + key={view.plan_id} + planId={view.plan_id} + examName={view.exam_name} + timeZone={timeZone} + canReschedule={reschedulable} + items={view.items.map((item) => ({ id: item.id, mode: item.mode, topics: item.topics, state: item.state }))} + calendar={calendar} + > + <PageHeader + title={planName(view)} + description={`${examCountdown(view.exam_name, view.exam_date, todayKey)}: ${formatDayKey(view.exam_date)}.`} + actions={ + <PlanToolbar courseName={view.course_name} upcomingCount={upcoming} totalSessions={view.items.length} /> + } + /> + <CalendarNotice /> + <PlanProgress counts={view.counts} /> + <PlanAgenda view={view} timeZone={timeZone} canReschedule={reschedulable} now={now} /> + <PlanMaterials courseName={view.course_name} materials={materials} /> + </PlanActionsProvider> + </PlanWorkspace> + ) +} diff --git a/src/app/(app)/settings/layout.tsx b/src/app/(app)/settings/layout.tsx new file mode 100644 index 00000000..e30e0101 --- /dev/null +++ b/src/app/(app)/settings/layout.tsx @@ -0,0 +1,9 @@ +import type { Metadata } from "next"; + +export const metadata: Metadata = { + title: "Settings", +}; + +export default function Layout({ children }: { children: React.ReactNode }) { + return children; +} diff --git a/src/app/(app)/settings/loading.tsx b/src/app/(app)/settings/loading.tsx new file mode 100644 index 00000000..3698bcf2 --- /dev/null +++ b/src/app/(app)/settings/loading.tsx @@ -0,0 +1,41 @@ +import { PageContainer } from "@/components/app/page-container" +import { LoadingRegion } from "@/components/app/skeletons" +import { Skeleton } from "@/components/ui/skeleton" + +function SectionSkeleton({ rows }: { rows: number }) { + return ( + <div aria-hidden="true" className="flex flex-col gap-6 rounded-2xl bg-card p-4 ring-1 ring-border sm:p-6"> + <Skeleton className="h-6 w-40" /> + {Array.from({ length: rows }, (_, i) => ( + <div key={i} className="flex flex-col gap-2"> + <Skeleton className="h-4 w-32" /> + <Skeleton className="h-3 w-72 max-w-full" /> + <Skeleton className="h-12 w-full max-w-sm rounded-md" /> + </div> + ))} + </div> + ) +} + +/** Matches the Settings layout: the section list on wide windows, then section cards. */ +export default function SettingsLoading() { + return ( + <PageContainer> + <LoadingRegion + label="Loading settings…" + className="grid gap-8 md:grid-cols-[13rem_minmax(0,1fr)] lg:grid-cols-[15rem_minmax(0,1fr)]" + > + <div aria-hidden="true" className="hidden flex-col gap-1 md:flex"> + {Array.from({ length: 7 }, (_, i) => ( + <Skeleton key={i} className="h-12 w-full rounded-full" /> + ))} + </div> + <div className="flex max-w-3xl min-w-0 flex-col gap-6"> + <SectionSkeleton rows={2} /> + <SectionSkeleton rows={3} /> + <SectionSkeleton rows={1} /> + </div> + </LoadingRegion> + </PageContainer> + ) +} diff --git a/src/app/(app)/settings/page.tsx b/src/app/(app)/settings/page.tsx new file mode 100644 index 00000000..8e40e75f --- /dev/null +++ b/src/app/(app)/settings/page.tsx @@ -0,0 +1,107 @@ +import { redirect } from "next/navigation" + +import { PageContainer } from "@/components/app/page-container" +import { ThemeToggle } from "@/components/app/theme-toggle" +import { AccountSection } from "@/components/settings/account-section" +import { AiSection } from "@/components/settings/ai-section" +import { ConnectResultBanner } from "@/components/settings/connect-result-banner" +import { DataSection } from "@/components/settings/data-section" +import { GoogleCalendarSection } from "@/components/settings/google-calendar-section" +import { PreferencesForm, type AccountSummary } from "@/components/settings/preferences-form" +import { SettingsNav, type SettingsNavItem } from "@/components/settings/settings-nav" +import { SettingsRows, SettingsSection } from "@/components/settings/settings-section" +import { Field, FieldDescription, FieldTitle } from "@/components/ui/field" +import { getCurrentUserId } from "@/lib/auth" +import { prisma } from "@/lib/db" +import { googleConnectResult } from "@/lib/google/messages" +import { logger } from "@/lib/logger" +import { publicConfig } from "@/lib/public-config" +import { readGoogleStatus } from "@/services/google-status" +import { readSettings } from "@/services/settings" + +type SearchParams = Promise<Record<string, string | string[] | undefined>> + +function first(value: string | string[] | undefined): string | undefined { + return Array.isArray(value) ? value[0] : value +} + +/** Resolves to null instead of throwing, so one failed read can't take the page down. */ +async function orNull<T>(label: string, userId: string, promise: Promise<T>): Promise<T | null> { + try { + return await promise + } catch (err) { + logger.error("settings.page_load_failed", { part: label, user_id: userId, error: String(err) }) + return null + } +} + +export default async function SettingsPage({ searchParams }: { searchParams: SearchParams }) { + const userId = await getCurrentUserId() + if (!userId) redirect("/auth/signin?callbackUrl=%2Fsettings") + + const [params, user, settings, google] = await Promise.all([ + searchParams, + orNull( + "account", + userId, + prisma.user.findUnique({ where: { id: userId }, select: { name: true, email: true } }) + ), + orNull("settings", userId, readSettings(userId)), + orNull("google", userId, readGoogleStatus(userId)), + ]) + + const config = publicConfig() + const dev = process.env.NODE_ENV !== "production" + const account: AccountSummary | null = user ? { name: user.name, email: user.email } : null + const connectResult = googleConnectResult(first(params.google), first(params.reason), { dev }) + // Without the fake provider or a client id there's nothing to connect; only developers need to hear why. + const showCalendar = config.google_configured || dev + + const sections: SettingsNavItem[] = [ + { id: "profile", label: "Profile" }, + { id: "study", label: "Study preferences" }, + { id: "appearance", label: "Appearance" }, + ...(showCalendar ? [{ id: "calendar", label: "Google Calendar" }] : []), + { id: "ai", label: "AI features" }, + { id: "data", label: "Data" }, + { id: "account", label: "Account" }, + ] + + return ( + <PageContainer> + <div className="grid gap-8 md:grid-cols-[13rem_minmax(0,1fr)] lg:grid-cols-[15rem_minmax(0,1fr)]"> + <SettingsNav items={sections} /> + <div className="flex max-w-3xl min-w-0 flex-col gap-6"> + {connectResult ? <ConnectResultBanner result={connectResult} /> : null} + + <PreferencesForm initial={settings} account={account} /> + + <SettingsSection id="appearance" title="Appearance"> + <SettingsRows> + <Field> + <FieldTitle>Theme</FieldTitle> + <FieldDescription> + Applies right away, on this device only. System follows your device's light or + dark setting. + </FieldDescription> + <ThemeToggle variant="segmented" /> + </Field> + </SettingsRows> + </SettingsSection> + + {showCalendar ? ( + <GoogleCalendarSection initial={google} configured={config.google_configured} dev={dev} /> + ) : null} + + <AiSection config={config} dev={dev} /> + <DataSection /> + <AccountSection + emailConfigured={config.email_configured} + passwordResetAvailable={config.email_links_available} + dev={dev} + /> + </div> + </div> + </PageContainer> + ) +} diff --git a/src/app/(auth)/auth/forgot-password/page.tsx b/src/app/(auth)/auth/forgot-password/page.tsx new file mode 100644 index 00000000..2975a9ae --- /dev/null +++ b/src/app/(auth)/auth/forgot-password/page.tsx @@ -0,0 +1,36 @@ +import type { Metadata } from "next"; +import Link from "next/link"; + +import { AuthActions, AuthCard } from "@/components/auth/auth-card"; +import { ForgotPasswordForm } from "@/components/auth/forgot-password-form"; +import { Button } from "@/components/ui/button"; +import { areEmailLinksAvailable } from "@/lib/email/delivery"; +import { PASSWORD_RESET_UNAVAILABLE } from "@/lib/email/messages"; + +// Whether reset links can go out depends on the server's runtime settings, +// so the page can't be rendered once at build time. +export const dynamic = "force-dynamic"; + +export function generateMetadata(): Metadata { + return { title: areEmailLinksAvailable() ? "Reset password" : PASSWORD_RESET_UNAVAILABLE.title }; +} + +/** + * Open to signed-in visitors as well: an emailed reset link is the only way + * to change a password, signed in or not. A server that can't deliver the + * link says so up front instead of asking for an address. + */ +export default function ForgotPasswordPage() { + if (!areEmailLinksAvailable()) { + return ( + <AuthCard title={PASSWORD_RESET_UNAVAILABLE.title} description={PASSWORD_RESET_UNAVAILABLE.description}> + <AuthActions> + <Button asChild> + <Link href="/auth/signin">Back to sign in</Link> + </Button> + </AuthActions> + </AuthCard> + ); + } + return <ForgotPasswordForm />; +} diff --git a/src/app/(auth)/auth/reset-password/page.tsx b/src/app/(auth)/auth/reset-password/page.tsx new file mode 100644 index 00000000..c8813e3e --- /dev/null +++ b/src/app/(auth)/auth/reset-password/page.tsx @@ -0,0 +1,44 @@ +import type { Metadata } from "next"; +import { cache } from "react"; + +import { resetPasswordTitle, type ResetLinkProblem } from "@/components/auth/link-copy"; +import { ResetPasswordForm } from "@/components/auth/reset-password-form"; +import { firstParam, type SearchParams } from "@/components/auth/server"; +import { inspectToken } from "@/lib/tokens"; +import { logger } from "@/lib/logger"; + +/** + * Why the link can't be used, or null to show the form. Cached for the + * request, so the tab title and the page share one token lookup. + */ +const linkProblem = cache(async (token: string): Promise<ResetLinkProblem | null> => { + if (!token) return "invalid"; + try { + const state = await inspectToken(token, "PASSWORD_RESET"); + return state.status === "valid" ? null : state.status; + } catch (err) { + // Show the form; the API checks the link again when it's submitted. + logger.error("password_reset.inspect_failed", { error: String(err) }); + return null; + } +}); + +async function tokenFrom(searchParams: SearchParams): Promise<string> { + return firstParam((await searchParams).token) ?? ""; +} + +/** The tab title names the screen the link opens: the form, or why the link doesn't work. */ +export async function generateMetadata({ searchParams }: { searchParams: SearchParams }): Promise<Metadata> { + return { title: resetPasswordTitle(await linkProblem(await tokenFrom(searchParams))) }; +} + +/** + * /auth/reset-password?token=... (the URL in the reset email; keep it). + * Open to signed-in visitors too: a reset link must work on a device that + * is still signed in. + */ +export default async function ResetPasswordPage({ searchParams }: { searchParams: SearchParams }) { + const token = await tokenFrom(searchParams); + const problem = await linkProblem(token); + return <ResetPasswordForm key={token} token={token} initialProblem={problem} />; +} diff --git a/src/app/(auth)/auth/signin/page.tsx b/src/app/(auth)/auth/signin/page.tsx new file mode 100644 index 00000000..50453794 --- /dev/null +++ b/src/app/(auth)/auth/signin/page.tsx @@ -0,0 +1,31 @@ +import type { Metadata } from "next"; + +import { safeCallbackUrl } from "@/components/auth/callback-url"; +import { signInErrorBanner } from "@/lib/auth-messages"; +import { firstParam, redirectIfSignedIn, type SearchParams } from "@/components/auth/server"; +import { SignInForm } from "@/components/auth/sign-in-form"; + +export const metadata: Metadata = { + title: "Sign in", +}; + +/** + * /auth/signin?callbackUrl=/plan&verified=true&error=CredentialsSignin + * (?account=deleted after deleting an account in Settings) + * callbackUrl is honoured only as a same-origin path; error codes from + * next-auth are shown in plain words, never as the raw code. + */ +export default async function SignInPage({ searchParams }: { searchParams: SearchParams }) { + const params = await searchParams; + const callbackUrl = safeCallbackUrl(params.callbackUrl); + await redirectIfSignedIn(callbackUrl); + + return ( + <SignInForm + callbackUrl={callbackUrl} + verified={firstParam(params.verified) === "true"} + accountDeleted={firstParam(params.account) === "deleted"} + initialError={signInErrorBanner(firstParam(params.error))} + /> + ); +} diff --git a/src/app/(auth)/auth/signup/page.tsx b/src/app/(auth)/auth/signup/page.tsx new file mode 100644 index 00000000..b9daeb66 --- /dev/null +++ b/src/app/(auth)/auth/signup/page.tsx @@ -0,0 +1,20 @@ +import type { Metadata } from "next"; + +import { safeCallbackUrl } from "@/components/auth/callback-url"; +import { isEmailVerificationRequired, redirectIfSignedIn, type SearchParams } from "@/components/auth/server"; +import { SignUpForm } from "@/components/auth/sign-up-form"; + +export const metadata: Metadata = { + title: "Create account", +}; + +/** /auth/signup?callbackUrl=/plan */ +export default async function SignUpPage({ searchParams }: { searchParams: SearchParams }) { + const params = await searchParams; + const callbackUrl = safeCallbackUrl(params.callbackUrl); + await redirectIfSignedIn(callbackUrl); + + // Read on the server, so the form knows where a new account goes without + // a request to /api/config after the account is created. + return <SignUpForm callbackUrl={callbackUrl} verificationRequired={isEmailVerificationRequired()} />; +} diff --git a/src/app/(auth)/auth/verify-email/page.tsx b/src/app/(auth)/auth/verify-email/page.tsx new file mode 100644 index 00000000..aeaed660 --- /dev/null +++ b/src/app/(auth)/auth/verify-email/page.tsx @@ -0,0 +1,32 @@ +import type { Metadata } from "next"; + +import { parseVerifyEmailStatus, verifyEmailTitle } from "@/components/auth/link-copy"; +import { firstParam, redirectIfSignedIn, type SearchParams } from "@/components/auth/server"; +import { validateEmail } from "@/lib/auth-validation"; +import { VerifyEmailPanel } from "@/components/auth/verify-email-panel"; + +const MAX_EMAIL_LENGTH = 254; + +/** The tab title matches the panel's heading, so a broken link doesn't read "Verify your email". */ +export async function generateMetadata({ searchParams }: { searchParams: SearchParams }): Promise<Metadata> { + const status = parseVerifyEmailStatus(firstParam((await searchParams).status)); + return { title: verifyEmailTitle(status) }; +} + +/** + * /auth/verify-email?email=... after creating an account, or + * /auth/verify-email?status=expired|invalid|busy|failed when a verification + * link from the email didn't work (see /api/auth/verify-email). + */ +export default async function VerifyEmailPage({ searchParams }: { searchParams: SearchParams }) { + await redirectIfSignedIn("/"); + const params = await searchParams; + + const status = parseVerifyEmailStatus(firstParam(params.status)); + + // Only echo something that looks like an email address back onto the page. + const rawEmail = firstParam(params.email)?.trim() ?? ""; + const email = rawEmail.length <= MAX_EMAIL_LENGTH && !validateEmail(rawEmail) ? rawEmail : null; + + return <VerifyEmailPanel status={status} email={email} />; +} diff --git a/src/app/(auth)/layout.tsx b/src/app/(auth)/layout.tsx new file mode 100644 index 00000000..ca742eb5 --- /dev/null +++ b/src/app/(auth)/layout.tsx @@ -0,0 +1,22 @@ +import { ThemeToggle } from "@/components/app/theme-toggle"; + +/** + * Sign-in, create account, password and verification screens, laid out like + * Google's sign-in: one card centred on a tonal page with the theme control + * under it, and no app navigation. Under 600px the page itself is the card. + * Each page renders its own AuthCard, whose title is the page's h1. + */ +export default function AuthLayout({ children }: { children: React.ReactNode }) { + return ( + <div className="flex min-h-dvh flex-col bg-card sm:items-center sm:justify-center sm:bg-surface-container sm:px-6 sm:py-10"> + <div className="flex w-full flex-1 flex-col sm:max-w-[30rem] sm:flex-none md:max-w-[65rem]"> + <main id="main-content" tabIndex={-1} className="flex flex-1 flex-col"> + {children} + </main> + <footer className="flex items-center px-3 py-2 sm:px-0 sm:pt-3"> + <ThemeToggle /> + </footer> + </div> + </div> + ); +} diff --git a/src/app/(card-review)/flashcards/[deckId]/review/error.tsx b/src/app/(card-review)/flashcards/[deckId]/review/error.tsx new file mode 100644 index 00000000..f90b7e62 --- /dev/null +++ b/src/app/(card-review)/flashcards/[deckId]/review/error.tsx @@ -0,0 +1,38 @@ +"use client" + +import Link from "next/link" +import { CloudOffIcon, RotateCcwIcon } from "lucide-react" + +import { StatusScreen } from "@/components/app/status-screen" +import { Button } from "@/components/ui/button" + +/** The review failed to load or crashed: ratings already saved stay saved. */ +export default function ReviewError({ + error, + retry, +}: { + error: Error & { digest?: string } + /** Refetches and re-renders the segment (reset would only re-render the failed payload). */ + retry: () => void +}) { + return ( + <StatusScreen + icon={CloudOffIcon} + tone="error" + title="Cards didn't load." + description="Ratings you already gave are saved. Retry, or go back to your decks." + actions={ + <> + <Button onClick={() => retry()}> + <RotateCcwIcon data-icon="inline-start" aria-hidden="true" /> + Retry + </Button> + <Button asChild variant="outline"> + <Link href="/flashcards">Go to Flashcards</Link> + </Button> + </> + } + footnote={error.digest ? `Reference: ${error.digest}` : undefined} + /> + ) +} diff --git a/src/app/(card-review)/flashcards/[deckId]/review/not-found.tsx b/src/app/(card-review)/flashcards/[deckId]/review/not-found.tsx new file mode 100644 index 00000000..f59552be --- /dev/null +++ b/src/app/(card-review)/flashcards/[deckId]/review/not-found.tsx @@ -0,0 +1,20 @@ +import Link from "next/link" +import { LayersIcon } from "lucide-react" + +import { StatusScreen } from "@/components/app/status-screen" +import { Button } from "@/components/ui/button" + +export default function ReviewNotFound() { + return ( + <StatusScreen + icon={LayersIcon} + title="Deck not found" + description="This link doesn't match one of your decks. It may have been deleted." + actions={ + <Button asChild> + <Link href="/flashcards">Go to Flashcards</Link> + </Button> + } + /> + ) +} diff --git a/src/app/(card-review)/flashcards/[deckId]/review/page.tsx b/src/app/(card-review)/flashcards/[deckId]/review/page.tsx new file mode 100644 index 00000000..96940060 --- /dev/null +++ b/src/app/(card-review)/flashcards/[deckId]/review/page.tsx @@ -0,0 +1,76 @@ +import { cache, Suspense } from "react" +import type { Metadata } from "next" +import { notFound, redirect } from "next/navigation" + +import { getCurrentUserId } from "@/lib/auth" +import { isDeckOwner } from "@/services/flashcards" +import { getStudyCards, type StudyScope } from "@/services/spaced-repetition" +import { CardReview } from "@/components/cards/review/card-review" +import { initialReviewState, reviewTitle } from "@/components/cards/review/review-state" +import { ReviewSkeleton } from "@/components/cards/skeletons" + +type Props = { + params: Promise<{ deckId: string }> + searchParams: Promise<{ scope?: string | string[] }> +} + +/** One load per request, shared by the metadata and the page. */ +const loadReview = cache(async (deckId: string, scope: StudyScope) => { + const userId = await getCurrentUserId() + if (!userId) return { userId: null, data: null } + try { + return { userId, data: await getStudyCards(userId, deckId, scope) } + } catch (err) { + if (err instanceof Error && err.message === "Deck not found") return { userId, data: null } + throw err + } +}) + +function scopeOf(value: string | string[] | undefined): StudyScope { + return value === "all" ? "all" : "due" +} + +export async function generateMetadata({ params, searchParams }: Props): Promise<Metadata> { + const [{ deckId }, sp] = await Promise.all([params, searchParams]) + try { + const { data } = await loadReview(deckId, scopeOf(sp.scope)) + if (!data) return { title: "Deck not found" } + // The same title the review sets once it's on screen, so the tab doesn't change on load + return { title: reviewTitle(initialReviewState(data.cards, data.stats), data.deck.title) } + } catch { + return { title: "Review" } + } +} + +/** + * /flashcards/:deckId/review: the due cards (or ?scope=all, every card) one + * at a time. Refreshing starts again from the server's state, so cards + * already rated aren't due anymore and the review picks up where it was. + * + * The deck is checked before anything streams, so a missing deck or another + * account's deck answers with a real 404 (like /s/[sessionId]). That is why + * this segment has no loading.tsx; the skeleton comes from the Suspense + * boundary below, after the check. + */ +export default async function ReviewPage({ params, searchParams }: Props) { + const [{ deckId }, sp] = await Promise.all([params, searchParams]) + const scope = scopeOf(sp.scope) + const userId = await getCurrentUserId() + if (!userId) { + redirect(`/auth/signin?callbackUrl=${encodeURIComponent(`/flashcards/${deckId}/review`)}`) + } + if (!(await isDeckOwner(userId, deckId))) notFound() + + return ( + <Suspense fallback={<ReviewSkeleton />}> + <ReviewContent deckId={deckId} scope={scope} /> + </Suspense> + ) +} + +async function ReviewContent({ deckId, scope }: { deckId: string; scope: StudyScope }) { + const { data } = await loadReview(deckId, scope) + // Deleted between the check and this load + if (!data) notFound() + return <CardReview key={`${deckId}:${scope}`} data={data} timeZone={data.timeZone} /> +} diff --git a/src/app/(card-review)/layout.tsx b/src/app/(card-review)/layout.tsx new file mode 100644 index 00000000..75759ef9 --- /dev/null +++ b/src/app/(card-review)/layout.tsx @@ -0,0 +1,17 @@ +import { SkipLink } from "@/components/shell/skip-link" + +/** + * A flashcard review takes the whole screen like a study session: no rail, + * no app bar, the .lesson scope (rounded type, lesson palette), and the + * close button in the review's own top bar. + */ +export default function CardReviewLayout({ children }: { children: React.ReactNode }) { + return ( + <div className="lesson flex min-h-dvh flex-col"> + <SkipLink /> + <main id="main-content" tabIndex={-1} className="flex flex-1 flex-col"> + {children} + </main> + </div> + ) +} diff --git a/src/app/achievements/page.tsx b/src/app/achievements/page.tsx deleted file mode 100644 index 1521119e..00000000 --- a/src/app/achievements/page.tsx +++ /dev/null @@ -1,242 +0,0 @@ -"use client"; - -import { useState, useEffect } from "react"; -import Link from "next/link"; -import { apiGet } from "@/lib/client-api"; -import { ALL_BADGES, TOTAL_BADGES, CATEGORY_LABELS } from "@/lib/badge-data"; - -interface GameState { - xpToday: number; - xpTotal: number; - dailyXpGoal: number; - streak: number; - streakFreezes: number; - reviewCount: number; - achievements: { badgeType: string; earnedAt: string }[]; - newAchievements: string[]; -} - -export default function AchievementsPage() { - const [gameState, setGameState] = useState<GameState | null>(null); - const [loading, setLoading] = useState(true); - - useEffect(() => { - apiGet("/api/stats/game") - .then((state) => setGameState(state)) - .catch(() => {}) - .finally(() => setLoading(false)); - }, []); - - if (loading) { - return ( - <main style={mainStyle}> - <style>{`@keyframes dash-spin { to { transform: rotate(360deg); } }`}</style> - <h1 style={headingStyle}>Achievements</h1> - <div style={{ textAlign: "center", padding: "4rem 0", color: "var(--color-text-muted)" }}> - <div style={spinnerStyle} /> - <p style={{ marginTop: "1rem" }}>Loading achievements...</p> - </div> - </main> - ); - } - - const earnedSet = new Set(gameState?.achievements.map((a) => a.badgeType) || []); - const earnedMap = new Map(gameState?.achievements.map((a) => [a.badgeType, a.earnedAt]) || []); - const totalEarned = earnedSet.size; - const completionPct = Math.round((totalEarned / TOTAL_BADGES) * 100); - - function getProgress(badge: typeof ALL_BADGES[0]): number { - if (earnedSet.has(badge.key)) return badge.threshold; - if (badge.category === "streak") return gameState?.streak || 0; - if (badge.category === "xp") return gameState?.xpTotal || 0; - if (badge.category === "review") return gameState?.reviewCount || 0; - return 0; - } - - const categories = ["streak", "review", "xp"] as const; - - return ( - <main style={mainStyle}> - <h1 style={headingStyle}>Achievements</h1> - - {/* Overall progress */} - <section style={overviewCardStyle}> - <div style={{ display: "flex", alignItems: "center", gap: "1rem" }}> - <svg width={64} height={64} viewBox="0 0 64 64" style={{ flexShrink: 0 }}> - <circle cx={32} cy={32} r={26} fill="none" strokeWidth={5} style={{ stroke: "var(--color-bg-darkest)" }} /> - <circle - cx={32} cy={32} r={26} - fill="none" - strokeWidth={5} - strokeLinecap="round" - strokeDasharray={2 * Math.PI * 26} - strokeDashoffset={2 * Math.PI * 26 * (1 - completionPct / 100)} - transform="rotate(-90 32 32)" - style={{ transition: "stroke-dashoffset 0.5s", stroke: "var(--color-primary)" }} - /> - <text x={32} y={35} textAnchor="middle" fontSize="14" fontWeight="bold" fontFamily="inherit" style={{ fill: "var(--color-primary)" }}> - {completionPct}% - </text> - </svg> - <div> - <div style={{ fontSize: "1.3rem", fontWeight: 700, color: "var(--color-primary)", fontFamily: "var(--font-display)" }}> - {totalEarned} / {TOTAL_BADGES} Badges - </div> - <div style={{ fontSize: "0.8rem", color: "var(--color-text-dim)", marginTop: "0.2rem" }}> - {totalEarned === TOTAL_BADGES - ? "All achievements unlocked!" - : `${TOTAL_BADGES - totalEarned} more to collect`} - </div> - </div> - </div> - </section> - - {/* Badge categories */} - {categories.map((cat) => { - const badges = ALL_BADGES.filter((b) => b.category === cat); - const catInfo = CATEGORY_LABELS[cat]; - const earned = badges.filter((b) => earnedSet.has(b.key)).length; - - return ( - <section key={cat} style={{ marginBottom: "2rem" }}> - <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "0.75rem" }}> - <h2 style={{ ...sectionHeadingStyle, color: catInfo.color, margin: 0 }}>{catInfo.label}</h2> - <span style={{ fontSize: "0.75rem", color: "var(--color-text-dim)" }}>{earned}/{badges.length}</span> - </div> - <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(320px, 1fr))", gap: 16 }}> - {badges.map((badge) => { - const isEarned = earnedSet.has(badge.key); - const earnedDate = earnedMap.get(badge.key); - const current = getProgress(badge); - const pct = isEarned ? 100 : Math.min(Math.round((current / badge.threshold) * 100), 99); - - return ( - <div - key={badge.key} - style={{ - display: "flex", - alignItems: "center", - gap: "0.85rem", - padding: "1.25rem", - background: isEarned ? "var(--color-bg-done)" : "var(--color-bg-card)", - border: `1px solid ${isEarned ? "var(--color-border-done)" : "var(--color-border)"}`, - borderRadius: "var(--radius)", - opacity: isEarned ? 1 : 0.75, - }} - > - <div style={{ - fontSize: "1.6rem", - width: 40, - height: 40, - display: "flex", - alignItems: "center", - justifyContent: "center", - borderRadius: "50%", - background: isEarned ? "var(--color-bg-card)" : "var(--color-bg)", - filter: isEarned ? "none" : "grayscale(100%)", - flexShrink: 0, - }}> - {badge.icon} - </div> - - <div style={{ flex: 1, minWidth: 0 }}> - <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}> - <span style={{ - fontSize: "0.95rem", - fontWeight: 600, - color: isEarned ? "var(--color-text)" : "var(--color-text-muted)", - }}> - {badge.label} - </span> - {isEarned && earnedDate && ( - <span style={{ fontSize: "0.65rem", color: "var(--color-border-done)" }}> - {new Date(earnedDate).toLocaleDateString()} - </span> - )} - </div> - <div style={{ fontSize: "0.75rem", color: "var(--color-text-dim)", marginTop: "0.15rem" }}> - {badge.description} - </div> - {!isEarned && ( - <div style={{ marginTop: "0.4rem" }}> - <div style={{ height: 4, background: "var(--color-bg-darkest)", borderRadius: 2, overflow: "hidden" }}> - <div style={{ - height: "100%", - width: `${pct}%`, - background: catInfo.color, - borderRadius: 2, - transition: "width 0.5s", - opacity: 0.7, - }} /> - </div> - <div style={{ fontSize: "0.6rem", color: "var(--color-text-dim)", marginTop: "0.15rem", textAlign: "right" }}> - {current} / {badge.threshold} {badge.unit} - </div> - </div> - )} - {isEarned && ( - <div style={{ fontSize: "0.7rem", color: "var(--color-success)", marginTop: "0.2rem", fontWeight: 600 }}> - Unlocked - </div> - )} - </div> - </div> - ); - })} - </div> - </section> - ); - })} - - <div style={{ textAlign: "center", marginTop: "1rem" }}> - <Link href="/" style={{ color: "var(--color-text-dim)", fontSize: "0.85rem", textDecoration: "none" }}>Back to Dashboard</Link> - </div> - </main> - ); -} - -// ---- Styles ---- - -const mainStyle: React.CSSProperties = { - maxWidth: 1100, - margin: "0 auto", - padding: "1.5rem clamp(24px, 4vw, 32px)", - fontFamily: "var(--font-body)", - color: "var(--color-text)", - backgroundColor: "var(--color-bg)", - minHeight: "100vh", -}; - -const headingStyle: React.CSSProperties = { - fontSize: "2rem", - margin: "0 0 1.5rem", - color: "var(--color-primary)", - fontWeight: 700, - fontFamily: "var(--font-display)", -}; - -const sectionHeadingStyle: React.CSSProperties = { - fontSize: "1rem", - fontWeight: 600, - textTransform: "uppercase", - letterSpacing: "0.08em", -}; - -const overviewCardStyle: React.CSSProperties = { - background: "var(--color-bg-card)", - border: "1px solid var(--color-border-subtle)", - borderRadius: "var(--radius)", - boxShadow: "var(--shadow-card)", - padding: "1.5rem", - marginBottom: "2rem", -}; - -const spinnerStyle: React.CSSProperties = { - width: "32px", - height: "32px", - border: "3px solid var(--color-border)", - borderTop: "3px solid var(--color-primary)", - borderRadius: "50%", - margin: "0 auto", - animation: "dash-spin 0.8s linear infinite", -}; diff --git a/src/app/api/account/delete/route.ts b/src/app/api/account/delete/route.ts index 89e68597..aa4c42b0 100644 --- a/src/app/api/account/delete/route.ts +++ b/src/app/api/account/delete/route.ts @@ -1,38 +1,113 @@ import { NextRequest, NextResponse } from "next/server"; -import { z } from "zod/v4"; +import { unauthorized } from "@/lib/http"; +import bcrypt from "bcryptjs"; +import { z } from "zod"; +import { DELETE_ACCOUNT_PHRASE } from "@/lib/account"; import { getUserId } from "@/lib/auth"; +import { forgetSessionCheck } from "@/lib/auth-options"; +import { decryptToken } from "@/lib/crypto/token-vault"; import { prisma } from "@/lib/db"; import { logger } from "@/lib/logger"; +import { tooManyRequests } from "@/lib/rate-limit"; +import { accountDeleteLimiter, deleteUserFiles } from "@/services/account"; const deleteSchema = z.object({ - confirm: z.literal("DELETE MY ACCOUNT"), + confirm: z.literal(DELETE_ACCOUNT_PHRASE), + password: z.string().min(1).max(200), }); +const NOT_DELETED = "Account not deleted. Confirm in the dialog and retry."; +const WRONG_PASSWORD = "That password doesn't match your account. Check it and retry."; +/** Owner of the AI spend rows a deleted account leaves behind. */ +const DELETED_ACCOUNT_ID = "deleted"; + +/** + * The Google token to revoke once the account is gone, read before the + * rows are deleted. Null when there is no connection or the token can't be + * read (the fake provider's placeholder, a rotated key). + */ +async function googleTokenToRevoke(userId: string): Promise<string | null> { + try { + const integration = await prisma.googleIntegration.findUnique({ + where: { userId }, + select: { accessTokenEncrypted: true, refreshTokenEncrypted: true }, + }); + const encrypted = integration?.refreshTokenEncrypted ?? integration?.accessTokenEncrypted; + return encrypted ? decryptToken(encrypted) : null; + } catch { + return null; + } +} + +/** + * Best effort: revoke Study Bot's Google access so the deleted account + * doesn't leave a live grant at Google. Runs only after the deletion + * commits: a revoke can't be undone, and revoking before a failed delete + * would leave a calendar that shows as connected but no longer works. + */ +async function revokeGoogleAccess(userId: string, token: string): Promise<void> { + try { + await fetch("https://oauth2.googleapis.com/revoke", { + method: "POST", + headers: { "Content-Type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams({ token }), + signal: AbortSignal.timeout(5_000), + }); + } catch (err) { + // The tokens are already deleted; the student can remove the grant from + // their Google Account if this didn't reach Google. + logger.warn("account.delete.google_revoke_failed", { userId, error: String(err) }); + } +} + /** - * DELETE /api/account/delete - * GDPR account deletion: permanently deletes the user and all associated data. + * DELETE /api/account/delete with body { confirm: "DELETE MY ACCOUNT", password }. + * Permanently deletes the student and everything they own, uploaded files + * included. The password is checked first, so a session alone (a borrowed + * laptop, a stolen cookie) can't wipe the account. The client signs out + * afterwards, since the session token outlives the account. */ export async function DELETE(request: NextRequest) { const userId = await getUserId(request); if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + return unauthorized(); } let body: unknown; try { body = await request.json(); } catch { - return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 }); + return NextResponse.json({ error: NOT_DELETED }, { status: 400 }); } const parsed = deleteSchema.safeParse(body); if (!parsed.success) { + return NextResponse.json({ error: NOT_DELETED, issues: parsed.error.issues }, { status: 400 }); + } + + const limit = accountDeleteLimiter.check(userId); + if (!limit.allowed) { + return tooManyRequests(limit.retryAfterMs); + } + + const user = await prisma.user.findUnique({ where: { id: userId }, select: { passwordHash: true } }); + if (!user) { + return unauthorized(); + } + if (!(await bcrypt.compare(parsed.data.password, user.passwordHash))) { return NextResponse.json( - { error: "Validation failed. Body must include { confirm: \"DELETE MY ACCOUNT\" }.", issues: parsed.error.issues }, - { status: 400 }, + { + error: WRONG_PASSWORD, + code: "WRONG_PASSWORD", + issues: [{ path: ["password"], message: WRONG_PASSWORD }], + }, + { status: 403 }, ); } + // Read now, while the row exists; the revoke itself waits for the commit. + const googleToken = await googleTokenToRevoke(userId); + try { await prisma.$transaction(async (tx) => { // Phase 1: Leaf models with userId (no children, or children cascade) @@ -41,7 +116,10 @@ export async function DELETE(request: NextRequest) { tx.xpEvent.deleteMany({ where: { userId } }), tx.achievement.deleteMany({ where: { userId } }), tx.objectiveMastery.deleteMany({ where: { userId } }), - tx.aiCallLog.deleteMany({ where: { userId } }), + // Spend rows stay, detached from the account: they hold no content, + // and the cap across all accounts (AI_GLOBAL_DAILY_COST_CAP_USD) sums + // them, so deleting an account can't hand back today's spend. + tx.aiCallLog.updateMany({ where: { userId }, data: { userId: DELETED_ACCOUNT_ID } }), tx.oAuthState.deleteMany({ where: { userId } }), tx.studyGuide.deleteMany({ where: { userId } }), tx.planItemExternalEvent.deleteMany({ where: { userId } }), @@ -51,6 +129,11 @@ export async function DELETE(request: NextRequest) { tx.sessionErrorLog.deleteMany({ where: { userId } }), tx.chatMessage.deleteMany({ where: { userId } }), tx.verificationToken.deleteMany({ where: { userId } }), + // Queued embedding jobs carry the student's id in their payload. A + // running job is left to finish; it finds no chunks once they're gone. + tx.jobQueue.deleteMany({ + where: { payload: { path: ["userId"], equals: userId }, status: { not: "RUNNING" } }, + }), ]); // Phase 2: Child models without userId (filter via parent relation) @@ -78,12 +161,29 @@ export async function DELETE(request: NextRequest) { // Phase 5: Delete User — remaining cascade relations handle the rest await tx.user.delete({ where: { id: userId } }); }); + } catch (err) { + logger.error("account.delete.failed", { userId, error: String(err) }); + return NextResponse.json( + { error: "Account not deleted. Check your connection and retry." }, + { status: 500 }, + ); + } - logger.info("account.deleted", { userId }); + logger.info("account.deleted", { userId }); + // Sessions on other devices end on their next request, not after the + // recheck interval. + forgetSessionCheck(userId); - return NextResponse.json({ deleted: true }); + if (googleToken) await revokeGoogleAccess(userId, googleToken); + + // The rows are gone; now the uploaded lecture files. Nothing references + // them any more, so a later cleanup could never find them. A failure here + // is logged for the operator and doesn't undo the deletion. + try { + await deleteUserFiles(userId); } catch (err) { - logger.error("account.delete.failed", { userId, error: String(err) }); - return NextResponse.json({ error: "Internal server error" }, { status: 500 }); + logger.error("account.delete.files_failed", { userId, error: String(err) }); } + + return NextResponse.json({ deleted: true }); } diff --git a/src/app/api/account/export/route.ts b/src/app/api/account/export/route.ts index 422d57f2..7c2cb781 100644 --- a/src/app/api/account/export/route.ts +++ b/src/app/api/account/export/route.ts @@ -1,21 +1,39 @@ import { NextRequest, NextResponse } from "next/server"; +import { unauthorized } from "@/lib/http"; import { getUserId } from "@/lib/auth"; import { prisma } from "@/lib/db"; import { logger } from "@/lib/logger"; -import { aiLimiter, tooManyRequests } from "@/lib/rate-limit"; +import { plural } from "@/lib/format"; +import { createRateLimiter } from "@/lib/rate-limit"; + +// Exports are heavy reads, so they get their own budget instead of sharing +// the AI limiter (an export no longer blocks generating a deck, or the reverse). +const exportLimiter = createRateLimiter("account-export", { + maxRequests: 3, + windowMs: 60 * 1000, +}); /** * GET /api/account/export - * GDPR data export: returns all user data as a downloadable JSON file. + * Data export: returns everything the student owns as a JSON attachment. */ export async function GET(request: NextRequest) { const userId = await getUserId(request); if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + return unauthorized(); } - const rl = aiLimiter.check(userId); - if (!rl.allowed) return tooManyRequests(rl.retryAfterMs); + const rl = exportLimiter.check(userId); + if (!rl.allowed) { + const seconds = Math.max(1, Math.ceil(rl.retryAfterMs / 1000)); + return NextResponse.json( + { + error: `Too many exports. Retry in ${plural(seconds, { one: "# second", other: "# seconds" })}.`, + retry_after_seconds: seconds, + }, + { status: 429, headers: { "Retry-After": String(seconds) } }, + ); + } try { const [ @@ -160,13 +178,24 @@ export async function GET(request: NextRequest) { logger.info("account.export.success", { userId }); - return NextResponse.json(exportData, { + // Some columns are BigInt (AI call costs, Google token expiry), which + // JSON.stringify refuses; write them as decimal strings. + const body = JSON.stringify(exportData, (_key, value) => + typeof value === "bigint" ? value.toString() : value, + ); + + return new NextResponse(body, { headers: { + "Content-Type": "application/json; charset=utf-8", "Content-Disposition": `attachment; filename="study-bot-export-${Date.now()}.json"`, + "Cache-Control": "no-store", }, }); } catch (err) { logger.error("account.export.failed", { userId, error: String(err) }); - return NextResponse.json({ error: "Internal server error" }, { status: 500 }); + return NextResponse.json( + { error: "Data not exported. Check your connection and retry." }, + { status: 500 }, + ); } } diff --git a/src/app/api/admin/ai/usage/route.ts b/src/app/api/admin/ai/usage/route.ts index bd7b742a..04967e6a 100644 --- a/src/app/api/admin/ai/usage/route.ts +++ b/src/app/api/admin/ai/usage/route.ts @@ -1,23 +1,21 @@ /** * GET /api/admin/ai/usage — AI usage stats. * - * Query params: user_id (optional), days (default 7) + * Query params: user_id (optional, defaults to the caller), days (default 7) */ import { NextRequest, NextResponse } from "next/server"; import { prisma } from "@/lib/db"; -import { getUserId } from "@/lib/auth"; +import { requireAdmin } from "@/lib/admin"; import { generalLimiter, tooManyRequests } from "@/lib/rate-limit"; export async function GET(request: NextRequest) { - const userId = await getUserId(request); - if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); - } + const admin = await requireAdmin(request); + if ("response" in admin) return admin.response; - const rl = generalLimiter.check(userId); + const rl = generalLimiter.check(admin.userId); if (!rl.allowed) return tooManyRequests(rl.retryAfterMs); - const filterUserId = userId; + const filterUserId = request.nextUrl.searchParams.get("user_id") || admin.userId; const daysRaw = parseInt(request.nextUrl.searchParams.get("days") || "7", 10); const days = Math.max(1, Math.min(Number.isNaN(daysRaw) ? 7 : daysRaw, 365)); const since = new Date(); @@ -37,7 +35,7 @@ export async function GET(request: NextRequest) { const totalCostMicros = logs.reduce((sum, l) => sum + Number(l._sum.costUsdMicros ?? 0), 0); return NextResponse.json({ - user_id: userId, + user_id: filterUserId, period_days: days, total_cost_usd: totalCostMicros / 1_000_000, breakdown: logs.map((l) => ({ diff --git a/src/app/api/admin/jobs/route.ts b/src/app/api/admin/jobs/route.ts index d2ad17c5..7501a8cc 100644 --- a/src/app/api/admin/jobs/route.ts +++ b/src/app/api/admin/jobs/route.ts @@ -5,18 +5,11 @@ */ import { NextRequest, NextResponse } from "next/server"; import { prisma } from "@/lib/db"; -import { getUserId } from "@/lib/auth"; +import { requireAdmin } from "@/lib/admin"; export async function GET(request: NextRequest) { - const userId = await getUserId(request); - if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); - } - - const adminIds = (process.env.ADMIN_USER_IDS || "").split(",").filter(Boolean); - if (!adminIds.includes(userId)) { - return NextResponse.json({ error: "Forbidden" }, { status: 403 }); - } + const admin = await requireAdmin(request); + if ("response" in admin) return admin.response; const statusFilter = request.nextUrl.searchParams.get("status"); const limitRaw = parseInt(request.nextUrl.searchParams.get("limit") || "20", 10); diff --git a/src/app/api/admin/search/health/route.ts b/src/app/api/admin/search/health/route.ts index d5b0c3a4..28c1638e 100644 --- a/src/app/api/admin/search/health/route.ts +++ b/src/app/api/admin/search/health/route.ts @@ -5,18 +5,11 @@ */ import { NextRequest, NextResponse } from "next/server"; import { prisma } from "@/lib/db"; -import { getUserId } from "@/lib/auth"; +import { requireAdmin } from "@/lib/admin"; export async function GET(request: NextRequest) { - const userId = await getUserId(request); - if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); - } - - const adminIds = (process.env.ADMIN_USER_IDS || "").split(",").filter(Boolean); - if (!adminIds.includes(userId)) { - return NextResponse.json({ error: "Forbidden" }, { status: 403 }); - } + const admin = await requireAdmin(request); + if ("response" in admin) return admin.response; try { // Check pgvector extension let pgvectorAvailable = false; @@ -54,7 +47,7 @@ export async function GET(request: NextRequest) { embedding_status: statusMap, pending_embed_jobs: pendingJobs, }); - } catch (err) { + } catch { return NextResponse.json( { error: "Health check failed" }, { status: 500 }, diff --git a/src/app/api/assistant/answer/route.ts b/src/app/api/assistant/answer/route.ts index 71d10534..dcec54e2 100644 --- a/src/app/api/assistant/answer/route.ts +++ b/src/app/api/assistant/answer/route.ts @@ -1,71 +1,127 @@ /** - * POST /api/assistant/answer — RAG-powered study assistant. + * POST /api/assistant/answer: answers a question from the student's course + * materials, with numbered sources. * - * 1. Search course materials (hybrid FTS+vector) + * 1. Search course materials (hybrid FTS + vector): first for passages with + * every word of the question, then, if none has them all, for passages + * with enough of its words (search.ts, match "any") * 2. Pass retrieved chunks + question to AI (ANSWER_WITH_CITATIONS) - * 3. Return answer with citations + * 3. Renumber the sources so inline [n] matches sources[n - 1] + * 4. When nothing is retrieved, or the model says the excerpts don't answer + * the question, reply with the app's own notice instead of AI text + * 5. With save: true, store the question (first) and the answer in the + * course's chat history. A retry passes question_id so the question is + * stored once. */ import { NextRequest, NextResponse } from "next/server"; -import { z } from "zod/v4"; +import { z } from "zod"; import { getUserId } from "@/lib/auth"; -import { hybridSearch } from "@/lib/search"; +import { prisma } from "@/lib/db"; +import { hybridSearch, type RetrievalMode } from "@/lib/search"; import { runTask, embed, GatewayError, type GatewayContext } from "@/lib/ai/gateway"; import { AiTask } from "@/lib/ai/types"; import { getPrompt } from "@/lib/ai/prompt-registry"; import { createProvider } from "@/lib/ai/provider-factory"; import { logger } from "@/lib/logger"; -import { aiLimiter, tooManyRequests } from "@/lib/rate-limit"; +import { aiLimiter } from "@/lib/rate-limit"; +import { + failed, + gatewayFailure, + invalidInput, + invalidJson, + rateLimited, + unauthorized, +} from "../../flashcards/_lib/http"; +import { normalizeAnswer, noticeText, type ModelCitation, type StoredNotice } from "../../chat/_lib/sources"; +import { MESSAGE_SELECT, toMessageDtos } from "../../chat/_lib/messages"; + +const QUESTION_MAX = 2000; const answerRequestSchema = z.object({ - question: z.string().min(1).max(2000), - course_name: z.string().min(1), - exam_name: z.string().optional(), + question: z + .string() + .trim() + .min(1, "Type a question first.") + .max(QUESTION_MAX, "Shorten your question to 2,000 characters."), + course_name: z.string().trim().min(1).max(200), + exam_name: z.string().trim().max(200).optional(), verbosity: z.enum(["SHORT", "MEDIUM", "LONG"]).default("MEDIUM"), retrieval_mode: z.enum(["FTS", "VECTOR", "HYBRID"]).optional(), top_k: z.number().int().min(1).max(10).default(5), + /** Store the question and the answer in the course's chat history. */ + save: z.boolean().default(false), + /** Retrying a question that is already stored: answer it without storing it again. */ + question_id: z.string().min(1).max(100).optional(), }); interface AnswerOutput { answer_markdown: string; - citations: { chunk_id: string; reason: string; quote_snippet: string }[]; + citations: ModelCitation[]; } const EMBED_MODEL = process.env.AI_MODEL_EMBED || "text-embedding-3-small"; const ANSWER_MODEL = process.env.AI_MODEL_ANSWER || "gpt-4o-mini"; +const NOT_ANSWERED = "Answer not generated. Retry."; + +/** + * What ANSWER_WITH_CITATIONS tells the model to write when the excerpts + * don't answer the question. It's not an answer, so it gets the notice. + */ +const MODEL_NO_ANSWER = /^your materials don['’]t cover this( question)?\.?$/i; + +/** The search mode hybridSearch would pick, so FTS-only setups skip the embedding call. */ +function retrievalMode(requested: RetrievalMode | undefined): RetrievalMode { + return requested ?? (process.env.HYBRID_SEARCH_ENABLED === "true" ? "HYBRID" : "FTS"); +} const provider = createProvider(); export async function POST(request: NextRequest) { const userId = await getUserId(request); - if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); - } + if (!userId) return unauthorized(); const rl = aiLimiter.check(userId); - if (!rl.allowed) return tooManyRequests(rl.retryAfterMs); + if (!rl.allowed) return rateLimited(rl.retryAfterMs); let body: unknown; try { body = await request.json(); } catch { - return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 }); + return invalidJson(); } const parsed = answerRequestSchema.safeParse(body); if (!parsed.success) { - return NextResponse.json( - { error: "Validation failed", issues: parsed.error.issues }, - { status: 400 }, - ); + const questionIssue = parsed.error.issues.find((i) => i.path[0] === "question"); + return invalidInput(parsed.error, questionIssue?.message ?? "Choose a course, then ask again."); } - const { question, course_name, exam_name, verbosity, retrieval_mode, top_k } = parsed.data; + const { question, course_name, exam_name, verbosity, retrieval_mode, top_k, save, question_id } = parsed.data; + const examName = exam_name || undefined; + const courseKey = examName ? `${course_name}||${examName}` : course_name; const ctx: GatewayContext = { userId, provider }; + // Store the question before anything can fail, so it's never lost. + let questionRow: Awaited<ReturnType<typeof saveQuestion>> | null = null; + if (save) { + try { + questionRow = await saveQuestion(userId, courseKey, question, question_id); + } catch (err) { + if (err instanceof QuestionMissingError) { + return failed("This question isn't in your chat history anymore. Ask it again.", 404, "QUESTION_NOT_FOUND"); + } + logger.error("assistant.question_save_failed", { userId, error: String(err) }); + return failed("Question not saved. Retry."); + } + } + const questionDto = questionRow ? (await toMessageDtos(userId, courseKey, [questionRow]))[0] : null; + const extra = questionDto ? { question: questionDto } : undefined; + try { + const mode = retrievalMode(retrieval_mode); // Generate query embedding for vector/hybrid search let queryEmbedding: number[] | undefined; - if (retrieval_mode !== "FTS") { + if (mode !== "FTS") { try { const embedResult = await embed(ctx, [question], EMBED_MODEL); queryEmbedding = embedResult.embeddings[0]; @@ -75,24 +131,40 @@ export async function POST(request: NextRequest) { } } - // Retrieve relevant chunks - const searchResults = await hybridSearch({ + // Retrieve relevant chunks. Passages with every word of the question + // come first; a question rarely repeats its passage word for word + // ("Why does an ID selector beat any number of class selectors?"), so + // when none has them all, passages with enough of its words count. + const search = { userId, q: question, - namespace: "COURSE", + namespace: "COURSE" as const, courseName: course_name, - examName: exam_name, + examName, topK: top_k, embedding: queryEmbedding, - mode: retrieval_mode, - }); + mode, + }; + let searchResults = await hybridSearch({ ...search, match: "all" }); + if (searchResults.length === 0) searchResults = await hybridSearch({ ...search, match: "any" }); - if (searchResults.length === 0) { + // Say plainly why there's no answer; never fill the gap with unsourced text. + const replyWithNotice = async (notice: StoredNotice["notice"], chunksRetrieved: number) => { + const content = noticeText(notice, course_name); + const answer = save ? await saveAnswer(userId, courseKey, content, { notice }) : null; return NextResponse.json({ - answer_markdown: "I couldn't find any relevant materials in your course documents to answer this question. Try uploading more materials or rephrasing your question.", + answer_markdown: content, citations: [], - meta: { chunks_retrieved: 0 }, + sources: [], + kind: "notice", + meta: { chunks_retrieved: chunksRetrieved }, + ...extra, + ...(answer ? { answer } : {}), }); + }; + + if (searchResults.length === 0) { + return replyWithNotice(await noticeFor(userId, course_name, examName), 0); } // Build AI task input @@ -113,21 +185,80 @@ export async function POST(request: NextRequest) { parseOutput: (raw) => raw as AnswerOutput, }); + const rawMarkdown = typeof result.output.answer_markdown === "string" ? result.output.answer_markdown.trim() : ""; + if (!rawMarkdown) throw new GatewayError("EMPTY_OUTPUT", "The model returned no answer", true); + + const normalized = normalizeAnswer( + rawMarkdown, + Array.isArray(result.output.citations) ? result.output.citations : [], + searchResults, + ); + + // The model found nothing in the excerpts: that's the notice, not an AI answer + if (normalized.citations.length === 0 && MODEL_NO_ANSWER.test(normalized.markdown.trim())) { + return replyWithNotice("no_match", searchResults.length); + } + + const answer = save ? await saveAnswer(userId, courseKey, normalized.markdown, normalized.citations) : null; + return NextResponse.json({ - answer_markdown: result.output.answer_markdown, - citations: result.output.citations, + answer_markdown: normalized.markdown, + citations: normalized.citations, + sources: answer?.sources ?? (await toMessageDtos(userId, courseKey, [syntheticRow(normalized.markdown, normalized.citations)]))[0].sources, + kind: "answer", meta: { chunks_retrieved: searchResults.length, cache_hit: result.meta.cacheHit, latency_ms: result.meta.latencyMs, }, + ...extra, + ...(answer ? { answer } : {}), }); } catch (err) { - if (err instanceof GatewayError) { - const status = err.code === "BUDGET_EXCEEDED" ? 429 : err.code === "AI_DISABLED" ? 503 : 502; - return NextResponse.json({ error: err.message, code: err.code }, { status }); - } + if (err instanceof GatewayError) return gatewayFailure(err, NOT_ANSWERED, extra); logger.error("assistant.answer_failed", { userId, error: String(err) }); - return NextResponse.json({ error: "Internal server error" }, { status: 500 }); + return failed(NOT_ANSWERED, 500, "SERVER_ERROR", extra); } } + +class QuestionMissingError extends Error {} + +async function saveQuestion(userId: string, courseKey: string, question: string, questionId?: string) { + if (questionId) { + const existing = await prisma.chatMessage.findFirst({ + where: { id: questionId, userId, courseKey, role: "user" }, + select: MESSAGE_SELECT, + }); + if (!existing) throw new QuestionMissingError(); + return existing; + } + return prisma.chatMessage.create({ + data: { userId, courseKey, role: "user", content: question }, + select: MESSAGE_SELECT, + }); +} + +async function saveAnswer(userId: string, courseKey: string, content: string, citations: unknown) { + const row = await prisma.chatMessage.create({ + data: { userId, courseKey, role: "assistant", content, citations: citations as object }, + select: MESSAGE_SELECT, + }); + logger.info("chat.answer.saved", { userId, courseKey, messageId: row.id }); + return (await toMessageDtos(userId, courseKey, [row]))[0]; +} + +function syntheticRow(content: string, citations: unknown) { + return { id: "unsaved", role: "assistant", content, citations, createdAt: new Date() }; +} + +/** Why retrieval found nothing: no files, files still processing, or nothing relevant. */ +async function noticeFor(userId: string, courseName: string, examName?: string): Promise<StoredNotice["notice"]> { + const where = { userId, namespace: "COURSE", courseName, ...(examName ? { examName } : {}) }; + const [uploaded, ready] = await Promise.all([ + prisma.contentDocument.count({ where }), + prisma.contentDocument.count({ where: { ...where, status: "PROCESSED" } }), + ]); + if (uploaded === 0) return "no_materials"; + if (ready === 0) return "processing"; + return "no_match"; +} diff --git a/src/app/api/attempts/[attemptId]/feedback/route.ts b/src/app/api/attempts/[attemptId]/feedback/route.ts index 73afe32a..d8c16375 100644 --- a/src/app/api/attempts/[attemptId]/feedback/route.ts +++ b/src/app/api/attempts/[attemptId]/feedback/route.ts @@ -1,15 +1,16 @@ import { NextRequest, NextResponse } from "next/server"; +import { unauthorized } from "@/lib/http"; import { getUserId } from "@/lib/auth"; import { generateFeedback } from "@/services/feedback"; import { logger } from "@/lib/logger"; export async function GET( request: NextRequest, - { params }: { params: { attemptId: string } } + { params }: { params: Promise<{ attemptId: string }> } ) { const userId = await getUserId(request); if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + return unauthorized(); } const { attemptId } = await params; @@ -17,7 +18,7 @@ export async function GET( try { const result = await generateFeedback(userId, attemptId); if (result.status === "NOT_FOUND") { - return NextResponse.json({ error: "Attempt not found" }, { status: 404 }); + return NextResponse.json({ error: "Feedback not found for this answer." }, { status: 404 }); } if (result.status === "PENDING") { // Another request/worker is generating — clients poll until READY. @@ -33,6 +34,6 @@ export async function GET( return NextResponse.json(result); } catch (err) { logger.error("generate_feedback_failed", { error: String(err) }); - return NextResponse.json({ error: "Internal server error" }, { status: 500 }); + return NextResponse.json({ error: "Feedback didn't load. Retry." }, { status: 500 }); } } diff --git a/src/app/api/attempts/[attemptId]/meta/route.ts b/src/app/api/attempts/[attemptId]/meta/route.ts index 4dc97ee7..b73c174d 100644 --- a/src/app/api/attempts/[attemptId]/meta/route.ts +++ b/src/app/api/attempts/[attemptId]/meta/route.ts @@ -1,9 +1,10 @@ import { NextRequest, NextResponse } from "next/server"; +import { unauthorized } from "@/lib/http"; import { getUserId } from "@/lib/auth"; import { updateAttemptMeta } from "@/services/run"; import { updateAttemptMetaSchema } from "@/lib/validation"; import { logger } from "@/lib/logger"; -import { z } from "zod/v4"; +import { z } from "zod"; /** * PATCH /api/attempts/:attemptId/meta @@ -14,11 +15,11 @@ import { z } from "zod/v4"; */ export async function PATCH( request: NextRequest, - { params }: { params: { attemptId: string } } + { params }: { params: Promise<{ attemptId: string }> } ) { const userId = await getUserId(request); if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + return unauthorized(); } const { attemptId } = await params; @@ -27,7 +28,7 @@ export async function PATCH( try { body = await request.json(); } catch { - return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 }); + return NextResponse.json({ error: "Reflection not saved. Retry." }, { status: 400 }); } let parsed; @@ -36,7 +37,7 @@ export async function PATCH( } catch (err) { if (err instanceof z.ZodError) { return NextResponse.json( - { error: "Validation failed", issues: err.issues }, + { error: "Reflection not saved. Keep each answer under 2,000 characters.", issues: err.issues }, { status: 400 } ); } @@ -48,16 +49,16 @@ export async function PATCH( if ("error" in result) { if (result.error === "not_found") { - return NextResponse.json({ error: "Attempt not found" }, { status: 404 }); + return NextResponse.json({ error: "Reflection not saved: this answer no longer exists." }, { status: 404 }); } if (result.error === "forbidden") { - return NextResponse.json({ error: "Forbidden" }, { status: 403 }); + return NextResponse.json({ error: "This session belongs to another account." }, { status: 403 }); } } return NextResponse.json(result.data); } catch (err) { logger.error("attempt_meta_update_failed", { error: String(err) }); - return NextResponse.json({ error: "Internal server error" }, { status: 500 }); + return NextResponse.json({ error: "Reflection not saved. Retry." }, { status: 500 }); } } diff --git a/src/app/api/auth/[...nextauth]/route.ts b/src/app/api/auth/[...nextauth]/route.ts index 6e420cf5..4cdc6a4c 100644 --- a/src/app/api/auth/[...nextauth]/route.ts +++ b/src/app/api/auth/[...nextauth]/route.ts @@ -2,15 +2,56 @@ import NextAuth from "next-auth"; import { NextRequest } from "next/server"; import { authOptions } from "@/lib/auth-options"; import { authLimiter, getClientIp, tooManyRequests } from "@/lib/rate-limit"; +import { CREDENTIALS_SIGNIN, readSignInEmail, signInErrorCode, signInFailureLimiter } from "../_lib/limits"; +import { KNOWN_DEVICE_COOKIE, isKnownDevice, startsSession, withKnownDevice } from "../_lib/known-device"; const nextAuth = NextAuth(authOptions); -// GET passes through (CSRF token, providers, etc.) +type Context = { params: Promise<{ nextauth: string[] }> }; + +/** + * The POST actions that check a password. Sign-out, session updates and + * client logs pass through unlimited, so they never use up sign-in attempts. + */ +const SIGN_IN_ACTIONS = new Set(["signin", "callback"]); + +// GET passes through (CSRF token, providers, session, etc.) export { nextAuth as GET }; -// POST is rate-limited (handles login attempts) -export async function POST(request: NextRequest, context: any) { - const rl = authLimiter.check(getClientIp(request)); - if (!rl.allowed) return tooManyRequests(rl.retryAfterMs); - return nextAuth(request, context); +/** + * POST carries sign-in attempts, sign-out and session updates. Password + * attempts are limited per network, and wrong passwords per account. A + * browser that has signed in to the account before skips the per-account + * limit, so a stranger tripping it can't lock the student out. + */ +export async function POST(request: NextRequest, context: Context) { + const [action, provider] = (await context.params).nextauth ?? []; + if (!SIGN_IN_ACTIONS.has(action)) return nextAuth(request, context); + + const ip = authLimiter.check(getClientIp(request)); + if (!ip.allowed) return tooManyRequests(ip.retryAfterMs); + + const email = action === "callback" && provider === "credentials" ? await readSignInEmail(request) : null; + if (!email) return nextAuth(request, context); + + if (isKnownDevice(request.cookies.get(KNOWN_DEVICE_COOKIE)?.value, email)) { + const response = await nextAuth(request, context); + return startsSession(response) ? withKnownDevice(response, email) : response; + } + + const attempt = signInFailureLimiter.start(email); + if (!attempt.allowed) return tooManyRequests(attempt.retryAfterMs); + + let response: Response; + try { + response = await nextAuth(request, context); + } catch (err) { + signInFailureLimiter.forgive(email, attempt.stamp); + throw err; + } + // Only a wrong email or password counts against the account. + if ((await signInErrorCode(response)) !== CREDENTIALS_SIGNIN) { + signInFailureLimiter.forgive(email, attempt.stamp); + } + return startsSession(response) ? withKnownDevice(response, email) : response; } diff --git a/src/app/api/auth/_lib/known-device.ts b/src/app/api/auth/_lib/known-device.ts new file mode 100644 index 00000000..9d67f083 --- /dev/null +++ b/src/app/api/auth/_lib/known-device.ts @@ -0,0 +1,109 @@ +import { createHmac, timingSafeEqual } from "crypto"; + +import { SECURE_COOKIES, SESSION_COOKIE_NAME } from "@/lib/auth-options"; + +/** + * Known-device cookies (OWASP's "device cookies" against lockout attacks). + * + * The per-account sign-in limit keeps password guessing slow across many + * networks, but anyone who knows a student's email could keep that limit + * tripped and lock the student out, even on their own laptop. A browser + * that has signed in to the account before carries a signed cookie naming + * the account, and its sign-ins skip the per-account limit. The per-network + * limit still applies, and strangers never hold the cookie, so they stay + * capped. + * + * The value is `v1.<issued at, unix seconds>.<HMAC-SHA256>` over the + * account key and the issue time, keyed with NEXTAUTH_SECRET, so it can't + * be forged or moved to another account, and it stops counting after 90 + * days even if the browser keeps it. One cookie per browser: signing in to + * another account replaces it. No database row, so no schema change. + */ +export const KNOWN_DEVICE_COOKIE = "sb_kd"; + +const VERSION = "v1"; + +/** 90 days. Every successful sign-in starts it again. */ +export const KNOWN_DEVICE_MAX_AGE_S = 90 * 24 * 60 * 60; + +// Only the sign-in endpoints read it, so no page or other API ever sees it. +const COOKIE_PATH = "/api/auth"; + +// A cookie issued a little "in the future" by a server whose clock moved back. +const CLOCK_SKEW_S = 5 * 60; + +function signingKey(): string | null { + return process.env.NEXTAUTH_SECRET || process.env.AUTH_SECRET || null; +} + +function signature(key: string, account: string, issuedAt: number): Buffer { + return createHmac("sha256", key) + .update(`study-bot:known-device:${VERSION}\n${account}\n${issuedAt}`) + .digest(); +} + +/** The cookie value for an account key (see accountKey), or null without a secret. */ +export function knownDeviceValue(account: string, now: number = Date.now()): string | null { + const key = signingKey(); + if (!key || !account) return null; + const issuedAt = Math.floor(now / 1000); + return `${VERSION}.${issuedAt}.${signature(key, account, issuedAt).toString("base64url")}`; +} + +/** True when `value` is an unexpired cookie this server issued for `account`. */ +export function isKnownDevice(value: string | undefined, account: string, now: number = Date.now()): boolean { + const key = signingKey(); + if (!key || !value || !account) return false; + + const parts = value.split("."); + if (parts.length !== 3) return false; + const [version, issued, mac] = parts; + if (version !== VERSION || !/^\d{1,12}$/.test(issued)) return false; + + const issuedAt = Number(issued); + const age = Math.floor(now / 1000) - issuedAt; + if (age < -CLOCK_SKEW_S || age > KNOWN_DEVICE_MAX_AGE_S) return false; + + const expected = signature(key, account, issuedAt); + const given = Buffer.from(mac, "base64url"); + return given.length === expected.length && timingSafeEqual(given, expected); +} + +/** The Set-Cookie header that marks this browser as known for `account`, or null without a secret. */ +export function knownDeviceCookie(account: string, now: number = Date.now()): string | null { + const value = knownDeviceValue(account, now); + if (!value) return null; + return [ + `${KNOWN_DEVICE_COOKIE}=${value}`, + `Path=${COOKIE_PATH}`, + `Max-Age=${KNOWN_DEVICE_MAX_AGE_S}`, + "HttpOnly", + "SameSite=Lax", + ...(SECURE_COOKIES ? ["Secure"] : []), + ].join("; "); +} + +/** + * True when a sign-in response starts a session: next-auth sets the session + * cookie (possibly in chunks) only after the password matched. + */ +export function startsSession(response: Response): boolean { + return response.headers.getSetCookie().some((header) => { + const pair = header.split(";", 1)[0]; + const eq = pair.indexOf("="); + if (eq < 0) return false; + const name = pair.slice(0, eq).trim(); + const value = pair.slice(eq + 1).trim(); + const isSession = name === SESSION_COOKIE_NAME || name.startsWith(`${SESSION_COOKIE_NAME}.`); + return isSession && value.length > 0; + }); +} + +/** The same response with the known-device cookie added. */ +export function withKnownDevice(response: Response, account: string): Response { + const cookie = knownDeviceCookie(account); + if (!cookie) return response; + const headers = new Headers(response.headers); + headers.append("Set-Cookie", cookie); + return new Response(response.body, { status: response.status, statusText: response.statusText, headers }); +} diff --git a/src/app/api/auth/_lib/limits.ts b/src/app/api/auth/_lib/limits.ts new file mode 100644 index 00000000..2b9d54b2 --- /dev/null +++ b/src/app/api/auth/_lib/limits.ts @@ -0,0 +1,152 @@ +import { createRateLimiter } from "@/lib/rate-limit"; + +/** + * Per-account limits for the auth routes. The per-IP limiters in + * src/lib/rate-limit.ts stop one network; these stop many networks (or a + * spoofed X-Forwarded-For) aimed at one account: password guessing against + * one email, or a flood of reset and verification emails to one inbox. + * Keys are the normalized email as typed, whether or not an account uses it, + * so a 429 here says nothing about which accounts exist. + */ + +// A development server sees every browser and test run as one client, so +// the limits there are loose enough not to lock the developer out. +const isProduction = process.env.NODE_ENV === "production"; + +const SIGN_IN_WINDOW_MS = 15 * 60 * 1000; + +export type FailureAttempt = { allowed: true; stamp: number } | { allowed: false; retryAfterMs: number }; + +/** + * A sliding-window counter of failed attempts per key. An attempt counts + * from the moment it starts, so a burst of parallel guesses can't all slip + * in before the first one fails; `forgive` takes it back when it turns out + * not to be a failure (right password, unverified email, bad CSRF token). + * Successful sign-ins therefore never use up the allowance. + */ +export function createFailureLimiter({ maxFailures, windowMs }: { maxFailures: number; windowMs: number }) { + const failures = new Map<string, number[]>(); + let lastSweep = 0; + + function recent(key: string, now: number): number[] { + const stamps = (failures.get(key) ?? []).filter((t) => t > now - windowMs); + if (stamps.length > 0) failures.set(key, stamps); + else failures.delete(key); + return stamps; + } + + // Keys are attacker-chosen, so drop the expired ones once per window. + function sweep(now: number): void { + if (now - lastSweep < windowMs) return; + lastSweep = now; + for (const key of [...failures.keys()]) recent(key, now); + } + + return { + start(key: string, now: number = Date.now()): FailureAttempt { + sweep(now); + const stamps = recent(key, now); + if (stamps.length >= maxFailures) { + return { allowed: false, retryAfterMs: Math.max(stamps[0] + windowMs - now, 0) }; + } + stamps.push(now); + failures.set(key, stamps); + return { allowed: true, stamp: now }; + }, + + forgive(key: string, stamp: number): void { + const stamps = failures.get(key); + if (!stamps) return; + const index = stamps.indexOf(stamp); + if (index >= 0) stamps.splice(index, 1); + if (stamps.length === 0) failures.delete(key); + }, + + /** Forget every failure for one key (the account's password just changed). */ + clear(key: string): void { + failures.delete(key); + }, + + /** Clear every key (tests). */ + reset(): void { + failures.clear(); + lastSweep = 0; + }, + }; +} + +/** + * Failed sign-ins per account, from any network: 30 per 15 minutes. Three + * times the per-IP cap, so guessing stays slow. Only wrong passwords count. + * A browser that has signed in to the account before skips this limit (see + * known-device.ts), so a stranger who trips it can't lock the student out of + * their own devices; a password reset clears it. + */ +export const signInFailureLimiter = createFailureLimiter({ + maxFailures: isProduction ? 30 : 300, + windowMs: SIGN_IN_WINDOW_MS, +}); + +/** Reset and verification emails per address: 5 per hour, from any network. */ +export const authEmailAddressLimiter = createRateLimiter("auth-email-address", { + maxRequests: isProduction ? 5 : 50, + windowMs: 60 * 60 * 1000, +}); + +/** Longest address RFC 5321 allows; longer input can't be an account. */ +const MAX_EMAIL_LENGTH = 254; + +/** The limiter key for an email: trimmed, lowercased, length-capped. */ +export function accountKey(email: string): string { + return email.trim().toLowerCase().slice(0, MAX_EMAIL_LENGTH); +} + +/** + * The email from a credentials sign-in POST, read the way next-auth reads + * it (form-encoded or JSON; the last `email` wins in a form body, as in + * next-auth's Object.fromEntries), without consuming the body next-auth + * reads next. Reading it any other way would let a request name one email + * for the limiter and another for the password check. + */ +export async function readSignInEmail(request: Request): Promise<string | null> { + const contentType = request.headers.get("content-type") ?? ""; + let email: unknown; + try { + if (contentType.includes("application/json")) { + const body: unknown = await request.clone().json(); + email = (body as { email?: unknown } | null)?.email; + } else if (contentType.includes("application/x-www-form-urlencoded")) { + email = Object.fromEntries(new URLSearchParams(await request.clone().text())).email; + } + } catch { + // An unreadable body has no email to limit; next-auth rejects it. + return null; + } + return typeof email === "string" ? accountKey(email) || null : null; +} + +/** next-auth's code for a wrong email or password. */ +export const CREDENTIALS_SIGNIN = "CredentialsSignin"; + +/** + * The `error` code a next-auth sign-in response carries, from its redirect + * (a form post) or its JSON `url` (json=true), or null when it has none. + */ +export async function signInErrorCode(response: Response): Promise<string | null> { + let target = response.headers.get("location"); + if (!target && (response.headers.get("content-type") ?? "").includes("application/json")) { + try { + const body: unknown = await response.clone().json(); + const url = (body as { url?: unknown } | null)?.url; + target = typeof url === "string" ? url : null; + } catch { + target = null; + } + } + if (!target) return null; + try { + return new URL(target, "http://localhost").searchParams.get("error"); + } catch { + return null; + } +} diff --git a/src/app/api/auth/_lib/responses.ts b/src/app/api/auth/_lib/responses.ts new file mode 100644 index 00000000..0e0f59e8 --- /dev/null +++ b/src/app/api/auth/_lib/responses.ts @@ -0,0 +1,113 @@ +import { NextResponse } from "next/server"; +import { z } from "zod"; + +import { + FIELD_MESSAGES, + NAME_MAX_LENGTH, + PASSWORD_MIN_LENGTH, + passwordTooLong, +} from "@/lib/auth-validation"; +import { EMAIL_NOT_CONFIGURED, tooManyRequestsText } from "@/lib/auth-messages"; +import { tooManyRequests } from "@/lib/rate-limit"; +import { logger } from "@/lib/logger"; + +/** + * Shared request schemas and error responses for the auth API routes. + * Field messages are the ones the forms show, so a rule reads the same + * whether the browser or the server catches it. + */ + +export const emailField = z + .string({ error: FIELD_MESSAGES.emailMissing }) + .trim() + .min(1, FIELD_MESSAGES.emailMissing) + .pipe(z.email({ error: FIELD_MESSAGES.emailInvalid })); + +/** + * A password being set (sign-up, reset). Past 72 bytes bcrypt ignores the + * rest, so a longer one is refused rather than silently cut. Sign-in keeps + * accepting any password, so an existing one always still works. + */ +export const newPasswordField = z + .string({ error: FIELD_MESSAGES.newPasswordMissing }) + .min(1, FIELD_MESSAGES.newPasswordMissing) + .min(PASSWORD_MIN_LENGTH, FIELD_MESSAGES.passwordShort) + .refine((password) => !passwordTooLong(password), FIELD_MESSAGES.passwordLong); + +export const nameField = z + .string({ error: FIELD_MESSAGES.nameMissing }) + .trim() + .min(1, FIELD_MESSAGES.nameMissing) + .max(NAME_MAX_LENGTH, FIELD_MESSAGES.nameLong); + +export interface FieldIssue { + field: string; + message: string; +} + +/** One issue per field, in schema order. */ +export function fieldIssues(error: z.ZodError): FieldIssue[] { + const seen = new Set<string>(); + const issues: FieldIssue[] = []; + for (const issue of error.issues) { + const head = issue.path[0]; + const field = typeof head === "string" ? head : "form"; + if (seen.has(field)) continue; + seen.add(field); + issues.push({ field, message: issue.message }); + } + return issues; +} + +/** 400 with `issues` the form maps onto its fields; `error` repeats the first one. */ +export function invalidFields(error: z.ZodError): NextResponse { + const issues = fieldIssues(error); + return NextResponse.json( + { error: issues[0]?.message ?? "Check the highlighted fields.", code: "INVALID_FIELDS", issues }, + { status: 400 }, + ); +} + +export function unreadableBody(): NextResponse { + return NextResponse.json( + { error: "This request couldn't be read. Reload the page and retry.", code: "INVALID_BODY" }, + { status: 400 }, + ); +} + +/** Parse a JSON body, or null when it isn't JSON. */ +export async function readJson(request: Request): Promise<unknown | null> { + try { + return await request.json(); + } catch { + return null; + } +} + +/** + * A 503 for a link that can't be emailed (see areEmailLinksAvailable). The same + * answer for every address, so it says nothing about which accounts exist. + */ +export function emailNotConfigured(message: string): NextResponse { + return NextResponse.json({ error: message, code: EMAIL_NOT_CONFIGURED }, { status: 503 }); +} + +/** A 429 whose message names the limited action and when to retry. */ +export function rateLimited(retryAfterMs: number, subject: string): NextResponse { + return tooManyRequests(retryAfterMs, tooManyRequestsText(subject, Math.ceil(retryAfterMs / 1000))); +} + +/** + * Developer hint for local runs with verification switched on: the console + * email provider prints the link in the server terminal. This goes to the + * log only, never to the page. + */ +export function logVerificationLinkHint(): void { + if (process.env.NODE_ENV === "production") return; + if (process.env.REQUIRE_EMAIL_VERIFICATION !== "true") return; + if ((process.env.EMAIL_PROVIDER || "console") !== "console") return; + logger.info("auth.verification_link_in_console", { + hint: + "REQUIRE_EMAIL_VERIFICATION is on and EMAIL_PROVIDER is console, so the verification link is printed in this terminal. Open it to verify the account.", + }); +} diff --git a/src/app/api/auth/forgot-password/route.ts b/src/app/api/auth/forgot-password/route.ts index 393a85ce..4552f16f 100644 --- a/src/app/api/auth/forgot-password/route.ts +++ b/src/app/api/auth/forgot-password/route.ts @@ -1,50 +1,77 @@ -import { NextRequest, NextResponse } from "next/server"; -import { z } from "zod/v4"; +import { after, NextRequest, NextResponse } from "next/server"; +import { z } from "zod"; import { prisma } from "@/lib/db"; import { createPasswordResetToken } from "@/lib/tokens"; import { emailProvider } from "@/lib/email/provider"; import { passwordReset } from "@/lib/email/templates"; -import { authLimiter, getClientIp, tooManyRequests } from "@/lib/rate-limit"; +import { authEmailLimiter, getClientIp } from "@/lib/rate-limit"; import { logger } from "@/lib/logger"; +import { getBaseUrl } from "@/lib/config"; +import { areEmailLinksAvailable } from "@/lib/email/delivery"; +import { EMAIL_NOT_CONFIGURED_MESSAGES } from "@/lib/auth-messages"; +import { + emailField, + emailNotConfigured, + invalidFields, + rateLimited, + readJson, + unreadableBody, +} from "../_lib/responses"; +import { accountKey, authEmailAddressLimiter } from "../_lib/limits"; const schema = z.object({ - email: z.string().email(), + email: emailField, }); +/** Create the token and send the email. Runs after the response is sent. */ +async function sendResetLink(user: { id: string; email: string; name: string | null }): Promise<void> { + try { + const token = await createPasswordResetToken(user.id); + const resetUrl = `${getBaseUrl()}/auth/reset-password?token=${token}`; + const { subject, html } = passwordReset(user.name || "there", resetUrl); + await emailProvider.send(user.email, subject, html); + logger.info("password_reset.sent", { userId: user.id }); + } catch (err) { + logger.error("password_reset.failed", { userId: user.id, error: String(err) }); + } +} + /** * POST /api/auth/forgot-password - * Sends a password reset email. Always returns 200 to prevent email enumeration. + * Sends a password reset email. Always returns 200 for a well-formed email, + * whether or not an account uses it, to prevent email enumeration. The + * token write and the email happen after the response, so the answer takes + * the same time either way. A production server that can't send email + * answers 503 EMAIL_NOT_CONFIGURED for every address instead of promising + * a link that never arrives. */ export async function POST(request: NextRequest) { - const rl = authLimiter.check(getClientIp(request)); - if (!rl.allowed) return tooManyRequests(rl.retryAfterMs); + // Production without SMTP: the link would go nowhere (see areEmailLinksAvailable). + if (!areEmailLinksAvailable()) return emailNotConfigured(EMAIL_NOT_CONFIGURED_MESSAGES.resetLink); - let body: z.infer<typeof schema>; - try { - body = schema.parse(await request.json()); - } catch { - return NextResponse.json({ error: "Invalid email" }, { status: 400 }); - } + const rl = authEmailLimiter.check(getClientIp(request)); + if (!rl.allowed) return rateLimited(rl.retryAfterMs, "Too many reset requests."); + + const body = await readJson(request); + if (body === null) return unreadableBody(); + const parsed = schema.safeParse(body); + if (!parsed.success) return invalidFields(parsed.error); + + const email = accountKey(parsed.data.email); + const perAddress = authEmailAddressLimiter.check(email); + if (!perAddress.allowed) return rateLimited(perAddress.retryAfterMs, "Too many reset requests."); - // Always return 200 regardless of whether the email exists — prevents enumeration + // The same answer whether or not the email exists, to prevent enumeration const genericResponse = NextResponse.json({ - message: "If an account with that email exists, we've sent a password reset link.", + message: "If an account uses that email, a password reset link is on its way.", }); try { const user = await prisma.user.findUnique({ - where: { email: body.email.toLowerCase().trim() }, + where: { email }, + select: { id: true, email: true, name: true }, }); - - if (!user) return genericResponse; - - const token = await createPasswordResetToken(user.id); - const appUrl = process.env.NEXT_PUBLIC_APP_URL || "http://localhost:3000"; - const resetUrl = `${appUrl}/auth/reset-password?token=${token}`; - const { subject, html } = passwordReset(user.name || "there", resetUrl); - - await emailProvider.send(user.email, subject, html); - logger.info("password_reset.sent", { userId: user.id }); + if (user) after(() => sendResetLink(user)); } catch (err) { logger.error("password_reset.failed", { error: String(err) }); } diff --git a/src/app/api/auth/resend-verification/route.ts b/src/app/api/auth/resend-verification/route.ts index 6c414cff..ccb66387 100644 --- a/src/app/api/auth/resend-verification/route.ts +++ b/src/app/api/auth/resend-verification/route.ts @@ -1,44 +1,78 @@ -import { NextResponse } from "next/server"; +import { after, NextResponse } from "next/server"; +import { z } from "zod"; import { prisma } from "@/lib/db"; -import { authLimiter, getClientIp, tooManyRequests } from "@/lib/rate-limit"; +import { authEmailLimiter, getClientIp } from "@/lib/rate-limit"; import { createEmailVerificationToken } from "@/lib/tokens"; import { emailProvider } from "@/lib/email/provider"; import { emailVerification } from "@/lib/email/templates"; import { logger } from "@/lib/logger"; +import { getBaseUrl } from "@/lib/config"; +import { areEmailLinksAvailable } from "@/lib/email/delivery"; +import { EMAIL_NOT_CONFIGURED_MESSAGES } from "@/lib/auth-messages"; +import { + emailField, + emailNotConfigured, + invalidFields, + logVerificationLinkHint, + rateLimited, + readJson, + unreadableBody, +} from "../_lib/responses"; +import { accountKey, authEmailAddressLimiter } from "../_lib/limits"; + +const schema = z.object({ + email: emailField, +}); + +const GENERIC_MESSAGE = "If that email has an account waiting for verification, a new link is on its way."; + +/** Create the token and send the email. Runs after the response is sent. */ +async function sendVerificationLink(user: { id: string; email: string; name: string | null }): Promise<void> { + try { + const token = await createEmailVerificationToken(user.id); + const verifyUrl = `${getBaseUrl()}/api/auth/verify-email?token=${token}`; + const { subject, html } = emailVerification(user.name || "there", verifyUrl); + await emailProvider.send(user.email, subject, html); + logger.info("resend_verification.sent", { userId: user.id }); + logVerificationLinkHint(); + } catch (err) { + logger.error("resend_verification.failed", { userId: user.id, error: String(err) }); + } +} /** * POST /api/auth/resend-verification - * Resends the email verification link. Always returns 200 to prevent enumeration. + * Resends the email verification link. Always returns 200 for a well-formed + * email, whether or not an account needs it, to prevent enumeration. The + * token write and the email happen after the response, so the answer takes + * the same time either way. A production server that can't send email + * answers 503 EMAIL_NOT_CONFIGURED for every address. */ export async function POST(request: Request) { - const rl = authLimiter.check(getClientIp(request as any)); - if (!rl.allowed) return tooManyRequests(rl.retryAfterMs); + // Production without SMTP: the link would go nowhere (see areEmailLinksAvailable). + if (!areEmailLinksAvailable()) return emailNotConfigured(EMAIL_NOT_CONFIGURED_MESSAGES.verificationLink); - try { - const { email } = await request.json(); - if (!email || typeof email !== "string") { - return NextResponse.json({ message: "If that email exists, we've sent a new link." }); - } + const rl = authEmailLimiter.check(getClientIp(request)); + if (!rl.allowed) return rateLimited(rl.retryAfterMs, "Too many link requests."); - const user = await prisma.user.findUnique({ - where: { email: email.toLowerCase().trim() }, - }); + const body = await readJson(request); + if (body === null) return unreadableBody(); + const parsed = schema.safeParse(body); + if (!parsed.success) return invalidFields(parsed.error); - // Always return success to prevent enumeration - if (!user || user.emailVerified) { - return NextResponse.json({ message: "If that email exists, we've sent a new link." }); - } + const email = accountKey(parsed.data.email); + const perAddress = authEmailAddressLimiter.check(email); + if (!perAddress.allowed) return rateLimited(perAddress.retryAfterMs, "Too many link requests."); - const token = await createEmailVerificationToken(user.id); - const appUrl = process.env.NEXT_PUBLIC_APP_URL || "http://localhost:3000"; - const verifyUrl = `${appUrl}/api/auth/verify-email?token=${token}`; - const { subject, html } = emailVerification(user.name || "there", verifyUrl); - await emailProvider.send(user.email, subject, html); - logger.info("resend_verification.sent", { userId: user.id }); - - return NextResponse.json({ message: "If that email exists, we've sent a new link." }); + try { + const user = await prisma.user.findUnique({ + where: { email }, + select: { id: true, email: true, name: true, emailVerified: true }, + }); + if (user && !user.emailVerified) after(() => sendVerificationLink(user)); } catch (err) { logger.error("resend_verification.failed", { error: String(err) }); - return NextResponse.json({ message: "If that email exists, we've sent a new link." }); } + + return NextResponse.json({ message: GENERIC_MESSAGE }); } diff --git a/src/app/api/auth/reset-password/route.ts b/src/app/api/auth/reset-password/route.ts index bc80352d..4a5880b3 100644 --- a/src/app/api/auth/reset-password/route.ts +++ b/src/app/api/auth/reset-password/route.ts @@ -1,49 +1,97 @@ import { NextRequest, NextResponse } from "next/server"; -import { z } from "zod/v4"; -import bcrypt from "bcryptjs"; +import { z } from "zod"; import { prisma } from "@/lib/db"; -import { consumeToken } from "@/lib/tokens"; -import { authLimiter, getClientIp, tooManyRequests } from "@/lib/rate-limit"; +import { forgetSessionCheck, hashPassword } from "@/lib/auth-options"; +import { inspectToken, redeemToken, type TokenState } from "@/lib/tokens"; +import { authTokenLimiter, getClientIp } from "@/lib/rate-limit"; import { logger } from "@/lib/logger"; +import { REQUEST_FAILED } from "@/lib/auth-messages"; +import { invalidFields, newPasswordField, rateLimited, readJson, unreadableBody } from "../_lib/responses"; +import { accountKey, signInFailureLimiter } from "../_lib/limits"; const schema = z.object({ - token: z.string().min(1), - password: z.string().min(8, "Password must be at least 8 characters"), + token: z.string().catch(""), + password: newPasswordField, }); +type LinkProblem = Exclude<TokenState["status"], "valid">; + +/** Why a reset link didn't work, as a code the reset form turns into its own screen. */ +const TOKEN_ERRORS: Record<LinkProblem, { code: string; error: string }> = { + expired: { + code: "TOKEN_EXPIRED", + error: "This reset link expired. Request a new link to reset your password.", + }, + used: { + code: "TOKEN_USED", + error: "This reset link was already used. Request a new link to reset your password.", + }, + invalid: { + code: "TOKEN_INVALID", + error: "This reset link doesn't work. Request a new link to reset your password.", + }, +}; + +function linkError(problem: LinkProblem): NextResponse { + return NextResponse.json(TOKEN_ERRORS[problem], { status: 400 }); +} + /** * POST /api/auth/reset-password - * Resets the user's password using a valid reset token. + * Sets a new password with a reset token from the email link. + * + * 400 bodies carry either `issues` (the password field) or a `code` of + * TOKEN_EXPIRED, TOKEN_USED or TOKEN_INVALID. The link is used up only + * when the new password is saved: a failure answers 500 and the same link + * still works for a retry. */ export async function POST(request: NextRequest) { - const rl = authLimiter.check(getClientIp(request)); - if (!rl.allowed) return tooManyRequests(rl.retryAfterMs); + const rl = authTokenLimiter.check(getClientIp(request)); + if (!rl.allowed) return rateLimited(rl.retryAfterMs, "Too many attempts."); + + const body = await readJson(request); + if (body === null) return unreadableBody(); + const parsed = schema.safeParse(body); + if (!parsed.success) return invalidFields(parsed.error); + const { token, password } = parsed.data; - let body: z.infer<typeof schema>; try { - body = schema.parse(await request.json()); - } catch (err) { - if (err instanceof z.ZodError) { - return NextResponse.json({ error: err.issues[0].message }, { status: 400 }); - } - return NextResponse.json({ error: "Invalid request" }, { status: 400 }); - } + // A read first, so a bad link costs no bcrypt work. + const checked = await inspectToken(token, "PASSWORD_RESET"); + if (checked.status !== "valid") return linkError(checked.status); - const userId = await consumeToken(body.token, "PASSWORD_RESET"); - if (!userId) { - return NextResponse.json( - { error: "Invalid or expired reset link. Please request a new one." }, - { status: 400 }, - ); - } + // Hash outside the transaction: bcrypt takes a moment, and a + // transaction shouldn't hold a connection while it runs. + const passwordHash = await hashPassword(password); - const passwordHash = await bcrypt.hash(body.password, 12); - await prisma.user.update({ - where: { id: userId }, - data: { passwordHash }, - }); + // Claiming the link and saving the password commit together. If the + // save fails, the claim rolls back and the link still works. + const outcome = await prisma.$transaction(async (tx) => { + const state = await redeemToken(token, "PASSWORD_RESET", tx); + if (state.status !== "valid") return { state, email: null }; + const user = await tx.user.update({ + where: { id: state.userId }, + data: { passwordHash }, + select: { email: true }, + }); + return { state, email: user.email }; + }); + // Another request used the link between the check and the claim. + if (outcome.state.status !== "valid") return linkError(outcome.state.status); + const { userId } = outcome.state; - logger.info("password_reset.completed", { userId }); + // A new hash changes the session fingerprint (see auth-options), which + // ends every session signed in with the old password, from its next + // request on. + forgetSessionCheck(userId); + // Wrong passwords typed by someone else stop counting, so the student + // can sign in with the new one at once. + if (outcome.email) signInFailureLimiter.clear(accountKey(outcome.email)); - return NextResponse.json({ message: "Password reset successfully. You can now sign in." }); + logger.info("password_reset.completed", { userId }); + return NextResponse.json({ message: "Password updated. Sign in with your new password." }); + } catch (err) { + logger.error("password_reset.update_failed", { error: String(err) }); + return NextResponse.json({ error: REQUEST_FAILED.resetPassword }, { status: 500 }); + } } diff --git a/src/app/api/auth/signup/route.ts b/src/app/api/auth/signup/route.ts index 257f9f68..880fe432 100644 --- a/src/app/api/auth/signup/route.ts +++ b/src/app/api/auth/signup/route.ts @@ -1,38 +1,76 @@ -import { NextResponse } from "next/server"; -import bcrypt from "bcryptjs"; -import { prisma } from "@/lib/db"; +import { after, NextResponse } from "next/server"; import { z } from "zod"; -import { signupLimiter, getClientIp, tooManyRequests } from "@/lib/rate-limit"; +import { prisma } from "@/lib/db"; +import { hashPassword, isEmailVerificationRequired } from "@/lib/auth-options"; +import { signupLimiter, getClientIp } from "@/lib/rate-limit"; import { createEmailVerificationToken } from "@/lib/tokens"; import { emailProvider } from "@/lib/email/provider"; import { emailVerification } from "@/lib/email/templates"; import { logger } from "@/lib/logger"; +import { getBaseUrl } from "@/lib/config"; +import { REQUEST_FAILED } from "@/lib/auth-messages"; +import { + emailField, + invalidFields, + logVerificationLinkHint, + nameField, + newPasswordField, + rateLimited, + readJson, + unreadableBody, +} from "../_lib/responses"; const signupSchema = z.object({ - email: z.string().email("Invalid email address"), - password: z.string().min(8, "Password must be at least 8 characters"), - name: z.string().min(1, "Name is required").max(50), + name: nameField, + email: emailField, + password: newPasswordField, }); +/** Create the token and send the email. Runs after the response is sent. */ +async function sendVerificationLink(user: { id: string; email: string; name: string | null }): Promise<void> { + try { + const token = await createEmailVerificationToken(user.id); + const verifyUrl = `${getBaseUrl()}/api/auth/verify-email?token=${token}`; + const { subject, html } = emailVerification(user.name || "there", verifyUrl); + await emailProvider.send(user.email, subject, html); + logger.info("signup.verification_email_sent", { userId: user.id }); + logVerificationLinkHint(); + } catch (emailErr) { + // A mail failure never breaks signup; the sign-in form offers a new link. + logger.error("signup.verification_email_failed", { + userId: user.id, + error: String(emailErr), + }); + } +} + /** * POST /api/auth/signup * * Always returns the same shaped response whether the email is new or taken, - * to prevent email enumeration. A verification email is sent if the account - * is newly created. + * to prevent email enumeration. When sign-in requires a verified email, a + * new account gets a verification email after the response, so its token + * write and send don't make a new email answer slower than a taken one. + * Without that requirement the form signs the new account straight in, and + * no email is sent (the sign-in form offers a link if the setting changes). + * + * 400 bodies carry `issues: [{ field, message }]` for the form's fields. */ export async function POST(request: Request) { - const rl = signupLimiter.check(getClientIp(request as any)); - if (!rl.allowed) return tooManyRequests(rl.retryAfterMs); + const rl = signupLimiter.check(getClientIp(request)); + if (!rl.allowed) return rateLimited(rl.retryAfterMs, "Too many new accounts from this network."); - try { - const body = await request.json(); - const { email, password, name } = signupSchema.parse(body); + const body = await readJson(request); + if (body === null) return unreadableBody(); + const parsed = signupSchema.safeParse(body); + if (!parsed.success) return invalidFields(parsed.error); + const { email, password, name } = parsed.data; - const normalizedEmail = email.toLowerCase().trim(); - const passwordHash = await bcrypt.hash(password, 12); + try { + const normalizedEmail = email.toLowerCase(); + const passwordHash = await hashPassword(password); - // Generic response — same whether account is new or already exists + // Generic response, the same whether the account is new or already exists const genericResponse = NextResponse.json( { message: "Check your email to verify your account." }, { status: 201 }, @@ -58,24 +96,11 @@ export async function POST(request: Request) { return u; }); - // Send verification email (non-blocking — don't let email failures break signup) - try { - const token = await createEmailVerificationToken(user.id); - const appUrl = process.env.NEXT_PUBLIC_APP_URL || "http://localhost:3000"; - const verifyUrl = `${appUrl}/api/auth/verify-email?token=${token}`; - const { subject, html } = emailVerification(user.name || "there", verifyUrl); - await emailProvider.send(user.email, subject, html); - logger.info("signup.verification_email_sent", { userId: user.id }); - } catch (emailErr) { - logger.error("signup.verification_email_failed", { - userId: user.id, - error: String(emailErr), - }); - } + if (isEmailVerificationRequired()) after(() => sendVerificationLink(user)); return genericResponse; } catch (err: unknown) { - // Unique constraint violation (P2002) — email already taken. + // Unique constraint violation (P2002): the email is already taken. // Return the same generic response to prevent email enumeration. if ( typeof err === "object" && @@ -88,16 +113,7 @@ export async function POST(request: Request) { throw err; } } catch (err) { - if (err instanceof z.ZodError) { - return NextResponse.json( - { error: err.issues[0].message }, - { status: 400 }, - ); - } logger.error("signup.failed", { error: String(err) }); - return NextResponse.json( - { error: "Failed to create account" }, - { status: 500 }, - ); + return NextResponse.json({ error: REQUEST_FAILED.signup }, { status: 500 }); } } diff --git a/src/app/api/auth/verify-email/route.ts b/src/app/api/auth/verify-email/route.ts index 41ca53fd..4131a222 100644 --- a/src/app/api/auth/verify-email/route.ts +++ b/src/app/api/auth/verify-email/route.ts @@ -1,38 +1,60 @@ import { NextRequest, NextResponse } from "next/server"; -import { consumeToken } from "@/lib/tokens"; +import { redeemToken } from "@/lib/tokens"; import { prisma } from "@/lib/db"; import { logger } from "@/lib/logger"; -import { authLimiter, getClientIp, tooManyRequests } from "@/lib/rate-limit"; +import { authTokenLimiter, getClientIp } from "@/lib/rate-limit"; + +/** Where a verification link lands. The page explains each status in plain words. */ +type VerifyLinkStatus = "expired" | "invalid" | "busy" | "failed"; + +function landOn(request: NextRequest, path: string): NextResponse { + // 303 so a browser always follows with a GET to the page. + return NextResponse.redirect(new URL(path, request.url), 303); +} + +function landOnStatus(request: NextRequest, status: VerifyLinkStatus): NextResponse { + return landOn(request, `/auth/verify-email?status=${status}`); +} /** * GET /api/auth/verify-email?token=xxx - * Verifies the user's email address. + * The link in the verification email. It always ends on a page, never on + * raw JSON: sign-in with a "verified" banner on success, or the + * verify-email page with a status explaining what went wrong. */ export async function GET(request: NextRequest) { - const rl = authLimiter.check(getClientIp(request)); - if (!rl.allowed) return tooManyRequests(rl.retryAfterMs); + const rl = authTokenLimiter.check(getClientIp(request)); + if (!rl.allowed) return landOnStatus(request, "busy"); const token = request.nextUrl.searchParams.get("token"); - if (!token) { - return NextResponse.json({ error: "Missing token" }, { status: 400 }); - } + if (!token) return landOnStatus(request, "invalid"); - const userId = await consumeToken(token, "EMAIL_VERIFY"); - if (!userId) { - return NextResponse.json( - { error: "Invalid or expired verification link" }, - { status: 400 }, - ); - } + try { + const state = await redeemToken(token, "EMAIL_VERIFY"); - await prisma.user.update({ - where: { id: userId }, - data: { emailVerified: new Date() }, - }); + if (state.status === "valid") { + await prisma.user.update({ + where: { id: state.userId }, + data: { emailVerified: new Date() }, + }); + logger.info("email.verified", { userId: state.userId }); + return landOn(request, "/auth/signin?verified=true"); + } - logger.info("email.verified", { userId }); + if (state.status === "used") { + // Opened twice, or replaced by a newer link. If the account is already + // verified there's nothing left to do but sign in. + const user = await prisma.user.findUnique({ + where: { id: state.userId }, + select: { emailVerified: true }, + }); + if (user?.emailVerified) return landOn(request, "/auth/signin?verified=true"); + return landOnStatus(request, "invalid"); + } - // Redirect to sign-in with a success message - const url = new URL("/auth/signin?verified=true", request.url); - return NextResponse.redirect(url); + return landOnStatus(request, state.status); + } catch (err) { + logger.error("email.verify_failed", { error: String(err) }); + return landOnStatus(request, "failed"); + } } diff --git a/src/app/api/chat/_lib/messages.ts b/src/app/api/chat/_lib/messages.ts new file mode 100644 index 00000000..13afc832 --- /dev/null +++ b/src/app/api/chat/_lib/messages.ts @@ -0,0 +1,82 @@ +import { prisma } from "@/lib/db"; +import { + isLegacyNoMatch, + noticeText, + storedCitations, + storedNotice, + toSources, + type ChatSource, +} from "./sources"; + +export const MESSAGE_SELECT = { id: true, role: true, content: true, citations: true, createdAt: true } as const; + +export type MessageRow = { + id: string; + role: string; + content: string; + citations: unknown; + createdAt: Date; +}; + +export interface ChatMessageDto { + id: string; + role: "user" | "assistant"; + /** question: the student's; answer: AI-written; notice: the app's own line (no AI text). */ + kind: "question" | "answer" | "notice"; + content: string; + /** Numbered sources: inline [n] in `content` refers to sources[n - 1]. */ + sources: ChatSource[]; + /** The stored citations JSON, unchanged. */ + citations: unknown; + createdAt: string; +} + +export function courseNameOf(courseKey: string): string { + const i = courseKey.indexOf("||"); + return i === -1 ? courseKey : courseKey.slice(0, i); +} + +/** Shapes stored rows for the client: kind, numbered sources with file titles and pages. */ +export async function toMessageDtos(userId: string, courseKey: string, rows: MessageRow[]): Promise<ChatMessageDto[]> { + const chunkIds = new Set<string>(); + for (const row of rows) { + if (row.role === "assistant") for (const c of storedCitations(row.citations)) chunkIds.add(c.chunk_id); + } + + const chunks = new Map<string, { title: string; page: number | null }>(); + if (chunkIds.size > 0) { + const found = await prisma.contentChunk.findMany({ + where: { id: { in: [...chunkIds] }, document: { userId } }, + select: { id: true, pageNumber: true, document: { select: { title: true } } }, + }); + for (const c of found) chunks.set(c.id, { title: c.document.title, page: c.pageNumber }); + } + + const courseName = courseNameOf(courseKey); + return rows.map((row) => { + const role = row.role === "assistant" ? "assistant" : "user"; + const notice = role === "assistant" ? storedNotice(row.citations) : null; + const legacyNotice = role === "assistant" && !notice && isLegacyNoMatch(row.content); + if (notice || legacyNotice) { + return { + id: row.id, + role, + kind: "notice", + content: noticeText(notice ?? "no_match", courseName), + sources: [], + citations: row.citations, + createdAt: row.createdAt.toISOString(), + }; + } + return { + id: row.id, + role, + kind: role === "assistant" ? "answer" : "question", + content: row.content, + sources: role === "assistant" ? toSources(storedCitations(row.citations), chunks) : [], + citations: row.citations, + createdAt: row.createdAt.toISOString(), + }; + }); +} + diff --git a/src/app/api/chat/_lib/sources.ts b/src/app/api/chat/_lib/sources.ts new file mode 100644 index 00000000..4a9fc04a --- /dev/null +++ b/src/app/api/chat/_lib/sources.ts @@ -0,0 +1,231 @@ +/** + * Numbered sources for chat answers. + * + * The answer prompt lists the retrieved excerpts as [1]..[k] and asks the + * model to cite chunk ids. Models write inline markers like "[2]" against + * that excerpt numbering (sometimes against their own citation list), and + * their citation list comes in any order. normalizeAnswer() turns both into + * one convention that every stored message follows, old ones included: + * inline [n] refers to citations[n - 1], numbered in order of first mention. + */ + +/** A citation as stored on an assistant ChatMessage (JSON). Older rows lack the title and page. */ +export interface StoredCitation { + chunk_id: string; + reason?: string; + quote_snippet: string; + doc_title?: string | null; + page_number?: number | null; +} + +/** An assistant message with no AI text: the honesty line when retrieval finds nothing. */ +export interface StoredNotice { + notice: "no_match" | "processing" | "no_materials"; +} + +/** One numbered source as the client renders it. */ +export interface ChatSource { + n: number; + chunk_id: string; + /** File title, or null when the file was deleted. */ + title: string | null; + page: number | null; + quote: string; + /** The file was deleted from the materials after the answer. */ + missing: boolean; +} + +export interface RetrievedExcerpt { + chunk_id: string; + doc_title: string; + page_number: number | null; + snippet: string; +} + +export interface ModelCitation { + chunk_id: string; + reason?: string; + quote_snippet?: string; +} + +const MARKER = /\[(\d{1,3}(?:\s*,\s*\d{1,3})*)\](?![(:])/g; +const QUOTE_MAX = 280; + +/** Splits markdown into prose and code (fenced blocks and inline spans), so markers in code stay put. */ +function splitCode(markdown: string): { text: string; code: boolean }[] { + const parts: { text: string; code: boolean }[] = []; + const pattern = /(```[\s\S]*?(?:```|$)|~~~[\s\S]*?(?:~~~|$)|`[^`\n]+`)/g; + let last = 0; + for (const match of markdown.matchAll(pattern)) { + const index = match.index ?? 0; + if (index > last) parts.push({ text: markdown.slice(last, index), code: false }); + parts.push({ text: match[0], code: true }); + last = index + match[0].length; + } + if (last < markdown.length) parts.push({ text: markdown.slice(last), code: false }); + return parts; +} + +/** Numbers in inline markers, in order of appearance, outside code. */ +export function inlineMarkerNumbers(markdown: string): number[] { + const numbers: number[] = []; + for (const part of splitCode(markdown)) { + if (part.code) continue; + for (const match of part.text.matchAll(MARKER)) { + for (const n of match[1].split(",")) numbers.push(Number(n.trim())); + } + } + return numbers; +} + +function rewriteMarkers(markdown: string, map: (n: number) => number | null): string { + return splitCode(markdown) + .map((part) => + part.code + ? part.text + : part.text.replace(/(\s?)\[(\d{1,3}(?:\s*,\s*\d{1,3})*)\](?![(:])/g, (_whole, space: string, list: string) => { + const mapped = list + .split(",") + .map((n) => map(Number(n.trim()))) + .filter((n): n is number => n !== null); + const unique = [...new Set(mapped)]; + return unique.length > 0 ? `${space}${unique.map((n) => `[${n}]`).join("")}` : ""; + }), + ) + .join(""); +} + +function squash(text: string): string { + return text.replace(/\s+/g, " ").trim(); +} + +/** + * The quote shown under a source. The model's quote is kept only when it + * really appears in the excerpt; otherwise the excerpt's opening is used, + * so a source never shows words the file doesn't contain. + */ +export function verifiedQuote(modelQuote: string | undefined, excerpt: string): string { + const source = squash(excerpt.replace(/<<|>>/g, "")); + const quote = modelQuote ? squash(modelQuote).replace(/^["“]|["”]$/g, "").replace(/\.{3}$|…$/, "") : ""; + if (quote.length >= 12 && source.toLowerCase().includes(quote.toLowerCase())) { + return quote.length > QUOTE_MAX ? `${quote.slice(0, QUOTE_MAX).trimEnd()}…` : quote; + } + if (source.length <= QUOTE_MAX) return source; + const cut = source.slice(0, QUOTE_MAX); + const sentenceEnd = cut.lastIndexOf(". "); + return sentenceEnd > 80 ? cut.slice(0, sentenceEnd + 1) : `${cut.trimEnd()}…`; +} + +/** + * Renumbers an answer's sources. Returns the markdown with inline markers + * pointing at the returned citations (1-based, order of first mention, then + * cited-but-unmentioned excerpts), and drops markers and citations that + * match no retrieved excerpt. + */ +export function normalizeAnswer( + markdown: string, + modelCitations: ModelCitation[] | undefined, + retrieved: RetrievedExcerpt[], +): { markdown: string; citations: StoredCitation[] } { + const indexById = new Map(retrieved.map((r, i) => [r.chunk_id, i + 1])); + const cited = (modelCitations ?? []).filter( + (c): c is ModelCitation => Boolean(c) && typeof c.chunk_id === "string" && indexById.has(c.chunk_id), + ); + const citedIndexes = cited.map((c) => indexById.get(c.chunk_id)!); + const citedSet = new Set(citedIndexes); + const markers = inlineMarkerNumbers(markdown); + + // Which numbering did the model use for inline markers? Excerpt numbers + // ([1]..[k] in the prompt) unless they point outside the cited excerpts + // while the model's own citation order explains every marker. + const inExcerptRange = (n: number) => n >= 1 && n <= retrieved.length; + const excerptFits = markers.every((n) => inExcerptRange(n) && (citedSet.size === 0 || citedSet.has(n))); + const ownOrderFits = + !excerptFits && cited.length > 0 && markers.length > 0 && markers.every((n) => n >= 1 && n <= cited.length); + const toExcerpt = (n: number): number | null => { + if (ownOrderFits) return n >= 1 && n <= cited.length ? citedIndexes[n - 1] : null; + return inExcerptRange(n) ? n : null; + }; + + const order: number[] = []; + for (const n of markers) { + const excerpt = toExcerpt(n); + if (excerpt !== null && !order.includes(excerpt)) order.push(excerpt); + } + for (const excerpt of citedIndexes) if (!order.includes(excerpt)) order.push(excerpt); + + const displayNumber = new Map(order.map((excerpt, i) => [excerpt, i + 1])); + const rewritten = rewriteMarkers(markdown, (n) => { + const excerpt = toExcerpt(n); + return excerpt === null ? null : (displayNumber.get(excerpt) ?? null); + }); + + const citations = order.map((excerpt) => { + const r = retrieved[excerpt - 1]; + const model = cited.find((c) => c.chunk_id === r.chunk_id); + return { + chunk_id: r.chunk_id, + reason: model?.reason, + quote_snippet: verifiedQuote(model?.quote_snippet, r.snippet), + doc_title: r.doc_title, + page_number: r.page_number, + }; + }); + + return { markdown: rewritten, citations }; +} + +function isStoredCitation(value: unknown): value is StoredCitation { + return ( + typeof value === "object" && + value !== null && + typeof (value as StoredCitation).chunk_id === "string" + ); +} + +/** Stored citations JSON as an array (anything else is empty). */ +export function storedCitations(value: unknown): StoredCitation[] { + return Array.isArray(value) ? value.filter(isStoredCitation) : []; +} + +/** The notice kind when the stored JSON marks a no-AI message. */ +export function storedNotice(value: unknown): StoredNotice["notice"] | null { + if (typeof value !== "object" || value === null || Array.isArray(value)) return null; + const notice = (value as Partial<StoredNotice>).notice; + return notice === "no_match" || notice === "processing" || notice === "no_materials" ? notice : null; +} + +/** The sentence for each notice, about the course in `courseName`. */ +export function noticeText(notice: StoredNotice["notice"], courseName: string): string { + switch (notice) { + case "processing": + return `Your ${courseName} materials are still processing. Ask again when they're ready.`; + case "no_materials": + return `You haven't uploaded ${courseName} materials yet. Upload them, then ask again.`; + default: + return `Your ${courseName} materials don't cover this. Upload the file that does, or ask it a different way.`; + } +} + +/** Answers older builds stored when nothing matched, written in the first person. */ +export function isLegacyNoMatch(content: string): boolean { + return content.startsWith("I couldn't find any relevant materials in your course documents"); +} + +/** Builds the numbered sources for stored citations, with file titles and pages looked up by chunk. */ +export function toSources( + citations: StoredCitation[], + chunks: Map<string, { title: string; page: number | null }>, +): ChatSource[] { + return citations.map((c, i) => { + const chunk = chunks.get(c.chunk_id); + return { + n: i + 1, + chunk_id: c.chunk_id, + title: chunk?.title ?? c.doc_title ?? null, + page: chunk ? chunk.page : (c.page_number ?? null), + quote: c.quote_snippet ?? "", + missing: !chunk, + }; + }); +} diff --git a/src/app/api/chat/messages/route.ts b/src/app/api/chat/messages/route.ts index 09397ebc..6a969118 100644 --- a/src/app/api/chat/messages/route.ts +++ b/src/app/api/chat/messages/route.ts @@ -1,40 +1,75 @@ import { NextRequest, NextResponse } from "next/server"; -import { z } from "zod/v4"; +import { z } from "zod"; import { getUserId } from "@/lib/auth"; import { prisma } from "@/lib/db"; import { logger } from "@/lib/logger"; -import { chatLimiter, tooManyRequests } from "@/lib/rate-limit"; +import { chatLimiter } from "@/lib/rate-limit"; +import { failed, invalidInput, invalidJson, rateLimited, unauthorized } from "../../flashcards/_lib/http"; +import { MESSAGE_SELECT, toMessageDtos } from "../_lib/messages"; + +const listSchema = z.object({ + courseKey: z.string().min(1).max(200), + limit: z.coerce.number().int().min(1).max(100).default(50), + before: z.string().min(1).max(100).optional(), +}); /** - * GET /api/chat/messages?courseKey=CourseName||ExamName - * Returns messages for the authenticated user + course, ordered by createdAt, limit 100. + * GET /api/chat/messages?courseKey=Course||Exam&limit=50&before=<messageId> + * The newest `limit` messages (older than `before` when given), returned + * oldest first, with `has_more` and the course's total message count. */ export async function GET(request: NextRequest) { const userId = await getUserId(request); - if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); - } + if (!userId) return unauthorized(); const rl = chatLimiter.check(userId); - if (!rl.allowed) return tooManyRequests(rl.retryAfterMs); + if (!rl.allowed) return rateLimited(rl.retryAfterMs); - const courseKey = request.nextUrl.searchParams.get("courseKey"); - if (!courseKey) { - return NextResponse.json({ error: "courseKey query parameter is required" }, { status: 400 }); - } + const sp = request.nextUrl.searchParams; + const parsed = listSchema.safeParse({ + courseKey: sp.get("courseKey") ?? undefined, + limit: sp.get("limit") ?? undefined, + before: sp.get("before") ?? undefined, + }); + if (!parsed.success) return invalidInput(parsed.error, "Choose a course to see its chat."); + const { courseKey, limit, before } = parsed.data; try { - const messages = await prisma.chatMessage.findMany({ - where: { userId, courseKey }, - orderBy: { createdAt: "asc" }, - take: 100, - select: { id: true, role: true, content: true, citations: true, createdAt: true }, - }); - - return NextResponse.json({ messages }); + let cursor: Record<string, unknown> = {}; + if (before) { + const anchor = await prisma.chatMessage.findFirst({ + where: { id: before, userId, courseKey }, + select: { id: true, createdAt: true }, + }); + if (!anchor) { + return failed("Those messages aren't in this chat anymore. Reload to see the latest.", 404, "CURSOR_NOT_FOUND"); + } + cursor = { + OR: [ + { createdAt: { lt: anchor.createdAt } }, + { createdAt: anchor.createdAt, id: { lt: anchor.id } }, + ], + }; + } + + const [rows, total] = await Promise.all([ + prisma.chatMessage.findMany({ + where: { userId, courseKey, ...cursor }, + orderBy: [{ createdAt: "desc" }, { id: "desc" }], + take: limit + 1, + select: MESSAGE_SELECT, + }), + prisma.chatMessage.count({ where: { userId, courseKey } }), + ]); + + const hasMore = rows.length > limit; + const page = rows.slice(0, limit).reverse(); + const messages = await toMessageDtos(userId, courseKey, page); + + return NextResponse.json({ messages, has_more: hasMore, total }); } catch (err) { logger.error("chat.messages.get_failed", { userId, courseKey, error: String(err) }); - return NextResponse.json({ error: "Internal server error" }, { status: 500 }); + return failed("Chat history didn't load. Retry."); } } @@ -47,31 +82,25 @@ const postSchema = z.object({ /** * POST /api/chat/messages - * Saves a chat message and returns the created record. + * Saves a chat message and returns the created record. (The chat screen + * saves through /api/assistant/answer with save: true instead.) */ export async function POST(request: NextRequest) { const userId = await getUserId(request); - if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); - } + if (!userId) return unauthorized(); const rl = chatLimiter.check(userId); - if (!rl.allowed) return tooManyRequests(rl.retryAfterMs); + if (!rl.allowed) return rateLimited(rl.retryAfterMs); let body: unknown; try { body = await request.json(); } catch { - return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 }); + return invalidJson(); } const parsed = postSchema.safeParse(body); - if (!parsed.success) { - return NextResponse.json( - { error: "Validation failed", issues: parsed.error.issues }, - { status: 400 }, - ); - } + if (!parsed.success) return invalidInput(parsed.error); const { courseKey, role, content, citations } = parsed.data; @@ -84,31 +113,27 @@ export async function POST(request: NextRequest) { content, citations: citations ?? undefined, }, - select: { id: true, role: true, content: true, citations: true, createdAt: true }, + select: MESSAGE_SELECT, }); logger.info("chat.message.created", { userId, courseKey, role, messageId: message.id }); return NextResponse.json({ message }, { status: 201 }); } catch (err) { logger.error("chat.message.create_failed", { userId, courseKey, error: String(err) }); - return NextResponse.json({ error: "Internal server error" }, { status: 500 }); + return failed("Message not saved. Retry."); } } /** * DELETE /api/chat/messages?courseKey=CourseName||ExamName - * Deletes all messages for the authenticated user + course (clear chat). + * Deletes all messages for the authenticated user + course. */ export async function DELETE(request: NextRequest) { const userId = await getUserId(request); - if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); - } + if (!userId) return unauthorized(); const courseKey = request.nextUrl.searchParams.get("courseKey"); - if (!courseKey) { - return NextResponse.json({ error: "courseKey query parameter is required" }, { status: 400 }); - } + if (!courseKey) return failed("Choose a course to delete its chat history.", 400, "INVALID_INPUT"); try { const result = await prisma.chatMessage.deleteMany({ @@ -119,6 +144,6 @@ export async function DELETE(request: NextRequest) { return NextResponse.json({ deleted: result.count }); } catch (err) { logger.error("chat.messages.clear_failed", { userId, courseKey, error: String(err) }); - return NextResponse.json({ error: "Internal server error" }, { status: 500 }); + return failed("Chat history not deleted. Retry."); } } diff --git a/src/app/api/config/route.ts b/src/app/api/config/route.ts index 177e3b5d..56685658 100644 --- a/src/app/api/config/route.ts +++ b/src/app/api/config/route.ts @@ -1,19 +1,24 @@ import { NextResponse } from "next/server"; +import { publicConfig } from "@/lib/public-config"; // Env-derived flags must be read at request time, not baked in at build. export const dynamic = "force-dynamic"; /** - * GET /api/config — public, non-secret runtime flags for the UI. + * GET /api/config: public, non-secret runtime flags for the UI. * * - verification_required: whether email verification gates sign-in * (opt-in via REQUIRE_EMAIL_VERIFICATION, see src/lib/auth-options.ts). - * - ai_mock: whether the AI provider factory resolves to the mock provider - * (AI_PROVIDER unset or "mock", see src/lib/ai/provider-factory.ts). + * - ai_mock / ai_provider: whether the AI provider factory resolves to the + * mock provider (AI_PROVIDER unset or "mock", see src/lib/ai/provider-factory.ts). + * - ai_disabled: the AI kill switch (AI_DISABLED=true, see src/lib/ai/gateway.ts). + * - google_configured: Google Calendar can be connected (the fake provider, + * or OAuth with a client id; see src/lib/google/availability.ts). + * - email_configured: emails go out over SMTP. + * - email_links_available: password reset and verification links can reach + * the student (SMTP, or the terminal in development). Screens that would + * promise an email check this first. */ export async function GET() { - return NextResponse.json({ - verification_required: process.env.REQUIRE_EMAIL_VERIFICATION === "true", - ai_mock: (process.env.AI_PROVIDER || "mock") === "mock", - }); + return NextResponse.json(publicConfig()); } diff --git a/src/app/api/content/documents/[documentId]/process/route.ts b/src/app/api/content/documents/[documentId]/process/route.ts index 8daed244..df9c13c6 100644 --- a/src/app/api/content/documents/[documentId]/process/route.ts +++ b/src/app/api/content/documents/[documentId]/process/route.ts @@ -2,30 +2,46 @@ import { NextRequest, NextResponse } from "next/server"; import { getUserId } from "@/lib/auth"; import { processDocument } from "@/services/content"; import { aiLimiter, tooManyRequests } from "@/lib/rate-limit"; +import { unauthorized } from "@/lib/http"; +import { retryAfterText } from "@/lib/format"; +/** + * POST /api/content/documents/{id}/process: read the file into sections. + * Responds with `status` PROCESSED, FAILED, or PROCESSING when another + * request is already reading the file (check back; don't start over). + * Limited like other AI work; a 429 carries Retry-After, and the screen + * retries after it. + */ export async function POST( request: NextRequest, - { params }: { params: { documentId: string } } + { params }: { params: Promise<{ documentId: string }> } ) { const userId = await getUserId(request); if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + return unauthorized(); } const rl = aiLimiter.check(userId); - if (!rl.allowed) return tooManyRequests(rl.retryAfterMs); + if (!rl.allowed) { + const seconds = Math.ceil(rl.retryAfterMs / 1000); + return tooManyRequests(rl.retryAfterMs, `Too many files at once. ${retryAfterText(seconds)}`); + } const { documentId } = await params; const result = await processDocument(userId, documentId); if ("error" in result) { - if (result.error === "not_found") { - return NextResponse.json({ error: "Document not found" }, { status: 404 }); - } if (result.error === "forbidden") { - return NextResponse.json({ error: "Forbidden" }, { status: 403 }); + return NextResponse.json( + { error: "This file belongs to another account.", code: "forbidden" }, + { status: 403 }, + ); } + return NextResponse.json( + { error: "This file isn't in your materials anymore.", code: "not_found" }, + { status: 404 }, + ); } return NextResponse.json(result.data); diff --git a/src/app/api/content/documents/[documentId]/route.ts b/src/app/api/content/documents/[documentId]/route.ts new file mode 100644 index 00000000..d3239e61 --- /dev/null +++ b/src/app/api/content/documents/[documentId]/route.ts @@ -0,0 +1,44 @@ +import { NextRequest, NextResponse } from "next/server"; +import { getUserId } from "@/lib/auth"; +import { deleteDocument } from "@/services/content"; +import { logger } from "@/lib/logger"; +import { unauthorized } from "@/lib/http"; + +/** + * DELETE /api/content/documents/{id}: delete one course file, its sections + * and the stored file. Decks made from it stay. + */ +export async function DELETE( + request: NextRequest, + { params }: { params: Promise<{ documentId: string }> } +) { + const userId = await getUserId(request); + if (!userId) { + return unauthorized(); + } + + const { documentId } = await params; + + try { + const result = await deleteDocument(userId, documentId); + if ("data" in result) return NextResponse.json(result.data); + + if (result.error === "not_course_material") { + return NextResponse.json( + { error: "Research papers can't be deleted here.", code: result.error }, + { status: 409 }, + ); + } + // Another account's file reads as missing, so ids can't be probed + return NextResponse.json( + { error: "This file isn't in your materials anymore.", code: "not_found" }, + { status: 404 }, + ); + } catch (err) { + logger.error("document_delete_failed", { document_id: documentId, error: String(err) }); + return NextResponse.json( + { error: "File not deleted. Retry in a minute.", code: "internal" }, + { status: 500 }, + ); + } +} diff --git a/src/app/api/content/documents/[documentId]/summary/route.ts b/src/app/api/content/documents/[documentId]/summary/route.ts index cd0ff239..401970ab 100644 --- a/src/app/api/content/documents/[documentId]/summary/route.ts +++ b/src/app/api/content/documents/[documentId]/summary/route.ts @@ -1,14 +1,15 @@ import { NextRequest, NextResponse } from "next/server"; import { getUserId } from "@/lib/auth"; import { prisma } from "@/lib/db"; +import { unauthorized } from "@/lib/http"; export async function GET( request: NextRequest, - { params }: { params: { documentId: string } } + { params }: { params: Promise<{ documentId: string }> } ) { const userId = await getUserId(request); if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + return unauthorized(); } const { documentId } = await params; @@ -25,11 +26,12 @@ export async function GET( }, }); - if (!doc) { - return NextResponse.json({ error: "Document not found" }, { status: 404 }); - } - if (doc.userId !== userId) { - return NextResponse.json({ error: "Forbidden" }, { status: 403 }); + if (!doc || doc.userId !== userId) { + // Another account's file reads as missing, so ids can't be probed + return NextResponse.json( + { error: "This file isn't in your materials anymore.", code: "not_found" }, + { status: 404 }, + ); } return NextResponse.json({ diff --git a/src/app/api/content/documents/route.ts b/src/app/api/content/documents/route.ts index f6b6a30f..b518916e 100644 --- a/src/app/api/content/documents/route.ts +++ b/src/app/api/content/documents/route.ts @@ -2,9 +2,15 @@ import { NextRequest, NextResponse } from "next/server"; import { getUserId } from "@/lib/auth"; import { uploadDocument, listDocuments } from "@/services/content"; import { uploadDocumentSchema, listDocumentsSchema } from "@/lib/validation-content"; -import { z } from "zod/v4"; +import { z } from "zod"; import { logger } from "@/lib/logger"; -import { aiLimiter, tooManyRequests } from "@/lib/rate-limit"; +import { generalLimiter, tooManyRequests } from "@/lib/rate-limit"; +import { unauthorized } from "@/lib/http"; +import { retryAfterText } from "@/lib/format"; + +const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10 MB +/** Longest file name kept, matching the title limit in uploadDocumentSchema. */ +const MAX_NAME_LENGTH = 300; const ALLOWED_MIME_TYPES = [ "application/pdf", @@ -13,41 +19,63 @@ const ALLOWED_MIME_TYPES = [ "text/x-markdown", ]; +/** Browsers often send no type (or a generic one) for .md files. */ +const TYPE_BY_EXTENSION: Record<string, string> = { + pdf: "application/pdf", + txt: "text/plain", + md: "text/markdown", + markdown: "text/markdown", +}; + +function resolveMimeType(file: File): string { + const declared = file.type; + if (declared && declared !== "application/octet-stream") return declared; + const extension = file.name.split(".").pop()?.toLowerCase() ?? ""; + return TYPE_BY_EXTENSION[extension] ?? (declared || "text/plain"); +} + +const FILE_RULE = "Upload a PDF, text, or Markdown file up to 10 MB."; + +/** + * POST /api/content/documents (multipart: file, namespace, course_name, + * exam_name?, title?). Saves the file; processing is a separate call to + * /api/content/documents/{id}/process. Uploading the same file again returns + * the existing document (`deduped: true`) with the course it belongs to. + */ export async function POST(request: NextRequest) { const userId = await getUserId(request); - if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); - } + if (!userId) return unauthorized(); - const rl = aiLimiter.check(userId); - if (!rl.allowed) return tooManyRequests(rl.retryAfterMs); + // Saving a file calls no AI, so uploads use the general limit; processing + // (which writes the AI summary) keeps the AI limit. + const rl = generalLimiter.check(userId); + if (!rl.allowed) { + const seconds = Math.ceil(rl.retryAfterMs / 1000); + return tooManyRequests(rl.retryAfterMs, `Too many uploads at once. ${retryAfterText(seconds)}`); + } let formData: FormData; try { formData = await request.formData(); } catch { - return NextResponse.json({ error: "Invalid form data" }, { status: 400 }); + return NextResponse.json( + { error: "The upload didn't arrive complete. Retry.", code: "invalid_form" }, + { status: 400 }, + ); } const file = formData.get("file"); if (!file || !(file instanceof File)) { - return NextResponse.json({ error: "file must be an uploaded file" }, { status: 400 }); + return NextResponse.json({ error: "Choose a file to upload.", code: "no_file" }, { status: 400 }); } - const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10 MB if (file.size > MAX_FILE_SIZE) { - return NextResponse.json( - { error: `File too large. Maximum size is 10 MB.` }, - { status: 413 } - ); + return NextResponse.json({ error: FILE_RULE, code: "file_too_large" }, { status: 413 }); } - const mimeType = file.type || "text/plain"; + const mimeType = resolveMimeType(file); if (!ALLOWED_MIME_TYPES.includes(mimeType)) { - return NextResponse.json( - { error: `Unsupported file type: ${mimeType}. Allowed: PDF, text, markdown` }, - { status: 400 } - ); + return NextResponse.json({ error: FILE_RULE, code: "unsupported_type" }, { status: 400 }); } const fields = { @@ -57,18 +85,23 @@ export async function POST(request: NextRequest) { title: (formData.get("title") as string) || undefined, }; + // A hand-built request can put folders ("../") and any length in the + // name; keep only its last segment, at a length the screens can show. + // Storage never uses this name for the path (see storedFileName). + const fileName = (file.name.split(/[\\/]/).pop() ?? "").trim().slice(0, MAX_NAME_LENGTH) || "Untitled file"; + try { const parsed = uploadDocumentSchema.parse(fields); const fileBuffer = Buffer.from(await file.arrayBuffer()); - const title = parsed.title || file.name; + const title = parsed.title || fileName; const result = await uploadDocument( userId, parsed.namespace, parsed.course_name, - parsed.exam_name, + parsed.exam_name || undefined, title, - file.name, + fileName, mimeType, fileBuffer ); @@ -77,20 +110,25 @@ export async function POST(request: NextRequest) { } catch (err) { if (err instanceof z.ZodError) { return NextResponse.json( - { error: "Validation failed", issues: err.issues }, + { + error: err.issues[0]?.message ?? "Check the course name and retry.", + code: "validation_failed", + issues: err.issues, + }, { status: 400 } ); } logger.error("document_upload_failed", { error: String(err) }); - return NextResponse.json({ error: "Internal server error" }, { status: 500 }); + return NextResponse.json( + { error: `${fileName} wasn't uploaded. Retry in a minute.`, code: "internal" }, + { status: 500 }, + ); } } export async function GET(request: NextRequest) { const userId = await getUserId(request); - if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); - } + if (!userId) return unauthorized(); const { searchParams } = new URL(request.url); const params = { @@ -106,11 +144,14 @@ export async function GET(request: NextRequest) { } catch (err) { if (err instanceof z.ZodError) { return NextResponse.json( - { error: "Validation failed", issues: err.issues }, + { error: "That materials filter isn't valid.", code: "validation_failed", issues: err.issues }, { status: 400 } ); } logger.error("list_documents_failed", { error: String(err) }); - return NextResponse.json({ error: "Internal server error" }, { status: 500 }); + return NextResponse.json( + { error: "Materials didn't load. Retry in a minute.", code: "internal" }, + { status: 500 }, + ); } } diff --git a/src/app/api/content/search/route.ts b/src/app/api/content/search/route.ts deleted file mode 100644 index 72ba75af..00000000 --- a/src/app/api/content/search/route.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { NextRequest, NextResponse } from "next/server"; -import { getUserId } from "@/lib/auth"; -import { searchChunks } from "@/lib/search"; -import { searchContentSchema } from "@/lib/validation-content"; -import { z } from "zod/v4"; -import { logger } from "@/lib/logger"; - -export async function POST(request: NextRequest) { - const userId = await getUserId(request); - if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); - } - - let body: unknown; - try { - body = await request.json(); - } catch { - return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 }); - } - - try { - const parsed = searchContentSchema.parse(body); - - const results = await searchChunks({ - userId, - q: parsed.q, - namespace: parsed.namespace, - courseName: parsed.course_name, - examName: parsed.exam_name, - topK: parsed.top_k, - }); - - return NextResponse.json({ results }); - } catch (err) { - if (err instanceof z.ZodError) { - return NextResponse.json( - { error: "Validation failed", issues: err.issues }, - { status: 400 } - ); - } - logger.error("content_search_failed", { error: String(err) }); - return NextResponse.json({ error: "Internal server error" }, { status: 500 }); - } -} diff --git a/src/app/api/flashcards/[deckId]/cards/[cardId]/route.ts b/src/app/api/flashcards/[deckId]/cards/[cardId]/route.ts new file mode 100644 index 00000000..a64c1475 --- /dev/null +++ b/src/app/api/flashcards/[deckId]/cards/[cardId]/route.ts @@ -0,0 +1,62 @@ +import { NextRequest, NextResponse } from "next/server"; +import { getUserId } from "@/lib/auth"; +import { deleteFlashcard, FlashcardError, updateFlashcard } from "@/services/flashcards"; +import { logger } from "@/lib/logger"; +import { generalLimiter } from "@/lib/rate-limit"; +import { failed, invalidInput, invalidJson, rateLimited, unauthorized } from "../../../_lib/http"; +import { cardUpdateSchema } from "../../../_lib/card-schema"; + +type Params = { params: Promise<{ deckId: string; cardId: string }> }; + +function notFound(err: FlashcardError) { + return err.code === "CARD_NOT_FOUND" + ? failed("This card isn't in the deck anymore. Reload to see the deck.", 404, err.code) + : failed("This deck doesn't exist. It may have been deleted.", 404, err.code); +} + +/** PATCH /api/flashcards/:deckId/cards/:cardId { front?, back? }: edits a card's text. */ +export async function PATCH(request: NextRequest, { params }: Params) { + const userId = await getUserId(request); + if (!userId) return unauthorized(); + + const rl = generalLimiter.check(userId); + if (!rl.allowed) return rateLimited(rl.retryAfterMs); + + let body: unknown; + try { + body = await request.json(); + } catch { + return invalidJson(); + } + + const parsed = cardUpdateSchema.safeParse(body); + if (!parsed.success) return invalidInput(parsed.error); + + const { deckId, cardId } = await params; + + try { + const card = await updateFlashcard(userId, deckId, cardId, parsed.data); + return NextResponse.json({ card }); + } catch (err) { + if (err instanceof FlashcardError) return notFound(err); + logger.error("flashcards.card_update_failed", { userId, deckId, cardId, error: String(err) }); + return failed("Card not saved. Retry."); + } +} + +/** DELETE /api/flashcards/:deckId/cards/:cardId: deletes the card and its review history. */ +export async function DELETE(request: NextRequest, { params }: Params) { + const userId = await getUserId(request); + if (!userId) return unauthorized(); + + const { deckId, cardId } = await params; + + try { + await deleteFlashcard(userId, deckId, cardId); + return NextResponse.json({ success: true }); + } catch (err) { + if (err instanceof FlashcardError) return notFound(err); + logger.error("flashcards.card_delete_failed", { userId, deckId, cardId, error: String(err) }); + return failed("Card not deleted. Retry."); + } +} diff --git a/src/app/api/flashcards/[deckId]/cards/route.ts b/src/app/api/flashcards/[deckId]/cards/route.ts new file mode 100644 index 00000000..3e01b91c --- /dev/null +++ b/src/app/api/flashcards/[deckId]/cards/route.ts @@ -0,0 +1,42 @@ +import { NextRequest, NextResponse } from "next/server"; +import { getUserId } from "@/lib/auth"; +import { addFlashcard, FlashcardError } from "@/services/flashcards"; +import { logger } from "@/lib/logger"; +import { generalLimiter } from "@/lib/rate-limit"; +import { failed, invalidInput, invalidJson, rateLimited, unauthorized } from "../../_lib/http"; +import { cardCreateSchema } from "../../_lib/card-schema"; + +/** POST /api/flashcards/:deckId/cards { front, back }: adds a card at the end of the deck. */ +export async function POST( + request: NextRequest, + { params }: { params: Promise<{ deckId: string }> }, +) { + const userId = await getUserId(request); + if (!userId) return unauthorized(); + + const rl = generalLimiter.check(userId); + if (!rl.allowed) return rateLimited(rl.retryAfterMs); + + let body: unknown; + try { + body = await request.json(); + } catch { + return invalidJson(); + } + + const parsed = cardCreateSchema.safeParse(body); + if (!parsed.success) return invalidInput(parsed.error); + + const { deckId } = await params; + + try { + const card = await addFlashcard(userId, deckId, parsed.data); + return NextResponse.json({ card }, { status: 201 }); + } catch (err) { + if (err instanceof FlashcardError && err.code === "DECK_NOT_FOUND") { + return failed("This deck doesn't exist. It may have been deleted.", 404, err.code); + } + logger.error("flashcards.card_add_failed", { userId, deckId, error: String(err) }); + return failed("Card not added. Retry."); + } +} diff --git a/src/app/api/flashcards/[deckId]/review/route.ts b/src/app/api/flashcards/[deckId]/review/route.ts index a3644dda..1ad7013f 100644 --- a/src/app/api/flashcards/[deckId]/review/route.ts +++ b/src/app/api/flashcards/[deckId]/review/route.ts @@ -1,46 +1,53 @@ import { NextRequest, NextResponse } from "next/server"; -import { z } from "zod/v4"; +import { z } from "zod"; import { getUserId } from "@/lib/auth"; import { prisma } from "@/lib/db"; import { reviewCard, isDeckPerfect } from "@/services/spaced-repetition"; -import { awardXp } from "@/services/gamification"; +import { awardXp, resolveTimeZone, startOfDay } from "@/services/gamification"; import { logger } from "@/lib/logger"; +import { failed, invalidInput, invalidJson, unauthorized } from "../../_lib/http"; const reviewSchema = z.object({ card_id: z.string().min(1), rating: z.enum(["AGAIN", "HARD", "GOOD", "EASY"]), }); +const DECK_NOT_FOUND = "This deck doesn't exist. It may have been deleted."; +const CARD_NOT_FOUND = "This card isn't in the deck anymore. Reload to continue."; + +/** + * POST /api/flashcards/:deckId/review: rates one card. The new interval is + * capped by the course's nearest exam. Returns the card's new schedule, + * status and next interval previews, plus XP earned. + */ export async function POST( request: NextRequest, { params }: { params: Promise<{ deckId: string }> }, ) { const userId = await getUserId(request); - if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); - } + if (!userId) return unauthorized(); let body: unknown; try { body = await request.json(); } catch { - return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 }); + return invalidJson(); } const parsed = reviewSchema.safeParse(body); - if (!parsed.success) { - return NextResponse.json( - { error: "Validation failed", issues: parsed.error.issues }, - { status: 400 }, - ); - } + if (!parsed.success) return invalidInput(parsed.error, "Rate the card Again, Hard, Good, or Easy."); const { deckId } = await params; const { card_id, rating } = parsed.data; + // The student's zone sets the card's next due date and the day the + // perfect-deck bonus counts in. Its lookup runs alongside the deck check. + const zone = resolveTimeZone(userId); + zone.catch(() => {}); // awaited below; an early return must not leave it unhandled + try { // Validate the deck: it must exist, belong to this user, and contain the - // reviewed card — otherwise the perfect-deck bonus can be farmed with + // reviewed card; otherwise the perfect-deck bonus can be farmed with // arbitrary deck IDs. const deck = await prisma.flashcardDeck.findUnique({ where: { id: deckId }, @@ -49,58 +56,64 @@ export async function POST( cards: { where: { id: card_id }, select: { id: true } }, }, }); - if (!deck) { - return NextResponse.json({ error: "Deck not found" }, { status: 404 }); - } - if (deck.userId !== userId) { - return NextResponse.json({ error: "Forbidden" }, { status: 403 }); - } - if (deck.cards.length === 0) { - return NextResponse.json({ error: "Card not found in deck" }, { status: 404 }); - } - - const result = await reviewCard(userId, card_id, rating); + if (!deck) return failed(DECK_NOT_FOUND, 404, "DECK_NOT_FOUND"); + if (deck.userId !== userId) return failed(DECK_NOT_FOUND, 403, "FORBIDDEN"); + if (deck.cards.length === 0) return failed(CARD_NOT_FOUND, 404, "CARD_NOT_FOUND"); - // Award XP for the review - const xp = await awardXp(userId, "FLASHCARD_REVIEW", undefined, card_id); + const result = await reviewCard(userId, card_id, rating, zone); + const timeZone = await zone; // already settled: reviewCard waited for it - // Check for perfect deck bonus — awarded at most once per deck per UTC day - let perfectBonus = 0; - let perfectDeck = false; - if (rating !== "AGAIN") { - perfectDeck = await isDeckPerfect(userId, deckId); - if (perfectDeck) { - const utcDayStart = new Date(); - utcDayStart.setUTCHours(0, 0, 0, 0); - const alreadyAwarded = await prisma.xpEvent.findFirst({ - where: { - userId, - action: "PERFECT_DECK", - sourceId: deckId, - createdAt: { gte: utcDayStart }, - }, - select: { id: true }, - }); - if (!alreadyAwarded) { - const bonus = await awardXp(userId, "PERFECT_DECK", undefined, deckId); - perfectBonus = bonus.xpAmount; - } - } - } + // The review's XP and the perfect-deck check don't depend on each other. + // The bonus is awarded at most once per deck per day, in the student's + // time zone (the day the streak and XP today use). + const now = new Date(); + const [xp, perfect] = await Promise.all([ + awardXp(userId, "FLASHCARD_REVIEW", undefined, card_id), + rating === "AGAIN" ? NOT_PERFECT : perfectDeckToday(userId, deckId, timeZone, now), + ]); + const perfectBonus = perfect.bonusDue + ? (await awardXp(userId, "PERFECT_DECK", undefined, deckId)).xpAmount + : 0; return NextResponse.json({ ...result, xpEarned: xp.xpAmount + perfectBonus, - perfectDeck, + perfectDeck: perfect.perfectDeck, }); } catch (err) { if (err instanceof Error && err.message === "Card not found") { - return NextResponse.json({ error: "Card not found" }, { status: 404 }); + return failed(CARD_NOT_FOUND, 404, "CARD_NOT_FOUND"); } if (err instanceof Error && err.message === "Forbidden") { - return NextResponse.json({ error: "Forbidden" }, { status: 403 }); + return failed(DECK_NOT_FOUND, 403, "FORBIDDEN"); } logger.error("flashcard.review_failed", { userId, cardId: card_id, error: String(err) }); - return NextResponse.json({ error: "Internal server error" }, { status: 500 }); + return failed("Rating not saved. Retry."); } } + +const NOT_PERFECT = { perfectDeck: false, bonusDue: false }; + +/** + * Whether every card in the deck was rated Hard or better today, and if so + * whether today's bonus for it is still to be awarded. + */ +async function perfectDeckToday( + userId: string, + deckId: string, + timeZone: string, + now: Date, +): Promise<{ perfectDeck: boolean; bonusDue: boolean }> { + const perfectDeck = await isDeckPerfect(userId, deckId, timeZone, now); + if (!perfectDeck) return { perfectDeck, bonusDue: false }; + const alreadyAwarded = await prisma.xpEvent.findFirst({ + where: { + userId, + action: "PERFECT_DECK", + sourceId: deckId, + createdAt: { gte: startOfDay(now, timeZone) }, + }, + select: { id: true }, + }); + return { perfectDeck, bonusDue: !alreadyAwarded }; +} diff --git a/src/app/api/flashcards/[deckId]/route.ts b/src/app/api/flashcards/[deckId]/route.ts index f968caa5..bc66bc88 100644 --- a/src/app/api/flashcards/[deckId]/route.ts +++ b/src/app/api/flashcards/[deckId]/route.ts @@ -1,46 +1,50 @@ import { NextRequest, NextResponse } from "next/server"; import { getUserId } from "@/lib/auth"; -import { getFlashcardDeck, deleteFlashcardDeck } from "@/services/flashcards"; +import { getDeckDetail, deleteFlashcardDeck } from "@/services/flashcards"; import { logger } from "@/lib/logger"; +import { failed, unauthorized } from "../_lib/http"; +const DECK_NOT_FOUND = "This deck doesn't exist. It may have been deleted."; + +/** + * GET /api/flashcards/:deckId: the deck with counts, its upcoming exam, and + * every card with its status and next review. + */ export async function GET( request: NextRequest, { params }: { params: Promise<{ deckId: string }> }, ) { const userId = await getUserId(request); - if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); - } + if (!userId) return unauthorized(); const { deckId } = await params; - const deck = await getFlashcardDeck(userId, deckId); - if (!deck) { - return NextResponse.json({ error: "Deck not found" }, { status: 404 }); + try { + const deck = await getDeckDetail(userId, deckId); + if (!deck) return failed(DECK_NOT_FOUND, 404, "DECK_NOT_FOUND"); + return NextResponse.json(deck); + } catch (err) { + logger.error("flashcard.deck_get_failed", { userId, deckId, error: String(err) }); + return failed("Deck didn't load. Retry."); } - - return NextResponse.json(deck); } +/** DELETE /api/flashcards/:deckId: deletes the deck, its cards and their review history. */ export async function DELETE( request: NextRequest, { params }: { params: Promise<{ deckId: string }> }, ) { const userId = await getUserId(request); - if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); - } + if (!userId) return unauthorized(); const { deckId } = await params; try { const deleted = await deleteFlashcardDeck(userId, deckId); - if (!deleted) { - return NextResponse.json({ error: "Deck not found" }, { status: 404 }); - } + if (!deleted) return failed(DECK_NOT_FOUND, 404, "DECK_NOT_FOUND"); return NextResponse.json({ success: true }); } catch (err) { logger.error("flashcard.delete_failed", { userId, deckId, error: String(err) }); - return NextResponse.json({ error: "Internal server error" }, { status: 500 }); + return failed("Deck not deleted. Retry."); } } diff --git a/src/app/api/flashcards/[deckId]/study/route.ts b/src/app/api/flashcards/[deckId]/study/route.ts index e472045f..1c5ab034 100644 --- a/src/app/api/flashcards/[deckId]/study/route.ts +++ b/src/app/api/flashcards/[deckId]/study/route.ts @@ -2,26 +2,31 @@ import { NextRequest, NextResponse } from "next/server"; import { getUserId } from "@/lib/auth"; import { getStudyCards } from "@/services/spaced-repetition"; import { logger } from "@/lib/logger"; +import { failed, unauthorized } from "../../_lib/http"; +/** + * GET /api/flashcards/:deckId/study?scope=due|all: the cards for a review. + * "due" (new cards and cards due before today ends) or "all" (default, the + * whole deck). Each card carries the interval every rating would give it. + */ export async function GET( request: NextRequest, { params }: { params: Promise<{ deckId: string }> }, ) { const userId = await getUserId(request); - if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); - } + if (!userId) return unauthorized(); const { deckId } = await params; + const scope = request.nextUrl.searchParams.get("scope") === "due" ? "due" : "all"; try { - const result = await getStudyCards(userId, deckId); + const result = await getStudyCards(userId, deckId, scope); return NextResponse.json(result); } catch (err) { if (err instanceof Error && err.message === "Deck not found") { - return NextResponse.json({ error: "Deck not found" }, { status: 404 }); + return failed("This deck doesn't exist. It may have been deleted.", 404, "DECK_NOT_FOUND"); } logger.error("flashcard.study_failed", { userId, deckId, error: String(err) }); - return NextResponse.json({ error: "Internal server error" }, { status: 500 }); + return failed("Cards didn't load. Retry."); } } diff --git a/src/app/api/flashcards/_lib/card-schema.ts b/src/app/api/flashcards/_lib/card-schema.ts new file mode 100644 index 00000000..9142fcd5 --- /dev/null +++ b/src/app/api/flashcards/_lib/card-schema.ts @@ -0,0 +1,24 @@ +import { z } from "zod"; +import { CARD_BACK_MAX, CARD_FRONT_MAX } from "@/services/flashcards"; +import { formatNumber } from "@/lib/format"; + +/** The two sides of a card. Errors are written as instructions for the field. */ +export const cardFront = z + .string() + .trim() + .min(1, "Write the question or cue for the front.") + .max(CARD_FRONT_MAX, `Keep the front under ${formatNumber(CARD_FRONT_MAX)} characters.`); + +export const cardBack = z + .string() + .trim() + .min(1, "Write the answer for the back.") + .max(CARD_BACK_MAX, `Keep the back under ${formatNumber(CARD_BACK_MAX)} characters.`); + +export const cardCreateSchema = z.object({ front: cardFront, back: cardBack }); + +export const cardUpdateSchema = z + .object({ front: cardFront.optional(), back: cardBack.optional() }) + .refine((v) => v.front !== undefined || v.back !== undefined, { + message: "Change the front or the back.", + }); diff --git a/src/app/api/flashcards/_lib/http.ts b/src/app/api/flashcards/_lib/http.ts new file mode 100644 index 00000000..55d60a6d --- /dev/null +++ b/src/app/api/flashcards/_lib/http.ts @@ -0,0 +1,42 @@ +import { NextResponse } from "next/server"; +import { tooManyRequests } from "@/lib/rate-limit"; +import type { GatewayError } from "@/lib/ai/gateway"; + +/** + * Responses shared by the flashcard, chat and assistant routes. Every + * `error` string is written for the student (it may reach the screen), and + * `code` lets the client pick its own copy. + */ + +export { invalidInput, invalidJson, unauthorized } from "@/lib/http"; + +/** The one 429 body (tooManyRequests): RATE_LIMITED, Retry-After, and the wait in words. */ +export function rateLimited(retryAfterMs: number) { + return tooManyRequests(retryAfterMs); +} + + +export function failed( + message: string, + status = 500, + code = "SERVER_ERROR", + extra?: Record<string, unknown>, +) { + return NextResponse.json({ ...extra, error: message, code }, { status }); +} + +export const AI_PAUSED_MESSAGE = "AI features are paused. Existing decks and guides still work."; + +/** + * Maps an AI gateway failure: AI switched off or over budget reads as + * paused; anything else is the caller's "not generated" sentence. + */ +export function gatewayFailure(err: GatewayError, notDone: string, extra?: Record<string, unknown>) { + if (err.code === "AI_DISABLED" || err.code === "BUDGET_EXCEEDED") { + return NextResponse.json( + { ...extra, error: AI_PAUSED_MESSAGE, code: err.code }, + { status: err.code === "BUDGET_EXCEEDED" ? 429 : 503 }, + ); + } + return NextResponse.json({ ...extra, error: notDone, code: err.code }, { status: 502 }); +} diff --git a/src/app/api/flashcards/route.ts b/src/app/api/flashcards/route.ts index 0bafd8ff..15e1d05b 100644 --- a/src/app/api/flashcards/route.ts +++ b/src/app/api/flashcards/route.ts @@ -1,73 +1,93 @@ import { NextRequest, NextResponse } from "next/server"; -import { z } from "zod/v4"; +import { z } from "zod"; import { getUserId } from "@/lib/auth"; import { + FlashcardError, generateFlashcardsFromDocument, generateFlashcardsFromCourse, listFlashcardDecks, } from "@/services/flashcards"; import { GatewayError } from "@/lib/ai/gateway"; import { logger } from "@/lib/logger"; -import { aiLimiter, tooManyRequests } from "@/lib/rate-limit"; +import { aiLimiter } from "@/lib/rate-limit"; +import { + failed, + gatewayFailure, + invalidInput, + invalidJson, + rateLimited, + unauthorized, +} from "./_lib/http"; const generateSchema = z.object({ - course_name: z.string().min(1), - exam_name: z.string().optional(), - document_id: z.string().optional(), + course_name: z.string().trim().min(1).max(200), + exam_name: z.string().trim().max(200).optional(), + document_id: z.string().min(1).max(100).optional(), }); +const NOT_GENERATED = "Deck not generated. Retry."; + +/** + * POST /api/flashcards: generate a deck with AI from a course's processed + * materials (or one file with document_id). 201 with the deck. + */ export async function POST(request: NextRequest) { const userId = await getUserId(request); - if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); - } + if (!userId) return unauthorized(); const rl = aiLimiter.check(userId); - if (!rl.allowed) return tooManyRequests(rl.retryAfterMs); + if (!rl.allowed) return rateLimited(rl.retryAfterMs); let body: unknown; try { body = await request.json(); } catch { - return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 }); + return invalidJson(); } const parsed = generateSchema.safeParse(body); - if (!parsed.success) { - return NextResponse.json( - { error: "Validation failed", issues: parsed.error.issues }, - { status: 400 }, - ); - } + if (!parsed.success) return invalidInput(parsed.error, "Choose a course to generate a deck for."); const { course_name, exam_name, document_id } = parsed.data; try { const deck = document_id ? await generateFlashcardsFromDocument(userId, document_id) - : await generateFlashcardsFromCourse(userId, course_name, exam_name); + : await generateFlashcardsFromCourse(userId, course_name, exam_name || undefined); return NextResponse.json(deck, { status: 201 }); } catch (err) { - if (err instanceof GatewayError) { - const status = err.code === "BUDGET_EXCEEDED" ? 429 : err.code === "AI_DISABLED" ? 503 : 502; - return NextResponse.json({ error: err.message, code: err.code }, { status }); - } - if (err instanceof Error && (err.message.includes("not found") || err.message.includes("No course"))) { - return NextResponse.json({ error: err.message }, { status: 404 }); - } - if (err instanceof Error && err.message === "Forbidden") { - return NextResponse.json({ error: "Forbidden" }, { status: 403 }); + if (err instanceof GatewayError) return gatewayFailure(err, NOT_GENERATED); + if (err instanceof FlashcardError) { + switch (err.code) { + case "NO_MATERIALS": + return failed(`Upload materials for ${course_name} first. Decks are generated from them.`, 404, err.code); + case "MATERIALS_PROCESSING": + return failed( + `Your ${course_name} materials are still processing. Generate the deck when they're ready.`, + 409, + err.code, + ); + case "NO_CARDS": + return failed(`No cards came out of your ${course_name} materials. Retry, or upload more materials.`, 502, err.code); + case "DOC_NOT_FOUND": + case "FORBIDDEN": + return failed("That file isn't in your materials.", 404, err.code); + case "DOC_NOT_READY": + return failed("That file is still processing. Generate the deck when it's ready.", 409, err.code); + } } logger.error("flashcards.generate_failed", { userId, error: String(err) }); - return NextResponse.json({ error: "Internal server error" }, { status: 500 }); + return failed(NOT_GENERATED); } } +/** + * GET /api/flashcards?course_name=&exam_name=: decks with counts per status + * and due today. Filtering by course only (no exam) matches /api/learn. + */ export async function GET(request: NextRequest) { const userId = await getUserId(request); - if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); - } + if (!userId) return unauthorized(); const { searchParams } = new URL(request.url); const courseName = searchParams.get("course_name") || undefined; @@ -78,6 +98,6 @@ export async function GET(request: NextRequest) { return NextResponse.json({ decks }); } catch (err) { logger.error("flashcards.list_failed", { userId, error: String(err) }); - return NextResponse.json({ error: "Internal server error" }, { status: 500 }); + return failed("Decks didn't load. Retry."); } } diff --git a/src/app/api/guides/[guideId]/route.ts b/src/app/api/guides/[guideId]/route.ts index 53d55fb2..4c371aa6 100644 --- a/src/app/api/guides/[guideId]/route.ts +++ b/src/app/api/guides/[guideId]/route.ts @@ -1,34 +1,66 @@ +/** + * GET /api/guides/{guideId}: one guide with its sections, { guide }. + * DELETE /api/guides/{guideId}: deletes a guide the user owns. + */ import { NextRequest, NextResponse } from "next/server"; +import { z } from "zod"; import { getUserId } from "@/lib/auth"; -import { prisma } from "@/lib/db"; import { logger } from "@/lib/logger"; +import { deleteStudyGuide, getStudyGuide } from "@/services/study-guides"; +import { unauthorized } from "@/lib/http"; -export async function DELETE( +const paramsSchema = z.object({ guideId: z.string().trim().min(1).max(64) }); + +export async function GET( request: NextRequest, { params }: { params: Promise<{ guideId: string }> }, ) { const userId = await getUserId(request); - if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); - } + if (!userId) return unauthorized(); - const { guideId } = await params; + const parsed = paramsSchema.safeParse(await params); + if (!parsed.success) { + return NextResponse.json({ error: "This guide doesn't exist.", code: "NOT_FOUND" }, { status: 404 }); + } try { - const guide = await prisma.studyGuide.findUnique({ - where: { id: guideId }, - select: { userId: true }, - }); - - if (!guide || guide.userId !== userId) { - return NextResponse.json({ error: "Guide not found" }, { status: 404 }); + const guide = await getStudyGuide(userId, parsed.data.guideId); + if (!guide) { + return NextResponse.json( + { error: "This guide was deleted or belongs to another account.", code: "NOT_FOUND" }, + { status: 404 }, + ); } + return NextResponse.json({ guide }); + } catch (err) { + logger.error("guides.get_failed", { userId, error: String(err) }); + return NextResponse.json({ error: "Guide didn't load. Retry.", code: "INTERNAL" }, { status: 500 }); + } +} + +export async function DELETE( + request: NextRequest, + { params }: { params: Promise<{ guideId: string }> }, +) { + const userId = await getUserId(request); + if (!userId) return unauthorized(); - await prisma.studyGuide.delete({ where: { id: guideId } }); - logger.info("guide.deleted", { user_id: userId, guide_id: guideId }); + const parsed = paramsSchema.safeParse(await params); + if (!parsed.success) { + return NextResponse.json({ error: "This guide doesn't exist.", code: "NOT_FOUND" }, { status: 404 }); + } + try { + const deleted = await deleteStudyGuide(userId, parsed.data.guideId); + if (!deleted) { + return NextResponse.json( + { error: "This guide was already deleted or belongs to another account.", code: "NOT_FOUND" }, + { status: 404 }, + ); + } return NextResponse.json({ success: true }); - } catch { - return NextResponse.json({ error: "Internal server error" }, { status: 500 }); + } catch (err) { + logger.error("guides.delete_failed", { userId, error: String(err) }); + return NextResponse.json({ error: "Guide not deleted. Retry.", code: "INTERNAL" }, { status: 500 }); } } diff --git a/src/app/api/guides/route.ts b/src/app/api/guides/route.ts index 6cebe44a..1c9ad701 100644 --- a/src/app/api/guides/route.ts +++ b/src/app/api/guides/route.ts @@ -1,22 +1,52 @@ +/** + * GET /api/guides?course_name=&exam_name= list guides, newest first; only + * the newest of each format carries `sections` (GET /api/guides/{id} for others) + * POST /api/guides { course_name, exam_name?, guide_type } generate one + * + * Error bodies carry a VOICE.md sentence in `error` and a stable `code`. + */ import { NextRequest, NextResponse } from "next/server"; -import { z } from "zod/v4"; +import { z } from "zod"; import { getUserId } from "@/lib/auth"; -import { generateStudyGuide, listStudyGuides } from "@/services/study-guides"; import { GatewayError } from "@/lib/ai/gateway"; import { logger } from "@/lib/logger"; import { aiLimiter, tooManyRequests } from "@/lib/rate-limit"; +import { generateStudyGuide, listStudyGuides, NoGuideMaterialsError } from "@/services/study-guides"; +import { GUIDE_TYPES } from "@/lib/guide-format"; +import { unauthorized } from "@/lib/http"; const generateSchema = z.object({ - course_name: z.string().min(1), - exam_name: z.string().optional(), - guide_type: z.enum(["KEY_CONCEPTS", "FAQ", "CHEAT_SHEET"]), + course_name: z.string().trim().min(1).max(200), + exam_name: z.string().trim().max(200).optional(), + guide_type: z.enum(GUIDE_TYPES), }); +const listSchema = z.object({ + course_name: z.string().trim().max(200).optional(), + exam_name: z.string().trim().max(200).optional(), +}); + +const AI_PAUSED = "AI features are paused. Existing decks and guides still work."; + +/** Gateway failures as a status and a sentence the screen can show as is. */ +function gatewayResponse(err: GatewayError) { + switch (err.code) { + case "AI_DISABLED": + return { status: 503, error: AI_PAUSED }; + case "BUDGET_EXCEEDED": + return { status: 429, error: AI_PAUSED }; + case "CIRCUIT_OPEN": + return { status: 503, error: "The AI service failed several times in a row, so it's paused for a few minutes. Retry later." }; + case "PARSE_ERROR": + return { status: 502, error: "The AI response couldn't be read. Retry." }; + default: + return { status: 502, error: "The AI service didn't respond. Retry in a minute." }; + } +} + export async function POST(request: NextRequest) { const userId = await getUserId(request); - if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); - } + if (!userId) return unauthorized(); const rl = aiLimiter.check(userId); if (!rl.allowed) return tooManyRequests(rl.retryAfterMs); @@ -25,13 +55,16 @@ export async function POST(request: NextRequest) { try { body = await request.json(); } catch { - return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 }); + return NextResponse.json( + { error: "Guide not generated. Reload the page and retry.", code: "INVALID_JSON" }, + { status: 400 }, + ); } const parsed = generateSchema.safeParse(body); if (!parsed.success) { return NextResponse.json( - { error: "Validation failed", issues: parsed.error.issues }, + { error: "Choose a course and a guide format.", code: "VALIDATION", issues: parsed.error.issues }, { status: 400 }, ); } @@ -39,36 +72,47 @@ export async function POST(request: NextRequest) { const { course_name, exam_name, guide_type } = parsed.data; try { - const guide = await generateStudyGuide(userId, course_name, exam_name, guide_type); + const guide = await generateStudyGuide(userId, course_name, exam_name || undefined, guide_type); return NextResponse.json(guide, { status: 201 }); } catch (err) { if (err instanceof GatewayError) { - const status = err.code === "BUDGET_EXCEEDED" ? 429 : err.code === "AI_DISABLED" ? 503 : 502; - return NextResponse.json({ error: err.message, code: err.code }, { status }); + const { status, error } = gatewayResponse(err); + logger.warn("guides.generate_gateway_failed", { userId, code: err.code }); + return NextResponse.json({ error, code: err.code }, { status }); } - if (err instanceof Error && err.message.includes("No course materials")) { - return NextResponse.json({ error: err.message }, { status: 404 }); + if (err instanceof NoGuideMaterialsError) { + return NextResponse.json({ error: err.message, code: err.code }, { status: 404 }); } logger.error("guides.generate_failed", { userId, error: String(err) }); - return NextResponse.json({ error: "Internal server error" }, { status: 500 }); + return NextResponse.json({ error: "Guide not generated. Retry.", code: "INTERNAL" }, { status: 500 }); } } export async function GET(request: NextRequest) { const userId = await getUserId(request); - if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); - } + if (!userId) return unauthorized(); const { searchParams } = new URL(request.url); - const courseName = searchParams.get("course_name") || undefined; - const examName = searchParams.get("exam_name") || undefined; + const parsed = listSchema.safeParse({ + course_name: searchParams.get("course_name") || undefined, + exam_name: searchParams.get("exam_name") || undefined, + }); + if (!parsed.success) { + return NextResponse.json( + { error: "Choose a course to see its guides.", code: "VALIDATION", issues: parsed.error.issues }, + { status: 400 }, + ); + } try { - const guides = await listStudyGuides(userId, courseName, examName); + const guides = await listStudyGuides( + userId, + parsed.data.course_name || undefined, + parsed.data.exam_name || undefined, + ); return NextResponse.json({ guides }); } catch (err) { logger.error("guides.list_failed", { userId, error: String(err) }); - return NextResponse.json({ error: "Internal server error" }, { status: 500 }); + return NextResponse.json({ error: "Guides didn't load. Retry.", code: "INTERNAL" }, { status: 500 }); } } diff --git a/src/app/api/integrations/google/calendars/route.ts b/src/app/api/integrations/google/calendars/route.ts index 3b87c64b..671f7bc8 100644 --- a/src/app/api/integrations/google/calendars/route.ts +++ b/src/app/api/integrations/google/calendars/route.ts @@ -1,20 +1,35 @@ import { NextRequest, NextResponse } from "next/server"; +import { unauthorized } from "@/lib/http"; import { getUserId } from "@/lib/auth"; import { prisma } from "@/lib/db"; import { getGoogleClient, GoogleReconnectError } from "@/lib/google/calendar-client"; +import { GOOGLE_COPY } from "@/lib/google/messages"; import { logger } from "@/lib/logger"; +import { generalLimiter, tooManyRequests } from "@/lib/rate-limit"; +/** + * GET /api/integrations/google/calendars: the student's Google calendars. + * Errors carry a sentence in `error` and a machine `code`: + * 400 GOOGLE_NOT_CONNECTED, 409 GOOGLE_RECONNECT_REQUIRED, 502 GOOGLE_UNAVAILABLE. + */ export async function GET(request: NextRequest) { const userId = await getUserId(request); if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + return unauthorized(); } + // Each call reaches Google Calendar. + const rl = generalLimiter.check(userId); + if (!rl.allowed) return tooManyRequests(rl.retryAfterMs); + const integration = await prisma.googleIntegration.findUnique({ where: { userId }, }); if (!integration || integration.status !== "CONNECTED") { - return NextResponse.json({ error: "Google Calendar not connected" }, { status: 400 }); + return NextResponse.json( + { error: GOOGLE_COPY.notConnected, code: "GOOGLE_NOT_CONNECTED" }, + { status: 400 }, + ); } try { @@ -33,11 +48,14 @@ export async function GET(request: NextRequest) { } catch (err) { if (err instanceof GoogleReconnectError) { return NextResponse.json( - { error: "GOOGLE_RECONNECT_REQUIRED", message: "Please reconnect your Google account." }, + { error: GOOGLE_COPY.reconnect, code: "GOOGLE_RECONNECT_REQUIRED" }, { status: 409 }, ); } - logger.error("google_list_calendars_failed", { error: String(err) }); - return NextResponse.json({ error: "Failed to list calendars" }, { status: 500 }); + logger.error("google_list_calendars_failed", { user_id: userId, error: String(err) }); + return NextResponse.json( + { error: "Calendars didn't load. Retry.", code: "GOOGLE_UNAVAILABLE" }, + { status: 502 }, + ); } } diff --git a/src/app/api/integrations/google/callback/route.ts b/src/app/api/integrations/google/callback/route.ts index ea086c90..85834d97 100644 --- a/src/app/api/integrations/google/callback/route.ts +++ b/src/app/api/integrations/google/callback/route.ts @@ -1,7 +1,20 @@ import { NextRequest, NextResponse } from "next/server"; +import { getUserId } from "@/lib/auth"; import { prisma } from "@/lib/db"; -import { encrypt } from "@/lib/crypto"; +import { encryptToken } from "@/lib/crypto/token-vault"; import { logger } from "@/lib/logger"; +import { getBaseUrl } from "@/lib/config"; + +// The OAuth flow starts from the settings page, so every outcome lands back +// there: ?google=connected on success, ?google=error&reason=<code> otherwise. +function settingsRedirect(outcome: { connected: true } | { error: string }) { + const params = new URLSearchParams( + "error" in outcome + ? { google: "error", reason: outcome.error } + : { google: "connected" }, + ); + return NextResponse.redirect(`${getBaseUrl()}/settings?${params.toString()}`, 302); +} export async function GET(request: NextRequest) { const url = new URL(request.url); @@ -9,27 +22,32 @@ export async function GET(request: NextRequest) { const state = url.searchParams.get("state"); const error = url.searchParams.get("error"); - const baseUrl = process.env.BASE_URL || "http://localhost:3000"; + const baseUrl = getBaseUrl(); if (error) { - return NextResponse.redirect(`${baseUrl}/settings/calendar?error=${error}`, 302); + return settingsRedirect({ error }); } if (!code || !state) { - return NextResponse.redirect(`${baseUrl}/settings/calendar?error=missing_params`, 302); + return settingsRedirect({ error: "missing_params" }); } - // Validate state - const oauthState = await prisma.oAuthState.findUnique({ where: { state } }); - if (!oauthState || oauthState.expiresAt < new Date()) { - // Clean up expired state - if (oauthState) await prisma.oAuthState.delete({ where: { id: oauthState.id } }); - return NextResponse.redirect(`${baseUrl}/settings/calendar?error=invalid_state`, 302); + // The tokens belong to whoever is signed in here, never to whoever started + // the flow: otherwise an attacker could send a victim their own consent + // link (carrying the attacker's state) and receive the victim's calendar. + const userId = await getUserId(request); + if (!userId) { + return settingsRedirect({ error: "invalid_state" }); } - const userId = oauthState.userId; - // Delete state (one-time use) - await prisma.oAuthState.delete({ where: { id: oauthState.id } }); + // Claim the state in one statement: it must exist, be unexpired and have + // been issued to this same user. Two concurrent callbacks can't both win. + const { count } = await prisma.oAuthState.deleteMany({ + where: { state, userId, expiresAt: { gt: new Date() } }, + }); + if (count !== 1) { + return settingsRedirect({ error: "invalid_state" }); + } // Exchange code for tokens const clientId = process.env.GOOGLE_CLIENT_ID; @@ -38,7 +56,7 @@ export async function GET(request: NextRequest) { || `${baseUrl}/api/integrations/google/callback`; if (!clientId || !clientSecret) { - return NextResponse.redirect(`${baseUrl}/settings/calendar?error=not_configured`, 302); + return settingsRedirect({ error: "not_configured" }); } try { @@ -52,12 +70,13 @@ export async function GET(request: NextRequest) { redirect_uri: redirectUri, grant_type: "authorization_code", }), + signal: AbortSignal.timeout(10_000), }); if (!tokenRes.ok) { const errBody = await tokenRes.text(); logger.error("google_token_exchange_failed", { error: String(errBody) }); - return NextResponse.redirect(`${baseUrl}/settings/calendar?error=token_exchange_failed`, 302); + return settingsRedirect({ error: "token_exchange_failed" }); } const tokens = await tokenRes.json(); @@ -67,7 +86,7 @@ export async function GET(request: NextRequest) { const scope = (tokens.scope as string) || ""; if (!refreshToken) { - return NextResponse.redirect(`${baseUrl}/settings/calendar?error=no_refresh_token`, 302); + return settingsRedirect({ error: "no_refresh_token" }); } // Fetch connected email via userinfo @@ -75,18 +94,19 @@ export async function GET(request: NextRequest) { try { const userinfoRes = await fetch("https://www.googleapis.com/oauth2/v2/userinfo", { headers: { Authorization: `Bearer ${accessToken}` }, + signal: AbortSignal.timeout(5_000), }); if (userinfoRes.ok) { const info = await userinfoRes.json(); connectedEmail = (info.email as string) || null; } } catch { - // Non-critical — email is cosmetic + // Non-critical: the email is only shown in Settings. } // Encrypt and store tokens - const accessTokenEncrypted = encrypt(accessToken); - const refreshTokenEncrypted = encrypt(refreshToken); + const accessTokenEncrypted = encryptToken(accessToken); + const refreshTokenEncrypted = encryptToken(refreshToken); const tokenExpiryMs = BigInt(Date.now() + expiresIn * 1000); await prisma.googleIntegration.upsert({ @@ -114,9 +134,9 @@ export async function GET(request: NextRequest) { }, }); - return NextResponse.redirect(`${baseUrl}/settings/calendar?connected=1`, 302); + return settingsRedirect({ connected: true }); } catch (err) { logger.error("google_oauth_callback_failed", { error: String(err) }); - return NextResponse.redirect(`${baseUrl}/settings/calendar?error=internal`, 302); + return settingsRedirect({ error: "internal" }); } } diff --git a/src/app/api/integrations/google/connect/route.ts b/src/app/api/integrations/google/connect/route.ts index 9b74c164..dc712012 100644 --- a/src/app/api/integrations/google/connect/route.ts +++ b/src/app/api/integrations/google/connect/route.ts @@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from "next/server"; import { getUserId } from "@/lib/auth"; import { prisma } from "@/lib/db"; import { randomBytes } from "crypto"; +import { getBaseUrl } from "@/lib/config"; const GOOGLE_SCOPES = [ "https://www.googleapis.com/auth/calendar.events", @@ -10,20 +11,54 @@ const GOOGLE_SCOPES = [ "https://www.googleapis.com/auth/userinfo.email", ].join(" "); +/** The connection the fake provider answers for; its token is never decrypted or sent. */ +async function connectFakeGoogle(userId: string): Promise<void> { + const connection = { + status: "CONNECTED", + connectedEmail: "test@example.com", + refreshTokenEncrypted: "fake-encrypted-token", + tokenExpiryMs: BigInt(Date.now() + 3600_000), + scopeString: GOOGLE_SCOPES, + lastErrorCode: null, + lastErrorMessage: null, + lastHealthyAt: new Date(), + }; + await prisma.googleIntegration.upsert({ + where: { userId }, + create: { userId, ...connection }, + update: connection, + }); +} + +/** + * GET /api/integrations/google/connect: starts Google's OAuth consent flow. + * The Settings page links here with a full-page navigation, so every + * failure redirects to a page with a message instead of answering JSON. + */ export async function GET(request: NextRequest) { - // Support user ID from query param since this is a browser redirect (no custom headers) - const userId = await getUserId(request) - || request.nextUrl.searchParams.get("x_user_id"); + const userId = await getUserId(request); if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + const signIn = new URLSearchParams({ callbackUrl: "/settings#calendar" }); + return NextResponse.redirect(`${getBaseUrl()}/auth/signin?${signIn.toString()}`, 302); + } + + // With the in-memory fake provider (development and tests) there is no + // real Google account to consent with, and tokens from one would never be + // used. Connect to the fake calendar directly and land where the real + // callback would. + if (process.env.GOOGLE_PROVIDER === "fake") { + await connectFakeGoogle(userId); + const params = new URLSearchParams({ google: "connected" }); + return NextResponse.redirect(`${getBaseUrl()}/settings?${params.toString()}`, 302); } const clientId = process.env.GOOGLE_CLIENT_ID; const redirectUri = process.env.GOOGLE_REDIRECT_URI - || `${process.env.BASE_URL || "http://localhost:3000"}/api/integrations/google/callback`; + || `${getBaseUrl()}/api/integrations/google/callback`; if (!clientId) { - return NextResponse.json({ error: "Google OAuth not configured" }, { status: 503 }); + const params = new URLSearchParams({ google: "error", reason: "not_configured" }); + return NextResponse.redirect(`${getBaseUrl()}/settings?${params.toString()}`, 302); } // Generate state token and persist diff --git a/src/app/api/integrations/google/disconnect/route.ts b/src/app/api/integrations/google/disconnect/route.ts index 5ae12f4f..428185bf 100644 --- a/src/app/api/integrations/google/disconnect/route.ts +++ b/src/app/api/integrations/google/disconnect/route.ts @@ -1,13 +1,14 @@ import { NextRequest, NextResponse } from "next/server"; +import { unauthorized } from "@/lib/http"; import { getUserId } from "@/lib/auth"; import { prisma } from "@/lib/db"; -import { decrypt } from "@/lib/crypto"; +import { decryptToken } from "@/lib/crypto/token-vault"; import { logger } from "@/lib/logger"; export async function POST(request: NextRequest) { const userId = await getUserId(request); if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + return unauthorized(); } const integration = await prisma.googleIntegration.findUnique({ @@ -18,16 +19,20 @@ export async function POST(request: NextRequest) { return NextResponse.json({ disconnected: true, status: "DISCONNECTED" }); } - // Best-effort revoke token at Google + // Best-effort revoke at Google. Prefer the refresh token: revoking it ends + // the whole grant, while the stored access token has usually expired (it + // lasts about an hour) and Google rejects revoking it. try { - if (integration.accessTokenEncrypted) { - const token = decrypt(integration.accessTokenEncrypted); - // Send the token in the POST body — never in the URL, where it would + const encrypted = integration.refreshTokenEncrypted ?? integration.accessTokenEncrypted; + if (encrypted) { + const token = decryptToken(encrypted); + // Send the token in the POST body, never in the URL, where it would // leak into proxy/APM logs await fetch("https://oauth2.googleapis.com/revoke", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ token }), + signal: AbortSignal.timeout(5_000), }); } } catch { @@ -35,17 +40,25 @@ export async function POST(request: NextRequest) { } // Mark DISCONNECTED and clear tokens (leave row for reconnect) - await prisma.googleIntegration.update({ - where: { id: integration.id }, - data: { - status: "DISCONNECTED", - accessTokenEncrypted: null, - refreshTokenEncrypted: null, - tokenExpiryMs: BigInt(0), - lastErrorCode: null, - lastErrorMessage: null, - }, - }); + try { + await prisma.googleIntegration.update({ + where: { id: integration.id }, + data: { + status: "DISCONNECTED", + accessTokenEncrypted: null, + refreshTokenEncrypted: null, + tokenExpiryMs: BigInt(0), + lastErrorCode: null, + lastErrorMessage: null, + }, + }); + } catch (err) { + logger.error("google.integration.disconnect_failed", { user_id: userId, error: String(err) }); + return NextResponse.json( + { error: "Google Calendar not disconnected. Check your connection and retry." }, + { status: 500 }, + ); + } logger.info("google.integration.disconnected", { user_id: userId }); diff --git a/src/app/api/integrations/google/freebusy/route.ts b/src/app/api/integrations/google/freebusy/route.ts deleted file mode 100644 index 9a1b8be2..00000000 --- a/src/app/api/integrations/google/freebusy/route.ts +++ /dev/null @@ -1,107 +0,0 @@ -import { NextRequest, NextResponse } from "next/server"; -import { getUserId } from "@/lib/auth"; -import { prisma } from "@/lib/db"; -import { getGoogleClient, GoogleReconnectError, type BusyInterval } from "@/lib/google/calendar-client"; -import { mergeBusy, type TimeInterval } from "@/lib/google/free-slots"; -import { z } from "zod/v4"; -import { logger } from "@/lib/logger"; - -const freebusySchema = z.object({ - calendar_ids: z.array(z.string()).optional(), - time_min: z.string().min(1), - time_max: z.string().min(1), -}); - -export async function POST(request: NextRequest) { - const userId = await getUserId(request); - if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); - } - - const integration = await prisma.googleIntegration.findUnique({ - where: { userId }, - }); - if (!integration || integration.status !== "CONNECTED") { - return NextResponse.json({ error: "Google Calendar not connected" }, { status: 400 }); - } - - let body: unknown; - try { - body = await request.json(); - } catch { - return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 }); - } - - const parsed = freebusySchema.safeParse(body); - if (!parsed.success) { - return NextResponse.json({ error: "Validation failed", issues: parsed.error.issues }, { status: 400 }); - } - - // Default to user's busy calendar preferences - const calendarIds = parsed.data.calendar_ids?.length - ? parsed.data.calendar_ids - : integration.busyCalendarIds.split(",").filter(Boolean); - - const startMs = Date.now(); - logger.info("google.freebusy.started", { user_id: userId, calendar_count: calendarIds.length }); - - try { - const client = getGoogleClient(userId); - const busy: BusyInterval[] = await client.freebusyQuery({ - timeMin: parsed.data.time_min, - timeMax: parsed.data.time_max, - calendarIds, - }); - - const durationMs = Date.now() - startMs; - - // Flatten to {start,end,calendar_id} per spec - const busyFlat = busy.map((b) => ({ - start: b.start, - end: b.end, - calendar_id: b.calendarId, - })); - - // Merged busy (across all calendars) - const allIntervals: TimeInterval[] = busy.map((b) => ({ - start: new Date(b.start).getTime(), - end: new Date(b.end).getTime(), - })); - const merged = mergeBusy(allIntervals); - const mergedBusy = merged.map((m) => ({ - start: new Date(m.start).toISOString(), - end: new Date(m.end).toISOString(), - })); - - logger.info("google.freebusy.completed", { - user_id: userId, - calendar_count: calendarIds.length, - busy_count: busy.length, - duration_ms: durationMs, - }); - - return NextResponse.json({ - busy: busyFlat, - tz: integration.timezone || Intl.DateTimeFormat().resolvedOptions().timeZone, - duration_ms: durationMs, - // Legacy fields - calendars: Array.from( - busy.reduce((map, b) => { - if (!map.has(b.calendarId)) map.set(b.calendarId, []); - map.get(b.calendarId)!.push({ start: b.start, end: b.end }); - return map; - }, new Map<string, { start: string; end: string }[]>()).entries(), - ).map(([calId, intervals]) => ({ calendarId: calId, busy: intervals })), - merged_busy: mergedBusy, - }); - } catch (err) { - if (err instanceof GoogleReconnectError) { - return NextResponse.json( - { error: "GOOGLE_RECONNECT_REQUIRED", message: "Please reconnect your Google account." }, - { status: 409 }, - ); - } - logger.error("google_freebusy_query_failed", { error: String(err) }); - return NextResponse.json({ error: "Failed to query Google Calendar" }, { status: 500 }); - } -} diff --git a/src/app/api/integrations/google/preferences/route.ts b/src/app/api/integrations/google/preferences/route.ts index c8ce784a..96038253 100644 --- a/src/app/api/integrations/google/preferences/route.ts +++ b/src/app/api/integrations/google/preferences/route.ts @@ -1,39 +1,59 @@ import { NextRequest, NextResponse } from "next/server"; -import { z } from "zod/v4"; +import { unauthorized } from "@/lib/http"; +import { z } from "zod"; import { getUserId } from "@/lib/auth"; import { prisma } from "@/lib/db"; +import { GOOGLE_COPY } from "@/lib/google/messages"; import { logger } from "@/lib/logger"; +import { isValidTimezone } from "@/lib/timezone"; const preferencesSchema = z.object({ - default_calendar_id: z.string().min(1).optional(), - busy_calendar_ids: z.array(z.string().min(1)).min(1, "At least one busy calendar required").optional(), - timezone: z.string().min(1).optional(), + default_calendar_id: z.string().min(1, "Choose a calendar.").optional(), + busy_calendar_ids: z + .array(z.string().min(1)) + .min(1, "Keep at least one calendar checked.") + .optional(), + timezone: z + .string() + .min(1) + .refine(isValidTimezone, "Choose a time zone from the list, like America/New_York.") + .optional(), }); +/** + * POST /api/integrations/google/preferences: which calendar receives study + * sessions and which calendars count as busy time for new plans. + */ export async function POST(request: NextRequest) { const userId = await getUserId(request); if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + return unauthorized(); } const integration = await prisma.googleIntegration.findUnique({ where: { userId }, }); if (!integration || integration.status === "DISCONNECTED") { - return NextResponse.json({ error: "Google Calendar not connected" }, { status: 400 }); + return NextResponse.json( + { error: GOOGLE_COPY.notConnected, code: "GOOGLE_NOT_CONNECTED" }, + { status: 400 }, + ); } let body: unknown; try { body = await request.json(); } catch { - return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 }); + return NextResponse.json({ error: "Calendar settings not saved. Retry." }, { status: 400 }); } const parsed = preferencesSchema.safeParse(body); if (!parsed.success) { return NextResponse.json( - { error: "Validation failed", issues: parsed.error.issues }, + { + error: parsed.error.issues[0]?.message ?? "Calendar settings not saved. Retry.", + issues: parsed.error.issues, + }, { status: 400 }, ); } @@ -43,22 +63,32 @@ export async function POST(request: NextRequest) { data.calendarIdSelected = parsed.data.default_calendar_id; } if (parsed.data.busy_calendar_ids !== undefined) { - data.busyCalendarIds = parsed.data.busy_calendar_ids.join(","); + data.busyCalendarIds = [...new Set(parsed.data.busy_calendar_ids)].join(","); } if (parsed.data.timezone !== undefined) { data.timezone = parsed.data.timezone; } - await prisma.googleIntegration.update({ - where: { id: integration.id }, - data, - }); + try { + await prisma.googleIntegration.update({ + where: { id: integration.id }, + data, + }); + } catch (err) { + logger.error("google.preferences.update_failed", { user_id: userId, error: String(err) }); + return NextResponse.json( + { error: "Calendar settings not saved. Check your connection and retry." }, + { status: 500 }, + ); + } - logger.info("google.preferences.updated", { user_id: userId, ...parsed.data }); + logger.info("google.preferences.updated", { user_id: userId, fields: Object.keys(data) }); return NextResponse.json({ default_calendar_id: (data.calendarIdSelected as string) ?? integration.calendarIdSelected, - busy_calendar_ids: parsed.data.busy_calendar_ids ?? integration.busyCalendarIds.split(",").filter(Boolean), + busy_calendar_ids: + (data.busyCalendarIds as string | undefined)?.split(",") ?? + integration.busyCalendarIds.split(",").filter(Boolean), timezone: (data.timezone as string) ?? integration.timezone, }); } diff --git a/src/app/api/integrations/google/status/route.ts b/src/app/api/integrations/google/status/route.ts index 679fd668..9d6a2151 100644 --- a/src/app/api/integrations/google/status/route.ts +++ b/src/app/api/integrations/google/status/route.ts @@ -1,41 +1,22 @@ import { NextRequest, NextResponse } from "next/server"; +import { unauthorized } from "@/lib/http"; import { getUserId } from "@/lib/auth"; -import { prisma } from "@/lib/db"; +import { logger } from "@/lib/logger"; +import { readGoogleStatus } from "@/services/google-status"; export async function GET(request: NextRequest) { const userId = await getUserId(request); if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + return unauthorized(); } - const integration = await prisma.googleIntegration.findUnique({ - where: { userId }, - }); - - if (!integration || integration.status === "DISCONNECTED") { - return NextResponse.json({ - status: "DISCONNECTED", - connected: false, - scopes: [], - default_calendar_id: "primary", - busy_calendar_ids: ["primary"], - }); + try { + return NextResponse.json(await readGoogleStatus(userId)); + } catch (err) { + logger.error("google.status_failed", { user_id: userId, error: String(err) }); + return NextResponse.json( + { error: "Google Calendar status didn't load. Retry." }, + { status: 500 }, + ); } - - return NextResponse.json({ - status: integration.status, - connected: integration.status === "CONNECTED", - connected_email: integration.connectedEmail, - scopes: integration.scopeString.split(" ").filter(Boolean), - default_calendar_id: integration.calendarIdSelected, - busy_calendar_ids: integration.busyCalendarIds.split(",").filter(Boolean), - timezone: integration.timezone, - last_healthy_at: integration.lastHealthyAt?.toISOString() ?? null, - last_error: integration.lastErrorCode - ? { code: integration.lastErrorCode, message: integration.lastErrorMessage } - : null, - // Legacy fields for backward compat - selected_calendar_id: integration.calendarIdSelected, - token_expiry: Number(integration.tokenExpiryMs), - }); } diff --git a/src/app/api/integrations/google/__test-seed/route.ts b/src/app/api/integrations/google/test-seed/route.ts similarity index 75% rename from src/app/api/integrations/google/__test-seed/route.ts rename to src/app/api/integrations/google/test-seed/route.ts index b98a1f82..9a7f1657 100644 --- a/src/app/api/integrations/google/__test-seed/route.ts +++ b/src/app/api/integrations/google/test-seed/route.ts @@ -1,20 +1,28 @@ /** * Test-only endpoint to seed a GoogleIntegration record. - * Only available when GOOGLE_PROVIDER=fake. + * Only available with GOOGLE_PROVIDER=fake and test auth enabled + * (see lib/test-auth); otherwise it answers 404. + * + * The folder name must not start with an underscore: the App Router treats + * _folders as private and never routes them. */ import { NextRequest, NextResponse } from "next/server"; import { getUserId } from "@/lib/auth"; import { prisma } from "@/lib/db"; +import { isTestAuthEnabled } from "@/lib/test-auth"; +import { unauthorized } from "@/lib/http"; + +function available(): boolean { + return process.env.GOOGLE_PROVIDER === "fake" && isTestAuthEnabled(); +} export async function POST(request: NextRequest) { - if (process.env.GOOGLE_PROVIDER !== "fake") { + if (!available()) { return NextResponse.json({ error: "Not available" }, { status: 404 }); } const userId = await getUserId(request); - if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); - } + if (!userId) return unauthorized(); let body: Record<string, unknown> = {}; try { @@ -49,14 +57,12 @@ export async function POST(request: NextRequest) { } export async function DELETE(request: NextRequest) { - if (process.env.GOOGLE_PROVIDER !== "fake") { + if (!available()) { return NextResponse.json({ error: "Not available" }, { status: 404 }); } const userId = await getUserId(request); - if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); - } + if (!userId) return unauthorized(); await prisma.googleIntegration.deleteMany({ where: { userId } }); return NextResponse.json({ deleted: true }); diff --git a/src/app/api/integrations/google/test/route.ts b/src/app/api/integrations/google/test/route.ts deleted file mode 100644 index 1c842903..00000000 --- a/src/app/api/integrations/google/test/route.ts +++ /dev/null @@ -1,87 +0,0 @@ -import { NextRequest, NextResponse } from "next/server"; -import { getUserId } from "@/lib/auth"; -import { prisma } from "@/lib/db"; -import { getGoogleClient, GoogleReconnectError } from "@/lib/google/calendar-client"; -import { logger } from "@/lib/logger"; - -export async function POST(request: NextRequest) { - const userId = await getUserId(request); - if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); - } - - const integration = await prisma.googleIntegration.findUnique({ - where: { userId }, - }); - - if (!integration || integration.status === "DISCONNECTED") { - return NextResponse.json({ ok: false, reason: "Not connected" }); - } - - const startMs = Date.now(); - logger.info("google.integration.test.started", { user_id: userId }); - - try { - const client = getGoogleClient(userId); - await client.listCalendars(); - - await prisma.googleIntegration.update({ - where: { id: integration.id }, - data: { - lastHealthyAt: new Date(), - lastErrorCode: null, - lastErrorMessage: null, - status: "CONNECTED", - }, - }); - - const durationMs = Date.now() - startMs; - logger.info("google.integration.test.completed", { - user_id: userId, - ok: true, - duration_ms: durationMs, - }); - - return NextResponse.json({ ok: true, duration_ms: durationMs }); - } catch (err) { - const reason = err instanceof Error ? err.message : String(err); - const isReconnect = err instanceof GoogleReconnectError; - const durationMs = Date.now() - startMs; - - logger.info("google.integration.test.completed", { - user_id: userId, - ok: false, - reason, - is_reconnect: isReconnect, - duration_ms: durationMs, - }); - - if (isReconnect) { - // Mark DISCONNECTED so user knows to reconnect - await prisma.googleIntegration.update({ - where: { id: integration.id }, - data: { - status: "DISCONNECTED", - lastErrorCode: "GOOGLE_RECONNECT_REQUIRED", - lastErrorMessage: "Token revoked or expired. Please reconnect.", - }, - }); - - return NextResponse.json( - { - ok: false, - error: "GOOGLE_RECONNECT_REQUIRED", - reason: "Token revoked or expired. Please reconnect your Google account.", - duration_ms: durationMs, - }, - { status: 409 }, - ); - } - - return NextResponse.json({ - ok: false, - reason: "Connection test failed. Please try again.", - duration_ms: durationMs, - }); - } -} diff --git a/src/app/api/learn/recommendations/route.ts b/src/app/api/learn/recommendations/route.ts index 7d65fc20..4fa5c610 100644 --- a/src/app/api/learn/recommendations/route.ts +++ b/src/app/api/learn/recommendations/route.ts @@ -1,46 +1,51 @@ /** - * GET /api/learn/recommendations?course_name=... + * GET /api/learn/recommendations?course_name=...&exam_name=... * - * Returns mastery-driven study recommendations for a course, - * including the best next session, overdue/weak objectives, - * error summary, streak, and plan nudges. + * The recommended next session for a course (mode, topics, reason), plus + * overdue and weak topics, unresolved errors, the streak, today's planned + * sessions and the course's exam. exam_name (optional) is the exam chosen + * in the course switcher: its plan supplies the exam and planned sessions + * when one exists. */ import { NextRequest, NextResponse } from "next/server"; +import { z } from "zod"; import { getUserId } from "@/lib/auth"; import { generalLimiter, tooManyRequests } from "@/lib/rate-limit"; import { logger } from "@/lib/logger"; import { getStudyRecommendations } from "@/services/study-recommendations"; +import { unauthorized } from "@/lib/http"; + +const querySchema = z.object({ + course_name: z.string().trim().min(1).max(200), + exam_name: z.string().trim().max(200).optional(), +}); export async function GET(request: NextRequest) { const userId = await getUserId(request); - if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); - } + if (!userId) return unauthorized(); const rl = generalLimiter.check(userId); - if (!rl.allowed) { - return tooManyRequests(rl.retryAfterMs); - } + if (!rl.allowed) return tooManyRequests(rl.retryAfterMs); - const courseName = request.nextUrl.searchParams.get("course_name"); - if (!courseName) { + const parsed = querySchema.safeParse({ + course_name: request.nextUrl.searchParams.get("course_name") ?? "", + exam_name: request.nextUrl.searchParams.get("exam_name") || undefined, + }); + if (!parsed.success) { return NextResponse.json( - { error: "course_name query parameter required" }, + { error: "Choose a course to see its next session.", code: "VALIDATION", issues: parsed.error.issues }, { status: 400 }, ); } + const courseName = parsed.data.course_name; try { - const recommendations = await getStudyRecommendations(userId, courseName); + const recommendations = await getStudyRecommendations(userId, courseName, parsed.data.exam_name || null); return NextResponse.json(recommendations); } catch (err) { - logger.error("recommendations.fetch_failed", { - userId, - courseName, - error: String(err), - }); + logger.error("recommendations.fetch_failed", { userId, courseName, error: String(err) }); return NextResponse.json( - { error: "Internal server error" }, + { error: "Recommendation didn't load. Retry.", code: "INTERNAL" }, { status: 500 }, ); } diff --git a/src/app/api/learn/route.ts b/src/app/api/learn/route.ts index 3133e33b..633d43ee 100644 --- a/src/app/api/learn/route.ts +++ b/src/app/api/learn/route.ts @@ -1,115 +1,27 @@ +/** + * GET /api/learn + * + * Per-course counts for the Study screen: materials (ready, processing, + * couldn't be read), decks and cards due, and guides. + */ import { NextRequest, NextResponse } from "next/server"; import { getUserId } from "@/lib/auth"; -import { prisma } from "@/lib/db"; import { logger } from "@/lib/logger"; +import { getStudyCourses } from "@/services/study-recommendations"; +import { unauthorized } from "@/lib/http"; export async function GET(request: NextRequest) { const userId = await getUserId(request); - if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); - } + if (!userId) return unauthorized(); try { - const docs = await prisma.contentDocument.findMany({ - where: { userId, namespace: "COURSE", courseName: { not: null } }, - select: { courseName: true, examName: true, status: true }, - }); - - const courseMap = new Map<string, { examNames: Set<string>; docCount: number; processedCount: number }>(); - for (const doc of docs) { - if (!doc.courseName) continue; - const existing = courseMap.get(doc.courseName) || { examNames: new Set(), docCount: 0, processedCount: 0 }; - existing.docCount++; - if (doc.status === "PROCESSED") existing.processedCount++; - if (doc.examName) existing.examNames.add(doc.examName); - courseMap.set(doc.courseName, existing); - } - - if (courseMap.size === 0) { - return NextResponse.json({ courses: [], hasCourses: false }); - } - - const courseNames = Array.from(courseMap.keys()); - const now = new Date(); - - const [decks, dueNewCards, dueReviewCards, guides, recentXp] = await Promise.all([ - prisma.flashcardDeck.groupBy({ - by: ["courseName"], - where: { userId, courseName: { in: courseNames } }, - _count: { id: true }, - }), - // Count new cards (never reviewed) per course via deck groupBy - prisma.flashcard.groupBy({ - by: ["deckId"], - where: { - deck: { userId, courseName: { in: courseNames } }, - nextDueAt: null, - repetitions: 0, - }, - _count: { id: true }, - }), - // Count due review cards per course via deck groupBy - prisma.flashcard.groupBy({ - by: ["deckId"], - where: { - deck: { userId, courseName: { in: courseNames } }, - nextDueAt: { lte: now }, - }, - _count: { id: true }, - }), - prisma.studyGuide.groupBy({ - by: ["courseName"], - where: { userId, courseName: { in: courseNames } }, - _count: { id: true }, - }), - prisma.xpEvent.aggregate({ - where: { - userId, - createdAt: { gte: new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000) }, - }, - _sum: { xpAmount: true }, - }), - ]); - - // Need deck → course mapping to aggregate due cards by course - const deckCourseMap = new Map<string, string>(); - const allDecks = await prisma.flashcardDeck.findMany({ - where: { userId, courseName: { in: courseNames } }, - select: { id: true, courseName: true }, - }); - for (const d of allDecks) deckCourseMap.set(d.id, d.courseName); - - const duePerCourse = new Map<string, number>(); - for (const g of [...dueNewCards, ...dueReviewCards]) { - const cn = deckCourseMap.get(g.deckId); - if (cn) duePerCourse.set(cn, (duePerCourse.get(cn) || 0) + g._count.id); - } - - const deckCountMap = new Map(decks.map((d) => [d.courseName, d._count.id])); - const guideCountMap = new Map(guides.map((g) => [g.courseName, g._count.id])); - - const courses = courseNames.map((name) => { - const info = courseMap.get(name)!; - return { - courseName: name, - examNames: Array.from(info.examNames), - docCount: info.docCount, - processedDocCount: info.processedCount, - deckCount: deckCountMap.get(name) || 0, - dueCardCount: duePerCourse.get(name) || 0, - guideCount: guideCountMap.get(name) || 0, - }; - }); - - courses.sort((a, b) => b.dueCardCount - a.dueCardCount || b.docCount - a.docCount); - - return NextResponse.json({ - courses, - hasCourses: true, - weeklyXp: recentXp._sum.xpAmount || 0, - }); + const courses = await getStudyCourses(userId); + return NextResponse.json({ courses, hasCourses: courses.length > 0 }); } catch (err) { logger.error("learn.fetch_failed", { userId, error: String(err) }); - return NextResponse.json({ error: "Internal server error" }, { status: 500 }); + return NextResponse.json( + { error: "Courses didn't load. Retry.", code: "INTERNAL" }, + { status: 500 }, + ); } } diff --git a/src/app/api/learn/start/route.ts b/src/app/api/learn/start/route.ts new file mode 100644 index 00000000..44ee9d7c --- /dev/null +++ b/src/app/api/learn/start/route.ts @@ -0,0 +1,79 @@ +/** + * POST /api/learn/start + * + * Starts a session from the Study screen: the recommended topics for the + * course in the mode and length the student picked. Reuses an identical + * session created in the last few hours that was never started, so a + * second click or a return visit doesn't pile up empty sessions. + * + * Body: { course_name, exam_name?, mode, minutes } + * 201: { session_id, url: "/s/<id>", reused } + */ +import { NextRequest, NextResponse } from "next/server"; +import { z } from "zod"; +import { getUserId } from "@/lib/auth"; +import { generalLimiter, tooManyRequests } from "@/lib/rate-limit"; +import { logger } from "@/lib/logger"; +import { startStudySession, StudyStartError } from "@/services/study-recommendations"; +import { + isSessionLength, + STUDY_MODE_KEYS, + type SessionLength, +} from "@/lib/study-modes"; +import { unauthorized } from "@/lib/http"; + +const startSchema = z.object({ + course_name: z.string().trim().min(1).max(200), + exam_name: z.string().trim().min(1).max(200).optional(), + mode: z.enum(STUDY_MODE_KEYS), + minutes: z.custom<SessionLength>((value) => isSessionLength(value)), +}); + +export async function POST(request: NextRequest) { + const userId = await getUserId(request); + if (!userId) return unauthorized(); + + const rl = generalLimiter.check(userId); + if (!rl.allowed) return tooManyRequests(rl.retryAfterMs); + + let body: unknown; + try { + body = await request.json(); + } catch { + return NextResponse.json( + { error: "Session not started. Reload the page and retry.", code: "INVALID_JSON" }, + { status: 400 }, + ); + } + + const parsed = startSchema.safeParse(body); + if (!parsed.success) { + return NextResponse.json( + { error: "Choose a course, a mode, and a length.", code: "VALIDATION", issues: parsed.error.issues }, + { status: 400 }, + ); + } + + const { course_name, exam_name, mode, minutes } = parsed.data; + try { + const result = await startStudySession(userId, { + courseName: course_name, + examName: exam_name, + mode, + minutes, + }); + return NextResponse.json(result, { status: result.reused ? 200 : 201 }); + } catch (err) { + if (err instanceof StudyStartError) { + return NextResponse.json( + { error: err.message, code: err.code }, + { status: err.code === "COURSE_NOT_FOUND" ? 404 : 409 }, + ); + } + logger.error("study.start_failed", { userId, error: String(err) }); + return NextResponse.json( + { error: "Session not started. Retry.", code: "INTERNAL" }, + { status: 500 }, + ); + } +} diff --git a/src/app/api/mastery/route.ts b/src/app/api/mastery/route.ts deleted file mode 100644 index d91a9243..00000000 --- a/src/app/api/mastery/route.ts +++ /dev/null @@ -1,46 +0,0 @@ -/** - * GET /api/mastery?course_name=X — mastery summary for a course. - */ -import { NextRequest, NextResponse } from "next/server"; -import { getUserId } from "@/lib/auth"; -import { getMasterySummary } from "@/lib/mastery"; -import { logger } from "@/lib/logger"; - -export async function GET(request: NextRequest) { - const userId = await getUserId(request); - if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); - } - - const courseName = request.nextUrl.searchParams.get("course_name"); - if (!courseName) { - return NextResponse.json({ error: "course_name query parameter required" }, { status: 400 }); - } - - try { - const summary = await getMasterySummary(userId, courseName); - - // Derive top-10 due objectives from the already-fetched list (avoids a second query) - const dueObjectives = summary.objectives - .filter((o) => o.is_due) - .sort((a, b) => (a.next_due_at ?? "").localeCompare(b.next_due_at ?? "")) - .slice(0, 10); - - return NextResponse.json({ - course_name: courseName, - total: summary.total, - mastered: summary.mastered, - due: summary.due, - due_objectives: dueObjectives.map((o) => ({ - objective_key: o.objective_key, - next_due_at: o.next_due_at, - last_accuracy: o.last_accuracy, - interval_days: o.interval_days, - })), - objectives: summary.objectives, - }); - } catch (err) { - logger.error("mastery.get_failed", { userId, courseName, error: String(err) }); - return NextResponse.json({ error: "Internal server error" }, { status: 500 }); - } -} diff --git a/src/app/api/onboarding/route.ts b/src/app/api/onboarding/route.ts index 1ce4c025..e0c3da62 100644 --- a/src/app/api/onboarding/route.ts +++ b/src/app/api/onboarding/route.ts @@ -1,14 +1,19 @@ import { NextRequest, NextResponse } from "next/server"; +import { unauthorized } from "@/lib/http"; import { getUserId } from "@/lib/auth"; import { prisma } from "@/lib/db"; +import { logger } from "@/lib/logger"; /** - * GET /api/onboarding — check if user has completed onboarding. + * GET /api/onboarding: whether the student finished onboarding. + * + * Home no longer opens an onboarding dialog: a student with no plan and no + * materials sees the first-run panel instead. The flag stays for API clients. */ export async function GET(request: NextRequest) { const userId = await getUserId(request); if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + return unauthorized(); } try { @@ -20,18 +25,19 @@ export async function GET(request: NextRequest) { return NextResponse.json({ complete: state?.onboardingComplete ?? false, }); - } catch { - return NextResponse.json({ error: "Internal server error" }, { status: 500 }); + } catch (err) { + logger.error("onboarding.read_failed", { userId, error: String(err) }); + return NextResponse.json({ error: "Onboarding status didn't load. Retry." }, { status: 500 }); } } /** - * POST /api/onboarding — mark onboarding as complete. + * POST /api/onboarding: mark onboarding as finished. No body. */ export async function POST(request: NextRequest) { const userId = await getUserId(request); if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + return unauthorized(); } try { @@ -42,7 +48,8 @@ export async function POST(request: NextRequest) { }); return NextResponse.json({ complete: true }); - } catch { - return NextResponse.json({ error: "Internal server error" }, { status: 500 }); + } catch (err) { + logger.error("onboarding.write_failed", { userId, error: String(err) }); + return NextResponse.json({ error: "Onboarding status not saved. Retry." }, { status: 500 }); } } diff --git a/src/app/api/plans/[planId]/feed/route.ts b/src/app/api/plans/[planId]/feed/route.ts deleted file mode 100644 index 9c479486..00000000 --- a/src/app/api/plans/[planId]/feed/route.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { NextRequest, NextResponse } from "next/server"; -import { prisma } from "@/lib/db"; -import { generatePlanIcs } from "@/services/plan"; - -/** - * Public ICS feed endpoint for webcal:// subscription. - * No X-User-Id header required — uses planId as implicit auth - * (plan IDs are unguessable UUIDs). - * - * Usage: webcal://host/api/plans/{planId}/feed - * Google Calendar and other clients can subscribe to this URL. - */ -export async function GET( - _request: NextRequest, - { params }: { params: Promise<{ planId: string }> } -) { - const { planId } = await params; - - // Look up the plan to get the userId (needed by generatePlanIcs) - const plan = await prisma.studyPlan.findUnique({ - where: { planId }, - select: { userId: true }, - }); - - if (!plan) { - return NextResponse.json({ error: "Plan not found" }, { status: 404 }); - } - - const result = await generatePlanIcs(plan.userId, planId); - - if ("error" in result) { - return NextResponse.json({ error: "Plan not found" }, { status: 404 }); - } - - return new NextResponse(result.data as string, { - status: 200, - headers: { - "Content-Type": "text/calendar; charset=utf-8", - "Cache-Control": "public, max-age=300", - }, - }); -} diff --git a/src/app/api/plans/[planId]/ics/route.ts b/src/app/api/plans/[planId]/ics/route.ts index e9cb9f91..b7071d23 100644 --- a/src/app/api/plans/[planId]/ics/route.ts +++ b/src/app/api/plans/[planId]/ics/route.ts @@ -1,6 +1,7 @@ import { NextRequest, NextResponse } from "next/server"; import { getUserId } from "@/lib/auth"; import { generatePlanIcs } from "@/services/plan"; +import { unauthorized } from "@/lib/http"; export async function GET( request: NextRequest, @@ -8,7 +9,7 @@ export async function GET( ) { const userId = await getUserId(request); if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + return unauthorized(); } const { planId } = await params; @@ -16,16 +17,23 @@ export async function GET( if ("error" in result) { if (result.error === "not_found") { - return NextResponse.json({ error: "Plan not found" }, { status: 404 }); + return NextResponse.json( + { error: "This plan doesn't exist anymore.", code: "not_found" }, + { status: 404 }, + ); } - return NextResponse.json({ error: "Forbidden" }, { status: 403 }); + return NextResponse.json( + { error: "This plan belongs to another account.", code: "forbidden" }, + { status: 403 }, + ); } return new NextResponse(result.data as string, { status: 200, headers: { "Content-Type": "text/calendar; charset=utf-8", - "Content-Disposition": `attachment; filename="study-plan-${planId}.ics"`, + "Content-Disposition": `attachment; filename="${result.filename}"`, + "Cache-Control": "private, no-store", }, }); } diff --git a/src/app/api/plans/[planId]/items/[itemId]/status/route.ts b/src/app/api/plans/[planId]/items/[itemId]/status/route.ts index 90ebb3a5..7398a75e 100644 --- a/src/app/api/plans/[planId]/items/[itemId]/status/route.ts +++ b/src/app/api/plans/[planId]/items/[itemId]/status/route.ts @@ -1,8 +1,9 @@ import { NextRequest, NextResponse } from "next/server"; import { getUserId } from "@/lib/auth"; import { prisma } from "@/lib/db"; -import { z } from "zod/v4"; +import { z } from "zod"; import { ITEM_STATUSES } from "@/services/reflow"; +import { unauthorized } from "@/lib/http"; const updateStatusSchema = z.object({ status: z.enum(ITEM_STATUSES), @@ -16,21 +17,27 @@ export async function POST( ) { const userId = await getUserId(req); if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + return unauthorized(); } const { planId, itemId } = await params; // Verify plan ownership const plan = await prisma.studyPlan.findUnique({ where: { planId } }); - if (!plan) return NextResponse.json({ error: "Plan not found" }, { status: 404 }); - if (plan.userId !== userId) return NextResponse.json({ error: "Forbidden" }, { status: 403 }); + if (!plan) { + return NextResponse.json({ error: "This plan doesn't exist anymore.", code: "not_found" }, { status: 404 }); + } + if (plan.userId !== userId) { + return NextResponse.json({ error: "This plan belongs to another account.", code: "forbidden" }, { status: 403 }); + } // Verify item belongs to plan const item = await prisma.studyPlanItem.findFirst({ where: { id: itemId, planId }, }); - if (!item) return NextResponse.json({ error: "Item not found" }, { status: 404 }); + if (!item) { + return NextResponse.json({ error: "This session isn't in the plan anymore.", code: "item_not_found" }, { status: 404 }); + } // Parse body let body: z.infer<typeof updateStatusSchema>; @@ -38,9 +45,12 @@ export async function POST( body = updateStatusSchema.parse(await req.json()); } catch (err) { if (err instanceof z.ZodError) { - return NextResponse.json({ error: "Validation error", details: err.issues }, { status: 400 }); + return NextResponse.json( + { error: "That session status isn't valid.", code: "validation_failed", details: err.issues }, + { status: 400 }, + ); } - return NextResponse.json({ error: "Invalid JSON" }, { status: 400 }); + return NextResponse.json({ error: "The request wasn't valid JSON.", code: "INVALID_JSON" }, { status: 400 }); } // Build update data diff --git a/src/app/api/plans/[planId]/publish/google/route.ts b/src/app/api/plans/[planId]/publish/google/route.ts index 6e3a45e2..c44bcd28 100644 --- a/src/app/api/plans/[planId]/publish/google/route.ts +++ b/src/app/api/plans/[planId]/publish/google/route.ts @@ -1,11 +1,25 @@ import { NextRequest, NextResponse } from "next/server"; import { getUserId } from "@/lib/auth"; +import { generalLimiter, tooManyRequests } from "@/lib/rate-limit"; import { publishPlanToGoogle, getPublishStatus, publishRequestSchema, + calendarErrorMessage, } from "@/services/publish"; import { logger } from "@/lib/logger"; +import { unauthorized } from "@/lib/http"; + +/** + * Errors keep the machine code in `error` (API clients and tests match on + * it) and repeat it as `code`; `message` is the sentence to show. + */ +function errorResponse(code: string, status: number, extra: Record<string, unknown> = {}) { + return NextResponse.json( + { error: code, code, message: calendarErrorMessage(code), ...extra }, + { status }, + ); +} export async function POST( request: NextRequest, @@ -13,22 +27,31 @@ export async function POST( ) { const userId = await getUserId(request); if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + return unauthorized(); } + // Calls Google Calendar for every session in the plan + const rl = generalLimiter.check(userId); + if (!rl.allowed) return tooManyRequests(rl.retryAfterMs); + const { planId } = await params; let body: Record<string, unknown> = {}; try { body = await request.json(); } catch { - // Empty body is fine — all fields optional + // Empty body is fine: all fields optional } const parsed = publishRequestSchema.safeParse(body); if (!parsed.success) { return NextResponse.json( - { error: "Invalid request", details: parsed.error.issues }, + { + error: "Invalid request", + code: "validation_failed", + message: "The calendar options weren't valid.", + details: parsed.error.issues, + }, { status: 400 }, ); } @@ -41,20 +64,24 @@ export async function POST( }); if ("error" in result) { - const status = result.status || 500; - return NextResponse.json( - { - error: result.error, - ...(result.current_calendar_id ? { current_calendar_id: result.current_calendar_id } : {}), - }, - { status }, + return errorResponse( + result.error, + result.status || 500, + result.current_calendar_id ? { current_calendar_id: result.current_calendar_id } : {}, ); } return NextResponse.json(result.data); } catch (err) { logger.error("api.publish_google_failed", { user_id: userId, plan_id: planId, error: String(err) }); - return NextResponse.json({ error: "Internal server error" }, { status: 500 }); + return NextResponse.json( + { + error: "Sessions weren't added to Google Calendar. Retry in a minute.", + code: "internal", + message: "Sessions weren't added to Google Calendar. Retry in a minute.", + }, + { status: 500 }, + ); } } @@ -64,7 +91,7 @@ export async function GET( ) { const userId = await getUserId(request); if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + return unauthorized(); } const { planId } = await params; @@ -73,13 +100,19 @@ export async function GET( const result = await getPublishStatus(userId, planId); if ("error" in result) { - const status = result.status || 500; - return NextResponse.json({ error: result.error }, { status }); + return errorResponse(result.error, result.status || 500); } return NextResponse.json(result.data); } catch (err) { logger.error("api.publish_status_failed", { user_id: userId, plan_id: planId, error: String(err) }); - return NextResponse.json({ error: "Internal server error" }, { status: 500 }); + return NextResponse.json( + { + error: "The Google Calendar status didn't load. Retry in a minute.", + code: "internal", + message: "The Google Calendar status didn't load. Retry in a minute.", + }, + { status: 500 }, + ); } } diff --git a/src/app/api/plans/[planId]/reflow/apply/route.ts b/src/app/api/plans/[planId]/reflow/apply/route.ts index bdbe586e..b8c66dc7 100644 --- a/src/app/api/plans/[planId]/reflow/apply/route.ts +++ b/src/app/api/plans/[planId]/reflow/apply/route.ts @@ -1,147 +1,55 @@ import { NextRequest, NextResponse } from "next/server"; +import { z } from "zod"; import { getUserId } from "@/lib/auth"; +import { unauthorized } from "@/lib/http"; +import { generalLimiter, tooManyRequests } from "@/lib/rate-limit"; import { prisma } from "@/lib/db"; -import { computeReflow, ReflowItem, ReflowConfig } from "@/services/reflow"; -import { z } from "zod/v4"; -import { getGoogleClient, GoogleReconnectError, type BusyInterval } from "@/lib/google/calendar-client"; -import { type TimeInterval } from "@/lib/google/free-slots"; import { logger } from "@/lib/logger"; - -const applySchema = z.object({ - reason: z.string().optional().default("MANUAL"), - from_time: z.string().optional(), - only_future: z.boolean().optional().default(true), - respect_google_busy: z.boolean().optional().default(true), - calendar_ids: z.array(z.string()).optional(), - buffer_minutes: z.number().min(0).max(60).optional().default(10), - calendar_update: z.enum(["NONE", "REPUBLISH"]).optional().default("REPUBLISH"), - // Legacy compat +import { calendarErrorMessage, publishPlanToGoogle } from "@/services/publish"; +import { parseReflowBody, prepareReflow, reflowRequestSchema, summarize } from "../shared"; + +const applySchema = reflowRequestSchema.extend({ + /** + * Whether to update the plan's events in Google Calendar after moving + * sessions. Nothing in Google Calendar changes unless this is REPUBLISH, + * and only for a plan that is already in Google Calendar. + */ + calendar_update: z.enum(["NONE", "REPUBLISH"]).optional(), + // Legacy compat: republish: true means calendar_update: "REPUBLISH" republish: z.boolean().optional(), }); +/** + * POST /api/plans/{planId}/reflow/apply + * + * Moves sessions as the preview showed: moved items become RESCHEDULED + * (keeping their original times), sessions that don't fit become SKIPPED. + */ export async function POST( req: NextRequest, { params }: { params: Promise<{ planId: string }> }, ) { const userId = await getUserId(req); if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); - } - - const { planId } = await params; - - // Parse body - let body: z.infer<typeof applySchema>; - try { - const raw = await req.json().catch(() => ({})); - body = applySchema.parse(raw); - } catch (err) { - if (err instanceof z.ZodError) { - return NextResponse.json({ error: "Validation error", details: err.issues }, { status: 400 }); - } - return NextResponse.json({ error: "Invalid JSON" }, { status: 400 }); - } - - // Resolve calendar_update from legacy `republish` boolean - const shouldRepublish = - body.calendar_update === "REPUBLISH" || body.republish === true; - - const plan = await prisma.studyPlan.findUnique({ - where: { planId }, - include: { items: { orderBy: [{ dayIndex: "asc" }, { startTime: "asc" }] } }, - }); - - if (!plan) return NextResponse.json({ error: "Plan not found" }, { status: 404 }); - if (plan.userId !== userId) return NextResponse.json({ error: "Forbidden" }, { status: 403 }); - - // Load sessions for mode info - const sessionIds = plan.items.map((i) => i.sessionId); - const sessions = await prisma.session.findMany({ - where: { sessionId: { in: sessionIds } }, - }); - const sessionMap = new Map(sessions.map((s) => [s.sessionId, s])); - - // Build reflow items - const reflowItems: ReflowItem[] = plan.items.map((item) => { - const session = sessionMap.get(item.sessionId); - return { - id: item.id, - sessionId: item.sessionId, - dayIndex: item.dayIndex, - startTime: item.startTime, - endTime: item.endTime, - status: item.status, - locked: item.locked, - mode: session?.mode ?? "RETRIEVAL", - plannedMinutes: session?.plannedMinutes ?? 60, - }; - }); - - const config = plan.config as Record<string, unknown>; - const reflowConfig: ReflowConfig = { - availability: (config.availability as { start: string; end: string }[]) ?? - Array.from({ length: 7 }, () => ({ start: "09:00", end: "17:00" })), - daily_study_cap_minutes: (config.daily_study_cap_minutes as number) ?? 180, - }; - - const now = body.from_time ? new Date(body.from_time) : new Date(); - if (isNaN(now.getTime())) { - return NextResponse.json( - { error: "from_time must be a valid date string" }, - { status: 400 }, - ); + return unauthorized(); } - // Optionally fetch Google Calendar busy blocks - let busyIntervals: TimeInterval[] = []; - if (body.respect_google_busy) { - try { - const integration = await prisma.googleIntegration.findUnique({ - where: { userId }, - }); + // Each preview and apply reads Google Calendar free/busy + const rl = generalLimiter.check(userId); + if (!rl.allowed) return tooManyRequests(rl.retryAfterMs); - if (integration && integration.status === "CONNECTED") { - const client = getGoogleClient(userId); - const calendarIds = body.calendar_ids?.length - ? body.calendar_ids - : integration.busyCalendarIds.split(",").filter(Boolean); - - const planEndDate = new Date(plan.startDate); - planEndDate.setDate(planEndDate.getDate() + reflowConfig.availability.length); - - const busy: BusyInterval[] = await client.freebusyQuery({ - timeMin: now.toISOString(), - timeMax: planEndDate.toISOString(), - calendarIds, - }); + const { planId } = await params; - busyIntervals = busy.map((b) => ({ - start: new Date(b.start).getTime(), - end: new Date(b.end).getTime(), - })); + const parsed = await parseReflowBody(req, applySchema); + if ("response" in parsed) return parsed.response; + const body = parsed.body; - if (body.buffer_minutes > 0) { - const bufferMs = body.buffer_minutes * 60 * 1000; - busyIntervals = busyIntervals.map((b) => ({ - start: b.start - bufferMs, - end: b.end + bufferMs, - })); - } - } - } catch (err) { - if (err instanceof GoogleReconnectError) { - return NextResponse.json( - { error: "GOOGLE_RECONNECT_REQUIRED", message: "Please reconnect your Google account." }, - { status: 409 }, - ); - } - logger.warn("reflow.apply.busy_fetch_failed", { plan_id: planId, error: String(err) }); - } - } + const shouldRepublish = body.calendar_update === "REPUBLISH" || body.republish === true; - const result = computeReflow(reflowItems, reflowConfig, plan.startDate, now, busyIntervals); + const prepared = await prepareReflow(userId, planId, body, "reflow.apply"); + if ("response" in prepared) return prepared.response; + const { plan, reflowItems, result, now, busyIntervals } = prepared; - // Apply changes in a transaction const movedChanges = result.changes.filter((c) => c.action === "MOVED"); const droppedChanges = result.changes.filter((c) => c.action === "DROPPED"); @@ -149,18 +57,21 @@ export async function POST( return NextResponse.json({ plan_id: planId, applied: false, - message: "No changes needed", + message: "Nothing to reschedule.", changes: result.changes, warnings: result.warnings, + summary: summarize(result, plan.items.length), + calendar: null, }); } let auditId: string | null = null; + const itemById = new Map(plan.items.map((item) => [item.id, item])); - await prisma.$transaction(async (tx: any) => { + await prisma.$transaction(async (tx) => { // Apply MOVED items for (const change of movedChanges) { - const item = plan.items.find((i) => i.id === change.itemId)!; + const item = itemById.get(change.itemId)!; await tx.studyPlanItem.update({ where: { id: change.itemId }, data: { @@ -175,9 +86,9 @@ export async function POST( }); } - // Mark DROPPED items as SKIPPED + // Sessions that don't fit are SKIPPED for (const change of droppedChanges) { - const item = plan.items.find((i) => i.id === change.itemId)!; + const item = itemById.get(change.itemId)!; await tx.studyPlanItem.update({ where: { id: change.itemId }, data: { @@ -189,7 +100,6 @@ export async function POST( }); } - // Create audit record const audit = await tx.planReflowAudit.create({ data: { userId, @@ -198,10 +108,9 @@ export async function POST( algorithmVersion: result.algorithmVersion, inputSummary: { totalItems: plan.items.length, - movableCount: reflowItems.filter((i) => - i.status === "SCHEDULED" && !i.locked && i.endTime.getTime() > now.getTime() - ).length, - fixedCount: reflowItems.length - movedChanges.length - droppedChanges.length, + movableCount: result.changes.length, + fixedCount: reflowItems.length - result.changes.length, + include_missed: body.include_missed, respect_google_busy: body.respect_google_busy, busy_intervals_count: busyIntervals.length, }, @@ -218,26 +127,45 @@ export async function POST( moved: movedChanges.length, dropped: droppedChanges.length, reason: body.reason, + calendar_update: shouldRepublish ? "REPUBLISH" : "NONE", }); - // Post-commit: optionally trigger Google republish - let calendarResult = null; + // Post-commit: update Google Calendar only when asked, and only for a plan + // that is already there. Never publish a plan as a side effect. + let calendarResult: Record<string, unknown> | null = null; if (shouldRepublish) { - try { - const { publishPlanToGoogle } = await import("@/services/publish"); - const pubResult = await publishPlanToGoogle(userId, planId); - if ("data" in pubResult) { + const publication = await prisma.planCalendarPublication.findUnique({ + where: { provider_planId: { provider: "GOOGLE", planId } }, + select: { status: true }, + }); + const published = publication?.status === "PUBLISHED" || publication?.status === "PARTIAL"; + + if (!published) { + calendarResult = { status: "NOT_PUBLISHED" }; + } else { + try { + const pubResult = await publishPlanToGoogle(userId, planId); + if ("data" in pubResult) { + calendarResult = { + status: pubResult.data.status, + summary: pubResult.data.summary, + duration_ms: pubResult.data.duration_ms, + }; + } else { + calendarResult = { + status: "FAILED", + code: pubResult.error, + error: calendarErrorMessage(pubResult.error), + }; + } + } catch (err) { + logger.error("reflow.republish_failed", { plan_id: planId, error: String(err) }); calendarResult = { - status: pubResult.data.status, - summary: pubResult.data.summary, - duration_ms: pubResult.data.duration_ms, + status: "FAILED", + code: "unknown", + error: "Google Calendar wasn't updated. Retry from the plan's calendar options.", }; - } else { - calendarResult = { error: pubResult.error }; } - } catch (err) { - logger.error("reflow.republish_failed", { plan_id: planId, error: String(err) }); - calendarResult = { error: String(err) }; } } diff --git a/src/app/api/plans/[planId]/reflow/preview/route.ts b/src/app/api/plans/[planId]/reflow/preview/route.ts index 0998f1a0..7c211ff6 100644 --- a/src/app/api/plans/[planId]/reflow/preview/route.ts +++ b/src/app/api/plans/[planId]/reflow/preview/route.ts @@ -1,142 +1,38 @@ import { NextRequest, NextResponse } from "next/server"; import { getUserId } from "@/lib/auth"; -import { prisma } from "@/lib/db"; -import { computeReflow, ReflowItem, ReflowConfig } from "@/services/reflow"; -import { z } from "zod/v4"; -import { getGoogleClient, GoogleReconnectError, type BusyInterval } from "@/lib/google/calendar-client"; -import { type TimeInterval } from "@/lib/google/free-slots"; -import { logger } from "@/lib/logger"; - -const previewSchema = z.object({ - reason: z.string().optional().default("MANUAL"), - from_time: z.string().optional(), - only_future: z.boolean().optional().default(true), - respect_google_busy: z.boolean().optional().default(true), - calendar_ids: z.array(z.string()).optional(), - buffer_minutes: z.number().min(0).max(60).optional().default(10), -}); - +import { unauthorized } from "@/lib/http"; +import { generalLimiter, tooManyRequests } from "@/lib/rate-limit"; +import { parseReflowBody, prepareReflow, reflowRequestSchema, summarize } from "../shared"; + +/** + * POST /api/plans/{planId}/reflow/preview + * + * The moves a reschedule would make, without changing anything. With + * `include_missed: true` (the Plan screen), missed sessions move as well and + * every session must land before the exam day. + */ export async function POST( req: NextRequest, { params }: { params: Promise<{ planId: string }> }, ) { const userId = await getUserId(req); if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + return unauthorized(); } - const { planId } = await params; - - // Parse body - let body: z.infer<typeof previewSchema>; - try { - const raw = await req.json().catch(() => ({})); - body = previewSchema.parse(raw); - } catch (err) { - if (err instanceof z.ZodError) { - return NextResponse.json({ error: "Validation error", details: err.issues }, { status: 400 }); - } - return NextResponse.json({ error: "Invalid JSON" }, { status: 400 }); - } + // Each preview and apply reads Google Calendar free/busy + const rl = generalLimiter.check(userId); + if (!rl.allowed) return tooManyRequests(rl.retryAfterMs); - const plan = await prisma.studyPlan.findUnique({ - where: { planId }, - include: { items: { orderBy: [{ dayIndex: "asc" }, { startTime: "asc" }] } }, - }); - - if (!plan) return NextResponse.json({ error: "Plan not found" }, { status: 404 }); - if (plan.userId !== userId) return NextResponse.json({ error: "Forbidden" }, { status: 403 }); - - // Load sessions for mode info - const sessionIds = plan.items.map((i) => i.sessionId); - const sessions = await prisma.session.findMany({ - where: { sessionId: { in: sessionIds } }, - }); - const sessionMap = new Map(sessions.map((s) => [s.sessionId, s])); - - // Build reflow items - const reflowItems: ReflowItem[] = plan.items.map((item) => { - const session = sessionMap.get(item.sessionId); - return { - id: item.id, - sessionId: item.sessionId, - dayIndex: item.dayIndex, - startTime: item.startTime, - endTime: item.endTime, - status: item.status, - locked: item.locked, - mode: session?.mode ?? "RETRIEVAL", - plannedMinutes: session?.plannedMinutes ?? 60, - }; - }); - - const config = plan.config as Record<string, unknown>; - const reflowConfig: ReflowConfig = { - availability: (config.availability as { start: string; end: string }[]) ?? - Array.from({ length: 7 }, () => ({ start: "09:00", end: "17:00" })), - daily_study_cap_minutes: (config.daily_study_cap_minutes as number) ?? 180, - }; - - const now = body.from_time ? new Date(body.from_time) : new Date(); - if (isNaN(now.getTime())) { - return NextResponse.json( - { error: "from_time must be a valid date string" }, - { status: 400 }, - ); - } - - // Optionally fetch Google Calendar busy blocks - let busyIntervals: TimeInterval[] = []; - if (body.respect_google_busy) { - try { - const integration = await prisma.googleIntegration.findUnique({ - where: { userId }, - }); - - if (integration && integration.status === "CONNECTED") { - const client = getGoogleClient(userId); - const calendarIds = body.calendar_ids?.length - ? body.calendar_ids - : integration.busyCalendarIds.split(",").filter(Boolean); - - // Query busy for the plan's date range - const planEndDate = new Date(plan.startDate); - planEndDate.setDate(planEndDate.getDate() + reflowConfig.availability.length); - - const busy: BusyInterval[] = await client.freebusyQuery({ - timeMin: now.toISOString(), - timeMax: planEndDate.toISOString(), - calendarIds, - }); - - busyIntervals = busy.map((b) => ({ - start: new Date(b.start).getTime(), - end: new Date(b.end).getTime(), - })); + const { planId } = await params; - // Apply buffer: expand each busy block by buffer_minutes on each side - if (body.buffer_minutes > 0) { - const bufferMs = body.buffer_minutes * 60 * 1000; - busyIntervals = busyIntervals.map((b) => ({ - start: b.start - bufferMs, - end: b.end + bufferMs, - })); - } - } - // If not connected, just skip busy — don't error on preview - } catch (err) { - if (err instanceof GoogleReconnectError) { - return NextResponse.json( - { error: "GOOGLE_RECONNECT_REQUIRED", message: "Please reconnect your Google account." }, - { status: 409 }, - ); - } - // Non-fatal: log and continue without busy data - logger.warn("reflow.preview.busy_fetch_failed", { plan_id: planId, error: String(err) }); - } - } + const parsed = await parseReflowBody(req, reflowRequestSchema); + if ("response" in parsed) return parsed.response; + const body = parsed.body; - const result = computeReflow(reflowItems, reflowConfig, plan.startDate, now, busyIntervals); + const prepared = await prepareReflow(userId, planId, body, "reflow.preview"); + if ("response" in prepared) return prepared.response; + const { plan, result } = prepared; return NextResponse.json({ plan_id: planId, @@ -144,11 +40,6 @@ export async function POST( algorithm_version: result.algorithmVersion, changes: result.changes, warnings: result.warnings, - summary: { - total_items: plan.items.length, - moved: result.changes.filter((c) => c.action === "MOVED").length, - kept: result.changes.filter((c) => c.action === "KEPT").length, - dropped: result.changes.filter((c) => c.action === "DROPPED").length, - }, + summary: summarize(result, plan.items.length), }); } diff --git a/src/app/api/plans/[planId]/reflow/shared.ts b/src/app/api/plans/[planId]/reflow/shared.ts new file mode 100644 index 00000000..762b4db9 --- /dev/null +++ b/src/app/api/plans/[planId]/reflow/shared.ts @@ -0,0 +1,238 @@ +import { NextResponse } from "next/server"; +import { z } from "zod"; +import { prisma } from "@/lib/db"; +import { + computeReflow, + subtractIntervals, + type ReflowConfig, + type ReflowItem, + type ReflowResult, +} from "@/services/reflow"; +import { addDays, zonedTimeToUtc } from "@/lib/timezone"; +import { dateColumnKey } from "@/lib/plan-dates"; +import { getGoogleClient, GoogleReconnectError, type BusyInterval } from "@/lib/google/calendar-client"; +import { GOOGLE_COPY } from "@/lib/google/messages"; +import { type TimeInterval } from "@/lib/google/free-slots"; +import { logger } from "@/lib/logger"; + +/** Fields shared by the reflow preview and apply requests. */ +export const reflowRequestSchema = z.object({ + reason: z.string().max(64).optional().default("MANUAL"), + from_time: z.string().optional(), + only_future: z.boolean().optional().default(true), + respect_google_busy: z.boolean().optional().default(true), + calendar_ids: z.array(z.string()).optional(), + buffer_minutes: z.number().min(0).max(60).optional().default(10), + /** + * The Plan screen's "Reschedule sessions": also move missed sessions, and + * keep every session before the exam day (the ones that don't fit are + * skipped). Off by default so existing API callers keep the old behavior. + */ + include_missed: z.boolean().optional().default(false), +}); + +export type ReflowRequest = z.infer<typeof reflowRequestSchema>; + +type PlanWithItems = NonNullable<Awaited<ReturnType<typeof findPlan>>>; + +function findPlan(planId: string) { + return prisma.studyPlan.findUnique({ + where: { planId }, + include: { items: { orderBy: [{ dayIndex: "asc" }, { startTime: "asc" }] } }, + }); +} + +export function jsonError(status: number, error: string, code: string, extra: Record<string, unknown> = {}) { + return NextResponse.json({ error, code, ...extra }, { status }); +} + +/** Parse a reflow request body; returns a 400 response when it is invalid. */ +export async function parseReflowBody<T extends z.ZodTypeAny>( + req: Request, + schema: T, +): Promise<{ body: z.infer<T> } | { response: NextResponse }> { + let raw: unknown = {}; + try { + const text = await req.text(); + raw = text ? JSON.parse(text) : {}; + } catch { + return { response: jsonError(400, "The request wasn't valid JSON.", "INVALID_JSON") }; + } + const parsed = schema.safeParse(raw); + if (!parsed.success) { + return { + response: jsonError(400, "The reschedule options weren't valid.", "validation_failed", { + details: parsed.error.issues, + }), + }; + } + return { body: parsed.data }; +} + +export interface PreparedReflow { + plan: PlanWithItems; + reflowItems: ReflowItem[]; + result: ReflowResult; + now: Date; + busyIntervals: TimeInterval[]; +} + +/** + * Load a plan the user owns, gather Google busy time when asked, and compute + * the reflow. Returns an error response for a missing plan, another + * account's plan, a bad from_time, or a Google sign-in that expired. + */ +export async function prepareReflow( + userId: string, + planId: string, + body: ReflowRequest, + logPrefix: string, +): Promise<PreparedReflow | { response: NextResponse }> { + const plan = await findPlan(planId); + + if (!plan) { + return { response: jsonError(404, "This plan doesn't exist anymore.", "not_found") }; + } + if (plan.userId !== userId) { + return { response: jsonError(403, "This plan belongs to another account.", "forbidden") }; + } + + // Load sessions for mode info + const sessionIds = plan.items.map((i) => i.sessionId); + const sessions = await prisma.session.findMany({ + where: { sessionId: { in: sessionIds } }, + select: { sessionId: true, mode: true, plannedMinutes: true }, + }); + const sessionMap = new Map(sessions.map((s) => [s.sessionId, s])); + + const reflowItems: ReflowItem[] = plan.items.map((item) => { + const session = sessionMap.get(item.sessionId); + return { + id: item.id, + sessionId: item.sessionId, + dayIndex: item.dayIndex, + startTime: item.startTime, + endTime: item.endTime, + status: item.status, + locked: item.locked, + mode: session?.mode ?? "RETRIEVAL", + plannedMinutes: session?.plannedMinutes ?? 60, + }; + }); + + const config = (plan.config ?? {}) as Record<string, unknown>; + const reflowConfig: ReflowConfig = { + availability: + (config.availability as { start: string; end: string }[] | undefined) ?? + Array.from({ length: 7 }, () => ({ start: "09:00", end: "17:00" })), + daily_study_cap_minutes: (config.daily_study_cap_minutes as number | undefined) ?? 180, + }; + + const now = body.from_time ? new Date(body.from_time) : new Date(); + if (isNaN(now.getTime())) { + return { + response: jsonError(400, "from_time must be a valid date string.", "invalid_from_time"), + }; + } + + // The plan's first day is a DATE column; noon of that day in the plan's + // timezone is an instant that falls on it however far the zone is from UTC. + const startKey = dateColumnKey(plan.startDate); + const planStart = zonedTimeToUtc(startKey, "12:00", plan.timezone); + const examKey = dateColumnKey(plan.examDate); + const lastDay = body.include_missed ? addDays(examKey, -1) : undefined; + + // Optionally fetch Google Calendar busy blocks (a read; nothing is written). + // rawBusy is the time other events take; busyIntervals adds the buffer. + let busyIntervals: TimeInterval[] = []; + let rawBusy: TimeInterval[] = []; + if (body.respect_google_busy) { + try { + const integration = await prisma.googleIntegration.findUnique({ where: { userId } }); + + if (integration && integration.status === "CONNECTED") { + const client = getGoogleClient(userId); + const calendarIds = body.calendar_ids?.length + ? body.calendar_ids + : integration.busyCalendarIds.split(",").filter(Boolean); + + // Midnight after the last day sessions can land on + const lastItemDay = plan.items.reduce( + (max, item) => Math.max(max, item.dayIndex), + reflowConfig.availability.length - 1, + ); + const horizonEnd = lastDay ?? addDays(startKey, lastItemDay); + const timeMax = zonedTimeToUtc(addDays(horizonEnd, 1), "00:00", plan.timezone); + + if (timeMax.getTime() > now.getTime()) { + const busy: BusyInterval[] = await client.freebusyQuery({ + timeMin: now.toISOString(), + timeMax: timeMax.toISOString(), + calendarIds, + }); + + // The plan's own events are busy time in Google Calendar too. Cut + // them out first, or every published session clashes with itself + // (and with its neighbour once buffered) and gets moved. + const ownEvents = await prisma.planItemExternalEvent.findMany({ + where: { provider: "GOOGLE", planId }, + select: { planItemId: true }, + }); + const published = new Set(ownEvents.map((e) => e.planItemId)); + const ownSlots: TimeInterval[] = plan.items + .filter((item) => published.has(item.id)) + .map((item) => ({ start: item.startTime.getTime(), end: item.endTime.getTime() })); + + rawBusy = subtractIntervals( + busy.map((b) => ({ + start: new Date(b.start).getTime(), + end: new Date(b.end).getTime(), + })), + ownSlots, + ); + + // Expand each busy block by buffer_minutes on each side + const bufferMs = body.buffer_minutes * 60 * 1000; + busyIntervals = bufferMs > 0 + ? rawBusy.map((b) => ({ start: b.start - bufferMs, end: b.end + bufferMs })) + : rawBusy; + } + } + // Not connected: schedule without busy data + } catch (err) { + if (err instanceof GoogleReconnectError) { + return { + response: jsonError(409, GOOGLE_COPY.reconnect, "GOOGLE_RECONNECT_REQUIRED", { + message: GOOGLE_COPY.reconnect, + }), + }; + } + // Non-fatal: log and continue without busy data + logger.warn(`${logPrefix}.busy_fetch_failed`, { plan_id: planId, error: String(err) }); + } + } + + const result = computeReflow( + reflowItems, + reflowConfig, + planStart, + now, + busyIntervals, + plan.timezone, + // A kept session moves only when it really overlaps an event; the + // buffer applies to the new times picked for the others + { includeMissed: body.include_missed, lastDay, clashIntervals: rawBusy }, + ); + + return { plan, reflowItems, result, now, busyIntervals }; +} + +/** Counts for the response summary. */ +export function summarize(result: ReflowResult, totalItems: number) { + return { + total_items: totalItems, + moved: result.changes.filter((c) => c.action === "MOVED").length, + kept: result.changes.filter((c) => c.action === "KEPT").length, + dropped: result.changes.filter((c) => c.action === "DROPPED").length, + }; +} diff --git a/src/app/api/plans/[planId]/route.ts b/src/app/api/plans/[planId]/route.ts index ca67c1e7..125ba193 100644 --- a/src/app/api/plans/[planId]/route.ts +++ b/src/app/api/plans/[planId]/route.ts @@ -1,17 +1,15 @@ import { NextRequest, NextResponse } from "next/server"; import { getUserId } from "@/lib/auth"; -import { getPlan } from "@/services/plan"; -import { prisma } from "@/lib/db"; +import { deletePlan, getPlan } from "@/services/plan"; import { logger } from "@/lib/logger"; +import { unauthorized } from "@/lib/http"; export async function GET( request: NextRequest, { params }: { params: Promise<{ planId: string }> } ) { const userId = await getUserId(request); - if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); - } + if (!userId) return unauthorized(); const { planId } = await params; @@ -20,51 +18,70 @@ export async function GET( if ("error" in result) { if (result.error === "not_found") { - return NextResponse.json({ error: "Plan not found" }, { status: 404 }); + return NextResponse.json( + { error: "This plan doesn't exist anymore.", code: "not_found" }, + { status: 404 }, + ); } - return NextResponse.json({ error: "Forbidden" }, { status: 403 }); + return NextResponse.json( + { error: "This plan belongs to another account.", code: "forbidden" }, + { status: 403 }, + ); } return NextResponse.json(result.data); - } catch { - return NextResponse.json({ error: "Internal server error" }, { status: 500 }); + } catch (err) { + logger.error("get_plan_failed", { plan_id: planId, error: String(err) }); + return NextResponse.json( + { error: "The plan didn't load. Retry in a minute.", code: "internal" }, + { status: 500 }, + ); } } +/** + * DELETE /api/plans/{planId}[?calendar=remove] + * + * Deletes the plan and its items; sessions, answers and progress stay. With + * `calendar=remove`, the plan's Google Calendar events are removed first and + * the plan is kept (409) when any of them can't be. + */ export async function DELETE( request: NextRequest, { params }: { params: Promise<{ planId: string }> } ) { const userId = await getUserId(request); - if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); - } + if (!userId) return unauthorized(); const { planId } = await params; + const removeCalendarEvents = request.nextUrl.searchParams.get("calendar") === "remove"; try { - const plan = await prisma.studyPlan.findUnique({ - where: { planId }, - select: { userId: true }, - }); + const result = await deletePlan(userId, planId, { removeCalendarEvents }); - if (!plan || plan.userId !== userId) { - return NextResponse.json({ error: "Plan not found" }, { status: 404 }); + if ("data" in result) { + return NextResponse.json({ success: true, ...result.data }); } - - // Delete in correct order to respect FK constraints - await prisma.$transaction([ - prisma.planItemExternalEvent.deleteMany({ where: { planId } }), - prisma.planCalendarPublication.deleteMany({ where: { planId } }), - prisma.planReflowAudit.deleteMany({ where: { planId } }), - prisma.studyPlanItem.deleteMany({ where: { planId } }), - prisma.studyPlan.delete({ where: { planId } }), - ]); - - logger.info("plan.deleted", { user_id: userId, plan_id: planId }); - - return NextResponse.json({ success: true }); - } catch { - return NextResponse.json({ error: "Internal server error" }, { status: 500 }); + if (result.error === "not_found") { + return NextResponse.json( + { error: "This plan doesn't exist anymore.", code: "not_found" }, + { status: 404 }, + ); + } + return NextResponse.json( + { + error: result.message, + code: result.code, + removed: result.removed, + failed: result.failed, + }, + { status: 409 }, + ); + } catch (err) { + logger.error("delete_plan_failed", { plan_id: planId, error: String(err) }); + return NextResponse.json( + { error: "Plan not deleted. Retry in a minute.", code: "internal" }, + { status: 500 }, + ); } } diff --git a/src/app/api/plans/[planId]/unpublish/google/route.ts b/src/app/api/plans/[planId]/unpublish/google/route.ts index 7cd4d0fc..a6d6c997 100644 --- a/src/app/api/plans/[planId]/unpublish/google/route.ts +++ b/src/app/api/plans/[planId]/unpublish/google/route.ts @@ -1,7 +1,13 @@ import { NextRequest, NextResponse } from "next/server"; import { getUserId } from "@/lib/auth"; -import { unpublishPlanFromGoogle, unpublishRequestSchema } from "@/services/publish"; +import { generalLimiter, tooManyRequests } from "@/lib/rate-limit"; +import { + unpublishPlanFromGoogle, + unpublishRequestSchema, + calendarErrorMessage, +} from "@/services/publish"; import { logger } from "@/lib/logger"; +import { unauthorized } from "@/lib/http"; export async function POST( request: NextRequest, @@ -9,22 +15,31 @@ export async function POST( ) { const userId = await getUserId(request); if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + return unauthorized(); } + // Calls Google Calendar for every session in the plan + const rl = generalLimiter.check(userId); + if (!rl.allowed) return tooManyRequests(rl.retryAfterMs); + const { planId } = await params; let body: Record<string, unknown> = {}; try { body = await request.json(); } catch { - // Empty body is fine — all fields optional + // Empty body is fine: all fields optional } const parsed = unpublishRequestSchema.safeParse(body); if (!parsed.success) { return NextResponse.json( - { error: "Invalid request", details: parsed.error.issues }, + { + error: "Invalid request", + code: "validation_failed", + message: "The calendar options weren't valid.", + details: parsed.error.issues, + }, { status: 400 }, ); } @@ -36,13 +51,23 @@ export async function POST( }); if ("error" in result) { - const status = result.status || 500; - return NextResponse.json({ error: result.error }, { status }); + // `error` keeps the code for API clients; `message` is for the screen + return NextResponse.json( + { error: result.error, code: result.error, message: calendarErrorMessage(result.error) }, + { status: result.status || 500 }, + ); } return NextResponse.json(result.data); } catch (err) { logger.error("api.unpublish_google_failed", { user_id: userId, plan_id: planId, error: String(err) }); - return NextResponse.json({ error: "Internal server error" }, { status: 500 }); + return NextResponse.json( + { + error: "Events weren't removed from Google Calendar. Retry in a minute.", + code: "internal", + message: "Events weren't removed from Google Calendar. Retry in a minute.", + }, + { status: 500 }, + ); } } diff --git a/src/app/api/plans/followups/route.ts b/src/app/api/plans/followups/route.ts index 738f4a99..ce261039 100644 --- a/src/app/api/plans/followups/route.ts +++ b/src/app/api/plans/followups/route.ts @@ -3,14 +3,22 @@ import { getUserId } from "@/lib/auth"; import { scheduleFollowups } from "@/services/followups"; import { logger } from "@/lib/logger"; import { generalLimiter, tooManyRequests } from "@/lib/rate-limit"; -import { z } from "zod/v4"; +import { z } from "zod"; +import { unauthorized } from "@/lib/http"; -const bodySchema = z.object({ run_id: z.string().min(1) }); +const bodySchema = z.object({ run_id: z.string().min(1).max(100) }); + +/** Sentences for the service's error codes; the code travels as `code`. */ +const FOLLOWUP_ERRORS: Record<string, { status: number; message: string }> = { + not_found: { status: 404, message: "This session's results weren't found." }, + forbidden: { status: 403, message: "This session belongs to another account." }, + run_not_completed: { status: 409, message: "Finish the session before adding follow-ups." }, +}; export async function POST(request: NextRequest) { const userId = await getUserId(request); if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + return unauthorized(); } const rl = generalLimiter.check(userId); @@ -20,13 +28,16 @@ export async function POST(request: NextRequest) { try { body = await request.json(); } catch { - return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 }); + return NextResponse.json( + { error: "The request wasn't valid JSON.", code: "INVALID_JSON" }, + { status: 400 }, + ); } const parsed = bodySchema.safeParse(body); if (!parsed.success) { return NextResponse.json( - { error: "Validation failed", issues: parsed.error.issues }, + { error: "Follow-ups need a finished session.", code: "validation_failed", issues: parsed.error.issues }, { status: 400 }, ); } @@ -34,19 +45,23 @@ export async function POST(request: NextRequest) { try { const result = await scheduleFollowups(userId, parsed.data.run_id); - if ("error" in result) { - if (result.error === "not_found") { - return NextResponse.json({ error: "Run not found" }, { status: 404 }); - } - if (result.error === "forbidden") { - return NextResponse.json({ error: "Forbidden" }, { status: 403 }); - } - return NextResponse.json({ error: result.error }, { status: 409 }); + if ("error" in result && result.error) { + const known = FOLLOWUP_ERRORS[result.error] ?? { + status: 409, + message: "Follow-ups weren't added. Retry in a minute.", + }; + return NextResponse.json( + { error: known.message, code: result.error }, + { status: known.status }, + ); } return NextResponse.json(result.data); } catch (err) { logger.error("followups_schedule_failed", { error: String(err) }); - return NextResponse.json({ error: "Internal server error" }, { status: 500 }); + return NextResponse.json( + { error: "Follow-ups weren't added. Retry in a minute.", code: "internal" }, + { status: 500 }, + ); } } diff --git a/src/app/api/plans/route.ts b/src/app/api/plans/route.ts index 4016cea6..0cfe4118 100644 --- a/src/app/api/plans/route.ts +++ b/src/app/api/plans/route.ts @@ -1,14 +1,17 @@ import { NextRequest, NextResponse } from "next/server"; import { getUserId } from "@/lib/auth"; -import { createPlan } from "@/services/plan"; +import { createPlanWithReplace, planEndDateKey } from "@/services/plan"; import { prisma } from "@/lib/db"; -import { z } from "zod/v4"; +import { z } from "zod"; import { logger } from "@/lib/logger"; +import { dateColumnKey } from "@/lib/plan-dates"; +import { generalLimiter, tooManyRequests } from "@/lib/rate-limit"; +import { unauthorized } from "@/lib/http"; export async function GET(request: NextRequest) { const userId = await getUserId(request); if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + return unauthorized(); } try { @@ -35,9 +38,9 @@ export async function GET(request: NextRequest) { plan_id: plan.planId, course_name: plan.courseName, exam_name: plan.examName, - exam_date: plan.examDate.toISOString().split("T")[0], - start_date: plan.startDate.toISOString().split("T")[0], - end_date: plan.endDate.toISOString().split("T")[0], + exam_date: dateColumnKey(plan.examDate), + start_date: dateColumnKey(plan.startDate), + end_date: planEndDateKey(plan.startDate), timezone: plan.timezone, created_at: plan.createdAt.toISOString(), items: plan.items.map((item) => { @@ -67,41 +70,51 @@ export async function GET(request: NextRequest) { } catch (err) { logger.error("list_plans_failed", { error: String(err) }); return NextResponse.json( - { error: "Internal server error" }, + { error: "Plans didn't load. Retry in a minute.", code: "internal" }, { status: 500 }, ); } } +/** + * POST /api/plans: create a plan. With `replace_plan_id`, the replaced plan + * is deleted only after the new one is created (see createPlanWithReplace). + * Validation errors return `issues` whose paths name the fields + * (course_name, exam_name, exam_date, availability, objectives). + */ export async function POST(request: NextRequest) { const userId = await getUserId(request); if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + return unauthorized(); } + // Creating a plan runs AI topic extraction and reads Google Calendar + const rl = generalLimiter.check(userId); + if (!rl.allowed) return tooManyRequests(rl.retryAfterMs); + let body: unknown; try { body = await request.json(); } catch { return NextResponse.json( - { error: "Invalid JSON body" }, + { error: "The request wasn't valid JSON.", code: "INVALID_JSON" }, { status: 400 } ); } try { - const result = await createPlan(userId, body); + const result = await createPlanWithReplace(userId, body); return NextResponse.json(result, { status: 201 }); } catch (err) { if (err instanceof z.ZodError) { return NextResponse.json( - { error: "Validation failed", issues: err.issues }, + { error: "Check the highlighted fields.", code: "validation_failed", issues: err.issues }, { status: 400 } ); } logger.error("create_plan_failed", { error: String(err) }); return NextResponse.json( - { error: "Internal server error" }, + { error: "Plan not created. Retry in a minute.", code: "internal" }, { status: 500 } ); } diff --git a/src/app/api/runs/[runId]/attempt/route.ts b/src/app/api/runs/[runId]/attempt/route.ts index 02047613..475b2872 100644 --- a/src/app/api/runs/[runId]/attempt/route.ts +++ b/src/app/api/runs/[runId]/attempt/route.ts @@ -1,17 +1,18 @@ import { NextRequest, NextResponse } from "next/server"; +import { unauthorized } from "@/lib/http"; import { getUserId } from "@/lib/auth"; import { submitAttempt } from "@/services/run"; import { parseAttemptPayload } from "@/lib/validation"; import { logger } from "@/lib/logger"; -import { z } from "zod/v4"; +import { z } from "zod"; export async function POST( request: NextRequest, - { params }: { params: { runId: string } } + { params }: { params: Promise<{ runId: string }> } ) { const userId = await getUserId(request); if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + return unauthorized(); } const { runId } = await params; @@ -20,7 +21,7 @@ export async function POST( try { body = await request.json(); } catch { - return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 }); + return NextResponse.json({ error: "Answer not saved. Reload and retry." }, { status: 400 }); } let parsed; @@ -29,7 +30,7 @@ export async function POST( } catch (err) { if (err instanceof z.ZodError) { return NextResponse.json( - { error: "Validation failed", issues: err.issues }, + { error: "Answer not saved. Check your answer and retry.", issues: err.issues }, { status: 400 } ); } @@ -40,48 +41,48 @@ export async function POST( const result = await submitAttempt(userId, runId, parsed); if ("error" in result) { - const err = result.error; - if (err === "not_found") { - return NextResponse.json({ error: "Run not found" }, { status: 404 }); + if (result.error === "not_found") { + return NextResponse.json({ error: "Session not found. It may have been deleted." }, { status: 404 }); } - if (err === "forbidden") { - return NextResponse.json({ error: "Forbidden" }, { status: 403 }); + if (result.error === "forbidden") { + return NextResponse.json({ error: "This session belongs to another account." }, { status: 403 }); } - if (err === "run_completed") { - return NextResponse.json({ error: "Run is already completed" }, { status: 409 }); + if (result.error === "run_completed") { + return NextResponse.json({ error: "This session is already finished. Reload to see your results.", code: "run_completed" }, { status: 409 }); } - if (err === "on_break") { + if (result.error === "on_break") { return NextResponse.json( - { error: "Cannot submit during break", break_state: (result as any).break_state }, + // "break" in the message is matched by the session screen; keep it. + { error: "Cannot submit during break", code: "on_break", break_state: result.break_state }, { status: 409 } ); } - if (err === "wrong_index") { + if (result.error === "wrong_index") { return NextResponse.json( - { error: "Wrong prompt index", expected: (result as any).expected }, + { error: "This question was answered in another tab. Reload to continue.", code: "wrong_index", expected: result.expected }, { status: 409 } ); } - if (err === "invalid_index") { - return NextResponse.json({ error: "Invalid prompt index" }, { status: 400 }); + if (result.error === "invalid_index") { + return NextResponse.json({ error: "This question isn't in the session. Reload to continue." }, { status: 400 }); } - if (err === "duplicate_attempt") { - return NextResponse.json({ error: "Attempt already submitted for this prompt" }, { status: 409 }); + if (result.error === "duplicate_attempt") { + return NextResponse.json({ error: "This question was already answered. Reload to continue.", code: "duplicate_attempt" }, { status: 409 }); } - if (err === "wrong_phase") { + if (result.error === "wrong_phase") { return NextResponse.json( - { error: (result as any).message || "Invalid operation for current phase" }, + { error: result.message || "This step doesn't fit where the session is now. Reload to continue.", code: "wrong_phase" }, { status: 409 } ); } - if (err === "no_attempt_to_score") { - return NextResponse.json({ error: "No attempt found to score at this index" }, { status: 409 }); + if (result.error === "no_attempt_to_score") { + return NextResponse.json({ error: "There's no saved answer to score for this question. Reload to continue.", code: "no_attempt_to_score" }, { status: 409 }); } - if (err === "already_scored") { - return NextResponse.json({ error: "This attempt has already been scored" }, { status: 409 }); + if (result.error === "already_scored") { + return NextResponse.json({ error: "This answer was already scored. Reload to continue.", code: "already_scored" }, { status: 409 }); } - if (err === "missing_score") { - return NextResponse.json({ error: "self_score is required for SCORE kind" }, { status: 400 }); + if (result.error === "missing_score") { + return NextResponse.json({ error: "Score your answer before you save it." }, { status: 400 }); } } @@ -96,6 +97,6 @@ export async function POST( }); } catch (err) { logger.error("run_submit_attempt_failed", { error: String(err) }); - return NextResponse.json({ error: "Internal server error" }, { status: 500 }); + return NextResponse.json({ error: "Answer not saved. Retry." }, { status: 500 }); } } diff --git a/src/app/api/runs/[runId]/complete/route.ts b/src/app/api/runs/[runId]/complete/route.ts index 795ee5ee..928f243b 100644 --- a/src/app/api/runs/[runId]/complete/route.ts +++ b/src/app/api/runs/[runId]/complete/route.ts @@ -3,37 +3,32 @@ import { getUserId } from "@/lib/auth"; import { completeRun } from "@/services/run"; import { logger } from "@/lib/logger"; import { generalLimiter, tooManyRequests } from "@/lib/rate-limit"; +import { idSchema, internalError, sessionError } from "@/app/api/sessions/session-errors"; +/** Finish a run. Idempotent: a second call returns the same result. */ export async function POST( request: NextRequest, - { params }: { params: { runId: string } } + { params }: { params: Promise<{ runId: string }> } ) { const userId = await getUserId(request); - if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); - } + if (!userId) return sessionError("unauthorized"); const rl = generalLimiter.check(userId); if (!rl.allowed) return tooManyRequests(rl.retryAfterMs); const { runId } = await params; + if (!idSchema.safeParse(runId).success) return sessionError("run_not_found"); try { const result = await completeRun(userId, runId); if ("error" in result) { - if (result.error === "not_found") { - return NextResponse.json({ error: "Run not found" }, { status: 404 }); - } - if (result.error === "forbidden") { - return NextResponse.json({ error: "Forbidden" }, { status: 403 }); - } - return NextResponse.json({ error: result.error }, { status: 409 }); + return sessionError(result.error === "forbidden" ? "forbidden" : "run_not_found"); } return NextResponse.json(result.data); } catch (err) { logger.error("run_complete_failed", { error: String(err) }); - return NextResponse.json({ error: "Internal server error" }, { status: 500 }); + return internalError("Session not finished. Your answers are saved."); } } diff --git a/src/app/api/runs/[runId]/end-break/route.ts b/src/app/api/runs/[runId]/end-break/route.ts index e485a673..2d34a459 100644 --- a/src/app/api/runs/[runId]/end-break/route.ts +++ b/src/app/api/runs/[runId]/end-break/route.ts @@ -2,36 +2,30 @@ import { NextRequest, NextResponse } from "next/server"; import { getUserId } from "@/lib/auth"; import { endBreak } from "@/services/run"; import { logger } from "@/lib/logger"; +import { idSchema, internalError, sessionError } from "@/app/api/sessions/session-errors"; export async function POST( request: NextRequest, - { params }: { params: { runId: string } } + { params }: { params: Promise<{ runId: string }> } ) { const userId = await getUserId(request); - if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); - } + if (!userId) return sessionError("unauthorized"); const { runId } = await params; + if (!idSchema.safeParse(runId).success) return sessionError("run_not_found"); try { const result = await endBreak(userId, runId); if ("error" in result) { - if (result.error === "not_found") { - return NextResponse.json({ error: "Run not found" }, { status: 404 }); - } - if (result.error === "forbidden") { - return NextResponse.json({ error: "Forbidden" }, { status: 403 }); - } - if (result.error === "not_on_break") { - return NextResponse.json({ error: "Not currently on break" }, { status: 409 }); - } + if (result.error === "forbidden") return sessionError("forbidden"); + if (result.error === "not_on_break") return sessionError("not_on_break"); + return sessionError("run_not_found"); } return NextResponse.json(result.data); } catch (err) { logger.error("run_end_break_failed", { error: String(err) }); - return NextResponse.json({ error: "Internal server error" }, { status: 500 }); + return internalError("Break didn't end."); } } diff --git a/src/app/api/runs/[runId]/prompt/route.ts b/src/app/api/runs/[runId]/prompt/route.ts index 8a617a70..2a138cab 100644 --- a/src/app/api/runs/[runId]/prompt/route.ts +++ b/src/app/api/runs/[runId]/prompt/route.ts @@ -1,15 +1,16 @@ import { NextRequest, NextResponse } from "next/server"; +import { unauthorized } from "@/lib/http"; import { getUserId } from "@/lib/auth"; import { getRunPrompt } from "@/services/run"; import { logger } from "@/lib/logger"; export async function GET( request: NextRequest, - { params }: { params: { runId: string } } + { params }: { params: Promise<{ runId: string }> } ) { const userId = await getUserId(request); if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + return unauthorized(); } const { runId } = await params; @@ -17,12 +18,12 @@ export async function GET( const indexStr = url.searchParams.get("index"); if (indexStr === null) { - return NextResponse.json({ error: "index query parameter is required" }, { status: 400 }); + return NextResponse.json({ error: "This question isn't in the session. Reload to continue." }, { status: 400 }); } const index = parseInt(indexStr, 10); if (isNaN(index) || index < 0) { - return NextResponse.json({ error: "index must be a non-negative integer" }, { status: 400 }); + return NextResponse.json({ error: "This question isn't in the session. Reload to continue." }, { status: 400 }); } try { @@ -30,19 +31,19 @@ export async function GET( if ("error" in result) { if (result.error === "not_found") { - return NextResponse.json({ error: "Run not found" }, { status: 404 }); + return NextResponse.json({ error: "Session not found. It may have been deleted." }, { status: 404 }); } if (result.error === "forbidden") { - return NextResponse.json({ error: "Forbidden" }, { status: 403 }); + return NextResponse.json({ error: "This session belongs to another account." }, { status: 403 }); } if (result.error === "invalid_index") { - return NextResponse.json({ error: "Invalid prompt index" }, { status: 400 }); + return NextResponse.json({ error: "This question isn't in the session. Reload to continue." }, { status: 400 }); } } return NextResponse.json(result.data); } catch (err) { logger.error("run_get_prompt_failed", { error: String(err) }); - return NextResponse.json({ error: "Internal server error" }, { status: 500 }); + return NextResponse.json({ error: "The next question didn't load. Retry." }, { status: 500 }); } } diff --git a/src/app/api/runs/[runId]/reveal/route.ts b/src/app/api/runs/[runId]/reveal/route.ts index b223f5c1..184050b4 100644 --- a/src/app/api/runs/[runId]/reveal/route.ts +++ b/src/app/api/runs/[runId]/reveal/route.ts @@ -1,55 +1,121 @@ import { NextRequest, NextResponse } from "next/server"; +import { unauthorized } from "@/lib/http"; +import { z } from "zod"; import { getUserId } from "@/lib/auth"; import { getAnswerReveal } from "@/services/run"; import { logger } from "@/lib/logger"; /** + * The model answer and points to check for the run's current question. + * + * POST /api/runs/:runId/reveal { index, user_answer } + * Free recall: commits the student's answer and returns the standard to + * score it against. The first committed answer is the one recorded with + * the score. * GET /api/runs/:runId/reveal?index=N + * Only for a question that already has a recorded attempt (exam + * simulation scoring, an answered multiple-choice question). An + * unanswered free-recall question gets 409 and no model answer, so a + * prefetch can never show the answer before the student commits one. * - * Returns the model answer / key points for the current prompt so the - * student can self-score against an explicit standard. Only valid for the - * run's current index and never during the EXAM phase. + * Never during the EXAM phase of an exam simulation. */ + +const MESSAGES = { + badIndex: "This question isn't in the session. Reload to continue.", + badAnswer: "Write an answer before you check it.", + notFound: "Session not found. It may have been deleted.", + forbidden: "This session belongs to another account.", + wrongIndex: "This question was answered in another tab. Reload to continue.", + answerRequired: "Answer the question before you see the model answer.", + failed: "The model answer didn't load. Retry.", +} as const; + +const revealBodySchema = z.object({ + index: z.number().int().min(0), + user_answer: z.string().trim().min(1).max(20_000), +}); + +type RevealResult = Awaited<ReturnType<typeof getAnswerReveal>>; + +function toResponse(result: RevealResult): NextResponse { + if ("error" in result) { + switch (result.error) { + case "not_found": + return NextResponse.json({ error: MESSAGES.notFound }, { status: 404 }); + case "forbidden": + return NextResponse.json({ error: MESSAGES.forbidden }, { status: 403 }); + case "wrong_phase": + return NextResponse.json({ error: result.message, code: "wrong_phase" }, { status: 409 }); + case "wrong_index": + return NextResponse.json( + { error: MESSAGES.wrongIndex, code: "wrong_index", expected: result.expected }, + { status: 409 } + ); + case "answer_required": + return NextResponse.json({ error: MESSAGES.answerRequired, code: "answer_required" }, { status: 409 }); + } + } + return NextResponse.json(result.data); +} + export async function GET( request: NextRequest, - { params }: { params: { runId: string } } + { params }: { params: Promise<{ runId: string }> } ) { const userId = await getUserId(request); if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + return unauthorized(); } const { runId } = await params; const indexStr = new URL(request.url).searchParams.get("index"); - const index = indexStr === null ? NaN : parseInt(indexStr, 10); - if (Number.isNaN(index) || index < 0) { - return NextResponse.json({ error: "index must be a non-negative integer" }, { status: 400 }); + const index = indexStr === null ? NaN : Number(indexStr); + if (!Number.isInteger(index) || index < 0) { + return NextResponse.json({ error: MESSAGES.badIndex }, { status: 400 }); } try { - const result = await getAnswerReveal(userId, runId, index); - - if ("error" in result) { - if (result.error === "not_found") { - return NextResponse.json({ error: "Run not found" }, { status: 404 }); - } - if (result.error === "forbidden") { - return NextResponse.json({ error: "Forbidden" }, { status: 403 }); - } - if (result.error === "wrong_phase") { - return NextResponse.json({ error: result.message }, { status: 409 }); - } - if (result.error === "wrong_index") { - return NextResponse.json( - { error: "Wrong prompt index", expected: result.expected }, - { status: 409 } - ); - } - } + return toResponse(await getAnswerReveal(userId, runId, index)); + } catch (err) { + logger.error("run_reveal_failed", { error: String(err) }); + return NextResponse.json({ error: MESSAGES.failed }, { status: 500 }); + } +} + +export async function POST( + request: NextRequest, + { params }: { params: Promise<{ runId: string }> } +) { + const userId = await getUserId(request); + if (!userId) { + return unauthorized(); + } - return NextResponse.json(result.data); + const { runId } = await params; + + let body: unknown; + try { + body = await request.json(); + } catch { + return NextResponse.json({ error: MESSAGES.badAnswer }, { status: 400 }); + } + + const parsed = revealBodySchema.safeParse(body); + if (!parsed.success) { + const indexIssue = parsed.error.issues.some((issue) => issue.path[0] === "index"); + return NextResponse.json( + { error: indexIssue ? MESSAGES.badIndex : MESSAGES.badAnswer, issues: parsed.error.issues }, + { status: 400 } + ); + } + + try { + return toResponse( + await getAnswerReveal(userId, runId, parsed.data.index, { userAnswer: parsed.data.user_answer }) + ); } catch (err) { logger.error("run_reveal_failed", { error: String(err) }); - return NextResponse.json({ error: "Internal server error" }, { status: 500 }); + return NextResponse.json({ error: MESSAGES.failed }, { status: 500 }); } } diff --git a/src/app/api/runs/[runId]/route.ts b/src/app/api/runs/[runId]/route.ts index bd5c6d73..aa6fbb9a 100644 --- a/src/app/api/runs/[runId]/route.ts +++ b/src/app/api/runs/[runId]/route.ts @@ -2,33 +2,28 @@ import { NextRequest, NextResponse } from "next/server"; import { getUserId } from "@/lib/auth"; import { getRun } from "@/services/run"; import { logger } from "@/lib/logger"; +import { idSchema, internalError, sessionError } from "@/app/api/sessions/session-errors"; export async function GET( request: NextRequest, - { params }: { params: { runId: string } } + { params }: { params: Promise<{ runId: string }> } ) { const userId = await getUserId(request); - if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); - } + if (!userId) return sessionError("unauthorized"); const { runId } = await params; + if (!idSchema.safeParse(runId).success) return sessionError("run_not_found"); try { const result = await getRun(userId, runId); if ("error" in result) { - if (result.error === "not_found") { - return NextResponse.json({ error: "Run not found" }, { status: 404 }); - } - if (result.error === "forbidden") { - return NextResponse.json({ error: "Forbidden" }, { status: 403 }); - } + return sessionError(result.error === "forbidden" ? "forbidden" : "run_not_found"); } return NextResponse.json(result.data); } catch (err) { logger.error("run_get_failed", { error: String(err) }); - return NextResponse.json({ error: "Internal server error" }, { status: 500 }); + return internalError("Session didn't load."); } } diff --git a/src/app/api/sessions/[sessionId]/deck-preview/route.ts b/src/app/api/sessions/[sessionId]/deck-preview/route.ts new file mode 100644 index 00000000..7772851f --- /dev/null +++ b/src/app/api/sessions/[sessionId]/deck-preview/route.ts @@ -0,0 +1,24 @@ +import { NextRequest, NextResponse } from "next/server"; +import { getUserId } from "@/lib/auth"; +import { getSessionDeckPreview } from "@/services/session"; +import { idSchema, sessionError } from "../../session-errors"; + +/** + * What the next run of a session will hold ("7 new, 2 due for review"), for + * the intro after Start session again. `deck` is null when it can't be + * predicted. Owner only; anyone else gets the same 404 as a missing session. + */ +export async function GET( + request: NextRequest, + { params }: { params: Promise<{ sessionId: string }> } +) { + const userId = await getUserId(request); + if (!userId) return sessionError("unauthorized"); + + const { sessionId } = await params; + if (!idSchema.safeParse(sessionId).success) return sessionError("session_not_found"); + + const result = await getSessionDeckPreview(userId, sessionId); + if ("error" in result) return sessionError("session_not_found"); + return NextResponse.json({ deck: result.data }); +} diff --git a/src/app/api/sessions/[sessionId]/route.ts b/src/app/api/sessions/[sessionId]/route.ts index 0f7a6c6b..3e11a53e 100644 --- a/src/app/api/sessions/[sessionId]/route.ts +++ b/src/app/api/sessions/[sessionId]/route.ts @@ -1,26 +1,22 @@ import { NextRequest, NextResponse } from "next/server"; import { getUserId } from "@/lib/auth"; import { getSession } from "@/services/session"; +import { idSchema, sessionError } from "../session-errors"; export async function GET( request: NextRequest, - { params }: { params: { sessionId: string } } + { params }: { params: Promise<{ sessionId: string }> } ) { const userId = await getUserId(request); - if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); - } + if (!userId) return sessionError("unauthorized"); const { sessionId } = await params; + if (!idSchema.safeParse(sessionId).success) return sessionError("session_not_found"); + const result = await getSession(userId, sessionId); if ("error" in result) { - if (result.error === "not_found") { - return NextResponse.json({ error: "Session not found" }, { status: 404 }); - } - if (result.error === "forbidden") { - return NextResponse.json({ error: "Forbidden" }, { status: 403 }); - } + return sessionError(result.error === "forbidden" ? "forbidden" : "session_not_found"); } return NextResponse.json(result.data); diff --git a/src/app/api/sessions/[sessionId]/runs/[runId]/results/route.ts b/src/app/api/sessions/[sessionId]/runs/[runId]/results/route.ts new file mode 100644 index 00000000..db1e79b0 --- /dev/null +++ b/src/app/api/sessions/[sessionId]/runs/[runId]/results/route.ts @@ -0,0 +1,35 @@ +import { NextRequest, NextResponse } from "next/server"; +import { getUserId } from "@/lib/auth"; +import { getSessionResults } from "@/services/session"; +import { logger } from "@/lib/logger"; +import { idSchema, internalError, sessionError } from "../../../../session-errors"; + +/** + * Results of one finished run of a session: stats, rated answers for the + * confidence chart, and follow-up dates from the scheduler. Owner only. + */ +export async function GET( + request: NextRequest, + { params }: { params: Promise<{ sessionId: string; runId: string }> } +) { + const userId = await getUserId(request); + if (!userId) return sessionError("unauthorized"); + + const { sessionId, runId } = await params; + if (!idSchema.safeParse(sessionId).success || !idSchema.safeParse(runId).success) { + return sessionError("run_not_found"); + } + + try { + const result = await getSessionResults(userId, sessionId, runId); + if ("error" in result) { + if (result.error === "forbidden") return sessionError("forbidden"); + if (result.error === "not_completed") return sessionError("run_not_completed"); + return sessionError("run_not_found"); + } + return NextResponse.json(result.data); + } catch (err) { + logger.error("session_results_failed", { error: String(err), run_id: runId }); + return internalError("Results didn't load."); + } +} diff --git a/src/app/api/sessions/[sessionId]/runs/start/route.ts b/src/app/api/sessions/[sessionId]/runs/start/route.ts index abfffd22..634e8cf0 100644 --- a/src/app/api/sessions/[sessionId]/runs/start/route.ts +++ b/src/app/api/sessions/[sessionId]/runs/start/route.ts @@ -2,34 +2,25 @@ import { NextRequest, NextResponse } from "next/server"; import { getUserId } from "@/lib/auth"; import { startOrResumeRun } from "@/services/run"; import { logger } from "@/lib/logger"; +import { idSchema, internalError, sessionError } from "../../../session-errors"; export async function POST( request: NextRequest, - { params }: { params: { sessionId: string } } + { params }: { params: Promise<{ sessionId: string }> } ) { const userId = await getUserId(request); - if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); - } + if (!userId) return sessionError("unauthorized"); const { sessionId } = await params; + if (!idSchema.safeParse(sessionId).success) return sessionError("session_not_found"); try { const result = await startOrResumeRun(userId, sessionId); if ("error" in result) { - if (result.error === "session_not_found") { - return NextResponse.json({ error: "Session not found" }, { status: 404 }); - } - if (result.error === "forbidden") { - return NextResponse.json({ error: "Forbidden" }, { status: 403 }); - } - if (result.error === "unsupported_mode") { - return NextResponse.json( - { error: "This session mode is not yet supported for runs" }, - { status: 400 } - ); - } + if (result.error === "forbidden") return sessionError("forbidden"); + if (result.error === "unsupported_mode") return sessionError("unsupported_mode"); + return sessionError("session_not_found"); } const httpStatus = result.data!.resumed ? 200 : 201; @@ -46,6 +37,6 @@ export async function POST( }); } catch (err) { logger.error("run_start_failed", { error: String(err) }); - return NextResponse.json({ error: "Internal server error" }, { status: 500 }); + return internalError("Session not started."); } } diff --git a/src/app/api/sessions/route.ts b/src/app/api/sessions/route.ts index 63a01f35..abe32b5a 100644 --- a/src/app/api/sessions/route.ts +++ b/src/app/api/sessions/route.ts @@ -1,15 +1,14 @@ import { NextRequest, NextResponse } from "next/server"; import { getUserId } from "@/lib/auth"; import { createSession } from "@/services/session"; -import { z } from "zod/v4"; +import { z } from "zod"; import { logger } from "@/lib/logger"; import { generalLimiter, tooManyRequests } from "@/lib/rate-limit"; +import { internalError, sessionError } from "./session-errors"; export async function POST(request: NextRequest) { const userId = await getUserId(request); - if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); - } + if (!userId) return sessionError("unauthorized"); const rl = generalLimiter.check(userId); if (!rl.allowed) return tooManyRequests(rl.retryAfterMs); @@ -18,10 +17,7 @@ export async function POST(request: NextRequest) { try { body = await request.json(); } catch { - return NextResponse.json( - { error: "Invalid JSON body" }, - { status: 400 } - ); + return sessionError("invalid_json"); } try { @@ -30,14 +26,11 @@ export async function POST(request: NextRequest) { } catch (err) { if (err instanceof z.ZodError) { return NextResponse.json( - { error: "Validation failed", issues: err.issues }, + { error: "Check the highlighted fields.", code: "validation_failed", issues: err.issues }, { status: 400 } ); } logger.error("create_session_failed", { error: String(err) }); - return NextResponse.json( - { error: "Internal server error" }, - { status: 500 } - ); + return internalError("Session not created."); } } diff --git a/src/app/api/sessions/session-errors.ts b/src/app/api/sessions/session-errors.ts new file mode 100644 index 00000000..9976393d --- /dev/null +++ b/src/app/api/sessions/session-errors.ts @@ -0,0 +1,42 @@ +import { NextResponse } from "next/server"; +import { z } from "zod"; +import { UNAUTHORIZED_BODY } from "@/lib/http"; + +/** + * Error responses for the session and run routes. `error` is a sentence a + * student can read (VOICE.md); `code` is the stable value clients branch on. + * Statuses match what the routes returned before. + */ +const ERRORS = { + // The same body as every other 401 (UNAUTHORIZED_BODY), code included. + unauthorized: { status: 401, error: UNAUTHORIZED_BODY.error, code: UNAUTHORIZED_BODY.code }, + session_not_found: { + status: 404, + error: "Session not found. This link doesn't match a session. It may have been deleted.", + }, + run_not_found: { status: 404, error: "Session not found. It may have been deleted." }, + forbidden: { status: 403, error: "This session belongs to another account." }, + unsupported_mode: { status: 400, error: "This kind of session can't be practiced yet." }, + not_on_break: { status: 409, error: "The break already ended." }, + run_not_completed: { status: 409, error: "Finish the session to see its results." }, + invalid_json: { status: 400, error: "The request wasn't valid JSON.", code: "INVALID_JSON" }, +} as const; + +export type SessionErrorCode = keyof typeof ERRORS; + +/** The body's `code` is the key unless the entry names a shared one. */ +export function sessionError(code: SessionErrorCode, extra?: Record<string, unknown>) { + const entry: { status: number; error: string; code?: string } = ERRORS[code]; + return NextResponse.json({ error: entry.error, code: entry.code ?? code, ...extra }, { status: entry.status }); +} + +/** A failure we didn't expect: what didn't happen, then Retry. */ +export function internalError(what: string) { + return NextResponse.json( + { error: `${what} Retry in a moment.`, code: "INTERNAL_ERROR" }, + { status: 500 }, + ); +} + +/** Session and run IDs: 21-character nanoids, but older rows and tests use other URL-safe strings. */ +export const idSchema = z.string().regex(/^[A-Za-z0-9_-]{1,64}$/); diff --git a/src/app/api/settings/route.ts b/src/app/api/settings/route.ts index 39fe1078..53c6add1 100644 --- a/src/app/api/settings/route.ts +++ b/src/app/api/settings/route.ts @@ -1,107 +1,87 @@ import { NextRequest, NextResponse } from "next/server"; -import { z } from "zod/v4"; +import { unauthorized } from "@/lib/http"; import { getUserId } from "@/lib/auth"; -import { prisma } from "@/lib/db"; import { logger } from "@/lib/logger"; -import { isValidTimezone } from "@/lib/timezone"; +import { publicConfig } from "@/lib/public-config"; +import { readSettings, writeSettings } from "@/services/settings"; +import { + SETTINGS_INVALID_MESSAGE, + fieldErrorsFromIssues, + mergeSettings, + settingsUpdateSchema, + validateSettings, +} from "./schema"; + /** - * GET /api/settings — fetch user preferences (synced to backend). + * GET /api/settings: the student's study settings. Students who never saved + * any get the defaults (nothing is written on read). */ export async function GET(request: NextRequest) { const userId = await getUserId(request); if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + return unauthorized(); } - let state = await prisma.userGameState.findUnique({ where: { userId } }); - if (!state) { - state = await prisma.userGameState.create({ data: { userId } }); + try { + const settings = await readSettings(userId); + return NextResponse.json({ + ...settings, + google_configured: publicConfig().google_configured, + }); + } catch (err) { + logger.error("settings.read_failed", { user_id: userId, error: String(err) }); + return NextResponse.json({ error: "Settings didn't load. Retry." }, { status: 500 }); } - - return NextResponse.json({ - studyStart: state.studyStartTime, - studyEnd: state.studyEndTime, - dailyCap: state.dailyStudyCap, - dailyXpGoal: state.dailyXpGoal, - timezone: state.timezone, - google_configured: Boolean(process.env.GOOGLE_CLIENT_ID), - }); } -const updateSchema = z.object({ - studyStart: z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/).optional(), - studyEnd: z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/).optional(), - dailyCap: z.number().int().min(30).max(480).optional(), - dailyXpGoal: z.number().int().min(10).max(500).optional(), - // IANA timezone for streak day boundaries; empty string or null clears it (= UTC) - timezone: z.string().max(100).nullable().optional(), -}); - /** - * PUT /api/settings — update user preferences. + * PUT /api/settings: update some or all study settings. The update is + * merged onto the saved values and checked as a whole, so an end time + * before the start time is rejected even when only one of them changes. + * Rejections carry `fields`, one instruction per field. */ export async function PUT(request: NextRequest) { const userId = await getUserId(request); if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + return unauthorized(); } let body: unknown; try { body = await request.json(); } catch { - return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 }); + return NextResponse.json({ error: "Settings not saved. Retry." }, { status: 400 }); } - const parsed = updateSchema.safeParse(body); + const parsed = settingsUpdateSchema.safeParse(body); if (!parsed.success) { return NextResponse.json( - { error: "Validation failed", issues: parsed.error.issues }, + { + error: SETTINGS_INVALID_MESSAGE, + fields: fieldErrorsFromIssues(parsed.error.issues), + issues: parsed.error.issues, + }, { status: 400 }, ); } - const data = parsed.data; - const updateData: Record<string, unknown> = {}; - if (data.studyStart !== undefined) updateData.studyStartTime = data.studyStart; - if (data.studyEnd !== undefined) updateData.studyEndTime = data.studyEnd; - if (data.dailyCap !== undefined) updateData.dailyStudyCap = data.dailyCap; - if (data.dailyXpGoal !== undefined) updateData.dailyXpGoal = data.dailyXpGoal; - if (data.timezone !== undefined) { - if (data.timezone === null || data.timezone === "") { - updateData.timezone = null; - } else if (isValidTimezone(data.timezone)) { - updateData.timezone = data.timezone; - } else { - return NextResponse.json( - { error: `Invalid timezone: ${data.timezone}` }, - { status: 400 }, - ); - } - } - try { - const state = await prisma.userGameState.upsert({ - where: { userId }, - update: updateData, - create: { - userId, - ...updateData, - }, - }); - - logger.info("settings.updated", { user_id: userId, fields: Object.keys(updateData) }); + const current = await readSettings(userId); + const next = mergeSettings(current, parsed.data); + const fields = validateSettings(next); + if (Object.keys(fields).length > 0) { + return NextResponse.json({ error: SETTINGS_INVALID_MESSAGE, fields }, { status: 400 }); + } - return NextResponse.json({ - studyStart: state.studyStartTime, - studyEnd: state.studyEndTime, - dailyCap: state.dailyStudyCap, - dailyXpGoal: state.dailyXpGoal, - timezone: state.timezone, - }); + const saved = await writeSettings(userId, next); + logger.info("settings.updated", { user_id: userId, fields: Object.keys(parsed.data) }); + return NextResponse.json(saved); } catch (err) { - logger.error("settings.update_failed", { userId, error: String(err) }); - return NextResponse.json({ error: "Internal server error" }, { status: 500 }); + logger.error("settings.update_failed", { user_id: userId, error: String(err) }); + return NextResponse.json( + { error: "Settings not saved. Check your connection and retry." }, + { status: 500 }, + ); } } diff --git a/src/app/api/settings/schema.ts b/src/app/api/settings/schema.ts new file mode 100644 index 00000000..b52daecc --- /dev/null +++ b/src/app/api/settings/schema.ts @@ -0,0 +1,57 @@ +/** + * The PUT /api/settings body schema (zod, server side). The shared rules + * live in @/lib/settings-rules so the Settings form can use them without zod. + */ +import { z } from "zod"; +import { + DAILY_CAP_MINUTES, + DAILY_XP_GOAL, + SETTINGS_FIELD_MESSAGES, + TIME_PATTERN, + type SettingsField, + type SettingsFieldErrors, +} from "@/lib/settings-rules"; + +export * from "@/lib/settings-rules"; + +export const settingsUpdateSchema = z.object({ + studyStart: z.string().regex(TIME_PATTERN, SETTINGS_FIELD_MESSAGES.studyStart).optional(), + studyEnd: z.string().regex(TIME_PATTERN, SETTINGS_FIELD_MESSAGES.studyEnd).optional(), + dailyCap: z + .number() + .int() + .min(DAILY_CAP_MINUTES.min, SETTINGS_FIELD_MESSAGES.dailyCap) + .max(DAILY_CAP_MINUTES.max, SETTINGS_FIELD_MESSAGES.dailyCap) + .optional(), + dailyXpGoal: z + .number() + .int() + .min(DAILY_XP_GOAL.min, SETTINGS_FIELD_MESSAGES.dailyXpGoal) + .max(DAILY_XP_GOAL.max, SETTINGS_FIELD_MESSAGES.dailyXpGoal) + .optional(), + // Empty string or null clears the zone (UTC day boundaries). + timezone: z.string().max(100, SETTINGS_FIELD_MESSAGES.timezone).nullable().optional(), +}); + +export type SettingsUpdate = z.infer<typeof settingsUpdateSchema>; + +const FIELDS: readonly SettingsField[] = ["studyStart", "studyEnd", "dailyCap", "dailyXpGoal", "timezone"]; + +function isField(value: unknown): value is SettingsField { + return typeof value === "string" && (FIELDS as readonly string[]).includes(value); +} + +/** Maps zod issues onto fields, so "Validation failed" never reaches the screen. */ +export function fieldErrorsFromIssues( + issues: readonly { path: readonly PropertyKey[] }[], +): SettingsFieldErrors { + const errors: SettingsFieldErrors = {}; + for (const issue of issues) { + const field = issue.path[0]; + if (isField(field) && !errors[field]) { + errors[field] = SETTINGS_FIELD_MESSAGES[field]; + } + } + return errors; +} + diff --git a/src/app/api/stats/activity/route.ts b/src/app/api/stats/activity/route.ts index b080a12d..5294768a 100644 --- a/src/app/api/stats/activity/route.ts +++ b/src/app/api/stats/activity/route.ts @@ -1,83 +1,65 @@ import { NextRequest, NextResponse } from "next/server"; +import { unauthorized } from "@/lib/http"; +import { z } from "zod"; import { getUserId } from "@/lib/auth"; -import { prisma } from "@/lib/db"; +import { logger } from "@/lib/logger"; +import { addDays, dayKey } from "@/lib/timezone"; +import { getActivityByDay, getGameState } from "@/services/gamification"; +const querySchema = z.object({ + /** How many days back, today included. Defaults to a year. */ + days: z.coerce.number().int().min(1).max(400).default(371), +}); + +/** + * GET /api/stats/activity: study activity per day in the student's time + * zone, plus the streak and total XP (the same numbers Progress shows). + * + * activity[].count is what the day holds: sessions + card reviews. Each part + * is also given on its own. Guides and chat earn no XP and aren't counted. + */ export async function GET(request: NextRequest) { const userId = await getUserId(request); if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + return unauthorized(); } - try { - const now = new Date(); - const oneYearAgo = new Date(now); - oneYearAgo.setFullYear(oneYearAgo.getFullYear() - 1); - oneYearAgo.setHours(0, 0, 0, 0); - - const [completedItems, xpEvents, xpTotal] = await Promise.all([ - prisma.studyPlanItem.findMany({ - where: { - plan: { userId }, - status: "DONE", - completedAt: { gte: oneYearAgo }, - }, - select: { completedAt: true, startTime: true }, - }), - // Fetch XP event dates — dedupe to calendar days in JS - prisma.xpEvent.findMany({ - where: { userId, createdAt: { gte: oneYearAgo } }, - select: { createdAt: true }, - }), - prisma.xpEvent.aggregate({ - where: { userId }, - _sum: { xpAmount: true }, - }), - ]); - - const dailyCounts = new Map<string, number>(); - for (const item of completedItems) { - const d = item.completedAt || item.startTime; - const key = d.toISOString().slice(0, 10); - dailyCounts.set(key, (dailyCounts.get(key) || 0) + 1); - } - // Each XP event marks that day as active - for (const event of xpEvents) { - const key = event.createdAt.toISOString().slice(0, 10); - dailyCounts.set(key, (dailyCounts.get(key) || 0) + 1); - } - - const activity = Array.from(dailyCounts.entries()).map(([date, count]) => ({ - date, - count, - })); - - const todayKey = now.toISOString().slice(0, 10); - const yesterdayDate = new Date(now); - yesterdayDate.setDate(yesterdayDate.getDate() - 1); - const yesterdayKey = yesterdayDate.toISOString().slice(0, 10); - - let streak = 0; - const check = new Date(now); - check.setHours(0, 0, 0, 0); + const parsed = querySchema.safeParse({ + days: request.nextUrl.searchParams.get("days") ?? undefined, + }); + if (!parsed.success) { + return NextResponse.json( + { error: "Choose a number of days from 1 to 400.", issues: parsed.error.issues }, + { status: 400 }, + ); + } - if (dailyCounts.has(todayKey) || dailyCounts.has(yesterdayKey)) { - if (!dailyCounts.has(todayKey)) check.setDate(check.getDate() - 1); - const d = new Date(check); - while (dailyCounts.has(d.toISOString().slice(0, 10))) { - streak++; - d.setDate(d.getDate() - 1); - } - } + try { + const game = await getGameState(userId); + const todayKey = dayKey(new Date(), game.timeZone); + const sinceKey = addDays(todayKey, -(parsed.data.days - 1)); + const days = await getActivityByDay(userId, game.timeZone, sinceKey); - const xpFromEvents = xpTotal._sum.xpAmount || 0; - const totalXp = xpFromEvents > 0 - ? xpFromEvents - : await prisma.studyPlanItem.count({ - where: { plan: { userId }, status: "DONE" }, - }); + const activity = [...days.entries()] + .sort(([a], [b]) => (a < b ? -1 : 1)) + .map(([date, d]) => ({ + date, + count: d.sessions + d.reviews, + sessions: d.sessions, + reviews: d.reviews, + freeze_used: d.freezeUsed, + xp: d.xp, + })); - return NextResponse.json({ activity, streak, total_xp: totalXp }); - } catch { - return NextResponse.json({ error: "Internal server error" }, { status: 500 }); + return NextResponse.json({ + activity, + streak: game.streak, + total_xp: game.xpTotal, + time_zone: game.timeZone, + }); + } catch (err) { + logger.error("stats.activity_failed", { userId, error: String(err) }); + return NextResponse.json({ error: "Activity didn't load. Retry." }, { status: 500 }); } } + diff --git a/src/app/api/stats/daily-goal/route.ts b/src/app/api/stats/daily-goal/route.ts deleted file mode 100644 index 1129bbc3..00000000 --- a/src/app/api/stats/daily-goal/route.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { NextRequest, NextResponse } from "next/server"; -import { z } from "zod/v4"; -import { getUserId } from "@/lib/auth"; -import { setDailyXpGoal } from "@/services/gamification"; -import { logger } from "@/lib/logger"; - -const schema = z.object({ - goal: z.number().int().min(10).max(500), -}); - -export async function POST(request: NextRequest) { - const userId = await getUserId(request); - if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); - } - - let body: unknown; - try { - body = await request.json(); - } catch { - return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 }); - } - - const parsed = schema.safeParse(body); - if (!parsed.success) { - return NextResponse.json( - { error: "Validation failed", issues: parsed.error.issues }, - { status: 400 }, - ); - } - - try { - await setDailyXpGoal(userId, parsed.data.goal); - return NextResponse.json({ goal: parsed.data.goal }); - } catch (err) { - logger.error("stats.daily_goal_failed", { userId, error: String(err) }); - return NextResponse.json({ error: "Internal server error" }, { status: 500 }); - } -} diff --git a/src/app/api/stats/game/route.ts b/src/app/api/stats/game/route.ts index 7514e6e0..b42b4444 100644 --- a/src/app/api/stats/game/route.ts +++ b/src/app/api/stats/game/route.ts @@ -1,12 +1,18 @@ import { NextRequest, NextResponse } from "next/server"; +import { unauthorized } from "@/lib/http"; import { getUserId } from "@/lib/auth"; import { getGameState } from "@/services/gamification"; import { logger } from "@/lib/logger"; +/** + * GET /api/stats/game: streak, XP, freezes and achievements. Read-only; + * achievements are awarded when XP is earned, never here, so + * `newAchievements` is always empty. + */ export async function GET(request: NextRequest) { const userId = await getUserId(request); if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + return unauthorized(); } try { @@ -14,6 +20,6 @@ export async function GET(request: NextRequest) { return NextResponse.json(state); } catch (err) { logger.error("stats.game_failed", { userId, error: String(err) }); - return NextResponse.json({ error: "Internal server error" }, { status: 500 }); + return NextResponse.json({ error: "Progress didn't load. Retry." }, { status: 500 }); } } diff --git a/src/app/api/stats/streak-freeze/route.ts b/src/app/api/stats/streak-freeze/route.ts index 1c4ded52..10a4f458 100644 --- a/src/app/api/stats/streak-freeze/route.ts +++ b/src/app/api/stats/streak-freeze/route.ts @@ -1,25 +1,45 @@ import { NextRequest, NextResponse } from "next/server"; +import { unauthorized } from "@/lib/http"; import { getUserId } from "@/lib/auth"; -import { consumeStreakFreeze } from "@/services/gamification"; +import { consumeStreakFreeze, type FreezeRefusal } from "@/services/gamification"; import { logger } from "@/lib/logger"; +const REFUSALS: Record<FreezeRefusal, { status: number; error: string; code: string }> = { + no_freezes: { status: 409, error: "You have no streak freezes left.", code: "NO_FREEZES" }, + already_used_today: { + status: 409, + error: "A freeze already covers today.", + code: "FREEZE_ALREADY_USED_TODAY", + }, + already_active: { + status: 409, + error: "You studied today, so your streak is safe without a freeze.", + code: "ALREADY_STUDIED_TODAY", + }, +}; + +/** + * POST /api/stats/streak-freeze: spend one freeze on today. No body. + * 200 {success: true, freezesRemaining}; 409 {error, code, freezesRemaining}. + */ export async function POST(request: NextRequest) { const userId = await getUserId(request); if (!userId) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + return unauthorized(); } try { const result = await consumeStreakFreeze(userId); if (!result.success) { + const refusal = REFUSALS[result.reason]; return NextResponse.json( - { error: "No streak freezes available", freezesRemaining: result.freezesRemaining }, - { status: 400 }, + { error: refusal.error, code: refusal.code, freezesRemaining: result.freezesRemaining }, + { status: refusal.status }, ); } return NextResponse.json({ success: true, freezesRemaining: result.freezesRemaining }); } catch (err) { logger.error("stats.streak_freeze_failed", { userId, error: String(err) }); - return NextResponse.json({ error: "Internal server error" }, { status: 500 }); + return NextResponse.json({ error: "Freeze not used. Retry." }, { status: 500 }); } } diff --git a/src/app/auth/forgot-password/page.tsx b/src/app/auth/forgot-password/page.tsx deleted file mode 100644 index 7af41fff..00000000 --- a/src/app/auth/forgot-password/page.tsx +++ /dev/null @@ -1,107 +0,0 @@ -"use client"; - -import { useState } from "react"; -import Link from "next/link"; -import { - containerStyle, - cardStyle, - titleStyle, - subtitleStyle, - labelStyle, - inputStyle, - buttonStyle, - errorStyle, - textStyle, - mutedStyle, - switchStyle, - linkStyle, -} from "../styles"; - -export default function ForgotPasswordPage() { - const [email, setEmail] = useState(""); - const [sent, setSent] = useState(false); - const [loading, setLoading] = useState(false); - const [error, setError] = useState<string | null>(null); - - async function handleSubmit(e: React.FormEvent) { - e.preventDefault(); - setError(null); - setLoading(true); - - try { - const res = await fetch("/api/auth/forgot-password", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ email }), - }); - - if (res.status === 429) { - setError("Too many requests. Please try again later."); - setLoading(false); - return; - } - - setSent(true); - } catch { - setError("Something went wrong. Please try again."); - } finally { - setLoading(false); - } - } - - if (sent) { - return ( - <div style={containerStyle}> - <div style={cardStyle}> - <div style={{ textAlign: "center", fontSize: "3rem", marginBottom: "1rem" }}>📬</div> - <h1 style={{ ...titleStyle, margin: "0 0 1rem" }}>Check Your Email</h1> - <p style={textStyle}> - If an account with that email exists, we've sent a password reset link. - Check your inbox (and spam folder). - </p> - <p style={mutedStyle}> - <Link href="/auth/signin" style={linkStyle}>Back to sign in</Link> - </p> - </div> - </div> - ); - } - - return ( - <div style={containerStyle}> - <div style={cardStyle}> - <h1 style={titleStyle}>Forgot Password</h1> - <p style={subtitleStyle}>Enter your email and we'll send you a reset link</p> - - {error && <div style={errorStyle} role="alert" aria-live="polite">{error}</div>} - - <form onSubmit={handleSubmit}> - <label htmlFor="email" style={labelStyle}>Email</label> - <input - id="email" - type="email" - value={email} - onChange={(e) => setEmail(e.target.value)} - placeholder="you@example.com" - required - autoComplete="email" - style={inputStyle} - /> - - <button - type="submit" - disabled={loading} - style={{ ...buttonStyle, opacity: loading ? 0.6 : 1 }} - > - {loading ? "Sending..." : "Send Reset Link"} - </button> - </form> - - <p style={switchStyle}> - Remember your password?{" "} - <Link href="/auth/signin" style={linkStyle}>Sign in</Link> - </p> - </div> - </div> - ); -} diff --git a/src/app/auth/layout.tsx b/src/app/auth/layout.tsx deleted file mode 100644 index b23a0c13..00000000 --- a/src/app/auth/layout.tsx +++ /dev/null @@ -1,4 +0,0 @@ -/** Auth pages get no NavBar — clean centered layout */ -export default function AuthLayout({ children }: { children: React.ReactNode }) { - return <>{children}</>; -} diff --git a/src/app/auth/reset-password/page.tsx b/src/app/auth/reset-password/page.tsx deleted file mode 100644 index c9e6eeff..00000000 --- a/src/app/auth/reset-password/page.tsx +++ /dev/null @@ -1,169 +0,0 @@ -"use client"; - -import { useState, Suspense } from "react"; -import { useSearchParams } from "next/navigation"; -import Link from "next/link"; -import { - containerStyle, - cardStyle, - titleStyle, - subtitleStyle, - labelStyle, - buttonStyle, - errorStyle, - successStyle, - textStyle, - mutedStyle, - linkStyle, - passwordWrapperStyle, - passwordInputStyle, - passwordToggleStyle, -} from "../styles"; - -function ResetPasswordForm() { - const searchParams = useSearchParams(); - const token = searchParams.get("token"); - - const [password, setPassword] = useState(""); - const [confirmPassword, setConfirmPassword] = useState(""); - const [showPassword, setShowPassword] = useState(false); - const [error, setError] = useState<string | null>(null); - const [success, setSuccess] = useState(false); - const [loading, setLoading] = useState(false); - - if (!token) { - return ( - <div style={containerStyle}> - <div style={cardStyle}> - <h1 style={{ ...titleStyle, margin: "0 0 1rem" }}>Invalid Link</h1> - <p style={textStyle}>This password reset link is invalid or has expired.</p> - <p style={mutedStyle}> - <Link href="/auth/forgot-password" style={linkStyle}>Request a new reset link</Link> - </p> - </div> - </div> - ); - } - - async function handleSubmit(e: React.FormEvent) { - e.preventDefault(); - setError(null); - - if (password !== confirmPassword) { - setError("Passwords don't match"); - return; - } - - setLoading(true); - - try { - const res = await fetch("/api/auth/reset-password", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ token, password }), - }); - - const data = await res.json(); - - if (!res.ok) { - setError(data.error || "Something went wrong"); - setLoading(false); - return; - } - - setSuccess(true); - } catch { - setError("Something went wrong. Please try again."); - setLoading(false); - } - } - - if (success) { - return ( - <div style={containerStyle}> - <div style={cardStyle}> - <div style={{ textAlign: "center", fontSize: "3rem", marginBottom: "1rem" }}>✅</div> - <h1 style={{ ...titleStyle, margin: "0 0 1rem" }}>Password Reset</h1> - <div style={successStyle} role="alert">Your password has been reset successfully.</div> - <Link href="/auth/signin" style={{ ...buttonStyle, display: "block", textAlign: "center", textDecoration: "none", marginTop: "1rem" }}> - Sign In - </Link> - </div> - </div> - ); - } - - return ( - <div style={containerStyle}> - <div style={cardStyle}> - <h1 style={titleStyle}>Reset Password</h1> - <p style={subtitleStyle}>Enter your new password</p> - - {error && <div style={errorStyle} role="alert" aria-live="polite">{error}</div>} - - <form onSubmit={handleSubmit}> - <label htmlFor="password" style={labelStyle}>New Password</label> - <div style={passwordWrapperStyle}> - <input - id="password" - type={showPassword ? "text" : "password"} - value={password} - onChange={(e) => setPassword(e.target.value)} - placeholder="Min 8 characters" - required - minLength={8} - autoComplete="new-password" - style={passwordInputStyle} - /> - <button - type="button" - onClick={() => setShowPassword(!showPassword)} - style={passwordToggleStyle} - aria-label={showPassword ? "Hide password" : "Show password"} - className="compact-btn" - > - {showPassword ? "Hide" : "Show"} - </button> - </div> - - <label htmlFor="confirm-password" style={labelStyle}>Confirm Password</label> - <div style={passwordWrapperStyle}> - <input - id="confirm-password" - type={showPassword ? "text" : "password"} - value={confirmPassword} - onChange={(e) => setConfirmPassword(e.target.value)} - placeholder="Type it again" - required - minLength={8} - autoComplete="new-password" - style={passwordInputStyle} - /> - </div> - - <button - type="submit" - disabled={loading} - style={{ ...buttonStyle, opacity: loading ? 0.6 : 1 }} - > - {loading ? "Resetting..." : "Reset Password"} - </button> - </form> - </div> - </div> - ); -} - -export default function ResetPasswordPage() { - return ( - <Suspense fallback={ - <div style={containerStyle}> - <div style={cardStyle}> - <p style={{ textAlign: "center", color: "var(--color-text-muted)" }}>Loading...</p> - </div> - </div> - }> - <ResetPasswordForm /> - </Suspense> - ); -} diff --git a/src/app/auth/signin/page.tsx b/src/app/auth/signin/page.tsx deleted file mode 100644 index a7c815d5..00000000 --- a/src/app/auth/signin/page.tsx +++ /dev/null @@ -1,138 +0,0 @@ -"use client"; - -import { useState, Suspense } from "react"; -import { signIn } from "next-auth/react"; -import { useSearchParams } from "next/navigation"; -import Link from "next/link"; -import { - containerStyle, - cardStyle, - titleStyle, - subtitleStyle, - labelStyle, - buttonStyle, - errorStyle, - successStyle, - switchStyle, - linkStyle, - passwordWrapperStyle, - passwordInputStyle, - passwordToggleStyle, - inputStyle, -} from "../styles"; - -function SignInForm() { - const searchParams = useSearchParams(); - const justVerified = searchParams.get("verified") === "true"; - - const [email, setEmail] = useState(""); - const [password, setPassword] = useState(""); - const [showPassword, setShowPassword] = useState(false); - const [error, setError] = useState<string | null>(null); - const [loading, setLoading] = useState(false); - - async function handleSubmit(e: React.FormEvent) { - e.preventDefault(); - setError(null); - setLoading(true); - - const result = await signIn("credentials", { - email, - password, - redirect: false, - }); - - if (result?.error) { - setError("Invalid email or password"); - setLoading(false); - } else { - window.location.href = "/"; - } - } - - return ( - <div style={containerStyle}> - <div style={cardStyle}> - <h1 style={titleStyle}>Welcome Back</h1> - <p style={subtitleStyle}>Sign in to continue studying</p> - - {justVerified && ( - <div style={successStyle} role="alert">Email verified! You can now sign in.</div> - )} - - {error && <div style={errorStyle} role="alert" aria-live="polite">{error}</div>} - - <form onSubmit={handleSubmit}> - <label htmlFor="email" style={labelStyle}>Email</label> - <input - id="email" - type="email" - value={email} - onChange={(e) => setEmail(e.target.value)} - placeholder="you@example.com" - required - autoComplete="email" - style={inputStyle} - /> - - <label htmlFor="password" style={labelStyle}>Password</label> - <div style={passwordWrapperStyle}> - <input - id="password" - type={showPassword ? "text" : "password"} - value={password} - onChange={(e) => setPassword(e.target.value)} - placeholder="Min 8 characters" - required - minLength={8} - autoComplete="current-password" - style={passwordInputStyle} - /> - <button - type="button" - onClick={() => setShowPassword(!showPassword)} - style={passwordToggleStyle} - aria-label={showPassword ? "Hide password" : "Show password"} - className="compact-btn" - > - {showPassword ? "Hide" : "Show"} - </button> - </div> - - <button - type="submit" - disabled={loading} - style={{ ...buttonStyle, opacity: loading ? 0.6 : 1 }} - > - {loading ? "Signing in..." : "Sign In"} - </button> - </form> - - <p style={{ textAlign: "center", marginTop: "1rem" }}> - <Link href="/auth/forgot-password" style={{ ...linkStyle, fontSize: "0.85rem", fontWeight: 400 }}> - Forgot your password? - </Link> - </p> - - <p style={switchStyle}> - Don't have an account?{" "} - <Link href="/auth/signup" style={linkStyle}>Sign up</Link> - </p> - </div> - </div> - ); -} - -export default function SignInPage() { - return ( - <Suspense fallback={ - <div style={containerStyle}> - <div style={cardStyle}> - <p style={{ textAlign: "center", color: "var(--color-text-muted)" }}>Loading...</p> - </div> - </div> - }> - <SignInForm /> - </Suspense> - ); -} diff --git a/src/app/auth/signup/page.tsx b/src/app/auth/signup/page.tsx deleted file mode 100644 index 180c84dd..00000000 --- a/src/app/auth/signup/page.tsx +++ /dev/null @@ -1,186 +0,0 @@ -"use client"; - -import { useState } from "react"; -import { useRouter } from "next/navigation"; -import { signIn } from "next-auth/react"; -import Link from "next/link"; -import { - containerStyle, - cardStyle, - titleStyle, - subtitleStyle, - labelStyle, - inputStyle, - buttonStyle, - errorStyle, - switchStyle, - linkStyle, - passwordWrapperStyle, - passwordInputStyle, - passwordToggleStyle, -} from "../styles"; - -export default function SignUpPage() { - const [name, setName] = useState(""); - const [email, setEmail] = useState(""); - const [password, setPassword] = useState(""); - const [confirmPassword, setConfirmPassword] = useState(""); - const [showPassword, setShowPassword] = useState(false); - const [error, setError] = useState<string | null>(null); - const [loading, setLoading] = useState(false); - const router = useRouter(); - - async function handleSubmit(e: React.FormEvent) { - e.preventDefault(); - setError(null); - - if (password !== confirmPassword) { - setError("Passwords don't match"); - return; - } - - setLoading(true); - - try { - const res = await fetch("/api/auth/signup", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ email, password, name }), - }); - - const data = await res.json(); - if (!res.ok) { - setError(data.error || "Failed to create account"); - setLoading(false); - return; - } - - // When email verification is not required (the default), sign the new - // user in with the credentials they just chose and land them on the - // dashboard, which shows onboarding for fresh accounts. Only send them - // to "Check Your Email" when this server actually requires verification. - let verificationRequired = true; - try { - const configRes = await fetch("/api/config"); - if (configRes.ok) { - const config = await configRes.json(); - verificationRequired = config.verification_required === true; - } - } catch { - // Config unavailable — fall through to the verify-email page, which - // explains that verification may be optional. - } - - if (!verificationRequired) { - const result = await signIn("credentials", { - email, - password, - redirect: false, - }); - if (!result?.error) { - window.location.href = "/"; - return; - } - // Auto sign-in failed unexpectedly; let the user sign in manually. - router.push("/auth/signin"); - return; - } - - // Redirect to verify-email page with email for resend - router.push(`/auth/verify-email?email=${encodeURIComponent(email)}`); - } catch { - setError("Something went wrong. Please try again."); - setLoading(false); - } - } - - return ( - <div style={containerStyle}> - <div style={cardStyle}> - <h1 style={titleStyle}>Create Account</h1> - <p style={subtitleStyle}>Start your study journey</p> - - {error && <div style={errorStyle} role="alert" aria-live="polite">{error}</div>} - - <form onSubmit={handleSubmit}> - <label htmlFor="name" style={labelStyle}>Name</label> - <input - id="name" - type="text" - value={name} - onChange={(e) => setName(e.target.value)} - placeholder="Your name" - required - maxLength={50} - autoComplete="name" - style={inputStyle} - /> - - <label htmlFor="email" style={labelStyle}>Email</label> - <input - id="email" - type="email" - value={email} - onChange={(e) => setEmail(e.target.value)} - placeholder="you@example.com" - required - autoComplete="email" - style={inputStyle} - /> - - <label htmlFor="password" style={labelStyle}>Password</label> - <div style={passwordWrapperStyle}> - <input - id="password" - type={showPassword ? "text" : "password"} - value={password} - onChange={(e) => setPassword(e.target.value)} - placeholder="Min 8 characters" - required - minLength={8} - autoComplete="new-password" - style={passwordInputStyle} - /> - <button - type="button" - onClick={() => setShowPassword(!showPassword)} - style={passwordToggleStyle} - aria-label={showPassword ? "Hide password" : "Show password"} - className="compact-btn" - > - {showPassword ? "Hide" : "Show"} - </button> - </div> - - <label htmlFor="confirm-password" style={labelStyle}>Confirm Password</label> - <div style={passwordWrapperStyle}> - <input - id="confirm-password" - type={showPassword ? "text" : "password"} - value={confirmPassword} - onChange={(e) => setConfirmPassword(e.target.value)} - placeholder="Type it again" - required - minLength={8} - autoComplete="new-password" - style={passwordInputStyle} - /> - </div> - - <button - type="submit" - disabled={loading} - style={{ ...buttonStyle, opacity: loading ? 0.6 : 1 }} - > - {loading ? "Creating account..." : "Create Account"} - </button> - </form> - - <p style={switchStyle}> - Already have an account?{" "} - <Link href="/auth/signin" style={linkStyle}>Sign in</Link> - </p> - </div> - </div> - ); -} diff --git a/src/app/auth/styles.ts b/src/app/auth/styles.ts deleted file mode 100644 index 58038b69..00000000 --- a/src/app/auth/styles.ts +++ /dev/null @@ -1,150 +0,0 @@ -/** Shared styles for all auth pages */ - -export const containerStyle: React.CSSProperties = { - minHeight: "100vh", - display: "flex", - alignItems: "center", - justifyContent: "center", - padding: "1rem", - fontFamily: "var(--font-body)", - backgroundColor: "var(--color-bg)", -}; - -export const cardStyle: React.CSSProperties = { - width: "100%", - maxWidth: 400, - background: "var(--color-bg-card)", - border: "1px solid var(--color-border-subtle)", - borderRadius: "var(--radius-lg)", - boxShadow: "var(--shadow-card)", - padding: "2rem", -}; - -export const titleStyle: React.CSSProperties = { - fontSize: "1.8rem", - fontFamily: "var(--font-display)", - color: "var(--color-primary)", - margin: "0 0 0.25rem", - textAlign: "center", -}; - -export const subtitleStyle: React.CSSProperties = { - color: "var(--color-text-muted)", - textAlign: "center", - margin: "0 0 1.5rem", - fontSize: "0.95rem", -}; - -export const labelStyle: React.CSSProperties = { - display: "block", - fontSize: "0.85rem", - color: "var(--color-text-faint)", - marginBottom: "0.3rem", - textTransform: "uppercase", - letterSpacing: "0.06em", -}; - -export const inputStyle: React.CSSProperties = { - width: "100%", - padding: "0.65rem 0.75rem", - fontSize: "1rem", - fontFamily: "inherit", - background: "var(--color-bg-input)", - color: "var(--color-text)", - border: "1px solid var(--color-border)", - borderRadius: "var(--radius-sm)", - marginBottom: "1rem", - boxSizing: "border-box", -}; - -export const buttonStyle: React.CSSProperties = { - width: "100%", - padding: "0.75rem 1.5rem", - fontSize: "1.05rem", - fontFamily: "inherit", - fontWeight: 600, - background: "var(--color-primary)", - color: "var(--color-bg-darkest)", - border: "none", - borderRadius: "var(--radius)", - cursor: "pointer", - marginTop: "0.5rem", -}; - -export const errorStyle: React.CSSProperties = { - background: "var(--color-bg-error-tint)", - color: "var(--color-error)", - padding: "0.5rem 0.75rem", - borderRadius: "var(--radius-sm)", - fontSize: "0.85rem", - marginBottom: "1rem", - textAlign: "center", - border: "1px solid var(--color-error)", -}; - -export const successStyle: React.CSSProperties = { - background: "var(--color-bg-success-tint)", - color: "var(--color-success)", - padding: "0.5rem 0.75rem", - borderRadius: "var(--radius-sm)", - fontSize: "0.85rem", - marginBottom: "1rem", - textAlign: "center", - border: "1px solid var(--color-border-done)", -}; - -export const switchStyle: React.CSSProperties = { - textAlign: "center", - color: "var(--color-text-muted)", - fontSize: "0.9rem", - marginTop: "1.5rem", -}; - -export const linkStyle: React.CSSProperties = { - color: "var(--color-primary)", - textDecoration: "none", - fontWeight: 600, -}; - -export const textStyle: React.CSSProperties = { - color: "var(--color-text)", - textAlign: "center", - fontSize: "1rem", - lineHeight: 1.6, - margin: "0 0 1rem", -}; - -export const mutedStyle: React.CSSProperties = { - color: "var(--color-text-muted)", - textAlign: "center", - fontSize: "0.9rem", - margin: "0.5rem 0", -}; - -/** Wrapper style for password field + toggle button */ -export const passwordWrapperStyle: React.CSSProperties = { - position: "relative", - marginBottom: "1rem", -}; - -export const passwordInputStyle: React.CSSProperties = { - ...inputStyle, - marginBottom: 0, - paddingRight: "2.75rem", -}; - -export const passwordToggleStyle: React.CSSProperties = { - position: "absolute", - right: "0.5rem", - top: "50%", - transform: "translateY(-50%)", - background: "none", - border: "none", - color: "var(--color-text-muted)", - cursor: "pointer", - padding: "0.25rem", - fontSize: "0.85rem", - lineHeight: 1, - minHeight: "auto", - minWidth: "auto", -}; diff --git a/src/app/auth/verify-email/page.tsx b/src/app/auth/verify-email/page.tsx deleted file mode 100644 index 490ffb3f..00000000 --- a/src/app/auth/verify-email/page.tsx +++ /dev/null @@ -1,112 +0,0 @@ -"use client"; - -import { useState, Suspense } from "react"; -import { useSearchParams } from "next/navigation"; -import Link from "next/link"; -import { - containerStyle, - cardStyle, - titleStyle, - textStyle, - mutedStyle, - linkStyle, - buttonStyle, - errorStyle, - successStyle, -} from "../styles"; - -function VerifyEmailContent() { - const searchParams = useSearchParams(); - const emailParam = searchParams.get("email") || ""; - - const [resending, setResending] = useState(false); - const [resent, setResent] = useState(false); - const [error, setError] = useState<string | null>(null); - - async function handleResend() { - if (!emailParam || resending) return; - setResending(true); - setError(null); - - try { - const res = await fetch("/api/auth/resend-verification", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ email: emailParam }), - }); - - if (res.status === 429) { - setError("Too many requests. Please wait a few minutes."); - setResending(false); - return; - } - - setResent(true); - } catch { - setError("Something went wrong. Please try again."); - } finally { - setResending(false); - } - } - - return ( - <div style={containerStyle}> - <div style={cardStyle}> - <div style={{ textAlign: "center", fontSize: "3rem", marginBottom: "1rem" }}>📧</div> - <h1 style={{ ...titleStyle, margin: "0 0 1rem" }}>Check Your Email</h1> - <p style={textStyle}> - We've sent a verification link to your email address. - Click the link to activate your account. - </p> - <p style={mutedStyle}> - The link expires in 24 hours. If you don't see it, check your spam folder. - </p> - <p style={mutedStyle}> - Seeing this page means this server has REQUIRE_EMAIL_VERIFICATION enabled - (verification is off by default). Running locally with the default console email - provider? The verification link is printed in the terminal where{" "} - <code>npm run dev</code> is running. - </p> - - {error && <div style={errorStyle} role="alert" aria-live="polite">{error}</div>} - {resent && <div style={successStyle} role="alert">Verification email resent!</div>} - - {emailParam && !resent && ( - <button - onClick={handleResend} - disabled={resending} - style={{ - ...buttonStyle, - background: "var(--color-bg-input)", - color: "var(--color-text)", - border: "1px solid var(--color-border)", - opacity: resending ? 0.6 : 1, - marginTop: "1rem", - }} - > - {resending ? "Resending..." : "Resend verification email"} - </button> - )} - - <p style={mutedStyle}> - Already verified?{" "} - <Link href="/auth/signin" style={linkStyle}>Sign in</Link> - </p> - </div> - </div> - ); -} - -export default function VerifyEmailPage() { - return ( - <Suspense fallback={ - <div style={containerStyle}> - <div style={cardStyle}> - <p style={{ textAlign: "center", color: "var(--color-text-muted)" }}>Loading...</p> - </div> - </div> - }> - <VerifyEmailContent /> - </Suspense> - ); -} diff --git a/src/app/chat/page.tsx b/src/app/chat/page.tsx deleted file mode 100644 index 136e2e1b..00000000 --- a/src/app/chat/page.tsx +++ /dev/null @@ -1,710 +0,0 @@ -"use client"; - -import { useState, useRef, useEffect, useCallback } from "react"; -import Link from "next/link"; -import { getActiveCourse, setActiveCourse } from "@/lib/client-utils"; -import { apiGet, apiPost, apiDelete, type CourseOption } from "@/lib/client-api"; -import { titleStyle, subtitleStyle, selectStyle } from "@/lib/shared-styles"; -import { ErrorBoundary } from "@/ui/components/ErrorBoundary"; - -// --- Types --- - -interface Citation { - chunk_id: string; - reason: string; - quote_snippet: string; -} - -interface Message { - id: string; - role: "user" | "assistant"; - content: string; - citations?: Citation[]; - meta?: { chunks_retrieved?: number; latency_ms?: number }; -} - -const CHAT_PAGE_SIZE = 50; - -export default function ChatPage() { - const [messages, setMessages] = useState<Message[]>([]); - const [input, setInput] = useState(""); - const [loading, setLoading] = useState(false); - const [courses, setCourses] = useState<CourseOption[]>([]); - const [selectedCourse, setSelectedCourseRaw] = useState<string>(() => getActiveCourse()); - const setSelectedCourse = (v: string) => { setSelectedCourseRaw(v); setActiveCourse(v); }; - const [expandedCitation, setExpandedCitation] = useState<string | null>(null); - const [hasMore, setHasMore] = useState(false); - const [loadingMore, setLoadingMore] = useState(false); - const messagesEndRef = useRef<HTMLDivElement>(null); - const inputRef = useRef<HTMLTextAreaElement>(null); - - // Load chat history from database when course changes - useEffect(() => { - if (!selectedCourse) return; - let mounted = true; - const params = new URLSearchParams({ courseKey: selectedCourse, limit: String(CHAT_PAGE_SIZE) }); - apiGet(`/api/chat/messages?${params.toString()}`) - .then((data) => { - if (!mounted) return; - if (data.messages) { - const msgs = data.messages.map((m: { id: string; role: string; content: string; citations?: Citation[] }) => ({ - id: m.id, - role: m.role as "user" | "assistant", - content: m.content, - citations: m.citations as Citation[] | undefined, - })); - setMessages(msgs); - setHasMore(msgs.length >= CHAT_PAGE_SIZE); - } - }) - .catch(() => { - if (mounted) setMessages([]); - }); - return () => { mounted = false; }; - }, [selectedCourse]); - - const loadOlderMessages = useCallback(async () => { - if (!selectedCourse || loadingMore || messages.length === 0) return; - setLoadingMore(true); - const oldest = messages[0]; - const params = new URLSearchParams({ - courseKey: selectedCourse, - limit: String(CHAT_PAGE_SIZE), - before: oldest.id, - }); - try { - const data = await apiGet(`/api/chat/messages?${params.toString()}`); - if (data.messages && data.messages.length > 0) { - const older = data.messages.map((m: { id: string; role: string; content: string; citations?: Citation[] }) => ({ - id: m.id, - role: m.role as "user" | "assistant", - content: m.content, - citations: m.citations as Citation[] | undefined, - })); - setMessages((prev) => [...older, ...prev]); - setHasMore(older.length >= CHAT_PAGE_SIZE); - } else { - setHasMore(false); - } - } catch { - // Keep existing messages - } finally { - setLoadingMore(false); - } - }, [selectedCourse, loadingMore, messages]); - - // Fetch available courses on mount - useEffect(() => { - let mounted = true; - apiGet("/api/content/documents?namespace=COURSE").then((data) => { - if (!mounted) return; - if (data.documents) { - const courseMap = new Map<string, CourseOption>(); - for (const doc of data.documents as { course_name: string; exam_name: string | null }[]) { - if (!doc.course_name) continue; - const key = doc.exam_name - ? `${doc.course_name}||${doc.exam_name}` - : doc.course_name; - const existing = courseMap.get(key); - if (existing) { - existing.doc_count++; - } else { - courseMap.set(key, { - course_name: doc.course_name, - exam_name: doc.exam_name || undefined, - doc_count: 1, - }); - } - } - const options = Array.from(courseMap.values()); - setCourses(options); - const active = getActiveCourse(); - const match = active && options.some((o) => (o.exam_name ? `${o.course_name}||${o.exam_name}` : o.course_name) === active); - if (match) { - setSelectedCourse(active); - } else if (!selectedCourse && options.length > 0) { - setSelectedCourse( - options[0].exam_name - ? `${options[0].course_name}||${options[0].exam_name}` - : options[0].course_name - ); - } - } - }).catch(() => {}); - return () => { mounted = false; }; - // eslint-disable-next-line react-hooks/exhaustive-deps - }, []); - - // Scroll to bottom on new messages - useEffect(() => { - messagesEndRef.current?.scrollIntoView({ behavior: "smooth" }); - }, [messages]); - - const sendMessage = useCallback(async () => { - const question = input.trim(); - if (!question || !selectedCourse || loading) return; - - const [courseName, examName] = selectedCourse.split("||"); - - // Optimistically add user message to UI - const tempUserMsg: Message = { - id: `temp-u-${Date.now()}`, - role: "user", - content: question, - }; - - setMessages((prev) => [...prev, tempUserMsg]); - setInput(""); - setLoading(true); - - // Persist user message to database - try { - const { message: savedUserMsg } = await apiPost("/api/chat/messages", { - courseKey: selectedCourse, - role: "user", - content: question, - }); - // Replace temp message with server-assigned id - setMessages((prev) => - prev.map((m) => (m.id === tempUserMsg.id ? { ...m, id: savedUserMsg.id } : m)), - ); - } catch { - // Keep the temp message in UI even if persistence fails - } - - try { - const response = await apiPost("/api/assistant/answer", { - question, - course_name: courseName, - exam_name: examName || undefined, - verbosity: "MEDIUM", - top_k: 5, - }); - - const assistantContent = response.answer_markdown || "No response received."; - const assistantCitations = response.citations || []; - - // Persist assistant message to database - let assistantId = `temp-a-${Date.now()}`; - try { - const { message: savedAssistantMsg } = await apiPost("/api/chat/messages", { - courseKey: selectedCourse, - role: "assistant", - content: assistantContent, - citations: assistantCitations.length > 0 ? assistantCitations : undefined, - }); - assistantId = savedAssistantMsg.id; - } catch { - // Keep temp id if persistence fails - } - - const assistantMsg: Message = { - id: assistantId, - role: "assistant", - content: assistantContent, - citations: assistantCitations, - meta: response.meta, - }; - - setMessages((prev) => [...prev, assistantMsg]); - } catch (err) { - setMessages((prev) => [ - ...prev, - { - id: `e-${Date.now()}`, - role: "assistant", - content: err instanceof Error ? err.message : "Something went wrong. Please try again.", - meta: { failed: true } as any, - }, - ]); - } finally { - setLoading(false); - inputRef.current?.focus(); - } - }, [input, selectedCourse, loading]); - - const clearChat = useCallback(async () => { - if (!selectedCourse) return; - if (!window.confirm("Clear all messages in this chat? This cannot be undone.")) return; - setMessages([]); - try { - await apiDelete(`/api/chat/messages?courseKey=${encodeURIComponent(selectedCourse)}`); - } catch { - // UI already cleared - } - }, [selectedCourse]); - - const parsedCourse = selectedCourse.split("||"); - - return ( - <div id="main-content" style={pageContainer}> - {/* Header */} - <div style={headerStyle}> - <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between" }}> - <h1 style={titleStyle}>Chat</h1> - {messages.length > 0 && ( - <button - className="compact-btn" - onClick={clearChat} - style={clearButton} - type="button" - > - Clear chat - </button> - )} - </div> - <p style={{ ...subtitleStyle, margin: "0 0 0.75rem" }}>Ask questions about your course materials</p> - - {/* Course selector */} - {courses.length > 0 ? ( - <select - aria-label="Select course" - value={selectedCourse} - onChange={(e) => setSelectedCourse(e.target.value)} - style={selectStyle} - > - {courses.map((c) => { - const val = c.exam_name - ? `${c.course_name}||${c.exam_name}` - : c.course_name; - const label = c.exam_name - ? `${c.course_name} — ${c.exam_name} (${c.doc_count} doc${c.doc_count > 1 ? "s" : ""})` - : `${c.course_name} (${c.doc_count} doc${c.doc_count > 1 ? "s" : ""})`; - return ( - <option key={val} value={val}> - {label} - </option> - ); - })} - </select> - ) : ( - <p style={{ color: "var(--color-warning)", fontSize: "0.85rem", margin: 0 }}> - No course documents uploaded yet.{" "} - <Link href="/flashcards" style={{ color: "var(--color-primary)", textDecoration: "underline" }}> - Upload materials on the Flashcards page - </Link>{" "} - to start chatting with your content. - </p> - )} - </div> - - {/* Messages */} - <div style={messagesContainer} role="log" aria-live="polite"> - <div style={threadColumn}> - {hasMore && ( - <div style={{ textAlign: "center", paddingBottom: "0.75rem" }}> - <button - type="button" - onClick={loadOlderMessages} - disabled={loadingMore} - style={{ - fontSize: "0.75rem", - fontFamily: "inherit", - background: "var(--color-bg-card)", - color: "var(--color-text-muted)", - border: "1px solid var(--color-border-subtle)", - borderRadius: "var(--radius-sm)", - padding: "0.35rem 0.75rem", - cursor: loadingMore ? "wait" : "pointer", - opacity: loadingMore ? 0.6 : 1, - }} - > - {loadingMore ? "Loading..." : "Load older messages"} - </button> - </div> - )} - {messages.length === 0 && ( - <div style={emptyState}> - <p style={{ fontSize: "1.2rem", color: "var(--color-text-muted)", marginBottom: "0.5rem" }}> - Ask anything about your {parsedCourse[0] || "course"} materials - </p> - <p style={{ fontSize: "0.85rem", color: "var(--color-text-dim)" }}> - Your answers will be grounded in your uploaded documents with inline citations. - </p> - <p style={{ fontSize: "0.75rem", color: "var(--color-text-dim)", marginTop: "0.25rem" }}> - Press <kbd style={kbdStyle}>Enter</kbd> to send, <kbd style={kbdStyle}>Shift+Enter</kbd> for new line - </p> - </div> - )} - - {messages.map((msg) => ( - <ErrorBoundary key={msg.id} fallback={<div style={{ padding: "0.5rem", color: "var(--color-text-muted)" }}>Failed to render message.</div>}> - <div style={{ marginBottom: "1rem" }} role="article"> - {/* Message bubble */} - <div - style={ - msg.role === "user" ? userBubble : assistantBubble - } - > - <div - style={{ - fontSize: "0.7rem", - color: msg.role === "user" ? "var(--color-primary)" : "var(--color-info)", - marginBottom: "0.3rem", - fontWeight: 600, - letterSpacing: "0.05em", - }} - > - {msg.role === "user" ? "YOU" : "STUDY BOT"} - </div> - <div style={{ fontSize: "0.95rem", lineHeight: 1.65, whiteSpace: "pre-wrap" }}> - {renderAnswerWithCitations(msg.content, msg.citations)} - </div> - </div> - - {/* Citations */} - {msg.citations && msg.citations.length > 0 && ( - <div style={{ marginLeft: "0.5rem", marginTop: "0.4rem" }}> - <div - style={{ - fontSize: "0.7rem", - color: "var(--color-text-dim)", - marginBottom: "0.3rem", - letterSpacing: "0.05em", - }} - > - SOURCES ({msg.citations.length}) - </div> - {msg.citations.map((c, i) => ( - <div key={c.chunk_id} style={{ marginBottom: "0.3rem" }}> - <button - type="button" - aria-expanded={expandedCitation === `${msg.id}-${i}`} - onClick={() => - setExpandedCitation( - expandedCitation === `${msg.id}-${i}` - ? null - : `${msg.id}-${i}` - ) - } - style={citationButton} - > - <span style={citationBadge}>{i + 1}</span> - <span style={{ flex: 1, textAlign: "left" }}>{c.reason}</span> - <span style={{ color: "var(--color-text-dim)", fontSize: "0.75rem" }}> - {expandedCitation === `${msg.id}-${i}` ? "▼" : "▶"} - </span> - </button> - {expandedCitation === `${msg.id}-${i}` && ( - <div style={citationExpanded}> - <p style={{ margin: 0, fontSize: "0.8rem", lineHeight: 1.5, fontStyle: "italic" }}> - “{c.quote_snippet}” - </p> - </div> - )} - </div> - ))} - </div> - )} - - {/* Meta info */} - {msg.meta && !(msg.meta as any).failed && ( - <div style={{ fontSize: "0.65rem", color: "var(--color-text-dim)", marginTop: "0.25rem", marginLeft: "0.5rem" }}> - {msg.meta.chunks_retrieved ?? 0} sources searched - {msg.meta.latency_ms ? ` · ${(msg.meta.latency_ms / 1000).toFixed(1)}s` : ""} - </div> - )} - - {/* Retry button for failed messages */} - {msg.role === "assistant" && (msg.meta as any)?.failed && ( - <button - type="button" - onClick={() => { - // Remove the error message and the user message before it, then resend - const idx = messages.findIndex((m) => m.id === msg.id); - const userMsg = idx > 0 ? messages[idx - 1] : null; - if (userMsg && userMsg.role === "user") { - setMessages((prev) => prev.filter((m) => m.id !== msg.id)); - setInput(userMsg.content); - } - }} - style={{ - display: "inline-flex", - alignItems: "center", - gap: "0.3rem", - marginTop: "0.4rem", - marginLeft: "0.5rem", - padding: "0.25rem 0.6rem", - fontSize: "0.75rem", - fontFamily: "inherit", - background: "var(--color-bg)", - color: "var(--color-warning)", - border: "1px solid var(--color-border-subtle)", - borderRadius: "var(--radius-sm)", - cursor: "pointer", - }} - > - Retry - </button> - )} - </div> - </ErrorBoundary> - ))} - - {loading && ( - <div style={assistantBubble}> - <div style={{ fontSize: "0.7rem", color: "var(--color-info)", marginBottom: "0.3rem", fontWeight: 600 }}> - STUDY BOT - </div> - <div style={{ color: "var(--color-text-muted)", fontSize: "0.85rem", display: "flex", alignItems: "center", gap: "0.4rem" }}> - Searching your materials - <span style={dotAnimation}> - <span className="dot1">.</span> - <span className="dot2">.</span> - <span className="dot3">.</span> - </span> - </div> - <style>{` - @keyframes blink { 0%,20% { opacity: 0.2; } 50% { opacity: 1; } 100% { opacity: 0.2; } } - .dot1 { animation: blink 1.4s infinite 0s; } - .dot2 { animation: blink 1.4s infinite 0.2s; } - .dot3 { animation: blink 1.4s infinite 0.4s; } - `}</style> - </div> - )} - - <div ref={messagesEndRef} /> - </div> - </div> - - {/* Input area */} - <div style={inputContainer}> - <textarea - ref={inputRef} - aria-label="Ask a question" - value={input} - onChange={(e) => setInput(e.target.value)} - placeholder={ - courses.length === 0 - ? "Upload course materials first..." - : "Ask a question about your materials..." - } - disabled={courses.length === 0 || loading} - rows={3} - style={inputStyle} - onKeyDown={(e) => { - if (e.key === "Enter" && !e.shiftKey) { - e.preventDefault(); - sendMessage(); - } - }} - /> - <button - className="compact-btn" - onClick={sendMessage} - disabled={!input.trim() || !selectedCourse || loading || courses.length === 0} - aria-label="Send message" - type="button" - style={{ - ...sendButton, - opacity: input.trim() && selectedCourse && !loading ? 1 : 0.4, - }} - > - {loading ? "..." : "Ask"} - </button> - </div> - </div> - ); -} - -// --- Citation rendering --- - -function renderAnswerWithCitations( - text: string, - citations?: Citation[] -): React.ReactNode { - if (!citations || citations.length === 0) return text; - - // Replace [1], [2], etc. with styled citation badges - const parts = text.split(/(\[\d+\])/g); - return parts.map((part, i) => { - const match = part.match(/^\[(\d+)\]$/); - if (match) { - const num = parseInt(match[1], 10); - return ( - <span - key={i} - style={inlineCitationBadge} - title={citations[num - 1]?.reason || `Source ${num}`} - > - {num} - </span> - ); - } - return part; - }); -} - -// --- Styles --- - -const pageContainer: React.CSSProperties = { - display: "flex", - flexDirection: "column", - height: "calc(100vh - 52px)", - maxWidth: 1100, - margin: "0 auto", - padding: "0 clamp(1.5rem, 4vw, 2rem)", - fontFamily: "var(--font-body)", - color: "var(--color-text)", -}; - -const threadColumn: React.CSSProperties = { - width: "100%", - maxWidth: 900, - margin: "0 auto", -}; - -const headerStyle: React.CSSProperties = { - ...threadColumn, - padding: "1.25rem 0 1rem", - borderBottom: "1px solid var(--color-border-subtle)", - flexShrink: 0, -}; - -const messagesContainer: React.CSSProperties = { - flex: 1, - overflowY: "auto", - padding: "1rem 0", -}; - -const emptyState: React.CSSProperties = { - textAlign: "center", - padding: "3rem 1rem", -}; - -const userBubble: React.CSSProperties = { - background: "var(--color-bg-selected)", - border: "1px solid var(--color-border)", - borderRadius: "var(--radius)", - padding: "1rem 1.25rem", - marginLeft: "min(3rem, 12%)", -}; - -const assistantBubble: React.CSSProperties = { - background: "var(--color-bg-card)", - border: "1px solid var(--color-border-subtle)", - borderRadius: "var(--radius)", - padding: "1rem 1.25rem", - marginRight: "min(3rem, 12%)", -}; - -const citationButton: React.CSSProperties = { - display: "flex", - alignItems: "center", - gap: "0.5rem", - width: "100%", - padding: "0.55rem 0.8rem", - fontSize: "0.8rem", - fontFamily: "inherit", - background: "var(--color-bg)", - color: "var(--color-text-muted)", - border: "1px solid var(--color-border-subtle)", - borderRadius: "var(--radius-sm)", - cursor: "pointer", - textAlign: "left", -}; - -const citationBadge: React.CSSProperties = { - display: "inline-flex", - alignItems: "center", - justifyContent: "center", - width: 18, - height: 18, - borderRadius: "50%", - background: "var(--color-info)", - color: "var(--color-bg-darkest)", - fontSize: "0.65rem", - fontWeight: 700, - flexShrink: 0, -}; - -const inlineCitationBadge: React.CSSProperties = { - display: "inline-flex", - alignItems: "center", - justifyContent: "center", - width: 16, - height: 16, - borderRadius: "50%", - background: "var(--color-info)", - color: "var(--color-bg-darkest)", - fontSize: "0.6rem", - fontWeight: 700, - marginLeft: 2, - marginRight: 2, - verticalAlign: "super", - cursor: "help", -}; - -const citationExpanded: React.CSSProperties = { - background: "var(--color-bg)", - border: "1px solid var(--color-border-subtle)", - borderTop: "none", - borderRadius: "0 0 var(--radius-sm) var(--radius-sm)", - padding: "0.6rem 0.8rem", - color: "var(--color-text-secondary)", -}; - -const inputContainer: React.CSSProperties = { - ...threadColumn, - display: "flex", - gap: "0.6rem", - padding: "0.85rem 0", - borderTop: "1px solid var(--color-border-subtle)", - flexShrink: 0, - position: "sticky", - bottom: 0, - background: "var(--color-bg)", -}; - -const inputStyle: React.CSSProperties = { - flex: 1, - padding: "0.75rem 0.9rem", - fontSize: "0.95rem", - fontFamily: "inherit", - background: "var(--color-bg-input)", - color: "var(--color-text)", - border: "1px solid var(--color-border)", - borderRadius: "var(--radius-sm)", - resize: "none", -}; - -const sendButton: React.CSSProperties = { - padding: "0.7rem 1.4rem", - fontSize: "1rem", - fontFamily: "var(--font-display)", - fontWeight: 700, - background: "var(--color-primary)", - color: "var(--color-bg-darkest)", - border: "none", - borderRadius: "var(--radius)", - cursor: "pointer", - alignSelf: "flex-end", -}; - -const clearButton: React.CSSProperties = { - fontSize: "0.75rem", - fontFamily: "inherit", - color: "var(--color-text-dim)", - background: "none", - border: "1px solid var(--color-border-subtle)", - borderRadius: "var(--radius-sm)", - padding: "0.25rem 0.6rem", - cursor: "pointer", -}; - -const kbdStyle: React.CSSProperties = { - display: "inline-block", - fontSize: "0.65rem", - fontFamily: "var(--font-mono)", - background: "var(--color-bg-card)", - border: "1px solid var(--color-border)", - borderRadius: 3, - padding: "0.05rem 0.35rem", - color: "var(--color-text)", -}; - -const dotAnimation: React.CSSProperties = { - fontSize: "1.2rem", - letterSpacing: "0.1em", - lineHeight: 1, -}; diff --git a/src/app/error.tsx b/src/app/error.tsx index 1920b60b..c591420c 100644 --- a/src/app/error.tsx +++ b/src/app/error.tsx @@ -1,75 +1,45 @@ "use client"; -export default function GlobalError({ +import { useEffect } from "react"; +import Link from "next/link"; +import { CloudOffIcon, RotateCcwIcon } from "lucide-react"; + +import { StatusScreen } from "@/components/app/status-screen"; +import { Button } from "@/components/ui/button"; + +/** Errors outside the app shell: auth screens and study sessions. */ +export default function RootError({ error, - reset, + retry, }: { error: Error & { digest?: string }; - reset: () => void; + /** Refetches and re-renders the segment (reset would only re-render the failed payload). */ + retry: () => void; }) { + useEffect(() => { + console.error(error); + }, [error]); + return ( - <div - style={{ - minHeight: "100vh", - display: "flex", - alignItems: "center", - justifyContent: "center", - padding: "1rem", - fontFamily: "var(--font-body)", - backgroundColor: "var(--color-bg)", - }} - > - <div - style={{ - width: "100%", - maxWidth: 400, - background: "var(--color-bg-card)", - border: "1px solid var(--color-border-subtle)", - borderRadius: "var(--radius-lg)", - boxShadow: "var(--shadow-card)", - padding: "2rem", - textAlign: "center", - }} - > - <div style={{ fontSize: "3rem", marginBottom: "1rem" }}>😵</div> - <h1 - style={{ - fontSize: "1.6rem", - fontFamily: "var(--font-display)", - color: "var(--color-error)", - margin: "0 0 0.5rem", - }} - > - Something went wrong - </h1> - <p - style={{ - color: "var(--color-text-muted)", - fontSize: "0.9rem", - margin: "0 0 1.5rem", - lineHeight: 1.5, - }} - > - {error.message || "An unexpected error occurred. Please try again."} - </p> - <button - onClick={reset} - style={{ - width: "100%", - padding: "0.75rem", - fontSize: "1.05rem", - fontFamily: "inherit", - fontWeight: 600, - background: "var(--color-primary)", - color: "var(--color-bg-darkest)", - border: "none", - borderRadius: "var(--radius-sm)", - cursor: "pointer", - }} - > - Try again - </button> - </div> - </div> + <main id="main-content" tabIndex={-1} className="flex min-h-dvh flex-col bg-surface"> + <StatusScreen + icon={CloudOffIcon} + tone="error" + title="This page didn't load." + description="Your saved work is safe. Retry, or go back to Home." + actions={ + <> + <Button onClick={() => retry()}> + <RotateCcwIcon data-icon="inline-start" aria-hidden="true" /> + Retry + </Button> + <Button asChild variant="outline"> + <Link href="/">Go to Home</Link> + </Button> + </> + } + footnote={error.digest ? `Reference: ${error.digest}` : undefined} + /> + </main> ); } diff --git a/src/app/flashcards/page.tsx b/src/app/flashcards/page.tsx deleted file mode 100644 index 4867066f..00000000 --- a/src/app/flashcards/page.tsx +++ /dev/null @@ -1,754 +0,0 @@ -"use client"; - -import { useState, useEffect, useCallback, useRef } from "react"; -import Link from "next/link"; -import { getActiveCourse, setActiveCourse } from "@/lib/client-utils"; -import { apiGet, apiPost, apiDelete, type CourseOption } from "@/lib/client-api"; -import { - headerStyle, - titleStyle, - subtitleStyle, - labelStyle, - selectStyle, - generateBtnStyle, - sectionTitleStyle, - deleteBtnStyle, -} from "@/lib/shared-styles"; -import { ErrorBoundary } from "@/ui/components/ErrorBoundary"; - -// --- Types --- - -interface CardData { - id: string; - front: string; - back: string; - tags: string[] | null; - ordinal: number; - easeFactor: number; - intervalDays: number; - repetitions: number; - nextDueAt: string | null; - status: "new" | "learning" | "review" | "mastered"; -} - -interface StudyDeck { - deck: { id: string; title: string; courseName: string }; - cards: CardData[]; - stats: { newCount: number; learningCount: number; reviewCount: number; masteredCount: number }; -} - -interface DeckSummary { - id: string; - course_name: string; - exam_name: string | null; - document_id: string | null; - title: string; - card_count: number; - created_at: string; -} - -type ReviewRating = "AGAIN" | "HARD" | "GOOD" | "EASY"; - -// --- Status helpers --- - -const STATUS_COLORS: Record<string, string> = { - new: "var(--color-info)", - learning: "var(--color-warning)", - review: "var(--color-review)", - mastered: "var(--color-success)", -}; - -const STATUS_TINTS: Record<string, string> = { - new: "var(--color-bg-info-tint)", - learning: "var(--color-bg-warning-tint)", - review: "var(--color-bg-review-tint)", - mastered: "var(--color-bg-success-tint)", -}; - -const STATUS_LABELS: Record<string, string> = { - new: "New", - learning: "Learning", - review: "Review", - mastered: "Mastered", -}; - -const RATING_COLORS: Record<ReviewRating, string> = { - AGAIN: "var(--color-error)", - HARD: "var(--color-warning)", - GOOD: "var(--color-success)", - EASY: "var(--color-info)", -}; - -// --- Component --- - -type View = "list" | "study"; - -export default function FlashcardsPage() { - const [courses, setCourses] = useState<CourseOption[]>([]); - const [selectedCourse, setSelectedCourseRaw] = useState<string>(() => getActiveCourse()); - const setSelectedCourse = (v: string) => { setSelectedCourseRaw(v); setActiveCourse(v); }; - const [decks, setDecks] = useState<DeckSummary[]>([]); - const [generating, setGenerating] = useState(false); - const [error, setError] = useState<string | null>(null); - const [loadingDecks, setLoadingDecks] = useState(false); - - // Study mode state - const [view, setView] = useState<View>("list"); - const [studyData, setStudyData] = useState<StudyDeck | null>(null); - const [cardIndex, setCardIndex] = useState(0); - const [flipped, setFlipped] = useState(false); - const [loadingDeck, setLoadingDeck] = useState(false); - const [sessionXp, setSessionXp] = useState(0); - const [reviewedCount, setReviewedCount] = useState(0); - const [reviewing, setReviewing] = useState(false); - const [xpPopup, setXpPopup] = useState<{ amount: number; key: number } | null>(null); - const [deleting, setDeleting] = useState<string | null>(null); - const [lastReview, setLastReview] = useState<{ - cardIndex: number; - prevCard: CardData; - prevXp: number; - prevReviewedCount: number; - } | null>(null); - - const selectedCourseRef = useRef(selectedCourse); - selectedCourseRef.current = selectedCourse; - - // Fetch courses on mount - useEffect(() => { - let mounted = true; - apiGet("/api/content/documents?namespace=COURSE") - .then((data) => { - if (!mounted) return; - if (data.documents) { - const courseMap = new Map<string, CourseOption>(); - for (const doc of data.documents as { course_name: string; exam_name: string | null }[]) { - if (!doc.course_name) continue; - const key = doc.exam_name - ? `${doc.course_name}||${doc.exam_name}` - : doc.course_name; - const existing = courseMap.get(key); - if (existing) { - existing.doc_count++; - } else { - courseMap.set(key, { - course_name: doc.course_name, - exam_name: doc.exam_name || undefined, - doc_count: 1, - }); - } - } - const options = Array.from(courseMap.values()); - setCourses(options); - // Use persisted course if it exists in the list, else default to first - const active = getActiveCourse(); - const match = active && options.some((o) => (o.exam_name ? `${o.course_name}||${o.exam_name}` : o.course_name) === active); - if (match) { - setSelectedCourse(active); - } else if (options.length > 0) { - const first = options[0]; - setSelectedCourse( - first.exam_name - ? `${first.course_name}||${first.exam_name}` - : first.course_name, - ); - } - } - }) - .catch(() => {}); - return () => { mounted = false; }; - }, []); - - // Fetch decks when course changes. Deck listing is scoped by course only - // (not exam) so the decks shown here always match the per-course deck/due - // counts reported by /api/learn — a deck generated without an exam name - // must not vanish when an exam-specific option is selected. - useEffect(() => { - if (!selectedCourse) return; - let mounted = true; - setLoadingDecks(true); - const [courseName] = selectedCourse.split("||"); - const params = new URLSearchParams({ course_name: courseName }); - apiGet(`/api/flashcards?${params.toString()}`) - .then((data) => { - if (mounted && data.decks) setDecks(data.decks); - }) - .catch(() => { - if (mounted) setDecks([]); - }) - .finally(() => { - if (mounted) setLoadingDecks(false); - }); - return () => { mounted = false; }; - }, [selectedCourse]); - - const handleGenerate = useCallback(async () => { - if (!selectedCourse || generating) return; - const courseAtStart = selectedCourse; - setGenerating(true); - setError(null); - - const [courseName, examName] = selectedCourse.split("||"); - - try { - const deck = await apiPost("/api/flashcards", { - course_name: courseName, - exam_name: examName || undefined, - }); - if (selectedCourseRef.current === courseAtStart) { - setDecks((prev) => [deck, ...prev]); - } - } catch (err) { - if (selectedCourseRef.current === courseAtStart) { - setError(err instanceof Error ? err.message : "Generation failed"); - } - } finally { - setGenerating(false); - } - }, [selectedCourse, generating]); - - const openStudyMode = useCallback(async (deckId: string) => { - setLoadingDeck(true); - try { - const data = await apiGet(`/api/flashcards/${deckId}/study`); - setStudyData(data); - setCardIndex(0); - setFlipped(false); - setSessionXp(0); - setReviewedCount(0); - setView("study"); - } catch { - setError("Failed to load deck"); - } finally { - setLoadingDeck(false); - } - }, []); - - const handleFlip = () => setFlipped((f) => !f); - - const handleReview = useCallback(async (rating: ReviewRating) => { - if (!studyData || reviewing) return; - const card = studyData.cards[cardIndex]; - setReviewing(true); - - // Save state for undo before mutating - setLastReview({ - cardIndex, - prevCard: { ...card }, - prevXp: sessionXp, - prevReviewedCount: reviewedCount, - }); - - try { - const result = await apiPost(`/api/flashcards/${studyData.deck.id}/review`, { - card_id: card.id, - rating, - }); - - setStudyData((prev) => { - if (!prev) return prev; - const updatedCards = [...prev.cards]; - updatedCards[cardIndex] = { - ...updatedCards[cardIndex], - easeFactor: result.easeFactor, - intervalDays: result.intervalDays, - repetitions: result.repetitions, - nextDueAt: result.nextDueAt, - status: result.intervalDays === 0 ? "learning" - : result.intervalDays >= 21 ? "mastered" - : "review", - }; - return { ...prev, cards: updatedCards }; - }); - - const earned = result.xpEarned || 0; - setSessionXp((prev) => prev + earned); - setReviewedCount((prev) => prev + 1); - - // XP popup - if (earned > 0) { - setXpPopup({ amount: earned, key: Date.now() }); - setTimeout(() => setXpPopup(null), 1500); - } - - // Advance to next card - if (cardIndex < studyData.cards.length - 1) { - setCardIndex((i) => i + 1); - setFlipped(false); - } else { - // Reached end — flip to show summary - setFlipped(true); - } - } catch { - setError("Failed to submit review"); - } finally { - setReviewing(false); - } - }, [studyData, cardIndex, reviewing]); - - const handleUndo = useCallback(() => { - if (!lastReview || !studyData) return; - // Restore the card to its previous state (local only — server state already saved) - setStudyData((prev) => { - if (!prev) return prev; - const updatedCards = [...prev.cards]; - updatedCards[lastReview.cardIndex] = lastReview.prevCard; - return { ...prev, cards: updatedCards }; - }); - setCardIndex(lastReview.cardIndex); - setSessionXp(lastReview.prevXp); - setReviewedCount(lastReview.prevReviewedCount); - setFlipped(false); - setLastReview(null); - }, [lastReview, studyData]); - - const handleKeyDown = useCallback( - (e: KeyboardEvent) => { - if (view !== "study" || !studyData) return; - if (e.key === " " || e.key === "Enter") { - e.preventDefault(); - setFlipped((f) => !f); - } else if (e.key === "1") { handleReview("AGAIN"); } - else if (e.key === "2") { handleReview("HARD"); } - else if (e.key === "3") { handleReview("GOOD"); } - else if (e.key === "4") { handleReview("EASY"); } - }, - // eslint-disable-next-line react-hooks/exhaustive-deps - [view, studyData, cardIndex, reviewing], - ); - - useEffect(() => { - window.addEventListener("keydown", handleKeyDown); - return () => window.removeEventListener("keydown", handleKeyDown); - }, [handleKeyDown]); - - const handleDeleteDeck = useCallback(async (deckId: string) => { - if (deleting) return; - if (!window.confirm("Delete this deck and all its cards? This cannot be undone.")) return; - setDeleting(deckId); - try { - await apiDelete(`/api/flashcards/${deckId}`); - setDecks((prev) => prev.filter((d) => d.id !== deckId)); - } catch { - setError("Failed to delete deck"); - } finally { - setDeleting(null); - } - }, [deleting]); - - // --- Study Mode --- - if (view === "study" && studyData) { - const card = studyData.cards[cardIndex]; - const total = studyData.cards.length; - const progressPct = total > 0 ? ((cardIndex + 1) / total) * 100 : 0; - const isLastCard = cardIndex === total - 1; - const sessionComplete = isLastCard && reviewedCount >= total; - - return ( - <ErrorBoundary> - <div id="main-content" style={pageContainer}> - <style>{` - @keyframes xp-float { 0% { opacity: 1; transform: translateY(0); } 100% { opacity: 0; transform: translateY(-30px); } } - `}</style> - - <div style={studyColumn}> - <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "1rem" }}> - <div style={{ display: "flex", gap: "0.5rem" }}> - <button onClick={() => setView("list")} style={backBtn}> - Back to Decks - </button> - {lastReview && ( - <button onClick={handleUndo} style={{ ...backBtn, color: "var(--color-warning)", borderColor: "var(--color-warning)" }}> - Undo - </button> - )} - </div> - <div style={{ display: "flex", gap: "1rem", alignItems: "center" }}> - <span style={{ fontSize: "0.8rem", color: "var(--color-primary)", fontWeight: 600 }}> - +{sessionXp} XP - </span> - <span style={{ fontSize: "0.8rem", color: "var(--color-text-faint)" }}> - {reviewedCount}/{total} reviewed - </span> - </div> - </div> - - <h2 style={{ ...titleStyle, fontSize: "1.45rem", marginBottom: "0.5rem" }}>{studyData.deck.title}</h2> - - {/* Stats bar */} - <div style={{ display: "flex", gap: "0.5rem", marginBottom: "0.75rem", flexWrap: "wrap" }}> - {(["new", "learning", "review", "mastered"] as const).map((s) => { - const count = studyData.stats[`${s}Count` as keyof typeof studyData.stats]; - return ( - <span key={s} style={{ fontSize: "0.75rem", color: STATUS_COLORS[s], background: STATUS_TINTS[s], padding: "0.2rem 0.6rem", borderRadius: 3 }}> - {STATUS_LABELS[s]}: {count} - </span> - ); - })} - </div> - - {/* Progress bar */} - <div style={progressBarBg}> - <div style={{ ...progressBarFill, width: `${progressPct}%` }} /> - </div> - <p style={{ fontSize: "0.8rem", color: "var(--color-text-dim)", marginBottom: "0.5rem", textAlign: "center" }}> - Card {cardIndex + 1} of {total} - </p> - <p style={{ fontSize: "0.7rem", color: "var(--color-text-dim)", marginBottom: "1rem", textAlign: "center" }}> - <kbd style={kbdStyle}>Space</kbd> flip   - <kbd style={kbdStyle}>1</kbd> Again   - <kbd style={kbdStyle}>2</kbd> Hard   - <kbd style={kbdStyle}>3</kbd> Good   - <kbd style={kbdStyle}>4</kbd> Easy - </p> - - {/* Card */} - <div style={{ position: "relative" }} role="region" aria-label="Flashcard"> - {xpPopup && ( - <div - key={xpPopup.key} - style={{ - position: "absolute", top: -10, right: 10, zIndex: 10, - color: "var(--color-primary)", fontWeight: 700, fontSize: "1.1rem", - animation: "xp-float 1.5s ease-out forwards", - pointerEvents: "none", - }} - > - +{xpPopup.amount} XP - </div> - )} - <div - onClick={handleFlip} - style={{ - ...cardStyle, - background: flipped ? "var(--color-bg-info-tint)" : "var(--color-bg-card)", - borderColor: flipped ? "var(--color-info)" : "var(--color-border)", - cursor: "pointer", - }} - > - <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "0.75rem" }}> - <span style={{ fontSize: "0.75rem", color: flipped ? "var(--color-info)" : "var(--color-text-muted)", letterSpacing: "0.08em" }}> - {flipped ? "ANSWER" : "QUESTION"} - </span> - <span style={{ fontSize: "0.7rem", color: STATUS_COLORS[card.status], background: STATUS_TINTS[card.status], padding: "0.15rem 0.5rem", borderRadius: 3 }}> - {STATUS_LABELS[card.status]} - {card.intervalDays > 0 && ` · ${card.intervalDays}d`} - </span> - </div> - <div aria-live="polite" style={{ fontSize: "1.25rem", lineHeight: 1.7, whiteSpace: "pre-wrap" }}> - {flipped ? card.back : card.front} - </div> - {card.tags && card.tags.length > 0 && ( - <div style={{ marginTop: "1rem", display: "flex", gap: "0.35rem", flexWrap: "wrap" }}> - {(card.tags as string[]).map((tag) => ( - <span key={tag} style={tagStyle}>{tag}</span> - ))} - </div> - )} - </div> - </div> - - {!flipped && ( - <p style={{ fontSize: "0.8rem", color: "var(--color-text-dim)", textAlign: "center", margin: "0.75rem 0" }}> - Tap card or press Space to flip - </p> - )} - - {/* Rating buttons — only show when flipped */} - {flipped && !sessionComplete && ( - <div style={{ marginTop: "1rem" }}> - <p style={{ fontSize: "0.8rem", color: "var(--color-text-dim)", textAlign: "center", marginBottom: "0.6rem" }}> - How well did you know this? - </p> - <div style={{ display: "flex", gap: "0.6rem" }}> - {(["AGAIN", "HARD", "GOOD", "EASY"] as const).map((rating, i) => ( - <button - key={rating} - onClick={() => handleReview(rating)} - disabled={reviewing} - aria-label={`Rate ${rating.charAt(0) + rating.slice(1).toLowerCase()} (${i + 1})`} - type="button" - style={{ - ...ratingBtn, - borderColor: RATING_COLORS[rating], - color: RATING_COLORS[rating], - opacity: reviewing ? 0.5 : 1, - }} - > - <span style={{ fontSize: "0.75rem", opacity: 0.6 }}>{i + 1}</span> - <span>{rating.charAt(0) + rating.slice(1).toLowerCase()}</span> - </button> - ))} - </div> - </div> - )} - - {/* End of deck summary */} - {sessionComplete && ( - <div style={{ textAlign: "center", marginTop: "1.5rem", padding: "1.25rem", background: "var(--color-bg-card)", borderRadius: "var(--radius-lg)", border: "1px solid var(--color-border)", boxShadow: "var(--shadow-card)" }}> - <p style={{ fontSize: "1.2rem", color: "var(--color-primary)", margin: "0 0 0.5rem", fontFamily: "var(--font-display)" }}> - Session Complete! - </p> - <p style={{ fontSize: "0.9rem", color: "var(--color-success)", margin: "0 0 0.25rem" }}> - +{sessionXp} XP earned - </p> - <p style={{ fontSize: "0.85rem", color: "var(--color-text-muted)", margin: "0 0 1rem" }}> - {reviewedCount} cards reviewed - </p> - <div style={{ display: "flex", gap: "0.5rem", justifyContent: "center" }}> - <button - onClick={() => openStudyMode(studyData.deck.id)} - style={{ ...generateBtnStyle, width: "auto", fontSize: "1rem", padding: "0.7rem 1.4rem" }} - > - Study Again - </button> - <button - onClick={() => setView("list")} - style={{ ...backBtn, fontSize: "0.95rem", padding: "0.7rem 1.25rem" }} - > - Back to Decks - </button> - </div> - </div> - )} - - {error && <p role="alert" style={{ color: "var(--color-error)", fontSize: "0.85rem", marginTop: "0.5rem" }}>{error}</p>} - </div> - </div> - </ErrorBoundary> - ); - } - - // --- List Mode --- - return ( - <div id="main-content" style={pageContainer}> - <div style={headerStyle}> - <h1 style={titleStyle}>Flashcards</h1> - <p style={subtitleStyle}>Spaced repetition flashcards from your course materials</p> - </div> - - {courses.length > 0 ? ( - <div style={{ marginBottom: "2rem", maxWidth: 640 }}> - <label style={labelStyle}>Course</label> - <select - aria-label="Select course" - value={selectedCourse} - onChange={(e) => { setSelectedCourse(e.target.value); setError(null); }} - style={selectStyle} - > - {courses.map((c) => { - const val = c.exam_name - ? `${c.course_name}||${c.exam_name}` - : c.course_name; - const label = c.exam_name - ? `${c.course_name} — ${c.exam_name}` - : c.course_name; - return <option key={val} value={val}>{label}</option>; - })} - </select> - - <button - onClick={handleGenerate} - disabled={generating} - style={{ - ...generateBtnStyle, - marginTop: "0.75rem", - opacity: generating ? 0.5 : 1, - cursor: generating ? "wait" : "pointer", - }} - > - {generating ? "Generating..." : "Generate Flashcards"} - </button> - - {error && <p role="alert" style={{ color: "var(--color-error)", fontSize: "0.85rem", marginTop: "0.5rem" }}>{error}</p>} - </div> - ) : ( - <div style={{ textAlign: "center", padding: "2rem 1rem", border: "1px dashed var(--color-border-done)", borderRadius: "var(--radius-lg)" }}> - <p style={{ color: "var(--color-text-muted)", fontSize: "1rem", margin: "0 0 0.5rem" }}> - No course documents yet - </p> - <p style={{ color: "var(--color-text-faint)", fontSize: "0.85rem", margin: "0 0 1rem" }}> - Create a plan and upload your course notes there, then come back to generate flashcards. - </p> - <Link href="/plan" style={{ display: "inline-block", padding: "0.7rem 1.4rem", background: "var(--color-primary)", color: "var(--color-bg-darkest)", borderRadius: "var(--radius)", fontWeight: 700, textDecoration: "none", fontSize: "1rem" }}> - Create a Study Plan - </Link> - </div> - )} - - {/* Decks list */} - {loadingDecks && ( - <p style={{ color: "var(--color-text-dim)", fontSize: "0.85rem", textAlign: "center", padding: "1rem 0" }}> - Loading decks... - </p> - )} - {!loadingDecks && courses.length > 0 && decks.length === 0 && ( - <div style={{ textAlign: "center", padding: "2rem 1rem", border: "1px dashed var(--color-border-done)", borderRadius: "var(--radius-lg)" }}> - <p style={{ color: "var(--color-text-muted)", fontSize: "0.95rem", margin: "0 0 0.5rem" }}> - No flashcard decks yet for this course - </p> - <p style={{ color: "var(--color-text-faint)", fontSize: "0.8rem", margin: "0 0 1rem" }}> - Hit the Generate button above to create your first deck from your uploaded documents. - </p> - </div> - )} - {decks.length > 0 && ( - <div> - <h2 style={{ ...sectionTitleStyle, color: "var(--color-text-muted)", fontWeight: 600, textTransform: "uppercase" }}>YOUR DECKS</h2> - <div style={deckGrid}> - {decks.map((deck) => ( - <div key={deck.id} style={deckCard}> - <div style={{ display: "flex", alignItems: "flex-start", gap: "0.75rem" }}> - <div style={{ flex: 1 }}> - <div style={{ fontSize: "1rem", fontWeight: 600, marginBottom: "0.3rem", lineHeight: 1.4 }}> - {deck.title} - </div> - <div style={{ fontSize: "0.8rem", color: "var(--color-text-dim)" }}> - {deck.card_count} cards · {new Date(deck.created_at).toLocaleDateString("en-US", { month: "short", day: "numeric" })} - </div> - </div> - <button - className="compact-btn" - onClick={() => handleDeleteDeck(deck.id)} - disabled={deleting === deck.id} - aria-label={`Delete ${deck.title}`} - style={{ ...deleteBtnStyle, padding: "0.05rem 0.5rem" }} - > - {deleting === deck.id ? "..." : "×"} - </button> - </div> - <button - onClick={() => openStudyMode(deck.id)} - disabled={loadingDeck} - style={studyDeckBtn} - > - Study → - </button> - </div> - ))} - </div> - </div> - )} - </div> - ); -} - -// --- Styles --- - -const pageContainer: React.CSSProperties = { - maxWidth: 1100, - margin: "0 auto", - padding: "1.5rem clamp(1.5rem, 4vw, 2rem)", - fontFamily: "var(--font-body)", - color: "var(--color-text)", -}; - -const studyColumn: React.CSSProperties = { - width: "100%", - maxWidth: 760, - margin: "0 auto", -}; - -const deckGrid: React.CSSProperties = { - display: "grid", - gridTemplateColumns: "repeat(auto-fill, minmax(min(320px, 100%), 1fr))", - gap: 16, -}; - -const deckCard: React.CSSProperties = { - display: "flex", - flexDirection: "column", - padding: "1.25rem 1.5rem", - fontFamily: "inherit", - background: "var(--color-bg-card)", - color: "var(--color-text)", - border: "1px solid var(--color-border)", - borderRadius: "var(--radius)", - textAlign: "left", -}; - -const studyDeckBtn: React.CSSProperties = { - marginTop: "auto", - padding: "0.85rem 0 0", - alignSelf: "flex-start", - fontFamily: "inherit", - fontSize: "0.9rem", - fontWeight: 600, - color: "var(--color-primary)", - background: "none", - border: "none", - cursor: "pointer", -}; - -const cardStyle: React.CSSProperties = { - minHeight: 280, - padding: "2rem 2.25rem", - borderRadius: "var(--radius-lg)", - boxShadow: "var(--shadow-card)", - border: "2px solid var(--color-border)", - display: "flex", - flexDirection: "column", - justifyContent: "center", - transition: "background 0.2s, border-color 0.2s", -}; - -const progressBarBg: React.CSSProperties = { - height: 4, - background: "var(--color-bg-card)", - borderRadius: 2, - marginBottom: "0.25rem", - overflow: "hidden", -}; - -const progressBarFill: React.CSSProperties = { - height: "100%", - background: "var(--color-info)", - borderRadius: 2, - transition: "width 0.3s", -}; - -const ratingBtn: React.CSSProperties = { - flex: 1, - display: "flex", - flexDirection: "column", - alignItems: "center", - gap: "0.2rem", - padding: "0.85rem 0.4rem", - fontSize: "0.9rem", - fontFamily: "inherit", - fontWeight: 600, - background: "var(--color-bg-card)", - border: "1px solid var(--color-border)", - borderRadius: "var(--radius)", - cursor: "pointer", -}; - -const backBtn: React.CSSProperties = { - fontSize: "0.85rem", - fontFamily: "inherit", - color: "var(--color-text-dim)", - background: "none", - border: "1px solid var(--color-border-subtle)", - borderRadius: "var(--radius-sm)", - padding: "0.45rem 0.9rem", - cursor: "pointer", -}; - -const tagStyle: React.CSSProperties = { - fontSize: "0.6rem", - background: "var(--color-bg-info-tint)", - color: "var(--color-info)", - padding: "0.1rem 0.4rem", - borderRadius: 3, - letterSpacing: "0.03em", -}; - -const kbdStyle: React.CSSProperties = { - display: "inline-block", - fontSize: "0.6rem", - fontFamily: "var(--font-mono)", - background: "var(--color-bg-card)", - border: "1px solid var(--color-border)", - borderRadius: 3, - padding: "0.05rem 0.3rem", - color: "var(--color-text)", -}; diff --git a/src/app/global-error.tsx b/src/app/global-error.tsx new file mode 100644 index 00000000..b0f42c87 --- /dev/null +++ b/src/app/global-error.tsx @@ -0,0 +1,72 @@ +"use client"; + +import "@fontsource-variable/google-sans-flex/rond.css"; +import "./globals.css"; +import { useEffect, useSyncExternalStore } from "react"; +import { CloudOffIcon, RotateCcwIcon } from "lucide-react"; + +import { StatusScreen } from "@/components/app/status-screen"; +import { Button } from "@/components/ui/button"; + +const DARK_QUERY = "(prefers-color-scheme: dark)"; + +function subscribe(onChange: () => void) { + const query = window.matchMedia(DARK_QUERY); + query.addEventListener("change", onChange); + return () => query.removeEventListener("change", onChange); +} + +/** + * Last resort when the root layout itself fails. It replaces the whole + * document, so it has no providers and follows the system theme directly. + */ +export default function GlobalError({ + error, + retry, +}: { + error: Error & { digest?: string }; + /** Refetches and re-renders the segment (reset would only re-render the failed payload). */ + retry: () => void; +}) { + const dark = useSyncExternalStore( + subscribe, + () => window.matchMedia(DARK_QUERY).matches, + () => false + ); + + useEffect(() => { + console.error(error); + }, [error]); + + return ( + <html lang="en" className={dark ? "dark" : undefined}> + <head> + <title>Study Bot + + +
+ + + {/* A full page load, since the client router may be what failed. */} + + + } + footnote={error.digest ? `Reference: ${error.digest}` : undefined} + /> +
+ + + ); +} diff --git a/src/app/globals.css b/src/app/globals.css index c9797160..3b4fab97 100644 --- a/src/app/globals.css +++ b/src/app/globals.css @@ -1,394 +1,793 @@ -/* =========================== - Study Bot — Global Styles - =========================== */ - -/* ---- Design tokens ---- - A calm, high-contrast dark system. One accent color; semantic colors - reserved for meaning (success/warning/error/review). Cognitive-load - principle: the interface recedes, the content leads. */ - -:root { - --font-display: "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; - --font-body: "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; - --font-mono: ui-monospace, "SF Mono", "Cascadia Code", "JetBrains Mono", Menlo, Consolas, monospace; - - /* Surfaces (deep neutral slate, not pure black) */ - --color-bg-darkest: #0b0e14; - --color-bg: #10141c; - --color-bg-card: #171c26; - --color-bg-input: #1c2230; - --color-bg-done: #14231b; - - /* Tinted surfaces for semantic callouts */ - --color-bg-info-tint: #142230; - --color-bg-success-tint: #14231b; - --color-bg-warning-tint: #2a2314; - --color-bg-error-tint: #2a171c; - --color-bg-review-tint: #221d33; - --color-bg-selected: #1e2c47; - - /* Borders */ - --color-border: #2a3242; - --color-border-subtle: #202634; - --color-border-done: #2f4a3a; - - /* Text (4 steps of hierarchy is plenty). The two dimmest steps are still - WCAG AA readable on cards (faint 4.71:1, dim 4.69:1 on --color-bg-card) — - "dim" means lower salience, never illegible. */ - --color-text: #e7eaf0; - --color-text-secondary: #b8bfcc; - --color-text-muted: #949dae; - --color-text-faint: #7d8799; - --color-text-dim: #7c86a0; - - /* Accent + semantics */ - --color-primary: #6ea8fe; - --color-info: #66c5da; - --color-success: #58c98b; - --color-warning: #e2a94f; - --color-error: #e5737f; - --color-review: #a78bfa; - - /* Shape & depth */ - --radius-sm: 6px; - --radius: 10px; - --radius-lg: 14px; - --shadow-card: 0 1px 2px rgba(0, 0, 0, 0.35), 0 6px 20px rgba(0, 0, 0, 0.22); - - --nav-height: 52px; -} - -html { - -webkit-font-smoothing: antialiased; - -moz-osx-font-smoothing: grayscale; -} - -body { - margin: 0; - background: var(--color-bg); - color: var(--color-text); - font-family: var(--font-body); - line-height: 1.5; -} - -/* ---- Shared surface + control primitives ---- */ - -.card { - background: var(--color-bg-card); - border: 1px solid var(--color-border-subtle); - border-radius: var(--radius); - box-shadow: var(--shadow-card); -} - -/* Screen-reader-only content (aria-live announcements etc.) */ -.visually-hidden { - position: absolute; - width: 1px; - height: 1px; - padding: 0; - margin: -1px; - overflow: hidden; - clip: rect(0, 0, 0, 0); - white-space: nowrap; - border: 0; -} - -::selection { - background: rgba(110, 168, 254, 0.28); -} - -/* Scrollbars that don't shout */ -* { - scrollbar-width: thin; - scrollbar-color: var(--color-border) transparent; -} -*::-webkit-scrollbar { - width: 8px; - height: 8px; -} -*::-webkit-scrollbar-thumb { - background: var(--color-border); - border-radius: 4px; -} -*::-webkit-scrollbar-track { - background: transparent; -} - -/* ---- Skip-to-content link (accessibility) ---- */ - -.skip-to-content { - position: absolute; - top: -100%; - left: 1rem; - z-index: 10000; - padding: 0.75rem 1.5rem; - background: var(--color-primary); - color: var(--color-bg-darkest); - font-family: var(--font-body); - font-weight: 700; - font-size: 0.95rem; - text-decoration: none; - border-radius: 0 0 6px 6px; - transition: top 0.15s ease; -} - -.skip-to-content:focus { - top: 0; - outline: 3px solid var(--color-info); - outline-offset: 2px; -} - -/* ---- Focus-visible outlines (accessibility) ---- */ - -*:focus-visible { - outline: 2px solid var(--color-info); - outline-offset: 2px; -} - -button:focus-visible, -a:focus-visible, -select:focus-visible, -textarea:focus-visible, -input:focus-visible { - outline: 2px solid var(--color-info); - outline-offset: 2px; -} - -/* ---- Nav responsive ---- */ - -.nav-container { - /* Structural styles are inline; this class enables responsive overrides */ -} - -.nav-links { - display: flex; - list-style: none; - margin: 0; - padding: 0; - gap: 0.25rem; - overflow: auto; -} - -.nav-hamburger { - display: none; - align-items: center; - justify-content: center; - width: 44px; - height: 44px; - padding: 0; - background: none; - border: none; - cursor: pointer; - flex-shrink: 0; -} - -.nav-hamburger-line { - display: block; - width: 22px; - height: 2px; - background: var(--color-text); - border-radius: 1px; - position: relative; - transition: background 0.2s; -} - -.nav-hamburger-line::before, -.nav-hamburger-line::after { - content: ''; - display: block; - width: 22px; - height: 2px; - background: var(--color-text); - border-radius: 1px; - position: absolute; - left: 0; - transition: transform 0.2s, top 0.2s; -} - -.nav-hamburger-line::before { - top: -7px; +@import "tailwindcss"; +@import "tw-animate-css"; +@import "shadcn/tailwind.css"; + +@custom-variant dark (&:is(.dark *)); + +/* The design system page pins interaction states with data-preview="hover", + "focus" or "active" so reviewers can see every state without a pointer. */ +@custom-variant hover { + @media (hover: hover) { + &:hover { + @slot; + } + } + &[data-preview~="hover"] { + @slot; + } } +@custom-variant focus-visible (&:focus-visible, &[data-preview~="focus"]); +@custom-variant active (&:active, &[data-preview~="active"]); -.nav-hamburger-line::after { - top: 7px; -} +/* Short windows: a phone in landscape, or a laptop at 200 to 400% zoom. + Sticky bars give their space back here (`short:static`), so the content + between them stays visible and focused controls aren't covered. */ +@custom-variant short (@media (max-height: 32rem)); -/* Hamburger open state — animate to X */ -.nav-hamburger[aria-expanded="true"] .nav-hamburger-line { - background: transparent; +/* ========================================================================== + Colour roles: Google Material 3 (GM3 web baseline), light theme. + Every text and surface pair is contrast-checked in both themes. + ========================================================================== */ +:root { + color-scheme: light; + + /* Surfaces, from the page down to the most raised tonal container */ + --surface: #f8fafd; + --surface-container-lowest: #ffffff; + --surface-container-low: #f8fafd; + --surface-container: #f0f4f9; + --surface-container-high: #e9eef6; + --surface-container-highest: #dde3ea; + --on-surface: #1f1f1f; + --on-surface-variant: #444746; + --outline: #747775; + --outline-variant: #c4c7c5; + + --primary: #0b57d0; + --on-primary: #ffffff; + --primary-container: #d3e3fd; + --on-primary-container: #041e49; + --secondary-container: #c2e7ff; + --on-secondary-container: #001d35; + + /* Tertiary carries success */ + --tertiary: #146c2e; + --on-tertiary: #ffffff; + --tertiary-container: #c4eed0; + --on-tertiary-container: #072711; + + --error: #b3261e; + --on-error: #ffffff; + --error-container: #f9dedc; + --on-error-container: #410e0b; + + /* Warning: missed and due states */ + --warning: #995c00; + --on-warning: #ffffff; + --warning-container: #feefc3; + --on-warning-container: #5c3d00; + + --inverse-surface: #303030; + --inverse-on-surface: #f2f2f2; + --inverse-primary: #a8c7fa; + --scrim: #000000; + + /* Lesson palette: Duolingo's grammar in Google's product colours */ + --lesson-surface: #ffffff; + --lesson-on-surface: #1f1f1f; + --lesson-muted: #5f6368; + --lesson-option: #ffffff; + --lesson-option-border: #dadce0; + --lesson-option-hover: #f8f9fa; + --lesson-selected: #e8f0fe; + --lesson-selected-border: #1a73e8; + --lesson-selected-lip: #185abc; + --lesson-on-selected: #174ea6; + /* Hover fills move away from the label colour: darker under white labels + here, lighter under dark labels in the dark theme (contrast goes up). */ + --lesson-primary: #1a73e8; + --lesson-primary-hover: #1967d2; + --lesson-primary-lip: #185abc; + --lesson-on-primary: #ffffff; + --lesson-check: #188038; + --lesson-check-hover: #137333; + --lesson-check-lip: #0d652d; + --lesson-on-check: #ffffff; + --lesson-correct: #e6f4ea; + --lesson-on-correct: #137333; + --lesson-wrong: #fce8e6; + --lesson-on-wrong: #a50e0e; + --lesson-wrong-button: #c5221f; + --lesson-wrong-button-hover: #b31412; + --lesson-wrong-lip: #a50e0e; + --lesson-on-wrong-button: #ffffff; + --lesson-neutral-text: #3c4043; + --lesson-disabled: #e8eaed; + --lesson-on-disabled: #80868b; + --lesson-progress-track: #e8eaed; + --lesson-progress-fill: #1e8e3e; + + /* shadcn names mapped onto the roles */ + --background: var(--surface); + --foreground: var(--on-surface); + --card: var(--surface-container-lowest); + --card-foreground: var(--on-surface); + --popover: var(--surface-container-low); + --popover-foreground: var(--on-surface); + --secondary: var(--secondary-container); + --secondary-foreground: var(--on-secondary-container); + --primary-foreground: var(--on-primary); + --muted: var(--surface-container); + --muted-foreground: var(--on-surface-variant); + --accent: var(--surface-container-high); + --accent-foreground: var(--on-surface); + --destructive: var(--error); + --destructive-foreground: var(--on-error); + --border: var(--outline-variant); + --input: var(--outline); + --ring: var(--primary); + --chart-1: #0b57d0; + --chart-2: #146c2e; + --chart-3: #995c00; + --chart-4: #b3261e; + --chart-5: #6e4bc0; + --sidebar: var(--surface); + --sidebar-foreground: var(--on-surface-variant); + --sidebar-primary: var(--primary); + --sidebar-primary-foreground: var(--on-primary); + --sidebar-accent: var(--secondary-container); + --sidebar-accent-foreground: var(--on-secondary-container); + --sidebar-border: var(--outline-variant); + --sidebar-ring: var(--primary); + --radius: 0.75rem; + + /* Motion: M3 durations (easings live in @theme as --ease-*) */ + --duration-short: 150ms; + --duration-medium: 250ms; + --duration-long: 350ms; + /* The roundness dial: long and even enough to see, and it starts after the + first frame has painted square, so the change reads as a turn. */ + --duration-dial: 600ms; + --delay-dial: 120ms; + --ease-dial: cubic-bezier(0.4, 0, 0.2, 1); + + /* Shell metrics. --bottom-bar-height is the space the fixed bottom bar + covers: 5rem, or 0 in short windows, where the bar sits at the end of + the page instead (see below). */ + --app-bar-height: 4rem; + --rail-width: 5rem; + --bottom-bar-height: 5rem; +} + +/* Short windows (a phone in landscape, or 400% zoom): the bottom bar is + static there, so offsets that clear it (page padding, scroll margins, + pinned composers and save bars, toasts) drop to nothing. */ +@media (max-height: 32rem) { + :root { + --bottom-bar-height: 0rem; + } } -.nav-hamburger[aria-expanded="true"] .nav-hamburger-line::before { - top: 0; - transform: rotate(45deg); +/* Dark theme: the same roles at GM3's dark tones */ +.dark { + color-scheme: dark; + + --surface: #131314; + --surface-container-lowest: #0e0e0e; + --surface-container-low: #1b1b1b; + --surface-container: #1e1f20; + --surface-container-high: #282a2c; + --surface-container-highest: #333537; + --on-surface: #e3e3e3; + --on-surface-variant: #c4c7c5; + --outline: #8e918f; + --outline-variant: #444746; + + --primary: #a8c7fa; + --on-primary: #062e6f; + --primary-container: #0842a0; + --on-primary-container: #d3e3fd; + --secondary-container: #004a77; + --on-secondary-container: #c2e7ff; + + --tertiary: #6dd58c; + --on-tertiary: #0a3818; + --tertiary-container: #0f5223; + --on-tertiary-container: #c4eed0; + + --error: #f2b8b5; + --on-error: #601410; + --error-container: #8c1d18; + --on-error-container: #f9dedc; + + --warning: #fdd663; + --on-warning: #3d2e00; + --warning-container: #5a4300; + --on-warning-container: #feefc3; + + --inverse-surface: #e3e3e3; + --inverse-on-surface: #303030; + --inverse-primary: #0b57d0; + + --lesson-surface: #131314; + --lesson-on-surface: #e3e3e3; + --lesson-muted: #bdc1c6; + --lesson-option: #131314; + --lesson-option-border: #3c4043; + --lesson-option-hover: #1e1f20; + --lesson-selected: #1c2b41; + --lesson-selected-border: #8ab4f8; + --lesson-selected-lip: #669df6; + --lesson-on-selected: #d2e3fc; + --lesson-primary: #8ab4f8; + --lesson-primary-hover: #aecbfa; + --lesson-primary-lip: #5e97f6; + --lesson-on-primary: #062e6f; + --lesson-check: #81c995; + --lesson-check-hover: #a8dab5; + --lesson-check-lip: #4ca866; + --lesson-on-check: #0d3a1f; + --lesson-correct: #122a1b; + --lesson-on-correct: #81c995; + --lesson-wrong: #3a1a18; + --lesson-on-wrong: #f28b82; + --lesson-wrong-button: #f28b82; + --lesson-wrong-button-hover: #f6aea9; + --lesson-wrong-lip: #d9655b; + --lesson-on-wrong-button: #601410; + --lesson-neutral-text: #e8eaed; + --lesson-disabled: #282a2c; + --lesson-on-disabled: #9aa0a6; + --lesson-progress-track: #3c4043; + --lesson-progress-fill: #81c995; + + --popover: var(--surface-container-high); + --chart-1: #a8c7fa; + --chart-2: #6dd58c; + --chart-3: #fdd663; + --chart-4: #f2b8b5; + --chart-5: #d0bcff; +} + +@theme inline { + --color-background: var(--background); + --color-foreground: var(--foreground); + --color-card: var(--card); + --color-card-foreground: var(--card-foreground); + --color-popover: var(--popover); + --color-popover-foreground: var(--popover-foreground); + --color-primary: var(--primary); + --color-primary-foreground: var(--primary-foreground); + --color-secondary: var(--secondary); + --color-secondary-foreground: var(--secondary-foreground); + --color-muted: var(--muted); + --color-muted-foreground: var(--muted-foreground); + --color-accent: var(--accent); + --color-accent-foreground: var(--accent-foreground); + --color-destructive: var(--destructive); + --color-destructive-foreground: var(--destructive-foreground); + --color-border: var(--border); + --color-input: var(--input); + --color-ring: var(--ring); + --color-chart-1: var(--chart-1); + --color-chart-2: var(--chart-2); + --color-chart-3: var(--chart-3); + --color-chart-4: var(--chart-4); + --color-chart-5: var(--chart-5); + --color-sidebar: var(--sidebar); + --color-sidebar-foreground: var(--sidebar-foreground); + --color-sidebar-primary: var(--sidebar-primary); + --color-sidebar-primary-foreground: var(--sidebar-primary-foreground); + --color-sidebar-accent: var(--sidebar-accent); + --color-sidebar-accent-foreground: var(--sidebar-accent-foreground); + --color-sidebar-border: var(--sidebar-border); + --color-sidebar-ring: var(--sidebar-ring); + + --color-surface: var(--surface); + --color-surface-container-lowest: var(--surface-container-lowest); + --color-surface-container-low: var(--surface-container-low); + --color-surface-container: var(--surface-container); + --color-surface-container-high: var(--surface-container-high); + --color-surface-container-highest: var(--surface-container-highest); + --color-on-surface: var(--on-surface); + --color-on-surface-variant: var(--on-surface-variant); + --color-outline: var(--outline); + --color-outline-variant: var(--outline-variant); + --color-primary-container: var(--primary-container); + --color-on-primary-container: var(--on-primary-container); + --color-secondary-container: var(--secondary-container); + --color-on-secondary-container: var(--on-secondary-container); + --color-tertiary: var(--tertiary); + --color-on-tertiary: var(--on-tertiary); + --color-tertiary-container: var(--tertiary-container); + --color-on-tertiary-container: var(--on-tertiary-container); + --color-error: var(--error); + --color-on-error: var(--on-error); + --color-error-container: var(--error-container); + --color-on-error-container: var(--on-error-container); + --color-warning: var(--warning); + --color-on-warning: var(--on-warning); + --color-warning-container: var(--warning-container); + --color-on-warning-container: var(--on-warning-container); + --color-inverse-surface: var(--inverse-surface); + --color-inverse-on-surface: var(--inverse-on-surface); + --color-inverse-primary: var(--inverse-primary); + --color-scrim: var(--scrim); + + --color-lesson-surface: var(--lesson-surface); + --color-lesson-on-surface: var(--lesson-on-surface); + --color-lesson-muted: var(--lesson-muted); + --color-lesson-option: var(--lesson-option); + --color-lesson-option-border: var(--lesson-option-border); + --color-lesson-option-hover: var(--lesson-option-hover); + --color-lesson-selected: var(--lesson-selected); + --color-lesson-selected-border: var(--lesson-selected-border); + --color-lesson-selected-lip: var(--lesson-selected-lip); + --color-lesson-on-selected: var(--lesson-on-selected); + --color-lesson-primary: var(--lesson-primary); + --color-lesson-primary-hover: var(--lesson-primary-hover); + --color-lesson-primary-lip: var(--lesson-primary-lip); + --color-lesson-on-primary: var(--lesson-on-primary); + --color-lesson-check: var(--lesson-check); + --color-lesson-check-hover: var(--lesson-check-hover); + --color-lesson-check-lip: var(--lesson-check-lip); + --color-lesson-on-check: var(--lesson-on-check); + --color-lesson-correct: var(--lesson-correct); + --color-lesson-on-correct: var(--lesson-on-correct); + --color-lesson-wrong: var(--lesson-wrong); + --color-lesson-on-wrong: var(--lesson-on-wrong); + --color-lesson-wrong-button: var(--lesson-wrong-button); + --color-lesson-wrong-button-hover: var(--lesson-wrong-button-hover); + --color-lesson-wrong-lip: var(--lesson-wrong-lip); + --color-lesson-on-wrong-button: var(--lesson-on-wrong-button); + --color-lesson-neutral-text: var(--lesson-neutral-text); + --color-lesson-disabled: var(--lesson-disabled); + --color-lesson-on-disabled: var(--lesson-on-disabled); + --color-lesson-progress-track: var(--lesson-progress-track); + --color-lesson-progress-fill: var(--lesson-progress-fill); + + /* M3 shape scale pinned to the Tailwind radius steps the components use: + 4px accents and tooltips, 8px text fields and menus, 12px list items + and alerts, 16px cards, 28px dialogs and sheets. Pills use rounded-full. */ + --radius-xs: 4px; + --radius-sm: 4px; + --radius-md: 8px; + --radius-lg: 12px; + --radius-xl: 12px; + --radius-2xl: 16px; + --radius-3xl: 24px; + --radius-4xl: 28px; +} + +@theme static { + /* M3 easing: standard for state changes, emphasized for entrances */ + --ease-standard: cubic-bezier(0.2, 0, 0, 1); + --ease-emphasized: cubic-bezier(0.05, 0.7, 0.1, 1); + --ease-emphasized-accelerate: cubic-bezier(0.3, 0, 0.8, 0.15); + + --font-sans: "Google Sans Flex Variable", "Google Sans", ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; + --font-heading: "Google Sans Flex Variable", "Google Sans", ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; + --font-mono: "Google Sans Code Variable", ui-monospace, "Cascadia Code", Menlo, Consolas, monospace; +} + +/* Breakpoints follow M3 window size classes: compact under 600px (bottom + navigation), medium from 600px (navigation rail), expanded from 840px, + large from 1200px and extra large from 1600px. */ +@theme { + --breakpoint-sm: 37.5rem; + --breakpoint-md: 52.5rem; + --breakpoint-lg: 75rem; + --breakpoint-xl: 100rem; +} + +/* Elevation: tonal by default. Shadows only for menus, popovers, dialogs and + a hovered card (M3 levels 1 to 3). Inputs stay flat. */ +@theme { + --shadow-xs: 0 0 #0000; + --shadow-sm: 0 1px 2px 0 rgb(0 0 0 / 0.3), 0 1px 3px 1px rgb(0 0 0 / 0.15); + --shadow-md: 0 1px 2px 0 rgb(0 0 0 / 0.3), 0 2px 6px 2px rgb(0 0 0 / 0.15); + --shadow-lg: 0 1px 3px 0 rgb(0 0 0 / 0.3), 0 4px 8px 3px rgb(0 0 0 / 0.15); + --shadow-xl: 0 2px 3px 0 rgb(0 0 0 / 0.3), 0 6px 10px 4px rgb(0 0 0 / 0.15); + --shadow-2xl: 0 4px 4px 0 rgb(0 0 0 / 0.3), 0 8px 12px 6px rgb(0 0 0 / 0.15); +} + +/* ========================================================================== + Material 3 type scale. Fixed rem sizes; use these, not text-* sizes, so + cn() never drops a size sitting next to a colour class. + ========================================================================== */ +@utility type-display-l { + font-size: 3.5625rem; + line-height: 4rem; + font-weight: 400; + letter-spacing: -0.25px; +} +@utility type-display-m { + font-size: 2.8125rem; + line-height: 3.25rem; + font-weight: 400; + letter-spacing: 0; +} +@utility type-display-s { + font-size: 2.25rem; + line-height: 2.75rem; + font-weight: 400; + letter-spacing: 0; +} +@utility type-headline-l { + font-size: 2rem; + line-height: 2.5rem; + font-weight: 400; + letter-spacing: 0; +} +@utility type-headline-m { + font-size: 1.75rem; + line-height: 2.25rem; + font-weight: 400; + letter-spacing: 0; +} +@utility type-headline-s { + font-size: 1.5rem; + line-height: 2rem; + font-weight: 400; + letter-spacing: 0; +} +@utility type-title-l { + font-size: 1.375rem; + line-height: 1.75rem; + font-weight: 400; + letter-spacing: 0; +} +@utility type-title-m { + font-size: 1rem; + line-height: 1.5rem; + font-weight: 500; + letter-spacing: 0.15px; +} +@utility type-title-s { + font-size: 0.875rem; + line-height: 1.25rem; + font-weight: 500; + letter-spacing: 0.1px; +} +@utility type-body-l { + font-size: 1rem; + line-height: 1.5rem; + font-weight: 400; + letter-spacing: 0.5px; +} +@utility type-body-m { + font-size: 0.875rem; + line-height: 1.25rem; + font-weight: 400; + letter-spacing: 0.25px; +} +@utility type-body-s { + font-size: 0.75rem; + line-height: 1rem; + font-weight: 400; + letter-spacing: 0.4px; +} +@utility type-label-l { + font-size: 0.875rem; + line-height: 1.25rem; + font-weight: 500; + letter-spacing: 0.1px; +} +@utility type-label-m { + font-size: 0.75rem; + line-height: 1rem; + font-weight: 500; + letter-spacing: 0.5px; +} +@utility type-label-s { + font-size: 0.6875rem; + line-height: 1rem; + font-weight: 500; + letter-spacing: 0.5px; +} + +/* M3 state layer: an overlay in the content colour at 8% on hover and 10% + on focus and press. Works on any filled, tonal, outlined or text control. + Pair it with `relative isolate` (or `absolute isolate`) on the element. */ +@utility state-layer { + &::before { + content: ""; + position: absolute; + inset: 0; + z-index: -1; + border-radius: inherit; + background-color: currentColor; + opacity: 0; + pointer-events: none; + transition: opacity var(--duration-short) var(--ease-standard); + } + @variant hover { + &::before { + opacity: 0.08; + } + } + @variant focus-visible { + &::before { + opacity: 0.1; + } + } + @variant active { + &::before { + opacity: 0.1; + } + } } -.nav-hamburger[aria-expanded="true"] .nav-hamburger-line::after { - top: 0; - transform: rotate(-45deg); +/* The 4px bottom lip of lesson controls. Pressing moves the control down by + 2px and shrinks the lip, like a physical key. Set --lip to the lip colour. */ +@utility lesson-lip { + box-shadow: 0 4px 0 var(--lip, var(--lesson-option-border)); + transition: + transform var(--duration-short) var(--ease-standard), + box-shadow var(--duration-short) var(--ease-standard), + background-color var(--duration-short) var(--ease-standard), + border-color var(--duration-short) var(--ease-standard); + @variant active { + &:not(:disabled, [data-disabled], [aria-disabled="true"]) { + transform: translateY(2px); + box-shadow: 0 2px 0 var(--lip, var(--lesson-option-border)); + } + } } -/* ---- Buttons — touch targets & hover states ---- */ - -button, -[role="button"] { - min-height: 44px; - min-width: 44px; -} +/* Focus ring for actions: a solid 2px outline in the ring colour with a 2px + offset, unlayered so it wins over outline-none. Text fields and the select + trigger keep their own 2px border treatment. A component inside a clipping + container sets --focus-ring-offset (for example -2px) to draw it inside. */ +:is( + button, + a[href], + summary, + [role="button"], + [role="tab"], + [role="checkbox"], + [role="radio"], + [role="switch"], + [role="slider"], + [tabindex]:not([tabindex="-1"]) + ):not([data-slot="select-trigger"]):is(:focus-visible, [data-preview~="focus"]) { + outline: 2px solid var(--focus-ring-color, var(--ring)); + outline-offset: var(--focus-ring-offset, 2px); + --tw-ring-shadow: 0 0 #0000; +} + +@layer base { + * { + @apply border-border outline-ring; + } -button:hover:not(:disabled), -[role="button"]:hover:not(:disabled) { - filter: brightness(1.1); -} + html { + @apply font-sans; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; + text-rendering: optimizeLegibility; + font-variation-settings: "ROND" 0; + scrollbar-color: var(--outline-variant) transparent; + } -button:active:not(:disabled), -[role="button"]:active:not(:disabled) { - filter: brightness(0.95); -} + body { + @apply bg-background text-foreground type-body-m; + min-height: 100dvh; + caret-color: var(--primary); + } -/* Allow small inline badges / icon buttons to opt out with a class */ -button.compact-btn, -[role="button"].compact-btn { - min-height: auto; - min-width: auto; -} + ::selection { + background-color: var(--secondary-container); + color: var(--on-secondary-container); + } -/* ---- Form inputs ---- */ + ::placeholder { + color: var(--on-surface-variant); + opacity: 1; + } -select, -textarea, -input[type="text"], -input[type="email"], -input[type="password"], -input[type="search"], -input[type="url"], -input[type="number"] { - font-size: 16px; /* prevents iOS zoom on focus */ -} + :focus-visible { + outline: 2px solid var(--ring); + outline-offset: 2px; + } -/* ================================================================ - Tablet breakpoint (max-width: 768px) - ================================================================ */ + /* Keep focused controls clear of the fixed app bar and bottom bar. In + short windows neither covers the page, so a little room is enough. */ + :focus { + scroll-margin-top: calc(var(--app-bar-height) + 1rem); + scroll-margin-bottom: calc(var(--bottom-bar-height) + 1rem); -@media (max-width: 768px) { - /* -- Mobile nav -- */ - .nav-hamburger { - display: flex; + @variant short { + scroll-margin-top: 1rem; + } } - .nav-links { - display: none; - flex-direction: column; - position: absolute; - top: var(--nav-height); - left: 0; - right: 0; - background: var(--color-bg-darkest); - border-bottom: 1px solid var(--color-border-subtle); - padding: 0.5rem 0; - box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3); - z-index: 9998; - overflow: visible; + #main-content:focus { + outline: none; } - .nav-links.open { - display: flex; + button:not(:disabled), + [role="button"]:not(:disabled) { + cursor: pointer; } - .nav-links li { - width: 100%; + a { + text-underline-offset: 0.2em; } - .nav-links li a { - display: block; - padding: 0.75rem 1.25rem !important; - border-bottom: none !important; - font-size: 1.05rem !important; + code, + kbd, + samp, + pre { + @apply font-mono; } - .nav-links li a:hover, - .nav-links li a:focus { - background: var(--color-bg); + /* Thin themed scrollbars */ + * { + scrollbar-width: thin; } - - /* -- Page containers — reduce side padding -- */ - main { - padding-left: 0.5rem; - padding-right: 0.5rem; + ::-webkit-scrollbar { + width: 10px; + height: 10px; + } + ::-webkit-scrollbar-thumb { + background-color: var(--outline-variant); + border: 2px solid transparent; + border-radius: 9999px; + background-clip: padding-box; + } + ::-webkit-scrollbar-thumb:hover { + background-color: var(--outline); + } + ::-webkit-scrollbar-track, + ::-webkit-scrollbar-corner { + background: transparent; } - /* -- Stats grids: 4-col to 2-col -- */ - div[style*="gridTemplateColumns"] { - grid-template-columns: repeat(2, 1fr) !important; + /* Chrome autofill keeps the field surface instead of painting it yellow */ + input:-webkit-autofill, + input:-webkit-autofill:hover, + input:-webkit-autofill:focus { + -webkit-text-fill-color: var(--on-surface); + -webkit-box-shadow: 0 0 0 1000px var(--surface-container-lowest) inset; + caret-color: var(--primary); } - /* -- Font size adjustments -- */ - h1 { - font-size: 1.35rem; + /* Screen-reader-only content used by the session runner */ + .visually-hidden { + position: absolute; + width: 1px; + height: 1px; + padding: 0; + margin: -1px; + overflow: hidden; + clip: rect(0, 0, 0, 0); + white-space: nowrap; + border: 0; } +} - h2 { - font-size: 1.1rem; +/* ========================================================================== + Lesson scope. Entering a session, the type rounds itself: the ROND axis + eases from 0 to 100 and the weight steps up. Sessions only. + ========================================================================== */ +@layer components { + .lesson { + font-variation-settings: "ROND" 100; + font-weight: 500; + background-color: var(--lesson-surface); + color: var(--lesson-on-surface); + transition: + font-variation-settings var(--duration-dial) var(--ease-dial) var(--delay-dial), + font-weight var(--duration-dial) var(--ease-dial) var(--delay-dial); + + @starting-style { + font-variation-settings: "ROND" 0; + font-weight: 400; + } } - /* -- Chat bubbles: reduce side margins -- */ - div[style*="marginLeft: \"2rem\""], - div[style*="marginLeft"] { - margin-left: 0.5rem; + /* While the page is still its loading skeleton (grey bars, no text), the + dial waits at square. It turns when the first real screen replaces the + skeleton, so the student sees the question's own glyphs round. Moving + between screens later (intro, question, results) keeps it at 100. */ + .lesson:has(> main > [data-slot="loading-region"]) { + font-variation-settings: "ROND" 0; + font-weight: 400; } - div[style*="marginRight: \"2rem\""], - div[style*="marginRight"] { - margin-right: 0.5rem; + /* Menus, tooltips, dialogs and toasts portal out of .lesson to , + so during a session they take the rounded type explicitly. */ + body:has(.lesson) + :is( + [data-radix-popper-content-wrapper], + [data-sonner-toaster], + [role="dialog"], + [role="alertdialog"] + ) { + font-variation-settings: "ROND" 100; } } -/* ================================================================ - Phone breakpoint (max-width: 480px) - ================================================================ */ +/* ========================================================================== + Entering a session or a card review, the shell recedes: the navigation + rail slides out to the left, the top app bar slides up and the bottom + bar slides down while the lesson fades in (React in the + shell components names them). Coming back, they slide in again. + ========================================================================== */ +::view-transition { + /* Clicks during the short animation reach the live page */ + pointer-events: none; +} -@media (max-width: 480px) { - /* -- Even more compact layout -- */ - main { - padding-left: 0.25rem; - padding-right: 0.25rem; - } +::view-transition-old(.shell-rail-recede) { + animation: shell-rail-out var(--duration-medium) var(--ease-emphasized-accelerate) both; +} +::view-transition-old(.shell-bar-recede) { + animation: shell-bar-out var(--duration-medium) var(--ease-emphasized-accelerate) both; +} +::view-transition-new(.shell-rail-recede) { + animation: shell-rail-out var(--duration-long) var(--ease-emphasized) reverse both; +} +::view-transition-new(.shell-bar-recede) { + animation: shell-bar-out var(--duration-long) var(--ease-emphasized) reverse both; +} +::view-transition-old(.shell-nav-recede) { + animation: shell-nav-out var(--duration-medium) var(--ease-emphasized-accelerate) both; +} +::view-transition-new(.shell-nav-recede) { + animation: shell-nav-out var(--duration-long) var(--ease-emphasized) reverse both; +} - /* -- Stats grids: single column -- */ - div[style*="gridTemplateColumns"] { - grid-template-columns: 1fr !important; +@keyframes shell-rail-out { + to { + transform: translateX(-100%); } - - /* -- Cards: less padding -- */ - .card, - div[style*="padding: \"1.5rem\""] { - padding: 0.75rem; +} +@keyframes shell-bar-out { + to { + transform: translateY(-100%); } - - /* -- Buttons: full width on small screens -- */ - button:not(.nav-hamburger):not(.compact-btn) { - width: 100%; - text-align: center; +} +@keyframes shell-nav-out { + to { + transform: translateY(100%); } +} - /* -- Font sizes tighten further -- */ - h1 { - font-size: 1.2rem; +/* Compact windows: the floating Start session button sits above the bottom + bar, so the page leaves room for it at the end, and a control that takes + focus scrolls clear of it as well as the bar (WCAG 2.4.11). Short windows + hide the button (see SessionFab), so they need neither. */ +@media (width < 37.5rem) and (height > 32rem) { + body:has([data-slot="session-fab"][data-placement="floating"]) #main-content { + padding-bottom: calc(var(--bottom-bar-height) + env(safe-area-inset-bottom) + 5.5rem); } - h2 { - font-size: 1rem; + body:has([data-slot="session-fab"][data-placement="floating"]) :focus { + scroll-margin-bottom: calc(var(--bottom-bar-height) + env(safe-area-inset-bottom) + 5.5rem); } +} - /* -- Rating buttons in flashcards -- */ - div[style*="display: \"flex\""][style*="gap: \"0.4rem\""] { - flex-wrap: wrap; +/* Indeterminate linear progress: the bar sweeps across the track */ +@keyframes progress-indeterminate { + from { + left: -40%; + } + to { + left: 100%; } } -/* ================================================================ - Reduced motion preference - ================================================================ */ +/* The feedback sheet slides up from the bottom after each answer */ +@keyframes feedback-sheet-in { + from { + transform: translateY(100%); + } + to { + transform: translateY(0); + } +} @media (prefers-reduced-motion: reduce) { *, @@ -399,25 +798,22 @@ input[type="number"] { transition-duration: 0.01ms !important; scroll-behavior: auto !important; } -} - -/* ================================================================ - Print styles - ================================================================ */ -@media print { - .nav-container, - .nav-hamburger, - .skip-to-content { - display: none !important; + .lesson { + transition: none; } - body { - background: white; - color: black; + ::view-transition-group(*), + ::view-transition-old(*), + ::view-transition-new(*) { + animation-duration: 0s !important; + animation-delay: 0s !important; } +} - main { - padding-top: 0 !important; +@media print { + body { + background: #ffffff; + color: #000000; } } diff --git a/src/app/guides/page.tsx b/src/app/guides/page.tsx deleted file mode 100644 index 87e11bd4..00000000 --- a/src/app/guides/page.tsx +++ /dev/null @@ -1,501 +0,0 @@ -"use client"; - -import { useState, useEffect, useRef } from "react"; -import Link from "next/link"; -import { getActiveCourse, setActiveCourse } from "@/lib/client-utils"; -import { apiGet, apiPost, apiDelete, type CourseOption } from "@/lib/client-api"; -import { - headerStyle, - titleStyle, - subtitleStyle, - labelStyle, - selectStyle, - generateBtnStyle, - sectionTitleStyle, - deleteBtnStyle, -} from "@/lib/shared-styles"; - -// --- Types --- - -type GuideType = "KEY_CONCEPTS" | "FAQ" | "CHEAT_SHEET"; - -interface GuideSection { - concept?: string; - explanation?: string; - importance?: string; - question?: string; - answer?: string; - topic?: string; - content?: string; -} - -interface StudyGuide { - id: string; - course_name: string; - exam_name: string | null; - guide_type: GuideType; - title: string; - sections: GuideSection[]; - created_at: string; -} - -const GUIDE_TYPES: { value: GuideType; label: string; description: string }[] = [ - { value: "KEY_CONCEPTS", label: "Key Concepts", description: "Important concepts with explanations" }, - { value: "FAQ", label: "FAQ", description: "Common questions and detailed answers" }, - { value: "CHEAT_SHEET", label: "Cheat Sheet", description: "Quick reference for exam review" }, -]; - -export default function GuidesPage() { - const [courses, setCourses] = useState([]); - const [selectedCourse, setSelectedCourseRaw] = useState(() => getActiveCourse()); - const setSelectedCourse = (v: string) => { setSelectedCourseRaw(v); setActiveCourse(v); }; - const [guides, setGuides] = useState([]); - const [generating, setGenerating] = useState(false); - const [selectedType, setSelectedType] = useState("KEY_CONCEPTS"); - const [expandedGuide, setExpandedGuide] = useState(null); - const [error, setError] = useState(null); - const [loadingGuides, setLoadingGuides] = useState(false); - const [deleting, setDeleting] = useState(null); - const selectedCourseRef = useRef(selectedCourse); - selectedCourseRef.current = selectedCourse; - - // Fetch available courses on mount - useEffect(() => { - let mounted = true; - apiGet("/api/content/documents?namespace=COURSE").then((data) => { - if (!mounted) return; - if (data.documents) { - const courseMap = new Map(); - for (const doc of data.documents as { course_name: string; exam_name: string | null }[]) { - if (!doc.course_name) continue; - const key = doc.exam_name - ? `${doc.course_name}||${doc.exam_name}` - : doc.course_name; - const existing = courseMap.get(key); - if (existing) { - existing.doc_count++; - } else { - courseMap.set(key, { - course_name: doc.course_name, - exam_name: doc.exam_name || undefined, - doc_count: 1, - }); - } - } - const options = Array.from(courseMap.values()); - setCourses(options); - const active = getActiveCourse(); - const match = active && options.some((o) => (o.exam_name ? `${o.course_name}||${o.exam_name}` : o.course_name) === active); - if (match) { - setSelectedCourse(active); - } else if (options.length > 0) { - const first = options[0]; - setSelectedCourse(first.exam_name ? `${first.course_name}||${first.exam_name}` : first.course_name); - } - } - }).catch(() => {}); - return () => { mounted = false; }; - }, []); - - // Fetch existing guides when course changes - useEffect(() => { - if (!selectedCourse) return; - let mounted = true; - setLoadingGuides(true); - const [courseName, examName] = selectedCourse.split("||"); - const params = new URLSearchParams({ course_name: courseName }); - if (examName) params.set("exam_name", examName); - apiGet(`/api/guides?${params.toString()}`).then((data) => { - if (mounted && data.guides) setGuides(data.guides); - }).catch(() => { - if (mounted) setGuides([]); - }).finally(() => { - if (mounted) setLoadingGuides(false); - }); - return () => { mounted = false; }; - }, [selectedCourse]); - - const handleGenerate = async () => { - if (!selectedCourse || generating) return; - const courseAtStart = selectedCourse; - setGenerating(true); - setError(null); - - const [courseName, examName] = selectedCourse.split("||"); - - try { - const guide = await apiPost("/api/guides", { - course_name: courseName, - exam_name: examName || undefined, - guide_type: selectedType, - }); - // Only update list if user hasn't switched courses during generation - if (selectedCourseRef.current === courseAtStart) { - setGuides((prev) => [guide, ...prev]); - setExpandedGuide(guide.id); - } - } catch (err) { - if (selectedCourseRef.current === courseAtStart) { - setError(err instanceof Error ? err.message : "Generation failed"); - } - } finally { - setGenerating(false); - } - }; - - const handleDeleteGuide = async (guideId: string) => { - if (deleting) return; - if (!window.confirm("Delete this guide? This cannot be undone.")) return; - setDeleting(guideId); - try { - await apiDelete(`/api/guides/${guideId}`); - setGuides((prev) => prev.filter((g) => g.id !== guideId)); - if (expandedGuide === guideId) setExpandedGuide(null); - } catch { - setError("Failed to delete guide"); - } finally { - setDeleting(null); - } - }; - - return ( -
- {/* Header */} -
-

Study Guides

-

Generate reference guides from your course materials

-
- - {/* Course selector + guide type picker */} - {courses.length > 0 ? ( -
- - - - -
- {GUIDE_TYPES.map((t) => ( - - ))} -
- - - - {error && ( -

{error}

- )} -
- ) : ( -
-

- No course documents yet -

-

- Create a plan and upload your course notes there, then come back to generate study guides. -

- - Create a Study Plan - -
- )} - - {/* Existing guides */} - {loadingGuides && ( -

- Loading guides... -

- )} - {!loadingGuides && courses.length > 0 && guides.length === 0 && ( -
-

- No guides generated yet for this course -

-

- Pick a guide type above and hit Generate to create Key Concepts, FAQs, or Cheat Sheets from your materials. -

-
- )} - {guides.length > 0 && ( -
-

YOUR GUIDES

-
- {guides.map((guide) => ( -
-
- - -
- - {expandedGuide === guide.id && ( -
-
- {renderGuideContent(guide)} -
- -
-
-
- )} -
- ))} -
-
- )} -
- ); -} - -// --- Render guide content by type --- - -function renderGuideContent(guide: StudyGuide): React.ReactNode { - if (!guide.sections || guide.sections.length === 0) { - return

No content generated.

; - } - - switch (guide.guide_type) { - case "KEY_CONCEPTS": - return ( -
- {guide.sections.map((s, i) => ( -
-

- {s.concept || `Concept ${i + 1}`} -

- {s.explanation && ( -

- {s.explanation} -

- )} - {s.importance && ( -

- Why it matters: {s.importance} -

- )} -
- ))} -
- ); - - case "FAQ": - return ( -
- {guide.sections.map((s, i) => ( -
-

- Q: {s.question || `Question ${i + 1}`} -

- {s.answer && ( -

- {s.answer} -

- )} -
- ))} -
- ); - - case "CHEAT_SHEET": - return ( -
- {guide.sections.map((s, i) => ( -
-

- {s.topic || `Topic ${i + 1}`} -

- {s.content && ( -
- {s.content} -
- )} -
- ))} -
- ); - - default: - return

Unknown guide type

; - } -} - -// --- Styles --- - -const pageContainer: React.CSSProperties = { - maxWidth: 1100, - margin: "0 auto", - padding: "1.5rem clamp(1.5rem, 4vw, 2rem)", - fontFamily: "var(--font-body)", - color: "var(--color-text)", -}; - -const guidesGrid: React.CSSProperties = { - display: "grid", - gridTemplateColumns: "repeat(auto-fill, minmax(min(320px, 100%), 1fr))", - gap: 16, - alignItems: "start", -}; - -const typeButton: React.CSSProperties = { - flex: "1 1 auto", - minWidth: 0, - padding: "0.6rem 0.75rem", - fontFamily: "inherit", - border: "1px solid var(--color-border)", - borderRadius: "var(--radius)", - cursor: "pointer", - textAlign: "left", -}; - -const guideHeader: React.CSSProperties = { - display: "flex", - alignItems: "center", - width: "100%", - padding: "1.25rem 1.5rem", - fontSize: "0.9rem", - fontFamily: "inherit", - background: "var(--color-bg-card)", - color: "var(--color-text)", - border: "1px solid var(--color-border)", - borderRadius: "var(--radius)", - cursor: "pointer", -}; - -const guideTypeTag: React.CSSProperties = { - display: "inline-block", - fontSize: "0.65rem", - fontWeight: 600, - color: "var(--color-info)", - background: "var(--color-bg-info-tint)", - padding: "0.1rem 0.4rem", - borderRadius: 3, - marginRight: "0.5rem", - letterSpacing: "0.03em", -}; - -const guideContent: React.CSSProperties = { - background: "var(--color-bg)", - border: "1px solid var(--color-border)", - borderTop: "none", - borderRadius: "0 0 var(--radius) var(--radius)", - padding: "1.75rem clamp(1rem, 4vw, 2.5rem) 1.5rem", - boxShadow: "var(--shadow-card)", -}; - -const guideProse: React.CSSProperties = { - width: "100%", - maxWidth: 820, - margin: "0 auto", -}; - -const conceptCard: React.CSSProperties = { - background: "var(--color-bg-card)", - border: "1px solid var(--color-border)", - borderRadius: "var(--radius-sm)", - padding: "1rem 1.25rem", - marginBottom: "0.75rem", -}; diff --git a/src/app/icon.svg b/src/app/icon.svg index 8bad40b9..90cec9dd 100644 --- a/src/app/icon.svg +++ b/src/app/icon.svg @@ -1,5 +1,8 @@ - - - - + + + + + + + diff --git a/src/app/layout.tsx b/src/app/layout.tsx index a8cde30e..59d01eb2 100644 --- a/src/app/layout.tsx +++ b/src/app/layout.tsx @@ -1,11 +1,29 @@ -import type { Metadata } from "next"; -import { NavBar, NAV_HEIGHT } from "@/ui/components/NavBar"; -import { SessionProviderWrapper } from "@/ui/components/SessionProviderWrapper"; +import type { Metadata, Viewport } from "next"; +import "@fontsource-variable/google-sans-flex/rond.css"; +import "@fontsource-variable/google-sans-code/wght.css"; import "./globals.css"; +import { Providers } from "@/components/providers"; +import { THEME_COLORS } from "@/components/shell/theme-colors"; +import { TITLE_TEMPLATE } from "@/lib/metadata"; export const metadata: Metadata = { - title: "Study Bot", - description: "Research-based study planner", + title: { + default: "Study Bot", + template: TITLE_TEMPLATE, + }, + description: "Plan for your exams and practice from your own course files.", + applicationName: "Study Bot", + manifest: "/manifest.json", +}; + +// First paint follows the system theme; ThemeColorSync (in Providers) +// follows a manual Light or Dark choice after hydration. +export const viewport: Viewport = { + themeColor: [ + { media: "(prefers-color-scheme: light)", color: THEME_COLORS.light }, + { media: "(prefers-color-scheme: dark)", color: THEME_COLORS.dark }, + ], + colorScheme: "light dark", }; export default function RootLayout({ @@ -14,27 +32,9 @@ export default function RootLayout({ children: React.ReactNode; }) { return ( - - - - - - - - + - - - Skip to content - - -
- {children} -
-
+ {children} ); diff --git a/src/app/learn/page.tsx b/src/app/learn/page.tsx deleted file mode 100644 index e92a91ec..00000000 --- a/src/app/learn/page.tsx +++ /dev/null @@ -1,520 +0,0 @@ -"use client"; - -import { useState, useEffect } from "react"; -import Link from "next/link"; -import { getActiveCourse, setActiveCourse, MODE_LABELS } from "@/lib/client-utils"; -import { apiGet } from "@/lib/client-api"; - -/** Pretty label for a session mode (e.g. "RETRIEVAL" → "Retrieval"). */ -function modeLabel(mode: string): string { - return MODE_LABELS[mode] || mode.replace(/_/g, " "); -} - -/** Render a mastery key / objective slug (e.g. "photosynthesis_light_reactions") as a clean label. */ -function prettifyObjectiveKey(key: string): string { - return key - .replace(/_/g, " ") - .trim() - .replace(/\b\w/g, (c) => c.toUpperCase()); -} - -interface CourseData { - courseName: string; - examNames: string[]; - docCount: number; - processedDocCount: number; - deckCount: number; - dueCardCount: number; - guideCount: number; -} - -interface LearnData { - courses: CourseData[]; - hasCourses: boolean; -} - -interface Recommendation { - next_session: { - mode: string; - objectives: string[]; - topic_scope: string; - reason: string; - }; - overdue_objectives: { objective_key: string; days_overdue: number }[]; - weak_objectives: { objective_key: string; last_accuracy: number | null }[]; - unresolved_errors: { count: number; recent_error_types: string[] }; - streak: number; - plan_nudge: { - plan_id: string; - items: { session_id: string; start_time: string; message: string }[]; - } | null; -} - -export default function LearnPage() { - const [data, setData] = useState(null); - const [loading, setLoading] = useState(true); - const [selectedCourse, setSelectedCourseRaw] = useState(null); - const [recs, setRecs] = useState(null); - const [startingSession, setStartingSession] = useState(false); - const [startError, setStartError] = useState(null); - - // The core-loop entry point: turn the recommendation into a real session - // and go study. Objective ids reuse the mastery keys so spaced repetition, - // warm-ups, and pretest gating stay continuous with past sessions. - const startRecommendedSession = async () => { - if (!recs || !data || startingSession) return; - const activeCourse = data.courses.find((c) => c.courseName === selectedCourse) || data.courses[0]; - if (!activeCourse) return; - setStartingSession(true); - setStartError(null); - try { - const res = await fetch("/api/sessions", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ - course_name: activeCourse.courseName, - exam_name: activeCourse.examNames[0] || "General", - mode: recs.next_session.mode, - topic_scope: recs.next_session.topic_scope || activeCourse.courseName, - planned_minutes: 30, - objectives: recs.next_session.objectives.length > 0 - ? recs.next_session.objectives.map((key) => ({ id: key, title: prettifyObjectiveKey(key) })) - : undefined, - target_outcome: { prompt_count: 10 }, - break_protocol: { type: "25_5", cycles: 1 }, - }), - }); - const body = await res.json(); - if (!res.ok) throw new Error(body.error || "Failed to create session"); - window.location.href = body.session_url || `/s/${body.session_id}`; - } catch (e: unknown) { - setStartError(e instanceof Error ? e.message : "Failed to create session"); - setStartingSession(false); - } - }; - const setSelectedCourse = (v: string | null) => { setSelectedCourseRaw(v); if (v) setActiveCourse(v); }; - - useEffect(() => { - apiGet("/api/learn") - .then((d) => { - setData(d); - if (d.courses?.length > 0) { - const active = getActiveCourse(); - const match = d.courses.find((c: CourseData) => c.courseName === active); - setSelectedCourse(match ? match.courseName : d.courses[0].courseName); - } - }) - .catch(() => setData({ courses: [], hasCourses: false })) - .finally(() => setLoading(false)); - }, []); - - // Fetch mastery-driven recommendations when selected course changes - useEffect(() => { - if (!selectedCourse) return; - setRecs(null); - apiGet(`/api/learn/recommendations?course_name=${encodeURIComponent(selectedCourse)}`) - .then(setRecs) - .catch(() => {}); // Graceful: recommendations are optional - }, [selectedCourse]); - - if (loading) { - return ( -
- -

Learn

-
-
-

Loading your courses...

-
-
- ); - } - - if (!data?.hasCourses) { - return ( -
-

Learn

-
-

No courses yet

-

- Upload your first document to start learning. Study Bot will help you create flashcards, guides, and practice sessions. -

-
- Create a Study Plan - Go to Flashcards -
-
-
- ); - } - - const course = data.courses.find((c) => c.courseName === selectedCourse) || data.courses[0]; - - return ( -
-

Learn

- - {/* Course selector */} - {data.courses.length > 1 && ( -
- {data.courses.map((c) => ( - - ))} -
- )} - - {/* Course header */} -
-

{course.courseName}

- {course.examNames.length > 0 && ( -

- Exams: {course.examNames.join(", ")} -

- )} -
- - {/* Mastery-driven recommendation */} - {recs && ( -
- {recs.streak > 0 && ( -
- {recs.streak} day streak -
- )} - {recs.plan_nudge && recs.plan_nudge.items.length > 0 && ( -
- {recs.plan_nudge.items.map((item, i) => ( -
- {item.message} ({new Date(item.start_time).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}) -
- ))} -
- )} -
- - Recommended: {modeLabel(recs.next_session.mode)} - -
-

- {recs.next_session.reason} -

- {recs.overdue_objectives.length > 0 && ( -
- {recs.overdue_objectives.length} objective{recs.overdue_objectives.length !== 1 ? "s" : ""} overdue for review -
- )} - {recs.unresolved_errors.count > 0 && ( -
- {recs.unresolved_errors.count} unresolved error{recs.unresolved_errors.count !== 1 ? "s" : ""} to repair -
- )} - - {startError && ( -

{startError}

- )} -
- )} - - {/* Quick actions — focused on what matters now */} -
-

Quick Actions

-
- {course.deckCount > 0 && course.dueCardCount > 0 && ( - -
-
Review Due Cards
-
- {course.dueCardCount} card{course.dueCardCount !== 1 ? "s" : ""} ready for spaced repetition review -
-
- Review → - - )} - {course.processedDocCount > 0 && course.deckCount === 0 && ( - -
-
Generate Flashcards
-
- {course.processedDocCount} doc{course.processedDocCount !== 1 ? "s" : ""} processed and ready -
-
- Generate → - - )} - {course.guideCount === 0 && course.processedDocCount > 0 && ( - -
-
Create Study Guide
-
- Key concepts, FAQs, or cheat sheets from your materials -
-
- Create → - - )} - -
-
Ask a Question
-
- Chat with your {course.courseName} materials -
-
- Chat → - - {course.dueCardCount === 0 && course.deckCount > 0 && ( -
- All caught up! No cards due for review right now. -
- )} -
-
- - {/* Suggested learning path — onboarding scaffolding for new courses. - Once materials are uploaded and the first deck exists, the user has - found the core loop and this checklist just repeats the nav. */} - {!(course.processedDocCount > 0 && course.deckCount > 0) && ( -
-

Suggested Learning Path

-
- 0} - href="/flashcards" - /> - 0} - href="/flashcards" - /> - 0} - href="/flashcards" - /> - 0} - href="/guides" - /> - -
-
- )} -
- ); -} - -// ---- Learning Step Component ---- - -function LearningStep({ step, title, description, done, href }: { - step: number; - title: string; - description: string; - done: boolean; - href: string; -}) { - return ( - -
- {done ? "\u2713" : step} -
-
-
- {title} -
-
- {description} -
-
- - ); -} - -// ---- Styles ---- - -const mainStyle: React.CSSProperties = { - maxWidth: 1100, - margin: "0 auto", - padding: "1.5rem clamp(24px, 4vw, 32px)", - fontFamily: "var(--font-body)", - color: "var(--color-text)", - backgroundColor: "var(--color-bg)", - minHeight: "100vh", -}; - -const headingStyle: React.CSSProperties = { - fontSize: "2rem", - margin: "0 0 1.5rem", - color: "var(--color-primary)", - fontWeight: 700, - fontFamily: "var(--font-display)", -}; - -const courseNameStyle: React.CSSProperties = { - fontSize: "1.4rem", - color: "var(--color-text)", - fontWeight: 700, - margin: 0, - fontFamily: "var(--font-display)", -}; - -const sectionLabelStyle: React.CSSProperties = { - fontSize: "0.85rem", - color: "var(--color-text-muted)", - marginBottom: "0.75rem", - fontWeight: 600, - textTransform: "uppercase", - letterSpacing: "0.08em", -}; - -const recommendationStyle: React.CSSProperties = { - background: "var(--color-bg-selected)", - border: "1px solid var(--color-border)", - borderLeft: "3px solid var(--color-border)", - borderRadius: "var(--radius)", - padding: "1.5rem clamp(1.25rem, 3vw, 2rem)", - marginBottom: "1.5rem", - boxShadow: "var(--shadow-card)", -}; - -const quickActionsGridStyle: React.CSSProperties = { - display: "grid", - gridTemplateColumns: "repeat(auto-fill, minmax(320px, 1fr))", - gap: 16, -}; - -const quickActionStyle: React.CSSProperties = { - display: "flex", - flexDirection: "column", - gap: "0.75rem", - padding: "1.25rem 1.5rem", - background: "var(--color-bg-card)", - border: "1px solid var(--color-border)", - borderLeft: "3px solid var(--color-border)", - borderRadius: "var(--radius)", - textDecoration: "none", - cursor: "pointer", - boxShadow: "var(--shadow-card)", -}; - -const emptyCardStyle: React.CSSProperties = { - padding: "3rem 2rem", - border: "1px dashed var(--color-border-done)", - borderRadius: "var(--radius-lg)", - textAlign: "center", - color: "var(--color-text-secondary)", -}; - -const primaryBtnStyle: React.CSSProperties = { - padding: "0.7rem 1.4rem", - fontSize: "1rem", - background: "var(--color-primary)", - color: "var(--color-bg-darkest)", - border: "none", - borderRadius: "var(--radius)", - fontWeight: 700, - fontFamily: "inherit", - textDecoration: "none", - cursor: "pointer", -}; - -const secondaryBtnStyle: React.CSSProperties = { - padding: "0.7rem 1.25rem", - fontSize: "0.95rem", - background: "transparent", - color: "var(--color-primary)", - border: "1px solid var(--color-primary)", - borderRadius: "var(--radius)", - fontWeight: 600, - fontFamily: "inherit", - textDecoration: "none", - cursor: "pointer", -}; - -const spinnerStyle: React.CSSProperties = { - width: "32px", - height: "32px", - border: "3px solid var(--color-border)", - borderTop: "3px solid var(--color-primary)", - borderRadius: "50%", - margin: "0 auto", - animation: "dash-spin 0.8s linear infinite", -}; diff --git a/src/app/not-found.tsx b/src/app/not-found.tsx new file mode 100644 index 00000000..42a98030 --- /dev/null +++ b/src/app/not-found.tsx @@ -0,0 +1,34 @@ +import type { Metadata } from "next"; +import Link from "next/link"; +import { CompassIcon } from "lucide-react"; + +import { StatusScreen } from "@/components/app/status-screen"; +import { AppMark } from "@/components/shell/app-mark"; +import { Button } from "@/components/ui/button"; + +export const metadata: Metadata = { + title: "Page not found", +}; + +export default function NotFound() { + return ( +
+
+ + Study Bot +
+
+ + Go to Home + + } + /> +
+
+ ); +} diff --git a/src/app/page.tsx b/src/app/page.tsx deleted file mode 100644 index e044ab20..00000000 --- a/src/app/page.tsx +++ /dev/null @@ -1,886 +0,0 @@ -"use client"; - -import { useState, useEffect, useMemo, useCallback, useRef } from "react"; -import Link from "next/link"; -import { useRouter } from "next/navigation"; -import { MODE_LABELS } from "@/lib/client-utils"; -import { BADGE_MAP, TOTAL_BADGES } from "@/lib/badge-data"; -import { ErrorBoundary } from "@/ui/components/ErrorBoundary"; - -// ---- Types ---- - -interface RunInfo { - runId: string; - status: string; - metrics: unknown; - endedAt: string | null; - startedAt: string | null; -} - -interface PlanItem { - id: string; - start_time: string; - end_time: string; - status: string; - completed_at: string | null; - session_id: string; - mode: string; - topic_scope: string; - planned_minutes: number; - runs: RunInfo[]; -} - -interface Plan { - plan_id: string; - course_name: string; - exam_name: string; - items: PlanItem[]; -} - -interface ActivityDay { - date: string; - count: number; -} - -interface ActivityData { - activity: ActivityDay[]; - streak: number; - total_xp: number; -} - -interface GameState { - xpToday: number; - xpTotal: number; - dailyXpGoal: number; - streak: number; - streakFreezes: number; - achievements: { badgeType: string; earnedAt: string }[]; - newAchievements: string[]; -} - - -// ---- Helpers ---- - -function formatTime(iso: string): string { - return new Date(iso).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }); -} - -function isSameDay(a: Date, b: Date): boolean { - return a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate(); -} - -/** - * Session cards show a single quiet scope line. topic_scope is often a - * comma-joined objective list (sometimes with a "(+N more)" suffix); when it - * names more than 2 objectives, collapse to "N objectives" — the full scope - * lives on the session preflight screen. - */ -function formatScope(scope: string): string { - const moreMatch = scope.match(/\(\+(\d+) more\)\s*$/); - const base = moreMatch ? scope.slice(0, moreMatch.index).trim() : scope; - const parts = base.split(",").map((s) => s.trim()).filter(Boolean); - const total = parts.length + (moreMatch ? parseInt(moreMatch[1], 10) : 0); - return total > 2 ? `${total} objectives` : scope; -} - -const MODE_COLORS: Record = { - RETRIEVAL: "var(--color-info)", - INTERLEAVED_PRACTICE: "var(--color-review)", - ERROR_REPAIR: "var(--color-error)", - EXAM_SIM: "var(--color-primary)", - WORKED_EXAMPLES: "var(--color-success)", -}; - -// ---- Component ---- - -export default function DashboardPage() { - const router = useRouter(); - const [plans, setPlans] = useState([]); - const [loading, setLoading] = useState(true); - const [error, setError] = useState(null); - const [activityData, setActivityData] = useState(null); - const [gameState, setGameState] = useState(null); - const [showConfetti, setShowConfetti] = useState(false); - const [celebrationBadge, setCelebrationBadge] = useState(null); - const [onboarding, setOnboarding] = useState<{ show: boolean; step: number }>({ show: false, step: 0 }); - - useEffect(() => { - async function fetchPlans() { - try { - const res = await fetch("/api/plans"); - if (!res.ok) { - const data = await res.json().catch(() => ({})); - throw new Error(data.error || `HTTP ${res.status}`); - } - const data = await res.json(); - setPlans(data.plans || []); - } catch (e: unknown) { - setError(e instanceof Error ? e.message : "Failed to load plans"); - } finally { - setLoading(false); - } - } - async function fetchActivity() { - try { - const res = await fetch("/api/stats/activity"); - if (res.ok) { - const data = await res.json(); - setActivityData(data); - } - } catch { - // Activity is non-critical - } - } - async function fetchGameState() { - try { - const res = await fetch("/api/stats/game"); - if (res.ok) { - const data: GameState = await res.json(); - setGameState(data); - // Show confetti for new achievements - if (data.newAchievements && data.newAchievements.length > 0) { - setCelebrationBadge(data.newAchievements[0]); - setShowConfetti(true); - setTimeout(() => { setShowConfetti(false); setCelebrationBadge(null); }, 4000); - } - } - } catch { - // Non-critical - } - } - async function checkOnboarding() { - try { - const res = await fetch("/api/onboarding"); - if (res.ok) { - const data = await res.json(); - if (!data.complete) { - setOnboarding({ show: true, step: 0 }); - } - } - } catch { - // Non-critical - } - } - fetchPlans(); - fetchActivity(); - fetchGameState(); - checkOnboarding(); - }, []); - - const allItems = useMemo(() => plans.flatMap((p) => p.items), [plans]); - const today = useMemo(() => new Date(), []); - - const todaySessions = useMemo(() => { - return allItems - .filter((item) => isSameDay(new Date(item.start_time), today)) - .sort((a, b) => new Date(a.start_time).getTime() - new Date(b.start_time).getTime()); - }, [allItems, today]); - - // Stats - const stats = useMemo(() => { - const completed = allItems.filter((i) => i.status === "DONE"); - const totalMinutes = completed.reduce((sum, i) => sum + i.planned_minutes, 0); - const totalHours = Math.round((totalMinutes / 60) * 10) / 10; - - let totalAccuracy = 0; - let accuracyCount = 0; - for (const item of allItems) { - for (const run of item.runs) { - const m = run.metrics as Record | null; - if (m && typeof m === "object" && typeof m.accuracy === "number") { - totalAccuracy += m.accuracy as number; - accuracyCount++; - } - } - } - const avgAccuracy = accuracyCount > 0 ? Math.round((totalAccuracy / accuracyCount) * 100) : null; - - return { completed: completed.length, totalHours, avgAccuracy }; - }, [allItems]); - - // ---- Render ---- - - if (loading) { - return ( -
- -
-
-

Loading...

-
-
- ); - } - - if (error) { - return ( -
-
-

Failed to load dashboard

-

{error}

- -
-
- ); - } - - const streak = gameState?.streak ?? activityData?.streak ?? 0; - const totalXp = gameState?.xpTotal ?? activityData?.total_xp ?? 0; - const earnedBadges = gameState?.achievements.length ?? 0; - // First run: nothing to show but zeros — render only the welcoming Today card. - const firstRun = plans.length === 0 && streak === 0 && totalXp === 0 && earnedBadges === 0; - - return ( -
- - - {/* Confetti overlay */} - - {showConfetti && } - - - {/* Onboarding overlay */} - {onboarding.show && ( - setOnboarding((prev) => ({ ...prev, step: prev.step + 1 }))} - onComplete={async () => { - setOnboarding({ show: false, step: 0 }); - await fetch("/api/onboarding", { method: "POST" }).catch(() => {}); - router.push("/plan"); - }} - onSkip={async () => { - setOnboarding({ show: false, step: 0 }); - await fetch("/api/onboarding", { method: "POST" }).catch(() => {}); - }} - /> - )} - -

Dashboard

- - {/* Today's Sessions — the primary section, first on the page */} -
-

Today

- {todaySessions.length === 0 ? ( -
-

- {plans.length === 0 ? "Welcome to Study Bot" : "No sessions today"} -

-

- {plans.length === 0 - ? "Create a study plan and your daily sessions will show up here." - : "Rest is part of effective learning."} -

- {plans.length === 0 && ( - - Create your plan - - )} -
- ) : ( -
- {todaySessions.map((item) => { - const single = todaySessions.length === 1; - const mc = MODE_COLORS[item.mode] || "var(--color-info)"; - const actionable = item.status === "SCHEDULED" || item.status === "IN_PROGRESS"; - const actionLabel = item.status === "IN_PROGRESS" ? "Continue" : "Start"; - const cardContent = single ? ( - // Single session: one wide row so the lone card feels substantial. -
- - {formatTime(item.start_time)} - {formatTime(item.end_time)} - - - {MODE_LABELS[item.mode] || item.mode} - - - {formatScope(item.topic_scope)} - - {actionable && {actionLabel}} - {item.status === "DONE" && ( - Done - )} -
- ) : ( - // Grid cards: stacked layout that reads cleanly at ~320px wide. -
-
- - {formatTime(item.start_time)} - {formatTime(item.end_time)} - - {item.status === "DONE" && ( - Done - )} -
- - {MODE_LABELS[item.mode] || item.mode} - - - {formatScope(item.topic_scope)} - - {actionable && ( - {actionLabel} - )} -
- ); - const cardStyle = { - ...sessionCardStyle, - padding: single ? "1.75rem 2rem" : "1.25rem 1.5rem", - ...(single ? {} : { display: "flex" as const, flexDirection: "column" as const }), - textDecoration: "none" as const, - cursor: actionable ? "pointer" as const : "default" as const, - borderLeft: `3px solid ${mc}`, - }; - return actionable ? ( - - {cardContent} - - ) : ( -
- {cardContent} -
- ); - })} -
- )} -
- - {/* Everything below is suppressed on first run — no data, only zeros */} - {!firstRun && ( - <> - {/* Stats — one quiet line, no cards */} -
-

- - {gameState?.xpToday ?? 0} / {gameState?.dailyXpGoal ?? 50} XP today - - · - - {streak} day streak - {gameState && gameState.streakFreezes > 0 && ` (${gameState.streakFreezes} freeze${gameState.streakFreezes !== 1 ? "s" : ""})`} - - · - {stats.completed} session{stats.completed !== 1 ? "s" : ""} - · - {stats.avgAccuracy !== null ? `${stats.avgAccuracy}%` : "--"} accuracy - · - {stats.totalHours}h studied - · - {totalXp} XP total -

-
- - {/* Create plan shortcut if plans exist */} - {plans.length > 0 && ( - - + New Plan - - )} - - {/* Achievements */} -
-
-

Achievements

- - View All ({earnedBadges}/{TOTAL_BADGES}) - -
- {gameState && gameState.achievements.length > 0 ? ( -
- {gameState.achievements.map((a) => { - const info = BADGE_MAP[a.badgeType]; - if (!info) return null; - return ( - - {info.icon} - {info.label} - - ); - })} -
- ) : ( - -

- No badges earned yet. Start studying to unlock achievements! -

- - )} -
- - {/* Activity Heatmap — intentionally last */} - {activityData && ( -
-

Activity

- -
- )} - - )} - -
- ); -} - -// ---- Onboarding Flow ---- - -function OnboardingFlow({ - step, - onNext, - onComplete, - onSkip, -}: { - step: number; - onNext: () => void; - onComplete: () => void; - onSkip: () => void; -}) { - // Focus the dialog once on mount. - const dialogRef = useRef(null); - useEffect(() => { - dialogRef.current?.focus(); - }, []); - - const steps = [ - { - title: "Welcome to Study Bot!", - content: ( -
-

- Your AI-powered study companion. Upload your course materials and let Study Bot help you learn more effectively. -

-
- {[ - { icon: "\u{1F0CF}", text: "Generate flashcards with spaced repetition" }, - { icon: "\u{1F4D6}", text: "Create study guides and cheat sheets" }, - { icon: "\u{1F4AC}", text: "Chat with your course materials" }, - { icon: "\u{1F4C5}", text: "Plan study sessions and track progress" }, - { icon: "\u{1F3C6}", text: "Earn XP and unlock achievements" }, - ].map((item) => ( -
- {item.icon} - {item.text} -
- ))} -
-
- ), - }, - { - title: "Your learning journey", - content: ( -
-

- Here's how to get the most out of Study Bot: -

-
- {[ - { step: "1", title: "Create a plan", desc: "On the Plan page: course name, exam date, and upload your notes" }, - { step: "2", title: "Study your sessions", desc: "Each plan day links to a session with questions from your materials" }, - { step: "3", title: "Review regularly", desc: "Use spaced repetition to build lasting knowledge" }, - { step: "4", title: "Track progress", desc: "Watch your XP grow and unlock achievements" }, - ].map((item) => ( -
-
- {item.step} -
-
-
{item.title}
-
{item.desc}
-
-
- ))} -
-
- ), - }, - ]; - - const currentStep = steps[step] || steps[steps.length - 1]; - const isLast = step >= steps.length - 1; - - return ( -
-
- {/* Step indicator */} -
- {steps.map((_, i) => ( -
- ))} -
- -

- {currentStep.title} -

- - {currentStep.content} - -
- - -
-
-
- ); -} - -// ---- Confetti Overlay ---- - -function ConfettiOverlay({ badge }: { badge: string | null }) { - const info = badge ? BADGE_MAP[badge] : null; - const particles = useMemo(() => { - const colors = [ - "var(--color-primary)", - "var(--color-warning)", - "var(--color-success)", - "var(--color-info)", - "var(--color-review)", - "var(--color-error)", - ]; - return Array.from({ length: 40 }, (_, i) => ({ - id: i, - left: Math.random() * 100, - delay: Math.random() * 2, - duration: 2 + Math.random() * 2, - color: colors[i % colors.length], - size: 4 + Math.random() * 6, - })); - }, []); - - return ( -
- {particles.map((p) => ( -
- ))} - {info && ( -
-
{info.icon}
-
- {info.label}! -
-
- {info.description} -
-
- )} -
- ); -} - -// ---- Activity Heatmap ---- - -function ActivityHeatmap({ activity }: { activity: ActivityDay[] }) { - const { weeks, monthLabels } = useMemo(() => { - const countMap = new Map(); - for (const a of activity) countMap.set(a.date, a.count); - - const today = new Date(); - today.setHours(0, 0, 0, 0); - const dayOfWeek = today.getDay(); - const startDate = new Date(today); - startDate.setDate(startDate.getDate() - (52 * 7 + dayOfWeek)); - - const wks: { date: string; count: number; dayOfWeek: number }[][] = []; - const mLabels: { label: string; weekIndex: number }[] = []; - let lastMonth = -1; - - const cursor = new Date(startDate); - let weekIdx = 0; - let currentWeek: { date: string; count: number; dayOfWeek: number }[] = []; - - while (cursor <= today) { - const key = cursor.toISOString().slice(0, 10); - const dow = cursor.getDay(); - - if (dow === 0 && currentWeek.length > 0) { - wks.push(currentWeek); - weekIdx++; - currentWeek = []; - } - - const month = cursor.getMonth(); - if (month !== lastMonth) { - const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; - mLabels.push({ label: monthNames[month], weekIndex: weekIdx }); - lastMonth = month; - } - - currentWeek.push({ - date: key, - count: countMap.get(key) || 0, - dayOfWeek: dow, - }); - - cursor.setDate(cursor.getDate() + 1); - } - if (currentWeek.length > 0) wks.push(currentWeek); - - return { weeks: wks, monthLabels: mLabels }; - }, [activity]); - - const getColor = useCallback((count: number) => { - if (count === 0) return "var(--color-bg-darkest)"; - if (count === 1) return "rgba(88, 201, 139, 0.3)"; // --color-success @ 30% - if (count === 2) return "rgba(88, 201, 139, 0.5)"; - if (count <= 4) return "rgba(88, 201, 139, 0.72)"; - return "var(--color-success)"; - }, []); - - const cellSize = 11; - const cellGap = 2; - const step = cellSize + cellGap; - - // Natural drawing size; the SVGs scale up to fill the container on wide - // viewports (via viewBox + width 100%) and scroll horizontally on narrow ones. - const naturalWidth = weeks.length * step; - - return ( -
-
- - {monthLabels.map((m, i) => ( - - {m.label} - - ))} - - - {weeks.map((week, wi) => - week.map((day) => ( - - {day.date}: {day.count} session{day.count !== 1 ? "s" : ""} - - )) - )} - -
- Less - {[0, 1, 2, 3, 5].map((n) => ( - - - - ))} - More -
-
-
- ); -} - -// ---- Styles ---- - -const mainStyle: React.CSSProperties = { - maxWidth: 1100, - margin: "0 auto", - padding: "1.5rem 1.75rem", - fontFamily: "var(--font-body)", - color: "var(--color-text)", - backgroundColor: "var(--color-bg)", - minHeight: "100vh", -}; - -const headingStyle: React.CSSProperties = { - fontSize: "1.6rem", - margin: "0 0 1.5rem", - color: "var(--color-text)", - fontWeight: 700, - fontFamily: "var(--font-display)", -}; - -const sectionHeadingStyle: React.CSSProperties = { - fontSize: "0.8rem", - color: "var(--color-text-muted)", - marginBottom: "0.75rem", - fontWeight: 600, - textTransform: "uppercase", - letterSpacing: "0.08em", -}; - -const statStripStyle: React.CSSProperties = { - display: "flex", - flexWrap: "wrap", - alignItems: "baseline", - columnGap: "0.5rem", - rowGap: "0.2rem", - margin: 0, - fontSize: "0.8rem", - color: "var(--color-text-muted)", -}; - -const statStripDotStyle: React.CSSProperties = { - color: "var(--color-text-faint)", -}; - -const badgeStyle: React.CSSProperties = { - display: "flex", - flexDirection: "column", - alignItems: "center", - padding: "0.5rem 0.6rem", - background: "var(--color-bg-card)", - border: "1px solid var(--color-border-subtle)", - borderRadius: "var(--radius)", - minWidth: 60, -}; - -const sessionCardStyle: React.CSSProperties = { - padding: "0.75rem 1rem", - border: "1px solid var(--color-border-subtle)", - borderRadius: "var(--radius)", - backgroundColor: "var(--color-bg-card)", - boxShadow: "var(--shadow-card)", -}; - -const emptyCardStyle: React.CSSProperties = { - padding: "2rem", - border: "1px dashed var(--color-border-done)", - borderRadius: "var(--radius-lg)", - textAlign: "center", - color: "var(--color-text-secondary)", -}; - -// Filled primary — the single visual primary action on the page. -const primaryBtnStyle: React.CSSProperties = { - display: "inline-block", - padding: "0.7rem 1.4rem", - fontSize: "1rem", - fontWeight: 600, - color: "var(--color-bg-darkest)", - backgroundColor: "var(--color-primary)", - border: "none", - borderRadius: "var(--radius)", - textDecoration: "none", - cursor: "pointer", - fontFamily: "inherit", -}; - -const actionBtnStyle: React.CSSProperties = { - padding: "0.7rem 1.25rem", - fontSize: "0.95rem", - fontWeight: 600, - color: "var(--color-primary)", - border: "1px solid var(--color-primary)", - borderRadius: "var(--radius)", - backgroundColor: "var(--color-bg-selected)", - textDecoration: "none", - cursor: "pointer", - fontFamily: "inherit", -}; - -const spinnerStyle: React.CSSProperties = { - width: "32px", - height: "32px", - border: "3px solid var(--color-border)", - borderTop: "3px solid var(--color-primary)", - borderRadius: "50%", - margin: "0 auto", - animation: "dash-spin 0.8s linear infinite", -}; diff --git a/src/app/plan/page.tsx b/src/app/plan/page.tsx deleted file mode 100644 index fb6415fa..00000000 --- a/src/app/plan/page.tsx +++ /dev/null @@ -1,923 +0,0 @@ -"use client"; - -import { useState, useEffect, useCallback } from "react"; -import { MODE_LABELS } from "@/lib/client-utils"; - -interface PlanItem { - id: string; - day_index: number; - start_time: string; - end_time: string; - status?: string; - session_id: string; - session_url: string; - mode: string; - topic_scope: string; - planned_minutes: number; - objectives?: { id: string; title: string }[]; -} - -interface PlanDetail { - plan_id: string; - ics_download_url: string; - feed_url: string; - webcal_url: string; - course_name: string; - exam_name: string; - exam_date: string; // YYYY-MM-DD - timezone: string; - start_date: string; - end_date: string; - items: PlanItem[]; -} - -interface PlanSummary { - plan_id: string; - course_name: string; - exam_name: string; - exam_date: string; - created_at: string; -} - -// ---- Date helpers (all computed in the plan's timezone) ---- - -function ymdInTz(date: Date, tz?: string): string { - const opts: Intl.DateTimeFormatOptions = { year: "numeric", month: "2-digit", day: "2-digit" }; - try { - return new Intl.DateTimeFormat("en-CA", { ...opts, timeZone: tz }).format(date); - } catch { - return new Intl.DateTimeFormat("en-CA", opts).format(date); - } -} - -function ymdToUtcMs(ymd: string): number { - const [y, m, d] = ymd.split("-").map(Number); - return Date.UTC(y, m - 1, d); -} - -/** Calendar days from today (in the plan tz) until a YYYY-MM-DD date. */ -function daysUntil(ymd: string, tz?: string): number { - return Math.round((ymdToUtcMs(ymd) - ymdToUtcMs(ymdInTz(new Date(), tz))) / 86400000); -} - -/** "Wednesday, Jul 16" for an ISO instant, rendered in the plan tz. */ -function formatDayLabel(iso: string, tz?: string): string { - const opts: Intl.DateTimeFormatOptions = { weekday: "long", month: "short", day: "numeric" }; - try { - return new Intl.DateTimeFormat("en-US", { ...opts, timeZone: tz }).format(new Date(iso)); - } catch { - return new Intl.DateTimeFormat("en-US", opts).format(new Date(iso)); - } -} - -/** "Wednesday, Jul 23" for a YYYY-MM-DD calendar date (no tz math needed). */ -function formatCalendarDate(ymd: string): string { - return new Intl.DateTimeFormat("en-US", { - weekday: "long", - month: "short", - day: "numeric", - timeZone: "UTC", - }).format(new Date(ymdToUtcMs(ymd))); -} - -function formatTime(iso: string, tz?: string): string { - try { - return new Date(iso).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", timeZone: tz }); - } catch { - return new Date(iso).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }); - } -} - -/** Short per-session focus line: the item's own objectives, first 2 + "+N more". */ -function focusLine(item: PlanItem): string { - const titles = (item.objectives ?? []).map((o) => o.title).filter(Boolean); - // Fall back to topic_scope, but never print the full comma-joined list - const parts = - titles.length > 0 - ? titles - : item.topic_scope.split(",").map((s) => s.trim()).filter(Boolean); - const shown = parts.slice(0, 2).join(", "); - return parts.length > 2 ? `${shown} +${parts.length - 2} more` : shown; -} - -function countdownText(plan: PlanDetail): string { - const n = daysUntil(plan.exam_date, plan.timezone); - if (n > 1) return `${n} days until ${plan.exam_name}`; - if (n === 1) return `1 day until ${plan.exam_name}`; - if (n === 0) return `${plan.exam_name} is today`; - return `${plan.exam_name} was ${-n} ${-n === 1 ? "day" : "days"} ago`; -} - -export default function PlanPage() { - const [courseName, setCourseName] = useState(""); - const [examName, setExamName] = useState(""); - const [examDate, setExamDate] = useState(""); - const [uploadedFiles, setUploadedFiles] = useState<{ id: string; name: string; status: string }[]>([]); - const [uploading, setUploading] = useState(false); - const [useManualObjectives, setUseManualObjectives] = useState(false); - const [objectivesText, setObjectivesText] = useState(""); - const [loading, setLoading] = useState(false); - const [error, setError] = useState(null); - - // Availability prefilled from saved settings (falls back to localStorage, then defaults) - const [studyStart, setStudyStart] = useState("09:00"); - const [studyEnd, setStudyEnd] = useState("17:00"); - const [dailyCap, setDailyCap] = useState(180); - - // Persistent plan state — loaded from the API on every visit - const [plans, setPlans] = useState([]); - const [plan, setPlan] = useState(null); - const [initialLoading, setInitialLoading] = useState(true); - const [showForm, setShowForm] = useState(false); - - const [googleConnected, setGoogleConnected] = useState(false); - const [publishing, setPublishing] = useState(false); - const [publishDone, setPublishDone] = useState(false); - const [deletingPlan, setDeletingPlan] = useState(false); - const [reflowLoading, setReflowLoading] = useState(false); - const [reflowPreview, setReflowPreview] = useState<{ moved: number; kept: number; dropped: number; total_items: number } | null>(null); - - useEffect(() => { - async function checkGoogle() { - try { - const res = await fetch("/api/integrations/google/status", { - }); - const data = await res.json(); - setGoogleConnected(data.connected ?? data.status === "CONNECTED"); - } catch { - // Non-critical - } - } - checkGoogle(); - }, []); - - // Prefill availability from saved study hours (backend first, localStorage fallback) - useEffect(() => { - async function loadPrefs() { - try { - const res = await fetch("/api/settings"); - if (!res.ok) throw new Error("fallback"); - const settings = await res.json(); - if (settings.studyStart) setStudyStart(settings.studyStart); - if (settings.studyEnd) setStudyEnd(settings.studyEnd); - if (settings.dailyCap) setDailyCap(settings.dailyCap); - } catch { - try { - const raw = localStorage.getItem("study_bot_prefs"); - if (raw) { - const prefs = JSON.parse(raw); - if (prefs.studyStart) setStudyStart(prefs.studyStart); - if (prefs.studyEnd) setStudyEnd(prefs.studyEnd); - if (prefs.dailyCap) setDailyCap(prefs.dailyCap); - } - } catch { /* defaults */ } - } - } - loadPrefs(); - }, []); - - const fetchPlanDetail = useCallback(async (planId: string): Promise => { - const res = await fetch(`/api/plans/${planId}`, { cache: "no-store" }); - const data = await res.json(); - if (!res.ok) throw new Error(data.error || "Failed to load plan"); - return data as PlanDetail; - }, []); - - // Load the user's plans and show the most recent one (or the preferred one) - const refreshPlans = useCallback(async (preferPlanId?: string) => { - const res = await fetch("/api/plans", { cache: "no-store" }); - const data = await res.json(); - if (!res.ok) throw new Error(data.error || "Failed to load plans"); - const list: PlanSummary[] = data.plans ?? []; - setPlans(list); - const target = (preferPlanId && list.find((p) => p.plan_id === preferPlanId)) || list[0]; - if (target) { - const detail = await fetchPlanDetail(target.plan_id); - setPlan(detail); - setShowForm(false); - setReflowPreview(null); - } else { - setPlan(null); - setShowForm(true); - } - }, [fetchPlanDetail]); - - useEffect(() => { - refreshPlans() - .catch(() => setError("Failed to load your plans")) - .finally(() => setInitialLoading(false)); - }, [refreshPlans]); - - const switchPlan = async (planId: string) => { - setError(null); - try { - const detail = await fetchPlanDetail(planId); - setPlan(detail); - setPublishDone(false); - setReflowPreview(null); - } catch (e: unknown) { - setError(e instanceof Error ? e.message : "Failed to load plan"); - } - }; - - const handleFileUpload = async (e: React.ChangeEvent) => { - const files = e.target.files; - if (!files || files.length === 0) return; - if (!courseName.trim()) { - setError("Enter a course name before uploading"); - return; - } - - setUploading(true); - setError(null); - - for (const file of Array.from(files)) { - const formData = new FormData(); - formData.append("file", file); - formData.append("namespace", "COURSE"); - formData.append("course_name", courseName); - if (examName.trim()) formData.append("exam_name", examName); - - try { - const res = await fetch("/api/content/documents", { - method: "POST", - body: formData, - }); - const data = await res.json(); - if (res.ok) { - const docId = data.document_id; - setUploadedFiles((prev) => [ - ...prev, - { id: docId, name: file.name, status: data.status || "PENDING" }, - ]); - if (data.status !== "PROCESSED") { - fetch(`/api/content/documents/${docId}/process`, { - method: "POST", - }) - .then((r) => r.json()) - .then((d) => { - setUploadedFiles((prev) => - prev.map((f) => (f.id === docId ? { ...f, status: d.status || "PROCESSED" } : f)), - ); - }) - .catch(() => { - setUploadedFiles((prev) => - prev.map((f) => (f.id === docId ? { ...f, status: "FAILED" } : f)), - ); - }); - } - } else { - setError(`Failed to upload ${file.name}: ${data.error}`); - } - } catch { - setError(`Network error uploading ${file.name}`); - } - } - - setUploading(false); - e.target.value = ""; - }; - - const handlePublish = async () => { - if (!plan) return; - setPublishing(true); - setError(null); - try { - const res = await fetch(`/api/plans/${plan.plan_id}/publish/google`, { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({}), - }); - if (!res.ok) { - const data = await res.json(); - setError(data.error || "Failed to publish"); - return; - } - setPublishDone(true); - } catch { - setError("Network error"); - } finally { - setPublishing(false); - } - }; - - const handleSubmit = async (e: React.FormEvent) => { - e.preventDefault(); - setLoading(true); - setError(null); - - const objectives = useManualObjectives - ? objectivesText.split("\n").map((s) => s.trim()).filter(Boolean) - : []; - const document_ids = uploadedFiles.map((f) => f.id); - - if (objectives.length < 3 && document_ids.length === 0) { - setError("Upload course content or list at least 3 objectives"); - setLoading(false); - return; - } - - // Replace (never stack) any existing plan for the same course - const sameCourse = plans.filter( - (p) => p.course_name.trim().toLowerCase() === courseName.trim().toLowerCase(), - ); - if (sameCourse.length > 0) { - const ok = window.confirm( - `You already have a plan for ${sameCourse[0].course_name}. Creating a new one will replace it. Continue?`, - ); - if (!ok) { - setLoading(false); - return; - } - for (const old of sameCourse) { - try { - const delRes = await fetch(`/api/plans/${old.plan_id}`, { method: "DELETE" }); - if (!delRes.ok && delRes.status !== 404) { - const data = await delRes.json().catch(() => ({})); - setError(data.error || "Failed to replace the existing plan"); - setLoading(false); - return; - } - } catch { - setError("Network error"); - setLoading(false); - return; - } - } - } - - const availability = Array.from({ length: 7 }, () => ({ start: studyStart, end: studyEnd })); - - try { - const res = await fetch("/api/plans", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ - course_name: courseName, - exam_name: examName, - exam_date: examDate, - objectives: objectives.length > 0 ? objectives : undefined, - document_ids: document_ids.length > 0 ? document_ids : undefined, - availability, - daily_study_cap_minutes: dailyCap, - break_protocol_default: "25_5", - }), - }); - - const data = await res.json(); - if (!res.ok) { - setError(data.error || "Failed to create plan"); - return; - } - setPublishDone(false); - // Reset the form for next time and switch to the persistent plan view - setCourseName(""); - setExamName(""); - setExamDate(""); - setUploadedFiles([]); - setObjectivesText(""); - setUseManualObjectives(false); - await refreshPlans(data.plan_id); - } catch { - setError("Network error"); - } finally { - setLoading(false); - } - }; - - const handleDeletePlan = async () => { - if (!plan || deletingPlan) return; - if (!window.confirm("Delete this study plan? This cannot be undone.")) return; - setDeletingPlan(true); - setError(null); - try { - const res = await fetch(`/api/plans/${plan.plan_id}`, { - method: "DELETE", - }); - if (!res.ok) { - const data = await res.json().catch(() => ({})); - setError(data.error || "Failed to delete plan"); - return; - } - setPublishDone(false); - await refreshPlans(); - } catch { - setError("Network error"); - } finally { - setDeletingPlan(false); - } - }; - - // ---- Reflow: reschedule missed sessions (the recovery path a slipping - // exam week actually needs; ~900 lines of tested logic behind one button) - const previewReflow = async () => { - if (!plan || reflowLoading) return; - setReflowLoading(true); - setError(null); - try { - const res = await fetch(`/api/plans/${plan.plan_id}/reflow/preview`, { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ reason: "missed_sessions" }), - }); - const data = await res.json(); - if (!res.ok) throw new Error(data.error || "Failed to preview reschedule"); - setReflowPreview(data.summary); - } catch (e: unknown) { - setError(e instanceof Error ? e.message : "Failed to preview reschedule"); - } finally { - setReflowLoading(false); - } - }; - - const applyReflow = async () => { - if (!plan || reflowLoading) return; - setReflowLoading(true); - setError(null); - try { - const res = await fetch(`/api/plans/${plan.plan_id}/reflow/apply`, { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ reason: "missed_sessions" }), - }); - const data = await res.json(); - if (!res.ok) throw new Error(data.error || "Failed to apply reschedule"); - // Refresh the plan so the new times render - const fresh = await fetchPlanDetail(plan.plan_id); - setPlan(fresh); - setReflowPreview(null); - } catch (e: unknown) { - setError(e instanceof Error ? e.message : "Failed to apply reschedule"); - } finally { - setReflowLoading(false); - } - }; - - // ---- Loading view ---- - if (initialLoading) { - return ( -
-

Your Plan

-
Loading your plan...
-
- ); - } - - // ---- Form view ---- - if (showForm || !plan) { - return ( -
-
-

New Study Plan

- {plan && ( - - )} -
-
-
- - -
-
- -
-
- - -
- - {/* Content upload */} -
-
- Upload your course materials and we'll build a plan around them. -
- - - {uploadedFiles.length > 0 && ( -
- {uploadedFiles.map((file) => ( -
- {file.name} - - {file.status} - -
- ))} -
- )} - -
- - {useManualObjectives && ( -