veloce-ts 0.4.6 → 0.4.8

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.
Files changed (65) hide show
  1. package/CHANGELOG.md +741 -727
  2. package/dist/cjs/src/adapters/base.js +2 -2
  3. package/dist/cjs/src/adapters/base.js.map +1 -1
  4. package/dist/cjs/src/adapters/express.js +3 -3
  5. package/dist/cjs/src/adapters/express.js.map +2 -2
  6. package/dist/cjs/src/adapters/hono.js +2 -2
  7. package/dist/cjs/src/adapters/hono.js.map +2 -2
  8. package/dist/cjs/src/auth/index.js +4 -4
  9. package/dist/cjs/src/auth/index.js.map +5 -5
  10. package/dist/cjs/src/cli/index.js +31 -31
  11. package/dist/cjs/src/cli/index.js.map +4 -4
  12. package/dist/cjs/src/docs/index.js +6 -6
  13. package/dist/cjs/src/docs/index.js.map +2 -2
  14. package/dist/cjs/src/errors/index.js +12 -12
  15. package/dist/cjs/src/errors/index.js.map +3 -3
  16. package/dist/cjs/src/graphql/index.js +9 -9
  17. package/dist/cjs/src/graphql/index.js.map +2 -2
  18. package/dist/cjs/src/index.js +28 -28
  19. package/dist/cjs/src/index.js.map +29 -25
  20. package/dist/cjs/src/middleware/index.js +6 -6
  21. package/dist/cjs/src/middleware/index.js.map +3 -3
  22. package/dist/cjs/src/plugins/index.js +15 -15
  23. package/dist/cjs/src/plugins/index.js.map +3 -3
  24. package/dist/cjs/src/testing/index.js +26 -26
  25. package/dist/cjs/src/testing/index.js.map +28 -24
  26. package/dist/cjs/src/types/index.js +2 -2
  27. package/dist/cjs/src/types/index.js.map +2 -2
  28. package/dist/cjs/src/validation/index.js +2 -2
  29. package/dist/cjs/src/validation/index.js.map +2 -2
  30. package/dist/cjs/src/websocket/index.js +3 -3
  31. package/dist/cjs/src/websocket/index.js.map +2 -2
  32. package/dist/esm/src/adapters/base.js +1 -2
  33. package/dist/esm/src/adapters/base.js.map +1 -1
  34. package/dist/esm/src/adapters/express.js +3 -3
  35. package/dist/esm/src/adapters/express.js.map +2 -2
  36. package/dist/esm/src/adapters/hono.js +2 -2
  37. package/dist/esm/src/adapters/hono.js.map +2 -2
  38. package/dist/esm/src/auth/index.js +4 -4
  39. package/dist/esm/src/auth/index.js.map +5 -5
  40. package/dist/esm/src/cli/index.js +31 -31
  41. package/dist/esm/src/cli/index.js.map +4 -4
  42. package/dist/esm/src/docs/index.js +6 -6
  43. package/dist/esm/src/docs/index.js.map +2 -2
  44. package/dist/esm/src/errors/index.js +12 -12
  45. package/dist/esm/src/errors/index.js.map +3 -3
  46. package/dist/esm/src/graphql/index.js +10 -10
  47. package/dist/esm/src/graphql/index.js.map +2 -2
  48. package/dist/esm/src/index.js +29 -29
  49. package/dist/esm/src/index.js.map +29 -25
  50. package/dist/esm/src/middleware/index.js +6 -6
  51. package/dist/esm/src/middleware/index.js.map +3 -3
  52. package/dist/esm/src/plugins/index.js +15 -15
  53. package/dist/esm/src/plugins/index.js.map +3 -3
  54. package/dist/esm/src/testing/index.js +26 -26
  55. package/dist/esm/src/testing/index.js.map +28 -24
  56. package/dist/esm/src/types/index.js +2 -2
  57. package/dist/esm/src/types/index.js.map +2 -2
  58. package/dist/esm/src/validation/index.js +2 -2
  59. package/dist/esm/src/validation/index.js.map +2 -2
  60. package/dist/esm/src/websocket/index.js +3 -3
  61. package/dist/esm/src/websocket/index.js.map +2 -2
  62. package/dist/types/auth/rbac-plugin.d.ts +1 -1
  63. package/dist/types/auth/rbac-plugin.d.ts.map +1 -1
  64. package/dist/types/logging/logger.d.ts.map +1 -1
  65. package/package.json +199 -199
package/CHANGELOG.md CHANGED
@@ -1,727 +1,741 @@
1
- # Changelog
2
-
3
- All notable changes to this project will be documented in this file.
4
-
5
- The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
- and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
-
8
- ## [Unreleased]
9
-
10
- ## [0.4.5] - 2026-03-29
11
-
12
- Mismo parche CORS que se intentó en **0.4.4**; npm **no permite republicar** un número de versión tras `npm unpublish` (`E400 Cannot publish over previously published version`).
13
-
14
- ### Fixed
15
- - **CORS on error responses:** las respuestas del `ErrorHandler` (401, 422, 500, `application/problem+json`, etc.) incluyen `Access-Control-Allow-Origin` y el resto de cabeceras CORS configuradas, alineadas con respuestas OK (`veloce:corsHeaders` + `mergeVeloceCorsHeaders`). Export público: `mergeVeloceCorsHeaders`, `VELOCE_CORS_HEADERS_KEY`, `VeloceCorsHeadersSnapshot`.
16
-
17
- ## [0.4.4] - 2026-03-28
18
-
19
- **No usar:** la release en npm llegó sin tarball servible (404). Tras `npm unpublish veloce-ts@0.4.4`, el registry **bloquea** volver a publicar el mismo número. El parche CORS válido está en **0.4.5**.
20
-
21
- ## [0.4.3] - 2026-03-27
22
-
23
- ### Added
24
- - **RFC 9457 (Problem Details):** respuestas de error por defecto con `Content-Type: application/problem+json`, campos `type`, `title`, `status`, `detail`, `instance` y extensiones (`violations`/`details` en validación; `debug` en 500 solo en desarrollo).
25
- - **`VeloceTSConfig.errorResponseFormat`:** `'rfc9457'` (defecto) o `'legacy'` para el JSON `{ error, statusCode, details? }` anterior.
26
- - Helpers exportados: `problemTypeUri`, `resolveProblemType`, `resolveProblemTitle`, `buildProblemInstance`, `toLegacyErrorBody`, `sendErrorResponse`, constantes `PROBLEM_JSON_MEDIA_TYPE`, `DEFAULT_PROBLEM_TYPE_BASE`.
27
- - **`HTTPExceptionOptions`:** `problemType` y `title` opcionales en el constructor de `HTTPException`.
28
-
29
- ### Changed
30
- - Excepciones de auth (`AuthenticationException`, `AuthorizationException`) dejan de definir `toJSON` propio; heredan el formato unificado con URIs `authentication-error` / `authorization-error`.
31
-
32
- ### Documentation
33
- - Cabeceras `@module` en el núcleo (application, metadata, router-compiler, plugin, compiled-metadata), errores, validación, DI, respuestas, logging, middleware, adapters, testing, barrels y más.
34
- - **Benchmarks:** `benchmarks/run.ts` etiquetado como v0.4.3; `BENCHMARKS.md` y `benchmarks/results/latest.json` regenerados (6 000 req, 50 concurrentes, Bun 1.3.5, 2026-03-28).
35
-
36
- ### Notes
37
- - El cuerpo JSON de error sigue incluyendo `error` y `statusCode` junto a los campos RFC 9457. Si tu cliente exige `Content-Type: application/json` en errores, usa `errorResponseFormat: 'legacy'` o acepta `application/problem+json`.
38
-
39
- ## [0.4.2] - 2026-03-27
40
-
41
- ### Fixed
42
- - **HealthCheckPlugin:** checker display names are set with `Object.defineProperty` (with a fallback) so runtimes such as Bun do not throw when assigning `.name` on async checker functions.
43
- - **Public API:** `@Req` is now exported from the main `veloce-ts` entry (it was implemented in `decorators/params` but missing from the package exports).
44
-
45
- ## [0.4.1] - 2026-03-27
46
-
47
- ### Fixed
48
- - `include()` in `VeloceTS` application no longer drops decorator-set route fields (e.g. `statusCode` from `@HttpCode`, `responseSchema` from `@ResponseSchema`) when registering controller routes.
49
-
50
- ### Added
51
- - New test suite: `tests/routing.test.ts`, `tests/validation.test.ts`, `tests/errors.test.ts`, `tests/di.test.ts` 53 integration tests covering functional API, decorator routing, body/query validation, HTTP exceptions, and DI container.
52
- - Console-based fallback logger: if `pino` is not installed, the framework now falls back silently to a `console`-based logger instead of crashing at startup.
53
-
54
- ### Changed
55
- - `pino`, `pino-pretty`, and `ioredis` moved from `dependencies` to `optionalDependencies`. They are no longer installed automatically, reducing the default install footprint by ~7 MB. Install them explicitly if needed (`bun add pino pino-pretty` / `bun add ioredis`).
56
- - `winston` removed from `dependencies` entirely (it was listed but never used by the framework).
57
- - `@types/ioredis` and `@types/pino` removed from `devDependencies` (no longer needed).
58
- - Build threshold in `build.ts` updated from 100 KB to 600 KB to reflect the full framework scope.
59
- - Core bundle reduced from 444 KB to 408 KB (minified ESM).
60
-
61
- ### Deprecated
62
- - `FastAPITS` export: use `VeloceTS` or the shorter `Veloce` alias instead. `FastAPITS` will be removed in v1.0.0.
63
-
64
- ## [0.4.0] - 2026-03-27
65
-
66
- Esta versión representa la mayor actualización desde el lanzamiento inicial. Se añadieron más de 25 mejoras nuevas distribuidas en tres oleadas de trabajo (alta, media y baja prioridad), cubriendo la cadena completa desde la generación de rutas hasta la documentación OpenAPI, el testing, el ORM y la CLI.
67
-
68
- ### 🚀 Nuevos Decoradores
69
-
70
- #### Documentación OpenAPI (shorthand)
71
- Cinco decoradores de una sola línea como alternativa concisa a `@ApiDoc({...})`:
72
- - **`@Summary(text)`** descripción corta visible en la lista de Swagger UI
73
- - **`@Description(text)`** texto largo en el panel de detalle de la operación
74
- - **`@Tag(name)`** — asigna un tag individual; apilable con múltiples `@Tag`
75
- - **`@Tags(...names)`** — asigna varios tags en un solo decorador
76
- - **`@Deprecated()`** marca la ruta como obsoleta (tachado en Swagger UI)
77
-
78
- #### Control de respuesta
79
- - **`@HttpCode(statusCode)`** — sobreescribe el código HTTP de respuesta del handler (p.ej. `201` para creación). Usado también por el generador OpenAPI para el código de éxito documentado
80
- - **`@ResponseSchema(schema, statusCode?)`** valida y sanitiza la respuesta del handler con un esquema Zod; informa el modelo de respuesta al spec de OpenAPI
81
-
82
- #### Middleware declarativo por ruta
83
- - **`@Timeout(ms, message?)`** — aborta la petición con **408 Request Timeout** si el handler supera el límite. Inyecta automáticamente el middleware al inicio del pipeline y emite el header `X-Timeout-Ms`
84
- - **`@RateLimit(options)`** aplica rate-limiting a nivel de ruta individual usando la misma configuración de `createRateLimitMiddleware()`. Los headers estándar `X-RateLimit-*` se envían automáticamente
85
-
86
- ### 🛠️ Mejoras al Framework Core
87
-
88
- #### OpenAPI Generator (`src/docs/openapi-generator.ts`)
89
- - **Auto-tagging**: deriva tags automáticamente del primer segmento del path (`/products/:id` tag `"Products"`) sin necesidad de anotarlos manualmente
90
- - **Bearer security scheme**: añade `components.securitySchemes.bearerAuth` al spec y aplica `security: [{ bearerAuth: [] }]` en rutas protegidas de forma automática
91
- - **401 automático**: rutas protegidas reciben una respuesta `401 Unauthorized` documentada sin configuración adicional
92
- - **Soporte de `@HttpCode`**: usa el `statusCode` del decorador como clave del bloque de éxito en `responses`
93
- - **`@ResponseSchema` en el spec**: cuando está presente, el esquema Zod se convierte al formato JSON Schema para el bloque de contenido de la respuesta
94
-
95
- #### Sistema de Excepciones HTTP (`src/errors/exceptions.ts`)
96
- Seis nuevas clases de excepción para cubrir casos de error comunes:
97
- - `ConflictException` (409)
98
- - `GoneException` (410)
99
- - `PayloadTooLargeException` (413)
100
- - `UnprocessableEntityException` (422)
101
- - `TooManyRequestsException` (429)
102
- - `ServiceUnavailableException` (503)
103
-
104
- #### Logger estructurado en ErrorHandler (`src/errors/handler.ts`)
105
- - Errores 5xx se registran con `getLogger().error` incluyendo path, método, status y stack
106
- - Errores 4xx se registran como `warn` en entorno de desarrollo
107
- - Errores genéricos no capturados también pasan por Pino
108
-
109
- #### Arreglos de orden de decoradores
110
- - **`@UseMiddleware`** (`src/decorators/middleware.ts`): ahora siempre llama a `MetadataRegistry.defineRoute` para que el middleware no se pierda independientemente del orden de ejecución de los decoradores
111
- - **`@Cache` / `@CacheInvalidate`** (`src/decorators/cache.ts`): mismo patrón — los metadatos se fusionan correctamente sin importar el orden de apilamiento
112
-
113
- #### MetadataCompiler — caché lazy con snapshots (`src/core/compiled-metadata.ts`)
114
- - Compilación lazy: una ruta sólo se recompila si sus metadatos cambiaron (comparación por snapshot JSON)
115
- - IDs únicos para handlers funcionales vía `WeakMap<Function, number>` — evita colisiones de caché cuando distintas instancias de app registran el mismo path con handlers diferentes (bug crítico en tests paralelos)
116
- - Método `clearCache()` expuesto para limpiar el estado entre tests
117
-
118
- ### 🧪 TestClient API fluida y helpers de autenticación (`src/testing/test-client.ts`)
119
-
120
- Reescritura completa de `TestClient`:
121
- - **`TestResponse`** nueva clase de respuesta con propiedades `status`, `headers`, `body`, `text`, `ok` y métodos de aserción encadenables:
122
- - `expectStatus(code)`, `expectOk()`, `expectCreated()`, `expectNotFound()`, etc.
123
- - `expectJson(partialObject)` comprobación parcial del body
124
- - `expectField(field, value?)` verificar un campo específico
125
- - `expectHeader(name, value?)`verificar un header de respuesta
126
- - `expectArrayLength(n)` — verificar longitud de array en respuesta
127
- - **`withToken(token)`**crea una instancia inmutable del cliente con el header `Authorization: Bearer` ya configurado
128
- - **`withHeaders(headers)`** crea una instancia inmutable con headers adicionales
129
- - **`loginAs(credentials, endpoint?)`**hace login, extrae el JWT y lo inyecta en el cliente actual para las peticiones siguientes
130
- - **`registerAndLogin(user, endpoints?)`** registra y hace login en una sola llamada
131
- - **`clearAuth()`** — limpia el token almacenado
132
-
133
- ### 🔌 Plugins y Middleware
134
-
135
- #### HealthCheckers.disk (`src/plugins/health.ts`)
136
- - Usa `fs.statfs` (Node 18+ / Bun) para obtener métricas reales de disco: total, libre, usado y porcentaje
137
- - Degradación elegante a `"healthy"` en plataformas sin soporte
138
-
139
- #### CLIPlantilla Fullstack corregida (`src/cli/commands/new.ts`)
140
- - La plantilla `fullstack` ahora genera `src/index.ts` con `GraphQLPlugin` y `WebSocketPlugin` correctamente importados e instanciados (antes quedaban comentados)
141
-
142
- #### Subpath exports en el build (`build.ts`)
143
- - Se añadieron `./src/auth/index.ts`, `./src/adapters/base.ts`, `./src/adapters/hono.ts`, `./src/adapters/express.ts` como entrypoints explícitos para que los imports `veloce-ts/auth` y `veloce-ts/adapters/*` funcionen correctamente
144
-
145
- ### 🗄️ Drizzle ORM Integración DI (`src/dependencies/drizzle.ts`)
146
-
147
- Nuevo módulo para conectar Drizzle (u otro ORM) al contenedor de inyección de dependencias:
148
- ```typescript
149
- // Registrar la instancia de la DB
150
- registerDrizzle(app, db);
151
-
152
- // Inyectar en controladores
153
- @Get('/')
154
- async list(@InjectDB() db: DrizzleDB) { }
155
- ```
156
- - `DB_TOKEN` símbolo por defecto para el token de inyección
157
- - `registerDrizzle(app, db, token?)` registra como singleton en el `DIContainer`
158
- - `@InjectDB(token?)` — decorador de parámetro, alias de `@Depends(DB_TOKEN)`
159
-
160
- ### 📊 Paginación mejorada (`src/orm/pagination.ts`)
161
-
162
- #### Enriquecimiento de metadatos
163
- - `PaginationMeta` incluye `from` y `to` (rango 1-based, p.ej. `from: 11, to: 20`)
164
- - `CursorPaginatedResult` incluye `count` (ítems reales devueltos en la página)
165
-
166
- #### Cursor pagination más precisa
167
- - `createCursorPaginatedResult(data, limit, cursorField, hadPrevCursor)` — el nuevo parámetro `hadPrevCursor` activa `hasPrev: true` correctamente cuando se navega hacia adelante con cursor
168
- - `createMultiCursor(entity, fields[])` crea cursores compuestos por múltiples campos para ordenación estable (p.ej. `{ createdAt, id }`)
169
- - `decodeMultiCursor(cursor)` — decodifica un cursor multi-campo de vuelta a un objeto
170
-
171
- #### Helpers standalone
172
- - `paginate<T>(data, total, page, limit)` — construye `{ data, meta }` en una sola llamada, sin necesidad de instanciar `PaginationHelper`
173
- - `parseCursorQuery(query, defaultLimit?, maxLimit?)` — extrae `cursor` y `limit` de los query params sin lanzar excepciones
174
- - `PaginationHelper.parsePaginationQuery(query, defaultLimit?, maxLimit?)` — equivalente para paginación offset; aplica límite máximo y usa defaults cuando los valores son inválidos
175
-
176
- ### 🔌 Express Adapter — Compatibilidad ESM (`src/adapters/express.ts`)
177
-
178
- Reescritura completa del adaptador:
179
- - Carga Express de forma lazy y segura usando `Function('return require')()` para compatibilidad ESM sin necesitar `declare const require: any`
180
- - Acepta una instancia de Express pre-creada como segundo argumento del constructor (para añadir middleware propio antes del bridge)
181
- - Manejo correcto de body raw (`Buffer`) vs body parseado (JSON/urlencoded)
182
- - Omite el header `transfer-encoding` al reenviar respuestas (era fuente de errores en Express)
183
- - Delega errores inesperados al pipeline de error de Express mediante `next(err)` en lugar de responder con 500 directamente
184
-
185
- ### 🐛 Bug Fixes
186
-
187
- - **`ZodError` cross-module** (`src/errors/handler.ts`, `src/validation/validator.ts`): `instanceof ZodError` fallaba cuando la app consumidora tenía una instancia de Zod diferente a la del framework (caso frecuente con `bun link`). Añadido fallback `error.name === 'ZodError'` para garantizar respuestas 422 en todos los casos
188
- - **Rutas `GET` marcadas públicas retornaban 401** en `products-api`: `app.use()` aplicaba el middleware a todos los métodos; corregido usando `app.on(['POST', 'PUT', 'DELETE'], path, middleware)` para restringir sólo a métodos de escritura
189
- - **Cache collision en MetadataCompiler**: handlers funcionales distintos con el mismo path en diferentes instancias de app compartían el resultado compilado incorrecto; solucionado con IDs únicos por función
190
- - **`@Cache` / `@UseMiddleware` perdían metadatos**: cuando se apilaban en orden inverso al de ejecución de decoradores, los metadatos podían sobreescribirse; solucionado actualizando el registro explícitamente en cada decorador
191
-
192
- ### 📋 Mensajes de validación mejorados (`src/validation/exceptions.ts`)
193
-
194
- La respuesta de error `422` ahora incluye información estructurada adicional:
195
- - `field` en formato convencional: `items[0].price` en lugar de `items.0.price`
196
- - `received` tipo recibido (cuando Zod lo reporta)
197
- - `expected` tipo esperado (cuando aplica)
198
- - `minimum` / `maximum` — límites numéricos en errores de rango
199
-
200
- ```json
201
- {
202
- "error": "Validation Error",
203
- "statusCode": 422,
204
- "details": [
205
- { "field": "email", "message": "Invalid email", "code": "invalid_string" },
206
- { "field": "age", "message": "Number must be ≥ 18", "code": "too_small", "minimum": 18 },
207
- { "field": "tags[1]", "message": "String must not be empty", "code": "too_small" }
208
- ]
209
- }
210
- ```
211
-
212
- ### 💥 Breaking Changes
213
-
214
- Ninguno — todos los cambios son retrocompatibles. Las firmas de `createCursorPaginatedResult` tienen un nuevo parámetro opcional `hadPrevCursor` (cuarto argumento, `false` por defecto).
215
-
216
- ### 📦 Dependencias
217
-
218
- Sin cambios en dependencias de runtime. Express sigue siendo peer dependency opcional.
219
-
220
- ---
221
-
222
- ## [0.3.3] - 2025-10-31
223
-
224
- ### 🐛 Critical Bug Fixes
225
- - **JSON Response Serialization**: Fixed critical bug where JSON responses were not being serialized correctly
226
- - **CLI Version Resolution**: Confirmed CLI correctly fetches and uses latest npm version (0.3.2)
227
- - **Application Compilation**: Fixed missing `await app.compile()` call in generated templates
228
-
229
- ### 🔧 CLI Improvements
230
- - **Version Fetching**: CLI now correctly fetches latest version from npm registry
231
- - **Template Generation**: All templates now include proper `await app.compile()` call
232
- - **Error Handling**: Improved error handling in CLI operations
233
-
234
- ## [0.3.2] - 2025-10-31
235
-
236
- ## [0.3.1] - 2025-10-31
237
-
238
- ### 🛠️ CLI Improvements
239
-
240
- #### Enhanced Project Generation
241
- - **Latest Version Fetching**: CLI now automatically fetches the latest VeloceTS version from npm registry
242
- - **Improved Error Handling**: Better error messages and cleanup on project creation failure
243
- - **Type Safety**: Fixed TypeScript errors in CLI with proper type definitions for npm registry API
244
- - **Better User Experience**: Enhanced progress messages and visual feedback during project creation
245
- - **Robust Fallbacks**: Multiple fallback strategies for version detection when npm is unavailable
246
-
247
- #### Fixed Issues
248
- - **npm Registry Integration**: Fixed CLI to use correct npm registry endpoint (`/veloce-ts` instead of `/veloce-ts/latest`)
249
- - **Type Definitions**: Added proper TypeScript interfaces for npm registry response structure
250
- - **Version Resolution**: Improved version parsing with proper type checking and validation
251
- - **Package.json Generation**: Now uses specific dependency versions instead of 'latest' for better stability
252
- - **Template Compilation**: All generated templates now include mandatory `await app.compile()` call
253
-
254
- #### Technical Improvements
255
- - **NpmRegistryResponse Interface**: Added proper typing for npm registry API responses
256
- - **Async Error Handling**: Better error handling in async CLI operations
257
- - **Dependency Versions**: Updated to use specific versions for better reproducibility:
258
- - `hono: ^4.0.0` (instead of 'latest')
259
- - `reflect-metadata: ^0.2.0` (instead of 'latest')
260
- - `zod: ^3.22.0` (instead of 'latest')
261
- - `typescript: ^5.3.0` (instead of 'latest')
262
- - **Engine Requirements**: Added Node.js and Bun version requirements to generated package.json
263
-
264
- #### Developer Experience
265
- - **Progress Indicators**: Added emoji-based progress indicators for better visual feedback
266
- - **Cleanup on Failure**: Automatic cleanup of partial projects when creation fails
267
- - **Validation**: Better project name validation and error messages
268
- - **Documentation**: Generated projects include comprehensive setup instructions
269
-
270
- ### 🐛 Bug Fixes
271
- - **CLI TypeScript Errors**: Fixed 'data is of type unknown' error in npm registry API calls
272
- - **Template Generation**: Fixed missing `await app.compile()` in all CLI templates
273
- - **Dependency Management**: Improved dependency version resolution and fallback handling
274
-
275
- ### 📦 Migration Guide
276
-
277
- #### For CLI Users
278
- No breaking changes. Existing projects will continue to work. New projects generated with `veloce-ts new` will:
279
- - Use the latest VeloceTS version automatically
280
- - Include proper `await app.compile()` calls
281
- - Have more stable dependency versions
282
-
283
- #### For Framework Users
284
- No changes required. This release only improves the CLI experience.
285
-
286
- ## [0.3.0] - 2025-10-29
287
-
288
- ### 🚀 Major Features Added
289
-
290
- #### Response Caching System
291
- - **In-Memory Cache Store**: Fast LRU-based caching with automatic cleanup
292
- - **Redis Cache Store**: Distributed caching support for multi-instance deployments
293
- - **@Cache() Decorator**: Declarative response caching with flexible TTL configuration
294
- - **@CacheInvalidate() Decorator**: Pattern-based cache invalidation for mutations
295
- - **Cache Middleware**: Functional API support for route-level caching
296
- - **TTL Support**: Flexible time-to-live with string format ('5m', '1h', '1d') or seconds
297
- - **Pattern Invalidation**: Wildcard pattern matching for cache invalidation ('products:*')
298
- - **Cache Keys**: Smart key generation with placeholder support ('product:{id}')
299
- - **Cache Headers**: Automatic X-Cache headers (HIT/MISS) in responses
300
-
301
- #### Enhanced Request Context
302
- - **Automatic Request IDs**: UUID generation for every request
303
- - **@RequestId() Decorator**: Inject request ID into controller methods
304
- - **@AbortSignal() Decorator**: Request cancellation support for long-running operations
305
- - **Request Timeouts**: Configurable timeouts per route or globally
306
- - **Logging Integration**: Request ID automatically propagates through all logs
307
- - **Response Headers**: X-Request-ID header in all responses
308
- - **Metadata Storage**: Attach custom data to request context
309
- - **Request Lifecycle**: Automatic logging of request start/end with duration
310
-
311
- #### Logging Improvements
312
- - **Request Context Integration**: Automatic request ID in all log entries
313
- - **Child Loggers**: Enhanced contextual logging with inheritance
314
- - **Structured Logging**: JSON-formatted logs for production
315
- - **Pretty Printing**: Human-readable logs for development
316
- - **Log Middleware**: Request lifecycle logging with configurable headers
317
-
318
- ### 🎯 New Decorators
319
-
320
- - **@Cache(options)**: Cache route responses with TTL and key configuration
321
- - **@CacheInvalidate(pattern)**: Invalidate cache entries matching patterns
322
- - **@RequestId()**: Inject unique request ID into handler parameters
323
- - **@AbortSignal()**: Inject AbortSignal for request cancellation
324
-
325
- ### 🔧 New Middleware
326
-
327
- - **createRequestContextMiddleware()**: Initialize request context with ID, timeout, and logging
328
- - **createSimpleRequestIdMiddleware()**: Minimal request ID middleware
329
- - **createCacheMiddleware()**: Functional API route caching
330
- - **createCacheInvalidationMiddleware()**: Functional API cache invalidation
331
-
332
- ### 📦 New Modules
333
-
334
- - **src/cache/**: Complete caching system
335
- - `types.ts`: Cache interfaces and types
336
- - `memory-store.ts`: In-memory LRU cache implementation
337
- - `redis-store.ts`: Redis backend for distributed caching
338
- - `manager.ts`: Global cache management and utilities
339
- - **src/context/**: Enhanced request context
340
- - `request-context.ts`: Request tracking with UUID and AbortSignal
341
- - **src/middleware/**: New middleware
342
- - `request-context.ts`: Request context initialization
343
- - `cache.ts`: Cache middleware for functional API
344
- - **src/decorators/**: New decorators
345
- - `cache.ts`: @Cache and @CacheInvalidate decorators
346
-
347
- ### 🛠️ Core Improvements
348
-
349
- - **Router Compiler**: Integrated cache checking and invalidation in route handlers
350
- - **Type System**: New parameter types for request-id and abort-signal
351
- - **Export System**: All new decorators and middleware properly exported
352
- - **Error Handling**: Improved error handling with request ID context
353
-
354
- ### 📚 Documentation
355
-
356
- #### New Guides (English + Spanish)
357
- - **Caching Guide**: Complete guide to response caching (15,000 words total)
358
- - In-memory and Redis stores
359
- - Decorators and middleware
360
- - TTL configuration
361
- - Cache invalidation strategies
362
- - Best practices with 50+ code examples
363
- - **Request Context Guide**: Request tracking and management (12,000 words total)
364
- - Automatic UUID generation
365
- - Request cancellation with AbortSignal
366
- - Timeout configuration
367
- - Logging integration
368
- - 40+ code examples
369
- - **Logging Guide**: Structured logging with Pino (4,000 words total)
370
- - Logger configuration
371
- - Child loggers
372
- - Request ID integration
373
- - Best practices
374
-
375
- #### Documentation Coverage
376
- - Added 31,000+ words of professional documentation
377
- - 100+ new code examples
378
- - Bilingual support (English and Spanish)
379
- - SEO-optimized with meta descriptions
380
- - Cross-referenced between guides
381
-
382
- ### 🌐 Sidebar Updates
383
-
384
- Updated Starlight documentation sidebar with new guides:
385
- - Caching
386
- - Request Context
387
- - Logging
388
-
389
- ### Performance Improvements
390
-
391
- - **Cache System**: Sub-millisecond cache hits with in-memory store
392
- - **LRU Eviction**: Automatic memory management in cache store
393
- - **Request Context**: Minimal overhead UUID generation
394
- - **Logging**: Efficient structured logging with Pino
395
-
396
- ### 🔄 API Additions
397
-
398
- #### Cache Manager
399
- ```typescript
400
- - CacheManager.setDefaultStore(store)
401
- - CacheManager.getDefaultStore()
402
- - CacheManager.generateKey(method, path, params, query, options)
403
- - CacheManager.get(key, store?)
404
- - CacheManager.set(key, value, ttl?, store?)
405
- - CacheManager.delete(key, store?)
406
- - CacheManager.invalidate(pattern, store?)
407
- - CacheManager.clear(store?)
408
- ```
409
-
410
- #### Helper Functions
411
- ```typescript
412
- - getCache<T>(key): Promise<T | null>
413
- - setCache<T>(key, value, ttl?): Promise<void>
414
- - deleteCache(key): Promise<boolean>
415
- - invalidateCache(pattern): Promise<number>
416
- - clearCache(): Promise<void>
417
- - getRequestId(context): string | null
418
- - getAbortSignal(context): AbortSignal | null
419
- - setRequestMetadata(context, key, value): void
420
- - getRequestMetadata(context, key): any
421
- - generateRequestId(): string
422
- ```
423
-
424
- ### 🐛 Bug Fixes
425
-
426
- - **ORM Exports**: Fixed DrizzleTransactionManager import path
427
- - **Middleware Exports**: Added missing createCacheInvalidationMiddleware export
428
- - **Request Context**: Fixed AbortController reference in context
429
-
430
- ### 💥 Breaking Changes
431
-
432
- None - All changes are additive and backward compatible
433
-
434
- ### 📦 Dependencies
435
-
436
- No new runtime dependencies added. Caching works with existing dependencies:
437
- - In-memory cache: No dependencies (built-in)
438
- - Redis cache: Requires `redis` or `ioredis` (peer dependency)
439
-
440
- ### 🎯 Migration Guide
441
-
442
- #### Adding Cache to Existing Routes
443
-
444
- ```typescript
445
- // Before
446
- @Get('/products')
447
- async getProducts() {
448
- return await db.products.findAll();
449
- }
450
-
451
- // After - Add caching
452
- @Get('/products')
453
- @Cache({ ttl: '5m', key: 'products:list' })
454
- async getProducts() {
455
- return await db.products.findAll();
456
- }
457
- ```
458
-
459
- #### Adding Request Tracking
460
-
461
- ```typescript
462
- // Add to app initialization
463
- import { createRequestContextMiddleware } from 'veloce-ts';
464
-
465
- app.use(createRequestContextMiddleware({
466
- timeout: 30000,
467
- logging: true
468
- }));
469
-
470
- // Use in controllers
471
- @Get('/data')
472
- async getData(@RequestId() requestId: string) {
473
- logger.info({ requestId }, 'Processing request');
474
- return data;
475
- }
476
- ```
477
-
478
- ### 📊 Statistics
479
-
480
- - **New Files**: 15+ new source files
481
- - **Documentation**: 31,000+ words
482
- - **Code Examples**: 100+ examples
483
- - **Test Coverage**: All new features covered
484
- - **Languages**: Full bilingual support (EN/ES)
485
-
486
- ### 🙏 Acknowledgments
487
-
488
- This release brings powerful performance optimization features to Veloce-TS:
489
- - Response caching reduces database load and improves response times
490
- - Request tracking enables better debugging and monitoring
491
- - Enhanced logging provides better observability in production
492
-
493
- ## [0.2.6] - 2025-10-15
494
-
495
- ### Fixed
496
- - **Query Export**: Added missing `Query` export from main index to resolve import conflicts
497
- - **Parameter Decorators**: HTTP `@Query` decorator now properly exported alongside GraphQL decorators
498
- - **Import Resolution**: Fixed "Export named 'Query' not found" error in applications
499
-
500
- ## [0.2.5] - 2025-10-15
501
-
502
- ### Fixed
503
- - **GraphQL Query Conflict**: Removed conflicting alias `Query` from GraphQL decorators
504
- - **Import Resolution**: GraphQL decorators now use `GQLQuery` to avoid conflicts with HTTP `@Query` decorator
505
- - **Type Safety**: Eliminated TypeScript errors caused by decorator name conflicts
506
-
507
- ### Breaking Changes
508
- - GraphQL queries now use `@GQLQuery` instead of `@Query` to avoid conflicts with HTTP parameter decorator
509
-
510
- ## [0.2.4] - 2025-10-15
511
-
512
- ### Fixed
513
- - **Query Decorator**: Fixed `@Query` decorator to properly handle parameters without schemas
514
- - **Query Parameter Extraction**: Improved query parameter handling in router compiler
515
- - **Validation**: Added proper validation for query parameters with optional Zod schemas
516
- - **Error Handling**: Fixed missing `ValidationError` import, now using `BadRequestException`
517
-
518
- ### Improved
519
- - **Query Decorator Flexibility**: `@Query` now supports multiple usage patterns:
520
- - `@Query()` - Extract all query parameters
521
- - `@Query('param')` - Extract specific parameter
522
- - `@Query(Schema)` - Validate with Zod schema
523
- - **Router Compiler**: Enhanced parameter extraction and validation logic
524
- - **Type Safety**: Better TypeScript support for query parameter handling
525
-
526
- ### Breaking Changes
527
- - None
528
-
529
- ## [0.2.3] - 2025-10-14
530
-
531
- ### Fixed
532
- - **WebSocket Exports**: Fixed missing `WebSocket` decorator export from WebSocket module
533
- - **Import Resolution**: WebSocket decorators now properly exported from `veloce-ts/websocket`
534
-
535
- ## [0.2.2] - 2025-10-14
536
-
537
- ### Fixed
538
- - **GraphQL Decorators**: Added missing `Query`, `Mutation`, and `Subscription` aliases for GraphQL decorators
539
- - **Import Conflicts**: Fixed naming conflicts between params and GraphQL decorators
540
- - **CLI Templates**: Fixed import errors in CLI template generation
541
- - **Package Version**: CLI now uses current package version when generating new projects
542
-
543
- ### Changed
544
- - **GraphQL Exports**: GraphQL decorators now available with intuitive names (`Query`, `Mutation`, `Subscription`)
545
- - **Import Resolution**: Cleaner import structure to avoid naming conflicts
546
-
547
- ## [0.2.1] - 2025-10-14
548
-
549
- ### Fixed
550
- - **GraphQL Exports**: Fixed missing `Arg` decorator export from GraphQL module
551
- - **Import Resolution**: GraphQL decorators now properly exported from `veloce-ts/graphql`
552
- - **Type Definitions**: GraphQL decorators included in TypeScript declarations
553
-
554
- ## [0.2.0] - 2025-10-14
555
-
556
- ### 🚀 Major Features Added
557
- - **Complete Authentication System**: JWT-based authentication with access/refresh tokens
558
- - **Role-Based Access Control (RBAC)**: Hierarchical roles with granular permissions system
559
- - **SQLite Integration**: Built-in SQLite support with Bun's native database
560
- - **Real-time WebSocket Support**: Enhanced WebSocket handling with decorators
561
- - **GraphQL Integration**: Complete GraphQL support with resolvers and subscriptions
562
- - **Advanced Middleware System**: Custom middleware with request/response interceptors
563
- - **Admin Panel Features**: Comprehensive admin endpoints for user and system management
564
-
565
- ### 🎯 New Decorators & Features
566
- - **@Auth**: JWT authentication decorator with automatic user injection
567
- - **@CurrentUser**: Inject current authenticated user into handlers
568
- - **@MinimumRole**: Role-based endpoint protection
569
- - **@Permissions**: Granular permission-based access control
570
- - **@WebSocket**: Enhanced WebSocket decorators with connection management
571
- - **@Resolver**: GraphQL resolver decorators for queries and mutations
572
- - **@OnConnect/@OnMessage/@OnDisconnect**: WebSocket lifecycle decorators
573
-
574
- ### 🔧 Core Framework Improvements
575
- - **Router Compiler Fixes**: Fixed critical bugs with sparse array handling in metadata
576
- - **Dependency Injection**: Enhanced DI system with better error handling
577
- - **Parameter Resolution**: Improved parameter and dependency resolution
578
- - **Type Safety**: Enhanced TypeScript inference and type checking
579
- - **Error Handling**: Better error messages and debugging capabilities
580
-
581
- ### 📚 Documentation & Examples
582
- - **Veloce TaskMaster**: Complete real-world example with authentication, RBAC, and frontend
583
- - **Comprehensive Examples**: Task management system showcasing all framework features
584
- - **Migration Guides**: Documentation for migrating from Express.js and other frameworks
585
- - **API Documentation**: Enhanced OpenAPI/Swagger documentation generation
586
-
587
- ### 🛠️ Technical Improvements
588
- - **Performance**: Optimized router compilation and metadata handling
589
- - **Memory Management**: Better handling of metadata arrays and object references
590
- - **Bundle Size**: Reduced framework bundle size through optimizations
591
- - **Build System**: Improved TypeScript compilation and type generation
592
- - **Testing**: Enhanced testing utilities and error reporting
593
-
594
- ### 🔒 Security Enhancements
595
- - **JWT Security**: Secure token generation and validation
596
- - **Password Hashing**: Built-in password hashing utilities
597
- - **CSRF Protection**: Enhanced CORS and security middleware
598
- - **Input Validation**: Improved Zod schema validation
599
- - **Role Hierarchy**: Configurable role hierarchy with permission inheritance
600
-
601
- ### 🎨 Developer Experience
602
- - **Better Error Messages**: More descriptive error messages with stack traces
603
- - **Hot Reload**: Improved development server with better file watching
604
- - **TypeScript Support**: Enhanced type inference and IntelliSense
605
- - **Debugging**: Better debugging capabilities with request tracing
606
- - **CLI Improvements**: Enhanced CLI with better project scaffolding
607
-
608
- ### 🐛 Critical Bug Fixes
609
- - **Router Compilation**: Fixed sparse array handling in parameter metadata
610
- - **Dependency Resolution**: Fixed undefined dependency handling
611
- - **Array Length Errors**: Fixed array creation with invalid indices
612
- - **Import Path Issues**: Corrected all import paths in generated projects
613
- - **Metadata Processing**: Fixed metadata compilation edge cases
614
-
615
- ### 📦 New Dependencies
616
- - **jsonwebtoken**: JWT token generation and validation
617
- - **reflect-metadata**: Enhanced reflection capabilities for decorators
618
- - **zod-to-json-schema**: Improved OpenAPI schema generation
619
-
620
- ## [0.1.7] - 2025-10-12
621
-
622
- ### Fixed
623
- - Fixed syntax error in CLI new command that prevented build from completing
624
- - Fixed README generation in CLI templates
625
-
626
- ## [0.1.6] - 2025-10-12
627
-
628
- ### Added
629
- - **Landing Page**: Created modern Astro-based website with interactive terminal and file explorer
630
- - **Interactive Terminal**: Built terminal component for API testing with command history
631
- - **File Explorer**: Developed code browser with hierarchical navigation for demo app
632
- - **Documentation Files**: CLI now generates README.md and API_DOCUMENTATION.md in new projects
633
-
634
- ### Changed
635
- - **Complete Rebranding**: Renamed framework from FastAPI-TS to Veloce-TS throughout codebase
636
- - **OpenAPIPlugin**: Now serves Swagger UI directly from code (no need for static HTML files)
637
- - **Improved Swagger UI**: Updated to version 5.9.0 with better styling and functionality
638
- - **Simplified Templates**: `veloce-ts new` command no longer generates unnecessary public files
639
- - **Better Defaults**: OpenAPI documentation now uses "Veloce-TS" branding by default
640
- - **Updated URLs**: All references now point to correct GitHub repository and documentation
641
-
642
- ### Fixed
643
- - Fixed Swagger UI rendering issues with proper script loading
644
- - Fixed OpenAPI plugin to correctly serve HTML responses and return proper content types
645
- - Fixed broken links and outdated branding throughout codebase
646
- - Improved CORS handling in generated templates
647
- - Fixed CLI template generation to include proper documentation structure
648
-
649
- ## [0.1.5] - 2025-10-12
650
-
651
- ### Fixed
652
- - Fixed CLI templates to include OpenAPIPlugin automatically when docs: true
653
- - REST and Fullstack templates now properly initialize OpenAPI documentation
654
-
655
- ## [0.1.4] - 2025-10-13
656
-
657
- ### Fixed
658
- - Fixed CLI templates to call `await app.compile()` before `app.listen()`
659
- - This fixes the 404 error on all routes in generated projects
660
-
661
- ## [0.1.3] - 2025-10-12
662
-
663
- ### Fixed
664
- - Fixed package.json main and exports paths to point to correct dist/*/src/ directories
665
- - This fixes the "Cannot find package" error when importing veloce-ts
666
-
667
- ## [0.1.2] - 2025-10-12
668
-
669
- ### Fixed
670
- - Fixed CLI templates to use correct package name `veloce-ts` instead of `VeloceTS`
671
- - Fixed all import statements in generated projects
672
-
673
- ## [0.1.1] - 2025-10-12
674
-
675
- ### Fixed
676
- - Fixed CLI binary path to use compiled dist files instead of source files
677
-
678
- ## [0.1.0] - 2025-10-12
679
-
680
- ### Added
681
- - Initial release of veloce-ts framework
682
- - Decorator-based routing with @Controller, @Get, @Post, @Put, @Delete, @Patch
683
- - Functional API for decorator-free routing
684
- - Automatic request validation with Zod schemas
685
- - Dependency injection system with singleton, request, and transient scopes
686
- - Automatic OpenAPI documentation generation
687
- - Response handling with JSONResponse, HTMLResponse, FileResponse, StreamResponse, RedirectResponse
688
- - Plugin system for extensibility
689
- - WebSocket support with decorators
690
- - GraphQL support with decorators
691
- - CLI tool for project scaffolding and development
692
- - Middleware system with CORS, rate limiting, and compression
693
- - Error handling with custom exceptions
694
- - Testing utilities with TestClient
695
- - Multi-runtime support (Bun, Node.js, Deno, Cloudflare Workers)
696
- - Adapter system for Express and Hono
697
- - Type safety with full TypeScript support
698
- - Performance optimizations with metadata compilation and schema caching
699
-
700
- ## [0.1.0] - 2025-10-12
701
-
702
- ### Added
703
- - Initial development version
704
- - Core framework architecture
705
- - Basic routing and validation
706
- - Documentation generation
707
- - Plugin system
708
- - WebSocket and GraphQL support
709
- - CLI tooling
710
- - Testing utilities
711
-
712
- [Unreleased]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.4.0...HEAD
713
- [0.4.0]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.3.3...v0.4.0
714
- [0.3.3]: https://github.com/AlfredoMejia3001/veloce-ts/releases/tag/v0.3.3
715
- [0.3.2]: https://github.com/AlfredoMejia3001/veloce-ts/releases/tag/v0.3.2
716
- [0.3.1]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.3.0...v0.3.1
717
- [0.2.2]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.2.1...v0.2.2
718
- [0.2.1]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.2.0...v0.2.1
719
- [0.2.0]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.1.7...v0.2.0
720
- [0.1.7]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.1.6...v0.1.7
721
- [0.1.6]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.1.5...v0.1.6
722
- [0.1.5]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.1.4...v0.1.5
723
- [0.1.4]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.1.3...v0.1.4
724
- [0.1.3]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.1.2...v0.1.3
725
- [0.1.2]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.1.1...v0.1.2
726
- [0.1.1]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.1.0...v0.1.1
727
- [0.1.0]: https://github.com/AlfredoMejia3001/veloce-ts/releases/tag/v0.1.0
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [Unreleased]
9
+
10
+ ## [0.4.8] - 2026-05-03
11
+
12
+ ### Fixed
13
+ - **Logger transport eliminado:** se removió el uso de `pino-pretty` como `transport` en el logger de desarrollo. El transport de pino usa `thread-stream` para correr el pretty-printer en un worker thread, lo que causaba un crash al iniciar el servidor con el error `ModuleNotFound resolving "...thread-stream/lib/worker.js"` — el bundle publicado en npm tenía el `__dirname` de la máquina del autor hardcodeado (`C:\Users\alfredo\Desktop\...`). Ahora pino escribe JSON directo a stdout sin workers, eliminando la dependencia de `thread-stream` en runtime.
14
+
15
+ ## [0.4.6] - 2026-04-12
16
+
17
+ ### Fixed
18
+ - **Constructor injection en DIContainer:** `DIContainer.create()` ahora lee los metadatos de dependencias del constructor (`MetadataRegistry.getDependencyMetadata`) y resuelve cada dependencia antes de instanciar la clase. Anteriormente llamaba `new Class()` sin argumentos, causando que decoradores como `@InjectDB()` en parámetros de constructor no tuvieran efecto y las propiedades quedaran como `undefined`.
19
+ - **`@Depends` en parámetros de constructor:** eliminada la restricción que lanzaba error al usar `@Depends` en constructores. Ahora soporta tanto parámetros de método como de constructor.
20
+
21
+ ### Added
22
+ - **`@Inject(Provider, scope?)` decorator:** nuevo decorador para inyección de dependencias en constructores, con scope `'singleton'` por defecto. Alternativa semántica a `@Depends` optimizada para el patrón de constructor injection en controllers y servicios.
23
+
24
+ ## [0.4.5] - 2026-03-29
25
+
26
+ Mismo parche CORS que se intentó en **0.4.4**; npm **no permite republicar** un número de versión tras `npm unpublish` (`E400 Cannot publish over previously published version`).
27
+
28
+ ### Fixed
29
+ - **CORS on error responses:** las respuestas del `ErrorHandler` (401, 422, 500, `application/problem+json`, etc.) incluyen `Access-Control-Allow-Origin` y el resto de cabeceras CORS configuradas, alineadas con respuestas OK (`veloce:corsHeaders` + `mergeVeloceCorsHeaders`). Export público: `mergeVeloceCorsHeaders`, `VELOCE_CORS_HEADERS_KEY`, `VeloceCorsHeadersSnapshot`.
30
+
31
+ ## [0.4.4] - 2026-03-28
32
+
33
+ **No usar:** la release en npm llegó sin tarball servible (404). Tras `npm unpublish veloce-ts@0.4.4`, el registry **bloquea** volver a publicar el mismo número. El parche CORS válido está en **0.4.5**.
34
+
35
+ ## [0.4.3] - 2026-03-27
36
+
37
+ ### Added
38
+ - **RFC 9457 (Problem Details):** respuestas de error por defecto con `Content-Type: application/problem+json`, campos `type`, `title`, `status`, `detail`, `instance` y extensiones (`violations`/`details` en validación; `debug` en 500 solo en desarrollo).
39
+ - **`VeloceTSConfig.errorResponseFormat`:** `'rfc9457'` (defecto) o `'legacy'` para el JSON `{ error, statusCode, details? }` anterior.
40
+ - Helpers exportados: `problemTypeUri`, `resolveProblemType`, `resolveProblemTitle`, `buildProblemInstance`, `toLegacyErrorBody`, `sendErrorResponse`, constantes `PROBLEM_JSON_MEDIA_TYPE`, `DEFAULT_PROBLEM_TYPE_BASE`.
41
+ - **`HTTPExceptionOptions`:** `problemType` y `title` opcionales en el constructor de `HTTPException`.
42
+
43
+ ### Changed
44
+ - Excepciones de auth (`AuthenticationException`, `AuthorizationException`) dejan de definir `toJSON` propio; heredan el formato unificado con URIs `authentication-error` / `authorization-error`.
45
+
46
+ ### Documentation
47
+ - Cabeceras `@module` en el núcleo (application, metadata, router-compiler, plugin, compiled-metadata), errores, validación, DI, respuestas, logging, middleware, adapters, testing, barrels y más.
48
+ - **Benchmarks:** `benchmarks/run.ts` etiquetado como v0.4.3; `BENCHMARKS.md` y `benchmarks/results/latest.json` regenerados (6 000 req, 50 concurrentes, Bun 1.3.5, 2026-03-28).
49
+
50
+ ### Notes
51
+ - El cuerpo JSON de error sigue incluyendo `error` y `statusCode` junto a los campos RFC 9457. Si tu cliente exige `Content-Type: application/json` en errores, usa `errorResponseFormat: 'legacy'` o acepta `application/problem+json`.
52
+
53
+ ## [0.4.2] - 2026-03-27
54
+
55
+ ### Fixed
56
+ - **HealthCheckPlugin:** checker display names are set with `Object.defineProperty` (with a fallback) so runtimes such as Bun do not throw when assigning `.name` on async checker functions.
57
+ - **Public API:** `@Req` is now exported from the main `veloce-ts` entry (it was implemented in `decorators/params` but missing from the package exports).
58
+
59
+ ## [0.4.1] - 2026-03-27
60
+
61
+ ### Fixed
62
+ - `include()` in `VeloceTS` application no longer drops decorator-set route fields (e.g. `statusCode` from `@HttpCode`, `responseSchema` from `@ResponseSchema`) when registering controller routes.
63
+
64
+ ### Added
65
+ - New test suite: `tests/routing.test.ts`, `tests/validation.test.ts`, `tests/errors.test.ts`, `tests/di.test.ts` — 53 integration tests covering functional API, decorator routing, body/query validation, HTTP exceptions, and DI container.
66
+ - Console-based fallback logger: if `pino` is not installed, the framework now falls back silently to a `console`-based logger instead of crashing at startup.
67
+
68
+ ### Changed
69
+ - `pino`, `pino-pretty`, and `ioredis` moved from `dependencies` to `optionalDependencies`. They are no longer installed automatically, reducing the default install footprint by ~7 MB. Install them explicitly if needed (`bun add pino pino-pretty` / `bun add ioredis`).
70
+ - `winston` removed from `dependencies` entirely (it was listed but never used by the framework).
71
+ - `@types/ioredis` and `@types/pino` removed from `devDependencies` (no longer needed).
72
+ - Build threshold in `build.ts` updated from 100 KB to 600 KB to reflect the full framework scope.
73
+ - Core bundle reduced from 444 KB to 408 KB (minified ESM).
74
+
75
+ ### Deprecated
76
+ - `FastAPITS` export: use `VeloceTS` or the shorter `Veloce` alias instead. `FastAPITS` will be removed in v1.0.0.
77
+
78
+ ## [0.4.0] - 2026-03-27
79
+
80
+ Esta versión representa la mayor actualización desde el lanzamiento inicial. Se añadieron más de 25 mejoras nuevas distribuidas en tres oleadas de trabajo (alta, media y baja prioridad), cubriendo la cadena completa desde la generación de rutas hasta la documentación OpenAPI, el testing, el ORM y la CLI.
81
+
82
+ ### 🚀 Nuevos Decoradores
83
+
84
+ #### Documentación OpenAPI (shorthand)
85
+ Cinco decoradores de una sola línea como alternativa concisa a `@ApiDoc({...})`:
86
+ - **`@Summary(text)`** descripción corta visible en la lista de Swagger UI
87
+ - **`@Description(text)`** — texto largo en el panel de detalle de la operación
88
+ - **`@Tag(name)`** asigna un tag individual; apilable con múltiples `@Tag`
89
+ - **`@Tags(...names)`** asigna varios tags en un solo decorador
90
+ - **`@Deprecated()`** marca la ruta como obsoleta (tachado en Swagger UI)
91
+
92
+ #### Control de respuesta
93
+ - **`@HttpCode(statusCode)`** sobreescribe el código HTTP de respuesta del handler (p.ej. `201` para creación). Usado también por el generador OpenAPI para el código de éxito documentado
94
+ - **`@ResponseSchema(schema, statusCode?)`** — valida y sanitiza la respuesta del handler con un esquema Zod; informa el modelo de respuesta al spec de OpenAPI
95
+
96
+ #### Middleware declarativo por ruta
97
+ - **`@Timeout(ms, message?)`** — aborta la petición con **408 Request Timeout** si el handler supera el límite. Inyecta automáticamente el middleware al inicio del pipeline y emite el header `X-Timeout-Ms`
98
+ - **`@RateLimit(options)`** — aplica rate-limiting a nivel de ruta individual usando la misma configuración de `createRateLimitMiddleware()`. Los headers estándar `X-RateLimit-*` se envían automáticamente
99
+
100
+ ### 🛠️ Mejoras al Framework Core
101
+
102
+ #### OpenAPI Generator (`src/docs/openapi-generator.ts`)
103
+ - **Auto-tagging**: deriva tags automáticamente del primer segmento del path (`/products/:id` → tag `"Products"`) sin necesidad de anotarlos manualmente
104
+ - **Bearer security scheme**: añade `components.securitySchemes.bearerAuth` al spec y aplica `security: [{ bearerAuth: [] }]` en rutas protegidas de forma automática
105
+ - **401 automático**: rutas protegidas reciben una respuesta `401 Unauthorized` documentada sin configuración adicional
106
+ - **Soporte de `@HttpCode`**: usa el `statusCode` del decorador como clave del bloque de éxito en `responses`
107
+ - **`@ResponseSchema` en el spec**: cuando está presente, el esquema Zod se convierte al formato JSON Schema para el bloque de contenido de la respuesta
108
+
109
+ #### Sistema de Excepciones HTTP (`src/errors/exceptions.ts`)
110
+ Seis nuevas clases de excepción para cubrir casos de error comunes:
111
+ - `ConflictException` (409)
112
+ - `GoneException` (410)
113
+ - `PayloadTooLargeException` (413)
114
+ - `UnprocessableEntityException` (422)
115
+ - `TooManyRequestsException` (429)
116
+ - `ServiceUnavailableException` (503)
117
+
118
+ #### Logger estructurado en ErrorHandler (`src/errors/handler.ts`)
119
+ - Errores 5xx se registran con `getLogger().error` incluyendo path, método, status y stack
120
+ - Errores 4xx se registran como `warn` en entorno de desarrollo
121
+ - Errores genéricos no capturados también pasan por Pino
122
+
123
+ #### Arreglos de orden de decoradores
124
+ - **`@UseMiddleware`** (`src/decorators/middleware.ts`): ahora siempre llama a `MetadataRegistry.defineRoute` para que el middleware no se pierda independientemente del orden de ejecución de los decoradores
125
+ - **`@Cache` / `@CacheInvalidate`** (`src/decorators/cache.ts`): mismo patrón los metadatos se fusionan correctamente sin importar el orden de apilamiento
126
+
127
+ #### MetadataCompilercaché lazy con snapshots (`src/core/compiled-metadata.ts`)
128
+ - Compilación lazy: una ruta sólo se recompila si sus metadatos cambiaron (comparación por snapshot JSON)
129
+ - IDs únicos para handlers funcionales vía `WeakMap<Function, number>`evita colisiones de caché cuando distintas instancias de app registran el mismo path con handlers diferentes (bug crítico en tests paralelos)
130
+ - Método `clearCache()` expuesto para limpiar el estado entre tests
131
+
132
+ ### 🧪 TestClient — API fluida y helpers de autenticación (`src/testing/test-client.ts`)
133
+
134
+ Reescritura completa de `TestClient`:
135
+ - **`TestResponse`** — nueva clase de respuesta con propiedades `status`, `headers`, `body`, `text`, `ok` y métodos de aserción encadenables:
136
+ - `expectStatus(code)`, `expectOk()`, `expectCreated()`, `expectNotFound()`, etc.
137
+ - `expectJson(partialObject)` comprobación parcial del body
138
+ - `expectField(field, value?)` — verificar un campo específico
139
+ - `expectHeader(name, value?)` verificar un header de respuesta
140
+ - `expectArrayLength(n)` verificar longitud de array en respuesta
141
+ - **`withToken(token)`** — crea una instancia inmutable del cliente con el header `Authorization: Bearer` ya configurado
142
+ - **`withHeaders(headers)`** crea una instancia inmutable con headers adicionales
143
+ - **`loginAs(credentials, endpoint?)`** hace login, extrae el JWT y lo inyecta en el cliente actual para las peticiones siguientes
144
+ - **`registerAndLogin(user, endpoints?)`** — registra y hace login en una sola llamada
145
+ - **`clearAuth()`** limpia el token almacenado
146
+
147
+ ### 🔌 Plugins y Middleware
148
+
149
+ #### HealthCheckers.disk (`src/plugins/health.ts`)
150
+ - Usa `fs.statfs` (Node 18+ / Bun) para obtener métricas reales de disco: total, libre, usado y porcentaje
151
+ - Degradación elegante a `"healthy"` en plataformas sin soporte
152
+
153
+ #### CLI — Plantilla Fullstack corregida (`src/cli/commands/new.ts`)
154
+ - La plantilla `fullstack` ahora genera `src/index.ts` con `GraphQLPlugin` y `WebSocketPlugin` correctamente importados e instanciados (antes quedaban comentados)
155
+
156
+ #### Subpath exports en el build (`build.ts`)
157
+ - Se añadieron `./src/auth/index.ts`, `./src/adapters/base.ts`, `./src/adapters/hono.ts`, `./src/adapters/express.ts` como entrypoints explícitos para que los imports `veloce-ts/auth` y `veloce-ts/adapters/*` funcionen correctamente
158
+
159
+ ### 🗄️ Drizzle ORM — Integración DI (`src/dependencies/drizzle.ts`)
160
+
161
+ Nuevo módulo para conectar Drizzle (u otro ORM) al contenedor de inyección de dependencias:
162
+ ```typescript
163
+ // Registrar la instancia de la DB
164
+ registerDrizzle(app, db);
165
+
166
+ // Inyectar en controladores
167
+ @Get('/')
168
+ async list(@InjectDB() db: DrizzleDB) { }
169
+ ```
170
+ - `DB_TOKEN` — símbolo por defecto para el token de inyección
171
+ - `registerDrizzle(app, db, token?)` — registra como singleton en el `DIContainer`
172
+ - `@InjectDB(token?)` — decorador de parámetro, alias de `@Depends(DB_TOKEN)`
173
+
174
+ ### 📊 Paginación mejorada (`src/orm/pagination.ts`)
175
+
176
+ #### Enriquecimiento de metadatos
177
+ - `PaginationMeta` incluye `from` y `to` (rango 1-based, p.ej. `from: 11, to: 20`)
178
+ - `CursorPaginatedResult` incluye `count` (ítems reales devueltos en la página)
179
+
180
+ #### Cursor pagination más precisa
181
+ - `createCursorPaginatedResult(data, limit, cursorField, hadPrevCursor)` el nuevo parámetro `hadPrevCursor` activa `hasPrev: true` correctamente cuando se navega hacia adelante con cursor
182
+ - `createMultiCursor(entity, fields[])` crea cursores compuestos por múltiples campos para ordenación estable (p.ej. `{ createdAt, id }`)
183
+ - `decodeMultiCursor(cursor)` decodifica un cursor multi-campo de vuelta a un objeto
184
+
185
+ #### Helpers standalone
186
+ - `paginate<T>(data, total, page, limit)` — construye `{ data, meta }` en una sola llamada, sin necesidad de instanciar `PaginationHelper`
187
+ - `parseCursorQuery(query, defaultLimit?, maxLimit?)` extrae `cursor` y `limit` de los query params sin lanzar excepciones
188
+ - `PaginationHelper.parsePaginationQuery(query, defaultLimit?, maxLimit?)` equivalente para paginación offset; aplica límite máximo y usa defaults cuando los valores son inválidos
189
+
190
+ ### 🔌 Express Adapter Compatibilidad ESM (`src/adapters/express.ts`)
191
+
192
+ Reescritura completa del adaptador:
193
+ - Carga Express de forma lazy y segura usando `Function('return require')()` para compatibilidad ESM sin necesitar `declare const require: any`
194
+ - Acepta una instancia de Express pre-creada como segundo argumento del constructor (para añadir middleware propio antes del bridge)
195
+ - Manejo correcto de body raw (`Buffer`) vs body parseado (JSON/urlencoded)
196
+ - Omite el header `transfer-encoding` al reenviar respuestas (era fuente de errores en Express)
197
+ - Delega errores inesperados al pipeline de error de Express mediante `next(err)` en lugar de responder con 500 directamente
198
+
199
+ ### 🐛 Bug Fixes
200
+
201
+ - **`ZodError` cross-module** (`src/errors/handler.ts`, `src/validation/validator.ts`): `instanceof ZodError` fallaba cuando la app consumidora tenía una instancia de Zod diferente a la del framework (caso frecuente con `bun link`). Añadido fallback `error.name === 'ZodError'` para garantizar respuestas 422 en todos los casos
202
+ - **Rutas `GET` marcadas públicas retornaban 401** en `products-api`: `app.use()` aplicaba el middleware a todos los métodos; corregido usando `app.on(['POST', 'PUT', 'DELETE'], path, middleware)` para restringir sólo a métodos de escritura
203
+ - **Cache collision en MetadataCompiler**: handlers funcionales distintos con el mismo path en diferentes instancias de app compartían el resultado compilado incorrecto; solucionado con IDs únicos por función
204
+ - **`@Cache` / `@UseMiddleware` perdían metadatos**: cuando se apilaban en orden inverso al de ejecución de decoradores, los metadatos podían sobreescribirse; solucionado actualizando el registro explícitamente en cada decorador
205
+
206
+ ### 📋 Mensajes de validación mejorados (`src/validation/exceptions.ts`)
207
+
208
+ La respuesta de error `422` ahora incluye información estructurada adicional:
209
+ - `field` en formato convencional: `items[0].price` en lugar de `items.0.price`
210
+ - `received` — tipo recibido (cuando Zod lo reporta)
211
+ - `expected` — tipo esperado (cuando aplica)
212
+ - `minimum` / `maximum` — límites numéricos en errores de rango
213
+
214
+ ```json
215
+ {
216
+ "error": "Validation Error",
217
+ "statusCode": 422,
218
+ "details": [
219
+ { "field": "email", "message": "Invalid email", "code": "invalid_string" },
220
+ { "field": "age", "message": "Number must be ≥ 18", "code": "too_small", "minimum": 18 },
221
+ { "field": "tags[1]", "message": "String must not be empty", "code": "too_small" }
222
+ ]
223
+ }
224
+ ```
225
+
226
+ ### 💥 Breaking Changes
227
+
228
+ Ninguno — todos los cambios son retrocompatibles. Las firmas de `createCursorPaginatedResult` tienen un nuevo parámetro opcional `hadPrevCursor` (cuarto argumento, `false` por defecto).
229
+
230
+ ### 📦 Dependencias
231
+
232
+ Sin cambios en dependencias de runtime. Express sigue siendo peer dependency opcional.
233
+
234
+ ---
235
+
236
+ ## [0.3.3] - 2025-10-31
237
+
238
+ ### 🐛 Critical Bug Fixes
239
+ - **JSON Response Serialization**: Fixed critical bug where JSON responses were not being serialized correctly
240
+ - **CLI Version Resolution**: Confirmed CLI correctly fetches and uses latest npm version (0.3.2)
241
+ - **Application Compilation**: Fixed missing `await app.compile()` call in generated templates
242
+
243
+ ### 🔧 CLI Improvements
244
+ - **Version Fetching**: CLI now correctly fetches latest version from npm registry
245
+ - **Template Generation**: All templates now include proper `await app.compile()` call
246
+ - **Error Handling**: Improved error handling in CLI operations
247
+
248
+ ## [0.3.2] - 2025-10-31
249
+
250
+ ## [0.3.1] - 2025-10-31
251
+
252
+ ### 🛠️ CLI Improvements
253
+
254
+ #### Enhanced Project Generation
255
+ - **Latest Version Fetching**: CLI now automatically fetches the latest VeloceTS version from npm registry
256
+ - **Improved Error Handling**: Better error messages and cleanup on project creation failure
257
+ - **Type Safety**: Fixed TypeScript errors in CLI with proper type definitions for npm registry API
258
+ - **Better User Experience**: Enhanced progress messages and visual feedback during project creation
259
+ - **Robust Fallbacks**: Multiple fallback strategies for version detection when npm is unavailable
260
+
261
+ #### Fixed Issues
262
+ - **npm Registry Integration**: Fixed CLI to use correct npm registry endpoint (`/veloce-ts` instead of `/veloce-ts/latest`)
263
+ - **Type Definitions**: Added proper TypeScript interfaces for npm registry response structure
264
+ - **Version Resolution**: Improved version parsing with proper type checking and validation
265
+ - **Package.json Generation**: Now uses specific dependency versions instead of 'latest' for better stability
266
+ - **Template Compilation**: All generated templates now include mandatory `await app.compile()` call
267
+
268
+ #### Technical Improvements
269
+ - **NpmRegistryResponse Interface**: Added proper typing for npm registry API responses
270
+ - **Async Error Handling**: Better error handling in async CLI operations
271
+ - **Dependency Versions**: Updated to use specific versions for better reproducibility:
272
+ - `hono: ^4.0.0` (instead of 'latest')
273
+ - `reflect-metadata: ^0.2.0` (instead of 'latest')
274
+ - `zod: ^3.22.0` (instead of 'latest')
275
+ - `typescript: ^5.3.0` (instead of 'latest')
276
+ - **Engine Requirements**: Added Node.js and Bun version requirements to generated package.json
277
+
278
+ #### Developer Experience
279
+ - **Progress Indicators**: Added emoji-based progress indicators for better visual feedback
280
+ - **Cleanup on Failure**: Automatic cleanup of partial projects when creation fails
281
+ - **Validation**: Better project name validation and error messages
282
+ - **Documentation**: Generated projects include comprehensive setup instructions
283
+
284
+ ### 🐛 Bug Fixes
285
+ - **CLI TypeScript Errors**: Fixed 'data is of type unknown' error in npm registry API calls
286
+ - **Template Generation**: Fixed missing `await app.compile()` in all CLI templates
287
+ - **Dependency Management**: Improved dependency version resolution and fallback handling
288
+
289
+ ### 📦 Migration Guide
290
+
291
+ #### For CLI Users
292
+ No breaking changes. Existing projects will continue to work. New projects generated with `veloce-ts new` will:
293
+ - Use the latest VeloceTS version automatically
294
+ - Include proper `await app.compile()` calls
295
+ - Have more stable dependency versions
296
+
297
+ #### For Framework Users
298
+ No changes required. This release only improves the CLI experience.
299
+
300
+ ## [0.3.0] - 2025-10-29
301
+
302
+ ### 🚀 Major Features Added
303
+
304
+ #### Response Caching System
305
+ - **In-Memory Cache Store**: Fast LRU-based caching with automatic cleanup
306
+ - **Redis Cache Store**: Distributed caching support for multi-instance deployments
307
+ - **@Cache() Decorator**: Declarative response caching with flexible TTL configuration
308
+ - **@CacheInvalidate() Decorator**: Pattern-based cache invalidation for mutations
309
+ - **Cache Middleware**: Functional API support for route-level caching
310
+ - **TTL Support**: Flexible time-to-live with string format ('5m', '1h', '1d') or seconds
311
+ - **Pattern Invalidation**: Wildcard pattern matching for cache invalidation ('products:*')
312
+ - **Cache Keys**: Smart key generation with placeholder support ('product:{id}')
313
+ - **Cache Headers**: Automatic X-Cache headers (HIT/MISS) in responses
314
+
315
+ #### Enhanced Request Context
316
+ - **Automatic Request IDs**: UUID generation for every request
317
+ - **@RequestId() Decorator**: Inject request ID into controller methods
318
+ - **@AbortSignal() Decorator**: Request cancellation support for long-running operations
319
+ - **Request Timeouts**: Configurable timeouts per route or globally
320
+ - **Logging Integration**: Request ID automatically propagates through all logs
321
+ - **Response Headers**: X-Request-ID header in all responses
322
+ - **Metadata Storage**: Attach custom data to request context
323
+ - **Request Lifecycle**: Automatic logging of request start/end with duration
324
+
325
+ #### Logging Improvements
326
+ - **Request Context Integration**: Automatic request ID in all log entries
327
+ - **Child Loggers**: Enhanced contextual logging with inheritance
328
+ - **Structured Logging**: JSON-formatted logs for production
329
+ - **Pretty Printing**: Human-readable logs for development
330
+ - **Log Middleware**: Request lifecycle logging with configurable headers
331
+
332
+ ### 🎯 New Decorators
333
+
334
+ - **@Cache(options)**: Cache route responses with TTL and key configuration
335
+ - **@CacheInvalidate(pattern)**: Invalidate cache entries matching patterns
336
+ - **@RequestId()**: Inject unique request ID into handler parameters
337
+ - **@AbortSignal()**: Inject AbortSignal for request cancellation
338
+
339
+ ### 🔧 New Middleware
340
+
341
+ - **createRequestContextMiddleware()**: Initialize request context with ID, timeout, and logging
342
+ - **createSimpleRequestIdMiddleware()**: Minimal request ID middleware
343
+ - **createCacheMiddleware()**: Functional API route caching
344
+ - **createCacheInvalidationMiddleware()**: Functional API cache invalidation
345
+
346
+ ### 📦 New Modules
347
+
348
+ - **src/cache/**: Complete caching system
349
+ - `types.ts`: Cache interfaces and types
350
+ - `memory-store.ts`: In-memory LRU cache implementation
351
+ - `redis-store.ts`: Redis backend for distributed caching
352
+ - `manager.ts`: Global cache management and utilities
353
+ - **src/context/**: Enhanced request context
354
+ - `request-context.ts`: Request tracking with UUID and AbortSignal
355
+ - **src/middleware/**: New middleware
356
+ - `request-context.ts`: Request context initialization
357
+ - `cache.ts`: Cache middleware for functional API
358
+ - **src/decorators/**: New decorators
359
+ - `cache.ts`: @Cache and @CacheInvalidate decorators
360
+
361
+ ### 🛠️ Core Improvements
362
+
363
+ - **Router Compiler**: Integrated cache checking and invalidation in route handlers
364
+ - **Type System**: New parameter types for request-id and abort-signal
365
+ - **Export System**: All new decorators and middleware properly exported
366
+ - **Error Handling**: Improved error handling with request ID context
367
+
368
+ ### 📚 Documentation
369
+
370
+ #### New Guides (English + Spanish)
371
+ - **Caching Guide**: Complete guide to response caching (15,000 words total)
372
+ - In-memory and Redis stores
373
+ - Decorators and middleware
374
+ - TTL configuration
375
+ - Cache invalidation strategies
376
+ - Best practices with 50+ code examples
377
+ - **Request Context Guide**: Request tracking and management (12,000 words total)
378
+ - Automatic UUID generation
379
+ - Request cancellation with AbortSignal
380
+ - Timeout configuration
381
+ - Logging integration
382
+ - 40+ code examples
383
+ - **Logging Guide**: Structured logging with Pino (4,000 words total)
384
+ - Logger configuration
385
+ - Child loggers
386
+ - Request ID integration
387
+ - Best practices
388
+
389
+ #### Documentation Coverage
390
+ - Added 31,000+ words of professional documentation
391
+ - 100+ new code examples
392
+ - Bilingual support (English and Spanish)
393
+ - SEO-optimized with meta descriptions
394
+ - Cross-referenced between guides
395
+
396
+ ### 🌐 Sidebar Updates
397
+
398
+ Updated Starlight documentation sidebar with new guides:
399
+ - Caching
400
+ - Request Context
401
+ - Logging
402
+
403
+ ### Performance Improvements
404
+
405
+ - **Cache System**: Sub-millisecond cache hits with in-memory store
406
+ - **LRU Eviction**: Automatic memory management in cache store
407
+ - **Request Context**: Minimal overhead UUID generation
408
+ - **Logging**: Efficient structured logging with Pino
409
+
410
+ ### 🔄 API Additions
411
+
412
+ #### Cache Manager
413
+ ```typescript
414
+ - CacheManager.setDefaultStore(store)
415
+ - CacheManager.getDefaultStore()
416
+ - CacheManager.generateKey(method, path, params, query, options)
417
+ - CacheManager.get(key, store?)
418
+ - CacheManager.set(key, value, ttl?, store?)
419
+ - CacheManager.delete(key, store?)
420
+ - CacheManager.invalidate(pattern, store?)
421
+ - CacheManager.clear(store?)
422
+ ```
423
+
424
+ #### Helper Functions
425
+ ```typescript
426
+ - getCache<T>(key): Promise<T | null>
427
+ - setCache<T>(key, value, ttl?): Promise<void>
428
+ - deleteCache(key): Promise<boolean>
429
+ - invalidateCache(pattern): Promise<number>
430
+ - clearCache(): Promise<void>
431
+ - getRequestId(context): string | null
432
+ - getAbortSignal(context): AbortSignal | null
433
+ - setRequestMetadata(context, key, value): void
434
+ - getRequestMetadata(context, key): any
435
+ - generateRequestId(): string
436
+ ```
437
+
438
+ ### 🐛 Bug Fixes
439
+
440
+ - **ORM Exports**: Fixed DrizzleTransactionManager import path
441
+ - **Middleware Exports**: Added missing createCacheInvalidationMiddleware export
442
+ - **Request Context**: Fixed AbortController reference in context
443
+
444
+ ### 💥 Breaking Changes
445
+
446
+ None - All changes are additive and backward compatible
447
+
448
+ ### 📦 Dependencies
449
+
450
+ No new runtime dependencies added. Caching works with existing dependencies:
451
+ - In-memory cache: No dependencies (built-in)
452
+ - Redis cache: Requires `redis` or `ioredis` (peer dependency)
453
+
454
+ ### 🎯 Migration Guide
455
+
456
+ #### Adding Cache to Existing Routes
457
+
458
+ ```typescript
459
+ // Before
460
+ @Get('/products')
461
+ async getProducts() {
462
+ return await db.products.findAll();
463
+ }
464
+
465
+ // After - Add caching
466
+ @Get('/products')
467
+ @Cache({ ttl: '5m', key: 'products:list' })
468
+ async getProducts() {
469
+ return await db.products.findAll();
470
+ }
471
+ ```
472
+
473
+ #### Adding Request Tracking
474
+
475
+ ```typescript
476
+ // Add to app initialization
477
+ import { createRequestContextMiddleware } from 'veloce-ts';
478
+
479
+ app.use(createRequestContextMiddleware({
480
+ timeout: 30000,
481
+ logging: true
482
+ }));
483
+
484
+ // Use in controllers
485
+ @Get('/data')
486
+ async getData(@RequestId() requestId: string) {
487
+ logger.info({ requestId }, 'Processing request');
488
+ return data;
489
+ }
490
+ ```
491
+
492
+ ### 📊 Statistics
493
+
494
+ - **New Files**: 15+ new source files
495
+ - **Documentation**: 31,000+ words
496
+ - **Code Examples**: 100+ examples
497
+ - **Test Coverage**: All new features covered
498
+ - **Languages**: Full bilingual support (EN/ES)
499
+
500
+ ### 🙏 Acknowledgments
501
+
502
+ This release brings powerful performance optimization features to Veloce-TS:
503
+ - Response caching reduces database load and improves response times
504
+ - Request tracking enables better debugging and monitoring
505
+ - Enhanced logging provides better observability in production
506
+
507
+ ## [0.2.6] - 2025-10-15
508
+
509
+ ### Fixed
510
+ - **Query Export**: Added missing `Query` export from main index to resolve import conflicts
511
+ - **Parameter Decorators**: HTTP `@Query` decorator now properly exported alongside GraphQL decorators
512
+ - **Import Resolution**: Fixed "Export named 'Query' not found" error in applications
513
+
514
+ ## [0.2.5] - 2025-10-15
515
+
516
+ ### Fixed
517
+ - **GraphQL Query Conflict**: Removed conflicting alias `Query` from GraphQL decorators
518
+ - **Import Resolution**: GraphQL decorators now use `GQLQuery` to avoid conflicts with HTTP `@Query` decorator
519
+ - **Type Safety**: Eliminated TypeScript errors caused by decorator name conflicts
520
+
521
+ ### Breaking Changes
522
+ - GraphQL queries now use `@GQLQuery` instead of `@Query` to avoid conflicts with HTTP parameter decorator
523
+
524
+ ## [0.2.4] - 2025-10-15
525
+
526
+ ### Fixed
527
+ - **Query Decorator**: Fixed `@Query` decorator to properly handle parameters without schemas
528
+ - **Query Parameter Extraction**: Improved query parameter handling in router compiler
529
+ - **Validation**: Added proper validation for query parameters with optional Zod schemas
530
+ - **Error Handling**: Fixed missing `ValidationError` import, now using `BadRequestException`
531
+
532
+ ### Improved
533
+ - **Query Decorator Flexibility**: `@Query` now supports multiple usage patterns:
534
+ - `@Query()` - Extract all query parameters
535
+ - `@Query('param')` - Extract specific parameter
536
+ - `@Query(Schema)` - Validate with Zod schema
537
+ - **Router Compiler**: Enhanced parameter extraction and validation logic
538
+ - **Type Safety**: Better TypeScript support for query parameter handling
539
+
540
+ ### Breaking Changes
541
+ - None
542
+
543
+ ## [0.2.3] - 2025-10-14
544
+
545
+ ### Fixed
546
+ - **WebSocket Exports**: Fixed missing `WebSocket` decorator export from WebSocket module
547
+ - **Import Resolution**: WebSocket decorators now properly exported from `veloce-ts/websocket`
548
+
549
+ ## [0.2.2] - 2025-10-14
550
+
551
+ ### Fixed
552
+ - **GraphQL Decorators**: Added missing `Query`, `Mutation`, and `Subscription` aliases for GraphQL decorators
553
+ - **Import Conflicts**: Fixed naming conflicts between params and GraphQL decorators
554
+ - **CLI Templates**: Fixed import errors in CLI template generation
555
+ - **Package Version**: CLI now uses current package version when generating new projects
556
+
557
+ ### Changed
558
+ - **GraphQL Exports**: GraphQL decorators now available with intuitive names (`Query`, `Mutation`, `Subscription`)
559
+ - **Import Resolution**: Cleaner import structure to avoid naming conflicts
560
+
561
+ ## [0.2.1] - 2025-10-14
562
+
563
+ ### Fixed
564
+ - **GraphQL Exports**: Fixed missing `Arg` decorator export from GraphQL module
565
+ - **Import Resolution**: GraphQL decorators now properly exported from `veloce-ts/graphql`
566
+ - **Type Definitions**: GraphQL decorators included in TypeScript declarations
567
+
568
+ ## [0.2.0] - 2025-10-14
569
+
570
+ ### 🚀 Major Features Added
571
+ - **Complete Authentication System**: JWT-based authentication with access/refresh tokens
572
+ - **Role-Based Access Control (RBAC)**: Hierarchical roles with granular permissions system
573
+ - **SQLite Integration**: Built-in SQLite support with Bun's native database
574
+ - **Real-time WebSocket Support**: Enhanced WebSocket handling with decorators
575
+ - **GraphQL Integration**: Complete GraphQL support with resolvers and subscriptions
576
+ - **Advanced Middleware System**: Custom middleware with request/response interceptors
577
+ - **Admin Panel Features**: Comprehensive admin endpoints for user and system management
578
+
579
+ ### 🎯 New Decorators & Features
580
+ - **@Auth**: JWT authentication decorator with automatic user injection
581
+ - **@CurrentUser**: Inject current authenticated user into handlers
582
+ - **@MinimumRole**: Role-based endpoint protection
583
+ - **@Permissions**: Granular permission-based access control
584
+ - **@WebSocket**: Enhanced WebSocket decorators with connection management
585
+ - **@Resolver**: GraphQL resolver decorators for queries and mutations
586
+ - **@OnConnect/@OnMessage/@OnDisconnect**: WebSocket lifecycle decorators
587
+
588
+ ### 🔧 Core Framework Improvements
589
+ - **Router Compiler Fixes**: Fixed critical bugs with sparse array handling in metadata
590
+ - **Dependency Injection**: Enhanced DI system with better error handling
591
+ - **Parameter Resolution**: Improved parameter and dependency resolution
592
+ - **Type Safety**: Enhanced TypeScript inference and type checking
593
+ - **Error Handling**: Better error messages and debugging capabilities
594
+
595
+ ### 📚 Documentation & Examples
596
+ - **Veloce TaskMaster**: Complete real-world example with authentication, RBAC, and frontend
597
+ - **Comprehensive Examples**: Task management system showcasing all framework features
598
+ - **Migration Guides**: Documentation for migrating from Express.js and other frameworks
599
+ - **API Documentation**: Enhanced OpenAPI/Swagger documentation generation
600
+
601
+ ### 🛠️ Technical Improvements
602
+ - **Performance**: Optimized router compilation and metadata handling
603
+ - **Memory Management**: Better handling of metadata arrays and object references
604
+ - **Bundle Size**: Reduced framework bundle size through optimizations
605
+ - **Build System**: Improved TypeScript compilation and type generation
606
+ - **Testing**: Enhanced testing utilities and error reporting
607
+
608
+ ### 🔒 Security Enhancements
609
+ - **JWT Security**: Secure token generation and validation
610
+ - **Password Hashing**: Built-in password hashing utilities
611
+ - **CSRF Protection**: Enhanced CORS and security middleware
612
+ - **Input Validation**: Improved Zod schema validation
613
+ - **Role Hierarchy**: Configurable role hierarchy with permission inheritance
614
+
615
+ ### 🎨 Developer Experience
616
+ - **Better Error Messages**: More descriptive error messages with stack traces
617
+ - **Hot Reload**: Improved development server with better file watching
618
+ - **TypeScript Support**: Enhanced type inference and IntelliSense
619
+ - **Debugging**: Better debugging capabilities with request tracing
620
+ - **CLI Improvements**: Enhanced CLI with better project scaffolding
621
+
622
+ ### 🐛 Critical Bug Fixes
623
+ - **Router Compilation**: Fixed sparse array handling in parameter metadata
624
+ - **Dependency Resolution**: Fixed undefined dependency handling
625
+ - **Array Length Errors**: Fixed array creation with invalid indices
626
+ - **Import Path Issues**: Corrected all import paths in generated projects
627
+ - **Metadata Processing**: Fixed metadata compilation edge cases
628
+
629
+ ### 📦 New Dependencies
630
+ - **jsonwebtoken**: JWT token generation and validation
631
+ - **reflect-metadata**: Enhanced reflection capabilities for decorators
632
+ - **zod-to-json-schema**: Improved OpenAPI schema generation
633
+
634
+ ## [0.1.7] - 2025-10-12
635
+
636
+ ### Fixed
637
+ - Fixed syntax error in CLI new command that prevented build from completing
638
+ - Fixed README generation in CLI templates
639
+
640
+ ## [0.1.6] - 2025-10-12
641
+
642
+ ### Added
643
+ - **Landing Page**: Created modern Astro-based website with interactive terminal and file explorer
644
+ - **Interactive Terminal**: Built terminal component for API testing with command history
645
+ - **File Explorer**: Developed code browser with hierarchical navigation for demo app
646
+ - **Documentation Files**: CLI now generates README.md and API_DOCUMENTATION.md in new projects
647
+
648
+ ### Changed
649
+ - **Complete Rebranding**: Renamed framework from FastAPI-TS to Veloce-TS throughout codebase
650
+ - **OpenAPIPlugin**: Now serves Swagger UI directly from code (no need for static HTML files)
651
+ - **Improved Swagger UI**: Updated to version 5.9.0 with better styling and functionality
652
+ - **Simplified Templates**: `veloce-ts new` command no longer generates unnecessary public files
653
+ - **Better Defaults**: OpenAPI documentation now uses "Veloce-TS" branding by default
654
+ - **Updated URLs**: All references now point to correct GitHub repository and documentation
655
+
656
+ ### Fixed
657
+ - Fixed Swagger UI rendering issues with proper script loading
658
+ - Fixed OpenAPI plugin to correctly serve HTML responses and return proper content types
659
+ - Fixed broken links and outdated branding throughout codebase
660
+ - Improved CORS handling in generated templates
661
+ - Fixed CLI template generation to include proper documentation structure
662
+
663
+ ## [0.1.5] - 2025-10-12
664
+
665
+ ### Fixed
666
+ - Fixed CLI templates to include OpenAPIPlugin automatically when docs: true
667
+ - REST and Fullstack templates now properly initialize OpenAPI documentation
668
+
669
+ ## [0.1.4] - 2025-10-13
670
+
671
+ ### Fixed
672
+ - Fixed CLI templates to call `await app.compile()` before `app.listen()`
673
+ - This fixes the 404 error on all routes in generated projects
674
+
675
+ ## [0.1.3] - 2025-10-12
676
+
677
+ ### Fixed
678
+ - Fixed package.json main and exports paths to point to correct dist/*/src/ directories
679
+ - This fixes the "Cannot find package" error when importing veloce-ts
680
+
681
+ ## [0.1.2] - 2025-10-12
682
+
683
+ ### Fixed
684
+ - Fixed CLI templates to use correct package name `veloce-ts` instead of `VeloceTS`
685
+ - Fixed all import statements in generated projects
686
+
687
+ ## [0.1.1] - 2025-10-12
688
+
689
+ ### Fixed
690
+ - Fixed CLI binary path to use compiled dist files instead of source files
691
+
692
+ ## [0.1.0] - 2025-10-12
693
+
694
+ ### Added
695
+ - Initial release of veloce-ts framework
696
+ - Decorator-based routing with @Controller, @Get, @Post, @Put, @Delete, @Patch
697
+ - Functional API for decorator-free routing
698
+ - Automatic request validation with Zod schemas
699
+ - Dependency injection system with singleton, request, and transient scopes
700
+ - Automatic OpenAPI documentation generation
701
+ - Response handling with JSONResponse, HTMLResponse, FileResponse, StreamResponse, RedirectResponse
702
+ - Plugin system for extensibility
703
+ - WebSocket support with decorators
704
+ - GraphQL support with decorators
705
+ - CLI tool for project scaffolding and development
706
+ - Middleware system with CORS, rate limiting, and compression
707
+ - Error handling with custom exceptions
708
+ - Testing utilities with TestClient
709
+ - Multi-runtime support (Bun, Node.js, Deno, Cloudflare Workers)
710
+ - Adapter system for Express and Hono
711
+ - Type safety with full TypeScript support
712
+ - Performance optimizations with metadata compilation and schema caching
713
+
714
+ ## [0.1.0] - 2025-10-12
715
+
716
+ ### Added
717
+ - Initial development version
718
+ - Core framework architecture
719
+ - Basic routing and validation
720
+ - Documentation generation
721
+ - Plugin system
722
+ - WebSocket and GraphQL support
723
+ - CLI tooling
724
+ - Testing utilities
725
+
726
+ [Unreleased]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.4.0...HEAD
727
+ [0.4.0]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.3.3...v0.4.0
728
+ [0.3.3]: https://github.com/AlfredoMejia3001/veloce-ts/releases/tag/v0.3.3
729
+ [0.3.2]: https://github.com/AlfredoMejia3001/veloce-ts/releases/tag/v0.3.2
730
+ [0.3.1]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.3.0...v0.3.1
731
+ [0.2.2]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.2.1...v0.2.2
732
+ [0.2.1]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.2.0...v0.2.1
733
+ [0.2.0]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.1.7...v0.2.0
734
+ [0.1.7]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.1.6...v0.1.7
735
+ [0.1.6]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.1.5...v0.1.6
736
+ [0.1.5]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.1.4...v0.1.5
737
+ [0.1.4]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.1.3...v0.1.4
738
+ [0.1.3]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.1.2...v0.1.3
739
+ [0.1.2]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.1.1...v0.1.2
740
+ [0.1.1]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.1.0...v0.1.1
741
+ [0.1.0]: https://github.com/AlfredoMejia3001/veloce-ts/releases/tag/v0.1.0