From 3a1960d860faf27cca9eecba38d5d17852be4da6 Mon Sep 17 00:00:00 2001 From: Michael-A-Sloan Date: Sun, 2 Aug 2026 16:12:17 -0400 Subject: [PATCH] Initial commit --- .cursor/rules/accessibility.mdc | 17 ++ .cursor/rules/ai-agent-specialist.mdc | 47 ++++ .cursor/rules/anti-overengineering.mdc | 12 + .cursor/rules/anti-sycophancy.mdc | 38 +++ .cursor/rules/api-rest-design.mdc | 18 ++ .cursor/rules/clean-code.mdc | 56 ++++ .cursor/rules/code-review-checklist.mdc | 18 ++ .cursor/rules/code-style-consistency.mdc | 173 ++++++++++++ .cursor/rules/conventional-commits.mdc | 28 ++ .cursor/rules/cursor-rules-pack-v2.mdc | 34 +++ .cursor/rules/cypress-e2e.mdc | 76 ++++++ .cursor/rules/database.mdc | 86 ++++++ .cursor/rules/devsecops-appsec.mdc | 46 ++++ .cursor/rules/docker-devops.mdc | 16 ++ .cursor/rules/documentation.mdc | 15 ++ .cursor/rules/dry-solid-principles.mdc | 24 ++ .cursor/rules/error-handling.mdc | 17 ++ .cursor/rules/fastapi-production.mdc | 209 +++++++++++++++ .cursor/rules/fastapi.mdc | 86 ++++++ .cursor/rules/general-coding-standards.mdc | 17 ++ .cursor/rules/gherkin-bdd.mdc | 108 ++++++++ .cursor/rules/go.mdc | 42 +++ .cursor/rules/graphql-apollo.mdc | 46 ++++ .cursor/rules/jest-unit-testing.mdc | 128 +++++++++ .cursor/rules/js-ts-code-quality.mdc | 59 ++++ .cursor/rules/landing-page-images.mdc | 35 +++ .cursor/rules/nestjs-anti-hallucination.mdc | 253 ++++++++++++++++++ .cursor/rules/nextjs-tanstack-query.mdc | 102 +++++++ .cursor/rules/nextjs15-supabase-security.mdc | 137 ++++++++++ .cursor/rules/performance.mdc | 16 ++ .cursor/rules/playwright-e2e.mdc | 94 +++++++ .cursor/rules/postgresql.mdc | 44 +++ .cursor/rules/pr-review.mdc | 81 ++++++ .../rules/python-fastapi-best-practices.mdc | 21 ++ .cursor/rules/python-standards.mdc | 18 ++ .cursor/rules/react-native-expo.mdc | 43 +++ .cursor/rules/react-router-v7.mdc | 52 ++++ .cursor/rules/react-zustand.mdc | 115 ++++++++ .cursor/rules/readme-best-practices.mdc | 16 ++ .cursor/rules/rtl-i18n.mdc | 67 +++++ .cursor/rules/rust.mdc | 85 ++++++ .cursor/rules/security-basics.mdc | 17 ++ .cursor/rules/sql-database.mdc | 17 ++ .cursor/rules/sveltekit-typescript.mdc | 36 +++ .cursor/rules/tanstack-query-v5.mdc | 209 +++++++++++++++ .cursor/rules/testing-standards.mdc | 17 ++ .cursor/rules/typescript-strict.mdc | 18 ++ .cursor/rules/vercel-deployment.mdc | 115 ++++++++ .cursor/rules/vitest-unit-testing.mdc | 146 ++++++++++ .gitignore | 41 +++ GITEA-SSH-ON-UNRAID.md | 184 +++++++++++++ 51 files changed, 3395 insertions(+) create mode 100644 .cursor/rules/accessibility.mdc create mode 100644 .cursor/rules/ai-agent-specialist.mdc create mode 100644 .cursor/rules/anti-overengineering.mdc create mode 100644 .cursor/rules/anti-sycophancy.mdc create mode 100644 .cursor/rules/api-rest-design.mdc create mode 100644 .cursor/rules/clean-code.mdc create mode 100644 .cursor/rules/code-review-checklist.mdc create mode 100644 .cursor/rules/code-style-consistency.mdc create mode 100644 .cursor/rules/conventional-commits.mdc create mode 100644 .cursor/rules/cursor-rules-pack-v2.mdc create mode 100644 .cursor/rules/cypress-e2e.mdc create mode 100644 .cursor/rules/database.mdc create mode 100644 .cursor/rules/devsecops-appsec.mdc create mode 100644 .cursor/rules/docker-devops.mdc create mode 100644 .cursor/rules/documentation.mdc create mode 100644 .cursor/rules/dry-solid-principles.mdc create mode 100644 .cursor/rules/error-handling.mdc create mode 100644 .cursor/rules/fastapi-production.mdc create mode 100644 .cursor/rules/fastapi.mdc create mode 100644 .cursor/rules/general-coding-standards.mdc create mode 100644 .cursor/rules/gherkin-bdd.mdc create mode 100644 .cursor/rules/go.mdc create mode 100644 .cursor/rules/graphql-apollo.mdc create mode 100644 .cursor/rules/jest-unit-testing.mdc create mode 100644 .cursor/rules/js-ts-code-quality.mdc create mode 100644 .cursor/rules/landing-page-images.mdc create mode 100644 .cursor/rules/nestjs-anti-hallucination.mdc create mode 100644 .cursor/rules/nextjs-tanstack-query.mdc create mode 100644 .cursor/rules/nextjs15-supabase-security.mdc create mode 100644 .cursor/rules/performance.mdc create mode 100644 .cursor/rules/playwright-e2e.mdc create mode 100644 .cursor/rules/postgresql.mdc create mode 100644 .cursor/rules/pr-review.mdc create mode 100644 .cursor/rules/python-fastapi-best-practices.mdc create mode 100644 .cursor/rules/python-standards.mdc create mode 100644 .cursor/rules/react-native-expo.mdc create mode 100644 .cursor/rules/react-router-v7.mdc create mode 100644 .cursor/rules/react-zustand.mdc create mode 100644 .cursor/rules/readme-best-practices.mdc create mode 100644 .cursor/rules/rtl-i18n.mdc create mode 100644 .cursor/rules/rust.mdc create mode 100644 .cursor/rules/security-basics.mdc create mode 100644 .cursor/rules/sql-database.mdc create mode 100644 .cursor/rules/sveltekit-typescript.mdc create mode 100644 .cursor/rules/tanstack-query-v5.mdc create mode 100644 .cursor/rules/testing-standards.mdc create mode 100644 .cursor/rules/typescript-strict.mdc create mode 100644 .cursor/rules/vercel-deployment.mdc create mode 100644 .cursor/rules/vitest-unit-testing.mdc create mode 100644 .gitignore create mode 100644 GITEA-SSH-ON-UNRAID.md diff --git a/.cursor/rules/accessibility.mdc b/.cursor/rules/accessibility.mdc new file mode 100644 index 0000000..fe69f5e --- /dev/null +++ b/.cursor/rules/accessibility.mdc @@ -0,0 +1,17 @@ +--- +description: Web accessibility (a11y) — WCAG 2.1 AA patterns +globs: **/*.{tsx,jsx,vue,svelte,html} +alwaysApply: false +--- + +# Accessibility (a11y) + +- Use semantic HTML: ` + ) +} +``` + +## TypeScript +- Define explicit state and action interfaces for shared stores. +- Avoid `any`; use `unknown` plus narrowing for external data. +- Type action payloads and return values, including async actions. +- Prefer discriminated unions for complex local status instead of several loosely related booleans. +- Export store state types when tests, utilities, or vanilla store factories need them. + +## Updates and Middleware +- Use functional `set((state) => nextState)` when the next value depends on current state. +- Treat nested state immutably; install and use `immer` middleware only when it materially simplifies nested updates. +- Use `persist` only for state that must survive reloads. +- Use `partialize`, `version`, and `migrate` when persisting anything beyond trivial preferences. +- Never persist secrets, access tokens, refresh tokens, raw PII, or long-lived authorization state to browser storage. +- Use `devtools` in development for complex flows and give important actions clear names. +- Use `subscribeWithSelector` for non-React subscriptions that need fine-grained updates. + +## Async Actions +- Async store actions may coordinate client-only workflows, optimistic drafts, or local device APIs. +- Keep HTTP fetching in the project's server-state layer unless the state is explicitly client-owned. +- Represent async client workflows with explicit statuses such as `idle`, `pending`, `success`, and `error`. +- Reset error state deliberately when retrying or closing a workflow. + +## SSR and React Server Components +- Do not read or mutate browser-only stores from React Server Components. +- In SSR frameworks, create per-request vanilla stores when state must be initialized on the server. +- Guard persisted stores against hydration mismatches before rendering storage-backed values. +- Keep store modules free of direct `window`, `document`, and storage access outside middleware configuration. + +## Testing +- Test store actions directly without rendering React when possible. +- Reset stores between tests with their initial state. +- Assert selectors and actions separately from component behavior. +- Mock server-state libraries instead of routing fetched data through Zustand for tests. + +## Anti-Patterns +- Do not create one global store for the entire application. +- Do not put form input state in Zustand unless multiple distant components edit the same draft. +- Do not mutate nested objects directly without Immer middleware. +- Do not use Zustand as an event bus; prefer explicit callbacks, services, or a scoped store. +- Do not introduce Redux-style reducers, action constants, or dispatch wrappers unless the project already uses that pattern. diff --git a/.cursor/rules/readme-best-practices.mdc b/.cursor/rules/readme-best-practices.mdc new file mode 100644 index 0000000..c456897 --- /dev/null +++ b/.cursor/rules/readme-best-practices.mdc @@ -0,0 +1,16 @@ +--- +description: "Cursor rules for README documentation with best practices integration." +globs: **/* +alwaysApply: false +--- +Write READMEs like landing pages, not API docs. The reader decides in 3-5 seconds. + +Start with a bold one-liner saying what it does and why someone should care. Not "A tool that..." - a punchline. +Put a working code example in the first 5 lines. Show the value prop immediately. +Use feature tables (two columns) instead of **Feature:** bullet lists. Tables scan faster. +Quick Start must be copy-paste ready. No $ prefix on bash commands. Zero to running in 30 seconds. +Vary sentence lengths and structure. Mix one-liners with short paragraphs and tables. Not walls of same-length bullets. +Never use "seamless", "robust", "comprehensive", "cutting-edge", or other AI marketing words. +Never open with "In today's..." or close with "Happy coding!" +Check that referenced assets (demo.gif, screenshots) actually exist on disk before adding image links. +Author section should include a visual card or badge, not just plain text "Made by username". diff --git a/.cursor/rules/rtl-i18n.mdc b/.cursor/rules/rtl-i18n.mdc new file mode 100644 index 0000000..250b4c5 --- /dev/null +++ b/.cursor/rules/rtl-i18n.mdc @@ -0,0 +1,67 @@ +--- +description: "Cursor rules for RTL development with logical CSS properties, Tailwind logical classes, bidirectional text, and automated auditing via rtlify-ai." +globs: **/* +alwaysApply: false +--- +# RTL (Right-to-Left) Development Rules + +You are an expert in building applications that support RTL (Right-to-Left) languages including Hebrew, Arabic, Persian, and Urdu. + +## Core Rules + +### 1. Logical CSS Properties +Always use CSS logical properties instead of physical ones: +- `margin-inline-start` not `margin-left` +- `padding-inline-end` not `padding-right` +- `inset-inline-start` not `left` +- `border-inline-start` not `border-left` + +### 2. Tailwind CSS Logical Classes +Use logical Tailwind utilities: +- `ms-4` not `ml-4` (margin-start) +- `me-4` not `mr-4` (margin-end) +- `ps-4` not `pl-4` (padding-start) +- `pe-4` not `pr-4` (padding-end) +- `start-0` not `left-0` +- `end-0` not `right-0` + +### 3. React Native Logical Properties +Use logical properties in React Native styles: +- `paddingStart` not `paddingLeft` +- `paddingEnd` not `paddingRight` +- `marginStart` not `marginLeft` +- `marginEnd` not `marginRight` + +### 4. Bidirectional Text Safety +Wrap mixed-script text with `` tags: +```html +

User {userName} posted a comment

+``` + +### 5. Directional Icons +Flip directional icons (arrows, chevrons, back buttons) in RTL mode. +Non-directional icons (home, settings, search) should NOT be flipped. + +### 6. Internationalization +- Never hardcode strings — use translation functions (`t()`, `intl.formatMessage()`) +- Use `Intl.NumberFormat` for numbers and currency +- Use `Intl.DateTimeFormat` for dates +- Set `dir="auto"` or `dir="rtl"` on root elements + +### 7. RTL-Aware Components +- Carousels, sliders, and progress bars must reverse direction in RTL +- Swipe gestures must reverse in RTL +- Charts and graphs with directional axes must flip + +### 8. Testing +- Always test with `dir="rtl"` on the root element +- Verify with actual RTL content, not just flipped LTR + +## Automated RTL Auditing + +For automated RTL violation detection and fixing, use [rtlify-ai](https://github.com/idanlevi1/rtlify): +```bash +npx rtlify-ai init # Install RTL rules +npx rtlify-ai check # Find violations +npx rtlify-ai fix # Auto-fix violations +``` diff --git a/.cursor/rules/rust.mdc b/.cursor/rules/rust.mdc new file mode 100644 index 0000000..cb9144c --- /dev/null +++ b/.cursor/rules/rust.mdc @@ -0,0 +1,85 @@ +--- +description: "Rust best practices for Solana smart contract development using Anchor framework and Solana SDK" +globs: programs/**/*.rs, src/**/*.rs, tests/**/*.ts +alwaysApply: false +--- +# Rust + Solana (Anchor) Best Practices + +## Program Structure +- Structure Solana programs using `Anchor` framework standards +- Place program entrypoint logic in `lib.rs`, not `main.rs` +- Organize handlers into modules (e.g., `initialize`, `update`, `close`) +- Separate state definitions, errors, instructions, and utils +- Group reusable logic under a `utils` module (e.g., account validation) +- Use `declare_id!()` to define program ID + +## Anchor Framework +- Use `#[derive(Accounts)]` for all instruction contexts +- Validate accounts strictly using constraint macros (e.g., `#[account(mut)]`, `seeds`, `bump]`) +- Define all state structs with `#[account]` and `#[derive(AnchorSerialize, AnchorDeserialize)]` +- Prefer `Init`, `Close`, `Realloc`, `Mut`, and constraint macros to avoid manual deserialization +- Use `ctx.accounts` to access validated context accounts +- Handle CPI (Cross-Program Invocation) calls via Anchor’s CPI helpers + +## Serialization +- Use **Borsh** or Anchor's custom serializer (not Serde) for on-chain data +- Always include `#[account(zero_copy)]` or `#[repr(C)]` for packed structures +- Avoid floating point types — use `u64`, `u128`, or fixed-point math +- Zero out or close unused accounts to reduce rent costs + +## Testing +- Write tests in TypeScript using Anchor’s Mocha + Chai setup (`tests/*.ts`) +- Use `anchor.workspace.MyProgram` to load deployed contracts +- Use `provider.simulate()` to inspect failed txs +- Spin up a local validator (`anchor test`) and reset between tests +- Airdrop SOL to wallets with `provider.connection.requestAirdrop(...)` +- Validate program logs using `tx.confirmation.logMessages` + +## Solana SDK (Manual) +- Use `solana_program` crate when not using Anchor (bare-metal programs) +- Carefully deserialize accounts using `AccountInfo`, `try_from_slice_unchecked` +- Use `solana_program::msg!` for lightweight debugging logs +- Verify accounts via `is_signer`, `is_writable`, `key == expected` +- Never panic! Use `ProgramError::Custom(u32)` or `ErrorCode` enums + +## Security Patterns +- Always validate `msg.sender`/signer with `account_info.is_signer` +- Prevent replay attacks via `seeds`, `bump`, and unique PDAs +- Use strict size checks before reallocating or deserializing +- Avoid unsafe unchecked casting; prefer Anchor deserialization +- For CPIs, validate `target_program` against expected program ID +- When using randomness, never rely on timestamps — use oracles or off-chain VRFs + +## Performance +- Prefer zero-copy deserialization when accounts are large +- Minimize compute usage; avoid loops and recursion +- Avoid memory reallocations mid-instruction +- Use `#[account(zero_copy)]` and `#[repr(packed)]` for tight layout +- Profile compute units with `solana logs` and `anchor run` + +## Dev Workflow +- Use `anchor init` to scaffold projects +- Add Anchor IDL support for front-end usage (JSON ABI) +- Use `anchor build`, `anchor deploy`, `anchor test` consistently +- Use separate `Anchor.toml` environments for devnet/mainnet/localnet +- Format all Rust code with `cargo fmt`, lint with `cargo clippy` +- Keep `Cargo.lock` checked into `programs/` but not root + +## Documentation +- Use `///` Rust doc comments for all instructions and accounts +- Include doc examples for each instruction +- Document PDA derivation logic and bump seed expectations +- Maintain up-to-date `README.md` with test commands and deployment steps + +## Wallet & Network Handling +- Use `anchorProvider.wallet.publicKey` for signer verification in tests +- Do not hardcode keypairs — use env-based loading (`process.env.ANCHOR_WALLET`) +- Deploy with clear `cluster` targets (`localnet`, `devnet`, `mainnet`) +- Use `anchor keys sync` to propagate program ID changes +- Commit `target/idl/` and `target/types/` to share with front end + +## CI/CD & Deploy +- Use GitHub Actions with `solana-cli`, `anchor-cli`, and `node` installed +- Run `anchor test` in CI for every PR +- Use `solana program deploy` with explicit `--program-id` on production deploys +- Upload IDLs to a central registry (e.g., GitHub, IPFS, or `anchor.cloud`) diff --git a/.cursor/rules/security-basics.mdc b/.cursor/rules/security-basics.mdc new file mode 100644 index 0000000..a48659e --- /dev/null +++ b/.cursor/rules/security-basics.mdc @@ -0,0 +1,17 @@ +--- +description: Security basics — secrets, auth, injection, and safe defaults +alwaysApply: true +--- + +# Security Basics + +- Never commit secrets, API keys, tokens, or passwords. Use environment variables. +- Never log passwords, tokens, session IDs, or full credit card numbers. +- Parameterize all database queries. Never concatenate user input into SQL. +- Escape or sanitize user-generated content before rendering in HTML. +- Validate and whitelist file uploads: type, size, and storage path. +- Use HTTPS for all external API calls in production code paths. +- Apply least-privilege: services and DB users get only the permissions they need. +- Check authorization on every mutating endpoint — authentication alone is not enough. +- Set secure cookie flags (`HttpOnly`, `Secure`, `SameSite`) for session cookies. +- Do not disable TLS certificate verification in production code. diff --git a/.cursor/rules/sql-database.mdc b/.cursor/rules/sql-database.mdc new file mode 100644 index 0000000..02d8be1 --- /dev/null +++ b/.cursor/rules/sql-database.mdc @@ -0,0 +1,17 @@ +--- +description: SQL and database safety — queries, migrations, and indexes +globs: **/*.{sql,prisma},**/migrations/**/* +alwaysApply: false +--- + +# SQL & Database + +- Always use parameterized queries or an ORM. Never interpolate user input into SQL strings. +- Migrations must be reversible or include a documented rollback path. +- Add indexes for columns used in `WHERE`, `JOIN`, and `ORDER BY` on large tables. +- Avoid `SELECT *` in application code — select only needed columns. +- Use transactions for multi-step writes that must succeed or fail together. +- Set `statement_timeout` on long-running queries in production. +- Never store plaintext passwords. Use bcrypt, Argon2id, or scrypt. +- Soft-delete vs hard-delete: follow the project's existing pattern consistently. +- Name constraints and indexes explicitly for easier debugging in production. diff --git a/.cursor/rules/sveltekit-typescript.mdc b/.cursor/rules/sveltekit-typescript.mdc new file mode 100644 index 0000000..3cceaa6 --- /dev/null +++ b/.cursor/rules/sveltekit-typescript.mdc @@ -0,0 +1,36 @@ +--- +description: "Cursor rules for SvelteKit development with TypeScript integration." +globs: **/* +alwaysApply: false +--- +You are an expert in Svelte 5, SvelteKit, TypeScript, Supabase, Drizzle and modern web development. + +Key Principles + +Code Style and Structure +Naming Conventions +TypeScript Usage +Svelte Runes +UI and Styling +Shadcn Color Conventions +SvelteKit Project Structure +Component Development +State Management + +Use classes for complex state management (state machines): +```typescript +// counter.svelte.ts +class Counter { + count = $state(0); + incrementor = $state(1); + increment() { + this.count += this.incrementor; + } + resetCount() { + this.count = 0; + } + resetIncrementor() { + this.incrementor = 1; + } +} +export const counter = new Counter(); diff --git a/.cursor/rules/tanstack-query-v5.mdc b/.cursor/rules/tanstack-query-v5.mdc new file mode 100644 index 0000000..224e067 --- /dev/null +++ b/.cursor/rules/tanstack-query-v5.mdc @@ -0,0 +1,209 @@ +--- +description: "Cursor rules for TanStack Query v5 with query options, query key factories, mutations, optimistic updates, infinite queries, Suspense, and prefetching." +globs: **/* +alwaysApply: false +--- +You are an expert in TanStack Query v5 (formerly React Query), TypeScript, and async state management for React applications. + +# TanStack Query v5 Guidelines + +## Core Philosophy +- TanStack Query manages server state — it is NOT a general state manager for client-only state +- Every query should have a stable, serializable query key that uniquely describes the data +- Mutations handle writes; queries handle reads — never blur this boundary +- Prefer `queryOptions()` helper for reusable, co-located query definitions +- v5 breaking changes: `useQuery` no longer accepts positional args; always use the options object form + +## Setup +```tsx +// main.tsx +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { ReactQueryDevtools } from '@tanstack/react-query-devtools' + +const queryClient = new QueryClient({ + defaultOptions: { + queries: { + staleTime: 1000 * 60, // 1 minute default stale time + retry: 2, + refetchOnWindowFocus: true, + }, + }, +}) + +function App() { + return ( + + + + + ) +} +``` + +## Query Keys +- Always structure keys as arrays: `['entity', 'list']`, `['entity', 'detail', id]` +- Use a query key factory to avoid typos and enable easy invalidation +```ts +// queryKeys.ts +export const postKeys = { + all: ['posts'] as const, + lists: () => [...postKeys.all, 'list'] as const, + list: (filters: PostFilters) => [...postKeys.lists(), filters] as const, + details: () => [...postKeys.all, 'detail'] as const, + detail: (id: string) => [...postKeys.details(), id] as const, +} +``` + +## queryOptions Helper (v5) +- Use `queryOptions()` to define queries once and reuse across components and loaders +```ts +import { queryOptions } from '@tanstack/react-query' + +export const postQueryOptions = (id: string) => + queryOptions({ + queryKey: postKeys.detail(id), + queryFn: () => fetchPost(id), + staleTime: 1000 * 60 * 5, // 5 min + }) + +// In component +const { data } = useQuery(postQueryOptions(postId)) + +// In router loader (TanStack Router integration) +loader: ({ params, context: { queryClient } }) => + queryClient.ensureQueryData(postQueryOptions(params.postId)) +``` + +## useQuery +```tsx +const { + data, + isLoading, // true only on first load with no cached data + isFetching, // true whenever a fetch is in-flight + isError, + error, + isSuccess, +} = useQuery({ + queryKey: postKeys.detail(postId), + queryFn: () => fetchPost(postId), + enabled: !!postId, // disable query if params not ready +}) +``` + +## useMutation +```tsx +const { mutate, mutateAsync, isPending } = useMutation({ + mutationFn: (newPost: CreatePostInput) => createPost(newPost), + onSuccess: (data) => { + // Invalidate and refetch + queryClient.invalidateQueries({ queryKey: postKeys.lists() }) + toast.success('Post created!') + }, + onError: (error) => { + toast.error(error.message) + }, +}) + +// Usage +mutate({ title: 'Hello', body: '...' }) +``` + +## Optimistic Updates +```tsx +const queryClient = useQueryClient() + +const mutation = useMutation({ + mutationFn: updatePost, + onMutate: async (updatedPost) => { + await queryClient.cancelQueries({ queryKey: postKeys.detail(updatedPost.id) }) + const previous = queryClient.getQueryData(postKeys.detail(updatedPost.id)) + queryClient.setQueryData(postKeys.detail(updatedPost.id), updatedPost) + return { previous } + }, + onError: (err, updatedPost, context) => { + queryClient.setQueryData(postKeys.detail(updatedPost.id), context?.previous) + }, + onSettled: (_, __, updatedPost) => { + queryClient.invalidateQueries({ queryKey: postKeys.detail(updatedPost.id) }) + }, +}) +``` + +## Infinite Queries +```tsx +const { + data, + fetchNextPage, + hasNextPage, + isFetchingNextPage, +} = useInfiniteQuery({ + queryKey: postKeys.lists(), + queryFn: ({ pageParam }) => fetchPosts({ cursor: pageParam }), + initialPageParam: undefined as string | undefined, + getNextPageParam: (lastPage) => lastPage.nextCursor, +}) + +// data.pages is an array of page results — flatten for rendering +const allPosts = data?.pages.flatMap((page) => page.items) ?? [] +``` + +## Prefetching +- Prefetch on hover or during routing to eliminate loading states +```ts +// Hover prefetch +const handleMouseEnter = () => { + queryClient.prefetchQuery(postQueryOptions(postId)) +} + +// In router loader (eliminates all loading spinners) +export const Route = createFileRoute('/posts/$postId')({ + loader: ({ context: { queryClient }, params }) => + queryClient.ensureQueryData(postQueryOptions(params.postId)), +}) +``` + +## Cache Invalidation Patterns +```ts +// Invalidate all post queries +queryClient.invalidateQueries({ queryKey: postKeys.all }) + +// Invalidate only post lists +queryClient.invalidateQueries({ queryKey: postKeys.lists() }) + +// Remove from cache entirely +queryClient.removeQueries({ queryKey: postKeys.detail(id) }) + +// Directly update cache without refetch +queryClient.setQueryData(postKeys.detail(id), newData) +``` + +## Suspense Mode +- Use `useSuspenseQuery` for Suspense-based data fetching (v5) +- Wrap with `}>` +- Pair with `` for error handling +```tsx +// No need to handle isLoading — Suspense handles it +const { data } = useSuspenseQuery(postQueryOptions(postId)) +``` + +## Performance Best Practices +- Set appropriate `staleTime` per query — defaults to `0` (always stale) +- Use `select` to transform/subscribe to only relevant slices of data +- Use `placeholderData: keepPreviousData` for pagination to avoid layout shifts +- Avoid creating `QueryClient` inside components — instantiate once at app root +- Use `notifyOnChangeProps` to limit re-renders to only relevant data changes + +## Error Handling +- Use `throwOnError: true` to bubble errors to the nearest ErrorBoundary +- Use `retry` function for conditional retry logic (e.g., skip retry on 404) +```ts +retry: (failureCount, error) => { + if (error.status === 404) return false + return failureCount < 3 +}, +``` + +## TypeScript Tips +- Always type `queryFn` return value explicitly or infer from typed API functions +- Use `QueryObserverResult` to type hook return values +- Use `UseMutationResult` for mutations diff --git a/.cursor/rules/testing-standards.mdc b/.cursor/rules/testing-standards.mdc new file mode 100644 index 0000000..d52eb28 --- /dev/null +++ b/.cursor/rules/testing-standards.mdc @@ -0,0 +1,17 @@ +--- +description: Testing standards — structure, naming, and what to cover +globs: **/*.{test,spec}.{ts,tsx,js,jsx,py} +alwaysApply: false +--- + +# Testing Standards + +- Test behavior, not implementation details. Assert outputs and side effects users care about. +- Follow Arrange–Act–Assert (or Given–When–Then) structure. +- One assertion concept per test. Name tests: `should when `. +- Cover happy path, edge cases, and at least one failure case per feature. +- Mock external services (APIs, DB, email) — never call real third parties in unit tests. +- Do not test framework internals or trivial getters with no logic. +- Keep tests independent: no shared mutable state between tests. +- Prefer factory helpers or fixtures over copy-pasted setup blocks. +- Flaky tests are bugs — fix or delete them, do not `@skip` without a tracked issue. diff --git a/.cursor/rules/typescript-strict.mdc b/.cursor/rules/typescript-strict.mdc new file mode 100644 index 0000000..9803687 --- /dev/null +++ b/.cursor/rules/typescript-strict.mdc @@ -0,0 +1,18 @@ +--- +description: TypeScript strict patterns — types, null safety, and async +globs: **/*.{ts,tsx} +alwaysApply: false +--- + +# TypeScript Standards + +- Enable and respect `strict` mode. Avoid `any`; use `unknown` and narrow with type guards. +- Prefer `interface` for object shapes; use `type` for unions, intersections, and utilities. +- Handle `null` and `undefined` explicitly. Use optional chaining and nullish coalescing. +- Prefer `const` and `readonly` where mutation is not required. +- Use discriminated unions instead of boolean flag combinations. +- Async functions must have try/catch or propagate errors intentionally. +- Export types alongside public APIs. Do not leak internal types in public signatures. +- Use `satisfies` to validate object literals while preserving inferred types. +- Prefer `import type` for type-only imports. +- Name generic type parameters meaningfully (`TData`, `TError`), not single letters when ambiguous. diff --git a/.cursor/rules/vercel-deployment.mdc b/.cursor/rules/vercel-deployment.mdc new file mode 100644 index 0000000..a6eeddf --- /dev/null +++ b/.cursor/rules/vercel-deployment.mdc @@ -0,0 +1,115 @@ +--- +description: "Cursor rules for Vercel deployment including serverless functions, Edge Runtime, middleware, caching, CI/CD, and production-ready configuration." +globs: **/* +alwaysApply: false +--- +You are an expert in Vercel deployments, serverless architecture, and modern web application hosting. + +# Vercel Deployment Guidelines + +## Core Principles +- Always optimize for Vercel's edge network and serverless model +- Prefer Edge Runtime for globally distributed, low-latency responses +- Use Vercel's built-in environment variable management for secrets +- Structure projects to leverage Vercel's zero-config deployment detection +- Always use `vercel.json` for advanced routing, headers, and redirects configuration + +## Project Structure +- Place API routes in `/api` directory for automatic serverless function detection (Pages Router) or `/app/api` for App Router +- Use `public/` for static assets that should be served via Vercel's CDN +- Keep serverless functions small and focused — cold start time matters +- Separate long-running tasks to background jobs or external queues (Vercel has a 10s default timeout on Hobby, 60s on Pro) + +## Environment Variables +- Never hard-code secrets; always use `process.env.VARIABLE_NAME` +- Prefix client-side env vars with `NEXT_PUBLIC_` (Next.js) or expose explicitly per framework +- Use Vercel's Environment Variable UI or CLI (`vercel env add`) to manage per-environment values (Development, Preview, Production) +- Use `.env.local` for local development; never commit it +- Reference `vercel.json` `env` field only for build-time non-secret values + +## vercel.json Configuration +- Use `rewrites` for proxying API calls or SPA fallback routing +- Use `redirects` for permanent (308) or temporary (307) URL changes +- Use `headers` to set security headers (CSP, HSTS, X-Frame-Options) globally +- Use `regions` to pin serverless functions to specific regions when data locality matters +- Example security headers block: + ```json + { + "headers": [ + { + "source": "/(.*)", + "headers": [ + { "key": "X-Content-Type-Options", "value": "nosniff" }, + { "key": "X-Frame-Options", "value": "DENY" }, + { "key": "X-XSS-Protection", "value": "1; mode=block" }, + { "key": "Referrer-Policy", "value": "strict-origin-when-cross-origin" } + ] + } + ] + } + ``` + +## Serverless Functions +- Keep dependencies minimal — bundle size directly impacts cold starts +- Use Edge Functions (`export const runtime = 'edge'`) for auth checks, redirects, and A/B testing +- Use Node.js runtime for database connections, heavy computation, or Node-only packages +- Always handle errors gracefully and return proper HTTP status codes +- Use streaming responses for LLM or large data outputs + +## Edge Middleware +- Place middleware in `middleware.ts` at the project root +- Use middleware for: authentication guards, geo-based redirects, bot protection, and A/B flags +- Keep middleware lightweight — it runs on every request before the cache +- Use `matcher` config to scope middleware only to needed routes + ```ts + export const config = { + matcher: ['/dashboard/:path*', '/api/:path*'], + } + ``` + +## Performance & Caching +- Use `Cache-Control` headers to control Vercel's CDN caching behavior +- Use `stale-while-revalidate` for ISR-like behavior in non-Next.js apps +- Set `s-maxage` for CDN cache TTL and `max-age` for browser cache +- Avoid over-fetching in serverless functions — reuse DB connections with connection pooling (PgBouncer, Prisma Accelerate) +- Use `vercel/og` for dynamic OG image generation at the edge + +## CI/CD & Preview Deployments +- Use Vercel's GitHub/GitLab/Bitbucket integration for automatic preview deployments per PR +- Use `vercel pull` + `vercel build` + `vercel deploy --prebuilt` in custom CI pipelines +- Set branch protection rules to require passing preview deployment checks +- Use `VERCEL_ENV` environment variable to differentiate behavior across preview/production + +## Domain & DNS +- Use Vercel Domains or point external DNS to Vercel's nameservers for automatic SSL +- Always redirect `www` to apex or vice versa — never serve both +- Use `vercel domains add` CLI command for custom domain management + +## Monorepo Support +- Set `rootDirectory` in project settings to point to the correct app within a monorepo +- Use Turborepo with Vercel Remote Cache for fast CI builds (`turbo build --filter=...`) +- Scope environment variables per project even in shared monorepos + +## Databases & Storage +- Prefer Vercel-native storage (Vercel KV, Vercel Postgres, Vercel Blob) for zero-config integration +- For external databases, always use connection pooling — serverless functions do not maintain persistent connections +- Store large files in Vercel Blob or S3-compatible storage, not in the function bundle + +## Logging & Observability +- Use `console.log` / `console.error` — Vercel captures these as function logs +- Integrate with Vercel Log Drains to stream logs to Datadog, Sentry, or other observability tools +- Use Vercel Speed Insights and Web Analytics for real-user performance monitoring +- Set up alerts on error rate spikes via Vercel's integrations marketplace + +## Security Best Practices +- Enable Vercel's DDoS protection (included on all plans) +- Use Vercel Firewall rules to block malicious IPs and patterns +- Rotate secrets regularly using Vercel's environment variable versioning +- Never log sensitive data (tokens, passwords, PII) in serverless function output +- Use `VERCEL_OIDC_TOKEN` for secure machine-to-machine auth between Vercel and cloud providers + +## Deployment Workflow +- Run `vercel --prod` only from protected branches (main/master) +- Use `vercel deploy` (without `--prod`) for staging/preview deployments +- Alias stable preview URLs with `vercel alias` for QA sign-off +- Use deployment protection (password or Vercel Access) on preview deployments for private projects diff --git a/.cursor/rules/vitest-unit-testing.mdc b/.cursor/rules/vitest-unit-testing.mdc new file mode 100644 index 0000000..c0c4878 --- /dev/null +++ b/.cursor/rules/vitest-unit-testing.mdc @@ -0,0 +1,146 @@ +--- +description: "Cursor rules for Vitest development with unit testing." +globs: **/* +alwaysApply: false +--- +# Persona + +You are an expert developer with deep knowledge of Vitest and TypeScript, tasked with creating unit tests for JavaScript/TypeScript applications. + +# Auto-detect TypeScript Usage + +Check for TypeScript in the project through tsconfig.json or package.json dependencies. +Adjust syntax based on this detection. + +# Unit Testing Focus + +Create unit tests that focus on critical functionality (business logic, utility functions) +Mock dependencies (API calls, external modules) before imports using vi.mock +Test various data scenarios (valid inputs, invalid inputs, edge cases) +Write maintainable tests with descriptive names grouped in describe blocks + +# Best Practices + +**1** **Critical Functionality**: Prioritize testing business logic and utility functions +**2** **Dependency Mocking**: Always mock dependencies before imports with vi.mock() +**3** **Data Scenarios**: Test valid inputs, invalid inputs, and edge cases +**4** **Descriptive Naming**: Use clear test names indicating expected behavior +**5** **Test Organization**: Group related tests in describe/context blocks +**6** **Project Patterns**: Match team's testing conventions and patterns +**7** **Edge Cases**: Include tests for undefined values, type mismatches, and unexpected inputs +**8** **Test Quantity**: Limit to 3-5 focused tests per file for maintainability + +# Example Unit Test + +```js +import { describe, it, expect, beforeEach } from 'vitest'; +import { vi } from 'vitest'; + +// Mock dependencies before imports +vi.mock('../api/locale', () => ({ + getLocale: vi.fn(() => 'en-US'), // Mock locale API +})); + +// Import module under test +const { formatDate } = await import('../utils/formatDate'); + +describe('formatDate', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('should format date correctly', () => { + // Arrange + const date = new Date('2023-10-15'); + + // Act + const result = formatDate(date); + + // Assert + expect(result).toBe('2023-10-15'); + }); + + it('should handle invalid date', () => { + const result = formatDate(new Date('invalid')); + expect(result).toBe('Invalid Date'); + }); + + it('should throw error for undefined input', () => { + expect(() => formatDate(undefined)).toThrow('Input must be a Date object'); + }); + + it('should handle non-Date object', () => { + expect(() => formatDate('2023-10-15')).toThrow('Input must be a Date object'); + }); +}); +``` + +# TypeScript Example + +```ts +import { describe, it, expect, beforeEach } from 'vitest'; +import { vi } from 'vitest'; + +// Mock dependencies before imports +vi.mock('../api/weatherService', () => ({ + getWeatherData: vi.fn(), +})); + +// Import the mocked module and the function to test +import { getWeatherData } from '../api/weatherService'; +import { getForecast } from '../utils/forecastUtils'; + +// Define TypeScript interfaces +interface WeatherData { + temperature: number; + humidity: number; + conditions: string; +} + +interface Forecast { + prediction: string; + severity: 'low' | 'medium' | 'high'; +} + +describe('getForecast', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('should return forecast when weather data is available', async () => { + // Arrange + const mockWeather: WeatherData = { + temperature: 25, + humidity: 65, + conditions: 'sunny' + }; + (getWeatherData as any).mockResolvedValue(mockWeather); + + // Act + const result = await getForecast('New York'); + + // Assert + expect(getWeatherData).toHaveBeenCalledWith('New York'); + expect(result).toEqual({ + prediction: 'Clear skies', + severity: 'low' + }); + }); + + it('should handle missing data fields', async () => { + // Arrange: Weather data with missing fields + const incompleteData = { temperature: 25 }; + (getWeatherData as any).mockResolvedValue(incompleteData); + + // Act & Assert + await expect(getForecast('London')).rejects.toThrow('Incomplete weather data'); + }); + + it('should handle API errors gracefully', async () => { + // Arrange: API failure + (getWeatherData as any).mockRejectedValue(new Error('Service unavailable')); + + // Act & Assert + await expect(getForecast('Tokyo')).rejects.toThrow('Failed to get forecast: Service unavailable'); + }); +}); diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4090514 --- /dev/null +++ b/.gitignore @@ -0,0 +1,41 @@ +# Secrets — never commit +.env +.env.local +.env.*.local + +# Dependencies +node_modules/ + +# Build output +dist/ +build/ +.next/ +out/ +.vercel/ + +# Logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +pnpm-debug.log* + +# OS +.DS_Store +Thumbs.db + +# IDE (project-specific; .cursor/ is tracked intentionally) +.idea/ +.vscode/ +*.swp +*.swo + +# Test / coverage +coverage/ +.nyc_output/ + +# Python +__pycache__/ +*.py[cod] +.venv/ +venv/ diff --git a/GITEA-SSH-ON-UNRAID.md b/GITEA-SSH-ON-UNRAID.md new file mode 100644 index 0000000..4ba00f9 --- /dev/null +++ b/GITEA-SSH-ON-UNRAID.md @@ -0,0 +1,184 @@ +# Gitea SSH on Unraid (reusable) + +Use this for **any** repo on your Gitea (`git.masengr.com`) from the Unraid host — photo site, qBittorrent configs, etc. + +## Why this setup + +| Problem | Cause | Fix | +|--------|--------|-----| +| HTTPS keeps asking for a password | 2FA → need a PAT, not account password | Prefer SSH | +| `ssh git.masengr.com` asks for password on port 22 | Port **22** is Unraid’s SSH, not Gitea | Use Gitea’s mapped port | +| `git.masengr.com:2222` → connection refused | Public DNS/SWAG doesn’t expose 2222 | From Unraid, use `127.0.0.1` + Gitea SSH port | + +Your Gitea container typically publishes SSH like: + +```text +0.0.0.0:2222->22/tcp +``` + +Confirm anytime: + +```bash +docker ps --format 'table {{.Names}}\t{{.Ports}}' | grep -i gitea +``` + +Use whatever **host** port maps to container `22` (often `2222`). + +--- + +## One-time: create a user SSH key (all your repos) + +On Unraid: + +```bash +ssh-keygen -t ed25519 -C "unraid-gitea" -f ~/.ssh/gitea_unraid -N "" +cat ~/.ssh/gitea_unraid.pub +``` + +In Gitea (web UI): + +1. Avatar → **Settings → SSH / GPG Keys → Add Key** +2. Title: `unraid-gitea` +3. Paste the **entire** `.pub` line (`ssh-ed25519 AAAA... unraid-gitea`) +4. Save + +Use a **user** SSH key (works for every repo your user can access). +Use a **Deploy Key** only when you want one repo, read-only. + +--- + +## One-time: SSH config on Unraid + +Point the hostname at **local** Gitea SSH (same machine): + +```bash +mkdir -p ~/.ssh + +cat > ~/.ssh/config <<'EOF' +Host git.masengr.com + HostName 127.0.0.1 + User git + Port 2222 + IdentityFile ~/.ssh/gitea_unraid + IdentitiesOnly yes +EOF + +chmod 700 ~/.ssh +chmod 600 ~/.ssh/config ~/.ssh/gitea_unraid +chmod 644 ~/.ssh/gitea_unraid.pub +``` + +If `docker ps` shows a different host port than `2222`, change `Port` to match. + +### Test (success looks like this) + +```bash +ssh -T git@git.masengr.com +``` + +Expected: + +```text +Hi there, YOUR_USERNAME! You've successfully authenticated with the key named gitea_unraid, but Gitea does not provide shell access. +``` + +- **No password prompt** = good +- Post-quantum / `known_hosts` warnings can be ignored if auth succeeds +- If you see `Connection refused` on `git.masengr.com:2222` without this config, you were hitting the public IP — keep `HostName 127.0.0.1` + +--- + +## Per repo: use an SSH remote + +```bash +cd /path/to/clone + +git remote set-url origin git@git.masengr.com:YOUR_NAMESPACE/YOUR_REPO.git +git remote -v +git pull +``` + +Examples: + +```bash +git@git.masengr.com:Michael-A-Sloan/Neon-Photos_Site.git +git@git.masengr.com:Michael-A-Sloan/qBittorrent-Enhanced-Edition-docker-with-vpn.git +``` + +Clone fresh with SSH: + +```bash +cd /mnt/user/appdata +git clone git@git.masengr.com:Michael-A-Sloan/SOME_REPO.git some-folder +``` + +--- + +## Day-to-day + +```bash +cd /path/to/repo +git pull +# then whatever that project uses, e.g.: +# sh scripts/deploy.sh +``` + +No PAT prompt for git over SSH. + +--- + +## Troubleshooting + +### Still asks for password + +```bash +ssh -vT git@git.masengr.com 2>&1 | grep -iE 'Offering public key|Authentications that can continue|Authenticated|Connection' +``` + +Check: + +1. Pubkey is on **user** SSH keys in Gitea (exact match to `cat ~/.ssh/gitea_unraid.pub`) +2. `Port` matches `docker ps` host mapping +3. `HostName` is `127.0.0.1` (or `192.168.10.3`) when running **on** Unraid +4. Remote is SSH, not HTTPS: `git remote -v` should show `git@git.masengr.com:...` + +### Connection refused + +- Wrong port, or `HostName` is the public DNS without 2222 forwarded +- On Unraid → use `127.0.0.1` + correct `Port` + +### Remake the key + +```bash +rm -f ~/.ssh/gitea_unraid ~/.ssh/gitea_unraid.pub +# Delete old key in Gitea UI, then redo "create key" + paste .pub steps above +``` + +### HTTPS PAT (only if you must avoid SSH) + +```bash +git config --global credential.helper store +# git pull once; username = Gitea user; password = PAT (not account password) +chmod 600 /root/.git-credentials +``` + +SSH is preferred on Unraid for this Gitea. + +--- + +## What not to do + +- Don’t put a Gitea PAT in app `.env` or Docker template variables +- Don’t use Unraid host port **22** for Gitea if Unraid already owns SSH there +- Don’t expect `git.masengr.com:2222` from the internet unless you intentionally port-forward it + +--- + +## Quick checklist (new machine / new Unraid flash) + +1. [ ] `ssh-keygen` → `~/.ssh/gitea_unraid` +2. [ ] Paste `.pub` into Gitea user SSH keys +3. [ ] `~/.ssh/config` with `HostName 127.0.0.1`, `Port 2222` (or your map) +4. [ ] `ssh -T git@git.masengr.com` greets you +5. [ ] `git remote set-url origin git@git.masengr.com:USER/REPO.git` +6. [ ] `git pull` with no password