routefly 1.0.1 → 1.0.3

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.d.ts CHANGED
@@ -1,64 +1,85 @@
1
+ import { Hono } from 'hono';
2
+
1
3
  interface AppRequest {
2
- body: any;
4
+ body: unknown;
3
5
  params: Record<string, string>;
4
6
  query: Record<string, string>;
5
7
  headers: Record<string, string>;
6
8
  cookies: Record<string, string>;
7
9
  }
8
10
  interface AppResponse {
9
- status(code: number): this;
10
- setHeader(key: string, value: string): this;
11
- json(data: any, status?: number): Response;
11
+ status(code: number): AppResponse;
12
+ setHeader(key: string, value: string): AppResponse;
13
+ send(data: unknown, status?: number): Response;
14
+ json(data: unknown, status?: number): Response;
12
15
  html(html: string, status?: number): Response;
13
16
  redirect(url: string, status?: number): Response;
14
17
  }
18
+ type RouteMiddleware = (req: AppRequest, res: AppResponse, next: () => Promise<void> | void) => Promise<void> | void;
19
+ type RouteHandler = (req: AppRequest, res: AppResponse) => Response | Promise<Response> | unknown;
15
20
  interface ServerPort {
16
- addRoute(method: string, path: string, handler: Function, middlewares?: Function[]): void;
21
+ addRoute(method: string, path: string, handler: Function, middlewares?: RouteMiddleware[]): void;
17
22
  use(middleware: Function): void;
18
23
  start(port: number): Promise<void>;
19
- getApp(): any;
24
+ getApp(): unknown;
20
25
  }
21
26
  interface RouteDefinition {
22
27
  method: string;
23
28
  path: string;
24
29
  handler: Function;
25
- middlewares: Function[];
30
+ middlewares: RouteMiddleware[];
31
+ handlerName?: string;
32
+ }
33
+ interface ConfigServer {
34
+ server?: ServerPort | "default";
26
35
  }
27
- type ConfigServer = {
28
- server: ServerPort | "default";
29
- root: string;
30
- filePattern: string;
31
- exclude: string[];
32
- };
36
+
37
+ declare const Get: (path: string, ...middlewares: RouteMiddleware[]) => (target: any, propertyKeyOrContext?: any, descriptor?: PropertyDescriptor) => any;
38
+ declare const Post: (path: string, ...middlewares: RouteMiddleware[]) => (target: any, propertyKeyOrContext?: any, descriptor?: PropertyDescriptor) => any;
39
+ declare const Put: (path: string, ...middlewares: RouteMiddleware[]) => (target: any, propertyKeyOrContext?: any, descriptor?: PropertyDescriptor) => any;
40
+ declare const Patch: (path: string, ...middlewares: RouteMiddleware[]) => (target: any, propertyKeyOrContext?: any, descriptor?: PropertyDescriptor) => any;
41
+ declare const Delete: (path: string, ...middlewares: RouteMiddleware[]) => (target: any, propertyKeyOrContext?: any, descriptor?: PropertyDescriptor) => any;
33
42
 
34
43
  declare class RouteRegistry {
35
44
  private static routes;
45
+ private static collisions;
36
46
  static add(route: RouteDefinition): void;
37
- static getAll(): RouteDefinition[];
47
+ static validate(): void;
48
+ static getAll(): (RouteDefinition & {
49
+ file: string;
50
+ })[];
38
51
  static clear(): void;
39
52
  }
40
53
 
41
- declare const Get: (path: string, ...middlewares: Function[]) => (target: any, propertyKeyOrContext: any, descriptor?: PropertyDescriptor) => any;
42
- declare const Post: (path: string, ...middlewares: Function[]) => (target: any, propertyKeyOrContext: any, descriptor?: PropertyDescriptor) => any;
43
- declare const Put: (path: string, ...middlewares: Function[]) => (target: any, propertyKeyOrContext: any, descriptor?: PropertyDescriptor) => any;
44
- declare const Patch: (path: string, ...middlewares: Function[]) => (target: any, propertyKeyOrContext: any, descriptor?: PropertyDescriptor) => any;
45
- declare const Delete: (path: string, ...middlewares: Function[]) => (target: any, propertyKeyOrContext: any, descriptor?: PropertyDescriptor) => any;
54
+ declare class RouteflyApp {
55
+ private adapter;
56
+ private mounted;
57
+ constructor(adapter?: ServerPort);
58
+ use(middleware: Function): this;
59
+ addRoute(method: string, path: string, handler: Function, middlewares?: RouteMiddleware[]): this;
60
+ mountRoutes(): void;
61
+ start(port: number): Promise<void>;
62
+ getAdapter(): ServerPort;
63
+ }
64
+ declare const app: RouteflyApp;
65
+ declare function bootstrap(config?: ConfigServer, createConfigFile?: boolean): Promise<RouteflyApp>;
46
66
 
47
67
  declare class HonoServerAdapter implements ServerPort {
48
68
  private app;
49
69
  private globalMiddlewares;
50
70
  constructor();
51
71
  use(middleware: Function): void;
52
- addRoute(method: string, path: string, handler: Function, middlewares?: Function[]): void;
72
+ addRoute(method: string, path: string, handler: Function, middlewares?: RouteMiddleware[]): void;
53
73
  private buildRequest;
54
74
  private parseCookies;
55
75
  private createResponse;
56
76
  start(port: number): Promise<void>;
57
- getApp(): any;
77
+ getApp(): Hono;
58
78
  }
59
79
 
60
- declare function bootstrap(config?: ConfigServer): Promise<ServerPort>;
80
+ declare const config: Required<ConfigServer>;
81
+ declare function resolveServerAdapter(server?: ServerPort | "default"): ServerPort;
61
82
 
62
- declare function loadConfig(): Promise<ConfigServer>;
83
+ declare function loadOptionalConfig(createIfMissing?: boolean): Promise<ConfigServer>;
63
84
 
64
- export { type AppRequest, type AppResponse, type ConfigServer, Delete, Get, HonoServerAdapter, Patch, Post, Put, type RouteDefinition, RouteRegistry, type ServerPort, bootstrap, loadConfig };
85
+ export { type AppRequest, type AppResponse, type ConfigServer, Delete, Get, HonoServerAdapter, Patch, Post, Put, type RouteDefinition, type RouteHandler, type RouteMiddleware, RouteRegistry, RouteflyApp, type ServerPort, app, bootstrap, config, app as default, loadOptionalConfig, resolveServerAdapter };
package/dist/index.js CHANGED
@@ -1,143 +1,520 @@
1
- import {
2
- HonoServerAdapter
3
- } from "./chunk-GAM7LLVT.js";
1
+ // src/utils/log/alreadyRegistered.ts
2
+ var c = {
3
+ reset: "\x1B[0m",
4
+ bold: "\x1B[1m",
5
+ dim: "\x1B[2m",
6
+ red: "\x1B[31m",
7
+ yellow: "\x1B[33m",
8
+ gray: "\x1B[90m",
9
+ white: "\x1B[37m"
10
+ };
11
+ function reportCollisions(collisions) {
12
+ const divider = `${c.gray} ${"\u2500".repeat(60)}${c.reset}`;
13
+ process.stderr.write("\n");
14
+ process.stderr.write(
15
+ ` ${c.bold}${c.red}Route Collision${c.reset} ${c.dim}Server did not start${c.reset}
16
+ `
17
+ );
18
+ process.stderr.write(divider + "\n");
19
+ for (const { existing, duplicates } of collisions) {
20
+ const all = [
21
+ { ...existing, duplicate: false },
22
+ ...duplicates.map((d) => ({ ...d, duplicate: true }))
23
+ ];
24
+ process.stderr.write("\n");
25
+ for (const r of all) {
26
+ const methodColor = r.duplicate ? c.red : c.yellow;
27
+ const tag = r.duplicate ? ` ${c.red}\u2715 duplicate${c.reset}` : ` ${c.yellow}\u2713 first registered${c.reset}`;
28
+ const method = `${methodColor}${c.bold}${r.method.toUpperCase().padEnd(6)}${c.reset}`;
29
+ const path = `${c.white}${r.path}${c.reset}`;
30
+ const file = `${c.gray}${r.file}${c.reset}`;
31
+ const fn = r.handlerName ? ` ${c.dim}${r.handlerName}${c.reset}` : "";
32
+ process.stderr.write(` ${method} ${path} ${file}${fn}${tag}
33
+ `);
34
+ }
35
+ }
36
+ process.stderr.write("\n");
37
+ process.stderr.write(divider + "\n");
38
+ process.stderr.write(
39
+ ` ${c.dim}Remove the duplicate routes and restart.${c.reset}
40
+
41
+ `
42
+ );
43
+ process.exit(1);
44
+ }
4
45
 
5
46
  // src/core/registry.ts
47
+ function getCallerFile() {
48
+ const err = new Error();
49
+ const stack = err.stack?.split("\n") || [];
50
+ for (const line of stack) {
51
+ const match = line.match(/(?:at\s+)?(?:.*\s+\()?(.*?\.(?:ts|js)):\d+:\d+\)?/);
52
+ if (match && !match[1].includes("registry.ts") && !match[1].includes("decorators.ts") && !match[1].includes("bootstrap.ts")) {
53
+ return match[1].split(/[\\/]/).pop() || "unknown.ts";
54
+ }
55
+ }
56
+ return "unknown.ts";
57
+ }
6
58
  var RouteRegistry = class {
7
- static routes = [];
59
+ static routes = /* @__PURE__ */ new Map();
60
+ static collisions = /* @__PURE__ */ new Map();
8
61
  static add(route) {
9
- this.routes.push(route);
62
+ const key = `${route.method.toUpperCase()} ${route.path}`;
63
+ const file = getCallerFile();
64
+ if (this.routes.has(key)) {
65
+ const existing = this.routes.get(key);
66
+ if (!this.collisions.has(key)) {
67
+ this.collisions.set(key, {
68
+ existing: {
69
+ method: existing.method,
70
+ path: existing.path,
71
+ file: existing.file,
72
+ handlerName: existing.handlerName
73
+ },
74
+ duplicates: []
75
+ });
76
+ }
77
+ this.collisions.get(key).duplicates.push({
78
+ method: route.method,
79
+ path: route.path,
80
+ file,
81
+ handlerName: route.handlerName
82
+ });
83
+ return;
84
+ }
85
+ this.routes.set(key, { ...route, file, handlerName: route.handlerName });
86
+ }
87
+ static validate() {
88
+ if (this.collisions.size > 0) {
89
+ reportCollisions(Array.from(this.collisions.values()));
90
+ }
10
91
  }
11
92
  static getAll() {
12
- return this.routes;
93
+ return Array.from(this.routes.values());
13
94
  }
14
95
  static clear() {
15
- this.routes = [];
96
+ this.routes.clear();
97
+ this.collisions.clear();
16
98
  }
17
99
  };
18
100
 
19
- // src/core/decorators.ts
20
- function createRouteDecorator(method) {
21
- return function(path, ...middlewares) {
22
- return function(target, propertyKeyOrContext, descriptor) {
23
- const isTC39 = descriptor === void 0 && propertyKeyOrContext && typeof propertyKeyOrContext === "object" && "kind" in propertyKeyOrContext;
24
- if (isTC39) {
25
- const context = propertyKeyOrContext;
26
- const methodName = context.name;
27
- const originalMethod = target[methodName];
28
- const handler = async function(req, res) {
29
- const instance = new target.constructor();
30
- return originalMethod.call(instance, req, res);
31
- };
32
- RouteRegistry.add({
33
- method: method.toUpperCase(),
34
- path,
35
- handler,
36
- middlewares
101
+ // src/utils/log/printRoutesTable.ts
102
+ var c2 = {
103
+ reset: "\x1B[0m",
104
+ bold: "\x1B[1m",
105
+ dim: "\x1B[2m",
106
+ white: "\x1B[37m",
107
+ gray: "\x1B[90m",
108
+ cyan: "\x1B[36m",
109
+ green: "\x1B[32m",
110
+ yellow: "\x1B[33m",
111
+ blue: "\x1B[34m",
112
+ magenta: "\x1B[35m",
113
+ red: "\x1B[31m"
114
+ };
115
+ var METHOD_COLOR = {
116
+ GET: c2.green,
117
+ POST: c2.yellow,
118
+ PUT: c2.blue,
119
+ PATCH: c2.cyan,
120
+ DELETE: c2.red,
121
+ HEAD: c2.magenta,
122
+ OPTIONS: c2.gray
123
+ };
124
+ function methodBadge(method) {
125
+ const color = METHOD_COLOR[method.toUpperCase()] ?? c2.white;
126
+ return `${color}${c2.bold}${method.toUpperCase()}${c2.reset}`;
127
+ }
128
+ function visibleLen(str) {
129
+ return str.replace(/\x1b\[[0-9;]*m/g, "").length;
130
+ }
131
+ function padVisible(str, len) {
132
+ const diff = len - visibleLen(str);
133
+ return str + " ".repeat(Math.max(0, diff));
134
+ }
135
+ function printRoutesTable(routes) {
136
+ if (routes.length === 0) return;
137
+ let wMethod = "Method".length;
138
+ let wPath = "Route".length;
139
+ let wFile = "File".length;
140
+ let wFn = "Handler".length;
141
+ const rows = routes.map((r) => {
142
+ const method = r.method.toUpperCase();
143
+ const path = r.path;
144
+ const file = r.file.replace(/\.(ts|js)$/, "");
145
+ const fn = r.handlerName ?? "\u2014";
146
+ wMethod = Math.max(wMethod, method.length);
147
+ wPath = Math.max(wPath, path.length);
148
+ wFile = Math.max(wFile, file.length);
149
+ wFn = Math.max(wFn, fn.length);
150
+ return { method, path, file, fn };
151
+ });
152
+ const divider = `${c2.gray} ${"\u2500".repeat(wMethod + wPath + wFile + wFn + 13)}${c2.reset}`;
153
+ const header = ` ${c2.bold}${c2.white}${"Method".padEnd(wMethod)}${c2.reset} ${c2.gray}${"Route".padEnd(wPath)}${c2.reset} ${c2.gray}${"File".padEnd(wFile)}${c2.reset} ${c2.gray}${"Handler".padEnd(wFn)}${c2.reset}`;
154
+ console.log("");
155
+ console.log(`${c2.bold}${c2.cyan} HTTP Routes${c2.reset}`);
156
+ console.log(divider);
157
+ console.log(header);
158
+ console.log(divider);
159
+ for (const r of rows) {
160
+ const badge = methodBadge(r.method);
161
+ const line = ` ${padVisible(badge, wMethod)} ${c2.white}${r.path.padEnd(wPath)}${c2.reset} ${c2.gray}${r.file.padEnd(wFile)}${c2.reset} ${c2.dim}${r.fn.padEnd(wFn)}${c2.reset}`;
162
+ console.log(line);
163
+ }
164
+ console.log(divider);
165
+ console.log("");
166
+ }
167
+
168
+ // src/adapters/HonoServerAdapter.ts
169
+ import { Hono } from "hono";
170
+ import { serve } from "@hono/node-server";
171
+ var HonoServerAdapter = class {
172
+ app;
173
+ globalMiddlewares = [];
174
+ constructor() {
175
+ this.app = new Hono();
176
+ }
177
+ use(middleware) {
178
+ this.globalMiddlewares.push(middleware);
179
+ this.app.use("*", async (c3, next) => {
180
+ if (middleware.length >= 3) {
181
+ const req = await this.buildRequest(c3);
182
+ const res = this.createResponse();
183
+ await middleware(req, res, next);
184
+ return;
185
+ }
186
+ await middleware(c3, next);
187
+ });
188
+ }
189
+ addRoute(method, path, handler, middlewares = []) {
190
+ const honoMiddlewares = middlewares.map((mw) => async (c3, next) => {
191
+ const req = await this.buildRequest(c3);
192
+ const res = this.createResponse();
193
+ await mw(req, res, next);
194
+ });
195
+ this.app.on(
196
+ method.toUpperCase(),
197
+ path,
198
+ ...honoMiddlewares,
199
+ async (c3) => {
200
+ try {
201
+ const req = await this.buildRequest(c3);
202
+ const res = this.createResponse();
203
+ const result = await handler(req, res);
204
+ if (result instanceof Response) {
205
+ return result;
206
+ }
207
+ if (result !== void 0) {
208
+ if (typeof result === "string") {
209
+ return res.send(result);
210
+ }
211
+ return res.json(result);
212
+ }
213
+ return c3.body(null, 204);
214
+ } catch (error) {
215
+ console.error(`[Framework Error] ${method} ${path}:`, error);
216
+ return c3.json(
217
+ {
218
+ error: "Internal Server Error",
219
+ message: process.env.NODE_ENV === "development" ? error?.message : "Something went wrong"
220
+ },
221
+ 500
222
+ );
223
+ }
224
+ }
225
+ );
226
+ }
227
+ async buildRequest(c3) {
228
+ const rawBody = await c3.req.text();
229
+ let body = rawBody;
230
+ const contentType = c3.req.header("content-type") || "";
231
+ if (contentType.includes("application/json") && rawBody) {
232
+ try {
233
+ body = JSON.parse(rawBody);
234
+ } catch {
235
+ body = {};
236
+ }
237
+ }
238
+ return {
239
+ body,
240
+ params: c3.req.param(),
241
+ query: c3.req.query(),
242
+ headers: Object.fromEntries(c3.req.raw.headers.entries()),
243
+ cookies: this.parseCookies(c3.req.header("cookie") || "")
244
+ };
245
+ }
246
+ parseCookies(cookieString) {
247
+ const cookies = {};
248
+ if (!cookieString) return cookies;
249
+ cookieString.split(";").forEach((cookie) => {
250
+ const idx = cookie.indexOf("=");
251
+ if (idx === -1) return;
252
+ const key = cookie.slice(0, idx).trim();
253
+ const value = cookie.slice(idx + 1).trim();
254
+ if (key) {
255
+ try {
256
+ cookies[key] = decodeURIComponent(value);
257
+ } catch {
258
+ cookies[key] = value;
259
+ }
260
+ }
261
+ });
262
+ return cookies;
263
+ }
264
+ createResponse() {
265
+ let statusCode = 200;
266
+ const headers = new Headers({
267
+ "X-Content-Type-Options": "nosniff",
268
+ "X-Frame-Options": "DENY"
269
+ });
270
+ const response = {
271
+ status(code) {
272
+ statusCode = code;
273
+ return response;
274
+ },
275
+ setHeader(key, value) {
276
+ headers.set(key, value);
277
+ return response;
278
+ },
279
+ send(data, status) {
280
+ const responseHeaders = new Headers(headers);
281
+ if (typeof data === "object" && data !== null) {
282
+ responseHeaders.set("Content-Type", "application/json");
283
+ return new Response(JSON.stringify(data), {
284
+ status: status ?? statusCode,
285
+ headers: responseHeaders
286
+ });
287
+ }
288
+ if (!responseHeaders.has("Content-Type")) {
289
+ responseHeaders.set("Content-Type", "text/plain; charset=utf-8");
290
+ }
291
+ return new Response(String(data ?? ""), {
292
+ status: status ?? statusCode,
293
+ headers: responseHeaders
37
294
  });
38
- return originalMethod;
39
- } else {
40
- const propertyKey = propertyKeyOrContext;
41
- const originalMethod = descriptor.value;
42
- const handler = async function(req, res) {
43
- const instance = new target.constructor();
44
- return originalMethod.call(instance, req, res);
45
- };
46
- RouteRegistry.add({
47
- method: method.toUpperCase(),
48
- path,
49
- handler,
50
- middlewares
295
+ },
296
+ json(data, status) {
297
+ const responseHeaders = new Headers(headers);
298
+ responseHeaders.set("Content-Type", "application/json");
299
+ return new Response(JSON.stringify(data), {
300
+ status: status ?? statusCode,
301
+ headers: responseHeaders
302
+ });
303
+ },
304
+ html(html, status) {
305
+ const responseHeaders = new Headers(headers);
306
+ responseHeaders.set("Content-Type", "text/html; charset=utf-8");
307
+ return new Response(html, {
308
+ status: status ?? statusCode,
309
+ headers: responseHeaders
310
+ });
311
+ },
312
+ redirect(url, status = 302) {
313
+ const responseHeaders = new Headers(headers);
314
+ responseHeaders.set("Location", url);
315
+ return new Response(null, {
316
+ status,
317
+ headers: responseHeaders
51
318
  });
52
- return descriptor;
53
319
  }
54
320
  };
55
- };
56
- }
57
- var Get = createRouteDecorator("GET");
58
- var Post = createRouteDecorator("POST");
59
- var Put = createRouteDecorator("PUT");
60
- var Patch = createRouteDecorator("PATCH");
61
- var Delete = createRouteDecorator("DELETE");
321
+ return response;
322
+ }
323
+ async start(port) {
324
+ console.log(`Server listening on http://localhost:${port}`);
325
+ serve({
326
+ fetch: this.app.fetch,
327
+ port
328
+ });
329
+ }
330
+ getApp() {
331
+ return this.app;
332
+ }
333
+ };
62
334
 
63
- // src/bootstrap.ts
64
- import { readdir } from "fs/promises";
65
- import { join as join2, resolve } from "path";
66
- import { pathToFileURL as pathToFileURL2 } from "url";
335
+ // src/config.ts
336
+ var config = {
337
+ server: new HonoServerAdapter()
338
+ };
339
+ function resolveServerAdapter(server) {
340
+ if (!server || server === "default") {
341
+ return new HonoServerAdapter();
342
+ }
343
+ return server;
344
+ }
67
345
 
68
346
  // src/config-loader.ts
69
347
  import { existsSync, writeFileSync } from "fs";
70
348
  import { join } from "path";
71
349
  import { pathToFileURL } from "url";
72
350
  var DEFAULT_CONFIG = {
73
- server: "default",
74
- root: "./src",
75
- filePattern: "*.routes.ts",
76
- exclude: ["node_modules", "dist", "utils", "types", "domain"]
351
+ server: "default"
77
352
  };
78
353
  var CONFIG_TEMPLATE = `import type { ConfigServer } from "routefly";
79
354
 
80
355
  export const config: ConfigServer = {
81
- server: "default",
82
- root: "./src",
83
- filePattern: "*.routes.ts",
84
- exclude: ["node_modules", "dist", "utils", "types", "domain"]
356
+ server: "default"
85
357
  };
86
358
  `;
87
- async function loadConfig() {
359
+ async function loadOptionalConfig(createIfMissing = false) {
88
360
  const cwd = process.cwd();
89
361
  const tsPath = join(cwd, "config.server.ts");
90
362
  const jsPath = join(cwd, "config.server.js");
91
- let config;
92
363
  if (existsSync(tsPath) || existsSync(jsPath)) {
93
364
  const finalPath = existsSync(tsPath) ? tsPath : jsPath;
94
- const module = await import(pathToFileURL(finalPath).href);
95
- if (!module.config) {
365
+ const mod = await import(pathToFileURL(finalPath).href);
366
+ if (!mod.config) {
96
367
  throw new Error('config.server.ts precisa exportar um objeto "config"');
97
368
  }
98
- config = module.config;
99
- } else {
100
- writeFileSync(tsPath, CONFIG_TEMPLATE, { flag: "wx" });
101
- config = { ...DEFAULT_CONFIG };
369
+ return {
370
+ ...DEFAULT_CONFIG,
371
+ ...mod.config,
372
+ server: resolveServerAdapter(mod.config.server)
373
+ };
374
+ }
375
+ if (createIfMissing) {
376
+ writeFileSync(tsPath, CONFIG_TEMPLATE, { encoding: "utf-8", flag: "wx" });
102
377
  }
103
378
  return {
104
379
  ...DEFAULT_CONFIG,
105
- ...config,
106
- server: config.server === "default" ? new HonoServerAdapter() : config.server
380
+ server: resolveServerAdapter("default")
107
381
  };
108
382
  }
109
383
 
110
- // src/bootstrap.ts
111
- async function bootstrap(config) {
112
- const finalConfig = config ?? await loadConfig();
113
- const server = finalConfig.server === "default" ? new (await import("./HonoServerAdapter-M5Q3KGEI.js")).HonoServerAdapter() : finalConfig.server;
114
- const absoluteRoot = resolve(process.cwd(), finalConfig.root);
115
- const suffix = finalConfig.filePattern.replace("*", "");
116
- const files = await scanDirectory(absoluteRoot, suffix, finalConfig.exclude);
117
- files.sort();
118
- for (const file of files) {
119
- await import(pathToFileURL2(file).href);
120
- }
121
- for (const route of RouteRegistry.getAll()) {
122
- server.addRoute(route.method, route.path, route.handler, route.middlewares);
384
+ // src/core/decorators.ts
385
+ var controllerInstances = /* @__PURE__ */ new WeakMap();
386
+ function resolveInstance(target) {
387
+ if (!controllerInstances.has(target)) {
388
+ controllerInstances.set(target, new target());
123
389
  }
124
- return server;
390
+ return controllerInstances.get(target);
125
391
  }
126
- async function scanDirectory(dir, suffix, exclude) {
127
- const files = [];
128
- const entries = await readdir(dir, { withFileTypes: true });
129
- for (const entry of entries) {
130
- const fullPath = join2(dir, entry.name);
131
- if (entry.isDirectory()) {
132
- if (!exclude.includes(entry.name)) {
133
- files.push(...await scanDirectory(fullPath, suffix, exclude));
392
+ function createRouteDecorator(method) {
393
+ return function(path, ...middlewares) {
394
+ return function(target, propertyKeyOrContext, descriptor) {
395
+ const isTC39 = typeof propertyKeyOrContext === "object" && propertyKeyOrContext !== null && "kind" in propertyKeyOrContext;
396
+ if (isTC39) {
397
+ const context = propertyKeyOrContext;
398
+ if (context.kind === "function") {
399
+ RouteRegistry.add({
400
+ method: method.toUpperCase(),
401
+ path,
402
+ handler: target,
403
+ middlewares,
404
+ handlerName: target?.name || void 0
405
+ });
406
+ return target;
407
+ }
408
+ if (context.kind === "method") {
409
+ const methodName = context.name;
410
+ const handler = async function(req, res) {
411
+ const owner = this ?? resolveInstance(target.constructor ?? target);
412
+ return owner[methodName](req, res);
413
+ };
414
+ RouteRegistry.add({
415
+ method: method.toUpperCase(),
416
+ path,
417
+ handler,
418
+ middlewares,
419
+ handlerName: String(methodName)
420
+ });
421
+ return async function(req, res) {
422
+ return handler.call(this, req, res);
423
+ };
424
+ }
425
+ } else {
426
+ if (descriptor) {
427
+ const originalMethod = descriptor.value;
428
+ const handler = async function(req, res) {
429
+ if (typeof target === "function") {
430
+ const instance = resolveInstance(target);
431
+ return originalMethod.call(instance, req, res);
432
+ }
433
+ return originalMethod(req, res);
434
+ };
435
+ RouteRegistry.add({
436
+ method: method.toUpperCase(),
437
+ path,
438
+ handler,
439
+ middlewares,
440
+ handlerName: String(propertyKeyOrContext)
441
+ });
442
+ descriptor.value = async function(req, res) {
443
+ const instance = typeof target === "function" ? resolveInstance(target) : this;
444
+ return originalMethod.call(instance, req, res);
445
+ };
446
+ return descriptor;
447
+ }
448
+ RouteRegistry.add({
449
+ method: method.toUpperCase(),
450
+ path,
451
+ handler: target,
452
+ middlewares,
453
+ handlerName: target?.name || void 0
454
+ });
455
+ return target;
134
456
  }
135
- } else if (entry.isFile() && entry.name.endsWith(suffix)) {
136
- files.push(fullPath);
457
+ };
458
+ };
459
+ }
460
+ var Get = createRouteDecorator("GET");
461
+ var Post = createRouteDecorator("POST");
462
+ var Put = createRouteDecorator("PUT");
463
+ var Patch = createRouteDecorator("PATCH");
464
+ var Delete = createRouteDecorator("DELETE");
465
+
466
+ // src/bootstrap.ts
467
+ var RouteflyApp = class {
468
+ adapter;
469
+ mounted = false;
470
+ constructor(adapter) {
471
+ this.adapter = adapter ?? new HonoServerAdapter();
472
+ }
473
+ use(middleware) {
474
+ this.adapter.use(middleware);
475
+ return this;
476
+ }
477
+ addRoute(method, path, handler, middlewares = []) {
478
+ this.adapter.addRoute(method, path, handler, middlewares);
479
+ return this;
480
+ }
481
+ mountRoutes() {
482
+ if (this.mounted) return;
483
+ RouteRegistry.validate();
484
+ const routes = RouteRegistry.getAll();
485
+ for (const route of routes) {
486
+ this.adapter.addRoute(route.method, route.path, route.handler, route.middlewares);
137
487
  }
488
+ printRoutesTable(
489
+ routes.map((r) => ({
490
+ method: r.method,
491
+ path: r.path,
492
+ file: r.file,
493
+ handlerName: r.handlerName
494
+ }))
495
+ );
496
+ this.mounted = true;
497
+ }
498
+ async start(port) {
499
+ this.mountRoutes();
500
+ await this.adapter.start(port);
501
+ }
502
+ getAdapter() {
503
+ return this.adapter;
138
504
  }
139
- return files;
505
+ };
506
+ var app = new RouteflyApp(new HonoServerAdapter());
507
+ async function bootstrap(config2, createConfigFile = false) {
508
+ const resolvedConfig = config2 ?? await loadOptionalConfig(createConfigFile);
509
+ const targetApp = config2 ? new RouteflyApp(resolveServerAdapter(resolvedConfig.server)) : app;
510
+ if (config2) {
511
+ targetApp.mountRoutes();
512
+ }
513
+ return targetApp;
140
514
  }
515
+
516
+ // src/index.ts
517
+ var index_default = app;
141
518
  export {
142
519
  Delete,
143
520
  Get,
@@ -146,6 +523,11 @@ export {
146
523
  Post,
147
524
  Put,
148
525
  RouteRegistry,
526
+ RouteflyApp,
527
+ app,
149
528
  bootstrap,
150
- loadConfig
529
+ config,
530
+ index_default as default,
531
+ loadOptionalConfig,
532
+ resolveServerAdapter
151
533
  };
package/package.json CHANGED
@@ -1,10 +1,16 @@
1
1
  {
2
2
  "name": "routefly",
3
- "version": "1.0.1",
3
+ "version": "1.0.3",
4
4
  "description": "Framework web com decorator",
5
5
  "type": "module",
6
- "main": "dist/index.js",
7
- "types": "dist/index.d.ts",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ }
13
+ },
8
14
  "scripts": {
9
15
  "build": "tsup",
10
16
  "dev": "tsup --watch",
@@ -12,8 +18,7 @@
12
18
  },
13
19
  "dependencies": {
14
20
  "@hono/node-server": "^2.1.11",
15
- "hono": "^4.0.0",
16
- "routefly": "^1.0.0"
21
+ "hono": "^4.0.0"
17
22
  },
18
23
  "devDependencies": {
19
24
  "@types/bun": "^1.4.5",
@@ -1,6 +0,0 @@
1
- import {
2
- HonoServerAdapter
3
- } from "./chunk-GAM7LLVT.js";
4
- export {
5
- HonoServerAdapter
6
- };
@@ -1,117 +0,0 @@
1
- // src/adapters/HonoServerAdapter.ts
2
- import { Hono } from "hono";
3
- import { serve } from "@hono/node-server";
4
- var HonoServerAdapter = class {
5
- app;
6
- globalMiddlewares = [];
7
- constructor() {
8
- this.app = new Hono();
9
- }
10
- use(middleware) {
11
- this.globalMiddlewares.push(middleware);
12
- this.app.use("*", async (c, next) => {
13
- await middleware(c, next);
14
- });
15
- }
16
- addRoute(method, path, handler, middlewares = []) {
17
- const honoMiddlewares = middlewares.map((mw) => async (c, next) => {
18
- const req = await this.buildRequest(c);
19
- const res = this.createResponse();
20
- await mw(req, res, next);
21
- });
22
- this.app.on(method.toUpperCase(), path, ...honoMiddlewares, async (c) => {
23
- try {
24
- const req = await this.buildRequest(c);
25
- const res = this.createResponse();
26
- const result = await handler(req, res);
27
- if (result instanceof Response) {
28
- return result;
29
- }
30
- if (result !== void 0) {
31
- return c.json(result);
32
- }
33
- return c.body(null, 204);
34
- } catch (error) {
35
- console.error(`[Framework Error] ${method} ${path}:`, error);
36
- return c.json(
37
- {
38
- error: "Internal Server Error",
39
- message: process.env.NODE_ENV === "development" ? error.message : "Something went wrong"
40
- },
41
- 500
42
- );
43
- }
44
- });
45
- }
46
- async buildRequest(c) {
47
- const rawBody = await c.req.text();
48
- let body = rawBody;
49
- const contentType = c.req.header("content-type") || "";
50
- if (contentType.includes("application/json") && rawBody) {
51
- try {
52
- body = JSON.parse(rawBody);
53
- } catch {
54
- body = {};
55
- }
56
- }
57
- return {
58
- body,
59
- params: c.req.param(),
60
- query: c.req.query(),
61
- headers: Object.fromEntries(c.req.raw.headers.entries()),
62
- cookies: this.parseCookies(c.req.header("cookie") || "")
63
- };
64
- }
65
- parseCookies(cookieString) {
66
- const cookies = {};
67
- cookieString.split(";").forEach((cookie) => {
68
- const [key, value] = cookie.split("=").map((c) => c.trim());
69
- if (key) cookies[key] = decodeURIComponent(value);
70
- });
71
- return cookies;
72
- }
73
- createResponse() {
74
- let statusCode = 200;
75
- const headers = new Headers({
76
- "X-Content-Type-Options": "nosniff",
77
- "X-Frame-Options": "DENY"
78
- });
79
- return {
80
- status: (code) => {
81
- statusCode = code;
82
- return this;
83
- },
84
- setHeader: (key, value) => {
85
- headers.set(key, value);
86
- return this;
87
- },
88
- json: (data, status) => {
89
- headers.set("Content-Type", "application/json");
90
- return new Response(JSON.stringify(data), { status: status || statusCode, headers });
91
- },
92
- html: (html, status) => {
93
- headers.set("Content-Type", "text/html");
94
- return new Response(html, { status: status || statusCode, headers });
95
- },
96
- redirect: (url, status = 302) => {
97
- headers.set("Location", url);
98
- return new Response(null, { status, headers });
99
- }
100
- };
101
- }
102
- start(port) {
103
- console.log(`\u{1F680} Server listening on http://localhost:${port}`);
104
- serve({
105
- fetch: this.app.fetch,
106
- port
107
- });
108
- return Promise.resolve();
109
- }
110
- getApp() {
111
- return this.app;
112
- }
113
- };
114
-
115
- export {
116
- HonoServerAdapter
117
- };