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