@objectstack/plugin-hono-server 1.0.4 → 1.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,297 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
19
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
20
+
21
+ // src/index.ts
22
+ var index_exports = {};
23
+ __export(index_exports, {
24
+ HonoHttpServer: () => HonoHttpServer,
25
+ HonoServerPlugin: () => HonoServerPlugin
26
+ });
27
+
28
+ // src/adapter.ts
29
+ var adapter_exports = {};
30
+ __export(adapter_exports, {
31
+ HonoHttpServer: () => HonoHttpServer
32
+ });
33
+ __reExport(adapter_exports, core_star);
34
+ import * as core_star from "@objectstack/core";
35
+ import { Hono } from "hono";
36
+ import { serve } from "@hono/node-server";
37
+ import { serveStatic } from "@hono/node-server/serve-static";
38
+ var HonoHttpServer = class {
39
+ constructor(port = 3e3, staticRoot) {
40
+ this.port = port;
41
+ this.staticRoot = staticRoot;
42
+ __publicField(this, "app");
43
+ __publicField(this, "server");
44
+ __publicField(this, "listeningPort");
45
+ this.app = new Hono();
46
+ }
47
+ // internal helper to convert standard handler to Hono handler
48
+ wrap(handler) {
49
+ return async (c) => {
50
+ let body = {};
51
+ if (c.req.header("content-type")?.includes("application/json")) {
52
+ try {
53
+ body = await c.req.json();
54
+ } catch (e) {
55
+ try {
56
+ body = await c.req.parseBody();
57
+ } catch (e2) {
58
+ }
59
+ }
60
+ } else {
61
+ try {
62
+ body = await c.req.parseBody();
63
+ } catch (e) {
64
+ }
65
+ }
66
+ const req = {
67
+ params: c.req.param(),
68
+ query: c.req.query(),
69
+ body,
70
+ headers: c.req.header(),
71
+ method: c.req.method,
72
+ path: c.req.path
73
+ };
74
+ let capturedResponse;
75
+ const res = {
76
+ json: (data) => {
77
+ capturedResponse = c.json(data);
78
+ },
79
+ send: (data) => {
80
+ capturedResponse = c.html(data);
81
+ },
82
+ status: (code) => {
83
+ c.status(code);
84
+ return res;
85
+ },
86
+ header: (name, value) => {
87
+ c.header(name, value);
88
+ return res;
89
+ }
90
+ };
91
+ await handler(req, res);
92
+ return capturedResponse;
93
+ };
94
+ }
95
+ get(path2, handler) {
96
+ this.app.get(path2, this.wrap(handler));
97
+ }
98
+ post(path2, handler) {
99
+ this.app.post(path2, this.wrap(handler));
100
+ }
101
+ put(path2, handler) {
102
+ this.app.put(path2, this.wrap(handler));
103
+ }
104
+ delete(path2, handler) {
105
+ this.app.delete(path2, this.wrap(handler));
106
+ }
107
+ patch(path2, handler) {
108
+ this.app.patch(path2, this.wrap(handler));
109
+ }
110
+ use(pathOrHandler, handler) {
111
+ if (typeof pathOrHandler === "string" && handler) {
112
+ this.app.use(pathOrHandler, async (c, next) => {
113
+ await handler({}, {}, next);
114
+ });
115
+ } else if (typeof pathOrHandler === "function") {
116
+ this.app.use("*", async (c, next) => {
117
+ await pathOrHandler({}, {}, next);
118
+ });
119
+ }
120
+ }
121
+ /**
122
+ * Mount a sub-application or router
123
+ */
124
+ mount(path2, subApp) {
125
+ this.app.route(path2, subApp);
126
+ }
127
+ async listen(port) {
128
+ return new Promise((resolve2) => {
129
+ if (this.staticRoot) {
130
+ this.app.get("/*", serveStatic({ root: this.staticRoot }));
131
+ }
132
+ const targetPort = port || this.port;
133
+ this.server = serve({
134
+ fetch: this.app.fetch,
135
+ port: targetPort
136
+ }, (info) => {
137
+ this.listeningPort = info.port;
138
+ resolve2();
139
+ });
140
+ });
141
+ }
142
+ getPort() {
143
+ return this.listeningPort || this.port;
144
+ }
145
+ // Expose raw app for scenarios where standard interface is not enough
146
+ getRawApp() {
147
+ return this.app;
148
+ }
149
+ async close() {
150
+ if (this.server && typeof this.server.close === "function") {
151
+ this.server.close();
152
+ }
153
+ }
154
+ };
155
+
156
+ // src/hono-plugin.ts
157
+ import { createHonoApp } from "@objectstack/hono";
158
+ import { serveStatic as serveStatic2 } from "@hono/node-server/serve-static";
159
+ import * as fs from "fs";
160
+ import * as path from "path";
161
+ var HonoServerPlugin = class {
162
+ constructor(options = {}) {
163
+ __publicField(this, "name", "com.objectstack.server.hono");
164
+ __publicField(this, "version", "0.9.0");
165
+ __publicField(this, "options");
166
+ __publicField(this, "server");
167
+ /**
168
+ * Init phase - Setup HTTP server and register as service
169
+ */
170
+ __publicField(this, "init", async (ctx) => {
171
+ ctx.logger.debug("Initializing Hono server plugin", {
172
+ port: this.options.port,
173
+ staticRoot: this.options.staticRoot
174
+ });
175
+ ctx.registerService("http.server", this.server);
176
+ ctx.registerService("http-server", this.server);
177
+ ctx.logger.debug("HTTP server service registered", { serviceName: "http.server" });
178
+ });
179
+ /**
180
+ * Start phase - Bind routes and start listening
181
+ */
182
+ __publicField(this, "start", async (ctx) => {
183
+ ctx.logger.debug("Starting Hono server plugin");
184
+ try {
185
+ const kernel = ctx.getKernel();
186
+ const config = this.options.restConfig || {};
187
+ const apiVersion = config.api?.version || "v1";
188
+ const basePath = config.api?.basePath || "/api";
189
+ const apiPath = config.api?.apiPath || `${basePath}/${apiVersion}`;
190
+ const app = createHonoApp({
191
+ kernel,
192
+ prefix: apiPath
193
+ // Use the calculated path
194
+ });
195
+ ctx.logger.debug("Mounting ObjectStack Runtime App", { prefix: apiPath });
196
+ this.server.mount("/", app);
197
+ } catch (e) {
198
+ ctx.logger.error("Failed to create standard Hono app", e);
199
+ }
200
+ const mounts = this.options.staticMounts || [];
201
+ if (this.options.staticRoot) {
202
+ mounts.push({
203
+ root: this.options.staticRoot,
204
+ path: "/",
205
+ rewrite: false,
206
+ spa: this.options.spaFallback
207
+ });
208
+ }
209
+ if (mounts.length > 0) {
210
+ const rawApp = this.server.getRawApp();
211
+ for (const mount of mounts) {
212
+ const mountRoot = path.resolve(process.cwd(), mount.root);
213
+ if (!fs.existsSync(mountRoot)) {
214
+ ctx.logger.warn(`Static mount root not found: ${mountRoot}. Skipping.`);
215
+ continue;
216
+ }
217
+ const mountPath = mount.path || "/";
218
+ const normalizedPath = mountPath.startsWith("/") ? mountPath : `/${mountPath}`;
219
+ const routePattern = normalizedPath === "/" ? "/*" : `${normalizedPath.replace(/\/$/, "")}/*`;
220
+ const routes = normalizedPath === "/" ? [routePattern] : [normalizedPath, routePattern];
221
+ ctx.logger.debug("Mounting static files", {
222
+ to: routes,
223
+ from: mountRoot,
224
+ rewrite: mount.rewrite,
225
+ spa: mount.spa
226
+ });
227
+ routes.forEach((route) => {
228
+ rawApp.get(
229
+ route,
230
+ serveStatic2({
231
+ root: mount.root,
232
+ rewriteRequestPath: (reqPath) => {
233
+ if (mount.rewrite && normalizedPath !== "/") {
234
+ if (reqPath.startsWith(normalizedPath)) {
235
+ return reqPath.substring(normalizedPath.length) || "/";
236
+ }
237
+ }
238
+ return reqPath;
239
+ }
240
+ })
241
+ );
242
+ if (mount.spa) {
243
+ rawApp.get(route, async (c, next) => {
244
+ const config = this.options.restConfig || {};
245
+ const basePath = config.api?.basePath || "/api";
246
+ if (c.req.path.startsWith(basePath)) {
247
+ return next();
248
+ }
249
+ return serveStatic2({
250
+ root: mount.root,
251
+ rewriteRequestPath: () => "index.html"
252
+ })(c, next);
253
+ });
254
+ }
255
+ });
256
+ }
257
+ }
258
+ ctx.hook("kernel:ready", async () => {
259
+ const port = this.options.port || 3e3;
260
+ ctx.logger.debug("Starting HTTP server", { port });
261
+ await this.server.listen(port);
262
+ const actualPort = this.server.getPort();
263
+ ctx.logger.info("HTTP server started successfully", {
264
+ port: actualPort,
265
+ url: `http://localhost:${actualPort}`
266
+ });
267
+ });
268
+ });
269
+ this.options = {
270
+ port: 3e3,
271
+ registerStandardEndpoints: true,
272
+ useApiRegistry: true,
273
+ spaFallback: false,
274
+ ...options
275
+ };
276
+ this.server = new HonoHttpServer(this.options.port);
277
+ }
278
+ /**
279
+ * Destroy phase - Stop server
280
+ */
281
+ async destroy() {
282
+ this.server.close();
283
+ console.log("[HonoServerPlugin] Server stopped");
284
+ }
285
+ };
286
+ // Constants
287
+ __publicField(HonoServerPlugin, "DEFAULT_ENDPOINT_PRIORITY", 100);
288
+ __publicField(HonoServerPlugin, "CORE_ENDPOINT_PRIORITY", 950);
289
+ __publicField(HonoServerPlugin, "DISCOVERY_ENDPOINT_PRIORITY", 900);
290
+
291
+ // src/index.ts
292
+ __reExport(index_exports, adapter_exports);
293
+ export {
294
+ HonoHttpServer,
295
+ HonoServerPlugin
296
+ };
297
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/adapter.ts","../src/hono-plugin.ts"],"sourcesContent":["export * from './hono-plugin';\nexport * from './adapter';\n\n","// Export IHttpServer from core\nexport * from '@objectstack/core';\n\nimport { \n IHttpServer, \n RouteHandler, \n Middleware \n} from '@objectstack/core';\nimport { Hono } from 'hono';\nimport { serve } from '@hono/node-server';\nimport { serveStatic } from '@hono/node-server/serve-static';\n\n/**\n * Hono Implementation of IHttpServer\n */\nexport class HonoHttpServer implements IHttpServer {\n private app: Hono;\n private server: any;\n private listeningPort: number | undefined;\n\n constructor(\n private port: number = 3000,\n private staticRoot?: string\n ) {\n this.app = new Hono();\n }\n\n // internal helper to convert standard handler to Hono handler\n private wrap(handler: RouteHandler) {\n return async (c: any) => {\n let body: any = {};\n \n // Try to parse JSON body first if content-type is JSON\n if (c.req.header('content-type')?.includes('application/json')) {\n try { \n body = await c.req.json(); \n } catch(e) {\n // If JSON parsing fails, try parseBody\n try { \n body = await c.req.parseBody(); \n } catch(e2) {}\n }\n } else {\n // For non-JSON content types, use parseBody\n try { \n body = await c.req.parseBody(); \n } catch(e) {}\n }\n \n const req = {\n params: c.req.param(),\n query: c.req.query(),\n body,\n headers: c.req.header(),\n method: c.req.method,\n path: c.req.path\n };\n\n let capturedResponse: any;\n\n const res = {\n json: (data: any) => { capturedResponse = c.json(data); },\n send: (data: string) => { capturedResponse = c.html(data); },\n status: (code: number) => { c.status(code); return res; },\n header: (name: string, value: string) => { c.header(name, value); return res; }\n };\n\n await handler(req as any, res as any);\n return capturedResponse;\n };\n }\n\n get(path: string, handler: RouteHandler) {\n this.app.get(path, this.wrap(handler));\n }\n post(path: string, handler: RouteHandler) {\n this.app.post(path, this.wrap(handler));\n }\n put(path: string, handler: RouteHandler) {\n this.app.put(path, this.wrap(handler));\n }\n delete(path: string, handler: RouteHandler) {\n this.app.delete(path, this.wrap(handler));\n }\n patch(path: string, handler: RouteHandler) {\n this.app.patch(path, this.wrap(handler));\n }\n \n use(pathOrHandler: string | Middleware, handler?: Middleware) {\n if (typeof pathOrHandler === 'string' && handler) {\n // Path based middleware\n // Hono middleware signature is different (c, next) => ...\n this.app.use(pathOrHandler, async (c, next) => {\n // Simplistic conversion\n await handler({} as any, {} as any, next);\n });\n } else if (typeof pathOrHandler === 'function') {\n // Global middleware\n this.app.use('*', async (c, next) => {\n await pathOrHandler({} as any, {} as any, next);\n });\n }\n }\n\n /**\n * Mount a sub-application or router\n */\n mount(path: string, subApp: Hono) {\n this.app.route(path, subApp);\n }\n\n\n async listen(port: number) {\n return new Promise<void>((resolve) => {\n if (this.staticRoot) {\n this.app.get('/*', serveStatic({ root: this.staticRoot }));\n }\n \n const targetPort = port || this.port;\n this.server = serve({\n fetch: this.app.fetch,\n port: targetPort\n }, (info) => {\n this.listeningPort = info.port;\n resolve();\n });\n });\n }\n\n getPort() {\n return this.listeningPort || this.port;\n }\n\n // Expose raw app for scenarios where standard interface is not enough\n getRawApp() {\n return this.app;\n }\n\n async close() {\n if (this.server && typeof this.server.close === 'function') {\n this.server.close();\n }\n }\n\n\n}\n","import { Plugin, PluginContext, IHttpServer, ApiRegistry } from '@objectstack/core';\nimport { ObjectStackProtocol } from '@objectstack/spec/api';\nimport { \n ApiRegistryEntryInput,\n ApiEndpointRegistrationInput,\n RestServerConfig,\n} from '@objectstack/spec/api';\nimport { HonoHttpServer } from './adapter';\nimport { createHonoApp } from '@objectstack/hono';\nimport { serveStatic } from '@hono/node-server/serve-static';\nimport * as fs from 'fs';\nimport * as path from 'path';\n\nexport interface StaticMount {\n root: string;\n path?: string;\n rewrite?: boolean;\n spa?: boolean;\n}\n\nexport interface HonoPluginOptions {\n port?: number;\n staticRoot?: string;\n /**\n * Multiple static resource mounts\n */\n staticMounts?: StaticMount[];\n /**\n * REST server configuration\n * Controls automatic endpoint generation and API behavior\n */\n restConfig?: RestServerConfig;\n /**\n * Whether to register standard ObjectStack CRUD endpoints\n * @default true\n */\n registerStandardEndpoints?: boolean;\n /**\n * Whether to load endpoints from API Registry\n * @default true\n */\n useApiRegistry?: boolean;\n\n /**\n * Whether to enable SPA fallback\n * If true, returns index.html for non-API 404s\n * @default false\n */\n spaFallback?: boolean;\n}\n\n/**\n * Hono Server Plugin\n * \n * Provides HTTP server capabilities using Hono framework.\n * Registers routes for ObjectStack Runtime Protocol.\n */\nexport class HonoServerPlugin implements Plugin {\n name = 'com.objectstack.server.hono';\n version = '0.9.0';\n \n // Constants\n private static readonly DEFAULT_ENDPOINT_PRIORITY = 100;\n private static readonly CORE_ENDPOINT_PRIORITY = 950;\n private static readonly DISCOVERY_ENDPOINT_PRIORITY = 900;\n \n private options: HonoPluginOptions;\n private server: HonoHttpServer;\n\n constructor(options: HonoPluginOptions = {}) {\n this.options = { \n port: 3000,\n registerStandardEndpoints: true,\n useApiRegistry: true,\n spaFallback: false,\n ...options\n };\n // We handle static root manually in start() to support SPA fallback\n this.server = new HonoHttpServer(this.options.port);\n }\n\n /**\n * Init phase - Setup HTTP server and register as service\n */\n init = async (ctx: PluginContext) => {\n ctx.logger.debug('Initializing Hono server plugin', { \n port: this.options.port,\n staticRoot: this.options.staticRoot \n });\n \n // Register HTTP server service as IHttpServer\n // Register as 'http.server' to match core requirements\n ctx.registerService('http.server', this.server);\n // Alias 'http-server' for backward compatibility\n ctx.registerService('http-server', this.server);\n ctx.logger.debug('HTTP server service registered', { serviceName: 'http.server' });\n }\n\n /**\n * Start phase - Bind routes and start listening\n */\n start = async (ctx: PluginContext) => {\n ctx.logger.debug('Starting Hono server plugin');\n \n // Use Standard ObjectStack Runtime Hono App\n try {\n const kernel = ctx.getKernel();\n const config = this.options.restConfig || {};\n // Calculate prefix similar to before\n const apiVersion = config.api?.version || 'v1';\n const basePath = config.api?.basePath || '/api';\n const apiPath = config.api?.apiPath || `${basePath}/${apiVersion}`;\n \n const app = createHonoApp({ \n kernel,\n prefix: apiPath // Use the calculated path\n });\n \n ctx.logger.debug('Mounting ObjectStack Runtime App', { prefix: apiPath });\n // Use the mount method we added to HonoHttpServer\n this.server.mount('/', app as any);\n\n } catch (e: any) {\n ctx.logger.error('Failed to create standard Hono app', e);\n }\n\n // Configure Static Files & SPA Fallback\n const mounts: StaticMount[] = this.options.staticMounts || [];\n\n // Backward compatibility for staticRoot\n if (this.options.staticRoot) {\n mounts.push({\n root: this.options.staticRoot,\n path: '/',\n rewrite: false,\n spa: this.options.spaFallback\n });\n }\n\n if (mounts.length > 0) {\n const rawApp = this.server.getRawApp();\n \n for (const mount of mounts) {\n const mountRoot = path.resolve(process.cwd(), mount.root);\n\n if (!fs.existsSync(mountRoot)) {\n ctx.logger.warn(`Static mount root not found: ${mountRoot}. Skipping.`);\n continue;\n }\n\n const mountPath = mount.path || '/';\n const normalizedPath = mountPath.startsWith('/') ? mountPath : `/${mountPath}`;\n const routePattern = normalizedPath === '/' ? '/*' : `${normalizedPath.replace(/\\/$/, '')}/*`;\n \n // Routes to register: both /mount and /mount/*\n const routes = normalizedPath === '/' ? [routePattern] : [normalizedPath, routePattern];\n\n ctx.logger.debug('Mounting static files', { \n to: routes, \n from: mountRoot, \n rewrite: mount.rewrite, \n spa: mount.spa \n });\n\n routes.forEach(route => {\n // 1. Serve Static Files\n rawApp.get(\n route, \n serveStatic({ \n root: mount.root,\n rewriteRequestPath: (reqPath) => {\n if (mount.rewrite && normalizedPath !== '/') {\n // /console/assets/style.css -> /assets/style.css\n if (reqPath.startsWith(normalizedPath)) {\n return reqPath.substring(normalizedPath.length) || '/';\n }\n }\n return reqPath;\n }\n })\n );\n\n // 2. SPA Fallback (Scoped)\n if (mount.spa) {\n rawApp.get(route, async (c, next) => {\n // Skip if API path check\n const config = this.options.restConfig || {};\n const basePath = config.api?.basePath || '/api';\n \n if (c.req.path.startsWith(basePath)) {\n return next();\n }\n\n return serveStatic({ \n root: mount.root,\n rewriteRequestPath: () => 'index.html'\n })(c, next);\n });\n }\n });\n }\n }\n\n // Start server on kernel:ready hook\n ctx.hook('kernel:ready', async () => {\n const port = this.options.port || 3000;\n ctx.logger.debug('Starting HTTP server', { port });\n \n await this.server.listen(port);\n \n const actualPort = this.server.getPort();\n ctx.logger.info('HTTP server started successfully', { \n port: actualPort, \n url: `http://localhost:${actualPort}` \n });\n });\n }\n\n /**\n * Destroy phase - Stop server\n */\n async destroy() {\n this.server.close();\n // Note: Can't use ctx.logger here since we're in destroy\n console.log('[HonoServerPlugin] Server stopped');\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;AACA;AAAA,2BAAc;AAOd,SAAS,YAAY;AACrB,SAA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ACnD;AACJ;AAAA;AApKI,cALS,kBAKe,6BAA4B;AACpD,cANS,kBAMe,0BAAyB;AACjD,cAPS,kBAOe,+BAA8B;;;AF/D1D,0BAAc;","names":["path","resolve","serveStatic","serveStatic"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@objectstack/plugin-hono-server",
3
- "version": "1.0.4",
3
+ "version": "1.0.6",
4
4
  "license": "Apache-2.0",
5
5
  "description": "Standard Hono Server Adapter for ObjectStack Runtime",
6
6
  "main": "dist/index.js",
@@ -8,11 +8,11 @@
8
8
  "dependencies": {
9
9
  "@hono/node-server": "^1.2.0",
10
10
  "hono": "^4.0.0",
11
- "@objectstack/core": "1.0.4",
12
- "@objectstack/hono": "1.0.4",
13
- "@objectstack/runtime": "1.0.4",
14
- "@objectstack/spec": "1.0.4",
15
- "@objectstack/types": "1.0.4"
11
+ "@objectstack/core": "1.0.6",
12
+ "@objectstack/runtime": "1.0.6",
13
+ "@objectstack/hono": "1.0.6",
14
+ "@objectstack/spec": "1.0.6",
15
+ "@objectstack/types": "1.0.6"
16
16
  },
17
17
  "devDependencies": {
18
18
  "@types/node": "^25.1.0",
@@ -20,7 +20,7 @@
20
20
  "vitest": "^4.0.18"
21
21
  },
22
22
  "scripts": {
23
- "build": "tsc",
23
+ "build": "tsup --config ../../../tsup.config.ts",
24
24
  "test": "vitest run"
25
25
  }
26
26
  }
@@ -4,18 +4,36 @@ import { PluginContext } from '@objectstack/core';
4
4
  import { createHonoApp } from '@objectstack/hono';
5
5
  import { HonoHttpServer } from './adapter';
6
6
 
7
+ vi.mock('fs', async (importOriginal) => {
8
+ const actual = await importOriginal<typeof import('fs')>();
9
+ return {
10
+ ...actual,
11
+ existsSync: vi.fn().mockReturnValue(true)
12
+ };
13
+ });
14
+
7
15
  // Mock dependencies
8
16
  vi.mock('@objectstack/hono', () => ({
9
17
  createHonoApp: vi.fn(),
10
18
  }));
11
19
 
20
+ vi.mock('@hono/node-server/serve-static', () => ({
21
+ serveStatic: vi.fn(() => (c: any, next: any) => next())
22
+ }));
23
+
12
24
  vi.mock('./adapter', () => ({
13
25
  HonoHttpServer: vi.fn(function() {
14
26
  return {
15
27
  mount: vi.fn(),
16
28
  start: vi.fn(),
17
29
  stop: vi.fn(),
18
- getApp: vi.fn()
30
+ getApp: vi.fn(),
31
+ listen: vi.fn(),
32
+ getPort: vi.fn().mockReturnValue(3000),
33
+ close: vi.fn(),
34
+ getRawApp: vi.fn().mockReturnValue({
35
+ get: vi.fn(),
36
+ })
19
37
  };
20
38
  })
21
39
  }));
@@ -104,4 +122,23 @@ describe('HonoServerPlugin', () => {
104
122
 
105
123
  expect(logger.error).toHaveBeenCalledWith('Failed to create standard Hono app', expect.any(Error));
106
124
  });
125
+
126
+ it('should configure static files and SPA fallback when enabled', async () => {
127
+ const plugin = new HonoServerPlugin({
128
+ staticRoot: './public',
129
+ spaFallback: true
130
+ });
131
+
132
+ await plugin.init(context as PluginContext);
133
+ await plugin.start(context as PluginContext);
134
+
135
+ const serverInstance = (HonoHttpServer as any).mock.instances[0];
136
+ const rawApp = serverInstance.getRawApp();
137
+
138
+ expect(serverInstance.getRawApp).toHaveBeenCalled();
139
+ // Should register static files middleware
140
+ expect(rawApp.get).toHaveBeenCalledWith('/*', expect.anything());
141
+ // Should register SPA fallback middleware
142
+ expect(rawApp.get).toHaveBeenCalledWith('/*', expect.anything());
143
+ });
107
144
  });
@@ -7,10 +7,24 @@ import {
7
7
  } from '@objectstack/spec/api';
8
8
  import { HonoHttpServer } from './adapter';
9
9
  import { createHonoApp } from '@objectstack/hono';
10
+ import { serveStatic } from '@hono/node-server/serve-static';
11
+ import * as fs from 'fs';
12
+ import * as path from 'path';
13
+
14
+ export interface StaticMount {
15
+ root: string;
16
+ path?: string;
17
+ rewrite?: boolean;
18
+ spa?: boolean;
19
+ }
10
20
 
11
21
  export interface HonoPluginOptions {
12
22
  port?: number;
13
23
  staticRoot?: string;
24
+ /**
25
+ * Multiple static resource mounts
26
+ */
27
+ staticMounts?: StaticMount[];
14
28
  /**
15
29
  * REST server configuration
16
30
  * Controls automatic endpoint generation and API behavior
@@ -26,6 +40,13 @@ export interface HonoPluginOptions {
26
40
  * @default true
27
41
  */
28
42
  useApiRegistry?: boolean;
43
+
44
+ /**
45
+ * Whether to enable SPA fallback
46
+ * If true, returns index.html for non-API 404s
47
+ * @default false
48
+ */
49
+ spaFallback?: boolean;
29
50
  }
30
51
 
31
52
  /**
@@ -51,9 +72,11 @@ export class HonoServerPlugin implements Plugin {
51
72
  port: 3000,
52
73
  registerStandardEndpoints: true,
53
74
  useApiRegistry: true,
75
+ spaFallback: false,
54
76
  ...options
55
77
  };
56
- this.server = new HonoHttpServer(this.options.port, this.options.staticRoot);
78
+ // We handle static root manually in start() to support SPA fallback
79
+ this.server = new HonoHttpServer(this.options.port);
57
80
  }
58
81
 
59
82
  /**
@@ -101,6 +124,83 @@ export class HonoServerPlugin implements Plugin {
101
124
  ctx.logger.error('Failed to create standard Hono app', e);
102
125
  }
103
126
 
127
+ // Configure Static Files & SPA Fallback
128
+ const mounts: StaticMount[] = this.options.staticMounts || [];
129
+
130
+ // Backward compatibility for staticRoot
131
+ if (this.options.staticRoot) {
132
+ mounts.push({
133
+ root: this.options.staticRoot,
134
+ path: '/',
135
+ rewrite: false,
136
+ spa: this.options.spaFallback
137
+ });
138
+ }
139
+
140
+ if (mounts.length > 0) {
141
+ const rawApp = this.server.getRawApp();
142
+
143
+ for (const mount of mounts) {
144
+ const mountRoot = path.resolve(process.cwd(), mount.root);
145
+
146
+ if (!fs.existsSync(mountRoot)) {
147
+ ctx.logger.warn(`Static mount root not found: ${mountRoot}. Skipping.`);
148
+ continue;
149
+ }
150
+
151
+ const mountPath = mount.path || '/';
152
+ const normalizedPath = mountPath.startsWith('/') ? mountPath : `/${mountPath}`;
153
+ const routePattern = normalizedPath === '/' ? '/*' : `${normalizedPath.replace(/\/$/, '')}/*`;
154
+
155
+ // Routes to register: both /mount and /mount/*
156
+ const routes = normalizedPath === '/' ? [routePattern] : [normalizedPath, routePattern];
157
+
158
+ ctx.logger.debug('Mounting static files', {
159
+ to: routes,
160
+ from: mountRoot,
161
+ rewrite: mount.rewrite,
162
+ spa: mount.spa
163
+ });
164
+
165
+ routes.forEach(route => {
166
+ // 1. Serve Static Files
167
+ rawApp.get(
168
+ route,
169
+ serveStatic({
170
+ root: mount.root,
171
+ rewriteRequestPath: (reqPath) => {
172
+ if (mount.rewrite && normalizedPath !== '/') {
173
+ // /console/assets/style.css -> /assets/style.css
174
+ if (reqPath.startsWith(normalizedPath)) {
175
+ return reqPath.substring(normalizedPath.length) || '/';
176
+ }
177
+ }
178
+ return reqPath;
179
+ }
180
+ })
181
+ );
182
+
183
+ // 2. SPA Fallback (Scoped)
184
+ if (mount.spa) {
185
+ rawApp.get(route, async (c, next) => {
186
+ // Skip if API path check
187
+ const config = this.options.restConfig || {};
188
+ const basePath = config.api?.basePath || '/api';
189
+
190
+ if (c.req.path.startsWith(basePath)) {
191
+ return next();
192
+ }
193
+
194
+ return serveStatic({
195
+ root: mount.root,
196
+ rewriteRequestPath: () => 'index.html'
197
+ })(c, next);
198
+ });
199
+ }
200
+ });
201
+ }
202
+ }
203
+
104
204
  // Start server on kernel:ready hook
105
205
  ctx.hook('kernel:ready', async () => {
106
206
  const port = this.options.port || 3000;
package/dist/adapter.d.ts DELETED
@@ -1,29 +0,0 @@
1
- export * from '@objectstack/core';
2
- import { IHttpServer, RouteHandler, Middleware } from '@objectstack/core';
3
- import { Hono } from 'hono';
4
- /**
5
- * Hono Implementation of IHttpServer
6
- */
7
- export declare class HonoHttpServer implements IHttpServer {
8
- private port;
9
- private staticRoot?;
10
- private app;
11
- private server;
12
- private listeningPort;
13
- constructor(port?: number, staticRoot?: string | undefined);
14
- private wrap;
15
- get(path: string, handler: RouteHandler): void;
16
- post(path: string, handler: RouteHandler): void;
17
- put(path: string, handler: RouteHandler): void;
18
- delete(path: string, handler: RouteHandler): void;
19
- patch(path: string, handler: RouteHandler): void;
20
- use(pathOrHandler: string | Middleware, handler?: Middleware): void;
21
- /**
22
- * Mount a sub-application or router
23
- */
24
- mount(path: string, subApp: Hono): void;
25
- listen(port: number): Promise<void>;
26
- getPort(): number;
27
- getRawApp(): Hono<import("hono/types").BlankEnv, import("hono/types").BlankSchema, "/">;
28
- close(): Promise<void>;
29
- }