--- name: crud-automator description: Design, audit, document, refactor, and implement NestJS CRUD Automator resources using @elsikora/nestjs-crud-automator. Use when working with ApiController, ApiService, ApiFunction, ApiFunctionCustom, ApiRouteCustom, ApiMethod, ApiPropertyDescribe, ApiPropertyCopy, manual DTOs, autoDto, GET_LIST response item DTOs, transformers, validators, relation loading, subscribers, authorization policies, HOOKS/IAM, transaction scopes, Swagger contracts, or replacing hand-written NestJS CRUD patterns with native Crud Automator features. --- # Crud Automator ## Source Priority Use local source as the contract: 1. `src/interface/**`, `src/type/**`, and exported barrels define public API shape. 2. `test/unit/**` and `test/e2e/**` show supported behavior. 3. `docs/**` and `README.md` explain behavior, but may drift and must be checked against source. ## Default Workflow 1. Inspect the existing entity, service, controller, subscriber, policy, and DTO configuration. 2. Prefer native Crud Automator primitives before adding custom controllers, mappers, facades, or wrappers. 3. Verify route config against current interfaces before copying examples. 4. Validate Swagger, DTO shape, relation loading, subscriber firing, authorization decisions, and transaction behavior after meaningful changes. ## Current Contract Reminders - `@ApiController()` applies Nest `@Controller()` internally; use `path`. - `routes: {}` is valid and still generates default CRUD routes; omitted route entries do not disable routes. - Generated controller routes are `CREATE`, `GET`, `GET_LIST`, `UPDATE` (`PUT /:id`), `PARTIAL_UPDATE` (`PATCH /:id`), and `DELETE`. - `GET_MANY` is service/function/subscriber-only, not a generated HTTP route. - Route controls live under `generation`: `generation.isEnabled`, `generation.shouldWriteToController`, and `generation.decorators`. - Route security lives under `security.authentication` and `security.authorization`. - `authentication.type` is the principal category (`USER`, `ADMIN`, `ACCOUNT`, `MERCHANT`, or project string), not the bearer/security scheme. - Route-level Swagger security schemes use `authentication.securityRequirements`; one object is an AND group and multiple objects are OR alternatives. - Request config is target keyed with `EApiControllerRequestTarget.BODY`, `PARAMETERS`, and `QUERY`. - Response config is target keyed with `EApiControllerResponseTarget.RESPONSE`. - OpenAPI response headers live directly under `response.headers`, not under `EApiControllerResponseTarget.RESPONSE`. - Generated routes declare exactly the error statuses they can return: `400` and `500` always, `404` on row routes and on CREATE with `relations.request` (a securable CREATE outside the policy scope answers `403`, which the securable controller declares), `409` on CREATE, updates and DELETE, `413` and `415` on every route (Express parses a GET body, Fastify a DELETE body), `401` and `403` with any guard (`security.authentication`, `execution.guards`, `@UseGuards` on the class or the route, also on a REQUEST-scoped subclass without its own `@ApiController`, not `APP_GUARD`), `403` with a securable controller with `authorization`, plus each validator exception status, also one `HttpStatus` does not list. GET_LIST never declares `404`. Custom routes (`@ApiRouteCustom`, `@ApiMethod`) get `401`/`403` by the same rule, `429` with `throttling.default`, `400`/`413`/`415`/`500` on every route, each validator exception status, and `404` with an enabled relation in `relations.request.load.include` or any key in `relations.response.load.include`, also one set to `false`; what a handler throws comes from `response.errors`. Application-owned statuses such as a global `ThrottlerGuard` `429` go in `documentation.response.statuses`, which replaces the default response of that status. Every status requires only `statusCode` and `message`. `documentation.response.mediaTypes` (for example `["text/event-stream"]` on an SSE `@ApiRouteCustom`) documents the success response only, with the `response.type` schema when there is one (a class DTO as a component reference, a built-in type such as `String` inline as without media types, a `204` with no content); every error response stays `application/json` with its exception schema, and a `documentation.response.statuses` entry keeps its own content. Do not add `@ApiProduces` yourself: Swagger applies it to every response of the operation. - Refusal bodies the package builds carry codes only, never driver text or English reasons. A foreign key violation of the built-in create, update or delete answers `details: { type: "FOREIGN_KEY_VIOLATION" }`: a DELETE of a row still referenced (and a write the driver states hits one) is `409` `{ENTITY}_REFERENCED`, a write naming a missing row is `400` `{ENTITY}_REFERENCE_NOT_VALID`, on every driver; `ErrorForeignKeyException` builds both, logs only the schema names of `DatabaseTypeOrmGetForeignKeyViolationDetails` (never the key value or driver detail) at `verbose`, and keeps the driver error in `cause`. A body field the path decides answers `400` `{ error, message: "PARAMETERS_NOT_VALID", statusCode }` with no `details`; the `verbose` log names the property and the rule. Do not read a table, column, key value or reason from a response body. - `autoDto` is validators-only. Entity `ApiPropertyDescribe({ properties })` remains the capability baseline; generated GET_LIST `request[QUERY].filter`, `order`, and `pagination` own its generated query contract. - `ApiPropertyDescribe({ isAutoDtoEnabled: false })` keeps entity metadata, TypeORM behavior, and manual DTO use but removes the property from every generated BODY, PARAMETERS, QUERY, and RESPONSE DTO, generated Swagger relation components, and metadata-driven or typed client filter/order input. Omitted or `true` preserves normal generation. - Route/DTO `isEnabled: true`, generated GET identity, `pathScope`, `rowPath`, and query plans cannot re-enable a globally hidden property. Explicit `ApiPropertyCopy` may deliberately copy it to a manual DTO, but all other route/DTO, guard, and validation rules still apply. PAGE server-only defaults/tie-breakers may use the described scalar; CURSOR ordering cannot because it requires generated response exposure. - Manual `dto` and `autoDto` route branches are mutually exclusive. - A manual GET_LIST QUERY DTO is mutually exclusive with generated filter/order/pagination configuration. Manual RESPONSE DTOs remain compatible; CURSOR additionally requires Automator metadata proving its exact flat wrapper and same-name raw protected item fields. - Generated GET accepts top-level `identity: { parameter: "gameId" }` to rename only its primary-key wire parameter. The service predicate and HOOKS/IAM canonical identity still use the actual primary field, while the response shape is unchanged. It aliases one path field: more than one row column fails at startup. A controller path with parameters needs a complete controller-level `pathScope`. - Generated row routes (GET, PATCH, PUT, DELETE) take every primary key column in declaration order. Controller-level `rowPath: { fields }` chooses the columns and their order; empty, unknown, non-key, repeated, or `pathScope`-bound columns fail at startup. A date and time key column in the path of a composite key must be `timestamptz` with precision 0 to 3, or `datetime` with no precision or precision 0 to 3 (SQLite, MySQL, MariaDB), and takes only the canonical UTC millisecond form; a single-column key without bindings keeps its route byte for byte. - Controller-level `pathScope: { parameters: [{ parameter, field }] }` binds controller-path parameters on every generated route. With any generated route enabled, every path parameter must be bound exactly once to a distinct described direct scalar field, and wildcard or optional parameters fail at startup. A controller with all six generated routes disabled keeps any path. There is no route-level `read` key. - `pathScope` and `rowPath` are mutually exclusive with a manual PARAMETERS DTO on a route. They create route-scoped `ParametersDTO` components. Bound fields leave generated bodies; CREATE takes the value from the path and answers `400` for a body naming another one, relation keys included; writes outside the binding answer `404`. A PATCH or PUT body key column must equal its row parameter, and a key column the path leaves out cannot appear; the route checks the body as sent (copied before subscribers and transformers) and the processed body, so no pipe or transformer changes this. A body key or bound value must be the string the path carries (canonical UTC millisecond form for a date and time), and a matching one is dropped from a copy before the write, the request body unchanged. A relation whose join columns the entity declares, over one column or several, is written through the entity's own columns on every generated write, path or not: the own value (path, else body after transformers, else the raw value a pipe dropped) wins, a differing relation value answers `400`, a join column the body omits takes the value of the relation the route writes (after subscribers and transformers; a relation they or a pipe removed sets nothing, the sent copy is only compared), each join column must be a single value (an object or array there answers `400`), and PATCH/PUT keep key columns. A relation over one column is its referenced column's value (a `Date` from a transforming pipe included) or an object naming it; request relation loading still sees it, then a pure reference (a value, or an object of only the referenced and key columns) leaves the saved body unless loading replaced it with the row, so only the own column is written, while an object with other values of the related row stays for a cascade; an object naming no join column answers `400`; `null` for a key column answers `400`. A relation over several columns must be an object when the entity or path sets one of its columns (null, a scalar or an array answers `400`; clear it with a non-key own column such as `parentId: null`, or the logged reason says it cannot be cleared); a date and time key that a relation sets in a CREATE body is lifted into its own column and checked by the CREATE temporal key rule like the column, and `null` there for a key column answers `400`. Generated BODY DTOs publish a relation over one column with its referenced column's described type and format (not a UUID for a `varchar` key; left out when bound or a PATCH/PUT key) and a relation over several join columns as an object of the join columns the client may write (bound columns, and on PATCH/PUT key columns, left out; none left drops the relation), each typed from the related entity's described column; an undescribed referenced column fails at startup. A `request[PARAMETERS]` transformer on a bound field overrides the path value. Row/query predicates are AND-merged with the binding and then HOOKS/IAM scope without overwrite semantics. - A `rowPath` that leaves key columns out reads the key first, `take: 2` under the current scope and transaction. More than one match answers `500`, counting rows whose left-out instants differ only below a millisecond as two; CREATE does not read the path and reloads by every key column TypeORM saved (a date and time column matches its whole millisecond, more than one match answers `500` and rolls back); a write answers `500` before any change when a left-out date and time column holds a finer value than a millisecond. Direct `service.update/delete/get` calls apply neither setting and need the complete key. - GET_LIST order config may declare server-only ordered `defaultOrder` and `tieBreakers` entries. These validate against all described direct scalar fields, including UUID columns left out of the client order `fields`; UUID and `timestamptz` columns listed in `fields` are client-sortable. A client order pair replaces defaults, tie-breakers are appended, and duplicate fields keep the earlier entry. - GET_LIST pagination defaults to `PAGE`. Explicit `PAGE` keeps required `limit`/`page` and the count envelope. `CURSOR` keeps required `limit`, accepts at most one of `after`/`before`, omits `page`, and returns only `{ items, nextCursor, previousCursor }`. - `CURSOR` is a generated-route mode over the existing service: the first window uses one `getMany` query with `take = limit + 1`; a cursor window adds exactly one opposite-direction `take = 1` probe. It does not add a provider, read model, service, cursor table, or signing-key configuration. - A `CURSOR` order must be explicit. Every possible order field must be a selected, persisted, described, non-null direct scalar with no TypeORM value transformer or accessor and must be unconditionally raw-exposed in the generated response; the complete primary key, single or composite, must form the final explicit tie-breakers, with each component exactly once, in any order among them, after every other order entry and absent from the client order allowlist. - CURSOR v1 is PostgreSQL-only and requires the standard text result parsers. Its exact TypeORM order-declaration matrix is: `boolean`; signed `smallint` and `integer`, including increment-generated columns physically emitted through `SMALLSERIAL`/`SERIAL` DDL; numeric enums backed by `smallint` or `integer`; signed `bigint`, including increment-generated `BIGSERIAL` DDL, exposed as canonical decimal `BIGINT_STRING`; native `uuid`; and `timestamptz` with a declared integer `precision` from 0 to 3, described as `DATE_TIME` so a JavaScript `Date` round-trips exactly. An unset precision, any other precision, `timestamp`, and any date column the active driver does not store as `timestamptz`, such as an untyped `@CreateDateColumn`, fail at bootstrap; do not add microsecond or raw-text paths. Temporal token values are canonical ISO-8601 UTC strings with millisecond precision for years 0001 through 9999. Do not use `smallserial`, `serial`, or `bigserial` as TypeORM column type literals. Binary mode, custom `extra.types`, every other PostgreSQL storage type, and every other driver fail at application bootstrap, naming the route and the driver, and again before CURSOR query I/O; PAGE is unchanged. `ApiPropertyDescribe` establishes the primitive wire category and raw exposure, but request-only bounds, lengths, patterns, and `multipleOf` do not constrain the opaque seek boundary. `BIGINT_STRING` never converts through `Number`. Entity `@AfterLoad` listeners are rejected at bootstrap; applicable active TypeORM `afterLoad` subscribers fail at bootstrap and again before query I/O. Active subscriber `listenTo()` targets and PostgreSQL parser configuration are trusted TypeORM extension code and must be deterministic. - A generated controller over a TypeORM single-table-inheritance root serves polymorphic GET and GET_LIST responses with no DTO or option. Variants are compiled once at decoration from TypeORM metadata, every child entity file must be imported before the controller, and the controller constructor fails startup when a child loaded later (a REQUEST-scoped controller answers every request with a generic `500` instead, the cause only in the server log); a root with no child loaded fails the same way. The root declares and describes a selected string discriminator that stays in GET and GET_LIST responses, and values use only `[A-Za-z0-9_-]`. A child-only relation key is typed with `@ApiController>` and works in `relations.response`; in `relations.request` it fails startup by Automator's own rule (declare it on the root or use a child controller). A manual RESPONSE DTO keeps that route as it is. Filters, order, pagination, HOOKS/IAM scope, and `pathScope` stay on root columns; generated writes stay parent-only. - Every generated DTO and OpenAPI component name starts with the controller's schema prefix, the class name without a trailing `Controller`, and contains no entity name: `UserController` → `UserGetResponseDTO`, `AdminUserController` → `AdminUserGetResponseDTO`. Shared `Exception*DTO` names and user-set names such as `dto.response.name` stay as written. Several controllers on one entity are supported and each gets its own components. `@ApiRouteCustom` DTOs use the handler method name in place of the route type (`PublicUserController.getMe` → `PublicUserGetMeParametersDTO`). Nested generated DTOs at any depth are `[]DTO`; a segment uppercases the first letter and each letter after `_`, `-`, `.` or a space, drops those separators and keeps every other letter (`userID` → `UserID`, `created_by` → `CreatedBy`). A relation or dynamic object copied with `ApiPropertyCopy` is `[]DTO`, named after the DTO it is copied into. An anonymous controller class fails at decoration. Uniqueness is checked once per application at bootstrap (`app.init()`), by a check `@ApiController` attaches to the controller class, over every controller that application contains, plain `@Controller` classes included: two controller classes with one prefix, two different classes with one component name anywhere in a route schema of a generated, custom or plain route (generated, hand-written, or nested plain Swagger classes), or a lazy type that throws or returns `undefined` fail startup. Re-evaluated modules (HMR, `vi.resetModules`) and several applications in one process need nothing special. A document exported with `SwaggerModule.createDocument` without `app.init()` is not checked. - `ApiPropertyDescribe` object metadata uses `dataType`; manual `ApiPropertyObject` uses `type`. - `MetadataStorage` is keyed by class identity: `setMetadata`/`getMetadata` take the class, `getMetadata` merges the class's ancestors (nearest wins), and `getAllEntitiesMetadata()` returns a `Map` keyed by class. Resolve a `{ name }` reference with `ResolveMetadataTarget`, which reads `@Entity` registrations (`getMetadataArgsStorage().tables`), not `DataSource` metadata; an unknown or ambiguous name fails startup, a name known only through a `DataSource` fails or resolves to an unrelated same-named `@Entity` class, and an `EntitySchema` without a `target` class always fails. Subscriber, policy (rules cached per subscriber instance) and generated DTO registries, including GET_LIST item wrappers and the guard and validator classes in the DTO cache key, are keyed by class too (`apiSubscriberRegistry.getFunctionSubscribers(Class)`); requests run the subscribers of the route entity or `repository.metadata.target` class, two same-named GET_LIST item classes on one entity need distinct `name`s, one wrapper `name` cannot serve both PAGE and CURSOR routes of one entity, a class name passed to `MetadataStorage` throws a `TypeError`, and a string relation target that names several entity classes fails startup on every GET_LIST route that can filter by it, including one with a manual QUERY DTO and whichever is imported first (one loaded after controllers are instantiated fails the requests that filter through it). `GenerateEntityInformation` matches tables, columns and relations by class. Migration to 5.0.0: replace class-name strings with the class. - A controller with an enabled generated route needs a service repository for its entity, its table inheritance root, or a child of it; anything else fails startup, naming both classes and tables. Two same-named classes in one `forFeature` share one repository token, so declare them in separate modules or rename one. Non-`Repository` mocks and controllers with all six generated routes disabled are not checked. A REQUEST-scoped or lazy-loaded controller gets this check on its first generated request (500 with the error logged), but its other startup checks run at startup. Registry lookups (`getFunctionSubscribers`, `getRouteSubscribers`, `buildAggregatedPolicy`, `hasSubscriberForEntity`, `invalidateCache`) throw a `TypeError` for anything but a class. - `ApiPropertyDescribe` relation metadata does not currently accept array options. - `GetDefaultStringFormatProperties(format)` provides canonical defaults for supported string formats. - BigInt string sign options use `EApiGetDefaultStringFormatPropertiesBigIntStringSign`; the old type alias and paired-suffix validator configuration internals were removed. Import supported symbols from the package root. - Generated CREATE, UPDATE, and PARTIAL_UPDATE bodies omit date fields identified as `CREATED_AT`, `RECEIVED_AT`, or `UPDATED_AT`; responses retain them. Exclusion follows the semantic identifier rather than property names, and `DATE` remains writable. - There is no custom-only/default-disabled controller mode. Disable all six generated routes explicitly when a controller should expose only custom routes. - `generation.isEnabled: false` on a child controller also stops the route the parent controller generates. The generated handler stays callable from the child; a parent route declared with `@ApiMethod` or `@ApiRouteCustom` stays served. ## Function And Transaction Model - Service/function `create` and `update` receive `DeepPartial` directly, not `{ body }`. - Service/function `get`, `getList`, and `getMany` receive TypeORM options. - Generated service/context `delete` is `Promise`; direct decorator internals have a known return-shape inconsistency, so document and test the intended surface before changing it. - `@ApiFunctionCustom({ action, entity, transaction })` is for custom service commands that need function lifecycle, subscribers, and transaction context. - `@ApiFunctionStep({ entity, transaction })` is for internal service helper methods that need transaction context but are not standalone actions; direct calls are valid when the selected transaction mode permits. - Function steps do not create subscriber hooks, route metadata, Swagger metadata, or authorization action identities; do not model them as custom actions. - `@ApiService({ entity, functions })` can configure transaction modes for generated CRUD functions keyed by `EApiFunctionType.CREATE`, `UPDATE`, `DELETE`, `GET`, `GET_LIST`, and `GET_MANY`; omitted entries default to `SUPPORTS`, and `CUSTOM` belongs to `@ApiFunctionCustom`. - A singleton `@ApiController` with an enabled generated route fails at application bootstrap unless `service.repository` is a TypeORM repository, also when the decorator's return value is discarded: `Controller "" of entity "": service.repository is not a usable TypeORM repository because `. A controller whose generated routes are all disabled is not refused. A test may pass a repository of a PostgreSQL DataSource with built metadata and no connection, or an object with its `metadata` and `manager`, also on a CURSOR route. Nest runs no bootstrap hook on a request-scoped controller, so its GET_LIST route makes the repository and CURSOR database checks on the request (500, the named error in the log) and its other routes are unchecked. The check reads TypeORM's type markers through the properties, not `instanceof` or `in`, so a repository from a second installed TypeORM copy (pnpm workspace, monorepo) and a Proxy-wrapped repository count. In tests, provide a real repository of an in-memory DataSource (`new DataSource({ type: "better-sqlite3", database: ":memory:", entities: [E], synchronize: true }).initialize()`, then `dataSource.getRepository(E)`) under `getRepositoryToken(E)` and stub single methods with `vi.spyOn`; a plain-object repository mock or a mocked service fails at bootstrap. A generated CREATE counts its stored row through its own transaction, past the stubs, and answers 500 unless exactly one row matches the key, so let `save` store the row or insert the row a stubbed `save` answers with and leave its key out of the CREATE body, because a body that names the key of a stored row answers 409. Use a column type SQLite accepts: `type: "timestamp"` fails `initialize()` with `DataTypeNotSupportedError`. A CURSOR controller needs a real PostgreSQL DataSource with `vi.spyOn(repository, "find")`; do not switch the route to PAGE for a test. - Generated routes preflight the exact bound CREATE, GET, GET_LIST, GET_MANY, UPDATE, and DELETE function before the Automator-managed route transaction or repository I/O. It must be produced for the same entity/type by `@ApiService` or the matching built-in `@ApiFunction*`; undecorated overrides, accessors, and instance shadows fail closed at that boundary. Direct service calls are outside this route check. Generated CREATE, UPDATE and PARTIAL_UPDATE preflight the protected GET that reads their response. This is the intentional 4.0 breaking boundary. Startup refuses a generated route whose service lacks a protected function it calls (CREATE: CREATE and GET; UPDATE and PARTIAL_UPDATE: UPDATE and GET; GET: GET; DELETE: DELETE), or has one in a mode the route cannot give it: `MANDATORY` under route `SUPPORTS` or `NONE`, `NONE` under route `REQUIRED` or `MANDATORY`. CREATE always holds a transaction: route `NONE` and a `NONE` CREATE or GET function fail under every route mode, `MANDATORY` starts under every mode it accepts; this function check also runs with `manualInitialization`. - Function execution transaction modes use `EApiFunctionTransactionMode` with `transaction.mode`; subscriber requirements use `EApiFunctionSubscriberTransactionExpectation` with `transaction.expectation`. - Inside decorated service execution, use `this.getApiFunctionContext()` for `operations`, `repository`, `eventManager`, and `getRepository`. - Inside `@ApiFunctionStep`, use `this.getApiFunctionStepContext()` for `repository`, `eventManager`, and `getRepository`; it intentionally omits `operations`. - `ApiFunctionTransactionScope.runWithDataSource(dataSource, { name }, callback)` owns a named external transaction and passes its `EntityManager` to the callback; `runWithEntityManager()` is join-only and fails without an active Automator owner registry. Inside an active Automator transaction, `runWithDataSource` joins on the same `DataSource` (no `observation`) and runs on its own on another one. - Bind per-command state (such as an authority scope) to the transaction with `ApiFunctionTransactionScope.setValue(key: symbol, value)` and read it with `getValue(key)`; never pass `EntityManager` or the state through domain service arguments for this. The current transaction is the one the async context runs in (the one `runWithDataSource` joins): the owner, joined `REQUIRED`/`MANDATORY` functions, steps and function subscribers, and a same-`DataSource` `runWithDataSource` see one value; a transaction of another `DataSource` opened inside it sees none, a call back into the first `DataSource` sees it again. `setValue` throws outside an Automator transaction; values are released at commit or rollback, before `onAfterCommit`/`onAfterRollback`. `runWithValue(key, value, callback)` restores the previous value or its absence afterwards, also on throw; the value belongs to the transaction, so parallel work in it sees it too. Generated route subscribers run outside the route-owned transaction and see no value. - Release an effect that needs a value from inside the transaction (such as the id of a row it inserted) with `ApiFunctionTransactionScope.onAfterCommit(() => publish(message.id))`, never with a TypeORM transaction subscriber or a queue on the query runner. Callbacks run after the outermost COMMIT in registration order, before subscribers' `onAfterCommit` hooks, and the owner awaits them; rollback and an unknown COMMIT outcome drop them. Savepoints (`entityManager.transaction(...)` on the transaction manager or a second `startTransaction()` on its query runner) keep their own callbacks: rolled back → dropped, released → joined to the parent level. A savepoint belongs to the connection, so parallel work that registers while one is open shares its level and loses its callback when it rolls back; await savepoints before parallel registering work. Drivers that keep no TypeORM transaction depth (SAP, Spanner) refuse registration naming the driver. A failing callback stops no other callback or hook, is logged with `FormatErrorEvidenceForLog` evidence, and ends in one `ApiFunctionTransactionPostCommitException` (`COMMITTED`, stage `AFTER_COMMIT`, no `subscriberName`, `cause` = first failure). It throws with no active Automator transaction, for a non-function, and after the transaction ended (captured async context or inside a running callback); it never runs at once. In a generated route's route subscribers it throws unless an outer transaction is active; a route `AFTER` subscriber already runs post-commit and publishes directly. - Named scopes accept optional `observation: { selectors, onSettled }`. Select by exact entity constructor, native function/STEP type and method; configuration is copied before I/O, with at most 32 selectors and 256 reserved selected invocations per owner. Immutable output contains only selector index, native execution status and fractional callback duration, plus existing transaction outcome and dropped count. Durations include nested/context/subscriber work and are not isolated SQL or lock-wait time. Settlement runs once after the best-effort release attempt, context exit and terminal lifecycle, preserves native results/errors and does not await or propagate observer failures. Require bounded synchronous capture; STEP remains trace-only. Disabled/unmatched execution reads no clock, and preflight/startup failure creates no artificial measurement. - `onAfterCommit` and `onAfterRollback` run once after the outer transaction ends. Their readonly context exposes the `FUNCTION`, `ROUTE`, or `SCOPE` owner/id, all ordered events, and subscriber-matched events; events contain operation metadata only, never arguments, bodies, entities, or results, and STEP is trace-only. - Commit/rollback error lifecycle uses `onBeforeErrorCommit`, `onAfterErrorCommit`, `onBeforeErrorRollback`, and `onAfterErrorRollback`. Post-commit failures must remain distinguishable from database rollback. - Use the public `FormatErrorEvidenceForLog(error)` utility when an application deliberately logs a caught error. It emits only a bounded ASCII error type and an optional validated five-character SQLSTATE discovered through own data descriptors. Never log the error object, message, stack, cause, driver error, query, parameters, request URL, headers, IP, profile, or subscriber context. `FormatUnknownForLog` remains unchanged and is not an error-sanitization boundary. - `ApiFunctionUpdate` performs one ordinary decorated GET before `onBeforeUpdate`. Read the patch from `context.result`, the active manager repository when a transaction exists (otherwise the service base repository) from `context.DATA.repository`, and the top-level detached and frozen shallow snapshot from `context.DATA.currentEntity`. - UPDATE does not deep-clone or deep-freeze `currentEntity`. Default `SAVE` keeps nested aliases, full entity/relation/cascade persistence and no explicit reread after before-subscribers. A missing decorated GET skips update-before hooks and flows through GET then UPDATE error lifecycle. - UPDATE-only `persistenceMode: EApiFunctionUpdatePersistenceMode.PATCH` is supported by `ApiFunctionUpdate`, generic `ApiFunction`, and `ApiService.functions[UPDATE]`. It requires explicit REQUIRED/MANDATORY, the same complete equality primary key in every original/effective criteria branch, and flat selected writable direct columns. Criteria whose every branch pins a primary column to two different values (the `In([])` or `And(Equal(a), Equal(b))` an empty scope merge writes for a path id outside an own-row scope) answer `404 {ENTITY}_NOT_FOUND` like SAVE, before the identity check; criteria without a primary equality still answer `400`. Key values are compared as given: a primary key in a scope must use the key column's JavaScript type and canonical form, or PATCH answers `404` where SAVE finds the row. A null many-to-one/owning one-to-one relation over one declared join column (`{ "operator": null }`) is written as that column set to `NULL`; a null composite relation answers `400 PARAMETERS_NOT_VALID` (clear its columns by name). A scope through a relation (HOOKS `{ operator: { name } }`, an IAM field with `queryPath: "operator.name"`) answers as under SAVE (in scope `200`, outside `404`, a move out `403`, a missing related row `400 REFERENCE_NOT_VALID`): TypeORM's UPDATE cannot join, so a locking key read (`FOR UPDATE`, PostgreSQL/CockroachDB `FOR UPDATE OF` the entity, no lock on the SQLite family) checks the whole scope right before the UPDATE in its transaction, a miss is `404` (a row another writer moved out after the GET included), and the UPDATE runs by the key and the row's own column conditions. It writes only supplied fields (including explicit old values), preserves effective scope/soft-delete visibility at UPDATE and fresh-reads by criteria key/projection before AFTER without another Automator GET callback. Empty PATCH performs no UPDATE/version bump and rereads with effective scope. No initial row lock precedes UPDATE-before subscribers; the one lock PATCH takes is that key read, at the write after the BEFORE subscribers, and only when the scope or a write condition names a relation (a nested condition, an operator such as `IsNull()`/`Not(...)`/`In([...])`/`Equal(...)`, or a literal on it; all answer as under SAVE). The lock holds the written row's own columns; related rows a scope or condition reads are checked at the lock point but not locked on PostgreSQL/CockroachDB (`FOR UPDATE OF` the entity; MySQL locks them too). Spanner (TypeORM `LockNotSupportedOnGivenDriverError`) cannot run a PATCH relation scope or `addCondition`. Default SAVE is unchanged. - PATCH obtains selected columns from actual effective GET options, never hydrated own keys or constructor defaults. Unselected (including default-hidden), primary, generated, managed timestamp/version/delete-date, relation and embedded fields are not writable; functions/accessors/proxies in patch data reject. Requested relation graphs/IDs, lazy/embedded hydration, initial locks and empty/ambiguous selects reject; ordinary unloaded relations and native load hooks remain supported, with eager loading explicitly disabled when needed. Use SAVE for entity/relation/cascade semantics. Neither mode auto-loads arbitrary custom-function entities. ## Route Runtime Model - Generated route base config accepts `transaction: { mode: EApiFunctionTransactionMode }`. Omitted config and `SUPPORTS` open no route transaction, except for every generated CREATE and a scoped UPDATE/PARTIAL_UPDATE; `REQUIRED` opens or joins, `MANDATORY` requires an active owner, and `NONE` rejects an active transaction. - A CREATE with a non-empty `decision.scope.where` writes and reloads by its primary key and the scope in one transaction, opening a `ROUTE` owner under omitted config and `SUPPORTS` as well. A row outside the scope rolls back and answers `403`; only the reload's own miss becomes `403`. The reload runs inside the transaction after the insert and before the commit. Route `NONE`, a `NONE` `create` or `get` function and an undecorated `create` or `get` fail at startup, naming the controller and the reason; another `NONE` function on the path (such as one relation hydration uses) answers `500` and persists nothing. Non-scoped CREATE (no scope, `{}`, IAM Allow without conditions) runs the same way. A scope with a null value or an empty branch is a policy mistake: `500` before the write, naming the path. - The CREATE key is the primary key map TypeORM saved for the inserted row (the value TypeORM wrote into each primary column of the protected `save` result, taken from the related object for a key column that a relation also joins, reported through `ApiControllerGeneratedInsertedKeyStorage` before function subscribers), and it reads both the scope check and the response; a saved row without a value TypeORM knows for every primary column answers `500` and rolls back; a key column inside an embedded property is found, parsed and named by its property path; a date and time column matches its whole millisecond, bound through `DatabaseTypeOrmBindInstant` like every temporal read (UTC text for `timestamptz` on PostgreSQL/CockroachDB, a `Date` for `timestamp`/`datetime`, equality for `date`), a transformed temporal key matches by equality with its transformer run once, and the database must count exactly one row for the key, before and after the reload, otherwise `500` (a row another request commits into the millisecond of the key answers `500`, never in place of the created row). A date and time primary key in the body is parsed once before the transaction into the `Date` the write and its transformer receive (an instant on PostgreSQL/CockroachDB is written as its exact UTC instant), and answers `400` when it names a day or hour the calendar does not hold (`2026-02-30`, `2025-02-29`, `24:00`, checked by `IsCalendarDateTime` on the fields as written, before the offset), is finer than its column or a `Date`, has no `Z` or offset with minutes on `timestamptz`, or is the second occurrence of a repeated daylight saving hour on a wall clock column outside the SQLite family; a controller whose date and time primary key the database fills (column default, `CreateDateColumn`, generated value) fails at startup unless its driver is `postgres`, `cockroachdb` or `mariadb` (MySQL and SQLite have no `INSERT RETURNING`; MariaDB needs 10.5+), a request-scoped controller fails the same way at request time, and a key from the body works on every driver. On a single-connection driver (the SQLite family) the Automator runs the transactions it opens one at a time per DataSource; reads and writes outside them can still land inside an open transaction. Subscribers receive a `timestamptz` key on PostgreSQL/CockroachDB as a `Date` whose `getHours()` returns the UTC hour. A generated CREATE holds its pool connection for the whole request, so subscribers read through `DATA.repository`. A securable CREATE fails at startup on a date and time primary key finer than a millisecond, on every driver and from either source: declare `precision: 3` (a column without a precision passes on MySQL, MariaDB, the SQLite family, `datetime` and `smalldatetime`). `DATA.repository` keeps a `Repository` subclass, `.extend()` and a NestJS repository whose constructor takes the `DataSource`: the bound repository inherits from it and only replaces `manager` and `queryRunner`. Write custom repository code as methods: an arrow-function field (`save = async () => …`) keeps the service repository's `this` and writes through the service manager, outside the transaction; on a pooled driver (PostgreSQL, MySQL) its row stays committed after a scoped `403`, while on the SQLite family it shares the one connection and rolls back with the CREATE. A service or scope of another DataSource runs on its own connection and does not roll back with the CREATE; a call back into the CREATE's DataSource joins it again, also after a `SUPPORTS` hop without a transaction. In a route- or function-owned transaction `onAfterErrorCreate` runs after the rollback with no `eventManager` and the service repository, so a subscriber with expectation `REQUIRED` or `MANDATORY` cannot have it. A lost race (deadlock or snapshot error) answers `409` with no row left, and clients send it again. With `manualInitialization` the metadata checks wait, and the key rules run per request. - An UPDATE or PARTIAL_UPDATE with a non-empty `decision.scope.where` (HOOKS `rule.scope`, IAM Allow scope, or IAM Deny exclusion) addresses the old row through the scope (miss: `404`, nothing written) and reloads the written row by the same key and scope in one transaction, opening a `ROUTE` owner under omitted config and `SUPPORTS` as well. A body that moves the row out of the scope, including into a state a Deny excludes (`PATCH { status: "archived" }` under a Deny on `resource.status = "archived"`), rolls back and answers `403`; only the reload's own miss becomes `403`. One rule, no opt-out: a change that must leave the scope needs its own custom action (`update.archive`). Route `NONE`, or a `NONE` `update` or `get` function, answers `500` before the write, at request time. Non-scoped updates (no scope, `{}`) open no route transaction and are unchanged; a scoped one sends the same queries inside the transaction. - When a generated route opens and owns `REQUIRED`, request transformation/validation run first; request relation hydration, the generated service operation, and response relation reload share the route manager; commit lifecycle completes before response transformation, route-after, authorization result handling, and serialization. If `REQUIRED` joins an outer owner, that owner commits later. - Generated PUT and PATCH read their response through GET by the key in the request path, never by the UPDATE result; generated POST reads it by the key TypeORM saved for the inserted row, never by the CREATE result, so a primary key the database fills must be declared as generated or POST answers `500`. Under route `SUPPORTS` without a scope a reload that misses the row (`@DeleteDateColumn` set by the body, GET `onBeforeGet` filter, GET `onAfterGet` error) fails the route while the write stays (a scoped PUT/PATCH rolls back instead, and a scope move answers `403`), and with TypeORM `replication` the reload of POST, PUT or PATCH can read a stale replica; route `REQUIRED` avoids both. - Hydration, operation, and reload failures roll back a route-owned transaction. For a route that opened the transaction, route-after failures happen after commit and must not be reported as rollback. - Use `@ApiRouteCustom` for custom controller routes that need runtime behavior: transformers, validators, relation handling, subscribers, authorization result transforms, or serialization. - Register `new CorrelationIDResponseBodyExceptionFilter(app.get(HttpAdapterHost))` with the interceptor, before any app filter: guard and middleware rejections, unmatched routes, and malformed bodies never reach the interceptor. An app filter that wins must call `CorrelationIDNormalizeException(exception, host, httpAdapterHost)` and answer through the HTTP adapter. The filter is HTTP-only; never apply it to gateways. Every error body has `correlationID`, `statusCode`, and `timestamp`; an object response keeps its own shape, so a codes-only `{ code }` gets no `error` or `message`, while a string or array response, an http-errors value, and an unknown failure get both; an http-errors message reaches the client only with `expose: true`. Outside HTTP both pass the call through and log one warning per component instance; NestJS 12 runs global interceptors on gateways. - The built-in correlation interceptor emits at most one bounded log for a `5xx`. Its automatic logs omit request URLs, correlation header values, error messages, stacks, causes, queries, parameters, and driver objects while preserving the existing HTTP response and throw contract. The rethrown exception keeps the original failure in `cause` for exception filters; never send, log, or serialize the exception or its `cause`, and report only `FormatErrorEvidenceForLog(exception.cause)`. - The correlation interceptor, `CorrelationIDResponseBodyExceptionFilter` and `CorrelationIDNormalizeException` keep a client `x-correlation-id` only when it is one header of 1 to 128 characters of `[A-Za-z0-9._:-]`; anything else gets a generated UUID, and the response header and body `correlationID` always match. - Generated-route `transaction` config does not apply to `@ApiRouteCustom`; custom functions, steps, or named scopes continue to own transactions. - Root-level discriminated `@ApiRouteCustom` bodies are selected, transformed, and validated by Crud Automator, not the host `ValidationPipe`. Mirror pipe options on the body config with `validatorOptions`, `transformOptions`, and `exceptionFactory` (`ValidationPipe` semantics: sync or async, the awaited return value is thrown). The factory receives native variant `ValidationError[]` or one synthetic `mustMatchDiscriminatorMapping` error without `value`; no discriminator message echoes the rejected value. - `@ApiMethod` attaches one internal interceptor to every route it composes, generated and `@ApiRouteCustom` included: a body deeper than 64 levels, with an object of more than 1000 keys, with a key `__proto__`, `constructor`, `hasOwnProperty` or `prototype` at any depth, or with a NUL in any string or key answers `400` after the guards and before any pipe. The limits are fixed, with no option; plain Nest routes are not covered. It throws `ApiRequestValidationException`, so a host filter translates it with `ApiRequestValidationGetErrors(exception)`, not with an `exceptionFactory`. - Generated routes enforce the column rule of their path values themselves, once per request, before authorization and any query: a path value that does not fit the column's `ApiPropertyDescribe` type returns the `ValidationPipe` `400` body (`message: string[]`, `error`, `statusCode`) as `ApiRequestValidationException`: class-validator failures untouched, others with `property` = parameter and constraints `pathParameterNotCanonical`, `pathParameterNoText`, `pathParameterConversionMismatch`, `pathParameterUnstable`, or `isDefined`; a host filter translates it with `ApiRequestValidationGetErrors` and its pipe `exceptionFactory`. A configured `dto[PARAMETERS]` then validates the converted values (`forbidUnknownValues: false`): it narrows, never widens, and never changes the conversion; the Nest param type and OpenAPI come from the generated DTO. `pathScope`, subscribers, and the service get typed values (`NUMBER` → number, UUID → lower case, `BOOLEAN` → only `true`/`false`, `DATE` → `YYYY-MM-DD` string; only `DATE_TIME` becomes `Date`). Authorization (`request.parameters`, `resourcePath`, `${request.parameters.*}`, `resource.*` comparison) gets one canonical text: decimal integer, lower-case UUID, `true`/`false`, ISO 8601 UTC with ms, `YYYY-MM-DD`; the guard writes it back to `request.params`. Guards before `ApiAuthorizationGuard` see raw text. A securable `@ApiRouteCustom` must copy every path parameter its IAM `resourcePath` names from a scalar column with `ApiPropertyCopy`, or describe it with `ApiPropertyUUID`, an integer `ApiPropertyNumber`, or `ApiPropertyString` when the entity cannot be copied (startup error naming the placeholder and both sources; a described UUID must be lower-case, `400 pathParameterNotCanonical`). IAM and a HOOKS policy see the value the route's PARAMETERS DTO produces: the guard runs that DTO with and without implicit conversion (class-validator; read through the `@Expose` name; canonical text), so renames, `PickType`/`OmitType`/`PartialType`/`IntersectionType`, bare class-validator rules, and `@Transform` all count; invalid → `400` before IAM; a required property the path does not carry is left to the host pipe. A securable `@ApiRouteCustom` or `@ApiMethod` route with a path parameter, IAM or HOOKS, fails at startup (naming controller, method, parameter, and the change) without a PARAMETERS DTO, when the DTO does not describe a path parameter with a class-validator rule, `ApiProperty*`, `ApiPropertyCopy`, `@Transform`, or `@Type`, for a HOOKS DTO property without `ApiPropertyCopy` or `ApiProperty*` (a bare `@IsInt() @Type(() => Number)` has no column type; the declared DTO type decides the canonical text, and `ApiPropertyCopy` declares the column's type, so `ApiPropertyString` on an integer column keeps `016` for handler and policy alike), for a pipe other than `ValidationPipe` (class or instance) in `@UsePipes` on the method or the controller, and for a `ValidationPipe` there with `expectedType` or with another class-transformer or class-validator from `transformerPackage`/`validatorPackage` (process-wide in Nest; startup runs the pipe once on a probe DTO that passes every rule, so its `exceptionFactory` never runs; the probe DTO is declared only when such a pipe is found and stays in the class-transformer and class-validator metadata), for any pipe on `@Param` (`ParseIntPipe`), for a `@Param("id")` whose type compiles to neither `String` nor `Object` (`number`, `Date`, a class; `string`, `unknown`, `any`, and unions start), and for a `@Param()` typed as another class than the DTO. A global host pipe (`useGlobalPipes`, `APP_PIPE`) is the host's choice and is not checked. The path parameters are those of the served paths: global prefix (not on a route `setGlobalPrefix` excludes), `RouterModule` path (nested modules too), controller path, and route path; each part is read as the router of the running adapter reads it (Express: `\:x` is text; Fastify: `a::b` is text and `\:x` is the parameter `x`; another adapter: the names of both count). A wildcard (`*`, `*name`, `{*name}`) in any part of a securable route fails at startup, and so does a generated route whose `RouterModule` path or global prefix adds a parameter its generated DTO does not describe (`pathScope` binds only controller path parameters, so use `@ApiRouteCustom` with a PARAMETERS DTO). An IAM route, generated or custom, that neither lists nor creates fails at startup when its `resourcePath` names a placeholder that is not a path parameter (a generated GET `identity.parameter` counts for the field it names): it would render as `*`, which no Deny on a value matches; serve it with `@ApiRouteCustom` under that path parameter copied with `ApiPropertyCopy`, or use HOOKS. `resourceDefinition.routeParameters` does not fill it (a route-bound placeholder reads the path parameter of its name, which a generated row route never carries): serve a route-bound placeholder with `@ApiRouteCustom` and the path parameter described by `ApiPropertyUUID`, an integer `ApiPropertyNumber` or `ApiPropertyString`. A list (`route.type` `GET_LIST` or action `list`) keeps such a placeholder and maps it to row exclusions, but its handler must apply `decision.scope.where`, and its IAM action becomes `:list`, so a separate action such as `export` merges into `list`. A create (`route.type` `CREATE` or action `create`) keeps it too: it names no row yet. A request whose `request.params` holds a key startup did not record for its route, or that reaches a route startup did not check, answers `500` before the policy, the handler, and any query, logged with controller, method, and parameter; a test that replaces `ApiAuthorizationBootstrapValidationService` turns this off, but the guard then builds the rule of a custom route from its PARAMETERS DTO on its first request, so an upper-case UUID is still `400` and a route startup would refuse answers `500`. A path parameter is a UUID by any declaration: `ApiPropertyUUID`, `ApiPropertyString` with the UUID format, a bare `@IsUUID()`, or `ApiPropertyCopy` of a UUID column; an `ApiPropertyCopy` with `shouldAutoResolveContext` on a custom PARAMETERS DTO follows `route.type` + `PARAMETERS`, and one that no context reaches fails startup (a DTO with such a copy cannot serve two route types). `@Req()` and a custom param decorator read the canonical text the guard wrote to `request.params`; only their own conversion, or a pipe on them, is unchecked. The handler reads the value authorization saw, in the pipe modes none, validate-only, transform, implicit, groups, and version, or the request is refused: both conversions accept with different text → `400` (`@IsDefined() id: number`, `/016`); the canonical text is always written to `request.params`; the DTO runs again on it and an accepting conversion with other text → `400`. So a `@Transform` that changes its own output (`p-` on every call, base64 decode) cannot serve a securable route: keep it stable on its own output or convert in the handler. Transforms run several times per request and on samples at startup: they must be pure. Startup runs the same checks on samples (`true`/`false` too for a boolean, so a bare `@IsBoolean()`, `@Type(() => Boolean)`, and `value === "true"` fail; use `ApiPropertyBoolean`), naming controller, method, DTO, and the change; what a sample cannot show is checked per request on real values. Startup also fails, reading the metadata, for a path value that becomes an object or list or that the DTO drops, for two properties exposing one parameter name, for a `@Transform` with `groups`, `since`, or `until`, an `@Expose` with `since` or `until`, or a validator with `groups` on a path value, for a copied decimal column, and for `isResponse` in the DTO. On generated routes and copied columns, string text of an integer column must be `0` or `-?[1-9]\d*` (`/016`, `/-0` → `400`), an upper-case UUID path value is a `400` (`pathParameterNotCanonical`), never lower-cased, and a decimal/numeric/float/double/money column as a path value on a securable route, IAM or HOOKS, fails at startup. A Deny compares text; under a case-insensitive collation `/ABC` still finds the row of `abc`. `ApiPropertyUUID` keeps the sent text and an upper-case one is refused; bare `@IsUUID()`/`@IsDateString()`/`@IsNumberString()` keep the sent text, so add a pure `@Transform` for a canonical form. Rules are kept per controller class, so an inherited custom route follows each subclass's own `resourcePath`. Without a host `ValidationPipe` only path values, typed GET_LIST query plans, and root-level discriminated `@ApiRouteCustom` bodies are enforced; other bodies, custom route query DTOs, and a GET_LIST query without `filter`/`order`/`pagination` need the host pipe. `BOOLEAN` and `NUMBER` DTO properties check exactly the sent value, under any `@Expose` name and even under `enableImplicitConversion` (`"016"`, `true` for an integer → `400`); `DOUBLE` text is decimal text only (`0x10`, `" 16 "`, `""` → `400`); a lone value of a list field of any type is a one-item list, a comma list is one item, an empty value is one empty item the item rule checks (`?days=` → `400`; a string list gives `[""]` only if its rules allow `""`). A body or query UUID is never lower-cased: on every `ApiMethod` route (generated or custom), a value the `@Body()`/`@Query()` DTO validates as a UUID (`ApiPropertyUUID`, UUID-format `ApiPropertyString`, a relation by its UUID key, bare `@IsUUID()`, nested `@Type` DTOs, `@Expose` names) that is not lower-case is a `400` `ApiRequestValidationException` with constraint `uuidNotCanonical` and `property` = dotted path (`parentId`, `items.0.id`, query name), before any pipe and any query, with or without a host pipe (since 5.0.1); a generated GET_LIST UUID filter answers `400 FILTER_NOT_VALID`. HOOKS/IAM scope values that are upper-case UUIDs match nothing. Integer text must be canonical (`016`, `1e3`, `0x10` → `400`). An integer `NUMBER` bound outside the safe integer range fails at startup; describe `bigint` as `BIGINT_STRING`. HOOKS/IAM scope values merged against a column are converted to its type. - One row has exactly one accepted path spelling, or the route stops at startup (IAM and HOOKS, generated and custom): a path value on a text or integer column takes any matching description; a `uuid`, enum, boolean or date column only its own type (`UUID`, `ENUM`, `BOOLEAN`, `DATE`, or `ApiPropertyCopy` of it), so `STRING`/`ApiPropertyString` over it fails startup, also when the column is reached through a custom route's `resourcePath` placeholder (field `queryPath`, then `pathScope` binding, then the property of that name); `decimal`, float, `time`, `year`, `interval`, `inet`, `macaddr`, `set`, `bit`, JSON and array columns fail with any type (`ApiControllerParametersReadKeyDescribeTypes`). A UUID path value is only lower-case 8-4-4-4-12; `-0` and other non-canonical integer text answer `400 pathParameterNotCanonical`; a `bigint`/`int8`/`int64` value outside the signed 64-bit range answers `400` as a path value (`pathParameterOutOfRange`), a filter value (`FILTER_NOT_VALID`) and a body value (`isSignedBigIntText`, also under `BIGINT_STRING`, checked before any pipe like the lower-case UUID, so no host `ValidationPipe` is needed). - LIKE family filters (`cont`, `contl`, `starts`, `startsl`, `ends`, `endsl`, `eql`, `nel`, `inl`, `notinl`, array `cont`/`excl`) read client text literally on every database: `%`, `_` and `\` match themselves (`ApiControllerGetListQueryLike`: bound `Like`/`ILike` escaped by `\` on `DATABASE_DRIVER_TYPE_CONSTANT.LIKE_BACKSLASH_ESCAPE` drivers, else a `Raw` `LIKE :p ESCAPE '!'`, page lists only, since CURSOR is PostgreSQL-only). `IApiControllerGetListQueryOperatorDescriptor.compile(operand, driverType)` and `ApiControllerGetListQueryRuntime.compileWhere(ast, driverType)` take the driver. - Every generated controller, with or without authorization, fails startup on a `mysql`/`mariadb`/`aurora-mysql` DataSource whose `@@SESSION.sql_mode` or `@@GLOBAL.sql_mode` holds `NO_BACKSLASH_ESCAPES` (`DatabaseTypeOrmAssertBackslashEscapes`, cached per DataSource; request-scoped and manually initialized controllers check on the first generated request and answer `500`). Remove the mode; the Automator never sets session modes. - An IAM document record whose `namespace` is not a non-empty string is invalid before the namespace filter: `500` with the invalid-document failure. A stored-row placeholder column resolves by the field that maps it, then the `pathScope` binding of the parameter of that name, then the entity property of that name (`AuthorizationPlaceholderResolveQueryPath`). The simulator reads `resource.operator.id` from a nested `{ operator: { id } }`; a flat `{ operatorId }` does not count. With no DataSource the portable dialect applies: a plain Allow allows, a String equality on text, UUID or enum grants nothing. - A `resourcePath` placeholder listed in `resourceDefinition.routeParameters` reads the route parameter of its name as canonical path text and no column (`AuthorizationPlaceholderIsRouteBound`): use it for a controller whose rows are no entity of the application, keeping the entity as an anchor for its own condition columns. Any other placeholder must read a column, or startup fails naming the resource, the placeholder and the three fixes (a `resource.` field, a `pathScope` binding, or `routeParameters`); a `routeParameters` entry that is also a column of the entity fails startup too. On a list or a create a Deny that constrains a route-bound placeholder refuses the whole request (`403`) and an Allow that constrains it does not apply. - `ApiPropertyNumber` and `ApiPropertyBoolean` convert canonical text (`"5"`, `"true"`) only where the request carries text: a query, a path, and a form or multipart body on an `@ApiMethod` route. A JSON body must send JSON numbers and booleans, list items and nested objects included: `{ "count": "5" }` returns the usual validation `400`, under any host pipe and `enableImplicitConversion`. Generated QUERY and PARAMETERS DTOs convert and generated BODY DTOs do not; a hand-written DTO class converts only once a route reads it with `@Query()` or `@Param()` (whole or keyed) or as a configured `dto[QUERY]`/`dto[PARAMETERS]`, and one class read both from a JSON body and from a query or path fails at startup. No number format is text in JSON; `BIGINT_STRING` (`ApiPropertyString`) stays a string. - Use `@ApiFunctionCustom(...)` and `@ApiRouteCustom(...)`; response types belong on method return types and response metadata, not decorator generic parameters. - Use `@ApiMethod` as the low-level metadata/Nest/Swagger/security/throttling composer. - `execution.guards` (generated routes, `@ApiRouteCustom`, `@ApiMethod`) accepts plain guards or staged `{ guard, stage? }` entries with `EApiRouteGuardStage`. `@ApiMethod` composes one chain: `BEFORE_AUTHENTICATION` → `security.authentication.guard` → `AFTER_AUTHENTICATION` → `ApiAuthorizationGuard` → `AFTER_AUTHORIZATION`, keeping declaration order within each stage. Plain guards and omitted `stage` are `BEFORE_AUTHENTICATION`. A function or an object exposing `canActivate` (prototype chain included) is treated as a plain guard instance and its other properties, such as `guard` or `stage` fields, are ignored; every other object is a staged guard descriptor whose `guard` must be a guard class or instance. Use `AFTER_AUTHENTICATION` when a guard needs `request.user` (for example a `ThrottlerGuard` subclass whose `getTracker` returns the principal id; the stock tracker uses `request.ip`). Global `APP_GUARD` guards run before the whole staged chain. - `@ApiMethod` metadata lives under `metadata.resource`, `metadata.route`, `metadata.response`, `metadata.security`, and `metadata.throttling`. - Securable custom methods, declared or inherited, need `resource.action` and a `resource.entity` equal to the controller entity; startup fails otherwise. - Never put a plain Nest route (`@Get`, `@Post`, `@All`, `@Sse`) on a securable controller, directly, inherited, or as an override: startup fails. Use `@ApiRouteCustom` or `@ApiMethod`, or move the route, a health check included, to a controller that is not securable. There is no public or skip option. `@MessagePattern`, `@EventPattern` and `@SubscribeMessage` handlers are refused as well, with or without `@ApiMethod`, because the caller of those transports writes the payload the guard would read as the request: move them to a controller that is not securable. Do not replace a handler on the instance, such as `this.report = this.report.bind(this)`: Nest takes guards from that function, so startup fails, and a request-scoped controller answers `403`. A securable controller also needs `ApiAuthorizationModule` in the application, or startup fails; a test harness imports the module and overrides `ApiAuthorizationBootstrapValidationService` and `ApiAuthorizationRuntime`. The replaced `evaluate` returns a complete `IApiAuthorizationDecision` built with the enums (`EApiPolicyEffect.ALLOW` is `"Allow"`) and with `transforms: []`: a generated route runs the decision's `transforms` on the response, so `{ effect: "allow", principal: { id: "test" } }` answers `500`. Return `EApiPolicyEffect.DENY` to test a `403`. See the authorization guide, Test Harness. - Custom route response relation reload requires `controller.service` to extend `ApiServiceBase` and response items to have an `id`. - For `@ApiRouteCustom`, request relation loading hydrates only the method `@Body()` argument; custom route before-hook auth, headers, IP, metadata, and runtime properties live in `context.DATA`, not `context.result`. - Generated GET_LIST `request[EApiControllerRequestTarget.QUERY]` accepts optional sibling `filter`, `order`, and `pagination` sections. Omitted pagination means `PAGE`; omitted filter/order sections take their fields from entity metadata in PAGE mode, and a route without a typed filter validates its QUERY DTO itself, with or without a host `ValidationPipe`, including a `400` for any filter group key the DTO does not publish. Configured sections compile into one immutable plan used by dynamic DTO generation, OpenAPI, strict runtime parsing, and TypeORM compilation. `order.defaultOrder` and `order.tieBreakers` provide deterministic server compound ordering while client input remains one `orderBy`/`orderDirection` pair. - UUID filter fields support `in`/`notin` like boolean, enum, number, and string fields (each `[values]` item must be a UUID), on direct paths such as `id` and one-hop paths such as `currency.id`. The root primary key is a filter only on a route with a typed filter; a route without one answers `id[...]` with `400`. The plan signature includes allowed operations, so widening a baseline renames the generated query schema and invalidates previously minted CURSOR tokens once with `CURSOR_NOT_VALID`. - A column the list response hides (`select: false`, `isExpose: false`, a disabled GET_LIST response side, a response guard the route guard does not match, or a field a manual list response DTO leaves out) is never filterable or orderable: requests naming it return `400` before any SQL, a typed config enabling it fails at startup, and a PAGE route with a manual list response fails at startup until its generated filters match that response. - Typed query plans support direct and one-hop to-one scalar filter paths, declared relation filters (deeper and to-many property paths in `fields`, link entities in `links` through `ApiControllerGetListQueryLink`, each compiled to one `EXISTS`), direct-scalar order paths, `INHERIT` overlays or `REJECT` allowlists, exact disabled fields, narrowed operations, and `OMIT`/`REJECT`/`USE_DEFAULT` missing behavior. - Entity columns and relations are read from the entity class and each named parent class TypeORM maps, stopping at the first class without a name, and a column declared again on a subclass is listed once. Name the class a mixin returns, or its columns are not mapped. - The authoritative typed parser runs after route-before and request path/query transforms/validators, applies `USE_DEFAULT` when a field group is absent, and rejects malformed or disallowed input independently of host `ValidationPipe`. The route then validates the generated QUERY DTO, so typed and legacy routes share one rule: lowercase `orderDirection`, the `orderBy`/`orderDirection` pair, 1–100 membership `[values]`, the entity value constraints the OpenAPI schema publishes, `YYYY-MM-DD` calendar text and `HH:mm:ss` time text compared as written for `date`- and `time`-format fields, and the UTC instant `YYYY-MM-DDTHH:mm:ss.sssZ` for date-time fields. Allowed typed operations follow the describe kind; a `string` property accepts every operation a text-stored kind supports, and bootstrap checks the exact set. The optional route transaction then compiles predicates, AND-merges query filters with path scope and then authorization scope, applies the effective order, and runs the service query. CURSOR tokens bind the route, path values, query-plan signature, normalized filter AST, and effective order; `limit` and recalculated HOOKS/IAM scope are intentionally not token context. - GET_LIST date-time filters: Build server-side temporal values as Date. Strings must be UTC instants with Z. A Date built from zone-less text is read in the process TZ. A route-before subscriber may write a `Date`; a typed `defaultCondition` takes a `Date` or a UTC instant string and fails at startup, naming the controller, route and field, for any other string. - CURSOR remains a GET_LIST authorization action (`onBeforeGetList`) but uses the GET_MANY function lifecycle. Its BEFORE chain runs exactly once per HTTP request against detached base options; only the candidate `where` and `withDeleted` are captured and reused for the main window and opposite probe, while AFTER runs for each actual query. Generated calls re-AND mandatory scope/window `where`, restore route-owned `order`/`take`, force an own `cache: false`, shadow `select`/`skip`, reject subscriber `join`/`lock`, and reject later changes to protected row cardinality, sequence, raw order/primary tuples, cursors, or flat envelope. Direct GET_MANY calls keep their ordinary per-call subscriber contract. - Every generated mandatory read forces `cache: false`, including against inherited and global TypeORM query caching. Requested relations plus effective `relationLoadStrategy: "query"` plus data-source cache `alwaysEnabled: true` fail closed before repository I/O because relation-loader subqueries cannot inherit the root cache bypass; use join loading or disable the global always-on cache. - PostgreSQL and CockroachDB reads never bind a `Date` into a `timestamptz` condition or a parsed `Date` of a temporal primary key: on PostgreSQL and CockroachDB the loader binds every `Date` compared with a driver-normalized `timestamptz` column (filters, scopes, keys, service where clauses) as canonical UTC text after the column transformers ran once on every operand of the condition, while other drivers bind what the transformers return, and a composed condition (`And`, `Not`) on any transformed temporal column runs the transformers once per operand on every driver, and an invalid `Date` fails before query I/O; a client filter value on a date or time column outside its published form (`YYYY-MM-DD`, `HH:mm:ss`, or the UTC instant `YYYY-MM-DDTHH:mm:ss.sssZ`, of a day that exists in years 0001–9999) answers `400` on every GET_LIST route and every column, default routes included; and a paged read of a `timestamptz`/`timestamp`/`date` primary-key entity with joins (include, eager, relation filters) loads text page keys first, then exactly those entities; it orders only by its own columns. `relationLoadStrategy: "query"` from a temporal-PK entity or over a temporal join column, and to-many `@RelationId`/`loadRelationIds` of such an entity, fail at bootstrap (every generated route that is not disabled, listed or not, and its request relation loads; eager relations under a `"query"` load always count) or before query I/O (other reads); use `relationLoadStrategy: "join"`. - CURSOR custom `{ itemType }` DTOs must use compatible Automator `ApiProperty*` response metadata for every potential order/primary field under the same name; full wrappers must prove exactly `items`, `nextCursor`, and `previousCursor`. The final plain projection is asserted, so `@Expose` aliases, `toPlainOnly` transforms, accessors, and route/authorization transforms cannot mask or rewrite protected values. - The package does not provide a consumer-side typed URL/bracket-filter builder in the current 3.x contract; that deferral does not change the server-owned typed query contract. ## Relation Model - Request relation config: `relations.request.reference` and `relations.request.load`. - Request load config uses `relations.request.load.include`, optional `relations.request.load.relationLoadStrategy`, optional `relations.request.load.services` overrides, and optional direct-relation `relations.request.load.locks`. - `relations.request.load.include` is the single source of truth for direct request relations to hydrate. Omitted service keys use `${relationName}Service`. Include and lock keys must be relations on the route entity or a parent class, and the rest of the block must be valid, or decoration fails on every enabled route; nested keys and services fail at application bootstrap. On a CREATE route, generated or custom with `route.type` CREATE, an enabled include of a `OneToMany` or inverse `OneToOne` (no `@JoinColumn` on this side) also fails decoration: a create only inserts, and binding an existing row writes its foreign key. Bind such rows through the UPDATE of the related row, setting its to-one reference to the parent. The generated CREATE body does not declare these relations, and a CREATE body that references existing rows through one (a key value, or an object with only the related primary key, alone or in an array) answers `400` `property should not exist` and writes nothing. New related rows with their own values still insert through the cascade, and one whose key exists answers `409`. The host pipe decides first, since the body does not declare the key: without a pipe a reference answers `400`, an existing row with values `409` and a new row with values inserts; behind `whitelist: true` alone all three answer `201` with the key dropped without a word; behind `forbidNonWhitelisted: true` all three answer `400`. - Request locks accept native TypeORM `pessimistic_read` or `pessimistic_write`, require an active Automator transaction (a lock on a route with `transaction.mode: NONE` fails at decoration; otherwise a missing transaction fails at request time, because an outer scope can provide one), follow direct `include` declaration order, and disable implicit eager-relation loading. A locked direct relation with explicit nested includes requires `relationLoadStrategy: "query"`; nested loads share the manager without automatic locks. - A generated PUT or PATCH changes an owned to-one relation (ManyToOne, owning OneToOne), eager or not, nullable or not, one join column or several, through its key column or its relation property. A body whose key column and relation differ answers `400`; `null` for one that does not allow it answers `400`; a key of a missing row answers `400` `{ENTITY}_REFERENCE_NOT_VALID` with `details: { type: "FOREIGN_KEY_VIOLATION" }`; a move out of the scope answers `403` and rolls back. In `service.update()` and a function `onBeforeUpdate` subscriber a key column moves a loaded relation too, a relation they name decides, and the saved object then holds a reference with only the join values, not the related row. An update that names neither a relation nor its key keeps the stored key, also when the read loads the relation as `null` because the related row is soft deleted; such a relation stays `null` in the response and in the saved object. The save writes only the relations the update names: an eager `ManyToMany` keeps its link to a soft deleted row, and an eager cascaded relation does not save its related row. - HTTP scalar references are controller hydration input. Service `create`/`update` contracts remain entity-based; direct callers load entities through their active manager. - Response relation config: `relations.response.reference` and `relations.response.load.include` with optional `relationLoadStrategy`. - `OBJECT` and `SCALAR` are the supported destructive response reference projections. Do not assume `FULL` or `PRESERVE` modes exist. - HTTP generated relation filters use explicit one-level paths such as `author.id[...]` and `author.username[...]`; top-level `author[...]` is not generated or transformed. A typed plan can narrow these paths, and only an explicit enabled entry of a typed plan reaches deeper or through a to-many relation. - Generated relation filters skip to-many relations, and relation fields and object fields on the related entity; a route without a typed filter answers them, and any other query key its QUERY DTO does not publish (`_=…`, `utm_source`), with `400 property should not exist`. - GET_LIST filters need a flat query parser (Fastify's default, Express's `simple`); Express's `extended` parser rewrites `label[operator]` groups into nested objects before the route reads them. - For nested request or response relations, use TypeORM relation object maps in `load.include`. - Nested request include objects are only passed to the direct relation service as TypeORM `relations`; nested request references are not recursively hydrated. ## Subscriber Model - Import `ApiSubscriberModule`, register subscriber classes as Nest providers, and mark observed controllers/services with `@ApiControllerObservable()` / `@ApiServiceObservable()`. - Route subscribers receive route-shaped results such as `{ body, parameters, query, headers, ip, authenticationRequest }` in before hooks. - Custom route subscribers receive `{ body?, parameters?, query? }` in `context.result`; read auth/header/IP data from `context.DATA`. - Route subscriber authorization expectations are declared on `@ApiRouteSubscriber({ authorization: { expectation } })`; they are type-only. Use matching class/context generics with `EApiRouteSubscriberAuthorizationExpectation.REQUIRED` only when the route contract guarantees `authenticationRequest.authorizationDecision`. - Function subscribers receive service payloads directly; do not use `context.result.body` in function subscribers. - Function subscriber transaction expectations are declared on `@ApiFunctionSubscriber({ transaction: { expectation } })`; they are not inferred from service/function config. Use matching class/context generics for `REQUIRED` or `MANDATORY` so `context.DATA.eventManager` narrows to `EntityManager`. - Every function context's DATA carries `principal`: the deep-frozen principal the guard resolved for the route request (generated routes and `@ApiRouteCustom`), the same object for every function of that request. It travels by `AsyncLocalStorage`, so nested service calls (an update's internal GET, a service call in a custom handler) and functions called from callbacks the request registers (after-commit hooks) see it; it is `undefined` on direct calls, routes without authorization, and in work started outside a request. Async work started during a request (`setInterval`, an emitter listener registered in the request, a consumer or pool started lazily by a request) inherits that request's principal for its whole life, so jobs and consumers see none only when they start outside a request: start long-lived workers at bootstrap. Read the actor from it instead of threading it through service arguments. - `onBeforeUpdate` and `onBeforeDelete` (only those: `TApiSubscriberFunctionBeforeUpdateContext`, `TApiSubscriberFunctionBeforeDeleteContext`, `IApiSubscriberFunctionExecutionContextWriteData`) get `context.DATA.addCondition(where)`: append-only conditions ANDed into the criteria and the authorization scope under SAVE, PATCH and delete, never widening or replacing the scope; relation paths are allowed. A row a condition excludes answers `404 {ENTITY}_NOT_FOUND` through AFTER_ERROR, unchanged, exactly like a row outside the scope (never `403`). PATCH puts conditions in its UPDATE WHERE (locking key read first when they name a relation: nested condition, operator or literal); SAVE update and delete add one locking key read with scope and conditions right before the write, only when a condition was added, so without one the queries are unchanged. It needs a transaction: without one it throws `Function "." needs a transaction to add a write condition: configure its transaction mode as REQUIRED`. A call after the BEFORE chain throws. Conditions never make the criteria address a row: `delete({})` (or an `onBeforeDelete` returning `{}`) with a condition is still refused and removes nothing; `update({}, …)` is refused by its read before any BEFORE hook. The SAVE/delete lock keeps the read's soft-delete visibility (a row read live must still be live). An empty or widening WHERE throws when added. An `ApiFunctionTransactionScope.onAfterCommit` callback registered in a BEFORE subscriber belongs to the enclosing transaction: if a caller catches the `404` of a condition miss and the outer transaction commits, the callback still runs, so register publishing callbacks in AFTER subscribers (such as `onAfterUpdate`). - Custom hooks are `onBeforeCustom`, `onAfterCustom`, `onBeforeErrorCustom`, and `onAfterErrorCustom`. - Higher `priority` runs earlier; returned non-`undefined` hook results flow to later subscribers. ## Authorization Model - Use `EApiAuthorizationMode.HOOKS` plus `ApiAuthorizationPolicy` for code-first app rules. - Use IAM mode for policy documents, principal resolution, document sources, attachment sources, and boundaries. - Register `@ApiAuthorizationPolicy()` classes as Nest providers. - IAM policy document `Resource` values match literally or with wildcards; `{id}` placeholders belong in `resourceDefinition.resourcePath`. Every `Action` and `Resource` pattern, Allow and Deny alike, is a glob: `*` matches any sequence (empty, `:` and `/` included) at any position, `?` exactly one code point; `${*}`, `${?}` and `${$}` are the literal characters. On a list a pattern reads as every row, no row, some rows (`ApiAuthorizationIamResourcePattern` maps it to one glob per placeholder, in one way only) or ambiguous. Some rows compile into the scope, in an Allow and a Deny alike: `/item-1`, `/item-*`, `/?`, `/*-1` (exact values on every dialect, globs where the dialect is exact, which excludes portable for an Allow). Ambiguous, such as `tenant/*/item/x` on text columns, denies the whole list for a Deny and grants nothing for an Allow, unless the column's database type cannot hold the separator (uuid on PostgreSQL, integer and date on PostgreSQL, MySQL and MariaDB, boolean). A create names no row: only a `*` that covers every placeholder allows it; a Deny `Resource` reads as on a list, so a row it names is refused with `403` when the create reads it back, nothing is stored, and an ambiguous one denies every create. A row route reads a pattern twice, by the path text and on the stored row (a placeholder a path value fills whose column is text, compared exactly: the column of the field that maps it, filterable or not, else the entity property of its name; any other column keeps the path text; no column fails a pattern that constrains it closed, a `*` over it is unaffected), so another spelling a collation finds answers `404` under a Deny `Resource`; an Allow `Resource` and a Deny `NotResource` apply where both readings match, an Allow `NotResource` and a Deny `Resource` where either does. A path or body value that holds `/` or another non-alphanumeric character the `resourcePath` writes after its first placeholder names no resource: Allow grants nothing, Deny `403`. An `Action` pattern must reach the namespace (`iamPolicyPatternOutsideNamespace`) and takes no variable; `Resource` takes `${principal.id|type|attributes.*|claims.*}` and `${request.parameters.*}` (embedded, with a default; an unresolved one grants nothing in an Allow and denies the request in a Deny); `${resource.*}` and client-controlled values are refused. `NotAction` applies to actions no pattern matches. `NotResource` applies to resources no pattern matches, and takes the same variables: an unresolved one never counts as a miss, so an Allow grants nothing and a Deny denies. On a list an Allow `NotResource` scopes to the rows no pattern names and a Deny keeps only the rows a pattern names; on a create a pattern that names some rows leaves an Allow unmatched and denies for a Deny. - IAM keys and variables come from one registry (`AUTHORIZATION_POLICY_CONTEXT_KEY_CONSTANT`). Variables: `${principal.id|type|attributes.*|claims.*}`, `${request.parameters.*}`, `${request.ip}`, `${request.sourceIp}`, `${request.time}`, `${resource.*}`. String, IgnoreCase, Like and ARN values may embed them and take `${x, 'default'}` (an empty default `''` in a Like/ARN value or a `Resource`/`NotResource` pattern is refused at save and at load: `iamPolicyConditionValueInvalid`, `iamPolicyPatternInvalid`); Numeric, Date, Bool and IP values take only a whole-value variable, type kept. A variable with no scalar value and no default leaves an Allow unmatched and makes a Deny answer `403`. Client-controlled `${request.body|query|headers.*}`, `${principal.roles|groups}` and `request.secureTransport` are refused (`iamPolicyVariableNotAllowed`, `iamPolicyConditionKeyNotAllowed`). `request.time` is captured once per request (simulator: `time`), Date and `Null` only. `request.sourceIp` is `request.ip`: only as sound as `trust proxy`/`trustProxy`, never a boundary until only your own proxies are trusted. A `resource.*` key must be mapped and `isFilterable` by a `resourceDefinition` of the namespace, which bootstrap registers in `ApiAuthorizationIamResourceDefinitionRegistry`. - Check policy documents on save with `ApiAuthorizationIamDocumentValidator.assertSavable(document, { namespace })` (400, one `AUTHORIZATION_POLICY_DOCUMENT_FAILURE_CONSTANT` code per path), `inspect` for the list, or `@IsApiPolicyDocument({ namespace })` on a DTO; run them after bootstrap so `resource.*` keys are known. `AUTHORIZATION_POLICY_DOCUMENT_LIMIT_CONSTANT` holds at save and at load: at most 256 statements and 131,072 JSON characters (`iamPolicyDocumentInvalid`), 2,048 characters per pattern (`iamPolicyPatternInvalid`) and per condition string (`iamPolicyConditionValueInvalid`). Only the attached documents of the request's namespace are read and checked: another namespace's attached document is skipped, an unasked one ignored, an invalid one of this namespace answers `500`, and a boundary of another namespace denies. - An IAM `${resource.*}` condition value fails closed while no resource is loaded, which is every HTTP route, generated or custom: a `principal.*` or `request.*` key compared with it fails an Allow and holds for a Deny, and a `resource.*` key compared with it does not compile. Only a loaded resource (simulator, runtime from custom code) reads it. Compare rows as `"resource.tenantId": "${principal.attributes.tenantId}"`. - IAM documents follow one strict grammar (`ApiAuthorizationIamParser`), at save and at load. `EApiPolicyConditionOperator` names every AWS operator family (String, IgnoreCase, Like, Numeric, Date, Bool, Null, IpAddress, Arn, with `IfExists`), and the engine evaluates all of them in memory and in SQL, each exact or failing closed per dialect (values: exact decimals, never a float; ISO 8601 instants with a zone and at most milliseconds, or `YYYY-MM-DD`, no epoch; IP address or CIDR; colon-delimited ARN). A positive operator is false on a missing key or `NULL`, a negated one true; `IfExists` holds only when the key is missing, a `NULL` column of a present row takes the base operator; String families read `NULL` as `""`, ARN as no value. Each family must fit the mapped column (`iamPolicyConditionKeyTypeMismatch`, `400` at save, `500` at load): String on text/UUID/enum/boolean, IgnoreCase/Like/ARN on text, Numeric on numeric except money, Date on date/datetime/timestamp/timestamptz (`YYYY-MM-DD` only on `date`, an instant only on the others), `Bool` on boolean, IP on `inet`/`cidr`, `Null` anywhere. Per dialect: IgnoreCase is ASCII-only folding, exact on PostgreSQL (`lower(c COLLATE "C")`) and SQLite (`GLOB`), fail closed on MySQL/MariaDB; Like via `LIKE` or `GLOB`; Numeric exact on PostgreSQL and MySQL/MariaDB integer and decimal, doubles at most 15 digits, MySQL `FLOAT` fails closed, SQLite at most 15 digits or a safe integer; Date on a wall-clock column reads the process time zone, the second instant of a repeated hour fails closed, and a value finer than a MySQL column's precision fails closed (a bare `datetime` holds seconds, so `${request.time}` fails closed on it); IP on PostgreSQL only; ARN on PostgreSQL only, as an anchored regex. `BinaryEquals` and `StringLikeIgnoreCase` are refused for good. A key takes a scalar or a list (at most 64); a positive operator holds on any match and a negated one on no match, in memory and in SQL, one unresolved value fails the whole key closed, and an object or `null` is invalid. `ForAnyValue:`/`ForAllValues:` read multi-valued keys (`principal.roles|groups`, lists under `principal.attributes|claims.*` and `request.body|query.*`) with AWS semantics, and are refused on single-valued keys (`iamPolicyConditionQualifierUnsupported`): on a missing, `null` or empty set `ForAllValues` holds and `ForAnyValue` fails unless `IfExists`; a `null` or object in a context list fails closed. A `resource.*` key mapped as `.` needs a qualifier (`iamPolicyConditionQualifierRequired`) and compiles to `[NOT] EXISTS (...)` with `Raw`; a NULL related column takes the base operator, a soft-deleted related row does not count, a loaded resource must hold the whole relation or the key fails closed, and any other to-many path stops startup. A document source returning a refused document makes the request `500`, so a statement the engine cannot enforce is never evaluated. A key whose runtime value is a list or an object fails closed under every operator without a qualifier. - IAM values on a boolean column are only `true` or `false`, as a string or a boolean, in `resource.*` conditions and exact row-scoped Deny patterns; any other literal (`"1"`, `"TRUE"`, `"yes"`, `1`) is refused by the grammar (`iamPolicyConditionKeyTypeMismatch`, `500` at load), and a variable resolving to another value does not compile and fails closed. A boolean column is found through TypeORM metadata at any depth of `queryPath` (relations, embedded, inherited, STI), with or without `@ApiPropertyDescribe`, and includes `bit`; a `queryPath` TypeORM cannot resolve to a column does not compile either, nor does any key of an entity no TypeORM decorator maps. - IAM `resource.*` keys follow one rule in SQL and in memory: a loaded resource is read through each field's `queryPath` (load the relations it crosses), an unmapped key fails closed, and a path through a missing to-one relation (`NULL`, soft-deleted, or a foreign key naming no row) is a missing key at any depth, so `StringEqualsIfExists` holds for it in an Allow scope and a Deny alike. A `queryPath` through a OneToMany or ManyToMany relation stops startup; passed to the simulator it fails closed (Allow not matched, Deny holds). - IAM String operators compare exactly (code points: case, accents, trailing spaces) on every database. Bootstrap registers each IAM entity's SQL dialect in `ApiAuthorizationIamDialectRegistry` (`EApiAuthorizationIamDialect`: POSTGRES, MYSQL, MARIADB, SQLITE, PORTABLE, UNRESOLVED) and the planner lowers to it: MySQL/MariaDB through `CONVERT(c USING utf8mb4) COLLATE utf8mb4_0900_bin`/`utf8mb4_nopad_bin` (older servers or a non-`utf8mb4` connection fail closed), PostgreSQL `citext` through a `text` cast and collated columns under `COLLATE "C"` (`char(n)` fails closed; on `uuid` and enum columns a value other than a lower-case UUID or a declared enum value lowers to a match-nothing condition (`In([])`, a negated one to `IS NOT NULL`) instead of erroring, as MySQL, MariaDB and SQLite compare it, the rest compare natively), SQLite collated columns under `COLLATE BINARY` and prefixes through `GLOB`. PORTABLE fails String equality and text placeholders closed (its collation may ignore case); `aurora-mysql` probes as MySQL/MariaDB and `aurora-postgres` is POSTGRES. SQLite `GLOB` keeps a row with a NUL character in neither form. A wall-clock instant whose local wall clock leaves the years 0001 to 9999 fails closed. A placeholder text no row of a typed column renders (`abc`, `1e1` on a decimal; `2024-01-01` on an instant; `yes` on a `boolean`) names no row instead of reaching the database. A CURSOR list merges the `Raw` SQL the lowerers write with its keyset predicate and refuses any other `Raw`. Header keys read in lower case (`request.headers.X-Foo` is `x-foo`), paths read own properties only (`principal.attributes.constructor` is missing), an IPv4-mapped range reads as IPv4 for a request address. A NUL character in a path value answers `400 pathParameterNulCharacter`, in a string filter value `400 FILTER_NOT_VALID`. A to-many key on a related column with a value transformer is refused (`iamPolicyConditionKeyTypeMismatch`, `500` at load). A dialect that cannot express a key exactly fails it closed (Allow not matched, Deny `403`); it never approximates. String keys compare only text, UUID, enum or boolean columns (`EApiAuthorizationIamColumnFamily`); on numeric, date, JSON, array, binary or other columns the grammar refuses them (`iamPolicyConditionKeyTypeMismatch`). `Raw` lowerings fail closed on a column with a `transformer`. A loaded resource renders a `NULL`/`""` placeholder as `""`. A matched Allow without `resource.*` keys allows every row. Parameters are named `iam` + 24 hex of a hash, values bound as canonical text. - IAM Deny never fails open: compilable `resource.*` keys become row exclusions that keep exactly the rows the in-memory evaluator allows (lists hide rows, row routes 404); non-compilable keys, `""`/`null` values, oversized scopes (more than 128 branches across Allow statements, in identity × boundary, or with the Deny exclusions, checked before each merge), and `resource.*` Deny on CREATE deny the whole request; row-specific `Resource` Deny on `list` (GET_LIST or a `:list` custom action) excludes those rows, and on CREATE refuses a stored row it names with `403` and a rollback. Custom routes must apply `decision.scope.where`, which already carries the exclusions. - Authorization resolver caches default to `EApiAuthorizationCacheMode.SOURCE_FIRST`: every evaluation reads hooks permission, IAM attachment, and IAM document sources without cross-request map reads, writes, or stale fallback. - `MEMORY` is explicit process-local opt-in and requires positive safe-integer `ttlMs` and `maxEntries`; each resolver cache receives its own bound. - In memory mode, use `ApiAuthorizationCacheInvalidationService` when resolver backing data must be visible before TTL expiry. - Hooks policy-rule caching is separate, default-disabled, and can still be enabled per registry or policy; clear an enabled rule cache when its rules change regardless of resolver mode. `clearAll()` clears both cache families. ## Verification Checklist - Generated Swagger matches request and response contracts. - Every declared error status is reachable with the route config, and its body passes the declared `ExceptionDTO` schema. - DTO fields are scoped correctly for body/query/parameters/response. - GET_LIST uses the intended response mode: full wrapper DTO or `{ itemType, name? }`. - Typed GET_LIST DTO/OpenAPI fields match the normalized plan, two controllers over one entity receive distinct plan-scoped schemas, and strict parsing remains effective with host query whitelist changes. - Generated read PARAMETERS DTO/OpenAPI fields exactly match the configured GET identity alias and inherited path mappings, manual PARAMETERS DTO exclusion holds, authorization receives the canonical primary field, and identity/query → path → IAM criteria remain conjunctive on conflicts. - GET_LIST defaults/tie-breakers accept described UUID scalars without listing them in client `fields`, replace defaults on client order, de-duplicate predictably, and keep page/limit results deterministic for an unchanged dataset. - CURSOR DTO/OpenAPI exposes `limit`, optional paired client order, filters, and optional exclusive `after`/`before`, never `page`; its response is the flat three-field envelope. Tokens reject cross-route/path/filter/order reuse before database I/O, while current path and HOOKS/IAM predicates plus the one-shot GET_MANY candidate remain mandatory on both window and probe queries. - Route generation, transaction mode, security, request/response targets, relation locks, and DTO config type-check. - Subscribers fire on the route/function path being exercised. - Authorization metadata, policy documents, resource definitions, and cache invalidation match runtime behavior. - No wrapper helper was added where a native primitive is already clear. ## Additional Resources - For detailed source-aligned guidance, see [reference.md](reference.md). - For copyable patterns, see [examples.md](examples.md). - For common failure modes, see [pitfalls.md](pitfalls.md). - Version 3.0.2 is the published baseline before the current source. The generated-route capability boundary requires a major release; see [Migrating to 4.0](../../docs/guides/migrating-to-4-0/page.mdx). Release automation owns the exact publishing version.