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(publishing): services for publishing, scheduled posts and cron jobs

spacesdriveb2ebe7aa8ed4
diff --git a/backend/container.ts b/backend/container.ts
index cff7a7b..cfd388e 100644
--- a/backend/container.ts
+++ b/backend/container.ts
@@ -1,13 +1,22 @@
import { createAccountRepository } from './repositories/accountRepository.ts';
import { createAnalyticsCacheRepository } from './repositories/analyticsCacheRepository.ts';
+import { createScheduledPostRepository } from './repositories/scheduledPostRepository.ts';
import { createAccountService } from './services/accountService.ts';
import { createYouTubeAnalyticsService } from './services/youtubeAnalyticsService.ts';
import { createInstagramAnalyticsService } from './services/instagramAnalyticsService.ts';
import { createRedditAnalyticsService } from './services/redditAnalyticsService.ts';
+import { createPublishingService } from './services/publishingService.ts';
+import { createScheduledPublisher } from './services/scheduledPublisher.ts';
+import { createScheduledPostService } from './services/scheduledPostService.ts';
+import { createTokenRefreshService } from './services/tokenRefreshService.ts';
import type { AccountService } from './services/accountService.ts';
import type { YouTubeAnalyticsService } from './services/youtubeAnalyticsService.ts';
import type { InstagramAnalyticsService } from './services/instagramAnalyticsService.ts';
import type { RedditAnalyticsService } from './services/redditAnalyticsService.ts';
+import type { PublishingService } from './services/publishingService.ts';
+import type { ScheduledPublisher } from './services/scheduledPublisher.ts';
+import type { ScheduledPostService } from './services/scheduledPostService.ts';
+import type { TokenRefreshService } from './services/tokenRefreshService.ts';
import type { AppConfig } from './lib/config.ts';
import type { RequestContext } from './types/context.ts';
import type { Redis, SupabaseClient } from './types/app.ts';
@@ -22,16 +31,26 @@ export interface Services {
youtubeAnalytics: YouTubeAnalyticsService;
instagramAnalytics: InstagramAnalyticsService;
redditAnalytics: RedditAnalyticsService;
+ publishing: PublishingService;
+ scheduledPosts: ScheduledPostService;
+ scheduledPublisher: ScheduledPublisher;
+ tokenRefresh: TokenRefreshService;
}
// the composition root: wires repositories into services for one request or one cron run; building them is cheap
export function createServices(clients: Clients, config: AppConfig, context: RequestContext): Services {
const accounts = createAccountRepository(clients.supabase);
const cache = createAnalyticsCacheRepository(clients.redis);
+ const posts = createScheduledPostRepository(clients.supabase);
+ const scheduledPublisher = createScheduledPublisher({ accounts, posts, context });
return {
accounts: createAccountService({ accounts, cache, config, context }),
youtubeAnalytics: createYouTubeAnalyticsService({ accounts, cache, config, context }),
instagramAnalytics: createInstagramAnalyticsService({ accounts, cache, context }),
redditAnalytics: createRedditAnalyticsService({ accounts, cache, context }),
+ publishing: createPublishingService({ accounts, config, context }),
+ scheduledPosts: createScheduledPostService({ posts, publisher: scheduledPublisher }),
+ scheduledPublisher,
+ tokenRefresh: createTokenRefreshService({ accounts, context }),
};
}
diff --git a/backend/controllers/publishingController.ts b/backend/controllers/publishingController.ts
new file mode 100644
index 0000000..95e18b4
--- /dev/null
+++ b/backend/controllers/publishingController.ts
@@ -0,0 +1,33 @@
+import { controller, pathParam, servicesFor } from './http.ts';
+import { jsonBody, queryParams } from '../middleware/validate.ts';
+import { parseContainerInput, parseContainerStatusQuery, parsePublishRequest } from '../validators/publishingValidators.ts';
+import type {
+ CloudinaryConfigResponse, InstagramContainerStatusResponse, InstagramMediaPublishResponse, InstagramPublishingLimitResponse,
+ InstagramPublishResponse,
+} from '../../shared/types/instagram.ts';
+
+export const getCloudinaryConfig = controller.createHandlers(c => {
+ const { cloudName, uploadPreset } = servicesFor(c).publishing.cloudinaryConfig();
+ return c.json({ success: true, cloudName, uploadPreset } satisfies CloudinaryConfigResponse);
+});
+
+export const getPublishingLimit = controller.createHandlers(async c => {
+ const data = await servicesFor(c).publishing.publishingLimit(c.get('userId'), pathParam(c, 'id'));
+ return c.json({ success: true, data } satisfies InstagramPublishingLimitResponse);
+});
+
+export const createContainer = controller.createHandlers(jsonBody(parsePublishRequest), async c => {
+ const containerId = await servicesFor(c).publishing.createContainer(c.get('userId'), pathParam(c, 'id'), c.req.valid('json'));
+ return c.json({ success: true, containerId } satisfies InstagramPublishResponse);
+});
+
+export const getContainerStatus = controller.createHandlers(queryParams(parseContainerStatusQuery), async c => {
+ const { accountId } = c.req.valid('query');
+ const { statusCode, status } = await servicesFor(c).publishing.containerStatus(c.get('userId'), accountId, pathParam(c, 'containerId'));
+ return c.json({ success: true, statusCode, status } satisfies InstagramContainerStatusResponse);
+});
+
+export const publishContainer = controller.createHandlers(jsonBody(parseContainerInput), async c => {
+ const mediaId = await servicesFor(c).publishing.publishContainer(c.get('userId'), pathParam(c, 'id'), c.req.valid('json').containerId);
+ return c.json({ success: true, mediaId } satisfies InstagramMediaPublishResponse);
+});
diff --git a/backend/controllers/scheduledPostController.ts b/backend/controllers/scheduledPostController.ts
new file mode 100644
index 0000000..514fe56
--- /dev/null
+++ b/backend/controllers/scheduledPostController.ts
@@ -0,0 +1,37 @@
+import { controller, pathParam, servicesFor } from './http.ts';
+import { jsonBody } from '../middleware/validate.ts';
+import { parseScheduledPost, parseScheduledPostUpdate } from '../validators/scheduledPostValidators.ts';
+import type {
+ ScheduledPostDeleteAllResponse, ScheduledPostListResponse, ScheduledPostResponse, ScheduledPostUpdateResponse,
+ ScheduledPublishRunResponse, SuccessMessageResponse,
+} from '../../shared/types/domain.ts';
+
+export const listScheduledPosts = controller.createHandlers(async c => {
+ const posts = await servicesFor(c).scheduledPosts.list(c.get('userId'));
+ return c.json({ success: true, posts } satisfies ScheduledPostListResponse);
+});
+
+export const createScheduledPost = controller.createHandlers(jsonBody(parseScheduledPost), async c => {
+ const post = await servicesFor(c).scheduledPosts.create(c.get('userId'), c.req.valid('json'));
+ return c.json({ success: true, post } satisfies ScheduledPostResponse);
+});
+
+export const updateScheduledPost = controller.createHandlers(jsonBody(parseScheduledPostUpdate), async c => {
+ const post = await servicesFor(c).scheduledPosts.update(c.get('userId'), pathParam(c, 'id'), c.req.valid('json'));
+ return c.json({ success: true, post } satisfies ScheduledPostUpdateResponse);
+});
+
+export const deleteAllScheduledPosts = controller.createHandlers(async c => {
+ const { deleted, kept } = await servicesFor(c).scheduledPosts.removeAll(c.get('userId'));
+ return c.json({ success: true, deleted, kept } satisfies ScheduledPostDeleteAllResponse);
+});
+
+export const deleteScheduledPost = controller.createHandlers(async c => {
+ await servicesFor(c).scheduledPosts.remove(c.get('userId'), pathParam(c, 'id'));
+ return c.json({ success: true, message: 'Scheduled post deleted' } satisfies SuccessMessageResponse);
+});
+
+export const publishDuePosts = controller.createHandlers(async c => {
+ const result = await servicesFor(c).scheduledPosts.publishDueNow();
+ return c.json({ success: true, ...result, timestamp: new Date().toISOString() } satisfies ScheduledPublishRunResponse);
+});
diff --git a/backend/jobs/scheduled.ts b/backend/jobs/scheduled.ts
new file mode 100644
index 0000000..91a7792
--- /dev/null
+++ b/backend/jobs/scheduled.ts
@@ -0,0 +1,34 @@
+import { createServices } from '../container.ts';
+import { getSupabase } from '../database/supabase.ts';
+import { getRedis } from '../database/redis.ts';
+import { readConfig } from '../lib/config.ts';
+import { createLogger } from '../lib/logger.ts';
+import type { Env } from '../types/env.ts';
+import type { RequestContext } from '../types/context.ts';
+
+// must match the crons in wrangler.toml character for character
+export const PUBLISH_DUE_POSTS_CRON = '*/15 * * * *';
+export const REFRESH_TOKENS_CRON = '0 0 * * *';
+
+// a cron run gets its own id and a deadline under the Worker's 15 minute limit for scheduled events
+const CRON_DEADLINE_MS = 14 * 60 * 1000;
+
+function cronContext(cron: string): RequestContext {
+ const requestId = `cron-${crypto.randomUUID()}`;
+ return { requestId, signal: AbortSignal.timeout(CRON_DEADLINE_MS), log: createLogger({ requestId, cron }) };
+}
+
+// the cron entry point: the same services the API uses, built from the Worker env instead of a request
+export async function runScheduledJob(cron: string, env: Env): Promise<void> {
+ const context = cronContext(cron);
+ const services = createServices({ supabase: getSupabase(env), redis: getRedis(env) }, readConfig(env), context);
+
+ if (cron === PUBLISH_DUE_POSTS_CRON) {
+ const run = await services.scheduledPublisher.publishDue();
+ context.log.info('scheduled publish run', { processed: run.processed, failed: run.errors.length });
+ } else if (cron === REFRESH_TOKENS_CRON) {
+ await services.tokenRefresh.refreshExpiringInstagramTokens();
+ } else {
+ context.log.warn('no job for this cron', { cron });
+ }
+}
diff --git a/backend/routes/publishing.ts b/backend/routes/publishing.ts
deleted file mode 100644
index 9016106..0000000
--- a/backend/routes/publishing.ts
+++ /dev/null
@@ -1,114 +0,0 @@
-import { Hono } from 'hono';
-import { getAccountById } from '../lib/db.ts';
-import { buildMediaParams } from '../services/instagram/instagramPublishing.ts';
-import type { AppEnv } from '../types/app.ts';
-import type { InstagramApiContainerStatus, InstagramApiErrorBody, InstagramApiIdResponse } from '../services/instagram/instagramApi.ts';
-import type {
- CloudinaryConfigResponse, InstagramContainerStatusResponse, InstagramMediaPublishRequest, InstagramMediaPublishResponse,
- InstagramPublishingLimit, InstagramPublishingLimitResponse, InstagramPublishRequest, InstagramPublishResponse,
-} from '../../shared/types/instagram.ts';
-
-interface InstagramApiPublishingLimitBody extends InstagramApiErrorBody {
- data: InstagramPublishingLimit[];
-}
-
-const NO_TOKEN_MESSAGE = 'No Instagram access token stored - reconnect this account';
-
-const app = new Hono<AppEnv>();
-
-app.get('/cloudinary-config', (c) => {
- const cloudName = c.env.CLOUDINARY_CLOUD_NAME;
- const uploadPreset = c.env.CLOUDINARY_UPLOAD_PRESET;
- if (!cloudName || !uploadPreset) {
- return c.json({ success: false, message: 'Cloudinary not configured on server' }, 503);
- }
- return c.json({ success: true, cloudName, uploadPreset } satisfies CloudinaryConfigResponse);
-});
-
-app.get('/accounts/:id/ig-publishing-limit', async (c) => {
- try {
- const acct = await getAccountById(c.get('supabase'), c.req.param('id'), c.get('userId'));
- if (!acct || acct.platform !== 'instagram') {
- return c.json({ success: false, message: 'Instagram account not found' }, 404);
- }
- if (!acct.accessToken || !acct.igUserId) return c.json({ success: false, message: NO_TOKEN_MESSAGE }, 400);
- const response = await fetch(
- `https://graph.instagram.com/v25.0/${acct.igUserId}/content_publishing_limit?fields=quota_usage,config&access_token=${acct.accessToken}`
- );
- const data = await response.json() as InstagramApiPublishingLimitBody;
- if (data.error) throw new Error(data.error.message);
- return c.json({ success: true, ...data } satisfies InstagramPublishingLimitResponse);
- } catch (err) {
- return c.json({ success: false, message: (err as Error).message }, 500);
- }
-});
-
-app.post('/accounts/:id/ig-publish', async (c) => {
- try {
- const acct = await getAccountById(c.get('supabase'), c.req.param('id'), c.get('userId'));
- if (!acct || acct.platform !== 'instagram') {
- return c.json({ success: false, message: 'Instagram account not found' }, 404);
- }
- if (!acct.accessToken || !acct.igUserId) return c.json({ success: false, message: NO_TOKEN_MESSAGE }, 400);
-
- const igId = acct.igUserId;
- const params = buildMediaParams(await c.req.json() as InstagramPublishRequest, acct.accessToken);
-
- // URLSearchParams stringifies the boolean and number values
- const query = new URLSearchParams(params as unknown as Record<string, string>).toString();
- const response = await fetch(`https://graph.instagram.com/v25.0/${igId}/media?${query}`, { method: 'POST' });
- const data = await response.json() as InstagramApiIdResponse;
- if (data.error) throw new Error(data.error.message);
-
- return c.json({ success: true, containerId: data.id } satisfies InstagramPublishResponse);
- } catch (err) {
- return c.json({ success: false, message: (err as Error).message }, 500);
- }
-});
-
-app.get('/ig-container/:containerId/status', async (c) => {
- try {
- const containerId = c.req.param('containerId');
- const accountId = c.req.query('accountId');
- if (!accountId) return c.json({ success: false, message: 'accountId is required' }, 400);
- const acct = await getAccountById(c.get('supabase'), accountId, c.get('userId'));
- if (!acct || acct.platform !== 'instagram') {
- return c.json({ success: false, message: 'Instagram account not found' }, 404);
- }
- if (!acct.accessToken) return c.json({ success: false, message: NO_TOKEN_MESSAGE }, 400);
-
- const response = await fetch(
- `https://graph.instagram.com/v25.0/${containerId}?fields=status_code,status&access_token=${acct.accessToken}`
- );
- const data = await response.json() as InstagramApiContainerStatus;
- if (data.error) throw new Error(data.error.message);
-
- return c.json({ success: true, statusCode: data.status_code ?? 'IN_PROGRESS', status: data.status ?? '' } satisfies InstagramContainerStatusResponse);
- } catch (err) {
- return c.json({ success: false, message: (err as Error).message }, 500);
- }
-});
-
-app.post('/accounts/:id/ig-media-publish', async (c) => {
- try {
- const acct = await getAccountById(c.get('supabase'), c.req.param('id'), c.get('userId'));
- if (!acct || acct.platform !== 'instagram') {
- return c.json({ success: false, message: 'Instagram account not found' }, 404);
- }
- if (!acct.accessToken || !acct.igUserId) return c.json({ success: false, message: NO_TOKEN_MESSAGE }, 400);
-
- const { containerId } = await c.req.json() as InstagramMediaPublishRequest;
- const response = await fetch(
- `https://graph.instagram.com/v25.0/${acct.igUserId}/media_publish?creation_id=${containerId}&access_token=${acct.accessToken}`,
- { method: 'POST' }
- );
- const data = await response.json() as InstagramApiIdResponse;
- if (data.error) throw new Error(data.error.message);
-
- return c.json({ success: true, mediaId: data.id } satisfies InstagramMediaPublishResponse);
- } catch (err) {
- return c.json({ success: false, message: (err as Error).message }, 500);
- }
-});
-
-export default app;
diff --git a/backend/routes/publishingRoutes.ts b/backend/routes/publishingRoutes.ts
new file mode 100644
index 0000000..f8f9824
--- /dev/null
+++ b/backend/routes/publishingRoutes.ts
@@ -0,0 +1,15 @@
+import { Hono } from 'hono';
+import {
+ getCloudinaryConfig, getPublishingLimit, createContainer, getContainerStatus, publishContainer,
+} from '../controllers/publishingController.ts';
+import type { AppEnv } from '../types/app.ts';
+
+const router = new Hono<AppEnv>();
+
+router.get('/cloudinary-config', ...getCloudinaryConfig);
+router.get('/accounts/:id/ig-publishing-limit', ...getPublishingLimit);
+router.post('/accounts/:id/ig-publish', ...createContainer);
+router.get('/ig-container/:containerId/status', ...getContainerStatus);
+router.post('/accounts/:id/ig-media-publish', ...publishContainer);
+
+export default router;
diff --git a/backend/routes/scheduledPostRoutes.ts b/backend/routes/scheduledPostRoutes.ts
new file mode 100644
index 0000000..4ebfc95
--- /dev/null
+++ b/backend/routes/scheduledPostRoutes.ts
@@ -0,0 +1,18 @@
+import { Hono } from 'hono';
+import {
+ listScheduledPosts, createScheduledPost, updateScheduledPost, deleteAllScheduledPosts, deleteScheduledPost, publishDuePosts,
+} from '../controllers/scheduledPostController.ts';
+import type { AppEnv } from '../types/app.ts';
+
+const router = new Hono<AppEnv>();
+
+router.get('/scheduled-posts', ...listScheduledPosts);
+router.post('/scheduled-posts', ...createScheduledPost);
+router.put('/scheduled-posts/:id', ...updateScheduledPost);
+router.delete('/scheduled-posts', ...deleteAllScheduledPosts);
+router.delete('/scheduled-posts/:id', ...deleteScheduledPost);
+// the manual trigger for the scheduler; api.processScheduled() calls the GET form
+router.get('/process-scheduled', ...publishDuePosts);
+router.post('/process-scheduled', ...publishDuePosts);
+
+export default router;
diff --git a/backend/routes/scheduledPosts.ts b/backend/routes/scheduledPosts.ts
deleted file mode 100644
index 074957e..0000000
--- a/backend/routes/scheduledPosts.ts
+++ /dev/null
@@ -1,136 +0,0 @@
-import { Hono } from 'hono';
-import { getPosts, getPostById, createPost, updatePost, deletePost, deleteAllPosts } from '../lib/db.ts';
-import { generateId, processScheduledPosts } from '../utils/scheduler.ts';
-import type { AppEnv } from '../types/app.ts';
-import type {
- ScheduledPost, ScheduledPostDeleteAllResponse, ScheduledPostListResponse, ScheduledPostRequest, ScheduledPostResponse,
- ScheduledPostUpdateRequest, ScheduledPostUpdateResponse, ScheduledPublishRunResponse, SuccessMessageResponse,
-} from '../../shared/types/domain.ts';
-
-type EditableField = keyof ScheduledPostUpdateRequest;
-
-const app = new Hono<AppEnv>();
-
-app.get('/scheduled-posts', async (c) => {
- try {
- const posts = await getPosts(c.get('supabase'), c.get('userId'));
- return c.json({ success: true, posts } satisfies ScheduledPostListResponse);
- } catch (err) {
- return c.json({ success: false, message: (err as Error).message }, 500);
- }
-});
-
-app.post('/scheduled-posts', async (c) => {
- try {
- const body = await c.req.json() as ScheduledPostRequest;
- const {
- accountId, platform, mediaType, mediaUrl,
- caption, coverUrl, shareToFeed, collaborators,
- audioName, thumbOffset, locationId, userTags,
- altText, scheduledAt,
- } = body;
-
- if (!accountId || !mediaUrl || !scheduledAt) {
- return c.json({ success: false, message: 'accountId, mediaUrl, and scheduledAt are required' }, 400);
- }
-
- const scheduledDate = new Date(scheduledAt);
- if (isNaN(scheduledDate.getTime()) || scheduledDate <= new Date()) {
- return c.json({ success: false, message: 'scheduledAt must be a valid future date' }, 400);
- }
-
- const post: ScheduledPost = {
- id: generateId(),
- accountId,
- platform: platform || 'instagram',
- mediaType: mediaType || 'IMAGE',
- mediaUrl,
- caption: caption || '',
- coverUrl: coverUrl || null,
- shareToFeed: shareToFeed !== undefined ? shareToFeed : true,
- collaborators: collaborators || [],
- audioName: audioName || '',
- thumbOffset: thumbOffset || null,
- locationId: locationId || '',
- userTags: userTags || [],
- altText: altText || '',
- scheduledAt: scheduledDate.toISOString(),
- status: 'pending',
- createdAt: new Date().toISOString(),
- publishedMediaId: null,
- error: null,
- };
-
- await createPost(c.get('supabase'), post, c.get('userId'));
- return c.json({ success: true, post } satisfies ScheduledPostResponse);
- } catch (err) {
- return c.json({ success: false, message: (err as Error).message }, 500);
- }
-});
-
-app.put('/scheduled-posts/:id', async (c) => {
- try {
- const supabase = c.get('supabase');
- const userId = c.get('userId');
- const id = c.req.param('id');
- const post = await getPostById(supabase, id, userId);
- if (!post) return c.json({ success: false, message: 'Scheduled post not found' }, 404);
- if (post.status !== 'pending') {
- return c.json({ success: false, message: 'Can only edit pending posts' }, 400);
- }
-
- const body = await c.req.json() as ScheduledPostUpdateRequest;
- const allowed: EditableField[] = ['caption', 'scheduledAt', 'shareToFeed', 'collaborators', 'audioName',
- 'thumbOffset', 'locationId', 'userTags', 'altText', 'coverUrl'];
- const updates: Partial<ScheduledPost> = {};
- for (const key of allowed) {
- if (body[key] !== undefined) (updates as Record<EditableField, unknown>)[key] = body[key];
- }
- if (body.scheduledAt) updates.scheduledAt = new Date(body.scheduledAt).toISOString();
-
- await updatePost(supabase, id, updates, userId);
- const updated = await getPostById(supabase, id, userId);
- return c.json({ success: true, post: updated } satisfies ScheduledPostUpdateResponse);
- } catch (err) {
- return c.json({ success: false, message: (err as Error).message }, 500);
- }
-});
-
-app.delete('/scheduled-posts', async (c) => {
- try {
- const { deleted, kept } = await deleteAllPosts(c.get('supabase'), c.get('userId'));
- return c.json({ success: true, deleted, kept } satisfies ScheduledPostDeleteAllResponse);
- } catch (err) {
- return c.json({ success: false, message: (err as Error).message }, 500);
- }
-});
-
-app.delete('/scheduled-posts/:id', async (c) => {
- try {
- const supabase = c.get('supabase');
- const userId = c.get('userId');
- const id = c.req.param('id');
- const post = await getPostById(supabase, id, userId);
- if (!post) return c.json({ success: false, message: 'Scheduled post not found' }, 404);
- if (post.status === 'publishing') {
- return c.json({ success: false, message: 'Cannot delete a post that is currently publishing' }, 400);
- }
- await deletePost(supabase, id, userId);
- return c.json({ success: true, message: 'Scheduled post deleted' } satisfies SuccessMessageResponse);
- } catch (err) {
- return c.json({ success: false, message: (err as Error).message }, 500);
- }
-});
-
-// Manual trigger for testing
-app.get('/process-scheduled', async (c) => {
- const result = await processScheduledPosts(c.get('supabase'));
- return c.json({ success: true, ...result, timestamp: new Date().toISOString() } satisfies ScheduledPublishRunResponse);
-});
-
-app.post('/process-scheduled', async (c) => {
- const result = await processScheduledPosts(c.get('supabase'));
- return c.json({ success: true, ...result, timestamp: new Date().toISOString() } satisfies ScheduledPublishRunResponse);
-});
-
-export default app;
diff --git a/backend/server.ts b/backend/server.ts
index 618ad4a..59faeaf 100644
--- a/backend/server.ts
+++ b/backend/server.ts
@@ -11,15 +11,14 @@ import { RATE_LIMIT_RULES, QUOTA_ROUTES, PUBLISH_ROUTES, matchesRoute } from './
import keysRouter from './routes/keys.ts';
import accountRoutes from './routes/accountRoutes.ts';
import analyticsRoutes from './routes/analyticsRoutes.ts';
-import publishingRouter from './routes/publishing.ts';
-import scheduledPostsRouter from './routes/scheduledPosts.ts';
+import publishingRoutes from './routes/publishingRoutes.ts';
+import scheduledPostRoutes from './routes/scheduledPostRoutes.ts';
import settingsRouter from './routes/settings.ts';
import redditRoutes from './routes/redditRoutes.ts';
import trackedContentRouter from './routes/trackedContent.ts';
import overviewRouter from './routes/overview.ts';
import { urlHandler, callbackHandler } from './routes/instagramAuth.ts';
-import { processScheduledPosts } from './utils/scheduler.ts';
-import { autoRefreshInstagramTokens } from './services/instagram/instagramTokens.ts';
+import { runScheduledJob } from './jobs/scheduled.ts';
import type { AppEnv } from './types/app.ts';
import type { Env } from './types/env.ts';
@@ -58,8 +57,8 @@ api.use('*', rateLimit(RATE_LIMIT_RULES.publish, userKey, c => matchesRoute(PUBL
api.route('/', keysRouter);
api.route('/', accountRoutes);
api.route('/', analyticsRoutes);
-api.route('/', publishingRouter);
-api.route('/', scheduledPostsRouter);
+api.route('/', publishingRoutes);
+api.route('/', scheduledPostRoutes);
api.route('/', settingsRouter);
api.route('/', redditRoutes);
api.route('/', trackedContentRouter);
@@ -75,12 +74,6 @@ export default {
// wrangler.toml schedules: due posts every 15 minutes, token refresh daily
async scheduled(event: ScheduledController, env: Env, ctx: ExecutionContext) {
- const supabase = getSupabase(env);
-
- if (event.cron === '*/15 * * * *') {
- ctx.waitUntil(processScheduledPosts(supabase));
- } else if (event.cron === '0 0 * * *') {
- ctx.waitUntil(autoRefreshInstagramTokens(supabase));
- }
+ ctx.waitUntil(runScheduledJob(event.cron, env));
},
} satisfies ExportedHandler<Env>;
diff --git a/backend/services/instagram/instagramPublishing.ts b/backend/services/instagram/instagramPublishing.ts
index 07b2671..8f7aed6 100644
--- a/backend/services/instagram/instagramPublishing.ts
+++ b/backend/services/instagram/instagramPublishing.ts
@@ -1,4 +1,8 @@
-import type { InstagramPublishRequest } from '../../../shared/types/instagram.ts';
+import { igFetch, igPost } from './instagramApi.ts';
+import type { GraphParams, InstagramApiContainerStatus, InstagramApiIdResponse } from './instagramApi.ts';
+import type {
+ InstagramContainerStatusCode, InstagramPublishingLimit, InstagramPublishRequest,
+} from '../../../shared/types/instagram.ts';
// query parameters of POST /{ig-user-id}/media; URLSearchParams turns the booleans and numbers into strings
export interface InstagramMediaParams {
@@ -79,7 +83,7 @@ function addPhotoParams(params: InstagramMediaParams, post: InstagramPublishRequ
return params;
}
-// scripts/publish-scheduled.js keeps its own copy because it must stay dependency-free
+// scripts/publish-scheduled.ts keeps its own copy because it must stay dependency-free
export function buildMediaParams(post: InstagramPublishRequest, accessToken: string): InstagramMediaParams {
const params: InstagramMediaParams = { access_token: accessToken };
const { mediaType } = post;
@@ -90,3 +94,31 @@ export function buildMediaParams(post: InstagramPublishRequest, accessToken: str
if (mediaType === 'STORIES') return addStoryParams(params, post);
return addPhotoParams(params, post);
}
+
+export interface ContainerStatus {
+ statusCode: InstagramContainerStatusCode;
+ status: string;
+}
+
+// URLSearchParams turns the boolean and number values into strings
+export async function createMediaContainer(igUserId: string, params: InstagramMediaParams, signal?: AbortSignal): Promise<string> {
+ const data = await igPost<InstagramApiIdResponse>(`/${igUserId}/media`, params as unknown as GraphParams, signal);
+ return data.id;
+}
+
+export async function fetchContainerStatus(containerId: string, accessToken: string, signal?: AbortSignal): Promise<ContainerStatus> {
+ const data = await igFetch<InstagramApiContainerStatus>(`/${containerId}`, { fields: 'status_code,status', access_token: accessToken }, 1, signal);
+ return { statusCode: data.status_code ?? 'IN_PROGRESS', status: data.status ?? '' };
+}
+
+export async function publishMediaContainer(igUserId: string, containerId: string, accessToken: string, signal?: AbortSignal): Promise<string> {
+ const data = await igPost<InstagramApiIdResponse>(`/${igUserId}/media_publish`, { creation_id: containerId, access_token: accessToken }, signal);
+ return data.id;
+}
+
+export async function fetchPublishingLimit(igUserId: string, accessToken: string, signal?: AbortSignal): Promise<InstagramPublishingLimit[]> {
+ const data = await igFetch<{ data?: InstagramPublishingLimit[] }>(
+ `/${igUserId}/content_publishing_limit`, { fields: 'quota_usage,config', access_token: accessToken }, 1, signal,
+ );
+ return data.data ?? [];
+}
diff --git a/backend/services/instagram/instagramTokens.ts b/backend/services/instagram/instagramTokens.ts
index 1617ef6..09b56d3 100644
--- a/backend/services/instagram/instagramTokens.ts
+++ b/backend/services/instagram/instagramTokens.ts
@@ -1,11 +1,7 @@
-import { getAccounts, updateAccount } from '../../lib/db.ts';
import { igFetch } from './instagramApi.ts';
import { UpstreamError } from '../../lib/errors.ts';
-import type { Account } from '../../../shared/types/domain.ts';
-import type { SupabaseClient } from '../../types/app.ts';
const DEFAULT_TOKEN_LIFETIME_S = 5184000;
-const REFRESH_WINDOW_MS = 15 * 24 * 60 * 60 * 1000;
// answer of /access_token and /refresh_access_token
export interface InstagramApiToken {
@@ -48,39 +44,3 @@ export async function refreshLongLivedToken(longToken: string, signal?: AbortSig
if (!data.access_token) throw new UpstreamError('Failed to refresh token');
return toTokenResult(data as IssuedToken);
}
-
-type ExpiringInstagramAccount = Account & { accessToken: string; tokenExpiresAt: string };
-
-function isInstagramWithToken(account: Account): account is ExpiringInstagramAccount {
- return account.platform === 'instagram' && !!account.accessToken && !!account.tokenExpiresAt;
-}
-
-async function refreshStoredToken(supabase: SupabaseClient, account: ExpiringInstagramAccount): Promise<void> {
- try {
- const refreshed = await refreshLongLivedToken(account.accessToken);
- const tokenExpiresAt = new Date(Date.now() + (refreshed.expiresIn || DEFAULT_TOKEN_LIFETIME_S) * 1000).toISOString();
- await updateAccount(supabase, account.id, { accessToken: refreshed.accessToken, tokenExpiresAt });
- console.log(`Token refreshed for @${account.username} - expires ${tokenExpiresAt}`);
- } catch (err) {
- console.error(`Failed to refresh token for @${account.username}: ${(err as Error).message}`);
- }
-}
-
-// takes supabase directly because cron handlers have no hono request context
-export async function autoRefreshInstagramTokens(supabase: SupabaseClient): Promise<void> {
- try {
- const accounts = await getAccounts(supabase);
- const igAccounts = accounts.filter(isInstagramWithToken);
- if (igAccounts.length === 0) return;
-
- const soon = new Date(Date.now() + REFRESH_WINDOW_MS);
- const toRefresh = igAccounts.filter(account => new Date(account.tokenExpiresAt!) <= soon);
- if (toRefresh.length === 0) return;
-
- for (const account of toRefresh) {
- await refreshStoredToken(supabase, account);
- }
- } catch (err) {
- console.error('autoRefreshInstagramTokens error:', (err as Error).message);
- }
-}
diff --git a/backend/services/publishingService.ts b/backend/services/publishingService.ts
new file mode 100644
index 0000000..65e1da1
--- /dev/null
+++ b/backend/services/publishingService.ts
@@ -0,0 +1,70 @@
+import {
+ buildMediaParams, createMediaContainer, fetchContainerStatus, publishMediaContainer, fetchPublishingLimit,
+} from './instagram/instagramPublishing.ts';
+import { NotConfiguredError, NotFoundError, ValidationError } from '../lib/errors.ts';
+import type { ContainerStatus } from './instagram/instagramPublishing.ts';
+import type { AccountRepository } from '../repositories/accountRepository.ts';
+import type { AppConfig, CloudinaryConfig } from '../lib/config.ts';
+import type { RequestContext } from '../types/context.ts';
+import type { Account } from '../../shared/types/domain.ts';
+import type { InstagramPublishingLimit, InstagramPublishRequest } from '../../shared/types/instagram.ts';
+
+export interface PublishingDeps {
+ accounts: AccountRepository;
+ config: AppConfig;
+ context: RequestContext;
+}
+
+export interface PublishingService {
+ cloudinaryConfig(): CloudinaryConfig;
+ publishingLimit(userId: string, accountId: string): Promise<InstagramPublishingLimit[]>;
+ createContainer(userId: string, accountId: string, post: InstagramPublishRequest): Promise<string>;
+ containerStatus(userId: string, accountId: string, containerId: string): Promise<ContainerStatus>;
+ publishContainer(userId: string, accountId: string, containerId: string): Promise<string>;
+}
+
+export type PublishableAccount = Account & { igUserId: string; accessToken: string };
+
+export const NO_INSTAGRAM_TOKEN_MESSAGE = 'No Instagram access token stored - reconnect this account';
+
+// the only accounts that can publish: Instagram, with the id and token the Graph API calls need
+export function publishableAccount(account: Account | null): PublishableAccount {
+ if (!account || account.platform !== 'instagram') throw new NotFoundError('Instagram account not found');
+ if (!account.accessToken || !account.igUserId) throw new ValidationError(NO_INSTAGRAM_TOKEN_MESSAGE);
+ return { ...account, igUserId: account.igUserId, accessToken: account.accessToken };
+}
+
+export function createPublishingService({ accounts, config, context }: PublishingDeps): PublishingService {
+ const { signal } = context;
+
+ async function findPublishable(userId: string, accountId: string): Promise<PublishableAccount> {
+ return publishableAccount(await accounts.findForUser(accountId, userId));
+ }
+
+ return {
+ cloudinaryConfig() {
+ if (!config.cloudinary) throw new NotConfiguredError('Cloudinary not configured on server');
+ return config.cloudinary;
+ },
+
+ async publishingLimit(userId, accountId) {
+ const account = await findPublishable(userId, accountId);
+ return fetchPublishingLimit(account.igUserId, account.accessToken, signal);
+ },
+
+ async createContainer(userId, accountId, post) {
+ const account = await findPublishable(userId, accountId);
+ return createMediaContainer(account.igUserId, buildMediaParams(post, account.accessToken), signal);
+ },
+
+ async containerStatus(userId, accountId, containerId) {
+ const account = await findPublishable(userId, accountId);
+ return fetchContainerStatus(containerId, account.accessToken, signal);
+ },
+
+ async publishContainer(userId, accountId, containerId) {
+ const account = await findPublishable(userId, accountId);
+ return publishMediaContainer(account.igUserId, containerId, account.accessToken, signal);
+ },
+ };
+}
diff --git a/backend/services/scheduledPostService.ts b/backend/services/scheduledPostService.ts
new file mode 100644
index 0000000..02a4c1f
--- /dev/null
+++ b/backend/services/scheduledPostService.ts
@@ -0,0 +1,91 @@
+import { NotFoundError, ValidationError } from '../lib/errors.ts';
+import type { ScheduledPostRepository, DeleteAllResult } from '../repositories/scheduledPostRepository.ts';
+import type { ScheduledPublisher } from './scheduledPublisher.ts';
+import type {
+ ScheduledPost, ScheduledPostRequest, ScheduledPostUpdateRequest, ScheduledPublishRun,
+} from '../../shared/types/domain.ts';
+
+export interface ScheduledPostDeps {
+ posts: ScheduledPostRepository;
+ publisher: ScheduledPublisher;
+}
+
+export interface ScheduledPostService {
+ list(userId: string): Promise<ScheduledPost[]>;
+ create(userId: string, request: ScheduledPostRequest): Promise<ScheduledPost>;
+ update(userId: string, postId: string, changes: ScheduledPostUpdateRequest): Promise<ScheduledPost | null>;
+ remove(userId: string, postId: string): Promise<void>;
+ removeAll(userId: string): Promise<DeleteAllResult>;
+ publishDueNow(): Promise<ScheduledPublishRun>;
+}
+
+export function generateId(): string {
+ return Date.now().toString(36) + Math.random().toString(36).substring(2, 8);
+}
+
+function futureDate(value: string): string {
+ const date = new Date(value);
+ if (Number.isNaN(date.getTime()) || date.getTime() <= Date.now()) {
+ throw new ValidationError('scheduledAt must be a valid future date');
+ }
+ return date.toISOString();
+}
+
+export function createScheduledPostService({ posts, publisher }: ScheduledPostDeps): ScheduledPostService {
+ async function findOwned(userId: string, postId: string): Promise<ScheduledPost> {
+ const post = await posts.findForUser(postId, userId);
+ if (!post) throw new NotFoundError('Scheduled post not found');
+ return post;
+ }
+
+ return {
+ list: userId => posts.listForUser(userId),
+
+ async create(userId, request) {
+ const post: ScheduledPost = {
+ id: generateId(),
+ accountId: request.accountId,
+ platform: request.platform || 'instagram',
+ mediaType: request.mediaType || 'IMAGE',
+ mediaUrl: request.mediaUrl,
+ caption: request.caption || '',
+ coverUrl: request.coverUrl || null,
+ shareToFeed: request.shareToFeed !== undefined ? request.shareToFeed : true,
+ collaborators: request.collaborators || [],
+ audioName: request.audioName || '',
+ thumbOffset: request.thumbOffset || null,
+ locationId: request.locationId || '',
+ userTags: request.userTags || [],
+ altText: request.altText || '',
+ scheduledAt: futureDate(request.scheduledAt),
+ status: 'pending',
+ createdAt: new Date().toISOString(),
+ publishedMediaId: null,
+ error: null,
+ };
+ await posts.create(post, userId);
+ return post;
+ },
+
+ // only a post that has not started publishing can change
+ async update(userId, postId, changes) {
+ const post = await findOwned(userId, postId);
+ if (post.status !== 'pending') throw new ValidationError('Can only edit pending posts');
+ const updates: Partial<ScheduledPost> = { ...changes };
+ if (changes.scheduledAt) updates.scheduledAt = new Date(changes.scheduledAt).toISOString();
+ await posts.updateForUser(postId, updates, userId);
+ return posts.findForUser(postId, userId);
+ },
+
+ async remove(userId, postId) {
+ const post = await findOwned(userId, postId);
+ if (post.status === 'publishing') throw new ValidationError('Cannot delete a post that is currently publishing');
+ await posts.deleteForUser(postId, userId);
+ },
+
+ removeAll: userId => posts.deleteAllForUser(userId),
+
+ // the manual trigger runs the same publisher the cron uses, for every user's due posts
+ publishDueNow: () => publisher.publishDue(),
+ };
+}
diff --git a/backend/services/scheduledPublisher.ts b/backend/services/scheduledPublisher.ts
new file mode 100644
index 0000000..17ca222
--- /dev/null
+++ b/backend/services/scheduledPublisher.ts
@@ -0,0 +1,90 @@
+import { buildMediaParams, createMediaContainer, fetchContainerStatus, publishMediaContainer } from './instagram/instagramPublishing.ts';
+import { publishableAccount } from './publishingService.ts';
+import { NotFoundError, UpstreamError } from '../lib/errors.ts';
+import { errorFields } from '../lib/logger.ts';
+import type { AccountRepository } from '../repositories/accountRepository.ts';
+import type { ScheduledPostRepository } from '../repositories/scheduledPostRepository.ts';
+import type { RequestContext } from '../types/context.ts';
+import type { ScheduledPost, ScheduledPublishFailure, ScheduledPublishRun } from '../../shared/types/domain.ts';
+import type { InstagramPublishMediaType } from '../../shared/types/instagram.ts';
+
+export interface ScheduledPublisherDeps {
+ accounts: AccountRepository;
+ posts: ScheduledPostRepository;
+ context: RequestContext;
+}
+
+export interface ScheduledPublisher {
+ publishDue(): Promise<ScheduledPublishRun>;
+}
+
+const STATUS_POLLS = 60;
+const STATUS_POLL_MS = 3000;
+const IMAGE_SETTLE_MS = 2000;
+
+function wait(ms: number): Promise<void> {
+ return new Promise<void>(resolve => setTimeout(resolve, ms));
+}
+
+// publishes every user's due posts, so it runs from the cron job or the manual trigger, never per user
+export function createScheduledPublisher({ accounts, posts, context }: ScheduledPublisherDeps): ScheduledPublisher {
+ const { signal, log } = context;
+
+ // reels and stories need processing; other media only need a short pause
+ async function waitForContainer(mediaType: InstagramPublishMediaType | undefined, containerId: string, token: string): Promise<void> {
+ if (mediaType !== 'REELS' && mediaType !== 'STORIES') {
+ await wait(IMAGE_SETTLE_MS);
+ return;
+ }
+ for (let i = 0; i < STATUS_POLLS; i++) {
+ await wait(STATUS_POLL_MS);
+ const { statusCode, status } = await fetchContainerStatus(containerId, token, signal);
+ if (statusCode === 'FINISHED' || statusCode === 'PUBLISHED') return;
+ if (statusCode === 'ERROR') throw new UpstreamError('Processing failed: ' + status);
+ if (statusCode === 'EXPIRED') throw new UpstreamError('Container expired');
+ }
+ throw new UpstreamError('Instagram did not finish processing the media within 3 minutes');
+ }
+
+ async function publishPost(post: ScheduledPost): Promise<string> {
+ const found = await accounts.findById(post.accountId);
+ if (!found) throw new NotFoundError('Account not found: ' + post.accountId);
+ if (found.platform !== 'instagram') throw new UpstreamError('Scheduled posts can only publish to Instagram accounts');
+ const account = publishableAccount(found);
+
+ const containerId = await createMediaContainer(account.igUserId, buildMediaParams(post, account.accessToken), signal);
+ await waitForContainer(post.mediaType, containerId, account.accessToken);
+ return publishMediaContainer(account.igUserId, containerId, account.accessToken, signal);
+ }
+
+ return {
+ async publishDue() {
+ let processed = 0;
+ const errors: ScheduledPublishFailure[] = [];
+ let due: ScheduledPost[];
+ try {
+ due = await posts.listDue();
+ } catch (err) {
+ log.error('scheduler could not load due posts', errorFields(err));
+ return { processed, errors };
+ }
+
+ for (const post of due) {
+ // false when the other scheduler claimed it first
+ if (!(await posts.claim(post.id))) continue;
+ try {
+ const mediaId = await publishPost(post);
+ await posts.updateById(post.id, { status: 'published', publishedMediaId: mediaId, publishedAt: new Date().toISOString() });
+ processed++;
+ log.info('scheduled post published', { postId: post.id, mediaId });
+ } catch (err) {
+ const message = (err as Error).message;
+ await posts.updateById(post.id, { status: 'failed', error: message });
+ errors.push({ id: post.id, error: message });
+ log.error('scheduled post failed', { postId: post.id, ...errorFields(err) });
+ }
+ }
+ return { processed, errors };
+ },
+ };
+}
diff --git a/backend/services/tokenRefreshService.ts b/backend/services/tokenRefreshService.ts
new file mode 100644
index 0000000..ef5ed65
--- /dev/null
+++ b/backend/services/tokenRefreshService.ts
@@ -0,0 +1,55 @@
+import { refreshLongLivedToken } from './instagram/instagramTokens.ts';
+import { errorFields } from '../lib/logger.ts';
+import type { AccountRepository } from '../repositories/accountRepository.ts';
+import type { RequestContext } from '../types/context.ts';
+import type { Account } from '../../shared/types/domain.ts';
+
+export interface TokenRefreshDeps {
+ accounts: AccountRepository;
+ context: RequestContext;
+}
+
+export interface TokenRefreshService {
+ refreshExpiringInstagramTokens(): Promise<void>;
+}
+
+type ExpiringInstagramAccount = Account & { accessToken: string; tokenExpiresAt: string };
+
+const DEFAULT_TOKEN_LIFETIME_S = 5184000;
+const REFRESH_WINDOW_MS = 15 * 24 * 60 * 60 * 1000;
+
+function isInstagramWithToken(account: Account): account is ExpiringInstagramAccount {
+ return account.platform === 'instagram' && !!account.accessToken && !!account.tokenExpiresAt;
+}
+
+// the daily cron: long-lived tokens last 60 days, so anything expiring within 15 days is extended
+export function createTokenRefreshService({ accounts, context }: TokenRefreshDeps): TokenRefreshService {
+ const { signal, log } = context;
+
+ async function refreshStoredToken(account: ExpiringInstagramAccount): Promise<void> {
+ try {
+ const refreshed = await refreshLongLivedToken(account.accessToken, signal);
+ const tokenExpiresAt = new Date(Date.now() + (refreshed.expiresIn || DEFAULT_TOKEN_LIFETIME_S) * 1000).toISOString();
+ await accounts.updateById(account.id, { accessToken: refreshed.accessToken, tokenExpiresAt });
+ log.info('instagram token refreshed', { accountId: account.id, username: account.username, tokenExpiresAt });
+ } catch (err) {
+ // one failed account must not stop the others
+ log.error('instagram token refresh failed', { accountId: account.id, username: account.username, ...errorFields(err) });
+ }
+ }
+
+ return {
+ async refreshExpiringInstagramTokens() {
+ let listed: Account[];
+ try {
+ listed = await accounts.listAll();
+ } catch (err) {
+ log.error('token refresh could not load accounts', errorFields(err));
+ return;
+ }
+ const soon = Date.now() + REFRESH_WINDOW_MS;
+ const due = listed.filter(isInstagramWithToken).filter(account => new Date(account.tokenExpiresAt).getTime() <= soon);
+ for (const account of due) await refreshStoredToken(account);
+ },
+ };
+}
diff --git a/backend/tests/fixtures/scheduledPublisher.dbFailure.golden.json b/backend/tests/fixtures/scheduledPublisher.dbFailure.golden.json
new file mode 100644
index 0000000..2b3e83e
--- /dev/null
+++ b/backend/tests/fixtures/scheduledPublisher.dbFailure.golden.json
@@ -0,0 +1,12 @@
+{
+ "result": {
+ "processed": 0,
+ "errors": []
+ },
+ "logLines": [
+ [
+ "error",
+ "{\"level\":\"error\",\"message\":\"scheduler could not load due posts\",\"requestId\":\"cron-test\",\"error\":\"The database request failed. Try again in a moment.\",\"errorName\":\"DatabaseError\",\"cause\":\"db down\"}"
+ ]
+ ]
+}
diff --git a/backend/tests/fixtures/scheduler.process.golden.json b/backend/tests/fixtures/scheduledPublisher.process.golden.json
similarity index 87%
rename from backend/tests/fixtures/scheduler.process.golden.json
rename to backend/tests/fixtures/scheduledPublisher.process.golden.json
index a4f98ff..ee1dfb3 100644
--- a/backend/tests/fixtures/scheduler.process.golden.json
+++ b/backend/tests/fixtures/scheduledPublisher.process.golden.json
@@ -101,39 +101,39 @@
"logLines": [
[
"log",
- "Published scheduled post p-image → media m-c-IG1"
+ "{\"level\":\"info\",\"message\":\"scheduled post published\",\"requestId\":\"cron-test\",\"postId\":\"p-image\",\"mediaId\":\"m-c-IG1\"}"
],
[
"log",
- "Published scheduled post p-reel → media m-c-IG1"
+ "{\"level\":\"info\",\"message\":\"scheduled post published\",\"requestId\":\"cron-test\",\"postId\":\"p-reel\",\"mediaId\":\"m-c-IG1\"}"
],
[
"error",
- "Failed to publish scheduled post p-story: Processing failed: Bad video"
+ "{\"level\":\"error\",\"message\":\"scheduled post failed\",\"requestId\":\"cron-test\",\"postId\":\"p-story\",\"error\":\"Processing failed: Bad video\",\"errorName\":\"UpstreamError\"}"
],
[
"error",
- "Failed to publish scheduled post p-expired: Container expired"
+ "{\"level\":\"error\",\"message\":\"scheduled post failed\",\"requestId\":\"cron-test\",\"postId\":\"p-expired\",\"error\":\"Container expired\",\"errorName\":\"UpstreamError\"}"
],
[
"error",
- "Failed to publish scheduled post p-missing: Account not found: gone"
+ "{\"level\":\"error\",\"message\":\"scheduled post failed\",\"requestId\":\"cron-test\",\"postId\":\"p-missing\",\"error\":\"Account not found: gone\",\"errorName\":\"NotFoundError\"}"
],
[
"error",
- "Failed to publish scheduled post p-create: Invalid image"
+ "{\"level\":\"error\",\"message\":\"scheduled post failed\",\"requestId\":\"cron-test\",\"postId\":\"p-create\",\"error\":\"Invalid image\",\"errorName\":\"UpstreamError\"}"
],
[
"error",
- "Failed to publish scheduled post p-publish: Publish refused"
+ "{\"level\":\"error\",\"message\":\"scheduled post failed\",\"requestId\":\"cron-test\",\"postId\":\"p-publish\",\"error\":\"Publish refused\",\"errorName\":\"UpstreamError\"}"
],
[
"error",
- "Failed to publish scheduled post p-slow: Instagram did not finish processing the media within 3 minutes"
+ "{\"level\":\"error\",\"message\":\"scheduled post failed\",\"requestId\":\"cron-test\",\"postId\":\"p-slow\",\"error\":\"Instagram did not finish processing the media within 3 minutes\",\"errorName\":\"UpstreamError\"}"
],
[
"log",
- "Published scheduled post p-dup → media m-c-IG1"
+ "{\"level\":\"info\",\"message\":\"scheduled post published\",\"requestId\":\"cron-test\",\"postId\":\"p-dup\",\"mediaId\":\"m-c-IG1\"}"
]
],
"requests": [
@@ -150,11 +150,11 @@
"method": "POST"
},
{
- "url": "https://graph.instagram.com/v25.0/c-IG1?fields=status_code,status&access_token=T1",
+ "url": "https://graph.instagram.com/v25.0/c-IG1?fields=status_code%2Cstatus&access_token=T1",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-IG1?fields=status_code,status&access_token=T1",
+ "url": "https://graph.instagram.com/v25.0/c-IG1?fields=status_code%2Cstatus&access_token=T1",
"method": "GET"
},
{
@@ -166,7 +166,7 @@
"method": "POST"
},
{
- "url": "https://graph.instagram.com/v25.0/c-ERR?fields=status_code,status&access_token=T2",
+ "url": "https://graph.instagram.com/v25.0/c-ERR?fields=status_code%2Cstatus&access_token=T2",
"method": "GET"
},
{
@@ -174,11 +174,11 @@
"method": "POST"
},
{
- "url": "https://graph.instagram.com/v25.0/c-EXP?fields=status_code,status&access_token=T3",
+ "url": "https://graph.instagram.com/v25.0/c-EXP?fields=status_code%2Cstatus&access_token=T3",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-EXP?fields=status_code,status&access_token=T3",
+ "url": "https://graph.instagram.com/v25.0/c-EXP?fields=status_code%2Cstatus&access_token=T3",
"method": "GET"
},
{
@@ -198,243 +198,243 @@
"method": "POST"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
- "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
{
diff --git a/backend/tests/fixtures/scheduler.dbFailure.golden.json b/backend/tests/fixtures/scheduler.dbFailure.golden.json
deleted file mode 100644
index 096ba0a..0000000
--- a/backend/tests/fixtures/scheduler.dbFailure.golden.json
+++ /dev/null
@@ -1,13 +0,0 @@
-{
- "result": {
- "processed": 0,
- "errors": []
- },
- "logLines": [
- [
- "error",
- "Scheduler error:",
- "Error: db down"
- ]
- ]
-}
diff --git a/backend/tests/fixtures/instagramTokens.idle.golden.json b/backend/tests/fixtures/tokenRefreshService.idle.golden.json
similarity index 51%
rename from backend/tests/fixtures/instagramTokens.idle.golden.json
rename to backend/tests/fixtures/tokenRefreshService.idle.golden.json
index 5e60d59..ba8ee4b 100644
--- a/backend/tests/fixtures/instagramTokens.idle.golden.json
+++ b/backend/tests/fixtures/tokenRefreshService.idle.golden.json
@@ -2,8 +2,7 @@
"lines": [
[
"error",
- "autoRefreshInstagramTokens error:",
- "database unavailable"
+ "{\"level\":\"error\",\"message\":\"token refresh could not load accounts\",\"requestId\":\"cron-test\",\"error\":\"The database request failed. Try again in a moment.\",\"errorName\":\"DatabaseError\",\"cause\":\"database unavailable\"}"
]
],
"requests": [],
diff --git a/backend/tests/fixtures/instagramTokens.autoRefresh.golden.json b/backend/tests/fixtures/tokenRefreshService.refresh.golden.json
similarity index 87%
rename from backend/tests/fixtures/instagramTokens.autoRefresh.golden.json
rename to backend/tests/fixtures/tokenRefreshService.refresh.golden.json
index b00152a..2aca2eb 100644
--- a/backend/tests/fixtures/instagramTokens.autoRefresh.golden.json
+++ b/backend/tests/fixtures/tokenRefreshService.refresh.golden.json
@@ -2,15 +2,15 @@
"lines": [
[
"log",
- "Token refreshed for @soon - expires 2026-10-31T12:00:00.000Z"
+ "{\"level\":\"info\",\"message\":\"instagram token refreshed\",\"requestId\":\"cron-test\",\"accountId\":\"a1\",\"username\":\"soon\",\"tokenExpiresAt\":\"2026-10-31T12:00:00.000Z\"}"
],
[
"error",
- "Failed to refresh token for @failing: Session has expired"
+ "{\"level\":\"error\",\"message\":\"instagram token refresh failed\",\"requestId\":\"cron-test\",\"accountId\":\"a6\",\"username\":\"failing\",\"error\":\"Session has expired\",\"errorName\":\"UpstreamError\"}"
],
[
"log",
- "Token refreshed for @expired - expires 2026-10-31T12:00:00.000Z"
+ "{\"level\":\"info\",\"message\":\"instagram token refreshed\",\"requestId\":\"cron-test\",\"accountId\":\"a7\",\"username\":\"expired\",\"tokenExpiresAt\":\"2026-10-31T12:00:00.000Z\"}"
]
],
"requests": [
diff --git a/backend/tests/routes/publishing.test.ts b/backend/tests/routes/publishingRoutes.test.ts
similarity index 83%
rename from backend/tests/routes/publishing.test.ts
rename to backend/tests/routes/publishingRoutes.test.ts
index 7f110f8..a70673e 100644
--- a/backend/tests/routes/publishing.test.ts
+++ b/backend/tests/routes/publishingRoutes.test.ts
@@ -1,6 +1,6 @@
import { test, describe, beforeEach, afterEach } from 'node:test';
import assert from 'node:assert/strict';
-import publishingRouter from '../../routes/publishing.ts';
+import publishingRouter from '../../routes/publishingRoutes.ts';
import { installFetch, reply } from '../fixtures/fakeFetch.ts';
import type { FetchMock } from '../fixtures/fakeFetch.ts';
import { fakeSupabase, accountRow } from '../fixtures/fakeSupabase.ts';
@@ -23,6 +23,10 @@ function buildApp() {
return mountWithContext(app => app.route('/', publishingRouter), { supabase: fakeSupabase(ACCOUNTS), userId: 'user-1' });
}
+function failure(status: number, code: string, message: string) {
+ return { status, body: { success: false, code, message, requestId: 'req-test' } };
+}
+
async function call(method: string, path: string, json?: unknown, env = {}) {
const result = await callRoute(buildApp(), method, path, { json, env });
return { status: result.status, body: JSON.parse(result.body) as Record<string, unknown> };
@@ -30,7 +34,7 @@ async function call(method: string, path: string, json?: unknown, env = {}) {
describe('publishing routes check the account before calling Instagram', () => {
test('an Instagram account without a token is refused with 400 on every publishing route', async () => {
- const expected = { status: 400, body: { success: false, message: 'No Instagram access token stored - reconnect this account' } };
+ const expected = failure(400, 'VALIDATION_ERROR', 'No Instagram access token stored - reconnect this account');
assert.deepEqual(await call('GET', '/accounts/igNoToken/ig-publishing-limit'), expected);
assert.deepEqual(await call('POST', '/accounts/igNoToken/ig-publish', { mediaType: 'IMAGE', imageUrl: 'https://cdn/a.jpg' }), expected);
assert.deepEqual(await call('POST', '/accounts/igNoToken/ig-media-publish', { containerId: 'c-1' }), expected);
@@ -39,8 +43,8 @@ describe('publishing routes check the account before calling Instagram', () => {
});
test('the container status route needs an Instagram account id', async () => {
- assert.deepEqual(await call('GET', '/ig-container/c-1/status'), { status: 400, body: { success: false, message: 'accountId is required' } });
- assert.deepEqual(await call('GET', '/ig-container/c-1/status?accountId=yt1'), { status: 404, body: { success: false, message: 'Instagram account not found' } });
+ assert.deepEqual(await call('GET', '/ig-container/c-1/status'), failure(400, 'VALIDATION_ERROR', 'accountId is required'));
+ assert.deepEqual(await call('GET', '/ig-container/c-1/status?accountId=yt1'), failure(404, 'NOT_FOUND', 'Instagram account not found'));
assert.deepEqual(fetchMock!.requests, []);
});
@@ -51,7 +55,7 @@ describe('publishing routes check the account before calling Instagram', () => {
});
test('a missing Cloudinary configuration is an error status, not a 200', async () => {
- assert.deepEqual(await call('GET', '/cloudinary-config'), { status: 503, body: { success: false, message: 'Cloudinary not configured on server' } });
+ assert.deepEqual(await call('GET', '/cloudinary-config'), failure(503, 'NOT_CONFIGURED', 'Cloudinary not configured on server'));
assert.deepEqual(await call('GET', '/cloudinary-config', undefined, { CLOUDINARY_CLOUD_NAME: 'cloud', CLOUDINARY_UPLOAD_PRESET: 'preset' }), {
status: 200, body: { success: true, cloudName: 'cloud', uploadPreset: 'preset' },
});
diff --git a/backend/tests/routes/scheduledPostRoutes.test.ts b/backend/tests/routes/scheduledPostRoutes.test.ts
new file mode 100644
index 0000000..6f4d497
--- /dev/null
+++ b/backend/tests/routes/scheduledPostRoutes.test.ts
@@ -0,0 +1,82 @@
+import { test, describe, before, after, afterEach, mock } from 'node:test';
+import assert from 'node:assert/strict';
+import scheduledPostRoutes from '../../routes/scheduledPostRoutes.ts';
+import { fakeSupabase, tableRow } from '../fixtures/fakeSupabase.ts';
+import type { FakeSupabase } from '../fixtures/fakeSupabase.ts';
+import { mountWithContext, callRoute } from '../fixtures/routeHarness.ts';
+
+const FIXED_NOW = Date.parse('2026-09-01T12:00:00Z');
+
+function postRow(id: string, status: string, userId = 'user-1') {
+ return tableRow('scheduled_posts', {
+ id, user_id: userId, account_id: 'ig1', status, scheduled_at: '2026-09-02T00:00:00.000Z', data: { caption: 'Old', mediaUrl: 'https://cdn/a.jpg' },
+ });
+}
+
+before(() => mock.timers.enable({ apis: ['Date'], now: FIXED_NOW }));
+after(() => mock.timers.reset());
+afterEach(() => mock.restoreAll());
+
+function setup(rows = [postRow('pending1', 'pending'), postRow('busy', 'publishing'), postRow('done', 'published'), postRow('theirs', 'pending', 'user-2')]) {
+ mock.method(Math, 'random', () => 0.5);
+ mock.method(console, 'warn', () => undefined);
+ const supabase = fakeSupabase(rows);
+ const app = mountWithContext(app => app.route('/', scheduledPostRoutes), { supabase, userId: 'user-1' });
+ const call = async (method: string, path: string, json?: unknown) => {
+ const response = await callRoute(app, method, path, { json });
+ return { status: response.status, body: JSON.parse(response.body) as Record<string, unknown> };
+ };
+ return { supabase, call };
+}
+
+function failure(status: number, code: string, message: string) {
+ return { status, body: { success: false, code, message, requestId: 'req-test' } };
+}
+
+function storedData(supabase: FakeSupabase, id: string) {
+ return supabase.table.find(row => row.id === id)?.data as Record<string, unknown>;
+}
+
+describe('scheduled post routes', () => {
+ test('creating a post needs an account, media and a future time', async () => {
+ const { call } = setup();
+ const required = failure(400, 'VALIDATION_ERROR', 'accountId, mediaUrl, and scheduledAt are required');
+ assert.deepEqual(await call('POST', '/scheduled-posts', { accountId: 'ig1', mediaUrl: 'https://cdn/b.jpg' }), required);
+ assert.deepEqual(await call('POST', '/scheduled-posts', { accountId: 'ig1', mediaUrl: 'https://cdn/b.jpg', scheduledAt: '2026-08-01T00:00:00Z' }),
+ failure(400, 'VALIDATION_ERROR', 'scheduledAt must be a valid future date'));
+ assert.deepEqual(await call('POST', '/scheduled-posts', { accountId: 'ig1', mediaUrl: 'https://cdn/b.jpg', scheduledAt: '2026-09-03T00:00:00Z', mediaType: 'GIF' }),
+ failure(400, 'VALIDATION_ERROR', 'mediaType must be one of IMAGE, VIDEO, REELS, STORIES, CAROUSEL'));
+ });
+
+ test('a created post gets its defaults and is stored for the user', async () => {
+ const { supabase, call } = setup([]);
+ const created = await call('POST', '/scheduled-posts', { accountId: 'ig1', mediaUrl: ' https://cdn/b.jpg ', scheduledAt: '2026-09-03T08:00:00+02:00', caption: 'Hi' });
+ assert.equal(created.status, 200);
+ assert.deepEqual(created.body.post, {
+ id: (created.body.post as { id: string }).id,
+ accountId: 'ig1', platform: 'instagram', mediaType: 'IMAGE', mediaUrl: 'https://cdn/b.jpg', caption: 'Hi', coverUrl: null,
+ shareToFeed: true, collaborators: [], audioName: '', thumbOffset: null, locationId: '', userTags: [], altText: '',
+ scheduledAt: '2026-09-03T06:00:00.000Z', status: 'pending', createdAt: '2026-09-01T12:00:00.000Z', publishedMediaId: null, error: null,
+ });
+ assert.equal(supabase.table[0].user_id, 'user-1');
+ });
+
+ test('only pending posts of the user can be edited, and only the editable fields change', async () => {
+ const { supabase, call } = setup();
+ const edited = await call('PUT', '/scheduled-posts/pending1', { caption: 'New', mediaUrl: 'https://evil/x.jpg', coverUrl: null });
+ assert.equal(edited.status, 200);
+ assert.deepEqual(storedData(supabase, 'pending1'), { caption: 'New', mediaUrl: 'https://cdn/a.jpg', coverUrl: null });
+ assert.deepEqual(await call('PUT', '/scheduled-posts/done', { caption: 'x' }), failure(400, 'VALIDATION_ERROR', 'Can only edit pending posts'));
+ assert.deepEqual(await call('PUT', '/scheduled-posts/theirs', { caption: 'x' }), failure(404, 'NOT_FOUND', 'Scheduled post not found'));
+ assert.deepEqual(await call('PUT', '/scheduled-posts/pending1', { scheduledAt: 'soon' }), failure(400, 'VALIDATION_ERROR', 'scheduledAt must be a valid date'));
+ });
+
+ test('a post being published cannot be deleted, and delete all keeps it', async () => {
+ const { supabase, call } = setup();
+ assert.deepEqual(await call('DELETE', '/scheduled-posts/busy'), failure(400, 'VALIDATION_ERROR', 'Cannot delete a post that is currently publishing'));
+ assert.deepEqual(await call('DELETE', '/scheduled-posts/pending1'), { status: 200, body: { success: true, message: 'Scheduled post deleted' } });
+ const all = await call('DELETE', '/scheduled-posts');
+ assert.equal(all.status, 200);
+ assert.deepEqual(supabase.table.map(row => row.id).sort(), ['busy', 'theirs']);
+ });
+});
diff --git a/backend/tests/services/instagram/instagramTokens.test.ts b/backend/tests/services/instagram/instagramTokens.test.ts
index 4c40de1..c2d35f5 100644
--- a/backend/tests/services/instagram/instagramTokens.test.ts
+++ b/backend/tests/services/instagram/instagramTokens.test.ts
@@ -1,13 +1,10 @@
import { test, describe, before, after, afterEach, mock } from 'node:test';
-import { exchangeForLongLivedToken, refreshLongLivedToken, autoRefreshInstagramTokens } from '../../../services/instagram/instagramTokens.ts';
+import { exchangeForLongLivedToken, refreshLongLivedToken } from '../../../services/instagram/instagramTokens.ts';
import { assertGolden } from '../../fixtures/golden.ts';
import { installFetch, reply } from '../../fixtures/fakeFetch.ts';
import type { FetchMock } from '../../fixtures/fakeFetch.ts';
-import { fakeSupabase, accountRow } from '../../fixtures/fakeSupabase.ts';
import { FIXED_NOW } from '../../fixtures/instagramFixtures.ts';
-import type { SupabaseClient } from '../../../types/app.ts';
-const DAY_MS = 86400000;
let fetchMock: FetchMock | null = null;
before(() => mock.timers.enable({ apis: ['Date'], now: FIXED_NOW }));
@@ -25,17 +22,6 @@ async function outcomeOf(promise: Promise<unknown>) {
}
}
-function captureConsole() {
- const lines: unknown[][] = [];
- mock.method(console, 'log', (...args: unknown[]) => lines.push(['log', ...args]));
- mock.method(console, 'error', (...args: unknown[]) => lines.push(['error', ...args]));
- return lines;
-}
-
-function expiresIn(days: number) {
- return new Date(FIXED_NOW + days * DAY_MS).toISOString();
-}
-
describe('token exchange and refresh golden output', () => {
test('exchange and refresh map the response and reject a missing token', async () => {
const bodies = [
@@ -58,36 +44,3 @@ describe('token exchange and refresh golden output', () => {
assertGolden({ outcomes, requests: fetchMock.requests }, 'instagramTokens.exchange');
});
});
-
-describe('autoRefreshInstagramTokens golden output', () => {
- test('refreshes only tokens that expire within fifteen days and logs each result', async () => {
- const supabase = fakeSupabase([
- accountRow({ id: 'a1', platform: 'instagram', username: 'soon', accessToken: 'T1', tokenExpiresAt: expiresIn(5) }),
- accountRow({ id: 'a2', platform: 'instagram', username: 'later', accessToken: 'T2', tokenExpiresAt: expiresIn(40) }),
- accountRow({ id: 'a3', platform: 'instagram', username: 'notoken', tokenExpiresAt: expiresIn(1) }),
- accountRow({ id: 'a4', platform: 'instagram', username: 'noexpiry', accessToken: 'T4' }),
- accountRow({ id: 'a5', platform: 'youtube', channelId: 'UC1', accessToken: 'T5', tokenExpiresAt: expiresIn(1) }),
- accountRow({ id: 'a6', platform: 'instagram', username: 'failing', accessToken: 'T6', tokenExpiresAt: expiresIn(15) }),
- accountRow({ id: 'a7', platform: 'instagram', username: 'expired', accessToken: 'T7', tokenExpiresAt: expiresIn(-2) }, 'user-2'),
- ]);
- const bodies = {
- T1: { access_token: 'N1', expires_in: 5184000 },
- T6: { error: { message: 'Session has expired' } },
- T7: { access_token: 'N7' },
- };
- fetchMock = installFetch((request) => reply(bodies[new URL(request.url).searchParams.get('access_token') as keyof typeof bodies]));
- const lines = captureConsole();
- await autoRefreshInstagramTokens(supabase);
- assertGolden({ lines, requests: fetchMock.requests, calls: supabase.calls, table: supabase.table }, 'instagramTokens.autoRefresh');
- });
-
- test('does nothing without due accounts and logs a failed account lookup', async () => {
- fetchMock = installFetch(() => reply({}));
- const lines = captureConsole();
- const notDue = fakeSupabase([accountRow({ id: 'b1', platform: 'instagram', accessToken: 'T', tokenExpiresAt: expiresIn(30) })]);
- await autoRefreshInstagramTokens(notDue);
- await autoRefreshInstagramTokens(fakeSupabase([]));
- await autoRefreshInstagramTokens({ from() { throw new Error('database unavailable'); } } as unknown as SupabaseClient);
- assertGolden({ lines, requests: fetchMock.requests, calls: notDue.calls }, 'instagramTokens.idle');
- });
-});
diff --git a/backend/tests/utils/scheduler.test.ts b/backend/tests/services/scheduledPublisher.test.ts
similarity index 87%
rename from backend/tests/utils/scheduler.test.ts
rename to backend/tests/services/scheduledPublisher.test.ts
index 4fe9cfe..abc484d 100644
--- a/backend/tests/utils/scheduler.test.ts
+++ b/backend/tests/services/scheduledPublisher.test.ts
@@ -1,6 +1,9 @@
import { test, describe, before, after, afterEach, mock } from 'node:test';
import assert from 'node:assert/strict';
-import { processScheduledPosts } from '../../utils/scheduler.ts';
+import { createScheduledPublisher } from '../../services/scheduledPublisher.ts';
+import { createAccountRepository } from '../../repositories/accountRepository.ts';
+import { createScheduledPostRepository } from '../../repositories/scheduledPostRepository.ts';
+import { createLogger } from '../../lib/logger.ts';
import { assertGolden } from '../fixtures/golden.ts';
import { installFetch, reply } from '../fixtures/fakeFetch.ts';
import type { FetchMock, RecordedRequest } from '../fixtures/fakeFetch.ts';
@@ -67,9 +70,18 @@ function describeArg(arg: unknown) {
}
let fetchMock: FetchMock | null = null;
+
+function processScheduledPosts(supabase: SupabaseClient) {
+ const context = { requestId: 'cron-test', signal: new AbortController().signal, log: createLogger({ requestId: 'cron-test' }) };
+ return createScheduledPublisher({
+ accounts: createAccountRepository(supabase),
+ posts: createScheduledPostRepository(supabase),
+ context,
+ }).publishDue();
+}
afterEach(() => fetchMock?.restore());
-describe('processScheduledPosts golden output', () => {
+describe('scheduled publisher golden output', () => {
before(() => mock.timers.enable({ apis: ['Date'], now: FIXED_NOW }));
after(() => mock.timers.reset());
@@ -85,7 +97,7 @@ describe('processScheduledPosts golden output', () => {
const result = await processScheduledPosts(supabase);
mock.restoreAll();
- assertGolden({ result, delays, logLines, requests: fetchMock.requests, queries: supabase.calls, table: supabase.table }, 'scheduler.process');
+ assertGolden({ result, delays, logLines, requests: fetchMock.requests, queries: supabase.calls, table: supabase.table }, 'scheduledPublisher.process');
});
test('a failing due post query is logged and nothing is processed', async () => {
@@ -94,11 +106,11 @@ describe('processScheduledPosts golden output', () => {
const result = await processScheduledPosts({ from() { throw new Error('db down'); } } as unknown as SupabaseClient);
mock.restoreAll();
- assertGolden({ result, logLines }, 'scheduler.dbFailure');
+ assertGolden({ result, logLines }, 'scheduledPublisher.dbFailure');
});
});
-describe('processScheduledPosts account checks', () => {
+describe('scheduled publisher account checks', () => {
test('fails posts whose account is not an Instagram account or has no token, without calling Instagram', async () => {
const supabase = fakeSupabase([
tableRow('accounts', accountRow({ id: 'yt1', platform: 'youtube', channelId: 'UC1' })),
diff --git a/backend/tests/services/tokenRefreshService.test.ts b/backend/tests/services/tokenRefreshService.test.ts
new file mode 100644
index 0000000..7e6589e
--- /dev/null
+++ b/backend/tests/services/tokenRefreshService.test.ts
@@ -0,0 +1,69 @@
+import { describe, test, before, after, afterEach, mock } from 'node:test';
+import { createTokenRefreshService } from '../../services/tokenRefreshService.ts';
+import { createAccountRepository } from '../../repositories/accountRepository.ts';
+import { createLogger } from '../../lib/logger.ts';
+import { assertGolden } from '../fixtures/golden.ts';
+import { installFetch, reply } from '../fixtures/fakeFetch.ts';
+import type { FetchMock } from '../fixtures/fakeFetch.ts';
+import { fakeSupabase, accountRow } from '../fixtures/fakeSupabase.ts';
+import { FIXED_NOW } from '../fixtures/instagramFixtures.ts';
+import type { SupabaseClient } from '../../types/app.ts';
+
+const DAY_MS = 86400000;
+let fetchMock: FetchMock | null = null;
+
+before(() => mock.timers.enable({ apis: ['Date'], now: FIXED_NOW }));
+after(() => mock.timers.reset());
+afterEach(() => {
+ fetchMock?.restore();
+ mock.restoreAll();
+});
+
+function expiresIn(days: number) {
+ return new Date(FIXED_NOW + days * DAY_MS).toISOString();
+}
+
+function captureConsole() {
+ const lines: unknown[][] = [];
+ mock.method(console, 'log', (...args: unknown[]) => lines.push(['log', ...args]));
+ mock.method(console, 'error', (...args: unknown[]) => lines.push(['error', ...args]));
+ return lines;
+}
+
+function refreshTokens(supabase: SupabaseClient): Promise<void> {
+ const context = { requestId: 'cron-test', signal: new AbortController().signal, log: createLogger({ requestId: 'cron-test' }) };
+ return createTokenRefreshService({ accounts: createAccountRepository(supabase), context }).refreshExpiringInstagramTokens();
+}
+
+describe('refreshExpiringInstagramTokens golden output', () => {
+ test('refreshes only tokens that expire within fifteen days and logs each result', async () => {
+ const supabase = fakeSupabase([
+ accountRow({ id: 'a1', platform: 'instagram', username: 'soon', accessToken: 'T1', tokenExpiresAt: expiresIn(5) }),
+ accountRow({ id: 'a2', platform: 'instagram', username: 'later', accessToken: 'T2', tokenExpiresAt: expiresIn(40) }),
+ accountRow({ id: 'a3', platform: 'instagram', username: 'notoken', tokenExpiresAt: expiresIn(1) }),
+ accountRow({ id: 'a4', platform: 'instagram', username: 'noexpiry', accessToken: 'T4' }),
+ accountRow({ id: 'a5', platform: 'youtube', channelId: 'UC1', accessToken: 'T5', tokenExpiresAt: expiresIn(1) }),
+ accountRow({ id: 'a6', platform: 'instagram', username: 'failing', accessToken: 'T6', tokenExpiresAt: expiresIn(15) }),
+ accountRow({ id: 'a7', platform: 'instagram', username: 'expired', accessToken: 'T7', tokenExpiresAt: expiresIn(-2) }, 'user-2'),
+ ]);
+ const bodies = {
+ T1: { access_token: 'N1', expires_in: 5184000 },
+ T6: { error: { message: 'Session has expired' } },
+ T7: { access_token: 'N7' },
+ };
+ fetchMock = installFetch((request) => reply(bodies[new URL(request.url).searchParams.get('access_token') as keyof typeof bodies]));
+ const lines = captureConsole();
+ await refreshTokens(supabase);
+ assertGolden({ lines, requests: fetchMock.requests, calls: supabase.calls, table: supabase.table }, 'tokenRefreshService.refresh');
+ });
+
+ test('does nothing without due accounts and logs a failed account lookup', async () => {
+ fetchMock = installFetch(() => reply({}));
+ const lines = captureConsole();
+ const notDue = fakeSupabase([accountRow({ id: 'b1', platform: 'instagram', accessToken: 'T', tokenExpiresAt: expiresIn(30) })]);
+ await refreshTokens(notDue);
+ await refreshTokens(fakeSupabase([]));
+ await refreshTokens({ from() { throw new Error('database unavailable'); } } as unknown as SupabaseClient);
+ assertGolden({ lines, requests: fetchMock.requests, calls: notDue.calls }, 'tokenRefreshService.idle');
+ });
+});
diff --git a/backend/utils/scheduler.ts b/backend/utils/scheduler.ts
deleted file mode 100644
index 9ab6105..0000000
--- a/backend/utils/scheduler.ts
+++ /dev/null
@@ -1,102 +0,0 @@
-// fetch is a global in Cloudflare Workers.
-import { getDuePosts, updatePost, getAccountById, claimPost } from '../lib/db.ts';
-import { buildMediaParams } from '../services/instagram/instagramPublishing.ts';
-import type { InstagramMediaParams } from '../services/instagram/instagramPublishing.ts';
-import type { InstagramApiContainerStatus, InstagramApiIdResponse } from '../services/instagram/instagramApi.ts';
-import type { ScheduledPost, ScheduledPublishFailure, ScheduledPublishRun } from '../../shared/types/domain.ts';
-import type { InstagramPublishMediaType } from '../../shared/types/instagram.ts';
-import type { SupabaseClient } from '../types/app.ts';
-
-const GRAPH_API = 'https://graph.instagram.com/v25.0';
-
-export function generateId(): string {
- return Date.now().toString(36) + Math.random().toString(36).substring(2, 8);
-}
-
-function wait(ms: number): Promise<void> {
- return new Promise<void>(resolve => setTimeout(resolve, ms));
-}
-
-async function createContainer(igId: string, params: InstagramMediaParams): Promise<string> {
- // URLSearchParams stringifies the boolean and number values
- const query = new URLSearchParams(params as unknown as Record<string, string>).toString();
- const createRes = await fetch(`${GRAPH_API}/${igId}/media?${query}`, { method: 'POST' });
- const createData = await createRes.json() as InstagramApiIdResponse;
- if (createData.error) throw new Error(createData.error.message);
- return createData.id;
-}
-
-// reels and stories need processing; other media only need a short pause
-async function waitForContainer(mediaType: InstagramPublishMediaType | undefined, containerId: string, token: string): Promise<void> {
- 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() as InstagramApiContainerStatus;
- 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');
- }
- throw new Error('Instagram did not finish processing the media within 3 minutes');
-}
-
-async function publishContainer(igId: string, containerId: string, token: string): Promise<string> {
- const pubRes = await fetch(
- `${GRAPH_API}/${igId}/media_publish?creation_id=${containerId}&access_token=${token}`,
- { method: 'POST' }
- );
- const pubData = await pubRes.json() as InstagramApiIdResponse;
- if (pubData.error) throw new Error(pubData.error.message);
- return pubData.id;
-}
-
-async function publishPost(supabase: SupabaseClient, post: ScheduledPost): Promise<string> {
- const acct = await getAccountById(supabase, post.accountId);
- if (!acct) throw new Error('Account not found: ' + post.accountId);
- if (acct.platform !== 'instagram' || !acct.igUserId) throw new Error('Scheduled posts can only publish to Instagram accounts');
- if (!acct.accessToken) throw new Error('No Instagram access token stored - reconnect this account');
-
- 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: there is no request context, so supabase is passed in directly
-export async function processScheduledPosts(supabase: SupabaseClient): Promise<ScheduledPublishRun> {
- let processed = 0;
- const errors: ScheduledPublishFailure[] = [];
-
- try {
- const duePosts = await getDuePosts(supabase);
-
- for (const post of duePosts) {
- if (!(await claimPost(supabase, post.id))) continue;
-
- try {
- const mediaId = await publishPost(supabase, post);
- await updatePost(supabase, post.id, {
- status: 'published',
- publishedMediaId: mediaId,
- publishedAt: new Date().toISOString(),
- });
- processed++;
- console.log(`Published scheduled post ${post.id} → media ${mediaId}`);
- } catch (err) {
- await updatePost(supabase, post.id, { status: 'failed', error: (err as Error).message });
- errors.push({ id: post.id, error: (err as Error).message });
- console.error(`Failed to publish scheduled post ${post.id}: ${(err as Error).message}`);
- }
- }
- } catch (err) {
- console.error('Scheduler error:', err);
- }
-
- return { processed, errors };
-}
diff --git a/backend/validators/publishingValidators.ts b/backend/validators/publishingValidators.ts
new file mode 100644
index 0000000..50007dd
--- /dev/null
+++ b/backend/validators/publishingValidators.ts
@@ -0,0 +1,69 @@
+import { ValidationError } from '../lib/errors.ts';
+import { isObject, isString, optionalArray, optionalBoolean, optionalNumber, optionalString, requiredString } from './fields.ts';
+import type { Fields } from './fields.ts';
+import type { UserTag } from '../../shared/types/domain.ts';
+import type { InstagramPublishMediaType, InstagramPublishRequest } from '../../shared/types/instagram.ts';
+
+const PUBLISH_MEDIA_TYPES: InstagramPublishMediaType[] = ['IMAGE', 'VIDEO', 'REELS', 'STORIES', 'CAROUSEL', 'CAROUSEL_ITEM_IMAGE', 'CAROUSEL_ITEM_VIDEO'];
+
+export interface ContainerInput {
+ containerId: string;
+}
+
+export interface ContainerStatusQuery {
+ accountId: string;
+}
+
+export function mediaType<T extends string>(fields: Fields, allowed: T[]): T | undefined {
+ const value = optionalString(fields, 'mediaType');
+ if (!value) return undefined;
+ if (!allowed.includes(value as T)) throw new ValidationError(`mediaType must be one of ${allowed.join(', ')}`);
+ return value as T;
+}
+
+function isUserTag(item: unknown): item is UserTag {
+ return isObject(item) && typeof item.username === 'string';
+}
+
+export function userTags(fields: Fields): UserTag[] | undefined {
+ return optionalArray(fields, 'userTags', isUserTag, 'tags with a username');
+}
+
+// the fields every Instagram post can carry, shared by publishing now and scheduling for later
+export function postDetails(fields: Fields): Omit<InstagramPublishRequest, 'mediaType' | 'children'> {
+ const coverUrl = fields.coverUrl === null ? null : optionalString(fields, 'coverUrl');
+ const thumbOffset = fields.thumbOffset === null ? null : optionalNumber(fields, 'thumbOffset');
+ return {
+ mediaUrl: optionalString(fields, 'mediaUrl'),
+ caption: optionalString(fields, 'caption'),
+ coverUrl,
+ shareToFeed: optionalBoolean(fields, 'shareToFeed'),
+ collaborators: optionalArray(fields, 'collaborators', isString, 'usernames'),
+ audioName: optionalString(fields, 'audioName'),
+ thumbOffset,
+ locationId: optionalString(fields, 'locationId'),
+ userTags: userTags(fields),
+ altText: optionalString(fields, 'altText'),
+ };
+}
+
+// leaves out fields the client did not send, so buildMediaParams only sees real values
+function withoutUndefined<T extends object>(value: T): T {
+ return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined)) as T;
+}
+
+export function parsePublishRequest(body: Fields): InstagramPublishRequest {
+ return withoutUndefined({
+ mediaType: mediaType(body, PUBLISH_MEDIA_TYPES),
+ ...postDetails(body),
+ children: optionalArray(body, 'children', isString, 'container ids'),
+ });
+}
+
+export function parseContainerInput(body: Fields): ContainerInput {
+ return { containerId: requiredString(body, 'containerId', 'containerId is required') };
+}
+
+export function parseContainerStatusQuery(query: Fields): ContainerStatusQuery {
+ return { accountId: requiredString(query, 'accountId', 'accountId is required') };
+}
diff --git a/backend/validators/scheduledPostValidators.ts b/backend/validators/scheduledPostValidators.ts
new file mode 100644
index 0000000..0fae8be
--- /dev/null
+++ b/backend/validators/scheduledPostValidators.ts
@@ -0,0 +1,41 @@
+import { ValidationError } from '../lib/errors.ts';
+import { mediaType, postDetails } from './publishingValidators.ts';
+import { optionalString, presentField, requiredString } from './fields.ts';
+import type { Fields } from './fields.ts';
+import type { MediaType, Platform, ScheduledPostRequest, ScheduledPostUpdateRequest } from '../../shared/types/domain.ts';
+
+const SCHEDULED_MEDIA_TYPES: MediaType[] = ['IMAGE', 'VIDEO', 'REELS', 'STORIES', 'CAROUSEL'];
+const PLATFORMS: Platform[] = ['instagram'];
+
+// the fields a pending post can change; anything else in the body is ignored
+const EDITABLE_FIELDS = ['caption', 'scheduledAt', 'shareToFeed', 'collaborators', 'audioName', 'thumbOffset', 'locationId', 'userTags', 'altText', 'coverUrl'] as const;
+
+function platform(fields: Fields): Platform | undefined {
+ const value = optionalString(fields, 'platform');
+ if (!value) return undefined;
+ if (!PLATFORMS.includes(value as Platform)) throw new ValidationError('Only Instagram posts can be scheduled');
+ return value as Platform;
+}
+
+export function parseScheduledPost(body: Fields): ScheduledPostRequest {
+ const required = 'accountId, mediaUrl, and scheduledAt are required';
+ return {
+ ...postDetails(body),
+ accountId: requiredString(body, 'accountId', required),
+ mediaUrl: requiredString(body, 'mediaUrl', required),
+ scheduledAt: requiredString(body, 'scheduledAt', required),
+ platform: platform(body),
+ mediaType: mediaType(body, SCHEDULED_MEDIA_TYPES),
+ };
+}
+
+export function parseScheduledPostUpdate(body: Fields): ScheduledPostUpdateRequest {
+ const details = postDetails(body);
+ const all: ScheduledPostUpdateRequest = { ...details, scheduledAt: optionalString(body, 'scheduledAt') };
+ if (all.scheduledAt && Number.isNaN(new Date(all.scheduledAt).getTime())) throw new ValidationError('scheduledAt must be a valid date');
+ const changes: ScheduledPostUpdateRequest = {};
+ for (const field of EDITABLE_FIELDS) {
+ if (presentField(body, field)) Object.assign(changes, { [field]: all[field] });
+ }
+ return changes;
+}
diff --git a/docs/workflows/TESTING.md b/docs/workflows/TESTING.md
index 4f3ab23..304617b 100644
--- a/docs/workflows/TESTING.md
+++ b/docs/workflows/TESTING.md
@@ -23,7 +23,7 @@ Tests never sit next to source files. Each workspace has a `tests/` folder that
|---|---|
| `backend/services/youtube.ts` | `backend/tests/services/youtube.test.ts` |
| `backend/routes/accounts.ts` | `backend/tests/routes/accounts.test.ts` |
-| `backend/routes/publishing.ts` | `backend/tests/routes/publishing.test.ts` |
+| `backend/routes/publishingRoutes.ts` | `backend/tests/routes/publishingRoutes.test.ts` |
| `backend/routes/settings.ts` | `backend/tests/routes/settings.test.ts` |
| `backend/utils/scheduler.ts` | `backend/tests/utils/scheduler.test.ts` |
| `frontend/src/lib/accounts.ts` | `frontend/tests/lib/accounts.test.ts` |