|
| 1 | +import { Plugin, PluginContext } from '@objectstack/core'; |
| 2 | +import { ObjectQL, ObjectQLHostContext } from '@objectstack/objectql'; |
| 3 | + |
| 4 | +/** |
| 5 | + * AppPlugin |
| 6 | + * |
| 7 | + * Adapts a generic App Bundle (Manifest + Runtime Code) into a Kernel Plugin. |
| 8 | + * |
| 9 | + * Responsibilities: |
| 10 | + * 1. Register App Manifest as a service (for ObjectQL discovery) |
| 11 | + * 2. Execute Runtime `onEnable` hook (for code logic) |
| 12 | + */ |
| 13 | +export class AppPlugin implements Plugin { |
| 14 | + name: string; |
| 15 | + version?: string; |
| 16 | + |
| 17 | + private bundle: any; |
| 18 | + |
| 19 | + constructor(bundle: any) { |
| 20 | + this.bundle = bundle; |
| 21 | + // Support both direct manifest (legacy) and Stack Definition (nested manifest) |
| 22 | + const sys = bundle.manifest || bundle; |
| 23 | + const appId = sys.id || sys.name || 'unnamed-app'; |
| 24 | + |
| 25 | + this.name = `plugin.app.${appId}`; |
| 26 | + this.version = sys.version; |
| 27 | + } |
| 28 | + |
| 29 | + async init(ctx: PluginContext) { |
| 30 | + const sys = this.bundle.manifest || this.bundle; |
| 31 | + const appId = sys.id || sys.name; |
| 32 | + |
| 33 | + ctx.logger?.log(`[AppPlugin] Registering App Service: ${appId}`); |
| 34 | + |
| 35 | + // Register the app manifest as a service |
| 36 | + // ObjectQLPlugin will discover this and call ql.registerApp() |
| 37 | + const serviceName = `app.${appId}`; |
| 38 | + ctx.registerService(serviceName, this.bundle.manifest || this.bundle); |
| 39 | + } |
| 40 | + |
| 41 | + async start(ctx: PluginContext) { |
| 42 | + // Execute Runtime Step |
| 43 | + // Retrieve ObjectQL engine from services |
| 44 | + // We cast to any/ObjectQL because ctx.getService returns unknown |
| 45 | + const ql = ctx.getService('objectql') as ObjectQL; |
| 46 | + |
| 47 | + if (!ql) { |
| 48 | + ctx.logger?.warn(`[AppPlugin] ObjectQL engine service not found for app: ${this.name}`); |
| 49 | + return; |
| 50 | + } |
| 51 | + |
| 52 | + const runtime = this.bundle.default || this.bundle; |
| 53 | + |
| 54 | + if (runtime && typeof runtime.onEnable === 'function') { |
| 55 | + ctx.logger?.log(`[AppPlugin] Executing runtime.onEnable for: ${this.name}`); |
| 56 | + |
| 57 | + // Construct the Host Context (mirroring old ObjectQL.use logic) |
| 58 | + const hostContext: ObjectQLHostContext = { |
| 59 | + ql, |
| 60 | + logger: ctx.logger || console, |
| 61 | + drivers: { |
| 62 | + register: (driver: any) => ql.registerDriver(driver) |
| 63 | + }, |
| 64 | + ...ctx |
| 65 | + }; |
| 66 | + |
| 67 | + await runtime.onEnable(hostContext); |
| 68 | + } |
| 69 | + } |
| 70 | +} |
0 commit comments