@lenne.tech/nest-server 12.13.0 → 12.14.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.
@@ -351,7 +351,7 @@ This pattern is currently applied to:
351
351
  | S3 Connection Pool & Download Guard | `s3.maxSockets`, `s3.connectionTimeoutMs`, `s3.socketTimeoutMs`, `s3.downloadIdleTimeoutMs`; `file.downloadIdleTimeoutMs`, `file.downloadCaching` | Numeric — invalid → default, never off (Family C without opt-out) + Explicit Enum | **12.8.9, after a production outage**: S3 downloads delivered with a bare `stream.pipe(res)` kept their sockets when clients aborted; after 50 the SDK's pool was full, every S3 request waited forever (health check green), heap OOM hours later. Since then: `CoreS3Service` builds its client with OWN agents (`maxSockets` **200**, keep-alive), `connectionTimeout` **15 000** per attempt (the SDK starts it when the request is CREATED, so it also bounds the wait for a free socket — a short value fails healthy downloads under load; the SDK retries a timed-out attempt, 3 attempts in all, so a download that gets no socket answers **503** + `Retry-After: 5` after about 46 s — keep 3 × the value below the reverse proxy's read timeout, commonly 60 s), `socketTimeout` **120 000** (inactivity backstop for every request, uploads and copies included). The SDK's `requestTimeout` stops at the headers and its socket timeout destroys the body WITH an error (a process crash without a listener), so the real guard is `guardIdleStream()` (`common/helpers/idle-stream.helper.ts`): every stream from `getObject()` (`s3.downloadIdleTimeoutMs`, 30 000) and from `CoreFileService.getFileStream()` / `getFileStreamByName()` (`file.downloadIdleTimeoutMs`, 30 000 — GridFS cursors, file handles) is destroyed after that long WITHOUT READ PROGRESS, measured on the consumer side (`_read`) and at the source; a slow reader that keeps reading is never cut off; code that opens a stream and reads it LATE (an archive appending every file first) breaks — per call `downloadIdleTimeoutMs: false` (`FileServiceOptions`) / `getObject(key, { idleTimeoutMs: false })` opts out. `pipeFileToResponse()` destroys the source when the client goes — the response's `close`, the request's `close` (before its end and while the response is unfinished — Node closes a request whose body was read to the end by itself, a POST export stays deliverable) or the socket's `end`/`close`: measured under a k6 abort storm, about one in six aborted downloads never got a `close` on the response and reported it only through the request or the socket — and at once when it had ALREADY gone (`isResponseGone()`: response destroyed/closed OR request destroyed before its end OR socket destroyed; a client that gave up while waiting for a socket — the avalanche path); the routes pass an `abortSignal` (`downloadAbortSignal()`, exported: the same client-gone signals) down to `GetObjectCommand` and open the stream through `openDownloadStream()` (exported since 12.9.2 for a project's own routes): no store request for a gone client, `RESPONSE_GONE` instead of an ERROR when the store request failed because the client left (an aborted S3 request rejects with `AbortError`), a late stream destroyed, `TimeoutError` → 503 + `Retry-After`. An exhausted pool is logged as an ERROR once per minute with numbers (`getSocketPoolStats()` exposes them); deliberately NOT a health-check failure. `file.downloadCaching`: `'none'` (default, `private, no-store`) or `'revalidate'` (`private, no-cache` — the browser revalidates every use, `304` after the rights check without a store read); both send a WEAK `ETag` `W/"<id>"` (bytes under an id never change, but a `compression` middleware sends a gzip and an identity representation of the same file — RFC 9110 §8.8.3 forbids one strong validator for both; `If-None-Match` compares weakly) and `Content-Length`. The reference `src/main.ts` uses `compression.filter` (no gzip for JPEG/PNG/PDF/ZIP). Pinned by `tests/unit/idle-stream.spec.ts`, `tests/unit/core-file.controller.spec.ts`, `tests/unit/download-idle-opt-out.spec.ts` and `tests/s3-download-resilience.e2e-spec.ts` (real RustFS: dropped streams, abort storm with bare `pipe()`, clients giving up while waiting, 500 parallel downloads with `maxSockets: 4`, slow reader; mutations `idle-guard-*`, `s3-get-object-*`, `pipe-file-to-response-*`, `download-route-keeps-late-stream`, `file-stream-drops-idle-opt-out`). Implementation: `core-s3.service.ts`, `core-file.controller.ts`, `core-file.service.ts` |
352
352
  | TUS S3 Staging | `tus.s3Staging` | Explicit Boolean (default ON when S3 configured) | `true` when `s3` is configured, otherwise inert. Stages in-progress uploads in `s3.stagingBucket` via `@tus/s3-store` instead of `tus.uploadDir` on local disk, so resumable uploads survive replica restarts and need no sticky sessions. Set `false` to force local disk. Missing OPTIONAL peer `@tus/s3-store` → warning + fall back to local disk (NOT a boot failure). **Give the staging bucket a lifecycle rule expiring incomplete multipart uploads** — the framework's own expiration cleanup is skipped in S3 mode (S3 is the right place for that policy), so aborted uploads otherwise accumulate parts nothing removes |
353
353
  | TUS Configuration Source, Path & Extensions | `tus` (server config) / `TusModule.forRoot({ config })` | Enabled by Default + explicit-config-wins | **Since 11.42.9 `TusModule.forRoot()` without `config` reads the server config's `tus` key** (`ConfigService.get('tus')`, the zero-config rule `CoreBetterAuthModule.forRoot()` follows); an explicit `config` wins. Before, the key was never read: `tus: false`, `allowedTypes`, `maxSize`, `roles` in `config.env.ts` did nothing — real projects had upload restrictions they believed were enforced. **`path`** has three readings (`applyPath()`): unset → follows the controller's route; a new route (`/uploads`) → mounts the registered controller there (writes `PATH_METADATA`, config wins like the roles; the declared route is remembered per class and restored by a later `forRoot()` without `path`); a path ENDING with the controller's route (`/api/tus`, `/files/tus`) → the PUBLIC URL: the controller stays and upload URLs use it. The third reading is load-bearing: it was the only working setting under a global prefix or a prefix-stripping proxy before 11.42.9, and treating it as a route doubled the prefix (`/api/api/tus`, 404 on every upload — caught in the second pre-release review). The upload URL (`Location`) is built from the path the creation request arrived at (`uploadCollectionPath(req)`), or from `path` when that is longer and ends with it (proxy strip); `@tus/server` built it from `path` alone, which broke every resume below a global prefix, a URI version or a project route. **`relativeLocation`** (new): the framework owns `generateUrl`, which takes precedence over `@tus/server`'s option of that name, so it is honoured from `tus.relativeLocation` AND from the tus server's own options (a vendored core may pass it there). **Extensions**: `@tus/server` consults no flag, so `creation`, `creationWithUpload` and `termination` are enforced by `CoreTusService` — the store's advertised `extensions` are narrowed, and `assertExtensionEnabled()` answers 501 inside the server's `onIncomingRequest` / `onUploadCreate` options (not in the overridable hook, so an override without `super` cannot reopen it). `checksum` / `concatenation` have no effect: neither built-in store supports them. `configure(false)` now yields a DISABLED config (before it kept the defaults and started a tus server behind a module with no endpoint). Implementation: `tus.module.ts`, `core-tus.service.ts` |
354
- | Health Check | `healthCheck` | Presence Implies Enabled | Absent → no endpoints. Any object registers `GET /health-check` + the `healthCheck` query; **`enabled: false` leaves them out (honoured since 11.42.9 — before, it was declared and ignored)**. Individual checks under `configs.*` each have their own `enabled`. **Readiness (12.11.0): `healthCheck.readiness`, Boolean Shorthand + Presence Implies Enabled — absent = no readiness route, the health check exactly as before.** `true` / `{}` registers `GET /health-check/ready` (public, REST only, its own controller `CoreHealthCheckReadinessController`, so without it the route does not exist: 404) with the default checks `['database', 'build']`; `readiness.checks` lists the checks of `configs` it runs (`database` — MongoDB ping and every SQL source —, `memoryHeap`, `memoryRss`, `storage`, `build`; a comma-separated string as `NSC__HEALTH_CHECK__READINESS__CHECKS` gives it; unknown names ignored with one warning; not a list or string → the defaults; `[]` → only project indicators), with key, thresholds and options from `configs.<check>` and whatever `configs.<check>.enabled` says (that flag decides for liveness). `false` / `{ enabled: false }` registers nothing. 200 while every check is up, 503 when one is down, and `shutting_down` from the first shutdown signal on when `installGracefulShutdown()` handles it (it marks the shutdown before its `shutdownDelayMs` wait — `shutdown-state.helper.ts`, mutations `readiness-ignores-shutdown`, `graceful-shutdown-skips-drain-mark`); Terminus' own state alone comes only inside `app.close()`. **Project checks**: extend `CoreHealthCheckService`, override the protected `additionalHealthIndicators(kind: 'liveness' \| 'readiness')` (default `[]`, may be async) and return Terminus indicators; register the subclass with `CoreModule.forRoot(env, { healthCheck: { service } })` (`readinessController` replaces the readiness controller). `CoreHealthCheckModule` imported as it is stays the pre-12.11.0 module; `CoreHealthCheckModule.forRoot()` adds the readiness controller and the service override (a dynamic module extends the static metadata, so the liveness controller is never registered twice). Pinned by `tests/unit/health-check-readiness.spec.ts`, `tests/unit/core-module-signatures.spec.ts`. Implementation: `core.module.ts`, `modules/health-check/` (`resolveHealthCheckReadiness()` in `core-health-check.helpers.ts`) |
354
+ | Health Check | `healthCheck` | Presence Implies Enabled | Absent → no endpoints. Any object registers `GET /health-check` + the `healthCheck` query; **`enabled: false` leaves them out (honoured since 11.42.9 — before, it was declared and ignored)**. Individual checks under `configs.*` each have their own `enabled`. **Database ping (12.14.0):** `configs.database.options.timeout` (ms) bounds the MongoDB ping and every SQL source; default 2000 (`DEFAULT_DATABASE_PING_TIMEOUT_MS`; before: 300 ms for MongoDB without options, otherwise 1000 ms, SQL 1000 ms). The MongoDB ping is the core's own (`CoreHealthCheckService.pingMongoDb()`): a real `ping` that waits for the driver's server selection, WITHOUT Terminus' `readyState` gate, which reported a reachable replica set as down whenever the driver briefly saw no primary (Mongoose sets `disconnected` then) — more than 95 % of all "database down" alarms on a cluster with managed replica sets. Connection: `options.connection`, else the injected `@InjectConnection()` (property, so subclasses keep it). Pinned by `tests/unit/health-check-mongo-ping.spec.ts` (mutations `health-check-mongo-ping-*`). **Readiness (12.11.0): `healthCheck.readiness`, Boolean Shorthand + Presence Implies Enabled — absent = no readiness route, the health check exactly as before.** `true` / `{}` registers `GET /health-check/ready` (public, REST only, its own controller `CoreHealthCheckReadinessController`, so without it the route does not exist: 404) with the default checks `['database', 'build']`; `readiness.checks` lists the checks of `configs` it runs (`database` — MongoDB ping and every SQL source —, `memoryHeap`, `memoryRss`, `storage`, `build`; a comma-separated string as `NSC__HEALTH_CHECK__READINESS__CHECKS` gives it; unknown names ignored with one warning; not a list or string → the defaults; `[]` → only project indicators), with key, thresholds and options from `configs.<check>` and whatever `configs.<check>.enabled` says (that flag decides for liveness). `false` / `{ enabled: false }` registers nothing. 200 while every check is up, 503 when one is down, and `shutting_down` from the first shutdown signal on when `installGracefulShutdown()` handles it (it marks the shutdown before its `shutdownDelayMs` wait — `shutdown-state.helper.ts`, mutations `readiness-ignores-shutdown`, `graceful-shutdown-skips-drain-mark`); Terminus' own state alone comes only inside `app.close()`. **Project checks**: extend `CoreHealthCheckService`, override the protected `additionalHealthIndicators(kind: 'liveness' \| 'readiness')` (default `[]`, may be async) and return Terminus indicators; register the subclass with `CoreModule.forRoot(env, { healthCheck: { service } })` (`readinessController` replaces the readiness controller). `CoreHealthCheckModule` imported as it is stays the pre-12.11.0 module; `CoreHealthCheckModule.forRoot()` adds the readiness controller and the service override (a dynamic module extends the static metadata, so the liveness controller is never registered twice). Pinned by `tests/unit/health-check-readiness.spec.ts`, `tests/unit/core-module-signatures.spec.ts`. Implementation: `core.module.ts`, `modules/health-check/` (`resolveHealthCheckReadiness()` in `core-health-check.helpers.ts`) |
355
355
  | Cron Job Deduplication | per job: `distributed` in `CronJobConfig` | Explicit Boolean | **`true` when `redis` is configured, otherwise `false`** — a single-replica project that upgrades must not silently gain a `cron-locks` collection, a lease write per tick, and a new way for a tick to be skipped. A Redis-less multi-replica fleet opts in per job with `distributed: true` (lease in the SQL lease table of the default source, else in MongoDB). Mechanism: BullMQ job scheduler when Redis + the OPTIONAL peer `bullmq` are present AND `cronTime` is a string without `utcOffset`; otherwise local timer + lease (Redis `SET NX`, else the SQL lease table of the default source (`lt_locks`), else a TTL-indexed `cron-locks` document). Tick lease TTL 3600 s. **Leases fail open** — an unreachable lease store runs the tick everywhere rather than stopping all scheduled work fleet-wide. **`runOnInit` (default `true`) deduplicates over a FIXED per-job key with a 300 s TTL**, because replicas do not share a boot instant: replicas booting within 5 min run the startup tick once between them, and a replica restarting inside that window SKIPS its startup tick — set `distributed: false` on jobs whose `runOnInit` work is per-process (warming a process-local cache). No constructor change needed: `CoreModule` fills `core-cron-jobs.registry.ts` via `CoreCronJobsInitializer` and `CoreCronJobs` reads it lazily; explicit `{ connection, redisService }` in `CoreCronJobsOptions` wins. With neither source it warns once and every replica runs every tick. **A BullMQ schedule lost in Redis comes back (12.1.1+)**: `upsertJobScheduler` writes it once at bootstrap, and a Redis restart without persistence, a FLUSHDB or an eviction removed it with nothing re-registering it, so no replica ran the job until the next deploy. `restoreBullSchedulers()` now runs after every `ready` of the queue connection and every `bullSchedulerCheckIntervalMs` (protected, 60000; `0` switches only the timer off) and registers the schedules the queue's listing (`getJobSchedulers()`) no longer contains, with a warning — the listing, because `getJobScheduler()` does not exist before bullmq 5.23 and answers a deleted scheduler with an object up to 5.40.2, both inside the peer range. Only MISSING ones: an upsert of an existing scheduler removes its last planned job even when it is due and waits for a free worker, so a blind periodic upsert would drop that tick. A scheduler `removeStaleBullSchedulers()` removed on purpose carries a `cron-scheduler-removed:<job>` key, so a replica of the previous version still running in a rolling deploy does not bring it back (a job moved to a local timer would otherwise run twice per tick); the next BullMQ registration of that job deletes the key, and a real data loss takes it along. Only the schedule comes back (no second `runOnInit`, no second registry entry); a tick that fell due while it was missing is not run. **Changing a schedule at runtime (12.11.0): `rescheduleCronJob(name, schedule)`**, public — a cron expression or date (time zone / UTC offset kept) or `{ cronTime, timeZone }` / `{ cronTime, utcOffset }`; validated first (an invalid expression, an unknown zone or a past date rejects, the job stays as it was); calls run one after the other; rejects for a job that is not registered (unknown, disabled, before bootstrap, after shutdown). Only the schedule changes: `distributed`, `runParallel`, `throwException`, the leases and `bullJobOptions` stay. Local timer: the timer is replaced, a distributed tick leases on the NEW schedule's instant, a recurring job the Hub stopped stays stopped, `runOnInit` is not repeated. BullMQ: the scheduler is upserted with the new pattern and `bullJobOptions` — skipped when Redis already holds exactly that pattern and time zone, so N replicas calling it plan no tick twice —, the Hub's registry entry is replaced, and `restoreBullSchedulers()` restores the NEW schedule; Redis refusing the upsert rejects and keeps the old schedule. A schedule BullMQ cannot express (a date, a UTC offset) moves the job to a local timer with lease and removes its scheduler WITH the `cron-scheduler-removed:<job>` marker (marker first), so replicas still scheduling it through BullMQ do not restore it; a cron expression moves it back and deletes the marker. A BullMQ schedule changes fleet-wide, a local timer per process — call it on every replica; it is not stored, the next bootstrap schedules from the configuration (re-apply after `super.onApplicationBootstrap()`). Pinned by `tests/unit/core-cron-jobs-reschedule.spec.ts`. **Since 12.1.1 (DEV-3896)**: (1) a timer job's tick lease is keyed on the tick's SCHEDULED instant, captured from `nextDate()` when the job is armed and after each scheduled fire, and moved forward through the schedule to the last instant at or before the fire when the job did not fire for a while (stopped and started in the Hub; not for a `utcOffset` job) — cron 4 sets `lastDate()` to the moment its timer fired, so two replicas firing on either side of a second boundary computed different keys and both ran the tick. A fire that does not advance `lastDate()` is a manual run (the Hub's "Run now") with a key of its own, also on a job stopped in the Hub. (2) `runParallel: false` (or `1`) holds across replicas for a distributed job, in timer and BullMQ mode: the run holds a `<job>:running` lease (60 s, renewed every 20 s, released in `finally`; Redis — owner-checked renew and release —, else the SQL lease table, else `cron-locks`), and a replica that finds it held skips its tick; fail-open like the tick lease. A run that never ends therefore holds the job on EVERY replica while its process lives, not only on its own. A larger `runParallel` stays per process. (3) A failed TTL index on `cron-locks` is tried again on the next tick instead of being cached as done. (4) Without `redis`, startup logs ONE info line naming the jobs that run on every replica because they did not set `distributed` (silent with `log: false`, and for jobs that set `distributed: false`). (5) BullMQ scheduler jobs carry `bullJobOptions` (protected): `attempts: 1` — a failed tick is not repeated, as with the local timer —, `removeOnComplete: { count: 100 }`, `removeOnFail: { count: 500 }`; before, every completed and failed tick stayed in Redis for good. Existing schedulers get them at the next bootstrap, which upserts every scheduler — after `trimBullJobBacklog()` has removed the backlog an earlier version kept, oldest first, 1000 jobs per `clean()` call: BullMQ trims by `count` in one Lua call without a limit, and the first tick under the new options would otherwise delete the whole backlog at once (measured 2 s for 300k jobs, 4.4 s for 700k, with Redis answering nobody) |
356
356
  | Shutdown Delay | `shutdownDelayMs` | Numeric Sentinel — Family B (`0` = off) | `0` (default, no delay, no log). Waits N ms **in the SIGTERM/SIGINT handler, before `close()` is entered**, so a load balancer can finish deregistering while the instance still serves; from the signal on `GET /health-check/ready` answers 503 `shutting_down` (12.11.0, `markShutdownDraining()`), so a load balancer polling readiness starts deregistering at once. NOT a lifecycle hook: `close()` runs `onModuleDestroy` → `beforeApplicationShutdown` → dispose → `onApplicationShutdown`, so a delay in `beforeApplicationShutdown` would wait with every module already torn down while the socket still accepts — worse than no delay. **Requires `installGracefulShutdown(app)` in main.ts, which REPLACES `server.enableShutdownHooks()`** — keeping both makes Nest close the app in parallel with the wait, so the delay silently never happens. At delay `0` the helper IS `enableShutdownHooks()`. **Keep the value well below the orchestrator grace period AND leave room for the drain that follows**: Compose `stop_grace_period` 10s, Kubernetes `terminationGracePeriodSeconds` 30s, and `installProcessDiagnostics()` force-exits after 30s — exceed any and the process is SIGKILLed mid-wait with no hook running. Warns above `10000`, capped at `60000`. Non-numeric / negative values behave like `0` |
357
357
  | Body Parser Limits | `bodyParser.json.limit`, `bodyParser.urlencoded.limit` | Explicit Value (Express/body-parser default) — invalid → default, never unbounded | **Unset = 100 kB each, exactly as NestJS registers the parsers** (body-parser's own default — a limit nobody chose, and before 11.42.4 the only one in force: over it a request got a bare `request entity too large`, before auth and routing, GraphQL included). A number is bytes, a string a 1024-based size (`'500kb'`, `'2mb'`, units `b`/`kb`/`mb`/`gb`). The two limits are separate on purpose — raising JSON must not raise form posts. **Not raised by default because the parser runs before authentication** and `JSON.parse` blocks the event loop for the whole body: ~0.5 ms for 100 kB, ~16 ms for 1 MB, ~55 ms for 2 MB per request on a realistic document shape. Applied by `CoreBodyParserInitializer` (CoreModule provider) in `onModuleInit` by **swapping the handle of the global `jsonParser`/`urlencodedParser` layers NestJS registered, in place** — NestJS registers them inside `app.init()` before any init hook, and a parser appended later would sit behind the routes. Same position, `extended: true` for URL-encoded, `req.rawBody` kept when the app came from `NestFactory.create(…, { rawBody: true })` (read from the container's context options; under `Test.createTestingModule()` those options never reach the container, so a test app with `rawBody: true` gets no `req.rawBody` from a CONFIGURED parser). Because it runs during module init it **holds under `Test.createTestingModule()`**, which never runs `main.ts` — the reason a `useBodyParser()` in `main.ts` was not enough. A configured value also replaces a global parser registered in `main.ts`; a **path-scoped** one (`server.use('/upload', json({ limit }))`) is left alone and stays the way to give one path its own limit (the parser runs before routing; GraphQL shares one path). **Keep `server.useBodyParser('json')` in `main.ts` next to a path-scoped parser**: NestJS registers its global parser only when no layer with the same FUNCTION NAME exists (`isMiddlewareApplied()`), so a path-scoped `json()` registered before `app.init()` suppresses it and every other path gets an empty body (a sign-in fails with a validation error). Since 11.42.6 the initializer warns at boot about exactly that (`warnMissingGlobalParser()`). It deliberately does not re-insert the parser: NestJS would have placed it after everything `main.ts` registered, a position no longer knowable during module init, and a raw-body webhook or proxy registered after the path-scoped parser must keep seeing the unread stream. An invalid value (`0`, negative, `NaN`, a word) is refused with an error log and the parser keeps its limit. **Independent of configuration**, every 413 from a global parser is answered as `PayloadTooLargeException` with `#LTNS_0304: Request body too large [<n> bytes, limit <m> bytes]` (size only when a `Content-Length` was sent) and logged as a WARN naming method, path without query string, and the config key — no boot warning, because the framework cannot know which routes expect large bodies; the first oversized request is the earliest point anything can be said. Other parser errors pass through unchanged. Pinned by `tests/unit/body-parser.spec.ts` and `tests/body-parser.e2e-spec.ts` (mutations `body-parser-*`). Implementation: `common/services/core-body-parser.initializer.ts` |
@@ -181,7 +181,7 @@ by the ws maintainers on 2026-11-12 and was not yet in GitHub's global database
181
181
  `pnpm audit` did not report it — read the advisories of a package's own repository when a release announces a
182
182
  security fix. It left in 12.12.0, once `@nestjs/graphql` 14.2.2 pinned ws 8.23.0 itself (two fresh resolves with and
183
183
  without the entry: identical package set, one `ws@8.23.0`). `check:overrides` could not report it as UNUSED: every
184
- edge resolved to the override's target either way, so only the with/without resolve shows such an entry is inert. From 12.10.0 to 12.10.1 a second entry, `minimatch` 11 -> 11.0.9: `@nestjs/cli` 12.0.13 exact-pins 11.0.5, covered by three moderate advisories (dev tooling only; the target is the newest 11.x, because an older one held every other `^11` consumer back). It left in 12.11.0, once `@nestjs/cli` 12.0.15 pinned 11.0.9 itself. Since 12.10.0 the set holds `i18next` 26 -> 26.4.4 (its only entry since 12.12.0): `@compodoc/compodoc` 2.0.0 exact-pins 26.3.3, covered by two advisories (dev tooling only); GHSA-6jcc is in GitHub's global database since 2026-11-23, GHSA-5jr9 was still repository-only at 12.12.0. Since 12.12.2 the target is 26.7.2, the newest 26.x, as in nest-server-starter: the oldest-that-clears target held a generated project that hoists the starter's file and asks `^26` three minors back. An override is only necessary if removing it lets the package resolve
184
+ edge resolved to the override's target either way, so only the with/without resolve shows such an entry is inert. From 12.10.0 to 12.10.1 a second entry, `minimatch` 11 -> 11.0.9: `@nestjs/cli` 12.0.13 exact-pins 11.0.5, covered by three moderate advisories (dev tooling only; the target is the newest 11.x, because an older one held every other `^11` consumer back). It left in 12.11.0, once `@nestjs/cli` 12.0.15 pinned 11.0.9 itself. Since 12.10.0 the set holds `i18next` 26 -> 26.4.4 (its only entry since 12.12.0): `@compodoc/compodoc` 2.0.0 exact-pins 26.3.3, covered by two advisories (dev tooling only); GHSA-6jcc is in GitHub's global database since 2026-11-23, GHSA-5jr9 was still repository-only at 12.12.0. Since 12.12.2 the target is 26.7.2, the newest 26.x, as in nest-server-starter: the oldest-that-clears target held a generated project that hoists the starter's file and asks `^26` three minors back. Since 12.14.0 a second entry, `minimatch` 11 -> 11.0.10: GHSA-3924-r96c-gp9w (low, 11.0.6 to 11.0.9) reached GitHub's global database on 2026-12-04, and `@nestjs/cli` 12.0.15 as well as `@ts-morph/common` (production path via ts-morph) resolve 11.0.9; target 11.0.10, the newest 11.0.x, as in nest-server-starter. An override is only necessary if removing it lets the package resolve
185
185
  back INTO its vulnerable range (verify with a with/without lockfile diff; `pnpm audit` is the arbiter).
186
186
  "Cheap insurance against a parent re-pinning downwards" is not a reason to keep one: `pnpm audit` and
187
187
  `check:overrides` run on every `check` and report such a regression the day it happens. Each surviving entry carries its CVE rationale as a comment. Remove an entry once its parent dependency ships a fixed version.
@@ -418,7 +418,7 @@ pnpm run check:mutations -- --id=<id> # one mutation
418
418
  pnpm run check:mutations -- --list # the registry, without running anything
419
419
  pnpm run check:mutations -- --allow-dirty # when the fix and its evidence share a working tree
420
420
  pnpm run check:mutations -- --jobs=4 # N mutations at a time (default: 2, or 4 on >=12 cores)
421
- pnpm run check:mutations -- --no-infra # only the 546 that need no MongoDB
421
+ pnpm run check:mutations -- --no-infra # only the 550 that need no MongoDB
422
422
  pnpm run check:mutations -- --since=<ref> # only mutations touching files changed since <ref>
423
423
  pnpm run check:mutations -- --shard=2/4 # this job's quarter of the selection (CI splits the full run)
424
424
  ```
@@ -438,7 +438,7 @@ when the registry, a vitest config or a setup file changed, since those can move
438
438
  commit, and in CI alongside the publish without blocking it. The price of caching is a cache that
439
439
  has to model each spec's full dependency closure correctly, and getting that wrong produces a stale
440
440
  PASS for a test that has since gone vacuous — exactly what the gate is there to prevent. Bad trade
441
- at 805 mutations.
441
+ at 809 mutations.
442
442
 
443
443
  **Decided 2026-10-03 (repo owner): keep the full run.** Measured at 128 mutations, the CI job for
444
444
  11.41.6 took **14 minutes**. The trigger to revisit is that wall time, not the mutation count —
@@ -511,7 +511,7 @@ exactly the environment where the answer matters.
511
511
 
512
512
  Worth knowing before optimising the wrong thing: the specs behind all 259 e2e mutations add up to
513
513
  **~40 seconds**. The step takes ~740s. The remaining ~700s is paying vitest's startup — process
514
- spawn, transform, module graph, mongod connect, DB create and drop — once per mutation, 805 times.
514
+ spawn, transform, module graph, mongod connect, DB create and drop — once per mutation, 809 times.
515
515
  That work is largely single-threaded I/O and barely scales with cores: the full registry measures
516
516
  **744s on a 12-core laptop and 777s on a 4-vCPU CI runner**.
517
517
 
package/FRAMEWORK-API.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @lenne.tech/nest-server — Framework API Reference
2
2
 
3
- > Auto-generated from source code as of 2026-12-04 (v12.13.0)
3
+ > Auto-generated from source code as of 2026-12-04 (v12.14.0)
4
4
  > File: `FRAMEWORK-API.md` — compact, machine-readable API surface for Claude Code
5
5
 
6
6
  ## CoreModule.forRoot()
@@ -1,12 +1,17 @@
1
1
  export declare const DEFAULT_COMMIT_ENV = "APP_VERSION_COMMIT";
2
+ export declare const DEFAULT_BUILD_ENV = "APP_VERSION_BUILD";
2
3
  export declare const UNKNOWN_COMMIT = "unknown";
3
4
  export interface BuildInfo {
5
+ build?: string;
4
6
  commit: string;
5
7
  env?: string;
6
8
  version?: string;
7
9
  }
8
10
  export declare function getCommit(envName?: string): string;
11
+ export declare function getBuild(envName?: string): string | undefined;
12
+ export declare function composeVersion(version: string, build?: null | string): string;
9
13
  export declare function getBuildInfo(options?: {
14
+ buildEnvName?: string;
10
15
  commitEnvName?: string;
11
16
  env?: string;
12
17
  version?: string;
@@ -1,16 +1,31 @@
1
1
  import { existsSync, readFileSync } from 'fs';
2
2
  import { join } from 'path';
3
3
  export const DEFAULT_COMMIT_ENV = 'APP_VERSION_COMMIT';
4
+ export const DEFAULT_BUILD_ENV = 'APP_VERSION_BUILD';
4
5
  export const UNKNOWN_COMMIT = 'unknown';
5
6
  let cachedVersion;
6
7
  export function getCommit(envName = DEFAULT_COMMIT_ENV) {
7
8
  return process.env[envName] || UNKNOWN_COMMIT;
8
9
  }
10
+ export function getBuild(envName = DEFAULT_BUILD_ENV) {
11
+ const build = (process.env[envName] || '').trim();
12
+ return /^\d+$/.test(build) ? build : undefined;
13
+ }
14
+ export function composeVersion(version, build) {
15
+ const buildNumber = (build ?? '').trim();
16
+ const match = /^(\d+)\.(\d+)/.exec(version);
17
+ if (!match || !/^\d+$/.test(buildNumber)) {
18
+ return version;
19
+ }
20
+ return `${match[1]}.${match[2]}.${buildNumber}`;
21
+ }
9
22
  export function getBuildInfo(options = {}) {
23
+ const build = getBuild(options.buildEnvName);
10
24
  return {
25
+ ...(build ? { build } : {}),
11
26
  commit: getCommit(options.commitEnvName),
12
27
  env: options.env,
13
- version: options.version || getVersion(),
28
+ version: composeVersion(options.version || getVersion(), build),
14
29
  };
15
30
  }
16
31
  export function getVersion() {
@@ -1 +1 @@
1
- {"version":3,"file":"meta.helper.js","sourceRoot":"","sources":["../../../../src/core/common/helpers/meta.helper.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,IAAI,CAAC;AAC9C,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAG5B,MAAM,CAAC,MAAM,kBAAkB,GAAG,oBAAoB,CAAC;AAGvD,MAAM,CAAC,MAAM,cAAc,GAAG,SAAS,CAAC;AAGxC,IAAI,aAAwC,CAAC;AA0B7C,MAAM,UAAU,SAAS,CAAC,UAAkB,kBAAkB;I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AG,GAAG,MAAM,CAAC;QACf,CAAC;IACH,CAAC;IAAC,MAAM,CAAC;IAET,CAAC;IACD,OAAO,aAAa,IAAI,cAAc,CAAC;AACzC,CAAC"}
@@ -1,6 +1,12 @@
1
1
  import { DiskHealthIndicator, HealthCheckResult, HealthCheckService, type HealthIndicatorFunction, HealthIndicatorService, MemoryHealthIndicator, MongooseHealthIndicator } from '@nestjs/terminus';
2
2
  import { ConfigService } from '../../common/services/config.service.js';
3
3
  import { type CoreHealthCheckKind, type CoreHealthCheckName } from './core-health-check.helpers.js';
4
+ export declare const DEFAULT_DATABASE_PING_TIMEOUT_MS = 2000;
5
+ export interface IHealthCheckMongoConnection {
6
+ db?: {
7
+ command(command: Record<string, unknown>): Promise<unknown>;
8
+ } | null;
9
+ }
4
10
  export declare class CoreHealthCheckService {
5
11
  protected config: ConfigService;
6
12
  protected db: MongooseHealthIndicator | null;
@@ -9,11 +15,13 @@ export declare class CoreHealthCheckService {
9
15
  protected memory: MemoryHealthIndicator;
10
16
  protected indicators?: HealthIndicatorService;
11
17
  constructor(config: ConfigService, db: MongooseHealthIndicator | null, disk: DiskHealthIndicator, health: HealthCheckService, memory: MemoryHealthIndicator, indicators?: HealthIndicatorService);
18
+ protected mongoConnection?: IHealthCheckMongoConnection | null;
12
19
  healthCheck(): Promise<HealthCheckResult>;
13
20
  readinessCheck(): Promise<HealthCheckResult>;
14
21
  protected additionalHealthIndicators(_kind: CoreHealthCheckKind): HealthIndicatorFunction[] | Promise<HealthIndicatorFunction[]>;
15
22
  protected isLivenessCheckEnabled(check: CoreHealthCheckName): boolean;
16
23
  protected configuredHealthIndicators(check: CoreHealthCheckName): HealthIndicatorFunction[];
17
24
  protected databaseHealthIndicators(): HealthIndicatorFunction[];
25
+ protected pingMongoDb(connection: IHealthCheckMongoConnection): Promise<void>;
18
26
  protected buildHealthIndicators(): HealthIndicatorFunction[];
19
27
  }
@@ -14,9 +14,11 @@ import { Inject, Injectable, Optional, ServiceUnavailableException } from '@nest
14
14
  import { DiskHealthIndicator, HealthCheckService, HealthIndicatorService, MemoryHealthIndicator, MongooseHealthIndicator, } from '@nestjs/terminus';
15
15
  import { getBuildInfo } from '../../common/helpers/meta.helper.js';
16
16
  import { isShutdownDraining } from '../../common/helpers/shutdown-state.helper.js';
17
+ import { InjectConnection } from '../../common/persistence/mongo/mongoose-compat.js';
17
18
  import { getPersistenceRuntime } from '../../common/persistence/persistence-runtime.registry.js';
18
19
  import { ConfigService } from '../../common/services/config.service.js';
19
20
  import { CORE_HEALTH_CHECK_NAMES, resolveHealthCheckReadiness, } from './core-health-check.helpers.js';
21
+ export const DEFAULT_DATABASE_PING_TIMEOUT_MS = 2000;
20
22
  let CoreHealthCheckService = class CoreHealthCheckService {
21
23
  config;
22
24
  db;
@@ -32,6 +34,7 @@ let CoreHealthCheckService = class CoreHealthCheckService {
32
34
  this.memory = memory;
33
35
  this.indicators = indicators;
34
36
  }
37
+ mongoConnection;
35
38
  async healthCheck() {
36
39
  const checks = CORE_HEALTH_CHECK_NAMES.filter((check) => this.isLivenessCheckEnabled(check));
37
40
  return this.health.check([
@@ -84,14 +87,24 @@ let CoreHealthCheckService = class CoreHealthCheckService {
84
87
  databaseHealthIndicators() {
85
88
  const healthIndicatorFunctions = [];
86
89
  if (this.db) {
90
+ const db = this.db;
87
91
  healthIndicatorFunctions.push(() => {
88
- const { timeout, ...options } = this.config.get('healthCheck.configs.database.options') ?? { timeout: 300 };
89
- const attempt = this.db.pingCheck(this.config.get('healthCheck.configs.database.key') ?? 'database', options);
90
- return timeout === undefined ? attempt : attempt.withTimeout(timeout);
92
+ const { connection, timeout = DEFAULT_DATABASE_PING_TIMEOUT_MS, ...options } = this.config.get('healthCheck.configs.database.options') ?? {};
93
+ const key = this.config.get('healthCheck.configs.database.key') ?? 'database';
94
+ const target = connection ?? this.mongoConnection;
95
+ if (!this.indicators || !target) {
96
+ return db.pingCheck(key, { connection, ...options }).withTimeout(timeout);
97
+ }
98
+ return this.indicators
99
+ .check(key)
100
+ .attempt(() => this.pingMongoDb(target))
101
+ .withFailureData((error) => ({ code: error?.code }))
102
+ .withTimeout(timeout);
91
103
  });
92
104
  }
93
105
  const key = this.config.get('healthCheck.configs.database.key') ?? 'database';
94
- const timeout = this.config.get('healthCheck.configs.database.options')?.timeout ?? 1000;
106
+ const timeout = this.config.get('healthCheck.configs.database.options')?.timeout ??
107
+ DEFAULT_DATABASE_PING_TIMEOUT_MS;
95
108
  if (this.indicators) {
96
109
  for (const source of getPersistenceRuntime()?.sqlSources() ?? []) {
97
110
  healthIndicatorFunctions.push(() => this.indicators
@@ -102,11 +115,22 @@ let CoreHealthCheckService = class CoreHealthCheckService {
102
115
  }
103
116
  return healthIndicatorFunctions;
104
117
  }
118
+ async pingMongoDb(connection) {
119
+ if (!connection.db) {
120
+ throw new Error('Not connected to database');
121
+ }
122
+ await connection.db.command({ ping: 1 });
123
+ }
105
124
  buildHealthIndicators() {
106
125
  const build = getBuildInfo({ env: this.config.get('env'), version: this.config.get('version') });
107
126
  return [async () => ({ build: { ...build, status: 'up' } })];
108
127
  }
109
128
  };
129
+ __decorate([
130
+ Optional(),
131
+ InjectConnection(),
132
+ __metadata("design:type", Object)
133
+ ], CoreHealthCheckService.prototype, "mongoConnection", void 0);
110
134
  CoreHealthCheckService = __decorate([
111
135
  Injectable(),
112
136
  __param(1, Inject(MongooseHealthIndicator)),
@@ -1 +1 @@
1
- {"version":3,"file":"core-health-check.service.js","sourceRoot":"","sources":["../../../../src/core/modules/health-check/core-health-check.service.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,QAAQ,EAAE,2BAA2B,EAAE,MAAM,gBAAgB,CAAC;AAC3F,OAAO,EACL,mBAAmB,EAGnB,kBAAkB,EAElB,sBAAsB,EACtB,qBAAqB,EACrB,uBAAuB,GAExB,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EAAE,YAAY,EAAE,MAAM,qCAAqC,CAAC;AACnE,OAAO,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AAC,GAAG,CAA4B,sCAAsC,CAAC,EAAE,OAAO,IAAI,IAAI,CAAC;QACpH,IAAI,IAAI,CAAC,UAAU,EAAE,CAAC;YACpB,KAAK,MAAM,MAAM,IAAI,qBAAqB,EAAE,EAAE,UAAU,EAAE,IAAI,EAAE,EAAE,CAAC;gBACjE,wBAAwB,CAAC,IAAI,CAAC,GAAG,EAAE,CACjC,IAAI,CAAC,UAAU;qBACZ,KAAK,CAAC,GAAG,GAAG,IAAI,MAAM,CAAC,IAAI,EAAE,CAAC;qBAC9B,OAAO,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC;qBAC5B,WAAW,CAAC,OAAO,CAAC,CACxB,CAAC;YACJ,CAAC;QACH,CAAC;QACD,OAAO,wBAAwB,CAAC;IAClC,CAAC;IASS,qBAAqB;QAC7B,MAAM,KAAK,GAAG,YAAY,CAAC,EAAE,GAAG,EAAE,IAAI,CAAC,MAAM,CAAC,GAAG,CAAS,KAAK,CAAC,EAAE,OAAO,EAAE,IAAI,CAAC,MAAM,CAAC,GAAG,CAAS,SAAS,CAAC,EAAE,CAAC,CAAC;QACjH,OAAO,CAAC,KAAK,IAAI,EAAE,CAAC,CAAC,EAAE,KAAK,EAAE,EAAE,GAAG,KAAK,EAAE,MAAM,EAAE,IAAa,EAAE,EAAE,CAAC,CAAC,CAAC;IACxE,CAAC;CACF,CAAA;AA5KY,sBAAsB;IADlC,UAAU,EAAE;IAKR,WAAA,MAAM,CAAC,uBAAuB,CAAC,CAAA;IAI/B,WAAA,QAAQ,EAAE,CAAA;qCANO,aAAa;QAEgB,uBAAuB;QACtD,mBAAmB;QACjB,kBAAkB;QAClB,qBAAqB;QACJ,sBAAsB;GARhD,sBAAsB,CA4KlC"}
1
+ {"version":3,"file":"core-health-check.service.js","sourceRoot":"","sources":["../../../../src/core/modules/health-check/core-health-check.service.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,Q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AAC;YACJ,CAAC;QACH,CAAC;QACD,OAAO,wBAAwB,CAAC;IAClC,CAAC;IAeS,KAAK,CAAC,WAAW,CAAC,UAAuC;QACjE,IAAI,CAAC,UAAU,CAAC,EAAE,EAAE,CAAC;YAEnB,MAAM,IAAI,KAAK,CAAC,2BAA2B,CAAC,CAAC;QAC/C,CAAC;QACD,MAAM,UAAU,CAAC,EAAE,CAAC,OAAO,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,CAAC,CAAC;IAC3C,CAAC;IAUS,qBAAqB;QAC7B,MAAM,KAAK,GAAG,YAAY,CAAC,EAAE,GAAG,EAAE,IAAI,CAAC,MAAM,CAAC,GAAG,CAAS,KAAK,CAAC,EAAE,OAAO,EAAE,IAAI,CAAC,MAAM,CAAC,GAAG,CAAS,SAAS,CAAC,EAAE,CAAC,CAAC;QACjH,OAAO,CAAC,KAAK,IAAI,EAAE,CAAC,CAAC,EAAE,KAAK,EAAE,EAAE,GAAG,KAAK,EAAE,MAAM,EAAE,IAAa,EAAE,EAAE,CAAC,CAAC,CAAC;IACxE,CAAC;CACF,CAAA;AAnMW;IAFT,QAAQ,EAAE;IACV,gBAAgB,EAAE;;+DAC4C;AAjBpD,sBAAsB;IADlC,UAAU,EAAE;IAKR,WAAA,MAAM,CAAC,uBAAuB,CAAC,CAAA;IAI/B,WAAA,QAAQ,EAAE,CAAA;qCANO,aAAa;QAEgB,uBAAuB;QACtD,mBAAmB;QACjB,kBAAkB;QAClB,qBAAqB;QACJ,sBAAsB;GARhD,sBAAsB,CAoNlC"}
@@ -0,0 +1,132 @@
1
+ # Migration Guide: 12.13.x → 12.14.x
2
+
3
+ ## Overview
4
+
5
+ | Category | Details |
6
+ |---|---|
7
+ | **Breaking Changes** | A container image with bundled migrations but no migrate CLI no longer starts (§1). Changed defaults: the MongoDB health check pings instead of reading `readyState`, the database ping waits up to 2000 ms (§3) |
8
+ | **New Features** | `docker-entrypoint.sh` also finds the framework's compiled migrate CLI in a vendored build without `copy:bin` (§1); build number next to the commit: `getBuild()`, `composeVersion()`, `build` in `getBuildInfo()`, `/health-check` and the starter's `GET /meta`, version `<Major>.<Minor>.<Build>` (§2) |
9
+ | **Bugfixes** | None |
10
+ | **Migration Effort** | None for an image that already runs its migrations. Projects that copied nest-server-starter's `docker-entrypoint.sh` adopt the new version (§1). Build number: none for the health check; ~5 minutes for `GET /meta` and the Dockerfile (§2) |
11
+
12
+ ## Quick Migration
13
+
14
+ ```bash
15
+ pnpm add @lenne.tech/nest-server@12.14.0
16
+ pnpm run update # nest-server-starter based projects
17
+ pnpm run build
18
+ pnpm test
19
+ ```
20
+
21
+ **Vendor mode**: run `/lt-dev:backend:update-nest-server-core` as usual.
22
+
23
+ ## 1. `docker-entrypoint.sh`: no migrate CLI with bundled migrations refuses the start
24
+
25
+ nest-server's and nest-server-starter's `docker-entrypoint.sh` run the bundled migrations (`dist/migrations`)
26
+ before the server starts. When the image held no migrate CLI, the script used to print "migrate CLI not present
27
+ in image — skipping migrations" and start anyway: the server then served a schema without those migrations behind
28
+ a green health check.
29
+
30
+ Now an image whose `dist/migrations` is not empty but that holds no CLI is treated like a failed migration: the
31
+ container exits with status 1. `MIGRATIONS_ALLOW_FAILURE=true` (or `MIGRATE_FAILURE_POLICY=warn`) starts it
32
+ anyway for one deploy, with a warning. An image without bundled migrations starts as before.
33
+
34
+ The script now looks for the CLI in three places, the first one found runs:
35
+
36
+ | Layout | Path |
37
+ |---|---|
38
+ | npm mode | `node_modules/.bin/migrate` |
39
+ | vendor mode | `dist/bin/migrate.js` (copied by `copy:bin`) |
40
+ | vendor mode without `copy:bin` | `dist/src/core/modules/migrate/cli/migrate-cli.js` (`dist/core/…` for a build flattened to `rootDir: src`) |
41
+
42
+ The third is loaded the way `bin/migrate.js` loads it (`require()` and `runCli()`), never as
43
+ `node migrate-cli.js`: the CLI starts itself only behind a CommonJS `require.main === module` guard, so a compiled
44
+ ES module run directly exits 0 without migrating.
45
+
46
+ **Check:** a project that copied the starter's `docker-entrypoint.sh` takes the new version from
47
+ nest-server-starter. If a deploy then stops with "migrations are bundled …, but the image holds no migrate CLI",
48
+ rebuild the image (npm mode: `@lenne.tech/nest-server` in `dependencies`; vendor mode: `copy:bin` in the build), or
49
+ set `MIGRATIONS_ALLOW_FAILURE=true` for that one deploy.
50
+
51
+ ## 2. Build number: the version people read
52
+
53
+ Every image can carry a second build value next to the commit: the build number, the project's CI
54
+ pipeline counter, as `APP_VERSION_BUILD`. lt-ship 1.3+ passes it on the cluster as a Docker build arg,
55
+ the lt-monorepo CI on TurboOps (`BUILD_NUMBER: $CI_PIPELINE_IID`). The commit stays the value machines
56
+ compare; the build number is for people.
57
+
58
+ - `getBuild(envName = 'APP_VERSION_BUILD')`: the build number, `undefined` when unset or not a plain number.
59
+ - `composeVersion(version, build)`: `<Major>.<Minor>.<Build>`, e.g. `composeVersion('1.32.0', '1875')` →
60
+ `'1.32.1875'`. Without a usable build number, or for a version that is no `<major>.<minor>…`, it returns
61
+ `version` unchanged.
62
+ - `getBuildInfo()` adds `build` when one is set and composes `version` with it. The `/health-check` build
63
+ indicator therefore reports `build` and `<Major>.<Minor>.<Build>`; without `APP_VERSION_BUILD` it is unchanged.
64
+
65
+ Major.Minor come from `IServerOptions.version` (nest-server-starter sets it from `src/meta.json`), else from
66
+ `package.json`, and are raised by hand; the patch digit is replaced. Why: projects needed a readable, increasing version. The only one that had it (via
67
+ semantic-release) paid with a bot commit after every merge, which broke promotions dev → test → main and
68
+ needed a token with write access. The build number needs no commit, no tag and no token, and a promotion
69
+ carries it along with the image.
70
+
71
+ **Adopt in a project (optional):**
72
+
73
+ 1. Dockerfile, next to `APP_VERSION_COMMIT`:
74
+ ```dockerfile
75
+ ARG APP_VERSION_BUILD=
76
+ ENV APP_VERSION_BUILD=$APP_VERSION_BUILD
77
+ ```
78
+ 2. `GET /meta` (nest-server-starter's `MetaService`): import both helpers
79
+ (`import { composeVersion, getBuild } from '@lenne.tech/nest-server';`, vendor mode: from the core's
80
+ `common/helpers/meta.helper`), then `build: getBuild()` and
81
+ `version: composeVersion(metaData.version, build)`, plus a nullable `build` field on `Meta`.
82
+ 3. Set Major.Minor deliberately in `src/meta.json`, which `GET /meta` and `/health-check` read in a
83
+ starter-based API (`lt fullstack init` writes `0.0.0` there); raising `package.json` alone changes neither.
84
+
85
+ ## 3. Health check: the MongoDB check pings, and waits up to 2000 ms
86
+
87
+ **The MongoDB check no longer reports a reachable database as down.** It used Terminus' `MongooseHealthIndicator`,
88
+ which answers "down" BEFORE it pings whenever the Mongoose connection's `readyState` is not 1. Mongoose sets
89
+ `disconnected` as soon as the driver's topology briefly sees no primary: a replica set without
90
+ `ReplicaSetWithPrimary`, a single server turning `Unknown`. One lost heartbeat is enough, while the database answers
91
+ in milliseconds and the application's own queries simply wait for the driver's server selection. On a cluster with
92
+ managed MongoDB replica sets this gate caused far more than 95 % of all "database down" alarms (a few hundred per
93
+ project and month, at the same moments across all projects of one database instance), and three in a row took the
94
+ pod out of the readiness rotation.
95
+
96
+ The core now sends a real `ping` (`CoreHealthCheckService.pingMongoDb()`) without that gate. It waits for the
97
+ driver's server selection like any query, so the check reports down only when the database does not answer within
98
+ the timeout, or when the initial connect has not finished yet.
99
+
100
+ **The timeout is 2000 ms** for the MongoDB ping and for every SQL source, unless
101
+ `healthCheck.configs.database.options.timeout` sets another value (exported as `DEFAULT_DATABASE_PING_TIMEOUT_MS`).
102
+ Before, MongoDB waited 300 ms without configured options and 1000 ms with options but no `timeout`; SQL sources waited
103
+ 1000 ms. The longer budget gives server selection time to find the primary again.
104
+
105
+ **Check:** nothing to change. A database that does not answer is still reported down, after 2 s. Keep your probe
106
+ timeout above 2 s (the lt charts use 3 s, the starter's Dockerfile `HEALTHCHECK --timeout=5s`). A subclass of
107
+ `CoreHealthCheckService` keeps the new check without changes; one that overrides `databaseHealthIndicators()` and calls
108
+ `this.db.pingCheck()` itself keeps Terminus' gate. To keep the old timeout, set
109
+ `healthCheck.configs.database.options.timeout: 300`.
110
+
111
+ If your logs show these alarms, the brief loss of the primary itself is worth a look on the database side (the
112
+ driver's `serverHeartbeatFailed` events name the reason). The health check no longer turns it into an outage.
113
+
114
+ ## 4. Dependencies
115
+
116
+ | Package | Version | Note |
117
+ |---|---|---|
118
+ | `ai` | 7.0.188 → 7.1.0 | optional peer (AI SDK transport); tested range unchanged (`>=7.0.0 <8`). `pnpm run update` raises a project that uses it |
119
+ | `minimatch` (override) | 11.0.9 → 11.0.10 | GHSA-3924-r96c-gp9w (low) reached GitHub's global database on 2026-12-04, so `pnpm audit` fails on `@nestjs/cli` 12.0.15 and `@ts-morph/common`, which resolve 11.0.9. nest-server's override does not reach your project: add `'minimatch@>=11.0.0 <11.0.10': '11.0.10'` to `overrides` in your `pnpm-workspace.yaml` (nest-server-starter has it) |
120
+
121
+ Still held, as in 12.13.0: `@apollo/server` 5.5.1, `mysql2` 3.25.0 (3.26 refuses `caching_sha2_password` without TLS, see the 12.13.x guide §5), `mongodb` 7.9.1 (mongoose 9.13 pins `~7.9`).
122
+
123
+ ## Troubleshooting
124
+
125
+ | Symptom | Cause | Fix |
126
+ |---|---|---|
127
+ | Container exits: "migrations are bundled …, but the image holds no migrate CLI" | The image has `dist/migrations` but none of the three CLI paths (§1) | Rebuild the image with the CLI, or `MIGRATIONS_ALLOW_FAILURE=true` for one deploy |
128
+ | `/health-check` and `/meta` show the plain `package.json` version, no `build` | The image carries no `APP_VERSION_BUILD` (§2) | Add the Dockerfile `ARG`/`ENV`; on the cluster use lt-ship 1.3+, with docker compose pass `APP_VERSION_BUILD: ${BUILD_NUMBER:-}` |
129
+
130
+ ## Module Documentation
131
+
132
+ - `src/core/modules/migrate/README.md`: migration runner, failure policy
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lenne.tech/nest-server",
3
- "version": "12.13.0",
3
+ "version": "12.14.0",
4
4
  "type": "module",
5
5
  "description": "Server framework in TypeScript on top of NestJS: GraphQL and REST APIs on MongoDB, PostgreSQL, MySQL or MariaDB, with authentication, field-level permissions, multi-tenancy, offline sync and an AI assistant.",
6
6
  "keywords": [
@@ -275,7 +275,7 @@
275
275
  "@types/passport": "1.0.17",
276
276
  "@types/pg": "8.23.1",
277
277
  "@vitest/coverage-v8": "5.1.2",
278
- "ai": "7.0.188",
278
+ "ai": "7.1.0",
279
279
  "better-auth": "1.7.29",
280
280
  "bullmq": "6.7.12",
281
281
  "cross-env": "10.1.0",
@@ -11,7 +11,17 @@
11
11
  * deployed together bake the SAME commit, but each reads its own at runtime — so
12
12
  * comparing them detects a drifted / stale container after a partial rollout.
13
13
  *
14
+ * For people there is a second value: the build number (default env
15
+ * `APP_VERSION_BUILD`, fed from the CI pipeline counter — lt-ship 1.3+ passes it,
16
+ * so does the lt-monorepo CI). It always increases and travels with the image
17
+ * through a promotion. With it, the version shown to people becomes
18
+ * `<Major>.<Minor>.<Build>`: Major.Minor from package.json / config (raised by
19
+ * hand), the build number in the patch position. Without it the version stays
20
+ * as configured. The commit remains the identity machines compare.
21
+ *
14
22
  * @see getCommit
23
+ * @see getBuild
24
+ * @see composeVersion
15
25
  * @see getBuildInfo
16
26
  */
17
27
 
@@ -21,6 +31,9 @@ import { join } from 'path';
21
31
  /** Default environment variable the build commit SHA is baked into. */
22
32
  export const DEFAULT_COMMIT_ENV = 'APP_VERSION_COMMIT';
23
33
 
34
+ /** Default environment variable the build number (CI pipeline counter) is baked into. */
35
+ export const DEFAULT_BUILD_ENV = 'APP_VERSION_BUILD';
36
+
24
37
  /** Defined value returned when no commit could be resolved. */
25
38
  export const UNKNOWN_COMMIT = 'unknown';
26
39
 
@@ -31,13 +44,19 @@ let cachedVersion: null | string | undefined;
31
44
  * Build identity of the running process.
32
45
  */
33
46
  export interface BuildInfo {
47
+ /** Build number (CI pipeline counter) the image was built in, if known. */
48
+ build?: string;
49
+
34
50
  /** Git commit SHA the build was produced from, or `'unknown'`. */
35
51
  commit: string;
36
52
 
37
53
  /** Environment the process runs in (e.g. `'production'`), if provided. */
38
54
  env?: string;
39
55
 
40
- /** Semantic version of the build, or `'unknown'`. */
56
+ /**
57
+ * Version of the build for people: `<Major>.<Minor>.<Build>` when a build number is known,
58
+ * otherwise the configured / package.json version, or `'unknown'`.
59
+ */
41
60
  version?: string;
42
61
  }
43
62
 
@@ -55,6 +74,39 @@ export function getCommit(envName: string = DEFAULT_COMMIT_ENV): string {
55
74
  return process.env[envName] || UNKNOWN_COMMIT;
56
75
  }
57
76
 
77
+ /**
78
+ * Resolve the build number (CI pipeline counter) the running build was produced in.
79
+ *
80
+ * Reads `process.env[envName]` (default `APP_VERSION_BUILD`). Returns `undefined` when the
81
+ * variable is unset or not a plain number — local builds and builds outside the lt pipelines
82
+ * have none, and the version then stays as configured.
83
+ *
84
+ * @param envName Name of the environment variable holding the build number.
85
+ */
86
+ export function getBuild(envName: string = DEFAULT_BUILD_ENV): string | undefined {
87
+ const build = (process.env[envName] || '').trim();
88
+ return /^\d+$/.test(build) ? build : undefined;
89
+ }
90
+
91
+ /**
92
+ * Compose the version shown to people: `<Major>.<Minor>.<Build>`.
93
+ *
94
+ * Major.Minor come from `version` (package.json or config, raised by hand); the build number
95
+ * takes the patch position. Returns `version` unchanged when the build number is missing or not
96
+ * numeric, and when `version` itself is not a `<major>.<minor>…` version (e.g. `'unknown'`).
97
+ *
98
+ * @param version Configured / package.json version, e.g. `'1.32.0'`.
99
+ * @param build Build number, e.g. `'1875'`.
100
+ */
101
+ export function composeVersion(version: string, build?: null | string): string {
102
+ const buildNumber = (build ?? '').trim();
103
+ const match = /^(\d+)\.(\d+)/.exec(version);
104
+ if (!match || !/^\d+$/.test(buildNumber)) {
105
+ return version;
106
+ }
107
+ return `${match[1]}.${match[2]}.${buildNumber}`;
108
+ }
109
+
58
110
  /**
59
111
  * Assemble the build identity of the running process.
60
112
  *
@@ -62,15 +114,22 @@ export function getCommit(envName: string = DEFAULT_COMMIT_ENV): string {
62
114
  * `version` and `env`. Designed to be surfaced via a public meta / info endpoint
63
115
  * and the health check so deployments can be compared at a glance.
64
116
  *
117
+ * The `version` is composed with the build number (see {@link composeVersion}) when one is set.
118
+ *
119
+ * @param options.buildEnvName Override the env var the build number is read from.
65
120
  * @param options.commitEnvName Override the env var the commit SHA is read from.
66
121
  * @param options.env Environment label to include (e.g. from the config).
67
122
  * @param options.version Semantic version to include (e.g. from package.json).
68
123
  */
69
- export function getBuildInfo(options: { commitEnvName?: string; env?: string; version?: string } = {}): BuildInfo {
124
+ export function getBuildInfo(
125
+ options: { buildEnvName?: string; commitEnvName?: string; env?: string; version?: string } = {},
126
+ ): BuildInfo {
127
+ const build = getBuild(options.buildEnvName);
70
128
  return {
129
+ ...(build ? { build } : {}),
71
130
  commit: getCommit(options.commitEnvName),
72
131
  env: options.env,
73
- version: options.version || getVersion(),
132
+ version: composeVersion(options.version || getVersion(), build),
74
133
  };
75
134
  }
76
135
 
@@ -3046,6 +3046,8 @@ export interface IServerOptions {
3046
3046
  * Surfaced via the build-identity health indicator alongside the commit SHA.
3047
3047
  * Unlike the commit (which uniquely pins the exact build), the version is a
3048
3048
  * rarely-bumped semver and may legitimately differ between API and frontend.
3049
+ * When the image carries a build number (`APP_VERSION_BUILD`, since 12.14.0), its
3050
+ * Major.Minor are combined with it to `<Major>.<Minor>.<Build>`.
3049
3051
  *
3050
3052
  * @since 11.27.0
3051
3053
  */
@@ -3179,6 +3181,8 @@ export interface IServerOptions {
3179
3181
  * drifted / stale container can be detected after a partial rollout. The
3180
3182
  * commit is read from `process.env.APP_VERSION_COMMIT` (baked at build
3181
3183
  * time from the CI commit SHA); `version` comes from {@link IServerOptions.version}.
3184
+ * With `process.env.APP_VERSION_BUILD` (the CI pipeline counter, since 12.14.0) the
3185
+ * indicator also reports `build`, and `version` becomes `<Major>.<Minor>.<Build>`.
3182
3186
  *
3183
3187
  * @since 11.27.0
3184
3188
  */
@@ -3204,7 +3208,8 @@ export interface IServerOptions {
3204
3208
  key?: string;
3205
3209
 
3206
3210
  /**
3207
- * Database health check options
3211
+ * Database health check options. `timeout` (ms) applies to the MongoDB ping and to every SQL source;
3212
+ * default: 2000 (`DEFAULT_DATABASE_PING_TIMEOUT_MS`)
3208
3213
  */
3209
3214
  options?: MongoosePingCheckSettings;
3210
3215
  };
@@ -13,6 +13,7 @@ import {
13
13
 
14
14
  import { getBuildInfo } from '../../common/helpers/meta.helper.js';
15
15
  import { isShutdownDraining } from '../../common/helpers/shutdown-state.helper.js';
16
+ import { InjectConnection } from '../../common/persistence/mongo/mongoose-compat.js';
16
17
  import { getPersistenceRuntime } from '../../common/persistence/persistence-runtime.registry.js';
17
18
  import { ConfigService } from '../../common/services/config.service.js';
18
19
  import {
@@ -22,6 +23,22 @@ import {
22
23
  resolveHealthCheckReadiness,
23
24
  } from './core-health-check.helpers.js';
24
25
 
26
+ /**
27
+ * How long a database ping (MongoDB and every SQL source) may take before the health check reports the database as
28
+ * down, unless `healthCheck.configs.database.options.timeout` sets another value.
29
+ *
30
+ * 2 s, not the former 300 ms (MongoDB) / 1000 ms (SQL): the MongoDB ping waits for the driver's server selection
31
+ * (see {@link CoreHealthCheckService.pingMongoDb}), which rides out a replica set that briefly sees no primary; a
32
+ * single slow round trip to a managed database outside the cluster must not report it down either. 2 s still fails a
33
+ * database that does not answer and stays below the readiness probe timeout of the lt charts (3 s).
34
+ */
35
+ export const DEFAULT_DATABASE_PING_TIMEOUT_MS = 2000;
36
+
37
+ /** The part of a Mongoose connection the health check's MongoDB ping uses */
38
+ export interface IHealthCheckMongoConnection {
39
+ db?: { command(command: Record<string, unknown>): Promise<unknown> } | null;
40
+ }
41
+
25
42
  /**
26
43
  * Core health check service
27
44
  * Inspired by https://mobileappcircular.com/marketplace-backend-creating-a-health-check-endpoint-in-nestjs-app-using-terminus-25727e96c7d2
@@ -44,6 +61,14 @@ export class CoreHealthCheckService {
44
61
  @Optional() protected indicators?: HealthIndicatorService,
45
62
  ) {}
46
63
 
64
+ /**
65
+ * The application's Mongoose connection for the MongoDB ping (12.14.0); `null` where no MongoDB is configured.
66
+ * Injected as a property, so a project subclass with its own constructor receives it too.
67
+ */
68
+ @Optional()
69
+ @InjectConnection()
70
+ protected mongoConnection?: IHealthCheckMongoConnection | null;
71
+
47
72
  /**
48
73
  * The liveness check (`GET /health-check`, the `healthCheck` query): every check `healthCheck.configs` enables, then
49
74
  * the project's own (`additionalHealthIndicators('liveness')`). Answers the Terminus result; rejects with 503 when a
@@ -161,26 +186,36 @@ export class CoreHealthCheckService {
161
186
  const healthIndicatorFunctions: HealthIndicatorFunction[] = [];
162
187
  // The MongoDB ping where MongoDB is configured — a project on PostgreSQL alone has no MongoDB to ping
163
188
  if (this.db) {
189
+ const db = this.db;
164
190
  healthIndicatorFunctions.push(() => {
165
191
  // `timeout` stays part of the config contract, but @nestjs/terminus 12 deprecated it on the
166
192
  // indicator in favour of `.withTimeout()` on the returned attempt — translate it here, so the
167
193
  // configuration keeps working once the option is gone from the indicator.
168
- // Same effective timeouts as before: 300 ms without configured options, otherwise the
169
- // configured `timeout`, otherwise Terminus' own default (1000 ms).
170
- const { timeout, ...options } = this.config.get<MongoosePingCheckSettings>(
171
- 'healthCheck.configs.database.options',
172
- ) ?? { timeout: 300 };
173
- const attempt = this.db.pingCheck(
174
- this.config.get<string>('healthCheck.configs.database.key') ?? 'database',
175
- options,
176
- );
177
- return timeout === undefined ? attempt : attempt.withTimeout(timeout);
194
+ const {
195
+ connection,
196
+ timeout = DEFAULT_DATABASE_PING_TIMEOUT_MS,
197
+ ...options
198
+ } = this.config.get<MongoosePingCheckSettings>('healthCheck.configs.database.options') ?? {};
199
+ const key = this.config.get<string>('healthCheck.configs.database.key') ?? 'database';
200
+ const target: IHealthCheckMongoConnection | null | undefined = connection ?? this.mongoConnection;
201
+ if (!this.indicators || !target) {
202
+ // A subclass constructed without the HealthIndicatorService, or without the injected connection: Terminus'
203
+ // own check, with its readyState gate (see pingMongoDb)
204
+ return db.pingCheck(key, { connection, ...options }).withTimeout(timeout);
205
+ }
206
+ return this.indicators
207
+ .check(key)
208
+ .attempt(() => this.pingMongoDb(target))
209
+ .withFailureData((error: unknown) => ({ code: (error as { code?: unknown })?.code }))
210
+ .withTimeout(timeout);
178
211
  });
179
212
  }
180
213
  // Every SQL source answers on its own key, next to the MongoDB ping: `<key>:<source>` (`database:default`). A
181
214
  // database the application cannot reach is down, whichever one it is
182
215
  const key = this.config.get<string>('healthCheck.configs.database.key') ?? 'database';
183
- const timeout = this.config.get<MongoosePingCheckSettings>('healthCheck.configs.database.options')?.timeout ?? 1000;
216
+ const timeout =
217
+ this.config.get<MongoosePingCheckSettings>('healthCheck.configs.database.options')?.timeout ??
218
+ DEFAULT_DATABASE_PING_TIMEOUT_MS;
184
219
  if (this.indicators) {
185
220
  for (const source of getPersistenceRuntime()?.sqlSources() ?? []) {
186
221
  healthIndicatorFunctions.push(() =>
@@ -194,11 +229,33 @@ export class CoreHealthCheckService {
194
229
  return healthIndicatorFunctions;
195
230
  }
196
231
 
232
+ /**
233
+ * Pings the MongoDB the application uses (12.14.0): a real `ping` command, bounded by the check's timeout.
234
+ *
235
+ * Deliberately WITHOUT the `readyState` gate of Terminus' `MongooseHealthIndicator`, which reports "down" before it
236
+ * pings whenever the connection's `readyState` is not 1. Mongoose sets `disconnected` as soon as the driver's
237
+ * topology briefly sees no primary (a replica set without `ReplicaSetWithPrimary`, a single server turning
238
+ * `Unknown`): one lost heartbeat is enough, while the database answers in milliseconds and the application's own
239
+ * queries just wait for the driver's server selection. On a cluster with managed MongoDB replica sets that gate
240
+ * produced far more than 95 % of all "database down" alarms. Here the ping waits for server selection the same way,
241
+ * so the check reports down only when the database does not answer within the timeout.
242
+ *
243
+ * @param connection The Mongoose connection (`healthCheck.configs.database.options.connection` or the injected one)
244
+ */
245
+ protected async pingMongoDb(connection: IHealthCheckMongoConnection): Promise<void> {
246
+ if (!connection.db) {
247
+ // Not connected yet (the initial connect is still running) or never connected
248
+ throw new Error('Not connected to database');
249
+ }
250
+ await connection.db.command({ ping: 1 });
251
+ }
252
+
197
253
  /**
198
254
  * Build identity (commit / version / env) — always reported as "up", so it surfaces under `info`/`details` without
199
255
  * ever affecting the overall health status. Lets ops/monitoring detect a drifted or stale container after a partial
200
256
  * rollout (the same commit-SHA signal the admin UI compares). The commit is baked into the image at build time
201
- * (APP_VERSION_COMMIT, fed from the CI commit SHA); `version`/`env` come from the config. Opt out with
257
+ * (APP_VERSION_COMMIT, fed from the CI commit SHA); `version`/`env` come from the config, and with a build number
258
+ * (APP_VERSION_BUILD, the CI pipeline counter) `build` is reported and `version` becomes <Major>.<Minor>.<Build>. Opt out with
202
259
  * `healthCheck.configs.build.enabled: false`.
203
260
  */
204
261
  protected buildHealthIndicators(): HealthIndicatorFunction[] {