diff --git a/.claude/skills/vitnode-docs/SKILL.md b/.agents/skills/vitnode-docs/SKILL.md similarity index 100% rename from .claude/skills/vitnode-docs/SKILL.md rename to .agents/skills/vitnode-docs/SKILL.md diff --git a/.claude/skills/vitnode-docs/references/docs-site.md b/.agents/skills/vitnode-docs/references/docs-site.md similarity index 100% rename from .claude/skills/vitnode-docs/references/docs-site.md rename to .agents/skills/vitnode-docs/references/docs-site.md diff --git a/.claude/skills/vitnode-docs/references/seo-review.md b/.agents/skills/vitnode-docs/references/seo-review.md similarity index 100% rename from .claude/skills/vitnode-docs/references/seo-review.md rename to .agents/skills/vitnode-docs/references/seo-review.md diff --git a/.claude/skills/vitnode-upgrade-npm-packages/SKILL.md b/.agents/skills/vitnode-upgrade-npm-packages/SKILL.md similarity index 100% rename from .claude/skills/vitnode-upgrade-npm-packages/SKILL.md rename to .agents/skills/vitnode-upgrade-npm-packages/SKILL.md diff --git a/.claude/skills/performance-profiler b/.claude/skills/performance-profiler deleted file mode 120000 index 7cff7ac131..0000000000 --- a/.claude/skills/performance-profiler +++ /dev/null @@ -1 +0,0 @@ -../../.agents/skills/performance-profiler \ No newline at end of file diff --git a/.claude/skills/react-doctor/SKILL.md b/.claude/skills/react-doctor/SKILL.md deleted file mode 100644 index a6fce60819..0000000000 --- a/.claude/skills/react-doctor/SKILL.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -name: react-doctor -description: Use when finishing a feature, fixing a bug, before committing React code, or when the user types `/doctor`, asks to scan, triage, or clean up React diagnostics. Covers lint, accessibility, bundle size, architecture. Includes a regression check and a full local-triage workflow that fetches the canonical playbook. -version: "1.2.0" ---- - -# React Doctor - -Scans React codebases for security, performance, correctness, and architecture issues. Outputs a 0–100 health score. - -## After making React code changes: - -Run `npx react-doctor@latest --verbose --scope changed` and check the score did not regress. - -If the score dropped, fix the regressions before committing. - -## For general cleanup or code improvement: - -Run `npx react-doctor@latest --verbose` (the default `--scope full`) to scan the full codebase. Fix issues by severity — errors first, then warnings. - -## For a focused UI design audit: - -Run `npx react-doctor@latest design --verbose`. This selects only design-tagged UI composition, typography, interaction, accessibility, and motion rules, including focused rules that remain opt-in during a general health scan. - -## For runtime performance problems: - -Run `npx react-doctor@latest scan --format json` in an interactive terminal. React Doctor opens an isolated system Chrome profile, records a DevTools trace while the user reproduces the slow interaction, and flashes purple outlines with component names as React renders. It stops when they press Enter. Read the structured summary first, then inspect the returned local `.json.gz` trace for CPU, browser, and React component evidence. - -If the user needs their authenticated browser state, use `--cdp `. This requires Chrome to already be running with remote debugging. Never ask for cookies or copy the user's browser profile. Treat the trace as sensitive local application data and never upload it without explicit permission. - -## /doctor — full local triage workflow - -When the user types `/doctor`, says "run react doctor", or asks for a full triage / cleanup pass (not just a regression check), fetch the canonical local-triage playbook and follow every step in it: - -```bash -curl --fail --silent --show-error \ - --header 'Cache-Control: no-cache' \ - https://www.react.doctor/prompts/react-doctor-agent.md -``` - -The playbook is the single source of truth — a scan → filter → triage → fix → validate loop that edits the working tree directly (never commits, never opens PRs). Updating the prompt at its source updates every agent on its next fetch — no skill reinstall needed. - -Pair it with the matching per-rule prompts at `https://www.react.doctor/prompts/rules//.md` (fetched on demand inside the playbook) so each fix uses the canonical, reviewer-tested recipe. - -## Configuring or explaining rules - -When the user wants to understand a rule, disagrees with one, or wants to disable / tune which rules run (not fix code), read [references/explain.md](references/explain.md) and follow it. Start with `npx react-doctor@latest rules explain `, then apply the narrowest control via `npx react-doctor@latest rules disable|set|category|ignore-tag …`, which edits your `doctor.config.*` (or `package.json#reactDoctor`). - -## Command - -```bash -npx react-doctor@latest --verbose --scope changed -``` - -| Flag | Purpose | -| ----------------- | ---------------------------------------------------------------- | -| `.` | Scan current directory | -| `--verbose` | Show affected files and line numbers per rule | -| `--scope changed` | Only report issues introduced vs the base branch (default: full) | -| `--scope lines` | Only report issues on the changed lines | -| `--score` | Output only the numeric score | -| `design` | Run only the focused UI design diagnostics | diff --git a/.claude/skills/react-doctor/references/explain.md b/.claude/skills/react-doctor/references/explain.md deleted file mode 100644 index c3a10089ec..0000000000 --- a/.claude/skills/react-doctor/references/explain.md +++ /dev/null @@ -1,73 +0,0 @@ -# Explaining and configuring rules - -Explain React Doctor rules and edit `doctor.config.*` safely. Use this when a user -wants to understand a rule or change which rules run — not for fixing diagnostics -(that is the main `react-doctor` skill / `/doctor`). - -Triggers: "why did this rule fire", "I disagree with this rule", "turn this rule off", -"stop flagging X", "too noisy", "disable design rules". - -## Workflow - -1. Identify the rule key from the diagnostic (e.g. `react-doctor/no-array-index-as-key`). -2. Explain it before changing anything: - -```bash -npx react-doctor@latest rules explain react-doctor/no-array-index-as-key -``` - -3. Pick the narrowest control that matches the user's intent (see decision guide). -4. Apply it with a `rules` subcommand (edits your `doctor.config.*` or `package.json#reactDoctor` in place, preserving other fields and formatting). -5. Validate the change did what they wanted: - -```bash -npx react-doctor@latest --verbose --diff -``` - -## Commands - -```bash -npx react-doctor@latest rules list # every rule + its effective severity -npx react-doctor@latest rules list --configured # only what your config changed -npx react-doctor@latest rules list --category Performance # filter by category -npx react-doctor@latest rules explain # why it matters + how to configure -npx react-doctor@latest rules disable # rule never runs -npx react-doctor@latest rules enable # turn back on at its recommended severity -npx react-doctor@latest rules set warn # off | warn | error -npx react-doctor@latest rules category "React Native" off # whole category -npx react-doctor@latest rules ignore-tag design # skip a rule family (design, test-noise, …) -npx react-doctor@latest rules unignore-tag design -``` - -Rule references accept the full key (`react-doctor/no-danger`), the bare id (`no-danger`), or a legacy key (`react/no-danger`). - -## Decision guide - -Match the control to the intent — prefer the narrowest one: - -- **User disagrees with one rule / it's a false positive for them** → `rules disable ` (sets `rules. = "off"`; the rule stops running everywhere). This is the default for "I don't want this rule". -- **Rule is fine but wrong severity** → `rules set warn` or `rules set error`. -- **A disabled-by-default rule they want on** → `rules enable `. -- **A whole area is unwanted** (e.g. all React Native rules) → `rules category "" off`. -- **A behavioral family is noisy** (`design`, `test-noise`, `migration-hint`) → `rules ignore-tag `. -- **Keep it locally but hide from PR comment / score / CI gate only** → do NOT disable. Edit `surfaces` in your config (`surfaces.prComment.excludeRules`, `surfaces.score.excludeTags`, `surfaces.ciFailure.excludeCategories`). The rule still shows in local `cli` output. -- **Restore test or story findings to production health** → set `surfaces.score.includeFileContexts` or `surfaces.ciFailure.includeFileContexts` to `["test"]`, `["story"]`, or both. Other surface exclusions still apply. - -How the layers combine: `ignore.tags` disables every rule carrying that tag **before** linting, so a tagged rule stays off even if `rules`/`categories` set it to `warn`/`error` (a rule-level override cannot re-enable a tag-ignored rule). For rules that aren't tag-disabled, `rules` overrides `categories` overrides the rule's default. `surfaces` is visibility-only and never changes whether a rule runs. - -## Config shape - -Config lives in `doctor.config.ts` (or `.js`/`.mjs`/`.cjs`/`.json`/`.jsonc`), or the `reactDoctor` key in `package.json`. The `rules` commands edit whichever exists — TS/JS edits preserve formatting (via magicast) — and create `doctor.config.json` when none does, stamping `$schema`: - -```ts -// doctor.config.ts -export default { - rules: { "react-doctor/no-array-index-as-key": "off" }, - categories: { "React Native": "warn" }, - ignore: { tags: ["design"] }, -}; -``` - -## Educating the user - -When explaining a rule, lead with the "Why it matters" guidance from `rules explain` and, when they want depth, the per-rule recipe at `https://www.react.doctor/prompts/rules//.md`. Only after they understand it should you offer to disable it — many "bad" rules are catching real issues. diff --git a/.github/workflows/build-lint-test.yml b/.github/workflows/build-lint-test.yml index 4aefc80cb1..f9141468a6 100644 --- a/.github/workflows/build-lint-test.yml +++ b/.github/workflows/build-lint-test.yml @@ -83,4 +83,4 @@ jobs: name: packages-dist - name: Run tests - run: pnpm turbo run test test:types --only --continue + run: pnpm turbo run test --only --continue diff --git a/AGENTS.md b/AGENTS.md index b88a0b6cf6..10c2e52a8c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,212 +1,90 @@ -# Overview +# CLAUDE.md -You are VitNode, an expert AI coding assistant. Follow repository conventions and best practices for performance, security, accessibility, UX, and SEO. +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. -Account test with admin permissions: -login: test@test.com -pass: Test123! +VitNode is a plugin-first framework for community apps: TanStack Start front end, Hono API, Postgres (Drizzle) and an AdminCP. This is the 2.0 `canary` branch (PRs target `canary`). pnpm + Turborepo monorepo; Node `^22.22 || ^24.11 || >=26`. -# React / TanStack Start +## Commands -- Arrow functions for components - never `React.FC`. -- No `any`; use `unknown` as rarely as possible. -- Use `AutoForm` for forms instead of hand-built form components. -- Use `React.lazy` + `Suspense` for content-heavy dialogs (e.g. dialogs in forms). -- Pick the editing surface by the size of the settings: - - **Sheet** for short settings - a handful of fields about one thing (an AI action, the AI settings). Scrollable body plus `AutoFormSheetFooter` from `@vitnode/core/components/form/auto-form-sheet-footer`; close the sheet after a successful save. - - **Dialog** for bigger settings - several sections or tabs (a role's settings). Lazy-load the form. - - **Page** for the biggest - a full editor with its own navigation and preview (editing an article). -- After create/edit/delete: refresh the table data and show a `sonner` toast with a description. -- `` hides and restores children's UI and internal state: +```bash +pnpm docker:dev # Postgres (+ services) via docker compose in apps/api +pnpm db:migrate # run pending migrations +pnpm dev # build:scripts (CLI) -> build:plugins -> turbo dev; web on :3000, AdminCP at /admin +pnpm build # full build (plugins first) +pnpm lint # oxlint --type-aware in every package + oxfmt --check +pnpm lint:fix # fix lint + format; run before every commit, never commit lint errors +pnpm test # vitest across packages (incl. integration) +``` -```typescriptreact -import { Activity } from "react"; +- After changing the `vitnode` CLI (`packages/api/scripts/**`) run `pnpm build:scripts`; after changing a plugin or `@vitnode/core` exports consumed by the app, `pnpm build:plugins` (dev does both on start). +- Single test: `cd packages/vitnode && pnpm vitest run --project unit src/path/to/file.test.ts` (projects: `unit`, `isolated`, `dom`, `integration` in `packages/api`). Plugins have a plain `vitest run`. `pnpm test:unit` in a package skips integration tests. +- Migrations: `vitnode db generate` / `vitnode db migrate` (or `pnpm db:prepare` in `apps/api` to generate, apply and seed). Drizzle config lives in `apps/api/drizzle.config.ts`. +- i18n: `pnpm i18n:check | i18n:create | i18n:update | i18n:update:ai` (proxied to `apps/api`). +- Seeded admin account for driving the app locally: `test@test.com` / `Test123!`. - - -; -``` +## Layout and architecture -- Always use skeletons for loading feedback. Use `` only if its necessary. -- Breadcrumbs are optional on every page. Add one with the route's `staticData.breadcrumb` (or a plugin page's `route.breadcrumb`) only when the trail helps; leaving it out adds no crumb, and with no crumbs the breadcrumb bar is not rendered. A crumb that renders strings needs its own `RouteMessages`. -- Route files are topology only - `validateSearch`, `loaderDeps`, `loader`, `head`, `staticData`. The query, the permissions, the namespaces and the screen live in `@vitnode/core/tanstack/*`. -- Write `head` **after** `loader` in the same object literal: `loaderData` is inferred from `loader`, and TypeScript reads members in order. -- Name files `x.server.ts` when they must never reach the browser bundle. -- A package may declare `createIsomorphicFn` but never `createServerFn` - uncompiled on the server, its handler silently resolves to `undefined`. Server functions belong to the host app. -- New admin APIs always require staff permissions. - -### Loading feedback - -Pick one indicator per piece of pending work, by what is pending: - -- **Route navigation → top progress bar.** `NavigationProgress` (`packages/vitnode/src/tanstack/pending/navigation-progress.tsx`) is mounted once by `VitNodeRootProviders` - never render a second one or a page-level spinner for a navigation. It follows the router's lifecycle (`isRouteNavigating` / `useIsRouteNavigating` in `tanstack/pending/navigation-pending.ts`), so redirects, errors, superseded navigations, preloads, `router.invalidate()` and query refetches are already handled; never drive it with timers. -- **Keep the shell and the current page.** The router runs with `defaultPendingMs: Infinity`: header, sidebar and the page being left stay visible and usable until the destination commits. Don't add `pendingMs` to a route to swap it for a skeleton, and don't blank a breadcrumb or layout while navigating. -- **Section loading → a local skeleton.** Lists, profiles, cards, widgets and lazy dialogs whose data is not awaited in the loader get a `` (or `isPending`) fallback shaped like the final content - the shapes in `@vitnode/core/tanstack/pending` (`FeedPendingSkeleton`, `TablePendingSkeleton`, `CardsPendingSkeleton`, `FormPendingSkeleton`, `FormFieldsPendingSkeleton` for a lazy form in a dialog or sheet, `ProfilePendingSkeleton`…) or `Skeleton` from `@vitnode/core/components/ui/skeleton` with the same sizes as the real rows. Scope it to that section; a route's `pendingComponent` is its suspense fallback, not navigation feedback. -- **Refetches keep the data.** Branch on `isPending` (first load), never `isFetching`, for placeholders. Use `placeholderData: keepPreviousData` for queries keyed on search, filters or pages, and mark the stale view with `aria-busy={isFetching}` and at most a dim (`opacity-60`). -- **Actions → the control's own loading state.** Submissions and mutations use ` - - -``` +- `packages/api` → `@vitnode/api`: the backend. Hono API, Drizzle schema (`src/database`), Content Engine server (`src/content`), emails, events, WebSocket/Cloudflare runtime, and the `vitnode` CLI (`scripts/cli`, built with tsdown to `dist/scripts`). +- `packages/vitnode` → `@vitnode/core`: React, AdminCP, TanStack Start integration (`src/tanstack/*`), the Vite plugin, UI components (shadcn on Base UI), editor (Tiptap). +- **Dependency direction is one-way: `@vitnode/core` depends on `@vitnode/api`, never the reverse — not even for types.** Contracts both sides read (content definitions, staff permissions, widget schemas) live in browser-safe `@vitnode/api` subpaths and core imports them directly. +- The built-in plugin keeps the logical id `@vitnode/core` in endpoints, `fetcher({ plugin: "@vitnode/core" })`, permissions, events and DB rows. Never replace it with the package name. +- `packages/*` (others): adapters published as plugins — storage (`s3`, `supabase-storage`), email (`nodemailer`, `resend`), payments (`stripe`), search (`elasticsearch`), cron (`node-cron`); `create-vitnode-app` scaffolder; `config` shared tsconfig/lint. +- `plugins/*`: first-party feature plugins (`blog`, `forum`, `newsroom`, `payments-demo`). `plugins/blog` is the reference shape. +- `apps/web`: the host app (also vitnode.com + docs in `content/docs`, Fumadocs). It mounts the same Hono API at `/api/*`; `apps/api` is the standalone API build of the same config. Deployable to Node or Cloudflare Workers (`build:cloudflare`). -- The icon names the thing that failed (`BellOffIcon`, `MonitorSmartphoneIcon`, `MessageSquareWarningIcon`), not a generic warning. -- Copy is a `title` + `desc` key pair: a short title ("Devices didn't load") and a description that says what to do. Reuse the namespace's `retry` key or `core.global.errors.try_again`. -- The retry button refetches in place - never "refresh the page" - and shows `isLoading` while it runs. Drop it for a `403`, where retrying can't help, and say why in the description. -- Match the surface: `className="border"` (or `rounded-lg border`) on a page or section, no border inside a `Card` or `Sheet` that already frames it, `p-6` in a popover. -- **Refetch failed → keep the data.** A failed background refetch over data already on screen gets an `Alert variant="warning"` with a retry above the content, never an empty state that hides it. -- **One field failed → an inline message.** A form field whose options did not load shows its error inside the field (`role="alert"`), so the rest of the form stays usable. -- Small summary tiles that link to a full page (dashboard widgets, header pills) may keep a one-line message pointing there. - -### Fetching APIs - -- `fetcher` from `@vitnode/core/tanstack/fetcher` is universal - one call, SSR and browser. Never hand-write `createIsomorphicFn().server(...).client(...)` for a fetch. -- A call names the plugin, never an API module: `fetcher({ plugin: "@vitnode/core", method: "get", module: "users", path: "/devices" })`. `plugin`, `module` (any nesting depth, `admin/advanced/cron`), `path`, `method`, `args` and the response are all inferred from the plugin API registry; an invalid combination is a compile error at the offending property. -- The registry is `ApiPluginRegistry` in `@vitnode/api/lib/fetcher/registry` (`@vitnode/core/lib/fetcher/registry` re-exports it). Core registers itself; an app's `src/api-registry.gen.ts` registers every configured plugin that exports `config.api`, with type-only imports; `vitnode build`/`vitnode dev` write a plugin's own entry to its `types/api-registry.gen.d.ts` (kept out of the published package) so its pages can call it. Never import a plugin API factory as a value outside `vitnode.api.config.ts`. -- `@vitnode/core/tanstack/fetcher/server` is for work that is genuinely server-only: server functions, `allowSaveCookies` cookie relay, cron/jobs, upstream secrets or a different `origin`. Same call shape, more options. -- Shared `views/*` query modules call `fetcher` directly - no injected transport, no browser-only twin. `@vitnode/core/lib/fetcher-client` is the framework-neutral browser primitive the universal fetcher is built on, for code that never renders on a server. -- Write the route inline at the call site - never build a request object elsewhere and pass it in. -- Never annotate the result; the fetcher infers it. Put the shared contract on the feature's own `*Fetcher` type instead. -- `args` is required exactly when the route declares a body, params or a query. -- `captchaToken` for captcha-gated routes. -- `rawFetcher` only for generated Content Engine admin modules, which have no type to infer from. It is universal too, with the same server-only twin. A content type's _public_ routes are typed: `module: "content/"`. - -### Caching APIs - -- Client and SSR caching is TanStack Query. Invalidate with `queryClient.invalidateQueries` after a write; warm a route's data in its `loader` with `queryClient.query({ ...options, staleTime: "static" })` (`infiniteQuery` for a feed). `ensureQueryData`, `fetchQuery` and `prefetchQuery` are deprecated - `query` replaces all three. -- Server-side domain caching is the API's own: `c.get("cache")` in a Hono route, Redis-backed when `REDIS_URL` is set and a no-op otherwise. -- Content Engine tag builders live in `content/cache.ts` (`contentPublicListTag` and friends) - pure strings, used to expire a content type's cached reads. -- A background mutation cannot expire a front end's cache by calling a function. `dispatchContentRevalidation` posts to the origins an install opts into via `content.revalidateOrigins`. - -# Packages - -- `@vitnode/api` (`packages/api`) owns the backend: Hono API, database schema, Content Engine server, emails, WebSocket/Cloudflare runtime and the `vitnode` CLI. `@vitnode/core` (`packages/vitnode`) owns React, the AdminCP, TanStack Start and the Vite plugin, and depends on `@vitnode/api` - never the other way round, not even for types. -- Server code imports from `@vitnode/api/...` (`@vitnode/api/lib/plugin`, `@vitnode/api/database/*`, `@vitnode/api/content/server`, `buildApiConfig` from `@vitnode/api/vitnode.config`). Contracts both sides read (content definitions, staff permissions, widget schemas) live in browser-safe `@vitnode/api` subpaths; core imports them directly, not through its own re-export stubs. -- The built-in plugin keeps the logical id `@vitnode/core` in endpoints, `fetcher({ plugin: "@vitnode/core" })`, permissions, events and database rows. Never replace that id with the package name. - -# Coding Guidelines - -- Always implement best practices for performance, security, and accessibility. -- Semantic HTML (`main`, `header`) with correct ARIA roles/attributes, `sr-only` for screen-reader-only text, and alt text on all images unless decorative or repetitive. -- Emit events for important actions (create, update, delete) so other components can react; use events instead of prop drilling or context. Document them in `apps/web/content/docs/dev/events/built-in-events.mdx`. -- APIs return i18n keys, never translated text, for anything the UI shows (titles, descriptions, labels a plugin registers). The web translates them with `use-intl`, so the text follows the UI's language and the cached response works in every language. Translate on the server only for output with no UI, such as emails. -- AI features use the Vercel AI SDK only - resolve models via the `c.get("ai")` registry and call native SDK functions. - -# Design - -- New pages and components need good UX and a modern, clean UI. Design mobile-first, then enhance for larger screens. -- Update `layout.tsx` metadata (title, description) and viewport (theme-color, userScalable) for SEO. -- Exactly 3–5 colors total. Never use purple or violet prominently. -- If you override a background color, you MUST override its text color for contrast. -- Prefer semantic design tokens (`bg-background`, `text-foreground`). -- Every action button gets a `lucide-react` icon before its label (`aria-hidden`) - Save, Delete, Reply, Share, Try again, Sign in, submit buttons and confirm buttons in dialogs. The only exception is Cancel (and other dismiss buttons that just close something). -- Text links underline on hover (`underline-offset-4 hover:underline`), never just a color change. Links styled as buttons (`buttonVariants`) are the exception. -- Use the Tailwind spacing scale (`p-4`, `mx-2`) - never arbitrary values (`p-[16px]`). -- Use `gap-*` classes for spacing. Never use `space-*`, and never mix margin/padding with gap on the same element. -- Use semantic (`items-center`, `justify-between`) and responsive (`md:grid-cols-2`) classes. -- No floats or absolute positioning unless absolutely necessary. -- Body text: `leading-relaxed` (1.4–1.6), never below 14px, never decorative fonts. -- Wrap titles and important copy in `text-balance` or `text-pretty`. - -# Documentation - -- Document every new feature. Keep it simple, SEO-friendly, and understandable at any skill level. -- Friendly and lightly funny tone - don't overdo it. -- Skip big comments; code is self-documenting. -- Docs call the VitNode API with `fetcher` (`rawFetcher` for generated Content Engine admin routes), never raw `fetch` or a browser-console snippet. A check that needs a request with no UI yet uses a small temporary component with a button. -- Never end a page with a "Next step" (or "Next", "What's next") section; the sidebar and page footer link the following page. Use `## Related` for links worth following. -- Developer-facing APIs in feature code (exports of `@vitnode/core` and plugins that app or plugin authors call) need concise English JSDoc on the original declaration: - - Say what it is for, plus constraints, side effects, runtime (server-only, browser-only or universal) and `@throws` only when they are real and non-obvious. - - Document configuration properties one by one, including non-obvious defaults and constraints. - - Give major entry points a minimal `@example` with real imports. - - A behavior change updates the JSDoc in the same change. Keep tutorials in the MDX docs. -- Request images with a comment: `// Image prompt: {here_prompt_to_generate_image}` -- Put install commands in tabbed code blocks with correct syntax highlighting: - -````markdown -import { Tab, Tabs } from "fumadocs-ui/components/tabs"; - - - -```bash tab="bun" -bun i x -``` +### Plugins: two halves, one manifest -```bash tab="pnpm" -pnpm i x -``` +Every plugin exports a frontend half (`src/config.tsx` → `buildPlugin` from `@vitnode/core/lib/plugin`) and an API half (`src/config.api.ts` → `buildApiPlugin` from `@vitnode/api/lib/plugin`), both reading the same generated `manifest.gen.ts`. The host registers them in `apps/web/src/vitnode.config.ts` (`buildConfig`) and `vitnode.api.config.ts` (`buildApiConfig`). API code is organised as modules (`buildModule({ name, routes })`) with route files under `api/modules//routes`. AdminCP nav and content forms are discovered from the package's `admin/nav` and `admin/content` exports, not passed in config. -```bash tab="npm" -npm i x -``` +`vitnode dev`/`vitnode build` scan all configured plugins once (the "plugin surface") and write the app's `*.gen.ts` registries (`api-registry.gen.ts`, `plugin-routes.gen.ts`, `content-modules.gen.ts`, `routeTree.gen.ts`, …) and each plugin's `types/api-registry.gen.d.ts`. **Never hand-edit `*.gen.ts`** — change the source and regenerate. Never import a plugin API factory as a value outside `vitnode.api.config.ts`. + +### Domain vocabulary + +- **Staff** = root role holder, or anyone with an admin/moderator permission entry (even with zero permissions). Only **admins** get an **AdminCP session**; moderators act from the public site with their user session. A user has one primary and any number of secondary roles, all counted. +- **Session kinds**: user session vs AdminCP session, each with its own storage, cookie and cache. Sessions are bound to a **device** cookie; revoking a device ends every session on it. An **admin module** is an API module whose every route requires an AdminCP session. New admin APIs always require staff permissions. +- **Content Engine**: plugin-defined **content types** (fields, localization, editorial settings). Editorial types have drafts/versions/revisions. An entry has **shared fields** plus per-locale **translations**; a **save** is one transactional write; **commit effects** (events, search indexing, revalidation) run after the transaction ends. Tag builders live in `content/cache.ts`; `dispatchContentRevalidation` notifies origins listed in `content.revalidateOrigins`. +- **Route messages**: a named set of ≤16 translation namespaces (dotted paths like `admin.staff`) declared once per route. + +## Conventions + +### Front end (TanStack Start) - -```` +- Route files are topology only: `validateSearch`, `loaderDeps`, `loader`, `head`, `staticData`. Queries, permissions, namespaces and screens live in `@vitnode/core/tanstack/*`. Write `head` **after** `loader` so `loaderData` infers. +- `x.server.ts` for code that must never reach the browser bundle. A package may use `createIsomorphicFn` but never `createServerFn` (its handler silently resolves to `undefined` when uncompiled) — server functions belong to the host app. +- Arrow-function components, no `React.FC`, no `any`. Forms use `AutoForm`. Editing surface by size: **Sheet** (few fields, `AutoFormSheetFooter`, close on save) → **Dialog** (sections/tabs, lazy-load the form with `React.lazy` + `Suspense`) → **Page** (full editor). After create/edit/delete: refresh the data and show a `sonner` toast with a description. +- Breadcrumbs are opt-in via `staticData.breadcrumb` (plugin pages: `route.breadcrumb`); a crumb rendering strings needs its own `RouteMessages`. +- APIs return i18n keys, never translated text, for anything the UI shows (`use-intl` translates on the client). Translate server-side only for UI-less output like emails. +- Emit events for create/update/delete and document them in `apps/web/content/docs/dev/events/built-in-events.mdx`. +- AI features use the Vercel AI SDK only, with models resolved from the `c.get("ai")` registry. -# Testing +### Fetching and caching -- Never write unit tests in the same session. Spawn a new session, and write the test after the feature is working. Tests are for regression, not for development. -- UI component tests (`*.test.tsx`) should test DOM output, click events, and dialogs. Never test CSS classes, inline styles that only decorate, or form UI (`AutoForm`, form fields). -- Always run "pnpm lint:fix" to fix formatting and linting issues before committing. Never commit a file with lint errors. +- `fetcher` from `@vitnode/core/tanstack/fetcher` is universal (SSR + browser) — never hand-roll `createIsomorphicFn().server().client()` for a fetch. Calls name the plugin: `fetcher({ plugin: "@vitnode/core", method: "get", module: "users", path: "/devices" })`; plugin/module/path/method/args/response are all inferred from `ApiPluginRegistry` (`@vitnode/api/lib/fetcher/registry`) and invalid combinations are compile errors. Write the route inline at the call site; never annotate the result; `args` is required exactly when the route has a body/params/query; `captchaToken` for captcha-gated routes. +- `@vitnode/core/tanstack/fetcher/server` only for genuinely server-only work (server functions, cookie relay, cron, secrets, another origin). `rawFetcher` only for generated Content Engine admin modules; content types' public routes are typed as `module: "content/"`. +- Client/SSR caching is TanStack Query: invalidate with `queryClient.invalidateQueries`; warm loaders with `queryClient.query({ ...options, staleTime: "static" })` (`infiniteQuery` for feeds). `ensureQueryData`/`fetchQuery`/`prefetchQuery` are deprecated. Server-side cache is `c.get("cache")` (Redis when `REDIS_URL` is set, otherwise a no-op). -### What not to test +### Loading and error states -- An existing feature applied somewhere new. Building the widgets system earns tests; adding widget zones or widgets to another page or plugin does not, because the mechanism is already covered and only the wiring is new. The same goes for a route that only calls a tested helper, or a boot step that only calls a tested validator. -- Database models or schema definitions (Drizzle tables, column types, indexes, foreign keys, RLS), or the SQL text Drizzle generates. -- Static config, constants, color presets, plugin configuration (`config.api`, content type definitions), query-key literals, namespace lists, TanStack Query option values (`retry`, `staleTime`) and route `staticData`. -- Third-party libraries or trivial helper/wrapper code. A shadcn or Base UI wrapper does not earn a test for what Base UI already does (stepping a `NumberField`, a `Tooltip` delay, a `Progress` aria value). -- Source text. No `readFileSync` + `toContain`/`toMatch` on a module, no "this file still exists" or "this identifier is gone" checks - test behaviour. Import-graph checks that keep server or editor code out of a bundle are fine. -- Translated copy or the contents of a locale JSON - `use-intl` renders keys in tests, so assert on the key. -- The test's own fixtures. +- Navigation feedback is only the top `NavigationProgress` mounted by `VitNodeRootProviders`; the router runs `defaultPendingMs: Infinity`, so never add `pendingMs`, page spinners, or timer-driven progress. A route's `pendingComponent` is a suspense fallback, not navigation feedback. +- Sections loading data get a local skeleton shaped like the result (`@vitnode/core/tanstack/pending`: `FeedPendingSkeleton`, `TablePendingSkeleton`, `FormFieldsPendingSkeleton`, …, or `Skeleton`). Prefer skeletons over ``. Branch on `isPending`, never `isFetching`; use `placeholderData: keepPreviousData` for search/filter/page-keyed queries with `aria-busy={isFetching}`. +- Actions use `