-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhono-plugin.ts
More file actions
332 lines (290 loc) · 12.5 KB
/
hono-plugin.ts
File metadata and controls
332 lines (290 loc) · 12.5 KB
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import { Plugin, PluginContext, IHttpServer, IDataEngine } from '@objectstack/core';
import {
RestServerConfig,
} from '@objectstack/spec/api';
import { HonoHttpServer } from './adapter';
import { serveStatic } from '@hono/node-server/serve-static';
import * as fs from 'fs';
import * as path from 'path';
export interface StaticMount {
root: string;
path?: string;
rewrite?: boolean;
spa?: boolean;
}
export interface HonoPluginOptions {
port?: number;
staticRoot?: string;
/**
* Multiple static resource mounts
*/
staticMounts?: StaticMount[];
/**
* REST server configuration
* Controls automatic endpoint generation and API behavior
*/
restConfig?: RestServerConfig;
/**
* Whether to register standard ObjectStack CRUD endpoints
* @default true
*/
registerStandardEndpoints?: boolean;
/**
* Whether to load endpoints from API Registry
* @default true
*/
useApiRegistry?: boolean;
/**
* Whether to enable SPA fallback
* If true, returns index.html for non-API 404s
* @default false
*/
spaFallback?: boolean;
}
/**
* Hono Server Plugin
*
* Provides HTTP server capabilities using Hono framework.
* Registers the IHttpServer service so other plugins can register routes.
*
* Route registration is handled by plugins:
* - `@objectstack/rest` → CRUD, metadata, discovery, UI, batch
* - `createDispatcherPlugin()` → auth, graphql, analytics, packages, etc.
*/
export class HonoServerPlugin implements Plugin {
name = 'com.objectstack.server.hono';
type = 'server';
version = '0.9.0';
// Constants
private static readonly DEFAULT_ENDPOINT_PRIORITY = 100;
private static readonly CORE_ENDPOINT_PRIORITY = 950;
private static readonly DISCOVERY_ENDPOINT_PRIORITY = 900;
private options: HonoPluginOptions;
private server: HonoHttpServer;
constructor(options: HonoPluginOptions = {}) {
this.options = {
port: 3000,
registerStandardEndpoints: true,
useApiRegistry: true,
spaFallback: false,
...options
};
// We handle static root manually in start() to support SPA fallback
this.server = new HonoHttpServer(this.options.port);
}
/**
* Init phase - Setup HTTP server and register as service
*/
init = async (ctx: PluginContext) => {
ctx.logger.debug('Initializing Hono server plugin', {
port: this.options.port,
staticRoot: this.options.staticRoot
});
// Register HTTP server service as IHttpServer
// Register as 'http.server' to match core requirements
ctx.registerService('http.server', this.server);
// Alias 'http-server' for backward compatibility
ctx.registerService('http-server', this.server);
ctx.logger.debug('HTTP server service registered', { serviceName: 'http.server' });
}
/**
* Start phase - Configure static files and start listening
*/
start = async (ctx: PluginContext) => {
ctx.logger.debug('Starting Hono server plugin');
// Configure Static Files & SPA Fallback
const mounts: StaticMount[] = this.options.staticMounts || [];
// Auto-discover UI Plugins
try {
const rawKernel = ctx.getKernel() as any;
if (rawKernel.plugins) {
const loadedPlugins = rawKernel.plugins instanceof Map
? Array.from(rawKernel.plugins.values())
: Array.isArray(rawKernel.plugins) ? rawKernel.plugins : Object.values(rawKernel.plugins);
for (const plugin of (loadedPlugins as any[])) {
// Check for UI Plugin signature
// Support legacy 'ui-plugin' and new 'ui' type
if ((plugin.type === 'ui' || plugin.type === 'ui-plugin') && plugin.staticPath) {
// Derive base route from name: @org/console -> console
const slug = plugin.slug || plugin.name.split('/').pop();
const baseRoute = `/${slug}`;
ctx.logger.debug(`Auto-mounting UI Plugin: ${plugin.name}`, {
path: baseRoute,
root: plugin.staticPath
});
mounts.push({
root: plugin.staticPath,
path: baseRoute,
rewrite: true, // Strip prefix: /console/assets/x -> /assets/x
spa: true
});
// Handle Default Plugin Redirect
if (plugin.default || plugin.isDefault) {
const rawApp = this.server.getRawApp();
rawApp.get('/', (c) => c.redirect(baseRoute));
ctx.logger.debug(`Set default UI redirect: / -> ${baseRoute}`);
}
}
}
}
} catch (err: any) {
ctx.logger.warn('Failed to auto-discover UI plugins', { error: err.message || err });
}
// Backward compatibility for staticRoot
if (this.options.staticRoot) {
mounts.push({
root: this.options.staticRoot,
path: '/',
rewrite: false,
spa: this.options.spaFallback
});
}
if (mounts.length > 0) {
const rawApp = this.server.getRawApp();
for (const mount of mounts) {
const mountRoot = path.resolve(process.cwd(), mount.root);
if (!fs.existsSync(mountRoot)) {
ctx.logger.warn(`Static mount root not found: ${mountRoot}. Skipping.`);
continue;
}
const mountPath = mount.path || '/';
const normalizedPath = mountPath.startsWith('/') ? mountPath : `/${mountPath}`;
const routePattern = normalizedPath === '/' ? '/*' : `${normalizedPath.replace(/\/$/, '')}/*`;
// Routes to register: both /mount and /mount/*
const routes = normalizedPath === '/' ? [routePattern] : [normalizedPath, routePattern];
ctx.logger.debug('Mounting static files', {
to: routes,
from: mountRoot,
rewrite: mount.rewrite,
spa: mount.spa
});
routes.forEach(route => {
// 1. Serve Static Files
rawApp.get(
route,
serveStatic({
root: mount.root,
rewriteRequestPath: (reqPath) => {
if (mount.rewrite && normalizedPath !== '/') {
// /console/assets/style.css -> /assets/style.css
if (reqPath.startsWith(normalizedPath)) {
return reqPath.substring(normalizedPath.length) || '/';
}
}
return reqPath;
}
})
);
// 2. SPA Fallback (Scoped)
if (mount.spa) {
rawApp.get(route, async (c, next) => {
// Skip if API path check
const config = this.options.restConfig || {};
const basePath = config.api?.basePath || '/api';
if (c.req.path.startsWith(basePath)) {
return next();
}
return serveStatic({
root: mount.root,
rewriteRequestPath: () => 'index.html'
})(c, next);
});
}
});
}
}
// Start server on kernel:ready hook
ctx.hook('kernel:ready', async () => {
// Register standard endpoints before starting to listen
if (this.options.registerStandardEndpoints) {
this.registerDiscoveryAndCrudEndpoints(ctx);
}
const port = this.options.port ?? 3000;
ctx.logger.debug('Starting HTTP server', { port });
await this.server.listen(port);
const actualPort = this.server.getPort();
if (actualPort !== port) {
ctx.logger.warn(`Port ${port} is in use, using port ${actualPort} instead`);
}
ctx.logger.info('HTTP server started successfully', {
port: actualPort,
url: `http://localhost:${actualPort}`
});
});
}
/**
* Register discovery and basic CRUD endpoints.
* Called when `registerStandardEndpoints` is true, before the server starts listening.
*/
private registerDiscoveryAndCrudEndpoints(ctx: PluginContext) {
const rawApp = this.server.getRawApp();
const prefix = '/api/v1';
// Build the standard discovery response
const discovery = {
version: 'v1',
apiName: 'ObjectStack API',
routes: {
data: `${prefix}/data`,
metadata: `${prefix}/meta`,
auth: `${prefix}/auth`,
packages: `${prefix}/packages`,
analytics: `${prefix}/analytics`,
realtime: `${prefix}/realtime`,
workflow: `${prefix}/workflow`,
automation: `${prefix}/automation`,
ai: `${prefix}/ai`,
notifications: `${prefix}/notifications`,
i18n: `${prefix}/i18n`,
storage: `${prefix}/storage`,
ui: `${prefix}/ui`,
},
};
// Discovery endpoints
rawApp.get('/.well-known/objectstack', (c: any) => c.redirect(`${prefix}/discovery`));
rawApp.get(`${prefix}/discovery`, (c: any) => c.json({ data: discovery }));
ctx.logger.info('Registered discovery endpoints', { prefix });
// Basic CRUD data endpoints — delegate to ObjectQL service directly
const getObjectQL = () => ctx.getService<IDataEngine>('objectql');
// Create
rawApp.post(`${prefix}/data/:object`, async (c: any) => {
const ql = getObjectQL();
if (!ql) return c.json({ error: 'Data service not available' }, 503);
const object = c.req.param('object');
const data = await c.req.json().catch(() => ({}));
const res = await ql.insert(object, data);
const record = { ...data, ...res };
return c.json({ object, id: record.id, record });
});
// Get by ID
rawApp.get(`${prefix}/data/:object/:id`, async (c: any) => {
const ql = getObjectQL();
if (!ql) return c.json({ error: 'Data service not available' }, 503);
const object = c.req.param('object');
const id = c.req.param('id');
let all = await ql.find(object);
if (!all) all = [];
const match = all.find((i: any) => i.id === id);
return match ? c.json({ object, id, record: match }) : c.json({ error: 'Not found' }, 404);
});
// Find / List
rawApp.get(`${prefix}/data/:object`, async (c: any) => {
const ql = getObjectQL();
if (!ql) return c.json({ error: 'Data service not available' }, 503);
const object = c.req.param('object');
let all = await ql.find(object);
if (!Array.isArray(all) && all && (all as any).value) all = (all as any).value;
if (!all) all = [];
return c.json({ object, records: all, total: all.length });
});
ctx.logger.debug('Registered standard CRUD data endpoints', { prefix });
}
/**
* Destroy phase - Stop server
*/
async destroy() {
this.server.close();
// Note: Can't use ctx.logger here since we're in destroy
console.log('[HonoServerPlugin] Server stopped');
}
}