@adaptivestone/framework 5.0.0 → 5.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +68 -176
- package/dist/commands/OpenApi.d.ts +26 -0
- package/dist/commands/OpenApi.js +101 -0
- package/dist/commands/OpenApi.js.map +1 -0
- package/dist/commands/Routes.d.ts +17 -0
- package/dist/commands/Routes.js +35 -0
- package/dist/commands/Routes.js.map +1 -0
- package/dist/config/cache.d.ts +14 -0
- package/dist/config/cache.js +14 -0
- package/dist/config/cache.js.map +1 -0
- package/dist/controllers/index.js +28 -4
- package/dist/controllers/index.js.map +1 -1
- package/dist/helpers/appInstance.d.ts +6 -0
- package/dist/helpers/appInstance.js +13 -0
- package/dist/helpers/appInstance.js.map +1 -1
- package/dist/modules/BaseModel.d.ts +10 -0
- package/dist/modules/BaseModel.js +25 -0
- package/dist/modules/BaseModel.js.map +1 -1
- package/dist/server.d.ts +20 -1
- package/dist/server.js +24 -1
- package/dist/server.js.map +1 -1
- package/dist/services/cache/Cache.d.ts +3 -4
- package/dist/services/cache/Cache.js +43 -34
- package/dist/services/cache/Cache.js.map +1 -1
- package/dist/services/cache/CacheDriver.d.ts +19 -0
- package/dist/services/cache/CacheDriver.js +2 -0
- package/dist/services/cache/CacheDriver.js.map +1 -0
- package/dist/services/cache/drivers/MemoryDriver.d.ts +14 -0
- package/dist/services/cache/drivers/MemoryDriver.js +40 -0
- package/dist/services/cache/drivers/MemoryDriver.js.map +1 -0
- package/dist/services/cache/drivers/RedisDriver.d.ts +22 -0
- package/dist/services/cache/drivers/RedisDriver.js +44 -0
- package/dist/services/cache/drivers/RedisDriver.js.map +1 -0
- package/dist/services/documentation/OpenApiGenerator.d.ts +39 -0
- package/dist/services/documentation/OpenApiGenerator.js +296 -0
- package/dist/services/documentation/OpenApiGenerator.js.map +1 -0
- package/dist/services/http/HttpServer.d.ts +23 -0
- package/dist/services/http/HttpServer.js +57 -0
- package/dist/services/http/HttpServer.js.map +1 -1
- package/dist/services/http/builtinErrorHandlers.d.ts +36 -0
- package/dist/services/http/builtinErrorHandlers.js +71 -0
- package/dist/services/http/builtinErrorHandlers.js.map +1 -0
- package/dist/services/http/httpErrors.d.ts +30 -0
- package/dist/services/http/httpErrors.js +46 -0
- package/dist/services/http/httpErrors.js.map +1 -0
- package/dist/services/http/middleware/AbstractMiddleware.d.ts +25 -7
- package/dist/services/http/middleware/AbstractMiddleware.js +14 -0
- package/dist/services/http/middleware/AbstractMiddleware.js.map +1 -1
- package/dist/services/http/middleware/GetUserByToken.d.ts +13 -0
- package/dist/services/http/middleware/GetUserByToken.js +5 -1
- package/dist/services/http/middleware/GetUserByToken.js.map +1 -1
- package/dist/services/http/middleware/RateLimiter.d.ts +8 -2
- package/dist/services/http/middleware/RateLimiter.js +38 -13
- package/dist/services/http/middleware/RateLimiter.js.map +1 -1
- package/dist/services/http/routing/RouteNode.d.ts +2 -0
- package/dist/services/validate/drivers/StandardSchemaDriver.d.ts +5 -2
- package/dist/services/validate/drivers/StandardSchemaDriver.js +24 -3
- package/dist/services/validate/drivers/StandardSchemaDriver.js.map +1 -1
- package/dist/services/validate/drivers/YupDriver.js +91 -2
- package/dist/services/validate/drivers/YupDriver.js.map +1 -1
- package/dist/services/validate/types.d.ts +7 -4
- package/dist/tests/globalSetupNodeTest.d.ts +2 -0
- package/dist/tests/globalSetupNodeTest.js +23 -0
- package/dist/tests/globalSetupNodeTest.js.map +1 -0
- package/dist/tests/globalSetupVitest.js +6 -13
- package/dist/tests/globalSetupVitest.js.map +1 -1
- package/dist/tests/nodeRunner.node-test.d.ts +14 -0
- package/dist/tests/nodeRunner.node-test.js +41 -0
- package/dist/tests/nodeRunner.node-test.js.map +1 -0
- package/dist/tests/nodeRunnerShared.node-test.d.ts +14 -0
- package/dist/tests/nodeRunnerShared.node-test.js +39 -0
- package/dist/tests/nodeRunnerShared.node-test.js.map +1 -0
- package/dist/tests/setupFramework.d.ts +33 -0
- package/dist/tests/setupFramework.js +134 -0
- package/dist/tests/setupFramework.js.map +1 -0
- package/dist/tests/setupNodeTest.d.ts +1 -0
- package/dist/tests/setupNodeTest.js +16 -0
- package/dist/tests/setupNodeTest.js.map +1 -0
- package/dist/tests/setupVitest.js +8 -99
- package/dist/tests/setupVitest.js.map +1 -1
- package/package.json +12 -5
package/CHANGELOG.md
CHANGED
|
@@ -2,218 +2,110 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to this project will be documented in this file.
|
|
4
4
|
|
|
5
|
-
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
|
6
|
-
|
|
5
|
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
6
|
+
|
|
7
|
+
## [5.1.0] - 2026-07-05
|
|
8
|
+
|
|
9
|
+
### Added
|
|
10
|
+
|
|
11
|
+
- **OpenAPI 3.1 generator.** New `openapi` CLI command (`node src/cli.ts openapi [--output <file>]`) emits an OpenAPI 3.1 document from your controllers — paths, path/query parameters, request bodies (single schema or content-type map), security schemes, and tags — all derived from the route definitions you already write. Runs cold: loads controllers without opening a database/network connection or binding a port, so it's safe in CI. See the OpenAPI documentation chapter.
|
|
12
|
+
- **Vendor-neutral JSON Schema export on the validator driver seam.** `ValidatorDriver.toJsonSchema` is now implemented (and may return a `Promise`): Zod via native `z.toJSONSchema`, Yup via `.describe()`, ArkType (or any schema exposing a `.toJsonSchema()` method) via its native output. Validators with no introspection (`defineSchema`, custom `~standard` functions) degrade to a placeholder schema. The seam is reusable beyond OpenAPI (e.g. a future MCP surface).
|
|
13
|
+
- **`AbstractMiddleware.usedAuthParameters` is now a `static` getter** — the OpenAPI generator reads it off the class to build `components.securitySchemes` with zero instantiation. The instance form is kept for back-compat (removed in v6). `GetUserByToken` declares its `Authorization` header + bearer schemes, so routes behind it are documented as secured automatically.
|
|
14
|
+
- Route `description` now surfaces as the OpenAPI operation `summary`, and the controller class name becomes the operation's `tags`. (Internal: `HandlerEntry.meta` gained `description` / `controllerClass`; generated `.routes.gen.ts` output is byte-for-byte unchanged.)
|
|
15
|
+
- **Project boot hook (`bootHttp`).** Pass a `bootHttp` function (type `BootHttpHook`) to the `Server` constructor; it's called with the live `app` during `startServer` — after controllers register, before the adapter mounts — as the blessed place for app-wide HTTP wiring that doesn't fit a controller (ad-hoc routes via `app.httpServer.routeRegistry.registerRoute(...)`, Express-level middleware, boot setup). Wired explicitly rather than discovered from a folder (the framework's folders are all owned — config/ merges its files, controllers/ auto-loads its files). HTTP-specific by design (it needs `app.httpServer`, which only exists once the server boots; CLI/worker processes don't run it). Complements the existing `callbackBefore404` (which runs after the mount).
|
|
16
|
+
- **`routes` CLI command.** `node src/cli.ts routes` (or `npm run routes`) prints the project's route tree — every mounted method, full path, path/splat parameters, and the accumulated middleware chain per route — by walking the same `RouteRegistry` the server logs at boot. Read-only and boot-based: no database, no port (mirrors the `openapi` command).
|
|
17
|
+
- **Runner-agnostic test setup.** The test lifecycle moved into plain async functions (`tests/setupFramework` — `startTestMongo`/`stopTestMongo`, `startTestServer`/`stopTestServer`, `setTestRedisNamespace`/`clearTestRedisNamespace`) with no test-runner import. `tests/setupVitest` + `tests/globalSetupVitest` are now thin wrappers, and a new `tests/setupNodeTest` lets consumers run framework-backed tests under Node's built-in `node:test` (vitest stays an optional peer). The run-once in-memory Mongo is wired through node:test's `--test-global-setup` hook (Node ≥ 24) — the analog of vitest's `globalSetup`. See the testing docs.
|
|
18
|
+
- **Cache drivers — `@redis/client` is now optional.** The cache is built on a small `CacheDriver` interface with two first-party drivers: a per-process `MemoryDriver` (new default — needs no external service) and a `RedisDriver` that lazy-imports `@redis/client` only when selected. Choose via `config/cache.ts` (`{ driver: 'memory' | 'redis' }`, or `CACHE_DRIVER` env). A `CacheDriver` instance can be injected directly for a custom backend. The orchestration you rely on — namespacing, in-flight request dedup, JSON/bigint (de)serialization, and fail-soft degradation — is unchanged.
|
|
19
|
+
- **Zero-TTL means "don't cache" (issue #10).** `cache.getSetValue(key, fn, 0)` now skips the cache entirely and recomputes every call, instead of writing a never-expiring entry.
|
|
20
|
+
- **`getAppInstance()` helper.** `helpers/appInstance` now exports a throwing getter alongside the raw `appInstance` binding: it returns the app singleton, or throws a guided error ("construct the Server first"; tests can use `setAppInstance()`/`resetAppInstance()`) when nothing is set. Prefer it in code that may run before the `Server` is constructed (module scope, lazy imports, external modules) — reading the raw binding there fails later with an opaque `TypeError: cannot read properties of undefined` that gives no hint at the cause.
|
|
21
|
+
- **Duplicate-framework-copy diagnostic in the model loader.** When npm fails to dedupe and a model class extends `BaseModel` from a *different* installed copy of `@adaptivestone/framework`, `instanceof BaseModel` is false, so the loader used to silently misroute the class into the legacy (`AbstractModel`) branch — surfacing only as a confusing downstream failure. Boot now recognizes the shape (BaseModel's static `initialize` + `modelSchema` surface without the `instanceof`, via the new `isBaseModelSubclassShape` export) and fails with an error naming the model, the cause (duplicate/undeduped install), and the fix (`npm ls @adaptivestone/framework`, then dedupe). Genuinely legacy models still route to the legacy branch unchanged.
|
|
22
|
+
- **Error-handler registry + typed HTTP errors.** Throw `NotFoundError` / `new HttpError(status, message, body?)` (from `services/http/httpErrors.js`) inside a route handler to produce that status (built-in mapper, logged `verbose`), or map error classes you don't own via `app.httpServer.registerErrorHandler(ErrorClass, handler, { logLevel? })` (returns an unregister function) — e.g. from the `bootHttp` hook. Consumer handlers are checked before built-ins; a handler returning `null` passes to the next entry; unmatched errors keep the 500. The Mongoose validation safety net is now a built-in registry entry (semantics unchanged).
|
|
23
|
+
|
|
24
|
+
### Changed
|
|
25
|
+
|
|
26
|
+
- **Mongoose validation safety net — some controller 500s are now actionable 400s.** When a route handler throws a Mongoose `ValidationError` from `save()` (e.g. a model `maxLength` the route `request:`/`query:` schema didn't mirror), the wrapped handler no longer always returns a blanket `500`. If **every** failing model path is a field the client actually sent (a key of the validated `req.appInfo.request` ∪ `req.appInfo.query`, excluding the framework-injected `contentType`), it now returns `400 { errors: { <path>: message } }` with the Mongoose messages — the same shape as route-level validation — and logs a `warn` (the route schema is missing a constraint you should mirror). If **any** failing path is renamed or internal (not sent by the client), the response stays a `500` logged as `error`, so a non-public field name never leaks and a server-side bug is never misattributed to the client. **Behavior change:** a request that previously got a `500` for this specific case now gets a `400`. Mirroring model constraints in the route schema remains the recommended practice; this is a fallback, not a contract.
|
|
27
|
+
- **`@redis/client` moved from a required dependency to an optional peer dependency.** Both consumers of it — the cache and the `RateLimiter` redis driver — now load it lazily (via dynamic `import()`), so a project that doesn't use the redis driver for either never pulls the package into its import graph and can run without it installed. **Behavior change:** the **default cache backend is now in-memory** (per-process), where it was previously redis-backed. Single-node apps and local development need no change; **multi-node deployments that rely on a shared cache must set `config/cache.ts` `driver: 'redis'` (or `CACHE_DRIVER=redis`) and install `@redis/client`.** The default `RateLimiter` driver is unchanged (`mongo`); its `redis` driver still works and now lazy-loads the client. The cache key `namespace` stays in `config/redis.ts` (shared with the rate limiter).
|
|
28
|
+
|
|
29
|
+
### Notes
|
|
30
|
+
|
|
31
|
+
- Response bodies are not yet schema-documented — operations carry generic `200`/`400`/`401`/`404` responses without body schemas. A declared `response:` route field is planned.
|
|
32
|
+
|
|
33
|
+
## [5.0.1] - 2026-06-20
|
|
34
|
+
|
|
35
|
+
### Changed
|
|
36
|
+
|
|
37
|
+
- Widen the optional peer dependency range for `@adaptivestone/framework-module-email` to `^1.0.0 || ^2.0.0`. Email module v2 no longer bundles Pug — template engines are opt-in and registered by the consumer via `Mail.registerTemplateEngine` — so the framework now accepts both the v1 and v2 lines. The dependency remains optional; projects that don't send email are unaffected. See the [email module changelog](https://github.com/adaptivestone/framework-module-email/blob/main/CHANGELOG.md) for v2 migration notes.
|
|
7
38
|
|
|
8
39
|
## [5.0.0] - 2026-06-19
|
|
9
40
|
|
|
10
|
-
First stable release of the **v5** series — a major rewrite. v5 is
|
|
11
|
-
TypeScript-first and ESM-only, replaces Express's hidden router with a
|
|
12
|
-
framework-owned tree-based router, makes validation validator-agnostic via
|
|
13
|
-
[Standard Schema](https://standardschema.dev/), and hardens auth and boot.
|
|
41
|
+
First stable release of the **v5** series — a major rewrite. v5 is TypeScript-first and ESM-only, replaces Express's hidden router with a framework-owned tree-based router, makes validation validator-agnostic via [Standard Schema](https://standardschema.dev/), and hardens auth and boot.
|
|
14
42
|
|
|
15
|
-
This section is an upgrade-oriented summary. The granular per-change notes
|
|
16
|
-
(every `[NEW]` / `[FIX]` / `[BREAKING]`) live in the `5.0.0-rc.1` … `5.0.0-rc.9`
|
|
17
|
-
entries below; nothing changed in behavior between rc.9 and this release.
|
|
43
|
+
This section is an upgrade-oriented summary. The granular per-change notes (every `[NEW]` / `[FIX]` / `[BREAKING]`) live in the `5.0.0-rc.1` … `5.0.0-rc.9` entries below; nothing changed in behavior between rc.9 and this release.
|
|
18
44
|
|
|
19
45
|
### Highlights
|
|
20
46
|
|
|
21
|
-
- **Full TypeScript support, including Mongoose models.** New `BaseModel`
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
- **
|
|
27
|
-
internal router: structural specificity (static > param > splat), per-segment
|
|
28
|
-
URL decoding, `405` + `Allow`, `400` on malformed paths, HEAD→GET fallback,
|
|
29
|
-
and a boot-time route-tree log. Walkable by codegen / future emitters.
|
|
30
|
-
- **Standard Schema validation.** Yup ≥1.7, Zod, Valibot, and ArkType work out
|
|
31
|
-
of the box; pluggable `ValidatorDriver` + `ValidateService.register()`;
|
|
32
|
-
framework-owned `ValidationError` with structured `.issues`.
|
|
33
|
-
- **Security hardening.** Random, SHA-256-hashed session / recovery /
|
|
34
|
-
verification tokens with enforced expiry; per-user-salt versioned scrypt
|
|
35
|
-
password scheme; standard security headers on by default; account-enumeration
|
|
36
|
-
oracles closed; credentials no longer written to logs.
|
|
37
|
-
- **Robust lifecycle.** Graceful shutdown on `SIGTERM`/`SIGINT` (drains
|
|
38
|
-
in-flight requests, tears down mongo/redis/logger); fail-fast boot (Mongo and
|
|
39
|
-
`AUTH_SALT` required); crash-loop protection for clustered workers.
|
|
40
|
-
- **Runtime.** ESM-only, Node ≥ 24, runs `.ts` sources natively with no build
|
|
41
|
-
step. New helpers/models: `AppInstance`, `Lock`, `i18nService`, `IpDetector`,
|
|
42
|
-
and test helpers (`getTestServerURL`, `serverInstance`).
|
|
47
|
+
- **Full TypeScript support, including Mongoose models.** New `BaseModel` statics-based model type; per-controller route/handler type generation (`npm run gen` → `<File>.routes.gen.ts` + `genTypes.d.ts`) so handler signatures, `req.appInfo`, `params`, and `query` are typed from the real resolved middleware chain. Typed `getConfig` / `getModel`.
|
|
48
|
+
- **Tree-based router.** A framework-owned `RouteRegistry` replaces Express's internal router: structural specificity (static > param > splat), per-segment URL decoding, `405` + `Allow`, `400` on malformed paths, HEAD→GET fallback, and a boot-time route-tree log. Walkable by codegen / future emitters.
|
|
49
|
+
- **Standard Schema validation.** Yup ≥1.7, Zod, Valibot, and ArkType work out of the box; pluggable `ValidatorDriver` + `ValidateService.register()`; framework-owned `ValidationError` with structured `.issues`.
|
|
50
|
+
- **Security hardening.** Random, SHA-256-hashed session / recovery / verification tokens with enforced expiry; per-user-salt versioned scrypt password scheme; standard security headers on by default; account-enumeration oracles closed; credentials no longer written to logs.
|
|
51
|
+
- **Robust lifecycle.** Graceful shutdown on `SIGTERM`/`SIGINT` (drains in-flight requests, tears down mongo/redis/logger); fail-fast boot (Mongo and `AUTH_SALT` required); crash-loop protection for clustered workers.
|
|
52
|
+
- **Runtime.** ESM-only, Node ≥ 24, runs `.ts` sources natively with no build step. New helpers/models: `AppInstance`, `Lock`, `i18nService`, `IpDetector`, and test helpers (`getTestServerURL`, `serverInstance`).
|
|
43
53
|
|
|
44
54
|
### Breaking changes (v4 → v5)
|
|
45
55
|
|
|
46
|
-
Read the `5.0.0-rc.1` entry below for the full text and migration notes; the
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
- **
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
- **
|
|
53
|
-
Standard Schema). Legacy `{validate, cast}` validators, internal driver
|
|
54
|
-
classes, and Yup `req:` context in `.test()`/`.when()` removed; `ValidateService`
|
|
55
|
-
surface trimmed; `relatedRequest/QueryParameters` default to `null`.
|
|
56
|
-
- **Routing:** path syntax narrowed to literals, `:name`, and `{*name}` splats —
|
|
57
|
-
Express 5 optional params (`{:name}`) and inline regex are unsupported; replace
|
|
58
|
-
bare `_` route params with `*splat`. Route-type codegen requires statically
|
|
59
|
-
analyzable controllers. OpenAPI/documentation generation removed (returns later
|
|
60
|
-
with per-vendor `toJsonSchema`).
|
|
61
|
-
- **Models & auth:** all models must extend `BaseModel`. `AUTH_SALT` is required
|
|
62
|
-
(no default) and Mongo is required at boot. Default auth response changed to
|
|
63
|
-
`{ data: { token, user } }`. On upgrade, **all existing sessions and
|
|
64
|
-
recovery/verification links are invalidated** (token hardening); passwords
|
|
65
|
-
migrate silently on next login. `POST /auth/send-recovery-email` and
|
|
66
|
-
`/auth/send-verification` now return a uniform `200` (no account-existence
|
|
67
|
-
oracle) — update any frontend that branched on the old `400`. `RateLimiter`
|
|
68
|
-
now requires `IpDetector` earlier in the chain.
|
|
69
|
-
- **Removed / moved:** the email module moved to
|
|
70
|
-
`@adaptivestone/framework-module-email`; `staticFiles` middleware, `VIEWS`
|
|
71
|
-
folders, and `nodemailer-sendmail-transport` removed. The package `exports` map
|
|
72
|
-
is scoped to the public surface — internal subpaths are no longer importable
|
|
73
|
-
(see "Public API & stability" in the README).
|
|
56
|
+
Read the `5.0.0-rc.1` entry below for the full text and migration notes; the condensed list:
|
|
57
|
+
|
|
58
|
+
- **Runtime & deps:** Node ≥ 24, ESM-only (no CommonJS); Express 5, Mongoose 9, Vitest 4, i18next 24, `@redis/client` v6 (RESP3 default). Jest support and `minimist` CLI parsing removed.
|
|
59
|
+
- **Validation:** Yup is now an **optional peer dependency** (validator-agnostic Standard Schema). Legacy `{validate, cast}` validators, internal driver classes, and Yup `req:` context in `.test()`/`.when()` removed; `ValidateService` surface trimmed; `relatedRequest/QueryParameters` default to `null`.
|
|
60
|
+
- **Routing:** path syntax narrowed to literals, `:name`, and `{*name}` splats — Express 5 optional params (`{:name}`) and inline regex are unsupported; replace bare `_` route params with `*splat`. Route-type codegen requires statically analyzable controllers. OpenAPI/documentation generation removed (returns later with per-vendor `toJsonSchema`).
|
|
61
|
+
- **Models & auth:** all models must extend `BaseModel`. `AUTH_SALT` is required (no default) and Mongo is required at boot. Default auth response changed to `{ data: { token, user } }`. On upgrade, **all existing sessions and recovery/verification links are invalidated** (token hardening); passwords migrate silently on next login. `POST /auth/send-recovery-email` and `/auth/send-verification` now return a uniform `200` (no account-existence oracle) — update any frontend that branched on the old `400`. `RateLimiter` now requires `IpDetector` earlier in the chain.
|
|
62
|
+
- **Removed / moved:** the email module moved to `@adaptivestone/framework-module-email`; `staticFiles` middleware, `VIEWS` folders, and `nodemailer-sendmail-transport` removed. The package `exports` map is scoped to the public surface — internal subpaths are no longer importable (see "Public API & stability" in the README).
|
|
74
63
|
|
|
75
64
|
## [5.0.0-rc.9] - 2026-06-15
|
|
76
65
|
|
|
77
|
-
- **[FIX]** Regression in rc.8: a model whose `modelSchema` reuses a pre-built
|
|
78
|
-
mongoose `Schema` instance as a (sub-)document definition (`field: SubSchema`
|
|
79
|
-
or `[SubSchema]` — a standard Mongoose pattern) failed to type-check at every
|
|
80
|
-
`findOne(...)` call site with `TS2615` ("circularly references itself in mapped
|
|
81
|
-
type"). The rc.8 marker-scan (`HasTsOverride`) recursed over `keyof Schema`,
|
|
82
|
-
and a `Schema` instance isn't a constructor, so it wasn't treated as a leaf —
|
|
83
|
-
the scan descended into the instance's self-referential internals
|
|
84
|
-
(`childSchemas`, `options`, `session`, …). `IsLeafFieldDef` now treats a
|
|
85
|
-
`Schema` instance as a leaf (it can carry no `__tsType` marker anyway), so the
|
|
86
|
-
scan stops there. Type-only; a `tsc`-gate fixture pins it.
|
|
66
|
+
- **[FIX]** Regression in rc.8: a model whose `modelSchema` reuses a pre-built mongoose `Schema` instance as a (sub-)document definition (`field: SubSchema` or `[SubSchema]` — a standard Mongoose pattern) failed to type-check at every `findOne(...)` call site with `TS2615` ("circularly references itself in mapped type"). The rc.8 marker-scan (`HasTsOverride`) recursed over `keyof Schema`, and a `Schema` instance isn't a constructor, so it wasn't treated as a leaf — the scan descended into the instance's self-referential internals (`childSchemas`, `options`, `session`, …). `IsLeafFieldDef` now treats a `Schema` instance as a leaf (it can carry no `__tsType` marker anyway), so the scan stops there. Type-only; a `tsc`-gate fixture pins it.
|
|
87
67
|
|
|
88
68
|
## [5.0.0-rc.8] - 2026-06-15
|
|
89
69
|
|
|
90
|
-
- **[FIX]** Instance methods are now callable on the hydrated document without
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
`(schema.methods.x as …).call(doc, …)` cast. The caller-facing projection now
|
|
98
|
-
strips the authored `this` (a method accessed on its own document always has
|
|
99
|
-
the right `this` at runtime), while method bodies stay type-checked against
|
|
100
|
-
their declared `this`. Purely a type change, no runtime impact; a `tsc`-gate
|
|
101
|
-
test pins it.
|
|
102
|
-
|
|
103
|
-
- **[FIX]** A virtual now resolves to its getter's return type on the document
|
|
104
|
-
(e.g. `doc.fullName` is `string`) instead of the leaked raw definition
|
|
105
|
-
(`string & { get(): string; options: … }`). The virtuals slot fed to
|
|
106
|
-
Mongoose's inner document type was the raw `{ get, set, options }` object; it
|
|
107
|
-
is now the resolved `VirtualType<…>`, matching the override slot. Type-only.
|
|
108
|
-
|
|
109
|
-
- **[FIX]** `createdAt` / `updatedAt` are now typed as a non-null `Date` on the
|
|
110
|
-
hydrated document instead of `Date | null | undefined`. Mongoose always sets
|
|
111
|
-
the timestamps, so the nullable type only forced a needless guard at every
|
|
112
|
-
read. Type-only change.
|
|
113
|
-
|
|
114
|
-
- **[FIX]** Cleaner `TsTypeOverride` typing (rc.7 feature). The override mapping
|
|
115
|
-
no longer recurses into built-in instances (`ObjectId` refs, `Date`, `Map`) —
|
|
116
|
-
they showed as `ApplyTsOverrides<ObjectId, …>` in hovers though the recursion
|
|
117
|
-
was a no-op — and a marker-free schema (the common case) now skips the mapping
|
|
118
|
-
entirely, so its document type is the plain Mongoose inference with no wrapper
|
|
119
|
-
in hovers and no extra compile work. Type-only; no change to which types
|
|
120
|
-
resolve, only how cleanly.
|
|
70
|
+
- **[FIX]** Instance methods are now callable on the hydrated document without `this`-binding casts. A method whose body needs a narrower shape can declare an explicit `this: <bridge>` (a populated ref, a non-null plugin-reshaped field, reassignable sibling methods); that bridge was carried verbatim onto the document type, so a direct `doc.method(...)` call failed the this-context check (`TS2684`) — the framework-computed hydrated doc is deliberately not assignable to the narrower bridge — and every call site needed a `(schema.methods.x as …).call(doc, …)` cast. The caller-facing projection now strips the authored `this` (a method accessed on its own document always has the right `this` at runtime), while method bodies stay type-checked against their declared `this`. Purely a type change, no runtime impact; a `tsc`-gate test pins it.
|
|
71
|
+
|
|
72
|
+
- **[FIX]** A virtual now resolves to its getter's return type on the document (e.g. `doc.fullName` is `string`) instead of the leaked raw definition (`string & { get(): string; options: … }`). The virtuals slot fed to Mongoose's inner document type was the raw `{ get, set, options }` object; it is now the resolved `VirtualType<…>`, matching the override slot. Type-only.
|
|
73
|
+
|
|
74
|
+
- **[FIX]** `createdAt` / `updatedAt` are now typed as a non-null `Date` on the hydrated document instead of `Date | null | undefined`. Mongoose always sets the timestamps, so the nullable type only forced a needless guard at every read. Type-only change.
|
|
75
|
+
|
|
76
|
+
- **[FIX]** Cleaner `TsTypeOverride` typing (rc.7 feature). The override mapping no longer recurses into built-in instances (`ObjectId` refs, `Date`, `Map`) — they showed as `ApplyTsOverrides<ObjectId, …>` in hovers though the recursion was a no-op — and a marker-free schema (the common case) now skips the mapping entirely, so its document type is the plain Mongoose inference with no wrapper in hovers and no extra compile work. Type-only; no change to which types resolve, only how cleanly.
|
|
121
77
|
|
|
122
78
|
## [5.0.0-rc.7] - 2026-06-15
|
|
123
79
|
|
|
124
|
-
- **[NEW]** Per-field compile-time type overrides for plugin-reshaped fields. A
|
|
125
|
-
schema field intersected with the new `TsTypeOverride<T>` marker is typed as
|
|
126
|
-
`T` on `getModel(...).findOne()` results and method `this`, instead of the type
|
|
127
|
-
Mongoose infers from `type:` — so a field a runtime plugin reshapes
|
|
128
|
-
(`mongoose-intl`, encrypted fields, custom getters) keeps its static and
|
|
129
|
-
runtime types in sync, removing the casts that previously bridged the gap. The
|
|
130
|
-
marker is a phantom (`__tsType`, never set at runtime); applied by a deep
|
|
131
|
-
mapped type (`ApplyTsOverrides`) that recurses into nested objects and
|
|
132
|
-
subdocument arrays. Opt-in and a strict **no-op** for any field without the
|
|
133
|
-
marker, so existing models are unchanged.
|
|
80
|
+
- **[NEW]** Per-field compile-time type overrides for plugin-reshaped fields. A schema field intersected with the new `TsTypeOverride<T>` marker is typed as `T` on `getModel(...).findOne()` results and method `this`, instead of the type Mongoose infers from `type:` — so a field a runtime plugin reshapes (`mongoose-intl`, encrypted fields, custom getters) keeps its static and runtime types in sync, removing the casts that previously bridged the gap. The marker is a phantom (`__tsType`, never set at runtime); applied by a deep mapped type (`ApplyTsOverrides`) that recurses into nested objects and subdocument arrays. Opt-in and a strict **no-op** for any field without the marker, so existing models are unchanged.
|
|
134
81
|
|
|
135
82
|
## [5.0.0-rc.6] - 2026-06-14
|
|
136
83
|
|
|
137
|
-
- **[FIX]** The `User` auth helpers are now reusable on a **customized** `User`
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
methods (`generateToken`, `getPublic`, `send{Verification,PasswordRecovery}Email`)
|
|
141
|
-
were typed against the framework's own schema (`this: UserModelLite`), so on a
|
|
142
|
-
project model with a different shape every call site hit `TS2684` and needed a
|
|
143
|
-
cast. They're now typed against small structural contracts (`UserAuthDoc` /
|
|
144
|
-
`UserAuthInstance` / `UserAuthModel`, all newly exported) describing only the
|
|
145
|
-
fields each helper touches — the framework's `User` and a project's replacement
|
|
146
|
-
both satisfy them, and return types stay precise. This makes the supported
|
|
147
|
-
customization paths cast-free: `extends User` to **add** fields, or compose
|
|
148
|
-
(`extends BaseModel` + spread `User.modelStatics` / `modelInstanceMethods`) to
|
|
149
|
-
**reshape** them (an i18n `name`, a singular `role`, …) — a field-type
|
|
150
|
-
*replacement* can't go through `extends` (static-getter covariance, `TS2417`).
|
|
151
|
-
Both paths are documented on the `User` class. A `tsc`-gate test pins them.
|
|
152
|
-
|
|
153
|
-
- **[FIX]** Config-type codegen no longer drops env-only keys. A config value
|
|
154
|
-
read straight from the environment with no default (`saltSecret:
|
|
155
|
-
process.env.AUTH_SALT`) is `undefined` at gen time, so the value-based pass
|
|
156
|
-
omitted it from `getConfig('…')`'s type and every read needed an `as` cast.
|
|
157
|
-
Codegen now reads the config **source** (via `oxc-parser`, no value import) and
|
|
158
|
-
types a bare `process.env.X` as `string | undefined` (and `process.env.X!` as
|
|
159
|
-
`string`) — from the source, so the result is the same whether or not the var
|
|
160
|
-
happened to be set during codegen (deterministic output, no `--check` drift).
|
|
161
|
-
Keys without an env read (literals, `process.env.X || default`) are still typed
|
|
162
|
-
from their value as before. Secrets are never serialized (types only). Nested
|
|
163
|
-
keys and `NODE_ENV`-specific config files are handled.
|
|
84
|
+
- **[FIX]** The `User` auth helpers are now reusable on a **customized** `User` model without `this`-binding casts. The statics (`getUserByEmailAndPassword`, `getUserBy{Token,Email,VerificationToken,PasswordRecoveryToken}`) and instance methods (`generateToken`, `getPublic`, `send{Verification,PasswordRecovery}Email`) were typed against the framework's own schema (`this: UserModelLite`), so on a project model with a different shape every call site hit `TS2684` and needed a cast. They're now typed against small structural contracts (`UserAuthDoc` / `UserAuthInstance` / `UserAuthModel`, all newly exported) describing only the fields each helper touches — the framework's `User` and a project's replacement both satisfy them, and return types stay precise. This makes the supported customization paths cast-free: `extends User` to **add** fields, or compose (`extends BaseModel` + spread `User.modelStatics` / `modelInstanceMethods`) to **reshape** them (an i18n `name`, a singular `role`, …) — a field-type *replacement* can't go through `extends` (static-getter covariance, `TS2417`). Both paths are documented on the `User` class. A `tsc`-gate test pins them.
|
|
85
|
+
|
|
86
|
+
- **[FIX]** Config-type codegen no longer drops env-only keys. A config value read straight from the environment with no default (`saltSecret: process.env.AUTH_SALT`) is `undefined` at gen time, so the value-based pass omitted it from `getConfig('…')`'s type and every read needed an `as` cast. Codegen now reads the config **source** (via `oxc-parser`, no value import) and types a bare `process.env.X` as `string | undefined` (and `process.env.X!` as `string`) — from the source, so the result is the same whether or not the var happened to be set during codegen (deterministic output, no `--check` drift). Keys without an env read (literals, `process.env.X || default`) are still typed from their value as before. Secrets are never serialized (types only). Nested keys and `NODE_ENV`-specific config files are handled.
|
|
164
87
|
|
|
165
88
|
## [5.0.0-rc.5] - 2026-06-14
|
|
166
89
|
|
|
167
|
-
- **[FIX]** Route-type codegen extends the rc.4 untyped-`.js` degradation to
|
|
168
|
-
middleware in the `appInfo` provides chain. A controller guarded by an untyped
|
|
169
|
-
`.js` middleware (no sibling `.d.ts`) produced a gen file that did `import type
|
|
170
|
-
Mw from './Mw.js'` to build its `UnionAppInfoProvides<…>` chain — a `TS7016` in
|
|
171
|
-
a strict consumer build with no `allowJs`. Such a middleware is now dropped
|
|
172
|
-
from both the import and the chain (it contributes nothing to `appInfo`)
|
|
173
|
-
instead of breaking the typecheck. Typed middleware — `.ts`, `.js` with a
|
|
174
|
-
sibling `.d.ts`, or the framework's own (bare specifiers ship declarations) —
|
|
175
|
-
keep their precise `appInfo` contributions. Same incremental `.js` → `.ts`
|
|
176
|
-
migration goal as rc.4, now covering middleware as well as controllers.
|
|
90
|
+
- **[FIX]** Route-type codegen extends the rc.4 untyped-`.js` degradation to middleware in the `appInfo` provides chain. A controller guarded by an untyped `.js` middleware (no sibling `.d.ts`) produced a gen file that did `import type Mw from './Mw.js'` to build its `UnionAppInfoProvides<…>` chain — a `TS7016` in a strict consumer build with no `allowJs`. Such a middleware is now dropped from both the import and the chain (it contributes nothing to `appInfo`) instead of breaking the typecheck. Typed middleware — `.ts`, `.js` with a sibling `.d.ts`, or the framework's own (bare specifiers ship declarations) — keep their precise `appInfo` contributions. Same incremental `.js` → `.ts` migration goal as rc.4, now covering middleware as well as controllers.
|
|
177
91
|
|
|
178
92
|
## [5.0.0-rc.4] - 2026-06-14
|
|
179
93
|
|
|
180
|
-
- **[FIX]** Route-type codegen no longer emits an untyped self-import for `.js`
|
|
181
|
-
controllers. A schema-bearing controller still written in JavaScript with no
|
|
182
|
-
sibling `.d.ts` produced a gen file that did `import type Ctrl from
|
|
183
|
-
'./Ctrl.js'`, which fails with `TS7016` ("could not find a declaration file")
|
|
184
|
-
in a `strict` consumer build without `allowJs` — turning `rc.3`'s
|
|
185
|
-
now-succeeding `npm run gen` into a red typecheck. Such controllers now degrade
|
|
186
|
-
gracefully: the gen file skips the self-import and their inline request/query
|
|
187
|
-
schemas fall back to the base `Record<string, unknown>`. `.ts` controllers (and
|
|
188
|
-
`.js` with a sibling `.d.ts`) keep precise `InferOutput` types. Unblocks
|
|
189
|
-
incremental `.js` → `.ts` migration.
|
|
94
|
+
- **[FIX]** Route-type codegen no longer emits an untyped self-import for `.js` controllers. A schema-bearing controller still written in JavaScript with no sibling `.d.ts` produced a gen file that did `import type Ctrl from './Ctrl.js'`, which fails with `TS7016` ("could not find a declaration file") in a `strict` consumer build without `allowJs` — turning `rc.3`'s now-succeeding `npm run gen` into a red typecheck. Such controllers now degrade gracefully: the gen file skips the self-import and their inline request/query schemas fall back to the base `Record<string, unknown>`. `.ts` controllers (and `.js` with a sibling `.d.ts`) keep precise `InferOutput` types. Unblocks incremental `.js` → `.ts` migration.
|
|
190
95
|
|
|
191
96
|
## [5.0.0-rc.3] - 2026-06-13
|
|
192
97
|
|
|
193
|
-
- **[CHANGE]** Route-type codegen now skips controllers it can't statically
|
|
194
|
-
analyze instead of aborting the whole run. A controller whose `routes` /
|
|
195
|
-
`middleware` / `getHttpPath` uses a loop, conditional, computed value, or
|
|
196
|
-
`super` (e.g. one that extends another controller and merges `super.routes`) is
|
|
197
|
-
skipped with a warning; types are still generated for every other controller,
|
|
198
|
-
and the skipped one works at runtime (only its generated request types are
|
|
199
|
-
omitted). Previously a single such controller failed `npm run gen` for the
|
|
200
|
-
entire project.
|
|
98
|
+
- **[CHANGE]** Route-type codegen now skips controllers it can't statically analyze instead of aborting the whole run. A controller whose `routes` / `middleware` / `getHttpPath` uses a loop, conditional, computed value, or `super` (e.g. one that extends another controller and merges `super.routes`) is skipped with a warning; types are still generated for every other controller, and the skipped one works at runtime (only its generated request types are omitted). Previously a single such controller failed `npm run gen` for the entire project.
|
|
201
99
|
|
|
202
100
|
## [5.0.0-rc.2] - 2026-06-13
|
|
203
101
|
|
|
204
102
|
Patch over `rc.1`, fixing a regression for consumers that extend the framework.
|
|
205
103
|
|
|
206
|
-
- **[FIX]** Restored `./config/*` to the package `exports` map (it was dropped in
|
|
207
|
-
`rc.1`). Extending a framework default config — `import http from
|
|
208
|
-
'@adaptivestone/framework/config/http.js'`, then re-exporting an edited copy
|
|
209
|
-
from your own `src/config/http.ts` — threw `ERR_PACKAGE_PATH_NOT_EXPORTED` and
|
|
210
|
-
broke app boot. `config/*` is the intended Tier-2 extension surface and is
|
|
211
|
-
importable again.
|
|
104
|
+
- **[FIX]** Restored `./config/*` to the package `exports` map (it was dropped in `rc.1`). Extending a framework default config — `import http from '@adaptivestone/framework/config/http.js'`, then re-exporting an edited copy from your own `src/config/http.ts` — threw `ERR_PACKAGE_PATH_NOT_EXPORTED` and broke app boot. `config/*` is the intended Tier-2 extension surface and is importable again.
|
|
212
105
|
|
|
213
106
|
## [5.0.0-rc.1] - 2026-06-13
|
|
214
107
|
|
|
215
|
-
This is a big release that contains a lot of new features and breaking changes.
|
|
216
|
-
Main feature of that release is full TypeScript support including mongoose models.
|
|
108
|
+
This is a big release that contains a lot of new features and breaking changes. Main feature of that release is full TypeScript support including mongoose models.
|
|
217
109
|
|
|
218
110
|
### New Features
|
|
219
111
|
|
|
@@ -230,7 +122,7 @@ Main feature of that release is full TypeScript support including mongoose model
|
|
|
230
122
|
- **[NEW]** `IpDetector` middleware for detecting proxies and `X-Forwarded-For` headers.
|
|
231
123
|
- **[NEW]** Test helpers getTestServerURL and serverInstance.
|
|
232
124
|
- **[NEW]** Rate limiter middleware - add consumeResult function to allow user middleware as a regular rate limiter
|
|
233
|
-
- **[NEW]** Ip detector middleware - add getIpAdressFromIncomingMessage function to allow user middleware as a detector of id adresses without middleware
|
|
125
|
+
- **[NEW]** Ip detector middleware - add getIpAdressFromIncomingMessage function to allow user middleware as a detector of id adresses without middleware
|
|
234
126
|
- **[NEW]** Introduce i18nService (ability to user i18n not only inside middleware)
|
|
235
127
|
- **[NEW]** [Standard Schema](https://standardschema.dev/) validation. Yup ≥1.7, Zod, Valibot, ArkType supported.
|
|
236
128
|
- **[NEW]** Pluggable `ValidatorDriver` + `ValidateService.register(driver)` for custom validators.
|
|
@@ -515,7 +407,7 @@ Main feature of that release is full TypeScript support including mongoose model
|
|
|
515
407
|
|
|
516
408
|
## [5.0.0-beta.32] - 2025-08-21
|
|
517
409
|
|
|
518
|
-
- **[NEW]** Ip detector middleware - add getIpAdressFromIncomingMessage function to allow user middleware as a detector of id adresses without middleware
|
|
410
|
+
- **[NEW]** Ip detector middleware - add getIpAdressFromIncomingMessage function to allow user middleware as a detector of id adresses without middleware
|
|
519
411
|
|
|
520
412
|
---
|
|
521
413
|
|
|
@@ -541,7 +433,7 @@ Main feature of that release is full TypeScript support including mongoose model
|
|
|
541
433
|
|
|
542
434
|
## [5.0.0-beta.28] - 2025-07-29
|
|
543
435
|
|
|
544
|
-
- **[UPDATE]** Inside CLI allow to have a negative values
|
|
436
|
+
- **[UPDATE]** Inside CLI allow to have a negative values
|
|
545
437
|
- **[UPDATE]** Update deps.
|
|
546
438
|
|
|
547
439
|
---
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import AbstractCommand from '../modules/AbstractCommand.ts';
|
|
2
|
+
/**
|
|
3
|
+
* Generate an OpenAPI 3.1 document from the app's controllers.
|
|
4
|
+
*
|
|
5
|
+
* Boot-based: builds a `RouteRegistry` and registers every controller with
|
|
6
|
+
* `skipWrap` (no middleware instantiation, no mongo, no HTTP listen), then walks
|
|
7
|
+
* `flatten()` — the SAME route model codegen reads. Loading the controllers is
|
|
8
|
+
* what gives the generator the *live* schema objects needed to emit JSON Schema
|
|
9
|
+
* (the AST front-end only sees type references). OpenAPI is a cold, rare run, so
|
|
10
|
+
* the one-time load is fine.
|
|
11
|
+
*/
|
|
12
|
+
declare class OpenApi extends AbstractCommand {
|
|
13
|
+
static get description(): string;
|
|
14
|
+
static isShouldInitModels: boolean;
|
|
15
|
+
static isShouldGetModelPaths: boolean;
|
|
16
|
+
static get commandArguments(): {
|
|
17
|
+
output: {
|
|
18
|
+
type: "string";
|
|
19
|
+
description: string;
|
|
20
|
+
};
|
|
21
|
+
};
|
|
22
|
+
run(): Promise<boolean>;
|
|
23
|
+
/** Read `name`/`description`/`version`/`author.email` from the consumer's package.json. */
|
|
24
|
+
private readPackageInfo;
|
|
25
|
+
}
|
|
26
|
+
export default OpenApi;
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import AbstractCommand from "../modules/AbstractCommand.js";
|
|
4
|
+
import { generateOpenApi, } from "../services/documentation/OpenApiGenerator.js";
|
|
5
|
+
/**
|
|
6
|
+
* Generate an OpenAPI 3.1 document from the app's controllers.
|
|
7
|
+
*
|
|
8
|
+
* Boot-based: builds a `RouteRegistry` and registers every controller with
|
|
9
|
+
* `skipWrap` (no middleware instantiation, no mongo, no HTTP listen), then walks
|
|
10
|
+
* `flatten()` — the SAME route model codegen reads. Loading the controllers is
|
|
11
|
+
* what gives the generator the *live* schema objects needed to emit JSON Schema
|
|
12
|
+
* (the AST front-end only sees type references). OpenAPI is a cold, rare run, so
|
|
13
|
+
* the one-time load is fine.
|
|
14
|
+
*/
|
|
15
|
+
class OpenApi extends AbstractCommand {
|
|
16
|
+
static get description() {
|
|
17
|
+
return 'Generate an OpenAPI 3.1 JSON document from controllers and routes';
|
|
18
|
+
}
|
|
19
|
+
// No DB / no model paths — pure route + schema introspection.
|
|
20
|
+
static isShouldInitModels = false;
|
|
21
|
+
static isShouldGetModelPaths = false;
|
|
22
|
+
static get commandArguments() {
|
|
23
|
+
return {
|
|
24
|
+
output: {
|
|
25
|
+
type: 'string',
|
|
26
|
+
description: 'Output file path. Omit to print to stdout.',
|
|
27
|
+
},
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
async run() {
|
|
31
|
+
// 1. Build the route registry without an HttpServer (its ctor binds a port).
|
|
32
|
+
const { RouteRegistry } = await import("../services/http/routing/RouteRegistry.js");
|
|
33
|
+
const { default: ControllerManager } = await import("../controllers/index.js");
|
|
34
|
+
const registry = new RouteRegistry();
|
|
35
|
+
this.app.httpServer = {
|
|
36
|
+
routeRegistry: registry,
|
|
37
|
+
};
|
|
38
|
+
const controllerManager = new ControllerManager(this.app);
|
|
39
|
+
this.app.controllerManager = controllerManager;
|
|
40
|
+
await controllerManager.initControllers({ skipWrap: true });
|
|
41
|
+
const routes = registry.flatten();
|
|
42
|
+
// 2. Document metadata from package.json + http config.
|
|
43
|
+
const info = await this.readPackageInfo();
|
|
44
|
+
const http = this.app.getConfig('http');
|
|
45
|
+
const servers = [
|
|
46
|
+
{
|
|
47
|
+
url: `http://localhost:${http.port ?? 3300}`,
|
|
48
|
+
description: 'Localhost',
|
|
49
|
+
},
|
|
50
|
+
...(http.myDomain
|
|
51
|
+
? [{ url: http.myDomain, description: 'Domain from config' }]
|
|
52
|
+
: []),
|
|
53
|
+
];
|
|
54
|
+
// 3. Generate.
|
|
55
|
+
const warnings = [];
|
|
56
|
+
const doc = await generateOpenApi(routes, {
|
|
57
|
+
info,
|
|
58
|
+
servers,
|
|
59
|
+
onWarning: (m) => warnings.push(m),
|
|
60
|
+
});
|
|
61
|
+
if (warnings.length > 0) {
|
|
62
|
+
this.logger?.warn(`OpenAPI: ${warnings.length} schema(s) could not be fully introspected:\n ${warnings.join('\n ')}`);
|
|
63
|
+
}
|
|
64
|
+
// 4. Emit.
|
|
65
|
+
const json = JSON.stringify(doc, null, 2);
|
|
66
|
+
const output = this.args.output;
|
|
67
|
+
if (output) {
|
|
68
|
+
await fs.writeFile(output, json);
|
|
69
|
+
this.logger?.info(`OpenAPI document written to ${output}`);
|
|
70
|
+
}
|
|
71
|
+
else {
|
|
72
|
+
console.log(json);
|
|
73
|
+
}
|
|
74
|
+
return true;
|
|
75
|
+
}
|
|
76
|
+
/** Read `name`/`description`/`version`/`author.email` from the consumer's package.json. */
|
|
77
|
+
async readPackageInfo() {
|
|
78
|
+
const fallback = {
|
|
79
|
+
title: 'API',
|
|
80
|
+
description: undefined,
|
|
81
|
+
version: '0.0.0',
|
|
82
|
+
};
|
|
83
|
+
const pkgPath = process.env.npm_package_json ?? path.join(process.cwd(), 'package.json');
|
|
84
|
+
try {
|
|
85
|
+
const pkg = JSON.parse(await fs.readFile(pkgPath, 'utf8'));
|
|
86
|
+
const email = typeof pkg.author === 'object' ? pkg.author?.email : undefined;
|
|
87
|
+
return {
|
|
88
|
+
title: pkg.name ?? fallback.title,
|
|
89
|
+
description: pkg.description,
|
|
90
|
+
version: pkg.version ?? fallback.version,
|
|
91
|
+
...(email ? { contact: { email } } : {}),
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
catch {
|
|
95
|
+
this.logger?.warn(`OpenAPI: could not read package.json at ${pkgPath}; using defaults.`);
|
|
96
|
+
return fallback;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
export default OpenApi;
|
|
101
|
+
//# sourceMappingURL=OpenApi.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"OpenApi.js","sourceRoot":"","sources":["../../src/commands/OpenApi.ts"],"names":[],"mappings":"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"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import AbstractCommand from '../modules/AbstractCommand.ts';
|
|
2
|
+
/**
|
|
3
|
+
* Print the project's route tree — "what's mounted in my app".
|
|
4
|
+
*
|
|
5
|
+
* Boot-based, no DB / no port: builds a `RouteRegistry` and registers every
|
|
6
|
+
* controller with `skipWrap` (no middleware instantiation, no mongo, no HTTP
|
|
7
|
+
* listen), then renders the SAME tree the server logs at boot. Mirrors the
|
|
8
|
+
* `openapi` command's registry build and reuses `formatRouteTree`, so there is
|
|
9
|
+
* one source of truth for "what routes exist".
|
|
10
|
+
*/
|
|
11
|
+
declare class Routes extends AbstractCommand {
|
|
12
|
+
static get description(): string;
|
|
13
|
+
static isShouldInitModels: boolean;
|
|
14
|
+
static isShouldGetModelPaths: boolean;
|
|
15
|
+
run(): Promise<boolean>;
|
|
16
|
+
}
|
|
17
|
+
export default Routes;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import AbstractCommand from "../modules/AbstractCommand.js";
|
|
2
|
+
import { formatRouteTree } from "../services/http/routing/formatTree.js";
|
|
3
|
+
/**
|
|
4
|
+
* Print the project's route tree — "what's mounted in my app".
|
|
5
|
+
*
|
|
6
|
+
* Boot-based, no DB / no port: builds a `RouteRegistry` and registers every
|
|
7
|
+
* controller with `skipWrap` (no middleware instantiation, no mongo, no HTTP
|
|
8
|
+
* listen), then renders the SAME tree the server logs at boot. Mirrors the
|
|
9
|
+
* `openapi` command's registry build and reuses `formatRouteTree`, so there is
|
|
10
|
+
* one source of truth for "what routes exist".
|
|
11
|
+
*/
|
|
12
|
+
class Routes extends AbstractCommand {
|
|
13
|
+
static get description() {
|
|
14
|
+
return 'Print the project route tree (what is mounted in the app)';
|
|
15
|
+
}
|
|
16
|
+
// No DB / no model paths — pure route introspection.
|
|
17
|
+
static isShouldInitModels = false;
|
|
18
|
+
static isShouldGetModelPaths = false;
|
|
19
|
+
async run() {
|
|
20
|
+
// Build the route registry without an HttpServer (its ctor binds a port).
|
|
21
|
+
const { RouteRegistry } = await import("../services/http/routing/RouteRegistry.js");
|
|
22
|
+
const { default: ControllerManager } = await import("../controllers/index.js");
|
|
23
|
+
const registry = new RouteRegistry();
|
|
24
|
+
this.app.httpServer = {
|
|
25
|
+
routeRegistry: registry,
|
|
26
|
+
};
|
|
27
|
+
const controllerManager = new ControllerManager(this.app);
|
|
28
|
+
this.app.controllerManager = controllerManager;
|
|
29
|
+
await controllerManager.initControllers({ skipWrap: true });
|
|
30
|
+
console.log(formatRouteTree(registry));
|
|
31
|
+
return true;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
export default Routes;
|
|
35
|
+
//# sourceMappingURL=Routes.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"Routes.js","sourceRoot":"","sources":["../../src/commands/Routes.ts"],"names":[],"mappings":"AAAA,OAAO,eAAe,MAAM,+BAA+B,CAAC;AAE5D,OAAO,EAAE,eAAe,EAAE,MAAM,wCAAwC,CAAC;AAEzE;;;;;;;;GAQG;AACH,MAAM,MAAO,SAAQ,eAAe;IAClC,MAAM,KAAK,WAAW;QACpB,OAAO,2DAA2D,CAAC;IACrE,CAAC;IAED,qDAAqD;IACrD,MAAM,CAAC,kBAAkB,GAAG,KAAK,CAAC;IAClC,MAAM,CAAC,qBAAqB,GAAG,KAAK,CAAC;IAErC,KAAK,CAAC,GAAG;QACP,0EAA0E;QAC1E,MAAM,EAAE,aAAa,EAAE,GAAG,MAAM,MAAM,CACpC,2CAA2C,CAC5C,CAAC;QACF,MAAM,EAAE,OAAO,EAAE,iBAAiB,EAAE,GAAG,MAAM,MAAM,CACjD,yBAAyB,CAC1B,CAAC;QACF,MAAM,QAAQ,GAAG,IAAI,aAAa,EAAE,CAAC;QACrC,IAAI,CAAC,GAAG,CAAC,UAAU,GAAG;YACpB,aAAa,EAAE,QAAQ;SACC,CAAC;QAC3B,MAAM,iBAAiB,GAAG,IAAI,iBAAiB,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAC1D,IAAI,CAAC,GAAG,CAAC,iBAAiB,GAAG,iBAAiB,CAAC;QAC/C,MAAM,iBAAiB,CAAC,eAAe,CAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC,CAAC;QAE5D,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC,QAAQ,CAAC,CAAC,CAAC;QACvC,OAAO,IAAI,CAAC;IACd,CAAC;;AAGH,eAAe,MAAM,CAAC"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
declare const _default: {
|
|
2
|
+
/**
|
|
3
|
+
* Cache backend.
|
|
4
|
+
* - `'memory'` (default) — per-process `Map`; needs no external service, so a
|
|
5
|
+
* plain install never loads `@redis/client`.
|
|
6
|
+
* - `'redis'` — shared/multi-node cache; lazy-loads `@redis/client` (an
|
|
7
|
+
* optional peer dependency — install it to use this driver).
|
|
8
|
+
*
|
|
9
|
+
* Override per environment via `CACHE_DRIVER`. The cache key namespace is
|
|
10
|
+
* shared with the rate limiter and lives in `config/redis.ts` (`namespace`).
|
|
11
|
+
*/
|
|
12
|
+
driver: "memory" | "redis";
|
|
13
|
+
};
|
|
14
|
+
export default _default;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export default {
|
|
2
|
+
/**
|
|
3
|
+
* Cache backend.
|
|
4
|
+
* - `'memory'` (default) — per-process `Map`; needs no external service, so a
|
|
5
|
+
* plain install never loads `@redis/client`.
|
|
6
|
+
* - `'redis'` — shared/multi-node cache; lazy-loads `@redis/client` (an
|
|
7
|
+
* optional peer dependency — install it to use this driver).
|
|
8
|
+
*
|
|
9
|
+
* Override per environment via `CACHE_DRIVER`. The cache key namespace is
|
|
10
|
+
* shared with the rate limiter and lives in `config/redis.ts` (`namespace`).
|
|
11
|
+
*/
|
|
12
|
+
driver: (process.env.CACHE_DRIVER || 'memory'),
|
|
13
|
+
};
|
|
14
|
+
//# sourceMappingURL=cache.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cache.js","sourceRoot":"","sources":["../../src/config/cache.ts"],"names":[],"mappings":"AAAA,eAAe;IACb;;;;;;;;;OASG;IACH,MAAM,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,YAAY,IAAI,QAAQ,CAAuB;CACrE,CAAC"}
|
|
@@ -189,6 +189,11 @@ class ControllerManager extends Base {
|
|
|
189
189
|
}
|
|
190
190
|
continue;
|
|
191
191
|
}
|
|
192
|
+
// Tag the controller so the OpenAPI generator can derive tags +
|
|
193
|
+
// operationIds without re-deriving them from the path.
|
|
194
|
+
if (entry.meta) {
|
|
195
|
+
entry.meta.controllerClass ??= ctrlName;
|
|
196
|
+
}
|
|
192
197
|
handlers.push({
|
|
193
198
|
method: upperVerb,
|
|
194
199
|
path: convertPathSyntax(pathKey),
|
|
@@ -346,12 +351,26 @@ class ControllerManager extends Base {
|
|
|
346
351
|
return await Promise.resolve(original(req, res, next));
|
|
347
352
|
}
|
|
348
353
|
catch (err) {
|
|
349
|
-
|
|
350
|
-
//
|
|
351
|
-
// error finalizer instead of crashing with ERR_HTTP_HEADERS_SENT.
|
|
354
|
+
// A handler that already streamed can't be sent anything — hand off to
|
|
355
|
+
// the error finalizer instead of crashing with ERR_HTTP_HEADERS_SENT.
|
|
352
356
|
if (res.headersSent) {
|
|
357
|
+
logger?.error(err);
|
|
353
358
|
return next(err);
|
|
354
359
|
}
|
|
360
|
+
// Error-handler registry: consumer-registered handlers first, then the
|
|
361
|
+
// built-ins (`HttpError` mapper, mongoose validation safety net) —
|
|
362
|
+
// first `instanceof` match returning non-null wins. Each entry carries
|
|
363
|
+
// its own log level: `verbose` for deliberate HttpError control flow,
|
|
364
|
+
// `warn` for the safety net's schema-gap signal, `warn` default for
|
|
365
|
+
// consumer entries.
|
|
366
|
+
const resolved = app.httpServer
|
|
367
|
+
? await app.httpServer.resolveError(err, req)
|
|
368
|
+
: null;
|
|
369
|
+
if (resolved) {
|
|
370
|
+
logger?.[resolved.logLevel](err);
|
|
371
|
+
return res.status(resolved.status).json(resolved.body);
|
|
372
|
+
}
|
|
373
|
+
logger?.error(err);
|
|
355
374
|
return res.status(500).json({
|
|
356
375
|
message: 'Platform error. Please check later or contact support',
|
|
357
376
|
});
|
|
@@ -426,7 +445,12 @@ function buildHandlerEntry(spec, controller) {
|
|
|
426
445
|
const entry = {
|
|
427
446
|
// biome-ignore lint/complexity/noBannedTypes: handler is a user-provided callable
|
|
428
447
|
handler: obj.handler.bind(controller),
|
|
429
|
-
meta: {
|
|
448
|
+
meta: {
|
|
449
|
+
methodName: handlerName || undefined,
|
|
450
|
+
...(typeof obj.description === 'string'
|
|
451
|
+
? { description: obj.description }
|
|
452
|
+
: {}),
|
|
453
|
+
},
|
|
430
454
|
};
|
|
431
455
|
if (obj.request != null) {
|
|
432
456
|
// biome-ignore lint/suspicious/noExplicitAny: Standard Schema validator passthrough
|