Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.
refactor(ts): type the backend routes and their responses
spacesdrivec9ddbb84b11e
diff --git a/backend/routes/accounts.ts b/backend/routes/accounts.tsindex 94ade5f..d574be9 100644--- a/backend/routes/accounts.ts+++ b/backend/routes/accounts.ts@@ -7,67 +7,87 @@ import {} from '../services/accountConnect.ts';import { refreshAccount, refreshAllAccounts } from '../services/accountRefresh.ts';import { safeAccount } from '../lib/safeAccount.ts';+import type { AppContext, AppEnv } from '../types/app.ts';+import type { ServiceFailure } from '../services/accountConnect.ts';+import type {+ AccountListResponse, AccountRefreshAllResponse, AccountResponse, SuccessResponse, YouTubeAccountAddResponse,+} from '../../shared/types/domain.ts';+import type { ResolveChannelResponse } from '../../shared/types/youtube.ts';+import type { InstagramTokenRefreshResponse } from '../../shared/types/instagram.ts';-const app = new Hono();+interface ChannelInputBody {+ input: string;+}++interface AddRedditAccountBody {+ username?: string;+ cookie?: string;+}++interface AddInstagramAccountBody {+ accessToken?: string;+}++const app = new Hono<AppEnv>();-function failureResponse(c, failure) {+function failureResponse(c: AppContext, failure: ServiceFailure) {return c.json({ success: false, message: failure.message }, failure.status);}app.get('/accounts', async (c) => {try {const accounts = await getAccounts(c.get('supabase'), c.get('userId'));- return c.json(accounts.map(safeAccount));+ return c.json(accounts.map(safeAccount) satisfies AccountListResponse);} catch (err) {- return c.json({ success: false, message: err.message }, 500);+ return c.json({ success: false, message: (err as Error).message }, 500);}});app.post('/resolve-channel', async (c) => {try {- const { input } = await c.req.json();+ const { input } = await c.req.json() as ChannelInputBody;const apiKey = c.env.YOUTUBE_API_KEY?.replace(/^\uFEFF/, '').trim();if (!apiKey) return c.json({ success: false, message: 'YouTube API key not configured on server' }, 400);const channelId = await resolveChannelId(input, apiKey);const channelData = await fetchChannelData(channelId, apiKey);- return c.json({ success: true, data: channelData });+ return c.json({ success: true, data: channelData } satisfies ResolveChannelResponse);} catch (err) {- return c.json({ success: false, message: err.message }, 400);+ return c.json({ success: false, message: (err as Error).message }, 400);}});app.post('/accounts', async (c) => {try {- const { input } = await c.req.json();+ const { input } = await c.req.json() as ChannelInputBody;const apiKey = c.env.YOUTUBE_API_KEY?.replace(/^\uFEFF/, '').trim();if (!apiKey) return c.json({ success: false, message: 'YouTube API key not configured on server' }, 400);const account = await addYouTubeAccount(c.get('supabase'), c.get('userId'), input, apiKey);- return c.json({ success: true, account });+ return c.json({ success: true, account } satisfies YouTubeAccountAddResponse);} catch (err) {- return c.json({ success: false, message: err.message }, 400);+ return c.json({ success: false, message: (err as Error).message }, 400);}});app.post('/accounts/reddit', async (c) => {try {- const { username, cookie } = await c.req.json();+ const { username, cookie } = await c.req.json() as AddRedditAccountBody;if (!username) return c.json({ success: false, message: 'Username is required' }, 400);if (!cookie) return c.json({ success: false, message: 'Session cookie is required - open reddit.com in your browser, copy the reddit_session value from DevTools (Application > Cookies > reddit.com), and paste it here' }, 400);const account = await addRedditAccount(c.get('supabase'), c.get('userId'), username, cookie);- return c.json({ success: true, account: safeAccount(account) });+ return c.json({ success: true, account: safeAccount(account) } satisfies AccountResponse);} catch (err) {- return c.json({ success: false, message: err.message }, 400);+ return c.json({ success: false, message: (err as Error).message }, 400);}});app.post('/accounts/instagram', async (c) => {try {- const { accessToken } = await c.req.json();+ const { accessToken } = await c.req.json() as AddInstagramAccountBody;if (!accessToken) return c.json({ success: false, message: 'Access token is required' }, 400);const account = await addInstagramAccount(c.get('supabase'), c.get('userId'), accessToken, c.env.INSTAGRAM_APP_SECRET);- return c.json({ success: true, account: safeAccount(account) });+ return c.json({ success: true, account: safeAccount(account) } satisfies AccountResponse);} catch (err) {- return c.json({ success: false, message: err.message }, 400);+ return c.json({ success: false, message: (err as Error).message }, 400);}});@@ -79,9 +99,9 @@ app.post('/accounts/refresh-all', async (c) => {accounts: accounts.map(safeAccount),results,updatedAt: new Date().toISOString(),- });+ } satisfies AccountRefreshAllResponse);} catch (err) {- return c.json({ success: false, message: err.message }, 500);+ return c.json({ success: false, message: (err as Error).message }, 500);}});@@ -89,9 +109,9 @@ app.post('/accounts/:id/refresh-ig-token', async (c) => {try {const outcome = await refreshInstagramToken(c.get('supabase'), c.get('userId'), c.req.param('id'));if (outcome.failure) return failureResponse(c, outcome.failure);- return c.json({ success: true, message: 'Token refreshed for another 60 days', expiresAt: outcome.expiresAt });+ return c.json({ success: true, message: 'Token refreshed for another 60 days', expiresAt: outcome.expiresAt } satisfies InstagramTokenRefreshResponse);} catch (err) {- return c.json({ success: false, message: err.message }, 400);+ return c.json({ success: false, message: (err as Error).message }, 400);}});@@ -99,9 +119,9 @@ app.post('/accounts/:id/refresh', async (c) => {try {const outcome = await refreshAccount(c.get('supabase'), c.get('userId'), c.req.param('id'), c.env.YOUTUBE_API_KEY);if (outcome.failure) return failureResponse(c, outcome.failure);- return c.json({ success: true, account: safeAccount(outcome.account) });+ return c.json({ success: true, account: safeAccount(outcome.account) } satisfies AccountResponse);} catch (err) {- return c.json({ success: false, message: err.message }, 400);+ return c.json({ success: false, message: (err as Error).message }, 400);}});@@ -119,9 +139,9 @@ app.delete('/accounts/:id', async (c) => {deleteIGCache(redis, userId, id),deleteRedditCache(redis, userId, id),]);- return c.json({ success: true });+ return c.json({ success: true } satisfies SuccessResponse);} catch (err) {- return c.json({ success: false, message: err.message }, 500);+ return c.json({ success: false, message: (err as Error).message }, 500);}});diff --git a/backend/routes/analytics.ts b/backend/routes/analytics.tsindex 60e864f..d503b15 100644--- a/backend/routes/analytics.ts+++ b/backend/routes/analytics.ts@@ -5,15 +5,35 @@ import { fetchAllVideos, computeVideoAnalytics } from '../services/youtube.ts';import { fetchInstagramProfile, fetchInstagramMedia, computeInstagramAnalytics } from '../services/instagram.ts';import { channelMetrics, accountComparison, filterAndSortVideos } from '../services/youtubeLibrary.ts';import { backfillChannelData } from '../services/accountRefresh.ts';+import type { AppEnv, Redis, SupabaseClient } from '../types/app.ts';+import type { Account } from '../../shared/types/domain.ts';+import type {+ YouTubeAnalyticsPayload, YouTubeComparisonResponse, YouTubeLibraryResponse, YouTubeLibraryVideo, YouTubeVideosResponse,+} from '../../shared/types/youtube.ts';+import type {+ InstagramAnalyticsResponse, InstagramMedia, InstagramMediaResponse, InstagramProfile,+} from '../../shared/types/instagram.ts';++interface SnapshotScope {+ supabase: SupabaseClient;+ redis: Redis | null;+ userId: string;+ id: string;+}++// no stored account has a channelTitle field, so that fallback is always undefined+type LegacyChannelAccount = Account & { channelTitle?: string };-const app = new Hono();+const app = new Hono<AppEnv>();// api errors can echo request urls that carry the api key or access token-function redactUrls(message) {+function redactUrls(message: string): string {return message.replace(/https?:\/\/[^\s)]+/g, '[url]');}-async function storeInstagramSnapshot({ supabase, redis, userId, id }, account, profile, media) {+async function storeInstagramSnapshot(+ { supabase, redis, userId, id }: SnapshotScope, account: Account, profile: InstagramProfile, media: InstagramMedia[],+): Promise<void> {await Promise.all([setIGCache(redis, userId, id, { media, fetchedAt: new Date().toISOString() }),updateAccount(supabase, account.id, {@@ -36,7 +56,7 @@ app.get('/accounts/:id/analytics', async (c) => {const account = await getAccountById(supabase, c.req.param('id'), userId);if (!account) return c.json({ success: false, message: 'Account not found' }, 404);- const videos = await fetchAllVideos(account.uploadsPlaylistId, apiKey, 10);+ const videos = await fetchAllVideos(account.uploadsPlaylistId!, apiKey, 10);await setVideosCache(c.get('redis'), userId, c.req.param('id'), { videos, fetchedAt: new Date().toISOString() });const analytics = computeVideoAnalytics(videos);@@ -47,9 +67,9 @@ app.get('/accounts/:id/analytics', async (c) => {channel: { ...account, ...channelMetrics(account) },analytics,videoCount: videos.length,- });+ } satisfies YouTubeAnalyticsPayload);} catch (err) {- return c.json({ success: false, message: redactUrls(err.message) }, 400);+ return c.json({ success: false, message: redactUrls((err as Error).message) }, 400);}});@@ -62,7 +82,7 @@ app.get('/accounts/:id/videos', async (c) => {const cached = await getVideosCache(redis, userId, id);if (cached && cached.videos) {- return c.json({ success: true, videos: cached.videos, fetchedAt: cached.fetchedAt });+ return c.json({ success: true, videos: cached.videos, fetchedAt: cached.fetchedAt } satisfies YouTubeVideosResponse);}const apiKey = c.env.YOUTUBE_API_KEY?.replace(/^\uFEFF/, '').trim();@@ -71,23 +91,23 @@ app.get('/accounts/:id/videos', async (c) => {const account = await getAccountById(supabase, id, userId);if (!account) return c.json({ success: false, message: 'Account not found' }, 404);- const videos = await fetchAllVideos(account.uploadsPlaylistId, apiKey, 10);+ const videos = await fetchAllVideos(account.uploadsPlaylistId!, apiKey, 10);const fetchedAt = new Date().toISOString();await setVideosCache(redis, userId, id, { videos, fetchedAt });- return c.json({ success: true, videos, fetchedAt });+ return c.json({ success: true, videos, fetchedAt } satisfies YouTubeVideosResponse);} catch (err) {- return c.json({ success: false, message: err.message }, 400);+ return c.json({ success: false, message: (err as Error).message }, 400);}});app.get('/comparison', async (c) => {try {const accounts = await getAccounts(c.get('supabase'), c.get('userId'));- if (accounts.length === 0) return c.json({ success: true, comparison: null });- return c.json({ success: true, comparison: accountComparison(accounts) });+ if (accounts.length === 0) return c.json({ success: true, comparison: null } satisfies YouTubeComparisonResponse);+ return c.json({ success: true, comparison: accountComparison(accounts) } satisfies YouTubeComparisonResponse);} catch (err) {- return c.json({ success: false, message: err.message }, 500);+ return c.json({ success: false, message: (err as Error).message }, 500);}});@@ -107,7 +127,7 @@ app.get('/accounts/:id/ig-analytics', async (c) => {const [profile, media] = await Promise.all([fetchInstagramProfile(account.igUserId, account.accessToken),- fetchInstagramMedia(account.igUserId, account.accessToken, 500),+ fetchInstagramMedia(account.igUserId!, account.accessToken, 500),]);await storeInstagramSnapshot({ supabase, redis: c.get('redis'), userId, id }, account, profile, media);@@ -120,9 +140,9 @@ app.get('/accounts/:id/ig-analytics', async (c) => {account: publicAccount,analytics,mediaCount: media.length,- });+ } satisfies InstagramAnalyticsResponse);} catch (err) {- return c.json({ success: false, message: redactUrls(err.message) }, 400);+ return c.json({ success: false, message: redactUrls((err as Error).message) }, 400);}});@@ -135,7 +155,7 @@ app.get('/accounts/:id/ig-media', async (c) => {const cached = await getIGCache(redis, userId, id);if (cached && cached.media) {- return c.json({ success: true, media: cached.media, fetchedAt: cached.fetchedAt });+ return c.json({ success: true, media: cached.media, fetchedAt: cached.fetchedAt } satisfies InstagramMediaResponse);}const account = await getAccountById(supabase, id, userId);@@ -146,13 +166,13 @@ app.get('/accounts/:id/ig-media', async (c) => {return c.json({ success: false, message: 'No access token' }, 400);}- const media = await fetchInstagramMedia(account.igUserId, account.accessToken, 500);+ const media = await fetchInstagramMedia(account.igUserId!, account.accessToken, 500);const fetchedAt = new Date().toISOString();await setIGCache(redis, userId, id, { media, fetchedAt });- return c.json({ success: true, media, fetchedAt });+ return c.json({ success: true, media, fetchedAt } satisfies InstagramMediaResponse);} catch (err) {- return c.json({ success: false, message: redactUrls(err.message) }, 400);+ return c.json({ success: false, message: redactUrls((err as Error).message) }, 400);}});@@ -164,14 +184,14 @@ app.get('/videos/all', async (c) => {const { channelId, sort, order, search, minViews, maxViews } = c.req.query();const accounts = await getAccounts(supabase, userId);- const allVideos = [];- for (const account of accounts) {+ const allVideos: YouTubeLibraryVideo[] = [];+ for (const account of accounts as LegacyChannelAccount[]) {if (channelId && account.id !== channelId) continue;const cached = await getVideosCache(redis, userId, account.id);if (cached && cached.videos) {allVideos.push(...cached.videos.map(video => ({...video,- channelTitle: account.title || account.channelTitle,+ channelTitle: (account.title || account.channelTitle) as string,channelId: account.id,channelThumbnail: account.thumbnails?.default || '',})));@@ -185,9 +205,9 @@ app.get('/videos/all', async (c) => {videos,total: videos.length,channels: accounts.map(account => ({ id: account.id, title: account.title })),- });+ } satisfies YouTubeLibraryResponse);} catch (err) {- return c.json({ success: false, message: err.message }, 500);+ return c.json({ success: false, message: (err as Error).message }, 500);}});diff --git a/backend/routes/instagramAuth.ts b/backend/routes/instagramAuth.tsindex 894849f..4848c6b 100644--- a/backend/routes/instagramAuth.ts+++ b/backend/routes/instagramAuth.ts@@ -2,23 +2,25 @@ import { verifyOAuthState } from '../lib/oauthState.ts';import {readInstagramOAuthConfig, buildAuthorizationUrl, connectInstagramFromOAuth,} from '../services/instagramOAuth.ts';+import type { AppContext } from '../types/app.ts';+import type { InstagramAuthUrlResponse } from '../../shared/types/instagram.ts';// GET /api/auth/instagram/url - protected; returns the frontend redirect url-export async function urlHandler(c) {+export async function urlHandler(c: AppContext) {try {const config = readInstagramOAuthConfig(c.env);if (!config.appId || !config.appSecret) {return c.json({ success: false, message: 'Instagram App credentials not configured on server' }, 500);}- return c.json({ url: await buildAuthorizationUrl(config, c.get('userId')) });+ return c.json({ url: await buildAuthorizationUrl(config, c.get('userId')) } satisfies InstagramAuthUrlResponse);} catch (err) {- console.error('Instagram URL handler error:', err.message);- return c.json({ success: false, message: 'Failed to generate auth URL: ' + err.message }, 500);+ console.error('Instagram URL handler error:', (err as Error).message);+ return c.json({ success: false, message: 'Failed to generate auth URL: ' + (err as Error).message }, 500);}}// GET /api/auth/instagram/callback - public; the signed state gives the userId-export async function callbackHandler(c) {+export async function callbackHandler(c: AppContext) {const { code, state, error, error_reason: errorReason } = c.req.query();const config = readInstagramOAuthConfig(c.env);const accountsUrl = `${config.frontendUrl}/accounts`;@@ -28,7 +30,7 @@ export async function callbackHandler(c) {return c.redirect(`${accountsUrl}?ig_error=${encodeURIComponent(reason)}`);}- const userId = await verifyOAuthState(state, config.appSecret);+ const userId = await verifyOAuthState(state, config.appSecret as string);if (!userId) {return c.redirect(`${accountsUrl}?ig_error=invalid_state`);}@@ -38,7 +40,7 @@ export async function callbackHandler(c) {if (outcome === 'already_added') return c.redirect(`${accountsUrl}?ig_error=already_added`);return c.redirect(`${accountsUrl}?ig_connected=true`);} catch (err) {- console.error('Instagram OAuth callback error:', err.message);- return c.redirect(`${accountsUrl}?ig_error=${encodeURIComponent(err.message.substring(0, 100))}`);+ console.error('Instagram OAuth callback error:', (err as Error).message);+ return c.redirect(`${accountsUrl}?ig_error=${encodeURIComponent((err as Error).message.substring(0, 100))}`);}}diff --git a/backend/routes/keys.ts b/backend/routes/keys.tsindex ecd72a9..b8b9702 100644--- a/backend/routes/keys.ts+++ b/backend/routes/keys.ts@@ -1,6 +1,8 @@import { Hono } from 'hono';+import type { AppEnv } from '../types/app.ts';+import type { KeysStatusResponse } from '../../shared/types/domain.ts';-const app = new Hono();+const app = new Hono<AppEnv>();// keys are server env vars; this only reports which are set, for the status uiapp.get('/keys', (c) => {@@ -8,7 +10,7 @@ app.get('/keys', (c) => {youtube: { configured: !!c.env.YOUTUBE_API_KEY },instagram: { configured: !!(c.env.INSTAGRAM_APP_ID && c.env.INSTAGRAM_APP_SECRET) },cloudinary: { configured: !!(c.env.CLOUDINARY_CLOUD_NAME && c.env.CLOUDINARY_UPLOAD_PRESET) },- });+ } satisfies KeysStatusResponse);});export default app;diff --git a/backend/routes/overview.ts b/backend/routes/overview.tsindex d7b39be..6aa801d 100644--- a/backend/routes/overview.ts+++ b/backend/routes/overview.ts@@ -1,11 +1,13 @@import { Hono } from 'hono';import { getAccounts, getTrackedPosts } from '../lib/db.ts';import { summarizeAccountCaches } from '../services/overviewSummary.ts';+import type { AppContext, AppEnv } from '../types/app.ts';+import type { OverviewResponse } from '../../shared/types/domain.ts';-const router = new Hono();+const router = new Hono<AppEnv>();// the client re-polls while syncing, so warming never blocks the response-function runInBackground(c, tasks) {+function runInBackground(c: AppContext, tasks: Promise<void>[]): void {if (tasks.length === 0) return;const ctx = c.executionCtx;if (ctx?.waitUntil) {@@ -28,10 +30,10 @@ router.get('/overview', async (c) => {]);const { analyticsCache, warmTasks } = await summarizeAccountCaches(accounts, { redis, userId, apiKey });runInBackground(c, warmTasks);- return c.json({ tracked, analyticsCache });+ return c.json({ tracked, analyticsCache } satisfies OverviewResponse);} catch (err) {- console.error('GET /overview:', err.message);- return c.json({ error: err.message }, 500);+ console.error('GET /overview:', (err as Error).message);+ return c.json({ error: (err as Error).message }, 500);}});diff --git a/backend/routes/publishing.ts b/backend/routes/publishing.tsindex da83154..6a2ac49 100644--- a/backend/routes/publishing.ts+++ b/backend/routes/publishing.ts@@ -1,8 +1,20 @@import { Hono } from 'hono';import { getAccountById } from '../lib/db.ts';import { buildMediaParams } from '../services/instagram.ts';+import type { AppEnv } from '../types/app.ts';+import type {+ InstagramApiContainerStatus, InstagramApiErrorBody, InstagramApiIdResponse,+} from '../services/instagram.ts';+import type {+ CloudinaryConfigResponse, InstagramContainerStatusResponse, InstagramMediaPublishRequest, InstagramMediaPublishResponse,+ InstagramPublishingLimit, InstagramPublishingLimitResponse, InstagramPublishRequest, InstagramPublishResponse,+} from '../../shared/types/instagram.ts';-const app = new Hono();+interface InstagramApiPublishingLimitBody extends InstagramApiErrorBody {+ data: InstagramPublishingLimit[];+}++const app = new Hono<AppEnv>();app.get('/cloudinary-config', (c) => {const cloudName = c.env.CLOUDINARY_CLOUD_NAME;@@ -10,7 +22,7 @@ app.get('/cloudinary-config', (c) => {if (!cloudName || !uploadPreset) {return c.json({ success: false, message: 'Cloudinary not configured on server' });}- return c.json({ success: true, cloudName, uploadPreset });+ return c.json({ success: true, cloudName, uploadPreset } satisfies CloudinaryConfigResponse);});app.get('/accounts/:id/ig-publishing-limit', async (c) => {@@ -22,11 +34,11 @@ app.get('/accounts/:id/ig-publishing-limit', async (c) => {const response = await fetch(`https://graph.instagram.com/v25.0/${acct.igUserId}/content_publishing_limit?fields=quota_usage,config&access_token=${acct.accessToken}`);- const data = await response.json();+ const data = await response.json() as InstagramApiPublishingLimitBody;if (data.error) throw new Error(data.error.message);- return c.json({ success: true, ...data });+ return c.json({ success: true, ...data } satisfies InstagramPublishingLimitResponse);} catch (err) {- return c.json({ success: false, message: err.message }, 500);+ return c.json({ success: false, message: (err as Error).message }, 500);}});@@ -38,16 +50,17 @@ app.post('/accounts/:id/ig-publish', async (c) => {}const igId = acct.igUserId;- const params = buildMediaParams(await c.req.json(), acct.accessToken);+ const params = buildMediaParams(await c.req.json() as InstagramPublishRequest, acct.accessToken!);- const query = new URLSearchParams(params).toString();+ // URLSearchParams stringifies the boolean and number values+ const query = new URLSearchParams(params as unknown as Record<string, string>).toString();const response = await fetch(`https://graph.instagram.com/v25.0/${igId}/media?${query}`, { method: 'POST' });- const data = await response.json();+ const data = await response.json() as InstagramApiIdResponse;if (data.error) throw new Error(data.error.message);- return c.json({ success: true, containerId: data.id });+ return c.json({ success: true, containerId: data.id } satisfies InstagramPublishResponse);} catch (err) {- return c.json({ success: false, message: err.message }, 500);+ return c.json({ success: false, message: (err as Error).message }, 500);}});@@ -55,18 +68,18 @@ app.get('/ig-container/:containerId/status', async (c) => {try {const containerId = c.req.param('containerId');const accountId = c.req.query('accountId');- const acct = await getAccountById(c.get('supabase'), accountId, c.get('userId'));+ const acct = await getAccountById(c.get('supabase'), accountId!, c.get('userId'));if (!acct) return c.json({ success: false, message: 'Account not found' }, 404);const response = await fetch(`https://graph.instagram.com/v25.0/${containerId}?fields=status_code,status&access_token=${acct.accessToken}`);- const data = await response.json();+ const data = await response.json() as InstagramApiContainerStatus;if (data.error) throw new Error(data.error.message);- return c.json({ success: true, statusCode: data.status_code, status: data.status });+ return c.json({ success: true, statusCode: data.status_code!, status: data.status! } satisfies InstagramContainerStatusResponse);} catch (err) {- return c.json({ success: false, message: err.message }, 500);+ return c.json({ success: false, message: (err as Error).message }, 500);}});@@ -77,17 +90,17 @@ app.post('/accounts/:id/ig-media-publish', async (c) => {return c.json({ success: false, message: 'Instagram account not found' }, 404);}- const { containerId } = await c.req.json();+ const { containerId } = await c.req.json() as InstagramMediaPublishRequest;const response = await fetch(`https://graph.instagram.com/v25.0/${acct.igUserId}/media_publish?creation_id=${containerId}&access_token=${acct.accessToken}`,{ method: 'POST' });- const data = await response.json();+ const data = await response.json() as InstagramApiIdResponse;if (data.error) throw new Error(data.error.message);- return c.json({ success: true, mediaId: data.id });+ return c.json({ success: true, mediaId: data.id } satisfies InstagramMediaPublishResponse);} catch (err) {- return c.json({ success: false, message: err.message }, 500);+ return c.json({ success: false, message: (err as Error).message }, 500);}});diff --git a/backend/routes/reddit.ts b/backend/routes/reddit.tsindex 9c13de1..d69d830 100644--- a/backend/routes/reddit.ts+++ b/backend/routes/reddit.ts@@ -2,8 +2,10 @@ import { Hono } from 'hono';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>();// Full analytics: profile + computed stats + recent postsrouter.get('/accounts/:id/reddit-analytics', async (c) => {@@ -20,17 +22,17 @@ router.get('/accounts/:id/reddit-analytics', async (c) => {if (cached) return c.json(cached);const [profile, posts] = await Promise.all([- fetchRedditProfile(account.username, account.cookie),- fetchRedditPosts(account.username, account.cookie, 100),+ fetchRedditProfile(account.username!, account.cookie),+ fetchRedditPosts(account.username!, account.cookie, 100),]);const analytics = computeRedditAnalytics(profile, posts);- const result = { profile, analytics, posts };+ const result: RedditCacheData = { profile, analytics, posts };await setRedditCache(redis, userId, id, result);return c.json(result);} 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);}});@@ -48,11 +50,11 @@ router.get('/accounts/:id/reddit-posts', async (c) => {const cached = await getRedditCache(redis, userId, id);if (cached?.posts) return c.json(cached.posts);- const posts = await fetchRedditPosts(account.username, account.cookie, 100);+ const posts = await fetchRedditPosts(account.username!, account.cookie, 100);return c.json(posts);} catch (err) {- console.error(`GET /accounts/${id}/reddit-posts:`, err.message);- return c.json({ error: err.message }, 500);+ console.error(`GET /accounts/${id}/reddit-posts:`, (err as Error).message);+ return c.json({ error: (err as Error).message }, 500);}});diff --git a/backend/routes/scheduledPosts.ts b/backend/routes/scheduledPosts.tsindex 1c148b5..5c7f278 100644--- a/backend/routes/scheduledPosts.ts+++ b/backend/routes/scheduledPosts.ts@@ -1,21 +1,28 @@import { Hono } from 'hono';import { getPosts, getPostById, createPost, updatePost, deletePost, deleteAllPosts } from '../lib/db.ts';import { generateId, processScheduledPosts } from '../utils/scheduler.ts';+import type { AppEnv } from '../types/app.ts';+import type {+ ScheduledPost, ScheduledPostDeleteAllResponse, ScheduledPostListResponse, ScheduledPostRequest, ScheduledPostResponse,+ ScheduledPostUpdateRequest, ScheduledPostUpdateResponse, ScheduledPublishRunResponse, SuccessMessageResponse,+} from '../../shared/types/domain.ts';-const app = new Hono();+type EditableField = keyof ScheduledPostUpdateRequest;++const app = new Hono<AppEnv>();app.get('/scheduled-posts', async (c) => {try {const posts = await getPosts(c.get('supabase'), c.get('userId'));- return c.json({ success: true, posts });+ return c.json({ success: true, posts } satisfies ScheduledPostListResponse);} catch (err) {- return c.json({ success: false, message: err.message }, 500);+ return c.json({ success: false, message: (err as Error).message }, 500);}});app.post('/scheduled-posts', async (c) => {try {- const body = await c.req.json();+ const body = await c.req.json() as ScheduledPostRequest;const {accountId, platform, mediaType, mediaUrl,caption, coverUrl, shareToFeed, collaborators,@@ -32,7 +39,7 @@ app.post('/scheduled-posts', async (c) => {return c.json({ success: false, message: 'scheduledAt must be a valid future date' }, 400);}- const post = {+ const post: ScheduledPost = {id: generateId(),accountId,platform: platform || 'instagram',@@ -55,9 +62,9 @@ app.post('/scheduled-posts', async (c) => {};await createPost(c.get('supabase'), post, c.get('userId'));- return c.json({ success: true, post });+ return c.json({ success: true, post } satisfies ScheduledPostResponse);} catch (err) {- return c.json({ success: false, message: err.message }, 500);+ return c.json({ success: false, message: (err as Error).message }, 500);}});@@ -68,33 +75,34 @@ app.put('/scheduled-posts/:id', async (c) => {const id = c.req.param('id');const post = await getPostById(supabase, id, userId);if (!post) return c.json({ success: false, message: 'Scheduled post not found' }, 404);- if (post.status !== 'pending' && post.status !== 'scheduled') {+ // 'scheduled' is not a PostStatus; nothing writes it, so only pending posts pass+ if (post.status !== 'pending' && (post.status as string) !== 'scheduled') {return c.json({ success: false, message: 'Can only edit pending posts' }, 400);}- const body = await c.req.json();- const allowed = ['caption', 'scheduledAt', 'shareToFeed', 'collaborators', 'audioName',+ const body = await c.req.json() as ScheduledPostUpdateRequest;+ const allowed: EditableField[] = ['caption', 'scheduledAt', 'shareToFeed', 'collaborators', 'audioName','thumbOffset', 'locationId', 'userTags', 'altText', 'coverUrl'];- const updates = {};+ const updates: Partial<ScheduledPost> = {};for (const key of allowed) {- if (body[key] !== undefined) updates[key] = body[key];+ if (body[key] !== undefined) (updates as Record<EditableField, unknown>)[key] = body[key];}if (body.scheduledAt) updates.scheduledAt = new Date(body.scheduledAt).toISOString();await updatePost(supabase, id, updates, userId);const updated = await getPostById(supabase, id, userId);- return c.json({ success: true, post: updated });+ return c.json({ success: true, post: updated } satisfies ScheduledPostUpdateResponse);} catch (err) {- return c.json({ success: false, message: err.message }, 500);+ return c.json({ success: false, message: (err as Error).message }, 500);}});app.delete('/scheduled-posts', async (c) => {try {const { deleted, kept } = await deleteAllPosts(c.get('supabase'), c.get('userId'));- return c.json({ success: true, deleted, kept });+ return c.json({ success: true, deleted, kept } satisfies ScheduledPostDeleteAllResponse);} catch (err) {- return c.json({ success: false, message: err.message }, 500);+ return c.json({ success: false, message: (err as Error).message }, 500);}});@@ -109,21 +117,21 @@ app.delete('/scheduled-posts/:id', async (c) => {return c.json({ success: false, message: 'Cannot delete a post that is currently publishing' }, 400);}await deletePost(supabase, id, userId);- return c.json({ success: true, message: 'Scheduled post deleted' });+ return c.json({ success: true, message: 'Scheduled post deleted' } satisfies SuccessMessageResponse);} catch (err) {- return c.json({ success: false, message: err.message }, 500);+ return c.json({ success: false, message: (err as Error).message }, 500);}});// Manual trigger for testingapp.get('/process-scheduled', async (c) => {const result = await processScheduledPosts(c.get('supabase'));- return c.json({ success: true, ...result, timestamp: new Date().toISOString() });+ return c.json({ success: true, ...result, timestamp: new Date().toISOString() } satisfies ScheduledPublishRunResponse);});app.post('/process-scheduled', async (c) => {const result = await processScheduledPosts(c.get('supabase'));- return c.json({ success: true, ...result, timestamp: new Date().toISOString() });+ return c.json({ success: true, ...result, timestamp: new Date().toISOString() } satisfies ScheduledPublishRunResponse);});export default app;diff --git a/backend/routes/settings.ts b/backend/routes/settings.tsindex 2bce6d4..1024ef1 100644--- a/backend/routes/settings.ts+++ b/backend/routes/settings.ts@@ -1,31 +1,33 @@import { Hono } from 'hono';import { getSettings, saveSettings } from '../lib/db.ts';+import type { AppEnv } from '../types/app.ts';+import type { GitHubSettingsRequest, GitHubSettingsResponse, SuccessResponse } from '../../shared/types/domain.ts';-const app = new Hono();+const app = new Hono<AppEnv>();app.get('/settings/github', async (c) => {const supabase = c.get('supabase');const userId = c.get('userId');const settings = await getSettings(supabase, userId);- const github = settings.github || {};+ const github = (settings.github || {}) as GitHubSettingsRequest;return c.json({configured: !!(github.pat && github.repoOwner && github.repoName),repoOwner: github.repoOwner || '',repoName: github.repoName || '',branch: github.branch || 'main',patSet: !!github.pat,- });+ } satisfies GitHubSettingsResponse);});app.put('/settings/github', async (c) => {const supabase = c.get('supabase');const userId = c.get('userId');- const { pat, repoOwner, repoName, branch } = await c.req.json();+ const { pat, repoOwner, repoName, branch } = await c.req.json() as GitHubSettingsRequest;const current = await getSettings(supabase, userId);const update = { ...current, github: { pat, repoOwner, repoName, branch: branch || 'main' } };await saveSettings(supabase, update, userId);- return c.json({ success: true });+ return c.json({ success: true } satisfies SuccessResponse);});export default app;diff --git a/backend/routes/trackedContent.ts b/backend/routes/trackedContent.tsindex 761fbdb..3aee61a 100644--- a/backend/routes/trackedContent.ts+++ b/backend/routes/trackedContent.ts@@ -11,11 +11,25 @@ import {import { fetchTrackedPostData } from '../services/reddit.ts';import { fetchTrackedYouTubeData } from '../services/youtube.ts';import { detectContentType, manualViewsPatch, imageUrlPatch } from '../services/trackedContent.ts';+import type { AppContext, AppEnv, SupabaseClient } from '../types/app.ts';+import type { TrackedPostUpdates } from '../lib/db.ts';+import type { TrackedContentType } from '../services/trackedContent.ts';+import type {+ SuccessResponse, TrackedContentAddRequest, TrackedContentListResponse, TrackedContentUpdateRequest,+} from '../../shared/types/domain.ts';+import type { RedditTrackedPostData } from '../../shared/types/reddit.ts';+import type { YouTubeTrackedVideoData } from '../../shared/types/youtube.ts';-const router = new Hono();+type TrackedData = YouTubeTrackedVideoData | RedditTrackedPostData;++type RedditCookieLookup = { cookie: string | null; isNotFound?: undefined } | { isNotFound: true; cookie?: undefined };++type TrackedDataFetch = { response: Response; data?: undefined } | { data: TrackedData; response?: undefined };++const router = new Hono<AppEnv>();// no account means no cookie; a missing or non-reddit account is not found-async function redditCookieFor(supabase, accountId, userId) {+async function redditCookieFor(supabase: SupabaseClient, accountId: string | null | undefined, userId: string): Promise<RedditCookieLookup> {if (!accountId) return { cookie: null };const account = await getAccountById(supabase, accountId, userId);if (!account || account.platform !== 'reddit') return { isNotFound: true };@@ -23,7 +37,9 @@ async function redditCookieFor(supabase, accountId, userId) {}// returns the fetched data, or an error response the handler sends unchanged-async function fetchNewTrackedData(c, contentType, url, accountId) {+async function fetchNewTrackedData(+ c: AppContext, contentType: TrackedContentType, url: string, accountId: string | null | undefined,+): Promise<TrackedDataFetch> {if (contentType === 'youtube') {const apiKey = c.env.YOUTUBE_API_KEY?.replace(/^\uFEFF/, '').trim();if (!apiKey) return { response: c.json({ error: 'YouTube API key not configured on this server' }, 400) };@@ -39,17 +55,17 @@ router.get('/tracked-content', async (c) => {const supabase = c.get('supabase');try {const items = await getTrackedPosts(supabase, userId);- return c.json(items);+ return c.json(items satisfies TrackedContentListResponse);} catch (err) {- console.error('GET /tracked-content:', err.message);- return c.json({ error: err.message }, 500);+ console.error('GET /tracked-content:', (err as Error).message);+ return c.json({ error: (err as Error).message }, 500);}});router.post('/tracked-content', 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 TrackedContentAddRequest;const { url, accountId, label, category } = body;if (!url) return c.json({ error: 'url is required' }, 400);@@ -70,13 +86,13 @@ router.post('/tracked-content', async (c) => {category,contentType,}, userId);- await updateTrackedPost(supabase, id, { data: fetched.data }, userId);+ await updateTrackedPost(supabase, id, { data: fetched.data as unknown as Record<string, unknown> }, userId);const created = await getTrackedPostById(supabase, id, userId);return c.json(created, 201);} catch (err) {- console.error('POST /tracked-content:', err.message);- return c.json({ error: err.message }, 500);+ console.error('POST /tracked-content:', (err as Error).message);+ return c.json({ error: (err as Error).message }, 500);}});@@ -85,7 +101,7 @@ router.put('/tracked-content/:id', async (c) => {const id = c.req.param('id');const userId = c.get('userId');const supabase = c.get('supabase');- const body = await c.req.json();+ const body = await c.req.json() as TrackedContentUpdateRequest;const { label, category, accountId, manualViews, imageUrl } = body;try {@@ -97,16 +113,16 @@ router.put('/tracked-content/:id', async (c) => {if (manualViews !== undefined) {const viewsResult = manualViewsPatch(manualViews, isYouTube);if (viewsResult.error) return c.json({ error: viewsResult.error }, 400);- await patchTrackedPostData(supabase, id, viewsResult.patch, userId);+ await patchTrackedPostData(supabase, id, viewsResult.patch!, userId);}if (imageUrl !== undefined) {const imageResult = imageUrlPatch(imageUrl, isYouTube);if (imageResult.error) return c.json({ error: imageResult.error }, 400);- await patchTrackedPostData(supabase, id, imageResult.patch, userId);+ await patchTrackedPostData(supabase, id, imageResult.patch!, userId);}- const updates = {};+ const updates: TrackedPostUpdates = {};if (label !== undefined) updates.label = label;if (category !== undefined) updates.category = category;if (accountId !== undefined) updates.accountId = accountId;@@ -117,8 +133,8 @@ router.put('/tracked-content/:id', async (c) => {const updated = await getTrackedPostById(supabase, id, userId);return c.json(updated);} catch (err) {- console.error(`PUT /tracked-content/${id}:`, err.message);- return c.json({ error: err.message }, 500);+ console.error(`PUT /tracked-content/${id}:`, (err as Error).message);+ return c.json({ error: (err as Error).message }, 500);}});@@ -130,10 +146,10 @@ router.delete('/tracked-content/:id', async (c) => {const existing = await getTrackedPostById(supabase, id, userId);if (!existing) return c.json({ error: 'Tracked content not found' }, 404);await deleteTrackedPost(supabase, id, userId);- return c.json({ success: true });+ return c.json({ success: true } satisfies SuccessResponse);} catch (err) {- console.error(`DELETE /tracked-content/${id}:`, err.message);- return c.json({ error: err.message }, 500);+ console.error(`DELETE /tracked-content/${id}:`, (err as Error).message);+ return c.json({ error: (err as Error).message }, 500);}});@@ -146,14 +162,14 @@ router.post('/tracked-content/:id/refresh', async (c) => {if (!existing) return c.json({ error: 'Tracked content not found' }, 404);const contentType = existing.contentType || 'reddit';- let fetchedData;+ let fetchedData: TrackedData;if (contentType === 'youtube') {const apiKey = c.env.YOUTUBE_API_KEY?.replace(/^\uFEFF/, '').trim();if (!apiKey) return c.json({ error: 'YouTube API key not configured on this server' }, 400);fetchedData = await fetchTrackedYouTubeData(existing.url, apiKey);} else {- let cookie = null;+ let cookie: string | null = null;if (existing.accountId) {const account = await getAccountById(supabase, existing.accountId, userId);cookie = account?.cookie || null;@@ -162,12 +178,12 @@ router.post('/tracked-content/:id/refresh', async (c) => {}// Patch rather than replace so a manually entered view count survives the refresh- await patchTrackedPostData(supabase, id, fetchedData, userId);+ await patchTrackedPostData(supabase, id, fetchedData as unknown as Record<string, unknown>, userId);const updated = await getTrackedPostById(supabase, id, userId);return c.json(updated);} catch (err) {- console.error(`POST /tracked-content/${id}/refresh:`, err.message);- return c.json({ error: err.message }, 500);+ console.error(`POST /tracked-content/${id}/refresh:`, (err as Error).message);+ return c.json({ error: (err as Error).message }, 500);}});diff --git a/shared/types/domain.ts b/shared/types/domain.tsindex 780a9df..90214e7 100644--- a/shared/types/domain.ts+++ b/shared/types/domain.ts@@ -1,4 +1,6 @@import type { InstagramContentTypeSummary } from './instagram.ts';+import type { RedditTrackedPostData } from './reddit.ts';+import type { YouTubeTrackedVideoData } from './youtube.ts';export type Platform = 'youtube' | 'instagram' | 'reddit';@@ -185,3 +187,166 @@ export type AccountSummary = PendingAccountSummary | RedditAccountSummary | Inst// the overview's analyticsCache, keyed by account id; accounts whose cache read failed are left outexport type OverviewAnalyticsCache = Record<string, AccountSummary>;++// GET /api/accounts+export type AccountListResponse = SafeAccount[];++// the reddit, instagram and single refresh account routes+export interface AccountResponse {+ success: true;+ account: SafeAccount;+}++// POST /api/accounts adds a youtube account, which stores no secrets, so it is sent as created+export interface YouTubeAccountAddResponse {+ success: true;+ account: NewAccount;+}++// POST /api/accounts/refresh-all+export interface AccountRefreshAllResponse {+ success: true;+ accounts: SafeAccount[];+ results: AccountRefreshResult[];+ updatedAt: string;+}++// GET /api/scheduled-posts+export interface ScheduledPostListResponse {+ success: true;+ posts: ScheduledPost[];+}++// POST /api/scheduled-posts+export interface ScheduledPostResponse {+ success: true;+ post: ScheduledPost;+}++// PUT /api/scheduled-posts/:id; post is null when the row is gone by the time it is read back+export interface ScheduledPostUpdateResponse {+ success: true;+ post: ScheduledPost | null;+}++// DELETE /api/scheduled-posts; posts that are publishing are kept+export interface ScheduledPostDeleteAllResponse {+ success: true;+ deleted: number;+ kept: number;+}++// GET and POST /api/process-scheduled+export interface ScheduledPublishRunResponse extends ScheduledPublishRun {+ success: true;+ timestamp: string;+}++// GET /api/tracked-content+export type TrackedContentListResponse = TrackedPost[];++// GET /api/overview+export interface OverviewResponse {+ tracked: TrackedPost[];+ analyticsCache: OverviewAnalyticsCache;+}++// body of PUT /api/settings/github, stored as is under settings.github+export interface GitHubSettingsRequest {+ pat?: string;+ repoOwner?: string;+ repoName?: string;+ branch?: string;+}++// GET /api/settings/github; the token itself is never sent back+export interface GitHubSettingsResponse {+ configured: boolean;+ repoOwner: string;+ repoName: string;+ branch: string;+ patSet: boolean;+}++export interface KeyStatus {+ configured: boolean;+}++// GET /api/keys reports which server secrets are set+export interface KeysStatusResponse {+ youtube: KeyStatus;+ instagram: KeyStatus;+ cloudinary: KeyStatus;+}++// the failure body most routes send; request() only passes it on when the status is 2xx+export interface ApiFailure {+ success: false;+ message: string;+}++// DELETE /api/accounts/:id, DELETE /api/tracked-content/:id and PUT /api/settings/github+export interface SuccessResponse {+ success: true;+}++// DELETE /api/scheduled-posts/:id+export interface SuccessMessageResponse {+ success: true;+ message: string;+}++// GET /api/health+export interface HealthResponse {+ status: string;+ timestamp: string;+}++// body of POST /api/scheduled-posts; the route fills in defaults for the optional fields+export interface ScheduledPostRequest {+ accountId: string;+ mediaUrl: string;+ scheduledAt: string;+ platform?: Platform;+ mediaType?: MediaType;+ caption?: string;+ coverUrl?: string | null;+ shareToFeed?: boolean;+ collaborators?: string[];+ audioName?: string;+ thumbOffset?: number | null;+ locationId?: string;+ userTags?: UserTag[];+ altText?: string;+}++// body of PUT /api/scheduled-posts/:id; any other field is ignored+export type ScheduledPostUpdateRequest = Partial<Pick<ScheduledPost,+ 'caption' | 'scheduledAt' | 'shareToFeed' | 'collaborators' | 'audioName' | 'thumbOffset' | 'locationId' | 'userTags' | 'altText' | 'coverUrl'>>;++// fields the user types in for a reddit post, kept in the data jsonb next to the fetched ones+export interface TrackedPostManualFields {+ manualViews?: number | null;+ imageUrl?: string | null;+}++// a tracked post with the fetched fields of whichever platform it tracks+export type TrackedContentItem = TrackedPost+ & Partial<RedditTrackedPostData>+ & Partial<Omit<YouTubeTrackedVideoData, 'contentType'>>+ & TrackedPostManualFields;++// body of POST /api/tracked-content+export interface TrackedContentAddRequest {+ url: string;+ accountId?: string | null;+ label?: string;+ category?: string;+}++// body of PUT /api/tracked-content/:id; null clears manualViews or imageUrl+export interface TrackedContentUpdateRequest extends TrackedPostManualFields {+ label?: string;+ category?: string;+ accountId?: string | null;+}diff --git a/shared/types/instagram.ts b/shared/types/instagram.tsindex 987d6e6..5ea5aa7 100644--- a/shared/types/instagram.ts+++ b/shared/types/instagram.ts@@ -1,4 +1,4 @@-import type { MediaType, UserTag } from './domain.ts';+import type { Account, MediaType, UserTag } from './domain.ts';import type { PostFrequency } from './reddit.ts';export type InstagramContentType = 'reel' | 'post' | 'video';@@ -212,3 +212,31 @@ export interface CloudinaryConfigResponse {cloudName: string;uploadPreset: string;}++// GET /api/accounts/:id/ig-analytics; the account is sent without its access token+export interface InstagramAnalyticsResponse {+ success: true;+ profile: InstagramProfile;+ account: Omit<Account, 'accessToken'>;+ analytics: InstagramAnalytics;+ mediaCount: number;+}++// GET /api/accounts/:id/ig-media+export interface InstagramMediaResponse {+ success: true;+ media: InstagramMedia[];+ fetchedAt: string;+}++// POST /api/accounts/:id/refresh-ig-token+export interface InstagramTokenRefreshResponse {+ success: true;+ message: string;+ expiresAt: string;+}++// GET /api/auth/instagram/url+export interface InstagramAuthUrlResponse {+ url: string;+}diff --git a/shared/types/youtube.ts b/shared/types/youtube.tsindex b6965f3..1c30ab5 100644--- a/shared/types/youtube.ts+++ b/shared/types/youtube.ts@@ -226,3 +226,35 @@ export interface YouTubeLibraryVideo extends YouTubeVideo {channelId: string;channelThumbnail: string;}++// POST /api/resolve-channel+export interface ResolveChannelResponse {+ success: true;+ data: YouTubeChannelData;+}++// GET /api/accounts/:id/videos+export interface YouTubeVideosResponse {+ success: true;+ videos: YouTubeVideo[];+ fetchedAt: string;+}++// GET /api/comparison; comparison is null when the user has no accounts+export interface YouTubeComparisonResponse {+ success: true;+ comparison: YouTubeAccountComparison | null;+}++export interface YouTubeLibraryChannel {+ id: string;+ title?: string;+}++// GET /api/videos/all+export interface YouTubeLibraryResponse {+ success: true;+ videos: YouTubeLibraryVideo[];+ total: number;+ channels: YouTubeLibraryChannel[];+}