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.

refactor(backend): flatten nesting, rename short names and trim comments

spacesdrivea91056976809
diff --git a/backend/lib/cache.js b/backend/lib/cache.js
index 0bffa1f..e0233c4 100644
--- a/backend/lib/cache.js
+++ b/backend/lib/cache.js
@@ -4,8 +4,7 @@ export { createOAuthState, verifyOAuthState } from './oauthState.js';
// stats change constantly, so cached analytics expire instead of going stale
const ANALYTICS_TTL_SECONDS = 6 * 60 * 60;
-// bump a version when the cached shape changes, so old entries read as a miss
-// v2: likeCount and commentCount are null when youtube hides them
+// bump when the cached shape changes so old entries miss (v2: hidden youtube counts are null)
const VIDEOS_CACHE_VERSION = 2;
const IG_CACHE_VERSION = 2;
diff --git a/backend/lib/crypto.js b/backend/lib/crypto.js
index 98d471c..37b30c1 100644
--- a/backend/lib/crypto.js
+++ b/backend/lib/crypto.js
@@ -1,5 +1,4 @@
-// AES-256-GCM encryption and TOTP generation using the Web Crypto API (built into Cloudflare Workers).
-// AES key is a 64-char hex string (32 bytes). Ciphertext format: "<iv_hex>:<ciphertext_hex>"
+// web crypto only, no npm dependency; the key is 64 hex chars and output is "<iv_hex>:<cipher_hex>"
function hexToBuffer(hex) {
const bytes = new Uint8Array(hex.length / 2);
@@ -17,13 +16,13 @@ async function importKey(keyHex) {
export async function encryptPassword(plaintext, keyHex) {
const key = await importKey(keyHex);
- const iv = crypto.getRandomValues(new Uint8Array(12));
+ const initVector = crypto.getRandomValues(new Uint8Array(12));
const ciphertext = await crypto.subtle.encrypt(
- { name: 'AES-GCM', iv },
+ { name: 'AES-GCM', iv: initVector },
key,
new TextEncoder().encode(plaintext)
);
- return `${bufferToHex(iv.buffer)}:${bufferToHex(ciphertext)}`;
+ return `${bufferToHex(initVector.buffer)}:${bufferToHex(ciphertext)}`;
}
export async function decryptPassword(encrypted, keyHex) {
@@ -37,8 +36,7 @@ export async function decryptPassword(encrypted, keyHex) {
return new TextDecoder().decode(plaintext);
}
-// TOTP (RFC 6238) using HMAC-SHA1 via crypto.subtle. No npm dependency.
-// base32Secret is the raw Base32 string from the authenticator app QR code.
+// totp (rfc 6238) takes the raw base32 secret from the authenticator app qr code
function base32Decode(base32) {
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
const cleaned = base32.toUpperCase().replace(/[^A-Z2-7]/g, '');
diff --git a/backend/lib/db.js b/backend/lib/db.js
index 1a4cd38..99409f1 100644
--- a/backend/lib/db.js
+++ b/backend/lib/db.js
@@ -1,22 +1,16 @@
-// All functions accept `supabase` as first argument so they work both in
-// request handlers (where supabase comes from context) and in cron handlers
-// (where supabase is created from env). userId=null means service-level
-// (no user filter) - used by the scheduler and token refresh cron.
-
-// ── Accounts ──────────────────────────────────────────────────────────────────
-
+// supabase comes first so crons can call these too; a null userId skips the user filter
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;
+ 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 }));
}
export async function getAccountById(supabase, id, userId = null) {
- let q = supabase.from('accounts').select('id, platform, data').eq('id', id);
- if (userId) q = q.eq('user_id', userId);
- const { data, error } = await q.single();
+ let query = supabase.from('accounts').select('id, platform, data').eq('id', id);
+ if (userId) query = query.eq('user_id', userId);
+ const { data, error } = await query.single();
if (error || !data) return null;
return { id: data.id, platform: data.platform, ...data.data };
}
@@ -34,25 +28,23 @@ export async function updateAccount(supabase, id, updates, userId = null) {
if (!current) throw new Error('Account not found: ' + id);
const { id: _, platform: currentPlatform, ...currentData } = current;
const { platform: newPlatform, ...dataUpdates } = updates;
- let q = supabase.from('accounts').update({
+ let query = supabase.from('accounts').update({
platform: newPlatform || currentPlatform,
data: { ...currentData, ...dataUpdates },
}).eq('id', id);
- if (userId) q = q.eq('user_id', userId);
- const { error } = await q;
+ if (userId) query = query.eq('user_id', userId);
+ const { error } = await query;
if (error) throw error;
}
export async function deleteAccount(supabase, id, userId = null) {
- let q = supabase.from('accounts').delete().eq('id', id);
- if (userId) q = q.eq('user_id', userId);
- const { error } = await q;
+ let query = supabase.from('accounts').delete().eq('id', id);
+ if (userId) query = query.eq('user_id', userId);
+ const { error } = await query;
if (error) throw error;
}
-// ── Settings (API Keys) ───────────────────────────────────────────────────────
-// Table: settings (user_id uuid, key text, value jsonb) - PK is (user_id, key)
-
+// settings rows are keyed by (user_id, key); every saved value lives under 'api_keys'
const DEFAULT_KEYS = {};
export async function getSettings(supabase, userId) {
@@ -73,8 +65,6 @@ export async function saveSettings(supabase, keys, userId) {
if (error) throw error;
}
-// ── Scheduled Posts ───────────────────────────────────────────────────────────
-
function rowToPost(row) {
return {
id: row.id,
@@ -86,23 +76,23 @@ function rowToPost(row) {
}
export async function getPosts(supabase, userId) {
- let q = supabase
+ let query = supabase
.from('scheduled_posts')
.select('id, account_id, status, scheduled_at, data')
.order('scheduled_at', { ascending: true });
- if (userId) q = q.eq('user_id', userId);
- const { data, error } = await q;
+ if (userId) query = query.eq('user_id', userId);
+ const { data, error } = await query;
if (error) throw error;
return (data || []).map(rowToPost);
}
export async function getPostById(supabase, id, userId = null) {
- let q = supabase
+ let query = supabase
.from('scheduled_posts')
.select('id, account_id, status, scheduled_at, data')
.eq('id', id);
- if (userId) q = q.eq('user_id', userId);
- const { data, error } = await q.single();
+ if (userId) query = query.eq('user_id', userId);
+ const { data, error } = await query.single();
if (error || !data) return null;
return rowToPost(data);
}
@@ -117,8 +107,7 @@ export async function getDuePosts(supabase) {
return (data || []).map(rowToPost);
}
-// Atomically moves a due post from pending to publishing. Returns false when another scheduler
-// (the Worker cron or the GitHub Actions workflow) already claimed it.
+// atomic pending to publishing; false means the worker cron or the github workflow got it first
export async function claimPost(supabase, id) {
const { data, error } = await supabase
.from('scheduled_posts')
@@ -151,23 +140,23 @@ export async function updatePost(supabase, id, updates, userId = null) {
if (scheduledAt !== undefined) colUpdates.scheduled_at = scheduledAt;
if (Object.keys(dataUpdates).length > 0) {
- let q = supabase.from('scheduled_posts').select('data').eq('id', id);
- if (userId) q = q.eq('user_id', userId);
- const { data: rows } = await q;
+ let readQuery = supabase.from('scheduled_posts').select('data').eq('id', id);
+ if (userId) readQuery = readQuery.eq('user_id', userId);
+ const { data: rows } = await readQuery;
const currentData = rows?.[0]?.data || {};
colUpdates.data = { ...currentData, ...dataUpdates };
}
- let q = supabase.from('scheduled_posts').update(colUpdates).eq('id', id);
- if (userId) q = q.eq('user_id', userId);
- const { error } = await q;
+ let query = supabase.from('scheduled_posts').update(colUpdates).eq('id', id);
+ if (userId) query = query.eq('user_id', userId);
+ const { error } = await query;
if (error) throw error;
}
export async function deletePost(supabase, id, userId = null) {
- let q = supabase.from('scheduled_posts').delete().eq('id', id);
- if (userId) q = q.eq('user_id', userId);
- const { error } = await q;
+ let query = supabase.from('scheduled_posts').delete().eq('id', id);
+ if (userId) query = query.eq('user_id', userId);
+ const { error } = await query;
if (error) throw error;
}
@@ -189,8 +178,6 @@ export async function deleteAllPosts(supabase, userId) {
return { deleted: (total || 0) - (keeping || 0), kept: keeping || 0 };
}
-// ── Tracked Posts ─────────────────────────────────────────────────────────────
-
function rowToTrackedPost(row) {
return {
id: row.id,
@@ -254,8 +241,7 @@ export async function updateTrackedPost(supabase, id, updates, userId) {
if (error) throw error;
}
-// Merges keys into the data jsonb instead of replacing it, so manually entered
-// fields survive a live refresh and vice versa
+// merges into data instead of replacing it, so manual fields survive a live refresh and vice versa
export async function patchTrackedPostData(supabase, id, patch, userId) {
const { data: row, error: readError } = await supabase
.from('tracked_posts')
diff --git a/backend/lib/safeAccount.js b/backend/lib/safeAccount.js
index aa40e7c..4d8e3fc 100644
--- a/backend/lib/safeAccount.js
+++ b/backend/lib/safeAccount.js
@@ -1,5 +1,4 @@
-// Removes every credential from an account before it leaves the Worker. hasCookie lets the
-// frontend show Reddit session status without ever receiving the cookie itself.
+// hasCookie lets the frontend show reddit session status without ever receiving the cookie
const SECRET_FIELDS = ['accessToken', 'cookie', 'encryptedPassword', 'encryptedTotpSecret', 'authToken', 'ct0'];
export function safeAccount(account) {
diff --git a/backend/lib/supabase.js b/backend/lib/supabase.js
index f4328d4..17f93da 100644
--- a/backend/lib/supabase.js
+++ b/backend/lib/supabase.js
@@ -4,8 +4,7 @@ function clean(s) {
return s?.replace(/^/, '').trim();
}
-// Cloudflare Workers does not support the `cache` field on RequestInit.
-// Strip it from all fetch calls made by the Supabase client.
+// workers reject the `cache` field on RequestInit, so it is dropped from supabase requests
function workerFetch(url, options = {}) {
const { cache, ...rest } = options;
return fetch(url, rest);
diff --git a/backend/routes/analytics.js b/backend/routes/analytics.js
index 3d0bd6f..52a3129 100644
--- a/backend/routes/analytics.js
+++ b/backend/routes/analytics.js
@@ -1,8 +1,10 @@
import { Hono } from 'hono';
import { getAccounts, getAccountById, updateAccount } from '../lib/db.js';
import { getVideosCache, setVideosCache, getIGCache, setIGCache } from '../lib/cache.js';
-import { fetchAllVideos, fetchChannelData, computeVideoAnalytics } from '../services/youtube.js';
+import { fetchAllVideos, computeVideoAnalytics } from '../services/youtube.js';
import { fetchInstagramProfile, fetchInstagramMedia, computeInstagramAnalytics } from '../services/instagram.js';
+import { channelMetrics, accountComparison, filterAndSortVideos } from '../services/youtubeLibrary.js';
+import { backfillChannelData } from '../services/accountRefresh.js';
const app = new Hono();
@@ -20,51 +22,11 @@ app.get('/accounts/:id/analytics', async (c) => {
await setVideosCache(c.get('redis'), userId, c.req.param('id'), { videos, fetchedAt: new Date().toISOString() });
const analytics = computeVideoAnalytics(videos);
- if (!account.publishedAt) {
- try {
- const channelData = await fetchChannelData(account.channelId, apiKey);
- await updateAccount(supabase, account.id, {
- publishedAt: channelData.publishedAt,
- subscriberCount: channelData.subscriberCount,
- viewCount: channelData.viewCount,
- videoCount: channelData.videoCount,
- title: channelData.title,
- thumbnails: channelData.thumbnails,
- customUrl: channelData.customUrl,
- country: channelData.country,
- lastUpdated: new Date().toISOString(),
- }, userId);
- Object.assign(account, channelData);
- } catch (e) {
- console.error('Failed to backfill channel data:', e.message);
- }
- }
-
- const channelAge = account.publishedAt
- ? Math.floor((Date.now() - new Date(account.publishedAt).getTime()) / 86400000)
- : 365;
- const viewsPerSub = account.subscriberCount > 0 ? (account.viewCount / account.subscriberCount).toFixed(1) : 0;
- const subsPerView = account.viewCount > 0 ? (account.subscriberCount / account.viewCount * 100).toFixed(4) : 0;
- const avgViewsPerVideo = account.videoCount > 0 ? Math.round(account.viewCount / account.videoCount) : 0;
- const avgSubGainPerDay = channelAge > 0 ? Math.round(account.subscriberCount / channelAge) : 0;
- const avgViewsPerDay = channelAge > 0 ? Math.round(account.viewCount / channelAge) : 0;
+ if (!account.publishedAt) await backfillChannelData(supabase, account, apiKey, userId);
return c.json({
success: true,
- channel: {
- ...account,
- channelAge,
- channelAgeYears: (channelAge / 365).toFixed(1),
- viewsPerSubscriber: parseFloat(viewsPerSub),
- subscriberToViewRatio: parseFloat(subsPerView),
- avgViewsPerVideo,
- avgSubGainPerDay,
- avgViewsPerDay,
- estimatedMonthlyViews: avgViewsPerDay * 30,
- estimatedMonthlySubGain: avgSubGainPerDay * 30,
- estimatedYearlyViews: avgViewsPerDay * 365,
- estimatedYearlySubGain: avgSubGainPerDay * 365,
- },
+ channel: { ...account, ...channelMetrics(account) },
analytics,
videoCount: videos.length,
});
@@ -106,30 +68,7 @@ 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 });
-
- const sorted = {
- bySubscribers: [...accounts].sort((a, b) => b.subscriberCount - a.subscriberCount),
- byViews: [...accounts].sort((a, b) => b.viewCount - a.viewCount),
- byVideos: [...accounts].sort((a, b) => b.videoCount - a.videoCount),
- };
-
- const totals = accounts.reduce((acc, a) => ({
- subscribers: acc.subscribers + (a.subscriberCount || 0),
- views: acc.views + (a.viewCount || 0),
- videos: acc.videos + (a.videoCount || 0),
- }), { subscribers: 0, views: 0, videos: 0 });
-
- return c.json({
- success: true,
- comparison: {
- rankings: sorted,
- totals,
- accountCount: accounts.length,
- bestBySubscribers: sorted.bySubscribers[0] || null,
- bestByViews: sorted.byViews[0] || null,
- bestByVideos: sorted.byVideos[0] || null,
- },
- });
+ return c.json({ success: true, comparison: accountComparison(accounts) });
} catch (err) {
return c.json({ success: false, message: err.message }, 500);
}
@@ -221,7 +160,7 @@ app.get('/videos/all', async (c) => {
const { channelId, sort, order, search, minViews, maxViews } = c.req.query();
const accounts = await getAccounts(supabase, userId);
- let allVideos = [];
+ const allVideos = [];
for (const acct of accounts) {
if (channelId && acct.id !== channelId) continue;
const cached = await getVideosCache(redis, userId, acct.id);
@@ -235,29 +174,12 @@ app.get('/videos/all', async (c) => {
}
}
- if (search) {
- const q = search.toLowerCase();
- allVideos = allVideos.filter(v =>
- v.title?.toLowerCase().includes(q) ||
- (v.tags || []).some(t => t.toLowerCase().includes(q))
- );
- }
- if (minViews) allVideos = allVideos.filter(v => (v.viewCount || 0) >= parseInt(minViews));
- if (maxViews) allVideos = allVideos.filter(v => (v.viewCount || 0) <= parseInt(maxViews));
-
- const sortField = sort || 'viewCount';
- const sortOrder = order === 'asc' ? 1 : -1;
- allVideos.sort((a, b) => {
- const aVal = a[sortField] ?? 0;
- const bVal = b[sortField] ?? 0;
- if (typeof aVal === 'string') return sortOrder * aVal.localeCompare(bVal);
- return sortOrder * (bVal - aVal);
- });
+ const videos = filterAndSortVideos(allVideos, { search, minViews, maxViews, sort, order });
return c.json({
success: true,
- videos: allVideos,
- total: allVideos.length,
+ videos,
+ total: videos.length,
channels: accounts.map(a => ({ id: a.id, title: a.title })),
});
} catch (err) {
diff --git a/backend/routes/analytics.test.js b/backend/routes/analytics.test.js
new file mode 100644
index 0000000..6fef3f1
--- /dev/null
+++ b/backend/routes/analytics.test.js
@@ -0,0 +1,131 @@
+// keeps node's experimental mock timer warning out of the captured console output
+process.removeAllListeners('warning');
+
+import { test, describe, before, after, afterEach, mock } from 'node:test';
+import analyticsRouter from './analytics.js';
+import overviewRouter from './overview.js';
+import { assertGolden } from '../services/fixtures/golden.js';
+import { installFetch, reply } from '../services/fixtures/fakeFetch.js';
+import { fakeSupabase, accountRow, tableRow } from '../services/fixtures/fakeSupabase.js';
+import { mountWithContext, callRoute } from '../services/fixtures/routeHarness.js';
+
+const FIXED_NOW = Date.parse('2026-09-01T12:00:00Z');
+const ENV = { YOUTUBE_API_KEY: 'YTKEY' };
+
+const ACCOUNT_ROWS = [
+ accountRow({ 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' } }),
+ accountRow({ id: 'yt2', platform: 'youtube', channelId: 'UC2', uploadsPlaylistId: 'UU2', title: 'Beta', subscriberCount: 300, viewCount: 1000, videoCount: 0 }),
+ accountRow({ id: 'yt3', platform: 'youtube', channelId: 'UC3', title: 'Gamma' }),
+ accountRow({ id: 'ig1', platform: 'instagram', igUserId: 'IG1', accessToken: 'T1', username: 'ribbon' }),
+ accountRow({ id: 'rd1', platform: 'reddit', username: 'ribbon', cookie: 'COOKIE' }),
+ accountRow({ id: 'rd2', platform: 'reddit', username: 'nocookie' }),
+];
+
+const ROWS = [
+ ...ACCOUNT_ROWS.map(row => tableRow('accounts', row)),
+ tableRow('tracked_posts', { id: 't1', user_id: 'user-1', account_id: null, url: 'https://youtu.be/x', label: '', category: '', content_type: 'youtube', created_at: '2026-08-01T00:00:00Z', updated_at: '2026-08-01T00:00:00Z', data: { title: 'Tracked' } }),
+];
+
+const CACHED_VIDEOS = {
+ yt1: [
+ { videoId: 'a', title: 'Cooking pasta', tags: ['food'], viewCount: 900, likeCount: 10, commentCount: null, publishedAt: '2026-01-01T00:00:00Z' },
+ { videoId: 'b', title: 'Travel diary', tags: ['Trip', 'pasta'], viewCount: 50, likeCount: null, commentCount: 4, publishedAt: '2026-02-01T00:00:00Z' },
+ { videoId: 'c', title: 'Zebra facts', viewCount: 300, likeCount: 2, commentCount: 1, publishedAt: '2025-12-01T00:00:00Z' },
+ ],
+ yt2: [{ videoId: 'd', title: 'Another pasta', tags: [], viewCount: 300, likeCount: 1, commentCount: 1, publishedAt: '2026-03-01T00:00:00Z' }],
+};
+
+function cachedRedis() {
+ const store = {
+ 'videos:user-1:yt1': { videos: CACHED_VIDEOS.yt1, fetchedAt: 'then', version: 2 },
+ 'videos:user-1:yt2': { videos: CACHED_VIDEOS.yt2, fetchedAt: 'then', version: 2 },
+ 'ig:user-1:ig1': { media: [{ id: 'm1', contentType: 'reel', likeCount: 5, commentsCount: 2, viewCount: 90 }, { id: 'm2', contentType: 'post', likeCount: 1, commentsCount: 0, viewCount: null }], version: 2 },
+ 'reddit:user-1:rd1': { analytics: { fetchedPosts: 4, totalScore: 40 } },
+ };
+ return fakeStore(store);
+}
+
+function fakeStore(store) {
+ const writes = [];
+ return {
+ writes,
+ async get(key) { return store[key] ?? null; },
+ async set(key, value, options) { writes.push({ key, options, version: value.version }); store[key] = value; },
+ };
+}
+
+function youtubeReply(request) {
+ const url = new URL(request.url);
+ const endpoint = url.pathname.split('/').pop();
+ if (endpoint === 'playlistItems') return reply({ items: [{ snippet: { resourceId: { videoId: 'v1' } } }] });
+ if (endpoint === 'videos') {
+ return reply({ items: [{ id: 'v1', snippet: { title: 'Fresh', publishedAt: '2026-08-20T10:00:00Z', channelTitle: 'Gamma' }, contentDetails: { duration: 'PT45S' }, statistics: { viewCount: '70', likeCount: '7', commentCount: '1' } }] });
+ }
+ if (endpoint === 'channels' && url.searchParams.get('id') === 'UC3') {
+ return reply({ items: [{ id: 'UC3', snippet: { title: 'Gamma', customUrl: '@gamma', publishedAt: '2025-09-01T00:00:00Z', thumbnails: {} }, statistics: { subscriberCount: '20', viewCount: '400', videoCount: '2' }, contentDetails: { relatedPlaylists: { uploads: 'UU3' } } }] });
+ }
+ return reply({ error: { message: 'Channel lookup failed', errors: [{ reason: 'notFound' }], code: 404 } });
+}
+
+let fetchMock = null;
+afterEach(() => fetchMock?.restore());
+
+async function runCalls(router, calls, { redis = null, env = ENV } = {}) {
+ const supabase = fakeSupabase(ROWS);
+ const app = mountWithContext(server => server.route('/', router), { supabase, redis, userId: 'user-1' });
+ fetchMock = installFetch(youtubeReply);
+ const logLines = [];
+ mock.method(console, 'error', (...args) => logLines.push(['error', ...args]));
+ const responses = [];
+ for (const [method, path] of calls) {
+ responses.push({ call: `${method} ${path}`, ...(await callRoute(app, method, path, { env })) });
+ }
+ console.error.mock.restore();
+ return { responses, queries: supabase.calls, requests: fetchMock.requests, logLines, redisWrites: redis?.writes ?? null };
+}
+
+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 () => {
+ 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'],
+ ['GET', '/accounts/missing/analytics'],
+ ], { redis: cachedRedis() });
+ const withoutKey = await runCalls(analyticsRouter, [['GET', '/accounts/yt1/analytics']], { env: {} });
+ assertGolden({ result, withoutKey }, 'analyticsRoutes.youtube');
+ });
+
+ 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']]);
+ assertGolden({ cached, noRedis }, 'overviewRoutes.summary');
+ });
+
+ test('overview warms missing caches in the background', async () => {
+ const supabase = fakeSupabase(ROWS);
+ const redis = fakeStore({});
+ const app = mountWithContext(server => server.route('/', overviewRouter), { supabase, redis, userId: 'user-1' });
+ fetchMock = installFetch(() => reply({}));
+ const background = [];
+ const executionCtx = { waitUntil: promise => background.push(promise), passThroughOnException() {} };
+ const response = await app.request('/overview', { method: 'GET' }, ENV, executionCtx);
+ const body = await response.text();
+ const settled = await Promise.all(background);
+ assertGolden({ status: response.status, body, waitUntilCalls: background.length, settled, requests: fetchMock.requests, redisWrites: redis.writes }, 'overviewRoutes.warming');
+ });
+});
diff --git a/backend/routes/keys.js b/backend/routes/keys.js
index 92138fc..d7bd4dc 100644
--- a/backend/routes/keys.js
+++ b/backend/routes/keys.js
@@ -2,8 +2,7 @@ import { Hono } from 'hono';
const app = new Hono();
-// All API keys (YouTube, Instagram, Cloudinary) are server env vars.
-// This route returns a status object so the frontend can confirm the backend is reachable.
+// keys are server env vars; this only reports which are set, so the frontend can show status
app.get('/keys', (c) => {
return c.json({
youtube: { configured: !!c.env.YOUTUBE_API_KEY },
diff --git a/backend/routes/overview.js b/backend/routes/overview.js
index f6c9941..d470af4 100644
--- a/backend/routes/overview.js
+++ b/backend/routes/overview.js
@@ -7,6 +7,17 @@ import { fetchRedditProfile, fetchRedditPosts, computeRedditAnalytics } from '..
const router = new Hono();
+// the client re-polls while any account reports syncing, so warming never blocks the response
+function runInBackground(c, tasks) {
+ if (tasks.length === 0) return;
+ const ctx = c.executionCtx;
+ if (ctx?.waitUntil) {
+ ctx.waitUntil(Promise.allSettled(tasks));
+ return;
+ }
+ Promise.allSettled(tasks).catch(() => {});
+}
+
router.get('/overview', async (c) => {
const userId = c.get('userId');
const supabase = c.get('supabase');
@@ -20,8 +31,7 @@ router.get('/overview', async (c) => {
]);
const warmTasks = [];
- // Starts a background fetch and reports syncing: true only when one actually started, so the
- // client never waits on an account that cannot be fetched (no Redis, no key, no cookie).
+ // syncing is true only when a fetch started, so the client never waits on an unfetchable account
const warm = (id, task) => {
if (!redis || !task) return { id, cacheWarmed: false, syncing: false };
warmTasks.push(task().catch(() => {}));
@@ -87,15 +97,7 @@ router.get('/overview', async (c) => {
})
);
- // Fire warming tasks without blocking the response; the client re-polls while any account reports syncing.
- if (warmTasks.length > 0) {
- const ctx = c.executionCtx;
- if (ctx?.waitUntil) {
- ctx.waitUntil(Promise.allSettled(warmTasks));
- } else {
- Promise.allSettled(warmTasks).catch(() => {});
- }
- }
+ runInBackground(c, warmTasks);
const analyticsCache = {};
cacheResults.forEach(r => {
diff --git a/backend/routes/publishing.js b/backend/routes/publishing.js
index 1c25cca..d7b0c4c 100644
--- a/backend/routes/publishing.js
+++ b/backend/routes/publishing.js
@@ -19,10 +19,10 @@ app.get('/accounts/:id/ig-publishing-limit', async (c) => {
if (!acct || acct.platform !== 'instagram') {
return c.json({ success: false, message: 'Instagram account not found' }, 404);
}
- const r = await fetch(
+ 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 r.json();
+ const data = await response.json();
if (data.error) throw new Error(data.error.message);
return c.json({ success: true, ...data });
} catch (err) {
@@ -40,9 +40,9 @@ app.post('/accounts/:id/ig-publish', async (c) => {
const igId = acct.igUserId;
const params = buildMediaParams(await c.req.json(), acct.accessToken);
- const qs = new URLSearchParams(params).toString();
- const r = await fetch(`https://graph.instagram.com/v25.0/${igId}/media?${qs}`, { method: 'POST' });
- const data = await r.json();
+ const query = new URLSearchParams(params).toString();
+ const response = await fetch(`https://graph.instagram.com/v25.0/${igId}/media?${query}`, { method: 'POST' });
+ const data = await response.json();
if (data.error) throw new Error(data.error.message);
return c.json({ success: true, containerId: data.id });
@@ -58,10 +58,10 @@ app.get('/ig-container/:containerId/status', async (c) => {
const acct = await getAccountById(c.get('supabase'), accountId, c.get('userId'));
if (!acct) return c.json({ success: false, message: 'Account not found' }, 404);
- const r = await fetch(
+ const response = await fetch(
`https://graph.instagram.com/v25.0/${containerId}?fields=status_code,status&access_token=${acct.accessToken}`
);
- const data = await r.json();
+ const data = await response.json();
if (data.error) throw new Error(data.error.message);
return c.json({ success: true, statusCode: data.status_code, status: data.status });
@@ -78,11 +78,11 @@ app.post('/accounts/:id/ig-media-publish', async (c) => {
}
const { containerId } = await c.req.json();
- const r = await fetch(
+ 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 r.json();
+ const data = await response.json();
if (data.error) throw new Error(data.error.message);
return c.json({ success: true, mediaId: data.id });
diff --git a/backend/routes/settings.js b/backend/routes/settings.js
index c13a350..2e3e475 100644
--- a/backend/routes/settings.js
+++ b/backend/routes/settings.js
@@ -7,13 +7,13 @@ app.get('/settings/github', async (c) => {
const supabase = c.get('supabase');
const userId = c.get('userId');
const settings = await getSettings(supabase, userId);
- const gh = settings.github || {};
+ const github = settings.github || {};
return c.json({
- configured: !!(gh.pat && gh.repoOwner && gh.repoName),
- repoOwner: gh.repoOwner || '',
- repoName: gh.repoName || '',
- branch: gh.branch || 'main',
- patSet: !!gh.pat,
+ configured: !!(github.pat && github.repoOwner && github.repoName),
+ repoOwner: github.repoOwner || '',
+ repoName: github.repoName || '',
+ branch: github.branch || 'main',
+ patSet: !!github.pat,
});
});
diff --git a/backend/routes/trackedContent.js b/backend/routes/trackedContent.js
index 1430d48..3fc802b 100644
--- a/backend/routes/trackedContent.js
+++ b/backend/routes/trackedContent.js
@@ -10,14 +10,16 @@ import {
} from '../lib/db.js';
import { fetchTrackedPostData } from '../services/reddit.js';
import { fetchTrackedYouTubeData } from '../services/youtube.js';
+import { detectContentType, manualViewsPatch, imageUrlPatch } from '../services/trackedContent.js';
const router = new Hono();
-function detectContentType(url) {
- const lower = (url || '').toLowerCase();
- if (lower.includes('reddit.com') || lower.includes('redd.it')) return 'reddit';
- if (lower.includes('youtube.com') || lower.includes('youtu.be')) return 'youtube';
- return null;
+// no account means no cookie; a missing or non-reddit account is reported as not found
+async function redditCookieFor(supabase, accountId, userId) {
+ if (!accountId) return { cookie: null };
+ const account = await getAccountById(supabase, accountId, userId);
+ if (!account || account.platform !== 'reddit') return { notFound: true };
+ return { cookie: account.cookie || null };
}
// List all tracked content for the current user
@@ -53,13 +55,9 @@ router.post('/tracked-content', async (c) => {
if (!apiKey) return c.json({ error: 'YouTube API key not configured on this server' }, 400);
fetchedData = await fetchTrackedYouTubeData(url.trim(), apiKey);
} else {
- let cookie = null;
- if (accountId) {
- const account = await getAccountById(supabase, accountId, userId);
- if (!account || account.platform !== 'reddit') return c.json({ error: 'Reddit account not found' }, 404);
- cookie = account.cookie || null;
- }
- fetchedData = await fetchTrackedPostData(url.trim(), cookie);
+ const reddit = await redditCookieFor(supabase, accountId, userId);
+ if (reddit.notFound) return c.json({ error: 'Reddit account not found' }, 404);
+ fetchedData = await fetchTrackedPostData(url.trim(), reddit.cookie);
}
const id = Date.now().toString(36) + Math.random().toString(36).slice(2);
@@ -95,42 +93,16 @@ router.put('/tracked-content/:id', async (c) => {
const isYouTube = (existing.contentType || 'reddit') === 'youtube';
- // Reddit removed view_count from their API in 2018, so views can only be entered by hand.
- // YouTube returns a real view count, so accepting a manual one would silently override it.
if (manualViews !== undefined) {
- if (isYouTube) {
- return c.json({ error: 'YouTube view counts are fetched automatically and cannot be set by hand' }, 400);
- }
- if (manualViews === null || manualViews === '') {
- await patchTrackedPostData(supabase, id, { manualViews: null }, userId);
- } else {
- const views = Number(manualViews);
- if (!Number.isInteger(views) || views < 0) {
- return c.json({ error: 'Views must be a whole number of 0 or more' }, 400);
- }
- await patchTrackedPostData(supabase, id, { manualViews: views }, userId);
- }
+ const views = manualViewsPatch(manualViews, isYouTube);
+ if (views.error) return c.json({ error: views.error }, 400);
+ await patchTrackedPostData(supabase, id, views.patch, userId);
}
- // Reddit posts carry no thumbnail in the public JSON API, so the user uploads one to
- // Cloudinary from the browser and only the resulting URL reaches the Worker. YouTube
- // items already have a real thumbnail and must not be overridden.
if (imageUrl !== undefined) {
- if (isYouTube) {
- return c.json({ error: 'Images can only be attached to Reddit posts' }, 400);
- }
- if (imageUrl === null || imageUrl === '') {
- await patchTrackedPostData(supabase, id, { imageUrl: null }, userId);
- } else {
- let parsed = null;
- try { parsed = new URL(String(imageUrl)); } catch { parsed = null; }
- // https only - the value is rendered straight into an img src, so a
- // javascript: or data: URL must never be stored
- if (!parsed || parsed.protocol !== 'https:') {
- return c.json({ error: 'Image must be an https URL returned by the uploader' }, 400);
- }
- await patchTrackedPostData(supabase, id, { imageUrl: parsed.toString() }, userId);
- }
+ const image = imageUrlPatch(imageUrl, isYouTube);
+ if (image.error) return c.json({ error: image.error }, 400);
+ await patchTrackedPostData(supabase, id, image.patch, userId);
}
const updates = {};
diff --git a/backend/routes/trackedContent.test.js b/backend/routes/trackedContent.test.js
new file mode 100644
index 0000000..36bb6af
--- /dev/null
+++ b/backend/routes/trackedContent.test.js
@@ -0,0 +1,105 @@
+import { test, describe, before, after, afterEach, mock } from 'node:test';
+import trackedContentRouter from './trackedContent.js';
+import { assertGolden } from '../services/fixtures/golden.js';
+import { installFetch, reply } from '../services/fixtures/fakeFetch.js';
+import { fakeSupabase, accountRow, tableRow } from '../services/fixtures/fakeSupabase.js';
+import { mountWithContext, callRoute } from '../services/fixtures/routeHarness.js';
+
+const FIXED_NOW = Date.parse('2026-09-01T12:00:00Z');
+const ENV = { YOUTUBE_API_KEY: 'YTKEY' };
+
+const REDDIT_POST = [{ data: { children: [{ data: { id: 'p1', title: 'Tracked', subreddit: 'webdev', score: 77, upvote_ratio: 0.93, num_comments: 8, permalink: '/r/webdev/comments/p1/tracked/', over_18: false, created_utc: 1785000000 } }] } }];
+const YOUTUBE_VIDEO = { items: [{ snippet: { title: 'Watch', channelTitle: 'Ribbon', channelId: 'UC1', publishedAt: '2026-08-01T10:00:00Z', thumbnails: { medium: { url: 'm' } } }, statistics: { viewCount: '1500', likeCount: '40', commentCount: '3' } }] };
+
+function trackedRow(id, contentType, extra = {}) {
+ return tableRow('tracked_posts', { id, user_id: 'user-1', account_id: extra.accountId ?? null, url: extra.url ?? `https://example/${id}`, label: '', category: '', content_type: contentType, created_at: '2026-08-01T00:00:00Z', updated_at: '2026-08-01T00:00:00Z', data: extra.data ?? {} });
+}
+
+function seedRows() {
+ return [
+ tableRow('accounts', accountRow({ id: 'rd1', platform: 'reddit', username: 'ribbon', cookie: 'COOKIE' })),
+ tableRow('accounts', accountRow({ id: 'yt1', platform: 'youtube', channelId: 'UC1' })),
+ trackedRow('t-reddit', 'reddit', { accountId: 'rd1', url: 'https://www.reddit.com/r/webdev/comments/p1/tracked/', data: { title: 'Old', manualViews: 5 } }),
+ trackedRow('t-youtube', 'youtube', { url: 'https://www.youtube.com/watch?v=abc', data: { title: 'Video' } }),
+ trackedRow('t-orphan', 'reddit', { accountId: 'gone', url: 'https://www.reddit.com/r/webdev/comments/p1/tracked/' }),
+ ];
+}
+
+let fetchMock = null;
+afterEach(() => fetchMock?.restore());
+
+async function runCalls(calls, env = ENV) {
+ const supabase = fakeSupabase(seedRows());
+ const app = mountWithContext(server => server.route('/', trackedContentRouter), { supabase, userId: 'user-1' });
+ fetchMock = installFetch(request => (request.url.includes('googleapis') ? reply(YOUTUBE_VIDEO) : reply(REDDIT_POST)));
+ const responses = [];
+ const logLines = [];
+ mock.method(console, 'error', (...args) => logLines.push(['error', ...args]));
+ for (const [method, path, json] of calls) {
+ responses.push({ call: `${method} ${path}`, ...(await callRoute(app, method, path, { json, env })) });
+ }
+ console.error.mock.restore();
+ return { responses, queries: supabase.calls, requests: fetchMock.requests, logLines };
+}
+
+describe('tracked content routes golden output', () => {
+ before(() => {
+ mock.timers.enable({ apis: ['Date'], now: FIXED_NOW });
+ let seed = 0;
+ mock.method(Math, 'random', () => {
+ seed += 0.125;
+ return seed % 1;
+ });
+ });
+ after(() => {
+ mock.timers.reset();
+ mock.restoreAll();
+ });
+
+ test('adding items validates the link and the reddit account', async () => {
+ const result = await runCalls([
+ ['POST', '/tracked-content', {}],
+ ['POST', '/tracked-content', { url: 'https://example.com/post' }],
+ ['POST', '/tracked-content', { url: ' https://www.youtube.com/watch?v=abc ', label: 'Video', category: 'Music' }],
+ ['POST', '/tracked-content', { url: 'https://www.reddit.com/r/webdev/comments/p1/tracked/', accountId: 'yt1' }],
+ ['POST', '/tracked-content', { url: 'https://www.reddit.com/r/webdev/comments/p1/tracked/', accountId: 'missing' }],
+ ['POST', '/tracked-content', { url: 'https://www.reddit.com/r/webdev/comments/p1/tracked/', accountId: 'rd1', label: 'Mine' }],
+ ['POST', '/tracked-content', { url: 'https://www.reddit.com/r/webdev/comments/p1/tracked/' }],
+ ]);
+ const withoutKey = await runCalls([['POST', '/tracked-content', { url: 'https://youtu.be/abc' }]], {});
+ assertGolden({ result, withoutKey }, 'trackedContentRoutes.create');
+ });
+
+ test('updates check manual views and images before saving fields', async () => {
+ const result = await runCalls([
+ ['PUT', '/tracked-content/nope', { label: 'x' }],
+ ['PUT', '/tracked-content/t-youtube', { manualViews: 10 }],
+ ['PUT', '/tracked-content/t-youtube', { imageUrl: 'https://img/a.png' }],
+ ['PUT', '/tracked-content/t-reddit', { manualViews: '' }],
+ ['PUT', '/tracked-content/t-reddit', { manualViews: '12' }],
+ ['PUT', '/tracked-content/t-reddit', { manualViews: -1 }],
+ ['PUT', '/tracked-content/t-reddit', { manualViews: 1.5 }],
+ ['PUT', '/tracked-content/t-reddit', { imageUrl: 'https://img/a b.png' }],
+ ['PUT', '/tracked-content/t-reddit', { imageUrl: null }],
+ ['PUT', '/tracked-content/t-reddit', { imageUrl: 'javascript:alert(1)' }],
+ ['PUT', '/tracked-content/t-reddit', { manualViews: 7, imageUrl: 'http://img/a.png' }],
+ ['PUT', '/tracked-content/t-reddit', { label: 'New', category: 'Cat', accountId: '' }],
+ ['PUT', '/tracked-content/t-youtube', { label: 'Only label' }],
+ ]);
+ assertGolden(result, 'trackedContentRoutes.update');
+ });
+
+ test('list, refresh and delete', async () => {
+ const result = await runCalls([
+ ['GET', '/tracked-content'],
+ ['POST', '/tracked-content/t-reddit/refresh'],
+ ['POST', '/tracked-content/t-orphan/refresh'],
+ ['POST', '/tracked-content/t-youtube/refresh'],
+ ['POST', '/tracked-content/nope/refresh'],
+ ['DELETE', '/tracked-content/t-youtube'],
+ ['DELETE', '/tracked-content/t-youtube'],
+ ]);
+ const withoutKey = await runCalls([['POST', '/tracked-content/t-youtube/refresh']], {});
+ assertGolden({ result, withoutKey }, 'trackedContentRoutes.refresh');
+ });
+});
diff --git a/backend/server.js b/backend/server.js
index 0b50cbe..baafa61 100644
--- a/backend/server.js
+++ b/backend/server.js
@@ -24,28 +24,20 @@ app.onError((err, c) => {
return c.json({ error: 'Internal server error' }, 500);
});
-// ── Global middleware ─────────────────────────────────────────────────────────
-
app.use('*', cors());
-// Attach Supabase and Redis clients to context for every request.
-// Both are stateless HTTP clients - safe to create per-request in Workers.
+// both clients are stateless http clients, so creating them per request is safe
app.use('*', async (c, next) => {
c.set('supabase', getSupabase(c.env));
c.set('redis', getRedis(c.env));
await next();
});
-// ── Public routes ─────────────────────────────────────────────────────────────
-
app.get('/api/health', (c) => c.json({ status: 'ok', timestamp: new Date().toISOString() }));
-// Instagram OAuth callback - public because it's a browser redirect (no JWT available).
-// The userId is recovered from the Redis state token instead.
+// public: the oauth redirect carries no jwt, so the user comes from the redis state token
app.get('/api/auth/instagram/callback', callbackHandler);
-// ── Protected routes (require valid Supabase JWT) ─────────────────────────────
-
const api = new Hono();
api.use('*', requireAuth);
@@ -59,20 +51,15 @@ api.route('/', redditRouter);
api.route('/', trackedContentRouter);
api.route('/', overviewRouter);
-// Instagram OAuth URL generator - protected (needs userId to create state token)
+// protected: the state token needs the user id
api.get('/auth/instagram/url', urlHandler);
app.route('/api', api);
-// ── Cloudflare Workers export ─────────────────────────────────────────────────
-
export default {
- // Handles all HTTP requests
fetch: app.fetch,
- // Cron trigger handler - runs on the schedule defined in wrangler.toml:
- // "*/15 * * * *" → publish due scheduled posts
- // "0 0 * * *" → refresh expiring Instagram tokens
+ // schedules come from wrangler.toml: due posts every 15 minutes, token refresh daily
async scheduled(event, env, ctx) {
const supabase = getSupabase(env);
diff --git a/backend/services/accountRefresh.js b/backend/services/accountRefresh.js
index 10fafa8..ac6f1d0 100644
--- a/backend/services/accountRefresh.js
+++ b/backend/services/accountRefresh.js
@@ -52,6 +52,27 @@ function youtubeUpdates(channelData, full) {
};
}
+// accounts added before creation dates were stored get them once; a failure only skips the extras
+export async function backfillChannelData(supabase, account, apiKey, userId) {
+ try {
+ const channelData = await fetchChannelData(account.channelId, apiKey);
+ await updateAccount(supabase, account.id, {
+ publishedAt: channelData.publishedAt,
+ subscriberCount: channelData.subscriberCount,
+ viewCount: channelData.viewCount,
+ videoCount: channelData.videoCount,
+ title: channelData.title,
+ thumbnails: channelData.thumbnails,
+ customUrl: channelData.customUrl,
+ country: channelData.country,
+ lastUpdated: new Date().toISOString(),
+ }, userId);
+ Object.assign(account, channelData);
+ } catch (e) {
+ console.error('Failed to backfill channel data:', e.message);
+ }
+}
+
export async function fetchAccountUpdates(account, apiKey, full) {
if (account.platform === 'instagram') {
const profile = await fetchInstagramProfile(account.igUserId, account.accessToken);
diff --git a/backend/services/fixtures/analyticsRoutes.emptyComparison.golden.json b/backend/services/fixtures/analyticsRoutes.emptyComparison.golden.json
new file mode 100644
index 0000000..db91d26
--- /dev/null
+++ b/backend/services/fixtures/analyticsRoutes.emptyComparison.golden.json
@@ -0,0 +1,4 @@
+{
+ "status": 200,
+ "body": "{\"success\":true,\"comparison\":null}"
+}
diff --git a/backend/services/fixtures/analyticsRoutes.youtube.golden.json b/backend/services/fixtures/analyticsRoutes.youtube.golden.json
new file mode 100644
index 0000000..2dbd219
--- /dev/null
+++ b/backend/services/fixtures/analyticsRoutes.youtube.golden.json
@@ -0,0 +1,293 @@
+{
+ "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\"},{\"id\":\"ig1\",\"platform\":\"instagram\",\"igUserId\":\"IG1\",\"accessToken\":\"T1\",\"username\":\"ribbon\"},{\"id\":\"rd1\",\"platform\":\"reddit\",\"username\":\"ribbon\",\"cookie\":\"COOKIE\"},{\"id\":\"rd2\",\"platform\":\"reddit\",\"username\":\"nocookie\"}],\"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\"},{\"id\":\"ig1\",\"platform\":\"instagram\",\"igUserId\":\"IG1\",\"accessToken\":\"T1\",\"username\":\"ribbon\"},{\"id\":\"rd1\",\"platform\":\"reddit\",\"username\":\"ribbon\",\"cookie\":\"COOKIE\"},{\"id\":\"rd2\",\"platform\":\"reddit\",\"username\":\"nocookie\"}],\"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\"},{\"id\":\"ig1\",\"platform\":\"instagram\",\"igUserId\":\"IG1\",\"accessToken\":\"T1\",\"username\":\"ribbon\"},{\"id\":\"rd1\",\"platform\":\"reddit\",\"username\":\"ribbon\",\"cookie\":\"COOKIE\"},{\"id\":\"rd2\",\"platform\":\"reddit\",\"username\":\"nocookie\"}]},\"totals\":{\"subscribers\":400,\"views\":6000,\"videos\":10},\"accountCount\":6,\"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\"},{\"id\":\"rd1\"},{\"id\":\"rd2\"}]}"
+ },
+ {
+ "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\"},{\"id\":\"rd1\"},{\"id\":\"rd2\"}]}"
+ },
+ {
+ "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\"},{\"id\":\"rd1\"},{\"id\":\"rd2\"}]}"
+ },
+ {
+ "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\"},{\"id\":\"rd1\"},{\"id\":\"rd2\"}]}"
+ },
+ {
+ "call": "GET /accounts/yt1/analytics",
+ "status": 200,
+ "body": "{\"success\":true,\"channel\":{\"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\"},\"channelAge\":730,\"channelAgeYears\":\"2.0\",\"viewsPerSubscriber\":50,\"subscriberToViewRatio\":2,\"avgViewsPerVideo\":500,\"avgSubGainPerDay\":0,\"avgViewsPerDay\":7,\"estimatedMonthlyViews\":210,\"estimatedMonthlySubGain\":0,\"estimatedYearlyViews\":2555,\"estimatedYearlySubGain\":0},\"analytics\":{\"totalVideos\":1,\"totalViews\":70,\"totalLikes\":7,\"totalComments\":1,\"avgViews\":70,\"avgLikes\":7,\"avgComments\":1,\"medianViews\":70,\"totalEngagement\":8,\"overallEngagementRate\":\"11.43\",\"avgDurationSeconds\":45,\"avgDurationFormatted\":\"0m 45s\",\"totalDurationSeconds\":45,\"totalDurationFormatted\":\"0m 45s\",\"estimatedTotalWatchTimeHours\":1,\"bestByViews\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"bestByLikes\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"bestByComments\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"bestByEngagement\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"worstByViews\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"mostRecent\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"oldest\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"top10ByViews\":[{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45}],\"top10ByLikes\":[{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45}],\"top10ByComments\":[{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45}],\"top10ByEngagement\":[{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45}],\"shortsCount\":1,\"regularCount\":0,\"avgShortViews\":70,\"avgRegularViews\":0,\"avgShortLikes\":7,\"avgRegularLikes\":0,\"hdCount\":1,\"sdCount\":0,\"hdPercentage\":\"100.0\",\"captionCount\":0,\"captionPercentage\":\"0.0\",\"licensedCount\":0,\"licensedPercentage\":\"0.0\",\"madeForKidsCount\":0,\"embeddableCount\":0,\"embeddablePercentage\":\"0.0\",\"publishDayDistribution\":{\"Thursday\":1},\"publishHourDistribution\":{\"10\":1},\"peakPublishDay\":\"Thursday\",\"peakPublishHour\":10,\"durationDistribution\":{\"short\":1,\"medium\":0,\"long\":0,\"veryLong\":0},\"categoryDistribution\":{\"Unknown\":1},\"tagFrequency\":[],\"videosLast7Days\":0,\"videosLast30Days\":1,\"videosLast90Days\":1,\"videosLast365Days\":1,\"uploadFrequencyPerWeek\":\"0.6\",\"uploadFrequencyPerMonth\":\"1.0\",\"consistencyScore\":100,\"viralityScore\":1,\"viewsDistribution\":{\"ranges\":[\"0-7\",\"7-14\",\"14-21\",\"21-28\",\"28-35\",\"35-42\",\"42-49\",\"49-56\",\"56-63\",\"63-70\"],\"counts\":[0,0,0,0,0,0,0,0,0,0]},\"viewsTrend\":[{\"month\":\"2026-08\",\"value\":70,\"count\":1}],\"engagementTrend\":[{\"month\":\"2026-08\",\"value\":\"11.43\"}],\"likeRateTrend\":[{\"month\":\"2026-08\",\"value\":\"10.00\"}]},\"videoCount\":1}"
+ },
+ {
+ "call": "GET /accounts/yt2/analytics",
+ "status": 200,
+ "body": "{\"success\":true,\"channel\":{\"id\":\"yt2\",\"platform\":\"youtube\",\"channelId\":\"UC2\",\"uploadsPlaylistId\":\"UU2\",\"title\":\"Beta\",\"subscriberCount\":300,\"viewCount\":1000,\"videoCount\":0,\"channelAge\":365,\"channelAgeYears\":\"1.0\",\"viewsPerSubscriber\":3.3,\"subscriberToViewRatio\":30,\"avgViewsPerVideo\":0,\"avgSubGainPerDay\":1,\"avgViewsPerDay\":3,\"estimatedMonthlyViews\":90,\"estimatedMonthlySubGain\":30,\"estimatedYearlyViews\":1095,\"estimatedYearlySubGain\":365},\"analytics\":{\"totalVideos\":1,\"totalViews\":70,\"totalLikes\":7,\"totalComments\":1,\"avgViews\":70,\"avgLikes\":7,\"avgComments\":1,\"medianViews\":70,\"totalEngagement\":8,\"overallEngagementRate\":\"11.43\",\"avgDurationSeconds\":45,\"avgDurationFormatted\":\"0m 45s\",\"totalDurationSeconds\":45,\"totalDurationFormatted\":\"0m 45s\",\"estimatedTotalWatchTimeHours\":1,\"bestByViews\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"bestByLikes\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"bestByComments\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"bestByEngagement\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"worstByViews\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"mostRecent\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"oldest\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"top10ByViews\":[{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45}],\"top10ByLikes\":[{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45}],\"top10ByComments\":[{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45}],\"top10ByEngagement\":[{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45}],\"shortsCount\":1,\"regularCount\":0,\"avgShortViews\":70,\"avgRegularViews\":0,\"avgShortLikes\":7,\"avgRegularLikes\":0,\"hdCount\":1,\"sdCount\":0,\"hdPercentage\":\"100.0\",\"captionCount\":0,\"captionPercentage\":\"0.0\",\"licensedCount\":0,\"licensedPercentage\":\"0.0\",\"madeForKidsCount\":0,\"embeddableCount\":0,\"embeddablePercentage\":\"0.0\",\"publishDayDistribution\":{\"Thursday\":1},\"publishHourDistribution\":{\"10\":1},\"peakPublishDay\":\"Thursday\",\"peakPublishHour\":10,\"durationDistribution\":{\"short\":1,\"medium\":0,\"long\":0,\"veryLong\":0},\"categoryDistribution\":{\"Unknown\":1},\"tagFrequency\":[],\"videosLast7Days\":0,\"videosLast30Days\":1,\"videosLast90Days\":1,\"videosLast365Days\":1,\"uploadFrequencyPerWeek\":\"0.6\",\"uploadFrequencyPerMonth\":\"1.0\",\"consistencyScore\":100,\"viralityScore\":1,\"viewsDistribution\":{\"ranges\":[\"0-7\",\"7-14\",\"14-21\",\"21-28\",\"28-35\",\"35-42\",\"42-49\",\"49-56\",\"56-63\",\"63-70\"],\"counts\":[0,0,0,0,0,0,0,0,0,0]},\"viewsTrend\":[{\"month\":\"2026-08\",\"value\":70,\"count\":1}],\"engagementTrend\":[{\"month\":\"2026-08\",\"value\":\"11.43\"}],\"likeRateTrend\":[{\"month\":\"2026-08\",\"value\":\"10.00\"}]},\"videoCount\":1}"
+ },
+ {
+ "call": "GET /accounts/yt3/analytics",
+ "status": 200,
+ "body": "{\"success\":true,\"channel\":{\"id\":\"yt3\",\"platform\":\"youtube\",\"channelId\":\"UC3\",\"title\":\"Gamma\",\"customUrl\":\"@gamma\",\"publishedAt\":\"2025-09-01T00:00:00Z\",\"country\":\"Unknown\",\"thumbnails\":{\"default\":\"\",\"medium\":\"\",\"high\":\"\"},\"subscriberCount\":20,\"viewCount\":400,\"videoCount\":2,\"hiddenSubscriberCount\":false,\"uploadsPlaylistId\":\"UU3\",\"keywords\":\"\",\"bannerUrl\":\"\",\"madeForKids\":false,\"topicCategories\":[],\"isLinked\":false,\"channelAge\":365,\"channelAgeYears\":\"1.0\",\"viewsPerSubscriber\":20,\"subscriberToViewRatio\":5,\"avgViewsPerVideo\":200,\"avgSubGainPerDay\":0,\"avgViewsPerDay\":1,\"estimatedMonthlyViews\":30,\"estimatedMonthlySubGain\":0,\"estimatedYearlyViews\":365,\"estimatedYearlySubGain\":0},\"analytics\":{\"totalVideos\":1,\"totalViews\":70,\"totalLikes\":7,\"totalComments\":1,\"avgViews\":70,\"avgLikes\":7,\"avgComments\":1,\"medianViews\":70,\"totalEngagement\":8,\"overallEngagementRate\":\"11.43\",\"avgDurationSeconds\":45,\"avgDurationFormatted\":\"0m 45s\",\"totalDurationSeconds\":45,\"totalDurationFormatted\":\"0m 45s\",\"estimatedTotalWatchTimeHours\":1,\"bestByViews\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"bestByLikes\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"bestByComments\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"bestByEngagement\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"worstByViews\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"mostRecent\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"oldest\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"top10ByViews\":[{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45}],\"top10ByLikes\":[{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45}],\"top10ByComments\":[{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45}],\"top10ByEngagement\":[{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45}],\"shortsCount\":1,\"regularCount\":0,\"avgShortViews\":70,\"avgRegularViews\":0,\"avgShortLikes\":7,\"avgRegularLikes\":0,\"hdCount\":1,\"sdCount\":0,\"hdPercentage\":\"100.0\",\"captionCount\":0,\"captionPercentage\":\"0.0\",\"licensedCount\":0,\"licensedPercentage\":\"0.0\",\"madeForKidsCount\":0,\"embeddableCount\":0,\"embeddablePercentage\":\"0.0\",\"publishDayDistribution\":{\"Thursday\":1},\"publishHourDistribution\":{\"10\":1},\"peakPublishDay\":\"Thursday\",\"peakPublishHour\":10,\"durationDistribution\":{\"short\":1,\"medium\":0,\"long\":0,\"veryLong\":0},\"categoryDistribution\":{\"Unknown\":1},\"tagFrequency\":[],\"videosLast7Days\":0,\"videosLast30Days\":1,\"videosLast90Days\":1,\"videosLast365Days\":1,\"uploadFrequencyPerWeek\":\"0.6\",\"uploadFrequencyPerMonth\":\"1.0\",\"consistencyScore\":100,\"viralityScore\":1,\"viewsDistribution\":{\"ranges\":[\"0-7\",\"7-14\",\"14-21\",\"21-28\",\"28-35\",\"35-42\",\"42-49\",\"49-56\",\"56-63\",\"63-70\"],\"counts\":[0,0,0,0,0,0,0,0,0,0]},\"viewsTrend\":[{\"month\":\"2026-08\",\"value\":70,\"count\":1}],\"engagementTrend\":[{\"month\":\"2026-08\",\"value\":\"11.43\"}],\"likeRateTrend\":[{\"month\":\"2026-08\",\"value\":\"10.00\"}]},\"videoCount\":1}"
+ },
+ {
+ "call": "GET /accounts/missing/analytics",
+ "status": 404,
+ "body": "{\"success\":false,\"message\":\"Account not found\"}"
+ }
+ ],
+ "queries": [
+ {
+ "type": "select",
+ "table": "accounts",
+ "columns": "id, platform, data",
+ "filters": [
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "accounts",
+ "columns": "id, platform, data",
+ "filters": [
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "accounts",
+ "columns": "id, platform, data",
+ "filters": [
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "accounts",
+ "columns": "id, platform, data",
+ "filters": [
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "accounts",
+ "columns": "id, platform, data",
+ "filters": [
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "accounts",
+ "columns": "id, platform, data",
+ "filters": [
+ [
+ "id",
+ "yt1"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "accounts",
+ "columns": "id, platform, data",
+ "filters": [
+ [
+ "id",
+ "yt2"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "accounts",
+ "columns": "id, platform, data",
+ "filters": [
+ [
+ "id",
+ "yt3"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "accounts",
+ "columns": "id, platform, data",
+ "filters": [
+ [
+ "id",
+ "yt3"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "update",
+ "table": "accounts",
+ "values": {
+ "platform": "youtube",
+ "data": {
+ "channelId": "UC3",
+ "title": "Gamma",
+ "publishedAt": "2025-09-01T00:00:00Z",
+ "subscriberCount": 20,
+ "viewCount": 400,
+ "videoCount": 2,
+ "thumbnails": {
+ "default": "",
+ "medium": "",
+ "high": ""
+ },
+ "customUrl": "@gamma",
+ "country": "Unknown",
+ "lastUpdated": "2026-09-01T12:00:00.000Z"
+ }
+ },
+ "filters": [
+ [
+ "id",
+ "yt3"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "accounts",
+ "columns": "id, platform, data",
+ "filters": [
+ [
+ "id",
+ "missing"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ }
+ ],
+ "requests": [
+ {
+ "url": "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet%2CcontentDetails&playlistId=UU1&maxResults=50&key=YTKEY",
+ "method": "GET"
+ },
+ {
+ "url": "https://www.googleapis.com/youtube/v3/videos?part=statistics%2CcontentDetails%2Csnippet%2Cstatus&id=v1&key=YTKEY",
+ "method": "GET"
+ },
+ {
+ "url": "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet%2CcontentDetails&playlistId=UU2&maxResults=50&key=YTKEY",
+ "method": "GET"
+ },
+ {
+ "url": "https://www.googleapis.com/youtube/v3/videos?part=statistics%2CcontentDetails%2Csnippet%2Cstatus&id=v1&key=YTKEY",
+ "method": "GET"
+ },
+ {
+ "url": "https://www.googleapis.com/youtube/v3/channels?part=snippet%2Cstatistics%2CcontentDetails%2CbrandingSettings%2Cstatus%2CtopicDetails&id=UC2&key=YTKEY",
+ "method": "GET"
+ },
+ {
+ "url": "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet%2CcontentDetails&playlistId=undefined&maxResults=50&key=YTKEY",
+ "method": "GET"
+ },
+ {
+ "url": "https://www.googleapis.com/youtube/v3/videos?part=statistics%2CcontentDetails%2Csnippet%2Cstatus&id=v1&key=YTKEY",
+ "method": "GET"
+ },
+ {
+ "url": "https://www.googleapis.com/youtube/v3/channels?part=snippet%2Cstatistics%2CcontentDetails%2CbrandingSettings%2Cstatus%2CtopicDetails&id=UC3&key=YTKEY",
+ "method": "GET"
+ }
+ ],
+ "logLines": [
+ [
+ "error",
+ "Failed to backfill channel data:",
+ "Channel lookup failed"
+ ]
+ ],
+ "redisWrites": [
+ {
+ "key": "videos:user-1:yt1",
+ "options": {
+ "ex": 21600
+ },
+ "version": 2
+ },
+ {
+ "key": "videos:user-1:yt2",
+ "options": {
+ "ex": 21600
+ },
+ "version": 2
+ },
+ {
+ "key": "videos:user-1:yt3",
+ "options": {
+ "ex": 21600
+ },
+ "version": 2
+ }
+ ]
+ },
+ "withoutKey": {
+ "responses": [
+ {
+ "call": "GET /accounts/yt1/analytics",
+ "status": 400,
+ "body": "{\"success\":false,\"message\":\"No API key\"}"
+ }
+ ],
+ "queries": [],
+ "requests": [],
+ "logLines": [],
+ "redisWrites": null
+ }
+}
diff --git a/backend/services/fixtures/fakeSupabase.js b/backend/services/fixtures/fakeSupabase.js
index 6c72712..c7b622f 100644
--- a/backend/services/fixtures/fakeSupabase.js
+++ b/backend/services/fixtures/fakeSupabase.js
@@ -3,8 +3,18 @@ function copy(value) {
return value === undefined ? undefined : structuredClone(value);
}
+function matchesFilter(row, [column, value, operator]) {
+ if (operator === 'lte') return row[column] <= value;
+ return row[column] === value;
+}
+
function matchesFilters(row, filters) {
- return filters.every(([column, value]) => row[column] === value);
+ return filters.every(filter => matchesFilter(row, filter));
+}
+
+// rows without a _table tag are visible to every table, as the older tests expect
+function inTable(row, name) {
+ return row._table === undefined || row._table === name;
}
function queryBuilder(action, run) {
@@ -15,6 +25,11 @@ function queryBuilder(action, run) {
filters.push([column, value]);
return query;
},
+ lte(column, value) {
+ filters.push([column, value, 'lte']);
+ return query;
+ },
+ order() { return query; },
single() {
const found = run(action, filters);
if (found.length === 0) return Promise.resolve({ data: null, error: { message: 'no rows' } });
@@ -33,7 +48,7 @@ export function fakeSupabase(rows = []) {
function run(action, filters) {
calls.push({ ...copy(action), filters: copy(filters) });
- const found = table.filter(row => matchesFilters(row, filters));
+ const found = table.filter(row => inTable(row, action.table) && matchesFilters(row, filters));
if (action.type === 'update') found.forEach(row => Object.assign(row, copy(action.values)));
if (action.type === 'insert') table.push(copy(action.values));
if (action.type === 'delete') {
@@ -56,6 +71,10 @@ export function fakeSupabase(rows = []) {
};
}
+export function tableRow(name, row) {
+ return { _table: name, ...row };
+}
+
export function accountRow(account, userId = 'user-1') {
const { id, platform, ...data } = account;
return { id, platform, user_id: userId, data };
diff --git a/backend/services/fixtures/overviewRoutes.summary.golden.json b/backend/services/fixtures/overviewRoutes.summary.golden.json
new file mode 100644
index 0000000..353c7ce
--- /dev/null
+++ b/backend/services/fixtures/overviewRoutes.summary.golden.json
@@ -0,0 +1,74 @@
+{
+ "cached": {
+ "responses": [
+ {
+ "call": "GET /overview",
+ "status": 200,
+ "body": "{\"tracked\":[{\"id\":\"t1\",\"accountId\":null,\"url\":\"https://youtu.be/x\",\"label\":\"\",\"category\":\"\",\"contentType\":\"youtube\",\"createdAt\":\"2026-08-01T00:00:00Z\",\"updatedAt\":\"2026-08-01T00:00:00Z\",\"title\":\"Tracked\"}],\"analyticsCache\":{\"yt1\":{\"id\":\"yt1\",\"cacheWarmed\":true,\"totalLikes\":12,\"totalComments\":5},\"yt2\":{\"id\":\"yt2\",\"cacheWarmed\":true,\"totalLikes\":1,\"totalComments\":1},\"yt3\":{\"id\":\"yt3\",\"cacheWarmed\":false,\"syncing\":false},\"ig1\":{\"id\":\"ig1\",\"cacheWarmed\":true,\"totalLikes\":6,\"totalComments\":2,\"totalViews\":90,\"contentTypes\":{\"reel\":{\"count\":1,\"likes\":5,\"comments\":2,\"views\":90,\"viewsReported\":1},\"post\":{\"count\":1,\"likes\":1,\"comments\":0,\"views\":0,\"viewsReported\":0},\"video\":{\"count\":0,\"likes\":0,\"comments\":0,\"views\":0,\"viewsReported\":0}}},\"rd1\":{\"id\":\"rd1\",\"cacheWarmed\":true,\"fetchedPosts\":4,\"totalScore\":40,\"totalComments\":0},\"rd2\":{\"id\":\"rd2\",\"cacheWarmed\":false,\"syncing\":false}}}"
+ }
+ ],
+ "queries": [
+ {
+ "type": "select",
+ "table": "accounts",
+ "columns": "id, platform, data",
+ "filters": [
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "tracked_posts",
+ "columns": "id, account_id, url, label, category, content_type, created_at, updated_at, data",
+ "filters": [
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ }
+ ],
+ "requests": [],
+ "logLines": [],
+ "redisWrites": []
+ },
+ "noRedis": {
+ "responses": [
+ {
+ "call": "GET /overview",
+ "status": 200,
+ "body": "{\"tracked\":[{\"id\":\"t1\",\"accountId\":null,\"url\":\"https://youtu.be/x\",\"label\":\"\",\"category\":\"\",\"contentType\":\"youtube\",\"createdAt\":\"2026-08-01T00:00:00Z\",\"updatedAt\":\"2026-08-01T00:00:00Z\",\"title\":\"Tracked\"}],\"analyticsCache\":{\"yt1\":{\"id\":\"yt1\",\"cacheWarmed\":false,\"syncing\":false},\"yt2\":{\"id\":\"yt2\",\"cacheWarmed\":false,\"syncing\":false},\"yt3\":{\"id\":\"yt3\",\"cacheWarmed\":false,\"syncing\":false},\"ig1\":{\"id\":\"ig1\",\"cacheWarmed\":false,\"syncing\":false},\"rd1\":{\"id\":\"rd1\",\"cacheWarmed\":false,\"syncing\":false},\"rd2\":{\"id\":\"rd2\",\"cacheWarmed\":false,\"syncing\":false}}}"
+ }
+ ],
+ "queries": [
+ {
+ "type": "select",
+ "table": "accounts",
+ "columns": "id, platform, data",
+ "filters": [
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "tracked_posts",
+ "columns": "id, account_id, url, label, category, content_type, created_at, updated_at, data",
+ "filters": [
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ }
+ ],
+ "requests": [],
+ "logLines": [],
+ "redisWrites": null
+ }
+}
diff --git a/backend/services/fixtures/overviewRoutes.warming.golden.json b/backend/services/fixtures/overviewRoutes.warming.golden.json
new file mode 100644
index 0000000..7738525
--- /dev/null
+++ b/backend/services/fixtures/overviewRoutes.warming.golden.json
@@ -0,0 +1,80 @@
+{
+ "status": 200,
+ "body": "{\"tracked\":[{\"id\":\"t1\",\"accountId\":null,\"url\":\"https://youtu.be/x\",\"label\":\"\",\"category\":\"\",\"contentType\":\"youtube\",\"createdAt\":\"2026-08-01T00:00:00Z\",\"updatedAt\":\"2026-08-01T00:00:00Z\",\"title\":\"Tracked\"}],\"analyticsCache\":{\"yt1\":{\"id\":\"yt1\",\"cacheWarmed\":false,\"syncing\":true},\"yt2\":{\"id\":\"yt2\",\"cacheWarmed\":false,\"syncing\":true},\"yt3\":{\"id\":\"yt3\",\"cacheWarmed\":false,\"syncing\":false},\"ig1\":{\"id\":\"ig1\",\"cacheWarmed\":false,\"syncing\":true},\"rd1\":{\"id\":\"rd1\",\"cacheWarmed\":false,\"syncing\":true},\"rd2\":{\"id\":\"rd2\",\"cacheWarmed\":false,\"syncing\":false}}}",
+ "waitUntilCalls": 1,
+ "settled": [
+ [
+ {
+ "status": "fulfilled",
+ "value": "[undefined]"
+ },
+ {
+ "status": "fulfilled",
+ "value": "[undefined]"
+ },
+ {
+ "status": "fulfilled",
+ "value": "[undefined]"
+ },
+ {
+ "status": "fulfilled",
+ "value": "[undefined]"
+ }
+ ]
+ ],
+ "requests": [
+ {
+ "url": "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet%2CcontentDetails&playlistId=UU1&maxResults=50&key=YTKEY",
+ "method": "GET"
+ },
+ {
+ "url": "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet%2CcontentDetails&playlistId=UU2&maxResults=50&key=YTKEY",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/IG1/media?access_token=T1&limit=50&fields=id%2Ccaption%2Cmedia_type%2Cmedia_product_type%2Cmedia_url%2Cthumbnail_url%2Ccover_url%2Cpermalink%2Ctimestamp%2Clike_count%2Ccomments_count%2Cinsights.metric%28views%29",
+ "method": "GET"
+ },
+ {
+ "url": "https://www.reddit.com/user/ribbon/about.json",
+ "method": "GET",
+ "headers": {
+ "User-Agent": "script:twiligent:v1.0 (by /u/spacesdrive)",
+ "Accept": "application/json",
+ "Cookie": "reddit_session=COOKIE"
+ }
+ },
+ {
+ "url": "https://www.reddit.com/user/ribbon/submitted.json?limit=100&sort=new",
+ "method": "GET",
+ "headers": {
+ "User-Agent": "script:twiligent:v1.0 (by /u/spacesdrive)",
+ "Accept": "application/json",
+ "Cookie": "reddit_session=COOKIE"
+ }
+ }
+ ],
+ "redisWrites": [
+ {
+ "key": "videos:user-1:yt1",
+ "options": {
+ "ex": 21600
+ },
+ "version": 2
+ },
+ {
+ "key": "videos:user-1:yt2",
+ "options": {
+ "ex": 21600
+ },
+ "version": 2
+ },
+ {
+ "key": "ig:user-1:ig1",
+ "options": {
+ "ex": 21600
+ },
+ "version": 2
+ }
+ ]
+}
diff --git a/backend/services/fixtures/scheduler.dbFailure.golden.json b/backend/services/fixtures/scheduler.dbFailure.golden.json
new file mode 100644
index 0000000..096ba0a
--- /dev/null
+++ b/backend/services/fixtures/scheduler.dbFailure.golden.json
@@ -0,0 +1,13 @@
+{
+ "result": {
+ "processed": 0,
+ "errors": []
+ },
+ "logLines": [
+ [
+ "error",
+ "Scheduler error:",
+ "Error: db down"
+ ]
+ ]
+}
diff --git a/backend/services/fixtures/scheduler.process.golden.json b/backend/services/fixtures/scheduler.process.golden.json
new file mode 100644
index 0000000..c2bdc8f
--- /dev/null
+++ b/backend/services/fixtures/scheduler.process.golden.json
@@ -0,0 +1,1224 @@
+{
+ "result": {
+ "processed": 4,
+ "errors": [
+ {
+ "id": "p-story",
+ "error": "Processing failed: Bad video"
+ },
+ {
+ "id": "p-expired",
+ "error": "Container expired"
+ },
+ {
+ "id": "p-missing",
+ "error": "Account not found: gone"
+ },
+ {
+ "id": "p-create",
+ "error": "Invalid image"
+ },
+ {
+ "id": "p-publish",
+ "error": "Publish refused"
+ }
+ ]
+ },
+ "delays": [
+ 2000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 2000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 3000,
+ 2000
+ ],
+ "logLines": [
+ [
+ "log",
+ "Published scheduled post p-image → media m-c-IG1"
+ ],
+ [
+ "log",
+ "Published scheduled post p-reel → media m-c-IG1"
+ ],
+ [
+ "error",
+ "Failed to publish scheduled post p-story: Processing failed: Bad video"
+ ],
+ [
+ "error",
+ "Failed to publish scheduled post p-expired: Container expired"
+ ],
+ [
+ "error",
+ "Failed to publish scheduled post p-missing: Account not found: gone"
+ ],
+ [
+ "error",
+ "Failed to publish scheduled post p-create: Invalid image"
+ ],
+ [
+ "error",
+ "Failed to publish scheduled post p-publish: Publish refused"
+ ],
+ [
+ "log",
+ "Published scheduled post p-slow → media m-c-SLOW"
+ ],
+ [
+ "log",
+ "Published scheduled post p-dup → media m-c-IG1"
+ ]
+ ],
+ "requests": [
+ {
+ "url": "https://graph.instagram.com/v25.0/IG1/media?access_token=T1&image_url=https%3A%2F%2Fcdn%2Fa.jpg&caption=Hello",
+ "method": "POST"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/IG1/media_publish?creation_id=c-IG1&access_token=T1",
+ "method": "POST"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/IG1/media?access_token=T1&media_type=REELS&video_url=https%3A%2F%2Fcdn%2Fr.mp4&share_to_feed=true",
+ "method": "POST"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-IG1?fields=status_code,status&access_token=T1",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-IG1?fields=status_code,status&access_token=T1",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/IG1/media_publish?creation_id=c-IG1&access_token=T1",
+ "method": "POST"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/ERR/media?access_token=T2&media_type=STORIES&video_url=https%3A%2F%2Fcdn%2Fs.mp4",
+ "method": "POST"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-ERR?fields=status_code,status&access_token=T2",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/EXP/media?access_token=T3&media_type=REELS&video_url=https%3A%2F%2Fcdn%2Fe.mp4",
+ "method": "POST"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-EXP?fields=status_code,status&access_token=T3",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-EXP?fields=status_code,status&access_token=T3",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/BAD/media?access_token=T4&image_url=https%3A%2F%2Fcdn%2Fb.jpg",
+ "method": "POST"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/PUB/media?access_token=T5&image_url=https%3A%2F%2Fcdn%2Fp.jpg",
+ "method": "POST"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/PUB/media_publish?creation_id=c-PUB&access_token=T5",
+ "method": "POST"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/SLOW/media?access_token=T6&media_type=REELS&video_url=https%3A%2F%2Fcdn%2Fslow.mp4",
+ "method": "POST"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/SLOW/media_publish?creation_id=c-SLOW&access_token=T6",
+ "method": "POST"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/IG1/media?access_token=T1&image_url=https%3A%2F%2Fcdn%2Fd.jpg",
+ "method": "POST"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/IG1/media_publish?creation_id=c-IG1&access_token=T1",
+ "method": "POST"
+ }
+ ],
+ "queries": [
+ {
+ "type": "select",
+ "table": "scheduled_posts",
+ "columns": "id, account_id, status, scheduled_at, data",
+ "filters": [
+ [
+ "status",
+ "pending"
+ ],
+ [
+ "scheduled_at",
+ "2026-09-01T12:00:00.000Z",
+ "lte"
+ ]
+ ]
+ },
+ {
+ "type": "update",
+ "table": "scheduled_posts",
+ "values": {
+ "status": "publishing"
+ },
+ "filters": [
+ [
+ "id",
+ "p-image"
+ ],
+ [
+ "status",
+ "pending"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "accounts",
+ "columns": "id, platform, data",
+ "filters": [
+ [
+ "id",
+ "ig1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "scheduled_posts",
+ "columns": "data",
+ "filters": [
+ [
+ "id",
+ "p-image"
+ ]
+ ]
+ },
+ {
+ "type": "update",
+ "table": "scheduled_posts",
+ "values": {
+ "status": "published",
+ "data": {
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn/a.jpg",
+ "caption": "Hello",
+ "publishedMediaId": "m-c-IG1",
+ "publishedAt": "2026-09-01T12:00:00.000Z"
+ }
+ },
+ "filters": [
+ [
+ "id",
+ "p-image"
+ ]
+ ]
+ },
+ {
+ "type": "update",
+ "table": "scheduled_posts",
+ "values": {
+ "status": "publishing"
+ },
+ "filters": [
+ [
+ "id",
+ "p-reel"
+ ],
+ [
+ "status",
+ "pending"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "accounts",
+ "columns": "id, platform, data",
+ "filters": [
+ [
+ "id",
+ "ig1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "scheduled_posts",
+ "columns": "data",
+ "filters": [
+ [
+ "id",
+ "p-reel"
+ ]
+ ]
+ },
+ {
+ "type": "update",
+ "table": "scheduled_posts",
+ "values": {
+ "status": "published",
+ "data": {
+ "mediaType": "REELS",
+ "mediaUrl": "https://cdn/r.mp4",
+ "shareToFeed": true,
+ "publishedMediaId": "m-c-IG1",
+ "publishedAt": "2026-09-01T12:00:00.000Z"
+ }
+ },
+ "filters": [
+ [
+ "id",
+ "p-reel"
+ ]
+ ]
+ },
+ {
+ "type": "update",
+ "table": "scheduled_posts",
+ "values": {
+ "status": "publishing"
+ },
+ "filters": [
+ [
+ "id",
+ "p-story"
+ ],
+ [
+ "status",
+ "pending"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "accounts",
+ "columns": "id, platform, data",
+ "filters": [
+ [
+ "id",
+ "igErr"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "scheduled_posts",
+ "columns": "data",
+ "filters": [
+ [
+ "id",
+ "p-story"
+ ]
+ ]
+ },
+ {
+ "type": "update",
+ "table": "scheduled_posts",
+ "values": {
+ "status": "failed",
+ "data": {
+ "mediaType": "STORIES",
+ "mediaUrl": "https://cdn/s.mp4",
+ "error": "Processing failed: Bad video"
+ }
+ },
+ "filters": [
+ [
+ "id",
+ "p-story"
+ ]
+ ]
+ },
+ {
+ "type": "update",
+ "table": "scheduled_posts",
+ "values": {
+ "status": "publishing"
+ },
+ "filters": [
+ [
+ "id",
+ "p-expired"
+ ],
+ [
+ "status",
+ "pending"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "accounts",
+ "columns": "id, platform, data",
+ "filters": [
+ [
+ "id",
+ "igExp"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "scheduled_posts",
+ "columns": "data",
+ "filters": [
+ [
+ "id",
+ "p-expired"
+ ]
+ ]
+ },
+ {
+ "type": "update",
+ "table": "scheduled_posts",
+ "values": {
+ "status": "failed",
+ "data": {
+ "mediaType": "REELS",
+ "mediaUrl": "https://cdn/e.mp4",
+ "error": "Container expired"
+ }
+ },
+ "filters": [
+ [
+ "id",
+ "p-expired"
+ ]
+ ]
+ },
+ {
+ "type": "update",
+ "table": "scheduled_posts",
+ "values": {
+ "status": "publishing"
+ },
+ "filters": [
+ [
+ "id",
+ "p-missing"
+ ],
+ [
+ "status",
+ "pending"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "accounts",
+ "columns": "id, platform, data",
+ "filters": [
+ [
+ "id",
+ "gone"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "scheduled_posts",
+ "columns": "data",
+ "filters": [
+ [
+ "id",
+ "p-missing"
+ ]
+ ]
+ },
+ {
+ "type": "update",
+ "table": "scheduled_posts",
+ "values": {
+ "status": "failed",
+ "data": {
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn/m.jpg",
+ "error": "Account not found: gone"
+ }
+ },
+ "filters": [
+ [
+ "id",
+ "p-missing"
+ ]
+ ]
+ },
+ {
+ "type": "update",
+ "table": "scheduled_posts",
+ "values": {
+ "status": "publishing"
+ },
+ "filters": [
+ [
+ "id",
+ "p-create"
+ ],
+ [
+ "status",
+ "pending"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "accounts",
+ "columns": "id, platform, data",
+ "filters": [
+ [
+ "id",
+ "igBad"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "scheduled_posts",
+ "columns": "data",
+ "filters": [
+ [
+ "id",
+ "p-create"
+ ]
+ ]
+ },
+ {
+ "type": "update",
+ "table": "scheduled_posts",
+ "values": {
+ "status": "failed",
+ "data": {
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn/b.jpg",
+ "error": "Invalid image"
+ }
+ },
+ "filters": [
+ [
+ "id",
+ "p-create"
+ ]
+ ]
+ },
+ {
+ "type": "update",
+ "table": "scheduled_posts",
+ "values": {
+ "status": "publishing"
+ },
+ "filters": [
+ [
+ "id",
+ "p-publish"
+ ],
+ [
+ "status",
+ "pending"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "accounts",
+ "columns": "id, platform, data",
+ "filters": [
+ [
+ "id",
+ "igPub"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "scheduled_posts",
+ "columns": "data",
+ "filters": [
+ [
+ "id",
+ "p-publish"
+ ]
+ ]
+ },
+ {
+ "type": "update",
+ "table": "scheduled_posts",
+ "values": {
+ "status": "failed",
+ "data": {
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn/p.jpg",
+ "error": "Publish refused"
+ }
+ },
+ "filters": [
+ [
+ "id",
+ "p-publish"
+ ]
+ ]
+ },
+ {
+ "type": "update",
+ "table": "scheduled_posts",
+ "values": {
+ "status": "publishing"
+ },
+ "filters": [
+ [
+ "id",
+ "p-slow"
+ ],
+ [
+ "status",
+ "pending"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "accounts",
+ "columns": "id, platform, data",
+ "filters": [
+ [
+ "id",
+ "igSlow"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "scheduled_posts",
+ "columns": "data",
+ "filters": [
+ [
+ "id",
+ "p-slow"
+ ]
+ ]
+ },
+ {
+ "type": "update",
+ "table": "scheduled_posts",
+ "values": {
+ "status": "published",
+ "data": {
+ "mediaType": "REELS",
+ "mediaUrl": "https://cdn/slow.mp4",
+ "publishedMediaId": "m-c-SLOW",
+ "publishedAt": "2026-09-01T12:00:00.000Z"
+ }
+ },
+ "filters": [
+ [
+ "id",
+ "p-slow"
+ ]
+ ]
+ },
+ {
+ "type": "update",
+ "table": "scheduled_posts",
+ "values": {
+ "status": "publishing"
+ },
+ "filters": [
+ [
+ "id",
+ "p-dup"
+ ],
+ [
+ "status",
+ "pending"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "accounts",
+ "columns": "id, platform, data",
+ "filters": [
+ [
+ "id",
+ "ig1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "scheduled_posts",
+ "columns": "data",
+ "filters": [
+ [
+ "id",
+ "p-dup"
+ ]
+ ]
+ },
+ {
+ "type": "update",
+ "table": "scheduled_posts",
+ "values": {
+ "status": "published",
+ "data": {
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn/d.jpg",
+ "publishedMediaId": "m-c-IG1",
+ "publishedAt": "2026-09-01T12:00:00.000Z"
+ }
+ },
+ "filters": [
+ [
+ "id",
+ "p-dup"
+ ]
+ ]
+ },
+ {
+ "type": "update",
+ "table": "scheduled_posts",
+ "values": {
+ "status": "publishing"
+ },
+ "filters": [
+ [
+ "id",
+ "p-dup"
+ ],
+ [
+ "status",
+ "pending"
+ ]
+ ]
+ }
+ ],
+ "table": [
+ {
+ "_table": "accounts",
+ "id": "ig1",
+ "platform": "instagram",
+ "user_id": "user-1",
+ "data": {
+ "igUserId": "IG1",
+ "accessToken": "T1"
+ }
+ },
+ {
+ "_table": "accounts",
+ "id": "igErr",
+ "platform": "instagram",
+ "user_id": "user-1",
+ "data": {
+ "igUserId": "ERR",
+ "accessToken": "T2"
+ }
+ },
+ {
+ "_table": "accounts",
+ "id": "igExp",
+ "platform": "instagram",
+ "user_id": "user-1",
+ "data": {
+ "igUserId": "EXP",
+ "accessToken": "T3"
+ }
+ },
+ {
+ "_table": "accounts",
+ "id": "igBad",
+ "platform": "instagram",
+ "user_id": "user-1",
+ "data": {
+ "igUserId": "BAD",
+ "accessToken": "T4"
+ }
+ },
+ {
+ "_table": "accounts",
+ "id": "igPub",
+ "platform": "instagram",
+ "user_id": "user-1",
+ "data": {
+ "igUserId": "PUB",
+ "accessToken": "T5"
+ }
+ },
+ {
+ "_table": "accounts",
+ "id": "igSlow",
+ "platform": "instagram",
+ "user_id": "user-1",
+ "data": {
+ "igUserId": "SLOW",
+ "accessToken": "T6"
+ }
+ },
+ {
+ "_table": "scheduled_posts",
+ "id": "p-image",
+ "user_id": "user-1",
+ "account_id": "ig1",
+ "status": "published",
+ "scheduled_at": "2026-09-01T11:00:00.000Z",
+ "data": {
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn/a.jpg",
+ "caption": "Hello",
+ "publishedMediaId": "m-c-IG1",
+ "publishedAt": "2026-09-01T12:00:00.000Z"
+ }
+ },
+ {
+ "_table": "scheduled_posts",
+ "id": "p-reel",
+ "user_id": "user-1",
+ "account_id": "ig1",
+ "status": "published",
+ "scheduled_at": "2026-09-01T11:00:00.000Z",
+ "data": {
+ "mediaType": "REELS",
+ "mediaUrl": "https://cdn/r.mp4",
+ "shareToFeed": true,
+ "publishedMediaId": "m-c-IG1",
+ "publishedAt": "2026-09-01T12:00:00.000Z"
+ }
+ },
+ {
+ "_table": "scheduled_posts",
+ "id": "p-story",
+ "user_id": "user-1",
+ "account_id": "igErr",
+ "status": "failed",
+ "scheduled_at": "2026-09-01T11:00:00.000Z",
+ "data": {
+ "mediaType": "STORIES",
+ "mediaUrl": "https://cdn/s.mp4",
+ "error": "Processing failed: Bad video"
+ }
+ },
+ {
+ "_table": "scheduled_posts",
+ "id": "p-expired",
+ "user_id": "user-1",
+ "account_id": "igExp",
+ "status": "failed",
+ "scheduled_at": "2026-09-01T11:00:00.000Z",
+ "data": {
+ "mediaType": "REELS",
+ "mediaUrl": "https://cdn/e.mp4",
+ "error": "Container expired"
+ }
+ },
+ {
+ "_table": "scheduled_posts",
+ "id": "p-missing",
+ "user_id": "user-1",
+ "account_id": "gone",
+ "status": "failed",
+ "scheduled_at": "2026-09-01T11:00:00.000Z",
+ "data": {
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn/m.jpg",
+ "error": "Account not found: gone"
+ }
+ },
+ {
+ "_table": "scheduled_posts",
+ "id": "p-create",
+ "user_id": "user-1",
+ "account_id": "igBad",
+ "status": "failed",
+ "scheduled_at": "2026-09-01T11:00:00.000Z",
+ "data": {
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn/b.jpg",
+ "error": "Invalid image"
+ }
+ },
+ {
+ "_table": "scheduled_posts",
+ "id": "p-publish",
+ "user_id": "user-1",
+ "account_id": "igPub",
+ "status": "failed",
+ "scheduled_at": "2026-09-01T11:00:00.000Z",
+ "data": {
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn/p.jpg",
+ "error": "Publish refused"
+ }
+ },
+ {
+ "_table": "scheduled_posts",
+ "id": "p-slow",
+ "user_id": "user-1",
+ "account_id": "igSlow",
+ "status": "published",
+ "scheduled_at": "2026-09-01T11:00:00.000Z",
+ "data": {
+ "mediaType": "REELS",
+ "mediaUrl": "https://cdn/slow.mp4",
+ "publishedMediaId": "m-c-SLOW",
+ "publishedAt": "2026-09-01T12:00:00.000Z"
+ }
+ },
+ {
+ "_table": "scheduled_posts",
+ "id": "p-dup",
+ "user_id": "user-1",
+ "account_id": "ig1",
+ "status": "published",
+ "scheduled_at": "2026-09-01T11:00:00.000Z",
+ "data": {
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn/d.jpg",
+ "publishedMediaId": "m-c-IG1",
+ "publishedAt": "2026-09-01T12:00:00.000Z"
+ }
+ },
+ {
+ "_table": "scheduled_posts",
+ "id": "p-dup",
+ "user_id": "user-1",
+ "account_id": "ig1",
+ "status": "published",
+ "scheduled_at": "2026-09-01T11:00:00.000Z",
+ "data": {
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn/d.jpg",
+ "publishedMediaId": "m-c-IG1",
+ "publishedAt": "2026-09-01T12:00:00.000Z"
+ }
+ },
+ {
+ "_table": "scheduled_posts",
+ "id": "p-busy",
+ "user_id": "user-1",
+ "account_id": "ig1",
+ "status": "publishing",
+ "scheduled_at": "2026-09-01T11:00:00.000Z",
+ "data": {
+ "mediaType": "IMAGE"
+ }
+ },
+ {
+ "_table": "scheduled_posts",
+ "id": "p-later",
+ "user_id": "user-1",
+ "account_id": "ig1",
+ "status": "pending",
+ "scheduled_at": "2026-09-02T00:00:00.000Z",
+ "data": {
+ "mediaType": "IMAGE"
+ }
+ }
+ ]
+}
diff --git a/backend/services/fixtures/trackedContentRoutes.create.golden.json b/backend/services/fixtures/trackedContentRoutes.create.golden.json
new file mode 100644
index 0000000..e766b57
--- /dev/null
+++ b/backend/services/fixtures/trackedContentRoutes.create.golden.json
@@ -0,0 +1,304 @@
+{
+ "result": {
+ "responses": [
+ {
+ "call": "POST /tracked-content",
+ "status": 400,
+ "body": "{\"error\":\"url is required\"}"
+ },
+ {
+ "call": "POST /tracked-content",
+ "status": 400,
+ "body": "{\"error\":\"Only Reddit and YouTube URLs are supported\"}"
+ },
+ {
+ "call": "POST /tracked-content",
+ "status": 201,
+ "body": "{\"id\":\"mtim7pc04i\",\"accountId\":null,\"url\":\"https://www.youtube.com/watch?v=abc\",\"label\":\"Video\",\"category\":\"Music\",\"contentType\":\"youtube\",\"updatedAt\":\"2026-09-01T12:00:00.000Z\",\"title\":\"Watch\",\"channelTitle\":\"Ribbon\",\"channelId\":\"UC1\",\"thumbnail\":\"m\",\"publishedAt\":\"2026-08-01T10:00:00Z\",\"viewCount\":1500,\"likeCount\":40,\"commentCount\":3,\"isShort\":false,\"permalink\":\"https://www.youtube.com/watch?v=abc\",\"lastFetchedAt\":\"2026-09-01T12:00:00.000Z\"}"
+ },
+ {
+ "call": "POST /tracked-content",
+ "status": 404,
+ "body": "{\"error\":\"Reddit account not found\"}"
+ },
+ {
+ "call": "POST /tracked-content",
+ "status": 404,
+ "body": "{\"error\":\"Reddit account not found\"}"
+ },
+ {
+ "call": "POST /tracked-content",
+ "status": 201,
+ "body": "{\"id\":\"mtim7pc09\",\"accountId\":\"rd1\",\"url\":\"https://www.reddit.com/r/webdev/comments/p1/tracked/\",\"label\":\"Mine\",\"category\":\"\",\"contentType\":\"reddit\",\"createdAt\":\"2026-07-25T17:20:00.000Z\",\"updatedAt\":\"2026-09-01T12:00:00.000Z\",\"postId\":\"p1\",\"title\":\"Tracked\",\"subreddit\":\"webdev\",\"subredditPrefixed\":\"r/webdev\",\"author\":\"[deleted]\",\"score\":77,\"upvoteRatio\":0.93,\"numComments\":8,\"permalink\":\"https://reddit.com/r/webdev/comments/p1/tracked/\",\"isNsfw\":false,\"lastFetchedAt\":\"2026-09-01T12:00:00.000Z\"}"
+ },
+ {
+ "call": "POST /tracked-content",
+ "status": 201,
+ "body": "{\"id\":\"mtim7pc0di\",\"accountId\":null,\"url\":\"https://www.reddit.com/r/webdev/comments/p1/tracked/\",\"label\":\"\",\"category\":\"\",\"contentType\":\"reddit\",\"createdAt\":\"2026-07-25T17:20:00.000Z\",\"updatedAt\":\"2026-09-01T12:00:00.000Z\",\"postId\":\"p1\",\"title\":\"Tracked\",\"subreddit\":\"webdev\",\"subredditPrefixed\":\"r/webdev\",\"author\":\"[deleted]\",\"score\":77,\"upvoteRatio\":0.93,\"numComments\":8,\"permalink\":\"https://reddit.com/r/webdev/comments/p1/tracked/\",\"isNsfw\":false,\"lastFetchedAt\":\"2026-09-01T12:00:00.000Z\"}"
+ }
+ ],
+ "queries": [
+ {
+ "type": "insert",
+ "table": "tracked_posts",
+ "values": {
+ "id": "mtim7pc04i",
+ "user_id": "user-1",
+ "account_id": null,
+ "url": "https://www.youtube.com/watch?v=abc",
+ "label": "Video",
+ "category": "Music",
+ "content_type": "youtube"
+ },
+ "filters": []
+ },
+ {
+ "type": "update",
+ "table": "tracked_posts",
+ "values": {
+ "updated_at": "2026-09-01T12:00:00.000Z",
+ "data": {
+ "contentType": "youtube",
+ "title": "Watch",
+ "channelTitle": "Ribbon",
+ "channelId": "UC1",
+ "thumbnail": "m",
+ "publishedAt": "2026-08-01T10:00:00Z",
+ "viewCount": 1500,
+ "likeCount": 40,
+ "commentCount": 3,
+ "isShort": false,
+ "permalink": "https://www.youtube.com/watch?v=abc",
+ "lastFetchedAt": "2026-09-01T12:00:00.000Z"
+ }
+ },
+ "filters": [
+ [
+ "id",
+ "mtim7pc04i"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "tracked_posts",
+ "columns": "id, account_id, url, label, category, content_type, created_at, updated_at, data",
+ "filters": [
+ [
+ "id",
+ "mtim7pc04i"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "accounts",
+ "columns": "id, platform, data",
+ "filters": [
+ [
+ "id",
+ "yt1"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "accounts",
+ "columns": "id, platform, data",
+ "filters": [
+ [
+ "id",
+ "missing"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "accounts",
+ "columns": "id, platform, data",
+ "filters": [
+ [
+ "id",
+ "rd1"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "insert",
+ "table": "tracked_posts",
+ "values": {
+ "id": "mtim7pc09",
+ "user_id": "user-1",
+ "account_id": "rd1",
+ "url": "https://www.reddit.com/r/webdev/comments/p1/tracked/",
+ "label": "Mine",
+ "category": "",
+ "content_type": "reddit"
+ },
+ "filters": []
+ },
+ {
+ "type": "update",
+ "table": "tracked_posts",
+ "values": {
+ "updated_at": "2026-09-01T12:00:00.000Z",
+ "data": {
+ "postId": "p1",
+ "title": "Tracked",
+ "subreddit": "webdev",
+ "subredditPrefixed": "r/webdev",
+ "author": "[deleted]",
+ "score": 77,
+ "upvoteRatio": 0.93,
+ "numComments": 8,
+ "permalink": "https://reddit.com/r/webdev/comments/p1/tracked/",
+ "isNsfw": false,
+ "createdAt": "2026-07-25T17:20:00.000Z",
+ "lastFetchedAt": "2026-09-01T12:00:00.000Z"
+ }
+ },
+ "filters": [
+ [
+ "id",
+ "mtim7pc09"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "tracked_posts",
+ "columns": "id, account_id, url, label, category, content_type, created_at, updated_at, data",
+ "filters": [
+ [
+ "id",
+ "mtim7pc09"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "insert",
+ "table": "tracked_posts",
+ "values": {
+ "id": "mtim7pc0di",
+ "user_id": "user-1",
+ "account_id": null,
+ "url": "https://www.reddit.com/r/webdev/comments/p1/tracked/",
+ "label": "",
+ "category": "",
+ "content_type": "reddit"
+ },
+ "filters": []
+ },
+ {
+ "type": "update",
+ "table": "tracked_posts",
+ "values": {
+ "updated_at": "2026-09-01T12:00:00.000Z",
+ "data": {
+ "postId": "p1",
+ "title": "Tracked",
+ "subreddit": "webdev",
+ "subredditPrefixed": "r/webdev",
+ "author": "[deleted]",
+ "score": 77,
+ "upvoteRatio": 0.93,
+ "numComments": 8,
+ "permalink": "https://reddit.com/r/webdev/comments/p1/tracked/",
+ "isNsfw": false,
+ "createdAt": "2026-07-25T17:20:00.000Z",
+ "lastFetchedAt": "2026-09-01T12:00:00.000Z"
+ }
+ },
+ "filters": [
+ [
+ "id",
+ "mtim7pc0di"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "tracked_posts",
+ "columns": "id, account_id, url, label, category, content_type, created_at, updated_at, data",
+ "filters": [
+ [
+ "id",
+ "mtim7pc0di"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ }
+ ],
+ "requests": [
+ {
+ "url": "https://www.googleapis.com/youtube/v3/videos?part=snippet%2Cstatistics&id=abc&key=YTKEY",
+ "method": "GET"
+ },
+ {
+ "url": "https://www.reddit.com/r/webdev/comments/p1/tracked.json",
+ "method": "GET",
+ "headers": {
+ "User-Agent": "script:twiligent:v1.0 (by /u/spacesdrive)",
+ "Accept": "application/json",
+ "Cookie": "reddit_session=COOKIE"
+ }
+ },
+ {
+ "url": "https://www.reddit.com/r/webdev/comments/p1/tracked.json",
+ "method": "GET",
+ "headers": {
+ "User-Agent": "script:twiligent:v1.0 (by /u/spacesdrive)",
+ "Accept": "application/json"
+ }
+ }
+ ],
+ "logLines": []
+ },
+ "withoutKey": {
+ "responses": [
+ {
+ "call": "POST /tracked-content",
+ "status": 400,
+ "body": "{\"error\":\"YouTube API key not configured on this server\"}"
+ }
+ ],
+ "queries": [],
+ "requests": [],
+ "logLines": []
+ }
+}
diff --git a/backend/services/fixtures/trackedContentRoutes.refresh.golden.json b/backend/services/fixtures/trackedContentRoutes.refresh.golden.json
new file mode 100644
index 0000000..6f8a4ab
--- /dev/null
+++ b/backend/services/fixtures/trackedContentRoutes.refresh.golden.json
@@ -0,0 +1,424 @@
+{
+ "result": {
+ "responses": [
+ {
+ "call": "GET /tracked-content",
+ "status": 200,
+ "body": "[{\"id\":\"t-reddit\",\"accountId\":\"rd1\",\"url\":\"https://www.reddit.com/r/webdev/comments/p1/tracked/\",\"label\":\"\",\"category\":\"\",\"contentType\":\"reddit\",\"createdAt\":\"2026-08-01T00:00:00Z\",\"updatedAt\":\"2026-08-01T00:00:00Z\",\"title\":\"Old\",\"manualViews\":5},{\"id\":\"t-youtube\",\"accountId\":null,\"url\":\"https://www.youtube.com/watch?v=abc\",\"label\":\"\",\"category\":\"\",\"contentType\":\"youtube\",\"createdAt\":\"2026-08-01T00:00:00Z\",\"updatedAt\":\"2026-08-01T00:00:00Z\",\"title\":\"Video\"},{\"id\":\"t-orphan\",\"accountId\":\"gone\",\"url\":\"https://www.reddit.com/r/webdev/comments/p1/tracked/\",\"label\":\"\",\"category\":\"\",\"contentType\":\"reddit\",\"createdAt\":\"2026-08-01T00:00:00Z\",\"updatedAt\":\"2026-08-01T00:00:00Z\"}]"
+ },
+ {
+ "call": "POST /tracked-content/t-reddit/refresh",
+ "status": 200,
+ "body": "{\"id\":\"t-reddit\",\"accountId\":\"rd1\",\"url\":\"https://www.reddit.com/r/webdev/comments/p1/tracked/\",\"label\":\"\",\"category\":\"\",\"contentType\":\"reddit\",\"createdAt\":\"2026-07-25T17:20:00.000Z\",\"updatedAt\":\"2026-09-01T12:00:00.000Z\",\"title\":\"Tracked\",\"manualViews\":5,\"postId\":\"p1\",\"subreddit\":\"webdev\",\"subredditPrefixed\":\"r/webdev\",\"author\":\"[deleted]\",\"score\":77,\"upvoteRatio\":0.93,\"numComments\":8,\"permalink\":\"https://reddit.com/r/webdev/comments/p1/tracked/\",\"isNsfw\":false,\"lastFetchedAt\":\"2026-09-01T12:00:00.000Z\"}"
+ },
+ {
+ "call": "POST /tracked-content/t-orphan/refresh",
+ "status": 200,
+ "body": "{\"id\":\"t-orphan\",\"accountId\":\"gone\",\"url\":\"https://www.reddit.com/r/webdev/comments/p1/tracked/\",\"label\":\"\",\"category\":\"\",\"contentType\":\"reddit\",\"createdAt\":\"2026-07-25T17:20:00.000Z\",\"updatedAt\":\"2026-09-01T12:00:00.000Z\",\"postId\":\"p1\",\"title\":\"Tracked\",\"subreddit\":\"webdev\",\"subredditPrefixed\":\"r/webdev\",\"author\":\"[deleted]\",\"score\":77,\"upvoteRatio\":0.93,\"numComments\":8,\"permalink\":\"https://reddit.com/r/webdev/comments/p1/tracked/\",\"isNsfw\":false,\"lastFetchedAt\":\"2026-09-01T12:00:00.000Z\"}"
+ },
+ {
+ "call": "POST /tracked-content/t-youtube/refresh",
+ "status": 200,
+ "body": "{\"id\":\"t-youtube\",\"accountId\":null,\"url\":\"https://www.youtube.com/watch?v=abc\",\"label\":\"\",\"category\":\"\",\"contentType\":\"youtube\",\"createdAt\":\"2026-08-01T00:00:00Z\",\"updatedAt\":\"2026-09-01T12:00:00.000Z\",\"title\":\"Watch\",\"channelTitle\":\"Ribbon\",\"channelId\":\"UC1\",\"thumbnail\":\"m\",\"publishedAt\":\"2026-08-01T10:00:00Z\",\"viewCount\":1500,\"likeCount\":40,\"commentCount\":3,\"isShort\":false,\"permalink\":\"https://www.youtube.com/watch?v=abc\",\"lastFetchedAt\":\"2026-09-01T12:00:00.000Z\"}"
+ },
+ {
+ "call": "POST /tracked-content/nope/refresh",
+ "status": 404,
+ "body": "{\"error\":\"Tracked content not found\"}"
+ },
+ {
+ "call": "DELETE /tracked-content/t-youtube",
+ "status": 200,
+ "body": "{\"success\":true}"
+ },
+ {
+ "call": "DELETE /tracked-content/t-youtube",
+ "status": 404,
+ "body": "{\"error\":\"Tracked content not found\"}"
+ }
+ ],
+ "queries": [
+ {
+ "type": "select",
+ "table": "tracked_posts",
+ "columns": "id, account_id, url, label, category, content_type, created_at, updated_at, data",
+ "filters": [
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "tracked_posts",
+ "columns": "id, account_id, url, label, category, content_type, created_at, updated_at, data",
+ "filters": [
+ [
+ "id",
+ "t-reddit"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "accounts",
+ "columns": "id, platform, data",
+ "filters": [
+ [
+ "id",
+ "rd1"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "tracked_posts",
+ "columns": "data",
+ "filters": [
+ [
+ "id",
+ "t-reddit"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "update",
+ "table": "tracked_posts",
+ "values": {
+ "data": {
+ "title": "Tracked",
+ "manualViews": 5,
+ "postId": "p1",
+ "subreddit": "webdev",
+ "subredditPrefixed": "r/webdev",
+ "author": "[deleted]",
+ "score": 77,
+ "upvoteRatio": 0.93,
+ "numComments": 8,
+ "permalink": "https://reddit.com/r/webdev/comments/p1/tracked/",
+ "isNsfw": false,
+ "createdAt": "2026-07-25T17:20:00.000Z",
+ "lastFetchedAt": "2026-09-01T12:00:00.000Z"
+ },
+ "updated_at": "2026-09-01T12:00:00.000Z"
+ },
+ "filters": [
+ [
+ "id",
+ "t-reddit"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "tracked_posts",
+ "columns": "id, account_id, url, label, category, content_type, created_at, updated_at, data",
+ "filters": [
+ [
+ "id",
+ "t-reddit"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "tracked_posts",
+ "columns": "id, account_id, url, label, category, content_type, created_at, updated_at, data",
+ "filters": [
+ [
+ "id",
+ "t-orphan"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "accounts",
+ "columns": "id, platform, data",
+ "filters": [
+ [
+ "id",
+ "gone"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "tracked_posts",
+ "columns": "data",
+ "filters": [
+ [
+ "id",
+ "t-orphan"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "update",
+ "table": "tracked_posts",
+ "values": {
+ "data": {
+ "postId": "p1",
+ "title": "Tracked",
+ "subreddit": "webdev",
+ "subredditPrefixed": "r/webdev",
+ "author": "[deleted]",
+ "score": 77,
+ "upvoteRatio": 0.93,
+ "numComments": 8,
+ "permalink": "https://reddit.com/r/webdev/comments/p1/tracked/",
+ "isNsfw": false,
+ "createdAt": "2026-07-25T17:20:00.000Z",
+ "lastFetchedAt": "2026-09-01T12:00:00.000Z"
+ },
+ "updated_at": "2026-09-01T12:00:00.000Z"
+ },
+ "filters": [
+ [
+ "id",
+ "t-orphan"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "tracked_posts",
+ "columns": "id, account_id, url, label, category, content_type, created_at, updated_at, data",
+ "filters": [
+ [
+ "id",
+ "t-orphan"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "tracked_posts",
+ "columns": "id, account_id, url, label, category, content_type, created_at, updated_at, data",
+ "filters": [
+ [
+ "id",
+ "t-youtube"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "tracked_posts",
+ "columns": "data",
+ "filters": [
+ [
+ "id",
+ "t-youtube"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "update",
+ "table": "tracked_posts",
+ "values": {
+ "data": {
+ "title": "Watch",
+ "contentType": "youtube",
+ "channelTitle": "Ribbon",
+ "channelId": "UC1",
+ "thumbnail": "m",
+ "publishedAt": "2026-08-01T10:00:00Z",
+ "viewCount": 1500,
+ "likeCount": 40,
+ "commentCount": 3,
+ "isShort": false,
+ "permalink": "https://www.youtube.com/watch?v=abc",
+ "lastFetchedAt": "2026-09-01T12:00:00.000Z"
+ },
+ "updated_at": "2026-09-01T12:00:00.000Z"
+ },
+ "filters": [
+ [
+ "id",
+ "t-youtube"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "tracked_posts",
+ "columns": "id, account_id, url, label, category, content_type, created_at, updated_at, data",
+ "filters": [
+ [
+ "id",
+ "t-youtube"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "tracked_posts",
+ "columns": "id, account_id, url, label, category, content_type, created_at, updated_at, data",
+ "filters": [
+ [
+ "id",
+ "nope"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "tracked_posts",
+ "columns": "id, account_id, url, label, category, content_type, created_at, updated_at, data",
+ "filters": [
+ [
+ "id",
+ "t-youtube"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "delete",
+ "table": "tracked_posts",
+ "filters": [
+ [
+ "id",
+ "t-youtube"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "tracked_posts",
+ "columns": "id, account_id, url, label, category, content_type, created_at, updated_at, data",
+ "filters": [
+ [
+ "id",
+ "t-youtube"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ }
+ ],
+ "requests": [
+ {
+ "url": "https://www.reddit.com/r/webdev/comments/p1/tracked.json",
+ "method": "GET",
+ "headers": {
+ "User-Agent": "script:twiligent:v1.0 (by /u/spacesdrive)",
+ "Accept": "application/json",
+ "Cookie": "reddit_session=COOKIE"
+ }
+ },
+ {
+ "url": "https://www.reddit.com/r/webdev/comments/p1/tracked.json",
+ "method": "GET",
+ "headers": {
+ "User-Agent": "script:twiligent:v1.0 (by /u/spacesdrive)",
+ "Accept": "application/json"
+ }
+ },
+ {
+ "url": "https://www.googleapis.com/youtube/v3/videos?part=snippet%2Cstatistics&id=abc&key=YTKEY",
+ "method": "GET"
+ }
+ ],
+ "logLines": []
+ },
+ "withoutKey": {
+ "responses": [
+ {
+ "call": "POST /tracked-content/t-youtube/refresh",
+ "status": 400,
+ "body": "{\"error\":\"YouTube API key not configured on this server\"}"
+ }
+ ],
+ "queries": [
+ {
+ "type": "select",
+ "table": "tracked_posts",
+ "columns": "id, account_id, url, label, category, content_type, created_at, updated_at, data",
+ "filters": [
+ [
+ "id",
+ "t-youtube"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ }
+ ],
+ "requests": [],
+ "logLines": []
+ }
+}
diff --git a/backend/services/fixtures/trackedContentRoutes.update.golden.json b/backend/services/fixtures/trackedContentRoutes.update.golden.json
new file mode 100644
index 0000000..f65ed4f
--- /dev/null
+++ b/backend/services/fixtures/trackedContentRoutes.update.golden.json
@@ -0,0 +1,579 @@
+{
+ "responses": [
+ {
+ "call": "PUT /tracked-content/nope",
+ "status": 404,
+ "body": "{\"error\":\"Tracked content not found\"}"
+ },
+ {
+ "call": "PUT /tracked-content/t-youtube",
+ "status": 400,
+ "body": "{\"error\":\"YouTube view counts are fetched automatically and cannot be set by hand\"}"
+ },
+ {
+ "call": "PUT /tracked-content/t-youtube",
+ "status": 400,
+ "body": "{\"error\":\"Images can only be attached to Reddit posts\"}"
+ },
+ {
+ "call": "PUT /tracked-content/t-reddit",
+ "status": 200,
+ "body": "{\"id\":\"t-reddit\",\"accountId\":\"rd1\",\"url\":\"https://www.reddit.com/r/webdev/comments/p1/tracked/\",\"label\":\"\",\"category\":\"\",\"contentType\":\"reddit\",\"createdAt\":\"2026-08-01T00:00:00Z\",\"updatedAt\":\"2026-09-01T12:00:00.000Z\",\"title\":\"Old\",\"manualViews\":null}"
+ },
+ {
+ "call": "PUT /tracked-content/t-reddit",
+ "status": 200,
+ "body": "{\"id\":\"t-reddit\",\"accountId\":\"rd1\",\"url\":\"https://www.reddit.com/r/webdev/comments/p1/tracked/\",\"label\":\"\",\"category\":\"\",\"contentType\":\"reddit\",\"createdAt\":\"2026-08-01T00:00:00Z\",\"updatedAt\":\"2026-09-01T12:00:00.000Z\",\"title\":\"Old\",\"manualViews\":12}"
+ },
+ {
+ "call": "PUT /tracked-content/t-reddit",
+ "status": 400,
+ "body": "{\"error\":\"Views must be a whole number of 0 or more\"}"
+ },
+ {
+ "call": "PUT /tracked-content/t-reddit",
+ "status": 400,
+ "body": "{\"error\":\"Views must be a whole number of 0 or more\"}"
+ },
+ {
+ "call": "PUT /tracked-content/t-reddit",
+ "status": 200,
+ "body": "{\"id\":\"t-reddit\",\"accountId\":\"rd1\",\"url\":\"https://www.reddit.com/r/webdev/comments/p1/tracked/\",\"label\":\"\",\"category\":\"\",\"contentType\":\"reddit\",\"createdAt\":\"2026-08-01T00:00:00Z\",\"updatedAt\":\"2026-09-01T12:00:00.000Z\",\"title\":\"Old\",\"manualViews\":12,\"imageUrl\":\"https://img/a%20b.png\"}"
+ },
+ {
+ "call": "PUT /tracked-content/t-reddit",
+ "status": 200,
+ "body": "{\"id\":\"t-reddit\",\"accountId\":\"rd1\",\"url\":\"https://www.reddit.com/r/webdev/comments/p1/tracked/\",\"label\":\"\",\"category\":\"\",\"contentType\":\"reddit\",\"createdAt\":\"2026-08-01T00:00:00Z\",\"updatedAt\":\"2026-09-01T12:00:00.000Z\",\"title\":\"Old\",\"manualViews\":12,\"imageUrl\":null}"
+ },
+ {
+ "call": "PUT /tracked-content/t-reddit",
+ "status": 400,
+ "body": "{\"error\":\"Image must be an https URL returned by the uploader\"}"
+ },
+ {
+ "call": "PUT /tracked-content/t-reddit",
+ "status": 400,
+ "body": "{\"error\":\"Image must be an https URL returned by the uploader\"}"
+ },
+ {
+ "call": "PUT /tracked-content/t-reddit",
+ "status": 200,
+ "body": "{\"id\":\"t-reddit\",\"accountId\":null,\"url\":\"https://www.reddit.com/r/webdev/comments/p1/tracked/\",\"label\":\"New\",\"category\":\"Cat\",\"contentType\":\"reddit\",\"createdAt\":\"2026-08-01T00:00:00Z\",\"updatedAt\":\"2026-09-01T12:00:00.000Z\",\"title\":\"Old\",\"manualViews\":7,\"imageUrl\":null}"
+ },
+ {
+ "call": "PUT /tracked-content/t-youtube",
+ "status": 200,
+ "body": "{\"id\":\"t-youtube\",\"accountId\":null,\"url\":\"https://www.youtube.com/watch?v=abc\",\"label\":\"Only label\",\"category\":\"\",\"contentType\":\"youtube\",\"createdAt\":\"2026-08-01T00:00:00Z\",\"updatedAt\":\"2026-09-01T12:00:00.000Z\",\"title\":\"Video\"}"
+ }
+ ],
+ "queries": [
+ {
+ "type": "select",
+ "table": "tracked_posts",
+ "columns": "id, account_id, url, label, category, content_type, created_at, updated_at, data",
+ "filters": [
+ [
+ "id",
+ "nope"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "tracked_posts",
+ "columns": "id, account_id, url, label, category, content_type, created_at, updated_at, data",
+ "filters": [
+ [
+ "id",
+ "t-youtube"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "tracked_posts",
+ "columns": "id, account_id, url, label, category, content_type, created_at, updated_at, data",
+ "filters": [
+ [
+ "id",
+ "t-youtube"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "tracked_posts",
+ "columns": "id, account_id, url, label, category, content_type, created_at, updated_at, data",
+ "filters": [
+ [
+ "id",
+ "t-reddit"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "tracked_posts",
+ "columns": "data",
+ "filters": [
+ [
+ "id",
+ "t-reddit"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "update",
+ "table": "tracked_posts",
+ "values": {
+ "data": {
+ "title": "Old",
+ "manualViews": null
+ },
+ "updated_at": "2026-09-01T12:00:00.000Z"
+ },
+ "filters": [
+ [
+ "id",
+ "t-reddit"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "tracked_posts",
+ "columns": "id, account_id, url, label, category, content_type, created_at, updated_at, data",
+ "filters": [
+ [
+ "id",
+ "t-reddit"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "tracked_posts",
+ "columns": "id, account_id, url, label, category, content_type, created_at, updated_at, data",
+ "filters": [
+ [
+ "id",
+ "t-reddit"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "tracked_posts",
+ "columns": "data",
+ "filters": [
+ [
+ "id",
+ "t-reddit"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "update",
+ "table": "tracked_posts",
+ "values": {
+ "data": {
+ "title": "Old",
+ "manualViews": 12
+ },
+ "updated_at": "2026-09-01T12:00:00.000Z"
+ },
+ "filters": [
+ [
+ "id",
+ "t-reddit"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "tracked_posts",
+ "columns": "id, account_id, url, label, category, content_type, created_at, updated_at, data",
+ "filters": [
+ [
+ "id",
+ "t-reddit"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "tracked_posts",
+ "columns": "id, account_id, url, label, category, content_type, created_at, updated_at, data",
+ "filters": [
+ [
+ "id",
+ "t-reddit"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "tracked_posts",
+ "columns": "id, account_id, url, label, category, content_type, created_at, updated_at, data",
+ "filters": [
+ [
+ "id",
+ "t-reddit"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "tracked_posts",
+ "columns": "id, account_id, url, label, category, content_type, created_at, updated_at, data",
+ "filters": [
+ [
+ "id",
+ "t-reddit"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "tracked_posts",
+ "columns": "data",
+ "filters": [
+ [
+ "id",
+ "t-reddit"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "update",
+ "table": "tracked_posts",
+ "values": {
+ "data": {
+ "title": "Old",
+ "manualViews": 12,
+ "imageUrl": "https://img/a%20b.png"
+ },
+ "updated_at": "2026-09-01T12:00:00.000Z"
+ },
+ "filters": [
+ [
+ "id",
+ "t-reddit"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "tracked_posts",
+ "columns": "id, account_id, url, label, category, content_type, created_at, updated_at, data",
+ "filters": [
+ [
+ "id",
+ "t-reddit"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "tracked_posts",
+ "columns": "id, account_id, url, label, category, content_type, created_at, updated_at, data",
+ "filters": [
+ [
+ "id",
+ "t-reddit"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "tracked_posts",
+ "columns": "data",
+ "filters": [
+ [
+ "id",
+ "t-reddit"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "update",
+ "table": "tracked_posts",
+ "values": {
+ "data": {
+ "title": "Old",
+ "manualViews": 12,
+ "imageUrl": null
+ },
+ "updated_at": "2026-09-01T12:00:00.000Z"
+ },
+ "filters": [
+ [
+ "id",
+ "t-reddit"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "tracked_posts",
+ "columns": "id, account_id, url, label, category, content_type, created_at, updated_at, data",
+ "filters": [
+ [
+ "id",
+ "t-reddit"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "tracked_posts",
+ "columns": "id, account_id, url, label, category, content_type, created_at, updated_at, data",
+ "filters": [
+ [
+ "id",
+ "t-reddit"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "tracked_posts",
+ "columns": "id, account_id, url, label, category, content_type, created_at, updated_at, data",
+ "filters": [
+ [
+ "id",
+ "t-reddit"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "tracked_posts",
+ "columns": "data",
+ "filters": [
+ [
+ "id",
+ "t-reddit"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "update",
+ "table": "tracked_posts",
+ "values": {
+ "data": {
+ "title": "Old",
+ "manualViews": 7,
+ "imageUrl": null
+ },
+ "updated_at": "2026-09-01T12:00:00.000Z"
+ },
+ "filters": [
+ [
+ "id",
+ "t-reddit"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "tracked_posts",
+ "columns": "id, account_id, url, label, category, content_type, created_at, updated_at, data",
+ "filters": [
+ [
+ "id",
+ "t-reddit"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "update",
+ "table": "tracked_posts",
+ "values": {
+ "updated_at": "2026-09-01T12:00:00.000Z",
+ "label": "New",
+ "category": "Cat",
+ "account_id": null
+ },
+ "filters": [
+ [
+ "id",
+ "t-reddit"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "tracked_posts",
+ "columns": "id, account_id, url, label, category, content_type, created_at, updated_at, data",
+ "filters": [
+ [
+ "id",
+ "t-reddit"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "tracked_posts",
+ "columns": "id, account_id, url, label, category, content_type, created_at, updated_at, data",
+ "filters": [
+ [
+ "id",
+ "t-youtube"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "update",
+ "table": "tracked_posts",
+ "values": {
+ "updated_at": "2026-09-01T12:00:00.000Z",
+ "label": "Only label"
+ },
+ "filters": [
+ [
+ "id",
+ "t-youtube"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "tracked_posts",
+ "columns": "id, account_id, url, label, category, content_type, created_at, updated_at, data",
+ "filters": [
+ [
+ "id",
+ "t-youtube"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ }
+ ],
+ "requests": [],
+ "logLines": []
+}
diff --git a/backend/services/instagram.test.js b/backend/services/instagram.test.js
index 41aacdd..5ca3d7b 100644
--- a/backend/services/instagram.test.js
+++ b/backend/services/instagram.test.js
@@ -68,22 +68,22 @@ describe('extractInstagramViews', () => {
describe('normalizeInstagramMedia', () => {
test('reel keeps its cover as the thumbnail and never uses the video file', () => {
- const m = normalizeInstagramMedia({
+ const item = normalizeInstagramMedia({
id: '1', media_type: 'VIDEO', media_product_type: 'REELS',
media_url: 'https://cdn/video.mp4', like_count: 44, comments_count: 6,
insights: viewsInsight(900),
});
- assert.equal(m.contentType, 'reel');
- assert.equal(m.thumbnailUrl, '');
- assert.equal(m.viewCount, 900);
- assert.equal(m.likeCount, 44);
+ assert.equal(item.contentType, 'reel');
+ assert.equal(item.thumbnailUrl, '');
+ assert.equal(item.viewCount, 900);
+ assert.equal(item.likeCount, 44);
});
test('image post uses media_url as the thumbnail', () => {
- const m = normalizeInstagramMedia({ id: '2', media_type: 'IMAGE', media_product_type: 'FEED', media_url: 'https://cdn/img.jpg' });
- assert.equal(m.contentType, 'post');
- assert.equal(m.thumbnailUrl, 'https://cdn/img.jpg');
- assert.equal(m.viewCount, null);
+ const item = normalizeInstagramMedia({ id: '2', media_type: 'IMAGE', media_product_type: 'FEED', media_url: 'https://cdn/img.jpg' });
+ assert.equal(item.contentType, 'post');
+ assert.equal(item.thumbnailUrl, 'https://cdn/img.jpg');
+ assert.equal(item.viewCount, null);
});
});
@@ -137,38 +137,38 @@ describe('content type tracking', () => {
];
test('summarizeContentTypes counts each item exactly once', () => {
- const s = summarizeContentTypes(media);
- assert.equal(s.reel.count + s.post.count + s.video.count, media.length);
- assert.deepEqual(s.reel, { count: 2, likes: 55, comments: 14, views: 1000, viewsReported: 1 });
- assert.deepEqual(s.post, { count: 1, likes: 2, comments: 0, views: 50, viewsReported: 1 });
- assert.deepEqual(s.video, { count: 1, likes: 7, comments: 1, views: 300, viewsReported: 1 });
+ const summary = summarizeContentTypes(media);
+ assert.equal(summary.reel.count + summary.post.count + summary.video.count, media.length);
+ assert.deepEqual(summary.reel, { count: 2, likes: 55, comments: 14, views: 1000, viewsReported: 1 });
+ assert.deepEqual(summary.post, { count: 1, likes: 2, comments: 0, views: 50, viewsReported: 1 });
+ assert.deepEqual(summary.video, { count: 1, likes: 7, comments: 1, views: 300, viewsReported: 1 });
});
test('summarizeContentTypes always returns all three types', () => {
- const s = summarizeContentTypes([]);
- assert.deepEqual(Object.keys(s), ['reel', 'post', 'video']);
- assert.equal(s.reel.count, 0);
+ const summary = summarizeContentTypes([]);
+ assert.deepEqual(Object.keys(summary), ['reel', 'post', 'video']);
+ assert.equal(summary.reel.count, 0);
});
test('computeInstagramAnalytics splits counts and views by type without double counting', () => {
- const a = computeInstagramAnalytics({ followersCount: 100, mediaCount: 4 }, media);
- const { reel, post, video } = a.contentTypeStats;
+ const analytics = computeInstagramAnalytics({ followersCount: 100, mediaCount: 4 }, media);
+ const { reel, post, video } = analytics.contentTypeStats;
assert.equal(reel.count, 2);
assert.equal(post.count, 1);
assert.equal(video.count, 1);
assert.equal(reel.totalViews, 1000);
assert.equal(reel.avgViews, 1000);
- assert.equal(a.totalViews, reel.totalViews + post.totalViews + video.totalViews);
- assert.equal(a.totalLikes, reel.totalLikes + post.totalLikes + video.totalLikes);
- assert.equal(a.mediaWithViews, 3);
- assert.equal(a.avgViews, Math.round(1350 / 3));
+ assert.equal(analytics.totalViews, reel.totalViews + post.totalViews + video.totalViews);
+ assert.equal(analytics.totalLikes, reel.totalLikes + post.totalLikes + video.totalLikes);
+ assert.equal(analytics.mediaWithViews, 3);
+ assert.equal(analytics.avgViews, Math.round(1350 / 3));
});
test('computeInstagramAnalytics returns empty type stats with no media', () => {
- const a = computeInstagramAnalytics({ mediaCount: 0 }, []);
- assert.equal(a.totalViews, 0);
- assert.equal(a.contentTypeStats.reel.count, 0);
- assert.equal(a.contentTypeStats.video.avgViews, 0);
+ const analytics = computeInstagramAnalytics({ mediaCount: 0 }, []);
+ assert.equal(analytics.totalViews, 0);
+ assert.equal(analytics.contentTypeStats.reel.count, 0);
+ assert.equal(analytics.contentTypeStats.video.avgViews, 0);
});
});
diff --git a/backend/services/trackedContent.js b/backend/services/trackedContent.js
new file mode 100644
index 0000000..3cdf92e
--- /dev/null
+++ b/backend/services/trackedContent.js
@@ -0,0 +1,36 @@
+export function detectContentType(url) {
+ const lower = (url || '').toLowerCase();
+ if (lower.includes('reddit.com') || lower.includes('redd.it')) return 'reddit';
+ if (lower.includes('youtube.com') || lower.includes('youtu.be')) return 'youtube';
+ return null;
+}
+
+// reddit dropped view_count in 2018 so views are typed in; a youtube count is never overridden
+export function manualViewsPatch(manualViews, isYouTube) {
+ if (isYouTube) return { error: 'YouTube view counts are fetched automatically and cannot be set by hand' };
+ if (manualViews === null || manualViews === '') return { patch: { manualViews: null } };
+
+ const views = Number(manualViews);
+ if (!Number.isInteger(views) || views < 0) return { error: 'Views must be a whole number of 0 or more' };
+ return { patch: { manualViews: views } };
+}
+
+function parseUrl(value) {
+ try {
+ return new URL(String(value));
+ } catch {
+ // anything the URL parser rejects is not a usable image address
+ return null;
+ }
+}
+
+// reddit json has no thumbnail, so the browser uploads one; youtube thumbnails stay untouched
+export function imageUrlPatch(imageUrl, isYouTube) {
+ if (isYouTube) return { error: 'Images can only be attached to Reddit posts' };
+ if (imageUrl === null || imageUrl === '') return { patch: { imageUrl: null } };
+
+ const parsed = parseUrl(imageUrl);
+ // https only: the value goes straight into an img src, so javascript: and data: urls are refused
+ if (!parsed || parsed.protocol !== 'https:') return { error: 'Image must be an https URL returned by the uploader' };
+ return { patch: { imageUrl: parsed.toString() } };
+}
diff --git a/backend/services/trackedContent.test.js b/backend/services/trackedContent.test.js
new file mode 100644
index 0000000..9d4eb2a
--- /dev/null
+++ b/backend/services/trackedContent.test.js
@@ -0,0 +1,61 @@
+import { test, describe } from 'node:test';
+import assert from 'node:assert/strict';
+import { detectContentType, manualViewsPatch, imageUrlPatch } from './trackedContent.js';
+
+describe('detectContentType', () => {
+ test('recognises reddit and youtube links in any case', () => {
+ assert.equal(detectContentType('https://www.Reddit.com/r/x/comments/1'), 'reddit');
+ assert.equal(detectContentType('https://redd.it/abc'), 'reddit');
+ assert.equal(detectContentType('https://youtu.be/xyz'), 'youtube');
+ assert.equal(detectContentType('https://www.youtube.com/watch?v=1'), 'youtube');
+ });
+
+ test('anything else is unsupported', () => {
+ assert.equal(detectContentType('https://example.com'), null);
+ assert.equal(detectContentType(''), null);
+ assert.equal(detectContentType(undefined), null);
+ });
+});
+
+describe('manualViewsPatch', () => {
+ test('youtube items refuse manual views', () => {
+ assert.deepEqual(manualViewsPatch(10, true), { error: 'YouTube view counts are fetched automatically and cannot be set by hand' });
+ });
+
+ test('empty values clear the count', () => {
+ assert.deepEqual(manualViewsPatch(null, false), { patch: { manualViews: null } });
+ assert.deepEqual(manualViewsPatch('', false), { patch: { manualViews: null } });
+ });
+
+ test('whole numbers of zero or more are stored as numbers', () => {
+ assert.deepEqual(manualViewsPatch('42', false), { patch: { manualViews: 42 } });
+ assert.deepEqual(manualViewsPatch(0, false), { patch: { manualViews: 0 } });
+ });
+
+ test('fractions, negatives and text are refused', () => {
+ for (const value of ['1.5', -1, 'many']) {
+ assert.deepEqual(manualViewsPatch(value, false), { error: 'Views must be a whole number of 0 or more' });
+ }
+ });
+});
+
+describe('imageUrlPatch', () => {
+ test('youtube items refuse images', () => {
+ assert.deepEqual(imageUrlPatch('https://x/y.png', true), { error: 'Images can only be attached to Reddit posts' });
+ });
+
+ test('empty values clear the image', () => {
+ assert.deepEqual(imageUrlPatch(null, false), { patch: { imageUrl: null } });
+ assert.deepEqual(imageUrlPatch('', false), { patch: { imageUrl: null } });
+ });
+
+ test('https urls are stored normalised', () => {
+ assert.deepEqual(imageUrlPatch('https://res.cloudinary.com/a b.png', false), { patch: { imageUrl: 'https://res.cloudinary.com/a%20b.png' } });
+ });
+
+ test('other schemes and unparsable values are refused', () => {
+ for (const value of ['http://x/y.png', 'javascript:alert(1)', 'data:image/png;base64,AA', 'not a url']) {
+ assert.deepEqual(imageUrlPatch(value, false), { error: 'Image must be an https URL returned by the uploader' });
+ }
+ });
+});
diff --git a/backend/services/youtubeLibrary.js b/backend/services/youtubeLibrary.js
new file mode 100644
index 0000000..4797aae
--- /dev/null
+++ b/backend/services/youtubeLibrary.js
@@ -0,0 +1,74 @@
+import { DAY_MS } from './analyticsMath.js';
+
+// a channel without a creation date is treated as a year old
+export function channelMetrics(account) {
+ const channelAge = account.publishedAt
+ ? Math.floor((Date.now() - new Date(account.publishedAt).getTime()) / DAY_MS)
+ : 365;
+ const viewsPerSub = account.subscriberCount > 0 ? (account.viewCount / account.subscriberCount).toFixed(1) : 0;
+ const subsPerView = account.viewCount > 0 ? (account.subscriberCount / account.viewCount * 100).toFixed(4) : 0;
+ const avgViewsPerVideo = account.videoCount > 0 ? Math.round(account.viewCount / account.videoCount) : 0;
+ const avgSubGainPerDay = channelAge > 0 ? Math.round(account.subscriberCount / channelAge) : 0;
+ const avgViewsPerDay = channelAge > 0 ? Math.round(account.viewCount / channelAge) : 0;
+
+ return {
+ channelAge,
+ channelAgeYears: (channelAge / 365).toFixed(1),
+ viewsPerSubscriber: parseFloat(viewsPerSub),
+ subscriberToViewRatio: parseFloat(subsPerView),
+ avgViewsPerVideo,
+ avgSubGainPerDay,
+ avgViewsPerDay,
+ estimatedMonthlyViews: avgViewsPerDay * 30,
+ estimatedMonthlySubGain: avgSubGainPerDay * 30,
+ estimatedYearlyViews: avgViewsPerDay * 365,
+ estimatedYearlySubGain: avgSubGainPerDay * 365,
+ };
+}
+
+export function accountComparison(accounts) {
+ const sorted = {
+ bySubscribers: [...accounts].sort((a, b) => b.subscriberCount - a.subscriberCount),
+ byViews: [...accounts].sort((a, b) => b.viewCount - a.viewCount),
+ byVideos: [...accounts].sort((a, b) => b.videoCount - a.videoCount),
+ };
+
+ const totals = accounts.reduce((acc, account) => ({
+ subscribers: acc.subscribers + (account.subscriberCount || 0),
+ views: acc.views + (account.viewCount || 0),
+ videos: acc.videos + (account.videoCount || 0),
+ }), { subscribers: 0, views: 0, videos: 0 });
+
+ return {
+ rankings: sorted,
+ totals,
+ accountCount: accounts.length,
+ bestBySubscribers: sorted.bySubscribers[0] || null,
+ bestByViews: sorted.byViews[0] || null,
+ bestByVideos: sorted.byVideos[0] || null,
+ };
+}
+
+function matchesSearch(video, term) {
+ return video.title?.toLowerCase().includes(term) || (video.tags || []).some(tag => tag.toLowerCase().includes(term));
+}
+
+export function filterAndSortVideos(videos, { search, minViews, maxViews, sort, order }) {
+ 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((a, b) => {
+ const aVal = a[sortField] ?? 0;
+ const bVal = b[sortField] ?? 0;
+ if (typeof aVal === 'string') return sortOrder * aVal.localeCompare(bVal);
+ return sortOrder * (bVal - aVal);
+ });
+ return result;
+}
diff --git a/backend/utils/scheduler.js b/backend/utils/scheduler.js
index 6095923..340fbcf 100644
--- a/backend/utils/scheduler.js
+++ b/backend/utils/scheduler.js
@@ -2,12 +2,64 @@
import { getDuePosts, updatePost, getAccountById, claimPost } from '../lib/db.js';
import { buildMediaParams } from '../services/instagram.js';
+const GRAPH_API = 'https://graph.instagram.com/v25.0';
+
export function generateId() {
return Date.now().toString(36) + Math.random().toString(36).substring(2, 8);
}
-// Called by the cron trigger (every 15 min). Receives supabase directly since
-// there is no Hono request context in cron handlers.
+function wait(ms) {
+ return new Promise(resolve => setTimeout(resolve, ms));
+}
+
+async function createContainer(igId, params) {
+ const query = new URLSearchParams(params).toString();
+ const createRes = await fetch(`${GRAPH_API}/${igId}/media?${query}`, { method: 'POST' });
+ const createData = await createRes.json();
+ if (createData.error) throw new Error(createData.error.message);
+ return createData.id;
+}
+
+// reels and stories process for a while; other media only need a short pause before publishing
+async function waitForContainer(mediaType, containerId, token) {
+ if (mediaType !== 'REELS' && mediaType !== 'STORIES') {
+ await wait(2000);
+ return;
+ }
+ for (let i = 0; i < 60; i++) {
+ await wait(3000);
+ const statusRes = await fetch(`${GRAPH_API}/${containerId}?fields=status_code,status&access_token=${token}`);
+ const statusData = await statusRes.json();
+ if (statusData.status_code === 'FINISHED' || statusData.status_code === 'PUBLISHED') return;
+ if (statusData.status_code === 'ERROR') throw new Error('Processing failed: ' + (statusData.status || ''));
+ if (statusData.status_code === 'EXPIRED') throw new Error('Container expired');
+ }
+}
+
+async function publishContainer(igId, containerId, token) {
+ const pubRes = await fetch(
+ `${GRAPH_API}/${igId}/media_publish?creation_id=${containerId}&access_token=${token}`,
+ { method: 'POST' }
+ );
+ const pubData = await pubRes.json();
+ if (pubData.error) throw new Error(pubData.error.message);
+ return pubData.id;
+}
+
+async function publishPost(supabase, post) {
+ const acct = await getAccountById(supabase, post.accountId);
+ if (!acct) throw new Error('Account not found: ' + post.accountId);
+
+ const igId = acct.igUserId;
+ const token = acct.accessToken;
+ const params = buildMediaParams(post, token);
+
+ const containerId = await createContainer(igId, params);
+ await waitForContainer(post.mediaType, containerId, token);
+ return publishContainer(igId, containerId, token);
+}
+
+// cron entry point; it gets supabase directly because cron handlers have no request context
export async function processScheduledPosts(supabase) {
let processed = 0;
const errors = [];
@@ -19,50 +71,14 @@ export async function processScheduledPosts(supabase) {
if (!(await claimPost(supabase, post.id))) continue;
try {
- const acct = await getAccountById(supabase, post.accountId);
- if (!acct) throw new Error('Account not found: ' + post.accountId);
-
- const igId = acct.igUserId;
- const token = acct.accessToken;
- const params = buildMediaParams(post, token);
-
- const qs = new URLSearchParams(params).toString();
- const createRes = await fetch(`https://graph.instagram.com/v25.0/${igId}/media?${qs}`, { method: 'POST' });
- const createData = await createRes.json();
- if (createData.error) throw new Error(createData.error.message);
-
- const containerId = createData.id;
-
- if (post.mediaType === 'REELS' || post.mediaType === 'STORIES') {
- for (let i = 0; i < 60; i++) {
- await new Promise(r => setTimeout(r, 3000));
- const statusRes = await fetch(
- `https://graph.instagram.com/v25.0/${containerId}?fields=status_code,status&access_token=${token}`
- );
- const statusData = await statusRes.json();
- if (statusData.status_code === 'FINISHED' || statusData.status_code === 'PUBLISHED') break;
- if (statusData.status_code === 'ERROR') throw new Error('Processing failed: ' + (statusData.status || ''));
- if (statusData.status_code === 'EXPIRED') throw new Error('Container expired');
- }
- } else {
- await new Promise(r => setTimeout(r, 2000));
- }
-
- const pubRes = await fetch(
- `https://graph.instagram.com/v25.0/${igId}/media_publish?creation_id=${containerId}&access_token=${token}`,
- { method: 'POST' }
- );
- const pubData = await pubRes.json();
- if (pubData.error) throw new Error(pubData.error.message);
-
+ const mediaId = await publishPost(supabase, post);
await updatePost(supabase, post.id, {
status: 'published',
- publishedMediaId: pubData.id,
+ publishedMediaId: mediaId,
publishedAt: new Date().toISOString(),
});
processed++;
- console.log(`Published scheduled post ${post.id} → media ${pubData.id}`);
-
+ console.log(`Published scheduled post ${post.id} → media ${mediaId}`);
} catch (err) {
await updatePost(supabase, post.id, { status: 'failed', error: err.message });
errors.push({ id: post.id, error: err.message });
diff --git a/backend/utils/scheduler.test.js b/backend/utils/scheduler.test.js
new file mode 100644
index 0000000..9084216
--- /dev/null
+++ b/backend/utils/scheduler.test.js
@@ -0,0 +1,95 @@
+import { test, describe, before, after, afterEach, mock } from 'node:test';
+import { processScheduledPosts } from './scheduler.js';
+import { assertGolden } from '../services/fixtures/golden.js';
+import { installFetch, reply } from '../services/fixtures/fakeFetch.js';
+import { fakeSupabase, accountRow, tableRow } from '../services/fixtures/fakeSupabase.js';
+
+const FIXED_NOW = Date.parse('2026-09-01T12:00:00Z');
+
+function postRow(id, accountId, data, overrides = {}) {
+ return tableRow('scheduled_posts', { id, user_id: 'user-1', account_id: accountId, status: 'pending', scheduled_at: '2026-09-01T11:00:00.000Z', data, ...overrides });
+}
+
+const ACCOUNTS = [
+ accountRow({ id: 'ig1', platform: 'instagram', igUserId: 'IG1', accessToken: 'T1' }),
+ accountRow({ id: 'igErr', platform: 'instagram', igUserId: 'ERR', accessToken: 'T2' }),
+ accountRow({ id: 'igExp', platform: 'instagram', igUserId: 'EXP', accessToken: 'T3' }),
+ accountRow({ id: 'igBad', platform: 'instagram', igUserId: 'BAD', accessToken: 'T4' }),
+ accountRow({ id: 'igPub', platform: 'instagram', igUserId: 'PUB', accessToken: 'T5' }),
+ accountRow({ id: 'igSlow', platform: 'instagram', igUserId: 'SLOW', accessToken: 'T6' }),
+];
+
+const ROWS = [
+ ...ACCOUNTS.map(row => tableRow('accounts', row)),
+ postRow('p-image', 'ig1', { mediaType: 'IMAGE', mediaUrl: 'https://cdn/a.jpg', caption: 'Hello' }),
+ postRow('p-reel', 'ig1', { mediaType: 'REELS', mediaUrl: 'https://cdn/r.mp4', shareToFeed: true }),
+ postRow('p-story', 'igErr', { mediaType: 'STORIES', mediaUrl: 'https://cdn/s.mp4' }),
+ postRow('p-expired', 'igExp', { mediaType: 'REELS', mediaUrl: 'https://cdn/e.mp4' }),
+ postRow('p-missing', 'gone', { mediaType: 'IMAGE', mediaUrl: 'https://cdn/m.jpg' }),
+ postRow('p-create', 'igBad', { mediaType: 'IMAGE', mediaUrl: 'https://cdn/b.jpg' }),
+ postRow('p-publish', 'igPub', { mediaType: 'IMAGE', mediaUrl: 'https://cdn/p.jpg' }),
+ postRow('p-slow', 'igSlow', { mediaType: 'REELS', mediaUrl: 'https://cdn/slow.mp4' }),
+ postRow('p-dup', 'ig1', { mediaType: 'IMAGE', mediaUrl: 'https://cdn/d.jpg' }),
+ postRow('p-dup', 'ig1', { mediaType: 'IMAGE', mediaUrl: 'https://cdn/d.jpg' }),
+ postRow('p-busy', 'ig1', { mediaType: 'IMAGE' }, { status: 'publishing' }),
+ postRow('p-later', 'ig1', { mediaType: 'IMAGE' }, { scheduled_at: '2026-09-02T00:00:00.000Z' }),
+];
+
+const STATUS_SEQUENCES = {
+ 'c-IG1': ['IN_PROGRESS', 'FINISHED'],
+ 'c-ERR': ['ERROR'],
+ 'c-EXP': ['IN_PROGRESS', 'EXPIRED'],
+ 'c-SLOW': [],
+};
+
+function graphReply(request) {
+ const url = new URL(request.url);
+ const parts = url.pathname.split('/');
+ if (parts[3] === 'media') {
+ if (parts[2] === 'BAD') return reply({ error: { message: 'Invalid image' } });
+ return reply({ id: `c-${parts[2]}` });
+ }
+ if (parts[3] === 'media_publish') {
+ if (parts[2] === 'PUB') return reply({ error: { message: 'Publish refused' } });
+ return reply({ id: `m-${url.searchParams.get('creation_id')}` });
+ }
+ const sequence = STATUS_SEQUENCES[parts[2]] ?? [];
+ const statusCode = sequence.shift() ?? 'IN_PROGRESS';
+ return reply({ status_code: statusCode, status: statusCode === 'ERROR' ? 'Bad video' : undefined });
+}
+
+function describeArg(arg) {
+ return arg instanceof Error ? `Error: ${arg.message}` : arg;
+}
+
+let fetchMock = null;
+afterEach(() => fetchMock?.restore());
+
+describe('processScheduledPosts golden output', () => {
+ before(() => mock.timers.enable({ apis: ['Date'], now: FIXED_NOW }));
+ after(() => mock.timers.reset());
+
+ test('publishes due posts, waits for video processing and records failures', async () => {
+ const supabase = fakeSupabase(ROWS);
+ fetchMock = installFetch(graphReply);
+ const delays = [];
+ const logLines = [];
+ mock.method(globalThis, 'setTimeout', (callback, ms) => { delays.push(ms); callback(); return 0; });
+ mock.method(console, 'log', (...args) => logLines.push(['log', ...args.map(describeArg)]));
+ mock.method(console, 'error', (...args) => logLines.push(['error', ...args.map(describeArg)]));
+
+ const result = await processScheduledPosts(supabase);
+ mock.restoreAll();
+
+ assertGolden({ result, delays, logLines, requests: fetchMock.requests, queries: supabase.calls, table: supabase.table }, 'scheduler.process');
+ });
+
+ test('a failing due post query is logged and nothing is processed', async () => {
+ const logLines = [];
+ mock.method(console, 'error', (...args) => logLines.push(['error', ...args.map(describeArg)]));
+ const result = await processScheduledPosts({ from() { throw new Error('db down'); } });
+ mock.restoreAll();
+
+ assertGolden({ result, logLines }, 'scheduler.dbFailure');
+ });
+});
diff --git a/docs/architecture/backend/CRON.md b/docs/architecture/backend/CRON.md
index f8408b7..5b7499d 100644
--- a/docs/architecture/backend/CRON.md
+++ b/docs/architecture/backend/CRON.md
@@ -18,12 +18,14 @@ Both cron triggers invoke the `scheduled` export from `backend/server.js`.
**What it does:**
1. Queries `scheduled_posts` where `status = 'pending'` and `scheduled_at <= now()`
2. For each due post:
- - Fetches the associated account from `accounts` table
- - Sets post status to `'publishing'` (prevents double-publish if two schedulers run concurrently)
- - Calls `publishToInstagram(post, account)` in `backend/services/instagram.js`
+ - Claims it with `claimPost()` (pending to `'publishing'`); a post another scheduler already claimed is skipped
+ - Fetches the associated account from `accounts` table and builds the container parameters with `buildMediaParams()`
+ - Creates the Graph API container, waits for it (Reels and Stories poll the status every 3 seconds, up to 60 times; other media wait 2 seconds), then publishes it
- On success: sets status to `'published'`, stores `publishedMediaId` and `publishedAt` in `data`
- On failure: sets status to `'failed'`, stores `error` message in `data`
+`utils/scheduler.test.js` pins this sequence, the log lines and the stored results against a fake Supabase client and Graph API.
+
**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).
diff --git a/docs/architecture/backend/ROUTES.md b/docs/architecture/backend/ROUTES.md
index 16ad241..660ce30 100644
--- a/docs/architecture/backend/ROUTES.md
+++ b/docs/architecture/backend/ROUTES.md
@@ -31,6 +31,9 @@ Handlers delegate to `services/accountConnect.js` and `services/accountRefresh.j
| 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) |
### Analytics
+
+Channel metrics, the comparison and the all videos filter live in `services/youtubeLibrary.js`; the channel backfill lives in `services/accountRefresh.js`.
+
| 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 |
@@ -77,6 +80,9 @@ Handlers delegate to `services/accountConnect.js` and `services/accountRefresh.j
| 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 |
### Tracked Content
+
+Link detection and the manual views and image checks live in `services/trackedContent.js`.
+
| Method | Path | File | Purpose |
|---|---|---|---|
| GET | `/api/tracked-content` | `routes/trackedContent.js` | List all tracked items for the current user (Reddit posts and YouTube videos) |
diff --git a/docs/architecture/backend/SERVICES.md b/docs/architecture/backend/SERVICES.md
index a11c768..6f00425 100644
--- a/docs/architecture/backend/SERVICES.md
+++ b/docs/architecture/backend/SERVICES.md
@@ -85,6 +85,7 @@ function safeAccount(account) {
| `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`) |
### Key Functions
@@ -150,12 +151,18 @@ The account routes in `routes/accounts.js` only parse the request, check require
|---|---|
| `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) |
+| `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) |
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`)
+
+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.
+
+---
+
## Instagram OAuth (`instagramOAuth.js`)
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.
diff --git a/docs/workflows/TESTING.md b/docs/workflows/TESTING.md
index 9391f7b..374f44e 100644
--- a/docs/workflows/TESTING.md
+++ b/docs/workflows/TESTING.md
@@ -13,6 +13,8 @@ Frontend tests cover `src/lib/`: hold-to-confirm timing, command palette ranking
Test files sit next to the module they cover as `*.test.js` (for example `services/instagram.test.js`). Wrangler only bundles files reachable from `server.js`, so test files never ship in the Worker.
+Backend route and scheduler tests (`routes/*.test.js`, `utils/scheduler.test.js`) run the real handlers against `services/fixtures/fakeSupabase.js` and a scripted `fetch`, then compare responses, queries and outgoing requests with the `services/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.
+
The testing workflow documented here describes what should run before shipping any change.
## Pre-Deployment Checklist