diff --git a/.changeset/config.json b/.changeset/config.json index 546785e5..a870da3f 100644 --- a/.changeset/config.json +++ b/.changeset/config.json @@ -14,6 +14,7 @@ "updateInternalDependencies": "patch", "ignore": [ "classy-store-angular-example", + "classy-store-docs", "classy-store-nextjs-example", "classy-store-solid-example", "classy-store-svelte-example", diff --git a/.changeset/stable-one.md b/.changeset/stable-one.md new file mode 100644 index 00000000..d2243912 --- /dev/null +++ b/.changeset/stable-one.md @@ -0,0 +1,26 @@ +--- +"@codebelt/classy-store": major +--- + +Release 1.0.0, the first stable version. The public API and its behavior are now covered by semantic versioning. + +**Breaking changes** + +- Store methods and array operations are transactions. Synchronous subscribers, including every framework adapter, are notified once when the outermost call returns instead of once per property write. A `sort` or `unshift` on a long list is now one notification and one snapshot. +- `subscribe()` on a nested proxy observes only that proxy's subtree. It no longer fires for sibling changes. +- Each `subscribe()` call is an independent registration; subscribing the same callback twice yields two subscriptions. +- A frozen object held in a store is an immutable value, kept by reference and never proxied. That covers any object you freeze, a snapshot assigned into a store, and one read through React's auto-tracked hook. Reading a nested object through a frozen object no longer throws. +- `persist`: hydration is per field. A stored field is restored unless that same field was edited locally while the read was in flight, and a local edit can no longer overwrite the stored record before it is restored. Stored data whose version differs is ignored unless `migrate` is provided. +- `shallowEqual` returns `false` for values with different prototypes, compares dates by instant and maps and sets one level deep, and no longer treats arbitrary key-less objects as equal. +- `devtools()` returns a handle with `dispose()` instead of a function, and no longer declares anything on the global `Window` type. +- Angular: `injectStore` is renamed `injectClassyStore`. +- Solid: the adapter requires Solid 2 (`solid-js@^2.0.0`). +- Every error message now reads `@codebelt/classy-store [code]: facts`, with a stable code such as `[not-a-store]` or `[getter-cycle]`; the adapters' messages share that prefix. Match on the code, not the text after it. The documentation's "Errors and warnings" page lists every code. + +**Other changes** + +- `withHistory`: undo and redo remove top-level fields that the restored entry lacks, `undo()` steps back over an edit made in the same tick, and unchanged fields keep their identity. +- Reactive collections compare keys and values by identity, so a plain object works as a key whether it is given raw, as a store proxy or as a snapshot. Lookups scan the raw backing array. +- `batch(run)` is exported to group direct writes made outside a store method into one synchronous notification. +- `PROXYABLE` is exported so a class can opt into nested reactivity with `static [PROXYABLE] = true`. +- The package declares `engines.node >= 22` and exports `./package.json`. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 718003b0..30912709 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -8,18 +8,29 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v6 + # The floor guard compares against the commit the pull request started from. + with: {fetch-depth: 0} - uses: actions/setup-node@v6 with: node-version: "24" - uses: oven-sh/setup-bun@v2 with: - bun-version: "1.4.3" + bun-version: "1.4.4" - run: bun install --frozen-lockfile - run: bun run lint - - run: bun run test + # A pull request is checked out as a merge of its head into main; the + # guard judges the branch's own commits, up to the head. + - name: Floor of CONSTRAINTS.md (no silenced check, skipped test or loosened rule) + run: node scripts/floor-guard.mjs --head ${{ github.event.pull_request.head.sha }} + - name: Unit tests, with every source file at full line and function coverage + run: bun run test:coverage # Packed-consumer typechecks resolve the package's generated declarations. - run: bun run build - run: bun run typecheck + - name: Published package shape (publint, arethetypeswrong) + run: bun run --filter @codebelt/classy-store check:package + - name: Bundle size budgets + run: bun packages/classy-store/tests/size/runSize.ts - name: Solid 2 example production build run: bun run --filter classy-store-solid-example build - name: Angular 22 example production build diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index b30be12a..ec4e3a50 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -26,8 +26,9 @@ jobs: node-version: "24" - uses: oven-sh/setup-bun@v2 with: - bun-version: "1.4.3" - - run: bun install --cwd website --frozen-lockfile + bun-version: "1.4.4" + - run: bun install --frozen-lockfile + # Builds the library first: the site runs the package from this repository. - run: bun run docs:build - run: bunx playwright install --with-deps chromium working-directory: website diff --git a/.github/workflows/react-compatibility.yml b/.github/workflows/react-compatibility.yml index f68bb146..71197595 100644 --- a/.github/workflows/react-compatibility.yml +++ b/.github/workflows/react-compatibility.yml @@ -11,14 +11,19 @@ jobs: fail-fast: false matrix: react: ["18.0.0", "18.3.1", "19.0.0", "19.3.1"] + node: ["24"] + # The package declares Node 22 as its minimum; prove it on one consumer. + include: + - react: "19.3.1" + node: "22" steps: - uses: actions/checkout@v6 - uses: actions/setup-node@v6 with: - node-version: "24" + node-version: ${{ matrix.node }} - uses: oven-sh/setup-bun@v2 with: - bun-version: "1.4.3" + bun-version: "1.4.4" - run: bun install --frozen-lockfile - run: bun run build - run: node packages/classy-store/tests/compatibility/runCompatibility.mjs "${{ matrix.react }}" diff --git a/.github/workflows/react-next.yml b/.github/workflows/react-next.yml index dc76f37e..101e2b1e 100644 --- a/.github/workflows/react-next.yml +++ b/.github/workflows/react-next.yml @@ -20,7 +20,7 @@ jobs: node-version: "24" - uses: oven-sh/setup-bun@v2 with: - bun-version: "1.4.3" + bun-version: "1.4.4" - run: bun install --frozen-lockfile - name: Use Ubuntu archive mirror for browser dependencies run: | diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 46826ef2..e91ce365 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -21,7 +21,7 @@ jobs: node-version: "24" - uses: oven-sh/setup-bun@v2 with: - bun-version: "1.4.3" + bun-version: "1.4.4" - run: bun install --frozen-lockfile - run: bun run build - name: Create Release PR or Detect Publishable Versions diff --git a/.gitignore b/.gitignore index b412f5cf..8ecf3e05 100644 --- a/.gitignore +++ b/.gitignore @@ -37,6 +37,11 @@ report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json # Finder (MacOS) folder config .DS_Store +# Worktrees of helper agents. Each holds its own biome.json, which Biome +# refuses as a nested root configuration. +.claude/worktrees/ +.claude/settings.local.json + # Browser test artifacts playwright-report test-results diff --git a/CLAUDE.md b/CLAUDE.md index f510353a..2784be75 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,34 +4,42 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co ## What This Library Is -`@codebelt/classy-store` is a class-based reactive state management library (~2.3 KB gzipped) for React, Vue, Svelte, Solid, and Angular. You define state as a plain TypeScript class, wrap it with `createClassyStore()`, and get a reactive proxy back. Class getters become automatically memoized computed values. ES6 Proxy intercepts mutations, batches them via `queueMicrotask`, and notifies framework-specific bindings via immutable snapshots with structural sharing. +`@codebelt/classy-store` is a class-based reactive state management library (core about 3.7 KB minified and gzipped; about 4.9 KB with the React hooks) for React, Vue, Svelte, Solid, and Angular. You define state as a plain TypeScript class, wrap it with `createClassyStore()`, and get a reactive proxy back. Class getters become automatically memoized computed values. ES6 Proxy intercepts mutations and notifies subscribers through immutable snapshots with structural sharing: framework bindings synchronously, ordinary subscribers batched via `queueMicrotask`. ## Monorepo Layout ``` packages/classy-store/src/ -├── core/core.ts # Layer 1: Write Proxy — createClassyStore(), subscribe() +├── index.ts # Main entry: createClassyStore, snapshot, subscribe, batch, shallowEqual, PROXYABLE +├── storeRuntime.ts # Runtime shared by every entry and both module formats (#store-runtime) +├── types.ts # Public Snapshot, SubscribeOptions +├── core/core.ts # Layer 1: Write Proxy — createClassyStore(), subscribe(), transactions, computed getters +├── core/ownership.ts # StoreInternal: one node per object, parent links, detached subtrees +├── core/core.types.ts # DepEntry, ComputedEntry ├── snapshot/snapshot.ts # Layer 2: Immutable snapshots — snapshot(), structural sharing -├── types.ts # Snapshot, StoreInternal, DepEntry, ComputedEntry -├── index.ts # Main barrel: createClassyStore, snapshot, subscribe, shallowEqual ├── collections/collections.ts # ReactiveMap and ReactiveSet (array-backed Map/Set emulation) -├── collections/index.ts # Collections barrel: reactiveMap, reactiveSet, ReactiveMap, ReactiveSet +├── collections/index.ts # Collections entry: reactiveMap, reactiveSet, ReactiveMap, ReactiveSet ├── frameworks/ -│ ├── react/react.ts # Layer 3 (React): useClassyStore(), useLocalStore() via useSyncExternalStore -│ ├── vue/vue.ts # Vue: useClassyStore() → ShallowRef> (onUnmounted cleanup) +│ ├── react/react.ts # Layer 3 (React): client entry re-exporting the hooks +│ ├── react/server.ts # Server-safe entry: prepareStoreForHydration() +│ ├── react/hooks/ # useClassyStore, useLocalStore, useHistoryStatus, usePersistStatus +│ ├── react/utils/ # createStoreHook, tracking caches used by the auto-tracked hook +│ ├── vue/vue.ts # Vue: useClassyStore() → Ref> (effect-scope cleanup) │ ├── svelte/svelte.ts # Svelte: toSvelteStore() → ClassyReadable> -│ ├── solid/solid.ts # Solid: useClassyStore() → () => Snapshot signal (onCleanup) -│ └── angular/angular.ts # Angular: injectStore() → Signal> (DestroyRef) +│ ├── solid/solid.ts # Solid 2: useClassyStore() → () => Snapshot (owner cleanup) +│ └── angular/angular.ts # Angular: injectClassyStore() → Signal> (DestroyRef) └── utils/ - ├── index.ts # Utils barrel: persist, devtools, subscribeKey, withHistory + ├── index.ts # Utils entry: persist, devtools, subscribeKey, withHistory ├── persist/persist.ts # persist() — storage, transforms, versioning, cross-tab sync, TTL ├── devtools/devtools.ts # devtools() — Redux DevTools integration, time-travel ├── history/history.ts # withHistory() — undo/redo via snapshot stack, pause/resume ├── subscribe-key/subscribe-key.ts # subscribeKey() — single-property subscription ├── equality/equality.ts # shallowEqual + ├── cloneSnapshot/ # Mutable copies of snapshots, used by persist and history + ├── utilityStatus/ # Status publisher behind the persist and history handles └── internal/internal.ts # isPlainObject, canProxy, findGetterDescriptor, PROXYABLE -website/ # Fumadocs static site (Next.js) +website/ # Fumadocs static site (Next.js); a workspace member that runs the library built from this repository website/content/docs/ # .md source for all doc pages website/examples/ # Live React controls used by the MDX example pages website/public/ # Static assets and old demo bookmark redirect @@ -51,10 +59,17 @@ bun run test # Run all tests (Bun test runner, uses happy-dom for React bun run lint # Check with Biome linter bun run lint:fix # Auto-fix Biome lint issues bun run typecheck # TypeScript type check without emit +bun run check:package # Build, then publint + arethetypeswrong on the packed tarball bun run checkall # lint + test + typecheck (full CI check) -bun run docs:dev # Start Fumadocs at http://localhost:3000 -bun run docs:build # Export the GitHub Pages site to website/out/ +bun run test:coverage # Unit tests; fails if a source file is below 100% of lines or functions +bun run check:floor # Diff-scoped guard for the floor in CONSTRAINTS.md +bun run size # Build, then gzipped size per entry point against its budget +bun run test:mutation # Mutation run over the core files (about ten minutes); pass file paths to limit it +bun run benchmark:core # Per-operation timings on Bun; benchmark:core:node for V8 + +bun run docs:dev # Build the library, then start Fumadocs at http://localhost:3000 +bun run docs:build # Build the library, then export the GitHub Pages site to website/out/ ``` Run from `packages/classy-store/`: @@ -69,7 +84,7 @@ bun run typecheck # TypeScript type check without emit ### Test helper pattern -Because mutations are batched via `queueMicrotask`, tests must flush the microtask queue before asserting on subscriber calls: +Ordinary subscriptions are batched via `queueMicrotask`, so tests must flush the microtask queue before asserting on subscriber calls. A `{sync: true}` subscription can be asserted immediately: ```typescript const flush = () => new Promise((resolve) => setTimeout(resolve, 0)); @@ -84,9 +99,15 @@ it('notifies on mutation', async () => { }); ``` +## Quality Bar + +Read [CONSTRAINTS.md](CONSTRAINTS.md) before writing code. Do not weaken it to +make a change pass: a rule there is loosened only together with a decision +record under `docs/decisions/`. + ## Code Style -Enforced by Biome 2.4.0 (`biome.json` at repo root): +Enforced by Biome (`biome.json` at repo root; the version is pinned in the root `package.json`): - 2-space indentation, single quotes, no bracket spacing - `noUnusedImports` is an error @@ -95,10 +116,16 @@ Enforced by Biome 2.4.0 (`biome.json` at repo root): ## Key Technical Facts - **No arrow function methods:** Arrow function properties (`increment = () => {}`) have `this` lexically bound to the raw instance. `.bind()` is a no-op on arrow functions, so the GET trap cannot rebind `this` to the proxy. Mutations inside arrow functions bypass the SET trap entirely — no notifications, no reactivity. Always use prototype methods (`increment() {}`). -- **Batching:** mutations are coalesced via `queueMicrotask`. Multiple synchronous writes (including array `push` which triggers multiple SET traps) produce a single subscriber notification. +- **Batching:** ordinary subscribers are coalesced via `queueMicrotask`. Multiple synchronous writes (including array `push` which triggers multiple SET traps) produce a single notification. +- **Transactions:** `{sync: true}` subscribers, which is every framework binding, are notified once per direct write, and once per store method or array-method call, when the outermost call returns. Versions still bump on every write, so reads inside the call are current. Without this an in-place `sort` or `unshift` notifies once per moved element and each notification rebuilds the list snapshot. The exported `batch(run)` opens the same transaction around direct writes made outside a method. +- **Subscription scope:** `subscribe(node)` observes that node's subtree only. Each call is its own registration. +- **Frozen objects are values:** a frozen object held in a store is kept by reference and never proxied. That covers any object the caller froze, a snapshot assigned into a store, and a snapshot read through React's tracking proxy. The store does not look inside it: replace the field to update. The frozen check is cached in `linkChild()` (`core.ts`), because `Object.isFrozen` scans every property; do not move it into `canProxy()`, which history and persist use to copy frozen snapshot content. +- **Read-only properties:** a Proxy must return a non-writable, non-configurable property's own value, so `linkChild()` leaves such a value unproxied. That is what makes a frozen store root readable. A store embedded by its proxy is already that value and stays a child. - **Internal state:** stored in a `WeakMap` — never on the user's object. Allows GC when a store is dereferenced. -- **Non-proxyable types:** `Date`, `RegExp`, native `Map`, and native `Set` are treated as opaque values (internal slots can't be intercepted by Proxy). Use `reactiveMap()` and `reactiveSet()` for Map/Set semantics. Replace Date instances entirely to trigger updates. -- **Extending reactive types:** a class can opt into deep proxying by setting `static [PROXYABLE] = true` (the `PROXYABLE` symbol is exported from `utils/internal`). `ReactiveMap` and `ReactiveSet` use this. +- **Non-proxyable types:** `Date`, `RegExp`, native `Map`, and native `Set` are treated as opaque values (internal slots can't be intercepted by Proxy). Use `reactiveMap()` and `reactiveSet()` for Map/Set semantics. Replace Date instances entirely to trigger updates. Frozen objects are opaque in the same way. +- **Extending reactive types:** a class can opt into deep proxying by setting `static [PROXYABLE] = true` (the `PROXYABLE` symbol is exported from the main entry). `ReactiveMap` and `ReactiveSet` use this. +- **Collection identity:** reactive collections match members with `identityOf()`, which is the same for a raw object, its store proxy and every snapshot of it. Lookups scan the raw backing array except for tracked reads in a React component. +- **Typecheck with the package script:** run `bun run typecheck`, not `bunx tsc`; the latter can resolve a different TypeScript and miss errors. - **`persist()` exclusions:** getters (detected by walking the prototype chain with `Object.getOwnPropertyDescriptor`) and methods (`typeof value === 'function'`) are automatically excluded from persistence. Only own data properties are saved. - **Computed memoization:** two layers — the write proxy caches getter results keyed on dependency versions/values; the snapshot layer adds cross-snapshot caching using structural sharing reference equality. - **Structural sharing:** unchanged sub-trees reuse the previous frozen snapshot reference. This makes `Object.is` comparisons in selectors efficient without `shallowEqual`. diff --git a/CONSTRAINTS.md b/CONSTRAINTS.md new file mode 100644 index 00000000..8995018e --- /dev/null +++ b/CONSTRAINTS.md @@ -0,0 +1,100 @@ +# Constraints + +The quality bar for `@codebelt/classy-store`. Written on 2026-11-18, at the end +of stage 1 of the pre-1.0 review, from what was measured that day. On +2026-11-19 the owner handed the decisions of that review, the decision records +included, to the agent that runs it; merging into `main` and releasing stay +the owner's. + +Read this before changing code. When a check fails, the code is fixed. A rule +here is loosened or removed only together with a line in a decision record +under `docs/decisions/`, in the same commit; `bun run check:floor` blocks the +change otherwise. Tightening a rule needs nothing. + +## Floor + +Checked by `bun run check:floor`, in CI and before each push. It judges every +commit from the merge base with `origin/main` to the head against the commit +before it, and last the working tree against the head. While `main` does not +hold this file, it starts at the commit that added it, because the commits +before it were made with no bar. The branch is kept linear: a merge commit in +that range fails. + +- No new comment that silences a checker: `@ts-ignore`, `@ts-nocheck`, `biome-ignore`, `eslint-disable`, or a comment that hides code from coverage or from the mutation run. +- No new `@ts-expect-error` or `as any` in library source. A test may use `@ts-expect-error` where the type error is what it tests. +- No unfinished work: a "not implemented" throw, an empty `catch`, or a `TODO` or `FIXME` in code. +- No skipped or focused test: `skip`, `todo`, `only`. A skip that states a condition and a reason is allowed, like the one browser test that needs Chromium's clipboard. +- No deleted test file, and no test file left with fewer assertions, unless the commit message has a line `Test-change: : ` for that file, and the reason names a decision or the test of public behaviour that covers the same fact. +- No rule in this file removed or loosened without a line in a decision record in the same commit. +- No change to a bar file without a line in a decision record in the same commit. The bar files hold a part of the bar that nothing else checks: `scripts/floor-guard.mjs`, `packages/classy-store/bunfig.toml` and `packages/classy-store/tests/mutation/runMutation.ts`. +- No size budget or cost limit that rises without a line in record 0004 in the same commit. A ceiling in `budgets.json` changes only in a commit of its own, which holds the new number and its line in record 0004 and nothing else. +- A development-only check reads `process.env.NODE_ENV` inline at its call site, after a cheap test that is almost always false and behind `typeof process !== 'undefined'`, never in a helper or a module constant, and reports with `console.warn`, which nothing else in the library calls. Two checks hold it, not the guard: `bun run size` fails when a production bundle holds `console.warn` or a code listed in `packages/classy-store/tests/size/developmentOnly.json`, and `packages/classy-store/tests/size/productionBundle.test.ts` bundles the form for production and for development. + +## Enforced with numbers + +| Dimension | Rule | Checked by | Runs | +| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------- | ------------------------------------------ | +| Lint | No error from `biome.json` | `bun run lint` | CI | +| Types | No type error in the package, its harnesses, the examples or the docs site | `bun run typecheck` | CI | +| Tests | No failing test | `bun run test:coverage` | CI | +| Line coverage | At least 100% of lines in every source file | `bun run test:coverage` | CI | +| Function coverage | At least 100% of functions in every source file | `bun run test:coverage` | CI | +| Mutation | At most 0 unexplained surviving mutants in the target files | `bun run test:mutation` | Before a commit that touches a target file | +| Size of each entry | The main entry within its budget, every other entry adding no more than its budget, every budget within its ceiling, all in `budgets.json` | `bun run size` | CI | +| Read cost on Bun | At most 20 times a forwarding Proxy | `bun run benchmark:core --check` | Before a commit to library source | +| Write cost on Bun | At most 3.2 times a forwarding Proxy | `bun run benchmark:core --check` | Before a commit to library source | +| Cached getter cost on Bun | At most 41 times a forwarding Proxy read | `bun run benchmark:core --check` | Before a commit to library source | +| Cached snapshot cost on Bun | At most 10 times a forwarding Proxy read | `bun run benchmark:core --check` | Before a commit to library source | +| Read cost on Node | At most 2.5 times a forwarding Proxy | `bun run benchmark:core:node --check` | Before a commit to library source | +| Write cost on Node | At most 1.7 times a forwarding Proxy | `bun run benchmark:core:node --check` | Before a commit to library source | +| Cached getter cost on Node | At most 5.3 times a forwarding Proxy read | `bun run benchmark:core:node --check` | Before a commit to library source | +| Cached snapshot cost on Node | At most 1.8 times a forwarding Proxy read | `bun run benchmark:core:node --check` | Before a commit to library source | +| Package shape | No problem from publint in strict mode or from arethetypeswrong | `bun run check:package` | CI | +| Browsers and frameworks | No failure in the browser, React, Vue, Svelte, Angular, Solid and Next.js suites | The workflows under `.github/workflows/` | CI | + +The budgets and their ceilings are only in +`packages/classy-store/tests/size/budgets.json`, so that a budget that moves +changes one file. The cost limits are in +`packages/classy-store/tests/benchmark/limits.json` and are repeated above. +The commands read those files; this table is the record of why. + +### Where the numbers come from + +- **Coverage.** Every source file was at 100% of lines and functions when this + was written, and Bun applies the threshold to each file on its own. Bun + reports no branch coverage, so the mutation run stands in for it: a + condition that can be forced one way with no test failing is an untested + branch. +- **Mutation.** The seven target files are named in + `packages/classy-store/tests/mutation/runMutation.ts`. Every surviving + mutant there is either caught by a test or listed with a labelled reason. + The run takes about ten minutes, so it is not in CI. +- **Size.** Each budget started as the size measured at the end of stage 1, + rounded up by two to three percent: room for a fix of a few lines, not for + a feature. The main entry measured 3,661 bytes. Every other entry is + measured together with the main one and held to what it adds. Record 0004 + sets a ceiling for each entry, once, for the changes decided for 1.0. A + commit that grows an entry sets its budget to the new measured size plus 2% + and adds a line with the measured size to record 0004; no budget passes its + ceiling. +- **Cost.** Each limit is the highest of five baseline runs times 1.2. A cost + is a ratio to a Proxy that only forwards, timed in the same process, so it + holds on another machine. The limits differ by engine because a forwarding + Proxy costs about 2 nanoseconds on Bun and about 22 on Node. + +## Measured, not enforced + +| Metric | Today | Direction | +| ---------------------------- | ------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | +| Per-operation timings | `packages/classy-store/tests/benchmark/baseline.json` | Compared at every stage 4 commit. A difference outside the spread of the baseline runs is reported with numbers. | +| React commit timings | `packages/classy-store/tests/performance/baseline.json` | The same. | +| React memory retention | `packages/classy-store/tests/memory/baseline.json` | Must not grow. The harness fails on its own when cleanup leaves anything behind. | +| Lint warnings | 4 | Must not grow. | +| Mutants listed as unkillable | 78 | Each needs a labelled reason, which the runner enforces. The 25 that mark dead code should go down. | + +## Exceptions + +None. + +| ID | Rule | Path | Reason | Owner | Expires | +| --- | ---- | ---- | ------ | ----- | ------- | diff --git a/README.md b/README.md index 2d63d1c6..68e030a3 100644 --- a/README.md +++ b/README.md @@ -12,14 +12,6 @@ Visit the **[Documentation Website](https://codebelt.github.io/classy-store/)** for tutorials, API reference, and examples. -## Upgrading to 0.11.0 - -Applications upgrading from 0.10.x can keep their existing public imports. For behavior changes and framework support, see the [0.11.0 release notes](https://codebelt.github.io/classy-store/docs/UPGRADING_0_11). - -When upgrading from 0.7.x, replace persistence `unsubscribe()` with `dispose()`, handle rejected promises from explicit persistence operations, and import hydration preparation from `@codebelt/classy-store/react/server`. The `useHistoryStatus` and `usePersistStatus` hooks keep utility metadata reactive in React. - -See the [0.8.0 upgrade guide](https://codebelt.github.io/classy-store/docs/UPGRADING_0_8) for the removal of `getVersion` and migration examples. If upgrading from 0.6.x or earlier, also read the [0.7.0 upgrade guide](https://codebelt.github.io/classy-store/docs/UPGRADING_0_7). - ## 🚀 Features - **Class-Based**: Define state and logic using standard ES6 classes. @@ -75,8 +67,9 @@ the original instance, so their writes can bypass reactivity. Mutate through the store proxy and read render data through the hook. Nested plain objects, arrays, and the library's reactive collections support deep -updates. Native `Date`, `Map`, `Set`, and other nested class instances remain opaque: -replace their property to notify subscribers. Snapshots freeze copied state, but +updates. Native `Date`, `Map`, `Set`, frozen objects, and other nested class instances +remain opaque: replace their property to notify subscribers. A class of your own can opt into deep +updates with `static [PROXYABLE] = true`. Snapshots freeze copied state, but retain opaque values by reference. Keep computed getters pure and based on store property reads; changes to time or external variables do not invalidate their cache. @@ -94,6 +87,7 @@ property reads; changes to time or external variables do not invalidate their ca | Read state outside React or observe mutations | `snapshot(store)`, `subscribe(store, listener)`, `subscribeKey(store, key, listener)` | | Persist state, record history, or inspect it in DevTools | `persist(store, options)`, `withHistory(store)`, `devtools(store)` | | Track changes inside Map-like or Set-like collections | `reactiveMap()`, `reactiveSet()` | +| Group direct writes into one notification | `batch(run)` | | Compare selector results one level deep | `shallowEqual(previous, next)` | `useClassyStore` is the starting point for React components. The two status hooks @@ -117,7 +111,7 @@ return ( ); ``` -Ordinary `subscribe(store, listener)` callbacks still batch in a microtask. React batches renders within event handlers, while selectors can run after each mutation. +Ordinary `subscribe(store, listener)` callbacks still batch in a microtask. A store method or an array operation such as `sort` is one transaction: React is notified once when it returns, however many fields it wrote. A write made outside a method notifies on its own, so put a loop of writes in a store method or wrap it in `batch()`. For server-rendered React apps, call `prepareStoreForHydration(store)` from `@codebelt/classy-store/react/server` on matching server/client stores before persistence starts. Delayed Suspense boundaries then hydrate from the original data and catch up to live state. See the [SSR guide](https://codebelt.github.io/classy-store/docs/REACT_SSR). @@ -134,26 +128,26 @@ Most components only need `useClassyStore(store)` to render application data. Us ## Angular 22 integration The `/angular` adapter supports **all stable Angular 22 releases** (`^22.0.0`). -The library and example pin the Angular framework to `22.2.6`. Call `injectStore(store)` +The library and example pin the Angular framework to `22.2.6`. Call `injectClassyStore(store)` in a live Angular injection context to get a readonly snapshot signal. Store writes update the signal and dependent computed reads immediately; Angular schedules rendering, including in zoneless applications. The subscription is removed with its `DestroyRef` lifecycle. Ordinary core subscriptions remain batched. See the [Angular guide](https://codebelt.github.io/classy-store/docs/ANGULAR) -for inputs, keyed lists, cleanup, and migration requirements. +for inputs, keyed lists, and cleanup. ## Solid 2 integration -The `/solid` adapter is **in preview** and targets **Solid 2.0.0-rc.18 only**; Solid 1 is no longer -supported. Pin `solid-js` and the browser renderer `@solidjs/web` to that exact -release candidate. `useClassyStore(store)` returns an immutable snapshot accessor -and requires a live component or `createRoot()` owner for automatic cleanup. +The `/solid` adapter supports **Solid 2** (`solid-js@^2.0.0`). Keep `solid-js` and +the browser renderer `@solidjs/web` on the same version. `useClassyStore(store)` +returns an immutable snapshot accessor and requires a live component or +`createRoot()` owner for automatic cleanup. Store changes reach Solid synchronously, while Solid 2 batches its reactive updates. Use Solid's `flush()` when imperative code needs updated computed values or DOM immediately. Ordinary core subscriptions remain batched. See the -[Solid 2 guide](https://codebelt.github.io/classy-store/docs/SOLID) for inputs, -keyed lists, ownership, and migration of the example toolchain. +[Solid 2 guide](https://codebelt.github.io/classy-store/docs/SOLID) for setup, +inputs, keyed lists, and ownership. ## 📦 Installation @@ -165,13 +159,13 @@ bun add @codebelt/classy-store Framework peers are optional; install only what your application uses. -| Framework | Supported peer range | -| --------------- | -------------------------------- | -| React | `^18.0.0 \|\| ^19.0.0` | -| Vue | `^3.2.0` | -| Svelte | `^4.0.0 \|\| ^5.0.0` | -| Angular | `^22.0.0` | -| Solid (preview) | `2.0.0-rc.18` (exact prerelease) | +| Framework | Supported peer range | +| --------- | ---------------------- | +| React | `^18.0.0 \|\| ^19.0.0` | +| Vue | `^3.2.0` | +| Svelte | `^4.0.0 \|\| ^5.0.0` | +| Angular | `^22.0.0` | +| Solid | `^2.0.0` | Use matching `react` and `react-dom` versions for React applications. These ranges exclude untested future majors. Development dependency pins are separate diff --git a/REVIEW_PLAN.md b/REVIEW_PLAN.md new file mode 100644 index 00000000..bdf2a729 --- /dev/null +++ b/REVIEW_PLAN.md @@ -0,0 +1,745 @@ +# Pre-1.0 review and refactor plan + +Working plan for the deep review of `@codebelt/classy-store` before 1.0.0 is +published. Not part of the published docs; delete it when the work is done. + +## Status + +Read this first. Whoever finishes a stage updates its row: the state, the +commit it ended on, and where its report is. + +| Stage | State | Ended on | Report | +| --------------------- | -------------------------------------------------------------------------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------- | +| Plan | Revised 2026-11-18 after a check against the repository at `7540662` | | | +| 1. Safety net | Done 2026-11-18 | `5bc4008` | `review/stage-1-report.md` | +| 2. Library comparison | Done 2026-11-19 | `1b426fb` | `review/stage-2-report.md`, with the eleven reports in `review/stage-2/` | +| 3. Design review | Done 2026-11-25. Paused from 2026-11-19 to 2026-11-24 at the owner's request | `b080def` | `review/stage-3-report.md`, the decision document `review/stage-3-decisions.md`, the working reports in `review/stage-3/` | +| 4. Refactor | In progress since 2026-11-25. "Where stage 4 stands" below has what is done and what is next | | | +| 5. Release | Not started | | | + +## Where stage 3 ended + +Updated 2026-11-25. The owner paused the work on 2026-11-19 and lifted the +pause on 2026-11-24: "The pause is over, carry on with stage 3." + +**Done:** + +- Step 1, the merge: `review/stage-3/merged.md`. 77 distinct issues (`M1` to + `M77`), 29 contradictions between reports, and the order the issues depend + on each other. +- Step 2, our own code: `review/stage-3/own-code.md`. +- Step 3, the spikes. First wave: `spike-traps.md`, `spike-getters.md` and + `spike-delivery.md`. Second wave: `pinned.md`, `persist-devtools.md`, + `devbuild.md`, `adapters-collections.md`, `spike-snapshots.md`, + `spike-classes.md` and `spike-classes-2.md`. All are in `review/stage-3/`. + `spike-ownership.md` was not given to an agent: the own-code review ran its + main spikes. +- Steps 4 to 6, the decision document: `review/stage-3-decisions.md`, 46 + decisions, the guarantees of 1.0, the proposals not taken, and the order + for stage 4. +- The first adversarial review of that document: `adversarial-whole.md`, + `adversarial-core.md` and `adversarial-edges.md`, 58 objections. The + section "Objections and answers" of the decision document answers each. +- Three follow-up spikes the review asked for: `spike-functions.md`, + `spike-combos.md` and `spike-core-2.md`. Nine entries of the decision + document (1, 5, 6, 10, 11, 12, 27, 30 and 43) were decided again from + them, and the size ceilings were set again. +- The timings that were open: the trap combination, the ownership patch + `x2`, the dead-code patch `r5`, the table per prototype and the + `activeTracker()` ternary. They are in the reports that hold the patches. + +- The second adversarial review: `adversarial-2-whole.md` (14 objections, 5 + "wrong") and `adversarial-2-core.md` (16 objections, 6 "wrong"). + +- The second round is answered in full, in a second table of "Objections + and answers". Two more spikes were run for it: `spike-functions-2.md` (the + rule for functions, in a form that never changes the object) and + `spike-core-3.md` (a snapshot getter that reaches the live store, the + table per prototype that grew with absent keys, an undo into a container + that cannot be written). Decisions 1, 10, 11, 12, 29 and 30 were decided + again from them, and 21 to 24, 4, 27 and 36 from the review itself. + +- The third and last adversarial review: `adversarial-3.md`, 17 objections, + 4 "wrong", answered in a third table. Two last spikes were run for it: + `spike-functions-3.md` (only a class is handed out as data, and a short + path for a method already handed out) and `spike-persist-2.md` (the + `persist` rules built once and run through 33 paths). Decision 1 and + decisions 19 and 21 to 24 were decided again from them. +- **The decision document is decided.** Its last section says which two + decisions were made after the last round and have not been read by a + reviewer: 1, and the `persist` rules. The independent review of stage 4 + reads those first. +- The core benchmark's `--only` takes a list of metrics, at the owner's + request, so a timing of a few metrics takes seconds. + +- Step 7, two of three documents: the spec at `review/spec.md` and 46 + decision records with an index under `docs/decisions/`. Both are committed + as their writers left them and **have not been checked** against the + decision document. `review/stage-3/step7-open-points.md` holds what the + writers left open; the spec's 38 open points are in its own section 12. +- A draft of the stage 3 report: `review/stage-3-report.md`. + +- Step 7, the third document: the stage 4 task list, + `review/stage-4-tasks.md`, 59 tasks, committed as its writer left it and + not yet checked. Its 19 open points are in its own section "Open points". + +**The handover happened on 2026-11-25.** The old session on Fable stopped +and writes nothing more to this checkout. A new session on Opus 5.5 at +extra-high effort runs the plan from here, and is the one writer. Its helper +agents run on Opus 5.5 at medium effort (ground rule "Models"). + +- The check of the three step 7 documents: four read-only agents compared + them with the decision document (`review/stage-3/check-spec-api.md`, + `check-spec-rules.md`, `check-records.md`, `check-tasks.md`): 65 + findings and 13 points the decision document left unclear. +- **Every open point is settled**, in the decision document at `944a2f7`: + its section "Settled when the step 7 documents were checked" indexes them + (the nineteen error codes, the floor guard, the production-bundle test, + the benchmark rows before the redundant checks go, and the rest). +- Three helper agents applied the findings and the settled points to the + spec, the records and the task list, each on its own branch in a + throwaway worktree. Each diff was read against the decision document and + brought in as one commit: `737512e` (spec), `da08e4b` (records), + `b89f479` (task list). +- The stage 3 report is final: `review/stage-3-report.md`, at `b080def`. + +## Where stage 4 stands + +Updated 2026-11-25. Stage 4 follows `review/stage-4-tasks.md`, one task per +commit. Its working results are in `review/stage-4/`. + +**Done:** + +- T-01 at `a46cd96`: the per-commit floor guard and its 34 tests + (`packages/classy-store/tests/floor/`), the ceilings in `budgets.json`, + `checkSizes()` in the size script and its 7 tests, the new floor of + `CONSTRAINTS.md`, and its lines in record 0004. (Its commit message says 9 + and 32 tests; the counts are 7 and 34.) +- T-02 at `ae990df`, with a type fix at `09ba1f2`: the floor rule for a + development-only check, the production-bundle check in `bun run size` with + `tests/size/developmentOnly.json`, and `productionBundle.test.ts`. + `ae990df` was pushed with a type error, because the command that ran the + checks did not stop on it; CI fails on that commit and passes from + `09ba1f2`. +- Checkpoint 1: every check passes on the head, and the starting core + timings are in `review/stage-4/` (`README.md` has the ratios). + +- `bd50ec4`: a fix to T-01. On a pull request CI checks out a merge of the + head into `main`, and the per-commit guard failed on that merge commit. The + guard takes `--head ` now, and `ci.yml` passes the pull request's head. +- T-03 at `dc2f144`: today's six messages carry their codes, built by + `codedMessage()` in the core, and `website/content/docs/ERRORS.md` lists + them. The main entry is 12 bytes larger (3,673), under its budget. +- Every change that alters behaviour adds its line to the 1.0 changeset, + `.changeset/stable-one.md`, in its own commit (decision 34 asks for the + changelog entry); T-03's line is added after it. + +- `5c25a04`: a fix to T-03. The browser suite still matched the old Solid + message, and CI failed on it in all three browsers. Before a commit that + changes a message, search `tests/` as well as `src/`; before a commit to + library source, run the browser suite in Chromium (WebKit and Firefox are + not installed on this machine; CI runs them). +- T-04 at `0b6b4b3`: the ten dead lines of `core.ts`, `ownership.ts` and + `snapshot.ts`. The main entry is 3,641 bytes. The list of equivalent + mutants is 69 entries now; `CONSTRAINTS.md` still says 78 under "Measured, + not enforced", and T-59 records the final count. + +- T-05 at `319a478`: the dead and redundant blocks of `persist.ts`: one + `cancelPendingSave()` for the five copies, the unreachable disposed check + in `writeToStorage()` (a new test pins `save()`'s), two redundant guards. + `if (onError)` and `if (prop.transform)` stay, with reasons in the commit. + `./utils` adds 2,673 bytes. The list of equivalent mutants is 58 entries. + +- T-06 at `3f5f07d`: the redundant checks of `equality.ts` and `history.ts` + go. The object guard of `indexOfMember` stays, measured: without it the + new row `collection.has.primitive` is 5.6 times slower on Bun and 5% on + Node. The list of equivalent mutants is 51 entries. + +- T-07 at `06ceaa8`: the two snapshot-cache traps that proxy-compare + cannot reach are gone, with the one test that reached them through the + cache. Its commit carries the first `Test-change:` line, and the guard + accepts it. The React compatibility suite (four versions) and the Compiler + suite pass. + +- Checkpoint 2 passes; `review/stage-4/README.md` has its figures. + +- `54ec834`: the checkpoint 2 timings were committed in a layout that lint + refuses, and are formatted now. Never pipe a check into `tail` inside a + chain: it hid that failure; give each check its own exit code. +- T-08 at `bdaa479`: the walk to a detached parent is gone, and the read + that never returned now returns. The traps call a small + `resumeIfDetached()`: calling the larger `resume()` from them made a read + on Node 9% slower, because V8 could not inline it. The main entry is + 3,606 bytes. +- A known flake: under the mutation run's eight workers, the persist test + "clear during storage restore wins until a later local write + (editAfterClear=false)" can take seconds and fail, which marks a mutant + killed and its entry stale. Run the file again before you remove an + entry. + +- T-09 at `6052255`: getters are decided from a table per prototype. A + field read is 11.8 ns on Bun (was 32.4) and 34.9 on Node (was 46.8). The + main entry is 3,768 bytes and its budget 3,844, with the line in record + 0004. That flaky persist test struck twice more in this task's mutation + runs; fixing it is the next commit. + +- `b5146a2`: the flaky persist test now waits for the write itself. The + failure did not reproduce in sixteen parallel full runs, so if a mutation + run still marks an equivalent mutant killed by that test, run the file + again before you remove its entry. + +- T-10 at `ae8ffec`: a delete that removes nothing is no change. The main + entry is 3,776 bytes, budget 3,852. (Its message says 1,409 tests; the + run had 1,405.) + +- T-11 at `684cedf`: a definition through the store is a write. The main + entry is 3,847 bytes (71 over the 3,776 before, against an estimate of + 49), budget 3,924. Running total against decision 4: the main entry has + grown 186 bytes for decisions 2, 3, 8, 12, 20 and the codes, against 172 + estimated for the same set; the ceiling is 5,575. + +**Next:** T-12 (raw values on write, and a child kept through a freeze, +decision 5), then T-13 (the two benchmark rows decision 1 is measured by) +and T-14 (the rule for functions, decision 1). + +The throwaway worktrees of the step 7 fixers are in the scratchpad, on the +branches `step7/fix-spec`, `step7/fix-records` and `step7/fix-tasks`, which +are local only. Run `git worktree prune` if `git worktree list` shows +folders that no longer exist. + +## Starting point (read this if you are new to the work) + +**The library.** `@codebelt/classy-store` is a class-based reactive store. You +write a plain TypeScript class, wrap it with `createClassyStore()`, and get a +proxy back. Writes go through the proxy; consumers read frozen snapshots with +structural sharing; class getters are memoized. Adapters exist for React, Vue, +Svelte, Solid 2 and Angular. `CLAUDE.md` has the layout, commands and key +technical facts. The core is about 730 lines: `src/core/core.ts`, +`src/core/ownership.ts` and `src/snapshot/snapshot.ts` under +`packages/classy-store/`. + +**The owner's goal.** Before 1.0.0 is published, review the core against +comparable libraries, then refactor, clean up and simplify it. The owner is the +only user, so breaking changes and public API changes are welcome. There is no +deadline; the code should be as correct and clear as it can be made. + +**State of the repository** (as of 2026-11-18): + +- Branch `release/1.0`, pushed, with an open pull request: + https://github.com/codeBelt/classy-store/pull/45. It is not merged and + nothing is published; npm `latest` is 0.11.0. +- That branch already holds a full 1.0 preparation pass: transactions and + `batch()`, subscription scope, per-field persist hydration, stricter + `shallowEqual`, packaging checks, Solid 2, a rewritten docs site, and a + `major` changeset in `.changeset/stable-one.md`. +- It also holds the tests produced by a coverage run and a mutation sweep + (commits `b1d9ad7`, `5f15539`). The sweep's script, its mutation rules and + its list of equivalent mutants were not committed. Stage 1 extends that + work; read those commits first so nothing is repeated. +- Work continues on this branch unless the owner says otherwise. The pull + request stays open and unmerged until stage 4 is done, because merging it + starts the Changesets release flow. + +**Findings already in hand** from a first comparison with Solid 2's store: + +- Fixed in `f8a012f`: a frozen object held in a store was proxied, so reading a + nested object under it threw. Frozen objects are now kept by reference. +- Open, performance: a field read through the proxy costs about 40 ns against + under 1 ns raw, mostly from a property-descriptor lookup on every `get`. + Solid caches that answer per prototype. +- Open, diagnostics: writes inside arrow-function methods bypass the proxy and + notify no one, and writes after an `await` fall outside the transaction. + Both are silent. Solid reports the equivalents with stable codes in its + development build; we have no development/production split. +- Open, coverage of proxy traps: the store proxy defines `get`, `set`, + `defineProperty` and `deleteProperty`. There is no `has` or `ownKeys`. The + `defineProperty` trap came with `f8a012f` and handles freezing only. + Reproduced on `7540662`: `Object.defineProperty(store, 'b', {value: 2, ...})` + sets the live value, notifies no subscriber, and stays out of the snapshot + until the next ordinary write. +- Open, complexity: the suspend and resume logic in `ownership.ts`, and the + three kinds of getter dependency (value, version, computed) in `core.ts`, + are the hardest parts to reason about. + +**How to work through this plan.** Do the stages in order. Each stage ends +with a report, which is saved (see "Where the work is written down"), and the +Status table above is updated. Stage 3 is the decision point: every proposed +change gets a written decision there before stage 4 implements anything. +Until 2026-11-19 each stage waited for the owner's go-ahead and the owner +approved each stage 3 change. The owner has since handed those decisions to +the agent running the plan: see the first ground rule. When the Status table +says the work is paused, do nothing until the owner says to start again. + +**Commands** (from the repo root; see `CLAUDE.md` for the rest): + +```bash +bun install --frozen-lockfile +bun run lint +bun run test +bun run build +bun run typecheck +bun run check:package +bun run test:browser +``` + +The validation matrix. Each command builds the library first, and the first +two accept React versions as arguments. CI runs all of it on every push to +the pull request (`ci.yml`, `react-compatibility.yml`, `react-next.yml`), +with the benchmark and memory suites at smoke size: + +```bash +bun run test:react:compatibility # React 18.0.0, 18.3.1, 19.0.0, 19.3.1 +bun run test:react:compiler # the same with the React Compiler +bun run test:react:next # packed Next.js app, Compiler off and on +bun run test:frameworks:compatibility # packed Vue and Svelte, minimum versions +bun run test:angular:compatibility # packed Angular 22.0.0 and 22.2.3 +bun run test:react:memory # React memory retention +bun run benchmark:react # React commit budgets at scale +``` + +CI also builds two examples after `bun run build`: + +```bash +bun run --filter classy-store-solid-example build +bun run --filter classy-store-angular-example build +``` + +CI's docs job builds the site and runs its browser tests. Stage 1's matrix run +left the second command out, and CI then found a timing bug in a demo: + +```bash +bun run docs:build +bun run docs:test +``` + +The stage 1 tooling. Each has a guide beside it under +`packages/classy-store/tests/` (`mutation`, `size`, `benchmark`): + +```bash +bun run test:mutation # mutation run; add file paths to limit it +bun run size # bundle size per entry point, against its budget +bun run benchmark:core # per-operation timings on Bun (JavaScriptCore) +bun run benchmark:core:node # the same on Node (V8) +``` + +Helper agents get their worktrees under `.claude/worktrees/`, inside the +repository. Each holds its own `biome.json`, which would make `bun run lint` +fail in the main checkout, so `.gitignore` lists that folder. + +## Ground rules (every agent) + +- The agent running the plan makes the decisions, and does not wait for the + owner's approval or go-ahead. Two things stay the owner's alone: merging + into `main` and releasing. The owner said on 2026-11-19: "The only + limitation you have is not to merge into main. You can make all the + decisions in the world. You're the expert. Do not merge into main or + release. Those are the two things that you cannot do. Everything else you + can do. You are the one making the decisions from the research and building + this library." Every decision is still written down with its reasons, so + the owner can read why. +- No deadline. Correctness and clarity win over speed. +- Breaking changes and public API changes are allowed. The library has one user. +- Fixed: state is a plain class wrapped in a proxy, consumers read immutable + snapshots with structural sharing, and one core serves React, Vue, Svelte, + Solid and Angular. Everything built on that is open to change. +- The owner alone decides when anything is merged into `main` and when to + release. No agent merges the pull request, merges the Changesets release + pull request, enables auto-merge, publishes to npm, creates a tag or a + GitHub release, or runs the release workflow. Finishing a stage, passing + checks or an earlier approval is not permission; only the owner's explicit + instruction for that specific action is. +- Do not ask the owner to merge into `main` or to release, and do not suggest + it is time. Report the state of the work and stop; the owner will say when. +- Committing and pushing to the branch need no further approval. The owner + said on 2026-11-18: "From now on, you can commit and push anytime you want." +- Merging into any branch other than `main` needs no further approval, for + example a helper agent's branch into `release/1.0`. The owner said on + 2026-11-19: "You can always merge, just not into main branch." Merging into + `main` and releasing are unchanged: the first two rules still hold. +- Read the repo's agent instructions first (`AGENTS.md` if present, otherwise + `CLAUDE.md`). Typecheck with `bun run typecheck`, never `bunx tsc`. +- Use the skills listed for your stage. Load each one before the work it + covers, not after. +- One writer at a time in this checkout. Read-only agents may run in parallel. +- Read-only means this checkout is not changed. An agent that has to write + something in order to run it (a test ported to another library, code deleted + to see what fails, a spike) does that in a scratch folder or a throwaway Git + worktree, installs nothing here and leaves `bun.lock` alone. The one file a + read-only agent may create here is its own report under `review/`; the + agent running the stage commits it. +- **Models, from 2026-11-25.** The session that runs the plan is on Opus + 5.5 at extra-high effort. Every helper agent runs on Opus 5.5 at medium + effort: pass `model: "opus"` and `effort: "medium"` on every agent call. + The owner asked for it on 2026-11-25: "Are you able to move all the work + off this main thread that's using Fable 5.2 to a new session that uses + Opus 5.5 max, and then from there that session would orchestrate the + sub-agents using Opus 5.5. medium", and then "change the main session from + Opus 5.5 Max to Opus 5.5 Extra". Until then the main thread ran on Fable, + and from 2026-11-24 the helpers on Opus. This replaces the split in "Agent + models" below, which is kept for the record. + `.claude/settings.local.json` sets `CLAUDE_CODE_SUBAGENT_MODEL=opus`; it is + not committed. +- `CONSTRAINTS.md` is the quality bar from the end of stage 1. No agent lowers + a number in it or weakens a check to make something pass. A number moves + only through a stage 3 decision with a decision record under + `docs/decisions/` that states the new value and the reason. +- Report what was verified and what was not. A claim needs a test, a + reproduction or a measurement behind it. + +## Where the work is written down + +| What | Where | Kept after the work | +| ------------------------------------------------------------------------------------------------------------------- | ------------------------------------- | ------------------- | +| This plan | `REVIEW_PLAN.md` | No | +| Stage reports | `review/stage-1-report.md`, and so on | No | +| Library, adapter and security reports | `review/stage-2/.md` | No | +| Decision document | `review/stage-3-decisions.md` | No | +| 1.0 public API spec | `review/spec.md` | No | +| Decision records | `docs/decisions/` | Yes | +| Quality bar | `CONSTRAINTS.md` | Yes | +| Mutation runner, bundle-size script and core benchmark, with their saved results and the list of equivalent mutants | `packages/classy-store/tests/` | Yes | + +- `review/` is committed with the stage that wrote it, so a later agent with a + fresh context or its own worktree can read it. +- Stage 3 working reports are in `review/stage-3/`, and the briefs its + helper agents were given are in `review/stage-3/briefs/`. A brief is + started with a prompt that names `COMMON.md` and one other file, and gives + the real paths for the two placeholders below. +- No absolute path of this machine goes into a committed file: the branch is + public and such a path carries the local account name. Reports write + `` for the repository root and `` for the agent scratchpad. + Run `node scripts/scrub-paths.mjs ...` on a report before committing + it. The reports up to 2026-11-19 were committed with real paths and + scrubbed afterwards, so those paths are still in this branch's history. +- Only one document describes the public API when the work is done. The spec + is the working contract for stage 4. By the end of stage 4, + `website/content/docs/API_REFERENCE.md` says everything the spec says, and + stage 5 deletes the spec with the rest of `review/` and this plan. + +## Skills + +| Skill | Stage | Used for | +| ------------------------------------------------------------------- | ----- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `constraint-driven-development` | 1 | Write the quality bar into `CONSTRAINTS.md`: coverage and mutation thresholds, bundle-size budget per entry point, strict types, lint rules, no skipped tests. Later stages may not lower it; a number moves only through an approved stage 3 decision (see Ground rules). | +| `test-driven-development`, `mattpocock-skills:tdd` | 1, 4 | Stage 1 tests pin existing behaviour. In stage 4 every change starts with a failing test. | +| `source-driven-development` | 2, 4 | Read each library's actual source and official docs. Check every build-tool and framework API against its docs before relying on it. | +| `mattpocock-skills:research` | 2 | Structure each library report and cite the files read. | +| `api-and-interface-design` | 2, 3 | Judge the public API: small stable exports, consistent names across the five adapters, defined error behaviour. | +| `mattpocock-skills:codebase-design` | 3 | Decide module boundaries and seams for the core, so internals stay deep and hidden. | +| `doubt-driven-development` | 3, 4 | A fresh-context adversarial review of each design decision and each risky commit. | +| `spec-driven-development` | 3 | Write the 1.0 public API spec at `review/spec.md` from the approved decisions. The spec is what stage 4 implements. | +| `documentation-and-adrs` | 3, 4 | One decision record per approved change under `docs/decisions/`, and the API docs kept in step with the code. | +| `planning-and-task-breakdown` | 3 | Turn the approved decisions into ordered, verifiable tasks. | +| `mattpocock-skills:prototype` | 3 | Throwaway spikes for proposals whose feasibility, cost or benefit reading cannot settle. | +| `incremental-implementation` | 4 | Thin slices, each tested and committed before the next begins. | +| `code-simplification` | 4 | Internal simplification that leaves behaviour unchanged. | +| `performance-optimization` | 4 | Measure against the stage 1 baselines before and after any performance change. | +| `debugging-and-error-recovery`, `mattpocock-skills:diagnosing-bugs` | all | When a check fails or a bug appears: find the root cause, do not guess. | +| `code-review-and-quality` | 4 | The independent review after the last refactor commit. | +| `security-and-hardening` | 2, 4 | Stage 2: a read-only audit of dependencies (is each runtime dependency needed), supply-chain risk, and `persist` and `devtools` handling untrusted stored data, so its findings reach the stage 3 decision. Stage 4: the approved fixes. | +| `ci-cd-and-automation` | 1, 4 | Stage 1: add the CI gates that `CONSTRAINTS.md` needs and CI lacks, so the bar holds while the code is refactored. Stage 4: keep the gates in step with approved changes. | +| `git-workflow-and-versioning` | 4, 5 | Atomic commits, semver, changeset and changelog, release tagging. | +| `deprecation-and-migration` | 5 | Write the post-1.0 policy for renaming or removing exports. Not needed before 1.0: there are no users to migrate. | +| `shipping-and-launch` | 5 | The pre-publish checklist for 1.0.0. | + +Adapter work only: + +- `codebelt-code-style`: the React adapter, the Next.js example and the docs + site's React code. +- `codebelt-solidjs`: the Solid adapter and the Solid example. + +Not for this work: `frontend-ui-engineering`, `frontend-design`, `dataviz`, +`browser-testing-with-devtools`, `next-best-practices`, `caveman`, +`article-writing`, `find-skills`, and the document-format skills. + +## Agent models + +**Replaced on 2026-11-25** by the ground rule on models: the session that +runs the plan is on Opus 5.5 at extra-high effort, and every helper agent on +Opus 5.5 at medium effort. What follows is how the models were assigned +before that, kept for the record. The session that runs the plan is still +the one writer in stage 4. + +The main thread runs Fable, and it is the one writer in stage 4. A helper agent +runs on Fable, on Opus, or on Sonnet at high effort, and never on anything +lower: no Haiku, and no Sonnet below high effort. + +| Setting | Use it for | +| ------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Fable, inherited from the main thread | Work that needs judgement about subtle code, or that feeds a design decision. Mutation triage in `core.ts`, `ownership.ts` and `snapshot.ts`. The stage 2 source reads (Valtio, MobX, Vue reactivity, Solid 2, Svelte 5, Preact Signals and the TC39 proposal, Immer), the adapter agent and the security agent. Stage 3 spikes and adversarial reviews. The independent review and the second comparison pass in stage 4. | +| Opus | Work in between: it needs judgement but does not decide the design. Writing characterisation and type tests through the public API. Mutation triage in the utility files when a survivor is subtle. It may also stand in for Fable when usage is short, except on the three core files. | +| Sonnet at high effort | Self-contained work whose result a tool checks, and reading that only summarises. Mutation triage in `persist.ts`, `history.ts`, `equality.ts` and `collections.ts`, where the mutation runner checks the result. The stage 2 reads marked "API read only" (Legend-State, Zustand and Jotai). Running suites and collecting their results. | + +When it is unclear which applies, use the higher one. + +Running them, as learned on 2026-11-18: + +- At most four at once. Six Fable agents in parallel used a five-hour + allowance in about an hour. +- Every brief tells the agent to commit as soon as a file is in a good state. + After a session restart the agents could not be resumed, and what survived + was what they had left in their worktrees. +- Each agent uses a scratch folder of its own. They share one scratchpad, and + one agent overwrote another's files there. + +## Stage 1: Safety net (one agent, tests and tooling, no library source changes) + +Skills: `constraint-driven-development`, `test-driven-development`, +`mattpocock-skills:tdd`, `debugging-and-error-recovery`, +`ci-cd-and-automation`. + +Goal: any behaviour change in a later stage shows up as a failing test. + +1. Tooling first. None of it is in the repo, and the items below and stage 4 + depend on it. Put each tool under `packages/classy-store/tests/` beside the + existing harnesses, give it a root `package.json` command, and add that + command to "Commands" above. + - A mutation runner. The earlier sweep (655 single-line mutants: 595 + killed, 59 judged equivalent, 1 caught only by the Solid browser suite) + left its tests on the branch but not its script, its mutation rules or + its list of equivalents. The runner must be repeatable: fixed rules, a + seed, a way to limit it to named files, and a tracked list of equivalent + mutants with a reason for each. Its rules must mutate every condition + (negate it, force it true, force it false), because the mutation run + stands in for branch coverage. The unit suite takes about 4 seconds, so + 655 mutants take about 45 minutes run one at a time. + - A bundle-size script: minified and gzipped bytes for each entry point. + No script measures this today, so the sizes in `CLAUDE.md` cannot be + checked by a command. + - A core benchmark: per-operation timings for read, write, snapshot and + getter. The existing benchmark measures React commits in Chromium, not + core operations. +2. Line and function coverage for `src/core`, `src/snapshot`, + `src/collections`, `src/utils`, `src/frameworks`, from `bun test --coverage`. + Bun 1.4.4 reports no branch coverage, in its table or in its lcov file, so + branches are covered by the mutation run: a surviving mutant of a condition + is an untested branch. Every uncovered line gets a test, or a line in the + report saying why it cannot be reached. +3. Full mutation testing with that runner of `core.ts`, `ownership.ts`, + `snapshot.ts`, `collections.ts`, `persist.ts`, `history.ts`, `equality.ts`. + Each surviving mutant is either killed by a new test or added to the + tracked list of equivalent mutants with a reason. The earlier sweep's 59 + equivalents were never written down, so expect to explain about that many + again. +4. Characterisation tests for behaviour nobody has written down: + - notification order across owners and across stores; + - a listener that throws, subscribes or unsubscribes during delivery; + - suspended subtrees: detach, mutate while detached, re-attach, shared + children with several owners, garbage collection of dead owners; + - getters: nested getters, getters reading children, cycles, getters on + object literals and on subclasses, setters; + - proxy invariants: frozen, sealed and non-extensible objects, + non-configurable and non-writable properties, symbols, `__proto__` keys, + sparse arrays, array `length` writes, `Object.defineProperty` on a store; + - identity: the same raw object in two stores, a store inside a store, + a proxy assigned into another store, cycles. +5. Pair every test of internal state with a test of public behaviour. Tests + read internal state through `getInternal`, `getVersion`, `identityOf` and + `unwrap`, which the public entry does not export. For each such assertion, + add a test of the same fact through the public API (a notification, a + snapshot, a getter result, or a dropped object being collected), or say in + the report why nothing public can observe it. List these tests in the + report; stage 4 may rewrite those and no others. Two groups stand out: + - `core.ownership.test.ts` and `core.memory.test.ts` assert on + `getInternal(x).parents`, `.childInternals` and `.reference`, the + structures in `ownership.ts` that stage 3 may decide to reshape. + - The adapter tests, `history.test.ts` and the Solid browser fixtures read + the listener sets `syncListeners` and `batchedListeners`. +6. Extend the seeded differential fuzz test to getters, shared children, + reactive collections, `batch()`, deletes and array methods. A plain-object + model is the oracle. +7. Type tests for every public export and overload. +8. Save baselines: performance and memory suites at full size, bundle sizes + per entry point, and per-operation timings (read, write, snapshot, getter). + - Run the per-operation timings in both Bun (JavaScriptCore) and Node + (V8). The 40 ns figure under "Findings already in hand" does not say + which engine it came from. + - Run each suite at least five times and record the spread. Stage 4 treats + a difference inside that spread as noise and one outside it as a change. + - Record the machine, the OS, and the Bun, Node and browser versions. + - Save the results where Git tracks them, next to each harness. The + existing harnesses write their JSON to `test-results/`, which is ignored. +9. Record the quality bar in `CONSTRAINTS.md` from the numbers measured above. + - Write performance limits as ratios measured in one run (a store read + against a raw property read, for example), not as absolute times, so + they hold on another machine and in CI. + - The rule on skipped tests is no unconditional `skip`, `todo` or `only`. + The one skip in the package today is conditional and stays: clipboard + permissions outside Chromium, in `tests/browser/updates.spec.ts`. + - Record the type and lint suppressions that exist today as the ceiling. +10. Add the CI gates that `CONSTRAINTS.md` needs and CI lacks: coverage, + bundle size, skipped or focused tests, and new suppressions. CI gates + lint, types, tests, build and the packed-package checks already. The + mutation run is too slow for every push and stays a local command. + +Gate: all existing checks pass, the validation matrix included, so a later +failure can be traced to a later change; mutation survivors are zero or +explained; and the tooling, the baselines, `CONSTRAINTS.md` and the new CI +gates are committed. Report any bug found; do not fix it in this stage unless +the fix is one line and the owner agrees. + +## Stage 2: Library comparison (one read-only agent per library, plus adapters and security, parallel) + +Skills: `source-driven-development`, `mattpocock-skills:research`, +`api-and-interface-design`. The security agent adds `security-and-hardening`. + +Each library agent reads source, not documentation, at the files listed, and +records the package version or commit it read. Each also ports five to ten of +our edge-case tests to the other library and records how it behaves. The ports +are written and run in a scratch folder with that library installed there, +and the ported code goes in the report. Each agent writes one file, +`review/stage-2/.md`, and changes nothing else in this checkout. + +| Library | Files to read | Focus | +| -------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Valtio | `vanilla.ts`, `react.ts`, `vanilla/utils/*`, `proxy-compare` | Closest relative. Where are we more complicated for the same result? Version and snapshot caching, `ref()`, `proxyMap`/`proxySet`, `subscribeKey`, `devtools`, `useSnapshot` sync option. | +| MobX | `core/` (atom, derivation, computedvalue, action, reaction, transaction), `types/observableobject.ts`, `types/observablearray.ts`, `api/makeObservable.ts` | Getter memoization and dependency validation, transactions and `runInAction`, strict mode, `autoBind`, subclassing rules, how `this` and arrow functions are handled. | +| Vue reactivity | `reactive.ts`, `baseHandlers.ts`, `collectionHandlers.ts`, `arrayInstrumentations.ts`, `dep.ts`, `effect.ts`, `computed.ts` | The most thorough proxy handlers. `has`, `ownKeys`, `deleteProperty`, array method instrumentation, native Map/Set reactivity, `markRaw`, `toRaw`, `shallowReactive`, readonly proxies. | +| Solid 2 | `@solidjs/signals` `store/store.ts`, `store/types.ts`, `store/reconcile.ts`, `store/utils.ts`, dev diagnostics | Wrappability rules, per-prototype caching, `reconcile`, `snapshot` and `deep`, diagnostic codes and how the dev build is split from production. A first pass is summarised under "Findings already in hand"; go deeper than it did. | +| Svelte 5 | `svelte` `src/internal/client/proxy.js`, `src/reactivity/map.js`, `src/reactivity/set.js` (version 5.57.3 is installed in this repo) | The `$state` proxy: which values it wraps and which it leaves alone, class instances and class fields, and why `SvelteMap` and `SvelteSet` are separate classes that extend the native ones. Bears on API questions 5 and 6. | +| Preact Signals and the TC39 Signals proposal | `signals-core/src/index.ts`, the proposal's polyfill | Computed invalidation algorithm (push-pull, version checks), glitch freedom, cycle detection, batching. Compare only with our getter memoization. | +| Immer | `core/proxy.ts`, `core/finalize.ts`, `utils/common.ts` | Structural sharing, auto-freezing, handling of frozen and non-configurable input, class instances (`immerable`), Map/Set drafts. | +| Legend-State | `ObservableObject.ts`, `batching.ts`, persist plugins | Persistence and sync design, batching. API read only. | +| Zustand and Jotai | middleware (`persist`, `devtools`, `subscribeWithSelector`), public hooks | API read only: what React users expect from a store, persist and devtools options, SSR and hydration story. | + +Report format, one entry per finding: + +- **What they do**, with file and function. +- **What we do**, with `file:line`. +- **Difference in behaviour**, with a runnable reproduction where there is one. +- **Proposal**: adopt, adapt, or reject, and why. +- **Kind**: bug, simplification, performance, API design, diagnostics, docs. +- **Cost**: files touched, breaking or not, risk. + +Every library agent also answers these API questions from its library's point +of view, and writes "no position" where the library has none (Immer has no +subscriptions, for example): + +1. Should synchronous notification be the default for `subscribe()`? +2. Should writes outside a store method be allowed, warned about, or grouped + automatically? Does `batch()` belong in the API? +3. Should snapshot getters stay enumerable own accessors? +4. Can arrow-function methods and `#private` fields be made to work, for + example with a base class or a constructor that returns the proxy? +5. Should native `Map` and `Set` be reactive directly, replacing + `reactiveMap` and `reactiveSet`? +6. Is opt-in (`PROXYABLE`) or opt-out (`markRaw`, `ref`, freezing) the better + default for nested class instances? +7. Are the entry points, export names and adapter names consistent across the + five frameworks? +8. What development-only diagnostics would catch our silent failure modes? + +Two more read-only agents run alongside the library agents. They use the same +report format and write to the same folder: + +- **Adapters.** Reads our five adapters, and each framework's official + guidance for binding an external store: React (`useSyncExternalStore`, + server snapshots, the React Compiler), Vue (refs and effect scopes), Svelte + (the store contract the adapter targets, and what Svelte 5 offers for + binding an external store to runes), Solid 2 and Angular (signals, + `DestroyRef`). It also reads the public API of Pinia and NgRx SignalStore, + because Zustand and Jotai show only what React users expect. It answers API + question 7, and says for each adapter whether its name, return type and + cleanup are what that framework's users would expect. +- **Security.** Audits the dependencies and the supply chain (`proxy-compare` + is the only runtime dependency; publishing uses npm provenance), and how + `persist` and `devtools` treat data they did not write: stored JSON with + `__proto__` or `constructor` keys, version and migration input, cross-tab + storage events, and DevTools messages that set state. Each finding is a + proposal for stage 3, so it is decided with the rest. + +## Stage 3: Design review (one agent: read and experiment, decide, then write) + +1. Merge the stage 2 reports and remove duplicates. +2. Review our own code independently of other libraries: every function in + `core.ts`, `ownership.ts` and `snapshot.ts` must have a stated reason to + exist. Flag code that a test does not require (delete it in a throwaway + worktree and see what fails), duplicated logic, and names that no longer + match behaviour. +3. Spike what reading cannot settle. Where a proposal's feasibility, cost or + benefit is uncertain, build a throwaway spike in a scratch worktree and + measure it against the stage 1 baselines: which tests fail, bundle size, + per-operation timings. Likely candidates: arrow-function methods through a + base class or a constructor that returns the proxy, native `Map` and `Set` + reactivity, per-prototype descriptor caching, `has` and `ownKeys` traps, + and a development build. Spike code is never committed to the branch; + stage 4 writes the approved change again, test first. +4. Produce one decision document, `review/stage-3-decisions.md`, grouped by: + bugs, internal simplification, public API, diagnostics, performance. Each + proposed change has options, a recommendation, the tests it affects, its + cost, any number it would move in `CONSTRAINTS.md`, and one of two labels: + - **Before 1.0**: it changes the public API or documented behaviour, so + after 1.0 it would be a breaking change. + - **Can follow 1.0**: it could ship in a 1.x release without breaking a + consumer. Internal simplification, performance and diagnostics are + usually this kind. +5. In the same document, list every behaviour that stage 1 pinned and the + docs do not promise: notification order across owners, for example. + Recommend for each either **guaranteed** (documented, and changing it is a + breaking change) or **unspecified** (it may change in a minor release). + Without this, the stage 1 tests make every incidental behaviour part of + the 1.0 contract. +6. The agent running the stage decides each item and writes the decision and + its reason into the document. Before the decisions stand, a fresh agent + that took no part in the spikes reviews the document as an adversary and + its objections are answered in writing. Nothing is implemented before + that. The owner approved each item here until 2026-11-19 and has since + handed the decisions over (first ground rule). +7. From the approved items, write the 1.0 public API spec at `review/spec.md` + and one decision record per change under `docs/decisions/`, then an ordered + task list for stage 4. The spec lists guaranteed and unspecified behaviour + separately. + +Skills: `api-and-interface-design`, `mattpocock-skills:codebase-design`, +`mattpocock-skills:prototype`, `doubt-driven-development`, +`spec-driven-development`, `documentation-and-adrs`, +`planning-and-task-breakdown`. + +## Stage 4: Refactor (one writer, one change per commit) + +Skills: `incremental-implementation`, `test-driven-development`, +`mattpocock-skills:tdd`, `code-simplification`, `performance-optimization`, +`source-driven-development`, `security-and-hardening`, `ci-cd-and-automation`, +`documentation-and-adrs`, `git-workflow-and-versioning`, +`code-review-and-quality`, `doubt-driven-development`. + +- Order: bugs, then API removals, then internal simplification, then the + remaining API changes, then diagnostics, then performance. Removals come + before simplification so nothing is simplified and then deleted. The + stage 3 task list may reorder where one change depends on another. +- Each commit: the change, its tests, updated docs and examples, all checks, + the mutation run on touched files, and a comparison with the stage 1 + baselines. A regression in performance, memory or bundle size is reported + with numbers, not absorbed; a difference inside the spread recorded in + stage 1 is noise. If the approved decision moves a number in + `CONSTRAINTS.md`, the same commit edits that file and names the decision. +- A test of public behaviour may be changed only when the behaviour change + was approved in stage 3; the commit message names the decision. +- A test of internal state, from the list stage 1 made, may be rewritten or + removed when the internals it reads change. The commit message names the + public-behaviour test that covers the same fact. +- After the last refactor commit, in this order: + 1. An independent review by an agent that took no part in the refactor. + 2. A second library-comparison pass limited to the areas that changed. + 3. Their findings are decided like any stage 3 item, and written into the + stage report. An approved fix is committed under the same rules as any + other change. + 4. Last, on the final commit: the full validation matrix (browsers, React + versions with and without the compiler, Node versions, Vue, Svelte, + Angular, Next.js, packed-consumer checks). The stage report names the + commit it passed on. Any later commit that changes code, tests or build + configuration means running it again. + +## Stage 5: Release + +Skills: `shipping-and-launch`, `git-workflow-and-versioning`, +`deprecation-and-migration`. + +- Write the pre-publish checklist and the post-1.0 deprecation policy. +- Check that `website/content/docs/API_REFERENCE.md` says everything the spec + says, then delete `review/` and this plan in one commit. Decision records, + `CONSTRAINTS.md` and the stage 1 tooling stay. +- There is no release candidate and no soak period. +- The agent's work ends with a report that the branch is ready and what was + verified. The merge and the 1.0.0 release happen only when the owner + decides, and the owner gives that instruction or does it themselves. diff --git a/bun.lock b/bun.lock index 7e7abddd..fd1ccde0 100644 --- a/bun.lock +++ b/bun.lock @@ -54,12 +54,12 @@ "version": "0.0.0", "dependencies": { "@codebelt/classy-store": "workspace:*", - "@solidjs/web": "2.0.0-rc.18", - "solid-js": "2.0.0-rc.18", + "@solidjs/web": "2.0.0", + "solid-js": "2.0.0", }, "devDependencies": { - "@solidjs/vite-plugin": "3.0.0-next.51", - "typescript": "^5.7.0", + "@solidjs/vite-plugin": "3.0.1", + "typescript": "^7.0.2", "vite": "8.3.8", }, }, @@ -73,7 +73,7 @@ "devDependencies": { "@sveltejs/vite-plugin-svelte": "7.3.1", "svelte-check": "4.7.8", - "typescript": "^5.7.0", + "typescript": "^6.0.3", "vite": "8.3.8", }, }, @@ -86,7 +86,7 @@ }, "devDependencies": { "@vitejs/plugin-vue": "6.0.11", - "typescript": "^5.7.0", + "typescript": "^6.0.3", "vite": "8.3.8", "vue-tsc": "3.3.14", }, @@ -101,19 +101,22 @@ "@angular/compiler": "22.2.6", "@angular/core": "22.2.6", "@angular/platform-browser": "22.2.6", + "@arethetypeswrong/cli": "0.18.5", "@babel/core": "7.29.7", "@happy-dom/global-registrator": "21.0.4", "@playwright/test": "1.65.1", - "@solidjs/compiler": "2.0.0-rc.18", - "@solidjs/web": "2.0.0-rc.18", + "@solidjs/compiler": "2.0.0", + "@solidjs/web": "2.0.0", + "@types/babel__core": "7.20.5", "@types/bun": "1.4.4", "@types/react": "19.3.0", "@types/react-dom": "19.3.0", "babel-plugin-react-compiler": "1.0.0", + "publint": "0.3.25", "react": "19.3.1", "react-compiler-runtime": "1.0.0", "react-dom": "19.3.1", - "solid-js": "2.0.0-rc.18", + "solid-js": "2.0.0", "svelte": "5.57.3", "tsdown": "0.23.7", "typescript": "7.0.2", @@ -122,7 +125,7 @@ "peerDependencies": { "@angular/core": "^22.0.0", "react": "^18.0.0 || ^19.0.0", - "solid-js": "2.0.0-rc.18", + "solid-js": "^2.0.0", "svelte": "^4.0.0 || ^5.0.0", "vue": "^3.2.0", }, @@ -134,19 +137,44 @@ "vue", ], }, + "website": { + "name": "classy-store-docs", + "dependencies": { + "@codebelt/classy-store": "workspace:*", + "fumadocs-core": "16.19.4", + "fumadocs-mdx": "15.6.3", + "fumadocs-ui": "npm:@fumadocs/base-ui@16.19.4", + "mermaid": "^12.3.0", + "next": "16.4.6", + "next-themes": "0.4.6", + "react": "^19.3.1", + "react-dom": "^19.3.1", + }, + "devDependencies": { + "@playwright/test": "1.65.1", + "@tailwindcss/postcss": "^4.3.5", + "@types/mdx": "^2.0.14", + "@types/node": "^26.6.6", + "@types/react": "^19.3.0", + "@types/react-dom": "^19.3.0", + "postcss": "^8.5.33", + "serve": "^14.2.8", + "tailwindcss": "^4.3.5", + "typescript": "^7.0.2", + "zod": "^4.6.7", + }, + }, }, "trustedDependencies": [ "sharp", ], - "overrides": { - "@solidjs/babel-plugin": "2.0.0-rc.18", - "@solidjs/compiler": "2.0.0-rc.18", - }, "packages": { "@alloc/quick-lru": ["@alloc/quick-lru@5.2.0", "", {}, "sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw=="], "@ampproject/remapping": ["@ampproject/remapping@2.3.0", "", { "dependencies": { "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-30iZtAPgz+LTIYoeivqYo853f02jBYSd5uGnGpkFV0M3xOt9aN73erkgYAmZU43x4VfqcnLxW9Kpg3R5LC4YYw=="], + "@andrewbranch/untar.js": ["@andrewbranch/untar.js@1.0.4", "", {}, "sha512-pVXSwPsLuw8IGLo2Di0EaOfsk+ntVvpkk942J/sHYIkwvtKUakEcPh7HBgZ6tuimgzKSEHgCvO4XgQ05DEbwDw=="], + "@angular-devkit/architect": ["@angular-devkit/architect@0.2202.7", "", { "dependencies": { "@angular-devkit/core": "22.2.7", "rxjs": "7.8.2" }, "bin": { "architect": "bin/cli.js" } }, "sha512-l8apKEojW8WB5pqhK+BkO7+DZSCLNpvP+JBdBzDYagrtkKbtr1AKPuAE/2sVvlBE8SXyNCp3CX9gTtkk2q40mw=="], "@angular-devkit/core": ["@angular-devkit/core@22.2.7", "", { "dependencies": { "ajv": "8.20.0", "ajv-formats": "3.0.1", "jsonc-parser": "3.3.1", "picomatch": "4.0.7", "rxjs": "7.8.2", "source-map": "0.8.0" }, "peerDependencies": { "chokidar": "^5.0.0" }, "optionalPeers": ["chokidar"] }, "sha512-cchZAMsV4d76RDZBlWzPhYxM/Hb6bmq71oUngdrwehMbBbdQu3W9C2tGlvxuPxbRKru9ZlUa14YVXQ0+QnhFtw=="], @@ -167,6 +195,12 @@ "@angular/platform-browser": ["@angular/platform-browser@22.2.6", "", { "dependencies": { "tslib": "^2.3.0" }, "peerDependencies": { "@angular/animations": "22.2.6", "@angular/common": "22.2.6", "@angular/core": "22.2.6" }, "optionalPeers": ["@angular/animations"] }, "sha512-xXSgdnnLLv/3aEC/pqyrUd0xlyYURGZG2HR3sOIN3bsIoctGFvzA5iwt/GEKpIDA1rn+NnKNLK/EKQaPA4YZEw=="], + "@antfu/install-pkg": ["@antfu/install-pkg@2.1.0", "", { "dependencies": { "package-manager-detector": "^1.8.0", "tinyexec": "^1.3.1" } }, "sha512-sdg9NxU3zR4Mnawfbc/x6GB5Wf17WYud5qOuEuxXjaKpYpMkISSJEjItGebXJ2bQ4DIcly4NYH23mtkGJjvKUw=="], + + "@arethetypeswrong/cli": ["@arethetypeswrong/cli@0.18.5", "", { "dependencies": { "@arethetypeswrong/core": "0.18.5", "chalk": "^4.1.2", "cli-table3": "^0.6.3", "commander": "^10.0.1", "marked": "^9.1.2", "marked-terminal": "^7.1.0", "semver": "^7.5.4" }, "bin": { "attw": "./dist/index.js" } }, "sha512-gM+8vRsQOD/Uc7EnBedUhkG5OCsDWE4uoak5QvomGpMpaky0Eh41p04nIMgrWb8EOmqZUJGc6zz9hsP6E56R7g=="], + + "@arethetypeswrong/core": ["@arethetypeswrong/core@0.18.5", "", { "dependencies": { "@andrewbranch/untar.js": "^1.0.3", "@loaderkit/resolve": "^1.0.2", "cjs-module-lexer": "^1.2.3", "fflate": "^0.8.3", "lru-cache": "^11.0.1", "semver": "^7.5.4", "typescript": "5.6.1-rc", "validate-npm-package-name": "^5.0.0" } }, "sha512-9ytjzGwxjm9Uz7I9avfbt5vlQt6uk9uRRESzJjqrznl6WKvI6dwYTo+vJ3U02Wrq/mR3iql/PzhvHhKdJIAjDQ=="], + "@babel/code-frame": ["@babel/code-frame@7.29.7", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.29.7", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw=="], "@babel/compat-data": ["@babel/compat-data@7.29.7", "", {}, "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg=="], @@ -183,8 +217,6 @@ "@babel/helper-module-transforms": ["@babel/helper-module-transforms@7.29.14", "", { "dependencies": { "@babel/helper-module-imports": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7", "@babel/traverse": "^7.29.14" }, "peerDependencies": { "@babel/core": "^7.0.0" } }, "sha512-2XDvQVd9JESaOgGc4jT2/jquTAO7ppA5noTZQqH+MmZ89yjCzScLwtCPbWtkPZylL+TLWR49IwWmk+QkRR4GsA=="], - "@babel/helper-plugin-utils": ["@babel/helper-plugin-utils@7.29.7", "", {}, "sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw=="], - "@babel/helper-string-parser": ["@babel/helper-string-parser@7.29.14", "", {}, "sha512-CXvKMFvM80ihI7Vox9jb+kQjnyjESQNPM+vB7U0Zz6TWuZA+Z/FL0QPMH300h33qJtIx+REeBhXqWOPW48TcAQ=="], "@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@7.29.7", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="], @@ -195,8 +227,6 @@ "@babel/parser": ["@babel/parser@7.29.14", "", { "dependencies": { "@babel/types": "^7.29.14" }, "bin": "./bin/babel-parser.js" }, "sha512-VL220vXuyO2z3rNIQwY7ftj9UwpqOt+33sH+sBWkOekbsSR2g7EEMnOx24ZlCH0xOA3DM/33SifVFGbnJD8r/w=="], - "@babel/plugin-syntax-jsx": ["@babel/plugin-syntax-jsx@7.29.7", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-TSu8+mHCoEaaCDEZ0I3+6mvTBYR4PCxQwf2z9/r5Tbztv6NaLR3B9thGTTxX2WGuGHJqRiAbKPeGTJ5XWXVg6A=="], - "@babel/runtime": ["@babel/runtime@7.29.14", "", {}, "sha512-Y5tqevQaUAZhhj82BpYMNC1ssvLQTVAfwKdm8iy8qwmhvC2/CpcAu8OC+QEtjM7pMk7knx83u1Qj8gzkicyelw=="], "@babel/template": ["@babel/template@7.29.7", "", { "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/parser": "^7.29.7", "@babel/types": "^7.29.7" } }, "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg=="], @@ -205,6 +235,10 @@ "@babel/types": ["@babel/types@7.29.14", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.14", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-UjI/dKmwJwT9pOszJitq2G6EObZPnsZUfdCr92z2TlF3EZK9J3EdfOKUrCzHl6wFthbzwhzl1Soc/UIwxRiq6w=="], + "@base-ui/react": ["@base-ui/react@1.9.0", "", { "dependencies": { "@babel/runtime": "^7.29.7 || ^8.0.0", "@base-ui/utils": "0.5.0", "@floating-ui/react-dom": "^2.1.9", "@floating-ui/utils": "^0.2.12", "use-sync-external-store": "^1.7.0" }, "peerDependencies": { "@date-fns/tz": "^1.2.0", "@types/react": "^17 || ^18 || ^19", "date-fns": "^4.0.0", "react": "^17 || ^18 || ^19", "react-dom": "^17 || ^18 || ^19" }, "optionalPeers": ["@date-fns/tz", "@types/react", "date-fns"] }, "sha512-S8CSYosASBKtpL8SWUfS78rFElfLijiCgA7oHOK22jCJ95FULsYyKwBNFOgudt0RA+/7yNc7F81bOvQnRgbBiQ=="], + + "@base-ui/utils": ["@base-ui/utils@0.5.0", "", { "dependencies": { "@babel/runtime": "^7.29.7 || ^8.0.0", "@floating-ui/utils": "^0.2.12", "reselect": "^5.3.0", "use-sync-external-store": "^1.7.0" }, "peerDependencies": { "@types/react": "^17 || ^18 || ^19", "react": "^17 || ^18 || ^19", "react-dom": "^17 || ^18 || ^19" }, "optionalPeers": ["@types/react"] }, "sha512-dYGGcEttjkYiMoa5nHm8vLaJ2UcuTWxo3BFAwOYXeRg/q7UVVvA6cacEIXEs3FgBfK1CGtW1ptElqs7wsx+t9A=="], + "@biomejs/biome": ["@biomejs/biome@2.6.8", "", { "optionalDependencies": { "@biomejs/cli-android-arm64": "2.6.8", "@biomejs/cli-android-x64": "2.6.8", "@biomejs/cli-darwin-arm64": "2.6.8", "@biomejs/cli-darwin-x64": "2.6.8", "@biomejs/cli-linux-arm64": "2.6.8", "@biomejs/cli-linux-arm64-musl": "2.6.8", "@biomejs/cli-linux-x64": "2.6.8", "@biomejs/cli-linux-x64-musl": "2.6.8", "@biomejs/cli-win32-arm64": "2.6.8", "@biomejs/cli-win32-x64": "2.6.8" }, "bin": { "biome": "bin/biome" } }, "sha512-kqZUFvX6/aYQOmzfRN5ANcfNS9wLH4aHLWWP/dQKyhRZVoA6rdWszA7DGugFcxPbMiznUyVYyukVl+ExZN4PQA=="], "@biomejs/cli-android-arm64": ["@biomejs/cli-android-arm64@2.6.8", "", { "os": "android", "cpu": "arm64" }, "sha512-X4JKPLK85kfUTwuuaORFplnBfGjKkp62PsFhhcL7F/Tpltc7pyUofjlkkMnlZZLWsifFl7LNB8ngVrwJg1uo1Q=="], @@ -227,6 +261,10 @@ "@biomejs/cli-win32-x64": ["@biomejs/cli-win32-x64@2.6.8", "", { "os": "win32", "cpu": "x64" }, "sha512-cD6HvGczZUiAYsY8s2TxxXj2AHFzEdMomvVJfEjzOjBM45nGqIDfBpbtvwGQzDCN8X2yKKk9u1jnDZisT2nxIg=="], + "@braidai/lang": ["@braidai/lang@1.1.2", "", {}, "sha512-qBcknbBufNHlui137Hft8xauQMTZDKdophmLFv05r2eNmdIv/MlPuP4TdUknHG68UdWLgVZwgxVe735HzJNIwA=="], + + "@braintree/sanitize-url": ["@braintree/sanitize-url@7.1.2", "", {}, "sha512-jigsZK+sMF/cuiB7sERuo9V7N9jx+dhmHHnQyDSVdpZwVutaBu7WvNYqMDLSgFgfB30n452TP3vjDAvFC973mA=="], + "@bufbuild/protobuf": ["@bufbuild/protobuf@2.16.0", "", {}, "sha512-FWa0sPlqYGJgpTs6OxBRcL/AW4JT0OIO+W1ajerluoTVh8CV0B7XM1qsNCRgnkSCkRCgOICKHRQlY17jrsm0+Q=="], "@changesets/apply-release-plan": ["@changesets/apply-release-plan@7.1.1", "", { "dependencies": { "@changesets/config": "^3.1.4", "@changesets/get-version-range-type": "^0.4.0", "@changesets/git": "^3.0.4", "@changesets/should-skip-package": "^0.1.2", "@changesets/types": "^6.1.0", "@manypkg/get-packages": "^1.1.3", "detect-indent": "^6.0.0", "fs-extra": "^7.0.1", "lodash.startcase": "^4.4.0", "outdent": "^0.5.0", "prettier": "^2.7.1", "resolve-from": "^5.0.0", "semver": "^7.5.3" } }, "sha512-9qPCm/rLx/xoOFXIHGB229+4GOL76S4MC+7tyOuTsR6+1jYlfFDQORdvwR5hDA6y4FL2BPt3qpbcQIS+dW85LA=="], @@ -267,8 +305,20 @@ "@changesets/write": ["@changesets/write@0.4.0", "", { "dependencies": { "@changesets/types": "^6.1.0", "fs-extra": "^7.0.1", "human-id": "^4.1.1", "prettier": "^2.7.1" } }, "sha512-CdTLvIOPiCNuH71pyDu3rA+Q0n65cmAbXnwWH84rKGiFumFzkmHNT8KHTMEchcxN+Kl8I54xGUhJ7l3E7X396Q=="], + "@chevrotain/cst-dts-gen": ["@chevrotain/cst-dts-gen@13.2.0", "", { "dependencies": { "@chevrotain/gast": "13.2.0", "@chevrotain/types": "13.2.0" } }, "sha512-bA9dvWlhAUcHkNwU+8w9yiUxJPlj/Lm3VqS7MD+NbIR/7LmpNLuK/AWNFdCo/T3SK5ND0/UHf3IJvl/Jn/i6yg=="], + + "@chevrotain/gast": ["@chevrotain/gast@13.2.0", "", { "dependencies": { "@chevrotain/types": "13.2.0" } }, "sha512-bCARdAsG+eEbOveSXcOAC7pVxA04I1ionzeMOwIYf5NX7SaS7zgn4Dgug2BSqoL+iyKeMNSorQjsFSHJHsCNwg=="], + + "@chevrotain/regexp-to-ast": ["@chevrotain/regexp-to-ast@13.2.0", "", {}, "sha512-kxpUkLtiaK09ph+dib+Yvm+3sWSnuwlo25gqfKRgTPNmF6H7uW4gVkMjaRdtnN783S9sM6vUNWh9CsxYX4QwKw=="], + + "@chevrotain/types": ["@chevrotain/types@13.2.0", "", {}, "sha512-7qrYHRlKfWf2AvBfJi5eVOrKAkbxvMFsy/iIHTGIiApNcEecCaVIdR+mIQhyCBsTDJxBz4JWXHMo6krbhR9hVg=="], + + "@chevrotain/utils": ["@chevrotain/utils@13.2.0", "", {}, "sha512-SzKYY68rseOrb9KILVzPsl6SjkQtdWw01SRGB5aCVI5kFcHltQsOYV3JB0Ffst72DgkvHCyDQ0NLwxtmCCf97Q=="], + "@codebelt/classy-store": ["@codebelt/classy-store@workspace:packages/classy-store"], + "@colors/colors": ["@colors/colors@1.5.0", "", {}, "sha512-ooWCrlZP11i8GImSjTHYHLkvFDP48nS4+204nGb1RiX/WXYHmJA2III9/e2DWVabCESdW7hBAEzHRqUn9OUVvQ=="], + "@emnapi/core": ["@emnapi/core@1.11.3", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.3", "tslib": "^2.4.0" } }, "sha512-zLpS5asjEb7lq8jYLq37N6XKaE41DIexlY1rF/z4/tIl3wo13Sqm28fRyfIsKZD+NZ8mM5RoKkpW/rBcuoSZSg=="], "@emnapi/runtime": ["@emnapi/runtime@1.11.3", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA=="], @@ -327,10 +377,28 @@ "@esbuild/win32-x64": ["@esbuild/win32-x64@0.28.2", "", { "os": "win32", "cpu": "x64" }, "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g=="], + "@floating-ui/core": ["@floating-ui/core@1.8.0", "", { "dependencies": { "@floating-ui/utils": "^0.2.12" } }, "sha512-0CIZ5itps/8x7BG8dEIhs53BvCUH2PCoogtakwRTut+Arm58sJooJ0AuZhLw2HJYIR5cMLNPBSS728sPho2khQ=="], + + "@floating-ui/dom": ["@floating-ui/dom@1.8.0", "", { "dependencies": { "@floating-ui/core": "^1.8.0", "@floating-ui/utils": "^0.2.12" } }, "sha512-yXSrzeHZBTZadLOlfyhCkJHNeLJnHRnRInwdZ40L7ZiaAtrBwoYlsDrX3v5zB1Utk7CLfzcOVnVVWoXEky7Ceg=="], + + "@floating-ui/react-dom": ["@floating-ui/react-dom@2.1.9", "", { "dependencies": { "@floating-ui/dom": "^1.8.0" }, "peerDependencies": { "react": ">=16.8.0", "react-dom": ">=16.8.0" } }, "sha512-JDjEFGCpImxDCA7JJKviA0M9+RtmJdj0m/NVU5IMgBK+AmZouAQQ7/+2GLH0GXXY0YMw9oXPB8hKdbPYg5QLYg=="], + + "@floating-ui/utils": ["@floating-ui/utils@0.2.12", "", {}, "sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww=="], + + "@fuma-translate/react": ["@fuma-translate/react@1.0.2", "", { "peerDependencies": { "@types/react": "*", "react": "^19.2.0", "react-dom": "^19.2.0" }, "optionalPeers": ["@types/react"] }, "sha512-uOiOtBx3nRXR8Nu1GzBf1tApgF1FErDBTHxRIAQeyQdyOoZbrNRN6H4kDCWObY4qyGeGbHydG0DHzgeUgFDMIw=="], + + "@fumadocs/tailwind": ["@fumadocs/tailwind@0.1.5", "", { "peerDependencies": { "tailwindcss": "^4.0.0" }, "optionalPeers": ["tailwindcss"] }, "sha512-ohzmuLTfNNRvP6B/Xx31lWJ58xu40NcmI+6mc/jivYeOoofnmdxBKu5gCErTgOE/mUqyVv4GvYeqd9FhoLHphg=="], + + "@fumari/image-size": ["@fumari/image-size@0.1.1", "", {}, "sha512-iaiV2wyzJ4mW358NX4CX3yGit+WjKYzpaQ+rldK9BjL/5jFpeV6ruWnZVq7MEyMn3Gd0DLi8g/79NZAAQaGscw=="], + "@happy-dom/global-registrator": ["@happy-dom/global-registrator@21.0.4", "", { "dependencies": { "@types/node": ">=20.0.0", "happy-dom": "^21.0.4" } }, "sha512-Bbr0hW9hhDhBf3Jp0EyDlkCbFgbr0z2jd3BMKYOYW+fOkPM4Nx195GMXyCtRCGEgoNn6i09FabXrSkNFm2ONzg=="], "@harperfast/extended-iterable": ["@harperfast/extended-iterable@1.0.5", "", {}, "sha512-4ScXlphaKEa49RpHmqwATq9QI9aUTdWVYDlJkzxhsD7ShJP+pHCYLznMO9n/wREY8jPjRZ59wLJY6HM5yB5Gkw=="], + "@iconify/types": ["@iconify/types@2.0.0", "", {}, "sha512-+wluvCrRhXrhyOmRDJ3q8mux9JkKy5SJ/v8ol2tu4FVjyYvtEzkc/3pK15ET6RKg4b4w4BmTk1+gsCUhf21Ykg=="], + + "@iconify/utils": ["@iconify/utils@3.1.7", "", { "dependencies": { "@antfu/install-pkg": "^2.0.1", "@iconify/types": "^2.0.0", "import-meta-resolve": "^4.2.0" } }, "sha512-JZHlwdID+dy+lTgbYC8NEC4zeugqeYsc6jewvzb4c58kHauJn+X7rNwQjxz5p2qSjqaEeQoLkCIQ9v/H4PK0/w=="], + "@img/colour": ["@img/colour@1.1.0", "", {}, "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ=="], "@img/sharp-darwin-arm64": ["@img/sharp-darwin-arm64@0.35.5", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-arm64": "1.3.4" }, "os": "darwin", "cpu": "arm64" }, "sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg=="], @@ -443,10 +511,16 @@ "@lmdb/lmdb-win32-x64": ["@lmdb/lmdb-win32-x64@3.5.6", "", { "os": "win32", "cpu": "x64" }, "sha512-1g7G0knRX2iV/voDu54yxrGqw5Dk0w2oIYb7dgJq8IkOi+m7wbD8Q3QpPFjh0C01G58S88dqGn03len6UPCXsg=="], + "@loaderkit/resolve": ["@loaderkit/resolve@1.0.6", "", { "dependencies": { "@braidai/lang": "^1.0.0" } }, "sha512-G8FdIoF5CypfwmD9rl8BXod5HDn8JqB0CCNBXDTaRZ+yRYhARrrSToX1zg1zy9jX3zLqigsELwhT4gNtkdQAUg=="], + "@manypkg/find-root": ["@manypkg/find-root@1.1.0", "", { "dependencies": { "@babel/runtime": "^7.5.5", "@types/node": "^12.7.1", "find-up": "^4.1.0", "fs-extra": "^8.1.0" } }, "sha512-mki5uBvhHzO8kYYix/WRy2WX8S3B5wdVSc9D6KcU5lQNglP2yt58/VfLuAK49glRXChosY8ap2oJ1qgma3GUVA=="], "@manypkg/get-packages": ["@manypkg/get-packages@1.1.3", "", { "dependencies": { "@babel/runtime": "^7.5.5", "@changesets/types": "^4.0.1", "@manypkg/find-root": "^1.1.0", "fs-extra": "^8.1.0", "globby": "^11.0.0", "read-yaml-file": "^1.1.0" } }, "sha512-fo+QhuU3qE/2TQMQmbVMqaQ6EWbMhi4ABWP+O4AM1NqPBuy0OrApV5LO6BrrgnhtAHS2NH6RrVk9OL181tTi8A=="], + "@mdx-js/mdx": ["@mdx-js/mdx@3.1.1", "", { "dependencies": { "@types/estree": "^1.0.0", "@types/estree-jsx": "^1.0.0", "@types/hast": "^3.0.0", "@types/mdx": "^2.0.0", "acorn": "^8.0.0", "collapse-white-space": "^2.0.0", "devlop": "^1.0.0", "estree-util-is-identifier-name": "^3.0.0", "estree-util-scope": "^1.0.0", "estree-walker": "^3.0.0", "hast-util-to-jsx-runtime": "^2.0.0", "markdown-extensions": "^2.0.0", "recma-build-jsx": "^1.0.0", "recma-jsx": "^1.0.0", "recma-stringify": "^1.0.0", "rehype-recma": "^1.0.0", "remark-mdx": "^3.0.0", "remark-parse": "^11.0.0", "remark-rehype": "^11.0.0", "source-map": "^0.7.0", "unified": "^11.0.0", "unist-util-position-from-estree": "^2.0.0", "unist-util-stringify-position": "^4.0.0", "unist-util-visit": "^5.0.0", "vfile": "^6.0.0" } }, "sha512-f6ZO2ifpwAQIpzGWaBQT2TXxPv6z3RBzQKpVftEWN78Vl/YweF1uwussDx8ECAXVtr3Rs89fKyG9YlzUs9DyGQ=="], + + "@mermaid-js/parser": ["@mermaid-js/parser@2.0.1", "", { "dependencies": { "@chevrotain/types": "~13.2.0" } }, "sha512-j37dj/h6p6pots1L7pLPPNuABEEu9WP4OYg9pW1g+nYG331j0+3canE9OagtYdytYvdSAMG+2fKU5cxep6LgjA=="], + "@modelcontextprotocol/core": ["@modelcontextprotocol/core@2.3.1", "", { "dependencies": { "zod": "^4.2.0" } }, "sha512-laVmIhPGpWi7rG9q+0UigblRN0Hws/Yjlb6qLFtVqryXVLkc4h+yN8z731POD2LnAGQlFe7/tXhUm7Bi0YB91g=="], "@modelcontextprotocol/server": ["@modelcontextprotocol/server@2.3.1", "", { "dependencies": { "@modelcontextprotocol/core": "2.3.1", "zod": "^4.2.0" } }, "sha512-e59MfWuSssj6DoQ96JCTqdW1AXT5/XtnTl0WWd6MU1Ka434fFUGGosCLJbGNySDhHGvxQWoRWK137FXYFkYNWw=="], @@ -595,6 +669,8 @@ "@playwright/test": ["@playwright/test@1.65.1", "", { "dependencies": { "playwright": "1.65.1" }, "bin": { "playwright": "cli.js" } }, "sha512-y+NCIRm2LvY4slUVWvGh1nujJ8RF/hEisIsq2mtUPgdQC4L701bq5hZGMhrpeXjACvwvO9tj5dJqhvM6TP9lbw=="], + "@publint/pack": ["@publint/pack@0.1.7", "", { "dependencies": { "tinyexec": "^1.3.0" } }, "sha512-4EDEmvxWtgsCnnVeBvtFIFZtUhPPt1+bA9JrSwU4Sa//6oKtzCSlGGXYJr44OD9aGISymbieJ4mCKHUygUDU+g=="], + "@quansync/fs": ["@quansync/fs@1.0.0", "", { "dependencies": { "quansync": "^1.0.0" } }, "sha512-4TJ3DFtlf1L5LDMaM6CanJ/0lckGNtJcMjQ1NAV6zDmA0tEHKZtxNKin8EgPaVX1YzljbxckyT2tJrpQKAtngQ=="], "@rolldown/binding-android-arm-eabi": ["@rolldown/binding-android-arm-eabi@1.3.2", "", { "os": "android", "cpu": "arm" }, "sha512-kqR2xcygEx3WwDY69LsKeyf7SVmx4yzMtKZRknyaHieVJdRvvnAM97L0Gq6tUFc9T2YXcW/Ghij2+Um6He0LTw=="], @@ -633,27 +709,43 @@ "@schematics/angular": ["@schematics/angular@22.2.7", "", { "dependencies": { "@angular-devkit/core": "22.2.7", "@angular-devkit/schematics": "22.2.7", "jsonc-parser": "3.3.1", "oxc-parser": "0.156.0", "typescript": "6.0.3" } }, "sha512-cdwLAc0m6mWZ3HA0VHqulUKItviExnENQwDQ01f9lQS9bTAWBEkg7Pgua+3BijMUEE5sf/kamqCdwaKPUn1uXQ=="], - "@solidjs/babel-plugin": ["@solidjs/babel-plugin@2.0.0-rc.18", "", { "dependencies": { "@babel/helper-module-imports": "7.18.6", "@babel/plugin-syntax-jsx": "^7.18.6", "@babel/types": "^7.20.7", "html-entities": "2.3.3", "parse5": "^7.1.2" }, "peerDependencies": { "@babel/core": "^7.20.12", "@tsrx/core": "0.1.63" }, "optionalPeers": ["@tsrx/core"] }, "sha512-jgwUfRB9jZrIaFxjgzbr6Di7H+jSVEk7j+ZtYHLWSTuF1UnRct6wrfrGQOU9B9WQZa8fR0KWNkdLlb6zfqfeZw=="], + "@shikijs/core": ["@shikijs/core@4.6.0", "", { "dependencies": { "@shikijs/primitive": "4.6.0", "@shikijs/types": "4.6.0", "@shikijs/vscode-textmate": "^10.1.0", "@types/hast": "^3.0.5", "hast-util-to-html": "^9.0.6" } }, "sha512-bfd4OKgvoyXYiYmMRuleA656P4V7M/Du9lcTl38Ngm6KszMj7bq4J1IGZwSYR4c95Tv5UQALtYNWUwaI9UT3xw=="], + + "@shikijs/engine-javascript": ["@shikijs/engine-javascript@4.6.0", "", { "dependencies": { "@shikijs/types": "4.6.0", "@shikijs/vscode-textmate": "^10.1.0", "oniguruma-to-es": "^4.3.6" } }, "sha512-K0oqxFoL+kEMdz89mHLFO15Tsbv3kFZ6WR1cXZKMvLSc+oqaM00A6pyga1qSeXB22dP0tTiSApRcGBaKWsEccg=="], + + "@shikijs/engine-oniguruma": ["@shikijs/engine-oniguruma@4.6.0", "", { "dependencies": { "@shikijs/types": "4.6.0", "@shikijs/vscode-textmate": "^10.1.0" } }, "sha512-aggd6Q7SuJOXNnsUbfG2XesxBJKBMAw/PDTUo9PyRjMaaJJ2dNrI+q0C+25ARXAK9yLHAlwxc9oRT2u68YKZ7w=="], + + "@shikijs/langs": ["@shikijs/langs@4.6.0", "", { "dependencies": { "@shikijs/types": "4.6.0" } }, "sha512-1yMEX3oCVV54LUq/ovfpRkDQoYDkcvjSWFFa/YLUDMiSoRzMi2uxLJYbv41ahT8Lu9lFMaa7hecd3Q39trqUyg=="], + + "@shikijs/primitive": ["@shikijs/primitive@4.6.0", "", { "dependencies": { "@shikijs/types": "4.6.0", "@shikijs/vscode-textmate": "^10.1.0", "@types/hast": "^3.0.5" } }, "sha512-c54+TQEo9ToqgfL/AU8FpjnV09+GA9Oa7M5ROkkXteZfp5XzpAJGXjjvZQFQioJOwm/w/6Z3lIzQstAkl8coag=="], + + "@shikijs/themes": ["@shikijs/themes@4.6.0", "", { "dependencies": { "@shikijs/types": "4.6.0" } }, "sha512-qHAVAs80RiGD+IRuH9G+JPDOEc9A/kHsng4EzCUCwB9bLzW6Z0y9WETh2YyCcADJBmfrIaJ1Jp7KBNP6FHkgtQ=="], + + "@shikijs/types": ["@shikijs/types@4.6.0", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.1.0", "@types/hast": "^3.0.5" } }, "sha512-+ENG1adsKt/X7cRYw1Nl7BEpBmPOjmQ7bR/eGmHuMlT8gtOFf3KEi5l31DJYyAWhW6Y6bjP1plU7FmaxWGENFw=="], + + "@shikijs/vscode-textmate": ["@shikijs/vscode-textmate@10.1.0", "", {}, "sha512-cVBuhDQjBZaNMTwBquYfPydrUP+E3hE6oYGasx8h6ZrODIM7/r+gxLDXdd66oszbrggZHEntdE6j+5gYIVyMWQ=="], - "@solidjs/compiler": ["@solidjs/compiler@2.0.0-rc.18", "", { "optionalDependencies": { "@solidjs/compiler-darwin-arm64": "2.0.0-rc.18", "@solidjs/compiler-darwin-x64": "2.0.0-rc.18", "@solidjs/compiler-linux-arm64-gnu": "2.0.0-rc.18", "@solidjs/compiler-linux-x64-gnu": "2.0.0-rc.18", "@solidjs/compiler-wasm32-wasi": "2.0.0-rc.18", "@solidjs/compiler-win32-x64-msvc": "2.0.0-rc.18" } }, "sha512-I9wQy6RQeOeDvbxDxco+hlDIK5UBxnVNdBEc2LnaC+bkSZwQX7S5ebAohPGhxfsEChLD++u9A8NBkFd9vSVM7A=="], + "@sindresorhus/is": ["@sindresorhus/is@4.6.0", "", {}, "sha512-t09vSN3MdfsyCHoFcTRCH/iUtG7OJ0CsjzB8cjAmKc/va/kIgeDI/TxsigdncE/4be734m0cvIYwNaV4i2XqAw=="], - "@solidjs/compiler-darwin-arm64": ["@solidjs/compiler-darwin-arm64@2.0.0-rc.18", "", { "os": "darwin", "cpu": "arm64" }, "sha512-QXbaI9bCW4WGd3s5ZJIzI8quMTaMaWryoq/u9PD42apGCX1Md3B/foFU7UiW7jq51YHaRWCkf1iQkd8Ee5GI7w=="], + "@solidjs/compiler": ["@solidjs/compiler@2.0.0", "", { "optionalDependencies": { "@solidjs/compiler-darwin-arm64": "2.0.0", "@solidjs/compiler-darwin-x64": "2.0.0", "@solidjs/compiler-linux-arm64-gnu": "2.0.0", "@solidjs/compiler-linux-x64-gnu": "2.0.0", "@solidjs/compiler-wasm32-wasi": "2.0.0", "@solidjs/compiler-win32-x64-msvc": "2.0.0" } }, "sha512-Spgqz1+eojQ2pDl4yajnajIjX/kSusjTK/6mC6Fm7sAZ3YBI0yP4/epRR1hV08TU3YAH4xLBmZ6wjb1zC134Sw=="], - "@solidjs/compiler-darwin-x64": ["@solidjs/compiler-darwin-x64@2.0.0-rc.18", "", { "os": "darwin", "cpu": "x64" }, "sha512-Y6x899jJWsnTwoQqqpWyjMp+/Dz35fPXUHQKrcQesbUajXWsljPY+dT6XLDMpEILrMSxyyBPQ9lmRTRE7nJLGQ=="], + "@solidjs/compiler-darwin-arm64": ["@solidjs/compiler-darwin-arm64@2.0.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-pPHERRXgCcsfCsaC8sgK94uVlp4WGUcHTfMeBiAfme2amQ7vFn7dpjSD3TIVKY4jeYQTKjIKOYP0c5mqIR1LeA=="], - "@solidjs/compiler-linux-arm64-gnu": ["@solidjs/compiler-linux-arm64-gnu@2.0.0-rc.18", "", { "os": "linux", "cpu": "arm64" }, "sha512-bs7rXGsC+1rVk5WadxOyaxdux8Mx2vjEUdX8UnhTQc37uCHBCI5mLuYICoFX9qXdINZK9H8VrkgT2WJxVN6ypQ=="], + "@solidjs/compiler-darwin-x64": ["@solidjs/compiler-darwin-x64@2.0.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-Ndwy+pQs8v6BIfaAbQ+weu9HGBTM40HFCyu0XV2qX7U5XC+o+3fc4O6+8ZZyUzl+qvT6XU+wh2bQ6MI2lV+KBQ=="], - "@solidjs/compiler-linux-x64-gnu": ["@solidjs/compiler-linux-x64-gnu@2.0.0-rc.18", "", { "os": "linux", "cpu": "x64" }, "sha512-91+hS2M3HJdZQ/b44XJnFhpSjO9JdmAefwIQPz+iBvbkafNW6yvVjkiCd+BKZ106tJ1HtHnbj2OSQwH7+cxhyw=="], + "@solidjs/compiler-linux-arm64-gnu": ["@solidjs/compiler-linux-arm64-gnu@2.0.0", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-H/R9SUmuqd4P/IuuXTlRM1LhgUWe2EjLP3iMUo+L4IO1rmOSqfMUZp9h52eQnDsOdoIZCaKsw+b0qC5WooxDlg=="], - "@solidjs/compiler-wasm32-wasi": ["@solidjs/compiler-wasm32-wasi@2.0.0-rc.18", "", { "dependencies": { "@emnapi/core": "1.11.3", "@emnapi/runtime": "1.11.3", "@napi-rs/wasm-runtime": "^1.1.6" } }, "sha512-5JuKtcdNjVUBgkz2lyTuVen4K7/3ASwaJg6vp7zbnsM2ZapcQXzlIhP3zee8FBBhGgvdgbf18L+u2B3H6T88DQ=="], + "@solidjs/compiler-linux-x64-gnu": ["@solidjs/compiler-linux-x64-gnu@2.0.0", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-gafr9+2bP2sv2hRAvDgzab0mpQi4MiyWrie9bfYjadsK7qZKJBeMzEQCLNd4dTYlgirCj6Frzu2pfET7+ZUyNQ=="], - "@solidjs/compiler-win32-x64-msvc": ["@solidjs/compiler-win32-x64-msvc@2.0.0-rc.18", "", { "os": "win32", "cpu": "x64" }, "sha512-DOfsflkkvZ4XRzcgKPTpthdtDB4syTr+8ci6ZZkcfexi2TaxiWROIP7heMFlBBYrSYINW8ct6eOjgkFUom4kqQ=="], + "@solidjs/compiler-wasm32-wasi": ["@solidjs/compiler-wasm32-wasi@2.0.0", "", { "dependencies": { "@emnapi/core": "1.11.3", "@emnapi/runtime": "1.11.3", "@napi-rs/wasm-runtime": "^1.1.6" } }, "sha512-JnF21DJ/jx5fghYKIB6ANihHMM4aWg4JFe5pFLGDvqSeURZJdJGjwyyxOv3siEMUdkBzVGHXotTsviTcRyB5hQ=="], - "@solidjs/signals": ["@solidjs/signals@2.0.0-rc.18", "", {}, "sha512-pzYahnM93EpDN4xZF1EefdjPE6Buuu/90/kiaLOjUFhPd3H0W6J9R8lIF+kkD1Z78LW1OTHciRY5MCqpYj5iSQ=="], + "@solidjs/compiler-win32-x64-msvc": ["@solidjs/compiler-win32-x64-msvc@2.0.0", "", { "os": "win32", "cpu": "x64" }, "sha512-RkiUXt/LmJ1lk1fECa/iDVGCOv3UiwW5ocZgkhpayUviTSrceFjFHhiM9sFXq0at3kHI7Z8awN6zTaF5IStDAQ=="], - "@solidjs/vite-plugin": ["@solidjs/vite-plugin@3.0.0-next.51", "", { "dependencies": { "@ampproject/remapping": "^2.3.0", "@babel/core": "^7.23.3", "@solidjs/babel-plugin": "^2.0.0-rc.16", "@solidjs/compiler": "^2.0.0-rc.16", "@types/babel__core": "^7.20.4", "merge-anything": "^5.1.7", "vitefu": "^1.0.4" }, "peerDependencies": { "@solidjs/start-devtools": "^1.0.0-next.2", "@solidjs/web": "^2.0.0-rc.16", "@testing-library/jest-dom": "^5.16.6 || ^5.17.0 || ^6.0.0 || ^7.0.0", "solid-js": "^2.0.0-rc.16", "vite": "^8.0.0 || ^9.0.0" }, "optionalPeers": ["@solidjs/start-devtools", "@testing-library/jest-dom"] }, "sha512-ffpFNYX1z3mGjr95nM3hwo0R3P489FjVnYP5YCOorw+N8grCo+Ay1hGx68H00n5OAC7uGd/7B4GsU1HnA/VU0A=="], + "@solidjs/signals": ["@solidjs/signals@2.0.0", "", {}, "sha512-jrcT6XTVvsYRpesRp0At/mSUnsWr6jiprK8C93Oat56B8n7X9BMSe58Rxl6qSZUhBN0L+sxm8GzeO7HdhBXvDw=="], - "@solidjs/web": ["@solidjs/web@2.0.0-rc.18", "", { "dependencies": { "seroval": "1.7.0", "seroval-plugins": "1.7.0" }, "peerDependencies": { "solid-js": "^2.0.0-rc.18" } }, "sha512-qtxuskii4N/gMipmg94yfPSJ0djwVWF+Elrdhtdb/8ZThvPc6RI/edY6guEMwdx7OADa1f9cQ0MwQe7kDW+Vwg=="], + "@solidjs/vite-plugin": ["@solidjs/vite-plugin@3.0.1", "", { "dependencies": { "@ampproject/remapping": "^2.3.0", "@solidjs/compiler": "^2.0.0", "magic-string": "^0.30.21", "merge-anything": "^5.1.7", "vitefu": "^1.0.4" }, "peerDependencies": { "@babel/core": "^7.23.3 || ^8.0.0", "@solidjs/babel-plugin": "^2.0.0", "@solidjs/start-devtools": "^1.0.0-next.2", "@solidjs/web": "^2.0.0", "@testing-library/jest-dom": "^5.16.6 || ^5.17.0 || ^6.0.0 || ^7.0.0", "solid-js": "^2.0.0", "vite": "^8.0.0 || ^9.0.0" }, "optionalPeers": ["@babel/core", "@solidjs/babel-plugin", "@solidjs/start-devtools", "@testing-library/jest-dom"] }, "sha512-dyRU4LJXhzEEgtF32AtUdjqaUuMVYTVLQvhYlT6HcYBvf10yIVmKgW9cg42b5YDxkl6BgAJ9o0OjUnAy3qKb9A=="], + + "@solidjs/web": ["@solidjs/web@2.0.0", "", { "dependencies": { "csstype": "^3.1.0", "seroval": "^1.8.0", "seroval-plugins": "^1.8.0" }, "peerDependencies": { "solid-js": "^2.0.0" } }, "sha512-R0+JMCD6ukEXaID/sH5PVQe9bCIN9pRzJry+F6Sb6YvtlkAp9DEyVI7AeZYiV0cd6TSL98kpbCyLDiZnaAKGrA=="], "@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="], @@ -707,18 +799,98 @@ "@types/bun": ["@types/bun@1.4.4", "", { "dependencies": { "bun-types": "1.4.4" } }, "sha512-9wkRDXUXK124pEnAutE6n/l18j+i9GC5IAHK8TmX/2nlySETmky0OU6yL5U8pW1AoKh++AN9auDCr647BfurjQ=="], + "@types/d3": ["@types/d3@7.4.3", "", { "dependencies": { "@types/d3-array": "*", "@types/d3-axis": "*", "@types/d3-brush": "*", "@types/d3-chord": "*", "@types/d3-color": "*", "@types/d3-contour": "*", "@types/d3-delaunay": "*", "@types/d3-dispatch": "*", "@types/d3-drag": "*", "@types/d3-dsv": "*", "@types/d3-ease": "*", "@types/d3-fetch": "*", "@types/d3-force": "*", "@types/d3-format": "*", "@types/d3-geo": "*", "@types/d3-hierarchy": "*", "@types/d3-interpolate": "*", "@types/d3-path": "*", "@types/d3-polygon": "*", "@types/d3-quadtree": "*", "@types/d3-random": "*", "@types/d3-scale": "*", "@types/d3-scale-chromatic": "*", "@types/d3-selection": "*", "@types/d3-shape": "*", "@types/d3-time": "*", "@types/d3-time-format": "*", "@types/d3-timer": "*", "@types/d3-transition": "*", "@types/d3-zoom": "*" } }, "sha512-lZXZ9ckh5R8uiFVt8ogUNf+pIrK4EsWrx2Np75WvF/eTpJ0FMHNhjXk8CKEx/+gpHbNQyJWehbFaTvqmHWB3ww=="], + + "@types/d3-array": ["@types/d3-array@3.2.2", "", {}, "sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw=="], + + "@types/d3-axis": ["@types/d3-axis@3.0.6", "", { "dependencies": { "@types/d3-selection": "*" } }, "sha512-pYeijfZuBd87T0hGn0FO1vQ/cgLk6E1ALJjfkC0oJ8cbwkZl3TpgS8bVBLZN+2jjGgg38epgxb2zmoGtSfvgMw=="], + + "@types/d3-brush": ["@types/d3-brush@3.0.6", "", { "dependencies": { "@types/d3-selection": "*" } }, "sha512-nH60IZNNxEcrh6L1ZSMNA28rj27ut/2ZmI3r96Zd+1jrZD++zD3LsMIjWlvg4AYrHn/Pqz4CF3veCxGjtbqt7A=="], + + "@types/d3-chord": ["@types/d3-chord@3.0.6", "", {}, "sha512-LFYWWd8nwfwEmTZG9PfQxd17HbNPksHBiJHaKuY1XeqscXacsS2tyoo6OdRsjf+NQYeB6XrNL3a25E3gH69lcg=="], + + "@types/d3-color": ["@types/d3-color@3.1.3", "", {}, "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A=="], + + "@types/d3-contour": ["@types/d3-contour@3.0.6", "", { "dependencies": { "@types/d3-array": "*", "@types/geojson": "*" } }, "sha512-BjzLgXGnCWjUSYGfH1cpdo41/hgdWETu4YxpezoztawmqsvCeep+8QGfiY6YbDvfgHz/DkjeIkkZVJavB4a3rg=="], + + "@types/d3-delaunay": ["@types/d3-delaunay@6.0.4", "", {}, "sha512-ZMaSKu4THYCU6sV64Lhg6qjf1orxBthaC161plr5KuPHo3CNm8DTHiLw/5Eq2b6TsNP0W0iJrUOFscY6Q450Hw=="], + + "@types/d3-dispatch": ["@types/d3-dispatch@3.0.7", "", {}, "sha512-5o9OIAdKkhN1QItV2oqaE5KMIiXAvDWBDPrD85e58Qlz1c1kI/J0NcqbEG88CoTwJrYe7ntUCVfeUl2UJKbWgA=="], + + "@types/d3-drag": ["@types/d3-drag@3.0.7", "", { "dependencies": { "@types/d3-selection": "*" } }, "sha512-HE3jVKlzU9AaMazNufooRJ5ZpWmLIoc90A37WU2JMmeq28w1FQqCZswHZ3xR+SuxYftzHq6WU6KJHvqxKzTxxQ=="], + + "@types/d3-dsv": ["@types/d3-dsv@3.0.7", "", {}, "sha512-n6QBF9/+XASqcKK6waudgL0pf/S5XHPPI8APyMLLUHd8NqouBGLsU8MgtO7NINGtPBtk9Kko/W4ea0oAspwh9g=="], + + "@types/d3-ease": ["@types/d3-ease@3.0.2", "", {}, "sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA=="], + + "@types/d3-fetch": ["@types/d3-fetch@3.0.7", "", { "dependencies": { "@types/d3-dsv": "*" } }, "sha512-fTAfNmxSb9SOWNB9IoG5c8Hg6R+AzUHDRlsXsDZsNp6sxAEOP0tkP3gKkNSO/qmHPoBFTxNrjDprVHDQDvo5aA=="], + + "@types/d3-force": ["@types/d3-force@3.0.10", "", {}, "sha512-ZYeSaCF3p73RdOKcjj+swRlZfnYpK1EbaDiYICEEp5Q6sUiqFaFQ9qgoshp5CzIyyb/yD09kD9o2zEltCexlgw=="], + + "@types/d3-format": ["@types/d3-format@3.0.4", "", {}, "sha512-fALi2aI6shfg7vM5KiR1wNJnZ7r6UuggVqtDA+xiEdPZQwy/trcQaHnwShLuLdta2rTymCNpxYTiMZX/e09F4g=="], + + "@types/d3-geo": ["@types/d3-geo@3.1.1", "", { "dependencies": { "@types/geojson": "*" } }, "sha512-65Emv9fQiQQqphLlRkuQ5ypPsOmWPhtBGCMv61JDPEPMvsx+gzhGf74yw1a78xFKPj6zw4AgQICJoQv0vK9M2w=="], + + "@types/d3-hierarchy": ["@types/d3-hierarchy@3.1.7", "", {}, "sha512-tJFtNoYBtRtkNysX1Xq4sxtjK8YgoWUNpIiUee0/jHGRwqvzYxkq0hGVbbOGSz+JgFxxRu4K8nb3YpG3CMARtg=="], + + "@types/d3-interpolate": ["@types/d3-interpolate@3.0.4", "", { "dependencies": { "@types/d3-color": "*" } }, "sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA=="], + + "@types/d3-path": ["@types/d3-path@3.1.1", "", {}, "sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg=="], + + "@types/d3-polygon": ["@types/d3-polygon@3.0.2", "", {}, "sha512-ZuWOtMaHCkN9xoeEMr1ubW2nGWsp4nIql+OPQRstu4ypeZ+zk3YKqQT0CXVe/PYqrKpZAi+J9mTs05TKwjXSRA=="], + + "@types/d3-quadtree": ["@types/d3-quadtree@3.0.6", "", {}, "sha512-oUzyO1/Zm6rsxKRHA1vH0NEDG58HrT5icx/azi9MF1TWdtttWl0UIUsjEQBBh+SIkrpd21ZjEv7ptxWys1ncsg=="], + + "@types/d3-random": ["@types/d3-random@3.0.4", "", {}, "sha512-UHYId5WTCx4L4YNel7NU00XUXXgvgpgZOvp10PuvsQENjMDXhh2RyFc0KBjO7B45ne4Ha1yVH7ii0vnzKkuzWA=="], + + "@types/d3-scale": ["@types/d3-scale@4.0.9", "", { "dependencies": { "@types/d3-time": "*" } }, "sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw=="], + + "@types/d3-scale-chromatic": ["@types/d3-scale-chromatic@3.1.0", "", {}, "sha512-iWMJgwkK7yTRmWqRB5plb1kadXyQ5Sj8V/zYlFGMUBbIPKQScw+Dku9cAAMgJG+z5GYDoMjWGLVOvjghDEFnKQ=="], + + "@types/d3-selection": ["@types/d3-selection@3.0.12", "", {}, "sha512-Qe/KWYhEiIIxGs7HrAAjMfShxKldx19SJtr5zu53f3afPsdZNz7HHtdTLXo/kqeiWNXVycI24kSnfzBYkTzpgw=="], + + "@types/d3-shape": ["@types/d3-shape@3.2.0", "", { "dependencies": { "@types/d3-path": "*" } }, "sha512-kVd74ta9eof3eJOvbNd1vGKS/XERRyQbT26Og63hIsvDO84cjD5gEOhsXf26w3FSoNlPVz84DOFcKv/oou+fMw=="], + + "@types/d3-time": ["@types/d3-time@3.0.4", "", {}, "sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g=="], + + "@types/d3-time-format": ["@types/d3-time-format@4.0.3", "", {}, "sha512-5xg9rC+wWL8kdDj153qZcsJ0FWiFt0J5RB6LYUNZjwSnesfblqrI/bJ1wBdJ8OQfncgbJG5+2F+qfqnqyzYxyg=="], + + "@types/d3-timer": ["@types/d3-timer@3.0.2", "", {}, "sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw=="], + + "@types/d3-transition": ["@types/d3-transition@3.0.9", "", { "dependencies": { "@types/d3-selection": "*" } }, "sha512-uZS5shfxzO3rGlu0cC3bjmMFKsXv+SmZZcgp0KD22ts4uGXp5EVYGzu/0YdwZeKmddhcAccYtREJKkPfXkZuCg=="], + + "@types/d3-zoom": ["@types/d3-zoom@3.0.9", "", { "dependencies": { "@types/d3-interpolate": "*", "@types/d3-selection": "*" } }, "sha512-0sE1406XBYJGiqD3AusTl9ZqC//2mIXix51tbom25gDCA8ri4xnSZg28CaSE8Srl6FClqABUKfsn0qghgdepMA=="], + + "@types/debug": ["@types/debug@4.1.13", "", { "dependencies": { "@types/ms": "*" } }, "sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw=="], + "@types/estree": ["@types/estree@1.0.10", "", {}, "sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g=="], + "@types/estree-jsx": ["@types/estree-jsx@1.0.5", "", { "dependencies": { "@types/estree": "*" } }, "sha512-52CcUVNFyfb1A2ALocQw/Dd1BQFNmSdkuC3BkZ6iqhdMfQz7JWOFRuJFloOzjk+6WijU56m9oKXFAXc7o3Towg=="], + "@types/gensync": ["@types/gensync@1.0.5", "", {}, "sha512-MbsRCT7mTikHwKZ0X+LVUTLRrZZRLipTuXEO9qOYO+zmjMVk81axyClMROf6uoPD9MRVu46bx8zoR0Ad9q3NAg=="], + "@types/geojson": ["@types/geojson@7946.0.16", "", {}, "sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg=="], + + "@types/hast": ["@types/hast@3.0.5", "", { "dependencies": { "@types/unist": "*" } }, "sha512-rp/ezSWaD1m44dPKICGhiskI13nVr7qTloFwDa/IYkhhf5nzwP+zIQcIJh3WIFSBOy/H1PzB40jPjMDksN4F+g=="], + "@types/jsesc": ["@types/jsesc@2.5.1", "", {}, "sha512-9VN+6yxLOPLOav+7PwjZbxiID2bVaeq0ED4qSQmdQTdjnXJSaCVKTR58t15oqH1H5t8Ng2ZX1SabJVoN9Q34bw=="], + "@types/mdast": ["@types/mdast@4.0.4", "", { "dependencies": { "@types/unist": "*" } }, "sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA=="], + + "@types/mdx": ["@types/mdx@2.0.14", "", {}, "sha512-T48PeuJtvLosNTPVhfnIp3i/n3a4g4Bad7YCq5k64D4u7NwDrAotikQ+5+sjtUvBmxCMlbo3dVL+C2dP0rWHzg=="], + + "@types/ms": ["@types/ms@2.1.0", "", {}, "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA=="], + "@types/node": ["@types/node@26.6.6", "", { "dependencies": { "undici-types": "~8.9.0" } }, "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog=="], "@types/react": ["@types/react@19.3.0", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg=="], "@types/react-dom": ["@types/react-dom@19.3.0", "", { "peerDependencies": { "@types/react": "^19.3.0" } }, "sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q=="], + "@types/trusted-types": ["@types/trusted-types@2.0.7", "", {}, "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw=="], + + "@types/unist": ["@types/unist@3.0.3", "", {}, "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q=="], + "@types/whatwg-mimetype": ["@types/whatwg-mimetype@3.0.2", "", {}, "sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA=="], "@types/ws": ["@types/ws@8.18.1", "", { "dependencies": { "@types/node": "*" } }, "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg=="], @@ -763,6 +935,10 @@ "@typescript/typescript-win32-x64": ["@typescript/typescript-win32-x64@7.0.2", "", { "os": "win32", "cpu": "x64" }, "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g=="], + "@ungap/structured-clone": ["@ungap/structured-clone@1.4.0", "", {}, "sha512-1mEZtMKPM09vDmQt5y7YvmN2+DFTP7Tg0EWXdic8/C6VRnpb33e4ghisCIE3WZjsE2N8mf+QV1Zqh7ZFYLWInQ=="], + + "@upsetjs/venn.js": ["@upsetjs/venn.js@2.0.0", "", { "optionalDependencies": { "d3-selection": "^3.0.0", "d3-transition": "^3.0.1" } }, "sha512-WbBhLrooyePuQ1VZxrJjtLvTc4NVfpOyKx0sKqioq9bX1C1m7Jgykkn8gLrtwumBioXIqam8DLxp88Adbue6Hw=="], + "@vitejs/plugin-basic-ssl": ["@vitejs/plugin-basic-ssl@2.3.0", "", { "peerDependencies": { "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" } }, "sha512-bdyo8rB3NnQbikdMpHaML9Z1OZPBu6fFOBo+OtxsBlvMJtysWskmBcnbIDhUqgC8tcxNv/a+BcV5U+2nQMm1OQ=="], "@vitejs/plugin-vue": ["@vitejs/plugin-vue@6.0.11", "", { "dependencies": { "@rolldown/pluginutils": "^1.0.1" }, "peerDependencies": { "vite": "^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0", "vue": "^3.2.25 || ^3.6.0-rc.15" } }, "sha512-m48lskIUJGlB6qUiYhDMI8nd2ngeidz2U4nKTjqI13cFMu5rH8JeEILPkDtK9Fk/TjBA2pkj8AlbenqDaKu+ww=="], @@ -795,6 +971,30 @@ "@vue/shared": ["@vue/shared@3.5.45", "", {}, "sha512-ue9fgHmVNPlP7iW3+cxoBX/Cnlw53dHlVSw0JKGY6z1lObg8pHoj928M2nzG4/yVsMZ3NaRZ2s2z61uC16NDwQ=="], + "@yuku-core/binding-android-arm64": ["@yuku-core/binding-android-arm64@0.19.0", "", { "os": "android", "cpu": "arm64" }, "sha512-wdL2XmTiZixAOaHk9Z0JJZ8u9Qm8d333Zjpc6gaxXFX+UR5BlsfxZ7a2+2Rm71pamppsPYGUGFq2oVLbh6DISw=="], + + "@yuku-core/binding-darwin-arm64": ["@yuku-core/binding-darwin-arm64@0.19.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-7sNJa6XJhyetnTy64jw3NEi4YgUcezHk1G5GH9FSvXAuC8wIlbaOwT9lgq5qo5sspjrZJQlBR1TWflP49uRpMw=="], + + "@yuku-core/binding-darwin-x64": ["@yuku-core/binding-darwin-x64@0.19.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-pTC7dYEc59isdyizc3nsuyFNBu2LU5wMYZ1be6UMr59PY/AJNtO1aBLWV0MgL/z7C1nv/2sX4TNjGgKLoeevJw=="], + + "@yuku-core/binding-freebsd-x64": ["@yuku-core/binding-freebsd-x64@0.19.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-xrZjF6XOEwyLOiDIfrwDdRCS6ghxcJeirNC1KivQhVcUwlRonaU79S3/Uiyx3lBylPnT8qKJ3/aMT+H52nGTJQ=="], + + "@yuku-core/binding-linux-arm-gnu": ["@yuku-core/binding-linux-arm-gnu@0.19.0", "", { "os": "linux", "cpu": "arm", "libc": "glibc" }, "sha512-0OyIH53C0I1CbADHn9FSdCfX5qbpeLwJhmOVhonFJNYheybOnkSJ50qGMfTJIb8y5zrwqvLs7FVBvz6Fk8maZg=="], + + "@yuku-core/binding-linux-arm-musl": ["@yuku-core/binding-linux-arm-musl@0.19.0", "", { "os": "linux", "cpu": "arm", "libc": "musl" }, "sha512-z/iPfkCOCSXE34VXNt0uP1ORSW+4mEa9b5CiJcWZeqZH08g49bFU/jRM2T04f+Wpw5mJ6HIzNBiojxeAbrHjeg=="], + + "@yuku-core/binding-linux-arm64-gnu": ["@yuku-core/binding-linux-arm64-gnu@0.19.0", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-jLNTi+gzaRwBJ+gwhCJ+rDb5dmx/8hEBx93UWd7hjMSqPTL1D1wvVSvXVAldV5kALvju7b0/m51EHEhs4+I1fA=="], + + "@yuku-core/binding-linux-arm64-musl": ["@yuku-core/binding-linux-arm64-musl@0.19.0", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-YwyPIdW/rN2Fmv0MTFWi47FaB3F9g+2b+sJISyAw83Yd60RWH4T3Nx6XkAHHVN+uKJNBAd6So7/BVihSiFYvuQ=="], + + "@yuku-core/binding-linux-x64-gnu": ["@yuku-core/binding-linux-x64-gnu@0.19.0", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-/vskaAXVX3ESR43FiTdfiYS7z1b9uoQJwVQ/0RgUHgN2sWoAyCZs+aX4CgU7eKGIHTVfp9VFwv+c+2XchYiEtQ=="], + + "@yuku-core/binding-linux-x64-musl": ["@yuku-core/binding-linux-x64-musl@0.19.0", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-FuXL5igeSKib9Rye02TdH+D6SQezTyGxIATMu1Qsn/QywrzwpGl35OLpS2C1x5vpGLeVE2XgiLd5mVPFHmIglQ=="], + + "@yuku-core/binding-win32-arm64": ["@yuku-core/binding-win32-arm64@0.19.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-YuJAe7zEKT1Xa7LuHlhGJpPnYQeVtvo0rZvNjJRqkH0hQGOw4C8QeP30Tg5VKGzZfo2x8CjhjEhKt4TmLwfmdg=="], + + "@yuku-core/binding-win32-x64": ["@yuku-core/binding-win32-x64@0.19.0", "", { "os": "win32", "cpu": "x64" }, "sha512-o8iY/mXwlRkedp0LNTr4+TEfXTPQwoNZmv6k+1WIAd1ZXEn8xJJTBCtB0osaVvdZo/x/cNmV16UrWrrGpM5Mvw=="], + "@yuku-toolchain/darwin-arm64": ["@yuku-toolchain/darwin-arm64@0.28.1", "", { "os": "darwin", "cpu": "arm64" }, "sha512-xMtZUwiGvJH90ogLjRrnG5+YEhinKti8qMPF18bd5z0ahSoaHWyBoe16evT7cSUxid0JEaZvh6H3daDPwDw4+g=="], "@yuku-toolchain/darwin-x64": ["@yuku-toolchain/darwin-x64@0.28.1", "", { "os": "darwin", "cpu": "x64" }, "sha512-aI60ScUkZgVEX5GHZfpiAAfTb9e7L6NUxfSU7Ucn+34GyrtswvBapEntbYKPzUuy5ubtVcD9vSWgptm/mlyTxQ=="], @@ -803,27 +1003,39 @@ "@yuku-toolchain/linux-x64": ["@yuku-toolchain/linux-x64@0.28.1", "", { "os": "linux", "cpu": "x64" }, "sha512-lEWh0UkCr195bQj4DNlpww/B7hPeuotE0hpKbC2oz4STHqYxCEoaMzNOf9vr5Ydjwr9egEDepA0XRsu5xP+z8w=="], + "@yuku-toolchain/types": ["@yuku-toolchain/types@0.19.0", "", {}, "sha512-tFkNbsP4WXX9UMUC5syJGdK9dPMLK0PPaIuXCcCYH75sZ8MrebfBZ2XvCILRTw8AgLivSSCfDa4R67iYBDa4Kg=="], + "@yuku-toolchain/win32-arm64": ["@yuku-toolchain/win32-arm64@0.28.1", "", { "os": "win32", "cpu": "arm64" }, "sha512-CUiumoJIwNiH9Utm5SbG5GaEaJRUatEXgG5HcPj2yEWh4kxTmEbigB346C3HEmtc+zbRLY0T0XsFO5RGSZaj2A=="], "@yuku-toolchain/win32-x64": ["@yuku-toolchain/win32-x64@0.28.1", "", { "os": "win32", "cpu": "x64" }, "sha512-CSTUi/ya58q2PuWTpk//BNSpXgOz7ol45T+SDuU7QfD/vN1FcLjSh99KDQzLf4AbIy43ORUw5UFehhfMGPNj9w=="], + "@zeit/schemas": ["@zeit/schemas@2.36.0", "", {}, "sha512-7kjMwcChYEzMKjeex9ZFXkt1AyNov9R5HZtjBKVsmVpw7pa7ZtlCGvCBC2vnnXctaYN+aRI61HjIqeetZW5ROg=="], + "acorn": ["acorn@8.19.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw=="], + "acorn-jsx": ["acorn-jsx@5.3.2", "", { "peerDependencies": { "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" } }, "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ=="], + "agent-base": ["agent-base@9.0.0", "", {}, "sha512-TQf59BsZnytt8GdJKLPfUZ54g/iaUL2OWDSFCCvMOhsHduDQxO8xC4PNeyIkVcA5KwL2phPSv0douC0fgWzmnA=="], - "ajv": ["ajv@8.20.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="], + "ajv": ["ajv@8.18.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A=="], "ajv-formats": ["ajv-formats@3.0.1", "", { "dependencies": { "ajv": "^8.0.0" } }, "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ=="], "alien-signals": ["alien-signals@3.2.1", "", {}, "sha512-I8FjmltrfnDFoZedi5CG8DghVYNhzb/Ijluz7tCSJH0xpd0484Kowhbb1XDYOxfJpU1p5wnM2X54dA+IfGyD1g=="], + "ansi-align": ["ansi-align@3.0.1", "", { "dependencies": { "string-width": "^4.1.0" } }, "sha512-IOfwwBF5iczOjp/WeY4YxyjqAFMQoZufdQWDd19SEExbVLNXqvpzSJ/M7Za4/sCPmQ0+GRquoA7bGcINcxew6w=="], + "ansi-colors": ["ansi-colors@4.1.3", "", {}, "sha512-/6w/C21Pm1A7aZitlI5Ni/2J6FFQN8i1Cvz3kHABAAbw93v/NlvKdVOqz7CCWz/3iv/JplRSEEZ83XION15ovw=="], "ansi-escapes": ["ansi-escapes@7.3.0", "", { "dependencies": { "environment": "^1.0.0" } }, "sha512-BvU8nYgGQBxcmMuEeUEmNTvrMVjJNSH7RgW24vXexN4Ven6qCvy4TntnvlnwnMLTVlcRQQdbRY8NKnaIoeWDNg=="], - "ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="], + "ansi-regex": ["ansi-regex@6.6.0", "", {}, "sha512-XZ5apbzreCbXSKwPjJstu8R0zOi247w3XYwWxtwBXgpZrCyc1Ka7p9/xY0A9/diMewmHbEKz+FIraWaEWjlN5g=="], + + "ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="], - "ansi-styles": ["ansi-styles@6.2.3", "", {}, "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg=="], + "any-promise": ["any-promise@1.3.0", "", {}, "sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A=="], + + "arg": ["arg@5.0.2", "", {}, "sha512-PYjyFOLKQ9y57JvQ6QLo8dAgNqswh8M1RMJYdQduT6xbWSgK36P/Z/v+p888pM69jMMfS8Xd8F6I1kQ/I9HUGg=="], "argparse": ["argparse@2.0.1", "", {}, "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q=="], @@ -831,10 +1043,16 @@ "array-union": ["array-union@2.1.0", "", {}, "sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw=="], + "astring": ["astring@1.9.0", "", { "bin": { "astring": "bin/astring" } }, "sha512-LElXdjswlqjWrPpJFg1Fx4wpkOCxj1TDHlSV4PlaRxHGWko024xICaa97ZkMfs6DRKlCguiAI+rbXv5GWwXIkg=="], + "axobject-query": ["axobject-query@4.1.0", "", {}, "sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ=="], "babel-plugin-react-compiler": ["babel-plugin-react-compiler@1.0.0", "", { "dependencies": { "@babel/types": "^7.26.0" } }, "sha512-Ixm8tFfoKKIPYdCCKYTsqv+Fd4IJ0DQqMyEimo+pxUOMUR9cVPlwTrFt9Avu+3cb6Zp3mAzl+t1MrG2fxxKsxw=="], + "bail": ["bail@2.0.2", "", {}, "sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw=="], + + "balanced-match": ["balanced-match@1.0.2", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="], + "baseline-browser-mapping": ["baseline-browser-mapping@2.10.25", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-QO/VHsXCQdnzADMfmkeOPvHdIAkoB7i0/rGjINPJEetLx75hNttVWGQ/jycHUDP9zZ9rupbm60WRxcwViB0MiA=="], "beasties": ["beasties@0.5.4", "", { "dependencies": { "css-select": "^7.0.0", "css-what": "^8.0.0", "dom-serializer": "^3.0.0", "domhandler": "^6.0.0", "htmlparser2": "^12.0.0", "picocolors": "^1.1.1", "postcss": "^8.4.49", "postcss-media-query-parser": "^0.2.3", "postcss-safe-parser": "^7.0.1" } }, "sha512-8/lOOjT+PElYCnaUbmhgd3Uad5R1VTQ4Wg0k4rK8bX04m5WEqHNmnlLy3Q/lJ7dk25XA+72gayzc/skTfKKpcA=="], @@ -843,6 +1061,10 @@ "boolbase": ["boolbase@2.0.0", "", {}, "sha512-DkVaaQHymRhpYEYo9x1oo7Q7B0Y6KJUsjm3c9eTyFDby4MHLBTwZ6ZDWBel5zrYxj1WsZgC5oLpiz+93MluXeA=="], + "boxen": ["boxen@7.0.0", "", { "dependencies": { "ansi-align": "^3.0.1", "camelcase": "^7.0.0", "chalk": "^5.0.1", "cli-boxes": "^3.0.0", "string-width": "^5.1.2", "type-fest": "^2.13.0", "widest-line": "^4.0.1", "wrap-ansi": "^8.0.1" } }, "sha512-j//dBVuyacJbvW+tvZ9HuH03fZ46QcaKvvhZickZqtB271DxJ7SNRSNxrV/dZX0085m7hISRZWbzWlJvx/rHSg=="], + + "brace-expansion": ["brace-expansion@1.1.22", "", { "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, "sha512-CKLDTuSsN0+r1ThM0WkzzBI7dnPI6xEGfa/JnVYIK9JNBA1N1NyPwXVHor//NKD/y3sDxp764sZdLhFK7pH8XQ=="], + "braces": ["braces@3.0.3", "", { "dependencies": { "fill-range": "^7.1.1" } }, "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA=="], "browserslist": ["browserslist@4.28.2", "", { "dependencies": { "baseline-browser-mapping": "^2.10.12", "caniuse-lite": "^1.0.30001782", "electron-to-chromium": "^1.5.328", "node-releases": "^2.0.36", "update-browserslist-db": "^1.2.3" }, "bin": { "browserslist": "cli.js" } }, "sha512-48xSriZYYg+8qXna9kwqjIVzuQxi+KYWp2+5nCYnYKPTr0LvD89Jqk2Or5ogxz0NUMfIjhh2lIUX/LyX9B4oIg=="], @@ -853,20 +1075,46 @@ "bun-types": ["bun-types@1.4.4", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-yjrJh5oGX7mMPKGd19YXyIjmEuj4G4zNC30bs7PM9Az7NQ3ndF3j6hbeRdvJTRQEhJ/FYQwW0a2moweEi2hMxQ=="], + "bytes": ["bytes@3.1.2", "", {}, "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg=="], + "cac": ["cac@7.1.0", "", {}, "sha512-LMDU/U2yA4IPIY8KT0NsNPWEYZvAMkbgyspxJ6btJaYV+WMDOHAZCmB0lsTObiHaRS1V/ztKAl7+TSkTqXyeoA=="], + "camelcase": ["camelcase@7.0.1", "", {}, "sha512-xlx1yCK2Oc1APsPXDL2LdlNP6+uu8OCDdhOBSVT279M/S+y75O30C2VuD8T2ogdePBBl7PfPF4504tnLgX3zfw=="], + "caniuse-lite": ["caniuse-lite@1.0.30001791", "", {}, "sha512-yk0l/YSrOnFZk3UROpDLQD9+kC1l4meK/wed583AXrzoarMGJcbRi2Q4RaUYbKxYAsZ8sWmaSa/DsLmdBeI1vQ=="], - "chalk": ["chalk@5.6.2", "", {}, "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA=="], + "ccount": ["ccount@2.0.1", "", {}, "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg=="], + + "chalk": ["chalk@4.1.2", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="], + + "chalk-template": ["chalk-template@0.4.0", "", { "dependencies": { "chalk": "^4.1.2" } }, "sha512-/ghrgmhfY8RaSdeo43hNXxpoHAtxdbskUHjPpfqUWGttFgycUhYPGx3YZBCnUCvOa7Doivn1IZec3DEGFoMgLg=="], + + "char-regex": ["char-regex@1.0.2", "", {}, "sha512-kWWXztvZ5SBQV+eRgKFeh8q5sLuZY2+8WUIzlxWVTg+oGwY14qylx1KbKzHd8P6ZYkAg0xyIDU9JMHhyJMZ1jw=="], + + "character-entities": ["character-entities@2.0.2", "", {}, "sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ=="], + + "character-entities-html4": ["character-entities-html4@2.1.0", "", {}, "sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA=="], + + "character-entities-legacy": ["character-entities-legacy@3.0.0", "", {}, "sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ=="], + + "character-reference-invalid": ["character-reference-invalid@2.0.1", "", {}, "sha512-iBZ4F4wRbyORVsu0jPV7gXkOsGYjGHPmAyv+HiHG8gi5PtC9KI2j1+v8/tlibRvjoWX027ypmG/n0HtO5t7unw=="], "chardet": ["chardet@2.1.1", "", {}, "sha512-PsezH1rqdV9VvyNhxxOW32/d75r01NY7TQCmOqomRo15ZSOKbpTFVsfjghxo6JloQUCGnH4k1LGu0R4yCLlWQQ=="], + "chevrotain": ["chevrotain@13.2.0", "", { "dependencies": { "@chevrotain/cst-dts-gen": "13.2.0", "@chevrotain/gast": "13.2.0", "@chevrotain/regexp-to-ast": "13.2.0", "@chevrotain/types": "13.2.0", "@chevrotain/utils": "13.2.0" } }, "sha512-GTouk5YzgBxlTPCaDn5q0q2EJKkrYmnPF+HmF8v0Qo4r3iyPG7HJivkN1wthCXZcm3sIcZFpGTRovLPNdJNRCA=="], + "chokidar": ["chokidar@5.0.0", "", { "dependencies": { "readdirp": "^5.0.0" } }, "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw=="], "ci-info": ["ci-info@3.9.0", "", {}, "sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ=="], + "cjs-module-lexer": ["cjs-module-lexer@1.4.3", "", {}, "sha512-9z8TZaGM1pfswYeXrUpzPrkx8UnWYdhJclsiYMm6x/w5+nN+8Tf/LnAgfLGQCm59qAOxU8WwHEq2vNwF6i4j+Q=="], + + "class-variance-authority": ["class-variance-authority@0.7.1", "", { "dependencies": { "clsx": "^2.1.1" } }, "sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg=="], + "classy-store-angular-example": ["classy-store-angular-example@workspace:examples/angular"], + "classy-store-docs": ["classy-store-docs@workspace:website"], + "classy-store-nextjs-example": ["classy-store-nextjs-example@workspace:examples/nextjs"], "classy-store-solid-example": ["classy-store-solid-example@workspace:examples/solid"], @@ -875,10 +1123,16 @@ "classy-store-vue-example": ["classy-store-vue-example@workspace:examples/vue"], + "cli-boxes": ["cli-boxes@3.0.0", "", {}, "sha512-/lzGpEWL/8PfI0BmBOPRwp0c/wFNX1RdUML3jK/RcSBA9T8mZDdQpqYBKtCFTOfQbwPqWEOpjqW+Fnayc0969g=="], + "cli-cursor": ["cli-cursor@5.0.0", "", { "dependencies": { "restore-cursor": "^5.0.0" } }, "sha512-aCj4O5wKyszjMmDT4tZj93kxyydN/K5zPWSCe6/0AV/AA1pqe5ZBIw0a2ZfPQV7lL5/yb5HsUreJ6UFAF1tEQw=="], + "cli-highlight": ["cli-highlight@2.1.11", "", { "dependencies": { "chalk": "^4.0.0", "highlight.js": "^10.7.1", "mz": "^2.4.0", "parse5": "^5.1.1", "parse5-htmlparser2-tree-adapter": "^6.0.0", "yargs": "^16.0.0" }, "bin": { "highlight": "bin/highlight" } }, "sha512-9KDcoEVwyUXrjcJNvHD0NFc/hiwe/WPVYIleQh2O1N2Zro5gWJZ/K+3DGn8w8P/F6FxOgzyC5bxDyHIgCSPhGg=="], + "cli-spinners": ["cli-spinners@3.4.0", "", {}, "sha512-bXfOC4QcT1tKXGorxL3wbJm6XJPDqEnij2gQ2m7ESQuE+/z9YFIWnl/5RpTiKWbMq3EVKR4fRLJGn6DVfu0mpw=="], + "cli-table3": ["cli-table3@0.6.5", "", { "dependencies": { "string-width": "^4.2.0" }, "optionalDependencies": { "@colors/colors": "1.5.0" } }, "sha512-+W/5efTR7y5HRD7gACw9yQjqMVvEMLBHmboM/kPWam+H+Hmyrgjh6YncVKK122YZkXrLudzTuAukUw9FnMf7IQ=="], + "cli-truncate": ["cli-truncate@6.1.1", "", { "dependencies": { "slice-ansi": "^9.0.0", "string-width": "^8.2.0" } }, "sha512-06p9vyLahLa4zkGcgsGxU6iEkSOiuI4fhCH6Emhe2lPAcoUv73n72DnODsnHA+5wwXGnV0n9M9/qOQJSjYhFhw=="], "cli-width": ["cli-width@4.1.0", "", {}, "sha512-ouuZd4/dm2Sw5Gmqy6bGyNNNe1qt9RpmxveLSO7KcgsTnU7RXfsw+/bukWGo1abgBiMAic068rclZsO4IWmmxQ=="], @@ -889,10 +1143,34 @@ "clsx": ["clsx@2.1.1", "", {}, "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA=="], + "cn": ["cn@0.5.2", "", { "bin": { "cn": "bin/cn.mjs" } }, "sha512-wm10E6iuJ37rALOw3D+3cfaXXZSLNMh2uxpQn3dNICqfJM59yXqgbA9/9Iiz155j5kYNLdK6WreNdW3NQtx3OQ=="], + + "collapse-white-space": ["collapse-white-space@2.1.0", "", {}, "sha512-loKTxY1zCOuG4j9f6EPnuyyYkf58RnhhWTvRoZEokgB+WbdXehfjFviyOVYkqzEWz1Q5kRiZdBYS5SwxbQYwzw=="], + + "color-convert": ["color-convert@2.0.1", "", { "dependencies": { "color-name": "~1.1.4" } }, "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ=="], + + "color-name": ["color-name@1.1.4", "", {}, "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="], + "colorjs.io": ["colorjs.io@0.7.1", "", {}, "sha512-LY7OHnJZxHwT5UlzNa9bbhHHDbzB6yE5+3MIPwJEQKRvSCt/T4G7epsj+9j2BExUIIfXFIJGsIXUKdfrK9Q5tA=="], + "comma-separated-tokens": ["comma-separated-tokens@2.0.3", "", {}, "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg=="], + + "commander": ["commander@10.0.1", "", {}, "sha512-y4Mg2tXshplEbSGzx7amzPwKKOCGuoSRP/CjEdwwk0FOGlUbq6lKuoyDZTNZkmxHdJtp54hdfY/JUrdL7Xfdug=="], + + "compressible": ["compressible@2.0.18", "", { "dependencies": { "mime-db": ">= 1.43.0 < 2" } }, "sha512-AF3r7P5dWxL8MxyITRMlORQNaOA2IkAFaTr4k7BUumjPtRpGDTZpl0Pb1XCO6JeDCBdp126Cgs9sMxqSjgYyRg=="], + + "compression": ["compression@1.8.2", "", { "dependencies": { "bytes": "3.1.2", "compressible": "~2.0.18", "debug": "2.6.9", "destroy": "1.2.0", "negotiator": "~0.6.4", "on-headers": "~1.1.0", "safe-buffer": "5.2.1", "vary": "~1.1.2" } }, "sha512-o8vI5RE5A6EVVOd9o41jKp41aJom+QTEO/Bx8MYNjexMo/Bv2WOjUfZr+aL0WnYSgymUy6zeguqLTsIhV0gMvQ=="], + + "compute-scroll-into-view": ["compute-scroll-into-view@3.2.2", "", {}, "sha512-X+jf3y2j3TbtxA3fq3/kBNiSnD1QlIChiIQdAc2Yo1LtOc0yjO1TzgxWJf8PwtKPGgSvSfWUlVvrb7vGx1eYWA=="], + + "concat-map": ["concat-map@0.0.1", "", {}, "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg=="], + + "content-disposition": ["content-disposition@0.5.2", "", {}, "sha512-kRGRZw3bLlFISDBgwTSA1TMBFN6J6GWDeubmDE3AF+3+yXL8hTWv8r5rkLbqYXY4RjPk/EzHnClI3zQf1cFmHA=="], + "convert-source-map": ["convert-source-map@2.0.0", "", {}, "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg=="], + "cose-base": ["cose-base@1.0.3", "", { "dependencies": { "layout-base": "^1.0.0" } }, "sha512-s9whTXInMSgAp/NVXVNuVxVKzGH2qck3aQlVHxDCdAEPgtMKwc4Wq6/QKhgdEdgbLSi9rBTAcPoRa6JpiG4ksg=="], + "cross-spawn": ["cross-spawn@7.0.6", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="], "css-select": ["css-select@7.0.0", "", { "dependencies": { "boolbase": "^2.0.0", "css-what": "^8.0.0", "domhandler": "^6.0.1", "domutils": "^4.0.2", "nth-check": "^3.0.1" } }, "sha512-snmjEVXy+1LnwXdxhYvTMj1d9tOh4HxkA1YmoayVBeeyR2C14Pum7fcxJIm4SswYspVy866eYNwlH6xC3/VH5g=="], @@ -901,20 +1179,108 @@ "csstype": ["csstype@3.2.3", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="], + "cytoscape": ["cytoscape@3.35.0", "", {}, "sha512-sMvBIXiGMnhkCaWz2R06FwF/27MNlS+Tqvi17foO9UhnUg3XGZccKjxsvEqQFAQYMSSZmN5SxYzUYlQ0DOJJ3g=="], + + "cytoscape-cose-bilkent": ["cytoscape-cose-bilkent@4.1.0", "", { "dependencies": { "cose-base": "^1.0.0" }, "peerDependencies": { "cytoscape": "^3.2.0" } }, "sha512-wgQlVIUJF13Quxiv5e1gstZ08rnZj2XaLHGoFMYXz7SkNfCDOOteKBE6SYRfA9WxxI/iBc3ajfDoc6hb/MRAHQ=="], + + "cytoscape-fcose": ["cytoscape-fcose@2.2.0", "", { "dependencies": { "cose-base": "^2.2.0" }, "peerDependencies": { "cytoscape": "^3.2.0" } }, "sha512-ki1/VuRIHFCzxWNrsshHYPs6L7TvLu3DL+TyIGEsRcvVERmxokbf5Gdk7mFxZnTdiGtnA4cfSmjZJMviqSuZrQ=="], + + "d3": ["d3@7.9.2", "", { "dependencies": { "d3-array": "^3.2.5", "d3-axis": "^3.0.1", "d3-brush": "^3.0.1", "d3-chord": "^3.0.2", "d3-color": "^3.1.1", "d3-contour": "^4.0.3", "d3-delaunay": "^6.0.6", "d3-dispatch": "^3.0.2", "d3-drag": "^3.0.1", "d3-dsv": "^3.0.2", "d3-ease": "^3.0.2", "d3-fetch": "^3.0.2", "d3-force": "^3.0.1", "d3-format": "^3.1.3", "d3-geo": "^3.1.2", "d3-hierarchy": "^3.1.3", "d3-interpolate": "^3.0.2", "d3-path": "^3.1.1", "d3-polygon": "^3.0.2", "d3-quadtree": "^3.0.2", "d3-random": "^3.0.2", "d3-scale": "^4.0.3", "d3-scale-chromatic": "^3.1.1", "d3-selection": "^3.0.1", "d3-shape": "^3.2.1", "d3-time": "^3.1.1", "d3-time-format": "^4.1.1", "d3-timer": "^3.0.2", "d3-transition": "^3.0.2", "d3-zoom": "^3.0.1" } }, "sha512-ZKb/mONPVKzaO5UlcWcwN8bS4ezvQaYu+bsou+XgNABdGC800kwH651ADTbbTxMPHW13UlvbQafdmJQDk1w7Mg=="], + + "d3-array": ["d3-array@3.2.5", "", { "dependencies": { "internmap": "1 - 2" } }, "sha512-Th8qGXoBalmWsstpkuhmBuTsBQIFqYOJtjlBvNVvBfJ8E3uYusBUwUR8HU20U0qKKQkgCvKyR1YjiozWadk5QA=="], + + "d3-axis": ["d3-axis@3.0.1", "", {}, "sha512-E5QCXfaf/uJZEHHiqoWRq+bQEm2PzoVFv2rDC7CZ3wwI0MjfMW3w83J3ubobG4IJj3lShAI5eiPJhOu/8wHofA=="], + + "d3-brush": ["d3-brush@3.0.1", "", { "dependencies": { "d3-dispatch": "1 - 3", "d3-drag": "2 - 3", "d3-interpolate": "1 - 3", "d3-selection": "3", "d3-transition": "3" } }, "sha512-L5Glqa/Gb7LU3ndIOMtA5mDzlJ0aXKp5ELP2X09ctWF23jO7+faIUVDbmaIi+D6k3EemXFWn1F3lkfguExoVhA=="], + + "d3-chord": ["d3-chord@3.0.2", "", { "dependencies": { "d3-path": "1 - 3" } }, "sha512-cGmADo5M2PTi3ewJZ2lcE32eURd4JmHtQ5JwRIUcas5L1SXqufG9yPyjWp8fW0gRi7aZi9bgbZPFZO1eyZ+1CQ=="], + + "d3-color": ["d3-color@3.1.1", "", {}, "sha512-lfab8x0Bj0UO7SNsY8dZSbNIA6ipbkE3X0NG9nqjCu6CfCHZseuDnOSJY7hidKrjpP++i1M2qT+FlAdPKYRilA=="], + + "d3-contour": ["d3-contour@4.0.3", "", { "dependencies": { "d3-array": "^3.2.4" } }, "sha512-5DYURc8KwXPOhSUBblU0P9rVcArsSPxPOxsfO0Eud0s28oU0sB2e80aRHRL9AZW3usT8ikFKyIHpHHLNWLdRVA=="], + + "d3-delaunay": ["d3-delaunay@6.0.6", "", { "dependencies": { "delaunator": "5" } }, "sha512-DMQIEvSJhZCB6pwedcXaAlQ+MeKU5LlM2XakKtc73b/VM+RBiI1SRXycOEOKg2jsKj4zZ9F0KGYG6nCGwwWu/g=="], + + "d3-dispatch": ["d3-dispatch@3.0.2", "", {}, "sha512-sAzH4Y4nsLo8eSqw5jKiZt+LU2wZmL/qS+OkxQGjhwazB/D7TY34R/QK1eshfGr7cZEKymKZ/Haem7m+lu98Sg=="], + + "d3-drag": ["d3-drag@3.0.1", "", { "dependencies": { "d3-dispatch": "1 - 3", "d3-selection": "3" } }, "sha512-OWeoayCq8J69hUIjvL+Mb6Q6Oaj/fyHV5XaXByEUAG+JUjIfTGDnk3qGpcXrD3VmQ3BSV96fcbM6fqq7C0tbPA=="], + + "d3-dsv": ["d3-dsv@3.0.2", "", { "dependencies": { "commander": "7", "iconv-lite": "0.6", "rw": "1" }, "bin": { "csv2tsv": "bin/dsv2dsv.js", "dsv2dsv": "bin/dsv2dsv.js", "tsv2csv": "bin/dsv2dsv.js", "csv2json": "bin/dsv2json.js", "dsv2json": "bin/dsv2json.js", "json2csv": "bin/json2dsv.js", "json2dsv": "bin/json2dsv.js", "json2tsv": "bin/json2dsv.js", "tsv2json": "bin/dsv2json.js" } }, "sha512-FUnXhX7I4/AXyRCZzwfZTDGSq8PGZ4oR0tiCBqNGOZMsDrQ+6sIWNQnBzcCGhzJKZ6uCvCezTwflUqI209RRiQ=="], + + "d3-ease": ["d3-ease@3.0.2", "", {}, "sha512-B5znKqRmKROAN4oHWQ50W/qisVjA9GXh2WMsVKdFVp4DxWmcrOsweqgUOUVsv5th96kwaZlokU6SlV4J3gak1w=="], + + "d3-fetch": ["d3-fetch@3.0.2", "", { "dependencies": { "d3-dsv": "1 - 3" } }, "sha512-1wGF62bgjMRbF6mqbD+6rRWBL2hwWVYQjFO2UP3Wm1nIAvJZKaQxXM5caVY7athoCa8wIq9lCf7g44lPWFk50g=="], + + "d3-force": ["d3-force@3.0.1", "", { "dependencies": { "d3-dispatch": "1 - 3", "d3-quadtree": "1 - 3", "d3-timer": "1 - 3" } }, "sha512-kAaaHLFebBYwgi5cYBXAI8vKrQFMCD2MEswj2QuPKKbdU1wYLc8WXtS7O8F/b6POCIe3gJjY6hkDstHi1yMETQ=="], + + "d3-format": ["d3-format@3.1.3", "", {}, "sha512-+F+/49swqmGuQJmSKnVMIDH/QkEFV5li9QRj0xm/KhyAUBv099O5PrvpQFxBp24PYph17Mnvt9mjKQV0ii0nMA=="], + + "d3-geo": ["d3-geo@3.1.2", "", { "dependencies": { "d3-array": "2.5.0 - 3" } }, "sha512-5R8ZgDQorIxmauv7R6gpE/ndz+Z0qAZssigq0aXFdvPHdY41RqtW02jrRUQAL724NdPABYXo1+gQEGBBr7uKNg=="], + + "d3-hierarchy": ["d3-hierarchy@3.1.3", "", {}, "sha512-GRajN5ZcnEwYFWqqdzhG1qJ3+fDg6WWzk47TJg7ePY7yvYAgRfD2r1mUx+wviBOWuCwamCUzjwMSdato43jbGA=="], + + "d3-interpolate": ["d3-interpolate@3.0.2", "", { "dependencies": { "d3-color": "1 - 3" } }, "sha512-IRzGU62DtxhvsnSTWMQIdnoZ6gA+BCWwBon1EJI6SjoN595799b6z/QRBzXfFhE8iupUPp3042yBNo0STPqnzQ=="], + + "d3-path": ["d3-path@3.1.1", "", {}, "sha512-jsbgV8zIT38ReB9O7X7gcLndTQRONSqNNd+oGIaTBdUug4r5jFmp0N6RY9R5GWbdUDucn0qoTGyfjapT4tDhcg=="], + + "d3-polygon": ["d3-polygon@3.0.2", "", {}, "sha512-WAUvPudGU1Dn4mDPfb6+JnnbeVEV53hG/BoT+bxts6AkZsOpTEiV1jHYX+2vtwCICNFG9Wxv8QS+eW1zE/Dwfg=="], + + "d3-quadtree": ["d3-quadtree@3.0.2", "", {}, "sha512-9Lu9mqJKRbIk0d6mKDjpvPURaPdwHVK5CYbcdd0/4vBgz4ldz/7TIOse3kNERsByGNfld58KEco507AztJWyTQ=="], + + "d3-random": ["d3-random@3.0.2", "", {}, "sha512-PxJi9LNV+7mulaYO77nd+oGurXGL1fhedXjHnB3pWLUcqDnQtF4VASoqnQGHgoXLByVdv5QJ/2kfwkGn5HTS8g=="], + + "d3-sankey": ["d3-sankey@0.12.3", "", { "dependencies": { "d3-array": "1 - 2", "d3-shape": "^1.2.0" } }, "sha512-nQhsBRmM19Ax5xEIPLMY9ZmJ/cDvd1BG3UVvt5h3WRxKg5zGRbvnteTyWAbzeSvlh3tW7ZEmq4VwR5mB3tutmQ=="], + + "d3-scale": ["d3-scale@4.0.3", "", { "dependencies": { "d3-array": "2.10.0 - 3", "d3-format": "1 - 3", "d3-interpolate": "1.2.0 - 3", "d3-time": "2.1.1 - 3", "d3-time-format": "2 - 4" } }, "sha512-66cWobCNzcMvlfoaDHCxuIv9TBUWG1BLOWdv9kHHFuCr1JdqAWPvTmsaEYDD5NRMyWZ5+7u0GqiCDfMXMqh3hg=="], + + "d3-scale-chromatic": ["d3-scale-chromatic@3.1.1", "", { "dependencies": { "d3-color": "1 - 3", "d3-interpolate": "1 - 3", "d3-scale": "1 - 4" } }, "sha512-lA5gfN2yMvmChubmptnDiBfeGpHD7Yb1EbvCz0TZE0WHXhyR6W2allPuhKtzV5ILQRqeOdefF0qYtERReLUBDg=="], + + "d3-selection": ["d3-selection@3.0.1", "", {}, "sha512-ODSf35vqCrlCfp7hrm0eZjvOosSXSYLjqvIlhMBV9q9VOx7EBJG6pc+uXBswEZNJgCGJ+qnKYcWutbZDIxe/Xg=="], + + "d3-shape": ["d3-shape@3.2.1", "", { "dependencies": { "d3-path": "^3.1.1" } }, "sha512-dm2o+lbKdzg9tY7GEag/dB9hcbodLfwkE/DkvqbELJXaMz0yKzWWhZqhbI7CKubukA7HnRyz0avdtvi7EPxPvw=="], + + "d3-time": ["d3-time@3.1.1", "", { "dependencies": { "d3-array": "2 - 3" } }, "sha512-Ze7rjrhMzdeulh0/hjcfFj7XLAHOfowtEMfsoG6DU866HPynQNW7Wfen6hzXcqKTv8XzxvF6Hzr5XD6bMHr2ug=="], + + "d3-time-format": ["d3-time-format@4.1.1", "", { "dependencies": { "d3-time": "1 - 3" } }, "sha512-22XaqjyCjpqgda20erhsOjGmC3vvYwTNYniKAd45W5UWLDF43moeOuV9qYpRqobIlsnK0UhnKZjUUJm3VgORUA=="], + + "d3-timer": ["d3-timer@3.0.2", "", {}, "sha512-1Il1aliroVSErrv5aulRBxAY+7+DnaoLIWGd1C6SsBTWDeobWiP/V69vwb8vT6abR1kKwaNe1196pmaQ1fK90A=="], + + "d3-transition": ["d3-transition@3.0.2", "", { "dependencies": { "d3-color": "1 - 3", "d3-dispatch": "1 - 3", "d3-ease": "1 - 3", "d3-interpolate": "1 - 3", "d3-timer": "1 - 3" }, "peerDependencies": { "d3-selection": "2 - 3" } }, "sha512-RcjCsdFgyFoDB+QXLC5m60ZkTN0k9zH+ovoLlTdJnDS1AbfbcuowiM4pCKSTOclNibS4f4J4cbv2m7O7y8NTOQ=="], + + "d3-zoom": ["d3-zoom@3.0.1", "", { "dependencies": { "d3-dispatch": "1 - 3", "d3-drag": "2 - 3", "d3-interpolate": "1 - 3", "d3-selection": "2 - 3", "d3-transition": "2 - 3" } }, "sha512-kfjD3BDQu/FOatpZ6JdMSyIoDwTxIpI29ySTI2J5ZlDaH1WbuJGQJ2Q9oJkWTEZEW98j6idezoomSD3Cn2zwiw=="], + + "dagre-d3-es": ["dagre-d3-es@7.0.14", "", { "dependencies": { "d3": "^7.9.0", "lodash-es": "^4.17.21" } }, "sha512-P4rFMVq9ESWqmOgK+dlXvOtLwYg0i7u0HBGJER0LZDJT2VHIPAMZ/riPxqJceWMStH5+E61QxFra9kIS3AqdMg=="], + "dataloader": ["dataloader@1.4.0", "", {}, "sha512-68s5jYdlvasItOJnCuI2Q9s4q98g0pCyL3HrcKJu8KNugUl8ahgmZYg38ysLTgQjjXX3H8CJLkAvWrclWfcalw=="], + "dayjs": ["dayjs@1.11.23", "", {}, "sha512-QDTCU0M0MxR3hQfnlDJfwekQiaanm1ubOD231u73WBckQ/fsamwRLiE2GBz6D3a/xF1NgfiDLJjXBa1hYOYTtQ=="], + "debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], + "decode-named-character-reference": ["decode-named-character-reference@1.3.0", "", { "dependencies": { "character-entities": "^2.0.0" } }, "sha512-GtpQYB283KrPp6nRw50q3U9/VfOutZOe103qlN7BPP6Ad27xYnOIWv4lPzo8HCAL+mMZofJ9KEy30fq6MfaK6Q=="], + + "deep-extend": ["deep-extend@0.6.0", "", {}, "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA=="], + "deepmerge": ["deepmerge@4.3.1", "", {}, "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A=="], "defu": ["defu@6.1.7", "", {}, "sha512-7z22QmUWiQ/2d0KkdYmANbRUVABpZ9SNYyH5vx6PZ+nE5bcC0l7uFvEfHlyld/HcGBFTL536ClDt3DEcSlEJAQ=="], + "delaunator": ["delaunator@5.1.0", "", { "dependencies": { "robust-predicates": "^3.0.2" } }, "sha512-AGrQ4QSgssa1NGmWmLPqN5NY2KajF5MqxetNEO+o0n3ZwZZeTmt7bBnvzHWrmkZFxGgr4HdyFgelzgi06otLuQ=="], + + "dequal": ["dequal@2.0.3", "", {}, "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA=="], + + "destroy": ["destroy@1.2.0", "", {}, "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg=="], + "detect-indent": ["detect-indent@6.1.0", "", {}, "sha512-reYkTUJAZb9gUuZ2RvVCNhVHdg62RHnJ7WJl8ftMi4diZ6NWlciOzQN88pUhSELEwflJht4oQDv0F0BMlwaYtA=="], "detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="], + "detect-node-es": ["detect-node-es@1.1.0", "", {}, "sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ=="], + "devalue": ["devalue@5.9.4", "", {}, "sha512-sPAT4pztbu6586/hrhOnMKS17IJrvg12mXiSPSS3W5qDeN2RGgvZ0diZCm31dBbnevfVmujNO3IM2wrS4Y2Rhg=="], + "devlop": ["devlop@1.1.0", "", { "dependencies": { "dequal": "^2.0.0" } }, "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA=="], + "dir-glob": ["dir-glob@3.0.1", "", { "dependencies": { "path-type": "^4.0.0" } }, "sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA=="], "dom-serializer": ["dom-serializer@3.1.1", "", { "dependencies": { "domelementtype": "^3.0.0", "domhandler": "^6.0.0", "entities": "^8.0.0" } }, "sha512-4MEa38/QexBob6gFNwu+EGdWvhJ1OKuNwdYY3Y3NyeWDQfnGeDYQUDfIRzWu5B5gsv03so2Uxd28YC6zrsx3Lw=="], @@ -923,15 +1289,23 @@ "domhandler": ["domhandler@6.0.1", "", { "dependencies": { "domelementtype": "^3.0.0" } }, "sha512-gYzvtM72ZtxQO0T048kd6HWSbbGCNOUwcnfQ01cqIJ4X2IYKFFHZ5mKvrQETcFXxsRObZulDaKmy//R7TPtsBg=="], + "dompurify": ["dompurify@3.4.18", "", { "optionalDependencies": { "@types/trusted-types": "^2.0.7" } }, "sha512-ofe3wI/uNm68HInABYFJYqQxRw1EaKAjNdrFVKqjUY+UZurvNd2L/HuQe097s/4RivWiZyP6tT7aoT8atjfhwg=="], + "domutils": ["domutils@4.0.2", "", { "dependencies": { "dom-serializer": "^3.0.0", "domelementtype": "^3.0.0", "domhandler": "^6.0.0" } }, "sha512-qI4JLRKnSzqFqr7hAlS5xQDusBCjKSEG4t4+7aNrIQMHBcsC2TGEhuyABJdYkgSewL57PNLYEiibY2iPKhKpaA=="], "dotenv": ["dotenv@8.6.0", "", {}, "sha512-IrPdXQsk2BbzvCBGBOTmmSH5SodmqZNt4ERAZDmW4CT+tL8VtvinqywuANaFu4bOMWki16nqf0e4oC0QIaDr/g=="], "dts-resolver": ["dts-resolver@3.0.0", "", { "peerDependencies": { "oxc-resolver": ">=11.0.0" }, "optionalPeers": ["oxc-resolver"] }, "sha512-1T1f+z+4tl9XD+m+0HBgWoL/nm0bOIffyWaUuUSBlFg/86IWvfx+wjNaO/ybU0AJzG9/Mi5hBUgGV6zCmWEN7Q=="], + "eastasianwidth": ["eastasianwidth@0.2.0", "", {}, "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA=="], + "electron-to-chromium": ["electron-to-chromium@1.5.348", "", {}, "sha512-QC2X59nRlycQQMc4ZXjSVBX+tSgJfgRtcrYHbIZLgOV2dCvefoQGegLR7lLXKgpPpSuVmJU19LMzGrSa2C7k3Q=="], - "emoji-regex": ["emoji-regex@10.6.0", "", {}, "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A=="], + "elkjs": ["elkjs@0.12.1", "", {}, "sha512-IhMYKHE4S2vtx0QrhBP3lYOIKDeIiJXBrdq9MGYkuB8ZHqhrBnHNfSUndjXFewrX1CPK8chwq+2NA0K0hliYuw=="], + + "emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="], + + "emojilib": ["emojilib@2.4.0", "", {}, "sha512-5U0rVMU5Y2n2+ykNLQqMoqklN9ICBT/KsvC1Gz6vqHbz2AXXGkG+Pm5rMWk/8Vjrr/mY9985Hi8DYzn1F09Nyw=="], "empathic": ["empathic@2.1.0", "", {}, "sha512-AnfC1ATldl49/cvZdLPDjBfrRNwbDO05aibiOtzQu3qtlbJtomNLhF30HEtn/7iBz50dlMECqATo3fG0LrdEgw=="], @@ -943,18 +1317,42 @@ "environment": ["environment@1.1.0", "", {}, "sha512-xUtoPkMggbz0MPyPiIWr1Kp4aeWJjDZ6SMvURhimjdZgsRuDplF5/s9hcgGhyXMhs+6vpnuoiZ2kFiu3FMnS8Q=="], + "es-toolkit": ["es-toolkit@1.53.2", "", {}, "sha512-iUqZ+NlwH4jUgRmXZUxFBsV/9762TQEa1O4IXLFBmDEjVHScBytKuseX23I0+v9ShZ5MYxEx6WKNzm6IPnex8g=="], + + "esast-util-from-estree": ["esast-util-from-estree@2.0.0", "", { "dependencies": { "@types/estree-jsx": "^1.0.0", "devlop": "^1.0.0", "estree-util-visit": "^2.0.0", "unist-util-position-from-estree": "^2.0.0" } }, "sha512-4CyanoAudUSBAn5K13H4JhsMH6L9ZP7XbLVe/dKybkxMO7eDyLsT8UHl9TRNrU2Gr9nz+FovfSIjuXWJ81uVwQ=="], + + "esast-util-from-js": ["esast-util-from-js@2.0.1", "", { "dependencies": { "@types/estree-jsx": "^1.0.0", "acorn": "^8.0.0", "esast-util-from-estree": "^2.0.0", "vfile-message": "^4.0.0" } }, "sha512-8Ja+rNJ0Lt56Pcf3TAmpBZjmx8ZcK5Ts4cAzIOjsjevg9oSXJnl6SUQ2EevU8tv3h6ZLWmoKL5H4fgWvdvfETw=="], + "esbuild": ["esbuild@0.28.2", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.28.2", "@esbuild/android-arm": "0.28.2", "@esbuild/android-arm64": "0.28.2", "@esbuild/android-x64": "0.28.2", "@esbuild/darwin-arm64": "0.28.2", "@esbuild/darwin-x64": "0.28.2", "@esbuild/freebsd-arm64": "0.28.2", "@esbuild/freebsd-x64": "0.28.2", "@esbuild/linux-arm": "0.28.2", "@esbuild/linux-arm64": "0.28.2", "@esbuild/linux-ia32": "0.28.2", "@esbuild/linux-loong64": "0.28.2", "@esbuild/linux-mips64el": "0.28.2", "@esbuild/linux-ppc64": "0.28.2", "@esbuild/linux-riscv64": "0.28.2", "@esbuild/linux-s390x": "0.28.2", "@esbuild/linux-x64": "0.28.2", "@esbuild/netbsd-arm64": "0.28.2", "@esbuild/netbsd-x64": "0.28.2", "@esbuild/openbsd-arm64": "0.28.2", "@esbuild/openbsd-x64": "0.28.2", "@esbuild/openharmony-arm64": "0.28.2", "@esbuild/sunos-x64": "0.28.2", "@esbuild/win32-arm64": "0.28.2", "@esbuild/win32-ia32": "0.28.2", "@esbuild/win32-x64": "0.28.2" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA=="], "escalade": ["escalade@3.2.0", "", {}, "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA=="], + "escape-string-regexp": ["escape-string-regexp@5.0.0", "", {}, "sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw=="], + "esm-env": ["esm-env@1.2.2", "", {}, "sha512-Epxrv+Nr/CaL4ZcFGPJIYLWFom+YeV1DqMLHJoEd9SYRxNbaFruBwfEX/kkHUJf55j2+TUbmDcmuilbP1TmXHA=="], "esprima": ["esprima@4.0.1", "", { "bin": { "esparse": "./bin/esparse.js", "esvalidate": "./bin/esvalidate.js" } }, "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A=="], "esrap": ["esrap@2.4.0", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.4.15" }, "peerDependencies": { "@typescript-eslint/types": "^8.2.0" }, "optionalPeers": ["@typescript-eslint/types"] }, "sha512-CQPcneEHw/czj32uwQC52nYnax8H4SXt25FCM+LIwGZ49cMIxpOj3bP8wmzcI+Z0HIy5KkClaPhRLfCySzwHPA=="], + "estree-util-attach-comments": ["estree-util-attach-comments@3.0.0", "", { "dependencies": { "@types/estree": "^1.0.0" } }, "sha512-cKUwm/HUcTDsYh/9FgnuFqpfquUbwIqwKM26BVCGDPVgvaCl/nDCCjUfiLlx6lsEZ3Z4RFxNbOQ60pkaEwFxGw=="], + + "estree-util-build-jsx": ["estree-util-build-jsx@3.0.1", "", { "dependencies": { "@types/estree-jsx": "^1.0.0", "devlop": "^1.0.0", "estree-util-is-identifier-name": "^3.0.0", "estree-walker": "^3.0.0" } }, "sha512-8U5eiL6BTrPxp/CHbs2yMgP8ftMhR5ww1eIKoWRMlqvltHF8fZn5LRDvTKuxD3DUn+shRbLGqXemcP51oFCsGQ=="], + + "estree-util-is-identifier-name": ["estree-util-is-identifier-name@3.0.0", "", {}, "sha512-hFtqIDZTIUZ9BXLb8y4pYGyk6+wekIivNVTcmvk8NoOh+VeRn5y6cEHzbURrWbfp1fIqdVipilzj+lfaadNZmg=="], + + "estree-util-scope": ["estree-util-scope@1.0.1", "", { "dependencies": { "@types/estree": "^1.0.0", "devlop": "^1.0.0" } }, "sha512-B0np3dcdxqILX5e9nEi5/Fr4K7gL4oYFVPV1zRa2e9wRCbQoZZNWOZFYyoInvXUPJXBXjss+QXlWLJChDEHDkA=="], + + "estree-util-to-js": ["estree-util-to-js@2.0.0", "", { "dependencies": { "@types/estree-jsx": "^1.0.0", "astring": "^1.8.0", "source-map": "^0.7.0" } }, "sha512-WDF+xj5rRWmD5tj6bIqRi6CkLIXbbNQUcxQHzGysQzvHmdYG2G7p/Tf0J0gpxGgkeMZNTIjT/AoSvC9Xehcgdg=="], + + "estree-util-value-to-estree": ["estree-util-value-to-estree@3.5.0", "", { "dependencies": { "@types/estree": "^1.0.0" } }, "sha512-aMV56R27Gv3QmfmF1MY12GWkGzzeAezAX+UplqHVASfjc9wNzI/X6hC0S9oxq61WT4aQesLGslWP9tKk6ghRZQ=="], + + "estree-util-visit": ["estree-util-visit@2.0.0", "", { "dependencies": { "@types/estree-jsx": "^1.0.0", "@types/unist": "^3.0.0" } }, "sha512-m5KgiH85xAhhW8Wta0vShLcUvOsh3LLPI2YVwcbio1l7E09NTLL1EyMZFM1OyWowoH0skScNbhOPl4kcBgzTww=="], + "estree-walker": ["estree-walker@2.0.2", "", {}, "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w=="], + "extend": ["extend@3.0.2", "", {}, "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g=="], + "extendable-error": ["extendable-error@0.1.7", "", {}, "sha512-UOiS2in6/Q0FK0R0q6UY9vYpQ21mr/Qn1KOnte7vsACuNJf514WvCCUHSRCPcgjPT2bAhNIJdlE6bVap1GKmeg=="], "fast-deep-equal": ["fast-deep-equal@3.1.3", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="], @@ -973,39 +1371,71 @@ "fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="], + "fflate": ["fflate@0.8.3", "", {}, "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA=="], + "fill-range": ["fill-range@7.1.1", "", { "dependencies": { "to-regex-range": "^5.0.1" } }, "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg=="], "find-up": ["find-up@4.1.0", "", { "dependencies": { "locate-path": "^5.0.0", "path-exists": "^4.0.0" } }, "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw=="], "flru": ["flru@1.0.2", "", {}, "sha512-kWyh8ADvHBFz6ua5xYOPnUroZTT/bwWfrCeL0Wj1dzG4/YOmOcfJ99W8dOVyyynJN35rZ9aCOtHChqQovV7yog=="], + "framer-motion": ["framer-motion@14.14.0", "", { "dependencies": { "motion-dom": "14.14.0", "motion-utils": "14.7.0", "tslib": "^2.4.0" }, "peerDependencies": { "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0", "remix": "^3.1.0" }, "optionalPeers": ["react", "react-dom", "remix"] }, "sha512-fidRX0VzkZdA9OovFiBSzJtt9/jLcJpna78Z+KCqQQZIWoIpN3tOhEXAhhAw/FObUUh+o3Y18yx1F4BP0mVJ8Q=="], + "fs-extra": ["fs-extra@7.0.1", "", { "dependencies": { "graceful-fs": "^4.1.2", "jsonfile": "^4.0.0", "universalify": "^0.1.0" } }, "sha512-YJDaCJZEnBmcbw13fvdAM9AwNOJwOzrE4pqMqBq5nFiEqXUqHwlK4B+3pUw6JNvfSPtX05xFHtYy/1ni01eGCw=="], "fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="], + "fumadocs-core": ["fumadocs-core@16.19.4", "", { "dependencies": { "@fumari/image-size": "^0.1.1", "acorn": "^8.19.0", "acorn-jsx": "^5.3.2", "estree-util-value-to-estree": "^3.5.0", "github-slugger": "^2.0.0", "hast-util-from-dom": "^5.0.1", "hast-util-to-estree": "^3.1.3", "mdast-util-mdx": "^3.0.0", "micromark": "^4.0.3", "micromark-extension-gfm-table": "^2.1.2", "npm-to-yarn": "3.2.0", "remark": "^15.0.1", "remark-gfm": "^4.0.1", "remark-rehype": "^11.1.2", "scroll-into-view-if-needed": "^3.1.0", "shiki": "^4.6.0", "tinyglobby": "^0.2.17", "unified": "^11.0.5", "vfile": "^6.0.3", "yaml": "^2.9.1", "zbsearch": "^4.0.2" }, "peerDependencies": { "@mdx-js/mdx": "*", "@mixedbread/sdk": "0.x.x", "@modelcontextprotocol/server": "2.x.x", "@orama/core": "1.x.x", "@oramacloud/client": "2.x.x", "@pierre/highlights": "0.x.x", "@tanstack/react-router": "1.x.x", "@types/estree-jsx": "*", "@types/hast": "*", "@types/mdast": "*", "@types/react": "*", "algoliasearch": "5.x.x", "flexsearch": "*", "lucide-react": "*", "meilisearch": ">=0.50.0 <1.0.0", "next": "16.x.x", "react": "^19.2.0", "react-dom": "^19.2.0", "react-router": "7.x.x || 8.x.x", "waku": "*", "zod": "4.x.x" }, "optionalPeers": ["@mdx-js/mdx", "@mixedbread/sdk", "@modelcontextprotocol/server", "@orama/core", "@oramacloud/client", "@pierre/highlights", "@tanstack/react-router", "@types/estree-jsx", "@types/hast", "@types/mdast", "@types/react", "algoliasearch", "flexsearch", "lucide-react", "meilisearch", "next", "react", "react-dom", "react-router", "waku", "zod"] }, "sha512-PRYjTrfIbp3clCIE4n0nhbkGnoDg61cDOQp0GNYtAMl7haBgVykaQhI5SRTS8/i6POfodSR6C5lJiAGBBH1eNA=="], + + "fumadocs-mdx": ["fumadocs-mdx@15.6.3", "", { "dependencies": { "@mdx-js/mdx": "^3.1.1", "@standard-schema/spec": "^1.1.0", "acorn": "^8.19.0", "acorn-jsx": "^5.3.2", "chokidar": "^6.0.0", "esbuild": "^0.28.2", "estree-util-value-to-estree": "^3.5.0", "github-slugger": "^2.0.0", "magic-string": "^1.4.5", "mdast-util-from-markdown": "^2.1.0", "mdast-util-mdx": "^3.0.0", "micromark-extension-mdxjs-esm": "^3.0.0", "picocolors": "^1.1.1", "picomatch": "^4.0.7", "tinyexec": "^1.3.1", "tinyglobby": "^0.2.17", "unified": "^11.0.5", "unist-util-remove-position": "^5.0.0", "vfile": "^6.0.3", "yaml": "^2.9.1", "yuku-analyzer": "^0.19.0", "zod": "^4.6.7" }, "peerDependencies": { "@fumadocs/satteri": "0.x.x", "@types/mdast": "*", "@types/mdx": "*", "@types/react": "*", "@vitejs/plugin-rsc": "^0.5.34", "fumadocs-core": "^16.18.3", "mdast-util-directive": "*", "next": "^15.3.0 || ^16.0.0", "react": "^19.2.0", "rolldown": "*", "satteri": "^0.11.7", "vite": "7.x.x || 8.x.x" }, "optionalPeers": ["@fumadocs/satteri", "@types/mdast", "@types/mdx", "@types/react", "@vitejs/plugin-rsc", "mdast-util-directive", "next", "react", "rolldown", "satteri", "vite"], "bin": { "fumadocs-mdx": "./bin.js" } }, "sha512-MPuuZNfczeuYON3g+gWQB+jtD4gGIx0hEikYVDAb/GL/JO6SFyCBH6xASg0OuWrcLyLrhqaei65HXBZQMQCTRw=="], + + "fumadocs-ui": ["@fumadocs/base-ui@16.19.4", "", { "dependencies": { "@base-ui/react": "^1.9.0", "@fuma-translate/react": "^1.0.2", "@fumadocs/tailwind": "0.1.5", "class-variance-authority": "^0.7.1", "cn": "^0.5.2", "lucide-react": "^1.71.0", "motion": "^14.12.0", "next-themes": "^0.4.6", "react-remove-scroll": "^2.7.2", "scroll-into-view-if-needed": "^3.1.0", "shiki": "^4.6.0" }, "peerDependencies": { "@types/mdx": "*", "@types/react": "*", "fumadocs-core": "16.19.4", "next": "16.x.x", "react": "^19.2.0", "react-dom": "^19.2.0", "takumi-js": "*" }, "optionalPeers": ["@types/mdx", "@types/react", "next", "takumi-js"] }, "sha512-S8CPsuyIjWErT9Ek8+y/tmq+DPrlTJ+1b1KphvmKyeNKHnpfFC9BEj/Gqrz4gj0aZLQH2Fwo73igMAgnOUDeEw=="], + "gensync": ["gensync@1.0.0-beta.2", "", {}, "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg=="], "get-caller-file": ["get-caller-file@2.0.5", "", {}, "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg=="], "get-east-asian-width": ["get-east-asian-width@1.5.0", "", {}, "sha512-CQ+bEO+Tva/qlmw24dCejulK5pMzVnUOFOijVogd3KQs07HnRIgp8TGipvCCRT06xeYEbpbgwaCxglFyiuIcmA=="], + "get-nonce": ["get-nonce@1.0.1", "", {}, "sha512-FJhYRoDaiatfEkUK8HKlicmu/3SGFD51q3itKDGoSTysQJBnfOcxU5GxnhE1E6soB76MbT0MBtnKJuXyAx+96Q=="], + "get-tsconfig": ["get-tsconfig@5.0.0-beta.6", "", { "dependencies": { "resolve-pkg-maps": "^1.0.0" } }, "sha512-X6fBC0pmImC70gvX2zm56go9hx0MyoGVdG0tUCkg/D+Xnh5TJsOZ7iDbOdI3PvmtrDxnu1YdDufpK2QJX1Meqw=="], + "github-slugger": ["github-slugger@2.0.0", "", {}, "sha512-IaOQ9puYtjrkq7Y0Ygl9KDZnrf/aiUJYUpVf89y8kyaxbRG7Y1SrX/jaumrv81vc61+kiMempujsM3Yw7w5qcw=="], + "glob-parent": ["glob-parent@5.1.2", "", { "dependencies": { "is-glob": "^4.0.1" } }, "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow=="], "globby": ["globby@11.1.0", "", { "dependencies": { "array-union": "^2.1.0", "dir-glob": "^3.0.1", "fast-glob": "^3.2.9", "ignore": "^5.2.0", "merge2": "^1.4.1", "slash": "^3.0.0" } }, "sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g=="], "graceful-fs": ["graceful-fs@4.2.11", "", {}, "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ=="], + "hachure-fill": ["hachure-fill@0.5.2", "", {}, "sha512-3GKBOn+m2LX9iq+JC1064cSFprJY4jL1jCXTcpnfER5HYE2l/4EfWSGzkPa/ZDBmYI0ZOEj5VHV/eKnPGkHuOg=="], + "happy-dom": ["happy-dom@21.0.4", "", { "dependencies": { "@types/node": ">=20.0.0", "@types/whatwg-mimetype": "^3.0.2", "@types/ws": "^8.18.1", "buffer-image-size": "^0.6.4", "entities": "^7.0.1", "whatwg-mimetype": "^3.0.0", "ws": "^8.21.0" } }, "sha512-tFm+GaLBgo6o0awHnvHaNoraVo27qJ+2tZEtZ+cIa08hXbeitrxAJajLI05hsUy/2/YTKcUjQYzHe5mCcraLBw=="], "has-flag": ["has-flag@4.0.0", "", {}, "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ=="], + "hast-util-from-dom": ["hast-util-from-dom@5.0.1", "", { "dependencies": { "@types/hast": "^3.0.0", "hastscript": "^9.0.0", "web-namespaces": "^2.0.0" } }, "sha512-N+LqofjR2zuzTjCPzyDUdSshy4Ma6li7p/c3pA78uTwzFgENbgbUrm2ugwsOdcjI1muO+o6Dgzp9p8WHtn/39Q=="], + + "hast-util-parse-selector": ["hast-util-parse-selector@4.0.0", "", { "dependencies": { "@types/hast": "^3.0.0" } }, "sha512-wkQCkSYoOGCRKERFWcxMVMOcYE2K1AaNLU8DXS9arxnLOUEWbOXKXiJUNzEpqZ3JOKpnha3jkFrumEjVliDe7A=="], + + "hast-util-to-estree": ["hast-util-to-estree@3.1.3", "", { "dependencies": { "@types/estree": "^1.0.0", "@types/estree-jsx": "^1.0.0", "@types/hast": "^3.0.0", "comma-separated-tokens": "^2.0.0", "devlop": "^1.0.0", "estree-util-attach-comments": "^3.0.0", "estree-util-is-identifier-name": "^3.0.0", "hast-util-whitespace": "^3.0.0", "mdast-util-mdx-expression": "^2.0.0", "mdast-util-mdx-jsx": "^3.0.0", "mdast-util-mdxjs-esm": "^2.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", "style-to-js": "^1.0.0", "unist-util-position": "^5.0.0", "zwitch": "^2.0.0" } }, "sha512-48+B/rJWAp0jamNbAAf9M7Uf//UVqAoMmgXhBdxTDJLGKY+LRnZ99qcG+Qjl5HfMpYNzS5v4EAwVEF34LeAj7w=="], + + "hast-util-to-html": ["hast-util-to-html@9.0.6", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "ccount": "^2.0.0", "comma-separated-tokens": "^2.0.0", "hast-util-whitespace": "^3.0.0", "html-void-elements": "^3.0.0", "mdast-util-to-hast": "^13.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", "stringify-entities": "^4.0.0", "zwitch": "^2.0.4" } }, "sha512-1SZUxCN3TtJAE7e2BQN2MBHsoZ1gnmi9GoCP5Di59CSWptIezSAW09yDZyVbanb78V9eCwrKqdQsjtfVTxYHWA=="], + + "hast-util-to-jsx-runtime": ["hast-util-to-jsx-runtime@2.3.7", "", { "dependencies": { "@types/estree": "^1.0.0", "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "comma-separated-tokens": "^2.0.0", "devlop": "^1.0.0", "estree-util-is-identifier-name": "^3.0.0", "hast-util-whitespace": "^3.0.0", "mdast-util-mdx-expression": "^2.0.0", "mdast-util-mdx-jsx": "^3.0.0", "mdast-util-mdxjs-esm": "^2.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", "style-to-object": "^2.0.0", "unist-util-position": "^5.0.0", "vfile-message": "^4.0.0" } }, "sha512-F7DNV2NMcTxA4GqPVHnXzX+mpoPHAIY9rJAVH3CZ1FdBZOcBUEjUuvMkMpHVs/sicEtznh9tMGj5WUR9S4E2rg=="], + + "hast-util-whitespace": ["hast-util-whitespace@3.0.0", "", { "dependencies": { "@types/hast": "^3.0.0" } }, "sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw=="], + + "hastscript": ["hastscript@9.0.3", "", { "dependencies": { "@types/hast": "^3.0.0", "comma-separated-tokens": "^2.0.0", "hast-util-parse-selector": "^4.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0" } }, "sha512-1ALZXSmCGmW3h8AMz4R4+QKSKFi7sNgXLVwmwB8FYVtl1CwQ3WDkSAEY/d5tp1g/vbQgq2s1WlHgfO3jbw1TsA=="], + + "highlight.js": ["highlight.js@10.7.3", "", {}, "sha512-tzcUFauisWKNHaRkN4Wjl/ZA07gENAjFl3J/c480dprkGTg5EQstgaNFqBfUqCq54kZRIEcreTsAgF/m2quD7A=="], + "hookable": ["hookable@6.1.2", "", {}, "sha512-+abwxtiEA52GCVIsQqut3S/uKTbUwYIp4Pe/vv+6py5XiXBCqMZHg6pA6Y5qhgLSEys0/cYuPbO0z1QFj5ZCmg=="], "hosted-git-info": ["hosted-git-info@10.1.1", "", { "dependencies": { "lru-cache": "^11.1.0" } }, "sha512-DeOnSPAvOndYKfw075gt8yZzQ7S2hNztw34zBTfhIzLhmBTswIBg5/y+pqu/VD5cYWm5goAFTusDmUEmKZ0PEQ=="], - "html-entities": ["html-entities@2.3.3", "", {}, "sha512-DV5Ln36z34NNTDgnz0EWGBLZENelNAtkiFA4kyNOG2tDI6Mz1uSWiq1wAKdyjnJwyDiDO7Fa2SO1CTxPXL8VxA=="], + "html-void-elements": ["html-void-elements@3.0.0", "", {}, "sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg=="], "htmlparser2": ["htmlparser2@12.0.0", "", { "dependencies": { "domelementtype": "^3.0.0", "domhandler": "^6.0.0", "domutils": "^4.0.2", "entities": "^8.0.0" } }, "sha512-Tz7u1i95/g2x2jz81+x0FBVhBhY5aRTvD3tXXdFaljuNdzDLJ8UGNRrTcj2cgQvAg3iW/h77Fz15nLW0L0CrZw=="], @@ -1023,16 +1453,34 @@ "import-without-cache": ["import-without-cache@0.4.1", "", {}, "sha512-vXoV9PjKHEednCUu01e98TkImxy67e3BJXbTIOmIq4Hyzw3IAwYRcuPkfeTzJzwyyts4kjuA73x+pWJLc4f86A=="], + "ini": ["ini@1.3.8", "", {}, "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew=="], + + "inline-style-parser": ["inline-style-parser@0.2.7", "", {}, "sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA=="], + + "internmap": ["internmap@1.0.1", "", {}, "sha512-lDB5YccMydFBtasVtxnZ3MRBHuaoE8GKsppq+EchKL2U4nK/DmEpPHNH8MZe5HkMtpSiTSOZwfN0tzYjO/lJEw=="], + + "is-alphabetical": ["is-alphabetical@2.0.1", "", {}, "sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ=="], + + "is-alphanumerical": ["is-alphanumerical@2.0.1", "", { "dependencies": { "is-alphabetical": "^2.0.0", "is-decimal": "^2.0.0" } }, "sha512-hmbYhX/9MUMF5uh7tOXyK/n0ZvWpad5caBA17GsC6vyuCqaWliRG5K1qS9inmUhEMaOBIW7/whAnSwveW/LtZw=="], + + "is-decimal": ["is-decimal@2.0.1", "", {}, "sha512-AAB9hiomQs5DXWcRB1rqsxGUstbRroFOPPVAomNk/3XHR5JyEZChOyTWe2oayKnsSsr/kcGqF+z6yuH6HHpN0A=="], + "is-extglob": ["is-extglob@2.1.1", "", {}, "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ=="], - "is-fullwidth-code-point": ["is-fullwidth-code-point@5.1.0", "", { "dependencies": { "get-east-asian-width": "^1.3.1" } }, "sha512-5XHYaSyiqADb4RnZ1Bdad6cPp8Toise4TzEjcOYDHZkTCbKgiUl7WTUCpNWHuxmDt91wnsZBc9xinNzopv3JMQ=="], + "is-fullwidth-code-point": ["is-fullwidth-code-point@3.0.0", "", {}, "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg=="], "is-glob": ["is-glob@4.0.3", "", { "dependencies": { "is-extglob": "^2.1.1" } }, "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg=="], + "is-hexadecimal": ["is-hexadecimal@2.0.1", "", {}, "sha512-DgZQp241c8oO6cA1SbTEWiXeoxV42vlcJxgH+B3hi1AiqqKruZR3ZGF8In3fj4+/y/7rHvlOZLZtgJ/4ttYGZg=="], + "is-interactive": ["is-interactive@2.0.0", "", {}, "sha512-qP1vozQRI+BMOPcjFzrjXuQvdak2pHNUMZoeG2eRbiSqyvbEf/wQtEOTOX1guk6E3t36RkaqiSt8A/6YElNxLQ=="], "is-number": ["is-number@7.0.0", "", {}, "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng=="], + "is-plain-obj": ["is-plain-obj@4.1.0", "", {}, "sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg=="], + + "is-port-reachable": ["is-port-reachable@4.0.0", "", {}, "sha512-9UoipoxYmSk6Xy7QFgRv2HDyaysmgSG75TFQs6S+3pDM7ZhKTF/bskZV+0UlABHzKjNVhPjYCLfeZUEg1wXxig=="], + "is-reference": ["is-reference@3.0.3", "", { "dependencies": { "@types/estree": "^1.0.6" } }, "sha512-ixkJoqQvAP88E6wLydLGGqCJsrFUnqoH6HnaczB8XmDH1oaWU+xxdptvikTgaEhtZ53Ky6YXiBuUI2WXLMCwjw=="], "is-subdir": ["is-subdir@1.2.0", "", { "dependencies": { "better-path-resolve": "1.0.0" } }, "sha512-2AT6j+gXe/1ueqbW6fLZJiIw3F8iXGJtt0yDrZaBhAZEG1raiTxKWU+IPqMCzQAXOUCKdA4UDMgacKH25XG2Cw=="], @@ -1061,6 +1509,12 @@ "jsonfile": ["jsonfile@4.0.0", "", { "optionalDependencies": { "graceful-fs": "^4.1.6" } }, "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg=="], + "katex": ["katex@0.18.10", "", { "dependencies": { "commander": "^15.0.0" }, "bin": { "katex": "cli.js" } }, "sha512-/B6p9eY9DX7aHBfpkHdpirDTZ5QH9xTwL9y837PWuzuv41O5jFdqNQwVQEQsimY0/iVNkwBY4+4hMfhQ7d4Dbw=="], + + "khroma": ["khroma@2.1.0", "", {}, "sha512-Ls993zuzfayK269Svk9hzpeGUKob/sIgZzyHYdjQoAdQetRKpOLj+k/QQQ/6Qi0Yz65mlROrfd+Ev+1+7dz9Kw=="], + + "layout-base": ["layout-base@1.0.2", "", {}, "sha512-8h2oVEZNktL4BH2JCOI90iD1yXwL6iNW7KcCKT2QZgQJR2vbqDsldCTPRU9NifTCqHZci57XvQQ15YTu+sTYPg=="], + "lightningcss": ["lightningcss@1.33.0", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.33.0", "lightningcss-darwin-arm64": "1.33.0", "lightningcss-darwin-x64": "1.33.0", "lightningcss-freebsd-x64": "1.33.0", "lightningcss-linux-arm-gnueabihf": "1.33.0", "lightningcss-linux-arm64-gnu": "1.33.0", "lightningcss-linux-arm64-musl": "1.33.0", "lightningcss-linux-x64-gnu": "1.33.0", "lightningcss-linux-x64-musl": "1.33.0", "lightningcss-win32-arm64-msvc": "1.33.0", "lightningcss-win32-x64-msvc": "1.33.0" } }, "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA=="], "lightningcss-android-arm64": ["lightningcss-android-arm64@1.33.0", "", { "os": "android", "cpu": "arm64" }, "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg=="], @@ -1093,24 +1547,158 @@ "locate-path": ["locate-path@5.0.0", "", { "dependencies": { "p-locate": "^4.1.0" } }, "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g=="], + "lodash-es": ["lodash-es@4.18.1", "", {}, "sha512-J8xewKD/Gk22OZbhpOVSwcs60zhd95ESDwezOFuA3/099925PdHJ7OFHNTGtajL3AlZkykD32HykiMo+BIBI8A=="], + "lodash.startcase": ["lodash.startcase@4.4.0", "", {}, "sha512-+WKqsK294HMSc2jEbNgpHpd0JfIBhp7rEV4aqXWqFr6AlXov+SlcgB1Fv01y2kGe3Gc8nMW7VA0SrGuSkRfIEg=="], "log-symbols": ["log-symbols@7.0.1", "", { "dependencies": { "is-unicode-supported": "^2.0.0", "yoctocolors": "^2.1.1" } }, "sha512-ja1E3yCr9i/0hmBVaM0bfwDjnGy8I/s6PP4DFp+yP+a+mrHO4Rm7DtmnqROTUkHIkqffC84YY7AeqX6oFk0WFg=="], "log-update": ["log-update@8.0.0", "", { "dependencies": { "ansi-escapes": "^7.3.0", "cli-cursor": "^5.0.0", "slice-ansi": "^9.0.0", "string-width": "^8.2.0", "strip-ansi": "^7.2.0", "wrap-ansi": "^10.0.0" } }, "sha512-lddSgOt3bPASrylL54ZSpy8nBHns+vBVSoILlVOx+dei300pnLRN958rj/EdlVLKuWlSESU3qdnDZdAI7FXYGg=="], - "lru-cache": ["lru-cache@5.1.1", "", { "dependencies": { "yallist": "^3.0.2" } }, "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w=="], + "longest-streak": ["longest-streak@3.1.0", "", {}, "sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g=="], + + "lru-cache": ["lru-cache@11.5.3", "", {}, "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg=="], + + "lucide-react": ["lucide-react@1.74.0", "", { "peerDependencies": { "@types/react": "*", "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" }, "optionalPeers": ["@types/react"] }, "sha512-A1doIs/1fj1WnPbtIT7WRiM6Kvw5NUg+BtkoOh3Shpr4obwSDVt6WxCEcNH56EWprzuCoKle1OF0RqIkojwL1A=="], "magic-string": ["magic-string@0.30.21", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="], + "markdown-extensions": ["markdown-extensions@2.0.0", "", {}, "sha512-o5vL7aDWatOTX8LzaS1WMoaoxIiLRQJuIKKe2wAw6IeULDHaqbiqiggmx+pKvZDb1Sj+pE46Sn1T7lCqfFtg1Q=="], + + "markdown-table": ["markdown-table@3.1.0", "", {}, "sha512-xpeSCdM+B+6P3ncfgaB7FoDbtJ30xAe6Z18TGT7AgXJsHqCElCICZovQqdRMm7kHgpTyYv36EupqewoFFSB8vw=="], + + "marked": ["marked@9.1.6", "", { "bin": { "marked": "bin/marked.js" } }, "sha512-jcByLnIFkd5gSXZmjNvS1TlmRhCXZjIzHYlaGkPlLIekG55JDR2Z4va9tZwCiP+/RDERiNhMOFu01xd6O5ct1Q=="], + + "marked-terminal": ["marked-terminal@7.3.1", "", { "dependencies": { "ansi-escapes": "^7.3.0", "ansi-regex": "^6.4.0", "chalk": "^5.6.2", "cli-highlight": "^2.1.11", "cli-table3": "^0.6.5", "node-emoji": "^2.2.0", "supports-hyperlinks": "^3.2.0" }, "peerDependencies": { "marked": ">=1 <19" } }, "sha512-B1eKs5mRiacjHHMlex1zn0zkVomz2/KWjD/dyA8WRQTXk2d15OzVjiK/iuPfvDFB27Gvr8p/u6MYgU0NY/O45w=="], + + "mdast-util-find-and-replace": ["mdast-util-find-and-replace@3.0.4", "", { "dependencies": { "@types/mdast": "^4.0.0", "escape-string-regexp": "^5.0.0", "unist-util-is": "^6.0.0", "unist-util-visit-parents": "^6.1.0" } }, "sha512-z4B5c6jrnJ1ltOQemhWYPBSAo6y42Z8Gt2yEgfgNTMcLSU59B8bfj8Z8AnAlJrBGLnqkdAUZ7jdDEqQw3KuipQ=="], + + "mdast-util-from-markdown": ["mdast-util-from-markdown@2.1.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "@types/unist": "^3.0.0", "decode-named-character-reference": "^1.0.0", "devlop": "^1.0.0", "mdast-util-to-string": "^4.0.0", "micromark": "^4.0.0", "micromark-util-decode-numeric-character-reference": "^2.0.0", "micromark-util-decode-string": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0", "unist-util-stringify-position": "^4.0.0" } }, "sha512-KRLgmPaP2H1ul2bpoJkOS+9pAcDAAj9Nu1mqLnh8NLeJG5tlvj42TH80PIGBpROWlRXLk0lDrWNuZCFy/tsB4A=="], + + "mdast-util-gfm": ["mdast-util-gfm@3.1.0", "", { "dependencies": { "mdast-util-from-markdown": "^2.0.0", "mdast-util-gfm-autolink-literal": "^2.0.0", "mdast-util-gfm-footnote": "^2.0.0", "mdast-util-gfm-strikethrough": "^2.0.0", "mdast-util-gfm-table": "^2.0.0", "mdast-util-gfm-task-list-item": "^2.0.0", "mdast-util-to-markdown": "^2.0.0" } }, "sha512-0ulfdQOM3ysHhCJ1p06l0b0VKlhU0wuQs3thxZQagjcjPrlFRqY215uZGHHJan9GEAXd9MbfPjFJz+qMkVR6zQ=="], + + "mdast-util-gfm-autolink-literal": ["mdast-util-gfm-autolink-literal@2.1.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "ccount": "^2.0.0", "devlop": "^1.0.0", "mdast-util-find-and-replace": "^3.0.0", "micromark-util-character": "^2.0.0" } }, "sha512-Jx6QSK8wDo558Bcf7q+1pe0v81g2PVs09Hlvu9xJHmCFRF3sAPW7vXFVIAwBncs3sde92WbsVqNxwdqViA2XnQ=="], + + "mdast-util-gfm-footnote": ["mdast-util-gfm-footnote@2.1.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "devlop": "^1.1.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0" } }, "sha512-sqpDWlsHn7Ac9GNZQMeUzPQSMzR6Wv0WKRNvQRg0KqHh02fpTz69Qc1QSseNX29bhz1ROIyNyxExfawVKTm1GQ=="], + + "mdast-util-gfm-strikethrough": ["mdast-util-gfm-strikethrough@2.0.1", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.0.0" } }, "sha512-OuJHqvr455pwu2OaOrir7dbzqs4jlWKOtlu9L6GjcIjjQwNyw02VntQsr/Ek6/A13vgnXfUhBekWRUP1OkNivw=="], + + "mdast-util-gfm-table": ["mdast-util-gfm-table@2.0.1", "", { "dependencies": { "@types/mdast": "^4.0.0", "devlop": "^1.0.0", "markdown-table": "^3.0.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.0.0", "mdast-util-to-string": "^4.0.0", "unist-util-visit": "^5.0.0" } }, "sha512-fiIjPrAy4kz68/eFbPHhsiWDGHhqUSVoU1XsfLM5DsEPXw7MxgiVVyulUggFRckVWeT1KXQXkg5vm3kv4oMSOA=="], + + "mdast-util-gfm-task-list-item": ["mdast-util-gfm-task-list-item@2.0.1", "", { "dependencies": { "@types/mdast": "^4.0.0", "devlop": "^1.0.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.0.0" } }, "sha512-jXVO1hvB2hs82g1esi7I9nIJDqiijbQLIyH2jDUb5s7jIAZMr/79h0VHSq7XHKTqpLARRm+DDNjduB7S9+6XZA=="], + + "mdast-util-mdx": ["mdast-util-mdx@3.0.0", "", { "dependencies": { "mdast-util-from-markdown": "^2.0.0", "mdast-util-mdx-expression": "^2.0.0", "mdast-util-mdx-jsx": "^3.0.0", "mdast-util-mdxjs-esm": "^2.0.0", "mdast-util-to-markdown": "^2.0.0" } }, "sha512-JfbYLAW7XnYTTbUsmpu0kdBUVe+yKVJZBItEjwyYJiDJuZ9w4eeaqks4HQO+R7objWgS2ymV60GYpI14Ug554w=="], + + "mdast-util-mdx-expression": ["mdast-util-mdx-expression@2.0.1", "", { "dependencies": { "@types/estree-jsx": "^1.0.0", "@types/hast": "^3.0.0", "@types/mdast": "^4.0.0", "devlop": "^1.0.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.0.0" } }, "sha512-J6f+9hUp+ldTZqKRSg7Vw5V6MqjATc+3E4gf3CFNcuZNWD8XdyI6zQ8GqH7f8169MM6P7hMBRDVGnn7oHB9kXQ=="], + + "mdast-util-mdx-jsx": ["mdast-util-mdx-jsx@3.2.1", "", { "dependencies": { "@types/estree-jsx": "^1.0.0", "@types/hast": "^3.0.0", "@types/mdast": "^4.0.0", "@types/unist": "^3.0.0", "ccount": "^2.0.0", "devlop": "^1.1.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.0.0", "parse-entities": "^4.0.0", "stringify-entities": "^4.0.0", "unist-util-stringify-position": "^4.0.0", "vfile-message": "^4.0.0" } }, "sha512-oXp1GIa+E9IwIs3a106+tr3Bz2MlTTBvlXjOZMoIat11kk7vjqgmBnksB9WHmWv+gZh7k3IUgpAHlwHB7DH4GQ=="], + + "mdast-util-mdxjs-esm": ["mdast-util-mdxjs-esm@2.0.1", "", { "dependencies": { "@types/estree-jsx": "^1.0.0", "@types/hast": "^3.0.0", "@types/mdast": "^4.0.0", "devlop": "^1.0.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.0.0" } }, "sha512-EcmOpxsZ96CvlP03NghtH1EsLtr0n9Tm4lPUJUBccV9RwUOneqSycg19n5HGzCf+10LozMRSObtVr3ee1WoHtg=="], + + "mdast-util-phrasing": ["mdast-util-phrasing@4.1.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "unist-util-is": "^6.0.0" } }, "sha512-TqICwyvJJpBwvGAMZjj4J2n0X8QWp21b9l0o7eXyVJ25YNWYbJDVIyD1bZXE6WtV6RmKJVYmQAKWa0zWOABz2w=="], + + "mdast-util-to-hast": ["mdast-util-to-hast@13.2.2", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/mdast": "^4.0.0", "@ungap/structured-clone": "^1.0.0", "devlop": "^1.0.0", "micromark-util-sanitize-uri": "^2.0.0", "trim-lines": "^3.0.0", "unist-util-position": "^5.0.0", "unist-util-visit": "^5.0.0", "vfile": "^6.0.0" } }, "sha512-l2pnmOuqs+SGLVpTVXnRLQu5v1AzvDe181404fbXzzqObVxrAnnVxapAP27pUwzLBL/ABIkgUhGlPVU7QSvIFg=="], + + "mdast-util-to-markdown": ["mdast-util-to-markdown@2.2.3", "", { "dependencies": { "@types/mdast": "^4.0.0", "@types/unist": "^3.0.0", "longest-streak": "^3.0.0", "mdast-util-phrasing": "^4.0.0", "mdast-util-to-string": "^4.0.0", "micromark-util-character": "^2.0.0", "micromark-util-classify-character": "^2.0.0", "micromark-util-decode-string": "^2.0.0", "micromark-util-html-tag-name": "^2.0.0", "unist-util-visit": "^5.0.0", "zwitch": "^2.0.0" } }, "sha512-dImdB6VZRMRac1SwAW6o1c0ESk/7pFFAMCMuKM+9v7LpTSthMM5nzXpqKw4Mjo66aXVKhNkyrP4bMB9MurPyWg=="], + + "mdast-util-to-string": ["mdast-util-to-string@4.0.0", "", { "dependencies": { "@types/mdast": "^4.0.0" } }, "sha512-0H44vDimn51F0YwvxSJSm0eCDOJTRlmN0R1yBh4HLj9wiV1Dn0QoXGbvFAWj2hSItVTlCmBF1hqKlIyUBVFLPg=="], + "merge-anything": ["merge-anything@5.1.7", "", { "dependencies": { "is-what": "^4.1.8" } }, "sha512-eRtbOb1N5iyH0tkQDAoQ4Ipsp/5qSR79Dzrz8hEPxRX10RWWR/iQXdoKmBSRCThY1Fh5EhISDtpSc93fpxUniQ=="], "merge2": ["merge2@1.4.1", "", {}, "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg=="], + "mermaid": ["mermaid@12.3.0", "", { "dependencies": { "@braintree/sanitize-url": "^7.1.2", "@iconify/utils": "^3.0.2", "@mermaid-js/parser": "^2.0.1", "@types/d3": "^7.4.3", "@upsetjs/venn.js": "^2.0.0", "chevrotain": "~13.2.0", "cytoscape": "^3.34.0", "cytoscape-cose-bilkent": "^4.1.0", "cytoscape-fcose": "^2.2.0", "d3": "^7.9.0", "d3-sankey": "^0.12.3", "dagre-d3-es": "7.0.14", "dayjs": "^1.11.21", "dompurify": "^3.4.17", "elkjs": "^0.12.0", "es-toolkit": "^1.45.1", "katex": "^0.18.0", "khroma": "^2.1.0", "marked": "^16.3.0", "roughjs": "^4.6.6", "stylis": "^4.3.6", "ts-dedent": "^2.2.0" } }, "sha512-4113TdXeLAsMruJ79OpFL5O8+LTFXhQqZ260rF3tgUmiNAtRm4Uume04I+65PRN6yZ69J4f8rVYWW8zRk65UYw=="], + + "micromark": ["micromark@4.0.3", "", { "dependencies": { "@types/debug": "^4.0.0", "debug": "^4.0.0", "decode-named-character-reference": "^1.0.0", "devlop": "^1.0.0", "micromark-core-commonmark": "^2.0.0", "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-chunked": "^2.0.0", "micromark-util-combine-extensions": "^2.0.0", "micromark-util-decode-numeric-character-reference": "^2.0.0", "micromark-util-edit-map": "^1.0.0", "micromark-util-encode": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-resolve-all": "^2.0.0", "micromark-util-sanitize-uri": "^2.0.0", "micromark-util-subtokenize": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-oGYfQzHSG5dOMovQcJ3fyTmZlWAWpi0XA0sJwJs+i6OT88o1+Jtw/8z0CmdowSLxGhhFK89rQ/oXph/wN02PNw=="], + + "micromark-core-commonmark": ["micromark-core-commonmark@2.0.4", "", { "dependencies": { "decode-named-character-reference": "^1.0.0", "devlop": "^1.0.0", "micromark-factory-destination": "^2.0.0", "micromark-factory-label": "^2.0.0", "micromark-factory-space": "^2.1.0", "micromark-factory-title": "^2.0.0", "micromark-factory-whitespace": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-chunked": "^2.0.0", "micromark-util-classify-character": "^2.0.0", "micromark-util-edit-map": "^1.0.0", "micromark-util-html-tag-name": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-resolve-all": "^2.0.0", "micromark-util-subtokenize": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.3" } }, "sha512-wxEeE8v8XVvOrxn1TZj74qYhAtTQsSqufHVS3uNVyT1MupXxhyaHk8/9xDNPh9BmL77QNDgWTkZ3RsYHB2ry7w=="], + + "micromark-extension-gfm": ["micromark-extension-gfm@3.0.0", "", { "dependencies": { "micromark-extension-gfm-autolink-literal": "^2.0.0", "micromark-extension-gfm-footnote": "^2.0.0", "micromark-extension-gfm-strikethrough": "^2.0.0", "micromark-extension-gfm-table": "^2.0.0", "micromark-extension-gfm-tagfilter": "^2.0.0", "micromark-extension-gfm-task-list-item": "^2.0.0", "micromark-util-combine-extensions": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-vsKArQsicm7t0z2GugkCKtZehqUm31oeGBV/KVSorWSy8ZlNAv7ytjFhvaryUiCUJYqs+NoE6AFhpQvBTM6Q4w=="], + + "micromark-extension-gfm-autolink-literal": ["micromark-extension-gfm-autolink-literal@2.1.0", "", { "dependencies": { "micromark-util-character": "^2.0.0", "micromark-util-sanitize-uri": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-oOg7knzhicgQ3t4QCjCWgTmfNhvQbDDnJeVu9v81r7NltNCVmhPy1fJRX27pISafdjL+SVc4d3l48Gb6pbRypw=="], + + "micromark-extension-gfm-footnote": ["micromark-extension-gfm-footnote@2.1.0", "", { "dependencies": { "devlop": "^1.0.0", "micromark-core-commonmark": "^2.0.0", "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-sanitize-uri": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-/yPhxI1ntnDNsiHtzLKYnE3vf9JZ6cAisqVDauhp4CEHxlb4uoOTxOCJ+9s51bIB8U1N1FJ1RXOKTIlD5B/gqw=="], + + "micromark-extension-gfm-strikethrough": ["micromark-extension-gfm-strikethrough@2.1.0", "", { "dependencies": { "devlop": "^1.0.0", "micromark-util-chunked": "^2.0.0", "micromark-util-classify-character": "^2.0.0", "micromark-util-resolve-all": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-ADVjpOOkjz1hhkZLlBiYA9cR2Anf8F4HqZUO6e5eDcPQd0Txw5fxLzzxnEkSkfnD0wziSGiv7sYhk/ktvbf1uw=="], + + "micromark-extension-gfm-table": ["micromark-extension-gfm-table@2.1.2", "", { "dependencies": { "devlop": "^1.0.0", "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-pRzm4kDTu0MjlmBkxmS9yYhw60nncfcEwu9NNdPFSQEFXS95ZKyIIyTSHu/o3ReBUrLKYEq+7YaXCRn/bPB4MA=="], + + "micromark-extension-gfm-tagfilter": ["micromark-extension-gfm-tagfilter@2.0.0", "", { "dependencies": { "micromark-util-types": "^2.0.0" } }, "sha512-xHlTOmuCSotIA8TW1mDIM6X2O1SiX5P9IuDtqGonFhEK0qgRI4yeC6vMxEV2dgyr2TiD+2PQ10o+cOhdVAcwfg=="], + + "micromark-extension-gfm-task-list-item": ["micromark-extension-gfm-task-list-item@2.1.0", "", { "dependencies": { "devlop": "^1.0.0", "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-qIBZhqxqI6fjLDYFTBIa4eivDMnP+OZqsNwmQ3xNLE4Cxwc+zfQEfbs6tzAo2Hjq+bh6q5F+Z8/cksrLFYWQQw=="], + + "micromark-extension-mdx-expression": ["micromark-extension-mdx-expression@3.0.1", "", { "dependencies": { "@types/estree": "^1.0.0", "devlop": "^1.0.0", "micromark-factory-mdx-expression": "^2.0.0", "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-events-to-acorn": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-dD/ADLJ1AeMvSAKBwO22zG22N4ybhe7kFIZ3LsDI0GlsNr2A3KYxb0LdC1u5rj4Nw+CHKY0RVdnHX8vj8ejm4Q=="], + + "micromark-extension-mdx-jsx": ["micromark-extension-mdx-jsx@3.0.2", "", { "dependencies": { "@types/estree": "^1.0.0", "devlop": "^1.0.0", "estree-util-is-identifier-name": "^3.0.0", "micromark-factory-mdx-expression": "^2.0.0", "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-events-to-acorn": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0", "vfile-message": "^4.0.0" } }, "sha512-e5+q1DjMh62LZAJOnDraSSbDMvGJ8x3cbjygy2qFEi7HCeUT4BDKCvMozPozcD6WmOt6sVvYDNBKhFSz3kjOVQ=="], + + "micromark-extension-mdx-md": ["micromark-extension-mdx-md@2.0.0", "", { "dependencies": { "micromark-util-types": "^2.0.0" } }, "sha512-EpAiszsB3blw4Rpba7xTOUptcFeBFi+6PY8VnJ2hhimH+vCQDirWgsMpz7w1XcZE7LVrSAUGb9VJpG9ghlYvYQ=="], + + "micromark-extension-mdxjs": ["micromark-extension-mdxjs@3.0.0", "", { "dependencies": { "acorn": "^8.0.0", "acorn-jsx": "^5.0.0", "micromark-extension-mdx-expression": "^3.0.0", "micromark-extension-mdx-jsx": "^3.0.0", "micromark-extension-mdx-md": "^2.0.0", "micromark-extension-mdxjs-esm": "^3.0.0", "micromark-util-combine-extensions": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-A873fJfhnJ2siZyUrJ31l34Uqwy4xIFmvPY1oj+Ean5PHcPBYzEsvqvWGaWcfEIr11O5Dlw3p2y0tZWpKHDejQ=="], + + "micromark-extension-mdxjs-esm": ["micromark-extension-mdxjs-esm@3.0.0", "", { "dependencies": { "@types/estree": "^1.0.0", "devlop": "^1.0.0", "micromark-core-commonmark": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-events-to-acorn": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0", "unist-util-position-from-estree": "^2.0.0", "vfile-message": "^4.0.0" } }, "sha512-DJFl4ZqkErRpq/dAPyeWp15tGrcrrJho1hKK5uBS70BCtfrIFg81sqcTVu3Ta+KD1Tk5vAtBNElWxtAa+m8K9A=="], + + "micromark-factory-destination": ["micromark-factory-destination@2.0.1", "", { "dependencies": { "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-Xe6rDdJlkmbFRExpTOmRj9N3MaWmbAgdpSrBQvCFqhezUn4AHqJHbaEnfbVYYiexVSs//tqOdY/DxhjdCiJnIA=="], + + "micromark-factory-label": ["micromark-factory-label@2.0.1", "", { "dependencies": { "devlop": "^1.0.0", "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-VFMekyQExqIW7xIChcXn4ok29YE3rnuyveW3wZQWWqF4Nv9Wk5rgJ99KzPvHjkmPXF93FXIbBp6YdW3t71/7Vg=="], + + "micromark-factory-mdx-expression": ["micromark-factory-mdx-expression@2.0.3", "", { "dependencies": { "@types/estree": "^1.0.0", "devlop": "^1.0.0", "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-events-to-acorn": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0", "unist-util-position-from-estree": "^2.0.0", "vfile-message": "^4.0.0" } }, "sha512-kQnEtA3vzucU2BkrIa8/VaSAsP+EJ3CKOvhMuJgOEGg9KDC6OAY6nSnNDVRiVNRqj7Y4SlSzcStaH/5jge8JdQ=="], + + "micromark-factory-space": ["micromark-factory-space@2.1.0", "", { "dependencies": { "micromark-util-character": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-fS8hnLIjnjvdQIj39Geug8wWsR0HrYZ43KShKxNfwT7t2LOHo/LbWZEzEaSOjwtjdCsjoE6syHhonEzW0zv0+Q=="], + + "micromark-factory-title": ["micromark-factory-title@2.0.1", "", { "dependencies": { "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-5bZ+3CjhAd9eChYTHsjy6TGxpOFSKgKKJPJxr293jTbfry2KDoWkhBb6TcPVB4NmzaPhMs1Frm9AZH7OD4Cjzw=="], + + "micromark-factory-whitespace": ["micromark-factory-whitespace@2.0.1", "", { "dependencies": { "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-Ob0nuZ3PKt/n0hORHyvoD9uZhr+Za8sFoP+OnMcnWK5lngSzALgQYKMr9RJVOWLqQYuyn6ulqGWSXdwf6F80lQ=="], + + "micromark-util-character": ["micromark-util-character@2.1.1", "", { "dependencies": { "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-wv8tdUTJ3thSFFFJKtpYKOYiGP2+v96Hvk4Tu8KpCAsTMs6yi+nVmGh1syvSCsaxz45J6Jbw+9DD6g97+NV67Q=="], + + "micromark-util-chunked": ["micromark-util-chunked@2.0.1", "", { "dependencies": { "micromark-util-symbol": "^2.0.0" } }, "sha512-QUNFEOPELfmvv+4xiNg2sRYeS/P84pTW0TCgP5zc9FpXetHY0ab7SxKyAQCNCc1eK0459uoLI1y5oO5Vc1dbhA=="], + + "micromark-util-classify-character": ["micromark-util-classify-character@2.0.1", "", { "dependencies": { "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-K0kHzM6afW/MbeWYWLjoHQv1sgg2Q9EccHEDzSkxiP/EaagNzCm7T/WMKZ3rjMbvIpvBiZgwR3dKMygtA4mG1Q=="], + + "micromark-util-combine-extensions": ["micromark-util-combine-extensions@2.0.1", "", { "dependencies": { "micromark-util-chunked": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-OnAnH8Ujmy59JcyZw8JSbK9cGpdVY44NKgSM7E9Eh7DiLS2E9RNQf0dONaGDzEG9yjEl5hcqeIsj4hfRkLH/Bg=="], + + "micromark-util-decode-numeric-character-reference": ["micromark-util-decode-numeric-character-reference@2.0.2", "", { "dependencies": { "micromark-util-symbol": "^2.0.0" } }, "sha512-ccUbYk6CwVdkmCQMyr64dXz42EfHGkPQlBj5p7YVGzq8I7CtjXZJrubAYezf7Rp+bjPseiROqe7G6foFd+lEuw=="], + + "micromark-util-decode-string": ["micromark-util-decode-string@2.0.1", "", { "dependencies": { "decode-named-character-reference": "^1.0.0", "micromark-util-character": "^2.0.0", "micromark-util-decode-numeric-character-reference": "^2.0.0", "micromark-util-symbol": "^2.0.0" } }, "sha512-nDV/77Fj6eH1ynwscYTOsbK7rR//Uj0bZXBwJZRfaLEJ1iGBR6kIfNmlNqaqJf649EP0F3NWNdeJi03elllNUQ=="], + + "micromark-util-edit-map": ["micromark-util-edit-map@1.0.0", "", { "dependencies": { "micromark-util-types": "^2.0.0" } }, "sha512-Pa2ljlsEL6sVwFaYeyrOLSYbQt73JvGbPOYFq+9AElXiSnfI5Q4465RRZ1sHv7lDjDOnGRDDaqPXqClqWK/q1Q=="], + + "micromark-util-encode": ["micromark-util-encode@2.0.1", "", {}, "sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw=="], + + "micromark-util-events-to-acorn": ["micromark-util-events-to-acorn@2.0.3", "", { "dependencies": { "@types/estree": "^1.0.0", "@types/unist": "^3.0.0", "devlop": "^1.0.0", "estree-util-visit": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0", "vfile-message": "^4.0.0" } }, "sha512-jmsiEIiZ1n7X1Rr5k8wVExBQCg5jy4UXVADItHmNk1zkwEVhBuIUKRu3fqv+hs4nxLISi2DQGlqIOGiFxgbfHg=="], + + "micromark-util-html-tag-name": ["micromark-util-html-tag-name@2.0.1", "", {}, "sha512-2cNEiYDhCWKI+Gs9T0Tiysk136SnR13hhO8yW6BGNyhOC4qYFnwF1nKfD3HFAIXA5c45RrIG1ub11GiXeYd1xA=="], + + "micromark-util-normalize-identifier": ["micromark-util-normalize-identifier@2.0.1", "", { "dependencies": { "micromark-util-symbol": "^2.0.0" } }, "sha512-sxPqmo70LyARJs0w2UclACPUUEqltCkJ6PhKdMIDuJ3gSf/Q+/GIe3WKl0Ijb/GyH9lOpUkRAO2wp0GVkLvS9Q=="], + + "micromark-util-resolve-all": ["micromark-util-resolve-all@2.0.1", "", { "dependencies": { "micromark-util-types": "^2.0.0" } }, "sha512-VdQyxFWFT2/FGJgwQnJYbe1jjQoNTS4RjglmSjTUlpUMa95Htx9NHeYW4rGDJzbjvCsl9eLjMQwGeElsqmzcHg=="], + + "micromark-util-sanitize-uri": ["micromark-util-sanitize-uri@2.0.1", "", { "dependencies": { "micromark-util-character": "^2.0.0", "micromark-util-encode": "^2.0.0", "micromark-util-symbol": "^2.0.0" } }, "sha512-9N9IomZ/YuGGZZmQec1MbgxtlgougxTodVwDzzEouPKo3qFWvymFHWcnDi2vzV1ff6kas9ucW+o3yzJK9YB1AQ=="], + + "micromark-util-subtokenize": ["micromark-util-subtokenize@2.1.0", "", { "dependencies": { "devlop": "^1.0.0", "micromark-util-chunked": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-XQLu552iSctvnEcgXw6+Sx75GflAPNED1qx7eBJ+wydBb2KCbRZe+NwvIEEMM83uml1+2WSXpBAcp9IUCgCYWA=="], + + "micromark-util-symbol": ["micromark-util-symbol@2.0.1", "", {}, "sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q=="], + + "micromark-util-types": ["micromark-util-types@2.0.3", "", {}, "sha512-oxB2Ik03hI0gv+VNn9tnh1t1YEe9MDPptViAEgfdf3YQHsn0pzGTgCdlSCJXcwhqm8phaEuM7zeEu3QQzVBrPg=="], + "micromatch": ["micromatch@4.0.8", "", { "dependencies": { "braces": "^3.0.3", "picomatch": "^2.3.1" } }, "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA=="], + "mime-db": ["mime-db@1.54.0", "", {}, "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ=="], + + "mime-types": ["mime-types@2.1.18", "", { "dependencies": { "mime-db": "~1.33.0" } }, "sha512-lc/aahn+t4/SWV/qcmumYjymLsWfN3ELhpmVuUFjgsORruuZPVSwAQryq+HHGvO/SI2KVX26bx+En+zhM8g8hQ=="], + "mimic-function": ["mimic-function@5.0.1", "", {}, "sha512-VP79XUPxV2CigYP3jWwAUFSku2aKqBH7uTAapFWCBqutsbmDo96KY5o8uh6U+/YSIn5OxJnXp73beVkpqMIGhA=="], + "minimatch": ["minimatch@3.1.5", "", { "dependencies": { "brace-expansion": "^1.1.7" } }, "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w=="], + + "minimist": ["minimist@1.2.8", "", {}, "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA=="], + + "motion": ["motion@14.14.0", "", { "dependencies": { "framer-motion": "14.14.0", "tslib": "^2.4.0" }, "peerDependencies": { "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0", "remix": "^3.1.0" }, "optionalPeers": ["react", "react-dom", "remix"] }, "sha512-a306U6sV5VKq1abtzKiinB+UQjiY88jrsvQzWORP3WPv/DFANyoYVlPbdnmJPMEbusyPXB4GyQJVANaq/pSIYQ=="], + + "motion-dom": ["motion-dom@14.14.0", "", { "dependencies": { "motion-utils": "14.7.0" } }, "sha512-IAxcKhYkuQA2W0Tlx1AvVgImfqEoF3/t3IovbPQJlYkefmGsmrXjn967lMII5VmFmLpQEab4+ZkHo/ijJ4Esig=="], + + "motion-utils": ["motion-utils@14.7.0", "", {}, "sha512-woO0/Nb7ys75f94fjvQi/6leiHGvZUYkeHUPEZ3vxsV+9OpEVhkxp01x8MlRwX0zt31EqgXsKDAoBoJLC148Tw=="], + "mri": ["mri@1.2.0", "", {}, "sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA=="], "mrmime": ["mrmime@2.0.1", "", {}, "sha512-Y3wQdFg2Va6etvQ5I82yUhGdsKrcYox6p7FfL1LbK2J4V01F9TGlepTIhnK24t7koZibmg82KGglhA1XK5IsLQ=="], @@ -1125,12 +1713,20 @@ "mute-stream": ["mute-stream@3.0.0", "", {}, "sha512-dkEJPVvun4FryqBmZ5KhDo0K9iDXAwn08tMLDinNdRBNPcYEDiWYysLcc6k3mjTMlbP9KyylvRpd4wFtwrT9rw=="], + "mz": ["mz@2.7.0", "", { "dependencies": { "any-promise": "^1.0.0", "object-assign": "^4.0.1", "thenify-all": "^1.0.0" } }, "sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q=="], + "nanoid": ["nanoid@3.3.20", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ=="], + "negotiator": ["negotiator@0.6.4", "", {}, "sha512-myRT3DiWPHqho5PrJaIRyaMv2kgYf0mUVgBNOYMuCH5Ki1yEiQaf/ZJuQ62nvpc44wL5WDbTX7yGJi1Neevw8w=="], + "next": ["next@16.4.6", "", { "dependencies": { "@next/env": "16.4.6", "@swc/helpers": "0.5.23", "baseline-browser-mapping": "^2.9.19", "caniuse-lite": "^1.0.30001579", "postcss": "8.5.23", "styled-jsx": "5.1.6" }, "optionalDependencies": { "@next/swc-darwin-arm64": "16.4.6", "@next/swc-darwin-x64": "16.4.6", "@next/swc-linux-arm64-gnu": "16.4.6", "@next/swc-linux-arm64-musl": "16.4.6", "@next/swc-linux-x64-gnu": "16.4.6", "@next/swc-linux-x64-musl": "16.4.6", "@next/swc-win32-arm64-msvc": "16.4.6", "@next/swc-win32-x64-msvc": "16.4.6", "sharp": "^0.35.5" }, "peerDependencies": { "@opentelemetry/api": "^1.1.0", "@playwright/test": "^1.51.1", "babel-plugin-react-compiler": "*", "react": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0", "react-dom": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0", "sass": "^1.3.0" }, "optionalPeers": ["@opentelemetry/api", "@playwright/test", "babel-plugin-react-compiler", "sass"], "bin": { "next": "dist/bin/next" } }, "sha512-QZJiYhaZLJMo2KpkQGQIwvmd79WVsAWeYIU554a8d7zArS3si/IRy3lBNV/rtYhE70oLwdLYhPAXLPx8HwcwtA=="], + "next-themes": ["next-themes@0.4.6", "", { "peerDependencies": { "react": "^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc", "react-dom": "^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc" } }, "sha512-pZvgD5L0IEvX5/9GWyHMf3m8BKiVQwsCMHfoFosXtXBMnaS0ZnIJ9ST4b4NqLVKDEm8QBxoNNGNaBv2JNF6XNA=="], + "node-addon-api": ["node-addon-api@6.1.0", "", {}, "sha512-+eawOlIgy680F0kBzPUNFhMZGtJ1YmqM6l4+Crf4IkImjYrO/mqPwRMh352g23uIaQKFItcQ64I7KMaJxHgAVA=="], + "node-emoji": ["node-emoji@2.2.0", "", { "dependencies": { "@sindresorhus/is": "^4.6.0", "char-regex": "^1.0.2", "emojilib": "^2.4.0", "skin-tone": "^2.0.0" } }, "sha512-Z3lTE9pLaJF47NyMhd4ww1yFTAP8YhYI8SleJiHzM46Fgpm5cnNzSl9XfzFNqbaz+VlJrIj3fXQ4DeN1Rjm6cw=="], + "node-fetch": ["node-fetch@2.7.0", "", { "dependencies": { "whatwg-url": "^5.0.0" }, "peerDependencies": { "encoding": "^0.1.0" }, "optionalPeers": ["encoding"] }, "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A=="], "node-gyp-build-optional-packages": ["node-gyp-build-optional-packages@5.2.2", "", { "dependencies": { "detect-libc": "^2.0.1" }, "bin": { "node-gyp-build-optional-packages": "bin.js", "node-gyp-build-optional-packages-optional": "optional.js", "node-gyp-build-optional-packages-test": "build-test.js" } }, "sha512-s+w+rBWnpTMwSFbaE0UXsRlg7hU4FjekKU4eyAih5T8nJuNZT1nNsskXpxmeqSK9UzkBl6UgRlnKc8hz8IEqOw=="], @@ -1139,12 +1735,22 @@ "npm-package-arg": ["npm-package-arg@14.0.0", "", { "dependencies": { "hosted-git-info": "^10.1.0", "proc-log": "^7.0.0", "semver": "^7.3.5", "validate-npm-package-name": "^8.0.0" } }, "sha512-69XQh3k+dtGa1p+7RaR57IuG3rCko96xr/nUfN4yDYBXbTYICiWcOpsFKLN2GtGE9cyIljE+f1exnaYt9MvM+Q=="], + "npm-to-yarn": ["npm-to-yarn@3.2.0", "", {}, "sha512-K1HmQeZT2HrjpsR6KgqbN2FAXL2NrJJmNUSD9ck7HGTVu1JKXox8n9SB+tjbU8m8JGLF4OscrroPepew/L7/Xw=="], + "nth-check": ["nth-check@3.0.1", "", { "dependencies": { "boolbase": "^2.0.0" } }, "sha512-GX0gsdbGVCgnRgbeGaubfjpBXyYRWOOCVeYh08bSQvDZqxz5ndXs1OTfAt/h36G1xvI94YIspsI0sVFqAV9+RQ=="], + "object-assign": ["object-assign@4.1.1", "", {}, "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg=="], + "obug": ["obug@3.0.0", "", {}, "sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw=="], + "on-headers": ["on-headers@1.1.0", "", {}, "sha512-737ZY3yNnXy37FHkQxPzt4UZ2UWPWiCZWLvFZ4fu5cueciegX0zGPnrlY6bwRg4FdQOe9YU8MkmJwGhoMybl8A=="], + "onetime": ["onetime@7.0.0", "", { "dependencies": { "mimic-function": "^5.0.0" } }, "sha512-VXJjc87FScF88uafS3JllDgvAm+c/Slfz06lorj2uAY34rlUu0Nt+v8wreiImcrgAjjIHp1rXpTDlLOGw29WwQ=="], + "oniguruma-parser": ["oniguruma-parser@0.12.2", "", {}, "sha512-6HVa5oIrgMC6aA6WF6XyyqbhRPJrKR02L20+2+zpDtO5QAzGHAUGw5TKQvwi5vctNnRHkJYmjAhRVQF2EKdTQw=="], + + "oniguruma-to-es": ["oniguruma-to-es@4.3.6", "", { "dependencies": { "oniguruma-parser": "^0.12.2", "regex": "^6.1.0", "regex-recursion": "^6.0.2" } }, "sha512-csuQ9x3Yr0cEIs/Zgx/OEt9iBw9vqIunAPQkx19R/fiMq2oGVTgcMqO/V3Ybqefr1TBvosI6jU539ksaBULJyA=="], + "ora": ["ora@9.4.1", "", { "dependencies": { "chalk": "^5.6.2", "cli-cursor": "^5.0.0", "cli-spinners": "^3.2.0", "is-interactive": "^2.0.0", "is-unicode-supported": "^2.1.0", "log-symbols": "^7.0.1", "stdin-discarder": "^0.3.2", "string-width": "^8.1.0" } }, "sha512-6VlU9MLXbjVQD04AZCMX28hVtA5bUoadvUqO76MUCVA0ilwJbMiHsITRPfyVm6p/BC0Av/BXMujx39WCe1LEqw=="], "ordered-binary": ["ordered-binary@1.6.1", "", {}, "sha512-QkCdPooczexPLiXIrbVOPYkR3VO3T6v2OyKRkR1Xbhpy7/LAVXwahnRCgRp78Oe/Ehf0C/HATAxfSr6eA1oX+w=="], @@ -1165,18 +1771,28 @@ "package-manager-detector": ["package-manager-detector@0.2.11", "", { "dependencies": { "quansync": "^0.2.7" } }, "sha512-BEnLolu+yuz22S56CU1SUKq3XC3PkwD5wv4ikR4MfGvnRVcmzXR9DwSlW2fEamyTPyXHomBJRzgapeuBvRNzJQ=="], + "parse-entities": ["parse-entities@4.0.2", "", { "dependencies": { "@types/unist": "^2.0.0", "character-entities-legacy": "^3.0.0", "character-reference-invalid": "^2.0.0", "decode-named-character-reference": "^1.0.0", "is-alphanumerical": "^2.0.0", "is-decimal": "^2.0.0", "is-hexadecimal": "^2.0.0" } }, "sha512-GG2AQYWoLgL877gQIKeRPGO1xF9+eG1ujIb5soS5gPvLQ1y2o8FL90w2QWNdf9I361Mpp7726c+lj3U0qK1uGw=="], + "parse5": ["parse5@8.0.1", "", { "dependencies": { "entities": "^8.0.0" } }, "sha512-z1e/HMG90obSGeidlli3hj7cbocou0/wa5HacvI3ASx34PecNjNQeaHNo5WIZpWofN9kgkqV1q5YvXe3F0FoPw=="], "parse5-html-rewriting-stream": ["parse5-html-rewriting-stream@8.0.1", "", { "dependencies": { "entities": "^8.0.0", "parse5": "^8.0.0", "parse5-sax-parser": "^8.0.0" } }, "sha512-NaRku2aMpUN1Sh1Gyk1KWUh2A7EJx2c6qYzvwsPtqhoHoaURshdrceYK3LunVCm3WHhm6FS7Vcczbvdh3/UIVw=="], + "parse5-htmlparser2-tree-adapter": ["parse5-htmlparser2-tree-adapter@6.0.1", "", { "dependencies": { "parse5": "^6.0.1" } }, "sha512-qPuWvbLgvDGilKc5BoicRovlT4MtYT6JfJyBOMDsKoiT+GiuP5qyrPCnR9HcPECIJJmZh5jRndyNThnhhb/vlA=="], + "parse5-sax-parser": ["parse5-sax-parser@8.0.0", "", { "dependencies": { "parse5": "^8.0.0" } }, "sha512-/dQ8UzHZwnrzs3EvDj6IkKrD/jIZyTlB+8XrHJvcjNgRdmWruNdN9i9RK/JtxakmlUdPwKubKPTCqvbTgzGhrw=="], "path-browserify": ["path-browserify@1.0.1", "", {}, "sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g=="], + "path-data-parser": ["path-data-parser@0.1.0", "", {}, "sha512-NOnmBpt5Y2RWbuv0LMzsayp3lVylAHLPUTut412ZA3l+C4uw4ZVkQbjShYCQ8TCpUMdPapr4YjUqLYD6v68j+w=="], + "path-exists": ["path-exists@4.0.0", "", {}, "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w=="], + "path-is-inside": ["path-is-inside@1.0.2", "", {}, "sha512-DUWJr3+ULp4zXmol/SZkFf3JGsS9/SIv+Y3Rt93/UjPpDpklB5f1er4O3POIbUuUJ3FXgqte2Q7SrU6zAqwk8w=="], + "path-key": ["path-key@3.1.1", "", {}, "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q=="], + "path-to-regexp": ["path-to-regexp@3.3.0", "", {}, "sha512-qyCH421YQPS2WFDxDjftfc1ZR5WKQzVzqsp4n9M2kQhVOo/ByahFoUNJfl58kOcEGfQ//7weFTDhm+ss8Ecxgw=="], + "path-type": ["path-type@4.0.0", "", {}, "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw=="], "picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="], @@ -1191,7 +1807,11 @@ "playwright-core": ["playwright-core@1.65.1", "", { "bin": { "playwright-core": "cli.js" } }, "sha512-hqPpz7blSMPxWVdoeE1yiBSzXsKiVOd2k+kjCvmUywD2GPO2Dd9HfcWnq9NN0GHbNZDFgZ9JfBFr+X5/BLo0qw=="], - "postcss": ["postcss@8.5.31", "", { "dependencies": { "nanoid": "^3.3.20", "picocolors": "^1.1.1", "source-map-js": "^1.2.2" } }, "sha512-YUbWYCgErwnMAVkjUnYa+KlMBzGpHwiIt/DE7f0G33AuX2LH9UcTk6KgWxd3zRU+pN3u/C+Xl3EnMLM4Hea7Sg=="], + "points-on-curve": ["points-on-curve@0.2.0", "", {}, "sha512-0mYKnYYe9ZcqMCWhUjItv/oHjvgEsfKvnUTg8sAtnHr3GVy7rGkXCb6d5cSyqrWqL4k81b9CPg3urd+T7aop3A=="], + + "points-on-path": ["points-on-path@0.2.1", "", { "dependencies": { "path-data-parser": "0.1.0", "points-on-curve": "0.2.0" } }, "sha512-25ClnWWuw7JbWZcgqY/gJ4FQWadKxGWk+3kR/7kD0tCaDtPPMj7oHu2ToLaVhfpnHrZzYby2w6tUA0eOIuUg8g=="], + + "postcss": ["postcss@8.5.33", "", { "dependencies": { "nanoid": "^3.3.20", "picocolors": "^1.1.1", "source-map-js": "^1.2.2" } }, "sha512-RVHEU9/Pp1Fnjr/MpAJsZoADukCKhfIi15OunEYiGktIkYLkPVvC1sioWolGDS7XByMTx9m/IGbro0Js13zhnQ=="], "postcss-media-query-parser": ["postcss-media-query-parser@0.2.3", "", {}, "sha512-3sOlxmbKcSHMjlUXQZKQ06jOswE7oVkXPxmZdoB1r5l0q6gTFTQSHxNxOrCccElbW7dxNytifNEo8qidX2Vsig=="], @@ -1201,28 +1821,78 @@ "proc-log": ["proc-log@7.0.0", "", {}, "sha512-FYgfaA69XZ93zaXLoMNQ+ViDXGGBgR8aLh03txzcFhV+9xOXx7+8DLCULrKKpR9+GsH9ZfHm82aSUPpozX0Ztg=="], + "property-information": ["property-information@7.2.0", "", {}, "sha512-IAtzIB6sUiWaJYrX9smp3V46pBGbBeLFRGdh25kg1334VcBlD8HzhPeNIWQH9zhGmo2itIe25EHt9dQP7G5hmg=="], + "proxy-agent-negotiate": ["proxy-agent-negotiate@1.1.0", "", { "peerDependencies": { "kerberos": "^2.0.0" }, "optionalPeers": ["kerberos"] }, "sha512-N8IBcM3UgCVzz2L2Lqv8DVntDnnC8/hiV4nEDUPkqq72TPUgYWjQc+bdZlBPZK9LzPAvOY//gAt0S0DApoOXWQ=="], "proxy-compare": ["proxy-compare@3.0.1", "", {}, "sha512-V9plBAt3qjMlS1+nC8771KNf6oJ12gExvaxnNzN/9yVRLdTv/lc+oJlnSzrdYDAvBfTStPCoiaCOTmTs0adv7Q=="], + "publint": ["publint@0.3.25", "", { "dependencies": { "@publint/pack": "^0.1.7", "package-manager-detector": "^1.8.0", "picocolors": "^1.1.1", "sade": "^1.8.1" }, "bin": { "publint": "./src/cli.js" } }, "sha512-WMMbn/d7JqRlfXQL/JUI4n5skC8cJ5WVr8/wT5mmiYWkUdENkZr1I5rgs2+dQPVRgoJd+JRYtB46MTsuDylw9g=="], + "quansync": ["quansync@0.2.11", "", {}, "sha512-AifT7QEbW9Nri4tAwR5M/uzpBuqfZf+zwaEM/QkzEjj7NBuFD2rBuy0K3dE+8wltbezDV7JMA0WfnCPYRSYbXA=="], "queue-microtask": ["queue-microtask@1.2.3", "", {}, "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A=="], + "range-parser": ["range-parser@1.2.0", "", {}, "sha512-kA5WQoNVo4t9lNx2kQNFCxKeBl5IbbSNBl1M/tLkw9WCn+hxNBAW5Qh8gdhs63CJnhjJ2zQWFoqPJP2sK1AV5A=="], + + "rc": ["rc@1.2.8", "", { "dependencies": { "deep-extend": "^0.6.0", "ini": "~1.3.0", "minimist": "^1.2.0", "strip-json-comments": "~2.0.1" }, "bin": { "rc": "./cli.js" } }, "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw=="], + "react": ["react@19.3.1", "", {}, "sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw=="], "react-compiler-runtime": ["react-compiler-runtime@1.0.0", "", { "peerDependencies": { "react": "^17.0.0 || ^18.0.0 || ^19.0.0 || ^0.0.0-experimental" } }, "sha512-rRfjYv66HlG8896yPUDONgKzG5BxZD1nV9U6rkm+7VCuvQc903C4MjcoZR4zPw53IKSOX9wMQVpA1IAbRtzQ7w=="], "react-dom": ["react-dom@19.3.1", "", { "dependencies": { "scheduler": "^0.28.0" }, "peerDependencies": { "react": "^19.3.1" } }, "sha512-Y0bARz53lhEC1NMCASs0/j+faB/zqt3R8hpvg1e8+61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe+ZeBCavQPtKQ=="], + "react-remove-scroll": ["react-remove-scroll@2.7.2", "", { "dependencies": { "react-remove-scroll-bar": "^2.3.7", "react-style-singleton": "^2.2.3", "tslib": "^2.1.0", "use-callback-ref": "^1.3.3", "use-sidecar": "^1.1.3" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Iqb9NjCCTt6Hf+vOdNIZGdTiH1QSqr27H/Ek9sv/a97gfueI/5h1s3yRi1nngzMUaOOToin5dI1dXKdXiF+u0Q=="], + + "react-remove-scroll-bar": ["react-remove-scroll-bar@2.3.8", "", { "dependencies": { "react-style-singleton": "^2.2.2", "tslib": "^2.0.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" }, "optionalPeers": ["@types/react"] }, "sha512-9r+yi9+mgU33AKcj6IbT9oRCO78WriSj6t/cF8DWBZJ9aOGPOTEDvdUDz1FwKim7QXWwmHqtdHnRJfhAxEG46Q=="], + + "react-style-singleton": ["react-style-singleton@2.2.3", "", { "dependencies": { "get-nonce": "^1.0.0", "tslib": "^2.0.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-b6jSvxvVnyptAiLjbkWLE/lOnR4lfTtDAl+eUC7RZy+QQWc6wRzIV2CE6xBuMmDxc2qIihtDCZD5NPOFl7fRBQ=="], + "read-yaml-file": ["read-yaml-file@1.1.0", "", { "dependencies": { "graceful-fs": "^4.1.5", "js-yaml": "^3.6.1", "pify": "^4.0.1", "strip-bom": "^3.0.0" } }, "sha512-VIMnQi/Z4HT2Fxuwg5KrY174U1VdUIASQVWXXyqtNRtxSr9IYkn1rsI6Tb6HsrHCmB7gVpNwX6JxPTHcH6IoTA=="], "readdirp": ["readdirp@5.1.1", "", {}, "sha512-Kko+Y5XQ6fM+Ce3dq3m9YGxnacYZYl9cA1wZjaF3Vbry2L3i1qVg8+CAgNPsXRArPMUMCaOR7oa9Nqntc43JKA=="], + "recma-build-jsx": ["recma-build-jsx@1.0.0", "", { "dependencies": { "@types/estree": "^1.0.0", "estree-util-build-jsx": "^3.0.0", "vfile": "^6.0.0" } }, "sha512-8GtdyqaBcDfva+GUKDr3nev3VpKAhup1+RvkMvUxURHpW7QyIvk9F5wz7Vzo06CEMSilw6uArgRqhpiUcWp8ew=="], + + "recma-jsx": ["recma-jsx@1.0.1", "", { "dependencies": { "acorn-jsx": "^5.0.0", "estree-util-to-js": "^2.0.0", "recma-parse": "^1.0.0", "recma-stringify": "^1.0.0", "unified": "^11.0.0" }, "peerDependencies": { "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" } }, "sha512-huSIy7VU2Z5OLv6oFLosQGGDqPqdO1iq6bWNAdhzMxSJP7RAso4fCZ1cKu8j9YHCZf3TPrq4dw3okhrylgcd7w=="], + + "recma-parse": ["recma-parse@1.0.0", "", { "dependencies": { "@types/estree": "^1.0.0", "esast-util-from-js": "^2.0.0", "unified": "^11.0.0", "vfile": "^6.0.0" } }, "sha512-OYLsIGBB5Y5wjnSnQW6t3Xg7q3fQ7FWbw/vcXtORTnyaSFscOtABg+7Pnz6YZ6c27fG1/aN8CjfwoUEUIdwqWQ=="], + + "recma-stringify": ["recma-stringify@1.0.0", "", { "dependencies": { "@types/estree": "^1.0.0", "estree-util-to-js": "^2.0.0", "unified": "^11.0.0", "vfile": "^6.0.0" } }, "sha512-cjwII1MdIIVloKvC9ErQ+OgAtwHBmcZ0Bg4ciz78FtbT8In39aAYbaA7zvxQ61xVMSPE8WxhLwLbhif4Js2C+g=="], + "reflect-metadata": ["reflect-metadata@0.2.2", "", {}, "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q=="], + "regex": ["regex@6.1.0", "", { "dependencies": { "regex-utilities": "^2.3.0" } }, "sha512-6VwtthbV4o/7+OaAF9I5L5V3llLEsoPyq9P1JVXkedTP33c7MfCG0/5NOPcSJn0TzXcG9YUrR0gQSWioew3LDg=="], + + "regex-recursion": ["regex-recursion@6.0.2", "", { "dependencies": { "regex-utilities": "^2.3.0" } }, "sha512-0YCaSCq2VRIebiaUviZNs0cBz1kg5kVS2UKUfNIx8YVs1cN3AV7NTctO5FOKBA+UT2BPJIWZauYHPqJODG50cg=="], + + "regex-utilities": ["regex-utilities@2.3.0", "", {}, "sha512-8VhliFJAWRaUiVvREIiW2NXXTmHs4vMNnSzuJVhscgmGav3g9VDxLrQndI3dZZVVdp0ZO/5v0xmX516/7M9cng=="], + + "registry-auth-token": ["registry-auth-token@3.3.2", "", { "dependencies": { "rc": "^1.1.6", "safe-buffer": "^5.0.1" } }, "sha512-JL39c60XlzCVgNrO+qq68FoNb56w/m7JYvGR2jT5iR1xBrUA3Mfx5Twk5rqTThPmQKMWydGmq8oFtDlxfrmxnQ=="], + + "registry-url": ["registry-url@3.1.0", "", { "dependencies": { "rc": "^1.0.1" } }, "sha512-ZbgR5aZEdf4UKZVBPYIgaglBmSF2Hi94s2PcIHhRGFjKYu+chjJdYfHn4rt3hB6eCKLJ8giVIIfgMa1ehDfZKA=="], + + "rehype-recma": ["rehype-recma@1.0.0", "", { "dependencies": { "@types/estree": "^1.0.0", "@types/hast": "^3.0.0", "hast-util-to-estree": "^3.0.0" } }, "sha512-lqA4rGUf1JmacCNWWZx0Wv1dHqMwxzsDWYMTowuplHF3xH0N/MmrZ/G3BDZnzAkRmxDadujCjaKM2hqYdCBOGw=="], + + "remark": ["remark@15.0.1", "", { "dependencies": { "@types/mdast": "^4.0.0", "remark-parse": "^11.0.0", "remark-stringify": "^11.0.0", "unified": "^11.0.0" } }, "sha512-Eht5w30ruCXgFmxVUSlNWQ9iiimq07URKeFS3hNc8cUWy1llX4KDWfyEDZRycMc+znsN9Ux5/tJ/BFdgdOwA3A=="], + + "remark-gfm": ["remark-gfm@4.0.1", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-gfm": "^3.0.0", "micromark-extension-gfm": "^3.0.0", "remark-parse": "^11.0.0", "remark-stringify": "^11.0.0", "unified": "^11.0.0" } }, "sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg=="], + + "remark-mdx": ["remark-mdx@3.1.1", "", { "dependencies": { "mdast-util-mdx": "^3.0.0", "micromark-extension-mdxjs": "^3.0.0" } }, "sha512-Pjj2IYlUY3+D8x00UJsIOg5BEvfMyeI+2uLPn9VO9Wg4MEtN/VTIq2NEJQfde9PnX15KgtHyl9S0BcTnWrIuWg=="], + + "remark-parse": ["remark-parse@11.0.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-from-markdown": "^2.0.0", "micromark-util-types": "^2.0.0", "unified": "^11.0.0" } }, "sha512-FCxlKLNGknS5ba/1lmpYijMUzX2esxW5xQqjWxw2eHFfS2MSdaHVINFmhjo+qN1WhZhNimq0dZATN9pH0IDrpA=="], + + "remark-rehype": ["remark-rehype@11.1.2", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/mdast": "^4.0.0", "mdast-util-to-hast": "^13.0.0", "unified": "^11.0.0", "vfile": "^6.0.0" } }, "sha512-Dh7l57ianaEoIpzbp0PC9UKAdCSVklD8E5Rpw7ETfbTl3FqcOOgq5q2LVDhgGCkaBv7p24JXikPdvhhmHvKMsw=="], + + "remark-stringify": ["remark-stringify@11.0.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-to-markdown": "^2.0.0", "unified": "^11.0.0" } }, "sha512-1OSmLd3awB/t8qdoEOMazZkNsfVTeY4fTsgzcQFdXNq8ToTN4ZGwrMnlda4K6smTFKD+GRV6O48i6Z4iKgPPpw=="], + + "require-directory": ["require-directory@2.1.1", "", {}, "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q=="], + "require-from-string": ["require-from-string@2.0.2", "", {}, "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw=="], + "reselect": ["reselect@5.3.0", "", {}, "sha512-XGoLeRAVzUTcJ1qkxPQhDJyIZ5d6zzZD9nT7AEZOaaU9UbWclhycElmhO+VD5bFeLuzhPBaOV2oXC8uG35ZSpg=="], + "resolve-from": ["resolve-from@5.0.0", "", {}, "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw=="], "resolve-pkg-maps": ["resolve-pkg-maps@1.0.0", "", {}, "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw=="], @@ -1231,16 +1901,24 @@ "reusify": ["reusify@1.1.0", "", {}, "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw=="], + "robust-predicates": ["robust-predicates@3.0.3", "", {}, "sha512-NS3levdsRIUOmiJ8FZWCP7LG3QpJyrs/TE0Zpf1yvZu8cAJJ6QMW92H1c7kWpdIHo8RvmLxN/o2JXTKHp74lUA=="], + "rolldown": ["rolldown@1.3.2", "", { "dependencies": { "@oxc-project/types": "=0.158.0", "@rolldown/pluginutils": "^1.0.0" }, "optionalDependencies": { "@rolldown/binding-android-arm-eabi": "1.3.2", "@rolldown/binding-android-arm64": "1.3.2", "@rolldown/binding-darwin-arm64": "1.3.2", "@rolldown/binding-darwin-x64": "1.3.2", "@rolldown/binding-freebsd-x64": "1.3.2", "@rolldown/binding-linux-arm-gnueabihf": "1.3.2", "@rolldown/binding-linux-arm64-gnu": "1.3.2", "@rolldown/binding-linux-arm64-musl": "1.3.2", "@rolldown/binding-linux-ppc64-gnu": "1.3.2", "@rolldown/binding-linux-s390x-gnu": "1.3.2", "@rolldown/binding-linux-x64-gnu": "1.3.2", "@rolldown/binding-linux-x64-musl": "1.3.2", "@rolldown/binding-openharmony-arm64": "1.3.2", "@rolldown/binding-wasm32-wasi": "1.3.2", "@rolldown/binding-win32-arm64-msvc": "1.3.2", "@rolldown/binding-win32-x64-msvc": "1.3.2" }, "bin": { "rolldown": "./bin/cli.mjs" } }, "sha512-EFHqbVkXiYZA6akmYm2bvJhNbEGdUwAResRhYwl/BO8QhB5KxsG+t3RVHJSIOy5jBEb0XCACvrIGnnl6Z8sMGA=="], "rolldown-plugin-dts": ["rolldown-plugin-dts@0.30.2", "", { "dependencies": { "dts-resolver": "^3.0.0", "get-tsconfig": "5.0.0-beta.6", "obug": "^3.0.0", "yuku": "^0.28.0" }, "peerDependencies": { "@volar/typescript": "~2.4.0", "@vue/language-core": "~3.2.0 || ~3.3.0", "rolldown": "^1.2.0", "tsrs": "*", "typescript": "^5.0.0 || ^6.0.0 || ~7.0.0 || ~7.1.0-0", "vue-tsc": "~3.2.0 || ~3.3.0" }, "optionalPeers": ["@volar/typescript", "@vue/language-core", "tsrs", "typescript", "vue-tsc"] }, "sha512-Q3wRlwawifZeN1llb1BaeZfimmJMF/WHzm7z5ieZ8g2CWHQM0gvVWLYPbgBglsXJqcd405gc+3LS2NzSevbYNQ=="], + "roughjs": ["roughjs@4.6.6", "", { "dependencies": { "hachure-fill": "^0.5.2", "path-data-parser": "^0.1.0", "points-on-curve": "^0.2.0", "points-on-path": "^0.2.1" } }, "sha512-ZUz/69+SYpFN/g/lUlo2FXcIjRkSu3nDarreVdGGndHEBJ6cXPdKguS8JGxwj5HA5xIbVKSmLgr5b3AWxtRfvQ=="], + "run-parallel": ["run-parallel@1.2.0", "", { "dependencies": { "queue-microtask": "^1.2.2" } }, "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA=="], + "rw": ["rw@1.3.3", "", {}, "sha512-PdhdWy89SiZogBLaw42zdeqtRJ//zFd2PgQavcICDUgJT5oW10QCRKbJ6bg4r0/UY2M6BWd5tkxuGFRvCkgfHQ=="], + "rxjs": ["rxjs@7.8.2", "", { "dependencies": { "tslib": "^2.1.0" } }, "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA=="], "sade": ["sade@1.8.1", "", { "dependencies": { "mri": "^1.1.0" } }, "sha512-xal3CZX1Xlo/k4ApwCFrHVACi9fBqJ7V+mwhBsuf/1IOKbBy098Fex+Wa/5QMubw09pSZ/u8EY8PWgevJsXp1A=="], + "safe-buffer": ["safe-buffer@5.2.1", "", {}, "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="], + "safer-buffer": ["safer-buffer@2.1.2", "", {}, "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="], "sass": ["sass@1.104.1", "", { "dependencies": { "chokidar": "^5.0.0", "immutable": "^5.1.5", "source-map-js": ">=0.6.2 <2.0.0" }, "optionalDependencies": { "@parcel/watcher": "^2.4.1" }, "bin": { "sass": "sass.js" } }, "sha512-yDA+1aIG3EHgN4V/BvuhCvu61FF6hEd4e+9DxikUm9U0CAGuvdIZ/UYy7qbOxjhbbWQraoyLlMuzdRGOSV5Bmw=="], @@ -1285,11 +1963,17 @@ "scheduler": ["scheduler@0.28.0", "", {}, "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw=="], + "scroll-into-view-if-needed": ["scroll-into-view-if-needed@3.2.1", "", { "dependencies": { "compute-scroll-into-view": "^3.2.2" } }, "sha512-dgeJvJhSV9MY6hyhtsivbSxHoZVm+lumsWTObtUdAchJflwOGmKKHNkEpU8pVYMomZ8h/yrfzVQkcPlObQNDWQ=="], + "semver": ["semver@7.8.5", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="], - "seroval": ["seroval@1.7.0", "", {}, "sha512-FU+LUkmDzWNsJ6oubZFN3dGPKny53DRhPJG6nftEaXDL8MIn19+kEE1Gvc+63Go+qPOwVUlKIdKhsu2HN6tksw=="], + "seroval": ["seroval@1.8.1", "", {}, "sha512-7z9x1flFYfZBz+LfDkXNfm5UIhZJ/97ASaV8Q1wctoVkeqVfv+tLPsWebeMXBNw6XprvwxDE5wC5Ylqmr+iSrA=="], + + "seroval-plugins": ["seroval-plugins@1.8.0", "", { "peerDependencies": { "seroval": "^1.8.0" } }, "sha512-96vBb12rDvPPwdKUgWw1op3fGq8AVBFOr0IllbnM72yR5J9WWXF18cQ4g1XfDO7HCyh2dt70P3XdtyRayP8FWg=="], + + "serve": ["serve@14.2.8", "", { "dependencies": { "@zeit/schemas": "2.36.0", "ajv": "8.18.0", "arg": "5.0.2", "boxen": "7.0.0", "chalk": "5.0.1", "chalk-template": "0.4.0", "compression": "1.8.2", "is-port-reachable": "4.0.0", "serve-handler": "6.1.7", "tinyclip": "^0.1.12", "update-check": "1.5.4" }, "bin": { "serve": "build/main.js" } }, "sha512-7or7YqR3zXwHhiBGj40l9yODyQY146O+hXKaEAfQYQkcvHtMDdX95K96xr50qL9EjXScyYVJb1NIgVE8F0i5cA=="], - "seroval-plugins": ["seroval-plugins@1.7.0", "", { "peerDependencies": { "seroval": "^1.0" } }, "sha512-WM4rArfPtLZriTuxC5DBvNulEwAaRcjNe/dkMOEesOcuvXf5nEwKf5Bw3AT92WHohqcc45+57GdtsCuBTI0mjw=="], + "serve-handler": ["serve-handler@6.1.7", "", { "dependencies": { "bytes": "3.0.0", "content-disposition": "0.5.2", "mime-types": "2.1.18", "minimatch": "3.1.5", "path-is-inside": "1.0.2", "path-to-regexp": "3.3.0", "range-parser": "1.2.0" } }, "sha512-CinAq1xWb0vR3twAv9evEU8cNWkXCb9kd5ePAHUKJBkOsUpR1wt/CvGdeca7vqumL1U5cSaeVQ6zZMxiJ3yWsg=="], "sharp": ["sharp@0.35.5", "", { "dependencies": { "@img/colour": "^1.1.0", "detect-libc": "^2.1.2", "semver": "^7.8.5" }, "optionalDependencies": { "@img/sharp-darwin-arm64": "0.35.5", "@img/sharp-darwin-x64": "0.35.5", "@img/sharp-freebsd-wasm32": "0.35.5", "@img/sharp-libvips-darwin-arm64": "1.3.4", "@img/sharp-libvips-darwin-x64": "1.3.4", "@img/sharp-libvips-linux-arm": "1.3.4", "@img/sharp-libvips-linux-arm64": "1.3.4", "@img/sharp-libvips-linux-ppc64": "1.3.4", "@img/sharp-libvips-linux-riscv64": "1.3.4", "@img/sharp-libvips-linux-s390x": "1.3.4", "@img/sharp-libvips-linux-x64": "1.3.4", "@img/sharp-libvips-linuxmusl-arm64": "1.3.4", "@img/sharp-libvips-linuxmusl-x64": "1.3.4", "@img/sharp-linux-arm": "0.35.5", "@img/sharp-linux-arm64": "0.35.5", "@img/sharp-linux-ppc64": "0.35.5", "@img/sharp-linux-riscv64": "0.35.5", "@img/sharp-linux-s390x": "0.35.5", "@img/sharp-linux-x64": "0.35.5", "@img/sharp-linuxmusl-arm64": "0.35.5", "@img/sharp-linuxmusl-x64": "0.35.5", "@img/sharp-webcontainers-wasm32": "0.35.5", "@img/sharp-win32-arm64": "0.35.5", "@img/sharp-win32-ia32": "0.35.5", "@img/sharp-win32-x64": "0.35.5" }, "peerDependencies": { "@types/node": "*" }, "optionalPeers": ["@types/node"] }, "sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g=="], @@ -1297,13 +1981,17 @@ "shebang-regex": ["shebang-regex@3.0.0", "", {}, "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A=="], + "shiki": ["shiki@4.6.0", "", { "dependencies": { "@shikijs/core": "4.6.0", "@shikijs/engine-javascript": "4.6.0", "@shikijs/engine-oniguruma": "4.6.0", "@shikijs/langs": "4.6.0", "@shikijs/themes": "4.6.0", "@shikijs/types": "4.6.0", "@shikijs/vscode-textmate": "^10.1.0", "@types/hast": "^3.0.5" } }, "sha512-imjLsVHgPuWhvpU3P+zOekvMYqnel7QmKsFC4Sn0fCuAvaaalBsxwKEsrU8Ko5BdFnZA6Go/8a0RzahS634UgA=="], + "signal-exit": ["signal-exit@4.1.0", "", {}, "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw=="], + "skin-tone": ["skin-tone@2.0.0", "", { "dependencies": { "unicode-emoji-modifier-base": "^1.0.0" } }, "sha512-kUMbT1oBJCpgrnKoSr0o6wPtvRWT9W9UKvGLwfJYO2WuahZRHOpEyL1ckyMGgMWh0UdpmaoFqKKD29WTomNEGA=="], + "slash": ["slash@3.0.0", "", {}, "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q=="], "slice-ansi": ["slice-ansi@9.0.1", "", { "dependencies": { "ansi-styles": "^6.2.3", "is-fullwidth-code-point": "^5.1.0" } }, "sha512-aBY19bn/XA+hKOKX0qL7Z0UfdBsbQvc9hn993U8ALUjzxCvDcuZqLoRXjGJrUARWAlwMnsRVD9sw2AFNOYvalA=="], - "solid-js": ["solid-js@2.0.0-rc.18", "", { "dependencies": { "@solidjs/signals": "^2.0.0-rc.18", "csstype": "^3.1.0", "seroval": "1.7.0", "seroval-plugins": "1.7.0" } }, "sha512-g4KjUQUjfqvqHYnBddN5nVAF7DFcDjtuH+NeDu/26vx6SlSDiqBJS8jsNag6VpdKAnfK8oLfphogEhXtM4UOyw=="], + "solid-js": ["solid-js@2.0.0", "", { "dependencies": { "@solidjs/signals": "^2.0.0", "seroval": "^1.8.0", "seroval-plugins": "^1.8.0" } }, "sha512-9zN4uH2OQeQAYbF4BmIzoaa+L5Hb8Dp6kkP6ZXobHQ1FZVICdmzREPDVDBJY7umzdAE8D6zbFfWhxGtagkyslA=="], "source-map": ["source-map@0.6.1", "", {}, "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g=="], @@ -1311,21 +1999,35 @@ "source-map-support": ["source-map-support@0.5.21", "", { "dependencies": { "buffer-from": "^1.0.0", "source-map": "^0.6.0" } }, "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w=="], + "space-separated-tokens": ["space-separated-tokens@2.0.2", "", {}, "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q=="], + "spawndamnit": ["spawndamnit@3.0.1", "", { "dependencies": { "cross-spawn": "^7.0.5", "signal-exit": "^4.0.1" } }, "sha512-MmnduQUuHCoFckZoWnXsTg7JaiLBJrKFj9UI2MbRPGaJeVpsLcVBu6P/IGZovziM/YBsellCmsprgNA+w0CzVg=="], "sprintf-js": ["sprintf-js@1.0.3", "", {}, "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g=="], "stdin-discarder": ["stdin-discarder@0.3.2", "", {}, "sha512-eCPu1qRxPVkl5605OTWF8Wz40b4Mf45NY5LQmVPQ599knfs5QhASUm9GbJ5BDMDOXgrnh0wyEdvzmL//YMlw0A=="], - "string-width": ["string-width@8.3.0", "", { "dependencies": { "get-east-asian-width": "^1.5.0", "strip-ansi": "^7.1.2" } }, "sha512-ZbmZM0JCihQN91dWnxoipT2KOEyHqEyfRXUyjuRhW8b/xnqPDoq4gWEVApTVa9db2wN8mmoikgFBbjh71+cGeQ=="], + "string-width": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="], + + "stringify-entities": ["stringify-entities@4.0.4", "", { "dependencies": { "character-entities-html4": "^2.0.0", "character-entities-legacy": "^3.0.0" } }, "sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg=="], "strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="], "strip-bom": ["strip-bom@3.0.0", "", {}, "sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA=="], + "strip-json-comments": ["strip-json-comments@2.0.1", "", {}, "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ=="], + + "style-to-js": ["style-to-js@1.1.21", "", { "dependencies": { "style-to-object": "1.0.14" } }, "sha512-RjQetxJrrUJLQPHbLku6U/ocGtzyjbJMP9lCNK7Ag0CNh690nSH8woqWH9u16nMjYBAok+i7JO1NP2pOy8IsPQ=="], + + "style-to-object": ["style-to-object@1.0.14", "", { "dependencies": { "inline-style-parser": "0.2.7" } }, "sha512-LIN7rULI0jBscWQYaSswptyderlarFkjQ+t79nzty8tcIAceVomEVlLzH5VP4Cmsv6MtKhs7qaAiwlcp+Mgaxw=="], + "styled-jsx": ["styled-jsx@5.1.6", "", { "dependencies": { "client-only": "0.0.1" }, "peerDependencies": { "react": ">= 16.8.0 || 17.x.x || ^18.0.0-0 || ^19.0.0-0" } }, "sha512-qSVyDTeMotdvQYoHWLNGwRFJHC+i+ZvdBRYosOFgC+Wg1vx4frN2/RG/NA7SYqqvKNLf39P2LSRA2pu6n0XYZA=="], - "supports-color": ["supports-color@8.1.1", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q=="], + "stylis": ["stylis@4.4.0", "", {}, "sha512-5Z9ZpRzfuH6l/UAvCPAPUo3665Nk2wLaZU3x+TLHKVzIz33+sbJqbtrYoC3KD4/uVOr2Zp+L0LySezP9OHV9yA=="], + + "supports-color": ["supports-color@7.2.0", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw=="], + + "supports-hyperlinks": ["supports-hyperlinks@3.2.0", "", { "dependencies": { "has-flag": "^4.0.0", "supports-color": "^7.0.0" } }, "sha512-zFObLMyZeEwzAoKCyu1B91U79K2t7ApXuQfo8OuxwXLDgcKxuwM+YvcbIhm6QWqz7mHUH1TVytR1PwVVjEuMig=="], "svelte": ["svelte@5.57.3", "", { "dependencies": { "@jridgewell/remapping": "^2.3.5", "@jridgewell/sourcemap-codec": "^1.6.0", "@sveltejs/acorn-typescript": "^1.0.13", "@types/estree": "^1.0.9", "acorn": "^8.18.0", "aria-query": "5.3.1", "axobject-query": "^4.1.0", "clsx": "^2.1.1", "devalue": "^5.9.2", "esm-env": "^1.2.1", "esrap": "^2.3.6", "is-reference": "^3.0.3", "locate-character": "^3.0.0", "magic-string": "^0.30.11", "zimmerframe": "^1.1.2" } }, "sha512-5mAftM3SoDV9X0zdF386F9p2pv8iKOwi/KfBS1XnBAkVCKFzVOLHUoa8iGWAt4buoicLmyWVRpuuD5wplXOQsg=="], @@ -1339,6 +2041,12 @@ "term-size": ["term-size@2.2.1", "", {}, "sha512-wK0Ri4fOGjv/XPy8SBHZChl8CM7uMc5VML7SqiQ0zG7+J5Vr+RMQDoHa2CNT6KHUnTGIXH34UDMkPzAUyapBZg=="], + "thenify": ["thenify@3.3.1", "", { "dependencies": { "any-promise": "^1.0.0" } }, "sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw=="], + + "thenify-all": ["thenify-all@1.6.0", "", { "dependencies": { "thenify": ">= 3.1.0 < 4" } }, "sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA=="], + + "tinyclip": ["tinyclip@0.1.15", "", {}, "sha512-uo33abH+Ays0xYaDysoBt494Hb3hsEczMpcC0MwFl773pazORx4fmvKhclhR1wonUbB6vvpRsvVMwnhfqeMc+A=="], + "tinyexec": ["tinyexec@1.3.1", "", {}, "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA=="], "tinyglobby": ["tinyglobby@0.2.17", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g=="], @@ -1349,26 +2057,66 @@ "tr46": ["tr46@0.0.3", "", {}, "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw=="], + "trim-lines": ["trim-lines@3.0.1", "", {}, "sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg=="], + + "trough": ["trough@2.2.0", "", {}, "sha512-tmMpK00BjZiUyVyvrBK7knerNgmgvcV/KLVyuma/SC+TQN167GrMRciANTz09+k3zW8L8t60jWO1GpfkZdjTaw=="], + + "ts-dedent": ["ts-dedent@2.3.0", "", {}, "sha512-JfJeIHke7y2egdGGgRAvpCwYFUsHlM2gPcrVOxFkznt/4uzQ7HFmvE63iFHVLBJNDuyDOQgijDK/tXH/f6Msjg=="], + "tsdown": ["tsdown@0.23.7", "", { "dependencies": { "cac": "^7.1.0", "defu": "^6.1.7", "empathic": "^2.1.0", "hookable": "^6.1.2", "import-without-cache": "^0.4.1", "obug": "^3.0.0", "picomatch": "^4.0.7", "rolldown": "~1.3.0", "rolldown-plugin-dts": "^0.30.0", "tinyexec": "^1.3.1", "tinyglobby": "^0.2.17", "tinyps": "^0.5.1", "unconfig-core": "^7.5.0", "verkit": "^0.5.0" }, "peerDependencies": { "@arethetypeswrong/core": "^0.18.1", "@tsdown/css": "0.23.7", "@tsdown/exe": "0.23.7", "@vitejs/devtools": "*", "publint": "^0.3.8", "tsx": "*", "typescript": "^5.0.0 || ^6.0.0 || ^7.0.0", "unplugin-unused": ">=0.5.0", "unrun": "*" }, "optionalPeers": ["@arethetypeswrong/core", "@tsdown/css", "@tsdown/exe", "@vitejs/devtools", "publint", "tsx", "typescript", "unplugin-unused", "unrun"], "bin": { "tsdown": "./dist/run.mjs" } }, "sha512-w9nmWyEimfqQ7/HpVeKTldAeBvWGXiaWyNP7xaxSrr0GhKxsngEyTWqk1nOruRqvqRSkdpMMkpV2BcoWfLB4Uw=="], "tslib": ["tslib@2.9.1", "", {}, "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA=="], + "type-fest": ["type-fest@2.19.0", "", {}, "sha512-RAH822pAdBgcNMAfWnCBU3CFZcfZ/i1eZjwFU/dsLKumyuuP3niueg2UAukXYF0E2AAoc82ZSSf9J0WQBinzHA=="], + "typescript": ["typescript@7.0.2", "", { "optionalDependencies": { "@typescript/typescript-aix-ppc64": "7.0.2", "@typescript/typescript-darwin-arm64": "7.0.2", "@typescript/typescript-darwin-x64": "7.0.2", "@typescript/typescript-freebsd-arm64": "7.0.2", "@typescript/typescript-freebsd-x64": "7.0.2", "@typescript/typescript-linux-arm": "7.0.2", "@typescript/typescript-linux-arm64": "7.0.2", "@typescript/typescript-linux-loong64": "7.0.2", "@typescript/typescript-linux-mips64el": "7.0.2", "@typescript/typescript-linux-ppc64": "7.0.2", "@typescript/typescript-linux-riscv64": "7.0.2", "@typescript/typescript-linux-s390x": "7.0.2", "@typescript/typescript-linux-x64": "7.0.2", "@typescript/typescript-netbsd-arm64": "7.0.2", "@typescript/typescript-netbsd-x64": "7.0.2", "@typescript/typescript-openbsd-arm64": "7.0.2", "@typescript/typescript-openbsd-x64": "7.0.2", "@typescript/typescript-sunos-x64": "7.0.2", "@typescript/typescript-win32-arm64": "7.0.2", "@typescript/typescript-win32-x64": "7.0.2" }, "bin": { "tsc": "bin/tsc" } }, "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA=="], "unconfig-core": ["unconfig-core@7.5.0", "", { "dependencies": { "@quansync/fs": "^1.0.0", "quansync": "^1.0.0" } }, "sha512-Su3FauozOGP44ZmKdHy2oE6LPjk51M/TRRjHv2HNCWiDvfvCoxC2lno6jevMA91MYAdCdwP05QnWdWpSbncX/w=="], "undici-types": ["undici-types@8.9.0", "", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="], + "unicode-emoji-modifier-base": ["unicode-emoji-modifier-base@1.0.0", "", {}, "sha512-yLSH4py7oFH3oG/9K+XWrz1pSi3dfUrWEnInbxMfArOfc1+33BlGPQtLsOYwvdMy11AwUBetYuaRxSPqgkq+8g=="], + + "unified": ["unified@11.0.5", "", { "dependencies": { "@types/unist": "^3.0.0", "bail": "^2.0.0", "devlop": "^1.0.0", "extend": "^3.0.0", "is-plain-obj": "^4.0.0", "trough": "^2.0.0", "vfile": "^6.0.0" } }, "sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA=="], + + "unist-util-is": ["unist-util-is@6.0.1", "", { "dependencies": { "@types/unist": "^3.0.0" } }, "sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g=="], + + "unist-util-position": ["unist-util-position@5.0.0", "", { "dependencies": { "@types/unist": "^3.0.0" } }, "sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA=="], + + "unist-util-position-from-estree": ["unist-util-position-from-estree@2.0.0", "", { "dependencies": { "@types/unist": "^3.0.0" } }, "sha512-KaFVRjoqLyF6YXCbVLNad/eS4+OfPQQn2yOd7zF/h5T/CSL2v8NpN6a5TPvtbXthAGw5nG+PuTtq+DdIZr+cRQ=="], + + "unist-util-remove-position": ["unist-util-remove-position@5.0.0", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-visit": "^5.0.0" } }, "sha512-Hp5Kh3wLxv0PHj9m2yZhhLt58KzPtEYKQQ4yxfYFEO7EvHwzyDYnduhHnY1mDxoqr7VUwVuHXk9RXKIiYS1N8Q=="], + + "unist-util-stringify-position": ["unist-util-stringify-position@4.0.0", "", { "dependencies": { "@types/unist": "^3.0.0" } }, "sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ=="], + + "unist-util-visit": ["unist-util-visit@5.2.0", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-is": "^6.0.0", "unist-util-visit-parents": "^6.1.0" } }, "sha512-fpsYs/VVoZxfGY9/j3FQpZmN8wdLJaV1Pt38AaJNZu9uKIHcFU3halCdBveEq1HGKO1OEfJY65w1zvoFV1b3qQ=="], + + "unist-util-visit-parents": ["unist-util-visit-parents@6.1.0", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-is": "^6.0.0" } }, "sha512-vKXxz6O38sKDj1mtx/k2cWvkkFBuYGx6uGrlzBkVeWCRF/F8sdI0j3Wbkz/5rVNRRuVc8UrgRdbCxNhmYXgP3w=="], + "universalify": ["universalify@0.1.2", "", {}, "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg=="], "update-browserslist-db": ["update-browserslist-db@1.2.3", "", { "dependencies": { "escalade": "^3.2.0", "picocolors": "^1.1.1" }, "peerDependencies": { "browserslist": ">= 4.21.0" }, "bin": { "update-browserslist-db": "cli.js" } }, "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w=="], - "validate-npm-package-name": ["validate-npm-package-name@8.0.0", "", {}, "sha512-SCv6OOV6Xj2/3cXy3dGmADluJTNcL3o7hZAglNPTe+WYuEuvxgJzxPrSDLZhF+CwyQOubqgecjMmTJGMVLWjYQ=="], + "update-check": ["update-check@1.5.4", "", { "dependencies": { "registry-auth-token": "3.3.2", "registry-url": "3.1.0" } }, "sha512-5YHsflzHP4t1G+8WGPlvKbJEbAJGCgw+Em+dGR1KmBUbr1J36SJBqlHLjR7oob7sco5hWHGQVcr9B2poIVDDTQ=="], + + "use-callback-ref": ["use-callback-ref@1.3.3", "", { "dependencies": { "tslib": "^2.0.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-jQL3lRnocaFtu3V00JToYz/4QkNWswxijDaCVNZRiRTO3HQDLsdu1ZtmIUvV4yPp+rvWm5j0y0TG/S61cuijTg=="], + + "use-sidecar": ["use-sidecar@1.1.3", "", { "dependencies": { "detect-node-es": "^1.1.0", "tslib": "^2.0.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Fedw0aZvkhynoPYlA5WXrMCAMm+nSWdZt6lzJQ7Ok8S6Q+VsHmHpRWndVRJ8Be0ZbkfPc5LRYH+5XrzXcEeLRQ=="], + + "use-sync-external-store": ["use-sync-external-store@1.7.0", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-6L+EeigHMQhdaIPNIFUKwfWJSwWFQ8gJbJ2DLOs5sDIegTwR9fRxvnM3uciHKjIZhFz+KAv2emhWMRvDmMcY8A=="], + + "validate-npm-package-name": ["validate-npm-package-name@5.0.1", "", {}, "sha512-OljLrQ9SQdOUqTaQxqL5dEfZWrXExyyWsozYlAWFawPVNuD83igl7uJD2RTkNMbniIYgt8l81eCJGIdQF7avLQ=="], "varint": ["varint@6.0.0", "", {}, "sha512-cXEIW6cfr15lFv563k4GuVuW/fiwjknytD37jIOLSdSWuOI6WnO/oKwmP2FQTU2l01LP8/M5TSAJpzUaGe3uWg=="], + "vary": ["vary@1.1.2", "", {}, "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg=="], + "verkit": ["verkit@0.5.0", "", {}, "sha512-u4J1hr6Y+C/hit34GwL3eIcUf3wngT8TlYUjK7tk0jxydKLAq3sYvifjdTDA6U3KCKRcQCQDGf/srjxfZF3l7g=="], + "vfile": ["vfile@6.0.3", "", { "dependencies": { "@types/unist": "^3.0.0", "vfile-message": "^4.0.0" } }, "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q=="], + + "vfile-message": ["vfile-message@4.0.4", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-stringify-position": "^4.0.0" } }, "sha512-66ycRswIkNmHH9PHku7ADtv5RVwgIrOcuv3J8Svz6h4qgGRrKVa+9/neuKyJZUXyOpYwLTvS+whZ4R2urHHgQg=="], + "vite": ["vite@8.3.8", "", { "dependencies": { "lightningcss": "^1.33.0", "picomatch": "^4.0.7", "postcss": "^8.5.32", "rolldown": "~1.2.18", "tinyglobby": "^0.2.17" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "@vitejs/devtools": "^0.7.1 || ^0.8.0", "esbuild": "^0.27.0 || ^0.28.0", "jiti": ">=1.21.0", "less": "^4.0.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "@vitejs/devtools", "esbuild", "jiti", "less", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-LzOn3h9rG/0vhLdXrV4yJ4QFA9eEoqCl+Yx+kGJd7aB9w6nfNgVHKSYwLPZUHrz4ZGa+t+kXjV9itvcHDLQouA=="], "vitefu": ["vitefu@1.1.3", "", { "peerDependencies": { "vite": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0" }, "optionalPeers": ["vite"] }, "sha512-ub4okH7Z5KLjb6hDyjqrGXqWtWvoYdU3IGm/NorpgHncKoLTCfRIbvlhBm7r0YstIaQRYlp4yEbFqDcKSzXSSg=="], @@ -1389,6 +2137,8 @@ "weak-lru-cache": ["weak-lru-cache@1.2.2", "", {}, "sha512-DEAoo25RfSYMuTGc9vPJzZcZullwIqRDSI9LOy+fkCJPi6hykCnfKaXTuPBDuXAUcqHXyOgFtHNp/kB2FjYHbw=="], + "web-namespaces": ["web-namespaces@2.0.1", "", {}, "sha512-bKr1DkiNa2krS7qxNtdrtHAmzuYGFQLiQ13TsorsdT6ULTkPLKuu5+GsFpDlg6JFjUTwX2DyhMPG2be8uPrqsQ=="], + "webidl-conversions": ["webidl-conversions@3.0.1", "", {}, "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ=="], "whatwg-mimetype": ["whatwg-mimetype@3.0.0", "", {}, "sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q=="], @@ -1397,6 +2147,8 @@ "which": ["which@2.0.2", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="], + "widest-line": ["widest-line@4.0.1", "", { "dependencies": { "string-width": "^5.0.1" } }, "sha512-o0cyEG0e8GPzT4iGHphIOh0cJOV8fivsXxddQasHPHfoZf1ZexrfeA21w2NaEN1RHE+fXlfISmOE8R9N3u3Qig=="], + "wrap-ansi": ["wrap-ansi@10.0.2", "", { "dependencies": { "ansi-styles": "^6.2.3", "string-width": "^8.2.0" } }, "sha512-6OLRNZqRntVGBm26ghZ5eZhCuWWyOkRCSn8XsOIuq5stpCE/tjLbdozd93naILZig0lmD8ANfRwnhn0DLeXGlg=="], "ws": ["ws@8.22.0", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg=="], @@ -1407,6 +2159,8 @@ "yallist": ["yallist@3.1.1", "", {}, "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g=="], + "yaml": ["yaml@2.9.1", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw=="], + "yargs": ["yargs@18.1.0", "", { "dependencies": { "cliui": "^9.0.1", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "string-width": "^8.2.1", "y18n": "^5.0.5", "yargs-parser": "^22.0.0" } }, "sha512-2rAgRKu54VsHkqI0/tYkmluGXHD4KW7yZoycuqDQ15QOTnc2VVfy0nN/1eMhnQLO00A+dwtK20xuCnc1YGeUyg=="], "yargs-parser": ["yargs-parser@22.0.0", "", {}, "sha512-rwu/ClNdSMpkSrUb+d6BRsSkLUq1fmfsY6TOpYzTwvwkg1/NRG85KBy3kq++A8LKQwX6lsu+aWad+2khvuXrqw=="], @@ -1415,22 +2169,44 @@ "yuku": ["yuku@0.28.1", "", { "optionalDependencies": { "@yuku-toolchain/darwin-arm64": "0.28.1", "@yuku-toolchain/darwin-x64": "0.28.1", "@yuku-toolchain/linux-arm64": "0.28.1", "@yuku-toolchain/linux-x64": "0.28.1", "@yuku-toolchain/win32-arm64": "0.28.1", "@yuku-toolchain/win32-x64": "0.28.1" }, "peerDependencies": { "@yuku-toolchain/wasm": "0.28.1" }, "optionalPeers": ["@yuku-toolchain/wasm"] }, "sha512-l899L8rSywcq9OLHf8JNQKpgyrBUL7UNJ7JqefoSVy0oYaFpdf3HoF72EVQFNWYr9HqMw0nGw1r1DefNujOnLQ=="], + "yuku-analyzer": ["yuku-analyzer@0.19.0", "", { "dependencies": { "@yuku-toolchain/types": "^0.19.0", "yuku-ast": "^0.19.0", "yuku-core": "0.19.0" } }, "sha512-Iu7DV5cWOQ3ERSA7oBquz/RT5IEGsUyUeCivYs9lQaZ4nSjM31yD17mH616JKcTyVoVWYivsFZ+twT3UyBosTA=="], + + "yuku-ast": ["yuku-ast@0.19.0", "", { "dependencies": { "@yuku-toolchain/types": "^0.19.0" } }, "sha512-PyCsiScaelhxBGzL8dyeJkLqvRZycoh78R31Vrt/WqYrm0hMFoKwIw/X7Dx5mBKLWAMlV9I9HEyBOHnj2gZVyw=="], + + "yuku-core": ["yuku-core@0.19.0", "", { "dependencies": { "@yuku-toolchain/types": "^0.19.0" }, "optionalDependencies": { "@yuku-core/binding-android-arm64": "0.19.0", "@yuku-core/binding-darwin-arm64": "0.19.0", "@yuku-core/binding-darwin-x64": "0.19.0", "@yuku-core/binding-freebsd-x64": "0.19.0", "@yuku-core/binding-linux-arm-gnu": "0.19.0", "@yuku-core/binding-linux-arm-musl": "0.19.0", "@yuku-core/binding-linux-arm64-gnu": "0.19.0", "@yuku-core/binding-linux-arm64-musl": "0.19.0", "@yuku-core/binding-linux-x64-gnu": "0.19.0", "@yuku-core/binding-linux-x64-musl": "0.19.0", "@yuku-core/binding-win32-arm64": "0.19.0", "@yuku-core/binding-win32-x64": "0.19.0" } }, "sha512-kYK9e1XdfirNhkipzW0wmMcSWcVF/CWnuugodfVYRCUwvoBefweL9HzB96OiKEhsx78V5WbUxbJqlizMX869Qg=="], + + "zbsearch": ["zbsearch@4.0.4", "", {}, "sha512-uajYItKQcOP6f1z+XqzJSIx1jQPe7PbXajElh7r60KGc1MoSIn/hH9d++SvtkT78GXrZB4fah/e8Ts8jFh2CGw=="], + "zimmerframe": ["zimmerframe@1.1.4", "", {}, "sha512-B58NGBEoc8Y9MWWCQGl/gq9xBCe4IiKM0a2x7GZdQKOW5Exr8S1W24J6OgM1njK8xCRGvAJIL/MxXHf6SkmQKQ=="], - "zod": ["zod@4.6.6", "", {}, "sha512-4UmzQUF5fxvfcYHlbjBmejU+w+hbDnWFx4aS8kBx7nPBHcO2SqPbpAG8snbdg+Xse4pRefR98hgjFgIMCI/UhA=="], + "zod": ["zod@4.6.7", "", {}, "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg=="], + + "zwitch": ["zwitch@2.0.4", "", {}, "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A=="], + + "@angular-devkit/core/ajv": ["ajv@8.20.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="], "@angular-devkit/core/source-map": ["source-map@0.8.0", "", {}, "sha512-d8EqvL+k/SOXCreS/SUzg2ciyHqBBLcN/yuRjFsbvVhHTE2pgei7oAhmPM7kWFbkX6OSMQfUq4KbkF3au9lhYQ=="], "@angular-devkit/schematics/magic-string": ["magic-string@1.4.1", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.6.0" } }, "sha512-8lyCu36ErXR0J9uaGKlKQoiLZKmtI63YGLE8G2o9jyRPdr4X47LusSOwgOJOzcVtp81fTAAjxR7BwKz682Jhow=="], + "@angular/cli/zod": ["zod@4.6.6", "", {}, "sha512-4UmzQUF5fxvfcYHlbjBmejU+w+hbDnWFx4aS8kBx7nPBHcO2SqPbpAG8snbdg+Xse4pRefR98hgjFgIMCI/UhA=="], + "@angular/compiler-cli/@babel/core": ["@babel/core@8.0.1", "", { "dependencies": { "@babel/code-frame": "^8.0.0", "@babel/generator": "^8.0.0", "@babel/helper-compilation-targets": "^8.0.0", "@babel/helpers": "^8.0.0", "@babel/parser": "^8.0.0", "@babel/template": "^8.0.0", "@babel/traverse": "^8.0.0", "@babel/types": "^8.0.0", "@types/gensync": "^1.0.5", "convert-source-map": "^2.0.0", "empathic": "^2.0.1", "gensync": "^1.0.0-beta.2", "import-meta-resolve": "^4.2.0", "json5": "^2.2.3", "obug": "^2.1.1", "semver": "^7.7.3" } }, "sha512-5FgxM4dLQpMJHSiVATk8foW263dVHQHBVpXYiimNECVWG01f4nFyEbQixeT6Mwvg7TayREJ2gpKl3o2RoMdnqw=="], "@angular/compiler-cli/convert-source-map": ["convert-source-map@1.9.0", "", {}, "sha512-ASFBup0Mz1uyiIjANan1jzLQami9z1PoYSZCiiYW2FczPbenXc45FZdBZLzOT+r6+iciuEModtmCti+hjaAk0A=="], "@angular/compiler-cli/typescript": ["typescript@6.0.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw=="], + "@angular/forms/zod": ["zod@4.6.6", "", {}, "sha512-4UmzQUF5fxvfcYHlbjBmejU+w+hbDnWFx4aS8kBx7nPBHcO2SqPbpAG8snbdg+Xse4pRefR98hgjFgIMCI/UhA=="], + + "@antfu/install-pkg/package-manager-detector": ["package-manager-detector@1.9.0", "", {}, "sha512-zAMfbta9nPA8AKkA4WdmNAT8R8s6Dk0/xwPsqNnRidMFcLo1YkLuPDTgs2f64XdzS8vbLNnoJ+uUIkgbz7oRHA=="], + + "@arethetypeswrong/core/typescript": ["typescript@5.6.1-rc", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-E3b2+1zEFu84jB0YQi9BORDjz9+jGbwwy1Zi3G0LUNw7a7cePUrHMRNy8aPh53nXpkFGVHSxIZo5vKTfYaFiBQ=="], + "@babel/core/semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="], + "@babel/helper-compilation-targets/lru-cache": ["lru-cache@5.1.1", "", { "dependencies": { "yallist": "^3.0.2" } }, "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w=="], + "@babel/helper-compilation-targets/semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="], "@babel/helper-module-imports/@babel/traverse": ["@babel/traverse@7.29.10", "", { "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/generator": "^7.29.8", "@babel/helper-globals": "^7.29.7", "@babel/parser": "^7.29.9", "@babel/template": "^7.29.7", "@babel/types": "^7.29.8", "debug": "^4.3.1" } }, "sha512-B3lYAs2nkKskbgQ1nfy8Ma9ao9Q1rntTAQHrzzyDuj+TSO+X3le6PfWwqDvodsb+OumE10eMFfuMCTQSQ5iuIQ=="], @@ -1475,6 +2251,14 @@ "@manypkg/get-packages/fs-extra": ["fs-extra@8.1.0", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^4.0.0", "universalify": "^0.1.0" } }, "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g=="], + "@mdx-js/mdx/estree-walker": ["estree-walker@3.0.3", "", { "dependencies": { "@types/estree": "^1.0.0" } }, "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g=="], + + "@mdx-js/mdx/source-map": ["source-map@0.7.6", "", {}, "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ=="], + + "@modelcontextprotocol/core/zod": ["zod@4.6.6", "", {}, "sha512-4UmzQUF5fxvfcYHlbjBmejU+w+hbDnWFx4aS8kBx7nPBHcO2SqPbpAG8snbdg+Xse4pRefR98hgjFgIMCI/UhA=="], + + "@modelcontextprotocol/server/zod": ["zod@4.6.6", "", {}, "sha512-4UmzQUF5fxvfcYHlbjBmejU+w+hbDnWFx4aS8kBx7nPBHcO2SqPbpAG8snbdg+Xse4pRefR98hgjFgIMCI/UhA=="], + "@oxc-parser/binding-wasm32-wasi/@emnapi/core": ["@emnapi/core@2.0.0-alpha.6", "", { "dependencies": { "@emnapi/wasi-threads": "2.2.0", "tslib": "^2.4.0" } }, "sha512-MNVvMV7WtEJMgqaWJMvCyupK7Oi8sZctUIgPRZTsiS3cVvefk8DXPflOU3MSBddtj/rrYHygpYgpHDgwXnI3+w=="], "@oxc-parser/binding-wasm32-wasi/@emnapi/runtime": ["@emnapi/runtime@2.0.0-alpha.6", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-5ZR49ZsZ3cLvu5lkrVj6CMpHRgZjYz7XSlqK23GYYpyEqp749RVuIH0bEUKaGNghMh2pXRhIC3cnVrH28Y1j1Q=="], @@ -1489,12 +2273,6 @@ "@schematics/angular/typescript": ["typescript@6.0.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw=="], - "@solidjs/babel-plugin/@babel/helper-module-imports": ["@babel/helper-module-imports@7.18.6", "", { "dependencies": { "@babel/types": "^7.18.6" } }, "sha512-0NFvs3VkuSYbFi1x2Vd6tKrywq+z/cLeYC/RJNFrIX/30Bf5aiGYbtvGXolEktzJH8o5E5KJ3tT+nkxuuZFVlA=="], - - "@solidjs/babel-plugin/parse5": ["parse5@7.3.0", "", { "dependencies": { "entities": "^6.0.0" } }, "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw=="], - - "@solidjs/vite-plugin/@babel/core": ["@babel/core@7.29.13", "", { "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/generator": "^7.29.13", "@babel/helper-compilation-targets": "^7.29.13", "@babel/helper-module-transforms": "^7.29.13", "@babel/helpers": "^7.29.13", "@babel/parser": "^7.29.13", "@babel/template": "^7.29.7", "@babel/traverse": "^7.29.13", "@babel/types": "^7.29.11", "@jridgewell/remapping": "^2.3.5", "convert-source-map": "^2.0.0", "debug": "^4.1.0", "gensync": "^1.0.0-beta.2", "json5": "^2.2.3", "semver": "^6.3.1" } }, "sha512-j1nvOQCZYSgp7HLmisnCXFTpVvFODiijQ9QHkORfGKWH6YDtskTEeCJS7eV545GZ9UBzrq0e2xsOd5QQ5PjIqw=="], - "@sveltejs/vite-plugin-svelte/magic-string": ["magic-string@1.4.1", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.6.0" } }, "sha512-8lyCu36ErXR0J9uaGKlKQoiLZKmtI63YGLE8G2o9jyRPdr4X47LusSOwgOJOzcVtp81fTAAjxR7BwKz682Jhow=="], "@sveltejs/vite-plugin-svelte/obug": ["obug@2.2.1", "", {}, "sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q=="], @@ -1513,27 +2291,37 @@ "@tailwindcss/oxide-wasm32-wasi/tslib": ["tslib@2.9.1", "", { "bundled": true }, "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA=="], + "@tailwindcss/postcss/postcss": ["postcss@8.5.31", "", { "dependencies": { "nanoid": "^3.3.20", "picocolors": "^1.1.1", "source-map-js": "^1.2.2" } }, "sha512-YUbWYCgErwnMAVkjUnYa+KlMBzGpHwiIt/DE7f0G33AuX2LH9UcTk6KgWxd3zRU+pN3u/C+Xl3EnMLM4Hea7Sg=="], + "@volar/language-service/typescript": ["typescript@6.0.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw=="], "@volar/typescript/typescript": ["typescript@6.0.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw=="], - "@vue/compiler-sfc/postcss": ["postcss@8.5.33", "", { "dependencies": { "nanoid": "^3.3.20", "picocolors": "^1.1.1", "source-map-js": "^1.2.2" } }, "sha512-RVHEU9/Pp1Fnjr/MpAJsZoADukCKhfIi15OunEYiGktIkYLkPVvC1sioWolGDS7XByMTx9m/IGbro0Js13zhnQ=="], + "babel-plugin-react-compiler/@babel/types": ["@babel/types@7.29.0", "", { "dependencies": { "@babel/helper-string-parser": "^7.27.1", "@babel/helper-validator-identifier": "^7.28.5" } }, "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A=="], - "ajv-formats/ajv": ["ajv@8.18.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A=="], + "beasties/postcss": ["postcss@8.5.31", "", { "dependencies": { "nanoid": "^3.3.20", "picocolors": "^1.1.1", "source-map-js": "^1.2.2" } }, "sha512-YUbWYCgErwnMAVkjUnYa+KlMBzGpHwiIt/DE7f0G33AuX2LH9UcTk6KgWxd3zRU+pN3u/C+Xl3EnMLM4Hea7Sg=="], - "babel-plugin-react-compiler/@babel/types": ["@babel/types@7.29.0", "", { "dependencies": { "@babel/helper-string-parser": "^7.27.1", "@babel/helper-validator-identifier": "^7.28.5" } }, "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A=="], + "boxen/chalk": ["chalk@5.6.2", "", {}, "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA=="], + + "boxen/string-width": ["string-width@5.1.2", "", { "dependencies": { "eastasianwidth": "^0.2.0", "emoji-regex": "^9.2.2", "strip-ansi": "^7.0.1" } }, "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA=="], + + "boxen/wrap-ansi": ["wrap-ansi@8.1.0", "", { "dependencies": { "ansi-styles": "^6.1.0", "string-width": "^5.0.1", "strip-ansi": "^7.0.1" } }, "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ=="], "classy-store-angular-example/@angular/build": ["@angular/build@22.2.7", "", { "dependencies": { "@ampproject/remapping": "2.3.0", "@angular-devkit/architect": "0.2202.7", "@babel/core": "8.0.5", "@inquirer/confirm": "6.3.2", "@parcel/watcher": "2.6.0", "@vitejs/plugin-basic-ssl": "2.3.0", "beasties": "0.5.4", "browserslist": "^4.26.0", "chokidar": "5.0.0", "esbuild": "0.28.2", "https-proxy-agent": "9.1.0", "jsonc-parser": "3.3.1", "listr2": "11.1.0", "magic-string": "1.4.1", "mrmime": "2.0.1", "oxc-parser": "0.156.0", "parse5-html-rewriting-stream": "8.0.1", "picomatch": "4.0.7", "piscina": "5.3.2", "rolldown": "1.2.16", "sass": "1.104.1", "sass-embedded": "1.104.1", "semver": "7.8.5", "source-map-support": "0.5.21", "tinyglobby": "0.2.17", "vite": "8.3.5", "xxhash-wasm": "1.1.0" }, "optionalDependencies": { "@oxc-parser/binding-wasm32-wasi": "0.156.0", "lmdb": "3.5.6" }, "peerDependencies": { "@angular/compiler": "^22.0.0", "@angular/compiler-cli": "^22.0.0", "@angular/core": "^22.0.0", "@angular/localize": "^22.0.0", "@angular/platform-browser": "^22.0.0", "@angular/platform-server": "^22.0.0", "@angular/service-worker": "^22.0.0", "@angular/ssr": "^22.2.7", "istanbul-lib-instrument": "^6.0.0", "karma": "^6.4.0", "less": "^4.2.0", "ng-packagr": "^22.0.0", "postcss": "^8.4.0", "rollup": "^4.0.0", "tailwindcss": "^2.0.0 || ^3.0.0 || ^4.0.0", "tslib": "^2.3.0", "typescript": ">=6.0 <6.1", "vitest": "^4.0.8 || ^5.0.0" }, "optionalPeers": ["@angular/core", "@angular/localize", "@angular/platform-browser", "@angular/platform-server", "@angular/service-worker", "@angular/ssr", "istanbul-lib-instrument", "karma", "less", "ng-packagr", "postcss", "rollup", "tailwindcss", "vitest"] }, "sha512-tQGzQPHvPK2oG5CqAsOMayU49WliSLlFV001poDpClmZ5d7cBsPeUZZlsEv84aMkplFDfhxqj6Guqd38T9HRdQ=="], "classy-store-angular-example/typescript": ["typescript@6.0.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw=="], - "classy-store-solid-example/typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="], - "classy-store-svelte-example/svelte-check": ["svelte-check@4.7.8", "", { "dependencies": { "@jridgewell/trace-mapping": "^0.3.25", "@sveltejs/load-config": "^0.2.3", "chokidar": "^4.0.1", "fdir": "^6.2.0", "picocolors": "^1.0.0", "sade": "^1.7.4" }, "peerDependencies": { "svelte": "^4.0.0 || ^5.0.0-next.0", "typescript": "^5.0.0 || ^6.0.0" }, "bin": { "svelte-check": "bin/svelte-check" } }, "sha512-laZ49GFHZ3b0z2PWinJWL0syehc/PTR8aHaUaTiBkWJ+4Y38nhxjmXsSz7CbGa3VdKopViVbrBH3bGNqIAI0bQ=="], - "classy-store-svelte-example/typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="], + "classy-store-svelte-example/typescript": ["typescript@6.0.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw=="], + + "classy-store-vue-example/typescript": ["typescript@6.0.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw=="], + + "cli-highlight/parse5": ["parse5@5.1.1", "", {}, "sha512-ugq4DFI0Ptb+WWjAdOK16+u/nHfiIrcE+sh8kZMaM0WllQKLI9rOUq6c2b7cwPkXdzfQESqvoqK6ug7U/Yyzug=="], + + "cli-highlight/yargs": ["yargs@16.2.2", "", { "dependencies": { "cliui": "^7.0.2", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "require-directory": "^2.1.1", "string-width": "^4.2.0", "y18n": "^5.0.5", "yargs-parser": "^20.2.2" } }, "sha512-Nt9ZJjXTv5R8MHbqby/wXQ6Gi0Bb3TcYZkR1bzuL4yB2OxWPkXknz513gEF0GoA6tn00UpbPvERW8rzCuWCA6w=="], - "classy-store-vue-example/typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="], + "cli-truncate/string-width": ["string-width@8.3.0", "", { "dependencies": { "get-east-asian-width": "^1.5.0", "strip-ansi": "^7.1.2" } }, "sha512-ZbmZM0JCihQN91dWnxoipT2KOEyHqEyfRXUyjuRhW8b/xnqPDoq4gWEVApTVa9db2wN8mmoikgFBbjh71+cGeQ=="], "cliui/string-width": ["string-width@7.2.0", "", { "dependencies": { "emoji-regex": "^10.3.0", "get-east-asian-width": "^1.0.0", "strip-ansi": "^7.1.0" } }, "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ=="], @@ -1541,36 +2329,94 @@ "cliui/wrap-ansi": ["wrap-ansi@9.0.2", "", { "dependencies": { "ansi-styles": "^6.2.1", "string-width": "^7.0.0", "strip-ansi": "^7.1.0" } }, "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww=="], + "compression/debug": ["debug@2.6.9", "", { "dependencies": { "ms": "2.0.0" } }, "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA=="], + + "cytoscape-fcose/cose-base": ["cose-base@2.2.0", "", { "dependencies": { "layout-base": "^2.0.0" } }, "sha512-AzlgcsCbUMymkADOJtQm3wO9S3ltPfYOFD5033keQn9NJzIbtnZj+UdBJe7DYml/8TdbtHJW3j58SOnKhWY/5g=="], + + "d3-dsv/commander": ["commander@7.2.0", "", {}, "sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw=="], + + "d3-dsv/iconv-lite": ["iconv-lite@0.6.3", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw=="], + + "d3-sankey/d3-array": ["d3-array@2.12.1", "", { "dependencies": { "internmap": "^1.0.0" } }, "sha512-B0ErZK/66mHtEsR1TkPEEkwdy+WDesimkM5gpZr5Dsg54BiTA5RXtYW5qTLIAcekaS9xfZrzBLF/OAkB3Qn1YQ=="], + + "d3-sankey/d3-shape": ["d3-shape@1.3.7", "", { "dependencies": { "d3-path": "1" } }, "sha512-EUkvKjqPFUAZyOlhY5gzCxCeI0Aep04LwIRpsZ/mLFelJiUfnK56jo5JMDSE7yyP2kLSb6LtF+S5chMk7uqPqw=="], + "dom-serializer/entities": ["entities@8.1.0", "", {}, "sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA=="], - "hosted-git-info/lru-cache": ["lru-cache@11.5.3", "", {}, "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg=="], + "estree-util-build-jsx/estree-walker": ["estree-walker@3.0.3", "", { "dependencies": { "@types/estree": "^1.0.0" } }, "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g=="], + + "estree-util-to-js/source-map": ["source-map@0.7.6", "", {}, "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ=="], + + "fumadocs-mdx/chokidar": ["chokidar@6.0.0", "", { "dependencies": { "readdirp": "^5.1.1" } }, "sha512-Ec2Z7wpcKBiMpR7DxteoqS/sq5G5d2A4fpxzPv6+fD7xNNdrTghn7L11YwV5EN1B3i72Erc3XVT5FkWIDx90+A=="], + + "fumadocs-mdx/magic-string": ["magic-string@1.4.5", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.6.0" } }, "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w=="], + + "hast-util-to-jsx-runtime/style-to-object": ["style-to-object@2.0.2", "", { "dependencies": { "inline-style-parser": "0.2.9" } }, "sha512-QmbXPUylqU80HAgTOJeEOdbA40W9KtxmjMhQy+tq+b8F2aoh3aQLuy82hh2jm2qsC9hR9eI0+eQidTMydKcqRA=="], "htmlparser2/entities": ["entities@8.1.0", "", {}, "sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA=="], "is-reference/@types/estree": ["@types/estree@1.0.8", "", {}, "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w=="], + "katex/commander": ["commander@15.1.0", "", {}, "sha512-cgnQ88TRrWcC7pVq46RzJVRMktu3W2RcbnoidnfBsl1bmDCBwJS/udcIZpKoCrbAYYaCqsz1yZCVIgbIaU3ddQ=="], + + "log-update/string-width": ["string-width@8.3.0", "", { "dependencies": { "get-east-asian-width": "^1.5.0", "strip-ansi": "^7.1.2" } }, "sha512-ZbmZM0JCihQN91dWnxoipT2KOEyHqEyfRXUyjuRhW8b/xnqPDoq4gWEVApTVa9db2wN8mmoikgFBbjh71+cGeQ=="], + "log-update/strip-ansi": ["strip-ansi@7.2.0", "", { "dependencies": { "ansi-regex": "^6.2.2" } }, "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w=="], + "marked-terminal/chalk": ["chalk@5.6.2", "", {}, "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA=="], + + "mermaid/marked": ["marked@16.4.2", "", { "bin": { "marked": "bin/marked.js" } }, "sha512-TI3V8YYWvkVf3KJe1dRkpnjs68JUPyEa5vjKrp1XEEJUAOaQc+Qj+L1qWbPd0SJuAdQkFU0h73sXXqwDYxsiDA=="], + "micromatch/picomatch": ["picomatch@2.3.2", "", {}, "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA=="], + "mime-types/mime-db": ["mime-db@1.33.0", "", {}, "sha512-BHJ/EKruNIqJf/QahvxwQZXKygOQ256myeN/Ew+THcAa5q+PjyTTMMeNQC4DZw5AwfvelsUrA6B67NKMqXDbzQ=="], + "next/postcss": ["postcss@8.5.23", "", { "dependencies": { "nanoid": "^3.3.16", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-g50586zr4bZmwFiTlflMu8E0bDTb5I5gertgwAKmsdUlTQIhZtunzUlD1WSzwcVWPoAVpsrA6vlfCD7oXvRwgg=="], + "npm-package-arg/validate-npm-package-name": ["validate-npm-package-name@8.0.0", "", {}, "sha512-SCv6OOV6Xj2/3cXy3dGmADluJTNcL3o7hZAglNPTe+WYuEuvxgJzxPrSDLZhF+CwyQOubqgecjMmTJGMVLWjYQ=="], + + "ora/chalk": ["chalk@5.6.2", "", {}, "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA=="], + + "ora/string-width": ["string-width@8.3.0", "", { "dependencies": { "get-east-asian-width": "^1.5.0", "strip-ansi": "^7.1.2" } }, "sha512-ZbmZM0JCihQN91dWnxoipT2KOEyHqEyfRXUyjuRhW8b/xnqPDoq4gWEVApTVa9db2wN8mmoikgFBbjh71+cGeQ=="], + "oxc-parser/@oxc-project/types": ["@oxc-project/types@0.156.0", "", {}, "sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw=="], + "parse-entities/@types/unist": ["@types/unist@2.0.11", "", {}, "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA=="], + "parse5/entities": ["entities@8.1.0", "", {}, "sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA=="], "parse5-html-rewriting-stream/entities": ["entities@8.1.0", "", {}, "sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA=="], + "parse5-htmlparser2-tree-adapter/parse5": ["parse5@6.0.1", "", {}, "sha512-Ofn/CTFzRGTTxwpNEs9PP93gXShHcTq255nzRYSKe8AkVpZY7e1fpmTfOyoIvjP5HG7Z2ZM7VS9PPhQGW2pOpw=="], + + "publint/package-manager-detector": ["package-manager-detector@1.9.0", "", {}, "sha512-zAMfbta9nPA8AKkA4WdmNAT8R8s6Dk0/xwPsqNnRidMFcLo1YkLuPDTgs2f64XdzS8vbLNnoJ+uUIkgbz7oRHA=="], + "read-yaml-file/js-yaml": ["js-yaml@3.15.2", "", { "dependencies": { "argparse": "^1.0.7", "esprima": "^4.0.0" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-6EuL879VkRA+1Cz578mKMiKvjPNEuk6+r1JaFzoSWejZmtf7xWbIyw1e3KkxlkzTIt9Taw6JBhEppG7utc1P+w=="], - "string-width/strip-ansi": ["strip-ansi@7.2.0", "", { "dependencies": { "ansi-regex": "^6.2.2" } }, "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w=="], + "sass-embedded/supports-color": ["supports-color@8.1.1", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q=="], - "unconfig-core/quansync": ["quansync@1.0.0", "", {}, "sha512-5xZacEEufv3HSTPQuchrvV6soaiACMFnq1H8wkVioctoH3TRha9Sz66lOxRwPK/qZj7HPiSveih9yAyh98gvqA=="], + "serve/chalk": ["chalk@5.0.1", "", {}, "sha512-Fo07WOYGqMfCWHOzSXOt2CxDbC6skS/jO9ynEcmpANMoPrD+W1r1K6Vx7iNm+AQmETU1Xr2t+n8nzkV9t6xh3w=="], + + "serve-handler/bytes": ["bytes@3.0.0", "", {}, "sha512-pMhOfFDPiv9t5jjIXkHosWmkSyQbvsgEVNkz0ERHbuLh2T/7j4Mqqpz523Fe8MVY89KC6Sh/QfS2sM+SjgFDcw=="], + + "slice-ansi/ansi-styles": ["ansi-styles@6.2.3", "", {}, "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg=="], + + "slice-ansi/is-fullwidth-code-point": ["is-fullwidth-code-point@5.1.0", "", { "dependencies": { "get-east-asian-width": "^1.3.1" } }, "sha512-5XHYaSyiqADb4RnZ1Bdad6cPp8Toise4TzEjcOYDHZkTCbKgiUl7WTUCpNWHuxmDt91wnsZBc9xinNzopv3JMQ=="], - "vite/postcss": ["postcss@8.5.33", "", { "dependencies": { "nanoid": "^3.3.20", "picocolors": "^1.1.1", "source-map-js": "^1.2.2" } }, "sha512-RVHEU9/Pp1Fnjr/MpAJsZoADukCKhfIi15OunEYiGktIkYLkPVvC1sioWolGDS7XByMTx9m/IGbro0Js13zhnQ=="], + "strip-ansi/ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="], + + "unconfig-core/quansync": ["quansync@1.0.0", "", {}, "sha512-5xZacEEufv3HSTPQuchrvV6soaiACMFnq1H8wkVioctoH3TRha9Sz66lOxRwPK/qZj7HPiSveih9yAyh98gvqA=="], "vite/rolldown": ["rolldown@1.2.19", "", { "dependencies": { "@oxc-project/types": "=0.156.0", "@rolldown/pluginutils": "^1.0.0" }, "optionalDependencies": { "@rolldown/binding-android-arm-eabi": "1.2.19", "@rolldown/binding-android-arm64": "1.2.19", "@rolldown/binding-darwin-arm64": "1.2.19", "@rolldown/binding-darwin-x64": "1.2.19", "@rolldown/binding-freebsd-x64": "1.2.19", "@rolldown/binding-linux-arm-gnueabihf": "1.2.19", "@rolldown/binding-linux-arm64-gnu": "1.2.19", "@rolldown/binding-linux-arm64-musl": "1.2.19", "@rolldown/binding-linux-ppc64-gnu": "1.2.19", "@rolldown/binding-linux-s390x-gnu": "1.2.19", "@rolldown/binding-linux-x64-gnu": "1.2.19", "@rolldown/binding-linux-x64-musl": "1.2.19", "@rolldown/binding-openharmony-arm64": "1.2.19", "@rolldown/binding-wasm32-wasi": "1.2.19", "@rolldown/binding-win32-arm64-msvc": "1.2.19", "@rolldown/binding-win32-x64-msvc": "1.2.19" }, "bin": { "rolldown": "./bin/cli.mjs" } }, "sha512-QIiV1J9d0pzN4jeeTH4sjPy0AZ6cAy2cG0ExeoE1+U8Rvj+hR3gYkokx0YbeUNGlZqiQJJ2utcETe0oKXwzsuA=="], + "widest-line/string-width": ["string-width@5.1.2", "", { "dependencies": { "eastasianwidth": "^0.2.0", "emoji-regex": "^9.2.2", "strip-ansi": "^7.0.1" } }, "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA=="], + + "wrap-ansi/ansi-styles": ["ansi-styles@6.2.3", "", {}, "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg=="], + + "wrap-ansi/string-width": ["string-width@8.3.0", "", { "dependencies": { "get-east-asian-width": "^1.5.0", "strip-ansi": "^7.1.2" } }, "sha512-ZbmZM0JCihQN91dWnxoipT2KOEyHqEyfRXUyjuRhW8b/xnqPDoq4gWEVApTVa9db2wN8mmoikgFBbjh71+cGeQ=="], + + "yargs/string-width": ["string-width@8.3.0", "", { "dependencies": { "get-east-asian-width": "^1.5.0", "strip-ansi": "^7.1.2" } }, "sha512-ZbmZM0JCihQN91dWnxoipT2KOEyHqEyfRXUyjuRhW8b/xnqPDoq4gWEVApTVa9db2wN8mmoikgFBbjh71+cGeQ=="], + "@angular/compiler-cli/@babel/core/@babel/code-frame": ["@babel/code-frame@8.0.6", "", { "dependencies": { "@babel/helper-validator-identifier": "^8.0.6", "js-tokens": "^10.0.0" } }, "sha512-uMHhvmDmwFiLuiozaoRYTZHqMFuu3fem/X9JY78lohAuLoh8LSGGC8JqUzo2cVuBsBxkjMZNk56CE7ock8Xxkw=="], "@angular/compiler-cli/@babel/core/@babel/generator": ["@babel/generator@8.0.6", "", { "dependencies": { "@babel/parser": "^8.0.6", "@babel/types": "^8.0.6", "@jridgewell/gen-mapping": "0.4.0-beta.0", "@jridgewell/trace-mapping": "^0.3.31", "@types/jsesc": "^2.5.0", "jsesc": "^3.0.2" } }, "sha512-/pcanjdRsonCexCuxgGD8fKnBLLzk2i9uM4kmcmGyyev2R5YDs+rafMYZ89RvaGY1mW8T7C5au0TyYaEeHBGng=="], @@ -1605,14 +2451,18 @@ "@rolldown/binding-wasm32-wasi/@emnapi/core/@emnapi/wasi-threads": ["@emnapi/wasi-threads@2.2.0", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-JP7OYH38Q7+pyTAe14raZHLQIK7BDKbdwji+Xi3pcd/6QkJYQH3SX4wu6EplGrGJWRepoNzedfm0G3B9Z4e9Rw=="], - "@solidjs/babel-plugin/parse5/entities": ["entities@6.0.1", "", {}, "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g=="], - - "@solidjs/vite-plugin/@babel/core/semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="], - "babel-plugin-react-compiler/@babel/types/@babel/helper-string-parser": ["@babel/helper-string-parser@7.27.1", "", {}, "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA=="], "babel-plugin-react-compiler/@babel/types/@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@7.28.5", "", {}, "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q=="], + "boxen/string-width/emoji-regex": ["emoji-regex@9.2.2", "", {}, "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg=="], + + "boxen/string-width/strip-ansi": ["strip-ansi@7.2.0", "", { "dependencies": { "ansi-regex": "^6.2.2" } }, "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w=="], + + "boxen/wrap-ansi/ansi-styles": ["ansi-styles@6.2.3", "", {}, "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg=="], + + "boxen/wrap-ansi/strip-ansi": ["strip-ansi@7.2.0", "", { "dependencies": { "ansi-regex": "^6.2.2" } }, "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w=="], + "classy-store-angular-example/@angular/build/@babel/core": ["@babel/core@8.0.5", "", { "dependencies": { "@babel/code-frame": "^8.0.0", "@babel/generator": "^8.0.5", "@babel/helper-compilation-targets": "^8.0.5", "@babel/helpers": "^8.0.5", "@babel/parser": "^8.0.5", "@babel/template": "^8.0.0", "@babel/traverse": "^8.0.5", "@babel/types": "^8.0.5", "@types/gensync": "^1.0.5", "convert-source-map": "^2.0.0", "empathic": "^2.0.1", "gensync": "^1.0.0-beta.2", "import-meta-resolve": "^4.2.0", "json5": "^2.2.3", "obug": "^2.1.1", "verkit": "^0.3.2" } }, "sha512-2/oWkgTbBYoqioCWAE4XJobOrzwxTDa5/XjDP3tJ1BhDr/owcd9qnXBp4xc3/2G5X4bvXM04nrxbRJxFcXAxFQ=="], "classy-store-angular-example/@angular/build/magic-string": ["magic-string@1.4.1", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.6.0" } }, "sha512-8lyCu36ErXR0J9uaGKlKQoiLZKmtI63YGLE8G2o9jyRPdr4X47LusSOwgOJOzcVtp81fTAAjxR7BwKz682Jhow=="], @@ -1623,13 +2473,31 @@ "classy-store-svelte-example/svelte-check/chokidar": ["chokidar@4.0.3", "", { "dependencies": { "readdirp": "^4.0.1" } }, "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA=="], + "cli-highlight/yargs/cliui": ["cliui@7.0.4", "", { "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.0", "wrap-ansi": "^7.0.0" } }, "sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ=="], + + "cli-highlight/yargs/yargs-parser": ["yargs-parser@20.2.9", "", {}, "sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w=="], + + "cli-truncate/string-width/strip-ansi": ["strip-ansi@7.2.0", "", { "dependencies": { "ansi-regex": "^6.2.2" } }, "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w=="], + + "cliui/string-width/emoji-regex": ["emoji-regex@10.6.0", "", {}, "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A=="], + "cliui/strip-ansi/ansi-regex": ["ansi-regex@6.2.2", "", {}, "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg=="], + "cliui/wrap-ansi/ansi-styles": ["ansi-styles@6.2.3", "", {}, "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg=="], + + "compression/debug/ms": ["ms@2.0.0", "", {}, "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A=="], + + "cytoscape-fcose/cose-base/layout-base": ["layout-base@2.0.1", "", {}, "sha512-dp3s92+uNI1hWIpPGH3jK2kxE2lMjdXdr+DH8ynZHpd6PUlH6x6cbuXnoMmiNumznqaNO31xu9e79F0uuZ0JFg=="], + + "d3-sankey/d3-shape/d3-path": ["d3-path@1.0.9", "", {}, "sha512-VLaYcn81dtHVTjEHd8B+pbe9yHWpXKZUC87PzoFmsFrJqgFwDe/qxfp5MlfsfM1V5E/iVt0MmEbWQ7FVIXh/bg=="], + + "hast-util-to-jsx-runtime/style-to-object/inline-style-parser": ["inline-style-parser@0.2.9", "", {}, "sha512-IttN8BqKLxzUrnTqHI+/hwAJQItBAUjdoHERCDv+oOuX48VP6bzW8+QjOXSfoevzq3YrYAwX1uLHp8TqO9yIeg=="], + "log-update/strip-ansi/ansi-regex": ["ansi-regex@6.2.2", "", {}, "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg=="], - "read-yaml-file/js-yaml/argparse": ["argparse@1.0.10", "", { "dependencies": { "sprintf-js": "~1.0.2" } }, "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg=="], + "ora/string-width/strip-ansi": ["strip-ansi@7.2.0", "", { "dependencies": { "ansi-regex": "^6.2.2" } }, "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w=="], - "string-width/strip-ansi/ansi-regex": ["ansi-regex@6.2.2", "", {}, "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg=="], + "read-yaml-file/js-yaml/argparse": ["argparse@1.0.10", "", { "dependencies": { "sprintf-js": "~1.0.2" } }, "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg=="], "vite/rolldown/@oxc-project/types": ["@oxc-project/types@0.156.0", "", {}, "sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw=="], @@ -1665,6 +2533,14 @@ "vite/rolldown/@rolldown/binding-win32-x64-msvc": ["@rolldown/binding-win32-x64-msvc@1.2.19", "", { "os": "win32", "cpu": "x64" }, "sha512-y/sqRRc6d7hECzOFc5n3LSeqctmIp9mMjY1Kq4s14uLPd/LZ4z7i1zrW6fMtp2mPeuQIC4e6ULMcwQzMomqQag=="], + "widest-line/string-width/emoji-regex": ["emoji-regex@9.2.2", "", {}, "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg=="], + + "widest-line/string-width/strip-ansi": ["strip-ansi@7.2.0", "", { "dependencies": { "ansi-regex": "^6.2.2" } }, "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w=="], + + "wrap-ansi/string-width/strip-ansi": ["strip-ansi@7.2.0", "", { "dependencies": { "ansi-regex": "^6.2.2" } }, "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w=="], + + "yargs/string-width/strip-ansi": ["strip-ansi@7.2.0", "", { "dependencies": { "ansi-regex": "^6.2.2" } }, "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w=="], + "@angular/compiler-cli/@babel/core/@babel/code-frame/@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@8.0.6", "", {}, "sha512-HYx0YmuchRxRSpnjvcNffnPS8DCauKNmnumIuHG3jnQAVewRA7kfJGwF13ayEpSZs7s4R/oBH4eppuXcAQd5JQ=="], "@angular/compiler-cli/@babel/core/@babel/code-frame/js-tokens": ["js-tokens@10.0.0", "", {}, "sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q=="], @@ -1683,6 +2559,10 @@ "@angular/compiler-cli/@babel/core/@babel/types/@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@8.0.6", "", {}, "sha512-HYx0YmuchRxRSpnjvcNffnPS8DCauKNmnumIuHG3jnQAVewRA7kfJGwF13ayEpSZs7s4R/oBH4eppuXcAQd5JQ=="], + "boxen/string-width/strip-ansi/ansi-regex": ["ansi-regex@6.2.2", "", {}, "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg=="], + + "boxen/wrap-ansi/strip-ansi/ansi-regex": ["ansi-regex@6.2.2", "", {}, "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg=="], + "classy-store-angular-example/@angular/build/@babel/core/@babel/code-frame": ["@babel/code-frame@8.0.6", "", { "dependencies": { "@babel/helper-validator-identifier": "^8.0.6", "js-tokens": "^10.0.0" } }, "sha512-uMHhvmDmwFiLuiozaoRYTZHqMFuu3fem/X9JY78lohAuLoh8LSGGC8JqUzo2cVuBsBxkjMZNk56CE7ock8Xxkw=="], "classy-store-angular-example/@angular/build/@babel/core/@babel/generator": ["@babel/generator@8.0.6", "", { "dependencies": { "@babel/parser": "^8.0.6", "@babel/types": "^8.0.6", "@jridgewell/gen-mapping": "0.4.0-beta.0", "@jridgewell/trace-mapping": "^0.3.31", "@types/jsesc": "^2.5.0", "jsesc": "^3.0.2" } }, "sha512-/pcanjdRsonCexCuxgGD8fKnBLLzk2i9uM4kmcmGyyev2R5YDs+rafMYZ89RvaGY1mW8T7C5au0TyYaEeHBGng=="], @@ -1735,14 +2615,28 @@ "classy-store-angular-example/@angular/build/rolldown/@rolldown/binding-win32-x64-msvc": ["@rolldown/binding-win32-x64-msvc@1.2.16", "", { "os": "win32", "cpu": "x64" }, "sha512-1lv1KvX0Z871zfk7vw+dnXMMnHNyDwMzWG8Kv3HxDXMOhzCX4SHc7HK319fInP0i+0p9D8brkfzL7pJOaGl+tw=="], + "classy-store-angular-example/@angular/build/vite/postcss": ["postcss@8.5.31", "", { "dependencies": { "nanoid": "^3.3.20", "picocolors": "^1.1.1", "source-map-js": "^1.2.2" } }, "sha512-YUbWYCgErwnMAVkjUnYa+KlMBzGpHwiIt/DE7f0G33AuX2LH9UcTk6KgWxd3zRU+pN3u/C+Xl3EnMLM4Hea7Sg=="], + "classy-store-angular-example/@angular/build/vite/rolldown": ["rolldown@1.2.14", "", { "dependencies": { "@oxc-project/types": "=0.154.0", "@rolldown/pluginutils": "^1.0.0" }, "optionalDependencies": { "@rolldown/binding-android-arm-eabi": "1.2.14", "@rolldown/binding-android-arm64": "1.2.14", "@rolldown/binding-darwin-arm64": "1.2.14", "@rolldown/binding-darwin-x64": "1.2.14", "@rolldown/binding-freebsd-x64": "1.2.14", "@rolldown/binding-linux-arm-gnueabihf": "1.2.14", "@rolldown/binding-linux-arm64-gnu": "1.2.14", "@rolldown/binding-linux-arm64-musl": "1.2.14", "@rolldown/binding-linux-ppc64-gnu": "1.2.14", "@rolldown/binding-linux-s390x-gnu": "1.2.14", "@rolldown/binding-linux-x64-gnu": "1.2.14", "@rolldown/binding-linux-x64-musl": "1.2.14", "@rolldown/binding-openharmony-arm64": "1.2.14", "@rolldown/binding-win32-arm64-msvc": "1.2.14", "@rolldown/binding-win32-x64-msvc": "1.2.14" }, "bin": { "rolldown": "./bin/cli.mjs" } }, "sha512-eTBTTqMR6uHKLgcUqpJP8ntzDI6V4LYA8negAMBEI7gkgVvOdrx6VsvS2Ym+83KhOPdLCHWJu0w7UQFJZhHKNw=="], "classy-store-svelte-example/svelte-check/chokidar/readdirp": ["readdirp@4.1.2", "", {}, "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg=="], + "cli-highlight/yargs/cliui/wrap-ansi": ["wrap-ansi@7.0.0", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q=="], + + "cli-truncate/string-width/strip-ansi/ansi-regex": ["ansi-regex@6.2.2", "", {}, "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg=="], + + "ora/string-width/strip-ansi/ansi-regex": ["ansi-regex@6.2.2", "", {}, "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg=="], + "vite/rolldown/@rolldown/binding-wasm32-wasi/@emnapi/core": ["@emnapi/core@2.0.0-beta.2", "", { "dependencies": { "@emnapi/wasi-threads": "2.2.0", "tslib": "^2.4.0" } }, "sha512-MzCVoWtcg4Pm2B3je5mMvYMvj3MmBKw+fU7vbsJc9/iT8ip6/eYIHo/Dsm/mr+wsHB6SEyJDuxB09Yy6r/8+4A=="], "vite/rolldown/@rolldown/binding-wasm32-wasi/@emnapi/runtime": ["@emnapi/runtime@2.0.0-beta.2", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-JcrSPzPvZuNZvJqPTF9Fw25LbOJ8avzFVlaf2grmH4Cku0oGP47tRgqPZadcfj3YoZMHkFVnCYFbQM8I+i5QEw=="], + "widest-line/string-width/strip-ansi/ansi-regex": ["ansi-regex@6.2.2", "", {}, "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg=="], + + "wrap-ansi/string-width/strip-ansi/ansi-regex": ["ansi-regex@6.2.2", "", {}, "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg=="], + + "yargs/string-width/strip-ansi/ansi-regex": ["ansi-regex@6.2.2", "", {}, "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg=="], + "classy-store-angular-example/@angular/build/@babel/core/@babel/code-frame/@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@8.0.6", "", {}, "sha512-HYx0YmuchRxRSpnjvcNffnPS8DCauKNmnumIuHG3jnQAVewRA7kfJGwF13ayEpSZs7s4R/oBH4eppuXcAQd5JQ=="], "classy-store-angular-example/@angular/build/@babel/core/@babel/code-frame/js-tokens": ["js-tokens@10.0.0", "", {}, "sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q=="], diff --git a/docs/decisions/0001-a-function-read-through-the-store-is-a-method.md b/docs/decisions/0001-a-function-read-through-the-store-is-a-method.md new file mode 100644 index 00000000..6b350afb --- /dev/null +++ b/docs/decisions/0001-a-function-read-through-the-store-is-a-method.md @@ -0,0 +1,170 @@ +# 0001. A function in a field is a method when it is read through the store, and the object is never changed + +- **Status:** Accepted +- **Date:** 2026-11-25 +- **Kind:** public API, bug +- **Label:** Before 1.0 +- **Changes documented behaviour:** no + +## Context + +Before 1.0, the `get` trap binds every function it reads to the proxy. That +gives defects of its own: + +- A function in a list is a new wrapper on every read, so + `store.callbacks.indexOf(store.callbacks[0])` is `-1`, and + `store.callbacks.splice(store.callbacks.indexOf(first), 1)` removes the + last callback. +- A class held as a value comes back as a bound wrapper: + `store.Model.label` is `undefined`, and + `new store.Model('x') instanceof store.Model` is `false`. The same holds + for `constructor`. +- `store.f = store.f` writes a wrapper back. +- A getter that calls a function held in a field does not see a later + replacement of that function. +- A read of a read-only function property throws. + +A rule is needed for which functions a store hands out as methods (bound to +the proxy, run as one transaction) and which it hands out as data. + +## Decision + +A function is a **method**, bound to the proxy of the object that holds it +and run as one transaction, in two cases: + +1. It is found on the prototype chain, under any key but `constructor`. Any + kind of function. This is the rule from before 1.0. +2. It is the value of an own data property of an object that is not an + array, **and it is read through the store**. + +Case 2 does not apply, and the function is handed out as it is, when: + +- it is a class or a built-in constructor, told by its own `prototype` + property being read-only; +- it is a method that a read through any store handed out before; +- it is frozen, or it is a store; +- the property that holds it is read-only and not configurable. + +So an arrow function, a shorthand method, an `async` function, a bound +function, a generator method and a `function` are all methods when read +through the store. + +**The object is never changed.** The raw object and every snapshot hold each +function as it was written. There is one method per object and function, so +`store.f === store.f`, and the method takes the name of the key it was first +read under. + +A method written back: + +- A method that the same object handed out is stored as the function it + wraps. `store.f = store.f` is no change; `store.b = store.a` stores `a`'s + function. +- A method that another object handed out is stored as it is. It is data + there, and stays bound to the object it came from. + +A read of a function in a field counts as a read for a getter. + +**Short path.** The full test asks for the property's descriptor. Once an +object has handed out the method for a function, a later read skips the +descriptor while the object is extensible, no definition through the store +has made one of its properties read-only, and the function is not frozen. A +function on the prototype chain never needs the descriptor. + +The change lands only if the core benchmark's `store.method` stays inside +the spread of the commit before it on both engines, and two new benchmark +rows stay inside these bounds against that commit: a call of a method held +in a field at most 10% slower, a read and call of an arrow function held in +a field at most 1.6 times slower. The baseline is the commit before. A +difference inside the spread recorded when the cost limits of +`CONSTRAINTS.md` were measured is noise, but the figures of that +measurement are no baseline, because record 0012 has moved them by then. +The two new rows are recorded before and after in +the commit message. + +## Alternatives considered + +### Strict: only a function on the prototype chain is a method + +A method in an object literal is then not a transaction, throws when called +detached, and loses its transaction in silence. The base class of record +0011 would need an exception of its own. Not taken, and final for 1.0. + +### Born with: write the store's wrapper into the object + +It keeps the identity of a callback assigned to a declared field. It was +built, and it fails five ways: a store made from a copy of the object or of +a snapshot ran the old store's methods; a callback on a snapshot ignored the +`this` its caller passed; a getter read on a snapshot could write the live +store through an object's own method; a callback restored by `withHistory` +came back wrapped; and a read-only definition threw after it was made. Not +taken, and final for 1.0. + +### Every function with a `prototype` of its own is data + +It fixes a constructor held as a value. It also takes the binding and the +transaction away from `inc: function () {…}` in an object literal: two +notifications for two writes, a `TypeError` when called detached in strict +code, and a write to `globalThis` in code that is not strict. Before 1.0, +such a function is a bound method. Not taken, and final for 1.0. + +### Lenient: wrap every function on every read + +Except an element of a list, a class and `constructor`. It keeps the copied +wrapper and the stale getter. Not taken, and final for 1.0. + +### The same rule without the short path + +No read can throw, also after a change made on the raw object. It costs +every class method 2 to 3% on Node, a call of a method held in a field 10 to +15% against the code before 1.0, and a read and call of an arrow function +held in a field 1.6 to 1.8 times the time before 1.0. The one read it +protects is unspecified, and it throws before 1.0 as well. + +### Telling a bound function by its name + +A user can fake the name. + +## Consequences + +- `store.onSave === cb` is `false`, as it is before 1.0. + `snapshot(store).onSave === cb` is `true`. +- A method read through the store ignores the `this` its caller passes, as + it does before 1.0. An object of callbacks for another library is handed over from a + snapshot. +- A method is called on the store, not on a snapshot. A snapshot holds the + plain function: a method that writes `this` throws there in strict code, + and an arrow-function field of a `ClassyStore` subclass writes the live + store one write at a time, with one notification per write. Nothing + reports it. What a function read from a snapshot does is unspecified. +- `{...store}` copies methods, and a store built from that copy calls the old + store's methods, as it does before 1.0. A copy of a snapshot or of the object copies + plain functions. +- A constructor written as a `function` and held as a value is still handed + out as a method, as before 1.0: it is not `===` to itself, its statics are not + on what is read, and `instanceof` against it is `false`. `new` on it still + builds a real instance. The same holds for TypeScript's ES5 output of a + class. A real class, a built-in constructor and Babel's class shape (a + read-only `prototype`) are handed out as they are. A constructor that must + keep its identity is frozen or held in a list. +- Cost on Node: a call of a method held in a field is 270 nanoseconds against + 250 (about 8%); on Bun it stays at 177. A read and call of an arrow function + held in a field is 74 against 47 nanoseconds on Node and 39 against 35 on + Bun. A class method costs what it cost before 1.0. +- One read can still throw: after the store has handed out a method, a + definition on the raw object behind the store that makes the property + read-only makes the next read throw a `TypeError`. That is unspecified. + Before 1.0, every read of a read-only function property throws. + +- A property that is read-only and not configurable, for example after + `Object.freeze(store)`, hands out its function unbound. +- A class that does not extend `ClassyStore` and has an arrow-function field + still writes to the raw instance, unseen. Record 0011 answers it, and + record 0036 reports it if its check ships. +- Size: +228 bytes on the main entry, measured together with records 0002 + and 0011 (3,951 bytes for the three). +- Not run: the browser, framework and mutation suites; the `devtools` naming + reading the key; a component that calls an arrow method taken from a + snapshot; a compiler's real ES5 output (the rows were written by hand in + each compiler's shape). +- Open again if a way is found to tell a constructor written as `function` + from a method written as `function`. diff --git a/docs/decisions/0002-define-property-through-a-store-is-a-write.md b/docs/decisions/0002-define-property-through-a-store-is-a-write.md new file mode 100644 index 00000000..49bfef31 --- /dev/null +++ b/docs/decisions/0002-define-property-through-a-store-is-a-write.md @@ -0,0 +1,78 @@ +# 0002. `Object.defineProperty` through a store is a write, and nothing is refused + +- **Status:** Accepted +- **Date:** 2026-11-25 +- **Kind:** bug +- **Label:** Before 1.0: the tutorial says that `Object.defineProperty` + "bypasses assignment/deletion tracking" +- **Changes documented behaviour:** yes + +## Context + +Before 1.0, the `defineProperty` trap handles freezing only. The tutorial says +that `Object.defineProperty` "bypasses assignment/deletion tracking". The +result: + +- Defining a new data property sets the live value, notifies no one, and + stays out of the snapshot until the next ordinary write. +- Redefining a property that holds an object leaves the old object in place: + after `Object.defineProperty(s, 'child', {value: other})`, `s.child.n` + still reads the old child, and a later `s.child = other` counts as no + change. +- Defining `length` on a list leaves removed elements readable by index. +- After `Object.defineProperty(store.rows, 0, {value: 7})` the store returns + the old object and a snapshot shows 7. +- Freezing a removed container while its subtree is suspended detaches a + child without resuming it, so the next snapshot is stale once and a new + subscriber can miss a write (see record 0003). + +Class fields compiled as definitions reach this trap as data descriptors, so +the base class of record 0011 needs the trap to behave as a write. + +## Decision + +A definition through a store does the bookkeeping of a write: the value +becomes the property's child, or the old child is detached, and subscribers +are told when the value, the getter, the kind of property or its +enumerability changed. Every descriptor is still forwarded to the raw +object. `Object.freeze(store)` keeps working and stays silent. A definition +or a delete of a property that is or was an accessor clears the node's +getter cache, so a getter that read it is not left stale. No +`setPrototypeOf` trap is added. + +This commit stores a defined value as it is given. Record 0005 then changes +the trap to store the raw value. + +## Alternatives considered + +### Refuse accessor and read-only descriptors + +Immer does this. It costs 160 bytes more, most of it message text, and it +rules out the base class, whose fields arrive as definitions. An accessor or +a read-only definition works correctly on both layers after this decision, +so refusing it would forbid something that is right. Not taken, and final +for 1.0. + +### Refuse `Object.freeze(store)` + +MobX does this. It gives up a feature added on purpose and removes no code, +because a frozen root passed to `createClassyStore()` still needs the +read-only case. Not taken, and final for 1.0. + +### A `setPrototypeOf` trap that throws + +After record 0001, a method replaced on the prototype or a swapped prototype +is picked up. `persist` cannot swap a prototype. What is left is an +application that swaps the prototype of its own store on purpose, and that +is not the library's to forbid. Not taken, and final for 1.0. + +## Consequences + +- A definition through the store notifies and shows in the next snapshot. + The tutorial sentence about `defineProperty` changes. +- Size: +49 bytes on the main entry. 28 lines added and 9 removed in the + prototype; 17 unit tests changed, all of them tests that pinned the + defects above. Timings were inside the spread. +- What a prototype changed after its first read does stays unspecified + (record 0012). +- Open again if a use is found that needs a definition to be refused. diff --git a/docs/decisions/0003-suspension-stays-and-the-walk-to-a-detached-parent-goes.md b/docs/decisions/0003-suspension-stays-and-the-walk-to-a-detached-parent-goes.md new file mode 100644 index 00000000..b9010d56 --- /dev/null +++ b/docs/decisions/0003-suspension-stays-and-the-walk-to-a-detached-parent-goes.md @@ -0,0 +1,91 @@ +# 0003. Suspension stays; the walk to a detached parent goes + +- **Status:** Accepted +- **Date:** 2026-11-25 +- **Kind:** bug, simplification +- **Label:** Can follow 1.0: no documented behaviour changes +- **Changes documented behaviour:** no + +## Context + +When a subtree leaves the store and nothing observes it, the library +suspends it: each node saves its children's versions and drops its links. +Before 1.0, a suspended node also keeps a `detachedParent` pointer, and +`resumeScope()` walks those pointers up before a node resumes. + +That walk can loop. The `defineProperty` trap detaches a child of a +suspended container without resuming it first; the child keeps a pointer to +a container that no longer lists it, and two such pointers can form a loop. +Before 1.0, this read never returns: + +```ts +const store = createClassyStore({outer: {inner: {x: 1}}}); +const outer = store.outer; +const inner = outer.inner; +delete store.outer; +Object.defineProperty(outer, 'inner', {writable: false, configurable: false}); +snapshot(inner); +snapshot(inner); +inner.back = outer; +subscribe(inner, () => {})(); +inner.x; // never returns +``` + +The same cause, in a milder form, makes a snapshot under a frozen, removed +container stale once, and lets a subscriber added right after the freeze +miss a write. Without `WeakRef` the pointer is a strong link, so a held row +keeps its removed list alive. + +## Decision + +Remove the `detachedParent` pointer and the walk in `resumeScope()`. Keep +suspend and resume. Each node already saves its children's versions when it +is suspended, so each can resume on its own when it is touched. + +Left as it is: + +- The order in which owners are notified is unspecified. +- A subscription on a container that has left the store lasts while the + caller holds the store, the container or the unsubscribe function. The + tutorial gains that sentence in this change. +- A raw object changed while it is out of the store shows its old content in + the next snapshot. It is a case of "writes outside the proxy are not seen", + which the docs already state. + +The test of a runtime without `WeakRef`, which pinned the strong link, +changes with this decision. It asserts what the change makes true: with +`WeakRef` removed, a row that is held after its list was replaced no longer +keeps that list alive, and the row still reads, writes, notifies and +snapshots as a store of its own. Only "it works" is guaranteed in such a +runtime, so the memory half of the test is a change detector, and its file +says so. + +## Alternatives considered + +### Remove suspension as a whole + +85 lines. Without it, a write to a row that outlived 2,000 replaced lists +costs 122,610 nanoseconds against 446, until the collector runs, and for as +long as anything keeps the old lists alive. + +### Resume in the `defineProperty` trap + +A one-line fix that removes the hang. It is contained in record 0002 and is +harmless beside this decision, but it leaves the walk that causes the hang. + +### Hold a subscribed node strongly + +It would turn a forgotten unsubscribe into a leak. + +## Consequences + +- The read above returns. Ten lines out, one in, 36 bytes smaller on the main + entry, and the typecheck passes. 6 unit tests changed, all of them tests + that pinned the defects. The prototype was run twice in separate checkouts + with the same result. +- `resumeScope()` in `createClassyStore` becomes redundant and is removed in + the same commit (record 0020). +- This lands first among the core changes, because records 0002 and 0012 + touch the same traps. +- Open again if a case is found where a node cannot resume correctly on its + own. diff --git a/docs/decisions/0004-size-ceilings-for-every-entry.md b/docs/decisions/0004-size-ceilings-for-every-entry.md new file mode 100644 index 00000000..960fe1a2 --- /dev/null +++ b/docs/decisions/0004-size-ceilings-for-every-entry.md @@ -0,0 +1,261 @@ +# 0004. The size budgets move once, to a ceiling set for the whole set of 1.0 changes + +- **Status:** Accepted +- **Date:** 2026-11-25 +- **Kind:** constraint +- **Label:** Before 1.0 +- **Changes documented behaviour:** no + +## Context + +`CONSTRAINTS.md` holds a gzipped size budget for each entry point. Before +1.0, each budget was the measured size plus two to three percent: room for a +fix of a few lines, not for a feature. The main entry measured 3,661 bytes +against a budget of 3,750. + +The changes decided for 1.0 in records 0001 to 0046 do not fit those +budgets, and no subset worth shipping does. Before 1.0, the floor guard +(`bun run check:floor`) read only `CONSTRAINTS.md`, saw one difference for +the whole branch, and left its own file out of its scope. One decision +record anywhere on the branch would have switched it off for every later +change. + +This record is the one `CONSTRAINTS.md` points to for every size budget. + +## Decision + +Each budget gets a **ceiling**, set here once for the whole set of changes. + +| Entry | Before 1.0 | Budget before 1.0 | Estimate | Ceiling | What moves it | +| --------------------- | ---------: | ----------------: | -------: | ------: | ---------------------------------------------------------------- | +| `.` (the main entry) | 3,661 | 3,750 | 5,375 | 5,575 | The first table below | +| `./utils` adds | 2,686 | 2,750 | 4,216 | 4,350 | The second table below | +| `./collections` adds | 727 | 750 | 911 | 950 | The snapshot index, the membership rule, the mutator check | +| `./react` adds | 1,662 | 1,700 | 1,693 | 1,750 | The guard for a cyclic snapshot | +| `./vue` adds | 280 | 300 | 369 | 400 | The read-time ref, the server path, the setter that throws | +| `./angular` adds | 271 | 300 | 381 | 425 | The read-time signal, `untracked()`, the injector, its own check | +| `./solid` adds | 312 | 335 | 346 | 375 | The read-time accessor | +| `./svelte` adds | 182 | 200 | 182 | 200 | Nothing | +| `./react/server` adds | 153 | 175 | 153 | 175 | Nothing | + +All figures are gzipped bytes. An entry other than the main one is measured +together with the main entry and held to what it adds. + +**How a ceiling is set.** The estimate, plus an allowance for what was +decided and never built, plus the 2% every budget carries, rounded up to the +next 25 bytes. The allowances: 80 bytes on the main entry, because two built +combinations came out above the sum of their parts; 30 on `./utils` for +three parts of records 0021 and 0024 that no prototype holds; 20 on `./vue` +for the setter that throws; 30 on `./angular` for its own context check. + +**The main entry, change by change.** + +| Change | Record | Bytes | +| --------------------------------------------------------------------- | ------------ | -----: | +| The rule for functions | 0001 | +228 | +| `defineProperty` as a write | 0002 | +49 | +| The walk to a detached parent removed | 0003 | −36 | +| Raw values on write, and a child kept when its container is frozen | 0005 | +104 | +| Searches that find the object the caller holds | 0006 | +168 | +| `has` and `ownKeys` traps, a missing property as a value | 0007 | +156 | +| A delete that removes nothing | 0008 | +11 | +| A plain object from another realm | 0009 | +81 | +| Getters: one kind of dependency, errors, a getter that writes | 0010 | +281 | +| The base class | 0011 | +13 | +| A table per prototype in place of a descriptor lookup | 0012 | +180 | +| The delivery queue with its bound, setters, the rejection handler | 0013 to 0015 | +219 | +| The check for an `async` function in `batch()` | 0016 | +50 | +| Dead lines removed | 0020 | −32 | +| The hook through which `devtools` names a method | 0027 | +12 | +| Class getters on a derived prototype, and `this` in a snapshot getter | 0043 | +239 | +| A snapshot keeps a cycle | 0044 | −9 | +| Sum | | +1,714 | + +Measured on top of another change, not alone: record 0001 (on the strict +rule, record 0002 and the base class; the row is the three together, 3,951 +bytes, less the other two), the later parts of records 0005, 0006, 0010 and +0012 (each on the part before it), and record 0027 (on the first form of its +entries). Every other row is one change measured alone against the code +before 1.0. The sum puts the main entry near 5,375 bytes, 47% above its size +before 1.0. The messages were measured as the prototypes wrote them; the +codes of record 0035 shorten them, by about 100 bytes for the first set and +an unmeasured amount for the rest. + +**What `./utils` adds, change by change.** + +| Change | Record | Bytes | +| ---------------------------------------------------------------- | ------------------ | -----: | +| `persist`, `history` and `devtools` as one build | 0019 to 0025, 0027 | +710 | +| The `persist` rules of records 0021 to 0024, in their final form | 0021 to 0024 | +245 | +| The naming moved out of the core into `devtools.ts` | 0027 | +57 | +| The root store's getter values in what `devtools` sends | 0027, 0043 | +95 | +| Restore in place | 0030 | +113 | +| Each object entered once per restore | 0030 | +16 | +| A container that would refuse the restore is replaced | 0030 | +211 | +| `cloneSnapshot` made safe for a cycle | 0044 | +21 | +| `subscribeKey` without a snapshot of the whole store | 0031 | +62 | +| Sum | | +1,530 | + +The sum is 4,216 bytes. The first row is the first combined build of the +`persist`, `history` and `devtools` changes; the second is what the rules of +records 0021 to 0024 add to it in their final form, without a write-back +after a migration. Three small parts of those records are in neither build, +and the ceiling has 30 bytes for them. + +The +57 for the naming is what `./utils` adds on top of the main entry, as +every row of this table counts. Record 0027 gives 403 bytes for its entries +and 452 with the hook form, a difference of 49. The two figures differ by 8 +bytes because the main entry is 8 bytes smaller with the hook. + +**How a budget moves, and what enforces it.** + +- The first commit of the work is tooling only. `budgets.json` gets a + `ceiling` beside each budget, and the size script fails when a budget is + above its ceiling or a measured size is above its budget. +- **A ceiling does not move with the work.** The floor guard refuses a + commit that changes an existing ceiling together with anything else. The + first commit, which adds the ceilings, is the one exception, because there + is none before it. A ceiling changes only in a commit that holds the new + number and this record's reason for it, and nothing more, so it cannot + ride along with the change that needs it. +- **A budget moves with a line in this record.** The floor guard reads + `budgets.json` and `limits.json` as well as `CONSTRAINTS.md`, and blocks a + budget or a cost limit that rises unless the same commit adds a line to + this record: a budget or a cost limit that rises needs its line here. A + rule of `CONSTRAINTS.md` that is loosened needs a line in any record. +- **The guard checks every commit, itself included.** It walks the commits + from its start to the head and judges each against its parent. Its start + is the merge base with `main`, or, while `main` does not hold + `CONSTRAINTS.md`, the commit that added that file: the commits before it + were made with no bar. The branch is kept linear, and the guard fails on a + merge commit in its range rather than judge one. Last, it judges the + working tree (staged, unstaged and untracked files) against the head, so + that it is useful before a commit too. CI runs it on the pull request, and + it is run before each push. +- **Bar files.** Three files hold a part of the bar outside + `CONSTRAINTS.md`: the guard's own file `scripts/floor-guard.mjs`, the + coverage settings in `packages/classy-store/bunfig.toml`, and the list of + target files in `packages/classy-store/tests/mutation/runMutation.ts`. + The guard cannot read a loosened rule out of its own regular expressions, + so every change to one of these files counts as a change to the bar: the + commit passes only if it adds a line to a record under `docs/decisions/` + that says what changed and why. A change that tightens needs the line + too; it is one line. The guard does not scan its own file for its own + patterns, and the fixtures of its tests are put together when a test + runs, so that no file in the repository holds a line the guard would + flag. The first commit passes this rule like any other, with its lines in + the section "Changes to the tooling" below. +- **A test made smaller is named in the commit message.** The floor forbids + a deleted test file and a test file left with fewer assertions. Judged + per commit, that rule would also block two changes the work allows: a + test of public behaviour that a decision changes, and a test of internal + state rewritten when the internals change. Such a commit passes only if + its message has a line `Test-change: : ` for each such + file, and the reason names a decision (`decision N`) or the test of + public behaviour that covers the same fact (a path to a test file). In + the working tree, where no message exists yet, the guard reports it as a + note. +- **Where the numbers live.** `budgets.json` holds each entry as + `{"budget": …, "ceiling": …}`. An entry with no ceiling fails the size + script, as one with no budget does. The size rows of `CONSTRAINTS.md` + stop repeating the numbers and name `budgets.json`, so that a budget that + moves changes one file and the two cannot drift apart. +- **Each rule has a test.** The first commit adds tests for the size + script's two failures and for each rule of the guard, run on throwaway + repositories made by the test. +- A commit that grows an entry sets that entry's budget to its new measured + size plus 2%, adds a line with the measured size to the section "Measured + sizes" below, and stays under the ceiling. +- When the 1.0 work ends, before the release, every budget is the final measured size plus 2%. +- **A ceiling is an estimate and a tripwire, not a measurement.** A change + that would pass a ceiling is not committed, and the question goes back to a + decision. +- **The cost limits** of `CONSTRAINTS.md` are expected to hold; the whole set + was never timed. When the work ends, the baselines are recorded again. A + limit that can be tightened is tightened to the highest new run times 1.2. + A limit that would have to rise needs a line in this record, like a + budget. +- The owner delegated these decisions on 2026-11-19, except merging into + `main` and releasing, and this record is approved under that delegation. + The two sentences of `CONSTRAINTS.md` that say a record is one "that the + owner approved" and that "the owner has not reviewed it yet" are brought in + line with that in the first commit. + +## Alternatives considered + +### Keep the budgets from before 1.0 + +No subset of the decided changes worth shipping fits them. + +### Let a ceiling rise under the same condition as a budget + +A ceiling that moves with a line in the record is a sentence, not a check. + +### Ceilings below their own estimate plus 2% + +An earlier set had this for `./react`, `./vue` and `./angular`, so the last +step of the work would have failed on its own estimates. Every ceiling now +follows the one rule above. + +### What was cut to keep the size down + +Long error messages; refusals in the `defineProperty` trap (160 bytes, +record 0002); recording reads outside a getter's own node (124, record +0010); cached getter errors (73, record 0010); the changed-keys rebuild of a +snapshot (270, record 0046); an index beside live collections (339, record +0042); and every development warning but one (record 0036). + +## Consequences + +- What the larger items buy: + - 239 bytes (0043): a snapshot lists the store's keys, a snapshot of a + class with getters is four times faster to make, and `this` in a + snapshot getter is right. + - 219 bytes (0013 to 0015): no stack overflow and no hung event loop when + a subscriber writes, and faster ordinary writes. + - 281 bytes (0010): five getter defects removed, a cached getter read a + quarter faster, and a getter that writes its own store is told so on + both layers. + - 168 bytes (0006): `includes()` and `indexOf()` find the object the + caller holds, in about 1% of the time they took before 1.0. + - 228 bytes (0001): one rule for every function a store holds, a method + in an object literal that stays a transaction, and arrow-function + methods that work. + - 156 bytes (0007): getters that use `in` or `Object.keys(this)` stop + going stale. It serves fewer users than the others. + - 180 bytes (0012): a field read 2.7 times faster on JavaScriptCore and a + fifth faster on V8. + - 81 bytes (0009): a rare case, taken because it cannot be added later. +- The decided set was never built as one. Two built combinations came out + above the sum of their parts (the trap changes 650 bytes against 617, the + snapshot changes 243 against 230) and one below it (raw values, the + searches, the freeze, `defineProperty` and the table per prototype, 465 + against 486). +- Only `CLAUDE.md` gives a size figure: "about 3.7 KB", and "about 4.9 KB + with the React hooks". The README gives none. Both figures in `CLAUDE.md` + change to the measured figures when the work ends, before the release. +- Open again when a change cannot be made under its ceiling. + +## Measured sizes + +One line per commit that grows an entry. A commit cannot name its own hash, +so the first column of both tables holds the commit's subject. + +| Commit | Entry | Measured bytes | New budget | +| ---------------------------------------------------------------------- | ----- | -------------: | ---------: | +| perf: decide getters from a table per prototype, not a descriptor walk | `.` | 3,768 | 3,844 | +| fix: make a delete that removes nothing no change | `.` | 3,776 | 3,852 | +| fix: make a definition through the store a write | `.` | 3,847 | 3,924 | + +## Changes to the tooling + +One line per commit that changes a bar file (`scripts/floor-guard.mjs`, +`packages/classy-store/bunfig.toml` or +`packages/classy-store/tests/mutation/runMutation.ts`), or that loosens or +removes a rule of `CONSTRAINTS.md`. + +| Commit | File | What changed | Why | +| ------------------------------------------------------------------------ | ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | +| build: add the size ceilings and make the floor guard judge every commit | `scripts/floor-guard.mjs` | Judges each commit against its parent, from the merge base with `main` or the commit that added `CONSTRAINTS.md`, then the working tree; fails on a merge commit; reads `budgets.json` and `limits.json`; the ceiling rule; the three bar files; a record line in place of a touched record; the `Test-change:` line | This decision. The guard saw one difference for the whole branch, one record anywhere switched it off, and it left its own file out | +| build: add the size ceilings and make the floor guard judge every commit | `CONSTRAINTS.md` | The nine size rows become one that names `budgets.json`. The floor's rule on a smaller test admits a `Test-change:` line, and its rule on a loosened rule asks for a line in a record. Three floor rules are added: the bar files, budgets and limits, ceilings | This decision. A budget has one place, and judged per commit the floor allows the test changes a decision makes | +| fix(floor): judge a pull request's head, not the merge CI checks out | `scripts/floor-guard.mjs` | A `--head ` option: the walk ends at that commit, and the working tree is not judged. CI passes the pull request's head | On a pull request, CI checks out a merge of the head into `main`, and the guard failed on that merge commit, which is not part of the branch | diff --git a/docs/decisions/0005-raw-values-on-write-and-one-node-per-raw-object.md b/docs/decisions/0005-raw-values-on-write-and-one-node-per-raw-object.md new file mode 100644 index 00000000..68a0eedc --- /dev/null +++ b/docs/decisions/0005-raw-values-on-write-and-one-node-per-raw-object.md @@ -0,0 +1,71 @@ +# 0005. A write stores raw values, and there is one node per raw object + +- **Status:** Accepted +- **Date:** 2026-11-25 +- **Kind:** bug +- **Label:** Before 1.0, because `outer.inner === inner` changes its answer +- **Changes documented behaviour:** no + +## Context + +Before 1.0, the `set` trap stores whatever it is given, a proxy included, and +`linkChild` finds an existing node by the proxy only. Two defects follow: + +- A class instance that is already a store, placed in another store by its + raw object, is not connected. `outer.inner === raw`, and a method call + through it changes state without telling any subscriber of either store. + A plain object in the same position is shared and notifies both. +- Raw objects fill up with proxies. After `to.row = from.row`, or after + `store.list.reverse()`, the raw object behind the store holds the proxy, + not the raw row. + +Record 0002 needs a definition to store the raw value too. + +## Decision + +- The `set` trap stores the raw object behind a store proxy, and + `linkChild` finds an existing node by the raw object as well as by the + proxy. +- When a property becomes read-only through the store while it holds an + object the store tracks (`Object.freeze(container)`, or a definition + without a value), the trap first puts that object's proxy in the raw slot. + A read-only property has to hand out what the raw object holds, and this + way that is the proxy. So every child the store tracked before such a + freeze stays a child, however it got there. +- Two cases stay raw, and are documented: an object frozen before it reached + the store, and a read-only property defined with an object as its value + (both engines refuse a swap there). Such an object is handed out as it is; + a write through it is not seen, and the snapshot holds it unfrozen. That is + the behaviour before 1.0 as well. + +This lands in the commit after record 0002: record 0002 stores a defined +value as it is given, and this commit changes both traps to store the raw +value and adds the swap. + +## Alternatives considered + +### Raw values on write without the swap + +Then a child reads back raw after its container is frozen through the +store, and a write through it tells no one, where before 1.0 a child that +was assigned as a proxy stays reactive. + +### Replace the proxies in a list built from proxies + +`this.items = this.items.filter(…)` still holds proxies in its raw array. +Replacing them would change an array the caller may still hold, so it is not +done. + +## Consequences + +- `outer.inner === inner` changes its answer for an instance placed by its + raw object. +- A child that was assigned as a plain object, or was present at creation, + stays reactive after its container is frozen through the store, where + before 1.0 it read back raw. +- Size: +104 bytes on the main entry in all (36 for raw values on write, 68 + for the swap, measured on top of it). 3 unit tests changed, all fixes. +- One run showed store creation about 20% slower on Node. A second run, + between two runs of the code before this change, did not: + creating a small store and a store of + rows were both inside the drift of the machine on both engines. diff --git a/docs/decisions/0006-array-searches-find-the-object-the-caller-holds.md b/docs/decisions/0006-array-searches-find-the-object-the-caller-holds.md new file mode 100644 index 00000000..e9667029 --- /dev/null +++ b/docs/decisions/0006-array-searches-find-the-object-the-caller-holds.md @@ -0,0 +1,71 @@ +# 0006. `includes`, `indexOf` and `lastIndexOf` find the object the caller holds + +- **Status:** Accepted +- **Date:** 2026-11-25 +- **Kind:** bug +- **Label:** Before 1.0 +- **Changes documented behaviour:** no + +## Context + +Before 1.0: + +```ts +const row = {id: 1}; +store.rows.push(row); +store.rows.includes(row); // false +``` + +The list hands out proxies and the search compares them against the raw +object. That is a wrong answer from a documented array method, in the most +ordinary way of using it. Each element also goes through the `get` trap, so +a search is slow. + +## Decision + +On a list in a store, the three searches find an element that is part of a +store by any of its forms: its raw object, its proxy, or a snapshot of it. +Any other element, such as a snapshot or a frozen object kept as a value, or +a `Date`, is found by reference, as in a plain array. A primitive is searched +for with the native method. + +How: the raw list holds an element that is part of a store by its raw +object, or in an older list by its proxy, and a value by itself. So the +answer is the nearest hit of the engine's own search for up to three values: +the value given and, when it is a form of an object in a store, that +object's raw form and its proxy. `fromIndex` is passed to the engine +unchanged. + +A reactive collection answers differently, on purpose (record 0042): it +matches every member by identity, so two snapshots of one object are two +elements of a list and one member of a set. The collections guide states the +difference, and a test pins both answers. + +## Alternatives considered + +### Compare every element by identity + +Every snapshot of one object has the same identity. On a list of saved +versions, `indexOf(v2)` then answered 0, and `includes` was true for a +version that was never pushed. A list of snapshots kept as values is an undo +stack, and it has to answer as a plain array does. + +### One loop and no allocation + +Built as well: 42 bytes larger and five to eleven times slower. + +### Run every read-only array method on the raw array + +It would hand each element's proxy to the callback. It was not measured on +this library, and records 0010 and 0012 attack the same cost. + +## Consequences + +- A search for an object in a list of 1,000 rows takes 0.5 microseconds on + Bun and 0.9 on Node, against 95 and 180 before this change, and + 0.15 and 0.2 for a + plain array. It allocates two short arrays per search for an object. +- 18 rows of searches agree with a plain array wherever a plain array has an + answer. 7 unit tests changed, all fixes. +- Size: +168 bytes on the main entry (100, then 68 more for the answer on a + list of snapshots). diff --git a/docs/decisions/0007-has-and-ownkeys-traps-and-a-missing-property-is-a-value.md b/docs/decisions/0007-has-and-ownkeys-traps-and-a-missing-property-is-a-value.md new file mode 100644 index 00000000..ec6d58c6 --- /dev/null +++ b/docs/decisions/0007-has-and-ownkeys-traps-and-a-missing-property-is-a-value.md @@ -0,0 +1,61 @@ +# 0007. `has` and `ownKeys` traps on the live store, and a missing property is a value + +- **Status:** Accepted +- **Date:** 2026-11-25 +- **Kind:** bug +- **Label:** Before 1.0: the reference says "A live getter that reads an + absent field recomputes on subsequent reads", and that sentence goes +- **Changes documented behaviour:** yes + +## Context + +Before 1.0, the store proxy has no `has` and no `ownKeys` trap, and a getter +records nothing for a property that is not there: + +- A live getter that reads `Object.keys(this)` or `'b' in this` goes stale. + It still answers 2 and `true` after `delete store.b`. +- A live getter that reads a property which does not exist is recomputed on + every read, so a getter that builds an object returns a new one each time. + The reference says: "A live getter that reads an absent field recomputes + on subsequent reads". + +A memoized getter that returns a stale answer is a defect in the feature the +library is built around. + +## Decision + +- A getter that asks `'b' in this` records a dependency on the key. +- A getter that asks `Object.keys(this)` records a dependency on a per-node + counter of the key set. +- A read of a property that is not there records that it was missing, so + such a getter is memoized like any other. +- The `defineProperty` trap of record 0002 moves the key counter when a + definition adds a key or changes whether it is enumerable. +- The two new records take the single shape of a getter dependency of record + 0010, and this change is written on top of that one. + +Not tracked in 1.0: `Object.hasOwn(this, key)`, `this.hasOwnProperty(key)` +and `Object.getOwnPropertyDescriptor(this, key)` inside a getter. They do +not go through the two traps, and a getter that uses one stays stale after a +key is added, as it does before 1.0. The docs say to use `in`. + +What `this` is inside a snapshot getter is record 0043. + +## Alternatives considered + +### A trap that also records own-property checks + +It is an addition and can follow 1.0. + +## Consequences + +- The reference sentence about an absent field goes. +- Size: +156 bytes on the main entry, measured alone. 9 unit tests changed, + all fixes. Timings were inside the spread except two metrics on Node that + were 1.4% and 1.5% slower. +- Those figures are for a prototype written beside the old dependency kinds. + No prototype built it in the single shape of record 0010, so the commit + takes its figures from its own build. +- An own-property check in a getter stays stale, and the list of what 1.0 + does not catch names it (record 0036). +- Open again to add the trap for own-property checks. diff --git a/docs/decisions/0008-a-delete-that-removes-nothing-is-not-a-change.md b/docs/decisions/0008-a-delete-that-removes-nothing-is-not-a-change.md new file mode 100644 index 00000000..d309b904 --- /dev/null +++ b/docs/decisions/0008-a-delete-that-removes-nothing-is-not-a-change.md @@ -0,0 +1,33 @@ +# 0008. A delete that removes nothing is not a change + +- **Status:** Accepted +- **Date:** 2026-11-25 +- **Kind:** bug +- **Label:** Before 1.0: the rule that a write which changes nothing + notifies no one is false without this +- **Changes documented behaviour:** no + +## Context + +Before 1.0, `delete + store.dict.missing` calls every subscriber and replaces the +snapshot with an equal one. The same holds for `delete list[5]` past the end +of a list. Writing the value a field already holds does neither. + +The rule that 1.0 guarantees is that a write which changes nothing notifies +no one. That rule is false while a delete of a missing key notifies. + +## Decision + +`delete store.dict.missing` returns `true` and does nothing else: no version +bump, no notification, no new snapshot. + +## Alternatives considered + +None was named. + +## Consequences + +- A subscriber is not called for a delete that removes nothing. +- 2 lines, +11 bytes on the main entry. 7 unit tests changed, all fixes, and + one case that was kept out of the randomized test can go back into it. diff --git a/docs/decisions/0009-a-plain-object-from-another-realm-is-state.md b/docs/decisions/0009-a-plain-object-from-another-realm-is-state.md new file mode 100644 index 00000000..d04aacfb --- /dev/null +++ b/docs/decisions/0009-a-plain-object-from-another-realm-is-state.md @@ -0,0 +1,52 @@ +# 0009. A plain object from another realm is state + +- **Status:** Accepted +- **Date:** 2026-11-25 +- **Kind:** bug +- **Label:** Before 1.0 +- **Changes documented behaviour:** no + +## Context + +Before 1.0, `isPlainObject` accepts only this realm's `Object.prototype`. An +object made in an iframe or a Node `vm` context is kept by reference: writes +to it notify no one and its snapshot is not frozen, in silence. + +The change can ship in 1.0 or not at all. Afterwards the object would be a +frozen copy in a snapshot where it is now the object itself, so code that +compares or writes through a snapshot would break in a minor release. + +## Decision + +A plain object made in another realm is proxied and frozen in snapshots like +any other plain object. + +The commit first builds it without the per-prototype cache, and keeps the +smaller form that leaves store creation inside the spread. + +The docs say that the raw object must not be frozen once a store holds it. + +## Alternatives considered + +### A guard for a property frozen behind the store + +After `Object.freeze(raw.config)`, `s.config.nested` throws a `TypeError` +from the Proxy `get` invariant. A guard in `get` could detach the child and +return the raw value. That failure is loud, and the guard takes back most of +what record 0012 gains on a nested read. + +### A Proxy target of the library's own + +It would remove that invariant. It is too large for 1.0, makes the `has`, +`ownKeys`, `getOwnPropertyDescriptor` and `getPrototypeOf` traps mandatory, +needs separate support for `Object.freeze(store)`, and reopens records 0002 +and 0007. + +## Consequences + +- Writes to an object from another realm notify, and its snapshot is frozen. +- Size: +81 bytes on the main entry with the cache, 24 lines, no unit test + changed. The form without the cache was not measured. +- `canProxy` changes, and `persist` and `history` use it too. +- Freezing a raw object behind the store still makes a read throw. It is + unspecified, like anything done to the raw object behind a store. diff --git a/docs/decisions/0010-getters-one-kind-of-dependency-and-no-writes.md b/docs/decisions/0010-getters-one-kind-of-dependency-and-no-writes.md new file mode 100644 index 00000000..12df9713 --- /dev/null +++ b/docs/decisions/0010-getters-one-kind-of-dependency-and-no-writes.md @@ -0,0 +1,119 @@ +# 0010. Getters have one kind of dependency, behave the same on both layers, and must not write to their own object + +- **Status:** Accepted +- **Date:** 2026-11-25 +- **Kind:** bug, simplification +- **Label:** Before 1.0: a getter that writes becomes an error, and the + sentence about an absent field goes +- **Changes documented behaviour:** yes + +## Context + +Before 1.0, a getter records three kinds of dependency, and the two layers (the +live store and the snapshot) differ: + +- A getter that reads a property which does not exist is recomputed on every + read on the store, and cached on a snapshot. +- A getter that catches another getter's error, + `try { return this.strict } catch { return 'fallback' }`, stays + `'fallback'` after `strict` stops throwing. +- With `c` reading `b` reading `a`, `snapshot(s).c; s.unrelated = 1; + snapshot(s).c` runs `a` and `b` again: the snapshot layer throws away the + memo that the nested getters filled. +- A cycle of getters on a snapshot overflows the stack with a `RangeError`, + where the live store throws its own error. +- Getters arranged as a diamond cost twice as much per level. +- A getter that writes re-runs and notifies on every read on the live store. + On a snapshot the write is dropped in silence. `this.cache ??= …` works on + the store and fails in every adapter, because every adapter reads + snapshots. + +## Decision + +- **One kind of getter dependency**, `{value, version}` by property. It holds + the version stamp that makes a clean read constant, records each property + once per run, and treats a missing property as a value. +- A getter that reads a getter which threw records that dependency, on both + layers, inside a frame that also covers validation. +- The snapshot layer keeps the memo that nested getters filled, and reports a + cycle with the live layer's error, the code `getter-cycle` of record 0035. +- **A getter must not write to the object it is computed on, by any path.** + - On the live store, a write to the getter's own object throws a + `TypeError` with the code `getter-write` (record 0035) that names the + field: an assignment, a `delete`, a definition, also through a method + the getter calls. + - On a snapshot, a write to `this` throws the same way, and the traps throw + themselves, so it holds in code that is not strict too. While a snapshot + getter runs, the live object the snapshot was taken from counts as + having a getter running, so a write that reaches the live store around + `this` throws as well, with nothing written and nobody told: through an + arrow-function method of a `ClassyStore` subclass, through a reference + to the store, or through a method called on the store. + - The throw is for the one object the getter is computed on, and its + message names that object's field. A getter on a nested object that + writes its parent or the root is not covered; that is unspecified. + - Allowed on both layers: a write to another store, and constructing a + store inside a getter. A write to a child object is allowed on the live + store; on a snapshot it throws in strict code, because the child is + frozen, and is ignored in code that is not strict. That difference is + unspecified. +- Whether a thrown error is cached is unspecified. + +The snapshot part is written first on the snapshot layer as it is before +1.0. Record +0043 then installs a class's getters once, on a shared prototype, so the +live object has to be found from `this` at each run; the rows for this +decision are run again as tests after record 0043. + +## Alternatives considered + +### Three kinds of dependency with the fix added on + +77 bytes larger than one kind. + +### Leave the live store as it is + +`this.cache ??= …` would keep working on the store and throwing through +every adapter. A throw from a trap that returns `false` would be an error in +strict code only, so a getter in a plain script would lose its write in +silence. + +### Throw for every write made while any getter runs + +It would refuse a store constructed inside a getter, which the base class of +record 0011 does by writing its own fields, and a getter that calls a method +of another store. + +### Record reads outside the getter's own node + +For another store or a static. 124 bytes, 14 to 18% slower on a getter over +1,000 rows, and it cannot work on a snapshot. The docs state the limit and +the pattern that works: hold the other store as a field. + +### Cache a thrown error + +73 bytes and seven pinned behaviours changed, for one gain. It can follow +1.0. + +## Consequences + +- A getter that fills a cache field on its own store, or calls a method that + writes its own store, throws where it worked on the live store. It already + failed in every component. The docs say a getter must not write to the + store it reads. +- The reference sentence about an absent field goes. +- The version stamp is safe for a subtree that has left the store: a + differential fuzz of 300 seeds compared 180,112 getter reads with a plain + mirror, 55,058 of them on a node outside the store. +- Timings on Node: a cached getter read is 26% faster and a recompute 6 to 9% + slower; the four cost ratios stay inside their limits on both engines. The + throw around `this` kept a write and both getter reads inside the spread; + on Bun the recomputed read was a steady 4% higher. +- Size: +281 bytes on the main entry (165 for the combination, 74 for the + throw on both layers, 42 for the throw around `this`, each on the one + before). 16 unit tests changed for the combination (15 fixes, 1 + incidental), then 3 more that pinned a getter writing its own store. +- Not built: the throw around `this` on top of record 0001 and on top of + record 0043. + +- Open again if a case is found where a getter must write its own object. diff --git a/docs/decisions/0011-nested-instances-stay-opt-in-and-a-classystore-base-class.md b/docs/decisions/0011-nested-instances-stay-opt-in-and-a-classystore-base-class.md new file mode 100644 index 00000000..ee96ebd8 --- /dev/null +++ b/docs/decisions/0011-nested-instances-stay-opt-in-and-a-classystore-base-class.md @@ -0,0 +1,109 @@ +# 0011. Nested class instances stay opt-in, and a base class `ClassyStore` makes arrow-function methods work + +- **Status:** Accepted +- **Date:** 2026-11-25 +- **Kind:** public API +- **Label:** Before 1.0 for the default of nested instances, which needs no + code; the base class is an addition +- **Changes documented behaviour:** no + +## Context + +An arrow-function field has `this` bound to the raw instance: + +```ts +class Counter { + count = 0; + increment = () => { + this.count++; // writes the raw instance; no subscriber hears it + }; +} +const store = createClassyStore(new Counter()); +``` + +Before 1.0, this is the most prominent silent failure of the library, and +the docs can only +warn about it. The same holds for a method bound in the constructor and for +a timer the constructor starts. + +Separately, a class instance nested in a store is opaque unless its class +sets `static [PROXYABLE] = true`. The question was whether to proxy nested +instances by default. + +## Decision + +- **Nested class instances stay opaque unless the class says otherwise.** + `static [PROXYABLE] = true` stays, and `static [PROXYABLE] = false` is + documented as "opaque on purpose"; it already works. +- **A base class, `ClassyStore`, is exported from the main entry.** Its + constructor returns the store, so a class that extends it is a store from + its first line: arrow-function fields, methods bound in the constructor + and whatever the constructor starts all write through the store. Such a + class is reactive wherever it is placed, with no marker. + `createClassyStore(new X())` stays, for a plain object and for a class that + cannot extend the base class. +- **The base class has no rule of its own for functions.** An arrow-function + field is a function in a field, so record 0001 makes it a method when it is + read through the store, and so is a subclass's field that overrides the + parent's. +- **A `#private` field is never state.** With the base class it can be used + on the live store; a snapshot cannot carry it. The docs say so. +- The base class lands after records 0001, 0002 and 0030, which it needs. + The 17 compilations listed under Consequences are run again on the real + code. The forms the repository can compile with what it already installs + (TypeScript with class fields as definitions and as assignments, and + Bun's transpiler) become committed tests. The other compilers run once in + a scratch folder, because adding them would change `bun.lock`; the commit + message carries their results. + +## Alternatives considered + +### Wrap nested class instances by default + +Run and not taken. Eight tests change, six of them the documented rule. A +class with `#private` fields throws. An object that changes itself leaves a +stale copy that no check can see. A graph of 5,461 objects placed in a store +costs 20 milliseconds. What stays opaque by default is what the user does +not own, and for those objects opaque is right. Not taken, and final for +1.0. + +### Detect an arrow function by its source text + +It finds 6 of 7 lost writes, reports 2 fields that lose nothing, and costs +256 to 342 bytes. + +### An `opaque()` helper, and a mixin form of the base class + +Not taken. + +### Make the base class an exception to the rule for functions + +An earlier form did, and the exception held only here. Record 0001 now +covers the base class with no rule of its own. + +## Consequences + +- A class has to extend `ClassyStore` for its arrow-function fields to work. + The docs gain these sentences: + - A callback held in a field is compared on a snapshot, where it is the + function that was stored. + - An arrow method is called on the store. Taken from a snapshot it still + writes the store, one write at a time and not as one transaction. + - Under React's `StrictMode`, `useLocalStore` makes two stores in + development, so a constructor that starts a timer starts two. + - A class that has to extend another class uses `createClassyStore(new + X())` and prototype methods. +- Size: 4 lines and +13 bytes on the main entry. +- One subclass was compiled 17 ways (TypeScript with class fields as + definitions and as assignments, Bun, Oxc, esbuild, the SWC of Next.js with + the example's configuration, Babel in spec and loose mode). In every output + the first snapshot is right, an arrow method notifies once, and a field + write and a timer's write are seen. Those runs used an earlier rule for + functions; the current rule changes nothing when an object is created, and + the override case was run again both ways with Bun's transpiler. Seven + throwaway tests passed for Vue, Svelte, Solid, Angular, `createStoreHook` + and `useLocalStore`. A base-class store made inside a getter works on both + layers. +- After 1.0, a warning for an unmarked class placed in a store follows, + once it can be silenced for a class that is opaque on purpose (record + 0036). diff --git a/docs/decisions/0012-a-table-per-prototype-answers-is-this-key-a-getter.md b/docs/decisions/0012-a-table-per-prototype-answers-is-this-key-a-getter.md new file mode 100644 index 00000000..128ac0d8 --- /dev/null +++ b/docs/decisions/0012-a-table-per-prototype-answers-is-this-key-a-getter.md @@ -0,0 +1,87 @@ +# 0012. A table per prototype answers "is this key a getter?" + +- **Status:** Accepted +- **Date:** 2026-11-25 +- **Kind:** performance +- **Label:** Can follow 1.0 +- **Changes documented behaviour:** no + +## Context + +Before 1.0, the `get` and `set` traps walk the prototype chain with +`Object.getOwnPropertyDescriptor` on every access, to learn whether a key is +a getter. A read is the hottest operation the library has, and this walk is +most of its cost. + +## Decision + +- An own key is decided with `hasOwnProperty` and one flag per node. +- An inherited key is decided from a table per prototype, filled on the + first miss, that says for each key which prototype object carries an + accessor for it, or that none does. +- The table holds no function. A read whose cached result is still valid + returns it; only a recompute asks that prototype for its getter, so the + function that runs is the one the class has now. +- **The table cannot grow without bound.** A key the prototype chain has is + always recorded. A key that is absent everywhere is recorded only while the + table holds fewer than 256 keys; after that such a key is looked up at each + read, as before 1.0. + +This lands before records 0001 and 0002, because the trap then already knows +"own or inherited", which record 0001 asks. + +The table assumes that a prototype is not changed after its first read +through a store. That is unspecified, with these answers for now: + +- A getter added to a prototype for a key that was read as absent is seen, + and it is not memoized: its body runs at every read, where before 1.0 it + runs once. +- An override nearer the instance is not seen. +- A getter removed or replaced by a value is seen at its next recompute, + where before 1.0 it is seen at once. + +## Alternatives considered + +### Cache the whole descriptor, getter included + +46 bytes smaller and wrong: a getter redefined on the class kept its old body +on the live store while snapshots ran the new one, a getter replaced by a +value still ran, and a deleted getter still answered. + +### Record every absent key, with no bound + +The table of `Object.prototype` is shared by every plain object of every +store. A dictionary read by keys it does not have yet grew the heap by 88 MB +for a million keys, with no key left in the store. With the bound the same +run grows the heap by 0.2 MB, as the code before this change does. + +### Never record an absent key + +A read of a key that a class instance does not have is then slower than +before this change on Node: 107 to 116 nanoseconds against 97 to 100. + +### No table for `Object.prototype` and `Array.prototype` + +The tables of class prototypes still grow, and `Object.prototype` carries an +accessor, `__proto__`, which needs an exception that is easy to miss. + +### A table that names the prototype and reads the getter at every read + +23 bytes smaller than the form taken, and a cached getter read is then 19% +slower on Node than before this change. + +## Consequences + +- Timings against the code before this change (Bun / Node): a field read from 31.9 to 11.5 + nanoseconds and from 47.5 to 38; a read three objects deep from 108 to 48 + and from 143 to 116; a cached getter read from 58 to 35 and from 85 to 77. + Timed in three rounds of five processes per engine. All 1,341 unit tests + pass, and typecheck and lint pass. +- Size: +180 bytes on the main entry (165 for the table, 15 for the bound). +- Not measured: a read of an absent key once the table holds 256 keys. From + the form that never records one, that is about the cost before this change + on Node for a plain object + and up to 10% above it for a class instance. +- Not built: this table on top of the getter changes of record 0010. +- Open again if changing a prototype after its first read has to be + supported. diff --git a/docs/decisions/0013-one-delivery-queue-with-a-bound.md b/docs/decisions/0013-one-delivery-queue-with-a-bound.md new file mode 100644 index 00000000..5f4fc664 --- /dev/null +++ b/docs/decisions/0013-one-delivery-queue-with-a-bound.md @@ -0,0 +1,91 @@ +# 0013. One delivery queue, with a bound + +- **Status:** Accepted +- **Date:** 2026-11-25 +- **Kind:** bug +- **Label:** Before 1.0: the order of calls changes, and what a removed or a + late subscriber gets becomes guaranteed +- **Changes documented behaviour:** no + +## Context + +Before 1.0, a write made inside a subscriber is delivered by a nested call: + +- A synchronous subscriber that writes to the store it listens to recurses + until the stack overflows. The `RangeError` goes to `console.error`, and + the store keeps the writes. +- A batched subscriber that writes is served again in back-to-back + microtasks with no bound. A timer that is already due waits until the + writer stops; one that never stops hangs the event loop. +- A subscriber removed during delivery is still called once, after its + unsubscribe function returned. +- A subscriber added after a write sometimes hears that write. +- After a re-entrant write, a subscriber registered after the writer is + called twice with the same snapshot and never sees the state in between. + +## Decision + +- A write made while synchronous subscribers are being called is queued and + delivered after the round that is running, and before the outermost write + returns. +- A subscriber removed during delivery is not called. A subscriber added + during delivery hears the next change, not the one in flight. +- One queue serves all stores. +- On the batched path, one microtask serves every round: a write made inside + a batched subscriber is delivered to batched subscribers in that same + microtask, after the round that is running. +- Delivery stops after 100 rounds. It then reports once, with the code + `delivery-loop`, the store keeps the writes, and the subscribers that were + waiting are called at the next write. The report goes where a subscriber's + error goes (record 0014). +- **A subscriber hears of its own write**, once, as in MobX and Preact. A + subscriber that corrects state has to stop writing once the state is + right. +- **The first round reads the owners directly**, a variant that keeps a + direct write with a synchronous subscriber as fast as before this change. + The commit confirms on a quiet machine that the benchmark's + `store.write.sync` stays inside the spread of the commit before this + change on both engines. That is the same baseline as record 0001, because + records 0012, 0001 and 0010 move the write path first. If the variant does + not achieve that, the plain queue is taken and the slowdown is stated in + the reference. The figures go into the commit message. + +## Alternatives considered + +### A subscriber that does not hear of its own write + +Not taken, and final for 1.0: the guarantee of delivery states the choice +above. + +### A microtask of its own for each batched round + +Not taken, and final for 1.0. It would differ from the synchronous rule. + +### The plain queue without the direct first round + +A direct write with a synchronous subscriber is then about 85 nanoseconds +slower on Bun and 30 on Node. A direct write while a component is mounted is +the most common write an application makes. The plain queue is the fallback +if the variant fails its condition. + +## Consequences + +- No stack overflow and no hung event loop when a subscriber writes. MobX, + Preact Signals, Vue and Svelte reach the same design. +- An ordinary write gets faster, because every write takes one path: the + write ratio goes from 2.69 to 2.21 on Bun and from 1.4 to 1.06 on Node. +- A synchronous subscriber of store A that writes store B makes B current at + once, and B's subscribers hear a round later. Another subscriber of A in + that round therefore reads the new B through the store and the old B + through an adapter; before 1.0 it read the new B in both. + The reference says + that adapter values of another store may lag inside one delivery round. +- The order of calls changes, and what a removed or a late subscriber gets + becomes guaranteed. +- 72 lines added, 36 removed. 16 unit tests changed: 13 fixes and 3 + incidental. Size: the queue 33 bytes, the bound and its message 75 to 130 + more with the message as first written, less with a code; the direct first + round 30 bytes more. Records 0013 to 0015 together add +219 bytes to the + main entry. +- After this change Vue, Angular and Svelte drop their `active` flags + (record 0042). diff --git a/docs/decisions/0014-a-subscriber-error-is-caught-and-logged.md b/docs/decisions/0014-a-subscriber-error-is-caught-and-logged.md new file mode 100644 index 00000000..f9fb6f3c --- /dev/null +++ b/docs/decisions/0014-a-subscriber-error-is-caught-and-logged.md @@ -0,0 +1,55 @@ +# 0014. A subscriber's error is caught and logged, a rejection too, and the writer is never told + +- **Status:** Accepted +- **Date:** 2026-11-25 +- **Kind:** public API, bug +- **Label:** Before 1.0, as a guaranteed rule +- **Changes documented behaviour:** no + +## Context + +Before 1.0, a subscriber's +synchronous error is caught and sent to +`console.error`, and the other subscribers run. Two gaps: + +- A subscriber that returns a rejected promise is not reported. It becomes + an unhandled rejection, which ends a Node or Bun process. +- The report itself is not guarded. In a test setup that fails on console + output, `console.error` throws; that error reaches the writer and skips + every later subscriber of the round. + +## Decision + +The rule becomes part of what 1.0 guarantees: a subscriber's error is +caught, the other subscribers run, and the code that wrote is not told. The +rejection of an `async` subscriber is caught and logged in the same way. The +report is guarded: if `console.error` throws, the round goes on and the +writer still is not told. + +Where the report goes is unspecified. + +## Alternatives considered + +### Throw the first error to the writer + +Preact and Legend-State 3 do this. Every adapter is a synchronous +subscriber, so the code that fails is usually not the code that wrote. An +unrelated `store.count = 1` would throw after the count has changed, a +method's own error would be hidden and its return value lost. On the +microtask path there is no writer at all. Not taken, and final for 1.0. + +### `reportError()` + +It ends a Bun process and only logs on Node. + +### A reporter the application can replace + +An addition. It can follow 1.0. + +## Consequences + +- The two ways a callback can fail land in one place. The rejection handler + costs 25 bytes. 1 unit test changed, a fix. +- The guard on the report was not built in a prototype. Its test is written + first. +- The bound on delivery rounds (record 0013) reports through the same path. diff --git a/docs/decisions/0015-a-setter-is-a-transaction.md b/docs/decisions/0015-a-setter-is-a-transaction.md new file mode 100644 index 00000000..c81d3f6d --- /dev/null +++ b/docs/decisions/0015-a-setter-is-a-transaction.md @@ -0,0 +1,42 @@ +# 0015. A setter is a transaction + +- **Status:** Accepted +- **Date:** 2026-11-25 +- **Kind:** bug +- **Label:** Before 1.0: one sentence in the reference +- **Changes documented behaviour:** no + +## Context + +Before 1.0, a method and +an array method are transactions, and a setter is not: + +```ts +class Range { + min = 0; + max = 0; + set span([min, max]: [number, number]) { + this.min = min; + this.max = max; + } +} +``` + +`store.span = [1, 2]` gives two synchronous notifications, and a subscriber +sees the half-applied state between them. + +## Decision + +A class setter is run as one transaction, like a method. A setter that +writes two fields notifies a synchronous subscriber once, when it returns. +The reference gets one sentence for it. + +## Alternatives considered + +None was named. + +## Consequences + +- A synchronous subscriber does not see a half-applied setter. +- 8 lines, 5 bytes (inside the +219 of records 0013 to 0015). 2 unit tests + changed, both fixes. diff --git a/docs/decisions/0016-batch-refuses-a-promise-and-an-async-function.md b/docs/decisions/0016-batch-refuses-a-promise-and-an-async-function.md new file mode 100644 index 00000000..457824e8 --- /dev/null +++ b/docs/decisions/0016-batch-refuses-a-promise-and-an-async-function.md @@ -0,0 +1,62 @@ +# 0016. `batch()` refuses a callback that returns a promise, by its type, and an `async` function when it runs + +- **Status:** Accepted +- **Date:** 2026-11-25 +- **Kind:** public API +- **Label:** Before 1.0 +- **Changes documented behaviour:** yes + +## Context + +`batch(async () => …)` groups only the writes before the first `await` and +hands back the promise as if it had worked. The reference says that `batch` +"Returns whatever `run` returns". + +A type can stop that where it is written, but it cannot see an `async` +function held under a `() => void` type, a JavaScript caller or an `any`. +Both refusals have to be decided before 1.0: accepting promises again later +would be a compatible change, and starting to refuse them would be a +breaking one. + +## Decision + +- The parameter of `batch()` becomes a function whose result is not a + promise, with a type whose error message says why. +- At run time, `batch()` throws a `TypeError` with the code `batch-async` + when it is given a native `async` function, before the function is called, + in every build. Nothing is half applied and no promise is lost. It tells + an `async` function by `Symbol.toStringTag` equal to `'AsyncFunction'`, + the test record 0022 uses, because a looser test refuses the mock + functions of the test runner. A test pins that a mock function is + accepted. +- The type of the parameter is not exported in 1.0. Exporting it later is + an addition. + +- The reference states the rule for an `async` method: it is a transaction + up to its first `await`. + +## Alternatives considered + +### The type alone + +It costs no bytes, and it leaves the silent split for every caller it +cannot see. + +### Drop a write that is undone inside a batch + +A value set and set back inside a batch notifies once. One notification for +a batch that wrote is the simpler rule. + +## Consequences + +- `batch(() => { store.loading = true; return save(); })` no longer + compiles, and is rewritten with `save()` outside. At run time it is + accepted, because it is not an `async` function and it batches everything + it should. +- A wrapper generic over the result of `batch()` needs a cast. +- An `async` function that a build step has turned into a generator is not + seen by the check. +- The type is 7 lines and 0 bytes, and 3 type assertions in 2 test files + change. The check is 10 lines and 50 to 83 bytes with its message as first + written, less with a code (+50 on the main entry in record 0004). 2 unit + tests changed, both fixes. diff --git a/docs/decisions/0017-subscribe-stays-batched-by-default.md b/docs/decisions/0017-subscribe-stays-batched-by-default.md new file mode 100644 index 00000000..871cec13 --- /dev/null +++ b/docs/decisions/0017-subscribe-stays-batched-by-default.md @@ -0,0 +1,41 @@ +# 0017. `subscribe()` stays batched by default + +- **Status:** Accepted +- **Date:** 2026-11-25 +- **Kind:** public API +- **Label:** No change +- **Changes documented behaviour:** no + +## Context + +`subscribe(store, cb)` calls `cb` in a microtask, so several writes in one +task give one call. `{sync: true}` calls it before the write returns. Users +of other libraries may expect a synchronous default, and the question was +whether 1.0 should have one. + +## Decision + +No change. The reference says at the top of the `subscribe` section that +the callback runs in a microtask, that `{sync: true}` runs it before the +write returns, and that the callback receives no arguments. + +## Alternatives considered + +### A synchronous default + +A direct property write has no unit that groups two fields, so the microtask +is what gives `store.a = 1; store.b = 2` and `Object.assign` one call. A +synchronous default would hand every caller of `subscribe()` the cost that +only the adapters carry now (one call, and often one snapshot, per direct +write), and would turn the option of `persist`, `withHistory` and +`subscribeKey` around. Not taken, and final for 1.0. + +## Consequences + +- Nothing changes in the code. The reference states the timing first. +- Counted on a prototype: the batched default gives one call per turn in + every case measured; a synchronous default gives more for two direct + writes, for `Object.assign` and around an `await`. + +- Open again only with a new reason; changing the default after 1.0 is a + breaking change. diff --git a/docs/decisions/0018-writes-outside-a-method-stay-allowed.md b/docs/decisions/0018-writes-outside-a-method-stay-allowed.md new file mode 100644 index 00000000..431b6327 --- /dev/null +++ b/docs/decisions/0018-writes-outside-a-method-stay-allowed.md @@ -0,0 +1,43 @@ +# 0018. Writes outside a method stay allowed, without a warning + +- **Status:** Accepted +- **Date:** 2026-11-25 +- **Kind:** public API +- **Label:** No change +- **Changes documented behaviour:** no + +## Context + +A direct write is allowed anywhere, and each one notifies synchronous +subscribers. A method is a transaction only up to its first `await`. Neither +case is reported to the developer. Libraries such as MobX can enforce that +state changes only inside actions, and the question was whether 1.0 should +restrict or report writes outside a method. + +## Decision + +No change. Direct writes stay allowed, and `batch()` stays in the API. A +development warning when a synchronous subscriber is called many times in +one task follows in a 1.x release (record 0036). + +Why: a direct write is a documented way to change a store, and the ordinary +one in an event handler: `store.count++`. A warning for it would fire for +correct code and could not be silenced, which record 0036 rules out for +every warning. What a direct write costs is one notification per write on +the synchronous channel, and `batch()` is the answer to that cost, so it +stays. + +## Alternatives considered + +### A warning for a write outside a method + +It would fire for ordinary code that writes directly, and a warning for a +write after an `await` would fire for the ordinary `async` method. A warning +that fires for correct code and cannot be silenced is worse than none. +Because a warning changes no behaviour, one can arrive in any release. + +## Consequences + +- Nothing changes in the code or the docs. +- Open again when a warning is designed that can be silenced and does not + fire for correct code. diff --git a/docs/decisions/0019-persist-restores-before-it-returns-on-synchronous-storage.md b/docs/decisions/0019-persist-restores-before-it-returns-on-synchronous-storage.md new file mode 100644 index 00000000..47df0a14 --- /dev/null +++ b/docs/decisions/0019-persist-restores-before-it-returns-on-synchronous-storage.md @@ -0,0 +1,55 @@ +# 0019. `persist()` restores before it returns when the storage is synchronous + +- **Status:** Accepted +- **Date:** 2026-11-25 +- **Kind:** public API +- **Label:** Before 1.0 +- **Changes documented behaviour:** yes + +## Context + +Before 1.0, `persist()` reads the storage after it returns, even when the +storage is synchronous. A store on `localStorage` renders its defaults first, +and the saved state a microtask later. + +## Decision + +- `persist()` restores before it returns when the storage is synchronous. It + awaits only a storage that returns a promise. +- There is no option for it. `skipHydration` keeps its meaning: with it, + nothing is read, and so nothing is saved, until `rehydrate()` is called + (record 0021). +- The handle exists before the first read starts, so a report made during + that read can hand the handle to `onError` (record 0021). +- `hydrated` settles even when the store cannot be snapshotted at the start + of a read, and `rehydrate()` keeps the `finally` that guarantees it. + +The persist tutorial has to say two things: + +- **Call `persist()` after the store is constructed, never inside a + constructor.** With the base class of record 0011 a constructor is a + natural place for it, and it is the wrong one: the field initialisers of a + subclass run after the restore and overwrite it, and under record 0002 + they count as edits, so the next save writes them over the stored record. + A test pins what happens, so that the sentence stays true. The test needs + the base class, so it is written with record 0011. +- **On the client, `prepareStoreForHydration(store)` is called before + `persist(store)`** (record 0041). The React SSR guide already says that + `prepareStoreForHydration` captures the snapshot "before persistence or + other live updates begin"; this change names `persist()` there, and the + persist tutorial gains the same sentence. + +## Alternatives considered + +None was named. There is no option that keeps the timing from before 1.0. + +## Consequences + +- A store on a synchronous storage holds its saved state when `persist()` + returns, so its first render shows that state. +- 15 lines added and 18 removed; `./utils` gets 6 bytes smaller. 1 unit test + changed, incidental: it relied on the old timing. +- The persist tutorial says that hydration is asynchronous even with + `localStorage`. That sentence changes. +- A test pins what a `persist()` call inside a constructor of a + `ClassyStore` subclass does; the persist tutorial forbids the call. diff --git a/docs/decisions/0020-dead-code-goes-in-the-commit-that-makes-it-dead.md b/docs/decisions/0020-dead-code-goes-in-the-commit-that-makes-it-dead.md new file mode 100644 index 00000000..06fd8ccd --- /dev/null +++ b/docs/decisions/0020-dead-code-goes-in-the-commit-that-makes-it-dead.md @@ -0,0 +1,81 @@ +# 0020. Dead and redundant code goes, in the commit that makes it dead + +- **Status:** Accepted +- **Date:** 2026-11-25 +- **Kind:** simplification +- **Label:** Can follow 1.0 +- **Changes documented behaviour:** no + +## Context + +Before 1.0, the mutation run found code that no test can reach and checks that +can never fail, among them: + +- `core.ts`: `if (!cached) return false` in `areDepsValid` is unreachable, + because a computed dependency is recorded only after its cache entry + exists and entries are never removed. `node.resumeScope()` in + `createClassyStore` shows only through the defect of record 0003. +- `ownership.ts`: an unreachable `break` in `resume()`, three redundant + fast-path guards and one redundant early return. +- `snapshot.ts`: `configurable: true` and `writable: true` on properties that + `Object.freeze` overrides anyway, a `delete` from the in-progress set that + nothing reads again, and three checks that cannot fail. +- `persist.ts`: an `assertActive()` that can never throw and one that + duplicates it, four copies of the block that cancels the debounce timer, + two assignments that are never read, guards whose removal changes nothing, + and a default `merge = 'shallow'` whose text is never compared. +- `equality.ts`: three `instanceof` checks that cannot fail after the + same-prototype check. `history.ts`: the `if` around the truncation in + `record()` and the `disposed ||` in `redo()`. `collections.ts`: the object + guard in `indexOfMember`, which repeats the one inside `identityOf`. +- Two traps of the React snapshot cache cannot be reached through + `proxy-compare`. + +`CONSTRAINTS.md` allows no unexplained surviving mutant in a target file, so +dead code cannot wait for a cleanup step. + +## Decision + +- **Code that is dead before 1.0 is removed first**, before the other + changes: the ten dead lines of the three core files in the form the type + checker accepts, the dead blocks of `persist.ts`, and the redundant checks + in `equality.ts`, `history.ts` and `collections.ts`, each after a + benchmark where it sits in a loop. +- Only one of those checks sits in a loop: the object guard in + `indexOfMember`, which runs once per member. Before it goes, the core + benchmark gains two rows, `collection.has.primitive` and + `collection.has.object`: `has()` of the last member on a live + `reactiveSet` of 1,000 numbers and of 1,000 objects. The guard goes only + if both rows stay inside the spread of the commit before on both engines; + otherwise it stays as a measured shortcut, and its entry in the list of + equivalent mutants gives the figures. The checks in `equality.ts` and + `history.ts` sit in no loop and go without a benchmark. +- **Code that a later change makes dead is removed in that change's + commit.** That holds for the per-field bookkeeping of a restore, which + records 0022 and 0023 make unreachable, and for `resumeScope()` in + `createClassyStore`, which record 0003 makes redundant. +- **The two unreachable traps of the React snapshot cache** are removed if + deleting them fails no unit test and no React suite; otherwise each gets a + test that reaches it. Deleting them fails only two assertions of + `snapshotTargetCache.test.ts`, which reach the private copy through the + cache itself and were added for coverage. They are tests of internal + state and do not count. They go with the traps, and the commit message + names the assertions in the same file that cover the public fact: a write + and a delete through the tracking proxy are refused. +- **The ternary in `activeTracker()` stays.** It looks dead and is on the + path of every read. It was timed alone: without it a field read goes from + 45.3 to 82.6 nanoseconds on Node and from 31.9 to 59.2 on Bun, and the + read ratio on Node is 3.55, above its limit of 2.5. + +## Alternatives considered + +### Remove all dead code in one cleanup step at the end + +Code made dead in between would break the mutation rule in every commit +until then. + +## Consequences + +- The core files: 8 lines added, 17 removed, 32 bytes smaller on the main + entry. No test fails, and the typecheck passes. +- The number of mutants listed as unkillable goes down. diff --git a/docs/decisions/0021-persist-skips-nothing-in-silence-and-overwrites-nothing-it-could-not-restore.md b/docs/decisions/0021-persist-skips-nothing-in-silence-and-overwrites-nothing-it-could-not-restore.md new file mode 100644 index 00000000..1d4094f1 --- /dev/null +++ b/docs/decisions/0021-persist-skips-nothing-in-silence-and-overwrites-nothing-it-could-not-restore.md @@ -0,0 +1,163 @@ +# 0021. Nothing `persist` cannot use is skipped in silence, and nothing it could not restore is written over + +- **Status:** Accepted +- **Date:** 2026-11-25 +- **Kind:** bug, diagnostics +- **Label:** Before 1.0 +- **Changes documented behaviour:** yes + +## Context + +Before 1.0, `persist` can lose stored data in several ways: + +- A record it refuses is reported only to `onError`, which is optional; + without it the refusal is silent, and the next save replaces the record. +- A handle with `skipHydration` saves on its first edit, before any read. A + stored record is replaced by the defaults and one edit, and the + `rehydrate()` that follows reads the damage back. `skipHydration` is the + pattern the server-rendering guides teach, and they say it "does not delay + writes". +- A record of a newer version (another tab that has already updated, or a + deployment that was rolled back) is passed to `migrate`, and the next edit + writes the older build's state over it. +- A record that the application's own `migrate`, `merge` or `deserialize` + fails on is replaced at the next save, which turns a bug in one release + into lost data for every user who makes an edit. +- An `async` `migrate` is called and its promise dropped, which becomes an + unhandled rejection. +- `onError` has no handle, so it cannot call `clear()`; an error it throws is + swallowed. + +## Decision + +**A handle writes only after it has read.** Until its first read has +settled, a handle saves nothing: with `skipHydration` that is until the +first `rehydrate()`, and with a storage that returns a promise it is while +the first read is in flight. An edit made before then is kept in the store. +When the read restores a record, the edit wins for the field it changed, and +the result is saved. `save()` rejects before the first read has settled. +`clear()` works at any time. + +**A stored record that is read and not restored** is one of five kinds: + +| Kind | What it is | What happens | +| ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- | +| Nothing to keep | Not JSON; an envelope that is not an object; a `state` that is not a plain object; a version that is not a finite number of zero or more; an `expiresAt` that is neither a number, `null` nor missing; a record the library itself cannot restore, because it is nested too deep (record 0023) | Reported as `'parse'`. The next save replaces it | +| A lower version, no `migrate` | The documented way to drop an old format | Not used and not reported. The next save replaces it | +| From a newer version | Its version is above the configured one | Reported as `'parse'`. `migrate` is not called. The handle does not write while it is there | +| Not migrated or not merged | `migrate`, `merge` or a `deserialize` threw, or `migrate` or `merge` returned a thenable or something that is not a plain object | Reported as `'parse'`. The handle does not write while it is there | +| Not read | The read itself failed | Reported as `'read'`. It counts as no read, so the handle does not write | + +- **A handle that does not write** saves nothing: on an edit, when the page + is hidden, or on `save()`. An edit does not repeat the report. `save()` + reports as `'write'` and rejects with the error that `lastError` holds, + the report that stopped the handle from writing. A `rehydrate()` that + finds such a record again reports and rejects with that record's error. A + `rehydrate()` whose own read fails reports as `'read'` and rejects with + that error, as before 1.0. The handle writes again after `clear()`; after + a `rehydrate()` that restores a record, finds none or finds one with + nothing to keep; and when such a record, or the removal of the record, + arrives from another tab. `lastError` of the status holds the report for + as long as the handle does not write. +- **`onError` receives the handle as its third argument**, so that it can + call `clear()`. For a synchronous storage the first read runs inside + `persist()` (record 0019), so the report comes before `persist()` has + returned. An error that `onError` throws is logged with `console.error`. +- **When no `onError` is given, the report goes to `console.error`** with + its code, in every build. `onError` replaces that default. +- **What a report carries.** `onError(error, operation, handle)` receives + the value that was thrown when the library did not throw it: the + storage's error, the error of a `serialize`, `deserialize`, `migrate` or + `merge`, or the `SyntaxError` of the default `JSON.parse`. When the + library refuses a record or a call itself, `error` is an `Error` whose + message carries one of these codes (record 0035): `persist-invalid` for a + record with nothing to keep that parses, `persist-newer` for a record of a + newer version, `persist-not-plain` for a `migrate` or `merge` that + returned a thenable or a value that is not a plain object, and + `persist-unread` for a `save()` before the first read has settled. The + default report is one `console.error` call: its first argument is + `@codebelt/classy-store [persist-failed]: ""` and its + second is the error. +- **Every failure of `save()` is reported as `'write'` and rejects with the + same error**, as before 1.0; that includes a `save()` before the first + read has settled. A call on a disposed handle rejects with + `persist-disposed` and is not reported, because after `dispose()` the + handle reports nothing. + +- **One version rule, on both sides.** A version is a finite number, zero or + above. A record with no `version` field counts as version 0; any other + value, `null` and `"2"` included, leaves nothing to keep. The `version` + option is checked when `persist()` is called (record 0022). +- **`migrate` is called only for a lower version**, and never as an `async` + function: a native `async` function is refused when `persist()` is called + (record 0022). If a `migrate` returns a thenable when it runs, a handler is + attached to it, so no rejection is left unhandled, and the record counts as + not migrated. +- **Expiry comes first.** A record whose time has elapsed is treated as + expired whatever its version, as the build that wrote it would treat it. + +## Alternatives considered + +### Write over a newer record, or one that could not be migrated or merged + +Not saving is the failure that can be undone; it is reported, and the +application can choose the other one with `clear()`. Not taken, and final +for 1.0. + +### A handle that saves before it has read + +It writes over a record it never saw. Not taken, and final for 1.0. + +### A `skipHydration` handle that only looks at the stored version first + +It would still write the defaults over a record it could have restored. + +### Require an integer version, on the record only + +An application configured with `version: 1.1` would refuse its own record +after the upgrade. + +### Await an `async` `migrate` + +It would put a turn between the read and the apply, which record 0019 +removes. Accepting it later is a compatible change, so this is not final. + +### A `'migrate'` value for `PersistOperation` + +A new member of that public union would break a consumer's exhaustive +`switch`. Not taken, and final for 1.0. + +### Keep a record that is nested too deep + +No release can restore it, and keeping it would stop the store from ever +saving again. + +## Consequences + +- With `skipHydration`, nothing is saved until `rehydrate()` has been called. + An application that never calls it saves nothing, and only `save()` says + so, by rejecting. `isHydrated` shows the state. The guide sentence that + `skipHydration` "does not delay writes" is reversed. +- While a handle does not write, edits are not saved, and a later + `rehydrate()` that restores a record restores over them. After a release + whose `migrate`, `merge` or `deserialize` fails for a stored record, that + user's state is not saved until a later release reads the record or the + application calls `clear()`. +- After a rollback of a deployment, a user whose record the newer build saved + cannot save on the older build until the newer one is back. +- Two losses stay, and the guide names both: a tab that read before a newer + build wrote, and does not sync, writes over the newer record at its next + edit; and a `migrate` that returns a wrong result without throwing is + saved at the user's next edit. +- A callback written for two arguments still fits `onError`. +- The rules were built once together and run through 33 paths. 98 lines + added and 36 removed in `persist.ts` and `persist.types.ts`; +245 bytes on + `./utils` over the first combined build of the `persist` changes. 48 unit + tests changed: fixes, tests that used `skipHydration` as a set-up and + saved before any read (incidental), tests that pinned the read winning + over an earlier edit (changed by this decision), and tests of the + arguments of `onError` (incidental). +- Not in that build: a record nested too deep has nothing to keep; the + removal of the record in another tab lets a handle write again; the expiry + stamp of record 0024 only for a finite `expireIn`. Not run: a real + `pagehide`, a real second tab, the browser suites. diff --git a/docs/decisions/0022-persist-validates-its-options.md b/docs/decisions/0022-persist-validates-its-options.md new file mode 100644 index 00000000..318cbbb8 --- /dev/null +++ b/docs/decisions/0022-persist-validates-its-options.md @@ -0,0 +1,50 @@ +# 0022. `persist()` validates its options when it is called + +- **Status:** Accepted +- **Date:** 2026-11-25 +- **Kind:** bug +- **Label:** Before 1.0 +- **Changes documented behaviour:** no + +## Context + +Before 1.0, `persist()` accepts any options and does the wrong thing later: + +- A getter named in `properties` is saved, and restoring it fails part-way. + With `properties: ['count', 'doubled', 'tail']`, `save()` stores the + getter's value; hydrating then sets `count`, throws on `doubled`, leaves + `tail` unset and records a `'parse'` error. The types say getters are + always excluded. +- A malformed entry in `properties` is ignored: `{key: 'other', + deserialize}` with no `serialize` means `other` is never persisted. +- A bad `version` or an `async` `migrate` would only be found out record by + record, where the cost is a user's stored data. + +These are mistakes in the application's own code, at a boundary the library +owns. + +## Decision + +`persist()` throws a `TypeError` with the code `persist-option` (record +0035), before it reads or writes anything, for: + +- a prototype key, a getter or a method named in `properties`; +- a transform that is half written; +- a `version` that is not a finite number of zero or more; +- a `migrate` that is a native `async` function. + +A native `async` function is told by its `Symbol.toStringTag`, named +exactly. + +## Alternatives considered + +### A looser test for an `async` function + +It refused the mock functions of the test runner. + +## Consequences + +- A mistake in the options fails at the call, with a code. +- Size: 82 bytes for the checks of `properties` and transforms, 56 for the + checks of `version` and `migrate`. 5 unit tests changed: 4 fixes and 1 + incidental. diff --git a/docs/decisions/0023-a-restore-is-all-or-nothing.md b/docs/decisions/0023-a-restore-is-all-or-nothing.md new file mode 100644 index 00000000..f60376ec --- /dev/null +++ b/docs/decisions/0023-a-restore-is-all-or-nothing.md @@ -0,0 +1,44 @@ +# 0023. A restore is all or nothing + +- **Status:** Accepted +- **Date:** 2026-11-25 +- **Kind:** bug +- **Label:** Before 1.0, for the documented sentence +- **Changes documented behaviour:** yes + +## Context + +Before 1.0, `persist` restores a record field by field through the store: + +- A deeply nested record restores and then makes every snapshot and every + save throw, so it is never replaced, and the store never saves again. + Deeper still, the restore fails part-way: earlier fields are restored and + later ones are not. +- `JSON.parse` makes `"__proto__"` an ordinary own key. A restored object + keeps it as data, and the next save writes it back. +- A synchronous subscriber is told once per field and can edit another + field in between. + +## Decision + +- A restore copies every value first, writes them in one transaction, checks + that the result can be snapshotted, and rolls back if it cannot. +- A nested `__proto__` key is dropped. +- A record whose restore was rolled back, or that is nested too deep to + copy, has nothing to keep (record 0021): it is reported, and the next save + replaces it. No release can restore such a record, so keeping it would + only stop the store from saving for good. +- The per-field bookkeeping of a restore that this makes unreachable is + removed in the same commit (record 0020). + +## Alternatives considered + +None was named. + +## Consequences + +- A synchronous subscriber is told once, after the whole record is in. The + persist tutorial describes the behaviour from before 1.0, and that + sentence changes in the same commit. + +- Size: 74 bytes on `./utils`. 1 unit test changed, a fix. diff --git a/docs/decisions/0024-a-pending-save-is-flushed-and-only-an-expiry-stamp-is-written-back.md b/docs/decisions/0024-a-pending-save-is-flushed-and-only-an-expiry-stamp-is-written-back.md new file mode 100644 index 00000000..e44408a9 --- /dev/null +++ b/docs/decisions/0024-a-pending-save-is-flushed-and-only-an-expiry-stamp-is-written-back.md @@ -0,0 +1,56 @@ +# 0024. A pending save is written when the page is hidden, and nothing is written back at load but an expiry stamp + +- **Status:** Accepted +- **Date:** 2026-11-25 +- **Kind:** bug +- **Label:** Before 1.0: the persist tutorial says that hydration does not + rewrite storage, and the stamp is an exception to that sentence +- **Changes documented behaviour:** yes + +## Context + +- Before 1.0, a debounced save that is still waiting is lost when the page goes + away: `debounce` has no flush. +- After a restore that migrates version 1 to 2, the stored record still says + version 1, so the migration runs on every load until the first edit. +- With `expireIn` set, a record with no `expiresAt` never expires. +- The persist tutorial says that hydration does not rewrite storage. + +## Decision + +- A debounced save that is still waiting is written when the page is hidden + (`pagehide`). +- **A migrated record is not written back at load.** The first save writes + it, as before 1.0. +- **One thing is written back at load:** a record of the configured version + that has no `expiresAt`, or `null`, read by a handle whose `expireIn` is a + finite number, is saved again with an `expiresAt`, through the ordinary + save path and its debounce. Its state and its version are unchanged. +- A record that arrives from another tab is never written back. + +## Alternatives considered + +### Write a migrated record back at load + +So that the migration would not run again on the next load. It opens two +losses. A `migrate` that is wrong and does not throw would replace the +source record for every user who opens the release, edit or no edit, where +without the write-back a user who only looks keeps the old record. And after +a rollback, every user who merely opened the newer build would have a record +the older build must not write over. Running a `migrate` once more per load +costs nothing next to either. Not taken, and final for 1.0. + +### Stamp a record for any `expireIn` + +With `expireIn: Infinity` the record is written again on every load. + +## Consequences + +- The tutorial sentence that hydration does not rewrite storage gets the + stamp as its one exception. +- The `pagehide` flush changed no unit test. A real page unload was not + tested; it is tested in the browser suite. +- A migrated record was kept until the first edit, and a record without + `expiresAt` was written once with one, in a prototype. The limit to a + finite `expireIn` was not built. No test pins either write-back before 1.0; + both get tests. diff --git a/docs/decisions/0025-cross-tab-sync-ignores-another-storage-area.md b/docs/decisions/0025-cross-tab-sync-ignores-another-storage-area.md new file mode 100644 index 00000000..18038e3f --- /dev/null +++ b/docs/decisions/0025-cross-tab-sync-ignores-another-storage-area.md @@ -0,0 +1,33 @@ +# 0025. Cross-tab sync ignores an event from another storage area + +- **Status:** Accepted +- **Date:** 2026-11-25 +- **Kind:** bug +- **Label:** Can follow 1.0 +- **Changes documented behaviour:** no + +## Context + +With cross-tab sync on, `persist` listens to the `storage` event. Before +1.0, the handler +applies an event under the same key from another storage area, +for example a write to `sessionStorage` to a store kept in `localStorage`, +and a synthetic event that has no `storageArea`. + +## Decision + +The narrow form: when `storage` is a `Storage`, an event whose +`storageArea` is another area is ignored. An event without `storageArea` is +still accepted, because only a script can make one, and a script on the page +can write to the storage directly. + +## Alternatives considered + +### Refuse an event that has no `storageArea` + +It protects nothing: a script that can make such an event can write to the +storage itself. + +## Consequences + +- Size: 24 bytes on `./utils`. No unit test changed. diff --git a/docs/decisions/0026-persist-options-stay-as-they-are.md b/docs/decisions/0026-persist-options-stay-as-they-are.md new file mode 100644 index 00000000..4ec232c0 --- /dev/null +++ b/docs/decisions/0026-persist-options-stay-as-they-are.md @@ -0,0 +1,47 @@ +# 0026. `persist` options stay as they are + +- **Status:** Accepted +- **Date:** 2026-11-25 +- **Kind:** public API +- **Label:** No change +- **Changes documented behaviour:** no + +## Context + +Several changes to the options of `persist` were weighed before 1.0: +make +`storage` optional with a default of `localStorage`, as Zustand and Jotai +do; merge `expireIn` and `clearOnExpire` into one option; add a switch to +pause saving and a flag for a write in flight. + +## Decision + +No option is renamed, removed or made optional. `storage` stays required. +`clearOnExpire` stays. One callback gains an argument: `onError` receives +the handle as its third (record 0021). A callback written for two arguments +still fits. + +## Alternatives considered + +### An optional `storage` + +Making it optional later is an addition. A default of `localStorage` would +add a new silence where it is missing. + +### Remove `clearOnExpire` and always clear an expired record + +That was reasoned, not built, and it would delete data in two cases nobody +ran: a handle without `expireIn` reading a record another handle stamped, +and a device whose clock runs ahead on shared storage. A tidier option list +is not worth a deletion that was never tested. + +### A pause switch and an in-flight flag + +`pause()` and `resume()`, or an `isSaving` field in the status, can be added +later without breaking anyone. + +## Consequences + +- Nothing changes for a user beyond the third argument of `onError`. +- Open again with a test of the two expiry cases above, or when a user needs + the switch or the flag. diff --git a/docs/decisions/0027-devtools-named-entries-exact-time-travel-off-in-production.md b/docs/decisions/0027-devtools-named-entries-exact-time-travel-off-in-production.md new file mode 100644 index 00000000..5e759d57 --- /dev/null +++ b/docs/decisions/0027-devtools-named-entries-exact-time-travel-off-in-production.md @@ -0,0 +1,115 @@ +# 0027. `devtools` sends named entries, travels in time exactly, and is off in production + +- **Status:** Accepted +- **Date:** 2026-11-25 +- **Kind:** public API, bug +- **Label:** Before 1.0 +- **Changes documented behaviour:** yes + +## Context + +Before 1.0: + +- Every entry `devtools` sends is named `STORE_UPDATE`, which makes the + tool's list useless. +- A jump assigns each key of the parsed state in turn. Unknown fields are + added, missing ones are never deleted, a setter-only accessor is called, a + `Date` comes back as a string, and a synchronous subscriber is notified + once per field. +- `RESET`, `COMMIT`, `ROLLBACK` and `IMPORT_STATE` are ignored. +- `enabled` defaults to `true` everywhere. DevTools on a production page + hands the whole state to any extension that asks, and a default cannot be + changed after 1.0. + +## Decision + +- **Entries.** `devtools` subscribes on the synchronous channel. A store + method sends one entry, named after the method, when the outermost call + returns, with one snapshot. Direct writes outside a method send one + `STORE_UPDATE` entry per task, from a microtask. So the synchronous channel + costs one snapshot per outermost method and never one per direct write. +- **How the name reaches `devtools`: a hook.** The core holds one place for a + function, empty unless `devtools` is connected, and nothing else. + `devtools()` fills it while at least one connection is open and empties it + when the last one is disposed. A method call tests it; when it is empty the + call runs the same code as before 1.0. The naming itself lives in + `devtools.ts`. +- **The name is the key.** The key a method was first read under is handed + to that function with the call, for a class method and a method held in a + field alike. The function's own `name` is not used: it is empty for an + arrow function assigned in a constructor. There is one method per object + and function (record 0001), so after `store.b = store.a` a call of + `store.b()` is named `a`. +- **Time travel.** A jump replaces the state exactly, in one transaction, + without calling setters, through the restore of record 0030. A jump to an + entry this session sent restores the snapshot that was sent, so a `Date` + stays a `Date`; a jump the extension sends as JSON restores data. +- **Messages.** `RESET`, `COMMIT`, `ROLLBACK` and `IMPORT_STATE` are handled. + A jump that the shared restore refuses, because the root fails its check + (record 0030), writes nothing: `devtools` catches the `restore-locked` + error and logs it with `console.error`, and the extension's panel shows + the entry it jumped to until the next entry arrives. +- **Options.** `devtools(store, options)` takes `name` and `enabled`, as + before 1.0, and five options of the extension that the build passes to its + `connect()`: `maxAge`, `trace`, `traceLimit`, `actionsDenylist` and + `actionsAllowlist`. `maxAge`, 50 by default as in the extension, also + bounds how many sent snapshots this session keeps for exact time travel. + The list is named, not an index signature, so a misspelt option is a type + error. Their bytes are inside the figures of record 0004. +- **`enabled` defaults to on only where `NODE_ENV` can be read and is not + `production`.** It reads the environment the way record 0036 does. Where + there is no `process` to read, the default is off: a bundle in which + nothing replaced the expression must not hand every state to an extension + because of it. `enabled: true` turns it on anywhere. The guide names the + builds in which the default is off, and says that the extension receives + every state, so a store with secrets passes `enabled: false`. +- **Computed values.** A snapshot no longer lists class getters (record + 0043), so `devtools` adds the values of the root store's class getters to + what it sends, each read guarded. A getter of an object literal that throws + still loses the entry. + +## Alternatives considered + +### A naming hook that runs on every method call + +The first form. It ran for every user, `devtools()` or not, and cost 5 to 6% +of a method call on Node, and 20 bytes on the main entry. + +### A "slot" in the core with a counter and the naming + +It keeps a counter and the naming in the core. The hook form keeps the core +to one empty place and costs 12 bytes on the main entry. + +### One snapshot per direct write on the synchronous channel + +It would make every direct write pay for a snapshot while `devtools` is +connected. + +### The getter values of nested objects in what `devtools` sends + +It needs a walk and a copy of every object on the way for every entry. It +can be added in a 1.x release. + +### On by default in every environment + +Not taken, and final for 1.0, as every default is. + +## Consequences + +- With the hook, a method call without `devtools` is inside the spread of + the code before this change on both engines. The main entry carries 12 bytes for it. +- While `devtools` is connected, a method call allocates one closure. +- An application that loads `./utils` twice, once as ESM and once as + CommonJS, and connects `devtools` from both, has one copy's names fall back + to `STORE_UPDATE`. That was read from the code, not run. +- Size on `./utils`: 403 bytes for the entries, the messages and the jump, + and 452 with the hook form. Record 0004 counts the naming moved out of the + core as +57 on `./utils`. The getter values add 95. +- 1,341 unit tests passed with the hook. `store.method` was timed in five + rounds on each engine. The prototype read the function's own `name`; + passing the key was not built, and an entry for an arrow function written + to a new key and for one assigned in a constructor is tested first. +- Before 1.0 there are no tests for `devtools`; they are written first. + +- Not verified: the entry ids the Redux DevTools extension sends back, and + the real extension at all. diff --git a/docs/decisions/0028-an-edit-in-the-same-tick-as-undo-is-recorded.md b/docs/decisions/0028-an-edit-in-the-same-tick-as-undo-is-recorded.md new file mode 100644 index 00000000..ee36064d --- /dev/null +++ b/docs/decisions/0028-an-edit-in-the-same-tick-as-undo-is-recorded.md @@ -0,0 +1,38 @@ +# 0028. An edit made in the same tick as `undo()` is recorded + +- **Status:** Accepted +- **Date:** 2026-11-25 +- **Kind:** bug +- **Label:** Before 1.0: the history guide describes the behaviour from + before 1.0, and that sentence goes +- **Changes documented behaviour:** yes + +## Context + +Before 1.0, `withHistory` keeps a `restoring` counter while it applies an undo or +a redo, and skips what is written while it is set: + +```ts +history.undo(); +store.value = 9; // no flush in between +``` + +Here `canRedo` stays `true`, and `redo()` discards the 9. With a flush +between the two lines, the edit is recorded. The version check already +skips the restore's own notification, so the counter is redundant as well as +wrong. The history guide describes this behaviour. + +## Decision + +`withHistory` drops its `restoring` counter and runs undo and redo as one +transaction each. An edit made in the same tick as `undo()` or `redo()` is +then recorded like any other. + +## Alternatives considered + +None was named. + +## Consequences + +- The history guide sentence that describes the old behaviour goes. +- `./utils` gets 24 bytes smaller. 1 unit test changed, a fix. diff --git a/docs/decisions/0029-with-history-restores-a-function-field-by-reference.md b/docs/decisions/0029-with-history-restores-a-function-field-by-reference.md new file mode 100644 index 00000000..71409fa1 --- /dev/null +++ b/docs/decisions/0029-with-history-restores-a-function-field-by-reference.md @@ -0,0 +1,52 @@ +# 0029. `withHistory` restores a function held in an own field, by reference + +- **Status:** Accepted +- **Date:** 2026-11-25 +- **Kind:** public API +- **Label:** Before 1.0 +- **Changes documented behaviour:** yes + +## Context + +Before 1.0, `withHistory` treats +a function held in an own field as behaviour, +not state. The history guide says that keys that resolve to a getter or a +function on the live store are skipped. So undo neither removes a callback +that was added nor puts back one that was replaced. + +Under record 0001 a snapshot holds each function as it was written, so a +recorded entry has the value to put back, and history records the field. + +## Decision + +- Undo removes a function that was added to a field and puts back one that + was replaced, by reference. Methods on the prototype are untouched. +- **A restore from outside never touches a function field.** A DevTools jump + that the extension sends as JSON carries no functions. The shared restore + (record 0030) neither deletes nor writes a function field for such a + state, so a jump cannot remove the arrow methods or the callbacks of a + store. Only a state the library recorded itself restores function fields. +- After the restore a read through the store hands out the same method as + before, because there is one method per object and function. +- This lands after record 0001. + +## Alternatives considered + +### Restore function fields under an earlier rule for functions + +When the store wrote its wrapper into the object, a restored callback came +back wrapped. Record 0001 does not change the object, so the write-back +holds the callback itself. + +## Consequences + +- The history guide sentence about skipped functions changes. +- The write-back was run on the rule of record 0001: a callback whose key was + deleted is written back by assignment and by a definition, and the snapshot + holds the callback itself both times. +- The change in `history.ts` itself was not built. The tests are written + first: a callback that is replaced, a callback whose key was deleted, a + function field that held another function at the time of the undo, and a + jump by JSON on a store whose methods are own fields. If the change turns + out larger than a few lines in `history.ts`, the work stops and this is + decided again. diff --git a/docs/decisions/0030-undo-and-time-travel-change-a-nested-object-in-place.md b/docs/decisions/0030-undo-and-time-travel-change-a-nested-object-in-place.md new file mode 100644 index 00000000..dffcbf3b --- /dev/null +++ b/docs/decisions/0030-undo-and-time-travel-change-a-nested-object-in-place.md @@ -0,0 +1,107 @@ +# 0030. Undo and time travel change a nested object in place + +- **Status:** Accepted +- **Date:** 2026-11-25 +- **Kind:** bug, performance +- **Label:** Before 1.0: the reference says "changed fields are replaced + with mutable copies" +- **Changes documented behaviour:** yes + +## Context + +Before 1.0, a restore by `withHistory` replaces a changed branch with a mutable +copy; the reference says "changed fields are replaced with mutable copies". +After undoing an edit to one row, every row of the list is a new object, +every row component renders again, and a row the caller held is detached. + +It is worse for a store that holds other stores, which record 0011 makes +ordinary. After one undo every row is a frozen snapshot: a prototype method +on it throws, and an arrow method writes the old store. An undo also puts a +copy in place of an object two stores share, which ends the sharing without +a word. A DevTools jump uses a restore of its own (record 0027). + +## Decision + +- A restore goes down while both sides are containers of the same kind, and + writes only what differs. Where a restored value is the snapshot of an + object that is still live, the live object is put back. +- Undo, redo and a DevTools jump share that one function. +- The function enters each live object at most once per restore, and treats + the recorded root as the store, so a store that refers to itself is + restored like any other (record 0044). +- **A container that would refuse the restore is replaced, as before 1.0.** + Before an object is restored in place, one check asks whether every write + the restore would make there is allowed. A key to add to an object that is + not extensible, a read-only key whose value differs, and a key that cannot + be deleted each fail it. The check counts only the writes the restore will + make: a function field that a state from outside does not carry is not a + key to delete (record 0029), so a jump by JSON on a sealed store whose + methods are own fields does not fail it. The object is then replaced at its + parent by a copy. +- The root cannot be replaced. When the root fails the check, the restore + throws a `TypeError` with the code `restore-locked` (record 0035) before + it writes anything, and the history does not move. A DevTools jump on + such a root writes nothing, and `devtools` logs the error (record 0027). +- **The restore follows the object, not the place it was recorded in.** An + object that was in the store when the entry was recorded and is still live + is put back and restored in place, wherever else it now sits. If it is also + part of another store, that store sees the restore, and its subscribers are + told once. The history guide says: a history records one store, an object + two stores share is undone in both, and a move between two stores is + undone by a history on a store that holds both. +- A DevTools jump that the extension sends as JSON restores data, not class + instances. The guide says so. + +## Alternatives considered + +### Keep replacing every changed branch + +The cost described above, and it is slower. + +### Restore in place without entering each object once + +With record 0044 in the same build, every restore that reached an object on +a cycle overflowed the stack, left the store half restored and moved the +history pointer all the same. + +### Restore in place without the check for a container that refuses + +Record 0005 keeps the children of a container that is frozen through the +store, and record 0002 keeps that freeze silent, so no history entry records +it. Without the check, an undo into such a container was refused part-way: +the store was half restored, its one notification carried the half state, +and the history had moved. Before 1.0 the same undo works, because it +replaces the branch. + +## Consequences + +- Undo of one row in 1,000 goes from 2,315 microseconds to 273 on Bun, and + 999 row snapshots are kept. +- A container that was locked after the entry comes back as a new copy + without the lock, child objects included, so a reference to the old + container no longer points into the store. That is the behaviour before + 1.0 for every restored branch. +- An undo in one store can take back an edit made through another store that + shares the object. +- Size on `./utils`: 113 bytes for the restore in place, 16 for entering each + object once, 211 for the check. The mark and the check changed no unit + test of their own. +- Six stores with a cycle were undone, redone and jumped back: all return, + each object is the one that was made, and each undo notifies once. An undo + of 1,000 plain rows stayed inside the spread with the mark (264 + microseconds against 263); 1,000 rows that point back to their store take + 1.9 milliseconds, which is the cost of record 0044. Four cases of an object + that moved to another store or is shared by two were run. +- With the check, seven kinds of locked container that threw part-way return + with the recorded values and one notification. A frozen root throws with + nothing written and the history unmoved, where the code before 1.0 throws + with the history moved. The 1,000-row undo stays inside the spread, with medians 5 to 8% + higher, on Bun. +- Not timed on Node. Not run: a DevTools jump on a frozen root. The check as + built counted a function field as a key to delete; the rule above was not + built, and a jump by JSON is tested first. +- Its tests are the six rows of a store with a cycle (undo, redo and a + jump), the four rows of an object that moved or is shared, and ten rows of + a container that would refuse the restore. +- This lands on top of record 0027, and takes over the line record 0044 adds + to `history.ts`. diff --git a/docs/decisions/0031-subscribe-key-without-a-snapshot-of-the-whole-store.md b/docs/decisions/0031-subscribe-key-without-a-snapshot-of-the-whole-store.md new file mode 100644 index 00000000..6b33c1f6 --- /dev/null +++ b/docs/decisions/0031-subscribe-key-without-a-snapshot-of-the-whole-store.md @@ -0,0 +1,37 @@ +# 0031. `subscribeKey` works without a snapshot of the whole store, and has no selector form in 1.0 + +- **Status:** Accepted +- **Date:** 2026-11-25 +- **Kind:** performance +- **Label:** Can follow 1.0 +- **Changes documented behaviour:** no + +## Context + +Before 1.0, `subscribeKey(store, + key, cb)` takes a snapshot of the whole store +on every notification, to compare one top-level key. Beside 1,000 rows that +costs 113 microseconds on Bun and 49 on Node per notification. + +It takes a top-level key only. Users of Zustand expect a selector, an +equality option and an immediate first call. + +## Decision + +- `subscribeKey` reads the live value, and takes a snapshot of that one node + only when the node or its version changed. The callbacks and their values + are the same in every case that was run. +- A selector form, an equality option and an immediate first call are not + part of 1.0. + +## Alternatives considered + +### A selector form, with an equality option and an immediate first call + +They are additions and can follow 1.0, if the key form stays. + +## Consequences + +- A key beside 1,000 rows goes from 113 microseconds to 0.45 on Bun and from + 49 to 0.78 on Node. +- 21 lines, 62 bytes on `./utils`, no unit test fails. diff --git a/docs/decisions/0032-workflows-hardened-now-release-job-split-after-1-0.md b/docs/decisions/0032-workflows-hardened-now-release-job-split-after-1-0.md new file mode 100644 index 00000000..bf576386 --- /dev/null +++ b/docs/decisions/0032-workflows-hardened-now-release-job-split-after-1-0.md @@ -0,0 +1,53 @@ +# 0032. The workflows are hardened now; the release job is split after 1.0 + +- **Status:** Accepted +- **Date:** 2026-11-25 +- **Kind:** repository +- **Label:** Can follow 1.0 +- **Changes documented behaviour:** no + +## Context + +One job of `release.yml` holds the npm publishing identity +(`id-token: write`) and also runs `bun install`, the build and Changesets +before `npm publish`. Actions are pinned by major tag. A compromised +development dependency or a moved action tag could take the token and +publish a version of its own. Three workflows declare no permissions. + +## Decision + +- **Now:** every third-party action in every workflow is pinned to the + commit its tag points to, with a Dependabot configuration that keeps the + pins current. "Third-party" means every action this repository does not + define, GitHub's own `actions/*` included: a moved tag is the same risk + whoever owns it. The three workflows that declare no permissions get + `contents: read`. Neither changes what a run does. +- **After 1.0:** `release.yml` is split into a job that installs, builds, + runs Changesets and packs the tarball, and a job that holds + `id-token: write`, installs nothing and publishes that tarball. The design + for it names where each step goes, the tag step and the "already + published" check included, and sets `persist-credentials: false` on the + release checkout with the token passed to the push. The owner tries it + with a manual run before a release depends on it. +- Only the owner can do two steps of the split: a GitHub environment for the + publish job with a required reviewer, and the npm settings that accept + only that environment and refuse publishing with a token. + +## Alternatives considered + +### Split the release job before 1.0 + +A release workflow cannot be tried without releasing. If the split landed +before 1.0, its first run would be the publish of 1.0. Nothing about the +split has to ship with 1.0. + +## Consequences + +- The split closes the route by which an installed dependency takes the + token. It does not close the other one: the same code could rewrite + `dist` before it is packed, and the second job would publish that. + Pinning closes the moved-tag half of both. +- Until the split, a compromised development dependency in the release job + could still take the token. +- Not tried: that code in the job can take the token. It comes from how + GitHub and npm document the mechanism. diff --git a/docs/decisions/0033-dependencies-exact-pin-and-an-audit-step.md b/docs/decisions/0033-dependencies-exact-pin-and-an-audit-step.md new file mode 100644 index 00000000..effc27d1 --- /dev/null +++ b/docs/decisions/0033-dependencies-exact-pin-and-an-audit-step.md @@ -0,0 +1,29 @@ +# 0033. Dependencies: an exact pin, and an audit step that reports + +- **Status:** Accepted +- **Date:** 2026-11-25 +- **Kind:** repository +- **Label:** Can follow 1.0 +- **Changes documented behaviour:** no + +## Context + +`proxy-compare` is the library's one runtime dependency, and it is pinned to +an exact version. `bun audit` reports advisories in development +dependencies; the published tarball is accepted as it is. + +## Decision + +- `proxy-compare` stays pinned to an exact version, and `CONTRIBUTING.md` + says why. +- CI gets a `bun audit` step that reports and does not fail. +- The published tarball is accepted as it is. + +## Alternatives considered + +None was named. + +## Consequences + +- An update of `proxy-compare` is a deliberate change. +- An advisory shows in CI without blocking a change. diff --git a/docs/decisions/0034-documentation.md b/docs/decisions/0034-documentation.md new file mode 100644 index 00000000..7f3251c0 --- /dev/null +++ b/docs/decisions/0034-documentation.md @@ -0,0 +1,70 @@ +# 0034. Documentation changes go with the change they describe, and shared limits stay documented + +- **Status:** Accepted +- **Date:** 2026-11-25 +- **Kind:** docs +- **Label:** With each change +- **Changes documented behaviour:** no + +## Context + +Before 1.0, several limits and defaults are not stated in the docs, and +several limits are shared with other libraries and have no plan to change +them. +Code that spreads a snapshot changes without an error under record 0043. + +## Decision + +Each documentation change is made with the code change it belongs to, or, +where no code changes, in a documentation pass of its own before 1.0 is +released. A change +corrects every page it makes false, in its own commit, even where a later +change puts something back. These changes are made: + +- "Frozen objects are values" needs the whole value frozen: the mutable + contents of a shallowly frozen object are shared with every snapshot. +- An unmarked class instance is shared between the store and every snapshot. +- A `#private` field is never state. +- The object passed to `createClassyStore` is the store. The Solid guide says + so, because a Solid user expects it to stay untouched. +- `subscribe()` is batched by default, and its callback receives no + arguments. Both are stated at the top of the reference (record 0017). +- Each adapter guide names `batch()` beside the synchronous timing. +- The Svelte guide names its example value `snap`, not `state`, which + conflicts with the `$state` rune, and gets a section on runes (record + 0040). +- `persist`: recipes for AsyncStorage, IndexedDB and an encrypting wrapper; a + transform each for `Date`, `Map` and `Set`; unknown stored keys are ignored + and removed at the next save; stored data is untrusted input and `merge` is + the place to validate it; a record with no version counts as version 0. +- `devtools`: the extension receives every state, so secrets do not belong + in a store with DevTools enabled outside development (record 0027). + +These limits stay as they are, documented where they are documented or +listed as unspecified: + +- A write through the raw object is invisible until the next write through + the store to that node. +- A subscription follows the object, not the property. +- An object returned by a getter is not protected. +- `Object.getOwnPropertyDescriptor(store, key).value` is the raw object. +- `structuredClone(store)` throws. +- A write past the end of a typed-array store notifies and stores nothing. + +Two more sentences go into the reference: + +- **An array in a store carries its indices and `length` only.** A named + property written to one stays on the live array and is left out of every + snapshot. A check that reports it can follow in 1.x. +- **A spread or a serialised snapshot carries data, not computed values** + (record 0043). The changelog entry for 1.0 has the same sentence, because + code that spreads a snapshot changes without an error. + +## Alternatives considered + +None was named. + +## Consequences + +- The docs describe 1.0 at each commit, not only at the end. +- The changelog for 1.0 names the change to spreads of snapshots. diff --git a/docs/decisions/0035-every-error-carries-a-stable-code.md b/docs/decisions/0035-every-error-carries-a-stable-code.md new file mode 100644 index 00000000..48ff37af --- /dev/null +++ b/docs/decisions/0035-every-error-carries-a-stable-code.md @@ -0,0 +1,95 @@ +# 0035. Every error carries a stable code, and throws the same in every build + +- **Status:** Accepted +- **Date:** 2026-11-25 +- **Kind:** diagnostics +- **Label:** Before 1.0 +- **Changes documented behaviour:** no + +## Context + +The changes of 1.0 add many errors and reports. Message text is where the +bytes are: of the 625 bytes the first group of changes adds to the main +entry with its messages as first written, 271 are text. Before 1.0 the +library already has a few messages, and tests and users match on that text. +Before 1.0 the Vue and Solid messages start with their entry point and the +Angular one has no prefix. + +## Decision + +- An error or a logged report from the library reads + `@codebelt/classy-store [code]: facts`, where the code is a short string + such as `getter-cycle` and the facts are the names the user wrote. +- **One prefix.** Every message starts with `@codebelt/classy-store`, the + adapters' too; the code says where it comes from. +- The advice that goes with each code is on one page of the documentation. + The page also lists what 1.0 does not catch (record 0036). +- Codes are stable from 1.0: renaming one is a breaking change, adding one + is not. The text after the code is unspecified. +- No error subclass and no `code` property are added. +- No check throws in one build and not in another. The bound on delivery + rounds, the check for a cycle of getters on a snapshot (record 0010) and + the handling of a cyclic store in `snapshot()` (record 0044) stay in + every build. +- Codes are named subject first, then what went wrong. A `persist` record + has three codes, not one, because what happens next differs: a record + with nothing to keep is replaced at the next save, and the other two stop + the handle from writing. An `onError` that decides whether to call + `clear()` has to tell them apart, and the text after a code is not + stable. + +**The codes of 1.0.** Nineteen. A report made in every build is written with +`console.error`; the one development-only report with `console.warn` +(record 0036). + +| Code | Thrown or logged by | When | Record | +| -------------------- | ------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | ---------- | +| `getter-cycle` | A read of a getter, on the store or a snapshot | Getters read each other in a cycle. Facts: the path | 0010, 0035 | +| `not-a-store` | `snapshot`, `subscribe`, `subscribeKey`, `prepareStoreForHydration`, every hook and adapter | The argument is not a store | 0035 | +| `getter-write` | A getter, on the store or a snapshot | It writes to the object it is computed on. Facts: the field | 0010 | +| `delivery-loop` | Logged where a subscriber's error is logged | Delivery reached 100 rounds | 0013 | +| `batch-async` | `batch` | The callback is a native `async` function | 0016 | +| `frozen-collection` | The mutators of `ReactiveMap` and `ReactiveSet` | Called on a snapshot, through a tracking proxy, or on a collection its owner froze | 0045 | +| `persist-option` | `persist()`, before it reads or writes | A key in `properties` that is a prototype key, a getter or a method; a half-written transform; a `version`; an `async` `migrate` | 0022 | +| `persist-invalid` | A `persist` report, `'parse'` | A stored record that parses and has nothing to keep | 0021, 0023 | +| `persist-newer` | A `persist` report, `'parse'` | A stored record of a newer version | 0021 | +| `persist-not-plain` | A `persist` report, `'parse'` | `migrate` or `merge` returned a thenable or a value that is not a plain object | 0021 | +| `persist-unread` | A `persist` report, `'write'`, and the rejection of `save()` | `save()` before the first read has settled | 0021 | +| `persist-disposed` | The rejection of a call on a disposed handle | The handle was disposed | 0035 | +| `persist-failed` | The default `persist` report, without `onError` | Any report; the error is its second argument | 0021 | +| `restore-locked` | `undo()`, `redo()`, and a DevTools jump | The root of the store fails the check of the restore | 0030 | +| `vue-readonly` | A write to the ref the Vue adapter returns | Always | 0038 | +| `vue-no-scope` | The Vue `useClassyStore` | No active effect scope | 0035 | +| `solid-no-owner` | The Solid `useClassyStore` | No live owner | 0035 | +| `angular-no-context` | `injectClassyStore` | No injection context and no `injector`, or a destroyed context | 0035, 0039 | +| `lost-write` | Development only, logged once | A field of the raw object changed without a write through the store. Facts: the field. Only if the check of record 0036 lands | 0036 | + +Not reports of the library, and logged as they are: a subscriber's error and +the rejection of an `async` subscriber (record 0014), an error that +`onError` throws (record 0021), and a status listener's error. + +**The messages from before 1.0 get their codes in one commit**, early in +the work: `getter-cycle`, `not-a-store`, `vue-no-scope`, `solid-no-owner`, +`angular-no-context` and `persist-disposed`. Their text changes once. The +snapshot's `circular reference detected in snapshot` gets no code: record +0044 removes that throw before 1.0, so no user would ever see a code for +it, and the page never lists a code that 1.0 does not have. The page of +codes is created in that commit, and from then on every commit that adds a +message adds its code and its line on that page. + +## Alternatives considered + +### A development build with long messages and a production build without + +A split saves no more on messages than a code with the names does. A +program that fails in production and not in development, or the other way +round, is worse than either. + +## Consequences + +- About 100 bytes of the message text belong to messages that are kept, and + a code with the names saves them with no build split. The rest belonged to + refusals that are not taken. +- 29 assertions in 15 test files match the text from before 1.0 and are + rewritten to match the code. That count is from a search, not from a run. +- A user who matched on the old text has to match on the code. diff --git a/docs/decisions/0036-one-build-and-one-development-only-check.md b/docs/decisions/0036-one-build-and-one-development-only-check.md new file mode 100644 index 00000000..95cd7d19 --- /dev/null +++ b/docs/decisions/0036-one-build-and-one-development-only-check.md @@ -0,0 +1,121 @@ +# 0036. One build, and one development-only check in 1.0 + +- **Status:** Accepted +- **Date:** 2026-11-25 +- **Kind:** diagnostics +- **Label:** Before 1.0 for the guard's rule and the default of `devtools`; + the check can follow 1.0 +- **Changes documented behaviour:** no + +## Context + +Several silent failures stay in 1.0. The first is an arrow-function method +that writes to the raw instance. The base class of record 0011 removes it +only for a class that is changed to extend it; `createClassyStore(new X())` +stays documented, and a class that extends something else has no other way. +The same failure comes from a constructor that starts a timer, and from a +write through the raw object. + +A development-only check must cost production nothing, and must not break +the cost limits of `CONSTRAINTS.md`. + +## Decision + +- 1.0 ships one build. Export conditions are not used. +- It has one check that runs in development only: **the report of a lost + write.** When a snapshot is asked for and a field of the raw object has + changed without a write through the store, the library logs it once, with + the code `lost-write` and the name of the field. The comparison runs at + most once per task for a store, however often its snapshot is asked for in + that task. +- **The cost limits come first.** The core benchmark loads the built file as + it is, with `NODE_ENV` not set, so it measures the development path, and it + keeps doing so. The limits have to hold there with the check in. +- **The benchmark has to see it.** Each sample of the benchmark is one loop + in one task, so a check that runs once per task costs a sample one + comparison. So a row is first added to the benchmark that takes one cached + snapshot per task of the 1,000-row store, and it is recorded without the + check. The check lands only if that row with the check in stays below the + benchmark's `snapshot.afterWrite` for the same store, on both engines. The + figure goes into this record as the stated cost of the development path. + If the check cannot meet that, it does not ship in 1.0; it is a report and + can arrive in any release. +- **The row awaits between two snapshots.** It awaits a resolved promise + between two snapshots, so each snapshot is taken after the microtasks + queued before it have run, and the await is part of its time. "Once per + task" therefore means: the check marks the store as checked, and a + microtask it queues clears the mark. +- **The guard form.** A development-only check is guarded by an inline read + of `process.env.NODE_ENV` at its call site, after a test that is cheap and + almost always false, and behind `typeof process`. That form becomes a floor + rule of `CONSTRAINTS.md`, held by a test that bundles the built file for + production and asserts that no development text and no `console.warn` is + left in it. The default of `devtools({enabled})` reads the environment the + same way (record 0027). +- **How the test knows development text.** A development-only report is + written with `console.warn`, and nothing else in the library calls + `console.warn`. Its code is listed in + `packages/classy-store/tests/size/developmentOnly.json`, which is empty + until the check of this record lands. `bun run size` already bundles every + entry for production, with `NODE_ENV` set to `production`; it fails when + such a bundle holds `console.warn` or a listed code. A unit test bundles a + fixture written in the guard form, once for production and once for + development, and asserts that its marker text and its `console.warn` are + gone from the first and present in the second. So the form is held from + the first commit, before any check exists, and the floor rule names both. +- **What 1.0 still does not catch** is listed on the page of error codes + (record 0035): a native `Map` or `Set` in a store, an unmarked nested class + instance, a `Date` changed in place, a getter that reads another store or a + static, a result of a getter that is mutated, a named property on an + array, an own-property check inside a getter, and a prototype changed after + its first read through a store. +- Other warnings follow in a 1.x release. + +## Alternatives considered + +### Export conditions (`development` and `production`) + +Plain Node, `bun test` and an unminified bundle would load the production +build in silence, the published files double, and `check:package` does not +check the second branch. + +### The check on every cached snapshot + +As first built, the check compares the fields every time a cached snapshot +is handed out. That is eleven to thirteen times dearer and would put the +cached-snapshot ratio far above its limit on both engines. + +### The check always on + +It is 168 to 309 bytes. Behind the guard it costs production a few bytes. + +### Four more development warnings + +Five development warnings were built. The fifth, the report of a lost +write, ships in the better form described above. The other four are not +ready: a warning that fires for correct code and cannot be silenced is worse +than none. The one for an unmarked class instance fires for seven kinds of +object that are no mistake, and one for a write after an `await` would fire +for the ordinary `async` method. + +### A module-level constant for the environment + +It leaked 218 bytes into the production bundle, where an inline read cost 6. + +## Consequences + +- The check found six of seven lost writes in a prototype and reported + nothing that was not one. +- An inline read on the path of a write cost 184 nanoseconds on unbundled + Node, which is why the guard reads the environment after a cheap test. +- The once-per-task form was not built. The check was measured always on, + not behind the guard; it is measured there first. +- An application takes about one snapshot per store per task and pays for + the comparison each time in development. + +## Measured cost of the development path + +To be filled in when the check lands. + +| Commit | Row | Engine | Without the check | With the check | `snapshot.afterWrite` | +| ------ | --- | ------ | ----------------: | -------------: | --------------------: | diff --git a/docs/decisions/0037-vue-angular-and-solid-build-the-snapshot-when-it-is-read.md b/docs/decisions/0037-vue-angular-and-solid-build-the-snapshot-when-it-is-read.md new file mode 100644 index 00000000..88bbf96b --- /dev/null +++ b/docs/decisions/0037-vue-angular-and-solid-build-the-snapshot-when-it-is-read.md @@ -0,0 +1,44 @@ +# 0037. The Vue, Angular and Solid adapters build the snapshot when it is read + +- **Status:** Accepted +- **Date:** 2026-11-25 +- **Kind:** performance +- **Label:** Before 1.0 for Vue: the reference says the adapter returns a + ref "backed by `shallowRef`", and it becomes a custom ref that + `isShallow()` can tell apart. Can follow 1.0 for Angular and Solid +- **Changes documented behaviour:** yes + +## Context + +Before 1.0, every adapter takes +a snapshot inside its listener. Adapters +subscribe synchronously, so a loop of direct writes takes one snapshot per +write: 2,000 direct row writes followed by one read cost about 650 +milliseconds. The reference says the Vue adapter returns a ref "backed by +`shallowRef`". + +## Decision + +In the Vue, Angular and Solid adapters the listener only marks the value as +changed, and the snapshot is taken at the next read. The Vue adapter returns +a custom ref, which `isShallow()` can tell apart from a `shallowRef`; the +reference sentence changes in the same commit. + +React and Svelte cannot defer in this way, because their contracts hand the +value to the framework at once. For them the answer is `batch()`, which the +guides name. + +## Alternatives considered + +None was named for these three adapters. + +## Consequences + +- 2,000 direct row writes followed by one read go from about 650 + milliseconds to 2.4 in each of the three adapters. +- 34 to 44 bytes per entry. 1 unit test changed, incidental: `isShallow` on + the Vue ref. +- The packed-app and browser suites of each framework were not run on the + prototype. Each adapter change runs its framework's suite. +- The change is required before 1.0 for Vue, because it changes a documented + return shape, and can follow 1.0 for Angular and Solid. diff --git a/docs/decisions/0038-vue-no-listener-left-by-a-server-render-and-a-read-only-ref.md b/docs/decisions/0038-vue-no-listener-left-by-a-server-render-and-a-read-only-ref.md new file mode 100644 index 00000000..14cde9e9 --- /dev/null +++ b/docs/decisions/0038-vue-no-listener-left-by-a-server-render-and-a-read-only-ref.md @@ -0,0 +1,50 @@ +# 0038. Vue: no listener is left by a server render, and the ref is read-only + +- **Status:** Accepted +- **Date:** 2026-11-25 +- **Kind:** bug, public API +- **Label:** Before 1.0, for the documented return type +- **Changes documented behaviour:** yes + +## Context + +- Vue does not dispose component scopes during a server render, so a store + that outlives the request gains one listener per render: 1, 2, 3 after + three renders. +- The Vue adapter returns a writable ref. `state.value = …` compiles, but a + snapshot is frozen, so a writable ref promises something the value cannot + do. The Angular adapter already returns a read-only signal. + +## Decision + +- On the server the Vue adapter subscribes to nothing and reads the store at + every read. The adapter is on the server when it runs inside a component + and `inject(ssrContextKey, null)` is set, which is so exactly inside + `renderToString`. The check for an active effect scope from before 1.0 + stays, and comes first. +- The returned ref is typed `Readonly>>`, and a write to it + throws a `TypeError` with the code `vue-readonly` (record 0035). +- This lands in one change with the Vue part of record 0037. + +## Alternatives considered + +### Subscribe in `onMounted` + +It removes the leak and breaks something else: a store written in +`onServerPrefetch`, Vue's own way to load data on the server, then renders +its old value. Reading at the read removes the leak and keeps that write. + +### A setter that does nothing + +A silent failure for a template or a JavaScript caller. A throw is the loud +form. + +## Consequences + +- 0 listeners after three server renders, and the `onServerPrefetch` write + still renders. The prototype told the server by the same test of + `ssrContextKey`. + +- The documented return type changes. +- The type was not compiled against Vue 3.2.0, the floor of the peer range; + that is done first. The throwing setter was not built in a prototype. diff --git a/docs/decisions/0039-angular-untracked-an-injector-option-and-its-own-context-error.md b/docs/decisions/0039-angular-untracked-an-injector-option-and-its-own-context-error.md new file mode 100644 index 00000000..69942a5a --- /dev/null +++ b/docs/decisions/0039-angular-untracked-an-injector-option-and-its-own-context-error.md @@ -0,0 +1,42 @@ +# 0039. Angular: a store write inside a `computed` is not lost, and `injectClassyStore` takes an injector + +- **Status:** Accepted +- **Date:** 2026-11-25 +- **Kind:** bug, public API +- **Label:** Can follow 1.0 for the fix; the option is an addition +- **Changes documented behaviour:** no + +## Context + +- Before 1.0, a store write made while an Angular `computed` runs makes Angular + throw inside the adapter's listener. The core logs the error, and the + signal stays stale until the next write. +- `injectClassyStore` works only inside an injection context. +- Angular's own assertion for a missing injection context names the function + only in Angular's development mode; in a production build it is a bare + `NG0203`. + +## Decision + +- The adapter updates its signal inside `untracked()`. +- `injectClassyStore(store, {injector})` works outside an injection context. + The option is added while the signature is written down for 1.0. +- The adapter checks for an injection context itself and throws its own + error, with the library's prefix and the code `angular-no-context` + (record 0035), in every Angular build. The same code covers a context + that is already destroyed, which the message from before 1.0 reports. +- The type of the options object is not exported in 1.0. + +## Alternatives considered + +### Call Angular's own assertion + +Its message is a bare `NG0203` in a production build. + +## Consequences + +- The signal is current after a write made inside a `computed`. +- 19 bytes for the fix, 51 more for the option and the message, on + `./angular`. The library's own context check was not built in a prototype; + its ceiling has 30 bytes for it (record 0004). +- The fix can follow 1.0; the option is an addition. diff --git a/docs/decisions/0040-the-adapter-names-stay.md b/docs/decisions/0040-the-adapter-names-stay.md new file mode 100644 index 00000000..ab577613 --- /dev/null +++ b/docs/decisions/0040-the-adapter-names-stay.md @@ -0,0 +1,37 @@ +# 0040. The adapter names stay + +- **Status:** Accepted +- **Date:** 2026-11-25 +- **Kind:** public API +- **Label:** No change +- **Changes documented behaviour:** no + +## Context + +The adapters are `useClassyStore` for React, Vue and Solid, +`toSvelteStore` for Svelte and `injectClassyStore` for Angular. In Solid the +adapter behaves like Solid's `from()`, and `use*` there usually means a +context lookup, so `fromClassyStore` was weighed for Solid. + +## Decision + +No adapter is renamed. The Solid adapter keeps `useClassyStore`. + +The Svelte guide gets a section on runes and names its example value +`snap`, not `state`. + +## Alternatives considered + +### Rename the Solid adapter to `fromClassyStore` + +The precedent is split. The function has to be called under an owner and +returns an accessor, which is what a Solid user expects of a `use` function. +A rename is a cost with no behaviour behind it: eleven files and every Solid +import. The name is also the one a user of the React or the Vue adapter +already knows. Not taken, and final for 1.0. + +## Consequences + +- Nothing changes in the code. +- The same reasoning keeps `isEqual` (record 0041). +- Open again only with a new reason; a rename after 1.0 is a breaking change. diff --git a/docs/decisions/0041-prepare-store-for-hydration-stays-explicit.md b/docs/decisions/0041-prepare-store-for-hydration-stays-explicit.md new file mode 100644 index 00000000..b933b719 --- /dev/null +++ b/docs/decisions/0041-prepare-store-for-hydration-stays-explicit.md @@ -0,0 +1,56 @@ +# 0041. React: `prepareStoreForHydration` stays an explicit call, and `isEqual` keeps its name + +- **Status:** Accepted +- **Date:** 2026-11-25 +- **Kind:** public API +- **Label:** No change +- **Changes documented behaviour:** no + +## Context + +For server rendering, a React store is passed to +`prepareStoreForHydration(store)`, which captures the snapshot the server +renders so that the client hydrates from the same data. One question was +whether to capture that snapshot automatically. Separately, the equality +option of the hooks is called `isEqual`, where Zustand and Jotai say +`equalityFn`. + +## Decision + +- The server snapshot is not captured automatically. + `prepareStoreForHydration` stays an explicit call. +- The equality option keeps the name `isEqual`. +- The guides say that on the client `prepareStoreForHydration(store)` is + called before `persist(store)`. The React SSR guide already says that it + captures the snapshot "before persistence or other live updates begin"; + the change of record 0019 names `persist()` there, and the persist + tutorial gains the same sentence. With record 0019, + a store restored by + `persist()` holds its saved state when `persist()` returns; prepared + afterwards, it would capture that state and not the one the server + rendered. + +## Alternatives considered + +### Capture the hydration snapshot automatically + +Both automatic forms were built, and both break the pattern the guide +teaches: create the store, load the request's data, then render. The capture +fires on the first load write, so the server renders the empty store, and a +later explicit call cannot undo it. A store that refers to itself throws on +its first write or cannot be created. Memory grows by 19 megabytes per +100,000 rows. 12 and 20 tests failed, all regressions. + +### Rename `isEqual` + +React's own `useSyncExternalStoreWithSelector` calls the parameter +`isEqual`. Zustand and Jotai say `equalityFn`. A breaking rename for a split +precedent is not worth it. Not taken, and final for 1.0. + +## Consequences + +- Nothing changes in the code. The persist tutorial gains the sentence on + the order of the two calls, and the React SSR guide names `persist()`. + +- Open again for the capture only with a form that keeps the + create-load-render pattern. diff --git a/docs/decisions/0042-collections-one-membership-rule-and-a-snapshot-index.md b/docs/decisions/0042-collections-one-membership-rule-and-a-snapshot-index.md new file mode 100644 index 00000000..97a88934 --- /dev/null +++ b/docs/decisions/0042-collections-one-membership-rule-and-a-snapshot-index.md @@ -0,0 +1,77 @@ +# 0042. Reactive collections: one membership rule, an index for snapshots, and native `Map` and `Set` stay opaque + +- **Status:** Accepted +- **Date:** 2026-11-25 +- **Kind:** bug, performance +- **Label:** Before 1.0 for the membership rule, because the collections + guide documents the behaviour from before 1.0 for `-0`; the index can + follow 1.0 +- **Changes documented behaviour:** yes + +## Context + +Before 1.0, `reactiveMap` and `reactiveSet` are backed by arrays and match +members by identity, which is the same for a raw object, its proxy and +every snapshot of it. Two rules disagree: + +- `+0` and `-0` are two members when added and one when constructed: + `reactiveSet([0])` then `add(-0)` has size 2; `reactiveSet([0, -0])` has + size 1. A native `Set` holds one. The collections guide documents this. +- A collection constructed from one object in two forms holds it twice: + `reactiveSet([raw, proxy])` has size 2, and `delete(raw)` leaves + `has(raw)` true. `add` holds it once. + +Every lookup scans the backing array, also on a frozen snapshot: `has()` +among 10,000 members takes 160 to 525 microseconds. + +## Decision + +- **One membership rule.** `-0` and `+0` are one key, as in a native `Map`, + and a collection constructed from a raw object and its proxy holds it + once. +- **Membership is by identity for every member.** A raw object, its proxy + and each of its snapshots are one member. That keeps a selection made with + one snapshot of a row true for the next. A collection cannot hold two + snapshots of one object as two members: the second `add()` changes + nothing, and the guide says so. A list in a store does not work this way + (record 0006). +- **A snapshot of a collection answers `has()` and `get()` from an index**, + built on the second lookup. A read through the tracking proxy of the React + hook without a selector still scans, because the tracker has to see what + was read. +- **Native `Map` and `Set` stay opaque**, and `reactiveMap` and + `reactiveSet` stay separate classes. +- Once record 0013 is in, the core skips a removed subscriber, so the Vue, + Angular and Svelte adapters drop their `active` flags, in the adapter + commits that follow it, not in the commit of record 0013: the adapter + files are not mutation targets, so nothing in `CONSTRAINTS.md` fails in + between, and each adapter change runs its own framework's suites once. + Solid keeps its flag, which under record 0037 + decides what the accessor returns after disposal, and Angular keeps its + `destroyed` check. + +## Alternatives considered + +### An index beside the live array in 1.0 + +It is 100 times faster on a hit and costs 339 bytes, and it answers wrong +after a write to the raw backing array, which the scan gets right. Record +0045 keeps the backing arrays public and makes writing to them unspecified, +which leaves room for it later. + +### Reactive native `Map` and `Set` + +No library has a frozen native `Map`: one can still be written through +`Map.prototype.set`. + +## Consequences + +- The collections guide changes its sentence on `-0`. +- The membership rule costs 13 bytes, and the 2 tests that pinned the two + defects change. +- Plain lookups on a snapshot among 10,000 members go from 160 to 525 + microseconds to under 0.1. `./collections` grows from 727 to about 843 + bytes. A tracked lookup was not timed. +- The membership rule is required before 1.0, because the collections guide + documents the behaviour from before 1.0 for `-0`. The index can follow + 1.0. diff --git a/docs/decisions/0043-class-getters-on-one-derived-prototype-per-class.md b/docs/decisions/0043-class-getters-on-one-derived-prototype-per-class.md new file mode 100644 index 00000000..d56f02c6 --- /dev/null +++ b/docs/decisions/0043-class-getters-on-one-derived-prototype-per-class.md @@ -0,0 +1,89 @@ +# 0043. A snapshot carries class getters on one derived prototype per class + +- **Status:** Accepted +- **Date:** 2026-11-25 +- **Kind:** public API, performance +- **Label:** Before 1.0 +- **Changes documented behaviour:** yes + +## Context + +Before 1.0, every snapshot of a class instance gets each class getter as an +enumerable own accessor. So: + +- `Object.keys(store)` and `Object.keys(snapshot(store))` differ. +- A spread or a `JSON.stringify` of a snapshot runs every getter, and throws + if one does. A DevTools entry is serialised the same way, so one class + getter that throws spoils the entry. +- A snapshot of a class with eight getters is slow to make and large. +- Inside a snapshot getter, `this` is a tracking proxy over an empty object: + it has no own keys, is not an instance of the class, and `return this` + hands that proxy out. A getter that reads `Object.keys(this)` answers 0 on + a snapshot and 2 on the store. +- A class setter gets an own key on a snapshot. +- A snapshot lists every data field before any own getter, whatever their + order on the store. + +No compared library lists a class getter among the own enumerable keys of a +copy. + +## Decision + +- A class getter is no longer an own accessor of every snapshot. For each + class that has getters, one object that inherits from the class prototype + is made once, with one memoizing accessor per getter, and snapshots of that + class are created from it. +- Inside a snapshot getter, `this` is the frozen snapshot behind a tracker, + so it has the store's keys, and the class as its constructor and for + `instanceof`. Its prototype is the derived object, not `Class.prototype`. +- A getter on an object literal stays an own accessor of the snapshot, + listed where the store lists it. +- `devtools` adds the values of the root store's class getters to what it + sends, each read guarded, so a class getter of the root that throws shows + its error text and the entry is still sent. Nested objects are sent as + they are. A getter of an object literal is run by the extension's + serialiser, and one that throws still loses the entry, at the root or below + it. +- On the React tracking path a tracked read and a plain read have to share + one cached result. That is where the risk of this change is. + +## Alternatives considered + +### Own accessors that are not enumerable + +One line, the same visible change for `Object.keys` and JSON, none of the +gain in time and memory, and `this` then needs a filter to match the store. + +### Keep the shape from before 1.0 + +No compared library does it, and it keeps every defect above. + +## Consequences + +- A spread or a serialised snapshot no longer carries computed values; they + have to be named. Nothing reports it: `{...snap}.total` still type-checks + and is `undefined`, as it is for any class instance in TypeScript. Every + compared library behaves this way, and the cost is taken on purpose. The + tutorial paragraph changes, and the changelog names it (record 0034). +- `Object.getPrototypeOf(snapshot)` is no longer `Class.prototype` for a + class with a getter. `instanceof` and `constructor` are unchanged. The + reference's "keep the class prototype" becomes "are instances of the + class". +- A snapshot of a reactive collection no longer lists `size` in + `Object.keys` or JSON. `snap.size` reads as before. +- The DevTools panel no longer shows the getter values of a nested store or + a nested class instance. Showing them needs a walk and a copy of every + object on the way for every entry; it can be added in a 1.x release. +- A snapshot of a class with eight getters is four times faster to make and + holds sixteen times less memory. +- `persist` saves the same fields as before. The base class of record 0011 + gets a correct snapshot on top of this change. +- Size: +239 bytes on the main entry and 14 unit tests changed (fixes, and + eight tests of the old shape changed by this decision); 95 bytes on + `./utils` for the `devtools` values. The 239 bytes and the 14 tests were + measured on the snapshot layer as it is before 1.0. Record 0010 changes + that layer first, so they are a forecast, + and the commit takes its own figures from its own + build. +- A jump that carries the added keys back restores the fields and adds no + key. Not run: the real Redux DevTools extension. diff --git a/docs/decisions/0044-a-snapshot-keeps-a-cycle.md b/docs/decisions/0044-a-snapshot-keeps-a-cycle.md new file mode 100644 index 00000000..bd4ed2a5 --- /dev/null +++ b/docs/decisions/0044-a-snapshot-keeps-a-cycle.md @@ -0,0 +1,62 @@ +# 0044. A snapshot keeps a cycle + +- **Status:** Accepted +- **Date:** 2026-11-25 +- **Kind:** bug, public API +- **Label:** Before 1.0: it reverses a documented sentence +- **Changes documented behaviour:** yes + +## Context + +Before 1.0, a store that refers to itself can be written but not read: + +```ts +store.self = store; // succeeds and notifies +snapshot(store); // throws "circular reference detected in snapshot" +``` + +It throws until the reference is deleted, so no adapter can read the store. +The tutorial says that circular references in traversed state are rejected +by `snapshot()`. + +## Decision + +`snapshot()` of a store that refers to itself returns a frozen snapshot with +the same cycle in it. The React hook, `withHistory` and `cloneSnapshot` are +made safe for it. + +The restore of record 0030 walks into live objects and has to stop on a +cycle; it enters each live object at most once. The line this change adds to +`history.ts` moves into the restore function that undo, redo and a DevTools +jump share. + +## Alternatives considered + +### Refuse the write that closes a cycle + +It would need a walk from the new parent to the roots on every assignment of +an object, and would also have to reject a cycle already in the object given +to `createClassyStore()`, which works on the live side before 1.0. Not +taken, and final for 1.0. + +## Consequences + +- Everything on a cycle gets a new snapshot on every write to any of it, so + a model with parent pointers loses structural sharing for what the pointers + connect. The docs say so and name the alternatives: hold the parent's id, + or hold the parent in an object the store does not proxy. +- `JSON.stringify` of such a snapshot throws, as for any cycle, and + `persist` reports it through `onError`. +- In the DevTools panel, a class store with a getter and a cycle shows its + root once more under the field that points back, because what `devtools` + sends for such a store is a copy (record 0043). +- Size: the main entry is 9 bytes smaller, `./utils` 21 larger, `./react` 30 + larger. 7 unit tests changed, all of them asserting the throw. +- The guard costs a tracked comparison in the React hook 14 to 29 + nanoseconds on data without a cycle. +- Built apart from record 0030, an undo overflowed the stack; with the mark + of record 0030 it returns. 1,000 rows that point back to their store take + 1.9 milliseconds to undo. +- Not checked: what the Redux DevTools extension does with a cyclic state. +- A getter on a store that refers to itself recomputes on every write, a + write to a field it never read included. That stays. diff --git a/docs/decisions/0045-snapshot-types-tuples-and-collections-without-mutators.md b/docs/decisions/0045-snapshot-types-tuples-and-collections-without-mutators.md new file mode 100644 index 00000000..f8f51164 --- /dev/null +++ b/docs/decisions/0045-snapshot-types-tuples-and-collections-without-mutators.md @@ -0,0 +1,58 @@ +# 0045. Snapshot types: tuples stay tuples, and a collection snapshot has no mutators + +- **Status:** Accepted +- **Date:** 2026-11-25 +- **Kind:** public API +- **Label:** Before 1.0: public types +- **Changes documented behaviour:** yes + +## Context + +In the public types before 1.0: + +- `Snapshot<[string, number]>` is `readonly (string | number)[]`. +- A snapshot of a reactive collection keeps its mutators in the type. + `snapshot(store).todos.set(…)`, `.delete()`, `.clear()` and `tags.add()` + compile, and each throws a `TypeError` when run. +- `add()` on a set that its owner froze and placed in a store pushes to the + raw array and tells no one. +- The backing arrays `_entries` and `_items` are writable members of the + published `ReactiveMap` and `ReactiveSet` types. The `@internal` tag is + only a comment. + +## Decision + +- `Snapshot<[string, number]>` is `readonly [string, number]`. +- `Snapshot>` and `Snapshot>` are two + exported types, `ReactiveMapSnapshot` and `ReactiveSetSnapshot` + from `./collections`, with the queries and the iterators and without + `set`, `add`, `delete` and `clear`. +- Calling a mutator on a snapshot, through a tracking proxy, or on a + collection its owner froze throws a `TypeError` with the code + `frozen-collection` (record 0035). + +- The backing arrays `_entries` and `_items` stay public, read-only in the + snapshot types. The docs say that writing to them directly, on a live + collection, is unspecified: use the methods. +- A subclass of a reactive collection works at run time, and its own members + are not in its snapshot type in 1.0: `Snapshot` is the snapshot type + of the collection it extends. + +## Alternatives considered + +### Hide the backing arrays + +The repository's own Next.js example reads them from snapshots in four +components, and hiding them is a migration with nothing behind it. Not +taken, and final for 1.0. + +### A way for a class to name its snapshot type + +An addition. It can follow 1.0. + +## Consequences + +- Code that called a mutator on a snapshot no longer compiles; it threw at + run time before. +- No unit test changed. Type tests in 3 files changed, all fixes. + `./collections` grows by 55 bytes with a short message. diff --git a/docs/decisions/0046-a-snapshot-after-one-row-changes-still-rebuilds-the-list.md b/docs/decisions/0046-a-snapshot-after-one-row-changes-still-rebuilds-the-list.md new file mode 100644 index 00000000..a2a1ded6 --- /dev/null +++ b/docs/decisions/0046-a-snapshot-after-one-row-changes-still-rebuilds-the-list.md @@ -0,0 +1,38 @@ +# 0046. A snapshot after one row changes still rebuilds the list + +- **Status:** Accepted +- **Date:** 2026-11-25 +- **Kind:** performance +- **Label:** Can follow 1.0 +- **Changes documented behaviour:** no + +## Context + +When one row of a list changes, the next snapshot builds a new frozen array +for the whole list, reusing the snapshots of the unchanged rows. The cost +grows with the number of rows. On Bun, freezing a new 1,000-element array +costs about 80 microseconds by itself. + +## Decision + +Not changed in 1.0. + +## Alternatives considered + +### Record which keys changed and rebuild only those + +It is correct: a prototype showed no difference in 120,000 compared +snapshots. On Node it makes a snapshot after one of 1,000 rows changes three +times faster. On Bun, and so most likely in Safari, it gains nothing at that +size, because freezing a new 1,000-element array costs about 80 +microseconds there by itself. It costs 270 bytes, for arrays only. It +changed 8 tests and gave 9 type errors, all of which read an internal map. +It can follow in a 1.x release. + +## Consequences + +- Record 0037 already removes the worst case for three of the five adapters + without it: a loop of direct writes no longer takes one snapshot per write + there. +- Open again when the bytes are affordable, or when a measurement on + JavaScriptCore shows a gain. diff --git a/docs/decisions/README.md b/docs/decisions/README.md new file mode 100644 index 00000000..d8f6f145 --- /dev/null +++ b/docs/decisions/README.md @@ -0,0 +1,126 @@ +# Decision records + +This folder holds the decision records of `@codebelt/classy-store`. A record +says what was decided, why, what else was weighed, and what it costs. It +stands on its own: it describes a defect in words, with a short example, and +carries the numbers that were measured for it. + +## Naming and numbering + +- A record is named `NNNN-short-title.md`: four digits, then the title in + lower case with hyphens. +- Numbers are given in order and never reused. Records `0001` to `0046` are + the decisions for 1.0. +- The first line of a record is `# NNNN. Title`, and the title is a + statement of the decision. + +## Sections of a record + +- A list of fields: **Status**, **Date**, **Kind**, **Label**, and + **Changes documented behaviour** (yes or no): whether the decision changes + behaviour that the documentation of the library describes. +- **Context:** what the library did, and why that was a problem. +- **Decision:** what the library does now, exact enough to check the code + against it. +- **Alternatives considered:** each form that was weighed and not taken, and + why. "Final for 1.0" marks a choice that cannot be taken later without + breaking a consumer. +- **Consequences:** what changes for a user, what it costs, what stays + unverified, and what would make the decision worth opening again. + +A decision whose answer is "no change" has a record too, so that the +question is not opened again without a new reason. + +## The life of a record + +- **Accepted:** the decision holds. An accepted record is not rewritten. + A measured figure may be added in a section that exists for it, such as + the table of sizes in record 0004. +- **Superseded by NNNN:** a later record replaces it. The old record stays, + with its status changed and a link to the new one, and the new record names + the one it replaces. + +## Records and `CONSTRAINTS.md` + +A rule of `CONSTRAINTS.md` is loosened or removed only together with a +line in a decision record under `docs/decisions/`. `bun run check:floor` +blocks the change otherwise. Tightening a rule of `CONSTRAINTS.md` needs +nothing. + +Record 0004 is the record for every size budget. The size numbers live in +`budgets.json`, and the size rows of `CONSTRAINTS.md` name that file. A +budget +or a cost limit that rises needs a +line in record 0004; a commit that grows an entry adds a line with the +measured size there. A ceiling changes only in a commit of its own, with +the new number and the reason in that record. + +Three files hold a part of the bar outside `CONSTRAINTS.md`; record 0004 +names them. Every change to one of them, a tightening included, needs a +line in a record that says what changed and why. + +## Kinds and labels + +- **Kind:** bug, simplification, public API, diagnostics, performance, + repository (the workflows and dependencies), constraint (the numbers of + `CONSTRAINTS.md`), or docs. +- **Label:** **Before 1.0** means the change alters the public API or + documented behaviour, so after 1.0 it would be a breaking change. **Can + follow 1.0** means it could ship in a 1.x release without breaking a + consumer. **No change** means the decision keeps what the library does + before 1.0. A split label, such as "Before 1.0 for the rule; the index can + follow 1.0", gives each part of the decision its own label. +- **Before 1.0**, in the text of a record, means the library on the 1.0 + branch before the record's change: 0.11.0 plus the unreleased preparation + for 1.0. + +## All records + +| No. | Title | Kind | Label | +| ---- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------- | -------------------------------------------------------------------------------------------------- | +| 0001 | [A function in a field is a method when it is read through the store, and the object is never changed](0001-a-function-read-through-the-store-is-a-method.md) | public API, bug | Before 1.0 | +| 0002 | [`Object.defineProperty` through a store is a write, and nothing is refused](0002-define-property-through-a-store-is-a-write.md) | bug | Before 1.0 | +| 0003 | [Suspension stays; the walk to a detached parent goes](0003-suspension-stays-and-the-walk-to-a-detached-parent-goes.md) | bug, simplification | Can follow 1.0 | +| 0004 | [The size budgets move once, to a ceiling set for the whole set of 1.0 changes](0004-size-ceilings-for-every-entry.md) | constraint | Before 1.0 | +| 0005 | [A write stores raw values, and there is one node per raw object](0005-raw-values-on-write-and-one-node-per-raw-object.md) | bug | Before 1.0 | +| 0006 | [`includes`, `indexOf` and `lastIndexOf` find the object the caller holds](0006-array-searches-find-the-object-the-caller-holds.md) | bug | Before 1.0 | +| 0007 | [`has` and `ownKeys` traps on the live store, and a missing property is a value](0007-has-and-ownkeys-traps-and-a-missing-property-is-a-value.md) | bug | Before 1.0 | +| 0008 | [A delete that removes nothing is not a change](0008-a-delete-that-removes-nothing-is-not-a-change.md) | bug | Before 1.0 | +| 0009 | [A plain object from another realm is state](0009-a-plain-object-from-another-realm-is-state.md) | bug | Before 1.0 | +| 0010 | [Getters have one kind of dependency, behave the same on both layers, and must not write to their own object](0010-getters-one-kind-of-dependency-and-no-writes.md) | bug, simplification | Before 1.0 | +| 0011 | [Nested class instances stay opt-in, and a base class `ClassyStore` makes arrow-function methods work](0011-nested-instances-stay-opt-in-and-a-classystore-base-class.md) | public API | Before 1.0 for the default of nested instances, which needs no code; the base class is an addition | +| 0012 | [A table per prototype answers "is this key a getter?"](0012-a-table-per-prototype-answers-is-this-key-a-getter.md) | performance | Can follow 1.0 | +| 0013 | [One delivery queue, with a bound](0013-one-delivery-queue-with-a-bound.md) | bug | Before 1.0 | +| 0014 | [A subscriber's error is caught and logged, a rejection too, and the writer is never told](0014-a-subscriber-error-is-caught-and-logged.md) | public API, bug | Before 1.0 | +| 0015 | [A setter is a transaction](0015-a-setter-is-a-transaction.md) | bug | Before 1.0 | +| 0016 | [`batch()` refuses a callback that returns a promise, by its type, and an `async` function when it runs](0016-batch-refuses-a-promise-and-an-async-function.md) | public API | Before 1.0 | +| 0017 | [`subscribe()` stays batched by default](0017-subscribe-stays-batched-by-default.md) | public API | No change | +| 0018 | [Writes outside a method stay allowed, without a warning](0018-writes-outside-a-method-stay-allowed.md) | public API | No change | +| 0019 | [`persist()` restores before it returns when the storage is synchronous](0019-persist-restores-before-it-returns-on-synchronous-storage.md) | public API | Before 1.0 | +| 0020 | [Dead and redundant code goes, in the commit that makes it dead](0020-dead-code-goes-in-the-commit-that-makes-it-dead.md) | simplification | Can follow 1.0 | +| 0021 | [Nothing `persist` cannot use is skipped in silence, and nothing it could not restore is written over](0021-persist-skips-nothing-in-silence-and-overwrites-nothing-it-could-not-restore.md) | bug, diagnostics | Before 1.0 | +| 0022 | [`persist()` validates its options when it is called](0022-persist-validates-its-options.md) | bug | Before 1.0 | +| 0023 | [A restore is all or nothing](0023-a-restore-is-all-or-nothing.md) | bug | Before 1.0 | +| 0024 | [A pending save is written when the page is hidden, and nothing is written back at load but an expiry stamp](0024-a-pending-save-is-flushed-and-only-an-expiry-stamp-is-written-back.md) | bug | Before 1.0 | +| 0025 | [Cross-tab sync ignores an event from another storage area](0025-cross-tab-sync-ignores-another-storage-area.md) | bug | Can follow 1.0 | +| 0026 | [`persist` options stay as they are](0026-persist-options-stay-as-they-are.md) | public API | No change | +| 0027 | [`devtools` sends named entries, travels in time exactly, and is off in production](0027-devtools-named-entries-exact-time-travel-off-in-production.md) | public API, bug | Before 1.0 | +| 0028 | [An edit made in the same tick as `undo()` is recorded](0028-an-edit-in-the-same-tick-as-undo-is-recorded.md) | bug | Before 1.0 | +| 0029 | [`withHistory` restores a function held in an own field, by reference](0029-with-history-restores-a-function-field-by-reference.md) | public API | Before 1.0 | +| 0030 | [Undo and time travel change a nested object in place](0030-undo-and-time-travel-change-a-nested-object-in-place.md) | bug, performance | Before 1.0 | +| 0031 | [`subscribeKey` works without a snapshot of the whole store, and has no selector form in 1.0](0031-subscribe-key-without-a-snapshot-of-the-whole-store.md) | performance | Can follow 1.0 | +| 0032 | [The workflows are hardened now; the release job is split after 1.0](0032-workflows-hardened-now-release-job-split-after-1-0.md) | repository | Can follow 1.0 | +| 0033 | [Dependencies: an exact pin, and an audit step that reports](0033-dependencies-exact-pin-and-an-audit-step.md) | repository | Can follow 1.0 | +| 0034 | [Documentation changes go with the change they describe, and shared limits stay documented](0034-documentation.md) | docs | With each change | +| 0035 | [Every error carries a stable code, and throws the same in every build](0035-every-error-carries-a-stable-code.md) | diagnostics | Before 1.0 | +| 0036 | [One build, and one development-only check in 1.0](0036-one-build-and-one-development-only-check.md) | diagnostics | Before 1.0 for the guard; the check can follow | +| 0037 | [The Vue, Angular and Solid adapters build the snapshot when it is read](0037-vue-angular-and-solid-build-the-snapshot-when-it-is-read.md) | performance | Before 1.0 for Vue; the others can follow | +| 0038 | [Vue: no listener is left by a server render, and the ref is read-only](0038-vue-no-listener-left-by-a-server-render-and-a-read-only-ref.md) | bug, public API | Before 1.0 | +| 0039 | [Angular: a store write inside a `computed` is not lost, and `injectClassyStore` takes an injector](0039-angular-untracked-an-injector-option-and-its-own-context-error.md) | bug, public API | Can follow 1.0 for the fix; the option is an addition | +| 0040 | [The adapter names stay](0040-the-adapter-names-stay.md) | public API | No change | +| 0041 | [React: `prepareStoreForHydration` stays an explicit call, and `isEqual` keeps its name](0041-prepare-store-for-hydration-stays-explicit.md) | public API | No change | +| 0042 | [Reactive collections: one membership rule, an index for snapshots, and native `Map` and `Set` stay opaque](0042-collections-one-membership-rule-and-a-snapshot-index.md) | bug, performance | Before 1.0 for the rule; the index can follow | +| 0043 | [A snapshot carries class getters on one derived prototype per class](0043-class-getters-on-one-derived-prototype-per-class.md) | public API, performance | Before 1.0 | +| 0044 | [A snapshot keeps a cycle](0044-a-snapshot-keeps-a-cycle.md) | bug, public API | Before 1.0 | +| 0045 | [Snapshot types: tuples stay tuples, and a collection snapshot has no mutators](0045-snapshot-types-tuples-and-collections-without-mutators.md) | public API | Before 1.0 | +| 0046 | [A snapshot after one row changes still rebuilds the list](0046-a-snapshot-after-one-row-changes-still-rebuilds-the-list.md) | performance | Can follow 1.0 | diff --git a/examples/angular/src/app/app.component.ts b/examples/angular/src/app/app.component.ts index b4cf12c1..53526ad9 100644 --- a/examples/angular/src/app/app.component.ts +++ b/examples/angular/src/app/app.component.ts @@ -1,5 +1,5 @@ import {ChangeDetectionStrategy, Component, computed} from '@angular/core'; -import {injectStore} from '@codebelt/classy-store/angular'; +import {injectClassyStore} from '@codebelt/classy-store/angular'; import {counterStore, history} from '../store'; @Component({ @@ -53,7 +53,7 @@ import {counterStore, history} from '../store'; `, }) export class AppComponent { - readonly snap = injectStore(counterStore); + readonly snap = injectClassyStore(counterStore); readonly summary = computed( () => `${this.snap().label}: ${this.snap().enabled ? 'enabled' : 'disabled'}`, diff --git a/examples/nextjs/README.md b/examples/nextjs/README.md index 7c0c98a0..26b45705 100644 --- a/examples/nextjs/README.md +++ b/examples/nextjs/README.md @@ -11,11 +11,3 @@ bun dev ``` Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. - -- Realtime Colors (realtimecolors.com) — great for light/dark pairs -- Coolors (coolors.co) — shareable palette URLs -- Tailwind Color Generator (uicolors.app) -- Radix Colors (radix-ui.com/colors) -- Shadcn Themes (ui.shadcn.com/themes) -- Happy Hues (happyhues.co) -- Color Hunt (colorhunt.co) diff --git a/examples/nextjs/package.json b/examples/nextjs/package.json index 22dd25da..6424b56c 100644 --- a/examples/nextjs/package.json +++ b/examples/nextjs/package.json @@ -5,7 +5,8 @@ "scripts": { "dev": "bun --bun next dev", "build": "bun --bun next build", - "start": "bun --bun next start" + "start": "bun --bun next start", + "typecheck": "tsc --noEmit" }, "dependencies": { "@codebelt/classy-store": "workspace:*", diff --git a/examples/nextjs/src/components/features/FeatureMap.tsx b/examples/nextjs/src/components/features/FeatureMap.tsx index 4fdd9006..3606eedd 100644 --- a/examples/nextjs/src/components/features/FeatureMap.tsx +++ b/examples/nextjs/src/components/features/FeatureMap.tsx @@ -215,6 +215,12 @@ const sections: FeatureSection[] = [ {label: 'Shopping / AddItemForm', href: '/shopping'}, ], }, + { + api: 'Transactions', + description: + 'A store method that writes many fields notifies React once, when it returns', + links: [{label: 'Planner / PlannerGrid', href: '/planner'}], + }, { api: 'Cross-store reads', description: 'One component reads from multiple stores', diff --git a/examples/solid/package.json b/examples/solid/package.json index 0adbbe94..11c0e79c 100644 --- a/examples/solid/package.json +++ b/examples/solid/package.json @@ -12,12 +12,12 @@ }, "dependencies": { "@codebelt/classy-store": "workspace:*", - "@solidjs/web": "2.0.0-rc.18", - "solid-js": "2.0.0-rc.18" + "@solidjs/web": "2.0.0", + "solid-js": "2.0.0" }, "devDependencies": { - "@solidjs/vite-plugin": "3.0.0-next.51", - "typescript": "^5.7.0", + "@solidjs/vite-plugin": "3.0.1", + "typescript": "^7.0.2", "vite": "8.3.8" } } diff --git a/examples/solid/tsconfig.json b/examples/solid/tsconfig.json index cfedb9f8..4459435c 100644 --- a/examples/solid/tsconfig.json +++ b/examples/solid/tsconfig.json @@ -17,7 +17,6 @@ "noUnusedLocals": false, "noUnusedParameters": false, "noFallthroughCasesInSwitch": true, - "baseUrl": ".", "paths": { "@codebelt/classy-store": ["../../packages/classy-store/src/index.ts"], "@codebelt/classy-store/solid": [ diff --git a/examples/svelte/package.json b/examples/svelte/package.json index 3132ad3a..d774cd6d 100644 --- a/examples/svelte/package.json +++ b/examples/svelte/package.json @@ -17,7 +17,7 @@ "devDependencies": { "@sveltejs/vite-plugin-svelte": "7.3.1", "svelte-check": "4.7.8", - "typescript": "^5.7.0", + "typescript": "^6.0.3", "vite": "8.3.8" } } diff --git a/examples/svelte/tsconfig.json b/examples/svelte/tsconfig.json index 11488eb9..f36f4513 100644 --- a/examples/svelte/tsconfig.json +++ b/examples/svelte/tsconfig.json @@ -15,7 +15,6 @@ "noUnusedLocals": false, "noUnusedParameters": false, "noFallthroughCasesInSwitch": true, - "baseUrl": ".", "paths": { "@codebelt/classy-store": ["../../packages/classy-store/src/index.ts"], "@codebelt/classy-store/svelte": [ diff --git a/examples/vue/package.json b/examples/vue/package.json index af5c1d18..68c4efa5 100644 --- a/examples/vue/package.json +++ b/examples/vue/package.json @@ -15,7 +15,7 @@ }, "devDependencies": { "@vitejs/plugin-vue": "6.0.11", - "typescript": "^5.7.0", + "typescript": "^6.0.3", "vite": "8.3.8", "vue-tsc": "3.3.14" } diff --git a/examples/vue/tsconfig.app.json b/examples/vue/tsconfig.app.json index 89954675..efc1a689 100644 --- a/examples/vue/tsconfig.app.json +++ b/examples/vue/tsconfig.app.json @@ -17,7 +17,6 @@ "noUnusedParameters": false, "noFallthroughCasesInSwitch": true, "noUncheckedSideEffectImports": true, - "baseUrl": ".", "paths": { "@codebelt/classy-store": ["../../packages/classy-store/src/index.ts"], "@codebelt/classy-store/vue": [ diff --git a/package.json b/package.json index 6e9e10b2..cd12cd41 100644 --- a/package.json +++ b/package.json @@ -3,12 +3,9 @@ "private": true, "workspaces": [ "packages/*", - "examples/*" + "examples/*", + "website" ], - "overrides": { - "@solidjs/babel-plugin": "2.0.0-rc.18", - "@solidjs/compiler": "2.0.0-rc.18" - }, "scripts": { "---------- Dev --------------------------------------------------------": "", "dev": "bun run --filter @codebelt/classy-store dev", @@ -16,7 +13,9 @@ "build": "bun run --filter @codebelt/classy-store build", "---------- Test --------------------------------------------------------": "", "test": "bun run --filter @codebelt/classy-store test", + "test:coverage": "bun run --filter @codebelt/classy-store test:coverage", "test:browser": "bun run --filter @codebelt/classy-store test:browser", + "test:mutation": "bun packages/classy-store/tests/mutation/runMutation.ts", "test:frameworks:compatibility": "bun run build && node packages/classy-store/tests/frameworkCompatibility/runCompatibility.mjs", "test:angular:compatibility": "bun run build && node packages/classy-store/tests/angularCompatibility/runCompatibility.mjs", "test:react:compatibility": "bun run build && node packages/classy-store/tests/compatibility/runCompatibility.mjs", @@ -24,10 +23,17 @@ "test:react:memory": "bun run build && bun packages/classy-store/tests/memory/runMemory.ts", "test:react:next": "bun run build && node packages/classy-store/tests/next/runNext.mjs", "benchmark:react": "bun run build && bun packages/classy-store/tests/performance/runPerformance.ts", + "benchmark:react:compare": "bun packages/classy-store/tests/performance/baseline.ts compare", + "test:react:memory:compare": "bun packages/classy-store/tests/memory/baseline.ts compare", + "benchmark:core": "bun run build && bun packages/classy-store/tests/benchmark/runCoreBenchmark.mjs", + "benchmark:core:node": "bun run build && node packages/classy-store/tests/benchmark/runCoreBenchmark.mjs", + "size": "bun run build && bun packages/classy-store/tests/size/runSize.ts", "---------- Lint --------------------------------------------------------": "", "lint": "biome check", "lint:fix": "biome check --write", - "typecheck": "bun run --filter @codebelt/classy-store typecheck && bun run --filter @codebelt/classy-store typecheck:scoping && bun run --filter classy-store-svelte-example check:integration && bun run --filter classy-store-vue-example check:integration && bun run --filter classy-store-solid-example typecheck && bun run --filter classy-store-solid-example check:integration && bun run --filter classy-store-angular-example typecheck && bun run --filter classy-store-angular-example check:integration", + "check:package": "bun run build && bun run --filter @codebelt/classy-store check:package", + "check:floor": "node scripts/floor-guard.mjs", + "typecheck": "bun run --filter @codebelt/classy-store typecheck && bun run --filter @codebelt/classy-store typecheck:scoping && bun run --filter classy-store-svelte-example check:integration && bun run --filter classy-store-vue-example check:integration && bun run --filter classy-store-solid-example typecheck && bun run --filter classy-store-solid-example check:integration && bun run --filter classy-store-angular-example typecheck && bun run --filter classy-store-angular-example check:integration && bun run --filter classy-store-nextjs-example typecheck && bun run --filter classy-store-docs types:check", "---------- Release (Changesets) ----------------------------------------": "", "changeset": "changeset", "changeset:add": "changeset add", @@ -42,8 +48,8 @@ "solid:dev": "cd examples/solid && bun run dev", "angular:dev": "cd examples/angular && bun run start", "---------- Docs (Fumadocs) ------------------------------------------": "", - "docs:dev": "bun run --cwd website dev", - "docs:build": "bun run --cwd website build:pages", + "docs:dev": "bun run build && bun run --cwd website dev", + "docs:build": "bun run build && bun run --cwd website build:pages", "docs:test": "bun run --cwd website test:pages", "---------- CI / Helper ------------------------------------------------": "", "checkall": "bun run lint:fix && bun run test && bun run typecheck", diff --git a/packages/classy-store/CHANGELOG.md b/packages/classy-store/CHANGELOG.md index 8907a092..cd71f6e8 100644 --- a/packages/classy-store/CHANGELOG.md +++ b/packages/classy-store/CHANGELOG.md @@ -1,235 +1 @@ # @codebelt/classy-store - -## 0.11.0 - -### Minor Changes - -- [`eb7f585`](https://github.com/codeBelt/classy-store/commit/eb7f585c14b71987e82d3ccd72fe5c1edfbb27bb) Thanks [@codeBelt](https://github.com/codeBelt)! - Release 0.11.0 with the MIT license and support for stores shared between ESM and CommonJS callers. The Solid adapter stays in preview at exactly `solid-js@2.0.0-rc.18`. The Angular adapter supports stable `@angular/core@^22.0.0` releases, with the development framework pinned to `22.2.6`. - - Preserve edits made by synchronous subscribers to other fields during hydration and cross-tab restores, including when a field is missing from older stored data. Sparse-array selectors using `shallowEqual` now distinguish a hole from an element containing `undefined`. See the [0.11.0 release notes](https://codebelt.github.io/classy-store/docs/UPGRADING_0_11). - - Keep explicit store subscriptions scoped to their own subtree, follow child subscriptions when they change owners, and reclaim dead owner links on read-only shared data. A clear issued during restore remains effective until the next local edit. Dense array comparisons short-circuit on the first mismatch. - -### Patch Changes - -- [`b0ff991`](https://github.com/codeBelt/classy-store/commit/b0ff9917e51e8610e312d1ba1d4a1b9888e0d844) Thanks [@codeBelt](https://github.com/codeBelt)! - Keep retained rows reactive after reordering or filtering and invalidate every owner of a shared object. Preserve JSON `__proto__` keys as snapshot data, evaluate object-literal getters on snapshots, and track nested writes from class setters. Save local subscriber edits made during persistence hydration. - -- [`b9d51fa`](https://github.com/codeBelt/classy-store/commit/b9d51fae65eae800973f2a25c09ca57f295643f5) Thanks [@codeBelt](https://github.com/codeBelt)! - Preserve sparse array holes and trailing length in snapshots and React's auto-tracked reads. Distinguish arrays from records in `shallowEqual`, including an empty array and an empty record. - -- [`1545a53`](https://github.com/codeBelt/classy-store/commit/1545a5327a17fd5b8f92fdd6c03af9da6d24273d) Thanks [@codeBelt](https://github.com/codeBelt)! - Share store identity, snapshot caches, and React hydration preparation across ESM and CommonJS entry points from the same package installation. A CommonJS utility such as `withHistory` can now subscribe to an ESM-created store, and an ESM utility can use a CommonJS-created store. - -## 0.10.0 - -### Minor Changes - -- [#42](https://github.com/codeBelt/classy-store/pull/42) [`68bb261`](https://github.com/codeBelt/classy-store/commit/68bb261f9d127159ec7fb98e20add4d049fc6b55) Thanks [@codeBelt](https://github.com/codeBelt)! - Bound optional framework peers to supported stable majors: React `^18.0.0 || ^19.0.0`, Vue `^3.2.0`, and Svelte `^4.0.0 || ^5.0.0`. Future majors are no longer accepted automatically. Development dependency versions remain unchanged. - - Fix the Vue adapter's public declaration to return `Ref>` backed by a shallow ref. Vue 3.2.0 does not export the newer `ShallowRef` type; the stable type preserves readonly snapshot inference at the advertised minimum without changing runtime behavior. - - Validate packed consumers at React 18.0.0/19.0.0, Vue 3.2.0, and Svelte 4.0.0/5.0.0 using existing focused tests. Add the minimums to CI coverage and document Svelte 4's native deferred `$:` computations versus Svelte 5's immediate `$derived` reads. Store snapshots still update synchronously in the adapters, and ordinary core subscriptions remain batched. - -- [#42](https://github.com/codeBelt/classy-store/pull/42) [`68bb261`](https://github.com/codeBelt/classy-store/commit/68bb261f9d127159ec7fb98e20add4d049fc6b55) Thanks [@codeBelt](https://github.com/codeBelt)! - Support all stable Angular 22 releases with the optional `@angular/core` peer set to `^22.0.0` and update `injectStore` signals synchronously while preserving Angular's native rendering schedule and ordinary core subscription batching. Ignore notifications during teardown and release each subscription with its Angular lifecycle. - - This removes support for Angular 21 and earlier. Use aligned Angular runtime/compiler packages from a stable Angular 22 release and a compatible TypeScript 6.0 toolchain. Development dependencies and the example remain pinned to 22.2.3. The `/angular` import path and `injectStore(store)` signature are unchanged; imperative signal and computed reads now reflect writes immediately. - - Add zoneless input, computed, keyed-list, and cleanup regressions, an updated Angular example, and migration documentation. Validate packed consumers with aligned Angular 22.0.0 and 22.2.3 packages and run the shared focused browser tests for both versions in CI. - -## 0.9.0 - -### Minor Changes - -- [#40](https://github.com/codeBelt/classy-store/pull/40) [`3e2281d`](https://github.com/codeBelt/classy-store/commit/3e2281ddf1202c4742afdd72b0f5065c7d81d237) Thanks [@codeBelt](https://github.com/codeBelt)! - Migrate the `/solid` adapter to Solid 2.0.0-rc.18 only. Solid 1 is no longer - supported. Pin the exact release candidate; browser apps should also use - `@solidjs/web@2.0.0-rc.18` and Solid 2's compiler tooling. The public - `useClassyStore(store): () => Snapshot` API is unchanged. - - Forward store notifications synchronously to Solid while preserving Solid 2's - native scheduling and ordinary core subscription batching. Solid's `flush()` - now applies pending store-backed computed values and DOM updates. - - Require a live Solid owner before subscribing, and release subscriptions on owner - disposal, including disposal during notification. Add real-component regressions - for inputs, computed values, keyed lists, timing, and cleanup; update the example, - TypeScript checks, CI, and public integration guide. - -## 0.8.2 - -### Patch Changes - -- [#38](https://github.com/codeBelt/classy-store/pull/38) [`dfe1228`](https://github.com/codeBelt/classy-store/commit/dfe1228d63472387f002295f1f62bd6160f83be0) Thanks [@codeBelt](https://github.com/codeBelt)! - Update Vue snapshot refs synchronously so computed values are immediately current - and one `await nextTick()` waits for the resulting DOM update. Vue rendering and - ordinary core subscriptions still batch. - - Require an active Vue effect scope for `useClassyStore()` and stop delivery when - that scope is disposed, including disposal during notification. Call the hook in - `setup()` / ` +

{$snap.count}

`; +writeFileSync( + 'svelte-out/Counter.server.js', + compile(component, {generate: 'server', filename: 'Counter.svelte'}).js.code, +); + +// Runes in a module: fromStore() over the adapter, and a direct createSubscriber binding. +const runes = `import {fromStore, derived, get} from 'svelte/store'; +import {createSubscriber} from 'svelte/reactivity'; +import {flushSync} from 'svelte'; +import {toSvelteStore} from '${SRC}/frameworks/svelte/svelte'; +import {subscribe, getInternal} from '${SRC}/core/core'; +import {snapshot} from '${SRC}/snapshot/snapshot'; + +const listeners = (store) => getInternal(store).syncListeners.size; + +// Ten lines: what a rune-native binding would be. +function classyState(store) { + const track = createSubscriber((update) => subscribe(store, update, {sync: true})); + return { + get current() { + track(); + return snapshot(store); + }, + }; +} + +export async function run(store) { + const viaFromStore = fromStore(toSvelteStore(store)); + const direct = classyState(store); + const log = {fromStore: [], direct: [], derivedCount: [], derivedUser: 0}; + const count = $derived(direct.current.count); + const user = $derived(direct.current.user); + const stop = $effect.root(() => { + $effect(() => { log.fromStore.push(viaFromStore.current.count); }); + $effect(() => { log.direct.push(direct.current.count); }); + $effect(() => { log.derivedCount.push(count); }); + $effect(() => { user; log.derivedUser++; }); + }); + flushSync(); + console.log('mounted: listeners', listeners(store), JSON.stringify(log)); + store.other++; + flushSync(); + store.other++; + flushSync(); + console.log('two unrelated writes:', JSON.stringify(log)); + store.count++; + console.log('read outside an effect straight after a write: fromStore', viaFromStore.current.count, 'direct', direct.current.count); + flushSync(); + console.log('after count++:', JSON.stringify(log)); + stop(); + console.log('effects destroyed, same tick: listeners', listeners(store)); + await new Promise((resolve) => setTimeout(resolve, 0)); + console.log('effects destroyed, next task: listeners', listeners(store)); + // svelte/store helpers accept the adapter's readable. + const doubled = derived(toSvelteStore(store), ($s) => $s.count * 2); + console.log('derived + get:', get(doubled), 'listeners after get:', listeners(store)); +}`; +writeFileSync( + 'svelte-out/runes.svelte.js', + compileModule(runes, {generate: 'client', filename: 'runes.svelte.js'}).js + .code, +); +console.log('built'); +``` + +Output: + +```text +built +``` + +### `svelte-server.mjs` + +Run: `bun svelte-server.mjs` + +```js +// Svelte 5 server rendering with $store. Run: bun svelte-server.mjs +import {render} from 'svelte/server'; +import Counter from './svelte-out/Counter.server.js'; +import { + createClassyStore, + getInternal, +} from '/packages/classy-store/src/core/core'; + +const store = createClassyStore({count: 0}); +for (let request = 1; request <= 3; request++) { + const {body} = render(Counter, {props: {store}}); + console.log( + `request ${request}: ${body.replace(//g, '')} -> sync listeners: ${getInternal(store).syncListeners.size}`, + ); +} +``` + +Output: + +```text +request 1:

0

-> sync listeners: 0 +request 2:

0

-> sync listeners: 0 +request 3:

0

-> sync listeners: 0 +``` + +### `svelte-client.mjs` + +Run: `bun --conditions browser svelte-client.mjs` + +```js +// Runes over the adapter, on Svelte's client runtime. Run: bun --conditions browser svelte-client.mjs +import {run} from './svelte-out/runes.svelte.js'; +import {createClassyStore} from '/packages/classy-store/src/core/core'; +await run(createClassyStore({count: 0, other: 0, user: {name: 'Ada'}})); +``` + +Output: + +```text +mounted: listeners 2 {"fromStore":[0],"direct":[0],"derivedCount":[0],"derivedUser":1} +two unrelated writes: {"fromStore":[0,0,0],"direct":[0,0,0],"derivedCount":[0],"derivedUser":1} +read outside an effect straight after a write: fromStore 1 direct 1 +after count++: {"fromStore":[0,0,0,1],"direct":[0,0,0,1],"derivedCount":[0,1],"derivedUser":1} +effects destroyed, same tick: listeners 2 +effects destroyed, next task: listeners 0 +derived + get: 2 listeners after get: 0 +``` + +### `svelte-compile.mjs` + +Run: `bun svelte-compile.mjs (compiled code omitted from the output)` + +```js +// Compile the component from website/content/docs/SVELTE.md with the installed Svelte 5 compiler. +import { + compile, + VERSION, +} from '/packages/classy-store/node_modules/svelte/src/compiler/index.js'; + +const guide = ` + + +`; +const renamed = guide.replaceAll('state', 'snap'); + +for (const [label, source] of [ + ['guide (variable named state)', guide], + ['renamed to snap', renamed], +]) { + for (const generate of ['client', 'server']) { + try { + const result = compile(source, {generate, filename: 'Counter.svelte'}); + console.log( + label, + generate, + 'OK; warnings:', + result.warnings.map((w) => `${w.code}: ${w.message}`), + ); + if (label.startsWith('renamed')) console.log(result.js.code); + } catch (error) { + console.log(label, generate, 'ERROR', error.code, '-', error.message); + } + } +} +console.log('svelte', VERSION); +``` + +Output: + +```text +guide (variable named state) client OK; warnings: [] +guide (variable named state) server OK; warnings: [] +renamed to snap client OK; warnings: [] +renamed to snap server OK; warnings: [] +svelte 5.57.3 +``` + +### `svelte-compile-runes.mjs` + +Run: `bun svelte-compile-runes.mjs` + +```js +// The guide's component once the user adds a rune (runes mode), as most Svelte 5 components do. +import { + compile, + compileModule, +} from '/packages/classy-store/node_modules/svelte/src/compiler/index.js'; + +const cases = { + 'state + $props': ` +`, + 'state + $derived': ` +`, + 'state + own $state rune': ` +`, + 'snap + $derived (runes mode)': ` +`, +}; +for (const [label, source] of Object.entries(cases)) { + try { + const result = compile(source, { + generate: 'client', + filename: 'Counter.svelte', + }); + console.log( + label, + '=> OK; warnings:', + result.warnings.map((w) => `${w.code}: ${w.message}`), + ); + } catch (error) { + console.log(label, '=> ERROR', error.code, '-', error.message); + } +} + +// $store syntax in a .svelte.ts module +try { + compileModule( + `import {toSvelteStore} from '@codebelt/classy-store/svelte'; +import {counter} from './counter'; +const snap = toSvelteStore(counter); +export function read() { return $snap.count; }`, + {filename: 'shared.svelte.js'}, + ); + console.log('module with $snap => OK'); +} catch (error) { + console.log('module with $snap => ERROR', error.code, '-', error.message); +} +``` + +Output: + +```text +state + $props => OK; warnings: [] +state + $derived => OK; warnings: [] +state + own $state rune => OK; warnings: [ "store_rune_conflict: It looks like you're using the `$state` rune, but there is a local binding called `state`. Referencing a local variable with a `$` prefix will create a store subscription. Please rename `state` to avoid the ambiguity\nhttps://svelte.dev/e/store_rune_conflict" ] +snap + $derived (runes mode) => OK; warnings: [] +module with $snap => ERROR store_invalid_subscription_module - Cannot reference store value outside a `.svelte` file +https://svelte.dev/e/store_invalid_subscription_module +``` + +### `types-check.ts` + +Run: `node_modules/.bin/tsc --project tsconfig.types.json`. Exit 0, no output: the `@ts-expect-error` lines are errors as expected, and the rest compiles. + +```ts +// Type-level checks. Run: node_modules/.bin/tsc --project tsconfig.types.json +import { + computed, + type MaybeRefOrGetter, + type Ref, + type ShallowRef, + toValue, + unref, + watch, +} from 'vue'; +import {derived, fromStore, get, type Readable} from 'svelte/store'; +import type {Snapshot} from '/packages/classy-store/src/types'; +import {useClassyStore} from '/packages/classy-store/src/frameworks/vue/vue'; +import {toSvelteStore} from '/packages/classy-store/src/frameworks/svelte/svelte'; + +type Counter = {count: number; nested: {label: string}}; +declare const store: Counter; + +// Today: the write compiles. +const today = useClassyStore(store); +today.value = {count: 1, nested: {label: 'x'}}; + +// Candidate A: works on the whole peer range (Ref exists in 3.2.0). +declare const a: Readonly>>; +// @ts-expect-error value is read-only +a.value = {count: 1, nested: {label: 'x'}}; +// Candidate B: Vue's own shape for useTemplateRef(); ShallowRef is not exported by 3.2.0. +declare const b: Readonly>>; +// @ts-expect-error value is read-only +b.value = {count: 1, nested: {label: 'x'}}; + +// A read-only ref is still accepted wherever Vue reads a ref. +const n1: number = unref(a).count; +const n2: number = toValue(b).count; +const asSource: MaybeRefOrGetter> = a; +const asRef: Ref> = b; +watch(a, (value) => void value.count); +watch(b, (value) => void value.count); +const doubled = computed(() => a.value.count * 2); +void [n1, n2, asSource, asRef, doubled]; + +// Svelte: the adapter's own interface is accepted by svelte/store. +const readable: Readable> = toSvelteStore(store); +const viaRunes: {readonly current: Snapshot} = fromStore( + toSvelteStore(store), +); +const count: number = get(derived(toSvelteStore(store), ($s) => $s.count)); +void [readable, viaRunes, count]; +``` + +### `eager-vs-lazy.ts` + +Run: `bun eager-vs-lazy.ts` + +```ts +// Cost of building a snapshot in the listener (what four adapters do) against building it at the read. +// Run: bun eager-vs-lazy.ts +import {effectScope} from 'vue'; +import { + batch, + createClassyStore, +} from '/packages/classy-store/src/core/core'; +import {useClassyStore} from '/packages/classy-store/src/frameworks/vue/vue'; +import {useClassyStoreSketch} from './vue-sketch'; + +const ROWS = 2000; +const makeStore = () => + createClassyStore({ + rows: Array.from({length: ROWS}, (_, id) => ({id, done: false})), + }); + +function measure( + label: string, + bind: ( + store: ReturnType, + ) => {value: {rows: readonly {done: boolean}[]}} | undefined, + write: (store: ReturnType) => void, +) { + const times: number[] = []; + for (let round = 0; round < 7; round++) { + const store = makeStore(); + const scope = effectScope(); + const state = scope.run(() => bind(store)); + const start = performance.now(); + write(store); + // One read afterwards, as a render would do. + if (state && !state.value.rows[ROWS - 1].done) throw new Error('stale'); + times.push(performance.now() - start); + scope.stop(); + } + times.sort((a, b) => a - b); + console.log(`${label.padEnd(58)} median ${times[3].toFixed(2)} ms`); +} + +const directWrites = (store: ReturnType) => { + for (const row of store.rows) row.done = true; +}; +const batched = (store: ReturnType) => + batch(() => directWrites(store)); + +measure(`${ROWS} direct writes, no adapter`, () => undefined, directWrites); +measure( + `${ROWS} direct writes, Vue adapter (snapshot per notification)`, + (store) => useClassyStore(store), + directWrites, +); +measure( + `${ROWS} direct writes, sketch (snapshot at the read)`, + (store) => useClassyStoreSketch(store), + directWrites, +); +measure( + `${ROWS} writes inside batch(), Vue adapter`, + (store) => useClassyStore(store), + batched, +); +``` + +Output: + +```text +2000 direct writes, no adapter median 1.12 ms +2000 direct writes, Vue adapter (snapshot per notification) median 632.79 ms +2000 direct writes, sketch (snapshot at the read) median 2.21 ms +2000 writes inside batch(), Vue adapter median 2.02 ms +``` + +### `direct-writes-others.ts` + +Run: `bun direct-writes-others.ts` + +```ts +// The loop of direct writes with the Angular and Svelte adapters attached, and with a bare sync subscriber. +// Run: bun direct-writes-others.ts (Solid needs its client runtime: see solid-direct-writes.ts) +import {Injector, runInInjectionContext} from '@angular/core'; +import { + createClassyStore, + subscribe, +} from '/packages/classy-store/src/core/core'; +import {snapshot} from '/packages/classy-store/src/snapshot/snapshot'; +import {injectClassyStore} from '/packages/classy-store/src/frameworks/angular/angular'; +import {toSvelteStore} from '/packages/classy-store/src/frameworks/svelte/svelte'; + +const ROWS = 2000; +const makeStore = () => + createClassyStore({ + rows: Array.from({length: ROWS}, (_, id) => ({id, done: false})), + }); +type Store = ReturnType; + +function measure(label: string, attach: (store: Store) => () => void) { + const times: number[] = []; + for (let round = 0; round < 5; round++) { + const store = makeStore(); + const detach = attach(store); + const start = performance.now(); + for (const row of store.rows) row.done = true; + times.push(performance.now() - start); + detach(); + } + times.sort((a, b) => a - b); + console.log(`${label.padEnd(46)} median ${times[2].toFixed(2)} ms`); +} + +measure('no subscriber', () => () => {}); +measure('sync subscriber that does nothing', (store) => + subscribe(store, () => {}, {sync: true}), +); +measure('sync subscriber that calls snapshot()', (store) => + subscribe(store, () => void snapshot(store), {sync: true}), +); +measure('batched subscriber that calls snapshot()', (store) => + subscribe(store, () => void snapshot(store)), +); +measure('Angular adapter', (store) => { + const injector = Injector.create({providers: []}); + runInInjectionContext(injector, () => injectClassyStore(store)); + return () => injector.destroy(); +}); +measure('Svelte adapter, one subscriber', (store) => + toSvelteStore(store).subscribe(() => {}), +); +``` + +Output: + +```text +no subscriber median 2.51 ms +sync subscriber that does nothing median 1.13 ms +sync subscriber that calls snapshot() median 649.47 ms +batched subscriber that calls snapshot() median 1.03 ms +Angular adapter median 626.00 ms +Svelte adapter, one subscriber median 646.90 ms +``` + +### `react-direct-writes.ts` + +Run: `bun react-direct-writes.ts` + +```ts +// The same loop of direct writes with a mounted React consumer. Run: bun react-direct-writes.ts +import {GlobalRegistrator} from '@happy-dom/global-registrator'; +GlobalRegistrator.register(); +(globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean}).IS_REACT_ACT_ENVIRONMENT = + true; +const {createElement, act} = await import('react'); +const {createRoot} = await import('react-dom/client'); +const {batch, createClassyStore} = await import( + '/packages/classy-store/src/core/core' +); +const {useClassyStore} = await import( + '/packages/classy-store/src/frameworks/react/react' +); + +const ROWS = 2000; +const makeStore = () => + createClassyStore({ + rows: Array.from({length: ROWS}, (_, id) => ({id, done: false})), + }); +type Store = ReturnType; + +async function measure( + label: string, + mode: 'selector' | 'auto' | 'none', + write: (store: Store) => void, +) { + const times: number[] = []; + for (let round = 0; round < 5; round++) { + const store = makeStore(); + const host = document.createElement('div'); + const root = createRoot(host); + function View() { + if (mode === 'selector') + return createElement( + 'p', + null, + useClassyStore( + store, + (state) => state.rows.filter((row) => row.done).length, + ), + ); + const state = useClassyStore(store); + return createElement( + 'p', + null, + state.rows.filter((row) => row.done).length, + ); + } + if (mode !== 'none') + await act(async () => root.render(createElement(View))); + const start = performance.now(); + await act(async () => write(store)); + times.push(performance.now() - start); + if (mode !== 'none' && host.textContent !== String(ROWS)) + throw new Error(`stale: ${host.textContent}`); + await act(async () => root.unmount()); + } + times.sort((a, b) => a - b); + console.log(`${label.padEnd(52)} median ${times[2].toFixed(2)} ms`); +} + +const directWrites = (store: Store) => { + for (const row of store.rows) row.done = true; +}; +await measure(`${ROWS} direct writes, no consumer`, 'none', directWrites); +await measure( + `${ROWS} direct writes, selector hook mounted`, + 'selector', + directWrites, +); +await measure( + `${ROWS} direct writes, auto-tracked hook mounted`, + 'auto', + directWrites, +); +await measure( + `${ROWS} writes inside batch(), selector hook mounted`, + 'selector', + (store) => batch(() => directWrites(store)), +); +await GlobalRegistrator.unregister(); +``` + +Output: + +```text +2000 direct writes, no consumer median 1.26 ms +2000 direct writes, selector hook mounted median 763.86 ms +2000 direct writes, auto-tracked hook mounted median 655.26 ms +2000 writes inside batch(), selector hook mounted median 2.63 ms +``` diff --git a/review/stage-2/immer.md b/review/stage-2/immer.md new file mode 100644 index 00000000..cdaa15f4 --- /dev/null +++ b/review/stage-2/immer.md @@ -0,0 +1,2476 @@ +# Stage 2: Immer + +Stage 2 of the pre-1.0 review, 2026-11-19. Read-only: nothing in the +repository was changed apart from this file. + +## Library, version and files read + +- **Library:** Immer, `https://github.com/immerjs/immer`. +- **Version:** 11.2.10, the latest stable tag and the npm `latest` tag on + 2026-11-18. +- **Commit:** `16589b9c437a28433ceaf4072d5ab125287cd46a` (2026-11-10), tag + `v11.2.10`, cloned into the scratch folder and read there. npm's `gitHead` + for `immer@11.2.10` is the same commit. +- **Files read**, under `src/`: `core/proxy.ts`, `core/finalize.ts`, + `core/immerClass.ts`, `core/scope.ts`, `core/current.ts`, `utils/common.ts`, + `utils/errors.ts`, `utils/env.ts` and `plugins/mapset.ts` whole; + `types/types-external.ts` lines 1 to 110. +- **Ours:** `snapshot/snapshot.ts`, `utils/internal/internal.ts`, + `utils/cloneSnapshot/cloneSnapshot.ts`, `types.ts`, and in `core/core.ts` + `isImmutableValue`, `linkChild` and the proxy handler (lines 330 to 525). +- **Ported tests** ran on Bun 1.4.4 and, where marked, Node 24.21.0, against + `immer@11.2.10` from npm (its development build) and our source imported by + absolute path. For Node, our source was bundled with `bun build` into the + scratch folder first. Type-level port checked with TypeScript 7.0.2. + +Line numbers for Immer refer to that commit. Line numbers for ours refer to +`release/1.0` at `12fe57d`. Machine: Apple M1 Max, not otherwise quiet, so +timings are best-of-seven and good to about 20 per cent. + +## Summary + +Immer and our snapshot layer solve the same problem from opposite ends. Immer +copies on write: a draft proxy makes a shallow copy of each object the first +time it is written, and `finalize` swaps finished copies into their parents. +We copy on read: the live store is mutated in place, and `snapshot()` rebuilds +every node whose version changed. Both end with a frozen tree in which +unchanged subtrees keep their identity. On the ports, the two agree on which +objects are new and which are kept: after one of 1,000 rows changes, the root, +the array and the row are new, and the other 999 rows and every other branch +keep their identity. + +The findings that matter most: + +1. **The cost of a snapshot after one row changed (finding 1).** Immer is no + cheaper as long as it freezes: its deep freeze visits every element of + every new array, which costs as much as our rebuild (66 against 56 + microseconds for 1,000 rows on Node; 138 against 119 on Bun). The floor is + set by the engine. On Bun, freezing a new 1,000-element array costs about + 96 microseconds on its own, so nothing that returns a frozen array can be + much faster. On Node, freezing is nearly free and 90 per cent of our cost is + the per-element cache lookup; a rebuild that copies the previous snapshot + array and recomputes only the changed indices measured 6 microseconds, nine + times faster. +2. **Immer's proxies have a decoy target (finding 2).** A draft's Proxy target + is Immer's own state object, not the user's object, so the user's object can + be frozen, sealed or hold non-configurable properties without any Proxy + invariant applying. Ours targets the raw object, which is the root of stage + 1 findings 46 and 49 and of the read-only special case in `linkChild`. +3. **Immer refuses what it cannot represent, with a numbered error (findings 3, + 4 and 5).** `Object.defineProperty`, `Object.setPrototypeOf` (which also + blocks `__proto__` through `Object.assign`), and a named property written + to an array all throw in development. In each case we accept the operation + and then disagree with ourselves: the store and its snapshot diverge, or no + subscriber is told. + +Where Immer is weaker, the port shows it plainly: it flattens an own getter to +a value at the time of the copy, so the result reports a stale `double` (2 for +`n = 5`); it drops non-enumerable properties by default and leaves symbol-keyed +and non-enumerable objects unfrozen; it freezes the caller's own objects in +place; and a base that refers to itself produces a result whose `self` points +to the old base. Our behaviour is the one to keep in each case ("Where ours is +better"). + +## How the two designs differ + +- **Immer copies on write.** `createProxyProxy` (`core/proxy.ts:57-105`) makes + a revocable Proxy whose target is a state record holding `base_` (the + user's object) and `copy_` (null until the first write). The `get` trap + (`proxy.ts:111-162`) reads `latest(state)`, which is `copy_ ?? base_`, and + creates a child draft lazily, only for an object that is still the base's + own value at that key. The `set` trap (`proxy.ts:169-218`) returns early when + the value is unchanged, otherwise calls `prepareCopy` (`proxy.ts:356-366`), + which makes one shallow copy, and `markChanged` (`proxy.ts:347-354`), which + marks every ancestor modified. An unmodified draft finalizes to its base + (`core/finalize.ts:78-81`), which is the whole of Immer's structural sharing: + what was never written is never copied. +- **We copy on read.** The store proxy targets the raw object + (`core/core.ts:405`). A write bumps versions up to the root. `snapshot()` + (`snapshot/snapshot.ts:235-288`) returns the cached frozen object when the + version matches (`:241-244`) and otherwise rebuilds the node: an array by + visiting every element (`:255-261`, through `mapOwnArrayElements`, + `utils/internal/internal.ts:18-40`), an object by visiting every own key + (`:264-275`). Each child's own cache answers in O(1), so unchanged subtrees + are shared, but every element of a changed array is visited. +- **Freezing.** Immer freezes the finished result deeply once per `produce` + (`finalize.ts:100-105`, called at `:54`), with `freeze(value, true)` + (`utils/common.ts:266-289`). The walk stops at anything already frozen + (`common.ts:268`), visits only enumerable string keys (`common.ts:278-287`, + citing Immer issue 590), and freezes in place whatever it reaches, including + objects that came from the caller. Freezing can be turned off + (`setAutoFreeze`, `core/immerClass.ts:48`, `:175-181`). We freeze each + snapshot node we build (`snapshot.ts:282`) and never freeze the caller's + objects. + +## Findings + +### 1. The cost of a new snapshot after one row changed + +- **What they do.** `produce` copies only written objects (`prepareCopy`, + `proxy.ts:356-366`; an array is copied with `slice`, `common.ts:220`). Then + `maybeFreeze` deep-freezes the result (`finalize.ts:100-105`), and + `freeze(value, true)` calls itself on every element of every array it + reaches (`common.ts:281-287`), each call ending at `isFrozen` for an + unchanged row. +- **What we do.** `createSnapshotRecursive` (`snapshot.ts:255-261`) visits + every element of a changed array; for each object element `snapshotValue` + (`:183-193`) looks the child up in `childInternals` by `String(index)`, then + `snapshotCache` by target, then compares versions. Then it freezes the new + array (`:282`). +- **Difference in behaviour.** Measured, ports 1 and 1d: + + | 1,000 rows, write one, take the next result | Node 24 | Bun 1.4.4 | + | ------------------------------------------- | ------------ | -------------- | + | Immer, auto-freeze (default) | 66.3 µs | 138.5 µs | + | Immer, no freeze | 1.2 µs | 1.6 µs | + | By hand: `slice`, replace one row, freeze | 25.7 µs | 97.6 µs | + | Copy previous frozen array by index, freeze | 6.0 µs | 96.2 µs | + | The same without freezing the array | 6.3 µs | 2.3 µs | + | Ours | 55.7–56.3 µs | 118.5–120.2 µs | + | Ours, cached snapshot (nothing changed) | 39 ns | 22 ns | + | Immer, recipe that only reads one row | 26.2 µs | 16.7 µs | + + At 10,000 rows every figure except the cached snapshot grows about ten + times on Node and fifteen to twenty times on Bun, where freezing a larger + array costs more per element (port 1b), so all of them are at least in + proportion to the number of rows. Three things follow. First, Immer with freezing on + costs the same as we do, so stage 1 finding 2 is not a defect of our design + against Immer's. Second, on Bun `Object.freeze` of a new 1,000-element array + costs about 94 microseconds by itself (row 4 against row 5): that is 80 per + cent of our cost and cannot be removed while snapshots are frozen arrays. + Third, on Node freezing is nearly free and our per-element lookup is about + 50 of the 56 microseconds. On V8, `slice` of a frozen array is slow (about + 27 nanoseconds per element, port 1b), and copying it by index is not (5). + Immer's "reads one row" case costs 16 to 26 microseconds because the get + trap calls `prepareCopy` to cache the child draft (`proxy.ts:154-159`), + which copies the array even though nothing is written; the result is still + the base. +- **Proposal: adapt.** Take Immer's idea of knowing which keys changed. When a + child's version bump reaches its parent, record the child's key in a + per-node "changed since the last snapshot" set. When that set is small, + rebuild an array snapshot by copying the previous snapshot array by index and + recomputing only the recorded indices; fall back to today's walk when the + set is large, when the array's length changed, or when there is no previous + snapshot. Expected effect on Node: 56 to about 6 microseconds for 1,000 + rows. On Bun the gain is small because freezing dominates. Do not adopt an + off switch for freezing: frozen snapshots are part of the contract + (`CLAUDE.md`, "frozen objects are values"), and Immer's own numbers show + freezing is the price of that contract on JavaScriptCore. +- **Kind:** performance. +- **Cost:** `snapshot.ts` and the version propagation in `core.ts` or + `ownership.ts`. Not breaking. Moderate risk: the dirty set must be cleared + exactly when a snapshot is cached and must survive detach and resume; the + invariant and fuzz tests from stage 1 cover the result. The 6 microseconds + is the floor measured by port 1d, not a measured implementation. + +### 2. A decoy Proxy target keeps the user's object out of Proxy invariants + +- **What they do.** `createProxyProxy` uses the state record as the Proxy + target (`proxy.ts:88-99`; an array draft's target is `[state]` so that + `Array.isArray` stays true). Every trap reads from `latest(state)`. Because + the target never has the user's properties, a frozen base, a sealed base, or + a non-writable non-configurable property places no constraint on what a trap + may return. `getOwnPropertyDescriptor` (`proxy.ts:236-246`) reports every + property as writable and configurable. A frozen base is drafted and copied + like any other (`shallowCopy` turns non-writable into writable, + `common.ts:232-235`). +- **What we do.** The store proxy targets the raw object (`core.ts:405`). The + engine therefore checks every `get` result against the raw object's + descriptor. `linkChild` must leave a read-only property's object unproxied + (`core.ts:369-374`, `isReadOnly` at `:345-347`), and freezing the raw object + behind the store's back makes a read throw. +- **Difference in behaviour.** Port 2. A base frozen during the recipe and then + written through the draft gives a new result in Immer; ours throws on read + (stage 1 finding 46): + + ```text + immer: base frozen during the recipe, then written through the draft: 2 + ours: read after the raw object was frozen: THROWS TypeError: Proxy handler's 'get' result of a non-configurable and non-writable property should be the same value as the target's property + ``` + + For a non-writable, non-configurable property holding an object, Immer + writes inside it through a draft and leaves the base untouched; ours writes + the shared raw object, notifies nobody, changes a snapshot already taken, + and the snapshot's copy of it is not frozen (stage 1 finding 49). + + The decoy has a cost Immer pays too: `Object.freeze(draft)` throws an engine + error about a property `parent_` of Immer's state record, which means + nothing to the caller (port 2, last section). +- **Proposal: adapt, as a stage 3 design question, not a 1.0 blocker.** A decoy + target would remove findings 46 and 49 (second half), and the read-only + special case in `linkChild`. It also forces the proxy to answer every + operation itself: `has`, `ownKeys`, `getOwnPropertyDescriptor`, + `getPrototypeOf`, `defineProperty`, `preventExtensions`, `isExtensible`, + which overlaps with stage 1 findings 1, 30, 45 and 50 and with the Vue + report's finding on `has` and `ownKeys`. `Object.freeze(store)` and a frozen + store root, which work today, would need explicit support. The smaller + alternative is to document that the raw object must not be frozen or + redefined once a store holds it. +- **Kind:** bug (46, 49), simplification. +- **Cost:** `core.ts` proxy handler; every trap. Not breaking for ordinary use; + breaking for code that relies on `Object.isFrozen(store)` after freezing the + raw object. High risk; a design change. + +### 3. `defineProperty` and `setPrototypeOf` are refused with a clear error + +- **What they do.** The `defineProperty` trap throws error 11, "Object.defineProperty() cannot be used on an Immer draft" + (`proxy.ts:247-249`, text in `utils/errors.ts`). The `setPrototypeOf` trap + throws error 12 (`proxy.ts:253-255`). Because `Object.assign` with an own + `__proto__` key calls the `[[Set]]` of `__proto__`, which calls + `setPrototypeOf`, the same trap also blocks that prototype swap. +- **What we do.** The `defineProperty` trap (`core.ts:502-513`) applies any + definition to the raw object and only handles the case that makes a + property read-only. There is no `setPrototypeOf` trap. +- **Difference in behaviour.** Port 5: + + ```text + immer: on a draft: THROWS Error: [Immer] Object.defineProperty() cannot be used on an Immer draft + ours: store reads: 2 + ours: subscriber calls: 0 + ours: snapshot has the property: false + immer: Object.assign(draft, JSON.parse('{"__proto__": ...}')): THROWS Error: [Immer] Object.setPrototypeOf() cannot be used on an Immer draft + ours: Object.assign(store, JSON.parse('{"__proto__": ...}')): [true, true] + ``` + +- **Proposal: adopt, with one exception.** `Object.freeze(store)` reaches the + `defineProperty` trap once per property with a descriptor that has no + `value`, `get` or `set` (only `writable: false` and `configurable: false`), + so that call can keep today's behaviour and every definition that carries a + `value`, `get` or `set` can throw. Add a `setPrototypeOf` trap that throws. + Both close stage 1 findings 1, 45, 47 (the prototype half), 48 and 71 with + an error instead of a silent disagreement. The security agent's report on + `persist` should say whether stored JSON can reach the `__proto__` path; the + trap closes it either way. +- **Kind:** diagnostics, bug. +- **Cost:** `core.ts`, two traps. Breaking for code that defines properties on + a store, which today half-works. Low risk. + +### 4. Arrays carry indices and `length` only + +- **What they do.** In development, writing a property of an array draft that + is neither an index nor `length` throws error 14, and deleting one throws + error 13 (`proxy.ts:274-288`). Copies are made with `slice` + (`common.ts:220`), which keeps only the elements, so a named or symbol-keyed + property of the base array is gone from any result in which the array + changed. +- **What we do.** A named or symbol-keyed property of an array is reactive on + the store and missing from its snapshot, because `mapOwnArrayElements` + copies only indices (`internal.ts:18-40`, used at `snapshot.ts:257`). Stage 1 + finding 49. +- **Difference in behaviour.** Port 4: Immer throws on the write + (`Immer only supports setting array indices and the 'length' property`) and + drops the property after a `push`; ours accepts the write, the store reads + `"y"` and the snapshot reads `undefined`. A symbol write on an Immer array + draft fails with an unrelated `TypeError` from `parseInt`, so Immer's check + is not complete either. +- **Proposal: adopt the rule, as a development error.** Carrying named + properties into array snapshots would cost a `Reflect.ownKeys` of the whole + array on every rebuild, which is the cost finding 1 tries to remove. Rejecting + the write in development, as Immer does, makes the limit visible for nothing + at run time in production. Document it in either case. +- **Kind:** diagnostics, docs. +- **Cost:** `core.ts` `set` and `deleteProperty` traps, behind the + development check the diagnostics work (API question 8) introduces. Breaking + only for code that relies on a value nobody can see in a snapshot. Low risk. + +### 5. A delete that removes nothing is not a change + +- **What they do.** `deleteProperty` (`proxy.ts:219-233`) marks the draft + changed only when the key exists on the base; otherwise it forgets any + pending assignment and leaves the draft unmodified, so `produce` returns the + base. +- **What we do.** `deleteProperty` (`core.ts:515-524`) notifies whenever + `Reflect.deleteProperty` returns `true`, which it also does for a key that + is not there. Stage 1 finding 29. +- **Difference in behaviour.** Port 5: `produce(base, d => { delete d.missing })` + returns `base`; ours calls the subscriber once and replaces the snapshot with + an equal one. +- **Proposal: adopt.** Return `true` without notifying when + `!Object.hasOwn(_target, prop)`. An inherited property cannot be deleted + through the object either, so the same test covers it. +- **Kind:** bug. +- **Cost:** `core.ts`, one line. Not breaking. Low risk. + +### 6. A plain object from another realm is opaque to us + +- **What they do.** `isPlainObject` (`common.ts:61-78`) accepts a null + prototype, `Object.prototype`, a prototype whose own `constructor` is + `Object`, and otherwise compares `Function.prototype.toString` of the + prototype's constructor with that of `Object`, cached per constructor in a + `WeakMap` (`:59`, `:71-75`). An object made in an iframe or a Node `vm` + context therefore counts as plain. +- **What we do.** `isPlainObject` (`internal.ts:54-60`) accepts only a null + prototype or this realm's `Object.prototype`. `canProxy` (`:70-82`) + therefore treats a foreign plain object as an opaque value. Foreign arrays + pass, because `Array.isArray` works across realms. +- **Difference in behaviour.** Port 9 (Node and Bun, same output). Immer drafts + and copies the foreign object. Ours hands out the raw object, a write inside + it notifies nobody and changes a snapshot already taken. In a foreign array, + a `push` notifies but a write to a foreign row does not. +- **Proposal: adopt.** The case is real for data from an iframe, a worker + library that builds objects in a `vm` context, or a test runner with its own + realm, and the failure is silent. Immer's per-constructor cache keeps the + check cheap; the extra work happens only when the prototype is not this + realm's. +- **Kind:** bug. +- **Cost:** `internal.ts`, about ten lines. It changes the result of `canProxy` + for such objects, which `persist` and `history` also use, in the direction + of treating them as data. Low risk. + +### 7. Frozen means frozen to the bottom, or the store cannot see inside + +- **What they do.** `finalize` returns a frozen value untouched + (`finalize.ts:65`); `handleValue` skips it (`:286-294`); `freeze` stops at it + (`common.ts:268`). But a frozen base can still be drafted, so a write below a + frozen object in a recipe produces a new result and leaves the base alone. +- **What we do.** `isImmutableValue` (`core.ts:337-342`) treats any frozen + object as a value and `linkChild` (`core.ts:368`) leaves it unproxied, as + `CLAUDE.md` says. +- **Difference in behaviour.** Port 2: for `{config: Object.freeze({inner})}` + with `inner` not frozen, Immer gives a new result for + `draft.config.inner.n = 2`. Ours lets the write through to the raw `inner`, + calls no subscriber, and the snapshot taken before the write now reads 2: + a snapshot, documented as deeply frozen, changed. Immer has the same hole on + its side: an object below one that was already frozen is not frozen in the + result (`object below an already frozen one is frozen: false`). +- **Proposal: adapt, as documentation.** Say that "frozen objects are values" + means the whole value must be frozen, and that a shallowly frozen object's + mutable contents are shared with every snapshot. A development check that + deep-scans a frozen object on first sight would cost what `isImmutableValue` + caches to avoid; not worth it. +- **Kind:** docs. +- **Cost:** `CLAUDE.md` and the API reference. Not breaking. No risk. + +### 8. Frozen collections in a result throw a named error + +- **What they do.** `freeze` replaces `set`, `add`, `clear` and `delete` on a + frozen `Map` or `Set` with a function that throws error 2, "This object has + been frozen and should not be mutated" (`common.ts:269-276`, `:291-297`). The + types say the same thing: `Immutable` turns `Map` into `ReadonlyMap` and + `Set` into `ReadonlySet` (`types/types-external.ts:78-81`), so `set` does not + compile. The override is an own property, so + `Map.prototype.set.call(result.m, ...)` still writes (port 7). +- **What we do.** A snapshot of a `ReactiveMap` is a frozen instance whose + inherited `set` fails on a frozen backing array with an engine message. The + type keeps `set` (stage 1 finding 16). +- **Difference in behaviour.** Port 7: `snapshot.m.set()` throws + `TypeError: Attempted to assign to readonly property.` on Bun, which does not + name the store, the collection or the cause. Immer's message names the + cause. Ours cannot be bypassed: the frozen backing array refuses every + write. +- **Proposal: adopt the message and the types.** Have the mutators of + `ReactiveMap` and `ReactiveSet` check whether the instance is a snapshot and + throw an error that says so; map `ReactiveMap` to a read-only interface + in `Snapshot`. Keep the frozen backing array, which is sounder than + Immer's override. +- **Kind:** diagnostics, API design. +- **Cost:** `collections.ts`, `types.ts`. Breaking at the type level only for + code that calls a mutator on a snapshot, which already throws. Low risk. + +### 9. Map and Set drafts are subclasses of the native classes + +- **What they do.** With the opt-in plugin (`enableMapSet`, global and + permanent), a `Map` is drafted as a `DraftMap extends Map` + (`plugins/mapset.ts:35`) and a `Set` as a `DraftSet extends Set` (`:215`), + each carrying its state in an own field instead of being wrapped in a Proxy. + The draft passes `instanceof Map`, and the result is a native `Map` or `Set`. + A map copy is `new Map(base)` (`:208-213`), so a changed map costs one + native copy. A set has no keys to address its members by, so the first + read of a draft set's contents drafts every draftable member + (`prepareSetCopy`, `:334-348`), and `has` answers for both a member and its + draft (`:242-253`). Without the plugin, a `Map` nested in the base is + ignored until it is read, and reading it throws error 0, which names the + missing plugin (port 7, `noplugin`). +- **What we do.** `ReactiveMap` and `ReactiveSet` (`collections.ts:50`, `:205`) + are classes of their own, backed by an array, marked `PROXYABLE`. A native + `Map` in a store is opaque. +- **Difference in behaviour.** Port 7. Immer's result map is a native `Map`; + our snapshot of a `reactiveMap` is not `instanceof Map`. Both keep the + unchanged values' identity. Changing one value of a 1,000-entry map and + taking the next result: Immer 21 µs, ours 127 µs (Bun only; our collections + entry was not bundled for Node). A native `Map` in our store takes a write + to a value and a `set()` with no notification, and a snapshot taken earlier + reads both. +- **Proposal: no change for 1.0, input to API question 5.** Immer's subclass + approach works because a draft lives for one recipe and the result is a + fresh native copy. A store lives for the application's lifetime, and a + frozen native `Map` is still writable through `Map.prototype.set`, so our + snapshots could not be native maps without losing immutability. Making + `ReactiveMap` extend `Map`, so that `instanceof Map` is true on the store, + is possible but needs every inherited method overridden. The 6 times speed + difference comes from our array-backed snapshot visiting every entry + (finding 1 applies). +- **Kind:** API design, performance. +- **Cost:** none proposed. + +### 10. Tuples survive Immer's types + +- **What they do.** `Immutable` (`types/types-external.ts:74-86`) has no + array branch: everything that is not a leaf, `Map` or `Set` goes through one + homomorphic mapped type (`:85`), which keeps tuples and their element + positions. `WritableDraft` (`:31-37`) singles out plain arrays only to make + them mutable. `produce` returns the base type. +- **What we do.** `Snapshot` (`types.ts:38-44`) has an array branch, + `T extends Array ? ReadonlyArray>`, which turns a tuple + into an array of the union of its element types. Stage 1 finding 14. +- **Difference in behaviour.** Port 8 (type level, passes with TypeScript + 7.0.2). `Immutable<[string, number]>` is `readonly [string, number]`; ours is + `readonly (string | number)[]`. A copy of our type with the array branch + removed (`Snapshot2` in the port) gives `readonly [string, number]` for the + tuple and the same `readonly {readonly id: number}[]` as today for an array. +- **Proposal: adopt.** Remove the array branch; the mapped type handles arrays, + read-only arrays and tuples. +- **Kind:** API design. +- **Cost:** `types.ts`, one branch. Not breaking for arrays; a tuple's snapshot + type becomes more precise, which can break code that relied on the union. + The type tests from stage 1 pin the current type. Low risk. + +### 11. A cycle is neither detected nor resolved by Immer + +- **What they do.** Nothing detects cycles: error 5, "Immer forbids circular + references", is still in `utils/errors.ts` but nothing in `src/` raises it. + A draft assigned into itself is resolved by the finalization callbacks + (`finalize.ts:217-237`), so the result refers to itself. A base that already + refers to itself is copied once; the copy's `self` still points to the old + base. +- **What we do.** `createSnapshotRecursive` throws "circular reference detected + in snapshot" when it meets a target already in progress (`snapshot.ts:246-250`). + Stage 1 finding 8: the write that creates the cycle succeeds and notifies. +- **Difference in behaviour.** Port 6. Immer: `next.self === base` after + `draft.n = 2` on a self-referencing base, so `next.self.n` is the old value, + silently. Ours: the snapshot throws. +- **Proposal: reject Immer's behaviour.** A silent stale reference is worse + than our error. If cycles are to be supported, our snapshot could register + the new snapshot object before visiting its children and return it when the + cycle comes back, freezing it last; that is reasoning from reading, not + tried. Otherwise the error should be raised at the write that creates the + cycle, in development, so it points at the cause. +- **Kind:** bug, diagnostics. +- **Cost:** `snapshot.ts`, and the snapshot cache for a node that is its own + ancestor. Moderate risk. + +## Where ours is better + +Each is measured in the ports. + +- **Own getters.** Immer's copy reads an own accessor once and stores its value + (`common.ts:239-245` in strict mode; the default copy is an object spread, + which does the same, `common.ts:251-253`). In port 4, after `draft.n = 5`, + the result's `double` is 2, and so is `draft.double` inside the recipe. Our + snapshot keeps it as a memoized accessor and answers 10. +- **Symbols and non-enumerable properties.** Immer's default copy drops + non-enumerable properties, and its deep freeze skips them and symbol keys, + so in port 4 an object under a symbol is mutable after `produce`. Ours keeps + both and freezes both. +- **The caller's objects.** Immer freezes in place every object it reaches in + the result, including untouched branches of the base and objects assigned in + the recipe (port 2: `untouched branch of the base, frozen in place: true`). + We copy and never freeze the caller's objects. +- **Class instances.** Immer refuses a class instance without `immerable` at + the root (error 1) and leaves one nested in the base unfrozen and writable, + so a write in a recipe changes the base (port 3), exactly as our snapshot + shares an unmarked instance. Our root may be any class instance, which is + the library's purpose. Immer finds its marker through `value[DRAFTABLE]` or + `value.constructor[DRAFTABLE]` (`common.ts:51-52`), which reads the instance, + so an own field named `constructor` can change the answer; `canProxy` reads + the constructor from the prototype on purpose (`internal.ts:73-78`). + Neither library supports `#private` fields on a proxied or copied instance. + +## Stage 1 findings with a counterpart + +| Stage 1 | What Immer does there | +| ------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | +| 1 | `Object.defineProperty` on a draft throws error 11 (finding 3). | +| 2 | Same cost in proportion to the rows while auto-freeze is on; 1.2 µs with it off (finding 1). | +| 8 | No detection; a self-referencing base yields a result that points to the old base (finding 11). | +| 12 | A draft `Set` answers `has` for both a member and its draft (`mapset.ts:242-253`); the result holds the new copy, not the original. | +| 14 | `Immutable` keeps tuples (finding 10). | +| 15 | No counterpart: a draft's state is behind a symbol on a subclass field, not in the public type. | +| 16 | `Immutable` gives `ReadonlyMap` and `ReadonlySet`; frozen collections throw error 2 (finding 8). | +| 25 | No counterpart: there is no long-lived store, each `produce` starts from the base it is given. | +| 29 | A delete of a missing key leaves the result equal to the base (finding 5). | +| 30 | `has` and `ownKeys` read the latest copy, so `Object.keys(draft)` and `in` are right after a delete (port 5). | +| 31 | Prototype getters run with the result or the draft as `this`, so they see its keys (port 5: `[1, 1]`; ours `[2, 2, 0]`). | +| 40 | Prototype getters are not memoized: each read runs again on frozen data, so nothing is shared between results. | +| 45, 71 | `defineProperty` refused (finding 3). | +| 46 | Not possible: the Proxy target is a decoy (finding 2). | +| 47, 48 | `setPrototypeOf` refused, which also blocks `__proto__` through `Object.assign` (finding 3). | +| 49 | Named array properties refused in development and dropped from copies (finding 4); read-only properties made writable in the copy (finding 2). | +| 50 | The same: `getOwnPropertyDescriptor(draft, key).value` is the base object, and a write through it changes the base (port 5). | +| 70 | Results keep the input's key order; prototype getters stay on the prototype and own getters become data in place. | + +## The API questions + +1. Synchronous notification by default: no position (Immer has no + subscriptions). +2. Writes outside a store method and `batch()`: no position. A recipe is + Immer's only unit of change, which is the closest it comes to a + transaction. +3. **Should snapshot getters stay enumerable own accessors?** Immer's results + have no own accessors: a prototype getter stays on the prototype and runs + on each read, unmemoized (port 3: own keys of a class result are `["n"]`), + and an own getter on a plain object is turned into a data property at copy + time, which makes it stale (port 4). Immer's view is that a result is data + and computed values live on the class. That favours installing memoized + getters where the class has them, on a prototype, and keeping only data as + own enumerable keys, so `Object.keys(snapshot)` and spreading give data. + One way, from reading only: one derived prototype per class, created once + and cached, inheriting from the class's prototype, whose accessors look up + the per-snapshot cache. `instanceof` and `constructor` keep working, and + the per-snapshot `installMemoizedGetters` walk (`snapshot.ts:196-221`) goes + away. `Object.getPrototypeOf(snapshot) === Class.prototype` would become + false. +4. Arrow-function methods and `#private` fields: no position. Port 3 shows + that `#private` fails on Immer drafts and copies too. +5. **Should native `Map` and `Set` be reactive directly?** Immer drafts native + `Map` and `Set` directly, by substituting a subclass instance that carries + its own state, behind an opt-in plugin. That works because the draft is + thrown away after one recipe and the result is a native copy (finding 9). + For a store, which keeps its object and must hand out immutable snapshots, + the result side does not carry over: a frozen native `Map` can still be + written through `Map.prototype.set`. Immer therefore supports keeping + `reactiveMap` and `reactiveSet` as the snapshot representation, while + showing that the live side can be a subclass of the native class. +6. **Opt-in or opt-out for nested class instances?** Opt-in. Immer drafts only + plain objects, arrays, `Map`, `Set` and classes marked with `immerable`, + either as a static or as an instance field (`common.ts:46-56`). An unmarked + instance is a value: Immer neither copies nor freezes it. That is the same + default as `PROXYABLE`. +7. Entry points and adapter names: no position. +8. **Development diagnostics.** Immer's pattern is a numbered error table that + exists only in the development build (`utils/errors.ts`, guarded by + `process.env.NODE_ENV`), with production throwing the bare number and a + link. Its errors cover the operations it cannot represent: findings 3 and 4 + above, revoked drafts, a recipe that both returns and modifies, and a + missing plugin that is named in the message. + +## Verified by running, and only read + +**Verified by running code** (ports below): identity after a one-row write; +all timings; frozen input, nested frozen objects, freezing the raw object, a +read-only property holding an object; what auto-freeze freezes; class instances +with and without the marker, subclasses, `#private`; own getters, symbols, +non-enumerable properties, named array properties, sparse arrays; +`defineProperty`, `setPrototypeOf`, `__proto__` through `Object.assign`; a +delete of a missing key; keys and `in` after a delete; descriptor values; +revoked drafts; cycles; `Map` and `Set` drafts with and without the plugin; +another realm; the tuple types. + +**Only read:** that error 5 is never raised (a search of `src/`); the reason +reading one row through a draft costs as much as a write (`proxy.ts:154-159`); +the dirty-key rebuild in finding 1 beyond its measured floor; the derived +prototype in question 3; supporting cycles in our snapshot (finding 11). +`plugins/patches.ts` and the array-methods plugin were not read. + +## Appendix: ported tests + +Each port is a file in the scratch folder `stage-2-immer/ports/`, with the +shared helpers in `harness.mjs` (`show` prints a value or the error thrown; +`time` returns the best of seven rounds in nanoseconds per call). `.ts` ports +ran with `bun `; `.mjs` ports ran with both `node` and `bun` against a +bundle of our source. + +### Shared helpers + +`harness.mjs`: + +```js +// Shared helpers for the ported tests. +export function section(title) { + console.log(`\n## ${title}`); +} + +/** Print the value of an expression, or the error it throws. */ +export function show(label, run) { + try { + const value = run(); + console.log(`${label}: ${format(value)}`); + } catch (error) { + console.log( + `${label}: THROWS ${error?.constructor?.name}: ${error?.message}`, + ); + } +} + +function format(value) { + if (typeof value === 'string') return JSON.stringify(value); + if (typeof value === 'symbol') return value.toString(); + if (Array.isArray(value)) return `[${value.map(format).join(', ')}]`; + if (value && typeof value === 'object') { + try { + return JSON.stringify(value); + } catch { + return String(value); + } + } + return String(value); +} + +/** Best of `rounds`, in nanoseconds per call. */ +export function time(run, {rounds = 7, sampleMs = 60} = {}) { + // Warm up. + let iterations = 1; + for (;;) { + const start = performance.now(); + for (let index = 0; index < iterations; index++) run(index); + const elapsed = performance.now() - start; + if (elapsed >= sampleMs) break; + iterations *= 2; + } + let best = Number.POSITIVE_INFINITY; + let counter = iterations; + for (let round = 0; round < rounds; round++) { + const start = performance.now(); + for (let index = 0; index < iterations; index++) run(counter++); + const elapsed = performance.now() - start; + best = Math.min(best, (elapsed * 1e6) / iterations); + } + return best; +} + +export function ns(value) { + if (value >= 1e6) return `${(value / 1e6).toFixed(2)} ms`; + if (value >= 1e3) return `${(value / 1e3).toFixed(2)} us`; + return `${value.toFixed(1)} ns`; +} +``` + +### Port 1: one of 1,000 rows, identity and time + +`p1-rows.mjs`: + +```js +// Port 1: change one of N rows, time the next result, and see which objects +// keep their identity. Runs on Bun and on Node. +import {Immer, produce} from 'immer'; +import {createClassyStore, snapshot} from './classy.mjs'; +import {ns, section, show, time} from './harness.mjs'; + +const makeRows = (count) => + Array.from({length: count}, (_, index) => ({ + id: index, + value: index, + done: false, + })); +const makeState = (count) => ({ + count: 0, + label: 'a', + nested: {deep: {value: 0}}, + rows: makeRows(count), +}); + +section('identity after one row is written (1,000 rows)'); +{ + const base = makeState(1000); + const next = produce(base, (draft) => { + draft.rows[500].value = -1; + }); + let kept = 0; + for (let index = 0; index < 1000; index++) { + if (next.rows[index] === base.rows[index]) kept++; + } + show('immer: root is new', () => next !== base); + show('immer: rows array is new', () => next.rows !== base.rows); + show('immer: rows that kept identity', () => kept); + show('immer: nested kept identity', () => next.nested === base.nested); + show('immer: base row untouched', () => base.rows[500].value); + show( + 'immer: no write gives the base back', + () => produce(next, () => {}) === next, + ); + show( + 'immer: writing the value a field holds gives the base back', + () => + produce(next, (draft) => { + draft.count = 0; + }) === next, + ); + show( + 'immer: a read of one row gives the base back', + () => + produce(next, (draft) => { + void draft.rows[3].value; + }) === next, + ); + show( + 'immer: write then write back gives the base back', + () => + produce(next, (draft) => { + draft.count = 1; + draft.count = 0; + }) === next, + ); + + const store = createClassyStore(makeState(1000)); + const before = snapshot(store); + store.rows[500].value = -1; + const after = snapshot(store); + kept = 0; + for (let index = 0; index < 1000; index++) { + if (after.rows[index] === before.rows[index]) kept++; + } + show('ours: root is new', () => after !== before); + show('ours: rows array is new', () => after.rows !== before.rows); + show('ours: rows that kept identity', () => kept); + show('ours: nested kept identity', () => after.nested === before.nested); + show('ours: write then write back gives the same snapshot', () => { + const one = snapshot(store); + store.count = 1; + store.count = 0; + return snapshot(store) === one; + }); +} + +section('time to write one row and get the next immutable result'); +// Every timed write is a real change: `tick` is a value no row has held. +let tick = 0; +const frozen = new Immer({autoFreeze: true}); +const unfrozen = new Immer({autoFreeze: false}); +for (const count of [100, 1000, 10000]) { + const report = (label, value) => + console.log( + `${count} rows | ${label}: ${ns(value)} (${(value / count).toFixed(1)} ns/row)`, + ); + + let state = frozen.produce(makeState(count), () => {}); + report( + 'immer, auto-freeze', + time((index) => { + state = frozen.produce(state, (draft) => { + draft.rows[index % count].value = --tick; + }); + }), + ); + + let loose = makeState(count); + report( + 'immer, no freeze', + time((index) => { + loose = unfrozen.produce(loose, (draft) => { + draft.rows[index % count].value = --tick; + }); + }), + ); + + // The floor: copy by hand what has to change, freeze the three new objects. + let manual = makeState(count); + report( + 'by hand, frozen', + time((index) => { + const rows = manual.rows.slice(); + const at = index % count; + rows[at] = Object.freeze({...rows[at], value: --tick}); + manual = Object.freeze({...manual, rows: Object.freeze(rows)}); + }), + ); + + let bare = makeState(count); + report( + 'by hand, not frozen', + time((index) => { + const rows = bare.rows.slice(); + const at = index % count; + rows[at] = {...rows[at], value: --tick}; + bare = {...bare, rows}; + }), + ); + + const store = createClassyStore(makeState(count)); + snapshot(store); + let sum = 0; + report( + 'ours', + time((index) => { + store.rows[index % count].value = --tick; + sum += snapshot(store).rows.length; + }), + ); + if (sum < 0) console.log(sum); +} + +section('time for a result nothing changed in (1,000 rows)'); +{ + const state = frozen.produce(makeState(1000), () => {}); + const store = createClassyStore(makeState(1000)); + snapshot(store); + let sum = 0; + console.log( + `immer, empty recipe: ${ns( + time(() => { + sum += frozen.produce(state, () => {}).rows.length; + }), + )}`, + ); + console.log( + `immer, recipe reads one row: ${ns( + time((index) => { + sum += frozen.produce(state, (draft) => { + void draft.rows[index % 1000].value; + }).rows.length; + }), + )}`, + ); + console.log( + `ours, cached snapshot: ${ns( + time(() => { + sum += snapshot(store).rows.length; + }), + )}`, + ); + if (sum < 0) console.log(sum); +} +``` + +Output (Node 24): + +```text + +## identity after one row is written (1,000 rows) +immer: root is new: true +immer: rows array is new: true +immer: rows that kept identity: 999 +immer: nested kept identity: true +immer: base row untouched: 500 +immer: no write gives the base back: true +immer: writing the value a field holds gives the base back: true +immer: a read of one row gives the base back: true +immer: write then write back gives the base back: false +ours: root is new: true +ours: rows array is new: true +ours: rows that kept identity: 999 +ours: nested kept identity: true +ours: write then write back gives the same snapshot: false + +## time to write one row and get the next immutable result +100 rows | immer, auto-freeze: 7.79 us (77.9 ns/row) +100 rows | immer, no freeze: 1.00 us (10.0 ns/row) +100 rows | by hand, frozen: 2.74 us (27.4 ns/row) +100 rows | by hand, not frozen: 48.9 ns (0.5 ns/row) +100 rows | ours: 7.83 us (78.3 ns/row) +1000 rows | immer, auto-freeze: 66.30 us (66.3 ns/row) +1000 rows | immer, no freeze: 1.22 us (1.2 ns/row) +1000 rows | by hand, frozen: 25.65 us (25.7 ns/row) +1000 rows | by hand, not frozen: 253.8 ns (0.3 ns/row) +1000 rows | ours: 55.74 us (55.7 ns/row) +10000 rows | immer, auto-freeze: 631.37 us (63.1 ns/row) +10000 rows | immer, no freeze: 3.84 us (0.4 ns/row) +10000 rows | by hand, frozen: 250.28 us (25.0 ns/row) +10000 rows | by hand, not frozen: 2.83 us (0.3 ns/row) +10000 rows | ours: 529.15 us (52.9 ns/row) + +## time for a result nothing changed in (1,000 rows) +immer, empty recipe: 222.9 ns +immer, recipe reads one row: 26.20 us +ours, cached snapshot: 39.3 ns +``` + +Output (Bun 1.4.4): + +```text + +## identity after one row is written (1,000 rows) +immer: root is new: true +immer: rows array is new: true +immer: rows that kept identity: 999 +immer: nested kept identity: true +immer: base row untouched: 500 +immer: no write gives the base back: true +immer: writing the value a field holds gives the base back: true +immer: a read of one row gives the base back: true +immer: write then write back gives the base back: false +ours: root is new: true +ours: rows array is new: true +ours: rows that kept identity: 999 +ours: nested kept identity: true +ours: write then write back gives the same snapshot: false + +## time to write one row and get the next immutable result +100 rows | immer, auto-freeze: 13.21 us (132.1 ns/row) +100 rows | immer, no freeze: 917.2 ns (9.2 ns/row) +100 rows | by hand, frozen: 8.39 us (83.9 ns/row) +100 rows | by hand, not frozen: 102.7 ns (1.0 ns/row) +100 rows | ours: 12.20 us (122.0 ns/row) +1000 rows | immer, auto-freeze: 138.48 us (138.5 ns/row) +1000 rows | immer, no freeze: 1.60 us (1.6 ns/row) +1000 rows | by hand, frozen: 97.64 us (97.6 ns/row) +1000 rows | by hand, not frozen: 869.2 ns (0.9 ns/row) +1000 rows | ours: 118.54 us (118.5 ns/row) +10000 rows | immer, auto-freeze: 2.30 ms (230.3 ns/row) +10000 rows | immer, no freeze: 6.41 us (0.6 ns/row) +10000 rows | by hand, frozen: 1.96 ms (196.4 ns/row) +10000 rows | by hand, not frozen: 5.99 us (0.6 ns/row) +10000 rows | ours: 2.34 ms (234.1 ns/row) + +## time for a result nothing changed in (1,000 rows) +immer, empty recipe: 247.8 ns +immer, recipe reads one row: 16.72 us +ours, cached snapshot: 22.0 ns +``` + +### Port 1b: what freezing an array costs on each engine + +`p1b-freeze-cost.mjs`: + +```js +// What freezing an array costs on each engine, and what it does to later +// reads and copies. One call per size; no long loops, so a slow case shows. +const sizes = [100, 1000, 10000, 100000]; + +function once(run) { + const start = performance.now(); + const result = run(); + return [(performance.now() - start) * 1e6, result]; +} + +function median(run, repeats = 15) { + const all = []; + for (let index = 0; index < repeats; index++) all.push(once(run)[0]); + all.sort((a, b) => a - b); + return all[repeats >> 1]; +} + +for (const size of sizes) { + const rows = Array.from({length: size}, (_, index) => ({id: index})); + const copy = median(() => rows.slice()); + const freeze = median(() => Object.freeze(rows.slice())); + const frozen = Object.freeze(rows.slice()); + const isFrozen = median(() => Object.isFrozen(frozen)); + const sliceFrozen = median(() => frozen.slice()); + const readPlain = median(() => { + let sum = 0; + for (let index = 0; index < size; index++) sum += rows[index].id; + return sum; + }); + const readFrozen = median(() => { + let sum = 0; + for (let index = 0; index < size; index++) sum += frozen[index].id; + return sum; + }); + const forEachFrozen = median(() => { + let sum = 0; + frozen.forEach((row) => { + sum += row.id; + }); + return sum; + }); + const per = (value) => `${(value / size).toFixed(1)} ns/el`; + console.log( + `${size}: slice ${per(copy)} | slice+freeze ${per(freeze)} | isFrozen(frozen) ${per(isFrozen)}` + + ` | slice of frozen ${per(sliceFrozen)} | indexed read plain ${per(readPlain)} | indexed read frozen ${per(readFrozen)}` + + ` | forEach frozen ${per(forEachFrozen)}`, + ); +} +``` + +Output (Node 24): + +```text +100: slice 3.8 ns/el | slice+freeze 3.3 ns/el | isFrozen(frozen) 2.5 ns/el | slice of frozen 29.6 ns/el | indexed read plain 22.5 ns/el | indexed read frozen 22.1 ns/el | forEach frozen 60.8 ns/el +1000: slice 0.8 ns/el | slice+freeze 1.1 ns/el | isFrozen(frozen) 0.2 ns/el | slice of frozen 27.7 ns/el | indexed read plain 14.0 ns/el | indexed read frozen 5.3 ns/el | forEach frozen 25.9 ns/el +10000: slice 0.2 ns/el | slice+freeze 0.3 ns/el | isFrozen(frozen) 0.0 ns/el | slice of frozen 25.7 ns/el | indexed read plain 1.2 ns/el | indexed read frozen 4.8 ns/el | forEach frozen 25.5 ns/el +100000: slice 0.7 ns/el | slice+freeze 0.6 ns/el | isFrozen(frozen) 0.0 ns/el | slice of frozen 26.3 ns/el | indexed read plain 1.0 ns/el | indexed read frozen 4.7 ns/el | forEach frozen 27.0 ns/el +``` + +Output (Bun 1.4.4): + +```text +100: slice 1.2 ns/el | slice+freeze 84.6 ns/el | isFrozen(frozen) 41.7 ns/el | slice of frozen 14.6 ns/el | indexed read plain 54.6 ns/el | indexed read frozen 65.4 ns/el | forEach frozen 85.0 ns/el +1000: slice 0.3 ns/el | slice+freeze 98.0 ns/el | isFrozen(frozen) 48.3 ns/el | slice of frozen 16.4 ns/el | indexed read plain 7.2 ns/el | indexed read frozen 14.0 ns/el | forEach frozen 23.0 ns/el +10000: slice 0.7 ns/el | slice+freeze 183.6 ns/el | isFrozen(frozen) 130.0 ns/el | slice of frozen 15.2 ns/el | indexed read plain 2.3 ns/el | indexed read frozen 13.2 ns/el | forEach frozen 21.3 ns/el +100000: slice 5.8 ns/el | slice+freeze 223.8 ns/el | isFrozen(frozen) 152.3 ns/el | slice of frozen 16.7 ns/el | indexed read plain 1.3 ns/el | indexed read frozen 16.6 ns/el | forEach frozen 23.8 ns/el +``` + +### Port 1d: the floor for a rebuild that recomputes only changed indices + +`p1d-dirty-copy.mjs`: + +```js +// The floor for a "dirty keys" snapshot of an array: copy the previous frozen +// snapshot array by index, replace the one changed element, freeze the copy. +// Compared with what ours does today on the same array. +import {createClassyStore, snapshot} from './classy.mjs'; +import {ns, time} from './harness.mjs'; + +for (const count of [1000, 10000]) { + const rows = Array.from({length: count}, (_, index) => + Object.freeze({id: index, value: index}), + ); + let prev = Object.freeze(rows.slice()); + let tick = 0; + const copyLoop = time((index) => { + const next = new Array(count); + for (let i = 0; i < count; i++) next[i] = prev[i]; + const at = index % count; + next[at] = Object.freeze({...prev[at], value: --tick}); + prev = Object.freeze(next); + }); + let prev2 = Object.freeze(rows.slice()); + const copyNoFreeze = time((index) => { + const next = new Array(count); + for (let i = 0; i < count; i++) next[i] = prev2[i]; + const at = index % count; + next[at] = Object.freeze({...prev2[at], value: --tick}); + prev2 = next; + }); + const store = createClassyStore({ + rows: Array.from({length: count}, (_, index) => ({ + id: index, + value: index, + })), + }); + snapshot(store); + let sum = 0; + const ours = time((index) => { + store.rows[index % count].value = --tick; + sum += snapshot(store).rows.length; + }); + const per = (v) => `${ns(v)} (${(v / count).toFixed(1)} ns/row)`; + console.log( + `${count} rows | copy by index + freeze: ${per(copyLoop)} | copy by index, array not frozen: ${per(copyNoFreeze)} | ours: ${per(ours)}`, + ); + if (sum < 0) console.log(sum); +} +``` + +Output (Node 24): + +```text +1000 rows | copy by index + freeze: 5.98 us (6.0 ns/row) | copy by index, array not frozen: 6.25 us (6.3 ns/row) | ours: 56.40 us (56.4 ns/row) +10000 rows | copy by index + freeze: 63.53 us (6.4 ns/row) | copy by index, array not frozen: 63.54 us (6.4 ns/row) | ours: 502.57 us (50.3 ns/row) +``` + +Output (Bun 1.4.4): + +```text +1000 rows | copy by index + freeze: 95.33 us (95.3 ns/row) | copy by index, array not frozen: 2.14 us (2.1 ns/row) | ours: 123.02 us (123.0 ns/row) +10000 rows | copy by index + freeze: 1.92 ms (192.3 ns/row) | copy by index, array not frozen: 19.62 us (2.0 ns/row) | ours: 2.15 ms (214.9 ns/row) +``` + +### Port 2: frozen and read-only input + +`p2-frozen.ts`: + +```ts +// Port 2: frozen input, frozen objects nested in input, a read-only property +// that holds an object, and what auto-freeze does to objects Immer did not make. +import {produce} from 'immer'; +import { + createClassyStore, + snapshot, + subscribe, +} from '/packages/classy-store/src/index.ts'; +import {section, show} from './harness.mjs'; + +section('a frozen object as the input'); +{ + const base = Object.freeze({ + a: Object.freeze({b: 1}), + keep: Object.freeze({n: 1}), + }); + const next = produce(base, (draft) => { + draft.a.b = 2; + }); + show('immer: write through a draft of a frozen base', () => next.a.b); + show('immer: base untouched', () => base.a.b); + show('immer: untouched branch kept', () => next.keep === base.keep); + show( + 'immer: result frozen', + () => Object.isFrozen(next) && Object.isFrozen(next.a), + ); + + const store = createClassyStore(Object.freeze({a: Object.freeze({b: 1})})); + show('ours: read through a frozen root', () => store.a.b); + show('ours: write to a frozen root', () => { + (store as {a: object}).a = {b: 2}; + return store.a.b; + }); + show('ours: write inside the frozen child', () => { + (store.a as {b: number}).b = 2; + return store.a.b; + }); +} + +section( + 'a frozen object nested in the input, with an unfrozen object inside it', +); +{ + const inner = {n: 1}; + const base = {config: Object.freeze({inner}), other: 1}; + const next = produce(base, (draft) => { + draft.config.inner.n = 2; + }); + show('immer: write below the frozen object', () => next.config.inner.n); + show('immer: the original inner object', () => inner.n); + show('immer: config was copied', () => next.config !== base.config); + + const inner2 = {n: 1}; + const store = createClassyStore({ + config: Object.freeze({inner: inner2}), + other: 1, + }); + let calls = 0; + subscribe(store, () => calls++, {sync: true}); + const before = snapshot(store); + show('ours: write below the frozen object', () => { + store.config.inner.n = 2; + return store.config.inner.n; + }); + show('ours: subscriber calls', () => calls); + show( + 'ours: the snapshot taken before the write now reads', + () => before.config.inner.n, + ); + show( + 'ours: snapshot after is the same object', + () => snapshot(store) === before, + ); +} + +section('the raw object is frozen after the store has it (finding 46)'); +{ + const raw = {config: {nested: {n: 1}}}; + const next = produce(raw, (draft) => { + Object.freeze(raw.config); + draft.config.nested.n = 2; + }); + show( + 'immer: base frozen during the recipe, then written through the draft', + () => next.config.nested.n, + ); + + const raw2 = {config: {nested: {n: 1}}}; + const store = createClassyStore(raw2); + void store.config.nested; + Object.freeze(raw2.config); + show( + 'ours: read after the raw object was frozen', + () => store.config.nested.n, + ); +} + +section('a non-writable, non-configurable property that holds an object'); +{ + const make = () => { + const base: {locked: {n: number}; a: number} = {a: 1} as never; + Object.defineProperty(base, 'locked', { + value: {n: 1}, + writable: false, + configurable: false, + enumerable: true, + }); + return base; + }; + const base = make(); + const next = produce(base, (draft) => { + draft.locked.n = 2; + }); + show('immer: write inside it', () => next.locked.n); + show('immer: base untouched', () => base.locked.n); + const replaced = produce(base, (draft) => { + draft.locked = {n: 3}; + }); + show( + 'immer: replace the read-only property through the draft', + () => replaced.locked.n, + ); + show('immer: descriptor seen through a draft', () => { + let seen: PropertyDescriptor | undefined; + produce(base, (draft) => { + seen = Object.getOwnPropertyDescriptor(draft, 'locked'); + }); + return {writable: seen?.writable, configurable: seen?.configurable}; + }); + + const store = createClassyStore(make()); + let calls = 0; + subscribe(store, () => calls++, {sync: true}); + const before = snapshot(store); + show('ours: write inside it', () => { + store.locked.n = 2; + return store.locked.n; + }); + show('ours: subscriber calls', () => calls); + show( + 'ours: the snapshot taken before the write now reads', + () => before.locked.n, + ); + show( + 'ours: snapshot shares the object with the store', + () => before.locked === store.locked, + ); + show('ours: is that object frozen in the snapshot', () => + Object.isFrozen(before.locked), + ); +} + +section('what auto-freeze does to objects Immer did not create'); +{ + const shared = {d: 1}; + const base = {a: {b: 1}, shared}; + const added = {x: {y: 1}}; + const next = produce(base, (draft) => { + draft.a.b = 2; + (draft as {added?: object}).added = added; + }); + show('immer: base root frozen', () => Object.isFrozen(base)); + show('immer: untouched branch of the base, frozen in place', () => + Object.isFrozen(shared), + ); + show( + 'immer: object assigned in the recipe, frozen in place', + () => Object.isFrozen(added) && Object.isFrozen(added.x), + ); + show( + 'immer: result holds the assigned object itself', + () => (next as {added?: object}).added === added, + ); + + const halfFrozen = {keep: Object.freeze({inner: {n: 1}}), a: 1}; + const next2 = produce(halfFrozen, (draft) => { + draft.a = 2; + }); + show('immer: object below an already frozen one is frozen', () => + Object.isFrozen(next2.keep.inner), + ); + + const shared2 = {d: 1}; + const added2 = {x: {y: 1}}; + const store = createClassyStore({a: {b: 1}, shared: shared2} as { + a: {b: number}; + shared: object; + added?: object; + }); + store.added = added2; + const snap = snapshot(store); + show( + 'ours: raw objects frozen after a snapshot', + () => Object.isFrozen(shared2) || Object.isFrozen(added2), + ); + show( + 'ours: snapshot holds the assigned object itself', + () => snap.added === added2, + ); + show( + 'ours: snapshot copy is deeply frozen', + () => + Object.isFrozen(snap.added) && + Object.isFrozen((snap.added as typeof added2).x), + ); +} + +section('Object.freeze on a draft, and on a store'); +{ + show('immer: Object.freeze(draft)', () => + produce({a: 1, child: {n: 1}}, (draft) => { + Object.freeze(draft); + }), + ); + const store = createClassyStore({a: 1, child: {n: 1}}); + show('ours: Object.freeze(store)', () => { + Object.freeze(store); + return Object.isFrozen(store); + }); + show('ours: write after the freeze', () => { + store.a = 2; + return store.a; + }); +} +``` + +Output (Bun 1.4.4): + +```text + +## a frozen object as the input +immer: write through a draft of a frozen base: 2 +immer: base untouched: 1 +immer: untouched branch kept: true +immer: result frozen: true +ours: read through a frozen root: 1 +ours: write to a frozen root: THROWS TypeError: Proxy object's 'set' trap returned falsy value for property 'a' +ours: write inside the frozen child: THROWS TypeError: Attempted to assign to readonly property. + +## a frozen object nested in the input, with an unfrozen object inside it +immer: write below the frozen object: 2 +immer: the original inner object: 1 +immer: config was copied: true +ours: write below the frozen object: 2 +ours: subscriber calls: 0 +ours: the snapshot taken before the write now reads: 2 +ours: snapshot after is the same object: true + +## the raw object is frozen after the store has it (finding 46) +immer: base frozen during the recipe, then written through the draft: 2 +ours: read after the raw object was frozen: THROWS TypeError: Proxy handler's 'get' result of a non-configurable and non-writable property should be the same value as the target's property + +## a non-writable, non-configurable property that holds an object +immer: write inside it: 2 +immer: base untouched: 1 +immer: replace the read-only property through the draft: 3 +immer: descriptor seen through a draft: {"writable":true,"configurable":true} +ours: write inside it: 2 +ours: subscriber calls: 0 +ours: the snapshot taken before the write now reads: 2 +ours: snapshot shares the object with the store: true +ours: is that object frozen in the snapshot: false + +## what auto-freeze does to objects Immer did not create +immer: base root frozen: false +immer: untouched branch of the base, frozen in place: true +immer: object assigned in the recipe, frozen in place: true +immer: result holds the assigned object itself: true +immer: object below an already frozen one is frozen: false +ours: raw objects frozen after a snapshot: false +ours: snapshot holds the assigned object itself: false +ours: snapshot copy is deeply frozen: true + +## Object.freeze on a draft, and on a store +immer: Object.freeze(draft): THROWS TypeError: Proxy object's non-extensible 'target' has configurable property 'parent_' that was not in the result from the 'ownKeys' trap +ours: Object.freeze(store): true +ours: write after the freeze: THROWS TypeError: Proxy object's 'set' trap returned falsy value for property 'a' +``` + +### Port 3: class instances + +`p3-class.ts`: + +```ts +// Port 3: class instances with and without the marker, getters, #private. +import {immerable, produce} from 'immer'; +import { + createClassyStore, + PROXYABLE, + snapshot, + subscribe, +} from '/packages/classy-store/src/index.ts'; +import {section, show} from './harness.mjs'; + +class Unmarked { + n = 1; + get double() { + return this.n * 2; + } + inc() { + this.n++; + } +} + +class Marked { + static [immerable] = true; + static [PROXYABLE] = true; + n = 1; + get double() { + return this.n * 2; + } + inc() { + this.n++; + } +} + +class MarkedChild extends Marked { + extra = 'x'; +} + +class InstanceMarked { + [immerable] = true; + n = 1; +} + +class Private { + static [immerable] = true; + static [PROXYABLE] = true; + #secret = 1; + n = 1; + read() { + return this.#secret; + } +} + +section('a class instance without the marker'); +{ + show('immer: as the root', () => + produce(new Unmarked(), (draft) => void draft.inc()), + ); + const point = new Unmarked(); + const base = {point, a: 1}; + const next = produce(base, (draft) => { + draft.point.n = 5; + }); + show( + 'immer: nested, written in a recipe; the base instance now reads', + () => point.n, + ); + show('immer: result is the base', () => next === base); + show('immer: instance frozen', () => Object.isFrozen(next.point)); + const next2 = produce(base, (draft) => { + draft.a = 2; + }); + show('immer: instance frozen after another field changed', () => + Object.isFrozen(next2.point), + ); + + const point2 = new Unmarked(); + const store = createClassyStore({point: point2, a: 1}); + let calls = 0; + subscribe(store, () => calls++, {sync: true}); + const before = snapshot(store); + store.point.n = 5; + show('ours: nested, written; subscriber calls', () => calls); + show('ours: the snapshot taken before now reads', () => before.point.n); + show('ours: as the root', () => { + const root = createClassyStore(new Unmarked()); + root.inc(); + return [root.n, snapshot(root).double]; + }); +} + +section('a class instance with the marker'); +{ + const base = new Marked(); + const next = produce(base, (draft) => { + draft.inc(); + }); + show('immer: method on the draft', () => [base.n, next.n]); + show( + 'immer: result is an instance of the class', + () => next instanceof Marked, + ); + show('immer: prototype getter on the result', () => next.double); + show('immer: own keys of the result', () => Reflect.ownKeys(next)); + show('immer: result frozen', () => Object.isFrozen(next)); + show('immer: getter read inside the recipe after a write', () => { + let seen = 0; + produce(base, (draft) => { + draft.n = 10; + seen = draft.double; + }); + return seen; + }); + show( + 'immer: subclass of a marked class', + () => + produce(new MarkedChild(), (draft) => { + draft.inc(); + }).n, + ); + show( + 'immer: marker as an instance field', + () => + produce(new InstanceMarked(), (draft) => { + draft.n = 2; + }).n, + ); + + const store = createClassyStore({item: new Marked()}); + store.item.inc(); + const snap = snapshot(store); + show('ours: nested marked instance', () => [snap.item.n, snap.item.double]); + show( + 'ours: snapshot is an instance of the class', + () => snap.item instanceof Marked, + ); + show('ours: own keys of the snapshot', () => Reflect.ownKeys(snap.item)); + show('ours: Object.keys of the snapshot', () => Object.keys(snap.item)); +} + +section('#private fields'); +{ + show('immer: method that reads #private, on a draft', () => { + let seen: unknown; + produce(new Private(), (draft) => { + seen = draft.read(); + }); + return seen; + }); + show('immer: the same on a result that was copied', () => + produce(new Private(), (draft) => { + draft.n = 2; + }).read(), + ); + show('ours: on the store', () => createClassyStore(new Private()).read()); + show('ours: on the snapshot', () => + snapshot(createClassyStore(new Private())).read(), + ); +} +``` + +Output (Bun 1.4.4): + +```text + +## a class instance without the marker +immer: as the root: THROWS Error: [Immer] produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '[object Object]' +immer: nested, written in a recipe; the base instance now reads: 5 +immer: result is the base: true +immer: instance frozen: false +immer: instance frozen after another field changed: false +ours: nested, written; subscriber calls: 0 +ours: the snapshot taken before now reads: 5 +ours: as the root: [2, 4] + +## a class instance with the marker +immer: method on the draft: [1, 2] +immer: result is an instance of the class: true +immer: prototype getter on the result: 4 +immer: own keys of the result: ["n"] +immer: result frozen: true +immer: getter read inside the recipe after a write: 20 +immer: subclass of a marked class: 2 +immer: marker as an instance field: 2 +ours: nested marked instance: [2, 4] +ours: snapshot is an instance of the class: true +ours: own keys of the snapshot: ["n", "double"] +ours: Object.keys of the snapshot: ["n", "double"] + +## #private fields +immer: method that reads #private, on a draft: THROWS TypeError: Cannot access invalid private field (evaluating 'this.#secret') +immer: the same on a result that was copied: THROWS TypeError: Cannot access invalid private field (evaluating 'this.#secret') +ours: on the store: THROWS TypeError: Cannot access invalid private field (evaluating 'this.#secret') +ours: on the snapshot: THROWS TypeError: Cannot access invalid private field (evaluating 'this.#secret') +``` + +### Port 4: getters, symbols, non-enumerable and array properties, sparse arrays + +`p4-shapes.ts`: + +```ts +// Port 4: an own getter on the input, a symbol-keyed property, a +// non-enumerable property, a named property on an array, a sparse array. +import {Immer, produce} from 'immer'; +import { + createClassyStore, + snapshot, +} from '/packages/classy-store/src/index.ts'; +import {section, show} from './harness.mjs'; + +const strict = new Immer({useStrictShallowCopy: true}); + +section('an own getter on the input'); +{ + const make = () => ({ + n: 1, + get double() { + return this.n * 2; + }, + }); + const next = produce(make(), (draft) => { + draft.n = 5; + }); + show('immer: the getter on the result', () => next.double); + show( + 'immer: is it still an accessor', + () => 'get' in (Object.getOwnPropertyDescriptor(next, 'double') ?? {}), + ); + show('immer: read in the recipe after the write', () => { + let seen = 0; + produce(make(), (draft) => { + draft.n = 5; + seen = draft.double; + }); + return seen; + }); + show( + 'immer, strict copy: the getter on the result', + () => + strict.produce(make(), (draft) => { + draft.n = 5; + }).double, + ); + + const store = createClassyStore(make()); + store.n = 5; + const snap = snapshot(store); + show('ours: the getter on the snapshot', () => snap.double); + show( + 'ours: is it still an accessor', + () => 'get' in (Object.getOwnPropertyDescriptor(snap, 'double') ?? {}), + ); +} + +section('a symbol-keyed property that holds an object'); +{ + const key = Symbol('meta'); + const make = () => ({a: 1, [key]: {n: 1}}); + const base = make(); + const next = produce(base, (draft) => { + draft[key].n = 2; + }); + show('immer: written through the draft', () => [base[key].n, next[key].n]); + show('immer: the new object under the symbol is frozen', () => + Object.isFrozen(next[key]), + ); + show('immer: can it be changed after produce', () => { + next[key].n = 99; + return next[key].n; + }); + + const store = createClassyStore(make()); + store[key].n = 2; + const snap = snapshot(store); + show('ours: written through the store', () => snap[key].n); + show('ours: the object under the symbol is frozen', () => + Object.isFrozen(snap[key]), + ); +} + +section('a non-enumerable property'); +{ + const make = () => { + const base = {a: 1} as {a: number; hidden: {n: number}}; + Object.defineProperty(base, 'hidden', { + value: {n: 1}, + enumerable: false, + writable: true, + configurable: true, + }); + return base; + }; + const next = produce(make(), (draft) => { + draft.a = 2; + }); + show( + 'immer: present on the result after another field changed', + () => 'hidden' in next, + ); + const strictNext = strict.produce(make(), (draft) => { + draft.a = 2; + }); + show('immer, strict copy: present, and enumerable', () => [ + 'hidden' in strictNext, + Object.getOwnPropertyDescriptor(strictNext, 'hidden')?.enumerable, + ]); + show('immer, strict copy: is it frozen', () => + Object.isFrozen(strictNext.hidden), + ); + + const store = createClassyStore(make()); + store.a = 2; + const snap = snapshot(store); + show('ours: present, and enumerable', () => [ + 'hidden' in snap, + Object.getOwnPropertyDescriptor(snap, 'hidden')?.enumerable, + ]); + show('ours: is it frozen', () => Object.isFrozen(snap.hidden)); +} + +section('a named property and a symbol on an array'); +{ + const tag = Symbol('tag'); + const make = () => { + const list = [1, 2, 3] as number[] & {label?: string; [tag]?: string}; + list.label = 'x'; + list[tag] = 't'; + return {list}; + }; + const next = produce(make(), (draft) => { + draft.list.push(4); + }); + show('immer: named property after a push', () => next.list.label); + show('immer: symbol property after a push', () => next.list[tag]); + show( + 'immer: write a named property on a draft array', + () => + produce(make(), (draft) => { + draft.list.label = 'y'; + }).list.label, + ); + show( + 'immer: write a symbol property on a draft array', + () => + produce(make(), (draft) => { + draft.list[tag] = 'u'; + }).list[tag], + ); + show( + 'immer: delete a named property on a draft array', + () => + produce(make(), (draft) => { + delete draft.list.label; + }).list.label, + ); + + const store = createClassyStore(make()); + store.list.label = 'y'; + const snap = snapshot(store); + show('ours: named property on the store', () => store.list.label); + show('ours: named property on the snapshot', () => snap.list.label); + show('ours: symbol property on the snapshot', () => snap.list[tag]); +} + +section('a sparse array'); +{ + // biome-ignore lint/suspicious/noSparseArray: the hole is the test + const make = () => ({ + list: [{n: 1}, , {n: 3}] as ({n: number} | undefined)[], + }); + const next = produce(make(), (draft) => { + (draft.list[2] as {n: number}).n = 9; + }); + show('immer: length and the hole', () => [next.list.length, 1 in next.list]); + const grown = produce(make(), (draft) => { + draft.list[5] = {n: 6}; + }); + show('immer: write past the end', () => [ + grown.list.length, + 3 in grown.list, + 4 in grown.list, + ]); + show('immer: delete an index', () => { + const removed = produce(make(), (draft) => { + delete draft.list[0]; + }); + return [removed.list.length, 0 in removed.list, removed.list[0]]; + }); + + const store = createClassyStore(make()); + (store.list[2] as {n: number}).n = 9; + const snap = snapshot(store); + show('ours: length and the hole', () => [snap.list.length, 1 in snap.list]); + delete store.list[0]; + show('ours: delete an index', () => { + const after = snapshot(store); + return [after.list.length, 0 in after.list, after.list[0]]; + }); +} +``` + +Output (Bun 1.4.4): + +```text + +## an own getter on the input +immer: the getter on the result: 2 +immer: is it still an accessor: false +immer: read in the recipe after the write: 2 +immer, strict copy: the getter on the result: 2 +ours: the getter on the snapshot: 10 +ours: is it still an accessor: true + +## a symbol-keyed property that holds an object +immer: written through the draft: [1, 2] +immer: the new object under the symbol is frozen: false +immer: can it be changed after produce: 99 +ours: written through the store: 2 +ours: the object under the symbol is frozen: true + +## a non-enumerable property +immer: present on the result after another field changed: false +immer, strict copy: present, and enumerable: [true, false] +immer, strict copy: is it frozen: false +ours: present, and enumerable: [true, false] +ours: is it frozen: true + +## a named property and a symbol on an array +immer: named property after a push: undefined +immer: symbol property after a push: undefined +immer: write a named property on a draft array: THROWS Error: [Immer] Immer only supports setting array indices and the 'length' property +immer: write a symbol property on a draft array: THROWS TypeError: Cannot convert a symbol to a string +immer: delete a named property on a draft array: THROWS Error: [Immer] Immer only supports deleting array indices +ours: named property on the store: "y" +ours: named property on the snapshot: undefined +ours: symbol property on the snapshot: undefined + +## a sparse array +immer: length and the hole: [3, false] +immer: write past the end: [6, false, false] +immer: delete an index: [3, true, undefined] +ours: length and the hole: [3, false] +ours: delete an index: [3, false, undefined] +``` + +### Port 5: operations Immer refuses + +`p5-traps.ts`: + +```ts +// Port 5: operations the store proxy lets through and an Immer draft refuses +// or answers: defineProperty, setPrototypeOf, __proto__ through Object.assign, +// a delete of a missing key, keys and `in`, descriptors. +import {produce} from 'immer'; +import { + createClassyStore, + snapshot, + subscribe, +} from '/packages/classy-store/src/index.ts'; +import {section, show} from './harness.mjs'; + +section('Object.defineProperty (findings 1, 45, 71)'); +{ + show('immer: on a draft', () => + produce({a: 1}, (draft) => { + Object.defineProperty(draft, 'b', { + value: 2, + enumerable: true, + writable: true, + configurable: true, + }); + }), + ); + const store = createClassyStore({a: 1} as {a: number; b?: number}); + let calls = 0; + subscribe(store, () => calls++, {sync: true}); + const before = snapshot(store); + Object.defineProperty(store, 'b', { + value: 2, + enumerable: true, + writable: true, + configurable: true, + }); + show('ours: store reads', () => store.b); + show('ours: subscriber calls', () => calls); + show('ours: snapshot has the property', () => 'b' in snapshot(store)); + show( + 'ours: snapshot is the one from before', + () => snapshot(store) === before, + ); +} + +section('the prototype (findings 47, 48)'); +{ + show('immer: Object.setPrototypeOf(draft)', () => + produce({a: 1}, (draft) => { + Object.setPrototypeOf(draft, {polluted: true}); + }), + ); + show('immer: Object.assign(draft, JSON.parse(\'{"__proto__": ...}\'))', () => + produce({a: 1}, (draft) => { + Object.assign(draft, JSON.parse('{"__proto__": {"polluted": true}}')); + }), + ); + const store = createClassyStore({a: 1} as {a: number; polluted?: boolean}); + show('ours: Object.assign(store, JSON.parse(\'{"__proto__": ...}\'))', () => { + Object.assign(store, JSON.parse('{"__proto__": {"polluted": true}}')); + return [store.polluted, snapshot(store).polluted]; + }); +} + +section('a delete that removes nothing (finding 29)'); +{ + const base = {a: 1} as {a: number; missing?: number}; + show( + 'immer: result is the base', + () => + produce(base, (draft) => { + delete draft.missing; + }) === base, + ); + const store = createClassyStore({a: 1} as {a: number; missing?: number}); + let calls = 0; + subscribe(store, () => calls++, {sync: true}); + const before = snapshot(store); + delete store.missing; + show('ours: subscriber calls', () => calls); + show( + 'ours: snapshot is the one from before', + () => snapshot(store) === before, + ); +} + +section('keys and `in` after a delete (findings 30, 31)'); +{ + show('immer: Object.keys(draft) and "b" in draft after delete', () => { + let seen: unknown; + produce({a: 1, b: 2} as {a: number; b?: number}, (draft) => { + delete draft.b; + seen = [Object.keys(draft), 'b' in draft]; + }); + return seen; + }); + show( + 'immer: a prototype getter that reads Object.keys(this), on a draft and on the result', + () => { + class Bag { + static [Symbol.for('immer-draftable')] = true; + a = 1; + b?: number = 2; + get size() { + return Object.keys(this).length; + } + } + let inRecipe = 0; + const next = produce(new Bag(), (draft) => { + delete draft.b; + inRecipe = draft.size; + }); + return [inRecipe, next.size]; + }, + ); + class Bag { + a = 1; + b?: number = 2; + get size() { + return Object.keys(this).length; + } + } + const store = createClassyStore(new Bag()); + const first = store.size; + delete store.b; + show( + 'ours: the same getter, live before and after the delete, then on a snapshot', + () => [first, store.size, snapshot(store).size], + ); +} + +section('Object.getOwnPropertyDescriptor(...).value (finding 50)'); +{ + const base = {child: {n: 1}}; + let viaDescriptor: unknown; + produce(base, (draft) => { + viaDescriptor = Object.getOwnPropertyDescriptor(draft, 'child')?.value; + (viaDescriptor as {n: number}).n = 9; + }); + show( + 'immer: the descriptor value is the base object', + () => viaDescriptor === base.child, + ); + show('immer: base after a write through it', () => base.child.n); + + const raw = {child: {n: 1}}; + const store = createClassyStore(raw); + let calls = 0; + subscribe(store, () => calls++, {sync: true}); + const value = Object.getOwnPropertyDescriptor(store, 'child')?.value as { + n: number; + }; + value.n = 9; + show( + 'ours: the descriptor value is the raw object', + () => value === raw.child, + ); + show('ours: subscriber calls after a write through it', () => calls); +} + +section('use of a draft after produce returned'); +{ + let leaked: {n: number} | undefined; + produce({child: {n: 1}}, (draft) => { + leaked = draft.child; + }); + show('immer: write to a leaked draft', () => { + (leaked as {n: number}).n = 2; + return 'no error'; + }); +} +``` + +Output (Bun 1.4.4): + +```text + +## Object.defineProperty (findings 1, 45, 71) +immer: on a draft: THROWS Error: [Immer] Object.defineProperty() cannot be used on an Immer draft +ours: store reads: 2 +ours: subscriber calls: 0 +ours: snapshot has the property: false +ours: snapshot is the one from before: true + +## the prototype (findings 47, 48) +immer: Object.setPrototypeOf(draft): THROWS Error: [Immer] Object.setPrototypeOf() cannot be used on an Immer draft +immer: Object.assign(draft, JSON.parse('{"__proto__": ...}')): THROWS Error: [Immer] Object.setPrototypeOf() cannot be used on an Immer draft +ours: Object.assign(store, JSON.parse('{"__proto__": ...}')): [true, true] + +## a delete that removes nothing (finding 29) +immer: result is the base: true +ours: subscriber calls: 1 +ours: snapshot is the one from before: false + +## keys and `in` after a delete (findings 30, 31) +immer: Object.keys(draft) and "b" in draft after delete: [["a"], false] +immer: a prototype getter that reads Object.keys(this), on a draft and on the result: [1, 1] +ours: the same getter, live before and after the delete, then on a snapshot: [2, 2, 0] + +## Object.getOwnPropertyDescriptor(...).value (finding 50) +immer: the descriptor value is the base object: true +immer: base after a write through it: 9 +ours: the descriptor value is the raw object: true +ours: subscriber calls after a write through it: 0 + +## use of a draft after produce returned +immer: write to a leaked draft: THROWS TypeError: Proxy has already been revoked. No more operations are allowed to be performed on it +``` + +### Port 6: cycles + +`p6-cycle.ts`: + +```ts +// Port 6: a self-referencing object. Run with a timeout: a hang is a result. +import {produce} from 'immer'; +import { + createClassyStore, + snapshot, +} from '/packages/classy-store/src/index.ts'; +import {section, show} from './harness.mjs'; + +type Node = {n: number; self?: Node}; + +section('a base that refers to itself'); +{ + const base: Node = {n: 1}; + base.self = base; + const next = produce(base, (draft) => { + draft.n = 2; + }); + show('immer: result.n', () => next.n); + show('immer: result.self is the result', () => next.self === next); + show('immer: result.self is the base', () => next.self === base); + show('immer: the base is now frozen', () => Object.isFrozen(base)); + + const base2: Node = {n: 1}; + base2.self = base2; + const next2 = produce(base2, (draft) => { + (draft.self as Node).n = 3; + }); + show('immer: write through draft.self; result.n and result.self.n', () => [ + next2.n, + next2.self?.n, + ]); + show('immer: result.self is the result', () => next2.self === next2); +} + +section('a draft assigned to itself'); +{ + const next = produce({n: 1} as Node, (draft) => { + draft.self = draft; + }); + show('immer: result.self is the result', () => next.self === next); + show('immer: result.self is a revoked proxy', () => { + try { + void next.self?.n; + return false; + } catch { + return true; + } + }); + show('immer: result frozen', () => Object.isFrozen(next)); +} + +section('the same in a store (finding 8)'); +{ + const store = createClassyStore({n: 1} as Node); + show('ours: store.self = store', () => { + store.self = store; + return store.self === store; + }); + show('ours: snapshot', () => snapshot(store).n); +} +``` + +Output (Bun 1.4.4): + +```text + +## a base that refers to itself +immer: result.n: 2 +immer: result.self is the result: false +immer: result.self is the base: true +immer: the base is now frozen: true +immer: write through draft.self; result.n and result.self.n: [1, 3] +immer: result.self is the result: false + +## a draft assigned to itself +immer: result.self is the result: true +immer: result.self is a revoked proxy: false +immer: result frozen: true + +## the same in a store (finding 8) +ours: store.self = store: true +ours: snapshot: THROWS Error: @codebelt/classy-store: circular reference detected in snapshot +``` + +### Port 7: Map and Set + +`p7-mapset.ts`: + +```ts +// Port 7: a Map and a Set with object members. Pass "noplugin" to run the +// first section without enableMapSet(), which is global and cannot be undone. +import {enableMapSet, produce} from 'immer'; +import { + reactiveMap, + reactiveSet, +} from '/packages/classy-store/src/collections/index.ts'; +import { + createClassyStore, + snapshot, + subscribe, +} from '/packages/classy-store/src/index.ts'; +import {ns, section, show, time} from './harness.mjs'; + +if (process.argv[2] === 'noplugin') { + section('a Map without enableMapSet()'); + show('immer: Map as the root', () => produce(new Map([['a', 1]]), () => {})); + show( + 'immer: Map nested, never read', + () => + produce({m: new Map([['a', {n: 1}]]), x: 1}, (draft) => { + draft.x = 2; + }).x, + ); + show('immer: Map nested, read in the recipe', () => + produce({m: new Map([['a', {n: 1}]]), x: 1}, (draft) => { + void draft.m; + }), + ); + process.exit(0); +} + +enableMapSet(); + +section('a Map with object values'); +{ + const key = {id: 'k'}; + const base = { + m: new Map([ + ['a', {n: 1}], + ['b', {n: 2}], + [key, {n: 3}], + ]), + }; + const next = produce(base, (draft) => { + (draft.m.get('a') as {n: number}).n = 5; + }); + show('immer: result is a native Map', () => [ + next.m instanceof Map, + Object.getPrototypeOf(next.m) === Map.prototype, + ]); + show('immer: map is new, changed value is new, other value kept', () => [ + next.m !== base.m, + next.m.get('a') !== base.m.get('a'), + next.m.get('b') === base.m.get('b'), + ]); + show('immer: base value untouched', () => base.m.get('a')?.n); + show('immer: object key still finds its value', () => next.m.get(key)?.n); + show('immer: result.m.set()', () => next.m.set('c', {n: 9})); + show('immer: result.m.delete()', () => next.m.delete('a')); + show('immer: Map.prototype.set.call(result.m)', () => { + Map.prototype.set.call(next.m, 'c', {n: 9}); + return next.m.has('c'); + }); + show('immer: values are frozen', () => Object.isFrozen(next.m.get('b'))); + show('immer: draft is an instance of Map', () => { + let seen = false; + produce(base, (draft) => { + seen = draft.m instanceof Map; + }); + return seen; + }); + + const store = createClassyStore({m: new Map([['a', {n: 1}]])}); + let calls = 0; + subscribe(store, () => calls++, {sync: true}); + const before = snapshot(store); + (store.m.get('a') as {n: number}).n = 5; + store.m.set('z', {n: 0}); + show( + 'ours, native Map: subscriber calls after a value write and a set()', + () => calls, + ); + show('ours, native Map: the snapshot taken before now reads', () => [ + before.m.get('a')?.n, + before.m.has('z'), + ]); + + const reactive = createClassyStore({ + m: reactiveMap([ + ['a', {n: 1}], + ['b', {n: 2}], + ]), + }); + let reactiveCalls = 0; + subscribe(reactive, () => reactiveCalls++, {sync: true}); + const reactiveBefore = snapshot(reactive); + (reactive.m.get('a') as {n: number}).n = 5; + const reactiveAfter = snapshot(reactive); + show('ours, reactiveMap: subscriber calls', () => reactiveCalls); + show('ours, reactiveMap: before and after', () => [ + reactiveBefore.m.get('a')?.n, + reactiveAfter.m.get('a')?.n, + ]); + show( + 'ours, reactiveMap: other value kept', + () => reactiveAfter.m.get('b') === reactiveBefore.m.get('b'), + ); + show( + 'ours, reactiveMap: snapshot is an instance of Map', + () => reactiveAfter.m instanceof Map, + ); + show('ours, reactiveMap: snapshot.m.set()', () => + (reactiveAfter.m as unknown as Map).set('c', {}), + ); +} + +section('a Set with object members'); +{ + const row = {n: 1}; + const other = {n: 2}; + const base = {s: new Set([row, other])}; + let hasOriginal = false; + let hasDraft = false; + const next = produce(base, (draft) => { + hasOriginal = draft.s.has(row); + for (const member of draft.s) { + if (member.n === 1) { + member.n = 10; + hasDraft = draft.s.has(member); + } + } + }); + show('immer: draft.has(original) and draft.has(its draft)', () => [ + hasOriginal, + hasDraft, + ]); + show('immer: result is a native Set', () => next.s instanceof Set); + show('immer: members in order', () => [...next.s].map((member) => member.n)); + show( + 'immer: result has the original changed member, the unchanged one', + () => [next.s.has(row), next.s.has(other)], + ); + show('immer: result.s.add()', () => next.s.add({n: 3})); + + const store = createClassyStore({s: reactiveSet([{n: 1}, {n: 2}])}); + const before = snapshot(store); + for (const member of store.s) if (member.n === 1) member.n = 10; + const after = snapshot(store); + show('ours, reactiveSet: members before and after', () => [ + [...before.s].map((member) => member.n), + [...after.s].map((member) => member.n), + ]); + show( + 'ours, reactiveSet: unchanged member kept', + () => [...after.s][1] === [...before.s][1], + ); + show('ours, reactiveSet: snapshot.has(a row read from the store)', () => + after.s.has([...store.s][0]), + ); +} + +section( + 'time to change one value of a 1,000-entry map, then take the next result', +); +{ + const entries = () => + Array.from( + {length: 1000}, + (_, index) => [`k${index}`, {value: index}] as [string, {value: number}], + ); + let tick = 0; + let state = produce({m: new Map(entries())}, () => {}); + const immer = time((index) => { + state = produce(state, (draft) => { + (draft.m.get(`k${index % 1000}`) as {value: number}).value = --tick; + }); + }); + const store = createClassyStore({m: reactiveMap(entries())}); + snapshot(store); + let sum = 0; + const ours = time((index) => { + (store.m.get(`k${index % 1000}`) as {value: number}).value = --tick; + sum += snapshot(store).m.size; + }); + console.log( + `immer, native Map draft: ${ns(immer)} | ours, reactiveMap: ${ns(ours)}`, + ); + if (sum < 0) console.log(sum); +} +``` + +Output (Bun 1.4.4): + +```text + +## a Map with object values +immer: result is a native Map: [true, true] +immer: map is new, changed value is new, other value kept: [true, true, true] +immer: base value untouched: 1 +immer: object key still finds its value: 3 +immer: result.m.set(): THROWS Error: [Immer] This object has been frozen and should not be mutated +immer: result.m.delete(): THROWS Error: [Immer] This object has been frozen and should not be mutated +immer: Map.prototype.set.call(result.m): true +immer: values are frozen: true +immer: draft is an instance of Map: true +ours, native Map: subscriber calls after a value write and a set(): 0 +ours, native Map: the snapshot taken before now reads: [5, true] +ours, reactiveMap: subscriber calls: 1 +ours, reactiveMap: before and after: [1, 5] +ours, reactiveMap: other value kept: true +ours, reactiveMap: snapshot is an instance of Map: false +ours, reactiveMap: snapshot.m.set(): THROWS TypeError: Attempted to assign to readonly property. + +## a Set with object members +immer: draft.has(original) and draft.has(its draft): [true, true] +immer: result is a native Set: true +immer: members in order: [10, 2] +immer: result has the original changed member, the unchanged one: [false, true] +immer: result.s.add(): THROWS Error: [Immer] This object has been frozen and should not be mutated +ours, reactiveSet: members before and after: [[1, 2], [10, 2]] +ours, reactiveSet: unchanged member kept: true +ours, reactiveSet: snapshot.has(a row read from the store): true + +## time to change one value of a 1,000-entry map, then take the next result +immer, native Map draft: 21.29 us | ours, reactiveMap: 126.59 us +``` + +Output (Bun 1.4.4, with the argument noplugin): + +```text + +## a Map without enableMapSet() +immer: Map as the root: THROWS Error: [Immer] The plugin for 'MapSet' has not been loaded into Immer. To enable the plugin, import and call `enableMapSet()` when initializing your application. +immer: Map nested, never read: 2 +immer: Map nested, read in the recipe: THROWS Error: [Immer] The plugin for 'MapSet' has not been loaded into Immer. To enable the plugin, import and call `enableMapSet()` when initializing your application. +``` + +### Port 8: types (tuple, Map, Set) + +`p8-types.ts`: + +```ts +// Port 8, type level only: a tuple, a Map and a Set through Immer's types and +// through ours. Checked with `tsc --noEmit`; nothing here runs. +import {type Draft, type Immutable, produce} from 'immer'; +import type {ReactiveMap} from '/packages/classy-store/src/collections/index.ts'; +import type {Snapshot} from '/packages/classy-store/src/types.ts'; + +type Equal = + (() => T extends A ? 1 : 2) extends () => T extends B ? 1 : 2 + ? true + : false; +declare function expectTrue(): T; + +type Pair = [string, number]; +type State = { + pair: Pair; + rows: {id: number}[]; + tags: Map; + ids: Set; +}; + +// Immer: a tuple stays a tuple in both directions. +expectTrue, readonly [string, number]>>(); +expectTrue, [string, number]>>(); +expectTrue< + Equal, readonly {readonly id: number}[]> +>(); + +// Immer: produce gives back the base type, tuple included. +declare const state: State; +const next = produce(state, (draft) => { + draft.pair[1] = 2; + // @ts-expect-error index 2 is outside the tuple + draft.pair[2] = 3; +}); +expectTrue>(); + +// Immer: a Map and a Set become their read-only interfaces. +expectTrue< + Equal['tags'], ReadonlyMap> +>(); +expectTrue['ids'], ReadonlySet>>(); +declare const frozen: Immutable; +// @ts-expect-error ReadonlyMap has no set() +frozen.tags.set('a', {n: 1}); + +// Ours: the tuple becomes an array (finding 14). +expectTrue, readonly (string | number)[]>>(); +// @ts-expect-error control: it is not the tuple +expectTrue, readonly [string, number]>>(); + +// Ours with the array branch removed, as Immer's Immutable is written. +type Primitive = string | number | boolean | null | undefined | symbol | bigint; +type Leaf = + | Primitive + | ((...args: never[]) => unknown) + | Date + | RegExp + | Error + | Map + | Set; +type Snapshot2 = T extends Leaf + ? T + : T extends object + ? {readonly [K in keyof T]: Snapshot2} + : T; +expectTrue, readonly [string, number]>>(); +expectTrue< + Equal, readonly {readonly id: number}[]> +>(); +expectTrue< + Equal, readonly {readonly id: number}[]> +>(); + +// Ours: a native Map in a snapshot keeps set(), and so does a ReactiveMap (finding 16). +declare const snap: Snapshot<{ + native: Map; + reactive: ReactiveMap; +}>; +snap.native.set('a', 1); +snap.reactive.set('a', 1); +``` + +Output (tsc 7.0.2 --noEmit, lines for this file): + +```text +errors reported in p8-types.ts: 0 +``` + +### Port 9: another realm + +`p9-realm.mjs`: + +```js +// Port 9: a plain object made in another realm (an iframe, a Node vm context). +// Runs on Bun and on Node. +import vm from 'node:vm'; +import {produce} from 'immer'; +import {createClassyStore, snapshot, subscribe} from './classy.mjs'; +import {section, show} from './harness.mjs'; + +section('a plain object from another realm'); +const make = () => vm.runInNewContext('({a: {b: 1}, list: [{n: 1}]})'); +{ + const foreign = make(); + show( + "its prototype is this realm's Object.prototype", + () => Object.getPrototypeOf(foreign) === Object.prototype, + ); + const next = produce(foreign, (draft) => { + draft.a.b = 2; + }); + show('immer: drafted and copied', () => [foreign.a.b, next.a.b]); + + const data = make(); + const store = createClassyStore({data}); + let calls = 0; + subscribe(store, () => calls++, {sync: true}); + const before = snapshot(store); + store.data.a.b = 2; + show('ours: subscriber calls after a write inside it', () => calls); + show('ours: the snapshot taken before now reads', () => before.data.a.b); + show('ours: the store hands out the raw object', () => store.data === data); + + const list = vm.runInNewContext('[{n: 1}]'); + const listStore = createClassyStore({list}); + let listCalls = 0; + subscribe(listStore, () => listCalls++, {sync: true}); + listStore.list.push({n: 2}); + listStore.list[0].n = 5; + show( + 'ours: a foreign array, calls after a push and a write to a foreign row', + () => listCalls, + ); +} +``` + +Output (Node 24; Bun gives the same): + +```text + +## a plain object from another realm +its prototype is this realm's Object.prototype: false +immer: drafted and copied: [1, 2] +ours: subscriber calls after a write inside it: 0 +ours: the snapshot taken before now reads: 2 +ours: the store hands out the raw object: true +ours: a foreign array, calls after a push and a write to a foreign row: 1 +``` diff --git a/review/stage-2/legend-state.md b/review/stage-2/legend-state.md new file mode 100644 index 00000000..fb702574 --- /dev/null +++ b/review/stage-2/legend-state.md @@ -0,0 +1,1442 @@ +# Stage 2: Legend-State (persistence, sync and batching; API read) + +Stage 2 of the pre-1.0 review, 2026-11-19. Read-only: nothing in the +repository was changed apart from this file. This is an API read, so the +source was read only at the files that decide persistence and batching. + +## Library, version and files read + +- **Library:** `@legendapp/state`, from `https://github.com/LegendApp/legend-state`. +- **Two versions were read**, because the "latest stable release" is not where + the project is going: + - **2.1.15**, the npm `latest` tag and the newest stable release. Tag + `v2.1.15`, commit `02032f3c75874904b114ec6d69cbbfba45a29970`, dated + 2024-08-30. Its persistence is `persistObservable()`. + - **3.0.0-next.1**, the npm `next` tag. Tag `v3.0.0-next.1`, commit + `2676125aa77002cadbb70d32d795fa64930f8051`, dated 2026-11-17. Version 3 + replaces `persistObservable()` with `syncObservable()` and rewrites the + batcher. It is a pre-release; the stable line is two years old, so I read + it as the direction the library has taken. Every claim below names which + version it is about. +- **Files read, 2.1.15** (`src/`): `batching.ts` whole; `persist/persistObservable.ts` + whole; `persist-plugins/local-storage.ts` whole; `ObservableObject.ts` + lines 100 to 135, 545 to 625 and 700 to 760 (`set`, `setKey`, `assign`, + `updateNodesAndNotify`); the `PersistOptions*`, `ObservablePersistLocal` and + `PersistMetadata` types in `observableInterfaces.ts`. A grep over all of + `src/` for `beforeunload`, `pagehide`, `visibilitychange`, `storage` events, + `migrat`, `version`, `expire` and `ttl`. +- **Files read, 3.0.0-next.1** (`src/`): `batching.ts` lines 1 to 200 and 395 to + 562; `sync/syncTypes.ts`, `sync/persistTypes.ts`, `persistFormat.ts` whole; + `sync/retry.ts` lines 1 to 60; `sync/syncObservable.ts` lines 255 to 355 + (local save queue and metadata), 432 to 580 (the queue that turns changes + into saves), 3178 to 3554 (`onObsChange`, `loadLocal`, `loadPersistedLocal`) + and 4500 to 4518 (return value); `persist-plugins/local-storage.ts` whole; + `globals.ts` lines 43 to 138 (`safeStringify`, `safeParse`); a grep over + `src/` for every `NODE_ENV` branch and `[legend-state]` message. + `syncObservable.ts` is 4,520 lines, about 3,000 of them reconciliation of + pending changes with server data. I did not read that part line by line. +- **Not read:** the IndexedDB, MMKV, AsyncStorage and SQLite plugins beyond + their types and their parse-failure messages; the Firebase, Supabase and + CRUD sync plugins; the React bindings; Legend's website documentation. +- **Ours:** `utils/persist/persist.ts` and `persist.types.ts` whole, + `core/core.ts` lines 205 to 330 (notification, transactions, `batch`, + `deliver`) and 560 to 600 (`subscribe`), and the persist tutorial and + architecture pages under `website/content/docs/`. Line numbers for ours refer + to `release/1.0` at `5d866cb`. +- **Ported tests** ran on Bun 1.4.4, with `@legendapp/state@2.1.15` and + `@legendapp/state@3.0.0-next.1` each installed from npm in its own scratch + folder (version 3 imports itself by name, so the two cannot share a folder), + and against our source imported by absolute path. Their code and output are + in the appendix. + +## Summary + +Legend-State is not a class store, and its persistence is built around remote +sync: each observable can have a local cache and a remote, and the machinery +(pending-change tracking, replay after a failed upload, `lastSync`, retry with +back-off) exists for the remote. For a store that persists to `localStorage` +the comparison is narrower than the size of its source suggests, and it comes +out mostly in our favour: we have a schema version and migration, expiry, +cross-tab sync, a status handle, a disposable handle and a deferred save after +an early write, none of which Legend's local persistence has. Eleven findings +follow. The three that matter most: + +1. **Synchronous hydration (finding 4).** With a synchronous storage area, + Legend has the stored value in the observable the moment the persistence + call returns (port P2: 7 against our 0). We always read through an `await`, + so a store on `localStorage` renders its defaults first and the saved state + a microtask later. That is a choice with an SSR consequence, and it should + be made on purpose before 1.0. +2. **A throwing listener broke Legend's batcher until 3.0 (finding 1).** In + 2.1.15 one listener that throws leaves a module-level flag set, so no + observable notifies again, and the second listener on the same observable + never runs (port B5). Version 3 fixed it by running every listener and + rethrowing the first error. Our `deliver()` already isolates listeners + (`core.ts:314-327`); what is worth taking from version 3 is only its + decision about where the error goes. +3. **`batch()` and `async` functions (finding 3).** Neither library notices an + `async` function passed to `batch`; the writes after the first `await` fall + outside it (port B8). Legend avoids half of the trap by typing `batch` as + returning nothing; ours returns whatever `run` returns, so it hands back the + promise that tells the caller nothing was batched. A dev-only check or a type + that refuses a promise would catch it. + +"Where we already do better" lists what to keep. + +## How the two designs differ + +- **Legend notifies on every write, immediately, unless a batch is open.** + `notify()` runs "immediate" listeners, adds the node to the current batch, and + if no batch is open calls `runBatch()` at once (2.1.15 `batching.ts:79-109`; + 3.0.0-next.1 `batching.ts:116-190`). Port B1 shows the default listener has + run before the write returns. `ObservableObject.updateNodesAndNotify` opens a + batch around each write so that one write is one notification + (`ObservableObject.ts:719-752`). Ours is the opposite default: a plain + subscriber hears one notification per microtask and a `{sync: true}` one per + write or per method call (`core.ts:217-241`). +- **A Legend listener gets a list of changes** (`path`, `valueAtPath`, + `prevAtPath`) and a lazy `getPrevious()`; ours get nothing. Persistence is the + consumer that needs it: it saves the changed paths, not the whole value. +- **Legend's persistence is an observer of the observable**, registered with + `obs.onChange` (`persistObservable.ts:802-812`), like ours with `subscribe` + (`persist.ts:485`). It has no handle to stop it: `persistObservable` returns + the observable itself, and 3.0 returns the sync-state observable + (`syncObservable.ts:4500-4518`). Ours returns a handle with `dispose`. +- **Legend has no snapshots, so it has nothing like our version-keyed restore + bookkeeping.** It marks changes that came from a restore instead + (finding 6). + +## Findings + +### 1. A throwing listener wedged the batcher in 2.1.15; 3.0 fixed it + +Stage 1 findings 18, 22 and 23 concern what happens around a listener. Bears on +API question 8. + +- **What they do.** + - 2.1.15: `batchNotifyChanges` calls `listener(listenerParams!)` with no + `try` (`batching.ts:243`). `endBatch` sets `isRunningBatch = true`, calls + `runBatch()` and sets it back to `false` on the next line, with no `finally` + (`batching.ts:313-317`). A throw leaves `isRunningBatch` true, so every later + `endBatch` takes the "already running" branch, sets `didDelayEndBatch` and + returns (`batching.ts:296-300`): nothing is ever notified again. + - 3.0.0-next.1: `batchNotifyChanges` catches each listener's error, keeps the + first, finishes the other listeners and rethrows it (`batching.ts:412-420` + and the `if (didError) throw firstError` after the loop). `endBatch` resets + `isRunningBatch` in a `catch` (`batching.ts:523-535`), and + `endBatchAndThrow` closes a batch while keeping the error that interrupted + it (`batching.ts:545-551`). `batch()` uses it (`batching.ts:489-497`). +- **What we do.** `deliver()` copies the listeners, calls each in a `try`, and + sends the error to `console.error` (`core.ts:314-327`). The writer does not + see it. +- **Difference in behaviour.** Port B5, 2.1.15, run in a process of its own: + the write throws, the second listener on the same observable does not run, + and an unrelated observable's listener is called 0 times out of 2 writes, for + the rest of the process. Version 3 and ours: the second listener runs, and the + other store is notified twice (appendix, B5 and `b5.iso.ts`). Ours never + throws to the writer; version 3 does, with the first error. +- **Proposal: reject the bug, adapt the decision.** Keep `deliver()`. The open + question is where a listener's error should go. Version 3 gives it to the + writer, after every listener has run. That is wrong for us: the write has + already happened and a framework binding's error would surface in whatever + line assigned a field. `console.error` is the quietest answer and is what a + Vue or Solid user sees from their own effects. A cheap improvement that comes + from reading Legend: route the error through one function that dev tools and + tests can replace, so the stage 3 diagnostics work has a single place to hook. + That is optional. +- **Kind:** diagnostics. +- **Cost:** none to keep; a replaceable reporter is one function in `core.ts` + and an internal export, not breaking. + +### 2. A write that is undone inside a batch is not notified + +Bears on API question 2. + +- **What they do.** In 3.0.0-next.1, `notify()` looks for the node in the open + batch and, when the new value equals the value from before the batch, deletes + the entry, so no listener hears of it (`batching.ts:133-143`, the check + `existing.prev === value`). Port B6: `a` set to 1 and back to 0 inside a + batch gives 0 calls in 3.0.0-next.1. Version 2.1.15 gives 1 call: the + suppression is new in 3.0, and `notify()` in 2.1.15 only overwrites the + entry's value (`batching.ts:97-103`). +- **What we do.** Every write bumps the version and schedules a notification + (`core.ts:217-241`), and the transaction delivers once at the end + (`core.ts:249-256`). Port B6: 1 call, to a sync subscriber, with a snapshot + that differs from the earlier one in identity but not in content. +- **Difference in behaviour.** A net-zero batch is silent in Legend 3 and + notifies once in Legend 2.1.15 and in ours. +- **Proposal: reject.** Legend can do this because it has no snapshot object to + keep consistent. A framework binding of ours reads `snapshot(store)` and + compares identity; suppressing the notification while the version has moved + would let a binding hold a snapshot that is no longer the cached one, or force + the snapshot cache to treat a reverted version as unchanged. Structural + sharing could in principle return the old snapshot after a revert, but that is + a change to `snapshot.ts` for a rare case. This is reasoning from reading. +- **Kind:** performance. +- **Cost:** reject; none. + +### 3. `batch()` with an `async` function + +Bears on API questions 2 and 8. + +- **What they do.** `batch(fn: () => void)` in both versions. 2.1.15 calls + `fn()` inside `try/finally` and ends the batch (`batching.ts:268-285`); + 3.0 does the same (`batching.ts:489-497`). The return value is discarded, so + `batch(async () => ...)` returns `undefined`. Neither version inspects it. + `beginBatch()` arms a `setTimeout(onActionTimeout, 0)` that force-ends a batch + still open on the next macrotask and prints "Forcibly completing + observableBatcher because end() was never called" under + `NODE_ENV === 'development'` (2.1.15 `batching.ts:25-34, 286-291`; + 3.0 `batching.ts:49-58`). That watchdog guards the low-level + `beginBatch/endBatch` pair, not the async case: `batch()` always ends + synchronously. +- **What we do.** `batch(run: () => T): T` increments the depth, calls `run`, + and decrements in `finally` (`core.ts:299-306`). It returns what `run` + returns. The doc comment says the part after an `await` is not covered + (`core.ts:282-283`). +- **Difference in behaviour.** Port B8, 2.1.15 and 3.0.0-next.1: one write + before the `await`, two after; the listener has been called once when `batch` + returns and three times when the promise settles; no warning. Ours: the same + three calls, no warning, and `batch` returns the promise. In Legend that + promise is dropped, so the mistake is invisible; in ours it is returned, which + makes a check possible. +- **Proposal: adapt.** Two ways, both small. (a) A dev-only `console.warn` + when `run()` returns a thenable, with a stable message. (b) A type that + rejects a function returning a promise, for example a conditional type on the + parameter; this needs a type test because inference through a conditional + return is awkward (reading, not tried). Neither changes the runtime contract. + Do not copy Legend's watchdog timer: it exists for an unbalanced + `beginBatch/endBatch` pair, which we do not export. +- **Kind:** diagnostics. +- **Cost:** `core.ts` (about 5 lines) or `index.ts` types; not breaking; low + risk. + +### 4. Hydration is synchronous in Legend and asynchronous in ours + +Bears on API question 8 only indirectly; it is the persistence design question +the brief asks about ("how hydration interacts with rendering on a server"). + +- **What they do.** The local-storage plugin reads synchronously + (`persist-plugins/local-storage.ts:13-26` in both versions: `getTable` calls + `storage.getItem` and parses). `loadLocal` / `loadPersistedLocal` call it and + merge into the observable (2.1.15 `persistObservable.ts:520-616`; 3.0 + `syncObservable.ts:3296-3398`). The function is `async`, but it reaches its + first `await` only when the plugin is not yet initialised or has an + asynchronous `loadTable`. For `localStorage`, nothing is awaited, so the merge + has run when the persistence call returns. On the server the plugin is built + with `typeof localStorage !== 'undefined' ? localStorage : undefined` + (`local-storage.ts:67-71` in 2.1.15) and `getTable` returns `undefined` + without a storage object, so a server render sees the defaults and a client + render sees the stored data. That would be a hydration mismatch, and I found + no option for it (reading from the source; no server render was run). +- **What we do.** `persist()` starts `hydrateFromStorage()` and does not wait + (`persist.ts:488-496`). It reads with `raw = await storage.getItem(name)` + (`persist.ts:398`), and an `await` on a plain value still yields a + microtask. So even a synchronous adapter delivers after the call returns. + `skipHydration` and `rehydrate()` are the documented route for SSR + (`persist.types.ts:101-106`). +- **Difference in behaviour.** Port P2, both versions of Legend: the observable + holds 7 immediately after the call; ours holds 0 and reaches 7 after + `await handle.hydrated`. +- **Proposal: adapt, as a decision for stage 3.** The case for a synchronous + fast path: in a client-only app on `localStorage` the first render shows + defaults and the second shows the saved state, a visible flash that Legend and + Zustand's synchronous storage avoid. The case against: a synchronous restore + inside `persist()` runs `migrate`, transforms and `merge` (user code) inside + the caller's stack, and it makes hydration order depend on whether the adapter + happens to be synchronous. The middle path is an option, for example + `hydrate: 'sync' | 'async'`, defaulting to the current behaviour, so SSR stays + safe. `getItem` returning a non-promise is the signal; `hydrated` would still + resolve. This touches the restore-versus-local-edit logic (stage 1 finding + 56), which currently relies on the read being in flight. +- **Kind:** API design. +- **Cost:** `persist.ts`, `persist.types.ts`, docs and about 6 tests; additive if + it is an option; medium risk because of finding 56. + +### 5. No write is flushed when the page goes away + +- **What they do.** Neither version has a `beforeunload`, `pagehide` or + `visibilitychange` handler: the grep over `src/` finds listeners only in + `useHover.ts`, `pageHash.ts` and `pageHashParams.ts`. It does not need one for + local saves, because there is no local debounce: a change is queued in a + microtask and written at once (3.0 `syncObservable.ts:3233-3246`, 2.1.15 + `persistObservable.ts:488-500`). `debounceSet` (3.0) and `saveTimeout` (the + Firebase plugin) debounce the remote upload only (3.0 + `syncObservable.ts:518-530`), and they are not flushed either. +- **What we do.** `debounce` is for the local write (`persist.ts:247-259`) and + nothing flushes the timer when the tab closes; `syncTabs` is the only global + listener (`persist.ts:480-482`). +- **Difference in behaviour.** With `debounce: 500`, an edit made less than half + a second before the tab closes is lost. Legend has no equivalent exposure + because it has no local debounce. This is a gap the comparison exposes, not + something Legend solved. +- **Proposal: adapt.** When `debounce > 0` and a timer is pending, flush on + `pagehide` (and `visibilitychange` to `hidden`) with a synchronous + `storage.setItem` when the adapter returned a non-promise; for an async + adapter, start the write and accept it may not finish. Remove the listeners in + `dispose()`. Add an option or make it the default when `debounce > 0`. + Reading only; I did not test a browser unload. +- **Kind:** bug (data loss window), API design. +- **Cost:** `persist.ts`, one test file, docs; not breaking if added behind the + existing `debounce`; low risk. + +### 6. Telling a restore's writes from the user's + +Stage 1 finding 54 (dead and redundant code in `persist.ts`) and the version +bookkeeping in `applyPersistedState`. + +- **What they do.** Restores write inside a flag. In 3.0, `loadPersistedLocal` + sets `internal.globalState.isLoadingLocal = true` around `mergeIntoObservable` + (`syncObservable.ts:3386-3397`); `notify()` stores that flag on the batch + entry (`batching.ts:143-165`, `isFromPersist`, `isFromSync`); listeners receive + it as `isFromPersist` / `isFromSync` in their parameters, and `onObsChange` + skips a change when `isFromPersist` is set (`syncObservable.ts:3183-3185`). + 2.1.15 reads the global flag when the listener runs instead + (`persistObservable.ts:485-486`, `isLoadingLocal`, `isLoadingRemote`). +- **What we do.** After a batched notification we cannot tell who wrote, so + `persist` records the versions it expects: `skipAutoSaveVersion`, + `clearedVersion`, `expectedVersion`, `discardEditedFields()` and a baseline + snapshot comparison (`persist.ts:128-129, 262-270, 281-382`). About 100 lines, + and the area stage 1 found most to explain (finding 54, `persist.json`). +- **Difference in behaviour.** Equivalent results on the cases stage 1 pinned; + Legend's flag is simpler but cannot express "a subscriber edited another field + while the restore was running": there the restore's own batch is tagged as a + whole. +- **Proposal: reject.** To copy the flag we would tag each pending notification + in the core with its origin, because our persist subscriber runs in a later + microtask, after the restore function has returned; Legend can carry the tag + because its batch entries hold it. That puts persist-specific state into + `core.ts` and widens the listener contract. The version scheme is local to + `persist.ts` and exact. Keep it; if stage 3 wants fewer lines, simplify + inside `persist.ts` (the four cancel-timer blocks and the unread assignments + of finding 54), not by moving the logic. +- **Kind:** simplification (rejected). +- **Cost:** reject; none. + +### 7. The storage contract, ready-made backends and async transforms + +- **What they do.** A Legend backend is a class implementing a table-shaped + interface: `getTable`, `set(table, changes)`, `deleteTable`, `getMetadata`, + `setMetadata`, `deleteMetadata`, and optional `initialize` and `loadTable` + (3.0 `sync/syncTypes.ts:146-155`; 2.1.15 `observableInterfaces.ts:222-231`). + It receives changes by path and a metadata record for pending changes and + `lastSync`. The library ships six: localStorage, sessionStorage, AsyncStorage, + MMKV, IndexedDB and Expo SQLite. Backend-specific options live inside the + generic option objects (`mmkv`, `indexedDB`, `options: any`; + `syncTypes.ts:25-37`), and a plugin is instantiated once per class and shared + (`syncObservable.ts:3316-3328`). Transforms are `transform: {load, save}` + over the whole table, may return promises, and (2.1.15) `fieldTransforms` + renames fields; a field mapped to null is not saved (2.1.15 + `persistObservable.ts:276-278`). +- **What we do.** `StorageAdapter` is `getItem`, `setItem`, `removeItem` on + strings, sync or async (`persist.types.ts:10-14`): the Web Storage shape. A + per-property transform is `{key, serialize, deserialize}`, synchronous + (`persist.types.ts:22-31`). We ship no adapter. +- **Difference in behaviour.** Ours is simpler and is the shape every key-value + store already has, so wrapping AsyncStorage, MMKV or `idb-keyval` is a few + lines and encryption is a wrapper that encrypts the string in `setItem` and + decrypts in `getItem` (reading from the types; not tried). Legend's table + model is what lets IndexedDB store rows and SQLite store tables, which a + string key cannot do. Our synchronous `serialize` cannot call an async + encryption API; the adapter route can. +- **Proposal: keep the contract; adapt the docs.** Add short recipes for + AsyncStorage, IndexedDB and an encrypting wrapper to the persist tutorial, as + that is what a Legend user would otherwise look for. Reject a table model. + Consider letting `serialize` and `deserialize` return a promise only if a real + case needs it; the adapter already covers it. +- **Kind:** docs. +- **Cost:** `PERSIST_TUTORIAL.md`; not breaking. + +### 8. Date, Map and Set round trip by default in Legend + +Bears on API question 5. + +- **What they do.** `safeStringify` replaces a `Date`, a `Map` and a `Set` with a + tagged object, `{__LSType: 'Date' | 'Map' | 'Set', value}`, and `safeParse` + revives it (3.0 `globals.ts:43-83`; 2.1.15 `helpers.ts:254-259`). Both local + plugins use them. A stored object that merely looks like the tag is revived + too, and a malformed one makes `new Map(value.value)` throw during parse; + that is reasoning from reading, and a case for the security agent. + 3.0 stopped reviving plain ISO strings to dates, and prints a dev warning for + them (`globals.ts:92-107`). +- **What we do.** `JSON.stringify` of the snapshot (`persist.ts:217`). A `Date` + becomes a string, a `ReactiveMap` becomes whatever its snapshot serialises to, + so these need a `PropertyTransform` (`persist.types.ts:16-31`). Stage 1 + finding 53 shows the envelope check is loose about shapes. +- **Difference in behaviour.** A store with a `Date` field persists with no + configuration in Legend and needs a transform in ours. +- **Proposal: reject a tag format; adapt the docs.** A tag convention makes the + stored format part of the contract and invites the prototype-pollution class + of problem the security agent is asked to look at. A short "Dates, maps and + sets" section in the tutorial with a ready-made transform for each is + enough. Consider exporting those three transforms from the utils entry if the + tutorial already repeats them. +- **Kind:** docs, API design. +- **Cost:** docs; optionally three small exports; not breaking. + +### 9. Status: Legend has a pause switch and an in-flight count; we have neither + +- **What they do.** The returned sync state is an observable with + `isPersistLoaded`, `isPersistEnabled`, `isSyncEnabled`, `lastSync`, + `syncCount`, `isGetting`, `isSetting`, `numPendingGets`, `numPendingSets`, + `error`, `sync()`, `getPendingChanges()`, `resetPersistence()` and `reset()` + (3.0 `observableInterfaces.ts:199-231`). Setting `isPersistEnabled` to false + stops saving (`syncObservable.ts:566, 677`); `readonly` in the persist options + does the same statically. Errors go to `syncState.error` and to + `onError(error, {source, type, retry, ...})` (`syncObservable.ts:432-445`). +- **What we do.** `PersistStatus` holds `isHydrated`, `isExpired`, `isDisposed` + and `lastError`, observable through `UtilityStatusSource` + (`persist.types.ts:148-188`), plus `dispose`, `save`, `clear`, `rehydrate`. +- **Difference in behaviour.** Ours is smaller and, because `dispose()` exists, + covers stopping for good. A user who wants to pause saving for a while (for + example while loading a document from a server) has to dispose and + re-attach, losing the handle. There is no "a write is in flight" signal for a + "Saving..." indicator; `save()` resolves when its write ends, which covers the + explicit case only. +- **Proposal: reject for now.** Neither is a gap that stage 3 should fill before + 1.0 unless the owner uses them. If one is wanted, a `pause()` and `resume()` + on the handle that stop `scheduleWrite` and take a save on resume is about 10 + lines; an `isSaving` field in `PersistStatus` is the one addition the status + type can take later without breaking anyone. +- **Kind:** API design. +- **Cost:** `persist.ts`, `persist.types.ts`; additive. + +### 10. Cross-tab and conflicts: Legend has none locally; ours is last writer wins + +- **What they do.** There is no `storage` event handling in either version (grep + over `src/`). The local-storage plugin keeps the parsed table in a field, + `data[table]`, filled on the first read and updated by every `set` + (`local-storage.ts:14-38`). It therefore never sees another tab's write, and + its next save writes its cached copy back, so the other tab's change is lost. + Port P4: another tab writes `b = 99`; this tab then sets `a`; the stored + record is `{a: 1, b: 0}`, both versions. Conflict settlement exists only for + the remote: pending local paths are replayed over server data after a `get` + (2.1.15 `persistObservable.ts:724-748`; 3.0 `syncObservable.ts:3400-3532` and + the reconciliation functions that follow), with `mode` choosing set, assign, + merge, append or prepend (`GetMode`, `observableInterfaces.ts:165`) and + `lastSync` as the cursor. +- **What we do.** `syncTabs` listens for the `storage` event, ignores deletions + and obsolete values, cancels a pending debounced write, and restores field by + field (`persist.ts:446-476`). A write in this tab replaces the whole stored + record. Port P4 on ours without `syncTabs`: the same `{a: 1, b: 0}`, because we + also serialise the whole selected state. +- **Difference in behaviour.** With `syncTabs` on, ours would have taken `b = 99` + before the local write; Legend cannot. Neither has per-field merging of two + tabs' concurrent edits: whichever tab saves last wins the whole record. +- **Proposal: reject remote sync; adapt the docs.** Remote sync with pending + replay is a product of its own (about 3,000 lines in Legend) and does not + belong in a 1.0 persist util. What the comparison does show is that the + tutorial's `syncTabs` section should say plainly that two tabs editing + different fields at once is last-writer-wins on the whole record, which is + not obvious from "Tab B automatically receives the update". Per-field storage + (one key per property) would remove it but is a different design. +- **Kind:** docs. +- **Cost:** `PERSIST_TUTORIAL.md`; not breaking. + +### 11. Unknown stored keys are merged in Legend and dropped in ours + +Stage 1 findings 52, 53 and 55 concern what `persist` accepts from storage. + +- **What they do.** Whatever the record holds is merged into the observable with + `mergeIntoObservable` (3.0 `syncObservable.ts:3390-3394`; 2.1.15 + `persistObservable.ts:601`). There is no property list to filter by. Port P3: + a stored `{old: 1, count: 7}` over `{count: 0}` leaves the observable with the + keys `count` and `old`, both versions. A falsy root replaces the default + (`syncObservable.ts:3390-3392`), and a non-object root is accepted. +- **What we do.** Only keys in `propKeys` are written, and only those present in + the merged state (`persist.ts:337-339, 360-365`). Port P3 on ours: the keys + are `['count']`. Stage 1 finding 53 notes that an array in `state` still + passes the envelope check, so the filter is by key name, not by shape. +- **Difference in behaviour.** After a schema change Legend keeps stale keys in + live state and rewrites them on the next save; ours ignores them and drops + them on the next save. That is also why ours can be the safer one against a + stored `__proto__` key (the security agent's area). +- **Proposal: keep ours.** The `properties` allow-list, resolved once at attach + (`persist.ts:160-168`), is the thing Legend lacks. Say in the docs that + unknown stored keys are ignored and removed on the next save, because it is + the reason `migrate` is only needed for renames and shape changes. +- **Kind:** docs. +- **Cost:** `PERSIST_TUTORIAL.md`; none. + +## Where we already do better + +1. **Listener isolation** (finding 1): ours is the 3.0 behaviour minus the + rethrow, and far better than 2.1.15. +2. **Schema version and migration.** Legend has none. The only version is a + marker for the serialiser's own format, `__LSFormat: 1` in the metadata + record (3.0 `persistFormat.ts:5-9, 44-50`), used to decide how to revive + dates. An app that renames a field has to do it inside `transform.load` + without being told which version it is reading. `grep -rn migrat src` finds + nothing relevant in either version. Ours: `version`, `migrate`, `merge` + (`persist.ts:310-315`). +3. **Expiry.** No TTL in Legend (grep for `expire`, `ttl` in the persist and sync + folders: no match). Ours: `expireIn`, `clearOnExpire`. +4. **An edit made before the stored data arrives.** Legend refuses to save it: + it logs "An observable was changed before being loaded from persist" and + returns, so the change stays in memory and reaches storage only if a later + change happens (2.1.15 `persistObservable.ts:230-235`; 3.0 + `syncObservable.ts:569-576, 680-688`). Ours holds the save until the read + settles and then writes the merged state (`persist.ts:235-244, 436-439`). +5. **A corrupt record.** Port P1: both libraries fall back to the defaults and + overwrite the bad record on the next save. Legend says so with one + `console.error` and no callback; the plugin catches the parse error itself + (`local-storage.ts:17-22`), so the application never hears. Ours calls + `onError(error, 'parse')` and sets `lastError` in the status. Neither keeps a + copy of the bad record. +6. **Write coalescing in 2.1.15.** Port P5: three writes in one tick give three + `setItem` calls in 2.1.15 (each write is its own queued change), one in 3.0 + (`mergeQueuedChanges`, `syncObservable.ts:406-431, 449`), and one in ours. In + 3.0 the first write after loading a record that predates the format marker + also writes a second key; a record already in the current format gets one. +7. **A handle with `dispose`.** Legend's local persistence cannot be detached + from an observable. +8. **Cross-tab sync, debounce for local writes and `skipHydration`** have no + counterpart. + +## Our options next to Legend's + +Options of ours that look unusual beside it, and what that tells us: + +| Option | In Legend | Reading | +| --------------------------- | ------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `version`, `migrate` | Absent | Not unusual overall (Zustand has both); a real advantage over Legend. | +| `merge` | Always a merge into the initial value; no choice | Ours is an option with one non-default value; fine. | +| `expireIn`, `clearOnExpire` | Absent | The only options with no precedent in the libraries read so far. Two options for one concept; a single `expireIn` with the clearing as the default is worth a stage 3 look. | +| `syncTabs` | Absent | A browser-only listener behind a boolean. Keep. | +| `skipHydration` | Absent (hydration is synchronous) | Exists because of finding 4; the two decisions go together. | +| `debounce` | Remote only (`debounceSet`); local writes are immediate | Brings the unload gap of finding 5. | +| `properties` allow-list | Absent (whole observable; `fieldTransforms` can drop a field) | Useful; finding 52 and 55 of stage 1 are its edge cases. Consider throwing on an entry that is neither a key nor a complete transform. | + +Features a user of ours would miss, most to least likely: + +1. A synchronous first render with saved data (finding 4). +2. Dates, maps and sets saved without a transform (finding 8). +3. Ready-made backends for AsyncStorage, MMKV, IndexedDB, SQLite (finding 7). +4. A pause switch and an in-flight flag (finding 9). +5. Remote sync with retry, back-off and replay of pending changes. Out of scope. + +## Stage 1 findings with a counterpart + +| Stage 1 finding | Legend-State | +| ----------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | +| 18 (sync subscriber that writes recurses) | A write inside a listener is applied and the written node's listeners run (port B7, both versions: order `a,b`). No loop guard was looked for. | +| 22 (re-entrant write delivers a snapshot twice) | No snapshots; not comparable. | +| 23 (rejected promise from a subscriber) | Listener return values are ignored in `batchNotifyChanges`; an async listener's rejection is unhandled, as in ours. Reading only. | +| 43 (a setter is not a transaction) | Legend has no class setters. Its equivalent is a computed's `set`; not read. | +| 52 (a getter named in `properties` is saved) | No allow-list, so no counterpart. Computeds are not persisted unless they are the persisted observable. Not tested. | +| 53 (an array passes the envelope check) | Any JSON root is accepted; falsy roots replace the default, objects and arrays merge (`syncObservable.ts:3390-3394`). No envelope to check. | +| 54 (dead code in `persist.ts`) | See finding 6; Legend's flag approach has none of these blocks but moves the logic into the core. | +| 55 (malformed `properties` entry ignored) | No allow-list. | +| 56 (when a debounced save runs against a read) | Legend drops a change made before load with a console error (finding in "Where we already do better", item 4); it has no local debounce. | + +## The eight API questions, from Legend's point of view + +1. **Should synchronous notification be the default for `subscribe()`?** Legend's + default is synchronous per write (port B1), and it needs `batch()` and + per-write batching inside `set` to make that tolerable. Its persistence + layer then adds its own microtask queue on top (3.0 + `syncObservable.ts:3244-3246`, 2.1.15 `persistObservable.ts:498-499`), which + is what we have built in as the default. Legend is evidence that synchronous + delivery is workable; it is not evidence that ordinary subscribers should + have it, because Legend's framework bindings are the ones that want it. No + stronger position. +2. **Writes outside a method, and `batch()`.** Legend has no methods: every + write is outside one, and nothing warns. Grouping is explicit, with `batch()` + exported and used inside the library for compound writes (`assign`, + persistence restores). `batch` belongs in the API there because the default + is per-write notification; for us the default already coalesces, so `batch` + serves sync subscribers and framework bindings. Nested batches fold into the + outermost (port B3), a throwing body still notifies and rethrows (port B4), + and a write undone inside a batch is silent in 3.0 only (port B6, finding 2). Neither + library groups an `async` body (finding 3). Position: keep `batch`; do not + try to group automatically. +3. **Snapshot getters as enumerable own accessors.** No position (no snapshots). +4. **Arrow-function methods and `#private` fields.** No position (Legend is not + class based). +5. **Native `Map` and `Set` reactive directly.** Legend observes native Map and + Set and persists them as tagged JSON (3.0 `globals.ts:49-58`; + `batching.ts` handles `Map` in its previous-value rebuild). I did not test + its Map reactivity. No stronger position. +6. **Opt-in or opt-out for nested class instances.** Legend wraps plain objects + and arrays by default and has an opaque marker to exclude one (a symbol check + in `updateNodes`, 2.1.15 `ObservableObject.ts:105-135`; `ObservableHint.ts` + in 3.0, not read). That is opt-out. Reading only. +7. **Entry points and names consistent across the five frameworks.** No + position. Observation only: Legend splits by concern (`/persist`, `/sync`, + `/persist-plugins/*`), not by framework. +8. **Development-only diagnostics.** Legend has about 30 branches gated on + `process.env.NODE_ENV === 'development'` (sometimes also `'test'`), each with + a `[legend-state]` prefix: a circular reference, an `HTMLElement` set into + state, `toggle` on a non-boolean, duplicate ids in an array, an observable + changed before its persistence loaded, a missing `name` on `persist`, an + unfinished batch (3.0 `grep` result, listed under files read). Transfers to + us: (a) a dev warning when `batch()` receives a promise (finding 3); (b) the + "changed before loaded" warning is not needed because we defer the save; (c) + a missing `name` is already a type error for us. The watchdog timer for an + unbalanced batch does not apply. Bigger point: the split is a plain + `NODE_ENV` read, so the checks vanish from a minified build, which is what + the stage 3 diagnostics work needs. Both versions call `process.env` inline; + 3.0 caches the result in a variable for speed (`globals.ts:88-92`). + +## What I verified by running code, and what I only read + +Ran (appendix): batching behaviour on 2.1.15, 3.0.0-next.1 and ours (B1 to B8); +listener failure in 2.1.15 in an isolated process; persistence behaviour on all +three (P1 to P5). The localStorage in the ports is a map-backed stand-in with the +`getItem`, `setItem` and `removeItem` calls the plugins use; no browser was +involved, so nothing was tested about real `storage` events, quotas, or +page unload. + +Only read: every claim about `syncObservable.ts` outside the lines listed +(pending-change replay, `lastSync`, retry, `mode`), the Firebase, IndexedDB, +MMKV, AsyncStorage and SQLite plugins, `isPersistEnabled` behaviour, the Map +reactivity in Legend, `ObservableHint`, and finding 2's argument about snapshot +identity in our core. + +Not done: Legend's website documentation was not consulted, per the brief. + +## Appendix: ported tests and their output + +Ports were run with `bun `. The two Legend versions use separate folders +under the scratch directory, `ports/` (2.1.15) and `ports3/` (3.0.0-next.1); +the ours ports import our source by absolute path. + +### Batching, Legend-State + +The same file runs against each version. B5 comes last because in 2.1.15 it breaks the batcher for the rest of the process (a first run with it in the middle showed this). + +`ports/batch.legend.ts` + +```ts +import {observable, batch} from '@legendapp/state'; +const flush = () => new Promise((r) => setTimeout(r, 0)); +const pkg = JSON.parse( + await Bun.file( + import.meta.dir + '/node_modules/@legendapp/state/package.json', + ).text(), +).version; +console.log('legend-state', pkg); + +// B1 write outside batch: when does the listener run? +{ + const o = observable({a: 0}); + let calls = 0; + o.onChange(() => calls++); + o.a.set(1); + console.log( + 'B1 write outside batch, listener calls right after write:', + calls, + ); +} +// B2 three writes in a batch +{ + const o = observable({a: 0, b: 0, c: 0}); + const seen: number[] = []; + o.onChange((p) => seen.push(p.changes.length)); + batch(() => { + o.a.set(1); + o.b.set(1); + o.c.set(1); + }); + console.log( + 'B2 three writes in batch: calls, changes per call =', + JSON.stringify(seen), + ); +} +// B3 nested batch +{ + const o = observable({a: 0, b: 0}); + let calls = 0; + o.onChange(() => calls++); + batch(() => { + batch(() => { + o.a.set(1); + }); + console.log('B3 after inner batch, calls =', calls); + o.b.set(1); + }); + console.log('B3 after outer batch, calls =', calls); +} +// B4 throwing batch body +{ + const o = observable({a: 0}); + let calls = 0; + o.onChange(() => calls++); + let thrown: unknown; + try { + batch(() => { + o.a.set(1); + throw new Error('boom'); + }); + } catch (e) { + thrown = e; + } + console.log( + 'B4 throwing batch: error propagated =', + (thrown as Error)?.message, + ', listener calls =', + calls, + ); +} +// B6 revert inside batch +{ + const o = observable({a: 0}); + let calls = 0; + o.onChange(() => calls++); + batch(() => { + o.a.set(1); + o.a.set(0); + }); + console.log('B6 a 0->1->0 inside batch: calls =', calls); +} +// B7 write inside listener +{ + const o = observable({a: 0, b: 0}); + const log: string[] = []; + o.a.onChange(() => { + log.push('a'); + o.b.set(5); + }); + o.b.onChange(() => log.push('b')); + o.a.set(1); + console.log('B7 write in listener, order =', log.join(',')); +} +// B5 throwing listener: do others run, do later writes notify? +{ + const o = observable({a: 0}); + let second = 0, + later = 0; + o.onChange(() => { + throw new Error('listener boom'); + }); + o.onChange(() => second++); + let err: unknown; + try { + o.a.set(1); + } catch (e) { + err = e; + } + console.log( + 'B5 throwing listener: write threw =', + (err as Error)?.message, + ', second listener ran =', + second, + ); + const o2 = observable({x: 0}); + o2.onChange(() => later++); + try { + o2.x.set(1); + } catch {} + try { + o2.x.set(2); + } catch {} + console.log( + 'B5 a different observable afterwards: listener calls (expect 2) =', + later, + ); +} +``` + +Output, `batch.v2.txt`: + +```text +legend-state 2.1.15 +B1 write outside batch, listener calls right after write: 1 +B2 three writes in batch: calls, changes per call = [3] +B3 after inner batch, calls = 0 +B3 after outer batch, calls = 1 +B4 throwing batch: error propagated = boom , listener calls = 1 +B6 a 0->1->0 inside batch: calls = 1 +B7 write in listener, order = a,b +B5 throwing listener: write threw = listener boom , second listener ran = 0 +B5 a different observable afterwards: listener calls (expect 2) = 0 +``` + +Output, `batch.v3.txt`: + +```text +legend-state 3.0.0-next.1 +B1 write outside batch, listener calls right after write: 1 +B2 three writes in batch: calls, changes per call = [3] +B3 after inner batch, calls = 0 +B3 after outer batch, calls = 1 +B4 throwing batch: error propagated = boom , listener calls = 1 +B6 a 0->1->0 inside batch: calls = 0 +B7 write in listener, order = a,b +B5 throwing listener: write threw = listener boom , second listener ran = 1 +B5 a different observable afterwards: listener calls (expect 2) = 2 +``` + +### A throwing listener in 2.1.15, alone in its process + +`ports/b5.iso.ts` + +```ts +import {observable} from '@legendapp/state'; +const o = observable({a: 0}); +let second = 0; +o.onChange(() => { + throw new Error('boom'); +}); +o.onChange(() => second++); +try { + o.a.set(1); +} catch (e) { + console.log('threw', (e as Error).message); +} +const p = observable({x: 0}); +let later = 0; +p.onChange(() => later++); +p.x.set(1); +p.x.set(2); +console.log( + 'second listener ran:', + second, + '| unrelated observable listener calls after two writes (expect 2):', + later, +); +setTimeout( + () => console.log('after a macrotask, unrelated observable calls:', later), + 5, +); +``` + +Output, `b5iso.v2.txt`: + +```text +threw boom +second listener ran: 0 | unrelated observable listener calls after two writes (expect 2): 0 +after a macrotask, unrelated observable calls: 0 +``` + +### Batching, ours + +B5 on ours has `write threw = undefined` because `deliver()` sends the error to `console.error`, which the script counts. + +`ports/batch.ours.ts` + +```ts +import { + batch, + createClassyStore, + subscribe, +} from '/packages/classy-store/src/index.ts'; +const flush = () => new Promise((r) => setTimeout(r, 0)); +const origError = console.error; +let loggedErrors = 0; +console.error = () => { + loggedErrors++; +}; +const make = () => createClassyStore({a: 0, b: 0, c: 0}); +// B1 +{ + const s = make(); + let sync = 0, + async_ = 0; + subscribe(s, () => sync++, {sync: true}); + subscribe(s, () => async_++); + s.a = 1; + console.log( + 'B1 write outside batch: sync subscriber calls right after =', + sync, + ', default subscriber calls right after =', + async_, + ); + await flush(); + console.log('B1 default subscriber after a tick =', async_); +} +// B2 +{ + const s = make(); + let sync = 0, + def = 0; + subscribe(s, () => sync++, {sync: true}); + subscribe(s, () => def++); + batch(() => { + s.a = 1; + s.b = 1; + s.c = 1; + }); + await flush(); + console.log( + 'B2 three writes in batch: sync calls =', + sync, + ', default calls =', + def, + '(no change list is passed)', + ); +} +// B3 +{ + const s = make(); + let calls = 0; + subscribe(s, () => calls++, {sync: true}); + batch(() => { + batch(() => { + s.a = 1; + }); + console.log('B3 after inner batch, sync calls =', calls); + s.b = 1; + }); + console.log('B3 after outer batch, sync calls =', calls); +} +// B4 +{ + const s = make(); + let calls = 0; + subscribe(s, () => calls++, {sync: true}); + let thrown: any; + try { + batch(() => { + s.a = 1; + throw new Error('boom'); + }); + } catch (e) { + thrown = e; + } + console.log( + 'B4 throwing batch: error propagated =', + thrown?.message, + ', sync calls =', + calls, + ); +} +// B5 +{ + const s = make(); + let second = 0; + const s2 = make(); + let later = 0; + subscribe( + s, + () => { + throw new Error('listener boom'); + }, + {sync: true}, + ); + subscribe(s, () => second++, {sync: true}); + let err: any; + try { + s.a = 1; + } catch (e) { + err = e; + } + subscribe(s2, () => later++, {sync: true}); + s2.a = 1; + s2.a = 2; + console.log( + 'B5 throwing listener: write threw =', + err?.message, + ', second listener ran =', + second, + ', console.error calls =', + loggedErrors, + ', other store calls (expect 2) =', + later, + ); +} +// B6 +{ + const s = make(); + let calls = 0; + subscribe(s, () => calls++, {sync: true}); + batch(() => { + s.a = 1; + s.a = 0; + }); + console.log('B6 a 0->1->0 inside batch: sync calls =', calls); +} +// B7 +{ + const s = make(); + const log: string[] = []; + subscribe( + s, + () => { + log.push('first'); + if (log.length === 1) s.b = 5; + }, + {sync: true}, + ); + s.a = 1; + console.log('B7 write in listener, log =', log.join(',')); +} +console.error = origError; +``` + +Output, `batch.ours.txt`: + +```text +B1 write outside batch: sync subscriber calls right after = 1 , default subscriber calls right after = 0 +B1 default subscriber after a tick = 1 +B2 three writes in batch: sync calls = 1 , default calls = 1 (no change list is passed) +B3 after inner batch, sync calls = 0 +B3 after outer batch, sync calls = 1 +B4 throwing batch: error propagated = boom , sync calls = 1 +B5 throwing listener: write threw = undefined , second listener ran = 1 , console.error calls = 1 , other store calls (expect 2) = 2 +B6 a 0->1->0 inside batch: sync calls = 1 +B7 write in listener, log = first,first +``` + +### `batch()` with an async function + +Outputs in order: 2.1.15, 3.0.0-next.1, ours. + +`ports/batch.async.legend.ts` + +```ts +import {observable, batch} from '@legendapp/state'; +const o = observable({a: 0, b: 0, c: 0}); +let calls = 0; +o.onChange(() => calls++); +const warn: any[] = []; +const w = console.warn; +console.warn = (...a) => warn.push(a); +const e = console.error; +console.error = (...a) => warn.push(a); +const p = batch(async () => { + o.a.set(1); + await null; + o.b.set(1); + o.c.set(1); +}); +console.log( + 'B8 async batch: calls right after batch() returned =', + calls, + '| returned a promise =', + p instanceof Promise, +); +await p; +await new Promise((r) => setTimeout(r, 5)); +console.log( + 'B8 after the awaited writes: calls =', + calls, + '| warnings =', + warn.length, +); +console.warn = w; +console.error = e; +``` + +`ports/batch.async.ours.ts` + +```ts +import { + batch, + createClassyStore, + subscribe, +} from '/packages/classy-store/src/index.ts'; +const s = createClassyStore({a: 0, b: 0, c: 0}); +let calls = 0; +subscribe(s, () => calls++, {sync: true}); +const warn: any[] = []; +const w = console.warn; +console.warn = (...a) => warn.push(a); +const e = console.error; +console.error = (...a) => warn.push(a); +const p = batch(async () => { + s.a = 1; + await null; + s.b = 1; + s.c = 1; +}); +console.log( + 'B8 async batch: sync calls right after batch() returned =', + calls, + '| returned a promise =', + p instanceof Promise, +); +await p; +await new Promise((r) => setTimeout(r, 5)); +console.log( + 'B8 after the awaited writes: sync calls =', + calls, + '| warnings =', + warn.length, +); +console.warn = w; +console.error = e; +``` + +Output, `async.v2.txt`: + +```text +B8 async batch: calls right after batch() returned = 1 | returned a promise = false +B8 after the awaited writes: calls = 3 | warnings = 0 +``` + +Output, `async.v3.txt`: + +```text +B8 async batch: calls right after batch() returned = 1 | returned a promise = false +B8 after the awaited writes: calls = 3 | warnings = 0 +``` + +Output, `async.ours.txt`: + +```text +B8 async batch: sync calls right after batch() returned = 1 | returned a promise = true +B8 after the awaited writes: sync calls = 3 | warnings = 0 +``` + +### Persistence, Legend-State 2.1.15 + +`ports/persist.legend.v2.ts` + +```ts +// Legend-State 2.1.15 +const store = new Map(); +let writes = 0; +const writeLog: string[] = []; +(globalThis as any).localStorage = { + getItem: (k: string) => (store.has(k) ? store.get(k)! : null), + setItem: (k: string, v: string) => { + writes++; + writeLog.push(k); + store.set(k, v); + }, + removeItem: (k: string) => { + store.delete(k); + }, +}; +const {observable} = await import('@legendapp/state'); +const {persistObservable} = await import('@legendapp/state/persist'); +const {ObservablePersistLocalStorage} = await import( + '@legendapp/state/persist-plugins/local-storage' +); +const flush = () => new Promise((r) => setTimeout(r, 20)); +const errs: unknown[][] = []; +const origErr = console.error; +console.error = (...a) => errs.push(a); +const mk = (name: string, init: any) => { + const o = observable(init); + persistObservable(o, { + local: name, + pluginLocal: ObservablePersistLocalStorage, + }); + return o; +}; + +// P1 corrupt record, then a save +store.set('p1', '{not json'); +{ + const o = mk('p1', {count: 0}); + console.log( + 'P1 value right after attach =', + JSON.stringify(o.peek()), + '| console.error calls =', + errs.length, + '| error text =', + String(errs[0]?.[0]), + ); + await flush(); + o.count.set(5); + await flush(); + console.log('P1 stored after a later save =', store.get('p1')); +} +// P2 synchronous hydration +store.set('p2', JSON.stringify({count: 7})); +{ + const o = mk('p2', {count: 0}); + console.log('P2 value immediately after attach (no await) =', o.peek().count); +} +// P3 stored record from an older shape holds an unknown key +store.set('p3', JSON.stringify({old: 1, count: 7})); +{ + const o = mk('p3', {count: 0}); + await flush(); + console.log( + 'P3 keys after hydrating {old:1,count:7} over {count:0} =', + JSON.stringify(Object.keys(o.peek())), + ); +} +// P4 what is written for one changed field +store.set('p4', JSON.stringify({a: 0, b: 0})); +{ + const o = mk('p4', {a: 0, b: 0}); + await flush(); + store.set('p4', JSON.stringify({a: 0, b: 99})); // another tab writes + o.a.set(1); + await flush(); + console.log( + 'P4 after another tab wrote b=99 and this tab set a=1, stored =', + store.get('p4'), + ); +} +// P5 write per mutation: 3 sets in separate ticks vs same tick +store.set('p5', JSON.stringify({a: 0})); +{ + const o = mk('p5', {a: 0}); + await flush(); + writes = 0; + writeLog.length = 0; + o.a.set(1); + o.a.set(2); + o.a.set(3); + await flush(); + console.log( + 'P5 three writes in one tick -> storage setItem calls =', + writes, + JSON.stringify(writeLog), + ); +} +console.error = origErr; +``` + +Output, `persist.v2.txt`: + +```text +P1 value right after attach = {"count":0} | console.error calls = 1 | error text = [legend-state] ObservablePersistLocalStorage failed to parse +P1 stored after a later save = {"count":5} +P2 value immediately after attach (no await) = 7 +P3 keys after hydrating {old:1,count:7} over {count:0} = ["count","old"] +P4 after another tab wrote b=99 and this tab set a=1, stored = {"a":1,"b":0} +P5 three writes in one tick -> storage setItem calls = 3 ["p5","p5","p5"] +``` + +### Persistence, Legend-State 3.0.0-next.1 + +Differs from the 2.1.15 file in the import, the attach call, and the added P5b. + +`ports3/persist.legend.v3.ts` + +```ts +// Legend-State 3.0.0-next.1 +const store = new Map(); +let writes = 0; +const writeLog: string[] = []; +(globalThis as any).localStorage = { + getItem: (k: string) => (store.has(k) ? store.get(k)! : null), + setItem: (k: string, v: string) => { + writes++; + writeLog.push(k); + store.set(k, v); + }, + removeItem: (k: string) => { + store.delete(k); + }, +}; +const {observable} = await import('@legendapp/state'); +const {syncObservable} = await import('@legendapp/state/sync'); +const {ObservablePersistLocalStorage} = await import( + '@legendapp/state/persist-plugins/local-storage' +); +const flush = () => new Promise((r) => setTimeout(r, 20)); +const errs: unknown[][] = []; +const origErr = console.error; +console.error = (...a) => errs.push(a); +const mk = (name: string, init: any) => { + const o = observable(init); + syncObservable(o, {persist: {name, plugin: ObservablePersistLocalStorage}}); + return o; +}; + +// P1 corrupt record, then a save +store.set('p1', '{not json'); +{ + const o = mk('p1', {count: 0}); + console.log( + 'P1 value right after attach =', + JSON.stringify(o.peek()), + '| console.error calls =', + errs.length, + '| error text =', + String(errs[0]?.[0]), + ); + await flush(); + o.count.set(5); + await flush(); + console.log('P1 stored after a later save =', store.get('p1')); +} +// P2 synchronous hydration +store.set('p2', JSON.stringify({count: 7})); +{ + const o = mk('p2', {count: 0}); + console.log('P2 value immediately after attach (no await) =', o.peek().count); +} +// P3 stored record from an older shape holds an unknown key +store.set('p3', JSON.stringify({old: 1, count: 7})); +{ + const o = mk('p3', {count: 0}); + await flush(); + console.log( + 'P3 keys after hydrating {old:1,count:7} over {count:0} =', + JSON.stringify(Object.keys(o.peek())), + ); +} +// P4 what is written for one changed field +store.set('p4', JSON.stringify({a: 0, b: 0})); +{ + const o = mk('p4', {a: 0, b: 0}); + await flush(); + store.set('p4', JSON.stringify({a: 0, b: 99})); // another tab writes + o.a.set(1); + await flush(); + console.log( + 'P4 after another tab wrote b=99 and this tab set a=1, stored =', + store.get('p4'), + ); +} +// P5 write per mutation: 3 sets in separate ticks vs same tick +store.set('p5', JSON.stringify({a: 0})); +{ + const o = mk('p5', {a: 0}); + await flush(); + writes = 0; + writeLog.length = 0; + o.a.set(1); + o.a.set(2); + o.a.set(3); + await flush(); + console.log( + 'P5 three writes in one tick -> storage setItem calls =', + writes, + JSON.stringify(writeLog), + ); +} +console.error = origErr; +// P5b same as P5 but over a record already written by Legend (not a legacy record), second round of writes +{ + const o = mk('p5', {a: 0}); + await flush(); + writes = 0; + writeLog.length = 0; + o.a.set(10); + o.a.set(11); + o.a.set(12); + await flush(); + console.log( + 'P5b three more writes in one tick, record already in the current format -> storage setItem calls =', + writes, + JSON.stringify(writeLog), + ); +} +``` + +Output, `persist.v3.txt`: + +```text +P1 value right after attach = {"count":0} | console.error calls = 1 | error text = [legend-state] ObservablePersistLocalStorageBase failed to parse +P1 stored after a later save = {"count":5} +P2 value immediately after attach (no await) = 7 +P3 keys after hydrating {old:1,count:7} over {count:0} = ["count","old"] +P4 after another tab wrote b=99 and this tab set a=1, stored = {"a":1,"b":0} +P5 three writes in one tick -> storage setItem calls = 2 ["p5","p5__m"] +P5b three more writes in one tick, record already in the current format -> storage setItem calls = 1 ["p5"] +``` + +### Persistence, ours + +P1 in ours reads the status through `getSnapshot()`; the other ports use `onError` and storage contents. + +`ports/persist.ours.ts` + +```ts +import {createClassyStore} from '/packages/classy-store/src/index.ts'; +import {persist} from '/packages/classy-store/src/utils/persist/persist.ts'; +const store = new Map(); +let writes = 0; +const writeLog: string[] = []; +const storage = { + getItem: (k: string) => (store.has(k) ? store.get(k)! : null), + setItem: (k: string, v: string) => { + writes++; + writeLog.push(k); + store.set(k, v); + }, + removeItem: (k: string) => { + store.delete(k); + }, +}; +const flush = () => new Promise((r) => setTimeout(r, 20)); +const errors: Array<[unknown, string]> = []; +const mk = (name: string, init: any) => { + const s = createClassyStore(init); + const h = persist(s, { + name, + storage, + onError: (e, op) => errors.push([e, op]), + }); + return {s, h}; +}; +// P1 +store.set('p1', '{not json'); +{ + const {s, h} = mk('p1', {count: 0}); + await h.hydrated; + console.log( + 'P1 value after hydrated =', + JSON.stringify(s), + '| onError calls =', + errors.length, + 'operation =', + errors[0]?.[1], + '| status.lastError.operation =', + h.getSnapshot?.().lastError?.operation, + ); + s.count = 5; + await flush(); + console.log('P1 stored after a later save =', store.get('p1')); +} +// P2 +store.set('p2', JSON.stringify({version: 0, state: {count: 7}})); +{ + const {s, h} = mk('p2', {count: 0}); + console.log('P2 value immediately after attach (no await) =', s.count); + await h.hydrated; + console.log('P2 value after hydrated =', s.count); +} +// P3 +store.set('p3', JSON.stringify({version: 0, state: {old: 1, count: 7}})); +{ + const {s, h} = mk('p3', {count: 0}); + await h.hydrated; + console.log( + 'P3 keys after hydrating {old:1,count:7} over {count:0} =', + JSON.stringify(Object.keys(s)), + ); +} +// P4 +store.set('p4', JSON.stringify({version: 0, state: {a: 0, b: 0}})); +{ + const {s, h} = mk('p4', {a: 0, b: 0}); + await h.hydrated; + store.set('p4', JSON.stringify({version: 0, state: {a: 0, b: 99}})); + s.a = 1; + await flush(); + console.log( + 'P4 after another tab wrote b=99 and this tab set a=1 (no syncTabs), stored =', + store.get('p4'), + ); +} +// P5 +store.set('p5', JSON.stringify({version: 0, state: {a: 0}})); +{ + const {s, h} = mk('p5', {a: 0}); + await h.hydrated; + await flush(); + writes = 0; + writeLog.length = 0; + s.a = 1; + s.a = 2; + s.a = 3; + await flush(); + console.log( + 'P5 three writes in one tick -> storage setItem calls =', + writes, + JSON.stringify(writeLog), + ); +} +``` + +Output, `persist.ours.txt`: + +```text +P1 value after hydrated = {"count":0} | onError calls = 1 operation = parse | status.lastError.operation = parse +P1 stored after a later save = {"version":0,"state":{"count":5}} +P2 value immediately after attach (no await) = 0 +P2 value after hydrated = 7 +P3 keys after hydrating {old:1,count:7} over {count:0} = ["count"] +P4 after another tab wrote b=99 and this tab set a=1 (no syncTabs), stored = {"version":0,"state":{"a":1,"b":0}} +P5 three writes in one tick -> storage setItem calls = 1 ["p5"] +``` diff --git a/review/stage-2/mobx.md b/review/stage-2/mobx.md new file mode 100644 index 00000000..22d6b364 --- /dev/null +++ b/review/stage-2/mobx.md @@ -0,0 +1,3651 @@ +# Stage 2: MobX + +Read-only comparison of `@codebelt/classy-store` with MobX, for stage 3 of the +pre-1.0 review. Nothing in the repository was changed apart from this file. + +## The library and what was read + +- **Library:** MobX 7.1.7, the `latest` tag on npm on 2026-11-18. +- **Source:** `github.com/mobxjs/mobx` at tag `mobx@7.1.7`, commit + `f8cf51330d278ad45a3c0c70e35a79f420555044` (2026-11-13). +- **What ran:** the published `mobx@7.1.7` package in a scratch folder, on Bun + 1.4.4. With `NODE_ENV` unset Bun loads `dist/mobx.cjs.development.js`, so + the development checks are on unless a block says otherwise. +- **Our side:** `release/1.0` at `825ba2d`. The library source is unchanged + since `9ab9744`. Scripts import `packages/classy-store/src/index.ts` + directly. + +Files read in full, all under `packages/mobx/src/`: + +- `core/`: `atom.ts`, `derivation.ts`, `computedvalue.ts`, `observable.ts`, + `action.ts`, `reaction.ts`, `globalstate.ts`. There is no + `core/transaction.ts`: batching is `startBatch` and `endBatch` in + `core/observable.ts`, and the public wrapper is `api/transaction.ts`. +- `types/`: `observableobject.ts`, `observablearray.ts`, `dynamicobject.ts`, + `modifiers.ts`, `observablevalue.ts`, `autoannotation.ts`, + `actionannotation.ts`, `computedannotation.ts`, `observableannotation.ts`, + `overrideannotation.ts`. +- `api/`: `makeObservable.ts`, `action.ts`, `transaction.ts`, `autorun.ts`, + `observable.ts`, `configure.ts`, `tojs.ts`. +- `errors.ts`. + +Read in part: `api/extendobservable.ts`, `api/flow.ts`, `api/decorators.ts` +(one function), `scripts/create-rollup-config.mjs` (the development flag), and +the 7.0.0 entry of `packages/mobx/CHANGELOG.md`. + +Not read: `observablemap.ts` and `observableset.ts` beyond their class +declarations, `spy.ts`, the intercept and observe utilities, and the React +binding packages. + +## How MobX differs, in short + +Three facts bound what can be taken from it. + +1. **Every observable property is its own node.** A read reports to one global + "derivation that is running now". A write marks that property's observers + stale. Computed values recompute when read; reactions run when the + outermost batch ends. +2. **A class instance is not wrapped.** `makeObservable(this)` in the + constructor replaces each field with an accessor pair on the instance + itself. Only plain objects and arrays get a Proxy, and those are copies of + what the caller passed in. +3. **There are no snapshots, versions or parent links.** `toJS` copies the + whole tree on every call. + +So MobX has nothing to say about structural sharing or `ownership.ts`. It has +a great deal to say about getters, transactions, subscriber delivery, +diagnostics and `this`. + +## Findings + +Each reproduction is an excerpt from the output of a script in "Ported tests" +at the end, where every script and its whole output are given. Where an +excerpt is abridged or relabelled, it says so. + +### 1. A getter records only what it reads on its own node + +**What they do.** There is one slot, `globalState.trackingDerivation` +(`core/globalstate.ts:43`). Every observable read calls `reportObserved` +(`core/observable.ts:177-205`), which appends the property's node to the +running derivation, whichever object the property belongs to. +`bindDependencies` (`core/derivation.ts:226-286`) then subscribes the +derivation to each one. A getter on one object that reads a field of another +object depends on it like on anything else. + +**What we do.** `recordDep` returns early unless the read happened on the node +that owns the getter (`core.ts:88-91`). Reads below an own child are covered, +because reading the child records a dependency on the version of its whole +subtree (`core.ts:93-101`). A read on any other node records nothing: another +store, or a child reached through a reference that was not read from `this` +during this run. + +**Difference in behaviour.** Script 03: + +```text +MobX observed [20,30] runs: 2 +Ours live [20,20] runs: 1 | first snapshot after: 30 +``` + +Our live getter keeps 20 for good, and the first snapshot disagrees with the +live store. This is the first two cases of stage 1 finding 36 and the note +under finding 28. + +**Proposal: adapt.** We cannot take per-property subscriptions, but we can +meet the rule "every reactive read during a getter is a dependency" with what +we have. When a read happens on a node other than the getter's own, record a +dependency on that node's version, once per node per run. Skip it when the +node was handed out, during this run, by a node that is already covered: that +is the case of `this.rows[0].price`, which the dependency on `this.rows` +covers today. A read into another store starts at that store's root, and +versions bubble up to the root, so one dependency on the foreign root covers +everything read below it. This is coarser than MobX (any write in the other +store invalidates the getter), and it is the granularity our child +dependencies have already. + +**Kind.** Bug. + +**Cost.** `core.ts` (`recordDep`, the `get` trap, `areDepsValid`) and +`core.types.ts`. Not breaking. The snapshot layer has the same gap and is +harder: `computeWithTracking` sees only reads on `this` (`snapshot.ts:80-91`), +and a snapshot getter that reads another store reads that store live. Risk: +one set lookup more per object a getter walks through, to be measured against +the "getter that sums 1,000 rows" baseline; and a reference to a detached, +suspended container needs `resumeScope()` before its version is compared +(`ownership.ts:147-156`). This needs a stage 3 spike. + +### 2. An inner getter that throws leaves no trace + +**What they do.** `trackDerivedFunction` runs the getter inside `try`, keeps +a thrown error as the result, and still binds the dependencies read before +the throw (`core/derivation.ts:181-192`). `ComputedValue.get` keeps that +result as its cached value and rethrows the cause on every read +(`core/computedvalue.ts:237-242`). The outer getter registers its dependency +on the inner one before the inner one computes: `reportObserved(this)` comes +before the computation in `get` (`computedvalue.ts:218`). When a dependency +throws while it is being re-checked, that counts as a change +(`derivation.ts:96-105`). + +**What we do.** `evaluateComputed` caches on normal return only +(`core.ts:189-195`), so a getter that throws keeps neither a result nor a +dependency list. The `get` trap records the dependency on a getter after +`evaluateComputed` has returned (`core.ts:467-476`), so when the inner getter +throws, the outer getter records nothing either. The snapshot layer has the +same order: `computeWithTracking` adds the dependency after `Reflect.get` +returns (`snapshot.ts:84-88`). + +**Difference in behaviour.** Script 02. A getter `safe` catches the error of +a getter `strict`, which throws until `ready` is set: + +```text +MobX observed ["fallback","ready"] runs of safe: 2 +Ours live ["fallback","fallback"] runs of safe: 1 | strict now: ready | fresh snapshot: ready +``` + +And for the getter that throws, read twice with nothing changed: + +```text +MobX observed: read again threw RangeError: not ready (run 1) {"strict":1,"outer":1} +Ours live: read again threw RangeError: not ready (run 2) {"strict":2,"outer":2} +``` + +MobX hands out the same error object until a dependency changes. We re-run +the body on every read. This is the last case of stage 1 finding 36. + +**Proposal: adopt the dependency, and treat caching the error as optional.** +The smallest fix is to record the dependency on the inner getter in a +`finally`, in the `get` trap and in `computeWithTracking`. `areDepsValid` +then finds no cache entry for the inner getter and answers "invalid" at +`core.ts:140`. Stage 1 finding 64 lists that line as unreachable; with this +fix it is reached and needed. The outer getter re-runs while the inner one +throws, and settles once it returns. Caching the error together with its +dependencies, as MobX does, also stops the body from re-running on each read. +If that is taken, an error that recorded no dependency must not be cached, or +it would stay for good. A dependency that throws while it is validated should +count as changed, as in MobX. + +**Kind.** Bug. + +**Cost.** `core.ts` (the `get` trap; `evaluateComputed` and `ComputedEntry` +if errors are cached) and `snapshot.ts` (`computeWithTracking`, +`areMemoizedDepsValid`). Not breaking. It changes the two pinned tests under +"a getter that catches the error of another getter" +(`core.characterisation.getters.test.ts:1270-1300`), and, with error caching, +"runs its body and throws a new error on every read" (`:1161`). Risk low. + +### 3. Every read walks the dependency lists again, and a stale read re-runs every level + +**What they do.** Each derivation holds a state: up to date, possibly stale, +or stale (`core/derivation.ts:11-29`). A write pushes "stale" to the direct +observers and "possibly stale" on through computed values +(`core/observable.ts:230-282`). Reading an up-to-date computed costs one +comparison (`shouldCompute`, `derivation.ts:78-80`). A possibly stale one +reads its computed dependencies again, in the order they were first read. +Each of those validates itself, and the outer one recomputes only if one of +them produced a different value (`derivation.ts:84-125`, +`computedvalue.ts:261-290`). + +**What we do.** No state is kept. Every read of a getter runs `areDepsValid` +over its whole list (`core.ts:166-169`). For a dependency on another getter it +runs `areDepsValid` on that getter's list, recursively (`core.ts:137-142`). +Two things follow. + +- Nothing remembers that a list was validated a moment ago. A getter reached + by two paths is validated twice, its dependencies four times, and so on. +- If the nested list is invalid, the outer getter is declared invalid at once + (`core.ts:141`), without asking whether the nested getter's value changed. + The snapshot layer already does this the MobX way: `areMemoizedDepsValid` + reads the getter and compares the value (`snapshot.ts:104-110`). + +**Difference in behaviour.** For the second point, script 01, with `c` +reading `b` reading `a`, where `a` returns `true` for every positive count. +The counts are how often each body has run. Three lines of the output, +relabelled: + +```text +MobX count 1 -> 2, read from the top by the autorun {"a":2,"b":1,"c":1} +Ours, live count 1 -> 2, then c read from the top {"a":2,"b":2,"c":2} +Ours, snapshot count 1 -> 2, then c read on the next snapshot {"a":2,"b":2,"c":1} +``` + +The live result is pinned as a `FINDING` at +`core.characterisation.getters.test.ts:133`. + +For the first point, script 07 builds a ladder: two getters per level, each +reading both getters of the level below. A "clean read" is a read of the top +getter when nothing has changed, so no getter body runs. The figures are from +that script's output, put side by side: + +```text +depth | ours: first read | ours: clean read | MobX observed: clean read + 8 | 0.09 ms | 0.03 ms | 0.00 ms + 12 | 0.42 ms | 0.30 ms | 0.00 ms + 16 | 2.27 ms | 1.57 ms | 0.01 ms + 18 | 6.51 ms | 4.12 ms | 0.00 ms + 200 | not run | not run | 0.00 ms +``` + +Our cost doubles with each level. Real getter graphs are shallow, so this is +the shape of the cost and not something a user is known to have hit. The +"read a cached getter" figure in the stage 1 baseline (57 ns against 32 ns for +a field) is the case with one dependency. + +**Proposal: adapt, in two steps.** + +1. In `areDepsValid`, validate a dependency on a getter by reading that + getter through its own memoization and comparing the value, in recorded + order, stopping at the first difference. That is `shouldCompute`, and it is + what `snapshot.ts` does. The recursive branch goes, and both layers give + the same run counts. +2. Keep one module-level write counter, bumped in `notifyMutation`, and stamp + each cache entry with the counter value at which it was last found valid. + A read at the same counter value returns at once. This is the counterpart + of MobX's "up to date" state without observer lists, and it limits + validation to once per getter per write. + +**Kind.** Performance, simplification. + +**Cost.** `core.ts` and `core.types.ts`. Not breaking. Step 1 changes the +pinned run counts at `core.characterisation.getters.test.ts:133`, and the +tracker stack must be set aside during validation, as MobX does +(`derivation.ts:87`). Step 2 changes one edge: today a live getter notices a +primitive written through the raw object, because a value dependency re-reads +the target (`core.ts:147-149`). With the counter it would notice only after +the next write through a proxy, which is how snapshots behave already (stage +1 finding 11). Risk medium. Measure with `bun run benchmark:core`. + +### 4. A setter is not a transaction + +**What they do.** A setter is wrapped in an action. For a getter and setter +pair, the `ComputedValue` constructor wraps the setter with `createAction` +(`core/computedvalue.ts:125-130`). For a setter on its own, the default +annotation does it (`types/autoannotation.ts:55-75`). An action opens a batch +(`core/action.ts:111`, `:150`), so reactions run once, after the setter +returns. + +**What we do.** The `set` trap passes an accessor on to `Reflect.set` with +the proxy as receiver and opens no transaction (`core.ts:413-418`). Methods +and array operations do open one (`core.ts:263-277`). + +**Difference in behaviour.** Script 05, a `full` setter that writes `first` +and `last`: + +```text +MobX reaction saw ["Grace Hopper"] | warnings: 0 +Ours sync subscriber saw ["Grace Lovelace","Grace Hopper"] +``` + +Every framework adapter subscribes synchronously, so a component can render +the half-applied name. Stage 1 finding 43. + +**Proposal: adopt.** Wrap the accessor branch of the `set` trap in the same +`transactionDepth++` and `settleTransaction()` pair that `transactional` uses. + +**Kind.** Bug. + +**Cost.** Three lines in `core.ts`. Not breaking. Changes the pinned tests at +`core.characterisation.getters.test.ts:1838` and `:1850`. Risk low. + +### 5. Delivery to subscribers: re-entrant writes, removed subscribers, runaway loops + +**What they do.** A reaction is queued, not called from the write. +`schedule_` pushes it onto `globalState.pendingReactions` and calls +`runReactions`, which returns at once if a batch is open or the queue is +already being drained (`core/reaction.ts:117-123`, `:275-281`). +`runReactionsHelper` drains the queue in a loop and stops after 100 rounds +with an error that names the reaction (`reaction.ts:271`, `:283-307`). +`runReaction_` checks `isDisposed` at the moment of the call (`:128-129`), and +runs the reaction only if it is stale (`:134`), so one that has already seen +the latest state is not run again. An error is caught per reaction, logged +with the reaction's name and handed to `onReactionError` handlers +(`:192-220`). If the action that caused the run threw as well, the reaction's +error is reduced to a warning, so the developer sees the first error first +(`core/action.ts:143-145`, `reaction.ts:205-208`). + +**What we do.** `notifyMutation` calls `deliver` from inside the write +(`core.ts:232`), so a subscriber that writes enters `deliver` again, +recursively. `deliver` copies the listeners first (`core.ts:318-320`) and +calls each copy without checking that it is still registered. Nothing bounds +the recursion or the chain of microtasks. A subscription has no record of what +it has already seen. + +**Difference in behaviour.** Scripts 05 and 11: + +```text +MobX the same autorun after an outside write: runs 99 | count 109 | errors: ["Reaction doesn't converge to a stable state after 100 iterations. Probably there is a cycle in the reactive function: Reaction[Autorun@4]"] | warnings: 1 distinct +Ours sync subscriber that always writes: calls 2993 | count 2993 | errors: ["RangeError: Maximum call stack size exceeded."] + +MobX re-entrant write, two reactions: ["first:1","second:2","first:2"] +Ours re-entrant write, two sync subscribers: ["first:1","first:2","second:2","second:2"] + +── a subscriber removed during delivery ── +MobX: ["first"] +Ours: ["first","second"] + +── a subscriber added after a write ── +MobX: early autorun saw [0,1] | autorun added after the write saw [1] | reaction() added after the write fired [] +Ours, sync, inside batch(): early subscriber calls 1 | subscriber added after the write, calls 1 +``` + +Stage 1 findings 18, 19, 20, 21 and 22. + +**Proposal: adapt.** Three parts, each with a MobX line behind it. + +1. **One loop.** While a delivery is running, a write adds its owners to the + pending set and returns; the running loop picks them up. Bound the loop + (MobX uses 100 rounds) and report through `console.error`, naming the + store. +2. **Check at the call.** Skip a listener that is no longer in its set. +3. **Give a subscription the version it last saw.** Record the node's version + when `subscribe()` is called and at each call of the listener, and skip a + call when the version has not moved. That removes the second delivery of + the same snapshot (finding 22) and the late subscriber that hears an + earlier write (finding 21). It is the counterpart of a reaction being up to + date. + +**Kind.** Bug, diagnostics. + +**Cost.** `core.ts` (`deliver`, `notifyMutation`, `settleTransaction`, +`flushNotifications`, `subscribe`), about 30 lines. No API change. The order +of calls changes when a subscriber writes: its write is delivered after the +current round, not inside it. Several pinned tests in +`core.characterisation.notifications.test.ts` change, and stage 3 should mark +the order across re-entrant writes as unspecified. Risk medium: every adapter +relies on synchronous delivery. Delivery stays synchronous; only re-entrancy +goes. + +### 6. A write outside a transaction: MobX warns, also after an `await` + +**What they do.** `enforceActions` defaults to "observed" +(`core/globalstate.ts:109`, `api/configure.ts:25-30`). Every write path calls +`checkIfStateModificationsAreAllowed` (`core/derivation.ts:133-151`; called +from `types/observablevalue.ts:116`, `types/observablearray.ts:175` and +`:317`, `types/observableobject.ts:312` and `:490`). In development, a write +to a value that has observers, made while no action is running, logs a +warning that names the field. It warns and does not throw, and it is compiled +out of the production build. An async method is an action only up to its +first `await`. For the rest MobX offers `runInAction`, and `flow`, which +drives a generator and wraps each resumed step in an action +(`api/flow.ts:83-86`). Writes inside a computed are disallowed by the same +check (`core/computedvalue.ts:295`). + +**What we do.** A direct write is allowed anywhere and notifies on its own +(`core.ts:225-233`). A method is a transaction for its synchronous part only +(`core.ts:263-277`); the comment on `batch` says so (`core.ts:286-287`). +Nothing reports either case. + +**Difference in behaviour.** Script 05. `load()` sets `loading`, awaits, then +sets `rows` and `loading`. The first line is abridged: the second warning is +the same text for `Loader@1.loading`. + +```text +MobX async method reaction saw ["true/0","true/3","false/3"] | warnings: ["[MobX] Since strict-mode is enabled, changing (observed) observable values without using an action is not allowed. Tried to modify: Loader@1.rows", ...] +MobX await + runInAction reaction saw ["true/3","false/6"] | warnings: 0 +MobX generator (flow) reaction saw ["true/6","false/9"] | warnings: 0 +Ours async method sync subscriber saw ["true/0","true/3","false/3"] | warnings: 0 +``` + +Both libraries deliver the state in between, `true/3`. MobX tells the +developer which field and which store. For a getter that writes (stage 1 +finding 39): + +```text +MobX: reads 1 | warnings: ["[MobX] Since strict-mode is enabled, changing (observed) observable values without using an action is not allowed. Tried to modify: Sneaky@13.reads"] +``` + +**Proposal: adapt, as an opt-in.** MobX's rule cannot be our default. A +direct write from an event handler is a documented way to use the store, and +every adapter subscribes synchronously, so "warn on a write outside a +transaction to a store that has synchronous subscribers" would fire on +ordinary code. As an opt-in development check it catches the `await` case +exactly as MobX does, because after an `await` the transaction depth is back +at zero. The warning for a write inside a getter has no such conflict and can +be on in every development build: it is a write while the tracker stack is +not empty. The decision belongs with API question 2. + +**Kind.** Diagnostics. + +**Cost.** `core.ts` (`notifyMutation`), a development build (finding 7), and +docs. Not breaking. Risk low. + +### 7. A development build + +**What they do.** The source uses a bare `__DEV__` +(`packages/mobx/src/global.d.ts`). The build writes a development file, a +minified production file, and ESM files that work in either mode by reading +`process.env.NODE_ENV` once, at module scope, under a private name +(`scripts/create-rollup-config.mjs:84-91`). The comment there gives two +reasons: reading `process.env` at every call site is slow in Node, and a +private name cannot collide with a consumer's own `__DEV__` define. The +CommonJS entry picks a file by `NODE_ENV` (`dist/index.js`). `die()` throws +the full text in development and "minified error nr: N" in production +(`src/errors.ts:93-104`). The published 7.1.7 files measure 184 KB for +development, and 48 KB minified or 14.7 KB gzipped for production. + +**What we do.** One build with no development branch (`REVIEW_PLAN.md`, +"Findings already in hand"). + +**Difference in behaviour.** Script 09, last block, run twice. The lines are +from the two outputs, labelled, with whitespace inside the getter text +trimmed: + +```text +NODE_ENV unset makeAutoObservable in a subclass: threw Error: [MobX] 'makeAutoObservable' can only be used for classes that don't have a superclass +NODE_ENV=production makeAutoObservable in a subclass: threw TypeError: Unable to delete property. + +NODE_ENV unset write outside an action, warnings: 1 +NODE_ENV=production write outside an action, warnings: 0 + +NODE_ENV unset cycle: threw Error: [MobX] Cycle detected in computation Cycle@19.a: get a() { return this.a + 1; } +NODE_ENV=production cycle: threw Error: [MobX] minified error nr: 32 ObservableObject.key,get a() { return this.a + 1; }. See mobx.js.org/errors +``` + +The first pair is a warning to us. A check that throws in development only +means the two builds fail in different ways. + +**Proposal: adapt.** Take the mechanism: one constant, resolved once, around +diagnostics that the minifier removes. Do not take the development-only +throws: in development, warn, and keep every thrown error the same in both +builds. At our size, 3.7 KB gzipped, numbered error codes are not worth +having. + +**Kind.** Diagnostics. + +**Cost.** The build configuration, the `exports` map if the split is made by +condition and not by `NODE_ENV`, the size script (the budgets are for the +production build), and CI. Not breaking. Risk: two builds to test. This +agrees with the Solid finding already in hand. + +### 8. `this`, arrow-function methods and `#private` fields + +**What they do.** MobX does not put a Proxy around a class instance. +`makeObservable(this, …)` or `makeAutoObservable(this)`, called in the +constructor, defines an accessor pair for each field on the instance itself +(`types/observableobject.ts:391-405`, one shared descriptor per key at +`:678-690`) and keeps the values in an administration object under a symbol +(`:661-668`). There is one object. `this` in the constructor, `this` in an +arrow function, `this` in a method that passes a `#private` brand check, and +the object given to consumers are all the same. + +- An arrow-function field is an own property that holds a function. It + becomes an observable property whose value is wrapped as an action + (`types/autoannotation.ts:85-93`, `types/modifiers.ts:48-54`). +- A prototype method is replaced on the prototype, once per class, by an + action wrapper (`types/actionannotation.ts:42-50`). It is not bound unless + `autoBind: true` is passed, which defines a bound copy on every instance + (`actionannotation.ts:31-35`, `:132-134`). +- A `#private` field is not observable through `makeObservable`, because it + cannot be enumerated. It is observable with a standard decorator, + `@observable accessor #x`, where MobX files it under a fresh symbol + (`api/decorators.ts:22-24`). + +**What we do.** `createClassyStore(instance)` wraps a finished instance. The +`get` trap binds every function to the proxy and caches the wrapper per key +(`core.ts:483-492`): that is `autoBind: true` for every method with no work +per instance and no change to the class. An arrow-function field captured the +raw instance when it was constructed, so its writes go around the `set` trap +(`CLAUDE.md`, "No arrow function methods"). A method or getter that touches +`#x` throws, because `this` is the proxy and the proxy does not carry the +field. + +**Difference in behaviour.** Scripts 04 and 08, a selection of lines: + +```text +── a write inside an arrow-function method ── +MobX: count 1 | reaction runs after one call: 1 | arrow field is an action: true | observable prop: true +Ours: count 1 | sync notifications: 0 | snapshot count: 0 | snapshot replaced: false + +── #private fields and methods ── +MobX: read and write through #private: 2 | reaction saw [2] +Ours: getter that reads #secret: threw TypeError: Cannot access invalid private field (evaluating 'this.#secret') +MobX @observable accessor #secret: reaction saw [2,4] + +── `this` kept by the constructor ── +MobX: write through the reference the constructor kept → reaction runs: 1 | same object: true +Ours: write through the reference the constructor kept → sync notifications: 0 | same object: false | live 5 | snapshot 0 + +── a method passed around without its object ── +MobX default : threw TypeError: undefined is not an object (evaluating 'this.count') +MobX autoBind: true : 1 | own property: true | stable identity: true +Ours : 1 | stable identity: true | prototype untouched: true +``` + +One MobX line needs a note. The getter that reads only `#secret` answered 2 +when the field held 2 and the right answer was 4. Without the decorator a +`#private` field does not throw in MobX, and it is not reactive either, so an +observed getter over it is stale. + +**Proposal: adapt, with a spike in stage 3.** What MobX shows is that arrow +functions and `#private` work when the reactive object exists before the +subclass's fields are initialised. For a Proxy store the counterpart is a +base class whose constructor returns the proxy. Script 10 does that with a +base class of four lines, on the unmodified library: + +```text +first snapshot, before any read through the store: rows frozen? false | row frozen? false +arrow-function method: count 1 | sync notifications 1 | snapshot count 1 +getter that reads #secret, live: 4 +getter that reads #secret, snapshot: threw TypeError: Cannot access invalid private field (evaluating 'this.#secret') +`this` kept by the constructor is the store: true +write through that reference: sync notifications 1 +``` + +So it works on the live store today, and two things stand in the way. + +- Class fields are defined on the proxy, not assigned, so they arrive at the + `defineProperty` trap, which links no child (stage 1 findings 1 and 45). + The first snapshot holds the raw, unfrozen array. Those findings have to be + fixed first. +- A snapshot is another object, so a getter that reads `#x` still throws + there. MobX has no answer to this, having no snapshots. `#private` state + would also stay invisible to snapshots, persistence and subscribers, as it + stays unobservable in MobX without the decorator. + +What MobX pays for its approach, and a base class would not: a call in every +constructor, no `makeAutoObservable` for a subclass +(`api/makeObservable.ts:46-48`), an `override` annotation per overridden +member (`types/overrideannotation.ts:15-31`), every annotated member made +non-configurable (`observableobject.ts:393`, `actionannotation.ts:143-150`), +and a changed class prototype. + +If a base class is not wanted, the cheap part of the lesson is a development +warning in `createClassyStore()`. An own property whose value is a function +with no `prototype` property is an arrow function or a bound function, and on +a class instance it is nearly always an arrow-function field. This last part +is my reasoning; MobX has no such warning because it has no such failure. + +**Kind.** API design, diagnostics. + +**Cost.** One new export and its docs, after the fixes for findings 1 and 45. +An addition, not a breaking change. Risk medium: `instanceof`, `new.target` +and `useLocalStore` need checking in the spike. + +### 9. Functions and classes held as data + +**What they do.** A function stored in observable state is wrapped once, +when it is written, and the wrapper is what the state holds +(`types/modifiers.ts:48-54`). Every read returns that wrapper. To hold a +value exactly as given, the field is annotated `observableRef` or +`observableShallow` (`modifiers.ts:85-88`, `api/observable.ts:63-68`). +`makeAutoObservable` leaves `constructor` out by name +(`api/makeObservable.ts:68`). + +**What we do.** We wrap on read. For an object, one wrapper per key is cached +(`core.ts:487-491`). For an array, every read makes a new wrapper, elements +included (`core.ts:486`). `constructor` is a function found through the +prototype, so it is wrapped as well. + +**Difference in behaviour.** Script 06: + +```text +── a function held in an array ── +MobX: same function on two reads: true | is the function that was stored: false | wrapped as an action: true | indexOf(first): -1 | indexOf(what was read): 1 +MobX observableShallow: is the function that was stored: true | indexOf(first): 0 +Ours: same function on two reads: false | is the function that was stored: false | indexOf(first): -1 | indexOf(what was read): -1 +── a class held in a store ── +MobX: [false,null] | new: threw TypeError: Cannot call a class constructor Model without |new| +MobX observableRef: [true,"model",true] +Ours: [false,null,false] +``` + +MobX has the same weakness for a class held as data, and a worse symptom. Its +answer is the opt-out. + +**Proposal: adapt.** + +1. Cache wrappers per function, in a `WeakMap` on the node, not per key. Array + reads become stable, and `indexOf`, `includes` and + `splice(indexOf(x), 1)` work on what was read (stage 1 finding 5). +2. Never wrap `constructor` (finding 42). +3. Give a class or a callback held as data a way out, as MobX does. We have a + rule of that shape already: a frozen object is a value. Extending it to a + frozen function would cover finding 6 with no new export. This third step + is my suggestion and not MobX's design. + +**Kind.** Bug. + +**Cost.** The `get` trap and `boundMethods` in `core.ts`. Not breaking. Risk +low for steps 1 and 2. The comment at `core.ts:485` says array methods are +left uncached on purpose and gives no reason; stage 3 should find it before +changing that. + +### 10. Key enumeration, `in`, `defineProperty` and freezing + +**What they do.** For a plain object, the Proxy has `has`, `ownKeys`, +`defineProperty` and `preventExtensions` traps next to `get`, `set` and +`deleteProperty` (`types/dynamicobject.ts:17-52`). + +- `ownKeys` reports one keys node per object as observed + (`types/observableobject.ts:609-612`). Adding or deleting a key reports it + as changed (`:544`, `:606`). +- `in`, and a read of a key that does not exist, subscribe to a boolean for + that one key, made on demand and dropped when nobody observes it (`has_`, + `:254-272`; `get_`, `:212-218`). +- `defineProperty` deletes, defines and notifies inside one batch + (`:307-357`). +- `preventExtensions`, which `Object.freeze` calls first, throws with an + explanation (`dynamicobject.ts:49-51`, `types/observablearray.ts:106-108`). + +A class instance has no Proxy, so none of this applies to it. MobX offers the +helpers `keys()` and `has()` for that case. + +**What we do.** The traps are `get`, `set`, `defineProperty` and +`deleteProperty` (`core.ts:405-525`). `Object.keys(this)` and `'x' in this` +inside a getter record nothing. `defineProperty` links nothing, bumps nothing +and notifies no one; it exists for freezing (`core.ts:502-513`). Freezing +through the store is supported, and that branch is where the hang of stage 1 +finding 66 begins. + +**Difference in behaviour.** Scripts 03 and 09. Each pair is what a getter +returned for `Object.keys(this)` and `'extra' in this`: at the start, after +`extra` was added, and after it was deleted. The last two lines are from +script 09, the second of them cut short here: + +```text +MobX observable(object) [[["a"],false],[["a","extra"],true],[["a"],false]] {"keys":3,"hasExtra":3} +MobX class, plain assignment [[["a"],false]] {"keys":1,"hasExtra":1} +MobX class, keys() and has() [[["a"],false],[["a","extra"],true]] {"keys":2,"hasExtra":2} +Ours live [[["a"],false],[["a"],false],[["a"],false]] {"keys":1,"hasExtra":1} +Ours snapshot [[],false] + +MobX: reaction saw [[["a"],null],[["a","b"],2]] +Object.freeze(store.config): threw Error: [MobX] Dynamic observable objects cannot be frozen. ... +``` + +A MobX class instance is as stale as our store here, which is the price of +having no Proxy around it. + +**Proposal.** + +- **Adopt** `has` and `ownKeys` traps that record getter dependencies. Our + counterpart of the keys node is a per-node counter bumped when a key is + added or removed. Our counterpart of the per-key boolean is a dependency + entry that checks `Reflect.has` again. The Vue report should have the + fuller design. MobX adds one detail: a read of a missing key should record + that the key was missing. That fixes stage 1 finding 32, where such a + getter re-runs on every read because `core.ts:147` treats a missing key as + always invalid. +- **Adopt** sending a data descriptor given to `defineProperty` down the same + path as `set` (findings 1, 45 and 71). +- **Consider** MobX's position on freezing: refuse `Object.freeze(store)` + with a message that says to assign a frozen value. That removes the + read-only branch of the `defineProperty` trap, and findings 61, 66 and 67 + with it. It reverses behaviour added in `f8a012f`, so it is a decision for + before 1.0. + +**Kind.** Bug, simplification. + +**Cost.** The traps in `core.ts` and `DepEntry`. The tracking proxy at +`snapshot.ts:80-91` needs the same two traps for finding 31. Refusing to +freeze is breaking. Risk medium. + +### 11. Two small adoptions + +**A delete that removes nothing.** `delete_` returns before any notification +when the key is not an own property (`types/observableobject.ts:491-494`). +Ours notifies, because `Reflect.deleteProperty` answers `true` for a missing +key (`core.ts:517-522`). Script 03: + +```text +MobX: reaction runs after deleting a missing key: 0 +Ours: sync notifications after deleting a missing key: 1 | snapshot replaced: true +``` + +Adopt: check `Object.hasOwn` first. Kind: bug. Cost: one line in `core.ts`, +and the pinned tests of stage 1 finding 29. Risk low. + +**A getter cycle on a snapshot.** Each `ComputedValue` has an `isComputing` +flag, and `get` throws error 32 when it is set +(`core/computedvalue.ts:200-203`, `:293`, `:313`). Our live layer has the +counterpart (`core.ts:171-184`). The snapshot layer has none +(`snapshot.ts:121-162`). Script 02: + +```text +MobX, unobserved threw Error: [MobX] Cycle detected in computation Cycle@1.a: get a() { +Ours, live store threw Error: @codebelt/classy-store: circular computed getter dependency: a → b → a +Ours, snapshot threw RangeError: Maximum call stack size exceeded. +``` + +Adopt in `evaluateSnapshotGetter`: a marker per snapshot and key while a +getter runs, and the live layer's message. Kind: bug, diagnostics. Cost: +`snapshot.ts`, and the pinned test of finding 38. Risk low. + +### 12. What MobX does that we should not take + +- **Dropping a getter's cache when nobody observes it.** MobX caches a + computed only while something observes it or a batch is open + (`core/computedvalue.ts:204-215`, `:317-322`). In script 01, three reads + with no observer run every body three times. It is there to release memory, + and the third item of stage 1 finding 27 is what not doing it costs. Our + consumers read getters from snapshots and from the live store with no + observer in MobX's sense, so caching always is right for us. MobX's own + `keepAlive: true` behaves as we do. Reject. +- **Copying plain objects into the store.** `observable.object` builds a new + target and copies the properties across (`api/observable.ts:210-218`). + `store.child === raw` is false, and later writes to `raw` are not seen + (script 09). It rules out our raw-against-proxy findings (9, 10, 11, 25, + 50) by construction, and it is the opposite of "a plain class wrapped in a + proxy", which is fixed. Reject. +- **Annotations and decorators.** They are how MobX expresses what we infer + from the class: getter, method, field. Nothing to take. +- **Subclass rules.** MobX needs `override` and a call per constructor + because it installs members on the instance and the prototype. We read the + prototype chain on each access (`core.ts:464`), so an overriding getter + works with no rule at all. Script 06 shows the same run counts in both + libraries for the base body, the overriding body and an inherited getter. + Nothing to take. + +One thing noted on the way, read and not measured: MobX does its per-class +work once per prototype. `makeAutoObservable` caches the list of keys on the +prototype (`api/makeObservable.ts:63-71`), prototype methods are wrapped once +per class (`types/actionannotation.ts:42-50`), and one accessor descriptor +per key is shared by every instance (`types/observableobject.ts:48`, +`:678-690`). That supports the open performance item in `REVIEW_PLAN.md`: our +`get` trap looks the descriptor up on every read (`core.ts:464`), and the +answer depends only on the prototype and the key when the instance has no own +property of that name. + +## Stage 1 findings that have a counterpart in MobX + +"Ran" means a script in "Ported tests" shows it. "Read" means the source says +so and no script was run. + +| Finding | What we do | What MobX does there | Source | Basis | +| -------------- | --------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ | ---------------------- | +| 1, 45, 71 | `Object.defineProperty` through a store is silent and leaves children stale | The Proxy's `defineProperty` trap deletes, defines and notifies key observers in one batch. On a class instance annotated members are non-configurable, so redefining one throws | `observableobject.ts:307-357`, `dynamicobject.ts:38-45` | Ran, script 09 | +| 2, 3 | A snapshot or a getter over many rows costs time per row | One node per array, so a read of any index observes the whole array. A getter over 1,000 rows re-runs in full after one row changes, as ours does. There is no snapshot to rebuild | `observablearray.ts:114`, `:308-311` | Read | +| 5 | A function read from an array is a new wrapper each time | Wrapped once, when written. Reads are stable | `modifiers.ts:48-54` | Ran, script 06 | +| 6, 42 | A class in a store, and `constructor`, come back as bound wrappers | A class held as data is wrapped too, and `new` then throws. `observableRef` holds it as given. `constructor` is left out by name | `modifiers.ts:48-54`, `makeObservable.ts:68` | Ran, script 06 | +| 7 | `list.includes(raw)` misses | The same miss, for another reason: the store holds an observable copy of `raw` | `api/observable.ts:210-218` | Ran, script 09 | +| 8 | A store that refers to itself cannot be snapshotted | No snapshot. `toJS` follows a cycle through a map of objects already copied | `tojs.ts:35-37` | Read | +| 9, 10, 11, 25 | The raw object and the proxy can disagree | Cannot happen for a class instance, which is one object. A plain object is copied in, so the raw one is never connected | `observableobject.ts:391-405`, `api/observable.ts:210-218` | Ran, scripts 04 and 09 | +| 12 | A native `Set` or `Map` holds raw members | Replaced on assignment by an `ObservableMap` or `ObservableSet` whose members are made observable | `modifiers.ts:42-47` | Ran, script 09 | +| 18, 19 | A subscriber that writes overflows the stack, or never stops | One queue drained in a loop, stopped after 100 rounds with an error that names the reaction | `reaction.ts:271-307` | Ran, script 05 | +| 20 | A subscriber removed during delivery is still called | Checked for disposal at the moment of the call | `reaction.ts:128-129` | Ran, script 05 | +| 21 | A subscriber added after a write sometimes hears it | A new `autorun` runs once with the current state. A new `reaction()` does not fire for an earlier write | `autorun.ts:89-91`, `:170-175` | Ran, script 11 | +| 22 | A re-entrant write delivers the same snapshot twice | A reaction runs only when stale, so each sees the latest state once | `reaction.ts:134` | Ran, script 05 | +| 23 | A subscriber's rejected promise is not reported | The same. `autorun` ignores what the view returns | `autorun.ts:85-87` | Read | +| 24, 69 | The order of owner notifications | No owners. Reactions run in the order they became stale | `reaction.ts:117-123`, `observable.ts:238` | Read | +| 26 | A subscription follows the object, not the property | `observe(store.user, cb)` follows the object as ours does. `autorun(() => store.user.name)` follows the path | `api/observe.ts` was not read | Ran, script 11 | +| 27 | A getter's cache keeps what it read alive | A computed drops its value and its dependencies when its last observer leaves | `computedvalue.ts:317-322` | Ran, script 01 | +| 29 | A delete that removes nothing notifies | Returns early | `observableobject.ts:491-494` | Ran, script 03 | +| 30, 31 | A getter over `Object.keys(this)` or `in` goes stale | A keys node and a per-key boolean on Proxy objects. A class instance is as stale as ours unless `keys()` and `has()` are used | `observableobject.ts:254-272`, `:609-623` | Ran, script 03 | +| 32 | A getter that reads a missing property re-runs on every read | A read of a missing key inside a derivation subscribes to whether the key exists | `observableobject.ts:212-218` | Read | +| 36 | A getter misses another store, an outside reference, and a caught error | One global tracker records every read. A dependency is registered before it is computed, so a throw does not lose it | `observable.ts:177-205`, `derivation.ts:181-192`, `computedvalue.ts:218` | Ran, scripts 02 and 03 | +| 37 | The snapshot layer loses nested memoization | Each computed keeps its own cache. An outer one validates by reading the inner one | `derivation.ts:84-125` | Ran, script 01 | +| 38 | A getter cycle on a snapshot overflows the stack | A flag per computed while it runs, and error 32 | `computedvalue.ts:200-203` | Ran, script 02 | +| 39 | A getter that writes: re-runs on the live store, dropped on a snapshot | Writes are disallowed while a computed runs. A development warning names the field | `computedvalue.ts:295`, `derivation.ts:133-151` | Ran, script 05 | +| 40 | An object returned by a getter is not protected | The same. An `equals` option decides whether a new result counts as a change | `computedvalue.ts:131`, `:268-272` | Read | +| 41 | Inside a snapshot getter `this` is a tracking proxy over an empty object | `this` is the instance, or its Proxy for a plain object | `observableobject.ts:455` | Read | +| 43 | A setter is not a transaction | A setter is an action | `computedvalue.ts:125-130`, `autoannotation.ts:55-75` | Ran, script 05 | +| 44 | A redefined getter keeps the old result | Plain object: the old computed is deleted and its observers are told. Class instance: redefining throws | `observableobject.ts:534-542`, `:457-462` | Ran, script 09 | +| 46, 61, 66, 67 | Freezing through or behind the store | Freezing an observable Proxy is refused with an explanation. A frozen object assigned into a store is copied into an unfrozen observable | `dynamicobject.ts:49-51`, `observablearray.ts:106-108` | Ran, script 09 | +| 64, first item | `if (!cached) return false` in `areDepsValid` is unreachable | No counterpart. It becomes reachable, and needed, if finding 2 of this report is adopted | None | Reasoning | +| 72 | Suspending and resuming a detached subtree | Nothing comparable. A child does not know its container, so a held row cannot keep a removed list alive. The price is no structural sharing: `toJS` copies everything on each call | `tojs.ts:22-69` | Read | + +No counterpart, because MobX has no snapshots, no persistence or history in +its core, and no reactive collection of our kind: findings 4, 13 to 17, 28, +33 to 35, 47 to 60, 62, 63, 65, 68, 70 and 73. + +## The eight API questions, from MobX's point of view + +**1. Should synchronous notification be the default for `subscribe()`?** +Yes. A reaction runs synchronously when the outermost batch ends +(`core/observable.ts:111-124`). Delay is opt-in per reaction (`delay` and +`scheduler`, `api/autorun.ts:49`, `:102-108`) or for the whole process +(`reactionScheduler`, `core/reaction.ts:273`, `:311-314`). MobX can afford +this because delivery is queued, bounded and skips reactions that are up to +date. Finding 5 of this report is what our synchronous path lacks before it +could be the default. + +**2. Should writes outside a store method be allowed, warned about, or +grouped automatically? Does `batch()` belong in the API?** Allowed, and +warned about by default in development, when the value written has an +observer (`enforceActions: "observed"`, `core/globalstate.ts:109`, +`core/derivation.ts:133-151`). `"always"` warns for unobserved values too and +`"never"` turns it off. Never grouped automatically: each write outside an +action is its own batch and runs reactions on its own +(`core/atom.ts:94-98`). `batch()` belongs. MobX exports two forms: +`transaction(fn)`, which only batches (`api/transaction.ts:10-17`), and +`runInAction(fn)`, which batches, stops dependency tracking and permits +writes (`api/action.ts:93-95`, `core/action.ts:91-135`). We need one, and +`batch` is the right name for it. See finding 6 for why MobX's default cannot +be ours. + +**3. Should snapshot getters stay enumerable own accessors?** MobX says no to +"enumerable". A computed is defined with `enumerable: false`, on a class +instance and on a plain object alike (`types/observableobject.ts:457-462`), +and `toJS` leaves computed values out (`api/tojs.ts:60-66`, and its comment +at `:100-105`). Script 09: `Object.keys`, `JSON.stringify`, spread and `toJS` +of an object with a getter all give `{"amount":10}`. Derived values are not +data. We install an inherited getter on the snapshot as an own accessor with +`enumerable: true` (`snapshot.ts:213-217`), so a spread or a +`JSON.stringify` of a snapshot runs every getter, throws if one throws, and +`Object.keys(snapshot)` differs from `Object.keys(store)`. MobX's position +would be an own accessor that is not enumerable for a class getter. A getter +on an object literal is enumerable in the source object, and MobX hides that +one too. Being own is our business, since that is where the memoization +lives; MobX has no position on it. + +**4. Can arrow-function methods and `#private` fields be made to work, for +example with a base class or a constructor that returns the proxy?** MobX +makes both work by never wrapping the instance, with the limits given in +finding 8: a `#private` field is usable and not reactive unless it is a +decorated `accessor`. A base class whose constructor returns the proxy is the +Proxy counterpart, and the spike shows it working on the live store today for +both. Snapshots remain the open part for `#private`, and MobX has no position +there. + +**5. Should native `Map` and `Set` be reactive directly, replacing +`reactiveMap` and `reactiveSet`?** MobX makes them reactive by replacing +them. A `Map` or `Set` assigned into observable state is copied into an +`ObservableMap` or `ObservableSet` (`types/modifiers.ts:42-47`). Script 09: +the value read back is not the object that was assigned, is not +`instanceof Map`, reports `[object Map]`, and `structuredClone` rejects it. +So MobX's users write `new Map()` and get a different object that behaves +like one. That fits a library which copies plain objects on the way in. It +does not fit ours, where the raw object stays what the user made. MobX's +position is "the user should not need a second import". Its mechanism is not +one we can take without giving up that rule and pulling the collections into +the main entry (727 bytes gzipped today). A development warning when a native +`Map` or `Set` is assigned into a store would answer the same need. + +**6. Is opt-in (`PROXYABLE`) or opt-out (`markRaw`, `ref`, freezing) the +better default for nested class instances?** Opt-in. The deep enhancer +converts arrays, plain objects, maps, sets and functions, and returns +anything else as it is (`types/modifiers.ts:24-56`; "plain" is decided at +`utils/utils.ts:61-73`). A class instance is observable only if its own +constructor says so. Script 06: a write to a plain class instance nested in +observable state runs no reaction, a write to one that called +`makeAutoObservable` runs one, and the instance is kept by reference. For +plain data the default is the other way round, deep unless marked +`observableRef` or `observableShallow`. That is the split we have: plain data +is proxied unless frozen, a class instance only with `PROXYABLE`. + +**7. Are the entry points, export names and adapter names consistent across +the five frameworks?** No position on five frameworks: MobX's own bindings +are for React only. Two things bear on naming. MobX 7 replaced properties on +a namespace (`observable.ref`, `action.bound`, `comparer.shallow`) with named +exports (`observableRef`, `actionBound`, `compareShallow`) to make them +tree-shakeable (7.0.0 changelog entry). And the React binding's hook for a +store owned by a component is `useLocalObservable` (same entry), which +matches the shape of our `useLocalStore`. + +**8. What development-only diagnostics would catch our silent failure +modes?** What MobX has, with the failure of ours it would catch: + +| MobX diagnostic | Source | Our silent failure | +| ------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| Warning on a write to observed state outside an action, naming the store and field | `derivation.ts:133-151` | A write after an `await` in a method (opt-in for us, finding 6) | +| The same check while a computed runs | `computedvalue.ts:295` | A getter that writes (stage 1 finding 39) | +| Error after 100 rounds of reactions, naming the reaction | `reaction.ts:292-299` | A subscriber that writes to what it observes (findings 18, 19) | +| Error on a cycle between computed values, naming the getter | `computedvalue.ts:200-203` | A getter cycle on a snapshot (finding 38) | +| Opt-in warning for a derivation that read nothing observable (`reactionRequiresObservable`) | `derivation.ts:201-219` | A getter that recorded no dependency: another store, `Object.keys(this)`, a static, a `#private` field (findings 30, 36). Opt-in because a constant getter is legitimate | +| Opt-in warning for a computed read with no observer (`computedRequiresReaction`) | `computedvalue.ts:324-337` | None. We cache always | +| Error with an explanation on `Object.freeze` of an observable | `dynamicobject.ts:49-51` | Freezing behind or through the store (findings 46, 61, 66) | +| Error on an in-place `sort` or `reverse` inside a derivation | `observablearray.ts:429-449` | A getter that sorts `this.rows` in place: it writes while it runs | +| Errors when an annotation names a missing field, repeats one, or overrides nothing | `makeObservable.ts:97-100`, `observableobject.ts:751-761`, `overrideannotation.ts:24-29` | None. We have no annotations | +| `spy`, `getDependencyTree`, `getObserverTree` | 7.0.0 changelog entry | A supported way to count listeners in tests (stage 1, "Tests of internal state") | + +All of these are compiled out of the production build (finding 7). MobX has +no diagnostic for an arrow-function method, because there it works. The +warning proposed in finding 8 is ours to design. + +## What was verified by running code, and what was only read + +**Ran, in the scratch folder, with the output in this report:** + +- Scripts 01 to 06 and 11: ports of our tests to MobX, each with our library + run on the same case. +- Script 07: the cost of a clean getter read in a ladder of getters, ours + against MobX. One run, on a machine that was also running other agents, so + the figures show the shape and are not a baseline. +- Script 08: an `@observable accessor #secret` with standard decorators. + Bun's transform rejected `this.#secret++` on a decorated accessor, so the + script assigns `this.#secret + 1`. That is a Bun matter and not a MobX one. +- Script 09: the checks behind the table and the API answers, run with + `NODE_ENV` unset and again with `NODE_ENV=production` for its last block. +- Script 10: the base-class spike on our unmodified library. +- The sizes of the published MobX files, with `ls` and `gzip`. +- The scripts as they are printed below. Biome reformatted them when it + formatted this file, so they were extracted from the file and run once + more. Every output was identical, apart from the timings of script 07 and + the depth at which our subscriber overflows the stack in script 05 (3,011 + calls against 2,993). + +**Read in the source, not run:** + +- The rows of the table marked "Read". +- The state machine of `shouldCompute` and the three propagation functions. + The run counts in script 01 agree with it; the states themselves were not + inspected. +- `flow` beyond the one case in script 05, and the scheduler options of + `autorun` and `reaction`. +- How the build defines the development flag. The effect was run (script 09 + in production mode); the build was not. +- The per-prototype caching noted at the end of finding 12. + +**Reasoning, with no MobX source and no script behind it:** + +- Every "Proposal" is a judgement about our code. None was implemented, apart + from the spike in script 10. The cost lines are estimates from reading + `core.ts` and `snapshot.ts`. +- The warning for arrow-function fields in finding 8, and "a frozen function + is a value" in finding 9. +- That real getter graphs are shallow (finding 3). + +**Not done:** + +- Our test suites and benchmarks were not run, as instructed. +- `mobx-react-lite` and `mobx-react` were not read, so nothing here speaks to + how MobX binds to React. +- MobX's own test suite was not read or run. + +## Ported tests + +Everything below ran in a scratch folder outside the repository, with +`bun add mobx@7.1.7` and nothing else installed. `ours.ts` re-exports our +library from the repository by absolute path; `` stands for the +checkout. Each script is given whole, followed by its whole output. + +`ours.ts`: + +```ts +// Our library, read from the repository by absolute path. Nothing is installed there. +export { + batch, + createClassyStore, + snapshot, + subscribe, +} from '/packages/classy-store/src/index.ts'; +``` + +### Script 01: nested getters, three levels deep + +Port of `core.characterisation.getters.test.ts:81-165`. + +`01-nested-getters.ts`: + +```ts +// Port of "nested getters, three levels deep" (core.characterisation.getters.test.ts:81-165). +import {autorun, computed, makeAutoObservable} from 'mobx'; +import {createClassyStore, snapshot} from './ours'; + +function mobxChain() { + const runs = {a: 0, b: 0, c: 0}; + class Chain { + count = 1; + unrelated = 0; + constructor() { + makeAutoObservable(this); + } + get a() { + runs.a++; + return this.count * 2; + } + get b() { + runs.b++; + return this.a + 1; + } + get c() { + runs.c++; + return this.b + 1; + } + } + return {store: new Chain(), runs}; +} + +function mobxThreshold(keepAlive = false) { + const runs = {a: 0, b: 0, c: 0}; + class Threshold { + count = 1; + constructor() { + makeAutoObservable( + this, + keepAlive + ? { + a: computed({keepAlive: true}), + b: computed({keepAlive: true}), + c: computed({keepAlive: true}), + } + : undefined, + ); + } + get a() { + runs.a++; + return this.count > 0; + } + get b() { + runs.b++; + return this.a ? 'yes' : 'no'; + } + get c() { + runs.c++; + return `${this.b}!`; + } + } + return {store: new Threshold(), runs}; +} + +function oursThreshold() { + const runs = {a: 0, b: 0, c: 0}; + class Threshold { + count = 1; + get a() { + runs.a++; + return this.count > 0; + } + get b() { + runs.b++; + return this.a ? 'yes' : 'no'; + } + get c() { + runs.c++; + return `${this.b}!`; + } + } + return {store: createClassyStore(new Threshold()), runs}; +} + +const show = (label: string, runs: object) => + console.log(label.padEnd(74), JSON.stringify(runs)); + +console.log('── MobX, nobody observing ──'); +{ + const {store, runs} = mobxChain(); + store.c; + show('first read of c', runs); + store.c; + show('second read of c, nothing changed', runs); + store.unrelated = 1; + store.c; + show('read of c after a write to an unrelated field', runs); +} + +console.log('── MobX, c observed by an autorun ──'); +{ + const {store, runs} = mobxChain(); + const dispose = autorun(() => void store.c); + show('autorun created', runs); + store.c; + store.b; + store.a; + show('c, b and a read from outside', runs); + store.unrelated = 1; + show('write to an unrelated field', runs); + store.count = 2; + show('write to count (the autorun re-ran)', runs); + dispose(); + store.c; + show('autorun disposed, then c read', runs); +} + +console.log( + '── MobX, threshold chain: a gives the same result for every count > 0 ──', +); +{ + const {store, runs} = mobxThreshold(); + const dispose = autorun(() => void store.c); + show('autorun created', runs); + store.count = 2; + show('count 1 -> 2, read from the top by the autorun', runs); + dispose(); +} +{ + const {store, runs} = mobxThreshold(true); + store.c; + show('keepAlive, no observer: first read of c', runs); + store.c; + show('keepAlive, no observer: second read of c', runs); + store.count = 2; + store.c; + show('keepAlive, no observer: count 1 -> 2, then c read from the top', runs); +} + +console.log('── Ours, threshold chain ──'); +{ + const {store, runs} = oursThreshold(); + store.c; + show('live: first read of c', runs); + store.c; + show('live: second read of c', runs); + store.count = 2; + store.c; + show('live: count 1 -> 2, then c read from the top', runs); +} +{ + const {store, runs} = oursThreshold(); + snapshot(store).c; + show('snapshot: first read of c', runs); + store.count = 2; + snapshot(store).c; + show('snapshot: count 1 -> 2, then c read on the next snapshot', runs); +} +``` + +```text +── MobX, nobody observing ── +first read of c {"a":1,"b":1,"c":1} +second read of c, nothing changed {"a":2,"b":2,"c":2} +read of c after a write to an unrelated field {"a":3,"b":3,"c":3} +── MobX, c observed by an autorun ── +autorun created {"a":1,"b":1,"c":1} +c, b and a read from outside {"a":1,"b":1,"c":1} +write to an unrelated field {"a":1,"b":1,"c":1} +[MobX] Since strict-mode is enabled, changing (observed) observable values without using an action is not allowed. Tried to modify: Chain@2.count +write to count (the autorun re-ran) {"a":2,"b":2,"c":2} +autorun disposed, then c read {"a":3,"b":3,"c":3} +── MobX, threshold chain: a gives the same result for every count > 0 ── +autorun created {"a":1,"b":1,"c":1} +[MobX] Since strict-mode is enabled, changing (observed) observable values without using an action is not allowed. Tried to modify: Threshold@4.count +count 1 -> 2, read from the top by the autorun {"a":2,"b":1,"c":1} +keepAlive, no observer: first read of c {"a":1,"b":1,"c":1} +keepAlive, no observer: second read of c {"a":1,"b":1,"c":1} +[MobX] Since strict-mode is enabled, changing (observed) observable values without using an action is not allowed. Tried to modify: Threshold@6.count +keepAlive, no observer: count 1 -> 2, then c read from the top {"a":2,"b":1,"c":1} +── Ours, threshold chain ── +live: first read of c {"a":1,"b":1,"c":1} +live: second read of c {"a":1,"b":1,"c":1} +live: count 1 -> 2, then c read from the top {"a":2,"b":2,"c":2} +snapshot: first read of c {"a":1,"b":1,"c":1} +snapshot: count 1 -> 2, then c read on the next snapshot {"a":2,"b":2,"c":1} +``` + +### Script 02: a getter cycle, a getter that throws, a getter that catches + +Port of `core.characterisation.getters.test.ts:1049-1135`, `:1160-1215` and +`:1270-1300`. + +`02-cycle-and-throw.ts`: + +```ts +// Ports of "getters that read each other in a cycle" (getters test :1049-1135), +// "a getter that throws" (:1160-1215) and "a getter that catches the error of +// another getter" (:1270-1300). +import {autorun, makeAutoObservable, runInAction} from 'mobx'; +import {createClassyStore, snapshot} from './ours'; + +const message = (read: () => unknown) => { + try { + return `returned ${JSON.stringify(read())}`; + } catch (error) { + return `threw ${(error as Error).constructor.name}: ${String( + (error as Error).message, + ) + .split('\n')[0] + .slice(0, 110)}`; + } +}; + +console.log('── cycle: a reads b, b reads a ──'); +{ + class Cycle { + constructor() { + makeAutoObservable(this); + } + get a(): number { + return this.b + 1; + } + get b(): number { + return this.a + 1; + } + get fine() { + return 'fine'; + } + } + const store = new Cycle(); + console.log( + 'MobX, unobserved ', + message(() => store.a), + ); + let seen = ''; + const dispose = autorun(() => { + seen = message(() => store.a); + }); + console.log('MobX, inside autorun ', seen); + console.log( + 'MobX, other getter ', + message(() => store.fine), + ); + dispose(); +} +{ + class Cycle { + get a(): number { + return this.b + 1; + } + get b(): number { + return this.a + 1; + } + } + const store = createClassyStore(new Cycle()); + console.log( + 'Ours, live store ', + message(() => store.a), + ); + console.log( + 'Ours, snapshot ', + message(() => snapshot(store).a), + ); +} + +console.log('── a getter that throws, then recovers ──'); +function mobxLoader() { + const runs = {strict: 0, outer: 0}; + class Loader { + count = 0; + unrelated = 0; + constructor() { + makeAutoObservable(this); + } + get strict(): number { + runs.strict++; + if (this.count === 0) + throw new RangeError(`not ready (run ${runs.strict})`); + return this.count * 2; + } + get outer(): number { + runs.outer++; + return this.strict + 1; + } + } + return {store: new Loader(), runs}; +} +{ + const {store, runs} = mobxLoader(); + const seen: string[] = []; + const dispose = autorun(() => { + seen.push(message(() => store.outer)); + }); + console.log( + 'MobX observed: first run ', + seen.at(-1), + JSON.stringify(runs), + ); + console.log( + 'MobX observed: read again ', + message(() => store.outer), + JSON.stringify(runs), + ); + console.log( + 'MobX observed: same error object ', + (() => { + let first: unknown; + let second: unknown; + try { + store.strict; + } catch (error) { + first = error; + } + try { + store.strict; + } catch (error) { + second = error; + } + return first === second; + })(), + ); + runInAction(() => { + store.unrelated = 1; + }); + console.log( + 'MobX observed: unrelated write ', + message(() => store.outer), + JSON.stringify(runs), + ); + runInAction(() => { + store.count = 2; + }); + console.log( + 'MobX observed: count = 2 ', + seen.at(-1), + JSON.stringify(runs), + ); + runInAction(() => { + store.count = 0; + }); + console.log( + 'MobX observed: count = 0 again ', + seen.at(-1), + JSON.stringify(runs), + ); + dispose(); +} +{ + const runs = {strict: 0, outer: 0}; + class Loader { + count = 0; + unrelated = 0; + get strict(): number { + runs.strict++; + if (this.count === 0) + throw new RangeError(`not ready (run ${runs.strict})`); + return this.count * 2; + } + get outer(): number { + runs.outer++; + return this.strict + 1; + } + } + const store = createClassyStore(new Loader()); + console.log( + 'Ours live: first read ', + message(() => store.outer), + JSON.stringify(runs), + ); + console.log( + 'Ours live: read again ', + message(() => store.outer), + JSON.stringify(runs), + ); + store.count = 2; + console.log( + 'Ours live: count = 2 ', + message(() => store.outer), + JSON.stringify(runs), + ); +} + +console.log('── a getter that catches the error of another getter ──'); +{ + let runs = 0; + class Guarded { + ready = false; + constructor() { + makeAutoObservable(this); + } + get strict(): string { + if (!this.ready) throw new Error('not ready'); + return 'ready'; + } + get safe(): string { + runs++; + try { + return this.strict; + } catch { + return 'fallback'; + } + } + } + const store = new Guarded(); + const seen: string[] = []; + const dispose = autorun(() => { + seen.push(store.safe); + }); + runInAction(() => { + store.ready = true; + }); + console.log('MobX observed ', JSON.stringify(seen), 'runs of safe:', runs); + dispose(); + const unobserved = new Guarded(); + const before = unobserved.safe; + runInAction(() => { + unobserved.ready = true; + }); + console.log('MobX unobserved', JSON.stringify([before, unobserved.safe])); +} +{ + let runs = 0; + class Guarded { + ready = false; + get strict(): string { + if (!this.ready) throw new Error('not ready'); + return 'ready'; + } + get safe(): string { + runs++; + try { + return this.strict; + } catch { + return 'fallback'; + } + } + } + const store = createClassyStore(new Guarded()); + const before = store.safe; + store.ready = true; + console.log( + 'Ours live ', + JSON.stringify([before, store.safe]), + 'runs of safe:', + runs, + '| strict now:', + store.strict, + '| fresh snapshot:', + snapshot(store).safe, + ); +} +``` + +```text +── cycle: a reads b, b reads a ── +MobX, unobserved threw Error: [MobX] Cycle detected in computation Cycle@1.a: get a() { +MobX, inside autorun threw Error: [MobX] Cycle detected in computation Cycle@1.a: get a() { +MobX, other getter returned "fine" +Ours, live store threw Error: @codebelt/classy-store: circular computed getter dependency: a → b → a +Ours, snapshot threw RangeError: Maximum call stack size exceeded. +── a getter that throws, then recovers ── +MobX observed: first run threw RangeError: not ready (run 1) {"strict":1,"outer":1} +MobX observed: read again threw RangeError: not ready (run 1) {"strict":1,"outer":1} +MobX observed: same error object true +MobX observed: unrelated write threw RangeError: not ready (run 1) {"strict":1,"outer":1} +MobX observed: count = 2 returned 5 {"strict":2,"outer":2} +MobX observed: count = 0 again threw RangeError: not ready (run 3) {"strict":3,"outer":3} +Ours live: first read threw RangeError: not ready (run 1) {"strict":1,"outer":1} +Ours live: read again threw RangeError: not ready (run 2) {"strict":2,"outer":2} +Ours live: count = 2 returned 5 {"strict":3,"outer":3} +── a getter that catches the error of another getter ── +MobX observed ["fallback","ready"] runs of safe: 2 +MobX unobserved ["fallback","ready"] +Ours live ["fallback","fallback"] runs of safe: 1 | strict now: ready | fresh snapshot: ready +``` + +### Script 03: another store, `Object.keys(this)`, a delete that removes nothing + +Port of `core.characterisation.getters.test.ts:786` and `:2014-2059`, and of +the test for stage 1 finding 29 in `core.fuzz.findings.test.ts`. + +`03-other-store-and-keys.ts`: + +```ts +// Ports of "a getter that reads another store keeps its result after that store +// changes" (getters test :786) and "a getter whose result depends on which keys +// the store has" (:2014-2059). +import { + autorun, + extendObservable, + has as mobxHas, + keys as mobxKeys, + makeAutoObservable, + observable, + runInAction, +} from 'mobx'; +import {createClassyStore, snapshot} from './ours'; + +console.log('── a getter that reads another store ──'); +{ + class Rates { + rate = 2; + constructor() { + makeAutoObservable(this); + } + } + const rates = new Rates(); + let runs = 0; + class Cart { + amount = 10; + constructor() { + makeAutoObservable(this); + } + get total() { + runs++; + return this.amount * rates.rate; + } + } + const cart = new Cart(); + const seen: number[] = []; + const dispose = autorun(() => { + seen.push(cart.total); + }); + runInAction(() => { + rates.rate = 3; + }); + console.log('MobX observed ', JSON.stringify(seen), 'runs:', runs); + dispose(); +} +{ + const rates = createClassyStore({rate: 2}); + let runs = 0; + class Cart { + amount = 10; + get total() { + runs++; + return this.amount * rates.rate; + } + } + const cart = createClassyStore(new Cart()); + const before = cart.total; + rates.rate = 3; + console.log( + 'Ours live ', + JSON.stringify([before, cart.total]), + 'runs:', + runs, + '| first snapshot after:', + snapshot(cart).total, + ); +} + +console.log('── a getter that reads Object.keys(this) and `in` ──'); +{ + // A plain object made observable: MobX returns a Proxy with has and ownKeys traps. + const runs = {keys: 0, hasExtra: 0}; + const store = observable({ + a: 1, + get keys(): string[] { + runs.keys++; + return Object.keys(this); + }, + get hasExtra(): boolean { + runs.hasExtra++; + return 'extra' in this; + }, + }) as {a: number; extra?: number; keys: string[]; hasExtra: boolean}; + const seen: unknown[] = []; + const dispose = autorun(() => { + seen.push([store.keys, store.hasExtra]); + }); + runInAction(() => { + store.extra = 2; + }); + runInAction(() => { + delete store.extra; + }); + console.log( + 'MobX observable(object) ', + JSON.stringify(seen), + JSON.stringify(runs), + ); + dispose(); +} +{ + // A class instance: MobX installs accessors on the instance and returns no Proxy. + const runs = {keys: 0, hasExtra: 0}; + class Shape { + a = 1; + constructor() { + makeAutoObservable(this); + } + get keys(): string[] { + runs.keys++; + return Object.keys(this); + } + get hasExtra(): boolean { + runs.hasExtra++; + return 'extra' in this; + } + } + const store = new Shape() as Shape & {extra?: number}; + const seen: unknown[] = []; + const dispose = autorun(() => { + seen.push([store.keys, store.hasExtra]); + }); + // A plain assignment adds an ordinary, unobserved property. + store.extra = 2; + console.log( + 'MobX class, plain assignment ', + JSON.stringify(seen), + JSON.stringify(runs), + ); + delete store.extra; + // The supported way to add a field later. + runInAction(() => { + extendObservable(store, {extra: 2}); + }); + console.log( + 'MobX class, extendObservable ', + JSON.stringify(seen), + JSON.stringify(runs), + ); + dispose(); +} +{ + // The same class with MobX's own helpers in place of Object.keys and `in`. + const runs = {keys: 0, hasExtra: 0}; + class Shape { + a = 1; + constructor() { + makeAutoObservable(this); + } + get keys(): PropertyKey[] { + runs.keys++; + return mobxKeys(this); + } + get hasExtra(): boolean { + runs.hasExtra++; + return mobxHas(this, 'extra'); + } + } + const store = new Shape() as Shape & {extra?: number}; + const seen: unknown[] = []; + const dispose = autorun(() => { + seen.push([store.keys, store.hasExtra]); + }); + runInAction(() => { + extendObservable(store, {extra: 2}); + }); + console.log( + 'MobX class, keys() and has() ', + JSON.stringify(seen), + JSON.stringify(runs), + ); + dispose(); +} +{ + const runs = {keys: 0, hasExtra: 0}; + class Shape { + a = 1; + get keys(): string[] { + runs.keys++; + return Object.keys(this); + } + get hasExtra(): boolean { + runs.hasExtra++; + return 'extra' in this; + } + } + const store = createClassyStore(new Shape()) as Shape & {extra?: number}; + const seen: unknown[] = [[store.keys, store.hasExtra]]; + store.extra = 2; + seen.push([store.keys, store.hasExtra]); + delete store.extra; + seen.push([store.keys, store.hasExtra]); + console.log( + 'Ours live ', + JSON.stringify(seen), + JSON.stringify(runs), + ); + const snap = snapshot(store); + console.log( + 'Ours snapshot ', + JSON.stringify([snap.keys, snap.hasExtra]), + ); +} + +console.log('── a delete that removes nothing ──'); +{ + const dict = observable({a: 1}) as Record; + let runs = 0; + const dispose = autorun(() => { + runs++; + Object.keys(dict); + }); + runInAction(() => { + delete dict.missing; + }); + console.log('MobX: reaction runs after deleting a missing key:', runs - 1); + dispose(); +} +{ + const store = createClassyStore({dict: {a: 1} as Record}); + let calls = 0; + const {subscribe} = await import('./ours'); + subscribe( + store, + () => { + calls++; + }, + {sync: true}, + ); + const before = snapshot(store); + delete store.dict.missing; + console.log( + 'Ours: sync notifications after deleting a missing key:', + calls, + '| snapshot replaced:', + snapshot(store) !== before, + ); +} +``` + +```text +── a getter that reads another store ── +MobX observed [20,30] runs: 2 +Ours live [20,20] runs: 1 | first snapshot after: 30 +── a getter that reads Object.keys(this) and `in` ── +MobX observable(object) [[["a"],false],[["a","extra"],true],[["a"],false]] {"keys":3,"hasExtra":3} +MobX class, plain assignment [[["a"],false]] {"keys":1,"hasExtra":1} +MobX class, extendObservable [[["a"],false]] {"keys":1,"hasExtra":1} +MobX class, keys() and has() [[["a"],false],[["a","extra"],true]] {"keys":2,"hasExtra":2} +Ours live [[["a"],false],[["a"],false],[["a"],false]] {"keys":1,"hasExtra":1} +Ours snapshot [[],false] +── a delete that removes nothing ── +MobX: reaction runs after deleting a missing key: 0 +Ours: sync notifications after deleting a missing key: 1 | snapshot replaced: true +``` + +### Script 04: arrow-function methods, `#private`, `this`, binding + +Port of the arrow-function case in `CLAUDE.md` and of +`core.characterisation.getters.test.ts:2442`. + +`04-this-arrow-private.ts`: + +```ts +// Ports of the arrow-function method case (CLAUDE.md "No arrow function methods"), +// "a getter that reads a #private field" (getters test :2442), and method binding. +import { + autorun, + isAction, + isObservableProp, + makeAutoObservable, + observable, +} from 'mobx'; +import {createClassyStore, snapshot, subscribe} from './ours'; + +const outcome = (run: () => unknown) => { + try { + return JSON.stringify(run()); + } catch (error) { + return `threw ${(error as Error).constructor.name}: ${String((error as Error).message).slice(0, 90)}`; + } +}; + +console.log('── a write inside an arrow-function method ──'); +{ + class Counter { + count = 0; + other = 0; + constructor() { + makeAutoObservable(this); + } + increment = () => { + this.count++; + this.other++; + }; + } + const store = new Counter(); + let runs = 0; + const dispose = autorun(() => { + runs++; + void store.count; + void store.other; + }); + const detached = store.increment; + detached(); + console.log( + 'MobX: count', + store.count, + '| reaction runs after one call:', + runs - 1, + '| arrow field is an action:', + isAction(store.increment), + '| observable prop:', + isObservableProp(store, 'increment'), + ); + dispose(); +} +{ + class Counter { + count = 0; + other = 0; + increment = () => { + this.count++; + this.other++; + }; + } + const store = createClassyStore(new Counter()); + let calls = 0; + subscribe( + store, + () => { + calls++; + }, + {sync: true}, + ); + const before = snapshot(store); + store.increment(); + console.log( + 'Ours: count', + store.count, + '| sync notifications:', + calls, + '| snapshot count:', + snapshot(store).count, + '| snapshot replaced:', + snapshot(store) !== before, + ); +} + +console.log('── #private fields and methods ──'); +{ + class Vault { + #secret = 1; + visible = 1; + constructor() { + makeAutoObservable(this); + } + get doubled() { + return this.#secret * 2; + } + bump() { + this.#secret++; + this.visible++; + } + bumpSecretOnly() { + this.#secret++; + } + } + const store = new Vault(); + const seen: number[] = []; + const dispose = autorun(() => { + seen.push(store.doubled); + }); + store.bump(); + console.log( + 'MobX: read and write through #private:', + outcome(() => store.doubled), + '| reaction saw', + JSON.stringify(seen), + ); + store.bumpSecretOnly(); + console.log( + 'MobX: after a write to #secret alone, reaction saw', + JSON.stringify(seen), + '| unobserved read:', + (dispose(), store.doubled), + ); +} +{ + class Vault { + #secret = 1; + visible = 1; + get doubled() { + return this.#secret * 2; + } + bump() { + this.#secret++; + this.visible++; + } + } + const store = createClassyStore(new Vault()); + console.log( + 'Ours: getter that reads #secret:', + outcome(() => store.doubled), + ); + console.log( + 'Ours: method that writes #secret:', + outcome(() => store.bump()), + ); + console.log( + 'Ours: same getter on a snapshot:', + outcome(() => snapshot(store).doubled), + ); +} + +console.log('── `this` kept by the constructor ──'); +{ + const registry: {count: number}[] = []; + class Registered { + count = 0; + constructor() { + makeAutoObservable(this); + registry.push(this); + } + } + const store = new Registered(); + let runs = 0; + const dispose = autorun(() => { + runs++; + void store.count; + }); + registry[0].count = 5; + console.log( + 'MobX: write through the reference the constructor kept → reaction runs:', + runs - 1, + '| same object:', + registry[0] === store, + ); + dispose(); +} +{ + const registry: {count: number}[] = []; + class Registered { + count = 0; + constructor() { + registry.push(this); + } + } + const store = createClassyStore(new Registered()); + let calls = 0; + subscribe( + store, + () => { + calls++; + }, + {sync: true}, + ); + snapshot(store); + registry[0].count = 5; + console.log( + 'Ours: write through the reference the constructor kept → sync notifications:', + calls, + '| same object:', + registry[0] === store, + '| live', + store.count, + '| snapshot', + snapshot(store).count, + ); +} + +console.log('── a method passed around without its object ──'); +{ + class Plain { + count = 0; + constructor() { + makeAutoObservable(this); + } + increment() { + this.count++; + } + } + class Bound { + count = 0; + constructor() { + makeAutoObservable(this, {}, {autoBind: true}); + } + increment() { + this.count++; + } + } + const plain = new Plain(); + const bound = new Bound(); + const a = plain.increment; + const b = bound.increment; + console.log( + 'MobX default :', + outcome(() => { + a(); + return plain.count; + }), + ); + console.log( + 'MobX autoBind: true :', + outcome(() => { + b(); + return bound.count; + }), + '| own property:', + Object.hasOwn(bound, 'increment'), + '| stable identity:', + bound.increment === bound.increment, + ); + console.log( + 'MobX prototype method replaced by an action wrapper:', + isAction(Plain.prototype.increment), + ); +} +{ + class Plain { + count = 0; + increment() { + this.count++; + } + } + const store = createClassyStore(new Plain()); + const a = store.increment; + console.log( + 'Ours :', + outcome(() => { + a(); + return store.count; + }), + '| stable identity:', + store.increment === store.increment, + '| prototype untouched:', + Plain.prototype.increment.name === 'increment' && + !('isMobxAction' in Plain.prototype.increment), + ); +} + +console.log('── a plain object with an arrow function ──'); +{ + const store = observable({ + count: 0, + increment: () => { + store.count++; + }, + }); + let runs = 0; + const dispose = autorun(() => { + runs++; + void store.count; + }); + store.increment(); + console.log('MobX observable({...}): reaction runs', runs - 1); + dispose(); +} +``` + +```text +── a write inside an arrow-function method ── +MobX: count 1 | reaction runs after one call: 1 | arrow field is an action: true | observable prop: true +Ours: count 1 | sync notifications: 0 | snapshot count: 0 | snapshot replaced: false +── #private fields and methods ── +MobX: read and write through #private: 2 | reaction saw [2] +MobX: after a write to #secret alone, reaction saw [2] | unobserved read: 6 +Ours: getter that reads #secret: threw TypeError: Cannot access invalid private field (evaluating 'this.#secret') +Ours: method that writes #secret: threw TypeError: Cannot access invalid private field (evaluating 'this.#secret') +Ours: same getter on a snapshot: threw TypeError: Cannot access invalid private field (evaluating 'this.#secret') +── `this` kept by the constructor ── +[MobX] Since strict-mode is enabled, changing (observed) observable values without using an action is not allowed. Tried to modify: Registered@5.count +MobX: write through the reference the constructor kept → reaction runs: 1 | same object: true +Ours: write through the reference the constructor kept → sync notifications: 0 | same object: false | live 5 | snapshot 0 +── a method passed around without its object ── +MobX default : threw TypeError: undefined is not an object (evaluating 'this.count') +MobX autoBind: true : 1 | own property: true | stable identity: true +MobX prototype method replaced by an action wrapper: true +Ours : 1 | stable identity: true | prototype untouched: true +── a plain object with an arrow function ── +MobX observable({...}): reaction runs 1 +``` + +### Script 05: a write after an `await`, subscribers that write, setters, errors + +Port of the `await` case in `REVIEW_PLAN.md`, of stage 1 findings 18, 20 and +22 in `core.characterisation.notifications.test.ts`, and of +`core.characterisation.getters.test.ts:1836-1850` and `:1325`. + +`05-async-and-reactions.ts`: + +```ts +// Ports of: a write after an `await` inside a method (REVIEW_PLAN "Findings already +// in hand"), a subscriber that writes to what it observes (notifications test, +// findings 18, 19, 22), a subscriber removed during delivery (finding 20), a +// setter that writes two fields (finding 43) and a getter that writes (finding 39). +import { + autorun, + configure, + flow, + makeAutoObservable, + reaction, + runInAction, +} from 'mobx'; +import {batch, createClassyStore, snapshot, subscribe} from './ours'; + +const warnings: string[] = []; +const errors: string[] = []; +const realWarn = console.warn; +const realError = console.error; +console.warn = (...args: unknown[]) => { + warnings.push(String(args[0]).slice(0, 150)); +}; +console.error = (...args: unknown[]) => { + errors.push( + args + .map((arg) => + arg instanceof Error + ? `${arg.constructor.name}: ${arg.message}` + : String(arg), + ) + .join(' ') + .slice(0, 170), + ); +}; +const drain = (list: string[]) => { + const copy = [...list]; + list.length = 0; + return copy; +}; +const tick = () => new Promise((resolve) => setTimeout(resolve, 0)); + +console.log('── a write after an await inside a method ──'); +{ + class Loader { + loading = false; + rows = 0; + constructor() { + makeAutoObservable(this); + } + async load() { + this.loading = true; + this.rows = 0; + await tick(); + this.rows = 3; + this.loading = false; + } + async loadInAction() { + this.loading = true; + await tick(); + runInAction(() => { + this.rows = 6; + this.loading = false; + }); + } + *loadFlow() { + this.loading = true; + yield tick(); + this.rows = 9; + this.loading = false; + } + } + const store = new Loader(); + const seen: string[] = []; + const dispose = autorun(() => { + seen.push(`${store.loading}/${store.rows}`); + }); + seen.length = 0; + await store.load(); + console.log( + 'MobX async method reaction saw', + JSON.stringify(seen), + '| warnings:', + JSON.stringify(drain(warnings)), + ); + seen.length = 0; + await store.loadInAction(); + console.log( + 'MobX await + runInAction reaction saw', + JSON.stringify(seen), + '| warnings:', + drain(warnings).length, + ); + seen.length = 0; + await store.loadFlow(); + console.log( + 'MobX generator (flow) reaction saw', + JSON.stringify(seen), + '| warnings:', + drain(warnings).length, + ); + dispose(); +} +{ + class Loader { + loading = false; + rows = 0; + async load() { + this.loading = true; + this.rows = 0; + await tick(); + this.rows = 3; + this.loading = false; + } + } + const store = createClassyStore(new Loader()); + const seen: string[] = []; + subscribe( + store, + () => { + const snap = snapshot(store); + seen.push(`${snap.loading}/${snap.rows}`); + }, + {sync: true}, + ); + await store.load(); + console.log( + 'Ours async method sync subscriber saw', + JSON.stringify(seen), + '| warnings:', + drain(warnings).length, + ); +} + +console.log('── a reaction that writes to what it observes ──'); +{ + class Counter { + count = 0; + constructor() { + makeAutoObservable(this); + } + } + const store = new Counter(); + let runs = 0; + const dispose = autorun(() => { + runs++; + store.count = store.count + 1; + }); + console.log( + 'MobX autorun that always writes, first run: runs', + runs, + '| count', + store.count, + '| errors:', + drain(errors).length, + '| warnings:', + drain(warnings).length, + ); + runs = 0; + runInAction(() => { + store.count = 10; + }); + console.log( + 'MobX the same autorun after an outside write: runs', + runs, + '| count', + store.count, + '| errors:', + JSON.stringify(drain(errors)), + '| warnings:', + new Set(drain(warnings)).size, + 'distinct', + ); + dispose(); + + const bounded = new Counter(); + const order: string[] = []; + const first = autorun(() => { + order.push(`first:${bounded.count}`); + if (bounded.count === 1) bounded.count = 2; + }); + const second = autorun(() => { + order.push(`second:${bounded.count}`); + }); + order.length = 0; + runInAction(() => { + bounded.count = 1; + }); + console.log('MobX re-entrant write, two reactions:', JSON.stringify(order)); + first(); + second(); + drain(warnings); +} +{ + const store = createClassyStore({count: 0}); + let calls = 0; + const stop = subscribe( + store, + () => { + calls++; + if (calls < 20000) store.count++; + }, + {sync: true}, + ); + store.count = 1; + console.log( + 'Ours sync subscriber that always writes: calls', + calls, + '| count', + store.count, + '| errors:', + JSON.stringify(drain(errors).map((line) => line.slice(0, 60))), + ); + stop(); + + const bounded = createClassyStore({count: 0}); + const order: string[] = []; + subscribe( + bounded, + () => { + order.push(`first:${snapshot(bounded).count}`); + if (bounded.count === 1) bounded.count = 2; + }, + {sync: true}, + ); + subscribe( + bounded, + () => { + order.push(`second:${snapshot(bounded).count}`); + }, + {sync: true}, + ); + bounded.count = 1; + console.log( + 'Ours re-entrant write, two sync subscribers:', + JSON.stringify(order), + ); +} + +console.log('── a subscriber removed during delivery ──'); +{ + class Counter { + count = 0; + constructor() { + makeAutoObservable(this); + } + } + const store = new Counter(); + const order: string[] = []; + let disposeSecond = () => {}; + const disposeFirst = reaction( + () => store.count, + () => { + order.push('first'); + disposeSecond(); + }, + ); + disposeSecond = reaction( + () => store.count, + () => { + order.push('second'); + }, + ); + runInAction(() => { + store.count = 1; + }); + console.log('MobX:', JSON.stringify(order)); + disposeFirst(); +} +{ + const store = createClassyStore({count: 0}); + const order: string[] = []; + let stopSecond = () => {}; + subscribe( + store, + () => { + order.push('first'); + stopSecond(); + }, + {sync: true}, + ); + stopSecond = subscribe( + store, + () => { + order.push('second'); + }, + {sync: true}, + ); + store.count = 1; + console.log('Ours:', JSON.stringify(order)); +} + +console.log('── a setter that writes two fields ──'); +{ + class Name { + first = 'Ada'; + last = 'Lovelace'; + constructor() { + makeAutoObservable(this); + } + get full() { + return `${this.first} ${this.last}`; + } + set full(value: string) { + const [first, last] = value.split(' '); + this.first = first; + this.last = last; + } + } + const store = new Name(); + const seen: string[] = []; + const dispose = autorun(() => { + seen.push(`${store.first} ${store.last}`); + }); + seen.length = 0; + store.full = 'Grace Hopper'; + console.log( + 'MobX reaction saw', + JSON.stringify(seen), + '| warnings:', + drain(warnings).length, + ); + dispose(); +} +{ + class Name { + first = 'Ada'; + last = 'Lovelace'; + get full() { + return `${this.first} ${this.last}`; + } + set full(value: string) { + const [first, last] = value.split(' '); + this.first = first; + this.last = last; + } + } + const store = createClassyStore(new Name()); + const seen: string[] = []; + subscribe( + store, + () => { + const snap = snapshot(store); + seen.push(`${snap.first} ${snap.last}`); + }, + {sync: true}, + ); + store.full = 'Grace Hopper'; + console.log('Ours sync subscriber saw', JSON.stringify(seen)); +} + +console.log('── a getter that writes while it runs ──'); +{ + class Sneaky { + count = 1; + reads = 0; + constructor() { + makeAutoObservable(this); + } + get doubled() { + this.reads++; + return this.count * 2; + } + } + const store = new Sneaky(); + const watchReads = autorun(() => { + void store.reads; + }); + const dispose = autorun(() => { + void store.doubled; + }); + console.log( + 'MobX: reads', + store.reads, + '| warnings:', + JSON.stringify(drain(warnings)), + ); + dispose(); + watchReads(); +} + +console.log('── a reaction that throws ──'); +{ + class Counter { + count = 0; + constructor() { + makeAutoObservable(this); + } + fail() { + this.count++; + throw new Error('action failed'); + } + } + const store = new Counter(); + const order: string[] = []; + const first = autorun(() => { + if (store.count === 1) throw new Error('reaction failed'); + order.push(`first:${store.count}`); + }); + const second = autorun(() => { + order.push(`second:${store.count}`); + }); + order.length = 0; + runInAction(() => { + store.count = 1; + }); + console.log( + 'MobX: later reactions still ran', + JSON.stringify(order), + '| console.error:', + JSON.stringify(drain(errors)), + ); + runInAction(() => { + store.count = 0; + }); + order.length = 0; + try { + store.fail(); + } catch (error) { + order.push(`caller caught: ${(error as Error).message}`); + } + console.log( + 'MobX: an action that throws, with a reaction that then throws:', + JSON.stringify(order), + '| console.error:', + drain(errors).length, + '| console.warn:', + JSON.stringify(drain(warnings)), + ); + first(); + second(); +} + +console.warn = realWarn; +console.error = realError; +void batch; +void configure; +void flow; +``` + +```text +── a write after an await inside a method ── +MobX async method reaction saw ["true/0","true/3","false/3"] | warnings: ["[MobX] Since strict-mode is enabled, changing (observed) observable values without using an action is not allowed. Tried to modify: Loader@1.rows","[MobX] Since strict-mode is enabled, changing (observed) observable values without using an action is not allowed. Tried to modify: Loader@1.loading"] +MobX await + runInAction reaction saw ["true/3","false/6"] | warnings: 0 +MobX generator (flow) reaction saw ["true/6","false/9"] | warnings: 0 +Ours async method sync subscriber saw ["true/0","true/3","false/3"] | warnings: 0 +── a reaction that writes to what it observes ── +MobX autorun that always writes, first run: runs 1 | count 1 | errors: 0 | warnings: 0 +MobX the same autorun after an outside write: runs 99 | count 109 | errors: ["Reaction doesn't converge to a stable state after 100 iterations. Probably there is a cycle in the reactive function: Reaction[Autorun@4]"] | warnings: 1 distinct +MobX re-entrant write, two reactions: ["first:1","second:2","first:2"] +Ours sync subscriber that always writes: calls 2993 | count 2993 | errors: ["RangeError: Maximum call stack size exceeded."] +Ours re-entrant write, two sync subscribers: ["first:1","first:2","second:2","second:2"] +── a subscriber removed during delivery ── +MobX: ["first"] +Ours: ["first","second"] +── a setter that writes two fields ── +MobX reaction saw ["Grace Hopper"] | warnings: 0 +Ours sync subscriber saw ["Grace Lovelace","Grace Hopper"] +── a getter that writes while it runs ── +MobX: reads 1 | warnings: ["[MobX] Since strict-mode is enabled, changing (observed) observable values without using an action is not allowed. Tried to modify: Sneaky@13.reads"] +── a reaction that throws ── +MobX: later reactions still ran ["second:1"] | console.error: ["[mobx] Encountered an uncaught exception that was thrown by a reaction or observer component, in: 'Reaction[Autorun@17]' Error: reaction failed"] +MobX: an action that throws, with a reaction that then throws: ["second:1","caller caught: action failed"] | console.error: 0 | console.warn: ["[mobx] (error in reaction 'Autorun@17' suppressed, fix error of causing action below)"] +``` + +### Script 06: a subclass that overrides a getter, functions and classes as data + +Port of `core.characterisation.getters.test.ts:1551-1574` and of stage 1 +findings 5 and 6 in `core.characterisation.identity.test.ts`. + +`06-subclass-and-functions.ts`: + +```ts +// Ports of "getters on a subclass" (getters test :1551-1574), "a function read +// from an array is a new wrapper on every read" and "a class held in a store" +// (identity test, findings 5 and 6). +import { + action, + autorun, + computed, + isAction, + makeAutoObservable, + makeObservable, + observable, + observableRef, + observableShallow, + override, + runInAction, +} from 'mobx'; +import {createClassyStore} from './ours'; + +const outcome = (run: () => unknown) => { + try { + return JSON.stringify(run()); + } catch (error) { + return `threw ${(error as Error).constructor.name}: ${String( + (error as Error).message, + ) + .replace(/\n/g, ' ') + .slice(0, 150)}`; + } +}; + +console.log('── a subclass that overrides a getter ──'); +{ + class Base { + count = 5; + constructor() { + makeAutoObservable(this); + } + get label(): string { + return `base:${this.count}`; + } + } + class Derived extends Base { + suffix = '!'; + constructor() { + super(); + makeAutoObservable(this); + } + override get label(): string { + return `derived(${super.label})${this.suffix}`; + } + } + console.log( + 'MobX makeAutoObservable in a subclass :', + outcome(() => new Derived().label), + ); +} +{ + const runs = {base: 0, derived: 0, inherited: 0}; + class Base { + count = 5; + constructor() { + makeObservable(this, { + count: observable, + label: computed, + next: computed, + bump: action, + }); + } + get label(): string { + runs.base++; + return `base:${this.count}`; + } + get next() { + runs.inherited++; + return this.count + 1; + } + bump() { + this.count++; + } + } + class Forgetful extends Base { + suffix = '!'; + constructor() { + super(); + makeObservable(this, {suffix: observable, label: computed}); + } + override get label(): string { + return `derived(${super.label})${this.suffix}`; + } + } + console.log( + 'MobX makeObservable, getter annotated twice:', + outcome(() => new Forgetful().label), + ); + + class Derived extends Base { + suffix = '!'; + constructor() { + super(); + makeObservable(this, { + suffix: observable, + label: override, + bump: override, + }); + } + override get label(): string { + runs.derived++; + return `derived(${super.label})${this.suffix}`; + } + override bump() { + super.bump(); + this.suffix += '!'; + } + } + const store = new Derived(); + const seen: unknown[] = []; + const dispose = autorun(() => { + seen.push([store.label, store.next]); + }); + console.log( + 'MobX makeObservable + override, first run :', + JSON.stringify(seen), + JSON.stringify(runs), + ); + runInAction(() => { + store.suffix = '?'; + }); + console.log( + 'MobX after a write to the subclass field :', + JSON.stringify(seen.at(-1)), + JSON.stringify(runs), + ); + store.bump(); + console.log( + 'MobX after an overridden action :', + JSON.stringify(seen.at(-1)), + JSON.stringify(runs), + '| reaction runs in total:', + seen.length, + ); + dispose(); +} +{ + const runs = {base: 0, derived: 0, inherited: 0}; + class Base { + count = 5; + get label(): string { + runs.base++; + return `base:${this.count}`; + } + get next() { + runs.inherited++; + return this.count + 1; + } + } + class Derived extends Base { + suffix = '!'; + override get label(): string { + runs.derived++; + return `derived(${super.label})${this.suffix}`; + } + } + const store = createClassyStore(new Derived()); + const first = [store.label, store.next]; + console.log( + 'Ours, first read :', + JSON.stringify(first), + JSON.stringify(runs), + ); + store.suffix = '?'; + console.log( + 'Ours after a write to the subclass field :', + JSON.stringify([store.label, store.next]), + JSON.stringify(runs), + ); +} + +console.log('── a function held in an array ──'); +{ + const first = () => 'first'; + const second = () => 'second'; + const store = observable({callbacks: [first, second]}); + console.log( + 'MobX: same function on two reads:', + store.callbacks[0] === store.callbacks[0], + '| is the function that was stored:', + store.callbacks[0] === first, + '| wrapped as an action:', + isAction(store.callbacks[0]), + '| indexOf(first):', + store.callbacks.indexOf(first), + '| indexOf(what was read):', + store.callbacks.indexOf(store.callbacks[1]), + ); + const byRef = observable( + {callbacks: [first, second]}, + {callbacks: observableShallow}, + ); + console.log( + 'MobX observableShallow: is the function that was stored:', + byRef.callbacks[0] === first, + '| indexOf(first):', + byRef.callbacks.indexOf(first), + ); +} +{ + const first = () => 'first'; + const second = () => 'second'; + const store = createClassyStore({callbacks: [first, second]}); + console.log( + 'Ours: same function on two reads:', + store.callbacks[0] === store.callbacks[0], + '| is the function that was stored:', + store.callbacks[0] === first, + '| indexOf(first):', + store.callbacks.indexOf(first), + '| indexOf(what was read):', + store.callbacks.indexOf(store.callbacks[1]), + ); +} + +console.log('── a class held in a store ──'); +{ + class Model { + static label = 'model'; + constructor(public name: string) {} + } + const store = observable({Model}); + console.log( + 'MobX:', + outcome(() => [ + store.Model === Model, + (store.Model as typeof Model).label ?? null, + ]), + '| new:', + outcome(() => new store.Model('x') instanceof Model), + ); + const byRef = observable({Model}, {Model: observableRef}); + console.log( + 'MobX observableRef:', + outcome(() => [ + byRef.Model === Model, + byRef.Model.label, + new byRef.Model('x') instanceof byRef.Model, + ]), + ); +} +{ + class Model { + static label = 'model'; + constructor(public name: string) {} + } + const store = createClassyStore({Model}); + console.log( + 'Ours:', + outcome(() => [ + store.Model === Model, + store.Model.label ?? null, + new store.Model('x') instanceof store.Model, + ]), + ); +} + +console.log('── a class instance nested in a store ──'); +{ + class Plain { + n = 0; + } + class Marked { + n = 0; + constructor() { + makeAutoObservable(this); + } + } + const store = observable({ + plain: new Plain(), + marked: new Marked(), + literal: {n: 0}, + }); + let runs = 0; + const dispose = autorun(() => { + runs++; + void store.plain.n; + void store.marked.n; + void store.literal.n; + }); + runInAction(() => { + store.plain.n = 1; + }); + const afterPlain = runs - 1; + runInAction(() => { + store.marked.n = 1; + }); + const afterMarked = runs - 1 - afterPlain; + runInAction(() => { + store.literal.n = 1; + }); + console.log( + 'MobX: reaction runs after a write to a plain class instance:', + afterPlain, + '| to one that called makeAutoObservable:', + afterMarked, + '| to an object literal:', + runs - 1 - afterPlain - afterMarked, + '| instance kept by reference:', + store.plain instanceof Plain, + ); + dispose(); +} +``` + +```text +── a subclass that overrides a getter ── +MobX makeAutoObservable in a subclass : threw Error: [MobX] 'makeAutoObservable' can only be used for classes that don't have a superclass +MobX makeObservable, getter annotated twice: threw Error: [MobX] Cannot apply 'computed' to 'Forgetful@1.label': The field is already annotated with 'computed'. Re-annotating fields is not allowed. Use 'overr +MobX makeObservable + override, first run : [["derived(base:5)!",6]] {"base":1,"derived":1,"inherited":1} +MobX after a write to the subclass field : ["derived(base:5)?",6] {"base":2,"derived":2,"inherited":1} +MobX after an overridden action : ["derived(base:6)?!",7] {"base":3,"derived":3,"inherited":2} | reaction runs in total: 3 +Ours, first read : ["derived(base:5)!",6] {"base":1,"derived":1,"inherited":1} +Ours after a write to the subclass field : ["derived(base:5)?",6] {"base":2,"derived":2,"inherited":1} +── a function held in an array ── +MobX: same function on two reads: true | is the function that was stored: false | wrapped as an action: true | indexOf(first): -1 | indexOf(what was read): 1 +MobX observableShallow: is the function that was stored: true | indexOf(first): 0 +Ours: same function on two reads: false | is the function that was stored: false | indexOf(first): -1 | indexOf(what was read): -1 +── a class held in a store ── +MobX: [false,null] | new: threw TypeError: Cannot call a class constructor Model without |new| +MobX observableRef: [true,"model",true] +Ours: [false,null,false] +── a class instance nested in a store ── +MobX: reaction runs after a write to a plain class instance: 0 | to one that called makeAutoObservable: 1 | to an object literal: 1 | instance kept by reference: true +``` + +### Script 07: the cost of validating a ladder of getters + +A measurement, not a port. + +`07-validation-cost.ts`: + +```ts +// A measurement, not a port: what a clean read of a getter costs when getters +// read each other in a ladder. Each level has two getters and each reads both +// getters of the level below. +import {autorun, makeAutoObservable, runInAction} from 'mobx'; +import {createClassyStore, snapshot} from './ours'; + +function ladder(depth: number, observable: boolean) { + const runs = {count: 0}; + const target: Record = {base: 1, unrelated: 0}; + for (let level = 0; level < depth; level++) { + for (const side of ['l', 'r']) { + Object.defineProperty(target, `${side}${level}`, { + enumerable: true, + configurable: true, + get(this: Record) { + runs.count++; + return level === 0 + ? this.base + : this[`l${level - 1}`] + this[`r${level - 1}`]; + }, + }); + } + } + const store = observable + ? makeAutoObservable(target) + : createClassyStore(target); + return {store: store as Record, runs, top: `l${depth - 1}`}; +} + +const time = (run: () => void) => { + const start = performance.now(); + run(); + return `${(performance.now() - start).toFixed(2)} ms`.padStart(12); +}; + +console.log( + 'depth | ours: first read | ours: clean read | ours: read after base changed | ours: first snapshot read | getter runs (ours live, first read)', +); +for (const depth of [4, 8, 12, 16, 18]) { + const {store, runs, top} = ladder(depth, false); + const first = time(() => void store[top]); + const firstRuns = runs.count; + const clean = time(() => void store[top]); + store.base = 2; + const dirty = time(() => void store[top]); + const snap = ladder(depth, false); + const snapFirst = time(() => void snapshot(snap.store)[snap.top]); + console.log( + String(depth).padStart(5), + '|', + first, + '|', + clean, + '|', + dirty, + '|', + snapFirst, + '|', + firstRuns, + ); +} + +console.log( + 'depth | MobX observed: first run | clean read | reaction after base changed | getter runs (first run)', +); +for (const depth of [4, 8, 12, 16, 18, 200]) { + const {store, runs, top} = ladder(depth, true); + let dispose = () => {}; + const first = time(() => { + dispose = autorun(() => void store[top]); + }); + const firstRuns = runs.count; + const clean = time(() => void store[top]); + const dirty = time(() => + runInAction(() => { + store.base = 2; + }), + ); + dispose(); + console.log( + String(depth).padStart(5), + '|', + first, + '|', + clean, + '|', + dirty, + '|', + firstRuns, + ); +} + +console.log('depth | MobX unobserved: one read | getter runs'); +for (const depth of [4, 8, 12, 16, 200]) { + const {store, runs, top} = ladder(depth, true); + const first = time(() => void store[top]); + console.log(String(depth).padStart(5), '|', first, '|', runs.count); +} +``` + +```text +depth | ours: first read | ours: clean read | ours: read after base changed | ours: first snapshot read | getter runs (ours live, first read) + 4 | 0.19 ms | 0.01 ms | 0.03 ms | 0.23 ms | 7 + 8 | 0.09 ms | 0.03 ms | 0.10 ms | 0.07 ms | 15 + 12 | 0.42 ms | 0.30 ms | 0.34 ms | 0.07 ms | 23 + 16 | 2.27 ms | 1.57 ms | 1.96 ms | 0.05 ms | 31 + 18 | 6.51 ms | 4.12 ms | 6.44 ms | 0.07 ms | 35 +depth | MobX observed: first run | clean read | reaction after base changed | getter runs (first run) + 4 | 0.43 ms | 0.01 ms | 0.21 ms | 7 + 8 | 0.11 ms | 0.00 ms | 0.12 ms | 15 + 12 | 0.07 ms | 0.00 ms | 0.08 ms | 23 + 16 | 0.08 ms | 0.01 ms | 0.10 ms | 31 + 18 | 0.06 ms | 0.00 ms | 0.07 ms | 35 + 200 | 0.50 ms | 0.00 ms | 0.48 ms | 399 +depth | MobX unobserved: one read | getter runs + 4 | 0.11 ms | 7 + 8 | 0.03 ms | 15 + 12 | 0.02 ms | 23 + 16 | 0.05 ms | 31 + 200 | 0.45 ms | 399 +``` + +### Script 08: an observable `#private` accessor with standard decorators + +`08-decorators.ts`: + +```ts +// MobX 7 with standard (2022.3) decorators: an observable #private accessor. +import {action, autorun, computed, observable} from 'mobx'; + +class Vault { + @observable accessor #secret = 1; + + @computed get doubled() { + return this.#secret * 2; + } + + @action bump() { + this.#secret = this.#secret + 1; + } +} + +const store = new Vault(); +const seen: number[] = []; +const dispose = autorun(() => { + seen.push(store.doubled); +}); +store.bump(); +console.log( + 'MobX @observable accessor #secret: reaction saw', + JSON.stringify(seen), +); +dispose(); +``` + +```text +MobX @observable accessor #secret: reaction saw [2,4] +``` + +### Script 09: the checks behind the table and the API answers + +`09-shape-and-diagnostics.ts`: + +```ts +// Checks behind the API answers and the table of stage 1 findings. Not ports of +// one test each; every block names the finding it speaks to. +import { + autorun, + configure, + isObservable, + makeAutoObservable, + observable, + runInAction, + toJS, +} from 'mobx'; + +const outcome = (run: () => unknown) => { + try { + return JSON.stringify(run()); + } catch (error) { + return `threw ${(error as Error).constructor.name}: ${String( + (error as Error).message, + ) + .replace(/\n/g, ' ') + .slice(0, 140)}`; + } +}; +const warnings: string[] = []; +console.warn = (...args: unknown[]) => { + warnings.push(String(args[0]).slice(0, 130)); +}; +const drain = () => { + const copy = [...warnings]; + warnings.length = 0; + return copy; +}; + +console.log('── API question 3: are computed values enumerable? ──'); +{ + class Cart { + amount = 10; + constructor() { + makeAutoObservable(this); + } + get doubled() { + return this.amount * 2; + } + add() { + this.amount++; + } + } + const store = new Cart(); + console.log( + 'class instance: Object.keys', + JSON.stringify(Object.keys(store)), + '| JSON.stringify', + JSON.stringify(store), + '| toJS', + JSON.stringify(toJS(store)), + '| own accessor:', + Object.hasOwn(store, 'doubled'), + '| enumerable:', + Object.getOwnPropertyDescriptor(store, 'doubled')?.enumerable, + ); + const literal = observable({ + amount: 10, + get doubled(): number { + return this.amount * 2; + }, + }); + console.log( + 'object literal: Object.keys', + JSON.stringify(Object.keys(literal)), + '| JSON.stringify', + JSON.stringify(literal), + '| spread', + JSON.stringify({...literal}), + ); +} + +console.log('── finding 1 and 45: Object.defineProperty through the store ──'); +{ + const store = observable({a: 1}) as Record; + const seen: unknown[] = []; + const dispose = autorun(() => { + seen.push([Object.keys(store), store.b ?? null]); + }); + runInAction(() => { + Object.defineProperty(store, 'b', { + value: 2, + enumerable: true, + configurable: true, + writable: true, + }); + }); + console.log('MobX: reaction saw', JSON.stringify(seen)); + dispose(); +} + +console.log('── finding 44: a getter that is redefined ──'); +{ + const store = observable({ + count: 2, + get view(): string { + return `old ${this.count}`; + }, + }); + const seen: string[] = []; + const dispose = autorun(() => { + seen.push(store.view); + }); + console.log( + 'plain object:', + outcome(() => { + runInAction(() => { + Object.defineProperty(store, 'view', { + get() { + return `new ${this.count}`; + }, + configurable: true, + }); + }); + return seen; + }), + '| read now:', + store.view, + ); + dispose(); + class Viewer { + count = 2; + constructor() { + makeAutoObservable(this); + } + get view() { + return `old ${this.count}`; + } + } + const instance = new Viewer(); + console.log( + 'class instance:', + outcome(() => + Object.defineProperty(instance, 'view', { + get() { + return 'new'; + }, + configurable: true, + }), + ), + ); +} + +console.log('── finding 7, 9, 10, 11: the raw object and the store ──'); +{ + const raw = {n: 0}; + const store = observable({list: [raw], child: raw}); + console.log( + 'MobX: list.includes(raw)', + store.list.includes(raw), + '| store.child === raw', + store.child === raw, + '| raw is observable', + isObservable(raw), + '| includes(what was read)', + store.list.includes(store.list[0]), + ); + raw.n = 5; + console.log( + 'MobX: after raw.n = 5, store.child.n is', + store.child.n, + '(the store holds a copy)', + ); +} + +console.log( + '── API question 5: a native Map and Set held in observable state ──', +); +{ + const map = new Map([['a', {n: 1}]]); + const set = new Set([1]); + const store = observable({map, set}); + let runs = 0; + const dispose = autorun(() => { + runs++; + void store.map.get('a')?.n; + void store.set.has(2); + }); + runInAction(() => { + store.map.get('a')!.n = 2; + }); + runInAction(() => { + store.set.add(2); + }); + console.log( + 'MobX: same object as given', + store.map === map, + '| instanceof Map', + store.map instanceof Map, + '| instanceof Set', + store.set instanceof Set, + '| toStringTag', + Object.prototype.toString.call(store.map), + '| reaction runs after two writes:', + runs - 1, + '| original map entry changed:', + map.get('a')?.n, + ); + console.log( + 'MobX: structuredClone of the observable map:', + outcome(() => structuredClone(store.map) instanceof Map), + ); + dispose(); +} + +console.log('── finding 46: freezing ──'); +{ + const store = observable({config: {nested: {a: 1}}, list: [1]}); + console.log( + 'Object.freeze(store.config):', + outcome(() => Object.freeze(store.config)), + ); + console.log( + 'Object.freeze(store.list) :', + outcome(() => Object.freeze(store.list)), + ); + console.log( + 'observable(frozen object) :', + outcome(() => isObservable(observable(Object.freeze({a: 1})))), + ); + const holder = observable({value: null as unknown}); + runInAction(() => { + holder.value = Object.freeze({a: {b: 1}}); + }); + console.log( + 'a frozen object assigned into a store:', + outcome(() => [isObservable(holder.value), Object.isFrozen(holder.value)]), + ); +} + +console.log('── API question 8: opt-in warnings ──'); +{ + configure({computedRequiresReaction: true, reactionRequiresObservable: true}); + class Cart { + amount = 10; + constructor() { + makeAutoObservable(this); + } + get doubled() { + return this.amount * 2; + } + get constant() { + return 42; + } + } + const store = new Cart(); + void store.doubled; + console.log('computed read with no observer:', JSON.stringify(drain())); + const dispose = autorun(() => { + void store.constant; + }); + console.log( + 'computed that read nothing observable:', + JSON.stringify(drain()), + ); + dispose(); + const empty = autorun(() => {}); + console.log( + 'reaction that read nothing observable:', + JSON.stringify(drain()), + ); + empty(); + configure({ + computedRequiresReaction: false, + reactionRequiresObservable: false, + }); +} + +console.log('── build: NODE_ENV =', process.env.NODE_ENV ?? '(unset)', '──'); +{ + class Base { + count = 0; + constructor() { + makeAutoObservable(this); + } + } + class Derived extends Base { + extra = 0; + constructor() { + super(); + makeAutoObservable(this); + } + } + console.log( + 'makeAutoObservable in a subclass:', + outcome(() => { + const d = new Derived(); + return Object.keys(d); + }), + ); + const store = new Base(); + const dispose = autorun(() => { + void store.count; + }); + store.count = 1; + console.log('write outside an action, warnings:', drain().length); + class Cycle { + constructor() { + makeAutoObservable(this); + } + get a(): number { + return this.a + 1; + } + } + console.log( + 'cycle:', + outcome(() => new Cycle().a), + ); + dispose(); +} +``` + +With `NODE_ENV` unset: + +```text +── API question 3: are computed values enumerable? ── +class instance: Object.keys ["amount"] | JSON.stringify {"amount":10} | toJS {"amount":10} | own accessor: true | enumerable: false +object literal: Object.keys ["amount"] | JSON.stringify {"amount":10} | spread {"amount":10} +── finding 1 and 45: Object.defineProperty through the store ── +MobX: reaction saw [[["a"],null],[["a","b"],2]] +── finding 44: a getter that is redefined ── +plain object: ["old 2","new 2"] | read now: new 2 +class instance: threw TypeError: Attempting to change configurable attribute of unconfigurable property. +── finding 7, 9, 10, 11: the raw object and the store ── +MobX: list.includes(raw) false | store.child === raw false | raw is observable false | includes(what was read) true +MobX: after raw.n = 5, store.child.n is 0 (the store holds a copy) +── API question 5: a native Map and Set held in observable state ── +MobX: same object as given false | instanceof Map false | instanceof Set false | toStringTag [object Map] | reaction runs after two writes: 2 | original map entry changed: 1 +MobX: structuredClone of the observable map: threw DOMException: The object can not be cloned. +── finding 46: freezing ── +Object.freeze(store.config): threw Error: [MobX] Dynamic observable objects cannot be frozen. If you're passing observables to 3rd party component/function that calls Object.freeze, +Object.freeze(store.list) : threw Error: [MobX] Observable arrays cannot be frozen. If you're passing observables to 3rd party component/function that calls Object.freeze, pass copy +observable(frozen object) : true +a frozen object assigned into a store: [true,false] +── API question 8: opt-in warnings ── +computed read with no observer: ["[mobx] Computed value 'Cart@14.doubled' is being read outside a reactive context. Doing a full recompute."] +computed that read nothing observable: ["[mobx] Derivation 'Cart@14.constant' is created/updated without reading any observable value."] +reaction that read nothing observable: ["[mobx] Derivation 'Autorun@16' is created/updated without reading any observable value."] +── build: NODE_ENV = (unset) ── +makeAutoObservable in a subclass: threw Error: [MobX] 'makeAutoObservable' can only be used for classes that don't have a superclass +write outside an action, warnings: 1 +cycle: threw Error: [MobX] Cycle detected in computation Cycle@19.a: get a() { return this.a + 1; } +``` + +The last block again, with `NODE_ENV=production`: + +```text +── build: NODE_ENV = production ── +makeAutoObservable in a subclass: threw TypeError: Unable to delete property. +write outside an action, warnings: 0 +cycle: threw Error: [MobX] minified error nr: 32 ObservableObject.key,get a() { return this.a + 1; }. See mobx.js.org/errors +``` + +### Script 10: a base class whose constructor returns the proxy + +A spike on our unmodified library, not a port. + +`10-base-class-spike.ts`: + +```ts +// A spike, not a port: what MobX's "make `this` reactive inside the constructor" +// would look like for a Proxy store. The base constructor returns the proxy, so +// the subclass's field initialisers and constructor body run with `this` set to it. +import {createClassyStore, snapshot, subscribe} from './ours'; + +const outcome = (run: () => unknown) => { + try { + return JSON.stringify(run()); + } catch (error) { + return `threw ${(error as Error).constructor.name}: ${String((error as Error).message).slice(0, 80)}`; + } +}; + +class ClassyBase { + constructor() { + // biome-ignore lint/correctness/noConstructorReturn: the point of the spike + return createClassyStore(this); + } +} + +const registry: object[] = []; + +class Counter extends ClassyBase { + count = 0; + #secret = 1; + rows = [{n: 1}]; + constructor() { + super(); + registry.push(this); + } + increment = () => { + this.count++; + this.#secret++; + }; + get doubledSecret() { + return this.#secret * 2; + } + get total() { + return this.rows.reduce((sum, row) => sum + row.n, 0); + } +} + +const store = new Counter(); +let calls = 0; +subscribe( + store, + () => { + calls++; + }, + {sync: true}, +); + +console.log( + 'first snapshot, before any read through the store: rows frozen?', + Object.isFrozen(snapshot(store).rows), + '| row frozen?', + Object.isFrozen(snapshot(store).rows[0]), +); +const detached = store.increment; +detached(); +console.log( + 'arrow-function method: count', + store.count, + '| sync notifications', + calls, + '| snapshot count', + snapshot(store).count, +); +console.log( + 'getter that reads #secret, live:', + outcome(() => store.doubledSecret), +); +console.log( + 'getter that reads #secret, snapshot:', + outcome(() => snapshot(store).doubledSecret), +); +console.log( + '`this` kept by the constructor is the store:', + registry[0] === store, +); +calls = 0; +(registry[0] as Counter).count = 9; +console.log('write through that reference: sync notifications', calls); +store.rows[0].n = 5; +console.log( + 'getter over rows after a row write:', + store.total, + '| snapshot:', + snapshot(store).total, + '| rows frozen now?', + Object.isFrozen(snapshot(store).rows), +); +``` + +```text +first snapshot, before any read through the store: rows frozen? false | row frozen? false +arrow-function method: count 1 | sync notifications 1 | snapshot count 1 +getter that reads #secret, live: 4 +getter that reads #secret, snapshot: threw TypeError: Cannot access invalid private field (evaluating 'this.#secret') +`this` kept by the constructor is the store: true +write through that reference: sync notifications 1 +getter over rows after a row write: 5 | snapshot: 5 | rows frozen now? true +``` + +### Script 11: a subscriber added after a write, and a replaced object + +Port of stage 1 findings 21 and 26 +(`core.characterisation.notifications.test.ts`, +`core.characterisation.detached.test.ts`). + +`11-late-and-replaced.ts`: + +```ts +// Ports of "a subscriber added after a write sometimes hears that write" +// (finding 21) and "a subscription follows the object, not the property" +// (finding 26, detached test). +import { + autorun, + makeAutoObservable, + observe, + reaction, + runInAction, +} from 'mobx'; +import {batch, createClassyStore, subscribe} from './ours'; + +const flush = () => new Promise((resolve) => setTimeout(resolve, 0)); + +console.log('── a subscriber added after a write ──'); +{ + class Counter { + count = 0; + constructor() { + makeAutoObservable(this); + } + } + const store = new Counter(); + const early: number[] = []; + const late: number[] = []; + const lateEffect: number[] = []; + const disposeEarly = autorun(() => { + early.push(store.count); + }); + let disposeLate = () => {}; + let disposeEffect = () => {}; + runInAction(() => { + store.count = 1; + disposeLate = autorun(() => { + late.push(store.count); + }); + disposeEffect = reaction( + () => store.count, + (count) => { + lateEffect.push(count); + }, + ); + }); + console.log( + 'MobX: early autorun saw', + JSON.stringify(early), + '| autorun added after the write saw', + JSON.stringify(late), + '| reaction() added after the write fired', + JSON.stringify(lateEffect), + ); + disposeEarly(); + disposeLate(); + disposeEffect(); +} +{ + const store = createClassyStore({count: 0}); + let early = 0; + let late = 0; + subscribe( + store, + () => { + early++; + }, + {sync: true}, + ); + batch(() => { + store.count = 1; + subscribe( + store, + () => { + late++; + }, + {sync: true}, + ); + }); + console.log( + 'Ours, sync, inside batch(): early subscriber calls', + early, + '| subscriber added after the write, calls', + late, + ); + + const batched = createClassyStore({count: 0}); + let earlyBatched = 0; + let lateBatched = 0; + subscribe(batched, () => { + earlyBatched++; + }); + batched.count = 1; + subscribe(batched, () => { + lateBatched++; + }); + await flush(); + console.log( + 'Ours, batched: early subscriber calls', + earlyBatched, + '| subscriber added after the write, calls', + lateBatched, + ); +} + +console.log('── watching store.user, then replacing the user ──'); +{ + class Session { + user = {name: 'Ada'}; + constructor() { + makeAutoObservable(this); + } + } + const store = new Session(); + const byPath: string[] = []; + let byObject = 0; + const disposePath = autorun(() => { + byPath.push(store.user.name); + }); + const disposeObject = observe(store.user, () => { + byObject++; + }); + runInAction(() => { + store.user = {name: 'Grace'}; + }); + runInAction(() => { + store.user.name = 'Hedy'; + }); + console.log( + 'MobX: autorun(() => store.user.name) saw', + JSON.stringify(byPath), + '| observe(store.user, cb) calls', + byObject, + ); + disposePath(); + disposeObject(); +} +{ + const store = createClassyStore({user: {name: 'Ada'}}); + let calls = 0; + subscribe( + store.user, + () => { + calls++; + }, + {sync: true}, + ); + store.user = {name: 'Grace'}; + store.user.name = 'Hedy'; + console.log('Ours: subscribe(store.user, cb) calls', calls); +} +``` + +```text +── a subscriber added after a write ── +MobX: early autorun saw [0,1] | autorun added after the write saw [1] | reaction() added after the write fired [] +Ours, sync, inside batch(): early subscriber calls 1 | subscriber added after the write, calls 1 +Ours, batched: early subscriber calls 1 | subscriber added after the write, calls 1 +── watching store.user, then replacing the user ── +MobX: autorun(() => store.user.name) saw ["Ada","Grace","Hedy"] | observe(store.user, cb) calls 0 +Ours: subscribe(store.user, cb) calls 0 +``` diff --git a/review/stage-2/security.md b/review/stage-2/security.md new file mode 100644 index 00000000..ee7dfa3d --- /dev/null +++ b/review/stage-2/security.md @@ -0,0 +1,823 @@ +# Stage 2 report: security + +Subject: our own code and supply chain, not another library, so this report +has no ports and no table of counterparts. Read at commit `12fe57d` (branch +`release/1.0`), package version 0.11.0. All library line numbers below are at +that commit. + +## What I read and ran + +Read closely: + +- `packages/classy-store/src/utils/persist/persist.ts` and `persist.types.ts` + (the test files only where a finding touched them) +- `packages/classy-store/src/utils/devtools/devtools.ts` +- `packages/classy-store/src/utils/history/history.ts` +- `packages/classy-store/src/utils/cloneSnapshot/cloneSnapshot.ts` +- `packages/classy-store/src/utils/internal/internal.ts` (`canProxy`, + `findGetterDescriptor`, which persist, devtools and history rely on) +- `packages/classy-store/package.json`, `tsdown.config.ts`, the root + `package.json`, `bun.lock`, `bunfig.toml`, `.changeset/config.json` +- `.github/workflows/ci.yml`, `docs.yml`, `react-compatibility.yml`, + `react-next.yml`, `release.yml` +- The packed tarball `codebelt-classy-store-0.11.0.tgz` at the repository root + (listed, not unpacked), and the npm registry metadata for + `proxy-compare@3.0.1` and `@codebelt/classy-store@0.11.0` +- `website/content/docs/PERSIST_TUTORIAL.md` and `DEVTOOLS_TUTORIAL.md`, only + to see which `merge` and `enabled` idioms we teach + +Ran, all in +`/stage-2-security/`, +with Bun 1.4.4 importing our source by absolute path: + +- `repro/persist-input.ts`: hostile and malformed stored records, versions, + `migrate`, transforms, `merge`, expiry (output `repro/persist-input.out`) +- `repro/storage-events.ts`: crafted cross-tab events +- `repro/devtools-input.ts`: a fake Redux DevTools extension sending crafted + messages +- `repro/large-input.ts`, `repro/depth.ts`, `repro/depth2.ts`, + `repro/depth3.ts`: deep and large records +- `repro/reviver.ts`: the cost of stripping `__proto__` with a `JSON.parse` + reviver +- `audit/`: a copy of the manifests and `bun.lock` (nothing installed), where + `bun audit` ran +- `sig/`: `proxy-compare@3.0.1` installed with scripts disabled, where + `npm audit signatures` ran + +Nothing was run in the repository. + +## Threat model in one paragraph + +`persist` reads whatever is in storage under its key, and with `syncTabs` it +also reads every `storage` event under that key. `devtools` reads every message +the object at `window.__REDUX_DEVTOOLS_EXTENSION__` delivers. Who can write +those inputs: (a) script on the same origin, including XSS, which can already +do anything to the store directly; (b) a browser extension with access to the +page, which can too; (c) the user, through the browser's developer tools, on +their own client; (d) **another application on the same origin**, for example +two apps served from different paths of one `github.io` or intranet host, which +share `localStorage` but are otherwise separate; (e) an older or newer version +of the same application, which is not hostile but writes shapes this version +does not expect. Only (d) and (e) gain anything they did not already have, so +the findings below are about integrity and availability of one client's state. +None of them lets data reach another user or the server, and none pollutes +`Object.prototype`. + +## Findings + +### 1. Finding 48 settled: `persist` cannot swap the store's prototype unless the application lists `__proto__` itself + +- **What happens.** The restore loop writes only keys in the configured or + default property list (`propKeys`), and only when `Object.hasOwn(merged, key)` + holds. The default list comes from `Object.keys(snapshot(store))`, which + never contains `__proto__`, `constructor` or `prototype` for an ordinary + class store. So a record + `{"state":{"__proto__":{"polluted":1,"inc":"x"},"constructor":{"x":1},"prototype":{"y":1},"count":5}}` + restores `count` and nothing else: the prototype, methods and getters are + unchanged and `({}).polluted` is `undefined`. A custom `merge` written with + `Object.assign({}, current, persisted)` turns the stored `__proto__` into the + merged object's prototype, but `Object.hasOwn` then refuses the inherited + values, so the store is unchanged too. The spread idiom the tutorial teaches + (`{...current, ...persisted}`) keeps `__proto__` as an own key that no + listed property matches. Only when the application names the key in + `properties` (which `keyof T` does not offer, so it takes a cast or an + untyped array) does the assignment + `proxyStore['__proto__'] = clone` reach the inherited setter and replace the + prototype: methods and getters disappear. + + ```text + ## top-level __proto__/constructor/prototype, default properties + store proto is Settings.prototype: true count 5 ({}).polluted: undefined + ## top-level prototype keys named in properties + store proto is Settings.prototype: false inc is method: undefined doubled: undefined + ## custom merge using Object.assign({}, current, persisted) + store proto is Settings.prototype: true count 0 (stored __proto__.count 99 refused) + ``` + + Cross-tab events go through the same function and behave the same (repro + `storage-events.ts`, case 5). `withHistory` restores only snapshots of its + own store, and its `isData('__proto__')` is false because + `findGetterDescriptor` finds `Object.prototype.__proto__`. + +- **Where.** `persist.ts:337-339` (the `pending` filter), `persist.ts:363` + (the assignment), `persist.ts:42-68` (`resolveProperties`). +- **Who can cause it.** Only the application author, by listing the key. A + storage writer cannot on its own. Not serious. +- **Proposal: fix, cheaply.** In `resolveProperties`, throw when a listed key + is `__proto__`, `constructor`, `prototype`, a getter (finding 52) or a method, + and when an entry is an object without both `serialize` and `deserialize` + (finding 55). One validation pass at `persist()` time, so restore never has + to ask. +- **Kind:** hardening, diagnostics. +- **Cost:** `persist.ts` and its tests. Breaking only for code that lists a + getter or a malformed entry, which is already broken. Low risk. + +### 2. A nested `__proto__` key survives restore as an own data property and is written back on the next save + +- **What happens.** `JSON.parse` makes `"__proto__"` an ordinary own key. + `cloneSnapshotValue` copies every own key with `Object.defineProperty`, so + the restored object keeps that key as data and its real prototype stays + `Object.prototype`. The snapshot layer also uses `defineProperty` + (`snapshot.ts:213`, `snapshot.ts:269`), so snapshots are safe too. The + hazard is downstream: the store now holds `prefs` with own keys + `["__proto__","theme"]`, `JSON.stringify` writes it back on every save, and + application code that copies the object with `Object.assign(target, prefs)` + or a `for...in` loop that assigns `target[key] = value` replaces `target`'s + prototype. DevTools does the same for nested values (repro + `devtools-input.ts`: `prefs own keys: ["__proto__"]`). + + ```text + ## nested __proto__ in prefs + prefs own keys: ["__proto__","theme"] + prefs proto is Object.prototype: true + snapshot prefs proto is Object.prototype: true + ({}).polluted: undefined + ``` + +- **Where.** `cloneSnapshot.ts:22-41`, called from `persist.ts:363`; + `devtools.ts:87` and `devtools.ts:100`. +- **Who can cause it.** Anyone who can write the storage key (d, e above) or + send DevTools messages. It matters only with an unsafe copy in application + code. Low. +- **Proposal: fix.** Drop own `__proto__` keys at every depth when restoring + from storage or DevTools. The cheapest place is inside the walk + `cloneSnapshotValue` already does, behind a parameter that only `persist` + passes, so history keeps cloning exactly. A `JSON.parse` reviver would also + work, but measured about ten times slower to parse (2.1 MB record: 2.7 ms + plain, 35 ms with the reviver; `repro/reviver.out`). DevTools assigns parsed + values without cloning; see finding 7. +- **Kind:** hardening. +- **Cost:** `cloneSnapshot.ts`, `persist.ts`, `devtools.ts`, a test each. Not + breaking for any data a real application writes. Low risk. + +### 3. A deeply nested record bricks the store: restore succeeds, then every snapshot and every save throws, and the bad record is never replaced + +- **What happens.** Nothing bounds the depth of restored data. + `cloneSnapshotValue` and the snapshot builder both recurse once per level, + and the snapshot builder runs out of stack first. Between those two limits a + restore succeeds with no error, after which `snapshot(store)` throws + `RangeError` on every call. Every component that reads the store fails, every + automatic save fails with a `'write'` error, and `save()` rejects, so the + record that caused it stays in storage and the next page load repeats it. + Beyond the clone limit, restore fails part-way: fields earlier in the class + are restored, later ones are not, and a `'parse'` error is reported (the same + partial-restore shape as stage 1 finding 52). + + ```text + depth a (first field) b (deep field) snapshot errors + 15000 restored-a object ok + 16000 restored-a object RangeError (none) + 17000 restored-a object RangeError (none) + 18000 restored-a object RangeError (none) + 19000 restored-a default ok parse:RangeError + after an edit at depth 17000: errors write:RangeError | stored record unchanged: true + save() rejects with RangeError + ``` + + The limits are Bun's (JavaScriptCore's) and will differ by engine and by how + much stack is in use; browsers are likely to fail at lower depths. Large but + shallow input is only slow: 100,000 rows (2.1 MB) restore in 133 ms, 1,000,000 + rows (22 MB, beyond any browser's `localStorage` quota) in 1.5 s, with no + error (`repro/large-input.out`). +- **Where.** `cloneSnapshot.ts:37` (recursion), `snapshot.ts:235` + (`createSnapshotRecursive`), `persist.ts:360-377` (one field at a time). +- **Who can cause it.** A storage writer (d, e). An application can also do + it to itself with legitimately deep data, which is a core limit rather than + a persist one. Availability only, but persistent until the user clears site + data. Low to moderate for apps on a shared origin. +- **Proposal: fix the partial restore, and document the depth limit.** Clone + every value before assigning any, so a failure leaves the store untouched, + as a throwing `deserialize` already does (verified: `count` stayed 0). Then + take one `snapshot()` inside the same `try`; if it throws, put back the + fields just written and report `'parse'`. That turns a bricked store into a + reported, skipped record. A depth cap in `cloneSnapshotValue` is an + alternative, but any number we pick is engine-dependent. +- **Kind:** bug, hardening. +- **Cost:** `persist.ts` and a test. Not breaking. The rollback path needs + care with the existing `skipAutoSaveVersion` and `clearedVersion` + bookkeeping. Medium risk. + +### 4. Records persist cannot read are skipped without any report + +- **What happens.** A record that is valid JSON but not an envelope, or whose + `state` is not an object, is skipped with no error and no status change: + `5`, `null`, `"str"`, `[]`, `{"state":null}`, `{"state":"str"}`. So is a + record whose version differs when there is no `migrate`, and a `migrate` + that returns a string or an array. Only text that is not JSON, a `migrate` + that throws, or one that returns `null` is reported, as `'parse'`. An array + `state` passes the envelope check (stage 1 finding 53) and is handed to + `migrate`, whose type says `Record`. + + ```text + envelope 5 / null / "str" / [] / state null / state "str" / state [1,2,3] + count 0, errors: [], lastError: none + migrate returns a string / an array errors: [] + migrate throws errors: ["parse: migrate boom"] + migrate returns null errors: ["parse: null is not an object ..."] + ``` + +- **Where.** `persist.ts:287-294`, `persist.ts:312-315`, `persist.ts:321`. +- **Who can cause it.** Anyone who writes the key, mostly (e). It matters + because the store silently starts from defaults and the next save overwrites + the record, so data loss leaves no trace. +- **Proposal: fix.** Replace the scattered guards (which stage 1 finding 54 + shows are partly redundant) with one `readEnvelope(raw)` that returns either + a typed envelope or a reason, and report every reason through `onError` with + `'parse'`. Reject an array `state` and a `migrate` result that is not a plain + object. +- **Kind:** diagnostics, bug. +- **Cost:** `persist.ts`, `persist.types.ts` (perhaps an error class or code), + tests. Not breaking in the API; applications see new `onError` calls. Low. + +### 5. A version that is not a number counts as version 0 + +- **What happens.** `typeof envelope.version === 'number' ? envelope.version : 0` + makes a missing version, `"2"`, `null` and `{}` all version 0. With + `version: 2` configured, the record `{"version":"2",...}` is handed to + `migrate` as version 0, so a v0-to-v2 migration runs over data already in v2 + shape; without `migrate` it is dropped silently (finding 4). Negative, + fractional and huge numbers (`-1`, `2.5`, `1e308`) reach `migrate` as they + are. + + ```text + version "2" vs configured 2, with migrate: migrate got oldVersion 0 + version -1 / 2.5 / 1e308: migrate got -1 / 2.5 / 1e308 + version "2", no migrate: count 0, errors: [] + ``` + +- **Where.** `persist.ts:310-315`. +- **Who can cause it.** (e), or (d). Integrity of one client's state. Low. +- **Proposal: fix.** Only a missing `version` means 0 (keeps the documented + rule for old records). Any other value that is not a finite integer is an + unreadable record, reported as in finding 4. Document that `migrate` may + receive any integer, including one newer than the current version. +- **Kind:** bug, docs. +- **Cost:** `persist.ts`, the tutorial's migration section, a test. Breaking + only for records with a non-numeric version, which are already mishandled. + Low. + +### 6. With `expireIn` set, a record with no usable `expiresAt` never expires + +- **What happens.** Expiry is checked only when `expiresAt` is a number. A + record without it, or with a string, `null` or `1e308`, is restored however + old it is. `-1` and `0` expire as expected. + + ```text + expiresAt missing / "yesterday" / null / 1e308, expireIn 1000: restored (count 9) + expiresAt -1 / 0: skipped (count 0) + ``` + + The realistic case is benign: records written before the application added + `expireIn`, or by a version without it, live forever. The TTL is also not a + security control, since whoever writes the record chooses `expiresAt`. +- **Where.** `persist.ts:297-303`. +- **Who can cause it.** (e) mostly. Low. +- **Proposal: owner's call between fix and document.** Fixing means: when + `expireIn` is set, a record without a finite `expiresAt` counts as expired. + That drops pre-TTL records once, which is arguably what someone adding a TTL + wants. Either way, document that expiry bounds the age of data this + application wrote, and is not a way to make stored data trustworthy. +- **Kind:** bug or docs. +- **Cost:** `persist.ts` and a test, or one paragraph. Behaviour change for + old records if fixed. Low. + +### 7. DevTools time travel adds fields, calls setters, and differs from history's restore + +- **What happens.** Only `DISPATCH` messages whose payload type is + `JUMP_TO_STATE` or `JUMP_TO_ACTION` and which carry a `state` string are + acted on; `ROLLBACK`, `IMPORT_STATE`, `RESET`, `COMMIT`, `TOGGLE_ACTION` and + `ACTION` are ignored. For an acted-on message, every top-level key of the + parsed state is assigned unless the store has a getter or a function there. + Consequences, all verified: + - Prototype: safe. `__proto__` is skipped because `findGetterDescriptor` + finds the inherited accessor on `Object.prototype`, and `constructor` + because it reads as a function. This is incidental, not designed. + - Methods and getters cannot be replaced. + - **New fields are added** (`added`, `prototype` became own fields), and + fields missing from the jumped-to state are left as they are, so the store + can end up in a state DevTools never showed. + - **A setter-only accessor is called** with the message's value (`set level` + ran with `7`), because the skip checks only for a getter. + - Nested values are assigned as parsed, without the cloning history uses, and + keep own `__proto__` keys (finding 2). + - A malformed `state` is swallowed silently. + - An edit made in the same tick as a jump is never sent to DevTools, because + `isTimeTraveling` stays true until a microtask. + - Every snapshot is sent to the extension, so any secret held in store state + (a token, personal data) is copied into the extension's history. +- **Where.** `devtools.ts:82-113`, the skip at `devtools.ts:93-99`, the flag + at `devtools.ts:73-79` and `devtools.ts:107-109`. +- **Who can cause it.** The extension, or any page script that defines + `window.__REDUX_DEVTOOLS_EXTENSION__` before `devtools()` runs (a), or the + user (c). In production, if an application leaves `enabled` at its default + `true`, any user with the extension can edit the client state. That is the + user editing their own client, which the server must not trust anyway. Low. +- **Proposal: fix by reuse.** Apply the jumped-to state with the same function + history uses (`applySnapshot`'s rule: only keys that are data on the store, + delete data fields absent from the state, clone with the `__proto__` strip + from finding 2). Skip any accessor, not only getters. Report a malformed + message in development. Keep `enabled` defaulting to `true` (the library has + no portable way to detect production), but say in the API reference, next to + `enabled`, that the extension receives every state, so secrets should not + live in a store that has DevTools enabled outside development. +- **Kind:** hardening, simplification, docs. +- **Cost:** `devtools.ts`, `history.ts` (export the apply helper to a shared + internal module), docs, tests. Behaviour change for time travel only, which + becomes more faithful. Low. + +### 8. Cross-tab sync accepts events from any storage area, and synthetic events, under the same key + +- **What happens.** The handler checks the key, ignores `newValue === null`, + and, when `storageArea` is present, skips an event whose value is no longer + in that area. It does not check that the area is the configured storage. An + event from another `Storage` (for example `sessionStorage` in a same-origin + frame, or another library's area) with the same key is applied, and an event + with no `storageArea` (only a script can make one) skips the staleness check. + Events with another key, a `null` key (`localStorage.clear()` in another + tab), and events after `dispose()` are correctly ignored. + + ```text + 1. synthetic event without storageArea applied: true + 2. event from a different storage area with the same key applied: true theirs + 3. event whose value is no longer in the configured storage applied: false + 4. event with a different key applied: false + 7. clear() from another tab ignored + 8. event after dispose applied: false + ``` + +- **Where.** `persist.ts:446-453`. +- **Who can cause it.** Same-origin script (a), which gains nothing, or (d) + writing a different area under the same key. Low. +- **Proposal: document, and fix the cheap half.** When `storage` is itself + the event's kind of object (`storage instanceof Storage`), ignore events whose + `storageArea !== storage`. Do not require identity when the adapter is a + wrapper, or `syncTabs` stops working for wrapped `localStorage`. Document that + `syncTabs` listens to `localStorage` events under `name` whatever adapter is + configured. +- **Kind:** hardening, docs. +- **Cost:** `persist.ts`, `persist.types.ts` doc comment, a test. Not breaking + for real browser events. Low. + +### 9. Restored values are not validated against the class's field types + +- **What happens.** Any JSON value is restored into any field: a string into + `count`, an object into `label`, and `{"0":"x","length":3}` into an array + field, after which `Array.isArray(store.items)` is false and + `store.items.map` throws in application code. JSON cannot forge a `Date`, + `ReactiveMap` or class instance, because `cloneSnapshotValue` keeps the + parsed object's own prototype (`Object.prototype` or `Array.prototype`). + The tutorial already says stored input is `unknown` and transforms should + validate it (`PERSIST_TUTORIAL.md:145`), and a throwing `merge` or + `deserialize` already rejects the whole record before anything is assigned + (verified). +- **Where.** `persist.ts:321-339`. +- **Who can cause it.** (d), (e). Low; it is the application's schema. +- **Proposal: document, possibly adapt.** Say once, prominently, that stored + data is untrusted input and that a `merge` function is the place to validate + the whole record (throwing rejects it atomically). Show a short validating + `merge` with a schema library. A dedicated `validate` option would duplicate + `merge`; I would not add one before 1.0. +- **Kind:** docs. +- **Cost:** the persist tutorial and API reference. None to the code. + +### 10. Runtime dependency: `proxy-compare` 3.0.1 + +- **What happens.** It is the only runtime dependency and the published code + imports it externally (`dist/storeRuntime.mjs`, line 2). Registry metadata: + one maintainer (npm user `daishi`, the author of Valtio and Zustand), MIT, no + dependencies, no `preinstall`, `install` or `postinstall` script (its + scripts are build and test only), published 2024-11-22 and not changed + since, registry signature verified (`npm audit signatures`: "1 package has a + verified registry signature"), no provenance attestation. We declare it + exactly (`"proxy-compare": "3.0.1"`, `packages/classy-store/package.json`), + and `bunfig.toml` sets `exact = true` for future additions. Valtio 2.3.2 + declares `^3.0.1`. +- **Where.** `packages/classy-store/package.json` `dependencies`. +- **Who can cause it.** A takeover of that one npm account. With an exact pin + a malicious 3.0.2 does not reach our consumers until we release with it; the + cost is that a security fix in it does not reach them either, and that a + consumer with Valtio may install two copies once 3.0.2 exists. +- **Proposal: accept, and document the choice.** The package is small (a few + hundred lines), stable and has no dependencies of its own. Keep the exact pin + for 1.0, watch it with Dependabot or Renovate, and say in `CONTRIBUTING.md` + why it is exact. Vendoring it would remove the account risk but makes us the + maintainer of its fixes; not worth it unless it goes unmaintained. +- **Kind:** hardening, docs. +- **Cost:** none, or one paragraph. + +### 11. Development dependencies: 17 advisories, none in the published artifact + +- **What happens.** `bun audit` over the committed lockfile: + + ```text + baseline-browser-mapping@2.10.25 moderate DoS on invalid input + via next, @angular/build, and @babel/core (dev dependency of the package) + browserslist@4.28.2 2 high memory growth; prototype write via custom stats file + via @angular/build, and @babel/core (dev dependency of the package) + fast-uri@3.1.0 8 high, 2 moderate, 2 low URI parsing (ajv) + via website > serve, @angular/cli, @angular/build + immutable@5.1.5 2 high DoS (sass) + via examples (next, vite, @angular/build) + 17 vulnerabilities (12 high, 3 moderate, 2 low) + ``` + + None can reach a consumer: the tarball holds only `dist`, `README.md`, + `CHANGELOG.md`, `LICENSE` and `package.json` (verified by listing the packed + 0.11.0 tarball: 98 entries, all compiled output and source maps), and + `dist` imports only `proxy-compare` and the framework peers. All four + packages run at build or test time in CI on inputs we write (browserslist + queries in our configs, URIs in our configs, our own Sass). Bun runs no + dependency lifecycle scripts except its built-in trusted list and the root's + `trustedDependencies: ["sharp"]` (`bun.lock:168`). +- **Where.** `bun.lock`. +- **Who can cause it.** Nobody outside the project, as far as I can see. Low. +- **Proposal: fix at the next dependency refresh, not a release blocker.** + `bun update` within ranges clears most of them (`fast-uri` 3.1.9, + `browserslist` above 4.28.6, `immutable` 5.1.8). Add a `bun audit` step to + CI that reports but does not fail, or fails only for packages reachable from + `packages/classy-store`'s `dependencies`. +- **Kind:** hardening. +- **Cost:** `bun.lock`, perhaps `ci.yml`. Not breaking. + +### 12. The release job gives every dependency the npm publishing identity + +- **What happens.** `release.yml` runs one job with `contents: write`, + `pull-requests: write` and `id-token: write`. In that job it runs + `bun install --frozen-lockfile` (about 1,800 locked packages, including the + website's and examples' trees), `bun run build` (tsdown and its plugins), + `changesets/action@v1` (which runs `changeset version` and our `biome format` + script), then `npm publish --provenance` of the `dist` that build produced. + There is no npm token in the workflow: publishing uses npm trusted publishing + over OIDC, and the registry confirms it (`_npmUser` of 0.11.0 is + `GitHub Actions `, with a SLSA provenance + attestation). That design is good, but anything that executes in the job can + request the OIDC token from the runner's environment and publish its own + version, or rewrite `dist` before `npm publish` packs it. The provenance would + still say it came from this workflow. `actions/checkout` also leaves the + `GITHUB_TOKEN` (with `contents: write`) in `.git/config` for the whole job. + Actions are pinned by moving major tags (`actions/checkout@v6`, + `actions/setup-node@v6`, `oven-sh/setup-bun@v2`, `changesets/action@v1`), not + commit SHAs, so a moved tag on a third-party action runs with the same + rights. `ci.yml`, `react-compatibility.yml` and `react-next.yml` declare no + `permissions` (pull requests from forks get a read-only token anyway); + `docs.yml` declares `contents: read` and grants `pages` and `id-token` only to + the deploy job, which is the pattern the release job should follow. Node is + `"24"` (floating), Bun is pinned to 1.4.4. +- **Where.** `.github/workflows/release.yml` (permissions block and steps), + `ci.yml`, `react-compatibility.yml`, `react-next.yml` (no `permissions`). +- **Who can cause it.** A compromised development dependency or a moved action + tag, the realistic supply-chain path into consumers. Moderate: it is the one + route by which someone else's compromise becomes a malicious + `@codebelt/classy-store` release with valid provenance. +- **Proposal: fix before 1.0.** + 1. Split the release into two jobs. Job one (`contents: write`, + `pull-requests: write`, no `id-token`) installs, builds, runs + changesets, and on a publishable commit runs `npm pack` and uploads the + tarball as an artifact. Job two (`id-token: write` and `contents: read` + only) installs nothing, downloads the tarball, and runs + `npm publish --provenance`. A compromised dependency then never + sees the OIDC token. + 2. Put job two in a GitHub environment (for example `npm`) with the owner as + required reviewer, and configure the npm trusted publisher to accept only + that environment. This also matches the rule that the owner alone + releases. + 3. Pin every third-party action to a full commit SHA with the tag in a + comment, and let Dependabot update them. + 4. `persist-credentials: false` on checkouts that do not push; in the + release, push the tags with the token passed explicitly. + 5. Add `permissions: contents: read` at the top of the three workflows that + lack it. + 6. In the npm package settings, once trusted publishing works, disallow + publishing with tokens. +- **Kind:** hardening. +- **Cost:** `.github/workflows/*.yml` and npm settings. No code, not + breaking. Medium risk only in the sense that the first release after the + change must be watched. + +### 13. What the published tarball contains + +- **What happens.** `files` is `dist`, `README.md`, `CHANGELOG.md`, `LICENSE`. + The packed 0.11.0 tarball has 98 entries: those four files, `package.json`, + and `.mjs`, `.cjs`, `.d.mts`, `.d.cts` and `.map` files under `dist`. The + source maps embed `sourcesContent`, which is our public source and no + secret. No test, fixture, `.env` or configuration file is included, and the + library source has no `process.env`, `eval`, `new Function` or `innerHTML`. + The published `package.json` has no install-time scripts; it keeps + `prepack` (`cp ../../README.md .`), which runs only when someone packs from a + checkout. Unpacked size is 543 KB, mostly source maps. +- **Where.** `packages/classy-store/package.json` `files`, `scripts.prepack`. +- **Who can cause it.** Nothing to cause. Informational. +- **Proposal: accept.** Optionally strip the development scripts from the + published manifest, but nothing here is a risk. +- **Kind:** none needed. +- **Cost:** none. + +## Stage 1 findings followed up + +- **48** (`Object.assign` with `__proto__` swaps the prototype): settled in + finding 1. Persist does not use `Object.assign`, and its key filter keeps + `__proto__` out unless the application lists it. DevTools skips it by + accident of `findGetterDescriptor` (finding 7). +- **52** (a getter in `properties` is saved and restoring fails part-way): + still true. Finding 1 proposes rejecting getters at `persist()` time, and + finding 3 proposes the clone-everything-first restore that makes any failure + atomic. +- **53** (an array `state` passes the envelope check): still true, and the + array also reaches `migrate`, whose type says it cannot. Finding 4. +- **54** (dead or redundant code in `persist.ts`): none of it is a security + issue. The redundant `typeof envelope !== 'object'` guard is safe because a + primitive's `state` reads as `undefined`. Finding 4 proposes replacing the + guards with one `readEnvelope` that reports why a record was refused. + +## API question 8: development-only diagnostics that would catch silent failures + +From this subject's side, in order of value: + +1. **Unreadable stored records** (finding 4, 5): report through `onError` as + `'parse'` with a reason. This is not development-only; it is a missing + error. +2. **Bad `properties` entries** (finding 1, stage 1 findings 52 and 55): throw + at `persist()` time for a getter, a method, a prototype key or a malformed + transform. +3. **A restore that leaves the store unsnapshottable** (finding 3): one + `snapshot()` after restore, inside the existing `try`, turns a bricked store + into a reported failure. Cheap enough to run always. +4. **DevTools**: warn in development on a malformed time-travel message and on + a key that does not exist on the store, instead of swallowing the first and + silently adding the second (finding 7). +5. **`syncTabs` with an adapter that is not `localStorage`**: warn in + development, since the option then listens to `localStorage` events that + the adapter never produces (`persist.types.ts:113-114` already says so in a + comment). + +## Verified by running code, and only read + +Verified by running code (scripts and outputs in the scratch folder named +above): + +- Findings 1 to 9: every behaviour quoted in their output blocks, against our + source at `12fe57d`, under Bun 1.4.4. The depth limits in finding 3 are + Bun's and were not measured in a browser. +- Finding 10: registry metadata, absence of install scripts, registry + signature. +- Finding 11: `bun audit` output over a copy of the lockfile. +- Finding 12: that 0.11.0 was published by GitHub Actions over OIDC with a + provenance attestation (registry metadata). +- Finding 13: the tarball listing, and the absence of `process.env`, `eval`, + `new Function` and `innerHTML` in `packages/classy-store/src` (grep). + +Only read, not run: + +- That anything running in the release job can obtain the OIDC token and + publish (finding 12). This is how GitHub's OIDC and npm trusted publishing + work as documented; I did not attempt it. +- That Bun's default trusted list is the only set of dependency scripts that + run on install. +- That `keyof T` of a class instance type excludes `__proto__` and + `constructor` (finding 1). I did not compile a test. +- That an array `state` reaches `migrate` (finding 4): read from + `persist.ts:287-315`, not run with a version mismatch. +- That browsers hit the recursion limits of finding 3 at lower depths than + Bun. +- I did not read `~/.npmrc` or any credential file, and found no secret in the + tracked files (`git ls-files` has no `.env`, `.npmrc`, key or certificate + file). + +## Appendix: reproduction code and output + +The scripts are in +`/stage-2-security/repro/`. +The essential parts follow. + +### Hostile stored records (`persist-input.ts`, abridged) + +```ts +class Settings { + count = 0; + label = 'a'; + prefs: Record = {theme: 'light'}; + items: string[] = []; + get doubled() { + return this.count * 2; + } + inc() { + this.count++; + } +} + +async function restore(title: string, raw: string | null, extra = {}) { + const store = createClassyStore(new Settings()); + const storage = memoryStorage(raw); // a Map behind getItem/setItem/removeItem + const h = persist(store, {name: 'k', storage, onError, ...extra} as never); + await h.hydrated; + // prints prototype, fields, own keys of prefs, ({}).polluted, errors +} + +await restore( + 'top-level prototype keys named in properties', + `{"version":0,"state":{"__proto__":{"polluted":1},"constructor":{"x":1},"count":5}}`, + {properties: ['count', '__proto__', 'constructor']}, +); +await restore( + 'nested __proto__ in prefs', + `{"version":0,"state":{"prefs":{"__proto__":{"polluted":1,"isAdmin":true},"theme":"dark"}}}`, +); +await restore( + 'custom merge using Object.assign({}, current, persisted)', + `{"version":0,"state":{"__proto__":{"count":99,"polluted":1}}}`, + {merge: (p: object, c: object) => Object.assign({}, c, p)}, +); +// ...envelopes 'not json', '5', 'null', '"str"', '[]', state null/'str'/[1,2,3]; +// versions undefined, -1, '2', 2.5, 1e308, {}, null against version 2; +// migrate throwing / returning null, a string, an array; deserialize throwing; +// merge returning null; expiresAt undefined, 'yesterday', -1, 0, 1e308, null. +``` + +Output, condensed (the full output is `persist-input.out`): + +```text +top-level __proto__/constructor/prototype, default properties + proto Settings: true count 5 inc: function doubled 10 ({}).polluted: undefined errors [] +top-level prototype keys named in properties + proto Settings: false count 5 inc: undefined doubled undefined own constructor: true +nested __proto__ in prefs + proto Settings: true prefs own keys ["__proto__","theme"] prefs proto Object.prototype: true +custom merge using Object.assign / using spread + proto Settings: true count 0 / 3 ({}).polluted: undefined +stored keys named after a method and a getter + count 2 inc: function doubled 4 +envelope not json errors ["parse: JSON Parse error: Unexpected identifier \"not\""] +envelope 5, null, "str", [], state null, state "str", state [1,2,3] + count 0 errors [] +wrong field types count "hello" label {"nested":true} items {"0":"x","length":3} isArray false +version missing / {} / null migrate got oldVersion 0 +version "2" migrate got oldVersion 0 (configured version is 2) +version -1 / 2.5 / 1e308 migrate got -1 / 2.5 / 1e308 +version "2", no migrate count 0 errors [] +migrate throws errors ["parse: migrate boom"] +migrate returns null errors ["parse: null is not an object (evaluating 'Object.keys(state)')"] +migrate returns string/array count 0 errors [] +deserialize throws on label count 0 (nothing assigned) errors ["parse: bad label"] +merge returns null count 0 errors ["parse: null is not an object"] +expiresAt missing/"yesterday"/null/1e308 count 9 (restored) +expiresAt -1 / 0 count 0 (expired) +``` + +### Cross-tab events (`storage-events.ts`) + +```ts +function fire(init: { + key: string | null; + newValue: string | null; + storageArea?: unknown; +}) { + const event = new Event('storage') as Event & Record; + Object.assign(event, init); // Bun has no StorageEvent; persist reads only these three + globalThis.dispatchEvent(event); +} +const h = persist(store, {name: 'app', storage, syncTabs: true, onError}); +fire({key: 'app', newValue: rec({count: 1})}); +otherArea.map.set('app', rec({count: 2, token: 'theirs'})); +fire({ + key: 'app', + newValue: rec({count: 2, token: 'theirs'}), + storageArea: otherArea, +}); +fire({key: 'app', newValue: rec({count: 3}), storageArea: storage}); +fire({key: 'other', newValue: rec({count: 4})}); +fire({ + key: 'app', + newValue: '{"version":0,"state":{"__proto__":{"x":1},"count":5}}', +}); +fire({key: 'app', newValue: 'garbage'}); +fire({key: null, newValue: null}); +h.dispose(); +fire({key: 'app', newValue: rec({count: 99})}); +``` + +```text +1. synthetic event without storageArea applied: true +2. event from a different storage area with the same key applied: true theirs +3. event whose value is no longer in the configured storage applied: false +4. event with a different key applied: false +5. __proto__ in event: count 5 proto kept true +6. malformed event value -> errors: ["parse: JSON Parse error: Unexpected identifier \"garbage\""] +7. clear() from another tab ignored, count stays 5 +8. event after dispose applied: false +``` + +### DevTools messages (`devtools-input.ts`, abridged) + +```ts +globalThis.window = globalThis; +globalThis.__REDUX_DEVTOOLS_EXTENSION__ = { + connect: () => ({ + init, + send, + subscribe: (l) => { + listener = l; + return () => { + listener = undefined; + }; + }, + }), +}; +class Account { + count = 0; + role = 'user'; + prefs = {theme: 'light'}; + #secret = 1; + get isAdmin() { + return this.role === 'admin'; + } + set level(v: unknown) { + console.log(' setter "level" called with', JSON.stringify(v)); + } + promote() { + this.role = 'admin'; + } +} +const store = createClassyStore(new Account()); +devtools(store, {name: 'test'}); +jump({ + count: 5, + isAdmin: true, + promote: 'replaced', + constructor: {evil: 1}, + prototype: {p: 1}, + level: 7, + added: 'new field', +}); +listener({ + type: 'DISPATCH', + payload: {type: 'JUMP_TO_STATE'}, + state: + '{"__proto__":{"promote":"x","polluted":1},"prefs":{"__proto__":{"isAdmin":true}}}', +}); +// then ROLLBACK, IMPORT_STATE, RESET, COMMIT, TOGGLE_ACTION, ACTION with count 77/78; +// jump({count: 1}); jump({count: 2}) followed by store.count = 3 in the same tick; '{oops'. +``` + +```text +init payload keys: [ "count", "role", "prefs", "isAdmin", "level" ] + setter "level" called with 7 +count: 5 +isAdmin still a getter: false function +promote still a method: function +constructor own field: false prototype own field: true +added field: true new field +store proto unchanged: true +prefs own keys: ["__proto__"] prefs proto plain: true +({}).polluted: undefined +count after other message types: 5 +fields not in the jumped-to state survive: {"count":1,"role":"user","prefs":{"__proto__":{"isAdmin":true}},"prototype":{"p":1},"added":"new field","isAdmin":false} +edit in the same tick as a jump was sent: false count 3 +malformed state ignored without report +listener removed on dispose: true +``` + +### Deep and large records (`depth2.ts`, `depth3.ts`, `large-input.ts`) + +```ts +class S { + a: unknown = 'default-a'; + b: unknown = 'default-b'; +} +for (const d of [15000, 16000, 17000, 18000, 19000, 20000]) { + const raw = `{"version":0,"state":{"a":"restored-a","b":${'{"n":'.repeat(d)}0${'}'.repeat(d)}}}`; + const store = createClassyStore(new S()); + const h = persist(store, {name: 'k', storage: mapStorage(raw), onError}); + await h.hydrated; + // try snapshot(store); print a, typeof b, snapshot result, errors +} +// depth3.ts: at depth 17000, edit store.a, wait, compare the stored record, then save() +``` + +```text +15000 a= restored-a b= object snapshot ok errors +16000 a= restored-a b= object snapshot RangeError errors +17000 a= restored-a b= object snapshot RangeError errors +18000 a= restored-a b= object snapshot RangeError errors +19000 a= restored-a b= string snapshot ok errors parse:RangeError +20000 a= restored-a b= string snapshot ok errors parse:RangeError + +after an edit: errors write:RangeError | stored record unchanged: true +save() rejects with RangeError + +100000 rows (2.1 MB): restore 133.1 ms, list.length=100000, ok, ok, errors=[] +1000000 rows (21.9 MB): restore 1483.1 ms, list.length=1000000, ok, ok, errors=[] +``` + +### Cost of a `__proto__`-stripping reviver (`reviver.ts`) + +```ts +const rev = (k: string, v: unknown) => (k === '__proto__' ? undefined : v); +// JSON.parse(raw) vs JSON.parse(raw, rev) on a 2.1 MB record, three rounds +``` + +```text +2.1 MB: plain 4.0 ms, with __proto__ reviver 41.3 ms +2.1 MB: plain 2.6 ms, with __proto__ reviver 34.1 ms +2.1 MB: plain 2.7 ms, with __proto__ reviver 35.2 ms +["b"] +``` diff --git a/review/stage-2/signals.md b/review/stage-2/signals.md new file mode 100644 index 00000000..21c4aa3b --- /dev/null +++ b/review/stage-2/signals.md @@ -0,0 +1,3363 @@ +# Stage 2: Preact Signals and the TC39 Signals proposal + +Read-only comparison of our getter memoization and our batching with Preact +Signals and with the reference polyfill of the TC39 Signals proposal, for +stage 3 of the pre-1.0 review. Nothing in the repository was changed apart +from this file. + +This report builds on `review/stage-2/mobx.md`, findings 1 to 5, and does not +repeat them. Where it agrees with that report it says so in a line. Where it +corrects it (finding 2 below), it shows the reproduction. + +## The libraries and what was read + +- **Preact Signals:** `@preact/signals-core` 1.14.5. Source at + `github.com/preactjs/signals`, tag `@preact/signals-core@1.14.5`, commit + `30a797e962c76cc2e623e84f4194a00b9f0c5c8f` (2026-10-27). Read in full: + `packages/core/src/index.ts` (1,173 lines). +- **TC39 Signals polyfill:** `signal-polyfill` 0.2.3. Source at + `github.com/proposal-signals/signal-polyfill`, tag `v0.2.3`, commit + `958ad56b92e321b84673a42c3d16109f72209017` (2026-11-16). Read in full: + `src/graph.ts`, `src/computed.ts`, `src/signal.ts`, `src/wrapper.ts`. +- **What ran:** the published packages at those versions, in a scratch + folder, on Bun 1.4.4. +- **Our side:** `release/1.0` at `ac38f2f`. Scripts import + `packages/classy-store/src/index.ts` by absolute path. The spikes in finding + 1, 2, 3 and 6 ran on copies of `src/` in the scratch folder; their diffs are + in the appendix. +- **Our source read closely:** `core/core.ts` (`activeTracker`, `recordDep`, + `recordComputedDep`, `areDepsValid`, `evaluateComputed`, the `get` trap, + `notifyMutation`, `settleTransaction`, `transactional`, `batch`, `deliver`), + `core/core.types.ts`, and in `snapshot/snapshot.ts` `computeWithTracking`, + `areMemoizedDepsValid`, `evaluateSnapshotGetter`, `installMemoizedGetters`. + +## How they differ, in short + +Both libraries are push-pull graphs with version numbers. + +1. **Every source is its own node with a version.** A write bumps that + source's version and a global counter (Preact `globalVersion`, + `index.ts:161`, `:469-470`; the polyfill's `epoch`, `graph.ts:26`, + `signal.ts` `signalValueChanged`). A computed records each source it read + and the version it saw. +2. **Push marks, pull recomputes.** A write marks observed computeds as + possibly stale (Preact `_notify`, `index.ts:737-749`; polyfill + `consumerMarkDirty`, `graph.ts:330-334`). A read of a computed first asks + "has anything at all changed since I was last clean?" with the global + counter, then polls its sources in recorded order, refreshing each nested + computed and comparing its version (Preact `needsToRecompute`, + `index.ts:504-530`; polyfill `consumerPollProducersForChange`, + `graph.ts:390-415`). A nested computed whose value came out equal keeps its + version, so the outer one does not recompute. +3. **Unobserved computeds still work.** Neither library needs an observer for + memoization: the global counter gives a clean read in O(1) without any + subscription. + +We have no per-source nodes. A getter records three kinds of dependency +(`core.types.ts:9-27`): the version of a child node, the value of a primitive +field, and another getter's value. Every read re-walks that list, and a +dependency on another getter is checked by re-walking that getter's list +recursively (`core.ts:137-142`). + +So the signal libraries have nothing to say about snapshots, structural +sharing or ownership. They are directly comparable on three things: what a +clean read costs, how a nested getter is revalidated, and how batching and +delivery work. + +## Findings + +Each reproduction is an excerpt from the output of a script in the appendix, +where every script and its whole output are given. Times are microseconds +unless marked, from single runs on a laptop that was doing other work; read +them for shape, not for the last digit. + +### 1. A clean read costs time that doubles per level; a global stamp makes it constant + +**What they do.** Preact keeps `_globalVersion` on each computed and returns +at once when the global counter has not moved since the computed was last +found clean (`Computed.prototype._refresh`, `index.ts:661-664`). The counter +is taken before the body runs, so a body that writes is checked again next +time. When the computed is observed, a cheaper check comes first: tracking +and not marked outdated means clean (`index.ts:656-658`). The polyfill does +the same with `lastCleanEpoch` (`producerUpdateValueVersion`, +`graph.ts:277-298`), but stamps after the body has run (`graph.ts:297`). + +**What we do.** `evaluateComputed` calls `areDepsValid` on every read +(`core.ts:166-169`), and a dependency on a getter re-walks that getter's list +(`core.ts:141`). A getter reached by two paths is walked twice, its +dependencies four times, and so on. + +**Difference in behaviour.** Script 01, the ladder from the MobX report's +script 07: two getters per level, each reading both getters of the level +below. No body runs on a clean read in any library. Excerpt: + +```text + clean read of the top read after an unrelated write +depth | ours live | Preact | polyfill | ours live | Preact | polyfill + 8 | 10.28 | 0.07 | 0.08 | 7.27 | 0.42 | 0.70 + 16 | 1540.32 | 0.04 | 0.06 | 1111.15 | 0.68 | 1.11 + 20 | 16548.01 | 0.04 | 0.04 | 16424.39 | 0.68 | 0.92 + 200 | not run | 0.05 | 0.05 | not run | 11.58 | 9.55 +``` + +A spike (`spike-stamp`, appendix) adds a `stamp` to `ComputedEntry`: the +node's own version when the entry was last found valid, taken before the body +runs. A read whose node version equals the stamp returns at once, and a +nested entry found valid is stamped too, so each getter is walked at most +once per version. Script 01 against the spike, from the previous run of this +task: + +```text +depth | clean read | read after an unrelated write | read after base changed + 20 | 0.06 | 1.40 | 11.86 + 200 | 0.09 | 21.46 | 832.34 +``` + +The clean read and the read after an unrelated write become constant and +linear. The everyday case improves too (script 10, one getter over three +fields, nanoseconds per read, best of five rounds): + +```text +base: getter, clean 61 ns | write to another field + getter 206 ns | write to a field it reads + getter 316 ns +spike-stamp: getter, clean 46 ns | write to another field + getter 238 ns | write to a field it reads + getter 321 ns +``` + +All ports 02 to 08 give the same output on the spike as on the base. The +"read after base changed" column is still quadratic on this spike (832 at +200), because a stale nested entry still makes the outer one recompute, which +re-validates the chain below; finding 2 removes that. + +**Proposal: adopt.** This is step 2 of MobX finding 3, with two details the +signal libraries settle: + +- The node's own `version` is enough as the stamp; no new global counter is + needed. A write anywhere under a node bumps that node's version + (`notifyMutation`, `core.ts:222-224`), so for a getter on the root it is a + per-store counter. Preact needs a global counter only because its sources + are not in one tree. +- Take the stamp before the body runs, as Preact does, not after, as the + polyfill does. Script 06 shows the polyfill's choice: a computed that writes + the signal it reads stays at its first value (`values [1,1,1] | runs 1`), + where Preact and our live layer re-run. + +It also removes stage 1 finding 32 on the live store as a side effect: a +getter over a missing property is no longer recomputed on every read (probe, +appendix: `returns the same object twice: false` on the base, `true` on all +three spikes), and it still sees the property once it is written (`5`). + +**Kind.** Performance. + +**Cost.** `core.ts` (`evaluateComputed`, `areDepsValid`) and `core.types.ts`, +about ten lines. Not breaking. The one edge, already named in the MobX +report: a primitive written through the raw object is noticed only after the +next write through a proxy, which is how snapshots behave today (stage 1 +finding 11). Risk low. Measure with `bun run benchmark:core`. + +### 2. Revalidate a nested getter by refreshing it, but compare its node version as well as its value + +**What they do.** `needsToRecompute` (`index.ts:504-530`) walks the sources in +recorded order. For each one it compares the version it saw; if that matches +it calls `_refresh()` on the source, which recomputes it if needed, and +compares the version again. A computed whose new value is equal keeps its +version (`index.ts:679-687`; polyfill `producerRecomputeValue`, +`computed.ts:124-140`, with `equals`), so the outer computed stays valid. +Values held by signals are plain values: a computed returning the same object +means nothing below it changed. + +**What we do.** A dependency on a getter is valid only if that getter's whole +list is valid (`core.ts:141`); whether its value changed is never asked. Our +snapshot layer already does it the other way: it reads the getter through its +own memo and compares the value (`areMemoizedDepsValid`, `snapshot.ts:104-110`). + +**Difference in behaviour.** Script 02, a cutoff: `parity = a % 2` and +`label` reads `parity`. After `a` goes from 1 to 3, the run counts: + +```text +ours live a 1 -> 3, d and label {"b":2,"c":2,"d":2,"parity":2,"label":2} +Preact a 1 -> 3, unobserved {"b":2,"c":2,"d":2,"parity":2,"label":1} +polyfill a 1 -> 3, unwatched {"b":2,"c":2,"d":2,"parity":2,"label":1} +``` + +MobX finding 3, step 1, proposes exactly the signal libraries' rule: refresh +the nested getter, compare the value. A spike of that rule +(`spike-refresh`, appendix) fixes the cutoff above, and breaks this case +(`probe-first.ts`): + +```ts +class Table { + rows = [{price: 1}]; + get first() { + return this.rows[0]; + } + get firstPrice() { + return this.first.price; + } +} +const store = createClassyStore(new Table()); +store.firstPrice; // 1 +store.rows[0].price = 2; +store.firstPrice; // base: 2, spike-refresh: 1, spike-one: 2 +``` + +`first` returns the same store proxy before and after, so the value compare +says "unchanged". `firstPrice` read `.price` on a child of the root, which +`recordDep` does not record (`core.ts:91`). The only thing that catches it +today is the recursive walk into `first`'s list, which holds a version +dependency on `rows`. Our getters can return live store nodes; a signal never +can. So value equality is not enough for us. + +**Proposal: adapt.** Refresh the nested getter through its own memo and +compare both its value and, when the value is a store node, that node's +version. The `spike-one` spike (finding 9) does this with a `versionOf(value)` +lookup in `internalsMap`, and gives `2` above, `label` 1 in the cutoff, and +the error recovery of finding 4. On top of finding 1 it brings "read after +base changed" from quadratic to linear (script 01: 183.61 at depth 200 +against 832.34 with the stamp alone, and 25,660 at depth 20 on the base). +While refreshing, push a frame that records nothing, so reads made during +validation are not taken for the running getter's dependencies. Preact gets +the same effect another way: `needsToRecompute` calls `_refresh()` on a +source directly instead of reading `.value`, so nothing is recorded, and +`_refresh` sets its own context only when it recomputes +(`index.ts:674-693`). + +**Kind.** Performance, bug (the cutoff), and a correction to MobX finding 3. + +**Cost.** `core.ts` (`areDepsValid`), `core.types.ts`. Not breaking. Changes +the pinned run counts at `core.characterisation.getters.test.ts:133`. Risk +medium: the probe above must become a test before the change, and so must a +getter returning a child array that a later getter iterates. + +### 3. A getter that reads the same field in a loop records it once per read + +**What they do.** Preact records a source once per run: `addDependency` reuses +the node already attached to the signal for this context, and a second read +in the same run records nothing (`index.ts:208-256`, the checks on +`node._target !== evalContext` and `node._version === -1`). The polyfill +records every read, by position (`producerAccessed`, `graph.ts:214-260`), and +pays for it in polling. + +**What we do.** `recordDep` pushes an entry on every read +(`core.ts:93-104`). `this.rows` read inside the loop condition and the body +of a 1,000-row loop gives 2,000 version entries, each re-checked on every +read. The snapshot layer dedupes already (`readProps`, `snapshot.ts:77`, +`:85-88`). + +**Difference in behaviour.** Script 09, the same total computed two ways: + +```text +1000 rows first read | clean read | read after an unrelated write +ours live, loop 1204.38 us | 26.80 us | 25.96 us +ours live, hoisted 330.33 us | 0.12 us | 0.14 us +Preact, loop 327.46 us | 0.16 us | 0.12 us +polyfill, loop 576.67 us | 0.12 us | 12.46 us +polyfill, loop: recorded sources 2001 +``` + +The stamp of finding 1 fixes the clean read (0.24) but not the read after an +unrelated write (27.60). `spike-one`, which keys the list by property, gives +0.26 and 0.39. Writing `this.rows[i]` in a loop is the obvious way to write a +getter, and stage 1 finding 3's "200 nanoseconds per row" baseline is this +shape. + +**Proposal: adopt.** Record a property once per run. A `Set` of recorded +properties on the tracker frame, as `computeWithTracking` has, is the +smallest change. The first read is the one that counts. + +**Kind.** Performance. + +**Cost.** `core.ts` (`recordDep`, the tracker frame). Not breaking. Risk low. + +### 4. A computed that throws: both libraries cache the error, record the dependency first, and get stuck on a cycle + +**What they do.** Both cache a thrown error as the computed's result with the +dependencies read before the throw (Preact `index.ts:688-692`, flag +`HAS_ERROR`; polyfill `ERRORED`, `computed.ts:126-129`) and rethrow the same +object on each read until a dependency changes. Both record the outer +computed's dependency on the inner one before rethrowing: Preact calls +`addDependency` before `_refresh` (`index.ts:751-765`); the polyfill calls +`producerAccessed` before `throw node.error` (`computed.ts:48-59`). + +**What we do.** As the MobX report's finding 2 describes: nothing is cached on +a throw (`core.ts:189-195`) and the dependency on the inner getter is recorded +only after it returned (`core.ts:467-475`). + +**Difference in behaviour.** Script 04. `safe` catches the error of `strict`, +which throws until `ready` is set: + +```text +ours live after ready = true: safe fallback | runs {"strict":5,"safe":1,"outer":1} +Preact after ready = true: safe ready | runs {"strict":2,"safe":2,"outer":1} +polyfill after ready = true: safe ready | runs {"strict":2,"safe":2,"outer":1} +Preact strict, read again threw not ready | runs {"strict":1,...} | same error object: true +ours live strict, read again threw not ready | runs {"strict":2,...} | same error object: false +``` + +That agrees with MobX. What the signal libraries add is a counter-example to +caching blindly. Script 03 breaks a cycle with a write: `a = looped ? b : 0`, +`b = a + 1`: + +```text +ours live after looped = false: b returned 1 +Preact after looped = false: b threw Error: Cycle detected +Preact after another round trip: b threw Error: Cycle detected +polyfill after looped = false: b threw Error: Detected cycle in computations. +polyfill sources of b 0 +``` + +In both libraries the cycle error is thrown when `b` reads `a`, before `b` +has recorded `a` (Preact checks `RUNNING` at `index.ts:753`, before +`addDependency`; the polyfill throws inside `producerUpdateValueVersion`, +before `producerAccessed`). So `b` caches an error with no sources, and no +write can ever clear it. Our live layer recovers because it caches nothing. + +**Proposal: adopt MobX finding 2, with one rule from this case.** Record the +dependency on a getter in a `finally` (or before evaluating it), as both +libraries do, so the catching getter recovers. If errors are cached too, do +not cache one when the getter recorded no dependency, and record the +dependency on the getter that closes a cycle before throwing the cycle error. +On `spike-one`, which records the dependency in a `finally` but caches no +error, `safe` recovers (`ready | runs {"strict":6,"safe":2,"outer":1}`) and +`strict` re-runs more often while it throws (10 runs against 7 at the end of +script 04), since validation now refreshes it. Caching the error removes +those runs. + +**Kind.** Bug. + +**Cost.** As in the MobX report: `core.ts` and `snapshot.ts`, not breaking, +changes the pinned tests at `core.characterisation.getters.test.ts:1161` and +`:1270-1300`. Add a test for the broken cycle above, which today passes and +would fail under a naive error cache. + +### 5. Cycle detection: our live message is the best of the three; the snapshot layer has none + +**What they do.** Preact sets a `RUNNING` flag on a computed while it runs and +throws `Error('Cycle detected')` when it is read again (`index.ts:753-754`, +and for effects `:925-928`). The polyfill puts a `COMPUTING` sentinel in the +value slot and throws `Error('Detected cycle in computations.')` +(`computed.ts:111-115`). Neither names the computeds involved. + +**What we do.** `evaluateComputed` scans the tracker stack and throws an +error that names the path (`core.ts:171-184`): `circular computed getter +dependency: a → b → a`. The snapshot layer has no check +(`evaluateSnapshotGetter`, `snapshot.ts:121-162`). + +**Difference in behaviour.** Script 03: + +```text +ours live a <-> b threw Error: @codebelt/classy-store: circular computed getter dependency: a → b → a +ours snapshot a <-> b threw RangeError: Maximum call stack size exceeded. +Preact a <-> b threw Error: Cycle detected +polyfill a <-> b threw Error: Detected cycle in computations. +``` + +**Proposal: adopt for the snapshot layer.** Keep the live message. Give +`evaluateSnapshotGetter` the same check, with a module-level set of +`(target, key)` pairs being computed, so stage 1 finding 38 gives the same +error on both layers. The O(1) flag of the signal libraries is not worth +copying for the live layer: our scan is over the depth of nested getters, +which is small. + +**Kind.** Diagnostics. + +**Cost.** `snapshot.ts`, about ten lines. Not breaking. Changes the pinned +test for finding 38. Risk low. + +### 6. The snapshot layer loses nested memoization once, on a target's first getter + +**What they do.** Nothing comparable; this is a defect in our snapshot layer +that the 20-level chain in script 02 made visible. + +**What we do.** `evaluateSnapshotGetter` reads `memoMap` for the target before +running the getter (`snapshot.ts:132`). While the getter runs, nested getters +create the map for the same target and fill it. Afterwards, if `memoMap` was +undefined at the start, a fresh map replaces the one the nested getters filled +(`snapshot.ts:146-149`). + +**Difference in behaviour.** Script 02, a chain of 20 getters, each reading +the one below. Total body runs: + +```text +ours snapshot first snapshot read total 60 +ours snapshot after an unrelated write total 79 (19 levels re-ran) +ours snapshot after base 2 -> 3 total 99 +ours snapshot after another unrelated write total 99 (none re-ran) +``` + +So stage 1 finding 37 happens once per class instance, after its first +snapshot getter read, not on every snapshot. A one-line spike +(`spike-memo`, appendix) re-reads the map after the computation; the totals +become 60, 60, 80, 80, as Preact and the polyfill give for the live chain. + +**Proposal: adopt.** Re-read `crossSnapshotMemo.get(target)` after +`computeWithTracking` returns. + +**Kind.** Bug (performance only; results are correct). + +**Cost.** One line in `snapshot.ts`. Not breaking. Changes the pinned test for +finding 37. Risk low. + +### 7. A computed that writes + +**What they do.** Neither library forbids it in a computed. Preact runs it and +re-runs on every read when it writes what it reads; once an effect reads that +computed, the write inside the effect's batch trips the cycle guard +(`Cycle detected`, from `index.ts:463-464`). The polyfill lets a `Computed` +write (`consumerAllowSignalWrites = true`, `wrapper.ts:95`) but forbids reads +and writes inside a `Watcher` notification (`wrapper.ts:73`, +`graph.ts:214-221`). In production the read error has an empty message, +because the text is behind Angular's `ngDevMode` flag. + +**What we do.** On the live store the write goes through the `set` trap and +notifies; on a snapshot it is dropped (stage 1 finding 39). + +**Difference in behaviour.** Script 06: + +```text +ours live writes what it reads values [1,2,3] | runs 3 | n 3 | subscriber calls 3 +Preact writes what it reads values [1,2,3] | runs 3 | n 3 +Preact the same, read by an effect threw Error: Cycle detected +polyfill writes what it reads values [1,1,1] | runs 1 | n 1 +``` + +Our live behaviour matches Preact's. + +**Proposal: adapt, as a development warning only.** Neither library treats a +write in a computed as an error, so making it one would be stricter than the +field. A development-only `console.warn` from the `set` trap when +`trackerStack` is not empty, naming the getter, would catch the snapshot case, +where the write is lost in silence. Belongs with MobX finding 7 (a +development build). + +**Kind.** Diagnostics. + +**Cost.** `core.ts`, a few lines behind the development flag. Not breaking. + +### 8. Effects and subscribers: Preact confirms MobX's delivery model, and throws to the writer + +**What they do.** A Preact write starts a batch, marks targets, and runs +queued effects in `endBatch` when the outermost batch closes +(`index.ts:41-81`). Effects are queued, not called from the write, so a +re-entrant write is picked up by the running loop. `endBatch` skips a +disposed effect (`index.ts:62`) and an effect whose sources did not change. +A loop is bounded: after 100 iterations a write throws `Cycle detected` +(`index.ts:463-464`). An effect that throws does not stop the others; the +first error is rethrown to the writer once all have run (`index.ts:63-69`, +`:77-79`). The polyfill has no effect at all: a `Watcher`'s `notify` is +synchronous and may neither read nor write, and scheduling is left to the +user. + +**What we do.** `deliver` is called from inside the write (`core.ts:232`), +recursively on a re-entrant write, from a copy of the listener list +(`core.ts:318-327`), and logs a thrown error with `console.error`. + +**Difference in behaviour.** Script 07: + +```text +ours sync always writes no error at the write | calls 3017 | console.error: ["Maximum call stack size exceeded."] +Preact effect always writes, after a write threw Error: Cycle detected at the write | runs 102 | m 101 +ours sync second removed by first ["first","second"] +Preact second removed by first ["first"] +ours sync re-entrant write ["first:1","first:2","second:2","second:2"] +Preact re-entrant write ["first:1","second:2","first:2"] +ours sync first subscriber throws no error at the write | second called 1 | console.error: ["first subscriber failed"] +Preact first effect throws threw Error: first effect failed at the write | n 1 | second ran 1 +``` + +Preact gives the same results as MobX on loops, removal and re-entrancy, so +MobX finding 5 now has two libraries behind it. On errors the two differ: +MobX logs, Preact throws to the writer. + +**Proposal: adopt MobX finding 5; keep `console.error` for subscriber +errors.** Throwing from a write because a component's subscriber failed +would turn one broken view into a failed store method, and every adapter +subscribes synchronously. For the loop bound, Preact's 100 rounds is the same +number as MobX; the error should name the store, which neither library's +message does. + +**Kind.** Bug, diagnostics. + +**Cost.** As in the MobX report. + +### 9. Batching and glitch freedom match; one Preact refinement is not worth taking + +**What they do.** Preact's `batch` defers effects to the end of the outermost +batch, lets reads inside it see the new values, and still runs effects when +the callback throws (`index.ts:95-107`). Since 1.14 it also records each +signal's value at its first write in a batch and, if the value is back to it +at the end, fast-forwards the targets' versions so nothing re-runs +(`recordBatchSnapshot` and `reconcileBatchSnapshots`, `index.ts:163-206`). +Reads are pull-based, so a computed never sees half of a change; effects see +a consistent state at the end of a batch. + +**What we do.** `batch` and store methods share one transaction counter +(`core.ts:245-306`); versions bump on every write so reads inside are +current, and sync subscribers are told once when the outermost call returns +or throws. Getters are pull-based on both layers. + +**Difference in behaviour.** Scripts 02 and 08. No library showed a glitch: +in the diamond every `b/c` pair `d` saw was consistent (`2/2 4/6 12/22 22/42` +for us). Batching gives the same results: + +```text +ours sync batch(), total read inside saw [-14,28] +Preact batch(), total read inside saw [-14,28] +ours sync batch() that throws threw stop | price 7 | subscriber saw [7] +Preact batch() that throws threw stop | price 7 | effect saw [7] +ours sync set and set back in a batch subscriber calls 1 | same snapshot object: false | equal content: true +Preact set and set back in a batch effect runs after the first 0 | computed runs after the first 0 +``` + +**Proposal: keep `batch()` as it is; reject the set-and-set-back refinement.** +Preact can do it because a signal holds one value. We would need the value of +every written field at its first write in the batch, and the nodes' versions +would still have moved, so the snapshot would be rebuilt anyway. The case is +rare and the cost is one extra notification with equal content, which +selectors already absorb. + +**Kind.** API design. + +**Cost.** None. + +## Could our three kinds of dependency become one? + +Partly tested: the `spike-one` diff in the appendix does it, and ports 01 to +10 and the probe ran against it. The repository's test suites were not run +against it. + +**What it does.** A dependency is `{value, version}` keyed by property name on +the getter's own node, in first-read order. `value` is what the read gave: the +child's proxy for an object edge, the getter's result for a getter, the raw +value for a primitive, and a `MISSING` or `THREW` sentinel. `version` is the +version of the store node `value` is, or -1. Validation re-reads each property +through one function, `currentOf` (`childInternals` for an edge, the memoized +getter for an accessor, `Reflect.get` otherwise), with a frame on the tracker +stack that records nothing, and compares `Object.is(value)` and the version. +The `stamp` of finding 1 sits in front of it. This is the signal libraries' +one rule ("a source is unchanged when its version is the one I saw"), with a +store node's version standing in for a signal's. + +**What it gave.** All three kinds collapse into one entry type and one +validation loop; `recordComputedDep` goes, and the `parent`/`prop` check for a +replaced child falls out of comparing the proxy. Measured: + +- Script 01, ladder at depth 200: clean read 0.13, after an unrelated write + 70.53, after base changed 183.61 (Preact: 0.05, 11.58, 21.88). Linear, and + about six to eight times Preact. +- Script 09: 0.26 clean and 0.39 after an unrelated write, against 26.80 and + 25.96 on the base. +- Script 10, the everyday case: clean getter 48 ns against 61, but a write to + another field followed by the getter 300 ns against 206, because a miss on + the stamp now re-reads each dependency through a descriptor lookup instead + of comparing a stored version. +- Behaviour: the cutoff of finding 2, the probe of finding 2, the error + recovery of finding 4, and stage 1 finding 32 are fixed; nothing else in + ports 02 to 08 changed. + +**What it would take.** `core.ts` (`recordDep`, `areDepsValid`, +`evaluateComputed`, the `get` trap, the tracker frame) and `core.types.ts`, +about 150 lines of diff. Not breaking. Three things to settle first: + +1. The slower "write then read" path. Keeping a fast path for an edge (compare + the stored child version first, as the base does) should recover most of + it; not measured. +2. The snapshot layer keeps its own `{prop, value}` list, which is already + this model without versions (snapshot values are frozen, so value equality + is enough there). The two layers could then share the comparison rule but + not the code. +3. It does not widen what a getter can see. Reads on another node (MobX + finding 1) are still not recorded; a single kind makes it easier to add + "the version of a foreign node" as one more entry of the same shape. + +My recommendation, reasoning from these measurements: take findings 1, 3 and +the `finally` of finding 4 first, as small separate changes, and then decide +on the single kind with the benchmark in hand. Finding 2 needs either the +single kind or a version check bolted on to the `computed` kind; the single +kind is the cleaner of the two. + +## Stage 1 findings that have a counterpart + +| # | What the signal libraries do there | +| --- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 2 | No snapshots; no counterpart. | +| 3 | A 1,000-row sum recomputes in about 330 us in Preact and in our hoisted form; our loop form costs 1,200 us and 27 us per clean read because of duplicate dependencies (finding 3). | +| 13 | Not tested. A Preact computed depends on signals, not on an object that refers to itself. | +| 18 | Preact throws `Cycle detected` at the writer after 100 rounds; the polyfill forbids writes in a `Watcher` callback (finding 8). | +| 19 | Preact effects are synchronous; the same bound covers them. The polyfill leaves scheduling to the user, and its README's microtask effect does not re-run a computed that writes its source. | +| 20 | Preact skips a disposed effect at the call (finding 8). | +| 21 | A Preact effect created after a write runs once with the current value and never hears the earlier write (script 08: `late saw [7]`). | +| 22 | Queued: `["first:1","second:2","first:2"]` (finding 8). | +| 23 | No counterpart; an effect's return value is used only as a cleanup function. | +| 24 | No counterpart: no nested owners. | +| 32 | No counterpart: a missing signal cannot be read. The stamp of finding 1 removes it on our live store. | +| 36 | Both libraries recover the getter that catches another's error, and cache the thrown error (finding 4). Reads on another object: both track every signal read, like MobX. | +| 37 | No snapshot layer; on our side the cause is one line (finding 6). | +| 38 | Both throw a generic cycle error; we overflow the stack on snapshots (finding 5). | +| 39 | Both allow a write in a computed; Preact re-runs like our live layer (finding 7). | +| 40 | Neither freezes or copies a computed's result. Reasoning from reading. | +| 41 | No counterpart: a computed is a function, not a getter with `this`. | +| 42 | No counterpart. | +| 43 | No setters; `batch` is the counterpart, and it behaves like ours (finding 9). | +| 44 | No counterpart: a computed is an object, not a name. | +| 64 | `areDepsValid`'s `if (!cached) return false` becomes reachable with the `finally` of finding 4, as the MobX report noted; `spike-one` removes the whole branch. | + +## The eight API questions, from the signal libraries' point of view + +1. **Synchronous notification by default?** Preact: yes, effects run + synchronously when the outermost batch closes, which is our sync mode. + The polyfill: notification is synchronous but may do nothing except + schedule; running work is the caller's job, typically in a microtask. Both + point the same way as our adapters: synchronous delivery, grouped by a + transaction. +2. **Writes outside a method; `batch()`?** Preact allows writes anywhere, + warns about none, and exports `batch`, which is the only grouping it has. + That supports keeping `batch()` in the API. The polyfill has no batch: a + `Watcher` callback that schedules a microtask groups writes by + construction. +3. **Snapshot getters as enumerable own accessors?** No position. +4. **Arrow-function methods and `#private` fields?** No position. +5. **Native `Map` and `Set`?** No position. +6. **Opt-in or opt-out for nested class instances?** No position. +7. **Entry points and adapter names?** No position. +8. **Development diagnostics.** Both have weaker messages than ours for + cycles (finding 5). What they have that we lack: a bound on update loops + (finding 8), and the polyfill's ban on reads and writes during + notification. Its production build shows the cost of hiding messages + behind a development flag: the error is empty. If we add a development + build, keep the error text in production and drop only the extra checks. + +## What was verified by running code, and what was only read + +Verified by running, on Bun 1.4.4 with the published packages: + +- Every reproduction quoted above. Scripts 02 to 08 were re-run in this pass + and gave the same output as the first run, except the number of calls + before the stack overflowed in script 07 (3,017 against 3,025), which + depends on the stack. +- Scripts 01, 09 and 10 on the base were re-run; the figures quoted are from + the re-run. +- The spikes: `spike-stamp`, `spike-refresh` and `spike-one` against scripts + 01, 09, 10 and the probe (from the previous run of this task), and against + scripts 02 to 06 and 08 (this pass); `spike-memo` against script 02. + +Only read: + +- Every claim about the libraries' code paths, with the lines cited. +- That a stamp on our node version is safe for detached subtrees. A + suspended subtree's version is reconciled on resume (`ownership.ts`), which + `get` calls first (`core.ts:462`), so the stamp should see it; not tested. +- The repository's test suites were not run against any spike. +- Finding 40's line in the table. + +## Appendix: ported tests and their output + +All files are in +`/stage-2-signals/run/`. +`ours.ts` re-exports `batch`, `createClassyStore`, `snapshot` and `subscribe` +from the repository's `packages/classy-store/src/index.ts`; in each spike +folder it re-exports them from that folder's `src/index.ts`. +`polyfill-effect.ts` is the effect from the polyfill's README with a flush +counter added. + +### Helper: `ours.ts` + +```ts +// Our library, read from the repository's source. Nothing is installed there. +export { + batch, + createClassyStore, + snapshot, + subscribe, +} from '/packages/classy-store/src/index.ts'; +``` + +### Helper: `polyfill-effect.ts` + +```ts +// The proposal has no effect. This is the example from the polyfill's README +// (signal-polyfill 0.2.3, "Creating a simple effect"), with one addition: the +// number of flushes is counted so a test can stop a runaway loop. +import {Signal} from 'signal-polyfill'; + +export const flushes = {count: 0, limit: Number.POSITIVE_INFINITY}; +let needsEnqueue = true; + +const watcher = new Signal.subtle.Watcher(() => { + if (needsEnqueue) { + needsEnqueue = false; + queueMicrotask(processPending); + } +}); + +function processPending() { + needsEnqueue = true; + if (++flushes.count > flushes.limit) return; + for (const pending of watcher.getPending()) pending.get(); + watcher.watch(); +} + +export function effect(callback: () => void): () => void { + const computed = new Signal.Computed(() => { + callback(); + }); + watcher.watch(computed); + computed.get(); + return () => watcher.unwatch(computed); +} +``` + +### Script 01: `01-ladder.ts` + +```ts +// A ladder of computeds: two per level, each reading both of the level below. +// Same shape as script 07 of the MobX report, so the figures can be compared. +// "Clean read" is a read of the top when nothing changed: no body runs. +import {computed, effect, signal} from '@preact/signals-core'; +import {Signal} from 'signal-polyfill'; +import {createClassyStore} from './ours'; + +type Ladder = { + read: () => number; + setBase: (value: number) => void; + touchUnrelated: () => void; + runs: {count: number}; + observe?: () => () => void; +}; + +function oursLadder(depth: number): Ladder { + const runs = {count: 0}; + const target: Record = {base: 1, unrelated: 0}; + for (let level = 0; level < depth; level++) { + for (const side of ['l', 'r']) { + Object.defineProperty(target, `${side}${level}`, { + enumerable: true, + configurable: true, + get(this: Record) { + runs.count++; + return level === 0 + ? this.base + : this[`l${level - 1}`] + this[`r${level - 1}`]; + }, + }); + } + } + const store = createClassyStore(target) as Record; + const top = `l${depth - 1}`; + return { + read: () => store[top], + setBase: (value) => { + store.base = value; + }, + touchUnrelated: () => { + store.unrelated++; + }, + runs, + }; +} + +function preactLadder(depth: number): Ladder { + const runs = {count: 0}; + const base = signal(1); + const unrelated = signal(0); + let below = [base, base] as {value: number}[]; + for (let level = 0; level < depth; level++) { + const [l, r] = below; + const make = () => + computed(() => { + runs.count++; + return level === 0 ? base.value : l.value + r.value; + }); + below = [make(), make()]; + } + const top = below[0]; + return { + read: () => top.value, + setBase: (value) => { + base.value = value; + }, + touchUnrelated: () => { + unrelated.value++; + }, + runs, + observe: () => effect(() => void top.value), + }; +} + +function polyfillLadder(depth: number): Ladder { + const runs = {count: 0}; + const base = new Signal.State(1); + const unrelated = new Signal.State(0); + let below = [base, base] as {get(): number}[]; + for (let level = 0; level < depth; level++) { + const [l, r] = below; + const make = () => + new Signal.Computed(() => { + runs.count++; + return level === 0 ? base.get() : l.get() + r.get(); + }); + below = [make(), make()]; + } + const top = below[0] as Signal.Computed; + return { + read: () => top.get(), + setBase: (value) => base.set(value), + touchUnrelated: () => unrelated.set(unrelated.get() + 1), + runs, + observe: () => { + const watcher = new Signal.subtle.Watcher(() => {}); + watcher.watch(top); + return () => watcher.unwatch(top); + }, + }; +} + +/** Microseconds per call, averaged over `times` calls. */ +function micros(times: number, run: () => void, before?: () => void): string { + let total = 0; + for (let i = 0; i < times; i++) { + before?.(); + const start = performance.now(); + run(); + total += performance.now() - start; + } + return ((total / times) * 1000).toFixed(2).padStart(10); +} + +function measure( + name: string, + make: (depth: number) => Ladder, + depths: number[], + observed: boolean, +) { + console.log(`\n${name}${observed ? ', observed' : ''}`); + console.log( + 'depth | first read | clean read | read after an unrelated write | read after base changed | bodies run: first, clean, unrelated, base (times in microseconds)', + ); + for (const depth of depths) { + const ladder = make(depth); + const stop = observed ? ladder.observe?.() : undefined; + const times = + depth >= 16 && name === 'ours, live' && !process.env.SPIKE ? 3 : 200; + const first = observed ? ' -' : micros(1, ladder.read); + const firstRuns = ladder.runs.count; + const clean = micros(times, ladder.read); + const cleanRuns = ladder.runs.count - firstRuns; + const unrelated = micros(times, ladder.read, ladder.touchUnrelated); + const unrelatedRuns = ladder.runs.count - firstRuns - cleanRuns; + let next = 1; + const before = ladder.runs.count; + const dirty = micros(times, ladder.read, () => ladder.setBase(++next)); + const dirtyRuns = (ladder.runs.count - before) / times; + stop?.(); + console.log( + String(depth).padStart(5), + '|', + first, + '|', + clean, + '|', + unrelated.padStart(29), + '|', + dirty.padStart(23), + '|', + `${firstRuns}, ${cleanRuns}, ${unrelatedRuns}, ${dirtyRuns} per read`, + ); + } +} + +const spike = process.env.SPIKE === '1'; +measure( + 'ours, live', + oursLadder, + spike ? [4, 8, 12, 16, 18, 20, 200] : [4, 8, 12, 16, 18, 20], + false, +); +if (spike) process.exit(0); +measure('Preact Signals', preactLadder, [4, 8, 12, 16, 18, 20, 200], false); +measure('Preact Signals', preactLadder, [4, 8, 12, 16, 18, 20, 200], true); +measure('signal-polyfill', polyfillLadder, [4, 8, 12, 16, 18, 20, 200], false); +measure('signal-polyfill', polyfillLadder, [4, 8, 12, 16, 18, 20, 200], true); +``` + +Output on the base, this pass: + +```text + +ours, live +depth | first read | clean read | read after an unrelated write | read after base changed | bodies run: first, clean, unrelated, base (times in microseconds) + 4 | 220.33 | 3.27 | 1.60 | 4.57 | 7, 0, 0, 7 per read + 8 | 59.04 | 10.28 | 7.27 | 12.21 | 15, 0, 0, 15 per read + 12 | 379.96 | 79.32 | 65.94 | 105.05 | 23, 0, 0, 23 per read + 16 | 2258.54 | 1540.32 | 1111.15 | 1658.15 | 31, 0, 0, 31 per read + 18 | 7086.46 | 4707.40 | 4136.67 | 6480.60 | 35, 0, 0, 35 per read + 20 | 16926.46 | 16548.01 | 16424.39 | 25660.64 | 39, 0, 0, 39 per read + +Preact Signals +depth | first read | clean read | read after an unrelated write | read after base changed | bodies run: first, clean, unrelated, base (times in microseconds) + 4 | 143.25 | 0.43 | 0.94 | 1.97 | 7, 0, 0, 7 per read + 8 | 16.75 | 0.07 | 0.42 | 1.38 | 15, 0, 0, 15 per read + 12 | 7.25 | 0.04 | 0.60 | 1.69 | 23, 0, 0, 23 per read + 16 | 3.04 | 0.04 | 0.68 | 2.13 | 31, 0, 0, 31 per read + 18 | 4.37 | 0.04 | 0.61 | 2.09 | 35, 0, 0, 35 per read + 20 | 2.79 | 0.04 | 0.68 | 2.23 | 39, 0, 0, 39 per read + 200 | 156.54 | 0.05 | 11.58 | 21.88 | 399, 0, 0, 399 per read + +Preact Signals, observed +depth | first read | clean read | read after an unrelated write | read after base changed | bodies run: first, clean, unrelated, base (times in microseconds) + 4 | - | 0.03 | 0.04 | 0.04 | 7, 0, 0, 7 per read + 8 | - | 0.04 | 0.04 | 0.04 | 15, 0, 0, 15 per read + 12 | - | 0.04 | 0.04 | 0.04 | 23, 0, 0, 23 per read + 16 | - | 0.05 | 0.04 | 0.04 | 31, 0, 0, 31 per read + 18 | - | 0.04 | 0.04 | 0.04 | 35, 0, 0, 35 per read + 20 | - | 0.05 | 0.05 | 0.05 | 39, 0, 0, 39 per read + 200 | - | 0.04 | 0.04 | 0.04 | 399, 0, 0, 399 per read + +signal-polyfill +depth | first read | clean read | read after an unrelated write | read after base changed | bodies run: first, clean, unrelated, base (times in microseconds) + 4 | 184.75 | 0.59 | 1.25 | 2.75 | 7, 0, 0, 7 per read + 8 | 49.62 | 0.08 | 0.70 | 1.78 | 15, 0, 0, 15 per read + 12 | 28.29 | 0.05 | 0.83 | 1.95 | 23, 0, 0, 23 per read + 16 | 18.79 | 0.06 | 1.11 | 4.76 | 31, 0, 0, 31 per read + 18 | 32.17 | 0.05 | 1.05 | 2.94 | 35, 0, 0, 35 per read + 20 | 32.00 | 0.04 | 0.92 | 3.99 | 39, 0, 0, 39 per read + 200 | 170.88 | 0.05 | 9.55 | 35.67 | 399, 0, 0, 399 per read + +signal-polyfill, observed +depth | first read | clean read | read after an unrelated write | read after base changed | bodies run: first, clean, unrelated, base (times in microseconds) + 4 | - | 0.84 | 1.30 | 2.75 | 0, 7, 0, 7 per read + 8 | - | 0.28 | 1.12 | 2.60 | 0, 15, 0, 15 per read + 12 | - | 0.25 | 0.93 | 3.19 | 0, 23, 0, 23 per read + 16 | - | 0.15 | 1.17 | 4.06 | 0, 31, 0, 31 per read + 18 | - | 0.16 | 1.33 | 4.55 | 0, 35, 0, 35 per read + 20 | - | 0.18 | 1.53 | 5.31 | 0, 39, 0, 39 per read + 200 | - | 0.70 | 15.55 | 35.93 | 0, 399, 0, 399 per read +``` + +### Script 02: `02-diamond.ts` + +```ts +// A diamond (b and c over a, d over both), an equal-value cutoff, and a chain +// twenty levels deep. Ported from "nested getters, three levels deep" in +// core.characterisation.getters.test.ts (:81 live, :201 snapshots), widened. +import { + batch as preactBatch, + computed, + effect, + signal, +} from '@preact/signals-core'; +import {Signal} from 'signal-polyfill'; +import {batch, createClassyStore, snapshot, subscribe} from './ours'; +import {effect as polyfillEffect} from './polyfill-effect'; + +const tick = () => new Promise((resolve) => setTimeout(resolve, 0)); + +// ── ours ── +{ + const runs = {b: 0, c: 0, d: 0, parity: 0, label: 0}; + const pairs: string[] = []; + class Diamond { + a = 1; + get b() { + runs.b++; + return this.a + 1; + } + get c() { + runs.c++; + return this.a * 2; + } + get d() { + runs.d++; + pairs.push(`${this.b}/${this.c}`); + return this.b + this.c; + } + get parity() { + runs.parity++; + return this.a % 2; + } + get label() { + runs.label++; + return this.parity ? 'odd' : 'even'; + } + setTwice() { + this.a = 10; + this.a = 11; + } + } + const store = createClassyStore(new Diamond()); + const seen: number[] = []; + subscribe(store, () => seen.push(store.d), {sync: true}); + store.d; + store.label; + console.log('ours live first read ', JSON.stringify(runs)); + store.a = 3; + store.label; + console.log( + 'ours live a 1 -> 3, d and label ', + JSON.stringify(runs), + '| subscriber saw d =', + seen, + ); + store.setTwice(); + batch(() => { + store.a = 20; + store.a = 21; + }); + console.log( + 'ours live a method and a batch() ', + JSON.stringify(runs), + '| subscriber saw d =', + seen, + ); + console.log('ours live b/c pairs seen by d ', pairs.join(' ')); + + const snapRuns = {...runs}; + const before = snapshot(store); + before.d; + before.label; + store.a = 23; + const after = snapshot(store); + after.d; + after.label; + console.log( + 'ours snapshot a 21 -> 23, d and label ', + JSON.stringify( + Object.fromEntries( + Object.entries(runs).map(([key, value]) => [ + key, + value - snapRuns[key as keyof typeof runs], + ]), + ), + ), + '(runs since the line above, two snapshots)', + ); +} + +// ── Preact Signals ── +{ + const runs = {b: 0, c: 0, d: 0, parity: 0, label: 0}; + const pairs: string[] = []; + const a = signal(1); + const b = computed(() => (runs.b++, a.value + 1)); + const c = computed(() => (runs.c++, a.value * 2)); + const d = computed(() => { + runs.d++; + pairs.push(`${b.value}/${c.value}`); + return b.value + c.value; + }); + const parity = computed(() => (runs.parity++, a.value % 2)); + const label = computed(() => (runs.label++, parity.value ? 'odd' : 'even')); + const seen: number[] = []; + d.value; + label.value; + console.log('Preact first read ', JSON.stringify(runs)); + a.value = 3; + d.value; + label.value; + console.log('Preact a 1 -> 3, unobserved ', JSON.stringify(runs)); + const stop = effect(() => void seen.push(d.value)); + const stopLabel = effect(() => void label.value); + a.value = 5; + console.log( + 'Preact a 3 -> 5, in effects ', + JSON.stringify(runs), + '| effect saw d =', + seen, + ); + preactBatch(() => { + a.value = 20; + a.value = 21; + }); + console.log( + 'Preact a batch() ', + JSON.stringify(runs), + '| effect saw d =', + seen, + ); + console.log('Preact b/c pairs seen by d ', pairs.join(' ')); + stop(); + stopLabel(); +} + +// ── signal-polyfill ── +{ + const runs = {b: 0, c: 0, d: 0, parity: 0, label: 0}; + const pairs: string[] = []; + const a = new Signal.State(1); + const b = new Signal.Computed(() => (runs.b++, a.get() + 1)); + const c = new Signal.Computed(() => (runs.c++, a.get() * 2)); + const d = new Signal.Computed(() => { + runs.d++; + pairs.push(`${b.get()}/${c.get()}`); + return b.get() + c.get(); + }); + const parity = new Signal.Computed(() => (runs.parity++, a.get() % 2)); + const label = new Signal.Computed( + () => (runs.label++, parity.get() ? 'odd' : 'even'), + ); + d.get(); + label.get(); + console.log('polyfill first read ', JSON.stringify(runs)); + a.set(3); + d.get(); + label.get(); + console.log('polyfill a 1 -> 3, unwatched ', JSON.stringify(runs)); + const seen: number[] = []; + const stop = polyfillEffect(() => void seen.push(d.get())); + const stopLabel = polyfillEffect(() => void label.get()); + a.set(5); + a.set(7); + await tick(); + console.log( + 'polyfill a 3 -> 5 -> 7, README effect', + JSON.stringify(runs), + '| effect saw d =', + seen, + ); + console.log('polyfill b/c pairs seen by d ', pairs.join(' ')); + stop(); + stopLabel(); +} + +// ── a chain twenty levels deep: how often does each level run? ── +{ + const depth = 20; + const count = (list: number[]) => + `min ${Math.min(...list)}, max ${Math.max(...list)}, total ${list.reduce((sum, n) => sum + n, 0)}`; + + const oursRuns = new Array(depth).fill(0); + const target: Record = {base: 1, other: 0}; + for (let level = 0; level < depth; level++) { + Object.defineProperty(target, `g${level}`, { + enumerable: true, + configurable: true, + get(this: Record) { + oursRuns[level]++; + return level === 0 ? this.base : this[`g${level - 1}`] + 1; + }, + }); + } + const store = createClassyStore(target) as Record; + const report = (name: string, runsList: number[], value: number) => + console.log( + name.padEnd(46), + `top = ${value} | per level: ${count(runsList)}`, + ); + report('ours live chain of 20, first read', oursRuns, store.g19); + report('ours live read again', oursRuns, store.g19); + store.other = 1; + report('ours live after an unrelated write', oursRuns, store.g19); + store.base = 2; + report('ours live after base 1 -> 2', oursRuns, store.g19); + report('ours snapshot first snapshot read', oursRuns, snapshot(store).g19); + store.other = 2; + report( + 'ours snapshot after an unrelated write', + oursRuns, + snapshot(store).g19, + ); + store.base = 3; + report('ours snapshot after base 2 -> 3', oursRuns, snapshot(store).g19); + store.other = 3; + report( + 'ours snapshot after another unrelated write', + oursRuns, + snapshot(store).g19, + ); + + const preactRuns = new Array(depth).fill(0); + const base = signal(1); + const other = signal(0); + let previous: {value: number} = base; + for (let level = 0; level < depth; level++) { + const below = previous; + previous = computed( + () => (preactRuns[level]++, level === 0 ? base.value : below.value + 1), + ); + } + const top = previous; + report('Preact chain of 20, first read', preactRuns, top.value); + report('Preact read again', preactRuns, top.value); + other.value = 1; + report('Preact after an unrelated write', preactRuns, top.value); + base.value = 2; + report('Preact after base 1 -> 2', preactRuns, top.value); + + const polyRuns = new Array(depth).fill(0); + const pBase = new Signal.State(1); + const pOther = new Signal.State(0); + let pPrevious: {get(): number} = pBase; + for (let level = 0; level < depth; level++) { + const below = pPrevious; + pPrevious = new Signal.Computed( + () => (polyRuns[level]++, level === 0 ? pBase.get() : below.get() + 1), + ); + } + const pTop = pPrevious; + report('polyfill chain of 20, first read', polyRuns, pTop.get()); + report('polyfill read again', polyRuns, pTop.get()); + pOther.set(1); + report('polyfill after an unrelated write', polyRuns, pTop.get()); + pBase.set(2); + report('polyfill after base 1 -> 2', polyRuns, pTop.get()); +} +``` + +Output on the base, this pass: + +```text +ours live first read {"b":1,"c":1,"d":1,"parity":1,"label":1} +ours live a 1 -> 3, d and label {"b":2,"c":2,"d":2,"parity":2,"label":2} | subscriber saw d = [ + 10 +] +ours live a method and a batch() {"b":4,"c":4,"d":4,"parity":2,"label":2} | subscriber saw d = [ + 10, 34, 64 +] +ours live b/c pairs seen by d 2/2 4/6 12/22 22/42 +ours snapshot a 21 -> 23, d and label {"b":3,"c":3,"d":3,"parity":2,"label":1} (runs since the line above, two snapshots) +Preact first read {"b":1,"c":1,"d":1,"parity":1,"label":1} +Preact a 1 -> 3, unobserved {"b":2,"c":2,"d":2,"parity":2,"label":1} +Preact a 3 -> 5, in effects {"b":3,"c":3,"d":3,"parity":3,"label":1} | effect saw d = [ + 10, 16 +] +Preact a batch() {"b":4,"c":4,"d":4,"parity":4,"label":1} | effect saw d = [ + 10, 16, 64 +] +Preact b/c pairs seen by d 2/2 4/6 6/10 22/42 +polyfill first read {"b":1,"c":1,"d":1,"parity":1,"label":1} +polyfill a 1 -> 3, unwatched {"b":2,"c":2,"d":2,"parity":2,"label":1} +polyfill a 3 -> 5 -> 7, README effect {"b":3,"c":3,"d":3,"parity":3,"label":1} | effect saw d = [ + 10, 22 +] +polyfill b/c pairs seen by d 2/2 4/6 8/14 +ours live chain of 20, first read top = 20 | per level: min 1, max 1, total 20 +ours live read again top = 20 | per level: min 1, max 1, total 20 +ours live after an unrelated write top = 20 | per level: min 1, max 1, total 20 +ours live after base 1 -> 2 top = 21 | per level: min 2, max 2, total 40 +ours snapshot first snapshot read top = 21 | per level: min 3, max 3, total 60 +ours snapshot after an unrelated write top = 21 | per level: min 3, max 4, total 79 +ours snapshot after base 2 -> 3 top = 22 | per level: min 4, max 5, total 99 +ours snapshot after another unrelated write top = 22 | per level: min 4, max 5, total 99 +Preact chain of 20, first read top = 20 | per level: min 1, max 1, total 20 +Preact read again top = 20 | per level: min 1, max 1, total 20 +Preact after an unrelated write top = 20 | per level: min 1, max 1, total 20 +Preact after base 1 -> 2 top = 21 | per level: min 2, max 2, total 40 +polyfill chain of 20, first read top = 20 | per level: min 1, max 1, total 20 +polyfill read again top = 20 | per level: min 1, max 1, total 20 +polyfill after an unrelated write top = 20 | per level: min 1, max 1, total 20 +polyfill after base 1 -> 2 top = 21 | per level: min 2, max 2, total 40 +``` + +### Script 03: `03-cycles.ts` + +```ts +// Cycles between computeds. Ported from "getters that read each other in a +// cycle" in core.characterisation.getters.test.ts (:1049), plus a cycle that +// a later write breaks, to see whether the error outlives the cycle. +import {computed, signal} from '@preact/signals-core'; +import {Signal} from 'signal-polyfill'; +import {createClassyStore, snapshot} from './ours'; + +const attempt = (run: () => unknown): string => { + try { + return `returned ${JSON.stringify(run())}`; + } catch (error) { + const e = error as Error; + return `threw ${e.constructor.name}: ${e.message.slice(0, 90)}`; + } +}; +const line = (name: string, text: string) => console.log(name.padEnd(44), text); + +// ── a plain cycle: a reads b, b reads a ── +{ + class Loop { + get a(): number { + return this.b + 1; + } + get b(): number { + return this.a + 1; + } + get self(): number { + return this.self + 1; + } + } + const store = createClassyStore(new Loop()); + line( + 'ours live a <-> b', + attempt(() => store.a), + ); + line( + 'ours live a <-> b, read again', + attempt(() => store.a), + ); + line( + 'ours live self', + attempt(() => store.self), + ); + line( + 'ours snapshot a <-> b', + attempt(() => snapshot(store).a), + ); + + const a: {value: number} = computed(() => b.value + 1); + const b: {value: number} = computed(() => a.value + 1); + const self: {value: number} = computed(() => self.value + 1); + line( + 'Preact a <-> b', + attempt(() => a.value), + ); + line( + 'Preact a <-> b, read again', + attempt(() => a.value), + ); + line( + 'Preact self', + attempt(() => self.value), + ); + + const pa: Signal.Computed = new Signal.Computed(() => pb.get() + 1); + const pb: Signal.Computed = new Signal.Computed(() => pa.get() + 1); + const pself: Signal.Computed = new Signal.Computed( + () => pself.get() + 1, + ); + line( + 'polyfill a <-> b', + attempt(() => pa.get()), + ); + line( + 'polyfill a <-> b, read again', + attempt(() => pa.get()), + ); + line( + 'polyfill self', + attempt(() => pself.get()), + ); +} + +// ── a cycle that a write breaks: a = looped ? b : 0, b = a + 1 ── +console.log(); +{ + class Breakable { + looped = true; + get a(): number { + return this.looped ? this.b : 0; + } + get b(): number { + return this.a + 1; + } + } + const store = createClassyStore(new Breakable()); + line( + 'ours live while looped: a', + attempt(() => store.a), + ); + store.looped = false; + line( + 'ours live after looped = false: a', + attempt(() => store.a), + ); + line( + 'ours live after looped = false: b', + attempt(() => store.b), + ); + store.looped = true; + line( + 'ours snapshot while looped: a', + attempt(() => snapshot(store).a), + ); + store.looped = false; + line( + 'ours snapshot after looped = false: b', + attempt(() => snapshot(store).b), + ); + + const looped = signal(true); + const a: {value: number} = computed(() => (looped.value ? b.value : 0)); + const b: {value: number} = computed(() => a.value + 1); + line( + 'Preact while looped: a', + attempt(() => a.value), + ); + looped.value = false; + line( + 'Preact after looped = false: a', + attempt(() => a.value), + ); + line( + 'Preact after looped = false: b', + attempt(() => b.value), + ); + looped.value = true; + looped.value = false; + line( + 'Preact after another round trip: b', + attempt(() => b.value), + ); + + const pLooped = new Signal.State(true); + const pa: Signal.Computed = new Signal.Computed(() => + pLooped.get() ? pb.get() : 0, + ); + const pb: Signal.Computed = new Signal.Computed(() => pa.get() + 1); + line( + 'polyfill while looped: a', + attempt(() => pa.get()), + ); + pLooped.set(false); + line( + 'polyfill after looped = false: a', + attempt(() => pa.get()), + ); + line( + 'polyfill after looped = false: b', + attempt(() => pb.get()), + ); + line( + 'polyfill sources of b', + JSON.stringify(Signal.subtle.introspectSources(pb).length), + ); +} +``` + +Output on the base, this pass: + +```text +ours live a <-> b threw Error: @codebelt/classy-store: circular computed getter dependency: a → b → a +ours live a <-> b, read again threw Error: @codebelt/classy-store: circular computed getter dependency: a → b → a +ours live self threw Error: @codebelt/classy-store: circular computed getter dependency: self → self +ours snapshot a <-> b threw RangeError: Maximum call stack size exceeded. +Preact a <-> b threw Error: Cycle detected +Preact a <-> b, read again threw Error: Cycle detected +Preact self threw Error: Cycle detected +polyfill a <-> b threw Error: Detected cycle in computations. +polyfill a <-> b, read again threw Error: Detected cycle in computations. +polyfill self threw Error: Detected cycle in computations. + +ours live while looped: a threw Error: @codebelt/classy-store: circular computed getter dependency: a → b → a +ours live after looped = false: a returned 0 +ours live after looped = false: b returned 1 +ours snapshot while looped: a threw RangeError: Maximum call stack size exceeded. +ours snapshot after looped = false: b returned 1 +Preact while looped: a threw Error: Cycle detected +Preact after looped = false: a returned 0 +Preact after looped = false: b threw Error: Cycle detected +Preact after another round trip: b threw Error: Cycle detected +polyfill while looped: a threw Error: Detected cycle in computations. +polyfill after looped = false: a returned 0 +polyfill after looped = false: b threw Error: Detected cycle in computations. +polyfill sources of b 0 +``` + +### Script 04: `04-errors.ts` + +```ts +// A computed that throws and then recovers, and one that catches another's +// error. Ported from "a getter that throws" (:1160) and "a getter that catches +// the error of another getter" (:1270) in core.characterisation.getters.test.ts. +import {computed, signal} from '@preact/signals-core'; +import {Signal} from 'signal-polyfill'; +import {createClassyStore, snapshot} from './ours'; + +const line = (name: string, text: string) => console.log(name.padEnd(40), text); + +type Subject = { + name: string; + strict: () => string; + safe: () => string; + outer: () => string; + setReady: (value: boolean) => void; + touchOther: () => void; + runs: {strict: number; safe: number; outer: number}; +}; + +function exercise({ + name, + strict, + safe, + outer, + setReady, + touchOther, + runs, +}: Subject) { + const errors: unknown[] = []; + const read = (run: () => string) => { + try { + return run(); + } catch (error) { + errors.push(error); + return `threw ${(error as Error).message}`; + } + }; + line( + `${name} strict, first read`, + `${read(strict)} | runs ${JSON.stringify(runs)}`, + ); + line( + `${name} strict, read again`, + `${read(strict)} | runs ${JSON.stringify(runs)} | same error object: ${errors[0] === errors[1]}`, + ); + line( + `${name} outer (reads strict)`, + `${read(outer)} | runs ${JSON.stringify(runs)} | same error object: ${errors[0] === errors[2]}`, + ); + line( + `${name} safe (catches strict)`, + `${read(safe)} | runs ${JSON.stringify(runs)}`, + ); + touchOther(); + line( + `${name} after an unrelated write`, + `${read(strict)} | runs ${JSON.stringify(runs)} | same error object: ${errors[0] === errors[3]}`, + ); + setReady(true); + line( + `${name} after ready = true: safe`, + `${read(safe)} | runs ${JSON.stringify(runs)}`, + ); + line( + `${name} after ready = true: outer`, + `${read(outer)} | strict: ${read(strict)} | runs ${JSON.stringify(runs)}`, + ); + setReady(false); + line( + `${name} after ready = false: safe`, + `${read(safe)} | outer: ${read(outer)} | runs ${JSON.stringify(runs)}`, + ); + console.log(); +} + +// ── ours, live and snapshot ── +function ours(viaSnapshot: boolean) { + const runs = {strict: 0, safe: 0, outer: 0}; + class Loader { + ready = false; + other = 0; + get strict(): string { + runs.strict++; + if (!this.ready) throw new RangeError('not ready'); + return 'ready'; + } + get outer(): string { + runs.outer++; + return `outer:${this.strict}`; + } + get safe(): string { + runs.safe++; + try { + return this.strict; + } catch { + return 'fallback'; + } + } + } + const store = createClassyStore(new Loader()); + const view = () => (viaSnapshot ? snapshot(store) : store); + exercise({ + name: viaSnapshot ? 'ours snapshot ' : 'ours live ', + strict: () => view().strict, + safe: () => view().safe, + outer: () => view().outer, + setReady: (value) => { + store.ready = value; + }, + touchOther: () => { + store.other++; + }, + runs, + }); +} +ours(false); +ours(true); + +// ── Preact Signals ── +{ + const runs = {strict: 0, safe: 0, outer: 0}; + const ready = signal(false); + const other = signal(0); + const strict = computed(() => { + runs.strict++; + if (!ready.value) throw new RangeError('not ready'); + return 'ready'; + }); + const outer = computed(() => (runs.outer++, `outer:${strict.value}`)); + const safe = computed(() => { + runs.safe++; + try { + return strict.value; + } catch { + return 'fallback'; + } + }); + exercise({ + name: 'Preact ', + strict: () => strict.value, + safe: () => safe.value, + outer: () => outer.value, + setReady: (value) => { + ready.value = value; + }, + touchOther: () => { + other.value++; + }, + runs, + }); +} + +// ── signal-polyfill ── +{ + const runs = {strict: 0, safe: 0, outer: 0}; + const ready = new Signal.State(false); + const other = new Signal.State(0); + const strict = new Signal.Computed(() => { + runs.strict++; + if (!ready.get()) throw new RangeError('not ready'); + return 'ready'; + }); + const outer = new Signal.Computed( + () => (runs.outer++, `outer:${strict.get()}`), + ); + const safe = new Signal.Computed(() => { + runs.safe++; + try { + return strict.get(); + } catch { + return 'fallback'; + } + }); + exercise({ + name: 'polyfill ', + strict: () => strict.get(), + safe: () => safe.get(), + outer: () => outer.get(), + setReady: (value) => ready.set(value), + touchOther: () => other.set(other.get() + 1), + runs, + }); +} +``` + +Output on the base, this pass: + +```text +ours live strict, first read threw not ready | runs {"strict":1,"safe":0,"outer":0} +ours live strict, read again threw not ready | runs {"strict":2,"safe":0,"outer":0} | same error object: false +ours live outer (reads strict) threw not ready | runs {"strict":3,"safe":0,"outer":1} | same error object: false +ours live safe (catches strict) fallback | runs {"strict":4,"safe":1,"outer":1} +ours live after an unrelated write threw not ready | runs {"strict":5,"safe":1,"outer":1} | same error object: false +ours live after ready = true: safe fallback | runs {"strict":5,"safe":1,"outer":1} +ours live after ready = true: outer outer:ready | strict: ready | runs {"strict":6,"safe":1,"outer":2} +ours live after ready = false: safe fallback | outer: threw not ready | runs {"strict":7,"safe":1,"outer":3} + +ours snapshot strict, first read threw not ready | runs {"strict":1,"safe":0,"outer":0} +ours snapshot strict, read again threw not ready | runs {"strict":2,"safe":0,"outer":0} | same error object: false +ours snapshot outer (reads strict) threw not ready | runs {"strict":3,"safe":0,"outer":1} | same error object: false +ours snapshot safe (catches strict) fallback | runs {"strict":4,"safe":1,"outer":1} +ours snapshot after an unrelated write threw not ready | runs {"strict":5,"safe":1,"outer":1} | same error object: false +ours snapshot after ready = true: safe fallback | runs {"strict":5,"safe":1,"outer":1} +ours snapshot after ready = true: outer outer:ready | strict: ready | runs {"strict":6,"safe":1,"outer":2} +ours snapshot after ready = false: safe fallback | outer: threw not ready | runs {"strict":7,"safe":1,"outer":2} + +Preact strict, first read threw not ready | runs {"strict":1,"safe":0,"outer":0} +Preact strict, read again threw not ready | runs {"strict":1,"safe":0,"outer":0} | same error object: true +Preact outer (reads strict) threw not ready | runs {"strict":1,"safe":0,"outer":1} | same error object: true +Preact safe (catches strict) fallback | runs {"strict":1,"safe":1,"outer":1} +Preact after an unrelated write threw not ready | runs {"strict":1,"safe":1,"outer":1} | same error object: true +Preact after ready = true: safe ready | runs {"strict":2,"safe":2,"outer":1} +Preact after ready = true: outer outer:ready | strict: ready | runs {"strict":2,"safe":2,"outer":2} +Preact after ready = false: safe fallback | outer: threw not ready | runs {"strict":3,"safe":3,"outer":3} + +polyfill strict, first read threw not ready | runs {"strict":1,"safe":0,"outer":0} +polyfill strict, read again threw not ready | runs {"strict":1,"safe":0,"outer":0} | same error object: true +polyfill outer (reads strict) threw not ready | runs {"strict":1,"safe":0,"outer":1} | same error object: true +polyfill safe (catches strict) fallback | runs {"strict":1,"safe":1,"outer":1} +polyfill after an unrelated write threw not ready | runs {"strict":1,"safe":1,"outer":1} | same error object: true +polyfill after ready = true: safe ready | runs {"strict":2,"safe":2,"outer":1} +polyfill after ready = true: outer outer:ready | strict: ready | runs {"strict":2,"safe":2,"outer":2} +polyfill after ready = false: safe fallback | outer: threw not ready | runs {"strict":3,"safe":3,"outer":3} + +``` + +### Script 05: `05-dynamic-deps.ts` + +```ts +// A dependency that is read on one run and not on the next. Written for this +// comparison: I found no test of ours for this case by name. +import {computed, effect, signal} from '@preact/signals-core'; +import {Signal} from 'signal-polyfill'; +import {createClassyStore, snapshot, subscribe} from './ours'; + +const line = (name: string, text: string) => console.log(name.padEnd(34), text); + +type Subject = { + name: string; + pick: () => string; + set: (key: 'useA' | 'a' | 'b', value: boolean | string) => void; + runs: {pick: number}; +}; + +function exercise({name, pick, set, runs}: Subject) { + const steps: string[] = []; + const step = (label: string) => + steps.push(`${label}: ${pick()} (${runs.pick})`); + step('start'); + set('b', 'B2'); + step('b changed, not read'); + set('useA', false); + step('switched to b'); + set('a', 'A2'); + step('a changed, no longer read'); + set('b', 'B3'); + step('b changed, read'); + set('useA', true); + step('switched back'); + line(name, steps.join(' | ')); +} + +function ours(viaSnapshot: boolean) { + const runs = {pick: 0}; + class Picker { + useA = true; + a = 'A1'; + b = 'B1'; + get pick() { + runs.pick++; + return this.useA ? this.a : this.b; + } + } + const store = createClassyStore(new Picker()); + exercise({ + name: viaSnapshot ? 'ours snapshot' : 'ours live', + pick: () => (viaSnapshot ? snapshot(store) : store).pick, + set: (key, value) => { + (store as Record)[key] = value; + }, + runs, + }); +} +ours(false); +ours(true); + +{ + const runs = {pick: 0}; + const state = {useA: signal(true), a: signal('A1'), b: signal('B1')}; + const pick = computed( + () => (runs.pick++, state.useA.value ? state.a.value : state.b.value), + ); + exercise({ + name: 'Preact, unobserved', + pick: () => pick.value, + set: (key, value) => { + (state[key] as {value: unknown}).value = value; + }, + runs, + }); +} +{ + const runs = {pick: 0}; + const state = {useA: signal(true), a: signal('A1'), b: signal('B1')}; + const pick = computed( + () => (runs.pick++, state.useA.value ? state.a.value : state.b.value), + ); + let effectRuns = 0; + const stop = effect(() => { + effectRuns++; + pick.value; + }); + exercise({ + name: 'Preact, in an effect', + pick: () => pick.value, + set: (key, value) => { + (state[key] as {value: unknown}).value = value; + }, + runs, + }); + line( + 'Preact, in an effect', + `effect ran ${effectRuns} times for 5 writes, 2 of them to a field pick did not read at the time`, + ); + stop(); +} +{ + const runs = {pick: 0}; + const state = { + useA: new Signal.State(true), + a: new Signal.State('A1'), + b: new Signal.State('B1'), + }; + const pick = new Signal.Computed( + () => (runs.pick++, state.useA.get() ? state.a.get() : state.b.get()), + ); + exercise({ + name: 'polyfill, unwatched', + pick: () => pick.get(), + set: (key, value) => (state[key] as Signal.State).set(value), + runs, + }); + line( + 'polyfill, unwatched', + `sources after the last run: ${Signal.subtle.introspectSources(pick).length}`, + ); +} + +// What a subscriber hears: ours is told about every write to the store, +// whether or not anything it reads depends on the field. +{ + class Picker { + useA = true; + a = 'A1'; + b = 'B1'; + get pick() { + return this.useA ? this.a : this.b; + } + } + const store = createClassyStore(new Picker()); + let calls = 0; + subscribe(store, () => void calls++, {sync: true}); + store.b = 'B2'; + store.useA = false; + store.a = 'A2'; + line( + 'ours, sync subscriber', + `called ${calls} times for 3 writes, 2 of them to a field pick does not read at the time`, + ); +} +``` + +Output on the base, this pass: + +```text +ours live start: A1 (1) | b changed, not read: A1 (1) | switched to b: B2 (2) | a changed, no longer read: B2 (2) | b changed, read: B3 (3) | switched back: A2 (4) +ours snapshot start: A1 (1) | b changed, not read: A1 (1) | switched to b: B2 (2) | a changed, no longer read: B2 (2) | b changed, read: B3 (3) | switched back: A2 (4) +Preact, unobserved start: A1 (1) | b changed, not read: A1 (1) | switched to b: B2 (2) | a changed, no longer read: B2 (2) | b changed, read: B3 (3) | switched back: A2 (4) +Preact, in an effect start: A1 (1) | b changed, not read: A1 (1) | switched to b: B2 (2) | a changed, no longer read: B2 (2) | b changed, read: B3 (3) | switched back: A2 (4) +Preact, in an effect effect ran 4 times for 5 writes, 2 of them to a field pick did not read at the time +polyfill, unwatched start: A1 (1) | b changed, not read: A1 (1) | switched to b: B2 (2) | a changed, no longer read: B2 (2) | b changed, read: B3 (3) | switched back: A2 (4) +polyfill, unwatched sources after the last run: 2 +ours, sync subscriber called 3 times for 3 writes, 2 of them to a field pick does not read at the time +``` + +### Script 06: `06-computed-writes.ts` + +```ts +// A computed that writes. Ported from "a getter that writes to the store +// while it runs" in core.characterisation.getters.test.ts (:1325). +import {computed, effect, signal} from '@preact/signals-core'; +import {Signal} from 'signal-polyfill'; +import {createClassyStore, snapshot, subscribe} from './ours'; + +const line = (name: string, text: string) => console.log(name.padEnd(46), text); +const attempt = (run: () => unknown): string => { + try { + return JSON.stringify(run()); + } catch (error) { + return `threw ${(error as Error).constructor.name}: ${(error as Error).message}`; + } +}; + +// ── writes a field it does not read ── +{ + const runs = {doubled: 0}; + class Counter { + count = 1; + reads = 0; + get doubled() { + runs.doubled++; + this.reads = runs.doubled; + return this.count * 2; + } + } + const store = createClassyStore(new Counter()); + let calls = 0; + subscribe(store, () => void calls++, {sync: true}); + const values = [store.doubled, store.doubled, store.doubled]; + line( + 'ours live writes another field', + `values ${JSON.stringify(values)} | runs ${runs.doubled} | reads field ${store.reads} | subscriber calls ${calls}`, + ); + const snap = snapshot(store); + const before = runs.doubled; + line( + 'ours snapshot writes another field', + `${attempt(() => [snap.doubled, snap.doubled])} | runs ${runs.doubled - before}, and the body wrote ${runs.doubled} | reads field on the snapshot ${snap.reads}, on the store ${store.reads}`, + ); +} +{ + const runs = {doubled: 0}; + const count = signal(1); + const reads = signal(0); + const doubled = computed(() => { + runs.doubled++; + reads.value = runs.doubled; + return count.value * 2; + }); + let effectRuns = 0; + const stop = effect(() => void (reads.value, effectRuns++)); + const values = [doubled.value, doubled.value, doubled.value]; + line( + 'Preact writes another signal', + `values ${JSON.stringify(values)} | runs ${runs.doubled} | reads signal ${reads.value} | effect runs ${effectRuns}`, + ); + stop(); +} +{ + const runs = {doubled: 0}; + const count = new Signal.State(1); + const reads = new Signal.State(0); + const doubled = new Signal.Computed(() => { + runs.doubled++; + reads.set(runs.doubled); + return count.get() * 2; + }); + const values = [doubled.get(), doubled.get(), doubled.get()]; + line( + 'polyfill writes another signal', + `values ${JSON.stringify(values)} | runs ${runs.doubled} | reads signal ${reads.get()}`, + ); +} + +// ── writes the field it reads ── +console.log(); +{ + const runs = {next: 0}; + class Ticker { + n = 0; + get next() { + runs.next++; + this.n = this.n + 1; + return this.n; + } + } + const store = createClassyStore(new Ticker()); + let calls = 0; + subscribe(store, () => void calls++, {sync: true}); + const values = [store.next, store.next, store.next]; + line( + 'ours live writes what it reads', + `values ${JSON.stringify(values)} | runs ${runs.next} | n ${store.n} | subscriber calls ${calls}`, + ); + const store2 = createClassyStore(new Ticker()); + const snap = snapshot(store2); + line( + 'ours snapshot writes what it reads', + `${attempt(() => [snap.next, snap.next])} | n on the snapshot ${snap.n}, on the store ${store2.n}`, + ); +} +{ + const runs = {next: 0}; + const n = signal(0); + const next = computed(() => { + runs.next++; + n.value = n.value + 1; + return n.value; + }); + const values = [next.value, next.value, next.value]; + line( + 'Preact writes what it reads', + `values ${JSON.stringify(values)} | runs ${runs.next} | n ${n.value}`, + ); + line( + 'Preact the same, read by an effect', + attempt(() => { + const stop = effect(() => void next.value); + stop(); + return `no error | runs ${runs.next} | n ${n.value}`; + }), + ); +} +{ + const runs = {next: 0}; + const n = new Signal.State(0); + const next = new Signal.Computed(() => { + runs.next++; + n.set(n.get() + 1); + return n.get(); + }); + const values = [next.get(), next.get(), next.get()]; + line( + 'polyfill writes what it reads', + `values ${JSON.stringify(values)} | runs ${runs.next} | n ${n.get()}`, + ); + const watcher = new Signal.subtle.Watcher(() => {}); + watcher.watch(next); + line( + 'polyfill the same, watched', + attempt(() => [next.get(), next.get()]) + + ` | runs ${runs.next} | n ${n.get()}`, + ); +} +``` + +Output on the base, this pass: + +```text +ours live writes another field values [2,2,2] | runs 1 | reads field 1 | subscriber calls 1 +ours snapshot writes another field [2,2] | runs 1, and the body wrote 2 | reads field on the snapshot 1, on the store 1 +Preact writes another signal values [2,2,2] | runs 1 | reads signal 1 | effect runs 2 +polyfill writes another signal values [2,2,2] | runs 1 | reads signal 1 + +ours live writes what it reads values [1,2,3] | runs 3 | n 3 | subscriber calls 3 +ours snapshot writes what it reads [0,0] | n on the snapshot 0, on the store 0 +Preact writes what it reads values [1,2,3] | runs 3 | n 3 +Preact the same, read by an effect threw Error: Cycle detected +polyfill writes what it reads values [1,1,1] | runs 1 | n 1 +polyfill the same, watched [1,1] | runs 1 | n 1 +``` + +### Script 07: `07-effect-writes.ts` + +```ts +// A subscriber that writes to what it reads, and what happens to the others. +// Ported from "a write made inside a sync subscriber" (:501), "a subscriber +// that throws" (:833) and "unsubscribing during delivery" (:1148) in +// core.characterisation.notifications.test.ts. +import {effect, signal} from '@preact/signals-core'; +import {Signal} from 'signal-polyfill'; +import {createClassyStore, subscribe} from './ours'; +import {flushes, effect as polyfillEffect} from './polyfill-effect'; + +const tick = () => new Promise((resolve) => setTimeout(resolve, 0)); +const line = (name: string, text: string) => console.log(name.padEnd(48), text); +const attempt = (run: () => unknown): string => { + try { + const value = run(); + return value === undefined ? 'no error' : String(value); + } catch (error) { + return `threw ${(error as Error).constructor.name}: ${(error as Error).message}`; + } +}; +const consoleErrors: string[] = []; +const realError = console.error; +console.error = (...args: unknown[]) => + void consoleErrors.push( + String((args[0] as Error)?.message ?? args[0]).slice(0, 60), + ); + +// ── a subscriber that writes until a limit: converges ── +{ + const store = createClassyStore({n: 0}); + const seen: number[] = []; + subscribe( + store, + () => { + seen.push(store.n); + if (store.n < 3) store.n++; + }, + {sync: true}, + ); + store.n = 1; + line( + 'ours sync writes until n is 3', + `seen ${JSON.stringify(seen)} | n ${store.n}`, + ); + + const n = signal(0); + const pSeen: number[] = []; + const stop = effect(() => { + pSeen.push(n.value); + if (n.value > 0 && n.value < 3) n.value++; + }); + n.value = 1; + line( + 'Preact effect writes until n is 3', + `seen ${JSON.stringify(pSeen)} | n ${n.value}`, + ); + stop(); +} + +// ── a subscriber that always writes ── +{ + const store = createClassyStore({n: 0}); + let calls = 0; + subscribe( + store, + () => { + calls++; + store.n++; + }, + {sync: true}, + ); + line( + 'ours sync always writes', + `${attempt(() => { + store.n = 1; + })} at the write | calls ${calls} | n ${store.n} | console.error: ${JSON.stringify(consoleErrors)}`, + ); + consoleErrors.length = 0; + + const n = signal(0); + let runs = 0; + line( + 'Preact effect always writes, at creation', + `${attempt(() => { + effect(() => { + runs++; + n.value = n.value + 1; + }); + })} | runs ${runs} | n ${n.value}`, + ); + + const m = signal(0); + let mRuns = 0; + const stop = effect(() => { + mRuns++; + if (m.value > 0) m.value = m.value + 1; + }); + line( + 'Preact effect always writes, after a write', + `${attempt(() => { + m.value = 1; + })} at the write | runs ${mRuns} | m ${m.value}`, + ); + line( + 'Preact effect the next write', + `${attempt(() => { + m.value = 1000; + })} | runs ${mRuns} | m ${m.value}`, + ); + stop(); +} + +// ── the polyfill: a Watcher may not read or write ── +{ + const state = new Signal.State(0); + const other = new Signal.State(0); + const derived = new Signal.Computed(() => state.get() * 2); + let secondCalled = 0; + const writing = new Signal.subtle.Watcher(() => other.set(1)); + const second = new Signal.subtle.Watcher(() => void secondCalled++); + writing.watch(derived); + second.watch(derived); + derived.get(); + line( + 'polyfill Watcher that writes', + `${attempt(() => state.set(1))} at the write | state ${state.get()} | second watcher called ${secondCalled}`, + ); + writing.unwatch(derived); + second.unwatch(derived); + + const reading = new Signal.subtle.Watcher(() => void derived.get()); + reading.watch(derived); + derived.get(); + line( + 'polyfill Watcher that reads', + `${attempt(() => state.set(2))} at the write | state ${state.get()}`, + ); + reading.unwatch(derived); + + // The README effect runs in a microtask, so a write inside it is allowed. + const n = new Signal.State(0); + let runs = 0; + const stop = polyfillEffect(() => { + runs++; + n.set(n.get() + 1); + }); + await tick(); + line( + 'polyfill README effect, writes what it reads', + `runs ${runs} | n ${n.get()} | microtask flushes ${flushes.count}`, + ); + stop(); +} + +// ── a subscriber that throws: who hears about it, and does the next one run? ── +console.log(); +{ + const store = createClassyStore({n: 0}); + let second = 0; + subscribe( + store, + () => { + throw new Error('first subscriber failed'); + }, + {sync: true}, + ); + subscribe(store, () => void second++, {sync: true}); + line( + 'ours sync first subscriber throws', + `${attempt(() => { + store.n = 1; + })} at the write | second called ${second} | console.error: ${JSON.stringify(consoleErrors)}`, + ); + consoleErrors.length = 0; + + const n = signal(0); + let pSecond = 0; + const stopA = effect(() => { + if (n.value > 0) throw new Error('first effect failed'); + }); + const stopB = effect(() => void (n.value, pSecond++)); + line( + 'Preact first effect throws', + `${attempt(() => { + n.value = 1; + })} at the write | n ${n.value} | second ran ${pSecond - 1} | console.error: ${JSON.stringify(consoleErrors)}`, + ); + line( + 'Preact the next write', + `${attempt(() => { + n.value = 2; + })} at the write | second ran ${pSecond - 1}`, + ); + stopA(); + stopB(); +} + +// ── a subscriber removed by an earlier one, and a re-entrant write ── +console.log(); +{ + const store = createClassyStore({n: 0}); + const calls: string[] = []; + const stopSecond: {run?: () => void} = {}; + subscribe( + store, + () => { + calls.push('first'); + stopSecond.run?.(); + }, + {sync: true}, + ); + stopSecond.run = subscribe(store, () => void calls.push('second'), { + sync: true, + }); + store.n = 1; + line('ours sync second removed by first', JSON.stringify(calls)); + + const n = signal(0); + const pCalls: string[] = []; + const pStop: {run?: () => void} = {}; + effect(() => { + pCalls.push('first'); + if (n.value > 0) pStop.run?.(); + }); + pStop.run = effect(() => void (n.value, pCalls.push('second'))); + pCalls.length = 0; + n.value = 1; + line('Preact second removed by first', JSON.stringify(pCalls)); +} +{ + const store = createClassyStore({n: 0}); + const calls: string[] = []; + subscribe( + store, + () => { + calls.push(`first:${store.n}`); + if (store.n === 1) store.n = 2; + }, + {sync: true}, + ); + subscribe(store, () => void calls.push(`second:${store.n}`), {sync: true}); + store.n = 1; + line('ours sync re-entrant write', JSON.stringify(calls)); + + const n = signal(0); + const pCalls: string[] = []; + effect(() => { + pCalls.push(`first:${n.value}`); + if (n.value === 1) n.value = 2; + }); + effect(() => void pCalls.push(`second:${n.value}`)); + pCalls.length = 0; + n.value = 1; + line('Preact re-entrant write', JSON.stringify(pCalls)); +} +console.error = realError; +``` + +Output on the base, this pass: + +```text +ours sync writes until n is 3 seen [1,2,3] | n 3 +Preact effect writes until n is 3 seen [0,1,2,3] | n 3 +ours sync always writes no error at the write | calls 3017 | n 3018 | console.error: ["Maximum call stack size exceeded."] +Preact effect always writes, at creation threw Error: Cycle detected | runs 102 | n 101 +Preact effect always writes, after a write threw Error: Cycle detected at the write | runs 102 | m 101 +Preact effect the next write threw Error: Cycle detected | runs 203 | m 1100 +polyfill Watcher that writes threw Error: Writes to signals not permitted during Watcher callback at the write | state 1 | second watcher called 0 +polyfill Watcher that reads threw Error: at the write | state 2 +polyfill README effect, writes what it reads runs 1 | n 1 | microtask flushes 0 + +ours sync first subscriber throws no error at the write | second called 1 | console.error: ["first subscriber failed"] +Preact first effect throws threw Error: first effect failed at the write | n 1 | second ran 1 | console.error: [] +Preact the next write threw Error: first effect failed at the write | second ran 2 + +ours sync second removed by first ["first","second"] +Preact second removed by first ["first"] +ours sync re-entrant write ["first:1","first:2","second:2","second:2"] +Preact re-entrant write ["first:1","second:2","first:2"] +``` + +### Script 08: `08-batching.ts` + +```ts +// Batching, and when subscribers run. Ported from "transactions" (:10) and +// "batch()" (:237) in core.transactions.test.ts, and "subscribing or +// unsubscribing between a write and its delivery" (:414) in +// core.characterisation.notifications.test.ts. +import { + action, + batch as preactBatch, + computed, + createModel, + effect, + signal, +} from '@preact/signals-core'; +import {Signal} from 'signal-polyfill'; +import {batch, createClassyStore, snapshot, subscribe} from './ours'; + +const line = (name: string, text: string) => console.log(name.padEnd(50), text); +const attempt = (run: () => unknown): string => { + try { + run(); + return 'no error'; + } catch (error) { + return `threw ${(error as Error).message}`; + } +}; + +class Cart { + price = 10; + quantity = 1; + get total() { + return this.price * this.quantity; + } + restock() { + this.price = 20; + this.quantity = 3; + } +} + +// ── three ways to write two fields ── +{ + const store = createClassyStore(new Cart()); + const seen: number[] = []; + subscribe(store, () => void seen.push(store.total), {sync: true}); + store.price = 5; + store.quantity = 2; + const direct = seen.splice(0); + batch(() => { + store.price = 7; + seen.push(-store.total); + store.quantity = 4; + }); + const batched = seen.splice(0); + store.restock(); + line( + 'ours sync two direct writes', + `subscriber saw total ${JSON.stringify(direct)}`, + ); + line( + 'ours sync batch(), total read inside', + `saw ${JSON.stringify(batched)} (negative: read inside the batch)`, + ); + line('ours sync a method', `saw ${JSON.stringify(seen)}`); + + const price = signal(10); + const quantity = signal(1); + const total = computed(() => price.value * quantity.value); + const pSeen: number[] = []; + effect(() => void pSeen.push(total.value)); + pSeen.length = 0; + price.value = 5; + quantity.value = 2; + const pDirect = pSeen.splice(0); + preactBatch(() => { + price.value = 7; + pSeen.push(-total.value); + quantity.value = 4; + }); + const pBatched = pSeen.splice(0); + const restock = action(() => { + price.value = 20; + quantity.value = 3; + }); + restock(); + line( + 'Preact two direct writes', + `effect saw total ${JSON.stringify(pDirect)}`, + ); + line( + 'Preact batch(), total read inside', + `saw ${JSON.stringify(pBatched)} (negative: read inside the batch)`, + ); + line('Preact an action', `saw ${JSON.stringify(pSeen)}`); + + // createModel wraps every method of the model as an action. + const CartModel = createModel(() => { + const p = signal(10); + const q = signal(1); + return { + p, + q, + total: computed(() => p.value * q.value), + restock() { + p.value = 20; + q.value = 3; + }, + }; + }); + const model = new CartModel(); + const mSeen: number[] = []; + effect(() => void mSeen.push(model.total.value)); + mSeen.length = 0; + model.restock(); + line('Preact a createModel method', `saw ${JSON.stringify(mSeen)}`); + + const sPrice = new Signal.State(10); + const sQuantity = new Signal.State(1); + const sTotal = new Signal.Computed(() => sPrice.get() * sQuantity.get()); + let notified = 0; + const watcher = new Signal.subtle.Watcher(() => void notified++); + watcher.watch(sTotal); + sTotal.get(); + sPrice.set(5); + sQuantity.set(2); + const afterTwo = notified; + watcher.watch(); + sPrice.set(6); + const afterRearm = notified; + const read = sTotal.get(); + watcher.watch(); + sPrice.set(7); + line( + 'polyfill two direct writes', + `Watcher notified ${afterTwo} time | after watch() alone, a write notified ${afterRearm - afterTwo} | after a read (${read}) and watch(), a write notified ${notified - afterRearm}`, + ); +} + +// ── a write that is undone inside the same batch ── +console.log(); +{ + const store = createClassyStore(new Cart()); + let calls = 0; + subscribe(store, () => void calls++, {sync: true}); + const before = snapshot(store); + batch(() => { + store.price = 99; + store.price = 10; + }); + const after = snapshot(store); + line( + 'ours sync set and set back in a batch', + `subscriber calls ${calls} | same snapshot object: ${before === after} | equal content: ${JSON.stringify(before) === JSON.stringify(after)}`, + ); + + const price = signal(10); + let runs = 0; + let doubledRuns = 0; + const doubled = computed(() => (doubledRuns++, price.value * 2)); + effect(() => void (doubled.value, runs++)); + preactBatch(() => { + price.value = 99; + price.value = 10; + }); + line( + 'Preact set and set back in a batch', + `effect runs after the first ${runs - 1} | computed runs after the first ${doubledRuns - 1}`, + ); + price.value = 99; + price.value = 10; + line( + 'Preact the same without a batch', + `effect runs after the first ${runs - 1} | computed runs after the first ${doubledRuns - 1}`, + ); +} + +// ── a batch that throws ── +console.log(); +{ + const store = createClassyStore(new Cart()); + const seen: number[] = []; + subscribe(store, () => void seen.push(store.total), {sync: true}); + const result = attempt(() => + batch(() => { + store.price = 7; + throw new Error('stop'); + }), + ); + line( + 'ours sync batch() that throws', + `${result} | price ${store.price} | subscriber saw ${JSON.stringify(seen)}`, + ); + + const price = signal(10); + const pSeen: number[] = []; + effect(() => void pSeen.push(price.value)); + pSeen.length = 0; + const pResult = attempt(() => + preactBatch(() => { + price.value = 7; + throw new Error('stop'); + }), + ); + line( + 'Preact batch() that throws', + `${pResult} | price ${price.value} | effect saw ${JSON.stringify(pSeen)}`, + ); +} + +// ── a subscriber added inside a batch, after a write ── +console.log(); +{ + const store = createClassyStore(new Cart()); + let early = 0; + let late = 0; + subscribe(store, () => void early++, {sync: true}); + batch(() => { + store.price = 7; + subscribe(store, () => void late++, {sync: true}); + }); + line( + 'ours sync subscriber added after the write', + `early calls ${early} | late calls ${late}`, + ); + + const price = signal(10); + const earlySeen: number[] = []; + const lateSeen: number[] = []; + effect(() => void earlySeen.push(price.value)); + preactBatch(() => { + price.value = 7; + effect(() => void lateSeen.push(price.value)); + }); + line( + 'Preact effect added after the write', + `early saw ${JSON.stringify(earlySeen)} | late saw ${JSON.stringify(lateSeen)}`, + ); + const subSeen: number[] = []; + preactBatch(() => { + price.value = 8; + price.subscribe((value) => void subSeen.push(value)); + }); + line( + 'Preact signal.subscribe() added after', + `saw ${JSON.stringify(subSeen)}`, + ); +} +``` + +Output on the base, this pass: + +```text +ours sync two direct writes subscriber saw total [5,10] +ours sync batch(), total read inside saw [-14,28] (negative: read inside the batch) +ours sync a method saw [60] +Preact two direct writes effect saw total [5,10] +Preact batch(), total read inside saw [-14,28] (negative: read inside the batch) +Preact an action saw [60] +Preact a createModel method saw [60] +polyfill two direct writes Watcher notified 1 time | after watch() alone, a write notified 0 | after a read (12) and watch(), a write notified 1 + +ours sync set and set back in a batch subscriber calls 1 | same snapshot object: false | equal content: true +Preact set and set back in a batch effect runs after the first 0 | computed runs after the first 0 +Preact the same without a batch effect runs after the first 2 | computed runs after the first 2 + +ours sync batch() that throws threw stop | price 7 | subscriber saw [7] +Preact batch() that throws threw stop | price 7 | effect saw [7] + +ours sync subscriber added after the write early calls 1 | late calls 1 +Preact effect added after the write early saw [10,7] | late saw [7] +Preact signal.subscribe() added after saw [8] +``` + +### Script 09: `09-reads-per-dependency.ts` + +```ts +// A measurement, not a port: what a clean read costs when the body reads the +// same field many times. `loop` reads `this.rows` on every pass; `hoisted` +// reads it once. Both give the same total. +import {computed, signal} from '@preact/signals-core'; +import {Signal} from 'signal-polyfill'; +import {createClassyStore} from './ours'; + +const ROWS = 1000; +const makeRows = () => Array.from({length: ROWS}, (_, i) => ({price: i})); + +function micros(times: number, run: () => void, before?: () => void): string { + let total = 0; + for (let i = 0; i < times; i++) { + before?.(); + const start = performance.now(); + run(); + total += performance.now() - start; + } + return `${((total / times) * 1000).toFixed(2)} us`.padStart(11); +} +const line = (name: string, ...cells: string[]) => + console.log(name.padEnd(30), cells.join(' | ')); + +console.log( + `${ROWS} rows first read | clean read | read after an unrelated write`, +); +{ + class Table { + rows = makeRows(); + other = 0; + get loop() { + let sum = 0; + for (let i = 0; i < this.rows.length; i++) sum += this.rows[i].price; + return sum; + } + get hoisted() { + const rows = this.rows; + let sum = 0; + for (let i = 0; i < rows.length; i++) sum += rows[i].price; + return sum; + } + } + const store = createClassyStore(new Table()); + for (const key of ['loop', 'hoisted'] as const) { + line( + `ours live, ${key}`, + micros(1, () => void store[key]), + micros(2000, () => void store[key]), + micros( + 2000, + () => void store[key], + () => void store.other++, + ), + ); + } +} +{ + const rows = signal(makeRows()); + const other = signal(0); + const loop = computed(() => { + let sum = 0; + for (let i = 0; i < rows.value.length; i++) sum += rows.value[i].price; + return sum; + }); + line( + 'Preact, loop', + micros(1, () => void loop.value), + micros(2000, () => void loop.value), + micros( + 2000, + () => void loop.value, + () => void other.value++, + ), + ); +} +{ + const rows = new Signal.State(makeRows()); + const other = new Signal.State(0); + const loop = new Signal.Computed(() => { + let sum = 0; + for (let i = 0; i < rows.get().length; i++) sum += rows.get()[i].price; + return sum; + }); + line( + 'polyfill, loop', + micros(1, () => void loop.get()), + micros(2000, () => void loop.get()), + micros( + 2000, + () => void loop.get(), + () => other.set(other.get() + 1), + ), + ); + console.log( + 'polyfill, loop: recorded sources', + Signal.subtle.introspectSources(loop).length, + ); +} +``` + +Output on the base, this pass: + +```text +1000 rows first read | clean read | read after an unrelated write +ours live, loop 1204.38 us | 26.80 us | 25.96 us +ours live, hoisted 330.33 us | 0.12 us | 0.14 us +Preact, loop 327.46 us | 0.16 us | 0.12 us +polyfill, loop 576.67 us | 0.12 us | 12.46 us +polyfill, loop: recorded sources 2001 +``` + +### Script 10: `10-single-getter.ts` + +```ts +// A measurement, not a port: the everyday case. One getter over three fields, +// read when nothing changed, after an unrelated write, and after a write to a +// field it reads. Nanoseconds per read, best of five rounds of 500,000 reads. +import {createClassyStore} from './ours'; + +class Cart { + price = 10; + quantity = 2; + discount = 1; + other = 0; + get total() { + return this.price * this.quantity - this.discount; + } +} +const store = createClassyStore(new Cart()); +const READS = 500_000; +let sink = 0; + +function best(run: () => void): string { + let fastest = Number.POSITIVE_INFINITY; + for (let round = 0; round < 5; round++) { + const start = performance.now(); + run(); + fastest = Math.min(fastest, performance.now() - start); + } + return `${((fastest * 1e6) / READS).toFixed(0)} ns`.padStart(7); +} + +const field = best(() => { + for (let i = 0; i < READS; i++) sink += store.price; +}); +const clean = best(() => { + for (let i = 0; i < READS; i++) sink += store.total; +}); +const unrelated = best(() => { + for (let i = 0; i < READS; i++) { + store.other = i; + sink += store.total; + } +}); +const writeOnly = best(() => { + for (let i = 0; i < READS; i++) store.other = i + 1; +}); +const dirty = best(() => { + for (let i = 0; i < READS; i++) { + store.price = i; + sink += store.total; + } +}); +console.log( + `field read ${field} | getter, clean ${clean} | write alone ${writeOnly} | write to another field + getter ${unrelated} | write to a field it reads + getter ${dirty}`, + sink > 0 ? '' : '', +); +``` + +Output on the base, this pass: + +```text +field read 24 ns | getter, clean 61 ns | write alone 141 ns | write to another field + getter 206 ns | write to a field it reads + getter 316 ns +``` + +### Probe: `probe-first.ts` + +```ts +// A getter that returns a store node, read by another getter. +import {createClassyStore} from './ours'; + +class Table { + rows = [{price: 1}]; + get first() { + return this.rows[0]; + } + get firstPrice() { + return this.first.price; + } + get missing() { + return (this as unknown as {later?: number}).later ?? {fallback: true}; + } +} +const store = createClassyStore(new Table()); +const before = store.firstPrice; +store.rows[0].price = 2; +console.log( + 'firstPrice before and after the row changed:', + before, + store.firstPrice, +); +const a = store.missing; +console.log( + 'a getter over a missing property returns the same object twice:', + a === store.missing, +); +(store as unknown as {later?: number}).later = 5; +console.log('and sees the property once it exists:', store.missing); +``` + +Output on `spike-base`: + +```text +firstPrice before and after the row changed: 1 2 +a getter over a missing property returns the same object twice: false +and sees the property once it exists: 5 +``` + +Output on `spike-refresh`: + +```text +firstPrice before and after the row changed: 1 1 +a getter over a missing property returns the same object twice: true +and sees the property once it exists: 5 +``` + +Output on `spike-one`: + +```text +firstPrice before and after the row changed: 1 2 +a getter over a missing property returns the same object twice: true +and sees the property once it exists: 5 +``` + +### Spike outputs + +`01-ladder.spike-stamp` (previous run of this task): + +```text + +ours, live +depth | first read | clean read | read after an unrelated write | read after base changed | bodies run: first, clean, unrelated, base (times in microseconds) + 4 | 173.75 | 0.84 | 2.07 | 3.94 | 7, 0, 0, 7 per read + 8 | 29.46 | 0.21 | 1.64 | 5.68 | 15, 0, 0, 15 per read + 12 | 25.92 | 0.09 | 0.76 | 6.52 | 23, 0, 0, 23 per read + 16 | 13.54 | 0.08 | 0.99 | 10.60 | 31, 0, 0, 31 per read + 18 | 10.00 | 0.06 | 1.06 | 13.57 | 35, 0, 0, 35 per read + 20 | 16.00 | 0.06 | 1.40 | 11.86 | 39, 0, 0, 39 per read + 200 | 437.12 | 0.09 | 21.46 | 832.34 | 399, 0, 0, 399 per read +``` + +`01-ladder.spike-refresh` (previous run of this task): + +```text + +ours, live +depth | first read | clean read | read after an unrelated write | read after base changed | bodies run: first, clean, unrelated, base (times in microseconds) + 4 | 168.33 | 0.88 | 3.81 | 4.22 | 7, 0, 0, 7 per read + 8 | 24.79 | 0.23 | 4.36 | 4.76 | 15, 0, 0, 15 per read + 12 | 25.46 | 0.09 | 5.60 | 5.76 | 23, 0, 0, 23 per read + 16 | 19.08 | 0.09 | 4.19 | 11.10 | 31, 0, 0, 31 per read + 18 | 24.54 | 0.06 | 4.53 | 8.75 | 35, 0, 0, 35 per read + 20 | 23.13 | 0.06 | 5.02 | 12.42 | 39, 0, 0, 39 per read + 200 | 451.42 | 0.12 | 73.55 | 169.47 | 399, 0, 0, 399 per read +``` + +`01-ladder.spike-one` (previous run of this task): + +```text + +ours, live +depth | first read | clean read | read after an unrelated write | read after base changed | bodies run: first, clean, unrelated, base (times in microseconds) + 4 | 181.08 | 1.01 | 3.60 | 4.63 | 7, 0, 0, 7 per read + 8 | 23.79 | 0.21 | 2.41 | 5.22 | 15, 0, 0, 15 per read + 12 | 24.87 | 0.09 | 3.77 | 10.18 | 23, 0, 0, 23 per read + 16 | 18.63 | 0.10 | 3.91 | 8.44 | 31, 0, 0, 31 per read + 18 | 28.79 | 0.07 | 6.68 | 9.65 | 35, 0, 0, 35 per read + 20 | 17.46 | 0.07 | 4.25 | 12.00 | 39, 0, 0, 39 per read + 200 | 380.79 | 0.13 | 70.53 | 183.61 | 399, 0, 0, 399 per read +``` + +`09.spike-stamp` (previous run of this task): + +```text +1000 rows first read | clean read | read after an unrelated write +ours live, loop 1309.33 us | 0.24 us | 27.60 us +ours live, hoisted 368.04 us | 0.12 us | 0.15 us +``` + +`09.spike-refresh` (previous run of this task): + +```text +1000 rows first read | clean read | read after an unrelated write +ours live, loop 1263.00 us | 0.27 us | 27.56 us +ours live, hoisted 368.42 us | 0.11 us | 0.14 us +``` + +`09.spike-one` (previous run of this task): + +```text +1000 rows first read | clean read | read after an unrelated write +ours live, loop 1237.08 us | 0.26 us | 0.39 us +ours live, hoisted 356.88 us | 0.13 us | 0.19 us +``` + +`10.spike-base` (previous run of this task): + +```text +field read 23 ns | getter, clean 68 ns | write alone 138 ns | write to another field + getter 214 ns | write to a field it reads + getter 314 ns +``` + +`10.spike-stamp` (previous run of this task): + +```text +field read 23 ns | getter, clean 46 ns | write alone 145 ns | write to another field + getter 238 ns | write to a field it reads + getter 321 ns +``` + +`10.spike-refresh` (previous run of this task): + +```text +field read 24 ns | getter, clean 46 ns | write alone 150 ns | write to another field + getter 241 ns | write to a field it reads + getter 328 ns +``` + +`10.spike-one` (previous run of this task): + +```text +field read 23 ns | getter, clean 48 ns | write alone 146 ns | write to another field + getter 300 ns | write to a field it reads + getter 380 ns +``` + +Ports 02 to 08 on `spike-refresh`, lines that differ from the base (`<` base, `>` spike); `spike-stamp` gave no difference: + +```text +< ours live a 1 -> 3, d and label {"b":2,"c":2,"d":2,"parity":2,"label":2} | subscriber saw d = [ +> ours live a 1 -> 3, d and label {"b":2,"c":2,"d":2,"parity":2,"label":1} | subscriber saw d = [ +< ours live a method and a batch() {"b":4,"c":4,"d":4,"parity":2,"label":2} | subscriber saw d = [ +> ours live a method and a batch() {"b":4,"c":4,"d":4,"parity":2,"label":1} | subscriber saw d = [ +< ours live after ready = false: safe fallback | outer: threw not ready | runs {"strict":7,"safe":1,"outer":3} +> ours live after ready = false: safe fallback | outer: threw not ready | runs {"strict":8,"safe":1,"outer":3} +``` + +Ports 02 to 08 on `spike-one`, lines that differ from the base (`<` base, `>` spike); `spike-stamp` gave no difference: + +```text +< ours live a 1 -> 3, d and label {"b":2,"c":2,"d":2,"parity":2,"label":2} | subscriber saw d = [ +> ours live a 1 -> 3, d and label {"b":2,"c":2,"d":2,"parity":2,"label":1} | subscriber saw d = [ +< ours live a method and a batch() {"b":4,"c":4,"d":4,"parity":2,"label":2} | subscriber saw d = [ +> ours live a method and a batch() {"b":4,"c":4,"d":4,"parity":2,"label":1} | subscriber saw d = [ +< ours live after ready = true: safe fallback | runs {"strict":5,"safe":1,"outer":1} +< ours live after ready = true: outer outer:ready | strict: ready | runs {"strict":6,"safe":1,"outer":2} +< ours live after ready = false: safe fallback | outer: threw not ready | runs {"strict":7,"safe":1,"outer":3} +> ours live after ready = true: safe ready | runs {"strict":6,"safe":2,"outer":1} +> ours live after ready = true: outer outer:ready | strict: ready | runs {"strict":6,"safe":2,"outer":2} +> ours live after ready = false: safe fallback | outer: threw not ready | runs {"strict":10,"safe":3,"outer":3} +``` + +### Spike diffs + +`spike-stamp` + +```diff +--- core.types.ts ++++ core.types.ts (spike-stamp) +@@ -30,4 +30,6 @@ + export type ComputedEntry = { + value: unknown; + deps: DepEntry[]; ++ /** SPIKE: the owning node's version when this entry was last found valid. */ ++ stamp: number; + }; +--- core.ts ++++ core.ts (spike-stamp) +@@ -138,7 +138,11 @@ + // Validate through the computed cache — never re-execute the raw getter. + const cached = dep.internal.computedCache.get(dep.prop); + if (!cached) return false; // no cache → must recompute +- if (!areDepsValid(cached.deps)) return false; // nested deps changed ++ // SPIKE: validate a nested getter once per version of its node. ++ if (cached.stamp !== dep.internal.version) { ++ if (!areDepsValid(cached.deps)) return false; // nested deps changed ++ cached.stamp = dep.internal.version; ++ } + if (!Object.is(cached.value, dep.value)) return false; // value changed + } else { + // Check that the property still exists — if it was deleted and +@@ -164,8 +168,13 @@ + receiver: object, + ): unknown { + const cached = internal.computedCache.get(prop); +- if (cached && areDepsValid(cached.deps)) { +- return cached.value; ++ if (cached) { ++ // SPIKE: nothing under this node was written since the last check. ++ if (cached.stamp === internal.version) return cached.value; ++ if (areDepsValid(cached.deps)) { ++ cached.stamp = internal.version; ++ return cached.value; ++ } + } + + // Cycle detection: if this (internal, prop) pair is already being +@@ -187,8 +196,10 @@ + const frame = {internal, prop, deps: [] as DepEntry[]}; + trackerStack.push(frame); + try { ++ // SPIKE: taken before the body runs, so a getter that writes is checked again. ++ const stamp = internal.version; + const value = getterFn.call(receiver); +- internal.computedCache.set(prop, {value, deps: frame.deps}); ++ internal.computedCache.set(prop, {value, deps: frame.deps, stamp}); + return value; + } finally { + trackerStack.pop(); +``` + +`spike-refresh` + +```diff +--- core.types.ts ++++ core.types.ts (spike-refresh) +@@ -30,4 +30,6 @@ + export type ComputedEntry = { + value: unknown; + deps: DepEntry[]; ++ /** SPIKE: the owning node's version when this entry was last found valid. */ ++ stamp: number; + }; +--- core.ts ++++ core.ts (spike-refresh) +@@ -68,6 +68,13 @@ + deps: DepEntry[]; + }[] = []; + ++/** SPIKE: a frame that records nothing, pushed while a dependency is refreshed. */ ++const VALIDATING = { ++ internal: null as unknown as StoreInternal, ++ prop: Symbol('validating'), ++ deps: [] as DepEntry[], ++}; ++ + /** Returns the tracker currently recording deps, or `null` if none is active. */ + function activeTracker() { + return trackerStack.length > 0 ? trackerStack[trackerStack.length - 1] : null; +@@ -136,10 +143,18 @@ + if (dep.internal.version !== dep.version) return false; + } else if (dep.kind === 'computed') { + // Validate through the computed cache — never re-execute the raw getter. +- const cached = dep.internal.computedCache.get(dep.prop); +- if (!cached) return false; // no cache → must recompute +- if (!areDepsValid(cached.deps)) return false; // nested deps changed +- if (!Object.is(cached.value, dep.value)) return false; // value changed ++ // SPIKE: bring the nested getter up to date through its own memo, then ++ // ask whether its value changed. A frame that owns no node keeps the ++ // reads made here out of whichever getter is running further up. ++ trackerStack.push(VALIDATING); ++ try { ++ const current = Reflect.get(dep.internal.proxy, dep.prop); ++ if (!Object.is(current, dep.value)) return false; ++ } catch { ++ return false; // a dependency that throws counts as changed ++ } finally { ++ trackerStack.pop(); ++ } + } else { + // Check that the property still exists — if it was deleted and + // dep.value was `undefined`, Object.is(undefined, undefined) would +@@ -164,8 +179,13 @@ + receiver: object, + ): unknown { + const cached = internal.computedCache.get(prop); +- if (cached && areDepsValid(cached.deps)) { +- return cached.value; ++ if (cached) { ++ // SPIKE: nothing under this node was written since the last check. ++ if (cached.stamp === internal.version) return cached.value; ++ if (areDepsValid(cached.deps)) { ++ cached.stamp = internal.version; ++ return cached.value; ++ } + } + + // Cycle detection: if this (internal, prop) pair is already being +@@ -187,8 +207,10 @@ + const frame = {internal, prop, deps: [] as DepEntry[]}; + trackerStack.push(frame); + try { ++ // SPIKE: taken before the body runs, so a getter that writes is checked again. ++ const stamp = internal.version; + const value = getterFn.call(receiver); +- internal.computedCache.set(prop, {value, deps: frame.deps}); ++ internal.computedCache.set(prop, {value, deps: frame.deps, stamp}); + return value; + } finally { + trackerStack.pop(); +``` + +`spike-one` + +```diff +--- core.types.ts ++++ core.types.ts (spike-one) +@@ -1,33 +1,18 @@ + import type {StoreInternal} from './ownership'; + +-// ── Computed getter memoization types ───────────────────────────────────────── ++// SPIKE: one kind of dependency. Every entry says what a property of the ++// getter's own node gave when it was read: a plain value, a child's proxy, or ++// another getter's result. `version` is the version of the store node that ++// value is, or -1 when it is not one. ++export type DepEntry = {value: unknown; version: number}; + +-/** +- * A single dependency recorded during getter execution. +- * - `version`: dependency is a tracked sub-tree — compare `internal.version`. +- * - `value`: dependency is a primitive — compare via `Object.is`. +- */ +-export type DepEntry = +- | { +- kind: 'version'; +- internal: StoreInternal; +- version: number; +- /** Parent target — used to detect when the property is replaced entirely. */ +- parent: StoreInternal; +- /** Property name on the parent. */ +- prop: string | symbol; +- } +- | {kind: 'value'; target: object; prop: string | symbol; value: unknown} +- | { +- /** Dependency on a computed getter — validated via the computed cache, not raw getter re-execution. */ +- kind: 'computed'; +- internal: StoreInternal; +- prop: string | symbol; +- value: unknown; +- }; +- + /** Cached result of a memoized computed getter, together with its dependencies. */ + export type ComputedEntry = { + value: unknown; +- deps: DepEntry[]; ++ /** One entry per property read, in the order of the first read. */ ++ deps: Map; ++ /** The owning node's version when this entry was last found valid. */ ++ stamp: number; + }; ++ ++export type {StoreInternal}; +--- core.ts ++++ core.ts (spike-one) +@@ -63,93 +63,72 @@ + * because getter A can read getter B, which pushes a second tracker. + */ + const trackerStack: { +- internal: StoreInternal; ++ internal: StoreInternal | null; + prop: string | symbol; +- deps: DepEntry[]; ++ deps: Map; + }[] = []; + +-/** Returns the tracker currently recording deps, or `null` if none is active. */ +-function activeTracker() { +- return trackerStack.length > 0 ? trackerStack[trackerStack.length - 1] : null; ++/** A frame that records nothing, pushed while dependencies are re-read. */ ++const VALIDATING = { ++ internal: null, ++ prop: Symbol('validating'), ++ deps: new Map(), ++}; ++ ++/** Stands for "the property did not exist" and for "the getter threw". */ ++const MISSING = Symbol('missing'); ++const THREW = Symbol('threw'); ++ ++/** The version of the store node a value is, or -1 when it is not one. */ ++function versionOf(value: unknown): number { ++ if (typeof value !== 'object' || value === null) return -1; ++ return internalsMap.get(value)?.version ?? -1; + } + + /** +- * Record a dependency on the active tracker (if any). +- * Called from the GET trap whenever a non-getter, non-method property is read. ++ * Record what a property of the running getter's own node gave. The first read ++ * of a property in a run is the one that counts. + */ + function recordDep( + internal: StoreInternal, + prop: string | symbol, + value: unknown, + ): void { +- const tracker = activeTracker(); +- if (!tracker) return; +- +- // Only record deps for reads on the SAME proxy that owns the getter. +- // Child-proxy reads don't need explicit tracking because child mutations +- // bubble up via version numbers on the parent's childInternals. +- if (tracker.internal !== internal) return; +- +- const childInternal = internal.childInternals.get(prop); +- if (childInternal) { +- tracker.deps.push({ +- kind: 'version', +- internal: childInternal, +- version: childInternal.version, +- parent: internal, +- prop, +- }); +- } else { +- tracker.deps.push({kind: 'value', target: internal.target, prop, value}); +- } ++ if (trackerStack.length === 0) return; ++ const tracker = trackerStack[trackerStack.length - 1]; ++ if (tracker.internal !== internal || tracker.deps.has(prop)) return; ++ tracker.deps.set(prop, {value, version: versionOf(value)}); + } + +-/** +- * Record a computed getter dependency on the active tracker (if any). +- * Unlike `recordDep`, this creates a `'computed'` dep entry that validates +- * through the computed cache rather than re-executing the raw getter. +- */ +-function recordComputedDep( +- internal: StoreInternal, +- prop: string | symbol, +- value: unknown, +-): void { +- const tracker = activeTracker(); +- if (!tracker) return; +- if (tracker.internal !== internal) return; +- +- tracker.deps.push({kind: 'computed', internal, prop, value}); ++/** What reading `prop` gives now, without the method binding of the `get` trap. */ ++function currentOf(internal: StoreInternal, prop: string | symbol): unknown { ++ const child = internal.childInternals.get(prop); ++ if (child) return child.proxy; ++ const descriptor = findPropertyDescriptor(internal.target, prop); ++ if (!descriptor) return MISSING; ++ if (descriptor.get) ++ return evaluateComputed(internal, prop, descriptor.get, internal.proxy); ++ return Reflect.get(internal.target, prop); + } + +-/** +- * Check whether all dependencies from a previous computation are still valid. +- */ +-function areDepsValid(deps: DepEntry[]): boolean { +- for (const dep of deps) { +- if (dep.kind === 'version') { +- // Verify the parent property still references the same child object. +- // If the property was replaced entirely (e.g., store.items = newArray), +- // the old child internal is detached and its version never changes. +- // This check catches that case. +- if (dep.parent.childInternals.get(dep.prop) !== dep.internal) +- return false; +- if (dep.internal.version !== dep.version) return false; +- } else if (dep.kind === 'computed') { +- // Validate through the computed cache — never re-execute the raw getter. +- const cached = dep.internal.computedCache.get(dep.prop); +- if (!cached) return false; // no cache → must recompute +- if (!areDepsValid(cached.deps)) return false; // nested deps changed +- if (!Object.is(cached.value, dep.value)) return false; // value changed +- } else { +- // Check that the property still exists — if it was deleted and +- // dep.value was `undefined`, Object.is(undefined, undefined) would +- // incorrectly pass without this guard. +- if (!Reflect.has(dep.target, dep.prop)) return false; +- if (!Object.is(Reflect.get(dep.target, dep.prop), dep.value)) ++/** Re-read every dependency; any difference, or a throw, means "recompute". */ ++function areDepsValid( ++ internal: StoreInternal, ++ deps: Map, ++): boolean { ++ trackerStack.push(VALIDATING); ++ try { ++ for (const [prop, dep] of deps) { ++ const current = currentOf(internal, prop); ++ if (!Object.is(current, dep.value) || versionOf(current) !== dep.version) + return false; + } ++ return true; ++ } catch { ++ return false; ++ } finally { ++ trackerStack.pop(); + } +- return true; + } + + /** +@@ -164,16 +143,20 @@ + receiver: object, + ): unknown { + const cached = internal.computedCache.get(prop); +- if (cached && areDepsValid(cached.deps)) { +- return cached.value; ++ if (cached) { ++ // Nothing under this node was written since the last check. ++ if (cached.stamp === internal.version) return cached.value; ++ if (areDepsValid(internal, cached.deps)) { ++ cached.stamp = internal.version; ++ return cached.value; ++ } + } + +- // Cycle detection: if this (internal, prop) pair is already being +- // evaluated higher in the stack, the getter chain is recursive. + for (const existing of trackerStack) { + if (existing.internal === internal && existing.prop === prop) { + const cycle = trackerStack + .slice(trackerStack.indexOf(existing)) ++ .filter((f) => f.internal) + .map((f) => String(f.prop)) + .concat(String(prop)) + .join(' → '); +@@ -183,15 +166,32 @@ + } + } + +- // Push a new tracker frame for this getter evaluation. +- const frame = {internal, prop, deps: [] as DepEntry[]}; ++ const frame = {internal, prop, deps: new Map()}; + trackerStack.push(frame); + try { ++ // Taken before the body runs, so a getter that writes is checked again. ++ const stamp = internal.version; + const value = getterFn.call(receiver); +- internal.computedCache.set(prop, {value, deps: frame.deps}); ++ internal.computedCache.set(prop, {value, deps: frame.deps, stamp}); + return value; + } finally { + trackerStack.pop(); ++ } ++} ++ ++/** Read a getter for the `get` trap: recorded whether it returns or throws. */ ++function readGetter( ++ internal: StoreInternal, ++ prop: string | symbol, ++ getterFn: () => unknown, ++ receiver: object, ++): unknown { ++ let value: unknown = THREW; ++ try { ++ value = evaluateComputed(internal, prop, getterFn, receiver); ++ return value; ++ } finally { ++ recordDep(internal, prop, value); + } + } + +@@ -462,19 +462,8 @@ + internal.resumeScope(); + // 1. Check for getters on the prototype chain (computed values). + const getterDesc = findPropertyDescriptor(_target, prop); +- if (getterDesc?.get) { +- // Memoized: evaluate with dependency tracking, return cached if deps unchanged. +- const value = evaluateComputed( +- internal, +- prop, +- getterDesc.get, +- receiver, +- ); +- // Record as a computed dependency for any parent getter currently tracking. +- // Uses 'computed' dep kind so validation goes through the cache, not raw getter. +- recordComputedDep(internal, prop, value); +- return value; +- } ++ if (getterDesc?.get) ++ return readGetter(internal, prop, getterDesc.get, receiver); + + const value = Reflect.get(_target, prop); + +@@ -495,7 +484,11 @@ + // An inherited data property becomes an edge on its first proxy read. + const child = + internal.childInternals.get(prop) ?? linkChild(internal, prop, value); +- recordDep(internal, prop, value); ++ recordDep( ++ internal, ++ prop, ++ child ? child.proxy : getterDesc ? value : MISSING, ++ ); + return child ? child.proxy : value; + }, + +``` + +`spike-memo` + +```diff +--- spike-base/src/snapshot/snapshot.ts 2026-11-16 20:33:32 ++++ spike-memo/src/snapshot/snapshot.ts 2026-11-19 04:36:57 +@@ -142,6 +142,8 @@ + const computation = computeWithTracking(currentSnap, getterFn); + result = computation.result; + ++ // SPIKE: a nested getter may have created the map while this one ran. ++ memoMap = crossSnapshotMemo.get(target); + // Save cross-snapshot memo. + if (!memoMap) { + memoMap = new Map(); +``` diff --git a/review/stage-2/solid.md b/review/stage-2/solid.md new file mode 100644 index 00000000..cd555522 --- /dev/null +++ b/review/stage-2/solid.md @@ -0,0 +1,2811 @@ +# Stage 2: Solid 2's store (`@solidjs/signals`) + +Read-only comparison for the pre-1.0 review, 2026-11-18. Nothing in the +repository was changed except this file. + +## Library, version and commit + +- Library: the store in `@solidjs/signals`, which `solid-js` 2.0.0 re-exports. +- Version: `@solidjs/signals` 2.0.0, the version `solid-js` 2.0.0 depends on + and the one installed in this repository under + `node_modules/.bun/@solidjs+signals@2.0.0`. +- Source: `https://github.com/solidjs/solid`, tag `@solidjs/signals@2.0.0`, + commit `a8186e6738b3a6a3341c561f66e9325432d6759b` (2026-11-16). +- The package ships bundles only (`dist/dev.js`, `dist/prod/`, + `dist/observe/`), so the source was cloned into a scratch folder and read + there. Solid paths below are relative to `packages/signals/` in that + repository. Our paths are relative to `packages/classy-store/src/`. +- The ported tests ran on Node 24.21.0 against `@solidjs/signals@2.0.0` + installed from npm in the scratch folder, and on Bun 1.4.4 against our + source imported by absolute path. Machine: Apple M1 Max, macOS 26.6.2. + +## Files read + +Solid: + +- `src/store/types.ts`, `src/store/target.ts`, `src/store/reconcile.ts`, + `src/store/index.ts` (whole files) +- `src/store/store.ts` (3,003 lines), these parts: the header, `TargetShape`, + `createTarget`, `wrap`, `unwrapValue`, `getNode`, `getHasNode`, + `isOwnAccessor`, `cloneRaw`, `scanAccessorsOnce`, `ensurePB`, + `notifyWrites`, `inDraft`, `nodeValue`, `serveDataKey`, the `traps` object, + `warnWriteOutsideSetter`, `devGuardStoreSetterWrite`, + `devGuardStoreSetterResult`, `storeSetter`, `createStore`, `deep`, + `snapshot`, `snapshotWalk`, `snapshotRecord` +- `src/core/dev.ts`: the diagnostic types, `emitDiagnostic`, + `reportDiagnostic`, `assertInvariant` +- `src/globals.d.ts`, `src/index.ts`, `rollup.config.js`, `package.json` +- `packages/solid/package.json`, and the `diagnostics.json` that `solid-js` + ships +- Two upstream test files, for what the authors intend with class instances: + `tests/store/createStore.test.ts` ("Nested Classes") and + `tests/store/native-collections.test.ts` + +Ours: `core/core.ts`, `core/ownership.ts`, `snapshot/snapshot.ts`, +`utils/internal/internal.ts`, `frameworks/solid/solid.ts`, and +`applySnapshot` in `utils/history/history.ts`. + +Not read: Solid's `store/utils.ts` (it holds `merge` and `omit` for props, not +store internals), `optimistic.ts`, `projection.ts`, `storePath.ts`, the +scheduler, and the attribution engine behind the performance diagnostics. + +## Summary + +Solid 2.0.0's store is a different machine from the one the first comparison +described. Three facts shape everything below: + +- **Writes happen only inside `setStore(draft => ...)`.** A write anywhere + else is ignored. The development build says so; production is silent. +- **It never writes to the object it was given.** The first write clones the + record (copy-on-write), and the store reads its clone from then on. +- **A write is not visible until the flush.** After a setter returns, a plain + read still gives the old value until a microtask or `flush()` (port 7). + +The three findings I would act on first: + +1. **The per-prototype getter cache does not exist** (finding 1). Solid + caches _wrappability_ per prototype, and _accessor-ness_ per subscribed + key. It never classifies a prototype getter, and its class getters go stale + over nested data because of it (finding 2). A cache shaped for our needs + cut a field read by 18% on Node and 53% on Bun in a scratch spike. +2. **Functions are never wrapped, and class instances wrap without an + opt-in** (findings 3 and 4). The first removes the cause of stage 1 + findings 5, 6, 42 and 62. The second removes a third silent failure the + plan does not list: a method called on a nested class instance that lacks + `PROXYABLE` changes state and notifies no one. +3. **`defineProperty` is an ordinary write, `has` and `ownKeys` are tracked, + and diagnostics have stable codes in a build of their own** (findings 6 to + 9). The first two fix stage 1 findings 1, 30, 31, 45, 61, 66, 67 and 71. + Solid has no answer for arrow-function methods: there the write is lost + outright. + +## Findings + +### 1. The read path: what Solid caches, and what "per prototype" means there + +**What they do.** There is no per-prototype getter cache in 2.0.0. I also +searched the 2.0.0-rc.18 and 2.0.0-rc.23 bundles installed in this repository +and found none. Three smaller caches answer related questions: + +- **Wrappability, per prototype.** `wrappableProtos` in `src/store/types.ts` + (line 153) is a `WeakMap` from a prototype object to a boolean, read and + filled by `isWrappable` (lines 157 to 171). + - _Keyed_ by `Object.getPrototypeOf(obj)`. + - _Filled_ the first time an object with that prototype is tested, unless + the prototype is `Object.prototype`, `null` or the object is an array, + which are answered without the map. The verdict is "its + `Object.prototype.toString` tag is `[object Object]`, and it is not a DOM + `Node`". + - _Never invalidated._ + - _Assumes_ every instance of one prototype gives the same answer. The + frozen test is not cached: `Object.isFrozen(obj)` runs first on every + call (line 159). +- **Accessor-ness, per record and key.** Each subscribed key has a slot node, + and the node carries an `acc` flag. + - _Keyed_ by the record's internal target and the property key + (`target.n[key]`). + - _Filled_ when the node is created, in `getNode` (`src/store/store.ts` + lines 368 to 410, the flag at line 389), which happens on the first + _tracked_ read of the key (lines 2252 to 2259). The probe is + `isOwnAccessor` (lines 578 to 583): `hasOwnProperty`, then + `__lookupGetter__` and `__lookupSetter__`. No descriptor object is + allocated. + - _Refreshed_ in `notifyWrites` (line 1162), when a setter writes a key + that was an own accessor or has become one. + - _Assumes_ every change comes through the setter, and covers **own** + accessors only. +- **Accessors seen, per record.** `a` (sticky: an own accessor was seen) and + `sc` (scan grade) on the target, filled by `scanAccessorsOnce` (lines 641 + to 656) on the first write to the record. They choose the clone strategy + and decide whether a write may visit only the keys it wrote. + +A read of a key that has no node, outside a computation, checks nothing: it +is `src[key]` on the backing object (line 2285). A getter found that way runs +with the raw backing as `this`. Only when the result is `undefined` and the +key is not own does the trap read again with the proxy as receiver (lines +2286 to 2290). + +**What we do.** The `get` trap calls `findPropertyDescriptor(_target, prop)` +on every read (`core/core.ts:464`). That walks the prototype chain with +`Object.getOwnPropertyDescriptor` until it finds the key +(`utils/internal/internal.ts:88-99`): one allocated descriptor for an own +field, two or more calls for a class method, the whole chain for a missing +key. The `set` trap does the same (`core/core.ts:413`). + +**Difference in behaviour.** Timing only. Port 6 below, median of seven +rounds of two million reads, nanoseconds per read. "Spike" is a scratch copy +of our core with the change proposed here. + +| Read | Node 24.21.0 | Bun 1.4.4 | +| ------------------------------------------ | -----------: | --------: | +| Forwarding Proxy, field | 21.7 | 2.5 | +| classy-store today, field | 46.5 | 25.4 | +| classy-store with the spike, field | 38.2 | 11.9 | +| Solid, class field, nobody subscribed | 28.3 | 22.2 | +| Solid, class field, an effect subscribed | 33.1 | 16.9 | +| classy-store today, cached getter | 79.9 | 58.2 | +| classy-store with the spike, cached getter | 74.6 | 34.3 | +| Solid, prototype getter, nobody subscribed | 40.7 | 23.1 | +| classy-store today, method lookup | 64.5 | 49.8 | +| classy-store with the spike, method lookup | 60.1 | 30.9 | +| Solid, method lookup | 39.8 | 15.4 | + +The "today" figures are close to the stage 1 baseline (45.1 ns on Node, 31.8 +on Bun, from a different harness). + +**Proposal: adapt.** Solid's own mechanism cannot be copied, because it never +sees a prototype getter and our memoization depends on finding one (finding +2). The two ideas inside it can: + +1. _Decide an own key without a descriptor._ `hasOwnProperty`, plus one flag + per node, "this object has an own accessor". `createNode` already reads + every own descriptor when it indexes a node (`core/core.ts:537-541`), so + the flag is free there; the `defineProperty` trap sets it later. +2. _Answer an inherited key from a table per prototype_: a + `WeakMap>`, filled on the first + miss by the existing `findPropertyDescriptor`. The prototype is read with + `Object.getPrototypeOf(target)` on each inherited read, so + `Object.setPrototypeOf` on a store still works. + +The spike is 30 lines (its diff is under port 6). It assumes two things the +library already does not handle: a prototype is not given a new getter after +its first read through a store (stage 1 findings 44 and 47), and an accessor +is not defined on the raw object behind the proxy (finding 11). **The spike +was not run against the unit suite.** What remains on Node after it, about 16 +ns over a bare Proxy, is the rest of the trap: `resumeScope()`, the +`childInternals` lookup and `linkChild` on every read. + +**Kind:** performance. + +**Cost:** `core/core.ts` (`get` and `set` traps), one field in +`core/ownership.ts`. Not breaking. Risk low to medium; stage 3 lists this as +a spike already and can start from this one. + +### 2. Class getters: Solid's shortcut goes stale, ours does not + +**What they do.** A prototype getter is treated as data. + +- A tracked read runs it with the raw backing as `this` (`src[key]`, + `src/store/store.ts` line 2285) and stores the result in a slot node made + for that key (`serveDataKey`, lines 1759 to 1802). Later reads are served + from the node (lines 2187 to 2203) and do not run the getter. +- Nothing records what the getter read. Instead, when a setter writes a + record whose prototype is not plain, `notifyWrites` gives up on visiting + only the written keys (lines 1136 to 1138), visits every node of the + record, and reads each key again from the new backing (line 1176). That + re-runs every observed prototype getter of the record on every write to it. +- An **own** accessor (a getter in an object literal) takes another path: it + runs with the proxy as `this` on every read (lines 2260 to 2266), so + everything it reads is tracked. It is not memoized. + +**What we do.** Every getter, own or inherited, runs with the proxy as +`this`, records its dependencies and is memoized (`core/core.ts:160-196` and +`464-477`). A child object it reads is a version dependency +(`core/core.ts:93-101`). + +**Difference in behaviour.** Port 2. A class getter that sums nested rows: + +```text +Solid: write a nested row the getter reads: s.inner.items[0].price = 10 + -> {"seenTotal":5,"untrackedRead":5,"totalRuns":0} +ours: write a nested row the getter reads + -> {"total":13,"again":13,"totalRuns":2} +``` + +In Solid the effect never re-runs and even a plain read keeps answering 5, +because the write touched the row's record, not the instance's. A getter over +the instance's own fields does update, by the re-read described above; in the +same port a write to `count` re-ran both observed getters once each. + +The upstream test for this (`tests/store/native-collections.test.ts`, "user +class instances still wrap") reads one own field, and its comment says the +getter "kept the proxy receiver". For a prototype getter that is not what the +code does. + +**Proposal: reject.** Keep detecting prototype getters and tracking what +they read. This is the reason finding 1 adapts Solid's cache instead of +adopting it. + +**Kind:** API design (confirms ours). + +**Cost:** none. + +### 3. Functions are never wrapped + +**What they do.** The `get` trap separates two cases by where the function +lives (`src/store/store.ts`): + +- _Inherited from the prototype chain_: a method. It is returned as it is + (lines 2291 and 2310 to 2315). `this` is the proxy because the caller wrote + `proxy.method()`. Nothing is bound, cached or wrapped. +- _An own property_: data. It goes through `serveDataKey` like any value, and + since a function is not wrappable (`NotWrappable` in `src/store/types.ts` + lines 97 to 106) the function itself comes back. +- `constructor` is a special case: a plain read answers the source's class + (lines 2277 to 2284). + +**What we do.** Any function read through a store is wrapped by +`transactional(method, receiver)` (`core/core.ts:483-492`): a new wrapper on +every read for an array (line 486), one cached per property otherwise (lines +487 to 491). The wrapper forwards `new` (line 269) and has none of the +function's own properties. + +**Difference in behaviour.** Ports 3 and 8: + +```text + Solid ours +store.callbacks[0] === store.callbacks[0] true false +store.callbacks.indexOf(first) 0 -1 +remove the first callback by indexOf second is left wrong one removed +store.Model === Model, store.Model.label [true,"model"] [false,null] +new store.Model("x") instanceof store.Model true false +constructor is the class (port 2) true false +``` + +Solid pays for it in one place: a destructured method loses `this` (port 7, +"Methods are not bound"), where ours keeps it. + +**Proposal: adapt.** Solid can leave every function alone because all its +writes happen inside a setter. We need the wrapper for methods, to bind +`this` and to open the transaction. So keep the wrapper, and narrow what gets +it: + +- A function **inherited** from the prototype chain is a method: wrap it as + today. This covers class methods and `Array.prototype` methods. +- An **own** function in an **array** is data: return it untouched. +- A function whose own `prototype` property is **not writable** is a class or + a built-in constructor: return it untouched. That test is exact: it is + `false` for `class A {}` and for `Map`, `true` for `function () {}`, and the + property is absent on arrows, shorthand methods and async functions + (checked on Node 24). +- `constructor` is returned untouched. +- An own function on a non-array object stays wrapped and cached, as today. + An object-literal store (`{count: 0, increment() {...}}`) holds its methods + as own properties, so they must keep the transaction. + +With finding 1 in place the trap already knows "own or inherited" before it +gets here. This fixes stage 1 findings 5, 6 and 42, and the `holder.fn === +fn` part of 62. Not spiked. + +**Kind:** bug. + +**Cost:** `core/core.ts` (`get` trap). Breaking only for code that relied on +a function stored in an array being bound to that array. Risk low. + +### 4. Class instances wrap by default; opting out is explicit + +**What they do.** `isWrappable` (`src/store/types.ts` lines 157 to 171) wraps +plain objects, null-prototype objects, arrays, and any other object whose tag +is `[object Object]`, which is every ordinary class instance. Leaves are: + +- platform objects, by that tag check: `Date`, `Map`, `Set`, typed arrays, + promises (verified); +- DOM nodes; +- frozen objects; +- anything passed through `markRaw()` (lines 119 to 125), kept in a + `WeakSet` and checked in `wrap` (`src/store/store.ts` line 219). + +The header comment of `tests/store/native-collections.test.ts` gives the +reason for the tag check: native code checks internal slots and throws when +called with a proxy as `this`. + +One sharp edge, verified: a class that defines `Symbol.toStringTag` is a +leaf. + +**What we do.** `canProxy` (`utils/internal/internal.ts:70-82`) wraps arrays, +plain objects, and class instances whose constructor sets +`static [PROXYABLE] = true`. Everything else is kept by reference. The root +given to `createClassyStore` is always wrapped. + +**Difference in behaviour.** Port 2, the same class nested in a store with +and without the opt-in: + +```text +ours: store.inner.increment() notifies -> {"count":2,"subscriberCalls":0} + store.opted.increment() notifies -> {"count":2,"subscriberCalls":1} +Solid: call a prototype method on the draft: s.inner.increment() + -> {"count":6,"seenDouble":12,"rawCount":1} +``` + +Ours changes the state and tells no subscriber. This is a third silent +failure mode next to the two the plan names, and the commonest shape for it +is a class-based store that holds another class instance. + +**Proposal: adopt the default, adapt the test.** Wrap an object unless it is +a platform object, and cache the verdict per prototype as Solid does. Keep +two ways out: freezing, which we have, and one explicit marker (a +`markRaw`-style function, or `PROXYABLE` turned into an opt-out). API +question 6 below. + +**Kind:** API design. + +**Cost:** `utils/internal/internal.ts` (`canProxy`), the collections' use of +`PROXYABLE`, docs. **Breaking, so before 1.0**: a third-party class instance +held in a store becomes a proxy. One whose methods use `#private` fields then +throws when called through the store (port 9: both libraries throw a +`TypeError` there), and would need the marker. Risk medium. + +### 5. The proxy target is an empty shell, not the raw object + +**What they do.** `createTarget` (`src/store/store.ts` lines 197 to 209) +builds the proxy over an empty `[]` or `{}` (line 205). The handler is the +internal record itself; the traps sit on its prototype (line 2513). Because +the shell has no properties, no `get` invariant can ever fire, whatever +happens to the raw object. The price: + +- `has`, `ownKeys`, `getOwnPropertyDescriptor` and `getPrototypeOf` become + mandatory, and every descriptor is reported configurable (line 2399). +- `preventExtensions` is refused (line 2510), so `Object.freeze(store)` + throws. +- A non-configurable property defined inside a setter is applied to the + backing, and then the engine throws from the `defineProperty` invariant + (port 4). That looks like a bug in Solid. + +**What we do.** The proxy wraps the raw object (`core/core.ts:405`). +Invariants are handled one by one: `isReadOnly` (`core/core.ts:345-347`), its +use in `linkChild` (lines 369 to 374), and the `defineProperty` trap (lines +502 to 513). + +**Difference in behaviour.** Port 1: + +```text + Solid ours +freeze the raw child behind the store, read below 1 THROWS TypeError +Object.freeze(store) THROWS works (CLAUDE.md) +``` + +**Proposal: reject for 1.0.** It would fix stage 1 finding 46 and delete +`isReadOnly` and the freeze branch. It would also make four more traps +mandatory, give up `Object.freeze(store)`, and change what a descriptor read +reports. Document instead that the raw object must not be frozen or redefined +behind the store, which finding 11 of stage 1 already implies. It stays the +fallback if invariant bugs keep appearing after finding 7. + +**Kind:** simplification. + +**Cost:** large: every trap in `core/core.ts`, and `snapshot.ts` where it +reads descriptors. Breaking. + +### 6. `has`, `ownKeys` and descriptor reads are tracked, each on its own + +**What they do.** Three structures, so that each kind of reader re-runs only +for its own kind of change (`src/store/store.ts`): + +- `has` (lines 2319 to 2352) subscribes to a **presence node** for that one + key (`getHasNode`, lines 412 to 424). +- `ownKeys` (lines 2354 to 2362) subscribes to the record's **container + node**, which `notifyWrites` tells only when membership changed (lines 1228 + to 1248). +- `getOwnPropertyDescriptor` (lines 2364 to 2401) tracks presence. +- Reading a key that does not exist subscribes to that key (lines 2295 to + 2306). + +**What we do.** No `has` or `ownKeys` trap. A getter records `get` reads only +(`core/core.ts:80-105`). The proxy used to compute snapshot getters has a +`get` trap over an empty object and nothing else +(`snapshot/snapshot.ts:80-93`). + +**Difference in behaviour.** Port 4, section 7: adding an unrelated key +re-ran the `Object.keys` effect and not the `'c' in bag` effect; changing a +value re-ran neither. And a getter that reads its own keys (ports 4 and 8): + +```text +Solid: delete s.b -> {"seenCount":3,"seenHasB":false,"snapshotCount":3} +ours: delete store.b + -> {"count":4,"hasB":true,"snapshotCount":0,"snapshotHasB":false} +``` + +Ours is stale on the live store and wrong in another way on the snapshot +(stage 1 findings 30 and 31). + +**Proposal: adapt.** We have no observers outside getters, so we need no +nodes, only two more kinds of getter dependency: + +- a `has` trap that records `{prop, present}` while a getter of that node is + being tracked; +- an `ownKeys` trap that records the node's "shape" while a getter is being + tracked: a counter the `set` (new key), `deleteProperty` and + `defineProperty` traps bump. + +Both are a plain `Reflect` forward when no getter is running. On the snapshot +side, give the tracking proxy `has`, `ownKeys`, `getOwnPropertyDescriptor` +and `getPrototypeOf` traps that forward to the frozen snapshot and record the +key list as a dependency. That also answers stage 1 finding 41 (no own keys, +not an instance of the class). + +**Kind:** bug. + +**Cost:** `core/core.ts`, `core/core.types.ts`, `snapshot/snapshot.ts`. Not +breaking. Risk low. Stage 3 lists these traps as a spike. + +### 7. `defineProperty` is an ordinary write + +**What they do.** The `defineProperty` trap (`src/store/store.ts` lines 2458 +to 2475) passes the same gate as `set`, unwraps a proxy given as the value, +records the key as written, updates the accessor flags and defines the +property on the pending backing. The notification leaves with the rest of the +setter's writes; `notifyWrites` re-reads the key's accessor-ness (line 1162) +and compares old and new descriptors (lines 1163 to 1171). + +**What we do.** The trap forwards the definition and then only detaches a +child whose property became read-only (`core/core.ts:502-513`). It does not +resume a suspended subtree, link a new object value, drop the cached bound +method, bump a version or notify. + +**Difference in behaviour.** Port 4, section 6, and the same on ours (port +8): + +```text +Solid, in a setter: Object.defineProperty(s, "b", {value: 2, ...}) + -> {"storeB":2,"seenB":2,"keyRuns":2,"snapshotB":2} +ours: Object.defineProperty(store, "b", {value: 2, ...}) + -> {"storeB":2,"subscriberCalls":0,"snapshotB":"undefined"} + +Solid, in a setter: redefine a property that holds an object + -> {"childN":99,"snapshotChildN":99} +ours: redefine a property that holds an object -> {"childN":1} +``` + +**Proposal: adopt the principle.** Make the trap follow the steps of `set`: +`resumeScope()` first (this is the one-line remedy stage 1 proposed for +finding 66), then, after a successful definition, link or detach the child +from the property's new own descriptor, drop the cached bound method, set the +own-accessor flag of finding 1, and notify. Stay silent when nothing a +snapshot can show has changed (value, getter, setter, enumerability), so +`Object.freeze(store)`, which arrives as one definition per property, does +not notify once per field. + +This covers stage 1 findings 1, 45, 61, 66, 67 and 71. Our design handles +one case better than Solid's: a non-configurable definition, which Solid +applies and then throws on (finding 5). + +**Kind:** bug. + +**Cost:** `core/core.ts` only. Not breaking. Risk low to medium; the freeze +path needs its tests. + +### 8. Diagnostics: stable codes, once per object and key + +**What they do.** Every diagnostic has a code from one union +(`DiagnosticCode`, `src/core/dev.ts` lines 63 to 140), a kind and a severity. +The message starts with `[CODE]`. An event (lines 165 to 190) goes to two +places: `emitDiagnostic` (lines 966 to 1006) hands it to listeners and +captures, and `reportDiagnostic` (lines 1073 to 1081) prints it with +`console.warn` or `console.error`. `solid-js` ships a `diagnostics.json` +with 75 codes, each with a trigger, a repair text and a documentation URL. + +The codes that concern the store. Line numbers are in `src/store/store.ts` +unless a file is named. + +| Code | Severity | Reports | Where | What happens | +| ------------------------------- | -------- | --------------------------------------------------------------------------- | ----------------------------------------------- | ---------------------------------------------------------------------------------------- | +| `STORE_WRITE_OUTSIDE_SETTER` | warn | A `set`, `defineProperty` or `delete` on a store while its setter is closed | `warnWriteOutsideSetter`, 2068 to 2104 | The write is ignored in every build. The trap returns `true`, so strict code keeps going | +| `ASYNC_STORE_SETTER` | error | The setter callback returned a thenable | `devGuardStoreSetterResult`, 2565 to 2582 | Development throws, after the synchronous writes were applied. Later writes are ignored | +| `REACTIVE_WRITE_IN_OWNED_SCOPE` | error | `setStore` called inside a memo or a component body | `devGuardStoreSetterWrite`, 2541 to 2559 | Development throws. Production writes | +| `STORE_WRITE_THROUGH_LOADING` | warn | A write inside a child that is another store still loading | `devWriteThroughLoading`, 2110 to 2126 | Dropped. Derived stores only | +| `STRICT_READ_UNTRACKED` | warn | An untracked store read in a component body | `get` trap, 2231 to 2244 | Not a write | +| `UNTRACKED_READ_AFTER_AWAIT` | warn | A first read after an `await` in an async computation | `get` trap, 2211 to 2225 | Not a write | +| `IMMUTABLE_UPDATE_IN_STORE` | warn | A container replaced by a mostly equal copy | The attribution engine (catalogue entry only) | Performance advice | +| `UNSTABLE_LIST_IDENTITY` | warn | List rows recreated for equal items | The attribution engine (catalogue entry only) | Performance advice | +| `INVARIANT_VIOLATION` | error | An internal consistency check failed | `assertInvariant`, `src/core/dev.ts` 828 to 841 | Throws under the test flag, logs in development | + +The outside-setter warning is remembered per record and key in a `WeakMap` +of sets (lines 2059 and 2074 to 2078), so a loop does not flood the console. +The same memory hid the write after the `await` in port 5, because that key +had been warned about earlier. + +**What we do.** No diagnostics module and no development build. Errors are +ad hoc `Error`s with a package prefix (`core/core.ts:180-182` and `207`, +`snapshot/snapshot.ts:247-249`), and a subscriber's exception goes to +`console.error` (`core/core.ts:322-326`). + +**Difference in behaviour.** Port 5 in the development build and in +production: + +```text +dev: store.count = 5 -> {"storeCount":0,"rawCount":0} + [console.warn: [STORE_WRITE_OUTSIDE_SETTER] Writing store property "count" + outside its setter was ignored. ...] +prod: store.count = 5 -> {"storeCount":0,"rawCount":0} + +dev: setStore(async s => { s.count = 1; await 0; s.count = 2; }) + -> THROWS Error: [ASYNC_STORE_SETTER] ... +prod: -> no throw; after the await settled -> {"storeCount":1,"events":[]} +``` + +Our own two silent cases, ports 2 and 8: + +```text +store.opted.arrow() notifies -> {"count":3,"snapshotCount":3,"subscriberCalls":0} +sync notifications for one async method that writes three times -> 3 +sync notifications for batch(async () => ...) with three writes -> 3 +``` + +Solid has no diagnostic for an arrow-function method. Its write lands on the +original instance, which the store stopped reading at its first write, so it +is lost (port 2: `{"count":6,"seenDouble":12,"rawCount":2}`). + +**Proposal: adapt, small.** Take the shape and not the size: a `[CODE]` +prefix, one stable string code per diagnostic, once per object and key, a +reporter that exists only in the development build, and the codes listed in +the API reference. Leave out the event channel, owner paths and the catalogue +file until something reads them. Candidates, with the detector each needs: + +1. **`batch()` got a promise back** (`core/core.ts:299-306`). Exact, one + line, and the direct counterpart of `ASYNC_STORE_SETTER`. A warning, not a + throw: our later writes are not lost, only delivered one by one. +2. **A store method returned a promise** (`transactional`, + `core/core.ts:263-277`). The same detector, but an async method is a + normal thing to write here. I would document it and not warn. +3. **A write went around the proxy** (arrow-function and bound methods). + Nothing to copy from Solid. A possible detector for the development build: + when a function that is an own property of a class instance is called + through the store, compare the raw object's own data values before and + after with the node's version; a changed value under an unchanged version + is such a write. Exact for direct field writes, one pass over own keys per + call. Needs a spike. +4. **A write inside a getter** (stage 1 finding 39): a `set` while a getter + of the same node is being tracked. One check in the `set` trap. +5. **A subscriber that keeps writing** (finding 18): a depth counter in + `deliver`. + +**Kind:** diagnostics. + +**Cost:** one small module and its call sites in `core/core.ts`. Not +breaking. Depends on finding 9. + +### 9. How the development build is split from production + +**What they do.** One source, two compile-time flags, three builds: + +- `__DEV__` and `__OBSERVE__` are declared in `src/globals.d.ts` and replaced + with literals by `@rollup/plugin-replace` (`flags` in `rollup.config.js`). + A check is an ordinary `if (__DEV__)` at the call site, so it folds away. +- The outputs are `dist/dev.js` (checks and wiring), `dist/observe/` (wiring + only) and `dist/prod/` (neither). +- `package.json` selects one with export conditions: `development` and + `test` give the development build, `observe` gives observe, `default` gives + production. `solid-js` nests the same conditions under `browser`, `node`, + `worker` and `deno`. +- The `DEV` export is `undefined` outside the development build + (`src/index.ts` line 68). + +Verified: no file under `dist/prod` or `dist/observe` contains the string +`STORE_WRITE_OUTSIDE_SETTER`; plain `node` resolves production, `node +--conditions=development` the development build, `node --conditions=observe` +the observe build (port 5). So a runtime that sets no condition gets +production and no diagnostics, silently. + +**What we do.** One build per module format with no flag +(`tsdown.config.ts`), no `development` condition in `package.json`, and no +read of `NODE_ENV` anywhere in `src` (searched). + +**Proposal: adapt, and choose between two shapes.** + +- **A. Export conditions and a build-time flag**, as Solid does. Production + stays byte for byte what it is, so no size budget in `CONSTRAINTS.md` + moves. It costs a second build per format (four trees with ESM and CJS), + and the single shared runtime (`#store-runtime`) must hold within each + tier. Diagnostics are invisible wherever `development` is not set. +- **B. `process.env.NODE_ENV !== 'production'` guards in one build**, left to + the consumer's bundler to remove. One artifact, and diagnostics are on by + default in tests and scripts. The bytes stay for a consumer whose bundler + does not replace the expression, `process` must be guarded for a browser + without a bundler, and the size script must measure with the replacement + applied. + +I would take A while the diagnostics stay few, because it leaves the +production bundle and its budget alone. Stage 3 should spike it with tsdown +and check which of Vite, Next.js, Vitest, Bun and Node select `development`. +I verified Node only. + +**Kind:** diagnostics. + +**Cost:** `tsdown.config.ts`, `package.json` exports, the package checks and +the size script. Not breaking. Risk medium, in packaging. + +### 10. `snapshot` and `deep`: a data export, not a render value + +**What they do.** + +- `snapshot` (`src/store/store.ts` lines 2864 to 2867, through `snapshotWalk` + at 2885 to 2906 and `snapshotRecord` at 2909 to 2964) does not track. For a + subtree the store has never written it returns **the source object + itself**; for a record the store owns it returns a fresh copy. Nothing is + frozen and nothing is cached. A `seen` map keeps shared children shared and + makes cycles end. Accessors are copied as accessors (lines 2929 to 2932). +- `deep` (lines 2778 to 2857) is the tracking form. It subscribes to one + "deep witness" node per reachable record and returns a snapshot. Write + paths bump a witness only if one exists (lines 1211 to 1223). + +**What we do.** `snapshot()` returns a frozen object, cached by version +(`snapshot/snapshot.ts:241-244`), sharing unchanged subtrees with the +previous snapshot, and throws on a cycle (lines 246 to 250). + +**Difference in behaviour.** Port 7, port 3 section 9, and port 8: + +```text +Solid: before any write: snapshot(store) === raw -> true + after a write: two snapshots are the same object -> false + a snapshot is frozen -> [false,false] + writing to a snapshot changes the store -> {"touched":2,"untouched":88} + s.self = s, then snapshot(store) -> {"selfIsSnapshot":true,"name":"root"} +ours: snapshot(store) after store.self = store + -> THROWS Error: @codebelt/classy-store: circular reference detected in snapshot +``` + +**Proposal: reject the semantics, adapt the cycle handling.** Ours gives the +guarantees a render needs; theirs is a way to get plain data out. The one +thing worth taking is that a cycle is not an error. `createSnapshotRecursive` +could keep a map from target to the snapshot under construction, in place of +the `inProgress` set, hand that object out when the walk meets the same +target again, and freeze each object once its own fields are set. Version +propagation already copes with cycles (`ancestors()` keeps a visited set, +`core/ownership.ts:159-169`). Today `store.self = store` succeeds and +notifies, and every later `snapshot()` throws, which inside an adapter means +the subscriber throws (stage 1 finding 8). Not spiked. + +A note for the redesign of `ownership.ts`, **from reading, not a proposal**. +Solid has nothing like it. A record knows one parent (`u` in +`src/store/target.ts` line 95), used only to copy the path on a write. A +child's identity is a global map from raw object to record (`storeLookup`, +line 157), so the parent keeps pointing at the raw child and reads resolve it +to its current backing. Nothing is propagated upward: whoever observes a +subtree subscribes downward, record by record. So there are no owner counts, +no weak parent references, no suspend or resume, and one child under two keys +still reads and snapshots correctly (port 5, section 17). What we buy with +the upward walk is a cached snapshot in constant time and subtree +`subscribe`. Finding 72 of stage 1 says which parts of our walk can be seen +to matter. + +**Kind:** bug (cycles), API design (the rest). + +**Cost:** `snapshot/snapshot.ts`. Not breaking. Risk medium. + +### 11. `reconcile`: keeping identity when state is replaced wholesale + +**What they do.** `reconcile(value, key = "id")` (`src/store/index.ts` lines +110 to 115) is a setter transform. `reconcileState` +(`src/store/reconcile.ts` lines 46 to 88) and `applyAdopt` (lines 93 to 297) +adopt the incoming plain data as the new backing and notify only the nodes +whose value changed. For a list, the aligned prefix is walked by position; +from the first misalignment rows are matched by key (lines 156 to 185). +`descend` (lines 312 to 349) goes into a changed pair only where something +below is observed. Surviving rows keep their proxies. + +**What we do.** Nothing in the core. `withHistory` restores by top-level key: +an unchanged branch is left alone, a changed one is replaced by a deep clone +(`utils/history/history.ts:92-109`). + +**Difference in behaviour.** Port 7, section 20, and port 10: + +```text +Solid: reconcile a reordered, edited copy by id + -> {"order":"2,1,3","sameProxyForId1":true,"sameProxyForId2":true, + "editedValue":100,"rowEffectRuns":1} +ours, after undoing an edit to one row of three: + the untouched rows keep their snapshots -> [false,false] + the untouched row keeps its live proxy -> false +``` + +After one undo every row of the list is a new object, so every row component +renders again and anything holding a row proxy holds a detached one. + +**Proposal: adapt, inside the utilities.** A recursive apply that goes down +while both sides are containers of the same kind and writes only the leaves +that differ. Our snapshots already say which subtrees are unchanged, by +reference, so the same-position case needs no key function. Matching +reordered rows by key could follow. I did not read `persist.ts` or +`devtools.ts`; if they replace state the same way, they would share it. + +**Kind:** performance. + +**Cost:** `utils/history/history.ts`, possibly `persist.ts` and +`devtools.ts`. Not breaking. Risk medium. Can follow 1.0 unless a public +`reconcile` is wanted. + +### 12. Copy-on-write, and why it does not suit us + +**What they do.** The first write to a record clones it (`ensurePB`, +`src/store/store.ts` lines 705 to 749, and `cloneRaw`, lines 587 to 622), +along with its chain of ancestors. Until then the store reads the object it +was given. + +**What we do.** The object given to `createClassyStore` is the state. A write +lands on it (`core/core.ts:432`). + +**Difference in behaviour.** Port 5, section 11: + +```text +a write through the setter leaves the raw object alone + -> {"storeN":2,"rawN":1,"rawChildM":1,"snapshotIsRaw":false} +before any setter write the store reads the raw object itself + -> {"storeN":7,"snapshotIsRaw":true} +``` + +**Proposal: reject.** "State is a plain class wrapped in a proxy" is fixed by +the plan. The comparison is still useful for the Solid adapter's docs: a +Solid user will expect the object they passed in to stay untouched, and here +it is the store. + +**Kind:** docs. + +**Cost:** a paragraph in the Solid adapter's page. + +## Stage 1 findings with a counterpart in Solid 2's store + +"Verified" means a ported test below shows it. "Read" means it rests on the +source only. + +| Stage 1 finding | What Solid 2 does | Basis | +| --------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------ | +| 1. `Object.defineProperty` on a store is silent | Inside a setter it is an ordinary write. Outside it is ignored, with a development warning | Verified, port 4 | +| 2. A snapshot after one row costs time per row | No better: `snapshot` copies every owned record on every call and has no cache; `deep` walks every record | Verified, port 7 | +| 3. A getter over many rows is slow to recompute | The store does not memoize getters. A class getter is re-run on every write to its instance | Verified, port 2 | +| 5. A function in an array is a new wrapper per read | Functions are returned as they are | Verified, port 3 | +| 6. A class held in a store is a bound wrapper | The class itself comes back | Verified, port 3 | +| 7. `list.includes(raw)` misses | The same: `false` for the raw object, `true` for the proxy. No array method is instrumented | Verified, port 3 | +| 8. A store that refers to itself cannot be snapshotted | Works for writes, `snapshot` and `deep` | Verified, port 3 | +| 9. A class instance that is already a store is not connected | One record per raw object, across all stores. A write through one store reaches an effect reading through the other | Verified, port 3 | +| 10. Raw objects end up holding proxies | The `set` trap unwraps a store proxy before storing it (`store.ts` 2417 to 2420) | Verified, extra check | +| 11. A write through the raw object is invisible | Before the first setter write the raw object is the backing, so the write shows, untracked. After it the store reads its clone | Verified, port 5 | +| 12. A native `Set` or `Map` holds raw members | The same. Native collections are leaves | Verified, port 2 | +| 18. A sync subscriber that writes recurses | A setter called inside a computation throws `REACTIVE_WRITE_IN_OWNED_SCOPE` in development. Production performs the write | Verified, port 5 | +| 29. A delete that removes nothing counts as a write | No notification. A write of the value already held is silent too | Verified, port 4 | +| 30. A getter reading `Object.keys(this)` goes stale | Tracked through the `has` and `ownKeys` traps | Verified, port 4 | +| 31, 41. A snapshot getter sees no keys; `this` is a bare proxy | No tracking proxy. A snapshot is a copy with the same prototype and the accessor copied onto it | Verified, port 2 | +| 32. A getter reading a missing property recomputes on each read | Reading an absent key subscribes to that key | Verified, port 4 | +| 36. A getter misses some of what it reads | An own accessor tracks everything it reads. A prototype getter tracks nothing and goes stale over nested data | Verified, port 2 | +| 42. `constructor` through a store is a bound wrapper | A plain read answers the class | Verified, port 2 | +| 44. A redefined getter keeps the old result | Accessor-ness is read again when the key is written (`store.ts` 1162). A getter defined in a setter was tracked | Verified in part, port 4 | +| 45. `defineProperty` leaves the old child in place | The new object is read and snapshotted | Verified, port 4 | +| 46. Freezing a raw object behind the store makes reads throw | Reads keep working, because the proxy target is an empty shell. The frozen object becomes a leaf: a later write below it lands on the raw object, silently | Verified, port 1 | +| 47. A cached getter survives a prototype change | `setPrototypeOf` is refused (`store.ts` 2511). The wrappability verdict is cached per prototype for good | Read | +| 48. `Object.assign` with a `__proto__` key swaps the prototype | The `set` trap ignores `__proto__` (`store.ts` 2410), and an inherited `__proto__` or `prototype` is never served (2277 to 2284) | Read | +| 50. A descriptor read hands out the raw object | The same | Verified, port 4 | +| 51. `structuredClone(store)` throws | The same. `JSON.stringify` and spread work | Verified, port 4 | +| 61, 66 to 69, 72. Suspending and resuming detached subtrees | No counterpart. See the note in finding 10 | Read | +| 63. A typed-array store | A typed array is a leaf | Verified, extra check | + +Two rows are cheap to copy and not covered by a finding above: + +- **29.** Check `Object.hasOwn(_target, prop)` before deleting in the + `deleteProperty` trap (`core/core.ts:515-524`), and stay silent when the + key is not there. +- **48.** Solid refuses `__proto__` as a written key outright. Whether we + should is a question for the security report. + +## The eight API questions, from Solid 2's point of view + +1. **Should synchronous notification be the default for `subscribe()`?** + No. Solid 2 goes further the other way: a write is staged, and nothing + sees it until the flush, not even a plain read outside a computation (port + 7: 1 before `flush()`, 2 after). There is no synchronous subscription in + the store's public API. Batched by default, with `flush()` for imperative + code, is its position. Our Solid adapter subscribes synchronously and + lets Solid schedule (`frameworks/solid/solid.ts:29-36`), which fits: + synchronous delivery is a tool for adapter authors. +2. **Should writes outside a store method be allowed, warned about, or + grouped automatically? Does `batch()` belong in the API?** Not allowed: + ignored, with a development warning (finding 8). Grouping is automatic and + total: the setter is the transaction, and every setter before a flush + lands together. `@solidjs/signals` 2.0.0 exports no `batch` (checked); + `flush` is the only control, and it pushes the other way. For us that + reads as: `batch()` exists only because synchronous subscribers do. +3. **Should snapshot getters stay enumerable own accessors?** Solid keeps a + property where it was. An own accessor is copied as the same accessor, + with its own enumerability (`store.ts` 2929 to 2932); a prototype getter + stays on the prototype, because the copy is made with the source's + prototype (line 2918). It never turns an inherited getter into an own + property. It also does not memoize, which is why it has no need to. +4. **Can arrow-function methods and `#private` fields be made to work?** + Solid makes neither work and has no device for it. An arrow-function + method's write is lost (port 2). A method that touches a `#private` field + throws a `TypeError` when called through the store (port 9). A prototype + getter that reads one works, only because Solid runs it against the raw + object (finding 2). No position on a base class or a constructor that + returns the proxy. +5. **Should native `Map` and `Set` be reactive directly?** No. They are + leaves by a tag check, served raw; only the property that holds one is + tracked. The stated reason is that native methods check internal slots + and throw on a proxy. The package has no reactive collection of its own. +6. **Opt-in or opt-out for nested class instances?** Opt-out. Class + instances wrap; `markRaw`, freezing and being a platform object keep one + out (finding 4). +7. **Are entry points, export names and adapter names consistent?** Three + observations, none strong: + - `snapshot` means two things. Solid's is an unfrozen copy that shares + objects with the source; ours is frozen and cached. A Solid app that + uses our adapter can import both. + - Solid names a primitive that creates reactive state `create*` + (`createStore`, `createMemo`). `useClassyStore` returns an accessor, + which is what a Solid user expects to get, and `createClassyStore` is + taken by the core. + - A Solid user expects per-property updates from a store. Our adapter + hands out one accessor for the whole snapshot. This is reasoning, not + tested, and belongs to the adapters report. +8. **What development-only diagnostics would catch our silent failure + modes?** Finding 8 lists five with their detectors. Solid's lessons are + about form: a stable code in the message, once per object and key, in a + build of its own. It catches the write after an `await` because it + forbids every write outside the setter, which we cannot copy; and it does + not catch the arrow-function write at all. + +## Ported tests + +Every port prints what happened and never stops on a throw. Biome reformatted +the code blocks when this file was formatted, so they are longer here than the +scratch files they came from; the code is the same. The output blocks were +produced by running those scratch files on `825ba2d`, whose library source is +identical to `9ab9744`, where the work started. The helper the ports share: + +```js +// Shared by every port: run a case, print what happened, never stop on a throw. +const logs = []; +for (const level of ['warn', 'error']) { + const original = console[level]; + console[level] = (...args) => { + const first = String(args[0]).split('\n')[0]; + logs.push( + `console.${level}: ${first.length > 230 ? first.slice(0, 230) + '…' : first}`, + ); + }; + console[`_${level}`] = original; +} +export function show(label, fn) { + let out; + try { + const value = fn(); + out = typeof value === 'string' ? value : JSON.stringify(value); + } catch (error) { + out = `THROWS ${error?.constructor?.name}: ${String(error?.message).split('\n')[0].slice(0, 200)}`; + } + console.log(` ${label} -> ${out}`); + while (logs.length) console.log(` [${logs.shift()}]`); +} +export function title(text) { + console.log(`\n${text}`); +} +``` + +Solid ports were run with `node --conditions=development ` unless a +section says otherwise. Ours were run with `bun `. + +### Port 1: a frozen object held in a store; freezing through and behind it + +Solid: + +```js +import { + createStore, + snapshot, + createRoot, + createEffect, + flush, +} from '@solidjs/signals'; +import {show, title} from './helper.mjs'; + +title('1. A frozen object held in a store'); +const frozen = Object.freeze({nested: {n: 1}, list: [1, 2]}); +const [store, setStore] = createStore({config: frozen, live: {n: 1}}); +show( + 'store.config === frozen (kept by reference)', + () => store.config === frozen, +); +show('store.config.nested.n', () => store.config.nested.n); +show( + 'store.config.nested is the raw nested object', + () => store.config.nested === frozen.nested, +); +show( + 'store.live is a proxy', + () => store.live !== snapshot(store).live || 'same object', +); +let runs = 0; +createRoot(() => + createEffect( + () => store.config.nested.n, + () => void runs++, + ), +); +flush(); +show('write inside the frozen value, in a setter', () => { + setStore((s) => { + s.config.nested.n = 2; + }); + flush(); + return { + storeReads: store.config.nested.n, + rawReads: frozen.nested.n, + effectRuns: runs, + }; +}); +show('replace the frozen value', () => { + setStore((s) => { + s.config = Object.freeze({nested: {n: 9}}); + }); + flush(); + return {storeReads: store.config.nested.n, effectRuns: runs}; +}); + +title('1b. Freezing through the store, and behind it'); +const raw = {config: {nested: {n: 1}}}; +const [s2, setS2] = createStore(raw); +show('Object.freeze(store)', () => { + Object.freeze(s2); + return Object.isFrozen(s2); +}); +show('Object.preventExtensions(store)', () => { + Object.preventExtensions(s2); + return Object.isExtensible(s2); +}); +s2.config.nested; // hand out the proxy first, as our finding 46 does +show('freeze the raw child behind the store, then read below it', () => { + Object.freeze(raw.config); + return s2.config.nested.n; +}); +show('then write below it in a setter', () => { + setS2((s) => { + s.config.nested.n = 5; + }); + flush(); + return {storeReads: s2.config.nested.n, rawReads: raw.config.nested.n}; +}); +``` + +```text +$ node --conditions=development 01-frozen.solid.mjs +1. A frozen object held in a store + store.config === frozen (kept by reference) -> true + store.config.nested.n -> 1 + store.config.nested is the raw nested object -> true + store.live is a proxy -> true + write inside the frozen value, in a setter -> {"storeReads":2,"rawReads":2,"effectRuns":1} + replace the frozen value -> {"storeReads":9,"effectRuns":2} + +1b. Freezing through the store, and behind it + Object.freeze(store) -> THROWS TypeError: 'preventExtensions' on proxy: trap returned falsish + Object.preventExtensions(store) -> THROWS TypeError: 'preventExtensions' on proxy: trap returned falsish + freeze the raw child behind the store, then read below it -> 1 + then write below it in a setter -> {"storeReads":5,"rawReads":5} +``` + +Ours: + +```ts +import { + createClassyStore, + snapshot, + subscribe, +} from '/packages/classy-store/src/index.ts'; +import {show, title} from './helper.mjs'; + +title('1. A frozen object held in a store'); +const frozen = Object.freeze({nested: {n: 1}, list: [1, 2]}); +const store = createClassyStore({ + config: frozen as {nested: {n: number}}, + live: {n: 1}, +}); +show( + 'store.config === frozen (kept by reference)', + () => store.config === frozen, +); +show('store.config.nested.n', () => store.config.nested.n); +show( + 'store.config.nested is the raw nested object', + () => store.config.nested === frozen.nested, +); +let calls = 0; +subscribe(store, () => void calls++, {sync: true}); +show('write inside the frozen value', () => { + store.config.nested.n = 2; + return { + storeReads: store.config.nested.n, + rawReads: frozen.nested.n, + snapshotReads: snapshot(store).config.nested.n, + subscriberCalls: calls, + }; +}); + +title('1b. Freezing through the store, and behind it'); +const raw = {config: {nested: {n: 1}}}; +const s2 = createClassyStore(raw); +s2.config.nested; +show('freeze the raw child behind the store, then read below it', () => { + Object.freeze(raw.config); + return s2.config.nested.n; +}); +``` + +```text +$ bun 01-frozen.classy.ts +1. A frozen object held in a store + store.config === frozen (kept by reference) -> true + store.config.nested.n -> 1 + store.config.nested is the raw nested object -> true + write inside the frozen value -> {"storeReads":2,"rawReads":2,"snapshotReads":2,"subscriberCalls":0} + +1b. Freezing through the store, and behind it + freeze the raw child behind the store, then read below it -> THROWS TypeError: Proxy handler's 'get' result of a non-configurable and non-writable property should be the same value as the target's property +``` + +### Port 2: a class instance held in a store; getters on a class + +Solid: + +```js +import { + createStore, + snapshot, + createRoot, + createEffect, + createMemo, + flush, + isWrappable, +} from '@solidjs/signals'; +import {show, title} from './helper.mjs'; + +class Counter { + count = 1; + items = [{price: 2}, {price: 3}]; + static label = 'counter'; + get double() { + Counter.doubleRuns++; + return this.count * 2; + } + get total() { + Counter.totalRuns++; + return this.items.reduce((sum, item) => sum + item.price, 0); + } + increment() { + this.count++; + } + arrow = () => { + this.count++; + }; +} +Counter.doubleRuns = 0; +Counter.totalRuns = 0; + +title('2. A class instance held in a store, with no opt-in'); +const raw = new Counter(); +const [store, setStore] = createStore({ + inner: raw, + when: new Date(0), + map: new Map([['k', 1]]), +}); +show('isWrappable(new Counter())', () => isWrappable(new Counter())); +show('isWrappable(new Date()), isWrappable(new Map())', () => [ + isWrappable(new Date()), + isWrappable(new Map()), +]); +show('store.inner is a proxy, not the raw instance', () => store.inner !== raw); +show('store.inner instanceof Counter', () => store.inner instanceof Counter); +show('store.inner.constructor === Counter, and its static', () => [ + store.inner.constructor === Counter, + store.inner.constructor.label, +]); +show('store.when and store.map are the raw objects', () => [ + store.when instanceof Date, + store.map.get('k'), +]); + +title('5. A getter on a class used as store state'); +let seenDouble, seenTotal; +Counter.doubleRuns = Counter.totalRuns = 0; +createRoot(() => { + createEffect( + () => store.inner.double, + (v) => { + seenDouble = v; + }, + ); + createEffect( + () => store.inner.total, + (v) => { + seenTotal = v; + }, + ); +}); +flush(); +show('first effect run', () => ({ + seenDouble, + seenTotal, + doubleRuns: Counter.doubleRuns, + totalRuns: Counter.totalRuns, +})); +Counter.doubleRuns = Counter.totalRuns = 0; +show('two untracked reads of store.inner.double', () => { + store.inner.double; + store.inner.double; + return {doubleRuns: Counter.doubleRuns}; +}); +Counter.doubleRuns = Counter.totalRuns = 0; +show('write the field the getter reads: s.inner.count = 5', () => { + setStore((s) => { + s.inner.count = 5; + }); + flush(); + return { + seenDouble, + doubleRuns: Counter.doubleRuns, + totalRuns: Counter.totalRuns, + }; +}); +Counter.doubleRuns = Counter.totalRuns = 0; +show('write a nested row the getter reads: s.inner.items[0].price = 10', () => { + setStore((s) => { + s.inner.items[0].price = 10; + }); + flush(); + return { + seenTotal, + untrackedRead: store.inner.total, + totalRuns: Counter.totalRuns, + }; +}); +show('call a prototype method on the draft: s.inner.increment()', () => { + setStore((s) => { + s.inner.increment(); + }); + flush(); + return {count: store.inner.count, seenDouble, rawCount: raw.count}; +}); +show('call an arrow-function method on the draft: s.inner.arrow()', () => { + setStore((s) => { + s.inner.arrow(); + }); + flush(); + return {count: store.inner.count, seenDouble, rawCount: raw.count}; +}); +show( + 'call a prototype method outside a setter: store.inner.increment()', + () => { + store.inner.increment(); + flush(); + return {count: store.inner.count, rawCount: raw.count}; + }, +); + +title('5b. The same getters as own accessors on an object literal'); +let ownRuns = 0; +const [lit, setLit] = createStore({ + items: [{price: 2}, {price: 3}], + get total() { + ownRuns++; + return this.items.reduce((sum, item) => sum + item.price, 0); + }, +}); +let seenLit; +createRoot(() => + createEffect( + () => lit.total, + (v) => { + seenLit = v; + }, + ), +); +flush(); +ownRuns = 0; +show('write a nested row: s.items[0].price = 10', () => { + setLit((s) => { + s.items[0].price = 10; + }); + flush(); + return {seenLit, ownRuns}; +}); +ownRuns = 0; +show('write an unrelated key, then read the getter in a memo twice', () => { + const memo = createRoot(() => createMemo(() => lit.total)); + memo(); + memo(); + return {ownRuns}; +}); +show('snapshot(store) keeps the getter as an accessor', () => { + const d = Object.getOwnPropertyDescriptor(snapshot(lit), 'total'); + return { + hasGetter: typeof d.get === 'function', + frozen: Object.isFrozen(snapshot(lit)), + }; +}); +``` + +```text +$ node --conditions=development 02-class.solid.mjs +2. A class instance held in a store, with no opt-in + isWrappable(new Counter()) -> true + isWrappable(new Date()), isWrappable(new Map()) -> [false,false] + store.inner is a proxy, not the raw instance -> true + store.inner instanceof Counter -> true + store.inner.constructor === Counter, and its static -> [true,"counter"] + store.when and store.map are the raw objects -> [true,1] + +5. A getter on a class used as store state + first effect run -> {"seenDouble":2,"seenTotal":5,"doubleRuns":2,"totalRuns":2} + two untracked reads of store.inner.double -> {"doubleRuns":0} + write the field the getter reads: s.inner.count = 5 -> {"seenDouble":10,"doubleRuns":1,"totalRuns":1} + write a nested row the getter reads: s.inner.items[0].price = 10 -> {"seenTotal":5,"untrackedRead":5,"totalRuns":0} + call a prototype method on the draft: s.inner.increment() -> {"count":6,"seenDouble":12,"rawCount":1} + call an arrow-function method on the draft: s.inner.arrow() -> {"count":6,"seenDouble":12,"rawCount":2} + call a prototype method outside a setter: store.inner.increment() -> {"count":6,"rawCount":2} + [console.warn: [STORE_WRITE_OUTSIDE_SETTER] Writing store property "count" outside its setter was ignored. Stores are read-only outside the setter's draft: use `setStore(s => { s.count = value })`.] + +5b. The same getters as own accessors on an object literal + write a nested row: s.items[0].price = 10 -> {"seenLit":13,"ownRuns":1} + write an unrelated key, then read the getter in a memo twice -> {"ownRuns":1} + snapshot(store) keeps the getter as an accessor -> {"hasGetter":true,"frozen":false} +``` + +Ours: + +```ts +import { + createClassyStore, + snapshot, + subscribe, + PROXYABLE, +} from '/packages/classy-store/src/index.ts'; +import {show, title} from './helper.mjs'; + +class Counter { + count = 1; + items = [{price: 2}, {price: 3}]; + static label = 'counter'; + static doubleRuns = 0; + static totalRuns = 0; + get double() { + Counter.doubleRuns++; + return this.count * 2; + } + get total() { + Counter.totalRuns++; + return this.items.reduce((sum, item) => sum + item.price, 0); + } + increment() { + this.count++; + } + arrow = () => { + this.count++; + }; +} +class Opted extends Counter { + static [PROXYABLE] = true; +} + +title('2. A class instance held in a store, with no opt-in'); +const raw = new Counter(); +const store = createClassyStore({inner: raw, opted: new Opted()}); +let calls = 0; +subscribe(store, () => void calls++, {sync: true}); +show('store.inner is a proxy, not the raw instance', () => store.inner !== raw); +show( + 'store.opted is a proxy (PROXYABLE)', + () => store.opted !== snapshot(store).opted, +); +show('store.opted.constructor === Opted, and its static', () => [ + store.opted.constructor === Opted, + (store.opted.constructor as typeof Opted).label, +]); +show('store.inner.increment() notifies', () => { + store.inner.increment(); + return {count: store.inner.count, subscriberCalls: calls}; +}); +calls = 0; +show('store.opted.increment() notifies', () => { + store.opted.increment(); + return {count: store.opted.count, subscriberCalls: calls}; +}); +calls = 0; +show('store.opted.arrow() notifies', () => { + store.opted.arrow(); + return { + count: store.opted.count, + snapshotCount: snapshot(store).opted.count, + subscriberCalls: calls, + }; +}); + +title('5. A getter on a class used as store state'); +const root = createClassyStore(new Counter()); +Counter.doubleRuns = Counter.totalRuns = 0; +show('two reads of root.double', () => { + root.double; + root.double; + return {doubleRuns: Counter.doubleRuns}; +}); +Counter.totalRuns = 0; +show('write a nested row the getter reads', () => { + root.total; + root.items[0].price = 10; + return {total: root.total, again: root.total, totalRuns: Counter.totalRuns}; +}); +``` + +```text +$ bun 02-class.classy.ts +2. A class instance held in a store, with no opt-in + store.inner is a proxy, not the raw instance -> false + store.opted is a proxy (PROXYABLE) -> true + store.opted.constructor === Opted, and its static -> [false,null] + store.inner.increment() notifies -> {"count":2,"subscriberCalls":0} + store.opted.increment() notifies -> {"count":2,"subscriberCalls":1} + store.opted.arrow() notifies -> {"count":3,"snapshotCount":3,"subscriberCalls":0} + +5. A getter on a class used as store state + two reads of root.double -> {"doubleRuns":1} + write a nested row the getter reads -> {"total":13,"again":13,"totalRuns":2} +``` + +### Port 3: function identity, `includes(raw)`, shared objects, cycles + +Solid: + +```js +import { + createStore, + snapshot, + deep, + createRoot, + createEffect, + flush, +} from '@solidjs/signals'; +import {show, title} from './helper.mjs'; + +title('3. A function held in an array, read twice; a class held in a store'); +class Model { + static label = 'model'; + constructor(name) { + this.name = name; + } +} +const first = () => 1; +const second = () => 2; +const [store, setStore] = createStore({ + callbacks: [first, second], + Model, + handler: first, +}); +show( + 'store.callbacks[0] === store.callbacks[0]', + () => store.callbacks[0] === store.callbacks[0], +); +show('store.callbacks[0] === first', () => store.callbacks[0] === first); +show('store.callbacks.indexOf(first)', () => store.callbacks.indexOf(first)); +show('remove the first callback by indexOf, in a setter', () => { + setStore((s) => { + s.callbacks.splice(s.callbacks.indexOf(first), 1); + }); + flush(); + return store.callbacks.length === 1 && store.callbacks[0] === second + ? 'second is left' + : 'wrong one removed'; +}); +show('store.Model === Model, store.Model.label', () => [ + store.Model === Model, + store.Model.label, +]); +show( + 'new store.Model("x") instanceof store.Model', + () => new store.Model('x') instanceof store.Model, +); +show('store.handler === store.handler', () => store.handler === store.handler); +show( + 'a prototype method read twice is the same function', + () => + store.callbacks.push === store.callbacks.push && + store.callbacks.push === Array.prototype.push, +); + +title('4. list.includes(raw)'); +const row = {id: 1}; +const other = {id: 2}; +const [rows, setRows] = createStore({list: [row, other]}); +show( + 'rows.list[0] === row (the list hands out proxies)', + () => rows.list[0] === row, +); +show('rows.list.includes(row)', () => rows.list.includes(row)); +show('rows.list.indexOf(row), lastIndexOf(other)', () => [ + rows.list.indexOf(row), + rows.list.lastIndexOf(other), +]); +show('rows.list.includes(rows.list[0])', () => + rows.list.includes(rows.list[0]), +); +show('rows.list.indexOf(rows.list[1])', () => rows.list.indexOf(rows.list[1])); +show('inside a setter: s.list.includes(row), s.list.indexOf(s.list[1])', () => { + let out; + setRows((s) => { + out = [s.list.includes(row), s.list.indexOf(s.list[1])]; + }); + return out; +}); +show('after a write to the row: rows.list.includes(row)', () => { + setRows((s) => { + s.list[0].id = 10; + }); + flush(); + return { + includesRaw: rows.list.includes(row), + rawId: row.id, + storeId: rows.list[0].id, + }; +}); + +title('16. One raw object in two places and in two stores'); +const shared = {n: 1}; +const [a] = createStore({x: shared, y: shared}); +const [b, setB] = createStore({z: shared}); +show('a.x === a.y', () => a.x === a.y); +show( + 'a.x === b.z (one proxy per raw object, across stores)', + () => a.x === b.z, +); +show( + 'createStore(raw)[0] === createStore(raw)[0]', + () => createStore(shared)[0] === createStore(shared)[0], +); +let seen; +createRoot(() => + createEffect( + () => a.x.n, + (v) => { + seen = v; + }, + ), +); +flush(); +show('write through store b, read through store a', () => { + setB((s) => { + s.z.n = 2; + }); + flush(); + return {aReads: a.x.n, bReads: b.z.n, effectOnASaw: seen, raw: shared.n}; +}); + +title('9. A self-referencing object'); +const [cyc, setCyc] = createStore({name: 'root', child: {n: 1}}); +show('s.self = s in a setter', () => { + setCyc((s) => { + s.self = s; + }); + flush(); + return cyc.self === cyc; +}); +show('snapshot(store)', () => { + const snap = snapshot(cyc); + return {selfIsSnapshot: snap.self === snap, name: snap.self.self.name}; +}); +show('deep(store) inside an effect', () => { + let out; + createRoot(() => + createEffect( + () => deep(cyc), + (v) => { + out = v.self === v; + }, + ), + ); + flush(); + return out; +}); +show('a raw cycle given to createStore', () => { + const node = {n: 1}; + node.self = node; + const [c] = createStore(node); + return [ + c.self === c, + c.self.self.n, + snapshot(c).self === snapshot(c).self.self, + ]; +}); +``` + +```text +$ node --conditions=development 03-identity.solid.mjs +3. A function held in an array, read twice; a class held in a store + store.callbacks[0] === store.callbacks[0] -> true + store.callbacks[0] === first -> true + store.callbacks.indexOf(first) -> 0 + remove the first callback by indexOf, in a setter -> second is left + store.Model === Model, store.Model.label -> [true,"model"] + new store.Model("x") instanceof store.Model -> true + store.handler === store.handler -> true + a prototype method read twice is the same function -> true + +4. list.includes(raw) + rows.list[0] === row (the list hands out proxies) -> false + rows.list.includes(row) -> false + rows.list.indexOf(row), lastIndexOf(other) -> [-1,-1] + rows.list.includes(rows.list[0]) -> true + rows.list.indexOf(rows.list[1]) -> 1 + inside a setter: s.list.includes(row), s.list.indexOf(s.list[1]) -> [false,1] + after a write to the row: rows.list.includes(row) -> {"includesRaw":false,"rawId":1,"storeId":10} + +16. One raw object in two places and in two stores + a.x === a.y -> true + a.x === b.z (one proxy per raw object, across stores) -> true + createStore(raw)[0] === createStore(raw)[0] -> true + write through store b, read through store a -> {"aReads":2,"bReads":2,"effectOnASaw":2,"raw":1} + +9. A self-referencing object + s.self = s in a setter -> true + snapshot(store) -> {"selfIsSnapshot":true,"name":"root"} + deep(store) inside an effect -> true + a raw cycle given to createStore -> [true,1,true] +``` + +### Port 4: `defineProperty`, descriptors, `in` and `Object.keys`, empty writes + +Solid: + +```js +import { + createStore, + snapshot, + createRoot, + createEffect, + createMemo, + flush, + untrack, +} from '@solidjs/signals'; +import {show, title} from './helper.mjs'; + +title('6. Object.defineProperty through the proxy'); +const [store, setStore] = createStore({a: 1, child: {n: 1}}); +let seenB = 'never ran', + keyRuns = 0; +createRoot(() => { + createEffect( + () => store.b, + (v) => { + seenB = v; + }, + ); + createEffect( + () => Object.keys(store).join(), + () => void keyRuns++, + ); +}); +flush(); +show( + 'outside a setter: Object.defineProperty(store, "b", {value: 2, ...})', + () => { + const result = Reflect.defineProperty(store, 'b', { + value: 2, + writable: true, + enumerable: true, + configurable: true, + }); + flush(); + return { + trapReturned: result, + storeB: store.b, + seenB, + keys: Object.keys(store), + }; + }, +); +show('inside a setter: Object.defineProperty(s, "b", {value: 2, ...})', () => { + setStore((s) => { + Object.defineProperty(s, 'b', { + value: 2, + writable: true, + enumerable: true, + configurable: true, + }); + }); + flush(); + return {storeB: store.b, seenB, keyRuns, snapshotB: snapshot(store).b}; +}); +show('inside a setter: redefine a property that holds an object', () => { + const other = {n: 99}; + setStore((s) => { + Object.defineProperty(s, 'child', { + value: other, + writable: true, + enumerable: true, + configurable: true, + }); + }); + flush(); + return {childN: store.child.n, snapshotChildN: snapshot(store).child.n}; +}); +show( + 'inside a setter: define a non-writable, non-configurable property, then read it', + () => { + setStore((s) => { + Object.defineProperty(s, 'locked', { + value: {n: 1}, + writable: false, + enumerable: true, + configurable: false, + }); + }); + flush(); + const d = Object.getOwnPropertyDescriptor(store, 'locked'); + return { + lockedN: store.locked.n, + isProxy: store.locked !== d.value, + reportedConfigurable: d.configurable, + reportedWritable: d.writable, + }; + }, +); +show('then assign to it in a setter', () => { + setStore((s) => { + s.locked = {n: 2}; + }); + flush(); + return store.locked.n; +}); +show('inside a setter: define a getter', () => { + setStore((s) => { + Object.defineProperty(s, 'twice', { + get() { + return this.a * 2; + }, + enumerable: true, + configurable: true, + }); + }); + flush(); + let seen; + createRoot(() => + createEffect( + () => store.twice, + (v) => { + seen = v; + }, + ), + ); + flush(); + setStore((s) => { + s.a = 5; + }); + flush(); + return {twice: store.twice, effectSaw: seen}; +}); + +title('15. What a descriptor read hands out'); +show( + 'Object.getOwnPropertyDescriptor(store, "child").value is the proxy', + () => { + const d = Object.getOwnPropertyDescriptor(store, 'child'); + return {isStoreChild: d.value === store.child, isObject: typeof d.value}; + }, +); +show('structuredClone(store)', () => structuredClone(store).a); +show('JSON.stringify(store)', () => JSON.stringify(store)); +show('{...store} and Object.entries(store).length', () => [ + Object.keys({...store}).join(), + Object.entries(store).length, +]); + +title( + "7. 'key' in store and Object.keys(store) inside a computation, then a key is added", +); +const [bag, setBag] = createStore({a: 1, b: 2}); +let hasRuns = 0, + keysRuns = 0, + hasC, + keys, + forInKeys; +createRoot(() => { + createEffect( + () => 'c' in bag, + (v) => { + hasRuns++; + hasC = v; + }, + ); + createEffect( + () => Object.keys(bag), + (v) => { + keysRuns++; + keys = v.join(); + }, + ); + createEffect( + () => { + const out = []; + for (const k in bag) out.push(k); + return out.join(); + }, + (v) => { + forInKeys = v; + }, + ); +}); +flush(); +show('first run', () => ({hasC, keys, forInKeys, hasRuns, keysRuns})); +show('change a value only: s.a = 10', () => { + setBag((s) => { + s.a = 10; + }); + flush(); + return {hasRuns, keysRuns}; +}); +show('add another key: s.d = 4', () => { + setBag((s) => { + s.d = 4; + }); + flush(); + return {hasC, keys, hasRuns, keysRuns}; +}); +show('add the key: s.c = 3', () => { + setBag((s) => { + s.c = 3; + }); + flush(); + return {hasC, keys, forInKeys, hasRuns, keysRuns}; +}); +show('delete the key: delete s.c', () => { + setBag((s) => { + delete s.c; + }); + flush(); + return {hasC, keys, hasRuns, keysRuns}; +}); + +title( + '12. A delete that removes nothing; a write of the value a field already holds', +); +let anyRuns = 0; +createRoot(() => + createEffect( + () => [bag.a, Object.keys(bag).length, 'missing' in bag, bag.missing], + () => void anyRuns++, + ), +); +flush(); +anyRuns = 0; +show('delete s.missing', () => { + setBag((s) => { + delete s.missing; + }); + flush(); + return {effectRuns: anyRuns}; +}); +show('s.a = s.a', () => { + setBag((s) => { + s.a = untrack(() => bag.a); + }); + flush(); + return {effectRuns: anyRuns}; +}); + +title('12b. Own getter that reads its own keys'); +const [dict, setDict] = createStore({ + a: 1, + b: 2, + get count() { + return Object.keys(this).length; + }, + get hasB() { + return 'b' in this; + }, +}); +let seenCount, seenHasB; +createRoot(() => { + createEffect( + () => dict.count, + (v) => { + seenCount = v; + }, + ); + createEffect( + () => dict.hasB, + (v) => { + seenHasB = v; + }, + ); +}); +flush(); +show('first run', () => ({seenCount, seenHasB})); +show('delete s.b', () => { + setDict((s) => { + delete s.b; + }); + flush(); + return {seenCount, seenHasB, snapshotCount: snapshot(dict).count}; +}); +``` + +```text +$ node --conditions=development 04-traps.solid.mjs +6. Object.defineProperty through the proxy + outside a setter: Object.defineProperty(store, "b", {value: 2, ...}) -> {"trapReturned":true,"keys":["a","child"]} + [console.warn: [STORE_WRITE_OUTSIDE_SETTER] Writing store property "b" outside its setter was ignored. Stores are read-only outside the setter's draft: use `setStore(s => { s.b = value })`.] + inside a setter: Object.defineProperty(s, "b", {value: 2, ...}) -> {"storeB":2,"seenB":2,"keyRuns":2,"snapshotB":2} + inside a setter: redefine a property that holds an object -> {"childN":99,"snapshotChildN":99} + inside a setter: define a non-writable, non-configurable property, then read it -> THROWS TypeError: 'defineProperty' on proxy: trap returned truish for defining non-configurable property 'locked' which is either non-existent or configurable in the proxy target + then assign to it in a setter -> THROWS TypeError: Cannot assign to read only property 'locked' of object '#' + inside a setter: define a getter -> {"twice":10,"effectSaw":10} + +15. What a descriptor read hands out + Object.getOwnPropertyDescriptor(store, "child").value is the proxy -> {"isStoreChild":false,"isObject":"object"} + structuredClone(store) -> THROWS DOMException: # could not be cloned. + JSON.stringify(store) -> {"a":5,"child":{"n":99},"b":2,"locked":{"n":1},"twice":10} + {...store} and Object.entries(store).length -> ["a,child,b,locked,twice",5] + +7. 'key' in store and Object.keys(store) inside a computation, then a key is added + first run -> {"hasC":false,"keys":"a,b","forInKeys":"a,b","hasRuns":1,"keysRuns":1} + change a value only: s.a = 10 -> {"hasRuns":1,"keysRuns":1} + add another key: s.d = 4 -> {"hasC":false,"keys":"a,b,d","hasRuns":1,"keysRuns":2} + add the key: s.c = 3 -> {"hasC":true,"keys":"a,b,d,c","forInKeys":"a,b,d,c","hasRuns":2,"keysRuns":3} + delete the key: delete s.c -> {"hasC":false,"keys":"a,b,d","hasRuns":3,"keysRuns":4} + +12. A delete that removes nothing; a write of the value a field already holds + delete s.missing -> {"effectRuns":0} + s.a = s.a -> {"effectRuns":0} + +12b. Own getter that reads its own keys + first run -> {"seenCount":4,"seenHasB":true} + delete s.b -> {"seenCount":3,"seenHasB":false,"snapshotCount":3} +``` + +### Port 5: writes outside a setter in three builds; the raw object; a shared child + +Solid: + +```js +import { + createStore, + snapshot, + createRoot, + createEffect, + createMemo, + flush, + DEV, + OBSERVE, +} from '@solidjs/signals'; +import {show, title} from './helper.mjs'; + +title('8. A write outside any setter'); +show('which build is this', () => ({ + DEV: DEV !== undefined, + OBSERVE: OBSERVE !== undefined, +})); +const events = []; +const stop = OBSERVE?.diagnostics.subscribe((event) => + events.push(`${event.code}/${event.severity}/${JSON.stringify(event.data)}`), +); +const raw = {count: 0, list: [1], user: {name: 'a'}}; +const [store, setStore] = createStore(raw); +show('store.count = 5', () => { + store.count = 5; + return {storeCount: store.count, rawCount: raw.count}; +}); +show('store.count = 6 again (same key)', () => { + store.count = 6; + return store.count; +}); +show('store.list.push(2)', () => { + const length = store.list.push(2); + return {returned: length, storeLength: store.list.length}; +}); +show('delete store.user', () => { + const ok = delete store.user; + return {deleteReturned: ok, stillThere: 'user' in store}; +}); +show('"use strict" assignment does not throw', () => { + 'use strict'; + store.count = 7; + return 'no throw'; +}); +show('structured events on the diagnostics channel', () => events.splice(0)); + +title('8b. A setter that is async, and a write after an await'); +show('setStore(async s => { s.count = 1; await 0; s.count = 2; })', () => { + setStore(async (s) => { + s.count = 1; + await 0; + s.count = 2; + }); + return 'no throw'; +}); +await new Promise((resolve) => setTimeout(resolve, 5)); +show('after the await settled', () => ({ + storeCount: store.count, + events: events.splice(0), +})); +show('a helper that keeps the draft and writes later', () => { + let kept; + setStore((s) => { + kept = s; + }); + kept.count = 99; + return { + storeCount: store.count, + draftIsStore: kept === store, + events: events.splice(0), + }; +}); + +title('8c. A setter inside a computation'); +show('setStore inside createMemo', () => { + createRoot(() => { + const memo = createMemo(() => { + setStore((s) => { + s.count = 3; + }); + return 1; + }); + memo(); + }); + return {storeCount: store.count, events: events.splice(0)}; +}); + +title('11. The raw object behind the store'); +const source = {n: 1, child: {m: 1}}; +const [owned, setOwned] = createStore(source); +let seen; +createRoot(() => + createEffect( + () => owned.n, + (v) => { + seen = v; + }, + ), +); +flush(); +show('a write through the setter leaves the raw object alone', () => { + setOwned((s) => { + s.n = 2; + s.child.m = 2; + }); + flush(); + return { + storeN: owned.n, + rawN: source.n, + rawChildM: source.child.m, + snapshotIsRaw: snapshot(owned) === source, + }; +}); +show('a write to the raw object after the store took its copy', () => { + source.n = 50; + flush(); + return {storeN: owned.n, effectSaw: seen}; +}); +const fresh = {n: 1, child: {m: 1}}; +const [unwritten] = createStore(fresh); +show('before any setter write the store reads the raw object itself', () => { + fresh.n = 7; + return {storeN: unwritten.n, snapshotIsRaw: snapshot(unwritten) === fresh}; +}); + +title('17. One child under two keys, written through one of them'); +const shared = {n: 1}; +const [two, setTwo] = createStore({x: shared, y: shared, list: [shared]}); +show('write s.x.n = 2', () => { + setTwo((s) => { + s.x.n = 2; + }); + flush(); + const snap = snapshot(two); + return { + x: two.x.n, + y: two.y.n, + inList: two.list[0].n, + snapX: snap.x.n, + snapY: snap.y.n, + snapList: snap.list[0].n, + snapShares: snap.x === snap.y, + }; +}); +stop?.(); +``` + +Development build: + +```text +$ node --conditions=development 05-diagnostics.solid.mjs +8. A write outside any setter + which build is this -> {"DEV":true,"OBSERVE":true} + store.count = 5 -> {"storeCount":0,"rawCount":0} + [console.warn: [STORE_WRITE_OUTSIDE_SETTER] Writing store property "count" outside its setter was ignored. Stores are read-only outside the setter's draft: use `setStore(s => { s.count = value })`.] + store.count = 6 again (same key) -> 0 + store.list.push(2) -> {"returned":2,"storeLength":1} + [console.warn: [STORE_WRITE_OUTSIDE_SETTER] Writing store property "1" outside its setter was ignored. Stores are read-only outside the setter's draft: use `setStore(s => { s[1] = value })`.] + [console.warn: [STORE_WRITE_OUTSIDE_SETTER] Writing store property "length" outside its setter was ignored. Stores are read-only outside the setter's draft: use `setStore(s => { s.length = value })`.] + delete store.user -> {"deleteReturned":true,"stillThere":true} + [console.warn: [STORE_WRITE_OUTSIDE_SETTER] Deleting store property "user" outside its setter was ignored. Stores are read-only outside the setter's draft: use `setStore(s => { delete s.user })`.] + "use strict" assignment does not throw -> no throw + structured events on the diagnostics channel -> ["STORE_WRITE_OUTSIDE_SETTER/warn/{\"operation\":\"set\",\"property\":\"count\"}","STORE_WRITE_OUTSIDE_SETTER/warn/{\"operation\":\"set\",\"property\":\"1\"}","STORE_WRITE_OUTSIDE_SETTER/warn/{\"operation\":\"set\",\"property\":\"length\"}","STORE_WRITE_OUTSIDE_SETTER/warn/{\"operation\":\"deleteProperty\",\"property\":\"user\"}"] + +8b. A setter that is async, and a write after an await + setStore(async s => { s.count = 1; await 0; s.count = 2; }) -> THROWS Error: [ASYNC_STORE_SETTER] Store setter callback returned a Promise. A store setter is a synchronous transaction: the draft closes when the callback returns, so writes after an `await` are lost. Move the aw + after the await settled -> {"storeCount":1,"events":["ASYNC_STORE_SETTER/error/{\"operation\":\"setStore\"}"]} + a helper that keeps the draft and writes later -> {"storeCount":1,"draftIsStore":true,"events":[]} + +8c. A setter inside a computation + setStore inside createMemo -> THROWS StatusError: [REACTIVE_WRITE_IN_OWNED_SCOPE] Writing to reactive state inside an owned scope (component, computation) is not allowed. Move the write outside or set the `ownedWrite` option if this is intentional. ( + +11. The raw object behind the store + a write through the setter leaves the raw object alone -> {"storeN":2,"rawN":1,"rawChildM":1,"snapshotIsRaw":false} + a write to the raw object after the store took its copy -> {"storeN":2,"effectSaw":2} + before any setter write the store reads the raw object itself -> {"storeN":7,"snapshotIsRaw":true} + +17. One child under two keys, written through one of them + write s.x.n = 2 -> {"x":2,"y":2,"inList":2,"snapX":2,"snapY":2,"snapList":2,"snapShares":true} +``` + +Production build (plain `node`), the first sections: + +```text +$ node 05-diagnostics.solid.mjs | sed -n 1,20p +8. A write outside any setter + which build is this -> {"DEV":false,"OBSERVE":false} + store.count = 5 -> {"storeCount":0,"rawCount":0} + store.count = 6 again (same key) -> 0 + store.list.push(2) -> {"returned":2,"storeLength":1} + delete store.user -> {"deleteReturned":true,"stillThere":true} + "use strict" assignment does not throw -> no throw + structured events on the diagnostics channel -> [] + +8b. A setter that is async, and a write after an await + setStore(async s => { s.count = 1; await 0; s.count = 2; }) -> no throw + after the await settled -> {"storeCount":1,"events":[]} + a helper that keeps the draft and writes later -> {"storeCount":1,"draftIsStore":true,"events":[]} + +8c. A setter inside a computation + setStore inside createMemo -> {"storeCount":1,"events":[]} + +11. The raw object behind the store + a write through the setter leaves the raw object alone -> {"storeN":2,"rawN":1,"rawChildM":1,"snapshotIsRaw":false} +``` + +The observe build (`node --conditions=observe`) printed the same as +production, with `{"DEV":false,"OBSERVE":true}` on the first line. + +### Port 6: read cost, and the spike + +Not the repository's benchmark. The two "classy-store" variants are a copy of +`core/core.ts`, `core/ownership.ts`, `core/core.types.ts`, +`utils/internal/internal.ts` and `types.ts` in the scratch folder, bundled +with `bun build`, once unchanged and once with this diff: + +```diff +--- a/core/core.ts ++++ b/core/core.ts +@@ -7,6 +7,31 @@ + import type {DepEntry} from './core.types'; + import {StoreInternal} from './ownership'; + ++ ++// SPIKE: per-prototype answer to "which descriptor does this inherited key have". ++const hasOwn = Object.prototype.hasOwnProperty; ++const inheritedCache = new WeakMap< ++ object, ++ Map ++>(); ++function inheritedDescriptor( ++ proto: object | null, ++ prop: string | symbol, ++): PropertyDescriptor | undefined { ++ if (proto === null) return undefined; ++ let table = inheritedCache.get(proto); ++ if (!table) { ++ table = new Map(); ++ inheritedCache.set(proto, table); ++ } ++ let found = table.get(prop); ++ if (found === undefined) { ++ found = findPropertyDescriptor(proto, prop) ?? null; ++ table.set(prop, found); ++ } ++ return found ?? undefined; ++} ++ + // ── Global state ────────────────────────────────────────────────────────────── + + /** Maps every store proxy → its internal bookkeeping. */ +@@ -460,8 +485,15 @@ + + get(_target, prop, receiver) { + internal.resumeScope(); +- // 1. Check for getters on the prototype chain (computed values). +- const getterDesc = findPropertyDescriptor(_target, prop); ++ // SPIKE: an own key of a node with no own accessor is data, with no ++ // descriptor allocated. An inherited key is answered per prototype. ++ let getterDesc: PropertyDescriptor | undefined; ++ if (hasOwn.call(_target, prop)) { ++ if (internal.ownAccessors) ++ getterDesc = Object.getOwnPropertyDescriptor(_target, prop); ++ } else { ++ getterDesc = inheritedDescriptor(Object.getPrototypeOf(_target), prop); ++ } + if (getterDesc?.get) { + // Memoized: evaluate with dependency tracking, return cached if deps unchanged. + const value = evaluateComputed( +@@ -501,6 +533,8 @@ + + defineProperty(_target, prop, descriptor) { + const defined = Reflect.defineProperty(_target, prop, descriptor); ++ if (defined && (descriptor.get || descriptor.set)) ++ internal.ownAccessors = true; + // `Object.freeze(proxy)` arrives here once per property. A property that + // is now read-only holds its value as it is, as if frozen all along. + const own = defined && Object.getOwnPropertyDescriptor(_target, prop); +@@ -538,6 +572,7 @@ + const desc = Object.getOwnPropertyDescriptor(owner.target, key); + if (desc && 'value' in desc) + linkChild(owner, key, desc.value, nodes, desc); ++ else if (desc) owner.ownAccessors = true; + } + } + } +--- a/core/ownership.ts ++++ b/core/ownership.ts +@@ -6,6 +6,7 @@ + export class StoreInternal { + version = 0; + isStoreRoot = false; ++ ownAccessors = false; + // Each subscribe() call owns one entry, so the same callback can be + // registered more than once and released independently. + readonly batchedListeners = new Set<() => void>(); +``` + +```js +// Indicative read costs, not the repository's benchmark. Each case reads one +// field in a loop and adds it up so the read cannot be optimised away. +import {createStore, createRoot, createEffect, flush} from '@solidjs/signals'; +import * as original from '../spike/orig.mjs'; +import * as patched from '../spike/patched.mjs'; + +class Counter { + count = 1; + label = 'a'; + get double() { + return this.count * 2; + } + increment() { + this.count++; + } +} + +function time(label, read, rounds = 7, iterations = 2_000_000) { + let sink = 0; + for (let i = 0; i < 200_000; i++) sink += read(); + const samples = []; + for (let round = 0; round < rounds; round++) { + const start = performance.now(); + for (let i = 0; i < iterations; i++) sink += read(); + samples.push(((performance.now() - start) * 1e6) / iterations); + } + samples.sort((a, b) => a - b); + console.log( + ` ${label.padEnd(58)} ${samples[rounds >> 1].toFixed(1).padStart(6)} ns (${samples[0].toFixed(1)} to ${samples[rounds - 1].toFixed(1)})${sink ? '' : ''}`, + ); +} + +const forwarding = new Proxy(new Counter(), { + get: (target, key, receiver) => Reflect.get(target, key, receiver), +}); +const ours = original.createClassyStore(new Counter()); +const oursPatched = patched.createClassyStore(new Counter()); +const [solidFresh] = createStore(new Counter()); +const [solidPlain] = createStore({count: 1, label: 'a'}); +const [solidObserved] = createStore(new Counter()); +createRoot(() => + createEffect( + () => solidObserved.count, + () => {}, + ), +); +flush(); + +console.log( + `${typeof Bun !== 'undefined' ? `Bun ${Bun.version}` : `Node ${process.version}`}, production build of @solidjs/signals: ${(await import('@solidjs/signals')).DEV === undefined}`, +); +time('forwarding Proxy, field', () => forwarding.count); +time('classy-store today, field', () => ours.count); +time('classy-store patched, field', () => oursPatched.count); +time('Solid, class instance field, nobody subscribed', () => solidFresh.count); +time('Solid, plain object field, nobody subscribed', () => solidPlain.count); +time( + 'Solid, class instance field, an effect subscribed', + () => solidObserved.count, +); +time('classy-store today, cached getter', () => ours.double); +time('classy-store patched, cached getter', () => oursPatched.double); +time('Solid, prototype getter, nobody subscribed', () => solidFresh.double); +time('classy-store today, method lookup', () => (ours.increment ? 1 : 0)); +time('classy-store patched, method lookup', () => + oursPatched.increment ? 1 : 0, +); +time('Solid, method lookup', () => (solidFresh.increment ? 1 : 0)); +``` + +```text +$ node 06-read-cost.mjs +Node v24.21.0, production build of @solidjs/signals: true + forwarding Proxy, field 21.7 ns (21.7 to 22.1) + classy-store today, field 46.5 ns (46.3 to 47.0) + classy-store patched, field 38.2 ns (37.8 to 38.8) + Solid, class instance field, nobody subscribed 28.3 ns (28.3 to 28.5) + Solid, plain object field, nobody subscribed 28.4 ns (28.3 to 28.6) + Solid, class instance field, an effect subscribed 33.1 ns (33.0 to 33.3) + classy-store today, cached getter 79.9 ns (79.9 to 80.7) + classy-store patched, cached getter 74.6 ns (74.4 to 74.9) + Solid, prototype getter, nobody subscribed 40.7 ns (39.6 to 40.7) + classy-store today, method lookup 64.5 ns (63.7 to 66.0) + classy-store patched, method lookup 60.1 ns (59.8 to 62.3) + Solid, method lookup 39.8 ns (39.8 to 40.1) +``` + +```text +$ bun 06-read-cost.mjs +Bun 1.4.4, production build of @solidjs/signals: true + forwarding Proxy, field 2.5 ns (2.5 to 5.0) + classy-store today, field 25.4 ns (25.1 to 31.5) + classy-store patched, field 11.9 ns (9.0 to 12.0) + Solid, class instance field, nobody subscribed 22.2 ns (21.6 to 22.2) + Solid, plain object field, nobody subscribed 20.3 ns (20.3 to 20.4) + Solid, class instance field, an effect subscribed 16.9 ns (16.9 to 17.2) + classy-store today, cached getter 58.2 ns (56.2 to 59.7) + classy-store patched, cached getter 34.3 ns (34.3 to 34.4) + Solid, prototype getter, nobody subscribed 23.1 ns (23.1 to 23.1) + classy-store today, method lookup 49.8 ns (48.6 to 51.1) + classy-store patched, method lookup 30.9 ns (30.8 to 31.3) + Solid, method lookup 15.4 ns (15.4 to 16.4) +``` + +### Port 7: `snapshot`, `deep`, `reconcile`, unbound methods + +Solid: + +```js +import { + createStore, + snapshot, + deep, + reconcile, + createRoot, + createEffect, + flush, +} from '@solidjs/signals'; +import {show, title} from './helper.mjs'; + +title('18. snapshot(): identity, sharing and freezing'); +const raw = { + touched: {n: 1}, + untouched: {n: 1}, + rows: [ + {id: 1, n: 1}, + {id: 2, n: 1}, + ], +}; +const [store, setStore] = createStore(raw); +show( + 'before any write: snapshot(store) === raw', + () => snapshot(store) === raw, +); +setStore((s) => { + s.touched.n = 2; +}); +show('a read straight after the setter, before flush()', () => store.touched.n); +flush(); +show('the same read after flush()', () => store.touched.n); +const one = snapshot(store); +const two = snapshot(store); +show('after a write: two snapshots are the same object', () => one === two); +show('the unchanged subtree is the raw object in both', () => [ + one.untouched === raw.untouched, + two.untouched === raw.untouched, +]); +show( + 'the changed subtree is the same object in both', + () => one.touched === two.touched, +); +show('a snapshot is frozen', () => [ + Object.isFrozen(one), + Object.isFrozen(one.touched), +]); +show('writing to a snapshot changes the store', () => { + one.touched.n = 77; + one.untouched.n = 88; + return {touched: store.touched.n, untouched: store.untouched.n}; +}); + +title('19. deep(): one subscription for a whole subtree'); +let runs = 0; +createRoot(() => + createEffect( + () => deep(store), + () => void runs++, + ), +); +flush(); +runs = 0; +show('write a nested row', () => { + setStore((s) => { + s.rows[1].n = 5; + }); + flush(); + return {effectRuns: runs}; +}); +show('write a value it already holds', () => { + setStore((s) => { + s.rows[1].n = 5; + }); + flush(); + return {effectRuns: runs}; +}); + +title('20. reconcile(): keep row identity across a replaced list'); +const firstRow = store.rows[0]; +const secondRow = store.rows[1]; +let rowRuns = 0; +createRoot(() => + createEffect( + () => store.rows[0].n, + () => void rowRuns++, + ), +); +flush(); +rowRuns = 0; +show('reconcile a reordered, edited copy by id', () => { + setStore((s) => { + reconcile( + [ + {id: 2, n: 5}, + {id: 1, n: 100}, + {id: 3, n: 0}, + ], + 'id', + )(s.rows); + }); + flush(); + return { + order: store.rows.map((row) => row.id).join(), + sameProxyForId1: store.rows[1] === firstRow, + sameProxyForId2: store.rows[0] === secondRow, + editedValue: store.rows[1].n, + rowEffectRuns: rowRuns, + }; +}); +show('a plain assignment of a fresh list instead', () => { + const before = store.rows[0]; + setStore((s) => { + s.rows = [ + {id: 2, n: 5}, + {id: 1, n: 100}, + {id: 3, n: 0}, + ]; + }); + flush(); + return {sameProxyForId2: store.rows[0] === before}; +}); + +title('21. Methods are not bound'); +class Counter { + count = 0; + increment() { + this.count++; + } +} +const [counter, setCounter] = createStore(new Counter()); +show('const {increment} = draft; increment()', () => { + setCounter((s) => { + const {increment} = s; + increment(); + }); + flush(); + return counter.count; +}); +show( + 'store.increment === Counter.prototype.increment', + () => counter.increment === Counter.prototype.increment, +); +``` + +```text +$ node --conditions=development 07-snapshot.solid.mjs +18. snapshot(): identity, sharing and freezing + before any write: snapshot(store) === raw -> true + a read straight after the setter, before flush() -> 1 + the same read after flush() -> 2 + after a write: two snapshots are the same object -> false + the unchanged subtree is the raw object in both -> [true,true] + the changed subtree is the same object in both -> false + a snapshot is frozen -> [false,false] + writing to a snapshot changes the store -> {"touched":2,"untouched":88} + +19. deep(): one subscription for a whole subtree + write a nested row -> {"effectRuns":1} + write a value it already holds -> {"effectRuns":1} + +20. reconcile(): keep row identity across a replaced list + reconcile a reordered, edited copy by id -> {"order":"2,1,3","sameProxyForId1":true,"sameProxyForId2":true,"editedValue":100,"rowEffectRuns":1} + a plain assignment of a fresh list instead -> {"sameProxyForId2":false} + +21. Methods are not bound + const {increment} = draft; increment() -> THROWS TypeError: Cannot read properties of undefined (reading 'count') + store.increment === Counter.prototype.increment -> true +``` + +### Port 8: the cases of ports 3 and 4 on our library, and async writes + +```ts +import { + createClassyStore, + snapshot, + subscribe, + batch, +} from '/packages/classy-store/src/index.ts'; +import {show, title} from './helper.mjs'; + +title('3. A function held in an array, read twice; a class held in a store'); +class Model { + static label = 'model'; + name: string; + constructor(name: string) { + this.name = name; + } +} +const first = () => 1; +const second = () => 2; +const store = createClassyStore({ + callbacks: [first, second], + Model, + handler: first, +}); +show( + 'store.callbacks[0] === store.callbacks[0]', + () => store.callbacks[0] === store.callbacks[0], +); +show('store.callbacks.indexOf(first)', () => store.callbacks.indexOf(first)); +show('remove the first callback by indexOf', () => { + store.callbacks.splice(store.callbacks.indexOf(first), 1); + return store.callbacks.length === 1 && store.callbacks[0]() === 2 + ? 'second is left' + : 'wrong one removed'; +}); +show('store.Model === Model, store.Model.label', () => [ + store.Model === Model, + (store.Model as typeof Model).label, +]); +show( + 'new store.Model("x") instanceof store.Model', + () => new store.Model('x') instanceof store.Model, +); + +title('4. list.includes(raw)'); +const row = {id: 1}; +const rows = createClassyStore({list: [row, {id: 2}]}); +show('rows.list.includes(row), indexOf(row)', () => [ + rows.list.includes(row), + rows.list.indexOf(row), +]); +show('rows.list.includes(rows.list[0])', () => + rows.list.includes(rows.list[0]), +); + +title('6. Object.defineProperty through the proxy'); +const s6 = createClassyStore<{a: number; b?: number; child: {n: number}}>({ + a: 1, + child: {n: 1}, +}); +let calls = 0; +subscribe(s6, () => void calls++, {sync: true}); +snapshot(s6); +show('Object.defineProperty(store, "b", {value: 2, ...})', () => { + Object.defineProperty(s6, 'b', { + value: 2, + writable: true, + enumerable: true, + configurable: true, + }); + return { + storeB: s6.b, + subscriberCalls: calls, + snapshotB: snapshot(s6).b ?? 'undefined', + }; +}); +show('redefine a property that holds an object', () => { + s6.child.n; + Object.defineProperty(s6, 'child', { + value: {n: 99}, + writable: true, + enumerable: true, + configurable: true, + }); + return {childN: s6.child.n}; +}); + +title( + "7. 'key' in store and Object.keys(store) inside a getter, then a key is removed", +); +const dict = createClassyStore({ + a: 1, + b: 2, + get count() { + return Object.keys(this).length; + }, + get hasB() { + return 'b' in this; + }, +} as {a: number; b?: number; readonly count: number; readonly hasB: boolean}); +show('first read', () => ({count: dict.count, hasB: dict.hasB})); +show('delete store.b', () => { + delete dict.b; + return { + count: dict.count, + hasB: dict.hasB, + snapshotCount: snapshot(dict).count, + snapshotHasB: snapshot(dict).hasB, + }; +}); + +title('9. A self-referencing object'); +const cyc = createClassyStore<{name: string; self?: unknown}>({name: 'root'}); +show('store.self = store', () => { + cyc.self = cyc; + return cyc.self === cyc; +}); +show('snapshot(store)', () => snapshot(cyc).name); + +title('12. A delete that removes nothing'); +const bag = createClassyStore<{a: number; missing?: number}>({a: 1}); +let bagCalls = 0; +subscribe(bag, () => void bagCalls++, {sync: true}); +show('delete store.missing', () => { + delete bag.missing; + return {subscriberCalls: bagCalls}; +}); + +title('8b. An async method, and batch() around an await'); +class Loader { + a = 0; + b = 0; + async load() { + this.a = 1; + await 0; + this.a = 2; + this.b = 2; + } +} +const loader = createClassyStore(new Loader()); +let loaderCalls = 0; +subscribe(loader, () => void loaderCalls++, {sync: true}); +await loader.load(); +show( + 'sync notifications for one async method that writes three times', + () => loaderCalls, +); +loaderCalls = 0; +await batch(async () => { + loader.a = 3; + await 0; + loader.a = 4; + loader.b = 4; +}); +show( + 'sync notifications for batch(async () => ...) with three writes', + () => loaderCalls, +); +``` + +```text +$ bun 08-all.classy.ts +3. A function held in an array, read twice; a class held in a store + store.callbacks[0] === store.callbacks[0] -> false + store.callbacks.indexOf(first) -> -1 + remove the first callback by indexOf -> wrong one removed + store.Model === Model, store.Model.label -> [false,null] + new store.Model("x") instanceof store.Model -> false + +4. list.includes(raw) + rows.list.includes(row), indexOf(row) -> [false,-1] + rows.list.includes(rows.list[0]) -> true + +6. Object.defineProperty through the proxy + Object.defineProperty(store, "b", {value: 2, ...}) -> {"storeB":2,"subscriberCalls":0,"snapshotB":"undefined"} + redefine a property that holds an object -> {"childN":1} + +7. 'key' in store and Object.keys(store) inside a getter, then a key is removed + first read -> {"count":4,"hasB":true} + delete store.b -> {"count":4,"hasB":true,"snapshotCount":0,"snapshotHasB":false} + +9. A self-referencing object + store.self = store -> true + snapshot(store) -> THROWS Error: @codebelt/classy-store: circular reference detected in snapshot + +12. A delete that removes nothing + delete store.missing -> {"subscriberCalls":1} + +8b. An async method, and batch() around an await + sync notifications for one async method that writes three times -> 3 + sync notifications for batch(async () => ...) with three writes -> 3 +``` + +### Port 9: `#private` fields + +Solid: + +```js +import {createStore, flush} from '@solidjs/signals'; +import {show, title} from './helper.mjs'; + +title('22. #private fields'); +class Vault { + #secret = 1; + open = 1; + get doubled() { + return this.#secret * 2; + } + bump() { + this.#secret++; + this.open++; + } +} +const [vault, setVault] = createStore(new Vault()); +show('a prototype getter that reads a #private field', () => vault.doubled); +show('a prototype method that writes a #private field, on the draft', () => { + setVault((s) => { + s.bump(); + }); + flush(); + return vault.open; +}); +show('the public field after that', () => vault.open); +``` + +```text +$ node --conditions=development 09-private.solid.mjs +22. #private fields + a prototype getter that reads a #private field -> 2 + a prototype method that writes a #private field, on the draft -> THROWS TypeError: Cannot read private member #secret from an object whose class did not declare it + the public field after that -> 1 +``` + +Ours: + +```ts +import {createClassyStore} from '/packages/classy-store/src/index.ts'; +import {show, title} from './helper.mjs'; + +title('22. #private fields'); +class Vault { + #secret = 1; + open = 1; + get doubled() { + return this.#secret * 2; + } + bump() { + this.#secret++; + this.open++; + } +} +const vault = createClassyStore(new Vault()); +show('a prototype getter that reads a #private field', () => vault.doubled); +show('a prototype method that writes a #private field', () => { + vault.bump(); + return vault.open; +}); +``` + +```text +$ bun 09-private.classy.ts +22. #private fields + a prototype getter that reads a #private field -> THROWS TypeError: Cannot access invalid private field (evaluating 'this.#secret') + a prototype method that writes a #private field -> THROWS TypeError: Cannot access invalid private field (evaluating 'this.#secret') +``` + +### Port 10: row identity after an undo + +```ts +import { + createClassyStore, + snapshot, +} from '/packages/classy-store/src/index.ts'; +import {withHistory} from '/packages/classy-store/src/utils/index.ts'; +import {show, title} from './helper.mjs'; + +const flush = () => new Promise((resolve) => setTimeout(resolve, 0)); + +title('20. Row identity after an undo (our counterpart of reconcile)'); +const store = createClassyStore({ + rows: [ + {id: 1, n: 1}, + {id: 2, n: 1}, + {id: 3, n: 1}, + ], + other: {n: 1}, +}); +const history = withHistory(store); +await flush(); +const before = snapshot(store); +const liveRowBefore = store.rows[0]; +store.rows[2].n = 2; +await flush(); +history.undo(); +await flush(); +const after = snapshot(store); +show( + 'the untouched top-level branch keeps its snapshot', + () => after.other === before.other, +); +show('the untouched rows keep their snapshots', () => [ + after.rows[0] === before.rows[0], + after.rows[1] === before.rows[1], +]); +show( + 'the untouched row keeps its live proxy', + () => store.rows[0] === liveRowBefore, +); +show('the restored value', () => after.rows[2].n); +``` + +```text +$ bun 10-history.classy.ts +20. Row identity after an undo (our counterpart of reconcile) + the untouched top-level branch keeps its snapshot -> true + the untouched rows keep their snapshots -> [false,false] + the untouched row keeps its live proxy -> false + the restored value -> 1 +``` + +## What was verified by running code, and what was only read + +Verified by running, in the scratch folder: + +- Every line of output quoted in the findings and printed under "Ported + tests", on `@solidjs/signals` 2.0.0 from npm and on our source at + `825ba2d`. +- Which build each Node invocation resolves, and that the production and + observe trees contain no diagnostic text. +- The timings in finding 1, on Node and on Bun: one run of seven rounds each, + on a machine that was not otherwise idle. Treat them as indicative. The + spread within a run is in the port's output. +- That `@solidjs/signals` exports no `batch`; that a typed array, a promise + and a class with `Symbol.toStringTag` are not wrappable; that `markRaw` + keeps a value unwrapped; that a store proxy assigned into another store is + stored unwrapped. +- That a class's `prototype` property is not writable and a plain + function's is (finding 3). + +Only read, not run: + +- How each cache is filled and refreshed (finding 1), beyond what the ports + show from outside. +- The keyed part of `reconcile` beyond the one reorder in port 7. +- `STORE_WRITE_THROUGH_LOADING`, `STRICT_READ_UNTRACKED`, + `UNTRACKED_READ_AFTER_AWAIT` and the two performance codes. The last two + are from the catalogue entry alone. +- The rows marked "Read" in the table. + +Not done: + +- The spike in finding 1 was not run against our unit suite, and nothing + else proposed here was spiked. +- No bundler or test runner was checked for which export condition it sets + (finding 9). Node only. +- `persist.ts` and `devtools.ts` were not read for finding 11. +- Solid's `optimistic.ts`, `projection.ts`, `storePath.ts` and + `store/utils.ts` were not read. They cover derived and optimistic stores + and props helpers, which have no counterpart here. +- Nothing was run in a browser. diff --git a/review/stage-2/svelte.md b/review/stage-2/svelte.md new file mode 100644 index 00000000..f472a9d3 --- /dev/null +++ b/review/stage-2/svelte.md @@ -0,0 +1,2545 @@ +# Stage 2: Svelte 5 (`$state` proxy, `SvelteMap`, `SvelteSet`) + +Stage 2 of the pre-1.0 review, 2026-11-19. Read-only: nothing in the +repository was changed apart from this file. + +## Library, version and files read + +- **Library:** `svelte`, from `https://github.com/sveltejs/svelte`. +- **Version:** 5.57.3, read from the copy installed in this repository at + `node_modules/.bun/svelte@5.57.3/node_modules/svelte/src/`. Nothing was + cloned, so there is no commit to record. The copy installed from npm in the + scratch folder is identical (`diff -rq` of the two `src` folders reports no + difference). +- **Files read**, under `src/`: `internal/client/proxy.js`, + `reactivity/map.js`, `reactivity/set.js`, `internal/client/dev/equality.js`, + `internal/shared/clone.js` and + `compiler/phases/3-transform/client/visitors/ClassBody.js` whole; + `internal/client/reactivity/sources.js` lines 1 to 300. Single functions + were looked up in `internal/client/errors.js`, `internal/client/warnings.js`, + `internal/client/dom/operations.js`, `internal/client/reactivity/batch.js`, + `internal/client/reactivity/deriveds.js`, `reactivity/index-server.js`, + `store/index-client.js` and two compiler visitors + (`VariableDeclaration.js`, `BinaryExpression.js`). +- **Ours:** `core/core.ts`, `snapshot/snapshot.ts`, + `collections/collections.ts`, `utils/internal/internal.ts`, + `frameworks/svelte/svelte.ts`, and the first 60 and last 30 lines of + `core/ownership.ts`. +- **Ported tests.** `$state` is compiler syntax. Each port is a `.svelte.js` + module compiled with `compileModule` from `svelte/compiler`, then run on Bun + 1.4.4 with `--conditions browser --conditions development`, which selects + Svelte's client build and its development checks. Every port was run a + second time compiled and resolved for production. Nothing calls the internal + `proxy()` directly; the compiled output does. Our side ran from the + repository source imported by absolute path. Code and output are in the + appendix. + +Line numbers for Svelte refer to 5.57.3. Line numbers for ours refer to +`release/1.0` at `ac38f2f`. + +## Summary + +Svelte 5 makes state reactive in three unrelated ways. A plain object or array +given to `$state` is wrapped in a Proxy that keeps one signal per property. A +class is never wrapped: the compiler turns each `$state` field into a private +signal with a getter and a setter. Maps and sets are classes of their own that +extend the native ones. Set against ours, that gives eleven findings. The three +that matter most: + +1. **A class instance is never put behind a proxy (finding 1).** That is why + arrow-function methods and `#private` fields work in Svelte: `this` is + always the real instance. We cannot copy the mechanism, which needs a + compiler, but the idea carries over. A base class whose constructor returns + the store makes arrow-function methods notify on our library as it is today + (run, see the appendix). A `#private` field can never be state under + snapshots, with any wrapping scheme, and the docs should say so. This + answers API question 4. +2. **A `defineProperty` with a plain value is a write (finding 2).** Svelte + treats it exactly like an assignment and refuses every other descriptor + with a named error. Our trap handles freezing only. A 24-line spike that + gives the trap the bookkeeping of `set` fixed the reproductions of stage 1 + findings 1, 45, 66 and 71, and it is what makes the base class in point 1 + produce a correct first snapshot. +3. **`SvelteMap` and `SvelteSet` are separate classes, as ours are, but they + keep native storage (finding 8).** Svelte does not make a native `Map` + reactive either, which supports keeping `reactiveMap` and `reactiveSet` + (API question 5). The difference is cost and exactness: a lookup among + 10,000 entries took 17 nanoseconds there and 45 microseconds on ours, and + theirs get `-0` right for free. Ours match a raw object, its proxy and its + snapshot as one member, which theirs do not. + +Svelte is not the better design for our purpose in most other respects. "Where +we already do better" lists eight cases where our behaviour is the one to +keep. + +Six small changes to our source were tried in a throwaway copy: 66 lines +added and 24 removed across three files. Each fixed its reproduction. **The +repository's test suite was not run against the copy**, as the stage rules +require, so every one of them is a sketch for stage 3, not a tested change. + +## How the two designs differ + +This explains why some of Svelte's answers carry over and most cannot. + +- **Svelte's proxy never writes to the object it wraps.** Each proxy holds a + `Map` from property name to signal (`sources`, `proxy.js:58`). A signal is + made the first time a property is read or written, and from then on the + signal is the value. The `set` trap (`proxy.js:271-342`) contains no write + to the target. After `state.n = 5` the raw object still says 0 (port 10). We + write the target (`core.ts:432`) and keep an index of children beside it. +- **One raw object can have many proxies.** `proxy()` checks whether its + argument is already a state proxy and otherwise makes a new one + (`proxy.js:42-55`, `:118`). There is no map from raw object to proxy. We keep + one node per raw object (`targetNodes`, `core.ts:14`, `:396`). +- **No ownership graph.** A proxy knows nothing about who holds it. A reader + subscribes to the signals it read; nothing travels up to a root. So Svelte + has nothing like our versions, parent links, suspend and resume. Stage 1 + findings 24, 28, 61, 66 to 69 and 72 have no counterpart. +- **A snapshot is a clone.** `$state.snapshot` (`snapshot`, `clone.js:21`) + copies the whole value on every call. The copy is not frozen, shares nothing + with the previous copy and is not cached. +- **Reads are tracked by whatever is running.** A signal read registers with + the effect or derived value that is executing, whichever object owns the + signal. Our live getter records reads on its own node only + (`core.ts:91`). +- **A compiler is part of the library.** It rewrites `$state` fields in + classes (`ClassBody.js:86-106`) and, in development, every `===` and `!==` + (`BinaryExpression.js:11-21`). + +## Findings + +### 1. A class owns its reactivity; the instance is never wrapped + +API questions 4 and 6. Stage 1 finding 9. + +- **What they do.** `proxy()` returns its argument unchanged unless the + prototype is exactly `Object.prototype` or `Array.prototype` + (`proxy.js:51-55`). A class instance held in state is therefore stored as it + is, and nothing about it is reactive. A class becomes reactive from the + inside: the compiler replaces a field `n = $state(0)` with a private field + holding a signal, plus a getter and a setter on the prototype that read and + write it (`ClassBody`, `ClassBody.js:86-106`). In the compiled output of port + 2 the field reads `#n = $.state(0)`, with `get n()` and `set n(value)` + beside it. Reactivity belongs to the instance, so `this` can be the raw + instance everywhere. +- **What we do.** `createClassyStore(instance)` wraps the instance in a Proxy + (`core.ts:405`, `:566`). A method found on the prototype is bound to the + proxy and run as a transaction (`core.ts:483-491`), so `this.n++` reaches + the `set` trap. An arrow-function field captured the raw instance when the + constructor ran, so its writes go past the proxy. A `#private` field exists + on the raw instance only, and a bound method runs with the proxy as `this`, + so `this.#secret` throws. A nested class instance is wrapped only if its + class sets `static [PROXYABLE] = true` (`canProxy`, `internal.ts:70-82`). +- **Difference in behaviour.** Port 2 and `ours.ts`, same class on both sides: + + | Case | Svelte, class with `$state` fields | Ours, `createClassyStore(new Counter())` | + | ------------------------------------- | ------------------------------------------------------- | --------------------------------------------------- | + | Prototype method writes a field | Effect re-runs | Notifies | + | Arrow-function field, called detached | Effect re-runs | No notification; live `n` is 2, the snapshot says 1 | + | Method that writes a `#private` field | Effect re-runs | `TypeError` | + | Getter that reads a `#private` field | Works | `TypeError` | + | Prototype method, called detached | `TypeError`, `this` is `undefined` | Works, the method is bound | + | Plain class instance held in state | Not reactive, silently | Not reactive, silently, unless `PROXYABLE` | + | Snapshot of the instance | The same live instance, or a copy without its prototype | A frozen copy with its prototype and its getters | + + The last row is the price Svelte pays. `Object.keys` of the instance is + `["incArrow"]` and `JSON.stringify` gives `{}`, because the state sits in + private fields. `$state.snapshot` cannot copy it: it returned the same + instance with a `state_snapshot_uncloneable` warning for the class that has + an arrow field, and a prototype-less `structuredClone` for the plain one. + + **An experiment on our library.** If the reason arrow functions work in + Svelte is that `this` is the reactive object, the same can be had without a + compiler: a base class whose constructor returns the store. JavaScript then + runs the subclass's field initialisers with the store as `this`. + + ```ts + class Store { + constructor() { + return createClassyStore(this); + } + } + class Todos extends Store { + items = [{id: 1}]; + filter = 'all'; + setFilter = (value: string) => { + this.filter = value; + }; + } + const todos = new Todos(); + const {setFilter} = todos; + setFilter('done'); // notifies; snapshot(todos).filter is 'done' + ``` + + Run on the unmodified source (`ours.ts`, last block): the detached arrow + method notifies and the snapshot follows. A method that writes a `#private` + field no longer throws, because the field is now installed on the store + itself, but it notifies no one and a snapshot getter that reads the field + still throws: the snapshot is a different object and cannot hold another + class's private field. One defect showed: the first snapshot held the raw, + unfrozen `items` array, because class fields arrive through the + `defineProperty` trap, which does not index the new child. With the spike of + finding 2 the first snapshot is frozen (`repro.ts`, last block). +- **Proposal: adapt.** Do not chase the mechanism. Offer the base class as an + optional second way to make a store, and keep `createClassyStore(instance)` + for classes the user does not own. Say in the docs that a `#private` field + is never state: no proxy and no snapshot can read it from outside the class, + and Svelte only gets away with it because it has no snapshot of a class + instance. With the base class a private field becomes usable for things that + are not state, such as a timer handle. +- **Kind:** API design. +- **Cost:** one new export of about six lines and its docs; `core.ts` + unchanged apart from finding 2, which it depends on. Not breaking. Risk: + subclass constructors then write through the proxy, which costs trap time + per write, and the name and whether `useLocalStore` should accept such a + class are open. The MobX report covers the other route (binding in the + constructor); the two should be decided together. + +### 2. A `defineProperty` with a plain value is a write + +Stage 1 findings 1, 45, 61, 66 and 71. + +- **What they do.** The `defineProperty` trap (`proxy.js:119-147`) accepts a + descriptor only if it has a `value` and does not say `false` for + `writable`, `enumerable` or `configurable`. It then does what `set` does: it + writes the property's signal, wrapping an object value. Anything else throws + `state_descriptors_fixed`. The comment in the source gives the reason: the + proxy does not apply descriptors to its target, so it could not honour them + without breaking a Proxy invariant. `setPrototypeOf` throws + `state_prototype_fixed` (`proxy.js:361-363`). +- **What we do.** The trap forwards to the target and then handles one case, a + property that became read-only, by detaching its child (`core.ts:502-513`). + It does not resume a suspended subtree, index a new child, drop a stale + child, or notify. +- **Difference in behaviour.** Port 6 against `repro.ts` on our source: + + | Call through the proxy | Svelte | Ours today | + | -------------------------------------------- | ------------------------------------------------- | ---------------------------------------------------- | + | Define a new key with a full data descriptor | Readers of the key re-run | No notification; key missing from the next snapshot | + | Redefine a key that holds an object | `state.child.n` is the new object's, readers told | `s.child.n` still reads the old object, snapshot too | + | Redefine `rows[0]` as `7` | Live and snapshot both 7 | Live and snapshot both still the old row | + | Define with `{value: 3}` only | An ordinary writable, enumerable property | Native: read-only, hidden, and not notified | + | Define an accessor, or `writable: false` | Throws `state_descriptors_fixed` | Forwarded to the target | + | `Object.freeze(proxy)` | Throws, and leaves the target non-extensible | Works | + + Svelte's trap has a gap of its own. After a new key is defined, an effect + that read `Reflect.ownKeys(state)` is not told: the trap creates the signal + but does not bump the object's key-set version, which `set` and + `deleteProperty` do (`proxy.js:338`, `:156`, `:164`). Port 6 shows the + effect's list without `b` while `Object.keys(state)` read afterwards has it. + So the idea is worth taking and the code is not. + + **Spike.** In a throwaway copy the trap was given the bookkeeping of `set`: + resume the scope first (the one-line change stage 1 proposed for finding + 66), forward to the target, link the value as a child or detach the old one, + drop the cached bound method, and notify if the descriptor changed anything + a snapshot shows. `linkChild` already refuses a read-only value, so the + freeze case falls out of the same code. On `repro.ts`: a new key notifies + once and is in the snapshot; the redefined child and row read correctly on + both layers; the read of finding 66 returns 1 instead of never returning. +- **Proposal: adapt.** Take "a data descriptor is a write". Do not take the + refusals: Svelte must refuse what it cannot store, and we store everything on + the target, so accessors and read-only properties can keep working. +- **Kind:** bug. +- **Cost:** `core.ts` only, 24 lines added and 9 removed in the spike. Not + breaking for correct code. Risk: `Object.freeze(store)` goes through this + trap once per key, and the tests that pin findings 61 and 67 will change. + Stage 1 measured the one-line part against the suite; the rest was run + against the reproductions only. + +### 3. A function is returned as it is + +Stage 1 findings 5, 6, 42 and 62. + +- **What they do.** `proxy()` returns anything that is not an object + unchanged (`proxy.js:42-49`), and the `get` trap returns what the signal + holds (`proxy.js:198-201`). No function is bound or wrapped, whether it is + an array element, a class stored as data, or a method. +- **What we do.** Every function read through a store is wrapped by + `transactional` (`core.ts:483-491`). An object property's wrapper is cached, + an array element's is made anew on each read (`core.ts:486`). +- **Difference in behaviour.** Ports 1 and 3 against `ours.ts`: + `state.callbacks[0] === first` is `true` and `indexOf(first)` is 0, so the + splice removes the right callback. `state.Model.label` is `'model'` and + `new state.Model() instanceof state.Model` is `true`; ours gives `undefined` + and `false`. What Svelte loses is the binding: a prototype method taken off + a class instance throws when called (port 2), where ours works. +- **Proposal: adapt**, as the Vue report's finding 4 already says: keep + binding and transactions for methods, and stop wrapping array elements, + classes and `constructor`. Svelte adds nothing to that proposal except a + second library that does it and a reminder of what binding is worth. +- **Kind:** bug. +- **Cost:** see the Vue report. Nothing was spiked here. + +### 4. `has`, `ownKeys`, and a property that does not exist + +Stage 1 findings 30, 31, 32, 41 and 50. Bears on API question 3. + +- **What they do.** The `has` trap (`proxy.js:234-269`) makes a signal for the + key when it runs inside an effect or a derived value, including for a key + that is absent, which gets a marker value. The `get` trap does the same for + an absent key (`proxy.js:183-196`). `ownKeys` (`proxy.js:344-359`) reads one + signal per object that stands for its set of keys; `set` bumps it only when + the key is new (`proxy.js:324-339`) and `deleteProperty` only when a key + goes. `getOwnPropertyDescriptor` (`proxy.js:206-232`) calls `has` and reads + the key's signal, so it is tracked too. +- **What we do.** No `has`, `ownKeys` or `getOwnPropertyDescriptor` trap. + A live getter records a property read as a value to compare later, and + `areDepsValid` rejects that record whenever the property is absent + (`core.ts:147`), so a getter that read a missing property never has valid + dependencies. +- **Difference in behaviour.** Port 5, each reader in its own effect: + + | Write | `Object.keys` reader | `Reflect.ownKeys` reader | `'b' in state` reader | `state.nope` reader | + | -------------------- | -------------------- | ------------------------ | --------------------- | ------------------- | + | `state.a = 1` (same) | No | No | No | No | + | `state.a = 10` | **Re-runs** | No | No | No | + | Delete a missing key | No | No | No | No | + | `delete state.b` | Re-runs | Re-runs | Re-runs | No | + | `state.nope = 7` | Re-runs | Re-runs | No | Re-runs | + + Two things stand out. `Object.keys` re-runs on a value change, because the + engine asks for each key's descriptor to test enumerability and that trap + reads the value's signal. `for...in` behaves the same. Vue avoids this by + not trapping descriptors; its split between "a value changed" and "the set + of keys changed" is the cleaner one. And a derived value that read a missing + property is memoized: read twice, it ran once and returned the same object. + On ours it ran twice and returned two objects (finding 32). + + A descriptor read gives the raw object before the property has been read + and the proxy after (port 6, last lines). That is our finding 50 in half the + cases, so Svelte is no model there. + + **Spike for finding 32.** The value record was given a `present` flag, and + the check became "is it present as it was" instead of "is it present". On + `repro2.ts` the getter then ran once for two reads, again when the property + appeared and again when it was deleted. Seven lines. +- **Proposal: adopt** the split the Vue report proposes for `has` and + `ownKeys`; Svelte confirms it and shows the trap not to add + (`getOwnPropertyDescriptor` tracking). **Adopt** the `present` flag for + finding 32 whatever is decided about the traps. +- **Kind:** bug. +- **Cost:** for the flag, `core.ts` and `core.types.ts`, 7 lines; not + breaking; low risk. For the traps, see the Vue report, including what it + found about enumerable snapshot getters. + +### 5. Deleting a key that is not there + +Stage 1 finding 29. + +- **What they do.** `deleteProperty` (`proxy.js:149-168`) does nothing when + the key has no signal and is not in the target. An assignment of the value a + property already holds is dropped by the signal's equality check + (`internal_set`, `sources.js:190`). +- **What we do.** `Reflect.deleteProperty` returns `true` for a key that is + absent, and the trap then detaches, bumps versions and notifies + (`core.ts:515-524`). +- **Difference in behaviour.** Port 5: no reader re-runs. `repro.ts` on ours: + one notification and a new, equal snapshot. +- **Proposal: adopt.** Test `Object.hasOwn` before the delete and treat an + absent key as no write. Spiked: no notification, the same snapshot object, + and deleting a present key still notifies once. +- **Kind:** bug. +- **Cost:** `core.ts`, two lines. Changes behaviour only for code that relied + on a no-op delete to force a notification. Low risk. + +### 6. Searching an array for a raw object: Svelte warns, it does not fix + +Stage 1 finding 7. + +- **What they do.** Nothing in production: `state.list.includes(raw)` is + `false` (port 4). In development `init_array_prototype_warnings` + (`dev/equality.js:4-69`) replaces `Array.prototype.includes`, `indexOf` and + `lastIndexOf` for every array on the page. When a search misses and the raw + form of some element equals the argument, it prints + `state_proxy_equality_mismatch`. It is installed when the first component + mounts (`dom/operations.js:73`). The compiler also rewrites `===` and `!==` + in development to a function that prints the same warning + (`strict_equals`, `dev/equality.js:77-87`). +- **What we do.** The array's own methods run with the proxy as `this` and + compare proxies with the raw argument (`core.ts:486`), so they miss. No + warning. +- **Difference in behaviour.** The same wrong answer in both. Svelte names it + in development. +- **Proposal: reject** Svelte's way, **adopt** Vue's. A library cannot patch + `Array.prototype` for the whole page, and we have no compiler. The Vue + report's finding on raw values and array search fixes the answer instead of + describing it, and we already hold the piece that makes it possible: one + node per raw object, and `identityOf` (`core.ts:52-56`). +- **Kind:** bug. +- **Cost:** see the Vue report. + +### 7. Frozen objects + +Stage 1 finding 46 and the rule "frozen objects are values". + +- **What they do.** There is no frozen check in `proxy()`. A frozen plain + object is wrapped like any other. Its properties are not writable, so the + `get` trap makes no signal for them and returns the raw value + (`proxy.js:183`, `:203`). +- **What we do.** A frozen object is kept by reference and never proxied + (`isImmutableValue`, `core.ts:337-342`; `linkChild`, `core.ts:368`). A + property that becomes read-only through the store releases its child + (`core.ts:502-513`). +- **Difference in behaviour.** Port 7 against `ours.ts`: + + | Case | Svelte | Ours | + | ------------------------------------------------- | ------------------------------------------------------------------------------- | --------------------------------- | + | Frozen object in state | Wrapped; its nested objects come back raw | Kept as it is | + | Assign an existing key | `TypeError` from the engine's Proxy check | `TypeError`, as on a frozen value | + | Assign a new key | Accepted and readable | `TypeError` | + | `Object.keys` after that | `TypeError` from then on | Works | + | `Object.freeze(proxy)` | Throws; target left non-extensible; `Object.keys` breaks after the next new key | Works; reads and keys still fine | + | Freeze the raw object after the property was read | `TypeError` on the next read | `TypeError` on the next read | + | Freeze the raw object before any read | Raw value returned | `TypeError` on the next read | + + Only the last two rows favour Svelte, and only because it makes signals + lazily. Ours indexes children when the store is made (`core.ts:535-542`), so + a later freeze behind its back always leaves a child proxy that the engine + will not let the `get` trap return. + + **Spike for finding 46.** The `get` trap already has the property's own + descriptor in hand (`core.ts:464`). If the property is read-only and a child + proxy is indexed for it, the spike detaches the child and returns the raw + value. On `repro2.ts` the read returns 1 instead of throwing. +- **Proposal: reject** Svelte's handling; our rule is the better one. + **Consider** the nine-line guard for finding 46. It is free only while `get` + looks the descriptor up on every read. If the per-prototype cache from the + Solid report removes that lookup, the guard would have to pay for its own. +- **Kind:** bug. +- **Cost:** `core.ts`, 9 lines added and 3 removed. Not breaking. The + performance interaction above is the risk. + +### 8. `SvelteMap` and `SvelteSet` extend the native classes + +API question 5. Stage 1 findings 12, 15, 16, 33 and 34. + +- **What they do.** `SvelteMap extends Map` (`map.js:53`) and + `SvelteSet extends Set` (`set.js:47`). The data lives in the native + collection, reached with `super`. Beside it, in `#private` fields, sit one + signal per key that has been asked about, one version signal and one size + signal (`map.js:55-58`). Each reading method reads a signal and then calls + `super` (`get`, `map.js:131-154`); each writing method calls `super` and + then writes signals (`set`, `map.js:182-215`). Values are stored as given + and not made reactive, which the class comment states. Set operations that + build a new set return a new `SvelteSet` (`set.js:107-115`). On the server + the two names are the native classes themselves + (`reactivity/index-server.js:2-3`). +- **Why they are separate classes** (reasoning from the source, which does not + say). First, `proxy()` only wraps plain objects and arrays, so a `Map` in + state is never touched, and a Proxy could not intercept its internal slots + anyway; a native `Map` in state is not reactive (port 8). Second, a class + instance is never wrapped (finding 1), so a subclass can use `super`, + `#private` fields and the real `this` freely. The explicit class is the + opt-in. Third, extending the native class keeps everything a `Map` user + expects: `instanceof Map`, insertion order, key equality, constant-time + lookup, and the server alias. +- **What we do.** `ReactiveMap` and `ReactiveSet` are ordinary classes over a + plain array (`_entries`, `collections.ts:54`; `_items`, `:209`), marked + `PROXYABLE` so the store proxies the array. Lookups scan the array and + compare by `identityOf` (`indexOfMember`, `collections.ts:16-33`). The array + is what lets a collection be snapshotted, frozen and shared structurally + like any other state. Our collections could not extend the native ones as + the store stands: a method called through our proxy has the proxy as + `this`, and `Map.prototype.get` rejects it. +- **Difference in behaviour.** Port 8 against `ours.ts`: + + | Case | Svelte | Ours | + | ---------------------------------------- | ------------------------------- | -------------------------------------- | + | `instanceof Map` | `true` | `false` | + | Key set by raw object, read by its proxy | `undefined`: two different keys | Found; raw, proxy and snapshot are one | + | `set(proxy, …)` after `set(raw, …)` | Size 2 | Size 1 | + | Set built from `[raw, proxy]` | Size 2, and `add` agrees | Size 2, but `add` holds it once | + | `new Set([0])` then `add(-0)` | Size 1, as native | Size 2 (finding 33) | + | A value's field changed in place | Readers not told | Readers told | + | Snapshot | A plain, mutable `Map` copy | Frozen, shared, keeps the class | + | Internal storage visible on the instance | No: `Object.keys(map)` is empty | Yes: `_entries` is public | + | `get` of the last of 10,000 string keys | 17 ns | 45 µs live, 346 µs on a snapshot | + + The timings are one run of `lookup.ts` on Bun, on a machine that was doing + other work: read them as orders of magnitude. Ours grows with the size (0.75 + µs at 100 entries, 6 µs at 1,000), theirs does not. Why our snapshot is + slower than our live store was not looked into. +- **Proposal.** + - **Reject** making native `Map` and `Set` reactive directly. Svelte does + not do it either, and for us a native collection cannot be frozen or + shared between snapshots. + - **Keep** the array-backed classes and their identity rule; that rule is + better than Svelte's. + - **Adopt** native equality at the edges: `add(-0)` after `0` should be one + member (finding 33), and the constructor should use the same identity as + `add` (finding 34). Svelte is at least consistent between the two. + - **Consider** an index from identity to position, kept beside the array, + so that lookups stop scanning. This is a design task, not a patch: the + index has to stay right when history or persist replace the array. +- **Kind:** API design for the first two, bug for the third, performance for + the last. +- **Cost:** the equality fixes are a few lines in `collections.ts` and change + the two cases stage 1 pinned. The index is new code in `collections.ts` + with medium risk and needs the stage 1 benchmark to justify it. Nothing here + was spiked. + +### 9. A snapshot is a clone, and a cycle is not an error + +Stage 1 findings 8, 10, 11, 13 and 25. + +- **What they do.** `clone` (`clone.js:57-139`) walks the value through the + proxy and copies arrays and plain objects, keeping a map from each object to + its copy (`clone.js:59-60`, `:67`, `:86`). A second visit returns the copy + already made, so shared references stay shared and a cycle closes on itself. + `Map` and `Set` are copied one level deep, a `Date` is cloned, a class + instance is copied through its `toJSON` if it has one and otherwise through + `structuredClone`, and what cannot be cloned is returned as it is with a + development warning. +- **What we do.** `createSnapshotRecursive` builds frozen copies keyed on the + node's version and throws "circular reference detected in snapshot" when it + meets a node it is still building (`snapshot.ts:246-250`). +- **Difference in behaviour.** Port 9: `state.self = state` works, + `state.self.self.n` reads, a derived value that reads through the cycle + re-runs only when what it read changes, and the snapshot has + `snap.self === snap`. Ours accepts the write and then cannot produce a + snapshot until the reference is removed. Port 10: because nothing is cached, + an object changed while it was out of the state and then put back reads the + same live and in the snapshot (2 and 2); ours gives 2 and 1 (finding 25). + The same port shows what the clone model costs: the raw object and the state + drift apart for good after the first write. + + **Spike for finding 8.** The set of nodes being built became a map from node + to the unfinished snapshot, and meeting a node again returns that snapshot + instead of throwing. Every member of a cycle owns every other, so a write to + one bumps all their versions and they are rebuilt together. On `repro.ts`: a + store that holds itself, a ring of two objects and a list that holds itself + all snapshot, every node is frozen, a later write gives a new consistent + snapshot, and an unrelated sibling is still shared. +- **Proposal: adapt, or refuse the cycle at the write.** The state today, + where the write succeeds and the store can no longer be read, is the one + outcome to remove. The spike shows the core can support cycles in 13 lines. + What it does not show is the rest: `persist` and `devtools` serialise + snapshots as JSON, `withHistory` copies them, and React's tracked reads + compare them through `proxy-compare`. None of those was run with a cyclic + snapshot. If they are not to be made cycle-safe, throwing from the `set` + trap when a write closes a cycle is the honest alternative. +- **Kind:** bug, and API design for the choice. +- **Cost:** `snapshot.ts`, 13 lines added and 9 removed for the core. Not + breaking: it turns an error into a result. Risk is in the four utilities + named above. + +### 10. A setter is one change, and getters are not memoized by default + +Stage 1 findings 39, 40 and 43. + +- **What they do.** An accessor on a plain state object is not a signal: the + `get` trap falls through to `Reflect.get` with the proxy as receiver + (`proxy.js:203`), so the getter body runs on every read and its reads are + tracked by whoever called it. Memoization is something the author asks for, + with a `$derived` field. A setter is called by the `set` trap + (`proxy.js:317-322`) and its writes are ordinary writes; effects run later, + in a microtask or at `flushSync` (`batch.js:846`, `:991`), so they see the + end state. +- **What we do.** Every class getter is memoized on the live store + (`evaluateComputed`, `core.ts:160-196`) and again on the snapshot. A setter + is called with the proxy as `this` (`core.ts:414-418`) but outside any + transaction, so each write inside it notifies sync subscribers on its own. +- **Difference in behaviour.** Port 12: the plain getter ran twice for two + reads; the `$derived` field ran once and returned the same object. A setter + that writes two fields gave the effect one run, which saw `"c d"`. On ours + (`repro2.ts`) a sync subscriber saw `"c b"` and then `"c d"`. An object + returned by a derived value is as unprotected as ours (finding 40): the + reader changed it and the next read showed the change. In a snapshot of the + plain object the getter's result is an own data property (API question 3). + + **Spike for finding 43.** The setter call was wrapped in the same + transaction counter that methods use. The subscriber then saw `"c d"` once. +- **Proposal: adopt** the setter transaction. **Reject** opt-in memoization: + automatic memoization of class getters is the point of our library, and + Svelte's default costs a recomputation per read. +- **Kind:** bug. +- **Cost:** `core.ts`, 6 lines added and 1 removed. A subscriber that counted + one notification per write inside a setter sees fewer. Low risk. + +### 11. Diagnostics, and how the development build is separated + +API question 8. Stage 1 findings 18, 19, 38 and 39. + +- **What they do.** Every error and warning has a stable code. In development + the message is the code, a sentence and a link; in production it is the link + alone (`errors.js:436-446` is one example). The switch is the constant `DEV` + from the `esm-env` package, which resolves through the `development` and + `production` export conditions of `package.json`, not through + `process.env.NODE_ENV`. What exists, with the build it runs in: + + | Code | When | Build | Source | + | ------------------------------- | ------------------------------------------------------------- | ------------------ | ----------------------- | + | `state_unsafe_mutation` | A derived value writes state while it computes | Both, throws | `sources.js:150-160` | + | `effect_update_depth_exceeded` | Effects keep scheduling each other for more than 1,000 rounds | Both, throws | `batch.js:361`, `:1047` | + | `derived_references_self` | A derived value reads itself | Development only | `deriveds.js:358-364` | + | `state_descriptors_fixed` | A descriptor the proxy cannot store | Both, throws | `proxy.js:119-131` | + | `state_prototype_fixed` | `Object.setPrototypeOf` on state | Both, throws | `proxy.js:361-363` | + | `state_proxy_equality_mismatch` | A proxy compared with its raw object | Development, warns | `dev/equality.js` | + | `state_snapshot_uncloneable` | A snapshot kept something it could not copy | Development, warns | `clone.js:21-45` | + +- **What we do.** One build. A getter that writes re-runs and notifies on + every read (finding 39). A sync subscriber that writes recurses until the + stack overflows, and a batched one loops without bound (`deliver`, + `core.ts:314-328`, has no counter; findings 18 and 19). A getter cycle is + caught on the live store (`core.ts:171-184`) and overflows the stack on a + snapshot (finding 38). +- **Difference in behaviour.** Port 11, both builds. The derived value that + writes throws in both. The effect that writes what it reads is stopped with + the named error in both, after the state reached 1,001. The two derived + values that read each other throw the named error in development and a + `RangeError: Maximum call stack size exceeded` in production, which is our + finding 38 exactly: Svelte chose to pay for that check in development only. +- **Proposal.** + - **Adopt** a bound on subscriber delivery with a named error, in every + build. It is one counter. It turns findings 18 and 19 from a stack + overflow and a hung event loop into a message. + - **Adopt** an error for a write made while a getter is being computed. The + live store knows it is inside a getter (`trackerStack`, `core.ts:65`), so + the test is one length check in `set` and `deleteProperty`. It makes the + two layers agree: a snapshot getter cannot write at all. + - **Adopt** stable codes in messages. Ours already start with the package + name; a code after it costs nothing and gives the docs something to link. + - **Consider** export conditions for a development build, as Svelte and + Solid do, if stage 3 wants checks that are too slow for production. + Everything proposed above is cheap enough not to need it. + - **Reject** the equality warning; finding 6 fixes the cause. +- **Kind:** diagnostics. +- **Cost:** a counter in `deliver` and one check in two traps, `core.ts` + only. The getter-write error is breaking for a getter that fills a cache + field on first read. None of this was spiked; it is reasoning from our + source and from what port 11 showed of Svelte. + +## Where we already do better + +Each of these was run. Keep our behaviour. + +- **One object, one proxy.** In Svelte the same raw object placed in two + fields gets two proxies with separate signals: after `two.a.id = 5`, + `two.b.id` is still 1 and so is the raw object (port 1). Ours gives one + proxy, and all three agree on 5. +- **The raw object stays current.** We write the target, so the class instance + the user made holds the state. In Svelte the raw object keeps its first + values for good (port 10). +- **Frozen values and frozen stores** (finding 7). +- **Collections match by identity** across raw object, proxy and snapshot + (finding 8). +- **Snapshots of class instances** keep the prototype and the getters, are + frozen and are shared structurally. Svelte returns the live instance or a + prototype-less clone (finding 1). +- **Methods are bound.** A method taken off a store still works. In Svelte it + throws (port 2). +- **Getters are memoized without being asked** (finding 10). A Svelte derived + value read outside an effect also loses its memoization once a dependency + has changed without changing its result: three reads ran it three times + (`probes/x-probe.svelte.js`, not in the appendix). +- **Objects without a prototype are state.** Svelte leaves + `Object.create(null)` unwrapped (port 1); we proxy it + (`isPlainObject`, `internal.ts:59`). + +## Stage 1 findings with a counterpart in Svelte 5 + +"Port n" means the behaviour was run; "read" means it follows from the source +and was not run. + +| Stage 1 finding | What Svelte 5 does | Evidence | +| --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ | ---------- | +| 1. `defineProperty` is silent | A plain data descriptor is a write and wakes readers of the key. Readers of the key list are not told about a new key. | Port 6 | +| 5. Function in an array is a new wrapper per read | Returned as it is; `indexOf` finds it | Port 3 | +| 6. Class held in a store is a bound wrapper | Returned as it is; statics and `instanceof` work | Port 1 | +| 7. `includes(raw)` misses | Misses too. Development build warns `state_proxy_equality_mismatch` | Port 4 | +| 8. Self-reference can be written, not read | Works; the snapshot keeps the cycle | Port 9 | +| 9. Store placed by its raw object is not connected | A class instance has no separate raw form. A plain object placed twice gets two independent proxies, which is worse | Ports 1, 2 | +| 10. Raw objects end up holding proxies | The target is never written; proxies live in signals | Port 10 | +| 11. Raw write invisible until the next proxied write | Invisible for good once the property has been read or written; visible before that. Live state and snapshot always agree | Port 10 | +| 12. Native `Set` or `Map` holds raw members | The same: native collections are opaque, and `SvelteSet` holds what it was given | Port 8 | +| 13. Getter on a self-referring store recomputes on every write | A derived value re-runs only for what it read | Port 9 | +| 15. Backing arrays are public | Signals sit in `#private` fields; the instance has no own keys | Port 8 | +| 16. Snapshot of a collection keeps mutators in the type | The snapshot is a plain mutable `Map` or `Set` | Port 8 | +| 18, 19. A subscriber that writes loops without bound | Stopped after 1,000 rounds with `effect_update_depth_exceeded` | Port 11 | +| 25. Raw object changed while detached shows old content | No cache, so live and snapshot agree | Port 10 | +| 29. Deleting a missing key counts as a write | No effect | Port 5 | +| 30. Getter over `Object.keys` or `in` goes stale | Tracked. `Object.keys` also re-runs on value changes | Port 5 | +| 32. Getter over a missing property recomputes every read | A signal is made for the missing key; memoized | Port 5 | +| 33. `+0` and `-0` are two members when added | One member both ways, as native | Port 8 | +| 34. One object in two forms held twice when constructed | Held twice when constructed and when added: consistent, not unified | Port 8 | +| 36. Getter misses reads outside its own node | Any signal read while computing is a dependency, whoever owns it | Read | +| 38. Getter cycle overflows the stack on a snapshot | Named error in development; the same stack overflow in production | Port 11 | +| 39. A getter that writes | Throws `state_unsafe_mutation` in both builds | Port 11 | +| 40. Object returned by a getter is not protected | The same | Port 12 | +| 42. `constructor` is a bound wrapper | Functions are never wrapped | Port 1 | +| 43. A setter is not a transaction | Effects are batched, so they see the end state | Port 12 | +| 45. Redefining a property leaves the old object in place | The new value is read and readers are told | Port 6 | +| 46. Freezing a raw object behind the store makes reads throw | The same `TypeError` if the property was read before; raw value if not | Port 7 | +| 47. Cached getter survives a prototype change | `Object.setPrototypeOf` throws `state_prototype_fixed` | Port 6 | +| 48. `Object.assign` with a parsed `__proto__` key swaps the prototype | Ignored: the `set` trap makes no signal for an inherited accessor and never writes the target | Port 6 | +| 50. A descriptor's value is the raw object | Raw before the property's first read, the proxy after | Port 6 | +| 62. A store made from a function | Functions are never proxied | Read | +| 63. Typed-array store | Not wrapped: its prototype is not `Array.prototype` | Read | +| 71. Array element redefined disagrees between store and snapshot | They agree | Port 6 | + +No counterpart: findings 2 to 4, 14, 17, 20 to 24, 26 to 28, 31, 35, 37, 41, +44, 49, 51 to 61, 64 to 70, 72 and 73. They concern our snapshot cache, our +ownership graph, our subscriber delivery, or utilities Svelte does not have. + +## The eight API questions + +1. **Should synchronous notification be the default for `subscribe()`?** No. + Svelte batches: two writes gave one effect run, after a microtask or an + explicit `flushSync()` (`batch.js:846`, `:991`; port 2's counters move only + at `flushSync`). Derived values are pulled, so they are current whenever + read. Synchronous delivery is the exception one asks for. Our Svelte + adapter asks for it because the store contract requires it + (`svelte.ts:33`); that is the adapter's business, not the default's. +2. **Writes outside a store method: allowed, warned about, or grouped? Does + `batch()` belong in the API?** Allowed anywhere and grouped automatically, + with no warning and no `batch` function. The one forbidden place is inside + a derived value (`state_unsafe_mutation`). From this point of view + `batch()` exists in ours only because framework bindings are synchronous; + it is the right tool while that holds and would be unnecessary if delivery + to bindings were deferred. +3. **Should snapshot getters stay enumerable own accessors?** Svelte has two + answers. On a plain state object a getter's result becomes an enumerable + own data property of the snapshot (port 12). On a class, derived fields are + prototype accessors, not enumerable, and do not appear in `Object.keys` or + JSON at all unless the class writes a `toJSON` (port 2). Neither is an + enumerable accessor. The class answer matches the Vue report's finding + that enumerable getters and key tracking get in each other's way. +4. **Can arrow-function methods and `#private` fields be made to work?** + Svelte: yes to both, by never putting a proxy around the instance, which + needs its compiler. For us (finding 1): arrow-function methods work today + with a base class whose constructor returns the store. `#private` fields + stop throwing with that base class but cannot be state, because a snapshot + cannot copy them. +5. **Should native `Map` and `Set` be reactive directly?** No. Svelte leaves + them alone and ships `SvelteMap` and `SvelteSet`, separate classes that + extend the native ones (finding 8). Explicit reactive collection classes + are the shared answer; how they are built differs. +6. **Opt-in or opt-out for nested class instances?** Opt-in, more strictly + than ours. Nothing but a plain object or array is ever wrapped + (`proxy.js:51-55`), and there is no flag to change that: a class opts in by + declaring reactive fields. Because class instances are raw by default there + is no `markRaw`. The opt-out for plain data is at the declaration, + `$state.raw`, which the compiler leaves unwrapped + (`VariableDeclaration.js:139-142`); our equivalent is a frozen value. This + supports `PROXYABLE` as opt-in. +7. **Are entry points, export names and adapter names consistent?** No + position on the five frameworks. On naming only: Svelte's own conversion + functions are `toStore` and `fromStore` in `svelte/store` + (`store/index-client.js:47`, `:128`), and its reactive classes carry the + framework's name as a prefix. Our `toSvelteStore` reads naturally beside + those. The adapters report covers the rest. +8. **What development-only diagnostics would catch our silent failures?** + Finding 11. Svelte has no check for our two named failures, arrow-function + methods and writes after an `await`, because neither can happen there. What + it does have, and we lack, is a bound on notification loops, an error for a + write inside a computed value, and stable codes. + +## Verified by running, and only read + +**Run** (ports compiled by Svelte's compiler, on Bun 1.4.4, development and +production builds; our side from the repository source at `ac38f2f`): + +- Everything in the difference tables of findings 1 to 10, the port 11 rows + of finding 11, every row of the stage 1 table marked "Port", and every item + under "Where we already do better". +- The base-class experiment of finding 1, on the unmodified source and on the + spike. +- Six spike patches, each against its reproduction only: `defineProperty` as + a write, delete of a missing key, cyclic snapshots, the `present` flag, the + setter transaction, and the read-only guard in `get`. Their difference + against the repository source is in the appendix. +- The read that never returns (stage 1 finding 66) was reproduced on the + unmodified source: the script was killed by `timeout 8` at that read. +- Lookup timings, once, on a busy machine. + +**Only read, not run:** + +- Why `SvelteMap` and `SvelteSet` are separate classes. The source does not + state a reason; the three given in finding 8 are inferences from it. +- The server build (`reactivity/index-server.js`). All ports ran the client + build. +- That any signal read registers with the running effect or derived value, + whoever owns it (stage 1 table, finding 36). The runtime's `get` was not + read; the ports only show it for nested state. +- Typed arrays and stores made from functions in Svelte (stage 1 table, + findings 62 and 63). +- The proposals of finding 11. No loop bound or getter-write error was + spiked. +- The index proposed in finding 8. + +**Not done:** + +- The repository's test suite was not run against the spike, by the stage + rules. A spike patch that passes its reproduction may still break a pinned + test; findings 2 and 9 say where that is most likely. +- Cyclic snapshots were not tried with `persist`, `devtools`, `withHistory` + or React's tracked reads. +- The development warnings of port 4 were installed by calling Svelte's + internal function by hand, because there is no DOM in the scratch run. In a + browser the first mounted component installs them. +- Svelte's effect ordering, teardown and late-subscriber behaviour (stage 1 + findings 20 to 24) were not ported; they belong to a different model. + +## Appendix: ported tests and their output + +All files are in the scratch folder +`/stage-2-svelte/`. +Each port is compiled by `build.mjs` and run by `run.sh`, both shown at the +end. In the development build the compiler rewrites `===`, so a port that +compares a proxy with its raw object on purpose prints +`state_proxy_equality_mismatch`; those warnings are shortened to one line +below. + +### Port 1: which values are wrapped + +`ports/p01-wrapping.svelte.js`: + +```js +// Which values does $state wrap? Stage 1 findings 6, 42, 62; API question 6. +import {attempt} from '../helpers.js'; + +class Model { + static label = 'model'; + n = 0; +} +const raws = { + plain: {a: 1}, + array: [1], + nullProto: Object.assign(Object.create(null), {a: 1}), + instance: new Model(), + frozen: Object.freeze({nested: {a: 1}}), + date: new Date(0), + map: new Map(), + fn: () => 1, + Model, +}; +const state = $state({...raws}); + +for (const key of Object.keys(raws)) { + console.log( + `${key}: ${state[key] === raws[key] ? 'kept as it is' : 'wrapped'}`, + ); +} +console.log( + 'frozen.nested:', + state.frozen.nested === raws.frozen.nested ? 'kept as it is' : 'wrapped', +); +console.log('function read twice is the same:', state.fn === state.fn); +attempt('state.Model.label', () => state.Model.label); +attempt( + 'new state.Model() instanceof state.Model', + () => new state.Model() instanceof state.Model, +); +attempt( + 'state.instance.constructor === Model', + () => state.instance.constructor === Model, +); + +// One raw object in two places. +const shared = {id: 1}; +const two = $state({a: shared, b: shared}); +console.log('two.a === two.b:', two.a === two.b); +two.a.id = 5; +console.log( + 'after two.a.id = 5: two.b.id =', + two.b.id, + ', shared.id =', + shared.id, +); +``` + +Output, development build: + +```text +[svelte] state_proxy_equality_mismatch (console.warn, two more lines of text left out) +plain: wrapped +array: wrapped +nullProto: kept as it is +instance: kept as it is +[svelte] state_proxy_equality_mismatch (console.warn, two more lines of text left out) +frozen: wrapped +date: kept as it is +map: kept as it is +fn: kept as it is +Model: kept as it is +frozen.nested: kept as it is +function read twice is the same: true +state.Model.label -> model +new state.Model() instanceof state.Model -> true +state.instance.constructor === Model -> true +[svelte] state_proxy_equality_mismatch (console.warn, two more lines of text left out) +two.a === two.b: false +after two.a.id = 5: two.b.id = 1 , shared.id = 1 +``` + +### Port 2: a class instance in state, and a class with `$state` fields + +`ports/p02-classes.svelte.js`: + +```js +// A class instance held in state, and a class with $state fields. +// Stage 1 finding 9; API questions 4 and 6. +import {flushSync} from 'svelte'; +import {attempt, warnings} from '../helpers.js'; + +class Plain { + n = 0; + inc() { + this.n++; + } +} + +class Runes { + n = $state(0); + #secret = $state(1); + items = $state([]); + doubled = $derived(this.n * 2); + inc() { + this.n++; + } + incArrow = () => { + this.n++; + }; + bumpSecret() { + this.#secret++; + } + get secret() { + return this.#secret; + } +} + +const state = $state({plain: new Plain(), runes: new Runes()}); +const runs = {plain: 0, n: 0, secret: 0, items: 0}; +const stop = $effect.root(() => { + $effect(() => (state.plain.n, runs.plain++)); + $effect(() => (state.runes.n, runs.n++)); + $effect(() => (state.runes.secret, runs.secret++)); + $effect(() => (state.runes.items.length, runs.items++)); +}); +flushSync(); +const show = (label) => { + flushSync(); + console.log(label, JSON.stringify(runs)); +}; +show('initial '); +state.plain.inc(); +show('plain.inc() '); +console.log(' plain.n is now', state.plain.n); +state.runes.inc(); +show('runes.inc() '); +const {incArrow, inc} = state.runes; +incArrow(); +show('detached arrow incArrow()'); +attempt('detached prototype method inc()', () => inc()); +state.runes.bumpSecret(); +show('runes.bumpSecret() (#priv)'); +state.runes.items.push({x: 1}); +show('runes.items.push() '); +console.log('doubled:', state.runes.doubled, ' n:', state.runes.n); +console.log('Object.keys(runes):', JSON.stringify(Object.keys(state.runes))); +console.log('JSON.stringify(runes):', JSON.stringify(state.runes)); +let snap; +const warned = warnings(() => { + snap = $state.snapshot(state); +}); +console.log( + 'snapshot keeps the same instance:', + snap.runes === state.runes, + snap.plain === state.plain, +); +console.log('snapshot warnings:', JSON.stringify(warned)); +stop(); +``` + +Output, development build: + +```text +initial {"plain":1,"n":1,"secret":1,"items":1} +plain.inc() {"plain":1,"n":1,"secret":1,"items":1} + plain.n is now 1 +runes.inc() {"plain":1,"n":2,"secret":1,"items":1} +detached arrow incArrow() {"plain":1,"n":3,"secret":1,"items":1} +detached prototype method inc() THROWS TypeError: undefined is not an object (evaluating 'this.n') +runes.bumpSecret() (#priv) {"plain":1,"n":3,"secret":2,"items":1} +runes.items.push() {"plain":1,"n":3,"secret":2,"items":2} +doubled: 4 n: 2 +Object.keys(runes): ["incArrow"] +JSON.stringify(runes): {} +snapshot keeps the same instance: true false +snapshot warnings: ["state_snapshot_uncloneable"] +``` + +Lines that differ in the production build: + +```text +snapshot warnings: [] +``` + +### Port 3: a function held in an array + +`ports/p03-functions.svelte.js`: + +```js +// A function held in an array, read twice. Stage 1 finding 5. +const first = () => 'first'; +const second = () => 'second'; +const state = $state({callbacks: [first, second]}); + +console.log( + 'callbacks[0] === callbacks[0]:', + state.callbacks[0] === state.callbacks[0], +); +console.log('callbacks[0] === first:', state.callbacks[0] === first); +console.log('indexOf(first):', state.callbacks.indexOf(first)); +state.callbacks.splice(state.callbacks.indexOf(first), 1); +console.log( + 'after removing first, what is left:', + state.callbacks.map((f) => f()).join(','), +); +``` + +Output, development build: + +```text +callbacks[0] === callbacks[0]: true +callbacks[0] === first: true +indexOf(first): 0 +after removing first, what is left: second +``` + +### Port 4: `list.includes(raw)` + +`ports/p04-includes.svelte.js`: + +```js +// list.includes(raw), indexOf, lastIndexOf. Stage 1 finding 7. +import {warnings} from '../helpers.js'; +// In a browser, init_operations() installs these the first time a component +// mounts, in development only (dom/operations.js:73). There is no DOM here, +// so the same function is called by hand. +import {init_array_prototype_warnings} from '../node_modules/svelte/src/internal/client/dev/equality.js'; + +const raw = {id: 1}; +const state = $state({list: [raw]}); + +console.log('list[0] === raw:', state.list[0] === raw); +console.log('includes(raw):', state.list.includes(raw)); +console.log('indexOf(raw):', state.list.indexOf(raw)); +console.log('lastIndexOf(raw):', state.list.lastIndexOf(raw)); +console.log('includes(list[0]):', state.list.includes(state.list[0])); +console.log( + 'find by field:', + state.list.findIndex((row) => row.id === raw.id), +); + +init_array_prototype_warnings(); +const seen = warnings(() => { + state.list.includes(raw); + state.list.indexOf(raw); + state.list.includes(state.list[0]); +}); +console.log('warnings once the dev patch is installed:', JSON.stringify(seen)); +``` + +Output, development build: + +```text +[svelte] state_proxy_equality_mismatch (console.warn, two more lines of text left out) +list[0] === raw: false +includes(raw): false +indexOf(raw): -1 +lastIndexOf(raw): -1 +includes(list[0]): true +find by field: 0 +warnings once the dev patch is installed: ["state_proxy_equality_mismatch","state_proxy_equality_mismatch"] +``` + +### Port 5: `Object.keys(state)`, `'key' in state` and a missing property + +`ports/p05-keys.svelte.js`: + +```js +// A reader of Object.keys(state), of 'key' in state, and of a property that +// does not exist. Stage 1 findings 29 to 32. +import {flushSync} from 'svelte'; + +const state = $state({a: 1, b: 2}); +const runs = {keys: 0, ownKeys: 0, has: 0, missing: 0}; +const seen = {}; +const stop = $effect.root(() => { + $effect(() => (runs.keys++, (seen.keys = Object.keys(state).length))); + $effect(() => (runs.ownKeys++, Reflect.ownKeys(state))); + $effect(() => (runs.has++, (seen.hasB = 'b' in state))); + $effect(() => (runs.missing++, (seen.nope = state.nope))); +}); +const show = (label) => { + flushSync(); + console.log(label, JSON.stringify(seen), 'runs', JSON.stringify(runs)); +}; +show('initial '); +state.a = 1; +show('state.a = 1 (same) '); +state.a = 10; +show('state.a = 10 '); +delete state.missingKey; +show('delete a missing key'); +delete state.b; +show('delete state.b '); +state.nope = 7; +show('state.nope = 7 '); +stop(); + +// Finding 32: a derived value that reads a missing property keeps its result. +let derivedRuns = 0; +const missing = $derived.by(() => (derivedRuns++, {value: state.gone})); +console.log( + 'derived over a missing property, read twice: same object', + missing === missing, + ', runs', + derivedRuns, +); +``` + +Output, development build: + +```text +initial {"keys":2,"hasB":true} runs {"keys":1,"ownKeys":1,"has":1,"missing":1} +state.a = 1 (same) {"keys":2,"hasB":true} runs {"keys":1,"ownKeys":1,"has":1,"missing":1} +state.a = 10 {"keys":2,"hasB":true} runs {"keys":2,"ownKeys":1,"has":1,"missing":1} +delete a missing key {"keys":2,"hasB":true} runs {"keys":2,"ownKeys":1,"has":1,"missing":1} +delete state.b {"keys":1,"hasB":false} runs {"keys":3,"ownKeys":2,"has":2,"missing":1} +state.nope = 7 {"keys":2,"hasB":false,"nope":7} runs {"keys":4,"ownKeys":3,"has":2,"missing":2} +derived over a missing property, read twice: same object true , runs 1 +``` + +### Port 6: `Object.defineProperty`, `Object.freeze` and the prototype + +`ports/p06-define.svelte.js`: + +```js +// Object.defineProperty, Object.freeze and prototype changes through the +// proxy. Stage 1 findings 1, 45, 47, 48, 50, 71. +import {flushSync} from 'svelte'; +import {attempt} from '../helpers.js'; + +const basic = (value) => ({ + value, + writable: true, + enumerable: true, + configurable: true, +}); +const other = {n: 99}; +const state = $state({a: 1, child: {n: 1}, rows: [{id: 1}]}); +const seen = {}; +const stop = $effect.root(() => { + $effect(() => void (seen.keys = Reflect.ownKeys(state).join(','))); + $effect(() => void (seen.childN = state.child.n)); + $effect(() => void (seen.b = state.b)); +}); +const show = (label) => { + flushSync(); + console.log(label, JSON.stringify(seen)); +}; +show('initial '); +Object.defineProperty(state, 'b', basic(2)); +show('define a new key b '); +console.log(' Object.keys(state) read now:', Object.keys(state).join(',')); +Object.defineProperty(state, 'child', basic(other)); +show('redefine child as another object '); +Object.defineProperty(state.rows, 0, basic(7)); +console.log( + 'redefine rows[0] as 7: live', + state.rows[0], + ', snapshot', + JSON.stringify($state.snapshot(state.rows)), +); +stop(); + +attempt('define with {value: 3} only', () => { + Object.defineProperty(state, 'c', {value: 3}); + state.c = 4; + return `c = ${state.c}, enumerable = ${Object.keys(state).includes('c')}`; +}); +attempt('define an accessor', () => + Object.defineProperty(state, 'd', { + get: () => 1, + configurable: true, + enumerable: true, + }), +); +attempt('define a read-only value', () => + Object.defineProperty(state, 'e', { + value: 1, + writable: false, + enumerable: true, + configurable: true, + }), +); +attempt('Object.setPrototypeOf(state, {})', () => + Object.setPrototypeOf(state, {}), +); + +const untouched = $state({a: 1}); +attempt('Object.freeze(state), no key added before', () => + Object.freeze(untouched), +); +attempt(' then a read', () => untouched.a); +attempt(' then untouched.z = 1', () => ((untouched.z = 1), untouched.z)); +attempt(' then Object.keys', () => Object.keys(untouched).join(',')); + +const target = $state({a: 1}); +Object.assign(target, JSON.parse('{"__proto__": {"polluted": true}, "a": 2}')); +console.log( + 'assign a parsed __proto__ key: polluted =', + target.polluted, + ', a =', + target.a, + ', prototype unchanged =', + Object.getPrototypeOf(target) === Object.prototype, +); + +const rawChild = {n: 1}; +const holder = $state({child: rawChild}); +const early = Object.getOwnPropertyDescriptor(holder, 'child').value; +console.log( + 'descriptor value before any read is the raw object:', + Object.is(early, rawChild), +); +const live = holder.child; +const late = Object.getOwnPropertyDescriptor(holder, 'child').value; +console.log( + 'descriptor value after a read is the proxy:', + Object.is(late, live), +); +``` + +Output, development build: + +```text +initial {"keys":"a,child,rows","childN":1} +define a new key b {"keys":"a,child,rows","childN":1,"b":2} + Object.keys(state) read now: a,child,rows,b +redefine child as another object {"keys":"a,child,rows","childN":99,"b":2} +redefine rows[0] as 7: live 7 , snapshot [7] +define with {value: 3} only -> c = 4, enumerable = true +define an accessor THROWS Svelte error: state_descriptors_fixed +define a read-only value THROWS Svelte error: state_descriptors_fixed +Object.setPrototypeOf(state, {}) THROWS Svelte error: state_prototype_fixed +Object.freeze(state), no key added before THROWS Svelte error: state_descriptors_fixed + then a read -> 1 + then untouched.z = 1 -> 1 + then Object.keys THROWS TypeError: Proxy handler's 'ownKeys' method returned a key that was not present in its non-extensible target +assign a parsed __proto__ key: polluted = undefined , a = 2 , prototype unchanged = true +descriptor value before any read is the raw object: true +descriptor value after a read is the proxy: true +``` + +Lines that differ in the production build: + +```text +define an accessor THROWS Error: https://svelte.dev/e/state_descriptors_fixed +define a read-only value THROWS Error: https://svelte.dev/e/state_descriptors_fixed +Object.setPrototypeOf(state, {}) THROWS Error: https://svelte.dev/e/state_prototype_fixed +Object.freeze(state), no key added before THROWS Error: https://svelte.dev/e/state_descriptors_fixed +``` + +### Port 7: a frozen object in state + +`ports/p07-frozen.svelte.js`: + +```js +// A frozen object held in state, and an object frozen behind the proxy. +// Stage 1 finding 46 and the "frozen objects are values" rule. +import {attempt} from '../helpers.js'; + +const frozen = Object.freeze({nested: {a: 1}, n: 1}); +const state = $state({config: frozen}); +console.log('config is wrapped:', state.config !== frozen); +console.log( + 'config.nested is the raw object:', + state.config.nested === frozen.nested, +); +console.log('config.n:', state.config.n); +attempt('config.n = 2', () => ((state.config.n = 2), state.config.n)); +attempt('delete config.n', () => delete state.config.n); +attempt( + 'config.extra = 1 (new key)', + () => ((state.config.extra = 1), state.config.extra), +); +attempt('Object.keys(config) after that', () => + Object.keys(state.config).join(','), +); +attempt('"extra" in config', () => 'extra' in state.config); +attempt('JSON.stringify(config)', () => JSON.stringify(state.config)); + +const rawRead = {config: {nested: {a: 1}}}; +const read = $state(rawRead); +read.config.nested.a; +Object.freeze(rawRead.config); +attempt( + 'freeze behind the proxy after a read: config.nested', + () => read.config.nested.a, +); + +const rawUnread = {config: {nested: {a: 1}}}; +const unread = $state(rawUnread); +Object.freeze(rawUnread.config); +attempt( + 'freeze behind the proxy before any read: config.nested', + () => unread.config.nested.a, +); +console.log( + ' nested is then the raw object:', + unread.config.nested === rawUnread.config.nested, +); +``` + +Output, development build: + +```text +[svelte] state_proxy_equality_mismatch (console.warn, two more lines of text left out) +config is wrapped: true +config.nested is the raw object: true +config.n: 1 +config.n = 2 THROWS TypeError: Proxy handler's 'set' on a non-configurable and non-writable property on 'target' should either return false or be the same value already on the 'target' +delete config.n THROWS TypeError: Proxy handler's 'deleteProperty' method should return false when the target's property is not configurable +config.extra = 1 (new key) -> 1 +Object.keys(config) after that THROWS TypeError: Proxy object's 'target' has the non-configurable property 'n' that was not in the result from the 'ownKeys' trap +"extra" in config -> true +JSON.stringify(config) THROWS TypeError: Proxy object's 'target' has the non-configurable property 'n' that was not in the result from the 'ownKeys' trap +freeze behind the proxy after a read: config.nested THROWS TypeError: Proxy handler's 'get' result of a non-configurable and non-writable property should be the same value as the target's property +freeze behind the proxy before any read: config.nested -> 1 + nested is then the raw object: true +``` + +### Port 8: `SvelteMap` and `SvelteSet` + +`ports/p08-collections.svelte.js`: + +```js +// SvelteMap and SvelteSet with object keys. Stage 1 findings 12, 33, 34, 35; +// API question 5. +import {flushSync} from 'svelte'; +import {SvelteMap, SvelteSet} from 'svelte/reactivity'; + +const raw = {id: 1}; +const state = $state({list: [raw]}); +const proxied = state.list[0]; + +const map = new SvelteMap([[raw, 'by raw']]); +console.log( + 'map instanceof Map:', + map instanceof Map, + ' own keys:', + Object.keys(map).length, +); +console.log( + 'get(raw):', + map.get(raw), + ' get(proxy):', + map.get(proxied), + ' has(proxy):', + map.has(proxied), +); +map.set(proxied, 'by proxy'); +console.log('after set(proxy): size =', map.size); + +const set = new SvelteSet([raw, proxied]); +console.log( + 'SvelteSet([raw, proxy]).size:', + set.size, + ' delete(raw):', + set.delete(raw), + ' has(proxy):', + set.has(proxied), +); +const zeros = new SvelteSet([0]); +zeros.add(-0); +console.log( + 'SvelteSet([0]).add(-0).size:', + zeros.size, + ' SvelteSet([0, -0]).size:', + new SvelteSet([0, -0]).size, +); + +// Values are not made deeply reactive. +const values = new SvelteMap([['k', {n: 1}]]); +const held = $state({svelteMap: values, nativeMap: new Map([['a', 1]])}); +console.log( + 'a SvelteMap held in state is the same instance:', + held.svelteMap === values, +); +const runs = {value: 0, field: 0, size: 0, nativeSize: 0}; +const stop = $effect.root(() => { + $effect(() => (held.svelteMap.get('k'), runs.value++)); + $effect(() => (held.svelteMap.get('k').n, runs.field++)); + $effect(() => (held.svelteMap.size, runs.size++)); + $effect(() => (held.nativeMap.size, runs.nativeSize++)); +}); +const show = (label) => { + flushSync(); + console.log(label, JSON.stringify(runs)); +}; +show('initial '); +values.get('k').n = 2; +show("get('k').n = 2 "); +values.set('k', {n: 3}); +show("set('k', {...}) "); +values.set('other', 1); +show("set('other', 1) "); +held.nativeMap.set('b', 2); +show("native map .set('b', 2) "); + +const snap = $state.snapshot(held); +console.log( + 'snapshot of a SvelteMap: Map =', + snap.svelteMap instanceof Map, + ', SvelteMap =', + snap.svelteMap instanceof SvelteMap, + ', same instance =', + snap.svelteMap === values, +); +stop(); +``` + +Output, development build: + +```text +map instanceof Map: true own keys: 0 +get(raw): by raw get(proxy): undefined has(proxy): false +after set(proxy): size = 2 +SvelteSet([raw, proxy]).size: 2 delete(raw): true has(proxy): true +SvelteSet([0]).add(-0).size: 1 SvelteSet([0, -0]).size: 1 +a SvelteMap held in state is the same instance: true +initial {"value":1,"field":1,"size":1,"nativeSize":1} +get('k').n = 2 {"value":1,"field":1,"size":1,"nativeSize":1} +set('k', {...}) {"value":2,"field":2,"size":1,"nativeSize":1} +set('other', 1) {"value":2,"field":2,"size":2,"nativeSize":1} +native map .set('b', 2) {"value":2,"field":2,"size":2,"nativeSize":1} +snapshot of a SvelteMap: Map = true , SvelteMap = false , same instance = false +``` + +### Port 9: an object that refers to itself + +`ports/p09-self.svelte.js`: + +```js +// A state object that refers to itself. Stage 1 findings 8 and 13. +import {attempt} from '../helpers.js'; + +const state = $state({n: 1}); +state.self = state; +console.log('state.self === state:', state.self === state); +console.log('state.self.self.n:', state.self.self.n); +let runs = 0; +const total = $derived.by(() => (runs++, state.self.n * 2)); +console.log('derived:', total, 'runs', runs); +state.unrelated = 1; +console.log('after an unrelated write:', total, 'runs', runs); +state.n = 2; +console.log('after state.n = 2:', total, 'runs', runs); +attempt('snapshot of the cycle', () => { + const snap = $state.snapshot(state); + return `snap.self === snap: ${snap.self === snap}, snap === state: ${snap === state}, n: ${snap.n}`; +}); +``` + +Output, development build: + +```text +state.self === state: true +state.self.self.n: 1 +derived: 2 runs 1 +after an unrelated write: 2 runs 1 +after state.n = 2: 4 runs 2 +snapshot of the cycle -> snap.self === snap: true, snap === state: false, n: 2 +``` + +### Port 10: the raw object behind the proxy + +`ports/p10-raw.svelte.js`: + +```js +// Writes through the proxy and writes through the raw object. +// Stage 1 findings 10, 11, 25. +const raw = {n: 0, child: {n: 0}, list: [{id: 1}, {id: 2}]}; +const state = $state(raw); + +state.n = 5; +state.child.n = 1; +state.list.reverse(); +state.list.push({id: 3}); +console.log( + 'through the proxy: n', + state.n, + ' child.n', + state.child.n, + ' list', + state.list.map((r) => r.id).join(','), +); +console.log( + 'the raw object now: n', + raw.n, + ' child.n', + raw.child.n, + ' list', + raw.list.map((r) => r.id).join(','), +); + +raw.n = 9; +console.log( + 'raw.n = 9 after the proxy wrote n: state.n =', + state.n, + ', snapshot n =', + $state.snapshot(state).n, +); +raw.fresh = 1; +console.log( + 'raw.fresh = 1, never touched through the proxy: state.fresh =', + state.fresh, +); +raw.fresh = 2; +console.log('raw.fresh = 2 after that read: state.fresh =', state.fresh); + +// Finding 25: an object changed while it was out of the state, then put back. +const slotRaw = {n: 1}; +const holder = $state({slot: slotRaw}); +$state.snapshot(holder); +delete holder.slot; +slotRaw.n = 2; +holder.slot = slotRaw; +console.log( + 'put back after a raw change: live', + holder.slot.n, + ' snapshot', + $state.snapshot(holder).slot.n, +); +``` + +Output, development build: + +```text +through the proxy: n 5 child.n 1 list 2,1,3 +the raw object now: n 0 child.n 0 list 1,2 +raw.n = 9 after the proxy wrote n: state.n = 5 , snapshot n = 5 +raw.fresh = 1, never touched through the proxy: state.fresh = 1 +raw.fresh = 2 after that read: state.fresh = 1 +put back after a raw change: live 2 snapshot 2 +``` + +### Port 11: what Svelte reports + +`ports/p11-diagnostics.svelte.js`: + +```js +// What Svelte reports where we are silent. Stage 1 findings 18, 19, 38, 39. +import {flushSync} from 'svelte'; +import {attempt} from '../helpers.js'; + +const state = $state({n: 0}); + +const writes = $derived.by(() => { + state.n++; + return state.n; +}); +attempt('a derived value that writes state', () => writes); + +class Cycle { + a = $derived(this.b + 1); + b = $derived(this.a + 1); +} +attempt('two derived values that read each other', () => new Cycle().a); + +const stop = $effect.root(() => { + $effect(() => { + state.n = state.n + 1; + }); +}); +attempt('an effect that writes what it reads', () => flushSync()); +console.log('state.n after the loop was stopped:', state.n); +stop(); +``` + +Output, development build: + +```text +a derived value that writes state THROWS Svelte error: state_unsafe_mutation +two derived values that read each other THROWS Svelte error: derived_references_self +an effect that writes what it reads THROWS Svelte error: effect_update_depth_exceeded +state.n after the loop was stopped: 1001 +``` + +Lines that differ in the production build: + +```text +a derived value that writes state THROWS Error: https://svelte.dev/e/state_unsafe_mutation +two derived values that read each other THROWS RangeError: Maximum call stack size exceeded. +an effect that writes what it reads THROWS Error: https://svelte.dev/e/effect_update_depth_exceeded +``` + +### Port 12: getters, setters and `$derived` fields + +`ports/p12-getters.svelte.js`: + +```js +// A getter and a setter on a plain state object, against a $derived field. +// Stage 1 findings 39, 40, 43. +import {flushSync} from 'svelte'; + +let getterRuns = 0; +const state = $state({ + first: 'a', + last: 'b', + get full() { + getterRuns++; + return `${this.first} ${this.last}`; + }, + set full(value) { + [this.first, this.last] = value.split(' '); + }, +}); +state.full; +state.full; +console.log('plain getter read twice: runs', getterRuns); + +let effectRuns = 0; +const seen = []; +const stop = $effect.root(() => { + $effect(() => { + effectRuns++; + seen.push(state.full); + }); +}); +flushSync(); +state.full = 'c d'; +flushSync(); +console.log( + 'setter writing two fields: effect runs', + effectRuns, + ' saw', + JSON.stringify(seen), +); +stop(); +console.log( + 'snapshot of the plain object:', + JSON.stringify($state.snapshot(state)), + ', full is own data:', + 'value' in Object.getOwnPropertyDescriptor($state.snapshot(state), 'full'), +); + +let derivedRuns = 0; +class Name { + first = $state('a'); + last = $state('b'); + full = $derived.by( + () => (derivedRuns++, {text: `${this.first} ${this.last}`}), + ); +} +const name = new Name(); +const one = name.full; +const two = name.full; +console.log( + '$derived field read twice: runs', + derivedRuns, + ' same object', + one === two, +); +one.text = 'changed by the reader'; +console.log('object returned by a derived is not protected:', name.full.text); +``` + +Output, development build: + +```text +plain getter read twice: runs 2 +setter writing two fields: effect runs 2 saw ["a b","c d"] +snapshot of the plain object: {"first":"c","last":"d","full":"c d"} , full is own data: true +$derived field read twice: runs 1 same object true +object returned by a derived is not protected: changed by the reader +``` + +### The same situations on our library + +`ours.ts`, run with `bun ours.ts` against the repository source at `ac38f2f`: + +```ts +// The same situations on @codebelt/classy-store, from the repository's source. +import { + createClassyStore, + PROXYABLE, + snapshot, + subscribe, +} from '/packages/classy-store/src/index.ts'; +import { + reactiveMap, + reactiveSet, +} from '/packages/classy-store/src/collections/index.ts'; +import {attempt} from './helpers.js'; + +console.log('--- p01 wrapping'); +class Model { + static label = 'model'; + n = 0; +} +const raws: Record = { + plain: {a: 1}, + array: [1], + nullProto: Object.assign(Object.create(null), {a: 1}), + instance: new Model(), + frozen: Object.freeze({nested: {a: 1}}), + date: new Date(0), + map: new Map(), + fn: () => 1, + Model, +}; +const store = createClassyStore({...raws}) as Record; +for (const key of Object.keys(raws)) { + console.log( + `${key}: ${store[key] === raws[key] ? 'kept as it is' : 'wrapped'}`, + ); +} +console.log('function read twice is the same:', store.fn === store.fn); +attempt('store.Model.label', () => store.Model.label); +attempt( + 'new store.Model() instanceof store.Model', + () => new store.Model() instanceof store.Model, +); +const shared = {id: 1}; +const two = createClassyStore({a: shared, b: shared}); +console.log('two.a === two.b:', two.a === two.b); +two.a.id = 5; +console.log( + 'after two.a.id = 5: two.b.id =', + two.b.id, + ', shared.id =', + shared.id, +); + +console.log('--- p02 classes'); +class Plain { + n = 0; + inc() { + this.n++; + } +} +class Opted extends Plain { + static [PROXYABLE] = true; +} +class Counter { + n = 0; + #secret = 1; + inc() { + this.n++; + } + incArrow = () => { + this.n++; + }; + bumpSecret() { + this.#secret++; + } + get secret() { + return this.#secret; + } +} +const held = createClassyStore({plain: new Plain(), opted: new Opted()}); +let heldCalls = 0; +subscribe(held, () => heldCalls++, {sync: true}); +held.plain.inc(); +console.log( + 'plain.inc(): notifications', + heldCalls, + ', plain.n', + held.plain.n, + ', snapshot', + snapshot(held).plain.n, +); +held.opted.inc(); +console.log( + 'opted.inc() (PROXYABLE): notifications', + heldCalls, + ', opted.n', + held.opted.n, +); + +const counter = createClassyStore(new Counter()); +let calls = 0; +subscribe(counter, () => calls++, {sync: true}); +snapshot(counter); +counter.inc(); +console.log( + 'counter.inc(): notifications', + calls, + ', snapshot n', + snapshot(counter).n, +); +counter.incArrow(); +console.log( + 'counter.incArrow(): notifications', + calls, + ', live n', + counter.n, + ', snapshot n', + snapshot(counter).n, +); +const {inc} = counter; +attempt( + 'detached prototype method inc()', + () => (inc(), `notifications ${calls}`), +); +attempt('counter.bumpSecret() (#private)', () => counter.bumpSecret()); +attempt('counter.secret (getter over #private)', () => counter.secret); + +console.log('--- p07 frozen'); +const frozen = Object.freeze({nested: {a: 1}, n: 1}); +const withFrozen = createClassyStore({config: frozen}) as { + config: {nested: {a: number}; n: number; extra?: number}; +}; +console.log('config is kept as it is:', withFrozen.config === frozen); +attempt('config.n = 2', () => ((withFrozen.config.n = 2), withFrozen.config.n)); +attempt( + 'config.extra = 1', + () => ((withFrozen.config.extra = 1), withFrozen.config.extra), +); +attempt('Object.keys(config)', () => Object.keys(withFrozen.config).join(',')); +const root = createClassyStore({a: 1, child: {n: 1}}); +attempt('Object.freeze(store)', () => Object.isFrozen(Object.freeze(root))); +attempt( + ' then a read', + () => `${root.a}, ${root.child.n}, keys ${Object.keys(root).join(',')}`, +); + +console.log('--- p08 collections'); +const raw = {id: 1}; +const rows = createClassyStore({ + list: [raw], + map: reactiveMap(), + set: reactiveSet(), +}); +rows.map.set(raw, 'by raw'); +console.log( + 'get(raw):', + rows.map.get(raw), + ' get(proxy):', + rows.map.get(rows.list[0]), + ' get(snapshot):', + rows.map.get(snapshot(rows).list[0]), +); +rows.map.set(rows.list[0], 'by proxy'); +console.log( + 'after set(proxy): size =', + rows.map.size, + ', get(raw) =', + rows.map.get(raw), +); +console.log('map instanceof Map:', rows.map instanceof Map); +rows.set.add(raw); +rows.set.add(rows.list[0]); +console.log('set.add(raw), set.add(proxy): size =', rows.set.size); + +console.log('--- p10 raw'); +const rawState = {n: 0, list: [{id: 1}, {id: 2}]}; +const live = createClassyStore(rawState); +live.n = 5; +live.list.reverse(); +console.log( + 'the raw object after writes through the store: n', + rawState.n, + ', list', + rawState.list.map((r) => r.id).join(','), +); + +console.log( + '--- API question 4: a base class whose constructor returns the store', +); +class Store { + constructor() { + // biome-ignore lint/correctness/noConstructorReturn: the experiment + return createClassyStore(this); + } +} +class Derived extends Store { + n = 0; + #secret = 1; + items = [{id: 1}]; + incArrow = () => { + this.n++; + }; + bumpSecret() { + this.#secret++; + } + get secret() { + return this.#secret; + } + get double() { + return this.n * 2; + } +} +const derived = new Derived(); +let derivedCalls = 0; +subscribe(derived, () => derivedCalls++, {sync: true}); +const firstSnapshot = snapshot(derived); +console.log( + 'first snapshot: own keys', + Object.keys(firstSnapshot).join(','), + ', items frozen', + Object.isFrozen(firstSnapshot.items), +); +attempt( + 'first snapshot read of the getter over #private', + () => firstSnapshot.secret, +); +const {incArrow} = derived; +incArrow(); +console.log( + 'detached arrow method: notifications', + derivedCalls, + ', live n', + derived.n, + ', snapshot n', + snapshot(derived).n, + ', double', + snapshot(derived).double, +); +attempt( + 'bumpSecret() (#private)', + () => ( + derived.bumpSecret(), + `secret ${derived.secret}, notifications ${derivedCalls}` + ), +); +derived.items[0].id = 2; +console.log( + 'nested write: notifications', + derivedCalls, + ', snapshot', + JSON.stringify(snapshot(derived).items), +); +attempt('snapshot(derived).secret', () => snapshot(derived).secret); +``` + +Output: + +```text +--- p01 wrapping +plain: wrapped +array: wrapped +nullProto: wrapped +instance: kept as it is +frozen: kept as it is +date: kept as it is +map: kept as it is +fn: wrapped +Model: wrapped +function read twice is the same: true +store.Model.label -> undefined +new store.Model() instanceof store.Model -> false +two.a === two.b: true +after two.a.id = 5: two.b.id = 5 , shared.id = 5 +--- p02 classes +plain.inc(): notifications 0 , plain.n 1 , snapshot 1 +opted.inc() (PROXYABLE): notifications 1 , opted.n 1 +counter.inc(): notifications 1 , snapshot n 1 +counter.incArrow(): notifications 1 , live n 2 , snapshot n 1 +detached prototype method inc() -> notifications 2 +counter.bumpSecret() (#private) THROWS TypeError: Cannot access invalid private field (evaluating 'this.#secret') +counter.secret (getter over #private) THROWS TypeError: Cannot access invalid private field (evaluating 'this.#secret') +--- p07 frozen +config is kept as it is: true +config.n = 2 THROWS TypeError: Attempted to assign to readonly property. +config.extra = 1 THROWS TypeError: Attempting to define property on object that is not extensible. +Object.keys(config) -> nested,n +Object.freeze(store) -> true + then a read -> 1, 1, keys a,child +--- p08 collections +get(raw): by raw get(proxy): by raw get(snapshot): by raw +after set(proxy): size = 1 , get(raw) = by proxy +map instanceof Map: false +set.add(raw), set.add(proxy): size = 1 +--- p10 raw +the raw object after writes through the store: n 5 , list 2,1 +--- API question 4: a base class whose constructor returns the store +first snapshot: own keys n,items,incArrow,secret,double , items frozen false +first snapshot read of the getter over #private THROWS TypeError: Cannot access invalid private field (evaluating 'this.#secret') +detached arrow method: notifications 1 , live n 1 , snapshot n 1 , double 2 +bumpSecret() (#private) -> secret 2, notifications 1 +nested write: notifications 2 , snapshot [{"id":2}] +snapshot(derived).secret THROWS TypeError: Cannot access invalid private field (evaluating 'this.#secret') +``` + +### Reproductions run on our source and on the spike + +`repro.ts`: + +```ts +// Run as: bun repro.ts +// Reproductions of stage 1 findings 1, 8, 29, 45, 66 and 71, and the +// base-class experiment for API question 4. +import {attempt} from './helpers.js'; + +const {createClassyStore, snapshot, subscribe} = await import(process.argv[2]); +const basic = (value: unknown) => ({ + value, + writable: true, + enumerable: true, + configurable: true, +}); + +{ + const store = createClassyStore({a: 1}) as Record; + let calls = 0; + subscribe(store, () => calls++, {sync: true}); + snapshot(store); + Object.defineProperty(store, 'b', basic(2)); + console.log( + 'finding 1: define a new key: notifications', + calls, + ', in snapshot', + 'b' in snapshot(store), + ); +} +{ + const other = {n: 99}; + const s = createClassyStore({child: {n: 1}, rows: [{id: 1}]}) as any; + s.child.n; + Object.defineProperty(s, 'child', basic(other)); + console.log( + 'finding 45: redefine child: live child.n', + s.child.n, + ', snapshot', + snapshot(s).child.n, + ); + s.rows[0]; + Object.defineProperty(s.rows, 0, basic(7)); + console.log( + 'finding 71: redefine rows[0] as 7: live', + JSON.stringify(s.rows[0]), + ', snapshot', + JSON.stringify(snapshot(s).rows[0]), + ); +} +{ + const store = createClassyStore({dict: {a: 1}}) as any; + let calls = 0; + subscribe(store, () => calls++, {sync: true}); + const before = snapshot(store); + delete store.dict.missing; + console.log( + 'finding 29: delete a missing key: notifications', + calls, + ', same snapshot', + before === snapshot(store), + ); + delete store.dict.a; + console.log(' delete a present key: notifications', calls); +} +{ + const store = createClassyStore({n: 1, other: {x: 1}}) as any; + store.self = store; + attempt('finding 8: snapshot of a store that holds itself', () => { + const snap = snapshot(store); + const first = `self is the snapshot: ${snap.self === snap}, frozen: ${Object.isFrozen(snap)}`; + store.n = 2; + const next = snapshot(store); + return `${first}; after a write: n ${next.n}, self is the new snapshot: ${next.self === next}, sibling shared: ${next.other === snap.other}`; + }); + const ring = createClassyStore({ + a: {name: 'a'}, + b: {name: 'b'}, + list: [] as unknown[], + }) as any; + ring.a.next = ring.b; + ring.b.next = ring.a; + ring.list.push(ring.list); + attempt(' a ring of two objects, and a list that holds itself', () => { + const snap = snapshot(ring); + return `a.next.next === a: ${snap.a.next.next === snap.a}, list[0] === list: ${snap.list[0] === snap.list}, all frozen: ${Object.isFrozen(snap.a) && Object.isFrozen(snap.b) && Object.isFrozen(snap.list)}`; + }); +} +{ + const store = createClassyStore({outer: {inner: {x: 1}}}) as any; + const outer = store.outer; + const inner = outer.inner; + delete store.outer; + Object.defineProperty(outer, 'inner', {writable: false, configurable: false}); + snapshot(inner); + snapshot(inner); + inner.back = outer; + subscribe(inner, () => {})(); + console.log('finding 66: about to read'); + // The unmodified library never returns from this read; run under `timeout`. + console.log('finding 66: inner.x =', inner.x); +} +{ + class Store { + constructor() { + // biome-ignore lint/correctness/noConstructorReturn: the experiment + return createClassyStore(this); + } + } + class Todos extends Store { + items = [{id: 1}]; + filter = 'all'; + setFilter = (value: string) => { + this.filter = value; + }; + } + const todos = new Todos(); + let calls = 0; + subscribe(todos, () => calls++, {sync: true}); + const first = snapshot(todos); + const {setFilter} = todos; + setFilter('done'); + console.log( + 'question 4: fields defined through the proxy: first snapshot items frozen', + Object.isFrozen(first.items), + ', arrow method notifications', + calls, + ', snapshot filter', + snapshot(todos).filter, + ); +} +``` + +Output on the unmodified source. The run was stopped by `timeout 8` at the read that never returns (finding 66), so the last block did not run: + +```text +finding 1: define a new key: notifications 0 , in snapshot false +finding 45: redefine child: live child.n 1 , snapshot 1 +finding 71: redefine rows[0] as 7: live {"id":1} , snapshot {"id":1} +finding 29: delete a missing key: notifications 1 , same snapshot false + delete a present key: notifications 2 +finding 8: snapshot of a store that holds itself THROWS Error: @codebelt/classy-store: circular reference detected in snapshot + a ring of two objects, and a list that holds itself THROWS Error: @codebelt/classy-store: circular reference detected in snapshot +finding 66: about to read +exit 124 +``` + +Output on the spike copy: + +```text +finding 1: define a new key: notifications 1 , in snapshot true +finding 45: redefine child: live child.n 99 , snapshot 99 +finding 71: redefine rows[0] as 7: live 7 , snapshot 7 +finding 29: delete a missing key: notifications 0 , same snapshot true + delete a present key: notifications 1 +finding 8: snapshot of a store that holds itself -> self is the snapshot: true, frozen: true; after a write: n 2, self is the new snapshot: true, sibling shared: true + a ring of two objects, and a list that holds itself -> a.next.next === a: true, list[0] === list: true, all frozen: true +finding 66: about to read +finding 66: inner.x = 1 +question 4: fields defined through the proxy: first snapshot items frozen true , arrow method notifications 1 , snapshot filter done +exit 0 +``` + +`repro2.ts`: + +```ts +// Run as: bun repro2.ts +// Reproductions of stage 1 findings 32, 43 and 46. +import {attempt} from './helpers.js'; + +const {createClassyStore, snapshot, subscribe} = await import(process.argv[2]); + +{ + let runs = 0; + const store = createClassyStore({ + get view() { + runs++; + return {value: (this as any).nope}; + }, + }) as any; + const same = store.view === store.view; + console.log( + 'finding 32: getter over a missing property: same object', + same, + ', runs', + runs, + ); + store.nope = 7; + console.log( + ' after the property appears:', + store.view.value, + ', runs', + runs, + ); + delete store.nope; + console.log(' after it is deleted:', store.view.value, ', runs', runs); +} +{ + class Name { + first = 'a'; + last = 'b'; + get full() { + return `${this.first} ${this.last}`; + } + set full(value: string) { + [this.first, this.last] = value.split(' '); + } + } + const store = createClassyStore(new Name()); + const seen: string[] = []; + subscribe(store, () => seen.push(snapshot(store).full), {sync: true}); + store.full = 'c d'; + console.log( + 'finding 43: a setter that writes two fields: subscriber saw', + JSON.stringify(seen), + ); +} +{ + const raw = {config: {nested: {a: 1}}}; + const store = createClassyStore(raw); + store.config.nested.a; + Object.freeze(raw.config); + attempt( + 'finding 46: read after freezing the raw object', + () => store.config.nested.a, + ); + attempt(' snapshot after that', () => JSON.stringify(snapshot(store))); +} +``` + +Output on the unmodified source: + +```text +finding 32: getter over a missing property: same object false , runs 2 + after the property appears: 7 , runs 3 + after it is deleted: undefined , runs 4 +finding 43: a setter that writes two fields: subscriber saw ["c b","c d"] +finding 46: read after freezing the raw object THROWS TypeError: Proxy handler's 'get' result of a non-configurable and non-writable property should be the same value as the target's property + snapshot after that -> {"config":{"nested":{"a":1}}} +``` + +Output on the spike copy: + +```text +finding 32: getter over a missing property: same object true , runs 1 + after the property appears: 7 , runs 2 + after it is deleted: undefined , runs 3 +finding 43: a setter that writes two fields: subscriber saw ["c d"] +finding 46: read after freezing the raw object -> 1 + snapshot after that -> {"config":{"nested":{"a":1}}} +``` + +### The spike + +The whole difference between the repository source at `ac38f2f` and the spike copy. It was run against the reproductions above and nothing else. + +```diff +diff --git a/src/core/core.ts b/src/core/core.ts +index 252b9f1..dabe942 100644 +--- a/src/core/core.ts ++++ b/src/core/core.ts +@@ -100,7 +100,13 @@ function recordDep( + prop, + }); + } else { +- tracker.deps.push({kind: 'value', target: internal.target, prop, value}); ++ tracker.deps.push({ ++ kind: 'value', ++ target: internal.target, ++ prop, ++ value, ++ present: Reflect.has(internal.target, prop), ++ }); + } + } + +@@ -144,7 +150,7 @@ function areDepsValid(deps: DepEntry[]): boolean { + // Check that the property still exists — if it was deleted and + // dep.value was `undefined`, Object.is(undefined, undefined) would + // incorrectly pass without this guard. +- if (!Reflect.has(dep.target, dep.prop)) return false; ++ if (Reflect.has(dep.target, dep.prop) !== dep.present) return false; + if (!Object.is(Reflect.get(dep.target, dep.prop), dep.value)) + return false; + } +@@ -414,7 +420,12 @@ function createNode(target: object, pending?: StoreInternal[]): StoreInternal { + if (descriptor && !('value' in descriptor)) { + // Setters perform their own writes. Use the proxy as `this` so nested + // mutations invalidate their actual owners and notify just once. +- return Reflect.set(_target, prop, value, receiver); ++ transactionDepth++; ++ try { ++ return Reflect.set(_target, prop, value, receiver); ++ } finally { ++ settleTransaction(); ++ } + } + const oldValue = Reflect.get(_target, prop); + const previousChild = internal.childInternals.get(prop); +@@ -493,29 +504,50 @@ function createNode(target: object, pending?: StoreInternal[]): StoreInternal { + + // Own data edges are indexed before a retained alias can be mutated. + // An inherited data property becomes an edge on its first proxy read. +- const child = +- internal.childInternals.get(prop) ?? linkChild(internal, prop, value); ++ const known = internal.childInternals.get(prop); ++ if (known && known.proxy !== value && isReadOnly(getterDesc)) { ++ // Frozen through the raw object since it was indexed. ++ internal.detach(prop); ++ recordDep(internal, prop, value); ++ return value; ++ } ++ const child = known ?? linkChild(internal, prop, value); + recordDep(internal, prop, value); + return child ? child.proxy : value; + }, + + defineProperty(_target, prop, descriptor) { ++ internal.resumeScope(); ++ const before = Object.getOwnPropertyDescriptor(_target, prop); + const defined = Reflect.defineProperty(_target, prop, descriptor); +- // `Object.freeze(proxy)` arrives here once per property. A property that +- // is now read-only holds its value as it is, as if frozen all along. +- const own = defined && Object.getOwnPropertyDescriptor(_target, prop); +- if (own && isReadOnly(own)) { +- const child = internal.childInternals.get(prop); +- // An embedded store's proxy is that value: it remains a child. +- if (child && child.proxy !== own.value) internal.detach(prop); ++ if (!defined) return false; ++ const own = Object.getOwnPropertyDescriptor(_target, prop); ++ // The same bookkeeping as a write: the property's value is its child, or ++ // it has none. A read-only value stays as it is (linkChild refuses it). ++ if ( ++ !own || ++ !('value' in own) || ++ !linkChild(internal, prop, own.value, undefined, own) ++ ) { ++ internal.detach(prop); + } +- return defined; ++ boundMethods.delete(prop); ++ const changed = ++ !before || ++ !own || ++ 'value' in before !== 'value' in own || ++ before.enumerable !== own.enumerable || ++ !Object.is(before.value, own.value) || ++ before.get !== own.get; ++ if (changed) notifyMutation(internal); ++ return true; + }, + + deleteProperty(_target, prop) { + internal.resumeScope(); ++ const had = Object.hasOwn(_target, prop); + const deleted = Reflect.deleteProperty(_target, prop); +- if (deleted) { ++ if (deleted && had) { + internal.detach(prop); + boundMethods.delete(prop); + notifyMutation(internal); +diff --git a/src/core/core.types.ts b/src/core/core.types.ts +index 2ef9388..f912bd8 100644 +--- a/src/core/core.types.ts ++++ b/src/core/core.types.ts +@@ -17,7 +17,13 @@ export type DepEntry = + /** Property name on the parent. */ + prop: string | symbol; + } +- | {kind: 'value'; target: object; prop: string | symbol; value: unknown} ++ | { ++ kind: 'value'; ++ target: object; ++ prop: string | symbol; ++ value: unknown; ++ present: boolean; ++ } + | { + /** Dependency on a computed getter — validated via the computed cache, not raw getter re-execution. */ + kind: 'computed'; +diff --git a/src/snapshot/snapshot.ts b/src/snapshot/snapshot.ts +index afd3c51..ac8464f 100644 +--- a/src/snapshot/snapshot.ts ++++ b/src/snapshot/snapshot.ts +@@ -184,7 +184,7 @@ function snapshotValue( + value: unknown, + parent: StoreInternal, + key: string | symbol, +- inProgress: WeakSet, ++ inProgress: Map, + ): unknown { + const child = parent.childInternals.get(key); + return child +@@ -235,7 +235,7 @@ function installMemoizedGetters(snap: object, target: object): void { + function createSnapshotRecursive( + target: T, + internal: StoreInternal, +- inProgress: WeakSet = new WeakSet(), ++ inProgress: Map = new Map(), + ): T { + // Cache hit: version unchanged → return the same frozen snapshot reference. + const cached = snapshotCache.get(target); +@@ -243,25 +243,29 @@ function createSnapshotRecursive( + return cached[1] as T; + } + +- if (inProgress.has(target)) { +- throw new Error( +- '@codebelt/classy-store: circular reference detected in snapshot', +- ); +- } +- inProgress.add(target); ++ const building = inProgress.get(target); ++ if (building) return building as T; + + let snap: Record | unknown[]; + + if (Array.isArray(target)) { ++ // The array exists before its elements are visited, so an element that ++ // leads back here finds it. ++ const list: unknown[] = []; ++ snap = list; ++ inProgress.set(target, list); + // Only objects can be child nodes; primitives need no key lookup. +- snap = mapOwnArrayElements(target, (value, index) => ++ const mapped = mapOwnArrayElements(target, (value, index) => + typeof value === 'object' && value !== null + ? snapshotValue(value, internal, String(index), inProgress) + : value, + ); ++ list.length = mapped.length; ++ for (const key of Object.keys(mapped)) list[Number(key)] = mapped[Number(key)]; + } else { + // Preserve the prototype chain and install memoized getters on the snapshot. + snap = Object.create(Object.getPrototypeOf(target)); ++ inProgress.set(target, snap); + for (const key of Reflect.ownKeys(target)) { + const desc = Object.getOwnPropertyDescriptor(target, key); + if (!desc || !('value' in desc)) continue; +``` + +### Lookup timing + +`lookup.ts`, run once with `bun --conditions browser --conditions production lookup.ts`: + +```ts +// Order-of-magnitude timing of one keyed lookup. Not a benchmark. +import {SvelteMap} from 'svelte/reactivity'; +import { + createClassyStore, + snapshot, +} from '/packages/classy-store/src/index.ts'; +import {reactiveMap} from '/packages/classy-store/src/collections/index.ts'; + +function time(label: string, run: () => unknown, rounds: number) { + for (let i = 0; i < rounds / 10; i++) run(); + const start = performance.now(); + for (let i = 0; i < rounds; i++) run(); + const ns = ((performance.now() - start) * 1e6) / rounds; + console.log( + `${label}: ${ns < 1000 ? ns.toFixed(0) + ' ns' : (ns / 1000).toFixed(1) + ' µs'}`, + ); +} + +for (const size of [100, 1_000, 10_000]) { + const entries = Array.from( + {length: size}, + (_, i) => [`key${i}`, i] as [string, number], + ); + const last = `key${size - 1}`; + const svelte = new SvelteMap(entries); + const store = createClassyStore({map: reactiveMap(entries)}); + const snap = snapshot(store); + const rounds = size >= 10_000 ? 2_000 : 20_000; + console.log(`--- ${size} entries, get(last key)`); + time(' SvelteMap ', () => svelte.get(last), rounds); + time(' reactiveMap, live store ', () => store.map.get(last), rounds); + time(' reactiveMap, snapshot ', () => snap.map.get(last), rounds); +} +``` + +Output: + +```text +--- 100 entries, get(last key) + SvelteMap : 42 ns + reactiveMap, live store : 754 ns + reactiveMap, snapshot : 3.0 µs +--- 1000 entries, get(last key) + SvelteMap : 26 ns + reactiveMap, live store : 6.1 µs + reactiveMap, snapshot : 33.3 µs +--- 10000 entries, get(last key) + SvelteMap : 17 ns + reactiveMap, live store : 44.6 µs + reactiveMap, snapshot : 346.0 µs +``` + +### Harness + +`build.mjs`: + +```js +// Compile every ports/*.svelte.js module with Svelte's own compiler. +import {compileModule} from 'svelte/compiler'; +import {readdirSync, readFileSync, writeFileSync} from 'node:fs'; + +const dev = process.argv[2] !== 'prod'; +for (const name of readdirSync('ports').filter((f) => + f.endsWith('.svelte.js'), +)) { + const source = readFileSync(`ports/${name}`, 'utf8'); + const {js} = compileModule(source, {filename: name, dev, generate: 'client'}); + writeFileSync(`out/${name.replace('.svelte.js', '.js')}`, js.code); +} +``` + +`run.sh`: + +```sh +#!/bin/sh +# Compile the ports, then run each on Bun with Svelte's client build. +set -e +cd "$(dirname "$0")" +bun build.mjs "$1" +MODE=development +[ "$1" = "prod" ] && MODE=production +for file in out/p*.js; do + echo "=== $(basename "$file") ($MODE) ===" + bun --conditions browser --conditions "$MODE" "$file" 2>&1 || echo "(exit $?)" +done +``` + +`helpers.js`: + +```js +// Shared by every port. Not compiled: plain JavaScript. +export function attempt(label, run) { + try { + const result = run(); + console.log(`${label} -> ${format(result)}`); + } catch (error) { + const first = String(error.message).split('\n')[0]; + console.log(`${label} THROWS ${error.name}: ${first}`); + } +} + +export function format(value) { + if (typeof value === 'function') return `[function ${value.name}]`; + if (typeof value === 'object' && value !== null) { + try { + return JSON.stringify(value); + } catch { + return '[object]'; + } + } + return String(value); +} + +/** Collect console.warn calls made while `run` executes. */ +export function warnings(run) { + const original = console.warn; + const seen = []; + console.warn = (...args) => { + const text = args.filter((a) => typeof a === 'string').join(' '); + seen.push((text.match(/\b[a-z]+(_[a-z]+)+\b/) ?? [text])[0]); + }; + try { + run(); + } finally { + console.warn = original; + } + return seen; +} +``` diff --git a/review/stage-2/valtio.md b/review/stage-2/valtio.md new file mode 100644 index 00000000..6832b288 --- /dev/null +++ b/review/stage-2/valtio.md @@ -0,0 +1,3134 @@ +# Stage 2: Valtio + +## Library, version and commit + +- Library: Valtio, `https://github.com/pmndrs/valtio`. +- Version: 2.3.2, the latest stable tag on 2026-11-18. +- Commit: `15c64d4d7a7a9bd55d750fa6a317b440978a2b25` (2026-05-01), cloned at + tag `v2.3.2` into a scratch folder and read there. +- `proxy-compare` 3.0.1, read from this repository's + `node_modules/.bun/proxy-compare@3.0.1`. Valtio 2.3.2 depends on `^3.0.1`, + and the scratch install resolved the same 3.0.1. +- The ported tests ran on Bun 1.4.4 against `valtio@2.3.2` installed from npm + in the scratch folder, and against our source imported by absolute path. + +## Files read + +Valtio, all whole files, paths relative to `src/`: + +- `vanilla.ts` (459 lines) +- `react.ts` (174 lines) +- `vanilla/utils/subscribeKey.ts`, `devtools.ts`, `proxyMap.ts`, + `proxySet.ts`, `watch.ts`, `deepClone.ts`, `deepProxy.ts` +- `react/utils/useProxy.ts` + +`proxy-compare`: `src/index.ts` (whole file). + +Ours: `core/core.ts`, `core/ownership.ts`, `core/core.types.ts`, +`snapshot/snapshot.ts`, `collections/collections.ts`, +`utils/subscribe-key/subscribe-key.ts`, `utils/devtools/devtools.ts`, +`utils/internal/internal.ts`, `types.ts`, +`frameworks/react/hooks/useClassyStore/useClassyStore.ts` and +`frameworks/react/utils/trackedProxyCache/trackedProxyCache.ts`. + +Not read: Valtio's tests, documentation and website; our `persist`, `history`, +the four non-React adapters, and the React tracking caches other than the one +named above. + +## Summary + +Valtio is our design with three parts left out: it has no `get` trap, no +getter memoization and no transactions. Its `vanilla.ts` is 459 lines with +types and comments; our `core.ts`, `ownership.ts` and `snapshot.ts` are 1,092. + +**Where we are more complicated for the same result:** + +- Ownership. Valtio has no weak references, no suspend and resume and no + pointer to a detached parent, and it gives the same answers in every + detached-subtree case I ported. It also returns from the read that hangs us + (stage 1 finding 66). See V1. +- Functions. Valtio returns a stored function as it is. We wrap it on read, + which is the single cause of stage 1 findings 5, 6 and 42. See V2. +- Snapshot getters. We define an accessor per getter on every snapshot; Valtio + leaves them on the prototype. See V4. +- `subscribeKey`. We snapshot the whole store on every notification to compare + one key. See V8. + +**Where our extra code buys something Valtio does not have** (each measured or +reproduced below): transactions (one notification for a `sort`, where Valtio's +sync mode gives one per row), memoized getters, frozen snapshots, one identity +for raw object, proxy and snapshot in collections, isolation of a throwing +subscriber, deep input without recursion, and a snapshot that survives a +getter that throws. + +**Where both fail in the same way:** stage 1 findings 1, 7, 11, 18, 19, 22, +25, 26 and 29, arrow-function methods, and `#private` fields. + +**New, not in stage 1:** a subscription on a container that has left the +store stops being called once the garbage collector runs, if the caller kept +only one of its rows (V1). In a snapshot, `has()` on a collection of 10,000 +members costs about 245 microseconds, because reading a frozen array is the +slow path in both engines (V10). + +## Findings + +### V1. Ownership without weak references, suspend or resume + +- **What they do.** Each proxy keeps `propProxyStates`, a map from property + to the child's state (`vanilla.ts`, `proxy()`, lines 228-231). That is a + strong link from parent to child and nothing the other way. A child learns + of a parent only through a listener the parent adds to it, and the parent + adds one only while it has a listener itself (`addPropListener`, 232-246; + `addListener`, 254-264). When its last listener goes, the parent takes its + listeners off every child (265-275). Deleting or replacing a property drops + that listener at once (`removePropListener`, 247-253). So an upward link + exists only on a path that ends in a subscriber. Versions come from one + global counter (`versionHolder`, 171 and 198). A proxy nobody listens to + finds out about its children by asking: `ensureVersion` (206-217) walks them + when the global counter has moved since it last looked. +- **What we do.** Every child holds a weak reference to every owner, always + (`ownership.ts:15-17`, `46-54`), and a `FinalizationRegistry` prunes dead + ones (`59-76`). Each write walks `ancestors()` and bumps every owner + (`core.ts:221-224`). A detached, unobserved container is suspended: its + links are cut and its children's versions saved (`ownership.ts:89-114`), + then compared on resume (`116-144`). A suspended child points at its + detached parent, and every trap walks that chain first (`22-23`, `147-156`; + `core.ts:407`, `462`, `516`). +- **Difference in behaviour.** All verified by running; code under "Ported + tests", ports 4, 4b and 4d. + - The reproduction of stage 1 finding 66 prints `inner.x: 1` on Valtio. On + ours the process was killed by the 8-second timeout. + - New. `subscribe(store.list, cb)`, then `store.list = []`, keeping one row + and dropping the unsubscribe function. A write to the row calls `cb` on + both libraries. After a garbage collection Valtio still calls it (5 rounds + of 5); ours does not, because the list was collected (5 rounds of 5). Our + child holds its owner weakly, and nothing else holds a node that has a + listener. When the subscriber stops is decided by the collector. + - The same on both: a child written while its container is out of the + store shows in the snapshot after the container is put back; a subscriber + on a detached container still hears its children; the root no longer + does; a retained row does not keep a replaced list alive (collected in + most rounds on both; the misses are sporadic and on both). + - What Valtio pays for it. A snapshot of an unchanged 1,000-row store after + a write to another store costs 95 microseconds against our 231 + nanoseconds, because the global counter moved and the whole tree is + asked. Writing one row and taking a snapshot costs 259 to 284 + microseconds against our 124 to 129. The first subscribe and last + unsubscribe on that store cost 375 microseconds against our 84 + nanoseconds, because listeners are added to and removed from every node. +- **Proposal: adapt.** + 1. Remove the detached-parent pointer and the walk in `resumeScope()`. + Stage 1 finding 72 found that it adds nothing to correct behaviour and + causes findings 66 to 68. Valtio is a working store of the same shape + with no link from a detached child to its former parent. + 2. Do not take the pull. Our eager bump along `ancestors()` is what makes a + snapshot of an unchanged store a cache hit. It is the better half of our + design. + 3. Choose one mechanism against "a retained row keeps removed lists alive", + not two. We have weak links and suspension. Valtio has neither, and gets + the same result from a third rule (links only while observed). With weak + links alone, suspension and its three corrections (finding 72) can go; + what is left to measure is the cost of a write to a row that has many + dead owners not yet collected. This is reasoning from reading, not + measured. + 4. Decide what keeps a subscribed node alive. Either say in the docs that a + subscription lasts while the caller holds the store, the node or the + unsubscribe function, or hold a node strongly for as long as it has a + listener (a module-level set, added on the first listener and removed on + the last). The second makes the collector invisible, and a forgotten + unsubscribe then keeps that node for good, as with any event emitter. +- **Kind:** simplification, bug. +- **Cost:** `ownership.ts` and the three `resumeScope()` calls in `core.ts`. + Not breaking. Medium risk: the memory tests and the owner-order tests + (finding 69) pin today's behaviour. + +### V2. A stored function is returned as it is + +- **What they do.** The proxy handler has two traps, `deleteProperty` and + `set` (`vanilla.ts`, `createHandlerDefault`, 122-158). A read runs no + library code. That works because a child is stored in the object as its + proxy (151-154), and `proxy()` assigns every own writable data property + through the proxy at creation (289-297). A method runs with `this` as the + proxy because it is called on the proxy; nothing is bound. +- **What we do.** The `get` trap (`core.ts:461-500`) looks the descriptor up + the prototype chain (`464`), wraps every function in a transaction closure + (`483-492`), and for an array makes a new wrapper on every read (`486`). +- **Difference in behaviour.** Ports 1 and 6, and the timings. + - A function in an array: `callbacks[0] === callbacks[0]` is `true` on + Valtio and `false` on ours; `splice(indexOf(first), 1)` removes `first` + on Valtio and the last callback on ours (finding 5). + - A class held as data: `store.Model === Model`, its static is readable and + `instanceof` holds on Valtio; none of the three on ours (finding 6). + - A destructured method throws on Valtio (`this` is `undefined`) and works + on ours. That is what the wrapper is for. + - A field read costs 1.6 ns on Valtio and 30.5 ns on ours; three objects + deep, 12 ns and 141 ns. + - Valtio writes proxies into the object it was given: after + `proxy(raw)`, `raw.child` is the proxy. Ours leaves the raw graph alone at + creation (finding 10 lists where it does not). +- **Proposal: adapt.** Keep the trap: binding, transactions and getter + memoization live in it, and they are the class-based design. Wrap only what + is a method: + - An own element of an array is data. Only a function found on the array's + prototype chain is an array method. + - A class is data. It can be told apart without calling it: the `prototype` + property of a class is not writable, that of a function declaration is, + and arrows and methods have none (checked on Bun; the table is under + "Ported tests", port 7). + - Cache the array-method wrappers as the others are. + + This removes findings 5, 6 and 42 and keeps destructured methods working. + Do not copy "the raw object holds proxies": it changes the caller's object + graph. The per-prototype descriptor cache the Solid report proposes is the + answer to the read cost; Valtio's answer is to have no trap. +- **Kind:** bug, performance. +- **Cost:** the `get` trap in `core.ts`. A function read from an array + becomes equal to the function stored, which is a behaviour change in the + expected direction. Low risk. + +### V3. A cycle can be snapshotted + +- **What they do.** `createSnapshotDefault` puts the new snapshot object in + the cache before it fills it in (`vanilla.ts:90`), so a reference back to + an object being built resolves to that object. `useSnapshot` passes a fresh + `WeakMap` to proxy-compare's `isChanged` as its cycle guard + (`react.ts:146-151`). +- **What we do.** A repeat visit throws (`snapshot.ts:246-250`), and the + cache is written after the freeze (`285`). The React hook calls `isChanged` + with no cycle guard (`useClassyStore.ts:100`). +- **Difference in behaviour.** Port 1, case 8: after `store.self = store`, + Valtio gives `snapshot(store).self === snapshot(store)`; ours throws at the + next snapshot, wherever that is taken (finding 8). Valtio's way has a cost + of its own, port 6: when an own getter throws while the snapshot is built, + the half-built object stays in the cache, and the next `snapshot()` returns + it with only the keys filled in before the throw. Ours is not affected. +- **Proposal: adapt, if the owner wants parent pointers in class models to + work.** Keep our per-call `inProgress`, make it a map from target to the + unfinished snapshot, return that for a repeat visit, and freeze after + filling. An object can be referenced before it is frozen. Do not use the + shared cache for this, for the reason above. Then pass a cycle guard to + `isChanged`, and check `cloneSnapshot`, `shallowEqual`, `persist` and + `devtools` for recursion without end. If cycles stay unsupported, throw at + the write that makes one, not at a later snapshot. +- **Kind:** bug, API design. +- **Cost:** about ten lines in `snapshot.ts`, one in `useClassyStore.ts`, and + a check of four utilities. Not breaking. Medium risk. Reasoning from + reading; not prototyped. + +### V4. Snapshot getters stay on the prototype + +- **What they do.** A snapshot is created with the object's own prototype + (`vanilla.ts:86-88`) and nothing is defined for a class getter. It is + inherited, not enumerable, and runs on every read with the snapshot as + `this`. An own accessor (an object-literal getter) is evaluated once while + the snapshot is built and stored as a data property (`96-103`). +- **What we do.** For every snapshot of every class instance, + `installMemoizedGetters` walks the prototype chain and defines an own + accessor per getter, with a new closure each (`snapshot.ts:196-221`). An + inherited getter is defined enumerable (`215`). +- **Difference in behaviour.** Port 2. + - `Object.keys(store)` is `["items"]` on both. `Object.keys(snapshot)` is + `["items"]` on Valtio and `["items","total"]` on ours. `JSON.stringify` + and a spread of our snapshot run every getter and carry its value. + - Three reads of a getter run it three times on Valtio, live and on one + snapshot. Ours runs it once, and not at all for a new snapshot after an + unrelated write. + - Writing a field and taking a snapshot costs 672 ns for a class with no + getter and 1,938 ns for one with eight: about 160 ns per getter per + snapshot. Valtio: 339 and 338. + - Valtio's own-accessor rule is wrong for a getter that derives a list: + `snapshot.open[0]` is the live proxy, in an unfrozen array. Ours keeps the + accessor and answers with snapshot rows. +- **Proposal: adapt.** Keep the memoization; it is the point of class + getters. Stop defining accessors per snapshot. Build, once per class, an + object that inherits from the class prototype and carries the memoizing + accessors, not enumerable, as the class's own are. Cache it by class + prototype and create snapshots from it. The keys of store and snapshot then + agree, the per-snapshot cost goes, and `instanceof` still holds. Own + accessors stay as they are now. This is reasoning from reading; it is not + prototyped. If the owner would rather keep getter values in a spread and in + JSON, keep today's shape and document that a snapshot has more keys than + its store. +- **Kind:** API design, performance. +- **Cost:** `installMemoizedGetters` and what calls it, and the users of + `originalSnapshotAccessor`. Breaking for code that enumerates a snapshot + (`Object.keys`, spread, `JSON.stringify`, `shallowEqual`, the DevTools + payload), and `Object.getPrototypeOf(snapshot)` becomes the derived object. + Medium risk. It is an API shape, so it is cheaper to decide before 1.0. + +### V5. What a getter can ask of `this` + +- **What they do.** Valtio's getters run on the snapshot itself, so + `Object.keys(this)`, `key in this` and `this instanceof C` are answered by + the real object. proxy-compare, for render tracking, records four kinds of + read, not one: `get`, `has`, `getOwnPropertyDescriptor` and `ownKeys` + (`proxy-compare/src/index.ts:128`, `140`, `148`, `152`), and `isChanged` + compares each kind (`288` on). +- **What we do.** A snapshot getter runs on a Proxy over an empty object with + a `get` trap only (`snapshot.ts:80-93`). The store proxy has no `has` or + `ownKeys` trap (`core.ts:405-525`). +- **Difference in behaviour.** Port 2, case 30/31: for a class with fields + `a` and `b`, a getter returning `Object.keys(this).length`, one returning + `'b' in this` and one returning `this instanceof Bag` give `2, true, true` + on a Valtio snapshot and `0, false, false` on ours (findings 31 and 41). + After `delete store.b` the live getters give `1, false` on Valtio and still + `2, true` on ours (finding 30). +- **Proposal: adapt, in our own tracker. Do not call proxy-compare for + this.** I tried both on real snapshots of ours ("Ported tests", prototype + A/B/C): + - A, proxy-compare's `createProxy(snapshot)` as `this`: the three questions + are answered correctly, but every object read through it is a tracking + proxy (`this.rows[0] !== snapshot.rows[0]`), so a getter that returns + rows would hand out proxies. + - B, a Proxy over the frozen snapshot itself with `get`, `has` and + `ownKeys` traps: the questions are answered correctly, values are the + real snapshot values, and the three reads are recorded. The `get` trap + already returns the property's own value, which is what the Proxy rule + for a frozen target asks for. + + So: in `computeWithTracking`, proxy the snapshot, and record `has` and + `ownKeys` as dependencies. On the store, add `has` and `ownKeys` traps that + record the same for an active tracker; a per-node counter bumped when a key + is added or deleted is enough to validate them. +- **Kind:** bug. +- **Cost:** about fifteen lines in `snapshot.ts`; two traps and one + dependency kind in `core.ts`. Not breaking. Low risk. Prototype B had data + properties only; a snapshot with accessors was reasoned, not run. + +### V6. Each subscription knows whether it is still active + +- **What they do.** `subscribe()` keeps a flag per subscription, + `isListenerActive`, set false by the unsubscribe function and checked when + the batched callback runs (`vanilla.ts:325`, `337`, `346`). Each + subscription has its own pending promise (`334-341`). Sync listeners are + called straight from the live `Set` (`202`), with no `try`. +- **What we do.** `deliver()` copies the listeners of every pending node, then + calls each inside `try`/`catch` (`core.ts:314-328`). What is pending is the + node, not the listener (`241`, `308-312`). +- **Difference in behaviour.** Port 3. + + | Case | Valtio | Ours | + | ---------------------------------------------------------- | ------------------------------------------------ | ------------------------------------ | + | A unsubscribes B during delivery, sync and batched (20) | B is not called | B is called once | + | Batched subscriber added after the write (21) | not called | called | + | Sync subscriber added by another during delivery | called in that delivery | not called | + | First sync subscriber throws (23) | the writer gets the error, the second is skipped | logged, the second is called | + | Sync subscriber writes on every call (18) | `RangeError` reaches the writer | `RangeError` goes to `console.error` | + | Subscriber writes until a limit, a second one watches (22) | sees `3, 3, 3` | sees `3, 3, 3` | + | Batched subscriber writes, a timer is due (19) | three callbacks, then the timer | the same | + +- **Proposal.** Adopt the flag: in `subscribe()`, a boolean the unsubscribe + function clears and the listener checks. One line, and it fixes finding 20 + in both modes and across nodes. Adapt for finding 21: queue the listeners + that exist at the write, not the node, which is what a promise per + subscription amounts to. Reject Valtio's error handling and its iteration of + the live set; ours is better on both. Neither library stops a subscriber + that writes for ever, so Valtio has nothing to offer for 18 and 19. +- **Kind:** bug. +- **Cost:** `subscribe`, `notifyMutation` and `flushNotifications` in + `core.ts`. Changes what the tests of findings 20 and 21 pin. Low risk. + +### V7. The `sync` option, and why we do not need one + +- **What they do.** `useSnapshot(proxy, {sync: true})` passes a flag through + to `subscribe` (`react.ts:42-44`, `123`, `134`). The default is batched. + There is no transaction: every `set` trap notifies (`vanilla.ts:155`, + `196-204`). +- **What we do.** Every adapter subscribes sync (`useClassyStore.ts:144-147`), + and a method or an array operation is one transaction (`core.ts:245-306`, + `483-492`). +- **Difference in behaviour.** Port 3 and the timings. Sync notifications for + one operation on 100 rows: + + | Operation | Valtio | Ours | + | ------------------ | -----: | ---: | + | `push(row)` | 1 | 1 | + | `unshift(row)` | 102 | 1 | + | `sort()` | 100 | 1 | + | `reverse()` | 102 | 1 | + | `splice(0, 1)` | 103 | 1 | + | A two-field method | 2 | 1 | + | A two-field setter | 3 | 2 | + + Sorting 1,000 rows with one sync subscriber that takes a snapshot costs 248 + milliseconds on Valtio and 0.9 on ours. This is why Valtio's default is + batched and `sync` is an opt-in for controlled inputs. +- **Proposal: reject the option.** One mode is the better API, and the + transaction code (about 60 lines) is what pays for it. The one thing to fix + on our side is finding 43: run an accessor's setter inside a transaction + (`core.ts:414-418`), so a setter notifies once, as a method does. +- **Kind:** API design. +- **Cost:** three lines in `core.ts`. Changes what the test of finding 43 + pins. Low risk. + +### V8. `subscribeKey` without a snapshot of the whole store + +- **What they do.** It reads the live value once, and again on every + notification, and compares with `Object.is` + (`vanilla/utils/subscribeKey.ts:14-31`). The callback gets the new live + value. +- **What we do.** It takes a snapshot of the whole store on every + notification and compares `snapshot[key]`; the callback gets the new and + the previous snapshot value (`subscribe-key.ts:26-41`). +- **Difference in behaviour.** Port 7. + - A key that holds an object: a nested write does not call Valtio's + callback (the live proxy is the same object) and does call ours, with a + snapshot. Ours is the more useful contract. + - Cost. A store with `count` and 1,000 rows, `subscribeKey(store, 'count', + …, {sync: true})`, then writes to rows: 122 microseconds per write on + ours, against 1.0 with a plain sync subscriber. Valtio: 0.4. Every row + write rebuilds the root and list snapshots to learn that `count` did not + change. Where a mounted component takes the same snapshot anyway, the + work is shared; where `subscribeKey` is used alone, it is all extra. +- **Proposal: adapt.** Keep our callback contract and compare without the + root snapshot: read the live value; if it is a store node, compare the node + and its version, and call `snapshot()` on that node only when one of them + changed; otherwise compare with `Object.is`. A key that is a getter keeps + today's path, because a live getter and a snapshot getter return different + objects. +- **Kind:** performance. +- **Cost:** about fifteen lines in `subscribe-key.ts`. Not breaking. Low + risk. + +### V9. `devtools` + +- **What they do** (`vanilla/utils/devtools.ts`). + 1. `enabled` defaults to "not a production build" (`45-47`), and it warns + when enabled with no extension (`52-54`). + 2. Every other option is passed on to `connect` (`41`, `60`). + 3. An action is named from the operations in it, `set:count, delete:todos.1` + (`58`, `62-65`). + 4. It handles a dispatched action (`93-102`), `JUMP_TO_ACTION` and + `JUMP_TO_STATE` (`103-113`), `COMMIT` (`114-118`) and `IMPORT_STATE` + (`119-140`). + 5. It sends a shallow copy of the snapshot's own data (`74`). + 6. The time-travel flag is cleared by the next notification (`71-72`, + `108`). If a jump changes nothing, the flag stays set and the next real + change is not sent. Read, not run. +- **What we do** (`utils/devtools/devtools.ts`). `enabled` defaults to `true` + everywhere (`57`). Only `name` reaches `connect` (`66`). Every action is + `STORE_UPDATE` (`78`). Only the two jumps are handled, skipping getters and + methods (`83-100`). The flag is cleared in a microtask (`104-110`). The + payload is the snapshot, so every getter is run and sent (V4). It returns a + handle with `dispose()`. +- **Proposal.** + - Adapt 1: we have no production build to key on, so either require + `enabled` or default it from `process.env.NODE_ENV`. It belongs with the + stage 3 question of a development build. + - Adopt 2: pass unknown options through to `connect`. + - Adapt 3: we can do better than Valtio. The outermost transaction knows + which method was called, so the action can be `Cart.addItem`. That needs + a small internal hook in `transactional()`. + - Adopt `COMMIT` from 4; `IMPORT_STATE` is optional. + - Reject 6: ours is sounder. Keep our handle. +- **Kind:** API design, diagnostics. +- **Cost:** `devtools.ts`, and a hook in `core.ts` for the action name. The + `enabled` default is the only breaking part. Low risk. + +### V10. Reactive collections + +- **What they do.** `proxyMap` and `proxySet` keep a native `Map` from key to + index beside a `data` array (`proxyMap.ts:58`, `83-86`), and an `epoch` + counter that reads touch so that they are tracked (`98`, `105`). The index + is cloned once per snapshot (`60-69`, `87-93`). A deleted slot is left as a + hole (`130`). Mutators throw on a snapshot (`109-111`). The return type + names the snapshot's type, without mutators (`200-202`), through a hook in + `Snapshot` (`vanilla.ts:47-48`). Both are built on + `unstable_getInternalStates` (`proxyMap.ts:3`). +- **What we do.** A dense array and a linear scan with `identityOf` + (`collections.ts:16-33`). The constructors drop duplicates with a native + `Map` or `Set` on the values as given (`57-71`, `212-223`). +- **Difference in behaviour.** Port 5. + + | Case | Valtio | Ours | + | --------------------------------------------------------------- | ---------------------------------------- | ------------------------------------------------------ | + | `set.has` by raw, proxy, snapshot row | true, true, false | true, true, true | + | `map.get` by raw, proxy, snapshot row | found, missing, missing | found, found, found | + | `map.set(raw)` then `map.set(proxy)`: size | 2 | 1 | + | `+0` then `-0`: size when added, when constructed (33) | 1, 1 | 2, 1 | + | Constructed from `[raw, proxy]`: size (34) | 1 | 2 | + | Mutator on a snapshot (16) | `Cannot perform mutations on a snapshot` | `TypeError: Attempted to assign to readonly property.` | + | Backing array after 10,000 set and delete pairs, one entry left | length 10,000 | length 1 | + | 1,000 `has()` on 10,000 numbers, live | 0.2 ms | 22 ms | + | The same on a snapshot | 0.07 ms | 245 ms | + + Our snapshot lookup is eleven times slower than our live one because it + scans a frozen array. Reading a frozen array of 10,000 was 28 times slower + than an unfrozen one on Bun and 2.7 times on Node 24 (micro-benchmark under + "Ported tests"). Valtio's snapshot arrays are not frozen, but their + elements are non-writable, which measured as slow or slower; its lookups + are fast because of the index, not the array. +- **Proposal.** + - Reject Valtio's structure for live state: holes that never close, an + extra counter, weaker identity, and a dependence on internals. + - Adapt its per-snapshot index. For a frozen backing array, build a `Map` + from identity to index on the first lookup and keep it in a `WeakMap` + keyed by the array. It cannot go stale, because the array cannot change. + In a prototype over real snapshots of ours, 1,000 lookups in 10,000 + members took about 0.8 ms with the index build included, against 101 ms + (numbers) and 251 ms (objects) today. + - Adopt one membership rule everywhere: the constructors should compare as + `add` and `set` do, by `identityOf`, and all of them should treat `+0` + and `-0` as one, as a native `Set` does. That closes findings 33 and 34. + - Adopt the type hook: let a class name its own snapshot type, and give + `ReactiveMap` and `ReactiveSet` one without `set`, `add`, `delete` and + `clear`. That closes finding 16 at compile time; a check in each mutator + can give Valtio's clearer message at run time. +- **Kind:** performance, bug, API design. +- **Cost:** `collections.ts` and `types.ts`. The type change breaks code that + calls a mutator on a snapshot, which already throws. Low risk. + +### V11. `Snapshot` keeps a tuple a tuple + +- **What they do.** `Snapshot` has no branch for arrays + (`vanilla.ts:47-53`). The mapped type handles arrays and tuples. +- **What we do.** `T extends Array ? ReadonlyArray>` + comes first (`types.ts:38-44`). +- **Difference in behaviour.** Type-checked in the scratch folder with + TypeScript 7.0.2, with a deliberately wrong assertion as a control: + Valtio's `Snapshot<[string, number]>` is `readonly [string, number]`, ours + is `readonly (string | number)[]` (finding 14). Our type with the array + branch deleted gives the tuple, and still gives + `readonly {readonly id: number}[]` for an array of objects. +- **Proposal: adopt.** Delete the array branch. +- **Kind:** bug (types). +- **Cost:** one line in `types.ts` and the type tests that pin finding 14. I + did not run the repository's 54 type tests against the change. + +### V12. Opt-out with `ref()`, and snapshots that are not frozen + +- **What they do.** Every object is proxied unless it is iterable (arrays + excepted) or one of nine listed built-in types (`vanilla.ts`, + `canProxyDefault`, 64-76). A class instance is proxied. `ref(obj)` opts one + object out (`369-372`). A snapshot is not frozen: its properties are + non-writable but configurable, and it stays extensible (`101-107`, `118`). + The comment gives the reason: a frozen object forces proxy-compare to copy + it before wrapping it (`proxy-compare/src/index.ts:43`). +- **What we do.** Opt-in: arrays, plain objects and classes marked + `PROXYABLE` (`internal.ts:70-82`). A frozen object is a value + (`core.ts:336-342`). Snapshots are frozen (`snapshot.ts:282`). +- **Difference in behaviour.** Port 6. + - A nested class instance with no marker: Valtio proxies it and notifies. + Ours holds it as it is, so a write to it notifies no one and an earlier + snapshot shows the later value (`before.point.x` is 5). + - `#private`: a method that reads one throws a `TypeError` on both, on the + store and on the snapshot. + - On a Valtio snapshot, `snapshot.extra = 1`, `snapshot.list.push(3)` and + `delete snapshot.child` all succeed, and the next `snapshot()` returns + that changed object. Ours throws on each. + - To hold a plain object untracked, Valtio has `ref()` and its owner can + still change it. Our only way is to freeze it, which stops the owner too. +- **Proposal.** Reject opt-out as the default: opt-in is the safer rule for + host objects and for `#private`. Reject unfrozen snapshots: immutability is + a ground rule, and Valtio's snapshot can be changed in three ways. A + `ref()`-like marker for a plain object can be added after 1.0 without + breaking anything, so it need not be decided now. Say in the docs that an + unmarked class instance is shared between the store and every snapshot. +- **Kind:** API design, docs. +- **Cost:** none now. + +### V13. Things we do that Valtio shows are needed + +No change proposed. Each was reproduced (ports 6 and 3). + +- **Our registry of tracking proxies** (`trackedProxyCache.ts`, + `core.ts:19-30`, `409-412`). Valtio unwraps a tracked value with + proxy-compare's `getUntracked` (`vanilla.ts:149`). That function returns + `null` for a tracking proxy over a class-instance snapshot, on both + libraries' proxy-compare, because it tests the proxy's prototype + (`proxy-compare/src/index.ts:28`, `367`). Our registry does not have that + hole. +- **The work list at creation** (`core.ts:530-543`). An object nested 20,000 + deep overflows the stack in `proxy()`; ours accepts it. +- **`createClassyStore(store) === store`** (`core.ts:396-397`). Valtio wraps + the proxy again. +- **A getter that throws does not poison the snapshot.** See V3. +- **A subscriber that throws does not stop the others.** See V6. + +## Stage 1 findings that have a counterpart in Valtio + +"Run" means a port below shows it. "Read" means it follows from the source +and was not run. + +| Finding | What Valtio does | Basis | +| ------: | ------------------------------------------------------------------------------------------------------------------------- | --------- | +| 1 | The same. No `defineProperty` trap: the value is set, nobody is told, the snapshot is stale until the next write. | Run | +| 5 | No wrapper. A function in an array is itself on every read; `indexOf` finds it. | Run | +| 6 | No wrapper. A class read from the store is the class: statics and `instanceof` work. | Run | +| 7 | The same miss. `includes(raw)` is `false`, also right after `push(row)`. | Run | +| 8 | Works. `snapshot(store).self === snapshot(store)`. | Run | +| 9 | Connected. A raw object that is already a proxy's target is given that proxy, marked class or not. | Run | +| 10 | By design, and from creation: the raw object holds the child proxies. | Run | +| 11 | The same. A write through the raw object is invisible to subscribers and snapshots. | Run | +| 12 | The same. Iterables other than arrays are not proxied. | Read | +| 14 | A tuple stays a tuple. | Run | +| 16 | The snapshot's type has no mutators, and calling one throws a named error. | Run | +| 18 | The same recursion. The `RangeError` reaches the writer. | Run | +| 19 | The same. Back-to-back microtasks run before a timer that is due. | Run | +| 20 | Not called, in both modes. | Run | +| 21 | A late batched subscriber never hears an earlier write. A sync one added during delivery is called in that delivery. | Run | +| 22 | The same. A second subscriber sees the final state three times. | Run | +| 23 | Sync: the error reaches the writer and later subscribers are skipped. Batched: the subscription's own promise rejects. | Run, read | +| 24 | Depth first through each listener set in subscription order. Not inside out either. | Read | +| 25 | The same. `store.slot.n` is 2 and `snapshot(store).slot.n` is 1. | Run | +| 26 | The same, and the hook's comment documents it (`react.ts:79-98`). | Read | +| 27 | A child holds a parent that has a listener, strongly. A removed list with no listener is collectable. | Run | +| 29 | The same. A delete of a missing key notifies and replaces the snapshot. | Run | +| 30 | No live memoization, so the getter is right after the delete. | Run | +| 31, 41 | `this` in a snapshot getter is the snapshot: own keys, `in` and `instanceof` are right. | Run | +| 32 | Every getter runs on every read. | Run | +| 33, 34 | One member in each case. | Run | +| 36, 37 | Nothing is memoized, so nothing is stale and nothing is lost. | Run | +| 40 | Nothing is frozen at all. | Run | +| 42 | No wrapper, as for 5 and 6. | Read | +| 43 | Worse: a two-field setter notifies three times, a two-field method twice. | Run | +| 45 | Different and also wrong: the new object is held raw, a write to it tells nobody, and the snapshot holds the live object. | Run | +| 46 | Reading works. A strict-mode write throws a Proxy `TypeError`, after one notification. | Run | +| 50 | The descriptor's value is the proxy, because the raw object holds proxies. | Run | +| 61, 66 | No suspension and no `defineProperty` trap. The read returns 1. | Run | +| 72 | See V1. | Run | + +## The eight API questions, from Valtio's point of view + +1. **Should synchronous notification be the default for `subscribe()`?** + Valtio's default is batched, for `subscribe` (third positional argument, + `vanilla.ts:316`, `330-341`) and for `useSnapshot` (`sync` option). It has + to be: with no transactions, sync mode gives one notification per element + written (V7). So Valtio shows that sync without grouping cannot be a + default. It says nothing against a sync default where writes are grouped. +2. **Writes outside a store method: allowed, warned about, or grouped? + Does `batch()` belong?** Allowed, and the normal idiom: the hook's own + example is `++state.count` in a click handler (`react.ts:60`). Never + warned about. Grouped by the microtask only. There is no `batch()`: batched + mode does not need one and sync mode has none. No position on `batch()` + itself. +3. **Should snapshot getters stay enumerable own accessors?** No. A class + getter is not an own property of a Valtio snapshot and is not enumerable; + store and snapshot list the same keys. See V4. +4. **Can arrow-function methods and `#private` fields be made to work?** + Valtio does not try. Run on both libraries: an arrow method changes the + raw object and tells nobody; a method that reads a `#private` field throws + a `TypeError`. Valtio adds one failure we do not have: a destructured + method loses `this`. No position on a remedy. +5. **Should native `Map` and `Set` be reactive directly?** No. Valtio leaves + them alone (the iterable rule, `vanilla.ts:67`) and offers `proxyMap` and + `proxySet` as separate factories, with `unstable_deepProxy` to convert the + native ones in an input tree (`deepProxy.ts:38-55`) and `isProxyMap` and + `isProxySet` to test for them. The same choice as ours. +6. **Opt-in or opt-out for nested class instances?** Opt-out, with `ref()`. + Two signs that it costs something: the list of built-in types it has to + exclude by name (`vanilla.ts:64-76`), and a hook that lets an application + replace the rule (`unstable_replaceInternalFunction('canProxy', …)`, + `409-447`). See V12. +7. **Are entry points, export names and adapter names consistent across the + five frameworks?** No position: the package has one adapter. Its entries + are `valtio`, `valtio/vanilla`, `valtio/react`, `valtio/utils`, + `valtio/vanilla/utils` and `valtio/react/utils`. Two observations. The hook + is named for what it returns, `useSnapshot`, not for the library. And + Valtio is inconsistent where we are not: `subscribe(p, cb, true)` and + `subscribeKey(p, key, cb, true)` take a positional boolean, while the hook + takes `{sync: true}`. Our `{sync}` object everywhere is the better shape. +8. **What development-only diagnostics would catch our silent failures?** + Valtio has none for them: arrow methods, raw writes, `#private` and writes + after an `await` are as silent there. What it does have: + - The switch: `import.meta.env?.MODE !== 'production'` in the ESM build + and `process.env.NODE_ENV !== 'production'` in the CommonJS build + (checked in the published `esm/vanilla.mjs` and `vanilla.js`). + - A warning when `subscribe` or `snapshot` is given something that is not + a proxy (`vanilla.ts:319-321`, `356-358`). Ours throws, which is better. + - The paths a component tracked, shown in React DevTools through + `useDebugValue` and proxy-compare's `affectedToPathList` + (`react.ts:24-35`, `169-171`). We have no equivalent, and it answers + "why did this component re-render". Worth adopting in a development + build. + - A named error for a mutator called on a collection snapshot (V10). + +## Rough timings + +One process on Bun 1.4.4, an Apple M1 Max that other agents were using, three +rounds per case, best round. These are my own scripts (`bench.ts`, +`bench2.ts`), not the repository's benchmark, and they show orders of +magnitude only. Where rows are mentioned, the store holds 1,000 of +`{id, done, meta: {tags: {a}}}`, which is 3,002 nodes. + +| Operation | Valtio 2.3.2 | Ours | +| ------------------------------------------------------------------ | -----------: | -------: | +| Read a field | 1.6 ns | 30.5 ns | +| Read a field three objects deep | 12.1 ns | 141.0 ns | +| Write a field, no subscriber | 93.8 ns | 148.5 ns | +| Write a field, one sync subscriber | 132.8 ns | 155.1 ns | +| Call a method that writes one field | 104.0 ns | 167.6 ns | +| Take a cached snapshot | 27.6 ns | 22.9 ns | +| Write one of 1,000 rows, then snapshot (unobserved) | 283.7 us | 124.1 us | +| Write one of 1,000 rows, then snapshot (observed) | 258.8 us | 128.7 us | +| Write to another store, then snapshot an unchanged 1,000-row store | 95.0 us | 231.1 ns | +| Create a store of 1,000 rows | 2.51 ms | 1.52 ms | +| Create a store of 1,000 rows and snapshot it | 4.55 ms | 4.36 ms | +| Sort 1,000 rows, one sync subscriber that snapshots | 247.92 ms | 884.9 us | +| Read a getter that sums 1,000 rows, nothing changed | 23.2 us | 112.0 ns | +| Subscribe and unsubscribe, the only subscriber | 375 us | 84 ns | +| Subscribe and unsubscribe, a second subscriber | 83 ns | 66 ns | + +Reading and writing are where Valtio is cheaper, and both come from having no +`get` trap and no walk on write. Everything that involves a snapshot, a +getter or a subscription is cheaper on ours. + +## What was verified by running, and what was only read + +Run, on Bun 1.4.4, with the code and output below: + +- Every behaviour in V1 to V8 and V10 to V13 that is stated as a difference, + and every table row marked "Run". +- The timings above and the ones quoted in V4, V8 and V10. +- The two prototypes: tracking a snapshot getter's reads (V5) and a lazy + index for a frozen array (V10). +- The type assertions in V11, with a control that fails. + +Only read: + +- V9 (`devtools`) in full. No extension was mocked. +- Valtio's batched subscriber that throws (finding 23, second half), the + notification order across owners (finding 24), and finding 42. +- Valtio's React hook. Nothing was rendered. + +Reasoning, not tested: + +- The proposals in V1 (dropping suspension, holding a listened-to node + strongly), V3 (an in-progress map with freeze after filling) and V4 (one + derived prototype per class). Each needs a spike in stage 3. + +Not done: + +- Nothing was run on Node except the frozen-array micro-benchmark. +- The memory checks use `Bun.gc(true)` and a `WeakRef`. JavaScriptCore scans + the stack conservatively, so a single "not collected" is noise; only the + results that were the same in all five rounds are relied on. + +## Ported tests + +Everything here was written and run in the scratch folder, with +`valtio@2.3.2` installed there. Each scenario runs once on Valtio and once on +our source, imported by absolute path. `[valtio]` and `[classy]` mark the two +runs in the output. A number in a heading is the stage 1 finding the scenario +was ported from. + +### The harness, `libs.ts` + +```ts +// Shared harness: the same scenario runs against Valtio and against our source. +import * as v from 'valtio/vanilla'; +import * as vu from 'valtio/vanilla/utils'; +import * as c from '/packages/classy-store/src/index.ts'; +import * as cc from '/packages/classy-store/src/collections/index.ts'; +import * as cu from '/packages/classy-store/src/utils/index.ts'; + +export type Lib = { + name: string; + create(o: T): T; + snapshot(o: T): any; + subscribe(o: object, cb: () => void, sync?: boolean): () => void; +}; + +export const valtio: Lib = { + name: 'valtio', + create: (o) => v.proxy(o), + snapshot: (o) => v.snapshot(o), + subscribe: (o, cb, sync) => v.subscribe(o, () => cb(), sync), +}; +export const classy: Lib = { + name: 'classy', + create: (o) => c.createClassyStore(o), + snapshot: (o) => c.snapshot(o), + subscribe: (o, cb, sync) => c.subscribe(o, cb, {sync}), +}; +export const libs = [valtio, classy]; +export {v, vu, c, cc, cu}; + +export const flush = () => new Promise((r) => setTimeout(r, 0)); + +/** Run one labelled expression, print its value or the error it throws. */ +export function show(label: string, fn: () => unknown): void { + try { + const value = fn(); + console.log(` ${label}: ${format(value)}`); + } catch (error) { + console.log( + ` ${label}: THROWS ${(error as Error).name}: ${(error as Error).message.slice(0, 90)}`, + ); + } +} +function format(value: unknown): string { + if (typeof value === 'function') return `[function ${value.name}]`; + try { + return JSON.stringify(value) ?? String(value); + } catch { + return String(value); + } +} +export async function each( + title: string, + run: (lib: Lib) => void | Promise, +) { + console.log(`\n## ${title}`); + for (const lib of libs) { + console.log(` [${lib.name}]`); + try { + await run(lib); + } catch (error) { + console.log( + ` scenario THROWS ${(error as Error).name}: ${(error as Error).message.slice(0, 120)}`, + ); + } + } +} +``` + +### Port 1: identity (findings 5, 6, 7, 8, 10) + +```ts +import {each, show} from './libs'; + +// Stage 1 finding 5: a function held in an array. +await each('5. function held in an array', (lib) => { + const first = () => 'first'; + const second = () => 'second'; + const store = lib.create({callbacks: [first, second]}); + show( + 'callbacks[0] === callbacks[0]', + () => store.callbacks[0] === store.callbacks[0], + ); + show('callbacks[0] === first', () => store.callbacks[0] === first); + show('indexOf(first)', () => store.callbacks.indexOf(first)); + store.callbacks.splice(store.callbacks.indexOf(first), 1); + show('after splice(indexOf(first), 1), names left', () => + store.callbacks.map((f) => f()), + ); +}); + +// Stage 1 finding 6: a class held as data. +await each('6. class held in a store', (lib) => { + class Model { + static label = 'model'; + constructor(public id: string) {} + } + const store = lib.create({Model}); + show('store.Model === Model', () => store.Model === Model); + show('store.Model.label', () => store.Model.label); + show( + 'new store.Model("x") instanceof store.Model', + () => new store.Model('x') instanceof store.Model, + ); +}); + +// Stage 1 finding 7: searching a list for a raw object. +await each('7. list.includes(raw)', (lib) => { + const raw = {id: 1}; + const store = lib.create({list: [raw]}); + show('list.includes(raw)', () => store.list.includes(raw)); + show('list.indexOf(raw)', () => store.list.indexOf(raw)); + show('list.includes(list[0])', () => store.list.includes(store.list[0])); + const row = {id: 2}; + store.list.push(row); + show('after push(row): list.includes(row)', () => store.list.includes(row)); +}); + +// Stage 1 finding 8: a store that refers to itself, then a snapshot. +await each('8. self-reference, then snapshot', (lib) => { + const store = lib.create({n: 1} as {n: number; self?: unknown}); + let calls = 0; + lib.subscribe(store, () => calls++, true); + show('store.self = store', () => { + store.self = store; + return 'ok'; + }); + show('sync calls after the write', () => calls); + show('snapshot(store).self === snapshot(store)', () => { + const snap = lib.snapshot(store); + return snap.self === snap; + }); + store.n = 2; + show( + 'after n = 2: snapshot(store).self.self.n', + () => lib.snapshot(store).self.self.n, + ); + show('sync calls after the second write', () => calls); +}); + +// Stage 1 finding 10: what the raw object holds afterwards. +await each('10. raw object after wrapping', (lib) => { + const child = {n: 1}; + const raw = {child}; + const store = lib.create(raw); + void store.child; + show('raw.child === child (raw graph untouched)', () => raw.child === child); + show( + 'store.child === raw.child (raw holds the proxy)', + () => store.child === raw.child, + ); +}); +``` + +Output: + +```text + +## 5. function held in an array + [valtio] + callbacks[0] === callbacks[0]: true + callbacks[0] === first: true + indexOf(first): 0 + after splice(indexOf(first), 1), names left: ["second"] + [classy] + callbacks[0] === callbacks[0]: false + callbacks[0] === first: false + indexOf(first): -1 + after splice(indexOf(first), 1), names left: ["first"] + +## 6. class held in a store + [valtio] + store.Model === Model: true + store.Model.label: "model" + new store.Model("x") instanceof store.Model: true + [classy] + store.Model === Model: false + store.Model.label: undefined + new store.Model("x") instanceof store.Model: false + +## 7. list.includes(raw) + [valtio] + list.includes(raw): false + list.indexOf(raw): -1 + list.includes(list[0]): true + after push(row): list.includes(row): false + [classy] + list.includes(raw): false + list.indexOf(raw): -1 + list.includes(list[0]): true + after push(row): list.includes(row): false + +## 8. self-reference, then snapshot + [valtio] + store.self = store: "ok" + sync calls after the write: 1 + snapshot(store).self === snapshot(store): true + after n = 2: snapshot(store).self.self.n: 2 + sync calls after the second write: 2 + [classy] + store.self = store: "ok" + sync calls after the write: 1 + snapshot(store).self === snapshot(store): THROWS Error: @codebelt/classy-store: circular reference detected in snapshot + after n = 2: snapshot(store).self.self.n: THROWS Error: @codebelt/classy-store: circular reference detected in snapshot + sync calls after the second write: 2 + +## 10. raw object after wrapping + [valtio] + raw.child === child (raw graph untouched): false + store.child === raw.child (raw holds the proxy): true + [classy] + raw.child === child (raw graph untouched): true + store.child === raw.child (raw holds the proxy): false +``` + +### Port 2: `defineProperty`, deletes and getters (findings 1, 45, 29, 30, 31; question 3) + +```ts +import {each, flush, show} from './libs'; + +// Stage 1 findings 1 and 45: Object.defineProperty through the proxy. +await each('1. Object.defineProperty(store, "b", {value: 2})', (lib) => { + const store = lib.create({a: 1} as {a: number; b?: number}); + let calls = 0; + lib.subscribe(store, () => calls++, true); + lib.snapshot(store); + Object.defineProperty(store, 'b', { + value: 2, + writable: true, + enumerable: true, + configurable: true, + }); + show('store.b', () => store.b); + show('sync calls', () => calls); + show('snapshot(store).b', () => lib.snapshot(store).b); + store.a = 5; + show( + 'after an ordinary write: snapshot(store).b', + () => lib.snapshot(store).b, + ); +}); + +await each('45. defineProperty over a property that holds an object', (lib) => { + const store = lib.create({child: {n: 1}} as {child: {n: number}}); + const other = {n: 99}; + let calls = 0; + lib.subscribe(store, () => calls++, true); + Object.defineProperty(store, 'child', { + value: other, + writable: true, + enumerable: true, + configurable: true, + }); + show('store.child.n', () => store.child.n); + store.child.n = 100; + show('sync calls after store.child.n = 100', () => calls); + show('snapshot(store).child.n', () => lib.snapshot(store).child.n); + show('other.n', () => other.n); +}); + +// Stage 1 finding 29: a delete that removes nothing. +await each('29. delete of a missing key', async (lib) => { + const store = lib.create({dict: {} as Record, list: [1, 2]}); + let sync = 0; + let batched = 0; + lib.subscribe(store, () => sync++, true); + lib.subscribe(store, () => batched++); + const before = lib.snapshot(store); + delete store.dict.missing; + await flush(); + show('sync calls', () => sync); + show('batched calls', () => batched); + show( + 'snapshot unchanged (same object)', + () => lib.snapshot(store) === before, + ); + delete store.list[5]; + await flush(); + show('after delete list[5]: sync calls', () => sync); + store.dict.x = 1; + const mid = sync; + store.dict.x = 1; + show( + 'writing the value a field already holds: extra sync calls', + () => sync - mid, + ); +}); + +// Stage 1 findings 30 and 31: a getter that asks which keys `this` has. +await each('30/31. getter reading Object.keys(this) and "b" in this', (lib) => { + class Bag { + a = 1; + b?: number = 2; + get count() { + return Object.keys(this).length; + } + get hasB() { + return 'b' in this; + } + get isBag() { + return this instanceof Bag; + } + } + const store = lib.create(new Bag()); + show('live count, hasB', () => [store.count, store.hasB]); + show('snapshot count, hasB, isBag', () => { + const snap = lib.snapshot(store); + return [snap.count, snap.hasB, snap.isBag]; + }); + delete store.b; + show('after delete store.b: live count, hasB', () => [ + store.count, + store.hasB, + ]); + show('after delete store.b: snapshot count, hasB', () => { + const snap = lib.snapshot(store); + return [snap.count, snap.hasB]; + }); +}); + +// API question 3: what a snapshot lists as its own keys. +await each('Q3. own keys of a snapshot of a class with getters', (lib) => { + class Cart { + items = [{price: 2}, {price: 3}]; + get total() { + return this.items.reduce((sum, item) => sum + item.price, 0); + } + } + const store = lib.create(new Cart()); + const snap = lib.snapshot(store); + show('Object.keys(store)', () => Object.keys(store)); + show('Object.keys(snapshot)', () => Object.keys(snap)); + show('JSON.stringify(snapshot)', () => JSON.stringify(snap)); + show('{...snapshot}.total', () => ({...snap}).total); + show('Object.getOwnPropertyDescriptor(snapshot, "total") kind', () => { + const d = Object.getOwnPropertyDescriptor(snap, 'total'); + return d + ? 'get' in d + ? 'own accessor' + : 'own data' + : 'not own (on the prototype)'; + }); + show('snap.total === snap.total', () => snap.total === snap.total); +}); + +// Getter memoization: how often a getter body runs. +await each('getter runs: live reads and snapshot reads', (lib) => { + let runs = 0; + class Cart { + items = [{price: 2}, {price: 3}]; + other = 0; + get total() { + runs++; + return this.items.reduce((sum, item) => sum + item.price, 0); + } + } + const store = lib.create(new Cart()); + store.total; + store.total; + store.total; + show('runs after 3 live reads', () => runs); + runs = 0; + const snap = lib.snapshot(store); + snap.total; + snap.total; + snap.total; + show('runs after 3 reads of one snapshot', () => runs); + runs = 0; + store.other = 1; + lib.snapshot(store).total; + show('runs after an unrelated write, new snapshot, one read', () => runs); +}); + +// Valtio only: an object-literal getter in a snapshot. +await each('own (object-literal) getter in a snapshot', (lib) => { + const store = lib.create({ + items: [{done: false}, {done: true}], + get open() { + return this.items.filter((item) => !item.done); + }, + }); + const snap = lib.snapshot(store); + show('descriptor kind of snapshot.open', () => { + const d = Object.getOwnPropertyDescriptor(snap, 'open'); + return d ? ('get' in d && d.get ? 'own accessor' : 'own data') : 'not own'; + }); + show( + 'snapshot.open[0] is the live proxy', + () => snap.open[0] === store.items[0], + ); + show( + 'snapshot.open[0] is the snapshot row', + () => snap.open[0] === snap.items[0], + ); + show('Object.isFrozen(snapshot.open)', () => Object.isFrozen(snap.open)); +}); +``` + +Output: + +```text + +## 1. Object.defineProperty(store, "b", {value: 2}) + [valtio] + store.b: 2 + sync calls: 0 + snapshot(store).b: undefined + after an ordinary write: snapshot(store).b: 2 + [classy] + store.b: 2 + sync calls: 0 + snapshot(store).b: undefined + after an ordinary write: snapshot(store).b: 2 + +## 45. defineProperty over a property that holds an object + [valtio] + store.child.n: 99 + sync calls after store.child.n = 100: 0 + snapshot(store).child.n: 100 + other.n: 100 + [classy] + store.child.n: 1 + sync calls after store.child.n = 100: 1 + snapshot(store).child.n: 100 + other.n: 99 + +## 29. delete of a missing key + [valtio] + sync calls: 1 + batched calls: 1 + snapshot unchanged (same object): false + after delete list[5]: sync calls: 2 + writing the value a field already holds: extra sync calls: 0 + [classy] + sync calls: 1 + batched calls: 1 + snapshot unchanged (same object): false + after delete list[5]: sync calls: 2 + writing the value a field already holds: extra sync calls: 0 + +## 30/31. getter reading Object.keys(this) and "b" in this + [valtio] + live count, hasB: [2,true] + snapshot count, hasB, isBag: [2,true,true] + after delete store.b: live count, hasB: [1,false] + after delete store.b: snapshot count, hasB: [1,false] + [classy] + live count, hasB: [2,true] + snapshot count, hasB, isBag: [0,false,false] + after delete store.b: live count, hasB: [2,true] + after delete store.b: snapshot count, hasB: [0,false] + +## Q3. own keys of a snapshot of a class with getters + [valtio] + Object.keys(store): ["items"] + Object.keys(snapshot): ["items"] + JSON.stringify(snapshot): "{\"items\":[{\"price\":2},{\"price\":3}]}" + {...snapshot}.total: undefined + Object.getOwnPropertyDescriptor(snapshot, "total") kind: "not own (on the prototype)" + snap.total === snap.total: true + [classy] + Object.keys(store): ["items"] + Object.keys(snapshot): ["items","total"] + JSON.stringify(snapshot): "{\"items\":[{\"price\":2},{\"price\":3}],\"total\":5}" + {...snapshot}.total: 5 + Object.getOwnPropertyDescriptor(snapshot, "total") kind: "own accessor" + snap.total === snap.total: true + +## getter runs: live reads and snapshot reads + [valtio] + runs after 3 live reads: 3 + runs after 3 reads of one snapshot: 3 + runs after an unrelated write, new snapshot, one read: 1 + [classy] + runs after 3 live reads: 1 + runs after 3 reads of one snapshot: 1 + runs after an unrelated write, new snapshot, one read: 0 + +## own (object-literal) getter in a snapshot + [valtio] + descriptor kind of snapshot.open: "own data" + snapshot.open[0] is the live proxy: true + snapshot.open[0] is the snapshot row: false + Object.isFrozen(snapshot.open): false + [classy] + descriptor kind of snapshot.open: "own accessor" + snapshot.open[0] is the live proxy: false + snapshot.open[0] is the snapshot row: true + Object.isFrozen(snapshot.open): false +``` + +### Port 3: notifications (findings 18 to 23, 43; the `sync` option) + +```ts +import {each, flush, show} from './libs'; + +const quiet = async (run: () => void | Promise) => { + const original = console.error; + const errors: string[] = []; + console.error = (e: unknown) => errors.push((e as Error)?.name ?? String(e)); + try { + await run(); + } finally { + console.error = original; + } + return errors; +}; + +// Stage 1 finding 18: a sync subscriber that writes to the store it listens to. +await each( + '18. sync subscriber writes to its own store on every call', + async (lib) => { + const store = lib.create({n: 0}); + let calls = 0; + lib.subscribe( + store, + () => { + calls++; + store.n++; + }, + true, + ); + let thrown = 'nothing'; + const errors = await quiet(() => { + try { + store.n = 1; + } catch (error) { + thrown = (error as Error).name; + } + }); + show('the writer sees', () => thrown); + show('console.error received', () => [...new Set(errors)]); + show('subscriber calls > 1000', () => calls > 1000); + show('store.n > 1000 (the writes were kept)', () => store.n > 1000); + }, +); + +// The bounded form: a subscriber that writes until a limit. +await each( + '18b. sync subscriber writes until n reaches 3; second subscriber watches', + (lib) => { + const store = lib.create({n: 0}); + const seen: number[] = []; + lib.subscribe( + store, + () => { + if (store.n < 3) store.n++; + }, + true, + ); + lib.subscribe(store, () => seen.push(lib.snapshot(store).n), true); + store.n = 1; + show('values the second subscriber saw', () => seen); + }, +); + +// Stage 1 finding 19, bounded: a batched subscriber that writes. +await each( + '19. batched subscriber writes until n reaches 3; timer due meanwhile', + async (lib) => { + const store = lib.create({n: 0}); + const order: string[] = []; + lib.subscribe(store, () => { + order.push(`cb${store.n}`); + if (store.n < 3) store.n++; + }); + setTimeout(() => order.push('timer'), 0); + store.n = 1; + await flush(); + await flush(); + show('order', () => order); + }, +); + +// Stage 1 finding 20: unsubscribing during delivery. +await each('20. A unsubscribes B during delivery (sync)', (lib) => { + const store = lib.create({n: 0}); + const calls: string[] = []; + let offB = () => {}; + lib.subscribe( + store, + () => { + calls.push('A'); + offB(); + }, + true, + ); + offB = lib.subscribe(store, () => calls.push('B'), true); + store.n = 1; + show('calls', () => calls); +}); +await each('20. A unsubscribes B during delivery (batched)', async (lib) => { + const store = lib.create({n: 0}); + const calls: string[] = []; + let offB = () => {}; + lib.subscribe(store, () => { + calls.push('A'); + offB(); + }); + offB = lib.subscribe(store, () => calls.push('B')); + store.n = 1; + await flush(); + show('calls', () => calls); +}); +await each( + '20. unsubscribe after the write, before the microtask (batched)', + async (lib) => { + const store = lib.create({n: 0}); + let calls = 0; + const off = lib.subscribe(store, () => calls++); + store.n = 1; + off(); + await flush(); + show('calls', () => calls); + }, +); + +// Stage 1 finding 21: a subscriber added after a write. +await each('21. batched subscriber added after the write', async (lib) => { + const store = lib.create({n: 0}); + let early = 0; + let late = 0; + lib.subscribe(store, () => early++); + store.n = 1; + lib.subscribe(store, () => late++); + await flush(); + show('early, late', () => [early, late]); +}); +await each( + '21. sync subscriber added by another sync subscriber during delivery', + (lib) => { + const store = lib.create({n: 0}); + let added = 0; + let done = false; + lib.subscribe( + store, + () => { + if (!done) { + done = true; + lib.subscribe(store, () => added++, true); + } + }, + true, + ); + store.n = 1; + show('calls of the subscriber added during delivery', () => added); + }, +); + +// Stage 1 finding 23 and its sync twin: a subscriber that throws. +await each('23. first sync subscriber throws', async (lib) => { + const store = lib.create({n: 0}); + let second = 0; + lib.subscribe( + store, + () => { + throw new TypeError('boom'); + }, + true, + ); + lib.subscribe(store, () => second++, true); + let thrown = 'nothing'; + const errors = await quiet(() => { + try { + store.n = 1; + } catch (error) { + thrown = (error as Error).name; + } + }); + show('the writer sees', () => thrown); + show('console.error received', () => errors); + show('second subscriber calls', () => second); + show('store.n', () => store.n); +}); + +// The sync option: how many sync notifications one array operation makes. +await each('sync notifications per array operation (100 rows)', (lib) => { + const rows = Array.from({length: 100}, (_, i) => ({id: 100 - i})); + const store = lib.create({rows}); + let calls = 0; + lib.subscribe(store, () => calls++, true); + const count = (label: string, run: () => void) => { + calls = 0; + run(); + show(label, () => calls); + }; + count('push(row)', () => store.rows.push({id: 0})); + count('unshift(row)', () => store.rows.unshift({id: -1})); + count('sort()', () => store.rows.sort((a, b) => a.id - b.id)); + count('reverse()', () => store.rows.reverse()); + count('splice(0, 1)', () => store.rows.splice(0, 1)); + count('rows.length = 0', () => { + store.rows.length = 0; + }); +}); + +// Stage 1 finding 43: a setter that writes two fields. +await each( + '43. method and setter that write two fields: sync notifications', + (lib) => { + class Pair { + a = 0; + b = 0; + set both(value: number) { + this.a = value; + this.b = value; + } + setBoth(value: number) { + this.a = value; + this.b = value; + } + } + const store = lib.create(new Pair()); + const seen: string[] = []; + lib.subscribe(store, () => seen.push(`${store.a},${store.b}`), true); + store.setBoth(1); + show('method: states seen', () => seen.splice(0)); + store.both = 2; + show('setter: states seen', () => seen.splice(0)); + }, +); +``` + +Output: + +```text + +## 18. sync subscriber writes to its own store on every call + [valtio] + the writer sees: "RangeError" + console.error received: [] + subscriber calls > 1000: true + store.n > 1000 (the writes were kept): true + [classy] + the writer sees: "nothing" + console.error received: ["RangeError"] + subscriber calls > 1000: true + store.n > 1000 (the writes were kept): true + +## 18b. sync subscriber writes until n reaches 3; second subscriber watches + [valtio] + values the second subscriber saw: [3,3,3] + [classy] + values the second subscriber saw: [3,3,3] + +## 19. batched subscriber writes until n reaches 3; timer due meanwhile + [valtio] + order: ["cb1","cb2","cb3","timer"] + [classy] + order: ["cb1","cb2","cb3","timer"] + +## 20. A unsubscribes B during delivery (sync) + [valtio] + calls: ["A"] + [classy] + calls: ["A","B"] + +## 20. A unsubscribes B during delivery (batched) + [valtio] + calls: ["A"] + [classy] + calls: ["A","B"] + +## 20. unsubscribe after the write, before the microtask (batched) + [valtio] + calls: 0 + [classy] + calls: 0 + +## 21. batched subscriber added after the write + [valtio] + early, late: [1,0] + [classy] + early, late: [1,1] + +## 21. sync subscriber added by another sync subscriber during delivery + [valtio] + calls of the subscriber added during delivery: 1 + [classy] + calls of the subscriber added during delivery: 0 + +## 23. first sync subscriber throws + [valtio] + the writer sees: "TypeError" + console.error received: [] + second subscriber calls: 0 + store.n: 1 + [classy] + the writer sees: "nothing" + console.error received: ["TypeError"] + second subscriber calls: 1 + store.n: 1 + +## sync notifications per array operation (100 rows) + [valtio] + push(row): 1 + unshift(row): 102 + sort(): 100 + reverse(): 102 + splice(0, 1): 103 + rows.length = 0: 1 + [classy] + push(row): 1 + unshift(row): 1 + sort(): 1 + reverse(): 1 + splice(0, 1): 1 + rows.length = 0: 1 + +## 43. method and setter that write two fields: sync notifications + [valtio] + method: states seen: ["1,0","1,1"] + setter: states seen: ["2,1","2,2","2,2"] + [classy] + method: states seen: ["1,1"] + setter: states seen: ["2,1","2,2"] +``` + +### Port 4: detached subtrees and memory (findings 25, 27, 72) + +```ts +import {each, flush, show, type Lib} from './libs'; + +// Stage 1 finding 25: a raw object changed while detached, then put back. +await each( + '25. delete slot; raw.n = 2; slot = raw (snapshot taken before)', + (lib) => { + const raw = {n: 1}; + const store = lib.create({slot: raw} as {slot?: {n: number}}); + lib.snapshot(store); + delete store.slot; + raw.n = 2; + store.slot = raw; + show('store.slot.n', () => store.slot?.n); + show('snapshot(store).slot.n', () => lib.snapshot(store).slot.n); + }, +); + +// What suspend and resume are for: a child written through its proxy while its +// container is out of the store and unobserved, then the container put back. +await each( + '72. child written while its container is detached, container put back', + (lib) => { + const store = lib.create({box: {row: {n: 1}}} as { + box?: {row: {n: number}}; + }); + lib.snapshot(store); + const box = store.box!; + const row = box.row; + delete store.box; + lib.snapshot(store); + row.n = 2; + store.box = box; + show('snapshot(store).box.row.n', () => lib.snapshot(store).box.row.n); + let calls = 0; + lib.subscribe(store, () => calls++, true); + row.n = 3; + show('root subscriber hears a row write after re-attach', () => calls); + }, +); + +await each( + '72. subscriber on a detached container still hears its children', + (lib) => { + const store = lib.create({box: {row: {n: 1}}} as { + box?: {row: {n: number}}; + }); + const box = store.box!; + let boxCalls = 0; + let rootCalls = 0; + lib.subscribe(box, () => boxCalls++, true); + lib.subscribe(store, () => rootCalls++, true); + delete store.box; + rootCalls = 0; + box.row.n = 2; + show('box subscriber calls', () => boxCalls); + show( + 'root subscriber calls (box is no longer in the store)', + () => rootCalls, + ); + show('snapshot(box).row.n', () => lib.snapshot(box).row.n); + }, +); + +// Memory: one retained row must not keep the list it was removed with alive. +async function collected(ref: WeakRef): Promise { + for (let i = 0; i < 20 && ref.deref(); i++) { + await flush(); + Bun.gc(true); + } + return ref.deref() === undefined; +} +function setUp(lib: Lib, observed: boolean) { + const store = lib.create({list: Array.from({length: 50}, (_, n) => ({n}))}); + if (observed) lib.subscribe(store, () => {}, true); + lib.snapshot(store); + const row = store.list[0]; + const list = new WeakRef(store.list as object); + store.list = []; + lib.snapshot(store); + return {store, row, list}; +} +for (const observed of [true, false]) { + await each( + `27/72. retained row, replaced list, store ${observed ? 'observed' : 'unobserved'}`, + async (lib) => { + const held = setUp(lib, observed); + const gone = await collected(held.list); + show('the replaced list was collected', () => gone); + show('the retained row still works', () => { + held.row.n = 7; + return held.row.n; + }); + }, + ); +} +``` + +Output: + +```text + +## 25. delete slot; raw.n = 2; slot = raw (snapshot taken before) + [valtio] + store.slot.n: 2 + snapshot(store).slot.n: 1 + [classy] + store.slot.n: 2 + snapshot(store).slot.n: 1 + +## 72. child written while its container is detached, container put back + [valtio] + snapshot(store).box.row.n: 2 + root subscriber hears a row write after re-attach: 1 + [classy] + snapshot(store).box.row.n: 2 + root subscriber hears a row write after re-attach: 1 + +## 72. subscriber on a detached container still hears its children + [valtio] + box subscriber calls: 1 + root subscriber calls (box is no longer in the store): 0 + snapshot(box).row.n: 2 + [classy] + box subscriber calls: 1 + root subscriber calls (box is no longer in the store): 0 + snapshot(box).row.n: 2 + +## 27/72. retained row, replaced list, store observed + [valtio] + the replaced list was collected: false + the retained row still works: 7 + [classy] + the replaced list was collected: true + the retained row still works: 7 + +## 27/72. retained row, replaced list, store unobserved + [valtio] + the replaced list was collected: true + the retained row still works: 7 + [classy] + the replaced list was collected: true + the retained row still works: 7 +``` + +### Port 4b: the read that never returns (finding 66) + +```ts +// Stage 1 finding 66, run once per library in a child process with a timeout. +import {libs} from './libs'; +const lib = libs.find((l) => l.name === process.argv[2])!; +const store = lib.create({outer: {inner: {x: 1}}} as any); +const outer = store.outer; +const inner = outer.inner; +delete store.outer; +Object.defineProperty(outer, 'inner', {writable: false, configurable: false}); +lib.snapshot(inner); +lib.snapshot(inner); +inner.back = outer; +lib.subscribe(inner, () => {}, true)(); +console.log(` [${lib.name}] inner.x: ${inner.x}`); +``` + +Output: + +```text + [valtio] inner.x: 1 + [valtio] exit code: 0 (124 means killed by the 8-second timeout) + [classy] exit code: 124 (124 means killed by the 8-second timeout) +``` + +### Port 4c: the memory check, five rounds + +```ts +import {flush, libs, type Lib} from './libs'; +async function collected(ref: WeakRef): Promise { + for (let i = 0; i < 30 && ref.deref(); i++) { + await flush(); + Bun.gc(true); + } + return ref.deref() === undefined; +} +function setUp(lib: Lib, observed: boolean, snap: boolean) { + const store = lib.create({list: Array.from({length: 50}, (_, n) => ({n}))}); + if (observed) lib.subscribe(store, () => {}, true); + if (snap) lib.snapshot(store); + const row = store.list[0]; + const list = new WeakRef(store.list as object); + store.list = []; + if (snap) lib.snapshot(store); + return {store, row, list}; +} +const lib = libs.find((l) => l.name === process.argv[2])!; +const observed = process.argv[3] === 'observed'; +const snap = process.argv[4] !== 'nosnap'; +const results: boolean[] = []; +for (let round = 0; round < 5; round++) { + const held = setUp(lib, observed, snap); + results.push(await collected(held.list)); + held.row.n = 1; +} +console.log( + ` [${lib.name}] ${process.argv[3]} ${process.argv[4] ?? 'snap'}: collected in 5 rounds: ${results.join(', ')}`, +); +``` + +Output: + +```text + [valtio] observed snap: collected in 5 rounds: false, true, true, true, true + [valtio] unobserved snap: collected in 5 rounds: true, true, true, true, true + [classy] observed snap: collected in 5 rounds: true, true, true, false, true + [classy] unobserved snap: collected in 5 rounds: true, true, true, false, true +``` + +### Port 4d: a subscribed container after a garbage collection + +```ts +// A container that has a subscriber is removed from the store. The caller keeps +// one of its rows, and drops the unsubscribe function. Does the subscriber +// still hear a write to the row after a garbage collection? +import {flush, libs, type Lib} from './libs'; +const calls = {count: 0}; +function setUp(lib: Lib) { + const store = lib.create({list: Array.from({length: 50}, (_, n) => ({n}))}); + lib.subscribe(store.list, () => calls.count++, true); // unsubscribe function dropped + const row = store.list[0]; + const list = new WeakRef(store.list as object); + store.list = []; + return {row, list}; +} +const lib = libs.find((l) => l.name === process.argv[2])!; +const out: string[] = []; +for (let round = 0; round < 5; round++) { + const held = setUp(lib); + held.row.n = 100; // before any collection + const before = calls.count; + for (let i = 0; i < 30 && held.list.deref(); i++) { + await flush(); + Bun.gc(true); + } + held.row.n = 200; + out.push( + `${held.list.deref() ? 'alive' : 'collected'}/${before}->${calls.count}`, + ); + calls.count = 0; +} +console.log( + ` [${lib.name}] list after gc / subscriber calls before->after: ${out.join(' ')}`, +); +``` + +Output: + +```text + [valtio] list after gc / subscriber calls before->after: alive/1->2 alive/1->2 alive/1->2 alive/1->2 alive/1->2 + [classy] list after gc / subscriber calls before->after: collected/1->1 collected/1->1 collected/1->1 collected/1->1 collected/1->1 +``` + +### Port 5: reactive collections (findings 16, 33, 34) + +```ts +import {cc, each, show, vu, type Lib} from './libs'; + +const makeSet = (lib: Lib, init?: Iterable) => + lib.name === 'valtio' + ? (vu.proxySet(init as never) as any) + : (cc.reactiveSet(init) as any); +const makeMap = (lib: Lib, init?: Iterable<[unknown, unknown]>) => + lib.name === 'valtio' + ? (vu.proxyMap(init as never) as any) + : (cc.reactiveMap(init) as any); + +// Looking a member up by raw object, by proxy and by snapshot. +await each('collections: one object as raw, proxy and snapshot', (lib) => { + const raw = {id: 1}; + const store = lib.create({ + rows: [raw], + picked: makeSet(lib), + notes: makeMap(lib), + }); + const proxy = store.rows[0]; + store.picked.add(raw); + store.notes.set(raw, 'note'); + const snap = lib.snapshot(store); + show('set.size after add(raw)', () => store.picked.size); + show('set.has(raw), has(proxy), has(snapshot row)', () => [ + store.picked.has(raw), + store.picked.has(proxy), + store.picked.has(snap.rows[0]), + ]); + show('map.get(raw), get(proxy), get(snapshot row)', () => [ + store.notes.get(raw), + store.notes.get(proxy), + store.notes.get(snap.rows[0]), + ]); + show('snapshot: set.has(snapshot row), map.get(snapshot row)', () => [ + snap.picked.has(snap.rows[0]), + snap.notes.get(snap.rows[0]), + ]); + show('snapshot: set.has(proxy), map.get(raw)', () => [ + snap.picked.has(proxy), + snap.notes.get(raw), + ]); + store.picked.add(proxy); + store.notes.set(proxy, 'again'); + show('after add(proxy), set(proxy, …): set.size, map.size', () => [ + store.picked.size, + store.notes.size, + ]); +}); + +// Stage 1 findings 33 and 34. +await each('33. +0 and -0', (lib) => { + const added = makeSet(lib, [0]); + const store = lib.create({added, built: makeSet(lib, [0, -0])}); + store.added.add(-0); + show('add: size', () => store.added.size); + show('constructor: size', () => store.built.size); +}); +await each('34. constructed from [raw, proxy]', (lib) => { + const raw = {id: 1}; + const holder = lib.create({rows: [raw]}); + const store = lib.create({set: makeSet(lib, [raw, holder.rows[0]])}); + show('size', () => store.set.size); + store.set.delete(raw); + show('after delete(raw): has(raw), size', () => [ + store.set.has(raw), + store.set.size, + ]); +}); + +// Stage 1 finding 16: mutating a snapshot of a collection. +await each('16. mutators on a snapshot of a collection', (lib) => { + const store = lib.create({ + tags: makeSet(lib, ['a']), + todos: makeMap(lib, [['k', 1]]), + }); + const snap = lib.snapshot(store); + show('snapshot.tags.add("b")', () => snap.tags.add('b')); + show('snapshot.todos.set("k", 2)', () => snap.todos.set('k', 2)); + show('snapshot.todos.clear()', () => snap.todos.clear()); + show('snapshot.todos.get("k") afterwards', () => snap.todos.get('k')); +}); + +// Churn: what the backing storage looks like after many set/delete pairs. +await each( + 'backing storage after 10,000 set+delete pairs, one live entry', + (lib) => { + const store = lib.create({map: makeMap(lib)}); + for (let i = 0; i < 10_000; i++) { + store.map.set(`k${i}`, i); + if (i > 0) store.map.delete(`k${i - 1}`); + } + show('size', () => store.map.size); + show( + 'backing array length', + () => (store.map.data ?? store.map._entries).length, + ); + }, +); + +// Lookup cost in a large collection. +await each('time for 1,000 has() calls on a set of 10,000 numbers', (lib) => { + const store = lib.create({ + set: makeSet( + lib, + Array.from({length: 10_000}, (_, i) => i), + ), + }); + const start = performance.now(); + let hits = 0; + for (let i = 0; i < 1_000; i++) + if (store.set.has(9_000 + (i % 1_000))) hits++; + const ms = performance.now() - start; + show('hits', () => hits); + console.log(` milliseconds: ${ms.toFixed(2)}`); + const snap = lib.snapshot(store); + const start2 = performance.now(); + for (let i = 0; i < 1_000; i++) snap.set.has(9_000 + (i % 1_000)); + console.log( + ` milliseconds on a snapshot: ${(performance.now() - start2).toFixed(2)}`, + ); + const start3 = performance.now(); + for (let i = 0; i < 100; i++) { + store.set.add(20_000 + i); + lib.snapshot(store); + } + console.log( + ` milliseconds for 100 x (add one, snapshot): ${(performance.now() - start3).toFixed(2)}`, + ); +}); +``` + +Output: + +```text + +## collections: one object as raw, proxy and snapshot + [valtio] + set.size after add(raw): 1 + set.has(raw), has(proxy), has(snapshot row): [true,true,false] + map.get(raw), get(proxy), get(snapshot row): ["note",null,null] + snapshot: set.has(snapshot row), map.get(snapshot row): [false,null] + snapshot: set.has(proxy), map.get(raw): [true,"note"] + after add(proxy), set(proxy, …): set.size, map.size: [1,2] + [classy] + set.size after add(raw): 1 + set.has(raw), has(proxy), has(snapshot row): [true,true,true] + map.get(raw), get(proxy), get(snapshot row): ["note","note","note"] + snapshot: set.has(snapshot row), map.get(snapshot row): [true,"note"] + snapshot: set.has(proxy), map.get(raw): [true,"note"] + after add(proxy), set(proxy, …): set.size, map.size: [1,1] + +## 33. +0 and -0 + [valtio] + add: size: 1 + constructor: size: 1 + [classy] + add: size: 2 + constructor: size: 1 + +## 34. constructed from [raw, proxy] + [valtio] + size: 1 + after delete(raw): has(raw), size: [false,0] + [classy] + size: 2 + after delete(raw): has(raw), size: [true,1] + +## 16. mutators on a snapshot of a collection + [valtio] + snapshot.tags.add("b"): THROWS Error: Cannot perform mutations on a snapshot + snapshot.todos.set("k", 2): THROWS Error: Cannot perform mutations on a snapshot + snapshot.todos.clear(): THROWS Error: Cannot perform mutations on a snapshot + snapshot.todos.get("k") afterwards: 1 + [classy] + snapshot.tags.add("b"): THROWS TypeError: Attempted to assign to readonly property. + snapshot.todos.set("k", 2): THROWS TypeError: Attempted to assign to readonly property. + snapshot.todos.clear(): THROWS TypeError: Unable to delete property. + snapshot.todos.get("k") afterwards: 1 + +## backing storage after 10,000 set+delete pairs, one live entry + [valtio] + size: 1 + backing array length: 10000 + [classy] + size: 1 + backing array length: 1 + +## time for 1,000 has() calls on a set of 10,000 numbers + [valtio] + hits: 1000 + milliseconds: 0.20 + milliseconds on a snapshot: 0.07 + milliseconds for 100 x (add one, snapshot): 220.92 + [classy] + hits: 1000 + milliseconds: 22.06 + milliseconds on a snapshot: 245.15 + milliseconds for 100 x (add one, snapshot): 164.26 +``` + +### Port 6: private fields, class instances, `ref()`, immutability + +```ts +import {createProxy, getUntracked} from 'proxy-compare'; +import {each, show, v} from './libs'; + +// API question 4: arrow-function methods and #private fields. +await each( + 'Q4. arrow-function method, #private field, destructured method', + (lib) => { + class Counter { + count = 0; + #secret = 1; + arrow = () => { + this.count++; + }; + method() { + this.count++; + } + readSecret() { + return this.#secret; + } + } + const store = lib.create(new Counter()); + let calls = 0; + lib.subscribe(store, () => calls++, true); + store.arrow(); + show('after arrow(): store.count, sync calls, snapshot.count', () => [ + store.count, + calls, + lib.snapshot(store).count, + ]); + store.method(); + show('after method(): store.count, sync calls, snapshot.count', () => [ + store.count, + calls, + lib.snapshot(store).count, + ]); + show('readSecret() through the store', () => store.readSecret()); + show('readSecret() on a snapshot', () => lib.snapshot(store).readSecret()); + const {method} = store; + show('destructured method()', () => { + method(); + return store.count; + }); + }, +); + +// API question 6: a nested class instance, by default. +await each('Q6. nested class instance with no marker', (lib) => { + class Point { + x = 1; + move() { + this.x++; + } + } + const store = lib.create({point: new Point()}); + let calls = 0; + lib.subscribe(store, () => calls++, true); + const before = lib.snapshot(store); + store.point.x = 5; + show('sync calls after store.point.x = 5', () => calls); + show('snapshot(store).point.x', () => lib.snapshot(store).point.x); + show('earlier snapshot.point.x (should stay 1)', () => before.point.x); + show( + 'snapshot.point is the live instance', + () => lib.snapshot(store).point === store.point, + ); +}); + +// ref() and its nearest equivalents. +await each('ref(): a plain object held without tracking', (lib) => { + const blob = {big: [1, 2, 3]}; + const held = lib.name === 'valtio' ? v.ref(blob) : Object.freeze(blob); + const store = lib.create({held}); + show('store.held === blob', () => store.held === blob); + show( + 'snapshot(store).held === blob', + () => lib.snapshot(store).held === blob, + ); + show('blob can still be changed by its owner', () => { + (blob as any).extra = 1; + return (blob as any).extra; + }); +}); + +// Snapshot immutability. +await each('is a snapshot immutable?', (lib) => { + const store = lib.create({n: 1, list: [1, 2], child: {a: 1}} as any); + const snap = lib.snapshot(store); + show('Object.isFrozen(snapshot), isFrozen(snapshot.list)', () => [ + Object.isFrozen(snap), + Object.isFrozen(snap.list), + ]); + show('snapshot.n = 2', () => { + 'use strict'; + snap.n = 2; + return snap.n; + }); + show('snapshot.extra = 1', () => { + snap.extra = 1; + return snap.extra; + }); + show('snapshot.list.push(3)', () => { + snap.list.push(3); + return snap.list; + }); + show('delete snapshot.child', () => { + delete snap.child; + return 'child' in snap; + }); + show( + 'snapshot(store) is still that changed object', + () => lib.snapshot(store) === snap && Object.keys(snap), + ); +}); + +// A getter that throws while a snapshot is being built. +await each('own getter throws during snapshot(), then recovers', (lib) => { + let fail = true; + const store = lib.create({ + a: 1, + get risky() { + if (fail) throw new Error('not ready'); + return 'ready'; + }, + z: 26, + }); + show('first snapshot()', () => Object.keys(lib.snapshot(store))); + fail = false; + show('second snapshot(): keys', () => Object.keys(lib.snapshot(store))); + show('second snapshot(): risky, z', () => { + const s = lib.snapshot(store); + return [s.risky, s.z]; + }); +}); + +// Deep input. +await each('creating a store from an object nested 20,000 deep', (lib) => { + let deep: any = {leaf: true}; + for (let i = 0; i < 20_000; i++) deep = {next: deep}; + show('create', () => { + lib.create(deep); + return 'ok'; + }); +}); + +// Wrapping twice. +await each('wrapping a store again', (lib) => { + const store = lib.create({n: 1}); + show('create(store) === store', () => lib.create(store) === store); +}); + +// A tracked snapshot value handed back to the store. Valtio only here: this +// file's proxy-compare is the instance Valtio uses. The same check against the +// instance our library uses is in proto-getuntracked.ts. +console.log( + '\n## proxy-compare getUntracked() on a tracked snapshot of a class instance', +); +{ + class Row { + n = 1; + } + const store = v.proxy({plain: {n: 1}, row: new Row()}); + const snap = v.snapshot(store); + const tracked = createProxy(snap, new WeakMap()); + console.log(' [valtio]'); + show( + 'plain row: is a tracking proxy, getUntracked finds the snapshot', + () => [ + tracked.plain !== snap.plain, + getUntracked(tracked.plain) === snap.plain, + ], + ); + show( + 'class row: is a tracking proxy, getUntracked finds the snapshot', + () => [tracked.row !== snap.row, getUntracked(tracked.row) === snap.row], + ); +} +``` + +Output: + +```text + +## Q4. arrow-function method, #private field, destructured method + [valtio] + after arrow(): store.count, sync calls, snapshot.count: [1,0,1] + after method(): store.count, sync calls, snapshot.count: [2,1,2] + readSecret() through the store: THROWS TypeError: Cannot access invalid private field (evaluating 'this.#secret') + readSecret() on a snapshot: THROWS TypeError: Cannot access invalid private field (evaluating 'this.#secret') + destructured method(): THROWS TypeError: undefined is not an object (evaluating 'this.count') + [classy] + after arrow(): store.count, sync calls, snapshot.count: [1,0,1] + after method(): store.count, sync calls, snapshot.count: [2,1,2] + readSecret() through the store: THROWS TypeError: Cannot access invalid private field (evaluating 'this.#secret') + readSecret() on a snapshot: THROWS TypeError: Cannot access invalid private field (evaluating 'this.#secret') + destructured method(): 3 + +## Q6. nested class instance with no marker + [valtio] + sync calls after store.point.x = 5: 1 + snapshot(store).point.x: 5 + earlier snapshot.point.x (should stay 1): 1 + snapshot.point is the live instance: false + [classy] + sync calls after store.point.x = 5: 0 + snapshot(store).point.x: 5 + earlier snapshot.point.x (should stay 1): 5 + snapshot.point is the live instance: true + +## ref(): a plain object held without tracking + [valtio] + store.held === blob: true + snapshot(store).held === blob: true + blob can still be changed by its owner: 1 + [classy] + store.held === blob: true + snapshot(store).held === blob: true + blob can still be changed by its owner: THROWS TypeError: Attempting to define property on object that is not extensible. + +## is a snapshot immutable? + [valtio] + Object.isFrozen(snapshot), isFrozen(snapshot.list): [false,false] + snapshot.n = 2: THROWS TypeError: Attempted to assign to readonly property. + snapshot.extra = 1: 1 + snapshot.list.push(3): [1,2,3] + delete snapshot.child: false + snapshot(store) is still that changed object: ["n","list","extra"] + [classy] + Object.isFrozen(snapshot), isFrozen(snapshot.list): [true,true] + snapshot.n = 2: THROWS TypeError: Attempted to assign to readonly property. + snapshot.extra = 1: THROWS TypeError: Attempting to define property on object that is not extensible. + snapshot.list.push(3): THROWS TypeError: Attempted to assign to readonly property. + delete snapshot.child: THROWS TypeError: Unable to delete property. + snapshot(store) is still that changed object: ["n","list","child"] + +## own getter throws during snapshot(), then recovers + [valtio] + first snapshot(): THROWS Error: not ready + second snapshot(): keys: ["a"] + second snapshot(): risky, z: [null,null] + [classy] + first snapshot(): ["a","z","risky"] + second snapshot(): keys: ["a","z","risky"] + second snapshot(): risky, z: ["ready",26] + +## creating a store from an object nested 20,000 deep + [valtio] + create: THROWS RangeError: Maximum call stack size exceeded. + [classy] + create: "ok" + +## wrapping a store again + [valtio] + create(store) === store: false + [classy] + create(store) === store: true + +## proxy-compare getUntracked() on a tracked snapshot of a class instance + [valtio] + plain row: is a tracking proxy, getUntracked finds the snapshot: [true,true] + class row: is a tracking proxy, getUntracked finds the snapshot: [true,false] +``` + +### Port 7: embedded stores, frozen raw objects, `subscribeKey` (findings 9, 46, 50) + +```ts +import {c, cu, each, show, v, vu} from './libs'; + +// Stage 1 finding 9: a raw object that is already a store, placed in another store. +await each( + '9. raw instance that is already a store, placed in another store', + (lib) => { + class Inner { + static [c.PROXYABLE] = true; + n = 0; + bump() { + this.n++; + } + } + class Plain { + n = 0; + bump() { + this.n++; + } + } + for (const Kind of [Inner, Plain]) { + const raw = new Kind(); + const innerStore = lib.create(raw); + const outer = lib.create({ + inner: null as unknown as InstanceType, + }); + outer.inner = raw; + let outerCalls = 0; + let innerCalls = 0; + lib.subscribe(outer, () => outerCalls++, true); + lib.subscribe(innerStore, () => innerCalls++, true); + outer.inner.bump(); + show( + `${Kind.name}: outer.inner === innerStore, outer calls, inner calls`, + () => [outer.inner === innerStore, outerCalls, innerCalls], + ); + } + }, +); + +// Stage 1 finding 46: freezing the raw object behind the store. +await each( + '46. Object.freeze(raw.config), then read and write through the store', + (lib) => { + const raw = {config: {nested: {a: 1}, n: 1}}; + const store = lib.create(raw); + let calls = 0; + lib.subscribe(store, () => calls++, true); + Object.freeze(raw.config); + show('store.config.nested.a', () => store.config.nested.a); + show('store.config.n = 2 (strict mode)', () => { + 'use strict'; + store.config.n = 2; + return store.config.n; + }); + show('sync calls', () => calls); + }, +); + +// Stage 1 finding 50. +await each( + '50. Object.getOwnPropertyDescriptor(store, "child").value', + (lib) => { + const store = lib.create({child: {n: 0}}); + const value = Object.getOwnPropertyDescriptor(store, 'child')!.value; + show('is the proxy the store hands out', () => value === store.child); + }, +); + +// subscribeKey: what the callback gets, and whether a nested write calls it. +await each('subscribeKey on a key that holds an object', (lib) => { + const store = lib.create({count: 0, user: {name: 'a'}}); + const got: unknown[] = []; + if (lib.name === 'valtio') + vu.subscribeKey( + store, + 'user', + (value) => got.push(value === store.user ? 'live proxy' : typeof value), + true, + ); + else + cu.subscribeKey( + store, + 'user', + (value, previous) => + got.push( + Object.isFrozen(value) + ? `snapshot (previous: ${previous.name})` + : typeof value, + ), + {sync: true}, + ); + store.user.name = 'b'; + show('after a nested write', () => got.splice(0)); + store.user = {name: 'c'}; + show('after replacing the object', () => got.splice(0)); +}); + +// subscribeKey: cost of one notification in a store that also holds 1,000 rows. +await each( + 'subscribeKey(store, "count") beside 1,000 rows: cost of a write to a row', + (lib) => { + const rows = Array.from({length: 1_000}, (_, id) => ({id, done: false})); + const time = (store: {rows: typeof rows}) => { + for (let i = 0; i < 200; i++) store.rows[i].done = !store.rows[i].done; + const start = performance.now(); + for (let i = 0; i < 2_000; i++) + store.rows[i % 1_000].done = !store.rows[i % 1_000].done; + return ((performance.now() - start) * 1e3) / 2_000; + }; + const plain = lib.create({count: 0, rows: structuredClone(rows)}); + lib.subscribe(plain, () => {}, true); + const keyed = lib.create({count: 0, rows: structuredClone(rows)}); + if (lib.name === 'valtio') vu.subscribeKey(keyed, 'count', () => {}, true); + else cu.subscribeKey(keyed, 'count', () => {}, {sync: true}); + console.log( + ` microseconds per write with a plain sync subscriber: ${time(plain).toFixed(2)}`, + ); + console.log( + ` microseconds per write with subscribeKey on "count": ${time(keyed).toFixed(2)}`, + ); + }, +); + +// Cost of installing getters on every snapshot (ours only matters; Valtio installs none). +await each( + 'write one field, then snapshot: class with 0 getters and with 8 getters', + (lib) => { + class None { + static [c.PROXYABLE] = true; + n = 0; + } + class Eight { + static [c.PROXYABLE] = true; + n = 0; + get a() { + return this.n; + } + get b() { + return this.n; + } + get c() { + return this.n; + } + get d() { + return this.n; + } + get e() { + return this.n; + } + get f() { + return this.n; + } + get g() { + return this.n; + } + get h() { + return this.n; + } + } + for (const Kind of [None, Eight]) { + const store = lib.create(new Kind()); + for (let i = 0; i < 5_000; i++) { + store.n = i; + lib.snapshot(store); + } + const start = performance.now(); + for (let i = 0; i < 200_000; i++) { + store.n = i; + lib.snapshot(store); + } + console.log( + ` ${Kind.name}: ${(((performance.now() - start) * 1e6) / 200_000).toFixed(0)} ns per write + snapshot`, + ); + } + }, +); + +// How to tell a class from a method without calling it. +console.log( + '\n## telling a class from other functions by its `prototype` property', +); +class K {} +const kinds: [string, unknown][] = [ + ['class', K], + ['function declaration', function f() {}], + ['arrow', () => {}], + ['method', {m() {}}.m], + ['async function', async () => {}], + ['built-in Date', Date], +]; +for (const [label, fn] of kinds) { + const d = Object.getOwnPropertyDescriptor(fn as object, 'prototype'); + console.log( + ` ${label}: prototype ${d ? (d.writable ? 'writable' : 'not writable') : 'absent'}`, + ); +} +void v; +``` + +Output: + +```text + +## 9. raw instance that is already a store, placed in another store + [valtio] + Inner: outer.inner === innerStore, outer calls, inner calls: [true,1,1] + Plain: outer.inner === innerStore, outer calls, inner calls: [true,1,1] + [classy] + Inner: outer.inner === innerStore, outer calls, inner calls: [true,1,1] + Plain: outer.inner === innerStore, outer calls, inner calls: [false,0,0] + +## 46. Object.freeze(raw.config), then read and write through the store + [valtio] + store.config.nested.a: 1 + store.config.n = 2 (strict mode): THROWS TypeError: Proxy handler's 'set' on a non-configurable and non-writable property on 'target' should e + sync calls: 1 + [classy] + store.config.nested.a: THROWS TypeError: Proxy handler's 'get' result of a non-configurable and non-writable property should be the + store.config.n = 2 (strict mode): THROWS TypeError: Proxy object's 'set' trap returned falsy value for property 'n' + sync calls: 0 + +## 50. Object.getOwnPropertyDescriptor(store, "child").value + [valtio] + is the proxy the store hands out: true + [classy] + is the proxy the store hands out: false + +## subscribeKey on a key that holds an object + [valtio] + after a nested write: [] + after replacing the object: ["live proxy"] + [classy] + after a nested write: ["snapshot (previous: a)"] + after replacing the object: ["snapshot (previous: b)"] + +## subscribeKey(store, "count") beside 1,000 rows: cost of a write to a row + [valtio] + microseconds per write with a plain sync subscriber: 0.57 + microseconds per write with subscribeKey on "count": 0.38 + [classy] + microseconds per write with a plain sync subscriber: 1.00 + microseconds per write with subscribeKey on "count": 121.94 + +## write one field, then snapshot: class with 0 getters and with 8 getters + [valtio] + None: 339 ns per write + snapshot + Eight: 338 ns per write + snapshot + [classy] + None: 672 ns per write + snapshot + Eight: 1938 ns per write + snapshot + +## telling a class from other functions by its `prototype` property + class: prototype not writable + function declaration: prototype writable + arrow: prototype absent + method: prototype absent + async function: prototype absent + built-in Date: prototype not writable +``` + +### Prototype A: proxy-compare as the `this` of a snapshot getter + +```ts +// Prototype A: proxy-compare's createProxy(snapshot) as `this`, using the +// proxy-compare instance our library itself loads. +import { + createProxy, + isChanged, +} from '/packages/classy-store/src/storeRuntime.ts'; +import {getUntracked} from '/node_modules/.bun/proxy-compare@3.0.1/node_modules/proxy-compare'; +import {c} from './libs'; + +class Bag { + static [c.PROXYABLE] = true; + a = 1; + b?: number = 2; + rows = [{id: 1}, {id: 2}]; + child = new (class Row { + static [c.PROXYABLE] = true; + n = 1; + })(); +} +const store = c.createClassyStore(new Bag()); +const snap = c.snapshot(store) as Bag; +const affected = new WeakMap(); +const tracked = createProxy(snap, affected) as Bag; +console.log( + 'same proxy-compare instance (the root is wrapped):', + tracked !== snap, +); +console.log('A. proxy-compare createProxy(snapshot) as `this`'); +console.log( + ' Object.keys(this).length:', + Object.keys(tracked).length, + '(the snapshot has', + Object.keys(snap).length, + ')', +); +console.log(' "b" in this:', 'b' in tracked); +console.log(' this instanceof Bag:', tracked instanceof Bag); +const row = tracked.rows[0]; +console.log( + ' this.rows[0] is the snapshot row:', + row === snap.rows[0], + '| getUntracked finds it:', + getUntracked(row) === snap.rows[0], +); +const open = tracked.rows.filter((r) => r.id > 0); +console.log( + ' this.rows.filter(...)[0] is the snapshot row:', + open[0] === snap.rows[0], +); +console.log( + ' this.child is the snapshot child:', + tracked.child === snap.child, + '| getUntracked finds it:', + getUntracked(tracked.child) === snap.child, +); +delete store.b; +const next = c.snapshot(store); +console.log( + ' isChanged after delete store.b:', + isChanged(snap, next, affected), +); +``` + +Output: + +```text +same proxy-compare instance (the root is wrapped): true +A. proxy-compare createProxy(snapshot) as `this` + Object.keys(this).length: 4 (the snapshot has 4 ) + "b" in this: true + this instanceof Bag: true + this.rows[0] is the snapshot row: false | getUntracked finds it: true + this.rows.filter(...)[0] is the snapshot row: false + this.child is the snapshot child: false | getUntracked finds it: false + isChanged after delete store.b: true +``` + +### Prototypes B and C: hand-written trackers + +```ts +// Prototypes B and C: two hand-written trackers for what a snapshot getter +// reads, tried on a real snapshot of ours. Prototype A is in the next file. +import {c} from './libs'; + +class Bag { + static [c.PROXYABLE] = true; + a = 1; + b?: number = 2; + rows = [{id: 1}, {id: 2}]; +} +const store = c.createClassyStore(new Bag()); +const snap = c.snapshot(store) as Bag; + +const count = function (this: Bag) { + return Object.keys(this).length; +}; +const hasB = function (this: Bag) { + return 'b' in this; +}; +const isBag = function (this: Bag) { + return this instanceof Bag; +}; +const firstRow = function (this: Bag) { + return this.rows[0]; +}; +const openRows = function (this: Bag) { + return this.rows.filter((row) => row.id > 0); +}; + +console.log( + 'B. a Proxy over the frozen snapshot itself, with get, has and ownKeys traps', +); +{ + const reads: string[] = []; + const tracked = new Proxy(snap, { + get(target, prop) { + reads.push(`get ${String(prop)}`); + return Reflect.get(target, prop, target); + }, + has(target, prop) { + reads.push(`has ${String(prop)}`); + return Reflect.has(target, prop); + }, + ownKeys(target) { + reads.push('ownKeys'); + return Reflect.ownKeys(target); + }, + }); + console.log(' Object.keys(this).length:', count.call(tracked)); + console.log(' "b" in this:', hasB.call(tracked)); + console.log(' this instanceof Bag:', isBag.call(tracked)); + console.log( + ' this.rows[0] is the snapshot row:', + firstRow.call(tracked) === snap.rows[0], + ); + console.log( + ' this.rows.filter(...)[0] is the snapshot row:', + openRows.call(tracked)[0] === snap.rows[0], + ); + console.log(' recorded:', [...new Set(reads)].join(', ')); +} + +console.log('C. what we do today: a Proxy over {} with a get trap only'); +{ + const tracked = new Proxy( + {}, + { + get(_t, prop) { + return Reflect.get(snap, prop, snap); + }, + }, + ) as Bag; + console.log(' Object.keys(this).length:', count.call(tracked)); + console.log(' "b" in this:', hasB.call(tracked)); + console.log(' this instanceof Bag:', isBag.call(tracked)); +} +``` + +Output: + +```text +B. a Proxy over the frozen snapshot itself, with get, has and ownKeys traps + Object.keys(this).length: 3 + "b" in this: true + this instanceof Bag: true + this.rows[0] is the snapshot row: true + this.rows.filter(...)[0] is the snapshot row: true + recorded: ownKeys, has b, get rows +C. what we do today: a Proxy over {} with a get trap only + Object.keys(this).length: 0 + "b" in this: false + this instanceof Bag: false +``` + +### `getUntracked` with the proxy-compare instance our library loads + +```ts +import {createProxy} from '/packages/classy-store/src/storeRuntime.ts'; +import {getUntracked} from '/node_modules/.bun/proxy-compare@3.0.1/node_modules/proxy-compare'; +import {c} from './libs'; +class Row { + static [c.PROXYABLE] = true; + n = 1; +} +const store = c.createClassyStore({ + plain: {n: 1}, + row: new Row(), + selected: null as unknown, +}); +const snap = c.snapshot(store) as {plain: object; row: object}; +const tracked = createProxy(snap, new WeakMap()) as typeof snap; +console.log( + 'plain row: tracking proxy', + tracked.plain !== snap.plain, + '| getUntracked finds the snapshot', + getUntracked(tracked.plain) === snap.plain, +); +console.log( + 'class row: tracking proxy', + tracked.row !== snap.row, + '| getUntracked finds the snapshot', + getUntracked(tracked.row) === snap.row, +); +``` + +Output: + +```text +plain row: tracking proxy true | getUntracked finds the snapshot true +class row: tracking proxy true | getUntracked finds the snapshot false +``` + +### Prototype: a lazy index for a frozen snapshot array + +```ts +// A lookup index built lazily for a frozen snapshot array, which can never go stale. +import {c, cc} from './libs'; +import {identityOf} from '/packages/classy-store/src/storeRuntime.ts'; + +const indexes = new WeakMap>(); +function indexOfFrozen(backing: readonly unknown[], member: unknown): number { + let index = indexes.get(backing); + if (!index) { + index = new Map(); + for (let i = 0; i < backing.length; i++) { + const identity = identityOf(backing[i]); + if (!index.has(identity)) index.set(identity, i); + } + indexes.set(backing, index); + } + return index.get(identityOf(member)) ?? -1; +} + +for (const kind of ['numbers', 'objects'] as const) { + const members = Array.from({length: 10_000}, (_, i) => + kind === 'numbers' ? i : {id: i}, + ); + const store = c.createClassyStore({set: cc.reactiveSet(members)}); + const snap = c.snapshot(store) as { + set: {has(v: unknown): boolean; _items: readonly unknown[]}; + }; + const wanted = Array.from({length: 1_000}, (_, i) => members[9_000 + i]); + let start = performance.now(); + let hits = 0; + for (const value of wanted) if (snap.set.has(value)) hits++; + const today = performance.now() - start; + start = performance.now(); + let hits2 = 0; + for (const value of wanted) + if (indexOfFrozen(snap.set._items, value) !== -1) hits2++; + const indexed = performance.now() - start; + console.log( + `${kind}: 1,000 lookups in a snapshot of 10,000: today ${today.toFixed(2)} ms (${hits} hits), with a lazy index ${indexed.toFixed(2)} ms (${hits2} hits, index build included)`, + ); +} +``` + +Output: + +```text +numbers: 1,000 lookups in a snapshot of 10,000: today 101.27 ms (1000 hits), with a lazy index 0.77 ms (1000 hits, index build included) +objects: 1,000 lookups in a snapshot of 10,000: today 250.96 ms (1000 hits), with a lazy index 0.84 ms (1000 hits, index build included) +``` + +### Micro-benchmark: reading a frozen array + +```js +// Is reading a frozen array slower than reading an unfrozen one? +const make = () => Array.from({length: 10_000}, (_, i) => i); +const plain = make(); +const frozen = Object.freeze(make()); +const nonWritable = make(); +for (let i = 0; i < nonWritable.length; i++) + Object.defineProperty(nonWritable, i, {writable: false}); +function scan(list, wanted) { + for (let index = 0; index < list.length; index++) + if (Object.is(list[index], wanted)) return index; + return -1; +} +function time(label, list) { + for (let i = 0; i < 200; i++) scan(list, 9_999); // warm up + const start = performance.now(); + let sum = 0; + for (let i = 0; i < 1_000; i++) sum += scan(list, 9_000 + (i % 1_000)); + const ms = performance.now() - start; + console.log( + ` ${label}: ${((ms * 1000) / 1_000).toFixed(1)} microseconds per scan`, + ); + return sum; +} +time('plain array', plain); +time('frozen array', frozen); +time('non-writable elements, not frozen', nonWritable); +const objs = Object.freeze( + Array.from({length: 10_000}, (_, i) => Object.freeze({id: i})), +); +const objsPlain = Array.from({length: 10_000}, (_, i) => ({id: i})); +function sumIds(list) { + let s = 0; + for (const row of list) s += row.id; + return s; +} +for (const [label, list] of [ + ['for-of over plain rows', objsPlain], + ['for-of over frozen rows', objs], +]) { + for (let i = 0; i < 200; i++) sumIds(list); + const start = performance.now(); + for (let i = 0; i < 1_000; i++) sumIds(list); + console.log( + ` ${label}: ${(((performance.now() - start) * 1000) / 1_000).toFixed(1)} microseconds per pass`, + ); +} +``` + +Output: + +```text +Bun 1.4.4 (JavaScriptCore) + plain array: 4.5 microseconds per scan + frozen array: 140.8 microseconds per scan + non-writable elements, not frozen: 146.6 microseconds per scan + for-of over plain rows: 12.7 microseconds per pass + for-of over frozen rows: 164.0 microseconds per pass +Node v24.21.0 (V8) + plain array: 20.6 microseconds per scan + frozen array: 56.1 microseconds per scan + non-writable elements, not frozen: 238.0 microseconds per scan + for-of over plain rows: 22.2 microseconds per pass + for-of over frozen rows: 70.4 microseconds per pass +``` + +### Type check: tuples and collection snapshots + +Run with `tsc` 7.0.2 in the scratch folder: exit code 0. A copy with one +more line, asserting that our `Snapshot<[string, number]>` is a tuple, fails +with `TS2344`, so the assertions are being checked. + +```ts +import type {Snapshot as ValtioSnapshot} from 'valtio/vanilla'; +import {proxyMap} from 'valtio/vanilla/utils'; +import type {Snapshot as OurSnapshot} from '/packages/classy-store/src/types'; + +type Equal = + (() => T extends A ? 1 : 2) extends () => T extends B ? 1 : 2 + ? true + : false; +const yes = () => {}; + +// Stage 1 finding 14: a tuple. +yes, readonly [string, number]>>(); +yes, readonly (string | number)[]>>(); +yes, readonly {readonly id: number}[]>>(); + +// Our type without its Array branch, as Valtio writes it. +type Leaf = + | string + | number + | boolean + | null + | undefined + | symbol + | bigint + | ((...args: never[]) => unknown) + | Date; +type Without = T extends Leaf + ? T + : T extends object + ? {readonly [K in keyof T]: Without} + : T; +yes, readonly [string, number]>>(); +yes, readonly {readonly id: number}[]>>(); + +// Stage 1 finding 16: a snapshot of a collection has no mutators in its type. +const map = proxyMap(); +type MapSnapshot = ValtioSnapshot; +yes>(); +yes>(); +``` + +### The timing scripts + +The output of `bench.ts` is the table under "Rough timings". + +```ts +// A rough timing of the same operations on both libraries. One process, three +// rounds each, best round reported. Not the repository's benchmark. +import {libs, type Lib} from './libs'; + +let sink = 0; +function time(run: (i: number) => void, iterations: number): number { + for (let i = 0; i < Math.min(iterations, 2_000); i++) run(i); // warm up + let best = Infinity; + for (let round = 0; round < 3; round++) { + const start = performance.now(); + for (let i = 0; i < iterations; i++) run(i); + best = Math.min(best, ((performance.now() - start) * 1e6) / iterations); + } + return best; +} +const rows = (n: number) => + Array.from({length: n}, (_, id) => ({id, done: false, meta: {tags: {a: 1}}})); + +const cases: [string, (lib: Lib) => number][] = [ + [ + 'read a field', + (lib) => { + const s = lib.create({n: 1}); + return time(() => { + sink += s.n; + }, 2_000_000); + }, + ], + [ + 'read a field three objects deep', + (lib) => { + const s = lib.create({a: {b: {c: {n: 1}}}}); + return time(() => { + sink += s.a.b.c.n; + }, 2_000_000); + }, + ], + [ + 'write a field, no subscriber', + (lib) => { + const s = lib.create({n: 0}); + return time((i) => { + s.n = i; + }, 1_000_000); + }, + ], + [ + 'write a field, one sync subscriber', + (lib) => { + const s = lib.create({n: 0}); + lib.subscribe( + s, + () => { + sink++; + }, + true, + ); + return time((i) => { + s.n = i; + }, 1_000_000); + }, + ], + [ + 'call a method that writes one field', + (lib) => { + class C { + n = 0; + set(v: number) { + this.n = v; + } + } + const s = lib.create(new C()); + return time((i) => { + s.set(i); + }, 1_000_000); + }, + ], + [ + 'take a cached snapshot', + (lib) => { + const s = lib.create({n: 1, rows: rows(10)}); + lib.snapshot(s); + return time(() => { + sink += lib.snapshot(s).n; + }, 2_000_000); + }, + ], + [ + 'write one of 1,000 rows, then snapshot (unobserved)', + (lib) => { + const s = lib.create({rows: rows(1_000)}); + lib.snapshot(s); + return time((i) => { + s.rows[i % 1_000].done = !s.rows[i % 1_000].done; + lib.snapshot(s); + }, 2_000); + }, + ], + [ + 'write one of 1,000 rows, then snapshot (observed)', + (lib) => { + const s = lib.create({rows: rows(1_000)}); + lib.subscribe(s, () => {}, true); + lib.snapshot(s); + return time((i) => { + s.rows[i % 1_000].done = !s.rows[i % 1_000].done; + lib.snapshot(s); + }, 2_000); + }, + ], + [ + 'write to another store, then snapshot an unchanged 1,000-row store', + (lib) => { + const s = lib.create({rows: rows(1_000)}); + const other = lib.create({n: 0}); + lib.snapshot(s); + return time((i) => { + other.n = i; + lib.snapshot(s); + }, 5_000); + }, + ], + [ + 'create a store of 1,000 rows', + (lib) => + time(() => { + lib.create({rows: rows(1_000)}); + }, 200), + ], + [ + 'create a store of 1,000 rows and snapshot it', + (lib) => + time(() => { + lib.snapshot(lib.create({rows: rows(1_000)})); + }, 200), + ], + [ + 'sort 1,000 rows, one sync subscriber that snapshots', + (lib) => { + const s = lib.create({rows: rows(1_000)}); + lib.subscribe( + s, + () => { + lib.snapshot(s); + }, + true, + ); + return time((i) => { + s.rows.sort((a, b) => (i % 2 ? a.id - b.id : b.id - a.id)); + }, 20); + }, + ], + [ + 'read a getter that sums 1,000 rows, nothing changed', + (lib) => { + class C { + rows = rows(1_000); + get total() { + let t = 0; + for (const r of this.rows) t += r.id; + return t; + } + } + const s = lib.create(new C()); + return time(() => { + sink += s.total; + }, 2_000); + }, + ], +]; + +const fmt = (ns: number) => + ns >= 1e6 + ? `${(ns / 1e6).toFixed(2)} ms` + : ns >= 1e3 + ? `${(ns / 1e3).toFixed(1)} us` + : `${ns.toFixed(1)} ns`; +console.log('| Operation | Valtio 2.3.2 | Ours |'); +console.log('| --- | ---: | ---: |'); +for (const [label, run] of cases) { + const results = libs.map((lib) => run(lib)); + console.log(`| ${label} | ${fmt(results[0])} | ${fmt(results[1])} |`); +} +if (sink === -1) console.log(sink); +``` + +```ts +import {libs} from './libs'; +const rows = (n: number) => + Array.from({length: n}, (_, id) => ({id, done: false, meta: {tags: {a: 1}}})); +for (const lib of libs) { + const store = lib.create({rows: rows(1_000)}); + for (let i = 0; i < 200; i++) lib.subscribe(store, () => {}, true)(); + let best = Infinity; + for (let round = 0; round < 3; round++) { + const start = performance.now(); + for (let i = 0; i < 2_000; i++) lib.subscribe(store, () => {}, true)(); + best = Math.min(best, ((performance.now() - start) * 1e6) / 2_000); + } + const keep = lib.subscribe(store, () => {}, true); + let second = Infinity; + for (let round = 0; round < 3; round++) { + const start = performance.now(); + for (let i = 0; i < 200_000; i++) lib.subscribe(store, () => {}, true)(); + second = Math.min(second, ((performance.now() - start) * 1e6) / 200_000); + } + keep(); + console.log( + `[${lib.name}] subscribe + unsubscribe on a 1,000-row store (3,002 nodes): only subscriber ${best.toFixed(0)} ns, second subscriber ${second.toFixed(0)} ns`, + ); +} +``` + +Output of `bench2.ts`: + +```text +[valtio] subscribe + unsubscribe on a 1,000-row store (3,002 nodes): only subscriber 372823 ns, second subscriber 86 ns +[classy] subscribe + unsubscribe on a 1,000-row store (3,002 nodes): only subscriber 79 ns, second subscriber 63 ns +``` diff --git a/review/stage-2/vue-reactivity.md b/review/stage-2/vue-reactivity.md new file mode 100644 index 00000000..a2bfd921 --- /dev/null +++ b/review/stage-2/vue-reactivity.md @@ -0,0 +1,2958 @@ +# Stage 2: Vue reactivity (`@vue/reactivity`) + +Stage 2 of the pre-1.0 review, 2026-11-18. Read-only: nothing in the +repository was changed apart from this file. + +## Library, version and files read + +- **Library:** `@vue/reactivity`, from `https://github.com/vuejs/core`. +- **Version:** 3.5.45, the npm `latest` tag on 2026-11-18. Version 3.6 is at + `3.6.0-rc.15` on npm and was not read. +- **Commit:** `8b479a89445868d474f17e2d837765e7c9ece5e4`, tag `v3.5.45`, dated + 2026-11-05, cloned into a scratch folder and read there. +- **Files read**, under `packages/reactivity/src/`: `reactive.ts`, + `baseHandlers.ts`, `collectionHandlers.ts`, `arrayInstrumentations.ts` and + `dep.ts` whole; `effect.ts` lines 39 to 433 and `computed.ts` lines 40 to + 220, which hold everything that decides when an effect runs and when a + computed value is recomputed. Four helpers in `packages/shared/src/general.ts` + (`isObject`, `toRawType`, `isIntegerKey`, `hasChanged`), the package's + `index.ts` for what it exports, and a dozen lines of `watch.ts` were looked up. +- **Ours:** `core/core.ts`, `core/ownership.ts`, `snapshot/snapshot.ts`, + `collections/collections.ts`, `utils/internal/internal.ts`, `types.ts` and + `frameworks/vue/vue.ts`. +- **Ported tests** ran on Bun 1.4.4 against `@vue/reactivity@3.5.45` installed + from npm in the scratch folder (its development build), and against our + source imported by absolute path. Their code and output are at the end. + +Line numbers for Vue refer to that commit. Line numbers for ours refer to +`release/1.0` at `9ab9744`. + +## Summary + +Vue's proxies answer five of the thirteen object operations a Proxy can trap +(`get`, `set`, `deleteProperty`, `has`, `ownKeys`), replace 27 array methods, +and make native `Map` and `Set` reactive. Ours answer four (`get`, +`set`, `defineProperty`, `deleteProperty`). The comparison gives eleven +findings. The three that matter most: + +1. **`has` and `ownKeys` (finding 1).** Vue records a dependency for `key in + state` and for `Object.keys(state)`, and wakes the second only when a key is + added or removed. A sketch of the same idea in a throwaway copy of our + source fixed stage 1 findings 29 and 30 on the live store. On the snapshot + it showed that the fix cannot be separated from API question 3: because + snapshot getters are enumerable own accessors, a getter that lists the keys + of `this` counts the getters too, and one that calls `Object.entries(this)` + calls itself until the stack overflows. +2. **Raw values on write, and one node per raw object (findings 2 and 3).** Vue + strips the proxy from every value before it stores it, and finds an + object's proxy by the raw object. That one rule is why `includes(raw)` + works, why the raw graph never holds a proxy, and why an object that is + already reactive stays connected however it is handed over. A second sketch + (20 lines added, 7 removed) fixed stage 1 findings 5, 6, 7, 9, 10 and 42 + together with finding 4 below. +3. **A function is a value unless it is a method (finding 4).** Vue wraps no + function at all. We wrap every function read through a store, which is the + one cause behind stage 1 findings 5, 6, 42 and 62. We should keep binding + and transactions for methods, which Vue lacks, and stop wrapping array + elements, classes and `constructor`. + +Vue is not better everywhere. "Where we already do better" lists six cases +where our behaviour is the one to keep. + +## How the two designs differ + +This explains why some of Vue's answers carry over and some cannot. + +- **Vue keeps nothing per property.** A proxy is made the first time an object + is read and kept in a `WeakMap` keyed by the raw object (`reactiveMap`, + `reactive.ts:26`; lookup in `createReactiveObject`, `reactive.ts:292`). Each + `get` reads the target again and looks the proxy up again + (`baseHandlers.ts:99`, `:126-131`). One handler object serves every proxy + (`baseHandlers.ts:251`). +- **We keep an index of children per node** (`childInternals`, + `ownership.ts:14`), filled when the store is made (`core.ts:535-542`) and + kept in step by `set`, `deleteProperty` and the freezing half of + `defineProperty`. Snapshots with structural sharing need it: a write has to + reach every owner to bump its version (`core.ts:221-239`). Whatever changes + the target without updating the index leaves the store answering from the + old child. Stage 1 findings 45, 46 and 71 are all that. +- **Vue subscribes per property and per reader.** Reading `state.a` inside an + effect or a computed value links that reader to `(state, 'a')` + (`track`, `dep.ts:262`). There are no parent links, no ownership graph and so + nothing like our suspend and resume. Stage 1 findings 28, 61, 66 to 70 and 72 + have no counterpart. +- **Vue has no snapshots.** `readonly()` is a live view through a second proxy, + not a frozen copy. Questions about what a snapshot contains get "no + position". + +## Findings + +### 1. `has` and `ownKeys` traps, and a dependency on the set of keys + +Stage 1 findings 30, 31 and 41. Bears on API question 3. + +- **What they do.** `MutableReactiveHandler.has` (`baseHandlers.ts:207`) + records a dependency on the key. `ownKeys` (`baseHandlers.ts:215`) records + one on a marker that stands for "the set of keys of this object" + (`ITERATE_KEY`), or on `length` for an array. `trigger` (`dep.ts:294`) wakes + the readers of that marker only when a key is added or deleted + (`dep.ts:358-378`), not when a value changes. `get` records a dependency on a + key whether or not the key exists (`baseHandlers.ts:113`), so a reader of a + missing key is woken when the key appears. +- **What we do.** The store proxy has `get`, `set`, `defineProperty` and + `deleteProperty` (`core.ts:405-525`). `in` and `Object.keys` reach the target + directly and record nothing. A snapshot getter runs with `this` set to a + proxy over an empty object that has only a `get` trap (`snapshot.ts:80-93`), + so `in`, `Object.keys` and `instanceof` answer for the empty object. +- **Difference in behaviour.** Port 2. Vue: the key count goes 2, 2, 1, 2, 3 + and `'b' in state` goes true, true, false, false, true over a value write, a + delete and two additions, and each computed value re-runs only when its + answer could have changed. Ours: the live getters still say 2 and `true` + after `delete store.b`; the snapshot getters say 0 and `false` from the + start. +- **Proposal: adapt.** Vue pushes changes to readers and we validate on read, + so its mechanism does not carry over, but its two ideas do: + 1. Two more kinds of getter dependency on the live store. `has` records the + key and whether it was present, and is checked with `Reflect.has`. `keys` + records a per-node counter that moves only when a key is added or + removed. + 2. On the snapshot side, make the frozen snapshot the target of the + tracking proxy, so that every operation without a trap answers for the + real object, and add the same two traps. + + I tried both in a throwaway copy (port 13, 48 added lines). The live store + then answers 2 and `true`, 1 and `false` after the delete, 3 and `true` + after the additions. On the snapshot `'b' in this` and + `this instanceof Dict` become right, but `Object.keys(this).length` is 5 + where the live store says 2. The snapshot holds each getter as an enumerable + own accessor (`snapshot.ts:213-217`), so the three getters are counted. Port + 14 shows the sharper form: a getter that calls `Object.entries(this)` reads + itself and overflows the stack. So this fix has to be decided together with + API question 3. Either snapshot getters stop being enumerable, or the + tracker's `ownKeys` leaves accessors out. +- **Kind:** bug. +- **Cost:** `core.ts`, `ownership.ts` or `core.types.ts`, `snapshot.ts`; about + 50 lines. Not breaking on the live store. On a snapshot it changes what a + getter sees through `this`. Risk: medium, because of the tie to question 3. + The sketch was not run against the repository's suite. + +### 2. Identity-sensitive searches on a list + +Stage 1 finding 7. + +- **What they do.** `includes`, `indexOf` and `lastIndexOf` are replaced + (`arrayInstrumentations.ts:144-160`) by `searchProxy` + (`arrayInstrumentations.ts:380`). It runs the native method on the raw array + with the argument as given. If that finds nothing and the argument is a + proxy, it runs again with the raw argument. +- **What we do.** The native method runs with the proxy as `this` + (`core.ts:486`), so every element it reads is a proxy and is compared with + `===` against the argument. +- **Difference in behaviour.** Port 1. Vue: `list.includes(raw)` is `true` + and `indexOf(raw)` is 0. Ours: `false` and -1. In both libraries + `findIndex((x) => x === raw)` is -1, because a callback is handed proxies. + Vue's two tries have a gap of their own: a list built around a proxy misses + the raw object (`reactive([reactive(raw)]).includes(raw)` is `false`). +- **Proposal: adopt, and compare by `identityOf`.** `identityOf` + (`core.ts:52`) already gives one identity to a raw object, its proxy and its + snapshots, and `indexOfMember` uses it for the collections + (`collections.ts:16-33`). The three array searches should use the same + comparison. That closes Vue's gap as well. Port 15 shows a sketch: raw, + proxy and snapshot row are all found. +- **Kind:** bug. +- **Cost:** `core.ts` `get` trap, about ten lines. `includes(raw)` changes + from `false` to `true`. Risk: low. The sketch maps the whole array on each + call; the real version should loop once. + +### 3. Store raw values on write, and find a node by the raw object + +Stage 1 findings 9, 10 and 34. + +- **What they do.** `set` strips the proxy from the new value and from the + old one before it compares and stores them (`baseHandlers.ts:150-155`). + `Set.add` and `Map.set` do the same (`collectionHandlers.ts:169-176`, + `:190-192`). The proxy for an object is looked up by the raw object, and that + lookup comes before the check of what kind of object it is + (`reactive.ts:292`, then `:296`). So the raw graph never holds a proxy, and + one object has one proxy however it arrives. +- **What we do.** `set` stores what it is given, apart from a React tracking + proxy (`core.ts:409-412`, `:432`), and so has to compare against both forms + (`core.ts:421-427`). `linkChild` looks an existing node up by proxy only + (`core.ts:364`) and applies `canProxy` to a raw value (`core.ts:368`). A + class instance that is already a store, handed over raw, fails that check + and is left unconnected. +- **Difference in behaviour.** Port 7. Vue: after `to.row = from.row` and + after `list.reverse()` the raw objects hold raw rows; + `outer.inner === inner` is `true` and an effect ran for both `inc()` calls. + Ours: the raw objects hold proxies; `outer.inner === inner` is `false` and + `outer.inner.inc()` notified neither store. Port 10 shows a consequence of + Vue's rule: `structuredClone(toRaw(state))` works. +- **Proposal: adopt both halves.** Unwrap a store proxy in `set`, and let + `linkChild` find a node by raw object as well as by proxy. Port 15 shows a + sketch: the raw target holds the raw row, the two owners share one proxy and + both are notified, and the store placed by its raw object is connected. The + two-form comparison at `core.ts:421-427` then reduces to one. Two rules must + survive the change: a value under a read-only property is returned as it is + (`core.ts:369-374`), and a frozen container keeps whatever form it was given. +- **Kind:** bug, and a simplification. +- **Cost:** `core.ts`, `set` trap and `linkChild`, about ten lines. The raw + object behind a store holds raw children after a write, which only code that + keeps the raw object can see. Risk: medium, because it touches attach and + detach. Not run against the repository's suite. + +### 4. A function is a value unless it is a method + +Stage 1 findings 5, 6, 42 and 62. + +- **What they do.** Nothing wraps a function. `createReactiveObject` returns + anything that is not an object as it is (`reactive.ts:269`; `isObject` is + `typeof value === 'object'`), and `get` converts only objects + (`baseHandlers.ts:126`). A method takes `this` from the call, so + `state.inc()` runs with the proxy as `this`. The replaced array methods live + in one table shared by every array (`arrayInstrumentations.ts:52`). +- **What we do.** Every function read through a store is wrapped: a new + wrapper on each read for an array (`core.ts:486`), one cached per key + otherwise (`core.ts:487-491`). The wrapper binds `this` and opens a + transaction (`transactional`, `core.ts:263-277`). +- **Difference in behaviour.** Port 1. Vue: a function in an array is the same + on every read and `splice(indexOf(first), 1)` removes the right one; a class + held as a property keeps its statics and `instanceof`; `constructor` is the + class. A destructured method throws, because it is not bound. Ours: a new + wrapper each time, so `indexOf` is -1 and the splice removes the last + callback; `store.Model.label` is `undefined`; a destructured method works. +- **Proposal: adapt.** Keep binding and transactions for methods. They are + what Vue lacks: in port 6 one `reverse()` of eight slots re-ran a Vue effect + eight times, and ours notified once. Narrow what counts as a method: + 1. On an array, an own property that holds a function is an element. Return + it as it is. + 2. Return `constructor` as it is. + 3. Return a class as it is. A class can be told from a method without + guessing: its `prototype` property is not writable, an ordinary + function's is, and a method or an arrow function has none (port 10). + + Port 15 shows a sketch that fixes findings 5, 6 and 42 and keeps a + destructured method working. A shared table of array methods that take + `this` from the call, as Vue has, would also end the allocation on each + read. For finding 62, Vue's answer is that a function is never made + reactive: `reactive(fn)` returns `fn` and warns in development. +- **Kind:** bug. +- **Cost:** `core.ts` `get` trap, about ten lines. `store.Model` and + `store.constructor` become the class itself. Risk: low. + +### 5. A delete that removes nothing + +Stage 1 finding 29. + +- **What they do.** `deleteProperty` asks whether the key was an own key + before deleting, and triggers only if it was (`baseHandlers.ts:198-203`). +- **What we do.** `deleteProperty` notifies whenever `Reflect.deleteProperty` + succeeds, which it does for a missing key (`core.ts:515-524`). +- **Difference in behaviour.** Port 2. Vue: `delete state.missing` and + `delete list[5]` re-run nothing. Ours: one notification and a new snapshot + equal to the old one. +- **Proposal: adopt.** Check `Object.hasOwn` first. Port 13's sketch includes + it: no notification. +- **Kind:** bug. +- **Cost:** two lines in `core.ts`. Not breaking. Risk: low. + +### 6. `Object.defineProperty` through the proxy + +Stage 1 findings 1, 45 and 71. Bears on API question 4. + +- **What they do.** There is no `defineProperty` trap. The call reaches the + target and triggers nothing, which is the same silence as ours. Reads are + right afterwards all the same, because nothing is kept per property: the + next `get` reads the target (`baseHandlers.ts:99`). +- **What we do.** The trap handles the read-only case only + (`core.ts:502-513`). The child index is not updated, and `get` answers from + it first (`core.ts:496-499`). +- **Difference in behaviour.** Port 3. After redefining `child` to another + object, to 7, a list's `length` to 1 and its element 0 to 7, Vue reads 2, 7, + `undefined` and 7. Ours reads 1, `{n: 1}`, `{id: 3}` and `{id: 1}`, while the + snapshot says 7 for the last. Neither library tells a reader. + + Port 8 shows where this is reached without anyone calling + `Object.defineProperty`. When a base class constructor returns the proxy, + the fields of a derived class are defined through it. With our store, + `snapshot(todo).items` is then the raw array, not frozen, until the field + is first read through the store. +- **Proposal: adapt.** Take the outcome, not the missing trap: after any + define, the store must agree with the target. A define of a data property + is a write (relink the child, bump the version, notify). A define of an + accessor removes the child. This is required if question 4 is answered with + a base class. +- **Kind:** bug. +- **Cost:** `core.ts` trap, about 25 lines. Not breaking. Risk: medium. The + one-line fix for stage 1 finding 66 belongs in the same trap. Not sketched. + +### 7. Array reads on the raw array + +Stage 1 finding 3. Performance. + +- **What they do.** The methods that read a whole array (`forEach`, `map`, + `filter`, `find`, `some`, `every`, `reduce`, `join`, the iterators and + others) record one dependency for the array and then run the native method + on the raw array, converting each element as it is handed to the callback + (`apply`, `arrayInstrumentations.ts:310-346`; `shallowReadArray`, `:40`; + `reduce`, `:349`). An array subclass with its own method takes the ordinary + path (`:323-330`). `get` makes no descriptor lookup. +- **What we do.** The native method runs on the proxy (`core.ts:486`). Each + index goes through `get`: a descriptor lookup along the prototype chain + (`core.ts:464`, `internal.ts:88-99`), a `Map` lookup by string index + (`core.ts:497`) and `recordDep` (`core.ts:498`). +- **Difference in behaviour.** Port 11, on one machine (Apple M1 Max, Bun + 1.4.4, best of seven rounds), so indicative only: + + | Operation | Raw | Vue | Ours | + | ------------------------------------------ | -----: | ------: | -------: | + | Read a number field | 1.7 ns | 15.9 ns | 31.3 ns | + | Sum 1,000 rows with `reduce`, per row | 2.1 ns | 75.9 ns | 126.2 ns | + | Sum 1,000 rows with an index loop, per row | | 221 ns | 135 ns | + | `list.includes(10)` on ten numbers | | 56.9 ns | 921 ns | + + Vue's `reduce` figure includes a recorded dependency on every row's `value`, + which we do not need. Its index loop is slower than ours because it records + one dependency per index. +- **Proposal: adapt.** For the array methods that only read, run the native + method on the raw array and hand out each element's proxy. A getter being + tracked already holds one version dependency on the array node + (`core.ts:93-101`), so nothing is needed per element. `includes` and + `indexOf` on a list of primitives need no proxy work at all. +- **Kind:** performance. +- **Cost:** `core.ts`, a table of about fifteen methods. Not breaking if a + callback still receives proxies and the proxy as its third argument. Risk: + medium (sparse arrays, array subclasses, a callback that writes). Not + sketched: the gain on our side is an expectation from Vue's numbers, not a + measurement. + +### 8. What a computed value records, and when + +Stage 1 findings 32, 36 and 38. + +- **What they do.** Each dependency has a version counter that moves on every + trigger (`Dep.trigger`, `dep.ts:167`). Each pair of dependency and reader is + a `Link` that remembers the version the reader last saw (`dep.ts:32`, + `:127`). On a read, `refreshComputed` (`effect.ts:376`) returns the cached + value when nothing reactive has been written anywhere since the last check + (`:387`), or when `isDirty` (`effect.ts:353`) finds every link's version + unchanged, refreshing nested computed values first. Otherwise it runs the + function, collects the dependencies again (`prepareDeps` and `cleanupDeps`, + `:312-351`), and moves its own version only if the result changed by + `Object.is` (`:416`). Three details matter for us: + 1. Every reactive read made while the function runs is recorded, on any + object (`track`, `dep.ts:262`). + 2. The link to a nested computed value is made before that value is + evaluated (`computed.ts:131-139`), so one that throws is still a + dependency. + 3. A read of a missing key is a dependency on that key (finding 1). +- **What we do.** `recordDep` keeps only reads on the getter's own node + (`core.ts:91`). A nested getter is recorded after it returns + (`core.ts:467-475`), so not when it throws. A dependency on a missing key + fails validation every time (`core.ts:147`). +- **Difference in behaviour.** Ports 9 and 2. A value that reads another + object: Vue 21, ours 11 on the live store and 21 on a snapshot. A value that + catches another's error: Vue `'ok'` once the error stops, ours `'fallback'` + for good. A value that reads a missing key: Vue returns the same object on + both reads and recomputes when the key is added; ours builds a new object on + each read. + + The comparison goes the other way for a cycle. Vue returns `NaN` and reports + nothing. Our live store throws an error that names the cycle + (`core.ts:173-184`), which is the behaviour to keep. Our snapshot layer + overflows the stack and should throw the same error. +- **Proposal: adapt three things.** + 1. Record a nested getter before evaluating it, and treat a missing cache + entry as "recompute". The `if (!cached)` branch at `core.ts:140`, which + stage 1 finding 64 lists as unreachable, is then the one that handles it. + 2. Record whether the key was present with a value dependency, so that a + missing key is valid for as long as it stays missing. + 3. For a read on any other node, record that node's version, once per node + per evaluation. +- **Kind:** bug. +- **Cost:** `core.ts` (`recordDep`, `areDepsValid`, `get`), `core.types.ts`. + Not breaking. Risk: medium. The third change makes a getter that reads + another store recompute when that store changes, which is the point, and + adds a lookup per foreign read. Not sketched: the behaviour is measured, the + fix is reasoning from reading. + +### 9. Delivery: no re-entry, and no call after removal + +Stage 1 findings 18, 19 and 20. + +- **What they do.** `ReactiveEffect.notify` returns at once while the effect + is running (`effect.ts:150-156`), so an effect's own writes do not queue it + again. `endBatch` checks that an effect is still active just before it calls + it (`effect.ts:297`). The first error an effect throws is rethrown to the + writer after the others have run (`effect.ts:289-309`). The scheduler in + `runtime-core`, outside this package, has a limit of 100 repeats for a job + that queues itself (`scheduler.ts:64`; only that line was read). +- **What we do.** `deliver` copies the listeners and calls each one + (`core.ts:314-328`). It does not check that a listener is still subscribed + and has no guard against re-entry. Errors go to `console.error`. +- **Difference in behaviour.** Port 9. A Vue effect that writes what it reads + runs once per outside write, and an effect stopped by an earlier one in the + same delivery is not run. Stage 1 pins ours: stack overflow (18), unbounded + microtasks (19), one call after unsubscribing (20). +- **Proposal: adopt the check, adapt the guard.** Skip a listener that was + removed since the copy was made (finding 20). For finding 18, either skip a + sync listener that is already running, as Vue does, or count the depth and + throw an error that names the cause. Vue's choice means a subscriber does + not hear about its own writes, which suits a subscriber that corrects state. + For finding 19, a bound like the scheduler's, in development. No change + proposed for errors: logging keeps a faulty subscriber from breaking the + writer. +- **Kind:** bug (20), diagnostics (18, 19). +- **Cost:** `core.ts`, `deliver` and `subscribe`. The check is not breaking. A + guard changes what a subscriber that writes observes. Risk: low. + +### 10. Native `Map` and `Set` + +Stage 1 findings 12, 33 and 34. Bears on API question 5. + +- **What they do.** A native collection gets a proxy with a single trap, + `get`, which hands out replacement methods (`createInstrumentationGetter`, + `collectionHandlers.ts:270-296`). Each one takes the raw collection from + `this`, calls the native method on it and wraps what comes out (`get` + `:101`, `has` `:130`, `add` `:169`, `set` `:189`, `delete` `:213`, `clear` + `:232`, the iterators `:33`). Values are stored raw. A lookup tries the key + as given, then raw. The file is 331 lines and covers `Map`, `Set`, `WeakMap` + and `WeakSet` in mutable, read-only and shallow forms. In development it + warns when a collection holds both the raw and the reactive form of one + object (`checkIdentityKeys`, `:315`). +- **What we do.** Native collections are opaque (`internal.ts:70-82`). + `ReactiveMap` and `ReactiveSet` keep an array and scan it + (`collections.ts:16-33`). The arrays are public members (`collections.ts:54`, + `:209`). +- **Difference in behaviour.** Port 5. Vue: `state.set instanceof Set`; + `has` answers for the raw object and for the proxy; members come out + reactive; `add(-0)` after `0` leaves one member; `add(raw)` then + `add(proxy)` leaves one. Ours: a native set misses the proxy; `reactiveSet` + finds the raw object, the proxy and a snapshot of it; `add(-0)` after `0` + gives two members; `reactiveSet([raw, proxy])` holds two. +- **Proposal: do not replace the two classes for 1.0; take three details.** + Vue's proxy is a live view. Our consumers read frozen copies, and a native + `Map` cannot be frozen, so a snapshot would need a read-only class of its + own and a full copy on each change. That part is reasoning, and the Valtio + report is the place to test it. What can be taken now: + 1. Treat `+0` and `-0` as one member. `indexOfMember` compares with + `Object.is` (`collections.ts:30`); `Map` and `Set` do not. + 2. Remove duplicates by identity in the two constructors + (`collections.ts:57-70`, `:212-222`), as `add` already does. + 3. Warn in development when a native `Map` or `Set` is put in a store, + because that is the silent case. + + One decision is needed before 1.0 whichever way this goes: whether "a native + `Map` in a store is kept by reference" is part of the contract. Making it + reactive later would change what a snapshot holds. +- **Kind:** API design; the first two details are bugs. +- **Cost:** `collections.ts`, a few lines. The first changes the size of + `reactiveSet([0]).add(-0)`. Risk: low. + +### 11. Read-only types + +Stage 1 findings 14, 16 and 17. + +- **What they do.** `DeepReadonly` (`reactive.ts:157-177`) maps `Map` to + `ReadonlyMap` and `Set` to `ReadonlySet`, leaves functions, `Date`, `RegExp` + and `Error` alone, and uses a mapped type over `keyof T` for the rest, which + keeps a tuple a tuple. `ComputedRef` declares `readonly value` + (`computed.ts:27-28`). +- **What we do.** `Snapshot` turns every array into `ReadonlyArray` + (`types.ts:40-41`) and has no case for `ReactiveMap` or `ReactiveSet`, so + their mutators stay in the type. The Vue adapter returns + `Ref>`, cast from a `shallowRef` (`vue.ts:10-21`). +- **Difference in behaviour.** Port 12, a type check that passes: + `DeepReadonly<[string, number]>` is `readonly [string, number]`, and + `view.todos.set(...)` on a read-only `Map` is a compile error. +- **Proposal: adopt.** In `Snapshot`, drop the array case and let the + mapped type handle arrays and tuples, and map `ReactiveMap` and + `ReactiveSet` to interfaces without mutators. For the adapter, Vue's own + name for a ref that is replaced as a whole and not written by its reader is + `Readonly>`. +- **Kind:** API design. +- **Cost:** `types.ts`, `vue.ts` and the collection types. Breaking at the + type level for code that calls a mutator on a snapshot, which throws at run + time today. Risk: low. + +## Where we already do better + +Each was run. These are behaviours to keep. + +- **Freezing through the proxy** (port 4). `Object.freeze(state.config)` in + Vue freezes the target behind a live proxy, and the next nested read through + that proxy throws a `TypeError`. Ours reads 1, because the `defineProperty` + trap detaches the child (`core.ts:502-513`). +- **A read-only property that holds an object** (port 4). Vue throws on the + read. Ours returns the value (`core.ts:369-374`). +- **Sealed objects** (port 4). Vue leaves any non-extensible object out + (`reactive.ts:288`), so a sealed object is not reactive. Ours treats only a + frozen object as a value. +- **Transactions** (ports 6 and 8). Vue groups the writes of five array + methods (`noTracking`, `arrayInstrumentations.ts:401`). `reverse()` of eight + slots re-ran an effect eight times, `sort()` five times, and a setter that + writes two fields twice. Ours notifies once for each array method and store + method. Vue applications do not see this, because the framework's scheduler + groups the runs. +- **A setter on the prototype** (port 8). Vue's `set` takes it for a new key + (`baseHandlers.ts:174-186`), so an effect that reads only `Object.keys` ran + again. Ours checks the descriptor first (`core.ts:413-418`). +- **A cycle between getters** (port 9). Vue returns `NaN`. Our live store + throws an error that names the cycle. + +## Stage 1 findings with a counterpart in Vue + +"Run" means a ported test showed it. "Read" means it follows from the source +and was not run. + +| Stage 1 | What Vue does | Evidence | +| ------: | ------------------------------------------------------------------------------------------------------------------------ | ------------ | +| 1 | No `defineProperty` trap. The target changes, no effect is triggered, and reads are right afterwards. | Run, port 3 | +| 3 | Whole-array reads run on the raw array with one dependency for the array: 76 ns per row here, against 126 ns for ours. | Run, port 11 | +| 5 | A function in an array is returned as stored, the same on each read. | Run, port 1 | +| 6 | A class held as a property is returned as stored. Statics and `instanceof` work. | Run, port 1 | +| 7 | `includes`, `indexOf` and `lastIndexOf` find the raw object. A list built around a proxy still misses it. | Run, port 1 | +| 8 | An object can hold itself. The raw object holds itself raw. There is no snapshot to fail. | Run, port 7 | +| 9 | One proxy per raw object, found by the raw object. The instance is connected. | Run, port 7 | +| 10 | Raw objects never hold proxies: `set` strips them. | Run, port 7 | +| 11 | The same limit. A write through the raw object wakes no one. | Run, port 7 | +| 12 | Native `Set` and `Map` are reactive. `has` answers for the raw object and for the proxy. | Run, port 5 | +| 13 | A computed value on a self-referencing object does not re-run for a field it never read. | Run, port 7 | +| 14 | `DeepReadonly` keeps a tuple a tuple. | Run, port 12 | +| 16 | `DeepReadonly` of a `Map` has no mutators. At run time a write warns in development and does nothing. | Run, 5, 12 | +| 17 | Read-only handles are typed read-only: `ComputedRef` has `readonly value`, `DeepReadonly` maps a ref to a read-only one. | Read | +| 18 | A running effect is not queued again by its own writes. | Run, port 9 | +| 19 | Nothing in this package. The framework's scheduler stops after 100 repeats. | Read | +| 20 | An effect stopped during delivery is not called. | Run, port 9 | +| 26 | A dependency follows the property. After the object is replaced, the effect follows the new one. | Run, port 10 | +| 29 | A delete of a missing key triggers nothing. Nor does writing the value a field already holds, `NaN` included. | Run, port 2 | +| 30 | `in` and `Object.keys` are tracked. The reader re-runs when a key is added or removed. | Run, port 2 | +| 32 | A read of a missing key is cached and re-run when the key appears. | Run, port 2 | +| 33 | Native semantics: `+0` and `-0` are one member. | Run, port 5 | +| 34 | `add` stores the raw object, so one member. A `Set` constructed from both forms holds two, with a development warning. | Run, port 5 | +| 36 | Reads of other objects are tracked. A nested computed value that throws is still a dependency. | Run, port 9 | +| 38 | A cycle returns `NaN`. No error. | Run, port 9 | +| 39 | A computed value that writes re-runs on every read (1, 2, 3). No warning was printed. | Run, port 9 | +| 40 | The same. A computed result changed by its reader stays changed. | Run, port 10 | +| 42 | `constructor` is the class. | Run, port 1 | +| 43 | The same, and worse: a setter that writes two fields re-runs an effect twice and counts as a new key. | Run, port 8 | +| 45 | Reads follow the target after a redefinition. | Run, port 3 | +| 46 | The parent hands out the raw object from then on, without saying so. A proxy taken earlier throws the same `TypeError`. | Run, port 4 | +| 48 | The same as a plain object: the prototype is swapped. | Run, port 10 | +| 50 | The same. The descriptor's value is the raw object. | Run, port 10 | +| 51 | The same `DataCloneError`. `structuredClone(toRaw(state))` works, because the raw graph holds no proxy. | Run, port 10 | +| 62 | `reactive(fn)` returns `fn` and warns in development. | Run, port 1 | +| 63 | A typed array is not made reactive. Nor is a `Date`. | Run, port 10 | +| 71 | An element redefined to a primitive reads as the primitive. | Run, port 3 | + +No counterpart: findings 2, 4, 15, 21 to 25, 27, 28, 31, 35, 37, 41, 44, 47, +49, 52 to 61, 64 to 70, 72 and 73. They concern snapshots, the ownership +graph, grouped delivery, `persist`, `history` or code that Vue does not have. +Finding 1 above still proposes a fix for 31 and 41. + +## The eight API questions + +1. **Should synchronous notification be the default for `subscribe()`?** Vue + is synchronous at the bottom and grouped at the surface. `effect()` re-runs + before the writing statement returns (`endBatch`, `effect.ts:273`), and + `watch` in this package calls its job directly unless it is given a + scheduler (`watch.ts:294-296`). What application code uses goes through the + framework's scheduler, with a synchronous flush as an option; that part + lives in `runtime-core` and was not read. That is the arrangement we have: + the adapters subscribe synchronously and `subscribe()` is grouped by + default. Vue's position supports keeping it. +2. **Writes outside a store method: allowed, warned about, or grouped? Does + `batch()` belong?** Allowed, anywhere, with no warning. Vue has no notion + of an action. Only five array methods are grouped. `startBatch` and + `endBatch` exist, are marked internal and are not exported from the + package's `index.ts`. Vue can do without a public `batch()` because its + surface is grouped already. Our bindings are synchronous, so ours belongs. + Port 6 shows what a bare synchronous reader sees without one. +3. **Should snapshot getters stay enumerable own accessors?** No position on + snapshots: Vue makes no copies. What it shows is the other arrangement. A + getter stays on the prototype, so `Object.keys(reactive(instance))` lists + data only and `JSON.stringify` skips getters (port 14). With ours, + `Object.keys(store)` is `a,b` and `Object.keys(snapshot(store))` is + `a,b,entryCount`, and `JSON.stringify(snapshot(store))` runs every getter. + Finding 1 shows that the choice also decides what a getter may do with + `this`. +4. **Can arrow-function methods and `#private` fields be made to work?** Vue + has both limits and no remedy (port 8): a write inside an arrow method + wakes no one, and a getter that reads a `#private` field throws through the + proxy. A base class whose constructor returns the proxy works in both + libraries for arrow methods, and makes private fields readable on the live + object, because the derived class's fields are then installed on the proxy. + Port 8 and port 10 measured four limits with our store: + - The fields arrive through `defineProperty`, which our trap does not treat + as a write, so a snapshot holds the raw array until the field is first + read (finding 6). + - A write to a private field notifies no one. Private fields do not go + through a Proxy. Vue is the same. + - A getter that reads only private state is cached for good on the live + store: it read 1 before and after `bump()`. + - `snapshot(todo).secret` throws a `TypeError`, because the snapshot is a + new object without the private fields. + + So arrow methods can be made to work with a base class. Private fields + can be made readable on the live store, but not reactive, and not readable + on a snapshot. +5. **Should native `Map` and `Set` be reactive directly?** Vue's answer is + yes, and the mutable half costs one `get` trap and a dozen replaced methods + (finding 10). Vue has no answer for the frozen half, which is the part that + costs us. +6. **Opt-in or opt-out for nested class instances?** Opt-out. Vue proxies any + extensible object whose `Object.prototype.toString` tag is `Object`, + `Array`, `Map`, `Set`, `WeakMap` or `WeakSet` (`targetTypeMap`, + `reactive.ts:43`), which includes class instances and excludes `Date` and + typed arrays by their tag (port 10). The ways out are `markRaw`, + `shallowReactive` and making the object non-extensible (port 8). The cost + is loud: a class with `#private` fields throws when read through the proxy + (port 8). The cost of our opt-in is silent: in port 7 a nested class + instance changed its state and notified no one. Two things are particular + to us. A snapshot is a copy, so a class with private fields would fail on + the snapshot under opt-out. And `markRaw` works by writing a hidden + property onto the user's object (`reactive.ts:420-424`), which our rule + about internal state excludes; freezing is our way out today, and it does + not suit an object that must stay mutable, so opt-out would need a marker + kept in a `WeakSet`. +7. **Are the entry points, export names and adapter names consistent?** From + Vue's side only. `use…` is the name for a function that must run in + `setup()` or an effect scope and leaves its cleanup to the scope, which is + what `useClassyStore` does (`vue.ts:14-18`, `:33-36`), so the name fits. The + return type does not: see finding 11. No position on the other four. +8. **What development-only diagnostics would catch our silent failures?** Vue + compiles its warnings behind a `__DEV__` flag. The build for bundlers + leaves `process.env.NODE_ENV !== "production"` in place (34 times in + `reactivity.esm-bundler.js`) for the application's bundler to remove, and + `package.json` sends Node to `reactivity.cjs.prod.js` or + `reactivity.cjs.js` by the `production` and `development` conditions. The + production file has no warning call and is 51 KB against 55 KB. Run with + `NODE_ENV=production`, port 1 printed no warning. Its warnings, and what + the same idea would catch for us: + - A value that cannot be made reactive (`reactive.ts:269-278`). For us: a + native `Map` or `Set`, or a class instance without `PROXYABLE`, placed + in a store. Today that is silent. + - Both forms of one object in a collection (`collectionHandlers.ts:315`). + For us: stage 1 finding 34. + - A write to a read-only view (`baseHandlers.ts:230-248`). We throw + already, because snapshots are frozen. + - `onTrack` and `onTrigger` hooks that receive the target, the key and the + old and new value (`dep.ts:153-162`, `:309-323`). For us: a way to ask + which write caused a notification or a recompute. + - A repeat limit (finding 9). For us: stage 1 findings 18 and 19. + + Vue has no diagnostic for a write inside an arrow method or after an + `await`, and has the first of those failures itself (port 8). + +## What was verified by running, and what was only read + +**Run** (code and output below): every "Run" row of the table; the +differences stated in findings 1 to 11; the six cases under "Where we already +do better"; the timings in finding 7; the type check in finding 11; the two +sketches (ports 13 and 15) and the recursion in port 14; the absence of +warnings under `NODE_ENV=production`. + +**Read, not run:** how `refreshComputed` and `isDirty` decide (finding 8), +apart from the outcomes port 9 shows; the scheduler's limit of 100; that +`startBatch` and `endBatch` are not exported; the two "Read" rows of the +table. + +**Reasoning, not tested:** + +- The proposals in findings 6, 7 and 8 were not sketched. The expected gain in + finding 7 comes from Vue's numbers. +- The two sketches were run only against the scenarios in ports 13 to 15. The + repository's suite was not run against them, so they show that the idea + works, not that it is free of regressions. +- That a snapshot of a native `Map` needs its own class and a full copy + (finding 10). + +**Not done:** Vue 3.6 was not read. `watch.ts`, `ref.ts` and `effectScope.ts` +were not read beyond the lines cited. The timings ran on Bun only, not on +Node. + +## Ported tests + +Each script ran from a scratch folder with `@vue/reactivity@3.5.45` installed. +In the listings, `` stands for the absolute path of this checkout. +`[Vue warn]` lines are Vue's development warnings. Biome reformatted the +listings when this file was formatted; the code is otherwise what ran. + +### Helpers shared by the ports + +`helpers.ts`: + +```ts +export const out = (label: string, value: unknown) => + console.log( + `${label.padEnd(58)} ${typeof value === 'string' ? value : JSON.stringify(value)}`, + ); + +export const attempt = (run: () => unknown): unknown => { + try { + return run(); + } catch (error) { + return `throws ${(error as Error).constructor.name}: ${(error as Error).message.split('\n')[0]}`; + } +}; + +export const section = (title: string) => console.log(`\n# ${title}`); +``` + +### Port 1: searches on a list, a function in a list, a class as a property + +`01-array-identity.ts`: + +```ts +import {reactive, toRaw} from '@vue/reactivity'; +import {createClassyStore} from '/packages/classy-store/src/index.ts'; +import {attempt, out, section} from './helpers'; + +section('finding 7: identity-sensitive searches on a list of objects'); +{ + const raw = {id: 1}; + const vue = reactive({list: [raw]}); + out('vue list[0] === raw', vue.list[0] === raw); + out('vue list.includes(raw)', vue.list.includes(raw)); + out('vue list.indexOf(raw)', vue.list.indexOf(raw)); + out('vue list.lastIndexOf(raw)', vue.list.lastIndexOf(raw)); + out('vue list.includes(list[0])', vue.list.includes(vue.list[0])); + out( + 'vue list.findIndex(x => x === raw)', + vue.list.findIndex((x) => x === raw), + ); + const held = reactive([reactive(raw)]); + out('vue a list built around the proxy: includes(raw)', held.includes(raw)); + + const ours = createClassyStore({list: [raw]}); + out('ours list[0] === raw', ours.list[0] === raw); + out('ours list.includes(raw)', ours.list.includes(raw)); + out('ours list.indexOf(raw)', ours.list.indexOf(raw)); + out('ours list.lastIndexOf(raw)', ours.list.lastIndexOf(raw)); + out('ours list.includes(list[0])', ours.list.includes(ours.list[0])); + out( + 'ours list.findIndex(x => x === raw)', + ours.list.findIndex((x) => x === raw), + ); +} + +section('finding 5: a function held in an array, read twice'); +{ + const first = () => 1; + const second = () => 2; + const vue = reactive({callbacks: [first, second]}); + out( + 'vue callbacks[0] === callbacks[0]', + vue.callbacks[0] === vue.callbacks[0], + ); + out('vue callbacks[0] === first', vue.callbacks[0] === first); + out('vue callbacks.indexOf(first)', vue.callbacks.indexOf(first)); + vue.callbacks.splice(vue.callbacks.indexOf(first), 1); + out( + 'vue after splice(indexOf(first), 1): kept second', + vue.callbacks.length === 1 && vue.callbacks[0] === second, + ); + + const ours = createClassyStore({callbacks: [first, second]}); + out( + 'ours callbacks[0] === callbacks[0]', + ours.callbacks[0] === ours.callbacks[0], + ); + out('ours callbacks[0] === first', ours.callbacks[0] === first); + out('ours callbacks.indexOf(first)', ours.callbacks.indexOf(first)); + ours.callbacks.splice(ours.callbacks.indexOf(first), 1); + out( + 'ours after splice(indexOf(first), 1): kept second', + ours.callbacks.length === 1 && ours.callbacks[0]() === 2, + ); +} + +section('findings 6 and 42: a class held as a property, and `constructor`'); +{ + class Model { + static label = 'model'; + constructor(public name: string) {} + } + const vue = reactive({Model}); + out('vue state.Model === Model', vue.Model === Model); + out('vue state.Model.label', vue.Model.label); + out( + 'vue new state.Model("x") instanceof state.Model', + new vue.Model('x') instanceof vue.Model, + ); + + const ours = createClassyStore({Model}); + out('ours store.Model === Model', ours.Model === Model); + out('ours store.Model.label', String(ours.Model.label)); + out( + 'ours new store.Model("x") instanceof store.Model', + attempt(() => new ours.Model('x') instanceof ours.Model), + ); + + class Counter { + static kind = 'counter'; + count = 0; + inc() { + this.count++; + } + } + const vueCounter = reactive(new Counter()); + out( + 'vue counter.constructor === Counter', + vueCounter.constructor === Counter, + ); + out( + 'vue counter.inc === Counter.prototype.inc (unbound)', + vueCounter.inc === Counter.prototype.inc, + ); + const {inc: vueInc} = vueCounter; + out( + 'vue const {inc} = counter; inc()', + attempt(() => vueInc()), + ); + + const ourCounter = createClassyStore(new Counter()); + out( + 'ours counter.constructor === Counter', + ourCounter.constructor === Counter, + ); + out( + 'ours counter.constructor.kind', + String((ourCounter.constructor as typeof Counter).kind), + ); + const {inc: ourInc} = ourCounter; + out( + 'ours const {inc} = counter; inc(); counter.count', + attempt(() => (ourInc(), ourCounter.count)), + ); +} + +section('finding 62: a function given to the factory'); +{ + const fn = () => 1; + out( + 'vue reactive(fn) === fn', + (reactive as (value: unknown) => unknown)(fn) === fn, + ); + out( + 'vue toRaw(reactive(fn)) === fn', + toRaw((reactive as (value: unknown) => unknown)(fn)) === fn, + ); +} +``` + +Output: + +```text + +# finding 7: identity-sensitive searches on a list of objects +vue list[0] === raw false +vue list.includes(raw) true +vue list.indexOf(raw) 0 +vue list.lastIndexOf(raw) 0 +vue list.includes(list[0]) true +vue list.findIndex(x => x === raw) -1 +vue a list built around the proxy: includes(raw) false +ours list[0] === raw false +ours list.includes(raw) false +ours list.indexOf(raw) -1 +ours list.lastIndexOf(raw) -1 +ours list.includes(list[0]) true +ours list.findIndex(x => x === raw) -1 + +# finding 5: a function held in an array, read twice +vue callbacks[0] === callbacks[0] true +vue callbacks[0] === first true +vue callbacks.indexOf(first) 0 +vue after splice(indexOf(first), 1): kept second true +ours callbacks[0] === callbacks[0] false +ours callbacks[0] === first false +ours callbacks.indexOf(first) -1 +ours after splice(indexOf(first), 1): kept second false + +# findings 6 and 42: a class held as a property, and `constructor` +vue state.Model === Model true +vue state.Model.label model +vue new state.Model("x") instanceof state.Model true +ours store.Model === Model false +ours store.Model.label undefined +ours new store.Model("x") instanceof store.Model false +vue counter.constructor === Counter true +vue counter.inc === Counter.prototype.inc (unbound) true +vue const {inc} = counter; inc() throws TypeError: undefined is not an object (evaluating 'this.count') +ours counter.constructor === Counter false +ours counter.constructor.kind undefined +ours const {inc} = counter; inc(); counter.count 1 + +# finding 62: a function given to the factory +[Vue warn] value cannot be made reactive: () => 1 +vue reactive(fn) === fn true +[Vue warn] value cannot be made reactive: () => 1 +vue toRaw(reactive(fn)) === fn true +``` + +### Port 2: `Object.keys` and `in`, a delete of a missing key, a read of a missing key + +`02-keys-and-has.ts`: + +```ts +import {computed, effect, reactive} from '@vue/reactivity'; +import { + createClassyStore, + snapshot, + subscribe, +} from '/packages/classy-store/src/index.ts'; +import {out, section} from './helpers'; + +section( + 'finding 30: a derived value that reads Object.keys(state) and "b" in state', +); +{ + const state = reactive>({a: 1, b: 2}); + let keyRuns = 0; + let hasRuns = 0; + const keyCount = computed(() => (keyRuns++, Object.keys(state).length)); + const hasB = computed(() => (hasRuns++, 'b' in state)); + const read = () => + `keyCount=${keyCount.value} hasB=${hasB.value} keyRuns=${keyRuns} hasRuns=${hasRuns}`; + out('vue start', read()); + state.a = 10; + out('vue after state.a = 10 (a value, not a key)', read()); + delete state.b; + out('vue after delete state.b', read()); + state.c = 3; + out('vue after state.c = 3 (a new key)', read()); + state.b = 5; + out('vue after state.b = 5 (the key comes back)', read()); + + class Dict { + [key: string]: unknown; + a = 1; + b = 2; + get keyCount() { + return Object.keys(this).length; + } + get hasB() { + return 'b' in this; + } + } + const store = createClassyStore(new Dict()); + const readOurs = () => `keyCount=${store.keyCount} hasB=${store.hasB}`; + out('ours start, live', readOurs()); + out( + 'ours start, snapshot', + `keyCount=${snapshot(store).keyCount} hasB=${snapshot(store).hasB}`, + ); + delete store.b; + out('ours after delete store.b, live', readOurs()); + out( + 'ours after delete store.b, snapshot', + `keyCount=${snapshot(store).keyCount} hasB=${snapshot(store).hasB}`, + ); +} + +section( + 'finding 29: a delete that removes nothing, and a write of the same value', +); +{ + const state = reactive>({a: 1}); + let runs = 0; + effect(() => { + runs++; + Object.keys(state); + state.a; + state.missing; + }); + out('vue effect runs at start', runs); + delete state.missing; + out('vue after delete state.missing', runs); + state.a = 1; + out('vue after state.a = 1 (same value)', runs); + state.n = Number.NaN; + const afterNaN = runs; + state.n = Number.NaN; + out('vue a second state.n = NaN adds runs', runs - afterNaN); + const list = reactive([1, 2, 3]); + let listRuns = 0; + effect(() => { + listRuns++; + list.length; + list[0]; + }); + delete list[5]; + out('vue after delete list[5] (past the end)', listRuns); + + const store = createClassyStore>({a: 1}); + let calls = 0; + subscribe(store, () => calls++, {sync: true}); + const before = snapshot(store); + delete store.missing; + out('ours sync subscriber calls after delete store.missing', calls); + out('ours snapshot replaced by an equal one', snapshot(store) !== before); + store.a = 1; + out('ours sync subscriber calls after store.a = 1', calls); +} + +section( + 'finding 32: a derived value that reads a property which does not exist', +); +{ + const state = reactive<{maybe?: number}>({}); + let runs = 0; + const box = computed(() => (runs++, {value: state.maybe})); + out('vue box.value === box.value', box.value === box.value); + out('vue runs after two reads', runs); + state.maybe = 1; + out( + 'vue after state.maybe = 1: value, runs', + `${box.value.value}, ${runs}`, + ); + + class Holder { + maybe?: number; + runs = 0; + get box() { + return {value: (this as {maybe?: number}).maybe}; + } + } + const holder = new Holder(); + delete holder.maybe; + const store = createClassyStore(holder); + out('ours store.box === store.box', store.box === store.box); + out( + 'ours snapshot(store).box === snapshot(store).box', + snapshot(store).box === snapshot(store).box, + ); +} +``` + +Output: + +```text + +# finding 30: a derived value that reads Object.keys(state) and "b" in state +vue start keyCount=2 hasB=true keyRuns=1 hasRuns=1 +vue after state.a = 10 (a value, not a key) keyCount=2 hasB=true keyRuns=1 hasRuns=1 +vue after delete state.b keyCount=1 hasB=false keyRuns=2 hasRuns=2 +vue after state.c = 3 (a new key) keyCount=2 hasB=false keyRuns=3 hasRuns=2 +vue after state.b = 5 (the key comes back) keyCount=3 hasB=true keyRuns=4 hasRuns=3 +ours start, live keyCount=2 hasB=true +ours start, snapshot keyCount=0 hasB=false +ours after delete store.b, live keyCount=2 hasB=true +ours after delete store.b, snapshot keyCount=0 hasB=false + +# finding 29: a delete that removes nothing, and a write of the same value +vue effect runs at start 1 +vue after delete state.missing 1 +vue after state.a = 1 (same value) 1 +vue a second state.n = NaN adds runs 0 +vue after delete list[5] (past the end) 1 +ours sync subscriber calls after delete store.missing 1 +ours snapshot replaced by an equal one true +ours sync subscriber calls after store.a = 1 1 + +# finding 32: a derived value that reads a property which does not exist +vue box.value === box.value true +vue runs after two reads 1 +vue after state.maybe = 1: value, runs 1, 2 +ours store.box === store.box false +ours snapshot(store).box === snapshot(store).box true +``` + +### Port 3: `Object.defineProperty` through the proxy + +`03-define-property.ts`: + +```ts +import {effect, reactive} from '@vue/reactivity'; +import { + createClassyStore, + snapshot, + subscribe, +} from '/packages/classy-store/src/index.ts'; +import {attempt, out, section} from './helpers'; + +const data = {writable: true, enumerable: true, configurable: true}; + +section('finding 1: Object.defineProperty adds a key through the proxy'); +{ + const state = reactive>({a: 1}); + let runs = 0; + let seen = ''; + effect(() => { + runs++; + seen = `${Object.keys(state).join(',')} b=${state.b}`; + }); + Object.defineProperty(state, 'b', {value: 2, ...data}); + out('vue effect runs after defineProperty', runs); + out('vue what the effect last saw', seen); + out('vue live read state.b', state.b); + + const store = createClassyStore>({a: 1}); + let calls = 0; + subscribe(store, () => calls++, {sync: true}); + snapshot(store); + Object.defineProperty(store, 'b', {value: 2, ...data}); + out('ours sync subscriber calls after defineProperty', calls); + out('ours live read store.b', store.b); + out('ours snapshot(store).b', String(snapshot(store).b)); +} + +section('finding 45: redefining a property that holds an object'); +{ + const state = reactive<{child: {n: number} | number}>({child: {n: 1}}); + const other = {n: 2}; + (state.child as {n: number}).n; + Object.defineProperty(state, 'child', {value: other, ...data}); + out( + 'vue state.child.n after redefining to another object', + (state.child as {n: number}).n, + ); + Object.defineProperty(state, 'child', {value: 7, ...data}); + out('vue state.child after redefining to 7', state.child); + + const store = createClassyStore<{child: {n: number} | number}>({ + child: {n: 1}, + }); + (store.child as {n: number}).n; + Object.defineProperty(store, 'child', {value: other, ...data}); + out( + 'ours store.child.n after redefining to another object', + (store.child as {n: number}).n, + ); + Object.defineProperty(store, 'child', {value: 7, ...data}); + out('ours store.child after redefining to 7', store.child); +} + +section('findings 45 and 71: defineProperty on a list'); +{ + const list = reactive([{id: 1}, {id: 2}, {id: 3}]); + let runs = 0; + effect(() => { + runs++; + list.length; + list[2]; + }); + Object.defineProperty(list, 'length', {value: 1}); + out('vue list[2] after defining length = 1', String(list[2])); + out('vue effect runs', runs); + Object.defineProperty(list, 0, {value: 7, ...data}); + out('vue list[0] after redefining it to 7', list[0]); + + const store = createClassyStore<{rows: unknown[]}>({ + rows: [{id: 1}, {id: 2}, {id: 3}], + }); + store.rows[2]; + Object.defineProperty(store.rows, 'length', {value: 1}); + out( + 'ours rows[2] after defining length = 1', + attempt(() => JSON.stringify(store.rows[2])), + ); + Object.defineProperty(store.rows, 0, {value: 7, ...data}); + out( + 'ours rows[0] after redefining it to 7', + attempt(() => JSON.stringify(store.rows[0])), + ); + out( + 'ours snapshot(store).rows[0]', + attempt(() => JSON.stringify(snapshot(store).rows[0])), + ); +} +``` + +Output: + +```text + +# finding 1: Object.defineProperty adds a key through the proxy +vue effect runs after defineProperty 1 +vue what the effect last saw a b=undefined +vue live read state.b 2 +ours sync subscriber calls after defineProperty 0 +ours live read store.b 2 +ours snapshot(store).b undefined + +# finding 45: redefining a property that holds an object +vue state.child.n after redefining to another object 2 +vue state.child after redefining to 7 7 +ours store.child.n after redefining to another object 1 +ours store.child after redefining to 7 {"n":1} + +# findings 45 and 71: defineProperty on a list +vue list[2] after defining length = 1 undefined +vue effect runs 1 +vue list[0] after redefining it to 7 7 +ours rows[2] after defining length = 1 {"id":3} +ours rows[0] after redefining it to 7 {"id":1} +ours snapshot(store).rows[0] 7 +``` + +### Port 4: frozen, sealed and read-only + +`04-frozen.ts`: + +```ts +import {isReactive, reactive} from '@vue/reactivity'; +import {createClassyStore} from '/packages/classy-store/src/index.ts'; +import {attempt, out, section} from './helpers'; + +section('a frozen object given to a reactive parent'); +{ + const frozen = Object.freeze({nested: {n: 1}}); + const state = reactive({config: frozen}); + out('vue state.config === frozen', state.config === frozen); + out('vue isReactive(state.config.nested)', isReactive(state.config.nested)); + out( + 'vue reactive(Object.seal({a: 1})) is reactive', + isReactive(reactive(Object.seal({a: 1}))), + ); + out( + 'vue reactive(Object.preventExtensions({a: 1})) is reactive', + isReactive(reactive(Object.preventExtensions({a: 1}))), + ); + + const store = createClassyStore({ + config: frozen, + sealed: Object.seal({a: {n: 1}}), + }); + out('ours store.config === frozen', store.config === frozen); + out('ours store.config.nested.n', store.config.nested.n); + let calls = 0; + const {subscribe} = await import('/packages/classy-store/src/index.ts'); + subscribe(store, () => calls++, {sync: true}); + store.sealed.a.n = 2; + out('ours a write under a sealed object notifies', calls); +} + +section('finding 46: the raw object is frozen behind the proxy'); +{ + const raw = {config: {nested: {n: 1}}}; + const state = reactive(raw); + const before = state.config; + Object.freeze(raw.config); + out( + 'vue state.config.nested.n, read again from the parent', + attempt(() => state.config.nested.n), + ); + out('vue isReactive(state.config) now', isReactive(state.config)); + out( + 'vue nested.n through the proxy taken before', + attempt(() => before.nested.n), + ); + + const ourRaw = {config: {nested: {n: 1}}}; + const store = createClassyStore(ourRaw); + Object.freeze(ourRaw.config); + out( + 'ours store.config.nested.n', + attempt(() => store.config.nested.n), + ); +} + +section('Object.freeze through the proxy'); +{ + const state = reactive({config: {nested: {n: 1}}}); + const config = state.config; + Object.freeze(config); + out( + 'vue nested.n through the frozen proxy', + attempt(() => config.nested.n), + ); + out( + 'vue state.config.nested.n, read again from the parent', + attempt(() => state.config.nested.n), + ); + + const store = createClassyStore({config: {nested: {n: 1}}}); + const ourConfig = store.config; + Object.freeze(ourConfig); + out( + 'ours nested.n through the frozen proxy', + attempt(() => ourConfig.nested.n), + ); + out( + 'ours store.config.nested.n', + attempt(() => store.config.nested.n), + ); +} + +section('a read-only property that holds an object'); +{ + const make = () => { + const raw = {} as {child: {n: number}}; + Object.defineProperty(raw, 'child', {value: {n: 1}, enumerable: true}); + return raw; + }; + out( + 'vue reactive(raw).child.n', + attempt(() => reactive(make()).child.n), + ); + out( + 'ours createClassyStore(raw).child.n', + attempt(() => createClassyStore(make()).child.n), + ); +} +``` + +Output: + +```text + +# a frozen object given to a reactive parent +vue state.config === frozen true +vue isReactive(state.config.nested) false +vue reactive(Object.seal({a: 1})) is reactive false +vue reactive(Object.preventExtensions({a: 1})) is reactive false +ours store.config === frozen true +ours store.config.nested.n 1 +ours a write under a sealed object notifies 1 + +# finding 46: the raw object is frozen behind the proxy +vue state.config.nested.n, read again from the parent 1 +vue isReactive(state.config) now false +vue nested.n through the proxy taken before throws TypeError: Proxy handler's 'get' result of a non-configurable and non-writable property should be the same value as the target's property +ours store.config.nested.n throws TypeError: Proxy handler's 'get' result of a non-configurable and non-writable property should be the same value as the target's property + +# Object.freeze through the proxy +vue nested.n through the frozen proxy throws TypeError: Proxy handler's 'get' result of a non-configurable and non-writable property should be the same value as the target's property +vue state.config.nested.n, read again from the parent 1 +ours nested.n through the frozen proxy 1 +ours store.config.nested.n 1 + +# a read-only property that holds an object +vue reactive(raw).child.n throws TypeError: Proxy handler's 'get' result of a non-configurable and non-writable property should be the same value as the target's property +ours createClassyStore(raw).child.n 1 +``` + +### Port 5: native `Map` and `Set` + +`05-native-collections.ts`: + +```ts +import {effect, isReactive, reactive, readonly, toRaw} from '@vue/reactivity'; +import { + createClassyStore, + snapshot, +} from '/packages/classy-store/src/index.ts'; +import {reactiveSet} from '/packages/classy-store/src/collections/index.ts'; +import {attempt, out, section} from './helpers'; + +section( + 'finding 12: a native Set and Map with an object member, looked up by raw object and by proxy', +); +{ + const row = {id: 1}; + const state = reactive({ + list: [row], + set: new Set([row]), + map: new Map([[row, 'a']]), + }); + out('vue state.set instanceof Set', state.set instanceof Set); + out('vue set.has(row)', state.set.has(row)); + out('vue set.has(list[0])', state.set.has(state.list[0])); + out('vue map.get(row)', state.map.get(row)); + out('vue map.get(list[0])', state.map.get(state.list[0])); + out( + 'vue [...set][0] === list[0] (members come out reactive)', + [...state.set][0] === state.list[0], + ); + state.set.add(state.list[0]); + out('vue size after set.add(list[0])', state.set.size); + out('vue the raw set holds the raw row', [...toRaw(state.set)][0] === row); + let runs = 0; + effect(() => { + runs++; + state.set.has(row); + }); + state.set.delete(state.list[0]); + out('vue effect on set.has(row) re-ran after delete by proxy', runs === 2); + state.map.get(row); + state.map.set(state.list[0], 'b'); + out('vue map.size after map.set(list[0], "b")', state.map.size); + + const store = createClassyStore({ + list: [row], + set: new Set([row]), + tags: reactiveSet([row]), + }); + out('ours native set.has(row)', store.set.has(row)); + out('ours native set.has(list[0])', store.set.has(store.list[0])); + out('ours reactiveSet.has(row)', store.tags.has(row)); + out('ours reactiveSet.has(list[0])', store.tags.has(store.list[0])); + out( + 'ours reactiveSet.has(snapshot(store).list[0])', + store.tags.has(snapshot(store).list[0]), + ); + out( + 'ours store.tags instanceof Set', + (store.tags as unknown) instanceof Set, + ); +} + +section('finding 33: +0 and -0'); +{ + const zeros = reactive(new Set([0])); + zeros.add(-0); + out('vue new Set([0]) then add(-0): size', zeros.size); + const ours = createClassyStore({set: reactiveSet([0])}); + ours.set.add(-0); + out('ours reactiveSet([0]) then add(-0): size', ours.set.size); +} + +section('finding 34: one object given in two forms'); +{ + const row = {id: 1}; + const proxy = reactive(row); + const both = reactive(new Set([row, proxy])); + out('vue new Set([raw, proxy]): size', both.size); + both.delete(proxy); + out( + 'vue after delete(proxy): size, has(raw), has(proxy)', + `${both.size}, ${both.has(row)}, ${both.has(proxy)}`, + ); + const added = reactive(new Set()); + added.add(row); + added.add(proxy); + out('vue add(raw) then add(proxy): size', added.size); + + const ourRow = {id: 1}; + const holder = createClassyStore({row: ourRow}); + const ours = createClassyStore({ + set: reactiveSet([ourRow, holder.row]), + }); + out('ours reactiveSet([raw, proxy]): size', ours.set.size); + ours.set.delete(ourRow); + out( + 'ours after delete(raw): size, has(raw)', + `${ours.set.size}, ${ours.set.has(ourRow)}`, + ); +} + +section('a read-only view of a Map'); +{ + const view = readonly(reactive(new Map([['a', {n: 1}]]))); + out( + 'vue readonly map.set("b", ...) returns the map, size', + attempt( + () => ((view as Map).set('b', {n: 2}), view.size), + ), + ); + out('vue isReactive(view.get("a"))', isReactive(view.get('a'))); +} +``` + +Output: + +```text + +# finding 12: a native Set and Map with an object member, looked up by raw object and by proxy +vue state.set instanceof Set true +vue set.has(row) true +vue set.has(list[0]) true +vue map.get(row) a +vue map.get(list[0]) a +vue [...set][0] === list[0] (members come out reactive) true +vue size after set.add(list[0]) 1 +vue the raw set holds the raw row true +vue effect on set.has(row) re-ran after delete by proxy true +vue map.size after map.set(list[0], "b") 1 +ours native set.has(row) true +ours native set.has(list[0]) false +ours reactiveSet.has(row) true +ours reactiveSet.has(list[0]) true +ours reactiveSet.has(snapshot(store).list[0]) true +ours store.tags instanceof Set false + +# finding 33: +0 and -0 +vue new Set([0]) then add(-0): size 1 +ours reactiveSet([0]) then add(-0): size 2 + +# finding 34: one object given in two forms +vue new Set([raw, proxy]): size 2 +[Vue warn] Reactive Set contains both the raw and reactive versions of the same object, which can lead to inconsistencies. Avoid differentiating between the raw and reactive versions of an object and only use the reactive version if possible. +vue after delete(proxy): size, has(raw), has(proxy) 1, true, true +vue add(raw) then add(proxy): size 1 +ours reactiveSet([raw, proxy]): size 2 +ours after delete(raw): size, has(raw) 1, true + +# a read-only view of a Map +[Vue warn] Set operation on key "b" failed: target is readonly. Map(1) { + "a": { + n: 1, + }, +} +vue readonly map.set("b", ...) returns the map, size 1 +vue isReactive(view.get("a")) true +``` + +### Port 6: a write to `length`, and how many times a reader runs + +`06-array-length.ts`: + +```ts +import {effect, reactive} from '@vue/reactivity'; +import { + createClassyStore, + snapshot, + subscribe, +} from '/packages/classy-store/src/index.ts'; +import {out, section} from './helpers'; + +section('a write to an array length'); +{ + const list = reactive<({id: number} | undefined)[]>([ + {id: 1}, + {id: 2}, + {id: 3}, + ]); + const runs = {length: 0, first: 0, last: 0, iterate: 0}; + effect(() => (runs.length++, list.length)); + effect(() => (runs.first++, list[0])); + effect(() => (runs.last++, list[2])); + effect(() => { + runs.iterate++; + for (const row of list) row?.id; + }); + const read = () => JSON.stringify(runs); + out('vue effect runs at start', read()); + list.length = 1; + out('vue after list.length = 1', read()); + list.length = 1; + out('vue after list.length = 1 again', read()); + list[4] = {id: 5}; + out('vue after list[4] = row (past the end)', read()); + list.push({id: 6}, {id: 7}, {id: 8}); + out('vue after push of three rows', read()); + list.reverse(); + out('vue after reverse() of 8 slots', read()); + list.sort((a, b) => (a?.id ?? 0) - (b?.id ?? 0)); + out('vue after sort() of 8 slots', read()); + + const store = createClassyStore({rows: [{id: 1}, {id: 2}, {id: 3}]}); + let calls = 0; + subscribe(store, () => calls++, {sync: true}); + const last = store.rows[2]; + const before = snapshot(store).rows; + store.rows.length = 1; + out('ours sync calls after rows.length = 1', calls); + out( + 'ours snapshot rows length, first row shared', + `${snapshot(store).rows.length}, ${snapshot(store).rows[0] === before[0]}`, + ); + last.id = 99; + out('ours sync calls after a write to the removed row', calls); + store.rows.push({id: 6}, {id: 7}, {id: 8}); + out('ours sync calls after push of three rows', calls); + store.rows.reverse(); + out('ours sync calls after reverse()', calls); + store.rows.sort((a, b) => a.id - b.id); + out('ours sync calls after sort()', calls); +} +``` + +Output: + +```text + +# a write to an array length +vue effect runs at start {"length":1,"first":1,"last":1,"iterate":1} +vue after list.length = 1 {"length":2,"first":1,"last":2,"iterate":2} +vue after list.length = 1 again {"length":2,"first":1,"last":2,"iterate":2} +vue after list[4] = row (past the end) {"length":3,"first":1,"last":2,"iterate":3} +vue after push of three rows {"length":4,"first":1,"last":2,"iterate":4} +vue after reverse() of 8 slots {"length":4,"first":2,"last":3,"iterate":12} +vue after sort() of 8 slots {"length":4,"first":3,"last":3,"iterate":17} +ours sync calls after rows.length = 1 1 +ours snapshot rows length, first row shared 1, true +ours sync calls after a write to the removed row 1 +ours sync calls after push of three rows 2 +ours sync calls after reverse() 3 +ours sync calls after sort() 4 +``` + +### Port 7: self-reference, and what the raw object holds + +`07-self-reference-and-raw.ts`: + +```ts +import {computed, effect, isReactive, reactive, toRaw} from '@vue/reactivity'; +import { + createClassyStore, + snapshot, + subscribe, +} from '/packages/classy-store/src/index.ts'; +import {attempt, out, section} from './helpers'; + +section('finding 8 and 13: an object that refers to itself'); +{ + const state = reactive<{n: number; other: number; self?: unknown}>({ + n: 1, + other: 0, + }); + state.self = state; + out('vue state.self === state', state.self === state); + out( + 'vue the raw object holds itself raw', + toRaw(state).self === toRaw(state), + ); + let runs = 0; + const double = computed(() => (runs++, state.n * 2)); + double.value; + state.other = 1; + double.value; + out('vue computed runs after a write to a field it never read', runs); + + const store = createClassyStore<{n: number; self?: unknown}>({n: 1}); + store.self = store; + out('ours store.self === store', store.self === store); + out( + 'ours snapshot(store)', + attempt(() => typeof snapshot(store)), + ); +} + +section( + 'finding 10: what the raw object holds after an assignment or a reverse', +); +{ + const from = reactive({row: {id: 1}}); + const to = reactive<{row?: {id: number}}>({}); + to.row = from.row; + out( + 'vue raw target holds a proxy after to.row = from.row', + isReactive(toRaw(to).row), + ); + const list = reactive([{id: 1}, {id: 2}]); + list.reverse(); + out( + 'vue raw list holds a proxy after reverse()', + toRaw(list).some(isReactive), + ); + + const rawFrom = {row: {id: 1}}; + const rawTo: {row?: {id: number}} = {}; + const ourFrom = createClassyStore(rawFrom); + const ourTo = createClassyStore(rawTo); + ourTo.row = ourFrom.row; + out( + 'ours raw target holds the proxy after to.row = from.row', + rawTo.row === ourFrom.row && rawTo.row !== rawFrom.row, + ); + const rawList = [{id: 1}, {id: 2}]; + const first = rawList[0]; + const ourList = createClassyStore({list: rawList}); + ourList.list.reverse(); + out( + 'ours raw list holds a proxy after reverse()', + rawList[1] !== first && rawList[1] === ourList.list[1], + ); +} + +section( + 'finding 9: a class instance that is already reactive, placed in another parent by its raw object', +); +{ + class Inner { + n = 0; + inc() { + this.n++; + } + } + const raw = new Inner(); + const inner = reactive(raw); + const outer = reactive({inner: raw}); + out('vue outer.inner === inner', outer.inner === inner); + let runs = 0; + effect(() => (runs++, outer.inner.n)); + outer.inner.inc(); + inner.inc(); + out('vue effect runs after two inc() calls', runs); + + const ourRaw = new Inner(); + const ourInner = createClassyStore(ourRaw); + const ourOuter = createClassyStore({inner: ourRaw}); + out('ours outer.inner === inner', (ourOuter.inner as unknown) === ourInner); + let outerCalls = 0; + let innerCalls = 0; + subscribe(ourOuter, () => outerCalls++, {sync: true}); + subscribe(ourInner, () => innerCalls++, {sync: true}); + ourOuter.inner.inc(); + out( + 'ours calls after outer.inner.inc(): outer, inner', + `${outerCalls}, ${innerCalls}`, + ); +} + +section('finding 11: a write through the raw object'); +{ + const raw = {child: {n: 0}}; + const state = reactive(raw); + let runs = 0; + effect(() => (runs++, state.child.n)); + raw.child.n = 5; + out('vue live read, effect runs', `${state.child.n}, ${runs}`); +} +``` + +Output: + +```text + +# finding 8 and 13: an object that refers to itself +vue state.self === state true +vue the raw object holds itself raw true +vue computed runs after a write to a field it never read 1 +ours store.self === store true +ours snapshot(store) throws Error: @codebelt/classy-store: circular reference detected in snapshot + +# finding 10: what the raw object holds after an assignment or a reverse +vue raw target holds a proxy after to.row = from.row false +vue raw list holds a proxy after reverse() false +ours raw target holds the proxy after to.row = from.row true +ours raw list holds a proxy after reverse() true + +# finding 9: a class instance that is already reactive, placed in another parent by its raw object +vue outer.inner === inner true +vue effect runs after two inc() calls 3 +ours outer.inner === inner false +ours calls after outer.inner.inc(): outer, inner 0, 0 + +# finding 11: a write through the raw object +vue live read, effect runs 5, 1 +``` + +### Port 8: class instances, arrow methods, `#private` fields, a base class, a setter + +`08-class-instances.ts`: + +```ts +import { + effect, + isReactive, + markRaw, + reactive, + shallowReactive, +} from '@vue/reactivity'; +import { + createClassyStore, + snapshot, + subscribe, +} from '/packages/classy-store/src/index.ts'; +import {attempt, out, section} from './helpers'; + +section( + 'a class instance is proxied by default; an arrow method and a #private field', +); +{ + class Counter { + count = 0; + #secret = 1; + inc() { + this.count++; + } + arrow = () => { + this.count++; + }; + get secret() { + return this.#secret; + } + } + const counter = reactive(new Counter()); + let runs = 0; + effect(() => (runs++, counter.count)); + counter.inc(); + out('vue effect runs after inc()', runs); + counter.arrow(); + out( + 'vue effect runs after arrow(), live count', + `${runs}, ${counter.count}`, + ); + out( + 'vue counter.secret', + attempt(() => counter.secret), + ); + const nested = reactive({inner: new Counter()}); + out('vue a nested class instance is reactive', isReactive(nested.inner)); + out( + 'vue markRaw(instance) nested is reactive', + isReactive(reactive({inner: markRaw(new Counter())}).inner), + ); + out( + 'vue shallowReactive: nested is reactive', + isReactive(shallowReactive({inner: new Counter()}).inner), + ); + + const store = createClassyStore(new Counter()); + let calls = 0; + subscribe(store, () => calls++, {sync: true}); + store.arrow(); + out('ours sync calls after arrow(), live count', `${calls}, ${store.count}`); + out( + 'ours store.secret', + attempt(() => store.secret), + ); + out( + 'ours snapshot(store).secret', + attempt(() => snapshot(store).secret), + ); +} + +section('a base class whose constructor returns the proxy'); +{ + class VueBase { + constructor() { + // biome-ignore lint/correctness/noConstructorReturn: the point of the test + return reactive(this); + } + } + class Derived extends VueBase { + count = 0; + items = [{id: 1}]; + #secret = 1; + arrow = () => { + this.count++; + }; + bump() { + this.#secret++; + } + get secret() { + return this.#secret; + } + } + const derived = new Derived(); + out('vue new Derived() is reactive', isReactive(derived)); + let runs = 0; + let secretRuns = 0; + effect(() => (runs++, derived.count)); + effect(() => (secretRuns++, derived.secret)); + derived.arrow(); + out('vue effect runs after arrow()', runs); + derived.bump(); + out( + 'vue secret after bump(), runs of the effect that read it', + `${attempt(() => derived.secret)}, ${secretRuns}`, + ); + + class OurBase { + constructor() { + // biome-ignore lint/correctness/noConstructorReturn: the point of the test + return createClassyStore(this); + } + } + class Todo extends OurBase { + count = 0; + items = [{id: 1}]; + #secret = 1; + arrow = () => { + this.count++; + }; + bump() { + this.#secret++; + } + get secret() { + return this.#secret; + } + get double() { + return this.count * 2; + } + } + const todo = new Todo(); + let calls = 0; + subscribe(todo, () => calls++, {sync: true}); + out( + 'ours snapshot before any write: count, items frozen', + attempt( + () => `${snapshot(todo).count}, ${Object.isFrozen(snapshot(todo).items)}`, + ), + ); + todo.arrow(); + out( + 'ours sync calls after arrow(), live count, double', + `${calls}, ${todo.count}, ${todo.double}`, + ); + out( + 'ours snapshot after: count, double, items frozen', + attempt( + () => + `${snapshot(todo).count}, ${snapshot(todo).double}, ${Object.isFrozen(snapshot(todo).items)}`, + ), + ); + todo.bump(); + out( + 'ours live secret after bump(), sync calls', + `${attempt(() => todo.secret)}, ${calls}`, + ); + out( + 'ours snapshot(todo).secret', + attempt(() => snapshot(todo).secret), + ); + todo.items.push({id: 2}); + out( + 'ours sync calls after items.push, snapshot items length', + `${calls}, ${snapshot(todo).items.length}`, + ); +} + +section('finding 43: a setter that writes two fields'); +{ + class Person { + first = 'a'; + last = 'b'; + set full(value: string) { + [this.first, this.last] = value.split(' '); + } + } + const person = reactive(new Person()); + let runs = 0; + let keyRuns = 0; + effect(() => (runs++, person.first + person.last)); + effect(() => (keyRuns++, Object.keys(person))); + person.full = 'x y'; + out('vue runs of the effect that reads both fields', runs); + out('vue runs of an effect that reads only Object.keys', keyRuns); + + const store = createClassyStore(new Person()); + let calls = 0; + subscribe(store, () => calls++, {sync: true}); + store.full = 'x y'; + out('ours sync calls after the setter', calls); +} +``` + +Output: + +```text + +# a class instance is proxied by default; an arrow method and a #private field +vue effect runs after inc() 2 +vue effect runs after arrow(), live count 2, 2 +vue counter.secret throws TypeError: Cannot access invalid private field (evaluating 'this.#secret') +vue a nested class instance is reactive true +vue markRaw(instance) nested is reactive false +vue shallowReactive: nested is reactive false +ours sync calls after arrow(), live count 0, 1 +ours store.secret throws TypeError: Cannot access invalid private field (evaluating 'this.#secret') +ours snapshot(store).secret throws TypeError: Cannot access invalid private field (evaluating 'this.#secret') + +# a base class whose constructor returns the proxy +vue new Derived() is reactive true +vue effect runs after arrow() 2 +vue secret after bump(), runs of the effect that read it 2, 1 +ours snapshot before any write: count, items frozen 0, false +ours sync calls after arrow(), live count, double 1, 1, 2 +ours snapshot after: count, double, items frozen 1, 2, false +ours live secret after bump(), sync calls 2, 1 +ours snapshot(todo).secret throws TypeError: Cannot access invalid private field (evaluating 'this.#secret') +ours sync calls after items.push, snapshot items length 2, 2 + +# finding 43: a setter that writes two fields +vue runs of the effect that reads both fields 3 +vue runs of an effect that reads only Object.keys 2 +ours sync calls after the setter 2 +``` + +### Port 9: what a derived value records, cycles, and delivery + +`09-computed-and-loops.ts`: + +```ts +import {computed, effect, reactive, stop} from '@vue/reactivity'; +import { + createClassyStore, + snapshot, +} from '/packages/classy-store/src/index.ts'; +import {attempt, out, section} from './helpers'; + +section('finding 36: a derived value that reads another object'); +{ + const a = reactive({n: 1}); + const b = reactive({n: 10}); + const sum = computed(() => a.n + b.n); + sum.value; + b.n = 20; + out('vue sum after the other object changed', sum.value); + + const other = createClassyStore({n: 10}); + class Sum { + n = 1; + get total() { + return this.n + other.n; + } + } + const store = createClassyStore(new Sum()); + store.total; + other.n = 20; + out('ours live total after the other store changed', store.total); + out('ours snapshot total', snapshot(store).total); +} + +section("finding 36: a derived value that catches another one's error"); +{ + const state = reactive({fail: true}); + const strict = computed(() => { + if (state.fail) throw new Error('no'); + return 'ok'; + }); + const safe = computed(() => { + try { + return strict.value; + } catch { + return 'fallback'; + } + }); + out('vue safe while strict throws', safe.value); + state.fail = false; + out('vue safe after strict stops throwing', safe.value); + + class Guarded { + fail = true; + get strict() { + if (this.fail) throw new Error('no'); + return 'ok'; + } + get safe() { + try { + return this.strict; + } catch { + return 'fallback'; + } + } + } + const store = createClassyStore(new Guarded()); + out('ours safe while strict throws', store.safe); + store.fail = false; + out('ours live safe after strict stops throwing', store.safe); +} + +section('finding 37: a chain of three, then a write to an unrelated field'); +{ + const state = reactive({x: 1, unrelated: 0}); + const runs = {a: 0, b: 0, c: 0}; + const a = computed(() => (runs.a++, state.x)); + const b = computed(() => (runs.b++, a.value + 1)); + const c = computed(() => (runs.c++, b.value + 1)); + c.value; + state.unrelated = 1; + c.value; + out('vue runs after the unrelated write', JSON.stringify(runs)); + const positive = computed(() => (runs.a++, state.x > 0)); + const label = computed(() => (runs.b++, positive.value ? 'yes' : 'no')); + runs.a = 0; + runs.b = 0; + label.value; + state.x = 5; + label.value; + out( + 'vue x: 1 to 5 under "x > 0": runs of the test, runs of its reader', + `${runs.a}, ${runs.b}`, + ); +} + +section('finding 38: a cycle between two derived values'); +{ + const x: {value: number} = computed(() => y.value + 1); + const y: {value: number} = computed(() => x.value + 1); + out( + 'vue x.value', + attempt(() => String(x.value)), + ); + + class Cycle { + get x(): number { + return this.y + 1; + } + get y(): number { + return this.x + 1; + } + } + const store = createClassyStore(new Cycle()); + out( + 'ours live store.x', + attempt(() => store.x), + ); + out( + 'ours snapshot(store).x', + attempt(() => snapshot(store).x), + ); +} + +section('finding 39: a derived value that writes'); +{ + const state = reactive({n: 0}); + let runs = 0; + const writer = computed(() => (runs++, state.n++, state.n)); + out('vue three reads', `${writer.value}, ${writer.value}, ${writer.value}`); + out('vue runs', runs); +} + +section('finding 18: an effect that writes what it reads'); +{ + const state = reactive({n: 0}); + let runs = 0; + effect(() => { + runs++; + if (state.n < 5) state.n++; + }); + out('vue runs at start, n', `${runs}, ${state.n}`); + state.n = 0; + out('vue runs after state.n = 0, n', `${runs}, ${state.n}`); +} + +section('finding 20: an effect stopped while another one is being delivered'); +{ + const state = reactive({n: 0}); + let secondRuns = 0; + // Effects are delivered in the order they subscribed. + const first = effect(() => { + state.n; + if (state.n === 1) stop(second); + }); + const second = effect(() => (secondRuns++, state.n)); + state.n = 1; + out('vue runs of the stopped effect (1 is the first run)', secondRuns); + void first; +} +``` + +Output: + +```text + +# finding 36: a derived value that reads another object +vue sum after the other object changed 21 +ours live total after the other store changed 11 +ours snapshot total 21 + +# finding 36: a derived value that catches another one's error +vue safe while strict throws fallback +vue safe after strict stops throwing ok +ours safe while strict throws fallback +ours live safe after strict stops throwing fallback + +# finding 37: a chain of three, then a write to an unrelated field +vue runs after the unrelated write {"a":1,"b":1,"c":1} +vue x: 1 to 5 under "x > 0": runs of the test, runs of its reader 2, 1 + +# finding 38: a cycle between two derived values +vue x.value NaN +ours live store.x throws Error: @codebelt/classy-store: circular computed getter dependency: x → y → x +ours snapshot(store).x throws RangeError: Maximum call stack size exceeded. + +# finding 39: a derived value that writes +vue three reads 1, 2, 3 +vue runs 3 + +# finding 18: an effect that writes what it reads +vue runs at start, n 1, 1 +vue runs after state.n = 0, n 2, 1 + +# finding 20: an effect stopped while another one is being delivered +vue runs of the stopped effect (1 is the first run) 1 +``` + +### Port 10: other edges + +`10-edges.ts`: + +```ts +import {computed, effect, isReactive, reactive, toRaw} from '@vue/reactivity'; +import { + createClassyStore, + snapshot, + subscribe, +} from '/packages/classy-store/src/index.ts'; +import {attempt, out, section} from './helpers'; + +section( + 'finding 26: a dependency follows the property, a subscription follows the object', +); +{ + const state = reactive({user: {name: 'a'}}); + let runs = 0; + effect(() => (runs++, state.user.name)); + state.user = {name: 'b'}; + state.user.name = 'c'; + out( + 'vue effect runs after replacing the user, then renaming the new one', + runs, + ); + + const store = createClassyStore({user: {name: 'a'}}); + let calls = 0; + subscribe(store.user, () => calls++, {sync: true}); + store.user = {name: 'b'}; + store.user.name = 'c'; + out('ours calls of subscribe(store.user) after the same two writes', calls); +} + +section('findings 50, 51, 48, 63, 40: other edges'); +{ + const state = reactive({child: {n: 1}}); + out( + 'vue getOwnPropertyDescriptor(state, "child").value is reactive', + isReactive(Object.getOwnPropertyDescriptor(state, 'child')?.value), + ); + out( + 'vue structuredClone(state)', + attempt(() => typeof structuredClone(state)), + ); + out( + 'vue structuredClone(toRaw(state))', + attempt(() => JSON.stringify(structuredClone(toRaw(state)))), + ); + const target = reactive>({}); + Object.assign(target, JSON.parse('{"__proto__": {"polluted": true}}')); + out( + 'vue Object.assign(state, {"__proto__": ...}) swaps the prototype', + target.polluted === true, + ); + out( + 'vue reactive(new Uint8Array(2)) is reactive', + isReactive(reactive(new Uint8Array(2))), + ); + out( + 'vue reactive(new Date()) is reactive', + isReactive(reactive(new Date())), + ); + const made = computed(() => ({a: 1})); + made.value.a = 2; + out( + 'vue a computed result changed by the reader stays changed', + made.value.a, + ); +} + +section( + 'a getter that reads only a #private field, on a store made in a base constructor', +); +{ + class Base { + constructor() { + // biome-ignore lint/correctness/noConstructorReturn: the point of the test + return createClassyStore(this); + } + } + class Vault extends Base { + #secret = 1; + bump() { + this.#secret++; + } + get secret() { + return this.#secret; + } + } + const vault = new Vault(); + const before = vault.secret; + vault.bump(); + out('ours secret before bump(), after bump()', `${before}, ${vault.secret}`); +} + +section('telling a class from a method: the "prototype" property'); +{ + class Model {} + function legacy() {} + const describe = (fn: unknown) => { + const descriptor = Object.getOwnPropertyDescriptor(fn, 'prototype'); + return descriptor + ? `prototype writable=${descriptor.writable}` + : 'no prototype'; + }; + out('class Model {}', describe(Model)); + out('function legacy() {}', describe(legacy)); + out( + 'arrow function', + describe(() => {}), + ); + out('shorthand method', describe({method() {}}.method)); + out('Date', describe(Date)); +} +``` + +Output: + +```text + +# finding 26: a dependency follows the property, a subscription follows the object +vue effect runs after replacing the user, then renaming the new one 3 +ours calls of subscribe(store.user) after the same two writes 0 + +# findings 50, 51, 48, 63, 40: other edges +vue getOwnPropertyDescriptor(state, "child").value is reactive false +vue structuredClone(state) throws DOMException: The object can not be cloned. +vue structuredClone(toRaw(state)) {"child":{"n":1}} +vue Object.assign(state, {"__proto__": ...}) swaps the prototype true +vue reactive(new Uint8Array(2)) is reactive false +vue reactive(new Date()) is reactive false +vue a computed result changed by the reader stays changed 2 + +# a getter that reads only a #private field, on a store made in a base constructor +ours secret before bump(), after bump() 1, 1 + +# telling a class from a method: the "prototype" property +class Model {} prototype writable=false +function legacy() {} prototype writable=true +arrow function no prototype +shorthand method no prototype +Date prototype writable=false +``` + +### Port 11: timings (indicative) + +`11-timings.ts`: + +```ts +import {computed, reactive} from '@vue/reactivity'; +import {createClassyStore} from '/packages/classy-store/src/index.ts'; + +// Indicative only: one machine, Bun (JavaScriptCore), best of seven rounds. +const best = ( + label: string, + iterations: number, + per: number, + run: () => void, +) => { + let fastest = Number.POSITIVE_INFINITY; + for (let round = 0; round < 7; round++) { + const start = performance.now(); + for (let index = 0; index < iterations; index++) run(); + fastest = Math.min(fastest, performance.now() - start); + } + console.log( + `${label.padEnd(62)} ${((fastest * 1e6) / iterations / per).toFixed(1)} ns`, + ); +}; + +let sink = 0; + +{ + const raw = {count: 1}; + const vue = reactive({count: 1}); + const ours = createClassyStore({count: 1}); + best('read a number field, raw object', 5e6, 1, () => (sink += raw.count)); + best('read a number field, vue reactive', 5e6, 1, () => (sink += vue.count)); + best('read a number field, our store', 5e6, 1, () => (sink += ours.count)); +} + +{ + const rows = (n: number) => Array.from({length: n}, (_, value) => ({value})); + const vue = reactive({rows: rows(1000)}); + const vueReduce = computed(() => + vue.rows.reduce((sum, row) => sum + row.value, 0), + ); + const vueLoop = computed(() => { + const list = vue.rows; + let sum = 0; + for (let index = 0; index < list.length; index++) sum += list[index].value; + return sum; + }); + class Table { + rows = rows(1000); + get viaReduce() { + return this.rows.reduce((sum, row) => sum + row.value, 0); + } + get viaLoop() { + const list = this.rows; + let sum = 0; + for (let index = 0; index < list.length; index++) + sum += list[index].value; + return sum; + } + } + const ours = createClassyStore(new Table()); + let tick = 0; + best( + 'sum 1,000 rows after one changed, per row: vue reduce', + 2000, + 1000, + () => { + vue.rows[tick++ % 1000].value++; + sink += vueReduce.value; + }, + ); + best( + 'sum 1,000 rows after one changed, per row: vue index loop', + 2000, + 1000, + () => { + vue.rows[tick++ % 1000].value++; + sink += vueLoop.value; + }, + ); + best( + 'sum 1,000 rows after one changed, per row: ours reduce', + 2000, + 1000, + () => { + ours.rows[tick++ % 1000].value++; + sink += ours.viaReduce; + }, + ); + best( + 'sum 1,000 rows after one changed, per row: ours index loop', + 2000, + 1000, + () => { + ours.rows[tick++ % 1000].value++; + sink += ours.viaLoop; + }, + ); + const plain = rows(1000); + best('sum 1,000 rows, per row: plain array reduce', 2000, 1000, () => { + sink += plain.reduce((sum, row) => sum + row.value, 0); + }); +} + +{ + const vue = reactive({list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]}); + const ours = createClassyStore({list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]}); + const vueList = vue.list; + const ourList = ours.list; + best( + 'list.includes(10) on ten numbers: vue', + 2e6, + 1, + () => (sink += vueList.includes(10) ? 1 : 0), + ); + best( + 'list.includes(10) on ten numbers: ours', + 2e6, + 1, + () => (sink += ourList.includes(10) ? 1 : 0), + ); +} +console.log(sink > 0 ? 'done' : ''); +``` + +Output: + +```text +read a number field, raw object 1.7 ns +read a number field, vue reactive 15.9 ns +read a number field, our store 31.3 ns +sum 1,000 rows after one changed, per row: vue reduce 75.9 ns +sum 1,000 rows after one changed, per row: vue index loop 220.7 ns +sum 1,000 rows after one changed, per row: ours reduce 126.2 ns +sum 1,000 rows after one changed, per row: ours index loop 135.2 ns +sum 1,000 rows, per row: plain array reduce 2.1 ns +list.includes(10) on ten numbers: vue 56.9 ns +list.includes(10) on ten numbers: ours 920.8 ns +done +``` + +### Port 12: `DeepReadonly` on a tuple and a `Map` (type check) + +`12-types.ts`: + +```ts +import type {DeepReadonly} from '@vue/reactivity'; + +type Equal = + (() => T extends A ? 1 : 2) extends () => T extends B ? 1 : 2 + ? true + : false; + +// Finding 14: a tuple stays a tuple. +export const tuple: Equal< + DeepReadonly<[string, number]>, + readonly [string, number] +> = true; +// Finding 16: a read-only view of a Map or Set has no mutators in its type. +export const map: Equal< + DeepReadonly>, + ReadonlyMap +> = true; +export const set: Equal>, ReadonlySet> = true; + +declare const view: DeepReadonly<{ + todos: Map; + pair: [string, number]; +}>; +// @ts-expect-error no `set` on a read-only map +view.todos.set('a', {done: true}); +// @ts-expect-error a tuple has no third element +view.pair[2]; +// @ts-expect-error read-only element +view.pair[0] = 'x'; +``` + +Output: + +```text +tsc exit code: 0 +``` + +### Sketch A: `has` and `ownKeys` traps, applied to a throwaway copy of `src/` + +`patch-copy.py`: + +```python +import sys +from pathlib import Path + +root = Path(sys.argv[1]) + +def patch(path, pairs): + text = path.read_text() + for old, new in pairs: + if text.count(old) != 1: + raise SystemExit(f"{path.name}: expected one match for {old[:50]!r}, found {text.count(old)}") + text = text.replace(old, new) + path.write_text(text) + +patch(root / "core/ownership.ts", [ + (" version = 0;\n", " version = 0;\n keysVersion = 0;\n"), +]) + +patch(root / "core/core.ts", [ + # validate the two new kinds of dependency + (" } else if (dep.kind === 'computed') {", + " } else if ((dep as any).kind === 'has') {\n" + " if (Reflect.has((dep as any).target, (dep as any).prop) !== (dep as any).present) return false;\n" + " } else if ((dep as any).kind === 'keys') {\n" + " if ((dep as any).internal.keysVersion !== (dep as any).keysVersion) return false;\n" + " } else if (dep.kind === 'computed') {"), + # count key additions + (" const written = Reflect.set(_target, prop, value);\n", + " const hadKey = Object.hasOwn(_target, prop);\n" + " const written = Reflect.set(_target, prop, value);\n" + " if (written && !hadKey) internal.keysVersion++;\n"), + # a delete of a missing key is not a write; count key removals + (" const deleted = Reflect.deleteProperty(_target, prop);\n if (deleted) {\n", + " const hadKey = Object.hasOwn(_target, prop);\n" + " const deleted = Reflect.deleteProperty(_target, prop);\n" + " if (deleted && hadKey) {\n internal.keysVersion++;\n"), + # the two traps + (" deleteProperty(_target, prop) {\n", + " has(_target, prop) {\n" + " const present = Reflect.has(_target, prop);\n" + " const tracker = activeTracker();\n" + " if (tracker && tracker.internal === internal)\n" + " (tracker.deps as any[]).push({kind: 'has', target: _target, prop, present});\n" + " return present;\n" + " },\n\n" + " ownKeys(_target) {\n" + " const tracker = activeTracker();\n" + " if (tracker && tracker.internal === internal)\n" + " (tracker.deps as any[]).push({kind: 'keys', internal, keysVersion: internal.keysVersion});\n" + " return Reflect.ownKeys(_target);\n" + " },\n\n" + " deleteProperty(_target, prop) {\n"), +]) + +patch(root / "snapshot/snapshot.ts", [ + ("type GetterDep = {prop: string | symbol; value: unknown};", + "type GetterDep = {kind?: 'has' | 'keys'; prop: string | symbol; value: unknown};"), + (" return value;\n },\n };\n\n const tracked = new Proxy({}, handler);", + " return value;\n },\n" + " has(_target, prop) {\n" + " const value = Reflect.has(snap, prop);\n" + " deps.push({kind: 'has', prop, value});\n" + " return value;\n" + " },\n" + " ownKeys() {\n" + " const value = Reflect.ownKeys(snap);\n" + " deps.push({kind: 'keys', prop: '', value});\n" + " return value;\n" + " },\n" + " };\n\n" + " // The frozen snapshot is the target, so untrapped operations answer for it.\n" + " const tracked = new Proxy(snap, handler);"), + (" for (const dep of deps) {\n const currentValue", + " for (const dep of deps) {\n" + " if (dep.kind === 'has') {\n" + " if (Reflect.has(currentSnap, dep.prop) !== dep.value) return false;\n" + " continue;\n" + " }\n" + " if (dep.kind === 'keys') {\n" + " const before = dep.value as (string | symbol)[];\n" + " const now = Reflect.ownKeys(currentSnap);\n" + " if (now.length !== before.length || now.some((key, index) => key !== before[index])) return false;\n" + " continue;\n" + " }\n" + " const currentValue"), +]) +print("patched") +``` + +### Port 13: findings 29, 30, 31 and 41, before and after sketch A + +`13-patched-copy.ts`: + +```ts +// Runs against a throwaway copy of our source with `has` and `ownKeys` traps added. +import {out, section} from './helpers'; + +const variant = process.argv[2]; +const {createClassyStore, snapshot, subscribe} = await import( + variant === 'patched' + ? '../ours-copy/src/index.ts' + : '/packages/classy-store/src/index.ts' +); + +section(`${variant}: findings 29, 30, 31 and 41`); +class Dict { + [key: string]: unknown; + a = 1; + b = 2; + get keyCount() { + return Object.keys(this).length; + } + get hasB() { + return 'b' in this; + } + get isDict() { + return this instanceof Dict; + } +} +const store = createClassyStore(new Dict()); +const read = (from: Dict) => + `keyCount=${from.keyCount} hasB=${from.hasB} isDict=${from.isDict}`; +out('start, live', read(store)); +out('start, snapshot', read(snapshot(store))); +store.a = 10; +out('after store.a = 10, live', read(store)); +out('after store.a = 10, snapshot', read(snapshot(store))); +delete store.b; +out('after delete store.b, live', read(store)); +out('after delete store.b, snapshot', read(snapshot(store))); +store.c = 3; +store.b = 5; +out('after adding c and b, live', read(store)); +out('after adding c and b, snapshot', read(snapshot(store))); +let calls = 0; +subscribe(store, () => calls++, {sync: true}); +delete store.missing; +out('sync calls after delete store.missing', calls); +``` + +Output: + +```text + +# current: findings 29, 30, 31 and 41 +start, live keyCount=2 hasB=true isDict=true +start, snapshot keyCount=0 hasB=false isDict=false +after store.a = 10, live keyCount=2 hasB=true isDict=true +after store.a = 10, snapshot keyCount=0 hasB=false isDict=false +after delete store.b, live keyCount=2 hasB=true isDict=true +after delete store.b, snapshot keyCount=0 hasB=false isDict=false +after adding c and b, live keyCount=2 hasB=true isDict=true +after adding c and b, snapshot keyCount=0 hasB=false isDict=false +sync calls after delete store.missing 1 + +# patched: findings 29, 30, 31 and 41 +start, live keyCount=2 hasB=true isDict=true +start, snapshot keyCount=5 hasB=true isDict=true +after store.a = 10, live keyCount=2 hasB=true isDict=true +after store.a = 10, snapshot keyCount=5 hasB=true isDict=true +after delete store.b, live keyCount=1 hasB=false isDict=true +after delete store.b, snapshot keyCount=4 hasB=false isDict=true +after adding c and b, live keyCount=3 hasB=true isDict=true +after adding c and b, snapshot keyCount=6 hasB=true isDict=true +sync calls after delete store.missing 0 +``` + +### Port 14: a getter that lists the keys of `this`, before and after sketch A + +`14-snapshot-keys.ts`: + +```ts +// API question 3: what a getter sees when it lists the keys of `this`. +import {reactive} from '@vue/reactivity'; +import {attempt, out, section} from './helpers'; + +const variant = process.argv[2]; +const {createClassyStore, snapshot} = await import( + variant === 'patched' + ? '../ours-copy/src/index.ts' + : '/packages/classy-store/src/index.ts' +); + +class Dict { + a = 1; + b = 2; + get entryCount() { + return Object.entries(this).length; + } +} +section(variant); +const store = createClassyStore(new Dict()); +out('Object.keys(store)', Object.keys(store).join(',')); +out('Object.keys(snapshot(store))', Object.keys(snapshot(store)).join(',')); +out( + 'live store.entryCount', + attempt(() => store.entryCount), +); +out( + 'snapshot(store).entryCount', + attempt(() => snapshot(store).entryCount), +); +if (variant === 'current') { + const vue = reactive(new Dict()); + out('vue Object.keys(reactive(new Dict()))', Object.keys(vue).join(',')); + out('vue reactive(new Dict()).entryCount', vue.entryCount); + out( + 'JSON.stringify(snapshot(store))', + attempt(() => JSON.stringify(snapshot(store))), + ); + out('vue JSON.stringify(reactive(new Dict()))', JSON.stringify(vue)); +} +``` + +Output: + +```text + +# current +Object.keys(store) a,b +Object.keys(snapshot(store)) a,b,entryCount +live store.entryCount 2 +snapshot(store).entryCount 0 +vue Object.keys(reactive(new Dict())) a,b +vue reactive(new Dict()).entryCount 2 +JSON.stringify(snapshot(store)) {"a":1,"b":2,"entryCount":0} +vue JSON.stringify(reactive(new Dict())) {"a":1,"b":2} + +# patched +Object.keys(store) a,b +Object.keys(snapshot(store)) a,b,entryCount +live store.entryCount 2 +snapshot(store).entryCount throws RangeError: Maximum call stack size exceeded. +``` + +### Sketch B: raw values on write, nodes found by raw object, functions left alone + +`patch-copy-raw.py`: + +```python +import sys +from pathlib import Path + +path = Path(sys.argv[1]) / "core/core.ts" +text = path.read_text() + +def swap(old, new): + global text + if text.count(old) != 1: + raise SystemExit(f"expected one match for {old[:50]!r}, found {text.count(old)}") + text = text.replace(old, new) + +# 1. Store the raw object, never a store proxy (Vue: `value = toRaw(value)` in `set`). +swap( + " const descriptor = findPropertyDescriptor(_target, prop);\n if (descriptor && !('value' in descriptor)) {", + " const given = typeof value === 'object' && value !== null ? internalsMap.get(value) : undefined;\n" + " if (given) return Reflect.set(receiver, prop, given.target);\n" + " const descriptor = findPropertyDescriptor(_target, prop);\n if (descriptor && !('value' in descriptor)) {", +) + +# 2. Find an existing node by raw object as well as by proxy (Vue: the proxy +# map is keyed by raw object and consulted before the type check). +swap( + " const existing = internalsMap.get(value);\n if (!existing) {\n" + " // An immutable value is held by reference, like a `Date`. Opaque types are\n" + " // ruled out first: they are read far more often than they are frozen.\n" + " if (!canProxy(value) || isImmutableValue(value)) return;\n", + " const viaProxy = internalsMap.get(value);\n" + " const existing = viaProxy ?? targetNodes.get(value);\n" + " if (!viaProxy) {\n" + " if (isImmutableValue(value)) return;\n" + " if (!existing && !canProxy(value)) return;\n", +) + +# 3. Leave alone what is not a method: an array element that is a function, a +# class, and `constructor`. Identity-sensitive searches compare identities. +swap( + " // Array prototype methods should not be cached the same way as class methods.\n" + " if (Array.isArray(_target)) return transactional(method, receiver);\n", + " if (Array.isArray(_target)) {\n" + " if (Object.hasOwn(_target, prop)) return value;\n" + " if (prop === 'includes' || prop === 'indexOf' || prop === 'lastIndexOf') {\n" + " return (wanted: unknown, ...rest: unknown[]) =>\n" + " Reflect.apply(method, (_target as unknown[]).map(identityOf), [identityOf(wanted), ...rest]);\n" + " }\n" + " return transactional(method, receiver);\n" + " }\n" + " if (\n" + " prop === 'constructor' ||\n" + " Object.getOwnPropertyDescriptor(method, 'prototype')?.writable === false\n" + " )\n" + " return value;\n", +) +path.write_text(text) +print("patched") +``` + +### Port 15: findings 5, 6, 7, 9, 10 and 42, before and after sketch B + +`15-patched-raw.ts`: + +```ts +// Runs against a throwaway copy of our source: raw values on write, nodes found +// by raw object, and functions that are not methods left alone. +import {attempt, out, section} from './helpers'; + +const variant = process.argv[2]; +const {createClassyStore, snapshot, subscribe} = await import( + variant === 'patched' + ? '../ours-copy-raw/src/index.ts' + : '/packages/classy-store/src/index.ts' +); +const {reactiveSet} = await import( + variant === 'patched' + ? '../ours-copy-raw/src/collections/index.ts' + : '/packages/classy-store/src/collections/index.ts' +); + +section(`${variant}: findings 7 and 10`); +{ + const raw = {id: 1}; + const store = createClassyStore({list: [raw], other: [] as {id: number}[]}); + out( + 'list.includes(raw), indexOf(raw), lastIndexOf(raw)', + `${store.list.includes(raw)}, ${store.list.indexOf(raw)}, ${store.list.lastIndexOf(raw)}`, + ); + out( + 'list.includes(list[0]), includes(snapshot row)', + `${store.list.includes(store.list[0])}, ${store.list.includes(snapshot(store).list[0])}`, + ); + const rawTo: {row?: {id: number}} = {}; + const to = createClassyStore(rawTo); + to.row = store.list[0]; + out('raw target holds the raw row after to.row = list[0]', rawTo.row === raw); + out('to.row === list[0] (one proxy for the row)', to.row === store.list[0]); + let calls = 0; + subscribe(to, () => calls++, {sync: true}); + store.list[0].id = 2; + out('a write through list[0] notifies the second owner', calls); + const rawList = [{id: 1}, {id: 2}]; + const reversed = createClassyStore({list: rawList}); + reversed.list.reverse(); + out( + 'raw list holds only raw rows after reverse()', + rawList.every((row) => row !== reversed.list[rawList.indexOf(row)]), + ); + out('snapshot after reverse()', JSON.stringify(snapshot(reversed).list)); +} + +section(`${variant}: finding 9`); +{ + class Inner { + n = 0; + inc() { + this.n++; + } + } + const raw = new Inner(); + const inner = createClassyStore(raw); + const outer = createClassyStore({inner: raw}); + out('outer.inner === inner', outer.inner === inner); + let outerCalls = 0; + let innerCalls = 0; + subscribe(outer, () => outerCalls++, {sync: true}); + subscribe(inner, () => innerCalls++, {sync: true}); + outer.inner.inc(); + out( + 'calls after outer.inner.inc(): outer, inner', + `${outerCalls}, ${innerCalls}`, + ); + out('snapshot(outer).inner.n', snapshot(outer).inner.n); +} + +section(`${variant}: findings 5, 6 and 42`); +{ + const first = () => 1; + const second = () => 2; + const store = createClassyStore({callbacks: [first, second]}); + out( + 'callbacks[0] === callbacks[0], === first', + `${store.callbacks[0] === store.callbacks[0]}, ${store.callbacks[0] === first}`, + ); + store.callbacks.splice(store.callbacks.indexOf(first), 1); + out( + 'after splice(indexOf(first), 1): kept second', + store.callbacks.length === 1 && store.callbacks[0] === second, + ); + class Model { + static label = 'model'; + count = 0; + inc() { + this.count++; + } + } + const holder = createClassyStore({Model}); + out( + 'store.Model === Model, label, instanceof', + attempt( + () => + `${holder.Model === Model}, ${holder.Model.label}, ${new holder.Model() instanceof holder.Model}`, + ), + ); + const model = createClassyStore(new Model()); + out('store.constructor === Model', model.constructor === Model); + const {inc} = model; + inc(); + out('a destructured method still works: count', model.count); +} + +section(`${variant}: finding 34, by add`); +{ + const row = {id: 1}; + const holder = createClassyStore({row}); + const store = createClassyStore({set: reactiveSet()}); + store.set.add(row); + store.set.add(holder.row); + out('add(raw) then add(proxy): size', store.set.size); +} +``` + +Output: + +```text + +# current: findings 7 and 10 +list.includes(raw), indexOf(raw), lastIndexOf(raw) false, -1, -1 +list.includes(list[0]), includes(snapshot row) true, false +raw target holds the raw row after to.row = list[0] false +to.row === list[0] (one proxy for the row) true +a write through list[0] notifies the second owner 1 +raw list holds only raw rows after reverse() false +snapshot after reverse() [{"id":2},{"id":1}] + +# current: finding 9 +outer.inner === inner false +calls after outer.inner.inc(): outer, inner 0, 0 +snapshot(outer).inner.n 1 + +# current: findings 5, 6 and 42 +callbacks[0] === callbacks[0], === first false, false +after splice(indexOf(first), 1): kept second false +store.Model === Model, label, instanceof false, undefined, false +store.constructor === Model false +a destructured method still works: count 1 + +# current: finding 34, by add +add(raw) then add(proxy): size 1 + +# patched: findings 7 and 10 +list.includes(raw), indexOf(raw), lastIndexOf(raw) true, 0, 0 +list.includes(list[0]), includes(snapshot row) true, true +raw target holds the raw row after to.row = list[0] true +to.row === list[0] (one proxy for the row) true +a write through list[0] notifies the second owner 1 +raw list holds only raw rows after reverse() true +snapshot after reverse() [{"id":2},{"id":1}] + +# patched: finding 9 +outer.inner === inner true +calls after outer.inner.inc(): outer, inner 1, 1 +snapshot(outer).inner.n 1 + +# patched: findings 5, 6 and 42 +callbacks[0] === callbacks[0], === first true, true +after splice(indexOf(first), 1): kept second true +store.Model === Model, label, instanceof true, model, true +store.constructor === Model true +a destructured method still works: count 1 + +# patched: finding 34, by add +add(raw) then add(proxy): size 1 +``` diff --git a/review/stage-2/zustand-jotai.md b/review/stage-2/zustand-jotai.md new file mode 100644 index 00000000..c10a65f2 --- /dev/null +++ b/review/stage-2/zustand-jotai.md @@ -0,0 +1,1540 @@ +# Stage 2: Zustand and Jotai (API read) + +Stage 2 of the pre-1.0 review, 2026-11-19. Read-only: nothing in the +repository was changed apart from this file. This is an API read, as the brief +asks: documentation and public API first, source only at the files named. + +## Libraries, versions and files read + +- **Zustand 5.1.0**, `https://github.com/pmndrs/zustand`, tag `v5.1.0`, commit + `9fed2eb2f3af672da9f7bf694b996df3831fc207` (2026-11-06), which is the npm + `latest` tag on 2026-11-19. Read under `src/`: `react.ts`, `traditional.ts`, + `react/shallow.ts`, `vanilla.ts` whole; `middleware/persist.ts` whole; + `middleware/devtools.ts` lines 1 to 560 (the part that decides action names, + connection handling and every message handled; the rest is the action-dropdown + helpers); `middleware/subscribeWithSelector.ts` and `middleware/ssrSafe.ts` + whole. Docs read: `docs/reference/middlewares/persist.md` and `devtools.md` + (parameters and troubleshooting), `docs/learn/guides/nextjs.md`, + `ssr-and-hydration.md`, and the "Changes in v5" part of + `docs/reference/migrations/migrating-to-v5.md`. +- **Jotai 3.0.2**, `https://github.com/pmndrs/jotai`, tag `v3.0.2`, commit + `9de9377d10a5ac01388764b89458e2d7091d29d4` (2026-11-09), npm `latest` on + 2026-11-19. Read under `src/`: `react/Provider.ts`, `useAtom.ts`, + `useAtomValue.ts`, `useAtomValueRawSync.ts`, `useSetAtom.ts`, + `react/utils/useHydrateAtoms.ts`, `vanilla/utils/atomWithStorage.ts` and + `vanilla/utils/selectAtom.ts`. Docs read: `docs/utilities/ssr.mdx`, + `storage.mdx`, `select.mdx`, `docs/guides/nextjs.mdx`, `debugging.mdx` + (headings only) and `docs/core/store.mdx`. Jotai's Redux DevTools support is + a separate package that is not in this repository, so it was not read. +- **Ours**, read at `release/1.0`, commit `c59084e`: + `frameworks/react/hooks/useClassyStore/useClassyStore.ts`, + `frameworks/react/utils/createStoreHook/createStoreHook.ts`, + `hooks/useLocalStore/useLocalStore.ts`, `frameworks/react/server.ts`, + `utils/persist/persist.ts` and `persist.types.ts`, `utils/devtools/devtools.ts`, + `utils/subscribe-key/subscribe-key.ts`, `utils/history/history.ts`, + `utils/utilityStatus/utilityStatus.ts`, `types.ts`, and the entry files + `index.ts` and `utils/index.ts`. Also `types.react.test.ts` (signatures), + `core/core.ts` lines 255 to 300, 470 to 500 and 575 to 612, and the guides + `REACT_SSR.md`, `REACT_SCOPING.md`, `PERSIST_TUTORIAL.md` and + `DEVTOOLS_TUTORIAL.md` under `website/content/docs/`. +- **Ports** ran on Bun 1.4.4 with `react@19.3.1`, `zustand@5.1.0`, + `jotai@3.0.2` and `happy-dom@21.0.4`, in a scratch folder. Our source was + copied (without tests) from `c59084e` into the same folder, so that one + React instance serves all three libraries. The code and output are in the + appendix. + +Line numbers for Zustand and Jotai refer to those tags. Line numbers for ours +refer to `c59084e`. + +## Summary + +Zustand and Jotai disagree with each other on almost everything except two +things: both notify subscribers synchronously, and both let you write from +anywhere. Where they agree with each other and we differ, a user coming from +either will be surprised. Where we differ from one only, the difference is a +choice. Ten findings; the three that matter most: + +1. **Hydration safety is automatic in Zustand and manual in ours (finding 1).** + Zustand's hook reads `getInitialState()` as the server snapshot, so a store + written between the server render and hydration (a persist restore, another + boundary) causes no mismatch. In our port the same case raised React's + hydration error until `prepareStoreForHydration` was called, and Jotai + raised it too. Capturing the initial snapshot automatically is a + non-breaking change and removes the one call every SSR user has to remember. +2. **`persist` fails silently where Zustand speaks (finding 3).** A stored + version that differs from `version` with no `migrate` is ignored with no + `onError`, no log and no status; Zustand logs `console.error`. An async + `migrate`, which Zustand accepts, makes ours restore nothing at all without a + word. The migrated record is also never written back, so the migration runs + on every load until the user's first edit (finding 4). +3. **`devtools` is the thinnest of the three integrations (findings 6 and 7).** + Every entry is named `STORE_UPDATE`. Time travel notifies a synchronous + subscriber once per field (3 notifications for a 3-field jump, against 1 in + Zustand), turns a `Date` field into a string, and `RESET`, `COMMIT`, + `ROLLBACK` and `IMPORT_STATE` are ignored. Method names are already known + inside the core (`core.ts:487-491`), so real action names are cheap. + +Where we are better: the hook with no selector, the `persist` handle, and the +types of the two utilities. "Where ours is clearer" lists them. + +## How the two libraries differ from ours + +This explains why some answers carry over and some cannot. + +- **Zustand's store is a value you replace; ours is one you mutate.** A write is + one `setState(partial)` call, so there is one atomic unit and one + notification (`vanilla.ts:66-81`). Ours has direct property writes, so the + atomic unit has to be made (transactions, `batch()`), and several of our + findings are about that gap. +- **Zustand's middleware wraps the state creator at creation time.** `persist` + and `devtools` wrap `set` and replace `api.setState` + (`persist.ts:218-223`, `devtools.ts:267-296`). That is why they can name an + action and write on every `set`, and also why they have no teardown and need + the `Mutate`/`StoreMutators` type machinery (`vanilla.ts:20-41`). Ours attach + after creation and return a handle. +- **Jotai separates definition from value.** An atom is a key; a store holds the + values (`store.mdx`). A module-level atom is therefore safe on a server, and a + `Provider` makes a fresh store per mount (`Provider.ts:23-49`). Ours, like + Zustand's, puts the value in the module-level object. +- **Neither has a snapshot.** Both hand the component the state object itself. + Questions about frozen snapshots and getters get "no position". + +## Findings + +### 1. The server snapshot is automatic in Zustand, manual in ours + +Stage 1 has no number for this; it bears on API question 7 and 8. + +- **What they do.** Zustand's `useStore` passes `() => selector(api.getInitialState())` + as React's `getServerSnapshot` (`react.ts:30-34`). `getInitialState` is the + state the creator returned (`vanilla.ts:85-86`, `:95`), and `persist` replaces + it with the pre-restore state (`persist.ts:234`). React uses that function + only on the server and while hydrating, so nothing needs calling. Jotai passes + `getSnapshot` for both (`useAtomValueRawSync.ts:35-39`), so a value written + before hydration mismatches; its answer is `useHydrateAtoms`, which sets atoms + once per store before the first read (`useHydrateAtoms.ts:27-54`) and is + documented as the way to do it (`ssr.mdx`). +- **What we do.** `useClassyStore` reads a snapshot from a `WeakMap` that only + `prepareStoreForHydration` fills (`useClassyStore.ts:73-75`, `server.ts:16-22`, + `hydrationSnapshots.ts:4`). Without that call the server snapshot is the + current state (`REACT_SSR.md`: "Unprepared stores retain the existing behavior"). +- **Difference in behaviour.** Port 3: render `0` on the server, write `5`, then + `hydrateRoot`. Zustand: no error, shows 5 after hydration. Zustand with + `persist` and a synchronous storage already holding 7: no error, shows 7. + Jotai: `Hydration failed because the server rendered text didn't match`. + Ours unprepared: the same error. Ours after `prepareStoreForHydration`: no + error. (Appendix, port 3.) +- **Proposal: adapt.** Capture the initial snapshot without being asked. Two + ways, to be decided in stage 3 (reasoning from reading, not prototyped): + capture in `createClassyStore`, or lazily just before the first write, so a + store that is never written costs nothing. Keep `prepareStoreForHydration` as + an explicit capture for a store that was changed before it reached React. The + contract becomes Zustand's: the server and the first client render both start + from the state the store was created with. A late Suspense boundary is already + handled by the `WeakMap`, which would simply be filled earlier. +- **Kind:** API design (removes a required call; also a diagnostics gain, since + forgetting it is a silent mismatch). +- **Cost:** `core.ts` (the write path, if lazy) or `createClassyStore`, and + `hydrationSnapshots.ts` moves out of the React folder. Not breaking. Risk + medium: a retained snapshot holds old objects alive, and writes made through + a raw reference (stage 1 finding 11) would bypass a first-write hook. + +### 2. Hook shape: our no-selector form and `isEqual` against `useShallow` and `equalityFn` + +Stage 1 has no number. + +- **What they do.** Zustand v5's `useStore(api, selector)` takes no equality + argument; a selector that returns a new object every call loops (`react.ts:32`, + and "Changes in v5" in the migration guide). Its fixes are `useShallow(selector)` + (`react/shallow.ts:4-11`) and the separate `useStoreWithEqualityFn(api, + selector, equalityFn)` from `zustand/traditional` (`traditional.ts:21-45`). With + no selector it returns the whole state and re-renders on every change. Jotai + has no selector at all; the slice is another atom, and `selectAtom(atom, + selector, equalityFn)` is "an escape hatch" (`select.mdx`, `selectAtom.ts:24-57`). +- **What we do.** `useClassyStore(store, selector, {isEqual})` and + `useClassyStore(store)`, which returns a `proxy-compare` tracking proxy and + re-renders only for fields the component read (`useClassyStore.ts:35-49`, + `:129-136`). A selector's result is cached per snapshot, so a new object each + call does not loop (`:196-229`). +- **Difference in behaviour.** Port 1. Zustand, selector `s => ({a: s.a})`: + React reports `The result of getSnapshot should be cached` and throws + `Maximum update depth exceeded` after 55 renders. Ours: one render, and + one re-render for an unrelated write; with `isEqual: shallowEqual` zero. + No selector, unrelated write: Zustand re-renders once, ours zero, Jotai (atom + per field) zero. +- **Proposal: keep the behaviour; adapt the name.** Our no-selector form is the + best of the three and needs no change. The option is called `isEqual`; in + these two libraries every equivalent is `equalityFn` (`traditional.ts:28`, + `subscribeWithSelector.ts:54`, `selectAtom.ts:22`). Renaming it before the + freeze costs a find and replace and removes a surprise. Also keep `shallowEqual` + exported; Zustand's users know it as `shallow`. +- **Kind:** API design. +- **Cost:** `useClassyStore.types.ts`, the three adapter docs, the type test + (`types.react.test.ts`, one assertion). Breaking, but the owner is the only + user. Risk low. + +### 3. `persist` is silent where Zustand reports + +Stage 1 findings 52, 53 and 55 are the same family (accepted input that does +nothing). + +- **What they do.** With a stored version that differs and no `migrate`, + Zustand logs `State loaded from storage couldn't be migrated since no migrate + function was provided` and keeps the current state (`persist.ts:276-278`). + When storage is unavailable it logs a warning on every write (`:197-208`). + `migrate` may return a promise (`:99-105`, handled at `:271-273`). A stored + record with no `version` field is accepted whatever the configured version + (`:262-265`). +- **What we do.** A version mismatch with no `migrate` returns `false` and + nothing else: no `onError`, no status change, no log (`persist.ts:310-315`). A + record with no version counts as version 0 (`:310-311`). `migrate` is typed + and called as synchronous (`persist.types.ts:78-81`, `persist.ts:314`). There + is no development-mode logging anywhere in the package (the only two + `console.error` calls are listener failures, `core.ts:325` and + `utilityStatus.ts:45`). +- **Difference in behaviour.** Port 4c: version 1 stored, `version: 2`, no + `migrate`. Zustand: state kept, `console.error` as above. Ours: state kept, + `onError` calls `[]`. Port 4d: record without a version, `version: 2`. + Zustand restores 7; ours ignores it (0). Port 7: `migrate` is `async`. + Zustand restores 7; ours restores 0, `onError` is empty, `isHydrated` is true + (reached through a cast; the types forbid it, but a plain JavaScript user + has no types). +- **Proposal: adapt.** (a) Report a version mismatch with no `migrate` through + `onError` under a new operation (for example `'migrate'`), so `usePersistStatus` + shows it. (b) Await `migrate` so that an async function works, as Zustand + does: `hydrateFromStorage` is already async (`persist.ts:385`), so the await + goes before `applyPersistedState`, and the edit-protection baseline is taken + before it already. If a promise is not wanted, throw when the return value has + a `then`. (c) Keep "no version means 0"; it is safer than Zustand's, which + accepts an old unversioned record into a new schema. Document it in + `PERSIST_TUTORIAL.md`. +- **Kind:** diagnostics, API design. +- **Cost:** `persist.ts`, `persist.types.ts` (`PersistOperation` gains a member; + `migrate` return type widens), tutorial. Not breaking. Risk low to medium: + awaiting `migrate` adds a turn between the read and the apply, which the + existing "hydration request" counter already guards (`:386`, `:405`). + +### 4. A migrated record is not written back + +- **What they do.** After a successful migration Zustand calls `setItem()` at + once, so the stored record carries the new version (`persist.ts:297-299`). +- **What we do.** `applyPersistedState` restores the migrated state and sets + `skipAutoSaveVersion` so the restore itself does not trigger a write + (`persist.ts:378-380`). Nothing writes the record at the new version until the + first edit. +- **Difference in behaviour.** Port 4e: stored `{old: 7}` at version 1, + `version: 2`, a `migrate` that renames the field. Zustand: restores 7 and has + written `{"state":{"n":7},"version":2}`. Ours: restores 7, writes nothing. +- **Why it matters.** The migration then runs on every page load until the user + edits something. A user who only reads stays at version 1 indefinitely. When + a later release deletes the old `migrate` branch because "everyone has + migrated", those users hit finding 3's silent path and lose the stored data + (reasoning from reading; the run shows only the missing write). +- **Proposal: adopt.** Save once after a successful migration. Take care that the + write is a revision the handle already expects, as the restore already is + (`:372-376`), and check with `syncTabs` on that two tabs which both migrate do + not keep rewriting each other's record (not run). +- **Kind:** bug (data lifecycle). +- **Cost:** `persist.ts` only, plus a test. Not breaking. Risk low to medium + (a write at load changes when storage is first touched). + +### 5. `persist` defaults and option names against both libraries + +- **What they do.** Zustand's `persist` needs only `name`. `storage` defaults to + `createJSONStorage(() => localStorage)`, evaluated lazily so a server does not + throw (`persist.ts:178-180`, `:31-41`; documented in `persist.md`). Jotai's + `atomWithStorage` needs a key and a value; the default storage is `localStorage` + with the same lazy guard and a development warning if it throws + (`atomWithStorage.ts:100-113`). Zustand names the filter + `partialize` (a function); Jotai has none, since each atom is one value. Both + take a `storage` that already (de)serialises (`PersistStorage`, + `SyncStorage`), where ours takes a raw string store. +- **What we do.** `name` and `storage` are both required, and `storage` is a raw + string store such as `localStorage` itself (`persist.types.ts:37-45`). The + filter is `properties: Array` + (`:57`), a list rather than a function. +- **Difference.** A Zustand user types `persist(store, {name: 'x'})` and gets a + type error. Everything after that is clearer in ours: a raw `localStorage` + needs no wrapper, and a per-key transform is typed per key where Zustand + offers one global `storage` plus `partialize`. The stored envelope is nearly + identical (`{state, version}`, ours adds `expiresAt`), so an app moving from + Zustand to us keeps its stored data (port 4a, 4f show the same keys). +- **Proposal: adapt.** Make `storage` optional and default to a lazily read + `globalThis.localStorage`, with no persistence (and one development warning, + once finding 3's diagnostics exist) where it is missing or throws. Keep + `properties`; `partialize` would be a second way to say the same. Keep the + names `name`, `version`, `migrate`, `merge` and `skipHydration`, which already + match Zustand's in spelling and argument order (`persist.md`, `persist.ts:176-187`). +- **Kind:** API design. +- **Cost:** `persist.ts`, `persist.types.ts`, docs. Not breaking. Risk low. + +### 6. `devtools` action names and entry timing + +Bears on API question 8. + +- **What they do.** Zustand's patched `setState` takes a third argument, a + string or `{type, ...}`; otherwise it uses `anonymousActionType` or infers the + caller's function name from the stack, falling back to `anonymous` + (`devtools.ts:267-280`, `:223-235`). Several stores can share one connection + through the `store` option, which prefixes the name (`:281-294`). +- **What we do.** Every entry is `{type: 'STORE_UPDATE'}` (`devtools.ts:78`). + The subscription is the batched one, so every mutation in one tick makes one + entry (`:76-79`). The store already knows the method name: the get trap wraps + each method in `transactional(method, receiver)` (`core.ts:487-491`), so the + outermost method call is the natural action. +- **Difference in behaviour.** Port 5a: `inc()`, `inc()`, `reset()` in one tick. + Ours sends one `STORE_UPDATE`. Zustand sends one entry per `set`: `anonymous` + for the arrow function in Bun (stack inference depends on the engine's stack + format), and `counter/incNamed` when the name is passed. +- **Proposal: adapt.** Name the entry after the outermost store method (the + transaction already has the call) and use `STORE_UPDATE` for a direct write + made outside a method. Send on the synchronous channel, once per outermost + transaction, so three methods in a tick give three entries, which is what a + time-travel panel needs. This does not need Zustand's stack inference. +- **Kind:** API design, diagnostics. +- **Cost:** `core.ts` (`transactional` passes a name to a small internal slot), + `devtools.ts`. Not breaking. Risk medium: it touches the hot path, so run + `bun run benchmark:core` before and after; `transactional` runs once per method + call and the added work is one assignment at depth 0. + +### 7. `devtools` time travel and the messages it ignores + +- **What they do.** Zustand handles `ACTION` (custom dispatch, action dropdown), + `DISPATCH` with `RESET` (back to `initialState`), `COMMIT` (re-init), + `ROLLBACK`, `JUMP_TO_STATE`, `JUMP_TO_ACTION`, `IMPORT_STATE` and + `PAUSE_RECORDING` (`devtools.ts:391-557`). Time travel is one `set` call, so one + notification (`:313-318`). `enabled` defaults to off in production + (`:251-254`). Every other option is passed to the extension's `connect()` + (`:240-241`, `:327`), so `actionsDenylist`, `maxAge` and `trace` work. +- **What we do.** Only `JUMP_TO_STATE` and `JUMP_TO_ACTION` (`devtools.ts:85`). + Each key of the parsed state is assigned one at a time with no `batch()` + (`:91-101`). `enabled` defaults to `true` in any environment (`:57`). Only + `name` reaches `connect()` (`:66`). +- **Difference in behaviour.** Port 5b: a jump over 3 fields gives a + synchronous subscriber 3 calls (Zustand: 1), so a React binding is notified + three times for one jump. Port 5c: a `Date` field comes back as the string + `1970-01-01T00:00:00.000Z` after a jump, because the extension sends JSON and + the assignment takes it as is. A `RESET` message leaves the store unchanged + (n stayed 5). +- **Proposal: adopt (batch and Date), adapt (messages and options).** Wrap the + jump in `batch()` (one line). For the `Date` case, keep a current value that + is not JSON-like instead of overwriting it, or reuse the persist transform + shape. Handle `RESET` (back to the state captured at `devtools()` time, which + is what `init()` already sends), `COMMIT` and `ROLLBACK`. Pass remaining + options to `connect()`. Decide `enabled`: tie the default to the environment + as Zustand does, or leave it and keep the "Development-only" example in the + tutorial. The security agent covers the `message.state` parse. +- **Kind:** bug (batch, Date), API design (the rest). +- **Cost:** `devtools.ts`, `DEVTOOLS_TUTORIAL.md`. Not breaking, except a default + change for `enabled`. Risk low. + +### 8. Slice subscriptions: `subscribeKey` against `subscribeWithSelector` + +Bears on API question 1. + +- **What they do.** `subscribeWithSelector` adds an overload + `subscribe(selector, listener, {equalityFn, fireImmediately})`; the listener + gets the selected value and the previous one (`subscribeWithSelector.ts:46-71`). + The plain listener gets `(state, previousState)` (`vanilla.ts:62`). Jotai's + `store.sub(atom, listener)` takes a derived atom for a slice and passes no + arguments (`store.mdx`). +- **What we do.** `subscribeKey(store, key, cb, options)` takes a top-level key + only and calls `cb(value, previous)` (`subscribe-key.ts:17-42`). The core + `subscribe(store, cb, options)` calls `cb()` with nothing (`core.ts:585-603`). + There is no `equalityFn` and no `fireImmediately`. +- **Difference in behaviour.** Port 6b: watching `items.length`. Zustand's + selector does it in three lines and also fires immediately (`[[1,1],[2,1]]`). + Ours cannot name a derived value or a nested field; the port compares by hand + and gets `[[2,1]]`. +- **Proposal: adapt.** Let `subscribeKey` take a selector function as well as a + key, or add a separate selector function, and give it `equalityFn` and + `fireImmediately`. Leave the argument-free `subscribe(store, cb)`, since the + listener can call `snapshot(store)` at no cost (the snapshot is cached by + version); but say so in `API_REFERENCE.md`, because a Zustand user expects + `(state, prev)`. +- **Kind:** API design. +- **Cost:** `subscribe-key.ts`, its types and tutorial. Not breaking if the key + form stays. Risk low. + +### 9. Subscriber delivery: the three libraries chose differently + +Stage 1 findings 18 to 22; bears on API question 1. + +- **What they do.** Zustand notifies with `listeners.forEach` over a `Set` + (`vanilla.ts:79`) and passes the variable `state`, read at call time. Jotai + `store.sub` is synchronous too (port 6a). Neither has a loop guard. +- **What we do.** The core has batched and synchronous listener sets + (`core.ts:585-603`); stage 1 pinned the results as findings 18 to 22. +- **Difference in behaviour.** Port 8, with our subscribers synchronous: + finding 18 (a subscriber that writes): Zustand and Jotai both recurse with no + guard (stopped at 5000 by the test). Finding 20 (unsubscribe a later + subscriber from inside delivery): Zustand never calls it; ours calls it + once. Finding 21 (subscribe during delivery): Zustand calls the new subscriber + for the write in flight; ours does not. Finding 22 (re-entrant write): both + deliver the final state twice to the next subscriber, `[2, 2]`, identical. +- **Proposal: adopt for finding 20, keep ours for 21, no change for 18 and 22.** + Skipping a listener removed before its turn is what a caller expects and costs + a membership check. Not calling a subscriber that registered after the write is + the better rule, so ours is right there. For 18 and 22 neither library does + better; a guard is a stage 3 decision of its own. +- **Kind:** bug (20). +- **Cost:** the delivery loop in `core.ts`, and the test that pins finding 20. + Not breaking. Risk low. + +### 10. Server safety by construction, and the scoping story + +Bears on API question 8. + +- **What they do.** Jotai: atoms are definitions and `Provider` makes a store per + mount, so one app instance per request is isolated by default + (`Provider.ts:33-47`, `nextjs.mdx`). Zustand: "No global stores", create one + per request and pass it by context (`nextjs.md`), which is discipline, and an + experimental `ssrSafe` middleware that throws on `setState` when + `window` is undefined (`ssrSafe.ts:6-25`, marked "experimental" at `:3-5`). + Neither ships a context helper; Zustand's docs show a hand-written provider + that throws when used outside it. +- **What we do.** The same discipline as Zustand, documented in `REACT_SSR.md` + and `REACT_SCOPING.md`, plus `useLocalStore` for a store owned by one + component (`useLocalStore.ts:30-33`). No provider; no server-write check. +- **Proposal: reject a Provider and an automatic server-write check; keep + the docs.** A store is a value, not a key, so a provider would add a second + way to hold it. A server-write warning would fire on legitimate per-request + setup (the docs tell users to build the store from request data and mutate it + before render). If wanted, offer Zustand's opt-in shape (an explicit + read-only-on-server marker) rather than a default. `useLocalStore` is a + convenience neither library ships; keep it. +- **Kind:** docs. +- **Cost:** none to code. + +## Where ours is clearer + +- **The hook with no selector** re-renders only for fields read. Zustand's + returns everything and re-renders for everything; its v5 selector rule + (return a stable value or loop) is a trap ours does not have (port 1). +- **The `persist` handle.** `hydrated` (promise), `isHydrated`, `lastError`, + `isExpired`, `dispose()`, `save()`, `clear()`, `rehydrate()` and the + `usePersistStatus` hook replace Zustand's four pieces: `hasHydrated()`, + `onHydrate`, `onFinishHydration` and the `onRehydrateStorage` function + returning a function (`persist.ts:329-367`, `persist.md`). The handle is a + working external store (`getSnapshot`, `subscribe`; `utilityStatus.ts:11-24`). + Zustand's `persist` also has no teardown; ours does (`persist.ts:500-510`). +- **Errors.** `onError(error, operation)` covers read, parse, write and remove. + Zustand reports a read error only, through `onRehydrateStorage`'s second + argument (`persist.ts:317-326`); a failed write in its `setItem` is unhandled. +- **Edit protection during hydration.** A field edited while the read was in + flight keeps its edit (`persist.ts:343-377`). Neither library does this: both + replace state when the read lands (`persist.ts:296`, and `onMount`'s + `setAtom` at `atomWithStorage.ts:234`). +- **Types.** Our utilities are ordinary functions of a store. Zustand's + middleware need `StoreMutatorIdentifier`, `Mutate` and `StateCreator` with + four type parameters (`vanilla.ts:20-41`), and the docs have an + advanced-TypeScript guide (listed, not read). +- **Cross-tab sync** is an option (`syncTabs`). Zustand has none; Jotai's is + built into its default storage and cannot be turned off + (`atomWithStorage.ts:160-189`). + +## Names a user from either library would trip on + +| Ours | Zustand | Jotai | Note | +| -------------------------------------------- | -------------------------------------- | ------------------------------------------------ | ----------------------------------------------------------------------- | +| `isEqual` option | `equalityFn` | `equalityFn` | Finding 2. | +| `subscribe(store, cb)`, cb gets nothing | cb gets `(state, prev)` | cb gets nothing | Finding 8. | +| `persist` needs `storage` | defaults to `localStorage` | defaults to `localStorage` | Finding 5. | +| `properties: [...]` | `partialize(state)` | none | Keep ours. | +| `skipHydration` | `skipHydration` | restores on mount; `getOnInit` reads at creation | Same name as Zustand. | +| `persist` returns a handle | `store.persist.*` on the store | atom | Finding 5 and "clearer". | +| `prepareStoreForHydration` in `react/server` | automatic | `useHydrateAtoms` (client) | The name says server; it is called in client code too (`REACT_SSR.md`). | +| `devtools(store, {name, enabled})` | creator wrapper, many options | separate package | Findings 6 and 7. | +| `createStoreHook(store)` | `create(creator)` returns a bound hook | n/a | Ours is clear; Zustand's also exposes the store on the hook. | +| `useLocalStore(factory)` | docs recipe with `useState` | `Provider` | Neither ships it. | +| `shallowEqual` | `shallow`, `useShallow` | n/a | Keep. | + +## Stage 1 findings with a counterpart + +| Finding | Zustand | Jotai | +| ------------------------------------------------------- | ------------------------------------------------------------------------------------- | --------------------------------------------------------------- | +| 18, a sync subscriber that writes recurses | Same, no guard (port 8a) | Same, no guard (port 8a) | +| 19, batched subscriber served again in a loop | No counterpart: no batching | No counterpart | +| 20, a removed subscriber is still called once | Not called (port 8b) | Not run | +| 21, a late subscriber sometimes hears the write | Always hears the write in flight (port 8c) | Not run | +| 22, a re-entrant write delivers the same snapshot twice | Same: `[2, 2]` (port 8d) | Not run | +| 23, a returned rejected promise is not reported | The return value is ignored (`vanilla.ts:79`); reading only | Not read | +| 52, a getter named in `properties` | No getters; `partialize` is a function and `JSON.stringify` drops functions (reading) | n/a | +| 53, an array as stored `state` | The default `merge` spreads it into the state (`persist.ts:182-185`, reading) | n/a | +| 55, a malformed `properties` entry is ignored | No counterpart: `partialize` is a function | n/a | +| 56, debounce relative to a read | No debounce; writes on every `set` (`persist.ts:210-223`) | No debounce; writes on every set (`atomWithStorage.ts:259-260`) | +| 57, an edit in the same tick as `undo()` | No history middleware in the package | n/a | + +## The eight API questions + +1. **Should synchronous notification be the default for `subscribe()`?** Both + libraries notify synchronously, and neither has microtask batching (port + 6a: two writes, two calls, in both). They get atomicity from the shape of + the write: one `setState(partial)` or one atom write is one notification. + Ours has direct property writes, which have no such unit, so the microtask + default is the thing that gives a `store.a = 1; store.b = 2` pair one + notification. A user from either library will expect the sync behaviour, so + if the default stays batched, say it at the top of `API_REFERENCE.md`. If it + flips, a plain multi-field write must go through a method or `batch()`. + Evidence only supports "users expect sync"; it does not settle the choice. +2. **Writes outside a store method, and `batch()`.** Both libraries allow + writes from anywhere (`useStore.setState(...)`, `store.set(atom, ...)`) and + neither warns. Neither has `batch()`, because the multi-field write is a + single call (`setState({a, b})`; a Jotai write function that sets two atoms). + Our equivalent of that call is `Object.assign(store, {a, b})`, which is two + writes and two sync notifications (port 6d: Zustand 1, ours 2 synchronous and + 1 batched). So `batch()` belongs in the API, and a + warning on an outside write would contradict what both libraries teach. +3. **Snapshot getters as enumerable own accessors.** No position: neither has + snapshots or class getters. +4. **Arrow-function methods and `#private` fields.** No position. Zustand's + state is a plain object of closures, so arrow functions are its normal form; + that is the expectation a user brings, and the reason `CLAUDE.md`'s "no arrow + methods" rule will surprise them (reasoning from reading). +5. **Native `Map` and `Set`.** No position from the libraries' code. Zustand's + docs have a guide on Maps and Sets (`docs/learn/guides/maps-and-sets-usage.md`, + listed, not read). +6. **Opt-in or opt-out for nested class instances.** No position: neither + proxies anything. +7. **Entry points, export names and adapter names.** Zustand: `zustand`, + `zustand/vanilla`, `zustand/middleware`, `zustand/shallow`, + `zustand/react/shallow`, `zustand/traditional`. Jotai: `jotai`, + `jotai/vanilla`, `jotai/react`, `jotai/utils`. Ours: `.`, `./react`, + `./react/server`, `./utils`, `./collections`, plus one entry per framework. + Both libraries keep the vanilla core, the React binding and the utilities in + separate entries, so ours matches them. Two differences to know: `utils` + is Jotai's word, and Zustand calls the same things `middleware`; and + `prepareStoreForHydration` sits in `react/server` but is called on the client + too, which neither library does (Zustand has no such call, Jotai's + `useHydrateAtoms` is client code with `'use client'`). Finding 1 removes the + odd one out. Hook names follow each library's pattern (`useStore`, + `useAtom`, `useClassyStore`), so ours is consistent; React-only helpers + (`useHistoryStatus`, `usePersistStatus`) live in the React entry, beside the + utilities they read, as expected. +8. **Development-only diagnostics for silent failures.** Both libraries use + them where ours has none. Zustand: `persist` logs a version mismatch with no + migrate and an unavailable storage (`persist.ts:197-208`, `:276`); `devtools` + warns about a reserved action type and malformed dispatch JSON + (`devtools.ts:364-374`, `:424-439`); `ssrSafe` throws on a server write. + Jotai: `useSetAtom` throws `not writable atom` (`useSetAtom.ts:33`), atoms + carry `debugLabel`, and `atomWithStorage` warns in development when + `localStorage` throws (`atomWithStorage.ts:106-109`). Both gate on the build + mode (`import.meta.env.MODE`, `process.env.NODE_ENV`). Candidates for ours, + each tied to a silent case already found: a version mismatch with no + `migrate`, a `migrate` that returns a promise, a malformed `properties` + entry (stage 1 finding 55), a getter named in `properties` (finding 52), and + an unrecognised devtools message. The package would need a convention for + the gate first, since it has none today. + +## What was verified by running code, and what was only read + +**Run (Bun 1.4.4, ports in the appendix):** + +- Fresh-object selector: Zustand loops, ours does not (port 1). +- No-selector re-renders: Zustand yes, ours no, Jotai no (port 1). +- Hydration after a write, four variants and Zustand with `persist` (port 3). +- Persist lifecycle with a synchronous storage, version mismatch with and + without `migrate`, unversioned record, migrate write-back, write counts and + envelope shape (port 4); Jotai's restore on mount (port 4b). +- Devtools action names, time-travel notification count, `Date` after a jump, + `RESET` (port 5), through a fake `__REDUX_DEVTOOLS_EXTENSION__`, not a real + extension. +- Subscription timing, slice subscription, the multi-field write (port 6), + async `migrate` (port 7), subscriber delivery cases (port 8). + +**Only read:** + +- Zustand's action-name inference from the stack in V8 or Firefox: the port ran + on Bun's engine, where it gave `anonymous`. +- Zustand's `useShallow` and `traditional` behaviour beyond port 1; Jotai's + `selectAtom`, `useHydrateAtoms` and `atomWithStorage` `RESET`/validator + paths; Jotai's delivery cases 8b to 8d; Jotai DevTools. +- That Zustand's `persist` has no teardown, reports no write errors and + replaces state when a read lands, and that Jotai does the same on mount: from + source, not run. +- Our `devtools` ignoring `COMMIT`, `ROLLBACK` and `IMPORT_STATE`: read at + `devtools.ts:85`; only `RESET` was run. +- Every proposal's cost, and finding 4's claim that the data is lost when an old + `migrate` branch is deleted: reasoning from the missing write. +- Finding 1's lazy-capture variant: not prototyped. +- Real-browser hydration: the ports use happy-dom, so React's recoverable error + is the evidence, not a browser console. + +## Appendix: ported tests and their output + +Each file is in the scratch folder +`/stage-2-zustand-jotai/ports/` +and runs with `bun test ` there. `./ours/` is a copy of our `src` +(without tests) from `c59084e`. The preload registers happy-dom and sets +`IS_REACT_ACT_ENVIRONMENT`; `helpers.ts` mounts a component inside `act`. + +### preload.ts + +```ts +import {GlobalRegistrator} from '@happy-dom/global-registrator'; + +GlobalRegistrator.register(); +// @ts-expect-error +globalThis.IS_REACT_ACT_ENVIRONMENT = true; +``` + +### helpers.ts + +```ts +import {act, createElement} from 'react'; +import {createRoot} from 'react-dom/client'; + +export const SRC = './ours'; + +export async function mount(element: React.ReactElement) { + const container = document.createElement('div'); + document.body.appendChild(container); + const root = createRoot(container); + await act(async () => { + root.render(element); + }); + return { + container, + unmount: () => act(async () => root.unmount()), + }; +} +export {act, createElement}; +``` + +### p1-selectors.test.tsx + +```ts +// Ports 1 and 2: selector shape and what makes a component re-render. +import {expect, spyOn, test} from 'bun:test'; +import {createClassyStore} from './ours/index.ts'; +import {shallowEqual} from './ours/index.ts'; +import {useClassyStore} from './ours/frameworks/react/react.ts'; +import {atom, createStore, Provider, useAtomValue} from 'jotai'; +import {act} from 'react'; +import {create} from 'zustand'; +import {useShallow} from 'zustand/react/shallow'; +import {mount} from './helpers'; + +// Port 1: a selector that returns a NEW object on every call. +test('1a zustand v5: selector returning a fresh object, no useShallow', async () => { + const useStore = create<{a: number; b: number}>(() => ({a: 1, b: 2})); + const errors = spyOn(console, 'error').mockImplementation(() => {}); + let renders = 0; + let thrown: unknown; + function C() { + renders++; + const {a} = useStore((s) => ({a: s.a})); + return {a}; + } + try { + await mount(); + } catch (e) { + thrown = e; + } + const msg = String(errors.mock.calls[0]?.[0] ?? '').slice(0, 80); + errors.mockRestore(); + console.log('zustand fresh-object selector: renders', renders, 'thrown', String(thrown).slice(0, 90), '| console.error:', msg); +}); + +test('1b zustand v5 with useShallow: fresh object, stable result', async () => { + const useStore = create<{a: number; b: number}>(() => ({a: 1, b: 2})); + let renders = 0; + function C() { + renders++; + const {a} = useStore(useShallow((s) => ({a: s.a}))); + return {a}; + } + await mount(); + const before = renders; + await act(async () => useStore.setState({b: 3})); + console.log('zustand useShallow: renders after unrelated write', renders - before); +}); + +test('1c classy: fresh object selector without isEqual', async () => { + const store = createClassyStore({a: 1, b: 2}); + let renders = 0; + function C() { + renders++; + const {a} = useClassyStore(store, (s) => ({a: s.a})); + return {a}; + } + await mount(); + const first = renders; + await act(async () => { + store.b = 3; + }); + console.log('classy fresh-object selector: initial renders', first, 'after unrelated write', renders - first); +}); + +test('1d classy: fresh object selector with isEqual shallowEqual', async () => { + const store = createClassyStore({a: 1, b: 2}); + let renders = 0; + function C() { + renders++; + const {a} = useClassyStore(store, (s) => ({a: s.a}), {isEqual: shallowEqual}); + return {a}; + } + await mount(); + const first = renders; + await act(async () => { + store.b = 3; + }); + console.log('classy isEqual shallowEqual: initial renders', first, 'after unrelated write', renders - first); +}); + +// Port 2: no selector. Does an unrelated write re-render? +test('2a zustand: useStore(store) with no selector re-renders on any write', async () => { + const useStore = create<{a: number; b: number}>(() => ({a: 1, b: 2})); + let renders = 0; + function C() { + renders++; + const s = useStore(); + return {s.a}; + } + await mount(); + const first = renders; + await act(async () => useStore.setState({b: 3})); + console.log('zustand no selector: re-renders after unrelated write', renders - first); +}); + +test('2b classy: no selector is auto-tracked', async () => { + const store = createClassyStore({a: 1, b: 2}); + let renders = 0; + function C() { + renders++; + const s = useClassyStore(store); + return {s.a}; + } + await mount(); + const first = renders; + await act(async () => { + store.b = 3; + }); + const afterB = renders - first; + await act(async () => { + store.a = 9; + }); + console.log('classy no selector: re-renders after unrelated write', afterB, 'after read field write', renders - first - afterB); +}); + +test('2c jotai: one atom per field, useAtomValue re-renders only for its atom', async () => { + const aAtom = atom(1); + const bAtom = atom(2); + const store = createStore(); + let renders = 0; + function C() { + renders++; + return {useAtomValue(aAtom)}; + } + await mount( + + + , + ); + const first = renders; + await act(async () => store.set(bAtom, 3)); + console.log('jotai: re-renders after unrelated atom write', renders - first); +}); +``` + +Output: + +```text + +zustand fresh-object selector: renders 55 thrown Error: Maximum update depth exceeded. This can happen when a component repeatedly calls se | console.error: The result of getSnapshot should be cached to avoid an infinite loop +zustand useShallow: renders after unrelated write 0 +classy fresh-object selector: initial renders 1 after unrelated write 1 +classy isEqual shallowEqual: initial renders 1 after unrelated write 0 +zustand no selector: re-renders after unrelated write 1 +classy no selector: re-renders after unrelated write 0 after read field write 1 +jotai: re-renders after unrelated atom write 0 + +``` + +### p3-hydration.test.tsx + +```ts +// Port 3: the store changes between server render and hydration (what a +// persist restore, or another boundary hydrating first, does). +import {expect, test} from 'bun:test'; +import {atom, createStore, Provider, useAtomValue} from 'jotai'; +import {act} from 'react'; +import {hydrateRoot} from 'react-dom/client'; +import {renderToString} from 'react-dom/server'; +import {create} from 'zustand'; +import {createClassyStore} from './ours/index.ts'; +import {useClassyStore} from './ours/frameworks/react/react.ts'; +import {prepareStoreForHydration} from './ours/frameworks/react/server.ts'; + +async function hydrate(element: React.ReactElement, html: string) { + const container = document.createElement('div'); + container.innerHTML = html; + document.body.appendChild(container); + const errors: string[] = []; + await act(async () => { + hydrateRoot(container, element, { + onRecoverableError: (e) => errors.push(String((e as Error).message).split('\n')[0].slice(0, 60)), + }); + }); + return {errors, text: container.textContent}; +} + +test('3a zustand: store written before hydration, no preparation', async () => { + const useStore = create<{n: number}>(() => ({n: 0})); + const C = () => {useStore((s) => s.n)}; + const html = renderToString(); + useStore.setState({n: 5}); // e.g. a persist restore or an earlier boundary + const r = await hydrate(, html); + console.log('zustand:', JSON.stringify({html, ...r})); +}); + +test('3b jotai: atom written before hydration, no useHydrateAtoms', async () => { + const nAtom = atom(0); + const store = createStore(); + const C = () => {useAtomValue(nAtom)}; + const tree = ( + + + + ); + const html = renderToString(tree); + store.set(nAtom, 5); + const r = await hydrate(tree, html); + console.log('jotai:', JSON.stringify({html, ...r})); +}); + +test('3c classy: written before hydration, not prepared', async () => { + const store = createClassyStore({n: 0}); + const C = () => {useClassyStore(store, (s) => s.n)}; + const html = renderToString(); + store.n = 5; + const r = await hydrate(, html); + console.log('classy unprepared:', JSON.stringify({html, ...r})); +}); + +test('3d classy: written before hydration, prepareStoreForHydration', async () => { + const store = prepareStoreForHydration(createClassyStore({n: 0})); + const C = () => {useClassyStore(store, (s) => s.n)}; + const html = renderToString(); + store.n = 5; + const r = await hydrate(, html); + console.log('classy prepared:', JSON.stringify({html, ...r})); +}); + +import {createJSONStorage, persist} from 'zustand/middleware'; +test('3e zustand + persist with a sync storage that already holds n=7', async () => { + const data: Record = {k: JSON.stringify({state: {n: 7}, version: 0})}; + const storage = createJSONStorage(() => ({ + getItem: (k) => data[k] ?? null, + setItem: (k, v) => void (data[k] = v), + removeItem: (k) => void delete data[k], + })); + const useStore = create<{n: number}>()(persist(() => ({n: 0}), {name: 'k', storage})); + const C = () => {useStore((s) => s.n)}; + const html = renderToString(); // server has no storage; use the initial state + const r = await hydrate(, html); + console.log('zustand persist (sync storage holding 7): getState().n =', useStore.getState().n, JSON.stringify({html, ...r})); +}); +``` + +Output: + +```text + +zustand: {"html":"0","errors":[],"text":"5"} +jotai: {"html":"0","errors":["Hydration failed because the server rendered text didn't mat"],"text":"5"} +classy unprepared: {"html":"0","errors":["Hydration failed because the server rendered text didn't mat"],"text":"5"} +classy prepared: {"html":"0","errors":[],"text":"5"} +zustand persist (sync storage holding 7): getState().n = 7 {"html":"0","errors":[],"text":"7"} + +``` + +### p4-persist.test.tsx + +```ts +// Port 4: persist lifecycle, version handling and what is written. +import {expect, spyOn, test} from 'bun:test'; +import {atom, createStore} from 'jotai'; +import {atomWithStorage} from 'jotai/utils'; +import {create} from 'zustand'; +import {createJSONStorage, persist} from 'zustand/middleware'; +import {createClassyStore} from './ours/index.ts'; +import {persist as classyPersist} from './ours/utils/index.ts'; + +const flush = () => new Promise((r) => setTimeout(r, 0)); +const memory = (seed: Record = {}) => { + const data = {...seed}; + const writes: string[] = []; + return { + data, + writes, + getItem: (k: string) => data[k] ?? null, + setItem: (k: string, v: string) => { + data[k] = v; + writes.push(v); + }, + removeItem: (k: string) => { + delete data[k]; + }, + }; +}; + +test('4a hydration timing with a SYNC storage', async () => { + const mem = memory({k: JSON.stringify({state: {n: 7}, version: 0})}); + const z = create<{n: number}>()( + persist(() => ({n: 0}), {name: 'k', storage: createJSONStorage(() => mem)}), + ); + const zAtCreate = z.getState().n; + const zHyd = z.persist.hasHydrated(); + + class S { + n = 0; + } + const c = createClassyStore(new S()); + const h = classyPersist(c, {name: 'k', storage: mem}); + const cAtCreate = c.n; + const cHyd = h.isHydrated; + await h.hydrated; + console.log( + JSON.stringify({ + zustand: {atCreate: zAtCreate, hasHydrated: zHyd}, + classy: {atCreate: cAtCreate, isHydrated: cHyd, afterHydrated: c.n}, + }), + ); + h.dispose(); +}); + +test('4b jotai atomWithStorage: initial value first, stored value on mount', async () => { + const mem = memory({k: JSON.stringify(7)}); + const a = atomWithStorage('k', 0, { + getItem: (k, init) => + mem.getItem(k) === null ? init : JSON.parse(mem.getItem(k) as string), + setItem: (k, v) => mem.setItem(k, JSON.stringify(v)), + removeItem: (k) => mem.removeItem(k), + }); + const store = createStore(); + const before = store.get(a); + const unsub = store.sub(a, () => {}); + console.log( + 'jotai: read before any subscriber', + before, + '| after sub (onMount)', + store.get(a), + ); + unsub(); +}); + +test('4c stored version differs and there is no migrate', async () => { + const mem = memory({k: JSON.stringify({state: {n: 7}, version: 1})}); + const err = spyOn(console, 'error').mockImplementation(() => {}); + const z = create<{n: number}>()( + persist(() => ({n: 0}), { + name: 'k', + version: 2, + storage: createJSONStorage(() => mem), + }), + ); + const zMsg = err.mock.calls.map((c) => String(c[0]).slice(0, 70)); + err.mockRestore(); + + class S { + n = 0; + } + const c = createClassyStore(new S()); + const errors: unknown[] = []; + const h = classyPersist(c, { + name: 'k', + version: 2, + storage: mem, + onError: (e, op) => errors.push([String(e), op]), + }); + await h.hydrated; + console.log( + JSON.stringify({ + zustand: {n: z.getState().n, console_error: zMsg}, + classy: {n: c.n, onError: errors, status: h.getStatus?.() ?? 'n/a'}, + }), + ); + h.dispose(); +}); + +test('4d stored value has no version field', async () => { + const mem = memory({k: JSON.stringify({state: {n: 7}})}); + const z = create<{n: number}>()( + persist(() => ({n: 0}), { + name: 'k', + version: 2, + storage: createJSONStorage(() => mem), + }), + ); + class S { + n = 0; + } + const c = createClassyStore(new S()); + const h = classyPersist(c, {name: 'k', version: 2, storage: mem}); + await h.hydrated; + console.log( + JSON.stringify({ + zustand_n_with_version_2_and_unversioned_record: z.getState().n, + classy_n: c.n, + }), + ); + h.dispose(); +}); + +test('4e after a migration, is the migrated record written back at once?', async () => { + const seed = JSON.stringify({state: {old: 7}, version: 1}); + const memZ = memory({k: seed}); + const z = create<{n: number}>()( + persist(() => ({n: 0}), { + name: 'k', + version: 2, + storage: createJSONStorage(() => memZ), + migrate: (s: any) => ({n: s.old}), + }), + ); + await flush(); + class S { + n = 0; + } + const memC = memory({k: seed}); + const c = createClassyStore(new S()); + const h = classyPersist(c, { + name: 'k', + version: 2, + storage: memC, + migrate: (s: any) => ({n: s.old}), + }); + await h.hydrated; + await flush(); + console.log( + JSON.stringify({ + zustand: {n: z.getState().n, writes: memZ.writes}, + classy: {n: c.n, writes: memC.writes}, + }), + ); + h.dispose(); +}); + +test('4f a persisted store with a method: what is written, and is there a way to stop writing', async () => { + const mem = memory(); + const z = create<{n: number; inc: () => void}>()( + persist((set) => ({n: 0, inc: () => set((s) => ({n: s.n + 1}))}), { + name: 'k', + storage: createJSONStorage(() => mem), + partialize: (s) => ({n: s.n}), + }), + ); + z.getState().inc(); + z.getState().inc(); + const zWrites = mem.writes.length; + class S { + n = 0; + inc() { + this.n++; + } + } + const memC = memory(); + const c = createClassyStore(new S()); + const h = classyPersist(c, {name: 'k', storage: memC}); + await h.hydrated; + c.inc(); + await flush(); + c.inc(); + await flush(); + console.log( + JSON.stringify({ + zustand: {writes: zWrites, last: mem.writes.at(-1)}, + classy: {writes: memC.writes.length, last: memC.writes.at(-1)}, + }), + ); + h.dispose(); +}); +``` + +Output: + +```text + +{"zustand":{"atCreate":7,"hasHydrated":true},"classy":{"atCreate":0,"isHydrated":false,"afterHydrated":7}} +jotai: read before any subscriber 0 | after sub (onMount) 7 +{"zustand":{"n":0,"console_error":["State loaded from storage couldn't be migrated since no migrate functi"]},"classy":{"n":0,"onError":[],"status":"n/a"}} +{"zustand_n_with_version_2_and_unversioned_record":7,"classy_n":0} +{"zustand":{"n":7,"writes":["{\"state\":{\"n\":7},\"version\":2}"]},"classy":{"n":7,"writes":[]}} +{"zustand":{"writes":2,"last":"{\"state\":{\"n\":2},\"version\":0}"},"classy":{"writes":2,"last":"{\"version\":0,\"state\":{\"n\":2}}"}} + +``` + +### p5-devtools.test.tsx + +```ts +// Port 5: devtools action names, and time travel across several fields. +import {expect, test} from 'bun:test'; +import {create} from 'zustand'; +import {devtools as zdevtools} from 'zustand/middleware'; +import {createClassyStore, subscribe} from './ours/index.ts'; +import {devtools} from './ours/utils/index.ts'; + +function fakeExtension() { + const sent: Array<{action: unknown; state: unknown}> = []; + let listener: ((m: any) => void) | undefined; + const ext = { + connect: (opts: unknown) => ({ + init: (s: unknown) => sent.push({action: 'INIT', state: s}), + send: (action: unknown, state: unknown) => sent.push({action, state}), + subscribe: (l: (m: any) => void) => { + listener = l; + return () => {}; + }, + unsubscribe: () => {}, + }), + }; + (globalThis as any).window.__REDUX_DEVTOOLS_EXTENSION__ = ext; + return {sent, dispatch: (m: unknown) => listener?.(m)}; +} +const flush = () => new Promise((r) => setTimeout(r, 0)); + +test('5a action names from a store method', async () => { + const z = fakeExtension(); + const useStore = create<{n: number; inc: () => void; incNamed: () => void}>()( + zdevtools( + (set) => ({ + n: 0, + inc: () => set((s) => ({n: s.n + 1})), + incNamed: () => + set((s) => ({n: s.n + 1}), undefined, 'counter/incNamed'), + }), + {name: 'z', enabled: true}, + ), + ); + useStore.getState().inc(); + useStore.getState().incNamed(); + + const c = fakeExtension(); + class S { + n = 0; + inc() { + this.n++; + } + reset() { + this.n = 0; + } + } + const store = createClassyStore(new S()); + const h = devtools(store, {name: 'c'}); + store.inc(); + store.inc(); + store.reset(); + await flush(); + console.log( + JSON.stringify({ + zustand: z.sent.map((x) => x.action), + classy: c.sent.map((x) => x.action), + }), + ); + h.dispose(); +}); + +test('5b time travel: how many sync notifications for a 3-field jump', async () => { + const c = fakeExtension(); + class S { + a = 0; + b = 0; + c = 0; + } + const store = createClassyStore(new S()); + const h = devtools(store); + let syncCalls = 0; + subscribe(store, () => syncCalls++, {sync: true}); + c.dispatch({ + type: 'DISPATCH', + payload: {type: 'JUMP_TO_STATE'}, + state: JSON.stringify({a: 1, b: 2, c: 3}), + }); + await flush(); + + const z = fakeExtension(); + const useStore = create<{a: number; b: number; c: number}>()( + zdevtools(() => ({a: 0, b: 0, c: 0}), {enabled: true}), + ); + let zCalls = 0; + useStore.subscribe(() => zCalls++); + z.dispatch({ + type: 'DISPATCH', + payload: {type: 'JUMP_TO_STATE'}, + state: JSON.stringify({a: 1, b: 2, c: 3}), + }); + console.log( + JSON.stringify({ + classy_sync_subscriber_calls_for_one_jump: syncCalls, + zustand_subscriber_calls_for_one_jump: zCalls, + }), + ); + h.dispose(); +}); + +test('5c time travel of a Date field, and RESET / COMMIT messages', async () => { + const c = fakeExtension(); + class S { + at = new Date(0); + n = 0; + } + const store = createClassyStore(new S()); + const h = devtools(store); + store.n = 1; + store.at = new Date(5000); + await flush(); + const jsonState = JSON.stringify({at: new Date(0), n: 0}); // what the extension sends back + c.dispatch({ + type: 'DISPATCH', + payload: {type: 'JUMP_TO_STATE'}, + state: jsonState, + }); + await flush(); + const afterJump = typeof (store as any).at + ':' + (store as any).at; + store.n = 5; + await flush(); + c.dispatch({type: 'DISPATCH', payload: {type: 'RESET'}}); + await flush(); + console.log( + JSON.stringify({ + classy_after_jump_type_of_at: afterJump, + n_before_RESET_message: 5, + n_after_RESET_message: store.n, + }), + ); + h.dispose(); +}); +``` + +Output: + +```text + +{"zustand":["INIT",{"type":"anonymous"},{"type":"counter/incNamed"}],"classy":["INIT",{"type":"STORE_UPDATE"}]} +{"classy_sync_subscriber_calls_for_one_jump":3,"zustand_subscriber_calls_for_one_jump":1} +{"classy_after_jump_type_of_at":"string:1970-01-01T00:00:00.000Z","n_before_RESET_message":5,"n_after_RESET_message":5} + +``` + +### p6-subscribe.test.tsx + +```ts +// Port 6: subscribing outside React, and to one slice. +import {expect, test} from 'bun:test'; +import {atom, createStore} from 'jotai'; +import {create} from 'zustand'; +import {subscribeWithSelector} from 'zustand/middleware'; +import {createClassyStore, snapshot, subscribe} from './ours/index.ts'; +import {subscribeKey} from './ours/utils/index.ts'; + +const flush = () => new Promise((r) => setTimeout(r, 0)); + +test('6a notification timing for two writes in a row', async () => { + const z = create<{n: number}>()(() => ({n: 0})); + let zc = 0; + z.subscribe(() => zc++); + z.setState({n: 1}); + z.setState({n: 2}); + const zSync = zc; + + const nAtom = atom(0); + const js = createStore(); + let jc = 0; + js.sub(nAtom, () => jc++); + js.set(nAtom, 1); + js.set(nAtom, 2); + const jSync = jc; + + const c = createClassyStore({n: 0}); + let cc = 0; + subscribe(c, () => cc++); + let cs = 0; + subscribe(c, () => cs++, {sync: true}); + c.n = 1; + c.n = 2; + const cSync = [cc, cs]; + await flush(); + console.log( + JSON.stringify({ + zustand_sync_calls: zSync, + jotai_sync_calls: jSync, + classy_default_and_sync_right_after: cSync, + classy_default_after_flush: cc, + }), + ); +}); + +test('6b slice subscription: a derived value, equality, fireImmediately, previous value', async () => { + const z = create<{items: number[]; other: number}>()( + subscribeWithSelector(() => ({items: [1], other: 0})), + ); + const zCalls: unknown[] = []; + z.subscribe( + (s) => s.items.length, + (len, prev) => zCalls.push([len, prev]), + {fireImmediately: true}, + ); + z.setState({other: 1}); // not the slice + z.setState({items: [1, 2]}); + + const c = createClassyStore({items: [1], other: 0}); + const cCalls: unknown[] = []; + // subscribeKey takes a key, not a selector: watch `items` and compare lengths by hand. + let prevLen = snapshot(c).items.length; + subscribeKey(c, 'items', (items) => { + if (items.length !== prevLen) { + cCalls.push([items.length, prevLen]); + prevLen = items.length; + } + }); + c.other = 1; + await flush(); + c.items.push(2); + await flush(); + console.log(JSON.stringify({zustand: zCalls, classy_by_hand: cCalls})); +}); + +test('6c subscribeKey on a nested path is not possible, only top-level keys', () => { + // `K extends keyof T & keyof Snapshot`: a nested field has no key here. + const c = createClassyStore({user: {name: 'a'}}); + const calls: unknown[] = []; + subscribeKey(c, 'user', (u) => calls.push(u.name)); + expect(typeof c.user).toBe('object'); +}); + +test('6d the multi-field write: Zustand setState({a, b}) against Object.assign on our store', async () => { + const z = create<{a: number; b: number}>()(() => ({a: 0, b: 0})); + let zc = 0; + z.subscribe(() => zc++); + z.setState({a: 1, b: 1}); + + const c = createClassyStore({a: 0, b: 0}); + let syncCalls = 0; + let batchedCalls = 0; + subscribe(c, () => syncCalls++, {sync: true}); + subscribe(c, () => batchedCalls++); + Object.assign(c, {a: 1, b: 1}); + await flush(); + console.log( + JSON.stringify({ + zustand_setState_two_fields: zc, + classy_Object_assign_sync: syncCalls, + classy_Object_assign_default: batchedCalls, + }), + ); +}); +``` + +Output: + +```text + +{"zustand_sync_calls":2,"jotai_sync_calls":2,"classy_default_and_sync_right_after":[0,2],"classy_default_after_flush":1} +{"zustand":[[1,1],[2,1]],"classy_by_hand":[[2,1]]} +{"zustand_setState_two_fields":1,"classy_Object_assign_sync":2,"classy_Object_assign_default":1} + +``` + +### p7-migrate.test.tsx + +```ts +// Port 7: an async migrate, which Zustand allows (PromiseLike result). +import {test} from 'bun:test'; +import {create} from 'zustand'; +import {createJSONStorage, persist} from 'zustand/middleware'; +import {createClassyStore} from './ours/index.ts'; +import {persist as classyPersist} from './ours/utils/index.ts'; + +const mem = (seed: string) => { + const d: Record = {k: seed}; + return { + getItem: (k: string) => d[k] ?? null, + setItem: (k: string, v: string) => void (d[k] = v), + removeItem: (k: string) => void delete d[k], + }; +}; +test('7 async migrate', async () => { + const seed = JSON.stringify({state: {old: 7}, version: 1}); + const z = create<{n: number}>()( + persist(() => ({n: 0}), { + name: 'k', + version: 2, + storage: createJSONStorage(() => mem(seed)), + migrate: async (s: any) => ({n: s.old}), + }), + ); + await new Promise((r) => setTimeout(r, 5)); + class S { + n = 0; + } + const c = createClassyStore(new S()); + const errs: unknown[] = []; + const h = classyPersist(c, { + name: 'k', + version: 2, + storage: mem(seed), + migrate: (async (s: any) => ({n: s.old})) as any, + onError: (e, op) => errs.push(op), + }); + await h.hydrated; + console.log( + JSON.stringify({ + zustand_n: z.getState().n, + classy_n: c.n, + classy_onError: errs, + classy_isHydrated: h.isHydrated, + }), + ); + h.dispose(); +}); +``` + +Output: + +```text + +{"zustand_n":7,"classy_n":0,"classy_onError":[],"classy_isHydrated":true} + +``` + +### p8-delivery.test.tsx + +```ts +// Port 8: stage 1 findings 18, 20, 21, 22 (subscriber delivery) against +// Zustand's subscribe and Jotai's store.sub. Ours is the same case with +// {sync: true} subscribers. +import {test} from 'bun:test'; +import {atom, createStore} from 'jotai'; +import {create} from 'zustand'; +import {createClassyStore, subscribe} from './ours/index.ts'; + +const flush = () => new Promise((r) => setTimeout(r, 0)); + +test('8a finding 18: a subscriber that writes to its own store', async () => { + const z = create<{n: number}>()(() => ({n: 0})); + let zCalls = 0; + let zErr = ''; + z.subscribe(() => { + zCalls++; + if (zCalls < 5000) z.setState({n: zCalls}); // bounded only so the test ends + }); + z.setState({n: -1}); + const j = createStore(); + const nAtom = atom(0); + let jCalls = 0; + j.sub(nAtom, () => { + jCalls++; + if (jCalls < 5000) j.set(nAtom, jCalls); + }); + j.set(nAtom, -1); + console.log( + JSON.stringify({ + zustand_calls_until_bound: zCalls, + jotai_calls_until_bound: jCalls, + }), + ); +}); + +test('8b finding 20: unsubscribe a later subscriber during delivery', async () => { + const z = create<{n: number}>()(() => ({n: 0})); + let unsubB = () => {}; + const zLog: string[] = []; + z.subscribe(() => { + zLog.push('A'); + unsubB(); + }); + unsubB = z.subscribe(() => zLog.push('B')); + z.setState({n: 1}); + + const c = createClassyStore({n: 0}); + const cLog: string[] = []; + let cUnsubB = () => {}; + subscribe( + c, + () => { + cLog.push('A'); + cUnsubB(); + }, + {sync: true}, + ); + cUnsubB = subscribe(c, () => cLog.push('B'), {sync: true}); + c.n = 1; + console.log(JSON.stringify({zustand: zLog, classy_sync: cLog})); +}); + +test('8c finding 21: subscribe during delivery of the write that is being delivered', async () => { + const z = create<{n: number}>()(() => ({n: 0})); + const zLog: string[] = []; + let added = false; + z.subscribe(() => { + zLog.push('A'); + if (!added) { + added = true; + z.subscribe(() => zLog.push('late')); + } + }); + z.setState({n: 1}); + + const c = createClassyStore({n: 0}); + const cLog: string[] = []; + let cAdded = false; + subscribe( + c, + () => { + cLog.push('A'); + if (!cAdded) { + cAdded = true; + subscribe(c, () => cLog.push('late'), {sync: true}); + } + }, + {sync: true}, + ); + c.n = 1; + console.log(JSON.stringify({zustand: zLog, classy_sync: cLog})); +}); + +test('8d finding 22: a re-entrant write, what the next subscriber sees', async () => { + const z = create<{n: number}>()(() => ({n: 0})); + const zSeen: number[] = []; + let wrote = false; + z.subscribe((s) => { + if (!wrote) { + wrote = true; + z.setState({n: 2}); + } + }); + z.subscribe((s) => zSeen.push(s.n)); + z.setState({n: 1}); + + const c = createClassyStore({n: 0}); + const cSeen: number[] = []; + let cWrote = false; + subscribe( + c, + () => { + if (!cWrote) { + cWrote = true; + c.n = 2; + } + }, + {sync: true}, + ); + subscribe(c, () => cSeen.push(c.n), {sync: true}); + c.n = 1; + console.log( + JSON.stringify({zustand_B_sees: zSeen, classy_sync_B_sees: cSeen}), + ); +}); +``` + +Output: + +```text + +{"zustand_calls_until_bound":5000,"jotai_calls_until_bound":5000} +{"zustand":["A"],"classy_sync":["A","B"]} +{"zustand":["A","late"],"classy_sync":["A"]} +{"zustand_B_sees":[2,2],"classy_sync_B_sees":[2,2]} + +``` diff --git a/review/stage-3-decisions.md b/review/stage-3-decisions.md new file mode 100644 index 00000000..4ff41deb --- /dev/null +++ b/review/stage-3-decisions.md @@ -0,0 +1,2863 @@ +# Stage 3 decisions + +Stage 3 of the pre-1.0 review. No library source has been changed. Stage 4 +implements what is decided here, one change per commit, test first. + +**Status: decided.** Three rounds of review by agents that took no part in +the work raised 58, 30 and 17 objections. After each, the entries they +touched were decided again, most of them from a spike that built what the +objection asked for: seven more spikes in all. "Objections and answers" at +the end has a table for each round, and says what was decided after the +last round and has not been reviewed. The points left open by the spec, the +decision records and the task list were settled on 2026-11-25, when those +three were checked against this document; "Settled when the step 7 +documents were checked" lists them. + +## How to read this + +- **Who decides.** The owner handed the decisions to the agent running the + plan on 2026-11-19, except merging into `main` and releasing. Each entry + therefore says what is decided and why, not what is proposed. +- **Evidence.** Every entry names the report that holds the patch, the tests + it changes and the measurements. The reports are under `review/stage-3/`; + `merged.md` there lists the issues as `M1` to `M77`, and those ids are used + here. "Finding N" is a numbered finding of `review/stage-1-report.md`. +- **Tests.** A spike was run against the unit suite of 1,341 tests. A test + that fails under a spike is one of three kinds: it pins the defect the + change removes ("fix"), it pins behaviour nobody promised ("incidental"), + or the change is wrong ("regression"). No change decided here has a + regression. +- **Labels.** **Before 1.0** means the change alters the public API or + documented behaviour, so after 1.0 it would be a breaking change. **Can + follow 1.0** means it could ship in a 1.x release without breaking a + consumer. The label says when a change must land at the latest. "Stage 4" + says whether it is scheduled now. +- **Bytes** are gzipped bytes of the main entry unless another entry is + named. Today it measures 3,661 against a budget of 3,750. + +## All decisions on one page + +"Kind" is one of the plan's five groups: bug, simplification, public API, +diagnostics, performance. Three more are used for what is not a change to +the library's behaviour: "repository" for the workflows and dependencies, +"constraint" for the numbers of `CONSTRAINTS.md`, and "docs". +"Stage 4" says whether the change is scheduled now. The entries are grouped +by subject below, so their numbers are not in order there. + +| No. | Decision | Kind | Label | Stage 4 | +| --: | ------------------------------------------------------------------------------------------ | ----------------------- | ---------------------------------------------- | -------------------- | +| 1 | A function in a field is a method when read through the store; the object is never changed | Public API, bug | Before 1.0 | Yes | +| 2 | `Object.defineProperty` through a store is a write | Bug | Before 1.0 | Yes | +| 3 | Suspension stays; the walk to a detached parent goes | Bug, simplification | Can follow 1.0 | Yes | +| 4 | Size ceilings for every entry, and the tooling that holds them | Constraint | Before 1.0 | Yes, first | +| 5 | Raw values on write, one node per raw object | Bug | Before 1.0 | Yes | +| 6 | `includes`, `indexOf`, `lastIndexOf` find the object the caller holds | Bug | Before 1.0 | Yes | +| 7 | `has` and `ownKeys` traps; a missing property is a value | Bug | Before 1.0 | Yes | +| 8 | A delete that removes nothing is not a change | Bug | Before 1.0 | Yes | +| 9 | A plain object from another realm is state | Bug | Before 1.0 | Yes | +| 10 | Getters: one kind of dependency; errors; the snapshot layer | Bug, simplification | Before 1.0 | Yes | +| 11 | Nested instances stay opt-in; the base class `ClassyStore` | Public API | Before 1.0 | Yes | +| 12 | A table per prototype in place of a descriptor lookup | Performance | Can follow 1.0 | Yes | +| 13 | One delivery queue, with a bound | Bug | Before 1.0 | Yes | +| 14 | A subscriber's error is caught and logged, a rejection too | Public API, bug | Before 1.0 | Yes | +| 15 | A setter is a transaction | Bug | Before 1.0 | Yes | +| 16 | `batch()` refuses a promise by its type and an `async` function when it runs | Public API | Before 1.0 | Yes | +| 17 | `subscribe()` stays batched by default | Public API | No change | Docs | +| 18 | Writes outside a method stay allowed | Public API | No change | No | +| 19 | `persist()` restores before it returns when the storage is synchronous | Public API | Before 1.0 | Yes | +| 20 | Dead and redundant code goes, in the commit that makes it dead | Simplification | Can follow 1.0 | Yes | +| 21 | Nothing `persist` cannot use is skipped in silence | Bug, diagnostics | Before 1.0 | Yes | +| 22 | `persist()` validates its options | Bug | Before 1.0 | Yes | +| 23 | A restore is all or nothing | Bug | Before 1.0 | Yes | +| 24 | A pending save is flushed; nothing is written back at load but an expiry stamp | Bug | Before 1.0 | Yes | +| 25 | Cross-tab sync ignores an event from another storage area | Bug | Can follow 1.0 | Yes | +| 26 | `persist` options stay as they are | Public API | No change | No | +| 27 | `devtools`: named entries, exact time travel, off in production | Public API, bug | Before 1.0 | Yes | +| 28 | An edit made in the same tick as `undo()` is recorded | Bug | Before 1.0 | Yes | +| 29 | `withHistory` restores a function held in an own field | Public API | Before 1.0 | Yes | +| 30 | Undo and time travel change a nested object in place | Bug, performance | Before 1.0 | Yes | +| 31 | `subscribeKey` without a snapshot of the whole store; no selector form | Performance | Can follow 1.0 | Yes | +| 32 | The workflows are hardened now; the release job is split after 1.0 | Repository | Can follow 1.0 | Pins and permissions | +| 33 | Dependencies: exact pin, an audit step | Repository | Can follow 1.0 | Yes | +| 34 | Documentation | Docs | With each | Yes | +| 35 | Every error carries a stable code | Diagnostics | Before 1.0 | Yes | +| 36 | One build, and one development-only check | Diagnostics | Before 1.0 for the guard; the check can follow | Yes | +| 37 | Vue, Angular and Solid build the snapshot when it is read | Performance | Before 1.0 for Vue; the others can follow | Yes | +| 38 | Vue: no listener left by a server render; a read-only ref | Bug, public API | Before 1.0 | Yes | +| 39 | Angular: `untracked()`, an injector option, its own context error | Bug, public API | Can follow 1.0 | Yes | +| 40 | The adapter names stay | Public API | No change | Docs | +| 41 | `prepareStoreForHydration` stays explicit; `isEqual` stays | Public API | No change | Docs | +| 42 | Collections: one membership rule, a snapshot index | Bug, performance | Before 1.0 for the rule; the index can follow | Yes | +| 43 | Class getters on one derived prototype per class | Public API, performance | Before 1.0 | Yes | +| 44 | A snapshot keeps a cycle | Bug, public API | Before 1.0 | Yes | +| 45 | Snapshot types: tuples, collection snapshots without mutators | Public API | Before 1.0 | Yes | +| 46 | A snapshot after one row changes still rebuilds the list | Performance | Can follow 1.0 | No | + +## The four decisions the rest hangs on + +### 1. A function in a field is a method when it is read through the store, and the object is never changed + +**Decision.** A function is a **method**, bound to the proxy of the object +that holds it and run as one transaction, in two cases: + +1. It is found on the prototype chain, under any key but `constructor`. Any + kind of function. This is today's rule. +2. It is the value of an own data property of an object that is not an + array, **and it is read through the store**. + +Case 2 does not apply, and the function is handed out as it is, when: + +- it is a class or a built-in constructor, which is told by its own + `prototype` property being read-only; +- it is a method that a read through any store handed out before; +- it is frozen, or it is a store; +- the property that holds it is read-only and not configurable. + +So an arrow function, a shorthand method, an `async` function, a bound +function, a generator method and a function written with the `function` +keyword are all methods when they are read through the store. + +**The rule never changes the object.** The raw object and every snapshot +hold each function as it was written. Only a read through the store hands +out the method. There is one method per object and function, so +`store.f === store.f`, and it takes the name of the key it was first read +under. + +Two rules for a method that is written back: + +- A method that the same object handed out is stored as the function it + wraps. `store.f = store.f` is no change, and `store.b = store.a` stores + `a`'s function. +- A method that another object handed out is stored as it is. It is data + there, and stays bound to the object it came from. + +A read of a function in a field counts as a read for a getter, so a getter +that calls a function held in a field sees a later replacement. + +**A read of a method the object has already handed out takes a short +path.** The full test asks for the property's descriptor, which is what +makes a read-only property safe to read. Once an object has handed out the +method for a function, a later read skips the descriptor as long as the +object is extensible, no definition through the store has made one of its +properties read-only, and the function is not frozen. A function on the +prototype chain never needs the descriptor. + +**How this entry got here.** It is the fourth form, and each review changed +it. + +1. The first draft took the "strict" rule: only a function on the prototype + chain is a method. The first review showed that a method in an object + literal then loses its transaction in silence. +2. The second form made a function an object is "born with" a method and + wrote the store's wrapper into the object. The second review showed what + that write costs (objections 1, 2, 3, 6, 7 and 8 of + `adversarial-2-core.md`, each with a script): a store made from a copy of + the object or of a snapshot ran the old store's methods; a callback on a + snapshot ignored the `this` its caller passed; a getter read on a + snapshot could write the live store through an object's own method; a + callback restored by `withHistory` came back wrapped; and a read-only + definition threw after it was made. +3. The third form left the object alone and handed out the method on a read + through the store, but handed out every function with a `prototype` of + its own as data. The third review showed that this takes the binding and + the transaction away from `inc: function () {…}` in an object literal, + which today is a bound method (objection 1 of `adversarial-3.md`): two + notifications for two writes, a `TypeError` when it is called detached in + strict code, and a write to `globalThis` in code that is not strict. +4. This form hands out only a class as data, and reads a method it has + already handed out by a short path. + +Each form was built and run against the case tables of the forms before it +and against the reviewers' scripts. + +**Why.** + +- It is today's behaviour with today's defects removed. On every row that + was run, it gives either today's answer or a fix of today's answer; no row + was found on which it is wrong where today is right. +- It keeps every fix. A class, a built-in constructor, a frozen function and + a store held as a value, and a function in a list, are handed out as they + are (findings 5, 6 and 42). `store.f = store.f` is no change. A getter that + calls a function in a field does not go stale. One function held by two + stores writes the store it is called on. A subclass's arrow field that + overrides the parent's is one transaction, with class fields compiled as + assignments and as definitions. A method has a name for `devtools`. A read + of a read-only property does not throw. +- It has no rule about when a function was written or how, so the result + does not depend on how a compiler emits a class field, an arrow function + or a shorthand method, and decision 11 needs no rule of its own. +- It never writes into the object it is given. A copy of that object, or of + a snapshot, holds plain functions, and a store made from one is + independent. + +**What it costs a user.** + +- **A function read through the store is not the function that was stored.** + `store.onSave === cb` is false. That is so today. The identity is kept + where a component reads it: `snapshot(store).onSave === cb` is true. +- **A method read through the store ignores the `this` its caller passes.** + It always runs on the store. That is so today. A function read from a + snapshot or from the object itself runs with the `this` its caller gives, + so an object of callbacks for another library is handed over from a + snapshot. +- **A method is called on the store, not on a snapshot.** A snapshot holds + the plain function. A method that writes `this` throws there in strict + code. An arrow-function field of a `ClassyStore` subclass writes the live + store from there, one write at a time and not as one transaction; a + component that takes such a method from the hook's snapshot and calls it + causes one notification per write. Nothing reports it. The reference + already says to call methods on the store. +- **A method copied through the store stays bound to the store it came + from.** `{...store}` reads through the store, so it copies methods, and a + new store built from that copy calls the old store's methods. That is so + today. A copy of a snapshot or of the object itself copies plain + functions. +- **A constructor written as a `function`, held as a value, is still handed + out as a method**, as today: it is not `===` to itself, its static + properties are not on what is read, and `instanceof` against it is false. + `new` on it still builds a real instance and does not touch the store. + The same holds for a class that a compiler has turned into such a + function with a writable `prototype`, which is what TypeScript emits for + ES5. A real class and a built-in constructor are handed out as they are, + and so is a class in the shape Babel emits, which has a read-only + `prototype`; that shape was written by hand for the run, not compiled. + The third form fixed this row and this form gives it back, because a + function cannot be both this and a method written with `function`, and + the method is the commoner of the two. A constructor that has to keep its + identity is frozen, or held in a list. +- **A call of a method held in a field is a little slower than today on + Node.** A call is 270 nanoseconds against 250, about 8%; on Bun it is + today's 177. A read and call of an arrow function held in a field is 74 + against 47 on Node and 39 against 35 on Bun. A method of a class costs + what it costs today. +- **One read can still throw.** After the store has handed out a method, a + definition made on the raw object behind the store that makes that + property read-only makes the next read throw a `TypeError`: the short path + cannot see a change made behind the store. Today every read of a + read-only function property throws. What is done to the raw object behind + a store is unspecified, and the reference says to make a property + read-only through the store. +- A property that is read-only and not configurable, for example after + `Object.freeze(store)`, hands out its function as it is, unbound. +- A class that does not extend the base class and has an arrow-function field + still writes to the raw instance, and no subscriber hears it. No rule + about wrapping can change what `this` is inside that arrow function. + Decision 11 is the answer to it. Decision 36 reports it, if its check + ships. + +**Not taken.** + +- **Strict:** only a function on the prototype chain is a method. A method + in an object literal is then not a transaction and throws when detached, + and the base class needs an exception of its own. +- **Born with, written into the object** (the second form). It keeps the + identity of a callback assigned to a declared field, and costs the five + failures listed above. +- **Every function with a `prototype` of its own as data** (the third form). + It fixes a constructor held as a value, and silently breaks a method + written with `function`. +- **Lenient as first spiked:** wrap every function on every read except an + element of a list, a class and `constructor`. It keeps the copied wrapper + and the stale getter, which this form removes. +- **The same rule without the short path.** It asks for the descriptor at + every read of any function, so no read can throw, also after a change + made on the raw object. It costs every method of a class 2 to 3% on Node, + at the edge of the spread, a call of a method held in a field 10 to 15% + against today, and a read and call of an arrow function held in a field + 1.6 to 1.8 times today's time. The one read it protects is in the + unspecified list and throws today. +- **Telling a bound function by its name.** A user can fake the name. + +**Evidence.** `spike-functions-2.md` for the form without the class test +and for the short path as first built, and `spike-functions-3.md` for this +form, all built on the strict rule, decision 2 and the base class. In +`core.ts`: 67 lines added and 18 removed for the rule, 21 and 6 for the +class test, and 20 for the short path with its test for a frozen function. +26 tests change against 28 on that base: the fixes of the strict rule that +concern a class, a list of functions and an array method stay fixes; its +one incidental change, the object-literal method that stopped being a +transaction, passes again; and so does the test that pins a `function` in a +field as a bound method. No regression. The typecheck shows only the base +class's new export. The main entry is 3,951 bytes with all three in. Some +seventy rows were run on today's source and on each form, among them the +scripts of the second and third reviews, and four rows for a property made +read-only after a first read. + +Timed in two rounds on both engines against today's source and the two +forms before. `store.read`, `store.method` and `create.small` touch today's +ranges on both engines, and the four cost ratios stay inside their limits. +The rows for a method held in a field are the ones quoted above. Not run: +the browser, framework and mutation suites; the naming hook of decision 27 +reading the key; a component that calls an arrow method taken from a +snapshot; a compiler's real ES5 output (the rows are written by hand in +each compiler's shape). + +**Label.** Before 1.0. **Stage 4:** yes. The task adds two rows to the core +benchmark, a call of a method held in a field and a read and call of an arrow +function held in a field, and records them before and after, in the commit +message. The change lands +only if `store.method` is inside the spread of the commit before it on both +engines, and the two new rows are no slower than the figures above allow: 10% +for the call and 1.6 times for the read and call. The baseline is the commit +before, not the figures of stage 1, which decision 12 has moved by then. + +**Docs.** The sentences at the end of `spike-functions-2.md`, with the second +and the eighth changed and one added as `spike-functions-3.md` says, go into +the tutorial and the reference. The architecture page describes the cache of +methods, which is per object. + +### 2. `Object.defineProperty` through a store is a write, and nothing is refused + +**Decision.** A definition through a store does the bookkeeping of a write: +the value becomes the property's child or the old child is detached, and +subscribers are told when the value, the getter, the kind of property or its +enumerability changed. Every descriptor is still forwarded to the raw object. +`Object.freeze(store)` keeps working and stays silent. A definition or a +delete of a property that is or was an accessor clears the node's getter +cache, so a getter that read it is not left stale (finding 44). No +`setPrototypeOf` trap is added. + +**Why.** + +- It removes findings 1, 45, 61, 66, 67 and 71 for 49 bytes, and every test + it changes pins one of those defects. +- It takes nothing away. An accessor or a read-only definition works + correctly on both layers afterwards, so refusing it would forbid something + that is right. +- The base class for arrow-function methods needs it: class fields reach the + trap as data descriptors (`merged.md`, contradiction 8). + +**Not taken.** + +- Refusing accessor and read-only descriptors (Immer's way): 160 bytes more, + most of it message text, and it rules out the base class. +- Refusing `Object.freeze(store)` (MobX's way): it gives up a feature added + on purpose and removes no code, because a frozen root passed to + `createClassyStore()` still needs the read-only case. +- A `setPrototypeOf` trap that throws (findings 47 and 48). After decision 1 + a method replaced on the prototype or a swapped prototype is picked up, + which was the defect in finding 47. `persist` cannot swap a prototype + (security 1). What is left is an application that swaps the prototype of + its own store on purpose, and that is not ours to forbid. + +**Evidence.** `spike-traps.md`, T3 (a). 28 lines added, 9 removed. 17 tests +change, all fixes. Timings inside the spread. + +**Label.** Before 1.0: the tutorial says today that `Object.defineProperty` +"bypasses assignment/deletion tracking". **Stage 4:** yes. + +### 3. Suspension stays; the walk to a detached parent goes + +**Decision.** Remove the `detachedParent` pointer and the walk in +`resumeScope()`. Keep suspend and resume. + +**Why.** + +- The walk is the cause of findings 61, 66, 67 and 68, among them the read + that never returns. Each node already saves its children's versions when it + is suspended, so each can resume on its own when it is touched. +- Suspension itself earns its place. Without it a write to a row that + outlived 2,000 replaced lists costs 122,610 nanoseconds against 446, until + the collector runs, and for as long as anything keeps the old lists alive. +- Ten lines out, one in, 36 bytes smaller, and the typecheck passes. + +**Not taken.** Removing suspension as a whole (85 lines), for the cost above. +The one-line fix of stage 1 (resume in the `defineProperty` trap) is +contained in decision 2 and is harmless beside this one. + +**Evidence.** `own-code.md`, `x2`, run twice in separate worktrees with the +same result. 6 tests change, all fixes. The reproduction of finding 66 hangs +on the unmodified source and returns with the patch. + +**Label.** Can follow 1.0: no documented behaviour changes. **Stage 4:** +yes, first, because decisions 2 and 12 touch the same traps. + +**The test of a runtime without `WeakRef`** (finding 68), whose pin flips +with this change, asserts what the change makes true: with `WeakRef` +removed, a row that is held after its list was replaced no longer keeps that +list alive, and the row still reads, writes, notifies and snapshots as a +store of its own. Only "it works" is guaranteed in such a runtime, so the +memory half is a change detector and its file says so. + +**Left as it is.** + +- The order in which owners are notified (findings 24 and 69, M16) is + **unspecified**. +- A subscription on a container that has left the store lasts while the + caller holds the store, the container or the unsubscribe function (M15). + The tutorial gains that sentence in this change (decision 34). Holding a + subscribed node strongly would turn a forgotten unsubscribe into a leak. +- A raw object changed while it is out of the store shows its old content in + the next snapshot (finding 25, M17). It is a case of "writes outside the + proxy are not seen", which the docs already state. + +### 4. The size budgets move once, to a ceiling, for the whole set + +**Decision.** The decided changes do not fit the budgets of +`CONSTRAINTS.md`, and no subset worth shipping does. Each budget gets a +ceiling, set here once for the whole set. One decision record carries all of +them. + +| Entry | Today | Budget today | Estimate | Ceiling | What moves it | +| --------------------- | ----: | -----------: | -------: | ------: | ---------------------------------------------------------------- | +| `.` (the main entry) | 3,661 | 3,750 | 5,375 | 5,575 | The first table below | +| `./utils` adds | 2,686 | 2,750 | 4,216 | 4,350 | The second table below | +| `./collections` adds | 727 | 750 | 911 | 950 | The snapshot index, the membership rule, the mutator check | +| `./react` adds | 1,662 | 1,700 | 1,693 | 1,750 | The guard for a cyclic snapshot | +| `./vue` adds | 280 | 300 | 369 | 400 | The read-time ref, the server path, the setter that throws | +| `./angular` adds | 271 | 300 | 381 | 425 | The read-time signal, `untracked()`, the injector, its own check | +| `./solid` adds | 312 | 335 | 346 | 375 | The read-time accessor | +| `./svelte` adds | 182 | 200 | 182 | 200 | Nothing | +| `./react/server` adds | 153 | 175 | 153 | 175 | Nothing | + +**How a ceiling is set.** The estimate, plus an allowance for what was +decided and never built, plus the 2% that every budget carries, rounded up to +the next 25 bytes. The allowances: 80 bytes on the main entry, because two +built combinations came out above the sum of their parts; 30 on `./utils` for +three parts of decisions 21 and 24 that no spike holds; 20 on `./vue` for the +setter that throws; 30 on `./angular` for its own context check. The first +draft's ceilings for `./react`, `./vue` and `./angular` were below their own +estimates plus 2%, so the last step of stage 4 would have failed on the +reports' own numbers. + +**A ceiling is an estimate and a tripwire, not a measurement.** The decided +set was never built as one. Each figure in the two tables below is one +change measured alone against today's source, or, where a change was built +on top of another, the bytes it added there; the note under each table says +which. Two combinations that were built came out above the sum of their +parts (the trap spikes 650 against 617, the snapshot spikes 243 against +230), and one below it (raw values, the searches, the freeze, +`defineProperty` and the table per prototype, 465 against 486). What a +ceiling is for is to stop the work: a change that would pass one is not +committed, and the question goes back to a decision. + +**How a budget moves in stage 4, and what enforces it.** + +- Stage 4's first commit is tooling only. `budgets.json` gets a `ceiling` + beside each budget, and the size script fails when a budget is above its + ceiling or a measured size above its budget. +- **A ceiling does not move with the work.** The floor guard refuses a + commit that changes a ceiling that exists together with anything else. The + first commit, which adds the ceilings, is the one exception, because there + is none before it. A ceiling + changes only in a commit that holds the new number and the decision + record's reason for it, and nothing more, so it cannot ride along with the + change that needs it. The first draft let a ceiling rise under the same + condition as a budget, which made the tripwire a sentence and not a check. +- **A budget moves with a line in the record.** The floor guard reads + `budgets.json` and `limits.json` as well as `CONSTRAINTS.md`, and blocks a + budget or a limit that rises unless the same commit adds a line to the + decision record. Today it reads `CONSTRAINTS.md` only, and one record + anywhere on the branch would switch it off for every later change. +- **The guard checks every commit, itself included.** It walks the commits + from its start to the head and judges each against its parent; today it + sees one difference for the whole branch. Its start is the merge base with + `main`, or, while `main` does not hold `CONSTRAINTS.md`, the commit that + added that file, as today: the commits before it were made with no bar. + The branch is kept linear, and the guard fails on a merge commit in its + range rather than judge one. Last, it judges the working tree (staged, + unstaged and untracked files) against the head, so that it is useful + before a commit too. CI runs it on the pull request, and it is run before + each push during stage 4. +- **Its own file is a bar file.** The guard cannot read a loosened rule out + of its own regular expressions, so every change to `scripts/floor-guard.mjs` + counts as one: the commit passes only if it adds a line to a record under + `docs/decisions/` that says what changed in the guard and why. Today it + leaves itself out, so a later commit could weaken it unseen. The same + holds for the two files that hold a part of the bar outside + `CONSTRAINTS.md` and that nothing else checks: the coverage settings in + `packages/classy-store/bunfig.toml` and the list of target files in + `packages/classy-store/tests/mutation/runMutation.ts`. A change that + tightens asks for the line too; it is one line. The text of the guard's + own patterns is not a finding: the guard does not scan its own file for + them, and the fixtures of its tests are put together when a test runs, so + that no file in the repository holds a line the guard would flag. The + first commit passes this rule like any other, with its lines in record + 0004. +- **A test made smaller is named in the commit message.** The floor forbids + a deleted test file and a test file left with fewer assertions. Judged per + commit, that rule would also block what the plan allows stage 4: a test of + public behaviour that a decision changes, and a test of internal state + rewritten when the internals change. Such a commit passes only if its + message has a line `Test-change: : ` for each such file, and + the reason names a decision (`decision N`) or the public-behaviour test + that covers the same fact (a path to a test file). In the working tree, + where no message exists yet, the guard reports it as a note. +- **Where the numbers live.** `budgets.json` holds each entry as + `{"budget": …, "ceiling": …}`. An entry with no ceiling fails the size + script, as one with no budget does today. The size rows of + `CONSTRAINTS.md` stop repeating the numbers and name `budgets.json`, so + that a budget that moves changes one file and the two cannot drift apart. + A budget or a limit that rises needs its line in record 0004; a rule of + `CONSTRAINTS.md` that is loosened needs a line in any record. +- **Each rule has a test.** The first commit adds tests for the size + script's two failures and for each rule of the guard, run on throwaway + repositories made by the test. +- A commit that grows an entry sets that entry's budget to its new measured + size plus 2%, adds a line with the measured size to the decision record, + and stays under the ceiling. +- When stage 4 ends, every budget is the final measured size plus 2%. +- The record is approved by the agent running the plan, under the owner's + words of 2026-11-19 in the plan's first ground rule. `CONSTRAINTS.md` says + "that the owner approved" and "the owner has not reviewed it yet"; both + sentences are brought in line with that rule in the same first commit. + +**The main entry, change by change.** + +| Change | Decision | Bytes | +| --------------------------------------------------------------------- | -------: | -----: | +| The rule for functions | 1 | +228 | +| `defineProperty` as a write | 2 | +49 | +| The walk to a detached parent removed | 3 | −36 | +| Raw values on write, and a child kept when its container is frozen | 5 | +104 | +| Searches that find the object the caller holds | 6 | +168 | +| `has` and `ownKeys` traps, a missing property as a value | 7 | +156 | +| A delete that removes nothing | 8 | +11 | +| A plain object from another realm | 9 | +81 | +| Getters: one kind of dependency, errors, a getter that writes | 10 | +281 | +| The base class | 11 | +13 | +| A table per prototype in place of a descriptor lookup | 12 | +180 | +| The delivery queue with its bound, setters, the rejection handler | 13 to 15 | +219 | +| The check for an `async` function in `batch()` | 16 | +50 | +| Dead lines removed | 20 | −32 | +| The hook through which `devtools` names a method | 27 | +12 | +| Class getters on a derived prototype, and `this` in a snapshot getter | 43 | +239 | +| A snapshot keeps a cycle | 44 | −9 | +| Sum | | +1,714 | + +Measured on top of another change, not alone: decision 1 (on the strict +rule, decision 2 and the base class; the row is the three together, 3,951 +bytes, less the other two), the later parts of decisions 5, 6, 10 and 12 +(each on the part before it), and decision 27 (on the first form of its +entries). + +The sum puts the main entry near 5,375 bytes, 47% above today's. The first +draft of this entry counted 4,820 and left two rows open. The 553 bytes since +then are what the three reviews asked for: the rule for functions (228, an +open row before), the child kept through a freeze (68), the searches that +answer correctly for a list of snapshots (68), the throw for a getter that +writes, by any path (116), the table that holds no getter body and cannot +grow without bound (61), and the hook for `devtools` (12, the other open +row). The messages were measured as their spikes wrote them; the codes of +decision 35 shorten them, by about 100 bytes for the first set and unmeasured +for the rest. (The report that measured the messages gives 271 bytes of text +in all; the difference is the text of refusals this document does not take.) + +**What `./utils` adds, change by change.** + +| Change | Decision | Bytes | +| -------------------------------------------------------------------------- | -----------: | -----: | +| `persist`, `history` and `devtools` as one build | 19 to 25, 27 | +710 | +| The `persist` rules of decisions 21 to 24, as built after the third review | 21 to 24 | +245 | +| The naming moved out of the core into `devtools.ts` | 27 | +57 | +| The root store's getter values in what `devtools` sends | 27, 43 | +95 | +| Restore in place | 30 | +113 | +| Each object entered once per restore | 30 | +16 | +| A container that would refuse the restore is replaced | 30 | +211 | +| `cloneSnapshot` made safe for a cycle | 44 | +21 | +| `subscribeKey` without a snapshot of the whole store | 31 | +62 | +| Sum | | +1,530 | + +The sum is 4,216 bytes. The first row is the first combination of the +`persist`, `history` and `devtools` changes; the second is what the rules +of decisions 21 to 24 add to it in their final form, with the write-back +after a migration taken out again. Three small parts of those decisions are +not in that build, and the ceiling has 30 bytes for them. + +**What each of the larger items buys, so that it can be weighed.** + +- 239 bytes (decision 43): a snapshot lists the store's keys, a snapshot of + a class with getters is four times faster to make, and `this` inside a + snapshot getter is right. +- 219 bytes (decisions 13 to 15): no stack overflow and no hung event loop + when a subscriber writes, and faster ordinary writes. +- 281 bytes (decision 10): five getter defects, a cached getter read a + quarter faster, and a getter that writes its own store told so on both + layers. +- 168 bytes (decision 6): `includes()` and `indexOf()` find the object the + caller holds, in about 1% of today's time. +- 228 bytes (decision 1): one rule for every function a store holds, a + method in an object literal that stays a transaction, and arrow-function + methods that work. +- 156 bytes (decision 7): getters that use `in` or `Object.keys(this)` stop + returning stale answers. It serves fewer users than the others. +- 180 bytes (decision 12): a field read 2.7 times faster on JavaScriptCore + and a fifth faster on V8. +- 81 bytes (decision 9): a rare case. It is taken because it cannot be added + later; stage 4 tries the form without the cache first. + +**What was cut to keep it down:** long error messages, refusals in the +`defineProperty` trap (160), recording reads outside a getter's own node +(124), cached getter errors (73), the changed-keys rebuild (270), an index +beside live collections (339), and every development warning but one. + +**The cost limits** of `CONSTRAINTS.md` are expected to hold, and that is a +forecast: the whole set was never timed. When stage 4 ends, the baselines +are recorded again. A limit that can be tightened is tightened to the highest +new run times 1.2. A limit that would have to rise needs a line in the +decision record, like a budget. + +**The docs.** `CLAUDE.md` says "about 3.7 KB" and "about 4.9 KB with the +React hooks"; the README gives no figure. Stage 5 changes both to the +measured figures. + +## Bugs + +### 5. Raw values on write, and one node per raw object + +**Decision.** The `set` trap stores the raw object behind a store proxy, and +`linkChild` finds an existing node by the raw object as well as by the proxy. +One addition, from the first review: when a property becomes read-only +through the store while it holds an object the store tracks +(`Object.freeze(container)`, or a definition without a value), the trap puts +that object's proxy in the raw slot first. A read-only property has to hand +out what the raw object holds, and this way that is the proxy. + +**Why.** It removes findings 9 and 10: a class instance that is already a +store stays connected when it is placed in another store by its raw object, +and the raw object behind a store no longer fills up with proxies. Decision 2 +needs it for one line: a definition must store the raw value too. + +The addition answers objection C2. Without it, raw values on write made a +child read back raw after its container was frozen through the store, and a +write through it told no one, where today a child that was assigned as a +proxy stays reactive. With it, every child the store tracked before the +freeze stays a child, however it got there. That is better than today for a +child that was assigned as a plain object or was present at creation: today +both read back raw after a freeze. + +**What stays raw, and is documented.** An object frozen before it reached +the store, and a read-only property defined with an object as its value +(both engines refuse a swap there). Such an object is handed out as it is; a +write through it is not seen, and the snapshot holds it unfrozen. That is +today's behaviour, and "a frozen object is a value" already says it for the +first. + +**Evidence.** `spike-traps.md`, T2, first part: 12 lines added, 8 removed, +36 bytes, 3 tests change, all fixes. `spike-core-2.md`, F1: 15 lines added +and 2 removed in the `defineProperty` trap, 68 bytes, no test changes beyond +those of decisions 2 and 5, typecheck passes, and the reviewer's +reproduction gives today's answers again. One earlier run had shown store +creation about 20% slower on Node with raw values on write. A second run, +between two runs of the unmodified source, does not: creating a small store +and a store of rows are both inside the drift of the machine on both +engines. + +**Label.** Before 1.0, because `outer.inner === inner` changes its answer. +**Stage 4:** yes, in the commit after decision 2. Decision 2 lands first and +stores a defined value as it is given; this commit changes both traps to +store the raw value and adds the swap. + +**Not covered, on purpose.** A list built from proxies and then assigned +(`this.items = this.items.filter(…)`) still holds proxies in its raw array. +Replacing them would change an array the caller may still hold. + +### 6. `includes`, `indexOf` and `lastIndexOf` find the object the caller holds + +**Decision.** On a list in a store, the three searches find an element that +is part of a store by any of its forms: its raw object, its proxy, or a +snapshot of it. Any other element, such as a snapshot or a frozen object +kept as a value, or a `Date`, is found by reference, as in a plain array. A +primitive is searched for with the native method. + +**Why.** `const row = {…}; store.rows.push(row); store.rows.includes(row)` is +`false` today (finding 7). That is a wrong answer from a documented array +method, in the most ordinary way of using it. + +The first draft compared every element by identity, and objection C7 showed +where that is wrong. Every snapshot of one object has the same identity, so +on a list of saved versions `indexOf(v2)` answered 0 and `includes` was true +for a version that was never pushed. A list of snapshots kept as values is +an undo stack, and it has to answer as a plain array does. + +**A reactive collection answers differently, on purpose.** `reactiveSet` and +`reactiveMap` match every member by identity, a value too (decision 42). So +two snapshots of one object are two elements of a list and one member of a +set. A list is an array and has to answer as one. A collection is asked +"is this row selected?" with whatever snapshot of the row a component +holds, and has to say yes after the row was edited. The collections guide +states the difference, and a test pins both answers. + +**How.** The raw list holds an element that is part of a store by its raw +object, or in an older list by its proxy, and a value by itself. So the +answer is the nearest hit of the engine's own search for up to three +values: the value given, and, when it is a form of an object in a store, +that object's raw form and its proxy. `fromIndex` is passed to the engine +unchanged. + +**Evidence.** `spike-traps.md`, T2, searches: 100 bytes, 7 tests change with +the first part of T2, all fixes. `spike-core-2.md`, F3, on top of it: 30 +lines added and 14 removed, 68 more bytes, the same 7 tests and no other, +and 18 rows of searches that agree with a plain array wherever a plain array +has an answer. A search for an object in a list of 1,000 rows takes 0.5 +microseconds on Bun and 0.9 on Node, against 95 and 180 today, where each +element goes through the `get` trap, and 0.15 and 0.2 for a plain array. It +allocates two short arrays per search for an object. A form with one loop +and no allocation was built as well: 42 bytes larger and five to eleven +times slower. + +**Label.** Before 1.0. **Stage 4:** yes. + +### 7. `has` and `ownKeys` traps on the live store, and a missing property as a value + +**Decision.** A getter that asks `'b' in this` or `Object.keys(this)` records +a dependency: on the key for `in`, and on a per-node counter of the key set +for `Object.keys`. A read of a property that is not there records that it +was missing, so such a getter is memoized like any other. + +**Why.** It removes findings 30 and 32 on the live store. A memoized getter +that returns a stale answer is a defect in the feature the library is built +around. + +**Not tracked in 1.0.** An own-property check inside a getter: +`Object.hasOwn(this, key)`, `this.hasOwnProperty(key)` and +`Object.getOwnPropertyDescriptor(this, key)`. They do not go through the two +traps, and a getter that uses one stays stale after a key is added, as it +does today. The docs say to use `in`. A trap that records them is an +addition and can follow 1.0. + +**For stage 4.** The `defineProperty` trap of decision 2, which lands +earlier, has to move the key counter when a definition adds a key or changes +whether it is enumerable. The lines, bytes, tests and timings below are for +the spike's own records; under decision 10 the change is written in that +decision's single shape, which no spike built, so stage 4 takes its figures +from its own build. + +**Evidence.** `spike-traps.md`, T4, the live store. 55 lines added, 7 +removed, 156 bytes. 9 tests change, all fixes. Timings inside the spread +except two metrics on Node that are 1.4% and 1.5% slower. Under decision 10 +the two new records take the single shape of a getter dependency, so stage 4 +writes this on top of that, not beside it. + +**Label.** Before 1.0: the reference says "A live getter that reads an absent +field recomputes on subsequent reads", and that sentence goes. **Stage 4:** +yes. + +**The snapshot half** (findings 31 and 41: what `this` is inside a snapshot +getter) is decision 43. + +### 8. A delete that removes nothing is not a change + +**Decision.** `delete store.dict.missing` returns `true` and does nothing +else. + +**Evidence.** `spike-traps.md`, T5. 2 lines, 11 bytes. 7 tests change, all +fixes, and one switch leaves the randomized test. + +**Label.** Before 1.0: guaranteed rule 2 says that a write which changes +nothing notifies no one, and that is false without this. **Stage 4:** yes. + +### 9. A plain object from another realm is state + +**Decision.** A plain object made in an iframe or a Node `vm` context is +proxied and frozen in snapshots like any other plain object (M13). Stage 4 +builds it first without the per-prototype cache and keeps the smaller form +that leaves store creation inside the spread. + +**Why.** Today writes to such an object notify no one and its snapshot is +not frozen, in silence. It ships in 1.0 or not at all: afterwards the object +is a frozen copy in a snapshot where today it is the object itself, so code +that compares or writes through a snapshot would break in a minor release. + +**Not taken.** A guard for a read of a property that was frozen behind the +store's back (finding 46, M7). That failure is loud, a `TypeError` on the +read, and its guard takes back most of what decision 12 gains on a nested +read. The docs say that the raw object must not be frozen once a store holds +it. + +**Evidence.** `spike-traps.md`, T6. 24 lines, 81 bytes with the cache, no +test changes. The form without the cache was not measured. + +**Label.** Before 1.0. **Stage 4:** yes. + +### 10. Getters: one kind of dependency, on both layers what the other has + +**Decision.** Take the combination of the getter spikes: + +- One kind of getter dependency, `{value, version}` by property. It contains + the version stamp that makes a clean read constant, records each property + once per run, and treats a missing property as a value. +- A getter that reads a getter which threw records that dependency, on both + layers, inside a frame that also covers validation. +- The snapshot layer keeps the memo map that nested getters filled (finding + 37) and reports a cycle with the live layer's error where it overflows the + stack today (finding 38). +- **A getter must not write to the object it is computed on, by any path.** + - On the live store, a write to the getter's own object throws a + `TypeError` that names the field: an assignment, a `delete`, a + definition, also through a method the getter calls. + - On a snapshot, a write to `this` throws the same way; the traps throw + themselves, so it holds in code that is not in strict mode too. And + while a snapshot getter runs, the live object the snapshot was taken + from counts as having a getter running. So a write that reaches the live + store around `this` throws as well, with nothing written and nobody + told: through an arrow-function method of a `ClassyStore` subclass, + through a reference to the store, or through a method called on the + store. + - The throw is for the one object the getter is computed on, and its + message names that object's field, not "the store". A getter on a nested + object that writes its parent or the root is not covered: the write goes + through on both layers, and it is unspecified. + - Allowed on both layers: a write to another store, and the construction + of a store inside a getter. A write to a child object is allowed on the + live store; on a snapshot it throws in strict code, because the child is + frozen, and is ignored in code that is not strict. + +**Why.** + +- It removes findings 32, 36 (the getter that catches an error), 37, 38 and + 39, and the cost that doubles per level for getters arranged as a diamond. +- One kind of dependency is the smallest of the correct designs: 77 bytes + smaller than three kinds with the fix added on. +- The stamp is safe for a subtree that has left the store. That was the open + question, and it is now tested: a differential fuzz of 300 seeds compared + 180,112 getter reads with a plain mirror, 55,058 of them on a node outside + the store, and it holds under decision 3. +- A snapshot is frozen, so a getter cannot write to it, and every adapter + reads snapshots. Today that write is dropped without a word. An error + there shows the mistake the first time a component reads the getter. +- The first draft left the live store as it is, and two objections showed + what that leaves (C12 and C13). `this.cache ??= …` worked on the store and + threw through every adapter. And the throw on a snapshot came from a trap + that returned `false`, which only strict code turns into an error, so a + getter in a plain script lost its write in silence. Both are closed. The + throw on the live store is the narrow one, for the getter's own object, so + the two reasons the first draft gave against a throw no longer apply: a + store built inside a getter and a call into another store both work. +- The second review found the path the first fix left open (objection 3 of + `adversarial-2-core.md`): a getter read on a snapshot that calls an + arrow-function method of its own class, or writes through a reference to + its store, wrote the live store and told its subscribers while a component + was reading. With the base class of decision 11 that is an ordinary way to + write a class, and every adapter reads snapshots. +- A throw that is added after 1.0 is a breaking change. Dropping one is not. + +**What it costs a user.** A getter that fills a cache field on its own +store, or calls a method that writes its own store, throws where it worked +on the live store. It already failed in every component. A getter that +writes to a child object still differs between the layers, as described +above; covering that would mean walking the parents on each write made while +a getter runs. It is **unspecified**, and the docs say that a getter must +not write to the store it reads. + +**Not taken.** + +- Recording reads outside the getter's own node (another store, a static). + It costs 124 bytes and 14 to 18% on a getter over 1,000 rows, and it cannot + work on a snapshot. The docs state the limit and the pattern that works: + hold the other store as a field. +- Caching a thrown error. 73 bytes and seven pinned behaviours for one gain. + It can follow 1.0, and whether errors are cached is **unspecified**. +- Throwing for every write made while any getter runs. It would refuse a + store that is constructed inside a getter, which the base class of + decision 11 does by writing its own fields, and a getter that calls a + method of another store. + +**Evidence.** `spike-getters.md`. The combination: 182 lines added, 144 +removed, 165 bytes. 16 tests change: 15 fixes and 1 incidental. On Node a +cached getter read is 26% faster and a recompute 6 to 9% slower; the four +cost ratios stay inside their limits on both engines. `spike-core-2.md`, F4, +on top of that combination: 9 lines in `snapshot.ts` and 16 in `core.ts`, 74 +bytes with the two messages as written. Nine kinds of write were run on both +layers. 3 more tests change, all incidental: they pin today's behaviour of a +getter that writes a field of its own store. `spike-core-3.md`, G1, on top of +that: 18 lines in `core.ts` and 21 in `snapshot.ts`, 42 bytes, no test +changes. Three snapshot getters that wrote the live store and notified now +throw: one that calls a base-class arrow method, one that writes through a +reference to the store, and one that calls a method on the store. A write, a +cached snapshot getter and a recomputed one are inside the spread on both +engines; on Bun the recomputed one is a steady 4% higher. Not built: these +rows on top of decision 1, and on top of decision 43. The spike hands each +snapshot's live object to the getters it installs on that snapshot; decision +43 installs a class's getters once, on a shared prototype, so the live +object has to be found from `this` at each run. Stage 4 writes this part in +step 4 on today's snapshot layer and runs its rows again as tests after step +5. + +**Label.** Before 1.0: a getter that writes becomes an error, and the +sentence about an absent field goes. **Stage 4:** yes. + +### 11. Nested class instances stay opt-in, and a base class makes arrow-function methods work + +**Decision.** + +- **Nested class instances stay opaque unless the class says otherwise** + (API question 6). `static [PROXYABLE] = true` stays, and + `static [PROXYABLE] = false` is documented as "opaque on purpose"; it works + today. +- **A base class, `ClassyStore`, is added to the main entry** (API question + 4). Its constructor returns the store, so a class that extends it is a + store from its first line: arrow-function fields, methods bound in the + constructor and whatever the constructor starts all write through the + store. Such a class is reactive wherever it is placed, with no marker. + `createClassyStore(new X())` stays, for a plain object and for a class + that cannot extend it. +- **The base class has no rule of its own for functions.** Decision 1 covers + it: an arrow-function field is a function in a field, so it is a method + when it is read through the store, and so is a subclass's field that + overrides the parent's. The first draft made these an exception that held + only here. +- **A `#private` field is never state.** The docs say so. With the base + class it can be used on the live store; a snapshot cannot carry it. +- **The base class ships in 1.0.** A second spike ran what the first only + reasoned, and each point holds or has a fix that was run. + +**Why.** + +- An arrow-function method that writes to the raw instance and tells no one + is the most prominent silent failure the library has, and the docs can + only warn about it today. The base class removes it for 13 bytes. +- It answers question 6 for a class the user owns. What then stays opaque by + default is what the user does not own, and for those objects opaque is + right. +- Wrapping class instances by default was run and is not taken. Eight tests + change, six of them the documented rule. A class with `#private` fields + throws. An object that changes itself leaves a stale copy that no check + can see. A graph of 5,461 objects placed in a store costs 20 milliseconds. + +**What it costs a user.** A class has to extend `ClassyStore` for its +arrow-function fields to work, and the docs gain these sentences: + +- A callback held in a field is compared on a snapshot, where it is the + function that was stored (decision 1). +- An arrow method is called on the store. Taken from a snapshot it still + writes the store, one write at a time and not as one transaction. +- Under React's `StrictMode`, `useLocalStore` makes two stores in + development, so a constructor that starts a timer starts two. +- A class that has to extend another class uses `createClassyStore(new X())` + and prototype methods. + +**Not taken.** Detecting an arrow function by its source text: it finds 6 of +7 lost writes, reports 2 fields that lose nothing, and costs 256 to 342 +bytes. An `opaque()` helper and a mixin form of the base class. + +**Evidence.** `spike-classes.md`, `spike-classes-2.md` and +`spike-functions.md`. The base class is 4 lines and 13 bytes. One subclass +was compiled 17 ways (TypeScript with class fields as definitions and as +assignments, Bun, Oxc, esbuild, the SWC of Next.js with the example's +configuration, Babel in spec and loose mode), and in every output the first +snapshot is right, an arrow method notifies once, and a field write and a +timer's write are seen. Those 17 outputs were run on the first draft's rule. +Decision 1 as it now stands changes nothing when an object is created, so +what they showed still holds, and the override case was run again both ways +with Bun's transpiler. Seven throwaway tests pass +for Vue, Svelte, Solid, Angular, `createStoreHook` and `useLocalStore`. A +base-class store made inside a getter works on both layers. + +**Label.** The default for nested instances: before 1.0, and no code. The +base class: an addition. **Stage 4:** yes, after decisions 1 and 2, and +after decision 30, which it needs. Stage 4 runs the 17 compilations again +on the real code. The forms the repository can compile with what it already +installs, TypeScript with class fields as definitions and as assignments +and Bun's transpiler, become committed tests. The other compilers run once +in a scratch folder, because adding them would change `bun.lock`; the +commit message carries their results. + +**After 1.0** (decision 36): a warning for an unmarked class placed in a +store, once it can be silenced for a class that is opaque on purpose. + +## Performance + +### 12. A table per prototype answers "is this key a getter?" + +**Decision.** The `get` and `set` traps stop walking the prototype chain with +`Object.getOwnPropertyDescriptor` on every access. An own key is decided with +`hasOwnProperty` and one flag per node. An inherited key is decided from a +table per prototype, filled on the first miss, that says for each key which +prototype object carries an accessor for it, or that none does. The table +holds no function. A read whose cached result is still valid returns it; +only a recompute asks that prototype for its getter, so the function that +runs is the one the class has now. + +**The table cannot grow without bound.** A key the prototype chain has is +always recorded. A key that is absent everywhere is recorded only while the +table holds fewer than 256 keys; after that such a key is looked up at each +read, as today. + +**Why.** A read is the hottest operation the library has, and this is the +largest gain any spike measured: a field read goes from 31.9 to 11.5 +nanoseconds on Bun and from 47.5 to 38 on Node, a read three objects deep +from 108 to 48 and from 143 to 116, and a cached getter read from 58 to 35 +and from 85 to 77. All 1,341 tests pass. + +The first draft cached the whole descriptor, getter included, and objection +C6 showed what that does: a getter redefined on the class kept its old body +on the live store while snapshots ran the new one, a getter replaced by a +value still ran, and a deleted getter still answered. In the form decided +here a redefined getter runs its new body at its next recompute, as today. + +**What it assumes.** A prototype is not changed after its first read through +a store. The library does not handle that fully today either (findings 44 and +47), and it is **unspecified**, with these answers for now, two of which +differ from today's. A getter added to a prototype for a key that was read as +absent is seen, and it is not memoized: its body runs at every read, where +today it runs once. An override nearer the instance is not seen. A getter +removed or replaced by a value is seen at its next recompute, where today it +is seen at once. + +The bound answers objection 5 of the second review. As first spiked, the +table kept an entry for every key that was ever looked up and not found, and +the table of `Object.prototype` is shared by every plain object of every +store. A dictionary read by keys it does not have yet grew it by 88 MB for a +million keys, with no key left in the store. With the bound the same run +grows the heap by 0.2 MB, as today. + +**Not taken.** Never recording an absent key: a read of a key that a class +instance does not have is then slower than today on Node (107 to 116 +nanoseconds against 97 to 100). No table for `Object.prototype` and +`Array.prototype`: the tables of class prototypes still grow, and +`Object.prototype` does carry an accessor, `__proto__`, which needs an +exception that is easy to miss. The table that caches the descriptor: 46 +bytes smaller and wrong as described. A table that names the prototype and +reads the getter at every read: 23 bytes smaller than the form taken, and a +cached getter read is then 19% slower on Node than today. + +**Evidence.** `spike-core-2.md`, F2, the lazy form: 55 lines added and 12 +removed in `core.ts`, 1 line in `ownership.ts`, 165 bytes, no test fails, +typecheck and lint pass. Timed in three rounds of five processes per engine, +back to back with the unmodified source and the other two forms. The +orchestrating agent's own run of the descriptor form agrees: a field read +19% faster on Node and 66% on Bun. `spike-core-3.md`, G2, form (c), on top +of it: 5 lines added and 2 removed, 15 bytes, no test fails, and every +timing of the lazy form kept, a read of an absent key included. Not +measured: a read of an absent key once the table holds 256; from the form +that never records one it is about today's cost on Node for a plain object +and up to 10% above today's for a class instance. Not built: this form on +top of the getter combination of decision 10, where the getter is read +after that combination's own validation. + +**Label.** Can follow 1.0. **Stage 4:** yes, before decisions 1 and 2, +because the trap then already knows "own or inherited", which decision 1 +asks. + +## Subscriber delivery and transactions + +### 13. One delivery queue, with a bound + +**Decision.** A write made while synchronous subscribers are being called is +queued and delivered after the round that is running, and before the +outermost write returns. A subscriber removed during delivery is not called. +A subscriber added during delivery hears the next change, not the one in +flight. One queue serves all stores. On the batched path, one microtask +serves every round: a write made inside a batched subscriber is delivered to +batched subscribers in that same microtask, after the round that is running. + +Delivery stops after 100 rounds. It then reports once, with the code +`delivery-loop`, the store keeps the writes, and subscribers that were +waiting are called at the next write. + +Four choices inside it: + +- **A subscriber hears of its own write**, once, as in MobX and Preact. A + subscriber that corrects state has to stop writing once the state is right. +- **One microtask for every batched round**, the same rule as the + synchronous path. +- **The report of the bound goes where a subscriber's error goes** (decision + 14). +- **The first round reads the owners directly.** This is the variant that + costs 30 more bytes and keeps a direct write with a synchronous subscriber + as fast as today. A direct write while a component is mounted is the most + common write an application makes, so it is not the one to slow down. + Stage 4 confirms on a quiet machine that `store.write.sync` stays inside + the spread of the commit before this change on both engines, the same + baseline as decision 1, because decisions 12, 1 and 10 move the write path + first; if the variant does not achieve that, the plain queue is taken and + the slowdown stated in the reference. The figures go into the commit + message. + +**Why.** It removes findings 18 to 22, among them a stack overflow and an +event loop that never drains. MobX, Preact Signals, Vue and Svelte reach the +same design. It also makes an ordinary write faster, because every write now +takes one path: the write ratio goes from 2.69 to 2.21 on Bun and from 1.4 to +1.06 on Node. + +**What it changes for a user.** A synchronous subscriber of store A that +writes store B makes B current at once, and B's subscribers hear a round +later. Another subscriber of A in that round therefore reads the new B +through the store and the old B through an adapter. Today it reads the new B +in both. The reference says that adapter values of another store may lag +inside one delivery round. + +**Evidence.** `spike-delivery.md`, D1. 72 lines added, 36 removed. 16 tests +change: 13 fixes and 3 incidental. The queue costs 33 bytes; the bound and +its message 75 to 130 more as spiked, less with a code. Without the variant, +a direct write with a synchronous subscriber is about 85 nanoseconds slower +on Bun and 30 on Node. + +**Label.** Before 1.0: the order of calls changes, and what a removed or a +late subscriber gets goes into the spec as guaranteed. **Stage 4:** yes. + +### 14. A subscriber's error is caught and logged; the writer is never told + +**Decision.** Keep today's rule and write it into the spec: a subscriber's +error is caught, the other subscribers run, and the code that wrote is not +told. The rejection of an `async` subscriber is caught and logged in the same +way. The report itself is guarded: if `console.error` throws, as it does in +test setups that fail on console output, the round goes on and the writer +still is not told. + +**Why.** Every adapter is a synchronous subscriber, so the code that fails is +usually not the code that wrote. Throwing to the writer makes an unrelated +`store.count = 1` throw after the count has changed, hides a method's own +error and loses its return value. On the microtask path there is no writer +at all. The rejection handler makes the two ways a callback can fail land in +one place, for 25 bytes. Without the guard on the report, the rule is false +exactly where tests are strictest: a console that throws sends its error to +the writer and skips every later subscriber of the round, today and after +decision 13 alike. + +**Not taken.** Throwing the first error to the writer (Preact, Legend-State +3). `reportError()`, which ends a Bun process and only logs on Node. A +reporter the application can replace is an addition and can follow 1.0. + +**Evidence.** `spike-delivery.md`, D2: 1 test changes, a fix. The guard on +the report was reproduced as missing by `adversarial-edges.md`, objection 4, +and is not spiked; stage 4 writes its test first. + +**Label.** Before 1.0, as a line in the spec. **Stage 4:** yes. + +### 15. A setter is a transaction + +**Decision.** A class setter that writes two fields notifies a synchronous +subscriber once (finding 43). + +**Evidence.** `spike-delivery.md`, D3. 8 lines, 5 bytes. 2 tests change, both +fixes. + +**Label.** Before 1.0: one sentence in the reference. **Stage 4:** yes. + +### 16. `batch()` refuses a callback that returns a promise, by its type, and an `async` function when it runs + +**Decision.** + +- The parameter of `batch()` becomes a function whose result is not a + promise, with a type whose error message says why. +- At run time, `batch()` throws a `TypeError` with the code `batch-async` + when it is given a native `async` function, before the function is called, + in every build. It tells one by `Symbol.toStringTag` equal to + `'AsyncFunction'`, the test decision 22 uses, because a looser test + refuses the mock functions of the test runner; a test pins that a mock + function is accepted. +- The type of the parameter is not exported in 1.0. Exporting it later is + an addition. + +**Why.** `batch(async () => …)` groups only the writes before the first +`await` and hands back the promise as if it had worked. The type stops that +where it is written, for no bytes, but it cannot see an `async` function held +under a `() => void` type, a JavaScript caller or an `any`. Those keep the +silent split unless the function is checked when it arrives. The check runs +before anything is written, so nothing is half applied and no promise is +lost. Both refusals have to be decided now: accepting promises again after +1.0 would be a compatible change, and starting to refuse them would be a +breaking one. + +**What it costs a user.** `batch(() => { store.loading = true; return +save(); })` no longer compiles and is rewritten with the `save()` outside; at +run time it is accepted, because it is not an `async` function and it +batches everything it should. A wrapper generic over the result of `batch()` +needs a cast. An `async` function that a build step has turned into a +generator is not seen by the check. + +**Evidence.** `spike-delivery.md`, D4: the type is 7 lines and 0 bytes, and 3 +type assertions in 2 test files change; the check before the call is 10 +lines and 50 to 83 bytes as spiked, less with a code, and 2 tests change, both +fixes. `adversarial-edges.md`, objection 5, shows the three callers the type +does not see. + +**Label.** Before 1.0. **Stage 4:** yes. The reference also states the rule +for an `async` method: it is a transaction up to its first `await`. + +### 17. `subscribe()` stays batched by default + +**Decision.** No change (API question 1). The reference says at the top of +the `subscribe` section that the callback runs in a microtask and that +`{sync: true}` runs it before the write returns. + +**Why.** A direct property write has no unit that groups two fields, so the +microtask is what gives `store.a = 1; store.b = 2` and `Object.assign` one +call. A synchronous default would hand every caller of `subscribe()` the cost +only the adapters carry today (one call, and often one snapshot, per direct +write), and would turn the option of `persist`, `withHistory` and +`subscribeKey` around. + +**Evidence.** `spike-delivery.md`, D5, with the counts per case. + +### 18. Writes outside a method stay allowed, without a warning + +**Decision.** No change (API question 2, M32). `batch()` stays in the API. +A warning when a synchronous subscriber is called many times in one task +follows in 1.x (decision 36). + +**Why.** A direct write is a documented way to change a store, and the +ordinary one in an event handler: `store.count++`. A warning for it would +fire for correct code and could not be silenced, which decision 36 rules out +for every warning. What a direct write costs is one notification per write +on the synchronous channel, and `batch()` is the answer to that cost, so it +stays. + +## `persist`, `devtools` and `history` + +### 19. When hydration happens + +**Decision.** `persist()` restores before it returns when the storage is +synchronous. It awaits only a storage that returns a promise. There is no +option for it; `skipHydration` keeps its meaning. `hydrated` settles even +when the store cannot be snapshotted at the start of a read, and +`rehydrate()` keeps the `finally` that guarantees it. + +**Why.** A store on `localStorage` renders its defaults first today, and the +saved state a microtask later. The change is 15 lines added and 18 removed, +and `./utils` gets 6 bytes smaller. + +The handle exists before the first read starts, so a report made during it +can hand the handle to `onError` (decision 21). With `skipHydration` nothing +is read, and so nothing is saved, until `rehydrate()` is called (decision +21). + +**Two things the guide has to say.** + +- **Call `persist()` after the store is constructed, never inside a + constructor.** With the base class of decision 11 a constructor is a + natural place for it, and it is the wrong one: the field initialisers of a + subclass run after the restore and overwrite it, and under decision 2 they + count as edits, so the next save writes them over the stored record. Stage + 4 pins what happens with a test, so that the sentence stays true. The test + needs the base class, so it is written in the base-class step, not here. +- **On the client, `prepareStoreForHydration(store)` is called before + `persist(store)`** (decision 41). + +**Evidence.** `persist-devtools.md`, P1. 1 test changes, incidental: it +relies on the old timing. The constructor case is `adversarial-edges.md`, +objection 2, reproduced with a stand-in for the base class. The `hydrated` +gap is the spike's own note. + +**Label.** Before 1.0. **Stage 4:** yes. + +### 20. Dead and redundant code goes, in the commit that makes it dead + +**Decision.** + +- **Code that is dead today is removed first**, before the other changes: + the ten dead lines of the three core files in the form the type checker + accepts, the dead blocks of `persist.ts` (M54, finding 54), and the + redundant checks stage 1 listed in `equality.ts`, `history.ts` and + `collections.ts` (finding 59), each after a benchmark where it sits in a + loop. Only one sits in a loop: the object guard in `indexOfMember`, which + runs once per member. Before it goes, the core benchmark gains two rows, + `collection.has.primitive` and `collection.has.object`: `has()` of the + last member on a live `reactiveSet` of 1,000 numbers and of 1,000 objects. + The guard goes only if both rows stay inside the spread of the commit + before on both engines; otherwise it stays as a measured shortcut, and its + entry in the list of equivalent mutants gives the figures. The checks in + `equality.ts` and `history.ts` sit in no loop and go without a benchmark. +- **Code that a later change makes dead is removed in that change's + commit.** That holds for the per-field bookkeeping of a restore, which + decisions 22 and 23 make unreachable, and for `resumeScope()` in + `createClassyStore`, which decision 3 makes redundant. `CONSTRAINTS.md` + allows no unexplained surviving mutant in a target file, so dead code + cannot wait for a cleanup step. +- **The two traps of the React snapshot cache that proxy-compare cannot + reach** (finding 4) are removed if deleting them fails no unit test and no + React suite; otherwise each gets a test that reaches it. Deleting them + fails only two assertions of `snapshotTargetCache.test.ts`, which reach + the private copy through the cache itself; stage 1 added them for + coverage. They are tests of internal state and do not count. They go with + the traps, and the commit message names the assertions in the same file + that cover the public fact: a write and a delete through the tracking + proxy are refused. +- **The ternary in `activeTracker()` stays.** It looks dead and is on the + path of every read. It was timed alone after this entry was first written + (`own-code.md`, `c06`): without it a field read goes from 45.3 to 82.6 + nanoseconds on Node and from 31.9 to 59.2 on Bun, and the read ratio on + Node is 3.55, above its limit of 2.5. + +**Evidence.** `own-code.md`, `r5`: 8 lines added, 17 removed, 32 bytes +smaller, no test fails, typecheck passes. `persist-devtools.md`, "Seen on the +way". The claim about `activeTracker()` first rested on a patch that changed +several things at once; the timing alone, above, confirms it. + +**Label.** Can follow 1.0. **Stage 4:** yes. + +### 21. Nothing `persist` cannot use is skipped in silence, and nothing it could not restore is written over + +**Decision.** + +**A handle writes only after it has read.** Until its first read has +settled, a handle saves nothing: with `skipHydration` that is until the +first `rehydrate()`, and with a storage that returns a promise it is while +the first read is in flight. An edit made before then is kept in the store. +When the read restores a record, the edit wins for the field it changed, and +the result is saved. `save()` rejects before the first read has settled. +`clear()` works at any time. + +**A stored record that is read and not restored** is one of five kinds: + +| Kind | What it is | What happens | +| ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- | +| Nothing to keep | Not JSON; an envelope that is not an object; a `state` that is not a plain object; a version that is not a finite number of zero or more; an `expiresAt` that is neither a number, `null` nor missing; a record the library itself cannot restore, because it is nested too deep (decision 23) | Reported as `'parse'`. The next save replaces it | +| A lower version, no `migrate` | The documented way to drop an old format | Not used and not reported. The next save replaces it | +| From a newer version | Its version is above the configured one | Reported as `'parse'`. `migrate` is not called. The handle does not write while it is there | +| Not migrated or not merged | `migrate`, `merge` or a `deserialize` threw, or `migrate` or `merge` returned a thenable or something that is not a plain object | Reported as `'parse'`. The handle does not write while it is there | +| Not read | The read itself failed | Reported as `'read'`. It counts as no read, so the handle does not write | + +- **A handle that does not write** saves nothing: on an edit, when the page + is hidden, or on `save()`. An edit does not repeat the report. `save()` + reports as `'write'` and rejects with the error that `lastError` holds, + the report that stopped the handle from writing. A `rehydrate()` that + finds such a record again reports and rejects with that record's error. A + `rehydrate()` whose own read fails reports as `'read'` and rejects with + that error, as today. The handle writes again + after `clear()`, after a `rehydrate()` that restores a record, finds none + or finds one with nothing to keep, and when such a record, or the removal + of the record, arrives from another tab. `lastError` of the status holds + the report for as long as the handle does not write. +- **`onError` receives the handle as its third argument**, so that it can + call `clear()`. For a synchronous storage the first read runs inside + `persist()` (decision 19), and the report comes before `persist()` has + returned anything the callback could use. An error that `onError` throws + is logged with `console.error`; today it is swallowed. +- **When no `onError` is given, the report goes to `console.error`** with + its code, in every build. `onError` replaces that default. +- **What a report carries.** `onError(error, operation, handle)` receives + the value that was thrown when the library did not throw it: the storage's + error, the error of a `serialize`, `deserialize`, `migrate` or `merge`, or + the `SyntaxError` of the default `JSON.parse`. When the library refuses a + record or a call itself, `error` is an `Error` whose message carries one of + these codes (decision 35): `persist-invalid` for a record with nothing to + keep that parses, `persist-newer` for a record of a newer version, + `persist-not-plain` for a `migrate` or `merge` that returned a thenable or + a value that is not a plain object, and `persist-unread` for a `save()` + before the first read has settled. The default report is one + `console.error` call: its first argument is `@codebelt/classy-store +[persist-failed]: ""` and its second is the error. +- **Every failure of `save()` is reported as `'write'` and rejects with the + same error**, as today; that includes a `save()` before the first read has + settled. A call on a disposed handle rejects with `persist-disposed` and + is not reported, because after `dispose()` the handle reports nothing. +- **The version rule is one rule, on both sides.** A version is a finite + number, zero or above. A record with no `version` field counts as version + 0; any other value, `null` and `"2"` included, leaves nothing to keep. The + `version` option is checked when `persist()` is called (decision 22). +- **`migrate` is called only for a lower version**, and never as an `async` + function: a native `async` function is refused when `persist()` is called + (decision 22). If a `migrate` returns a thenable when it runs, a handler is + attached to it, so no rejection is left unhandled, and the record counts + as not migrated. +- **Expiry comes first.** A record whose time has elapsed is treated as + expired whatever its version, as the build that wrote it would treat it. + +**Why.** + +- One channel for every failure of a read, and a default for it. `onError` + is optional, and without a default a refused record is as silent as today. +- A handle that writes before it has read writes over a record it never + saw. That is what a handle with `skipHydration` does today on its first + edit, and `skipHydration` is the pattern the server-rendering guides + teach: a stored record is replaced by the defaults and one edit, and the + `rehydrate()` that follows reads the damage back. +- A record of a newer version is the data of a newer build of the same + application: another tab that has already updated, or a deployment that + was rolled back. Today `migrate` is called with it, and the next edit + writes the older build's state over it. +- A record that the application's own `migrate`, `merge` or `deserialize` + failed on is valid data that a corrected release can still read. Replacing + it at the next save turns a bug in one release into lost data for every + user who makes an edit. Not saving is the failure that can be undone; it + is reported, and the application can choose the other one with `clear()`. +- A record that is not a record, or that the library itself can never + restore, holds nothing a later release could use, and keeping it would + stop the store from ever saving again. A version raised with no `migrate` + is the documented way to drop an old format, and it stays silent. +- Awaiting an `async` `migrate` would put a turn between the read and the + apply, which is what decision 19 removes. Calling it and dropping its + promise would turn a silent skip into an unhandled rejection, which ends a + Node or Bun process. +- A version need not be an integer. The first draft demanded one, on the + record only: an application configured with `version: 1.1` would have + refused its own record after the upgrade. + +**What it costs a user.** + +- **With `skipHydration`, nothing is saved until `rehydrate()` has been + called.** An application that never calls it saves nothing, and only + `save()` says so, by rejecting. `isHydrated` shows the state. The guides + say today that `skipHydration` "does not delay writes"; that sentence is + reversed. +- **While a handle does not write, edits are not saved**, and if a later + `rehydrate()` restores a record, they are restored over. After a release + whose `migrate`, `merge` or `deserialize` fails for a stored record, that + user's state is not saved until a later release reads the record or the + application calls `clear()`. +- **After a rollback of a deployment**, a user whose record the newer build + saved cannot save on the older build until the newer one is back. +- **Two losses stay**, and the guide names both. A tab that read before a + newer build wrote, and does not sync, writes over the newer record at its + next edit: it cannot know. A `migrate` that returns a wrong result without + throwing is saved at the user's next edit. + +**How this entry got here.** Each of the three reviews found a way to lose +stored data in it, and it was rewritten each time before anything was +built: a silent skip without `onError`; an older build that wrote over a +newer record; advice to call `clear()` from a callback that had no handle; a +handle with `skipHydration` that wrote before it read. After the third +review the whole rule set was built once and run through 33 paths on today's +source, on the first combination of the `persist` changes and on the new +build. + +**Evidence.** `spike-persist-2.md`, on top of the combination of +`persist-devtools.md`: 98 lines added and 36 removed in `persist.ts` and +`persist.types.ts`. `./utils` adds 3,641 bytes, 245 more than that +combination. Of the 33 paths, the ones the reviewers raised now keep the +record: the rollback, `version: 1.1`, `skipHydration` over a newer record, +`clear()` from `onError` on both kinds of storage, a `merge` that throws, +and a `migrate` that returns `null` or a rejected promise. 48 tests change: +14 of that combination's 15; 24 that use `skipHydration` as a set-up and +save before any read, incidental; 2 that pin `save()` replacing a record it +never read, fixes; 3 that pin the read winning over an edit made before +`rehydrate()`, changed by decision; and 5 that check the arguments of +`onError`, incidental. The typecheck shows the type test of the two-argument +`onError`. Three parts are decided here and not in that build: a record +nested too deep has nothing to keep (the build keeps it, and the handle then +never saves again); the removal of the record in another tab lets a handle +write again; and the stamp of decision 24 only for a finite `expireIn`. Not +run: a real `pagehide`, a real second tab, the browser suites. + +**Label.** Before 1.0. **Stage 4:** yes. + +### 22. `persist()` validates its options when it is called + +**Decision.** `persist()` throws a `TypeError` with a code, before it reads +or writes anything, for: a prototype key, a getter or a method named in +`properties`; a transform that is half written; a `version` that is not a +finite number of zero or more; and a `migrate` that is a native `async` +function. + +**Why.** These are mistakes in the application's own code, at a boundary the +library owns. Today each is accepted and then does the wrong thing later. +Checking the version and `migrate` here, once, means neither is ever found +out record by record, where the cost would be a user's stored data. + +**Evidence.** `persist-devtools.md`, P3: 82 bytes, 5 tests change, 4 fixes +and 1 incidental. The checks of `version` and `migrate` were built in +`spike-persist-2.md`: 56 bytes. A native `async` function is told by its +`Symbol.toStringTag`, named exactly, because a looser test refused the mock +functions of the test runner. + +**Label.** Before 1.0. **Stage 4:** yes. + +### 23. A restore is all or nothing + +**Decision.** A restore copies every value first, writes them in one +transaction, checks that the result can be snapshotted, and rolls back if it +cannot. A nested `__proto__` key is dropped. A record whose restore was +rolled back, or that is nested too deep to copy, has nothing to keep +(decision 21): it is reported, and the next save replaces it. + +**Why.** Today a deeply nested record restores and then makes every snapshot +and every save throw, so it is never replaced. No release can restore such a +record, so keeping it would only stop the store from saving for good. + +**What it changes for a user.** A synchronous subscriber is told once, after +the whole record is in, where today it is told once per field and can edit +another field in between. The persist tutorial describes today's behaviour, +and that sentence changes in the same commit. + +**Evidence.** `persist-devtools.md`, P4. 74 bytes. 1 test changes, a fix. + +**Label.** Before 1.0, for the documented sentence. **Stage 4:** yes. + +### 24. A pending save is written when the page is hidden, and nothing is written back at load but an expiry stamp + +**Decision.** + +- A debounced save that is still waiting is written when the page is hidden + (`pagehide`). +- **A migrated record is not written back at load.** The first save writes + it, as today. +- **One thing is written back at load:** a record of the configured version + that has no `expiresAt`, or `null`, read by a handle whose `expireIn` is a + finite number, is saved again with an `expiresAt`, through the ordinary + save path and its debounce. Its state and its version are unchanged. +- A record that arrives from another tab is never written back. + +**Why no write-back after a migration.** The first two drafts wrote a +migrated record back at once, so that the migration would not run again on +the next load. The third review showed what that opens (objection 4 of +`adversarial-3.md`). A `migrate` that is wrong and does not throw would +replace the source record for every user who opens the release, edit or no +edit, where without the write-back a user who only looks keeps the old +record. And after a rollback, every user who merely opened the newer build +would have a record the older build must not write over. Running a +`migrate` once more per load costs nothing next to either. + +**Evidence.** `persist-devtools.md`, P5, for the `pagehide` flush: no test +changes; a real page unload was not tested, and stage 4 tests it in the +browser suite. `spike-persist-2.md` for the rest: a migrated record is kept +until the first edit (paths 2 and 4), and a record without `expiresAt` is +written once with one (path 10b). With `expireIn: Infinity` that build +writes the record again on every load, which is why the stamp is for a +finite `expireIn` only; that last part is not built. No test pins either +write-back today; stage 4 writes both. + +**Label.** Before 1.0: the persist tutorial says that hydration does not +rewrite storage, and the stamp is an exception to that sentence. **Stage +4:** yes. + +### 25. Cross-tab sync ignores an event from another storage area + +**Decision.** The narrow form: an event whose `storageArea` is another area +is ignored when `storage` is a `Storage`. An event without `storageArea` is +still accepted, because only a script can make one, and a script on the page +can write to the storage directly. + +**Evidence.** `persist-devtools.md`, P6. 24 bytes. No test changes. + +**Label.** Can follow 1.0. **Stage 4:** yes. + +### 26. `persist` options stay as they are + +**Decision.** No option is renamed, removed or made optional. `storage` +stays required: making it optional later is an addition, and a default of +`localStorage` would add a new silence where it is missing. `clearOnExpire` +stays. One callback gains an argument: `onError` receives the handle as its +third (decision 21). A callback written for two arguments still fits. + +**Why.** An earlier draft removed `clearOnExpire` and always cleared an +expired record. That was reasoned, not spiked, and it would delete data in +two cases nobody ran: a handle without `expireIn` reading a record another +handle stamped, and a device whose clock runs ahead on shared storage. A +tidier option list is not worth a deletion that was never tested. + +**Label.** No change. + +### 27. `devtools` + +**Decision.** + +- **Entries.** `devtools` subscribes on the synchronous channel. A store + method sends one entry, named after the method, when the outermost call + returns, with one snapshot. Direct writes outside a method send one + `STORE_UPDATE` entry per task, from a microtask. So the synchronous + channel costs one snapshot per outermost method and never one per direct + write. +- **How the name reaches `devtools`.** The core holds one place for a + function, empty unless `devtools` is connected, and nothing else. + `devtools()` fills it while at least one connection is open and empties it + when the last one is disposed. A method call tests it; when it is empty + the call is today's code. The naming itself lives in `devtools.ts`. This + is the "hook" form of the spike, not its "slot" form, which keeps a counter + and the naming in the core. +- **The name is the key.** The key a method was first read under is handed + to that function with the call, for a method of a class and for one held + in a field alike. The function's own `name` is not used: it is empty for an + arrow function assigned in a constructor. There is one method per object + and function, so a function held under two keys has the name of the key + that was read first: after `store.b = store.a`, a call of `store.b()` is + named `a`. +- **Time travel.** A jump replaces the state exactly, in one transaction, + without calling setters. A jump to an entry this session sent restores the + snapshot that was sent, so a `Date` stays a `Date`; a jump the extension + sends as JSON restores data. +- **Messages.** `RESET`, `COMMIT`, `ROLLBACK` and `IMPORT_STATE` are handled. + A jump that the shared restore refuses, because the root fails its check + (decision 30), writes nothing: `devtools` catches the `restore-locked` + error and logs it with `console.error`, and the extension's panel shows + the entry it jumped to until the next entry arrives. +- **Options.** `devtools(store, options)` takes `name` and `enabled` as + today, and five options of the extension that the build passed to its + `connect()`: `maxAge`, `trace`, `traceLimit`, `actionsDenylist` and + `actionsAllowlist`. `maxAge`, 50 by default as in the extension, also + bounds how many sent snapshots this session keeps for exact time travel. + The list is named, not an index signature, so a misspelt option is a type + error. Their bytes are inside the figures of decision 4. +- **`enabled` defaults to on only where `NODE_ENV` can be read and is not + `production`.** It reads the environment the way decision 36 does. Where + there is no `process` to read, the default is off: a bundle in which + nothing replaced the expression must not hand every state to an extension + because of it. `enabled: true` turns it on anywhere. The guide names the + builds in which the default is off, and says that the extension receives + every state, so a store with secrets passes `enabled: false`. +- **Computed values.** A snapshot no longer lists class getters (decision + 43), so `devtools` adds the values of the root store's class getters to + what it sends, each read guarded. Decision 43 has the details, the cost + and the limit: a getter of an object literal that throws still loses the + entry, as today. + +**Why.** Every entry is named `STORE_UPDATE` today, which makes the tool's +list useless, and a jump adds unknown fields, never deletes missing ones and +calls setter-only accessors. The default changes because DevTools on a +production page hands the whole state to any extension that asks, and a +default cannot be changed after 1.0. + +The hook form answers objection W17. The first draft's hook ran on every method +call of every user, `devtools()` or not, and cost 5 to 6% of a method call +on Node. With it a method call without `devtools` is inside the spread +of today's on both engines, and the main entry carries 12 bytes for it, not +20. + +**What it costs a user.** While `devtools` is connected, a method call +allocates one closure. An application that loads `./utils` twice, once as +ESM and once as CommonJS, and connects `devtools` from both has one copy's +names fall back to `STORE_UPDATE`; that was read from the code, not run. + +**Evidence.** `persist-devtools.md`, P7: 403 bytes on `./utils`, and no test +changes, because stage 1 added none for `devtools`; stage 4 writes them +first. `spike-combos.md`, K2, the hook form (`k2-hook-on-p7.patch`): 12 bytes on +the main entry and 452 on `./utils` with P7, 1,341 tests pass, +`store.method` timed in five rounds on each engine against today's and +against P7. That patch reads the function's own `name`; passing the key was +not built, and stage 4 tests an entry for an arrow function written to a +new key and for one assigned in a constructor first. Not +verified: the entry ids the Redux DevTools extension sends back. + +**Label.** Before 1.0. **Stage 4:** yes. + +### 28. An edit made in the same tick as `undo()` is recorded + +**Decision.** `withHistory` drops its `restoring` counter and runs undo and +redo as one transaction each. An edit made in the same tick as `undo()` or +`redo()` is then recorded like any other (findings 57 and 58). + +**Evidence.** `persist-devtools.md`, P8. `./utils` 24 bytes smaller. 1 test +changes, a fix. + +**Label.** Before 1.0: the history guide describes today's behaviour, and +that sentence goes. **Stage 4:** yes. + +### 29. `withHistory` restores a function held in an own field, by reference + +**Decision.** Undo removes a function that was added to a field and puts +back one that was replaced, by reference (finding 60, M59). Methods on the +prototype are untouched, as today. + +**A restore from outside never touches a function field.** A DevTools jump +that the extension sends as JSON carries no functions. The shared restore +neither deletes nor writes a function field for such a state, so a jump +cannot remove the arrow methods or the callbacks of a store. Only a state the +library recorded itself restores function fields, by reference. + +**Why.** It follows from decision 1. A snapshot holds each function as it +was written, so a recorded entry has the value to put back, and history +records the field, so it has to restore it. After the restore a read through +the store hands out the same method as before, because there is one method +per object and function. + +**Evidence.** The write-back was run on the form of decision 1 that is now +taken (`spike-functions-2.md`, the rows of `restore-fn.ts`): a callback whose +key was deleted is written back by assignment and by a definition, and the +snapshot holds the callback itself both times. Under the second form of +decision 1 it came back wrapped, which was objection 6 of +`adversarial-2-core.md`. The change in `history.ts` itself was not built: +undo skips functions on every build today. Stage 4 writes the tests first +and stops if the change turns out larger than a few lines there. The tests +cover a callback that is replaced, a callback whose key was deleted, a +function field that held another function at the time of the undo, and a +jump by JSON on a store whose methods are own fields. + +**Label.** Before 1.0. **Stage 4:** yes, after decision 1. + +### 30. Undo and time travel change a nested object in place + +**Decision.** A restore goes down while both sides are containers of the +same kind and writes only what differs. Where a restored value is the +snapshot of an object that is still live, the live object is put back. Undo, +redo and a DevTools jump share that one function (M60). The function enters +each live object at most once per restore, and treats the recorded root as +the store, so a store that refers to itself is restored like any other. + +**A container that would refuse the restore is replaced, as today.** Before +an object is restored in place, one check asks whether every write the +restore would make there is allowed. A key to add to an object that is not +extensible, a read-only key whose value differs, and a key that cannot be +deleted each fail it. The check counts only the writes the restore will make: +a function field that a state from outside does not carry is not a key to +delete (decision 29), so a jump by JSON on a sealed store whose methods are +own fields does not fail it. The spike's check was written before that rule +and counts such a key; stage 4 tests the jump first. The object is then +replaced at its parent by a copy. The root cannot be replaced: when the root +fails the check, the restore throws a `TypeError` before it writes anything, +and the history does not move. + +**Why.** + +- Today a restore replaces a changed branch with a copy. After undoing an + edit to one row, every row of the list is a new object, every row + component renders again, and a row the caller held is detached. +- It is worse for a store that holds other stores, which decision 11 makes + ordinary. After one undo every row is a frozen snapshot: a prototype + method on it throws, and an arrow method writes the old store. +- It is faster. Undo of one row in 1,000 goes from 2,315 microseconds to + 273 on Bun, and 999 row snapshots are kept. +- Entering each object once answers objections W1, C1 and E9. With decision + 44 in the same build and no such mark, every restore that reached an + object on a cycle overflowed the stack, left the store half restored and + moved the history pointer all the same. + +The check answers objection 4 of the second review. Decision 5 keeps the +children of a container that is frozen through the store, and decision 2 +keeps that freeze silent, so no history entry records it. Without the check +an undo into such a container was refused part-way: the store was half +restored, its one notification carried the half state, and the history had +moved. Today the same undo works, because it replaces the branch. + +**An object that has moved or is shared.** The restore follows the object, +not the place it was recorded in (objection E8). An object that was in the +store when the entry was recorded and is still live is put back and restored +in place, wherever else it now sits. If it is also part of another store, it +is one object there too: that store sees the restore, and its subscribers +are told once. So an undo in one store can take back an edit that was made +through another. The history guide says it: a history records one store, an +object two stores share is undone in both, and a move between two stores is +undone by a history on a store that holds both. Today an undo puts a copy in +place of a shared object, which ends the sharing without a word. + +**What it costs a user.** A container that was locked after the entry comes +back as a new copy without the lock, child objects included, so a reference +to the old container no longer points into the store. That is today's +behaviour for every restored branch. + +**What stays.** A DevTools jump that the extension sends as JSON restores +data, not class instances. The guide says so. + +**Evidence.** `spike-classes-2.md`, V4: 80 lines added, 48 removed, 113 bytes +on `./utils`. `spike-combos.md`, K1, on a build with V4 and decision 44: 5 +lines in `cloneSnapshot.ts`, 16 bytes on `./utils`, no test changes beyond +those of the two decisions. Six stores with a cycle were undone, redone and +jumped back: all return, each object is the one that was made, and each undo +notifies once. An undo of 1,000 plain rows is inside the spread with the mark +(264 microseconds against 263); 1,000 rows that point back to their store +take 1.9 milliseconds, which is decision 44's cost, not the restore's. The +addendum of that report ran four cases of an object that moved to another +store or is shared by two, on the same build and on the unmodified source. + +`spike-core-3.md`, G3, on that same build: 44 lines in `cloneSnapshot.ts` +and 5 in `history.ts`, 211 bytes on `./utils`, no test changes. Seven kinds +of locked container that threw part-way now return with the recorded values +and one notification. A frozen root throws with nothing written and the +history unmoved, where today it throws with the history moved. The six rows +of K1 and the four of the addendum give the same output. The 1,000-row undo +is inside the spread, with medians 5 to 8% higher. Not timed on Node. Not +run: a DevTools jump on a frozen root. + +**Label.** Before 1.0: the reference says "changed fields are replaced with +mutable copies". **Stage 4:** yes, on top of decision 27. Its tests are the +six rows of K1 for undo, redo and a jump, the four rows of the addendum and +the ten rows of G3. + +### 31. `subscribeKey` + +**Decision.** + +- A selector form, an equality option and an immediate first call (M62) are + additions and are not part of 1.0. +- It stops taking a snapshot of the whole store on every notification (M61). + It reads the live value, and takes a snapshot of that one node only when + the node or its version changed. The callbacks and their values are the + same in every case that was run; a key beside 1,000 rows goes from 113 + microseconds to 0.45 on Bun and from 49 to 0.78 on Node. 21 lines, 62 + bytes on `./utils`, no test fails (`spike-snapshots.md`, N5). Can follow + 1.0. **Stage 4:** yes. + +## Snapshots + +### 43. A snapshot carries class getters on one derived prototype per class + +**Decision.** A class getter is no longer an enumerable own accessor of +every snapshot (API question 3, M33). For each class that has getters, one +object that inherits from the class prototype is made once, with one +memoizing accessor per getter, and snapshots of that class are created from +it. Inside a snapshot getter `this` is the frozen snapshot behind a tracker, +so it has the store's keys, and the class as its constructor and for +`instanceof` (findings 31 and 41, M34). Its prototype is the derived object, +not `Class.prototype`. A getter on an object literal stays an own accessor, +listed where the store lists it (finding 70). + +`devtools` adds the values of the root store's class getters to what it +sends, each read guarded, so a class getter of the root that throws shows +its error text and the entry is still sent. Nested objects are sent as they +are. The guard goes no further than that: a getter of an object literal is +an own accessor of the snapshot, the extension's serialiser runs it, and one +that throws still loses the entry, at the root or below it, as today. + +**Why.** + +- No compared library lists a class getter among the own enumerable keys of + a copy. Today `Object.keys(store)` and `Object.keys(snapshot(store))` + differ, and a spread or a `JSON.stringify` of a snapshot runs every getter + and throws if one does. A DevTools entry is serialised the same way, so + today one class getter that throws spoils the entry. +- It is the only form that also removes a cost on the path every write in + every adapter takes: a snapshot of a class with eight getters is four + times faster to make and holds sixteen times less memory. +- It lets the snapshot's `this` match the store with no filtering, and it + drops the own key a class setter gets on a snapshot today. + +**What it costs a user.** + +- A spread or a serialised snapshot no longer carries computed values; they + have to be named. Nothing reports it: `{...snap}.total` still type-checks + and is `undefined`, as it is for any class instance in TypeScript. Every + compared library behaves this way, and the cost is taken on purpose + (objection C10). The tutorial documents today's behaviour, so the + paragraph changes, and the changelog names it. +- `Object.getPrototypeOf(snapshot)` is no longer `Class.prototype` for a + class with a getter. `instanceof` and `constructor` are unchanged. The + reference's "keep the class prototype" becomes "are instances of the + class". +- A snapshot of a reactive collection no longer lists `size` in + `Object.keys` or JSON. `snap.size` reads as before. +- The DevTools panel no longer shows the getter values of a nested store or + a nested class instance, only those of the store `devtools()` was given. + Showing them needs a walk and a copy of every object on the way for every + entry. It can be added in a 1.x release. + +**Not taken.** Own accessors that are not enumerable: one line, the same +visible change for `Object.keys` and JSON, none of the gain in time and +memory, and `this` then needs a filter to match the store. Keeping today's +shape, which no report supports. + +**Evidence.** `spike-snapshots.md`, N2, form A with S1 of the trap spikes. +122 lines added, 58 removed, in five files; 239 bytes. 14 tests change with +S1: fixes, except that the eight tests of today's shape change by decision. +`persist` saves the same fields as before. The base class of decision 11 +gets a correct snapshot on top of it, in one build. `spike-combos.md`, K3, +for `devtools`, on a build with this decision, decision 44 and the entries +of decision 27: 29 lines in `devtools.ts`, 95 bytes on `./utils`, no test +changes. A jump that carries the added keys back restores the fields and +adds no key. Not run: the real Redux DevTools extension. + +The 239 bytes and the 14 tests are those of the spike, which was built on +today's snapshot layer. Decision 10 changes that layer first, and the two +patches do not apply on each other, so both figures are a forecast and stage +4 takes its own from its own build. + +**Label.** Before 1.0. **Stage 4:** yes. The React tracking path is where +the risk is: a tracked read and a plain read have to share one cached +result. + +### 44. A snapshot keeps a cycle + +**Decision.** `snapshot()` of a store that refers to itself returns a frozen +snapshot with the same cycle in it, where it throws today (finding 8, M36). +The React hook, `withHistory` and `cloneSnapshot` are made safe for it. + +**Why.** Today the write that closes a cycle succeeds and the store can then +not be read by any adapter. Refusing that write would need a walk from the +new parent to the roots on every assignment of an object, and would also +have to reject a cycle already in the object given to `createClassyStore()`, +which works on the live side today. + +**What it needs.** The restore of decision 30 walks into live objects, and +on a cycle it has to stop. The two were first spiked apart. Built together, +an undo overflowed the stack; with the mark decision 30 now carries, it +returns. The line this decision's spike added to `history.ts` moves into the +restore function that undo, redo and a DevTools jump share. + +**What it costs a user.** Everything on a cycle gets a new snapshot on every +write to any of it, so a model with parent pointers loses structural sharing +for what the pointers connect. The docs say so and name the alternatives: +hold the parent's id, or hold the parent in an object the store does not +proxy. `JSON.stringify` of such a snapshot throws, as for any cycle, and +`persist` reports it through `onError`. In the DevTools panel, a class store +with a getter and a cycle shows its root once more under the field that +points back, because what `devtools` sends for such a store is a copy +(decision 43). + +**Evidence.** `spike-snapshots.md`, N3. The main entry is 9 bytes smaller, +`./utils` 21 larger, `./react` 30 larger. 7 tests change, all of them +asserting the throw. The guard costs a tracked comparison 14 to 29 +nanoseconds on data without a cycle. Not checked: what the Redux DevTools +extension does with a cyclic state. + +**Label.** Before 1.0: it reverses a documented sentence. **Stage 4:** yes. + +### 45. Snapshot types: tuples stay tuples, and a collection snapshot has no mutators + +**Decision.** + +- `Snapshot<[string, number]>` is `readonly [string, number]` (finding 14, + M41). +- `Snapshot>` and `Snapshot>` are two + exported types, `ReactiveMapSnapshot` and `ReactiveSetSnapshot` + from `./collections`, with the queries and the iterators and without + `set`, `add`, `delete` and `clear`. Calling a mutator on a snapshot, through a + tracking proxy, or on a collection its owner froze throws a `TypeError` + with the code of decision 35 (finding 16, M42). +- The backing arrays `_entries` and `_items` stay public, read-only in the + snapshot types (finding 15, M43). The docs say that writing to them + directly, on a live collection, is unspecified: use the methods. + +**Why.** A snapshot is frozen, so a mutator in its type promises something +that throws. One case is worse than a throw today: `add()` on a set that its +owner froze and placed in a store pushes to the raw array and tells no one. +The backing arrays stay because the repository's own Next.js example reads +them from snapshots in four components, and hiding them is a migration with +nothing behind it. + +**A subclass of a reactive collection** works at run time, and its own +members are not in its snapshot type in 1.0: `Snapshot` is the snapshot +type of the collection it extends. A way for a class to name its snapshot +type is an addition and can follow. + +**Evidence.** `spike-snapshots.md`, N4. No unit test changes. Type tests in 3 +files change, all fixes. `./collections` grows by 55 bytes with a short +message. + +**Label.** Before 1.0: public types. **Stage 4:** yes. + +### 46. A snapshot after one row changes still rebuilds the list + +**Decision.** Not changed in 1.0 (finding 2, M35). Recording which keys +changed and rebuilding only those is correct and can follow in a 1.x +release. + +**Why.** On Node it makes a snapshot after one of 1,000 rows changes three +times faster. On Bun, and so most likely in Safari, it gains nothing at that +size, because freezing a new 1,000-element array costs about 80 microseconds +there by itself. It costs 270 bytes, for arrays only. Decision 37 already +removes the worst case for three of the five adapters without it. + +**Evidence.** `spike-snapshots.md`, N1: no difference in 120,000 compared +snapshots; 8 tests and 9 type errors, all of which read an internal map. + +**Label.** Can follow 1.0. **Stage 4:** no. + +## Adapters and collections + +### 37. The Vue, Angular and Solid adapters build the snapshot when it is read + +**Decision.** In these three adapters the listener only marks the value as +changed, and the snapshot is taken at the next read (M63). + +**Why.** Every adapter takes a snapshot inside its listener today, so a loop +of direct writes takes one snapshot per write. With the change, 2,000 direct +row writes followed by one read go from about 650 milliseconds to 2.4 in each +of the three. React and Svelte cannot defer in this way, because their +contracts hand the value to the framework at once; for them the answer is +`batch()`, which the guides name. + +**Evidence.** `adapters-collections.md`, A1. 34 to 44 bytes per entry. 1 test +changes, incidental: `isShallow` on the Vue ref. + +**Label.** Before 1.0 for Vue: the reference says the adapter returns a ref +"backed by `shallowRef`", and it becomes a custom ref that `isShallow()` can +tell apart. The sentence changes in the same commit. Can follow 1.0 for +Angular and Solid. **Stage 4:** yes. Each adapter change runs its +framework's packed-app and browser suite, which the spike did not. + +### 38. Vue: no listener is left by a server render, and the ref is read-only + +**Decision.** On the server the Vue adapter subscribes to nothing and reads +the store at every read. The returned ref is typed +`Readonly>>`, and a write to it throws a `TypeError` with the +code `vue-readonly`. The adapter is on the server when it runs inside a +component and `inject(ssrContextKey, null)` is set, which is so exactly +inside `renderToString`; that is the test the spike ran. Today's check for an +active effect scope stays, and comes first. + +**Why.** Vue does not dispose component scopes during a server render, so a +store that outlives the request gains one listener per render (M64). The fix +stage 2 proposed, subscribing in `onMounted`, removes the leak and breaks +something else: a store written in `onServerPrefetch`, Vue's own way to load +data on the server, then renders its old value. Reading at the read removes +the leak and keeps that write. A snapshot is frozen, so a writable ref +promises something the value cannot do (finding 17, M65). The spike made the +setter do nothing, which is a silent failure for a template or a JavaScript +caller; a throw is the loud form. + +**Evidence.** `adapters-collections.md`, A2: 0 listeners after three server +renders against 1, 2, 3, and the `onServerPrefetch` write still renders. The +type was not compiled against Vue 3.2.0, the floor of the peer range; stage 4 +does that first. The throwing setter is not spiked. + +**Label.** Before 1.0, for the documented return type. **Stage 4:** yes, in +one change with decision 37 for Vue. + +### 39. Angular: a store write inside a `computed` is not lost, and `injectClassyStore` takes an injector + +**Decision.** The adapter updates its signal inside `untracked()`. +`injectClassyStore(store, {injector})` works outside an injection context. +The adapter checks for an injection context itself and throws its own error, +with the prefix and the code `angular-no-context`, in every Angular build; +the same code covers a context that is already destroyed, which today's +message reports. The type of the options object is not exported in 1.0. + +**Why.** Today a store write made while a `computed` runs makes Angular +throw inside the listener; the core logs it and the signal stays stale until +the next write (M66). The option is an addition, and is cheapest to add +while the signature is being written down for 1.0 (M67). The spike called +Angular's own assertion, whose message names the function only in Angular's +development mode; in a production build it is a bare `NG0203`. + +**Evidence.** `adapters-collections.md`, A3. 19 bytes for the fix, 51 more +for the option and the message. The library's own check is not spiked. + +**Label.** The fix: can follow 1.0. The option: an addition. **Stage 4:** +both. + +### 40. The adapter names stay + +**Decision.** No adapter is renamed (API question 7, M68). The Solid adapter +keeps `useClassyStore`. + +**Why.** Two reports lean towards `fromClassyStore` for Solid, because the +adapter behaves like Solid's `from()` and `use*` there usually means a +context lookup. The Solid report disagrees: the function has to be called +under an owner and returns an accessor, which is what a Solid user expects +of it. Where the precedent is split, a rename is a cost with no behaviour +behind it: eleven files and every Solid import. The name is also the one a +user of the React or the Vue adapter already knows. The same reasoning keeps +`isEqual` (decision 41). + +**Also.** The Svelte guide gets a section on runes (M69) and names its +example value `snap`, not `state`. + +### 41. React: `prepareStoreForHydration` stays an explicit call + +**Decision.** The server snapshot is not captured automatically (M70). The +equality option keeps the name `isEqual` (M71). The guide says that on the +client `prepareStoreForHydration(store)` is called before `persist(store)`. +`REACT_SSR.md` already says that it captures the snapshot "before +persistence or other live updates begin"; the change of decision 19 names +`persist()` there, and the persist tutorial gains the same sentence. + +**Why.** + +- Both automatic forms were built, and both break the pattern the guide + teaches: create the store, load the request's data, then render. The + capture fires on the first load write, so the server renders the empty + store, and a later explicit call cannot undo it. A store that refers to + itself throws on its first write or cannot be created. Memory grows by 19 + megabytes per 100,000 rows. 12 and 20 tests fail, all regressions. +- With decision 19, a store restored by `persist()` holds its saved state + when `persist()` returns. Prepared afterwards, it would capture that state + and not the one the server rendered. Hence the sentence in the guide. +- React's own `useSyncExternalStoreWithSelector` calls the parameter + `isEqual`. Zustand and Jotai say `equalityFn`. A breaking rename for a + split precedent is not worth it. + +**Evidence.** `adapters-collections.md`, A5. + +### 42. Reactive collections: one membership rule now, an index for snapshots, native `Map` and `Set` stay opaque + +**Decision.** + +- **One membership rule** (findings 33 and 34, M39). `-0` and `+0` are one + key, as in a native `Map`, and a collection constructed from a raw object + and its proxy holds it once. +- **Membership is by identity for every member**, as today: a raw object, + its proxy and each of its snapshots are one member. That is what keeps a + selection that was made with one snapshot of a row true for the next. The + price is that a collection cannot hold two snapshots of one object as two + members: the second `add()` changes nothing, and the guide says so. A list + in a store does not work this way (decision 6). +- **A snapshot of a collection answers `has()` and `get()` from an index** + (M40), built on the second lookup. A read through the tracking proxy of + the React hook without a selector still scans, because the tracker has to + see what was read. +- **No index beside the live array in 1.0.** It is 100 times faster on a hit + and costs 339 bytes, and it answers wrong after a write to the raw backing + array, which today's scan gets right. Decision 45 keeps the backing arrays + public and says that writing to them directly is unspecified, which leaves + room for it later. +- **Native `Map` and `Set` stay opaque** (API question 5, M38), and + `reactiveMap` and `reactiveSet` stay separate classes. No library has a + frozen native `Map`: one can still be written through `Map.prototype.set`. +- **Three adapters drop their `active` flags** once decision 13 is in, + because the core then skips a removed subscriber: Vue, Angular and Svelte. + They go in the adapter step of the order, not in the commit of decision + 13: the adapter files are not mutation targets, so nothing in + `CONSTRAINTS.md` fails in between, and each adapter change runs its own + framework's suites once. + Solid keeps its flag, which under decision 37 decides what the accessor + returns after disposal, and Angular keeps its `destroyed` check. + +**Evidence.** `adapters-collections.md`, A6 and A7. The membership rule: 13 +bytes, and the 2 tests that pin findings 33 and 34 change. The snapshot +index: plain lookups among 10,000 members go from 160 to 525 microseconds to +under 0.1, and `./collections` grows from 727 to about 843 bytes. A tracked +lookup was not timed. + +**Label.** The membership rule: before 1.0, because the collections guide +documents today's `-0`. The index: can follow 1.0. **Stage 4:** both, and +the flags in the adapter commits that follow decision 13. + +## Diagnostics + +### 35. Every error carries a stable code, and throws the same in every build + +**Decision.** An error or a logged report from the library reads +`@codebelt/classy-store [code]: facts`, where the code is a short string such +as `getter-cycle` and the facts are the names the user wrote. The advice +that goes with each code is on one page of the documentation. Codes are +stable from 1.0: renaming one is a breaking change, adding one is not. No +error subclass and no `code` property are added. No check throws in one +build and not in another. + +**One prefix.** Every message starts with `@codebelt/classy-store`, the +adapters' too; the code says where it comes from. Today the Vue and Solid +messages start with their entry point and the Angular one has no prefix. + +**The codes of 1.0.** Nineteen. A report made in every build is written with +`console.error`; the one development-only report with `console.warn` +(decision 36). + +| Code | Thrown or logged by | When | Decision | +| -------------------- | ------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | -------: | +| `getter-cycle` | A read of a getter, on the store or a snapshot | Getters read each other in a cycle. Facts: the path | 10, 35 | +| `not-a-store` | `snapshot`, `subscribe`, `subscribeKey`, `prepareStoreForHydration`, every hook and adapter | The argument is not a store | 35 | +| `getter-write` | A getter, on the store or a snapshot | It writes to the object it is computed on. Facts: the field | 10 | +| `delivery-loop` | Logged where a subscriber's error is logged | Delivery reached 100 rounds | 13 | +| `batch-async` | `batch` | The callback is a native `async` function | 16 | +| `frozen-collection` | The mutators of `ReactiveMap` and `ReactiveSet` | Called on a snapshot, through a tracking proxy, or on a collection its owner froze | 45 | +| `persist-option` | `persist()`, before it reads or writes | A key in `properties` that is a prototype key, a getter or a method; a half-written transform; a `version`; an `async` `migrate` | 22 | +| `persist-invalid` | A `persist` report, `'parse'` | A stored record that parses and has nothing to keep | 21, 23 | +| `persist-newer` | A `persist` report, `'parse'` | A stored record of a newer version | 21 | +| `persist-not-plain` | A `persist` report, `'parse'` | `migrate` or `merge` returned a thenable or a value that is not a plain object | 21 | +| `persist-unread` | A `persist` report, `'write'`, and the rejection of `save()` | `save()` before the first read has settled | 21 | +| `persist-disposed` | The rejection of a call on a disposed handle | The handle was disposed | 35 | +| `persist-failed` | The default `persist` report, without `onError` | Any report; the error is its second argument | 21 | +| `restore-locked` | `undo()`, `redo()`, and a DevTools jump | The root of the store fails the check of the restore | 30 | +| `vue-readonly` | A write to the ref the Vue adapter returns | Always | 38 | +| `vue-no-scope` | The Vue `useClassyStore` | No active effect scope | 35 | +| `solid-no-owner` | The Solid `useClassyStore` | No live owner | 35 | +| `angular-no-context` | `injectClassyStore` | No injection context and no `injector`, or a destroyed context | 35, 39 | +| `lost-write` | Development only, logged once | A field of the raw object changed without a write through the store. Facts: the field. Only if decision 36's check lands | 36 | + +Not reports of the library, and logged as they are: a subscriber's error and +the rejection of an `async` subscriber (decision 14), an error that +`onError` throws (decision 21), and a status listener's error. + +**Today's messages get their codes in one commit**, step 2 of the order: +`getter-cycle`, `not-a-store`, `vue-no-scope`, `solid-no-owner`, +`angular-no-context` and `persist-disposed`. The snapshot's `circular +reference detected in snapshot` gets no code: decision 44 removes that throw +before 1.0, so no user would ever see a code for it, and the page never +lists a code that 1.0 does not have. Every later commit that adds a message +adds its code and its line on the page. + +**Why.** + +- Message text is where the bytes are. Of the 625 bytes the first-wave + changes add to the main entry with their messages as written, 271 are + text. About 100 of those belong to messages this document keeps, and a + code with the names saves them with no build split at all; the rest + belonged to refusals that are not taken. A split saves no more on + messages. +- A program that fails in production and not in development, or the other + way round, is worse than either. So the bound on delivery rounds, the + check for a cycle of getters on a snapshot (decision 10) and the handling + of a cyclic store in `snapshot()` (decision 44) stay in every build. +- The messages the library has today get codes at the same time, because + tests and users match on that text and it should change once. +- Codes are named subject first, then what went wrong, in the form of the + four that were named first. A `persist` record has three codes, not one, + because what happens next differs: a record with nothing to keep is + replaced at the next save, and the other two stop the handle from writing, + so an `onError` that decides whether to call `clear()` has to tell them + apart, and the text after a code is not stable. + +**Evidence.** `devbuild.md`, B1 and B2. 29 assertions in 15 test files match +today's text and are rewritten to match the code; that count is from a +search, not from a run. + +**Label.** Before 1.0. **Stage 4:** yes, with each change that adds a +message, and once for today's messages. + +### 36. One build, and one development-only check in 1.0 + +**Decision.** 1.0 ships one build. It has one check that runs in +development only: the report of a lost write. When a snapshot is asked for +and a field of the raw object has changed without a write through the store, +the library logs it once, with the code `lost-write` and the name of the +field. The comparison runs at most once per task for a store, however often +its snapshot is asked for in that task. Other warnings follow in a 1.x +release. Export conditions are not used. + +**The cost limits come first.** The core benchmark loads the built file as +it is, with `NODE_ENV` not set, so it measures the development path, and it +keeps doing so. The limits of `CONSTRAINTS.md` have to hold there with the +check in. As it was spiked, the check compares the fields every time a +cached snapshot is handed out, which is eleven to thirteen times dearer and +would put the cached-snapshot ratio far above its limit on both engines +(objection 3 of the second review). Once per task, a loop of reads pays for +one comparison. That form was not built. + +**The benchmark has to be able to see it.** Each sample of the benchmark is +one loop in one task, so a check that runs once per task costs a sample one +comparison, and the limits hold whatever that comparison costs (objection 10 +of the third review). An application takes about one snapshot per store per +task and pays for the comparison each time. So stage 4 first adds a row to +the benchmark that takes one cached snapshot per task of the 1,000-row +store, and records it without the check. The check lands only if that row +with the check in stays below the benchmark's `snapshot.afterWrite` for the +same store, on both engines: a render in development then never costs more +for the check than it costs after a write. The figure goes into the decision +record as the stated cost of the development path. If the check cannot meet +that, it does not ship in 1.0; it is a report and can arrive in any release. + +The row awaits a resolved promise between two snapshots, so each snapshot is +taken after the microtasks queued before it have run; the await is part of +its time. "Once per task" therefore means: the check marks the store as +checked, and a microtask it queues clears the mark. The figure goes into +record 0036. + +A development-only check is guarded by an inline read of +`process.env.NODE_ENV` at its call site, after a test that is cheap and +almost always false, and behind `typeof process`. That form becomes a floor +rule of `CONSTRAINTS.md`, held by a test that bundles the built file for +production and asserts that no development text and no `console.warn` is +left in it. + +**How the test knows development text.** A development-only report is +written with `console.warn`, and nothing else in the library calls +`console.warn`. Its code is listed in +`packages/classy-store/tests/size/developmentOnly.json`, which is empty until +the check of this entry lands. `bun run size` already bundles every entry +for production, with `NODE_ENV` set to `production`; it fails when such a +bundle holds `console.warn` or a listed code. A unit test bundles a fixture +written in the guard form, once for production and once for development, +and asserts that its marker text and its `console.warn` are gone from the +first and present in the second. So the form is held from the first commit, +before any check exists, and the floor rule names both. + +**Why.** + +- An arrow-function method that writes to the raw instance is the first + silent failure the plan names. The base class of decision 11 removes it + only for a class that is changed to extend it; + `createClassyStore(new X())` stays documented, and a class that extends + something else has no other way. The lost-write report covers those, and a + constructor that starts a timer, and a write through the raw object. +- It is precise. In its spike it found six of seven lost writes and reported + nothing that was not one. +- It cannot be always on, and it cannot run on every read: it makes a + cached snapshot eleven to thirteen times dearer, and it is 168 to 309 + bytes. Behind the guard it costs production a few bytes, and "this store + was already checked in this task" is the cheap test the guard form asks + for in front of the read of the environment. +- The other candidates are not ready. A warning that fires for correct code + and cannot be silenced is worse than none: the one for an unmarked class + instance fires for seven kinds of object that are no mistake, and one for a + write after an `await` would fire for the ordinary `async` method. A + warning changes no behaviour, so those can arrive in any release. + +**What 1.0 still does not catch.** The docs page of decision 35 lists these +beside the codes, so that they are written down in one place: a native `Map` +or `Set` in a store, an unmarked nested class instance, a `Date` changed in +place, a getter that reads another store or a static, a result of a getter +that is mutated, a named property on an array, an own-property check inside +a getter, and a prototype changed after its first read through a store. + +**What follows for other entries.** The default of `devtools({enabled})` +reads the same environment (decision 27). `batch()` gets a check that needs +no build split (decision 16). + +**Not taken.** Export conditions (`development` and `production`): plain +Node, `bun test` and an unminified bundle would load the production build in +silence, the published files double, and `check:package` does not check the +second branch. Shipping the five warnings as the development-build report +spiked them: one of them, the report of a lost write, ships in the better +form of `spike-classes.md`, C4 (b), and the other four are not ready, for the +reason above. + +**Evidence.** `devbuild.md` for the guard and its traps: a module-level +constant leaked 218 bytes into production where an inline read cost 6, and an +inline read on the path of a write cost 184 nanoseconds on unbundled Node. +`spike-classes.md`, C4 (b), for the check. The check was measured always on, +not behind the guard; stage 4 measures it there first. + +**Label.** The guard's rule and the default of `devtools`: before 1.0. The +check: can follow 1.0. **Stage 4:** yes. + +## The release workflow, dependencies and documentation + +### 32. The workflows are hardened now; the release job is split after 1.0 + +**Decision.** + +- **In stage 4:** every third-party action in every workflow is pinned to + the commit its tag points to today. "Third-party" means every action this + repository does not define, GitHub's own `actions/*` included: a moved tag + is the same risk whoever owns it. A Dependabot configuration keeps the + pins current. The three workflows that declare no permissions + get `contents: read`. Neither changes what a run does. +- **After 1.0:** `release.yml` is split into a job that installs, builds, + runs Changesets and packs the tarball, and a job that holds + `id-token: write`, installs nothing and publishes that tarball. The plan + for it names where each step goes, the tag step and the "already + published" check included, and sets `persist-credentials: false` on the + release checkout with the token passed to the push. The owner tries it + with a manual run before a release depends on it. + +**Why.** + +- Today one job holds the publishing identity and also runs `bun install`, + the build and Changesets. A compromised development dependency or a moved + action tag could take the token and publish a version of its own. The + split closes that route. It does not close the other one: the same code + could rewrite `dist` before it is packed, and the second job would publish + that. Pinning closes the moved-tag half of both. +- A release workflow cannot be tried without releasing, and no agent runs + it. If the split landed in stage 4, its first run would be the publish of + 1.0. Nothing about the split has to ship with 1.0, so it does not. + +**Only the owner can do** two steps of the later split: a GitHub environment +for the publish job with a required reviewer, and the npm settings that +accept only that environment and refuse publishing with a token. + +**Evidence.** `review/stage-2/security.md`, finding 12 (M74); +`adversarial-whole.md`, objection 6. That code in the job can take the token +comes from how GitHub and npm document the mechanism; nobody tried it. + +**Label.** Can follow 1.0. **Stage 4:** the pins and the permissions only. + +### 33. Dependencies + +**Decision.** `proxy-compare` stays pinned to an exact version, and +`CONTRIBUTING.md` says why. CI gets a `bun audit` step that reports and does +not fail. The published tarball is accepted as it is (M75). + +**Stage 4:** yes. + +### 34. Documentation + +**Decision.** The documentation changes listed under M76 are made in stage +4, each with the code change it belongs to, or in stage 5 where no code +changes. The limits listed under M77 stay as they are and go into the +unspecified list or stay documented where they are documented. + +Two more sentences go into the reference: + +- **An array in a store carries its indices and `length` only** (M37). A + named property written to one stays on the live array and is left out of + every snapshot. A check that reports it can follow in 1.x. +- **A spread or a serialised snapshot carries data, not computed values** + (decision 43), with the same sentence in the changelog entry for 1.0, + because code that spreads a snapshot today changes without an error. + +## What 1.0 guarantees, and what it leaves unspecified + +Stage 1 added 547 tests that pin what the library does today. +`review/stage-3/pinned.md` sorts the behaviours behind them into 250 rows: 56 +the docs already promise, 47 that are defects, and 147 that needed a label. +Its table is the evidence. This section is the decision. + +A guarantee is written as a rule, not as a row. A rule is documented, and +changing it is a breaking change. Everything not covered by a rule here or +by a sentence in the reference is unspecified, and may change in a minor +release. The stage 1 tests stay; a test of unspecified behaviour is a change +detector, and its file says so. + +### Guaranteed + +1. **Subscribers.** The subscribers of one node are called in the order they + subscribed. A subscriber hears only writes made after `subscribe()` + returned, and none after its unsubscribe function returned. A subscriber + that throws leaves the write applied, the other subscribers called and + itself subscribed; the code that wrote is never told, whatever the console + does. +2. **Transactions.** A method, a setter, an array method and `batch()` each + notify synchronous subscribers once, when the outermost call returns, and + that covers every store written inside it. An `async` method is a + transaction up to its first `await`; each write after it is a write of + its own. The body of a generator method runs at each `next()`, after the + call has returned, so each write in it is a write of its own. A write + that changes nothing notifies no one. Decision 1 says which functions are + methods. +3. **Delivery.** A write made while synchronous subscribers are being called + is delivered to them after the round that is running, and before the + outermost write returns, for up to 100 rounds. A write made inside a + batched subscriber is delivered to batched subscribers in the same + microtask, after the round that is running. +4. **Getters.** A getter is lazy. It returns the same result while nothing it + read through `this` changed, and a correct one after anything it read + changed. An own-property check (`Object.hasOwn`, `hasOwnProperty`) is not + a read in that sense. A cycle of getters throws, and the other getters + keep working. A getter that writes to the object it is computed on + throws a `TypeError`, on the store and on a snapshot, whichever way the + write gets there. +5. **Snapshots.** The root of a snapshot, and every plain object, array and + reactive collection in it, is frozen. A value the store does not proxy (a + class instance without the marker, a native `Map`, `Set` or `Date`, a + function) is shared with the snapshot by reference, and an object a getter + returns is not frozen. A subtree that did not change and is not on a + cycle keeps its snapshot object. Taking a snapshot runs no getter. +6. **Identity.** One object has one proxy, however it is reached through the + store's proxies and in however many stores it sits. Two ways of reaching + an object hand it out as it is, with no proxy: through an object that was + frozen before it reached the store, and through a read-only property that + was defined with the object as its value. `createClassyStore()` on a + proxy, or on the raw object behind one, returns that proxy. A value the + store does not proxy reads back as itself, except a function that + decision 1 makes a method: it reads back through the store as one + function for that object, the same on every read, and the object and its + snapshots hold the function that was written. +7. **An object that has left the store** stays a working store of its own: + reads, writes, subscriptions and snapshots work, and the store it left is + no longer told. Put back, it is the same proxy. +8. **The native rules of an object hold through a store**: key order, holes, + `TypeError` on a refused write, `false` from `Reflect`, and the meaning of + sealed and frozen. +9. **Memory.** The library keeps no strong reference to a store that nothing + else references, or to a subscriber after its unsubscribe function was + called, in a runtime that has `WeakRef`. +10. **`persist`.** A handle writes only after it has read. A stored record + is removed or replaced only in these cases: its time has elapsed; + `clear()` is called; a save follows a restore of that record; a save + follows no record, a record with nothing to keep, or a record of a lower + version when no `migrate` is given (decision 21 says which). A record of + a newer version, one that the application's `migrate`, `merge` or + `deserialize` failed on, and one whose read failed, is reported and is + not written over by the handle that read it. Two cases are outside this + rule, and the guide names them: a tab that read before a newer build + wrote, and does not sync, writes over the newer record; and a `migrate` + that returns a wrong result without throwing is saved at the next edit. + An edit made before or during the first read is kept in the store, and + saved unless the record is one the handle does not write over. The + first `clear()` of a task, and the first `save()` of a task on a handle + that writes, reaches a synchronous storage before it returns. After `dispose()` nothing is read, written or + scheduled. +11. **Exports.** Every export the reference lists exists with its documented + signature. The list may grow in a minor release. +12. **Error codes.** The code in an error or a logged report is stable. + +### Unspecified + +- The order in which different nodes, owners and stores are notified + (findings 24 and 69). +- How calls nest when a subscriber writes, where the microtask of a + batched round falls among the application's own microtasks (rule 3 says + which round a write inside a batched subscriber joins), and what an + adapter of another store shows inside one delivery round. +- Where a subscriber's error is reported, and the text of an error message + after its code. +- Whether a getter re-runs more often than rule 4 requires, and whether a + thrown error is cached. +- What a getter does that writes to another object of the same store: a + child, a parent or the root. Today's answer is that it works on the store; + on a snapshot a write to a child throws in strict code, and a write to a + parent reaches the live store. +- What a prototype that is changed after its first read through a store + does (findings 44 and 47). Decision 12 gives the answers of the form + taken, which differ from today's in two places. +- What a function does when it is read from a snapshot and called. Today's + answers: a method of the class or of an object literal that writes `this` + throws, and an arrow-function field of a `ClassyStore` subclass writes the + live store without a transaction (decision 1). +- What reflection hands out: `Object.getOwnPropertyDescriptor(store, key)` + and `structuredClone(store)` (findings 50 and 51). +- Anything reached through the raw object behind a store (finding 11), and + a write to the backing array of a reactive collection. One case of it is + named in decision 1: a property made read-only on the raw object after + the store has handed out its method throws on the next read. +- A store made from a function or from a typed array (findings 62 and 63), + beyond decision 1's rule that a function which is a store is handed out as + it is. +- Behaviour in a runtime without `WeakRef` or `FinalizationRegistry`, beyond + "it works" (finding 68). + +### Where this differs from `pinned.md` + +- **Functions.** `pinned.md` recommends wrapping every function a store + holds, on every read. Decision 1 does that for every function held in a + field but a class, as that report asks. The rows that pin a new wrapper + for an element of a list and for a class held as a value change. +- **The shape of a snapshot.** The rows that pin a class getter as an own key + of a snapshot, and `Class.prototype` as its prototype, change with decision + 43. The rows that pin the throw on a cycle change with decision 44. +- **Accessors of an object literal and of a class** are labelled the same + and guaranteed there. On the store they still are. On a snapshot they + differ after decision 43: a getter of an object literal is an own key, + carried by a spread and by JSON, and a class getter is neither. The + tutorial says where the two differ. +- **The ownership rows** are folded into rule 7. The order in which removed + containers hear of a write stays unspecified. +- **The type tests fail when an export is added.** They stay as change + detectors, and rule 11 says what is promised. + +## Proposed in a report and not taken + +Each is named in the entry it belongs to. In one list, with **(final)** on +the ones that 1.0 settles for good, because taking them later would break a +consumer: + +- Four other rules for a function held in a field (M1): "strict", under + which only a function on the prototype chain is a method; "lenient" as + first spiked, which wraps every function on every read and keeps a copied + wrapper and a stale getter; "born with", which writes the store's wrapper + into the object; and every function with a `prototype` of its own as + data. Decision 1 keeps the object as it is, hands out the method on a read + through the store, and treats only a class as data. **(final)** +- The rule for functions without its short path, which asks for a + descriptor at every read of a function (decision 1). +- Refusing accessor and read-only definitions, `setPrototypeOf`, or + `Object.freeze(store)` (M2, M8). **(final)** +- A Proxy target of the library's own (M7): both reports that describe it + call it too large for 1.0, and it reopens decisions 2 and 7. +- A guard for a raw object frozen behind the store (M7). +- Array methods run on the raw array (M10): unmeasured on this library, and + decisions 10 and 12 attack the same cost. +- Wrapping nested class instances by default (M11). **(final)** +- Detecting an arrow function by its source text, an `opaque()` helper and + a mixin form of the base class (M12). +- Removing suspension as a whole (M14), and holding a subscribed node + strongly (M15). +- Recording reads outside a getter's own node (M21), and caching a thrown + error (M22). +- Throwing a subscriber's error to the writer (M28). **(final)** +- `reportError()` as the place a subscriber's error is reported (M28). + Where the report goes is unspecified, so this can still change. +- A subscriber that does not hear of its own write, and a microtask of its + own for each batched round (decision 13). **(final)**: guarantee 3 states + the other choice. +- Dropping a write that is undone inside a batch (M30): one notification for + a batch that wrote is the simpler rule. +- A synchronous default for `subscribe()` (M31). **(final)** +- A warning for a write outside a method (M32). +- Own accessors that are not enumerable, as the form for snapshot getters + (M33). +- Rebuilding only the changed keys of a snapshot (M35), in 1.0. +- Refusing the write that closes a cycle (M36). **(final)** +- Reactive native `Map` and `Set` (M38), and an index beside the live array + of a collection (M40), in 1.0. +- Hiding the backing arrays `_entries` and `_items` (M43). **(final)** +- A `'migrate'` value for the public `PersistOperation` type (M45). + **(final)**: a new member of that union would break a consumer's + exhaustive `switch`. +- Awaiting an `async` `migrate` (M45). Accepting later what is refused now + is a compatible change, so this is not final. +- Writing over a record of a newer version, or over one that could not be + migrated or merged, at the next save (decision 21). **(final)** +- Writing a migrated record back at load (M47), and a handle that saves + before it has read (decisions 21 and 24). **(final)** +- A handle with `skipHydration` that only looks at the stored version before + its first save: it would still write the defaults over a record it could + have restored. +- An optional `storage`, removing `clearOnExpire`, a pause switch and an + in-flight flag for `persist` (M46, M49, M55). +- Refusing a cross-tab event that has no `storageArea` (M53). +- One snapshot per direct write on the synchronous channel of `devtools` + (M57), a naming hook that runs on every method call, and the getter values + of nested objects in what `devtools` sends, in 1.0. +- `devtools` on by default in every environment (decision 27). **(final)**, + as every default is. +- A table per prototype that caches the whole descriptor of a getter (M9), + one that never records an absent key, and one that leaves out + `Object.prototype` and `Array.prototype` (decision 12). +- A selector form of `subscribeKey` (M62), in 1.0. +- Renaming the Solid adapter (M68) or `isEqual` (M71), and capturing the + hydration snapshot automatically (M70). **(final)** for the two names. +- Export conditions for a development build, and four of the five warnings + the development-build report spiked (M72, M73). +- Splitting the release job before 1.0 (M74). + +## Every merged issue, and where it is decided + +| Issues | Decision | Issues | Decision | Issues | Decision | +| ---------- | -------: | ---------- | -------: | -------- | -------: | +| M1 | 1 | M28 | 13, 14 | M56, M57 | 27, 30 | +| M2, M8 | 2 | M29 | 15 | M58 | 28 | +| M3 | 7 | M30 | 16 | M59 | 29 | +| M4 | 8 | M31 | 17 | M60 | 30 | +| M5 | 6 | M32 | 18 | M61, M62 | 31 | +| M6 | 5 | M33, M34 | 43 | M63 | 37 | +| M7, M13 | 9 | M35 | 46 | M64, M65 | 38 | +| M9 | 12 | M36 | 44 | M66, M67 | 39 | +| M10 | None | M37 | 34 | M68, M69 | 40 | +| M11, M12 | 11 | M38 to M40 | 42 | M70, M71 | 41 | +| M14 to M17 | 3 | M41 to M43 | 45 | M72, M73 | 35, 36 | +| M18 to M22 | 10 | M44 | 22 | M74 | 32 | +| M23 | 7 | M45, M46 | 21, 26 | M75 | 33 | +| M54 | 20 | M47, M50 | 24 | M76, M77 | 34 | +| M55 | None | M48, M49 | 19, 26 | M51, M52 | 23 | +| M24 to M27 | 10 | M53 | 25 | | | + +"None" means the proposal is in the list of what is not taken. + +**Stage 1 findings that no merged issue covers.** Finding 4 (two traps of +the React snapshot cache that cannot be reached) is in decision 20. Findings +13, 35 and 40 are behaviour that stays: a getter on a store that refers to +itself recomputes on every write, a snapshot used as a key of a collection +answers for the live row, and an object a getter returns is not protected. +Finding 59 is in decision 20. + +## The order for stage 4 + +One change per commit, test first. Each is measured against the commit +before it, and a difference inside the spread that stage 1 recorded is +noise; decision 1 says why the stage 1 figures themselves are no baseline +once decision 12 has moved them. Stage 4 writes each change again from its +decision; it applies no spike patch. The order follows what each change touches and what it needs. +The task list that follows refines it. + +1. **Tooling.** The ceilings in `budgets.json`, the size script and the + floor guard with their tests (decision 4), with the decision record. The + guard form for a development-only check as a floor rule, with the test + that bundles the built file for production (36): decision 27 uses that + form long before the check of decision 36 itself. +2. **Codes, and code that is dead today.** The six messages the library + has today that 1.0 keeps get codes, and the page of codes is created + (35). From here on + every commit that adds a message adds its code and its line on that page. + Then the dead lines (20). +3. **The core, reads and writes.** The walk (3). The table per prototype + (12), which tells the trap "own or inherited" before decision 1 asks. The + delete (8). `defineProperty` as a write (2). Then, as its own commit, raw + values on write with the child kept through a freeze (5). The rule for + functions (1). The searches (6). The realm guard (9). +4. **Getters.** One kind of dependency and the rest of decision 10, which is + the first change built on the table of decision 12 that no spike ran + together with it. Then the `has` and `ownKeys` traps (7), which add two + records in that one shape. +5. **Snapshots.** Class getters on a derived prototype, with `this` (43). + Cycles (44). The types (45). +6. **Delivery.** The queue (13), the report that cannot throw and the + rejection handler (14), the setter (15), `batch()` (16). +7. **Collections.** The membership rule and the snapshot index (42). +8. **Utilities.** `persist` (19, 21 to 25). `devtools` (27), with the hook + in the core and the getter values it sends (43). Restore in place (30), + which takes over the line decision 44 added to `history.ts`. `history` + (28, 29). `subscribeKey` (31). +9. **The base class** (11), which needs 1, 2 and 30, and with it the tests + that need it: the rows of decision 1 for an arrow-function field (one + transaction, the overriding field under both ways of compiling, its + name, and a call taken from a snapshot), `persist()` called in a + constructor (19), and a getter read on a snapshot that calls an + arrow-function method (10). +10. **Adapters.** Vue (37, 38). Angular (37, 39). Solid (37). The `active` + flags of Vue, Angular and Svelte (42). +11. **The lost-write check** (36), measured against the cost limits before + it lands. +12. **The repository.** The audit step and `CONTRIBUTING.md` (33). The pins + and permissions of the workflows (32). + +A change that makes other code dead removes it in the same commit (20). +Documentation changes go with the change they describe (34), and a change +corrects every page it makes false in that commit, even where a later step +puts something back: the snapshot commit of decision 43 says on the +DevTools page that the panel shows no computed values, and the `devtools` +commit that sends the root's getter values changes that sentence again. + +Budgets are set to their final size plus 2% (decision 4) after the +independent review's fixes are committed and before the full validation +matrix runs, so that a fix that moves a size is counted. + +## Settled when the step 7 documents were checked + +The spec, the decision records and the task list were written from this +document and then checked against it by four agents +(`review/stage-3/check-spec-api.md`, `check-spec-rules.md`, +`check-records.md` and `check-tasks.md`). Their writers and checkers listed +what this document left open. Each point is settled here, and the entry it +belongs to now says it. Where a point changed an entry, the entry carries +the full text; this list is the index. + +| Point | Settled | Entry | +| --------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -----------: | +| The names of the error codes, and which of today's messages get one | Nineteen codes, listed in decision 35. All of today's messages get theirs in one commit, except the snapshot's circular reference, which decision 44 removes before 1.0 and which therefore gets none. One prefix for every message, the adapters' too | 35 | +| What a `persist` report carries | A value the library did not throw is passed as it is. A refusal of the library's own is an `Error` with one of four codes. The default report is one `console.error` line with the code `persist-failed` and the error. Every failure of `save()` is reported and rejects, a `save()` before the first read included | 21 | +| What `save()` and `rehydrate()` reject with on a handle that does not write | The error `lastError` holds. A `rehydrate()` whose read fails reports as `'read'` and rejects | 21 | +| How the floor guard walks the commits | From the merge base with `main`, or from the commit that added `CONSTRAINTS.md` while `main` does not hold it; each commit against its parent; a merge commit in the range fails; then the working tree against the head | 4 | +| How the guard judges its own file | Its own file, the coverage settings and the list of mutation targets are bar files: every change to one needs a line in a decision record. Its own patterns are not scanned for | 4 | +| A test made smaller in a commit | Allowed when the commit message has a `Test-change:` line for the file that names a decision or the public test that covers the fact | 4 | +| Where the ceilings live, and an entry without one | Beside each budget in `budgets.json`; an entry without a ceiling fails. The size rows of `CONSTRAINTS.md` name the file and stop repeating its numbers | 4 | +| What the production-bundle test looks for | `console.warn`, which only a development-only report uses, and the codes listed in `tests/size/developmentOnly.json`, checked by `bun run size`; plus a unit test of the guard form on a fixture | 36 | +| How the benchmark row takes one snapshot per task | It awaits a resolved promise between two snapshots, and the await is in its time | 36 | +| Which benchmark comes before a redundant check goes | Only the guard in `indexOfMember` sits in a loop; two rows, `collection.has.primitive` and `collection.has.object`, come first | 20 | +| The direct tests of the two React cache traps | Tests of internal state; they go with the traps | 20 | +| The `activeTracker()` timing | Already timed alone; the line stays | 20 | +| Which baseline a change is measured against | The commit before it, with the spread of stage 1 as the noise; decision 13's condition too | Order, 1, 13 | +| Where timings recorded before and after are kept | In the commit message; the lost-write figure in record 0036 | 1, 13, 36 | +| The test of a runtime without `WeakRef` after the walk goes | It asserts that a held row no longer keeps its replaced list alive and still works; the memory half is a change detector | 3 | +| The 17 compilations | Committed tests for TypeScript both ways and Bun; the other compilers in a scratch folder | 11 | +| The options of `devtools` | `maxAge`, `trace`, `traceLimit`, `actionsDenylist` and `actionsAllowlist` are taken, as built | 27 | +| A DevTools jump on a frozen root | It writes nothing; `devtools` logs the `restore-locked` error | 27 | +| How `batch()` tells an `async` function, and its exported types | By `Symbol.toStringTag`, as decision 22; a mock function is accepted. The type of its parameter is not exported | 16 | +| The names of the collection snapshot types | `ReactiveMapSnapshot` and `ReactiveSetSnapshot`, from `./collections` | 45 | +| How the Vue adapter knows it is on the server | Inside a component with `inject(ssrContextKey, null)` set; the scope check stays first | 38 | +| The Angular options type and a destroyed context | The options type is not exported; a destroyed context has the same code | 39 | +| When the adapters' `active` flags go | In the adapter step, as the order says | 42 | +| Rule 3 against "which microtask a batched round runs in" | Rule 3 wins; the unspecified item now names only where that microtask falls among the application's own | Lists | +| A generator method | Rule 2 says that each write in its body is a write of its own | Rule 2 | +| Rule 6 and functions | Rule 6 states the method as the exception to "reads back as itself" | Rule 6 | +| Rule 10 and a handle that does not write | The first `save()` of a task reaches a synchronous storage on a handle that writes; `clear()` always | Rule 10 | +| A store made from a function | Unspecified, beyond decision 1's rule that a function which is a store is handed out as it is | Lists | +| Which actions are third-party | Every action the repository does not define, GitHub's own included | 32 | +| A page that is false between two steps | Each change corrects every page it makes false, in its own commit | Order | +| When the budgets are set to their final size | After the independent review's fixes, before the full validation matrix | Order | +| A reason for decision 18 | Written | 18 | +| The labels of decisions without a **Label** paragraph | Their records take the label of the index table; decisions 11 and 39 keep their split labels | Index | +| "The five warnings" against "four of the five" | Four: the fifth ships as the lost-write report in a better form | 36 | +| 57 or 49 bytes for the naming of `devtools` | 57 is right: it is what `./utils` adds to the main entry, as every row of that table counts; the totals differ by 49 because the main entry is 8 bytes smaller with the hook | 4 | +| The README and "about 3.7 KB" | Only `CLAUDE.md` gives the figure | 4 | +| The sentence decision 3 said the docs already have | They do not; the tutorial gains it with decision 3 | 3 | +| "0.11" in the records | Wrong: 0.11.0 has no `batch()` and no transactions. A record says "before 1.0" for the code on the 1.0 branch before its change | Records | + +## Objections and answers + +Agents that took no part in the spikes or in writing this document reviewed +it as adversaries, in rounds. Every objection was checked against the text +and its evidence. None was dismissed as noise. + +### The first round + +Three reviewers read the first complete draft: +`review/stage-3/adversarial-whole.md` (W), `adversarial-core.md` (C) and +`adversarial-edges.md` (E). They raised 58 objections; 28 were rated +"wrong", 4 "mislabelled", 13 "unsupported" and 13 "unclear". + +"Changed" means the entry was rewritten to answer it. "Changed after a +spike" means the objection could not be settled by reading, a spike was run +for it, and the entry was decided again from the result. "Accepted" means +the objection is right, the cost is taken on purpose, and the entry now says +so. The number in brackets is the decision that carries the change. + +| No. | Against | Objection | Answer | +| --- | -------------- | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------ | +| W1 | 30, 44 | Undo on a store with a cycle never returns | Changed after a spike: the restore enters each object once (30); six stores with a cycle undo, redo and jump | +| W2 | 27 | Named entries need the synchronous channel the entry ruled out | Changed: 27 says what the spike did; 17 no longer lists `devtools` as batched | +| W3 | 11, 30 | The base class is ordered before the restore it needs | Changed: the base class follows the utilities in the order | +| W4 | 4 | Nothing enforces the ceilings, and one record switches the guard off | Changed: stage 4 starts with the tooling; the guard works per commit | +| W5 | 4, 45 | The collections ceiling rests on 32 bytes where the report says 55 | Changed: 55, and a ceiling of 950 | +| W6 | 32 | The split does not stop a rewritten `dist`, and its first run would be the 1.0 publish | Changed: pins and permissions now, the split after 1.0, and the "why" corrected | +| W7 | 20 | Dead code removed last breaks the mutation rule in between | Changed: dead code goes in the commit that makes it dead | +| W8 | 1 | An object-literal method stops being a transaction, in silence | Changed after two spikes: a method in an object literal is a transaction again under decision 1 as it now stands | +| W9 | 36, 11 | Thirteen silent failures remain in 1.0, and the base class covers only classes that change | Changed: one development-only check is decided for 1.0, on a stated condition (36); the rest are listed in the docs. Accepted for the rest | +| W10 | 27, 36 | `enabled: true` is locked in for all of 1.x | Changed: on, except where `NODE_ENV` is `production` | +| W11 | 42, 37 | Solid's flag cannot go, and the change sits in two steps | Changed: Vue, Angular and Svelte drop theirs; one place in the order | +| W12 | 8, 9, 28, 37 | Four labels contradict the definition | Changed: 8, 9, 28 and the Vue half of 37 are "before 1.0"; 9 ships in 1.0 | +| W13 | Guarantees | Rules 2, 3 and 5 are false as written; "error text" contradicts the stable codes | Changed: the rules are rewritten, and rule 12 added | +| W14 | 20, 24, 28, 34 | Finding 4 and M37 are decided nowhere; 24 and 28 have no decision text | Changed: finding 4 in 20, M37 in 34, both texts written | +| W15 | Not taken | The list misses choices that 1.0 makes final | Changed: completed, with the final ones marked | +| W16 | 4, 35 | The figures disagree, and the set was never built or timed | Changed: one sum, 5,255 and 44% after the second set of spikes; the entry says the ceilings are estimates | +| W17 | 4, 27, 9, 7 | Four items buy little for their bytes, and the hook costs every method call | Changed: 4 weighs each. The hook is replaced by a slot that costs a method call nothing measurable (27) | +| W18 | 43 | What `devtools` sends for computed values was never built | Changed after a spike: built and counted, 95 bytes on `./utils` (43, 27) | +| C1 | 30, 44 | The same as W1, reproduced on the library | Changed, as W1 | +| C2 | 5 | After a freeze through the store a child reads back raw and its writes are lost | Changed after a spike: the trap puts the proxy in the raw slot before the property locks (5). Two cases stay raw and are stated | +| C3 | 11 | One function in two stores writes the first store | Changed after a spike: one method per object and function (1) | +| C4 | 11 | A subclass that overrides an arrow method loses the transaction | Changed after two spikes: an arrow field is a method when it is read through the store, whichever way it was written (1) | +| C5 | 11 | The same as W3 | Changed | +| C6 | 12 | A getter redefined on the class keeps its old body on the live store | Changed after a spike: the table holds no function (12) | +| C7 | 6 | A list of saved snapshots gets wrong answers from the searches | Changed after a spike: a value is found by reference, an object in a store by any form (6) | +| C8 | 7 | `Object.hasOwn(this, …)` in a getter stays stale, against rule 4 | Changed: 7 and rule 4 name it as not tracked. Accepted: a trap for it can follow | +| C9 | 43 | The same as W18 | Changed, as W18 | +| C10 | 43 | A spread loses computed values with no error | Accepted: every compared library does this; 34 adds the sentence and the changelog note | +| C11 | 43 | `this` does not have the store's prototype | Changed: the sentence says keys, constructor and `instanceof` | +| C12 | 10 | The throw on a snapshot holds in strict code only | Changed after a spike: the traps throw themselves (10) | +| C13 | 10 | The own-node form of the live-store throw was never weighed | Changed after a spike: taken, for the getter's own object (10). Accepted: a write to a child still differs between the layers | +| C14 | 1 | The tie-breaker is false: the strict rule's cost is silent too | Changed, as W8 | +| C15 | 7, 10, 43 | The three were never run together, and 7's figures are for a design nobody will build | Changed: 7 and 4 say so; stage 4 takes its figures from its own build | +| C16 | 29, 30, 11 | A jump by JSON could delete every arrow method | Changed: 29 says a restore from outside never touches a function field | +| C17 | 11, 27 | An arrow method gets no name for `devtools` | Changed after a spike: a method takes the name of the key it was read under (1, 27) | +| C18 | 45 | A subclass of a collection loses its members in the snapshot type | Changed: 45 says so, and that a hook for it can follow | +| E1 | 21, rule 10 | Without `onError` a refused record is still silent, and the next save replaces it | Changed: a default report to `console.error`; rule 10 says what happens to it | +| E2 | 19, 11 | A restore inside a constructor is lost to a subclass's initialisers | Accepted: nothing can detect it; 19 names it, the guide forbids it, and a test pins it | +| E3 | 27 | The same as W2 | Changed | +| E4 | 14, rule 1 | A console that throws sends its error to the writer and stops the round | Changed: the report is guarded | +| E5 | 16 | The type cannot see most callers, and a runtime refusal can only come before 1.0 | Changed: an `async` function is refused when it arrives, in every build | +| E6 | 21 | An `async` `migrate` is called and its rejection left unhandled | Changed: refused before the call, and a handler on a returned thenable | +| E7 | 26 | Removing `clearOnExpire` deletes data, and was never spiked | Changed: it stays | +| E8 | 30 | An undo writes into an object that now lives in another store | Accepted: the restore follows the object, and 30 says so. Run: four cases, and today ends a sharing in silence | +| E9 | 30 | The same as W1 | Changed, as W1 | +| E10 | 11, 30 | The same as W3 | Changed | +| E11 | Rule 3 | False for a write made inside a batched subscriber | Changed: one sentence per path | +| E12 | Rule 5 | Contradicts decision 44 | Changed: "and is not on a cycle" | +| E13 | Rule 10 | A second `save()` in one task reaches storage a microtask later | Changed: "the first of a task" | +| E14 | Rule 6 | An object reached through a frozen container reads back raw | Changed: rule 6 names the two ways an object is handed out raw. The behaviour is changed after a spike (5) | +| E15 | Rule 2 | Leaves out arrow methods and the `async` method rule | Changed | +| E16 | 38 | A write to the Vue ref is ignored in silence | Changed: it throws | +| E17 | 37 | The Vue half changes a documented shape | Changed: "before 1.0" for Vue | +| E18 | 42 | The index is skipped for tracked React reads; Solid's flag stays | Changed: both stated | +| E19 | 39 | The Angular message names the function in development mode only | Changed: the adapter throws its own coded error | +| E20 | 21 | The version rule is stated three ways | Changed: one rule, with `null` refused | +| E21 | 19 | The spike's gap, a `hydrated` that never settles, was dropped | Changed: 19 carries it | +| E22 | 13 | What an adapter of another store shows inside a round, and no criterion for the variant | Changed: stated, and the variant is taken on a stated condition | + +Of the 58, 55 are answered by a change to the document, 17 of those after +a spike, and 3 are accepted as costs. Four of the changes leave a part that +is accepted as a cost. Each accepted cost is stated in its entry. + +### The second round + +Two reviewers read the document as revised after the first round: +`adversarial-2-whole.md` (2W) and `adversarial-2-core.md` (2C). They raised +30 objections; 11 were rated "wrong", 1 "mislabelled", 5 "unsupported" and +13 "unclear". Two more spikes were run for the ones that needed a build: +`spike-functions-2.md` and `spike-core-3.md`. + +| No. | Against | Objection | Answer | +| ---- | --------------- | ---------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | +| 2W1 | 24, 21, rule 10 | An older build writes over a newer record when it loads | Changed: a newer record is never used or written over, and a record is written back only after an upgrade (21, 24). Not built | +| 2W2 | 21, 22 | The integer rule refuses a record the application saved itself | Changed: a version is a finite number on both sides; the option and an `async` `migrate` are checked when `persist()` is called | +| 2W3 | 36, 4 | The lost-write check breaks the cost limits as the benchmark runs today | Changed: once per task for a store, and the limits come first: the check gives way if it cannot hold them (36). Not built | +| 2W4 | 4 | Nothing stops a ceiling from rising | Changed: a ceiling moves only in a commit of its own; the guard covers itself and every commit, and has tests (4) | +| 2W5 | 4 | The React ceiling is below its own estimate plus 2% | Changed: every ceiling follows one stated rule (4) | +| 2W6 | 24, 23 | Both change a documented sentence and are labelled "can follow 1.0" | Changed: both are "before 1.0" | +| 2W7 | 27 | The naming reads a name that is empty; the evidence names the wrong build | Changed: the key is handed over with the call, and the hook form is named (27). Passing the key was not built | +| 2W8 | 27 | The default of `devtools` where there is no `process` | Changed: off (27) | +| 2W9 | 27, 43 | A getter of an object literal that throws still loses the entry | Accepted: the guard covers the root's class getters only, and both entries say so | +| 2W10 | Pinned | A guaranteed row that decision 43 breaks is missing | Changed: the line is added | +| 2W11 | 21 | An unusable `expiresAt`: restored, or refused | Changed: missing or `null` is restored; any other value that is not a number leaves nothing to keep (21) | +| 2W12 | 4, 35 | 100 against 271 bytes for the codes; rows that are not measured alone | Changed: 35 gives both figures, and 4 says which rows are measured on top of another | +| 2W13 | Order | Four steps need something a later step brings | Changed: the guard rule and the codes page come first, the constructor test moves, and 2 and 5 are two commits | +| 2W14 | Not taken | Two wrong "(final)" marks, three final choices missing, M23 listed twice | Changed | +| 2C1 | 1, rule 6 | A store made from a copy of an object or a snapshot runs the old store's methods | Changed after a spike: the object is never changed, so a copy holds plain functions (1). A copy made through the store is stated | +| 2C2 | 1 | A function on a snapshot or on the object ignores the `this` its caller passes | Changed after a spike: both hold the function as written (1). Accepted for a read through the store, as today | +| 2C3 | 10, 1, rule 4 | A snapshot getter that calls an own method writes the live store | Changed after two spikes: a method of an object literal throws there (1), and any path to the live object throws (10) | +| 2C4 | 30, 5, 2 | An undo into a container frozen through the store fails part-way | Changed after a spike: a container that would refuse a write is replaced, and a root that would throws before anything is written | +| 2C5 | 12 | The table grows with every absent key, for good | Changed after a spike: an absent key is recorded only while the table is small (12) | +| 2C6 | 29, 1 | A callback that is restored comes back wrapped | Changed after a spike: a restore writes the function back as it was written (1, 29). The change to `history.ts` itself is not built | +| 2C7 | 1 | The rule's text and the spike's code differ for a prototype method | Changed: case 1 is any function on the prototype chain, in the text and in the code | +| 2C8 | 1, 2 | A read-only function definition throws after it is made | Changed after a spike: nothing is wrapped at a definition, and such a property hands out its function as it is | +| 2C9 | 43, 27 | The same as 2W9 | Accepted, as 2W9 | +| 2C10 | 6, 42 | A list and a reactive collection answer differently for a snapshot kept as a value | Accepted: on purpose. Both entries say why, and a test pins both answers | +| 2C11 | 1, 12 | The timing condition names a baseline that decision 12 has moved | Changed: the baseline is the commit before the change (1) | +| 2C12 | 27 | "The slot form" is cited with the hook form's figures | Changed, as 2W7 | +| 2C13 | 5, 4 | 56 bytes where the report gives 68 | Changed: 68, and the sum with it | +| 2C14 | 10 | "A write to a child throws" is false outside strict code | Changed: the entry says what happens in each kind of code, and that it is unspecified | +| 2C15 | 43 | Its figures come from a layer that decision 10 changes first | Changed: 43 says its figures are a forecast | +| 2C16 | Rule 6 | Rule 6 and the unspecified list disagree with decision 1 on prototype methods | Changed: rule 6 speaks of a read through the store only, and a call on a snapshot is in the unspecified list | + +Of the 30, 27 are answered by a change, 7 of those after a spike, and 3 are +accepted as costs. Three decisions changed in substance: the rule for +functions (1), what `persist` does with a record it could not use (21), and +what an undo does with a container it cannot write (30). + +### The third round + +One reviewer read what had changed since the second round: +`adversarial-3.md` (3). It raised 17 objections; 4 were rated "wrong", 1 +"mislabelled", 3 "unsupported" and 9 "unclear". Two last spikes were run: +`spike-functions-3.md` and `spike-persist-2.md`. + +| No. | Against | Objection | Answer | +| ---- | ----------- | --------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | +| 3-1 | 1, rule 2 | A method written with `function` loses its binding and its transaction, in silence | Changed after a spike: only a class is handed out as data (1). Accepted: a constructor written as a `function` is as today | +| 3-2 | 21, 19 | `clear()` from `onError` cannot work on a synchronous storage | Changed after a spike: `onError` receives the handle, and an error it throws is logged (21) | +| 3-3 | Rule 10, 21 | Rule 10 is false for `skipHydration` and for an edit made during a read | Changed after a spike: a handle writes only after it has read, and rule 10 says what happens to such an edit | +| 3-4 | 24, 21 | Writing a migrated record back at load opens two losses | Changed: it is not written back (24). Accepted: a wrong `migrate` is still saved at the next edit | +| 3-5 | 1 | Slower than today for a method held in a field, and the condition measures another path | Changed after a spike: the short path is taken, the cost against today is stated, and the condition names two new benchmark rows (1) | +| 3-6 | 1 | The fast path that "can follow" changes documented behaviour | Changed after a spike: the gap for a frozen function is closed; the one left is stated and is in the unspecified list (1) | +| 3-7 | 21 | What `save()` and `rehydrate()` do on a handle that does not write | Changed after a spike: both report and reject (21) | +| 3-8 | 21, 24 | The two entries disagree on what is written back, and when | Changed: one list, in 24 | +| 3-9 | 21 | No row for a `merge` that fails | Changed after a spike: it is in the row of `migrate` (21) | +| 3-10 | 36 | The benchmark cannot see a check that runs once per task | Changed: a row that takes one snapshot per task, and a condition stated in figures of the benchmark (36) | +| 3-11 | 10, rule 4 | A getter on a nested object that writes the root goes through | Accepted: the throw is for the getter's own object, and a write to a parent is in the unspecified list | +| 3-12 | 10, 43 | The fix for a snapshot getter rests on a closure that decision 43 removes | Changed: 10 says so, and its rows are run again as tests after 43 | +| 3-13 | 1, 27 | One function under two keys has one name | Accepted: the name is the key that was read first, and both entries say so | +| 3-14 | 12 | Its "answers for now" do not match its own spike | Changed | +| 3-15 | 4 | The guard would flag its own text, and the first commit breaks the rule for ceilings | Changed: both have a rule | +| 3-16 | 30, 29 | The restore's check counts a function field as a key to delete on a jump by JSON | Changed: the check counts only the writes the restore makes. Not built; stage 4 tests the jump first | +| 3-17 | Lists | Loose ends in the lists, an answer of the first round, and the order | Changed | + +Of the 17, 15 are answered by a change, 7 of those after a spike, and 2 are +accepted as costs. + +**There is no fourth round.** The plan allows three. Two things were decided +after the third round and have not been read by a reviewer: the fourth form +of the rule for functions (decision 1) and the `persist` rules as built +(decisions 19 and 21 to 24). Both were built and run, each against the +scripts of the reviews that came before. They are the first things the +independent review of stage 4 reads, together with the points settled when +the step 7 documents were checked. diff --git a/review/stage-3-report.md b/review/stage-3-report.md new file mode 100644 index 00000000..c00bffc0 --- /dev/null +++ b/review/stage-3-report.md @@ -0,0 +1,222 @@ +# Stage 3 report: design review + +Stage 3 of the pre-1.0 review of `@codebelt/classy-store`. It ran from +2026-11-19 to 2026-11-25, with a pause from 2026-11-19 to 2026-11-24 at the +owner's request. No library source was changed. This report says what the +stage produced, what it decided, and what stage 4 has to know before it +starts. + +## Summary + +| Question | Answer | +| --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| What was decided? | 46 decisions, in `review/stage-3-decisions.md`. 31 change the public API or documented behaviour in whole or in part and must land before 1.0; 9 can follow 1.0; 5 keep things as they are; 1 is the documentation | +| Who decided? | The agent running the plan. The owner handed the decisions over on 2026-11-19, except merging into `main` and releasing | +| What is it based on? | 18 reports of spikes and of our own code under `review/stage-3/`, each with its patches and scripts in an appendix, and the merge of the 11 reports of stage 2 | +| Was it challenged? | Three times, by agents that took no part in writing it. Round 1: 58 objections. Round 2: 30. Round 3: 17. Every objection is answered in the document, in a table per round. Two decisions were made after the last round and have not been read by a reviewer. Then four agents checked the spec, the records and the task list against it: 65 findings, all applied, and 13 points it left unclear, all settled in it | +| What does 1.0 guarantee? | Twelve rules, and a list of what stays unspecified, in the decision document and in `review/spec.md` | +| What does it cost in size? | The main entry goes from 3,661 bytes to about 5,375, 47% more. `./utils` adds about 4,216 where it adds 2,686 today. The ceilings are 5,575 and 4,350 | +| What does it cost in speed? | The four cost ratios of `CONSTRAINTS.md` stayed inside their limits in every spike that timed them; the whole set was never timed. A field read gets faster: 2.7 times on Bun, a fifth on Node | +| What was not verified? | The whole set was never built as one. "What stage 4 has to check first" below lists the rest | +| What comes next? | Stage 4, from `review/stage-4-tasks.md`: 59 tasks, 58 in twelve steps and the last after the independent review, one change per commit, test first | + +## What the stage produced + +| Step of the plan | Result | +| ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 1. Merge the stage 2 reports | `review/stage-3/merged.md`: 77 distinct issues, 29 contradictions between reports, the order the issues depend on each other | +| 2. Review our own code | `own-code.md`: 101 single deletions run against the suite, 10 dead lines, the ownership patch that removes a hang | +| 3. Spike what reading cannot settle | Ten reports in two waves (traps, getters, delivery, pinned behaviour, `persist` and `devtools`, a development build, adapters and collections, snapshots, classes twice), and seven more that the reviews asked for | +| 4 and 5. The decision document | `review/stage-3-decisions.md`: the decisions, the guarantees, the proposals not taken, every merged issue mapped to a decision, the order for stage 4 | +| 6. Decide, and an adversarial review | Three rounds, six reports: `adversarial-whole.md`, `adversarial-core.md`, `adversarial-edges.md`, `adversarial-2-core.md`, `adversarial-2-whole.md`, `adversarial-3.md` | +| 7. Spec, decision records, task list | `review/spec.md`, `docs/decisions/` (46 records and an index), `review/stage-4-tasks.md`, each checked against the decision document and corrected (below) | + +## The decisions that shape 1.0 + +The decision document has all 46. These are the ones a user of the library +will notice. + +- **Which function is a method (decision 1).** A method of a class, as + today. And a function held in a field, when it is read through the store: + an arrow function, a shorthand method, a function written with + `function`. The object and its snapshots keep the function as it was + written. A class and anything in a list are handed out as they are. +- **A base class, `ClassyStore` (decision 11).** A class that extends it is a + store from its first line, so arrow-function methods work. The silent + failure the docs could only warn about is gone for such a class. +- **Subscriber delivery (decisions 13 to 16).** One queue with a bound, so a + subscriber that writes can no longer overflow the stack or hang the event + loop. A subscriber's error never reaches the code that wrote. `batch()` + refuses an `async` function. +- **Getters (decisions 7, 10 and 12).** Five getter defects go. A getter that + uses `in` or `Object.keys(this)` is no longer stale. A getter that writes + to its own store throws, on the store and on a snapshot. +- **Snapshots (decisions 43 to 45).** A class getter is no longer an own key + of every snapshot, so a spread or `JSON.stringify` of a snapshot carries + data only. A store that refers to itself can be read. Tuples stay tuples + in the types. +- **Lists (decision 6).** `includes()` and `indexOf()` find the object the + caller holds. +- **`persist` (decisions 19 to 26).** A synchronous storage is restored + before `persist()` returns. A handle writes only after it has read, so + with `skipHydration` nothing is saved before `rehydrate()`. Nothing it + cannot use is skipped in silence. A record from a newer version, or one + that could not be migrated, is never written over. A restore is all or + nothing. `onError` receives the handle. +- **`devtools` and history (decisions 27 to 30).** Entries are named after + the method that wrote. Time travel is exact. Undo changes a nested object + in place, so a row the caller holds stays the row in the store. +- **Errors (decisions 35 and 36).** Every error has a stable code, nineteen + in all, behind one prefix. One build, with one development-only check: the + report of a write that went to the raw object. + +## What the reviews changed + +The decisions that a review reversed or replaced, not only reworded: + +- **The rule for functions changed three times.** The first draft made only + a function on the prototype chain a method; round 1 showed that a method + in an object literal then loses its transaction in silence. The second + form wrote the store's wrapper into the object; round 2 showed that a + store made from a copy then runs the old store's methods, and that a + callback on a snapshot loses its caller's `this`. The third form left the + object alone and handed out every function with a `prototype` as data; + round 3 showed that a method written with `function` then loses its + binding. The form taken treats only a class as data. +- **Two decisions that were spiked apart broke together.** With a snapshot + that keeps a cycle, an undo overflowed the stack. With a container frozen + through the store, an undo failed part-way. The restore now enters each + object once and replaces a container it cannot write. +- **`persist` could have destroyed data, and each round found another way.** + Writing a migrated record back at once would have let an older build + replace a newer record as it loads. Replacing every refused record at the + next save would have turned one bad `migrate` into lost data. A handle + with `skipHydration` wrote before it read. The advice to call `clear()` + from `onError` could not work. After the third round the whole rule set + was built once and run through 33 paths. Removing `clearOnExpire` was + never spiked and is dropped. +- **The naming of `devtools` entries** cost every method call 5 to 6% on + Node. It moved behind a hook that `devtools` fills only while connected. +- **The table that speeds up reads** cached a getter's body, and then grew + without bound with keys that do not exist. The form taken does neither. +- **The list searches** gave wrong answers on a list of saved snapshots. +- **A getter that wrote to its own store** worked on the store and failed in + every component, and on a snapshot could still write the live store. It + now throws by every path. +- **The size ceilings** were not enforced by anything, and three were below + their own estimates. Stage 4 starts with the tooling, and each ceiling + follows one stated rule. +- **The order for stage 4** put the base class before the restore it needs, + removed dead code last, and wrote the page of error codes after the + messages. All three are corrected. +- **The release workflow** is not split before 1.0: the 1.0 publish would + have been the first run of an untested job. + +## What stage 4 has to check first + +Each of these is a statement the decision document makes from a part, not +from a whole, or from reading. + +- **The set was never built as one.** Sizes are sums of parts with a ceiling + above them. The largest combination built is five core changes, and it came + out 21 bytes under its sum. +- **Creating a store is 11 to 18% slower on Bun** with the trap changes + together (`spike-traps.md`, the timing of the combination; the decision + document does not carry the figure). The cause was not found; raw values + on write alone does not show it. Creation has no limit, so stage 4 times + it as each trap change lands. +- **Two decisions were made after the last review**: the fourth form of the + rule for functions, and the `persist` rules as built. Both were built and + run. No reviewer has read them. +- **The getter changes were never built on the table per prototype**, and the + throw for a getter that writes was never built on the rule for functions + or on the new snapshot layer. +- **Three small parts of the `persist` rules** are not in their build: a + record nested too deep is replaced, a removal in another tab lets a + handle write again, and the expiry stamp is for a finite `expireIn` only. + 24 tests that use `skipHydration` as a set-up have to call `rehydrate()` + first. +- **The lost-write check** was measured on every read, where it breaks the + cost limits. The once-per-task form was not built. It ships only if a new + benchmark row, one snapshot per task, stays below the cost of a snapshot + after a write. +- **`withHistory` and a function in a field** (decision 29) was reasoned; + only the write-back was run. +- **The key handed to the `devtools` naming hook** was not built. +- **The real Redux DevTools extension was never run**: the ids it sends back, + a cyclic state, an entry whose getter threw. +- **The browser, framework and mutation suites** ran on no spike. + +## The check of the step 7 documents + +The three documents of step 7 were each written by a helper agent from the +decision document. Four more agents then checked them against it, read-only: +the spec in two halves (`check-spec-api.md`, 10 findings, and +`check-spec-rules.md`, 17), the records (`check-records.md`, 19) and the task +list (`check-tasks.md`, 19). The writers had also listed 70 open points of +their own: 38 in the spec, 13 for the records and 19 in the task list. The +spec's part B, 24 of its 38, are things stage 4 checks first rather than +questions, and stay in the spec as such. + +Every open point, and the 13 points the checkers found unclear in the +decision document, was settled in the decision document itself, in the +entry it belongs to; its section "Settled when the step 7 documents were +checked" indexes them. The ones that blocked stage 4: + +- **Error codes.** Nineteen, all named now, behind one prefix. Today's + messages get theirs in one commit, except the snapshot's circular + reference, which decision 44 removes before 1.0 and which gets no code. +- **The floor guard.** It judges every commit against its parent, from the + merge base with `main` (or the commit that added `CONSTRAINTS.md`), then the + working tree. A merge commit fails it. Its own file, the coverage settings + and the list of mutation targets need a line in a decision record when they + change. A test made smaller needs a `Test-change:` line in the commit + message that names a decision or the public test that covers the fact. +- **The production-bundle test.** `console.warn` is used only by a + development-only report; `bun run size` fails when a production bundle + holds it or a listed development-only code, and a unit test checks the + guard form on a fixture. +- **The redundant checks.** Only the guard in `indexOfMember` sits in a loop; + two benchmark rows come first. + +Three more were found wrong in the decision document itself and corrected: +"0.11" is not what the records compare with, because the npm release 0.11.0 +has neither `batch()` nor transactions; the README gives no size figure, +only `CLAUDE.md` does; and decision 3 said the docs already describe a +subscription on a removed container, which they do not. + +Three helper agents applied the findings and the settled points, each in a +throwaway worktree on a branch of its own, and the orchestrating agent read +each diff against the decision document before bringing it in. + +## How the work was done + +- One orchestrating agent on Fable, which merged, decided and wrote the + decision document, and helper agents for the spikes, the reviews and the + three documents of step 7. From 2026-11-24 every helper ran on Opus, at the + owner's request, after the weekly Fable limit had stopped the work. On + 2026-11-25, after the decisions were final, the owner moved the + orchestration to a session on Opus 5.5 at extra-high effort, with its + helpers on Opus 5.5 at medium effort. That session checked and corrected + the three step 7 documents and settled their open points. +- Every spike ran in a throwaway worktree in the scratchpad, at commit + `57404c3`. No spike code is on the branch. Every patch and script is in the + appendix of its report, and stage 4 writes each change again, test first. +- A helper agent could create one file in the repository, its own report. +- Timings were taken on a machine that other agents were using. A difference + is reported only where the ranges of two builds do not touch. + +## Verified and not verified + +- **Run by the orchestrating agent itself:** the ownership patch and the + dead-code patch (tests, typecheck, size, timings); the timings of the trap + combination, of raw values on write, of the table per prototype and of the + `activeTracker()` line, each between two runs of the unmodified source; the + benchmark of the getter combination on Node; an undo after an object moved + to another store. +- **Run by a helper agent and read by the orchestrating agent:** everything + else the decision document cites as run. +- **A second opinion from another model** was offered to the owner and not + taken up. All three rounds of review used Claude agents with no knowledge + of the work, and a reviewer of the same kind can share the author's blind + spots. diff --git a/review/stage-3/adapters-collections.md b/review/stage-3/adapters-collections.md new file mode 100644 index 00000000..a6b956c0 --- /dev/null +++ b/review/stage-3/adapters-collections.md @@ -0,0 +1,4143 @@ +# Stage 3 spikes: adapters and collections + +Stage 3 of the pre-1.0 review, 2026-11-24 and 25. Spikes A1 to A7 of the +brief `review/stage-3/briefs/adapters-collections.md`, run in a throwaway +worktree at `5ab613f` (`/stage-3-adapters-collections/wt`), with an +unmodified second worktree beside it (`.../base`) for every "before". Nothing +in the repository was changed apart from this file. + +## Summary + +| Item | Result | Recommendation | Label | +| ------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------- | ----------------------------------- | +| A1. Snapshot at the read (Vue, Angular, Solid) | 2,000 direct writes: about 700 ms to 2.4 ms in each. One incidental test (`isShallow`). +34 to +44 bytes per entry | Do it | Can follow 1.0 | +| A2. Vue: no listener on the server, read-only ref | The stage 2 fix (`onMounted`) breaks `onServerPrefetch` data loading. Only A1's read-time ref fixes the leak and keeps it. `Readonly` settles contradiction 28 | Do it on top of A1 | Before 1.0 (the type) | +| A3. Angular: `untracked()`, `{injector}` | Both fixed and run. `untracked()` alone is +19 bytes; the option +51 more | Do it | Fix: can follow. Option: before 1.0 | +| A4. Solid rename to `fromClassyStore` | Eleven files; tests, typecheck and examples pass | Rename (owner's call) | Before 1.0 | +| A5. React: automatic first snapshot | Breaks the documented server pattern (create, load, render), even with `prepareStoreForHydration`; cyclic stores fail; +19 MB per 100,000 rows | Do not. Keep `isEqual` | No change | +| A6. One guard | With D1, all four `active` flags can go; Angular's `destroyed` check stays. Saves 13 to 16 bytes per adapter | Do it with D1, never without | Can follow 1.0 | +| A7. Collections | Snapshot lookups 160 to 525 µs down to under 0.1 µs; live 100 times faster with a live index, which answers wrong after a raw write. `-0` and constructors fixed in 13 bytes | M39 and the snapshot index: do. Live index: later, with M43 | M39: before 1.0. Index: can follow | + +Three things the owner should know before the detail: + +1. **The stage 2 fix for the Vue server leak is wrong as proposed.** + Subscribing in `onMounted` (or skipping the listener on the server) makes + a server render miss writes from `onServerPrefetch`, Vue's own way to load + data. The leak fix needs A1's ref that builds the snapshot when read. +2. **Automatic hydration capture (M70) is breaking, not additive.** Our + guide says to create the store, load the request data, then prepare. + An automatic capture fires on that first load write, so the server renders + the empty store, and an explicit call afterwards cannot undo it. +3. **Every adapter entry that changes goes over its budget**, by 13 to 77 + bytes; `./collections` by 93 with the snapshot index. The decision document + should set these budgets together with the main entry's. + +## Baseline + +The unmodified worktree at `5ab613f`, Apple M1 Max, Bun 1.4.5, other agents +running on the machine. + +- `bun run test`: 1,341 pass, 0 fail, 95 files. +- `bun run --filter @codebelt/classy-store typecheck`: passes (after one + `bun run build`). +- `bun run size`, bytes gzipped that each entry adds to the main one: + + | Entry | Bytes | Budget | Room | + | --------------- | ----: | -----: | ---: | + | `.` (main) | 3,661 | 3,750 | 89 | + | `./collections` | 727 | 750 | 23 | + | `./react` | 1,662 | 1,700 | 38 | + | `./vue` | 280 | 300 | 20 | + | `./svelte` | 182 | 200 | 18 | + | `./angular` | 271 | 300 | 29 | + | `./solid` | 312 | 335 | 23 | + +- The stage 2 adapter scripts no longer exist. I recreated the ones I needed + from the appendix of `review/stage-2/adapters.md` as two scripts, + `a1-timing.ts` and `adapter-checks.ts` (appendix), and ran each against both + worktrees. Their "before" output matches what stage 2 printed. + +## A1. Build the snapshot at the read, not in the listener + +**Question.** Can the Vue, Angular and Solid adapters stop building a +snapshot on every synchronous notification, and keep every behaviour their +tests pin? Adapters A1, M63, stage 1 finding 2, merged dependency 19. + +**What was changed** (`a1.patch`), three files, 75 lines added and 31 +removed. Each adapter keeps the last snapshot it handed out and a `stale` +flag. The listener only sets the flag and tells the framework that something +changed; the snapshot is built at the next read, once, however many writes +came before it. + +- **Vue** (`vue.ts`): a `customRef` whose getter tracks and builds the + snapshot if stale; the listener calls `trigger()`. Its setter does nothing. +- **Angular** (`angular.ts`): a private `version` signal bumped by the + listener, and a `computed` that reads it and builds the snapshot if stale. + The `computed` is what is returned; it is read-only by construction, so + `asReadonly()` goes. +- **Solid** (`solid.ts`): a `version` signal bumped by the listener; the + accessor reads the version and builds the snapshot when the version it sees + has moved. Because a Solid 2 signal shows a write only after `flush()`, an + imperative read straight after a write still returns the old value, exactly + as today. A first try with `createMemo` failed a test: Solid's server + runtime (which `bun test` resolves) never re-runs a memo, so a live read on + the server went stale. A plain accessor over the version signal has neither + problem. +- **Disposal.** Each adapter reads once in its cleanup, so a ref or signal + read after its scope stopped holds the last write delivered before it + stopped. That is what the pinned tests for stage 1 finding 20 expect; it + costs about 10 bytes per adapter. The `active` flags stay (A6). + +**Result.** + +- **Timing**, 2,000 direct row writes outside a method, then one read, + median of 7 (`a1-timing.ts`): + + | Attached | Before | A1 | + | -------- | -----: | -----------------------------------: | + | nothing | 1.2 ms | 1.2 ms | + | Vue | 777 ms | 2.4 ms | + | Angular | 710 ms | 2.4 ms | + | Solid | 745 ms | 2.3 ms | + | Svelte | 734 ms | 726 ms (unchanged, not in the spike) | + + Every run ended with the value current and no listener left. +- **Tests**: 1,340 pass, 1 fails. `vue.test.ts`, "returns a shallow ref + containing the current immutable snapshot": `isShallow(state)` is now + false, because a `customRef` is not a `shallowRef`. **Incidental.** The + value is a frozen snapshot, which Vue never makes deep-reactive, so the only + observable difference is `isShallow()`, and that `watch(state, cb)` now + compares values (a new snapshot is always a new object, so it fires on every + change as before). The decision document should say this may change. +- **Typecheck** passes. +- **Size**: `./vue` 324 (+44, 24 over 300), `./angular` 311 (+40, 11 over + 300), `./solid` 346 (+34, 11 over 335). The first form measured +53, +43 + and +34; folding the read into the getter saved the difference. +- **Stage 2 checks, before and after** (`adapter-checks.ts`): Vue `computed` + granularity unchanged (effect runs `whole 3, count 1, user 1`), Angular + `computed` granularity unchanged (`count 1, user 1`), Solid timing and + granularity unchanged (read straight after a write 0, effect on `user` ran + once after two unrelated writes, 0 listeners after dispose). Vue writing + the ref: before, the ref shows 99 while the store holds 0; after, the write + is ignored and the ref shows 0. Angular N1: before, the signal said + `reads 0` after a write inside a `computed`; after, it says `reads 1`, but + `console.error` still receives Angular's error, because the version bump is + itself a signal write. N1 still needs A3's `untracked()`. + +**What it changes for a user.** Nothing in the common case: a read after a +write is current in Vue and Angular, and after `flush()` in Solid, as today. +Writing the Vue ref is now a silent no-op instead of a fake value (A2 makes +it a type error too). Vue's `isShallow(ref)` is false. + +**Recommendation: do it. Can follow 1.0**, because no documented behaviour or +type changes. Taking it before 1.0 is still better: it removes the +640-millisecond case from three of five adapters, and stage 4 touches these +files for A2 and A3 anyway. + +**Cost for stage 4.** Three adapter files; one test changes +(`isShallow`); new tests per adapter: "N direct writes build one snapshot at +the read" (count `snapshot` calls through a spy or count rebuilds of a getter) +and "a read after dispose holds the last delivered value". Risk medium: the +framework suites (Vue, Angular, Solid in Playwright) must run, which I did +not. Budgets: `./vue` to about 330, `./angular` and `./solid` up by about 15, +unless A6 pays for it (see there). + +## A2. Vue: no listener after a server render, and a read-only ref + +**Question.** Can the Vue adapter stop leaking one listener per server +render (adapters V1, M64), and should the ref be typed read-only (stage 1 +finding 17, adapters V2, M65, contradiction 28)? + +**What was changed.** Three forms, each in `vue.ts` only, each with the +return type `Readonly>>`. + +1. **`a2.patch`, the stage 2 sketch** (26 added, 11 removed): a component + that is not mounted subscribes in `onMounted`, and refreshes once there; a + bare effect scope subscribes at once. +2. **The same with server detection instead** (no patch kept; it is + `a1a2-vue.patch` without the `customRef`): a component skips the + subscription when `inject(ssrContextKey)` is set, which stage 2 verified is + non-null exactly inside `renderToString`, and subscribes at once otherwise. +3. **`a1a2-vue.patch`, on top of A1** (48 added, 14 removed): A1's + `customRef`, plus server detection as in form 2. On the server it adds no + listener and its getter reads `snapshot(store)` at every read, which is a + cached lookup while the store is unchanged. + +**Result.** `adapter-checks.ts`, before and after: + +| Case | Before | Form 1 | Form 2 | Form 3 (A1 + A2) | +| ---------------------------------------------------------- | ---------------------------- | ------------------------------ | -------------- | ----------------- | +| Listeners after three `renderToString` of one module store | 1, 2, 3 | 0, 0, 0 | 0, 0, 0 | 0, 0, 0 | +| Store written in `onServerPrefetch`, then rendered (5) | `

5

` | `

0

` | `

0

` | `

5

` | +| Client: setup writes the store after the call, then mounts | first render shows 1 | first render shows 0, then 1 | shows 1 | shows 1 | +| Client: mount, write, unmount | 1 listener, updates, 0 after | the same | the same | the same | +| `state.value = {count: 99}` | compiles; ref 99, store 0 | type error; at run time ref 99 | type error; 99 | type error; ref 0 | + +The second row is the finding of this spike. `onServerPrefetch` is Vue's +documented way to load data during a server render, and it writes the store +after setup. Today the listener carries that write into the ref; forms 1 and 2 +render the setup-time value, because without a listener nothing tells the +ref. **A fix for V1 that keeps an eager `shallowRef` breaks server data +loading.** Only a ref that reads the store at the read (A1's shape) can do +without the listener and stay current. Form 1 also costs the client an extra +render when setup writes the store. + +- **Tests**: 1,341 pass with forms 1 and 2. Form 3 fails A1's one incidental + test (`isShallow`), and nothing else. +- **Typecheck** fails in `types.vue.test.ts`, two assertions that compare the + exact return type, among them the one marked `FINDING` for stage 1 finding + 17. **Fixes**: both flip because the type changed on purpose. +- **Size** of `./vue`: form 1 337 (+57), form 2 329 (+49), form 3 369 (+89, + 69 over the budget of 300). Most of the cost is the names imported from + `vue`, which stay unminified (`getCurrentInstance`, `inject`, + `ssrContextKey`, `customRef`). +- **Contradiction 28** (`Readonly` against `Readonly`). Not + settled with `tsc` against Vue 3.2.0: that version is not installed and not + in the local package cache, and I did not download it. Two things settle it + without the run. `Readonly>` uses only `Ref`, which every Vue 3 + release exports, and TypeScript's own `Readonly`, so it holds on the floor + of the peer range by construction. And with A1 the ref is a `customRef`, + which is not shallow at run time, so `ShallowRef` would be a false type. + Take `Readonly>>`. + +**What it changes for a user.** A module-level store no longer gains a +listener per request in a Vue server render. Code that assigns the ref stops +compiling. With form 3, a server render reads the store at each read, so +writes from `onServerPrefetch` still show. + +**Recommendation: do form 3, that is A2 only together with A1. Before 1.0** +for the type (it changes the documented return type `Ref>`); +the leak fix alone could follow 1.0. Do not take forms 1 or 2. + +**Cost for stage 4.** `vue.ts`, `types.vue.test.ts` (two assertions flip), +`vue.test.ts` (new: no listener under `renderToString`; a write in +`onServerPrefetch` renders; the ref refuses a write), `VUE.md` and +`API_REFERENCE.md` (return type, a sentence on server rendering). Risk +medium: run the Vue packed-app suite and a real Nuxt or Vite SSR page, which I +did not. Budget `./vue` to about 370, or 375 with room. + +## A3. Angular: `untracked()` and an `{injector}` option + +**Question.** Does `untracked()` around the signal write keep a store write +made inside a `computed` (adapters N1, M66), and can the adapter take an +`{injector}` and name itself in the error (adapters N2, M67)? + +**What was changed** (`a3.patch`, `angular.ts`, 20 added, 7 removed): +`injectClassyStore(store, options?: {injector?: Injector})`. Without an +injector it calls `assertInInjectionContext(injectClassyStore)` first, as +`toSignal` does; with one it takes `injector.get(DestroyRef)`. The listener +writes inside `untracked()`. Our own message gets the package prefix: +"@codebelt/classy-store/angular: injectClassyStore() requires a live Angular +injection context or injector". `a3-untracked-only.patch` is the one-line +`untracked()` change alone (3 added, 2 removed). + +**Result.** `adapter-checks.ts`, before and after: + +| Case | Before | A3 | +| -------------------------------------------- | ------------------------------------------- | -------------------------------------------------------------------------- | +| Called outside an injection context | NG0203 naming "The `DestroyRef` token" | NG0203 naming "injectClassyStore() can only be used…" | +| Called with `{injector}` outside a context | NG0203 | works; value current after a write; 0 listeners after `injector.destroy()` | +| Store write inside a `computed` | `console.error` once; signal says `reads 0` | no error; signal says `reads 1` | +| `computed` granularity, two unrelated writes | downstream runs `count 1, user 1` | the same | + +- **Tests**: 1,341 pass. A first wording of the message ("…a live Angular + injector") failed one test that matches `/live Angular injection context/`; + that test pins the message text only, so it is **incidental**, and the + wording above keeps it passing. +- **Typecheck** fails in `types.angular.test.ts` on the assertion of the + exact signature `(proxyStore: T) => Signal>`. **Fixes**: the + signature gains its option on purpose. +- **Size** of `./angular`: 341 (+70, 41 over 300). `untracked()` alone is 290 + (+19), inside the budget. The option, the assertion and the longer message + are the other 51. + +**What it changes for a user.** A store method that writes, called inside a +`computed` or a template expression, no longer loses its update and no longer +logs an error. `injectClassyStore` can be called from `ngOnInit` or an event +handler with `{injector: this.injector}`, and the error says which call +failed. + +**Recommendation: do it.** The `untracked()` fix **can follow 1.0** (a bug +fix, no API change). The `{injector}` option is additive, but it settles the +documented signature, so take it **before 1.0** while that is free. With A1, +the `untracked()` goes around the version bump instead (A1 alone still logs +the error, see A1). + +**Cost for stage 4.** `angular.ts`, `types.angular.test.ts` (one assertion), +`angular.test.ts` (new: write inside `computed`; `{injector}` outside a +context; the NG0203 message names our function), `ANGULAR.md`, +`API_REFERENCE.md`. Risk low. Budget `./angular` to about 345, or about 360 +with A1. + +## A4. Solid: rename `useClassyStore` to `fromClassyStore` + +**Question.** What does the rename touch (adapters Q7, M68, contradiction +27)? + +**What was changed** (`a4.patch`, six files, 30 lines changed): the export, +its error message, and every import and call in code. + +**Result.** 1,341 tests pass; the whole repository typecheck passes (package, +scoping harness, all examples, the docs site); `./solid` 314 (+2). + +**Every place the rename touches:** + +| Kind | File | Uses | +| ------------ | ------------------------------------------------------------------------------ | ---: | +| Source | `packages/classy-store/src/frameworks/solid/solid.ts` (name, message) | 2 | +| Unit test | `packages/classy-store/src/frameworks/solid/solid.test.ts` | 12 | +| Type test | `packages/classy-store/src/types.solid.test.ts` (incl. the export list) | 7 | +| Browser test | `packages/classy-store/tests/browser/solid/components/solidForm/SolidForm.tsx` | 2 | +| Browser test | `packages/classy-store/tests/browser/solid/lifecycleProbe.ts` | 5 | +| Example | `examples/solid/src/App.tsx` | 2 | +| Guide | `website/content/docs/SOLID.md` | 8 | +| Reference | `website/content/docs/API_REFERENCE.md` lines 40 and 59 | 2 | +| Overview | `website/content/docs/ABOUT.md` line 40 | 1 | +| Readme | `README.md` line 142 | 1 | +| Agent notes | `CLAUDE.md` line 29 | 1 | + +The docs are not in the patch. `ARCHITECTURE.md` describes the Solid adapter +without naming the function. `llms.txt` and the per-page Markdown are +generated from the docs. No changelog entry exists to change; one is needed. + +**What it changes for a user.** Every Solid import breaks. The library has one +user. + +**Recommendation: rename, before 1.0, or never.** The scheme the other four +adapters follow is "the framework's idiom", and in Solid `use*` means a +context lookup while `from()` is the primitive this adapter reproduces +(stage 2 O1). The Solid report's objection (contradiction 27) is that the +return type is what a Solid user expects, which is true and unaffected by the +name. The cost is the table above and a changelog line. This is the owner's +call; my lean is to rename. + +**Cost for stage 4.** The eleven files above, mechanical. Risk low; the +Solid browser suite must run. + +## A5. React: capture the first snapshot without `prepareStoreForHydration` + +**Question.** Can the React hooks get their server snapshot without the call, +as Zustand does (Zustand and Jotai finding 1, M70, "proposals I think are +wrong" item 16), captured at creation or just before the first write? What +memory does it hold, and what does a write through a raw reference do? And +P1's claim in `persist-devtools.md`, that either form is captured before +`persist()`'s first restore write. + +**What was changed.** Two forms. In both, the React entries (`./react` and +`./react/server`) register a hook in the core when they load, so an app that +does not import React pays only a null check; the capture fills the same +`WeakMap` that `prepareStoreForHydration` fills, which keeps the first +capture. + +- **Lazy, before the first write** (`a5-lazy.patch`, 6 files, 51 added, 2 + removed): a `written` flag per node; the `set` and `deleteProperty` traps + call the hook once per node before its first write, and the hook snapshots + each store root above it that has no capture yet. +- **At creation** (`a5-creation.patch`, 5 files, 42 added, 2 removed): + `createClassyStore` calls the hook, which snapshots the new store. + +**Result.** `a5-hydration.tsx`, `renderToString` and `hydrateRoot` under +happy-dom, before and after (both forms give the same output): + +| Case | Before | Either form | +| -------------------------------------------------------------------------------- | ----------------------------------------- | ---------------------------------- | +| 1. Server renders "Ada"; client loads "Ada", then a restore writes "Saved Grace" | hydration error, then shows "Saved Grace" | server HTML is `(empty)`; no error | +| 2. Server: create, `load('Ada')`, render, no prepare | `Ada` | `(empty)` | +| 3. Server: create, `load('Ada')`, `prepareStoreForHydration`, render (the guide) | `Ada` | `(empty)` | +| 4. Server: data passed to the constructor, then one write, render | the written value | the constructor's value | + +Case 1 is M70, and it is "fixed" only because both sides now render the empty +pre-load state. Cases 2 and 3 are the finding: `REACT_SSR.md` tells users to +prepare "after initializing the store with the data used to render the page", +and the first write of that loading is exactly what an automatic capture +fires on. The server then renders the store as it was before its data +arrived, and an explicit `prepareStoreForHydration` afterwards cannot correct +it, because the first capture wins. Zustand avoids this because its initial +state is whatever the creator function returned: there is no "create, then +load" in Zustand. Ours has one, and the guide uses it. + +- **Tests.** Lazy: 1,329 pass, 12 fail. At creation: 1,321 pass, 20 fail. The + unit suite runs in one process, so once a React test file has loaded the + entry, the hook is on for every later core test, which is what an app that + imports React sees. Every failure is a **regression** of the design, not of + the patch: + - `react.hydration.lifecycle.test.tsx`, "does not affect an unprepared + request store": case 2 above. + - Five tests in "what the collector can free" (both forms) and "putting a + removed subtree back": the captured snapshot keeps a replaced list or a + removed subtree alive for the life of the store. + - "reference cycles" (3 lazy, 5 at creation) and three `snapshot()` tests on + circular references (at creation): a store that refers to itself (M36) + throws on its first write (lazy) or cannot be created at all (at + creation), because the capture takes a snapshot, which throws on a cycle. + - "a store created from very deeply nested state": the capture's snapshot + recurses, so the first write at the bottom overflows the stack. + - At creation also: two "array element redefined" tests and one + `defineProperty` test, which expect no snapshot cached before their write. +- **Typecheck** passes. +- **Size**, lazy: main 3,705 (+44), `./react` adds 1,707 (+45 over its own + baseline, 7 over 1,700), `./react/server` 200 (25 over 175). At creation: + main 3,670 (+9), `./react` 1,708, `./react/server` 200. +- **Memory** (`a5-memory.ts`): ten stores of 10,000 rows each, every row + written once, one live snapshot held: 141.1 MB before, 160.2 MB with + either form, 19 MB more, about 190 bytes per row. That is the frozen copy of + every row's first state, kept for the life of the store whether or not it + is ever server-rendered. `CONSTRAINTS.md` says retained memory must not + grow; the memory suite (`tests/memory`, not run) would catch this. +- **A write through a raw reference** (stage 1 finding 11): with the lazy + form, a raw write made before the first write through the store is not + seen by any trap, so the "first" snapshot captured later already contains + it (`raw write`, where the creation form says `initial`). It cannot be + fixed without a trap on the raw object, which is what finding 11 is about. +- **P1's claim.** Correct as far as it goes: case 1 writes through the `set` + trap as `persist`'s restore does (`proxyStore[key] = …`), and the lazy form + captured before it. But the same mechanism captures before the request + data is loaded, so "capture before `persist()`'s first restore" is not + enough on its own. Without A5, P1 needs the order the guide already states: + `prepareStoreForHydration` after loading, before `persist()`. + +**What it would change for a user.** The documented server pattern renders +the empty store, with or without the call. Every store in a React app keeps +its first state for life. Stores with cycles stop working. + +**Recommendation: do not capture automatically. No change; can follow 1.0 +if a better form is found.** The merged document's item 16 called it dearer +than "not breaking" suggests; the spike shows it is breaking. What would +help instead, all additive: + +1. A sentence in `REACT_SSR.md` beside P1: with a synchronous storage, + `persist()` restores inside the call, so `prepareStoreForHydration` must + come before it. The guide's order already says so; P1 makes it matter. +2. In a development build (M72), a warning from the hooks when React reports + a recoverable hydration error for a store that was never prepared. Not + spiked. + +**`isEqual` against `equalityFn`** (Zustand and Jotai finding 2, M71, item +17). Keep `isEqual`. React's own `useSyncExternalStoreWithSelector` names the +same parameter `isEqual` (checked in the installed +`use-sync-external-store` 1.7.0); Zustand and Jotai say `equalityFn`. A +breaking rename for a split precedent buys nothing. No change, no label. + +**Cost for stage 4.** One paragraph in `REACT_SSR.md`. Nothing else. + +## A6. One guard, written once + +**Question.** Every adapter keeps an `active` flag so that a listener removed +during a delivery is not called (stage 1 finding 20, adapters A2, merged +dependency 10). Does D1 of `spike-delivery.md`, which makes the core skip a +subscriber removed during delivery, remove the need? + +**What was changed.** `d1.patch` from `spike-delivery.md` applies unchanged +to `5ab613f` (no package file changed since `216b3d1`). On top of it, +`a6-on-d1.patch` removes the four flags (4 files, 8 added, 29 removed): each +cleanup becomes the core's unsubscribe function itself, and the Svelte +`subscribe` returns the core's unsubscribe directly. Angular's +`destroyRef.destroyed` and Solid's `isDisposed(owner)` checks stay; I then +removed those two as well, to see what they still do. + +**Result.** + +- **D1 alone** reproduces its report here: 1,325 pass, the same 16 core + tests fail, main entry 3,824. +- **D1 and A6**: 1,325 pass and the same 16 fail; every adapter test passes, + including the four that pin finding 20 per adapter ("does not update a ref + whose scope is stopped during the same notification", "does not call a + subscriber removed during the same notification", "ignores delivery after + disposal during an in-progress notification", "ignores callbacks copied + before an earlier listener destroys the injector"). +- **Without the two framework checks as well**: Solid still passes + everything, so `isDisposed(owner)` can go too. Angular fails "ignores + writes from an earlier destroy callback": an `onDestroy` callback + registered before ours writes the store while our listener is still + subscribed, which is not a delivery-time removal and which D1 does not + cover. Angular's `destroyed` check stays. +- **Typecheck** passes. +- **Size**, bytes added over the main entry, D1 alone and D1 with A6: + + | Entry | D1 | D1 + A6 | Saved | + | ----------- | --: | ------: | ----: | + | `./vue` | 281 | 268 | 13 | + | `./svelte` | 180 | 164 | 16 | + | `./angular` | 272 | 258 | 14 | + | `./solid` | 312 | 298 | 14 | + + Solid's `isDisposed` check would save a few more bytes; not measured on + its own. + +**What it changes for a user.** Nothing. + +**Recommendation: yes, D1 removes the need. Do A6 if and only if D1 is +taken**, in the same change; without D1 the flags are the only guard. Can +follow 1.0 (no behaviour change). The 13 to 16 bytes per adapter pay for most +of what A1 and A3 add (see the combination). + +**Cost for stage 4.** Four adapter files, no test changes. Risk low, given D1 +and the framework suites. + +## A7. Collections: an index for snapshots and for live state, and one membership rule + +**Question.** Can lookups stop scanning the backing array, on a snapshot (the +lazy index the Valtio agent prototyped, M40 (a)) and on live state (an index +beside the array, M40 (b), contradiction 23, "proposals I think are wrong" +item 14), while keeping `identityOf()` and fixing `-0` and the constructors +(stage 1 findings 33 and 34, M39)? Measured against the `./collections` +budget of 750, which had 23 bytes free. + +**What was changed**, `collections.ts` only, three patches, each against +`5ab613f`: + +- **`a7-m39.patch`, the membership rule alone** (24 added, 15 removed). One + function, `keyOf`, gives the key a member is matched by: `identityOf()` for + an object, the value itself for a primitive, with `-0` read as `0`, as a + native `Map` and `Set` do. The scan and both constructors use it. The map + constructor now keeps the first key and the last value of a repeated key, + as a native `Map` does; it used to keep the last key too. +- **`a7a.patch`, M39 and the snapshot index** (68 added, 26 removed). A + module-level `WeakMap` from a snapshot's frozen backing array to a native + `Map` from key to position. The first lookup on a snapshot scans and marks + the array; the second builds the index, which can never go stale because + the array cannot change. Two details mattered, both found by measuring: + - Building on the first lookup made "write one key, then one lookup on the + new snapshot" 1.6 times slower (3.1 to 4.9 ms), since every write makes a + new frozen array. Building on the second lookup keeps that case at + today's cost. + - `Object.isFrozen` reads every element: about 1 ms on a frozen array of + 10,000 in Bun, twice a full scan. The spike tells a snapshot's array by + `identityOf(array) !== array` instead, which is a `WeakMap` lookup, + because every snapshot is registered with its source. +- **`a7b.patch`, the snapshot index and a live index** (134 added, 31 + removed). The same `WeakMap` also holds, for a live backing array, a `Map` + and the store version of the array it is current for, read with + `getVersion()`. It is keyed by the raw array, not stored on the instance, + so a snapshot never shares it (the problem item 14 names). The + collection's own `set`, `add` and `delete` keep it current in place (an + append adds one key; a delete moves the later keys down, which is + O(n − i) like the `splice` it follows). Any other write bumps the version + and makes the index suspect: a hit is then checked against the array in + O(1), and a miss scans as today; the index is rebuilt only when that scan + finds a member the index lacked. `withHistory` and `persist`, which replace + the backing array, give a new raw array, which simply has no index yet. + +**Result.** `a7-lookup.ts`, Bun, the median of five runs of 1,000 calls: + +| Case (10,000 members) | Before | M39 alone | `a7a` | `a7b` | +| ----------------------------------------------------- | ------: | --------: | ------: | ------: | +| live `map.get`, last string key | 44 µs | 43 µs | 40 µs | 0.42 µs | +| live `map.get`, last object key, raw | 251 µs | | 185 µs | 0.34 µs | +| live `set.has`, last number | 21 µs | 26 µs | 23 µs | 0.26 µs | +| live `set.has`, a missing number | 21 µs | | 23 µs | 0.20 µs | +| snapshot `map.get`, last string key | 481 µs | | 0.08 µs | 0.07 µs | +| snapshot `set.has`, last number | 160 µs | | 0.06 µs | 0.06 µs | +| snapshot `set.has` by raw object, last | 525 µs | | 0.04 µs | 0.04 µs | +| live `set` of a new key, then its `delete` | 496 µs | | 450 µs | 366 µs | +| live `set` of an existing key | 68 µs | | 54 µs | 0.82 µs | +| a value changed in place, then `get` of a present key | 67 µs | | | 1.7 µs | +| a value changed in place, then `get` of a missing key | 57 µs | | | 61 µs | +| `set` one key, then one `get` on the new snapshot | 3.08 ms | | 3.01 ms | 2.90 ms | + +The last row is dominated by building the snapshot itself (M35), which none +of this touches. Behaviour, before and after (all three patches): + +| Case | Before | After | +| ---------------------------------------------------------- | -------------------------- | ----------------------------------------------------------------------- | +| `get` by raw key, its proxy, its snapshot; snapshot by raw | found, found, found; found | the same | +| `new Set([0])`, then `add(-0)`: size (finding 33) | 2 | 1 | +| constructed from `[0, -0]`: size | 1 | 1 | +| constructed from `[raw, its proxy]`: size (finding 34) | 2 | 1 | +| `withHistory`: add, undo, redo | right | right | +| `_items[0] = 'z'` through the store, then `has` | right | right | +| `_items[0] = 'z'` on the raw array, outside every trap | right (`has('z')`) | M39, `a7a`: right. `a7b`: **wrong** (`has('a')` true, `has('z')` false) | + +The last row is the price of the live index. A write to the raw array is +invisible to every trap (stage 1 finding 11): today a scan reads the raw +array, so it is right anyway; a version-checked index cannot see the write. +It is the only case I found, and the public `_entries` and `_items` (M43) are +what make it reachable. + +- **Tests.** All three: 1,339 pass, 2 fail, both in the core differential + findings, "+0 and -0 are two members when added and one when constructed" + and "a collection constructed from a row and its proxy holds the row + twice". **Fixes**: they pin findings 33 and 34. A first version of `a7b` + failed two more (a getter over a collection, and the randomized + differential test) because a suspect index could point past the end of the + array after a delete; the patch has the bound check, and both pass. +- **Coverage** of `collections.ts` stays at 100% of lines and functions with + `a7b` (run with `bun test --coverage src`). +- **Typecheck** passes. +- **Size** of `./collections`, against 727 today and a budget of 750: + + | Patch | Bytes | Over 750 | + | -------- | ----: | -------: | + | `a7-m39` | 740 | — | + | `a7a` | 843 | 93 | + | `a7b` | 1,066 | 316 | + +- **Memory.** Not measured. One native `Map` per indexed array: for a live + collection for its life, for a snapshot for as long as the snapshot lives + (the `WeakMap` drops it with the array). +- **Native `Map` and `Set` (M38, contradiction 22).** Not spiked: the merged + document's run already settles 22, and every report keeps the separate + classes for 1.0. What this spike adds: the speed argument for native + storage is answered without it. A native-backed live side would still need + the array for snapshots, and it would have exactly `a7b`'s blind spot for + raw writes. + +**What it changes for a user.** M39: `-0` and `0` are one member everywhere, +and a collection built from an object and its proxy holds it once, as `add` +already did; `REACTIVE_COLLECTIONS_TUTORIAL.md` documents the opposite for +`-0` and must change. The indexes change no result, only the time, except +`a7b`'s raw-write case. + +**Recommendation.** + +- **M39 (`a7-m39`): do it. Before 1.0**, because it changes documented + behaviour. It fits the budget. +- **The snapshot index (`a7a`): do it.** Snapshot reads are what every + framework adapter renders from, and it turns 160 to 525 microseconds into + under 0.1, with no case that gets slower and no case that changes. **Can + follow 1.0.** It needs a budget of about 850. +- **The live index (`a7b`): not for 1.0. Can follow 1.0**, and only together + with M43 (the backing arrays leave the public type, so a raw write to them + is no longer something a user can reach by typing a property name). It is + 100 times faster on hits, but it costs 223 bytes more than `a7a`, a second + validity rule (store versions) that stage 4 must test against history, + persist, devtools time travel and direct writes, and one wrong answer + today's code does not give. "Their lookups are linear" is documented, so a + faster live side is additive whenever it comes. + +**Cost for stage 4.** `collections.ts`; flip the two finding tests; new tests: +`-0` in every path, a constructor with an object and its proxy, a snapshot +lookup that builds the index on the second call, a snapshot index that +survives structural sharing (an unchanged collection in a newer snapshot +reuses it). The tutorial sentence on `-0`. Budget `./collections` to about +850. + +## The combination I would recommend + +Two forms, because A6 depends on D1, which is another report's item. + +- **`combo.patch`** (9 files, 203 added, 89 removed): A1 for Vue, Angular + and Solid; A2 form 3 (Vue on the server, read-only ref); A3 (`untracked()` + around the version bump, `{injector}`, the message); A4 (the Solid rename, + code, tests and example); A7 `a7a` (M39 and the snapshot index). Not A5, + not the live index. +- **`combo-d1.patch`** (11 files, 275 added, 141 removed): the same plus + `d1.patch` and A6 on the lazy adapters. With A1, Solid's `active` flag + stays: it now also decides what the accessor returns after disposal. Vue, + Angular and Svelte lose theirs. Solid's `isDisposed(owner)` check goes (A6 + showed it is covered by D1), Angular's `destroyed` check stays. + +**Result.** + +- **Tests.** `combo`: 1,338 pass, 3 fail: the two finding tests of M39 + (**fixes**) and `isShallow` (**incidental**, A1). `combo-d1`: 1,322 pass, + 19 fail: those three and D1's 16, which `spike-delivery.md` classifies + (none a regression). +- **Typecheck** fails on three exact-signature assertions, all **fixes**: + `types.vue.test.ts` twice (the read-only ref), `types.angular.test.ts` once + (the new option). Lint: the same 2 warnings as the baseline. +- **Size**, bytes added over the main entry: + + | Entry | Today | Budget | `combo` | `combo-d1` | + | --------------- | ----: | -----: | ------: | ---------: | + | `.` (main) | 3,661 | 3,750 | 3,661 | 3,824 | + | `./collections` | 727 | 750 | 843 | 837 | + | `./vue` | 280 | 300 | 369 | 362 | + | `./svelte` | 182 | 200 | 182 | 164 | + | `./angular` | 271 | 300 | 377 | 361 | + | `./solid` | 312 | 335 | 348 | 341 | + | `./react` | 1,662 | 1,700 | 1,662 | 1,652 | + + `./react` and `./svelte` are unchanged by my items. New budgets I would + propose, each the combination plus about 3%: `./collections` 870, `./vue` + 380, `./angular` 390, `./solid` 360; `./svelte` and `./react` unchanged. +- **Benchmark** (`bun run benchmark:core`, base and `combo` back to back, + Bun, nanoseconds, the median of five runs): store read 31.8 and 32.2, + nested read 108 and 109, write 167 and 166, sync write 179 and 178, batched + write 181 and 181, snapshot read 0.164 and 0.165, forwarding Proxy read 2.06 + and 2.06. Every difference is inside the spread, as expected: `combo` + changes no core file. Node was not run (see "Not done"); for `combo-d1` the + core timings are D1's, in `spike-delivery.md`. +- **Reproductions**, `combo` and `combo-d1` alike (`adapter-checks.ts`, + `a1-timing.ts`, `solid-probe.ts`, `a7-lookup.ts`): + - 2,000 direct row writes then one read: Vue 645 to 2.4 ms, Angular 654 to + 2.5 ms, Solid 651 to 2.4 ms; Svelte unchanged at about 650 to 680 ms. + - Vue: 0 listeners after three server renders (1, 2, 3 before); an + `onServerPrefetch` write still renders; a client mount, write and unmount + as before; a write to the ref is ignored (before: shows 99). + - Angular: the NG0203 message names `injectClassyStore()`; `{injector}` + works outside a context and cleans up; a store write inside a `computed` + lands with no error (before: lost, one `console.error`). + - Solid: a read straight after a write is 0 until `flush()`, 1 after, 1 + after dispose, exactly as before; `createMemo` granularity unchanged. + - Collections: as `a7a` in A7. + +**Cost for stage 4**, in order: A7 M39 (before 1.0, small), A3 and A1 for +Angular together (the `untracked()` goes around the version bump), A1 and A2 +for Vue together, A1 for Solid with the rename, the snapshot index, then A6 +in the same change as D1. Each adapter change needs its framework's +packed-app and browser suite, which I did not run. + +## Verified and not verified + +**Run** (scripts and output above, code in the appendix): the unit suite, +the package typecheck (and for A4 the whole repository's typecheck, +examples and docs site included), `bun run size` and Biome, for every spike +alone and for both combinations; the A1 timings on all four non-React +adapters; the recreated stage 2 adapter checks (Vue server leak, +`onServerPrefetch`, client mount, writable ref, `computed` granularity; +Angular NG0203 text, `{injector}`, write inside `computed`, granularity; +Solid timing, `flush()`, dispose, granularity) against the baseline and each +spike; the A5 hydration cases with `renderToString` and `hydrateRoot` under +happy-dom, the A5 heap measurement, the raw-write case; the A7 lookup +timings and behaviour cases, including `withHistory` undo and redo and direct +writes to the backing array; coverage of `collections.ts` with `a7b`; +`d1.patch` applied to `5ab613f` reproduces its own report's 16 failures and +3,824 bytes. + +**Only read or reasoned:** + +- Vue 3.2.0 was not installed and not downloaded, so contradiction 28 is + settled by reasoning (A2), not by `tsc` on that version. +- The browser, framework, packed-app, memory and mutation suites were not + run, as the brief says. The Vue, Angular and Solid changes rest on the unit + suite under happy-dom and Bun's Solid server runtime, plus my scripts; a + real Nuxt or Vite SSR page, an Angular application and Solid in a browser + were not tried. The memory suite would likely catch A5. +- Timings are on one machine with other agents running; the A1 and A7 + differences are orders of magnitude, far outside the spread. +- A5's claim that the creation form fails the same hydration cases as the + lazy form was run; its claim that a development warning on hydration errors + would help is reasoning. +- The memory held by the A7 indexes was not measured. + +## Not done + +1. **The framework suites** for any adapter change (see above). +2. **`tsc` against Vue 3.2.0** for contradiction 28 (no download). +3. **Svelte**: A1 does not apply (the store contract hands the value over + on notify); a `createSubscriber` binding (M69) that would defer the + snapshot was not spiked. +4. **A5 alternatives**: the development warning was not built. +5. **A7**: the live index with M43 (private backing arrays) was not tried, + nor a native `Map` or `Set` subclass (M38 (c)); memory of the indexes not + measured; devtools time travel over a collection with a live index not + tested. +6. **`benchmark:core:node`** was not run: one Bun pair took about an hour + with other agents' benchmarks on the machine, and `combo` touches no core + file. **Combination benchmarks with D1** were not rerun either; D1's own timings are in + `spike-delivery.md`. My items do not touch the core except A5, which is + not recommended. + +## Appendix: patches and scripts + +Each patch applies with `git apply` to a worktree at `5ab613f`. Scripts run +with `scripts/run.sh