zen-fs-config 0.10.3 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/DESIGN.md CHANGED
@@ -255,19 +255,30 @@ A config-sync group can reference data-sync groups on behalf of specific apps. E
255
255
  {
256
256
  "id": "gitee-data",
257
257
  "type": "Gitee",
258
- "options": { "token": "...", "owner": "...", "repo": "my-app-data", "branch": "main" },
258
+ "options": { "repo": "my-app-data", "branch": "main" },
259
259
  "accountBackendId": "gitee-prod",
260
- "description": "App data on Gitee (reuses gitee-prod account)"
260
+ "credentialMode": "config",
261
+ "description": "App data on Gitee (resolves gitee-prod account at connect time)"
261
262
  }
262
263
  ]
263
264
  }
264
265
  ```
265
266
 
266
- ### Account Reuse
267
+ ### Credential Source Modes
267
268
 
268
- The `accountBackendId` field (optional) references a config-sync backend whose account fields (e.g., `token`, `owner`, `baseUrl` for Gitee/GitHub) are reused. When present, the data-sync backend's `options` only need to specify the **storage location** fields (e.g., `repo`, `branch`); account fields are merged in from the referenced config-sync backend at creation time.
269
+ `accountBackendId` (optional) references a config-sync backend that holds the account fields (e.g. `token`, `owner`, `baseUrl` for Gitee/GitHub). `credentialMode` determines how those fields are used:
269
270
 
270
- When `accountBackendId` is absent or null, the data-sync backend must provide a complete set of options (including credentials).
271
+ | `credentialMode` | Persisted `options` | Behavior |
272
+ |---|---|---|
273
+ | `inline` (default / absent) | Storage location + a **copy** of account fields | Legacy "account reuse": account fields are merged from the referenced config backend **once**, at creation time, and written into the descriptor. Later account changes in the config group do NOT affect this backend. |
274
+ | `config` | Storage location only — **no account fields on disk** | "Credential reference": the descriptor stores only `accountBackendId`; on every connect the account fields are resolved fresh from `.meta/backends/{accountBackendId}.json` in the config-sync group. The account backend must exist, must have the same `type`, and must contain every account field marked `required` by backend metadata. Resolved values are in-memory only and are never written back. |
275
+
276
+ Rules that apply to both modes:
277
+
278
+ - `accountBackendId` absent/null → the backend must carry a complete option set (including credentials); this is the plain standalone backend.
279
+ - Identity dedup keys include the reference dimension: `config` mode keys a backend by `backendDedupKey + ref({accountBackendId})`, so two data backends pointing at the same remote with different referenced accounts are not collapsed into one.
280
+ - Conversion between modes is explicit and lossless in the `config → inline` direction: `convertAppDataBackendCredentialMode(groupId, backendId, 'config' | 'inline', { accountBackendId? })`. Converting to `inline` first resolves the account (fail-closed if unresolvable) and writes it back into `options`; converting to `config` strips account fields from `options` and keeps the reference.
281
+ - `config` mode is fail-closed: if the referenced config backend or a required account field is missing/incompatible, backend creation throws rather than silently falling back to a credential-less connection. Error messages never include credential values.
271
282
 
272
283
  The `accountFields` metadata for each backend type (registered via `BackendMetadata.accountFields`) determines which fields are "account" vs "storage location":
273
284
 
@@ -278,6 +289,36 @@ The `accountFields` metadata for each backend type (registered via `BackendMetad
278
289
  | WebDAV | `url`, `username`, `password` | `rootPath` |
279
290
  | RemoteStorage | `userAddress`, `token` | (none) |
280
291
 
292
+ ### Read-Only Mirror Backends (`accessMode: 'ro'`)
293
+
294
+ A data backend may declare `accessMode: 'ro'` to become a **pull-only mirror**. The remote is treated strictly as a source of truth that this device cannot write:
295
+
296
+ | Mode | Pair direction | Local writes | Missing on remote | `.meta/` |
297
+ |---|---|---|---|---|
298
+ | `rw` (default) | `local → remote`, bidirectional | pushed | deleted on remote | synced (tombstones/versions) |
299
+ | `ro` | `remote → local`, one-way | **not** pushed | **not deleted locally** | excluded from this pair |
300
+
301
+ Rules:
302
+
303
+ - Only backend types whose metadata declares `accessModes: ['rw','ro']` accept `ro`. Currently only **RemoteStorage** does: a scoped `r` token (e.g. `/app_data/:r`) physically cannot write, so a pull-only mirror is safe. Other types are rejected with a clear error.
304
+ - The remote root must **already** contain this group's `.meta/group.json` with a matching `kind` / `id` / `instanceId`. A read-only backend never claims, rewrites, or aliases identity — if the descriptor is missing or mismatched, the backend is reported as a conflict (`canAdoptRemoteInstance` may still be offered for instance-only mismatches) and no pair is created.
305
+ - Tombstones: a read-only backend never confirms tombstones (it is excluded from `tombstoneTargets()` / `allBackendIds()` / GC quorum), and its `.meta/` subtree is excluded from the pair. Remote deletions still reach the local store through the normal tombstone prefetch/merge path; local deletions never propagate upward.
306
+ - Endpoint dedup treats `ro` and `rw` as distinct, so the same remote can be mirrored read-only alongside a writable replica without being collapsed.
307
+ - On-device repeated "extra" files produce harmless delete-skip results each cycle (the target's `unlink` is a no-op). This is intentional: a read-only mirror must not delete local data it did not create.
308
+
309
+ ### Credential Lifecycle (`credentialMode: 'config'`)
310
+
311
+ A referenced account can change after the data backend connected, and the backend instance keeps the credentials it was created with. Rather than hot-swapping secrets inside a live backend, the library exposes three explicit operations:
312
+
313
+ | Operation | What it does | Failure mode |
314
+ |---|---|---|
315
+ | `getAppDataGroupCredentialStaleness(groupId)` | compares each `config` backend's account fingerprint (32-bit FNV-1a over account fields, stored at connect time) with the source's current values | source gone / unparsable → reported as stale with a reason |
316
+ | `refreshAppDataGroupCredentials(groupId, backendIds?)` | re-resolves every referenced account first, then rebuilds **all** sync pairs once, so nothing is half-old | any resolve error aborts before teardown (old pairs stay) |
317
+ | `convertAppDataGroupCredentialMode(groupId, 'config' \| 'inline')` | batch converts every backend with account fields; auto-pairs a config backend only when exactly one of the same type exists | per-backend failures land in `skipped` with a reason |
318
+
319
+ **Staleness is detected, never repaired silently.** The fingerprint is irreversible and is exposed only through `BackendSyncState.credentialFingerprint`, so `getBackendSyncStates()` never leaks the secret. A stale backend keeps working until the next reconnect — the UI is expected to show a "credentials changed, refresh" hint instead of blocking sync. Refresh is whole-group because a pair rebuild is the only way to replace runtime credentials, and rebuilding per backend would restart identity/handshake N times.
320
+
321
+
281
322
  ## 5. Sync Rules (`.meta/sync-rules.json`)
282
323
 
283
324
  ```json
package/README.md CHANGED
@@ -84,6 +84,35 @@ Global build → global variable mapping:
84
84
 
85
85
  `zen-fs-config` auto-detects these globals (`window.ZenFSGitee` / `window.ZenFSGitHub` / `window.ZenFSRemoteStorage`) and uses them directly, skipping the bare `import()`. Because all three packages declare a `browser`/`unpkg` field, a bare package URL (e.g. `https://unpkg.com/zen-fs-github`) also returns the global build — so you may shorten the three `<script>` lines to bare URLs if you prefer.
86
86
 
87
+ ## Cloud backends in a bundler (Vite / Rollup / webpack)
88
+
89
+ The core loads cloud backends through a **variable** `import(pkg)` (`pkg` is decided at runtime from `type: 'Gitee'` etc.). Bundlers cannot resolve a variable specifier, so in a Vite/webpack app this either throws `TypeError: Failed to resolve module specifier` or silently degrades into `import("zen-fs-gitee?import")`. The failure is caught and rethrown as:
90
+
91
+ > `Backend package "zen-fs-gitee" is not available...`
92
+
93
+ That error means *"the bundler could not resolve this at build time"*, **not** "the package is missing from node_modules".
94
+
95
+ Each cloud backend therefore has an **opt-in subpath entry** whose body is a single *literal* `import()`. Import it once in your app entry (or anywhere that runs before the first `createBackend()` / `connect()` / `initStorage()`), and the backend becomes resolvable while everything else still stays optional:
96
+
97
+ ```js
98
+ // src/main.js — before app startup
99
+ import 'zen-fs-config/backends/gitee' // → zen-fs-gitee
100
+ import 'zen-fs-config/backends/github' // → zen-fs-github
101
+ import 'zen-fs-config/backends/webdav' // → zen-fs-webdav
102
+ import 'zen-fs-config/backends/remotestorage' // → zen-fs-remotestoragejs
103
+ ```
104
+
105
+ Notes:
106
+ - Importing an entry does **not** duplicate the registry: all entries share one chunk with the main entry, so the backend map stays single-instance, and the package itself is still code-split (only fetched when the backend is first used).
107
+ - The backend metadata (options schema, identity/account fields) always comes from the library — hosts should not re-declare it.
108
+ - If you prefer to own the registration, the same entries work with an injected loader:
109
+ ```js
110
+ import { registerGiteeBackend } from 'zen-fs-config';
111
+ registerGiteeBackend(() => import('zen-fs-gitee')); // literal on your side
112
+ ```
113
+ - An import map (`"zen-fs-gitee": "/vendor/zen-fs-gitee.js"`) also fixes the variable import, but requires a served file plus a `<script type="importmap">` in every HTML entry.
114
+ - `<script>`-only pages keep using the UMD globals described above — unchanged.
115
+
87
116
  ## Quick Start
88
117
 
89
118
  ### 1. Initialize (zero-configuration)
@@ -326,18 +355,27 @@ zen-fs-config bundles two built-in backends (no install needed):
326
355
  - **IndexedDB** — local primary backend (based on `@zenfs/dom`)
327
356
  - **InMemory** — in-memory backend (based on `@zenfs/core`), useful for testing
328
357
 
329
- Three **cloud backend types are pre-registered by the core** (lazy-loaded on first use): `GitHub` (`zen-fs-github`), `Gitee` (`zen-fs-gitee`), and `RemoteStorage` (`zen-fs-remotestoragejs`). You do **not** need to call `registerBackend` for them — just install the matching package (see Installation) and pass `type: 'Gitee'`, etc. to `addBackend`/`connect`. `registerBackend` is only needed to add a *fully custom* backend or to override a built-in registration:
358
+ Three **cloud backend types are pre-registered by the core** (lazy-loaded on first use): `GitHub` (`zen-fs-github`), `Gitee` (`zen-fs-gitee`), `RemoteStorage` (`zen-fs-remotestoragejs`), plus `WebDAV` (`zen-fs-webdav`). You do **not** need to call `registerBackend` for them — install the matching package (see Installation), then in a bundler app import the matching subpath entry (see "Cloud backends in a bundler") and pass `type: 'Gitee'`, etc. to `addBackend`/`connect`. `registerBackend` is only needed to add a *fully custom* backend or to override a built-in registration — and when overriding, write a **literal** `import()`, because a variable specifier is exactly what bundlers cannot resolve:
330
359
 
331
360
  ```typescript
332
361
  import { registerBackend } from 'zen-fs-config';
333
362
 
334
363
  // Example: override the built-in Gitee registration with a custom factory
335
364
  registerBackend('Gitee', async (options) => {
336
- const { Gitee } = await import('zen-fs-gitee');
365
+ const { Gitee } = await import('zen-fs-gitee'); // literal specifier — bundler can see it
337
366
  return Gitee.create(options);
338
367
  });
339
368
  ```
340
369
 
370
+ Prefer the narrower helper when you only want to supply the loader — metadata stays owned by the library:
371
+
372
+ ```typescript
373
+ import { registerGiteeBackend } from 'zen-fs-config';
374
+ registerGiteeBackend(() => import('zen-fs-gitee'));
375
+ ```
376
+
377
+ Available helpers: `registerGiteeBackend`, `registerGithubBackend`, `registerRemoteStorageBackend`, `registerWebdavBackend`. Each accepts an optional loader; without it the built-in lazy loader is used, which still supports UMD globals in `<script>` pages.
378
+
341
379
  ## Architecture
342
380
 
343
381
  ```
package/README.zh-CN.md CHANGED
@@ -81,6 +81,31 @@ npm install zen-fs-remotestoragejs # RemoteStorage 副本
81
81
 
82
82
  `zen-fs-config` 会自动识别这些全局变量(`window.ZenFSGitee` / `window.ZenFSGitHub` / `window.ZenFSRemoteStorage`)并直接使用,跳过裸 `import()`。由于三个包都声明了 `browser`/`unpkg` 字段,裸包名 URL(如 `https://unpkg.com/zen-fs-github`)同样会返回全局构建——如果你愿意,也可以把前面三行 `<script>` 简写成裸 URL。
83
83
 
84
+ ## 打包环境(Vite / Rollup / webpack)里怎么接云后端
85
+
86
+ 核心是通过**运行时变量**调用 `import(pkg)` 加载云后端的(`pkg` 由 `type: 'Gitee'` 等决定)。打包器无法静态解析变量形式,于是要么抛 `TypeError: Failed to resolve module specifier`,要么被改写成 `import("zen-fs-gitee?import")`。这个失败被捕获后统一重抛成:
87
+
88
+ > `Backend package "zen-fs-gitee" is not available...`
89
+
90
+ 这句话的含义是**「打包时没能解析到」**,并**不是**「node_modules 里没装」。
91
+
92
+ 因此每个云后端都提供了一个可选的**子路径入口**,入口里是唯一一句**字面量** `import()`。在应用入口(或任何早于首次 `createBackend()` / `connect()` / `initStorage()` 执行的位置)引入一次即可,其余部分依旧保持可选:
93
+
94
+ ```js
95
+ // src/main.js —— 在应用启动之前
96
+ import 'zen-fs-config/backends/gitee' // → zen-fs-gitee
97
+ import 'zen-fs-config/backends/github' // → zen-fs-github
98
+ import 'zen-fs-config/backends/webdav' // → zen-fs-webdav
99
+ import 'zen-fs-config/backends/remotestorage' // → zen-fs-remotestoragejs
100
+ ```
101
+
102
+ 说明:
103
+ - 引入入口**不会**产生第二份注册表:所有入口与主入口共享同一个 chunk,后端列表仍是单实例;后端包本身依旧按需分包(首次使用时才下载)。
104
+ - 后端的元数据(参数 schema、identity/account 字段)始终由库提供,宿主不要另抄一份。
105
+ - 如果你想自己掌控注册:`import { registerGiteeBackend } from 'zen-fs-config'; registerGiteeBackend(() => import('zen-fs-gitee'));`(字面量写在你这一侧)。
106
+ - import map(`"zen-fs-gitee": "/vendor/zen-fs-gitee.js"`)也能解决变量 import,但需要额外提供可访问的文件,并在每个 HTML 入口加 `<script type="importmap">`。
107
+ - 纯 `<script>` 页面继续用上面那套 UMD 全局变量,行为不变。
108
+
84
109
  ## 快速开始
85
110
 
86
111
  ### 1. 初始化(零参数)
@@ -287,7 +312,32 @@ zen-fs-config 内置两个后端(无需安装):
287
312
  - **IndexedDB** — 本地主后端(基于 `@zenfs/dom`)
288
313
  - **InMemory** — 内存后端(基于 `@zenfs/core`),用于测试
289
314
 
290
- 另有三种**云后端类型由核心预注册**(首次使用时懒加载):`GitHub`(`zen-fs-github`)、`Gitee`(`zen-fs-gitee`)、`RemoteStorage`(`zen-fs-remotestoragejs`)。你**无需**为它们调用 `registerBackend`——只需先安装对应包(见「安装」),再把 `type: 'Gitee'` 等传给 `addBackend`/`connect` 即可。`registerBackend` 仅在你需要新增**完全自定义**的后端或覆盖内置注册时才用到:
315
+ 另有四种**云后端类型由核心预注册**(首次使用时懒加载):`GitHub`(`zen-fs-github`)、`Gitee`(`zen-fs-gitee`)、`RemoteStorage`(`zen-fs-remotestoragejs`)、`WebDAV`(`zen-fs-webdav`)。你**无需**为它们调用 `registerBackend`——安装对应包(见「安装」)后,在打包环境里再引入对应的子路径入口(见上文「打包环境里怎么接云后端」),然后把 `type: 'Gitee'` 等传给 `addBackend`/`connect` 即可。`registerBackend` 仅在你需要新增**完全自定义**的后端或覆盖内置注册时才用到——覆盖时请写字面量 `import()`,因为变量形式正是打包器解析不了的那种写法:
316
+
317
+ ```typescript
318
+ import { registerBackend } from 'zen-fs-config';
319
+
320
+ // 示例:用自定义工厂覆盖内置的 Gitee 注册
321
+ registerBackend('Gitee', async (options) => {
322
+ const { Gitee } = await import('zen-fs-gitee'); // 字面量,打包器可见
323
+ return Gitee.create(options);
324
+ });
325
+
326
+ // 示例:新增一个自定义后端(如 S3)
327
+ registerBackend('S3Bucket', async (options) => {
328
+ const { S3Bucket } = await import('@zenfs/core');
329
+ return S3Bucket.create(options);
330
+ });
331
+ ```
332
+
333
+ 如果你只是想换个加载方式、不想接管元数据,用更窄的 helper:
334
+
335
+ ```typescript
336
+ import { registerGiteeBackend } from 'zen-fs-config';
337
+ registerGiteeBackend(() => import('zen-fs-gitee'));
338
+ ```
339
+
340
+ 可用的 helper:`registerGiteeBackend`、`registerGithubBackend`、`registerRemoteStorageBackend`、`registerWebdavBackend`,都接受可选的 loader 参数;不传则沿用内置懒加载(`<script>` 页面的 UMD 全局回退依然有效)。
291
341
 
292
342
  ```typescript
293
343
  import { registerBackend } from 'zen-fs-config';
@@ -0,0 +1,44 @@
1
+ import {
2
+ GITEE_BACKEND_METADATA,
3
+ GITHUB_BACKEND_METADATA,
4
+ REMOTESTORAGE_BACKEND_METADATA,
5
+ WEBDAV_BACKEND_METADATA,
6
+ backendSupportsAccessMode,
7
+ createBackend,
8
+ getAccountFields,
9
+ getBackendMetadata,
10
+ hasBackend,
11
+ listBackendMetadata,
12
+ listBackends,
13
+ mergeAccountFields,
14
+ registerBackend,
15
+ registerGiteeBackend,
16
+ registerGithubBackend,
17
+ registerRemoteStorageBackend,
18
+ registerWebdavBackend,
19
+ stripAccountFields,
20
+ unregisterBackend,
21
+ wrapZenFSFileSystem
22
+ } from "./chunk-S2OW2HJC.mjs";
23
+ export {
24
+ GITEE_BACKEND_METADATA,
25
+ GITHUB_BACKEND_METADATA,
26
+ REMOTESTORAGE_BACKEND_METADATA,
27
+ WEBDAV_BACKEND_METADATA,
28
+ backendSupportsAccessMode,
29
+ createBackend,
30
+ getAccountFields,
31
+ getBackendMetadata,
32
+ hasBackend,
33
+ listBackendMetadata,
34
+ listBackends,
35
+ mergeAccountFields,
36
+ registerBackend,
37
+ registerGiteeBackend,
38
+ registerGithubBackend,
39
+ registerRemoteStorageBackend,
40
+ registerWebdavBackend,
41
+ stripAccountFields,
42
+ unregisterBackend,
43
+ wrapZenFSFileSystem
44
+ };
@@ -0,0 +1,2 @@
1
+
2
+ export { }
@@ -0,0 +1,6 @@
1
+ import {
2
+ registerGiteeBackend
3
+ } from "../chunk-S2OW2HJC.mjs";
4
+
5
+ // src/backends/gitee.ts
6
+ registerGiteeBackend(() => import("zen-fs-gitee"));
@@ -0,0 +1,2 @@
1
+
2
+ export { }
@@ -0,0 +1,6 @@
1
+ import {
2
+ registerGithubBackend
3
+ } from "../chunk-S2OW2HJC.mjs";
4
+
5
+ // src/backends/github.ts
6
+ registerGithubBackend(() => import("zen-fs-github"));
@@ -0,0 +1,2 @@
1
+
2
+ export { }
@@ -0,0 +1,6 @@
1
+ import {
2
+ registerRemoteStorageBackend
3
+ } from "../chunk-S2OW2HJC.mjs";
4
+
5
+ // src/backends/remotestorage.ts
6
+ registerRemoteStorageBackend(() => import("zen-fs-remotestoragejs"));
@@ -0,0 +1,2 @@
1
+
2
+ export { }
@@ -0,0 +1,6 @@
1
+ import {
2
+ registerWebdavBackend
3
+ } from "../chunk-S2OW2HJC.mjs";
4
+
5
+ // src/backends/webdav.ts
6
+ registerWebdavBackend(() => import("zen-fs-webdav"));