π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β»οΈ refactor(replica): consume the published local-replica package (#21616)
Arvin Xu280039213f3a
diff --git a/.agents/skills/store-data-structures/SKILL.md b/.agents/skills/store-data-structures/SKILL.mdindex 217698818bd..0ca8afae167 100644--- a/.agents/skills/store-data-structures/SKILL.md+++ b/.agents/skills/store-data-structures/SKILL.md@@ -11,7 +11,7 @@ Read [Zustand data structures](../zustand/references/data-structures.md) forlist/detail types, maps, reducers and shared type sources. The `zustand` skillis the automatic entry for store work.-A domain whose reads go through `@lobechat/replica` keeps its data in the same+A domain whose reads go through `local-replica` keeps its data in the sameid-keyed `<domain>Map` views, plus one `<domain>Replica` bookkeeping field perview; its resources live in a sibling `projection.ts`. See[replica-backed server data](../zustand/SKILL.md#replica-backed-server-data).diff --git a/.agents/skills/testing/references/zustand-store-action-test.md b/.agents/skills/testing/references/zustand-store-action-test.mdindex 447f40b9155..28f58079a2d 100644--- a/.agents/skills/testing/references/zustand-store-action-test.md+++ b/.agents/skills/testing/references/zustand-store-action-test.md@@ -121,7 +121,7 @@ it('should handle streaming chunks', async () => {## Fetch Hook Testing-### Replica-backed hooks (`useFetch*` over `@lobechat/replica`)+### Replica-backed hooks (`useFetch*` over `local-replica`)A replica hook returns sync flags plus a `queryKey`; the data lives in the store and is read through selectors. The engine is what the test exercises, so the SWR driver is a bare recorder: capture the registered sync, run its fetcher, fold the response through `onSuccess`, then read it back with the selector.diff --git a/.agents/skills/zustand/SKILL.md b/.agents/skills/zustand/SKILL.mdindex 14644cc89f0..938c1c87508 100644--- a/.agents/skills/zustand/SKILL.md+++ b/.agents/skills/zustand/SKILL.md@@ -1,6 +1,6 @@---name: zustand-description: 'Use for Zustand stores: state shapes and type sources, state-only stores with xActions classes, replica-backed list/detail data (@lobechat/replica), selectors, optimistic writes, and legacy slice/internal_* action composition.'+description: 'Use for Zustand stores: state shapes and type sources, state-only stores with xActions classes, replica-backed list/detail data (local-replica), selectors, optimistic writes, and legacy slice/internal_* action composition.'user-invocable: false---@@ -33,7 +33,7 @@ Actions stay out of the Zustand state. Reference: `src/store/page`.## Replica-Backed Server Data-Server lists and details the UI paints go through `@/libs/replica`, not a hand-written SWR `onSuccess` + reducer. The engine owns hydration from IndexedDB, head revalidation, paging, optimistic overlays with rollback, and scope (user + workspace) isolation. API reference: [`packages/replica/README.md`](../../../packages/replica/README.md).+Server lists and details the UI paints go through `@/libs/replica`, not a hand-written SWR `onSuccess` + reducer. The engine owns hydration from IndexedDB, head revalidation, paging, optimistic overlays with rollback, and scope (user + workspace) isolation. API reference: the [`local-replica` README](https://github.com/lobehub/local-replica#readme). The engine is maintained in [lobehub/local-replica](https://github.com/lobehub/local-replica): fix it there, publish, then bump the dependency here.1. Define the resource (`defineReplica` / `definePagedReplica`) in the store's `projection.ts`, converting server rows at the boundary.2. Add two state fields per replica: the view (`xxxMap: Record<key, TData>`) and its bookkeeping (`xxxReplica: createReplicaState()`).diff --git a/.agents/skills/zustand/references/legacy-slices.md b/.agents/skills/zustand/references/legacy-slices.mdindex 06edb516700..ebb5a8dba6d 100644--- a/.agents/skills/zustand/references/legacy-slices.md+++ b/.agents/skills/zustand/references/legacy-slices.md@@ -1,6 +1,6 @@# Legacy Slices (actions flattened into state)-Most stores still compose action classes into the Zustand state with `flattenActions`. Follow this layout only when editing one of them. New stores, and stores moving their data onto `@lobechat/replica`, use the state-only layout in [SKILL.md](../SKILL.md). Reference store: `src/store/eval` (benchmark slice).+Most stores still compose action classes into the Zustand state with `flattenActions`. Follow this layout only when editing one of them. New stores, and stores moving their data onto `local-replica`, use the state-only layout in [SKILL.md](../SKILL.md). Reference store: `src/store/eval` (benchmark slice).## Layoutdiff --git a/.github/workflows/test.yml b/.github/workflows/test.ymlindex e9e4bc1e0c3..4136491725b 100644--- a/.github/workflows/test.yml+++ b/.github/workflows/test.yml@@ -47,7 +47,7 @@ jobs:runs-on: ubuntu-latestname: Test Packagesenv:- PACKAGES: '@lobechat/file-loaders @lobechat/prompts @lobechat/model-runtime @lobechat/web-crawler @lobechat/electron-server-ipc @lobechat/utils @lobechat/context-engine @lobechat/agent-runtime @lobechat/conversation-flow @lobechat/ssrf-safe-fetch @lobechat/memory-user-memory @lobechat/types @lobechat/trpc @lobechat/app-config @lobechat/locales @lobechat/env @lobechat/builtin-tool-lobe-agent @lobechat/builtin-tool-message model-bank @lobechat/agent-gateway-client @lobechat/agent-manager-runtime @lobechat/device-gateway-client @lobechat/device-identity @lobechat/eval-dataset-parser @lobechat/eval-rubric @lobechat/fetch-sse @lobechat/heterogeneous-agents @lobechat/openapi @lobechat/replica'+ PACKAGES: '@lobechat/file-loaders @lobechat/prompts @lobechat/model-runtime @lobechat/web-crawler @lobechat/electron-server-ipc @lobechat/utils @lobechat/context-engine @lobechat/agent-runtime @lobechat/conversation-flow @lobechat/ssrf-safe-fetch @lobechat/memory-user-memory @lobechat/types @lobechat/trpc @lobechat/app-config @lobechat/locales @lobechat/env @lobechat/builtin-tool-lobe-agent @lobechat/builtin-tool-message model-bank @lobechat/agent-gateway-client @lobechat/agent-manager-runtime @lobechat/device-gateway-client @lobechat/device-identity @lobechat/eval-dataset-parser @lobechat/eval-rubric @lobechat/fetch-sse @lobechat/heterogeneous-agents @lobechat/openapi'steps:- name: Checkoutdiff --git a/package.json b/package.jsonindex c9ff8f534c9..c7723880f3a 100644--- a/package.json+++ b/package.json@@ -316,7 +316,6 @@"@lobechat/openapi": "workspace:*","@lobechat/prompts": "workspace:*","@lobechat/python-interpreter": "workspace:*",- "@lobechat/replica": "workspace:*","@lobechat/shared-tool-ui": "workspace:*","@lobechat/ssrf-safe-fetch": "workspace:*","@lobechat/tool-runtime": "workspace:*",@@ -410,6 +409,7 @@"langfuse": "^3.38.20","langfuse-core": "^3.38.20","lexical": "0.42.0",+ "local-replica": "^0.0.4","lucide-react": "^1.31.0","mammoth": "^1.12.1","marked": "^17.0.6",diff --git a/packages/replica/README.md b/packages/replica/README.mddeleted file mode 100644index b3f0a8dd91e..00000000000--- a/packages/replica/README.md+++ /dev/null@@ -1,147 +0,0 @@-# @lobechat/replica--Every list and detail the UI shows is a **replica**: a local copy of server state that paints on the first frame, then converges on the server in the background.--- **First frame from the replica.** The last confirmed value is read from persistent storage before the network answers, so a reload or a revisit never flashes a skeleton.-- **Server confirms quietly.** The head page from the network replaces the replica. Loaded pages, client-only rows and pending writes survive the replace.-- **Writes land immediately.** Optimistic overlays apply right away. A failed write rolls back to the confirmed base plus any other writes still in flight. Optimistic values never reach storage.-- **One entity, every copy.** `linkReplicaEntity` sends a patch or delete to every replica that holds the entity: the list row, the management page and the detail cache.-- **Identity-safe.** Memory and storage are partitioned by scope (user + workspace). On a scope switch the view is cleared before paint, and late results from the previous scope are dropped.--## Layers--| Entry | What it owns |-| --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `@lobechat/replica` | Core engine, framework-agnostic: resource definition, pure reducer, paging (offset / cursor, forward / backward), entity links, serialized persistence, storage adapters (see [Storage](#storage)). |-| `@lobechat/replica/zustand` | Zustand adapter: binds a resource to one location in a domain store (`recordLens`). Adds a `useSync` hook that schedules fetches through a `ReplicaSyncDriver` (`createSWRDriver` for SWR). |--The host store stays the only UI source of truth. Components read the store through their usual selectors. `useSync` only reports fetch flags (`isHydrated`, `isValidating`, `error`, `revalidate`) and never returns data.--## Usage--```ts-import { definePagedReplica, KeyValueReplicaStorage } from '@lobechat/replica';-import { createReplicaSlice, createSWRDriver, recordLens } from '@lobechat/replica/zustand';--const topicList = definePagedReplica<Params, Topic, number, TopicPage>({- key: ({ agentId }) => `agent_${agentId}`,- name: 'topicList',- paging: { direction: 'forward', getId: (t) => t.id, mode: 'offset', persist: { pages: 1 } },- query: ({ sortBy }) => ({ sortBy }), // query identity beyond the key- scope, // ReplicaScope: { get, use, canPersist }- storage: (namespace) => new KeyValueReplicaStorage({ namespace, store }), // see Storage- version: 1,-});--const slice = createReplicaSlice(topicList, {- driver: createSWRDriver({ mutate, useSWR }),- fetcher: fetchTopicPage, // (params, cursor) => { items, total?, nextCursor? }- get,- set,- stateKey: 'topicListReplica', // bookkeeping slot: createReplicaState()- view: recordLens('topicDataMap'), // where the rendered value lives-});--slice.useSync(params); // in a component: hydrate, then sync-slice.loadMore(key);-slice.optimistic(key, apply, serverCall);-```--A persisted read is asynchronous, so a list hydrated only by `useSync` paints its loading state for a few frames on a cold start. When that list must paint without a skeleton, seed it from the route loader before the route commits: `slice.ensureScope(scope)` + `slice.hydrate(params, scope)`, bounded by `settleWithin(hydrate, ms)` so a stalled storage never holds the route back. A later `useSync` hydrate is a no-op once the slot is filled.--A persisted row is only rewritten when its value changes: a persist whose value is deep-equal to what the engine last wrote to (or hydrated from) that row is skipped, so an unchanged revalidation costs no storage write. A failed write, a delete, an entity patch, an eviction or a `clear()` forgets what the row holds, so the next persist writes it again. The engine only tracks its own writes: a row changed behind it (another tab) is corrected by the next changed value or the next session.--## Storage--A resource persists through any `ReplicaStorage` (`get` / `getStrict` / `set` / `remove`; see [Invalidation](#invalidation) for the failure contract). Two adapters ship with the package, both keyed `<namespace>:<scope>:<queryKey>`:--| Adapter | Backing | Use |-| ---------------------------- | ----------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |-| `KeyValueReplicaStorage` | Any async key-value store `{ get, set, delete, initialize? }`: an IndexedDB object store, SQLite over IPC β¦ | Lists and details of any size. Rows are stored as objects, so the store decides what it can clone. |-| `LocalStorageReplicaStorage` | `window.localStorage` through a codec (JSON by default; pass superjson or similar for `Date`, `Map` β¦) | Small values that must paint inside pre-paint initialization: `getSync(key)` reads a row without yielding a frame. |--Both reject failed writes and deletes and implement `getStrict`, so every destructive pass works on them. Outside a browser `LocalStorageReplicaStorage` is a no-op miss.--## Fetching without a mounted view--`slice.revalidate(key)` only re-runs the `useSync` queries that are mounted. A store that needs the data while no view is mounted β a hover prefetch, a refresh after a mutation on a route without the list β calls `slice.fetch(params)` instead of calling the service and `replace` by hand:--```ts-const { applied, data, missing } = await slice.fetch(params); // joins a request in flight-await slice.fetch(params, { fresh: true }); // after a mutation: new request, retires older ones-```--Every head response, from `useSync` or `fetch`, goes through one settle pipeline. A request captures its scope, the `clear()` generation, the entry's removal generation and its query when it starts. The response is dropped when any of them moved on (identity switch, `clear()`, `remove` / a pruned entity, a view now showing another query) or when a newer response for the entry already applied. Otherwise it is folded in with `replace`; an `isMissing` answer removes the entry, and an `isMissing` answer captured under a scope the store has since left purges that scope's row instead. `fetch` resolves `{ applied, data, missing }` and rejects when the request fails.--- **Dedupe.** `fetch` joins a request already in flight for the same entry, whether a `useSync` or another `fetch` started it. The request settles once, so effects do not run twice. `{ fresh: true }` starts a new request and retires the older ones, because those may still hold the pre-mutation value.-- **Captured scope.** A flow that fans out from an earlier response (a warmup fetching replies for the roots it got) passes `{ scope }` captured at its start. Each step then settles into that scope. Once the scope is no longer active, `fetch` rejects with `ReplicaScopeChangedError` and sends no request, because the request would read the new identity's data under the old identity's label.-- **Driver cache.** After `fetch` applies a response, it seeds the driver's cache under the sync key (`driver.seed`; for SWR that is `mutate(key, data, { revalidate: false })`). It skips the seed while a `useSync` request for that key is in flight: SWR discards an in-flight request that a write overtakes, so seeding then would drop that request's newer response. SWR still revalidates a later mount unless the sync sets `revalidateIfStale: false`. The value is already in the store, so that revalidation only confirms it.-- **Effects.** Side effects that every response needs go on the slice, not on one view's callbacks:-- ```ts- createReplicaSlice(resource, {- effects: {- onApplied: (data, params, ctx) => {}, // folded into the active scope- onMissing: (params, ctx) => {}, // `isMissing`, removed from the active scope- onPurge: (params, ctx) => {}, // `isMissing` captured under a scope left behind- onError: (error, params, { isActive, key, scope }) => {},- },- isMissing: (data) => data === null,- // β¦- });- ```-- They run for `useSync` responses and `fetch` responses alike. A `useSync` request settles on its own response even when the hook has moved to another key and the driver skips its callback. `useSync`'s per-call `onSuccess` / `onError` remain for UI callbacks of that one view, and `onSuccess` is skipped for a key the hook has left.--Use `revalidate` when the views that show the data are mounted and should refetch on their own schedule. Use `fetch` when the caller needs the data now, needs to know whether it applied, or may run with nothing mounted.--## Invalidation--Persisted rows are kept per entry key **and** per query (`key?<query>`), so a resource can hold several rows for one key. Never delete through a plain `set` or by clearing SWR keys: the persisted rows survive and a reload paints the deleted data. Use the primitive that matches what is gone:--| What is gone | Call | What it does |-| --------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| One entity (a deleted topic, file, memory) | `linkReplicaEntity(...).remove(id)` / `slice.removeEntity(id)` | Drops it from every loaded entry and from persisted rows of unloaded entries. A value hydrated later β even by a read already in flight β comes back without it until a server value holds it again; if the persisted patch does not land (untrusted scope, unreadable storage), the guard stays for the session. |-| One entry key, under every filter / sort | `slice.remove(key)` | Drops the entry and every persisted query variant of the key. No variant hydrates again until a server `replace` for the key supersedes the removal. |-| The whole resource ("delete all", a reset) | `slice.clear()` / `linkReplicaEntity(...).clear()` | Empties memory in one commit, deletes every persisted row and the index of the active scope, and drops hydrates and `useSync` responses that started before it. Resolves `true` once storage is purged. |-| The whole resource for a scope that is no longer active (an account switched away mid-"delete all") | `slice.clearScope(scope)` | Deletes every persisted row and the index of `scope` behind the writes this session already queued for it; memory (another scope's, on screen) is untouched. For the active scope it is `clear()`. Resolves `true` once storage is purged. |--`slice.updateEntity(id, (item) => undefined)` also drops the entity from loaded values and persisted rows, but it is a plain patch: only `removeEntity` (which `linkReplicaEntity.remove` and an optimistic `'remove'` call) guards hydrates already in flight.--A `ReplicaStorage` must reject from `remove` when a delete did not land, and must implement `getStrict` (a read that rejects on I/O failure) for any destructive pass to succeed: `remove(key)` variant scans, `clear()`, off-scope purges, entity patches of unloaded rows and evictions all read through it, so an unreadable index fails the pass instead of passing for an empty one. A storage without `getStrict` still hydrates and persists, but every destructive pass fails: `clear()` resolves `false`, a removal stays unpurged and is retried, an entity guard is kept. `get` and `set` stay best-effort. The engine then keeps the row indexed and the removal unpurged, so the next `remove(key)` / `clear()` retries it.--Prefer the narrowest call: an entity delete keeps the rest of every list; `remove(key)` is for a key whose whole value is gone or denied (NOT_FOUND / FORBIDDEN); `clear()` is for flows that invalidate everything the user has of that resource. `clear()` does not refetch: mounted views show their loading state until the next sync, so call `slice.revalidate()` after it when the server still has data to show.--## Bounding persisted query variants--Every distinct key + query a resource persists is its own row, so a resource keyed (or queried) by free text β a search, a market filter, a per-topic bundle β would grow storage with every query the user ever ran. Opt in to a cap instead of hand-rolling a recency window around `remove`:--```ts-const searchList = defineReplica<Params, Result>({- key: ({ keyword }) => keyword,- name: 'search',- persist: { maxEntries: 20 }, // at most 20 persisted rows per scope- // β¦-});-```--- **What counts.** Persisted storage keys per scope: each `key?query` row counts once.-- **Recency.** A hydrate, a persist, or an unchanged revalidation whose write is skipped marks the row as used. The order is kept in the per-scope index (oldest first), so it survives reloads. Rows an unbounded release indexed keep their append order.-- **Eviction.** Past the cap, the oldest rows go: the row, its index entry, and the memory entry that answers it. An evicted entry is a cache miss. A revisit fetches it again; it is not a removal and does not block hydrates the way `remove` does.-- **Never evicted.** A row with a mounted `useSync` (pinned for as long as it is mounted), an entry with pending optimistic writes, and an entry with a `loadMore` in flight. A view that renders an entry without `useSync` pins it with `slice.retain(key, storageKey)`, which returns the release.-- **Failure.** A failed delete stays indexed and is picked again on the next use. An unreadable index (see `getStrict`) evicts nothing.--## Transcripts and other irregular pages--Message-like resources page backward by cursor, with windows whose length changes on every refresh. The paging config covers them:--| Option / API | Use |-| ------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |-| `paging.isCursorable(item)` | Skip synthetic rows (group / summary nodes) when pinning the join anchor or deriving a cursor. A head refresh replaces the head page's synthetic rows by id. |-| `paging.deriveCursor(item)` | Plain lists whose server reports no `nextCursor`: the next cursor comes from the oldest eligible row. Only for rows with a lossless position. |-| `paging.sort` | Stable: rows the comparator ties keep server order. Compare positions only. |-| `persistKey(key)` | Entries that stay in memory (no hydrate, no persist), e.g. scoped buckets. |-| `slice.update(key, fn, { persist: false })` + `slice.persist(key)` | Stream into memory, then persist the confirmed value once. |-| `splitPagedLens({ itemsField, metaField, derive })` | Keep raw rows where readers expect them, paging bookkeeping beside them, and derived fields (a parsed display list) in the same commit. |--`useSync(params, options)` forwards a sync schedule (`refreshInterval`, `dedupingInterval`, `revalidateIfStale`, `revalidateOnFocus`, β¦) to the driver, and runs `onSuccess` / `onError` side effects after a response is folded in (resource-wide side effects belong in the slice `effects`, see above). On a cold start with no network (offline / slow), `onHydrated` runs the same "success" handling off the persisted value the hydrate paints, since there is no response for `onSuccess` to run on.diff --git a/packages/replica/package.json b/packages/replica/package.jsondeleted file mode 100644index f815cbef01f..00000000000--- a/packages/replica/package.json+++ /dev/null@@ -1,39 +0,0 @@-{- "name": "@lobechat/replica",- "version": "0.0.1",- "private": true,- "description": "Local-first replicas: paint the last known state on the first frame, reconcile with the server in the background",- "exports": {- ".": {- "types": "./src/index.ts",- "default": "./src/index.ts"- },- "./zustand": {- "types": "./src/zustand/index.ts",- "default": "./src/zustand/index.ts"- }- },- "main": "./src/index.ts",- "types": "./src/index.ts",- "scripts": {- "test": "vitest",- "test:coverage": "vitest --coverage --silent='passed-only'"- },- "dependencies": {- "fast-deep-equal": "^3.1.3"- },- "devDependencies": {- "@testing-library/react": "^16.3.2",- "swr": "^2.5.0",- "zustand": "5.0.4"- },- "peerDependencies": {- "react": ">=18",- "zustand": ">=4"- },- "peerDependenciesMeta": {- "zustand": {- "optional": true- }- }-}diff --git a/packages/replica/src/core/defineReplica.ts b/packages/replica/src/core/defineReplica.tsdeleted file mode 100644index ab88d1f935e..00000000000--- a/packages/replica/src/core/defineReplica.ts+++ /dev/null@@ -1,165 +0,0 @@-import type { ReplicaPagedData, ReplicaPageResult, ReplicaPagingConfig } from './paging';-import type { ReplicaResource, ReplicaScope, ReplicaStorage } from './types';--/** Persisted row key: one row per entry key and query. */-export const replicaStorageKey = (key: string, query?: string) => (query ? `${key}?${query}` : key);--/**- * Whether `storageKey` is a persisted row of entry `key`, under any query.- *- * Entry keys are free-form, so a `?` prefix alone cannot tell `foo` + a query- * from a plain entry `foo?bar`. A row only counts as a variant when it is- * exactly `replicaStorageKey(key, query)` for a query this module could have- * written: the rest after `key?` must be a canonical `stableQueryKey` (it- * parses as JSON and serializes back to itself). Row keys and the index keep- * their existing flat format, so rows already persisted on devices match the- * same way.- */-export const isReplicaStorageKeyOf = (storageKey: string, key: string): boolean => {- if (storageKey === key) return true;- if (!storageKey.startsWith(`${key}?`)) return false;- const query = storageKey.slice(key.length + 1);- try {- return stableQueryKey(JSON.parse(query)) === query;- } catch {- return false;- }-};--/** Deterministic JSON: sorted keys, `undefined` dropped. */-export const stableQueryKey = (value: unknown): string =>- JSON.stringify(value, (_key, item) =>- item && typeof item === 'object' && !Array.isArray(item)- ? Object.fromEntries(- Object.keys(item)- .sort()- .filter((key) => item[key] !== undefined)- .map((key) => [key, item[key]]),- )- : item,- ) ?? '';--/**- * A fixed identity partition. The default for apps without accounts; an app- * with sign-in passes a scope derived from the signed-in user / workspace so- * one browser profile never mixes two identities' rows.- */-export const staticReplicaScope = (scope = 'default'): ReplicaScope => ({- canPersist: () => true,- get: () => scope,- use: () => scope,-});--const DEFAULT_SCOPE = staticReplicaScope();--/** Builds the storage of one resource from its namespace (`replica:<name>:v<version>`). */-export type ReplicaStorageFactory<TData> = (namespace: string) => ReplicaStorage<TData> | undefined;--export interface DefineReplicaOptions<TParams, TData, TFetched = TData, TCursor = any> {- /** Default network fetcher; a store binding may override it. */- fetcher?: (params: TParams, cursor?: TCursor) => Promise<TFetched>;- /** Entry identity inside one scope (memory bucket + persisted row). */- key: (params: TParams) => string;- name: string;- paging?: ReplicaPagingConfig<any, TCursor>;- /**- * Bound what the resource keeps in storage. `maxEntries` caps the persisted- * rows (storage keys: one per entry key and query) per scope; past it the- * least recently used rows are evicted β their persisted row, index entry- * and, when nothing holds it, their memory entry. Use rows (a hydrate or a- * persist, including a skipped unchanged one) count as recent, and the order- * lives in the persisted index, so it survives reloads. A row on screen (a- * mounted `useSync`, see `retain`), with pending optimistic writes or a- * `loadMore` in flight is never evicted. Unbounded by default.- */- persist?: { maxEntries?: number };- /**- * Entries that never touch storage (no hydrate, no persist) β e.g. scoped- * buckets whose rows must not land under an ordinary entry. Defaults to all.- */- persistKey?: (key: string) => boolean;- /**- * Query identity beyond `key` (filters, sort, page size) β anything that- * changes the rows without changing the key. Persisted rows are kept per- * query, so a projection taken under other filters never hydrates; in memory- * a query change resets loaded pages.- */- query?: (params: TParams) => unknown;- /** Identity partition of memory and persisted rows. Defaults to one static scope. */- scope?: ReplicaScope;- /** Persisted copy of the replica. Omit for a memory-only replica (no first-frame paint). */- storage?: ReplicaStorage<TData> | ReplicaStorageFactory<TData>;- /**- * Query-cache key of the network sync, for a resource adopting an existing- * key that other code already revalidates by. Defaults to `replicaKeys.sync`.- * With a custom key, revalidate through that key β `slice.revalidate` only- * matches default keys.- */- syncKey?: (params: TParams) => readonly unknown[];- /** Bump to invalidate every persisted row written by older shapes. */- version: number;-}--export const defineReplica = <TParams, TData, TFetched = TData, TCursor = any>(- options: DefineReplicaOptions<TParams, TData, TFetched, TCursor>,-): ReplicaResource<TParams, TData, TFetched, TCursor> => {- const namespace = `replica:${options.name}:v${options.version}`;- const storage =- typeof options.storage === 'function' ? options.storage(namespace) : options.storage;-- return {- fetcher: options.fetcher,- key: options.key,- maxPersistedEntries: options.persist?.maxEntries,- name: options.name,- namespace,- paging: options.paging,- persistKey: options.persistKey ?? (() => true),- persisted: !!storage,- query: (params) => (options.query ? stableQueryKey(options.query(params)) : undefined),- storageKey: (params) =>- replicaStorageKey(- options.key(params),- options.query ? stableQueryKey(options.query(params)) : undefined,- ),- scope: options.scope ?? DEFAULT_SCOPE,- syncKey: options.syncKey,- storage,- version: options.version,- };-};--export interface DefinePagedReplicaOptions<TParams, TItem, TCursor> extends Omit<- DefineReplicaOptions<- TParams,- ReplicaPagedData<TItem, TCursor>,- ReplicaPageResult<TItem, TCursor>- >,- 'fetcher' | 'paging' | 'storage'-> {- /** `cursor` is `undefined` for the head page. */- fetchPage?: (- params: TParams,- cursor: TCursor | undefined,- ) => Promise<ReplicaPageResult<TItem, TCursor>>;- paging: ReplicaPagingConfig<TItem, TCursor>;- storage?: ReplicaStorage<any> | ReplicaStorageFactory<any>;-}--/**- * A resource whose value is a paged list ({@link ReplicaPagedData}). The- * store view type may extend the paged shape with domain fields.- */-export const definePagedReplica = <- TParams,- TItem,- TCursor = number,- TData extends ReplicaPagedData<TItem, TCursor> = ReplicaPagedData<TItem, TCursor>,->(- options: DefinePagedReplicaOptions<TParams, TItem, TCursor>,-): ReplicaResource<TParams, TData, ReplicaPageResult<TItem, TCursor>, TCursor> =>- defineReplica<TParams, TData, ReplicaPageResult<TItem, TCursor>, TCursor>({- ...options,- fetcher: options.fetchPage,- storage: options.storage as ReplicaStorage<TData> | ReplicaStorageFactory<TData> | undefined,- });diff --git a/packages/replica/src/core/engine.persistence.test.ts b/packages/replica/src/core/engine.persistence.test.tsdeleted file mode 100644index 0c54f185887..00000000000--- a/packages/replica/src/core/engine.persistence.test.ts+++ /dev/null@@ -1,730 +0,0 @@-import { renderHook } from '@testing-library/react';-import { describe, expect, it, vi } from 'vitest';-import { createStore } from 'zustand/vanilla';--import { testDriver } from '../../tests/testDriver';-import { createReplicaSlice, recordLens } from '../zustand/createReplicaSlice';-import { defineReplica } from './defineReplica';-import { createReplicaEngine, REPLICA_INDEX_KEY, type ReplicaStorePort } from './engine';-import { arrayEntity } from './entityAdapters';-import { createReplicaState } from './reducer';-import type { ReplicaRow, ReplicaScope, ReplicaState, ReplicaStorage } from './types';--interface Item {- id: string;-}--const SCOPE = 'u1';-const scopeState = { current: SCOPE, trusted: true };-const scope: ReplicaScope = {- canPersist: () => scopeState.trusted,- get: () => scopeState.current,- use: () => scopeState.current,-};--const flush = () => new Promise((resolve) => setTimeout(resolve, 0));-const item = (id: string): Item => ({ id });--/**- * In-memory storage keyed like the app adapters. `strict: false` builds a- * legacy adapter without `getStrict`; `failReads` makes reads of the listed row- * keys fail the way the app adapters do (`get` swallows into a miss,- * `getStrict` rejects).- */-const createStorage = ({ strict = true }: { strict?: boolean } = {}) => {- const rows = new Map<string, ReplicaRow<any>>();- const failReads = new Set<string>();- const failRemoves = new Set<string>();- const failSets = new Set<string>();- const writes: string[] = [];- const id = ({ queryKey, scope }: { queryKey: string; scope: string }) => `${scope}|${queryKey}`;- const storage: ReplicaStorage<any> = {- get: async (key) => (failReads.has(key.queryKey) ? undefined : rows.get(id(key))),- remove: async (key) => {- if (failRemoves.has(key.queryKey)) throw new Error('delete failed');- rows.delete(id(key));- },- set: async (key, row) => {- if (failSets.has(key.queryKey)) throw new Error('write failed');- writes.push(key.queryKey);- rows.set(id(key), row);- },- };- if (strict)- storage.getStrict = async (key) => {- if (failReads.has(key.queryKey)) throw new Error('read failed');- return rows.get(id(key));- };- const index = () => (rows.get(`${SCOPE}|${REPLICA_INDEX_KEY}`)?.data as string[]) ?? [];- const dataKeys = () =>- [...rows.keys()]- .filter((key) => !key.endsWith(REPLICA_INDEX_KEY))- .map((key) => key.slice(SCOPE.length + 1))- .sort();- return { dataKeys, failReads, failRemoves, failSets, index, rows, storage, writes };-};--/** Minimal host: a record of views plus the bookkeeping slot. */-const createHost = <T>() => {- let state: ReplicaState<T> = createReplicaState<T>();- let view: Record<string, T> = {};- const port: ReplicaStorePort<T> = {- commit: (writes, next) => {- for (const write of writes) {- if ('type' in write) view = {};- else if (write.data === undefined) {- const { [write.key]: _dropped, ...rest } = view;- view = rest;- } else view = { ...view, [write.key]: write.data };- }- state = next;- },- getState: () => state,- keys: () => Object.keys(view),- read: (key) => view[key],- };- return { port, state: () => state, view: () => view };-};--type ListParams = { id: string; q?: string };--const setupList = (- storage: ReturnType<typeof createStorage>,- { maxEntries }: { maxEntries?: number } = {},-) => {- const resource = defineReplica<ListParams, Item[]>({- key: ({ id }) => id,- name: 'list',- persist: { maxEntries },- query: ({ q }) => ({ q }),- scope,- storage: storage.storage,- version: 1,- });- const host = createHost<Item[]>();- const engine = createReplicaEngine(resource, {- entity: arrayEntity<Item>((entry) => entry.id),- port: host.port,- });- return { engine, host, resource };-};--const resetScope = () => {- scopeState.current = SCOPE;- scopeState.trusted = true;-};--describe('destructive passes need a strict read', () => {- it('fails a clear on a legacy storage without getStrict instead of reporting success', async () => {- resetScope();- const storage = createStorage({ strict: false });- const first = setupList(storage);- first.engine.replace({ id: 'a' }, [item('1')]);- first.engine.replace({ id: 'b' }, [item('2')]);- await flush();- // The index row cannot be read on this device: `get` swallows it into a miss.- storage.failReads.add(REPLICA_INDEX_KEY);-- // A fresh session only knows the rows through the index.- const { engine } = setupList(storage);- expect(await engine.clear()).toBe(false);- expect(storage.dataKeys()).toEqual(['a?{}', 'b?{}']);- // Hydration stays off while the wipe is incomplete.- expect(await engine.hydrate({ id: 'a' })).toBe(false);- });-- it('keeps a removal of a legacy storage unpurged, so every later removal retries it', async () => {- resetScope();- const storage = createStorage({ strict: false });- const first = setupList(storage);- first.engine.replace({ id: 'a', q: 'x' }, [item('1')]);- await flush();-- const { engine } = setupList(storage);- expect(engine.remove('a')).toBe(true);- await flush();- // The variant is only known through the index, which cannot be read strictly.- expect(storage.dataKeys()).toEqual(['a?{"q":"x"}']);- // Not marked purged: the next removal is dispatched again rather than a no-op.- expect(engine.remove('a')).toBe(true);- });-- it('never rewrites an unreadable index as just the new key, and retries the append', async () => {- resetScope();- const storage = createStorage();- const first = setupList(storage);- first.engine.replace({ id: 'a' }, [item('1')]);- first.engine.replace({ id: 'b' }, [item('2')]);- await flush();- expect(storage.index()).toEqual(['a?{}', 'b?{}']);-- const { engine } = setupList(storage);- storage.failReads.add(REPLICA_INDEX_KEY);- engine.replace({ id: 'c' }, [item('3')]);- await flush();- // The earlier session's keys survive the failed read.- expect(storage.index()).toEqual(['a?{}', 'b?{}']);-- storage.failReads.delete(REPLICA_INDEX_KEY);- engine.replace({ id: 'c' }, [item('3'), item('4')]);- await flush();- expect(storage.index()).toEqual(['a?{}', 'b?{}', 'c?{}']);- });-});--describe('removeEntity keeps its guard until the persisted patch lands', () => {- /** A session that persisted `b` (holding entity `1`), then a fresh engine. */- const persistedB = async () => {- const storage = createStorage();- const first = setupList(storage);- first.engine.replace({ id: 'b' }, [item('1'), item('2')]);- await flush();- return { storage, ...setupList(storage) };- };-- it('a failed index read keeps the guard, so a later hydrate strips the entity', async () => {- resetScope();- const { engine, host, storage } = await persistedB();- const errors = vi.spyOn(console, 'error').mockImplementation(() => {});- storage.failReads.add(REPLICA_INDEX_KEY);-- engine.removeEntity('1');- await flush();- // The unloaded row still holds the deleted entityβ¦- expect(storage.rows.get(`${SCOPE}|b?{}`)?.data).toEqual([item('1'), item('2')]);-- // β¦but a hydrate that starts long after the failed patch never paints it.- expect(await engine.hydrate({ id: 'b' })).toBe(true);- expect(host.view().b).toEqual([item('2')]);- errors.mockRestore();- });-- it('an untrusted scope keeps the guard, and a later successful removal releases it', async () => {- resetScope();- const { engine, host, storage } = await persistedB();- scopeState.trusted = false;-- engine.removeEntity('1');- await flush();- expect(storage.rows.get(`${SCOPE}|b?{}`)?.data).toEqual([item('1'), item('2')]);- expect(await engine.hydrate({ id: 'b' })).toBe(true);- expect(host.view().b).toEqual([item('2')]);-- // Once trusted, a repeated removal of an unloaded row lands its patch.- scopeState.trusted = true;- const fresh = setupList(storage);- fresh.engine.removeEntity('1');- await flush();- expect(storage.rows.get(`${SCOPE}|b?{}`)?.data).toEqual([item('2')]);- });-});--describe('removeEntity in a scope left behind', () => {- it("drops the entity from that scope's rows without touching the active view", async () => {- resetScope();- const storage = createStorage();- const first = setupList(storage);- first.engine.replace({ id: 'b' }, [item('1'), item('2')]);- await flush();-- // The UI moved to another scope, which shows its own `b`.- scopeState.current = 'u2';- const { engine, host } = setupList(storage);- engine.replace({ id: 'b' }, [item('1'), item('9')]);- await flush();-- // A late "gone" for entity 1, answered for the scope left behind.- engine.removeEntity('1', { scope: SCOPE });- await flush();-- // That scope's persisted row loses it; the scope on screen keeps its own.- expect(storage.rows.get(`${SCOPE}|b?{}`)?.data).toEqual([item('2')]);- expect(host.view().b).toEqual([item('1'), item('9')]);- resetScope();- });-});--describe('redundant persist writes', () => {- const rowWrites = (storage: ReturnType<typeof createStorage>, queryKey: string) =>- storage.writes.filter((key) => key === queryKey).length;-- it('skips a revalidation whose value equals what this session persisted', async () => {- resetScope();- const storage = createStorage();- const { engine } = setupList(storage);- engine.replace({ id: 'a' }, [item('1')]);- await flush();- // A fresh but deep-equal response.- engine.replace({ id: 'a' }, [item('1')]);- await flush();- expect(rowWrites(storage, 'a?{}')).toBe(1);-- engine.replace({ id: 'a' }, [item('1'), item('2')]);- await flush();- expect(rowWrites(storage, 'a?{}')).toBe(2);- });-- it('skips a revalidation equal to the row it hydrated, and writes one that differs', async () => {- resetScope();- const storage = createStorage();- storage.rows.set(`${SCOPE}|a?{}`, { data: [item('1')], updatedAt: 1 });- storage.rows.set(`${SCOPE}|b?{}`, { data: [item('old')], updatedAt: 1 });- const { engine } = setupList(storage);- await engine.hydrate({ id: 'a' });- await engine.hydrate({ id: 'b' });-- engine.replace({ id: 'a' }, [item('1')]);- engine.replace({ id: 'b' }, [item('new')]);- await flush();- expect(rowWrites(storage, 'a?{}')).toBe(0);- expect(rowWrites(storage, 'b?{}')).toBe(1);- });-- it('writes again after a failed write, a removal or a clear', async () => {- resetScope();- const storage = createStorage();- const { engine } = setupList(storage);- storage.failSets.add('a?{}');- engine.replace({ id: 'a' }, [item('1')]);- await flush();- storage.failSets.delete('a?{}');- engine.replace({ id: 'a' }, [item('1')]);- await flush();- expect(storage.rows.get(`${SCOPE}|a?{}`)?.data).toEqual([item('1')]);-- engine.remove('a');- await flush();- expect(storage.rows.has(`${SCOPE}|a?{}`)).toBe(false);- engine.replace({ id: 'a' }, [item('1')]);- await flush();- expect(storage.rows.get(`${SCOPE}|a?{}`)?.data).toEqual([item('1')]);-- expect(await engine.clear()).toBe(true);- engine.replace({ id: 'a' }, [item('1')]);- await flush();- expect(storage.rows.get(`${SCOPE}|a?{}`)?.data).toEqual([item('1')]);- });-- it('does not count an unconfirmed write as stored: a dropped write is retried', async () => {- resetScope();- const storage = createStorage();- const { engine } = setupList(storage);- // The first write of the row is slow, then fails (an aborted transaction).- let failFirst!: () => void;- const { set } = storage.storage;- let held = true;- storage.storage.set = (key, row) =>- held && key.queryKey === 'a?{}'- ? ((held = false),- new Promise<void>((_, reject) => (failFirst = () => reject(new Error('aborted')))))- : set(key, row);-- engine.replace({ id: 'a' }, [item('1')]);- await flush();- // A deep-equal revalidation while that write is still in flight.- engine.replace({ id: 'a' }, [item('1')]);- await flush();- failFirst();- await flush();-- // The second persist was not skipped: the row holds the value.- expect(storage.rows.get(`${SCOPE}|a?{}`)?.data).toEqual([item('1')]);-- // Once a write is confirmed, an equal revalidation is skipped again.- const writes = rowWrites(storage, 'a?{}');- engine.replace({ id: 'a' }, [item('1')]);- await flush();- expect(rowWrites(storage, 'a?{}')).toBe(writes);- });-- it('writes again after an entity patch rewrote the row behind it', async () => {- resetScope();- const storage = createStorage();- const { engine } = setupList(storage);- engine.replace({ id: 'a' }, [item('1'), item('2')]);- // The entry moves on to another query: the first row is no longer loaded.- engine.replace({ id: 'a', q: 'x' }, [item('2')]);- await flush();-- engine.updateEntity<Item>('1', () => ({ id: '1', renamed: true }) as Item);- await flush();- expect(storage.rows.get(`${SCOPE}|a?{}`)?.data).toEqual([- { id: '1', renamed: true },- item('2'),- ]);-- // Back to the first query with the original value: the row must be rewritten.- engine.replace({ id: 'a' }, [item('1'), item('2')]);- await flush();- expect(storage.rows.get(`${SCOPE}|a?{}`)?.data).toEqual([item('1'), item('2')]);- });-});--describe('clearScope purges an inactive scope behind its queued writes', () => {- it('purges a row and index entry whose writes were still queued, and leaves the active scope alone', async () => {- resetScope();- const storage = createStorage();- const { engine, host } = setupList(storage);- // The previous user's row write is still in flight when the purge starts.- let release!: () => void;- const held = new Promise<void>((resolve) => (release = resolve));- const { set } = storage.storage;- storage.storage.set = async (key, row) => {- if (key.scope === SCOPE && key.queryKey === 'a?{}') await held;- return set(key, row);- };- engine.replace({ id: 'a' }, [item('deleted')]);-- // The account switches; the new user paints and persists its own row.- scopeState.current = 'u2';- engine.replace({ id: 'b' }, [item('active')]);- await flush();-- const purging = engine.clearScope(SCOPE);- release();- await expect(purging).resolves.toBe(true);- await flush();-- expect(storage.rows.has(`${SCOPE}|a?{}`)).toBe(false);- expect(storage.index()).not.toContain('a?{}');- // The active user's view and row are untouched.- expect(host.view().b).toEqual([item('active')]);- expect(storage.rows.get('u2|b?{}')?.data).toEqual([item('active')]);- resetScope();- });-- it('is clear() for the active scope', async () => {- resetScope();- const storage = createStorage();- const { engine, host } = setupList(storage);- engine.replace({ id: 'a' }, [item('1')]);- await flush();-- await expect(engine.clearScope(SCOPE)).resolves.toBe(true);-- expect(host.view()).toEqual({});- expect(storage.dataKeys()).toEqual([]);- });-});--describe('entity changes confirmed for a captured scope', () => {- it('removeEntity({ scope }) patches only that scopeβs rows, leaving the active view alone', async () => {- resetScope();- const storage = createStorage();- const { engine, host } = setupList(storage);- engine.replace({ id: 'a' }, [item('1'), item('2')]);- await flush();-- // The account switches; the new one shows a list holding the same id.- scopeState.current = 'u2';- engine.replace({ id: 'b' }, [item('1')]);- await flush();-- engine.removeEntity('1', { scope: SCOPE });- await flush();-- expect(storage.rows.get(`${SCOPE}|a?{}`)?.data).toEqual([item('2')]);- // The active account's view and row are untouched.- expect(host.view().b).toEqual([item('1')]);- expect(storage.rows.get('u2|b?{}')?.data).toEqual([item('1')]);-- // Back on the first account, its list hydrates without the entity.- scopeState.current = SCOPE;- engine.ensureScope(SCOPE);- await engine.hydrate({ id: 'a' });- expect(host.view().a).toEqual([item('2')]);- resetScope();- });-- it('reconciles an entry hydrated while an off-scope update was still landing', async () => {- resetScope();- const storage = createStorage();- const { engine, host } = setupList(storage);- engine.replace({ id: 'a' }, [item('1'), item('2')]);- await flush();- scopeState.current = 'u2';- engine.ensureScope('u2');-- // Hold the patch on its index read, so the switch back lands first.- let release!: () => void;- const held = new Promise<void>((resolve) => (release = resolve));- const { getStrict } = storage.storage;- storage.storage.getStrict = async (key) => {- if (key.scope === SCOPE && key.queryKey === REPLICA_INDEX_KEY) await held;- return getStrict!(key);- };- engine.updateEntity<Item>('1', () => ({ id: '1', renamed: true }) as Item, { scope: SCOPE });-- // Back on the first account: its list hydrates the pre-patch row.- scopeState.current = SCOPE;- engine.ensureScope(SCOPE);- await engine.hydrate({ id: 'a' });- expect(host.view().a).toEqual([item('1'), item('2')]);-- release();- await flush();- await flush();-- // The patch landed in storage and in the view now on screen.- expect(storage.rows.get(`${SCOPE}|a?{}`)?.data).toEqual([- { id: '1', renamed: true },- item('2'),- ]);- expect(host.view().a).toEqual([{ id: '1', renamed: true }, item('2')]);- resetScope();- });-- it('patches a captured scopeβs rows whose writes were still queued at the switch', async () => {- resetScope();- const storage = createStorage();- const { engine, host } = setupList(storage);- // Every write of the first account is still queued when the account switches.- let release!: () => void;- const held = new Promise<void>((resolve) => (release = resolve));- const { set } = storage.storage;- storage.storage.set = async (key, row) => {- if (key.scope === SCOPE) await held;- return set(key, row);- };- engine.replace({ id: 'a' }, [item('1'), item('2')]);- engine.replace({ id: 'b' }, [item('1')]);-- scopeState.current = 'u2';- engine.ensureScope('u2');- engine.replace({ id: 'c' }, [item('1')]);- engine.removeEntity('1', { scope: SCOPE });- engine.updateEntity<Item>('2', () => ({ id: '2', renamed: true }) as Item, { scope: SCOPE });-- release();- for (let i = 0; i < 5; i++) await flush();-- // Neither row was in the persisted index yet, yet both got the change.- expect(storage.rows.get(`${SCOPE}|a?{}`)?.data).toEqual([{ id: '2', renamed: true }]);- expect(storage.rows.get(`${SCOPE}|b?{}`)?.data).toEqual([]);- // The active account is untouched.- expect(host.view().c).toEqual([item('1')]);- expect(storage.rows.get('u2|c?{}')?.data).toEqual([item('1')]);- resetScope();- });-- it('updateEntity({ scope }) patches only that scopeβs rows', async () => {- resetScope();- const storage = createStorage();- const { engine, host } = setupList(storage);- engine.replace({ id: 'a' }, [item('1')]);- await flush();- scopeState.current = 'u2';- engine.replace({ id: 'b' }, [item('1')]);- await flush();-- engine.updateEntity<Item>('1', () => ({ id: '1', renamed: true }) as Item, { scope: SCOPE });- await flush();-- expect(storage.rows.get(`${SCOPE}|a?{}`)?.data).toEqual([{ id: '1', renamed: true }]);- expect(host.view().b).toEqual([item('1')]);- expect(storage.rows.get('u2|b?{}')?.data).toEqual([item('1')]);- resetScope();- });-});--describe('bounded persisted entries (persist.maxEntries)', () => {- const bounded = (storage = createStorage()) => ({- storage,- ...setupList(storage, { maxEntries: 2 }),- });-- it('evicts the least recently used row, its index entry and its idle memory entry', async () => {- resetScope();- const { engine, host, storage } = bounded();- engine.replace({ id: 'a' }, [item('1')]);- engine.replace({ id: 'b' }, [item('2')]);- await flush();- engine.replace({ id: 'c' }, [item('3')]);- await flush();-- expect(storage.dataKeys()).toEqual(['b?{}', 'c?{}']);- expect(storage.index()).toEqual(['b?{}', 'c?{}']);- expect(Object.keys(host.view()).sort()).toEqual(['b', 'c']);- expect(host.state().entries.a).toBeUndefined();- });-- it('counts an unchanged revalidation and a hydrate as a use', async () => {- resetScope();- const { engine, storage } = bounded();- engine.replace({ id: 'a' }, [item('1')]);- engine.replace({ id: 'b' }, [item('2')]);- await flush();- // `a` is revalidated with the same value: no row write, but it is now recent.- engine.replace({ id: 'a' }, [item('1')]);- await flush();- engine.replace({ id: 'c' }, [item('3')]);- await flush();- expect(storage.dataKeys()).toEqual(['a?{}', 'c?{}']);-- // A later session hydrates `a`: `c` becomes the oldest.- const next = bounded(storage);- expect(await next.engine.hydrate({ id: 'a' })).toBe(true);- await flush();- next.engine.replace({ id: 'd' }, [item('4')]);- await flush();- expect(storage.dataKeys()).toEqual(['a?{}', 'd?{}']);- });-- it('keeps recency across reloads through the persisted index', async () => {- resetScope();- const first = bounded();- first.engine.replace({ id: 'a' }, [item('1')]);- first.engine.replace({ id: 'b' }, [item('2')]);- await flush();- first.engine.replace({ id: 'a' }, [item('1'), item('x')]);- await flush();- expect(first.storage.index()).toEqual(['b?{}', 'a?{}']);-- const { engine, storage } = bounded(first.storage);- engine.replace({ id: 'c' }, [item('3')]);- await flush();- expect(storage.dataKeys()).toEqual(['a?{}', 'c?{}']);- });-- it('never evicts a retained row or an entry with pending writes', async () => {- resetScope();- const { engine, host, storage } = bounded();- engine.replace({ id: 'a' }, [item('1')]);- engine.replace({ id: 'b' }, [item('2')]);- await flush();- const release = engine.retain('a', 'a?{}');- const pending = engine.beginOptimistic('b', (data) => [...data, item('tmp')]);-- engine.replace({ id: 'c' }, [item('3')]);- await flush();- // Both older rows are pinned: the cap waits rather than dropping them.- expect(storage.dataKeys()).toEqual(['a?{}', 'b?{}', 'c?{}']);- expect(host.view().a).toEqual([item('1')]);-- pending.rollback();- release();- engine.replace({ id: 'd' }, [item('4')]);- await flush();- expect(storage.dataKeys()).toEqual(['c?{}', 'd?{}']);- expect(Object.keys(host.view()).sort()).toEqual(['c', 'd']);- });-- it('keeps a row whose eviction delete failed indexed, and retries it on the next use', async () => {- resetScope();- const { engine, storage } = bounded();- storage.failRemoves.add('a?{}');- engine.replace({ id: 'a' }, [item('1')]);- engine.replace({ id: 'b' }, [item('2')]);- engine.replace({ id: 'c' }, [item('3')]);- await flush();- // `a` was picked but its delete failed: it stays indexed and stored.- expect(storage.index()).toEqual(['a?{}', 'b?{}', 'c?{}']);- expect(storage.dataKeys()).toEqual(['a?{}', 'b?{}', 'c?{}']);-- storage.failRemoves.delete('a?{}');- engine.replace({ id: 'c' }, [item('3'), item('4')]);- await flush();- expect(storage.index()).toEqual(['b?{}', 'c?{}']);- expect(storage.dataKeys()).toEqual(['b?{}', 'c?{}']);- });-- it('leaves an unbounded resource append-ordered and unevicted', async () => {- resetScope();- const storage = createStorage();- const { engine } = setupList(storage);- for (const id of ['a', 'b', 'c']) engine.replace({ id }, [item(id)]);- await flush();- engine.replace({ id: 'a' }, [item('a'), item('x')]);- await flush();- expect(storage.index()).toEqual(['a?{}', 'b?{}', 'c?{}']);- });-});--describe('useSync pins the entry it shows', () => {- it('a mounted useSync keeps its row and memory entry; unmounting releases them', async () => {- resetScope();- const storage = createStorage();- const resource = defineReplica<ListParams, Item[]>({- key: ({ id }) => id,- name: 'list',- persist: { maxEntries: 1 },- query: ({ q }) => ({ q }),- scope,- storage: storage.storage,- version: 1,- });- interface State {- lists: Record<string, Item[]>;- listsReplica: ReplicaState<Item[]>;- }- const store = createStore<State>()(() => ({ lists: {}, listsReplica: createReplicaState() }));- const slice = createReplicaSlice<State, ListParams, Item[]>(resource, {- driver: testDriver,- // No fetcher: only the pin is under test.- get: store.getState,- set: (partial) => store.setState(partial),- stateKey: 'listsReplica',- view: recordLens('lists'),- });-- const view = renderHook(() => slice.useSync({ id: 'a' }));- slice.replace({ id: 'a' }, [item('1')]);- slice.replace({ id: 'b' }, [item('2')]);- await flush();- await flush();- expect(storage.dataKeys()).toEqual(['a?{}', 'b?{}']);- expect(store.getState().lists.a).toEqual([item('1')]);-- view.unmount();- slice.replace({ id: 'c' }, [item('3')]);- await flush();- await flush();- expect(storage.dataKeys()).toEqual(['c?{}']);- expect(Object.keys(store.getState().lists)).toEqual(['c']);- });-});--describe('entity patches of unloaded rows', () => {- it('writes a `null` the entity adapter maps to as a value, and drops the row only on `undefined`', async () => {- resetScope();- const storage = createStorage();- const setup = () => {- const resource = defineReplica<ListParams, Item[] | null>({- key: ({ id }) => id,- name: 'list',- query: ({ q }) => ({ q }),- scope,- storage: storage.storage,- version: 1,- });- const host = createHost<Item[] | null>();- const engine = createReplicaEngine(resource, {- // `null` is a real value of this resource: "cleared", not "gone".- entity: {- has: (data, id) => !!data?.some((entry) => entry.id === id),- map: (data, id, fn) => {- if (!data?.some((entry) => entry.id === id)) return data;- const next = data.map((entry) => (entry.id === id ? fn(entry) : entry));- if (next.includes(undefined)) return id === 'gone' ? undefined : null;- return next as Item[];- },- },- port: host.port,- });- return engine;- };- const first = setup();- first.replace({ id: 'a' }, [item('cleared')]);- first.replace({ id: 'b' }, [item('gone')]);- await flush();-- // A fresh session holds neither entry in memory, so both go through storage.- const engine = setup();- await engine.removeEntity('cleared');- await engine.removeEntity('gone');- await flush();-- expect(storage.rows.get(`${SCOPE}|a?{}`)?.data).toBeNull();- expect(storage.rows.has(`${SCOPE}|b?{}`)).toBe(false);- });-});diff --git a/packages/replica/src/core/engine.ts b/packages/replica/src/core/engine.tsdeleted file mode 100644index ede1698e257..00000000000--- a/packages/replica/src/core/engine.ts+++ /dev/null@@ -1,842 +0,0 @@-import isEqual from 'fast-deep-equal';--import { replicaStorageKey, stableQueryKey } from './defineReplica';-import { createEntityPropagation } from './entityPropagation';-import {- applyHeadPage,- applyNextPage,- collapseToHead,- getNextPageCursor,- insertHeadItems,- joinPages,- pagingFor,- type ReplicaPagedData,- type ReplicaPageResult,- type ReplicaPagingContext,- toPersistedPage,-} from './paging';-import { createPersistedRows } from './persistedRows';-import type { ReplicaAction, ReplicaEffect, ReplicaViewWrite } from './reducer';-import { replicaReducer } from './reducer';-import { createEntityRemovalGuards, createRemovalGuards } from './removalGuards';-import type { ReplicaResource, ReplicaSource, ReplicaState } from './types';-import { ReplicaWriteQueue } from './writeQueue';--/** Reserved storage key of the per-scope index of persisted rows. */-export { REPLICA_INDEX_KEY } from './persistedRows';--/**- * The engine's view of the host store. The engine never owns the rendered- * value β the host does (a Zustand slice, a signal, a plain object) β it only- * reads entries through `read` and hands every transition to `commit`.- */-export interface ReplicaStorePort<TData> {- /**- * Apply the view writes and the next bookkeeping slot as ONE host update, so- * subscribers never observe a view out of step with its bookkeeping.- */- commit: (writes: ReplicaViewWrite<TData>[], state: ReplicaState<TData>, label: string) => void;- /** Current bookkeeping slot. */- getState: () => ReplicaState<TData>;- /** Enumerate loaded keys (entity propagation). Defaults to the bookkeeping entries. */- keys?: () => string[];- /** Materialized value of one entry, as the UI sees it. */- read: (key: string) => TData | undefined;-}--/**- * How entities (e.g. topics) appear inside a non-paged resource value. Paged- * resources get this for free from `paging.getId`. Build one with- * `singleEntity` (a detail value), `arrayEntity` (a plain list) or by hand for- * nested shapes (grouped lists).- */-export interface ReplicaEntityAdapter<TData, TItem> {- /** Whether `data` holds the entity. */- has: (data: TData, id: string) => boolean;- /**- * Map the entity inside `data` (`fn` returning `undefined` deletes it).- * Return `data` itself when nothing changed, or `undefined` when the whole- * value goes away with the entity (a detail value).- */- map: (data: TData, id: string, fn: (item: TItem) => TItem | undefined) => TData | undefined;-}--export interface ReplicaEngineOptions<TParams, TData, TFetched> {- /** Label prefix of host updates (devtools action names). Defaults to the resource name. */- actionPrefix?: string;- /** Non-paged resources: how entities sit in the value (see `linkReplicaEntity`). */- entity?: ReplicaEntityAdapter<TData, any>;- /** Overrides `resource.fetcher` when the fetch needs store context. */- fetcher?: (params: TParams, cursor?: any) => Promise<TFetched>;- /** Paged: rows that only exist client-side (kept across refreshes, never persisted). */- isClientOnly?: (item: any) => boolean;- /** Reject a persisted value that cannot serve these params. Rarely needed: rows are stored per query. */- isHydratable?: (cached: TData, params: TParams) => boolean;- /**- * Non-paged: whether a head response means the entry no longer exists. Such a- * response is applied as an explicit removal (memory + persisted row) instead- * of through `merge` β otherwise a `null` would fall back to the confirmed- * value (the reducer resolves `action.data(confirmed) ?? confirmed`), so a- * deleted aggregate would be retained and re-persisted.- */- isMissing?: (incoming: TFetched) => boolean;- /**- * Non-paged: fold a server response into the confirmed value. Return- * `undefined` to keep the current value. Defaults to "the response is the value".- */- merge?: (incoming: TFetched, confirmed: TData | undefined, params: TParams) => TData | undefined;- /** Where the engine reads and commits the view. */- port: ReplicaStorePort<TData>;- /**- * Reconcile a server response with the value currently shown before it is- * folded in β e.g. keep a row the client knows is newer, or ignore a- * response that raced a newer local state. Return `undefined` to drop the- * response entirely.- */- prepareHead?: (- incoming: TFetched,- current: TData | undefined,- params: TParams,- ) => TFetched | undefined;- /** Re-run the network sync of one entry (or all); wired by the fetch adapter. */- revalidate?: (key?: string) => Promise<unknown>;- /**- * Strip transient / client-only parts before persisting.- *- * - a value β persisted- * - `undefined` β skip this write (keep whatever is already stored)- * - `null` β the entry is a server-confirmed absence: drop any prior- * persisted projection, so a later hydrate cannot paint a value the server- * no longer has (the view keeps the confirmed value).- */- toPersisted?: (data: TData) => TData | null | undefined;- /** Paged: domain fields derived from params, written with every head page. */- viewFields?: (params: TParams) => Partial<TData>;-}--/** What a head response did once folded in (see `applyHead`). */-export type ReplicaHeadOutcome = 'dropped' | 'missing' | 'replaced';--export interface OptimisticMutationOptions<TData, TResult> {- /** Turn the server result into the confirmed value; defaults to re-applying `apply`. */- confirm?: (result: TResult) => (data: TData) => TData;- /** Revalidate the entry after the server call settles. */- revalidate?: boolean;-}--/** Handle of an optimistic overlay that is settled later (see `beginOptimistic`). */-export interface ReplicaOptimisticToken<TData> {- commit: (confirm?: (data: TData) => TData) => void;- rollback: () => void;-}--/**- * The replica engine: every transition of one resource, independent of any- * UI framework or state library.- *- * It owns hydrate-if-empty, server replace, pagination, optimistic overlays- * with commit/rollback, entity propagation, scope isolation and serialized- * persistence. The host store keeps the rendered value (see- * {@link ReplicaStorePort}); fetch scheduling (when to sync, dedupe, focus- * revalidation) belongs to an adapter such as `@lobechat/replica/zustand`.- */-export const createReplicaEngine = <TParams, TData, TFetched = TData>(- resource: ReplicaResource<TParams, TData, TFetched>,- options: ReplicaEngineOptions<TParams, TData, TFetched>,-) => {- const { port } = options;- const paging = resource.paging;- const at = (key: string) => pagingFor(paging!, key);- const pagingCtx: ReplicaPagingContext<any> = { isClientOnly: options.isClientOnly };- const prefix = options.actionPrefix ?? resource.name;- const writeQueue = resource.storage ? new ReplicaWriteQueue<TData>(resource.storage) : undefined;- const fetcher = options.fetcher ?? resource.fetcher;- let mutationSeq = 0;- /** Keys with a `loadMore` request in flight (the only valid `isLoadingMore`). */- const loadingMore = new Set<string>();-- // ---- removal guards (see `removalGuards.ts`) ------------------------------ const { clearRemoved, isPurged, isRemoved, markPurged, markRemoved, removalGeneration } =- createRemovalGuards();- const entityGuards = createEntityRemovalGuards();-- // ---- resource-wide clear ----------------------------------------------- /** Bumped by every `clear()` of a scope; reads started before it are stale. */- const clearGenerations = new Map<string, number>();- const clearGeneration = (scope: string) => clearGenerations.get(scope) ?? 0;- /**- * The persisted-row purge of the last `clear()` per scope: `true` once every- * row delete landed. A hydrate waits for it, and refuses to read while the- * purge failed (an untrusted scope, a storage error) so a wiped resource can- * never paint a row that survived it.- */- const scopePurges = new Map<string, Promise<boolean>>();-- const getSlot = port.getState;- const storageKey = (key: string, query?: string) => ({- queryKey: replicaStorageKey(key, query),- });-- const toPersisted = (data: TData): TData | null | undefined => {- const paged = paging ? (toPersistedPage(data as any, paging, pagingCtx) as TData) : data;- return options.toPersisted ? options.toPersisted(paged) : paged;- };-- // ---- persisted rows (see `persistedRows.ts`) ------------------------------ const rows = createPersistedRows<TData>({- commit: (keys, state) =>- port.commit(- keys.map((key) => ({ data: undefined, key })),- state,- `${prefix}/evict`,- ),- getSlot,- isRemoved,- loadingMore,- resource,- writeQueue,- });- const { deleteRows, readIndex, removeStoredVariants, retain, touchStorageKey } = rows;-- const runEffects = (effects: ReplicaEffect<TData>[]) => {- if (!writeQueue || effects.length === 0) return;- // Until identity resolves the scope is a guess; never write into it.- if (!resource.scope.canPersist()) return;- for (const effect of effects) {- if (!resource.persistKey(effect.key)) continue;- const key = { ...storageKey(effect.key, effect.query), scope: effect.scope };- if (effect.type === 'remove') {- // A repeated removal for this key can be a real no-op (see `remove`) β- // but only once the row delete actually landed. A storage that rejects- // the delete (a closed IndexedDB, a quota error) must leave the key- // unpurged, so the next terminal answer retries it instead of letting a- // stale row survive to hydrate again.- // Every query variant goes: a row persisted under other filters would- // otherwise hydrate the removed entry once the guard is superseded.- void removeStoredVariants(effect.scope, effect.key, key.queryKey).then((removed) => {- if (removed) markPurged(effect.scope, effect.key);- });- continue;- }- const data = toPersisted(effect.data);- if (data === undefined) continue;- if (data === null) {- // Server-confirmed absence: remove the prior projection rather than- // leaving it to be hydrated as if the value were still current.- void deleteRows(effect.scope, [key.queryKey]);- continue;- }- rows.writeRow(effect.scope, key.queryKey, data);- }- };-- /** Read an entry as it will be once `writes` are applied (latest write wins). */- const readThrough = (writes: ReplicaViewWrite<TData>[], key: string): TData | undefined => {- for (let i = writes.length - 1; i >= 0; i--) {- const write = writes[i];- if ('type' in write) return undefined;- if (write.key === key) return write.data;- }- return port.read(key);- };-- const dispatch = (action: ReplicaAction<TData>): boolean => runActions([action]);-- /**- * Fold one or more actions into a single host commit. A caller that seeds- * many keys (a list refresh) must not clone the view and notify subscribers- * once per key; every action is still reduced in order, and the accumulated- * writes are applied as ONE host update. A batch is dropped whole when any- * action belongs to another identity (see {@link dispatch}).- */- function runActions(actions: ReplicaAction<TData>[]): boolean {- if (actions.length === 0) return false;- const activeScope = resource.scope.get();- // An action captured under another identity is stale β drop it.- if (actions.some((action) => action.scope !== activeScope)) return false;-- for (const action of actions) {- // Every removal path (explicit `remove`, a missing response, an entity that- // takes its whole value with it) arms the hydration guard for this key.- if (action.type === 'remove') markRemoved(action.scope, action.key);- // A replacement that reaches the active scope supersedes an earlier- // removal, so the key may hydrate again. A response captured under another- // scope is dropped above and must NOT clear its guard: the removal still- // stands for its own scope, whose row delete may be pending or may have failed.- if (action.type === 'replace') clearRemoved(action.scope, action.key);- }-- const initial = getSlot();- let slot = initial;- const writes: ReplicaViewWrite<TData>[] = [];- const effects: ReplicaEffect<TData>[] = [];- const read = (key: string) => readThrough(writes, key);- if (slot.scope !== undefined && slot.scope !== activeScope) {- // Memory moves to another identity; what we knew of its rows can go.- rows.forgetScope(slot.scope);- const reset = replicaReducer(slot, { scope: activeScope, type: 'resetScope' }, read);- writes.push(...reset.writes);- slot = reset.state;- }-- let changed = false;- for (const action of actions) {- const transition = replicaReducer(slot, action, read);- writes.push(...transition.writes);- effects.push(...transition.effects);- // The reducer returns the entry's state unchanged for a no-op.- if (transition.state !== slot) {- slot = transition.state;- changed = true;- }- }-- if (!changed && writes.length === 0 && slot === initial) return false;- port.commit(writes, slot, `${prefix}/${actions.length > 1 ? 'batch' : actions[0].type}`);- runEffects(effects);- return true;- }-- /**- * Drop memory owned by another identity as soon as a new scope is active β- * even when the new scope has nothing persisted and its fetch is slow, the- * previous user's / workspace's rows must not stay on screen.- */- const ensureScope = (scope: string) => {- if (scope === resource.scope.get() && getSlot().scope !== scope)- dispatch({ scope, type: 'resetScope' });- };-- const getConfirmed = (key: string): TData | undefined => {- const entry = getSlot().entries[key];- return entry?.pending.length ? entry.base : port.read(key);- };-- /**- * An overwrite hydrate repaints the entry from another query's persisted page.- * Client-only rows (an in-flight upload / create) have no server row yet, so- * that page cannot contain them β keep the ones still in the view, so a- * same-pool query change (a re-sort, a view-mode switch) never drops them.- * A cross-pool navigate is not "client-only" for the new params and is dropped.- */- const keepClientOnlyRows = (incoming: TData, current: TData | undefined, key: string): TData => {- if (!paging || !options.isClientOnly || !current) return incoming;- const page = incoming as unknown as ReplicaPagedData<unknown, unknown>;- const currentItems = (current as unknown as ReplicaPagedData<unknown, unknown>).items ?? [];- const incomingIds = new Set(page.items.map((item) => paging.getId(item)));- const survivors = currentItems.filter(- (item) => options.isClientOnly!(item) && !incomingIds.has(paging.getId(item)),- );- if (survivors.length === 0) return incoming;- const items = joinPages(survivors, page.items, at(key).direction);- return { ...(incoming as object), items } as TData;- };-- const hydrate = async (- params: TParams,- scope = resource.scope.get(),- { overwrite = false }: { overwrite?: boolean } = {},- ) => {- if (!resource.storage) return false;- // An identity-less runtime reads network-only: its scope is a guess, so- // hydrating it could paint another session's private rows.- if (resource.scope.canHydrate && !resource.scope.canHydrate()) return false;- const key = resource.key(params);- if (!resource.persistKey(key)) return false;- // A removed entry is not read back: only a later server value supersedes- // the removal (see `replace`), so a stale row can never repaint it.- if (isRemoved(scope, key)) return false;- // Pending until settled: entity guards outlive every read that may hold them.- const settle = entityGuards.startHydrate(scope);- try {- return await readAndHydrate(params, key, scope, overwrite);- } finally {- settle();- }- };-- const readAndHydrate = async (- params: TParams,- key: string,- scope: string,- overwrite: boolean,- ) => {- const storage = resource.storage!;- // A read started before a `clear()` of this scope holds a wiped row.- const generation = clearGeneration(scope);- // After a `clear()`, read only once its row deletes landed.- const purge = scopePurges.get(scope);- if (purge && !(await purge)) return false;- const query = resource.query(params);- const { queryKey } = storageKey(key, query);- const writesBefore = rows.writeCount();- const cached = await storage.get({ queryKey, scope });- if (!cached) return false;- // Re-check after the read: a removal or a clear that landed while it was in- // flight must not resurrect the row it just dropped.- if (isRemoved(scope, key) || clearGeneration(scope) !== generation) return false;- // The row holds what was read, unless a write was queued while reading.- rows.rememberRead(scope, queryKey, cached.data, writesBefore);- if (options.isHydratable && !options.isHydratable(cached.data, params)) return false;- // Entities deleted while the read was in flight may still be in the row.- const stored = withoutRemovedEntities(scope, cached.data);- if (stored === undefined) return false;- const data = overwrite ? keepClientOnlyRows(stored, port.read(key), key) : stored;- const applied = dispatch({- data,- key,- overwrite,- params,- query,- scope,- type: 'hydrate',- updatedAt: cached.updatedAt,- });- // A hydrated row is a used row (bounded resources keep LRU order).- if (applied && resource.scope.canPersist()) touchStorageKey(scope, queryKey);- return applied;- };-- const viewMatchesFields = (current: TData | undefined, params: TParams) => {- const fields = options.viewFields?.(params);- if (!current || !fields) return true;- // Falsy descriptors (undefined / false / null) are equivalent.- const norm = (value: unknown) => stableQueryKey(value || null);- return Object.entries(fields).every(- ([field, value]) => norm(value) === norm((current as Record<string, unknown>)[field]),- );- };-- /** Non-paged: whether a (prepared) head response is a terminal absence (`isMissing`). */- const isMissingHead = (incoming: TFetched): boolean => !paging && !!options.isMissing?.(incoming);-- const mergeHead = (- key: string,- incoming: TFetched,- confirmed: TData | undefined,- params: TParams,- reset: boolean,- ) => {- const page = incoming as unknown as ReplicaPageResult<unknown, unknown>;- const pageSize = (params as { pageSize?: number }).pageSize ?? page.items.length;- const merged = {- ...applyHeadPage(confirmed as any, page, { pageSize, reset }, at(key), pagingCtx),- ...options.viewFields?.(params),- isLoadingMore: loadingMore.has(key),- };- // Keep domain-only fields of the current view (e.g. transient flags).- const next = { ...(confirmed as object), ...merged } as TData;- return confirmed !== undefined && isEqual(next, confirmed) ? undefined : next;- };-- /**- * Fold a head response in and report what it was: dropped by `prepareHead`,- * a terminal absence (`isMissing`, applied as a removal) or a replacement.- * `changed` is whether the store moved. `replace` is the boolean shorthand;- * the zustand slice's settle pipeline reads the outcome to pick its effects.- */- const applyHead = (- params: TParams,- fetched: TFetched,- scope = resource.scope.get(),- ): { changed: boolean; outcome: ReplicaHeadOutcome } => {- const key = resource.key(params);- const incoming = options.prepareHead- ? options.prepareHead(fetched, port.read(key), params)- : fetched;- if (incoming === undefined) return { changed: false, outcome: 'dropped' };- // A response that says the entry is gone clears it outright: the merge path- // would keep β and re-persist β the confirmed value it is replacing. It also- // arms the hydration guard, so a persisted read still in flight cannot bring- // the dropped value back.- if (isMissingHead(incoming)) {- // Route through `remove` so a repeated "missing" is a no-op and a response- // captured under another scope is dropped rather than applied here.- return { changed: remove(key, scope), outcome: 'missing' };- }- const query = resource.query(params);- const entry = getSlot().entries[key];- // A different query (filters, sort) must not merge with loaded pages. A- // view seeded without bookkeeping is compared by its `viewFields`.- const reset = entry- ? entry.query !== query- : paging !== undefined && !viewMatchesFields(port.read(key), params);- const applied = dispatch({- data: (confirmed) =>- paging- ? mergeHead(key, incoming, confirmed, params, reset)- : options.merge- ? options.merge(incoming, confirmed, params)- : (incoming as unknown as TData),- key,- params,- query,- scope,- type: 'replace',- });- if (applied) forgetRestoredEntities(scope, getConfirmed(key));- return { changed: applied, outcome: 'replaced' };- };-- const replace = (params: TParams, fetched: TFetched, scope = resource.scope.get()) =>- applyHead(params, fetched, scope).changed;-- /**- * Confirmed local write: patches the view (and the base under any overlay).- * Pass `source: 'seed'` for a provisional row (a list row standing in for a- * detail): it is hydratable and never persisted, so the authoritative value it- * stands in for is preserved (see `ReplicaSource`).- */- const update = (- key: string,- apply: (data: TData | undefined) => TData | undefined,- {- persist = true,- seedTag,- source,- }: { persist?: boolean; seedTag?: string; source?: ReplicaSource } = {},- ) =>- dispatch({ apply, key, persist, scope: resource.scope.get(), seedTag, source, type: 'update' });-- /**- * Confirmed local write to several keys as ONE host update β same per-key- * semantics as {@link update}, but a whole list seeds in a single commit- * instead of one per row (no repeated view cloning or subscriber churn).- */- const updateMany = (- entries: { apply: (data: TData | undefined) => TData | undefined; key: string }[],- {- persist = true,- seedTag,- source,- }: { persist?: boolean; seedTag?: string; source?: ReplicaSource } = {},- ) => {- const scope = resource.scope.get();- return runActions(- entries.map(({ apply, key }) => ({- apply,- key,- persist,- scope,- seedTag,- source,- type: 'update' as const,- })),- );- };-- /**- * Purge a removal that belongs to a scope which is no longer active.- *- * The in-memory view is not ours to touch β the active scope owns it β but the- * guard and the persisted row both belong to THAT scope. Arming the one and- * deleting the other keeps a switch back from hydrating a value the server- * just deleted or denied. `dispatch` would reject the off-scope action- * outright (see `replace`'s stale-scope guard), so the row would otherwise- * survive untouched.- *- * Like `remove`, the delete only counts as done once it was actually queued:- * an untrusted scope refuses writes, so the guard stays armed as `unpurged`- * and a later removal retries instead of reporting a no-op that never deletes.- */- const purge = (key: string, scope: string): boolean => {- if (isRemoved(scope, key) && isPurged(scope, key)) return false;- markRemoved(scope, key);- // Nothing persisted (no storage, or a key this resource never persists) is- // already "cleared": the guard alone is the whole purge.- if (!writeQueue || !resource.persistKey(key)) {- markPurged(scope, key);- return false;- }- if (!resource.scope.canPersist()) return false;- void removeStoredVariants(scope, key, storageKey(key).queryKey).then((removed) => {- if (removed) markPurged(scope, key);- });- return true;- };-- /**- * Drop an entry and its persisted row.- *- * A removal is a no-op only once there is genuinely nothing left to do: the- * key is guarded, its value is gone, AND its stale row was already scheduled- * for deletion (or there is no persisted row to clear). A subject with no- * acceptance polls `null` every couple of seconds, and re-emitting the same- * delete on every tick would only churn storage. But a removal whose delete- * was skipped β an untrusted scope refuses writes β keeps retrying, so the row- * cannot survive to hydrate again once the scope is trusted.- *- * A removal captured under another identity (a late NOT_FOUND arriving after a- * workspace switch) is routed to {@link purge}: it must not touch the scope on- * screen, yet its own scope's row still has to go.- */- const remove = (key: string, scope: string = resource.scope.get()): boolean => {- if (scope !== resource.scope.get()) return purge(key, scope);- // Nothing persisted (no storage, or a key this resource never persists) is- // already "cleared"; otherwise the row delete must have been queued.- const rowCleared = !writeQueue || !resource.persistKey(key) || isPurged(scope, key);- if (rowCleared && isRemoved(scope, key) && port.read(key) === undefined) return false;- return dispatch({ key, scope, type: 'remove' });- };-- /**- * Persist the confirmed value of an entry as it is now β the flush after a- * burst of in-memory `update(..., { persist: false })` writes (a stream).- */- const persist = (key: string) => {- const scope = resource.scope.get();- if (getSlot().scope !== undefined && getSlot().scope !== scope) return;- const data = getConfirmed(key);- if (data === undefined) return;- runEffects([{ data, key, query: getSlot().entries[key]?.query, scope, type: 'persist' }]);- };-- /**- * Wipe the resource in the active scope: every entry leaves memory in one- * host commit, every persisted row (all keys, all query variants) and the- * index are deleted, and reads already in flight are dropped β a hydrate- * started before the clear never dispatches, and `useSync` discards head- * responses whose request started before it. Requests started afterwards- * apply normally. Resolves `true` once the persisted rows are gone.- */- const clear = (): Promise<boolean> => {- const scope = resource.scope.get();- clearGenerations.set(scope, clearGeneration(scope) + 1);- port.commit([{ type: 'clear' }], { entries: {}, scope }, `${prefix}/clear`);- rows.forgetScope(scope);- const purge = purgeScope(scope);- scopePurges.set(scope, purge);- return purge;- };-- /**- * `clear()` for any scope, including one that is not active (a user who- * switched away while their data was being deleted): every persisted row of- * `scope` and its index go, and for the active scope memory is wiped too- * (exactly `clear()`). An inactive scope's memory is not on screen and is- * left alone. The row deletes go through the write queue, so they land after- * any write this session already queued for that scope β a row (or index- * entry) written just before is purged rather than landing after the purge.- * A later hydrate of `scope` waits for the purge. Resolves `true` once the- * persisted rows are gone.- */- const clearScope = (scope: string): Promise<boolean> => {- if (scope === resource.scope.get()) return clear();- clearGenerations.set(scope, clearGeneration(scope) + 1);- const purge = purgeScope(scope);- scopePurges.set(scope, purge);- return purge;- };-- /** Delete every persisted row of `scope` (see `clear`). */- const purgeScope = async (scope: string): Promise<boolean> => {- if (!writeQueue) return true;- // Until identity resolves the scope is a guess; never write into it.- if (!resource.scope.canPersist()) return false;- // Rows this session knows about are queued now, ahead of any later write.- const queued = deleteRows(scope, [...(rows.indexedKeys(scope) ?? [])]);- let persisted: string[];- try {- persisted = await readIndex(scope);- } catch {- return false;- }- // Keys this session tracks are already queued above, or were written by a- // newer response since the clear (their row is fresh): skip both.- const known = rows.indexedKeys(scope);- const stale = persisted.filter((queryKey) => !known?.has(queryKey));- const [first, rest] = await Promise.all([queued, deleteRows(scope, stale)]);- return first && rest;- };-- const revalidate = (key?: string): Promise<unknown> =>- options.revalidate ? options.revalidate(key) : Promise.resolve();-- /**- * Start an optimistic overlay now and settle it later (multi-resource flows).- * `query` tags the overlay with the query it describes; a caller that knows- * the requested query (e.g. before the first page painted) should pass it, so- * the overlay is scoped to that query rather than kept across every change.- */- const beginOptimistic = (- key: string,- apply: (data: TData) => TData,- query?: string,- ): ReplicaOptimisticToken<TData> => {- const scope = resource.scope.get();- const id = ++mutationSeq;- // Tag the overlay with the query it describes: the entry may move on to- // another query (or another query may reuse the key) before it settles.- dispatch({- apply,- id,- key,- query: query ?? getSlot().entries[key]?.query,- scope,- type: 'optimistic',- });- return {- commit: (confirm) => {- dispatch({ confirm, id, key, scope, type: 'commit' });- },- rollback: () => {- dispatch({ id, key, scope, type: 'rollback' });- },- };- };-- /**- * Apply `apply` to the view right away, run `serverCall`, then commit (the- * confirmed value is persisted) or roll back (the view is rebuilt from the- * confirmed base plus any other in-flight overlays) and rethrow.- */- const optimistic = async <TResult>(- key: string,- apply: (data: TData) => TData,- serverCall: () => Promise<TResult>,- mutationOptions: OptimisticMutationOptions<TData, TResult> = {},- ): Promise<TResult> => {- const token = beginOptimistic(key, apply);- try {- const result = await serverCall();- token.commit(mutationOptions.confirm?.(result));- return result;- } catch (error) {- token.rollback();- throw error;- } finally {- if (mutationOptions.revalidate) void revalidate(key);- }- };-- // ---- pagination ---------------------------------------------------------- /**- * Fetch and merge the next page with the params of the loaded head page- * (`fallbackParams` covers views seeded outside `useSync`). In `cursor` mode- * paging only starts from a server-confirmed head page: a hydrated cursor- * may be stale. A result is dropped when the scope, the query or the loaded- * depth changed while it was in flight.- */- const loadMore = async (key: string, fallbackParams?: TParams): Promise<void> => {- if (!paging || !fetcher) return;- const entry = getSlot().entries[key];- const current = port.read(key) as ReplicaPagedData<unknown, unknown> | undefined;- if (!current || loadingMore.has(key)) return;- if (paging.mode === 'cursor' && entry?.source === 'storage') return;- const params = (entry?.params ?? fallbackParams) as TParams | undefined;- if (params === undefined) return;- const cursor = getNextPageCursor(current, at(key));- if (cursor === null || cursor === undefined) return;-- const query = entry?.query;- const scope = resource.scope.get();- const depth = current.currentPage;- const setLoading = (patch: object) =>- update(key, (data) => data && ({ ...data, ...patch } as TData), { persist: false });-- loadingMore.add(key);- setLoading({ isLoadingMore: true, loadMoreError: undefined });- const isCurrent = () => {- const latest = port.read(key) as ReplicaPagedData<unknown, unknown> | undefined;- return (- resource.scope.get() === scope &&- getSlot().entries[key]?.query === query &&- latest?.currentPage === depth- );- };- try {- const page = (await fetcher(params, cursor)) as unknown as ReplicaPageResult<- unknown,- unknown- >;- if (!isCurrent()) return void setLoading({ isLoadingMore: false });- update(- key,- (data) => data && (applyNextPage(data as any, page, at(key), pagingCtx) as TData),- { persist: (paging.persist?.pages ?? 1) > 1 },- );- } catch (error) {- setLoading({ isLoadingMore: false, loadMoreError: isCurrent() ? error : undefined });- } finally {- loadingMore.delete(key);- }- };-- /** Insert rows at the head (new / streamed items). */- const insertHead = <TItem>(key: string, items: TItem[], { persist = false } = {}) =>- paging- ? update(key, (data) => data && (insertHeadItems(data as any, items, at(key)) as TData), {- persist,- })- : false;-- /** Drop loaded pages, keeping the head (e.g. after an edit inside older pages). */- const collapse = (key: string) =>- paging- ? update(key, (data) => data && (collapseToHead(data as any, at(key)) as TData), {- persist: false,- })- : false;-- // ---- entity propagation (see `entityPropagation.ts`) ---------------------- const entities = createEntityPropagation<TData>({- beginOptimistic,- entity: options.entity,- entityGuards,- getSlot,- paging,- port,- remove,- resource,- rows,- update,- });- const {- beginEntityOptimistic,- entityKeys,- forgetRestoredEntities,- patchStoredEntity,- removeEntity,- updateEntity,- withoutRemovedEntities,- } = entities;- const { patchStoredRows } = rows;-- return {- applyHead,- beginEntityOptimistic,- beginOptimistic,- clear,- clearGeneration,- clearScope,- removalGeneration,- collapse,- dispatch,- ensureScope,- entityKeys,- fetcher,- getConfirmed,- hydrate,- insertHead,- isMissingHead,- loadMore,- optimistic,- patchStoredEntity,- patchStoredRows,- persist,- remove,- removeEntity,- replace,- resource,- retain,- revalidate,- update,- updateEntity,- updateMany,- };-};--export type ReplicaEngine<TParams, TData, TFetched = TData> = ReturnType<- typeof createReplicaEngine<TParams, TData, TFetched>->;diff --git a/packages/replica/src/core/entity.ts b/packages/replica/src/core/entity.tsdeleted file mode 100644index 89e37fff422..00000000000--- a/packages/replica/src/core/entity.ts+++ /dev/null@@ -1,100 +0,0 @@-import type { ReplicaOptimisticToken } from './engine';--/** The part of a slice entity propagation needs (structural, so any slice fits). */-export interface ReplicaEntityTarget {- beginEntityOptimistic: <TItem>(- id: string,- fn: (item: TItem) => TItem | undefined,- ) => ReplicaOptimisticToken<any>[];- /** Wipe the resource in the active scope (memory + every persisted row). */- clear?: () => Promise<boolean>;- /** Patch persisted rows whose entry is not loaded in memory. */- patchStoredEntity: <TItem>(id: string, fn: (item: TItem) => TItem | undefined) => Promise<void>;- /**- * Explicit entity removal that also guards later hydrates. Optional for- * custom targets; `linkReplicaEntity` falls back to `updateEntity`.- */- removeEntity?: (id: string, options?: { persist?: boolean; scope?: string }) => void;- revalidate: (key?: string) => Promise<unknown>;- updateEntity: <TItem>(- id: string,- fn: (item: TItem) => TItem | undefined,- options?: { persist?: boolean },- ) => void;-}--/**- * Link resources that hold copies of the same entity (e.g. a topic in the- * sidebar list, the management page and the detail cache).- *- * Each resource keeps exactly one store location and decides how the entity- * maps into its own shape (paged resources by `getId`, single-entity ones by- * their entity adapter). The link only fans an entity-level change out to the- * resources that currently hold it β no global event bus, no shared owner.- */-export const linkReplicaEntity = <TItem>(targets: ReplicaEntityTarget[]) => {- /**- * Confirmed patch everywhere the entity is loaded, and (when persisted, the- * default) in persisted rows of entries that are not loaded.- */- const update = (- id: string,- fn: (item: TItem) => TItem,- options?: { persist?: boolean },- ): void => {- for (const target of targets) target.updateEntity<TItem>(id, fn, options);- };-- /**- * Confirmed removal everywhere (list rows dropped, single-entity values- * removed). A value hydrated later β even one whose read was already in- * flight β comes back without the entity. With `scope` set to a scope left- * behind, only that scope's persisted rows lose the entity; the view on- * screen belongs to another scope and is left alone.- */- const remove = (id: string, options?: { persist?: boolean; scope?: string }): void => {- for (const target of targets) {- if (target.removeEntity) target.removeEntity(id, options);- else if (!options?.scope) target.updateEntity<TItem>(id, () => undefined, options);- }- };-- /**- * Wipe every linked resource in the active scope (e.g. "delete all"): memory,- * every persisted row and reads in flight. Resolves `true` once every- * persisted row is gone.- */- const clear = async (): Promise<boolean> => {- const purged = await Promise.all(targets.map((target) => target.clear?.() ?? true));- return purged.every(Boolean);- };-- /**- * One server call, one overlay per resource holding the entity: all commit- * together or all roll back together (then rethrow). Pass `'remove'` for an- * optimistic delete.- */- const optimistic = async <TResult>(- id: string,- fn: ((item: TItem) => TItem) | 'remove',- serverCall: () => Promise<TResult>,- ): Promise<TResult> => {- const apply = fn === 'remove' ? () => undefined : fn;- const tokens = targets.flatMap((target) => target.beginEntityOptimistic<TItem>(id, apply));- try {- const result = await serverCall();- for (const token of tokens) token.commit();- // `remove` / `update` also patch persisted rows that are not loaded.- if (fn === 'remove') remove(id);- else for (const target of targets) void target.patchStoredEntity<TItem>(id, fn);- return result;- } catch (error) {- for (const token of tokens) token.rollback();- throw error;- }- };-- const revalidate = () => Promise.all(targets.map((target) => target.revalidate()));-- return { clear, optimistic, remove, revalidate, update };-};diff --git a/packages/replica/src/core/entityAdapters.test.ts b/packages/replica/src/core/entityAdapters.test.tsdeleted file mode 100644index 08c14777300..00000000000--- a/packages/replica/src/core/entityAdapters.test.ts+++ /dev/null@@ -1,143 +0,0 @@-import { describe, expect, it } from 'vitest';--import { defineReplica } from './defineReplica';-import { createReplicaEngine, type ReplicaStorePort } from './engine';-import { linkReplicaEntity } from './entity';-import { arrayEntity, singleEntity } from './entityAdapters';-import { createReplicaState } from './reducer';-import type { ReplicaState } from './types';--interface Row {- id: string;- name: string;-}-interface Detail {- members: string[];- project: Row;-}--/** A host without Zustand: a plain object behind the store port. */-const createHost = <T>() => {- const host = { slot: createReplicaState<T>() as ReplicaState<T>, views: {} as Record<string, T> };- const port: ReplicaStorePort<T> = {- commit: (writes, state) => {- for (const write of writes) {- if ('type' in write) host.views = {};- else if (write.data === undefined) delete host.views[write.key];- else host.views[write.key] = write.data;- }- host.slot = state;- },- getState: () => host.slot,- keys: () => Object.keys(host.views),- read: (key) => host.views[key],- };- return { host, port };-};--const rowById = (id: string) => (row: Row) => row.id === id;--describe('arrayEntity', () => {- const adapter = arrayEntity<Row>((row) => row.id);- const list = [- { id: 'a', name: 'A' },- { id: 'b', name: 'B' },- ];-- it('patches and removes one row', () => {- expect(adapter.has(list, 'b')).toBe(true);- expect(adapter.map(list, 'b', (row) => ({ ...row, name: 'B2' }))).toEqual([- { id: 'a', name: 'A' },- { id: 'b', name: 'B2' },- ]);- expect(adapter.map(list, 'a', () => undefined)).toEqual([{ id: 'b', name: 'B' }]);- });-- it('keeps the reference when nothing changed', () => {- expect(adapter.map(list, 'missing', (row) => ({ ...row, name: 'x' }))).toBe(list);- expect(adapter.map(list, 'a', (row) => row)).toBe(list);- });-});--describe('singleEntity with a lens', () => {- const adapter = singleEntity<Detail, Row>((row) => row.id, {- get: (detail) => detail.project,- set: (detail, project) => ({ ...detail, project }),- });- const detail: Detail = { members: ['m'], project: { id: 'p', name: 'P' } };-- it('patches the wrapped entity and keeps the rest of the value', () => {- expect(adapter.map(detail, 'p', (row) => ({ ...row, name: 'P2' }))).toEqual({- members: ['m'],- project: { id: 'p', name: 'P2' },- });- });-- it('drops the whole value when the entity is deleted', () => {- expect(adapter.map(detail, 'p', () => undefined)).toBeUndefined();- });-});--describe('entity link over non-paged replicas (engine without Zustand)', () => {- const setup = () => {- const listHost = createHost<Row[]>();- const detailHost = createHost<Detail>();- const list = createReplicaEngine(- defineReplica<void, Row[]>({ key: () => 'all', name: 'rows', version: 1 }),- { entity: arrayEntity<Row>((row) => row.id), port: listHost.port },- );- const detail = createReplicaEngine(- defineReplica<string, Detail>({ key: (id) => id, name: 'rowDetail', version: 1 }),- {- entity: singleEntity<Detail, Row>((row) => row.id, {- get: (value) => value.project,- set: (value, project) => ({ ...value, project }),- }),- port: detailHost.port,- },- );- list.replace(undefined, [- { id: 'a', name: 'A' },- { id: 'b', name: 'B' },- ]);- detail.replace('b', { members: ['m'], project: { id: 'b', name: 'B' } });- return { detailHost, link: linkReplicaEntity<Row>([list, detail]), listHost };- };-- it('patches the row in the list and the wrapped entity in the detail', () => {- const { detailHost, link, listHost } = setup();-- link.update('b', (row) => ({ ...row, name: 'B2' }));-- expect(listHost.host.views.all.find(rowById('b'))?.name).toBe('B2');- expect(detailHost.host.views.b.project.name).toBe('B2');- expect(detailHost.host.views.b.members).toEqual(['m']);- });-- it('rolls both back when the server call fails', async () => {- const { detailHost, link, listHost } = setup();-- const pending = link.optimistic(- 'b',- (row) => ({ ...row, name: 'B2' }),- async () => {- expect(listHost.host.views.all.find(rowById('b'))?.name).toBe('B2');- expect(detailHost.host.views.b.project.name).toBe('B2');- throw new Error('boom');- },- );-- await expect(pending).rejects.toThrow('boom');- expect(listHost.host.views.all.find(rowById('b'))?.name).toBe('B');- expect(detailHost.host.views.b.project.name).toBe('B');- });-- it('removes the list row and the detail value on delete', async () => {- const { detailHost, link, listHost } = setup();-- await link.optimistic('b', 'remove', async () => undefined);-- expect(listHost.host.views.all.map((row) => row.id)).toEqual(['a']);- expect(detailHost.host.views.b).toBeUndefined();- });-});diff --git a/packages/replica/src/core/entityAdapters.ts b/packages/replica/src/core/entityAdapters.tsdeleted file mode 100644index 8378cc8bd35..00000000000--- a/packages/replica/src/core/entityAdapters.ts+++ /dev/null@@ -1,43 +0,0 @@-import type { ReplicaEntityAdapter } from './engine';--/**- * The value IS one entity, or wraps one (`{ project, members }`). Deleting the- * entity drops the whole value.- */-export const singleEntity = <TData, TItem = TData>(- getId: (item: TItem) => string,- lens?: { get: (data: TData) => TItem; set: (data: TData, item: TItem) => TData },-): ReplicaEntityAdapter<TData, TItem> => {- const pick = (data: TData) => (lens ? lens.get(data) : (data as unknown as TItem));- return {- has: (data, id) => getId(pick(data)) === id,- map: (data, _id, fn) => {- const current = pick(data);- const next = fn(current);- if (next === undefined) return undefined;- if (next === current) return data;- return lens ? lens.set(data, next) : (next as unknown as TData);- },- };-};--/** The value is a plain list of entities; deleting one filters it out. */-export const arrayEntity = <TItem>(- getId: (item: TItem) => string,-): ReplicaEntityAdapter<TItem[], TItem> => ({- has: (data, id) => data.some((item) => getId(item) === id),- map: (data, id, fn) => {- let changed = false;- const next: TItem[] = [];- for (const item of data) {- if (getId(item) !== id) {- next.push(item);- continue;- }- const mapped = fn(item);- if (mapped !== item) changed = true;- if (mapped !== undefined) next.push(mapped);- }- return changed ? next : data;- },-});diff --git a/packages/replica/src/core/entityPropagation.ts b/packages/replica/src/core/entityPropagation.tsdeleted file mode 100644index ffc3062acab..00000000000--- a/packages/replica/src/core/entityPropagation.ts+++ /dev/null@@ -1,296 +0,0 @@-import { replicaStorageKey } from './defineReplica';-import type { ReplicaEntityAdapter, ReplicaOptimisticToken, ReplicaStorePort } from './engine';-import {- hasPagedItem,- mapPagedItem,- type ReplicaPagedData,- type ReplicaPagingConfig,-} from './paging';-import { DROP_ROW, type ReplicaPersistedRows } from './persistedRows';-import type { ReplicaEntityRemovalGuards } from './removalGuards';-import type { ReplicaResource, ReplicaSource, ReplicaState } from './types';--export interface ReplicaEntityPropagationDeps<TData> {- beginOptimistic: (key: string, apply: (data: TData) => TData) => ReplicaOptimisticToken<TData>;- /** Non-paged resources: how entities sit in the value. */- entity?: ReplicaEntityAdapter<TData, any>;- entityGuards: ReplicaEntityRemovalGuards;- getSlot: () => ReplicaState<TData>;- paging?: ReplicaPagingConfig<any, any>;- port: ReplicaStorePort<TData>;- remove: (key: string) => boolean;- resource: ReplicaResource<any, TData, any>;- rows: ReplicaPersistedRows<TData>;- update: (- key: string,- apply: (data: TData | undefined) => TData | undefined,- options?: { persist?: boolean; seedTag?: string; source?: ReplicaSource },- ) => boolean;-}--/**- * Entity propagation: a change to one entity (e.g. a topic) applied to every- * entry that holds it β in memory, in persisted rows memory does not hold,- * and in rows a hydrate reads back while a removal is still landing.- */-export const createEntityPropagation = <TData>({- beginOptimistic,- entity,- entityGuards,- getSlot,- paging,- port,- remove,- resource,- rows,- update,-}: ReplicaEntityPropagationDeps<TData>) => {- const entityKeys = (id: string): string[] => {- const keys = port.keys?.() ?? Object.keys(getSlot().entries);- return keys.filter((key) => {- const data = port.read(key);- if (data === undefined) return false;- if (paging) return hasPagedItem(data as any, id, paging);- return entity ? entity.has(data, id) : false;- });- };-- /** Map one entity inside a value; `undefined` means the whole value goes away. */- const mapEntity = <TItem>(- data: TData,- id: string,- fn: (item: TItem) => TItem | undefined,- ): TData | undefined => {- if (paging) return mapPagedItem(data as any, id, fn as any, paging) as TData;- if (!entity || !entity.has(data, id)) return data;- return entity.map(data, id, fn);- };-- /** Which of `ids` are held by `data`. */- const heldEntities = (data: TData, ids: string[]): string[] => {- if (paging) {- const items = (data as unknown as ReplicaPagedData<unknown, unknown>).items ?? [];- const present = new Set(items.map((item) => paging.getId(item)));- return ids.filter((id) => present.has(id));- }- return entity ? ids.filter((id) => entity.has(data, id)) : [];- };-- /** Strip entities removed in `scope` from a value read back from storage. */- const withoutRemovedEntities = (scope: string, data: TData): TData | undefined => {- const removed = entityGuards.removedIds(scope);- if (removed.length === 0) return data;- let next: TData | undefined = data;- for (const id of heldEntities(data, removed)) {- next = mapEntity(next!, id, () => undefined);- if (next === undefined) break;- }- return next;- };-- /** A server value holding a removed entity again (restored) lifts its guard. */- const forgetRestoredEntities = (scope: string, data: TData | undefined) => {- const removed = entityGuards.removedIds(scope);- if (removed.length === 0 || data === undefined) return;- entityGuards.liftEntityGuards(scope, heldEntities(data, removed));- };-- /**- * Apply an entity change to persisted rows that memory does not hold (the- * memory path already persists loaded entries). Read-modify-write runs in- * the per-key write queue, so it sees every earlier write; a missing row is- * never recreated. Resolves once the patches have settled: `true` when every- * unloaded row is known to be patched (or nothing is persisted), `false` when- * a row may still hold the old entity (untrusted scope, unreadable index or- * row, a failed write, an identity switch mid-pass).- */- const patchStoredEntityRows = async <TItem>(- id: string,- fn: (item: TItem) => TItem | undefined,- scope: string = resource.scope.get(),- ): Promise<boolean> => {- if (!resource.storage) return true;- if (!resource.scope.canPersist()) return false;- // A scope left behind is patched on purpose: nothing of it is loaded, and an- // identity switch while reading its index does not make its rows foreign.- const offScope = scope !== resource.scope.get();- const slot = getSlot();- // Rows memory holds are patched through memory β but only in the active- // scope; a view still showing a scope left behind is not what it persists.- const loaded = new Set(- !offScope && slot.scope === scope- ? Object.entries(slot.entries).map(([key, entry]) => replicaStorageKey(key, entry.query))- : [],- );- let keys: string[];- try {- keys = await rows.readIndex(scope);- } catch (error) {- // Rows cannot be enumerated: nothing to patch. Loaded entries are already- // updated, and a removal keeps guarding later hydrates (`removeEntity`).- console.error(`[replica:${resource.name}] failed to read the persisted index`, error);- return false;- }- // Identity changed while reading the index: those rows are not ours to touch.- if (!offScope && resource.scope.get() !== scope) return false;- // Rows this session wrote to the scope may not be in the persisted index yet- // (their row or index write is still queued β e.g. just before an account- // switch). Patch them too: each patch is queued behind the row's own write,- // so it reads the row once that write landed.- for (const queryKey of rows.indexedKeys(scope) ?? [])- if (!keys.includes(queryKey)) keys.push(queryKey);- const patches: Promise<boolean>[] = [];- for (const queryKey of keys) {- if (loaded.has(queryKey)) continue;- patches.push(- rows.patchRow(scope, queryKey, (data) => {- const next = mapEntity(data, id, fn);- if (next === data) return undefined;- return next === undefined ? DROP_ROW : next;- }),- );- }- return (await Promise.all(patches)).every(Boolean);- };-- const patchStoredEntity = async <TItem>(- id: string,- fn: (item: TItem) => TItem | undefined,- ): Promise<void> => {- await patchStoredEntityRows(id, fn);- };-- /**- * `updateEntity`, returning the persisted-row patch (if any) to wait on β- * `true` once every unloaded row is patched.- */- const applyEntity = <TItem>(- id: string,- fn: (item: TItem) => TItem | undefined,- { persist = true }: { persist?: boolean } = {},- ): Promise<boolean> | undefined => {- const patch = persist ? patchStoredEntityRows(id, fn) : undefined;- for (const key of entityKeys(id)) {- const current = port.read(key);- if (current === undefined) continue;- const next = mapEntity(current, id, fn);- if (next === undefined) remove(key);- else- update(key, (data) => (data === undefined ? data : (mapEntity(data, id, fn) ?? data)), {- persist,- });- }- return patch;- };-- /**- * An entity patch started for a scope that was not active settled. If the- * user switched back to that scope meanwhile, an entry may have hydrated the- * pre-patch row before the patch landed: apply the same change to what is- * loaded now, in memory only β storage already holds it.- */- const reconcileLoaded = <TItem>(- scope: string,- id: string,- fn: (item: TItem) => TItem | undefined,- ) => {- if (resource.scope.get() !== scope || getSlot().scope !== scope) return;- for (const key of entityKeys(id)) {- const current = port.read(key);- if (current === undefined) continue;- // A hydrate during the patch may have recorded the pre-patch row as stored.- rows.forgetStored(scope, [replicaStorageKey(key, getSlot().entries[key]?.query)]);- if (mapEntity(current, id, fn) === undefined) remove(key);- else- update(key, (data) => (data === undefined ? data : (mapEntity(data, id, fn) ?? data)), {- persist: false,- });- }- };-- /**- * Confirmed patch of one entity everywhere it is loaded and in the persisted- * rows of unloaded entries. `scope` targets a scope captured earlier (a- * write confirmed after the account switched): when it is no longer active,- * only that scope's persisted rows are patched and the view on screen β- * another identity's β is left alone.- */- const updateEntity = <TItem>(- id: string,- fn: (item: TItem) => TItem | undefined,- options?: { persist?: boolean; scope?: string },- ) => {- if (options?.scope !== undefined && options.scope !== resource.scope.get()) {- const scope = options.scope;- if (options.persist === false) return;- const settle = () => reconcileLoaded(scope, id, fn);- void patchStoredEntityRows(id, fn, scope).then(settle, settle);- return;- }- void applyEntity(id, fn, options);- };-- /**- * Confirmed removal of one entity everywhere (see `updateEntity`, including- * its captured `scope`). Unlike a plain mapper returning `undefined`, it is- * also remembered for that scope:- * a value hydrated afterwards β even by a read already in flight β comes- * back without the entity (see `createEntityRemovalGuards`).- */- const removeEntity = (id: string, options?: { persist?: boolean; scope?: string }) => {- const scope = options?.scope ?? resource.scope.get();- // A removal confirmed after the account switched belongs to the scope that- // asked for it: guard and patch that scope's rows, never the active view.- const offScope = scope !== resource.scope.get();- const release = entityGuards.guardEntity(scope, id);- // A scope left behind has nothing on screen: only its persisted rows drop- // the entity, and the guard keeps a later hydrate there from reading it back.- const patch = offScope- ? options?.persist === false- ? undefined- : patchStoredEntityRows(id, () => undefined, scope).then((patched) => {- // Switched back meanwhile: drop it from anything hydrated since.- reconcileLoaded(scope, id, () => undefined);- return patched;- })- : applyEntity(id, () => undefined, options);- // Without a storage patch (`persist: false`) only reads already in flight- // can hold the entity; with one, reads that start before it lands can too.- // A patch that did not land (untrusted scope, unreadable index or row, a- // failed write, an identity switch) leaves the entity in an unloaded row:- // every later hydrate of that row could resurrect it, so the guard is kept- // β until a server value holds the entity again, or a later removal of the- // same id lands its patch.- if (patch)- void patch.then(- (patched) => {- if (patched) release();- },- () => undefined,- );- else release();- };-- const beginEntityOptimistic = <TItem>(- id: string,- fn: (item: TItem) => TItem | undefined,- ): ReplicaOptimisticToken<TData>[] =>- entityKeys(id).flatMap((key) => {- // Removing a whole value (a detail) is applied on commit, not optimistically.- if (!paging) {- const current = port.read(key);- if (current !== undefined && mapEntity(current, id, fn) === undefined) return [];- }- return [beginOptimistic(key, (data) => mapEntity(data, id, fn) ?? data)];- });-- return {- beginEntityOptimistic,- entityKeys,- forgetRestoredEntities,- patchStoredEntity,- removeEntity,- updateEntity,- withoutRemovedEntities,- };-};diff --git a/packages/replica/src/core/keys.ts b/packages/replica/src/core/keys.tsdeleted file mode 100644index 4fb3b00e068..00000000000--- a/packages/replica/src/core/keys.ts+++ /dev/null@@ -1,27 +0,0 @@-/**- * Keys of the queries a fetch adapter runs for a replica. Hosts that sweep- * their query cache by prefix (e.g. "refetch everything after a restore")- * match on {@link REPLICA_KEY_PREFIX}.- */-export const REPLICA_KEY_PREFIX = 'replica:';--export const replicaKeys = {- /** One-shot read of the persisted row for `storageKey`. */- hydrate: (name: string, version: number, scope: string, storageKey: string) =>- ['replica:hydrate', name, version, scope, storageKey] as const,- /** Network sync of the head of one entry. */- sync: (name: string, version: number, scope: string, key: string, params: unknown) =>- ['replica:sync', name, version, scope, key, params] as const,-};--/** Match a resource's sync keys, optionally narrowed to one scope and/or entry key. */-export const isReplicaSyncKey = (- queryKey: unknown,- name: string,- filter: { key?: string; scope?: string } = {},-): boolean =>- Array.isArray(queryKey) &&- queryKey[0] === 'replica:sync' &&- queryKey[1] === name &&- (filter.scope === undefined || queryKey[3] === filter.scope) &&- (filter.key === undefined || queryKey[4] === filter.key);diff --git a/packages/replica/src/core/paging.test.ts b/packages/replica/src/core/paging.test.tsdeleted file mode 100644index 43a2f3b9e60..00000000000--- a/packages/replica/src/core/paging.test.ts+++ /dev/null@@ -1,552 +0,0 @@-import { describe, expect, expectTypeOf, it } from 'vitest';--import { definePagedReplica } from './defineReplica';-import {- applyHeadPage,- applyNextPage,- collapseToHead,- getNextPageCursor,- insertHeadItems,- mapPagedItem,- type ReplicaPagedData,- type ReplicaPagingConfig,- toPersistedPage,-} from './paging';--interface Row {- id: string;- title?: string;-}--const rows = (...ids: string[]): Row[] => ids.map((id) => ({ id }));-const ids = (data: { items: Row[] }) => data.items.map((item) => item.id);--const offset: ReplicaPagingConfig<Row> = {- direction: 'forward',- getId: (row) => row.id,- mode: 'offset',-};--describe('offset / forward paging (topic-like list)', () => {- const twoPages = () => {- const head = applyHeadPage(- undefined,- { items: rows('a', 'b'), total: 5 },- { pageSize: 2 },- offset,- );- return applyNextPage(head, { items: rows('c', 'd'), total: 5 }, offset);- };-- it('merges the next page and dedupes by id', () => {- const head = applyHeadPage(- undefined,- { items: rows('a', 'b'), total: 5 },- { pageSize: 2 },- offset,- );- expect(head).toMatchObject({ currentPage: 0, hasMore: true, nextCursor: 1 });-- // A row shifted from page 0 into page 1 (offset drift) is not duplicated.- const next = applyNextPage(head, { items: rows('b', 'c'), total: 5 }, offset);- expect(ids(next)).toEqual(['a', 'b', 'c']);- expect(next).toMatchObject({ currentPage: 1, isLoadingMore: false, nextCursor: 2 });- });-- it('a head refresh keeps the loaded depth and dedupes by id', () => {- const refreshed = applyHeadPage(- twoPages(),- { items: rows('new', 'a'), total: 6 },- { pageSize: 2 },- offset,- );- expect(ids(refreshed)).toEqual(['new', 'a', 'b', 'c']);- expect(refreshed.currentPage).toBe(1);- expect(refreshed.hasMore).toBe(true);- });-- it('a query reset or a page-size change collapses to the head page', () => {- const reset = applyHeadPage(- twoPages(),- { items: rows('x'), total: 1 },- { pageSize: 2, reset: true },- offset,- );- expect(ids(reset)).toEqual(['x']);- expect(reset).toMatchObject({ currentPage: 0, hasMore: false, nextCursor: null });-- const resized = applyHeadPage(- twoPages(),- { items: rows('a', 'b', 'c'), total: 5 },- { pageSize: 3 },- offset,- );- expect(resized.currentPage).toBe(0);- });-- it('a head refresh clears the last page error', () => {- const failed = { ...twoPages(), loadMoreError: new Error('boom') };- const refreshed = applyHeadPage(- failed,- { items: rows('a', 'b'), total: 5 },- { pageSize: 2 },- offset,- );- expect(refreshed.loadMoreError).toBeUndefined();- });-- it('keeps client-only rows across head refreshes', () => {- const ctx = { isClientOnly: (row: Row) => row.id === 'tmp' };- const withTmp = insertHeadItems(twoPages(), rows('tmp'), offset);- const refreshed = applyHeadPage(- withTmp,- { items: rows('a', 'b'), total: 5 },- { pageSize: 2 },- offset,- ctx,- );- expect(ids(refreshed)).toEqual(['tmp', 'a', 'b', 'c', 'd']);-- // Once the server returns the row it is no longer duplicated.- const confirmed = applyHeadPage(- refreshed,- { items: rows('tmp', 'a'), total: 6 },- { pageSize: 2 },- offset,- ctx,- );- expect(ids(confirmed).filter((id) => id === 'tmp')).toHaveLength(1);- });-- it('inserts new rows at the head without moving the cursor', () => {- const data = twoPages();- const inserted = insertHeadItems(data, rows('n1', 'a'), offset);- expect(ids(inserted)).toEqual(['n1', 'a', 'b', 'c', 'd']);- expect(inserted.nextCursor).toBe(data.nextCursor);- expect(inserted.total).toBe(6);- expect(inserted.pages?.[0].count).toBe(3);- });-- it('patches and removes a row by id', () => {- const data = twoPages();- const renamed = mapPagedItem(data, 'c', (row) => ({ ...row, title: 'C' }), offset);- expect(renamed.items[2]).toEqual({ id: 'c', title: 'C' });- expect(mapPagedItem(data, 'missing', () => undefined, offset)).toBe(data);-- const removed = mapPagedItem(data, 'c', () => undefined, offset);- expect(ids(removed)).toEqual(['a', 'b', 'd']);- expect(removed.total).toBe(4);- });-- it('derives the offset cursor for views without bookkeeping', () => {- const legacy = { currentPage: 1, hasMore: true, items: rows('a'), pageSize: 1 };- expect(getNextPageCursor(legacy, offset)).toBe(2);- expect(getNextPageCursor({ ...legacy, hasMore: false }, offset)).toBeNull();- });-- describe('server-reported exhaustion (rows filtered after paging)', () => {- it('keeps paging past a short page the server says is not the end', () => {- // The server consumed a full raw window of 3 but filtered one row out.- const head = applyHeadPage(- undefined,- { items: rows('a', 'b'), nextCursor: 1 },- { pageSize: 3 },- offset,- );- expect(head).toMatchObject({ currentPage: 0, hasMore: true, nextCursor: 1 });-- const next = applyNextPage(head, { items: rows('c'), nextCursor: 2 }, offset);- expect(next).toMatchObject({ currentPage: 1, hasMore: true, nextCursor: 2 });-- const last = applyNextPage(next, { items: rows('d', 'e', 'f'), nextCursor: null }, offset);- expect(last).toMatchObject({ currentPage: 2, hasMore: false, nextCursor: null });- });-- it('persists the server verdict for a short head page', () => {- const head = applyHeadPage(- undefined,- { items: rows('a', 'b'), nextCursor: 1 },- { pageSize: 3 },- offset,- );- expect(toPersistedPage(head, offset)).toMatchObject({ hasMore: true, nextCursor: 1 });-- const done = applyHeadPage(- undefined,- { items: rows('a', 'b'), nextCursor: null },- { pageSize: 3 },- offset,- );- expect(toPersistedPage(done, offset)).toMatchObject({ hasMore: false, nextCursor: null });- });- });-- describe('persistence limits', () => {- it('persists the head page only by default, without flags or client-only rows', () => {- const data = { ...insertHeadItems(twoPages(), rows('tmp'), offset), isLoadingMore: true };- const persisted = toPersistedPage(data, offset, { isClientOnly: (row) => row.id === 'tmp' });- expect(ids(persisted)).toEqual(['a', 'b']);- expect(persisted).toMatchObject({ currentPage: 0, hasMore: true, nextCursor: 1 });- expect(persisted).not.toHaveProperty('isLoadingMore');- });-- it('honours persist.pages and persist.maxItems', () => {- const threePages = applyNextPage(twoPages(), { items: rows('e'), total: 5 }, offset);- const pages = toPersistedPage(threePages, { ...offset, persist: { pages: 2 } });- expect(ids(pages)).toEqual(['a', 'b', 'c', 'd']);- expect(pages).toMatchObject({ currentPage: 1, nextCursor: 2 });-- // maxItems cuts at a page boundary so the persisted offset stays valid.- const capped = toPersistedPage(threePages, { ...offset, persist: { maxItems: 3, pages: 3 } });- expect(ids(capped)).toEqual(['a', 'b']);- expect(capped.currentPage).toBe(0);- });- });-});--/**- * Message-like fixture: transcript ascending by createdAt (newest last),- * "load older" prepends, the server cursor is `{ createdAt, id }` and `null`- * marks the topic start β mirrors `getMessagesByCursor` / `olderCursor`.- */-describe('cursor / backward paging (message-like transcript)', () => {- interface Message {- createdAt: number;- id: string;- }- interface Cursor {- createdAt: number;- id: string;- }- const msg = (n: number): Message => ({ createdAt: n, id: `m${n}` });- const range = (from: number, to: number) =>- Array.from({ length: to - from + 1 }, (_, i) => msg(from + i));- const cursorOf = (m: Message): Cursor => ({ createdAt: m.createdAt, id: m.id });- const messages: ReplicaPagingConfig<Message> = {- direction: 'backward',- getId: (m) => m.id,- mode: 'cursor',- persist: { maxItems: 100 },- sort: (a, b) => a.createdAt - b.createdAt,- };- const mids = (data: ReplicaPagedData<Message, Cursor>) => data.items.map((m) => m.id);-- const loadedTwoWindows = () => {- const head = applyHeadPage<Message, Cursor>(- undefined,- { items: range(7, 10), nextCursor: cursorOf(msg(7)) },- { pageSize: 4 },- messages,- );- return applyNextPage(head, { items: range(3, 6), nextCursor: cursorOf(msg(3)) }, messages);- };-- it('prepends older history and pins the join anchor', () => {- const data = loadedTwoWindows();- expect(mids(data)).toEqual(['m3', 'm4', 'm5', 'm6', 'm7', 'm8', 'm9', 'm10']);- expect(data.anchorId).toBe('m7');- expect(data.nextCursor).toEqual({ createdAt: 3, id: 'm3' });- });-- it('marks the topic start on a null cursor or an empty page', () => {- const exhausted = applyNextPage(- loadedTwoWindows(),- { items: range(1, 2), nextCursor: null },- messages,- );- expect(exhausted.hasMore).toBe(false);- const empty = applyNextPage(- loadedTwoWindows(),- { items: [], nextCursor: cursorOf(msg(3)) },- messages,- );- expect(empty.nextCursor).toBeNull();- });-- it('streamed messages land at the newest end without breaking the older cursor', () => {- const data = insertHeadItems(loadedTwoWindows(), [msg(11)], messages);- expect(mids(data).at(-1)).toBe('m11');- expect(data.nextCursor).toEqual({ createdAt: 3, id: 'm3' });- });-- it('keeps older pages when the refreshed window still contains the anchor', () => {- const refreshed = applyHeadPage(- loadedTwoWindows(),- { items: range(7, 11), nextCursor: cursorOf(msg(7)) },- { pageSize: 4 },- messages,- );- expect(mids(refreshed)).toEqual(range(3, 11).map((m) => m.id));- expect(refreshed.nextCursor).toEqual({ createdAt: 3, id: 'm3' });- });-- // Round-trimmed windows change length on every refresh; a cursor walk must- // not read that as a query change and drop the loaded history.- it('keeps older pages when the refreshed window has another length', () => {- const refreshed = applyHeadPage(- loadedTwoWindows(),- { items: range(7, 12), nextCursor: cursorOf(msg(7)) },- { pageSize: 6 },- messages,- );- expect(mids(refreshed)).toEqual(range(3, 12).map((m) => m.id));- expect(refreshed.currentPage).toBe(1);- });-- it.each(['backward', 'forward'] as const)(- 'refreshes the head cursor before trimming %s pages',- (direction) => {- const config = {- ...messages,- direction,- sort: (a: Message, b: Message) =>- direction === 'backward' ? a.createdAt - b.createdAt : b.createdAt - a.createdAt,- };- const view = (rows: Message[]) => (direction === 'backward' ? rows : [...rows].reverse());- const head = applyHeadPage<Message, Cursor>(- undefined,- { items: view(range(7, 10)), nextCursor: cursorOf(msg(7)) },- { pageSize: 4 },- config,- );- const extended = applyNextPage(- head,- { items: view(range(3, 6)), nextCursor: cursorOf(msg(3)) },- config,- );- const refreshed = applyHeadPage(- extended,- { items: view(range(6, 10)), nextCursor: cursorOf(msg(6)) },- { pageSize: 5 },- config,- );- expect(refreshed.nextCursor).toEqual(cursorOf(msg(3)));- for (const trimmed of [- collapseToHead(refreshed, config),- toPersistedPage(refreshed, config),- ]) {- expect(trimmed.items).toEqual(view(range(6, 10)));- expect(getNextPageCursor(trimmed, config)).toEqual(cursorOf(msg(6)));- }- },- );-- describe('synthetic group nodes', () => {- interface Node extends Message {- role?: 'compressedGroup' | 'user';- }- const grouped: ReplicaPagingConfig<Node> = {- ...(messages as ReplicaPagingConfig<Node>),- isCursorable: (m) => m.role !== 'compressedGroup',- };- const group = (n: number): Node => ({ createdAt: n, id: `g${n}`, role: 'compressedGroup' });-- it.each(['backward', 'forward'] as const)(- 'retains synthetic head rows sorted outside the head in %s views',- (direction) => {- const config = {- ...grouped,- direction,- sort: (a: Node, b: Node) =>- direction === 'backward' ? a.createdAt - b.createdAt : b.createdAt - a.createdAt,- };- const view = (rows: Node[]) => (direction === 'backward' ? rows : [...rows].reverse());- const head = applyHeadPage<Node, Cursor>(- undefined,- { items: view([group(0), ...range(7, 10)]), nextCursor: cursorOf(msg(7)) },- { pageSize: 5 },- config,- );- const extended = applyNextPage(- head,- { items: view(range(3, 6)), nextCursor: cursorOf(msg(3)) },- config,- );- for (const trimmed of [- collapseToHead(extended, config),- toPersistedPage(extended, config),- ]) {- expect(trimmed.items).toEqual(view([group(0), ...range(7, 10)]));- expect(trimmed.nextCursor).toEqual(cursorOf(msg(7)));- }- },- );-- it('never pins the join anchor on a synthetic node', () => {- const head = applyHeadPage<Node, Cursor>(- undefined,- { items: [group(6), ...range(7, 10)], nextCursor: cursorOf(msg(7)) },- { pageSize: 5 },- grouped,- );- const extended = applyNextPage(head, { items: range(3, 5), nextCursor: null }, grouped);- expect(extended.anchorId).toBe('m7');-- // The refreshed window still holds m7, so the older page survives even- // though the group node in front of it was re-summarized away.- const refreshed = applyHeadPage(- extended,- { items: range(7, 11), nextCursor: cursorOf(msg(7)) },- { pageSize: 5 },- grouped,- );- expect(mids(refreshed)).toEqual(['m3', 'm4', 'm5', ...range(7, 11).map((m) => m.id)]);- });- });-- describe('plain list without server cursors (threads)', () => {- const plain: ReplicaPagingConfig<Message, Cursor> = {- ...messages,- deriveCursor: cursorOf,- isCursorable: (m) => !m.id.startsWith('g'),- };-- it('derives the next cursor from the oldest eligible row', () => {- const head = applyHeadPage<Message, Cursor>(- undefined,- { items: [{ createdAt: 6, id: 'g6' }, ...range(7, 10)] },- { pageSize: 5 },- plain,- );- expect(head.hasMore).toBe(true);- expect(getNextPageCursor(head, plain)).toEqual({ createdAt: 7, id: 'm7' });- });-- it('keeps loaded pages across head refreshes and ends on an empty page', () => {- const head = applyHeadPage<Message, Cursor>(- undefined,- { items: range(7, 10) },- { pageSize: 4 },- plain,- );- const extended = applyNextPage(head, { items: range(3, 6) }, plain);- expect(getNextPageCursor(extended, plain)).toEqual({ createdAt: 3, id: 'm3' });-- const refreshed = applyHeadPage(extended, { items: range(7, 11) }, { pageSize: 5 }, plain);- expect(mids(refreshed)).toEqual(range(3, 11).map((m) => m.id));-- const done = applyNextPage(refreshed, { items: [] }, plain);- expect(getNextPageCursor(done, plain)).toBeNull();- });-- it('waits for a server cursor when the resource cannot derive one', () => {- const head = applyHeadPage<Message, Cursor>(- undefined,- { items: range(7, 10) },- { pageSize: 4 },- messages,- );- expect(getNextPageCursor(head, messages)).toBeUndefined();- });- });-- it('keeps the server order of rows the sort ties', () => {- const sameTick = applyHeadPage<Message, Cursor>(- undefined,- {- items: [- { createdAt: 5, id: 'z-user' },- { createdAt: 5, id: 'a-assistant' },- ],- nextCursor: null,- },- { pageSize: 2 },- messages,- );- expect(mids(sameTick)).toEqual(['z-user', 'a-assistant']);- });-- it('collapses to the fresh window when it slid past the anchor (gap)', () => {- const refreshed = applyHeadPage(- loadedTwoWindows(),- { items: range(9, 12), nextCursor: cursorOf(msg(9)) },- { pageSize: 4 },- messages,- );- expect(mids(refreshed)).toEqual(['m9', 'm10', 'm11', 'm12']);- expect(refreshed.currentPage).toBe(0);- expect(refreshed.nextCursor).toEqual({ createdAt: 9, id: 'm9' });- });-- it('keeps optimistic (tmp) messages at the newest end across refreshes', () => {- const ctx = { isClientOnly: (m: Message) => m.id.startsWith('tmp') };- const withTmp = insertHeadItems(loadedTwoWindows(), [{ createdAt: 99, id: 'tmp_1' }], messages);- const refreshed = applyHeadPage(- withTmp,- { items: range(7, 10), nextCursor: cursorOf(msg(7)) },- { pageSize: 4 },- messages,- ctx,- );- expect(mids(refreshed).at(-1)).toBe('tmp_1');- expect(toPersistedPage(refreshed, messages, ctx).items.some((m) => m.id === 'tmp_1')).toBe(- false,- );- });-- it('collapse after an edit in older history keeps the newest window and its cursor', () => {- const collapsed = collapseToHead(loadedTwoWindows(), messages);- expect(mids(collapsed)).toEqual(['m7', 'm8', 'm9', 'm10']);- expect(collapsed.nextCursor).toEqual({ createdAt: 7, id: 'm7' });- });-- it('persists rows appended to the head after it was fetched', () => {- const head = applyHeadPage<Message, Cursor>(- undefined,- { items: range(1, 4), nextCursor: null },- { pageSize: 4 },- messages,- );- // A sent message and its reply land through a plain write, not a page.- const grown = { ...head, items: [...head.items, msg(5), msg(6)] };-- expect(mids(toPersistedPage(grown, messages))).toEqual(['m1', 'm2', 'm3', 'm4', 'm5', 'm6']);- // With older pages loaded, only the head (and its growth) is kept.- const loaded = loadedTwoWindows();- const loadedGrown = { ...loaded, items: [...loaded.items, msg(11)] };- expect(mids(toPersistedPage(loadedGrown, messages))).toEqual(['m7', 'm8', 'm9', 'm10', 'm11']);- });-- it('persists the newest window, capped by maxItems; a cut forgets the cursor', () => {- const persisted = toPersistedPage(loadedTwoWindows(), messages);- expect(mids(persisted)).toEqual(['m7', 'm8', 'm9', 'm10']);- expect(persisted.nextCursor).toEqual({ createdAt: 7, id: 'm7' });-- const capped = toPersistedPage(loadedTwoWindows(), { ...messages, persist: { maxItems: 2 } });- expect(mids(capped)).toEqual(['m9', 'm10']);- expect(capped.nextCursor).toBeUndefined();- });-});--describe('paged resource cursor types', () => {- it('preserves an object cursor in the configuration and resource', () => {- interface Cursor {- id: string;- }- const resource = definePagedReplica<undefined, Row, Cursor>({- key: () => 'rows',- name: 'rows',- version: 1,- paging: {- direction: 'backward',- getId: (row) => row.id,- mode: 'cursor',- deriveCursor: (row) => ({ id: row.id }),- },- });- expectTypeOf(resource.paging!.deriveCursor!).returns.toEqualTypeOf<Cursor>();- expectTypeOf(resource.fetcher!).parameter(1).toEqualTypeOf<Cursor | undefined>();- definePagedReplica<undefined, Row, Cursor>({- key: () => 'invalid',- name: 'invalid',- version: 1,- paging: {- direction: 'backward',- getId: (row) => row.id,- mode: 'cursor',- // @ts-expect-error An object-cursor resource cannot derive a string cursor.- deriveCursor: (row) => row.id,- },- });- });-});diff --git a/packages/replica/src/core/paging.ts b/packages/replica/src/core/paging.tsdeleted file mode 100644index 2741b247f84..00000000000--- a/packages/replica/src/core/paging.ts+++ /dev/null@@ -1,574 +0,0 @@-/**- * First-class pagination for replicas.- *- * Vocabulary (direction-agnostic):- * - HEAD page: the newest window, what a refresh re-fetches (`cursor` undefined).- * - NEXT pages: further pages in the paging direction (older history).- * - `forward`: the view is head-first, next pages append at the END- * (sidebar lists: newest topic first, "load more" below).- * - `backward`: the view is oldest-first, next pages PREPEND at the start- * (chat transcripts: newest message last, "load older" on scroll-up).- * - `offset` mode: the cursor is the page index (0 = head).- * `cursor` mode: the server hands back an opaque `nextCursor`.- *- * Every function is pure; the store binding owns staleness and scope.- */--export type ReplicaPagingMode = 'cursor' | 'offset';-export type ReplicaPagingDirection = 'backward' | 'forward';--export interface ReplicaPagingConfig<TItem, TCursor = any> {- /**- * Cursor mode: cursor to the page past `item`, the last cursor-eligible row- * on the far side, for a server that pages by row but reports no- * `nextCursor` (a plain list). Only safe when the row carries a lossless- * position; omit it when the server owns the cursor, and paging then waits- * for one.- */- deriveCursor?: (item: TItem) => TCursor;- direction: ReplicaPagingDirection;- /**- * Per-entry direction, for a resource whose entries read differently (a- * transcript read from its first round). Defaults to `direction`. Persisting- * an entry always uses `direction`, so keep such entries in memory.- */- directionOf?: (key: string) => ReplicaPagingDirection;- getId: (item: TItem) => string;- /**- * Rows that may anchor a join or derive a cursor. Synthetic rows the query- * injects (group / summary nodes) have no position of their own on the- * server, so they are skipped. Defaults to every row.- */- isCursorable?: (item: TItem) => boolean;- mode: ReplicaPagingMode;- /** Which part survives a reload. Defaults to the head page only. */- persist?: {- /** Hard cap on persisted items (taken from the head side). */- maxItems?: number;- /** Number of pages from the head side. Default 1. */- pages?: number;- };- /**- * Optional total order re-applied after every merge (e.g. messages by- * createdAt). The sort is stable: rows the comparator ties keep the order- * the server sent them in, so compare positions only β an id tie-break- * would reorder rows created within the same tick.- */- sort?: (a: TItem, b: TItem) => number;-}--export interface ReplicaPageResult<TItem, TCursor> {- items: TItem[];- /**- * Cursor mode: next page cursor; `null` = exhausted, `undefined` = unknown.- * Offset mode: the server's own verdict β `null` = exhausted, any other- * value = more pages (the engine still advances by page index); `undefined`- * falls back to `total` / a full page. A server that filters rows after- * paging returns short pages that are not the end, so it must report this.- */- nextCursor?: TCursor | null;- total?: number;-}--export interface ReplicaPageInfo<TCursor> {- /** Items this page contributed after de-duplication. */- count: number;- /** Cursor of the page after this one; `null` = exhausted, `undefined` = unknown. */- next?: TCursor | null;-}--/**- * The paged view a resource keeps in the store. Domain views extend it, so- * selectors read `items` / `hasMore` / `isLoadingMore` as before.- */-export interface ReplicaPagedData<TItem, TCursor = number> {- /**- * Boundary row of the head page once more pages are loaded (forward: its- * last row, backward: its first row). A refreshed head page that no longer- * contains it has slid past the loaded pages β merging would hide a gap.- */- anchorId?: string;- /** Index of the last merged page (0 = head only). */- currentPage: number;- hasMore: boolean;- /**- * Synthetic (non-cursorable) rows of the head page. A sort can place them- * among older pages, so a head refresh drops them by id rather than by- * position β the fresh head brings its own.- */- headSyntheticIds?: string[];- isLoadingMore?: boolean;- items: TItem[];- loadMoreError?: unknown;- /** Cursor for the next page (offset: page index). `null` = exhausted. */- nextCursor?: TCursor | null;- /** Per-page bookkeeping, head first. Missing on legacy data = one page. */- pages?: ReplicaPageInfo<TCursor>[];- pageSize: number;- total?: number;-}--export interface ReplicaPagingContext<TItem> {- /**- * Client-only rows (optimistic inserts whose server row may not exist yet).- * They survive head refreshes and are never persisted.- */- isClientOnly?: (item: TItem) => boolean;-}--const dedupe = <TItem>(- items: TItem[],- getId: (item: TItem) => string,- seen = new Set<string>(),-) => {- const out: TItem[] = [];- for (const item of items) {- const id = getId(item);- if (seen.has(id)) continue;- seen.add(id);- out.push(item);- }- return out;-};--const ordered = <TItem>(items: TItem[], config: ReplicaPagingConfig<TItem>) =>- config.sort ? [...items].sort(config.sort) : items;--/** Concatenate in view order: forward = head first, backward = head last. */-export const joinPages = <TItem>(- head: TItem[],- rest: TItem[],- direction: ReplicaPagingDirection,-) => (direction === 'forward' ? [...head, ...rest] : [...rest, ...head]);--/** The paging config one entry reads with: `directionOf` resolved for `key`. */-export const pagingFor = <TItem, TCursor>(- config: ReplicaPagingConfig<TItem, TCursor>,- key: string,-) => (config.directionOf ? { ...config, direction: config.directionOf(key) } : config);--const deriveHasMore = <TItem, TCursor>(- data: Pick<ReplicaPagedData<TItem, TCursor>, 'items' | 'nextCursor' | 'total'>,- serverCount: number,-) => (data.total !== undefined ? data.total > serverCount : data.nextCursor !== null);--const offsetNext = (more: boolean, nextIndex: number) => (more ? nextIndex : null);--/** Offset mode: whether a page past the loaded ones exists. */-const offsetHasMore = <TItem, TCursor>(- page: ReplicaPageResult<TItem, TCursor>,- total: number | undefined,- serverCount: number,- pageSize: number,-) => {- if (page.nextCursor !== undefined) return page.nextCursor !== null;- return total !== undefined ? total > serverCount : page.items.length >= pageSize;-};--/**- * Cursor to request the next page with; `null` β exhausted, `undefined` β- * cannot page yet. Offset views without bookkeeping (seeded by legacy code or- * an older persisted shape) derive it from `currentPage` / `hasMore`.- */-export const getNextPageCursor = <TItem, TCursor>(- data: ReplicaPagedData<TItem, TCursor> | undefined,- config: Pick<- ReplicaPagingConfig<TItem, TCursor>,- 'deriveCursor' | 'direction' | 'isCursorable' | 'mode'- >,-): TCursor | null | undefined => {- if (!data) return undefined;- if (data.nextCursor !== undefined) return data.nextCursor;- if (config.mode === 'offset')- return (data.hasMore ? (data.currentPage ?? 0) + 1 : null) as TCursor | null;- if (!config.deriveCursor || !data.hasMore) return undefined;- const boundary = farBoundary(data.items, config);- return boundary === undefined ? undefined : config.deriveCursor(boundary);-};--/**- * The boundary row on the far side of `items` (forward: last, backward: first)- * that may anchor a join or derive a cursor.- */-const farBoundary = <TItem>(- items: TItem[],- config: Pick<ReplicaPagingConfig<TItem>, 'direction' | 'isCursorable'>,-): TItem | undefined => {- const eligible = config.isCursorable ?? (() => true);- if (config.direction === 'forward') return items.findLast((item) => eligible(item));- return items.find((item) => eligible(item));-};--const syntheticIds = <TItem>(- items: TItem[],- config: Pick<ReplicaPagingConfig<TItem>, 'getId' | 'isCursorable'>,-): string[] | undefined => {- if (!config.isCursorable) return undefined;- const ids = items.filter((item) => !config.isCursorable!(item)).map(config.getId);- return ids.length ? ids : undefined;-};--const splitClientOnly = <TItem>(items: TItem[], ctx: ReplicaPagingContext<TItem>) => {- if (!ctx.isClientOnly) return { clientOnly: [] as TItem[], server: items };- const clientOnly: TItem[] = [];- const server: TItem[] = [];- for (const item of items) (ctx.isClientOnly(item) ? clientOnly : server).push(item);- return { clientOnly, server };-};--/**- * Fold a fresh HEAD page into the view.- *- * - First load, a query change (`reset`) or an unextended view β the head page.- * - Extended view, `offset` mode β keep the loaded depth: fresh head first,- * then previously loaded rows not in it (shifted offsets self-heal by id).- * - Extended view, `cursor` mode β keep older pages only when the fresh head- * still contains the join anchor and the next cursor is known; otherwise- * collapse to the head page (never show a hidden gap).- *- * Client-only rows still in the view are kept on the head side.- */-export const applyHeadPage = <TItem, TCursor>(- current: ReplicaPagedData<TItem, TCursor> | undefined,- page: ReplicaPageResult<TItem, TCursor>,- options: { pageSize: number; reset?: boolean },- config: ReplicaPagingConfig<TItem, TCursor>,- ctx: ReplicaPagingContext<TItem> = {},-): ReplicaPagedData<TItem, TCursor> => {- const { getId, direction } = config;- const fresh = dedupe(page.items, getId);- const freshIds = new Set(fresh.map(getId));- const { clientOnly, server: currentServer } = splitClientOnly(current?.items ?? [], ctx);- const survivors = clientOnly.filter((item) => !freshIds.has(getId(item)));- const total = page.total ?? (options.reset ? undefined : current?.total);- // Client-only rows are the newest: they sit at the very head of the view.- const headItems = direction === 'forward' ? [...survivors, ...fresh] : [...fresh, ...survivors];-- const headOnly = (): ReplicaPagedData<TItem, TCursor> => {- const nextCursor =- config.mode === 'offset'- ? (offsetNext(- offsetHasMore(page, total, fresh.length, options.pageSize),- 1,- ) as TCursor | null)- : page.nextCursor;- const data = {- anchorId: undefined,- currentPage: 0,- headSyntheticIds: syntheticIds(fresh, config),- items: ordered(headItems, config),- nextCursor,- pageSize: options.pageSize,- pages: [{ count: fresh.length, next: nextCursor }],- total,- };- return {- ...data,- hasMore: deriveHasMore(data, fresh.length),- isLoadingMore: current?.isLoadingMore,- // A fresh head page supersedes the last page failure.- loadMoreError: undefined,- };- };-- const extended = !!current && current.currentPage > 0 && !options.reset;- // A cursor walk keys pages by position, so a head page of another length- // (round-trimmed windows vary on every refresh) still joins by its anchor.- if (!extended || (config.mode === 'offset' && current.pageSize !== options.pageSize))- return headOnly();-- let rest: TItem[];- let anchorId: string | undefined;- if (config.mode === 'offset') {- const restCandidates = currentServer.filter((item) => !freshIds.has(getId(item)));- // Keep the depth the user scrolled to, bounded by what still exists.- const visible = Math.min(currentServer.length, total ?? Number.POSITIVE_INFINITY);- const keep = Math.max(0, visible - fresh.length);- rest =- direction === 'forward'- ? restCandidates.slice(0, keep)- : restCandidates.slice(Math.max(0, restCandidates.length - keep));- } else {- const anchorIndex = current.anchorId- ? currentServer.findIndex((item) => getId(item) === current.anchorId)- : -1;- // Without a known next cursor the loaded pages can only be kept when the- // cursor is derivable from the rows themselves.- const cursorKnown = current.nextCursor !== undefined || !!config.deriveCursor;- if (anchorIndex === -1 || !freshIds.has(current.anchorId!) || !cursorKnown) return headOnly();- const farSide =- direction === 'forward'- ? currentServer.slice(anchorIndex + 1)- : currentServer.slice(0, anchorIndex);- const staleHead = new Set(current.headSyntheticIds);- rest = farSide.filter((item) => !freshIds.has(getId(item)) && !staleHead.has(getId(item)));- const boundary = farBoundary(fresh, config);- anchorId = boundary ? getId(boundary) : current.anchorId;- }-- const headNext = config.mode === 'cursor' ? page.nextCursor : current.pages?.[0]?.next;- // A larger head absorbs rows the older pages were counted with; shed the- // overlap from the pages nearest the head so later trims cut at the boundary.- let overlap =- (current.pages ?? []).slice(1).reduce((sum, info) => sum + info.count, 0) - rest.length;- const olderPages = (current.pages ?? []).slice(1).map((info) => {- const shed = Math.min(info.count, Math.max(0, overlap));- overlap -= shed;- return shed ? { ...info, count: info.count - shed } : info;- });- const pages = [{ count: fresh.length, next: headNext }, ...olderPages];- const data = {- anchorId: anchorId ?? current.anchorId,- currentPage: current.currentPage,- headSyntheticIds: syntheticIds(fresh, config),- items: ordered(joinPages(headItems, rest, direction), config),- nextCursor: current.nextCursor,- pageSize: options.pageSize,- pages,- total,- };- return {- ...data,- hasMore: deriveHasMore(data, fresh.length + rest.length),- isLoadingMore: current.isLoadingMore,- loadMoreError: undefined,- };-};--/** Merge the NEXT page (fetched with `getNextPageCursor`) into the view. */-export const applyNextPage = <TItem, TCursor>(- current: ReplicaPagedData<TItem, TCursor>,- page: ReplicaPageResult<TItem, TCursor>,- config: ReplicaPagingConfig<TItem, TCursor>,- ctx: ReplicaPagingContext<TItem> = {},-): ReplicaPagedData<TItem, TCursor> => {- const { getId, direction } = config;- const seen = new Set(current.items.map(getId));- const added = dedupe(page.items, getId, seen);- const total = page.total ?? current.total;- const serverCount = splitClientOnly(current.items, ctx).server.length + added.length;-- let next: TCursor | null | undefined;- if (config.mode === 'offset') {- const more = offsetHasMore(page, total, serverCount, current.pageSize);- next = offsetNext(more, current.currentPage + 2) as TCursor | null;- } else {- // Only an empty page marks the end when the server reports no cursor.- next = page.items.length === 0 ? null : page.nextCursor;- }-- // The first extension pins the join anchor at the head page's boundary.- let anchorId = current.anchorId;- if (current.currentPage === 0) {- const boundary = farBoundary(splitClientOnly(current.items, ctx).server, config);- anchorId = boundary ? getId(boundary) : undefined;- }-- const items = ordered(- direction === 'forward' ? [...current.items, ...added] : [...added, ...current.items],- config,- );- const data = {- ...current,- anchorId,- currentPage: current.currentPage + 1,- isLoadingMore: false,- items,- loadMoreError: undefined,- nextCursor: next,- pages: [- ...(current.pages?.length ? current.pages : [{ count: current.items.length }]),- { count: added.length, next },- ],- total,- };- return { ...data, hasMore: deriveHasMore(data, serverCount) };-};--/**- * Insert new rows on the HEAD side (a streamed message, a created topic).- * Cursors point at the far end, so they stay valid; offsets shift and are- * healed by id de-duplication on the next page merge.- */-export const insertHeadItems = <TItem, TCursor>(- current: ReplicaPagedData<TItem, TCursor>,- items: TItem[],- config: ReplicaPagingConfig<TItem, TCursor>,-): ReplicaPagedData<TItem, TCursor> => {- const seen = new Set(current.items.map(config.getId));- const added = dedupe(items, config.getId, seen);- if (added.length === 0) return current;- const pages = current.pages?.length ? current.pages : [{ count: current.items.length }];- return {- ...current,- items: ordered(joinPages(added, current.items, config.direction), config),- pages: [{ ...pages[0], count: pages[0].count + added.length }, ...pages.slice(1)],- total: current.total === undefined ? undefined : current.total + added.length,- };-};--/**- * Patch (or remove, when `fn` returns `undefined`) one row by id. Returns the- * same reference when the row is absent or unchanged.- */-export const mapPagedItem = <TItem, TCursor, TData extends ReplicaPagedData<TItem, TCursor>>(- current: TData,- id: string,- fn: (item: TItem) => TItem | undefined,- config: Pick<ReplicaPagingConfig<TItem>, 'getId'>,-): TData => {- const index = current.items.findIndex((item) => config.getId(item) === id);- if (index === -1) return current;- const next = fn(current.items[index]);- if (next === current.items[index]) return current;- if (next !== undefined) {- const items = [...current.items];- items[index] = next;- return { ...current, items };- }- const items = current.items.filter((_, i) => i !== index);- const total = current.total === undefined ? undefined : Math.max(items.length, current.total - 1);- return {- ...current,- hasMore: total !== undefined ? total > items.length : current.hasMore,- items,- total,- };-};--/** Whether a paged view holds a row. */-export const hasPagedItem = <TItem>(- data: ReplicaPagedData<TItem, unknown> | undefined,- id: string,- config: Pick<ReplicaPagingConfig<TItem>, 'getId'>,-) => !!data?.items.some((item) => config.getId(item) === id);--/** Select head-side rows without losing synthetic head rows sorted among older pages. */-const takeHeadItems = <TItem, TCursor>(- items: TItem[],- count: number,- data: ReplicaPagedData<TItem, TCursor>,- config: ReplicaPagingConfig<TItem, TCursor>,-): TItem[] => {- if (count === 0) return [];- const synthetic = new Set(data.headSyntheticIds);- const syntheticCount = items.filter((item) => synthetic.has(config.getId(item))).length;- const regular = items.filter((item) => !synthetic.has(config.getId(item)));- const regularCount = Math.max(0, count - syntheticCount);- const selected =- config.direction === 'forward'- ? regular.slice(0, regularCount)- : regular.slice(Math.max(0, regular.length - regularCount));- const ids = new Set(selected.map(config.getId));- return items- .filter((item) => synthetic.has(config.getId(item)) || ids.has(config.getId(item)))- .slice(- config.direction === 'forward' ? 0 : -count,- config.direction === 'forward' ? count : undefined,- );-};--/** Drop every loaded page but the head (e.g. after an edit inside older history). */-export const collapseToHead = <TItem, TCursor>(- current: ReplicaPagedData<TItem, TCursor>,- config: ReplicaPagingConfig<TItem, TCursor>,-): ReplicaPagedData<TItem, TCursor> => {- if (current.currentPage === 0) return current;- const head = current.pages?.[0];- const count = head?.count ?? current.pageSize;- const items = takeHeadItems(current.items, count, current, config);- const nextCursor = config.mode === 'offset' ? (1 as TCursor) : (head?.next ?? undefined);- return {- ...current,- anchorId: undefined,- currentPage: 0,- hasMore: true,- items,- nextCursor,- pages: [{ count: items.length, next: nextCursor }],- };-};--/**- * What survives a reload: whole pages from the head side, bounded by- * `persist.pages` and `persist.maxItems`, client-only rows and transient- * flags stripped. Offset views are cut at page-size boundaries so the- * persisted `currentPage` stays a valid offset; a cut inside a cursor page- * forgets the cursor (pagination resumes after the next server head page).- */-export const toPersistedPage = <TItem, TCursor, TData extends ReplicaPagedData<TItem, TCursor>>(- data: TData,- config: ReplicaPagingConfig<TItem, TCursor>,- ctx: ReplicaPagingContext<TItem> = {},-): TData => {- const { server } = splitClientOnly(data.items, ctx);- const pageLimit = Math.max(1, config.persist?.pages ?? 1);- const maxItems = config.persist?.maxItems ?? Number.POSITIVE_INFINITY;- // The head page absorbs every row written since it was fetched (a sent- // message, a streamed reply): older pages keep their fetched size, so the- // head is whatever they do not account for.- const olderCount = (data.pages ?? []).slice(1).reduce((sum, page) => sum + page.count, 0);- const pages = data.pages?.length- ? [{ ...data.pages[0], count: Math.max(0, server.length - olderCount) }, ...data.pages.slice(1)]- : [{ count: server.length, next: data.nextCursor }];-- let count = 0;- let keptPages = 0;- let aligned = true;- if (config.mode === 'offset') {- const loadedPages = Math.min(pageLimit, data.currentPage + 1);- const byItems = Math.floor(maxItems / Math.max(1, data.pageSize));- keptPages = Math.max(1, Math.min(loadedPages, byItems || 1));- count = Math.min(server.length, keptPages * data.pageSize, maxItems);- } else {- for (const page of pages.slice(0, pageLimit)) {- if (count + page.count > maxItems) {- aligned = false;- count = keptPages === 0 ? Math.min(page.count, maxItems) : count;- if (keptPages === 0) keptPages = 1;- break;- }- count += page.count;- keptPages += 1;- }- count = Math.min(count, server.length);- }-- const items = takeHeadItems(server, count, data, config);- const lastKept = pages[keptPages - 1];- const nextCursor =- config.mode === 'offset'- ? ((count < (data.total ?? server.length) ||- // Every loaded row survives: the server's own verdict on the page past- // them still holds (a filtered short page is not necessarily the end).- (count === server.length && data.total === undefined && data.nextCursor != null)- ? keptPages- : null) as TCursor | null)- : aligned- ? lastKept?.next- : undefined;-- const {- isLoadingMore: _loading,- loadMoreError: _error,- ...rest- } = data as ReplicaPagedData<TItem, TCursor>;- return {- ...rest,- anchorId: keptPages > 1 ? data.anchorId : undefined,- currentPage: keptPages - 1,- hasMore: data.total !== undefined ? data.total > items.length : nextCursor !== null,- items,- nextCursor,- pages: [- ...pages.slice(0, keptPages - 1),- {- count: Math.max(- 0,- items.length - pages.slice(0, keptPages - 1).reduce((sum, page) => sum + page.count, 0),- ),- next: nextCursor,- },- ],- } as unknown as TData;-};diff --git a/packages/replica/src/core/persistedRows.ts b/packages/replica/src/core/persistedRows.tsdeleted file mode 100644index add218b1cb9..00000000000--- a/packages/replica/src/core/persistedRows.ts+++ /dev/null@@ -1,468 +0,0 @@-import isEqual from 'fast-deep-equal';--import { isReplicaStorageKeyOf, replicaStorageKey } from './defineReplica';-import type { ReplicaResource, ReplicaState } from './types';-import { readReplicaRowStrict, type ReplicaWriteQueue } from './writeQueue';--/** Reserved storage key of the per-scope index of persisted rows. */-export const REPLICA_INDEX_KEY = '__replica:index';--export interface ReplicaPersistedRowsDeps<TData> {- /** Drop evicted entries from the host view (one commit). */- commit: (keys: string[], state: ReplicaState<TData>) => void;- getSlot: () => ReplicaState<TData>;- /** Whether `scope`/`key` is guarded as removed (see `createRemovalGuards`). */- isRemoved: (scope: string, key: string) => boolean;- /** Keys with a `loadMore` request in flight (pinned against eviction). */- loadingMore: ReadonlySet<string>;- resource: ReplicaResource<any, TData, any>;- writeQueue: ReplicaWriteQueue<TData> | undefined;-}--/** Returned by a `patchRow` transform to delete the row (`null` stays a value). */-export const DROP_ROW = Symbol('replica.dropRow');--/**- * Bookkeeping of the rows one engine persisted: the per-scope index, the latest- * queued write per row, what each row is known to hold, and the bounded- * (`persist.maxEntries`) eviction. Every row write and delete of the engine- * goes through here, so the index never misses or resurrects a row.- */-export const createPersistedRows = <TData>({- commit,- getSlot,- isRemoved,- loadingMore,- resource,- writeQueue,-}: ReplicaPersistedRowsDeps<TData>) => {- // ---- persisted-row index ---------------------------------------------- // Storage has no key listing, so each scope keeps an index row of the- // storage keys this resource persisted. Entity changes use it to patch rows- // whose entry is not loaded in memory (e.g. a status update for a list the- // user navigated away from), so a later visit never hydrates a stale value.- const indexKey = (scope: string) => ({ queryKey: REPLICA_INDEX_KEY, scope });- /** Keys known to be in the index row, per scope (skips redundant index writes). */- const indexed = new Map<string, Set<string>>();- const indexedKeys = (scope: string) => indexed.get(scope);-- /**- * Latest queued write per row (`scope` + storage key), from one monotonic- * counter. A confirmed delete only takes its key out of the index when no- * later write re-created the row in the meantime.- */- const rowWrites = new Map<string, number>();- let writeCounter = 0;- const writeCount = () => writeCounter;- const rowId = (scope: string, queryKey: string) => `${scope}\u0000${queryKey}`;- const noteWrite = (scope: string, queryKey: string) => {- const seq = ++writeCounter;- rowWrites.set(rowId(scope, queryKey), seq);- return seq;- };-- // ---- last persisted value per row ---------------------------------------- // What this session knows a row holds in storage: the value of its latest- // write once that write is confirmed (`ReplicaStorage.set` resolved), or the- // value read back by a hydrate no write raced. A write still in flight, or one- // that failed, leaves the row unknown. A persist of a- // deep-equal value is skipped β an unchanged revalidation must not rewrite- // the same row. Every path that may change a row behind it (a delete, a- // patch, a clear, an eviction) forgets the row, so the next persist writes.- const storedValues = new Map<string, Map<string, unknown>>();- const rememberStored = (scope: string, queryKey: string, data: unknown) => {- const rows = storedValues.get(scope) ?? new Map<string, unknown>();- storedValues.set(scope, rows);- rows.set(queryKey, data);- };- const forgetStored = (scope: string, queryKeys: Iterable<string>) => {- const rows = storedValues.get(scope);- if (!rows) return;- for (const queryKey of queryKeys) rows.delete(queryKey);- if (rows.size === 0) storedValues.delete(scope);- };- /** Forget every row of `scope` (memory moved to another identity, or a clear). */- const forgetScope = (scope: string) => {- storedValues.delete(scope);- };- const isStored = (scope: string, queryKey: string, data: unknown) => {- const rows = storedValues.get(scope);- return !!rows?.has(queryKey) && isEqual(rows.get(queryKey), data);- };- /**- * A hydrate read `data` back from the row: the row holds it, unless a write- * was queued while reading (`writesBefore` is `writeCount()` before the read).- */- const rememberRead = (scope: string, queryKey: string, data: unknown, writesBefore: number) => {- if (writeCounter === writesBefore && !storedValues.get(scope)?.has(queryKey))- rememberStored(scope, queryKey, data);- };-- // ---- bounded persisted entries ----------------------------------------- // With `persist.maxEntries`, the index is kept in least-recently-used order- // (oldest first β the order an unbounded index is appended in, so rows an- // earlier release indexed keep their place) and every use of a row moves it- // to the end. Past the cap the oldest rows that nothing pins are evicted.- const maxEntries = resource.maxPersistedEntries;- /** Mounted readers per storage key and per entry key (see `retain`). */- const retainedRows = new Map<string, number>();- const retainedKeys = new Map<string, number>();- /** Rows whose eviction delete is queued, per scope. */- const evicting = new Map<string, Set<string>>();-- const bump = (counts: Map<string, number>, id: string, by: number) => {- const next = (counts.get(id) ?? 0) + by;- if (next > 0) counts.set(id, next);- else counts.delete(id);- };-- /**- * Pin an entry (and the row of the query it asks for) while something shows- * it: eviction never drops a retained row or the memory entry of a retained- * key. `useSync` retains for as long as it is mounted. Returns the release.- */- const retain = (key: string, queryKey: string = replicaStorageKey(key)) => {- bump(retainedKeys, key, 1);- bump(retainedRows, queryKey, 1);- let released = false;- return () => {- if (released) return;- released = true;- bump(retainedKeys, key, -1);- bump(retainedRows, queryKey, -1);- };- };-- /** Rows the memory of `scope` holds, by storage key β entry key. */- const loadedRows = (scope: string) => {- const slot = getSlot();- const rows = new Map<string, string>();- if (slot.scope !== scope) return rows;- for (const [key, entry] of Object.entries(slot.entries))- rows.set(replicaStorageKey(key, entry.query), key);- return rows;- };-- /** A row on screen, or whose entry has writes / a page load in flight. */- const isPinned = (queryKey: string, entryKey: string | undefined) =>- retainedRows.has(queryKey) ||- (entryKey !== undefined &&- (retainedKeys.has(entryKey) ||- (getSlot().entries[entryKey]?.pending.length ?? 0) > 0 ||- loadingMore.has(entryKey)));-- /** The oldest unpinned rows past the cap (`keys` is oldest first). */- const pickEvictions = (scope: string, keys: string[], touched: string): string[] => {- const going = evicting.get(scope);- let excess = keys.length - maxEntries! - keys.filter((key) => going?.has(key)).length;- if (excess <= 0) return [];- const loaded = loadedRows(scope);- const picked: string[] = [];- for (const queryKey of keys) {- if (excess <= 0) break;- if (queryKey === touched || going?.has(queryKey)) continue;- if (isPinned(queryKey, loaded.get(queryKey))) continue;- picked.push(queryKey);- excess -= 1;- }- return picked;- };-- /**- * Evict rows: drop the memory entries that answer them (one commit), then- * delete the rows. A row leaves the index only once its delete landed, so a- * failed eviction is picked again by a later use.- */- const evictRows = (scope: string, queryKeys: string[]) => {- if (resource.scope.get() !== scope || !resource.scope.canPersist()) return;- const going = evicting.get(scope) ?? new Set<string>();- evicting.set(scope, going);- const loaded = loadedRows(scope);- // Re-check: a row may have been pinned since it was picked.- const rows = queryKeys.filter(- (queryKey) => !going.has(queryKey) && !isPinned(queryKey, loaded.get(queryKey)),- );- if (rows.length === 0) return;- for (const queryKey of rows) going.add(queryKey);- const dropped = rows.flatMap((queryKey) => {- const key = loaded.get(queryKey);- return key === undefined ? [] : [key];- });- if (dropped.length > 0) {- const slot = getSlot();- const entries = { ...slot.entries };- for (const key of dropped) delete entries[key];- commit(dropped, { entries, scope });- }- void deleteRows(scope, rows).finally(() => {- for (const queryKey of rows) going.delete(queryKey);- if (going.size === 0 && evicting.get(scope) === going) evicting.delete(scope);- });- };-- /**- * A bounded resource used a row: move it to the end of the index and evict- * past the cap. No-op for an unbounded resource.- */- const touchStorageKey = (scope: string, queryKey: string) => {- if (!writeQueue || maxEntries === undefined) return;- const known = indexed.get(scope) ?? new Set<string>();- indexed.set(scope, known);- known.add(queryKey);- let picked: string[] = [];- void writeQueue- .update(- indexKey(scope),- (current) => {- const keys = (current?.data as unknown as string[] | undefined) ?? [];- const next = [...keys.filter((key) => key !== queryKey), queryKey];- picked = pickEvictions(scope, next, queryKey);- if (keys.length === next.length && keys.at(-1) === queryKey) return undefined;- return { data: next as unknown as TData, updatedAt: Date.now() };- },- { read: 'prefer-strict' },- )- .then((touched) => {- // Unreadable index: leave it untouched, retry the append on the next use.- if (!touched) return void known.delete(queryKey);- if (picked.length > 0) evictRows(scope, picked);- });- };-- /** Record a persisted row in the index (queued after the row write). */- const trackStorageKey = (scope: string, queryKey: string) => {- if (!writeQueue) return;- noteWrite(scope, queryKey);- if (maxEntries !== undefined) return touchStorageKey(scope, queryKey);- const known = indexed.get(scope) ?? new Set<string>();- indexed.set(scope, known);- if (known.has(queryKey)) return;- known.add(queryKey);- void writeQueue- .update(- indexKey(scope),- (current) => {- const keys = new Set((current?.data as unknown as string[] | undefined) ?? []);- if (keys.has(queryKey)) return undefined;- keys.add(queryKey);- return { data: [...keys] as unknown as TData, updatedAt: Date.now() };- },- { read: 'prefer-strict' },- )- // An unreadable index is left untouched (never rewritten as just this- // key); forget the key so the next write of the row retries the append.- .then((tracked) => {- if (!tracked) known.delete(queryKey);- });- };-- /**- * Read the index for a destructive pass (remove / clear / entity patch).- * Uses the storage's strict read when it has one, so an unreadable index- * rejects instead of looking empty β a purge must never report success for- * rows it could not enumerate.- */- const readIndex = async (scope: string): Promise<string[]> => {- // A storage without `getStrict` rejects here: its `get` cannot tell an- // unreadable index from an empty one.- const row = await readReplicaRowStrict(resource.storage!, indexKey(scope));- return (row?.data as unknown as string[] | undefined) ?? [];- };-- /**- * Drop storage keys from the index (both the session's view of it and the- * persisted row, which may list keys this session never wrote).- */- const untrackStorageKeys = (scope: string, queryKeys: string[]) => {- if (!writeQueue || queryKeys.length === 0) return;- const known = indexed.get(scope);- for (const queryKey of queryKeys) known?.delete(queryKey);- const dropped = new Set(queryKeys);- writeQueue.update(- indexKey(scope),- (current) => {- const keys = (current?.data as unknown as string[] | undefined) ?? [];- const next = keys.filter((queryKey) => !dropped.has(queryKey));- if (!current || next.length === keys.length) return undefined;- return { data: next as unknown as TData, updatedAt: Date.now() };- },- { read: 'prefer-strict' },- );- };-- /** Take rows whose delete landed out of the index, unless rewritten since. */- const confirmDeleted = (scope: string, deleted: [queryKey: string, seq: number][]) => {- const gone = deleted- .filter(([queryKey, seq]) => rowWrites.get(rowId(scope, queryKey)) === seq)- .map(([queryKey]) => queryKey);- for (const queryKey of gone) rowWrites.delete(rowId(scope, queryKey));- untrackStorageKeys(scope, gone);- };-- /**- * Queue row deletes now (ordered before any later write to the same rows).- * A key leaves the index only once its delete is confirmed: a failed delete- * stays indexed, so the next `remove` / `clear` finds and retries it.- * Resolves `true` when every delete landed.- */- const deleteRows = (scope: string, queryKeys: string[]): Promise<boolean> => {- const queue = writeQueue!;- forgetStored(scope, queryKeys);- const queued = queryKeys.map((queryKey) => {- const seq = noteWrite(scope, queryKey);- return queue- .remove({ queryKey, scope })- .then((removed): [string, number] | undefined => (removed ? [queryKey, seq] : undefined));- });- return Promise.all(queued).then((results) => {- confirmDeleted(- scope,- results.filter((result): result is [string, number] => !!result),- );- return results.every(Boolean);- });- };-- /**- * Delete every persisted row of entry `key` in `scope` β `current` (the row- * memory knows about, queued right away so it orders before any later write)- * plus every other query variant the index lists. Resolves `true` once all- * deletes landed.- */- const removeStoredVariants = (scope: string, key: string, current: string) => {- const first = deleteRows(scope, [current]);- const rest = readIndex(scope).then(- (persisted) => {- // A server value that superseded the removal while the index was read- // owns its (fresh) row: keep it, delete only the stale variants.- const slot = getSlot();- const live = !isRemoved(scope, key) && slot.scope === scope ? slot.entries[key] : undefined;- const liveKey = live && replicaStorageKey(key, live.query);- const variants = new Set(- [...(indexed.get(scope) ?? []), ...persisted].filter(- (queryKey) =>- queryKey !== current && queryKey !== liveKey && isReplicaStorageKeyOf(queryKey, key),- ),- );- return variants.size === 0 ? true : deleteRows(scope, [...variants]);- },- () => false,- );- return Promise.all([first, rest]).then((results) => results.every(Boolean));- };-- /** Persist `data` to one row (the write path of a `persist` effect). */- const writeRow = (scope: string, queryKey: string, data: TData) => {- const queue = writeQueue!;- // The row already holds this value: an unchanged revalidation is no write.- if (isStored(scope, queryKey, data)) {- touchStorageKey(scope, queryKey);- return;- }- // Until this write is confirmed the row's content is unknown: forget what- // it held, and only remember `data` once the write observably landed and- // is still the latest queued for the row. A failed (or best-effort,- // silently dropped) write therefore never makes a later identical persist- // look redundant β that one writes again.- forgetStored(scope, [queryKey]);- trackStorageKey(scope, queryKey);- const id = rowId(scope, queryKey);- const seq = rowWrites.get(id);- void queue.set({ queryKey, scope }, { data, updatedAt: Date.now() }).then((written) => {- if (written && rowWrites.get(id) === seq) rememberStored(scope, queryKey, data);- });- };-- /**- * Read-modify-write one row in the per-key write queue, so it sees every- * earlier write; a missing row is never recreated. `transform` returns the- * next data, `undefined` to leave the row, or `DROP_ROW` to drop it (the row- * leaves the index once its delete landed). Resolves whether it settled.- */- const patchRow = (- scope: string,- queryKey: string,- transform: (data: TData) => TData | typeof DROP_ROW | undefined,- ): Promise<boolean> => {- const seq = noteWrite(scope, queryKey);- forgetStored(scope, [queryKey]);- let dropped = false;- return writeQueue!- .update(- { queryKey, scope },- (current) => {- if (!current) return undefined;- const next = transform(current.data);- if (next === undefined) return undefined;- if (next === DROP_ROW) {- dropped = true;- return null;- }- return { data: next, updatedAt: Date.now() };- },- { read: 'strict' },- )- .then((written) => {- if (written && dropped) confirmDeleted(scope, [[queryKey, seq]]);- return written;- });- };-- /**- * Read-modify-write the persisted rows memory does not hold, keyed by row- * rather than by entity: a cached list for a folder the user is not viewing- * gets its projection patched in the per-key write queue, so a later visit- * hydrates the reconciled value instead of a stale page. `fn` returns the- * next data, the same reference (or `undefined`) to skip, or `null` to drop- * the row. Runs in the write queue, so it sees every earlier write.- */- const patchStoredRows = async (fn: (data: TData) => TData | null | undefined): Promise<void> => {- if (!writeQueue || !resource.scope.canPersist()) return;- const scope = resource.scope.get();- const slot = getSlot();- const loaded = new Set(- slot.scope === scope- ? Object.entries(slot.entries).map(([key, entry]) => replicaStorageKey(key, entry.query))- : [],- );- let keys: string[];- try {- keys = await readIndex(scope);- } catch (error) {- console.error(`[replica:${resource.name}] failed to read the persisted index`, error);- return;- }- // Identity changed while reading the index: those rows are not ours to touch.- if (resource.scope.get() !== scope) return;- const patches: Promise<boolean>[] = [];- for (const queryKey of keys) {- if (loaded.has(queryKey)) continue;- patches.push(- patchRow(scope, queryKey, (data) => {- const next = fn(data);- if (next === data) return undefined;- return next === null ? DROP_ROW : next;- }),- );- }- await Promise.all(patches);- };-- return {- deleteRows,- forgetScope,- forgetStored,- indexedKeys,- patchRow,- patchStoredRows,- readIndex,- rememberRead,- removeStoredVariants,- retain,- touchStorageKey,- writeCount,- writeRow,- };-};--export type ReplicaPersistedRows<TData> = ReturnType<typeof createPersistedRows<TData>>;diff --git a/packages/replica/src/core/reducer.test.ts b/packages/replica/src/core/reducer.test.tsdeleted file mode 100644index 3e7a0da9b3b..00000000000--- a/packages/replica/src/core/reducer.test.ts+++ /dev/null@@ -1,548 +0,0 @@-import { describe, expect, it } from 'vitest';--import type { ReplicaAction, ReplicaViewWrite } from './reducer';-import { createReplicaState, replicaReducer } from './reducer';-import type { ReplicaState } from './types';--type List = string[];--/** Tiny harness: applies view writes to a plain record, like a store lens would. */-const createHarness = (initialView: Record<string, List> = {}) => {- let state: ReplicaState<List> = createReplicaState();- let view: Record<string, List> = { ...initialView };- const effects: unknown[] = [];-- const run = (action: ReplicaAction<List>) => {- const transition = replicaReducer(state, action, (key) => view[key], 1);- state = transition.state;- for (const write of transition.writes as ReplicaViewWrite<List>[]) {- if ('type' in write) view = {};- else if (write.data === undefined) delete view[write.key];- else view[write.key] = write.data;- }- effects.push(...transition.effects);- return transition;- };-- return {- effects,- run,- get state() {- return state;- },- get view() {- return view;- },- };-};--const S = 'user-1:personal';-const append = (item: string) => (list: List) => [...list, item];-/** A seed write merges into its input, as a replayed seed must (see `seedPatches`). */-const seedWith = (item: string) => (list: List | undefined) => [...(list ?? []), item];--describe('replicaReducer', () => {- describe('hydrate vs replace ordering', () => {- it('hydrates an empty slot without persisting', () => {- const h = createHarness();- h.run({ data: ['cached'], key: 'k', scope: S, type: 'hydrate' });-- expect(h.view.k).toEqual(['cached']);- expect(h.state.entries.k.source).toBe('storage');- expect(h.effects).toEqual([]);- });-- it('never lets a late hydrate overwrite a server projection', () => {- const h = createHarness();- h.run({ data: () => ['server'], key: 'k', scope: S, type: 'replace' });- h.run({ data: ['stale-cache'], key: 'k', scope: S, type: 'hydrate' });-- expect(h.view.k).toEqual(['server']);- expect(h.state.entries.k.source).toBe('server');- });-- it('does not hydrate over data already in memory (written outside the binding)', () => {- const h = createHarness({ k: ['memory'] });- h.run({ data: ['cached'], key: 'k', scope: S, type: 'hydrate' });-- expect(h.view.k).toEqual(['memory']);- });-- it('repaints a slot answering another query when the caller asks to overwrite', () => {- const h = createHarness();- h.run({ data: ['query-1'], key: 'k', params: 1, query: 'q1', scope: S, type: 'hydrate' });-- h.run({- data: ['query-2'],- key: 'k',- overwrite: true,- params: 2,- query: 'q2',- scope: S,- type: 'hydrate',- });-- expect(h.view.k).toEqual(['query-2']);- expect(h.state.entries.k.query).toBe('q2');- expect(h.state.entries.k.source).toBe('storage');- expect(h.effects).toEqual([]);- });-- it('keeps the slot when the overwriting hydrate asks for the query it already answers', () => {- const h = createHarness();- h.run({- data: () => ['server'],- key: 'k',- params: 1,- query: 'q1',- scope: S,- type: 'replace',- });-- const transition = h.run({- data: ['stale-cache'],- key: 'k',- overwrite: true,- params: 1,- query: 'q1',- scope: S,- type: 'hydrate',- });-- expect(h.view.k).toEqual(['server']);- expect(transition.writes).toEqual([]);- });-- it('never clobbers an in-flight optimistic write, even with overwrite', () => {- const h = createHarness();- h.run({ data: ['a'], key: 'k', params: 1, query: 'q1', scope: S, type: 'hydrate' });- h.run({ apply: append('opt'), id: 1, key: 'k', scope: S, type: 'optimistic' });-- h.run({- data: ['b'],- key: 'k',- overwrite: true,- params: 2,- query: 'q2',- scope: S,- type: 'hydrate',- });-- expect(h.view.k).toEqual(['a', 'opt']);- expect(h.state.entries.k.query).toBe('q1');- });-- it('replace overwrites hydrated data and persists it', () => {- const h = createHarness();- h.run({ data: ['cached'], key: 'k', scope: S, type: 'hydrate' });- h.run({ data: () => ['server'], key: 'k', scope: S, type: 'replace' });-- expect(h.view.k).toEqual(['server']);- expect(h.effects).toEqual([{ data: ['server'], key: 'k', scope: S, type: 'persist' }]);- });-- it('replace merges against the confirmed value and treats undefined as no-op', () => {- const h = createHarness({ k: ['a'] });- const before = h.view.k;- h.run({ data: (confirmed) => confirmed, key: 'k', scope: S, type: 'replace' });- expect(h.view.k).toBe(before);-- h.run({ data: () => undefined, key: 'k', scope: S, type: 'replace' });- expect(h.view.k).toBe(before);- expect(h.state.entries.k.source).toBe('server');- });-- it('hydrates over a provisional seed (a list row standing in for a detail)', () => {- const h = createHarness();- // The seed makes the object resolvable before its own detail is known.- h.run({- apply: seedWith('seed'),- key: 'k',- persist: false,- scope: S,- source: 'seed',- type: 'update',- });- expect(h.view.k).toEqual(['seed']);- expect(h.state.entries.k.source).toBe('seed');-- // The persisted detail hydrates instead of being blocked, and the seed's- // own (fresher) fields are merged back over it.- h.run({ data: ['persisted'], key: 'k', scope: S, type: 'hydrate' });- expect(h.view.k).toEqual(['persisted', 'seed']);- expect(h.state.entries.k.source).toBe('storage');- expect(h.effects).toEqual([]);- });-- it('keeps a confirmed local write authoritative over a late hydrate', () => {- const h = createHarness();- h.run({ apply: () => ['local'], key: 'k', persist: true, scope: S, type: 'update' });- expect(h.state.entries.k.source).toBe('local');-- h.run({ data: ['persisted'], key: 'k', scope: S, type: 'hydrate' });- expect(h.view.k).toEqual(['local']);- });-- // A confirmed write made over a seed (e.g. a rename while the detail is still- // reading storage) must survive the late hydrate that replaces the seed:- // it is replayed onto the hydrated value, which then persists.- it('replays a confirmed write made over a seed onto the late hydrate', () => {- const h = createHarness();- h.run({- apply: seedWith('seed'),- key: 'k',- persist: false,- scope: S,- source: 'seed',- type: 'update',- });- h.run({ apply: append('confirmed'), key: 'k', persist: true, scope: S, type: 'update' });- // Still provisional: persisting the seed would clobber the stored detail.- expect(h.effects).toEqual([]);-- h.run({ data: ['persisted'], key: 'k', scope: S, type: 'hydrate' });- expect(h.view.k).toEqual(['persisted', 'seed', 'confirmed']);- expect(h.state.entries.k.source).toBe('local');- expect(h.effects).toEqual([- { data: ['persisted', 'seed', 'confirmed'], key: 'k', scope: S, type: 'persist' },- ]);-- // Now authoritative: another late hydrate cannot clobber it either.- h.run({ data: ['stale'], key: 'k', scope: S, type: 'hydrate' });- expect(h.view.k).toEqual(['persisted', 'seed', 'confirmed']);- });-- it('replays the latest seed and later writes, but persists neither seeds nor in-memory writes', () => {- const h = createHarness();- h.run({- apply: seedWith('seed'),- key: 'k',- persist: false,- scope: S,- source: 'seed',- type: 'update',- });- h.run({- apply: append('reseeded'),- key: 'k',- persist: false,- scope: S,- source: 'seed',- type: 'update',- });- h.run({ apply: append('memory'), key: 'k', persist: false, scope: S, type: 'update' });-- h.run({ data: ['persisted'], key: 'k', scope: S, type: 'hydrate' });- // The re-seed supersedes the first seed (same source); the in-memory- // write still replays after it.- expect(h.view.k).toEqual(['persisted', 'reseeded', 'memory']);- expect(h.effects).toEqual([]);- });-- // Repeated refreshes of one source must not grow the remembered history:- // a later seed of the same tag supersedes the earlier one since the last- // confirmed write, while other tags and confirmed writes keep their order.- it('coalesces repeated seeds of one tag, keeping their order around confirmed writes', () => {- const h = createHarness();- const seed = (item: string, seedTag: string) =>- h.run({- apply: seedWith(item),- key: 'k',- persist: false,- scope: S,- seedTag,- source: 'seed',- type: 'update',- });- for (let i = 0; i < 50; i++) seed(`list-${i}`, 'list');- seed('session', 'session');- seed('list-last', 'list');- h.run({ apply: append('confirmed'), key: 'k', persist: true, scope: S, type: 'update' });- seed('list-after', 'list');-- expect(h.state.entries.k.seedPatches).toHaveLength(4);- h.run({ data: ['persisted'], key: 'k', scope: S, type: 'hydrate' });- expect(h.view.k).toEqual(['persisted', 'session', 'list-last', 'confirmed', 'list-after']);- });-- it('does not hydrate over a seed that carries an in-flight overlay', () => {- const h = createHarness();- h.run({- apply: seedWith('seed'),- key: 'k',- persist: false,- scope: S,- source: 'seed',- type: 'update',- });- h.run({ apply: append('opt'), id: 1, key: 'k', scope: S, type: 'optimistic' });-- h.run({ data: ['persisted'], key: 'k', scope: S, type: 'hydrate' });- expect(h.view.k).toEqual(['seed', 'opt']);- });- });-- describe('scope isolation', () => {- it('ignores actions captured under another scope', () => {- const h = createHarness();- h.run({ data: () => ['mine'], key: 'k', scope: S, type: 'replace' });- h.run({ data: () => ['other-user'], key: 'k', scope: 'user-2:personal', type: 'replace' });- h.run({ data: ['other'], key: 'j', scope: 'user-2:personal', type: 'hydrate' });-- expect(h.view).toEqual({ k: ['mine'] });- });-- it('resetScope clears memory of the previous scope', () => {- const h = createHarness();- h.run({ data: () => ['mine'], key: 'k', scope: S, type: 'replace' });- h.run({ scope: 'user-2:personal', type: 'resetScope' });-- expect(h.view).toEqual({});- expect(h.state).toEqual({ entries: {}, scope: 'user-2:personal' });-- h.run({ data: ['theirs'], key: 'k', scope: 'user-2:personal', type: 'hydrate' });- expect(h.view.k).toEqual(['theirs']);- });-- it('adopting the first scope does not clear data already in memory', () => {- const h = createHarness({ k: ['memory'] });- h.run({ scope: S, type: 'resetScope' });- expect(h.view.k).toEqual(['memory']);- });- });-- describe('optimistic overlay', () => {- it('commit keeps the view and persists the confirmed value', () => {- const h = createHarness({ k: ['a'] });- h.run({ apply: append('b'), id: 1, key: 'k', scope: S, type: 'optimistic' });- expect(h.view.k).toEqual(['a', 'b']);- expect(h.effects).toEqual([]);-- h.run({ id: 1, key: 'k', scope: S, type: 'commit' });- expect(h.view.k).toEqual(['a', 'b']);- expect(h.state.entries.k.pending).toEqual([]);- expect(h.state.entries.k.base).toBeUndefined();- expect(h.effects).toEqual([{ data: ['a', 'b'], key: 'k', scope: S, type: 'persist' }]);- });-- it('rollback restores the confirmed value without persisting', () => {- const h = createHarness({ k: ['a'] });- h.run({ apply: append('b'), id: 1, key: 'k', scope: S, type: 'optimistic' });- h.run({ id: 1, key: 'k', scope: S, type: 'rollback' });-- expect(h.view.k).toEqual(['a']);- expect(h.effects).toEqual([]);- });-- it('rolling back one mutation keeps the other in-flight overlays', () => {- const h = createHarness({ k: ['a'] });- h.run({ apply: append('b'), id: 1, key: 'k', scope: S, type: 'optimistic' });- h.run({ apply: append('c'), id: 2, key: 'k', scope: S, type: 'optimistic' });- h.run({ id: 1, key: 'k', scope: S, type: 'rollback' });-- expect(h.view.k).toEqual(['a', 'c']);- h.run({ id: 2, key: 'k', scope: S, type: 'commit' });- expect(h.view.k).toEqual(['a', 'c']);- expect(h.effects.at(-1)).toEqual({ data: ['a', 'c'], key: 'k', scope: S, type: 'persist' });- });-- it('a background replace rebases pending overlays instead of hiding them', () => {- const h = createHarness({ k: ['a'] });- h.run({ apply: append('b'), id: 1, key: 'k', scope: S, type: 'optimistic' });- h.run({ data: () => ['a', 'z'], key: 'k', scope: S, type: 'replace' });-- expect(h.view.k).toEqual(['a', 'z', 'b']);- // Only the server value is persisted, never the optimistic overlay.- expect(h.effects.at(-1)).toEqual({ data: ['a', 'z'], key: 'k', scope: S, type: 'persist' });-- h.run({ id: 1, key: 'k', scope: S, type: 'rollback' });- expect(h.view.k).toEqual(['a', 'z']);- });-- it('commit can confirm with the server result', () => {- const h = createHarness({ k: ['a'] });- h.run({ apply: append('tmp'), id: 1, key: 'k', scope: S, type: 'optimistic' });- h.run({ confirm: append('real'), id: 1, key: 'k', scope: S, type: 'commit' });-- expect(h.view.k).toEqual(['a', 'real']);- });-- it('an optimistic write on an unloaded key is a no-op', () => {- const h = createHarness();- h.run({ apply: append('b'), id: 1, key: 'k', scope: S, type: 'optimistic' });- h.run({ id: 1, key: 'k', scope: S, type: 'commit' });-- expect(h.view).toEqual({});- expect(h.effects).toEqual([]);- });-- it('drops a commit that lands after a scope switch', () => {- const h = createHarness({ k: ['a'] });- h.run({ apply: append('b'), id: 1, key: 'k', scope: S, type: 'optimistic' });- h.run({ scope: 'user-2:personal', type: 'resetScope' });- h.run({ id: 1, key: 'k', scope: S, type: 'commit' });-- expect(h.view).toEqual({});- expect(h.effects).toEqual([]);- });- });-- describe('confirmed local updates', () => {- it('patches view and base under an overlay, persisting the confirmed value', () => {- const h = createHarness({ k: ['a'] });- h.run({ apply: append('opt'), id: 1, key: 'k', scope: S, type: 'optimistic' });- h.run({- apply: (list) => list && [...list, 'confirmed'],- key: 'k',- persist: true,- scope: S,- type: 'update',- });-- expect(h.view.k).toEqual(['a', 'opt', 'confirmed']);- expect(h.effects).toEqual([- { data: ['a', 'confirmed'], key: 'k', scope: S, type: 'persist' },- ]);-- h.run({ id: 1, key: 'k', scope: S, type: 'rollback' });- expect(h.view.k).toEqual(['a', 'confirmed']);- });-- it('persist: false only touches memory', () => {- const h = createHarness({ k: ['a'] });- h.run({ apply: () => ['b'], key: 'k', persist: false, scope: S, type: 'update' });-- expect(h.view.k).toEqual(['b']);- expect(h.effects).toEqual([]);- });-- it('a seed never persists, even when its write asks to', () => {- const h = createHarness();- h.run({- apply: () => ['seed'],- key: 'k',- persist: true,- scope: S,- source: 'seed',- type: 'update',- });- // A later write on top of the seed keeps it provisional.- h.run({ apply: append('patched'), key: 'k', persist: true, scope: S, type: 'update' });-- expect(h.view.k).toEqual(['seed', 'patched']);- expect(h.state.entries.k.source).toBe('seed');- expect(h.effects).toEqual([]);- });-- it('remove drops the entry and its persisted row', () => {- const h = createHarness({ k: ['a'] });- h.run({ key: 'k', scope: S, type: 'remove' });-- expect(h.view).toEqual({});- expect(h.effects).toEqual([{ key: 'k', scope: S, type: 'remove' }]);- });- });-- describe('optimistic overlay query affinity', () => {- it('does not carry an overlay into another query, and its commit stays out', () => {- const h = createHarness();- h.run({ data: ['a'], key: 'k', params: 1, query: 'q1', scope: S, type: 'hydrate' });- h.run({- apply: append('pending-a'),- id: 1,- key: 'k',- query: 'q1',- scope: S,- type: 'optimistic',- });- expect(h.view.k).toEqual(['a', 'pending-a']);-- // The key is reused for another query while the overlay is in flight.- h.run({- data: (basis) => [...(basis ?? []), 'b'],- key: 'k',- params: 2,- query: 'q2',- scope: S,- type: 'replace',- });-- // The overlay described q1, so it must not surface under q2 ...- expect(h.view.k).toEqual(['a', 'b']);- expect(h.state.entries.k.pending).toEqual([]);-- // ... and settling it later must not insert q1's row into q2.- h.run({ confirm: append('created-a'), id: 1, key: 'k', scope: S, type: 'commit' });- expect(h.view.k).toEqual(['a', 'b']);- });-- it('still rebases a same-query overlay onto the fresh server value', () => {- const h = createHarness();- h.run({ data: ['a'], key: 'k', params: 1, query: 'q1', scope: S, type: 'hydrate' });- h.run({- apply: append('pending'),- id: 1,- key: 'k',- query: 'q1',- scope: S,- type: 'optimistic',- });-- h.run({- data: (basis) => [...(basis ?? []), 'server'],- key: 'k',- params: 1,- query: 'q1',- scope: S,- type: 'replace',- });-- expect(h.view.k).toEqual(['a', 'server', 'pending']);- expect(h.state.entries.k.pending).toHaveLength(1);- });-- it('keeps an untagged overlay: its query cannot be proven different', () => {- const h = createHarness({ k: ['a'] });- h.run({ apply: append('untagged'), id: 1, key: 'k', scope: S, type: 'optimistic' });-- h.run({- data: (basis) => [...(basis ?? []), 'b'],- key: 'k',- params: 2,- query: 'q2',- scope: S,- type: 'replace',- });-- // Rebased onto the fresh value, exactly as before query affinity existed.- expect(h.view.k).toEqual(['a', 'b', 'untagged']);- expect(h.state.entries.k.pending).toHaveLength(1);- });-- it('lets a navigation hydrate repaint over the query being left', () => {- const h = createHarness();- h.run({ data: ['a'], key: 'k', params: 1, query: 'q1', scope: S, type: 'hydrate' });- h.run({- apply: append('pending-a'),- id: 1,- key: 'k',- query: 'q1',- scope: S,- type: 'optimistic',- });-- h.run({- data: ['b-cached'],- key: 'k',- overwrite: true,- params: 2,- query: 'q2',- scope: S,- type: 'hydrate',- });-- expect(h.view.k).toEqual(['b-cached']);- expect(h.state.entries.k.pending).toEqual([]);- });- });-});diff --git a/packages/replica/src/core/reducer.ts b/packages/replica/src/core/reducer.tsdeleted file mode 100644index 16c1e7f6497..00000000000--- a/packages/replica/src/core/reducer.ts+++ /dev/null@@ -1,334 +0,0 @@-import type {- ReplicaEntryMeta,- ReplicaPendingMutation,- ReplicaSeedPatch,- ReplicaSource,- ReplicaState,-} from './types';--/**- * Pure transition core of a replica. It never touches the store- * or storage: it returns the next bookkeeping slot, the view writes the store- * binding must apply, and the persistence effects it must run.- *- * The VIEW (what selectors read) lives in the domain store, wherever the- * binding's lens puts it. The reducer only reads it through `readView`, so a- * domain can keep its existing state shape (e.g. `topicDataMap`).- */-export type ReplicaAction<T> =- | {- data: T;- key: string;- /**- * Repaint a slot that answers a *different* query from the persisted page- * (a navigation). Only the caller that knows the entry has moved on- * (the requested query changed) may ask for it; by default a hydrate only- * fills an empty slot.- */- overwrite?: boolean;- params?: unknown;- query?: string;- scope: string;- type: 'hydrate';- updatedAt?: number;- }- | {- /** Receives the confirmed value (base or view); `undefined` keeps it. */- data: (confirmed: T | undefined) => T | undefined;- key: string;- params?: unknown;- query?: string;- scope: string;- type: 'replace';- }- | {- apply: (data: T | undefined) => T | undefined;- key: string;- persist: boolean;- scope: string;- /** Marks a provisional write (`'seed'`); defaults to the entry's own source. */- source?: ReplicaSource;- /**- * Seed writes of one source (a list refresh, a session refresh). A later- * seed write supersedes an earlier one of the same tag since the last- * confirmed write, so a remembered seed history stays bounded.- */- seedTag?: string;- type: 'update';- }- | {- apply: (data: T) => T;- id: number;- key: string;- /** Query the overlay is started under (see `ReplicaPendingMutation`). */- query?: string;- scope: string;- type: 'optimistic';- }- | { confirm?: (data: T) => T; id: number; key: string; scope: string; type: 'commit' }- | { id: number; key: string; scope: string; type: 'rollback' }- | { key: string; scope: string; type: 'remove' }- | { scope: string; type: 'resetScope' };--export type ReplicaEffect<T> =- | { data: T; key: string; query?: string; scope: string; type: 'persist' }- | { key: string; query?: string; scope: string; type: 'remove' };--export type ReplicaViewWrite<T> = { data: T | undefined; key: string } | { type: 'clear' };--export interface ReplicaTransition<T> {- effects: ReplicaEffect<T>[];- state: ReplicaState<T>;- writes: ReplicaViewWrite<T>[];-}--export const createReplicaState = <T>(): ReplicaState<T> => ({ entries: {} });--const materialize = <T>(- base: T | undefined,- pending: ReplicaPendingMutation<T>[],-): T | undefined =>- base === undefined- ? undefined- : pending.reduce<T>((data, mutation) => mutation.apply(data), base);--const noop = <T>(state: ReplicaState<T>): ReplicaTransition<T> => ({- effects: [],- state,- writes: [],-});--/**- * Drop the seed patches a new seed write of `tag` supersedes: those of the same- * tag after the last confirmed patch. Repeated refreshes of one source then keep- * one patch instead of one per refresh, while the order relative to confirmed- * writes (and to other sources' seeds) is preserved.- */-const coalesceSeedPatches = <T>(- patches: ReplicaSeedPatch<T>[],- isSeedWrite: boolean,- tag: string | undefined,-): ReplicaSeedPatch<T>[] => {- if (!isSeedWrite) return patches;- let lastConfirmed = -1;- patches.forEach((patch, index) => {- if (!patch.seed) lastConfirmed = index;- });- return patches.filter(- (patch, index) => index <= lastConfirmed || !patch.seed || patch.tag !== tag,- );-};--export const replicaReducer = <T>(- state: ReplicaState<T>,- action: ReplicaAction<T>,- readView: (key: string) => T | undefined,- now: number = Date.now(),-): ReplicaTransition<T> => {- if (action.type === 'resetScope') {- if (state.scope === action.scope) return noop(state);- // A different identity owns memory now: drop every entry (and its view) of- // the previous scope instead of letting it bleed into the new one.- return {- effects: [],- state: { entries: {}, scope: action.scope },- writes: state.scope === undefined ? [] : [{ type: 'clear' }],- };- }-- // Late results from another scope (workspace switch, logout) are ignored.- if (state.scope !== undefined && state.scope !== action.scope) return noop(state);-- const scope = action.scope;- const entry = state.entries[action.key];- const view = readView(action.key);- const confirmed = entry?.pending.length ? entry.base : view;- const withEntry = (next: ReplicaEntryMeta<T> | undefined): ReplicaState<T> => {- const entries = { ...state.entries };- if (next) entries[action.key] = next;- else delete entries[action.key];- return { entries, scope };- };-- switch (action.type) {- case 'hydrate': {- // A removed key never reaches here: the engine's removal tombstones drop a- // storage read that resolves after a removal (see `hydrate` in engine.ts).- // Hydrate only fills an empty slot: a server-confirmed value, an- // optimistic write or any local write always wins over storage. A caller- // that knows the slot answers a *different* query (a navigation) may ask- // to repaint it from that query's persisted page instead β the overlays it- // drops belong to the query being left. An overlay whose query is unknown- // still wins: we cannot prove it is not this query's.- //- // A provisional `seed` is the other exception β it is a list row standing- // in for a detail, not authoritative state, so the persisted value- // replaces it. Otherwise a seeded entry would block the persisted detail- // forever.- const provisionalSeed = !!entry && entry.source === 'seed' && entry.pending.length === 0;- if (entry && !provisionalSeed) {- if (- !action.overwrite ||- entry.query === action.query ||- entry.pending.some((mutation) => mutation.query === undefined)- )- return noop(state);- } else if (!entry && view !== undefined) {- return noop(state);- }- // The writes made over the seed are replayed onto the stored value, so- // storage cannot clobber them: the seed's own (fresher) fields β a list- // row's renamed title β and any confirmed edit made before storage- // answered. Only a confirmed edit makes the result a local value (and- // persists it); seed writes stay in-memory.- const patches = (provisionalSeed && entry.seedPatches) || [];- const data = patches.reduce((value, patch) => patch.apply(value) ?? value, action.data);- const confirmedPatches = patches.filter((patch) => !patch.seed);- return {- effects: confirmedPatches.some((patch) => patch.persist)- ? [{ data, key: action.key, query: action.query, scope, type: 'persist' }]- : [],- state: withEntry({- params: action.params,- pending: [],- query: action.query,- source: confirmedPatches.length ? 'local' : 'storage',- updatedAt: confirmedPatches.length ? now : (action.updatedAt ?? now),- }),- writes: [{ data, key: action.key }],- };- }-- case 'replace': {- // An overlay only describes the query it was started under, so a replace- // for another query drops it instead of reapplying it: its base belongs to- // the old query, and a later commit would insert that query's row here.- const pending = (entry?.pending ?? []).filter(- (mutation) => mutation.query === undefined || mutation.query === action.query,- );- // The merge basis under a query change is the old query's confirmed value- // (never the view, which may still carry a dropped overlay).- const basis = entry && entry.query !== action.query ? (entry.base ?? view) : confirmed;- const next = action.data(basis) ?? basis;- const query = 'query' in action ? action.query : entry?.query;- const nextState = withEntry({- base: pending.length ? next : undefined,- params: action.params ?? entry?.params,- pending,- query,- source: 'server',- updatedAt: now,- });- if (next === undefined) return { effects: [], state: nextState, writes: [] };- // In-flight optimistic mutations are rebased onto the fresh server value- // so a background revalidation never flickers them away.- const nextView = materialize(next, pending);- return {- effects: [{ data: next, key: action.key, query, scope, type: 'persist' }],- state: nextState,- writes: nextView === view ? [] : [{ data: nextView, key: action.key }],- };- }-- case 'update': {- const nextView = action.apply(view);- const pending = entry?.pending ?? [];- const nextBase = pending.length ? action.apply(entry!.base) : nextView;- if (nextView === view && nextBase === confirmed) return noop(state);- // A provisional seed is never authoritative, so it must not persist: it- // only stands in for a value another source owns, and persisting it would- // overwrite that value's persisted row. A `seed` also only ever marks a- // fresh slot β a value already in memory (written outside the binding) is- // authoritative and is never downgraded to a seed.- const source: ReplicaSource =- entry?.source ?? (view === undefined ? (action.source ?? 'local') : 'local');- const persist = action.persist && source !== 'seed';- // Every write while the entry is a seed is remembered so a hydrate that- // replaces the seed replays it (see `hydrate`): a confirmed write keeps- // the seed provisional, and a seed write carries fresher fields.- const isSeedWrite = action.source === 'seed';- const seedPatches =- source === 'seed'- ? [- ...coalesceSeedPatches(entry?.seedPatches ?? [], isSeedWrite, action.seedTag),- {- apply: action.apply,- persist: !isSeedWrite && action.persist,- ...(isSeedWrite && { seed: true, tag: action.seedTag }),- },- ]- : entry?.seedPatches;- return {- effects:- persist && nextBase !== undefined- ? [{ data: nextBase, key: action.key, query: entry?.query, scope, type: 'persist' }]- : [],- state: withEntry({- ...entry,- base: pending.length ? nextBase : undefined,- pending,- seedPatches,- source,- updatedAt: now,- }),- writes: nextView === view ? [] : [{ data: nextView, key: action.key }],- };- }-- case 'optimistic': {- if (view === undefined) return noop(state);- const pending = [- ...(entry?.pending ?? []),- { apply: action.apply, id: action.id, query: action.query },- ];- return {- effects: [],- state: withEntry({- ...entry,- base: confirmed,- pending,- source: entry?.source ?? 'local',- updatedAt: entry?.updatedAt ?? now,- }),- writes: [{ data: action.apply(view), key: action.key }],- };- }-- case 'commit':- case 'rollback': {- const mutation = entry?.pending.find((item) => item.id === action.id);- if (!entry || !mutation) return noop(state);- const pending = entry.pending.filter((item) => item.id !== action.id);- const base =- action.type === 'commit' && entry.base !== undefined- ? (action.confirm ?? mutation.apply)(entry.base)- : entry.base;- // A plain commit confirms what the view already shows; only a rollback or- // a server-provided `confirm` needs the view rebuilt from the base.- const nextView =- action.type === 'commit' && !action.confirm ? view : materialize(base, pending);- return {- effects:- action.type === 'commit' && base !== undefined- ? [{ data: base, key: action.key, query: entry.query, scope, type: 'persist' }]- : [],- state: withEntry({- ...entry,- base: pending.length ? base : undefined,- pending,- source: entry.source,- updatedAt: action.type === 'commit' ? now : entry.updatedAt,- }),- writes: nextView === view ? [] : [{ data: nextView, key: action.key }],- };- }-- case 'remove': {- return {- effects: [{ key: action.key, query: entry?.query, scope, type: 'remove' }],- state: withEntry(undefined),- writes: view === undefined ? [] : [{ data: undefined, key: action.key }],- };- }- }-};diff --git a/packages/replica/src/core/removalGuards.ts b/packages/replica/src/core/removalGuards.tsdeleted file mode 100644index a08e553b493..00000000000--- a/packages/replica/src/core/removalGuards.ts+++ /dev/null@@ -1,134 +0,0 @@-import { createTombstones, DEFAULT_REMOVAL_TOMBSTONE_LIMIT } from './tombstones';--/**- * Removal guard of one engine.- *- * An explicit removal (a deleted / unauthorized aggregate, or a subject whose- * attachment is gone) drops the entry AND its persisted row β but a read of- * that row that started before the removal still holds the old value, and a- * removal leaves no trace in the slots for the `hydrate` guard to see. So a- * scope+key is remembered as removed and refuses hydration until a server- * value supersedes it, otherwise the late read resurrects the exact value the- * removal just dropped.- */-export const createRemovalGuards = () => {- const removedEntries = createTombstones();- /**- * Keys whose persisted row delete was actually queued. `runEffects` refuses to- * write while the scope is untrusted, so a removal made on a cold boot can arm- * the guard without clearing the row. The guard alone must therefore not turn- * a later removal into a no-op, or the stale row would survive and hydrate- * again once the scope becomes trusted.- */- const purgedEntries = createTombstones();- /**- * Bumped on every removal of a scope+key. A network response whose request- * started before the entry was removed (deleted, access revoked, pruned by an- * authoritative parent list) must not `replace` it back: the slice records- * the generation a request starts under and drops a response that crossed a- * removal. Bounded like the tombstones; an evicted key reads 0, which only- * ever drops a response (the next revalidate refetches), never admits one.- */- const removalGenerations = new Map<string, number>();- const removalId = (scope: string, key: string) => `${scope}\u0000${key}`;- const removalGeneration = (scope: string, key: string) =>- removalGenerations.get(removalId(scope, key)) ?? 0;- const markRemoved = (scope: string, key: string) => {- removedEntries.add(scope, key);- const id = removalId(scope, key);- const next = (removalGenerations.get(id) ?? 0) + 1;- // Re-insert so the map's insertion order is least-recently-removed first.- removalGenerations.delete(id);- removalGenerations.set(id, next);- if (removalGenerations.size > DEFAULT_REMOVAL_TOMBSTONE_LIMIT)- removalGenerations.delete(removalGenerations.keys().next().value as string);- };- const clearRemoved = (scope: string, key: string) => {- removedEntries.clear(scope, key);- purgedEntries.clear(scope, key);- };- const isRemoved = (scope: string, key: string) => removedEntries.has(scope, key);- const markPurged = (scope: string, key: string) => purgedEntries.add(scope, key);- const isPurged = (scope: string, key: string) => purgedEntries.has(scope, key);-- return { clearRemoved, isPurged, isRemoved, markPurged, markRemoved, removalGeneration };-};--export type ReplicaRemovalGuards = ReturnType<typeof createRemovalGuards>;--/**- * Entity removal guards of one engine.- *- * A hydrate that read its row before `removeEntity` patched storage still- * holds the entity, so it is stripped from every value that hydrates while- * such a read may be pending. A guard's lifetime follows the hydrates, not a- * count: it is released once its storage patch landed (`releasedAt`) and is- * dropped as soon as no hydrate that started before that point is pending.- * So memory stays bounded by in-flight reads, and no guard a pending read- * still needs is ever evicted. A patch that did not land is never released:- * the unloaded row still holds the entity, so every later hydrate needs the- * guard. A server value holding the entity again (restored) lifts it early.- */-export const createEntityRemovalGuards = () => {- /** Logical clock shared by hydrate starts and guard releases. */- let guardClock = 0;- /** Start ticks of the hydrates in flight, per scope. */- const pendingHydrates = new Map<string, Set<number>>();- /** Removed entity ids per scope; `releasedAt` is unset until the storage patch landed. */- const removedEntities = new Map<string, Map<string, { releasedAt?: number }>>();- const removedIds = (scope: string) => [...(removedEntities.get(scope)?.keys() ?? [])];-- /** Drop the guards no pending hydrate of `scope` can still need. */- const pruneEntityGuards = (scope: string) => {- const guards = removedEntities.get(scope);- if (!guards) return;- let oldestPending = Infinity;- for (const start of pendingHydrates.get(scope) ?? [])- oldestPending = Math.min(oldestPending, start);- for (const [id, guard] of guards)- if (guard.releasedAt !== undefined && guard.releasedAt <= oldestPending) guards.delete(id);- if (guards.size === 0) removedEntities.delete(scope);- };-- /**- * Mark a hydrate of `scope` pending until settled: entity guards outlive every- * read that may hold them. Returns the settle.- */- const startHydrate = (scope: string) => {- const start = ++guardClock;- const pending = pendingHydrates.get(scope) ?? new Set<number>();- pendingHydrates.set(scope, pending);- pending.add(start);- return () => {- pending.delete(start);- if (pending.size === 0) pendingHydrates.delete(scope);- pruneEntityGuards(scope);- };- };-- /** Arm the guard of entity `id` in `scope`. Returns its release (call once the patch landed). */- const guardEntity = (scope: string, id: string) => {- const guard: { releasedAt?: number } = {};- const guards = removedEntities.get(scope) ?? new Map<string, { releasedAt?: number }>();- removedEntities.set(scope, guards);- guards.set(id, guard);- return () => {- // A newer removal of the same id owns the slot now.- if (guards.get(id) !== guard) return;- guard.releasedAt = ++guardClock;- pruneEntityGuards(scope);- };- };-- /** Lift the guards of `ids` early (a server value holds them again). */- const liftEntityGuards = (scope: string, ids: string[]) => {- const guards = removedEntities.get(scope);- if (!guards) return;- for (const id of ids) guards.delete(id);- if (guards.size === 0) removedEntities.delete(scope);- };-- return { guardEntity, liftEntityGuards, removedIds, startHydrate };-};--export type ReplicaEntityRemovalGuards = ReturnType<typeof createEntityRemovalGuards>;diff --git a/packages/replica/src/core/settle.test.ts b/packages/replica/src/core/settle.test.tsdeleted file mode 100644index 79984bda07e..00000000000--- a/packages/replica/src/core/settle.test.ts+++ /dev/null@@ -1,24 +0,0 @@-import { afterEach, describe, expect, it, vi } from 'vitest';--import { settleWithin } from './settle';--afterEach(() => vi.useRealTimers());--describe('settleWithin', () => {- it('resolves as soon as the promise settles, rejection included', async () => {- await expect(settleWithin(Promise.resolve('x'), 1000)).resolves.toBeUndefined();- await expect(settleWithin(Promise.reject(new Error('io')), 1000)).resolves.toBeUndefined();- });-- it('resolves at the deadline when the promise never settles', async () => {- vi.useFakeTimers();- const settled = vi.fn();-- void settleWithin(new Promise(() => {}), 50).then(settled);- await vi.advanceTimersByTimeAsync(49);- expect(settled).not.toHaveBeenCalled();-- await vi.advanceTimersByTimeAsync(1);- expect(settled).toHaveBeenCalledOnce();- });-});diff --git a/packages/replica/src/core/settle.ts b/packages/replica/src/core/settle.tsdeleted file mode 100644index 02fe3e596b6..00000000000--- a/packages/replica/src/core/settle.ts+++ /dev/null@@ -1,16 +0,0 @@-/**- * Resolve once `promise` settles or `ms` elapses β never rejects, never hangs.- *- * Bounds a pre-paint hydrate in a route loader: the persisted read is usually- * sub-millisecond, and the deadline only fires on a pathological storage stall,- * so a route transition never waits longer than `ms` for it.- */-export const settleWithin = (promise: Promise<unknown>, ms: number): Promise<void> =>- new Promise((resolve) => {- const finish = () => {- clearTimeout(timer);- resolve();- };- const timer = setTimeout(finish, ms);- void Promise.resolve(promise).then(finish, finish);- });diff --git a/packages/replica/src/core/storedKeys.test.ts b/packages/replica/src/core/storedKeys.test.tsdeleted file mode 100644index 14ce07a6038..00000000000--- a/packages/replica/src/core/storedKeys.test.ts+++ /dev/null@@ -1,32 +0,0 @@-import { describe, expect, it } from 'vitest';--import { staticReplicaScope } from './defineReplica';-import { REPLICA_INDEX_KEY } from './engine';-import { readReplicaStoredKeys } from './storedKeys';-import type { ReplicaRow, ReplicaStorage } from './types';--const memoryStorage = (rows: Record<string, ReplicaRow<any>>): ReplicaStorage<any> => ({- get: async ({ queryKey, scope }) => rows[`${scope}/${queryKey}`],- remove: async () => {},- set: async () => {},-});--describe('readReplicaStoredKeys', () => {- it('reads the index row of the active scope', async () => {- const storage = memoryStorage({- [`a/${REPLICA_INDEX_KEY}`]: { data: ['k1', 'k2?sort=asc'], updatedAt: 1 },- [`b/${REPLICA_INDEX_KEY}`]: { data: ['other'], updatedAt: 1 },- });-- await expect(readReplicaStoredKeys({ scope: staticReplicaScope('a'), storage })).resolves.toEqual(- ['k1', 'k2?sort=asc'],- );- });-- it('reports no keys without an index row or a storage', async () => {- const scope = staticReplicaScope('a');-- await expect(readReplicaStoredKeys({ scope, storage: memoryStorage({}) })).resolves.toEqual([]);- await expect(readReplicaStoredKeys({ scope, storage: undefined })).resolves.toEqual([]);- });-});diff --git a/packages/replica/src/core/storedKeys.ts b/packages/replica/src/core/storedKeys.tsdeleted file mode 100644index 6b92c3a712f..00000000000--- a/packages/replica/src/core/storedKeys.ts+++ /dev/null@@ -1,26 +0,0 @@-import { REPLICA_INDEX_KEY } from './engine';-import type { ReplicaResource } from './types';--/**- * The entry storage keys this resource has a persisted row for in the active- * scope, oldest first.- *- * Storage has no key listing of its own; the engine keeps one index row per- * scope (`REPLICA_INDEX_KEY`) as it persists and drops entries, and this reads- * it. That is how code outside the owning store reaches rows an *earlier- * session* wrote β bounding how many survive a reload, or invalidating a row- * whose entry is not loaded in memory.- *- * The keys are storage keys (`key`, plus `?query` when the resource sets one),- * so a caller only matches them against entry keys when the resource leaves- * `query` unset.- */-export const readReplicaStoredKeys = async (- resource: Pick<ReplicaResource<any, any, any>, 'scope' | 'storage'>,-): Promise<string[]> => {- const row = await resource.storage?.get({- queryKey: REPLICA_INDEX_KEY,- scope: resource.scope.get(),- });- return (row?.data as unknown as string[] | undefined) ?? [];-};diff --git a/packages/replica/src/core/tombstones.test.ts b/packages/replica/src/core/tombstones.test.tsdeleted file mode 100644index d6363dda8a2..00000000000--- a/packages/replica/src/core/tombstones.test.ts+++ /dev/null@@ -1,48 +0,0 @@-import { describe, expect, it } from 'vitest';--import { createTombstones } from './tombstones';--describe('createTombstones', () => {- it('tracks keys per scope, so a scope switch keeps each identity guarded', () => {- const tombstones = createTombstones();- tombstones.add('user-1:personal', 'a');- tombstones.add('user-2:personal', 'a');-- expect(tombstones.has('user-1:personal', 'a')).toBe(true);- expect(tombstones.has('user-2:personal', 'a')).toBe(true);- expect(tombstones.has('user-1:personal', 'b')).toBe(false);- });-- it('is idempotent and drops an emptied scope bucket', () => {- const tombstones = createTombstones();- tombstones.add('s', 'a');- tombstones.add('s', 'a');- expect(tombstones.size()).toBe(1);-- tombstones.clear('s', 'a');- expect(tombstones.size()).toBe(0);- expect(tombstones.has('s', 'a')).toBe(false);- });-- it('bounds the tracked keys, evicting the oldest first', () => {- const tombstones = createTombstones(3);- for (const key of ['a', 'b', 'c', 'd']) tombstones.add('s', key);-- // A long-lived session that visits more subjects than the cap must not keep- // growing: the oldest keys fall out first.- expect(tombstones.size()).toBe(3);- expect(tombstones.has('s', 'a')).toBe(false);- expect(tombstones.has('s', 'd')).toBe(true);- });-- it('does not evict when re-adding an already-tracked key', () => {- const tombstones = createTombstones(2);- tombstones.add('s', 'a');- tombstones.add('s', 'a');- tombstones.add('s', 'b');-- expect(tombstones.size()).toBe(2);- expect(tombstones.has('s', 'a')).toBe(true);- expect(tombstones.has('s', 'b')).toBe(true);- });-});diff --git a/packages/replica/src/core/tombstones.ts b/packages/replica/src/core/tombstones.tsdeleted file mode 100644index 94e4b998baa..00000000000--- a/packages/replica/src/core/tombstones.ts+++ /dev/null@@ -1,65 +0,0 @@-/**- * How many removal tombstones one engine remembers. The guards exist to win a- * race with a hydrate that started around a removal, so a modest window is- * plenty; the cap is what keeps a long-lived session from growing forever.- */-export const DEFAULT_REMOVAL_TOMBSTONE_LIMIT = 5000;--export interface ReplicaTombstones {- /** Remember `scope`/`key` (idempotent). */- add: (scope: string, key: string) => void;- /** Forget `scope`/`key`; an emptied scope bucket is dropped too. */- clear: (scope: string, key: string) => void;- has: (scope: string, key: string) => boolean;- /** Tracked key count (observability + tests). */- size: () => number;-}--/**- * Scope-keyed removal tombstones with a hard size bound.- *- * A removal must stay visible until a server value supersedes it β including- * across a scope switch, so the keys are bucketed per scope rather than in one- * flat set. But the engine lives as long as the page: a session that visits tens- * of thousands of subjects (a task list full of items that simply have no- * acceptance) would otherwise pin one entry per subject forever. So the oldest- * keys are evicted once the cap is reached.- *- * Eviction is safe for what the tombstone is for: it closes a race with a- * hydrate that was already in flight when the removal landed. By the time a key- * is old enough to be evicted, any such read has long since settled.- */-export const createTombstones = (limit = DEFAULT_REMOVAL_TOMBSTONE_LIMIT): ReplicaTombstones => {- const byScope = new Map<string, Set<string>>();- let tracked = 0;-- const evictOverflow = () => {- while (tracked > limit) {- // `Map`/`Set` iterate in insertion order, so the first entry is the oldest.- const oldestScope = byScope.keys().next().value as string;- const keys = byScope.get(oldestScope)!;- keys.delete(keys.values().next().value as string);- tracked -= 1;- if (keys.size === 0) byScope.delete(oldestScope);- }- };-- return {- add: (scope, key) => {- const keys = byScope.get(scope) ?? new Set<string>();- byScope.set(scope, keys);- if (keys.has(key)) return;- keys.add(key);- tracked += 1;- evictOverflow();- },- clear: (scope, key) => {- const keys = byScope.get(scope);- if (!keys?.delete(key)) return;- tracked -= 1;- if (keys.size === 0) byScope.delete(scope);- },- has: (scope, key) => byScope.get(scope)?.has(key) ?? false,- size: () => tracked,- };-};diff --git a/packages/replica/src/core/types.ts b/packages/replica/src/core/types.tsdeleted file mode 100644index 189f94892f0..00000000000--- a/packages/replica/src/core/types.ts+++ /dev/null@@ -1,172 +0,0 @@-import type { ReplicaPagingConfig } from './paging';--// ---- persistence contract ------------------------------------------------/** Address of one persisted row: the resource's row key inside an identity scope. */-export interface ReplicaRowKey {- queryKey: string;- scope: string;-}--export interface ReplicaRow<T> {- data: T;- updatedAt: number;-}--/**- * Where a replica keeps its rows between sessions (IndexedDB, localStorage β¦).- * The server stays the durable source of truth, so `get` is best-effort: it- * swallows its own I/O failures and reports a miss. Writes are not: `set` and- * `remove` must reject when they did not land (see each method), so the- * engine can retry them instead of treating a dropped row as persisted.- */-export interface ReplicaStorage<T> {- get: (key: ReplicaRowKey) => Promise<ReplicaRow<T> | undefined>;- /**- * Strict read for destructive passes: like `get`, but **rejects** when the- * row could not be read (I/O error, unparsable value) instead of reporting a- * miss. The engine reads its per-scope index (and every row it patches)- * through it before `remove` / `clear` / an entity patch / an eviction, so an- * unreadable index fails the pass rather than passing for an empty one.- *- * Optional only for compatibility: a storage without it still hydrates and- * persists, but every destructive pass **fails** (`clear()` resolves `false`,- * a removal stays unpurged and is retried, an entity guard is kept) because- * the engine cannot tell a miss from a failed read through `get`.- */- getStrict?: (key: ReplicaRowKey) => Promise<ReplicaRow<T> | undefined>;- /**- * Delete a row. Must **reject** when the delete did not land (a closed- * IndexedDB, a quota or security error): the engine keeps the row indexed- * and the removal unpurged, so the next `remove` / `clear` retries it instead- * of letting a row the user deleted hydrate again. A missing row is a success.- */- remove: (key: ReplicaRowKey) => Promise<void>;- /**- * Write a row. Should **reject** when the write did not land: the engine only- * treats a row as holding a value after `set` resolved, so a rejected write is- * retried by the next persist rather than skipped as redundant. A storage that- * swallows failures still works, but a dropped write then survives until the- * value changes or the next session.- */- set: (key: ReplicaRowKey, row: ReplicaRow<T>) => Promise<void>;-}--/**- * Where the confirmed value of an entry came from.- * - `storage`: hydrated from the persisted projection (may be stale)- * - `server`: confirmed by a network response- * - `local`: written locally before any hydrate/replace landed- * - `seed`: a provisional local row (e.g. a list row standing in for a detail so- * an object stays resolvable). Unlike `local` it is *not* authoritative: a- * persisted `storage` value may replace it on hydrate, and it never persists β- * so it cannot overwrite the detail it is only standing in for.- */-export type ReplicaSource = 'local' | 'seed' | 'server' | 'storage';--/**- * Identity partition of the persisted projection (user + workspace by default).- * `use` feeds the sync hook, `get` imperative actions, `canPersist` gates writes- * while the scope is still an optimistic guess (identity not resolved yet).- */-export interface ReplicaScope {- /**- * Whether this runtime may read the persisted projection back into memory.- * Defaults to `true`. A surface that never resolves an identity (e.g. a- * public embed that does not mount the user store) opts out: its scope is- * only the last-known guess, so hydrating it could paint a different β or a- * since-invalidated β session's private rows before authorization is checked.- */- canHydrate?: () => boolean;- canPersist: () => boolean;- get: () => string;- use: () => string;-}--export interface ReplicaPendingMutation<T> {- apply: (data: T) => T;- id: number;- /**- * Query the overlay was started under. An entry key can be reused for another- * query (a navigation), and an overlay only ever describes the query that- * created it β carrying it over would apply (and later persist) one query's- * row inside another.- */- query?: string;-}--export interface ReplicaEntryMeta<T> {- /**- * Confirmed snapshot. Only kept while optimistic mutations are in flight β- * otherwise the view itself is the confirmed value.- */- base?: T;- /** Params of the last hydrate/replace β what `loadMore` pages with. */- params?: unknown;- pending: ReplicaPendingMutation<T>[];- /** Stable query identity beyond the key (filters, page size). */- query?: string;- /**- * Every write made while the entry is still a `seed`, in order β the seed- * writes themselves and the confirmed writes made over them. A hydrate that- * replaces the seed replays them onto the stored value: the seed's fresher- * fields (a list row's renamed title) and a confirmed edit made before- * storage answered both survive, instead of storage painting older values.- */- seedPatches?: ReplicaSeedPatch<T>[];- source: ReplicaSource;- updatedAt: number;-}--export interface ReplicaSeedPatch<T> {- /**- * Replayed onto the stored value, so a seed write must merge the fields it- * owns into its input rather than ignore it (its first run sees `undefined`).- */- apply: (data: T | undefined) => T | undefined;- persist: boolean;- /** A provisional seed write: replayed, but never makes the result confirmed. */- seed?: boolean;- /**- * Source of a seed write. A later seed of the same tag supersedes this one- * (since the last confirmed write), so it must carry every field this one set.- */- tag?: string;-}--/** Bookkeeping slot a replica keeps inside its domain store. */-export interface ReplicaState<T> {- entries: Record<string, ReplicaEntryMeta<T>>;- /** The scope every entry in memory belongs to. */- scope?: string;-}--export interface ReplicaResource<TParams, TData, TFetched = TData, TCursor = any> {- /** Paged resources receive the page cursor (`undefined` = head page). */- fetcher?: (params: TParams, cursor?: TCursor) => Promise<TFetched>;- key: (params: TParams) => string;- /** Cap of persisted rows per scope (LRU eviction, see `DefineReplicaOptions.persist`). */- maxPersistedEntries?: number;- name: string;- /** Storage namespace β `name` + `version`, so a version bump orphans old rows. */- namespace: string;- /** Present on paged resources (`definePagedReplica`). */- paging?: ReplicaPagingConfig<any, TCursor>;- /** Whether the resource survives a reload (it has a storage). */- persisted: boolean;- /** Whether an entry key may be hydrated and persisted (see `persistKey`). */- persistKey: (key: string) => boolean;- /**- * Query identity beyond `key` (filters, page size). Persisted rows are- * stored per query, so a different query never hydrates; in memory a query- * change resets loaded pages.- */- query: (params: TParams) => string | undefined;- scope: ReplicaScope;- storage?: ReplicaStorage<TData>;- /** Row key in `storage` for these params (`key`, plus `?query` when set). */- storageKey: (params: TParams) => string;- /** Custom query-cache key of the network sync (see `DefineReplicaOptions.syncKey`). */- syncKey?: (params: TParams) => readonly unknown[];- version: number;-}diff --git a/packages/replica/src/core/writeQueue.test.ts b/packages/replica/src/core/writeQueue.test.tsdeleted file mode 100644index ccea124c394..00000000000--- a/packages/replica/src/core/writeQueue.test.ts+++ /dev/null@@ -1,104 +0,0 @@-import { describe, expect, it, vi } from 'vitest';--import type { ReplicaStorage } from './types';-import { ReplicaWriteQueue } from './writeQueue';--describe('ReplicaWriteQueue', () => {- it('serializes writes for the same projection key', async () => {- let releaseFirst!: () => void;- const first = new Promise<void>((resolve) => (releaseFirst = resolve));- const calls: number[] = [];- const storage: ReplicaStorage<number> = {- get: vi.fn(),- remove: vi.fn(),- set: vi.fn(async (_key, projection) => {- calls.push(projection.data);- if (projection.data === 1) await first;- }),- };- const queue = new ReplicaWriteQueue(storage);- const key = { queryKey: 'list', scope: 'scope' };-- queue.set(key, { data: 1, updatedAt: 1 });- queue.set(key, { data: 2, updatedAt: 2 });- await vi.waitFor(() => expect(calls).toEqual([1]));-- releaseFirst();- await vi.waitFor(() => expect(calls).toEqual([1, 2]));- });-- it('update reads after earlier queued writes and never recreates a removed row', async () => {- const rows = new Map<string, { data: number; updatedAt: number }>();- const storage: ReplicaStorage<number> = {- get: async ({ queryKey }) => rows.get(queryKey),- remove: async ({ queryKey }) => {- rows.delete(queryKey);- },- set: async ({ queryKey }, projection) => {- await new Promise((resolve) => setTimeout(resolve, 5));- rows.set(queryKey, projection);- },- };- const queue = new ReplicaWriteQueue(storage);- const key = { queryKey: 'list', scope: 'scope' };- const increment = (current?: { data: number }) =>- current ? { data: current.data + 1, updatedAt: 2 } : undefined;-- queue.set(key, { data: 1, updatedAt: 1 });- queue.update(key, increment);- await vi.waitFor(() => expect(rows.get('list')?.data).toBe(2));-- queue.remove(key);- queue.update(key, increment);- await new Promise((resolve) => setTimeout(resolve, 20));- expect(rows.has('list')).toBe(false);- });-- it('reports whether a queued write actually landed', async () => {- let fail = false;- const storage: ReplicaStorage<number> = {- get: vi.fn(),- remove: vi.fn(async () => {- if (fail) throw new Error('IndexedDB delete failed');- }),- set: vi.fn(async () => {}),- };- const queue = new ReplicaWriteQueue(storage);- const key = { queryKey: 'list', scope: 'scope' };-- await expect(queue.remove(key)).resolves.toBe(true);-- fail = true;- // A rejected delete resolves `false` instead of rejecting: the caller must be- // able to keep the removal retryable, and one bad write must not poison the- // chain for later writers on the same key.- await expect(queue.remove(key)).resolves.toBe(false);- await expect(queue.set(key, { data: 1, updatedAt: 1 })).resolves.toBe(true);- });-- it('update reads best-effort by default, and strictly only when asked', async () => {- const set = vi.fn(async () => {});- const legacy: ReplicaStorage<number> = { get: async () => undefined, remove: vi.fn(), set };- const key = { queryKey: 'row', scope: 'scope' };- const queue = new ReplicaWriteQueue(legacy);- const next = () => ({ data: 1, updatedAt: 1 });-- expect(await queue.update(key, next)).toBe(true);- expect(await queue.update(key, next, { read: 'prefer-strict' })).toBe(true);- // No `getStrict`: a strict read-modify-write refuses rather than guessing.- expect(await queue.update(key, next, { read: 'strict' })).toBe(false);- expect(set).toHaveBeenCalledTimes(2);-- const failing = new ReplicaWriteQueue<number>({- get: async () => undefined,- getStrict: async () => {- throw new Error('read failed');- },- remove: vi.fn(),- set,- });- // A failed strict read never passes for a missing row.- expect(await failing.update(key, next, { read: 'prefer-strict' })).toBe(false);- expect(set).toHaveBeenCalledTimes(2);- });-});diff --git a/packages/replica/src/core/writeQueue.ts b/packages/replica/src/core/writeQueue.tsdeleted file mode 100644index 6557159d9ed..00000000000--- a/packages/replica/src/core/writeQueue.ts+++ /dev/null@@ -1,89 +0,0 @@-import type { ReplicaRow, ReplicaRowKey, ReplicaStorage } from './types';--/**- * Strict read of one row (see `ReplicaStorage.getStrict`). Rejects when the- * storage has no strict read: its `get` swallows I/O failures into a miss, so a- * destructive pass reading through it could take an unreadable row (the index)- * for an empty one and report success for rows it never saw.- */-export const readReplicaRowStrict = <T>(- storage: ReplicaStorage<T>,- key: ReplicaRowKey,-): Promise<ReplicaRow<T> | undefined> =>- // Call through `storage`: a class-based storage needs its receiver.- storage.getStrict- ? storage.getStrict(key)- : Promise.reject(- new Error('[replica] storage has no `getStrict`: destructive passes are disabled'),- );--/**- * Serializes writes for one projection key. A later snapshot can never be overwritten by an- * earlier, slower IndexedDB write.- */-export class ReplicaWriteQueue<T> {- readonly #pending = new Map<string, Promise<void>>();- readonly #storage: ReplicaStorage<T>;-- constructor(storage: ReplicaStorage<T>) {- this.#storage = storage;- }-- #id = ({ queryKey, scope }: ReplicaRowKey) => `${scope}:${queryKey}`;-- /** Resolves `false` when storage rejected the delete (see `ReplicaStorage.remove`). */- remove = (key: ReplicaRowKey): Promise<boolean> =>- this.#enqueue(key, () => this.#storage.remove(key));-- set = (key: ReplicaRowKey, value: ReplicaRow<T>): Promise<boolean> =>- this.#enqueue(key, () => this.#storage.set(key, value));-- /**- * Serialized read-modify-write: `fn` sees the row as of every earlier queued- * write for this key. Return a projection to write it, `null` to remove the- * row, or `undefined` to leave it untouched (a missing row stays missing).- *- * `read` picks how the row is read:- * - `'get'` (default): best-effort `get`, a failed read passes for a miss.- * - `'prefer-strict'`: `getStrict` when the storage has one, so a read failure- * fails the update (resolves `false`) instead of passing for a missing row- * that `fn` would then overwrite; `get` otherwise.- * - `'strict'`: `getStrict` only; a storage without it fails the update.- * Required for destructive passes (see `readReplicaRowStrict`).- */- update = (- key: ReplicaRowKey,- fn: (current: ReplicaRow<T> | undefined) => ReplicaRow<T> | null | undefined,- { read = 'get' }: { read?: 'get' | 'prefer-strict' | 'strict' } = {},- ): Promise<boolean> =>- this.#enqueue(key, async () => {- const storage = this.#storage;- const strict = read === 'strict' || (read === 'prefer-strict' && !!storage.getStrict);- const current = await (strict ? readReplicaRowStrict(storage, key) : storage.get(key));- const next = fn(current);- if (next === null) await this.#storage.remove(key);- else if (next !== undefined) await this.#storage.set(key, next);- });-- /**- * Queue `operation` behind the earlier writes for this key and report whether- * it settled successfully. A failed write never rejects the returned promise:- * the caller decides what to do (e.g. keep a removal retryable), while a- * rejection on the queue itself is already swallowed so one bad write cannot- * poison the chain.- */- #enqueue = (key: ReplicaRowKey, operation: () => Promise<void>): Promise<boolean> => {- const id = this.#id(key);- const previous = this.#pending.get(id) ?? Promise.resolve();- const current = previous.catch(() => undefined).then(operation);- this.#pending.set(id, current);- const settled = current.then(- () => true,- () => false,- );- void settled.finally(() => {- if (this.#pending.get(id) === current) this.#pending.delete(id);- });- return settled;- };-}diff --git a/packages/replica/src/index.ts b/packages/replica/src/index.tsdeleted file mode 100644index dca454763cc..00000000000--- a/packages/replica/src/index.ts+++ /dev/null@@ -1,12 +0,0 @@-export * from './core/defineReplica';-export * from './core/engine';-export * from './core/entity';-export * from './core/entityAdapters';-export * from './core/keys';-export * from './core/paging';-export * from './core/reducer';-export * from './core/settle';-export * from './core/storedKeys';-export type * from './core/types';-export * from './core/writeQueue';-export * from './storage';diff --git a/packages/replica/src/storage/index.ts b/packages/replica/src/storage/index.tsdeleted file mode 100644index 25b8252d50a..00000000000--- a/packages/replica/src/storage/index.ts+++ /dev/null@@ -1,2 +0,0 @@-export * from './keyValue';-export * from './localStorage';diff --git a/packages/replica/src/storage/keyValue.test.ts b/packages/replica/src/storage/keyValue.test.tsdeleted file mode 100644index 532f236fe7d..00000000000--- a/packages/replica/src/storage/keyValue.test.ts+++ /dev/null@@ -1,79 +0,0 @@-import { describe, expect, it, vi } from 'vitest';--import { KeyValueReplicaStorage, type ReplicaKeyValueStore } from './keyValue';--const createStore = (overrides: Partial<ReplicaKeyValueStore> = {}) => {- const rows = new Map<string, unknown>();- const store: ReplicaKeyValueStore = {- delete: vi.fn(async (key: string) => {- rows.delete(key);- }),- get: vi.fn(async (key: string) => rows.get(key)),- initialize: vi.fn(async () => {}),- set: vi.fn(async (key: string, value: unknown) => {- rows.set(key, value);- }),- ...overrides,- };- return { rows, store };-};--describe('KeyValueReplicaStorage', () => {- it('stores one scoped record per row, after opening the store', async () => {- const { rows, store } = createStore();- const storage = new KeyValueReplicaStorage<string[]>({ namespace: 'projects', store });- const key = { queryKey: 'detail:1', scope: 'user:workspace' };-- await storage.set(key, { data: ['cached'], updatedAt: 1 });-- expect(store.initialize).toHaveBeenCalled();- expect([...rows.keys()]).toEqual(['projects:user%3Aworkspace:detail%3A1']);- await expect(storage.get(key)).resolves.toEqual({ data: ['cached'], updatedAt: 1 });- await expect(storage.get({ ...key, scope: 'other' })).resolves.toBeUndefined();- });-- it('works with a store that needs no initialization', async () => {- const { store } = createStore({ initialize: undefined });- const storage = new KeyValueReplicaStorage<number>({ namespace: 'n', store });- const key = { queryKey: 'q', scope: 's' };-- await storage.set(key, { data: 1, updatedAt: 1 });- await storage.remove(key);-- await expect(storage.getStrict(key)).resolves.toBeUndefined();- });-- it('rejects a write that did not land, so the replica retries it', async () => {- const { store } = createStore({ set: vi.fn().mockRejectedValue(new Error('aborted')) });- const storage = new KeyValueReplicaStorage<string[]>({ namespace: 'projects', store });-- await expect(- storage.set({ queryKey: 'all', scope: 'personal' }, { data: ['x'], updatedAt: 1 }),- ).rejects.toThrow('aborted');- });-- it('treats a store that cannot open as a cache miss', async () => {- const { store } = createStore({- initialize: vi.fn().mockRejectedValue(new Error('unavailable')),- });- const storage = new KeyValueReplicaStorage<string[]>({ namespace: 'projects', store });-- await expect(storage.get({ queryKey: 'all', scope: 'personal' })).resolves.toBeUndefined();- });-- it('reports a failed delete so the caller can retry it', async () => {- const { store } = createStore({ delete: vi.fn().mockRejectedValue(new Error('closed')) });- const storage = new KeyValueReplicaStorage<string[]>({ namespace: 'projects', store });-- await expect(storage.remove({ queryKey: 'all', scope: 'personal' })).rejects.toThrow('closed');- });-- it('rejects a strict read that failed, while get stays a cache miss', async () => {- const { store } = createStore({ get: vi.fn().mockRejectedValue(new Error('closed')) });- const storage = new KeyValueReplicaStorage<string[]>({ namespace: 'projects', store });- const key = { queryKey: '__replica:index', scope: 'personal' };-- await expect(storage.getStrict(key)).rejects.toThrow('closed');- await expect(storage.get(key)).resolves.toBeUndefined();- });-});diff --git a/packages/replica/src/storage/keyValue.ts b/packages/replica/src/storage/keyValue.tsdeleted file mode 100644index 5ac21092cdb..00000000000--- a/packages/replica/src/storage/keyValue.ts+++ /dev/null@@ -1,74 +0,0 @@-import type { ReplicaRow, ReplicaRowKey, ReplicaStorage } from '../core/types';--/**- * An async key-value store a replica can persist into: an IndexedDB object- * store, a SQLite table behind IPC, a `Map` in tests. Values are stored as- * given (structured clone), so the store decides what it can hold.- */-export interface ReplicaKeyValueStore {- /** Rejects when the delete did not land. A missing key is a success. */- delete: (key: string) => Promise<void>;- /** Rejects when the read failed; resolves `undefined` for a missing key. */- get: (key: string) => Promise<unknown>;- /** Opens the store; awaited before every operation. */- initialize?: () => Promise<void>;- /** Rejects when the write did not land. */- set: (key: string, value: unknown) => Promise<void>;-}--export interface KeyValueReplicaStorageOptions {- /** Prefix of every row of this storage, usually the resource name. */- namespace: string;- store: ReplicaKeyValueStore;-}--/** Store key of one row: `<namespace>:<scope>:<queryKey>`, each part URI-encoded but the namespace. */-export const replicaRowStoreKey = (namespace: string, { queryKey, scope }: ReplicaRowKey) =>- `${namespace}:${encodeURIComponent(scope)}:${encodeURIComponent(queryKey)}`;--/** {@link ReplicaStorage} over an async key-value store, one record per row. */-export class KeyValueReplicaStorage<T> implements ReplicaStorage<T> {- readonly #namespace: string;- readonly #store: ReplicaKeyValueStore;-- constructor({ namespace, store }: KeyValueReplicaStorageOptions) {- this.#namespace = namespace;- this.#store = store;- }-- #key = (key: ReplicaRowKey) => replicaRowStoreKey(this.#namespace, key);-- get = async (key: ReplicaRowKey): Promise<ReplicaRow<T> | undefined> => {- try {- return await this.getStrict(key);- } catch {- return undefined;- }- };-- /** Like `get`, but rejects when the row could not be read (see `ReplicaStorage.getStrict`). */- getStrict = async (key: ReplicaRowKey): Promise<ReplicaRow<T> | undefined> => {- await this.#store.initialize?.();- return (await this.#store.get(this.#key(key))) as ReplicaRow<T> | undefined;- };-- /**- * Rejects when the delete did not land, unlike reads: a caller that removes a- * row the user deleted must be able to retry it.- */- remove = async (key: ReplicaRowKey): Promise<void> => {- await this.#store.initialize?.();- await this.#store.delete(this.#key(key));- };-- /**- * Rejects when the write did not land (see `ReplicaStorage.set`): the replica- * engine only treats a row as holding a value after a confirmed write, so a- * dropped write is retried by the next persist instead of being skipped as- * redundant.- */- set = async (key: ReplicaRowKey, row: ReplicaRow<T>): Promise<void> => {- await this.#store.initialize?.();- await this.#store.set(this.#key(key), row);- };-}diff --git a/packages/replica/src/storage/localStorage.test.ts b/packages/replica/src/storage/localStorage.test.tsdeleted file mode 100644index a0a7ad4adb6..00000000000--- a/packages/replica/src/storage/localStorage.test.ts+++ /dev/null@@ -1,78 +0,0 @@-import { afterEach, describe, expect, it, vi } from 'vitest';--import { LocalStorageReplicaStorage } from './localStorage';--afterEach(() => {- vi.restoreAllMocks();- localStorage.clear();-});--describe('LocalStorageReplicaStorage', () => {- it('restores a scoped row synchronously before the next paint', () => {- const storage = new LocalStorageReplicaStorage<string[]>({ namespace: 'test' });- const key = { queryKey: 'display', scope: 'user-a' };-- void storage.set(key, { data: ['cached'], updatedAt: 1 });-- expect(storage.getSync(key)).toEqual({ data: ['cached'], updatedAt: 1 });- expect(storage.getSync({ ...key, scope: 'user-b' })).toBeUndefined();- });-- it('isolates rows by scope and query key', async () => {- const storage = new LocalStorageReplicaStorage<string[]>({ namespace: 'test' });-- await storage.set({ queryKey: 'limit:10', scope: 'scope-a' }, { data: ['a'], updatedAt: 1 });-- expect(localStorage.getItem('test:scope-a:limit%3A10')).toBe(- JSON.stringify({ data: ['a'], updatedAt: 1 }),- );- await expect(storage.get({ queryKey: 'limit:10', scope: 'scope-b' })).resolves.toBeUndefined();- await expect(storage.get({ queryKey: 'limit:50', scope: 'scope-a' })).resolves.toBeUndefined();- });-- it('serializes through a custom codec', async () => {- const codec = {- parse: vi.fn((value: string) => ({ data: value.slice(4), updatedAt: 0 })),- stringify: vi.fn(({ data }: { data: string }) => `raw:${data}`),- };- const storage = new LocalStorageReplicaStorage<string>({ codec, namespace: 'test' });- const key = { queryKey: 'q', scope: 's' };-- await storage.set(key, { data: 'hello', updatedAt: 1 });-- await expect(storage.get(key)).resolves.toEqual({ data: 'hello', updatedAt: 0 });- });-- it('rejects a write that did not land (quota), so the replica retries it', async () => {- const storage = new LocalStorageReplicaStorage<string[]>({ namespace: 'test' });- vi.spyOn(localStorage, 'setItem').mockImplementation(() => {- throw new Error('QuotaExceededError');- });-- await expect(- storage.set({ queryKey: 'q', scope: 'user-a' }, { data: ['x'], updatedAt: 1 }),- ).rejects.toThrow('QuotaExceededError');- });-- it('reports a failed delete so the caller can retry it', async () => {- const storage = new LocalStorageReplicaStorage<string[]>({ namespace: 'test' });- vi.spyOn(localStorage, 'removeItem').mockImplementation(() => {- throw new Error('access denied');- });-- await expect(storage.remove({ queryKey: 'display', scope: 'user-a' })).rejects.toThrow(- 'access denied',- );- });-- it('rejects a strict read that failed, while get stays a cache miss', async () => {- const storage = new LocalStorageReplicaStorage<string[]>({ namespace: 'test' });- const key = { queryKey: '__replica:index', scope: 'user-a' };- vi.spyOn(localStorage, 'getItem').mockImplementation(() => {- throw new Error('access denied');- });-- await expect(storage.getStrict(key)).rejects.toThrow('access denied');- await expect(storage.get(key)).resolves.toBeUndefined();- });-});diff --git a/packages/replica/src/storage/localStorage.ts b/packages/replica/src/storage/localStorage.tsdeleted file mode 100644index 6df71147923..00000000000--- a/packages/replica/src/storage/localStorage.ts+++ /dev/null@@ -1,78 +0,0 @@-import type { ReplicaRow, ReplicaRowKey, ReplicaStorage } from '../core/types';-import { replicaRowStoreKey } from './keyValue';--/** Turns a row into the string `localStorage` holds, and back. */-export interface ReplicaRowCodec<T> {- parse: (value: string) => ReplicaRow<T>;- stringify: (row: ReplicaRow<T>) => string;-}--export interface LocalStorageReplicaStorageOptions<T> {- /** Defaults to JSON. Pass a richer codec (e.g. superjson) for `Date`, `Map` β¦ */- codec?: ReplicaRowCodec<T>;- /** Prefix of every row of this storage, usually the resource name. */- namespace: string;-}--const jsonCodec: ReplicaRowCodec<any> = { parse: JSON.parse, stringify: JSON.stringify };--/**- * {@link ReplicaStorage} over `window.localStorage`. Small values only (the- * origin shares a ~5 MB quota), but the read is synchronous: `getSync` restores- * a row inside pre-paint initialization without yielding a frame. Outside a- * browser every operation is a no-op miss.- */-export class LocalStorageReplicaStorage<T> implements ReplicaStorage<T> {- readonly #codec: ReplicaRowCodec<T>;- readonly #namespace: string;-- constructor({ codec = jsonCodec, namespace }: LocalStorageReplicaStorageOptions<T>) {- this.#codec = codec;- this.#namespace = namespace;- }-- #key = (key: ReplicaRowKey) => replicaRowStoreKey(this.#namespace, key);-- get = async (key: ReplicaRowKey): Promise<ReplicaRow<T> | undefined> => this.getSync(key);-- /** Restore a row inside pre-paint initialization without yielding a frame. */- getSync = (key: ReplicaRowKey): ReplicaRow<T> | undefined => {- if (typeof window === 'undefined') return undefined;-- try {- const value = localStorage.getItem(this.#key(key));- return value ? this.#codec.parse(value) : undefined;- } catch {- return undefined;- }- };-- /** Like `get`, but rejects when the row could not be read or parsed (see `ReplicaStorage.getStrict`). */- getStrict = async (key: ReplicaRowKey): Promise<ReplicaRow<T> | undefined> => {- if (typeof window === 'undefined') return undefined;-- const value = localStorage.getItem(this.#key(key));- return value ? this.#codec.parse(value) : undefined;- };-- /**- * Rejects when the delete did not land (e.g. storage access denied), unlike- * reads: a caller removing a row the user deleted must be able to retry it.- */- remove = async (key: ReplicaRowKey): Promise<void> => {- if (typeof window === 'undefined') return;-- localStorage.removeItem(this.#key(key));- };-- /**- * Rejects when the write did not land (a quota error, see `ReplicaStorage.set`):- * the replica engine only treats a row as holding a value after a confirmed- * write.- */- set = async (key: ReplicaRowKey, row: ReplicaRow<T>): Promise<void> => {- if (typeof window === 'undefined') return;-- localStorage.setItem(this.#key(key), this.#codec.stringify(row));- };-}diff --git a/packages/replica/src/zustand/createReplicaSlice.fetch.test.ts b/packages/replica/src/zustand/createReplicaSlice.fetch.test.tsdeleted file mode 100644index 1f550cbca70..00000000000--- a/packages/replica/src/zustand/createReplicaSlice.fetch.test.ts+++ /dev/null@@ -1,472 +0,0 @@-/**- * @vitest-environment happy-dom- */-import { act, renderHook, waitFor } from '@testing-library/react';-import type { PropsWithChildren } from 'react';-import { createElement } from 'react';-import { SWRConfig } from 'swr';-import { beforeEach, describe, expect, it, vi } from 'vitest';-import { createStore } from 'zustand/vanilla';--import { testDriver } from '../../tests/testDriver';-import { defineReplica } from '../core/defineReplica';-import { REPLICA_INDEX_KEY } from '../core/engine';-import { replicaKeys } from '../core/keys';-import { createReplicaState } from '../core/reducer';-import type { ReplicaRow, ReplicaScope, ReplicaState, ReplicaStorage } from '../core/types';-import type { ReplicaEffects } from './createReplicaSlice';-import { createReplicaSlice, recordLens, ReplicaScopeChangedError } from './createReplicaSlice';-import type { ReplicaSyncDriver } from './driver';--type Value = string[] | null;--interface TestState {- lists: Record<string, Value>;- listsReplica: ReplicaState<Value>;-}--const scopeState = { current: 'user-1:personal' };-const scope: ReplicaScope = {- canPersist: () => true,- get: () => scopeState.current,- use: () => scopeState.current,-};--const createMemoryStorage = () => {- const rows = new Map<string, ReplicaRow<Value>>();- const indexRows = new Map<string, ReplicaRow<Value>>();- const read: ReplicaStorage<Value>['get'] = async ({ queryKey, scope }) =>- queryKey === REPLICA_INDEX_KEY ? indexRows.get(scope) : rows.get(`${scope}|${queryKey}`);- const storage: ReplicaStorage<Value> = {- get: read,- getStrict: read,- remove: async ({ queryKey, scope }) => {- if (queryKey === REPLICA_INDEX_KEY) return void indexRows.delete(scope);- rows.delete(`${scope}|${queryKey}`);- },- set: async ({ queryKey, scope }, row) => {- if (queryKey === REPLICA_INDEX_KEY) return void indexRows.set(scope, row);- rows.set(`${scope}|${queryKey}`, row);- },- };- return { rows, storage };-};--/** A fetcher whose responses resolve / reject on demand, in call order. */-const deferredFetcher = () => {- const calls: { reject: (error: unknown) => void; resolve: (value: Value) => void }[] = [];- const fetcher = vi.fn(- () =>- new Promise<Value>((resolve, reject) => {- calls.push({ reject, resolve });- }),- );- return { calls, fetcher };-};--const setup = ({- driver = testDriver,- effects,- fetcher = vi.fn(async () => ['server'] as Value),- storage = createMemoryStorage(),-}: {- driver?: ReplicaSyncDriver;- effects?: ReplicaEffects<{ id: string }, Value>;- fetcher?: (params: { id: string }) => Promise<Value>;- storage?: ReturnType<typeof createMemoryStorage>;-} = {}) => {- const resource = defineReplica<{ id: string }, Value>({- fetcher,- key: ({ id }) => id,- name: 'fetchList',- scope,- storage: storage.storage,- version: 1,- });- const store = createStore<TestState>()(() => ({- lists: {},- listsReplica: createReplicaState(),- }));- const slice = createReplicaSlice<TestState, { id: string }, Value>(resource, {- driver,- effects,- get: store.getState,- // `null` is the server's "this entry does not exist".- isMissing: (data) => data === null,- set: (partial) => store.setState(partial),- stateKey: 'listsReplica',- view: recordLens('lists'),- });- return { slice, storage, store };-};--const wrapper = ({ children }: PropsWithChildren) =>- createElement(SWRConfig, { value: { dedupingInterval: 0, provider: () => new Map() } }, children);--const effectSpies = () => ({- onApplied: vi.fn(),- onError: vi.fn(),- onMissing: vi.fn(),- onPurge: vi.fn(),- onSettled: vi.fn(),-});--beforeEach(() => {- scopeState.current = 'user-1:personal';-});--describe('createReplicaSlice fetch', () => {- it('applies the head with no view mounted, persists it and runs onApplied', async () => {- const effects = effectSpies();- const { slice, storage, store } = setup({ effects });-- const result = await slice.fetch({ id: 'a' });-- expect(result).toEqual({ applied: true, data: ['server'], missing: false });- expect(store.getState().lists.a).toEqual(['server']);- expect(effects.onApplied).toHaveBeenCalledWith(- ['server'],- { id: 'a' },- { key: 'a', scope: 'user-1:personal', source: 'fetch' },- );- await waitFor(() => expect(storage.rows.get('user-1:personal|a')?.data).toEqual(['server']));- });-- it('drops a response captured under a scope the store has left, without effects', async () => {- const { calls, fetcher } = deferredFetcher();- const effects = effectSpies();- const { slice, storage, store } = setup({ effects, fetcher });-- const pending = slice.fetch({ id: 'a' });- scopeState.current = 'user-2:personal';- calls[0].resolve(['previous identity']);-- await expect(pending).resolves.toMatchObject({ applied: false });- expect(store.getState().lists.a).toBeUndefined();- expect(effects.onApplied).not.toHaveBeenCalled();- expect(storage.rows.size).toBe(0);- });-- it('drops a response whose entry was removed while it was in flight', async () => {- const { calls, fetcher } = deferredFetcher();- const effects = effectSpies();- const { slice, store } = setup({ effects, fetcher });-- const pending = slice.fetch({ id: 'a' });- slice.remove('a');- calls[0].resolve(['deleted on the server']);-- await expect(pending).resolves.toMatchObject({ applied: false });- expect(store.getState().lists.a).toBeUndefined();- expect(effects.onApplied).not.toHaveBeenCalled();- });-- it('settles a discarded response so per-request bookkeeping can be released', async () => {- const { calls, fetcher } = deferredFetcher();- const effects = effectSpies();- const { slice } = setup({ effects, fetcher });-- const pending = slice.fetch({ id: 'a' });- slice.remove('a');- calls[0].resolve(['deleted on the server']);-- await expect(pending).resolves.toMatchObject({ applied: false });- expect(effects.onSettled).toHaveBeenCalledWith(- ['deleted on the server'],- { id: 'a' },- { key: 'a', scope: 'user-1:personal', source: 'fetch' },- );- });-- it('drops a response whose request started before a clear()', async () => {- const { calls, fetcher } = deferredFetcher();- const effects = effectSpies();- const { slice, store } = setup({ effects, fetcher });-- const pending = slice.fetch({ id: 'a' });- await slice.clear();- calls[0].resolve(['wiped']);-- await expect(pending).resolves.toMatchObject({ applied: false });- expect(store.getState().lists.a).toBeUndefined();- expect(effects.onApplied).not.toHaveBeenCalled();- });-- it('removes a terminal absence and runs onMissing in the active scope', async () => {- const storage = createMemoryStorage();- const effects = effectSpies();- const { slice, store } = setup({ effects, fetcher: vi.fn(async () => null), storage });- store.setState({ lists: { a: ['cached'] } });- storage.rows.set('user-1:personal|a', { data: ['cached'], updatedAt: 1 });-- await expect(slice.fetch({ id: 'a' })).resolves.toEqual({- applied: true,- data: null,- missing: true,- });-- expect(store.getState().lists.a).toBeUndefined();- expect(effects.onMissing).toHaveBeenCalledWith(- { id: 'a' },- { key: 'a', scope: 'user-1:personal', source: 'fetch' },- );- expect(effects.onApplied).not.toHaveBeenCalled();- await waitFor(() => expect(storage.rows.has('user-1:personal|a')).toBe(false));- });-- it('purges a late terminal absence in the scope it was captured under, without onMissing', async () => {- const storage = createMemoryStorage();- storage.rows.set('user-1:personal|a', { data: ['previous'], updatedAt: 1 });- storage.rows.set('user-2:personal|a', { data: ['current'], updatedAt: 1 });- const { calls, fetcher } = deferredFetcher();- const effects = effectSpies();- const { slice, store } = setup({ effects, fetcher, storage });- store.setState({ lists: { a: ['current'] } });-- const pending = slice.fetch({ id: 'a' });- scopeState.current = 'user-2:personal';- calls[0].resolve(null);-- await expect(pending).resolves.toEqual({ applied: false, data: null, missing: true });- // The row of the scope the request belonged to is goneβ¦- await waitFor(() => expect(storage.rows.has('user-1:personal|a')).toBe(false));- // β¦while the scope on screen keeps its own value and runs no effects.- expect(storage.rows.get('user-2:personal|a')?.data).toEqual(['current']);- expect(store.getState().lists.a).toEqual(['current']);- expect(effects.onMissing).not.toHaveBeenCalled();- // Linked resources purge their own rows of that scope.- expect(effects.onPurge).toHaveBeenCalledWith(- { id: 'a' },- { key: 'a', scope: 'user-1:personal', source: 'fetch' },- );- });-- it('rejects on a failed request after routing it to effects.onError with the captured scope', async () => {- const failure = new Error('offline');- const { calls, fetcher } = deferredFetcher();- const effects = effectSpies();- const { slice } = setup({ effects, fetcher });-- const active = slice.fetch({ id: 'a' });- calls[0].reject(failure);- await expect(active).rejects.toBe(failure);- expect(effects.onError).toHaveBeenLastCalledWith(- failure,- { id: 'a' },- { isActive: true, key: 'a', scope: 'user-1:personal' },- );-- const offScope = slice.fetch({ id: 'b' });- scopeState.current = 'user-2:personal';- calls[1].reject(failure);- await expect(offScope).rejects.toBe(failure);- expect(effects.onError).toHaveBeenLastCalledWith(- failure,- { id: 'b' },- { isActive: false, key: 'b', scope: 'user-1:personal' },- );- });-- it('joins the request of a mounted useSync and settles it once', async () => {- const { calls, fetcher } = deferredFetcher();- const effects = effectSpies();- const onSuccess = vi.fn();- const { slice, store } = setup({ effects, fetcher });-- renderHook(() => slice.useSync({ id: 'a' }, { onSuccess }), { wrapper });- await waitFor(() => expect(fetcher).toHaveBeenCalledTimes(1));-- const pending = slice.fetch({ id: 'a' });- expect(fetcher).toHaveBeenCalledTimes(1);-- await act(async () => calls[0].resolve(['server']));- await expect(pending).resolves.toEqual({ applied: true, data: ['server'], missing: false });-- expect(store.getState().lists.a).toEqual(['server']);- await waitFor(() => expect(onSuccess).toHaveBeenCalledTimes(1));- // The resource effects run once for the shared request, not per path.- expect(effects.onApplied).toHaveBeenCalledTimes(1);- expect(effects.onApplied.mock.calls[0][2]).toMatchObject({ source: 'sync' });- });-- it('runs the resource effects for useSync responses too', async () => {- const effects = effectSpies();- const { slice } = setup({ effects });-- renderHook(() => slice.useSync({ id: 'a' }), { wrapper });-- await waitFor(() =>- expect(effects.onApplied).toHaveBeenCalledWith(- ['server'],- { id: 'a' },- { key: 'a', scope: 'user-1:personal', source: 'sync' },- ),- );- });-- it('settles a useSync response the hook moved past, with its resource effects', async () => {- const { calls, fetcher } = deferredFetcher();- const effects = effectSpies();- const onSuccess = vi.fn();- const { slice, store } = setup({ effects, fetcher });-- const { rerender } = renderHook(({ id }) => slice.useSync({ id }, { onSuccess }), {- initialProps: { id: 'a' },- wrapper,- });- await waitFor(() => expect(fetcher).toHaveBeenCalledTimes(1));- rerender({ id: 'b' });- await waitFor(() => expect(fetcher).toHaveBeenCalledTimes(2));-- // `a` answers "gone" after the view moved to `b`: the driver no longer- // calls this hook back for it, yet the absence is still settled.- store.setState({ lists: { a: ['cached'] } });- await act(async () => calls[0].resolve(null));-- expect(store.getState().lists.a).toBeUndefined();- expect(effects.onMissing).toHaveBeenCalledWith(- { id: 'a' },- { key: 'a', scope: 'user-1:personal', source: 'sync' },- );- // The view's own callback is not run for a key it left.- expect(onSuccess).not.toHaveBeenCalled();- });-- it('releases the record of a sync request whose callback the driver skipped', async () => {- const { calls, fetcher } = deferredFetcher();- const { slice } = setup({ fetcher });-- const { rerender, unmount } = renderHook(({ id }) => slice.useSync({ id }), {- initialProps: { id: 'a' },- wrapper,- });- await waitFor(() => expect(fetcher).toHaveBeenCalledTimes(1));- rerender({ id: 'b' });- await waitFor(() => expect(fetcher).toHaveBeenCalledTimes(2));- rerender({ id: 'c' });- await waitFor(() => expect(fetcher).toHaveBeenCalledTimes(3));- unmount();-- // Every request answers after its hook moved on or unmounted: the driver- // runs none of the callbacks that would have taken the records.- await act(async () => {- for (const call of calls) call.resolve(['server']);- });- await act(() => new Promise((resolve) => setTimeout(resolve, 10)));-- expect(slice.debugPendingSyncRequests()).toBe(0);- });-- it('settles a fetch into the scope its caller captured, and refuses one that left it', async () => {- const { calls, fetcher } = deferredFetcher();- const { slice, store } = setup({ fetcher });-- const pending = slice.fetch({ id: 'a' }, { scope: 'user-1:personal' });- scopeState.current = 'user-2:personal';- calls[0].resolve(['previous identity']);- await expect(pending).resolves.toMatchObject({ applied: false });-- // A later step of the same flow must not fetch the new identity's data- // under the old identity's label.- await expect(slice.fetch({ id: 'b' }, { scope: 'user-1:personal' })).rejects.toBeInstanceOf(- ReplicaScopeChangedError,- );- expect(fetcher).toHaveBeenCalledTimes(1);- expect(store.getState().lists).toEqual({});- });-- it('a fresh fetch retires the requests started before it', async () => {- const { calls, fetcher } = deferredFetcher();- const { slice, store } = setup({ fetcher });-- const stale = slice.fetch({ id: 'a' });- const fresh = slice.fetch({ id: 'a' }, { fresh: true });- expect(fetcher).toHaveBeenCalledTimes(2);-- // The pre-mutation request answers first: it may not paint even briefly.- calls[0].resolve(['before mutation']);- await expect(stale).resolves.toMatchObject({ applied: false });- expect(store.getState().lists.a).toBeUndefined();-- calls[1].resolve(['after mutation']);- await expect(fresh).resolves.toMatchObject({ applied: true });- expect(store.getState().lists.a).toEqual(['after mutation']);- });-- it('keeps no retirement records once nothing older is in flight', async () => {- const { slice } = setup();-- for (let index = 0; index < 50; index++) {- await slice.fetch({ id: `doc-${index}` });- await slice.fetch({ id: `doc-${index}` }, { fresh: true });- }-- expect(slice.debugRetiredRequests()).toBe(0);- });-- it('keeps a retirement while an older request is in flight, then prunes it', async () => {- const { calls, fetcher } = deferredFetcher();- const { slice, store } = setup({ fetcher });-- const older = slice.fetch({ id: 'a' });- const newer = slice.fetch({ id: 'a' }, { fresh: true });- calls[1].resolve(['newer']);- await newer;- // The older request is still pending: its retirement must survive pruning.- expect(slice.debugRetiredRequests()).toBe(1);-- calls[0].resolve(['older']);- await expect(older).resolves.toMatchObject({ applied: false });- expect(store.getState().lists.a).toEqual(['newer']);- expect(slice.debugRetiredRequests()).toBe(0);- });-- it('drops an older response once a newer one for the entry has applied', async () => {- const { calls, fetcher } = deferredFetcher();- const { slice, store } = setup({ fetcher });-- const older = slice.fetch({ id: 'a' });- const newer = slice.fetch({ id: 'a' }, { fresh: true });- calls[1].resolve(['newer']);- await newer;- calls[0].resolve(['older']);-- await expect(older).resolves.toMatchObject({ applied: false });- expect(store.getState().lists.a).toEqual(['newer']);- });-- it('seeds the driver cache under the sync key only while no useSync request is in flight', async () => {- const seed = vi.fn();- const driver: ReplicaSyncDriver = { ...testDriver, seed };- const { slice } = setup({ driver });-- await slice.fetch({ id: 'a' });-- expect(seed).toHaveBeenCalledWith(- replicaKeys.sync('fetchList', 1, 'user-1:personal', 'a', { id: 'a' }),- ['server'],- );-- const { calls, fetcher } = deferredFetcher();- const joined = setup({ driver, fetcher });- seed.mockClear();- renderHook(() => joined.slice.useSync({ id: 'b' }), { wrapper });- await waitFor(() => expect(fetcher).toHaveBeenCalledTimes(1));- const pending = joined.slice.fetch({ id: 'b' });- await act(async () => calls[0].resolve(['server']));- await pending;- // The mounted query fills its own cache entry.- expect(seed).not.toHaveBeenCalled();- });-- it('works with a driver that has no cache of its own', async () => {- const driver: ReplicaSyncDriver = {- revalidate: vi.fn(async () => undefined),- useQuery: vi.fn(() => ({ isValidating: false, mutate: vi.fn() })),- };- const { slice, store } = setup({ driver });-- await expect(slice.fetch({ id: 'a' })).resolves.toMatchObject({ applied: true });- expect(store.getState().lists.a).toEqual(['server']);- });-});diff --git a/packages/replica/src/zustand/createReplicaSlice.invalidation.test.ts b/packages/replica/src/zustand/createReplicaSlice.invalidation.test.tsdeleted file mode 100644index 2d60198d2a3..00000000000--- a/packages/replica/src/zustand/createReplicaSlice.invalidation.test.ts+++ /dev/null@@ -1,494 +0,0 @@-/**- * @vitest-environment happy-dom- */-import { act, renderHook, waitFor } from '@testing-library/react';-import { beforeEach, describe, expect, it, vi } from 'vitest';-import { createStore } from 'zustand/vanilla';--import { testDriver as driver } from '../../tests/testDriver';-import { defineReplica } from '../core/defineReplica';-import { REPLICA_INDEX_KEY } from '../core/engine';-import { createReplicaState } from '../core/reducer';-import type { ReplicaRow, ReplicaStorage } from '../core/types';-import { createReplicaSlice, recordLens } from './createReplicaSlice';-import type { TestState } from './testUtils';-import { createMemoryStorage, resetScopeState, scope, scopeState, setup, wrapper } from './testUtils';--beforeEach(resetScopeState);--describe('createReplicaSlice', () => {- describe('remove', () => {- it('does not let an in-flight response resurrect a removed entry', async () => {- let resolveFetch!: (value: string[]) => void;- const fetcher = vi.fn(() => new Promise<string[]>((resolve) => (resolveFetch = resolve)));- const { slice, store } = setup({ fetcher });-- renderHook(() => slice.useSync({ id: 'a' }), { wrapper });- await waitFor(() => expect(fetcher).toHaveBeenCalled());-- // The entry is invalidated while its own request is still in flight.- act(() => {- slice.remove('a');- });- await act(async () => resolveFetch(['late']));-- expect(store.getState().lists.a).toBeUndefined();- });- });-- describe('persisted index', () => {- it('removes a key this instance never wrote from the stored index', async () => {- const storage = createMemoryStorage();- // An earlier session persisted this row and listed it in the index. This- // instance has no memory of the key β the eviction / invalidation case- // where the index write must still reach storage.- storage.rows.set('user-1:personal|a', { data: ['stale'], updatedAt: 1 });- storage.indexRows.set('user-1:personal', { data: ['a'], updatedAt: 1 });- const { slice } = setup({ storage });-- act(() => slice.remove('a'));-- await waitFor(() => expect(storage.rows.get('user-1:personal|a')).toBeUndefined());- await waitFor(() => expect(storage.indexRows.get('user-1:personal')?.data).toEqual([]));- });- });-- describe('invalidation', () => {- interface QueryParams {- id: string;- q?: string;- }- /** A resource whose rows are persisted per query (`a`, `a?{"q":"x"}` β¦). */- const setupQueried = ({- driver: queryDriver = driver,- storage = createMemoryStorage(),- }: {- driver?: Parameters<typeof createReplicaSlice>[1]['driver'];- storage?: ReturnType<typeof createMemoryStorage>;- } = {}) => {- const resource = defineReplica<QueryParams, string[]>({- fetcher: async () => ['server'],- key: ({ id }) => id,- name: 'queriedList',- query: ({ q }) => ({ q }),- scope,- storage: storage.storage,- version: 1,- });- const store = createStore<TestState>()(() => ({- lists: {},- listsReplica: createReplicaState(),- }));- const slice = createReplicaSlice<TestState, QueryParams, string[]>(resource, {- driver: queryDriver,- get: store.getState,- set: (partial) => store.setState(partial),- stateKey: 'listsReplica',- view: recordLens('lists'),- });- return { resource, slice, storage, store };- };- const row = (resource: { storageKey: (params: QueryParams) => string }, params: QueryParams) =>- `user-1:personal|${resource.storageKey(params)}`;-- /** Persist `a` (unfiltered + filtered) and `ab` in one session. */- const persistVariants = async () => {- const first = setupQueried();- act(() => {- first.slice.replace({ id: 'a' }, ['a-all']);- first.slice.replace({ id: 'a', q: 'x' }, ['a-x']);- first.slice.replace({ id: 'ab' }, ['ab-all']);- });- await waitFor(() => expect(first.storage.rows.size).toBe(3));- return first;- };-- it('remove drops every persisted query variant of the key, not only the one in memory', async () => {- const { resource, slice, storage } = await persistVariants();-- // Memory holds the filtered query; the unfiltered row was persisted earlier.- act(() => slice.remove('a'));-- await waitFor(() => {- expect(storage.rows.has(row(resource, { id: 'a' }))).toBe(false);- expect(storage.rows.has(row(resource, { id: 'a', q: 'x' }))).toBe(false);- });- // Another key that merely shares the prefix is untouched.- expect(storage.rows.get(row(resource, { id: 'ab' }))?.data).toEqual(['ab-all']);- });-- it('remove drops variants persisted by an earlier session, through the index', async () => {- const first = await persistVariants();- // Reload: memory is empty, only the persisted index knows the variants.- const { resource, slice, storage, store } = setupQueried({ storage: first.storage });-- act(() => slice.remove('a'));-- await waitFor(() => {- expect(storage.rows.has(row(resource, { id: 'a' }))).toBe(false);- expect(storage.rows.has(row(resource, { id: 'a', q: 'x' }))).toBe(false);- });- // No variant of the removed key hydrates.- await act(async () => {- expect(await slice.hydrate({ id: 'a', q: 'x' })).toBe(false);- });- expect(store.getState().lists.a).toBeUndefined();- });-- it('an off-scope purge drops every query variant of its scope', async () => {- const { resource, slice, storage } = await persistVariants();-- scopeState.current = 'user-2:personal';- act(() => slice.remove('a', 'user-1:personal'));-- await waitFor(() => {- expect(storage.rows.has(row(resource, { id: 'a' }))).toBe(false);- expect(storage.rows.has(row(resource, { id: 'a', q: 'x' }))).toBe(false);- });- });-- /** Make storage reject the first delete of `queryKey` (a closed IndexedDB). */- const failFirstDelete = (storage: ReturnType<typeof createMemoryStorage>, queryKey: string) => {- const original = storage.storage.remove;- let failed = false;- storage.storage.remove = async (key) => {- if (key.queryKey === queryKey && !failed) {- failed = true;- throw new Error('IndexedDB delete failed');- }- return original(key);- };- };-- it('keeps a variant whose delete failed indexed, so a later remove retries it', async () => {- const { resource, slice, storage } = await persistVariants();- const filtered = row(resource, { id: 'a', q: 'x' });- failFirstDelete(storage, resource.storageKey({ id: 'a', q: 'x' }));- // Memory holds another variant, so the failing row is found through the index.- act(() => slice.replace({ id: 'a' }, ['a-all']));-- act(() => slice.remove('a'));- await waitFor(() => expect(storage.rows.has(row(resource, { id: 'a' }))).toBe(false));- await new Promise((resolve) => setTimeout(resolve, 10));- expect(storage.rows.has(filtered)).toBe(true);-- // The next removal still knows about the failed row and retries it.- act(() => slice.remove('a'));- await waitFor(() => expect(storage.rows.has(filtered)).toBe(false));- });-- it('keeps a row whose delete failed indexed, so a later clear retries it', async () => {- const { resource, slice, storage } = await persistVariants();- failFirstDelete(storage, resource.storageKey({ id: 'ab' }));-- let purge!: Promise<boolean>;- act(() => {- purge = slice.clear();- });- expect(await purge).toBe(false);- expect([...storage.rows.keys()]).toEqual([row(resource, { id: 'ab' })]);-- act(() => {- purge = slice.clear();- });- expect(await purge).toBe(true);- expect(storage.rows.size).toBe(0);- });-- /**- * Storage whose index read fails the way the app adapters do: `get`- * swallows it into a miss, only `getStrict` reports it.- */- const failIndexReads = (storage: ReturnType<typeof createMemoryStorage>) => {- const state = { failing: true };- const original = storage.storage.get;- storage.storage.get = async (key) =>- key.queryKey === REPLICA_INDEX_KEY && state.failing ? undefined : original(key);- storage.storage.getStrict = async (key) => {- if (key.queryKey === REPLICA_INDEX_KEY && state.failing)- throw new Error('IndexedDB read failed');- return original(key);- };- return state;- };-- it('reports a clear as failed when the index cannot be read, and a later clear retries', async () => {- const first = await persistVariants();- // Reload: only the persisted index knows the earlier session's rows.- const { slice, storage, store } = setupQueried({ storage: first.storage });- const index = failIndexReads(storage);-- let purge!: Promise<boolean>;- act(() => {- purge = slice.clear();- });- expect(await purge).toBe(false);- expect(storage.rows.size).toBe(3);- // Hydration stays off while the wipe is incomplete.- await act(async () => {- expect(await slice.hydrate({ id: 'a' })).toBe(false);- });- expect(store.getState().lists.a).toBeUndefined();-- index.failing = false;- act(() => {- purge = slice.clear();- });- expect(await purge).toBe(true);- expect(storage.rows.size).toBe(0);- });-- it('keeps a removal unpurged when the index cannot be read, so it retries', async () => {- const first = await persistVariants();- const { resource, slice, storage } = setupQueried({ storage: first.storage });- const filtered = row(resource, { id: 'a', q: 'x' });- const index = failIndexReads(storage);-- // Memory is empty, so every variant is known only through the index.- act(() => slice.remove('a'));- await new Promise((resolve) => setTimeout(resolve, 10));- expect(storage.rows.has(row(resource, { id: 'a' }))).toBe(true);- expect(storage.rows.has(filtered)).toBe(true);-- index.failing = false;- act(() => slice.remove('a'));- await waitFor(() => {- expect(storage.rows.has(row(resource, { id: 'a' }))).toBe(false);- expect(storage.rows.has(filtered)).toBe(false);- });- });-- it('never mistakes a plain key containing `?` for a query variant', async () => {- const storage = createMemoryStorage();- const { slice } = setup({ storage });- act(() => {- slice.replace({ id: 'foo' }, ['foo']);- slice.replace({ id: 'foo?bar' }, ['foo?bar']);- });- await waitFor(() => expect(storage.rows.size).toBe(2));-- act(() => slice.remove('foo'));-- await waitFor(() => expect(storage.rows.has('user-1:personal|foo')).toBe(false));- await new Promise((resolve) => setTimeout(resolve, 10));- expect(storage.rows.get('user-1:personal|foo?bar')?.data).toEqual(['foo?bar']);- });-- it('cleans variants listed by an index written in the existing flat format', async () => {- const storage = createMemoryStorage();- // Rows and index as an earlier release persisted them on a device.- for (const queryKey of ['foo?{}', 'foo?{"q":"x"}', 'foo?bar?{}'])- storage.rows.set(`user-1:personal|${queryKey}`, { data: [queryKey], updatedAt: 1 });- storage.indexRows.set('user-1:personal', {- data: ['foo?{}', 'foo?{"q":"x"}', 'foo?bar?{}'],- updatedAt: 1,- });- const { slice } = setupQueried({ storage });-- act(() => slice.remove('foo'));-- await waitFor(() => expect([...storage.rows.keys()]).toEqual(['user-1:personal|foo?bar?{}']));- await waitFor(() =>- expect(storage.indexRows.get('user-1:personal')?.data).toEqual(['foo?bar?{}']),- );- });-- it('calls a class-based storage with its receiver on every index pass', async () => {- /** Prototype methods that rely on `this`, like most storage classes. */- class ClassStorage implements ReplicaStorage<string[]> {- rows = new Map<string, ReplicaRow<string[]>>();- #id({ queryKey, scope }: { queryKey: string; scope: string }) {- return `${scope}|${queryKey}`;- }- async get(key: { queryKey: string; scope: string }) {- return this.rows.get(this.#id(key));- }- async getStrict(key: { queryKey: string; scope: string }) {- return this.rows.get(this.#id(key));- }- async remove(key: { queryKey: string; scope: string }) {- this.rows.delete(this.#id(key));- }- async set(key: { queryKey: string; scope: string }, row: ReplicaRow<string[]>) {- this.rows.set(this.#id(key), row);- }- }- const backing = new ClassStorage();- const storage = { ...createMemoryStorage(), storage: backing };- const dataRows = () =>- [...backing.rows.keys()].filter((key) => !key.endsWith(REPLICA_INDEX_KEY));- const first = setupQueried({ storage });- act(() => {- first.slice.replace({ id: 'a' }, ['a-all']);- first.slice.replace({ id: 'a', q: 'x' }, ['a-x']);- first.slice.replace({ id: 'b' }, ['b-all']);- });- await waitFor(() => expect(dataRows()).toHaveLength(3));- const errors = vi.spyOn(console, 'error').mockImplementation(() => {});-- // A fresh engine only finds the rows through the index.- const { slice } = setupQueried({ storage });- slice.updateEntity('x', (item) => item);- act(() => slice.remove('a'));- await waitFor(() => expect(dataRows()).toEqual(['user-1:personal|b?{}']));- expect(await slice.clear()).toBe(true);- expect(dataRows()).toEqual([]);- expect(errors).not.toHaveBeenCalled();- errors.mockRestore();- });-- it('drops the request record of a failure even without an onError', async () => {- const requests: { fetch: () => Promise<unknown>; onError?: (error: unknown) => void }[] = [];- const useQuery = vi.fn((key: any, fetch: () => Promise<unknown>, options: any) => {- if (key?.[0] === 'replica:sync') requests.push({ fetch, onError: options.onError });- return { isValidating: false, mutate: vi.fn() };- });- const { slice } = setupQueried({ driver: { revalidate: vi.fn(), useQuery } });- const deletes = vi.spyOn(Map.prototype, 'delete');-- const { rerender } = renderHook((props: QueryParams) => slice.useSync(props), {- initialProps: { id: 'k1' } as QueryParams,- });- for (const id of ['k1', 'k2', 'k3']) {- rerender({ id });- const request = requests.at(-1)!;- await request.fetch();- act(() => request.onError!(new Error('forbidden')));- }-- const dropped = deletes.mock.calls.map(([id]) => String(id));- for (const id of ['k1', 'k2', 'k3'])- expect(- dropped.some((record) => record.includes('replica:sync') && record.includes(id)),- ).toBe(true);- deletes.mockRestore();- });-- it('clear wipes memory, every persisted row and the index of the active scope', async () => {- const first = await persistVariants();- // A later session loads only one entry; the rest is known only to the index.- const { slice, storage, store } = setupQueried({ storage: first.storage });- act(() => slice.replace({ id: 'b' }, ['b-all']));- storage.rows.set('user-2:personal|a', { data: ['other-user'], updatedAt: 1 });-- let purge!: Promise<boolean>;- act(() => {- purge = slice.clear();- });- expect(store.getState().lists).toEqual({});- expect(store.getState().listsReplica.entries).toEqual({});-- await act(async () => {- expect(await purge).toBe(true);- });- // Only the other identity's row survives; the index lists nothing.- expect([...storage.rows.keys()]).toEqual(['user-2:personal|a']);- await waitFor(() => expect(storage.indexRows.get('user-1:personal')?.data).toEqual([]));- await act(async () => {- expect(await slice.hydrate({ id: 'a' })).toBe(false);- });- });-- it('clear refuses a hydrate that was already reading', async () => {- const storage = createMemoryStorage();- storage.rows.set('user-1:personal|a', { data: ['wiped'], updatedAt: 1 });- const originalGet = storage.storage.get;- let release!: () => void;- const held = new Promise<void>((resolve) => (release = resolve));- storage.storage.get = async (key) => {- const value = await originalGet(key);- if (key.queryKey === 'a') await held;- return value;- };- const { slice, store } = setup({ storage });-- let hydration!: Promise<boolean>;- await act(async () => {- hydration = slice.hydrate({ id: 'a' });- });- act(() => {- void slice.clear();- });- await act(async () => {- release();- expect(await hydration).toBe(false);- });- expect(store.getState().lists.a).toBeUndefined();- });-- it('clear discards a head response that started before it, and applies one started after', () => {- const requests: { fetch: () => Promise<unknown>; onSuccess: (data: string[]) => void }[] = [];- const useQuery = vi.fn((key: any, fetch: () => Promise<unknown>, options: any) => {- if (key?.[0] === 'replica:sync') requests.push({ fetch, onSuccess: options.onSuccess });- return { isValidating: false, mutate: vi.fn() };- });- const { slice, store } = setupQueried({ driver: { revalidate: vi.fn(), useQuery } });- renderHook(() => slice.useSync({ id: 'a' }));- const request = requests.at(-1)!;-- // The request is issued, then the resource is wiped before it settles.- void request.fetch();- act(() => {- void slice.clear();- });- act(() => request.onSuccess(['before-clear']));- expect(store.getState().lists.a).toBeUndefined();-- // A request issued after the clear is ordinary.- void request.fetch();- act(() => request.onSuccess(['after-clear']));- expect(store.getState().lists.a).toEqual(['after-clear']);- });-- it('a clear whose purge could not run keeps refusing hydration', async () => {- const storage = createMemoryStorage();- storage.rows.set('user-1:personal|a', { data: ['stale'], updatedAt: 1 });- const { slice, store } = setup({ storage });-- // Identity is not resolved yet, so the row deletes are refused.- scopeState.trusted = false;- let purge!: Promise<boolean>;- act(() => {- purge = slice.clear();- });- expect(await purge).toBe(false);- scopeState.trusted = true;-- await act(async () => {- expect(await slice.hydrate({ id: 'a' })).toBe(false);- });- expect(store.getState().lists.a).toBeUndefined();- });-- it('does not surface the error of a query the entry has moved past', () => {- const requests: { onError: (error: unknown) => void; params: { q?: string } }[] = [];- const useQuery = vi.fn((key: any, _fetch: unknown, options: any) => {- if (key?.[0] === 'replica:sync')- requests.push({ onError: options.onError, params: key.at(-1) });- return { isValidating: false, mutate: vi.fn() };- });- const { slice } = setupQueried({ driver: { revalidate: vi.fn(), useQuery } });- const onError = vi.fn();-- const { rerender } = renderHook((props: QueryParams) => slice.useSync(props, { onError }), {- initialProps: { id: 'a' } as QueryParams,- });- rerender({ id: 'a', q: 'b' });-- const base = requests.find((request) => request.params.q === undefined)!;- const search = requests.find((request) => request.params.q === 'b')!;-- // The superseded query fails late: the search on screen must not see it.- act(() => base.onError(new Error('stale')));- expect(onError).not.toHaveBeenCalled();-- const failure = new Error('search failed');- act(() => search.onError(failure));- expect(onError).toHaveBeenCalledWith(failure, {- isActive: true,- key: 'a',- scope: 'user-1:personal',- });- });- });-});diff --git a/packages/replica/src/zustand/createReplicaSlice.responses.test.ts b/packages/replica/src/zustand/createReplicaSlice.responses.test.tsdeleted file mode 100644index d54ef428de5..00000000000--- a/packages/replica/src/zustand/createReplicaSlice.responses.test.ts+++ /dev/null@@ -1,227 +0,0 @@-/**- * @vitest-environment happy-dom- */-import { act, renderHook } from '@testing-library/react';-import { beforeEach, describe, expect, it, vi } from 'vitest';-import { createStore } from 'zustand/vanilla';--import { testDriver as driver } from '../../tests/testDriver';-import { defineReplica } from '../core/defineReplica';-import { singleEntity } from '../core/entityAdapters';-import { createReplicaState } from '../core/reducer';-import type { ReplicaState } from '../core/types';-import { createReplicaSlice, recordLens } from './createReplicaSlice';-import type { TestState } from './testUtils';-import { resetScopeState, scope, scopeState } from './testUtils';--beforeEach(resetScopeState);--describe('createReplicaSlice', () => {- describe('missing responses', () => {- it('applies a response the resource marks as missing as an explicit removal', () => {- // A nullable detail (e.g. the acceptance attached to a subject): the- // server answering "none" must clear a previously cached value, not let- // the merge fall back to it.- type NullableState = {- notes: Record<string, string[] | null>;- notesReplica: ReplicaState<string[] | null>;- };- const resource = defineReplica<{ id: string }, string[] | null>({- key: ({ id }) => id,- name: 'nullableNote',- scope,- version: 1,- });- const store = createStore<NullableState>()(() => ({- notes: {},- notesReplica: createReplicaState(),- }));- const slice = createReplicaSlice<NullableState, { id: string }, string[] | null>(resource, {- driver,- get: store.getState,- isMissing: (note) => note === null,- set: (partial) => store.setState(partial),- stateKey: 'notesReplica',- view: recordLens('notes'),- });-- act(() => slice.replace({ id: 'a' }, ['kept']));- expect(store.getState().notes.a).toEqual(['kept']);-- act(() => slice.replace({ id: 'a' }, null));- expect(store.getState().notes.a).toBeUndefined();- expect(store.getState().notesReplica.entries.a).toBeUndefined();- });-- it('treats a repeated missing response as a no-op', () => {- type NullableState = {- notes: Record<string, string[] | null>;- notesReplica: ReplicaState<string[] | null>;- };- const resource = defineReplica<{ id: string }, string[] | null>({- key: ({ id }) => id,- name: 'nullableNoteRepeat',- scope,- version: 1,- });- const store = createStore<NullableState>()(() => ({- notes: {},- notesReplica: createReplicaState(),- }));- const slice = createReplicaSlice<NullableState, { id: string }, string[] | null>(resource, {- driver,- get: store.getState,- isMissing: (note) => note === null,- set: (partial) => store.setState(partial),- stateKey: 'notesReplica',- view: recordLens('notes'),- });-- act(() => slice.replace({ id: 'a' }, ['kept']));- // The first "missing" drops the entry and clears stale storageβ¦- expect(slice.replace({ id: 'a' }, null)).toBe(true);- // β¦a poll that still answers "missing" must not re-emit the removal.- expect(slice.replace({ id: 'a' }, null)).toBe(false);- expect(store.getState().notes.a).toBeUndefined();- });- });-- describe('late scoped responses', () => {- it('does not replay a response that lands after a scope switch', () => {- // A driver that settles each request through its own callback, so the- // test chooses the moment the response arrives.- let settle!: (data: string[]) => void;- const useQuery = vi.fn((key: any, _fetcher: unknown, options: any) => {- if (key !== null) settle = options.onSuccess;- return { isValidating: false, mutate: vi.fn() };- });- const resource = defineReplica<{ id: string }, string[]>({- fetcher: async () => ['server'],- key: ({ id }) => id,- name: 'lateScopeResponse',- scope,- version: 1,- });- const store = createStore<TestState>()(() => ({- lists: {},- listsReplica: createReplicaState(),- }));- const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {- driver: { revalidate: vi.fn(), useQuery },- get: store.getState,- set: (partial) => store.setState(partial),- stateKey: 'listsReplica',- view: recordLens('lists'),- });-- const onSuccess = vi.fn();- renderHook(() => slice.useSync({ id: 'a' }, { onSuccess }));-- // The identity switches while the request is in flight; the response- // belongs to the previous scope and `replace` rejects it.- scopeState.current = 'user-2:personal';- act(() => settle(['late-user-1']));-- expect(store.getState().lists.a).toBeUndefined();- expect(onSuccess).not.toHaveBeenCalled();- });-- // An entity removed while its entry's request is in flight (deleted, pruned- // by an authoritative parent list) must not be recreated by that response.- // `slice.remove` drops the head-query marker, but an entity removal goes- // straight through the engine, so the request generation must catch it.- it('drops a response whose request started before the entity was removed', () => {- interface Item {- id: string;- title: string;- }- interface ItemState {- items: Record<string, Item>;- itemsReplica: ReplicaState<Item>;- }- let settle!: (data: Item) => void;- const useQuery = vi.fn((key: any, fetcher: () => unknown, options: any) => {- if (key !== null) {- settle = options.onSuccess;- void fetcher();- }- return { isValidating: false, mutate: vi.fn() };- });- const resource = defineReplica<{ id: string }, Item>({- fetcher: () => new Promise<Item>(() => {}),- key: ({ id }) => id,- name: 'removedEntityInFlight',- scope,- version: 1,- });- const store = createStore<ItemState>()(() => ({- items: {},- itemsReplica: createReplicaState(),- }));- const slice = createReplicaSlice<ItemState, { id: string }, Item>(resource, {- driver: { revalidate: vi.fn(), useQuery },- entity: singleEntity<Item>((item) => item.id),- get: store.getState,- set: (partial) => store.setState(partial),- stateKey: 'itemsReplica',- view: recordLens('items'),- });- act(() => slice.replace({ id: 'a' }, { id: 'a', title: 'first' }));-- const onSuccess = vi.fn();- renderHook(() => slice.useSync({ id: 'a' }, { onSuccess }));- act(() => slice.removeEntity('a'));- expect(store.getState().items.a).toBeUndefined();-- act(() => settle({ id: 'a', title: 'stale' }));- expect(store.getState().items.a).toBeUndefined();- expect(onSuccess).not.toHaveBeenCalled();- });-- // a β b while a's request is in flight: a's late response still fills its- // own cache entry, but its success side effects act on the CURRENT view, so- // they must not re-adopt `a` while the hook shows `b`.- it('does not replay a response for a key the hook has moved past', () => {- let settle!: (data: string[]) => void;- const useQuery = vi.fn((key: any, _fetcher: unknown, options: any) => {- if (key !== null) settle = options.onSuccess;- return { isValidating: false, mutate: vi.fn() };- });- const resource = defineReplica<{ id: string }, string[]>({- fetcher: async ({ id }) => [id],- key: ({ id }) => id,- name: 'lateKeyResponse',- scope,- version: 1,- });- const store = createStore<TestState>()(() => ({- lists: {},- listsReplica: createReplicaState(),- }));- const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {- driver: { revalidate: vi.fn(), useQuery },- get: store.getState,- set: (partial) => store.setState(partial),- stateKey: 'listsReplica',- view: recordLens('lists'),- });-- const onSuccess = vi.fn();- const { rerender } = renderHook(({ id }) => slice.useSync({ id }, { onSuccess }), {- initialProps: { id: 'a' },- });- const settleA = settle;-- rerender({ id: 'b' });- const settleB = settle;- act(() => settleA(['late-a']));-- expect(store.getState().lists.a).toEqual(['late-a']);- expect(onSuccess).not.toHaveBeenCalled();-- act(() => settleB(['b']));- expect(onSuccess).toHaveBeenCalledTimes(1);- expect(onSuccess).toHaveBeenCalledWith(['b']);- });- });-});diff --git a/packages/replica/src/zustand/createReplicaSlice.scope.test.ts b/packages/replica/src/zustand/createReplicaSlice.scope.test.tsdeleted file mode 100644index 2fc0bde4393..00000000000--- a/packages/replica/src/zustand/createReplicaSlice.scope.test.ts+++ /dev/null@@ -1,135 +0,0 @@-/**- * @vitest-environment happy-dom- */-import { act, renderHook, waitFor } from '@testing-library/react';-import { beforeEach, describe, expect, it, vi } from 'vitest';--import { createMemoryStorage, resetScopeState, scopeState, setup, wrapper } from './testUtils';--beforeEach(resetScopeState);--describe('createReplicaSlice', () => {- describe('scope isolation', () => {- it('clears the previous identity and drops its late results', async () => {- const { slice, store, storage } = setup();- act(() => {- slice.replace({ id: 'a' }, ['user-1-data']);- });- expect(store.getState().lists.a).toEqual(['user-1-data']);-- scopeState.current = 'user-2:personal';- // A response that was in flight for user 1 lands after the switch.- act(() => {- slice.replace({ id: 'a' }, ['late-user-1'], 'user-1:personal');- });- expect(store.getState().lists.a).toEqual(['user-1-data']);-- // The first action under the new identity resets memory.- act(() => {- slice.replace({ id: 'b' }, ['user-2-data']);- });- expect(store.getState().lists).toEqual({ b: ['user-2-data'] });- expect(store.getState().listsReplica.scope).toBe('user-2:personal');-- await waitFor(() => expect(storage.rows.size).toBe(2));- expect(storage.rows.get('user-1:personal|a')?.data).toEqual(['user-1-data']);- expect(storage.rows.get('user-2:personal|b')?.data).toEqual(['user-2-data']);- });-- it('useSync clears the previous identity even when the new scope has nothing to hydrate', async () => {- const fetcher = vi.fn(() => new Promise<string[]>(() => {}));- const { slice, store } = setup({ fetcher });- act(() => {- slice.replace({ id: 'a' }, ['user-1-data']);- });-- scopeState.current = 'user-2:personal';- const { result } = renderHook(() => slice.useSync({ id: 'a' }), { wrapper });-- await waitFor(() => expect(result.current.isHydrated).toBe(true));- expect(store.getState().lists).toEqual({});- expect(store.getState().listsReplica.scope).toBe('user-2:personal');- });-- it('hydrates only the active scope partition', async () => {- const storage = createMemoryStorage();- storage.rows.set('user-2:personal|a', { data: ['someone-else'], updatedAt: 1 });- const { slice, store } = setup({ storage });-- await act(async () => {- await slice.hydrate({ id: 'a' });- });-- expect(store.getState().lists.a).toBeUndefined();- });-- it('does not hydrate the persisted projection when the runtime opts out', async () => {- // An identity-less runtime (e.g. the public Workbench) can only guess the- // scope, so it must not read another session's rows back into memory.- const storage = createMemoryStorage();- storage.rows.set('user-1:personal|a', { data: ['someone-elses'], updatedAt: 1 });- scopeState.canHydrate = false;- const { slice, store } = setup({ storage });-- await act(async () => {- await slice.hydrate({ id: 'a' });- });-- expect(store.getState().lists.a).toBeUndefined();- expect(store.getState().listsReplica.entries.a).toBeUndefined();- });-- it('never persists while the scope is untrusted', async () => {- scopeState.trusted = false;- const { slice, storage } = setup();- act(() => {- slice.replace({ id: 'a' }, ['server']);- });- await new Promise((resolve) => setTimeout(resolve, 10));- expect(storage.writes).toEqual([]);- });-- it('retries a removal whose storage delete failed, instead of treating it as purged', async () => {- const storage = createMemoryStorage();- storage.rows.set('user-1:personal|a', { data: ['stale'], updatedAt: 1 });- const { slice } = setup({ storage });-- const original = storage.storage.remove;- let attempts = 0;- storage.storage.remove = async (key) => {- attempts += 1;- if (attempts === 1) throw new Error('IndexedDB delete failed');- return original(key);- };-- // The first delete is rejected by storage: the guard is armed, but the row- // is still on disk and must NOT be treated as purged.- act(() => slice.remove('a'));- await new Promise((resolve) => setTimeout(resolve, 20));- expect(storage.rows.get('user-1:personal|a')).toBeDefined();-- // A later terminal answer must retry the delete rather than no-op.- act(() => slice.remove('a'));- await waitFor(() => expect(storage.rows.get('user-1:personal|a')).toBeUndefined());- expect(attempts).toBeGreaterThanOrEqual(2);- });-- it('retries the storage delete of a removal made while the scope was untrusted', async () => {- const storage = createMemoryStorage();- storage.rows.set('user-1:personal|a', { data: ['stale'], updatedAt: 1 });- const { slice } = setup({ storage });-- // Cold boot: identity is not resolved, so writes are refused and the- // delete never reaches storage β the hydration guard is armed all the same.- scopeState.trusted = false;- act(() => slice.remove('a'));- await new Promise((resolve) => setTimeout(resolve, 10));- expect(storage.rows.get('user-1:personal|a')).toBeDefined();-- // Identity resolves: the next removal must clear the row, not no-op.- scopeState.trusted = true;- act(() => slice.remove('a'));- await waitFor(() => expect(storage.rows.get('user-1:personal|a')).toBeUndefined());- });- });-});diff --git a/packages/replica/src/zustand/createReplicaSlice.ts b/packages/replica/src/zustand/createReplicaSlice.tsdeleted file mode 100644index 9deb0903328..00000000000--- a/packages/replica/src/zustand/createReplicaSlice.ts+++ /dev/null@@ -1,945 +0,0 @@-import { useEffect, useLayoutEffect, useRef } from 'react';--import { stableQueryKey } from '../core/defineReplica';-import { createReplicaEngine, type ReplicaEngineOptions } from '../core/engine';-import { isReplicaSyncKey, replicaKeys } from '../core/keys';-import type { ReplicaPagedData } from '../core/paging';-import type { ReplicaViewWrite } from '../core/reducer';-import { DEFAULT_REMOVAL_TOMBSTONE_LIMIT } from '../core/tombstones';-import type { ReplicaResource, ReplicaState } from '../core/types';-import type { ReplicaSyncDriver, ReplicaSyncSchedule } from './driver';--/** Zustand `setState`, with the devtools action label. */-type Setter<TStore> = (partial: Partial<TStore>, replace?: false, action?: any) => void;--/**- * One `key` write in a batched lens update (see {@link ReplicaLens.setMany}).- */-export interface ReplicaViewSet<TData> {- data: TData | undefined;- key: string;-}--/**- * Where the materialized value lives in the domain store. Selectors keep- * reading this location; the slice is the only writer.- */-export interface ReplicaLens<TStore, TData> {- clear: (state: TStore) => Partial<TStore>;- get: (state: TStore, key: string) => TData | undefined;- /** Enumerate loaded keys (needed for entity propagation). */- keys?: (state: TStore) => string[];- set: (state: TStore, key: string, data: TData | undefined) => Partial<TStore>;- /**- * Apply several key writes in one pass β one clone of the backing field- * instead of one per key. Optional: the slice falls back to repeated `set`- * when a lens does not implement it.- */- setMany?: (state: TStore, entries: ReplicaViewSet<TData>[]) => Partial<TStore>;-}--export interface CreateReplicaSliceOptions<TStore, TParams, TData, TFetched> extends Omit<- ReplicaEngineOptions<TParams, TData, TFetched>,- 'port' | 'revalidate'-> {- /** Query cache that schedules fetches (see `createSWRDriver`). */- driver: ReplicaSyncDriver;- /**- * Side effects of the resource itself, run by every head response β a- * mounted `useSync` and an imperative `fetch` alike β after the response is- * folded in (see {@link ReplicaEffects}).- */- effects?: ReplicaEffects<TParams, TFetched>;- get: () => TStore;- set: Setter<TStore>;- /** Store field holding the {@link ReplicaState} bookkeeping slot. */- stateKey: keyof TStore & string;- /** Where the view lives in the store; `recordLens(field)` covers `Record<key, TData>`. */- view: ReplicaLens<TStore, TData>;-}--/**- * What a failed sync read was captured under. `scope` is the cache scope active- * when the request was issued, which may differ from the scope active when the- * callback runs (an identity / workspace switch in between).- */-export interface ReplicaSyncErrorContext {- /**- * Whether the captured `scope` is still the one the store is on. A failure- * with `isActive: false` belongs to an identity / workspace the store has- * left: surface it on the *current* view only when this is true, while still- * using the captured `key` / `scope` to clean up the scope it came from.- */- isActive: boolean;- /** The entry key the read was for; `undefined` for a disabled read. */- key: string | undefined;- /** The cache scope the read was captured under. */- scope: string;-}--/** Where a settled head response was captured, for {@link ReplicaEffects}. */-export interface ReplicaSettleContext {- key: string;- /** The cache scope the request was captured under (the active one, except for `onPurge`). */- scope: string;- /** Which path requested it: a mounted `useSync`, or `slice.fetch`. */- source: 'fetch' | 'sync';-}--/**- * Resource-level side effects of head responses. Unlike `useSync`'s per-call- * `onSuccess` / `onError` (UI callbacks of one mounted view), these run for- * every response the resource settles, whichever path requested it β so a- * store that fetches while no view is mounted keeps the same side effects.- *- * They run only for a response that passed every guard (clear, removal, active- * query, a newer response already applied) and, for `onApplied` / `onMissing`,- * only when its captured scope is still the active one.- */-export interface ReplicaEffects<TParams, TFetched> {- /**- * A response was folded into the active scope (`prepareHead` kept it and it- * is not a terminal absence). Runs even when the value did not change.- */- onApplied?: (data: TFetched, params: TParams, context: ReplicaSettleContext) => void;- /**- * A failed head read. Like `useSync`'s `onError`, it is forwarded off-scope- * too, with `isActive: false`: use the captured key / scope to clean up that- * scope, and touch the view on screen only when `isActive`.- */- onError?: (error: unknown, params: TParams, context: ReplicaSyncErrorContext) => void;- /**- * The response was a terminal absence (`isMissing`) and the entry was- * removed from the active scope. An absence captured under a scope the store- * has left purges that scope's row and runs `onPurge` instead.- */- onMissing?: (params: TParams, context: ReplicaSettleContext) => void;- /**- * A terminal absence captured under a scope the store has since left. The- * entry's row in that scope is already purged; purge what other resources- * keep of it there (a linked list row). Never touch the view on screen.- */- onPurge?: (params: TParams, context: ReplicaSettleContext) => void;- /**- * Every successful response, including one the guards discard (cleared or- * removed entry, superseded query, off-scope) and one `prepareHead` drops.- * Use it for per-request bookkeeping that must be released even when the- * response is never folded. Not called for errors.- */- onSettled?: (data: TFetched, params: TParams, context: ReplicaSettleContext) => void;-}--export interface ReplicaFetchOptions {- /**- * Start a new request even when one for the same entry is in flight, and- * retire every request started before it: a late response of an older one- * is dropped instead of applied. Use it for refreshes after a mutation,- * where an in-flight request may hold the pre-mutation value. By default- * `fetch` joins the request in flight (a `useSync` one or another `fetch`).- */- fresh?: boolean;- /**- * The cache scope the fetch belongs to, captured by a caller that started a- * multi-step flow earlier (a warmup fanning out from a parent response). The- * response settles into that scope under the same off-scope rules as any- * other. When the scope is no longer active the fetch rejects without a- * request: it would read the new identity's data under the old one's label.- * Defaults to the active scope.- */- scope?: string;-}--export interface ReplicaFetchResult<TFetched> {- /**- * Whether the response was settled into the active scope: folded in, or- * applied as a terminal absence. `false` when a guard dropped it (scope- * switch, `remove` / `clear` mid-flight, superseded) or `prepareHead` did.- */- applied: boolean;- /** The response as fetched, also when it was not applied. */- data: TFetched;- /** The response was a terminal absence (`isMissing`), in whichever scope. */- missing: boolean;-}--export interface ReplicaSyncOptions<- TFetched = unknown,- TData = unknown,-> extends ReplicaSyncSchedule {- enabled?: boolean;- /**- * Side effects of a failed fetch (error side-maps); the store view is left as is.- * Receives the captured {@link ReplicaSyncErrorContext} so a terminal removal- * can target the scope the request belonged to rather than the one that is- * active once the callback runs.- */- onError?: (error: unknown, context: ReplicaSyncErrorContext) => void;- /**- * Side effects of a hydrated persisted value, run after it is folded into the- * replica. A cold start with no network (offline / slow) has no response for- * `onSuccess` to run on, so the same "success" handling must also run off the- * persisted value it paints.- */- onHydrated?: (data: TData) => void;- /**- * Side effects of a response, run after it is folded into the replica- * (e.g. adopting an active id). UI callbacks of this view only: effects every- * response of the resource needs belong in the slice's `effects`, which- * `fetch` runs too.- */- onSuccess?: (data: TFetched) => void;-}--export interface ReplicaSyncResult {- error: unknown;- /** The persisted row has been read (or there is nothing to read). */- isHydrated: boolean;- /** A network request is in flight. Never a reason to hide store data. */- isValidating: boolean;- /** Re-run the network sync for this entry. */- revalidate: () => Promise<unknown>;-}--/** `slice.fetch` was asked to fetch for a scope that is no longer active. */-export class ReplicaScopeChangedError extends Error {- constructor(name: string, scope: string) {- super(`[replica] ${name}: scope ${scope} is no longer active`);- this.name = 'ReplicaScopeChangedError';- }-}--/** One head request, from `begin` to `settle`. */-interface ReplicaRequest<TParams, TFetched> {- /** `clear()` generation of `scope` when the request started. */- clearGeneration: number;- key: string;- params: TParams;- /** Settles the request; set once it is sent. */- promise?: Promise<TFetched>;- /** Row key of the query it asks for (`headQuery` guard). */- queryKey: string;- /** `remove` generation of `scope` + `key` when the request started. */- removalGeneration: number;- /** Scope + sync key: requests of the same id dedupe and supersede each other. */- requestId: string;- /** The cache scope it was captured under. */- scope: string;- /** Start order across the slice. */- seq: number;- /** What it settled to; a request is settled once (a joined fetch and its sync share it). */- settled?: ReplicaSettled;- /** The response (or failure) it settled with. */- settledWith?: unknown;- source: 'fetch' | 'sync';- syncKey: readonly unknown[];-}--interface ReplicaSettled {- /** Settled into the active scope (folded in or removed as missing). */- applied: boolean;- /** Passed every guard; `isActive` says whether its scope is still on screen. */- current: boolean;- isActive: boolean;- missing: boolean;-}--type ReplicaOutcome<TFetched> = { data: TFetched } | { error: unknown };--export interface ReplicaSyncResult {- error: unknown;- /** The persisted row has been read (or there is nothing to read). */- isHydrated: boolean;- /** A network request is in flight. Never a reason to hide store data. */- isValidating: boolean;- /** Re-run the network sync for this entry. */- revalidate: () => Promise<unknown>;-}--/**- * Bind a replica to a domain Zustand store.- *- * The domain store stays the only UI source of truth: components read the- * `view` location through their usual selectors. The engine owns every- * transition of that location; this slice adds the Zustand port and a- * `useSync` hook that only orchestrates fetching β data never flows through- * its return value.- */-export const createReplicaSlice = <TStore, TParams, TData, TFetched = TData>(- resource: ReplicaResource<TParams, TData, TFetched>,- {- driver,- effects,- get,- set,- stateKey,- view,- ...options- }: CreateReplicaSliceOptions<TStore, TParams, TData, TFetched>,-) => {- /**- * Apply every view write as ONE host update, so subscribers never observe a- * view out of step with its bookkeeping. Consecutive key writes go through- * the lens' `setMany` when it has one, so seeding N rows clones the backing- * field once instead of N times.- */- const applyWrites = (state: TStore, writes: ReplicaViewWrite<TData>[]) => {- let patch: Partial<TStore> = {};- let current = state;- let pending: ReplicaViewSet<TData>[] = [];-- const flush = () => {- if (pending.length === 0) return;- const entries = pending;- pending = [];- if (view.setMany && entries.length > 1) {- const next = view.setMany(current, entries);- patch = { ...patch, ...next };- current = { ...current, ...next };- return;- }- for (const entry of entries) {- const next = view.set(current, entry.key, entry.data);- patch = { ...patch, ...next };- current = { ...current, ...next };- }- };-- for (const write of writes) {- if ('type' in write) {- flush();- const next = view.clear(current);- patch = { ...patch, ...next };- current = { ...current, ...next };- } else {- pending.push({ data: write.data, key: write.key });- }- }- flush();- return patch;- };-- const revalidate = (key?: string) =>- driver.revalidate((queryKey) =>- isReplicaSyncKey(queryKey, resource.name, { key, scope: resource.scope.get() }),- );-- const engine = createReplicaEngine(resource, {- ...options,- port: {- commit: (writes, state, label) =>- set({ ...applyWrites(get(), writes), [stateKey]: state } as Partial<TStore>, false, label),- getState: () => get()[stateKey] as unknown as ReplicaState<TData>,- keys: view.keys && (() => view.keys!(get())),- read: (key) => view.get(get(), key),- },- revalidate,- });- const {- applyHead,- clearGeneration,- ensureScope,- fetcher,- hydrate,- isMissingHead,- removalGeneration,- retain,- } = engine;-- /**- * Row key of the head query each entry last asked for. One entry backs a- * single view, so a response that belongs to a query the entry has already- * moved past must not repaint it β it would show a superseded query, and a- * view gated on the current query would then wait forever. Making this an- * invariant of the slice (not of one driver) keeps it true for drivers that- * leave a request's own callback live after the query changed.- */- const headQuery = new Map<string, string>();-- /**- * Entries (`scope` + key) whose one-shot hydration actually painted a- * persisted row. The hydration query settles `true` on a cache miss too, so- * a reactivated key may only replay `onHydrated` when its row really came from- * storage β not off a provisional seed or another source that happens to sit- * in the view.- */- const hydratedEntries = new Set<string>();- const hydratedEntryId = (scope: string, key: string) => `${scope}\u0000${key}`;-- // ---- one settle pipeline ---------------------------------------------- // Every head response β a mounted `useSync`, or `fetch` with no view mounted- // β is captured by `begin` when its request starts and folded in by `settle`,- // so every path applies the same guards and the same resource effects.-- let requestSeq = 0;-- /**- * Requests whose start order is at or below this number are retired, per- * request id: a newer response already applied, or a `fresh` fetch started- * after them. Their late response would repaint an older value.- *- * An entry only matters while a request it retires is still unsettled:- * every request started later has a higher sequence, so a missing entry- * (read as 0) admits exactly the same responses. Entries are pruned as soon- * as no sent request at or below them is pending, so the map holds only the- * ids with an older request in flight.- */- const retiredThrough = new Map<string, number>();- /** Sequences of the sent requests that have not settled yet, per request id. */- const unsettled = new Map<string, Set<number>>();-- /** Drop the retirement of `requestId` once no request it retires is pending. */- const pruneRetired = (requestId: string) => {- const through = retiredThrough.get(requestId);- if (through === undefined) return;- for (const seq of unsettled.get(requestId) ?? []) if (seq <= through) return;- retiredThrough.delete(requestId);- };-- const retire = (requestId: string, seq: number) => {- if ((retiredThrough.get(requestId) ?? 0) < seq) retiredThrough.set(requestId, seq);- pruneRetired(requestId);- // Backstop: never more ids than a removal tombstone window. Only an entry- // with no older request pending may go β evicting one that still retires- // a request in flight would let its stale response win.- if (retiredThrough.size <= DEFAULT_REMOVAL_TOMBSTONE_LIMIT) return;- for (const id of retiredThrough.keys()) {- pruneRetired(id);- if (retiredThrough.size <= DEFAULT_REMOVAL_TOMBSTONE_LIMIT) return;- }- };-- const trackUnsettled = ({ requestId, seq }: ReplicaRequest<TParams, TFetched>) => {- const pending = unsettled.get(requestId) ?? new Set<number>();- unsettled.set(requestId, pending);- pending.add(seq);- };-- const untrackUnsettled = ({ requestId, seq }: ReplicaRequest<TParams, TFetched>) => {- const pending = unsettled.get(requestId);- if (!pending?.delete(seq)) return;- if (pending.size === 0) unsettled.delete(requestId);- pruneRetired(requestId);- };-- /** The latest request in flight per id, which a non-`fresh` `fetch` joins. */- const inflight = new Map<string, ReplicaRequest<TParams, TFetched>>();- /** `useSync` requests in flight per id (`fetch` seeds the driver only while none is). */- const syncInflight = new Map<string, number>();-- /**- * `useSync` request each sync id last started, settled by the driver's- * callback. The driver settles one request per key at a time (a newer- * request supersedes the older one), so the latest start is the one that- * settles.- */- const syncRequests = new Map<string, ReplicaRequest<TParams, TFetched>>();-- const syncKeyOf = (params: TParams, scope: string, key: string) =>- resource.syncKey?.(params) ??- replicaKeys.sync(resource.name, resource.version, scope, key, params);-- /** Capture what a head request for `params` started under. */- const begin = (- params: TParams,- scope: string,- source: 'fetch' | 'sync',- ): ReplicaRequest<TParams, TFetched> => {- const key = resource.key(params);- const syncKey = syncKeyOf(params, scope, key);- return {- clearGeneration: clearGeneration(scope),- key,- params,- queryKey: resource.storageKey(params),- removalGeneration: removalGeneration(scope, key),- requestId: `${scope}\u0000${stableQueryKey(syncKey)}`,- scope,- seq: ++requestSeq,- source,- syncKey,- };- };-- /** Send the request and track it in flight until it settles. */- const send = (request: ReplicaRequest<TParams, TFetched>) => {- const { requestId } = request;- const sent = fetcher!(request.params, undefined);- // Tolerate a fetcher (a test double) that does not return a promise: the- // driver still gets exactly what it returned.- const promise = Promise.resolve(sent);- request.promise = promise;- // Until it settles, a retirement that covers it must be kept.- trackUnsettled(request);- inflight.set(requestId, request);- if (request.source === 'sync')- syncInflight.set(requestId, (syncInflight.get(requestId) ?? 0) + 1);- const done = () => {- if (inflight.get(requestId) === request) inflight.delete(requestId);- if (request.source !== 'sync') return;- const count = (syncInflight.get(requestId) ?? 1) - 1;- if (count > 0) syncInflight.set(requestId, count);- else syncInflight.delete(requestId);- };- promise.then(done, done);- // A `useSync` request settles on its own response, not only through the- // driver's callback: a driver skips that callback once the hook moved to- // another key, unmounted, or a newer request superseded it β and the- // resource effects (a terminal absence, a purge) must not depend on which- // view is still mounted. The callback then reads the memoized result.- if (request.source === 'sync')- promise.then(- (data) => settle(request, { data }),- (error: unknown) => settle(request, { error }),- );- return sent;- };-- /**- * Whether the request still answers the query its entry shows. A `useSync`- * request must match the query the entry last asked for (see `headQuery`). A- * `fetch` may also land with no view mounted, but never over a view that- * shows another query of the key.- */- const isActiveQuery = ({ key, queryKey, source }: ReplicaRequest<TParams, TFetched>) => {- const head = headQuery.get(key);- return source === 'sync' ? head === queryKey : head === undefined || head === queryKey;- };-- const settleOnce = (- request: ReplicaRequest<TParams, TFetched>,- outcome: ReplicaOutcome<TFetched>,- ): ReplicaSettled => {- const { key, params, scope } = request;- /**- * Whether the entry is still on the scope the request was captured under.- *- * A response can settle after an identity/workspace switch. `replace` drops- * it β the engine refuses off-scope actions β but no side effect may run- * either: it carries the previous identity's state (onboarding redirect,- * display snapshot, analytics identify, settings writes). The captured- * key/scope is not enough on its own, because a switch to a scope that- * reads the same key/query satisfies the other guards.- */- const isActive = resource.scope.get() === scope;- const dropped: ReplicaSettled = { applied: false, current: false, isActive, missing: false };-- // Discard a response that started before a `clear()` of its scope or a- // `remove` of its entry (it holds wiped data), one for a query the entry- // has moved past (the newer query owns the view, see `headQuery`), and one- // older than a response already applied or a `fresh` fetch.- if (- request.clearGeneration !== clearGeneration(scope) ||- request.removalGeneration !== removalGeneration(scope, key) ||- request.seq <= (retiredThrough.get(request.requestId) ?? 0) ||- !isActiveQuery(request)- ) {- if (!('error' in outcome)) {- // A discarded success still settles the request; release any- // per-request bookkeeping even though it is never folded.- effects?.onSettled?.(outcome.data, params, { key, scope, source: request.source });- }- return dropped;- }-- if ('error' in outcome) {- // Forwarded even off-scope: the captured `key`/`scope` lets a consumer- // purge that scope's row (a late NOT_FOUND / FORBIDDEN) without touching- // the scope on screen; `isActive` tells it whether the failure also- // belongs to the view on screen.- effects?.onError?.(outcome.error, params, { isActive, key, scope });- return { ...dropped, current: true };- }-- // Every successful response releases per-request bookkeeping, including- // one that ends up off-scope or is dropped by `prepareHead` below.- effects?.onSettled?.(outcome.data, params, { key, scope, source: request.source });-- if (!isActive) {- // Off-scope: never fold a value into the scope on screen. A terminal- // absence still purges its own scope's row (`remove` routes it there), so- // a switch back cannot hydrate a value the server no longer has.- const missing = isMissingHead(outcome.data);- if (missing) {- remove(key, scope);- effects?.onPurge?.(params, { key, scope, source: request.source });- }- return { ...dropped, current: true, missing };- }-- retire(request.requestId, request.seq - 1);- const { outcome: folded } = applyHead(params, outcome.data, scope);- const context: ReplicaSettleContext = { key, scope, source: request.source };- if (folded === 'replaced') effects?.onApplied?.(outcome.data, params, context);- else if (folded === 'missing') effects?.onMissing?.(params, context);- return {- applied: folded !== 'dropped',- current: true,- isActive,- missing: folded === 'missing',- };- };-- /**- * Fold a settled head request into the replica: apply every guard, then- * `replace` / remove a terminal absence (in the captured scope) / purge one- * captured off-scope, then run the resource effects. A request is settled- * once: a `fetch` that joined a `useSync` request shares its result.- */- const settle = (- request: ReplicaRequest<TParams, TFetched>,- outcome: ReplicaOutcome<TFetched>,- ): ReplicaSettled => {- if (request.settled) return request.settled;- request.settledWith = 'error' in outcome ? outcome.error : outcome.data;- request.settled = settleOnce(request, outcome);- untrackUnsettled(request);- if (request.source === 'sync') releaseSyncRequest(request);- return request.settled;- };-- /**- * Drop a settled `useSync` request's record once its driver callback had its- * chance to read it. The record is normally taken by that callback, but the- * driver skips it when the hook changed key, unmounted or was superseded β- * the request still settles on its own promise, and its record (holding the- * response) must not stay behind. A driver runs the callback in the same- * turn the response resolves (SWR does, in microtasks), so a macrotask later- * the record is only a leak.- */- const releaseSyncRequest = (request: ReplicaRequest<TParams, TFetched>) => {- setTimeout(() => {- if (syncRequests.get(request.requestId) === request) syncRequests.delete(request.requestId);- }, 0);- };-- /**- * Fetch the head of an entry now and settle it like a `useSync` response β- * for stores that need the data while no view is mounted (a hover prefetch,- * a refresh after a mutation on a route without the list). `revalidate` only- * re-runs mounted queries.- *- * Joins a request in flight for the same entry unless `fresh`. Resolves with- * what was fetched and whether it was applied; rejects when the request- * fails, after routing the failure through `effects.onError`.- */- const fetch = async (- params: TParams,- { fresh = false, scope = resource.scope.get() }: ReplicaFetchOptions = {},- ): Promise<ReplicaFetchResult<TFetched>> => {- if (!fetcher) throw new Error(`[replica] ${resource.name} has no fetcher`);- if (scope !== resource.scope.get()) throw new ReplicaScopeChangedError(resource.name, scope);- let request = begin(params, scope, 'fetch');- const joined = fresh ? undefined : inflight.get(request.requestId);- if (joined) request = joined;- else {- if (fresh) retire(request.requestId, request.seq - 1);- send(request);- }-- let data: TFetched;- try {- data = await request.promise!;- } catch (error) {- settle(request, { error });- throw error;- }- const settled = settle(request, { data });- // Seed the driver's cache with what this fetch applied, unless a `useSync`- // request of the key is in flight: it fills the cache itself, and a write- // overtaking it could make the driver discard its newer response.- if (settled.applied && request.source === 'fetch' && !syncInflight.has(request.requestId))- driver.seed?.(request.syncKey, data);- return { applied: settled.applied, data, missing: settled.missing };- };-- /**- * Forget the key's head query as well as the entry. A `useSync` request- * already in flight for it would otherwise pass the settle guards (the- * marker still matches), `replace` the entry and persist pre-mutation rows- * back over an invalidation that has already completed. (The engine's- * removal generation drops a `fetch` captured before the removal.)- */- const remove = (key: string, scope?: string) => {- // Only the active scope's marker belongs to the entry on screen; an- // off-scope removal (see `engine.remove`) must not drop it.- if (scope === undefined || scope === resource.scope.get()) headQuery.delete(key);- return engine.remove(key, scope);- };-- /**- * Hydrates the persisted row once per scope/key/query, then lets the driver- * fetch and revalidate the head. Read the data from the store.- */- const useSync = (- params: TParams | null | undefined,- {- enabled = true,- onError,- onHydrated,- onSuccess,- ...schedule- }: ReplicaSyncOptions<TFetched, TData> = {},- ): ReplicaSyncResult => {- const scope = resource.scope.use();- const key = params ? resource.key(params) : undefined;- const active = enabled && !!params && key !== undefined;- const queryKey = params ? resource.storageKey(params) : undefined;-- // Layout effect: runs before paint, so a scope switch never shows a frame- // of the previous identity's data.- useLayoutEffect(() => {- if (active) ensureScope(scope);- }, [active, scope]);-- // Remember the query this entry now asks for (see `headQuery`).- useLayoutEffect(() => {- if (active && key !== undefined && queryKey !== undefined) headQuery.set(key, queryKey);- }, [active, key, queryKey]);-- // Pin the entry on screen against eviction (`persist.maxEntries`).- useLayoutEffect(() => {- if (active && key !== undefined && queryKey !== undefined) return retain(key, queryKey);- }, [active, key, queryKey]);-- // The entry this hook currently asks for. A hydrate that resolves after the- // hook moved to another key still fills its own cache entry (harmless), but- // it must not replay `onHydrated`: those side effects act on the *current*- // view, so they would re-adopt a superseded object (e.g. navigate g1 β g2- // while g1's storage read is slow, then g1's hydrate resets the active group- // back to g1's supervisor).- const activeKey = useRef<string | undefined>(undefined);- // The entry (scope + key) whose hydration side effects already ran in its- // current activation. Reset on every key or scope change, so an entry that- // comes back (g1 β g2 β g1, or scope A β B β A with the same key) gets them- // replayed even though its `once` hydration is not re-run.- const hydratedKey = useRef<string | undefined>(undefined);- useLayoutEffect(() => {- activeKey.current = active ? key : undefined;- hydratedKey.current = undefined;- }, [active, key, scope]);-- const hydration = driver.useQuery<boolean>(- active && resource.persisted && resource.persistKey(key!)- ? replicaKeys.hydrate(resource.name, resource.version, scope, resource.storageKey(params!))- : null,- async () => {- const didHydrate = await hydrate(params!, scope);- if (didHydrate) hydratedEntries.add(hydratedEntryId(scope, key!));- // A superseded key (the hook moved on) runs no side effects at all.- if (activeKey.current !== key) return true;- hydratedKey.current = hydratedEntryId(scope, key!);- // A persisted row is a successful value with no network response: replay- // the success side effects off it, so an offline / slow first paint still- // adopts the roster and settles the flags the response path would.- if (didHydrate) {- const hydrated = view.get(get(), key!);- if (hydrated !== undefined) onHydrated?.(hydrated);- }- return true;- },- { once: true },- );-- // Reactivating a key whose hydration already settled: the driver reuses the- // `once` result and the fetcher above does not run, so replay the side- // effects off the value in memory. Without it, returning to g1 offline- // leaves them acting on g2 until a response lands (or forever, offline).- useEffect(() => {- if (!active || key === undefined || hydration.data !== true) return;- const entry = hydratedEntryId(scope, key);- if (hydratedKey.current === entry) return;- hydratedKey.current = entry;- const current = view.get(get(), key);- if (current !== undefined) {- // A lookup that missed storage hydrated nothing to replay.- if (hydratedEntries.has(entry)) onHydrated?.(current);- return;- }- // Back on a scope whose view `ensureScope` cleared (A β B β A): the cached- // `once` result means the fetcher will not read storage again, so read it- // here β otherwise a row still in A's partition stays off screen while- // the network is slow or offline.- void hydrate(params!, scope).then((didHydrate) => {- if (!didHydrate) return;- hydratedEntries.add(entry);- if (activeKey.current !== key || resource.scope.get() !== scope) return;- const hydrated = view.get(get(), key);- if (hydrated !== undefined) onHydrated?.(hydrated);- });- }, [active, key, scope, hydration.data]);-- const syncKey = active && fetcher ? syncKeyOf(params!, scope, key!) : null;- /** The request settling now: the one this sync id last started. */- const takeRequest = (response: unknown) => {- const requestId = `${scope}\u0000${stableQueryKey(syncKey)}`;- const request = syncRequests.get(requestId);- syncRequests.delete(requestId);- // The request already settled on its own response, and the driver now- // reports that same response: read the memoized result.- if (request && (!request.settled || request.settledWith === response)) return request;- // A response the driver settles without having run our fetcher (a- // cache-shared key), or one the recorded request did not produce, is- // captured now: nothing it started under is known.- return begin(params!, scope, 'sync');- };-- const sync = driver.useQuery<TFetched>(- syncKey,- () => {- const request = begin(params!, scope, 'sync');- syncRequests.set(request.requestId, request);- return send(request);- },- {- ...schedule,- // Always installed, so a failed request is settled (and its capture- // dropped) even when the caller has no error side effects. A failure- // of a query the entry has moved past (or of a request from before a- // clear) never surfaces on the query now on screen; an off-scope one is- // still forwarded with the captured key/scope (see `settle`).- onError: (error: unknown) => {- const settled = settle(takeRequest(error), { error });- if (settled.current) onError?.(error, { isActive: settled.isActive, key, scope });- },- onSuccess: (data) => {- const settled = settle(takeRequest(data), { data });- if (!settled.current || !settled.isActive) return;- // A key the hook has moved past (g1 β g2 while g1's request is in- // flight): the response still fills g1's own entry, but this view's- // side effects would re-adopt g1 over the g2 view.- if (activeKey.current !== key) return;- onSuccess?.(data);- },- },- );-- return {- error: sync.error,- // A read with no key has nothing to hydrate, so it counts as hydrated: a- // conditional consumer must not show "loading" for an absent id (the- // former SWR disabled-key behaviour). A read that is disabled but *has* a- // key still waits for its persisted row.- isHydrated:- key === undefined ||- !resource.persisted ||- !resource.persistKey(key) ||- hydration.data === true,- isValidating: sync.isValidating,- revalidate: () => sync.mutate(),- };- };-- return {- ...engine,- /** @internal Records of `useSync` requests not yet released (leak checks in tests). */- debugPendingSyncRequests: () => syncRequests.size,- /** @internal Retirement records still held (leak checks in tests). */- debugRetiredRequests: () => retiredThrough.size,- fetch,- remove,- useSync,- };-};--export type ReplicaSlice<TStore, TParams, TData, TFetched = TData> = ReturnType<- typeof createReplicaSlice<TStore, TParams, TData, TFetched>->;--/** Lens for the common case: a `Record<key, TData>` field on the store. */-export const recordLens = <TStore, TData>(- field: keyof TStore & string,-): ReplicaLens<TStore, TData> => ({- clear: () => ({ [field]: {} }) as Partial<TStore>,- get: (state, key) => (state[field] as Record<string, TData> | undefined)?.[key],- keys: (state) => Object.keys((state[field] as Record<string, TData> | undefined) ?? {}),- set: (state, key, data) => {- const next = { ...(state[field] as Record<string, TData> | undefined) };- if (data === undefined) delete next[key];- else next[key] = data;- return { [field]: next } as Partial<TStore>;- },- setMany: (state, entries) => {- // One clone of the record, then every key β a list refresh seeds N groups- // in a single copy instead of N.- const next = { ...(state[field] as Record<string, TData> | undefined) };- for (const { key, data } of entries) {- if (data === undefined) delete next[key];- else next[key] = data;- }- return { [field]: next } as Partial<TStore>;- },-});--/**- * Lens for a paged view split across store fields: the rows stay where- * existing readers expect them (`itemsField[key]`, a plain array), the paging- * bookkeeping lives in `metaField[key]`, and `derive` recomputes fields built- * from the rows (e.g. a parsed display list) in the same commit β so a derived- * field is never one frame behind its rows.- *- * Rows seeded without bookkeeping (by code outside the replica) read as a- * single head page.- */-export const splitPagedLens = <TStore, TItem, TCursor = unknown>({- clearDerived,- derive,- itemsField,- metaField,-}: {- /** Derived fields to reset on a scope change. */- clearDerived?: () => Partial<TStore>;- /** Fields computed from an entry's rows (`undefined` = the entry is gone). */- derive?: (state: TStore, key: string, items: TItem[] | undefined) => Partial<TStore>;- itemsField: keyof TStore & string;- metaField: keyof TStore & string;-}): ReplicaLens<TStore, ReplicaPagedData<TItem, TCursor>> => {- type Meta = Omit<ReplicaPagedData<TItem, TCursor>, 'items'>;- const NO_META = {} as Meta;- // Same rows + same bookkeeping β the same view object, so the engine's- // reference checks see "unchanged".- const views = new WeakMap<TItem[], WeakMap<Meta, ReplicaPagedData<TItem, TCursor>>>();- const remember = (items: TItem[], meta: Meta, view: ReplicaPagedData<TItem, TCursor>) => {- let byMeta = views.get(items);- if (!byMeta) views.set(items, (byMeta = new WeakMap()));- byMeta.set(meta, view);- return view;- };- const rowsOf = (state: TStore) => (state[itemsField] ?? {}) as Record<string, TItem[]>;- const metaOf = (state: TStore) => (state[metaField] ?? {}) as Record<string, Meta>;-- return {- clear: () => ({ [itemsField]: {}, [metaField]: {}, ...clearDerived?.() }) as Partial<TStore>,- get: (state, key) => {- const items = rowsOf(state)[key];- if (!items) return undefined;- const meta = metaOf(state)[key] ?? NO_META;- const cached = views.get(items)?.get(meta);- if (cached) return cached;- const view =- meta === NO_META- ? { currentPage: 0, hasMore: true, items, pageSize: items.length }- : { ...meta, items };- return remember(items, meta, view);- },- keys: (state) => Object.keys(rowsOf(state)),- set: (state, key, data) => {- const rows = { ...rowsOf(state) };- const metas = { ...metaOf(state) };- if (data === undefined) {- delete rows[key];- delete metas[key];- } else {- const { items, ...meta } = data;- rows[key] = items;- metas[key] = meta;- remember(items, meta, data);- }- const next = { ...state, [itemsField]: rows, [metaField]: metas } as TStore;- return {- [itemsField]: rows,- [metaField]: metas,- ...derive?.(next, key, data?.items),- } as Partial<TStore>;- },- };-};diff --git a/packages/replica/src/zustand/createReplicaSlice.useSync.test.ts b/packages/replica/src/zustand/createReplicaSlice.useSync.test.tsdeleted file mode 100644index b611e1c9902..00000000000--- a/packages/replica/src/zustand/createReplicaSlice.useSync.test.ts+++ /dev/null@@ -1,403 +0,0 @@-/**- * @vitest-environment happy-dom- */-import { act, renderHook, waitFor } from '@testing-library/react';-import { beforeEach, describe, expect, it, vi } from 'vitest';-import { createStore } from 'zustand/vanilla';--import { testDriver as driver } from '../../tests/testDriver';-import { defineReplica } from '../core/defineReplica';-import { createReplicaState } from '../core/reducer';-import { createReplicaSlice, recordLens } from './createReplicaSlice';-import type { TestState } from './testUtils';-import { createMemoryStorage, resetScopeState, scope, scopeState, setup, wrapper } from './testUtils';--beforeEach(resetScopeState);--describe('createReplicaSlice', () => {- describe('useSync', () => {- it('paints the persisted projection while the network request is in flight', async () => {- const storage = createMemoryStorage();- storage.rows.set('user-1:personal|a', { data: ['cached'], updatedAt: 1 });- let resolveFetch!: (value: string[]) => void;- const fetcher = vi.fn(() => new Promise<string[]>((resolve) => (resolveFetch = resolve)));- const { slice, store } = setup({ fetcher, storage });-- const { result } = renderHook(() => slice.useSync({ id: 'a' }), { wrapper });-- await waitFor(() => expect(store.getState().lists.a).toEqual(['cached']));- // Background loading never hides the hydrated data.- expect(result.current.isHydrated).toBe(true);- expect(result.current.isValidating).toBe(true);-- await act(async () => resolveFetch(['server']));-- await waitFor(() => expect(store.getState().lists.a).toEqual(['server']));- expect(store.getState().listsReplica.entries.a.source).toBe('server');- await waitFor(() => expect(storage.rows.get('user-1:personal|a')?.data).toEqual(['server']));- });-- it('runs onSuccess after the response is folded in, and onError on a failed fetch', async () => {- const { slice, store } = setup();- const seen: unknown[] = [];- renderHook(- () =>- slice.useSync(- { id: 'a' },- { onSuccess: (data) => seen.push([data, store.getState().lists.a]) },- ),- { wrapper },- );- // The callback already sees the store view the response produced.- await waitFor(() => expect(seen).toEqual([[['server'], ['server']]]));-- const failure = new Error('offline');- const onError = vi.fn();- const failing = setup({- fetcher: vi.fn(async () => {- throw failure;- }),- });- renderHook(() => failing.slice.useSync({ id: 'b' }, { onError }), { wrapper });- // The callback also receives the key/scope the failing read was captured- // under, so a terminal removal can be bound to the right scope.- await waitFor(() =>- expect(onError).toHaveBeenCalledWith(failure, {- isActive: true,- key: 'b',- scope: 'user-1:personal',- }),- );- expect(failing.store.getState().lists.b).toBeUndefined();- });-- it('runs onHydrated with the hydrated value, and skips it when nothing was stored', async () => {- const storage = createMemoryStorage();- storage.rows.set('user-1:personal|a', { data: ['cached'], updatedAt: 1 });- let resolveFetch!: (value: string[]) => void;- const fetcher = vi.fn(() => new Promise<string[]>((resolve) => (resolveFetch = resolve)));- const { slice, store } = setup({ fetcher, storage });- const seen: string[][] = [];- renderHook(() => slice.useSync({ id: 'a' }, { onHydrated: (data) => seen.push(data) }), {- wrapper,- });-- await waitFor(() => expect(store.getState().lists.a).toEqual(['cached']));- expect(seen).toEqual([['cached']]);-- await act(async () => resolveFetch(['server']));- await waitFor(() => expect(store.getState().lists.a).toEqual(['server']));- // The network response stays `onSuccess`'s job; onHydrated does not fire for it.- expect(seen).toEqual([['cached']]);-- // An empty slot has no persisted value, so nothing is replayed.- const empty = setup();- const missed = vi.fn();- renderHook(() => empty.slice.useSync({ id: 'b' }, { onHydrated: missed }), { wrapper });- await waitFor(() => expect(empty.store.getState().lists.b).toEqual(['server']));- expect(missed).not.toHaveBeenCalled();- });-- it('drops the prior persisted projection when `toPersisted` reports a confirmed absence', async () => {- const storage = createMemoryStorage();- storage.rows.set('user-1:personal|a', { data: ['cached'], updatedAt: 1 });- const resource = defineReplica<{ id: string }, string[]>({- // The server confirms the id no longer exists.- fetcher: vi.fn(async () => []),- key: ({ id }) => id,- name: 'absentList',- scope,- storage: storage.storage,- version: 1,- });- const store = createStore<TestState>()(() => ({- lists: {},- listsReplica: createReplicaState(),- }));- const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {- driver,- get: store.getState,- set: (partial) => store.setState(partial),- stateKey: 'listsReplica',- // An empty list is a confirmed absence: drop the stored row instead of- // leaving the stale projection to be hydrated again.- toPersisted: (data) => (data.length ? data : null),- view: recordLens('lists'),- });-- renderHook(() => slice.useSync({ id: 'a' }), { wrapper });-- // The confirmed absence replaces the hydrated value in the viewβ¦- await waitFor(() => expect(store.getState().lists.a).toEqual([]));- // β¦and the stale persisted projection is gone, so a reload cannot paint it.- await waitFor(() => expect(storage.rows.get('user-1:personal|a')).toBeUndefined());- });-- it('keeps the stored row when `toPersisted` returns undefined (skip)', async () => {- const storage = createMemoryStorage();- storage.rows.set('user-1:personal|a', { data: ['cached'], updatedAt: 1 });- const resource = defineReplica<{ id: string }, string[]>({- fetcher: vi.fn(async () => ['server']),- key: ({ id }) => id,- name: 'skippedList',- scope,- storage: storage.storage,- version: 1,- });- const store = createStore<TestState>()(() => ({- lists: {},- listsReplica: createReplicaState(),- }));- const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {- driver,- get: store.getState,- set: (partial) => store.setState(partial),- stateKey: 'listsReplica',- // `undefined` means "skip this write", not "remove".- toPersisted: () => undefined,- view: recordLens('lists'),- });-- renderHook(() => slice.useSync({ id: 'a' }), { wrapper });-- await waitFor(() => expect(store.getState().lists.a).toEqual(['server']));- expect(storage.rows.get('user-1:personal|a')?.data).toEqual(['cached']);- });-- it('hands its schedule (polling, focus revalidation β¦) to the driver', () => {- const useQuery = vi.fn(() => ({ isValidating: false, mutate: vi.fn() }));- const resource = defineReplica<{ id: string }, string[]>({- fetcher: async () => ['server'],- key: ({ id }) => id,- name: 'scheduled',- scope,- version: 1,- });- const store = createStore<TestState>()(() => ({- lists: {},- listsReplica: createReplicaState(),- }));- const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {- driver: { revalidate: vi.fn(), useQuery },- get: store.getState,- set: (partial) => store.setState(partial),- stateKey: 'listsReplica',- view: recordLens('lists'),- });-- renderHook(() =>- slice.useSync({ id: 'a' }, { refreshInterval: 10_000, revalidateOnFocus: false }),- );-- expect(useQuery).toHaveBeenCalledWith(- expect.arrayContaining(['replica:sync', 'scheduled']),- expect.any(Function),- expect.objectContaining({ refreshInterval: 10_000, revalidateOnFocus: false }),- );- });-- it('discards a head response from a query the entry has moved past', () => {- // A driver that settles every request through its own callback lets two- // queries of the same key resolve out of order. One entry backs one view,- // so the query the entry no longer asks for must not repaint it.- const requests: {- onSuccess: (data: string[]) => void;- params: { q?: string };- }[] = [];- const useQuery = vi.fn((key: any, _fetcher: unknown, options: any) => {- if (key !== null) requests.push({ onSuccess: options.onSuccess, params: key.at(-1) });- return { isValidating: false, mutate: vi.fn() };- });- const resource = defineReplica<{ q?: string }, string[]>({- fetcher: async () => ['server'],- key: () => 'all',- name: 'orderedHead',- query: ({ q }) => ({ q }),- scope,- version: 1,- });- const store = createStore<TestState>()(() => ({- lists: {},- listsReplica: createReplicaState(),- }));- const slice = createReplicaSlice<TestState, { q?: string }, string[]>(resource, {- driver: { revalidate: vi.fn(), useQuery },- get: store.getState,- set: (partial) => store.setState(partial),- stateKey: 'listsReplica',- view: recordLens('lists'),- });-- const { rerender } = renderHook((props: { q?: string }) => slice.useSync(props), {- initialProps: {} as { q?: string },- });- rerender({ q: 'b' });-- const base = requests.find((request) => request.params.q === undefined)!;- const search = requests.find((request) => request.params.q === 'b')!;-- act(() => search.onSuccess(['b-1']));- expect(store.getState().lists.all).toEqual(['b-1']);-- // The superseded query settles late: it must not overwrite the search.- act(() => base.onSuccess(['a-1']));- expect(store.getState().lists.all).toEqual(['b-1']);- });-- it('syncs under a custom key when the resource adopts one', () => {- const useQuery = vi.fn(() => ({ isValidating: false, mutate: vi.fn() }));- const resource = defineReplica<{ id: string }, string[]>({- fetcher: async () => ['server'],- key: ({ id }) => id,- name: 'customKeyed',- scope,- syncKey: ({ id }) => ['legacy:list', id],- version: 1,- });- const store = createStore<TestState>()(() => ({- lists: {},- listsReplica: createReplicaState(),- }));- const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {- driver: { revalidate: vi.fn(), useQuery },- get: store.getState,- set: (partial) => store.setState(partial),- stateKey: 'listsReplica',- view: recordLens('lists'),- });-- renderHook(() => slice.useSync({ id: 'a' }));-- expect(useQuery).toHaveBeenCalledWith(- ['legacy:list', 'a'],- expect.any(Function),- expect.any(Object),- );- });-- it('does not let a slow hydration overwrite a faster server response', async () => {- const storage = createMemoryStorage();- storage.rows.set('user-1:personal|a', { data: ['cached'], updatedAt: 1 });- const originalGet = storage.storage.get;- storage.storage.get = async (key) => {- await new Promise((resolve) => setTimeout(resolve, 30));- return originalGet(key);- };- const { slice, store } = setup({ storage });-- const { result } = renderHook(() => slice.useSync({ id: 'a' }), { wrapper });-- await waitFor(() => expect(result.current.isHydrated).toBe(true));- expect(store.getState().lists.a).toEqual(['server']);- });-- it('does not let a slow hydration resurrect an entry removed while it was in flight', async () => {- // A NOT_FOUND / FORBIDDEN response removes the entry (and its row) while- // the persisted read is still in flight. That read already holds the old- // row, so landing it afterwards would repaint the value just dropped.- const storage = createMemoryStorage();- storage.rows.set('user-1:personal|a', { data: ['revoked'], updatedAt: 1 });- const originalGet = storage.storage.get;- let release!: () => void;- const held = new Promise<void>((resolve) => (release = resolve));- storage.storage.get = async (key) => {- const row = await originalGet(key);- if (key.queryKey === 'a') await held;- return row;- };- const { slice, store } = setup({ storage });-- let hydration!: Promise<boolean>;- await act(async () => {- hydration = slice.hydrate({ id: 'a' });- });-- // The network answers first and drops the entry.- act(() => slice.remove('a'));- expect(store.getState().lists.a).toBeUndefined();-- // The slow read settles: it must not paint the row the removal dropped.- await act(async () => {- release();- await hydration;- });-- expect(store.getState().lists.a).toBeUndefined();- expect(store.getState().listsReplica.entries.a).toBeUndefined();- });-- it('refuses to hydrate a key that was explicitly removed even if its row is still on disk', async () => {- const storage = createMemoryStorage();- storage.rows.set('user-1:personal|a', { data: ['revoked'], updatedAt: 1 });- const { slice, store } = setup({ storage });-- act(() => slice.remove('a'));- // The delete may not have flushed yet β the row must not come back anyway.- storage.rows.set('user-1:personal|a', { data: ['revoked'], updatedAt: 1 });-- await act(async () => {- expect(await slice.hydrate({ id: 'a' })).toBe(false);- });- expect(store.getState().lists.a).toBeUndefined();- });-- it('lets a later server value supersede a removal so the key hydrates again', async () => {- const storage = createMemoryStorage();- storage.rows.set('user-1:personal|a', { data: ['revoked'], updatedAt: 1 });- const { slice, store } = setup({ storage });-- act(() => slice.remove('a'));- // Access restored: the server now answers with a value again.- act(() => slice.replace({ id: 'a' }, ['regranted']));- expect(store.getState().lists.a).toEqual(['regranted']);- // Let the confirmed value reach the persisted row before reading it back.- await waitFor(() =>- expect(storage.rows.get('user-1:personal|a')?.data).toEqual(['regranted']),- );-- // Drop memory the way a scope switch does, then come back: with the- // removal superseded, the persisted row may hydrate once more.- scopeState.current = 'user-2:personal';- act(() => slice.ensureScope('user-2:personal'));- scopeState.current = 'user-1:personal';- act(() => slice.ensureScope('user-1:personal'));-- await act(async () => {- expect(await slice.hydrate({ id: 'a' })).toBe(true);- });- expect(store.getState().lists.a).toEqual(['regranted']);- });-- it('reports a keyless (disabled) read as hydrated, so it never looks loading', () => {- const { slice } = setup();-- const { result } = renderHook(() => slice.useSync(null), { wrapper });-- expect(result.current.isHydrated).toBe(true);- expect(result.current.isValidating).toBe(false);- });-- it('keeps the removal guard when a response captured under another scope is discarded', async () => {- const storage = createMemoryStorage();- storage.rows.set('user-1:personal|a', { data: ['revoked'], updatedAt: 1 });- // The persisted-row delete is best-effort: simulate it still being pending.- storage.storage.remove = async () => {};- const { slice, store } = setup({ storage });-- // Scope A removes the entry (and arms its guard).- act(() => slice.remove('a'));-- // A response captured under A resolves only after the user switched to B,- // so `dispatch` drops it. It must not clear A's guard on the way out.- scopeState.current = 'user-2:personal';- act(() => slice.replace({ id: 'a' }, ['stale'], 'user-1:personal'));-- // Switching back to A must still refuse to hydrate the stale row.- scopeState.current = 'user-1:personal';- await act(async () => {- expect(await slice.hydrate({ id: 'a' })).toBe(false);- });- expect(store.getState().lists.a).toBeUndefined();- });- });-});diff --git a/packages/replica/src/zustand/createReplicaSlice.useSyncSettle.test.ts b/packages/replica/src/zustand/createReplicaSlice.useSyncSettle.test.tsdeleted file mode 100644index e4743c169ef..00000000000--- a/packages/replica/src/zustand/createReplicaSlice.useSyncSettle.test.ts+++ /dev/null@@ -1,550 +0,0 @@-/**- * @vitest-environment happy-dom- */-import { act, renderHook, waitFor } from '@testing-library/react';-import { beforeEach, describe, expect, it, vi } from 'vitest';-import { createStore } from 'zustand/vanilla';--import { testDriver as driver } from '../../tests/testDriver';-import { defineReplica } from '../core/defineReplica';-import { REPLICA_INDEX_KEY } from '../core/engine';-import { createReplicaState } from '../core/reducer';-import type { ReplicaRow, ReplicaStorage } from '../core/types';-import { createReplicaSlice, recordLens } from './createReplicaSlice';-import type { TestState } from './testUtils';-import { createMemoryStorage, resetScopeState, scope, scopeState, setup, wrapper } from './testUtils';--beforeEach(resetScopeState);--describe('createReplicaSlice', () => {- describe('useSync', () => {- it('runs the caller success side effects when the response changes nothing', () => {- // `replace` reports false both for a rejected response and for one with- // nothing to write (an unchanged revalidation, or `undefined` for an id the- // server no longer has). Callers rely on onSuccess in the latter cases β- // e.g. removing a cached detail the server answered with nothing.- const requests: { onSuccess: (data: string[] | undefined) => void }[] = [];- const useQuery = vi.fn((key: any, _fetcher: unknown, options: any) => {- if (key !== null && options?.onSuccess) requests.push({ onSuccess: options.onSuccess });- return { isValidating: false, mutate: vi.fn() };- });- const resource = defineReplica<{ id: string }, string[]>({- fetcher: async () => ['server'],- key: ({ id }) => id,- name: 'noopSuccessSideEffects',- scope,- version: 1,- });- const store = createStore<TestState>()(() => ({- lists: { a: ['same'] },- listsReplica: createReplicaState(),- }));- const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {- driver: { revalidate: vi.fn(), useQuery },- get: store.getState,- set: (partial) => store.setState(partial),- stateKey: 'listsReplica',- view: recordLens('lists'),- });-- scopeState.current = 'user-1:personal';- const onSuccess = vi.fn();- renderHook(() => slice.useSync({ id: 'a' }, { onSuccess }), { wrapper });- const request = requests.find((entry) => entry)!;-- act(() => request.onSuccess(['same']));- act(() => request.onSuccess(['same']));- act(() => request.onSuccess(undefined));-- expect(onSuccess).toHaveBeenCalledTimes(3);- expect(onSuccess).toHaveBeenLastCalledWith(undefined);- });-- it("drops a settled request's success side effects once the store has left its scope", () => {- // A response can settle after an identity/workspace switch. The engine- // refuses the off-scope `replace`, but the caller's callbacks carry the- // previous identity's side effects, so they must not run either β and a- // switch to a scope reading the same key/query defeats both the- // moved-past-query and since-clear guards.- const requests: {- onError: (error: unknown) => void;- onSuccess: (data: string[]) => void;- }[] = [];- const useQuery = vi.fn((key: any, _fetcher: unknown, options: any) => {- if (key !== null) requests.push({ onError: options.onError, onSuccess: options.onSuccess });- return { isValidating: false, mutate: vi.fn() };- });- const resource = defineReplica<{ id: string }, string[]>({- fetcher: async () => ['server'],- key: ({ id }) => id,- name: 'staleScopeCallbacks',- scope,- version: 1,- });- const store = createStore<TestState>()(() => ({- lists: {},- listsReplica: createReplicaState(),- }));- const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {- driver: { revalidate: vi.fn(), useQuery },- get: store.getState,- set: (partial) => store.setState(partial),- stateKey: 'listsReplica',- view: recordLens('lists'),- });-- const onSuccess = vi.fn();- const onError = vi.fn();- renderHook(() => slice.useSync({ id: 'a' }, { onError, onSuccess }), { wrapper });-- const captured = requests.find((request) => request)!;-- // The identity/workspace switches while the request is still in flight.- scopeState.current = 'user-2:personal';-- act(() => captured.onSuccess(['stale']));- expect(onSuccess).not.toHaveBeenCalled();- expect(store.getState().lists.a).toBeUndefined();-- // A failure is still handed over, bound to the scope it was captured- // under and flagged as no longer active, so the caller can purge that- // scope's row (see below) without repainting the current view.- act(() => captured.onError(new Error('stale')));- expect(onError).toHaveBeenCalledWith(expect.any(Error), {- isActive: false,- key: 'a',- scope: 'user-1:personal',- });- });-- it('lets a late terminal error purge its captured scope through the sync callback', async () => {- const requests: { onError: (error: unknown) => void }[] = [];- const useQuery = vi.fn((key: any, _fetcher: unknown, options: any) => {- // The sync request carries the callbacks; the hydration read does not.- if (key !== null && options?.onError) requests.push({ onError: options.onError });- return { isValidating: false, mutate: vi.fn() };- });- const memory = createMemoryStorage();- memory.rows.set('user-1:personal|a', { data: ['revoked'], updatedAt: 1 });- const resource = defineReplica<{ id: string }, string[]>({- fetcher: async () => ['server'],- key: ({ id }) => id,- name: 'lateTerminalError',- scope,- storage: memory.storage,- version: 1,- });- const store = createStore<TestState>()(() => ({- lists: {},- listsReplica: createReplicaState(),- }));- const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {- driver: { revalidate: vi.fn(), useQuery },- get: store.getState,- set: (partial) => store.setState(partial),- stateKey: 'listsReplica',- view: recordLens('lists'),- });-- scopeState.current = 'user-1:personal';- const contexts: { isActive: boolean; key: string | undefined; scope: string }[] = [];- renderHook(- () =>- slice.useSync(- { id: 'a' },- {- onError: (_error, context) => {- contexts.push(context);- if (context.key) slice.remove(context.key, context.scope);- },- },- ),- { wrapper },- );- const request = requests.find((entry) => entry)!;-- // The identity switches and loads its own entry before the denial lands.- scopeState.current = 'user-2:personal';- act(() => slice.replace({ id: 'a' }, ['b-value']));-- act(() => request.onError(new Error('NOT_FOUND')));-- // The callback still runs, flagged as belonging to a scope left behind, so- // the consumer can purge that scope without repainting the current one.- expect(contexts[0]).toMatchObject({ isActive: false, key: 'a', scope: 'user-1:personal' });- // The scope on screen keeps its entry; the denied scope's row is purged.- expect(store.getState().lists.a).toEqual(['b-value']);- await waitFor(() => expect(memory.rows.get('user-1:personal|a')).toBeUndefined());- });-- // The guard lives in the engine, per scope β not in the bookkeeping slot a- // scope reset wipes β so an A β B β A round trip cannot lift it.- it('keeps the removal guard across a scope round trip', async () => {- const storage = createMemoryStorage();- storage.rows.set('user-1:personal|a', { data: ['revoked'], updatedAt: 1 });- // The persisted-row delete is still pending: the stale row stays on disk.- storage.storage.remove = async () => {};- const { slice, store } = setup({ storage });-- act(() => slice.remove('a'));-- scopeState.current = 'user-2:personal';- act(() => slice.ensureScope('user-2:personal'));- expect(store.getState().listsReplica.scope).toBe('user-2:personal');- scopeState.current = 'user-1:personal';- act(() => slice.ensureScope('user-1:personal'));-- await act(async () => {- expect(await slice.hydrate({ id: 'a' })).toBe(false);- });- expect(store.getState().lists.a).toBeUndefined();- });-- it('purges the captured scope row for a removal that lands after a scope switch', async () => {- const storage = createMemoryStorage();- storage.rows.set('user-1:personal|a', { data: ['revoked'], updatedAt: 1 });- const { slice, store } = setup({ storage });-- // The active scope has its own entry loaded.- scopeState.current = 'user-2:personal';- act(() => slice.replace({ id: 'a' }, ['b-value']));- expect(store.getState().lists.a).toEqual(['b-value']);-- // A late NOT_FOUND from a request captured under the previous scope must- // not delete the entry that is on screen nowβ¦- act(() => slice.remove('a', 'user-1:personal'));- expect(store.getState().lists.a).toEqual(['b-value']);-- // β¦but that scope's own persisted row still has to go, or switching back- // to it would hydrate the value the server just denied.- await waitFor(() => expect(storage.rows.get('user-1:personal|a')).toBeUndefined());- });-- it('retries an off-scope purge once the captured scope may persist again', async () => {- const storage = createMemoryStorage();- storage.rows.set('user-1:personal|a', { data: ['revoked'], updatedAt: 1 });- const { slice } = setup({ storage });-- // The terminal answer lands while writes are still refused.- scopeState.current = 'user-2:personal';- scopeState.trusted = false;- act(() => slice.remove('a', 'user-1:personal'));- await new Promise((resolve) => setTimeout(resolve, 10));- expect(storage.rows.get('user-1:personal|a')).toBeDefined();-- // Identity resolves: the next terminal answer must clear the row, not- // report a no-op that never deletes it.- scopeState.trusted = true;- act(() => slice.remove('a', 'user-1:personal'));- await waitFor(() => expect(storage.rows.get('user-1:personal|a')).toBeUndefined());- });-- it('binds the captured key and scope to the error callback', async () => {- const fetcher = vi.fn(async () => {- throw new Error('not found');- });- const { slice } = setup({ fetcher });- const contexts: { isActive: boolean; key: string | undefined; scope: string }[] = [];-- scopeState.current = 'user-1:personal';- renderHook(- () => slice.useSync({ id: 'a' }, { onError: (_error, context) => contexts.push(context) }),- { wrapper },- );-- await waitFor(() => expect(contexts.length).toBeGreaterThan(0));- expect(contexts[0]).toEqual({ isActive: true, key: 'a', scope: 'user-1:personal' });- });-- it('evicts the persisted row when a response has nothing to persist', async () => {- // Two bindings share one storage, so the second one reads what the first- // one left behind β a reload of the same resource.- const storage = createMemoryStorage();- const bind = () => {- const resource = defineReplica<{ id: string }, string[]>({- key: ({ id }) => id,- name: 'evictingList',- scope,- storage: storage.storage,- version: 1,- });- const store = createStore<TestState>()(() => ({- lists: {},- listsReplica: createReplicaState(),- }));- const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {- driver,- get: store.getState,- set: (partial) => store.setState(partial),- stateKey: 'listsReplica',- // `['gone']` is a page state that must never be persisted.- toPersisted: (data) => (data[0] === 'gone' ? null : data),- view: recordLens('lists'),- });- return { slice, store };- };-- const first = bind();- act(() => {- first.slice.replace({ id: 'a' }, ['cached']);- });- await waitFor(() => expect(storage.rows.get('user-1:personal|a')?.data).toEqual(['cached']));-- act(() => {- first.slice.replace({ id: 'a' }, ['gone']);- });- // The value stays in memoryβ¦- expect(first.store.getState().lists.a).toEqual(['gone']);- // β¦while the row persisted for it earlier is removed.- await waitFor(() => expect(storage.rows.has('user-1:personal|a')).toBe(false));-- // A reload hydrates nothing instead of resurrecting the evicted value.- const reloaded = bind();- await act(async () => {- await reloaded.slice.hydrate({ id: 'a' });- });- expect(reloaded.store.getState().lists.a).toBeUndefined();- });-- it('clears a reloaded key from the persisted index when the response has nothing to persist', async () => {- const storage = createMemoryStorage();- const indexKey = { queryKey: REPLICA_INDEX_KEY, scope: 'user-1:personal' };- const bind = () => {- const resource = defineReplica<{ id: string }, string[]>({- key: ({ id }) => id,- name: 'indexedList',- scope,- storage: storage.storage,- version: 1,- });- const store = createStore<TestState>()(() => ({- lists: {},- listsReplica: createReplicaState(),- }));- const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {- driver,- get: store.getState,- set: (partial) => store.setState(partial),- stateKey: 'listsReplica',- toPersisted: (data) => (data[0] === 'gone' ? null : data),- view: recordLens('lists'),- });- return { slice, store };- };-- const first = bind();- act(() => {- first.slice.replace({ id: 'a' }, ['cached']);- });- await waitFor(() => expect(storage.rows.get('user-1:personal|a')?.data).toEqual(['cached']));- await waitFor(async () => expect((await storage.storage.get(indexKey))?.data).toEqual(['a']));-- // A reload: a fresh engine whose in-memory index bookkeeping is empty, so- // only the persisted index knows the key is there.- const reloaded = bind();- await act(async () => {- await reloaded.slice.hydrate({ id: 'a' });- });- expect(reloaded.store.getState().lists.a).toEqual(['cached']);-- act(() => {- reloaded.slice.replace({ id: 'a' }, ['gone']);- });- // The row goesβ¦- await waitFor(() => expect(storage.rows.has('user-1:personal|a')).toBe(false));- // β¦and so does its index entry, so later entity scans do not chase a- // missing row.- await waitFor(async () => expect((await storage.storage.get(indexKey))?.data).toEqual([]));- });-- // The removal deletes the entry, but a storage read that started before it- // can still resolve afterwards; the replica must not let that stale read- // resurrect the removed entry (the server already confirmed it gone).- it('does not let a hydrate that resolves after a removal resurrect the entry', async () => {- const storage = createMemoryStorage();- storage.rows.set('user-1:personal|a', { data: ['stale'], updatedAt: 1 });- const realGet = storage.storage.get.bind(storage.storage);- let releaseRead!: () => void;- const readGate = new Promise<void>((resolve) => (releaseRead = resolve));- let readStarted = false;- vi.spyOn(storage.storage, 'get').mockImplementation(async (key) => {- if (key.queryKey === 'a') {- // A storage read is a snapshot: capture the row now, resolve later.- const snapshot = await realGet(key);- readStarted = true;- await readGate;- return snapshot;- }- return realGet(key);- });-- // A network that never answers, so only the hydrate is at play.- const { slice, store } = setup({ fetcher: () => new Promise<string[]>(() => {}), storage });-- let hydrated = false;- const session = renderHook(- () => slice.useSync({ id: 'a' }, { onHydrated: () => (hydrated = true) }),- { wrapper },- );- await waitFor(() => expect(readStarted).toBe(true));-- // The key is removed (a server-confirmed absence) before the read lands.- act(() => slice.remove('a'));-- releaseRead();- await act(async () => {});-- expect(hydrated).toBe(false);- expect(store.getState().lists.a).toBeUndefined();- expect(store.getState().listsReplica.entries.a).toBeUndefined();- session.unmount();- });-- // a β b β a: a's hydration query already settled and is not re-run, so its- // side effects must be replayed off the cached value when `a` is active again- // β or they stay pointed at `b` until (or, offline, without) a response.- it('replays onHydrated when a hydrated key becomes active again', async () => {- const storage = createMemoryStorage();- storage.rows.set('user-1:personal|a', { data: ['cached-a'], updatedAt: 1 });- storage.rows.set('user-1:personal|b', { data: ['cached-b'], updatedAt: 1 });- // Offline: the network never answers, so only hydration can run effects.- const { slice, store } = setup({ fetcher: () => new Promise<string[]>(() => {}), storage });- const seen: string[][] = [];-- const session = renderHook(- ({ id }: { id: string }) =>- slice.useSync({ id }, { onHydrated: (data) => seen.push(data) }),- { initialProps: { id: 'a' }, wrapper },- );- await waitFor(() => expect(session.result.current.isHydrated).toBe(true));- // The first activation runs it once, from the hydrate itself.- expect(seen).toEqual([['cached-a']]);-- session.rerender({ id: 'b' });- await waitFor(() => expect(seen).toEqual([['cached-a'], ['cached-b']]));-- session.rerender({ id: 'a' });- await waitFor(() => expect(seen).toEqual([['cached-a'], ['cached-b'], ['cached-a']]));- expect(store.getState().lists.a).toEqual(['cached-a']);-- // A plain re-render of the same key does not replay again.- session.rerender({ id: 'a' });- await act(async () => {});- expect(seen).toHaveLength(3);- session.unmount();- });-- // Scope A β B β A with the same key: B's activation cleared the view and- // A's `once` hydration result is reused, so the slice must read A's- // partition again β offline, nothing else would bring the row back.- it('rehydrates an entry after returning to a prior scope', async () => {- const storage = createMemoryStorage();- storage.rows.set('user-1:personal|a', { data: ['cached-a1'], updatedAt: 1 });- storage.rows.set('user-2:personal|a', { data: ['cached-a2'], updatedAt: 1 });- const { slice, store } = setup({ fetcher: () => new Promise<string[]>(() => {}), storage });- const seen: string[][] = [];-- const session = renderHook(- () => slice.useSync({ id: 'a' }, { onHydrated: (data) => seen.push(data) }),- { wrapper },- );- await waitFor(() => expect(store.getState().lists.a).toEqual(['cached-a1']));-- scopeState.current = 'user-2:personal';- session.rerender();- await waitFor(() => expect(store.getState().lists.a).toEqual(['cached-a2']));-- scopeState.current = 'user-1:personal';- session.rerender();- await waitFor(() => expect(store.getState().lists.a).toEqual(['cached-a1']));- // Its side effects follow the row back too.- await waitFor(() => expect(seen.at(-1)).toEqual(['cached-a1']));- session.unmount();- });-- // A lookup that missed storage settles `true` as well; reactivating its key- // must not replay `onHydrated` off a value that never came from storage- // (a provisional seed written into the view).- it('does not replay onHydrated for a reactivated key whose lookup missed storage', async () => {- const storage = createMemoryStorage();- storage.rows.set('user-1:personal|b', { data: ['cached-b'], updatedAt: 1 });- const { slice } = setup({ fetcher: () => new Promise<string[]>(() => {}), storage });- const seen: string[][] = [];-- const session = renderHook(- ({ id }: { id: string }) =>- slice.useSync({ id }, { onHydrated: (data) => seen.push(data) }),- { initialProps: { id: 'a' }, wrapper },- );- await waitFor(() => expect(session.result.current.isHydrated).toBe(true));- expect(seen).toEqual([]);-- session.rerender({ id: 'b' });- await waitFor(() => expect(seen).toEqual([['cached-b']]));-- // A seed lands in `a`'s view while the hook shows `b`.- act(() => {- slice.update('a', () => ['seed-a'], { persist: false, source: 'seed' });- });- session.rerender({ id: 'a' });- await act(async () => {});- expect(seen).toEqual([['cached-b']]);- session.unmount();- });-- it('a version bump ignores rows written by the previous version', async () => {- // One backing map shared by every version, keyed by the namespace the- // factory receives β like IndexedDB rows of two app releases.- const backing = new Map<string, ReplicaRow<string[]>>();- const namespaced = (namespace: string): ReplicaStorage<string[]> => ({- get: async ({ queryKey, scope }) => backing.get(`${namespace}|${scope}|${queryKey}`),- remove: async ({ queryKey, scope }) => {- backing.delete(`${namespace}|${scope}|${queryKey}`);- },- set: async ({ queryKey, scope }, row) => {- backing.set(`${namespace}|${scope}|${queryKey}`, row);- },- });- const bind = (version: number) => {- const resource = defineReplica<{ id: string }, string[]>({- key: ({ id }) => id,- name: 'versionedList',- scope,- storage: namespaced,- version,- });- const store = createStore<TestState>()(() => ({- lists: {},- listsReplica: createReplicaState(),- }));- const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {- driver,- get: store.getState,- set: (partial) => store.setState(partial),- stateKey: 'listsReplica',- view: recordLens('lists'),- });- return { slice, store };- };-- const v1 = bind(1);- act(() => {- v1.slice.replace({ id: 'a' }, ['v1-shape']);- });- const dataKeys = () => [...backing.keys()].filter((key) => !key.includes(REPLICA_INDEX_KEY));- await waitFor(() => expect(dataKeys()).toHaveLength(1));-- const v1Reload = bind(1);- await act(async () => {- await v1Reload.slice.hydrate({ id: 'a' });- });- expect(v1Reload.store.getState().lists.a).toEqual(['v1-shape']);-- const v2 = bind(2);- await act(async () => {- await v2.slice.hydrate({ id: 'a' });- });- expect(v2.store.getState().lists.a).toBeUndefined();- });- });-});diff --git a/packages/replica/src/zustand/createReplicaSlice.writes.test.ts b/packages/replica/src/zustand/createReplicaSlice.writes.test.tsdeleted file mode 100644index 1b4dbc015a1..00000000000--- a/packages/replica/src/zustand/createReplicaSlice.writes.test.ts+++ /dev/null@@ -1,133 +0,0 @@-/**- * @vitest-environment happy-dom- */-import { act, waitFor } from '@testing-library/react';-import { beforeEach, describe, expect, it, vi } from 'vitest';-import { createStore } from 'zustand/vanilla';--import { defineReplica } from '../core/defineReplica';-import { createReplicaState } from '../core/reducer';-import { createReplicaSlice, recordLens } from './createReplicaSlice';-import type { TestState } from './testUtils';-import { createMemoryStorage, resetScopeState, scope, setup } from './testUtils';--beforeEach(resetScopeState);--describe('createReplicaSlice', () => {- describe('updateMany', () => {- it('applies many keys as one commit and clones the record once', () => {- const resource = defineReplica<{ id: string }, string[]>({- fetcher: async () => ['server'],- key: ({ id }) => id,- name: 'batchedSeed',- scope,- version: 1,- });- const store = createStore<TestState>()(() => ({- lists: {},- listsReplica: createReplicaState(),- }));- const lens = recordLens<TestState, string[]>('lists');- const setMany = vi.spyOn(lens, 'setMany');- const set = vi.spyOn(lens, 'set');- let commits = 0;- const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {- driver: {- revalidate: vi.fn(),- useQuery: vi.fn(() => ({ isValidating: false, mutate: vi.fn() })),- },- get: store.getState,- set: (partial) => {- commits += 1;- store.setState(partial);- },- stateKey: 'listsReplica',- view: lens,- });-- act(() => {- slice.updateMany([- { apply: () => ['a'], key: 'a' },- { apply: () => ['b'], key: 'b' },- { apply: () => ['c'], key: 'c' },- ]);- });-- expect(store.getState().lists).toEqual({ a: ['a'], b: ['b'], c: ['c'] });- // One host commit for the whole batch, and one clone of the record.- expect(commits).toBe(1);- expect(setMany).toHaveBeenCalledTimes(1);- expect(set).not.toHaveBeenCalled();-- // An empty batch commits nothing.- expect(slice.updateMany([])).toBe(false);- expect(commits).toBe(1);- });- });-- describe('optimistic', () => {- it('commits and persists the confirmed value on success', async () => {- const { slice, store, storage } = setup();- act(() => {- slice.replace({ id: 'a' }, ['x']);- });-- let resolveCall!: () => void;- let promise!: Promise<unknown>;- act(() => {- promise = slice.optimistic(- 'a',- (list) => [...list, 'y'],- () => new Promise<void>((resolve) => (resolveCall = resolve)),- );- });- expect(store.getState().lists.a).toEqual(['x', 'y']);-- await act(async () => {- resolveCall();- await promise;- });- expect(store.getState().lists.a).toEqual(['x', 'y']);- await waitFor(() => expect(storage.writes.at(-1)).toBe('x,y'));- });-- it('rolls back and rethrows on failure', async () => {- const { slice, store, storage } = setup();- act(() => {- slice.replace({ id: 'a' }, ['x']);- });- await waitFor(() => expect(storage.writes).toEqual(['x']));-- await act(async () => {- await expect(- slice.optimistic(- 'a',- (list) => [...list, 'y'],- async () => {- throw new Error('boom');- },- ),- ).rejects.toThrow('boom');- });-- expect(store.getState().lists.a).toEqual(['x']);- expect(storage.writes).toEqual(['x']);- });- });-- describe('write ordering', () => {- it('serializes persistence per key so the latest snapshot wins', async () => {- // The first write is slow; without serialization it would land last.- const storage = createMemoryStorage({ first: 30 });- const { slice } = setup({ storage });-- act(() => {- slice.replace({ id: 'a' }, ['first']);- slice.replace({ id: 'a' }, ['second']);- });-- await waitFor(() => expect(storage.writes).toEqual(['first', 'second']));- expect(storage.rows.get('user-1:personal|a')?.data).toEqual(['second']);- });- });-});diff --git a/packages/replica/src/zustand/driver.ts b/packages/replica/src/zustand/driver.tsdeleted file mode 100644index f25a44e251f..00000000000--- a/packages/replica/src/zustand/driver.ts+++ /dev/null@@ -1,117 +0,0 @@-/**- * Scheduling knobs a sync can ask its driver for. Named after SWR's options;- * a driver maps them onto its own cache (or ignores what it cannot honor).- */-export interface ReplicaSyncSchedule {- /** Collapse identical requests within this window (ms). */- dedupingInterval?: number;- /** Skip focus revalidation while the last one is younger than this (ms). */- focusThrottleInterval?: number;- /**- * Hold every network request (mount, stale, focus, revalidate) while it- * returns `true`, for a read whose input outside the sync key is not ready- * yet. Unlike `revalidateOnMount: false` it also covers a later key change.- * Read on each request, so it may close over a ref.- */- isPaused?: () => boolean;- /** Poll every N ms while mounted (0 = off); a function decides per tick from the latest data. */- refreshInterval?: number | ((latest: any) => number);- /** Keep polling while the page is hidden. */- refreshWhenHidden?: boolean;- /** Keep polling while the browser is offline. */- refreshWhenOffline?: boolean;- revalidateIfStale?: boolean;- revalidateOnFocus?: boolean;- /**- * Whether the first mount fetches. `false` leaves the first request to an- * explicit `revalidate`, for a read whose input outside the sync key is not- * ready yet. SWR only honors it on the first mount: a later key change still- * fetches when the new key has no cached data.- */- revalidateOnMount?: boolean;- revalidateOnReconnect?: boolean;-}--export interface ReplicaQueryOptions<T> extends ReplicaSyncSchedule {- /** Run once per key: no refetch on focus, reconnect or remount (hydration reads). */- once?: boolean;- onError?: (error: unknown) => void;- onSuccess?: (data: T) => void;-}--export interface ReplicaQueryResult<T> {- data?: T;- error?: unknown;- isValidating: boolean;- /** Re-run this query. */- mutate: () => Promise<unknown>;-}--/**- * The query cache that schedules a replica's fetches: dedupe, focus /- * reconnect revalidation, retries. The replica decides what a response means;- * the driver only decides when to ask. `createSWRDriver` adapts SWR.- */-export interface ReplicaSyncDriver {- /** Re-run every mounted query whose key matches. */- revalidate: (match: (key: unknown) => boolean) => Promise<unknown>;- /**- * Write a head response that `slice.fetch` requested outside `useQuery` into- * the query cache under its sync key, without re-running the query β so a- * `useQuery` of that key sees the latest data (a `revalidateIfStale: false`- * mount does not refetch it). Optional: a driver without a cache of its own- * leaves it out; requests still dedupe in the slice.- *- * The slice calls it only while no `useQuery` request of the key is in- * flight. A cache that discards in-flight requests a write overtakes (SWR- * does) would otherwise drop a newer response than the one written.- */- seed?: (key: readonly unknown[], data: unknown) => void;- useQuery: <T>(- key: readonly unknown[] | null,- fetcher: () => Promise<T>,- options: ReplicaQueryOptions<T>,- ) => ReplicaQueryResult<T>;-}--type SWRLikeHook = (- key: any,- fetcher: any,- config?: any,-) => { data?: any; error?: unknown; isValidating: boolean; mutate: () => Promise<any> };--/**- * Driver over SWR. Pass the app's own hook and scoped `mutate` when it wraps- * SWR (custom cache provider, key augmentation, retry policy).- */-export const createSWRDriver = ({- mutate,- useSWR,-}: {- /**- * SWR's (scoped) `mutate`. Called as `mutate(match)` to revalidate, and as- * `mutate(key, data, { revalidate: false })` to seed β pass the arguments- * through unchanged: SWR tells a revalidation from a write by their count.- */- mutate: (- ...args: [match: (key: any) => boolean] | [key: unknown, data: unknown, options: object]- ) => Promise<unknown>;- useSWR: SWRLikeHook;-}): ReplicaSyncDriver => ({- revalidate: (match) => mutate(match),- // Populate the cache only: re-running the query would refetch what was just fetched.- seed: (key, data) => {- void mutate(key, data, { revalidate: false }).catch(() => undefined);- },- useQuery: (key, fetcher, { once, onError, onSuccess, ...schedule }) =>- useSWR(key, fetcher, {- ...Object.fromEntries(Object.entries(schedule).filter(([, value]) => value !== undefined)),- ...(once && {- revalidateIfStale: false,- revalidateOnFocus: false,- revalidateOnReconnect: false,- }),- ...(onError && { onError: (error: unknown) => onError(error) }),- ...(onSuccess && { onSuccess: (data: unknown) => onSuccess(data as never) }),- }),-});diff --git a/packages/replica/src/zustand/index.ts b/packages/replica/src/zustand/index.tsdeleted file mode 100644index 4862ffd3922..00000000000--- a/packages/replica/src/zustand/index.ts+++ /dev/null@@ -1,2 +0,0 @@-export * from './createReplicaSlice';-export * from './driver';diff --git a/packages/replica/src/zustand/pagedSlice.direction.test.ts b/packages/replica/src/zustand/pagedSlice.direction.test.tsdeleted file mode 100644index 545e46d14ed..00000000000--- a/packages/replica/src/zustand/pagedSlice.direction.test.ts+++ /dev/null@@ -1,99 +0,0 @@-import { describe, expect, it, vi } from 'vitest';-import { createStore } from 'zustand/vanilla';--import { testDriver as driver } from '../../tests/testDriver';-import { definePagedReplica } from '../core/defineReplica';-import type { ReplicaPagedData, ReplicaPageResult } from '../core/paging';-import { createReplicaState } from '../core/reducer';-import type { ReplicaScope, ReplicaState } from '../core/types';-import { createReplicaSlice, recordLens } from './createReplicaSlice';--interface Row {- id: string;-}-interface Params {- forward: boolean;- topic: string;-}-type Paged = ReplicaPagedData<Row, string>;-interface TestState {- rows: Record<string, Paged>;- rowsReplica: ReplicaState<Paged>;-}--const scope: ReplicaScope = { canPersist: () => false, get: () => 'user-1', use: () => 'user-1' };--const page = (items: string[], nextCursor: string | null): ReplicaPageResult<Row, string> => ({- items: items.map((id) => ({ id })),- nextCursor,-});--const setup = () => {- const fetchPage = vi.fn(async ({ forward }: Params, cursor?: string) =>- forward- ? cursor === 'after-b'- ? page(['c', 'd'], null)- : page(['a', 'b'], 'after-b')- : cursor === 'before-c'- ? page(['a', 'b'], null)- : page(['c', 'd'], 'before-c'),- );- const resource = definePagedReplica<Params, Row, string>({- fetchPage,- key: ({ forward, topic }) => `${forward ? 'f' : 'b'}:${topic}`,- name: 'directionTest',- paging: {- direction: 'backward',- directionOf: (key) => (key.startsWith('f:') ? 'forward' : 'backward'),- getId: (item) => item.id,- mode: 'cursor',- },- scope,- version: 1,- });- const store = createStore<TestState>()(() => ({ rows: {}, rowsReplica: createReplicaState() }));- const slice = createReplicaSlice(resource, {- driver,- get: store.getState,- set: (partial) => store.setState(partial),- stateKey: 'rowsReplica',- view: recordLens<TestState, Paged>('rows'),- });- return { slice, store };-};--const ids = (data?: Paged) => data?.items.map((item) => item.id);--describe('paged replica direction per key', () => {- it('appends the next page after the head for a forward key', async () => {- const { slice, store } = setup();- const params = { forward: true, topic: 't1' };-- slice.replace(params, page(['a', 'b'], 'after-b'));- await slice.loadMore('f:t1', params);-- expect(ids(store.getState().rows['f:t1'])).toEqual(['a', 'b', 'c', 'd']);- expect(store.getState().rows['f:t1']).toMatchObject({ hasMore: false });- });-- it('keeps prepending older pages for a key the resolver leaves backward', async () => {- const { slice, store } = setup();- const params = { forward: false, topic: 't1' };-- slice.replace(params, page(['c', 'd'], 'before-c'));- await slice.loadMore('b:t1', params);-- expect(ids(store.getState().rows['b:t1'])).toEqual(['a', 'b', 'c', 'd']);- });-- it('keeps appended pages when a forward head is refreshed', async () => {- const { slice, store } = setup();- const params = { forward: true, topic: 't1' };-- slice.replace(params, page(['a', 'b'], 'after-b'));- await slice.loadMore('f:t1', params);- slice.replace(params, page(['a', 'b'], 'after-b'));-- expect(ids(store.getState().rows['f:t1'])).toEqual(['a', 'b', 'c', 'd']);- });-});diff --git a/packages/replica/src/zustand/pagedSlice.test.ts b/packages/replica/src/zustand/pagedSlice.test.tsdeleted file mode 100644index 8d809b68f55..00000000000--- a/packages/replica/src/zustand/pagedSlice.test.ts+++ /dev/null@@ -1,529 +0,0 @@-import { beforeEach, describe, expect, it, vi } from 'vitest';-import { createStore } from 'zustand/vanilla';--import { testDriver as driver } from '../../tests/testDriver';-import { definePagedReplica, defineReplica } from '../core/defineReplica';-import { REPLICA_INDEX_KEY } from '../core/engine';-import { linkReplicaEntity } from '../core/entity';-import { singleEntity } from '../core/entityAdapters';-import type { ReplicaPagedData, ReplicaPageResult } from '../core/paging';-import { createReplicaState } from '../core/reducer';-import type { ReplicaRow, ReplicaScope, ReplicaState, ReplicaStorage } from '../core/types';-import { createReplicaSlice, recordLens } from './createReplicaSlice';--interface Row {- id: string;- title: string;-}-interface Params {- filter?: string;- owner: string;- pageSize: number;-}-type Paged = ReplicaPagedData<Row, number> & { filter?: string };--interface TestState {- details: Record<string, Row>;- detailsReplica: ReplicaState<Row>;- lists: Record<string, Paged>;- listsReplica: ReplicaState<Paged>;-}--const scopeState = { current: 'user-1' };-const scope: ReplicaScope = {- canPersist: () => true,- get: () => scopeState.current,- use: () => scopeState.current,-};--const createMemoryStorage = <T>() => {- const rows = new Map<string, ReplicaRow<T>>();- const read: ReplicaStorage<T>['get'] = async ({ queryKey, scope }) =>- rows.get(`${scope}|${queryKey}`);- const storage: ReplicaStorage<T> = {- get: read,- getStrict: read,- remove: async ({ queryKey, scope }) => {- rows.delete(`${scope}|${queryKey}`);- },- set: async ({ queryKey, scope }, projection) => {- rows.set(`${scope}|${queryKey}`, projection);- },- };- return { rows, storage };-};--const row = (id: string, title = id): Row => ({ id, title });-const ids = (data?: { items: Row[] }) => data?.items.map((item) => item.id);-const deferred = <T>() => {- let resolve!: (value: T) => void;- let reject!: (error: unknown) => void;- const promise = new Promise<T>((res, rej) => {- resolve = res;- reject = rej;- });- return { promise, reject, resolve };-};--/** Server with 2-row pages over `a..e` (or a filtered set). */-const pageOf = (params: Params, cursor = 0): ReplicaPageResult<Row, number> => {- const all = (params.filter === 'odd' ? ['a', 'c', 'e'] : ['a', 'b', 'c', 'd', 'e']).map((id) =>- row(id),- );- return {- items: all.slice(cursor * params.pageSize, (cursor + 1) * params.pageSize),- total: all.length,- };-};--const setup = (- fetchPage = vi.fn(async (params: Params, cursor?: number) => pageOf(params, cursor)),- {- detailStorage = createMemoryStorage<Row>(),- listStorage = createMemoryStorage<Paged>(),- }: {- detailStorage?: ReturnType<typeof createMemoryStorage<Row>>;- listStorage?: ReturnType<typeof createMemoryStorage<Paged>>;- } = {},-) => {- const listResource = definePagedReplica<Params, Row, number, Paged>({- fetchPage,- key: ({ owner }) => owner,- name: 'pagedTest',- paging: { direction: 'forward', getId: (item) => item.id, mode: 'offset' },- query: ({ filter }) => ({ filter }),- scope,- storage: listStorage.storage,- version: 1,- });- const detailResource = defineReplica<string, Row>({- key: (id) => id,- name: 'detailTest',- scope,- storage: detailStorage.storage,- version: 1,- });- const store = createStore<TestState>()(() => ({- details: {},- detailsReplica: createReplicaState(),- lists: {},- listsReplica: createReplicaState(),- }));- const list = createReplicaSlice(listResource, {- driver,- get: store.getState,- isClientOnly: (item: Row) => item.id.startsWith('tmp'),- set: (partial) => store.setState(partial),- stateKey: 'listsReplica',- view: recordLens<TestState, Paged>('lists'),- viewFields: ({ filter }) => ({ filter }),- });- const detail = createReplicaSlice(detailResource, {- driver,- entity: singleEntity<Row>((item) => item.id),- get: store.getState,- set: (partial) => store.setState(partial),- stateKey: 'detailsReplica',- view: recordLens<TestState, Row>('details'),- });- return { detail, detailStorage, fetchPage, list, listResource, listStorage, store };-};--const params: Params = { owner: 'o1', pageSize: 2 };--beforeEach(() => {- scopeState.current = 'user-1';-});--describe('paged replica slice', () => {- it('loadMore pages with the stored head params and dedupes by id', async () => {- const { fetchPage, list, store } = setup();- list.replace(params, pageOf(params));- await list.loadMore('o1');- expect(fetchPage).toHaveBeenLastCalledWith(params, 1);- expect(ids(store.getState().lists.o1)).toEqual(['a', 'b', 'c', 'd']);- expect(store.getState().lists.o1).toMatchObject({ currentPage: 1, hasMore: true });- });-- it('drops a page that lands after the query changed', async () => {- const pending = deferred<ReplicaPageResult<Row, number>>();- const { list, store } = setup(- vi.fn(async (p: Params, cursor?: number) => (cursor ? pending.promise : pageOf(p, cursor))),- );- list.replace(params, pageOf(params));- const loading = list.loadMore('o1');- expect(store.getState().lists.o1.isLoadingMore).toBe(true);-- const odd = { ...params, filter: 'odd' };- list.replace(odd, pageOf(odd));- // Head refresh while the page is in flight keeps the flag.- expect(store.getState().lists.o1).toMatchObject({ filter: 'odd', isLoadingMore: true });-- pending.resolve(pageOf(params, 1));- await loading;- expect(ids(store.getState().lists.o1)).toEqual(['a', 'c']);- expect(store.getState().lists.o1.isLoadingMore).toBe(false);- });-- it('a head refresh with no page in flight clears a stale loading flag', () => {- const { list, store } = setup();- list.replace(params, pageOf(params));- list.update('o1', (data) => data && { ...data, isLoadingMore: true }, { persist: false });- list.replace(params, { items: [row('z'), row('a')], total: 6 });- expect(store.getState().lists.o1.isLoadingMore).toBe(false);- });-- it('a scope switch clears loaded pages and drops the late page', async () => {- const pending = deferred<ReplicaPageResult<Row, number>>();- const { list, store } = setup(- vi.fn(async (p: Params, cursor?: number) => (cursor ? pending.promise : pageOf(p, cursor))),- );- list.replace(params, pageOf(params));- const loading = list.loadMore('o1');-- scopeState.current = 'user-2';- list.ensureScope('user-2');- expect(store.getState().lists).toEqual({});-- pending.resolve(pageOf(params, 1));- await loading;- expect(store.getState().lists).toEqual({});- });-- it('rolls back an optimistic patch without losing a page loaded meanwhile', async () => {- const { list, store } = setup();- list.replace(params, pageOf(params));- const server = deferred<void>();-- const write = list- .optimistic(- 'o1',- (data) => ({ ...data, items: data.items.map((r) => (r.id === 'a' ? row('a', 'A!') : r)) }),- () => server.promise,- )- .catch(() => undefined);- expect(store.getState().lists.o1.items[0].title).toBe('A!');-- await list.loadMore('o1');- expect(ids(store.getState().lists.o1)).toEqual(['a', 'b', 'c', 'd']);-- server.reject(new Error('nope'));- await write;- expect(store.getState().lists.o1.items[0].title).toBe('a');- expect(ids(store.getState().lists.o1)).toEqual(['a', 'b', 'c', 'd']);- });-- it('persists the head page per query; another query never hydrates it', async () => {- const { list, listResource, listStorage, store } = setup();- list.replace(params, pageOf(params));- await list.loadMore('o1');- await vi.waitFor(() =>- expect(listStorage.rows.get(`user-1|${listResource.storageKey(params)}`)).toBeDefined(),- );- const persisted = listStorage.rows.get(`user-1|${listResource.storageKey(params)}`)!;- expect(ids(persisted.data)).toEqual(['a', 'b']);-- // Fresh store: the filtered query misses, the original query hydrates.- const reloaded = setup();- reloaded.listStorage.rows.set(`user-1|${listResource.storageKey(params)}`, persisted);- expect(await reloaded.list.hydrate({ ...params, filter: 'odd' })).toBe(false);- expect(await reloaded.list.hydrate(params)).toBe(true);- expect(ids(reloaded.store.getState().lists.o1)).toEqual(['a', 'b']);- expect(store).toBeDefined();- });-- it('insertHead keeps client-only rows across refreshes but out of storage', async () => {- const { list, listResource, listStorage, store } = setup();- list.replace(params, pageOf(params));- list.insertHead('o1', [row('tmp-1')]);- list.replace(params, pageOf(params));- expect(ids(store.getState().lists.o1)).toEqual(['tmp-1', 'a', 'b']);- await vi.waitFor(() => {- const persisted = listStorage.rows.get(`user-1|${listResource.storageKey(params)}`);- expect(ids(persisted?.data)).toEqual(['a', 'b']);- });- });-});--describe('linkReplicaEntity', () => {- const seeded = () => {- const ctx = setup();- ctx.list.replace(params, pageOf(params));- ctx.list.replace({ owner: 'o2', pageSize: 2 }, { items: [row('a'), row('x')], total: 2 });- ctx.detail.replace('a', row('a'));- const topic = linkReplicaEntity<Row>([ctx.list, ctx.detail]);- return { ...ctx, topic };- };-- it('propagates a patch to every resource and key holding the entity', () => {- const { store, topic } = seeded();- topic.update('a', (r) => ({ ...r, title: 'renamed' }));- const state = store.getState();- expect(state.lists.o1.items[0].title).toBe('renamed');- expect(state.lists.o2.items[0].title).toBe('renamed');- expect(state.details.a.title).toBe('renamed');- expect(state.lists.o1.items[1].title).toBe('b');- });-- it('removes the entity everywhere and fixes list totals', () => {- const { store, topic } = seeded();- topic.remove('a');- const state = store.getState();- expect(ids(state.lists.o1)).toEqual(['b']);- expect(state.lists.o1.total).toBe(4);- expect(state.details.a).toBeUndefined();- });-- it('an optimistic write commits or rolls back across all resources together', async () => {- const { store, topic } = seeded();- const rename = (r: Row) => ({ ...r, title: 'opt' });-- await expect(- topic.optimistic('a', rename, async () => {- expect(store.getState().details.a.title).toBe('opt');- expect(store.getState().lists.o2.items[0].title).toBe('opt');- throw new Error('server down');- }),- ).rejects.toThrow('server down');- expect(store.getState().details.a.title).toBe('a');- expect(store.getState().lists.o1.items[0].title).toBe('a');-- await topic.optimistic('a', rename, async () => 'ok');- expect(store.getState().details.a.title).toBe('opt');- expect(store.getState().listsReplica.entries.o1.pending).toHaveLength(0);- });-- it('an optimistic delete hides list rows at once and drops the detail on commit', async () => {- const { store, topic } = seeded();- const server = deferred<void>();- const removal = topic.optimistic('a', 'remove', () => server.promise);- expect(ids(store.getState().lists.o1)).toEqual(['b']);- expect(store.getState().details.a).toBeDefined();- server.resolve();- await removal;- expect(store.getState().details.a).toBeUndefined();- expect(ids(store.getState().lists.o2)).toEqual(['x']);- });-});--describe('entity changes for entries that are not loaded', () => {- /** Session 1 persists `o1` (list) and `a` (detail); session 2 starts with empty memory. */- const persistedThenReloaded = async () => {- const first = setup();- first.list.replace(params, pageOf(params));- first.detail.replace('a', row('a'));- const listKey = `user-1|${first.listResource.storageKey(params)}`;- await vi.waitFor(() => {- expect(first.listStorage.rows.get(listKey)).toBeDefined();- expect(first.detailStorage.rows.get('user-1|a')).toBeDefined();- });- const second = setup(undefined, {- detailStorage: first.detailStorage,- listStorage: first.listStorage,- });- const topic = linkReplicaEntity<Row>([second.list, second.detail]);- return { ...second, listKey, topic };- };-- it('patches persisted rows of unloaded entries', async () => {- const { detailStorage, listKey, listStorage, store, topic } = await persistedThenReloaded();- topic.update('a', (r) => ({ ...r, title: 'done' }));- expect(store.getState().lists).toEqual({});- await vi.waitFor(() => {- expect(listStorage.rows.get(listKey)?.data.items[0].title).toBe('done');- expect(detailStorage.rows.get('user-1|a')?.data.title).toBe('done');- });- expect(listStorage.rows.get(listKey)?.data.items[1].title).toBe('b');- });-- it('removes the entity from unloaded persisted rows and never resurrects them', async () => {- const { detailStorage, listKey, listStorage, topic } = await persistedThenReloaded();- topic.remove('a');- await vi.waitFor(() => {- expect(ids(listStorage.rows.get(listKey)?.data)).toEqual(['b']);- expect(detailStorage.rows.has('user-1|a')).toBe(false);- });- expect(listStorage.rows.get(listKey)?.data.total).toBe(4);-- // A later patch of the removed entity must not recreate its detail row.- topic.update('a', (r) => ({ ...r, title: 'ghost' }));- await new Promise((resolve) => setTimeout(resolve, 10));- expect(detailStorage.rows.has('user-1|a')).toBe(false);- });-- it('a committed optimistic write also reaches unloaded rows', async () => {- const { listKey, listStorage, topic } = await persistedThenReloaded();- await topic.optimistic(- 'a',- (r) => ({ ...r, title: 'opt' }),- async () => 'ok',- );- await vi.waitFor(() => expect(listStorage.rows.get(listKey)?.data.items[0].title).toBe('opt'));- });-- it('never touches rows of another scope', async () => {- const { listKey, listStorage, topic } = await persistedThenReloaded();- scopeState.current = 'user-2';- topic.update('a', (r) => ({ ...r, title: 'other-user' }));- await new Promise((resolve) => setTimeout(resolve, 10));- expect(listStorage.rows.get(listKey)?.data.items[0].title).toBe('a');- });-});--describe('entity removals vs reads in flight', () => {- /** Hold every `get` of `storage` for `queryKey` until released (the row is read first). */- const holdReads = <T>(storage: ReplicaStorage<T>, queryKey: string) => {- const originalGet = storage.get;- let release!: () => void;- const held = new Promise<void>((resolve) => (release = resolve));- storage.get = async (key) => {- const value = await originalGet(key);- if (key.queryKey === queryKey) await held;- return value;- };- return () => release();- };-- const persisted = async () => {- const first = setup();- first.list.replace(params, pageOf(params));- first.detail.replace('a', row('a'));- await vi.waitFor(() => {- expect(- first.listStorage.rows.get(`user-1|${first.listResource.storageKey(params)}`),- ).toBeDefined();- expect(first.detailStorage.rows.get('user-1|a')).toBeDefined();- });- const second = setup(undefined, {- detailStorage: first.detailStorage,- listStorage: first.listStorage,- });- return { ...second, topic: linkReplicaEntity<Row>([second.list, second.detail]) };- };-- it('a hydrate that read its row before the entity was deleted paints it without the entity', async () => {- const { detail, detailStorage, list, listResource, listStorage, store, topic } =- await persisted();- const releaseList = holdReads(listStorage.storage, listResource.storageKey(params));- const releaseDetail = holdReads(detailStorage.storage, 'a');-- const listHydrate = list.hydrate(params);- const detailHydrate = detail.hydrate('a');- await new Promise((resolve) => setTimeout(resolve, 0));- topic.remove('a');- releaseList();- releaseDetail();- await Promise.all([listHydrate, detailHydrate]);-- expect(ids(store.getState().lists.o1)).toEqual(['b']);- expect(store.getState().lists.o1.total).toBe(4);- expect(store.getState().details.a).toBeUndefined();- });-- it('an explicit slice.removeEntity beats a hydrate already reading', async () => {- const { list, listResource, listStorage, store } = await persisted();- const release = holdReads(listStorage.storage, listResource.storageKey(params));-- const hydration = list.hydrate(params);- await new Promise((resolve) => setTimeout(resolve, 0));- list.removeEntity('a');- release();- await hydration;-- expect(ids(store.getState().lists.o1)).toEqual(['b']);- });-- it('updateEntity with a mapper returning undefined still deletes, whatever its arity', async () => {- const { list, listResource, listStorage, store } = await persisted();- list.replace({ owner: 'o2', pageSize: 2 }, { items: [row('a'), row('x')], total: 2 });-- list.updateEntity<Row>('a', (_item) => undefined);-- expect(ids(store.getState().lists.o2)).toEqual(['x']);- // The unloaded persisted row loses it too.- await vi.waitFor(() =>- expect(ids(listStorage.rows.get(`user-1|${listResource.storageKey(params)}`)?.data)).toEqual([- 'b',- ]),- );- });-- it('never invokes an entity mapper speculatively', () => {- const ctx = setup();- ctx.list.replace(params, pageOf(params));- const mapper = vi.fn(() => row('a', 'renamed'));-- ctx.list.updateEntity<Row>('a', mapper, { persist: false });-- // Once to probe the loaded value, once inside the confirmed update.- expect(mapper).toHaveBeenCalledTimes(2);- expect(ctx.store.getState().lists.o1.items[0].title).toBe('renamed');- });-- it('keeps every guard a pending hydrate needs, however many, and releases them after', async () => {- const { list, listResource, listStorage, store } = await persisted();- const many = { owner: 'o9', pageSize: 600 };- const items = Array.from({ length: 600 }, (_, index) => row(`x${index}`));- listStorage.rows.set(`user-1|${listResource.storageKey(many)}`, {- data: { currentPage: 0, hasMore: false, items, pageSize: 600, total: 600 },- updatedAt: 1,- });- const release = holdReads(listStorage.storage, listResource.storageKey(many));-- const hydration = list.hydrate(many);- await new Promise((resolve) => setTimeout(resolve, 0));- // A batch delete larger than any fixed window, while the read is pending.- for (const item of items) list.removeEntity(item.id);- await new Promise((resolve) => setTimeout(resolve, 10));- release();- await hydration;- expect(ids(store.getState().lists.o9)).toEqual([]);-- // Once that read settled the guards are released: a row this session never- // patched (not indexed) hydrates as stored.- const later = { owner: 'o10', pageSize: 2 };- listStorage.rows.set(`user-1|${listResource.storageKey(later)}`, {- data: { currentPage: 0, hasMore: false, items: [row('x0')], pageSize: 2, total: 1 },- updatedAt: 1,- });- await list.hydrate(later);- expect(ids(store.getState().lists.o10)).toEqual(['x0']);- });-- it('a server value holding the entity again lifts the removal', async () => {- const { list, listResource, listStorage, store, topic } = await persisted();- topic.remove('a');- // Restored on the server: a head response holds it again.- list.replace(params, pageOf(params));- expect(ids(store.getState().lists.o1)).toEqual(['a', 'b']);-- // Another entry persisted with the entity hydrates it as stored.- const other = { owner: 'o3', pageSize: 2 };- listStorage.rows.set(`user-1|${listResource.storageKey(other)}`, {- data: { currentPage: 0, hasMore: false, items: [row('a')], pageSize: 2, total: 1 },- updatedAt: 1,- });- await list.hydrate(other);- expect(ids(store.getState().lists.o3)).toEqual(['a']);- });-});--describe('linkReplicaEntity.clear', () => {- it('wipes every linked resource in memory and storage', async () => {- const ctx = setup();- ctx.list.replace(params, pageOf(params));- ctx.detail.replace('a', row('a'));- await vi.waitFor(() => expect(ctx.detailStorage.rows.get('user-1|a')).toBeDefined());- const topic = linkReplicaEntity<Row>([ctx.list, ctx.detail]);-- const purge = topic.clear();- expect(ctx.store.getState().lists).toEqual({});- expect(ctx.store.getState().details).toEqual({});- expect(await purge).toBe(true);- // Only the (emptied) index rows remain.- const dataRows = (rows: Map<string, unknown>) =>- [...rows.keys()].filter((key) => !key.endsWith(REPLICA_INDEX_KEY));- expect(dataRows(ctx.listStorage.rows)).toEqual([]);- expect(dataRows(ctx.detailStorage.rows)).toEqual([]);- });-});diff --git a/packages/replica/src/zustand/splitPagedLens.test.ts b/packages/replica/src/zustand/splitPagedLens.test.tsdeleted file mode 100644index 2653db4a1b9..00000000000--- a/packages/replica/src/zustand/splitPagedLens.test.ts+++ /dev/null@@ -1,204 +0,0 @@-import { describe, expect, it } from 'vitest';-import { createStore } from 'zustand/vanilla';--import { testDriver as driver } from '../../tests/testDriver';-import { definePagedReplica } from '../core/defineReplica';-import type { ReplicaPagedData } from '../core/paging';-import { createReplicaState } from '../core/reducer';-import type { ReplicaRow, ReplicaScope, ReplicaState, ReplicaStorage } from '../core/types';-import { createReplicaSlice, splitPagedLens } from './createReplicaSlice';--/**- * A transcript-shaped host: raw rows in `rowsMap` (what existing readers use),- * paging bookkeeping beside them, and a display list derived from the rows.- */-interface Message {- createdAt: number;- id: string;-}-interface TestState {- displayMap: Record<string, string[]>;- pagingMap: Record<string, Omit<ReplicaPagedData<Message, number>, 'items'>>;- replica: ReplicaState<ReplicaPagedData<Message, number>>;- rowsMap: Record<string, Message[]>;-}--const scope: ReplicaScope = { canPersist: () => true, get: () => 'u1', use: () => 'u1' };--const memoryStorage = () => {- const rows = new Map<string, ReplicaRow<any>>();- const storage: ReplicaStorage<any> = {- get: async ({ queryKey, scope }) => rows.get(`${scope}|${queryKey}`),- remove: async ({ queryKey, scope }) => void rows.delete(`${scope}|${queryKey}`),- set: async ({ queryKey, scope }, row) => void rows.set(`${scope}|${queryKey}`, row),- };- return { rows, storage };-};--const msg = (n: number): Message => ({ createdAt: n, id: `m${n}` });-const flush = () => new Promise((resolve) => setTimeout(resolve, 0));--const setup = () => {- const { rows, storage } = memoryStorage();- const resource = definePagedReplica<{ topic: string }, Message, number>({- key: ({ topic }) => topic,- name: 'transcript',- paging: { direction: 'backward', getId: (m) => m.id, mode: 'cursor' },- // Scoped buckets (e.g. a page copilot) stay in memory.- persistKey: (key) => !key.startsWith('scoped:'),- scope,- storage,- version: 1,- });- const store = createStore<TestState>()(() => ({- displayMap: {},- pagingMap: {},- replica: createReplicaState(),- rowsMap: {},- }));- const slice = createReplicaSlice(resource, {- driver,- get: store.getState,- set: (partial) => store.setState(partial),- stateKey: 'replica',- view: splitPagedLens<TestState, Message, number>({- clearDerived: () => ({ displayMap: {} }),- derive: (state, key, items) => {- const displayMap = { ...state.displayMap };- if (items) displayMap[key] = items.map((m) => m.id.toUpperCase());- else delete displayMap[key];- return { displayMap };- },- itemsField: 'rowsMap',- metaField: 'pagingMap',- }),- });- return { rows, slice, store };-};--describe('splitPagedLens', () => {- it('keeps raw rows, bookkeeping and the derived list in step', () => {- const { slice, store } = setup();-- slice.replace({ topic: 't1' }, { items: [msg(1), msg(2)], nextCursor: 1 });-- const state = store.getState();- expect(state.rowsMap.t1.map((m) => m.id)).toEqual(['m1', 'm2']);- expect(state.pagingMap.t1).toMatchObject({ currentPage: 0, nextCursor: 1 });- expect(state.displayMap.t1).toEqual(['M1', 'M2']);- });-- it('reads an unchanged entry as the same view object', () => {- const { slice, store } = setup();- slice.replace({ topic: 't1' }, { items: [msg(1)], nextCursor: null });- const before = store.getState().rowsMap;-- // Folding the identical page in again is a no-op for readers.- slice.replace({ topic: 't1' }, { items: [msg(1)], nextCursor: null });- slice.update('t1', (data) => data);-- expect(store.getState().rowsMap).toBe(before);- });-- it('treats rows seeded without bookkeeping as a head page', () => {- const { slice, store } = setup();- store.setState({ rowsMap: { t1: [msg(1)] } });-- slice.updateEntity<Message>('m1', (m) => ({ ...m, createdAt: 9 }), { persist: false });-- expect(store.getState().rowsMap.t1[0].createdAt).toBe(9);- expect(store.getState().displayMap.t1).toEqual(['M1']);- });-- it('drops derived fields with the entry', () => {- const { slice, store } = setup();- slice.replace({ topic: 't1' }, { items: [msg(1)], nextCursor: null });-- slice.remove('t1');- expect(store.getState().displayMap.t1).toBeUndefined();- expect(store.getState().rowsMap.t1).toBeUndefined();- });-});--describe('prepareHead', () => {- it('reconciles a head page with the shown rows, or drops it', () => {- const resource = definePagedReplica<{ topic: string }, Message, number>({- key: ({ topic }) => topic,- name: 'preparedTranscript',- paging: { direction: 'backward', getId: (m) => m.id, mode: 'cursor' },- scope,- version: 1,- });- const store = createStore<TestState>()(() => ({- displayMap: {},- pagingMap: {},- replica: createReplicaState(),- rowsMap: {},- }));- let dropNext = false;- const slice = createReplicaSlice(resource, {- driver,- get: store.getState,- // Keep a locally newer row (higher createdAt) over the server's copy.- prepareHead: (page, current) => {- if (dropNext) return undefined;- const local = new Map(current?.items.map((m) => [m.id, m]));- return {- ...page,- items: page.items.map((m) => {- const mine = local.get(m.id);- return mine && mine.createdAt > m.createdAt ? mine : m;- }),- };- },- set: (partial) => store.setState(partial),- stateKey: 'replica',- view: splitPagedLens<TestState, Message, number>({- itemsField: 'rowsMap',- metaField: 'pagingMap',- }),- });-- slice.replace({ topic: 't1' }, { items: [msg(1)], nextCursor: null });- slice.update('t1', (data) => data && { ...data, items: [{ createdAt: 9, id: 'm1' }] });- slice.replace({ topic: 't1' }, { items: [msg(1), msg(2)], nextCursor: null });- expect(store.getState().rowsMap.t1).toEqual([{ createdAt: 9, id: 'm1' }, msg(2)]);-- dropNext = true;- expect(slice.replace({ topic: 't1' }, { items: [], nextCursor: null })).toBe(false);- expect(store.getState().rowsMap.t1).toHaveLength(2);- });-});--describe('persistKey and persist()', () => {- it('never persists or hydrates a key the resource keeps in memory', async () => {- const { rows, slice } = setup();-- slice.replace({ topic: 'scoped:page-1' }, { items: [msg(1)], nextCursor: null });- slice.replace({ topic: 't1' }, { items: [msg(1)], nextCursor: null });- await flush();-- expect(rows.has('u1|scoped:page-1')).toBe(false);- expect(rows.has('u1|t1')).toBe(true);- expect(await slice.hydrate({ topic: 'scoped:page-1' })).toBe(false);- });-- it('flushes in-memory writes (a finished stream) in one persist', async () => {- const { rows, slice } = setup();- slice.replace({ topic: 't1' }, { items: [msg(1)], nextCursor: null });- await flush();-- for (const n of [2, 3, 4]) slice.insertHead('t1', [msg(n)]);- await flush();- expect(rows.get('u1|t1')?.data.items).toHaveLength(1);-- slice.persist('t1');- await flush();- expect(rows.get('u1|t1')?.data.items.map((m: Message) => m.id)).toEqual([- 'm1',- 'm2',- 'm3',- 'm4',- ]);- });-});diff --git a/packages/replica/src/zustand/testUtils.ts b/packages/replica/src/zustand/testUtils.tsdeleted file mode 100644index 04f136da815..00000000000--- a/packages/replica/src/zustand/testUtils.ts+++ /dev/null@@ -1,95 +0,0 @@-import type { PropsWithChildren } from 'react';-import { createElement } from 'react';-import { SWRConfig } from 'swr';-import { vi } from 'vitest';-import { createStore } from 'zustand/vanilla';--import { testDriver as driver } from '../../tests/testDriver';-import { defineReplica } from '../core/defineReplica';-import { REPLICA_INDEX_KEY } from '../core/engine';-import { createReplicaState } from '../core/reducer';-import type { ReplicaRow, ReplicaScope, ReplicaState, ReplicaStorage } from '../core/types';-import { createReplicaSlice, recordLens } from './createReplicaSlice';--export interface TestState {- lists: Record<string, string[]>;- listsReplica: ReplicaState<string[]>;-}--export const scopeState = { canHydrate: true, current: 'user-1:personal', trusted: true };-export const scope: ReplicaScope = {- canHydrate: () => scopeState.canHydrate,- canPersist: () => scopeState.trusted,- get: () => scopeState.current,- // The real `use` is `useCacheScope`; a plain getter is enough for these tests.- use: () => scopeState.current,-};--/** In-memory storage that records every write, keyed like the real ones. */-export const createMemoryStorage = (delays: Record<string, number> = {}) => {- const rows = new Map<string, ReplicaRow<string[]>>();- const writes: string[] = [];- const indexRows = new Map<string, ReplicaRow<string[]>>();- const read: ReplicaStorage<string[]>['get'] = async ({ queryKey, scope }) =>- queryKey === REPLICA_INDEX_KEY- ? (indexRows.get(scope) as ReplicaRow<string[]> | undefined)- : rows.get(`${scope}|${queryKey}`);- const storage: ReplicaStorage<string[]> = {- get: read,- getStrict: read,- remove: async ({ queryKey, scope }) => {- if (queryKey === REPLICA_INDEX_KEY) return void indexRows.delete(scope);- rows.delete(`${scope}|${queryKey}`);- },- set: async ({ queryKey, scope }, projection) => {- // The per-scope index of persisted rows is bookkeeping, not a data write.- if (queryKey === REPLICA_INDEX_KEY) return void indexRows.set(scope, projection);- const delay = delays[projection.data.join(',')] ?? 0;- if (delay) await new Promise((resolve) => setTimeout(resolve, delay));- writes.push(projection.data.join(','));- rows.set(`${scope}|${queryKey}`, projection);- },- };- return { indexRows, rows, storage, writes };-};--export const setup = ({- fetcher = vi.fn(async (_params: { id: string }) => ['server']),- storage = createMemoryStorage(),- version = 1,-}: {- fetcher?: (params: { id: string }) => Promise<string[]>;- storage?: ReturnType<typeof createMemoryStorage>;- version?: number;-} = {}) => {- const resource = defineReplica<{ id: string }, string[]>({- fetcher,- key: ({ id }) => id,- name: 'testList',- scope,- storage: storage.storage,- version,- });- const store = createStore<TestState>()(() => ({- lists: {},- listsReplica: createReplicaState(),- }));- const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {- driver,- get: store.getState,- set: (partial) => store.setState(partial),- stateKey: 'listsReplica',- view: recordLens('lists'),- });- return { fetcher, resource, slice, storage, store };-};--export const wrapper = ({ children }: PropsWithChildren) =>- createElement(SWRConfig, { value: { dedupingInterval: 0, provider: () => new Map() } }, children);--/** Reset the shared scope to a trusted, hydratable `user-1:personal`. */-export const resetScopeState = () => {- scopeState.canHydrate = true;- scopeState.current = 'user-1:personal';- scopeState.trusted = true;-};diff --git a/packages/replica/tests/testDriver.ts b/packages/replica/tests/testDriver.tsdeleted file mode 100644index 71d7466dab8..00000000000--- a/packages/replica/tests/testDriver.ts+++ /dev/null@@ -1,9 +0,0 @@-import useSWR, { mutate } from 'swr';--import { createSWRDriver } from '../src/zustand/driver';--/** SWR driver for tests: plain `useSWR`, matcher revalidation and seeding on the default cache. */-export const testDriver = createSWRDriver({- mutate: (...args) => (mutate as (...args: unknown[]) => Promise<unknown>)(...args),- useSWR,-});diff --git a/packages/replica/vitest.config.mts b/packages/replica/vitest.config.mtsdeleted file mode 100644index 940870a78e9..00000000000--- a/packages/replica/vitest.config.mts+++ /dev/null@@ -1,10 +0,0 @@-import { defineConfig } from 'vitest/config';--export default defineConfig({- test: {- coverage: {- reporter: ['text', 'json', 'lcov', 'text-summary'],- },- environment: 'happy-dom',- },-});diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex 033d7c103ff..e91a3e0a92e 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -38,6 +38,7 @@ minimumReleaseAgeExclude:- '@auv-js/[email protected]'- '@lobehub/*'+ - local-replica# Build scripts run one at a time. Several peer-variant copies of# @lobehub/editor resolve in this workspace and every copy's postinstalldiff --git a/src/features/Conversation/WorkingSidebar/Files/__tests__/useRememberedFilesLocation.test.ts b/src/features/Conversation/WorkingSidebar/Files/__tests__/useRememberedFilesLocation.test.tsindex b02da1c5181..413318c5641 100644--- a/src/features/Conversation/WorkingSidebar/Files/__tests__/useRememberedFilesLocation.test.ts+++ b/src/features/Conversation/WorkingSidebar/Files/__tests__/useRememberedFilesLocation.test.ts@@ -158,7 +158,7 @@ describe('useRememberedFilesLocation', { timeout: 15_000 }, () => {});it('keeps its replica keys out of the SWR persistent cache', async () => {- const { replicaKeys } = await import('@lobechat/replica');+ const { replicaKeys } = await import('local-replica');const { unstable_serialize } = await import('swr');const { CACHE_TIERS } = await import('@/libs/swr/localStorageProvider');const { filesLocationResource } = await import('@/store/projectFile/projection');diff --git a/src/features/DevPanel/Replica/model.test.ts b/src/features/DevPanel/Replica/model.test.tsindex 5bb985fc6cf..8f6dc6ef6b0 100644--- a/src/features/DevPanel/Replica/model.test.ts+++ b/src/features/DevPanel/Replica/model.test.ts@@ -1,4 +1,4 @@-import type { ReplicaState } from '@lobechat/replica';+import type { ReplicaState } from 'local-replica';import { describe, expect, it } from 'vitest';import type { ReplicaDevtoolsEntry } from '@/libs/replica/devtools';diff --git a/src/features/ResourceManager/components/Explorer/hooks/useExplorerSearchResults.ts b/src/features/ResourceManager/components/Explorer/hooks/useExplorerSearchResults.tsindex ebecf37b4d7..a64fc2665ca 100644--- a/src/features/ResourceManager/components/Explorer/hooks/useExplorerSearchResults.ts+++ b/src/features/ResourceManager/components/Explorer/hooks/useExplorerSearchResults.ts@@ -10,7 +10,7 @@ import { type FileListItem } from '@/types/files';* Rows of the explorer's search overlay, or `searchParams: null` while no* keyword is typed.*- * Search results are a `@lobechat/replica` entry owned by the ResourceManager+ * Search results are a `local-replica` entry owned by the ResourceManager* store: the head page is persisted, so re-opening a search paints the rows it* had before the request lands. The keyword is part of the query identity, so* the painted rows are only used while they still answer the request on screen.diff --git a/src/features/ResourceManager/components/LibraryHierarchy/SearchResults.tsx b/src/features/ResourceManager/components/LibraryHierarchy/SearchResults.tsxindex ae632787234..47dc7c4f244 100644--- a/src/features/ResourceManager/components/LibraryHierarchy/SearchResults.tsx+++ b/src/features/ResourceManager/components/LibraryHierarchy/SearchResults.tsx@@ -36,7 +36,7 @@ interface SearchResultsProps {* hit opens exactly like its tree counterpart (folder β navigate, page β page* editor, file β file editor) and keeps the same context menu.*- * The rows are a `@lobechat/replica` entry owned by the ResourceManager store:+ * The rows are a `local-replica` entry owned by the ResourceManager store:* the head page is persisted, so coming back to the same search paints it* before the request lands, and "load more" appends further pages through the* engine instead of re-fetching a widening window.diff --git a/src/features/ResourceManager/store/initialState.ts b/src/features/ResourceManager/store/initialState.tsindex c4f015a6577..17b48b1cb3b 100644--- a/src/features/ResourceManager/store/initialState.ts+++ b/src/features/ResourceManager/store/initialState.ts@@ -30,7 +30,7 @@ export type ResourceListVisibilityFilter = 'private' | 'workspace';export const DEFAULT_WORKSPACE_LIST_VISIBILITY: ResourceListVisibilityFilter = 'workspace';/**- * The ResourceManager's two search surfaces as `@lobechat/replica` views.+ * The ResourceManager's two search surfaces as `local-replica` views.** Both were bare `useClientDataSWR` entries before: the rows only lived in the* SWR cache, so re-opening a search (or coming back to the surface) had to waitdiff --git a/src/features/ResourceManager/store/replica.test.ts b/src/features/ResourceManager/store/replica.test.tsindex 15ff27b4319..3d92e1f4da9 100644--- a/src/features/ResourceManager/store/replica.test.ts+++ b/src/features/ResourceManager/store/replica.test.ts@@ -1,7 +1,7 @@/*** @vitest-environment happy-dom*- * The ResourceManager's two search surfaces are `@lobechat/replica` paged+ * The ResourceManager's two search surfaces are `local-replica` paged* resources owned by the feature store: the persisted head page paints before* the network answers, the response confirms and persists it, "load more"* appends through the engine, and a new keyword repaints from its own head pagediff --git a/src/hooks/usePrefetchPage.ts b/src/hooks/usePrefetchPage.tsindex 83e566b31ef..6657cf0ce04 100644--- a/src/hooks/usePrefetchPage.ts+++ b/src/hooks/usePrefetchPage.ts@@ -8,7 +8,7 @@ import { useDocumentStore } from '@/store/document';* paints from the projection instead of a skeleton.** The Pages sidebar list is no longer an SWR cache entry β it is a- * `@lobechat/replica` resource that hydrates from IndexedDB on mount β so only+ * `local-replica` resource that hydrates from IndexedDB on mount β so only* the document detail is warmed here.*/export const usePrefetchPage = () => {diff --git a/src/libs/replica/devtools.ts b/src/libs/replica/devtools.tsindex b5e82e441e8..efee8b6e3f8 100644--- a/src/libs/replica/devtools.ts+++ b/src/libs/replica/devtools.ts@@ -1,5 +1,5 @@-import type { ReplicaResource, ReplicaState } from '@lobechat/replica';-import type { ReplicaLens } from '@lobechat/replica/zustand';+import type { ReplicaResource, ReplicaState } from 'local-replica';+import type { ReplicaLens } from 'local-replica/zustand';export interface ReplicaDevtoolsEntry {keys: () => string[];diff --git a/src/libs/replica/index.ts b/src/libs/replica/index.tsindex 254734a9ff5..9200e5caa94 100644--- a/src/libs/replica/index.ts+++ b/src/libs/replica/index.ts@@ -8,12 +8,12 @@ import {type ReplicaResource,type ReplicaScope,type ReplicaStorage,-} from '@lobechat/replica';+} from 'local-replica';import {createReplicaSlice as createCoreReplicaSlice,type CreateReplicaSliceOptions,createSWRDriver,-} from '@lobechat/replica/zustand';+} from 'local-replica/zustand';import { mutate, useClientDataSWR } from '@/libs/swr';import { getCacheScope, isScopeTrusted, useCacheScope } from '@/libs/swr/useCacheScope';@@ -22,7 +22,7 @@ import { notifyReplicaDevtools, registerReplicaDevtools } from './devtools';import { AppIndexedDBStorage, AppLocalStorage } from './storage';/**- * LobeHub wiring of `@lobechat/replica`: replicas are partitioned like the SWR+ * LobeHub wiring of `local-replica`: replicas are partitioned like the SWR* cache (`${userId}:${workspaceId}`), persist to IndexedDB by default and* fetch through the app's SWR hook (workspace-augmented keys, retry policy).*/@@ -193,10 +193,10 @@ export const createReplicaSlice = <TStore, TParams, TData, TFetched = TData>(};export { AppIndexedDBStorage, AppLocalStorage } from './storage';-export * from '@lobechat/replica';+export * from 'local-replica';export {recordLens,type ReplicaLens,type ReplicaSyncResult,splitPagedLens,-} from '@lobechat/replica/zustand';+} from 'local-replica/zustand';diff --git a/src/libs/replica/prePaint.ts b/src/libs/replica/prePaint.tsindex 03e9fc0ddb3..93e972f3024 100644--- a/src/libs/replica/prePaint.ts+++ b/src/libs/replica/prePaint.ts@@ -1,4 +1,4 @@-export { settleWithin } from '@lobechat/replica';+export { settleWithin } from 'local-replica';/*** Upper bound for a route loader's pre-paint hydrate.diff --git a/src/libs/replica/storage.ts b/src/libs/replica/storage.tsindex 99e084c77e0..948d2481921 100644--- a/src/libs/replica/storage.ts+++ b/src/libs/replica/storage.ts@@ -3,7 +3,7 @@ import {LocalStorageReplicaStorage,type ReplicaRow,type ReplicaRowCodec,-} from '@lobechat/replica';+} from 'local-replica';import superjson from 'superjson';import { localDatabase } from '@/libs/localDatabase';diff --git a/src/libs/swr/keys.test.ts b/src/libs/swr/keys.test.tsindex 484e2f050ec..01d973e594c 100644--- a/src/libs/swr/keys.test.ts+++ b/src/libs/swr/keys.test.ts@@ -1,4 +1,4 @@-import { replicaKeys } from '@lobechat/replica';+import { replicaKeys } from 'local-replica';import { unstable_serialize } from 'swr';import { describe, expect, it } from 'vitest';diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 1331c4dde9e..9f0ce752c59 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -253,7 +253,7 @@ export const recentKeys = {* "what needs you" feeds, and the topic link is a discovery poll.** The goal list, the home roll-up, the graph snapshot and the metric series- * used to live here β they are `@lobechat/replica` resources now (see+ * used to live here β they are `local-replica` resources now (see* `src/store/goal/projection.ts`), so their sync keys are not SWR cache keys.*/export const goalKeys = {@@ -292,7 +292,7 @@ export const workKeys = {// ---- brief --------------------------------------------------------------// The unresolved brief feed no longer has an SWR key: it moved onto-// `@lobechat/replica` (`briefList`, partitioned by identity scope). Only the+// `local-replica` (`briefList`, partitioned by identity scope). Only the// day-scoped news digest still reads through SWR.export const briefKeys = {/**@@ -313,7 +313,7 @@ export const agentConfigKeys = {};// ---- image generation ----------------------------------------------------// The topic list and the per-topic batches live in `@lobechat/replica`+// The topic list and the per-topic batches live in `local-replica`// resources now (see `src/store/image/slices/*/projection.ts`); only the// generation-status poll is still an SWR key.export const imageKeys = {@@ -325,7 +325,7 @@ export const imageKeys = {};// ---- video generation ----------------------------------------------------// The topic list and the per-topic batches live in `@lobechat/replica`+// The topic list and the per-topic batches live in `local-replica`// resources now (see `src/store/video/slices/*/projection.ts`); only the// generation-status poll is still an SWR key.export const videoKeys = {diff --git a/src/services/document/invalidation.test.ts b/src/services/document/invalidation.test.tsindex e7c5ee8fd8d..5fb1844afd1 100644--- a/src/services/document/invalidation.test.ts+++ b/src/services/document/invalidation.test.ts@@ -1,5 +1,5 @@-import { replicaKeys } from '@lobechat/replica';import { act, renderHook, waitFor } from '@testing-library/react';+import { replicaKeys } from 'local-replica';import useSWR from 'swr';import { describe, expect, it, vi } from 'vitest';diff --git a/src/services/document/invalidation.ts b/src/services/document/invalidation.tsindex fb01d0b4f7a..76992b1d4ac 100644--- a/src/services/document/invalidation.ts+++ b/src/services/document/invalidation.ts@@ -43,7 +43,7 @@ export const invalidateDocumentMutation = async (// keyed by `document:editor`, so revalidate the replica instead.revalidations.push(revalidateReplica(documentDetailResource, documentId));}- // The page domain is a `@lobechat/replica` domain, so its by-id copy and+ // The page domain is a `local-replica` domain, so its by-id copy and// its list sync through `replica:sync` keys rather than the SWR cache:// refresh them here or a rename / move would not reach the Pages sidebar or// the page header until a remount.diff --git a/src/store/agent/slices/knowledge/replica.test.ts b/src/store/agent/slices/knowledge/replica.test.tsindex bc3db68305d..470c326080d 100644--- a/src/store/agent/slices/knowledge/replica.test.ts+++ b/src/store/agent/slices/knowledge/replica.test.ts@@ -1,7 +1,7 @@/*** @vitest-environment happy-dom*- * The agent-knowledge list is a `@lobechat/replica` resource whose view is the+ * The agent-knowledge list is a `local-replica` resource whose view is the* agent store's `agentKnowledgeMap`: the persisted projection paints while the* network confirms it, an unchanged response keeps the array reference, a* refresh after a knowledge mutation repaints the surface, and a cache-scopediff --git a/src/store/agentDocument/replica.test.ts b/src/store/agentDocument/replica.test.tsindex 7adffa95073..25256f254b2 100644--- a/src/store/agentDocument/replica.test.ts+++ b/src/store/agentDocument/replica.test.ts@@ -1,7 +1,7 @@/*** @vitest-environment happy-dom*- * An agent's document list and the read-only reader are `@lobechat/replica`+ * An agent's document list and the read-only reader are `local-replica`* resources: the persisted projection paints a cold start while the network* confirms it, client-side edits never reach storage, scopes stay isolated, and* the reader keeps only the fields it renders and forgets deleted documents.diff --git a/src/store/agentGroup/action.ts b/src/store/agentGroup/action.tsindex 6cb2a32ee83..9bf075ad82f 100644--- a/src/store/agentGroup/action.ts+++ b/src/store/agentGroup/action.ts@@ -346,7 +346,7 @@ class ChatGroupInternalAction implements ResetableStore {** The write is a `seed`, not authoritative detail: it is in-memory only, and* the detail replica may still hydrate the persisted full detail over it (see- * `packages/replica/src/core/reducer.ts`). A plain local entry would have+ * `local-replica`'s `src/core/state/reducer.ts`). A plain local entry would have* blocked that hydrate, stranding the group page on default config and no* members whenever the network was slow, failed or offline.*diff --git a/src/store/agentGroup/replica.test.ts b/src/store/agentGroup/replica.test.tsindex f2e7daf9e28..a9c439c1172 100644--- a/src/store/agentGroup/replica.test.ts+++ b/src/store/agentGroup/replica.test.ts@@ -1,7 +1,7 @@/*** @vitest-environment happy-dom*- * The agent group store is two `@lobechat/replica` resources: the group list+ * The agent group store is two `local-replica` resources: the group list* (`groups`) and the per-group detail (`groupMap`). The persisted projection* paints while the network confirms it, a gone group is dropped from every view* that holds it (and from storage), and one group row is patched everywhere itdiff --git a/src/store/aiInfra/slices/aiProvider/projection.ts b/src/store/aiInfra/slices/aiProvider/projection.tsindex 9ba250ca384..f9733779ca0 100644--- a/src/store/aiInfra/slices/aiProvider/projection.ts+++ b/src/store/aiInfra/slices/aiProvider/projection.ts@@ -1,4 +1,4 @@-import type { ReplicaStorage } from '@lobechat/replica';+import type { ReplicaStorage } from 'local-replica';import type { LobeDefaultAiModelListItem } from 'model-bank';import { AppIndexedDBStorage, defineReplica, stableQueryKey } from '@/libs/replica';@@ -12,7 +12,7 @@ import type {/*** The aiProvider reads β the provider list, one provider detail, and the- * derived runtime state β as `@lobechat/replica` resources. Each used to be a+ * derived runtime state β as `local-replica` resources. Each used to be a* bare `useClientDataSWR`; the replica engine now owns hydration, scope* isolation and head revalidation.*diff --git a/src/store/device/gitHooks.ts b/src/store/device/gitHooks.tsindex 00a5be2a158..84e437c40cf 100644--- a/src/store/device/gitHooks.ts+++ b/src/store/device/gitHooks.ts@@ -1,6 +1,4 @@import { isDesktop } from '@lobechat/const';-import type { ReplicaOptimisticToken } from '@lobechat/replica';-import type { ReplicaSlice, ReplicaSyncSchedule } from '@lobechat/replica/zustand';import type {DeviceGitAheadBehind,DeviceGitBranchListItem,@@ -12,6 +10,8 @@ import type {DeviceGitWorkingTreeStatus,DeviceGitWorktreeListItem,} from '@lobechat/types';+import type { ReplicaOptimisticToken } from 'local-replica';+import type { ReplicaSlice, ReplicaSyncSchedule } from 'local-replica/zustand';import { useCallback, useMemo, useRef } from 'react';import { mutate } from '@/libs/swr';diff --git a/src/store/device/heteroModelCatalog/projection.ts b/src/store/device/heteroModelCatalog/projection.tsindex 398822be299..7c8fe593a74 100644--- a/src/store/device/heteroModelCatalog/projection.ts+++ b/src/store/device/heteroModelCatalog/projection.ts@@ -1,9 +1,9 @@-import { replicaKeys } from '@lobechat/replica';import type {HeterogeneousAgentModelCatalogSuccess,HeterogeneousProviderConfig,ListHeterogeneousAgentModelsParams,} from '@lobechat/types';+import { replicaKeys } from 'local-replica';import { cacheScope, defineReplica } from '@/libs/replica';diff --git a/src/store/eval/slices/benchmark/action.test.ts b/src/store/eval/slices/benchmark/action.test.tsindex 3a53b754bbc..ad478bff551 100644--- a/src/store/eval/slices/benchmark/action.test.ts+++ b/src/store/eval/slices/benchmark/action.test.ts@@ -1,7 +1,7 @@/*** @vitest-environment happy-dom*- * The benchmark list and detail are `@lobechat/replica` resources. These tests+ * The benchmark list and detail are `local-replica` resources. These tests* pin the fetch orchestration and the write paths (create / update / delete)* at the boundary: which service call each action makes and that the replica* network sync is revalidated instead of a hand-written SWR `mutate`.diff --git a/src/store/eval/slices/benchmark/replica.test.ts b/src/store/eval/slices/benchmark/replica.test.tsindex 9b2103677b4..952e4a2b213 100644--- a/src/store/eval/slices/benchmark/replica.test.ts+++ b/src/store/eval/slices/benchmark/replica.test.ts@@ -1,7 +1,7 @@/*** @vitest-environment happy-dom*- * The benchmark list and detail are `@lobechat/replica` resources whose views+ * The benchmark list and detail are `local-replica` resources whose views* are the eval store's flat `benchmarkList` / `benchmarkDetailMap` fields. This* suite drives the real replica sync through SWR (no mocked fetch hook) to show* the behaviour the migration must preserve: a persisted list paints while thediff --git a/src/store/eval/slices/dataset/action.test.ts b/src/store/eval/slices/dataset/action.test.tsindex 45e336b69da..971ad4caf9c 100644--- a/src/store/eval/slices/dataset/action.test.ts+++ b/src/store/eval/slices/dataset/action.test.ts@@ -2,7 +2,7 @@* @vitest-environment happy-dom** The dataset lists (benchmark-scoped + scope-wide) and the dataset detail are- * `@lobechat/replica` resources. These tests pin the fetch orchestration at the+ * `local-replica` resources. These tests pin the fetch orchestration at the* boundary: which service call each hook registers, the pre-migration return* shapes, and that the refresh actions revalidate the replica sync instead of a* hand-written SWR `mutate`.diff --git a/src/store/eval/slices/dataset/replica.test.ts b/src/store/eval/slices/dataset/replica.test.tsindex 9cd0e1785c2..086f7ccd97e 100644--- a/src/store/eval/slices/dataset/replica.test.ts+++ b/src/store/eval/slices/dataset/replica.test.ts@@ -2,7 +2,7 @@* @vitest-environment happy-dom** The dataset lists (benchmark-scoped + scope-wide) and the dataset detail are- * `@lobechat/replica` resources whose views are `datasetListMap` /+ * `local-replica` resources whose views are `datasetListMap` /* `datasetDetailMap`. This suite drives the real replica sync through SWR (no* mocked fetch hook) to show the behaviour the migration must preserve: a* persisted list paints while the network answers, a server response settlesdiff --git a/src/store/eval/slices/experiment/action.test.ts b/src/store/eval/slices/experiment/action.test.tsindex 75965f57bd9..f817b6ceb6c 100644--- a/src/store/eval/slices/experiment/action.test.ts+++ b/src/store/eval/slices/experiment/action.test.ts@@ -1,7 +1,7 @@/*** @vitest-environment happy-dom*- * The experiment list and detail are `@lobechat/replica` resources whose views+ * The experiment list and detail are `local-replica` resources whose views* are the eval store's flat `experimentList` / `experimentDetailMap` fields.* These tests pin the fetch orchestration and the write paths (create / update* / delete) at the boundary: which service call each action makes and that thediff --git a/src/store/eval/slices/experiment/replica.test.ts b/src/store/eval/slices/experiment/replica.test.tsindex f761eecb8cb..109275d7866 100644--- a/src/store/eval/slices/experiment/replica.test.ts+++ b/src/store/eval/slices/experiment/replica.test.ts@@ -1,7 +1,7 @@/*** @vitest-environment happy-dom*- * The experiment list and detail are `@lobechat/replica` resources whose views+ * The experiment list and detail are `local-replica` resources whose views* are the eval store's flat `experimentList` / `experimentDetailMap` fields.* This suite drives the real replica sync through SWR (no mocked fetch hook) to* show the behaviour the migration must preserve: a persisted list paints whilediff --git a/src/store/file/slices/fileManager/action.ts b/src/store/file/slices/fileManager/action.tsindex 989a33a9592..91e3a56d91d 100644--- a/src/store/file/slices/fileManager/action.ts+++ b/src/store/file/slices/fileManager/action.ts@@ -122,7 +122,7 @@ export const createFileManageSlice = (set: Setter, get: () => FileStore, _api?:export class FileManageActionImpl {readonly #get: () => FileStore;/**- * The knowledge-item list is a `@lobechat/replica` paged resource: the+ * The knowledge-item list is a `local-replica` paged resource: the* persisted head page paints before the network answers and "load more"* appends further pages through the engine instead of a hand-rolled offset.*/diff --git a/src/store/file/slices/fileManager/replica.test.ts b/src/store/file/slices/fileManager/replica.test.tsindex 75c3f822294..76733240515 100644--- a/src/store/file/slices/fileManager/replica.test.ts+++ b/src/store/file/slices/fileManager/replica.test.ts@@ -2,7 +2,7 @@* @vitest-environment happy-dom** The file manager's knowledge-item list and by-id detail are- * `@lobechat/replica` resources: the persisted head page / detail paints before+ * `local-replica` resources: the persisted head page / detail paints before* the network answers, the response confirms and persists it, "load more"* appends through the engine, and β because the two resources are linked β a* rename or delete reaches the list row and every loaded detail entry at once.diff --git a/src/store/file/slices/resource/action.ts b/src/store/file/slices/resource/action.tsindex 7fafc1900c4..0a7e71065de 100644--- a/src/store/file/slices/resource/action.ts+++ b/src/store/file/slices/resource/action.ts@@ -120,7 +120,7 @@ export const createResourceSlice = (set: Setter, get: () => FileStore, api?: unkexport class ResourceActionImpl {readonly #get: () => FileStore;/**- * The explorer list is a `@lobechat/replica` paged resource: the persisted+ * The explorer list is a `local-replica` paged resource: the persisted* head page paints before the network answers, and "load more" appends further* pages through the engine instead of a hand-rolled `offset` accumulator.*/diff --git a/src/store/file/slices/resource/initialState.ts b/src/store/file/slices/resource/initialState.tsindex a99129ee898..38c9b088ff6 100644--- a/src/store/file/slices/resource/initialState.ts+++ b/src/store/file/slices/resource/initialState.ts@@ -6,7 +6,7 @@ import { type ResourceListParams, type ResourceListValue } from './projection';/*** Resource slice state.*- * The list itself is a `@lobechat/replica` paged resource: `resourceListEntry`+ * The list itself is a `local-replica` paged resource: `resourceListEntry`* is the replica view, and `resourceList` / `resourceMap` / `hasMore` / `total`* / `offset` / `queryParams` / `isLoadingMore` are derived from it by the* slice's lens, so every existing selector keeps reading the same place.diff --git a/src/store/file/slices/resource/replica.test.ts b/src/store/file/slices/resource/replica.test.tsindex 71b373ebad7..80f31c8d130 100644--- a/src/store/file/slices/resource/replica.test.ts+++ b/src/store/file/slices/resource/replica.test.ts@@ -1,7 +1,7 @@/*** @vitest-environment happy-dom*- * The explorer list is a `@lobechat/replica` paged resource: the persisted head+ * The explorer list is a `local-replica` paged resource: the persisted head* page paints before the network answers, the response confirms and persists it,* "load more" appends through the engine, and a query change repaints from its* own head page instead of appending to the previous folder's rows.diff --git a/src/store/home/slices/label/replica.test.ts b/src/store/home/slices/label/replica.test.tsindex bcb56625eaa..31154b99c8c 100644--- a/src/store/home/slices/label/replica.test.ts+++ b/src/store/home/slices/label/replica.test.ts@@ -1,7 +1,7 @@/*** @vitest-environment happy-dom*- * The agent-label registry is a `@lobechat/replica` resource whose view is the+ * The agent-label registry is a `local-replica` resource whose view is the* home store's flat `agentLabels` field: the persisted projection paints while* the network confirms it, an unchanged response keeps the array reference, and* a cache-scope switch drops the previous workspace's registry before paint βdiff --git a/src/store/image/slices/generationBatch/replica.test.ts b/src/store/image/slices/generationBatch/replica.test.tsindex eb63105b67b..79e0d3a8c40 100644--- a/src/store/image/slices/generationBatch/replica.test.ts+++ b/src/store/image/slices/generationBatch/replica.test.ts@@ -1,7 +1,7 @@/*** @vitest-environment happy-dom*- * Generation batches are a `@lobechat/replica` resource with one entry per+ * Generation batches are a `local-replica` resource with one entry per* topic (`generationBatchesMap[topicId]`): the persisted projection paints the* feed before the network answers, an unchanged response keeps the array* reference, and a cache-scope switch drops the previous identity's batchesdiff --git a/src/store/image/slices/generationTopic/replica.test.ts b/src/store/image/slices/generationTopic/replica.test.tsindex 3e02d9e91d8..221cbde8d04 100644--- a/src/store/image/slices/generationTopic/replica.test.ts+++ b/src/store/image/slices/generationTopic/replica.test.ts@@ -1,7 +1,7 @@/*** @vitest-environment happy-dom*- * The image generation topic list is a `@lobechat/replica` resource whose view+ * The image generation topic list is a `local-replica` resource whose view* is the image store's `generationTopics` field: the persisted projection paints* while the network confirms it, an unchanged response keeps the array* reference, a cache-scope switch drops the previous identity's topics beforediff --git a/src/store/projectFile/action.ts b/src/store/projectFile/action.tsindex bbd8ee36681..da2121a87fa 100644--- a/src/store/projectFile/action.ts+++ b/src/store/projectFile/action.ts@@ -1,5 +1,5 @@import type { GitWorkingTreeFiles, ProjectFileIndexResult } from '@lobechat/electron-client-ipc';-import type { ReplicaSyncOptions } from '@lobechat/replica/zustand';+import type { ReplicaSyncOptions } from 'local-replica/zustand';import type { ReplicaSyncResult } from '@/libs/replica';import type { StoreSetter } from '@/store/types';diff --git a/src/store/sandbox/replica.test.ts b/src/store/sandbox/replica.test.tsindex 9ea1504370f..828cd585f99 100644--- a/src/store/sandbox/replica.test.ts+++ b/src/store/sandbox/replica.test.ts@@ -2,7 +2,7 @@* @vitest-environment happy-dom** The cloud-sandbox entitlement, the composer picker's environment and- * instance lists and a bound instance's directory are `@lobechat/replica`+ * instance lists and a bound instance's directory are `local-replica`* resources: a cold start paints the persisted answer while the network* confirms it, only slim projections reach storage, the instance list is one* row however many conversations ask, and scopes stay isolated.diff --git a/src/store/tool/slices/connector/action.ts b/src/store/tool/slices/connector/action.tsindex 2175ca3a6b3..b5096fdf652 100644--- a/src/store/tool/slices/connector/action.ts+++ b/src/store/tool/slices/connector/action.ts@@ -93,7 +93,7 @@ export const createConnectorSlice = (set: Setter, get: () => ToolStore, _api?: unew ConnectorActionImpl(set, get, _api);/**- * The connector slice is a set of `@lobechat/replica` resources: the base+ * The connector slice is a set of `local-replica` resources: the base* list, the agent-bound aggregate and the per-agent buckets. The store fields* keep their historical shape (`connectors`, `agentBoundConnectors`,* `agentConnectors`) as the replica views, so every selector and consumer isdiff --git a/src/store/tool/slices/connector/replica.test.ts b/src/store/tool/slices/connector/replica.test.tsindex 05fc4e318a6..64d9f7eb147 100644--- a/src/store/tool/slices/connector/replica.test.ts+++ b/src/store/tool/slices/connector/replica.test.ts@@ -1,7 +1,7 @@/*** @vitest-environment happy-dom*- * The connector lists are `@lobechat/replica` resources: the persisted+ * The connector lists are `local-replica` resources: the persisted* projection paints while the network confirms it, a permission write shows on* the row immediately and rolls back when the server rejects it, and a* confirmed delete drops the same connector from every list that holds it indiff --git a/src/store/tool/slices/lobehubSkillStore/action.ts b/src/store/tool/slices/lobehubSkillStore/action.tsindex 7e16a2e46c1..71229d54403 100644--- a/src/store/tool/slices/lobehubSkillStore/action.ts+++ b/src/store/tool/slices/lobehubSkillStore/action.ts@@ -85,7 +85,7 @@ export class LobehubSkillStoreActionImpl {*/readonly #providerTools;/**- * The user's connected providers β a `@lobechat/replica` list, so the+ * The user's connected providers β a `local-replica` list, so the* persisted row paints before the network answers and a connect / revoke shows* on the row at once.*/diff --git a/src/store/tool/slices/mcpStore/action.ts b/src/store/tool/slices/mcpStore/action.tsindex 7c1a3e37a19..a7260820fa4 100644--- a/src/store/tool/slices/mcpStore/action.ts+++ b/src/store/tool/slices/mcpStore/action.ts@@ -166,7 +166,7 @@ export const createMCPPluginStoreSlice = (set: Setter, get: () => ToolStore, _apexport class PluginMCPStoreActionImpl {readonly #get: () => ToolStore;/**- * The MCP marketplace list is a `@lobechat/replica` paged resource: the+ * The MCP marketplace list is a `local-replica` paged resource: the* persisted head page paints before the network answers, and "load more"* appends further pages through the engine instead of a hand-rolled* `currentPage` + accumulator.diff --git a/src/store/tool/slices/mcpStore/replica.test.ts b/src/store/tool/slices/mcpStore/replica.test.tsindex 6db55b78546..f9c32edd518 100644--- a/src/store/tool/slices/mcpStore/replica.test.ts+++ b/src/store/tool/slices/mcpStore/replica.test.ts@@ -1,7 +1,7 @@/*** @vitest-environment happy-dom*- * The MCP marketplace list is a `@lobechat/replica` paged resource: the+ * The MCP marketplace list is a `local-replica` paged resource: the* persisted head page paints before the network answers, the response confirms* and persists it, "load more" appends through the engine, and a query change* (search term) repaints from its own head page instead of appending to thediff --git a/src/store/topicComment/replica.test.ts b/src/store/topicComment/replica.test.tsindex ada60d397da..4d8843ff00f 100644--- a/src/store/topicComment/replica.test.ts+++ b/src/store/topicComment/replica.test.ts@@ -1,7 +1,7 @@/*** @vitest-environment happy-dom*- * `topicComment` is a `@lobechat/replica`-backed store. The root feed, the+ * `topicComment` is a `local-replica`-backed store. The root feed, the* reply feed, the per-topic counts and one comment by id each paint their* persisted row before the network answers, are confirmed and persisted by the* response, page further through the engine, and are re-partitioned when thediff --git a/src/store/trash/action.ts b/src/store/trash/action.tsindex fedf60f4fe9..90a7cc381a1 100644--- a/src/store/trash/action.ts+++ b/src/store/trash/action.ts@@ -37,7 +37,7 @@ const RESTORE_AFFECTED_KEY_PREFIXES = ['group:','home:','image:',- // Replicas (topic list, β¦) sync through `replica:sync` keys (`@lobechat/replica`).+ // Replicas (topic list, β¦) sync through `replica:sync` keys (`local-replica`).'replica:',// conversation transcripts β a restored message must reappear in its thread'message:',diff --git a/src/store/user/slices/common/action.ts b/src/store/user/slices/common/action.tsindex 92081be2a66..438f3294bda 100644--- a/src/store/user/slices/common/action.ts+++ b/src/store/user/slices/common/action.ts@@ -1,7 +1,7 @@import { isDesktop } from '@lobechat/const';-import type { ReplicaSlice } from '@lobechat/replica/zustand';import type { UserGeneralConfig } from '@lobechat/types';import isEqual from 'fast-deep-equal';+import type { ReplicaSlice } from 'local-replica/zustand';import { type SWRResponse } from 'swr';import useSWR from 'swr';import { type PartialDeep } from 'type-fest';diff --git a/src/store/user/slices/common/initialState.ts b/src/store/user/slices/common/initialState.tsindex c01900ec9ef..b2642b3ca60 100644--- a/src/store/user/slices/common/initialState.ts+++ b/src/store/user/slices/common/initialState.ts@@ -2,12 +2,12 @@// wiring pulls `@/libs/swr/useCacheScope`, which reads this very store, and the// cycle would leave `createReplicaState` undefined while the initial state is// built.-import { createReplicaState, type ReplicaState } from '@lobechat/replica';import {type Plans,type ReferralStatusString,type UserInitializationState,} from '@lobechat/types';+import { createReplicaState, type ReplicaState } from 'local-replica';export interface CommonState {isFreePlan?: boolean;diff --git a/src/store/user/slices/common/replica.test.ts b/src/store/user/slices/common/replica.test.tsindex 699fcf39ec7..f4f5206c9d9 100644--- a/src/store/user/slices/common/replica.test.ts+++ b/src/store/user/slices/common/replica.test.ts@@ -1,7 +1,7 @@/*** @vitest-environment happy-dom*- * The user bootstrap is a `@lobechat/replica` resource whose view is the user+ * The user bootstrap is a `local-replica` resource whose view is the user* store's flat flags (`isUserStateInit`, `user`, `settings` β¦). It stays* memory-only on purpose: `@/store/user/displaySnapshot` β not a persisted* payload β bridges a cold boot, so entitlement (`isFreePlan`) and onboardingdiff --git a/src/store/user/slices/workspaceUserSettings/action.ts b/src/store/user/slices/workspaceUserSettings/action.tsindex 8639a752f05..25d47eb1def 100644--- a/src/store/user/slices/workspaceUserSettings/action.ts+++ b/src/store/user/slices/workspaceUserSettings/action.ts@@ -1,7 +1,7 @@-import type { ReplicaSlice } from '@lobechat/replica/zustand';import type { WorkspaceUserPreference } from '@lobechat/types';import { mergeNotificationSettings } from '@lobechat/utils/mergeNotificationSettings';import isEqual from 'fast-deep-equal';+import type { ReplicaSlice } from 'local-replica/zustand';import { useSyncExternalStore } from 'react';import {diff --git a/src/store/user/slices/workspaceUserSettings/replica.test.ts b/src/store/user/slices/workspaceUserSettings/replica.test.tsindex 84da8b70ba0..307581b5128 100644--- a/src/store/user/slices/workspaceUserSettings/replica.test.ts+++ b/src/store/user/slices/workspaceUserSettings/replica.test.ts@@ -1,7 +1,7 @@/*** @vitest-environment happy-dom*- * The workspace-user preference bucket is a `@lobechat/replica` resource whose+ * The workspace-user preference bucket is a `local-replica` resource whose* view is the user store's flat `workspaceUserPreference` field (+ the* `workspaceUserPreferenceWorkspaceId` loaded marker): a persisted projection* paints while the network confirms it, personal mode never hits the network,diff --git a/src/store/userMemory/slices/activity/initialState.ts b/src/store/userMemory/slices/activity/initialState.tsindex c308560a91e..38b5d0ddb1a 100644--- a/src/store/userMemory/slices/activity/initialState.ts+++ b/src/store/userMemory/slices/activity/initialState.ts@@ -6,7 +6,7 @@ import { memoryListKey } from '../../utils/replica';import { type ActivityListData, type ActivityListSort } from './projection';/**- * The activity list is a `@lobechat/replica` paged resource with one page set+ * The activity list is a `local-replica` paged resource with one page set* per search / sort (`activityListEntries`). The long-standing flat fields* (`activityListData`, `activities`, `activitiesTotal`, `activitiesPage`,* `activitiesHasMore`, `activitiesInit`) mirror the active query's entry so everydiff --git a/src/store/userMemory/slices/agent/replica.test.ts b/src/store/userMemory/slices/agent/replica.test.tsindex 5c6c45f407d..d7163a02d59 100644--- a/src/store/userMemory/slices/agent/replica.test.ts+++ b/src/store/userMemory/slices/agent/replica.test.ts@@ -8,8 +8,8 @@*/import { randomUUID } from 'node:crypto';-import { REPLICA_INDEX_KEY } from '@lobechat/replica';import { act, cleanup, renderHook, waitFor } from '@testing-library/react';+import { REPLICA_INDEX_KEY } from 'local-replica';import type { PropsWithChildren } from 'react';import { createElement, useEffect } from 'react';import { SWRConfig, useSWRConfig } from 'swr';diff --git a/src/store/userMemory/slices/base/replica.test.ts b/src/store/userMemory/slices/base/replica.test.tsindex f3dceb1e6c8..396548f69a8 100644--- a/src/store/userMemory/slices/base/replica.test.ts+++ b/src/store/userMemory/slices/base/replica.test.ts@@ -1,7 +1,7 @@/*** @vitest-environment happy-dom*- * The user-memory base slice's server reads are `@lobechat/replica` resources:+ * The user-memory base slice's server reads are `local-replica` resources:* the retrieve result map and one memory detail per `${layer}:${id}`. These* tests pin the local-first guarantees and the shape the existing consumers* keep reading (`memoryMap` / `memoryDetailMap`), plus the purge that drops thediff --git a/src/store/userMemory/slices/context/initialState.ts b/src/store/userMemory/slices/context/initialState.tsindex 8009e0a261c..5f019926923 100644--- a/src/store/userMemory/slices/context/initialState.ts+++ b/src/store/userMemory/slices/context/initialState.ts@@ -5,7 +5,7 @@ import { memoryListKey } from '../../utils/replica';import { type ContextListData, type ContextListSort } from './projection';/**- * The context list is a `@lobechat/replica` paged resource with one page set+ * The context list is a `local-replica` paged resource with one page set* per search / sort (`contextListEntries`). The long-standing flat fields* (`contextListData`, `contexts`, `contextsTotal`, `contextsPage`,* `contextsHasMore`, `contextsInit`) mirror the active query's entry so everydiff --git a/src/store/userMemory/slices/experience/initialState.ts b/src/store/userMemory/slices/experience/initialState.tsindex b22dde334fc..cd727513027 100644--- a/src/store/userMemory/slices/experience/initialState.ts+++ b/src/store/userMemory/slices/experience/initialState.ts@@ -6,7 +6,7 @@ import { memoryListKey } from '../../utils/replica';import { type ExperienceListData, type ExperienceListSort } from './projection';/**- * The experience list is a `@lobechat/replica` paged resource with one page set+ * The experience list is a `local-replica` paged resource with one page set* per search / sort (`experienceListEntries`). The long-standing flat fields* (`experienceListData`, `experiences`, `experiencesTotal`, `experiencesPage`,* `experiencesHasMore`, `experiencesInit`) mirror the active query's entry so everydiff --git a/src/store/userMemory/slices/home/action.ts b/src/store/userMemory/slices/home/action.tsindex 110d93802a2..cac464cb1c7 100644--- a/src/store/userMemory/slices/home/action.ts+++ b/src/store/userMemory/slices/home/action.ts@@ -84,7 +84,7 @@ export const createHomeSlice = (/*** The memory home reads: the persona and the identity roles + tags aggregate.*- * Server state is two `@lobechat/replica` single-value resources (`personaData`+ * Server state is two `local-replica` single-value resources (`personaData`* and `identityRolesData`): the persisted copy paints on the first frame and* the network confirms it in the background. The domain store exposes the same* flat fields and the same action surface it always has, backed by the replicadiff --git a/src/store/userMemory/slices/home/initialState.ts b/src/store/userMemory/slices/home/initialState.tsindex 72268fed896..a756c53b2a2 100644--- a/src/store/userMemory/slices/home/initialState.ts+++ b/src/store/userMemory/slices/home/initialState.ts@@ -4,7 +4,7 @@ import { type IdentityRolesData, type PersonaData, type PersonaReplicaData } fro/*** The memory home reads (persona + identity roles/tags) are two- * `@lobechat/replica` single-value resources. Their canonical values live in+ * `local-replica` single-value resources. Their canonical values live in* `personaData` / `identityRolesData`; the long-standing flat fields* (`persona`, `personaInit`, `roles`, `tags`, `tagsInit`) are derived mirrors* of those views so every existing consumer keeps reading the place it alwaysdiff --git a/src/store/userMemory/slices/home/replica.test.ts b/src/store/userMemory/slices/home/replica.test.tsindex d72b200bb47..03a818e5f48 100644--- a/src/store/userMemory/slices/home/replica.test.ts+++ b/src/store/userMemory/slices/home/replica.test.ts@@ -2,7 +2,7 @@* @vitest-environment happy-dom** The memory home reads (persona + identity roles/tags) are two- * `@lobechat/replica` single-value resources: the persisted copy paints before+ * `local-replica` single-value resources: the persisted copy paints before* the network answers, the response confirms and persists it, a server* `null` persona is a real (persisted) absence, an unchanged revalidation does* not repaint, and the persona delete drops the value from the view and thediff --git a/src/store/userMemory/slices/identity/replica.test.ts b/src/store/userMemory/slices/identity/replica.test.tsindex 86f93bff4ce..a1a62baaa36 100644--- a/src/store/userMemory/slices/identity/replica.test.ts+++ b/src/store/userMemory/slices/identity/replica.test.ts@@ -1,7 +1,7 @@/*** @vitest-environment happy-dom*- * The identities list is a `@lobechat/replica` paged resource whose view is the+ * The identities list is a `local-replica` paged resource whose view is the* userMemory store's flat `identities` array (with `identitiesMeta` beside it):* the persisted head page paints while the network confirms it, "load more"* appends through the engine, an optimistic delete rolls back on failure, and adiff --git a/src/store/userMemory/slices/preference/initialState.ts b/src/store/userMemory/slices/preference/initialState.tsindex a56faf6fee6..93ec9b2e9b2 100644--- a/src/store/userMemory/slices/preference/initialState.ts+++ b/src/store/userMemory/slices/preference/initialState.ts@@ -5,7 +5,7 @@ import { memoryListKey } from '../../utils/replica';import { type PreferenceListData, type PreferenceListSort } from './projection';/**- * The preference list is a `@lobechat/replica` paged resource with one page set+ * The preference list is a `local-replica` paged resource with one page set* per search / sort (`preferenceListEntries`). The long-standing flat fields* (`preferenceListData`, `preferences`, `preferencesTotal`, `preferencesPage`,* `preferencesHasMore`, `preferencesInit`) mirror the active query's entry so everydiff --git a/src/store/video/slices/generationBatch/replica.test.ts b/src/store/video/slices/generationBatch/replica.test.tsindex b064cfa6134..77c3d2c16d5 100644--- a/src/store/video/slices/generationBatch/replica.test.ts+++ b/src/store/video/slices/generationBatch/replica.test.ts@@ -1,7 +1,7 @@/*** @vitest-environment happy-dom*- * Generation batches are a `@lobechat/replica` resource with one entry per+ * Generation batches are a `local-replica` resource with one entry per* topic (`generationBatchesMap[topicId]`): the persisted projection paints the* feed before the network answers, an unchanged response keeps the array* reference, and a cache-scope switch drops the previous identity's batchesdiff --git a/src/store/video/slices/generationTopic/replica.test.ts b/src/store/video/slices/generationTopic/replica.test.tsindex 5fcee0fc952..9331c074b6f 100644--- a/src/store/video/slices/generationTopic/replica.test.ts+++ b/src/store/video/slices/generationTopic/replica.test.ts@@ -1,7 +1,7 @@/*** @vitest-environment happy-dom*- * The video generation topic list is a `@lobechat/replica` resource whose view+ * The video generation topic list is a `local-replica` resource whose view* is the video store's `generationTopics` field: the persisted projection paints* while the network confirms it, an unchanged response keeps the array* reference, a cache-scope switch drops the previous identity's topics beforediff --git a/src/store/work/action.ts b/src/store/work/action.tsindex 7ca16cbedf3..42a916edc23 100644--- a/src/store/work/action.ts+++ b/src/store/work/action.ts@@ -1,5 +1,5 @@-import type { ReplicaSyncOptions } from '@lobechat/replica/zustand';import type { WorkListItem, WorkVersionItem } from '@lobechat/types';+import type { ReplicaSyncOptions } from 'local-replica/zustand';import type { ReplicaSyncResult } from '@/libs/replica';import type { StoreSetter } from '@/store/types';