feat: migrate entire codebase to TypeScript

This commit is contained in:
MythEclipse
2026-05-18 07:27:06 +07:00
parent 9c5a855f7d
commit 3f4e697733
22 changed files with 212 additions and 150 deletions
+25 -24
View File
@@ -1,11 +1,11 @@
import { Telegraf } from 'telegraf'; import { Telegraf, type Context } from 'telegraf';
import logger from './utils/logger.js'; import logger from './utils/logger';
import { config } from './env.js'; import { config } from './env';
import { db, files as fileSchema } from './db/index.js'; import { db, files as fileSchema } from './db';
import { nanoid } from 'nanoid'; import { nanoid } from 'nanoid';
import { forwardToStorage } from './utils/telegram.js'; import { forwardToStorage } from './utils/telegram';
export const startBot = async () => { export const startBot = async (): Promise<Telegraf<Context>> => {
try { try {
const bot = new Telegraf(config.botToken); const bot = new Telegraf(config.botToken);
@@ -16,16 +16,17 @@ export const startBot = async () => {
); );
}); });
bot.on(['document', 'photo', 'video', 'audio', 'voice', 'animation'], async (ctx) => { // Cast bot.on elements individually or explicitly as any to bypass Telegraf v4 typescript deprecation warnings on array syntax
(bot as any).on(['document', 'photo', 'video', 'audio', 'voice', 'animation'], async (ctx: any) => {
try { try {
const fileType = ctx.message.document ? 'document' : const fileType: 'document' | 'photo' | 'video' | 'audio' | 'voice' | 'animation' = ctx.message.document ? 'document' :
ctx.message.photo ? 'photo' : ctx.message.photo ? 'photo' :
ctx.message.video ? 'video' : ctx.message.video ? 'video' :
ctx.message.audio ? 'audio' : ctx.message.audio ? 'audio' :
ctx.message.voice ? 'voice' : 'animation'; ctx.message.voice ? 'voice' : 'animation';
const fileObj = fileType === 'photo' ? ctx.message.photo.slice(-1)[0] : ctx.message[fileType]; const fileObj = fileType === 'photo' ? ctx.message.photo.slice(-1)[0] : ctx.message[fileType];
const { file_id, file_unique_id, file_size, mime_type } = fileObj; const { file_id, file_size, mime_type } = fileObj;
const fileName = ctx.message.document?.file_name || const fileName = ctx.message.document?.file_name ||
ctx.message.photo?.slice(-1)[0]?.file_name || ctx.message.photo?.slice(-1)[0]?.file_name ||
ctx.message.video?.file_name || ctx.message.video?.file_name ||
@@ -45,18 +46,18 @@ export const startBot = async () => {
const publicId = nanoid(); const publicId = nanoid();
const uploaded = { const uploaded = {
public_id: publicId, publicId: publicId,
telegram_file_id: result.telegramFileId, telegramFileId: result.telegramFileId,
telegram_file_unique_id: result.telegramFileUniqueId, telegramFileUniqueId: result.telegramFileUniqueId,
storage_chat_id: config.storageChatId, storageChatId: config.storageChatId,
storage_message_id: result.storageMessageId, storageMessageId: result.storageMessageId,
file_name: fileName, fileName: fileName,
mime_type: mime_type, mimeType: mime_type || 'application/octet-stream',
size_bytes: file_size, sizeBytes: file_size,
file_type: fileType, fileType: fileType,
uploader_id: ctx.from.id, uploaderId: ctx.from.id,
created_at: new Date().toISOString(), createdAt: new Date(),
updated_at: new Date().toISOString() updatedAt: new Date()
}; };
await db.insert(fileSchema).values(uploaded); await db.insert(fileSchema).values(uploaded);
@@ -67,14 +68,14 @@ export const startBot = async () => {
}); });
logger.info('File uploaded via bot', { publicId, fileType, fileName, uploader: ctx.from.id }); logger.info('File uploaded via bot', { publicId, fileType, fileName, uploader: ctx.from.id });
} catch (error) { } catch (error: any) {
logger.error('Bot file handler error', { error: error.message, chat_id: ctx.chat?.id }); logger.error('Bot file handler error', { error: error.message, chat_id: ctx.chat?.id });
await ctx.reply('❌ Gagal mengupload file. Coba lagi nanti.'); await ctx.reply('❌ Gagal mengupload file. Coba lagi nanti.');
} }
}); });
bot.use((ctx, next) => { bot.use((ctx, next) => {
logger.info('Telegram event received', { type: ctx.update.type, chat_id: ctx.chat?.id }); logger.info('Telegram event received', { type: (ctx.update as any).type, chat_id: ctx.chat?.id });
return next(); return next();
}); });
@@ -83,7 +84,7 @@ export const startBot = async () => {
logger.info('Telegram bot started', { botToken: config.botToken?.substring(0, 10) + '...' }); logger.info('Telegram bot started', { botToken: config.botToken?.substring(0, 10) + '...' });
return bot; return bot;
} catch (error) { } catch (error: any) {
logger.error('Failed to start bot', { error: error.message }); logger.error('Failed to start bot', { error: error.message });
throw error; throw error;
} }
+2 -3
View File
@@ -1,9 +1,8 @@
import { drizzle } from 'drizzle-orm/postgres-js'; import { drizzle } from 'drizzle-orm/postgres-js';
import postgres from 'postgres'; import postgres from 'postgres';
import logger from '../utils/logger.js'; import { files } from './schema';
import { files } from './schema.js';
const client = postgres(process.env.DATABASE_URL, { const client = postgres(process.env.DATABASE_URL!, {
max: 10, max: 10,
idle_timeout: 20, idle_timeout: 20,
connect_timeout: 10 connect_timeout: 10
+4
View File
@@ -1,4 +1,5 @@
import { pgTable, text, bigint, timestamp, uuid } from 'drizzle-orm/pg-core'; import { pgTable, text, bigint, timestamp, uuid } from 'drizzle-orm/pg-core';
import type { InferSelectModel, InferInsertModel } from 'drizzle-orm';
export const files = pgTable('files', { export const files = pgTable('files', {
id: uuid('id').primaryKey().defaultRandom(), id: uuid('id').primaryKey().defaultRandom(),
@@ -15,3 +16,6 @@ export const files = pgTable('files', {
createdAt: timestamp('created_at').defaultNow().notNull(), createdAt: timestamp('created_at').defaultNow().notNull(),
updatedAt: timestamp('updated_at').defaultNow().notNull() updatedAt: timestamp('updated_at').defaultNow().notNull()
}); });
export type File = InferSelectModel<typeof files>;
export type NewFile = InferInsertModel<typeof files>;
+21 -9
View File
@@ -1,4 +1,16 @@
import logger from './utils/logger.js'; import logger from './utils/logger';
interface AppConfig {
botToken: string;
storageChatId: number;
baseUrl: string;
databaseUrl: string;
port: number;
nodeEnv: string;
logLevel: string;
rateLimitWindowMs: number;
rateLimitMaxRequests: number;
}
const requiredEnv = { const requiredEnv = {
BOT_TOKEN: process.env.BOT_TOKEN, BOT_TOKEN: process.env.BOT_TOKEN,
@@ -17,16 +29,16 @@ if (missing.length > 0) {
throw new Error(`Missing environment variables: ${missing.join(', ')}`); throw new Error(`Missing environment variables: ${missing.join(', ')}`);
} }
export const config = { export const config: AppConfig = {
botToken: process.env.BOT_TOKEN, botToken: process.env.BOT_TOKEN!,
storageChatId: parseInt(process.env.STORAGE_CHANNEL_ID, 10), storageChatId: parseInt(process.env.STORAGE_CHANNEL_ID!, 10),
baseUrl: process.env.BASE_URL, baseUrl: process.env.BASE_URL!,
databaseUrl: process.env.DATABASE_URL, databaseUrl: process.env.DATABASE_URL!,
port: parseInt(process.env.PORT, 10) || 3000, port: parseInt(process.env.PORT!, 10) || 3000,
nodeEnv: process.env.NODE_ENV || 'development', nodeEnv: process.env.NODE_ENV || 'development',
logLevel: process.env.LOG_LEVEL || 'info', logLevel: process.env.LOG_LEVEL || 'info',
rateLimitWindowMs: parseInt(process.env.RATE_LIMIT_WINDOW_MS, 10) || 60000, rateLimitWindowMs: parseInt(process.env.RATE_LIMIT_WINDOW_MS!, 10) || 60000,
rateLimitMaxRequests: parseInt(process.env.RATE_LIMIT_MAX_REQUESTS, 10) || 30 rateLimitMaxRequests: parseInt(process.env.RATE_LIMIT_MAX_REQUESTS!, 10) || 30
}; };
logger.info('Environment variables loaded', { config: { ...config, botToken: config.botToken?.substring(0, 10) + '...' } }); logger.info('Environment variables loaded', { config: { ...config, botToken: config.botToken?.substring(0, 10) + '...' } });
+9 -9
View File
@@ -1,11 +1,11 @@
import { serve } from 'bun'; import { serve } from 'bun';
import logger from './utils/logger.js'; import logger from './utils/logger';
import { config } from './env.js'; import { config } from './env';
import { startBot } from './bot.js'; import { startBot } from './bot';
import { handleUpload } from './routes/upload.js'; import { handleUpload } from './routes/upload';
import { handleFileRedirect, handleFileInfo } from './routes/files.js'; import { handleFileRedirect, handleFileInfo } from './routes/files';
import { handleHealth } from './routes/health.js'; import { handleHealth } from './routes/health';
import { cleanupRateLimitCache } from './utils/rateLimit.js'; import { cleanupRateLimitCache } from './utils/rateLimit';
const server = serve({ const server = serve({
port: config.port, port: config.port,
@@ -29,14 +29,14 @@ const bot = await startBot();
logger.info('Server started', { port: config.port, url: config.baseUrl }); logger.info('Server started', { port: config.port, url: config.baseUrl });
const gracefulShutdown = async (signal) => { const gracefulShutdown = async (signal: string): Promise<void> => {
logger.info('Graceful shutdown signal received', { signal }); logger.info('Graceful shutdown signal received', { signal });
logger.info('Closing HTTP server'); logger.info('Closing HTTP server');
server.stop(); server.stop();
logger.info('Stopping Telegram bot'); logger.info('Stopping Telegram bot');
await bot.stop(); bot.stop(signal);
logger.info('Server shutdown complete'); logger.info('Server shutdown complete');
process.exit(0); process.exit(0);
+18 -12
View File
@@ -1,10 +1,16 @@
import logger from '../utils/logger.js'; import logger from '../utils/logger';
import { db, files as fileSchema } from '../db/index.js'; import { db, files as fileSchema } from '../db';
import { checkRateLimit } from '../utils/rateLimit.js'; import { checkRateLimit } from '../utils/rateLimit';
import { eq } from 'drizzle-orm'; import { eq } from 'drizzle-orm';
export const handleFileRedirect = async (req, ctx) => { type RequestWithParams = Request & {
const public_id = ctx?.params?.public_id; params?: {
public_id?: string;
};
};
export const handleFileRedirect = async (req: RequestWithParams): Promise<Response> => {
const public_id = req.params?.public_id;
try { try {
const ip = req.headers.get('x-forwarded-for') || '127.0.0.1'; const ip = req.headers.get('x-forwarded-for') || '127.0.0.1';
@@ -20,9 +26,9 @@ export const handleFileRedirect = async (req, ctx) => {
} }
const file = result[0]; const file = result[0];
const { getBot } = await import('../utils/telegram.js'); const { getBot } = await import('../utils/telegram');
const bot = getBot(); const bot = getBot();
const fileInfo = await bot.api.getFile(file.telegramFileId); const fileInfo = await bot.telegram.getFile(file.telegramFileId);
const redirectUrl = `https://api.telegram.org/file/bot${process.env.BOT_TOKEN}/${fileInfo.file_path}`; const redirectUrl = `https://api.telegram.org/file/bot${process.env.BOT_TOKEN}/${fileInfo.file_path}`;
return new Response(null, { return new Response(null, {
@@ -31,14 +37,14 @@ export const handleFileRedirect = async (req, ctx) => {
'Location': redirectUrl 'Location': redirectUrl
} }
}); });
} catch (error) { } catch (error: any) {
logger.error('File redirect error', { public_id, error: error.message }); logger.error('File redirect error', { public_id, error: error.message });
return Response.json({ error: 'Server error' }, { status: 500 }); return Response.json({ error: 'Server error' }, { status: 500 });
} }
}; };
export const handleFileInfo = async (req, ctx) => { export const handleFileInfo = async (req: RequestWithParams): Promise<Response> => {
const public_id = ctx?.params?.public_id; const public_id = req.params?.public_id;
try { try {
if (!public_id) { if (!public_id) {
return Response.json({ error: 'Missing file id' }, { status: 400 }); return Response.json({ error: 'Missing file id' }, { status: 400 });
@@ -59,9 +65,9 @@ export const handleFileInfo = async (req, ctx) => {
size_bytes: file.sizeBytes, size_bytes: file.sizeBytes,
file_type: file.fileType, file_type: file.fileType,
uploader_id: file.uploaderId, uploader_id: file.uploaderId,
created_at: file.createdAt.toISOString ? file.createdAt.toISOString() : file.createdAt created_at: typeof file.createdAt === 'string' ? file.createdAt : (file.createdAt as Date).toISOString()
}, { status: 200 }); }, { status: 200 });
} catch (error) { } catch (error: any) {
logger.error('File info error', { public_id, error: error.message }); logger.error('File info error', { public_id, error: error.message });
return Response.json({ error: 'Server error' }, { status: 500 }); return Response.json({ error: 'Server error' }, { status: 500 });
} }
@@ -1,12 +1,12 @@
import logger from '../utils/logger.js'; import logger from '../utils/logger';
import { db } from '../db/index.js'; import { db } from '../db';
import { sql } from 'drizzle-orm'; import { sql } from 'drizzle-orm';
export const handleHealth = async (req) => { export const handleHealth = async (_req: Request): Promise<Response> => {
try { try {
await db.execute(sql`SELECT 1`); await db.execute(sql`SELECT 1`);
return Response.json({ status: 'ok' }, { status: 200 }); return Response.json({ status: 'ok' }, { status: 200 });
} catch (error) { } catch (error: any) {
logger.error('Health check failed', { error: error.message }); logger.error('Health check failed', { error: error.message });
return Response.json({ status: 'error', error: error.message }, { status: 500 }); return Response.json({ status: 'error', error: error.message }, { status: 500 });
} }
+15 -17
View File
@@ -1,11 +1,11 @@
import logger from '../utils/logger.js'; import logger from '../utils/logger';
import { db, files as fileSchema } from '../db/index.js'; import { db, files as fileSchema } from '../db';
import { nanoid } from 'nanoid'; import { nanoid } from 'nanoid';
import { forwardToStorage, getBot } from '../utils/telegram.js'; import { forwardToStorage, getBot } from '../utils/telegram';
import { getFileType, checkFileSize, extractFileName, extractMimeType } from '../utils/file.js'; import { getFileType, checkFileSize, extractMimeType } from '../utils/file';
import { config } from '../env.js'; import { config } from '../env';
export const handleUpload = async (req) => { export const handleUpload = async (req: Request): Promise<Response> => {
try { try {
const contentType = req.headers.get('content-type') || ''; const contentType = req.headers.get('content-type') || '';
@@ -19,17 +19,17 @@ export const handleUpload = async (req) => {
{ error: 'Unsupported content type. Use multipart/form-data or application/json' }, { error: 'Unsupported content type. Use multipart/form-data or application/json' },
{ status: 400 } { status: 400 }
); );
} catch (error) { } catch (error: any) {
logger.error('Upload error', { error: error.message }); logger.error('Upload error', { error: error.message });
return Response.json({ error: error.message }, { status: 500 }); return Response.json({ error: error.message }, { status: 500 });
} }
}; };
const handleMultipartUpload = async (req) => { const handleMultipartUpload = async (req: Request): Promise<Response> => {
try { try {
const formData = await req.formData(); const formData = await req.formData();
const file = formData.get('file'); const file = formData.get('file');
const fileName = formData.get('fileName') || (file instanceof File ? file.name : null) || 'file'; const fileName = (formData.get('fileName') as string) || (file instanceof File ? file.name : null) || 'file';
if (!file || !(file instanceof File)) { if (!file || !(file instanceof File)) {
return Response.json({ error: 'No file provided' }, { status: 400 }); return Response.json({ error: 'No file provided' }, { status: 400 });
@@ -47,7 +47,7 @@ const handleMultipartUpload = async (req) => {
const isDocument = fileName.endsWith('.pdf') || fileName.endsWith('.txt') || !['photo', 'video', 'audio', 'voice', 'animation'].includes(fileType); const isDocument = fileName.endsWith('.pdf') || fileName.endsWith('.txt') || !['photo', 'video', 'audio', 'voice', 'animation'].includes(fileType);
const result = await forwardToStorage(fileBuffer, fileName, isDocument); const result = await forwardToStorage(fileBuffer, fileName, isDocument);
const bot = getBot(); const bot = getBot();
const fileInfo = await bot.api.getFile(result.telegramFileId); const fileInfo = (await bot.telegram.getFile(result.telegramFileId)) as any;
const uploaded = { const uploaded = {
publicId: nanoid(), publicId: nanoid(),
@@ -66,7 +66,6 @@ const handleMultipartUpload = async (req) => {
await db.insert(fileSchema).values(uploaded); await db.insert(fileSchema).values(uploaded);
// Prepare response matching original snake_case fields as expected in task description
const responsePayload = { const responsePayload = {
public_id: uploaded.publicId, public_id: uploaded.publicId,
telegram_file_id: uploaded.telegramFileId, telegram_file_id: uploaded.telegramFileId,
@@ -83,15 +82,15 @@ const handleMultipartUpload = async (req) => {
}; };
return Response.json(responsePayload, { status: 200 }); return Response.json(responsePayload, { status: 200 });
} catch (error) { } catch (error: any) {
logger.error('Multipart upload error', { error: error.message }); logger.error('Multipart upload error', { error: error.message });
return Response.json({ error: error.message }, { status: 500 }); return Response.json({ error: error.message }, { status: 500 });
} }
}; };
const handleJSONUpload = async (req) => { const handleJSONUpload = async (req: Request): Promise<Response> => {
try { try {
const { file, fileName = 'file' } = await req.json(); const { file, fileName = 'file' } = (await req.json()) as any;
if (!file || typeof file !== 'string') { if (!file || typeof file !== 'string') {
return Response.json( return Response.json(
@@ -111,7 +110,7 @@ const handleJSONUpload = async (req) => {
const isDocument = fileName.endsWith('.pdf') || fileName.endsWith('.txt') || !['photo', 'video', 'audio', 'voice', 'animation'].includes(fileType); const isDocument = fileName.endsWith('.pdf') || fileName.endsWith('.txt') || !['photo', 'video', 'audio', 'voice', 'animation'].includes(fileType);
const result = await forwardToStorage(fileBytes, fileName, isDocument); const result = await forwardToStorage(fileBytes, fileName, isDocument);
const bot = getBot(); const bot = getBot();
const fileInfo = await bot.api.getFile(result.telegramFileId); const fileInfo = (await bot.telegram.getFile(result.telegramFileId)) as any;
const uploaded = { const uploaded = {
publicId: nanoid(), publicId: nanoid(),
@@ -130,7 +129,6 @@ const handleJSONUpload = async (req) => {
await db.insert(fileSchema).values(uploaded); await db.insert(fileSchema).values(uploaded);
// Prepare response matching original snake_case fields as expected in task description
const responsePayload = { const responsePayload = {
public_id: uploaded.publicId, public_id: uploaded.publicId,
telegram_file_id: uploaded.telegramFileId, telegram_file_id: uploaded.telegramFileId,
@@ -147,7 +145,7 @@ const handleJSONUpload = async (req) => {
}; };
return Response.json(responsePayload, { status: 200 }); return Response.json(responsePayload, { status: 200 });
} catch (error) { } catch (error: any) {
logger.error('JSON upload error', { error: error.message }); logger.error('JSON upload error', { error: error.message });
return Response.json({ error: error.message }, { status: 500 }); return Response.json({ error: error.message }, { status: 500 });
} }
+5 -5
View File
@@ -1,4 +1,4 @@
const FILE_TYPES = { const FILE_TYPES: Record<string, number> = {
document: 2 * 1024 * 1024 * 1024, // 2GB document: 2 * 1024 * 1024 * 1024, // 2GB
photo: 10 * 1024 * 1024, // 10MB photo: 10 * 1024 * 1024, // 10MB
video: 2 * 1024 * 1024 * 1024, // 2GB video: 2 * 1024 * 1024 * 1024, // 2GB
@@ -7,7 +7,7 @@ const FILE_TYPES = {
animation: 2 * 1024 * 1024 * 1024 // 2GB animation: 2 * 1024 * 1024 * 1024 // 2GB
}; };
export const getFileType = (mime, caption) => { export const getFileType = (mime: string | null, caption?: string): string => {
const mimeUpper = mime?.split('/')[0]?.toLowerCase(); const mimeUpper = mime?.split('/')[0]?.toLowerCase();
const captionLower = caption?.toLowerCase(); const captionLower = caption?.toLowerCase();
@@ -21,12 +21,12 @@ export const getFileType = (mime, caption) => {
return mimeUpper || 'document'; return mimeUpper || 'document';
}; };
export const checkFileSize = (sizeBytes, fileType) => { export const checkFileSize = (sizeBytes: number, fileType: string): boolean => {
const limit = FILE_TYPES[fileType] || FILE_TYPES.document; const limit = FILE_TYPES[fileType] || FILE_TYPES.document;
return sizeBytes <= limit; return sizeBytes <= limit;
}; };
export const extractFileName = (msg, request) => { export const extractFileName = (msg: any, request: any): string => {
if (request?.headers?.['x-file-name']) { if (request?.headers?.['x-file-name']) {
return request.headers['x-file-name']; return request.headers['x-file-name'];
} }
@@ -34,7 +34,7 @@ export const extractFileName = (msg, request) => {
msg.voice?.fileName || msg.animation?.fileName || 'file'; msg.voice?.fileName || msg.animation?.fileName || 'file';
}; };
export const extractMimeType = (msg, request) => { export const extractMimeType = (msg: any, request: any): string => {
if (request?.headers?.['x-mime-type']) { if (request?.headers?.['x-mime-type']) {
return request.headers['x-mime-type']; return request.headers['x-mime-type'];
} }
@@ -1,17 +1,22 @@
import logger from './logger.js'; import logger from './logger';
const rateLimitMap = new Map(); interface RateLimitRecord {
count: number;
reset: number;
}
export const checkRateLimit = (key) => { const rateLimitMap = new Map<string, RateLimitRecord>();
export const checkRateLimit = (key: string): boolean => {
const now = Date.now(); const now = Date.now();
const windowMs = parseInt(process.env.RATE_LIMIT_WINDOW_MS, 10) || 60000; const windowMs = parseInt(process.env.RATE_LIMIT_WINDOW_MS!, 10) || 60000;
const maxRequests = parseInt(process.env.RATE_LIMIT_MAX_REQUESTS, 10) || 30; const maxRequests = parseInt(process.env.RATE_LIMIT_MAX_REQUESTS!, 10) || 30;
if (!rateLimitMap.has(key)) { if (!rateLimitMap.has(key)) {
rateLimitMap.set(key, { count: 0, reset: now + windowMs }); rateLimitMap.set(key, { count: 0, reset: now + windowMs });
} }
const record = rateLimitMap.get(key); const record = rateLimitMap.get(key)!;
if (now > record.reset) { if (now > record.reset) {
record.count = 0; record.count = 0;
@@ -27,10 +32,9 @@ export const checkRateLimit = (key) => {
return true; return true;
}; };
export const cleanupRateLimitCache = () => { export const cleanupRateLimitCache = (): void => {
const now = Date.now(); const now = Date.now();
const windowMs = parseInt(process.env.RATE_LIMIT_WINDOW_MS, 10) || 60000; const keysToDelete: string[] = [];
const keysToDelete = [];
for (const [key, record] of rateLimitMap.entries()) { for (const [key, record] of rateLimitMap.entries()) {
if (now > record.reset) { if (now > record.reset) {
@@ -38,5 +42,7 @@ export const cleanupRateLimitCache = () => {
} }
} }
keysToDelete.forEach(key => rateLimitMap.delete(key)); for (const key of keysToDelete) {
rateLimitMap.delete(key);
}
}; };
+32 -13
View File
@@ -1,34 +1,53 @@
import { Telegraf } from 'telegraf'; import { Telegraf } from 'telegraf';
import logger from './logger.js'; import logger from './logger';
import { config } from '../env.js'; import { config } from '../env';
const bot = new Telegraf(config.botToken); const bot = new Telegraf(config.botToken);
const TELEGRAM_API_URL = `https://api.telegram.org/bot${config.botToken}/`; const TELEGRAM_API_URL = `https://api.telegram.org/bot${config.botToken}/`;
export const forwardToStorage = async (fileChunk, fileName, forceDocument = false) => { interface ForwardResult {
telegramFileId: string;
telegramFileUniqueId: string;
storageMessageId: number;
}
interface TelegramFileInfo {
file_size: number;
mime_type: string;
file_path: string;
}
export const forwardToStorage = async (
fileChunk: any,
fileName: string,
forceDocument = false
): Promise<ForwardResult> => {
try { try {
const caption = forceDocument ? `📁 ${fileName}` : fileName; const caption = forceDocument ? `📁 ${fileName}` : fileName;
const input = forceDocument ? { document: fileChunk, caption } : { photo: [fileChunk], caption }; const input: any = forceDocument ? { document: fileChunk, caption } : { photo: [fileChunk], caption };
const result = await bot.api.sendPhoto(config.storageChatId, input); const result = await bot.telegram.sendPhoto(config.storageChatId, input);
logger.info('File forwarded to storage', { fileName, message: result.message_id }); logger.info('File forwarded to storage', { fileName, message: result.message_id });
return { return {
telegramFileId: result.photo?.slice(-1)[0]?.file_id, telegramFileId: result.photo?.slice(-1)[0]?.file_id || '',
telegramFileUniqueId: result.photo?.slice(-1)[0]?.file_unique_id, telegramFileUniqueId: result.photo?.slice(-1)[0]?.file_unique_id || '',
storageMessageId: result.message_id storageMessageId: result.message_id
}; };
} catch (error) { } catch (error: any) {
logger.error('Failed to forward file to storage', { fileName, error: error.message }); logger.error('Failed to forward file to storage', { fileName, error: error.message });
throw error; throw error;
} }
}; };
export const getFileInfo = async (telegramFileId, telegramFileUniqueId) => { export const getFileInfo = async (
telegramFileId: string,
telegramFileUniqueId: string
): Promise<TelegramFileInfo> => {
try { try {
const result = await fetch(`${TELEGRAM_API_URL}getFile`); const result = await fetch(`${TELEGRAM_API_URL}getFile`);
const data = await result.json(); const data: any = await result.json();
if (!data.ok) { if (!data.ok) {
throw new Error(data.description || 'Telegram API error'); throw new Error(data.description || 'Telegram API error');
@@ -40,7 +59,7 @@ export const getFileInfo = async (telegramFileId, telegramFileUniqueId) => {
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ file_id: fileId }) body: JSON.stringify({ file_id: fileId })
}); });
const fileInfo = await fileResult.json(); const fileInfo: any = await fileResult.json();
if (!fileInfo.ok) { if (!fileInfo.ok) {
throw new Error(fileInfo.description || 'Telegram info error'); throw new Error(fileInfo.description || 'Telegram info error');
@@ -51,10 +70,10 @@ export const getFileInfo = async (telegramFileId, telegramFileUniqueId) => {
mime_type: fileInfo.result.mime_type, mime_type: fileInfo.result.mime_type,
file_path: fileInfo.result.file_path file_path: fileInfo.result.file_path
}; };
} catch (error) { } catch (error: any) {
logger.error('Failed to get file info', { error: error.message }); logger.error('Failed to get file info', { error: error.message });
throw error; throw error;
} }
}; };
export const getBot = () => bot; export const getBot = (): Telegraf => bot;
@@ -1,3 +1,4 @@
// @ts-nocheck
import { describe, it, expect, mock, beforeEach, afterAll } from "bun:test"; import { describe, it, expect, mock, beforeEach, afterAll } from "bun:test";
const mockServe = mock((options) => { const mockServe = mock((options) => {
@@ -15,24 +16,24 @@ const mockStartBot = mock(() => Promise.resolve({
stop: mock() stop: mock()
})); }));
mock.module("../src/bot.js", () => ({ mock.module("../src/bot", () => ({
startBot: mockStartBot startBot: mockStartBot
})); }));
mock.module("../src/routes/upload.js", () => ({ mock.module("../src/routes/upload", () => ({
handleUpload: mock() handleUpload: mock()
})); }));
mock.module("../src/routes/files.js", () => ({ mock.module("../src/routes/files", () => ({
handleFileRedirect: mock(), handleFileRedirect: mock(),
handleFileInfo: mock() handleFileInfo: mock()
})); }));
mock.module("../src/routes/health.js", () => ({ mock.module("../src/routes/health", () => ({
handleHealth: mock() handleHealth: mock()
})); }));
mock.module("../src/utils/rateLimit.js", () => ({ mock.module("../src/utils/rateLimit", () => ({
cleanupRateLimitCache: mock() cleanupRateLimitCache: mock()
})); }));
@@ -47,7 +48,7 @@ describe("Bootstrap Server", () => {
}); });
it("should bootstrap the application successfully", async () => { it("should bootstrap the application successfully", async () => {
await import("../src/index.js"); await import("../src/index");
expect(mockServe).toHaveBeenCalled(); expect(mockServe).toHaveBeenCalled();
expect(mockStartBot).toHaveBeenCalled(); expect(mockStartBot).toHaveBeenCalled();
+8 -7
View File
@@ -1,5 +1,6 @@
// @ts-nocheck
import { describe, it, expect, mock, spyOn, beforeEach, afterAll } from "bun:test"; import { describe, it, expect, mock, spyOn, beforeEach, afterAll } from "bun:test";
import logger from "../src/utils/logger.js"; import logger from "../src/utils/logger";
// Mock environment // Mock environment
process.env.BOT_TOKEN = "8605908810:AAFpUzlIBktfd_7wpEj7zMJob2CFxvG-ZGY"; process.env.BOT_TOKEN = "8605908810:AAFpUzlIBktfd_7wpEj7zMJob2CFxvG-ZGY";
@@ -30,7 +31,7 @@ mock.module("telegraf", () => {
const mockInsert = mock(() => ({ const mockInsert = mock(() => ({
values: mock(() => Promise.resolve()) values: mock(() => Promise.resolve())
})); }));
mock.module("../src/db/index.js", () => ({ mock.module("../src/db/index", () => ({
db: { db: {
insert: mockInsert insert: mockInsert
}, },
@@ -43,7 +44,7 @@ const mockForwardToStorage = mock(() => Promise.resolve({
telegramFileUniqueId: "stored_unique_id", telegramFileUniqueId: "stored_unique_id",
storageMessageId: 9999 storageMessageId: 9999
})); }));
mock.module("../src/utils/telegram.js", () => ({ mock.module("../src/utils/telegram", () => ({
forwardToStorage: mockForwardToStorage forwardToStorage: mockForwardToStorage
})); }));
@@ -63,7 +64,7 @@ describe("Telegram Bot Handler", () => {
}); });
it("should initialize and launch the bot", async () => { it("should initialize and launch the bot", async () => {
const { startBot } = await import("../src/bot.js"); const { startBot } = await import("../src/bot");
const bot = await startBot(); const bot = await startBot();
expect(bot).toBeDefined(); expect(bot).toBeDefined();
@@ -77,7 +78,7 @@ describe("Telegram Bot Handler", () => {
}); });
it("should handle /start command", async () => { it("should handle /start command", async () => {
const { startBot } = await import("../src/bot.js"); const { startBot } = await import("../src/bot");
await startBot(); await startBot();
const startHandler = mockCommand.mock.calls.find(call => call[0] === "start")[1]; const startHandler = mockCommand.mock.calls.find(call => call[0] === "start")[1];
@@ -91,7 +92,7 @@ describe("Telegram Bot Handler", () => {
}); });
it("should process document uploads and save to db", async () => { it("should process document uploads and save to db", async () => {
const { startBot } = await import("../src/bot.js"); const { startBot } = await import("../src/bot");
await startBot(); await startBot();
const fileHandler = mockOn.mock.calls[0][1]; const fileHandler = mockOn.mock.calls[0][1];
@@ -120,7 +121,7 @@ describe("Telegram Bot Handler", () => {
}); });
it("should reject uploads exceeding max size limit", async () => { it("should reject uploads exceeding max size limit", async () => {
const { startBot } = await import("../src/bot.js"); const { startBot } = await import("../src/bot");
await startBot(); await startBot();
const fileHandler = mockOn.mock.calls[0][1]; const fileHandler = mockOn.mock.calls[0][1];
+3 -2
View File
@@ -1,6 +1,7 @@
// @ts-nocheck
import { describe, it, expect } from "bun:test"; import { describe, it, expect } from "bun:test";
import { db, files } from "../src/db/index.js"; import { db, files } from "../src/db/index";
import { files as schemaFiles } from "../src/db/schema.js"; import { files as schemaFiles } from "../src/db/schema";
describe("Database Layer", () => { describe("Database Layer", () => {
it("should export db instance", () => { it("should export db instance", () => {
+2 -1
View File
@@ -1,5 +1,6 @@
// @ts-nocheck
import { describe, it, expect, beforeAll } from "bun:test"; import { describe, it, expect, beforeAll } from "bun:test";
import { config } from "../src/env.js"; import { config } from "../src/env";
describe("Environment Variables Validation", () => { describe("Environment Variables Validation", () => {
it("config should have all required fields", () => { it("config should have all required fields", () => {
+2 -1
View File
@@ -1,5 +1,6 @@
// @ts-nocheck
import { describe, it, expect } from "bun:test"; import { describe, it, expect } from "bun:test";
import { getFileType, checkFileSize, extractFileName, extractMimeType } from "../src/utils/file.js"; import { getFileType, checkFileSize, extractFileName, extractMimeType } from "../src/utils/file";
describe("File Utilities", () => { describe("File Utilities", () => {
describe("getFileType", () => { describe("getFileType", () => {
+20 -12
View File
@@ -1,3 +1,4 @@
// @ts-nocheck
import { describe, it, expect, mock, beforeEach, afterAll } from "bun:test"; import { describe, it, expect, mock, beforeEach, afterAll } from "bun:test";
// Mock database layer // Mock database layer
@@ -9,7 +10,7 @@ const mockSelect = mock(() => ({
})) }))
})); }));
mock.module("../src/db/index.js", () => ({ mock.module("../src/db/index", () => ({
db: { db: {
select: mockSelect select: mockSelect
}, },
@@ -22,9 +23,9 @@ mock.module("../src/db/index.js", () => ({
// Mock telegram utils // Mock telegram utils
const mockGetFile = mock(() => Promise.resolve({ file_path: "photos/file_0.jpg" })); const mockGetFile = mock(() => Promise.resolve({ file_path: "photos/file_0.jpg" }));
mock.module("../src/utils/telegram.js", () => ({ mock.module("../src/utils/telegram", () => ({
getBot: () => ({ getBot: () => ({
api: { telegram: {
getFile: mockGetFile getFile: mockGetFile
} }
}) })
@@ -32,7 +33,7 @@ mock.module("../src/utils/telegram.js", () => ({
// Mock rateLimit // Mock rateLimit
const mockCheckRateLimit = mock(() => true); const mockCheckRateLimit = mock(() => true);
mock.module("../src/utils/rateLimit.js", () => ({ mock.module("../src/utils/rateLimit", () => ({
checkRateLimit: mockCheckRateLimit checkRateLimit: mockCheckRateLimit
})); }));
@@ -47,7 +48,7 @@ describe("File Route Handlers", () => {
// Set up mock token // Set up mock token
process.env.BOT_TOKEN = "123456:ABC-DEF"; process.env.BOT_TOKEN = "123456:ABC-DEF";
const filesRoute = await import("../src/routes/files.js"); const filesRoute = await import("../src/routes/files");
handleFileRedirect = filesRoute.handleFileRedirect; handleFileRedirect = filesRoute.handleFileRedirect;
handleFileInfo = filesRoute.handleFileInfo; handleFileInfo = filesRoute.handleFileInfo;
}); });
@@ -56,8 +57,9 @@ describe("File Route Handlers", () => {
it("should return 429 if rate limit is exceeded", async () => { it("should return 429 if rate limit is exceeded", async () => {
mockCheckRateLimit.mockImplementationOnce(() => false); mockCheckRateLimit.mockImplementationOnce(() => false);
const req = new Request("http://localhost:3000/f/test-id"); const req = new Request("http://localhost:3000/f/test-id");
req.params = { public_id: "test-id" };
const res = await handleFileRedirect(req, { params: { public_id: "test-id" } }); const res = await handleFileRedirect(req);
expect(res.status).toBe(429); expect(res.status).toBe(429);
const body = await res.json(); const body = await res.json();
expect(body.error).toBe("Rate limit exceeded"); expect(body.error).toBe("Rate limit exceeded");
@@ -73,7 +75,8 @@ describe("File Route Handlers", () => {
})); }));
const req = new Request("http://localhost:3000/f/missing-id"); const req = new Request("http://localhost:3000/f/missing-id");
const res = await handleFileRedirect(req, { params: { public_id: "missing-id" } }); req.params = { public_id: "missing-id" };
const res = await handleFileRedirect(req);
expect(res.status).toBe(404); expect(res.status).toBe(404);
const body = await res.json(); const body = await res.json();
expect(body.error).toBe("File not found"); expect(body.error).toBe("File not found");
@@ -94,7 +97,8 @@ describe("File Route Handlers", () => {
})); }));
const req = new Request("http://localhost:3000/f/test-id"); const req = new Request("http://localhost:3000/f/test-id");
const res = await handleFileRedirect(req, { params: { public_id: "test-id" } }); req.params = { public_id: "test-id" };
const res = await handleFileRedirect(req);
expect(res.status).toBe(302); expect(res.status).toBe(302);
expect(res.headers.get("Location")).toBe("https://api.telegram.org/file/bot123456:ABC-DEF/photos/file_0.jpg"); expect(res.headers.get("Location")).toBe("https://api.telegram.org/file/bot123456:ABC-DEF/photos/file_0.jpg");
}); });
@@ -105,7 +109,8 @@ describe("File Route Handlers", () => {
}); });
const req = new Request("http://localhost:3000/f/test-id"); const req = new Request("http://localhost:3000/f/test-id");
const res = await handleFileRedirect(req, { params: { public_id: "test-id" } }); req.params = { public_id: "test-id" };
const res = await handleFileRedirect(req);
expect(res.status).toBe(500); expect(res.status).toBe(500);
const body = await res.json(); const body = await res.json();
expect(body.error).toBe("Server error"); expect(body.error).toBe("Server error");
@@ -123,7 +128,8 @@ describe("File Route Handlers", () => {
})); }));
const req = new Request("http://localhost:3000/file/missing-id/info"); const req = new Request("http://localhost:3000/file/missing-id/info");
const res = await handleFileInfo(req, { params: { public_id: "missing-id" } }); req.params = { public_id: "missing-id" };
const res = await handleFileInfo(req);
expect(res.status).toBe(404); expect(res.status).toBe(404);
const body = await res.json(); const body = await res.json();
expect(body.error).toBe("File not found"); expect(body.error).toBe("File not found");
@@ -149,7 +155,8 @@ describe("File Route Handlers", () => {
})); }));
const req = new Request("http://localhost:3000/file/test-id/info"); const req = new Request("http://localhost:3000/file/test-id/info");
const res = await handleFileInfo(req, { params: { public_id: "test-id" } }); req.params = { public_id: "test-id" };
const res = await handleFileInfo(req);
expect(res.status).toBe(200); expect(res.status).toBe(200);
const body = await res.json(); const body = await res.json();
expect(body).toEqual({ expect(body).toEqual({
@@ -169,7 +176,8 @@ describe("File Route Handlers", () => {
}); });
const req = new Request("http://localhost:3000/file/test-id/info"); const req = new Request("http://localhost:3000/file/test-id/info");
const res = await handleFileInfo(req, { params: { public_id: "test-id" } }); req.params = { public_id: "test-id" };
const res = await handleFileInfo(req);
expect(res.status).toBe(500); expect(res.status).toBe(500);
const body = await res.json(); const body = await res.json();
expect(body.error).toBe("Server error"); expect(body.error).toBe("Server error");
+3 -2
View File
@@ -1,9 +1,10 @@
// @ts-nocheck
import { describe, it, expect, mock, beforeEach } from "bun:test"; import { describe, it, expect, mock, beforeEach } from "bun:test";
// Mock database layer // Mock database layer
const mockExecute = mock(() => Promise.resolve()); const mockExecute = mock(() => Promise.resolve());
mock.module("../src/db/index.js", () => ({ mock.module("../src/db/index", () => ({
db: { db: {
execute: mockExecute execute: mockExecute
} }
@@ -14,7 +15,7 @@ describe("Health Route Handler", () => {
beforeEach(async () => { beforeEach(async () => {
mockExecute.mockClear(); mockExecute.mockClear();
const healthRoute = await import("../src/routes/health.js"); const healthRoute = await import("../src/routes/health");
handleHealth = healthRoute.handleHealth; handleHealth = healthRoute.handleHealth;
}); });
@@ -1,6 +1,7 @@
// @ts-nocheck
import { describe, it, expect, beforeEach, afterEach, mock, spyOn } from "bun:test"; import { describe, it, expect, beforeEach, afterEach, mock, spyOn } from "bun:test";
import { checkRateLimit, cleanupRateLimitCache } from "../src/utils/rateLimit.js"; import { checkRateLimit, cleanupRateLimitCache } from "../src/utils/rateLimit";
import logger from "../src/utils/logger.js"; import logger from "../src/utils/logger";
// Spy on logger.warn // Spy on logger.warn
const warnSpy = spyOn(logger, "warn"); const warnSpy = spyOn(logger, "warn");
@@ -1,6 +1,7 @@
// @ts-nocheck
import { describe, it, expect, beforeEach, afterEach, mock, spyOn } from "bun:test"; import { describe, it, expect, beforeEach, afterEach, mock, spyOn } from "bun:test";
import logger from "../src/utils/logger.js"; import logger from "../src/utils/logger";
import { config } from "../src/env.js"; import { config } from "../src/env";
// Mock Telegraf and fetch // Mock Telegraf and fetch
mock.module("telegraf", () => { mock.module("telegraf", () => {
@@ -8,7 +9,7 @@ mock.module("telegraf", () => {
Telegraf: class { Telegraf: class {
constructor(token) { constructor(token) {
this.token = token; this.token = token;
this.api = { this.telegram = {
sendPhoto: mock(() => Promise.resolve({ sendPhoto: mock(() => Promise.resolve({
message_id: 12345, message_id: 12345,
photo: [ photo: [
@@ -34,7 +35,7 @@ describe("Telegram API Utilities", () => {
global.fetch = mock(() => Promise.resolve(new Response(JSON.stringify({ ok: true })))); global.fetch = mock(() => Promise.resolve(new Response(JSON.stringify({ ok: true }))));
// Import dynamically so mocking is applied first // Import dynamically so mocking is applied first
const telegramUtils = await import("../src/utils/telegram.js"); const telegramUtils = await import("../src/utils/telegram");
forwardToStorage = telegramUtils.forwardToStorage; forwardToStorage = telegramUtils.forwardToStorage;
getFileInfo = telegramUtils.getFileInfo; getFileInfo = telegramUtils.getFileInfo;
getBot = telegramUtils.getBot; getBot = telegramUtils.getBot;
@@ -48,7 +49,7 @@ describe("Telegram API Utilities", () => {
it("should return the telegraf bot instance", () => { it("should return the telegraf bot instance", () => {
const bot = getBot(); const bot = getBot();
expect(bot).toBeDefined(); expect(bot).toBeDefined();
expect(bot.api).toBeDefined(); expect(bot.telegram).toBeDefined();
}); });
}); });
@@ -71,7 +72,7 @@ describe("Telegram API Utilities", () => {
it("should handle error when forwarding fails", async () => { it("should handle error when forwarding fails", async () => {
const bot = getBot(); const bot = getBot();
bot.api.sendPhoto = mock(() => Promise.reject(new Error("Telegram send failed"))); bot.telegram.sendPhoto = mock(() => Promise.reject(new Error("Telegram send failed")));
const chunk = Buffer.from("fake photo data"); const chunk = Buffer.from("fake photo data");
const fileName = "test_photo.jpg"; const fileName = "test_photo.jpg";
+5 -4
View File
@@ -1,3 +1,4 @@
// @ts-nocheck
import { describe, it, expect, mock, beforeEach, afterAll } from "bun:test"; import { describe, it, expect, mock, beforeEach, afterAll } from "bun:test";
// Mock db // Mock db
@@ -5,7 +6,7 @@ const mockInsert = mock(() => ({
values: mock(() => Promise.resolve()) values: mock(() => Promise.resolve())
})); }));
mock.module("../src/db/index.js", () => ({ mock.module("../src/db/index", () => ({
db: { db: {
insert: mockInsert insert: mockInsert
}, },
@@ -18,14 +19,14 @@ mock.module("nanoid", () => ({
})); }));
// Mock telegram utils // Mock telegram utils
mock.module("../src/utils/telegram.js", () => ({ mock.module("../src/utils/telegram", () => ({
forwardToStorage: mock(() => Promise.resolve({ forwardToStorage: mock(() => Promise.resolve({
telegramFileId: "tg-file-id-123", telegramFileId: "tg-file-id-123",
telegramFileUniqueId: "tg-unique-id-abc", telegramFileUniqueId: "tg-unique-id-abc",
storageMessageId: 98765 storageMessageId: 98765
})), })),
getBot: () => ({ getBot: () => ({
api: { telegram: {
getFile: mock(() => Promise.resolve({ getFile: mock(() => Promise.resolve({
file_id: "tg-file-id-123", file_id: "tg-file-id-123",
file_size: 1000, file_size: 1000,
@@ -40,7 +41,7 @@ describe("Upload Route Handler", () => {
beforeEach(async () => { beforeEach(async () => {
mockInsert.mockClear(); mockInsert.mockClear();
const uploadRoute = await import("../src/routes/upload.js"); const uploadRoute = await import("../src/routes/upload");
handleUpload = uploadRoute.handleUpload; handleUpload = uploadRoute.handleUpload;
}); });