File size: 2,389 Bytes
aeffde1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
568802f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
const fastify = require('fastify')({ logger: true });
const fs = require('fs');
const path = require('path');
const chokidar = require('chokidar');

const pluginsDir = path.join(__dirname, 'plugins');

// 1. Registrasi Multipart (WAJIB untuk POST file/OCR)
fastify.register(require('@fastify/multipart'), {
  limits: { fileSize: 10 * 1024 * 1024 } // Batas 10MB
});

// 2. Registrasi EJS
fastify.register(require('@fastify/view'), {
  engine: { ejs: require('ejs') },
  root: pluginsDir
});

let availablePlugins = [];

async function loadPlugins() {
  // Membersihkan rute lama agar tidak duplikat saat reload (Opsional: Restart server lebih aman)
  availablePlugins = []; 
  if (!fs.existsSync(pluginsDir)) return;

  const files = fs.readdirSync(pluginsDir);
  files.forEach(file => {
    if (file.endsWith('.js')) {
      const filePath = path.join(pluginsDir, file);
      delete require.cache[require.resolve(filePath)];
      
      try {
        const plugin = require(filePath);
        if (plugin.path && plugin.handler) {
          // Daftarkan route
          fastify.route({
            method: plugin.method || 'GET',
            url: plugin.path,
            handler: plugin.handler
          });

          availablePlugins.push({
            name: file.replace('.js', ''),
            path: plugin.path,
            method: plugin.method || 'GET',
            description: plugin.description || 'No description'
          });
        }
      } catch (err) {
        console.error(`Error loading ${file}:`, err.message);
      }
    }
  });
}

fastify.get('/', async (request, reply) => {
  return reply.view('index.ejs', { plugins: availablePlugins });
});

const start = async () => {
  try {
    await loadPlugins();
    // Port 7860 untuk Hugging Face, atau 3000 untuk lokal
    const port = process.env.PORT || 7860; 
    await fastify.listen({ port: port, host: '0.0.0.0' });
    console.log(`Server running on port ${port}`);
  } catch (err) {
    fastify.log.error(err);
    process.exit(1);
  }
};

chokidar.watch(pluginsDir, { ignoreInitial: true }).on('all', () => {
  console.log("Plugins changed, reloading...");
  // Catatan: Fastify tidak mendukung penghapusan route secara native tanpa plugin tambahan.
  // Untuk hasil terbaik di produksi, proses harus di-restart.
});

start();