@baukit/preferences-core

中文文档
0.18.3发布于 2026/11/07MITTypeScriptES Module零依赖构建来源已验证近 30 天下载 8270

Typed preferences and their update behavior, with storage and effects supplied by the product.

原始使用文档
文档目录5 节
  1. Update modes
  2. Side-effect ordering
  3. Migration
  4. Storage adapter tests
  5. Boundaries

@baukit/preferences-core

@baukit/preferences-core defines typed preferences and their update behavior. Products provide the definitions, storage adapter, and any effects caused by a change.

Update modes

Each definition supplies a key, default value, normalizer, and scope. Hydration reads the store, normalizes every stored field, and fills omitted fields from their definitions.

The default optimistic mode makes a local update visible immediately, then writes it as a patch. If the write fails, the controller restores the previous visible values and records the error. This remains the default for compatibility.

Set updateMode: "serialized" when each update must start from the latest committed values:

const controller = createPreferenceController({
  definitions,
  store,
  updateMode: 'serialized',
  onVisibleChange: (values) => renderPreferences(values),
});

Serialized mode runs one patch at a time. It keeps committed values visible while writes are pending and returns SerializedPreferenceControllerState from getState(). Its pendingCount includes the active write and every queued write. onVisibleChange also runs when this count changes, even when the values argument has not changed. A failed write leaves committed values unchanged. The next patch still runs and uses the last successful result.

Call switchIdentity with the next identity's store when the authenticated subject changes. The controller publishes defaults before it starts the new read. A slow read or write for the old identity cannot put that identity's preferences back into visible state, and a reported side-effect failure that belongs to the replaced identity does not land on the new one.

Call stop() when whatever owns onVisibleChange goes away, such as a React provider unmounting. In-flight work still settles and getState() stays accurate; the callback just stops firing. In serialized mode, queued writes continue against their captured store without publishing after stop(). Consumers do not need their own mounted flag around onVisibleChange.

An identity switch cancels queued writes for the old identity. A write already sent to the old store may settle, but it cannot publish values or start an old queued patch against the new store. A cancelled queued update and a successful stale in-flight update resolve to the current identity's values. A failed in-flight store call still rejects with its store error.

Wire codecs distinguish three states by checking whether a payload owns a field:

  • absent means an older peer did not send the setting, so no patch is made;
  • null means the peer explicitly cleared a nullable setting;
  • value contains the setting's decoded value.

An optional TypeScript property does not carry this distinction by itself.

Side-effect ordering

The default policy is after-persistence. Locale changes, permission prompts, reminder rescheduling, analytics changes, and network-query enablement should run only after the local write succeeds. Every hook declares onError: "report" | "ignore". A reported effect error stays in controller state, while the persisted and visible preference remains unchanged.

Some visual changes need an immediate preview. A definition can opt into preview-with-rollback, provide the preview operation, and provide its inverse. The controller runs that rollback if preview or persistence fails. Its optional afterPersistence hook still runs only after the write.

Migration

Existing callers do not need to change. Calls without updateMode still use optimistic visibility and may have overlapping store writes. Callers that currently maintain their own write queue can set updateMode: "serialized", read pendingCount from getState(), and remove that queue. Their UI must expect committed visibility while updates are pending.

Storage adapter tests

Adapters implement PreferenceStore.read and PreferenceStore.patch. Import describePreferenceStoreContract from @baukit/preferences-core/vitest to run the shared Vitest contract. That subpath is ESM-only and has no default condition, so Jest cannot resolve it. InMemoryPreferenceStore is suitable for tests and small in-process consumers.

RepositoryPreferenceStore (or createRepositoryPreferenceStore) adapts a repository keyed by a subject id, which is how most products already store a settings row. Give it the repository, the subject id, and the two projections:

const store = createRepositoryPreferenceStore({
  repository: repositories.settings,
  subjectId: userId,
  toValues: (record) => ({ mode: record.theme, accent: record.accent_color }),
  toRecordPatch: (patch) => ({
    ...(patch.mode === undefined ? {} : { theme: patch.mode }),
    ...(patch.accent === undefined ? {} : { accent_color: patch.accent }),
  }),
});

toRecordPatch must omit keys the patch does not carry, so an untouched preference is never written back. read resolves to undefined when the repository returns null or undefined for that subject, which is what makes the controller fall back to definition defaults.

Boundaries

This package does not generate SQL, choose a storage schema, run migrations, or render a settings interface. Products still decide which preferences exist, where each scope is stored, what users see, and how synchronized payloads reach a server.

版本与发布记录

@baukit/preferences-core 共发布 67 个版本,首次发布于 2026/08/26;过去 12 个月发布了 67 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.18.3latest2026/11/07今天
0.18.22026/11/061 天前
0.18.12026/11/062 天前
0.18.02026/11/052 天前
0.17.12026/11/034 天前
0.17.02026/11/025 天前

关于 @baukit/preferences-core 的常见问题

@baukit/preferences-core 是什么?

Typed preferences and their update behavior, with storage and effects supplied by the product.

如何安装 @baukit/preferences-core?

在项目目录运行 npm install @baukit/preferences-core,或使用 pnpm add / yarn add / bun add。

@baukit/preferences-core 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@baukit/preferences-core 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@baukit/preferences-core 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=24.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@baukit/preferences-core 可以商用吗?

@baukit/preferences-core 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@baukit/preferences-core 的下载量有多少?

根据 npm 官方下载统计,@baukit/preferences-core 在 2026/10/08 – 2026/11/06 这 30 天内被下载 8,270 次,日均约 276 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@baukit/preferences-core 还在维护吗?

最新版本 0.18.3 发布于 2026/11/07(今天);至今共发布 67 个版本,其中过去 12 个月发布了 67 个;首次发布于 2026/08/26。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。