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 logger from './utils/logger.js';
import { config } from './env.js';
import { db, files as fileSchema } from './db/index.js';
import { Telegraf, type Context } from 'telegraf';
import logger from './utils/logger';
import { config } from './env';
import { db, files as fileSchema } from './db';
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 {
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 {
const fileType = ctx.message.document ? 'document' :
const fileType: 'document' | 'photo' | 'video' | 'audio' | 'voice' | 'animation' = ctx.message.document ? 'document' :
ctx.message.photo ? 'photo' :
ctx.message.video ? 'video' :
ctx.message.audio ? 'audio' :
ctx.message.voice ? 'voice' : 'animation';
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 ||
ctx.message.photo?.slice(-1)[0]?.file_name ||
ctx.message.video?.file_name ||
@@ -45,18 +46,18 @@ export const startBot = async () => {
const publicId = nanoid();
const uploaded = {
public_id: publicId,
telegram_file_id: result.telegramFileId,
telegram_file_unique_id: result.telegramFileUniqueId,
storage_chat_id: config.storageChatId,
storage_message_id: result.storageMessageId,
file_name: fileName,
mime_type: mime_type,
size_bytes: file_size,
file_type: fileType,
uploader_id: ctx.from.id,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString()
publicId: publicId,
telegramFileId: result.telegramFileId,
telegramFileUniqueId: result.telegramFileUniqueId,
storageChatId: config.storageChatId,
storageMessageId: result.storageMessageId,
fileName: fileName,
mimeType: mime_type || 'application/octet-stream',
sizeBytes: file_size,
fileType: fileType,
uploaderId: ctx.from.id,
createdAt: new Date(),
updatedAt: new Date()
};
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 });
} catch (error) {
} catch (error: any) {
logger.error('Bot file handler error', { error: error.message, chat_id: ctx.chat?.id });
await ctx.reply('❌ Gagal mengupload file. Coba lagi nanti.');
}
});
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();
});
@@ -83,7 +84,7 @@ export const startBot = async () => {
logger.info('Telegram bot started', { botToken: config.botToken?.substring(0, 10) + '...' });
return bot;
} catch (error) {
} catch (error: any) {
logger.error('Failed to start bot', { error: error.message });
throw error;
}
+2 -3
View File
@@ -1,9 +1,8 @@
import { drizzle } from 'drizzle-orm/postgres-js';
import postgres from 'postgres';
import logger from '../utils/logger.js';
import { files } from './schema.js';
import { files } from './schema';
const client = postgres(process.env.DATABASE_URL, {
const client = postgres(process.env.DATABASE_URL!, {
max: 10,
idle_timeout: 20,
connect_timeout: 10
+5 -1
View File
@@ -1,4 +1,5 @@
import { pgTable, text, bigint, timestamp, uuid } from 'drizzle-orm/pg-core';
import type { InferSelectModel, InferInsertModel } from 'drizzle-orm';
export const files = pgTable('files', {
id: uuid('id').primaryKey().defaultRandom(),
@@ -14,4 +15,7 @@ export const files = pgTable('files', {
uploaderId: bigint('uploader_id', { mode: 'number' }).notNull(),
createdAt: timestamp('created_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 = {
BOT_TOKEN: process.env.BOT_TOKEN,
@@ -17,16 +29,16 @@ if (missing.length > 0) {
throw new Error(`Missing environment variables: ${missing.join(', ')}`);
}
export const config = {
botToken: process.env.BOT_TOKEN,
storageChatId: parseInt(process.env.STORAGE_CHANNEL_ID, 10),
baseUrl: process.env.BASE_URL,
databaseUrl: process.env.DATABASE_URL,
port: parseInt(process.env.PORT, 10) || 3000,
export const config: AppConfig = {
botToken: process.env.BOT_TOKEN!,
storageChatId: parseInt(process.env.STORAGE_CHANNEL_ID!, 10),
baseUrl: process.env.BASE_URL!,
databaseUrl: process.env.DATABASE_URL!,
port: parseInt(process.env.PORT!, 10) || 3000,
nodeEnv: process.env.NODE_ENV || 'development',
logLevel: process.env.LOG_LEVEL || 'info',
rateLimitWindowMs: parseInt(process.env.RATE_LIMIT_WINDOW_MS, 10) || 60000,
rateLimitMaxRequests: parseInt(process.env.RATE_LIMIT_MAX_REQUESTS, 10) || 30
rateLimitWindowMs: parseInt(process.env.RATE_LIMIT_WINDOW_MS!, 10) || 60000,
rateLimitMaxRequests: parseInt(process.env.RATE_LIMIT_MAX_REQUESTS!, 10) || 30
};
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 logger from './utils/logger.js';
import { config } from './env.js';
import { startBot } from './bot.js';
import { handleUpload } from './routes/upload.js';
import { handleFileRedirect, handleFileInfo } from './routes/files.js';
import { handleHealth } from './routes/health.js';
import { cleanupRateLimitCache } from './utils/rateLimit.js';
import logger from './utils/logger';
import { config } from './env';
import { startBot } from './bot';
import { handleUpload } from './routes/upload';
import { handleFileRedirect, handleFileInfo } from './routes/files';
import { handleHealth } from './routes/health';
import { cleanupRateLimitCache } from './utils/rateLimit';
const server = serve({
port: config.port,
@@ -29,14 +29,14 @@ const bot = await startBot();
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('Closing HTTP server');
server.stop();
logger.info('Stopping Telegram bot');
await bot.stop();
bot.stop(signal);
logger.info('Server shutdown complete');
process.exit(0);
+18 -12
View File
@@ -1,10 +1,16 @@
import logger from '../utils/logger.js';
import { db, files as fileSchema } from '../db/index.js';
import { checkRateLimit } from '../utils/rateLimit.js';
import logger from '../utils/logger';
import { db, files as fileSchema } from '../db';
import { checkRateLimit } from '../utils/rateLimit';
import { eq } from 'drizzle-orm';
export const handleFileRedirect = async (req, ctx) => {
const public_id = ctx?.params?.public_id;
type RequestWithParams = Request & {
params?: {
public_id?: string;
};
};
export const handleFileRedirect = async (req: RequestWithParams): Promise<Response> => {
const public_id = req.params?.public_id;
try {
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 { getBot } = await import('../utils/telegram.js');
const { getBot } = await import('../utils/telegram');
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}`;
return new Response(null, {
@@ -31,14 +37,14 @@ export const handleFileRedirect = async (req, ctx) => {
'Location': redirectUrl
}
});
} catch (error) {
} catch (error: any) {
logger.error('File redirect error', { public_id, error: error.message });
return Response.json({ error: 'Server error' }, { status: 500 });
}
};
export const handleFileInfo = async (req, ctx) => {
const public_id = ctx?.params?.public_id;
export const handleFileInfo = async (req: RequestWithParams): Promise<Response> => {
const public_id = req.params?.public_id;
try {
if (!public_id) {
return Response.json({ error: 'Missing file id' }, { status: 400 });
@@ -59,9 +65,9 @@ export const handleFileInfo = async (req, ctx) => {
size_bytes: file.sizeBytes,
file_type: file.fileType,
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 });
} catch (error) {
} catch (error: any) {
logger.error('File info error', { public_id, error: error.message });
return Response.json({ error: 'Server error' }, { status: 500 });
}
@@ -1,12 +1,12 @@
import logger from '../utils/logger.js';
import { db } from '../db/index.js';
import logger from '../utils/logger';
import { db } from '../db';
import { sql } from 'drizzle-orm';
export const handleHealth = async (req) => {
export const handleHealth = async (_req: Request): Promise<Response> => {
try {
await db.execute(sql`SELECT 1`);
return Response.json({ status: 'ok' }, { status: 200 });
} catch (error) {
} catch (error: any) {
logger.error('Health check failed', { error: error.message });
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 { db, files as fileSchema } from '../db/index.js';
import logger from '../utils/logger';
import { db, files as fileSchema } from '../db';
import { nanoid } from 'nanoid';
import { forwardToStorage, getBot } from '../utils/telegram.js';
import { getFileType, checkFileSize, extractFileName, extractMimeType } from '../utils/file.js';
import { config } from '../env.js';
import { forwardToStorage, getBot } from '../utils/telegram';
import { getFileType, checkFileSize, extractMimeType } from '../utils/file';
import { config } from '../env';
export const handleUpload = async (req) => {
export const handleUpload = async (req: Request): Promise<Response> => {
try {
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' },
{ status: 400 }
);
} catch (error) {
} catch (error: any) {
logger.error('Upload error', { error: error.message });
return Response.json({ error: error.message }, { status: 500 });
}
};
const handleMultipartUpload = async (req) => {
const handleMultipartUpload = async (req: Request): Promise<Response> => {
try {
const formData = await req.formData();
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)) {
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 result = await forwardToStorage(fileBuffer, fileName, isDocument);
const bot = getBot();
const fileInfo = await bot.api.getFile(result.telegramFileId);
const fileInfo = (await bot.telegram.getFile(result.telegramFileId)) as any;
const uploaded = {
publicId: nanoid(),
@@ -66,7 +66,6 @@ const handleMultipartUpload = async (req) => {
await db.insert(fileSchema).values(uploaded);
// Prepare response matching original snake_case fields as expected in task description
const responsePayload = {
public_id: uploaded.publicId,
telegram_file_id: uploaded.telegramFileId,
@@ -83,15 +82,15 @@ const handleMultipartUpload = async (req) => {
};
return Response.json(responsePayload, { status: 200 });
} catch (error) {
} catch (error: any) {
logger.error('Multipart upload error', { error: error.message });
return Response.json({ error: error.message }, { status: 500 });
}
};
const handleJSONUpload = async (req) => {
const handleJSONUpload = async (req: Request): Promise<Response> => {
try {
const { file, fileName = 'file' } = await req.json();
const { file, fileName = 'file' } = (await req.json()) as any;
if (!file || typeof file !== 'string') {
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 result = await forwardToStorage(fileBytes, fileName, isDocument);
const bot = getBot();
const fileInfo = await bot.api.getFile(result.telegramFileId);
const fileInfo = (await bot.telegram.getFile(result.telegramFileId)) as any;
const uploaded = {
publicId: nanoid(),
@@ -130,7 +129,6 @@ const handleJSONUpload = async (req) => {
await db.insert(fileSchema).values(uploaded);
// Prepare response matching original snake_case fields as expected in task description
const responsePayload = {
public_id: uploaded.publicId,
telegram_file_id: uploaded.telegramFileId,
@@ -147,7 +145,7 @@ const handleJSONUpload = async (req) => {
};
return Response.json(responsePayload, { status: 200 });
} catch (error) {
} catch (error: any) {
logger.error('JSON upload error', { error: error.message });
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
photo: 10 * 1024 * 1024, // 10MB
video: 2 * 1024 * 1024 * 1024, // 2GB
@@ -7,7 +7,7 @@ const FILE_TYPES = {
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 captionLower = caption?.toLowerCase();
@@ -21,12 +21,12 @@ export const getFileType = (mime, caption) => {
return mimeUpper || 'document';
};
export const checkFileSize = (sizeBytes, fileType) => {
export const checkFileSize = (sizeBytes: number, fileType: string): boolean => {
const limit = FILE_TYPES[fileType] || FILE_TYPES.document;
return sizeBytes <= limit;
};
export const extractFileName = (msg, request) => {
export const extractFileName = (msg: any, request: any): string => {
if (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';
};
export const extractMimeType = (msg, request) => {
export const extractMimeType = (msg: any, request: any): string => {
if (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 windowMs = parseInt(process.env.RATE_LIMIT_WINDOW_MS, 10) || 60000;
const maxRequests = parseInt(process.env.RATE_LIMIT_MAX_REQUESTS, 10) || 30;
const windowMs = parseInt(process.env.RATE_LIMIT_WINDOW_MS!, 10) || 60000;
const maxRequests = parseInt(process.env.RATE_LIMIT_MAX_REQUESTS!, 10) || 30;
if (!rateLimitMap.has(key)) {
rateLimitMap.set(key, { count: 0, reset: now + windowMs });
}
const record = rateLimitMap.get(key);
const record = rateLimitMap.get(key)!;
if (now > record.reset) {
record.count = 0;
@@ -27,10 +32,9 @@ export const checkRateLimit = (key) => {
return true;
};
export const cleanupRateLimitCache = () => {
export const cleanupRateLimitCache = (): void => {
const now = Date.now();
const windowMs = parseInt(process.env.RATE_LIMIT_WINDOW_MS, 10) || 60000;
const keysToDelete = [];
const keysToDelete: string[] = [];
for (const [key, record] of rateLimitMap.entries()) {
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 logger from './logger.js';
import { config } from '../env.js';
import logger from './logger';
import { config } from '../env';
const bot = new Telegraf(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 {
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 });
return {
telegramFileId: result.photo?.slice(-1)[0]?.file_id,
telegramFileUniqueId: result.photo?.slice(-1)[0]?.file_unique_id,
telegramFileId: result.photo?.slice(-1)[0]?.file_id || '',
telegramFileUniqueId: result.photo?.slice(-1)[0]?.file_unique_id || '',
storageMessageId: result.message_id
};
} catch (error) {
} catch (error: any) {
logger.error('Failed to forward file to storage', { fileName, error: error.message });
throw error;
}
};
export const getFileInfo = async (telegramFileId, telegramFileUniqueId) => {
export const getFileInfo = async (
telegramFileId: string,
telegramFileUniqueId: string
): Promise<TelegramFileInfo> => {
try {
const result = await fetch(`${TELEGRAM_API_URL}getFile`);
const data = await result.json();
const data: any = await result.json();
if (!data.ok) {
throw new Error(data.description || 'Telegram API error');
@@ -40,7 +59,7 @@ export const getFileInfo = async (telegramFileId, telegramFileUniqueId) => {
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ file_id: fileId })
});
const fileInfo = await fileResult.json();
const fileInfo: any = await fileResult.json();
if (!fileInfo.ok) {
throw new Error(fileInfo.description || 'Telegram info error');
@@ -51,10 +70,10 @@ export const getFileInfo = async (telegramFileId, telegramFileUniqueId) => {
mime_type: fileInfo.result.mime_type,
file_path: fileInfo.result.file_path
};
} catch (error) {
} catch (error: any) {
logger.error('Failed to get file info', { error: error.message });
throw error;
}
};
export const getBot = () => bot;
export const getBot = (): Telegraf => bot;