Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.
refactor(ts): type the backend foundation and add shared API types
spacesdrive3a8f84a50db4
diff --git a/backend/lib/cache.ts b/backend/lib/cache.tsindex bd37adc..6c63735 100644--- a/backend/lib/cache.ts+++ b/backend/lib/cache.ts@@ -1,3 +1,8 @@+import type { Redis } from '@upstash/redis';+import type { VideosCacheData } from '../../shared/types/youtube.ts';+import type { IGCacheData } from '../../shared/types/instagram.ts';+import type { RedditCacheData } from '../../shared/types/reddit.ts';+// every helper is a no-op without redis: the cache is optionalexport { createOAuthState, verifyOAuthState } from './oauthState.ts';@@ -8,17 +13,19 @@ const ANALYTICS_TTL_SECONDS = 6 * 60 * 60;const VIDEOS_CACHE_VERSION = 2;const IG_CACHE_VERSION = 2;-async function readKey(redis, key) {+type Versioned<T> = T & { version: number };++async function readKey<T>(redis: Redis | null, key: string): Promise<T | null> {if (!redis) return null;try {- return await redis.get(key);+ return await redis.get<T>(key);} catch {// a cache miss falls back to the live apireturn null;}}-async function writeKey(redis, key, value) {+async function writeKey(redis: Redis | null, key: string, value: unknown): Promise<undefined> {if (!redis) return undefined;try {await redis.set(key, value, { ex: ANALYTICS_TTL_SECONDS });@@ -29,7 +36,7 @@ async function writeKey(redis, key, value) {return undefined;}-async function deleteKey(redis, key) {+async function deleteKey(redis: Redis | null, key: string): Promise<undefined> {if (!redis) return undefined;try {await redis.del(key);@@ -40,40 +47,40 @@ async function deleteKey(redis, key) {return undefined;}-export async function getVideosCache(redis, userId, accountId) {- const cached = await readKey(redis, `videos:${userId}:${accountId}`);+export async function getVideosCache(redis: Redis | null, userId: string, accountId: string): Promise<Versioned<VideosCacheData> | null> {+ const cached = await readKey<Versioned<VideosCacheData>>(redis, `videos:${userId}:${accountId}`);return cached?.version === VIDEOS_CACHE_VERSION ? cached : null;}-export async function setVideosCache(redis, userId, accountId, data) {+export async function setVideosCache(redis: Redis | null, userId: string, accountId: string, data: VideosCacheData): Promise<void> {await writeKey(redis, `videos:${userId}:${accountId}`, { ...data, version: VIDEOS_CACHE_VERSION });}-export async function deleteVideosCache(redis, userId, accountId) {+export async function deleteVideosCache(redis: Redis | null, userId: string, accountId: string): Promise<void> {await deleteKey(redis, `videos:${userId}:${accountId}`);}-export async function getIGCache(redis, userId, accountId) {- const cached = await readKey(redis, `ig:${userId}:${accountId}`);+export async function getIGCache(redis: Redis | null, userId: string, accountId: string): Promise<Versioned<IGCacheData> | null> {+ const cached = await readKey<Versioned<IGCacheData>>(redis, `ig:${userId}:${accountId}`);return cached?.version === IG_CACHE_VERSION ? cached : null;}-export async function setIGCache(redis, userId, accountId, data) {+export async function setIGCache(redis: Redis | null, userId: string, accountId: string, data: IGCacheData): Promise<void> {await writeKey(redis, `ig:${userId}:${accountId}`, { ...data, version: IG_CACHE_VERSION });}-export async function deleteIGCache(redis, userId, accountId) {+export async function deleteIGCache(redis: Redis | null, userId: string, accountId: string): Promise<void> {await deleteKey(redis, `ig:${userId}:${accountId}`);}-export async function getRedditCache(redis, userId, accountId) {- return (await readKey(redis, `reddit:${userId}:${accountId}`)) || null;+export async function getRedditCache(redis: Redis | null, userId: string, accountId: string): Promise<RedditCacheData | null> {+ return (await readKey<RedditCacheData>(redis, `reddit:${userId}:${accountId}`)) || null;}-export async function setRedditCache(redis, userId, accountId, data) {+export async function setRedditCache(redis: Redis | null, userId: string, accountId: string, data: RedditCacheData): Promise<void> {await writeKey(redis, `reddit:${userId}:${accountId}`, data);}-export async function deleteRedditCache(redis, userId, accountId) {+export async function deleteRedditCache(redis: Redis | null, userId: string, accountId: string): Promise<void> {await deleteKey(redis, `reddit:${userId}:${accountId}`);}diff --git a/backend/lib/crypto.ts b/backend/lib/crypto.tsindex b728680..68987d1 100644--- a/backend/lib/crypto.ts+++ b/backend/lib/crypto.ts@@ -1,20 +1,20 @@// web crypto, no npm dependency; 64 hex char key, output "<iv_hex>:<cipher_hex>"-function hexToBuffer(hex) {+function hexToBuffer(hex: string): ArrayBuffer {const bytes = new Uint8Array(hex.length / 2);for (let i = 0; i < hex.length; i += 2) bytes[i / 2] = parseInt(hex.slice(i, i + 2), 16);return bytes.buffer;}-function bufferToHex(buf) {+function bufferToHex(buf: ArrayBuffer): string {return [...new Uint8Array(buf)].map(b => b.toString(16).padStart(2, '0')).join('');}-async function importKey(keyHex) {+async function importKey(keyHex: string): Promise<CryptoKey> {return crypto.subtle.importKey('raw', hexToBuffer(keyHex), { name: 'AES-GCM' }, false, ['encrypt', 'decrypt']);}-export async function encryptPassword(plaintext, keyHex) {+export async function encryptPassword(plaintext: string, keyHex: string): Promise<string> {const key = await importKey(keyHex);const initVector = crypto.getRandomValues(new Uint8Array(12));const ciphertext = await crypto.subtle.encrypt(@@ -25,7 +25,7 @@ export async function encryptPassword(plaintext, keyHex) {return `${bufferToHex(initVector.buffer)}:${bufferToHex(ciphertext)}`;}-export async function decryptPassword(encrypted, keyHex) {+export async function decryptPassword(encrypted: string, keyHex: string): Promise<string> {const [ivHex, cipherHex] = encrypted.split(':');const key = await importKey(keyHex);const plaintext = await crypto.subtle.decrypt(@@ -37,11 +37,11 @@ export async function decryptPassword(encrypted, keyHex) {}// totp (rfc 6238) takes the raw base32 secret from the authenticator app qr code-function base32Decode(base32) {+function base32Decode(base32: string): Uint8Array<ArrayBuffer> {const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';const cleaned = base32.toUpperCase().replace(/[^A-Z2-7]/g, '');let bits = 0, value = 0;- const output = [];+ const output: number[] = [];for (const char of cleaned) {const idx = alphabet.indexOf(char);if (idx === -1) continue;@@ -55,7 +55,7 @@ function base32Decode(base32) {return new Uint8Array(output);}-export async function generateTOTP(base32Secret) {+export async function generateTOTP(base32Secret: string): Promise<string> {const secret = base32Decode(base32Secret);const counter = Math.floor(Date.now() / 30000);const counterBuf = new ArrayBuffer(8);diff --git a/backend/lib/db.ts b/backend/lib/db.tsindex 99d0577..daea35d 100644--- a/backend/lib/db.ts+++ b/backend/lib/db.ts@@ -1,21 +1,68 @@+import type { SupabaseClient } from '@supabase/supabase-js';+import type { Account, NewAccount, Platform, PostStatus, ScheduledPost, TrackedPost } from '../../shared/types/domain.ts';++interface AccountRow {+ id: string;+ platform: Platform;+ data: Omit<Account, 'id' | 'platform'>;+}++interface ScheduledPostRow {+ id: string;+ account_id: string;+ status: PostStatus;+ scheduled_at: string;+ data: Partial<ScheduledPost> | null;+}++interface TrackedPostRow {+ id: string;+ account_id: string | null;+ url: string;+ label: string | null;+ category: string | null;+ content_type: string | null;+ created_at: string;+ updated_at: string;+ data: Record<string, unknown> | null;+}++export type Settings = Record<string, unknown>;++export interface NewTrackedPost {+ id: string;+ accountId?: string | null;+ url: string;+ label?: string;+ category?: string;+ contentType?: string;+}++export interface TrackedPostUpdates {+ label?: string;+ category?: string;+ accountId?: string | null;+ data?: Record<string, unknown>;+}+// crons share these, so supabase is an argument; a null userId skips the filter-export async function getAccounts(supabase, userId = null) {+export async function getAccounts(supabase: SupabaseClient, userId: string | null = null): Promise<Account[]> {let query = supabase.from('accounts').select('id, platform, data');if (userId) query = query.eq('user_id', userId);const { data, error } = await query;if (error) throw error;- return (data || []).map(row => ({ id: row.id, platform: row.platform, ...row.data }));+ return ((data || []) as AccountRow[]).map(row => ({ id: row.id, platform: row.platform, ...row.data }));}-export async function getAccountById(supabase, id, userId = null) {+export async function getAccountById(supabase: SupabaseClient, id: string, userId: string | null = null): Promise<Account | null> {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 };+ return { id: data.id, platform: data.platform, ...(data as AccountRow).data };}-export async function createAccount(supabase, account, userId) {+export async function createAccount(supabase: SupabaseClient, account: NewAccount, userId: string): Promise<void> {const { id, platform, ...rest } = account;const { error } = await supabase.from('accounts')@@ -23,7 +70,7 @@ export async function createAccount(supabase, account, userId) {if (error) throw error;}-export async function updateAccount(supabase, id, updates, userId = null) {+export async function updateAccount(supabase: SupabaseClient, id: string, updates: Partial<Account>, userId: string | null = null): Promise<void> {const current = await getAccountById(supabase, id, userId);if (!current) throw new Error('Account not found: ' + id);const { id: _, platform: currentPlatform, ...currentData } = current;@@ -37,7 +84,7 @@ export async function updateAccount(supabase, id, updates, userId = null) {if (error) throw error;}-export async function deleteAccount(supabase, id, userId = null) {+export async function deleteAccount(supabase: SupabaseClient, id: string, userId: string | null = null): Promise<void> {let query = supabase.from('accounts').delete().eq('id', id);if (userId) query = query.eq('user_id', userId);const { error } = await query;@@ -45,9 +92,9 @@ export async function deleteAccount(supabase, id, userId = null) {}// rows are keyed by (user_id, key); every saved value lives under 'api_keys'-const DEFAULT_KEYS = {};+const DEFAULT_KEYS: Settings = {};-export async function getSettings(supabase, userId) {+export async function getSettings(supabase: SupabaseClient, userId: string): Promise<Settings> {const { data, error } = await supabase.from('settings').select('value')@@ -58,14 +105,14 @@ export async function getSettings(supabase, userId) {return { ...DEFAULT_KEYS, ...data.value };}-export async function saveSettings(supabase, keys, userId) {+export async function saveSettings(supabase: SupabaseClient, keys: Settings, userId: string): Promise<void> {const { error } = await supabase.from('settings').upsert({ user_id: userId, key: 'api_keys', value: keys }, { onConflict: 'user_id,key' });if (error) throw error;}-function rowToPost(row) {+function rowToPost(row: ScheduledPostRow): ScheduledPost {return {id: row.id,accountId: row.account_id,@@ -75,7 +122,7 @@ function rowToPost(row) {};}-export async function getPosts(supabase, userId) {+export async function getPosts(supabase: SupabaseClient, userId: string | null): Promise<ScheduledPost[]> {let query = supabase.from('scheduled_posts').select('id, account_id, status, scheduled_at, data')@@ -86,7 +133,7 @@ export async function getPosts(supabase, userId) {return (data || []).map(rowToPost);}-export async function getPostById(supabase, id, userId = null) {+export async function getPostById(supabase: SupabaseClient, id: string, userId: string | null = null): Promise<ScheduledPost | null> {let query = supabase.from('scheduled_posts').select('id, account_id, status, scheduled_at, data')@@ -97,7 +144,7 @@ export async function getPostById(supabase, id, userId = null) {return rowToPost(data);}-export async function getDuePosts(supabase) {+export async function getDuePosts(supabase: SupabaseClient): Promise<ScheduledPost[]> {const { data, error } = await supabase.from('scheduled_posts').select('id, account_id, status, scheduled_at, data')@@ -108,7 +155,7 @@ export async function getDuePosts(supabase) {}// atomic pending to publishing; false means the cron or github workflow won-export async function claimPost(supabase, id) {+export async function claimPost(supabase: SupabaseClient, id: string): Promise<boolean> {const { data, error } = await supabase.from('scheduled_posts').update({ status: 'publishing' })@@ -119,7 +166,7 @@ export async function claimPost(supabase, id) {return (data || []).length > 0;}-export async function createPost(supabase, post, userId) {+export async function createPost(supabase: SupabaseClient, post: ScheduledPost, userId: string): Promise<void> {const { id, accountId, status, scheduledAt, ...rest } = post;const { error } = await supabase.from('scheduled_posts').insert({id,@@ -132,9 +179,9 @@ export async function createPost(supabase, post, userId) {if (error) throw error;}-export async function updatePost(supabase, id, updates, userId = null) {+export async function updatePost(supabase: SupabaseClient, id: string, updates: Partial<ScheduledPost>, userId: string | null = null): Promise<void> {const { status, scheduledAt, accountId: _, ...dataUpdates } = updates;- const colUpdates = {};+ const colUpdates: { status?: PostStatus; scheduled_at?: string; data?: Partial<ScheduledPost> } = {};if (status !== undefined) colUpdates.status = status;if (scheduledAt !== undefined) colUpdates.scheduled_at = scheduledAt;@@ -153,14 +200,14 @@ export async function updatePost(supabase, id, updates, userId = null) {if (error) throw error;}-export async function deletePost(supabase, id, userId = null) {+export async function deletePost(supabase: SupabaseClient, id: string, userId: string | null = null): Promise<void> {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;}-export async function deleteAllPosts(supabase, userId) {+export async function deleteAllPosts(supabase: SupabaseClient, userId: string | null): Promise<{ deleted: number; kept: number }> {let countQ = supabase.from('scheduled_posts').select('*', { count: 'exact', head: true });let keepQ = supabase.from('scheduled_posts').select('*', { count: 'exact', head: true }).eq('status', 'publishing');let delQ = supabase.from('scheduled_posts').delete().neq('status', 'publishing');@@ -178,7 +225,7 @@ export async function deleteAllPosts(supabase, userId) {return { deleted: (total || 0) - (keeping || 0), kept: keeping || 0 };}-function rowToTrackedPost(row) {+function rowToTrackedPost(row: TrackedPostRow): TrackedPost {return {id: row.id,accountId: row.account_id,@@ -192,7 +239,7 @@ function rowToTrackedPost(row) {};}-export async function getTrackedPosts(supabase, userId) {+export async function getTrackedPosts(supabase: SupabaseClient, userId: string): Promise<TrackedPost[]> {const { data, error } = await supabase.from('tracked_posts').select('id, account_id, url, label, category, content_type, created_at, updated_at, data')@@ -202,7 +249,7 @@ export async function getTrackedPosts(supabase, userId) {return (data || []).map(rowToTrackedPost);}-export async function getTrackedPostById(supabase, id, userId) {+export async function getTrackedPostById(supabase: SupabaseClient, id: string, userId: string): Promise<TrackedPost | null> {const { data, error } = await supabase.from('tracked_posts').select('id, account_id, url, label, category, content_type, created_at, updated_at, data')@@ -213,7 +260,7 @@ export async function getTrackedPostById(supabase, id, userId) {return rowToTrackedPost(data);}-export async function createTrackedPost(supabase, post, userId) {+export async function createTrackedPost(supabase: SupabaseClient, post: NewTrackedPost, userId: string): Promise<void> {const { id, accountId, url, label, category, contentType } = post;const { error } = await supabase.from('tracked_posts').insert({id,@@ -227,8 +274,14 @@ export async function createTrackedPost(supabase, post, userId) {if (error) throw error;}-export async function updateTrackedPost(supabase, id, updates, userId) {- const colUpdates = { updated_at: new Date().toISOString() };+export async function updateTrackedPost(supabase: SupabaseClient, id: string, updates: TrackedPostUpdates, userId: string): Promise<void> {+ const colUpdates: {+ updated_at: string;+ label?: string;+ category?: string;+ account_id?: string | null;+ data?: Record<string, unknown>;+ } = { updated_at: new Date().toISOString() };if (updates.label !== undefined) colUpdates.label = updates.label;if (updates.category !== undefined) colUpdates.category = updates.category;if (updates.accountId !== undefined) colUpdates.account_id = updates.accountId || null;@@ -242,7 +295,7 @@ export async function updateTrackedPost(supabase, id, updates, userId) {}// merges into data so manual fields and live refresh fields survive each other-export async function patchTrackedPostData(supabase, id, patch, userId) {+export async function patchTrackedPostData(supabase: SupabaseClient, id: string, patch: Record<string, unknown>, userId: string): Promise<void> {const { data: row, error: readError } = await supabase.from('tracked_posts').select('data')@@ -260,7 +313,7 @@ export async function patchTrackedPostData(supabase, id, patch, userId) {if (error) throw error;}-export async function deleteTrackedPost(supabase, id, userId) {+export async function deleteTrackedPost(supabase: SupabaseClient, id: string, userId: string): Promise<void> {const { error } = await supabase.from('tracked_posts').delete()diff --git a/backend/lib/oauthState.ts b/backend/lib/oauthState.tsindex 8d26118..adc9405 100644--- a/backend/lib/oauthState.ts+++ b/backend/lib/oauthState.ts@@ -1,11 +1,11 @@// state format: base64url(userId:timestamp).base64url(hmac-sha256 signature)const STATE_TTL_MS = 10 * 60 * 1000;-function toBase64Url(text) {+function toBase64Url(text: string): string {return btoa(text).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');}-async function hmacSign(secret, message) {+async function hmacSign(secret: string, message: string): Promise<string> {const key = await crypto.subtle.importKey('raw',new TextEncoder().encode(secret),@@ -17,18 +17,18 @@ async function hmacSign(secret, message) {return toBase64Url(String.fromCharCode(...new Uint8Array(signature)));}-async function hmacVerify(secret, message, signature) {+async function hmacVerify(secret: string, message: string, signature: string): Promise<boolean> {const expected = await hmacSign(secret, message);return expected === signature;}-export async function createOAuthState(userId, secret) {+export async function createOAuthState(userId: string, secret: string): Promise<string> {const payload = toBase64Url(`${userId}:${Date.now()}`);const signature = await hmacSign(secret, payload);return `${payload}.${signature}`;}-export async function verifyOAuthState(state, secret) {+export async function verifyOAuthState(state: string, secret: string): Promise<string | null> {const separatorIndex = state.lastIndexOf('.');if (separatorIndex === -1) return null;diff --git a/backend/lib/redis.ts b/backend/lib/redis.tsindex fbfcea7..d808f43 100644--- a/backend/lib/redis.ts+++ b/backend/lib/redis.ts@@ -1,6 +1,7 @@import { Redis } from '@upstash/redis';+import type { Env } from '../types/env.ts';-export function getRedis(env) {+export function getRedis(env: Env): Redis | null {const url = env.UPSTASH_REDIS_REST_URL?.replace(/^\uFEFF/, '').trim();const token = env.UPSTASH_REDIS_REST_TOKEN?.replace(/^\uFEFF/, '').trim();if (!url || !token) return null;diff --git a/backend/lib/safeAccount.ts b/backend/lib/safeAccount.tsindex 2cad087..3762b44 100644--- a/backend/lib/safeAccount.ts+++ b/backend/lib/safeAccount.ts@@ -1,8 +1,10 @@+import type { Account, SafeAccount } from '../../shared/types/domain.ts';+// hasCookie shows reddit session status without sending the cookie-const SECRET_FIELDS = ['accessToken', 'cookie', 'encryptedPassword', 'encryptedTotpSecret', 'authToken', 'ct0'];+const SECRET_FIELDS: (keyof Account)[] = ['accessToken', 'cookie', 'encryptedPassword', 'encryptedTotpSecret', 'authToken', 'ct0'];-export function safeAccount(account) {- const copy = { ...account, hasCookie: !!account.cookie };+export function safeAccount(account: Account): SafeAccount {+ const copy: Partial<Account> & { hasCookie: boolean } = { ...account, hasCookie: !!account.cookie };for (const field of SECRET_FIELDS) delete copy[field];- return copy;+ return copy as SafeAccount;}diff --git a/backend/lib/supabase.ts b/backend/lib/supabase.tsindex fd53ebd..23b8e3f 100644--- a/backend/lib/supabase.ts+++ b/backend/lib/supabase.ts@@ -1,11 +1,13 @@import { createClient } from '@supabase/supabase-js';+import type { SupabaseClient } from '@supabase/supabase-js';+import type { Env } from '../types/env.ts';-function clean(s) {+function clean(s: string): string {return s?.replace(/^\uFEFF/, '').trim();}// workers reject the `cache` RequestInit field, so supabase requests drop it-function workerFetch(url, options = {}) {+function workerFetch(url: RequestInfo | URL, options: RequestInit = {}): Promise<Response> {const { cache: _cache, ...rest } = options;return fetch(url, rest);}@@ -13,11 +15,11 @@ function workerFetch(url, options = {}) {const CLIENT_OPTS = { auth: { persistSession: false }, global: { fetch: workerFetch } };// Returns a service-role client that bypasses RLS - used for all DB operations.-export function getSupabase(env) {+export function getSupabase(env: Env): SupabaseClient {return createClient(clean(env.SUPABASE_URL), clean(env.SUPABASE_SERVICE_KEY), CLIENT_OPTS);}// Returns an anon client - used only to verify user JWTs in auth middleware.-export function getSupabaseAuth(env) {+export function getSupabaseAuth(env: Env): SupabaseClient {return createClient(clean(env.SUPABASE_URL), clean(env.SUPABASE_ANON_KEY), CLIENT_OPTS);}diff --git a/backend/middleware/auth.ts b/backend/middleware/auth.tsindex 483d37b..13be8dd 100644--- a/backend/middleware/auth.ts+++ b/backend/middleware/auth.ts@@ -1,6 +1,8 @@+import type { Next } from 'hono';import { getSupabaseAuth } from '../lib/supabase.ts';+import type { AppContext } from '../types/app.ts';-export async function requireAuth(c, next) {+export async function requireAuth(c: AppContext, next: Next) {const token = c.req.header('Authorization')?.replace('Bearer ', '');if (!token) return c.json({ error: 'Unauthorized' }, 401);const supabaseAuth = getSupabaseAuth(c.env);diff --git a/backend/server.ts b/backend/server.tsindex c1681ee..3086816 100644--- a/backend/server.ts+++ b/backend/server.ts@@ -16,8 +16,10 @@ import { urlHandler, callbackHandler } from './routes/instagramAuth.ts';import { processScheduledPosts } from './utils/scheduler.ts';import { autoRefreshInstagramTokens } from './services/instagram.ts';import { autoRefreshRedditSessions } from './services/reddit.ts';+import type { AppEnv } from './types/app.ts';+import type { Env } from './types/env.ts';-const app = new Hono();+const app = new Hono<AppEnv>();app.onError((err, c) => {console.error('Worker error:', err.message);@@ -38,7 +40,7 @@ app.get('/api/health', (c) => c.json({ status: 'ok', timestamp: new Date().toISO// public: the oauth redirect has no jwt; the signed hmac state names the userapp.get('/api/auth/instagram/callback', callbackHandler);-const api = new Hono();+const api = new Hono<AppEnv>();api.use('*', requireAuth);api.route('/', keysRouter);@@ -60,7 +62,7 @@ export default {fetch: app.fetch,// wrangler.toml schedules: due posts every 15 minutes, token refresh daily- async scheduled(event, env, ctx) {+ async scheduled(event: ScheduledController, env: Env, ctx: ExecutionContext) {const supabase = getSupabase(env);if (event.cron === '*/15 * * * *') {@@ -70,4 +72,4 @@ export default {ctx.waitUntil(autoRefreshRedditSessions(supabase, env.REDDIT_ENCRYPTION_KEY));}},-};+} satisfies ExportedHandler<Env>;diff --git a/backend/types/app.ts b/backend/types/app.tsnew file mode 100644index 0000000..6f32a62--- /dev/null+++ b/backend/types/app.ts@@ -0,0 +1,21 @@+import type { Context } from 'hono';+import type { SupabaseClient } from '@supabase/supabase-js';+import type { Redis } from '@upstash/redis';+import type { Env } from './env.ts';++export type { SupabaseClient, Redis };++// set by the client middleware in server.ts for every request, and by requireAuth under /api+export interface AppVariables {+ supabase: SupabaseClient;+ redis: Redis | null;+ userId: string;+ userEmail: string | undefined;+}++export interface AppEnv {+ Bindings: Env;+ Variables: AppVariables;+}++export type AppContext = Context<AppEnv>;diff --git a/backend/types/env.ts b/backend/types/env.tsnew file mode 100644index 0000000..b50f728--- /dev/null+++ b/backend/types/env.ts@@ -0,0 +1,16 @@+// Worker secrets set with `wrangler secret put`; see docs/architecture/cloudflare/WORKERS.md+export interface Env {+ SUPABASE_URL: string;+ SUPABASE_SERVICE_KEY: string;+ SUPABASE_ANON_KEY: string;+ YOUTUBE_API_KEY?: string;+ INSTAGRAM_APP_ID?: string;+ INSTAGRAM_APP_SECRET?: string;+ CLOUDINARY_CLOUD_NAME?: string;+ CLOUDINARY_UPLOAD_PRESET?: string;+ BACKEND_URL?: string;+ FRONTEND_URL?: string;+ UPSTASH_REDIS_REST_URL?: string;+ UPSTASH_REDIS_REST_TOKEN?: string;+ REDDIT_ENCRYPTION_KEY?: string;+}diff --git a/shared/types/domain.ts b/shared/types/domain.tsnew file mode 100644index 0000000..67099d6--- /dev/null+++ b/shared/types/domain.ts@@ -0,0 +1,123 @@+export type Platform = 'youtube' | 'instagram' | 'reddit';++export interface YouTubeThumbnail {+ url: string;+ width?: number;+ height?: number;+}++export type YouTubeThumbnails = Partial<Record<'default' | 'medium' | 'high' | 'standard' | 'maxres', YouTubeThumbnail>>;++// one row of `accounts`: id and platform are columns, every other field lives in the data jsonb+export interface Account {+ id: string;+ platform: Platform;+ title?: string;+ addedAt?: string;+ lastUpdated?: string;++ // youtube+ channelId?: string;+ description?: string;+ customUrl?: string;+ publishedAt?: string;+ country?: string;+ thumbnails?: YouTubeThumbnails;+ subscriberCount?: number;+ viewCount?: number;+ videoCount?: number;+ hiddenSubscriberCount?: boolean;+ uploadsPlaylistId?: string;+ keywords?: string;+ topicCategories?: string[];+ madeForKids?: boolean;++ // instagram and reddit+ username?: string;++ igUserId?: string;+ biography?: string;+ website?: string;+ profilePictureUrl?: string;+ followersCount?: number;+ followsCount?: number;+ mediaCount?: number;+ accessToken?: string;+ tokenExpiresAt?: string | null;++ totalKarma?: number;+ postKarma?: number;+ commentKarma?: number;+ iconUrl?: string;+ createdAt?: string | number;+ cookie?: string;+ encryptedPassword?: string;+ encryptedTotpSecret?: string;+ authToken?: string;+ ct0?: string;+}++// youtube accounts are created without a platform field; createAccount stores them as 'youtube'+export type NewAccount = Omit<Account, 'platform'> & { platform?: Platform };++// what an account looks like in a response: secrets removed, cookie presence kept+export type SafeAccount = Omit<Account, 'accessToken' | 'cookie' | 'encryptedPassword' | 'encryptedTotpSecret' | 'authToken' | 'ct0'> & {+ hasCookie: boolean;+};++export type PostStatus = 'pending' | 'publishing' | 'published' | 'failed';++export type MediaType = 'IMAGE' | 'VIDEO' | 'REELS' | 'STORIES' | 'CAROUSEL';++export interface UserTag {+ username: string;+ x?: number;+ y?: number;+}++export interface CarouselItem {+ mediaUrl: string;+ mediaType?: MediaType;+}++// one row of `scheduled_posts`: id, account_id, status and scheduled_at are columns, the rest is data jsonb+export interface ScheduledPost {+ id: string;+ accountId: string;+ status: PostStatus;+ scheduledAt: string;+ platform?: Platform;+ mediaType?: MediaType;+ mediaUrl?: string;+ caption?: string;+ coverUrl?: string | null;+ shareToFeed?: boolean;+ collaborators?: string[];+ audioName?: string;+ thumbOffset?: number | null;+ locationId?: string;+ userTags?: UserTag[];+ altText?: string;+ children?: string[];+ carouselItems?: CarouselItem[];+ createdAt?: string;+ publishedAt?: string;+ publishedMediaId?: string | null;+ error?: string | null;+}++// one row of `tracked_posts`; fields refreshed from the platform live in the data jsonb+export interface TrackedPost {+ id: string;+ accountId: string | null;+ url: string;+ label: string;+ category: string;+ // 'reddit' unless the row says otherwise+ contentType: string;+ createdAt: string;+ updatedAt: string;+ [field: string]: unknown;+}diff --git a/shared/types/instagram.ts b/shared/types/instagram.tsnew file mode 100644index 0000000..56b2e97--- /dev/null+++ b/shared/types/instagram.ts@@ -0,0 +1,21 @@+export type InstagramContentType = 'reel' | 'post' | 'video';++// a media item as normalizeInstagramMedia() stores it in the ig: cache+export interface InstagramMedia {+ id: string;+ caption: string;+ contentType: InstagramContentType;+ mediaType: string;+ mediaUrl: string;+ thumbnailUrl: string;+ permalink: string;+ timestamp: string;+ likeCount: number;+ commentsCount: number;+ viewCount: number | null;+}++export interface IGCacheData {+ media: InstagramMedia[];+ fetchedAt: string;+}diff --git a/shared/types/reddit.ts b/shared/types/reddit.tsnew file mode 100644index 0000000..a8fa782--- /dev/null+++ b/shared/types/reddit.ts@@ -0,0 +1,107 @@+export interface RedditProfile {+ username: string;+ totalKarma: number;+ postKarma: number;+ commentKarma: number;+ awardeeKarma: number;+ awarderKarma: number;+ iconUrl: string;+ createdAt: string;+ isGold: boolean;+ isMod: boolean;+ verified: boolean;+}++export type RedditMediaType = 'video' | 'image' | 'text' | 'link';++export interface RedditPost {+ id: string;+ title: string;+ subreddit: string;+ subredditPrefixed: string;+ score: number;+ upvoteRatio: number;+ numComments: number;+ url: string;+ permalink: string;+ thumbnail: string;+ mediaType: RedditMediaType;+ isSelf: boolean;+ isVideo: boolean;+ isNsfw: boolean;+ createdAt: string;+ flair: string;+ awardsCount: number;+}++export interface RedditSubredditStats {+ subreddit: string;+ posts: number;+ totalScore: number;+ totalComments: number;+ avgScore: number;+ avgComments: number;+}++export interface RedditDayStats {+ day: string;+ shortDay: string;+ posts: number;+ avgScore: number;+ avgComments: number;+}++export interface RedditHourStats {+ hour: number;+ label: string;+ posts: number;+ avgScore: number;+}++export interface RedditMonthStats {+ month: string;+ posts: number;+ score: number;+ comments: number;+ avgScore: number;+}++export interface PostFrequency {+ perWeek: number;+ perMonth: number;+}++// computeRedditAnalytics() output, stored in the reddit: cache and returned by the analytics route+export interface RedditAnalytics {+ fetchedPosts: number;+ totalScore: number;+ avgScore: number;+ medianScore: number;+ totalComments: number;+ avgComments: number;+ avgUpvoteRatio: number;+ totalAwards: number;+ avgAwards: number;+ topPosts: RedditPost[];+ worstPosts: RedditPost[];+ subredditBreakdown: RedditSubredditStats[];+ mediaTypeDistribution: Partial<Record<RedditMediaType, number>>;+ postsByDayOfWeek: RedditDayStats[];+ postsByHour: RedditHourStats[];+ monthlyBreakdown: RedditMonthStats[];+ engagementTimeline: RedditMonthStats[];+ postsLast7Days: number;+ postsLast30Days: number;+ postsLast90Days: number;+ postFrequency: PostFrequency;+ viralityScore: number;+ consistencyScore: number;+ bestPostingDay: string;+ bestPostingHour: string;+}++export interface RedditCacheData {+ profile: RedditProfile;+ analytics: RedditAnalytics;+ posts: RedditPost[];+}diff --git a/shared/types/youtube.ts b/shared/types/youtube.tsnew file mode 100644index 0000000..3e975a2--- /dev/null+++ b/shared/types/youtube.ts@@ -0,0 +1,31 @@+// a video as normalizeYouTubeVideo() stores it in the videos: cache+export interface YouTubeVideo {+ videoId: string;+ title: string;+ description: string;+ publishedAt: string;+ channelTitle: string;+ thumbnails: { default: string; medium: string; high: string };+ tags: string[];+ categoryId: string;+ liveBroadcastContent: string;+ defaultAudioLanguage: string;+ duration: string;+ dimension: string;+ definition: string;+ caption: boolean;+ licensedContent: boolean;+ projection: string;+ viewCount: number;+ // null when the owner hides likes or turns comments off+ likeCount: number | null;+ commentCount: number | null;+ privacyStatus: string;+ embeddable: boolean;+ madeForKids: boolean;+}++export interface VideosCacheData {+ videos: YouTubeVideo[];+ fetchedAt: string;+}