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(api): remove the comparison, all-videos and publishing-limit routes
spacesdrive78e8b222390d
diff --git a/backend/controllers/analyticsController.ts b/backend/controllers/analyticsController.tsindex f93f7ea..68130ef 100644--- a/backend/controllers/analyticsController.ts+++ b/backend/controllers/analyticsController.ts@@ -1,9 +1,7 @@import { controller, pathParam, servicesFor } from './http.ts';import { queryParams } from '../middleware/validate.ts';-import { parseFreshQuery, parseVideoLibraryQuery } from '../validators/analyticsValidators.ts';-import type {- YouTubeAnalyticsPayload, YouTubeComparisonResponse, YouTubeLibraryResponse, YouTubeVideosResponse,-} from '../../shared/types/youtube.ts';+import { parseFreshQuery } from '../validators/analyticsValidators.ts';+import type { YouTubeAnalyticsPayload, YouTubeVideosResponse } from '../../shared/types/youtube.ts';import type { InstagramAnalyticsResponse, InstagramMediaResponse } from '../../shared/types/instagram.ts';export const getChannelAnalytics = controller.createHandlers(async c => {@@ -16,16 +14,6 @@ export const getChannelVideos = controller.createHandlers(queryParams(parseFreshreturn c.json({ success: true, ...result } satisfies YouTubeVideosResponse);});-export const getComparison = controller.createHandlers(async c => {- const comparison = await servicesFor(c).youtubeAnalytics.comparison(c.get('userId'));- return c.json({ success: true, comparison } satisfies YouTubeComparisonResponse);-});--export const getVideoLibrary = controller.createHandlers(queryParams(parseVideoLibraryQuery), async c => {- const { videos, channels } = await servicesFor(c).youtubeAnalytics.videoLibrary(c.get('userId'), c.req.valid('query'));- return c.json({ success: true, videos, total: videos.length, channels } satisfies YouTubeLibraryResponse);-});-export const getInstagramAnalytics = controller.createHandlers(async c => {const result = await servicesFor(c).instagramAnalytics.analytics(c.get('userId'), pathParam(c, 'id'));return c.json({ success: true, ...result } satisfies InstagramAnalyticsResponse);diff --git a/backend/controllers/publishingController.ts b/backend/controllers/publishingController.tsindex 95e18b4..5c12825 100644--- a/backend/controllers/publishingController.ts+++ b/backend/controllers/publishingController.ts@@ -2,7 +2,7 @@ import { controller, pathParam, servicesFor } from './http.ts';import { jsonBody, queryParams } from '../middleware/validate.ts';import { parseContainerInput, parseContainerStatusQuery, parsePublishRequest } from '../validators/publishingValidators.ts';import type {- CloudinaryConfigResponse, InstagramContainerStatusResponse, InstagramMediaPublishResponse, InstagramPublishingLimitResponse,+ CloudinaryConfigResponse, InstagramContainerStatusResponse, InstagramMediaPublishResponse,InstagramPublishResponse,} from '../../shared/types/instagram.ts';@@ -11,11 +11,6 @@ export const getCloudinaryConfig = controller.createHandlers(c => {return c.json({ success: true, cloudName, uploadPreset } satisfies CloudinaryConfigResponse);});-export const getPublishingLimit = controller.createHandlers(async c => {- const data = await servicesFor(c).publishing.publishingLimit(c.get('userId'), pathParam(c, 'id'));- return c.json({ success: true, data } satisfies InstagramPublishingLimitResponse);-});-export const createContainer = controller.createHandlers(jsonBody(parsePublishRequest), async c => {const containerId = await servicesFor(c).publishing.createContainer(c.get('userId'), pathParam(c, 'id'), c.req.valid('json'));return c.json({ success: true, containerId } satisfies InstagramPublishResponse);diff --git a/backend/routes/analyticsRoutes.ts b/backend/routes/analyticsRoutes.tsindex a1ca156..a2b2807 100644--- a/backend/routes/analyticsRoutes.ts+++ b/backend/routes/analyticsRoutes.ts@@ -1,6 +1,6 @@import { Hono } from 'hono';import {- getChannelAnalytics, getChannelVideos, getComparison, getVideoLibrary, getInstagramAnalytics, getInstagramMedia,+ getChannelAnalytics, getChannelVideos, getInstagramAnalytics, getInstagramMedia,} from '../controllers/analyticsController.ts';import type { AppEnv } from '../types/app.ts';@@ -8,8 +8,6 @@ const router = new Hono<AppEnv>();router.get('/accounts/:id/analytics', ...getChannelAnalytics);router.get('/accounts/:id/videos', ...getChannelVideos);-router.get('/comparison', ...getComparison);-router.get('/videos/all', ...getVideoLibrary);router.get('/accounts/:id/ig-analytics', ...getInstagramAnalytics);router.get('/accounts/:id/ig-media', ...getInstagramMedia);diff --git a/backend/routes/publishingRoutes.ts b/backend/routes/publishingRoutes.tsindex f8f9824..1094537 100644--- a/backend/routes/publishingRoutes.ts+++ b/backend/routes/publishingRoutes.ts@@ -1,13 +1,12 @@import { Hono } from 'hono';import {- getCloudinaryConfig, getPublishingLimit, createContainer, getContainerStatus, publishContainer,+ getCloudinaryConfig, createContainer, getContainerStatus, publishContainer,} from '../controllers/publishingController.ts';import type { AppEnv } from '../types/app.ts';const router = new Hono<AppEnv>();router.get('/cloudinary-config', ...getCloudinaryConfig);-router.get('/accounts/:id/ig-publishing-limit', ...getPublishingLimit);router.post('/accounts/:id/ig-publish', ...createContainer);router.get('/ig-container/:containerId/status', ...getContainerStatus);router.post('/accounts/:id/ig-media-publish', ...publishContainer);diff --git a/backend/services/youtube/youtubeLibrary.ts b/backend/services/youtube/youtubeLibrary.tsindex cf65c13..409f235 100644--- a/backend/services/youtube/youtubeLibrary.ts+++ b/backend/services/youtube/youtubeLibrary.ts@@ -1,15 +1,6 @@import { DAY_MS } from '../../lib/analyticsMath.ts';import type { Account } from '../../../shared/types/domain.ts';-import type { YouTubeAccountComparison, YouTubeChannelMetrics, YouTubeVideo } from '../../../shared/types/youtube.ts';--// query string values from GET /api/videos/all-export interface VideoLibraryFilters {- search?: string;- minViews?: string;- maxViews?: string;- sort?: string;- order?: string;-}+import type { YouTubeAccountComparison, YouTubeChannelMetrics } from '../../../shared/types/youtube.ts';type ComparableAccount = Pick<Account, 'subscriberCount' | 'viewCount' | 'videoCount'>;@@ -61,29 +52,3 @@ export function accountComparison<TAccount extends ComparableAccount>(accounts:bestByVideos: sorted.byVideos[0] || null,};}--function matchesSearch(video: YouTubeVideo, term: string): boolean {- return video.title?.toLowerCase().includes(term) || (video.tags || []).some(tag => tag.toLowerCase().includes(term));-}--export function filterAndSortVideos<TVideo extends YouTubeVideo>(- videos: TVideo[], { search, minViews, maxViews, sort, order }: VideoLibraryFilters,-): TVideo[] {- let result = videos;- if (search) {- const term = search.toLowerCase();- result = result.filter(video => matchesSearch(video, term));- }- if (minViews) result = result.filter(video => (video.viewCount || 0) >= parseInt(minViews));- if (maxViews) result = result.filter(video => (video.viewCount || 0) <= parseInt(maxViews));-- const sortField = sort || 'viewCount';- const sortOrder = order === 'asc' ? 1 : -1;- result.sort((first, second) => {- const firstValue = first[sortField as keyof YouTubeVideo] ?? 0;- const secondValue = second[sortField as keyof YouTubeVideo] ?? 0;- if (typeof firstValue === 'string') return sortOrder * firstValue.localeCompare(secondValue as string);- return sortOrder * ((secondValue as number) - (firstValue as number));- });- return result;-}diff --git a/backend/services/youtubeAnalyticsService.ts b/backend/services/youtubeAnalyticsService.tsindex aec1183..2ac66e5 100644--- a/backend/services/youtubeAnalyticsService.ts+++ b/backend/services/youtubeAnalyticsService.ts@@ -1,19 +1,18 @@import { fetchAllVideos } from './youtube/youtubeVideos.ts';import { fetchChannelData } from './youtube/youtubeChannels.ts';import { computeVideoAnalytics } from './youtube/youtubeAnalytics.ts';-import { channelMetrics, accountComparison, filterAndSortVideos } from './youtube/youtubeLibrary.ts';+import { channelMetrics, accountComparison } from './youtube/youtubeLibrary.ts';import { NO_YOUTUBE_KEY_MESSAGE } from './accountService.ts';import { NotConfiguredError, NotFoundError, ValidationError } from '../lib/errors.ts';import { errorFields } from '../lib/logger.ts';import { safeAccount } from '../lib/safeAccount.ts';-import type { VideoLibraryFilters } from './youtube/youtubeLibrary.ts';import type { AccountRepository } from '../repositories/accountRepository.ts';import type { AnalyticsCacheRepository } from '../repositories/analyticsCacheRepository.ts';import type { AppConfig } from '../lib/config.ts';import type { RequestContext } from '../types/context.ts';import type { Account, SafeAccount } from '../../shared/types/domain.ts';import type {- VideoAnalytics, YouTubeAccountComparison, YouTubeChannelMetrics, YouTubeLibraryChannel, YouTubeLibraryVideo, YouTubeVideo,+ VideoAnalytics, YouTubeAccountComparison, YouTubeChannelMetrics, YouTubeVideo,} from '../../shared/types/youtube.ts';export interface YouTubeAnalyticsDeps {@@ -34,20 +33,10 @@ export interface ChannelVideos {fetchedAt: string;}-export interface VideoLibraryQuery extends VideoLibraryFilters {- channelId?: string;-}--export interface VideoLibrary {- videos: YouTubeLibraryVideo[];- channels: YouTubeLibraryChannel[];-}-export interface YouTubeAnalyticsService {channelAnalytics(userId: string, accountId: string): Promise<ChannelAnalytics>;channelVideos(userId: string, accountId: string, options?: { fresh?: boolean }): Promise<ChannelVideos>;comparison(userId: string): Promise<YouTubeAccountComparison<SafeAccount> | null>;- videoLibrary(userId: string, query: VideoLibraryQuery): Promise<VideoLibrary>;}const MAX_PLAYLIST_PAGES = 10;@@ -126,25 +115,5 @@ export function createYouTubeAnalyticsService({ accounts, cache, config, contextreturn channels.length === 0 ? null : accountComparison(channels);},- // built from cached videos only; a channel that was never opened contributes nothing yet- async videoLibrary(userId, { channelId, ...filters }) {- const listed = await accounts.listForUser(userId);- const videos: YouTubeLibraryVideo[] = [];- for (const account of listed) {- if (channelId && account.id !== channelId) continue;- const cached = await cache.getVideos(userId, account.id);- if (!cached?.videos) continue;- videos.push(...cached.videos.map(video => ({- ...video,- channelTitle: account.title || video.channelTitle,- channelId: account.id,- channelThumbnail: account.thumbnails?.default || '',- })));- }- return {- videos: filterAndSortVideos(videos, filters),- channels: listed.map(account => ({ id: account.id, title: account.title })),- };- },};}diff --git a/backend/tests/fixtures/analyticsRoutes.emptyComparison.golden.json b/backend/tests/fixtures/analyticsRoutes.emptyComparison.golden.jsondeleted file mode 100644index db91d26..0000000--- a/backend/tests/fixtures/analyticsRoutes.emptyComparison.golden.json+++ /dev/null@@ -1,4 +0,0 @@-{- "status": 200,- "body": "{\"success\":true,\"comparison\":null}"-}diff --git a/backend/tests/fixtures/analyticsRoutes.youtube.golden.json b/backend/tests/fixtures/analyticsRoutes.youtube.golden.jsonindex a09e017..15a55a5 100644--- a/backend/tests/fixtures/analyticsRoutes.youtube.golden.json+++ b/backend/tests/fixtures/analyticsRoutes.youtube.golden.json@@ -1,31 +1,6 @@{"result": {"responses": [- {- "call": "GET /comparison",- "status": 200,- "body": "{\"success\":true,\"comparison\":{\"rankings\":{\"bySubscribers\":[{\"id\":\"yt2\",\"platform\":\"youtube\",\"channelId\":\"UC2\",\"uploadsPlaylistId\":\"UU2\",\"title\":\"Beta\",\"subscriberCount\":300,\"viewCount\":1000,\"videoCount\":0},{\"id\":\"yt1\",\"platform\":\"youtube\",\"channelId\":\"UC1\",\"uploadsPlaylistId\":\"UU1\",\"title\":\"Alpha\",\"subscriberCount\":100,\"viewCount\":5000,\"videoCount\":10,\"publishedAt\":\"2024-09-01T00:00:00Z\",\"thumbnails\":{\"default\":\"a.jpg\"}},{\"id\":\"yt3\",\"platform\":\"youtube\",\"channelId\":\"UC3\",\"title\":\"Gamma\"}],\"byViews\":[{\"id\":\"yt1\",\"platform\":\"youtube\",\"channelId\":\"UC1\",\"uploadsPlaylistId\":\"UU1\",\"title\":\"Alpha\",\"subscriberCount\":100,\"viewCount\":5000,\"videoCount\":10,\"publishedAt\":\"2024-09-01T00:00:00Z\",\"thumbnails\":{\"default\":\"a.jpg\"}},{\"id\":\"yt2\",\"platform\":\"youtube\",\"channelId\":\"UC2\",\"uploadsPlaylistId\":\"UU2\",\"title\":\"Beta\",\"subscriberCount\":300,\"viewCount\":1000,\"videoCount\":0},{\"id\":\"yt3\",\"platform\":\"youtube\",\"channelId\":\"UC3\",\"title\":\"Gamma\"}],\"byVideos\":[{\"id\":\"yt1\",\"platform\":\"youtube\",\"channelId\":\"UC1\",\"uploadsPlaylistId\":\"UU1\",\"title\":\"Alpha\",\"subscriberCount\":100,\"viewCount\":5000,\"videoCount\":10,\"publishedAt\":\"2024-09-01T00:00:00Z\",\"thumbnails\":{\"default\":\"a.jpg\"}},{\"id\":\"yt2\",\"platform\":\"youtube\",\"channelId\":\"UC2\",\"uploadsPlaylistId\":\"UU2\",\"title\":\"Beta\",\"subscriberCount\":300,\"viewCount\":1000,\"videoCount\":0},{\"id\":\"yt3\",\"platform\":\"youtube\",\"channelId\":\"UC3\",\"title\":\"Gamma\"}]},\"totals\":{\"subscribers\":400,\"views\":6000,\"videos\":10},\"accountCount\":3,\"bestBySubscribers\":{\"id\":\"yt2\",\"platform\":\"youtube\",\"channelId\":\"UC2\",\"uploadsPlaylistId\":\"UU2\",\"title\":\"Beta\",\"subscriberCount\":300,\"viewCount\":1000,\"videoCount\":0},\"bestByViews\":{\"id\":\"yt1\",\"platform\":\"youtube\",\"channelId\":\"UC1\",\"uploadsPlaylistId\":\"UU1\",\"title\":\"Alpha\",\"subscriberCount\":100,\"viewCount\":5000,\"videoCount\":10,\"publishedAt\":\"2024-09-01T00:00:00Z\",\"thumbnails\":{\"default\":\"a.jpg\"}},\"bestByVideos\":{\"id\":\"yt1\",\"platform\":\"youtube\",\"channelId\":\"UC1\",\"uploadsPlaylistId\":\"UU1\",\"title\":\"Alpha\",\"subscriberCount\":100,\"viewCount\":5000,\"videoCount\":10,\"publishedAt\":\"2024-09-01T00:00:00Z\",\"thumbnails\":{\"default\":\"a.jpg\"}}}}"- },- {- "call": "GET /videos/all",- "status": 200,- "body": "{\"success\":true,\"videos\":[{\"videoId\":\"b\",\"title\":\"Travel diary\",\"tags\":[\"Trip\",\"pasta\"],\"viewCount\":50,\"likeCount\":null,\"commentCount\":4,\"publishedAt\":\"2026-02-01T00:00:00Z\",\"channelTitle\":\"Alpha\",\"channelId\":\"yt1\",\"channelThumbnail\":\"a.jpg\"},{\"videoId\":\"c\",\"title\":\"Zebra facts\",\"viewCount\":300,\"likeCount\":2,\"commentCount\":1,\"publishedAt\":\"2025-12-01T00:00:00Z\",\"channelTitle\":\"Alpha\",\"channelId\":\"yt1\",\"channelThumbnail\":\"a.jpg\"},{\"videoId\":\"d\",\"title\":\"Another pasta\",\"tags\":[],\"viewCount\":300,\"likeCount\":1,\"commentCount\":1,\"publishedAt\":\"2026-03-01T00:00:00Z\",\"channelTitle\":\"Beta\",\"channelId\":\"yt2\",\"channelThumbnail\":\"\"},{\"videoId\":\"a\",\"title\":\"Cooking pasta\",\"tags\":[\"food\"],\"viewCount\":900,\"likeCount\":10,\"commentCount\":null,\"publishedAt\":\"2026-01-01T00:00:00Z\",\"channelTitle\":\"Alpha\",\"channelId\":\"yt1\",\"channelThumbnail\":\"a.jpg\"}],\"total\":4,\"channels\":[{\"id\":\"yt1\",\"title\":\"Alpha\"},{\"id\":\"yt2\",\"title\":\"Beta\"},{\"id\":\"yt3\",\"title\":\"Gamma\"},{\"id\":\"ig1\"}]}"- },- {- "call": "GET /videos/all?search=PASTA&sort=title&order=asc",- "status": 200,- "body": "{\"success\":true,\"videos\":[{\"videoId\":\"d\",\"title\":\"Another pasta\",\"tags\":[],\"viewCount\":300,\"likeCount\":1,\"commentCount\":1,\"publishedAt\":\"2026-03-01T00:00:00Z\",\"channelTitle\":\"Beta\",\"channelId\":\"yt2\",\"channelThumbnail\":\"\"},{\"videoId\":\"a\",\"title\":\"Cooking pasta\",\"tags\":[\"food\"],\"viewCount\":900,\"likeCount\":10,\"commentCount\":null,\"publishedAt\":\"2026-01-01T00:00:00Z\",\"channelTitle\":\"Alpha\",\"channelId\":\"yt1\",\"channelThumbnail\":\"a.jpg\"},{\"videoId\":\"b\",\"title\":\"Travel diary\",\"tags\":[\"Trip\",\"pasta\"],\"viewCount\":50,\"likeCount\":null,\"commentCount\":4,\"publishedAt\":\"2026-02-01T00:00:00Z\",\"channelTitle\":\"Alpha\",\"channelId\":\"yt1\",\"channelThumbnail\":\"a.jpg\"}],\"total\":3,\"channels\":[{\"id\":\"yt1\",\"title\":\"Alpha\"},{\"id\":\"yt2\",\"title\":\"Beta\"},{\"id\":\"yt3\",\"title\":\"Gamma\"},{\"id\":\"ig1\"}]}"- },- {- "call": "GET /videos/all?channelId=yt1&minViews=100&maxViews=899",- "status": 200,- "body": "{\"success\":true,\"videos\":[{\"videoId\":\"c\",\"title\":\"Zebra facts\",\"viewCount\":300,\"likeCount\":2,\"commentCount\":1,\"publishedAt\":\"2025-12-01T00:00:00Z\",\"channelTitle\":\"Alpha\",\"channelId\":\"yt1\",\"channelThumbnail\":\"a.jpg\"}],\"total\":1,\"channels\":[{\"id\":\"yt1\",\"title\":\"Alpha\"},{\"id\":\"yt2\",\"title\":\"Beta\"},{\"id\":\"yt3\",\"title\":\"Gamma\"},{\"id\":\"ig1\"}]}"- },- {- "call": "GET /videos/all?sort=likeCount",- "status": 200,- "body": "{\"success\":true,\"videos\":[{\"videoId\":\"b\",\"title\":\"Travel diary\",\"tags\":[\"Trip\",\"pasta\"],\"viewCount\":50,\"likeCount\":null,\"commentCount\":4,\"publishedAt\":\"2026-02-01T00:00:00Z\",\"channelTitle\":\"Alpha\",\"channelId\":\"yt1\",\"channelThumbnail\":\"a.jpg\"},{\"videoId\":\"d\",\"title\":\"Another pasta\",\"tags\":[],\"viewCount\":300,\"likeCount\":1,\"commentCount\":1,\"publishedAt\":\"2026-03-01T00:00:00Z\",\"channelTitle\":\"Beta\",\"channelId\":\"yt2\",\"channelThumbnail\":\"\"},{\"videoId\":\"c\",\"title\":\"Zebra facts\",\"viewCount\":300,\"likeCount\":2,\"commentCount\":1,\"publishedAt\":\"2025-12-01T00:00:00Z\",\"channelTitle\":\"Alpha\",\"channelId\":\"yt1\",\"channelThumbnail\":\"a.jpg\"},{\"videoId\":\"a\",\"title\":\"Cooking pasta\",\"tags\":[\"food\"],\"viewCount\":900,\"likeCount\":10,\"commentCount\":null,\"publishedAt\":\"2026-01-01T00:00:00Z\",\"channelTitle\":\"Alpha\",\"channelId\":\"yt1\",\"channelThumbnail\":\"a.jpg\"}],\"total\":4,\"channels\":[{\"id\":\"yt1\",\"title\":\"Alpha\"},{\"id\":\"yt2\",\"title\":\"Beta\"},{\"id\":\"yt3\",\"title\":\"Gamma\"},{\"id\":\"ig1\"}]}"- },{"call": "GET /accounts/yt1/analytics","status": 200,@@ -48,101 +23,6 @@}],"queries": [- {- "type": "select",- "table": "accounts",- "columns": "id, platform, data",- "filters": [- [- "user_id",- "user-1"- ],- [- "platform",- [- "youtube",- "instagram"- ],- "in"- ]- ]- },- {- "type": "select",- "table": "accounts",- "columns": "id, platform, data",- "filters": [- [- "user_id",- "user-1"- ],- [- "platform",- [- "youtube",- "instagram"- ],- "in"- ]- ]- },- {- "type": "select",- "table": "accounts",- "columns": "id, platform, data",- "filters": [- [- "user_id",- "user-1"- ],- [- "platform",- [- "youtube",- "instagram"- ],- "in"- ]- ]- },- {- "type": "select",- "table": "accounts",- "columns": "id, platform, data",- "filters": [- [- "user_id",- "user-1"- ],- [- "platform",- [- "youtube",- "instagram"- ],- "in"- ]- ]- },- {- "type": "select",- "table": "accounts",- "columns": "id, platform, data",- "filters": [- [- "user_id",- "user-1"- ],- [- "platform",- [- "youtube",- "instagram"- ],- "in"- ]- ]- },{"type": "select","table": "accounts",diff --git a/backend/tests/middleware/rateLimit.test.ts b/backend/tests/middleware/rateLimit.test.tsindex c9e3515..fae8756 100644--- a/backend/tests/middleware/rateLimit.test.ts+++ b/backend/tests/middleware/rateLimit.test.ts@@ -139,7 +139,7 @@ test('quota and publish routes match the endpoints that spend platform API callsconst publish = (method: string, path: string) => matchesRoute(PUBLISH_ROUTES, method, path);assert.equal(publish('POST', '/api/accounts/abc/ig-publish'), true);assert.equal(publish('POST', '/api/accounts/abc/ig-media-publish'), true);- assert.equal(publish('GET', '/api/accounts/abc/ig-publishing-limit'), false);+ assert.equal(publish('GET', '/api/accounts/abc/ig-media'), false);});test('every rule uses a different algorithm and a positive limit', () => {diff --git a/backend/tests/routes/analyticsRoutes.test.ts b/backend/tests/routes/analyticsRoutes.test.tsindex 6ce0eab..688bd25 100644--- a/backend/tests/routes/analyticsRoutes.test.ts+++ b/backend/tests/routes/analyticsRoutes.test.ts@@ -14,7 +14,7 @@ import { mountWithContext, callRoute } from '../fixtures/routeHarness.ts';import type { RouteStep } from '../fixtures/routeHarness.ts';import type { AppEnv } from '../../types/app.ts';import type { Env } from '../../types/env.ts';-import type { YouTubeAnalyticsPayload, YouTubeComparisonResponse } from '../../../shared/types/youtube.ts';+import type { YouTubeAnalyticsPayload } from '../../../shared/types/youtube.ts';import assert from 'node:assert/strict';interface StoreWrite {@@ -109,13 +109,8 @@ describe('analytics and overview routes golden output', () => {before(() => mock.timers.enable({ apis: ['Date'], now: FIXED_NOW }));after(() => mock.timers.reset());- test('channel analytics, comparison and the all videos library', async () => {+ test('channel analytics', async () => {const result = await runCalls(analyticsRouter, [- ['GET', '/comparison'],- ['GET', '/videos/all'],- ['GET', '/videos/all?search=PASTA&sort=title&order=asc'],- ['GET', '/videos/all?channelId=yt1&minViews=100&maxViews=899'],- ['GET', '/videos/all?sort=likeCount'],['GET', '/accounts/yt1/analytics'],['GET', '/accounts/yt2/analytics'],['GET', '/accounts/yt3/analytics'],@@ -169,22 +164,6 @@ describe('analytics and overview routes golden output', () => {assert.equal('isLinked' in channel, false);});- test('the comparison ranks YouTube channels only and never returns stored secrets', async () => {- const supabase = fakeSupabase(ACCOUNT_ROWS);- const app = mountWithContext(server => server.route('/', analyticsRouter), { supabase, redis: null, userId: 'user-1' });- const response = await callRoute(app, 'GET', '/comparison');- const body = JSON.parse(response.body) as YouTubeComparisonResponse;- const ranked = body.comparison!.rankings.bySubscribers;- assert.deepEqual(ranked.map(account => account.id), ['yt2', 'yt1', 'yt3']);- assert.equal(response.body.includes('"accessToken"'), false, 'accessToken leaked');- });-- test('an empty account list has no comparison', async () => {- const supabase = fakeSupabase([]);- const app = mountWithContext(server => server.route('/', analyticsRouter), { supabase, redis: null, userId: 'user-1' });- assertGolden(await callRoute(app, 'GET', '/comparison'), 'analyticsRoutes.emptyComparison');- });-test('overview summarises cached accounts and reports what cannot sync', async () => {const cached = await runCalls(overviewRouter, [['GET', '/overview']], { redis: cachedRedis() });const noRedis = await runCalls(overviewRouter, [['GET', '/overview']]);diff --git a/backend/tests/routes/publishingRoutes.test.ts b/backend/tests/routes/publishingRoutes.test.tsindex a70673e..cc23785 100644--- a/backend/tests/routes/publishingRoutes.test.ts+++ b/backend/tests/routes/publishingRoutes.test.ts@@ -35,7 +35,6 @@ async function call(method: string, path: string, json?: unknown, env = {}) {describe('publishing routes check the account before calling Instagram', () => {test('an Instagram account without a token is refused with 400 on every publishing route', async () => {const expected = failure(400, 'VALIDATION_ERROR', 'No Instagram access token stored - reconnect this account');- assert.deepEqual(await call('GET', '/accounts/igNoToken/ig-publishing-limit'), expected);assert.deepEqual(await call('POST', '/accounts/igNoToken/ig-publish', { mediaType: 'IMAGE', imageUrl: 'https://cdn/a.jpg' }), expected);assert.deepEqual(await call('POST', '/accounts/igNoToken/ig-media-publish', { containerId: 'c-1' }), expected);assert.deepEqual(await call('GET', '/ig-container/c-1/status?accountId=igNoToken'), expected);diff --git a/backend/validators/analyticsValidators.ts b/backend/validators/analyticsValidators.tsindex d32e1d5..b57c3b8 100644--- a/backend/validators/analyticsValidators.ts+++ b/backend/validators/analyticsValidators.ts@@ -1,15 +1,6 @@import { ValidationError } from '../lib/errors.ts';import { optionalString } from './fields.ts';import type { Fields } from './fields.ts';-import type { VideoLibraryQuery } from '../services/youtubeAnalyticsService.ts';--const SORT_ORDERS = ['asc', 'desc'];--function optionalCount(query: Fields, name: string): string | undefined {- const value = optionalString(query, name);- if (value && !/^\d+$/.test(value)) throw new ValidationError(`${name} must be a whole number`);- return value || undefined;-}export interface FreshQuery {fresh: boolean;@@ -22,16 +13,3 @@ export function parseFreshQuery(query: Fields): FreshQuery {return { fresh: fresh === '1' };}-// GET /api/videos/all?channelId=&search=&minViews=&maxViews=&sort=&order=-export function parseVideoLibraryQuery(query: Fields): VideoLibraryQuery {- const order = optionalString(query, 'order');- if (order && !SORT_ORDERS.includes(order)) throw new ValidationError('order must be asc or desc');- return {- channelId: optionalString(query, 'channelId') || undefined,- search: optionalString(query, 'search') || undefined,- minViews: optionalCount(query, 'minViews'),- maxViews: optionalCount(query, 'maxViews'),- sort: optionalString(query, 'sort') || undefined,- order: order || undefined,- };-}diff --git a/docs/architecture/backend/ROUTES.md b/docs/architecture/backend/ROUTES.mdindex 4d1b8b4..07a60c5 100644--- a/docs/architecture/backend/ROUTES.md+++ b/docs/architecture/backend/ROUTES.md@@ -107,10 +107,8 @@ Controllers call `YouTubeAnalyticsService` and `InstagramAnalyticsService`. Chan|---|---|---|---|| GET | `/api/accounts/:id/analytics` | `analyticsRoutes.ts`, `analyticsController.getChannelAnalytics` | Full YouTube analytics - fetches up to 500 videos, runs `computeVideoAnalytics()`, returns 50+ metrics; 404 for an account that is not a YouTube channel, 400 when no uploads playlist is stored || GET | `/api/accounts/:id/videos` | `analyticsRoutes.ts`, `analyticsController.getChannelVideos` | Returns `{ videos, fetchedAt }` from the cache when it has the channel, live otherwise; `?fresh=1` skips the cache (a person's Refresh; spends YouTube quota); the same 404 and 400 checks before a live fetch |-| GET | `/api/videos/all` | `analyticsRoutes.ts`, `analyticsController.getVideoLibrary` | Every cached video across the user's channels, filtered and sorted by `channelId`, `search`, `minViews`, `maxViews`, `sort` and `order` query parameters || GET | `/api/accounts/:id/ig-analytics` | `analyticsRoutes.ts`, `analyticsController.getInstagramAnalytics` | Instagram analytics - fetches up to 500 media with views, classifies each as reel, post, or video, runs `computeInstagramAnalytics()` || GET | `/api/accounts/:id/ig-media` | `analyticsRoutes.ts`, `analyticsController.getInstagramMedia` | Returns `{ media, fetchedAt }` (each item with `contentType` and `viewCount`) from cache, fetching live on a miss; `?fresh=1` skips the cache |-| GET | `/api/comparison` | `analyticsRoutes.ts`, `analyticsController.getComparison` | Cross-account comparison data for the Overview dashboard |### Instagram OAuth| Method | Path | File | Purpose |@@ -125,7 +123,6 @@ Controllers call `PublishingService` (`services/publishingService.ts`).| Method | Path | File | Purpose ||---|---|---|---|| GET | `/api/cloudinary-config` | `publishingRoutes.ts`, `publishingController.getCloudinaryConfig` | Returns `{ cloudName, uploadPreset }` for frontend Cloudinary upload; 503 when the Worker has no Cloudinary settings |-| GET | `/api/accounts/:id/ig-publishing-limit` | `publishingRoutes.ts`, `publishingController.getPublishingLimit` | Checks daily Instagram publishing quota remaining || POST | `/api/accounts/:id/ig-publish` | `publishingRoutes.ts`, `publishingController.createContainer` | Creates Instagram media container via Graph API; returns `{ containerId }` || GET | `/api/ig-container/:containerId/status` | `publishingRoutes.ts`, `publishingController.getContainerStatus` | Polls container status (`FINISHED`, `IN_PROGRESS`, `ERROR`, `EXPIRED`); needs `?accountId=` of an Instagram account with a token (400 or 404 otherwise) || POST | `/api/accounts/:id/ig-media-publish` | `publishingRoutes.ts`, `publishingController.publishContainer` | Publishes the container to Instagram; returns `{ mediaId }` |diff --git a/docs/architecture/backend/SERVICES.md b/docs/architecture/backend/SERVICES.mdindex 8777955..5049715 100644--- a/docs/architecture/backend/SERVICES.md+++ b/docs/architecture/backend/SERVICES.md@@ -30,9 +30,9 @@ A service receives only what it uses: repositories, the cleaned `AppConfig` from| Service (key in `Services`) | File | Repositories | Methods ||---|---|---|---|| `accounts` | `accountService.ts` | accounts, cache | `list`, `resolveChannel`, `addYouTube`, `refresh`, `refreshAll`, `remove` |-| `youtubeAnalytics` | `youtubeAnalyticsService.ts` | accounts, cache | `channelAnalytics`, `channelVideos`, `comparison`, `videoLibrary` |+| `youtubeAnalytics` | `youtubeAnalyticsService.ts` | accounts, cache | `channelAnalytics`, `channelVideos`, `comparison` (used by the MCP `compare_youtube_channels` tool) || `instagramAnalytics` | `instagramAnalyticsService.ts` | accounts, cache | `analytics`, `media` |-| `publishing` | `publishingService.ts` | accounts | `cloudinaryConfig`, `publishingLimit`, `createContainer`, `containerStatus`, `publishContainer` |+| `publishing` | `publishingService.ts` | accounts | `cloudinaryConfig`, `publishingLimit` (used by the MCP `get_instagram_publishing_limit` tool), `createContainer`, `containerStatus`, `publishContainer` || `scheduledPosts` | `scheduledPostService.ts` | accounts, scheduled posts (and the publisher) | `list`, `create`, `update`, `remove`, `removeAll`, `publishDueNow` || `scheduledPublisher` | `scheduledPublisher.ts` | accounts, scheduled posts | `publishDue` (every user's due posts; cron and manual trigger) || `tokenRefresh` | `tokenRefreshService.ts` | accounts | `refreshExpiringInstagramTokens` (daily cron) |@@ -217,7 +217,7 @@ There is no barrel: services and tests import each module directly.| `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 `YouTubeAnalyticsService`: `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`) |+| `youtubeLibrary.ts` | Pure helpers for `YouTubeAnalyticsService`: `channelMetrics` (channel age, ratios and estimates; a channel without `publishedAt` counts as 365 days old), `accountComparison` (rankings and totals for the MCP `compare_youtube_channels` tool). The app filters and sorts the video library in the browser (`frontend/src/features/analytics/videos/videoLibrary.ts`) |### Key Functionsdiff --git a/frontend/src/services/api.ts b/frontend/src/services/api.tsindex f9dfb89..08bf73e 100644--- a/frontend/src/services/api.ts+++ b/frontend/src/services/api.ts@@ -9,7 +9,7 @@ import type {} from '@shared/types/domain.ts';import type {CloudinaryConfigResponse, InstagramAnalyticsResponse, InstagramAuthUrlResponse, InstagramConnectCompleteResponse, InstagramContainerStatusResponse,- InstagramMediaPublishRequest, InstagramMediaPublishResponse, InstagramMediaResponse, InstagramPublishingLimitResponse, InstagramPublishRequest,+ InstagramMediaPublishRequest, InstagramMediaPublishResponse, InstagramMediaResponse, InstagramPublishRequest,InstagramPublishResponse,} from '@shared/types/instagram.ts';import type {@@ -18,7 +18,7 @@ import type {AutomationTestResponse,} from '@shared/types/automation.ts';import type {- ResolveChannelResponse, YouTubeAnalyticsPayload, YouTubeComparisonResponse, YouTubeVideosResponse,+ ResolveChannelResponse, YouTubeAnalyticsPayload, YouTubeVideosResponse,} from '@shared/types/youtube.ts';import type {McpAccessTokenCreateRequest, McpAccessTokenCreateResponse, McpAccessTokenListResponse, McpClientApprovalRequest,@@ -140,13 +140,10 @@ export const api = {getAnalytics: (id: string) => request<YouTubeAnalyticsPayload>(`/accounts/${id}/analytics`),getVideos: (id: string, fresh = false) => request<YouTubeVideosResponse>(`/accounts/${id}/videos${fresh ? '?fresh=1' : ''}`),- getComparison: () => request<YouTubeComparisonResponse>('/comparison'),-getCloudinaryConfig: () => request<CloudinaryConfigResponse>('/cloudinary-config'),uploadToCloudinary,// Instagram Publishing- getIGPublishingLimit: (id: string) => request<InstagramPublishingLimitResponse>(`/accounts/${id}/ig-publishing-limit`),createIGContainer: (id: string, data: InstagramPublishRequest) => request<InstagramPublishResponse>(`/accounts/${id}/ig-publish`, { method: 'POST', body: JSON.stringify(data) }),getIGContainerStatus: (containerId: string, accountId: string) => request<InstagramContainerStatusResponse>(`/ig-container/${containerId}/status?accountId=${accountId}`),publishIGContainer: (id: string, containerId: string) => request<InstagramMediaPublishResponse>(`/accounts/${id}/ig-media-publish`, { method: 'POST', body: JSON.stringify({ containerId } satisfies InstagramMediaPublishRequest) }),diff --git a/shared/types/instagram.ts b/shared/types/instagram.tsindex df2d7fc..13b5f1e 100644--- a/shared/types/instagram.ts+++ b/shared/types/instagram.ts@@ -202,11 +202,6 @@ export interface InstagramPublishingLimit {};}-export interface InstagramPublishingLimitResponse {- success: true;- data: InstagramPublishingLimit[];-}-export interface CloudinaryConfigResponse {success: true;cloudName: string;diff --git a/shared/types/youtube.ts b/shared/types/youtube.tsindex 3f9658b..544e0b6 100644--- a/shared/types/youtube.ts+++ b/shared/types/youtube.ts@@ -211,7 +211,7 @@ export interface YouTubeAccountRankings<TAccount = Account> {byVideos: TAccount[];}-// accountComparison() output, sent by GET /api/comparison+// accountComparison() output, which the MCP compare tool summarisesexport interface YouTubeAccountComparison<TAccount = Account> {rankings: YouTubeAccountRankings<TAccount>;totals: { subscribers: number; views: number; videos: number };@@ -221,12 +221,6 @@ export interface YouTubeAccountComparison<TAccount = Account> {bestByVideos: TAccount | null;}-// a cached video tagged with its channel, as GET /api/videos/all lists it-export interface YouTubeLibraryVideo extends YouTubeVideo {- channelId: string;- channelThumbnail: string;-}-// POST /api/resolve-channelexport interface ResolveChannelResponse {success: true;@@ -239,23 +233,3 @@ export interface YouTubeVideosResponse {videos: YouTubeVideo[];fetchedAt: string;}--// GET /api/comparison; comparison is null when the user has no accounts-// GET /api/comparison ranks YouTube channels only, with secrets removed by safeAccount()-export interface YouTubeComparisonResponse {- success: true;- comparison: YouTubeAccountComparison<SafeAccount> | null;-}--export interface YouTubeLibraryChannel {- id: string;- title?: string;-}--// GET /api/videos/all-export interface YouTubeLibraryResponse {- success: true;- videos: YouTubeLibraryVideo[];- total: number;- channels: YouTubeLibraryChannel[];-}diff --git a/site/src/components/mockups/bento/EdgeMock.tsx b/site/src/components/mockups/bento/EdgeMock.tsxindex 38bb70e..663a4cf 100644--- a/site/src/components/mockups/bento/EdgeMock.tsx+++ b/site/src/components/mockups/bento/EdgeMock.tsx@@ -10,10 +10,10 @@ const LOG: [string, string, number, number][] = [['GET', '/api/overview', 200, 38],['GET', '/api/accounts', 200, 21],['POST', '/api/accounts/:id/refresh', 200, 412],- ['GET', '/api/comparison', 200, 44],+ ['GET', '/api/accounts/:id/videos', 200, 44],['GET', '/api/scheduled-posts', 200, 19],['POST', '/api/tracked-content', 201, 286],- ['GET', '/api/videos/all', 200, 57],+ ['GET', '/api/automations', 200, 57],['GET', '/api/health', 200, 4],['GET', '/api/accounts/:id/analytics', 200, 96],['POST', '/api/scheduled-posts', 201, 33],