Skip to content

Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.

docs: describe the TypeScript codebase everywhere

spacesdrive7aba61262c8f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9c2a1a6..bf3d28a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -32,6 +32,14 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
### Changed
+**TypeScript**
+- The backend Worker, the React app, the scheduled publisher script and every test are now TypeScript in strict mode, with no change in behaviour: each file, with its types removed, matches the JavaScript it replaced
+- API request and response shapes live once in `shared/types/` and are used by both the Worker routes and `services/api.ts`
+- `npm run typecheck` checks the whole repository; the deploy workflows type-check and test before deploying, and a new CI workflow checks every pull request and branch
+- Running the tests or the publisher locally needs Node 22.18 or newer; the GitHub Actions publisher runs on Node 24
+- The publisher log no longer prints emoji
+
+
**Interface redesign in the Twiligent brand**
- New app shell: 256px sidebar with the Twiligent lockup, search, grouped navigation, account and category lists, and a user menu with theme and sign-out; a 50px top bar with breadcrumb, refresh and theme toggle
- Every page rebuilt on shared components and design tokens: Sora headings, Manrope text, JetBrains Mono numbers, brand red for primary actions and active states, warm dusk and paper surfaces, hairline borders
diff --git a/DECISIONS.md b/DECISIONS.md
index 2ec545c..2989205 100644
--- a/DECISIONS.md
+++ b/DECISIONS.md
@@ -229,7 +229,7 @@ Records every significant architectural decision, the alternatives considered, a
## ADR-010: No TypeScript in any layer
**Date:** 2024 (initial)
-**Status:** Accepted
+**Status:** Superseded by ADR-030 (2026-10-14)
**Decision:** The entire project is plain JavaScript and JSX. No TypeScript, no JSDoc type annotations, no type checking step.
@@ -624,3 +624,20 @@ Records every significant architectural decision, the alternatives considered, a
- Without Redis the limits are per isolate, which is looser than a global count. Rate limiting is still on, not off.
- The Lua scripts and the TypeScript functions must change together. Bucket levels are rounded to a millionth so the two agree exactly; they were checked against each other in a Lua VM on 110,000 random requests.
- Behind a shared IP (an office or a carrier NAT), many users share the `ip` rule. Its limit is high for that reason, and IPv6 is keyed per /64.
+
+---
+
+## ADR-030: TypeScript in strict mode, type-stripped at build and test time, with shared API types
+
+**Date:** 2026-10-14
+**Status:** Accepted
+
+**Decision:** The Worker, the React app, the scheduled publisher, the tests and a new `shared/types/` folder are TypeScript in `strict` mode. Nothing is compiled ahead of time: Wrangler and Vite strip types while bundling, and Node (22.18 or newer) strips them when it runs the tests and `scripts/publish-scheduled.ts`. `npm run typecheck` runs `tsc --noEmit` for every project and gates every deploy and pull request in CI. The shared compiler settings (`tsconfig.base.json`) allow only erasable syntax (`erasableSyntaxOnly`), require `import type` for types (`verbatimModuleSyntax`) and keep `.ts` extensions in relative imports, so Node can run any file directly. `shared/types/` holds the API contract (accounts, posts, analytics, request and response shapes) as types only; the backend uses it to check every response with `satisfies`, and `frontend/src/services/api.ts` returns those types. The tooling is TypeScript 6.0, `typescript-eslint`, `@types/node` and `@cloudflare/workers-types`, all development dependencies.
+
+**Context:** The codebase had grown to about 430 files with API shapes restated by hand on both sides, and several bugs only showed up at runtime. The conversion was done file by file with a rule of no runtime change, checked mechanically: every converted file, with its types stripped by esbuild, had to match the original JavaScript on `main`. Only six files differ, each intentionally. The checker surfaced real defects (an endpoint returning account secrets, missing credential checks, dead code), which were filed as separate issues instead of being fixed inside the migration.
+
+**Trade-offs:**
+- TypeScript 7 (the native compiler) is out, but `typescript-eslint` only supports TypeScript below 6.1, so the project stays on 6.0 until that changes.
+- Type stripping means no enums, namespaces or parameter properties, and type-only imports must be marked. The compiler enforces all three.
+- Node 22.18 is now the minimum for running tests and the publisher locally, and the GitHub Actions publisher moved from Node 20 to 24.
+- Some boundaries (external API JSON, test fakes) are typed by a single cast at the point where data enters, which the type checker trusts.
diff --git a/README.md b/README.md
index 72341fc..991fb43 100644
--- a/README.md
+++ b/README.md
@@ -7,6 +7,7 @@
<p><strong>A self-hosted analytics and publishing dashboard for YouTube and Instagram.<br/>Your data. Your infrastructure. No subscriptions.</strong></p>
<p>
+ <a href="https://www.typescriptlang.org"><img src="https://img.shields.io/badge/TypeScript-strict-3178C6?style=flat-square&logo=typescript&logoColor=white" alt="TypeScript strict" /></a>
<a href="https://react.dev"><img src="https://img.shields.io/badge/React-19-61DAFB?style=flat-square&logo=react&logoColor=black" alt="React 19" /></a>
<a href="https://vitejs.dev"><img src="https://img.shields.io/badge/Vite-7-646CFF?style=flat-square&logo=vite&logoColor=white" alt="Vite 7" /></a>
<a href="https://tailwindcss.com"><img src="https://img.shields.io/badge/Tailwind_CSS-v4-06B6D4?style=flat-square&logo=tailwindcss&logoColor=white" alt="Tailwind CSS v4" /></a>
@@ -155,7 +156,7 @@ The full documentation, including a step-by-step self-hosting guide that explain
| Requirement | Notes |
|---|---|
-| Node.js 22 or later | Required by the dev tooling (Vite 7, concurrently); the deploy workflows use Node 24 |
+| Node.js 22.18 or later | Node runs the TypeScript tests and the scheduled publisher directly by stripping types, which needs 22.18 or newer (the `engines` field in `package.json`); the GitHub workflows use Node 24 |
| Wrangler CLI | Installed by `npm install` at the root; run `npx wrangler login` once |
| Cloudflare account | Free tier sufficient for Workers and Pages |
| Supabase project | Free tier sufficient; create at [supabase.com](https://supabase.com) |
@@ -260,16 +261,19 @@ Run every command from the repository root.
| `npm install` | Installs both workspaces and the shared tooling |
| `npm run dev` | Starts the Worker (`wrangler dev`, port 8787) and Vite (port 5173) together |
| `npm run dev:backend` / `npm run dev:frontend` | Starts one of them |
+| `npm run typecheck` | Type-checks every TypeScript project: backend, backend tests, frontend, frontend tooling and tests, scripts |
| `npm run build` | Builds the frontend into `frontend/dist/` |
-| `npm test` | Runs the backend tests, then the frontend tests (Node's built-in test runner) |
+| `npm test` | Runs the backend tests, then the frontend tests (Node's built-in test runner on `tests/**/*.test.ts`) |
| `npm run lint` | Runs ESLint over the whole repository with the shared `eslint.config.mjs` |
| `npm run format` | Applies Prettier (`.prettierrc.json`) to the whole repository |
Add a dependency to the app that uses it: `npm install <package> --workspace backend` or `npm install <package> --workspace frontend`. Only shared development tooling goes in the root `package.json`.
-Tests live outside the source folders, in `backend/tests/` and `frontend/tests/`, and mirror the source tree: the test for `backend/services/youtube.js` is `backend/tests/services/youtube.test.js`, and the test for `frontend/src/lib/accounts.js` is `frontend/tests/lib/accounts.test.js`. Backend fixtures and golden snapshots are in `backend/tests/fixtures/`.
+The whole project is TypeScript in `strict` mode. Nothing is compiled ahead of time: Wrangler and Vite strip the types while bundling, and Node strips them when it runs the tests and `scripts/publish-scheduled.ts`. None of them checks types, so run `npm run typecheck` before you commit; CI runs it on every pull request and before every deploy. The API request and response types live once in `shared/types/` and are used by both the backend and the frontend. See `docs/guidelines/TYPESCRIPT.md`.
-ESLint, Prettier and EditorConfig are configured once at the root. The existing code has not been reformatted in bulk, so run `npm run format` only when you mean to reformat.
+Tests live outside the source folders, in `backend/tests/` and `frontend/tests/`, and mirror the source tree: the test for `backend/services/youtube.ts` is `backend/tests/services/youtube.test.ts`, and the test for `frontend/src/lib/accounts.ts` is `frontend/tests/lib/accounts.test.ts`. Backend fixtures and golden snapshots are in `backend/tests/fixtures/`.
+
+ESLint (with `typescript-eslint`), Prettier and EditorConfig are configured once at the root, and the shared compiler settings are in `tsconfig.base.json`. The existing code has not been reformatted in bulk, so run `npm run format` only when you mean to reformat.
---
@@ -427,38 +431,52 @@ flowchart TD
twiligent/
├── .github/
│ └── workflows/
-│ ├── deploy-backend.yml # Wrangler deploy on backend or root lockfile changes
-│ ├── deploy-frontend.yml # Cloudflare Pages deploy on frontend or root lockfile changes
-│ └── publish-scheduled.yml # Scheduled post fallback (every 15 minutes)
+│ ├── ci.yml # Type check, lint, test, build and Worker dry-run on pull requests and branches
+│ ├── deploy-backend.yml # Type check, test, then Wrangler deploy on backend, shared or root config changes
+│ ├── deploy-frontend.yml # Type check, test, then Cloudflare Pages deploy on frontend, shared or root config changes
+│ └── publish-scheduled.yml # Scheduled post fallback (every 15 minutes, Node 24)
│
├── backend/
│ ├── lib/
-│ │ ├── db.js # All Supabase query functions (single source)
-│ │ ├── cache.js # Redis cache helpers (silent fail on error)
-│ │ ├── redis.js # Upstash Redis client factory
-│ │ └── supabase.js # Supabase client factory
+│ │ ├── db.ts # All Supabase query functions (single source)
+│ │ ├── cache.ts # Redis cache helpers (silent fail on error)
+│ │ ├── redis.ts # Upstash Redis client factory
+│ │ ├── safeAccount.ts # Strips tokens and cookies from accounts in responses
+│ │ ├── rateLimit/ # Rate limit rules, algorithms and Lua scripts
+│ │ └── supabase.ts # Supabase client factory
│ ├── middleware/
-│ │ └── auth.js # requireAuth: JWT verification, sets userId
+│ │ ├── auth.ts # requireAuth: JWT verification, sets userId
+│ │ └── rateLimit.ts # Per-IP and per-user rate limits
│ ├── routes/
-│ │ ├── accounts.js # Add, remove, and refresh accounts
-│ │ ├── analytics.js # YouTube and Instagram analytics
-│ │ ├── publishing.js # Instagram Graph API publish flow
-│ │ ├── scheduledPosts.js # CRUD for scheduled post queue
-│ │ ├── instagramAuth.js # Instagram OAuth flow
-│ │ ├── settings.js # User settings (GitHub repository for setup links)
-│ │ └── keys.js # API key presence check
+│ │ ├── accounts.ts # Add, remove, and refresh accounts
+│ │ ├── analytics.ts # YouTube and Instagram analytics
+│ │ ├── publishing.ts # Instagram Graph API publish flow
+│ │ ├── scheduledPosts.ts # CRUD for scheduled post queue
+│ │ ├── instagramAuth.ts # Instagram OAuth flow
+│ │ ├── settings.ts # User settings (GitHub repository for setup links)
+│ │ └── keys.ts # API key presence check
│ ├── services/
-│ │ ├── youtube.js # YouTube Data API v3 client
-│ │ └── instagram.js # Instagram Graph API client
-│ ├── tests/ # Node tests mirroring lib/, routes/, services/, utils/; fixtures/ holds fakes and golden snapshots
-│ ├── server.js # Hono app + Worker export (fetch + scheduled)
-│ ├── wrangler.toml # Cloudflare Worker config and cron triggers
-│ └── package.json # Backend workspace: hono, supabase-js, upstash redis, wrangler
+│ │ ├── youtube.ts # YouTube Data API v3 client
+│ │ └── instagram.ts # Instagram Graph API client
+│ ├── types/
+│ │ ├── env.ts # Env: Worker secrets and bindings
+│ │ └── app.ts # AppEnv, AppContext: Hono context typing
+│ ├── tests/ # Node tests (*.test.ts) mirroring lib/, middleware/, routes/, services/, utils/; fixtures/ holds fakes and golden snapshots
+│ ├── server.ts # Hono app + Worker export (fetch + scheduled)
+│ ├── wrangler.toml # Cloudflare Worker config (main = "server.ts") and cron triggers
+│ ├── tsconfig.json # Worker type check (Workers types, no DOM or Node)
+│ └── package.json # Backend workspace: hono, supabase-js, upstash redis, wrangler, workers-types
│
├── frontend/
-│ ├── tests/ # Node tests mirroring src/ (lib, utils, features, docs)
+│ ├── tests/ # Node tests (*.test.ts) mirroring src/ (lib, utils, features, docs)
+│ ├── index.html # Loads /src/main.tsx
+│ ├── vite.config.ts # Vite config: React and Tailwind plugins, @ alias
+│ ├── tsconfig.json # Type check for src/ (DOM, JSX, @/ and @shared/ paths)
+│ ├── tsconfig.node.json # Type check for vite.config.ts and tests/
│ ├── package.json # Frontend workspace: React, Vite, Tailwind, shadcn
│ └── src/
+│ ├── main.tsx # Entry point
+│ ├── App.tsx # Router and provider tree
│ ├── features/
│ │ ├── analytics/
│ │ │ ├── overview/ # Unified cross-platform dashboard
@@ -471,19 +489,24 @@ twiligent/
│ │ ├── publishing/ # Single and bulk upload with scheduler
│ │ └── settings/ # Theme, server status, setup guides
│ ├── context/
-│ │ └── AppContext.jsx # Global accounts and loading state
+│ │ └── AppContext.tsx # Global accounts and loading state
│ ├── layout/
-│ │ ├── Sidebar.jsx # Collapsible navigation sidebar
-│ │ └── Header.jsx # Breadcrumbs, refresh, theme toggle
+│ │ ├── Sidebar.tsx # Collapsible navigation sidebar
+│ │ └── Header.tsx # Breadcrumbs, refresh, theme toggle
│ ├── components/ui/ # shadcn/ui components and custom primitives
│ └── services/
-│ └── api.js # Frontend API client (all fetch calls)
+│ └── api.ts # Frontend API client (all fetch calls)
+│
+├── shared/
+│ └── types/ # API contract shared by backend and frontend (types only)
│
├── scripts/
-│ └── publish-scheduled.js # Node.js script run by GitHub Actions fallback (no dependencies)
+│ ├── publish-scheduled.ts # TypeScript run directly by Node in the GitHub Actions fallback (no dependencies)
+│ └── tsconfig.json # Type check for scripts/ (Node types)
│
-├── package.json # npm workspaces root: scripts and shared dev tooling
+├── package.json # npm workspaces root: scripts, shared dev tooling, engines (Node 22.18+)
├── package-lock.json # The only lockfile, for both workspaces
+├── tsconfig.base.json # Shared strict compiler settings
├── eslint.config.mjs # Shared ESLint config
├── .prettierrc.json # Shared Prettier config
└── .editorconfig # Shared editor defaults
@@ -493,6 +516,14 @@ twiligent/
## Tech Stack
+**Language and tooling**
+
+| Tool | Version | Purpose |
+|---|---|---|
+| TypeScript | 6.0 | Strict type checking across the backend, frontend, shared types, scripts and tests |
+| typescript-eslint | 8 | TypeScript lint rules |
+| Node.js | 22.18 or later | Runs the tests and the scheduled publisher by stripping types |
+
**Frontend**
| Library | Version | Purpose |
@@ -515,6 +546,7 @@ twiligent/
| @supabase/supabase-js | 2 | Supabase client for database and auth |
| @upstash/redis | 1 | Edge-compatible Redis client for caching |
| Wrangler | 3 | Cloudflare Workers CLI (dev and deploy) |
+| @cloudflare/workers-types | 5 | Types for the Workers runtime |
**Infrastructure**
@@ -527,7 +559,7 @@ twiligent/
| YouTube Data API v3 | Channel and video analytics |
| Instagram Graph API v25 | Account analytics and content publishing |
| Cloudinary | Media CDN (Instagram requires public URLs) |
-| GitHub Actions | Fallback cron publisher and deployment CI/CD |
+| GitHub Actions | Fallback cron publisher, pull request checks and deployment CI/CD |
---
@@ -560,7 +592,7 @@ Contributions are welcome. Every change starts with a GitHub issue: search the [
git checkout -b feature/your-feature-name
```
-3. Make your changes, check them from the repository root with `npm run build`, `npm test` and `npm run lint`, and commit
+3. Make your changes, check them from the repository root with `npm run typecheck`, `npm run build`, `npm test` and `npm run lint`, and commit
```bash
git commit -m "feat: add your feature description"
diff --git a/ROADMAP.md b/ROADMAP.md
index bc2036c..391876c 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -30,8 +30,17 @@ What Twiligent is for, and what every change should move forward.
## In Progress
-- **TypeScript migration** ([#2](https://github.com/spacesdrive/twiligent/issues/2)) - Backend, frontend and the scheduled publisher script rewritten in TypeScript with strict checks, without behaviour changes. Sub-issues: tooling (#3), backend (#4), frontend (#5), publisher script (#6), docs (#7).
-- **API rate limiting** ([#8](https://github.com/spacesdrive/twiligent/issues/8)) - Token bucket, leaking bucket, fixed window, sliding window log and sliding window counter limiters in Redis (atomic Lua scripts) with an in-memory fallback, applied per IP, per user and per expensive route.
+Nothing is in progress. The TypeScript migration (#2) and API rate limiting (#8) are finished and recorded in `CHANGELOG.md`.
+
+The migration found defects that are now tracked as issues, in priority order:
+
+1. **Redis outages slow cached requests** ([#10](https://github.com/spacesdrive/twiligent/issues/10)) - the local Upstash database no longer resolves, and the cache client retries for about 4 seconds per call. Check the production database first.
+2. **Instagram credential and account checks before publishing** ([#11](https://github.com/spacesdrive/twiligent/issues/11))
+3. **Required account fields before platform API calls** ([#12](https://github.com/spacesdrive/twiligent/issues/12))
+4. **Analytics edge cases** ([#15](https://github.com/spacesdrive/twiligent/issues/15)) - empty-state shape, hidden like counts, Reddit karma
+5. **Saving GitHub settings erases the stored token** ([#13](https://github.com/spacesdrive/twiligent/issues/13))
+6. **Declared variants and design tokens in three components** ([#16](https://github.com/spacesdrive/twiligent/issues/16))
+7. **Dead code from the migration** ([#14](https://github.com/spacesdrive/twiligent/issues/14))
---
@@ -119,8 +128,9 @@ React Native app using the same Cloudflare Worker backend.
- `wrangler.toml` has no `vars` section for non-secret configuration - any non-sensitive config currently requires a redeploy to change.
- The scheduled publishers (`backend/utils/scheduler` and `scripts/publish-scheduled`) publish due posts one after another in a single run. A large batch due at the same moment can exceed the Worker's or the Actions job's time limit; the rest wait for the next run.
-- CORS allows every origin (`cors()` with no options). Restricting it to `FRONTEND_URL` would block other sites from calling the API with a stolen token.
-- `scripts/publish-scheduled.js` prints emoji in its log output, which breaks the writing standards; it is rewritten in the TypeScript migration (#6).
+- CORS allows every origin. Restricting it to `FRONTEND_URL` would block other sites from calling the API with a stolen token.
+- Rate limits are counted per Worker isolate when Redis is not configured, which is looser than one global count (see `docs/architecture/backend/RATE_LIMITING.md`).
+- The project stays on TypeScript 6.0 until `typescript-eslint` supports TypeScript 7.
- No end-to-end tests; see `docs/workflows/TESTING.md` for the planned Playwright coverage.
### Resolved
@@ -129,3 +139,7 @@ React Native app using the same Cloudflare Worker backend.
- The legacy Express prototype in the root `public/` folder and its root dependencies were removed; the root `package.json` is now the npm workspaces root.
- Reddit integration shipped (public JSON API, no cookies or OAuth).
- Secrets with PowerShell-injected BOM characters broke the GitHub Actions publisher - it now strips non-ASCII characters from them.
+- The API had no rate limiting - every request is now limited per IP, per user and per quota-spending route (#8).
+- The codebase was JavaScript with API shapes restated on both sides - it is now strict TypeScript with shared API types (#2).
+- `GET /api/comparison` returned stored account secrets - fixed (#9).
+- The publisher log printed emoji - removed (#6).
diff --git a/backend/services/reddit.ts b/backend/services/reddit.ts
index 005c7e5..b16653d 100644
--- a/backend/services/reddit.ts
+++ b/backend/services/reddit.ts
@@ -149,7 +149,7 @@ export async function fetchRedditPosts(username: string, cookie: RedditCookie, l
return allPosts.slice(0, limit).map(normalizeRedditPost);
}
-// no-op kept because the server.js cron handler still calls it
+// no-op kept because the server.ts cron handler still calls it
export async function autoRefreshRedditSessions(): Promise<void> {}
function parseRedditPostUrl(rawUrl: string): string {
diff --git a/claude.md b/claude.md
index e2a5e22..6b88161 100644
--- a/claude.md
+++ b/claude.md
@@ -33,18 +33,20 @@ The repo is an npm workspaces monorepo. Run every install and script from the ro
```
package.json workspaces ["backend", "frontend"], shared dev tooling, root scripts
package-lock.json the only lockfile; one node_modules at the root
-eslint.config.mjs shared ESLint config (frontend rules, backend Workers rules, Node rules for tests)
+tsconfig.base.json shared TypeScript settings (strict, erasable syntax only); each project extends it
+eslint.config.mjs shared ESLint config (typescript-eslint, frontend rules, backend Workers rules, Node rules for tests)
.prettierrc.json shared Prettier config matching the existing style (not applied in bulk)
.editorconfig editor defaults (4 spaces in backend, 2 elsewhere)
+shared/types/ API contract types shared by backend and frontend (types only, no runtime code)
backend/ Hono Worker; tests in backend/tests/ mirroring the source folders
frontend/ React SPA; tests in frontend/tests/ mirroring frontend/src/
-scripts/ publish-scheduled.js, run by GitHub Actions with no dependencies
+scripts/ publish-scheduled.ts, run by GitHub Actions with no dependencies
```
- `npm install` at the root installs both apps. Never run `npm install` inside `backend/` or `frontend/`, and never commit a lockfile there.
-- `npm run dev` starts the Worker (port 8787) and Vite (port 5173) together; `npm test`, `npm run lint` and `npm run build` cover the whole repo.
+- `npm run dev` starts the Worker (port 8787) and Vite (port 5173) together; `npm run typecheck`, `npm test`, `npm run lint` and `npm run build` cover the whole repo.
- Add a dependency to the app that uses it: `npm install <pkg> --workspace backend` or `--workspace frontend`. Only shared dev tooling belongs in the root `package.json`.
-- Tests never live next to source files. A test for `backend/services/youtube.js` is `backend/tests/services/youtube.test.js`; a test for `frontend/src/lib/accounts.js` is `frontend/tests/lib/accounts.test.js`.
+- Tests never live next to source files. A test for `backend/services/youtube.ts` is `backend/tests/services/youtube.test.ts`; a test for `frontend/src/lib/accounts.ts` is `frontend/tests/lib/accounts.test.ts`.
---
@@ -56,7 +58,7 @@ Before implementing any feature or fix, read these documents in this exact order
2. `docs/workflows/ISSUES.md` - open or find the GitHub issue for the task before anything else
3. `docs/WRITING_STANDARDS.md` - typography, icons, writing style, UI copy rules
4. `docs/architecture/OVERVIEW.md` - system topology and request flow
-5. `docs/guidelines/JAVASCRIPT.md` - code standards (always apply)
+5. `docs/guidelines/TYPESCRIPT.md` - code standards and typing rules (always apply)
6. Relevant architecture doc - backend, frontend, database, or cloudflare
7. Relevant feature guide - if one exists in `docs/features/`
8. Relevant engineering guideline - if the task touches a specific layer
@@ -77,16 +79,17 @@ docs/
backend/
HONO.md App structure, middleware, routing pattern
ROUTES.md All routes, method, auth requirement, purpose
- SERVICES.md instagram.js, youtube.js service layer
+ SERVICES.md instagram.ts, youtube.ts service layer
MIDDLEWARE.md requireAuth, CORS, context injection
CACHING.md Redis strategy, cache keys, invalidation
+ RATE_LIMITING.md Rate limit rules, algorithms, Redis Lua scripts, fallbacks
CRON.md Scheduled handlers, cron triggers
frontend/
- REACT_ARCHITECTURE.md Provider tree, lazy loading, App.jsx
+ REACT_ARCHITECTURE.md Provider tree, lazy loading, App.tsx
DESIGN_SYSTEM.md Tokens, shared components, page patterns
ROUTING.md All pages, paths, layout nesting
CONTEXTS.md AuthContext, AppContext, usage rules
- API_LAYER.md api.js, request(), auth header injection
+ API_LAYER.md api.ts, request(), auth header injection
FEATURES.md Feature module conventions, directory map
database/
SCHEMA.md All tables, columns, types, constraints
@@ -101,7 +104,7 @@ docs/
ANALYTICS.md YouTube and Instagram analytics fetch and compute
SCHEDULING.md Scheduled post lifecycle, dual-scheduler design
guidelines/
- JAVASCRIPT.md Code style, modules, naming, comments policy
+ TYPESCRIPT.md Compiler settings, typing rules, where types live, code style, comments policy
REACT.md Component rules, hooks, JSX conventions
HONO.md Route handlers, middleware, context usage
CLOUDFLARE_WORKERS.md Worker-safe patterns, env access, no Node APIs
@@ -137,7 +140,7 @@ docs/
SECURITY.md Security model, key handling, isolation
PERFORMANCE.md Caching strategy, edge optimization
-frontend/src/docs/ Public user and self-hosting docs served at /docs (in-app, JSX)
+frontend/src/docs/ Public user and self-hosting docs served at /docs (in-app, TSX)
DECISIONS.md Architectural decision log
CHANGELOG.md Version history and feature changes
ROADMAP.md Planned features and priorities
@@ -256,11 +259,11 @@ This is not optional for features that touch new UI patterns, new APIs, or new i
**Always read before writing.** Read every file you will modify. Read all files in the same directory that might be affected. Read sibling files to understand conventions before adding new ones.
-**Match the existing pattern.** This project has established conventions for routes, context hooks, db.js queries, cache.js patterns, and api.js methods. Find the nearest existing example and follow it exactly before introducing anything new.
+**Match the existing pattern.** This project has established conventions for routes, context hooks, db.ts queries, cache.ts patterns, and api.ts methods. Find the nearest existing example and follow it exactly before introducing anything new.
-**No TypeScript.** The entire project - backend and frontend - is JavaScript/JSX. Do not suggest or introduce TypeScript unless explicitly asked.
+**TypeScript only, in strict mode.** The whole project - Worker, React app, shared types, scripts and tests - is TypeScript (`.ts`, and `.tsx` for files with JSX). Never add a `.js` or `.jsx` source file, never use `any`, `@ts-ignore` or `@ts-expect-error`, and only use syntax Node can strip (no enums, namespaces or parameter properties; `import type` for types; relative imports keep their `.ts` extension). Types the API sends or receives live in `shared/types/`; change them there first. `npm run typecheck` must pass before every commit. See `docs/guidelines/TYPESCRIPT.md`.
-**No dependencies without explicit approval.** The backend uses zero npm dependencies at runtime beyond `hono`, `@supabase/supabase-js`, and `@upstash/redis`. Adding packages to the Cloudflare Worker increases bundle size and startup time. The `scripts/publish-scheduled.js` file uses zero npm dependencies by design.
+**No dependencies without explicit approval.** The backend uses zero npm dependencies at runtime beyond `hono`, `@supabase/supabase-js`, and `@upstash/redis`. Adding packages to the Cloudflare Worker increases bundle size and startup time. The `scripts/publish-scheduled.ts` file uses zero npm dependencies by design.
**Security invariants - never violate these:**
- `SUPABASE_SERVICE_KEY` is only ever used server-side (backend Worker)
@@ -269,9 +272,9 @@ This is not optional for features that touch new UI patterns, new APIs, or new i
- All user-scoped queries always append `.eq('user_id', userId)` where `userId` comes from a verified JWT, never from user input
- `backend/.dev.vars` must never be committed
-**Use the established db.js pattern.** All database operations go through `lib/db.js`. Never write inline Supabase queries in route handlers. Add new operations to `db.js` and import them.
+**Use the established db.ts pattern.** All database operations go through `lib/db.ts`. Never write inline Supabase queries in route handlers. Add new operations to `db.ts` and import them.
-**Use the established api.js pattern.** All frontend-to-backend calls go through `frontend/src/services/api.js`. Never call `fetch()` directly in components. Add new endpoints to the `api` object in `api.js`.
+**Use the established api.ts pattern.** All frontend-to-backend calls go through `frontend/src/services/api.ts`. Never call `fetch()` directly in components. Add new endpoints to the `api` object in `api.ts`.
**Redis failures are always silent.** Wrap all Redis operations in try/catch. Cache misses must fall back to live API calls. The app must work with Redis completely absent.
@@ -328,7 +331,8 @@ When anything changes, update every relevant docs file from the table below. The
| New npm package (frontend) | `docs/architecture/frontend/REACT_ARCHITECTURE.md`, `DECISIONS.md` |
| New npm package (root dev tooling) | `docs/workflows/TESTING.md` or the guideline it serves, `DECISIONS.md`, `README.md` |
| Workspaces, root `package.json` scripts or the root lockfile changed | `README.md`, `docs/workflows/DEPLOYMENT.md`, `docs/workflows/FEATURE_DEVELOPMENT.md`, `docs/architecture/cloudflare/CI_CD.md`, this file (Repository Layout section) |
-| Shared tooling config changed (`eslint.config.mjs`, `.prettierrc.json`, `.editorconfig`) | `docs/guidelines/JAVASCRIPT.md`, `docs/workflows/TESTING.md`, this file (Repository Layout section) |
+| Shared tooling config changed (`eslint.config.mjs`, `tsconfig*.json`, `.prettierrc.json`, `.editorconfig`) | `docs/guidelines/TYPESCRIPT.md`, `docs/workflows/TESTING.md`, this file (Repository Layout section) |
+| API request or response shape changed | `shared/types/*.ts` first (the type checker then lists every caller), `docs/architecture/backend/ROUTES.md`, `docs/architecture/frontend/API_LAYER.md` |
| New frontend feature module | `docs/architecture/frontend/FEATURES.md`, `docs/architecture/frontend/ROUTING.md`, `docs/architecture/OVERVIEW.md` |
| New data flow | `docs/architecture/data-flows/` (add or update relevant file), `docs/architecture/OVERVIEW.md` |
| New cron trigger | `docs/architecture/cloudflare/WORKERS.md`, `docs/architecture/backend/CRON.md`, `docs/architecture/cloudflare/CI_CD.md` |
@@ -337,14 +341,16 @@ When anything changes, update every relevant docs file from the table below. The
| Test added, moved or test command changed | `docs/workflows/TESTING.md` (layout, commands, coverage list) |
| New backend service file | `docs/architecture/backend/SERVICES.md` |
| New cache key | `docs/architecture/backend/CACHING.md` |
+| Rate limit rule, limit or covered route changed | `docs/architecture/backend/RATE_LIMITING.md` (rules table), `backend/tests/middleware/rateLimit.test.ts` (route matchers) |
+| Rate limit algorithm or Lua script changed | Both `backend/lib/rateLimit/algorithms.ts` and `scripts.ts` together, `docs/architecture/backend/RATE_LIMITING.md`, `DECISIONS.md` |
| New middleware | `docs/architecture/backend/MIDDLEWARE.md`, `docs/architecture/backend/HONO.md` |
| Auth flow changed | `docs/architecture/data-flows/AUTHENTICATION.md` |
| Publishing flow changed | `docs/architecture/data-flows/PUBLISHING.md` |
| Scheduling flow changed | `docs/architecture/data-flows/SCHEDULING.md` |
| Analytics computation changed | `docs/architecture/data-flows/ANALYTICS.md` |
| New React context or hook | `docs/architecture/frontend/CONTEXTS.md` |
-| api.js changed | `docs/architecture/frontend/API_LAYER.md` |
-| App.jsx routing changed | `docs/architecture/frontend/ROUTING.md` |
+| api.ts changed | `docs/architecture/frontend/API_LAYER.md` |
+| App.tsx routing changed | `docs/architecture/frontend/ROUTING.md` |
| Frontend deployment config changed | `docs/architecture/cloudflare/PAGES.md` |
| Architecture decision made | `DECISIONS.md` (append only, never delete) |
| Any feature shipped | `CHANGELOG.md` (append to Unreleased section) |
diff --git a/docs/WRITING_STANDARDS.md b/docs/WRITING_STANDARDS.md
index 7739c77..1ae1d61 100644
--- a/docs/WRITING_STANDARDS.md
+++ b/docs/WRITING_STANDARDS.md
@@ -19,7 +19,7 @@ These rules apply to all generated code, documentation, UI copy, commit messages
- Never use emoji as icons in UI.
- Use SVG icons only.
-- Prefer Lucide React icons (`lucide-react`) at a 1.75 stroke. Platform logos (YouTube, Instagram, Reddit) come from `components/brand/platform-icons.jsx`.
+- Prefer Lucide React icons (`lucide-react`) at a 1.75 stroke. Platform logos (YouTube, Instagram, Reddit) come from `components/brand/platform-icons.tsx`.
- If Lucide does not have an appropriate icon, use another open-source SVG icon library (e.g. Heroicons, Radix Icons).
- All icons in the same UI context must have consistent size, stroke width, spacing, and visual weight.
diff --git a/docs/architecture/OVERVIEW.md b/docs/architecture/OVERVIEW.md
index c1551a2..399da6d 100644
--- a/docs/architecture/OVERVIEW.md
+++ b/docs/architecture/OVERVIEW.md
@@ -68,7 +68,7 @@ Cloudflare Worker edge node (nearest to user)
-> sets c.userId, c.userEmail on Hono context
-> rateLimit(user), and rateLimit(quota) or rateLimit(publish) on the routes they cover
-> route handler (e.g., accounts router)
- -> db.getAccounts(supabase, userId) [lib/db.js]
+ -> db.getAccounts(supabase, userId) [lib/db.ts]
-> supabase.from('accounts').select(...).eq('user_id', userId)
-> normalizes rows
-> returns JSON response
@@ -111,7 +111,7 @@ See `docs/architecture/cloudflare/WORKERS.md` for the full list of required Work
Frontend env vars are documented in `docs/architecture/cloudflare/PAGES.md`.
-The SPA also serves public documentation at `/docs` (no sign-in, no API calls). It is static JSX in `frontend/src/docs/`, code-split per section; see `docs/architecture/frontend/FEATURES.md`.
+The SPA also serves public documentation at `/docs` (no sign-in, no API calls). It is static TSX in `frontend/src/docs/`, code-split per section; see `docs/architecture/frontend/FEATURES.md`.
## Key Architectural Invariants
@@ -123,8 +123,10 @@ The SPA also serves public documentation at `/docs` (no sign-in, no API calls).
4. **`safeAccount()` is the only place access tokens are stripped.** Any route that returns account data must pass through this function before responding.
-5. **`db.js` is the only file that contains Supabase queries.** Route handlers import and call db functions - they never call `supabase.from()` directly.
+5. **`db.ts` is the only file that contains Supabase queries.** Route handlers import and call db functions - they never call `supabase.from()` directly.
6. **Every `/api` request is rate limited.** Per IP before authentication, per user after it, and tighter on routes that spend platform API quota. See `docs/architecture/backend/RATE_LIMITING.md`.
-7. **`api.js` is the only file that calls `fetch()` in the frontend.** Components call `api.methodName()` - they never construct fetch calls.
+7. **`api.ts` is the only file that calls `fetch()` in the frontend.** Components call `api.methodName()` - they never construct fetch calls.
+
+8. **The API contract is typed once, in `shared/types/`.** Routes check every response against it with `satisfies`, and `api.ts` methods return the same types, so `npm run typecheck` catches a shape change on both sides. CI runs the type check before every deploy, because Wrangler and Vite strip types without checking them. See `docs/guidelines/TYPESCRIPT.md`.
diff --git a/docs/architecture/backend/CACHING.md b/docs/architecture/backend/CACHING.md
index ae892de..425fb31 100644
--- a/docs/architecture/backend/CACHING.md
+++ b/docs/architecture/backend/CACHING.md
@@ -2,22 +2,36 @@
## Overview
-Caching is implemented via Upstash Redis (REST API) using the `@upstash/redis` SDK. It is **entirely optional** - if `UPSTASH_REDIS_REST_URL` is not set, `getRedis()` returns `null` and all cache functions in `lib/cache.js` silently no-op.
+Caching is implemented via Upstash Redis (REST API) using the `@upstash/redis` SDK. It is **entirely optional** - if `UPSTASH_REDIS_REST_URL` is not set, `getRedis()` returns `null` and all cache functions in `lib/cache.ts` silently no-op.
-## Cache Layer: `backend/lib/cache.js`
+## Cache Layer: `backend/lib/cache.ts`
All cache operations follow this contract:
-- Accept `redis` as the first argument
+- Accept `redis` (`Redis | null`) as the first argument
- If `redis` is `null`, return immediately (no-op)
- Wrap all `redis` calls in `try/catch` - a Redis failure must never break the main request
+- Return the cached shape from `shared/types` (`VideosCacheData`, `IGCacheData`, `RedditCacheData`), or `null` on a miss
-```js
-export async function getVideosCache(redis, userId, accountId) {
+The private helpers `readKey<T>()`, `writeKey()` and `deleteKey()` implement the null check, the `try/catch` and the TTL once; every exported function goes through them:
+
+```ts
+async function readKey<T>(redis: Redis | null, key: string): Promise<T | null> {
if (!redis) return null;
- try { return (await redis.get(`videos:${userId}:${accountId}`)) || null; } catch { return null; }
+ try {
+ return await redis.get<T>(key);
+ } catch {
+ // a cache miss falls back to the live api
+ return null;
+ }
+}
+
+export async function getRedditCache(redis: Redis | null, userId: string, accountId: string): Promise<RedditCacheData | null> {
+ return (await readKey<RedditCacheData>(redis, `reddit:${userId}:${accountId}`)) || null;
}
```
+`redis.get<T>()` does not validate what Redis returns; the type is what the matching setter wrote. Bump the cache version (below) when that shape changes.
+
## Cache Keys
| Key pattern | Content | Set when | Invalidated when |
@@ -32,11 +46,11 @@ Rate limit state also lives in Redis under `ratelimit:{rule}:{identifier}` keys
## Cache Versioning
-`ig:` entries carry a `version` field written by `setIGCache()`. `getIGCache()` treats an entry whose `version` differs from `IG_CACHE_VERSION` in `lib/cache.js` as a miss, so the next request refetches from Instagram and overwrites it. Bump `IG_CACHE_VERSION` whenever the cached media shape changes. Version 2 added `contentType` and `viewCount`.
+`ig:` entries carry a `version` field written by `setIGCache()`. `getIGCache()` treats an entry whose `version` differs from `IG_CACHE_VERSION` in `lib/cache.ts` as a miss, so the next request refetches from Instagram and overwrites it. Bump `IG_CACHE_VERSION` whenever the cached media shape changes. Version 2 added `contentType` and `viewCount`.
## Cache TTL
-`videos:`, `ig:` and `reddit:` keys expire after 6 hours (`ANALYTICS_TTL_SECONDS` in `lib/cache.js`), so counts refetch rather than going stale. They are also removed when the account is deleted.
+`videos:`, `ig:` and `reddit:` keys expire after 6 hours (`ANALYTICS_TTL_SECONDS` in `lib/cache.ts`), so counts refetch rather than going stale. They are also removed when the account is deleted.
`videos:` entries carry a `version` field like `ig:` entries (`VIDEOS_CACHE_VERSION`). Version 2 stores `likeCount` and `commentCount` as `null` when YouTube hides them (the owner hid likes, or comments are off), instead of `0`; the UI shows those as "Hidden".
@@ -48,7 +62,7 @@ Rate limit state also lives in Redis under `ratelimit:{rule}:{identifier}` keys
The analytics routes use this pattern:
-```js
+```ts
// GET /api/accounts/:id/analytics
const cached = await getVideosCache(redis, userId, accountId);
if (cached) return c.json(cached);
@@ -62,7 +76,7 @@ return c.json(result);
## Adding New Cache Keys
-1. Add getter, setter, and deleter functions to `backend/lib/cache.js`
+1. Add getter, setter, and deleter functions to `backend/lib/cache.ts`
2. Follow the existing naming convention: `{entity}:{userId}:{accountId}`
3. Always guard with `if (!redis) return null/undefined`
4. Always wrap in `try/catch`
@@ -71,7 +85,7 @@ return c.json(result);
## HMAC OAuth State (Not Redis)
-The `createOAuthState()` and `verifyOAuthState()` functions live in `lib/oauthState.js`; `services/instagramOAuth.js` and `routes/instagramAuth.js` import them from there directly, and `cache.js` still re-exports them. They are **not** Redis-based. They use `crypto.subtle.sign()` (native Web Crypto API in Workers) to create self-verifying state tokens. Redis is not involved.
+The `createOAuthState()` and `verifyOAuthState()` functions live in `lib/oauthState.ts`; `services/instagramOAuth.ts` and `routes/instagramAuth.ts` import them from there directly, and `cache.ts` still re-exports them. They are **not** Redis-based. They use `crypto.subtle.sign()` (native Web Crypto API in Workers) to create self-verifying state tokens. Redis is not involved.
```
State format: base64url(userId:timestamp).base64url(HMAC-SHA256-signature)
@@ -79,4 +93,4 @@ Expiry: 10 minutes (checked by comparing embedded timestamp to Date.now())
Secret: INSTAGRAM_APP_SECRET
```
-These functions are in `cache.js` for historical reasons - they started as Redis-backed and were migrated to HMAC. They could logically live in `lib/auth.js` but remain in `cache.js` for stability.
+They started in `cache.ts` as Redis-backed helpers and were migrated to HMAC, then moved to their own module. `cache.ts` still re-exports them, but new code imports them from `lib/oauthState.ts`.
diff --git a/docs/architecture/backend/CRON.md b/docs/architecture/backend/CRON.md
index 1748a98..245364b 100644
--- a/docs/architecture/backend/CRON.md
+++ b/docs/architecture/backend/CRON.md
@@ -7,13 +7,13 @@
crons = ["*/15 * * * *", "0 0 * * *"]
```
-Both cron triggers invoke the `scheduled` export from `backend/server.js`.
+Both cron triggers invoke the `scheduled` export from `backend/server.ts`.
## Cron Handlers
### `*/15 * * * *` - Instagram Scheduled Post Publisher
-**Function:** `processScheduledPosts(supabase)` in `backend/utils/scheduler.js`
+**Function:** `processScheduledPosts(supabase)` in `backend/utils/scheduler.ts`
**What it does:**
1. Queries `scheduled_posts` where `status = 'pending'` and `scheduled_at <= now()`
@@ -24,17 +24,17 @@ Both cron triggers invoke the `scheduled` export from `backend/server.js`.
- On success: sets status to `'published'`, stores `publishedMediaId` and `publishedAt` in `data`
- On failure: sets status to `'failed'`, stores `error` message in `data`
-`backend/tests/utils/scheduler.test.js` pins this sequence, the log lines and the stored results against a fake Supabase client and Graph API (fixtures and golden snapshots in `backend/tests/fixtures/`).
+`backend/tests/utils/scheduler.test.ts` pins this sequence, the log lines and the stored results against a fake Supabase client and Graph API (fixtures and golden snapshots in `backend/tests/fixtures/`).
**No userId filter** - the scheduler operates across all users. It uses the service-role Supabase client.
**Concurrency safety:** The `'publishing'` status acts as a mutex. If the Worker cron and GitHub Actions cron overlap, the second one to claim a post will find it already in `'publishing'` state and skip it (it won't appear in the `status=pending` query).
-### `0 0 * * *` - Instagram Token Auto-Refresh + Reddit Session Refresh
+### `0 0 * * *` - Instagram Token Auto-Refresh and Reddit Session Hook
Two functions run in parallel via `ctx.waitUntil()`:
-**1. `autoRefreshInstagramTokens(supabase)` in `backend/services/instagram.js`**
+**1. `autoRefreshInstagramTokens(supabase)` in `backend/services/instagram.ts`**
**What it does:**
1. Queries all accounts with `platform = 'instagram'`
@@ -48,27 +48,16 @@ Two functions run in parallel via `ctx.waitUntil()`:
- The daily cron refreshes any token expiring within 15 days
- This gives a 15-day window for recovery if the cron fails for a few days
-**2. `autoRefreshRedditSessions(supabase, encryptionKey)` in `backend/services/reddit.js`**
+**2. `autoRefreshRedditSessions()` in `backend/services/reddit.ts`**
-**What it does:**
-1. Queries all accounts with `platform = 'reddit'` that have `encryptedPassword` set
-2. For each, checks if `cookieAcquiredAt` is older than 23 hours
-3. If stale: decrypts the stored password using `REDDIT_ENCRYPTION_KEY` and calls `loginToReddit(username, password)`
-4. Updates `cookie`, `cookieAcquiredAt`, and `cookieExpiresAt` in Supabase
-5. Logs success or error per account; never throws - failures are non-fatal
-
-**Cookie lifecycle:**
-- Reddit session cookies obtained via `ssl.reddit.com/api/login` last approximately 24 hours
-- The daily cron refreshes cookies older than 23 hours
-- If `REDDIT_ENCRYPTION_KEY` is not set, this function exits immediately (no-op)
-- Accounts without a stored encrypted password (public-only access) are skipped
+This function is currently a no-op: it takes no arguments and returns immediately. Reddit accounts are added with a `reddit_session` cookie copied from the browser (`POST /api/accounts/reddit` with `{ username, cookie }`), and nothing logs in to Reddit or refreshes that cookie on a schedule. When the cookie expires, the user re-adds the account. `REDDIT_ENCRYPTION_KEY` is declared in `Env` but read nowhere.
## The `ctx.waitUntil()` Pattern
Cron handlers use `ctx.waitUntil()` to run work after the handler returns:
-```js
-async scheduled(event, env, ctx) {
+```ts
+async scheduled(event: ScheduledController, env: Env, ctx: ExecutionContext) {
const supabase = getSupabase(env);
if (event.cron === '*/15 * * * *') {
ctx.waitUntil(processScheduledPosts(supabase));
@@ -80,7 +69,7 @@ This is required because Workers have a request deadline. `ctx.waitUntil()` tell
## Dual-Scheduler (GitHub Actions Fallback)
-The same `*/15` publishing logic also runs via `scripts/publish-scheduled.js` in GitHub Actions. See `docs/architecture/data-flows/SCHEDULING.md` for details on how both systems coexist safely.
+The same `*/15` publishing logic also runs via `scripts/publish-scheduled.ts` in GitHub Actions. See `docs/architecture/data-flows/SCHEDULING.md` for details on how both systems coexist safely.
## Adding a New Cron Trigger
@@ -89,14 +78,14 @@ The same `*/15` publishing logic also runs via `scripts/publish-scheduled.js` in
crons = ["*/15 * * * *", "0 0 * * *", "0 12 * * 1"]
```
-2. Add a handler branch in `server.js`:
- ```js
+2. Add a handler branch in `server.ts`:
+ ```ts
} else if (event.cron === '0 12 * * 1') {
ctx.waitUntil(myWeeklyJob(supabase));
}
```
-3. Implement `myWeeklyJob(supabase)` in the appropriate service or utils file
+3. Implement `myWeeklyJob(supabase: SupabaseClient): Promise<void>` in the appropriate service or utils file, and run `npm run typecheck`
4. Update `docs/architecture/backend/CRON.md` (this file)
diff --git a/docs/architecture/backend/HONO.md b/docs/architecture/backend/HONO.md
index 78509d3..35df99f 100644
--- a/docs/architecture/backend/HONO.md
+++ b/docs/architecture/backend/HONO.md
@@ -1,59 +1,81 @@
# Backend - Hono Application Structure
-## Entry Point: `backend/server.js`
+## Entry Point: `backend/server.ts`
-The entire backend is a single Hono application exported as a Cloudflare Workers module.
+The entire backend is a single Hono application exported as a Cloudflare Workers module. `backend/wrangler.toml` points at it with `main = "server.ts"`; Wrangler bundles it and strips the types, and `npm run typecheck` checks them.
-```js
+```ts
// The two exports Cloudflare Workers looks for:
export default {
fetch: app.fetch, // handles all HTTP requests
- async scheduled(event, env, ctx) { ... } // handles cron triggers
-};
+ async scheduled(event: ScheduledController, env: Env, ctx: ExecutionContext) { ... } // handles cron triggers
+} satisfies ExportedHandler<Env>;
```
## Application Structure
-```
-const app = new Hono(); // root application
+```ts
+const app = new Hono<AppEnv>(); // root application
// Global middleware (runs on every request)
-app.use('*', cors());
-app.use('*', clientInjectionMiddleware); // attaches supabase + redis to context
+app.use('*', cors({ exposeHeaders: RATE_LIMIT_HEADERS }));
+app.use('*', async (c, next) => { /* sets supabase, redis, rateLimitRedis */ await next(); });
+app.use('/api/*', rateLimit(RATE_LIMIT_RULES.ip, clientIp));
// Public routes
app.get('/api/health', ...);
-app.get('/api/auth/instagram/callback', callbackHandler);
+app.get('/api/auth/instagram/callback', rateLimit(RATE_LIMIT_RULES.oauth, clientIp), callbackHandler);
// Protected sub-application
-const api = new Hono();
+const api = new Hono<AppEnv>();
api.use('*', requireAuth); // JWT verification on all /api/* routes
+api.use('*', rateLimit(RATE_LIMIT_RULES.user, userKey));
+// plus the quota and publish limits for the routes listed in lib/rateLimit/rules.ts
api.route('/', keysRouter);
api.route('/', accountsRouter);
api.route('/', analyticsRouter);
api.route('/', publishingRouter);
api.route('/', scheduledPostsRouter);
api.route('/', settingsRouter);
+api.route('/', redditRouter);
+api.route('/', trackedContentRouter);
+api.route('/', overviewRouter);
api.get('/auth/instagram/url', urlHandler);
app.route('/api', api); // mount protected sub-app under /api
```
+See `docs/architecture/backend/RATE_LIMITING.md` for the rate limit rules.
+
+## Types
+
+| Type | File | Purpose |
+|---|---|---|
+| `Env` | `backend/types/env.ts` | Worker secrets and bindings, read through `c.env` or the `env` argument of `scheduled()` |
+| `AppVariables` | `backend/types/app.ts` | The keys set with `c.set()` and read with `c.get()` |
+| `AppEnv` | `backend/types/app.ts` | `{ Bindings: Env; Variables: AppVariables }`, the type argument of every `new Hono<AppEnv>()` |
+| `AppContext` | `backend/types/app.ts` | `Context<AppEnv>`, for middleware and handlers declared outside a router |
+| Request and response shapes | `shared/types/*.ts` | Shared with the frontend; routes check responses with `satisfies` |
+
+`ScheduledController`, `ExecutionContext` and `ExportedHandler` are global types from `@cloudflare/workers-types`.
+
## Context Values
These are set on the Hono context (`c`) and available in all route handlers:
| Key | Type | Set by | Available after |
|---|---|---|---|
-| `supabase` | Supabase client (service-role) | global middleware | All routes |
-| `redis` | Upstash Redis client \| null | global middleware | All routes |
-| `rateLimitRedis` | Upstash Redis client \| null (no retries, 1 second timeout) | global middleware | All routes; used only by `rateLimit` |
-| `userId` | string (UUID) | `requireAuth` | Protected routes only |
-| `userEmail` | string | `requireAuth` | Protected routes only |
-
-**Accessing context values in a handler:**
-```js
-export async function myHandler(c) {
+| `supabase` | `SupabaseClient` (service-role) | global middleware | All routes |
+| `redis` | `Redis \| null` | global middleware | All routes |
+| `rateLimitRedis` | `Redis \| null` (no retries, 1 second timeout) | global middleware | All routes; used only by `rateLimit` |
+| `userId` | `string` (UUID) | `requireAuth` | Protected routes only |
+| `userEmail` | `string \| undefined` | `requireAuth` | Protected routes only |
+
+The keys and their types are declared in `AppVariables`, so `c.get('redis')` is typed `Redis | null` without a cast. Add a key there before setting a new one.
+
+**Accessing context values in a handler declared outside a router:**
+```ts
+export async function myHandler(c: AppContext) {
const supabase = c.get('supabase');
const redis = c.get('redis');
const userId = c.get('userId');
@@ -65,53 +87,55 @@ export async function myHandler(c) {
Every route file follows this structure:
-```js
-// backend/routes/myFeature.js
+```ts
+// backend/routes/myFeature.ts
import { Hono } from 'hono';
-import { getMyData, createMyData } from '../lib/db.js';
+import { getMyData, createMyData } from '../lib/db.ts';
+import type { AppEnv } from '../types/app.ts';
+import type { MyData, MyDataRequest } from '../../shared/types/domain.ts';
-const router = new Hono();
+const router = new Hono<AppEnv>();
router.get('/my-resource', async (c) => {
const userId = c.get('userId');
const supabase = c.get('supabase');
try {
const data = await getMyData(supabase, userId);
- return c.json(data);
+ return c.json(data satisfies MyData[]);
} catch (err) {
- console.error('GET /my-resource:', err.message);
- return c.json({ error: err.message }, 500);
+ console.error('GET /my-resource:', (err as Error).message);
+ return c.json({ error: (err as Error).message }, 500);
}
});
router.post('/my-resource', async (c) => {
const userId = c.get('userId');
const supabase = c.get('supabase');
- const body = await c.req.json();
+ const body = await c.req.json() as MyDataRequest;
// validate body...
try {
await createMyData(supabase, body, userId);
return c.json({ success: true }, 201);
} catch (err) {
- console.error('POST /my-resource:', err.message);
- return c.json({ error: err.message }, 500);
+ console.error('POST /my-resource:', (err as Error).message);
+ return c.json({ error: (err as Error).message }, 500);
}
});
export default router;
```
-Then in `server.js`:
-```js
-import myFeatureRouter from './routes/myFeature.js';
+Then in `server.ts`:
+```ts
+import myFeatureRouter from './routes/myFeature.ts';
// ...
api.route('/', myFeatureRouter);
```
## Error Handling
-The global error handler catches uncaught errors:
-```js
+The global error handler catches uncaught errors (Hono types `err` as `Error` here):
+```ts
app.onError((err, c) => {
console.error('Worker error:', err.message);
return c.json({ error: 'Internal server error' }, 500);
@@ -124,12 +148,12 @@ Route handlers should catch their own errors and return descriptive messages. Do
Worker environment variables are accessed via `c.env` in middleware and handlers, or via the `env` parameter in the `scheduled` handler:
-```js
+```ts
// In middleware or handler:
-const apiKey = c.env.YOUTUBE_API_KEY;
+const apiKey = c.env.YOUTUBE_API_KEY; // string | undefined, declared in Env
// In cron handler:
-async scheduled(event, env, ctx) {
+async scheduled(event: ScheduledController, env: Env, ctx: ExecutionContext) {
const supabase = getSupabase(env);
}
```
@@ -146,10 +170,14 @@ async scheduled(event, env, ctx) {
| `@supabase/supabase-js` | runtime | Database and JWT verification |
| `@upstash/redis` | runtime | Optional cache over REST |
| `wrangler` | dev | Local dev server, deploys and secrets (version pinned by the root lockfile) |
+| `@cloudflare/workers-types` | dev | Types for the Workers runtime, loaded by `backend/tsconfig.json` |
+
+TypeScript itself, `typescript-eslint` and `@types/node` are root dev dependencies shared by both workspaces.
- Install from the repository root with `npm install`; it fills the single root `node_modules`. Add a backend package with `npm install <pkg> --workspace backend` (new runtime packages need explicit approval, see CLAUDE.md). There is no `backend/package-lock.json`.
-- Workspace scripts: `dev` and `start` run `wrangler dev`, `deploy` runs `wrangler deploy`, `test` runs `node --test "tests/**/*.test.js"`. From the root, `npm run dev:backend` starts the Worker alone, `npm run dev` starts it with Vite, and `npm test` runs the backend tests before the frontend ones.
+- Workspace scripts: `dev` and `start` run `wrangler dev`, `deploy` runs `wrangler deploy`, `test` runs `node --test "tests/**/*.test.ts"` (Node strips the types), `typecheck` runs `tsc -p tsconfig.json && tsc -p tests/tsconfig.json`. From the root, `npm run dev:backend` starts the Worker alone, `npm run dev` starts it with Vite, `npm test` runs the backend tests before the frontend ones, and `npm run typecheck` checks every project.
+- TypeScript: `backend/tsconfig.json` extends the root `tsconfig.base.json`, checks the Worker source with `@cloudflare/workers-types` only (no DOM, no Node), and excludes `tests/`. `backend/tests/tsconfig.json` checks the tests and the source they import, adding the Node types. Relative imports name the file with its `.ts` extension, because Node loads the same files in tests.
- `wrangler dev` reloads on save, so there is no nodemon or other watcher.
-- Lint is the root `eslint.config.mjs`: backend source gets the ESLint recommended rules with service worker globals (the Worker runs on the web platform, not Node), and `backend/tests/` gets Node globals. Run `npm run lint` from the root.
+- Lint is the root `eslint.config.mjs`: backend source gets the ESLint and `typescript-eslint` recommended rules with service worker globals (the Worker runs on the web platform, not Node), and `backend/tests/` gets Node globals. Run `npm run lint` from the root.
- Formatting follows the root `.prettierrc.json` and `.editorconfig`: 4-space indentation in `backend/`, single quotes, semicolons, 120 columns.
- Tests and fixtures live in `backend/tests/`, outside the source folders, so Wrangler never bundles them. See `docs/workflows/TESTING.md`.
diff --git a/docs/architecture/backend/MIDDLEWARE.md b/docs/architecture/backend/MIDDLEWARE.md
index d5b50fb..a75273f 100644
--- a/docs/architecture/backend/MIDDLEWARE.md
+++ b/docs/architecture/backend/MIDDLEWARE.md
@@ -39,12 +39,12 @@ Configured with defaults - allows all origins in development. For production, th
## 2. Client Injection Middleware
-**Source:** Inline in `backend/server.js`
+**Source:** Inline in `backend/server.ts`
**Applied to:** Every request
Creates per-request Supabase and Redis client instances and sets them on the Hono context. This is the correct pattern for Cloudflare Workers - clients must be created fresh per request because there is no persistent process memory.
-```js
+```ts
app.use('*', async (c, next) => {
c.set('supabase', getSupabase(c.env));
c.set('redis', getRedis(c.env));
@@ -57,15 +57,17 @@ app.use('*', async (c, next) => {
**`getRedis(env)`** - creates an Upstash Redis client if `UPSTASH_REDIS_REST_URL` is set, otherwise returns `null`. All cache functions in `lib/cache.ts` handle `null` silently.
**`getRateLimitRedis(env)`** - a second Upstash client for the rate limiter, with retries off and a 1 second timeout, so a Redis outage cannot slow every request. `null` without credentials.
+The keys and their types are declared in `AppVariables` in `backend/types/app.ts`, so `c.set()` rejects a value of the wrong type and `c.get()` needs no cast.
+
---
## 3. requireAuth Middleware
-**Source:** `backend/middleware/auth.js`
+**Source:** `backend/middleware/auth.ts`
**Applied to:** All routes mounted under the `api` sub-application (`/api/*`)
-```js
-export async function requireAuth(c, next) {
+```ts
+export async function requireAuth(c: AppContext, next: Next) {
const token = c.req.header('Authorization')?.replace('Bearer ', '');
if (!token) return c.json({ error: 'Unauthorized' }, 401);
const supabaseAuth = getSupabaseAuth(c.env);
@@ -81,7 +83,7 @@ export async function requireAuth(c, next) {
1. Extracts `Authorization: Bearer <token>` header
2. Creates a Supabase **anon** client (not service-role) to verify the JWT
3. Calls `supabaseAuth.auth.getUser(token)` - Supabase validates the token signature
-4. Sets `userId` (UUID) and `userEmail` (string) on the Hono context
+4. Sets `userId` (UUID) and `userEmail` (`string | undefined`) on the Hono context
5. Returns 401 JSON if token is missing, invalid, or expired
**Critical:** `userId` from this middleware is the only trusted source of user identity. Route handlers must use `c.get('userId')` - never accept a userId from request body or query params.
@@ -103,21 +105,26 @@ See `RATE_LIMITING.md` for the rules, the algorithms and how failures are handle
Place new middleware files in `backend/middleware/`. Follow this pattern:
-```js
-// backend/middleware/myMiddleware.js
-export async function myMiddleware(c, next) {
+```ts
+// backend/middleware/myMiddleware.ts
+import type { Next } from 'hono';
+import type { AppContext } from '../types/app.ts';
+
+export async function myMiddleware(c: AppContext, next: Next) {
// do something before route handler
await next();
// optionally do something after route handler
}
```
-Apply globally in `server.js`:
-```js
+A middleware that sets a new context value needs the key added to `AppVariables` in `backend/types/app.ts` first.
+
+Apply globally in `server.ts`:
+```ts
app.use('*', myMiddleware);
```
Or apply to a specific route group:
-```js
+```ts
api.use('/admin/*', adminOnlyMiddleware);
```
diff --git a/docs/architecture/backend/ROUTES.md b/docs/architecture/backend/ROUTES.md
index 7ed5bd3..4be5f1e 100644
--- a/docs/architecture/backend/ROUTES.md
+++ b/docs/architecture/backend/ROUTES.md
@@ -16,97 +16,97 @@ Every route is rate limited and can answer `429` with `Retry-After`; see `RATE_L
### Keys
| Method | Path | File | Purpose |
|---|---|---|---|
-| GET | `/api/keys` | `routes/keys.js` | Returns `{ youtube: bool, instagram: bool, cloudinary: bool }` - whether each API key is configured |
+| GET | `/api/keys` | `routes/keys.ts` | Returns `{ youtube: bool, instagram: bool, cloudinary: bool }` - whether each API key is configured |
### Accounts
-Handlers delegate to `services/accountConnect.js` and `services/accountRefresh.js`; the Instagram OAuth handlers delegate to `services/instagramOAuth.js`. See `SERVICES.md`.
+Handlers delegate to `services/accountConnect.ts` and `services/accountRefresh.ts`; the Instagram OAuth handlers delegate to `services/instagramOAuth.ts`. See `SERVICES.md`.
| Method | Path | File | Purpose |
|---|---|---|---|
-| GET | `/api/accounts` | `routes/accounts.js` | List all user accounts (tokens stripped via `safeAccount()`) |
-| POST | `/api/accounts` | `routes/accounts.js` | Add YouTube channel - resolves URL/handle to channel ID, fetches stats |
-| DELETE | `/api/accounts/:id` | `routes/accounts.js` | Remove account + invalidate Redis cache for that account |
-| POST | `/api/accounts/refresh-all` | `routes/accounts.js` | Refresh stats for every account; returns updated accounts list |
-| POST | `/api/accounts/:id/refresh` | `routes/accounts.js` | Refresh a single account's stats |
-| POST | `/api/accounts/instagram` | `routes/accounts.js` | Add Instagram account via a raw access token (for manual setup) |
-| POST | `/api/accounts/:id/refresh-ig-token` | `routes/accounts.js` | Extend Instagram long-lived token (valid up to 60 days; refresh when < 15 days remain) |
+| GET | `/api/accounts` | `routes/accounts.ts` | List all user accounts (tokens stripped via `safeAccount()`) |
+| POST | `/api/accounts` | `routes/accounts.ts` | Add YouTube channel - resolves URL/handle to channel ID, fetches stats |
+| DELETE | `/api/accounts/:id` | `routes/accounts.ts` | Remove account + invalidate Redis cache for that account |
+| POST | `/api/accounts/refresh-all` | `routes/accounts.ts` | Refresh stats for every account; returns updated accounts list |
+| POST | `/api/accounts/:id/refresh` | `routes/accounts.ts` | Refresh a single account's stats |
+| POST | `/api/accounts/instagram` | `routes/accounts.ts` | Add Instagram account via a raw access token (for manual setup) |
+| POST | `/api/accounts/:id/refresh-ig-token` | `routes/accounts.ts` | Extend Instagram long-lived token (valid up to 60 days; refresh when < 15 days remain) |
### Analytics
-Channel metrics, the comparison and the all videos filter live in `services/youtubeLibrary.js`; the channel backfill lives in `services/accountRefresh.js`.
+Channel metrics, the comparison and the all videos filter live in `services/youtubeLibrary.ts`; the channel backfill lives in `services/accountRefresh.ts`.
| Method | Path | File | Purpose |
|---|---|---|---|
-| GET | `/api/accounts/:id/analytics` | `routes/analytics.js` | Full YouTube analytics - fetches up to 500 videos, runs `computeVideoAnalytics()`, returns 50+ metrics |
-| GET | `/api/accounts/:id/videos` | `routes/analytics.js` | Returns cached video list (from Redis if available) |
-| GET | `/api/accounts/:id/ig-analytics` | `routes/analytics.js` | Instagram analytics - fetches up to 500 media with views, classifies each as reel, post, or video, runs `computeInstagramAnalytics()` |
-| GET | `/api/accounts/:id/ig-media` | `routes/analytics.js` | Returns the Instagram media list (with `contentType` and `viewCount`) from cache, fetching live on a miss |
-| GET | `/api/comparison` | `routes/analytics.js` | Cross-account comparison data for the Overview dashboard |
+| GET | `/api/accounts/:id/analytics` | `routes/analytics.ts` | Full YouTube analytics - fetches up to 500 videos, runs `computeVideoAnalytics()`, returns 50+ metrics |
+| GET | `/api/accounts/:id/videos` | `routes/analytics.ts` | Returns cached video list (from Redis if available) |
+| GET | `/api/accounts/:id/ig-analytics` | `routes/analytics.ts` | Instagram analytics - fetches up to 500 media with views, classifies each as reel, post, or video, runs `computeInstagramAnalytics()` |
+| GET | `/api/accounts/:id/ig-media` | `routes/analytics.ts` | Returns the Instagram media list (with `contentType` and `viewCount`) from cache, fetching live on a miss |
+| GET | `/api/comparison` | `routes/analytics.ts` | Cross-account comparison data for the Overview dashboard |
### Instagram OAuth
| Method | Path | File | Purpose |
|---|---|---|---|
-| GET | `/api/auth/instagram/url` | `routes/instagramAuth.js` | Generates Instagram OAuth URL with HMAC-signed state. Returns `{ url }`. |
+| GET | `/api/auth/instagram/url` | `routes/instagramAuth.ts` | Generates Instagram OAuth URL with HMAC-signed state. Returns `{ url }`. |
### Publishing
| Method | Path | File | Purpose |
|---|---|---|---|
-| GET | `/api/cloudinary-config` | `routes/publishing.js` | Returns `{ cloudName, uploadPreset }` for frontend Cloudinary upload |
-| GET | `/api/accounts/:id/ig-publishing-limit` | `routes/publishing.js` | Checks daily Instagram publishing quota remaining |
-| POST | `/api/accounts/:id/ig-publish` | `routes/publishing.js` | Creates Instagram media container via Graph API; returns `{ containerId }` |
-| GET | `/api/ig-container/:id/status` | `routes/publishing.js` | Polls container status (`FINISHED`, `IN_PROGRESS`, `ERROR`, `EXPIRED`) |
-| POST | `/api/accounts/:id/ig-media-publish` | `routes/publishing.js` | Publishes the container to Instagram; returns `{ mediaId }` |
+| GET | `/api/cloudinary-config` | `routes/publishing.ts` | Returns `{ cloudName, uploadPreset }` for frontend Cloudinary upload |
+| GET | `/api/accounts/:id/ig-publishing-limit` | `routes/publishing.ts` | Checks daily Instagram publishing quota remaining |
+| POST | `/api/accounts/:id/ig-publish` | `routes/publishing.ts` | Creates Instagram media container via Graph API; returns `{ containerId }` |
+| GET | `/api/ig-container/:id/status` | `routes/publishing.ts` | Polls container status (`FINISHED`, `IN_PROGRESS`, `ERROR`, `EXPIRED`) |
+| POST | `/api/accounts/:id/ig-media-publish` | `routes/publishing.ts` | Publishes the container to Instagram; returns `{ mediaId }` |
### Scheduled Posts
| Method | Path | File | Purpose |
|---|---|---|---|
-| GET | `/api/scheduled-posts` | `routes/scheduledPosts.js` | List all user's scheduled posts, ordered by `scheduled_at` ascending |
-| POST | `/api/scheduled-posts` | `routes/scheduledPosts.js` | Create a new scheduled post with `status: 'pending'` |
-| PUT | `/api/scheduled-posts/:id` | `routes/scheduledPosts.js` | Edit a pending post (caption, scheduled time, media, etc.) |
-| DELETE | `/api/scheduled-posts/:id` | `routes/scheduledPosts.js` | Delete a single post |
-| DELETE | `/api/scheduled-posts` | `routes/scheduledPosts.js` | Delete all posts except those with `status: 'publishing'` |
-| GET | `/api/process-scheduled` | `routes/scheduledPosts.js` | Manual trigger - runs `processScheduledPosts()` immediately (dev/test) |
-| POST | `/api/process-scheduled` | `routes/scheduledPosts.js` | Same as above |
+| GET | `/api/scheduled-posts` | `routes/scheduledPosts.ts` | List all user's scheduled posts, ordered by `scheduled_at` ascending |
+| POST | `/api/scheduled-posts` | `routes/scheduledPosts.ts` | Create a new scheduled post with `status: 'pending'` |
+| PUT | `/api/scheduled-posts/:id` | `routes/scheduledPosts.ts` | Edit a pending post (caption, scheduled time, media, etc.) |
+| DELETE | `/api/scheduled-posts/:id` | `routes/scheduledPosts.ts` | Delete a single post |
+| DELETE | `/api/scheduled-posts` | `routes/scheduledPosts.ts` | Delete all posts except those with `status: 'publishing'` |
+| GET | `/api/process-scheduled` | `routes/scheduledPosts.ts` | Manual trigger - runs `processScheduledPosts()` immediately (dev/test) |
+| POST | `/api/process-scheduled` | `routes/scheduledPosts.ts` | Same as above |
### Reddit
| Method | Path | File | Purpose |
|---|---|---|---|
-| POST | `/api/accounts/reddit` | `routes/accounts.js` | Add Reddit account by username + optional session cookie |
-| GET | `/api/accounts/:id/reddit-analytics` | `routes/reddit.js` | Fetch profile + posts + computed analytics; cached in Redis |
-| GET | `/api/accounts/:id/reddit-posts` | `routes/reddit.js` | Returns cached post list or live-fetched posts |
+| POST | `/api/accounts/reddit` | `routes/accounts.ts` | Add Reddit account by username + optional session cookie |
+| GET | `/api/accounts/:id/reddit-analytics` | `routes/reddit.ts` | Fetch profile + posts + computed analytics; cached in Redis |
+| GET | `/api/accounts/:id/reddit-posts` | `routes/reddit.ts` | Returns cached post list or live-fetched posts |
### Overview
| Method | Path | File | Purpose |
|---|---|---|---|
-| GET | `/api/overview` | `routes/overview.js` | Returns tracked content list + per-account analytics summary from Redis cache (no live API calls); used by the Overview dashboard to aggregate Total Content, Total Comments, Total Likes across all platforms |
+| GET | `/api/overview` | `routes/overview.ts` | Returns tracked content list + per-account analytics summary from Redis cache (no live API calls); used by the Overview dashboard to aggregate Total Content, Total Comments, Total Likes across all platforms |
### Tracked Content
-Link detection and the manual views and image checks live in `services/trackedContent.js`.
+Link detection and the manual views and image checks live in `services/trackedContent.ts`.
| Method | Path | File | Purpose |
|---|---|---|---|
-| GET | `/api/tracked-content` | `routes/trackedContent.js` | List all tracked items for the current user (Reddit posts and YouTube videos) |
-| POST | `/api/tracked-content` | `routes/trackedContent.js` | Add a URL to track; auto-detects Reddit or YouTube; fetches live data immediately |
-| PUT | `/api/tracked-content/:id` | `routes/trackedContent.js` | Update `label`, `category`, `accountId`, `manualViews`, or `imageUrl` for a tracked item. `manualViews` and `imageUrl` are Reddit-only (400 for YouTube) and `null` clears either. `manualViews` must be a whole number of 0 or more; `imageUrl` must parse as an `https:` URL |
-| DELETE | `/api/tracked-content/:id` | `routes/trackedContent.js` | Remove a tracked item |
-| POST | `/api/tracked-content/:id/refresh` | `routes/trackedContent.js` | Re-fetch live data from Reddit or YouTube API for one tracked item |
+| GET | `/api/tracked-content` | `routes/trackedContent.ts` | List all tracked items for the current user (Reddit posts and YouTube videos) |
+| POST | `/api/tracked-content` | `routes/trackedContent.ts` | Add a URL to track; auto-detects Reddit or YouTube; fetches live data immediately |
+| PUT | `/api/tracked-content/:id` | `routes/trackedContent.ts` | Update `label`, `category`, `accountId`, `manualViews`, or `imageUrl` for a tracked item. `manualViews` and `imageUrl` are Reddit-only (400 for YouTube) and `null` clears either. `manualViews` must be a whole number of 0 or more; `imageUrl` must parse as an `https:` URL |
+| DELETE | `/api/tracked-content/:id` | `routes/trackedContent.ts` | Remove a tracked item |
+| POST | `/api/tracked-content/:id/refresh` | `routes/trackedContent.ts` | Re-fetch live data from Reddit or YouTube API for one tracked item |
### Settings
| Method | Path | File | Purpose |
|---|---|---|---|
-| GET | `/api/settings/github` | `routes/settings.js` | Retrieve GitHub PAT + repo config for the current user |
-| PUT | `/api/settings/github` | `routes/settings.js` | Save GitHub PAT + repo config |
+| GET | `/api/settings/github` | `routes/settings.ts` | Retrieve GitHub PAT + repo config for the current user |
+| PUT | `/api/settings/github` | `routes/settings.ts` | Save GitHub PAT + repo config |
## Adding a New Route
See `docs/features/NEW_API_ENDPOINT.md` for the complete workflow.
**Quick checklist:**
-1. Create `backend/routes/myFeature.js` (copy an existing route file as a template)
+1. Add the request and response types to `shared/types/`, then create `backend/routes/myFeature.ts` with `new Hono<AppEnv>()` (copy an existing route file as a template)
2. Export the router as default
-3. Import and mount in `backend/server.js` via `api.route('/', myFeatureRouter)`
-4. Add all db operations to `backend/lib/db.js`
+3. Import and mount in `backend/server.ts` via `api.route('/', myFeatureRouter)`
+4. Add all db operations to `backend/lib/db.ts`
5. Update `docs/architecture/backend/ROUTES.md` (this file)
-6. Update `frontend/src/services/api.js` with corresponding frontend methods
+6. Update `frontend/src/services/api.ts` with corresponding frontend methods that return the shared types, then run `npm run typecheck`
diff --git a/docs/architecture/backend/SERVICES.md b/docs/architecture/backend/SERVICES.md
index 70cd467..961d167 100644
--- a/docs/architecture/backend/SERVICES.md
+++ b/docs/architecture/backend/SERVICES.md
@@ -2,26 +2,26 @@
Services in `backend/services/` contain all logic for communicating with external APIs (YouTube, Instagram) and computing analytics. Route handlers call services; services never import from routes.
-## Shared analytics math (`backend/services/analyticsMath.js`)
+## Shared analytics math (`backend/services/analyticsMath.ts`)
-Pure helpers whose formulas are identical in the Instagram and Reddit analytics: `DAY_NAMES`, `DAY_MS`, `sumOf`, `roundedAverage`, `medianOf`, `countWithinDays` (inclusive `<=`), `postFrequency` (posts per week and month over the dated span), `consistencyScore` (coefficient of variation, needs 3 values), `bestToAverageRatio` (virality), `pickHighest` and `monthKey` (local time). YouTube keeps its own recency (strict `<`) and weekly consistency formulas: `youtubeAnalytics.js` imports `DAY_MS`, `sumOf`, `roundedAverage` and `medianOf`, and `youtubeTrends.js` imports `DAY_NAMES`, `DAY_MS` and `monthKey`.
+Pure helpers whose formulas are identical in the Instagram and Reddit analytics: `DAY_NAMES`, `DAY_MS`, `sumOf`, `roundedAverage`, `medianOf`, `countWithinDays` (inclusive `<=`), `postFrequency` (posts per week and month over the dated span), `consistencyScore` (coefficient of variation, needs 3 values), `bestToAverageRatio` (virality), `pickHighest` and `monthKey` (local time). YouTube keeps its own recency (strict `<`) and weekly consistency formulas: `youtubeAnalytics.ts` imports `DAY_MS`, `sumOf`, `roundedAverage` and `medianOf`, and `youtubeTrends.ts` imports `DAY_NAMES`, `DAY_MS` and `monthKey`.
---
-## Instagram (`backend/services/instagram*.js`)
+## Instagram (`backend/services/instagram*.ts`)
-`services/instagram.js` is a barrel that re-exports the public names below, so routes and the scheduler import from it unchanged. Tests in `backend/tests/services/` import the individual modules directly. Each module imports its siblings directly, never the barrel.
+`services/instagram.ts` is a barrel that re-exports the public names below, so routes and the scheduler import from it unchanged. Tests in `backend/tests/services/` import the individual modules directly. Each module imports its siblings directly, never the barrel.
| Module | Contents |
|---|---|
-| `instagramApi.js` | `igFetch(endpoint, params, retries)` transport (15 s timeout, one retry on abort, `EAI_AGAIN` or `ECONNRESET`, no API version prefix for `/oauth`, `/access_token`, `/refresh_access_token`) and `fetchInstagramProfile` |
-| `instagramTokens.js` | `exchangeForLongLivedToken`, `refreshLongLivedToken`, `autoRefreshInstagramTokens` |
-| `instagramMedia.js` | `classifyInstagramMedia`, `extractInstagramViews`, `normalizeInstagramMedia`, paged `fetchInstagramMedia` |
-| `instagramContentTypes.js` | `CONTENT_TYPES`, `summarizeContentTypes`, per type stats used by the analytics |
-| `instagramTiming.js` | Posts by day of week and hour, best posting day and hour, monthly breakdown |
-| `instagramCaptions.js` | Hashtag analysis and caption length correlation |
-| `instagramAnalytics.js` | `computeInstagramAnalytics` orchestrator, the empty state and the engagement, views and ranking helpers |
-| `instagramPublishing.js` | `buildMediaParams`, one helper per media type |
+| `instagramApi.ts` | `igFetch(endpoint, params, retries)` transport (15 s timeout, one retry on abort, `EAI_AGAIN` or `ECONNRESET`, no API version prefix for `/oauth`, `/access_token`, `/refresh_access_token`) and `fetchInstagramProfile` |
+| `instagramTokens.ts` | `exchangeForLongLivedToken`, `refreshLongLivedToken`, `autoRefreshInstagramTokens` |
+| `instagramMedia.ts` | `classifyInstagramMedia`, `extractInstagramViews`, `normalizeInstagramMedia`, paged `fetchInstagramMedia` |
+| `instagramContentTypes.ts` | `CONTENT_TYPES`, `summarizeContentTypes`, per type stats used by the analytics |
+| `instagramTiming.ts` | Posts by day of week and hour, best posting day and hour, monthly breakdown |
+| `instagramCaptions.ts` | Hashtag analysis and caption length correlation |
+| `instagramAnalytics.ts` | `computeInstagramAnalytics` orchestrator, the empty state and the engagement, views and ranking helpers |
+| `instagramPublishing.ts` | `buildMediaParams`, one helper per media type |
### Key Functions
@@ -59,12 +59,15 @@ Views come from the media insights `views` metric (the replacement for `plays`,
### `safeAccount(account)`
-Strips the `accessToken` field before the account object is returned in any API response:
+`safeAccount()` lives in `backend/lib/safeAccount.ts`. It removes every field listed in `SECRET_FIELDS` (`accessToken`, `cookie`, `encryptedPassword`, `encryptedTotpSecret`, `authToken`, `ct0`) and adds `hasCookie`, returning the `SafeAccount` type from `shared/types/domain.ts`:
-```js
-function safeAccount(account) {
- const { accessToken, ...safe } = account;
- return safe;
+```ts
+const SECRET_FIELDS: (keyof Account)[] = ['accessToken', 'cookie', 'encryptedPassword', 'encryptedTotpSecret', 'authToken', 'ct0'];
+
+export function safeAccount(account: Account): SafeAccount {
+ const copy: Partial<Account> & { hasCookie: boolean } = { ...account, hasCookie: !!account.cookie };
+ for (const field of SECRET_FIELDS) delete copy[field];
+ return copy as SafeAccount;
}
```
@@ -72,20 +75,20 @@ function safeAccount(account) {
---
-## YouTube (`backend/services/youtube*.js`)
+## YouTube (`backend/services/youtube*.ts`)
-`services/youtube.js` is a barrel that re-exports `resolveChannelId`, `fetchChannelData`, `fetchAllVideos`, `fetchTrackedYouTubeData` and `computeVideoAnalytics`, so importers are unchanged.
+`services/youtube.ts` is a barrel that re-exports `resolveChannelId`, `fetchChannelData`, `fetchAllVideos`, `fetchTrackedYouTubeData` and `computeVideoAnalytics`, so importers are unchanged.
| Module | Contents |
|---|---|
-| `youtubeApi.js` | `ytFetch(endpoint, params, apiKey)` (adds `key` to the params object it is given; errors carry `reason` and `status`) and `optionalCount` (null for a hidden or missing count) |
-| `youtubeChannels.js` | Channel id extraction from URLs and handles, the handle, username, search lookup chain, `resolveChannelId`, `fetchChannelData` |
-| `youtubeVideos.js` | `normalizeYouTubeVideo`, the playlist page fetch that treats `playlistNotFound` as no videos, `fetchAllVideos` |
-| `youtubeTracked.js` | `extractYouTubeVideoId`, `fetchTrackedYouTubeData` |
-| `youtubeFormat.js` | `parseDuration`, `formatCompact`, `formatDuration`, `formatVideoSummary` |
-| `youtubeAnalytics.js` | `computeVideoAnalytics` orchestrator, the empty state, totals, durations, rankings, Shorts split, format flags |
-| `youtubeTrends.js` | Publish day and hour distribution, categories, tags, recency counts, upload frequency, weekly consistency, views histogram, monthly trends |
-| `youtubeLibrary.js` | Pure helpers for `routes/analytics.js`: `channelMetrics` (channel age, ratios and estimates; a channel without `publishedAt` counts as 365 days old), `accountComparison` (rankings and totals for `/comparison`), `filterAndSortVideos` (search, view range and sort for `/videos/all`) |
+| `youtubeApi.ts` | `ytFetch(endpoint, params, apiKey)` (adds `key` to the params object it is given; errors carry `reason` and `status`) and `optionalCount` (null for a hidden or missing count) |
+| `youtubeChannels.ts` | Channel id extraction from URLs and handles, the handle, username, search lookup chain, `resolveChannelId`, `fetchChannelData` |
+| `youtubeVideos.ts` | `normalizeYouTubeVideo`, the playlist page fetch that treats `playlistNotFound` as no videos, `fetchAllVideos` |
+| `youtubeTracked.ts` | `extractYouTubeVideoId`, `fetchTrackedYouTubeData` |
+| `youtubeFormat.ts` | `parseDuration`, `formatCompact`, `formatDuration`, `formatVideoSummary` |
+| `youtubeAnalytics.ts` | `computeVideoAnalytics` orchestrator, the empty state, totals, durations, rankings, Shorts split, format flags |
+| `youtubeTrends.ts` | Publish day and hour distribution, categories, tags, recency counts, upload frequency, weekly consistency, views histogram, monthly trends |
+| `youtubeLibrary.ts` | Pure helpers for `routes/analytics.ts`: `channelMetrics` (channel age, ratios and estimates; a channel without `publishedAt` counts as 365 days old), `accountComparison` (rankings and totals for `/comparison`), `filterAndSortVideos` (search, view range and sort for `/videos/all`) |
### Key Functions
@@ -107,7 +110,7 @@ function safeAccount(account) {
- Monthly breakdown of uploads and views
- Category distribution
-`computeInstagramAnalytics()` (in `instagramAnalytics.js`) returns:
+`computeInstagramAnalytics()` (in `instagramAnalytics.ts`) returns:
- Engagement rate (likes + comments / followers)
- Average likes, comments per post
- Best performing post
@@ -118,11 +121,11 @@ function safeAccount(account) {
---
-## `backend/services/reddit.js`
+## `backend/services/reddit.ts`
### HTTP Client
-`reddit.js` holds the API code. All Reddit public JSON API calls go through `redditFetch(path, cookie)`, and `normalizeRedditPost()` maps each submitted post to the cached post shape. Requests include a descriptive `User-Agent` header (required by Reddit). Cookie is optional - if provided, it is sent as `Cookie: reddit_session=<value>` for private account access and higher rate limits.
+`reddit.ts` holds the API code. All Reddit public JSON API calls go through `redditFetch(path, cookie)`, and `normalizeRedditPost()` maps each submitted post to the cached post shape. Requests include a descriptive `User-Agent` header (required by Reddit). Cookie is optional - if provided, it is sent as `Cookie: reddit_session=<value>` for private account access and higher rate limits.
### Key Functions
@@ -130,12 +133,12 @@ function safeAccount(account) {
|---|---|
| `fetchRedditProfile(username, cookie)` | Fetches profile data from `/user/{username}/about.json` |
| `fetchRedditPosts(username, cookie, limit)` | Paginates submitted posts up to `limit` (default 100) via `/user/{username}/submitted.json` |
-| `computeRedditAnalytics(profile, posts)` | Lives in `redditAnalytics.js` (re-exported by `reddit.js`); computes score stats, subreddit breakdown, media type distribution, posting time patterns, monthly breakdown, virality/consistency scores using the shared helpers in `analyticsMath.js` |
+| `computeRedditAnalytics(profile, posts)` | Lives in `redditAnalytics.ts` (re-exported by `reddit.ts`); computes score stats, subreddit breakdown, media type distribution, posting time patterns, monthly breakdown, virality/consistency scores using the shared helpers in `analyticsMath.ts` |
| `fetchTrackedPostData(postUrl, cookie)` | Fetches score, comments, and metadata for any public Reddit post URL using the `.json` trick; optionally uses a session cookie |
### Credentials in responses
-Account responses for every platform pass through `safeAccount()` in `backend/lib/safeAccount.js`, which strips the Reddit `cookie` along with the Instagram `accessToken` and sets `hasCookie` so the frontend can show session status.
+Account responses for every platform pass through `safeAccount()` in `backend/lib/safeAccount.ts`, which strips the Reddit `cookie` along with the Instagram `accessToken` and sets `hasCookie` so the frontend can show session status.
### No Worker secrets required
@@ -143,48 +146,49 @@ Reddit integration requires no Worker secrets. The session cookie is a per-user
---
-## Accounts (`accountFactory.js`, `accountConnect.js`, `accountRefresh.js`)
+## Accounts (`accountFactory.ts`, `accountConnect.ts`, `accountRefresh.ts`)
-The account routes in `routes/accounts.js` only parse the request, check required fields and shape the response; the work lives here.
+The account routes in `routes/accounts.ts` only parse the request, check required fields and shape the response; the work lives here.
| Module | Contents |
|---|---|
-| `accountFactory.js` | Pure builders: `newAccountId`, `tokenExpiryIso` (null without a lifetime), `buildYouTubeAccount`, `buildRedditAccount`, `buildInstagramAccount` |
-| `accountConnect.js` | `addYouTubeAccount`, `addRedditAccount`, `addInstagramAccount` (tries the long-lived exchange when `INSTAGRAM_APP_SECRET` is set and keeps the pasted token if it fails), `refreshInstagramToken` |
-| `accountRefresh.js` | `fetchAccountUpdates` (profile fields per platform; a single refresh updates more fields than refresh-all), `refreshAccount`, `refreshAllAccounts` (`Promise.allSettled`, results aligned with the account list by index), `backfillChannelData` (fills channel fields for a YouTube account without `publishedAt` when its analytics load; a failure is logged and skipped) |
+| `accountFactory.ts` | Pure builders: `newAccountId`, `tokenExpiryIso` (null without a lifetime), `buildYouTubeAccount`, `buildRedditAccount`, `buildInstagramAccount` |
+| `accountConnect.ts` | `addYouTubeAccount`, `addRedditAccount`, `addInstagramAccount` (tries the long-lived exchange when `INSTAGRAM_APP_SECRET` is set and keeps the pasted token if it fails), `refreshInstagramToken` |
+| `accountRefresh.ts` | `fetchAccountUpdates` (profile fields per platform; a single refresh updates more fields than refresh-all), `refreshAccount`, `refreshAllAccounts` (`Promise.allSettled`, results aligned with the account list by index), `backfillChannelData` (fills channel fields for a YouTube account without `publishedAt` when its analytics load; a failure is logged and skipped) |
Duplicate accounts throw an `Error` whose message the route returns with status 400, the same shape as any other failure. Failures that need another status (404 for a missing account, 400 for a missing credential) come back as `{ failure: { status, message } }`.
---
-## Tracked content (`trackedContent.js`)
+## Tracked content (`trackedContent.ts`)
-Pure rules for `routes/trackedContent.js`: `detectContentType(url)` (`reddit`, `youtube` or `null`), `manualViewsPatch(value, isYouTube)` and `imageUrlPatch(value, isYouTube)`. The two patch helpers return `{ patch }` for the route to merge into the item's `data`, or `{ error }` for a 400 response. Empty values clear the field, YouTube items refuse both, views must be whole numbers of 0 or more, and images must be `https` URLs.
+Pure rules for `routes/trackedContent.ts`: `detectContentType(url)` (`reddit`, `youtube` or `null`), `manualViewsPatch(value, isYouTube)` and `imageUrlPatch(value, isYouTube)`. The two patch helpers return `{ patch }` for the route to merge into the item's `data`, or `{ error }` for a 400 response. Empty values clear the field, YouTube items refuse both, views must be whole numbers of 0 or more, and images must be `https` URLs.
---
-## Overview summary (`overviewSummary.js`)
+## Overview summary (`overviewSummary.ts`)
-Used by `routes/overview.js`. `summarizeAccountCaches(accounts, { redis, userId, apiKey })` reads each account's Redis cache in parallel (`Promise.allSettled`) and returns `{ analyticsCache, warmTasks }`. A warm account gets its totals (`cacheWarmed: true`); an account with no cache gets `cacheWarmed: false`, and when Redis and the account's credentials are present its background fetch starts at once and `syncing` is `true`. An account whose cache read fails is left out of `analyticsCache`. The route passes `warmTasks` to `waitUntil` so the response never waits for them.
+Used by `routes/overview.ts`. `summarizeAccountCaches(accounts, { redis, userId, apiKey })` reads each account's Redis cache in parallel (`Promise.allSettled`) and returns `{ analyticsCache, warmTasks }`. A warm account gets its totals (`cacheWarmed: true`); an account with no cache gets `cacheWarmed: false`, and when Redis and the account's credentials are present its background fetch starts at once and `syncing` is `true`. An account whose cache read fails is left out of `analyticsCache`. The route passes `warmTasks` to `waitUntil` so the response never waits for them.
---
-## Instagram OAuth (`instagramOAuth.js`)
+## Instagram OAuth (`instagramOAuth.ts`)
-Used by `routes/instagramAuth.js`. `readInstagramOAuthConfig(env)` strips a leading byte order mark and whitespace from the app id, secret and URLs, drops a trailing slash from `BACKEND_URL`, and falls back to `http://localhost:8787` and `http://localhost:5173`. `buildAuthorizationUrl` signs the state with the app secret. `connectInstagramFromOAuth` exchanges the code (stripping a trailing `#_`), upgrades to a long-lived token when Instagram allows it (otherwise keeps the short-lived token with no expiry), fetches the profile and returns `'already_added'` or `'connected'`. The route turns those into the `ig_error` and `ig_connected` redirects.
+Used by `routes/instagramAuth.ts`. `readInstagramOAuthConfig(env)` strips a leading byte order mark and whitespace from the app id, secret and URLs, drops a trailing slash from `BACKEND_URL`, and falls back to `http://localhost:8787` and `http://localhost:5173`. `buildAuthorizationUrl` signs the state with the app secret. `connectInstagramFromOAuth` exchanges the code (stripping a trailing `#_`), upgrades to a long-lived token when Instagram allows it (otherwise keeps the short-lived token with no expiry), fetches the profile and returns `'already_added'` or `'connected'`. The route turns those into the `ig_error` and `ig_connected` redirects.
---
## Shared Instagram publishing parameters
-`buildMediaParams(post, accessToken)` in `services/instagramPublishing.js` (re-exported by `services/instagram.js`) builds the Graph API container parameters for photos, Reels, Stories and carousel items. The publish route (`routes/publishing.js`) and the cron scheduler (`utils/scheduler.js`) both call it. `scripts/publish-scheduled.js` keeps its own copy on purpose: it runs in GitHub Actions with zero npm dependencies and cannot import Worker code.
+`buildMediaParams(post, accessToken)` in `services/instagramPublishing.ts` (re-exported by `services/instagram.ts`) builds the Graph API container parameters for photos, Reels, Stories and carousel items. The publish route (`routes/publishing.ts`) and the cron scheduler (`utils/scheduler.ts`) both call it. `scripts/publish-scheduled.ts` keeps its own copy on purpose: it runs in GitHub Actions with zero npm dependencies and cannot import Worker code.
---
## Adding a New Service
-1. Create `backend/services/myPlatform.js`
-2. Define an internal fetch helper (`myPlatformFetch`) that handles base URL, auth headers, and error extraction
-3. Export named functions for each operation (fetch data, exchange tokens, compute analytics)
-4. If the platform requires OAuth, add token exchange functions following the Instagram pattern
-5. Update `docs/architecture/backend/SERVICES.md` (this file)
+1. Create `backend/services/myPlatform.ts`
+2. Define an internal fetch helper (`myPlatformFetch<T>()`) that handles base URL, auth headers, and error extraction, and casts the parsed JSON to the expected payload type once
+3. Describe the raw upstream payloads with interfaces in the service file (covering only the fields the code reads), and put the shapes the API returns in `shared/types/`
+4. Export named functions for each operation (fetch data, exchange tokens, compute analytics), each with a declared return type
+5. If the platform requires OAuth, add token exchange functions following the Instagram pattern
+6. Update `docs/architecture/backend/SERVICES.md` (this file)
diff --git a/docs/architecture/cloudflare/CI_CD.md b/docs/architecture/cloudflare/CI_CD.md
index f64edc5..81cfcea 100644
--- a/docs/architecture/cloudflare/CI_CD.md
+++ b/docs/architecture/cloudflare/CI_CD.md
@@ -2,15 +2,46 @@
## Workflows
+| Workflow | Runs on | Purpose |
+|---|---|---|
+| `ci.yml` | Pull requests, pushes to any branch except `main`, manual | Type check, lint, test, build and bundle before anything reaches `main` |
+| `deploy-backend.yml` | Pushes to `main` that touch the backend, manual | Type check and test the backend, then deploy the Worker |
+| `deploy-frontend.yml` | Pushes to `main` that touch the frontend, manual | Type check and test the frontend, then build and deploy to Pages |
+| `publish-scheduled.yml` | Every 15 minutes, manual | Publish due Instagram posts (fallback for the Worker cron) |
+
+Nothing compiles TypeScript ahead of time: Wrangler and Vite strip the types while bundling, and Node strips them when it runs tests and `scripts/publish-scheduled.ts`. None of those steps checks types, so each workflow that ships code runs `tsc` first.
+
+### `ci.yml`
+
+**Trigger:** `pull_request` (any branch), `push` to every branch except `main`, and `workflow_dispatch`. There are no path filters: every pull request and branch push is checked.
+
+**What it does (one job, "Type check, lint, test, build"):**
+1. Checkout repo
+2. `actions/setup-node@v4` with Node 24 and the npm cache keyed on the root `package-lock.json`
+3. `npm ci` at the repository root
+4. `npm run typecheck` - every TypeScript project: backend, backend tests, frontend, frontend tooling and tests, scripts
+5. `npm run lint` - ESLint over the whole repository
+6. `npm test` - backend then frontend tests
+7. `npm run build` - Vite production build of the frontend (without the `VITE_*` secrets)
+8. `npx wrangler deploy --dry-run --outdir dist` in `backend/` - bundles the Worker without deploying, which catches import and bundling errors
+
+**Required GitHub secrets:** none.
+
+---
+
### `deploy-backend.yml`
-**Trigger:** Push to `main` branch, when files under `backend/**`, the root `package.json`, the root `package-lock.json` or `.github/workflows/deploy-backend.yml` change; also `workflow_dispatch` for a manual run
+**Trigger:** Push to `main` branch, when files under `backend/**` or `shared/**`, `tsconfig.base.json`, the root `package.json`, the root `package-lock.json` or `.github/workflows/deploy-backend.yml` change; also `workflow_dispatch` for a manual run
**What it does:**
1. Checkout repo
2. `actions/setup-node@v4` with Node 24 and the npm cache keyed on the root `package-lock.json`
3. `npm ci` at the repository root, which installs every workspace, including Wrangler
-4. Run `wrangler deploy` via `cloudflare/wrangler-action@v4` with `workingDirectory: backend`. The action finds the Wrangler installed from the lockfile (3.114.17) and uses it instead of installing its own default version.
+4. `npm run typecheck --workspace backend` - checks the Worker source and the backend tests
+5. `npm test --workspace backend`
+6. Run `wrangler deploy` via `cloudflare/wrangler-action@v4` with `workingDirectory: backend`. The action finds the Wrangler installed from the lockfile (3.114.17) and uses it instead of installing its own default version.
+
+A type error or failing test stops the run before the deploy step.
**Required GitHub secrets:**
- `CLOUDFLARE_API_TOKEN` - API token with Worker deploy permission
@@ -22,14 +53,16 @@
### `deploy-frontend.yml`
-**Trigger:** Push to `main` branch, when files under `frontend/**`, the root `package.json`, the root `package-lock.json` or `.github/workflows/deploy-frontend.yml` change; also `workflow_dispatch` for a manual run
+**Trigger:** Push to `main` branch, when files under `frontend/**` or `shared/**`, `tsconfig.base.json`, the root `package.json`, the root `package-lock.json` or `.github/workflows/deploy-frontend.yml` change; also `workflow_dispatch` for a manual run
**What it does:**
1. Checkout repo
2. `actions/setup-node@v4` with Node 24 and the npm cache keyed on the root `package-lock.json`
3. `npm ci` at the repository root, which installs every workspace
-4. `npm run build --workspace frontend` - Vite builds to `frontend/dist/`
-5. Deploy `dist/` to Cloudflare Pages via `wrangler pages deploy` (`cloudflare/wrangler-action@v4` with `workingDirectory: frontend`, using the Wrangler from the lockfile)
+4. `npm run typecheck --workspace frontend` - checks `frontend/src` (`tsconfig.json`) and `vite.config.ts` plus the frontend tests (`tsconfig.node.json`)
+5. `npm test --workspace frontend`
+6. `npm run build --workspace frontend` - Vite builds to `frontend/dist/`
+7. Deploy `dist/` to Cloudflare Pages via `wrangler pages deploy` (`cloudflare/wrangler-action@v4` with `workingDirectory: frontend`, using the Wrangler from the lockfile)
**Required GitHub secrets:**
- `CLOUDFLARE_API_TOKEN`
@@ -40,7 +73,7 @@
- `VITE_ADMIN_EMAIL` - optional, injected at build time; the administrator contact shown in the app
- `VITE_GOOGLE_CLIENT_ID` - optional, injected at build time; enables the Sign in with Google button
-**Note:** `VITE_*` variables are baked into the built JS bundle at build time. They are not runtime environment variables.
+**Note:** `VITE_*` variables are baked into the built bundle at build time. They are not runtime environment variables.
---
@@ -52,8 +85,8 @@
**What it does:**
1. Checkout repo
-2. Setup Node.js 20
-3. `node scripts/publish-scheduled.js`
+2. `actions/setup-node@v4` with Node 24 (no npm cache and no install: the script has no dependencies)
+3. `node scripts/publish-scheduled.ts` - Node runs the TypeScript file directly by stripping the types (Node 22.18 or newer; the workflow uses 24)
**Required GitHub secrets:**
- `SUPABASE_URL` - the Supabase project URL
@@ -61,18 +94,24 @@
**This is the GitHub Actions fallback for the Worker cron.** Both this workflow and the Worker cron (`*/15`) run the same publishing logic against the same Supabase table. The `publishing` status mutex prevents double-publishing.
+The script is type-checked by `npm run typecheck` (`scripts/tsconfig.json`) in `ci.yml`, not by this workflow.
+
---
## Path Filtering
-GitHub Actions path filters mean:
+The deploy workflows use path filters; `ci.yml` does not.
+
- Editing `frontend/` only -> triggers `deploy-frontend.yml`, not `deploy-backend.yml`
- Editing `backend/` only -> triggers `deploy-backend.yml`, not `deploy-frontend.yml`
+- Editing `shared/` or `tsconfig.base.json` -> triggers both, because both apps import the shared types and extend the base config
- Editing the root `package.json` or `package-lock.json` -> triggers both, because the single lockfile pins the dependencies of both apps
-- Editing root tooling config (`eslint.config.mjs`, `.prettierrc.json`, `.editorconfig`) -> triggers nothing; no workflow runs lint or tests
+- Editing root tooling config (`eslint.config.mjs`, `.prettierrc.json`, `.editorconfig`) -> triggers no deploy; `ci.yml` checks it on the branch or pull request before it reaches `main`
- Editing `scripts/` -> triggers neither deploy workflow (only `publish-scheduled.yml` on its cron)
-- Editing `docs/` -> triggers nothing
-- Editing `CLAUDE.md`, `DECISIONS.md`, etc. -> triggers nothing
+- Editing `docs/` -> triggers no deploy
+- Editing `CLAUDE.md`, `DECISIONS.md`, etc. -> triggers no deploy
+
+`ci.yml` runs on every pull request and every push to a branch other than `main`, whatever changed.
## Deployment Verification
@@ -94,6 +133,7 @@ Trigger `publish-scheduled.yml` manually via GitHub Actions UI -> Actions -> "In
1. Create `.github/workflows/my-workflow.yml`
2. Add appropriate path filters to avoid unnecessary runs
-3. If the workflow needs project dependencies, run `actions/setup-node` with `cache-dependency-path: package-lock.json` and `npm ci` at the repository root; there are no lockfiles inside `backend/` or `frontend/`
-4. Document it in `docs/architecture/cloudflare/CI_CD.md` (this file)
-5. Add any required secrets via GitHub repo -> Settings -> Secrets -> Actions
+3. If the workflow needs project dependencies, run `actions/setup-node` with Node 24, `cache-dependency-path: package-lock.json` and `npm ci` at the repository root; there are no lockfiles inside `backend/` or `frontend/`
+4. If it ships code, run `npm run typecheck` (or the workspace's `typecheck` script) before the deploy step
+5. Document it in `docs/architecture/cloudflare/CI_CD.md` (this file)
+6. Add any required secrets via GitHub repo -> Settings -> Secrets -> Actions
diff --git a/docs/architecture/cloudflare/PAGES.md b/docs/architecture/cloudflare/PAGES.md
index 60552a9..eda50ee 100644
--- a/docs/architecture/cloudflare/PAGES.md
+++ b/docs/architecture/cloudflare/PAGES.md
@@ -12,10 +12,12 @@ The React frontend is deployed to Cloudflare Pages. It is a static SPA - all rou
| Build command | `npm ci && npm run build` |
| Build output directory | `frontend/dist` |
| Root directory | `/` (repo root) |
-| Node.js version | 22 or later (the deploy workflow uses 24; Vite 7 needs 20.19 or later) |
+| Node.js version | 22.18 or later (the root `package.json` `engines` field; the deploy workflow uses 24) |
These are configured in the Cloudflare Pages project settings, not in a file. The repository is an npm workspaces monorepo: the install runs once at the root against the root `package-lock.json` (there is no lockfile in `frontend/`), and the root `build` script runs `npm run build --workspace frontend`.
+The build is `vite build` with `frontend/vite.config.ts`, starting from `frontend/index.html`, which loads `/src/main.tsx`. Vite strips the TypeScript types and does not check them, so a Pages build connected directly to the repository does not type-check. The GitHub Actions deploy runs `npm run typecheck --workspace frontend` and the frontend tests before it builds.
+
## SPA Fallback
All requests that don't match a static file should serve `index.html` so React Router can handle the path. This is configured in:
@@ -48,12 +50,13 @@ Vite exposes them at runtime as `import.meta.env.VITE_*`.
## Deployment
-Cloudflare Pages deploys automatically on every push to `main` that changes files in `frontend/`, the root `package.json` or the root `package-lock.json`. This is configured in `.github/workflows/deploy-frontend.yml`, which runs `npm ci` at the root, builds with `npm run build --workspace frontend` and uploads `frontend/dist` with the Wrangler version from the lockfile.
+Cloudflare Pages deploys automatically on every push to `main` that changes files in `frontend/` or `shared/`, `tsconfig.base.json`, the root `package.json` or the root `package-lock.json`. This is configured in `.github/workflows/deploy-frontend.yml`, which runs `npm ci` at the root, type-checks and tests the frontend, builds with `npm run build --workspace frontend` and uploads `frontend/dist` with the Wrangler version from the lockfile.
Manual deployment (emergency or first setup), from the repository root:
```bash
npm ci
+npm run typecheck
npm run build
cd frontend
npx wrangler pages deploy dist --project-name=twiligent
@@ -73,7 +76,7 @@ From the repository root, start the Vite dev server (port 5173) and the backend
npm run dev
```
-The frontend calls the Worker at `VITE_API_URL`, which defaults to `http://localhost:8787/api` when unset (see `frontend/src/services/api.js`); Vite does not proxy requests. To run the frontend alone, use `npm run dev:frontend`.
+The frontend calls the Worker at `VITE_API_URL`, which defaults to `http://localhost:8787/api` when unset (see `frontend/src/services/api.ts`); Vite does not proxy requests. To run the frontend alone, use `npm run dev:frontend`.
## First-Time Setup
diff --git a/docs/architecture/cloudflare/WORKERS.md b/docs/architecture/cloudflare/WORKERS.md
index 636f668..193b176 100644
--- a/docs/architecture/cloudflare/WORKERS.md
+++ b/docs/architecture/cloudflare/WORKERS.md
@@ -4,7 +4,7 @@
```toml
name = "twiligent"
-main = "server.js"
+main = "server.ts"
compatibility_date = "2025-01-01"
[triggers]
@@ -12,7 +12,7 @@ crons = ["*/15 * * * *", "0 0 * * *"]
```
- `name` - the Worker name as deployed on Cloudflare; also determines the default URL
-- `main` - entry point file (ES module)
+- `main` - entry point file (`backend/server.ts`). Wrangler bundles it with esbuild, which strips the TypeScript types without checking them; `npm run typecheck` is the check
- `compatibility_date` - pins the Workers runtime API version
- `crons` - cron trigger schedules (see `docs/architecture/backend/CRON.md`)
@@ -20,20 +20,22 @@ crons = ["*/15 * * * *", "0 0 * * *"]
The Worker exports two handlers:
-```js
+```ts
export default {
fetch: app.fetch, // handles HTTP requests (the Hono app)
- async scheduled(event, env, ctx) { // handles cron triggers
+ async scheduled(event: ScheduledController, env: Env, ctx: ExecutionContext) { // handles cron triggers
// event.cron - the cron expression that fired
// env - Worker environment bindings (secrets + vars)
// ctx.waitUntil(promise) - keeps Worker alive for background work
- }
-};
+ },
+} satisfies ExportedHandler<Env>;
```
+`ScheduledController`, `ExecutionContext` and `ExportedHandler` come from `@cloudflare/workers-types`, which `backend/tsconfig.json` loads as its only ambient types.
+
## Environment Bindings (Secrets)
-All secrets are set via `npx wrangler secret put <NAME>`, run from `backend/`. They are available at runtime as `env.NAME` or `c.env.NAME`.
+All secrets are set via `npx wrangler secret put <NAME>`, run from `backend/`. They are available at runtime as `env.NAME` or `c.env.NAME`, typed by the `Env` interface in `backend/types/env.ts`. The three Supabase values are declared as `string`; the rest are optional (`?: string`), so code that reads them handles the missing case.
| Secret | Required | Purpose |
|---|---|---|
@@ -49,6 +51,7 @@ All secrets are set via `npx wrangler secret put <NAME>`, run from `backend/`. T
| `FRONTEND_URL` | Yes | Frontend URL (for post-OAuth redirect back to the SPA) |
| `UPSTASH_REDIS_REST_URL` | Optional | Upstash Redis endpoint; caching disabled if absent |
| `UPSTASH_REDIS_REST_TOKEN` | Optional | Upstash auth token |
+| `REDDIT_ENCRYPTION_KEY` | Unused | Declared in `Env` but read nowhere; Reddit accounts store a browser session cookie and no password is encrypted. Do not set it |
### Setting secrets
@@ -84,7 +87,7 @@ Run locally from the repository root: `npm run dev:backend` (Worker only, port 8
These are hard constraints imposed by the Cloudflare Workers runtime. Violating them causes runtime errors:
-1. **No Node.js APIs.** No `fs`, `Buffer`, `path`, `process.env` (use `c.env`), `require()`. Everything must be ESM `import`.
+1. **No Node.js APIs.** No `fs`, `Buffer`, `path`, `process.env` (use `c.env`), `require()`. Everything must be ESM `import`. `backend/tsconfig.json` does not load the Node types, so `npm run typecheck` flags these in Worker source.
2. **No binary file handling.** The Worker cannot efficiently stream large binary files. Never add routes that accept file uploads - Cloudinary handles that directly from the browser.
@@ -94,13 +97,14 @@ These are hard constraints imposed by the Cloudflare Workers runtime. Violating
5. **`ctx.waitUntil()` in cron handlers.** Cron handlers must use `ctx.waitUntil(promise)` for async work. Without it, the Worker may terminate before the work completes.
-6. **Bundle size.** The Worker bundle must be a single ESM file (Wrangler handles bundling). Avoid large dependencies.
+6. **Bundle size.** The Worker bundle must be a single ESM file (Wrangler handles bundling). Avoid large dependencies. Type-only imports, including everything in `shared/types/`, add nothing to the bundle.
## Adding a New Worker Secret
-1. Set via `npx wrangler secret put NEW_SECRET_NAME` from `backend/`
-2. Add to `backend/.env.example` with a placeholder value
-3. Add to `backend/.dev.vars` locally
-4. Set as a GitHub secret if needed by deploy workflow
-5. Update `docs/architecture/cloudflare/WORKERS.md` (this file)
-6. Append to `DECISIONS.md` if it represents an architectural dependency
+1. Declare it in the `Env` interface in `backend/types/env.ts` (`NEW_SECRET_NAME?: string` unless the Worker cannot run without it)
+2. Set via `npx wrangler secret put NEW_SECRET_NAME` from `backend/`
+3. Add to `backend/.env.example` with a placeholder value
+4. Add to `backend/.dev.vars` locally
+5. Set as a GitHub secret if needed by deploy workflow
+6. Update `docs/architecture/cloudflare/WORKERS.md` (this file)
+7. Append to `DECISIONS.md` if it represents an architectural dependency
diff --git a/docs/architecture/data-flows/ANALYTICS.md b/docs/architecture/data-flows/ANALYTICS.md
index 848bfb4..2ef674e 100644
--- a/docs/architecture/data-flows/ANALYTICS.md
+++ b/docs/architecture/data-flows/ANALYTICS.md
@@ -6,7 +6,7 @@
User navigates to /channel/:id
│
▼
-ChannelAnalytics.jsx mounts -> api.getAnalytics(id)
+ChannelAnalytics.tsx mounts -> api.getAnalytics(id)
-> GET /api/accounts/:id/analytics
│
▼
@@ -31,7 +31,9 @@ ChannelAnalytics.jsx mounts -> api.getAnalytics(id)
### computeVideoAnalytics() Output (partial)
-```js
+Typed as `VideoAnalytics` in `shared/types/youtube.ts`.
+
+```ts
{
channel: { /* channel metadata */ },
totals: {
@@ -67,7 +69,7 @@ ChannelAnalytics.jsx mounts -> api.getAnalytics(id)
User navigates to /instagram/:id
│
▼
-InstagramAnalytics.jsx mounts -> api.getIGAnalytics(id)
+InstagramAnalytics.tsx mounts -> api.getIGAnalytics(id)
-> GET /api/accounts/:id/ig-analytics
│
▼
@@ -92,7 +94,9 @@ cache entry is current, otherwise fetches with the same pipeline and caches it.
### Instagram media item (cached shape)
-```js
+Typed as `InstagramMedia` in `shared/types/instagram.ts`; the cache entry is `IGCacheData`.
+
+```ts
{
id, caption, permalink, timestamp, mediaUrl, thumbnailUrl,
contentType: 'reel', // 'reel' | 'post' | 'video' - see SERVICES.md for the rules
@@ -105,7 +109,9 @@ cache entry is current, otherwise fetches with the same pipeline and caches it.
### computeInstagramAnalytics() Output (partial)
-```js
+Typed as `InstagramAnalytics` in `shared/types/instagram.ts`.
+
+```ts
{
totalPosts: 200, // profile media_count
fetchedPosts: 200, // items analyzed (max 500)
@@ -131,7 +137,7 @@ cache entry is current, otherwise fetches with the same pipeline and caches it.
User navigates to /reddit/:id
│
▼
-RedditAnalytics.jsx mounts -> api.getRedditAnalytics(id)
+RedditAnalytics.tsx mounts -> api.getRedditAnalytics(id)
-> GET /api/accounts/:id/reddit-analytics
│
▼
@@ -148,12 +154,14 @@ RedditAnalytics.jsx mounts -> api.getRedditAnalytics(id)
4. computeRedditAnalytics(profile, posts)
-> score stats, subreddit breakdown, timing analysis
5. Cache result in Redis
- 6. Return { profile, analytics }
+ 6. Return { profile, analytics, posts } (RedditCacheData)
```
### computeRedditAnalytics() Output (partial)
-```js
+Typed as `RedditAnalytics` in `shared/types/reddit.ts`.
+
+```ts
{
fetchedPosts: 100,
totalScore: 45000,
@@ -190,7 +198,9 @@ RedditAnalytics.jsx mounts -> api.getRedditAnalytics(id)
### Per-post fields (in posts array and topPosts)
-```js
+Typed as `RedditPost` in `shared/types/reddit.ts`.
+
+```ts
{
id, title, subreddit, subredditPrefixed,
score, upvoteRatio, numComments,
@@ -211,7 +221,7 @@ Note: Reddit disabled `view_count` from their API in December 2018. The field al
User navigates to /
│
▼
-Overview.jsx uses accounts from AppContext (data loaded by useOverviewData.js)
+Overview.tsx uses accounts from AppContext (data loaded by useOverviewData.ts)
-> Combined totals computed from account.subscriberCount, viewCount, etc.
-> api.getOverview() -> GET /api/overview
-> returns { tracked: [...], analyticsCache: { [accountId]: {...} } }
@@ -246,7 +256,7 @@ Audience as that account's reputation.
Reddit removed `view_count` from its API in December 2018, so a tracked Reddit post's views are
whatever the user typed into the edit dialog, stored as `data.manualViews`. `trackedViews()` in
-`frontend/src/utils/trackedContent.js` is the single place that decides which field to read:
+`frontend/src/utils/trackedContent.ts` is the single place that decides which field to read:
`viewCount` for YouTube items, `manualViews` for Reddit items. Every view total in the UI goes
through it, so a post with no manual figure contributes 0 rather than breaking the sum.
diff --git a/docs/architecture/data-flows/AUTHENTICATION.md b/docs/architecture/data-flows/AUTHENTICATION.md
index 4d54468..77e85a6 100644
--- a/docs/architecture/data-flows/AUTHENTICATION.md
+++ b/docs/architecture/data-flows/AUTHENTICATION.md
@@ -9,7 +9,7 @@ User visits the app
React Router: no session -> ProtectedRoute redirects to /login
│
▼
-Login.jsx renders email/password form
+Login.tsx renders email/password form
│
▼
User submits -> AuthContext.signIn(email, password)
@@ -36,8 +36,8 @@ User sees Overview dashboard
Optional; enabled when `VITE_GOOGLE_CLIENT_ID` is set and the Google provider is on in Supabase.
```
-Login.jsx renders GoogleSignInButton
- -> lib/googleIdentity.js loads https://accounts.google.com/gsi/client once
+Login.tsx renders GoogleSignInButton
+ -> lib/googleIdentity.ts loads https://accounts.google.com/gsi/client once
-> createNonce(): raw random nonce + its SHA-256 hex
-> google.accounts.id.initialize({ client_id, nonce: hashed, callback })
-> google.accounts.id.renderButton(...) (Google's own button, popup or FedCM)
@@ -94,7 +94,7 @@ requireAuth middleware
## Sign Out Flow
```
-User clicks Sign Out (Header.jsx)
+User clicks Sign Out (Header.tsx)
-> AuthContext.signOut()
-> supabase.auth.signOut()
-> Supabase invalidates refresh token server-side
diff --git a/docs/architecture/data-flows/PUBLISHING.md b/docs/architecture/data-flows/PUBLISHING.md
index fb31a5f..077cffa 100644
--- a/docs/architecture/data-flows/PUBLISHING.md
+++ b/docs/architecture/data-flows/PUBLISHING.md
@@ -59,7 +59,7 @@ User creates a scheduled post
▼
2. Every 15 minutes, one of two schedulers fires:
A. Cloudflare Worker cron -> processScheduledPosts(supabase)
- B. GitHub Actions -> node scripts/publish-scheduled.js -> direct Supabase REST calls
+ B. GitHub Actions -> node scripts/publish-scheduled.ts -> direct Supabase REST calls
│
▼
3. Scheduler queries due posts:
diff --git a/docs/architecture/data-flows/SCHEDULING.md b/docs/architecture/data-flows/SCHEDULING.md
index 8c63760..f3c5dc7 100644
--- a/docs/architecture/data-flows/SCHEDULING.md
+++ b/docs/architecture/data-flows/SCHEDULING.md
@@ -7,13 +7,13 @@ Two independent systems check for due posts every 15 minutes. Both target the sa
## System A: Cloudflare Worker Cron
**Trigger:** `*/15 * * * *` cron in `wrangler.toml`
-**Handler:** `backend/utils/scheduler.js` -> `processScheduledPosts(supabase)`
+**Handler:** `backend/utils/scheduler.ts` -> `processScheduledPosts(supabase)`
**Supabase client:** service-role (created from Worker env)
## System B: GitHub Actions
**Trigger:** `publish-scheduled.yml` workflow -> `schedule: cron('*/15 * * * *')`
-**Handler:** `scripts/publish-scheduled.js` (standalone Node.js, zero npm deps)
+**Handler:** `scripts/publish-scheduled.ts` (standalone TypeScript run directly by Node 24 with type stripping, zero npm deps)
**Supabase client:** direct REST API calls using `SUPABASE_URL` + `SUPABASE_SERVICE_KEY` GitHub secrets
## Why Both?
@@ -34,7 +34,7 @@ WHERE id = :id AND status = 'pending'
The `AND status = 'pending'` condition means only one scheduler can successfully claim a post. The second scheduler to run will find no matching rows for that post ID and skip it.
-Both schedulers implement this claim: `claimPost()` in `backend/lib/db.js` for the Worker, and `claimPost()` in `scripts/publish-scheduled.js` (a `PATCH` filtered on `status=eq.pending` with `Prefer: return=representation`). A scheduler that gets no row back skips the post. PostgreSQL serializes the two updates, so exactly one scheduler publishes each post even when both run at the same moment.
+Both schedulers implement this claim: `claimPost()` in `backend/lib/db.ts` for the Worker, and `claimPost()` in `scripts/publish-scheduled.ts` (a `PATCH` filtered on `status=eq.pending` with `Prefer: return=representation`). A scheduler that gets no row back skips the post. PostgreSQL serializes the two updates, so exactly one scheduler publishes each post even when both run at the same moment.
## Post Status Lifecycle
@@ -58,7 +58,7 @@ publishing Claimed by a scheduler - in-flight
Both schedulers implement the same logic:
-| Step | Worker (`scheduler.js`) | GitHub Actions (`publish-scheduled.js`) |
+| Step | Worker (`scheduler.ts`) | GitHub Actions (`publish-scheduled.ts`) |
|---|---|---|
| Fetch due posts | `db.getDuePosts(supabase)` | `GET /scheduled_posts?status=eq.pending&scheduled_at=lte.now` |
| Fetch account | `db.getAccountById(supabase, accountId)` | `GET /accounts?id=eq.{accountId}` |
diff --git a/docs/architecture/database/SCHEMA.md b/docs/architecture/database/SCHEMA.md
index 706d9c5..bea4e5d 100644
--- a/docs/architecture/database/SCHEMA.md
+++ b/docs/architecture/database/SCHEMA.md
@@ -162,7 +162,7 @@ Stores Reddit posts and YouTube videos the user wants to monitor. Previously Red
### `data` jsonb shape for Reddit items
-Populated by `fetchTrackedPostData()` in `backend/services/reddit.js`:
+Populated by `fetchTrackedPostData()` in `backend/services/reddit.ts`:
```json
{
@@ -200,7 +200,7 @@ Both keys are rejected for YouTube items, which already carry a real `viewCount`
### `data` jsonb shape for YouTube items
-Populated by `fetchTrackedYouTubeData()` in `backend/services/youtube.js`:
+Populated by `fetchTrackedYouTubeData()` in `backend/services/youtube.ts`:
```json
{
@@ -249,39 +249,43 @@ ALTER TABLE tracked_posts ADD COLUMN IF NOT EXISTS content_type text NOT NULL DE
---
-## `lib/db.js` - Query Layer
+## `lib/db.ts` - Query Layer
-All SQL operations are centralized in `backend/lib/db.js`. Route handlers and cron handlers import named functions from this file - they never call `supabase.from()` directly.
+All SQL operations are centralized in `backend/lib/db.ts`. Route handlers and cron handlers import named functions from this file - they never call `supabase.from()` directly.
### Available functions
-```js
+Each function takes the `SupabaseClient` first and returns a type from `shared/types/domain.ts`. A `userId` of `null` means service-level access (cron handlers that scan every user).
+
+```ts
// Accounts
-getAccounts(supabase, userId?) // null userId = all users (for cron)
-getAccountById(supabase, id, userId?)
-createAccount(supabase, account, userId)
-updateAccount(supabase, id, updates, userId?)
-deleteAccount(supabase, id, userId?)
+getAccounts(supabase, userId: string | null = null): Promise<Account[]>
+getAccountById(supabase, id, userId: string | null = null): Promise<Account | null>
+createAccount(supabase, account: NewAccount, userId): Promise<void>
+updateAccount(supabase, id, updates: Partial<Account>, userId: string | null = null): Promise<void>
+deleteAccount(supabase, id, userId: string | null = null): Promise<void>
// Settings
-getSettings(supabase, userId)
-saveSettings(supabase, keys, userId)
+getSettings(supabase, userId): Promise<Settings>
+saveSettings(supabase, keys: Settings, userId): Promise<void>
// Scheduled Posts
-getPosts(supabase, userId?)
-getPostById(supabase, id, userId?)
-getDuePosts(supabase) // for cron - no userId filter, selects pending+overdue
-createPost(supabase, post, userId)
-updatePost(supabase, id, updates, userId?)
-deletePost(supabase, id, userId?)
-deleteAllPosts(supabase, userId) // skips 'publishing' status posts
-
-// Tracked Reddit Posts
-getTrackedPosts(supabase, userId)
-getTrackedPostById(supabase, id, userId)
-createTrackedPost(supabase, post, userId)
-updateTrackedPost(supabase, id, updates, userId)
-deleteTrackedPost(supabase, id, userId)
+getPosts(supabase, userId: string | null): Promise<ScheduledPost[]>
+getPostById(supabase, id, userId: string | null = null): Promise<ScheduledPost | null>
+getDuePosts(supabase): Promise<ScheduledPost[]> // for cron - no userId filter, selects pending+overdue
+claimPost(supabase, id): Promise<boolean> // pending to publishing; false when another scheduler won
+createPost(supabase, post: ScheduledPost, userId): Promise<void>
+updatePost(supabase, id, updates: Partial<ScheduledPost>, userId: string | null = null): Promise<void>
+deletePost(supabase, id, userId: string | null = null): Promise<void>
+deleteAllPosts(supabase, userId: string | null): Promise<{ deleted: number; kept: number }> // skips 'publishing' status posts
+
+// Tracked Content
+getTrackedPosts(supabase, userId): Promise<TrackedPost[]>
+getTrackedPostById(supabase, id, userId): Promise<TrackedPost | null>
+createTrackedPost(supabase, post: NewTrackedPost, userId): Promise<void>
+updateTrackedPost(supabase, id, updates: TrackedPostUpdates, userId): Promise<void>
+patchTrackedPostData(supabase, id, patch: Record<string, unknown>, userId): Promise<void>
+deleteTrackedPost(supabase, id, userId): Promise<void>
```
## Adding a New Table
diff --git a/docs/architecture/database/SECURITY.md b/docs/architecture/database/SECURITY.md
index a64399d..d72aa8d 100644
--- a/docs/architecture/database/SECURITY.md
+++ b/docs/architecture/database/SECURITY.md
@@ -5,10 +5,10 @@
The backend uses the **service-role key** for all database operations. This key bypasses Row Level Security (RLS). Data isolation is enforced by the application:
1. `requireAuth` middleware verifies the JWT and sets `c.userId` from Supabase's response - this is the only trusted source of `userId`
-2. Every user-scoped query in `lib/db.js` appends `.eq('user_id', userId)` using this verified value
+2. Every user-scoped query in `lib/db.ts` appends `.eq('user_id', userId)` using this verified value
3. `userId` is never accepted from request body, query params, or any other user-controlled input
-**This means a missing `.eq('user_id', userId)` call is a security bug.** The centralization of all queries in `lib/db.js` makes this auditable - every public function signature documents whether it accepts a userId.
+**This means a missing `.eq('user_id', userId)` call is a security bug.** The centralization of all queries in `lib/db.ts` makes this auditable - every public function signature documents whether it accepts a userId.
## Why Not Use RLS?
@@ -58,9 +58,9 @@ The Instagram `accessToken` stored in `accounts.data.accessToken` is a long-live
1. Stored only in the Supabase `accounts` table (server-side)
2. Never returned in API responses - `safeAccount()` strips it
3. Only used server-side, by these modules:
- - Graph API calls: `services/instagramApi.js`, `services/instagramMedia.js` and `services/instagramPublishing.js` (the token is passed in as `access_token`)
- - Obtaining and storing tokens: `services/instagramTokens.js` (long-lived exchange and refresh), `services/instagramOAuth.js` (OAuth code exchange), `services/accountConnect.js` and `services/accountFactory.js` (pasted tokens and new account rows)
- - Reading the stored token: `routes/publishing.js` and `utils/scheduler.js` (publishing), `routes/analytics.js` (Instagram analytics and media), `services/accountRefresh.js` (profile refresh) and `services/overviewSummary.js` (overview cache warm-up)
+ - Graph API calls: `services/instagramApi.ts`, `services/instagramMedia.ts` and `services/instagramPublishing.ts` (the token is passed in as `access_token`)
+ - Obtaining and storing tokens: `services/instagramTokens.ts` (long-lived exchange and refresh), `services/instagramOAuth.ts` (OAuth code exchange), `services/accountConnect.ts` and `services/accountFactory.ts` (pasted tokens and new account rows)
+ - Reading the stored token: `routes/publishing.ts` and `utils/scheduler.ts` (publishing), `routes/analytics.ts` (Instagram analytics and media), `services/accountRefresh.ts` (profile refresh) and `services/overviewSummary.ts` (overview cache warm-up)
4. The `GET /api/accounts` endpoint passes all accounts through `safeAccount()` before returning
**If you add a new route that returns account data, you must call `safeAccount()`.** There is no automatic stripping - it is an explicit step in route handlers.
@@ -75,7 +75,7 @@ The GitHub Personal Access Token stored in `settings.value.githubPat` is stored
## Audit Points
When reviewing security, check these files:
-- `backend/middleware/auth.js` - JWT verification
-- `backend/lib/db.js` - every function that accepts an optional `userId` should either: require it explicitly, or have a documented reason for omitting it (cron use case)
-- `backend/lib/safeAccount.js` - `safeAccount()` definition; it strips every stored credential for all platforms
+- `backend/middleware/auth.ts` - JWT verification
+- `backend/lib/db.ts` - every function that accepts an optional `userId` should either: require it explicitly, or have a documented reason for omitting it (cron use case)
+- `backend/lib/safeAccount.ts` - `safeAccount()` definition; it strips every stored credential for all platforms
- All route files in `backend/routes/` - verify `safeAccount()` is called on every account response
diff --git a/docs/architecture/frontend/API_LAYER.md b/docs/architecture/frontend/API_LAYER.md
index 6ec6862..eab1b5b 100644
--- a/docs/architecture/frontend/API_LAYER.md
+++ b/docs/architecture/frontend/API_LAYER.md
@@ -1,15 +1,18 @@
# Frontend API Layer
-## Location: `frontend/src/services/api.js`
+## Location: `frontend/src/services/api.ts`
The single source of truth for all frontend-to-backend communication. **Never call `fetch()` directly in components or contexts.** Always add methods here and call them from components.
## The `request()` Function
-```js
+```ts
const API = import.meta.env.VITE_API_URL || 'http://localhost:8787/api';
-async function request(path, options = {}) {
+// callers that check success also handle a failure body the server sent with a 2xx status; success bodies carry no message
+export type ApiResult<T> = (T & { message?: undefined }) | ApiFailure;
+
+async function request<T>(path: string, options: RequestInit = {}): Promise<T> {
const { data: { session } } = await supabase.auth.getSession();
const token = session?.access_token;
@@ -20,56 +23,75 @@ async function request(path, options = {}) {
},
...options,
});
- const data = await res.json();
+ const data = await res.json() as T & ResponseStatusFields;
if (!res.ok && !data.success) throw new Error(data.message || data.error || 'Request failed');
return data;
}
```
+`T` is the response type from `shared/types/` that the route returns; `request<T>()` casts the parsed JSON to it once and does not validate it at runtime. `ResponseStatusFields` (`success?`, `message?`, `error?`) is the private type for the fields `request()` reads to decide whether the call failed. `import.meta.env` is typed by `ImportMetaEnv` in `frontend/src/vite-env.d.ts`; add a new `VITE_*` variable there.
+
**What it does automatically:**
1. Gets the current Supabase session token
2. Attaches `Authorization: Bearer <token>` header if logged in
3. Parses the JSON response
4. Throws an `Error` if the response is not OK (unless `data.success` is explicitly true)
-**Error handling:** The error message comes from the backend's `{ error: '...' }` response body, falling back to `'Request failed'`. Callers are responsible for catching this error and showing appropriate UI.
+**Error handling:** The error message comes from the backend's `message` or `error` field, falling back to `'Request failed'`. Callers are responsible for catching this error and showing appropriate UI.
+
+### `ApiResult<T>`
+
+A few routes answer `{ success: false, message }` (the `ApiFailure` type in `shared/types/domain.ts`) with a 2xx status, which `request()` returns instead of throwing. Their methods return `request<ApiResult<T>>()`: `getCloudinaryConfig`, `createIGContainer`, `publishIGContainer`, `getScheduledPosts`, `createScheduledPost` and `updateScheduledPost`. The caller narrows on `success` before reading the data:
+
+```ts
+const res = await api.createScheduledPost(post);
+if (!res.success) {
+ showToast(res.message, 'error');
+ return;
+}
+// res is ScheduledPostResponse here
+```
## The `api` Object
-All backend endpoints are methods on the exported `api` object:
+All backend endpoints are methods on the exported `api` object. Each method types its parameters and passes the shared response type to `request<T>()`, so the call site gets a typed result without a cast:
-```js
+```ts
export const api = {
- health: () => request('/health'),
- getAccounts: () => request('/accounts'),
- addAccount: (input) => request('/accounts', { method: 'POST', body: JSON.stringify({ input }) }),
- // ... (see api.js for full list)
+ health: () => request<HealthResponse>('/health'),
+ getAccounts: () => request<AccountListResponse>('/accounts'),
+ addAccount: (input: string) => request<YouTubeAccountAddResponse>('/accounts', { method: 'POST', body: JSON.stringify({ input }) }),
+ // ... (see api.ts for full list)
};
```
+The response types are imported with `import type` from `@shared/types/*.ts`, so nothing from `shared/` reaches the bundle.
+
## Adding a New API Method
-1. Add to `api.js`:
- ```js
+1. Add or reuse the request and response types in `shared/types/`.
+
+2. Add to `api.ts`:
+ ```ts
export const api = {
// ... existing methods
- getMyResource: (id) => request(`/my-resource/${id}`),
- createMyResource: (data) => request('/my-resource', { method: 'POST', body: JSON.stringify(data) }),
+ getMyResource: (id: string) => request<MyResource>(`/my-resource/${id}`),
+ createMyResource: (data: MyResourceCreateRequest) => request<MyResourceCreateResponse>('/my-resource', { method: 'POST', body: JSON.stringify(data) }),
};
```
-2. Use in a component:
- ```jsx
+3. Use in a component:
+ ```tsx
import { api } from '../services/api';
// ...
- const data = await api.getMyResource(id);
+ const data = await api.getMyResource(id); // typed as MyResource
```
-3. Update `docs/architecture/backend/ROUTES.md` if this is a new backend route
+4. Run `npm run typecheck`, and update `docs/architecture/backend/ROUTES.md` if this is a new backend route
## Error Handling Pattern in Components
-```jsx
+```tsx
const [loading, setLoading] = useState(false);
const { showToast } = useAppContext();
@@ -77,10 +99,10 @@ async function handleAction() {
setLoading(true);
try {
const result = await api.someMethod(data);
- showToast('Action completed!');
+ showToast('Changes saved');
// update state with result
} catch (err) {
- showToast(err.message, 'error');
+ showToast((err as Error).message, 'error');
} finally {
setLoading(false);
}
@@ -89,24 +111,24 @@ async function handleAction() {
## Overview Method
-```js
-getOverview: () => request('/overview'),
+```ts
+getOverview: () => request<OverviewResponse>('/overview'),
```
-Returns `{ tracked: TrackedItem[], analyticsCache: { [accountId]: { fetchedPosts?, totalLikes?, totalComments?, totalScore? } } }`.
+Returns `OverviewResponse` from `shared/types/domain.ts`: `{ tracked: TrackedPost[], analyticsCache: OverviewAnalyticsCache }`, where `analyticsCache` maps each account ID to its cached totals.
-The `analyticsCache` is populated from Redis on the backend — no live API calls are made. Data is only present for accounts whose analytics pages have been previously visited (which populates the Redis cache). The Overview dashboard uses this to compute Total Content, Total Comments, and Total Likes across all platforms without expensive per-account API calls on load.
+The `analyticsCache` is populated from Redis on the backend; no live API calls are made. Data is only present for accounts whose analytics pages have been previously visited (which populates the Redis cache). The Overview dashboard uses this to compute Total Content, Total Comments, and Total Likes across all platforms without expensive per-account API calls on load.
## Tracked Content Methods
-Added to the `api` object in `api.js`. Handles both Reddit posts and YouTube videos:
+Added to the `api` object in `api.ts`. Handles both Reddit posts and YouTube videos:
-```js
-getTrackedContent: () => request('/tracked-content'),
-addTrackedContent: (url, accountId, label, category) => request('/tracked-content', { method: 'POST', body: JSON.stringify({ url, accountId, label, category }) }),
-updateTrackedContent: (id, updates) => request(`/tracked-content/${id}`, { method: 'PUT', body: JSON.stringify(updates) }),
-deleteTrackedContent: (id) => request(`/tracked-content/${id}`, { method: 'DELETE' }),
-refreshTrackedContent: (id) => request(`/tracked-content/${id}/refresh`, { method: 'POST' }),
+```ts
+getTrackedContent: () => request<TrackedContentItem[]>('/tracked-content'),
+addTrackedContent: (url: string, accountId: string | null, label: string, category: string) => request<TrackedContentItem>('/tracked-content', { method: 'POST', body: JSON.stringify({ url, accountId, label, category }) }),
+updateTrackedContent: (id: string, updates: TrackedContentUpdateRequest) => request<TrackedContentItem>(`/tracked-content/${id}`, { method: 'PUT', body: JSON.stringify(updates) }),
+deleteTrackedContent: (id: string) => request<SuccessResponse>(`/tracked-content/${id}`, { method: 'DELETE' }),
+refreshTrackedContent: (id: string) => request<TrackedContentItem>(`/tracked-content/${id}/refresh`, { method: 'POST' }),
```
`accountId` may be `null`. For YouTube items, `accountId` is always `null` (fetched via the server's `YOUTUBE_API_KEY`). For Reddit items, `accountId` is optional and refers to a Reddit account whose cookie improves datacenter IP access.
@@ -122,16 +144,16 @@ sends only the returned `secure_url`.
## Cloudinary Uploads
-These are the only calls in `api.js` that do not go to the Worker.
+These are the only calls in `api.ts` that do not go to the Worker.
-```js
-uploadImage(file, cloudConfig)
+```ts
+uploadImage(file: File, cloudConfig: CloudinaryUploadConfig): Promise<string>
```
-Used for tracked item screenshots. It posts the image with `fetch` to `https://api.cloudinary.com/v1_1/<cloudName>/image/upload` and resolves with `secure_url`. It throws an `Error` with Cloudinary's own message, or `'Cloudinary did not return an image URL'`, and network or JSON failures reject with the browser's own error. The tracked content editor shows that `err.message` after `Image upload failed.` in an error toast.
+Used for tracked item screenshots. It posts the image with `fetch` to `https://api.cloudinary.com/v1_1/<cloudName>/image/upload` and resolves with `secure_url`. It throws an `Error` with Cloudinary's own message, or `'Cloudinary did not return an image URL'`, and network or JSON failures reject with the browser's own error. The tracked content editor shows that `(err as Error).message` after `Image upload failed.` in an error toast.
-```js
-uploadToCloudinary(file, cloudConfig, { onProgress })
+```ts
+uploadToCloudinary(file: File, cloudConfig: CloudinaryUploadConfig, { onProgress }: UploadOptions = {}): Promise<string>
```
Used by publishing. It posts `file` and the unsigned
@@ -139,10 +161,10 @@ Used by publishing. It posts `file` and the unsigned
`https://api.cloudinary.com/v1_1/<cloudName>/<video|image>/upload` (`video` for `video/*` files, `image` otherwise) with `XMLHttpRequest`, so
upload progress is available, and resolves with the response's `secure_url`.
-- `cloudConfig`: the object from `getCloudinaryConfig()` (`cloudName`, `uploadPreset`). Callers check it is set first.
+- `cloudConfig`: `CloudinaryUploadConfig`, the `cloudName` and `uploadPreset` from `getCloudinaryConfig()`. Callers check it is set first.
- `onProgress(percent)`: optional; called with a whole number from 0 to 100. The progress listener is only attached when this is passed.
-Failures reject with an `Error` that carries a `reason` so each page keeps its own wording:
+Failures reject with an `UploadError` (an `Error` with a `reason` of type `UploadErrorReason` and the extra fields below), so each page keeps its own wording. `api.ts` exports these types:
| `reason` | When | Default `message` | Extra fields |
|---|---|---|---|
@@ -150,7 +172,7 @@ Failures reject with an `Error` that carries a `reason` so each page keeps its o
| `rejected` | Cloudinary answered with a non-2xx status | `Upload failed` | `cloudinaryMessage` (Cloudinary's `error.message`, if any) or `parseMessage` (the body was not JSON) |
The bulk upload shows the default messages. The single post flow maps the error to its own
-wording (`singleUploadMessage` in `features/publishing/publishHelpers.js`). Tracked Content does
+wording (`singleUploadMessage` in `features/publishing/publishHelpers.ts`). Tracked Content does
not use this function: its screenshots go through `uploadImage()` above.
## Authentication
diff --git a/docs/architecture/frontend/CONTEXTS.md b/docs/architecture/frontend/CONTEXTS.md
index 467a993..b160ce7 100644
--- a/docs/architecture/frontend/CONTEXTS.md
+++ b/docs/architecture/frontend/CONTEXTS.md
@@ -1,18 +1,20 @@
# Frontend Contexts
-## AuthContext (`frontend/src/context/AuthContext.jsx`)
+## AuthContext (`frontend/src/context/AuthContext.tsx`)
Wraps Supabase Auth state and exposes it to the entire app.
### What it provides
-```js
+```ts
const { session, user, signIn, signUp, signInWithGoogle, signOut } = useAuth();
```
+The value is typed as `AuthContextValue`, exported from `AuthContext.tsx`.
+
| Value | Type | Description |
|---|---|---|
-| `session` | `Session \| null` | Current Supabase session; null if not logged in |
+| `session` | `Session \| null \| undefined` | Current Supabase session; `undefined` until the first `getSession()` resolves, `null` if not logged in |
| `user` | `User \| null` | `session.user` shorthand |
| `signIn(email, password)` | async function | Calls `supabase.auth.signInWithPassword()` |
| `signUp(email, password)` | async function | Calls `supabase.auth.signUp()` |
@@ -21,8 +23,8 @@ const { session, user, signIn, signUp, signInWithGoogle, signOut } = useAuth();
### How it works
-```js
-const [session, setSession] = useState(null);
+```ts
+const [session, setSession] = useState<Session | null | undefined>(undefined); // undefined = still loading
useEffect(() => {
supabase.auth.getSession().then(({ data: { session } }) => setSession(session));
@@ -38,30 +40,32 @@ useEffect(() => {
### Where to use it
- `ProtectedRoute` - reads `session` to decide whether to redirect to `/login`
-- `Login.jsx` - calls `signIn()`, `signUp()` and `signInWithGoogle()`
-- `Header.jsx` - calls `signOut()`, shows `user.email`
+- `Login.tsx` - calls `signIn()`, `signUp()` and `signInWithGoogle()`
+- `Header.tsx` - calls `signOut()`, shows `user.email`
- Do **not** use in page/feature components - they should never need auth state directly
---
-## AppContext (`frontend/src/context/AppContext.jsx`)
+## AppContext (`frontend/src/context/AppContext.tsx`)
Provides the global accounts list and shared utilities to all feature pages.
### What it provides
-```js
+```ts
const { accounts, setAccounts, loading, showToast, loadAccounts, refreshAll } = useAppContext();
```
+The value is typed as `AppContextValue`, exported from `AppContext.tsx`. `useAppContext()` throws if it is called outside `AppProvider`, so callers never handle `null`.
+
| Value | Type | Description |
|---|---|---|
-| `accounts` | `Account[]` | All connected accounts (YouTube + Instagram), normalized via `normalizeAccount()` |
-| `setAccounts` | setter | Direct setter (used by AccountManager after add/delete) |
+| `accounts` | `AppAccount[]` | All connected accounts (YouTube, Instagram, Reddit), normalized via `normalizeAccount()` |
+| `setAccounts` | `Dispatch<SetStateAction<AppAccount[]>>` | Direct setter (used by AccountManager after add/delete) |
| `loading` | `boolean` | True during `refreshAll()` only |
-| `showToast(msg, severity)` | function | Shows a Sonner toast. `severity`: `'success'` (default), `'error'`, `'warning'`, `'info'` |
-| `loadAccounts()` | async function | Fetches `GET /api/accounts` and updates `accounts` |
-| `refreshAll()` | async function | Calls `POST /api/accounts/refresh-all`, sets `loading` true during request |
+| `showToast(message, severity?)` | `(message: string, severity?: ToastSeverity) => void` | Shows a Sonner toast. `ToastSeverity`: `'success'` (default), `'error'`, `'warning'`, `'info'` |
+| `loadAccounts()` | `() => Promise<void>` | Fetches `GET /api/accounts` and updates `accounts` |
+| `refreshAll()` | `() => Promise<void>` | Calls `POST /api/accounts/refresh-all`, sets `loading` true during request |
### Loading behavior
@@ -70,18 +74,20 @@ const { accounts, setAccounts, loading, showToast, loadAccounts, refreshAll } =
### Where to use it
All feature pages and layout components use `useAppContext()`:
-- `Sidebar.jsx` - generates per-account nav links from `accounts`
-- `Overview.jsx` - renders the all-accounts dashboard
-- `AccountManager.jsx` - calls `loadAccounts()` after add/delete
-- `ChannelAnalytics.jsx` - finds the account by `params.id`
+- `Sidebar.tsx` - generates per-account nav links from `accounts`
+- `Overview.tsx` - renders the all-accounts dashboard
+- `AccountManager.tsx` - calls `loadAccounts()` after add/delete
+- `ChannelAnalytics.tsx` - finds the account by `params.id`
- All pages that show toast notifications call `showToast()`
### Account shape after `normalizeAccount()`
-```js
+`AppAccount` is defined in `frontend/src/utils/formatters.ts`: the `SafeAccount` type from `shared/types/domain.ts` plus fields older saved accounts can carry, with `title` and `thumbnail` filled in per platform. An example:
+
+```ts
{
id: 'account-id',
- platform: 'youtube' | 'instagram',
+ platform: 'youtube' | 'instagram' | 'reddit',
// YouTube fields:
channelId: '...',
title: '...',
@@ -89,13 +95,16 @@ All feature pages and layout components use `useAppContext()`:
subscriberCount: 12345,
viewCount: 456789,
videoCount: 100,
- thumbnailUrl: '...',
+ thumbnail: '...',
// Instagram fields:
igUserId: '...',
username: '...',
followersCount: 5000,
mediaCount: 200,
- // Note: accessToken is NEVER present - stripped by safeAccount() on the backend
+ // Reddit fields:
+ totalKarma: 1234,
+ hasCookie: true,
+ // Note: accessToken and cookie are NEVER present - stripped by safeAccount() on the backend
}
```
@@ -107,11 +116,11 @@ Hooks used by more than one feature. Hooks used by a single feature live in that
| Hook | File | Purpose |
|---|---|---|
-| `useIsMobile()` | `use-mobile.js` | True below the mobile breakpoint |
-| `useCommandPaletteShortcut(setOpen)` | `use-command-palette-shortcut.js` | Ctrl+K / Cmd+K toggle for the command palette |
-| `useSmoothTheme()` | `use-smooth-theme.js` | Theme switch as one cross-fade |
-| `useCloudinaryConfig(reloadKey)` | `use-cloudinary-config.js` | Loads `api.getCloudinaryConfig()`; returns the config or `null` |
-| `useAccountAnalytics(account, fetchAnalytics, label)` | `use-account-analytics.js` | Loads one account's analytics and refreshes it; used by Instagram and Reddit analytics |
+| `useIsMobile()` | `use-mobile.ts` | True below the mobile breakpoint |
+| `useCommandPaletteShortcut(setOpen)` | `use-command-palette-shortcut.ts` | Ctrl+K / Cmd+K toggle for the command palette |
+| `useSmoothTheme()` | `use-smooth-theme.ts` | Theme switch as one cross-fade |
+| `useCloudinaryConfig(reloadKey)` | `use-cloudinary-config.ts` | Loads `api.getCloudinaryConfig()`; returns the config or `null` |
+| `useAccountAnalytics(account, fetchAnalytics, label)` | `use-account-analytics.ts` | Loads one account's analytics and refreshes it; used by Instagram and Reddit analytics |
`useCloudinaryConfig` sets the config only when the response has `success: true`. A failed request keeps the previous value (initially `null`), and pages show a missing config as an alert or a disabled upload field. The request runs again whenever `reloadKey` changes: the Publish page passes `accounts`, Tracked Content passes nothing and loads once.
diff --git a/docs/architecture/frontend/DESIGN_SYSTEM.md b/docs/architecture/frontend/DESIGN_SYSTEM.md
index 10c5087..b8bb471 100644
--- a/docs/architecture/frontend/DESIGN_SYSTEM.md
+++ b/docs/architecture/frontend/DESIGN_SYSTEM.md
@@ -13,7 +13,7 @@ All tokens live in `frontend/src/index.css`: raw values on `:root` and `.dark`,
| Text | `text-ink`, `text-ink-muted`, `text-ink-faint`, `text-ink-inverse` | All pass WCAG AA on every surface in both themes |
| Brand | `bg-brand`, `hover:bg-brand-hover`, `bg-brand-soft`, `text-brand-text`, `text-on-brand` | Red as text is always `text-brand-text` |
| Status | `success`, `warning`, `danger`, `info`, each with `-soft` | Errors share the brand red, so they always carry an icon and the word "Error" |
-| Charts | `var(--chart-1)` to `var(--chart-5)` via `lib/chart.js` `SERIES` | Brand series order; platforms map to series in `lib/accounts.js` |
+| Charts | `var(--chart-1)` to `var(--chart-5)` via `lib/chart.ts` `SERIES` | Brand series order; platforms map to series in `lib/accounts.ts` |
| Type | `font-heading` (Sora), `font-sans` (Manrope), `font-mono` (JetBrains Mono); `text-display`, `text-page-title`, `text-section`, `text-body`, `text-small`, `text-caption` | Fonts are self-hosted from `frontend/public/fonts` and preloaded in `index.html` |
| Radius | `rounded-row` 10, `rounded-control` 10, `rounded-field` 12, `rounded-card` 16, `rounded-panel` 24, `rounded-dialog` 24, `rounded-pill` | Buttons, inputs and chips are rounded rectangles; badges keep the brand capsule |
| Sizes | `h-(--control-h-sm)` 32, `h-(--control-h)` 36, `h-(--control-h-lg)` 40, `--nav-row-h` 32, `--topbar-h` 50, `--sidebar-w` 256 | |
@@ -64,4 +64,4 @@ Shared components live in `frontend/src/components/`. Reach for these before wri
- Every async action disables its trigger, shows a spinner or progress, and ends in a toast that names what happened.
- Sentence case in all UI copy. No exclamation marks. Errors say what happened and what to do.
- Lucide icons at 1.75 stroke. 18px in navigation, 16px in controls.
-- New logic that can be pure goes in `src/lib/`, with its test at the mirrored path in `frontend/tests/` (`src/lib/library.js` -> `frontend/tests/lib/library.test.js`; run `npm test`).
+- New logic that can be pure goes in `src/lib/`, with its test at the mirrored path in `frontend/tests/` (`src/lib/library.ts` -> `frontend/tests/lib/library.test.ts`; run `npm test`).
diff --git a/docs/architecture/frontend/FEATURES.md b/docs/architecture/frontend/FEATURES.md
index 416eba9..5936317 100644
--- a/docs/architecture/frontend/FEATURES.md
+++ b/docs/architecture/frontend/FEATURES.md
@@ -5,118 +5,118 @@
```
frontend/src/
├── components/
-│ ├── SurfaceBox.jsx, MetricBox.jsx, PageHeader.jsx, ... <- Shared components, see DESIGN_SYSTEM.md
-│ ├── MetricAreaChart.jsx <- Shared Recharts area chart for single-metric comparisons
-│ ├── ChartPanel.jsx <- Titled chart container with an empty state
-│ └── ImageLightbox.jsx <- Thumbnail that opens the full image in a Dialog
+│ ├── SurfaceBox.tsx, MetricBox.tsx, PageHeader.tsx, ... <- Shared components, see DESIGN_SYSTEM.md
+│ ├── MetricAreaChart.tsx <- Shared Recharts area chart for single-metric comparisons
+│ ├── ChartPanel.tsx <- Titled chart container with an empty state
+│ └── ImageLightbox.tsx <- Thumbnail that opens the full image in a Dialog
├── docs/ <- Public documentation at /docs (outside the feature tree: no auth, no AppContext)
-│ ├── DocsLayout.jsx <- Page frame: theme, search shortcut, copy page, scroll to hash
-│ ├── DocsHeader.jsx, DocsSidebarNav.jsx, DocsMobileNav.jsx, DocsPager.jsx, DocsToc.jsx, DocsSearch.jsx
-│ ├── useTableOfContents.js <- Collects page headings and tracks the one in view
-│ ├── components.jsx <- DocTitle, H2, H3, Callout, Steps, CodeBlock, Table, PathCards, Badge
-│ ├── nav.js <- Tabs, groups and pages; the single source for navigation; firstPagePath(tab)
-│ ├── routes.js <- Slug to lazy page map; nav.test.js checks it matches nav.js
+│ ├── DocsLayout.tsx <- Page frame: theme, search shortcut, copy page, scroll to hash
+│ ├── DocsHeader.tsx, DocsSidebarNav.tsx, DocsMobileNav.tsx, DocsPager.tsx, DocsToc.tsx, DocsSearch.tsx
+│ ├── useTableOfContents.ts <- Collects page headings and tracks the one in view
+│ ├── components.tsx <- DocTitle, H2, H3, Callout, Steps, CodeBlock, Table, PathCards, Badge
+│ ├── nav.ts <- Tabs, groups and pages; the single source for navigation; firstPagePath(tab)
+│ ├── routes.ts <- Slug to lazy page map; nav.test.ts checks it matches nav.ts
│ └── pages/ <- Overview, Use, SelfHost, Reference (one chunk each)
-│ ├── use/ <- One file per page plus AdminLink.jsx; Use.jsx re-exports them
-│ ├── reference/ <- One file per page; Reference.jsx re-exports them
-│ └── selfHost/ <- One file per self-hosting page plus selfHostSql.js (selfHostSql.test.js); SelfHost.jsx re-exports them
+│ ├── use/ <- One file per page plus AdminLink.tsx; Use.tsx re-exports them
+│ ├── reference/ <- One file per page; Reference.tsx re-exports them
+│ └── selfHost/ <- One file per self-hosting page plus selfHostSql.ts (selfHostSql.test.ts); SelfHost.tsx re-exports them
├── features/
│ ├── analytics/
│ │ ├── channel/
-│ │ │ ├── ChannelAnalytics.jsx <- Page: YouTube channel analytics with eight tabs
-│ │ │ ├── ChannelOverviewTab.jsx, ChannelVideosTab.jsx, ChannelEngagementTab.jsx, ChannelContentTab.jsx
-│ │ │ ├── ChannelPublishingTab.jsx, ChannelGrowthTab.jsx, ChannelShortsTab.jsx, ChannelTagsTab.jsx, TagCloud.jsx
-│ │ │ ├── ChannelHeader.jsx, ChannelNoVideos.jsx, ChannelVideoTable.jsx, TrendArea.jsx, MetricGrid.jsx
-│ │ │ ├── useChannelAnalytics.js <- Loads api.getAnalytics(id); returns data, loading and the reload
-│ │ │ └── channelChartData.js <- Pure chart rows and labels (channelChartData.test.js)
+│ │ │ ├── ChannelAnalytics.tsx <- Page: YouTube channel analytics with eight tabs
+│ │ │ ├── ChannelOverviewTab.tsx, ChannelVideosTab.tsx, ChannelEngagementTab.tsx, ChannelContentTab.tsx
+│ │ │ ├── ChannelPublishingTab.tsx, ChannelGrowthTab.tsx, ChannelShortsTab.tsx, ChannelTagsTab.tsx, TagCloud.tsx
+│ │ │ ├── ChannelHeader.tsx, ChannelNoVideos.tsx, ChannelVideoTable.tsx, TrendArea.tsx, MetricGrid.tsx
+│ │ │ ├── useChannelAnalytics.ts <- Loads api.getAnalytics(id); returns data, loading and the reload
+│ │ │ └── channelChartData.ts <- Pure chart rows and labels (channelChartData.test.ts)
│ │ ├── instagram/
-│ │ │ ├── InstagramAnalytics.jsx <- Page: Instagram account analytics (loads through useAccountAnalytics)
-│ │ │ ├── InstagramHeader.jsx, InstagramMetrics.jsx, InstagramInsightChips.jsx, TypeBadge.jsx
-│ │ │ ├── InstagramEngagementCharts.jsx, InstagramPostCharts.jsx, InstagramHashtags.jsx, InstagramRecentGrid.jsx
-│ │ │ ├── InstagramTopPostsTable.jsx, InstagramTypeSummaryTable.jsx
-│ │ │ └── instagramAnalyticsData.js <- Pure chart rows and labels (instagramAnalyticsData.test.js)
+│ │ │ ├── InstagramAnalytics.tsx <- Page: Instagram account analytics (loads through useAccountAnalytics)
+│ │ │ ├── InstagramHeader.tsx, InstagramMetrics.tsx, InstagramInsightChips.tsx, TypeBadge.tsx
+│ │ │ ├── InstagramEngagementCharts.tsx, InstagramPostCharts.tsx, InstagramHashtags.tsx, InstagramRecentGrid.tsx
+│ │ │ ├── InstagramTopPostsTable.tsx, InstagramTypeSummaryTable.tsx
+│ │ │ └── instagramAnalyticsData.ts <- Pure chart rows and labels (instagramAnalyticsData.test.ts)
│ │ ├── overview/
-│ │ │ ├── Overview.jsx <- Page: cross-platform aggregate dashboard with six metric tabs
-│ │ │ ├── OverviewHeader.jsx, QuickActions.jsx, GettingStarted.jsx, MetricTabsList.jsx
-│ │ │ ├── AudienceTab.jsx, AudienceChart.jsx, ViewsTab.jsx, ContentTab.jsx, AccountsTab.jsx, CommentsTab.jsx, LikesTab.jsx
-│ │ │ ├── InstagramViewsTable.jsx, YouTubeViewsTable.jsx, AccountCell.jsx, AccountRankRow.jsx, CategoryRow.jsx, OpenAnalytics.jsx
-│ │ │ ├── useOverviewData.js <- Loads api.getOverview() and re-polls while accounts are syncing
-│ │ │ ├── useOverviewStats.js <- Memoized totals, rankings and chart rows
-│ │ │ └── overviewStats.js, overviewTrackedStats.js, overviewCharts.js, overviewLabels.js, greeting.js <- Pure helpers with *.test.js
+│ │ │ ├── Overview.tsx <- Page: cross-platform aggregate dashboard with six metric tabs
+│ │ │ ├── OverviewHeader.tsx, QuickActions.tsx, GettingStarted.tsx, MetricTabsList.tsx
+│ │ │ ├── AudienceTab.tsx, AudienceChart.tsx, ViewsTab.tsx, ContentTab.tsx, AccountsTab.tsx, CommentsTab.tsx, LikesTab.tsx
+│ │ │ ├── InstagramViewsTable.tsx, YouTubeViewsTable.tsx, AccountCell.tsx, AccountRankRow.tsx, CategoryRow.tsx, OpenAnalytics.tsx
+│ │ │ ├── useOverviewData.ts <- Loads api.getOverview() and re-polls while accounts are syncing
+│ │ │ ├── useOverviewStats.ts <- Memoized totals, rankings and chart rows
+│ │ │ └── overviewStats.ts, overviewTrackedStats.ts, overviewCharts.ts, overviewLabels.ts, greeting.ts <- Pure helpers with *.test.ts
│ │ ├── reddit/
-│ │ │ ├── RedditAnalytics.jsx <- Page: Reddit account analytics (loads through useAccountAnalytics)
-│ │ │ ├── RedditHeader.jsx, RedditKarmaSummary.jsx, RedditKarmaCharts.jsx, RedditStatPanels.jsx
-│ │ │ ├── RedditTimingCharts.jsx, RedditSubredditTable.jsx, RedditTopPostsTable.jsx
-│ │ │ ├── redditAnalyticsData.js <- Pure chart rows and stat lists (redditAnalyticsData.test.js)
-│ │ │ ├── RedditPosts.jsx <- Per-account post explorer
-│ │ │ ├── RedditPostsAll.jsx <- Global post explorer (all Reddit accounts)
-│ │ │ ├── RedditPostFilters.jsx, RedditPostTable.jsx <- Filters and table shared by both post explorers
-│ │ │ └── redditPostUtils.js <- Shared sort options, filtering and sorting
+│ │ │ ├── RedditAnalytics.tsx <- Page: Reddit account analytics (loads through useAccountAnalytics)
+│ │ │ ├── RedditHeader.tsx, RedditKarmaSummary.tsx, RedditKarmaCharts.tsx, RedditStatPanels.tsx
+│ │ │ ├── RedditTimingCharts.tsx, RedditSubredditTable.tsx, RedditTopPostsTable.tsx
+│ │ │ ├── redditAnalyticsData.ts <- Pure chart rows and stat lists (redditAnalyticsData.test.ts)
+│ │ │ ├── RedditPosts.tsx <- Per-account post explorer
+│ │ │ ├── RedditPostsAll.tsx <- Global post explorer (all Reddit accounts)
+│ │ │ ├── RedditPostFilters.tsx, RedditPostTable.tsx <- Filters and table shared by both post explorers
+│ │ │ └── redditPostUtils.ts <- Shared sort options, filtering and sorting
│ │ └── tracked/
-│ │ ├── TrackedContent.jsx <- Page: tracked Reddit posts and YouTube videos
-│ │ ├── TrackedMetrics.jsx, TrackedFilters.jsx, BulkCategoryBar.jsx, TrackedTable.jsx, TrackedRow.jsx, TrackedThumbnail.jsx
-│ │ ├── AddTrackedDialog.jsx, EditTrackedDialog.jsx, TrackedImageField.jsx, CategoryPicker.jsx, RowAction.jsx
-│ │ ├── useTrackedItems.js, useTrackedFilters.js, useTrackedSelection.js, useBulkCategory.js
-│ │ ├── useTrackedDelete.js, useAddTracked.js, useTrackedEditor.js <- Delete, add form, edit and image upload
-│ │ ├── trackedList.js <- Pure sort, filter, stats and form helpers (trackedList.test.js)
-│ │ ├── TrackedCategory.jsx <- Page: per-category analytics for tracked content
-│ │ ├── CategoryYouTubeSection.jsx, CategoryRedditSection.jsx, NumberCell.jsx, OpenLink.jsx
-│ │ └── trackedCategoryStats.js <- Pure per-category totals and labels (trackedCategoryStats.test.js)
+│ │ ├── TrackedContent.tsx <- Page: tracked Reddit posts and YouTube videos
+│ │ ├── TrackedMetrics.tsx, TrackedFilters.tsx, BulkCategoryBar.tsx, TrackedTable.tsx, TrackedRow.tsx, TrackedThumbnail.tsx
+│ │ ├── AddTrackedDialog.tsx, EditTrackedDialog.tsx, TrackedImageField.tsx, CategoryPicker.tsx, RowAction.tsx
+│ │ ├── useTrackedItems.ts, useTrackedFilters.ts, useTrackedSelection.ts, useBulkCategory.ts
+│ │ ├── useTrackedDelete.ts, useAddTracked.ts, useTrackedEditor.ts <- Delete, add form, edit and image upload
+│ │ ├── trackedList.ts <- Pure sort, filter, stats and form helpers (trackedList.test.ts)
+│ │ ├── TrackedCategory.tsx <- Page: per-category analytics for tracked content
+│ │ ├── CategoryYouTubeSection.tsx, CategoryRedditSection.tsx, NumberCell.tsx, OpenLink.tsx
+│ │ └── trackedCategoryStats.ts <- Pure per-category totals and labels (trackedCategoryStats.test.ts)
│ ├── accounts/
-│ │ ├── AccountManager.jsx <- Page: connected accounts by platform, refresh and remove
-│ │ ├── AccountSection.jsx, AccountCard.jsx, AccountsEmptyState.jsx
-│ │ ├── AddAccountDialog.jsx <- Platform picker, per-platform fields and footer actions
-│ │ ├── YouTubeAccountFields.jsx, RedditAccountFields.jsx, AddAccountFooter.jsx
-│ │ ├── useAddAccount.js <- Add dialog state; Back keeps typed fields, Cancel clears them
-│ │ ├── useAccountRefresh.js, useAccountDelete.js
-│ │ ├── useInstagramOAuthReturn.js <- Reads ?ig_connected, ?ig_error and ?add once, then clears them
-│ │ ├── platformChoices.js <- Platform choice titles, descriptions and icons
-│ │ └── accountManagerData.js <- Pure OAuth return, error text, card metrics (accountManagerData.test.js)
+│ │ ├── AccountManager.tsx <- Page: connected accounts by platform, refresh and remove
+│ │ ├── AccountSection.tsx, AccountCard.tsx, AccountsEmptyState.tsx
+│ │ ├── AddAccountDialog.tsx <- Platform picker, per-platform fields and footer actions
+│ │ ├── YouTubeAccountFields.tsx, RedditAccountFields.tsx, AddAccountFooter.tsx
+│ │ ├── useAddAccount.ts <- Add dialog state; Back keeps typed fields, Cancel clears them
+│ │ ├── useAccountRefresh.ts, useAccountDelete.ts
+│ │ ├── useInstagramOAuthReturn.ts <- Reads ?ig_connected, ?ig_error and ?add once, then clears them
+│ │ ├── platformChoices.ts <- Platform choice titles, descriptions and icons
+│ │ └── accountManagerData.ts <- Pure OAuth return, error text, card metrics (accountManagerData.test.ts)
│ ├── publishing/
-│ │ ├── UploadContent.jsx <- Page: tabs, Cloudinary alert, scheduled posts (default export)
-│ │ ├── SinglePostTab.jsx <- Single post form or its progress view
-│ │ ├── MediaPicker.jsx, CaptionBox.jsx, SinglePostSettings.jsx, ReelOptions.jsx, ScheduleFields.jsx, PostSummary.jsx
-│ │ ├── PublishProgress.jsx, PublishResult.jsx <- Upload, processing, done, scheduled and error states
-│ │ ├── BulkUploadTab.jsx <- Bulk queue, results and settings
-│ │ ├── BulkFileList.jsx, BulkFileItem.jsx, BulkResults.jsx, BulkSettings.jsx, BulkScheduleFields.jsx
-│ │ ├── ScheduledPostsSection.jsx <- Scheduled post table with filters and the overdue alert
-│ │ ├── ScheduledPostRow.jsx, ScheduledPostEditRow.jsx, ScheduledPostDialogs.jsx, OverdueAlert.jsx
-│ │ ├── AccountSelect.jsx, TypePicker.jsx, ScheduleToggle.jsx, ScheduleHint.jsx, IconInput.jsx, StatusBadge.jsx, NoInstagramAccount.jsx
-│ │ ├── useSinglePostForm.js, useSinglePostMedia.js <- Single post fields, file and cover
-│ │ ├── useSinglePublish.js, usePublishProgress.js <- Single post publish or schedule run
-│ │ ├── useBulkSettings.js, useBulkQueue.js, useBulkPublish.js <- Bulk settings, file queue, upload loop
-│ │ ├── useScheduledPosts.js, useScheduledPostEdit.js, useScheduledPostDelete.js
-│ │ ├── containerPolling.js <- Waits for an Instagram container (single post and bulk)
-│ │ ├── singlePostFlow.js <- Single post Cloudinary upload, then publish or schedule
-│ │ ├── publishConstants.js <- Content types, statuses, intervals, caption limit
-│ │ └── publishHelpers.js, scheduleHelpers.js, queueHelpers.js <- Pure helpers with *.test.js
+│ │ ├── UploadContent.tsx <- Page: tabs, Cloudinary alert, scheduled posts (default export)
+│ │ ├── SinglePostTab.tsx <- Single post form or its progress view
+│ │ ├── MediaPicker.tsx, CaptionBox.tsx, SinglePostSettings.tsx, ReelOptions.tsx, ScheduleFields.tsx, PostSummary.tsx
+│ │ ├── PublishProgress.tsx, PublishResult.tsx <- Upload, processing, done, scheduled and error states
+│ │ ├── BulkUploadTab.tsx <- Bulk queue, results and settings
+│ │ ├── BulkFileList.tsx, BulkFileItem.tsx, BulkResults.tsx, BulkSettings.tsx, BulkScheduleFields.tsx
+│ │ ├── ScheduledPostsSection.tsx <- Scheduled post table with filters and the overdue alert
+│ │ ├── ScheduledPostRow.tsx, ScheduledPostEditRow.tsx, ScheduledPostDialogs.tsx, OverdueAlert.tsx
+│ │ ├── AccountSelect.tsx, TypePicker.tsx, ScheduleToggle.tsx, ScheduleHint.tsx, IconInput.tsx, StatusBadge.tsx, NoInstagramAccount.tsx
+│ │ ├── useSinglePostForm.ts, useSinglePostMedia.ts <- Single post fields, file and cover
+│ │ ├── useSinglePublish.ts, usePublishProgress.ts <- Single post publish or schedule run
+│ │ ├── useBulkSettings.ts, useBulkQueue.ts, useBulkPublish.ts <- Bulk settings, file queue, upload loop
+│ │ ├── useScheduledPosts.ts, useScheduledPostEdit.ts, useScheduledPostDelete.ts
+│ │ ├── containerPolling.ts <- Waits for an Instagram container (single post and bulk)
+│ │ ├── singlePostFlow.ts <- Single post Cloudinary upload, then publish or schedule
+│ │ ├── publishConstants.ts <- Content types, statuses, intervals, caption limit
+│ │ └── publishHelpers.ts, scheduleHelpers.ts, queueHelpers.ts <- Pure helpers with *.test.ts
│ ├── settings/
-│ │ ├── Settings.jsx <- Page: loads server settings, then renders each section; keeps the #hash scroll
-│ │ ├── SettingsSection.jsx, AppearanceSection.jsx, ServerKeysSection.jsx, SchedulingSection.jsx
-│ │ ├── PlatformRequirementsSection.jsx, UsefulLinksSection.jsx
-│ │ ├── SchedulingSetupGuide.jsx <- Optional GitHub backup scheduler steps for administrators
-│ │ ├── SchedulingSetupSteps.jsx, SetupStep.jsx, GithubRepoForm.jsx, CopyChip.jsx, GuideLinkButton.jsx, RepoLinkButton.jsx
-│ │ ├── useServerSettings.js <- Loads keys and the saved repository; saves the repository
-│ │ ├── useApiHealthCheck.js <- Runs api.health() for the server keys section
-│ │ ├── settingsData.js <- Pure load sequence (api injected), links, health text (settingsData.test.js)
-│ │ └── schedulingProgress.js <- Pure guide progress in localStorage (schedulingProgress.test.js)
+│ │ ├── Settings.tsx <- Page: loads server settings, then renders each section; keeps the #hash scroll
+│ │ ├── SettingsSection.tsx, AppearanceSection.tsx, ServerKeysSection.tsx, SchedulingSection.tsx
+│ │ ├── PlatformRequirementsSection.tsx, UsefulLinksSection.tsx
+│ │ ├── SchedulingSetupGuide.tsx <- Optional GitHub backup scheduler steps for administrators
+│ │ ├── SchedulingSetupSteps.tsx, SetupStep.tsx, GithubRepoForm.tsx, CopyChip.tsx, GuideLinkButton.tsx, RepoLinkButton.tsx
+│ │ ├── useServerSettings.ts <- Loads keys and the saved repository; saves the repository
+│ │ ├── useApiHealthCheck.ts <- Runs api.health() for the server keys section
+│ │ ├── settingsData.ts <- Pure load sequence (api injected), links, health text (settingsData.test.ts)
+│ │ └── schedulingProgress.ts <- Pure guide progress in localStorage (schedulingProgress.test.ts)
│ ├── analytics/videos/
-│ │ ├── VideoExplorer.jsx <- Page: YouTube video library with filtering
-│ │ ├── VideoFilters.jsx, LayoutToggle.jsx, VideoListTable.jsx, VideoSortHeader.jsx, VideoGrid.jsx
-│ │ ├── useChannelVideos.js <- Loads every channel's videos; shared with Shorts
-│ │ └── videoLibrary.js <- Pure channel merge, filter, sort and totals (videoLibrary.test.js)
+│ │ ├── VideoExplorer.tsx <- Page: YouTube video library with filtering
+│ │ ├── VideoFilters.tsx, LayoutToggle.tsx, VideoListTable.tsx, VideoSortHeader.tsx, VideoGrid.tsx
+│ │ ├── useChannelVideos.ts <- Loads every channel's videos; shared with Shorts
+│ │ └── videoLibrary.ts <- Pure channel merge, filter, sort and totals (videoLibrary.test.ts)
│ ├── analytics/shorts/
-│ │ ├── ShortsExplorer.jsx <- Page: YouTube Shorts (60 seconds or less)
-│ │ ├── ShortsFilters.jsx, ShortsGrid.jsx
-│ │ └── shortsLibrary.js <- Pure Shorts selection, filter, sort and description (shortsLibrary.test.js)
+│ │ ├── ShortsExplorer.tsx <- Page: YouTube Shorts (60 seconds or less)
+│ │ ├── ShortsFilters.tsx, ShortsGrid.tsx
+│ │ └── shortsLibrary.ts <- Pure Shorts selection, filter, sort and description (shortsLibrary.test.ts)
│ └── analytics/reels/
-│ ├── ReelsExplorer.jsx <- Page: Instagram reels, posts and videos
-│ ├── ReelsMetrics.jsx, ReelsFilters.jsx, ReelsGrid.jsx
-│ ├── useInstagramMedia.js <- Loads media from every Instagram account
-│ └── reelsLibrary.js <- Pure merge, filter, sort and totals (reelsLibrary.test.js)
+│ ├── ReelsExplorer.tsx <- Page: Instagram reels, posts and videos
+│ ├── ReelsMetrics.tsx, ReelsFilters.tsx, ReelsGrid.tsx
+│ ├── useInstagramMedia.ts <- Loads media from every Instagram account
+│ └── reelsLibrary.ts <- Pure merge, filter, sort and totals (reelsLibrary.test.ts)
```
-Test files are not in this tree. A `(name.test.js)` or `with *.test.js` note above means the helper has a test in `frontend/tests/` at the mirrored path: `src/features/analytics/channel/channelChartData.js` is covered by `frontend/tests/features/analytics/channel/channelChartData.test.js`, and `src/docs/nav.js` by `frontend/tests/docs/nav.test.js`. See `docs/workflows/TESTING.md`.
+Test files are not in this tree. A `(name.test.ts)` or `with *.test.ts` note above means the helper has a test in `frontend/tests/` at the mirrored path: `src/features/analytics/channel/channelChartData.ts` is covered by `frontend/tests/features/analytics/channel/channelChartData.test.ts`, and `src/docs/nav.ts` by `frontend/tests/docs/nav.test.ts`. See `docs/workflows/TESTING.md`.
## Metric Naming
@@ -130,10 +130,10 @@ the word "score".
## Shared Chart Component
-`components/MetricAreaChart.jsx` renders a single-series area chart with the project's axis,
+`components/MetricAreaChart.tsx` renders a single-series area chart with the project's axis,
grid, gradient, and tooltip styling. Use it instead of hand-rolling a Recharts `AreaChart`:
-```jsx
+```tsx
<MetricAreaChart
data={[{ name: 'Item', karma: 42 }]}
dataKey="karma"
@@ -148,10 +148,10 @@ never collide.
## Image Lightbox
-`components/ImageLightbox.jsx` renders a thumbnail that opens the full image in a shadcn
+`components/ImageLightbox.tsx` renders a thumbnail that opens the full image in a shadcn
`Dialog`. Used for tracked Reddit post images, which have no platform thumbnail:
-```jsx
+```tsx
<ImageLightbox src={item.imageUrl} alt={item.title} thumbClassName="size-14" />
```
@@ -168,21 +168,22 @@ Each top-level directory under `features/` represents a product area. Sub-direct
```
features/analytics/youtube/ <- correct
-features/ChannelAnalytics.jsx <- wrong (flat, not grouped)
+features/ChannelAnalytics.tsx <- wrong (flat, not grouped)
```
### One page component per file
-Each `.jsx` file in `features/` is a routable page. It is lazy-imported in `App.jsx` and mapped to a URL path. Shared sub-components that appear only on that page live in the same directory:
+Each feature directory has one routable page component, exported as default from a `PascalCase.tsx` file. It is lazy-imported in `App.tsx` and mapped to a URL path. Sub-components, hooks and pure helpers that serve only that page live in the same directory:
```
features/analytics/channel/
- ChannelAnalytics.jsx <- page (exported as default)
- VideoCard.jsx <- sub-component used only here
- useChannelData.js <- hook used only here
+ ChannelAnalytics.tsx <- page (exported as default)
+ ChannelHeader.tsx <- sub-component used only here (props typed by ChannelHeaderProps)
+ useChannelAnalytics.ts <- hook used only here (.ts: no JSX)
+ channelChartData.ts <- pure helper, tested from frontend/tests/
```
-Shared components used across multiple features go in `components/` (shadcn UI pieces) or `components/shared/` (custom cross-feature pieces).
+Shared components used across multiple features go in `components/ui/` (shadcn primitives) or `components/` (project components such as `PageHeader` and `MetricBox`).
### Page components receive no props
@@ -194,9 +195,10 @@ Each page manages its own loading/data/error state. Pages do not write to `AppCo
### Naming
-- Page files: `PascalCase.jsx` matching the feature name - `ChannelAnalytics.jsx`, `Schedule.jsx`
-- Sub-components: `PascalCase.jsx` named for what they render - `VideoCard.jsx`, `StatRow.jsx`
-- Hooks: `camelCase.js` with `use` prefix - `useChannelData.js`
+- Page files: `PascalCase.tsx` matching the feature name - `ChannelAnalytics.tsx`, `UploadContent.tsx`
+- Sub-components: `PascalCase.tsx` named for what they render, with a `<Component>Props` interface - `ChannelHeader.tsx`, `ReelsGrid.tsx`
+- Hooks: `useCamelCase.ts` - `useChannelAnalytics.ts`; export the result type when callers need it
+- Pure helpers: `camelCase.ts` with no JSX, so Node tests can import them - `channelChartData.ts`
- Directories: `camelCase` matching the feature - `analytics/channel/`, `publish/`
## Current Features
@@ -219,9 +221,9 @@ Each page manages its own loading/data/error state. Pages do not write to `AppCo
## Adding a New Feature
-1. Create `frontend/src/features/myFeature/MyPage.jsx`
+1. Create `frontend/src/features/myFeature/MyPage.tsx`
2. Follow `docs/features/NEW_REACT_PAGE.md` for the component template
-3. Add lazy import and route in `App.jsx`
-4. Add sidebar link in `Sidebar.jsx` if it's a top-level destination or per-account page
-5. Add API methods in `api.js`
+3. Add lazy import and route in `App.tsx`
+4. Add a nav item to `NAV_GROUPS` in `layout/navigation.ts` if it's a top-level destination (accounts are listed in the sidebar automatically)
+5. Add API methods in `api.ts` that return the response types from `shared/types/`, then run `npm run typecheck`
6. Update this file with the new entry in the Current Features table
diff --git a/docs/architecture/frontend/REACT_ARCHITECTURE.md b/docs/architecture/frontend/REACT_ARCHITECTURE.md
index 28c105a..8393e80 100644
--- a/docs/architecture/frontend/REACT_ARCHITECTURE.md
+++ b/docs/architecture/frontend/REACT_ARCHITECTURE.md
@@ -4,6 +4,7 @@
| Concern | Library | Version |
|---|---|---|
+| Language | TypeScript (`strict`) | 6.0 |
| Framework | React | 19 |
| Router | React Router | 7 |
| Build tool | Vite | 7 |
@@ -18,17 +19,34 @@
Visual tokens and shared components are described in `DESIGN_SYSTEM.md`.
-## Entry: `frontend/src/main.jsx`
+## TypeScript and Vite
-```jsx
-ReactDOM.createRoot(document.getElementById('root')).render(<App />);
+Every file in `frontend/src` is `.ts`, or `.tsx` when it contains JSX. Vite (with `@vitejs/plugin-react` and `@tailwindcss/vite`, configured in `frontend/vite.config.ts`) strips the types while it serves and builds; it does not check them. `npm run typecheck` does:
+
+| Config | Checks | Notes |
+|---|---|---|
+| `frontend/tsconfig.json` | `frontend/src` | Extends the root `tsconfig.base.json`; DOM lib, `jsx: react-jsx`, `vite/client` types; path aliases `@/*` (to `src/*`) and `@shared/*` (to `../shared/*`) |
+| `frontend/tsconfig.node.json` | `vite.config.ts`, `frontend/tests`, `src/vite-env.d.ts` | Node types |
+
+`src/vite-env.d.ts` types `import.meta.env` (the `VITE_*` variables). `vite.config.ts` defines only the `@` alias: `@shared` imports are always `import type`, which Vite erases before it resolves anything. The API response types come from `shared/types/` (see `API_LAYER.md`); component props are typed with a `<Component>Props` interface in the component file (see `docs/guidelines/TYPESCRIPT.md`).
+
+## Entry: `frontend/src/main.tsx`
+
+`frontend/index.html` loads `/src/main.tsx`:
+
+```tsx
+ReactDOM.createRoot(document.getElementById('root')!).render(
+ <React.StrictMode>
+ <App />
+ </React.StrictMode>
+);
```
-## Application Shell: `frontend/src/App.jsx`
+## Application Shell: `frontend/src/App.tsx`
Defines the router, provider tree, and lazy-loaded page imports.
-**Lazy loading:** All pages except `Login` are wrapped in `React.lazy()`. This means pages are code-split into separate JS chunks and loaded on first navigation. The `<Suspense fallback={null}>` wrapper renders nothing while the chunk loads.
+**Lazy loading:** All pages except `Login` are wrapped in `React.lazy()`. This means pages are code-split into separate chunks and loaded on first navigation. The `<Suspense fallback={null}>` wrapper renders nothing while the chunk loads.
**Router:** Uses `createBrowserRouter` (React Router v7 data router). This enables nested layouts via `<Outlet />` in `MainLayout`.
@@ -37,14 +55,14 @@ Defines the router, provider tree, and lazy-loaded page imports.
```
ThemeProvider (next-themes) <- OS/user theme preference
TooltipProvider (shadcn) <- global tooltip context
- AuthProvider (AuthContext.jsx) <- Supabase session
+ AuthProvider (AuthContext.tsx) <- Supabase session
Suspense (fallback=null)
RouterProvider
/login -> Login (no protection)
/* ->
ProtectedRoute <- redirects to /login if no session
AppProvider <- accounts[], loading, showToast
- AppShell (layout/index.jsx)
+ AppShell (layout/index.tsx)
AppSidebar <- navigation, accounts, categories, user menu
TopBar <- breadcrumb, refresh, theme
(lazy page)
@@ -58,76 +76,77 @@ ThemeProvider (next-themes) <- OS/user theme preference
```
frontend/src/
- main.jsx Entry point
- App.jsx Router + provider tree
+ main.tsx Entry point
+ App.tsx Router + provider tree
index.css Tailwind + CSS variable tokens
lib/
- supabase.js Supabase anon client (singleton)
- utils.js cn() = clsx + tailwind-merge
- accounts.js Platform helpers: paths, names, handles, platform summary
- chart.js Recharts axis, grid, tooltip and series styling
- library.js Filter tiers, paging, duration and engagement helpers
- commandSearch.js Command palette ranking
- holdProgress.js Hold-to-confirm timing
+ supabase.ts Supabase anon client (singleton)
+ utils.ts cn() = clsx + tailwind-merge
+ accounts.ts Platform helpers: paths, names, handles, platform summary
+ chart.ts Recharts axis, grid, tooltip and series styling
+ library.ts Filter tiers, paging, duration and engagement helpers
+ commandSearch.ts Command palette ranking
+ holdProgress.ts Hold-to-confirm timing
services/
- api.js All backend HTTP calls
+ api.ts All backend HTTP calls
context/
- AuthContext.jsx Session, signIn, signUp, signOut
- AppContext.jsx Accounts list, loading, showToast
+ AuthContext.tsx Session, signIn, signUp, signOut
+ AppContext.tsx Accounts list, loading, showToast
utils/
- formatters.js fmtNum, fmtDate, fmtDuration, normalizeAccount, etc.
+ formatters.ts fmtNum, fmtDate, fmtDuration, normalizeAccount, etc.
hooks/
- use-mobile.js useIsMobile()
- use-command-palette-shortcut.js Ctrl+K / Cmd+K toggle
- use-smooth-theme.js useSmoothTheme(), theme cross-fade
- use-cloudinary-config.js useCloudinaryConfig(reloadKey), shared by Publish and Tracked content
- use-account-analytics.js useAccountAnalytics(account, fetchAnalytics, label), shared by Instagram and Reddit analytics
+ use-mobile.ts useIsMobile()
+ use-command-palette-shortcut.ts Ctrl+K / Cmd+K toggle
+ use-smooth-theme.ts useSmoothTheme(), theme cross-fade
+ use-cloudinary-config.ts useCloudinaryConfig(reloadKey), shared by Publish and Tracked content
+ use-account-analytics.ts useAccountAnalytics(account, fetchAnalytics, label), shared by Instagram and Reddit analytics
layout/
- index.jsx AppShell: SidebarProvider + AppSidebar + TopBar + Outlet + CommandPalette
- navigation.js NAV_GROUPS and route titles (single source for sidebar, top bar, palette)
- Sidebar.jsx Collapsible sidebar: logo, search, nav groups, accounts, categories, user menu
- Header.jsx TopBar: breadcrumb, refresh all, theme toggle
+ index.tsx AppShell: SidebarProvider + AppSidebar + TopBar + Outlet + CommandPalette
+ navigation.ts NAV_GROUPS and route titles (single source for sidebar, top bar, palette)
+ Sidebar.tsx Collapsible sidebar: logo, search, nav groups, accounts, categories, user menu
+ Header.tsx TopBar: breadcrumb, refresh all, theme toggle
components/
- ProtectedRoute.jsx Auth guard component
- PageHeader.jsx, SurfaceBox.jsx, MetricBox.jsx, ... Shared components (see DESIGN_SYSTEM.md)
+ ProtectedRoute.tsx Auth guard component
+ PageHeader.tsx, SurfaceBox.tsx, MetricBox.tsx, ... Shared components (see DESIGN_SYSTEM.md)
brand/ Logo and platform icons
ui/ shadcn generated components, restyled onto the tokens
pages/
- Login.jsx Auth page (not lazy-loaded, always small); owns mode, fields and the password toggle
- LoginForm.jsx Email and password form
- LoginBrandPanel.jsx Decorative product preview beside the form
- loginCopy.js Sign-in and sign-up text, privacy link
+ Login.tsx Auth page (not lazy-loaded, always small); owns mode, fields and the password toggle
+ LoginForm.tsx Email and password form
+ LoginBrandPanel.tsx Decorative product preview beside the form
+ loginCopy.ts Sign-in and sign-up text, privacy link
features/
analytics/
- overview/ Overview.jsx - all-accounts dashboard (page; tabs, hooks and helpers beside it)
- channel/ ChannelAnalytics.jsx - per-channel YouTube (page; tabs, hook and helpers beside it)
- instagram/ InstagramAnalytics.jsx - per-account Instagram (page; sections and helpers beside it)
- videos/ VideoExplorer.jsx - all videos table (page; filters, table, grid and helpers beside it)
- shorts/ ShortsExplorer.jsx - shorts-filtered grid (page; filters and grid beside it)
- reels/ ReelsExplorer.jsx - Instagram media grid (page; hook, filters and helpers beside it)
+ overview/ Overview.tsx - all-accounts dashboard (page; tabs, hooks and helpers beside it)
+ channel/ ChannelAnalytics.tsx - per-channel YouTube (page; tabs, hook and helpers beside it)
+ instagram/ InstagramAnalytics.tsx - per-account Instagram (page; sections and helpers beside it)
+ videos/ VideoExplorer.tsx - all videos table (page; filters, table, grid and helpers beside it)
+ shorts/ ShortsExplorer.tsx - shorts-filtered grid (page; filters and grid beside it)
+ reels/ ReelsExplorer.tsx - Instagram media grid (page; hook, filters and helpers beside it)
reddit/ RedditAnalytics (page; sections and helpers beside it), RedditPosts, RedditPostsAll, shared post table
- tracked/ TrackedContent.jsx, TrackedCategory.jsx (pages; components, hooks and helpers beside them)
+ tracked/ TrackedContent.tsx, TrackedCategory.tsx (pages; components, hooks and helpers beside them)
publishing/
- UploadContent.jsx Instagram publishing + schedule queue (page; components, hooks and helpers beside it)
+ UploadContent.tsx Instagram publishing + schedule queue (page; components, hooks and helpers beside it)
accounts/
- AccountManager.jsx Add/remove/refresh accounts (page; dialog, cards, hooks and helpers beside it)
+ AccountManager.tsx Add/remove/refresh accounts (page; dialog, cards, hooks and helpers beside it)
settings/
- Settings.jsx API keys status + GitHub config (page; sections, setup guide, hooks and helpers beside it)
+ Settings.tsx API keys status + GitHub config (page; sections, setup guide, hooks and helpers beside it)
```
-Unit tests are outside `src/`, in `frontend/tests/`, which mirrors this tree: `src/lib/accounts.js` is covered by `frontend/tests/lib/accounts.test.js`. They run on the Node test runner with `npm test` (see `docs/workflows/TESTING.md`), and Vite never bundles them.
+Unit tests are outside `src/`, in `frontend/tests/`, which mirrors this tree: `src/lib/accounts.ts` is covered by `frontend/tests/lib/accounts.test.ts`. They run on the Node test runner with `npm test` (Node strips the types; see `docs/workflows/TESTING.md`), and Vite never bundles them.
## Packages and Tooling
-`frontend/` is a workspace of the root npm workspaces monorepo. Install from the repository root with `npm install`, and add a frontend package with `npm install <pkg> --workspace frontend`; there is no `frontend/package-lock.json`. Shared dev tooling (ESLint and its plugins, `globals`, Prettier, concurrently) is in the root `package.json`, and the lint rules are in the root `eslint.config.mjs`. From the root, `npm run dev:frontend` starts Vite on port 5173, `npm run dev` starts it with the Worker, and `npm run build` builds `frontend/dist/`.
+`frontend/` is a workspace of the root npm workspaces monorepo. Install from the repository root with `npm install`, and add a frontend package with `npm install <pkg> --workspace frontend`; there is no `frontend/package-lock.json`. The frontend's own dev dependencies include `@types/react` and `@types/react-dom`. Shared dev tooling (TypeScript, `typescript-eslint`, `@types/node`, ESLint and its plugins, `globals`, Prettier, concurrently) is in the root `package.json`, and the lint rules are in the root `eslint.config.mjs`. From the root, `npm run dev:frontend` starts Vite on port 5173, `npm run dev` starts it with the Worker, `npm run build` builds `frontend/dist/`, and `npm run typecheck` runs the workspace's `typecheck` script (`tsc -p tsconfig.json && tsc -p tsconfig.node.json`) along with the other projects.
## Naming Conventions
-- Feature files: `PascalCase.jsx` (matches component name)
-- Utility files: `camelCase.js`
-- Context files: `PascalCaseContext.jsx`
-- Hook files: `use-kebab-case.js` in `hooks/` when shared across features; `useCamelCase.js` inside the feature folder when only one feature uses it
-- shadcn ui files: `kebab-case.jsx` (generated convention, do not rename)
+- Feature files: `PascalCase.tsx` (matches component name)
+- Utility files: `camelCase.ts`
+- Context files: `PascalCaseContext.tsx`
+- Hook files: `use-kebab-case.ts` in `hooks/` when shared across features; `useCamelCase.ts` inside the feature folder when only one feature uses it
+- shadcn ui files: `kebab-case.tsx` (generated convention, do not rename; `components.json` sets `tsx: true`)
+- `.tsx` only for files that contain JSX; see `docs/guidelines/NAMING.md`
## Adding a New Page
diff --git a/docs/architecture/frontend/ROUTING.md b/docs/architecture/frontend/ROUTING.md
index 68be732..ff19cf8 100644
--- a/docs/architecture/frontend/ROUTING.md
+++ b/docs/architecture/frontend/ROUTING.md
@@ -2,40 +2,40 @@
## Router Configuration
-The app uses React Router v6 in `frontend/src/App.jsx`. The router uses `BrowserRouter` with a nested layout route.
+The app uses React Router v6 in `frontend/src/App.tsx`. The router uses `BrowserRouter` with a nested layout route.
## Route Table
| Path | Component | Notes |
|---|---|---|
-| `/login` | `Login.jsx` | Public - redirects to `/` if already authenticated |
-| `/docs`, `/docs/*` | `docs/DocsLayout.jsx` | Public documentation. Child routes come from `docsChildRoutes` in `docs/routes.js`; unknown paths redirect to `/docs` |
+| `/login` | `Login.tsx` | Public - redirects to `/` if already authenticated |
+| `/docs`, `/docs/*` | `docs/DocsLayout.tsx` | Public documentation. Child routes come from `docsChildRoutes` in `docs/routes.ts`; unknown paths redirect to `/docs` |
| `/` (layout) | `AppLayout` (inline) | Protected - redirects to `/login` if unauthenticated |
-| `/` (index) | `Overview.jsx` | Default page after login |
-| `/accounts` | `AccountManager.jsx` | Connect and remove accounts. `?add=1` opens the add flow; `?ig_connected` and `?ig_error` report the Instagram OAuth result |
-| `/channel/:id` | `ChannelAnalytics.jsx` | `:id` = account.id for YouTube accounts |
-| `/instagram/:id` | `InstagramAnalytics.jsx` | `:id` = account.id for Instagram accounts |
-| `/reddit/:id` | `RedditAnalytics.jsx` | `:id` = account.id for Reddit accounts |
-| `/reddit-posts` | `RedditPostsAll.jsx` | Combined post explorer across all connected Reddit accounts |
-| `/reddit-posts/:id` | `RedditPosts.jsx` | `:id` = account.id; filterable/sortable post explorer for one account |
-| `/tracked-content` | `TrackedContent.jsx` | Tracked Reddit posts and YouTube videos - add, manage, categorize, refresh |
-| `/tracked-content/category/:name` | `TrackedCategory.jsx` | Per-category analytics page; `:name` is URL-encoded category label; shows YouTube and Reddit sections separately |
+| `/` (index) | `Overview.tsx` | Default page after login |
+| `/accounts` | `AccountManager.tsx` | Connect and remove accounts. `?add=1` opens the add flow; `?ig_connected` and `?ig_error` report the Instagram OAuth result |
+| `/channel/:id` | `ChannelAnalytics.tsx` | `:id` = account.id for YouTube accounts |
+| `/instagram/:id` | `InstagramAnalytics.tsx` | `:id` = account.id for Instagram accounts |
+| `/reddit/:id` | `RedditAnalytics.tsx` | `:id` = account.id for Reddit accounts |
+| `/reddit-posts` | `RedditPostsAll.tsx` | Combined post explorer across all connected Reddit accounts |
+| `/reddit-posts/:id` | `RedditPosts.tsx` | `:id` = account.id; filterable/sortable post explorer for one account |
+| `/tracked-content` | `TrackedContent.tsx` | Tracked Reddit posts and YouTube videos - add, manage, categorize, refresh |
+| `/tracked-content/category/:name` | `TrackedCategory.tsx` | Per-category analytics page; `:name` is URL-encoded category label; shows YouTube and Reddit sections separately |
| `/reddit-tracked` | redirect | Redirects to `/tracked-content` |
-| `/videos` | `VideoExplorer.jsx` | Every video from every YouTube channel |
-| `/shorts` | `ShortsExplorer.jsx` | Videos of 60 seconds or less |
-| `/reels` | `ReelsExplorer.jsx` | Instagram reels, posts and videos |
-| `/upload` | `UploadContent.jsx` | Publish and schedule to Instagram, plus the scheduled post queue |
-| `/settings` | `Settings.jsx` | User/platform settings |
+| `/videos` | `VideoExplorer.tsx` | Every video from every YouTube channel |
+| `/shorts` | `ShortsExplorer.tsx` | Videos of 60 seconds or less |
+| `/reels` | `ReelsExplorer.tsx` | Instagram reels, posts and videos |
+| `/upload` | `UploadContent.tsx` | Publish and schedule to Instagram, plus the scheduled post queue |
+| `/settings` | `Settings.tsx` | User/platform settings |
## Auth Guard
-Auth protection is applied via a `<ProtectedRoute>` component wrapping the layout route in `App.jsx`. All child routes are protected. `/login` and `/docs` are the only public routes.
+Auth protection is applied via a `<ProtectedRoute>` component wrapping the layout route in `App.tsx`. All child routes are protected. `/login` and `/docs` are the only public routes.
## Lazy Loading
All page components are lazy-loaded to reduce initial bundle size:
-```jsx
+```tsx
const Overview = lazy(() => import('./features/analytics/overview/Overview'));
const ChannelAnalytics = lazy(() => import('./features/analytics/channel/ChannelAnalytics'));
// ... etc
@@ -45,17 +45,17 @@ All lazy components are wrapped in `<Suspense>` with a shared fallback.
## Adding a New Route
-1. Add the lazy import at the top of `App.jsx`:
- ```jsx
+1. Add the lazy import at the top of `App.tsx`:
+ ```tsx
const MyPage = lazy(() => import('./features/myFeature/MyPage'));
```
2. Add the route inside the children of the layout route:
- ```jsx
+ ```tsx
{ path: 'my-page/:id', element: <MyPage /> }
```
-3. If the page appears in the sidebar, add it to `NAV_GROUPS` in `layout/navigation.js`. The sidebar, top bar title and command palette all read from it. Detail routes get a title in `DETAIL_ROUTES` in the same file.
+3. If the page appears in the sidebar, add it to `NAV_GROUPS` in `layout/navigation.ts`. The sidebar, top bar title and command palette all read from it. Detail routes get a title in `DETAIL_ROUTES` in the same file.
4. Update the Route Table in this file.
@@ -63,8 +63,8 @@ All lazy components are wrapped in `<Suspense>` with a shared fallback.
The `:id` param in per-account routes always refers to `account.id` - the primary key of the `accounts` table. Pages look up the account from `AppContext`:
-```js
-const { id } = useParams();
+```ts
+const { id } = useParams<{ id: string }>();
const account = accounts.find(a => a.id === id);
```
@@ -72,9 +72,9 @@ If `account` is undefined (invalid ID or account deleted), the page renders an e
## Navigation
-Navigation between routes uses React Router's `<Link>` component or the `useNavigate` hook. Sidebar items render as real links. Per-account links come from `accountPath(account)` in `lib/accounts.js`:
+Navigation between routes uses React Router's `<Link>` component or the `useNavigate` hook. Sidebar items render as real links. Per-account links come from `accountPath(account)` in `lib/accounts.ts`:
-```jsx
+```tsx
accounts.map(account => ({ title: accountName(account), url: accountPath(account) }))
```
diff --git a/docs/features/NEW_ANALYTICS_PAGE.md b/docs/features/NEW_ANALYTICS_PAGE.md
index a3f4bd6..fc490fd 100644
--- a/docs/features/NEW_ANALYTICS_PAGE.md
+++ b/docs/features/NEW_ANALYTICS_PAGE.md
@@ -1,6 +1,6 @@
# Guide: Adding an Analytics Page for a New Platform
-Use this when adding a full analytics view for a new connected platform (e.g., Reddit, Twitter/X, TikTok). This guide is specific to analytics pages that follow the pattern of `ChannelAnalytics.jsx` and `InstagramAnalytics.jsx`.
+Use this when adding a full analytics view for a new connected platform (e.g., Reddit, Twitter/X, TikTok). This guide is specific to analytics pages that follow the pattern of `ChannelAnalytics.tsx` and `InstagramAnalytics.tsx`.
## Architecture Impact
@@ -8,94 +8,112 @@ Adding a platform analytics page touches all layers:
| Layer | What changes |
|---|---|
+| **Shared types** | New `shared/types/<platform>.ts` with the profile, post, analytics and cache shapes |
| **Backend service** | New service file with platform API client, data fetcher, analytics computation |
-| **Backend cache** | New cache key functions in `lib/cache.js` |
+| **Backend cache** | New cache key functions in `lib/cache.ts` |
| **Backend db** | No schema change needed - `platform='reddit'` works with existing `accounts` table |
| **Backend routes** | New analytics routes (`/accounts/:id/platform-analytics`, `/accounts/:id/platform-media`) |
-| **Backend server** | Mount new router in `server.js` |
-| **Frontend api** | New methods in `api.js` |
+| **Backend server** | Mount new router in `server.ts` |
+| **Frontend api** | New methods in `api.ts` |
| **Frontend page** | New analytics page in `features/analytics/platform/` |
-| **Frontend routing** | New route in `App.jsx` |
-| **Frontend navigation** | New nav links in `Sidebar.jsx` for platform accounts |
+| **Frontend routing** | New route in `App.tsx` |
+| **Frontend navigation** | Platform branch in `accountPath()` and `PLATFORM_META` in `lib/accounts.ts`; the sidebar lists accounts from them |
| **Frontend overview** | Add platform KPIs to Overview dashboard if appropriate |
## File Structure to Create
```
+shared/types/
+ reddit.ts <- RedditProfile, RedditPost, RedditAnalytics, RedditCacheData
+
backend/
services/
- reddit.js <- API client + analytics computation
+ reddit.ts <- API client + analytics computation
routes/
- reddit.js <- analytics routes
+ reddit.ts <- analytics routes
frontend/src/
features/
analytics/
reddit/
- RedditAnalytics.jsx
+ RedditAnalytics.tsx
+```
+
+## Step 1: Shared Types
+
+Define what the API returns before writing code that produces or reads it. `shared/types/<platform>.ts` holds types only; both the Worker and the frontend import it with `import type`.
+
+```ts
+// shared/types/reddit.ts
+export interface RedditProfile { username: string; totalKarma: number; /* ... */ }
+export interface RedditPost { id: string; title: string; score: number; /* ... */ }
+export interface RedditAnalytics { /* totals, breakdowns */ }
+export interface RedditCacheData { profile: RedditProfile; analytics: RedditAnalytics; posts: RedditPost[] }
```
-## Step 1: Backend Service
+## Step 2: Backend Service
-Model it after `backend/services/instagram.js`:
+Model it after `backend/services/instagram.ts`. Raw upstream payloads get their own interfaces in the service file, covering only the fields the code reads:
-```js
-// backend/services/reddit.js
+```ts
+// backend/services/reddit.ts
+import type { RedditAnalytics, RedditPost, RedditProfile } from '../../shared/types/reddit.ts';
-async function redditFetch(path, cookies) {
- const res = await fetch(`https://www.reddit.com${path}.json`, {
+async function redditFetch<T>(path: string, cookie: string): Promise<T> {
+ const res = await fetch(`https://www.reddit.com${path}`, {
headers: {
- 'Cookie': cookies,
+ 'Cookie': cookie,
'User-Agent': 'Twiligent/1.0',
},
});
if (!res.ok) throw new Error(`Reddit API ${res.status}`);
- return res.json();
+ return await res.json() as T;
}
-export async function getRedditProfile(username, cookies) { ... }
-export async function getRedditPosts(username, cookies, limit = 100) { ... }
-export function computeRedditAnalytics(posts, profile) {
+export async function fetchRedditProfile(username: string, cookie: string): Promise<RedditProfile> { ... }
+export async function fetchRedditPosts(username: string, cookie: string, limit = 100): Promise<RedditPost[]> { ... }
+export function computeRedditAnalytics(profile: RedditProfile, posts: RedditPost[]): RedditAnalytics {
// Return analytics object with:
// - totalPosts, totalKarma, avgUpvotes, avgComments
// - best performing post
// - posting time distribution
// - subreddit breakdown
// - monthly breakdown
- return { profile, totals: { ... }, posts, monthlyBreakdown: [...] };
+ return { ... };
}
```
-## Step 2: Backend Cache
+## Step 3: Backend Cache
-```js
-// Add to backend/lib/cache.js
-export async function getRedditCache(redis, userId, accountId) {
- if (!redis) return null;
- try { return (await redis.get(`reddit:${userId}:${accountId}`)) || null; } catch { return null; }
+Use the private `readKey`, `writeKey` and `deleteKey` helpers in `cache.ts`; they return early without Redis, swallow Redis errors and apply the analytics TTL:
+
+```ts
+// Add to backend/lib/cache.ts
+export async function getRedditCache(redis: Redis | null, userId: string, accountId: string): Promise<RedditCacheData | null> {
+ return (await readKey<RedditCacheData>(redis, `reddit:${userId}:${accountId}`)) || null;
}
-export async function setRedditCache(redis, userId, accountId, data) {
- if (!redis) return;
- try { await redis.set(`reddit:${userId}:${accountId}`, data); } catch { /* non-fatal */ }
+export async function setRedditCache(redis: Redis | null, userId: string, accountId: string, data: RedditCacheData): Promise<void> {
+ await writeKey(redis, `reddit:${userId}:${accountId}`, data);
}
-export async function deleteRedditCache(redis, userId, accountId) {
- if (!redis) return;
- try { await redis.del(`reddit:${userId}:${accountId}`); } catch { /* non-fatal */ }
+export async function deleteRedditCache(redis: Redis | null, userId: string, accountId: string): Promise<void> {
+ await deleteKey(redis, `reddit:${userId}:${accountId}`);
}
```
-## Step 3: Backend Routes
+## Step 4: Backend Routes
-```js
-// backend/routes/reddit.js
+```ts
+// backend/routes/reddit.ts
import { Hono } from 'hono';
-import { getAccountById } from '../lib/db.js';
-import { getRedditCache, setRedditCache } from '../lib/cache.js';
-import { getRedditProfile, getRedditPosts, computeRedditAnalytics } from '../services/reddit.js';
+import { getAccountById } from '../lib/db.ts';
+import { getRedditCache, setRedditCache } from '../lib/cache.ts';
+import { fetchRedditProfile, fetchRedditPosts, computeRedditAnalytics } from '../services/reddit.ts';
+import type { AppEnv } from '../types/app.ts';
+import type { RedditCacheData } from '../../shared/types/reddit.ts';
-const router = new Hono();
+const router = new Hono<AppEnv>();
router.get('/accounts/:id/reddit-analytics', async (c) => {
const id = c.req.param('id');
@@ -104,42 +122,43 @@ router.get('/accounts/:id/reddit-analytics', async (c) => {
const redis = c.get('redis');
try {
const account = await getAccountById(supabase, id, userId);
- if (!account) return c.json({ error: 'Account not found' }, 404);
+ if (!account || account.platform !== 'reddit') return c.json({ error: 'Reddit account not found' }, 404);
+ if (!account.cookie || !account.username) return c.json({ error: 'No session cookie stored - re-add this account' }, 400);
const cached = await getRedditCache(redis, userId, id);
if (cached) return c.json(cached);
- const profile = await getRedditProfile(account.username, account.cookies);
- const posts = await getRedditPosts(account.username, account.cookies);
- const analytics = computeRedditAnalytics(posts, profile);
+ const profile = await fetchRedditProfile(account.username, account.cookie);
+ const posts = await fetchRedditPosts(account.username, account.cookie);
+ const data: RedditCacheData = { profile, analytics: computeRedditAnalytics(profile, posts), posts };
- await setRedditCache(redis, userId, id, analytics);
- return c.json(analytics);
+ await setRedditCache(redis, userId, id, data);
+ return c.json(data);
} catch (err) {
- console.error(`GET /accounts/${id}/reddit-analytics:`, err.message);
- return c.json({ error: err.message }, 500);
+ console.error(`GET /accounts/${id}/reddit-analytics:`, (err as Error).message);
+ return c.json({ error: (err as Error).message }, 500);
}
});
export default router;
```
-## Step 4: Mount Route + Account Deletion Cache Invalidation
+## Step 5: Mount Route + Account Deletion Cache Invalidation
-```js
-// backend/server.js
-import redditRouter from './routes/reddit.js';
+```ts
+// backend/server.ts
+import redditRouter from './routes/reddit.ts';
api.route('/', redditRouter);
```
-```js
-// backend/routes/accounts.js - in the delete handler
+```ts
+// backend/routes/accounts.ts - in the delete handler
await deleteRedditCache(redis, userId, id); // add alongside existing cache deletes
```
-## Step 5: Frontend Page
+## Step 6: Frontend Page
-Model after `InstagramAnalytics.jsx`. Key sections:
+Model after `InstagramAnalytics.tsx`. Read the data as the shared type (`RedditCacheData`) that `api.ts` returns, and give each sub-component a `<Component>Props` interface. Key sections:
- Profile header (username, follower count, karma)
- KPI row: avg upvotes, avg comments, total posts, engagement rate
- Best performing post card
@@ -147,26 +166,35 @@ Model after `InstagramAnalytics.jsx`. Key sections:
- Subreddit distribution (pie or bar)
- Posting time heatmap (if available)
-## Step 6: Add to App.jsx, Sidebar, and api.js
+## Step 7: Add to App.tsx, lib/accounts.ts, and api.ts
-```jsx
-// App.jsx
+```tsx
+// App.tsx
const RedditAnalytics = lazy(() => import('./features/analytics/reddit/RedditAnalytics'));
// route:
{ path: 'reddit/:id', element: <RedditAnalytics /> }
```
-```js
-// api.js
-getRedditAnalytics: (id) => request(`/accounts/${id}/reddit-analytics`),
+```ts
+// api.ts
+getRedditAnalytics: (id: string) => request<RedditCacheData>(`/accounts/${id}/reddit-analytics`),
```
-```jsx
-// Sidebar.jsx - in per-account link generation for Reddit accounts
-{ title: 'Reddit', url: `/reddit/${account.id}`, icon: RedditIcon }
+```ts
+// lib/accounts.ts - the sidebar and command palette build account links from accountPath()
+export function accountPath(account: AccountFields): string {
+ const platform = platformOf(account);
+ if (platform === 'instagram') return `/instagram/${account.id}`;
+ if (platform === 'reddit') return `/reddit/${account.id}`;
+ return `/channel/${account.id}`;
+}
```
-## Step 7: Update Documentation
+## Step 8: Type-check and Test
+
+Run `npm run typecheck`, `npm run lint` and `npm test` from the repository root. Pure analytics helpers (like `computeRedditAnalytics`) get a test in `backend/tests/services/` at the mirrored path.
+
+## Step 9: Update Documentation
- `docs/architecture/backend/ROUTES.md` - new routes
- `docs/architecture/backend/CACHING.md` - new cache keys
diff --git a/docs/features/NEW_API_ENDPOINT.md b/docs/features/NEW_API_ENDPOINT.md
index bd3d279..8a0e24f 100644
--- a/docs/features/NEW_API_ENDPOINT.md
+++ b/docs/features/NEW_API_ENDPOINT.md
@@ -1,34 +1,65 @@
# Guide: Adding a New API Endpoint
-Follow this guide when adding a route to the Hono backend. Read the existing `backend/routes/accounts.js` and `backend/routes/scheduledPosts.js` as reference implementations before starting.
+Follow this guide when adding a route to the Hono backend. Read the existing `backend/routes/accounts.ts` and `backend/routes/scheduledPosts.ts` as reference implementations before starting, and `docs/guidelines/TYPESCRIPT.md` for the typing rules.
## Files to Create or Modify
| Action | File |
|---|---|
-| Create (if new feature area) | `backend/routes/myFeature.js` |
-| Modify | `backend/lib/db.js` (add query functions) |
-| Modify | `backend/server.js` (mount new router) |
-| Modify | `frontend/src/services/api.js` (add frontend method) |
+| Modify | `shared/types/domain.ts` (or the platform file) - request and response types |
+| Create (if new feature area) | `backend/routes/myFeature.ts` |
+| Modify | `backend/lib/db.ts` (add query functions) |
+| Modify | `backend/server.ts` (mount new router) |
+| Modify | `frontend/src/services/api.ts` (add frontend method) |
+| Create | `backend/tests/routes/myFeature.test.ts` |
| Update | `docs/architecture/backend/ROUTES.md` |
-## Step 1: Add Database Functions (if needed)
+## Step 1: Define the Request and Response Types
-In `backend/lib/db.js`, add query functions for the new resource. Follow the established patterns:
+Add the shapes the endpoint sends and receives to `shared/types/` first. Use `domain.ts` for cross-platform data, or `youtube.ts`, `instagram.ts` or `reddit.ts` for platform data. These files hold types only and never import runtime code.
+
+```ts
+// shared/types/domain.ts
+export interface MyResource {
+ id: string;
+ name: string;
+}
+
+export interface MyResourceCreateRequest {
+ name: string;
+}
+
+export interface MyResourceCreateResponse {
+ success: true;
+ id: string;
+}
+```
+
+When you change an existing route's response, change its type here first: `npm run typecheck` then lists every backend and frontend file that reads the old shape.
+
+## Step 2: Add Database Functions (if needed)
+
+In `backend/lib/db.ts`, add query functions for the new resource. Follow the established patterns:
+
+```ts
+interface MyResourceRow {
+ id: string;
+ name: string;
+ data: Record<string, unknown>;
+}
-```js
// For user-scoped data: always accept userId, always apply .eq('user_id', userId)
-export async function getMyResources(supabase, userId) {
+export async function getMyResources(supabase: SupabaseClient, userId: string): Promise<MyResource[]> {
const { data, error } = await supabase
.from('my_table')
.select('id, name, data')
.eq('user_id', userId)
.order('created_at', { ascending: false });
if (error) throw error;
- return (data || []).map(row => ({ id: row.id, name: row.name, ...row.data }));
+ return ((data || []) as MyResourceRow[]).map(row => ({ id: row.id, name: row.name, ...row.data }));
}
-export async function createMyResource(supabase, resource, userId) {
+export async function createMyResource(supabase: SupabaseClient, resource: MyResource, userId: string): Promise<void> {
const { id, name, ...rest } = resource;
const { error } = await supabase
.from('my_table')
@@ -37,71 +68,86 @@ export async function createMyResource(supabase, resource, userId) {
}
```
-## Step 2: Add Service Functions (if external API calls needed)
+## Step 3: Add Service Functions (if external API calls needed)
-In `backend/services/myPlatform.js`, add functions for external API calls. Keep business logic out of routes.
+In `backend/services/myPlatform.ts`, add functions for external API calls. Keep business logic out of routes. Describe each upstream payload with an interface that covers the fields the service reads, kept in the service module.
-## Step 3: Create the Route File
+## Step 4: Create the Route File
-```js
-// backend/routes/myFeature.js
+```ts
+// backend/routes/myFeature.ts
import { Hono } from 'hono';
-import { getMyResources, createMyResource } from '../lib/db.js';
+import { getMyResources, createMyResource } from '../lib/db.ts';
+import type { AppEnv } from '../types/app.ts';
+import type { MyResource, MyResourceCreateRequest, MyResourceCreateResponse } from '../../shared/types/domain.ts';
-const router = new Hono();
+const router = new Hono<AppEnv>();
router.get('/my-resources', async (c) => {
const userId = c.get('userId');
const supabase = c.get('supabase');
try {
const resources = await getMyResources(supabase, userId);
- return c.json(resources);
+ return c.json(resources satisfies MyResource[]);
} catch (err) {
- console.error('GET /my-resources:', err.message);
- return c.json({ error: err.message }, 500);
+ console.error('GET /my-resources:', (err as Error).message);
+ return c.json({ error: (err as Error).message }, 500);
}
});
router.post('/my-resources', async (c) => {
const userId = c.get('userId');
const supabase = c.get('supabase');
- const body = await c.req.json();
- const { name } = body;
+ const { name } = await c.req.json() as MyResourceCreateRequest;
if (!name) return c.json({ error: 'Missing required field: name' }, 400);
try {
const id = Date.now().toString(36) + Math.random().toString(36).slice(2);
await createMyResource(supabase, { id, name }, userId);
- return c.json({ success: true, id }, 201);
+ return c.json({ success: true, id } satisfies MyResourceCreateResponse, 201);
} catch (err) {
- console.error('POST /my-resources:', err.message);
- return c.json({ error: err.message }, 500);
+ console.error('POST /my-resources:', (err as Error).message);
+ return c.json({ error: (err as Error).message }, 500);
}
});
export default router;
```
-## Step 4: Mount in server.js
+## Step 5: Mount in server.ts
-```js
-// backend/server.js
-import myFeatureRouter from './routes/myFeature.js';
+```ts
+// backend/server.ts
+import myFeatureRouter from './routes/myFeature.ts';
// ...
api.route('/', myFeatureRouter);
```
-## Step 5: Add Frontend API Methods
+Routes mounted on `api` get authentication and the per-IP and per-user rate limits automatically. If the endpoint spends platform API quota or publishes, add it to `QUOTA_ROUTES` or `PUBLISH_ROUTES` in `backend/lib/rateLimit/rules.ts` (see `docs/architecture/backend/RATE_LIMITING.md`).
+
+## Step 6: Add Frontend API Methods
+
+```ts
+// frontend/src/services/api.ts
+import type { MyResource, MyResourceCreateRequest, MyResourceCreateResponse } from '@shared/types/domain.ts';
-```js
-// frontend/src/services/api.js
export const api = {
// ... existing methods
- getMyResources: () => request('/my-resources'),
- createMyResource: (data) => request('/my-resources', { method: 'POST', body: JSON.stringify(data) }),
+ getMyResources: () => request<MyResource[]>('/my-resources'),
+ createMyResource: (data: MyResourceCreateRequest) => request<MyResourceCreateResponse>('/my-resources', { method: 'POST', body: JSON.stringify(data) }),
};
```
-## Step 6: Update Documentation
+If the route can answer `{ success: false, message }` with a 2xx status, return `request<ApiResult<T>>` instead so callers check `success` (see `docs/architecture/frontend/API_LAYER.md`).
+
+## Step 7: Type-check
+
+```bash
+npm run typecheck
+```
+
+Fix every error before moving on. Wrangler and Vite strip types without checking them, so this is the only place a wrong shape is caught.
+
+## Step 8: Update Documentation
Add the new routes to `docs/architecture/backend/ROUTES.md`.
@@ -111,12 +157,12 @@ Add the new routes to `docs/architecture/backend/ROUTES.md`.
- [ ] Route handler reads `userId` from `c.get('userId')` - not from request body
- [ ] All DB queries include `.eq('user_id', userId)` for user-scoped data
- [ ] Any account data in the response passes through `safeAccount()` if it contains tokens
-- [ ] Input validation returns 400 for missing required fields
+- [ ] Input validation returns 400 for missing required fields (the `as` cast on `c.req.json()` checks nothing at runtime)
- [ ] Errors are caught and return JSON with appropriate status code
## Testing
-Pure logic behind the route (validation, response shaping) gets a unit test in `backend/tests/`, at the path that mirrors the source file: a handler in `backend/routes/myFeature.js` is tested in `backend/tests/routes/myFeature.test.js`. Route tests run the real handler against the fakes in `backend/tests/fixtures/` (`routeHarness.js`, `fakeSupabase.js`, `fakeFetch.js`) and compare the result with a `*.golden.json` snapshot there; see `backend/tests/routes/accounts.test.js` and `docs/workflows/TESTING.md`. Run `npm test` from the repository root.
+Pure logic behind the route (validation, response shaping) gets a unit test in `backend/tests/`, at the path that mirrors the source file: a handler in `backend/routes/myFeature.ts` is tested in `backend/tests/routes/myFeature.test.ts`. Route tests run the real handler against the fakes in `backend/tests/fixtures/` (`routeHarness.ts`, `fakeSupabase.ts`, `fakeFetch.ts`) and compare the result with a `*.golden.json` snapshot there; see `backend/tests/routes/accounts.test.ts` and `docs/workflows/TESTING.md`. Run `npm test` and `npm run typecheck` from the repository root.
```bash
# Local test, from the repository root
diff --git a/docs/features/NEW_DATABASE_TABLE.md b/docs/features/NEW_DATABASE_TABLE.md
index b23d4d8..7745fed 100644
--- a/docs/features/NEW_DATABASE_TABLE.md
+++ b/docs/features/NEW_DATABASE_TABLE.md
@@ -57,72 +57,108 @@ CREATE POLICY "Users can manage their own drafts"
USING (user_id = auth.uid());
```
-### Step 4: Add Query Functions to `lib/db.js`
+### Step 4: Add the Types
+
+Add the entity as the API returns it to `shared/types/domain.ts` (types only, no runtime code). Status columns become a union of string literals, never an `enum`:
+
+```ts
+// shared/types/domain.ts
+export type DraftStatus = 'draft' | 'ready' | 'archived';
+
+export interface ContentDraft {
+ id: string;
+ accountId: string;
+ platform: Platform;
+ status: DraftStatus;
+ createdAt: string;
+ updatedAt: string;
+ caption?: string;
+}
+
+export type ContentDraftUpdate = Partial<Omit<ContentDraft, 'id' | 'accountId' | 'platform' | 'createdAt' | 'updatedAt'>>;
+```
+
+The raw row shape stays private to `lib/db.ts`, next to the functions that read it.
+
+### Step 5: Add Query Functions to `lib/db.ts`
Follow the established pattern exactly:
-```js
-// backend/lib/db.js
+```ts
+// backend/lib/db.ts
+interface ContentDraftRow {
+ id: string;
+ account_id: string;
+ platform: Platform;
+ status: DraftStatus;
+ created_at: string;
+ updated_at: string;
+ data: Partial<ContentDraft> | null;
+}
-// ── Content Drafts ────────────────────────────────────────────────────────────
+function rowToDraft(row: ContentDraftRow): ContentDraft {
+ return {
+ ...(row.data || {}),
+ id: row.id,
+ accountId: row.account_id,
+ platform: row.platform,
+ status: row.status,
+ createdAt: row.created_at,
+ updatedAt: row.updated_at,
+ };
+}
-export async function getDrafts(supabase, userId) {
+export async function getDrafts(supabase: SupabaseClient, userId: string): Promise<ContentDraft[]> {
const { data, error } = await supabase
.from('content_drafts')
.select('id, account_id, platform, status, created_at, updated_at, data')
.eq('user_id', userId)
.order('created_at', { ascending: false });
if (error) throw error;
- return (data || []).map(row => ({
- id: row.id,
- accountId: row.account_id,
- platform: row.platform,
- status: row.status,
- createdAt: row.created_at,
- updatedAt: row.updated_at,
- ...(row.data || {}),
- }));
+ return ((data || []) as ContentDraftRow[]).map(rowToDraft);
}
-export async function createDraft(supabase, draft, userId) {
- const { id, accountId, platform, ...rest } = draft;
+export async function createDraft(supabase: SupabaseClient, draft: ContentDraft, userId: string): Promise<void> {
+ const { id, accountId, platform, status, createdAt: _c, updatedAt: _u, ...rest } = draft;
const { error } = await supabase.from('content_drafts').insert({
id,
user_id: userId,
account_id: accountId,
platform,
+ status,
data: rest,
});
if (error) throw error;
}
-export async function updateDraft(supabase, id, updates, userId) {
+export async function updateDraft(supabase: SupabaseClient, id: string, updates: ContentDraftUpdate, userId: string | null = null): Promise<void> {
// Merge data fields with existing (never replace the whole data object)
const current = await getDraftById(supabase, id, userId);
if (!current) throw new Error('Draft not found: ' + id);
- const colUpdates = { updated_at: new Date().toISOString() };
- if (updates.status) colUpdates.status = updates.status;
- // merge data fields
- const { status: _, accountId: __, ...dataUpdates } = updates;
+ const colUpdates: { updated_at: string; status?: DraftStatus; data?: Partial<ContentDraft> } = { updated_at: new Date().toISOString() };
+ const { status, ...dataUpdates } = updates;
+ if (status) colUpdates.status = status;
if (Object.keys(dataUpdates).length > 0) {
const { id: _id, accountId: _aid, platform: _p, status: _s, createdAt: _c, updatedAt: _u, ...currentData } = current;
colUpdates.data = { ...currentData, ...dataUpdates };
}
- let q = supabase.from('content_drafts').update(colUpdates).eq('id', id);
- if (userId) q = q.eq('user_id', userId);
- const { error } = await q;
+ let query = supabase.from('content_drafts').update(colUpdates).eq('id', id);
+ if (userId) query = query.eq('user_id', userId);
+ const { error } = await query;
if (error) throw error;
}
-export async function deleteDraft(supabase, id, userId) {
- let q = supabase.from('content_drafts').delete().eq('id', id);
- if (userId) q = q.eq('user_id', userId);
- const { error } = await q;
+export async function deleteDraft(supabase: SupabaseClient, id: string, userId: string | null = null): Promise<void> {
+ let query = supabase.from('content_drafts').delete().eq('id', id);
+ if (userId) query = query.eq('user_id', userId);
+ const { error } = await query;
if (error) throw error;
}
```
-### Step 5: Document the Schema
+Run `npm run typecheck` from the root after adding them.
+
+### Step 6: Document the Schema
Update `docs/architecture/database/SCHEMA.md` with:
- Table name and purpose
@@ -130,12 +166,12 @@ Update `docs/architecture/database/SCHEMA.md` with:
- The `data` jsonb shape
- Recommended indexes
-### Step 6: Wire Up the Feature
+### Step 7: Wire Up the Feature
Follow the guides for:
- `docs/features/NEW_API_ENDPOINT.md` - add backend routes
- `docs/features/NEW_REACT_PAGE.md` - add frontend page
-- `docs/features/NEW_API_ENDPOINT.md` - add frontend api.js methods
+- `docs/features/NEW_API_ENDPOINT.md` - add frontend api.ts methods
## Naming Conventions for New Tables
diff --git a/docs/features/NEW_INTEGRATION.md b/docs/features/NEW_INTEGRATION.md
index ef0f0ff..9d1bff5 100644
--- a/docs/features/NEW_INTEGRATION.md
+++ b/docs/features/NEW_INTEGRATION.md
@@ -1,6 +1,6 @@
# Guide: Adding a New Platform Integration
-A "platform integration" is a new social or content platform (e.g., Reddit, Twitter/X, TikTok, LinkedIn). This guide walks through every layer that needs to change.
+A "platform integration" is a new social or content platform (e.g., Reddit, Twitter/X, TikTok, LinkedIn). This guide walks through every layer that needs to change. Read `docs/guidelines/TYPESCRIPT.md` first: the types for the new platform are written before the code that uses them.
## Decision Checklist Before Starting
@@ -18,32 +18,102 @@ Document the answers in `DECISIONS.md` as a new ADR before writing any code.
| Layer | File | Action |
|---|---|---|
-| Backend | `backend/services/{platform}.js` | Create |
-| Backend | `backend/routes/{platform}.js` | Create |
-| Backend | `backend/lib/db.js` | Extend (if needed) |
-| Backend | `backend/lib/cache.js` | Extend |
-| Backend | `backend/server.js` | Mount router |
-| Backend | `wrangler.toml` | Add secrets |
-| Frontend | `frontend/src/services/api.js` | Add methods |
+| Shared | `shared/types/{platform}.ts` | Create: profile, post, analytics and cache types |
+| Shared | `shared/types/domain.ts` | Add the platform to `Platform` and its fields to `Account` |
+| Backend | `backend/services/{platform}.ts` | Create |
+| Backend | `backend/routes/{platform}.ts` | Create |
+| Backend | `backend/lib/db.ts` | Extend (if needed) |
+| Backend | `backend/lib/cache.ts` | Extend |
+| Backend | `backend/lib/safeAccount.ts` | Add secret fields to `SECRET_FIELDS` (and to `SafeAccount` in `shared/types/domain.ts`) |
+| Backend | `backend/types/env.ts` | Add new secrets to `Env` |
+| Backend | `backend/server.ts` | Mount router |
+| Frontend | `frontend/src/services/api.ts` | Add methods |
| Frontend | `frontend/src/features/` | Create page(s) |
-| Frontend | `frontend/src/App.jsx` | Add routes |
-| Frontend | `frontend/src/lib/accounts.js`, `frontend/src/components/brand/platform-icons.jsx` | Add the platform to `PLATFORM_META`, `platformOf()`, `accountPath()` and an icon; the sidebar lists accounts automatically |
-| Frontend | `frontend/src/context/AppContext.jsx` | Add normalization |
-| Config | `.github/workflows/deploy-backend.yml` | Add new secret |
+| Frontend | `frontend/src/App.tsx` | Add routes |
+| Frontend | `frontend/src/lib/accounts.ts`, `frontend/src/components/brand/platform-icons.tsx` | Add the platform to `PLATFORM_META`, `platformOf()`, `accountPath()` and an icon; the sidebar lists accounts automatically |
+| Frontend | `frontend/src/utils/formatters.ts` | Add normalization in `normalizeAccount()` |
+| Config | `.github/workflows/deploy-backend.yml` | Add new secret (only if a workflow step needs it) |
| Docs | `DECISIONS.md` | Add ADR |
| Docs | `CHANGELOG.md` | Add entry |
| Docs | `docs/architecture/backend/SERVICES.md` | Document service |
| Docs | `docs/architecture/backend/ROUTES.md` | Document routes |
| Docs | `docs/architecture/backend/CACHING.md` | Document cache keys |
-## Step 1: Create the Service File
+## Step 1: Define the Types
-```js
-// backend/services/twitter.js
+Add the platform to the shared `Platform` union and its stored fields to `Account` in `shared/types/domain.ts`, then create `shared/types/twitter.ts` for what the API returns. The type checker then points at every `switch` or lookup on `platform` that needs a new branch.
-// API client wrapper
-async function twitterFetch(path, accessToken, method = 'GET', body = null) {
- const options = {
+```ts
+// shared/types/domain.ts
+export type Platform = 'youtube' | 'instagram' | 'reddit' | 'twitter';
+
+export interface Account {
+ // ...existing fields
+ // twitter
+ refreshToken?: string;
+}
+```
+
+```ts
+// shared/types/twitter.ts
+export interface TwitterProfileSummary {
+ username: string;
+ name: string;
+ followers: number;
+ following: number;
+ tweetCount: number;
+}
+
+export interface TwitterTweet {
+ id: string;
+ text: string;
+ createdAt: string;
+ likeCount: number;
+ retweetCount: number;
+ replyCount: number;
+}
+
+export interface TwitterAnalytics {
+ profile: TwitterProfileSummary;
+ totals: { totalLikes: number; totalRetweets: number; totalReplies: number; avgEngagement: number };
+ tweets: TwitterTweet[];
+}
+
+export interface TweetPostResponse {
+ success: true;
+ tweetId: string | undefined;
+}
+```
+
+## Step 2: Create the Service File
+
+Raw API payloads get interfaces in the service file, covering only the fields the code reads.
+
+```ts
+// backend/services/twitter.ts
+import type { TwitterAnalytics, TwitterTweet } from '../../shared/types/twitter.ts';
+
+interface TwitterApiUser {
+ id: string;
+ username: string;
+ name: string;
+ public_metrics: { followers_count: number; following_count: number; tweet_count: number };
+}
+
+interface TwitterApiTweet {
+ id: string;
+ text: string;
+ created_at: string;
+ public_metrics?: { like_count?: number; retweet_count?: number; reply_count?: number };
+}
+
+interface TwitterApiError {
+ title?: string;
+ detail?: string;
+}
+
+async function twitterFetch<T>(path: string, accessToken: string, method = 'GET', body: unknown = null): Promise<T> {
+ const options: RequestInit = {
method,
headers: {
'Authorization': `Bearer ${accessToken}`,
@@ -53,33 +123,40 @@ async function twitterFetch(path, accessToken, method = 'GET', body = null) {
if (body) options.body = JSON.stringify(body);
const res = await fetch(`https://api.twitter.com/2${path}`, options);
if (!res.ok) {
- const err = await res.json().catch(() => ({ title: res.statusText }));
+ const err = await res.json().catch(() => ({ title: res.statusText })) as TwitterApiError;
throw new Error(`Twitter API ${res.status}: ${err.title || err.detail || res.statusText}`);
}
- return res.json();
+ return await res.json() as T;
}
-// Account-level functions
-export async function getTwitterProfile(accessToken) {
- const { data } = await twitterFetch('/users/me?user.fields=public_metrics,profile_image_url', accessToken);
+export async function getTwitterProfile(accessToken: string): Promise<TwitterApiUser> {
+ const { data } = await twitterFetch<{ data: TwitterApiUser }>('/users/me?user.fields=public_metrics,profile_image_url', accessToken);
return data;
}
-export async function getTwitterTweets(userId, accessToken) {
- const { data } = await twitterFetch(
+export async function getTwitterTweets(userId: string, accessToken: string): Promise<TwitterApiTweet[]> {
+ const { data } = await twitterFetch<{ data?: TwitterApiTweet[] }>(
`/users/${userId}/tweets?max_results=100&tweet.fields=public_metrics,created_at`,
- accessToken
+ accessToken,
);
return data || [];
}
// Analytics computation (pure function - easy to test)
-export function computeTwitterAnalytics(tweets, profile) {
- const totalLikes = tweets.reduce((sum, t) => sum + (t.public_metrics?.like_count || 0), 0);
- const totalRetweets = tweets.reduce((sum, t) => sum + (t.public_metrics?.retweet_count || 0), 0);
- const totalReplies = tweets.reduce((sum, t) => sum + (t.public_metrics?.reply_count || 0), 0);
+export function computeTwitterAnalytics(apiTweets: TwitterApiTweet[], profile: TwitterApiUser): TwitterAnalytics {
+ const tweets: TwitterTweet[] = apiTweets.map(t => ({
+ id: t.id,
+ text: t.text,
+ createdAt: t.created_at,
+ likeCount: t.public_metrics?.like_count || 0,
+ retweetCount: t.public_metrics?.retweet_count || 0,
+ replyCount: t.public_metrics?.reply_count || 0,
+ }));
+ const totalLikes = tweets.reduce((sum, t) => sum + t.likeCount, 0);
+ const totalRetweets = tweets.reduce((sum, t) => sum + t.retweetCount, 0);
+ const totalReplies = tweets.reduce((sum, t) => sum + t.replyCount, 0);
const avgEngagement = tweets.length > 0
- ? ((totalLikes + totalRetweets + totalReplies) / tweets.length).toFixed(2)
+ ? Number(((totalLikes + totalRetweets + totalReplies) / tweets.length).toFixed(2))
: 0;
return {
@@ -95,51 +172,59 @@ export function computeTwitterAnalytics(tweets, profile) {
};
}
-// Strip access token before sending to frontend
-export function safeTwitterAccount(account) {
- const safe = { ...account };
- delete safe.accessToken;
- delete safe.refreshToken;
- return safe;
-}
-
// Publishing (if applicable)
-export async function postTweet(text, accessToken) {
+export async function postTweet(text: string, accessToken: string): Promise<{ data?: { id: string } }> {
return twitterFetch('/tweets', accessToken, 'POST', { text });
}
```
-## Step 2: Create Cache Functions
+## Step 3: Strip Secrets From Responses
+
+`safeAccount()` in `backend/lib/safeAccount.ts` removes every field listed in `SECRET_FIELDS` before an account reaches the frontend. Add the new platform's secret fields there instead of writing a per-platform function:
+
+```ts
+const SECRET_FIELDS: (keyof Account)[] = ['accessToken', 'cookie', 'encryptedPassword', 'encryptedTotpSecret', 'authToken', 'ct0', 'refreshToken'];
+```
+
+Add the same field to the `Omit` list of `SafeAccount` in `shared/types/domain.ts`, so the frontend type does not claim the field exists.
+
+## Step 4: Create Cache Functions
+
+Use the private `readKey`, `writeKey` and `deleteKey` helpers in `cache.ts`; they return early without Redis and swallow Redis errors.
-```js
-// Additions to backend/lib/cache.js
+```ts
+// Additions to backend/lib/cache.ts
+import type { TwitterAnalytics } from '../../shared/types/twitter.ts';
-export async function getTwitterCache(redis, userId, accountId) {
- if (!redis) return null;
- try { return (await redis.get(`twitter:${userId}:${accountId}`)) || null; } catch { return null; }
+export async function getTwitterCache(redis: Redis | null, userId: string, accountId: string): Promise<TwitterAnalytics | null> {
+ return (await readKey<TwitterAnalytics>(redis, `twitter:${userId}:${accountId}`)) || null;
}
-export async function setTwitterCache(redis, userId, accountId, data) {
- if (!redis) return;
- try { await redis.set(`twitter:${userId}:${accountId}`, data); } catch { /* non-fatal */ }
+export async function setTwitterCache(redis: Redis | null, userId: string, accountId: string, data: TwitterAnalytics): Promise<void> {
+ await writeKey(redis, `twitter:${userId}:${accountId}`, data);
}
-export async function deleteTwitterCache(redis, userId, accountId) {
- if (!redis) return;
- try { await redis.del(`twitter:${userId}:${accountId}`); } catch { /* non-fatal */ }
+export async function deleteTwitterCache(redis: Redis | null, userId: string, accountId: string): Promise<void> {
+ await deleteKey(redis, `twitter:${userId}:${accountId}`);
}
```
-## Step 3: Create Route File
+## Step 5: Create Route File
-```js
-// backend/routes/twitter.js
+```ts
+// backend/routes/twitter.ts
import { Hono } from 'hono';
-import { getAccountById } from '../lib/db.js';
-import { getTwitterCache, setTwitterCache } from '../lib/cache.js';
-import { getTwitterProfile, getTwitterTweets, computeTwitterAnalytics, safeTwitterAccount, postTweet } from '../services/twitter.js';
+import { getAccountById } from '../lib/db.ts';
+import { getTwitterCache, setTwitterCache } from '../lib/cache.ts';
+import { getTwitterProfile, getTwitterTweets, computeTwitterAnalytics, postTweet } from '../services/twitter.ts';
+import type { AppEnv } from '../types/app.ts';
+import type { TweetPostResponse } from '../../shared/types/twitter.ts';
+
+interface TweetRequest {
+ text?: string;
+}
-const router = new Hono();
+const router = new Hono<AppEnv>();
// Analytics
router.get('/accounts/:id/twitter-analytics', async (c) => {
@@ -149,7 +234,7 @@ router.get('/accounts/:id/twitter-analytics', async (c) => {
const redis = c.get('redis');
try {
const account = await getAccountById(supabase, id, userId);
- if (!account) return c.json({ error: 'Account not found' }, 404);
+ if (!account || account.platform !== 'twitter' || !account.accessToken) return c.json({ error: 'Account not found' }, 404);
const cached = await getTwitterCache(redis, userId, id);
if (cached) return c.json(cached);
@@ -161,8 +246,8 @@ router.get('/accounts/:id/twitter-analytics', async (c) => {
await setTwitterCache(redis, userId, id, analytics);
return c.json(analytics);
} catch (err) {
- console.error(`GET /accounts/${id}/twitter-analytics:`, err.message);
- return c.json({ error: err.message }, 500);
+ console.error(`GET /accounts/${id}/twitter-analytics:`, (err as Error).message);
+ return c.json({ error: (err as Error).message }, 500);
}
});
@@ -171,91 +256,106 @@ router.post('/accounts/:id/tweet', async (c) => {
const id = c.req.param('id');
const userId = c.get('userId');
const supabase = c.get('supabase');
- const body = await c.req.json();
- if (!body.text) return c.json({ error: 'Missing text' }, 400);
+ const { text } = await c.req.json() as TweetRequest;
+ if (!text) return c.json({ error: 'Missing text' }, 400);
try {
const account = await getAccountById(supabase, id, userId);
- if (!account) return c.json({ error: 'Account not found' }, 404);
- const result = await postTweet(body.text, account.accessToken);
- return c.json({ success: true, tweetId: result.data?.id });
+ if (!account || !account.accessToken) return c.json({ error: 'Account not found' }, 404);
+ const result = await postTweet(text, account.accessToken);
+ return c.json({ success: true, tweetId: result.data?.id } satisfies TweetPostResponse);
} catch (err) {
- console.error(`POST /accounts/${id}/tweet:`, err.message);
- return c.json({ error: err.message }, 500);
+ console.error(`POST /accounts/${id}/tweet:`, (err as Error).message);
+ return c.json({ error: (err as Error).message }, 500);
}
});
export default router;
```
-## Step 4: Mount in server.js
+## Step 6: Mount in server.ts
-```js
-// backend/server.js
-import twitterRouter from './routes/twitter.js';
+```ts
+// backend/server.ts
+import twitterRouter from './routes/twitter.ts';
api.route('/', twitterRouter);
```
-## Step 5: Add Cache Invalidation on Account Delete
+Add publishing and quota-spending routes to `PUBLISH_ROUTES` or `QUOTA_ROUTES` in `backend/lib/rateLimit/rules.ts` (see `docs/architecture/backend/RATE_LIMITING.md`).
+
+## Step 7: Add Cache Invalidation on Account Delete
-In `backend/routes/accounts.js`, add the cache delete alongside existing ones:
+In `backend/routes/accounts.ts`, add the cache delete alongside existing ones:
-```js
+```ts
await deleteTwitterCache(redis, userId, id);
```
-## Step 6: Declare New Secrets
+## Step 8: Declare New Secrets
+
+Declare each secret in the `Env` interface in `backend/types/env.ts`, so `c.env.TWITTER_CLIENT_ID` type-checks. Use `?: string` for optional secrets and handle the missing case.
-```toml
-# wrangler.toml
-[vars]
-# (no vars for platform-specific secrets - use secrets)
+```ts
+// backend/types/env.ts
+export interface Env {
+ // ...existing bindings
+ TWITTER_CLIENT_ID?: string;
+ TWITTER_CLIENT_SECRET?: string;
+}
```
+Then set the values on the Worker; never put them in `wrangler.toml`:
+
```bash
-# Add the secrets to the Worker
cd backend
npx wrangler secret put TWITTER_CLIENT_ID
npx wrangler secret put TWITTER_CLIENT_SECRET
```
-Add corresponding secrets to GitHub Actions if the CI/CD pipeline needs them.
+Add corresponding secrets to GitHub Actions only if a workflow step needs them. The deploy workflow does not pass Worker secrets; they live on the Worker.
-## Step 7: Account Normalization in AppContext
+## Step 9: Account Normalization
-The frontend `normalizeAccount()` function in `AppContext.jsx` maps raw DB rows to a consistent shape. Add normalization for the new platform:
+`normalizeAccount()` in `frontend/src/utils/formatters.ts` maps the account list from `GET /api/accounts` to the `AppAccount` shape that `AppContext` keeps. Add a branch for the new platform:
-```js
-// frontend/src/context/AppContext.jsx
-function normalizeAccount(raw) {
+```ts
+// frontend/src/utils/formatters.ts
+export function normalizeAccount(acct: AccountInput): AppAccount {
// ...existing platforms...
- if (raw.platform === 'twitter') {
+ if (acct.platform === 'twitter') {
return {
- id: raw.id,
- platform: 'twitter',
- title: raw.data?.username ? `@${raw.data.username}` : 'Twitter Account',
- username: raw.data?.username,
- profileImage: raw.data?.profileImage,
+ ...acct,
+ title: acct.title || `@${acct.username}`,
+ thumbnail: acct.profilePictureUrl || '',
};
}
// ...
}
```
-## Step 8: Add Frontend Pages
+## Step 10: Add Frontend Pages
-Follow `docs/features/NEW_REACT_PAGE.md` and `docs/features/NEW_ANALYTICS_PAGE.md`.
+Follow `docs/features/NEW_REACT_PAGE.md` and `docs/features/NEW_ANALYTICS_PAGE.md`. The `api.ts` methods return the types from `shared/types/twitter.ts`:
-## Step 9: OAuth Flow (if applicable)
+```ts
+getTwitterAnalytics: (id: string) => request<TwitterAnalytics>(`/accounts/${id}/twitter-analytics`),
+postTweet: (id: string, text: string) => request<TweetPostResponse>(`/accounts/${id}/tweet`, { method: 'POST', body: JSON.stringify({ text }) }),
+```
+
+## Step 11: OAuth Flow (if applicable)
If the platform uses OAuth:
- Backend: add `GET /auth/{platform}/start` and `GET /auth/{platform}/callback` routes
-- Use the HMAC-signed state pattern (see `docs/architecture/backend/CACHING.md` and `ADR-006` in `DECISIONS.md`)
+- Use the HMAC-signed state pattern in `backend/lib/oauthState.ts` (see `docs/architecture/backend/CACHING.md` and `ADR-006` in `DECISIONS.md`)
- Store tokens in `accounts.data` - never in a separate table
- Delete cache on every token refresh
+## Step 12: Verify
+
+Run `npm run typecheck`, `npm run lint` and `npm test` from the repository root. Add tests for the pure helpers (such as `computeTwitterAnalytics`) in `backend/tests/services/twitter.test.ts`.
+
## Security Checklist
-- [ ] Access token never returned in any API response (use `safeTwitterAccount()` or equivalent)
+- [ ] Every secret field is listed in `SECRET_FIELDS`, so `safeAccount()` strips it from every API response
- [ ] Access token read from `account.accessToken` on the backend - never passed from frontend
- [ ] OAuth callback validates HMAC state before accepting code
- [ ] New Worker secrets added with `npx wrangler secret put` - not stored in `wrangler.toml` plaintext
diff --git a/docs/features/NEW_REACT_PAGE.md b/docs/features/NEW_REACT_PAGE.md
index 3c41fcb..0844f90 100644
--- a/docs/features/NEW_REACT_PAGE.md
+++ b/docs/features/NEW_REACT_PAGE.md
@@ -1,43 +1,47 @@
# Guide: Adding a New React Page
-Read `frontend/src/features/analytics/channel/ChannelAnalytics.jsx` as a reference implementation before starting.
+Read `frontend/src/features/analytics/channel/ChannelAnalytics.tsx` as a reference implementation before starting.
## Files to Create or Modify
| Action | File |
|---|---|
-| Create | `frontend/src/features/myFeature/MyPage.jsx` |
-| Modify | `frontend/src/App.jsx` (add lazy import + route) |
-| Modify | `frontend/src/layout/navigation.js` (add a nav item if the page belongs in the sidebar) |
-| Modify | `frontend/src/services/api.js` (add API methods) |
+| Modify | `shared/types/*.ts` (response type for any new endpoint, see `NEW_API_ENDPOINT.md`) |
+| Create | `frontend/src/features/myFeature/MyPage.tsx` |
+| Modify | `frontend/src/App.tsx` (add lazy import + route) |
+| Modify | `frontend/src/layout/navigation.ts` (add a nav item if the page belongs in the sidebar) |
+| Modify | `frontend/src/services/api.ts` (add API methods) |
| Update | `docs/architecture/frontend/REACT_ARCHITECTURE.md` |
## Step 1: Create the Page Component
-```jsx
-// frontend/src/features/myFeature/MyPage.jsx
+```tsx
+// frontend/src/features/myFeature/MyPage.tsx
import { useState, useEffect, useCallback } from 'react';
import { useParams } from 'react-router-dom';
+import { UserX } from 'lucide-react';
+import PageHeader from '@/components/PageHeader';
+import SurfaceBox from '@/components/SurfaceBox';
+import { EmptyState, PageSkeleton } from '@/components/StateViews';
import { useAppContext } from '../../context/AppContext';
import { api } from '../../services/api';
-import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
-import { Skeleton } from '@/components/ui/skeleton';
+import type { MyData } from '@shared/types/domain.ts';
export default function MyPage() {
- const { id } = useParams(); // if the page has a dynamic segment
+ const { id } = useParams<{ id: string }>(); // if the page has a dynamic segment
const { accounts, showToast } = useAppContext();
- const [data, setData] = useState(null);
+ const [data, setData] = useState<MyData | null>(null);
const [loading, setLoading] = useState(true);
const account = accounts.find(a => a.id === id); // find from global accounts
const loadData = useCallback(async () => {
- if (!account) return;
+ if (!account || !id) return;
try {
- const result = await api.getMyData(id);
+ const result = await api.getMyData(id); // typed by api.ts, no cast needed
setData(result);
} catch (err) {
- showToast(err.message, 'error');
+ showToast((err as Error).message, 'error');
} finally {
setLoading(false);
}
@@ -68,10 +72,10 @@ export default function MyPage() {
}
```
-## Step 2: Add the Route in App.jsx
+## Step 2: Add the Route in App.tsx
-```jsx
-// frontend/src/App.jsx
+```tsx
+// frontend/src/App.tsx
const MyPage = lazy(() => import('./features/myFeature/MyPage'));
// In the router definition, inside the children array:
@@ -80,24 +84,31 @@ const MyPage = lazy(() => import('./features/myFeature/MyPage'));
## Step 3: Add Navigation
-If the page belongs in the sidebar, add it to `NAV_GROUPS` in `frontend/src/layout/navigation.js`. The sidebar, top bar title and command palette pick it up automatically:
+If the page belongs in the sidebar, add it to `NAV_GROUPS` in `frontend/src/layout/navigation.ts`. The sidebar, top bar title and command palette pick it up automatically:
-```js
+```ts
{ path: '/my-page', label: 'My page', icon: IconName },
```
+`icon` is a `LucideIcon` (the component, not an element); the item is checked against the `NavItem` interface in the same file.
+
Detail pages that are not in the sidebar get a top bar title in `DETAIL_ROUTES` in the same file.
## Step 4: Add API Methods
-```js
-// frontend/src/services/api.js
-getMyData: (id) => request(`/accounts/${id}/my-data`),
+```ts
+// frontend/src/services/api.ts
+getMyData: (id: string) => request<MyData>(`/accounts/${id}/my-data`),
```
+## Step 5: Type-check
+
+Run `npm run typecheck` from the repository root and fix every error. Vite strips types without checking them, so a page that builds can still have type errors.
+
## Conventions
- Use `useAppContext()` - don't re-fetch the accounts list, use what's in context
+- Use the response types `api.ts` returns; do not restate them in the page. Sub-components get a `<Component>Props` interface
- Always handle loading and error states
- Use `PageSkeleton` or `Skeleton` for loading states, `EmptyState` for no data, and a toast for failures
- Use semantic HTML for the page structure
@@ -109,7 +120,7 @@ getMyData: (id) => request(`/accounts/${id}/my-data`),
For pages that show aggregate data across all accounts (like Overview):
-```jsx
+```tsx
export default function MyAggregatePage() {
const { accounts, loading: accountsLoading } = useAppContext();
// accounts is already loaded - no need to fetch
diff --git a/docs/features/NEW_SCHEDULED_TASK.md b/docs/features/NEW_SCHEDULED_TASK.md
index 3c0bad8..a60f715 100644
--- a/docs/features/NEW_SCHEDULED_TASK.md
+++ b/docs/features/NEW_SCHEDULED_TASK.md
@@ -9,68 +9,74 @@ A scheduled task runs on a recurring schedule without user interaction. Options
| **Cloudflare Worker cron** | Low latency, needs access to Supabase/Redis, runs every 15 min minimum |
| **GitHub Actions workflow** | Needs Node.js APIs (file system, npm packages), long-running, can run on custom schedule |
+Both are TypeScript: the Worker handler is bundled by Wrangler, and a workflow script is a `.ts` file that Node 24 runs directly by stripping the types.
+
For most tasks: use the Cloudflare Worker cron first. It's simpler and doesn't require managing GitHub secrets.
## Option A: Add a New Worker Cron Handler
### Step 1: Write the handler function
-Add a new export in `backend/cron.js` (or a new file in `backend/cron/`):
+There is no separate cron module. Cron work lives in the service or utils file it belongs to (`processScheduledPosts` in `backend/utils/scheduler.ts`, `autoRefreshInstagramTokens` in `backend/services/instagram.ts`) and takes the service-role Supabase client that `scheduled()` creates. Database access goes through `lib/db.ts`, called with `userId = null` because a cron job scans every user.
+
+```ts
+// backend/services/myPlatform.ts
+import type { SupabaseClient } from '@supabase/supabase-js';
+import { getAccounts, updateAccount } from '../lib/db.ts';
-```js
-// backend/cron.js
-export async function autoRefreshRedditTokens(env) {
- const supabase = createClient(env.SUPABASE_URL, env.SUPABASE_SERVICE_KEY);
- const { data: accounts, error } = await supabase
- .from('accounts')
- .select('id, user_id, data')
- .eq('platform', 'reddit');
- if (error) { console.error('cron/reddit-refresh:', error.message); return; }
+export async function autoRefreshMyPlatformTokens(supabase: SupabaseClient): Promise<void> {
+ const accounts = (await getAccounts(supabase)).filter(a => a.platform === 'myPlatform');
for (const account of accounts) {
+ if (!account.accessToken) continue;
try {
- const refreshed = await refreshRedditCookies(account.data.cookies);
- await supabase.from('accounts').update({ data: { ...account.data, cookies: refreshed } })
- .eq('id', account.id);
+ const accessToken = await refreshMyPlatformToken(account.accessToken);
+ await updateAccount(supabase, account.id, { accessToken });
} catch (err) {
- console.error(`cron/reddit-refresh account ${account.id}:`, err.message);
+ console.error(`cron/my-platform-refresh account ${account.id}:`, (err as Error).message);
}
}
}
```
+A cron job must never throw for one bad account: catch per account and log, as above. Comparing `a.platform` with `'myPlatform'` only type-checks once the platform is in the `Platform` union in `shared/types/domain.ts` (see `NEW_INTEGRATION.md`).
+
### Step 2: Register the Trigger in `wrangler.toml`
```toml
[triggers]
crons = [
"*/15 * * * *", # existing: processScheduledPosts
- "0 2 * * *", # existing: autoRefreshInstagramTokens
- "30 3 * * *" # new: autoRefreshRedditTokens (runs at 3:30 AM UTC daily)
+ "0 0 * * *", # existing: autoRefreshInstagramTokens, autoRefreshRedditSessions
+ "30 3 * * *" # new: autoRefreshMyPlatformTokens (runs at 3:30 AM UTC daily)
]
```
-**Important:** Cloudflare routes cron triggers to the `scheduled()` handler in `worker.js` by trigger index. When you add a new cron string, you must also handle it in the worker's `scheduled()` function.
+**Important:** every cron trigger calls the same `scheduled()` handler exported from `backend/server.ts`. When you add a new cron string, you must also handle it there.
-### Step 3: Dispatch in `worker.js`
+### Step 3: Dispatch in `server.ts`
-```js
-// backend/worker.js
+```ts
+// backend/server.ts
export default {
- // ... fetch handler
- async scheduled(event, env, ctx) {
+ fetch: app.fetch,
+
+ async scheduled(event: ScheduledController, env: Env, ctx: ExecutionContext) {
+ const supabase = getSupabase(env);
+
if (event.cron === '*/15 * * * *') {
- ctx.waitUntil(processScheduledPosts(env));
- } else if (event.cron === '0 2 * * *') {
- ctx.waitUntil(autoRefreshInstagramTokens(env));
+ ctx.waitUntil(processScheduledPosts(supabase));
+ } else if (event.cron === '0 0 * * *') {
+ ctx.waitUntil(autoRefreshInstagramTokens(supabase));
+ ctx.waitUntil(autoRefreshRedditSessions());
} else if (event.cron === '30 3 * * *') {
- ctx.waitUntil(autoRefreshRedditTokens(env));
+ ctx.waitUntil(autoRefreshMyPlatformTokens(supabase));
}
},
-};
+} satisfies ExportedHandler<Env>;
```
-Or match by the cron expression string - the `event.cron` property contains the exact cron string from `wrangler.toml`.
+`event.cron` is the exact cron string from `wrangler.toml`, so the strings must match character for character. Run `npm run typecheck` before deploying.
### Step 4: Test Locally
@@ -99,10 +105,10 @@ Use this when:
### Step 1: Write the script
-Create `scripts/my-task.js`:
+Create `scripts/my-task.ts`. `scripts/tsconfig.json` includes every `scripts/*.ts` file, so `npm run typecheck` checks it with the Node types. Use only erasable TypeScript (no `enum`, no parameter properties) and `import type` for types, because Node runs the file by stripping the types; import shared types by relative path with the extension (`../shared/types/domain.ts`).
-```js
-// scripts/my-task.js
+```ts
+// scripts/my-task.ts
import { createClient } from '@supabase/supabase-js';
const SUPABASE_URL = (process.env.SUPABASE_URL || '').replace(/[^\x20-\x7E]/g, '').trim();
@@ -148,10 +154,10 @@ jobs:
env:
SUPABASE_URL: ${{ secrets.SUPABASE_URL }}
SUPABASE_SERVICE_KEY: ${{ secrets.SUPABASE_SERVICE_KEY }}
- run: node scripts/my-task.js
+ run: node scripts/my-task.ts
```
-Install from the root lockfile with `npm ci`, as the deploy workflows do. Do not run `npm install <pkg>` in the workflow: at the root it would add the package to the root `package.json`, and there is no lockfile inside `backend/` or `frontend/` to install from. If the script needs a package that is not in the lockfile yet, add it to the workspace that owns it (with approval) and commit the root lockfile. `scripts/publish-scheduled.js` is the exception by design: it has no dependencies, so its workflow skips the install.
+Install from the root lockfile with `npm ci`, as the deploy workflows do. Do not run `npm install <pkg>` in the workflow: at the root it would add the package to the root `package.json`, and there is no lockfile inside `backend/` or `frontend/` to install from. If the script needs a package that is not in the lockfile yet, add it to the workspace that owns it (with approval) and commit the root lockfile. `scripts/publish-scheduled.ts` is the exception by design: it has no dependencies, so its workflow skips the install.
### Step 3: Add Required Secrets
@@ -169,7 +175,7 @@ GitHub -> Actions -> "My Scheduled Task" -> "Run workflow" -> watch the logs.
## Documentation After Adding
-- Update `docs/architecture/cloudflare/CRON.md` with the new trigger
+- Update `docs/architecture/backend/CRON.md` and `docs/architecture/cloudflare/WORKERS.md` with the new trigger
- Update `docs/architecture/cloudflare/CI_CD.md` if a new GitHub Actions workflow was added
- Update `CHANGELOG.md` under Unreleased
- If the task adds new secrets, update `docs/architecture/cloudflare/WORKERS.md` (env bindings table)
diff --git a/docs/guidelines/API_CONVENTIONS.md b/docs/guidelines/API_CONVENTIONS.md
index 25c5c98..857e0e8 100644
--- a/docs/guidelines/API_CONVENTIONS.md
+++ b/docs/guidelines/API_CONVENTIONS.md
@@ -4,6 +4,8 @@
### Success responses
+Every response body has a TypeScript type in `shared/types/` (`domain.ts`, `youtube.ts`, `instagram.ts`, `reddit.ts`). The route checks the object it returns with `satisfies`, and the matching `api.ts` method returns the same type, so a change to a response shape is caught by `npm run typecheck` on both sides.
+
Most endpoints return the data directly as a JSON object or array:
```json
@@ -21,15 +23,15 @@ Most endpoints return the data directly as a JSON object or array:
### Error responses
-All errors return a JSON object with an `error` key:
+Errors return a JSON object with an `error` key, or, in routes whose success body has `success: true`, `success: false` with a `message` (the `ApiFailure` type in `shared/types/domain.ts`):
```json
{ "error": "Account not found" }
{ "error": "Missing required field: scheduledAt" }
-{ "error": "Instagram API: (#10) Application does not have permission" }
+{ "success": false, "message": "Account not found" }
```
-The `request()` function in `frontend/src/services/api.js` reads `data.error` and throws it as the error message.
+The `request()` function in `frontend/src/services/api.ts` throws an `Error` with `data.message` or `data.error` when the status is not 2xx. Methods whose route can send `success: false` with a 2xx status return `ApiResult<T>`, so the caller checks `success` before reading the data. Keep one shape per route.
## Status Codes
@@ -48,13 +50,13 @@ The `request()` function in `frontend/src/services/api.js` reads `data.error` an
POST and PUT handlers read the request body via:
-```js
-const body = await c.req.json();
+```ts
+const body = await c.req.json() as ScheduledPostRequest;
```
-Always validate required fields and return 400 for missing ones:
+`c.req.json()` is untyped, so cast it once to the shared request type where it enters. The cast does not check anything at runtime: always validate required fields and return 400 for missing ones:
-```js
+```ts
const { scheduledAt, accountId, mediaUrl } = body;
if (!scheduledAt || !accountId || !mediaUrl) {
return c.json({ error: 'Missing required fields: scheduledAt, accountId, mediaUrl' }, 400);
@@ -65,16 +67,16 @@ if (!scheduledAt || !accountId || !mediaUrl) {
Access route params via `c.req.param('name')`:
-```js
+```ts
router.delete('/accounts/:id', async (c) => {
const id = c.req.param('id');
// ...
});
```
-Access query params via `c.req.query('name')`:
+Access query params via `c.req.query('name')`, which returns `string | undefined`:
-```js
+```ts
router.get('/ig-container/:id/status', async (c) => {
const containerId = c.req.param('id');
const accountId = c.req.query('accountId');
@@ -96,18 +98,18 @@ The backend extracts and verifies it in `requireAuth`. Route handlers access the
- Actions on resources: verb-noun - `/accounts/refresh-all`, `/accounts/:id/refresh`
- Non-resource actions: verb noun - `/resolve-channel`, `/process-scheduled`
-## Frontend `api.js` Conventions
+## Frontend `api.ts` Conventions
-Each method in the `api` object corresponds to one backend endpoint:
+Each method in the `api` object corresponds to one backend endpoint, types its parameters, and passes the shared response type to `request<T>()`:
-```js
+```ts
// Pattern: {verb}{Noun}(params) where params match what the endpoint needs
-getAccounts: () => request('/accounts'),
-addAccount: (input) => request('/accounts', { method: 'POST', body: JSON.stringify({ input }) }),
-deleteAccount: (id) => request(`/accounts/${id}`, { method: 'DELETE' }),
-refreshAccount: (id) => request(`/accounts/${id}/refresh`, { method: 'POST' }),
-getAnalytics: (id) => request(`/accounts/${id}/analytics`),
-createScheduledPost: (data) => request('/scheduled-posts', { method: 'POST', body: JSON.stringify(data) }),
+getAccounts: () => request<AccountListResponse>('/accounts'),
+addAccount: (input: string) => request<YouTubeAccountAddResponse>('/accounts', { method: 'POST', body: JSON.stringify({ input }) }),
+deleteAccount: (id: string) => request<SuccessResponse>(`/accounts/${id}`, { method: 'DELETE' }),
+refreshAccount: (id: string) => request<AccountResponse>(`/accounts/${id}/refresh`, { method: 'POST' }),
+getAnalytics: (id: string) => request<YouTubeAnalyticsPayload>(`/accounts/${id}/analytics`),
+createScheduledPost: (data: ScheduledPostRequest) => request<ApiResult<ScheduledPostResponse>>('/scheduled-posts', { method: 'POST', body: JSON.stringify(data) }),
```
Name frontend methods to describe what they do from the user's perspective, not the HTTP method: `addAccount` not `postAccount`, `deleteAccount` not `removeAccount`.
diff --git a/docs/guidelines/CLOUDFLARE_WORKERS.md b/docs/guidelines/CLOUDFLARE_WORKERS.md
index ce2b644..5b2f663 100644
--- a/docs/guidelines/CLOUDFLARE_WORKERS.md
+++ b/docs/guidelines/CLOUDFLARE_WORKERS.md
@@ -4,19 +4,24 @@
Access environment variables and secrets via `c.env` (in Hono handlers) or `env` (in the `scheduled` cron handler). Never use `process.env` - it does not exist in the Workers runtime.
-```js
-// In a Hono handler or middleware:
-const apiKey = c.env.YOUTUBE_API_KEY;
-const url = c.env.SUPABASE_URL;
+Every binding is declared in the `Env` interface in `backend/types/env.ts`. Add a new secret there (optional ones as `?: string`) before reading it, or the type checker rejects `c.env.MY_SECRET`.
-// In the cron handler:
+```ts
+// In a Hono handler or middleware (the router is new Hono<AppEnv>()):
+const apiKey = c.env.YOUTUBE_API_KEY; // string | undefined
+const url = c.env.SUPABASE_URL; // string
+
+// In the cron handler (backend/server.ts):
export default {
- async scheduled(event, env, ctx) {
+ fetch: app.fetch,
+ async scheduled(event: ScheduledController, env: Env, ctx: ExecutionContext) {
const supabase = getSupabase(env);
- }
-};
+ },
+} satisfies ExportedHandler<Env>;
```
+`ScheduledController`, `ExecutionContext` and `ExportedHandler` are globals from `@cloudflare/workers-types`, which `backend/tsconfig.json` loads instead of the DOM and Node types.
+
## No Node.js APIs
The Workers runtime does not have Node.js built-ins. These are unavailable:
@@ -27,6 +32,8 @@ The Workers runtime does not have Node.js built-ins. These are unavailable:
- `crypto` module - use Web Crypto API (`crypto.subtle`)
- `require()` - use ESM `import`
+`backend/tsconfig.json` does not load the Node types, so `npm run typecheck` reports Node globals in Worker source as errors. Tests in `backend/tests/` run under Node and get the Node types from `backend/tests/tsconfig.json`.
+
**Web APIs available in Workers:**
- `fetch()` - for HTTP calls
- `crypto.subtle` - for HMAC, hashing
@@ -39,9 +46,9 @@ The Workers runtime does not have Node.js built-ins. These are unavailable:
In cron handlers, use `ctx.waitUntil()` to keep the Worker alive for async background work:
-```js
-async scheduled(event, env, ctx) {
- ctx.waitUntil(myAsyncJob(env));
+```ts
+async scheduled(event: ScheduledController, env: Env, ctx: ExecutionContext) {
+ ctx.waitUntil(myAsyncJob(getSupabase(env)));
}
```
@@ -53,17 +60,17 @@ Do not use `ctx.waitUntil()` in HTTP request handlers - just `await` the work no
The Workers runtime does not guarantee a persistent process between requests. Do not rely on module-level variables to persist state:
-```js
+```ts
// BAD - will not work reliably
-let cachedData = null;
-export default { fetch: async (request, env) => {
+let cachedData: MyData | null = null;
+export default { fetch: async (request: Request, env: Env) => {
if (cachedData) return Response.json(cachedData); // unreliable
cachedData = await fetchData(env);
return Response.json(cachedData);
}};
// GOOD - use Redis or Supabase for persistence
-const cached = await redis.get('my-key');
+const cached = await redis.get<MyData>('my-key');
if (cached) return c.json(cached);
const fresh = await fetchData(env);
await redis.set('my-key', fresh);
@@ -72,7 +79,7 @@ return c.json(fresh);
## Bundle Size
-The Worker is bundled as a single ESM file by Wrangler. Large dependencies increase cold-start time and may exceed Workers bundle size limits. The current backend has minimal dependencies:
+Wrangler bundles `backend/server.ts` and everything it imports into a single ESM file, stripping the types without checking them. Type-only imports (`import type`, including everything from `shared/types`) add nothing to the bundle. Large dependencies increase cold-start time and may exceed Workers bundle size limits. The current backend has minimal dependencies:
- `hono` - ~15KB gzipped
- `@supabase/supabase-js` - larger; mostly used for auth.getUser()
@@ -84,8 +91,8 @@ Avoid adding large dependencies. If a library is only needed for one small utili
Use the native Web Crypto API for cryptographic operations:
-```js
-async function hmacSign(secret, message) {
+```ts
+async function hmacSign(secret: string, message: string): Promise<string> {
const key = await crypto.subtle.importKey(
'raw',
new TextEncoder().encode(secret),
@@ -99,7 +106,7 @@ async function hmacSign(secret, message) {
}
```
-This pattern is used in `backend/lib/oauthState.js` for OAuth state tokens.
+This pattern is used in `backend/lib/oauthState.ts` for OAuth state tokens.
## Local Development
@@ -121,17 +128,20 @@ npx wrangler deploy
`npx wrangler` runs the Wrangler version pinned in the root `package-lock.json`.
-Or push to `main` with changes in `backend/` - GitHub Actions deploys automatically via `deploy-backend.yml`.
+Run `npm run typecheck` from the root first, because Wrangler does not check types.
+
+Or push to `main` with changes in `backend/`, `shared/`, `tsconfig.base.json` or the root package files - `deploy-backend.yml` type-checks and tests the backend, then deploys it.
## CORS
-The current CORS configuration (`cors()` with no options) allows all origins. For a more restrictive policy, pass the `FRONTEND_URL` as the allowed origin:
+The current CORS configuration in `server.ts`, `cors({ exposeHeaders: RATE_LIMIT_HEADERS })`, allows all origins and lets the browser read the rate limit headers. For a more restrictive policy, return the `FRONTEND_URL` as the allowed origin. `c.env` only exists inside a request, so pass a function:
-```js
+```ts
app.use('*', cors({
- origin: c.env.FRONTEND_URL,
+ origin: (origin, c) => c.env.FRONTEND_URL ?? origin,
allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowHeaders: ['Content-Type', 'Authorization'],
+ exposeHeaders: RATE_LIMIT_HEADERS,
}));
```
diff --git a/docs/guidelines/ERROR_HANDLING.md b/docs/guidelines/ERROR_HANDLING.md
index b16f75a..6b7b504 100644
--- a/docs/guidelines/ERROR_HANDLING.md
+++ b/docs/guidelines/ERROR_HANDLING.md
@@ -6,47 +6,49 @@
Throw descriptive errors immediately when the external API returns an error object. Let the caller decide what to do:
-```js
-const data = await res.json();
+```ts
+const data = await res.json() as YouTubeApiErrorBody;
if (data.error) throw new Error(data.error.message);
```
+Cast the parsed JSON once to an interface that covers the fields the service reads (see `docs/guidelines/TYPESCRIPT.md`).
+
For HTTP-level errors (non-200 but no error body):
-```js
+```ts
if (!res.ok) throw new Error(`YouTube API ${res.status}: ${await res.text()}`);
```
-### Database Calls (lib/db.js)
+### Database Calls (lib/db.ts)
Check the Supabase `error` field and throw:
-```js
+```ts
const { data, error } = await supabase.from('accounts').select('*').eq('user_id', userId);
if (error) throw error;
```
Supabase errors are objects with `message`, `code`, and `details`. Throwing the error object directly passes the message through cleanly.
-### Cache Operations (lib/cache.js)
+### Cache Operations (lib/cache.ts)
Always catch and fall back silently - cache failures must never surface to users. Every `catch` returns an explicit fallback with a one-line reason, so no catch block is empty:
-```js
+```ts
try {
- return await redis.get(key);
+ return await redis.get<T>(key);
} catch {
// a cache miss falls back to the live api
return null;
}
```
-`cache.js` keeps this in three private helpers (`readKey`, `writeKey`, `deleteKey`) that every exported function uses. Do not log cache errors - they create noise for transient Redis connection issues.
+`cache.ts` keeps this in three private helpers (`readKey`, `writeKey`, `deleteKey`) that every exported function uses. Do not log cache errors - they create noise for transient Redis connection issues.
### Route Handlers (routes/)
Wrap the main logic in try/catch, log the error, and return a JSON error response:
-```js
+```ts
router.get('/accounts/:id/analytics', async (c) => {
const id = c.req.param('id');
const userId = c.get('userId');
@@ -57,12 +59,14 @@ router.get('/accounts/:id/analytics', async (c) => {
const analytics = await getAnalytics(account, c.env);
return c.json(analytics);
} catch (err) {
- console.error(`GET /accounts/${id}/analytics:`, err.message);
- return c.json({ error: err.message }, 500);
+ console.error(`GET /accounts/${id}/analytics:`, (err as Error).message);
+ return c.json({ error: (err as Error).message }, 500);
}
});
```
+Caught errors are `unknown` in strict TypeScript, so read the message with `(err as Error).message`.
+
**Status codes:**
- `400` - bad request (missing required fields, invalid input)
- `401` - unauthorized (handled by `requireAuth`, not route handlers)
@@ -74,7 +78,7 @@ router.get('/accounts/:id/analytics', async (c) => {
Catch in the component or handler, show a toast, and handle loading state:
-```jsx
+```tsx
const [loading, setLoading] = useState(false);
const { showToast } = useAppContext();
@@ -82,22 +86,22 @@ async function handleSubmit() {
setLoading(true);
try {
await api.doSomething(data);
- showToast('Saved successfully!');
+ showToast('Settings saved');
} catch (err) {
- showToast(err.message, 'error');
+ showToast((err as Error).message, 'error');
} finally {
setLoading(false);
}
}
```
-The `api.js` `request()` function already extracts the error message from `{ error: '...' }` backend responses, so `err.message` will be the backend's error string.
+The `api.ts` `request()` function throws an `Error` built from the response's `message` or `error` field when the status is not 2xx, so `(err as Error).message` is the backend's error string. A body with `success: false` sent with a 2xx status is returned, not thrown; methods typed `ApiResult<T>` make the caller check `success`. See `docs/architecture/frontend/API_LAYER.md`.
-### Global Error Handler (server.js)
+### Global Error Handler (server.ts)
The Hono global error handler catches any uncaught errors that bubble up past route handlers:
-```js
+```ts
app.onError((err, c) => {
console.error('Worker error:', err.message);
return c.json({ error: 'Internal server error' }, 500);
@@ -110,7 +114,7 @@ This is the last resort. Route handlers should not rely on it.
Use `console.error()` for errors in route handlers - Cloudflare Workers captures these in the dashboard logs.
-Format: `console.error('METHOD /path:', err.message)` - includes the route for easy filtering.
+Format: `console.error('METHOD /path:', (err as Error).message)` - includes the route for easy filtering.
Do not log sensitive values: access tokens, API keys, user emails, Supabase URLs.
diff --git a/docs/guidelines/HONO.md b/docs/guidelines/HONO.md
index 67ad965..463e4ae 100644
--- a/docs/guidelines/HONO.md
+++ b/docs/guidelines/HONO.md
@@ -2,9 +2,9 @@
## Route Handler Structure
-Every route handler follows this exact shape:
+Every router is `new Hono<AppEnv>()`, so `c.get()`, `c.set()` and `c.env` are typed from `backend/types/app.ts` and `backend/types/env.ts`. Every route handler follows this exact shape:
-```js
+```ts
router.METHOD('/path', async (c) => {
const userId = c.get('userId'); // from requireAuth middleware
const supabase = c.get('supabase'); // from client injection middleware
@@ -12,7 +12,7 @@ router.METHOD('/path', async (c) => {
// 1. Read inputs
const id = c.req.param('id');
- const body = await c.req.json(); // POST/PUT only
+ const body = await c.req.json() as MyThingRequest; // POST/PUT only
// 2. Validate inputs early
if (!body.name) return c.json({ error: 'Missing required field: name' }, 400);
@@ -20,53 +20,56 @@ router.METHOD('/path', async (c) => {
// 3. Execute business logic (in try/catch)
try {
const result = await doSomething(supabase, userId, id);
- return c.json(result);
+ return c.json(result satisfies MyThingResponse);
} catch (err) {
- console.error('METHOD /path:', err.message);
- return c.json({ error: err.message }, 500);
+ console.error('METHOD /path:', (err as Error).message);
+ return c.json({ error: (err as Error).message }, 500);
}
});
```
+Request and response types (`MyThingRequest`, `MyThingResponse`) live in `shared/types/` so the frontend reads the same shape. A handler extracted from the router (like `callbackHandler` in `routes/instagramAuth.ts`) takes `c: AppContext`.
+
## Context Values
-Access these via `c.get()` - never reconstruct them inside handlers:
+Access these via `c.get()` - never reconstruct them inside handlers. They are declared in `AppVariables` in `backend/types/app.ts`; add a key there before setting a new one.
| Key | Type | Notes |
|---|---|---|
-| `userId` | string (UUID) | Set by `requireAuth`. Always present on protected routes |
-| `userEmail` | string | Set by `requireAuth`. May be undefined on older JWTs |
-| `supabase` | SupabaseClient | Set by client injection middleware |
-| `redis` | Redis \| null | Set by client injection middleware. Null if not configured |
+| `userId` | `string` (UUID) | Set by `requireAuth`. Always present on protected routes |
+| `userEmail` | `string \| undefined` | Set by `requireAuth`. May be undefined on older JWTs |
+| `supabase` | `SupabaseClient` | Set by client injection middleware |
+| `redis` | `Redis \| null` | Set by client injection middleware. Null if not configured |
+| `rateLimitRedis` | `Redis \| null` | Set by client injection middleware for the rate limiter only. See `docs/architecture/backend/RATE_LIMITING.md` |
## Reading Request Data
-```js
+```ts
// URL params (/accounts/:id)
const id = c.req.param('id');
-// Query string (?limit=10)
+// Query string (?limit=10), string | undefined
const limit = c.req.query('limit');
-// JSON body (POST/PUT)
-const body = await c.req.json();
+// JSON body (POST/PUT): cast once to the shared request type
+const body = await c.req.json() as ScheduledPostRequest;
// Headers
const auth = c.req.header('Authorization');
```
-Never destructure `c.req` directly - always call the method.
+Never destructure `c.req` directly - always call the method. `c.req.json()` returns untyped JSON, so cast it once where it enters and validate the fields the handler needs before using them.
## Returning Responses
-```js
-// JSON success
-return c.json(data); // 200
+```ts
+// JSON success, checked against the shared response type
+return c.json({ success: true, posts } satisfies ScheduledPostListResponse); // 200
return c.json(data, 201); // 201 Created
// JSON error
return c.json({ error: 'message' }, 400); // client error
-return c.json({ error: err.message }, 500); // server error
+return c.json({ error: (err as Error).message }, 500); // server error
// Early return (validation fail)
if (!id) return c.json({ error: 'Missing id' }, 400);
@@ -76,11 +79,12 @@ Always return `c.json()`. Never use `return new Response()` inside app route han
## Router Organization
-```js
-// backend/routes/myFeature.js
+```ts
+// backend/routes/myFeature.ts
import { Hono } from 'hono';
+import type { AppEnv } from '../types/app.ts';
-const router = new Hono();
+const router = new Hono<AppEnv>();
router.get('/my-resources', async (c) => { ... });
router.post('/my-resources', async (c) => { ... });
@@ -89,32 +93,35 @@ router.delete('/my-resources/:id', async (c) => { ... });
export default router;
```
-Mount in `server.js`:
+Mount in `server.ts`:
-```js
-import myFeatureRouter from './routes/myFeature.js';
+```ts
+import myFeatureRouter from './routes/myFeature.ts';
api.route('/', myFeatureRouter);
```
## Middleware
-Middleware uses `async (c, next) => { ... await next(); }`. Never skip `next()` unless intentionally short-circuiting:
+Middleware is `async (c: AppContext, next: Next) => { ... await next(); }`. Never skip `next()` unless intentionally short-circuiting:
+
+```ts
+// backend/middleware/auth.ts: short-circuits (returns early without calling next)
+import type { Next } from 'hono';
+import type { AppContext } from '../types/app.ts';
-```js
-// Short-circuit (returns early without calling next)
-app.use('/api/*', async (c, next) => {
+export async function requireAuth(c: AppContext, next: Next) {
const token = c.req.header('Authorization')?.replace('Bearer ', '');
if (!token) return c.json({ error: 'Unauthorized' }, 401);
- // set context, then continue
- c.set('userId', userId);
+ // verify the token, set context, then continue
+ c.set('userId', user.id);
await next();
-});
+}
```
## Error Handling Rules
- Always wrap external calls (Supabase, platform APIs) in try/catch
-- Log with `console.error('VERB /path:', err.message)` - include the route in the log
+- Log with `console.error('VERB /path:', (err as Error).message)` - include the route in the log
- Never throw from a route handler - catch and return `c.json({ error }, status)`
- 400 for client errors (missing fields, invalid format, resource not found)
- 500 for server errors (DB failures, external API failures)
diff --git a/docs/guidelines/NAMING.md b/docs/guidelines/NAMING.md
index 179afcb..af26c22 100644
--- a/docs/guidelines/NAMING.md
+++ b/docs/guidelines/NAMING.md
@@ -4,18 +4,23 @@
| Location | Convention | Examples |
|---|---|---|
-| Backend routes | `camelCase.js` | `accounts.js`, `scheduledPosts.js`, `instagramAuth.js` |
-| Backend services | `camelCase.js` | `instagram.js`, `youtube.js` |
-| Backend lib | `camelCase.js` | `db.js`, `cache.js`, `supabase.js`, `redis.js` |
-| Backend middleware | `camelCase.js` | `auth.js` |
-| Frontend pages | `PascalCase.jsx` | `Login.jsx`, `Overview.jsx` |
-| Frontend feature components | `PascalCase.jsx` | `ChannelAnalytics.jsx`, `AccountManager.jsx` |
-| Frontend contexts | `PascalCaseContext.jsx` | `AuthContext.jsx`, `AppContext.jsx` |
-| Frontend layout | `PascalCase.jsx` or `index.jsx` | `Sidebar.jsx`, `Header.jsx`, `index.jsx` |
-| Frontend hooks | `use-kebab-case.js` | `use-mobile.js` |
-| Frontend utilities | `camelCase.js` | `formatters.js`, `api.js`, `utils.js` |
-| shadcn components | `kebab-case.jsx` | `button.jsx`, `card.jsx` (generated - do not rename) |
-| Documentation | `SCREAMING_SNAKE_CASE.md` | `OVERVIEW.md`, `JAVASCRIPT.md`, `SCHEMA.md` |
+| Backend routes | `camelCase.ts` | `accounts.ts`, `scheduledPosts.ts`, `instagramAuth.ts` |
+| Backend services | `camelCase.ts` | `instagram.ts`, `youtube.ts` |
+| Backend lib | `camelCase.ts` | `db.ts`, `cache.ts`, `supabase.ts`, `redis.ts` |
+| Backend middleware | `camelCase.ts` | `auth.ts`, `rateLimit.ts` |
+| Type-only modules | `camelCase.ts` | `shared/types/domain.ts`, `backend/types/env.ts`, `backend/types/app.ts` |
+| Frontend pages | `PascalCase.tsx` | `Login.tsx`, `Overview.tsx` |
+| Frontend feature components | `PascalCase.tsx` | `ChannelAnalytics.tsx`, `AccountManager.tsx` |
+| Frontend contexts | `PascalCaseContext.tsx` | `AuthContext.tsx`, `AppContext.tsx` |
+| Frontend layout | `PascalCase.tsx` or `index.tsx` | `Sidebar.tsx`, `Header.tsx`, `index.tsx` |
+| Frontend feature hooks | `useCamelCase.ts` in the feature folder | `useBulkQueue.ts`, `useChannelVideos.ts` |
+| Frontend shared hooks | `use-kebab-case.ts` in `src/hooks` | `use-mobile.ts` |
+| Frontend utilities | `camelCase.ts` | `formatters.ts`, `api.ts`, `utils.ts` |
+| shadcn components | `kebab-case.tsx` | `button.tsx`, `card.tsx` (generated - do not rename) |
+| Tests | `<source name>.test.ts` in the workspace `tests/` folder | `backend/tests/services/youtube.test.ts` |
+| Documentation | `SCREAMING_SNAKE_CASE.md` | `OVERVIEW.md`, `TYPESCRIPT.md`, `SCHEMA.md` |
+
+Use `.tsx` only for files that contain JSX; everything else is `.ts`.
## Functions
@@ -26,6 +31,13 @@
- React event handlers: `handle` + PascalCase noun/event - `handleSubmit()`, `handleDeleteClick()`, `handleInputChange()`
- React custom hooks: `use` + PascalCase noun - `useAppContext()`, `useIsMobile()`
+## Types
+
+- Interfaces, type aliases and React components: `PascalCase` - `ScheduledPost`, `ChannelAnalytics`
+- Component props: `<Component>Props` - `ChannelHeaderProps`
+- Request and response bodies: `<Thing>Request`, `<Thing>Response` - `ScheduledPostRequest`, `ScheduledPostListResponse`
+- Raw upstream payloads: platform name + `Api` + entity - `YouTubeApiVideo`
+
## Variables
- `camelCase` throughout - `accountId`, `scheduledAt`, `accessToken`, `uploadPlaylistId`
@@ -45,7 +57,7 @@
- Table names: `snake_case`, plural - `accounts`, `settings`, `scheduled_posts`
- Column names: `snake_case` - `user_id`, `account_id`, `scheduled_at`, `access_token` (inside jsonb)
-- jsonb field names: `camelCase` - these are JavaScript objects embedded in JSON, so they follow JS conventions: `accessToken`, `subscriberCount`, `publishedAt`
+- jsonb field names: `camelCase` - they become fields on TypeScript objects, so they follow the code's naming: `accessToken`, `subscriberCount`, `publishedAt`
## Routes
diff --git a/docs/guidelines/REACT.md b/docs/guidelines/REACT.md
index 6a6f123..f9cf7a5 100644
--- a/docs/guidelines/REACT.md
+++ b/docs/guidelines/REACT.md
@@ -4,7 +4,7 @@
**Function components only.** No class components.
-```jsx
+```tsx
export default function ChannelAnalytics() {
// ...
return <div>...</div>;
@@ -13,34 +13,47 @@ export default function ChannelAnalytics() {
**One component per file.** Small helper sub-components can live in the same file if they are only used in that one file and are not exported.
-**No prop-types.** This project does not use PropTypes or TypeScript types. Descriptive prop names are the documentation.
+**Typed props.** Every component that receives props declares a `<Component>Props` interface in the same file; export it only when another file needs it. Children are `React.ReactNode`, icons are `LucideIcon`. No PropTypes. See `docs/guidelines/TYPESCRIPT.md`.
+
+```tsx
+interface AccountCardProps {
+ account: AppAccount;
+ onRemove: (id: string) => void;
+}
+
+export default function AccountCard({ account, onRemove }: AccountCardProps) {
+ // ...
+}
+```
## Hooks
Use hooks at the top level of the component, never inside conditions or loops:
-```jsx
+```tsx
// Good
-function MyComponent({ id }) {
- const [data, setData] = useState(null);
+function MyComponent({ id }: MyComponentProps) {
+ const [data, setData] = useState<YouTubeAnalyticsPayload | null>(null);
const { showToast } = useAppContext();
// ...
}
-// Bad
-function MyComponent({ id }) {
+// Bad: conditional hook
+function MyComponent({ id }: MyComponentProps) {
if (id) {
- const [data, setData] = useState(null); // ❌ conditional hook
+ const [data, setData] = useState<YouTubeAnalyticsPayload | null>(null);
}
}
```
+Give `useState` a type argument when the initial value does not show the full type (`null`, `[]`), and `useRef` the element type: `useRef<HTMLDivElement>(null)`.
+
**Custom hooks** live where they are used:
-- A hook used by one feature lives in that feature folder as `useCamelCase.js`, for example `features/analytics/videos/useChannelVideos.js` or `features/publishing/useBulkQueue.js`.
-- A hook shared across features lives in `frontend/src/hooks/` as `use-kebab-case.js`, for example `hooks/use-cloudinary-config.js`.
+- A hook used by one feature lives in that feature folder as `useCamelCase.ts`, for example `features/analytics/videos/useChannelVideos.ts` or `features/publishing/useBulkQueue.ts`.
+- A hook shared across features lives in `frontend/src/hooks/` as `use-kebab-case.ts`, for example `hooks/use-cloudinary-config.ts`.
-Either way, export a single function named `useSomething`. Move a feature hook into `hooks/` (and rename it) once a second feature needs it.
+Either way, export a single function named `useSomething`. A hook that returns several values also exports its result type, for example `export type BulkQueue = ReturnType<typeof useBulkQueue>`. Move a feature hook into `hooks/` (and rename it) once a second feature needs it.
## State Management
@@ -56,8 +69,8 @@ See `docs/guidelines/STATE_MANAGEMENT.md` for detailed guidance.
Fetch data in `useEffect` on component mount:
-```jsx
-const [data, setData] = useState(null);
+```tsx
+const [data, setData] = useState<YouTubeAnalyticsPayload | null>(null);
const [loading, setLoading] = useState(true);
const { showToast } = useAppContext();
@@ -68,7 +81,7 @@ useEffect(() => {
const result = await api.getAnalytics(id);
if (!cancelled) setData(result);
} catch (err) {
- if (!cancelled) showToast(err.message, 'error');
+ if (!cancelled) showToast((err as Error).message, 'error');
} finally {
if (!cancelled) setLoading(false);
}
@@ -78,12 +91,12 @@ useEffect(() => {
}, [id, showToast]);
```
-The `cancelled` flag prevents state updates on unmounted components (important for pages that navigate away during loading).
+`api` methods return the shared response types from `shared/types`, so `result` is already typed; do not restate the shape in the page. The `cancelled` flag prevents state updates on unmounted components (important for pages that navigate away during loading).
## JSX Rules
**Conditional rendering:**
-```jsx
+```tsx
// For if/else with significant content:
{loading ? <Skeleton /> : <DataTable data={data} />}
@@ -92,24 +105,24 @@ The `cancelled` flag prevents state updates on unmounted components (important f
```
**Lists always need `key`:**
-```jsx
+```tsx
{accounts.map(account => (
<AccountCard key={account.id} account={account} />
))}
```
**Event handlers** are named `handle{Event}` by convention:
-```jsx
-function handleSubmit(e) { ... }
+```tsx
+function handleSubmit(e: React.FormEvent<HTMLFormElement>) { ... }
function handleDeleteClick() { ... }
-function handleInputChange(e) { ... }
+function handleInputChange(e: React.ChangeEvent<HTMLInputElement>) { ... }
```
## Lazy Loading
-All pages are lazy-loaded via `React.lazy()` in `App.jsx`. Do not import pages directly - always use lazy imports for new pages.
+All pages are lazy-loaded via `React.lazy()` in `App.tsx`. Do not import pages directly - always use lazy imports for new pages.
-```jsx
+```tsx
const MyNewPage = lazy(() => import('./features/myFeature/MyNewPage'));
```
diff --git a/docs/guidelines/SHADCN.md b/docs/guidelines/SHADCN.md
index 96d898e..7361d9a 100644
--- a/docs/guidelines/SHADCN.md
+++ b/docs/guidelines/SHADCN.md
@@ -3,23 +3,23 @@
## Configuration
```json
-// frontend/components.json
+// frontend/components.json (excerpt)
{
"style": "base-nova",
"rsc": false,
- "tsx": false,
- "tailwind": { "cssVariables": true },
- "aliases": { "components": "@/components", "utils": "@/lib/utils" }
+ "tsx": true,
+ "tailwind": { "config": "", "css": "src/index.css", "cssVariables": true },
+ "aliases": { "components": "@/components", "utils": "@/lib/utils", "ui": "@/components/ui" }
}
```
-Style: `base-nova`. CSS variables: enabled. No TypeScript (tsx: false).
+Style: `base-nova`. CSS variables: enabled. TypeScript: `tsx: true`, so the CLI writes `.tsx` files. `tailwind.config` is empty because Tailwind v4 is configured in `src/index.css`.
## Import Pattern
Always import from the local `@/components/ui/` path:
-```jsx
+```tsx
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
@@ -36,13 +36,13 @@ npx shadcn add <component-name>
Run the CLI from `frontend/`, where `components.json` lives. The `shadcn` CLI is a dependency of the frontend workspace, so `npx shadcn` uses the version pinned in the root `package-lock.json`. If the CLI installs npm packages for a component, check afterwards that no `frontend/package-lock.json` was created; the root lockfile is the only one, and a stray workspace lockfile should be deleted and `npm install` run again at the root.
-This copies the component source into `frontend/src/components/ui/`. After adding, verify the generated file uses `.jsx` (not `.tsx`). The `components.json` configuration should handle this automatically.
+This copies the component source into `frontend/src/components/ui/` as a `.tsx` file, following the official base-nova TypeScript sources. Run `npm run typecheck` from the root afterwards.
## Composition Rules
shadcn components are composed using their named export variants. Read the component file in `frontend/src/components/ui/` to understand the available props before using them.
-```jsx
+```tsx
// Card composition
<Card>
<CardHeader>
@@ -80,7 +80,7 @@ shadcn components are composed using their named export variants. Read the compo
Always use `cn()` from `@/lib/utils` to combine class names - it handles conditional classes and tailwind-merge conflicts:
-```jsx
+```tsx
import { cn } from '@/lib/utils';
<div className={cn('base-class', isActive && 'active-class', className)}>
@@ -90,7 +90,7 @@ import { cn } from '@/lib/utils';
Project components in `frontend/src/components/` sit on top of the shadcn primitives. Use them before composing primitives by hand. `MetricBox` is the KPI tile used across analytics pages:
-```jsx
+```tsx
import MetricBox from '@/components/MetricBox';
<MetricBox
diff --git a/docs/guidelines/STATE_MANAGEMENT.md b/docs/guidelines/STATE_MANAGEMENT.md
index 78bf58d..0d206db 100644
--- a/docs/guidelines/STATE_MANAGEMENT.md
+++ b/docs/guidelines/STATE_MANAGEMENT.md
@@ -24,30 +24,34 @@ Default choice. Use it for:
- UI state (open/closed, selected tab, active filter)
- Page-specific fetched data (analytics results, video list)
-```jsx
-const [analytics, setAnalytics] = useState(null);
+```tsx
+const [analytics, setAnalytics] = useState<YouTubeAnalyticsPayload | null>(null);
const [loading, setLoading] = useState(true);
-const [selectedTab, setSelectedTab] = useState('overview');
+const [selectedTab, setSelectedTab] = useState<'overview' | 'videos'>('overview');
```
+Pass a type argument when the initial value does not describe the full type: `null` for data that loads later, `[]` for a list, or a string literal that is one of several allowed values.
+
## AppContext - What Belongs Here
-`AppContext` currently provides:
+`AppContext` currently provides (typed as `AppContextValue` in `context/AppContext.tsx`):
| State | Type | Why global |
|---|---|---|
-| `accounts` | `Account[]` | Needed by Sidebar (nav links), Overview (dashboard), all analytics pages (lookup by ID), AccountManager (CRUD), Header (refresh button) |
+| `accounts` | `AppAccount[]` | Needed by Sidebar (nav links), Overview (dashboard), all analytics pages (lookup by ID), AccountManager (CRUD), Header (refresh button) |
+| `setAccounts` | `Dispatch<SetStateAction<AppAccount[]>>` | Lets account management update the list after an add or delete |
| `loading` | `boolean` | The global refresh spinner in Header |
-| `showToast` | `function` | Toast notifications from anywhere - avoids threading Sonner's `toast` import everywhere |
+| `showToast` | `(message: string, severity?: ToastSeverity) => void` | Toast notifications from anywhere - avoids threading Sonner's `toast` import everywhere |
+| `loadAccounts`, `refreshAll` | `() => Promise<void>` | Reload the account list, or refresh every account's data |
**Do not add** page-specific data to `AppContext`. If only one or two pages need a piece of data, keep it local.
## AuthContext - What Belongs Here
-Only auth state:
-- `session` - the Supabase session object
-- `user` - shorthand for `session.user`
-- `signIn`, `signUp`, `signOut` - auth actions
+Only auth state (typed as `AuthContextValue` in `context/AuthContext.tsx`):
+- `session` - the Supabase session object (`undefined` while the first session check runs, `null` when signed out)
+- `user` - shorthand for `session.user`, or `null`
+- `signIn`, `signUp`, `signInWithGoogle`, `signOut` - auth actions
Feature pages should not need to read `AuthContext`. If a feature page needs the user's email or ID, reconsider - in most cases, the backend handles user scoping via the JWT, so the frontend doesn't need to know the userId.
@@ -55,13 +59,13 @@ Feature pages should not need to read `AuthContext`. If a feature page needs the
Prefer computing derived values at render time rather than storing them in state:
-```jsx
+```tsx
// Good - derive from existing state
const youtubeAccounts = accounts.filter(a => a.platform === 'youtube');
const totalViews = accounts.reduce((sum, a) => sum + (a.viewCount || 0), 0);
// Bad - storing derived data in extra state
-const [youtubeAccounts, setYoutubeAccounts] = useState([]);
+const [youtubeAccounts, setYoutubeAccounts] = useState<AppAccount[]>([]);
useEffect(() => {
setYoutubeAccounts(accounts.filter(a => a.platform === 'youtube'));
}, [accounts]);
@@ -69,7 +73,7 @@ useEffect(() => {
If the derivation is expensive (e.g., sorting 500 videos), use `useMemo`:
-```jsx
+```tsx
const sortedVideos = useMemo(
() => [...videos].sort((a, b) => b.viewCount - a.viewCount),
[videos]
@@ -83,7 +87,7 @@ For filterable/sortable pages (VideoExplorer, ReelsExplorer), consider putting f
## Refs (`useRef`)
Use `useRef` for:
-- Referencing DOM elements (`ref={inputRef}; inputRef.current.focus()`)
+- Referencing DOM elements (`const inputRef = useRef<HTMLInputElement>(null)`, then `inputRef.current?.focus()`)
- Storing mutable values that should not trigger re-renders (e.g., a timer ID, a cancelled flag)
Do not use `useRef` as a workaround for stale closures - fix the closure instead.
diff --git a/docs/guidelines/SUPABASE.md b/docs/guidelines/SUPABASE.md
index a3bfde1..782a8b2 100644
--- a/docs/guidelines/SUPABASE.md
+++ b/docs/guidelines/SUPABASE.md
@@ -4,42 +4,44 @@
| Client | Key used | Created by | Purpose |
|---|---|---|---|
-| Service client | `SUPABASE_SERVICE_KEY` | `getSupabase(env)` in `lib/supabase.js` | All DB operations (bypasses RLS) |
-| Auth client | `SUPABASE_ANON_KEY` | `getSupabaseAuth(env)` in `lib/supabase.js` | JWT verification only (`auth.getUser(token)`) |
-| Frontend client | `VITE_SUPABASE_ANON_KEY` | `lib/supabase.js` in frontend | Supabase Auth (sign in/out, session) - no DB queries |
+| Service client | `SUPABASE_SERVICE_KEY` | `getSupabase(env)` in `lib/supabase.ts` | All DB operations (bypasses RLS) |
+| Auth client | `SUPABASE_ANON_KEY` | `getSupabaseAuth(env)` in `lib/supabase.ts` | JWT verification only (`auth.getUser(token)`) |
+| Frontend client | `VITE_SUPABASE_ANON_KEY` | `lib/supabase.ts` in frontend | Supabase Auth (sign in/out, session) - no DB queries |
**Rule:** The service client is the only client used for database queries. The auth client is used exclusively in `requireAuth` middleware. The frontend client is used only for Supabase Auth, never for database access.
## Query Pattern
-All Supabase queries are in `backend/lib/db.js`. Route handlers never call `supabase.from()` directly.
+All Supabase queries are in `backend/lib/db.ts`. Route handlers never call `supabase.from()` directly.
-```js
-// In lib/db.js:
-export async function getAccounts(supabase, userId = null) {
- let q = supabase.from('accounts').select('id, platform, data');
- if (userId) q = q.eq('user_id', userId);
- const { data, error } = await q;
+```ts
+// In lib/db.ts:
+export async function getAccounts(supabase: SupabaseClient, userId: string | null = null): Promise<Account[]> {
+ let query = supabase.from('accounts').select('id, platform, data');
+ if (userId) query = query.eq('user_id', userId);
+ const { data, error } = await query;
if (error) throw error;
- return (data || []).map(row => ({ id: row.id, platform: row.platform, ...row.data }));
+ return ((data || []) as AccountRow[]).map(row => ({ id: row.id, platform: row.platform, ...row.data }));
}
// In route handler:
-import { getAccounts } from '../lib/db.js';
+import { getAccounts } from '../lib/db.ts';
router.get('/accounts', async (c) => {
const supabase = c.get('supabase');
const userId = c.get('userId');
const accounts = await getAccounts(supabase, userId);
- return c.json(accounts);
+ return c.json(accounts.map(safeAccount) satisfies AccountListResponse);
});
```
+The client is untyped (there is no generated database type), so each `db.ts` function casts the rows once to a local row interface (`AccountRow`, `ScheduledPostRow`) and returns a `shared/types` shape. Every exported `db.ts` function declares its return type.
+
## Error Handling
Always check the `error` field from Supabase responses and throw:
-```js
+```ts
const { data, error } = await supabase.from('accounts').select('*');
if (error) throw error;
```
@@ -50,28 +52,29 @@ Do not silently ignore errors. Route handlers will catch the thrown error and re
Use `onConflict` to specify the conflict resolution key:
-```js
-await supabase
+```ts
+const { error } = await supabase
.from('settings')
- .upsert(
- { user_id: userId, key: 'api_keys', value: keys },
- { onConflict: 'user_id,key' }
- );
+ .upsert({ user_id: userId, key: 'api_keys', value: keys }, { onConflict: 'user_id,key' });
+if (error) throw error;
```
## jsonb Data Column Pattern
The `data` jsonb column stores platform-specific fields for accounts and post metadata for scheduled posts. The pattern for reading and updating:
-```js
+```ts
// Reading: spread data into the returned object
return { id: row.id, platform: row.platform, ...row.data };
// Updating: merge new fields with existing data (don't replace the whole object)
const current = await getAccountById(supabase, id, userId);
+if (!current) throw new Error('Account not found: ' + id);
const { id: _, platform: currentPlatform, ...currentData } = current;
+const { platform: newPlatform, ...dataUpdates } = updates;
await supabase.from('accounts').update({
- data: { ...currentData, ...updates } // merge, not replace
+ platform: newPlatform || currentPlatform,
+ data: { ...currentData, ...dataUpdates }, // merge, not replace
}).eq('id', id);
```
@@ -81,15 +84,16 @@ await supabase.from('accounts').update({
Every user-scoped query must include `.eq('user_id', userId)`. Functions that intentionally omit this (for cron use) should document it with a comment:
-```js
-export async function getDuePosts(supabase) {
- // No userId filter - used by cron scheduler to process all users' posts
+```ts
+// No userId filter - used by cron scheduler to process all users' posts
+export async function getDuePosts(supabase: SupabaseClient): Promise<ScheduledPost[]> {
const { data, error } = await supabase
.from('scheduled_posts')
- .select(...)
+ .select('id, account_id, status, scheduled_at, data')
.eq('status', 'pending')
.lte('scheduled_at', new Date().toISOString());
- ...
+ if (error) throw error;
+ return (data || []).map(rowToPost);
}
```
@@ -97,16 +101,18 @@ export async function getDuePosts(supabase) {
Supabase clients are created fresh per request in the Worker - they are stateless HTTP clients and safe to create on each request. Do not cache client instances in module-level variables; they would hold references to a specific request's `env` bindings.
-```js
-// lib/supabase.js
-export function getSupabase(env) {
- return createClient(env.SUPABASE_URL, env.SUPABASE_SERVICE_KEY);
+```ts
+// lib/supabase.ts
+export function getSupabase(env: Env): SupabaseClient {
+ return createClient(clean(env.SUPABASE_URL), clean(env.SUPABASE_SERVICE_KEY), CLIENT_OPTS);
}
```
+`CLIENT_OPTS` turns off session persistence and passes a `fetch` wrapper that drops the `cache` request option, which Workers reject. Import `SupabaseClient` as a type (`import type { SupabaseClient } from '@supabase/supabase-js'`) when a function takes the client as a parameter.
+
## Frontend - No DB Access
-The frontend's Supabase client (`frontend/src/lib/supabase.js`) is used only for:
+The frontend's Supabase client (`frontend/src/lib/supabase.ts`) is used only for:
- `supabase.auth.signInWithPassword()`
- `supabase.auth.signUp()`
- `supabase.auth.signOut()`
diff --git a/docs/guidelines/TAILWIND.md b/docs/guidelines/TAILWIND.md
index 4d78014..94253e0 100644
--- a/docs/guidelines/TAILWIND.md
+++ b/docs/guidelines/TAILWIND.md
@@ -3,8 +3,8 @@
## Version
This project uses **Tailwind CSS v4**. The v4 API is substantially different from v3:
-- Configuration is done via CSS `@theme` instead of `tailwind.config.js`
-- No `tailwind.config.js` exists - do not create one
+- Configuration is done via CSS `@theme` in `frontend/src/index.css` instead of a Tailwind config file
+- The project has no Tailwind config file (`components.json` sets `tailwind.config` to an empty string) - do not create one
- Use `@import "tailwindcss"` in the main CSS entry point
- Utility classes are the same as v3 in most cases
@@ -28,7 +28,7 @@ The shadcn names (`bg-background`, `text-muted-foreground`, `bg-primary`) still
The app shell already pads and centres the content column. Pages start with a flex column:
-```jsx
+```tsx
<div className="flex flex-col gap-6">
<PageHeader title="Videos" description="..." actions={...} />
{/* sections */}
@@ -37,7 +37,7 @@ The app shell already pads and centres the content column. Pages start with a fl
### Grid layouts
-```jsx
+```tsx
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
{/* stat cards */}
</div>
@@ -45,7 +45,7 @@ The app shell already pads and centres the content column. Pages start with a fl
### Flex rows
-```jsx
+```tsx
<div className="flex items-center gap-2">
{/* icon + label */}
</div>
@@ -65,7 +65,7 @@ Use the spacing scale consistently. Common patterns in this project:
Use `PageHeader` for the page title and `SectionHeader` or a `SurfaceBox` title for sections. When writing type directly:
-```jsx
+```tsx
<h1 className="font-heading text-page-title font-semibold">Page title</h1>
<h2 className="font-heading text-section font-semibold">Section</h2>
<p className="text-small text-ink-muted">Secondary info</p>
@@ -83,7 +83,7 @@ Mobile-first. Most pages in this app are designed primarily for desktop (analyti
## Dark Mode
-Light and dark values are both defined as tokens, so token utilities switch automatically. Do not use `dark:` variants for colour. The one sanctioned use of `dark:` is swapping the logo file in `components/brand/Logo.jsx`.
+Light and dark values are both defined as tokens, so token utilities switch automatically. Do not use `dark:` variants for colour. The one sanctioned use of `dark:` is swapping the logo file in `components/brand/Logo.tsx`.
If you need to add a custom dark-mode variant for non-token colors, add a CSS custom property to the `@theme` block instead.
@@ -91,7 +91,7 @@ If you need to add a custom dark-mode variant for non-token colors, add a CSS cu
Use `cn()` (from `@/lib/utils`) for conditional class merging:
-```jsx
+```tsx
import { cn } from '@/lib/utils';
<div className={cn(
@@ -108,5 +108,5 @@ Never use template literals for conditional classes - they won't be properly mer
- Do not use `style={{}}` for values that can be expressed as Tailwind utilities
- Do not hardcode colors in class names (`text-[#ff0000]`) - use design token utilities
- Do not use `!important` (`!text-red-500`) unless debugging a specificity conflict
-- Do not create a `tailwind.config.js` - configuration lives in the CSS `@theme` block in v4
+- Do not create a Tailwind config file - configuration lives in the CSS `@theme` block in v4
- Do not use `dark:` prefix variants - theme is token-based, not class-based
diff --git a/docs/guidelines/TYPESCRIPT.md b/docs/guidelines/TYPESCRIPT.md
index 7c5d4a0..c483de9 100644
--- a/docs/guidelines/TYPESCRIPT.md
+++ b/docs/guidelines/TYPESCRIPT.md
@@ -1,44 +1,135 @@
-# JavaScript Standards
+# TypeScript Standards
-This project is plain JavaScript - no TypeScript, no Babel transpilation beyond what Vite handles. These rules apply to both the backend (Cloudflare Worker) and the frontend (Vite + React).
+The whole project is TypeScript in `strict` mode: the Worker (`backend/`), the React app (`frontend/`), the shared API types (`shared/types/`), the scheduled publisher (`scripts/`) and every test. These rules apply everywhere.
+
+Nothing compiles TypeScript to JavaScript ahead of time. Wrangler and Vite strip the types while bundling, and Node strips them when it runs the tests and the publisher script. Type checking is a separate step, `npm run typecheck`, which CI runs before every deploy.
+
+## Compiler Settings
+
+Shared settings live in `tsconfig.base.json` at the root; each project extends it.
+
+| File | Checks | Notable settings |
+|---|---|---|
+| `tsconfig.base.json` | (base only) | `strict`, `noEmit`, `moduleResolution: bundler`, `verbatimModuleSyntax`, `erasableSyntaxOnly`, `allowImportingTsExtensions`, `isolatedModules` |
+| `backend/tsconfig.json` | Worker source | `types: ["@cloudflare/workers-types"]`, no DOM, no Node |
+| `backend/tests/tsconfig.json` | Backend tests and the source they import | adds `node` types |
+| `frontend/tsconfig.json` | `frontend/src` | DOM lib, `jsx: react-jsx`, `vite/client` types, `@/*` and `@shared/*` paths |
+| `frontend/tsconfig.node.json` | `vite.config.ts`, `frontend/tests` | `node` types, DOM lib |
+| `scripts/tsconfig.json` | `scripts/` | `node` types |
+
+`npm run typecheck` at the root runs all of them. The project uses TypeScript 6.0: TypeScript 7 (the native compiler) is not yet supported by `typescript-eslint`.
+
+## Syntax That Can Be Stripped
+
+Because Node runs `.ts` files by removing the types, only syntax that can be erased is allowed (`erasableSyntaxOnly` enforces it):
+
+- No `enum`. Use a union of string literals, or an object with `as const`.
+- No `namespace` with runtime code, no parameter properties (`constructor(private x)`), no `import x = require()`.
+- Type-only imports use `import type { X }` or `import { type X }`. `verbatimModuleSyntax` makes this an error otherwise, and without it Node would try to import a value that does not exist.
+- Relative imports name the file with its extension: `import { getAccounts } from '../lib/db.ts'`. The frontend's `@/` imports stay extensionless because Vite resolves them; files imported by Node tests (see `docs/workflows/TESTING.md`) use relative `.ts` imports only.
+
+## Where Types Live
+
+| Kind of type | Location |
+|---|---|
+| Shapes the API sends or receives: accounts, posts, analytics, request bodies, responses | `shared/types/*.ts` (`domain.ts`, `youtube.ts`, `instagram.ts`, `reddit.ts`) |
+| Worker bindings and Hono context | `backend/types/env.ts` (`Env`), `backend/types/app.ts` (`AppEnv`, `AppContext`, `AppVariables`) |
+| Raw payloads from YouTube, Instagram and Reddit | The service module that parses them (`YouTubeApiVideo` in `services/youtubeApi.ts`) |
+| Props, hook results, local state | The component or hook file, exported when another file needs it |
+
+`shared/types` holds types only. It never imports runtime code, so either app can import it with `import type` and nothing from it reaches a bundle. The backend imports it by relative path (`../../shared/types/domain.ts`), the frontend by alias (`@shared/types/domain.ts`), except files that Node tests import, which use the relative path.
+
+When a route's response changes, change its type in `shared/types` first. The type checker then lists every frontend file that reads the old shape.
+
+## Typing Rules
+
+- `any` is a lint error. Use a precise type. At a true boundary (JSON from `fetch`, `c.req.json()`, a test fake), use `unknown` or cast once to a named interface right where the value enters: `const body = await c.req.json() as AddAccountBody`.
+- Describe external API payloads with an interface covering the fields the code reads, not the whole upstream schema.
+- Exported functions declare their return type. Local helpers may rely on inference.
+- `interface` for object shapes, `type` for unions, aliases and mapped types.
+- Prefer narrowing (`if (!account) return ...`) over non-null assertions. Use `!` only where an earlier check guarantees the value, and never to hide a missing check.
+- Caught errors are `unknown`: read the message with `(err as Error).message`.
+- Response objects built in a route are checked with `satisfies`: `return c.json({ success: true, posts } satisfies ScheduledPostListResponse)`.
+- No `// @ts-ignore` or `// @ts-expect-error`. Fix the type, or cast narrowly with a one-line comment that says why.
+
+### Backend patterns
+
+```ts
+import { Hono } from 'hono';
+import type { AppEnv, AppContext } from '../types/app.ts';
+
+const app = new Hono<AppEnv>();
+
+app.get('/accounts', async (c) => {
+ const accounts = await getAccounts(c.get('supabase'), c.get('userId'));
+ return c.json(accounts.map(safeAccount) satisfies AccountListResponse);
+});
+
+// handlers extracted from the router take the typed context
+export async function callbackHandler(c: AppContext) { /* ... */ }
+```
+
+### Frontend patterns
+
+```tsx
+interface ChannelHeaderProps {
+ account: AppAccount;
+ onRefresh: () => void;
+}
+
+export default function ChannelHeader({ account, onRefresh }: ChannelHeaderProps) {
+ const [analytics, setAnalytics] = useState<VideoAnalytics | null>(null);
+ const panelRef = useRef<HTMLDivElement>(null);
+ // ...
+}
+```
+
+- Every component that receives props has a `<Component>Props` interface; children are `React.ReactNode`, icons are `LucideIcon`.
+- Hooks that return several values export their result type: `export type BulkQueue = ReturnType<typeof useBulkQueue>`.
+- shadcn components in `components/ui` follow the official base-nova TypeScript sources; `components.json` sets `tsx: true`, so `npx shadcn add` writes TypeScript.
+- `api.ts` methods return the shared response types. Pages use those types instead of restating them.
## Module System
-- **Backend:** ES modules only (`"type": "module"` in `backend/package.json`). Use `import`/`export`. No `require()`.
-- **Frontend:** ES modules via Vite. Same rules.
-- Never mix `import` and `require()` in the same file.
+ES modules everywhere (`"type": "module"` in both workspaces). Use `import`/`export`, never `require()`.
## File Conventions
-- **Backend files:** `camelCase.js` - `server.js`, `auth.js`, `instagram.js`, `db.js`
-- **Frontend utility/service files:** `camelCase.js` - `api.js`, `formatters.js`
-- **Frontend React files:** `PascalCase.jsx` - `Overview.jsx`, `AppContext.jsx`
-- **shadcn generated files:** `kebab-case.jsx` - do not rename these
+| Kind | Name | Example |
+|---|---|---|
+| Backend modules | `camelCase.ts` | `server.ts`, `db.ts`, `instagramApi.ts` |
+| Frontend helpers and services | `camelCase.ts` | `api.ts`, `formatters.ts`, `overviewStats.ts` |
+| React components and pages | `PascalCase.tsx` | `Overview.tsx`, `AppContext.tsx` |
+| Feature hooks | `useCamelCase.ts` in the feature folder | `useOverviewData.ts` |
+| Shared hooks | `use-kebab-case.ts` in `src/hooks` | `use-account-analytics.ts` |
+| shadcn generated files | `kebab-case.tsx`, do not rename | `dropdown-menu.tsx` |
+| Type-only modules | `camelCase.ts` | `shared/types/domain.ts`, `backend/types/env.ts` |
+| Tests | `<source name>.test.ts` in the workspace `tests/` folder | `backend/tests/services/youtube.test.ts` |
+
+A `.tsx` extension is only for files that contain JSX.
## Comments Policy
-Write no comments by default. Add a comment only when the WHY is non-obvious and cannot be expressed in naming alone: a hidden constraint, a surprising invariant, a workaround for a specific bug.
+Write no comments by default. Add a comment only when the WHY is non-obvious and cannot be expressed in naming or in a type: a hidden constraint, a surprising invariant, a workaround for a specific bug.
**Do not write:**
-- Comments explaining what the code does (naming does that)
+- Comments explaining what the code does (naming and types do that)
- Comments referencing the task or PR ("added for issue #123")
- Multi-line comment blocks
-- JSDoc
+- JSDoc (types replace it)
**Do write (sparingly):**
-```js
+```ts
// userId=null means service-level - used by cron handlers that scan all users
-export async function getAccounts(supabase, userId = null) { ... }
-
-// Redis HMAC state: base64url(userId:timestamp).HMAC-SHA256-sig - see cache.js
+export async function getAccounts(supabase: SupabaseClient, userId: string | null = null): Promise<Account[]> { ... }
```
## Naming
-- Functions: `camelCase` - `getAccounts`, `computeVideoAnalytics`, `publishToInstagram`
-- Variables: `camelCase` - `accountId`, `scheduledAt`, `accessToken`
-- Constants: `SCREAMING_SNAKE_CASE` only for true global constants (rare)
-- React components: `PascalCase` - `ChannelAnalytics`, `AppProvider`
+- Functions and variables: `camelCase` - `getAccounts`, `computeVideoAnalytics`, `scheduledAt`
+- Types, interfaces and React components: `PascalCase` - `ScheduledPost`, `ChannelAnalytics`
+- Constants: `SCREAMING_SNAKE_CASE` only for true module-level constants
+- Prop interfaces: `<Component>Props`; request and response types: `<Thing>Request`, `<Thing>Response`
Prefer names that describe intent, not implementation:
- `getVideosCache` not `redisGetVideos`
@@ -48,33 +139,33 @@ Prefer names that describe intent, not implementation:
## Error Handling
In **route handlers**, always catch and return JSON errors:
-```js
+```ts
try {
const data = await someOperation();
return c.json(data);
} catch (err) {
- console.error('GET /my-route:', err.message);
- return c.json({ error: err.message }, 500);
+ console.error('GET /my-route:', (err as Error).message);
+ return c.json({ error: (err as Error).message }, 500);
}
```
-In **service functions**, throw descriptive errors - let the caller decide how to handle:
-```js
+In **service functions**, throw descriptive errors and let the caller decide how to handle them:
+```ts
if (data.error) throw new Error(data.error.message);
```
-In **cache functions**, always catch and silently ignore - cache failures must never bubble up:
-```js
-try { return await redis.get(key); } catch { return null; }
+In **cache functions**, always catch and silently ignore; cache failures must never bubble up:
+```ts
+try { return await redis.get<T>(key); } catch { return null; }
```
In **frontend components**, catch API errors and show toasts:
-```js
+```ts
try {
- const result = await api.doThing();
- showToast('Done!');
+ await api.deleteAccount(id);
+ showToast('Account removed');
} catch (err) {
- showToast(err.message, 'error');
+ showToast((err as Error).message, 'error');
}
```
@@ -82,52 +173,16 @@ try {
Use `async/await` everywhere. Do not use `.then()/.catch()` chains except in brief one-liners where the chain is clearer.
-```js
-// Good
-const data = await api.getAnalytics(id);
-
-// Avoid
-api.getAnalytics(id).then(data => ...).catch(err => ...);
-```
-
-## Variable Declarations
-
-Use `const` by default. Use `let` only when the variable is reassigned. Never use `var`.
+## Variables, Equality, Strings, Objects
-## Equality
-
-Always use `===` and `!==`. Never `==` or `!=`.
-
-## String Formatting
-
-Use template literals for all string interpolation:
-```js
-const url = `${SUPABASE_URL}/rest/v1/accounts?id=eq.${accountId}`;
-```
-
-## Object Patterns
-
-Prefer destructuring:
-```js
-const { id, platform, ...data } = account;
-const { data: { session } } = await supabase.auth.getSession();
-```
-
-Use optional chaining:
-```js
-const token = session?.access_token;
-const name = account?.data?.username;
-```
-
-Use nullish coalescing:
-```js
-const limit = params.limit ?? 500;
-const accounts = data ?? [];
-```
+- `const` by default, `let` only when reassigned, never `var`.
+- `===` and `!==` only.
+- Template literals for interpolation.
+- Prefer destructuring, optional chaining (`account?.data?.username`) and nullish coalescing (`params.limit ?? 500`).
## No Unused Code
-Do not leave unused variables, unused imports, or commented-out code blocks. Remove them.
+Do not leave unused variables, imports, types or commented-out code. Remove them.
## Lint and Format
@@ -135,11 +190,12 @@ The tooling config lives once at the repository root and covers both apps:
| File | What it sets |
|---|---|
-| `eslint.config.mjs` | ESLint flat config. Frontend: recommended, React hooks and React Refresh rules with browser globals. Backend: recommended rules with service worker globals (the Worker has no Node APIs). `backend/tests/`, `scripts/` and root config files: recommended rules with Node globals. |
+| `eslint.config.mjs` | ESLint flat config. Every `.ts`/`.tsx` file: ESLint recommended plus `typescript-eslint` recommended (`no-explicit-any` is an error). Frontend: React hooks and React Refresh rules with browser globals. Backend: service worker globals (the Worker has no Node APIs). Tests, `scripts/` and `vite.config.ts`: Node globals. |
+| `tsconfig.base.json` | Shared compiler settings; see Compiler Settings above |
| `.prettierrc.json` | Single quotes, semicolons, trailing commas, `arrowParens: "avoid"`, 120 columns, 2-space indentation, 4 spaces in `backend/` |
| `.prettierignore` | Skips `node_modules`, build output, `package-lock.json`, the shadcn files in `frontend/src/components/ui`, the backend golden snapshots and Markdown |
| `.editorconfig` | Editor defaults: UTF-8, 2-space indentation, 4 in `backend/`, final newline, trimmed trailing whitespace except in Markdown |
-- Run `npm run lint` from the root before every commit. Unused variables are errors; in the backend, prefix an intentionally unused variable or argument with `_`.
-- Match the indentation and quote style of the file you edit. The existing code was not reformatted in bulk; `npm run format` applies Prettier to the whole repository and belongs in its own commit when it is run.
-- Do not add per-app ESLint or Prettier config files. Change the root config instead, and update this section and `docs/workflows/TESTING.md`.
+- Run `npm run typecheck` and `npm run lint` from the root before every commit. Unused variables are errors; in the backend, prefix an intentionally unused variable or argument with `_`.
+- Match the indentation and quote style of the file you edit. `npm run format` applies Prettier to the whole repository and belongs in its own commit when it is run.
+- Do not add per-app ESLint, Prettier or base TypeScript settings. Change the root config instead, and update this section and `docs/workflows/TESTING.md`.
diff --git a/docs/mcp/CONTEXT7.md b/docs/mcp/CONTEXT7.md
index b7403d9..0613dd1 100644
--- a/docs/mcp/CONTEXT7.md
+++ b/docs/mcp/CONTEXT7.md
@@ -11,18 +11,20 @@ Context7 fetches current, version-accurate documentation for libraries and APIs.
## When to Use
-✅ **Use Context7 for:**
+**Use Context7 for:**
- Instagram Graph API - container creation params, field names, error codes
- YouTube Data API v3 - endpoint params, quota costs, response shapes
- Hono v4 - middleware API, context methods, routing
-- Supabase JS - client methods, query builder, auth API
+- Supabase JS (`@supabase/supabase-js`) - client methods, query builder, auth API, exported types
- Cloudflare Workers - runtime APIs, `ctx.waitUntil()`, env bindings
- Recharts v3 - component props, data shapes, chart configuration
- shadcn/ui components - available props, slot composition
- React 19 - hooks API, new features
- React Router v7 - `createBrowserRouter`, `Outlet`, nested routes
+- TypeScript 6.0 - compiler options in `tsconfig.base.json`, type stripping rules
+- `@cloudflare/workers-types` and `@types/react` - runtime and component types
-❌ **Do not use Context7 for:**
+**Do not use Context7 for:**
- Debugging business logic (read the code instead)
- Code review
- Architecture decisions (use Sequential Thinking)
@@ -56,8 +58,8 @@ query-docs: "How do I use upsert with onConflict to specify composite primary ke
```
resolve-library-id: "hono cloudflare workers"
-query-docs: "How do I set and get values on the Hono context using c.set() and c.get()?
- What is the TypeScript interface for custom context variables?"
+query-docs: "How do I type c.set() and c.get() with the Variables generic on new Hono<{ Bindings; Variables }>()?
+ How do I type a middleware declared outside the router?"
```
### Recharts area chart
diff --git a/docs/mcp/FILESYSTEM.md b/docs/mcp/FILESYSTEM.md
index 6f502cd..0304d98 100644
--- a/docs/mcp/FILESYSTEM.md
+++ b/docs/mcp/FILESYSTEM.md
@@ -6,14 +6,14 @@ Filesystem MCP provides advanced file operations: recursive search, directory tr
## When to Use
-✅ **Use Filesystem for:**
+**Use Filesystem for:**
- Finding all files that import a specific module
- Getting a directory tree to understand project structure
- Searching for all uses of a function or variable name
- Moving or renaming files and updating all imports
- Reading multiple related files simultaneously
-❌ **Do not use Filesystem when:**
+**Do not use Filesystem when:**
- You know the exact file path (use Read tool directly)
- You're looking for a single string (use Grep tool directly)
- You're searching for a file by pattern (use Glob tool directly)
@@ -57,7 +57,7 @@ path: frontend/src/
The built-in Grep and Glob tools are faster for most search tasks:
- `Grep pattern="useAppContext"` - faster than filesystem search for string patterns
-- `Glob pattern="backend/routes/*.js"` - faster than filesystem for file patterns
+- `Glob pattern="backend/routes/*.ts"` - faster than filesystem for file patterns
- `Read file_path="..."` - faster than filesystem for single file reads
Use Filesystem MCP when you need its specific features: recursive directory trees, multi-file reads in one call, or file move operations.
diff --git a/docs/mcp/PARALLEL_SEARCH.md b/docs/mcp/PARALLEL_SEARCH.md
index e372be8..95e128b 100644
--- a/docs/mcp/PARALLEL_SEARCH.md
+++ b/docs/mcp/PARALLEL_SEARCH.md
@@ -6,7 +6,7 @@ Parallel Search fetches current web content for research tasks: UX patterns, bro
## When to Use
-✅ **Use Parallel Search for:**
+**Use Parallel Search for:**
- UX patterns for a feature you're designing ("how do social media schedulers handle bulk post editing?")
- Browser/platform compatibility ("does Instagram Graph API support carousel posts on all account types?")
- Recent API changes not yet in Context7 ("Instagram Graph API v21 vs v25 container creation changes")
@@ -14,7 +14,7 @@ Parallel Search fetches current web content for research tasks: UX patterns, bro
- Competitor analysis ("how does Buffer/Hootsuite handle the scheduling queue UI?")
- Current events ("is Upstash Redis still recommended for Cloudflare Workers in 2025?")
-❌ **Do not use Parallel Search for:**
+**Do not use Parallel Search for:**
- Library API docs with stable method signatures (use Context7)
- Codebase exploration (use Filesystem)
- Architecture planning (use Sequential Thinking)
diff --git a/docs/mcp/SEQUENTIAL_THINKING.md b/docs/mcp/SEQUENTIAL_THINKING.md
index 56101a9..6d8e531 100644
--- a/docs/mcp/SEQUENTIAL_THINKING.md
+++ b/docs/mcp/SEQUENTIAL_THINKING.md
@@ -6,7 +6,7 @@ Sequential Thinking enables structured, step-by-step reasoning for complex probl
## When to Use
-✅ **Use Sequential Thinking for:**
+**Use Sequential Thinking for:**
- Planning a new feature that touches more than 3 files
- Architecture decisions with multiple viable approaches
- Debugging when the root cause is not immediately obvious
@@ -14,7 +14,7 @@ Sequential Thinking enables structured, step-by-step reasoning for complex probl
- Features that require coordinating frontend + backend + DB changes
- Evaluating trade-offs between approaches
-❌ **Do not use Sequential Thinking for:**
+**Do not use Sequential Thinking for:**
- Simple, well-understood tasks (adding a route that follows an existing pattern exactly)
- Library API lookups (use Context7)
- File searches (use Filesystem or Grep)
@@ -66,7 +66,8 @@ Sequential Thinking would work through:
- Which endpoints to call (`/user/{username}/submitted.json`, etc.)
- How to store credentials (in `accounts.data` jsonb alongside Instagram pattern)
- Token refresh strategy (poll `Set-Cookie` header on each API call)
-- New cache keys to add to `cache.js`
+- Which shapes go in `shared/types/reddit.ts` (profile, post, analytics, cache entry)
+- New cache keys to add to `cache.ts`
- New routes to add to backend
- New analytics page structure
- How the sidebar/nav changes
diff --git a/docs/philosophy/ARCHITECTURE.md b/docs/philosophy/ARCHITECTURE.md
index 93ff034..929b09e 100644
--- a/docs/philosophy/ARCHITECTURE.md
+++ b/docs/philosophy/ARCHITECTURE.md
@@ -38,9 +38,9 @@ User-specific tokens (Instagram access tokens, GitHub PATs) live in `accounts.da
New platform-specific fields go into the `data jsonb` column on `accounts` or `scheduled_posts`. Adding a new table requires a clear reason: the data has a lifecycle of its own, or it needs to be queried/filtered by a column that can't be in jsonb. See `ADR-005`.
-### 7. No TypeScript anywhere
+### 7. Strict TypeScript, stripped rather than compiled
-This is a deliberate constraint, not an oversight. See `ADR-010` and `docs/guidelines/JAVASCRIPT.md`.
+Every layer is TypeScript in `strict` mode, and the API contract lives once in `shared/types/`, used by both the Worker and the frontend. Nothing is compiled ahead of time: Wrangler, Vite and Node strip the types, and `npm run typecheck` gates every deploy and pull request. Only erasable syntax is allowed, so any file can run directly under Node. See `ADR-030` (which replaces `ADR-010`) and `docs/guidelines/TYPESCRIPT.md`.
## What This Architecture Is Not
@@ -55,7 +55,7 @@ This is a deliberate constraint, not an oversight. See `ADR-010` and `docs/guide
These principles guide the initial implementation. Breaking them requires an explicit ADR:
- Adding a second Worker: write `ADR-013` explaining why one Worker is insufficient
- Enabling RLS: write an ADR explaining why application-layer isolation failed
-- Adding TypeScript: write an ADR with clear measurable benefit
+- Adding a compile step or non-erasable TypeScript syntax (`enum`, parameter properties): write an ADR with clear measurable benefit
- Adding a state management library: write an ADR showing that context + local state is insufficient
The cost of documenting the decision is intentionally low. The point is to make the tradeoff visible, not to prevent evolution.
diff --git a/docs/philosophy/PERFORMANCE.md b/docs/philosophy/PERFORMANCE.md
index 56b5f7c..d6f6eb1 100644
--- a/docs/philosophy/PERFORMANCE.md
+++ b/docs/philosophy/PERFORMANCE.md
@@ -21,7 +21,7 @@ Request
| YouTube analytics | `videos:{userId}:{accountId}` | 6 hours | Versioned; old versions read as a miss |
| Instagram analytics | `ig:{userId}:{accountId}` | 6 hours | Versioned; old versions read as a miss |
| Reddit analytics | `reddit:{userId}:{accountId}` | 6 hours | |
-| OAuth state | none (HMAC-signed token, see `lib/oauthState.js`) | 10 minutes | Security-critical - do not extend |
+| OAuth state | none (HMAC-signed token, see `lib/oauthState.ts`) | 10 minutes | Security-critical - do not extend |
Cache invalidation happens on:
- Account deletion (explicit `redis.del()`)
@@ -34,7 +34,7 @@ There is no time-based expiration for analytics caches yet (known issue). Until
When fixing the known TTL issue, use the Upstash Redis `EX` option:
-```js
+```ts
await redis.set(key, data, { ex: 3600 }); // expire after 1 hour
```
diff --git a/docs/philosophy/SECURITY.md b/docs/philosophy/SECURITY.md
index 99ce437..9a49708 100644
--- a/docs/philosophy/SECURITY.md
+++ b/docs/philosophy/SECURITY.md
@@ -44,7 +44,7 @@ The Worker uses the service role key and is therefore responsible for its own ac
**What this prevents:** User A querying user B's accounts, posts, or settings by guessing an account ID.
**What to verify when adding new queries:**
-```js
+```ts
// Correct: userId from JWT, not from request body or params
const userId = c.get('userId');
const { data } = await supabase
diff --git a/docs/workflows/DEPLOYMENT.md b/docs/workflows/DEPLOYMENT.md
index d3436ee..bc8912f 100644
--- a/docs/workflows/DEPLOYMENT.md
+++ b/docs/workflows/DEPLOYMENT.md
@@ -9,13 +9,14 @@ Push to `main` -> GitHub Actions deploys automatically.
| `backend/**` | `deploy-backend.yml` | Cloudflare Worker |
| `frontend/**` | `deploy-frontend.yml` | Cloudflare Pages |
| Both | Both workflows | Both (in parallel) |
+| `shared/**` or `tsconfig.base.json` | Both workflows | Both (in parallel) |
| Root `package.json` or `package-lock.json` | Both workflows | Both (in parallel) |
| `docs/`, `scripts/`, `*.md` | Neither | Nothing deployed |
Monitor deployment status at:
`https://github.com/spacesdrive/twiligent/actions`
-Both deploy workflows set up Node 24, run `npm ci` once at the repository root (the root `package-lock.json` is the only lockfile), and deploy with the Wrangler version pinned in that lockfile. See `docs/architecture/cloudflare/CI_CD.md`.
+Both deploy workflows set up Node 24, run `npm ci` once at the repository root (the root `package-lock.json` is the only lockfile), type-check and test their workspace (`npm run typecheck --workspace <app>`, `npm test --workspace <app>`), and only then deploy with the Wrangler version pinned in that lockfile. A type error or failing test stops the deploy. Before code reaches `main`, `ci.yml` runs the full type check, lint, tests, frontend build and a Worker dry-run bundle on every pull request and branch push. See `docs/architecture/cloudflare/CI_CD.md`.
## Manual Deployment (Local)
@@ -25,6 +26,15 @@ The repository is an npm workspaces monorepo. Install once at the root; never ru
npm ci
```
+This needs Node 22.18 or newer (the root `package.json` `engines` field), because the tests and `scripts/publish-scheduled.ts` run as TypeScript under Node. Before any manual deploy, run the same checks CI runs:
+
+```bash
+npm run typecheck
+npm test
+```
+
+Wrangler and Vite strip types without checking them, so skipping `npm run typecheck` can ship code with type errors.
+
Wrangler is a backend dev dependency, so `npx wrangler` runs the lockfile version from any folder in the repo. Authenticate once with `npx wrangler login`.
### Backend (Cloudflare Worker)
@@ -89,7 +99,7 @@ Required for `deploy-frontend.yml` and `publish-scheduled.yml`:
- `SUPABASE_URL`
- `SUPABASE_SERVICE_KEY`
-**Windows / PowerShell note:** When setting GitHub secrets via PowerShell, use UTF-8 without BOM encoding to avoid the `ByteString` error. Write to a temp file using `[System.Text.UTF8Encoding]::new($false)` then pipe to `gh secret set`. See `scripts/publish-scheduled.js` for the defensive `.replace(/[^\x20-\x7E]/g, '').trim()` pattern that handles any remaining BOM.
+**Windows / PowerShell note:** When setting GitHub secrets via PowerShell, use UTF-8 without BOM encoding to avoid the `ByteString` error. Write to a temp file using `[System.Text.UTF8Encoding]::new($false)` then pipe to `gh secret set`. See `scripts/publish-scheduled.ts` for the defensive `.replace(/[^\x20-\x7E]/g, '').trim()` pattern that handles any remaining BOM.
## Deployment Verification
@@ -127,10 +137,10 @@ For a fresh deployment from this repo:
3. Create Upstash Redis database (optional)
4. Create Cloudinary account + upload preset
5. Create Meta/Facebook Developer app with Instagram Graph API product
-6. `npm ci` at the repository root, then `npx wrangler login`
+6. Install Node 22.18 or newer, run `npm ci` at the repository root, then `npx wrangler login`
7. Set all Worker secrets (see above)
8. Set all GitHub Actions secrets (see above)
-9. `cd backend && npx wrangler deploy` (first manual deploy)
+9. `npm run typecheck`, then `cd backend && npx wrangler deploy` (first manual deploy)
10. Verify health endpoint
11. `npm run build` at the root, then `cd frontend && npx wrangler pages deploy dist --project-name=twiligent`
12. Verify frontend loads
diff --git a/docs/workflows/FEATURE_DEVELOPMENT.md b/docs/workflows/FEATURE_DEVELOPMENT.md
index e438caf..8154513 100644
--- a/docs/workflows/FEATURE_DEVELOPMENT.md
+++ b/docs/workflows/FEATURE_DEVELOPMENT.md
@@ -68,10 +68,10 @@ Determine:
**Step 10 - Identify reuse opportunities**
Before creating new patterns, check:
-- Is there a db.js function that almost does what you need? Extend it.
+- Is there a db.ts function that almost does what you need? Extend it.
- Is there a service function you can call? Use it.
- Is there a shadcn component that fits? Use it.
-- Is there a formatting function in formatters.js? Use it.
+- Is there a formatting function in formatters.ts? Use it.
---
@@ -79,28 +79,30 @@ Before creating new patterns, check:
**Step 11 - Implement in this order:**
1. DB schema changes (if any) - see `docs/features/NEW_DATABASE_TABLE.md`
-2. Backend: `lib/db.js` additions (new query functions)
-3. Backend: `services/` additions (new external API calls)
-4. Backend: `routes/` additions (new route handlers)
-5. Backend: `server.js` mounting (if new router)
-6. Frontend: `services/api.js` additions (new API methods)
-7. Frontend: new page/feature component
-8. Frontend: `App.jsx` routing (if new page)
-9. Frontend: `Sidebar.jsx` navigation (if new page needs nav entry)
-10. Tests for new pure logic, in the workspace's `tests/` folder at the path that mirrors the source file (`backend/services/youtube.js` -> `backend/tests/services/youtube.test.js`, `frontend/src/lib/accounts.js` -> `frontend/tests/lib/accounts.test.js`); see `docs/workflows/TESTING.md`
+2. Types: request, response and entity shapes in `shared/types/` (types only, no runtime code); see `docs/guidelines/TYPESCRIPT.md`
+3. Backend: `lib/db.ts` additions (new query functions)
+4. Backend: `services/` additions (new external API calls)
+5. Backend: `routes/` additions (new route handlers on `new Hono<AppEnv>()`, responses checked with `satisfies`)
+6. Backend: `server.ts` mounting (if new router)
+7. Frontend: `services/api.ts` additions (new API methods returning the shared types)
+8. Frontend: new page/feature component, with a `<Component>Props` interface for each component that takes props
+9. Frontend: `App.tsx` routing (if new page)
+10. Frontend: `layout/navigation.ts` (if new page needs a nav entry)
+11. Tests for new pure logic, in the workspace's `tests/` folder at the path that mirrors the source file (`backend/services/youtube.ts` -> `backend/tests/services/youtube.test.ts`, `frontend/src/lib/accounts.ts` -> `frontend/tests/lib/accounts.test.ts`); see `docs/workflows/TESTING.md`
If the feature needs a new npm package (approval required, see CLAUDE.md), add it to the app that uses it from the repository root: `npm install <pkg> --workspace backend` or `--workspace frontend`. Never run `npm install` inside `backend/` or `frontend/`; the root `package-lock.json` is the only lockfile.
**Step 12 - Eliminate duplication**
-After implementing, look for logic that duplicates something that already existed. Extract it into the appropriate shared location (`lib/db.js`, `services/`, `utils/formatters.js`, shared components).
+After implementing, look for logic that duplicates something that already existed. Extract it into the appropriate shared location (`lib/db.ts`, `services/`, `utils/formatters.ts`, shared components).
---
## Phase 5: Verify
-**Step 13 - Build verification**
+**Step 13 - Type check and build verification**
Run from the repository root:
```bash
+npm run typecheck # every TypeScript project must type-check
npm run build # frontend must build without errors
npm test # backend and frontend unit tests must pass
npm run dev # Worker (8787) and Vite (5173) must both start without errors
diff --git a/docs/workflows/GIT.md b/docs/workflows/GIT.md
index c80f695..fc90783 100644
--- a/docs/workflows/GIT.md
+++ b/docs/workflows/GIT.md
@@ -23,7 +23,7 @@ A meaningful change is one that:
- Updates documentation to reflect a real change
- Refactors without changing behavior
-Do not commit work-in-progress that breaks the build. Use a feature branch if the work spans multiple sessions.
+Do not commit work-in-progress that breaks the build or the type check. Use a feature branch if the work spans multiple sessions.
---
@@ -100,8 +100,8 @@ release: v1.1.0 - Reddit integration
## What to Commit Together
### Always group these in a single commit:
-- A new route + its db.js functions + its api.js method
-- A new page + its route in App.jsx + its Sidebar entry
+- A new route + its db.ts functions + its api.ts method
+- A new page + its route in App.tsx + its Sidebar entry
- A bug fix + updated docs if the fix changes documented behavior
- A new feature + CHANGELOG.md update + relevant architecture doc updates
- A dependency change + the workspace `package.json` it touches + the root `package-lock.json`
@@ -199,15 +199,16 @@ Run before every commit:
Run the commands from the repository root:
-1. `npm run build` - frontend must build without errors
-2. `npm test` - backend and frontend unit tests must pass
-3. `npm run lint` - no new lint errors (one run covers backend, frontend, tests and scripts)
-4. `git status` - verify only intended files are staged
-5. `git diff --staged` - review the full diff before committing
-6. Check no secrets or credentials appear in the diff
-7. Check no lockfile appears inside `backend/` or `frontend/`; the root `package-lock.json` is the only lockfile
-8. Verify CHANGELOG.md is updated if the commit adds a feature or fix
-9. Verify the commit body ends with `Refs #N` or `Closes #N` for the tracking issue
+1. `npm run typecheck` - every TypeScript project must type-check (Vite and Wrangler do not check types)
+2. `npm run build` - frontend must build without errors
+3. `npm test` - backend and frontend unit tests must pass
+4. `npm run lint` - no new lint errors (one run covers backend, frontend, tests and scripts)
+5. `git status` - verify only intended files are staged
+6. `git diff --staged` - review the full diff before committing
+7. Check no secrets or credentials appear in the diff
+8. Check no lockfile appears inside `backend/` or `frontend/`; the root `package-lock.json` is the only lockfile
+9. Verify CHANGELOG.md is updated if the commit adds a feature or fix
+10. Verify the commit body ends with `Refs #N` or `Closes #N` for the tracking issue
---
@@ -217,7 +218,8 @@ After pushing to `main`, monitor GitHub Actions:
- `backend/` changes trigger `deploy-backend.yml`
- `frontend/` changes trigger `deploy-frontend.yml`
-- Root `package.json` or `package-lock.json` changes trigger both
+- `shared/`, `tsconfig.base.json`, root `package.json` or `package-lock.json` changes trigger both
+- Every pull request and every push to another branch runs `ci.yml` (type check, lint, test, build, Worker dry-run)
- `scripts/` changes do not trigger automatic deployment
If a deployment workflow fails:
diff --git a/docs/workflows/SCHEDULING_SETUP.md b/docs/workflows/SCHEDULING_SETUP.md
index eb0f7b0..cb92eea 100644
--- a/docs/workflows/SCHEDULING_SETUP.md
+++ b/docs/workflows/SCHEDULING_SETUP.md
@@ -57,7 +57,7 @@ GitHub switches workflows off in new copies.
| What you see | What it means | Fix |
|---|---|---|
-| Red cross, "Missing SUPABASE_URL or SUPABASE_SERVICE_KEY" | A secret name is misspelled | Check the names in step 3 |
+| Red cross, "Error: missing SUPABASE_URL or SUPABASE_SERVICE_KEY" | A secret name is misspelled | Check the names in step 3 |
| Red cross, "Supabase GET ... 401" | The secret key is wrong or cut short | Copy the key again in step 2 and replace the secret |
| No Run workflow button | The workflow is still switched off | Repeat step 4 |
@@ -66,6 +66,7 @@ GitHub switches workflows off in new copies.
## After setup
- GitHub checks every 15 minutes. You do not need to keep anything open.
+- The workflow runs `node scripts/publish-scheduled.ts` on Node 24, which runs the TypeScript file directly. It installs nothing, so there is no build step to maintain in your copy.
- The server scheduler and this workflow can run at the same time. Each post is claimed by whichever runs first, so it is published once.
- If nothing changes in your copy for 60 days, GitHub pauses the schedule and emails you. Repeat step 4.
- A private copy uses GitHub's free minutes (2,000 a month), and a run every 15 minutes uses more than that. Keep your copy public, or change `*/15 * * * *` to `*/30 * * * *` in `.github/workflows/publish-scheduled.yml`.
diff --git a/docs/workflows/TESTING.md b/docs/workflows/TESTING.md
index 91e2378..fff19b2 100644
--- a/docs/workflows/TESTING.md
+++ b/docs/workflows/TESTING.md
@@ -4,15 +4,16 @@
Most testing is manual. Both the backend and the frontend have unit tests for pure logic using Node's built-in test runner (no dependencies). Broader coverage is a known gap - see ROADMAP.md.
-Run every test from the repository root:
+Run every test and the type check from the repository root:
```bash
npm test # backend, then frontend
npm test --workspace backend # backend only
npm test --workspace frontend # frontend only
+npm run typecheck # every TypeScript project
```
-Each workspace's `test` script is `node --test "tests/**/*.test.js"`.
+Each workspace's `test` script is `node --test "tests/**/*.test.ts"`. The tests are TypeScript: Node strips the types and runs the files directly, which needs Node 22.18 or newer (CI uses Node 24). Node does not check types while it runs them, so a test can pass with a type error; `npm run typecheck` covers the tests too (`backend/tests/tsconfig.json` and `frontend/tsconfig.node.json`).
### Test layout
@@ -20,29 +21,34 @@ Tests never sit next to source files. Each workspace has a `tests/` folder that
| Source file | Test file |
|---|---|
-| `backend/services/youtube.js` | `backend/tests/services/youtube.test.js` |
-| `backend/routes/accounts.js` | `backend/tests/routes/accounts.test.js` |
-| `backend/utils/scheduler.js` | `backend/tests/utils/scheduler.test.js` |
-| `frontend/src/lib/accounts.js` | `frontend/tests/lib/accounts.test.js` |
-| `frontend/src/features/analytics/overview/overviewStats.js` | `frontend/tests/features/analytics/overview/overviewStats.test.js` |
-| `frontend/src/docs/nav.js` | `frontend/tests/docs/nav.test.js` |
+| `backend/services/youtube.ts` | `backend/tests/services/youtube.test.ts` |
+| `backend/routes/accounts.ts` | `backend/tests/routes/accounts.test.ts` |
+| `backend/utils/scheduler.ts` | `backend/tests/utils/scheduler.test.ts` |
+| `frontend/src/lib/accounts.ts` | `frontend/tests/lib/accounts.test.ts` |
+| `frontend/src/features/analytics/overview/overviewStats.ts` | `frontend/tests/features/analytics/overview/overviewStats.test.ts` |
+| `frontend/src/docs/nav.ts` | `frontend/tests/docs/nav.test.ts` |
-Backend tests are in `backend/tests/lib`, `backend/tests/routes`, `backend/tests/services` and `backend/tests/utils`. Shared test helpers (`fakeSupabase.js`, `fakeFetch.js`, `golden.js`, `routeHarness.js`, the per-platform `*Fixtures.js` data) and the `*.golden.json` snapshots are in `backend/tests/fixtures/`. Wrangler only bundles files reachable from `server.js`, so nothing in `backend/tests/` ships in the Worker.
+Backend tests are in `backend/tests/lib`, `backend/tests/middleware`, `backend/tests/routes`, `backend/tests/services` and `backend/tests/utils`. Shared test helpers (`fakeSupabase.ts`, `fakeFetch.ts`, `golden.ts`, `routeHarness.ts`, the per-platform `*Fixtures.ts` data) and the `*.golden.json` snapshots are in `backend/tests/fixtures/`. Wrangler only bundles files reachable from `server.ts`, so nothing in `backend/tests/` ships in the Worker.
-Frontend tests cover shared helpers in `src/lib/` and `src/utils/` (hold-to-confirm timing, command palette ranking, library filtering and paging, platform helpers, and a check that every Lucide icon imported in `src` exists) and page helpers in `src/features/**` and `src/docs/**`, such as `features/analytics/overview/overviewStats.js`. A testable helper is a plain `.js` file with no JSX and no `@/` imports, and its imports of project files are relative paths that end in `.js`, so Node can load it directly. This rule lives here, so helper files do not repeat it in a header comment.
+Frontend tests cover shared helpers in `src/lib/` and `src/utils/` (hold-to-confirm timing, command palette ranking, library filtering and paging, platform helpers, and a check that every Lucide icon imported in `src` exists) and page helpers in `src/features/**` and `src/docs/**`, such as `features/analytics/overview/overviewStats.ts`. A testable helper is a plain `.ts` file with no JSX and no `@/` or `@shared/` imports, and its imports of project files (including `shared/types`) are relative paths that end in `.ts`, so Node can load it directly. It uses only erasable TypeScript (no `enum`, no parameter properties) and `import type` for types. This rule lives here, so helper files do not repeat it in a header comment.
+
+Test files import the code under test the same way, by relative path with the `.ts` extension (`../../src/lib/accounts.ts`). Type test fakes narrowly: cast a fake once to the interface it stands in for, rather than using `any`, which is a lint error.
Rate limiting has its own tests: `tests/lib/rateLimit/algorithms.test.ts` (each algorithm's decisions, retry and reset times), `tests/lib/rateLimit/limiter.test.ts` (Redis path, memory fallback, circuit breaker, deny cache, eviction) and `tests/middleware/rateLimit.test.ts` (headers, the 429 body, route filters, IPv6 keys). The Lua scripts in `lib/rateLimit/scripts.ts` cannot run in Node; when you change one, change the twin function in `algorithms.ts` the same way and check both against each other in a Lua VM (see `docs/architecture/backend/RATE_LIMITING.md`).
-Backend route and scheduler tests (`tests/routes/*.test.js`, `tests/utils/scheduler.test.js`) run the real handlers against `tests/fixtures/fakeSupabase.js` and a scripted `fetch`, then compare responses, queries and outgoing requests with the `tests/fixtures/*.golden.json` snapshots. Rows tagged with `tableRow(name, row)` are only visible to that table; untagged rows are visible to every table. A refactor must leave the snapshots unchanged. Prettier ignores the snapshots (`.prettierignore`), because the tests compare them byte for byte.
+Backend route and scheduler tests (`tests/routes/*.test.ts`, `tests/utils/scheduler.test.ts`) run the real handlers against `tests/fixtures/fakeSupabase.ts` and a scripted `fetch`, then compare responses, queries and outgoing requests with the `tests/fixtures/*.golden.json` snapshots. Rows tagged with `tableRow(name, row)` are only visible to that table; untagged rows are visible to every table. A refactor must leave the snapshots unchanged. Prettier ignores the snapshots (`.prettierignore`), because the tests compare them byte for byte.
The testing workflow documented here describes what should run before shipping any change.
## Pre-Deployment Checklist
-### 1. Build Verification
+### 1. Type Check and Build Verification
```bash
-# From the repository root: frontend must build without errors
+# From the repository root: every TypeScript project must type-check
+npm run typecheck
+
+# Frontend must build without errors
npm run build
# Unit tests must pass
@@ -52,7 +58,7 @@ npm test
cd backend && npx wrangler deploy --dry-run
```
-A broken build is a hard blocker. Do not deploy if build fails.
+A type error or a broken build is a hard blocker. Do not deploy if either fails. Vite and Wrangler strip types without checking them, so a clean build does not mean the code type-checks. `ci.yml` runs these same steps (plus lint) on every pull request and branch push.
### 2. Lint
@@ -61,11 +67,13 @@ npm run lint
```
One ESLint run from the root covers the whole repository. The shared config is `eslint.config.mjs` at the root:
-- `frontend/**`: the ESLint recommended rules, React hooks rules (no conditional hooks) and React Refresh rules, with browser globals; unused variables are errors unless they start with a capital letter or underscore
-- `backend/**`: the ESLint recommended rules with service worker globals, because the Worker runs on the web platform, not Node; unused variables and arguments starting with `_` are allowed, and unused caught errors are not reported
-- `backend/tests/**`, `scripts/**` and root config files: the ESLint recommended rules with Node globals
+- Every `.ts` and `.tsx` file: the ESLint recommended rules plus the `typescript-eslint` recommended rules (`@typescript-eslint/no-explicit-any` is an error)
+- `frontend/**`: also React hooks rules (no conditional hooks) and React Refresh rules, with browser globals; unused variables are errors unless they start with a capital letter or underscore
+- `backend/**`: service worker globals, because the Worker runs on the web platform, not Node; unused variables and arguments starting with `_` are allowed, and unused caught errors are not reported
+- `backend/tests/**`, `frontend/tests/**`, `frontend/vite.config.ts` and `scripts/**`: Node globals
+- Root `*.js` and `*.mjs` config files: the ESLint recommended rules with Node globals
-Do not add lint errors. The frontend has 8 known errors that predate the shared config: `react-refresh/only-export-components` in `components/ui/badge.jsx`, `button.jsx`, `sidebar.jsx`, `tabs.jsx` and `toggle.jsx` and in `context/AppContext.jsx` and `AuthContext.jsx`, and `no-undef` for `__dirname` in `vite.config.js`. Any other error is new.
+Do not add lint errors. The frontend has 7 known errors, all `react-refresh/only-export-components`: in `components/ui/badge.tsx`, `button.tsx`, `sidebar.tsx`, `tabs.tsx` and `toggle.tsx`, and in `context/AppContext.tsx` and `AuthContext.tsx`. These files export a hook or a variants helper next to their component. Any other error is new.
### Formatting
@@ -138,9 +146,9 @@ Open the app in a browser. For each changed area, test:
### 6. Console Error Verification
Open browser DevTools -> Console. Navigate through all changed pages.
-- No JavaScript errors
+- No runtime errors or uncaught promise rejections
- No failed network requests (red in Network tab)
-- No React warnings about missing keys, prop types, etc.
+- No React warnings about missing keys or invalid DOM props
### 7. Accessibility Verification
@@ -167,7 +175,7 @@ Verify:
### 9. Scheduled Publisher Verification
-After any change to `scripts/publish-scheduled.js` or `publish-scheduled.yml`:
+After any change to `scripts/publish-scheduled.ts` or `publish-scheduled.yml`:
1. GitHub Actions -> "Instagram Scheduled Publisher" -> "Run workflow"
2. Watch the run output
@@ -179,5 +187,5 @@ If you have a test post scheduled in the near future, use `GET /api/process-sche
Already in place: golden tests for `computeVideoAnalytics()`, `computeInstagramAnalytics()` and `computeRedditAnalytics()`, and route tests that run the Hono handlers against a fake Supabase client (`backend/tests/fixtures/`). Still to add, in priority order:
-1. **Tests for `lib/db.js` against a real database** - using a Supabase test project
+1. **Tests for `lib/db.ts` against a real database** - using a Supabase test project
2. **End-to-end tests** - Playwright for the full login -> view analytics -> publish flow
diff --git a/frontend/src/docs/nav.ts b/frontend/src/docs/nav.ts
index 6d52610..1ca1b45 100644
--- a/frontend/src/docs/nav.ts
+++ b/frontend/src/docs/nav.ts
@@ -1,4 +1,4 @@
-// tabs, sidebar groups and pages; routes.js maps each page to its component
+// tabs, sidebar groups and pages; routes.ts maps each page to its component
export interface DocPage {
slug: string;
diff --git a/frontend/src/docs/pages/Use.tsx b/frontend/src/docs/pages/Use.tsx
index 0829e68..8c5ce58 100644
--- a/frontend/src/docs/pages/Use.tsx
+++ b/frontend/src/docs/pages/Use.tsx
@@ -1,4 +1,4 @@
-// each page lives in use/; this barrel keeps them in one lazy chunk for routes.js
+// each page lives in use/; this barrel keeps them in one lazy chunk for routes.ts
export { default as GettingStarted } from './use/GettingStarted';
export { default as ConnectAccounts } from './use/ConnectAccounts';
export { default as Analytics } from './use/Analytics';
diff --git a/frontend/src/docs/pages/selfHost/DeployBackend.tsx b/frontend/src/docs/pages/selfHost/DeployBackend.tsx
index f3f2fb8..78c846d 100644
--- a/frontend/src/docs/pages/selfHost/DeployBackend.tsx
+++ b/frontend/src/docs/pages/selfHost/DeployBackend.tsx
@@ -17,7 +17,8 @@ npx wrangler login
</Step>
<Step title="Deploy once to get your URL">
<CodeBlock>{'npx wrangler deploy'}</CodeBlock>
- <P>Wrangler prints the Worker address, for example <Code>https://twiligent.your-subdomain.workers.dev</Code>. This is your <strong>backend URL</strong>.</P>
+ <P>Wrangler builds the Worker from <Code>server.ts</Code>, the entry file named in <Code>wrangler.toml</Code>, and prints the Worker address, for example <Code>https://twiligent.your-subdomain.workers.dev</Code>. This is your <strong>backend URL</strong>.</P>
+ <P>If you changed the code, run <Code>npm run typecheck</Code> in the top folder first. Wrangler does not check TypeScript types, so this is the step that catches a type error before it reaches Cloudflare.</P>
</Step>
<Step title="Add the secrets">
<P>Run each command and paste the value when asked. Values are encrypted by Cloudflare and never shown again.</P>
diff --git a/frontend/src/docs/pages/selfHost/DeployFrontend.tsx b/frontend/src/docs/pages/selfHost/DeployFrontend.tsx
index f2afb41..b7b622f 100644
--- a/frontend/src/docs/pages/selfHost/DeployFrontend.tsx
+++ b/frontend/src/docs/pages/selfHost/DeployFrontend.tsx
@@ -25,7 +25,7 @@ npm run build
cd frontend
npx wrangler pages deploy dist --project-name=twiligent
`}</CodeBlock>
- <P>The first time, Wrangler creates the Pages project and prints the address, for example <Code>https://twiligent.pages.dev</Code>.</P>
+ <P><Code>npm run build</Code> runs Vite with <Code>frontend/vite.config.ts</Code> and writes the site to <Code>frontend/dist</Code>. The first time, Wrangler creates the Pages project and prints the address, for example <Code>https://twiligent.pages.dev</Code>.</P>
</Step>
<Step title="Point the backend at it">
<P>Set <Code>FRONTEND_URL</Code> on the Worker to that address, so Instagram sign-in returns members to the right place:</P>
diff --git a/frontend/src/docs/pages/selfHost/GitHub.tsx b/frontend/src/docs/pages/selfHost/GitHub.tsx
index 2a7a8ca..6600319 100644
--- a/frontend/src/docs/pages/selfHost/GitHub.tsx
+++ b/frontend/src/docs/pages/selfHost/GitHub.tsx
@@ -8,7 +8,7 @@ export default function GitHub() {
<P>Both parts are optional. Fork <A href="https://github.com/spacesdrive/twiligent">spacesdrive/twiligent</A> to your own GitHub account first. Add secrets in your fork under <strong>Settings</strong>, <strong>Secrets and variables</strong>, <strong>Actions</strong>, <strong>New repository secret</strong>.</P>
<H2>Deploy on push</H2>
- <P>The workflows <Code>deploy-backend.yml</Code> and <Code>deploy-frontend.yml</Code> deploy whenever <Code>backend/</Code> or <Code>frontend/</Code> changes on <Code>main</Code>. A change to <Code>package.json</Code> or <Code>package-lock.json</Code> in the top folder deploys both, because those files list the packages for the whole project. Each workflow installs the packages itself, so there is nothing to install on GitHub.</P>
+ <P>The workflows <Code>deploy-backend.yml</Code> and <Code>deploy-frontend.yml</Code> deploy whenever <Code>backend/</Code> or <Code>frontend/</Code> changes on <Code>main</Code>. A change to <Code>shared/</Code>, <Code>tsconfig.base.json</Code>, <Code>package.json</Code> or <Code>package-lock.json</Code> in the top folder deploys both, because both parts use those files. Each workflow installs the packages itself, so there is nothing to install on GitHub. Before deploying, each one checks the TypeScript types and runs the tests, and stops if either fails. A third workflow, <Code>ci.yml</Code>, runs the same checks on every pull request and on pushes to other branches.</P>
<Table
head={['Secret', 'Where to get it']}
rows={[
@@ -24,7 +24,7 @@ export default function GitHub() {
<P>Worker secrets stay in Cloudflare; the backend workflow does not need them.</P>
<H2>Backup scheduler</H2>
- <P>The Worker already publishes scheduled posts. <Code>publish-scheduled.yml</Code> runs the same job from GitHub every 15 minutes as a safety net. Each post is claimed before publishing, so it is never posted twice even when both run at once.</P>
+ <P>The Worker already publishes scheduled posts. <Code>publish-scheduled.yml</Code> runs the same job from GitHub every 15 minutes as a safety net, with <Code>node scripts/publish-scheduled.ts</Code> on Node 24. The script needs no packages, so the workflow installs nothing. Each post is claimed before publishing, so it is never posted twice even when both run at once.</P>
<Steps>
<Step title="Add two secrets">
<P><Code>SUPABASE_URL</Code> and <Code>SUPABASE_SERVICE_KEY</Code>, with the same values the Worker uses.</P>
diff --git a/frontend/src/docs/pages/selfHost/Overview.tsx b/frontend/src/docs/pages/selfHost/Overview.tsx
index 48c555a..c9157d3 100644
--- a/frontend/src/docs/pages/selfHost/Overview.tsx
+++ b/frontend/src/docs/pages/selfHost/Overview.tsx
@@ -40,7 +40,7 @@ export default function Overview() {
<H2>What you need on your computer</H2>
<UL>
- <li>Node.js 22 or newer, and Git.</li>
+ <li>Node.js 22.18 or newer, and Git. The tests and the backup scheduler script are TypeScript files that Node runs directly, which older versions cannot do.</li>
<li>A copy of the code: <Code>git clone https://github.com/spacesdrive/twiligent.git</Code></li>
<li>The project's packages: run <Code>npm install</Code> once in the cloned <Code>twiligent</Code> folder. It installs the backend, the website and the Wrangler command used to deploy them.</li>
</UL>
diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts
index a0430ea..bca4f29 100644
--- a/frontend/vite.config.ts
+++ b/frontend/vite.config.ts
@@ -8,6 +8,7 @@ export default defineConfig({
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
+ '@shared': path.resolve(__dirname, '../shared'),
},
},
})
diff --git a/scripts/publish-scheduled.ts b/scripts/publish-scheduled.ts
index 879eb51..a2b1f76 100644
--- a/scripts/publish-scheduled.ts
+++ b/scripts/publish-scheduled.ts
@@ -1,14 +1,7 @@
#!/usr/bin/env node
-/**
- * Instagram Scheduled Post Publisher
- *
- * Runs standalone in GitHub Actions (cron every 15 min).
- * Uses native fetch (Node 18+) and the Supabase REST API - no npm install needed.
- *
- * Required GitHub Secrets:
- * SUPABASE_URL - your Supabase project URL
- * SUPABASE_SERVICE_KEY - a Supabase secret key (sb_secret_...) or the legacy service_role key
- */
+// Instagram scheduled post publisher, run by GitHub Actions every 15 minutes with no npm install.
+// Node 22.18+ runs this file directly by stripping its types; it needs SUPABASE_URL and
+// SUPABASE_SERVICE_KEY (a sb_secret_ key or the legacy service_role key) as GitHub secrets.
import type { Account, Platform, PostStatus, ScheduledPost } from '../shared/types/domain.ts';