File size: 9,785 Bytes
6d9f36a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
import { Express, Router } from "express";
import { readdirSync, statSync, existsSync } from "fs";
import { join, extname, relative } from "path";
import { watch } from "chokidar";
import { pathToFileURL } from "url";
import { ApiPluginHandler, PluginMetadata, PluginRegistry } from "./types/plugin";

export class PluginLoader {
  private pluginRegistry: PluginRegistry = {};
  private pluginsDir: string;
  private router: Router | null = null;
  private app: Express | null = null;
  private watcher: any = null;

  constructor(pluginsDir: string) {
    this.pluginsDir = pluginsDir;
  }

  async loadPlugins(app: Express, enableHotReload = false) {
    this.app = app;
    this.router = Router();

    await this.scanDirectory(this.pluginsDir, this.router);
    app.use("/api", this.router);

    console.log(`✅ Loaded ${Object.keys(this.pluginRegistry).length} plugins`);

    if (enableHotReload) {
      this.enableHotReload();
    }

    return this.pluginRegistry;
  }

  private enableHotReload() {
    if (this.watcher) {
      console.log("Hot reload already enabled");
      return;
    }

    console.log("🔥 Hot reload enabled for plugins");

    let reloadTimeout: NodeJS.Timeout | null = null;

    this.watcher = watch(this.pluginsDir, {
      ignored: /(^|[\/\\])\../, // ignore dotfiles
      persistent: true,
      ignoreInitial: true,
      awaitWriteFinish: {
        stabilityThreshold: 500,
        pollInterval: 100,
      },
    });

    const handleChange = (eventType: string, path: string) => {
      console.log(`📝 Plugin ${eventType}: ${relative(this.pluginsDir, path)}`);

      if (reloadTimeout) {
        clearTimeout(reloadTimeout);
      }

      reloadTimeout = setTimeout(() => {
        this.reloadPlugins();
      }, 200);
    };

    this.watcher
      .on("add", (path: string) => handleChange("added", path))
      .on("change", (path: string) => handleChange("changed", path))
      .on("unlink", (path: string) => {
        console.log(`🗑️ Plugin removed: ${relative(this.pluginsDir, path)}`);
        this.reloadPlugins();
      });
  }

  private async reloadPlugins() {
    if (!this.app || !this.router) return;

    try {
      console.log("🔄 Reloading plugins...");
      const oldRegistry = { ...this.pluginRegistry };
      const oldRouter = this.router;
      this.pluginRegistry = {};
      const newRouter = Router();
      this.clearModuleCache(this.pluginsDir);

      try {
        await this.scanDirectory(this.pluginsDir, newRouter);

        // If successful, replace old router with new one
        this.removeOldRouter();
        this.router = newRouter;
        this.app.use("/api", this.router);

        console.log(`✅ Successfully reloaded ${Object.keys(this.pluginRegistry).length} plugins`);
      } catch (scanError) {
        console.error("❌ Error scanning plugins, rolling back...");
        this.pluginRegistry = oldRegistry;
        this.router = oldRouter;
        throw scanError;
      }
    } catch (error) {
      console.error("❌ Error reloading plugins:", error);
      console.log("⚠️ Keeping previous plugin configuration");
    }
  }

  private removeOldRouter() {
    if (!this.app) return;

    try {
      // Express 5 uses app._router differently
      const stack = (this.app as any)._router?.stack || [];

      for (let i = stack.length - 1; i >= 0; i--) {
        const layer = stack[i];
        if (layer.name === 'router' && layer.regexp.test('/api')) {
          stack.splice(i, 1);
        }
      }
    } catch (error) {
      // if _router structure is different, just log warning
      console.warn("⚠️ Could not remove old router, continuing anyway...");
    }
  }

  private clearModuleCache(dirPath: string) {
    if (!existsSync(dirPath)) return;

    const items = readdirSync(dirPath);

    for (const item of items) {
      const fullPath = join(dirPath, item);
      const stat = statSync(fullPath);

      if (stat.isDirectory()) {
        this.clearModuleCache(fullPath);
      } else if (stat.isFile() && (extname(item) === ".ts" || extname(item) === ".js")) {
        // In ES modules, we can't clear cache like CommonJS.
        // Hot Reload also doesn't seem to have any effect on API serving.
        // For now, Just log and mark as reload, We have to restart the server in "development" mode.
        // TODO: Find another way. If hot reloading doesn't work, try restarting automatically.
        const relativePath = relative(process.cwd(), fullPath);
        console.log(`♻️ Marked for reload: ${relativePath}`);
      }
    }
  }

  private async scanDirectory(dir: string, router: Router, categoryPath: string[] = []) {
    try {
      const items = readdirSync(dir);

      for (const item of items) {
        const fullPath = join(dir, item);
        const stat = statSync(fullPath);

        if (stat.isDirectory()) {
          await this.scanDirectory(fullPath, router, [...categoryPath, item]);
        } else if (stat.isFile() && (extname(item) === ".ts" || extname(item) === ".js")) {
          await this.loadPlugin(fullPath, router, categoryPath);
        }
      }
    } catch (error) {
      console.error(`❌ Error scanning directory ${dir}:`, error);
    }
  }

  private isValidPluginMetadata(handler: ApiPluginHandler, fileName: string): { valid: boolean; reason?: string } {
    if (!handler.category || !Array.isArray(handler.category) || handler.category.length === 0) {
      return { valid: false, reason: 'category is missing or empty' };
    }

    if (!handler.name || typeof handler.name !== 'string' || handler.name.trim() === '') {
      return { valid: false, reason: 'name is missing or empty' };
    }

    if (!handler.description || typeof handler.description !== 'string' || handler.description.trim() === '') {
      return { valid: false, reason: 'description is missing or empty' };
    }

    return { valid: true };
  }

  private async loadPlugin(filePath: string, router: Router, categoryPath: string[]) {
    const fileName = relative(this.pluginsDir, filePath);
    
    try {
      const fileUrl = pathToFileURL(filePath).href;
      const cacheBuster = `?update=${Date.now()}`;
      const module = await import(fileUrl + cacheBuster);

      const handler: ApiPluginHandler = module.default;

      if (!handler || !handler.exec) {
        console.warn(`⚠️ Skipping plugin '${fileName}': missing handler or exec function`);
        return;
      }

      if (!handler.method) {
        console.warn(`⚠️ Skipping plugin '${fileName}': missing 'method' field`);
        return;
      }

      if (!handler.alias || handler.alias.length === 0) {
        console.warn(`⚠️ Skipping plugin '${fileName}': missing 'alias' array`);
        return;
      }

      if (typeof handler.exec !== 'function') {
        console.warn(`⚠️ Skipping plugin '${fileName}': 'exec' must be a function`);
        return;
      }

      const metadataValidation = this.isValidPluginMetadata(handler, fileName);
      const shouldShowInDocs = metadataValidation.valid;

      if (!shouldShowInDocs) {
        console.warn(`⚠️ Plugin '${fileName}' will be hidden from docs: ${metadataValidation.reason}`);
      }

      const basePath = handler.category && handler.category.length > 0 
        ? `/${handler.category.join("/")}` 
        : "";

      const primaryAlias = handler.alias[0];
      const primaryEndpoint = basePath ? `${basePath}/${primaryAlias}` : `/${primaryAlias}`;
      const method = handler.method.toLowerCase() as "get" | "post" | "put" | "delete" | "patch";

      const wrappedExec = async (req: any, res: any, next: any) => {
        try {
          await handler.exec(req, res, next);
        } catch (error) {
          console.error(`❌ Error in plugin ${handler.name || 'unknown'}:`, error);
          if (!res.headersSent) {
            res.status(500).json({
              success: false,
              message: "Plugin execution error",
              plugin: handler.name || 'unknown',
              error: error instanceof Error ? error.message : "Unknown error",
            });
          }
        }
      };

      for (const alias of handler.alias) {
        const endpoint = basePath ? `${basePath}/${alias}` : `/${alias}`;
        router[method](endpoint, wrappedExec);
        console.log(`✓ [${handler.method}] ${endpoint} -> ${handler.name || 'unnamed'}`);
      }

      if (shouldShowInDocs) {
        const metadata: PluginMetadata = {
          name: handler.name,
          description: handler.description,
          version: handler.version || "1.0.0",
          category: handler.category,
          method: handler.method,
          endpoint: primaryEndpoint,
          aliases: handler.alias,
          tags: handler.tags || [],
          parameters: handler.parameters || {
            query: [],
            body: [],
            headers: [],
            path: []
          },
          responses: handler.responses || {}
        };

        this.pluginRegistry[primaryEndpoint] = { handler, metadata };
      }
    } catch (error) {
      console.error(`❌ Failed to load plugin '${fileName}':`, error instanceof Error ? error.message : error);
    }
  }

  getPluginMetadata(): PluginMetadata[] {
    return Object.values(this.pluginRegistry).map(p => p.metadata);
  }

  getPluginRegistry(): PluginRegistry {
    return this.pluginRegistry;
  }

  stopHotReload() {
    if (this.watcher) {
      this.watcher.close();
      this.watcher = null;
      console.log("🛑 Hot reload stopped");
    }
  }
}

let pluginLoader: PluginLoader;

export function initPluginLoader(pluginsDir: string) {
  pluginLoader = new PluginLoader(pluginsDir);
  return pluginLoader;
}

export function getPluginLoader() {
  return pluginLoader;
}