Для AI-агентов
Краткая и точная шпаргалка для coding-агентов (Claude Code, Cursor, Copilot...), которые работают с библиотекой. Тот же текст (на английском — так надёжнее для агентов) поставляется в npm-пакете как AGENTS.md (лежит в node_modules/@alt-point/active-models/), а индекс llms.txt публикуется рядом с этим сайтом.
Подсказка: сошлитесь на него из CLAUDE.md / AGENTS.md своего проекта:
Перед работой с моделями прочитай node_modules/@alt-point/active-models/AGENTS.md.@alt-point/active-models — guide for AI agents
Use this file when writing code with this library (a consumer) or on it (a contributor). Full docs: https://alt-point.github.io/active-models/ · Source of truth is src/ and tests/.
What it is
Reactive, self-validating DTO models built on Proxy + legacy TypeScript decorators. A model class extends ActiveModel; each field is declared with @ActiveField(options).
Requires "experimentalDecorators": true in tsconfig (legacy decorators, not TC39 stage-3).
import { ActiveModel } from '@alt-point/active-models/ActiveModel'
import { ActiveField } from '@alt-point/active-models/decorators'
import { EventType } from '@alt-point/active-models/types'
class User extends ActiveModel {
@ActiveField({ readonly: true }) id: string = ''
@ActiveField({ validator: (_m, prop, v) => { if (!v) throw new TypeError(`${prop} required`) } })
name: string = 'Guest'
@ActiveField({ hidden: true }) passwordHash: string = ''
@ActiveField({ factory: Address }) address?: Address // nested model (arrays too)
}
const user = User.create({ id: '1', name: 'Ann' }) // ALWAYS create via the factory
user.name = 'Bob'
JSON.stringify(user) // hidden fields are excludedImports: one subpath per capability, no root entry
import ... from '@alt-point/active-models' does not resolve (no barrel). Import each capability from its own subpath, so a bundler only includes what you use (ActiveModel alone is ~8 KB gzipped; collections, maps, sets and scalars cost nothing until imported).
| Subpath | Exports |
|---|---|
/ActiveModel | ActiveModel, type InvariantCheck |
/decorators | ActiveField, ActiveFactory, GetterMethod, SetterMethod, InvariantMethod, isHidden, isFillable, isProtected |
/types | EventType and every option / payload type (FactoryOptions, CollectionOptions, ActiveFieldDescriptor, EventListener, ...) |
/pipeline | ValidationError; types ValidationIssue, ValidationResult, ValidationCode, FieldRules, Transform, Transitions, CoerceTo, ValueType, Coercible, Bound |
/ActiveCollection, /ActiveMap, /ActiveSet | the class of the same name (ActiveCollection also exports type CollectionInput) |
/collectionRegistry | isCollection |
/scalars/Decimal, /scalars/Money, /scalars/LocalDate, /scalars/immutable | Decimal (+ DecimalInput, RoundingMode); Money, minorUnits; LocalDate; markImmutable |
/CallableModel, /utils | CallableModel; types ModelProperties, RecursivePartialActiveModel |
Containers are opt-in: a model, @ActiveField and the rest never load ActiveCollection / ActiveMap / ActiveSet. To use a typed container in a field, import it and describe the field with it: @ActiveField({ container: ActiveCollection.field(Task, { sortBy: 'id' }) }).
Rules that prevent the most bugs
- Build models with
Model.create(data), nevernew Model(data). Field initializers run after the constructor and overwrite the datanewfilled in. (createLazyreturns an existing instance as-is.) - Lists:
Model.createFromCollection([...]).create([...])throws. - Async data:
Model.asyncCreate(promise),asyncCreateFromCollection(promise). - A
validatorrejects by throwing or by returningfalse(aValidationError, codevalidator). It runs only when the value actually changes, so it can't enforce "field is required" — check keys beforecreate(). - Never rely on a listener to veto a write (the value is already written); use
validator. - Replace values instead of mutating them in place:
m.items = [...m.items, x], notm.items.push(x)— in-place mutation emits no events (nestedActiveModels viafactorydo bubbletouched). - Don't reach into the raw object: the
targetinbeforeSetValue/afterSetValue/nulling/beforeDeletingAttributepayloads is the raw instance — read only. - There is no
model.emitterand nostartTracking()(removed in 4.0) — see migration below.
@ActiveField options
| Option | Effect |
|---|---|
value / attribute | default for a key absent from create() data (value or () => value) |
validator(model, prop, value) | throw or return false to reject |
setter(model, prop, value, receiver) / getter(model, prop, receiver) | transform on write / read |
readonly: true | can be set once at creation, later writes are silently ignored |
fillable: false | data can never set it; direct assignment throws |
hidden: true | excluded from Object.keys, spread, in, JSON.stringify, isTouched(); still readable directly |
protected (default true) | delete throws; set false to allow delete |
factory: Model / [Model, () => default] | wrap nested object / array items in Model; many: false / true refuses the other shape |
on: { afterSetValue, ... } / once | field-level hooks, shared by all instances (and subclasses) |
Validation pipeline (every write)
transform (trim/lowercase/uppercase/fn) → coerce → same value? stop → transitions → rules → validator → events. Rules: required (not null/undefined/''), type, min/max (number or Date), minLength/maxLength, pattern, oneOf (array or TS enum). A refused write throws ValidationError (.issues). model.validate() → { valid, issues } covers all fields, including ones never set (required), nested models and collections (history[1].city); assertValid() throws; create(data, { validate: true }) too. transitions: { new: ['paid'], paid: [] } restricts state changes (first value and creation from data are free); canTransition(), allowedTransitions(). static strict = true refuses writes to undeclared properties. Rules are bypassed when values are restored (undo/rollback). Cross-field rules: @InvariantMethod('msg') static ok(m) { return … } / Model.defineInvariant(name, check), checked by validate()/transaction()/atomic fill(), not per write. model.transaction(fn) is all-or-nothing (rolls back on a throw or an invalid result; async ok); fill(data, { atomic: true }). Tracked models ({ tracked: true }) have changes(), dirtyFields(), isDirty(f), revert(f?), reset(). create(data, { history: true | { limit } }) enables undo()/redo()/canUndo()/canRedo()/clearHistory(); a transaction is one step.
Events
EventType: beforeSetValue, afterSetValue, nulling (non-null → null only), beforeDeletingAttribute, touched, created. Payloads: { target, prop, value, oldValue }; beforeDeletingAttribute → { target, prop }; touched/created → { target } (the model itself).
const off = user.on(EventType.afterSetValue, ({ prop, value }) => {}) // one instance; returns unsubscribe
User.on(EventType.created, ({ target }) => {}) // every instance + subclasses
user.once(...) / User.once(...)create()emitscreatedsynchronously;new Model()emits it in a microtask. Children before parents.touchedis not emitted during creation.createdlisteners must be registered beforecreate()(useModel.on, orstatic beforeFill(model, data)to reach the instance under construction).- Listener errors: all listeners run, then the first error is rethrown (several →
error.errors).
Other API
model.fill(data, force?)— partial update; ignores unknown /fillable: falsekeys unlessforce. Does not re-applyvaluedefaults.model.toJSON()— hidden/functions/symbols dropped; honorstoJSON()(Date),Set→array,Map→object.model.clone()— deep, fully working proxied copy (hidden kept, locks +isTouchedbaseline carried).model.makeFreeze()— shallow; later write/delete throwsTypeError.- Dirty tracking:
Model.create(data, { tracked: true });model.isTouched()→true/false, orundefinedif never tracked. Reset the baseline by re-creating the model.model.getRaw()returns the frozen source data exactly as passed to thatcreate()(pre-defaults, pre-strip),undefinedif untracked.{ tracked: 'shallow' }keeps the field values by reference and compares them withObject.is(O(fields), no deep copy): a reassignment counts, an edit inside a nested model or collection does not;revert()puts the kept instance back. - Mapping:
Model.mapTo(Target, (m, ...args) => ...),model.mapTo(Target, lazy = true, ...args),hasMapping(Target).lazy(default) falls back toclone();lazy: falsethrows. - Collections:
ActiveCollection.create(Model, items, { sortBy, compare, order, coerce })/ActiveCollection.createFromData(Model, data, opts)(every item throughModel.create()) /@ActiveField({ container: ActiveCollection.field(Model, options) })give anActiveCollection: an array that accepts only instances of that model (plain objects are coerced unlesscoerce: false; anything else throws), never has holes, and — withsortBy/compare— stays sorted (pushinserts in place, items move when their key changes,bisectLeft/Right,findByKey,range).unique: 'field' | fnrejects duplicate keys atomically (ValidationErrorcodeunique;getByKey/hasKey).ActiveMap.create(Model, { key }, items)(map.addAll(iterable)adds a batch later) /ActiveSet.create(Model, items, { unique })and thecontainer: ActiveMap.field(Model, { key })/container: ActiveSet.field(Model, opts)field options give the keyed / set flavours with the same rules (.field(), not.of()—ActiveCollectionextendsArray, whose staticofis taken). Events:itemsAdded,itemsRemoved,touched(bubbles into the parent model). Use its own methods, notArray.prototype.x.call(collection)(guarded but not atomic). - Scalars:
@ActiveField({ coerce: Money | Decimal | LocalDate })turns strings/numbers/objects into immutable value objects (Money.of('19.99','USD'),'19.99 USD';Decimal.from('0.1').add('0.2');LocalDate.from('2026-09-25')). Never usenumberfor money.min/maxwork with any value havingcompareTo()(mixed currencies fail the bound). Custom class: staticfrom(),compareTo,toJSON,markImmutable(Class). CallableModel— instances are callable, implement__call.
Migrating 5.x → 6.0
No codemod. Model.create(primitive) / new Model(primitive) throw a TypeError (an empty model before). Enum, EnumItemType and the /Enum entry are gone: use a TS enum or a string union with oneOf (the codemod prints a MANUAL line for them). A validator that returns false refuses the write (ignored before). transaction() rolls back from a journal of writes, so an in-place mutation of a plain value (m.tags.push(x)) stays after the rollback - replace the value instead. Details: docs/en/migration-6.md.
Migrating 4.x → 5.0
Run npx @alt-point/active-models migrate <dir> (dry run; --write applies, --check for CI): it rewrites root imports into subpath imports in ts/tsx/js/jsx/mjs/cjs/vue files and the collection API as below; leftovers are printed as MANUAL with file:line. No root import (use subpaths); collection/map/set field options → container: ActiveCollection.field(...) / ActiveMap.field(...) / ActiveSet.field(...); Model.collection() / createCollection() → ActiveCollection.create() / createFromData(). Details: docs/en/migration-5.md.
Migrating 3.x → 4.0
model.emitter.on(...) → model.on(...); form.startTracking() → form = Form.create(saved, { tracked: true }); create([...]) → createFromCollection([...]). Details: docs/en/migration.md.
Contributing to this repo
bun install
bun run typecheck && bun run lint && bun run test # all must pass
bun run test:coverage # thresholds enforced
bun run test:perf # performance budgets
bun run test:mutation # Stryker mutation testing
bun run build # tsup -> dist/
bun run test:dist # smoke test of the built package (after build)
bun run docs:dev # VitePress- Tests use a custom esbuild transform (
vitest.config.ts) so they compile decorators exactly like the published build; don't replace it with SWC/oxc — class-field/Proxy timing differs. - Every public capability is a tsup entry and a
package.jsonexportssubpath (+typesVersions); there is nosrc/index.ts. Adding one means touchingtsup.config.ts,exports,typesVersions(tests/package-entries.test.tsfails otherwise) andtypedoc.json. Internals (meta,emitter,history,equal,clone,collectionCore,mapper,journal) must stay unexported. Zero runtime dependencies is enforced. bun run test:distchecks the built package (ESM + CJS load by subpath and share one copy of every class);tests/treeshake.test.tsbundles each entry and fails if it pulls in code it should not, or grows past its size budget.- Style: no semicolons, single quotes,
space-before-function-paren(enforced by ESLint). - Add a test for every behavior change and update
docs/(RU) +docs/en/(EN) +CHANGELOG.md. - Versioning is strict SemVer (rules at the top of
CHANGELOG.md): breaking → MAJOR, feature → MINOR, fix → PATCH. Record every user-visible change under## [Unreleased]in the same commit and mark breaking commits with!(fix!:) plus aBREAKING CHANGE:footer. - Commit messages: conventional commits; do not add co-author footers.