burger-api 0.0.39 → 0.1.0
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/README.md +129 -8
- package/dist/src/core/{router.d.ts → api-router.d.ts} +11 -18
- package/dist/src/core/api-router.js +209 -0
- package/dist/src/core/openapi.d.ts +2 -2
- package/dist/src/core/page-router.d.ts +59 -0
- package/dist/src/core/page-router.js +231 -0
- package/dist/src/core/server.d.ts +5 -4
- package/dist/src/core/server.js +7 -5
- package/dist/src/index.d.ts +3 -2
- package/dist/src/index.js +28 -12
- package/dist/src/types/index.d.ts +5 -5
- package/dist/src/utils/error.js +2 -155
- package/dist/src/utils/index.d.ts +1 -0
- package/dist/src/utils/index.js +2 -0
- package/dist/src/utils/routing.d.ts +32 -0
- package/dist/src/utils/routing.js +54 -0
- package/package.json +5 -5
- package/dist/src/core/router.js +0 -197
package/README.md
CHANGED
|
@@ -1,9 +1,37 @@
|
|
|
1
|
-
|
|
1
|
+
|
|
2
|
+
<p align="center">
|
|
3
|
+
<img src="https://github.com/user-attachments/assets/0d9b376e-1d89-479a-aa7f-e7ee3c6b2342" alt="BurgerAPI logo"/>
|
|
4
|
+
</p>
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
[](https://github.com/isfhan/burger-api) [](LICENSE) [](https://bun.sh)
|
|
2
8
|
|
|
3
9
|
**burger-api** is a modern, open source API framework built on [Bun.js](https://bun.sh). It combines the simplicity of file-based routing with powerful features like built-in middleware, Zod-based schema validation, and automatic OpenAPI generation. Designed for high performance and ease-of-use, burger-api leverages Bun's native modules to deliver blazing-fast API responses while keeping your codebase clean and maintainable.
|
|
4
10
|
|
|
5
11
|
**This project is under active development and should not be used in production yet.**
|
|
6
12
|
|
|
13
|
+
## 📚 Table of Contents
|
|
14
|
+
|
|
15
|
+
- [Overview](#-overview)
|
|
16
|
+
- [Features](#-features)
|
|
17
|
+
- [Core Features](#core-features)
|
|
18
|
+
- [Release Notes](#-release-notes)
|
|
19
|
+
- [Version 0.1.0](#version-010)
|
|
20
|
+
- [Version 0.0.39](#version-0039)
|
|
21
|
+
- [What's Coming Next](#-whats-coming-next)
|
|
22
|
+
- [Installation](#-installation)
|
|
23
|
+
- [How to Use burger-api](#-how-to-use-burger-api)
|
|
24
|
+
- [Basic Usage Example](#basic-usage-example)
|
|
25
|
+
- [Project Structure](#recommended-project-structure)
|
|
26
|
+
- [Implementation Examples](#example-implementation)
|
|
27
|
+
- [File-Based Routing](#file-based-routing-examples)
|
|
28
|
+
- [Page Directory Usage](#page-directory-structure)
|
|
29
|
+
- [Route Examples](#route-file-example)
|
|
30
|
+
- [API Documentation](#api-documentation-endpoints)
|
|
31
|
+
- [Contributing](#-contributing)
|
|
32
|
+
- [License](#-license)
|
|
33
|
+
- [FAQs & Resources](#-faqs--additional-resources)
|
|
34
|
+
|
|
7
35
|
## 🚀 Overview
|
|
8
36
|
|
|
9
37
|
burger-api is built to offer a robust developer experience through:
|
|
@@ -65,15 +93,40 @@ burger-api is built to offer a robust developer experience through:
|
|
|
65
93
|
- 🔍 **Swagger UI Integration:**
|
|
66
94
|
Provides a `/docs` endpoint serving an interactive Swagger UI that reads from `/openapi.json`.
|
|
67
95
|
|
|
96
|
+
## 📣 Release Notes
|
|
97
|
+
|
|
98
|
+
### Version 0.1.0
|
|
99
|
+
|
|
100
|
+
- 🎨 **Static Page Serving:**
|
|
101
|
+
- Basic support for serving static `.html` files
|
|
102
|
+
- File-based routing for pages
|
|
103
|
+
- Support for route grouping with `(group)` syntax
|
|
104
|
+
- Support for dynamic route with `[slug]` syntax
|
|
105
|
+
|
|
106
|
+
### Version 0.0.39
|
|
107
|
+
|
|
108
|
+
- 🚀 Initial release with core API features
|
|
109
|
+
- ⚡ Bun-native HTTP server implementation
|
|
110
|
+
- 📁 File-based API routing
|
|
111
|
+
- ✅ Zod schema validation
|
|
112
|
+
- 📚 OpenAPI/Swagger integration
|
|
113
|
+
- 🔄 Middleware system
|
|
114
|
+
|
|
68
115
|
## 🎯 What's Coming Next?
|
|
69
116
|
|
|
70
|
-
We're enhancing burger-api
|
|
117
|
+
We're actively enhancing burger-api with powerful new features:
|
|
71
118
|
|
|
72
|
-
### 🎨
|
|
73
|
-
|
|
74
|
-
-
|
|
75
|
-
-
|
|
76
|
-
-
|
|
119
|
+
### 🎨 Page Serving Enhancements (In Development)
|
|
120
|
+
|
|
121
|
+
- 🔥 **TSX Support:** Adding React/TSX rendering capabilities
|
|
122
|
+
- 🔐 **Global Middleware:** Applies to all routes for tasks like logging and authentication.
|
|
123
|
+
- 🔐 **Page-Specific Middleware:** Defined in individual route files for tailored processing.
|
|
124
|
+
- 🛠️ **Advanced Middleware:** More built-in middleware for common use cases:
|
|
125
|
+
- CORS handling
|
|
126
|
+
- Rate limiting
|
|
127
|
+
- Request logging
|
|
128
|
+
- Security headers
|
|
129
|
+
- 🎯 **Performance Optimizations:** Further leveraging Bun's capabilities for faster page serving
|
|
77
130
|
|
|
78
131
|
Stay tuned for updates as we continue to build and improve burger-api! We're committed to making it the best API framework for Bun.js.
|
|
79
132
|
|
|
@@ -114,6 +167,7 @@ burger.serve(4000, (port) => {
|
|
|
114
167
|
```
|
|
115
168
|
|
|
116
169
|
The `debug` option enables:
|
|
170
|
+
|
|
117
171
|
- 🔍 Interactive stack trace page at when errors occur
|
|
118
172
|
- Shows detailed error information
|
|
119
173
|
- Displays the full stack trace
|
|
@@ -159,16 +213,22 @@ my-api/
|
|
|
159
213
|
Here's how to implement this structure:
|
|
160
214
|
|
|
161
215
|
1. **Global Middleware** (`src/middleware/global/logger.ts`):
|
|
216
|
+
|
|
162
217
|
```ts
|
|
163
218
|
import type { BurgerRequest, BurgerResponse } from "burger-api";
|
|
164
219
|
|
|
165
|
-
export const logger = async (
|
|
220
|
+
export const logger = async (
|
|
221
|
+
req: BurgerRequest,
|
|
222
|
+
res: BurgerResponse,
|
|
223
|
+
next: () => Promise<Response>
|
|
224
|
+
) => {
|
|
166
225
|
console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
|
|
167
226
|
return next();
|
|
168
227
|
};
|
|
169
228
|
```
|
|
170
229
|
|
|
171
230
|
2. **Route-Specific Middleware** (`src/middleware/routes/products.ts`):
|
|
231
|
+
|
|
172
232
|
```ts
|
|
173
233
|
import type { BurgerRequest, BurgerResponse } from "burger-api";
|
|
174
234
|
|
|
@@ -183,6 +243,7 @@ export const validateProductAccess = async (
|
|
|
183
243
|
```
|
|
184
244
|
|
|
185
245
|
3. **Schemas** (`src/schemas/product.ts`):
|
|
246
|
+
|
|
186
247
|
```ts
|
|
187
248
|
import { z } from "zod";
|
|
188
249
|
|
|
@@ -201,6 +262,7 @@ export const productSchema = {
|
|
|
201
262
|
```
|
|
202
263
|
|
|
203
264
|
4. **Route File** (`src/api/products/route.ts`):
|
|
265
|
+
|
|
204
266
|
```ts
|
|
205
267
|
import type { BurgerRequest, BurgerResponse } from "burger-api";
|
|
206
268
|
import { validateProductAccess } from "../../middleware/routes/products";
|
|
@@ -227,6 +289,7 @@ export async function POST(req: BurgerRequest, res: BurgerResponse) {
|
|
|
227
289
|
```
|
|
228
290
|
|
|
229
291
|
5. **Main Application** (`src/index.ts`):
|
|
292
|
+
|
|
230
293
|
```ts
|
|
231
294
|
import { Burger } from "burger-api";
|
|
232
295
|
import { logger } from "./middleware/global/logger";
|
|
@@ -245,6 +308,7 @@ burger.serve(4000, (port) => {
|
|
|
245
308
|
```
|
|
246
309
|
|
|
247
310
|
This structure provides several benefits:
|
|
311
|
+
|
|
248
312
|
- 🎯 Clear separation of concerns
|
|
249
313
|
- 📁 Easy to find and maintain code
|
|
250
314
|
- 🔄 Reusable components
|
|
@@ -265,6 +329,63 @@ This structure provides several benefits:
|
|
|
265
329
|
└── route.ts // Handles /api/product/:id
|
|
266
330
|
```
|
|
267
331
|
|
|
332
|
+
### **Page Directory Structure**
|
|
333
|
+
|
|
334
|
+
burger-api supports serving static pages alongside your API routes. Here's how to use the `pageDir` feature:
|
|
335
|
+
|
|
336
|
+
```ts
|
|
337
|
+
const burger = new Burger({
|
|
338
|
+
title: "My Custom API",
|
|
339
|
+
description: "Custom API with auto-generated docs and validation",
|
|
340
|
+
apiDir: "api",
|
|
341
|
+
pageDir: "pages", // Enable page serving from the pages directory
|
|
342
|
+
globalMiddleware: [globalLogger],
|
|
343
|
+
version: "1.0.0",
|
|
344
|
+
});
|
|
345
|
+
```
|
|
346
|
+
|
|
347
|
+
#### **Page Directory Structure Example:**
|
|
348
|
+
|
|
349
|
+
```
|
|
350
|
+
my-api/
|
|
351
|
+
├── src/
|
|
352
|
+
│ ├── pages/ # Pages directory
|
|
353
|
+
│ │ ├── index.html # Home page (/)
|
|
354
|
+
│ │ ├── about.html # About page (/about)
|
|
355
|
+
│ │ └── products/
|
|
356
|
+
│ │ ├── index.html # Products list (/products)
|
|
357
|
+
│ │ └── [id]/ # Dynamic product pages
|
|
358
|
+
│ │ └── index.html # Single product (/products/123)
|
|
359
|
+
│ └── api/ # Your API routes
|
|
360
|
+
```
|
|
361
|
+
|
|
362
|
+
#### **Page Routing Features:**
|
|
363
|
+
|
|
364
|
+
- 📄 **Index Pages:** Files named `index.html` serve as directory index pages
|
|
365
|
+
- 🔄 **Clean URLs:**
|
|
366
|
+
- `/pages/about.html` → `/about`
|
|
367
|
+
- 📁 **Dynamic Routes:** Use `[param]` syntax in folder names
|
|
368
|
+
- `/pages/products/[id]/index.html` → `/products/:id`
|
|
369
|
+
- 🎯 **Route Grouping:** Use `(group)` syntax for logical grouping
|
|
370
|
+
- `/pages/(auth)/login.html` → `/login`
|
|
371
|
+
- `/pages/(auth)/register.html` → `/register`
|
|
372
|
+
|
|
373
|
+
#### **Example Page Structure:**
|
|
374
|
+
|
|
375
|
+
```html
|
|
376
|
+
<!-- pages/products/[id]/index.html -->
|
|
377
|
+
<!DOCTYPE html>
|
|
378
|
+
<html>
|
|
379
|
+
<head>
|
|
380
|
+
<title>Product Details</title>
|
|
381
|
+
</head>
|
|
382
|
+
<body>
|
|
383
|
+
<h1>Product Details</h1>
|
|
384
|
+
<!-- Content here -->
|
|
385
|
+
</body>
|
|
386
|
+
</html>
|
|
387
|
+
```
|
|
388
|
+
|
|
268
389
|
### **Route File Example**
|
|
269
390
|
|
|
270
391
|
Below is an example route file demonstrating schema validation, route-specific middleware, and OpenAPI metadata.
|
|
@@ -1,17 +1,17 @@
|
|
|
1
1
|
import type { RouteDefinition } from "../types/index.js";
|
|
2
2
|
/**
|
|
3
|
-
*
|
|
3
|
+
* ApiRouter class for handling file-based routing.
|
|
4
4
|
* Loads routes from a directory structure and matches requests to the appropriate route handlers.
|
|
5
5
|
* Supports dynamic segments (e.g., [id]) and HTTP method handlers.
|
|
6
6
|
* Routes are sorted to prioritize static routes over dynamic ones to prevent overlapping route issues.
|
|
7
7
|
*/
|
|
8
|
-
export declare class
|
|
8
|
+
export declare class ApiRouter {
|
|
9
9
|
private routesDir;
|
|
10
10
|
private prefix;
|
|
11
11
|
/** Array of loaded route definitions */
|
|
12
12
|
routes: RouteDefinition[];
|
|
13
13
|
/**
|
|
14
|
-
* Constructor for the
|
|
14
|
+
* Constructor for the ApiRouter class.
|
|
15
15
|
* @param routesDir The directory path where route modules are located.
|
|
16
16
|
* @param prefix Optional prefix to prepend to all routes (e.g., "api" becomes "/api/...").
|
|
17
17
|
*/
|
|
@@ -20,14 +20,22 @@ export declare class Router {
|
|
|
20
20
|
* Loads route modules from the specified directory and adds them to the routes array.
|
|
21
21
|
* After loading, sorts the routes to prioritize static routes over dynamic ones based on specificity.
|
|
22
22
|
* @returns A promise that resolves when all route modules have been loaded and sorted.
|
|
23
|
+
* @throws Error if the routes directory doesn't exist or can't be accessed
|
|
23
24
|
*/
|
|
24
25
|
loadRoutes(): Promise<void>;
|
|
25
26
|
/**
|
|
26
27
|
* Recursively scans the directory for route modules and adds them to the routes array.
|
|
27
28
|
* @param dir The current directory to scan.
|
|
28
29
|
* @param basePath The base path for constructing the route path.
|
|
30
|
+
* @throws Error if multiple dynamic folders are found at the same level or if directory access fails
|
|
29
31
|
*/
|
|
30
32
|
private scanDirectory;
|
|
33
|
+
/**
|
|
34
|
+
* Loads a route module and adds it to the routes array
|
|
35
|
+
* @param entryPath Full path to the route file
|
|
36
|
+
* @param relativePath Relative path used to construct the route
|
|
37
|
+
*/
|
|
38
|
+
private loadRouteModule;
|
|
31
39
|
/**
|
|
32
40
|
* Converts a file path to a route path by processing dynamic segments,
|
|
33
41
|
* removing certain directory indicators, and applying a prefix if specified.
|
|
@@ -51,19 +59,4 @@ export declare class Router {
|
|
|
51
59
|
* @returns A record of dynamic parameters if matched, otherwise null.
|
|
52
60
|
*/
|
|
53
61
|
private matchRoute;
|
|
54
|
-
/**
|
|
55
|
-
* Calculates the specificity of a route path based on the number of static segments.
|
|
56
|
-
* Static segments increase the score, while dynamic segments (:param) do not.
|
|
57
|
-
* @param path The route path to evaluate.
|
|
58
|
-
* @returns The specificity score (higher means more static segments).
|
|
59
|
-
*/
|
|
60
|
-
private getRouteSpecificity;
|
|
61
|
-
/**
|
|
62
|
-
* Compares two routes for sorting, prioritizing those with higher specificity (more static segments).
|
|
63
|
-
* If specificity is equal, sorts alphabetically by path.
|
|
64
|
-
* @param a The first route to compare.
|
|
65
|
-
* @param b The second route to compare.
|
|
66
|
-
* @returns Negative if a comes before b, positive if b comes before a, zero if equal.
|
|
67
|
-
*/
|
|
68
|
-
private compareRoutes;
|
|
69
62
|
}
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
// Import stuff from node
|
|
2
|
+
import { readdirSync } from "fs";
|
|
3
|
+
import * as path from "path";
|
|
4
|
+
// Import utils
|
|
5
|
+
import { cleanPrefix, normalizePath, compareRoutes, ROUTE_CONSTANTS, HTTP_METHODS, } from "../utils/index.js";
|
|
6
|
+
/**
|
|
7
|
+
* ApiRouter class for handling file-based routing.
|
|
8
|
+
* Loads routes from a directory structure and matches requests to the appropriate route handlers.
|
|
9
|
+
* Supports dynamic segments (e.g., [id]) and HTTP method handlers.
|
|
10
|
+
* Routes are sorted to prioritize static routes over dynamic ones to prevent overlapping route issues.
|
|
11
|
+
*/
|
|
12
|
+
export class ApiRouter {
|
|
13
|
+
routesDir;
|
|
14
|
+
prefix;
|
|
15
|
+
/** Array of loaded route definitions */
|
|
16
|
+
routes = [];
|
|
17
|
+
/**
|
|
18
|
+
* Constructor for the ApiRouter class.
|
|
19
|
+
* @param routesDir The directory path where route modules are located.
|
|
20
|
+
* @param prefix Optional prefix to prepend to all routes (e.g., "api" becomes "/api/...").
|
|
21
|
+
*/
|
|
22
|
+
constructor(routesDir, prefix = "") {
|
|
23
|
+
this.routesDir = routesDir;
|
|
24
|
+
this.prefix = prefix;
|
|
25
|
+
if (!routesDir) {
|
|
26
|
+
throw new Error("Routes directory path is required");
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Loads route modules from the specified directory and adds them to the routes array.
|
|
31
|
+
* After loading, sorts the routes to prioritize static routes over dynamic ones based on specificity.
|
|
32
|
+
* @returns A promise that resolves when all route modules have been loaded and sorted.
|
|
33
|
+
* @throws Error if the routes directory doesn't exist or can't be accessed
|
|
34
|
+
*/
|
|
35
|
+
async loadRoutes() {
|
|
36
|
+
try {
|
|
37
|
+
this.routes = [];
|
|
38
|
+
await this.scanDirectory(this.routesDir);
|
|
39
|
+
// Sort routes to ensure static routes are matched before dynamic ones
|
|
40
|
+
this.routes.sort((a, b) => compareRoutes(a, b));
|
|
41
|
+
}
|
|
42
|
+
catch (error) {
|
|
43
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
44
|
+
throw new Error(`Failed to load routes: ${errorMessage}`);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Recursively scans the directory for route modules and adds them to the routes array.
|
|
49
|
+
* @param dir The current directory to scan.
|
|
50
|
+
* @param basePath The base path for constructing the route path.
|
|
51
|
+
* @throws Error if multiple dynamic folders are found at the same level or if directory access fails
|
|
52
|
+
*/
|
|
53
|
+
async scanDirectory(dir, basePath = "") {
|
|
54
|
+
// Track if a dynamic folder has been found at this directory level
|
|
55
|
+
let dynamicFolderFound = false;
|
|
56
|
+
try {
|
|
57
|
+
const entries = readdirSync(dir, { withFileTypes: true });
|
|
58
|
+
for (const entry of entries) {
|
|
59
|
+
const entryPath = path.join(dir, entry.name);
|
|
60
|
+
const relativePath = path.join(basePath, entry.name);
|
|
61
|
+
if (entry.isDirectory()) {
|
|
62
|
+
// Handle dynamic directories (e.g., [id])
|
|
63
|
+
if (entry.name.startsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_START) &&
|
|
64
|
+
entry.name.endsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_END)) {
|
|
65
|
+
if (dynamicFolderFound) {
|
|
66
|
+
throw new Error(`Multiple dynamic route folders found in the same directory: '${entry.name}' conflicts with another dynamic folder in '${dir}'.`);
|
|
67
|
+
}
|
|
68
|
+
dynamicFolderFound = true;
|
|
69
|
+
}
|
|
70
|
+
await this.scanDirectory(entryPath, relativePath);
|
|
71
|
+
}
|
|
72
|
+
else if (entry.isFile() && entry.name === "route.ts") {
|
|
73
|
+
await this.loadRouteModule(entryPath, relativePath);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
catch (error) {
|
|
78
|
+
if (error instanceof Error) {
|
|
79
|
+
throw error; // Re-throw specific errors we created
|
|
80
|
+
}
|
|
81
|
+
throw new Error(`Failed to scan directory '${dir}': ${String(error)}`);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Loads a route module and adds it to the routes array
|
|
86
|
+
* @param entryPath Full path to the route file
|
|
87
|
+
* @param relativePath Relative path used to construct the route
|
|
88
|
+
*/
|
|
89
|
+
async loadRouteModule(entryPath, relativePath) {
|
|
90
|
+
try {
|
|
91
|
+
// Convert file path to route path and load the module
|
|
92
|
+
const routePath = this.convertFilePathToRoute(relativePath);
|
|
93
|
+
const modulePath = path.resolve(entryPath);
|
|
94
|
+
const routeModule = await import(modulePath);
|
|
95
|
+
// Collect HTTP method handlers from the module
|
|
96
|
+
const handlers = {};
|
|
97
|
+
for (const method of HTTP_METHODS) {
|
|
98
|
+
if (typeof routeModule[method] === "function") {
|
|
99
|
+
handlers[method] = routeModule[method];
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
// Create route definition
|
|
103
|
+
const routeDef = {
|
|
104
|
+
path: routePath,
|
|
105
|
+
handlers,
|
|
106
|
+
middleware: routeModule.middleware,
|
|
107
|
+
schema: routeModule.schema,
|
|
108
|
+
openapi: routeModule.openapi,
|
|
109
|
+
};
|
|
110
|
+
this.routes.push(routeDef);
|
|
111
|
+
}
|
|
112
|
+
catch (error) {
|
|
113
|
+
throw new Error(`Failed to load route module '${entryPath}': ${String(error)}`);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Converts a file path to a route path by processing dynamic segments,
|
|
118
|
+
* removing certain directory indicators, and applying a prefix if specified.
|
|
119
|
+
* @param filePath The file path to convert into a route path.
|
|
120
|
+
* @returns The converted route path string.
|
|
121
|
+
*/
|
|
122
|
+
convertFilePathToRoute(filePath) {
|
|
123
|
+
// Remove the "route.ts" suffix
|
|
124
|
+
if (filePath.endsWith("route.ts")) {
|
|
125
|
+
filePath = filePath.slice(0, -"route.ts".length);
|
|
126
|
+
}
|
|
127
|
+
// Split path into segments
|
|
128
|
+
const segments = filePath.split(path.sep);
|
|
129
|
+
const resultSegments = [];
|
|
130
|
+
for (let segment of segments) {
|
|
131
|
+
if (!segment)
|
|
132
|
+
continue; // Skip empty segments
|
|
133
|
+
// Skip grouping segments (e.g., (group))
|
|
134
|
+
if (segment.startsWith(ROUTE_CONSTANTS.GROUPING_FOLDER_START) &&
|
|
135
|
+
segment.endsWith(ROUTE_CONSTANTS.GROUPING_FOLDER_END))
|
|
136
|
+
continue;
|
|
137
|
+
// Convert dynamic segments from [param] to :param
|
|
138
|
+
if (segment.startsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_START) &&
|
|
139
|
+
segment.endsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_END)) {
|
|
140
|
+
const param = segment.slice(1, -1);
|
|
141
|
+
resultSegments.push(ROUTE_CONSTANTS.DYNAMIC_SEGMENT_PREFIX + param);
|
|
142
|
+
}
|
|
143
|
+
else {
|
|
144
|
+
resultSegments.push(segment);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
// Construct the route with leading slash
|
|
148
|
+
let route = "/" + resultSegments.join("/");
|
|
149
|
+
// Apply prefix if provided
|
|
150
|
+
if (this.prefix) {
|
|
151
|
+
const cleanPrefixStr = cleanPrefix(this.prefix);
|
|
152
|
+
route = "/" + cleanPrefixStr + route;
|
|
153
|
+
}
|
|
154
|
+
// Remove trailing slash unless it's the root
|
|
155
|
+
if (route !== "/" && route.endsWith("/")) {
|
|
156
|
+
route = route.slice(0, -1);
|
|
157
|
+
}
|
|
158
|
+
return route;
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Resolves the given request by finding a matching route and extracting dynamic parameters.
|
|
162
|
+
* @param request The request to resolve.
|
|
163
|
+
* @returns An object containing the matched route and parameters, or an empty params object if no match.
|
|
164
|
+
*/
|
|
165
|
+
resolve(request) {
|
|
166
|
+
try {
|
|
167
|
+
const url = new URL(request.url);
|
|
168
|
+
const reqPath = normalizePath(url.pathname);
|
|
169
|
+
const method = request.method.toUpperCase();
|
|
170
|
+
for (const route of this.routes) {
|
|
171
|
+
const match = this.matchRoute(reqPath, route.path);
|
|
172
|
+
if (match && route.handlers[method]) {
|
|
173
|
+
return { route, params: match };
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
return { params: {} };
|
|
177
|
+
}
|
|
178
|
+
catch (error) {
|
|
179
|
+
// Return no match in case of URL parsing errors
|
|
180
|
+
return { params: {} };
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Checks if the request path matches the route path, extracting dynamic parameters if matched.
|
|
185
|
+
* @param requestPath The request path to check.
|
|
186
|
+
* @param routePath The route path to match against.
|
|
187
|
+
* @returns A record of dynamic parameters if matched, otherwise null.
|
|
188
|
+
*/
|
|
189
|
+
matchRoute(requestPath, routePath) {
|
|
190
|
+
const reqSegments = requestPath.split("/").filter(Boolean);
|
|
191
|
+
const routeSegments = routePath.split("/").filter(Boolean);
|
|
192
|
+
if (reqSegments.length !== routeSegments.length) {
|
|
193
|
+
return null;
|
|
194
|
+
}
|
|
195
|
+
const params = {};
|
|
196
|
+
for (let i = 0; i < reqSegments.length; i++) {
|
|
197
|
+
const rSegment = routeSegments[i];
|
|
198
|
+
const reqSegment = reqSegments[i];
|
|
199
|
+
if (rSegment.startsWith(ROUTE_CONSTANTS.DYNAMIC_SEGMENT_PREFIX)) {
|
|
200
|
+
const paramName = rSegment.slice(1);
|
|
201
|
+
params[paramName] = decodeURIComponent(reqSegment);
|
|
202
|
+
}
|
|
203
|
+
else if (rSegment !== reqSegment) {
|
|
204
|
+
return null;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
return params;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { ApiRouter } from "./api-router.js";
|
|
2
2
|
import type { ServerOptions } from "../types/index.js";
|
|
3
3
|
/**
|
|
4
4
|
* Generates an OpenAPI 3.0 document from the router's routes and global options.
|
|
@@ -6,7 +6,7 @@ import type { ServerOptions } from "../types/index.js";
|
|
|
6
6
|
* @param options Global options, including OpenAPI metadata.
|
|
7
7
|
* @returns The OpenAPI document as a JavaScript object.
|
|
8
8
|
*/
|
|
9
|
-
export declare function generateOpenAPIDocument(router:
|
|
9
|
+
export declare function generateOpenAPIDocument(router: ApiRouter, options: ServerOptions): {
|
|
10
10
|
openapi: string;
|
|
11
11
|
info: {
|
|
12
12
|
title: string;
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import type { PageDefinition } from "../types/index.js";
|
|
2
|
+
/**
|
|
3
|
+
* PageRouter class for handling file-based page routing.
|
|
4
|
+
* Loads pages from a directory structure and matches requests to the appropriate page handlers.
|
|
5
|
+
* Supports dynamic segments (e.g., [id]) and uses default exports as page handlers.
|
|
6
|
+
*/
|
|
7
|
+
export declare class PageRouter {
|
|
8
|
+
private pagesDir;
|
|
9
|
+
private prefix;
|
|
10
|
+
/** Array of loaded page definitions */
|
|
11
|
+
pages: PageDefinition[];
|
|
12
|
+
/**
|
|
13
|
+
* Constructor for the PageRouter class.
|
|
14
|
+
* @param pagesDir The directory path where page modules are located.
|
|
15
|
+
* @param prefix Optional prefix to prepend to all routes (e.g., "pages" becomes "/pages/...").
|
|
16
|
+
*/
|
|
17
|
+
constructor(pagesDir: string, prefix?: string);
|
|
18
|
+
/**
|
|
19
|
+
* Loads page modules from the specified directory and adds them to the pages array.
|
|
20
|
+
* After loading, sorts the pages to prioritize static routes over dynamic ones based on specificity.
|
|
21
|
+
* @returns A promise that resolves when all page modules have been loaded and sorted.
|
|
22
|
+
*/
|
|
23
|
+
loadPages(): Promise<void>;
|
|
24
|
+
/**
|
|
25
|
+
* Recursively scans the directory for page modules and adds them to the pages array.
|
|
26
|
+
* @param dir The current directory to scan.
|
|
27
|
+
* @param basePath The base path for constructing the route path.
|
|
28
|
+
*/
|
|
29
|
+
private scanDirectory;
|
|
30
|
+
/**
|
|
31
|
+
* Converts a file path to a route path by processing dynamic segments,
|
|
32
|
+
* removing certain directory indicators, and applying a prefix if specified.
|
|
33
|
+
* @param filePath The file path to convert into a route path.
|
|
34
|
+
* @returns The converted route path string (before extension cleaning).
|
|
35
|
+
*/
|
|
36
|
+
private convertFilePathToRoute;
|
|
37
|
+
/**
|
|
38
|
+
* Cleans a route path by handling index files and removing extensions.
|
|
39
|
+
* @param routePath The route path to clean
|
|
40
|
+
* @returns The cleaned route path
|
|
41
|
+
*/
|
|
42
|
+
private cleanRoutePath;
|
|
43
|
+
/**
|
|
44
|
+
* Resolves the given request by finding a matching page and extracting dynamic parameters.
|
|
45
|
+
* @param request The request to resolve.
|
|
46
|
+
* @returns An object containing the matched page and parameters, or an empty params object if no match.
|
|
47
|
+
*/
|
|
48
|
+
resolve(request: Request): {
|
|
49
|
+
page?: PageDefinition;
|
|
50
|
+
params: Record<string, string>;
|
|
51
|
+
};
|
|
52
|
+
/**
|
|
53
|
+
* Checks if the request path matches the page path, extracting dynamic parameters if matched.
|
|
54
|
+
* @param requestPath The request path to check.
|
|
55
|
+
* @param pagePath The page path to match against.
|
|
56
|
+
* @returns A record of dynamic parameters if matched, otherwise null.
|
|
57
|
+
*/
|
|
58
|
+
private matchRoute;
|
|
59
|
+
}
|