@lark-apaas/devtool-kits 0.1.0-alpha.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/LICENSE +13 -0
- package/README.md +313 -0
- package/dist/index.cjs +29557 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +179 -0
- package/dist/index.d.ts +179 -0
- package/dist/index.js +29545 -0
- package/dist/index.js.map +1 -0
- package/package.json +54 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Lark Technologies Pte. Ltd. and/or its affiliates
|
|
4
|
+
|
|
5
|
+
Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted,provided that the above copyright notice and this permission notice appear in all copies.
|
|
6
|
+
|
|
7
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
|
|
8
|
+
IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE
|
|
9
|
+
INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
|
|
10
|
+
EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
|
|
11
|
+
CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
|
|
12
|
+
DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
|
|
13
|
+
ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
# Fullstack Toolkits
|
|
2
|
+
|
|
3
|
+
A comprehensive toolkit for NestJS applications, providing middleware utilities and development tools.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- 🔧 **Development Middleware** - Dev-logs middleware for request/response logging and tracing
|
|
8
|
+
- 📚 **OpenAPI Enhancement** - Enhanced OpenAPI/Swagger documentation with source code information
|
|
9
|
+
- 🛠️ **Utility Functions** - Common utilities for path normalization and more
|
|
10
|
+
- 🔍 **Path Matching** - Powerful path pattern matching for OpenAPI/Swagger/NestJS routes
|
|
11
|
+
|
|
12
|
+
## Installation
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
npm install @apaas/fullstack-toolkits
|
|
16
|
+
# or
|
|
17
|
+
yarn add @apaas/fullstack-toolkits
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
## Usage
|
|
21
|
+
|
|
22
|
+
### Middleware Registration
|
|
23
|
+
|
|
24
|
+
The toolkit supports two types of middlewares:
|
|
25
|
+
- **Route Middlewares**: Mount at specific paths (e.g., `/dev/logs`, `/openapi.json`)
|
|
26
|
+
- **Global Middlewares**: Apply to all requests without path mounting
|
|
27
|
+
|
|
28
|
+
Use the `registerMiddlewares` function to register both types:
|
|
29
|
+
|
|
30
|
+
```typescript
|
|
31
|
+
import {
|
|
32
|
+
registerMiddlewares,
|
|
33
|
+
createDevLogsMiddleware,
|
|
34
|
+
createOpenapiMiddleware
|
|
35
|
+
} from '@apaas/fullstack-toolkits';
|
|
36
|
+
|
|
37
|
+
// For rspack/webpack dev server
|
|
38
|
+
export default {
|
|
39
|
+
devServer: {
|
|
40
|
+
setupMiddlewares: (middlewares, devServer) => {
|
|
41
|
+
if (devServer.app) {
|
|
42
|
+
registerMiddlewares(devServer.app, [
|
|
43
|
+
// Global middlewares execute first (in array order)
|
|
44
|
+
createCorsMiddleware({ origin: '*' }),
|
|
45
|
+
createRequestLoggerMiddleware(),
|
|
46
|
+
|
|
47
|
+
// Route middlewares mount at specific paths
|
|
48
|
+
createDevLogsMiddleware({ logDir: './logs' }),
|
|
49
|
+
createOpenapiMiddleware({
|
|
50
|
+
openapiFilePath: './openapi.json',
|
|
51
|
+
enableEnhancement: true
|
|
52
|
+
}),
|
|
53
|
+
], {
|
|
54
|
+
basePath: '/api',
|
|
55
|
+
isDev: true,
|
|
56
|
+
rootDir: __dirname
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
return middlewares;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// For Vite dev server
|
|
65
|
+
export default {
|
|
66
|
+
plugins: [
|
|
67
|
+
{
|
|
68
|
+
name: 'dev-middlewares',
|
|
69
|
+
configureServer: (server) => {
|
|
70
|
+
registerMiddlewares(server.middlewares, [
|
|
71
|
+
createDevLogsMiddleware({ logDir: './logs' }),
|
|
72
|
+
createOpenapiMiddleware({
|
|
73
|
+
openapiFilePath: './openapi.json',
|
|
74
|
+
enableEnhancement: true
|
|
75
|
+
}),
|
|
76
|
+
], {
|
|
77
|
+
basePath: '/',
|
|
78
|
+
isDev: true,
|
|
79
|
+
rootDir: __dirname
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
]
|
|
84
|
+
}
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
**Important Notes:**
|
|
88
|
+
- Middleware execution order matches the array order
|
|
89
|
+
- Place global middlewares before route middlewares
|
|
90
|
+
- Global middlewares apply to all requests
|
|
91
|
+
- Route middlewares only handle requests matching their mount path
|
|
92
|
+
|
|
93
|
+
### Global Middleware Examples
|
|
94
|
+
|
|
95
|
+
Create custom global middlewares using the `GlobalMiddleware` interface:
|
|
96
|
+
|
|
97
|
+
```typescript
|
|
98
|
+
import type { GlobalMiddleware } from '@apaas/fullstack-toolkits';
|
|
99
|
+
|
|
100
|
+
// Example: CORS middleware
|
|
101
|
+
function createCorsMiddleware(options?: { origin?: string }): GlobalMiddleware {
|
|
102
|
+
return {
|
|
103
|
+
name: 'cors',
|
|
104
|
+
createHandler: () => {
|
|
105
|
+
return (req, res, next) => {
|
|
106
|
+
res.setHeader('Access-Control-Allow-Origin', options?.origin || '*');
|
|
107
|
+
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
|
|
108
|
+
next();
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// Example: Request logger
|
|
115
|
+
function createRequestLoggerMiddleware(): GlobalMiddleware {
|
|
116
|
+
return {
|
|
117
|
+
name: 'request-logger',
|
|
118
|
+
enabled: (context) => context.isDev, // Only in dev mode
|
|
119
|
+
createHandler: () => {
|
|
120
|
+
return (req, res, next) => {
|
|
121
|
+
console.log(`[${new Date().toISOString()}] ${req.method} ${req.path}`);
|
|
122
|
+
next();
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
See `src/middlewares/examples.ts` for more global middleware examples.
|
|
130
|
+
|
|
131
|
+
### Dev Logs Middleware
|
|
132
|
+
|
|
133
|
+
Provides request/response logging with trace ID support.
|
|
134
|
+
|
|
135
|
+
**Features:**
|
|
136
|
+
- View log entries by trace ID
|
|
137
|
+
- Browse recent trace calls with pagination
|
|
138
|
+
- Filter logs by API path patterns
|
|
139
|
+
- Support for OpenAPI/Swagger path patterns
|
|
140
|
+
|
|
141
|
+
**Routes:**
|
|
142
|
+
- `GET /dev/logs/app/trace/:traceId` - Get log entries by trace ID
|
|
143
|
+
- `GET /dev/logs/trace/recent` - Get recent trace calls (with pagination and path filtering)
|
|
144
|
+
- `GET /dev/logs/files/:fileName` - Get log file content
|
|
145
|
+
|
|
146
|
+
**Example:**
|
|
147
|
+
```typescript
|
|
148
|
+
createDevLogsMiddleware({
|
|
149
|
+
logDir: './logs', // Optional, defaults to 'logs'
|
|
150
|
+
})
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
### OpenAPI Middleware
|
|
154
|
+
|
|
155
|
+
Enhances OpenAPI/Swagger documentation with source code information.
|
|
156
|
+
|
|
157
|
+
**Features:**
|
|
158
|
+
- Automatically enhance OpenAPI paths with controller source locations
|
|
159
|
+
- Transform paths to include basePath
|
|
160
|
+
- Caching support for better performance
|
|
161
|
+
|
|
162
|
+
**Routes:**
|
|
163
|
+
- `GET /dev/openapi` - Get enhanced OpenAPI documentation
|
|
164
|
+
|
|
165
|
+
**Example:**
|
|
166
|
+
```typescript
|
|
167
|
+
createOpenapiMiddleware({
|
|
168
|
+
openapiPath: './openapi.json',
|
|
169
|
+
enableEnhancement: true,
|
|
170
|
+
})
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
### Path Matching Utility
|
|
174
|
+
|
|
175
|
+
Powerful path pattern matching for OpenAPI/Swagger/NestJS routes.
|
|
176
|
+
|
|
177
|
+
**Supported Patterns:**
|
|
178
|
+
- Exact matching: `/api/users` === `/api/users`
|
|
179
|
+
- Path parameters: `/api/users/{id}` matches `/api/users/123`
|
|
180
|
+
- Single wildcard: `/api/*/users` matches `/api/v1/users`
|
|
181
|
+
- Recursive wildcard: `/files/**` matches `/files/a/b/c`
|
|
182
|
+
- Prefix matching: `/api/users` matches `/api/users/123`
|
|
183
|
+
|
|
184
|
+
**Example:**
|
|
185
|
+
```typescript
|
|
186
|
+
import { matchesPathPattern, extractPathParams } from '@apaas/fullstack-toolkits';
|
|
187
|
+
|
|
188
|
+
// Match path patterns
|
|
189
|
+
matchesPathPattern('/api/users/123', '/api/users/{id}'); // true
|
|
190
|
+
matchesPathPattern('/api/v1/users', '/api/*/users'); // true
|
|
191
|
+
matchesPathPattern('/files/a/b/c', '/files/**'); // true
|
|
192
|
+
|
|
193
|
+
// Extract path parameters
|
|
194
|
+
extractPathParams('/api/users/123', '/api/users/{id}');
|
|
195
|
+
// Returns: { id: '123' }
|
|
196
|
+
|
|
197
|
+
extractPathParams('/api/users/123/posts/456', '/api/users/{userId}/posts/{postId}');
|
|
198
|
+
// Returns: { userId: '123', postId: '456' }
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
### Utility Functions
|
|
202
|
+
|
|
203
|
+
```typescript
|
|
204
|
+
import { normalizeBasePath } from '@apaas/fullstack-toolkits';
|
|
205
|
+
|
|
206
|
+
// Normalize base path (adds leading slash, removes trailing slash)
|
|
207
|
+
normalizeBasePath('api'); // '/api'
|
|
208
|
+
normalizeBasePath('/api/'); // '/api'
|
|
209
|
+
normalizeBasePath('api/v1'); // '/api/v1'
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
## API Reference
|
|
213
|
+
|
|
214
|
+
### Middleware Types
|
|
215
|
+
|
|
216
|
+
#### `RouteMiddleware`
|
|
217
|
+
Route-based middleware that mounts at a specific path.
|
|
218
|
+
|
|
219
|
+
```typescript
|
|
220
|
+
interface RouteMiddleware {
|
|
221
|
+
name: string;
|
|
222
|
+
mountPath: string; // Required - path to mount the router
|
|
223
|
+
routes?: RouteInfo[];
|
|
224
|
+
enabled?: (context: MiddlewareContext) => boolean;
|
|
225
|
+
createRouter: (context: MiddlewareContext) => Router;
|
|
226
|
+
}
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
**Example:**
|
|
230
|
+
```typescript
|
|
231
|
+
function createDevLogsMiddleware(options): RouteMiddleware {
|
|
232
|
+
return {
|
|
233
|
+
name: 'dev-logs',
|
|
234
|
+
mountPath: '/dev/logs',
|
|
235
|
+
createRouter: (context) => createRouter(options)
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
#### `GlobalMiddleware`
|
|
241
|
+
Global middleware that applies to all requests.
|
|
242
|
+
|
|
243
|
+
```typescript
|
|
244
|
+
interface GlobalMiddleware {
|
|
245
|
+
name: string;
|
|
246
|
+
mountPath?: never; // Must not have mountPath
|
|
247
|
+
enabled?: (context: MiddlewareContext) => boolean;
|
|
248
|
+
createHandler: (context: MiddlewareContext) => RequestHandler;
|
|
249
|
+
}
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
**Example:**
|
|
253
|
+
```typescript
|
|
254
|
+
function createCorsMiddleware(): GlobalMiddleware {
|
|
255
|
+
return {
|
|
256
|
+
name: 'cors',
|
|
257
|
+
createHandler: () => (req, res, next) => {
|
|
258
|
+
res.setHeader('Access-Control-Allow-Origin', '*');
|
|
259
|
+
next();
|
|
260
|
+
}
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
```
|
|
264
|
+
|
|
265
|
+
#### `Middleware`
|
|
266
|
+
Union type of route-based and global middlewares.
|
|
267
|
+
|
|
268
|
+
```typescript
|
|
269
|
+
type Middleware = RouteMiddleware | GlobalMiddleware;
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
#### `MiddlewareContext`
|
|
273
|
+
```typescript
|
|
274
|
+
interface MiddlewareContext {
|
|
275
|
+
basePath: string;
|
|
276
|
+
isDev: boolean;
|
|
277
|
+
rootDir: string;
|
|
278
|
+
[key: string]: any;
|
|
279
|
+
}
|
|
280
|
+
```
|
|
281
|
+
|
|
282
|
+
### Core Functions
|
|
283
|
+
|
|
284
|
+
#### `registerMiddlewares(server, middlewares, options?): Promise<void>`
|
|
285
|
+
Register middlewares for Express-compatible servers or Vite dev server.
|
|
286
|
+
|
|
287
|
+
**Parameters:**
|
|
288
|
+
- `server` - Express app or Vite middleware instance
|
|
289
|
+
- `middlewares` - Array of middleware objects (route or global)
|
|
290
|
+
- `options` - Optional context configuration
|
|
291
|
+
|
|
292
|
+
**Returns:** Promise that resolves when all middlewares are registered
|
|
293
|
+
|
|
294
|
+
**Example:**
|
|
295
|
+
```typescript
|
|
296
|
+
await registerMiddlewares(devServer.app, [
|
|
297
|
+
createCorsMiddleware(),
|
|
298
|
+
createDevLogsMiddleware({ logDir: './logs' })
|
|
299
|
+
], {
|
|
300
|
+
basePath: '/api',
|
|
301
|
+
isDev: true,
|
|
302
|
+
rootDir: __dirname
|
|
303
|
+
});
|
|
304
|
+
```
|
|
305
|
+
|
|
306
|
+
### Utility Functions
|
|
307
|
+
|
|
308
|
+
#### `normalizeBasePath(basePath): string`
|
|
309
|
+
Normalize base path to ensure it starts with '/' and has no trailing slash.
|
|
310
|
+
|
|
311
|
+
## License
|
|
312
|
+
|
|
313
|
+
MIT
|