How immerjs/immer works
1. What this repository is
- This is the Immer library: a TypeScript/JavaScript immutability engine that lets callers “mutate” a draft and then produces a new immutable tree.
- The core architectural flow is: user code calls produce or related APIs, Immer creates a draft proxy, records mutations, and then finalizes the result into a new persistent state.
2. Public API boundary
- The main runtime entrypoint is src/immer.ts, with supporting internals in src/internal.ts.
- The library exposes a small API surface around state transformation: produce, curried produce variants, current, original, patch generation, and configuration on the Immer class.
- Most consumers should only see this boundary; the rest of src/core, src/plugins, and src/utils are implementation details.
3. Core state-management pipeline
- src/core/scope.ts manages per-operation draft scopes, including nested produce calls and bookkeeping for proxies and finalization.
- src/core/proxy.ts creates and manages draft proxies that intercept reads/writes.
- src/core/finalize.ts turns drafts into immutable output, applying copy-on-write semantics and optional freezing.
- src/core/current.ts supports “snapshot of current draft state” behavior without completing the full produce cycle.
- These modules form the main data path: draft creation → mutation tracking → finalization.
4. Plugin-based feature extensions
- src/plugins/patches.ts adds patch and inverse-patch generation.
- src/plugins/mapset.ts enables support for Map and Set drafts, which are not handled by the base object/array proxy path alone.
- src/plugins/arrayMethods.ts provides special handling for array behaviors that need draft-aware interception.
- src/utils/plugins.ts likely acts as the registration/feature-flag layer for these optional behaviors.
- Architecturally, the core is intentionally small and the more specialized behaviors are isolated behind plugin boundaries.
5. Data model and draftability rules
- src/utils/common.ts, src/utils/env.ts, and src/utils/errors.ts hold shared logic for runtime checks, environment-specific behavior, and error reporting.
- Draftability decisions are central to Immer’s behavior: the library must distinguish plain objects/arrays from non-draftable values and special containers.
- This logic determines whether a value is proxied, copied, left untouched, or rejected.
6. Type system and compatibility layer
- The repo supports multiple typing ecosystems: TypeScript sources under src/, Flow definitions under src/types/index.js.flow, and external/internal TS type definitions.
- src/types/types-external.ts and src/types/types-internal.ts separate public API typing from internal implementation typing.
- The presence of __tests__/flow and __tests__/tsconfig.json shows type-compatibility is treated as part of the architecture, not just documentation.
7. Testing architecture
- __tests__ is broad and behavior-driven, covering base behavior, currying, patches, map/set, freezing, regressions, redux integration, and type-related scenarios.
- Snapshot coverage appears in __tests__/__snapshots__ and production snapshots in __tests__/__prod_snapshots__, indicating the build output is compared as part of validation.
- Test files are organized by feature, so the test suite doubles as a map of the library’s feature boundaries.
8. Performance validation
- __performance_tests__ and perf-testing/ are separate from correctness tests and focus on benchmarking and profiling the mutation/finalization pipeline.
- These scripts include large-object, incremental-update, and benchmark scenarios, which suggests performance is a first-class concern in the architecture.
- The repo distinguishes between functional correctness and runtime efficiency, which matters for understanding why the proxy/finalize pipeline is carefully split.
9. Documentation and website subsystem
- website/ is a standalone Docusaurus documentation site with its own package.json, sidebars, theme customization, localization, and static assets.
- Docs are not just marketing: they describe feature boundaries such as patches, freezing, map/set support, TypeScript, and update patterns.
- readme.md is the top-level summary, but the website is the real user-facing knowledge layer for the library.
10. Build and release toolchain
- The package uses tsup.config.ts for bundling and vitest.config.ts / vitest.config.build.ts for testing and build-related validation.
- GitHub Actions workflows in .github/workflows handle test, docs publication, and release automation.
- The repo also includes coverage configuration, formatting config, and CI setup, indicating a mature library packaging pipeline.
11. Generated/public artifacts
- _site/ contains generated documentation output, likely used for publishing the docs site.
- images/ stores branding assets such as the Immer logo used in the README and site.
- These are not runtime dependencies, but they matter for understanding distribution and publication boundaries.
12. Overall architectural picture
- The repository is structured around a small immutable-state engine at its center, surrounded by optional feature plugins, type-definition compatibility, and a large validation/documentation envelope.
- A useful diagram would show user calls entering produce/API entrypoints, flowing through draft proxy creation and scope tracking, then through finalization, with optional branches for patches, Map/Set, and current snapshots.
- Around that core sit the test suite, performance benchmarks, docs site, and release tooling that validate and publish the library.
Main entry points: immer.ts Immer API · proxy.ts Proxy drafts · scope.ts Scope · finalize.ts Finalize
Components 22
Core runtime
Draft creation, mutation tracking, and finalization.
- Immer class · Class-based configuration and API surface for advanced usage.
src/core/immerClass.ts - Scope · Tracks per-operation draft state, nesting, and bookkeeping.
src/core/scope.ts - Proxy drafts · Creates draft proxies and intercepts reads and writes.
src/core/proxy.ts - Finalize · Converts drafts into immutable output and applies freezing.
src/core/finalize.ts - Current snapshot · Produces the current draft state without ending the produce cycle.
src/core/current.ts
Extensions
Optional feature paths layered on top of the core.
- Patches · Generates patches and inverse patches from draft changes.
src/plugins/patches.ts - Map/Set · Special draft support for Map and Set containers.
src/plugins/mapset.ts - Array methods · Draft-aware handling for array behaviors and mutations.
src/plugins/arrayMethods.ts - Plugin wiring · Shared plugin registration and feature-flag helpers.
src/utils/plugins.ts
Public surface
Entry points and shared API typing.
- Immer API · Main public runtime entrypoint for produce and related APIs.
src/immer.ts - Internal API · Internal exports and wiring shared across the implementation.
src/internal.ts - Common utils · Runtime checks and shared utility logic.
src/utils/common.ts - Env utils · Environment-specific behavior and platform checks.
src/utils/env.ts - Errors · Central error and assertion handling for the library.
src/utils/errors.ts - External types · Public TypeScript types exposed to consumers.
src/types/types-external.ts - Internal types · Implementation-focused TypeScript types used inside the repo.
src/types/types-internal.ts
Validation
Tests and performance checks that guard behavior and speed.
- Behavior tests · Feature-oriented correctness tests and snapshots.
__tests__ - Perf tests · Benchmarking and profiling for mutation and finalization paths.
__performance_tests__ - Perf tooling · Standalone scripts and configs for immutability benchmarking.
perf-testing
Docs and release
Website, generated docs, and packaging/release tooling.
- Docs site · Standalone Docusaurus documentation and localized content.
website - Generated site · Built documentation output used for publication.
_site - Build config · Bundling, test, and validation configuration for the package.
tsup.config.ts
Connections 26
- Immer API → Scope: starts · Public API opens a draft scope for each produce call.
- Immer API → Proxy drafts: drafts · Entrypoints create proxies that capture mutations.
- Immer API → Finalize: returns · Public calls eventually finalize into immutable results.
- Internal API → Immer class: exposes · Internal wiring supports configuration and advanced API behavior.
- Scope → Proxy drafts: creates · Scopes manage the lifecycle of draft proxies.
- Proxy drafts → Finalize: tracks changes · Proxy mutations feed the finalization step.
- Finalize → Current snapshot: supports · Finalization pipeline shares logic with current snapshot creation.
- Current snapshot → Immer API: used by · Current snapshots are exposed through the public API boundary.
- Plugin wiring → Patches: enables · Plugin wiring activates patch generation.
- Plugin wiring → Map/Set: enables · Plugin wiring activates Map/Set support.
- Plugin wiring → Array methods: enables · Plugin wiring activates special array handling.
- Map/Set → Proxy drafts: extends · Map/Set support plugs into draft proxy behavior.
- Array methods → Proxy drafts: extends · Array-specific interception complements base proxying.
- Common utils → Proxy drafts: guards · Shared helpers inform draftability and runtime checks.
- Env utils → Common utils: specializes · Environment logic feeds shared utility decisions.
- Errors → Scope: reports · Errors are surfaced from scope and lifecycle checks.
- External types → Immer API: types · Public types describe the external API.
- Internal types → Scope: types · Internal types support core runtime implementation.
- Behavior tests → Immer API: verifies · Behavior tests exercise the public API and feature boundaries.
- Behavior tests → Patches: covers · Test coverage includes plugin features and snapshots.
- Perf tests → Finalize: measures · Benchmarks focus on the mutation-to-finalization pipeline.
- Perf tooling → Perf tests: drives · Standalone tooling runs benchmark and profiling scenarios.
- Docs site → Immer API: documents · Docs site explains the public API and usage patterns.
- Generated site → Docs site: publishes · Generated site is the built output of the docs system.
- Build config → Immer API: packages · Build config supports bundling and release validation.
- Build config → Behavior tests: validates · Test/build config connects to the validation suite.