@leonhoy/dsh-localstate-sync 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/README.md +120 -2
- package/client.js +969 -0
- package/cordis.patch.yml +10 -0
- package/docs/en.md +111 -0
- package/icon.svg +8 -0
- package/index.js +257 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/market/README.md +52 -0
- package/market/build-index.mjs +99 -0
- package/market/index.json +66 -0
- package/package.json +66 -4
- package/seeder.js +45 -0
- package/store.js +330 -0
- package/test/verify.mjs +435 -0
package/cordis.patch.yml
ADDED
package/docs/en.md
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
# Browser state sync
|
|
2
|
+
|
|
3
|
+
Some plugin settings in this app exist only in `localStorage`: keybindings, the right sidebar's tab layout, the last tab selected in the schedule panel, the plugin-market registry choice. Clear site data once, open the same Harness through a second address (a default port and a reverse proxy port are two different origins), or switch browsers, and those settings are gone.
|
|
4
|
+
|
|
5
|
+
This bundle keeps them in one JSON file on the Host and writes them back **before the page boots**:
|
|
6
|
+
|
|
7
|
+
```
|
|
8
|
+
$DSH_HOME/localstate-sync/state.json
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
中文说明:[README.md](../README.md)
|
|
12
|
+
|
|
13
|
+
## How it works
|
|
14
|
+
|
|
15
|
+
1. **Capture.** The client bundle wraps `Storage.prototype.setItem / removeItem / clear`. It only records writes where `this === window.localStorage` and the key matches the allowlist. The original is always called first, its own bookkeeping sits in `try/catch`, and the original's exception behavior is unchanged. A 400 ms debounce batches the recorded changes into one `POST`.
|
|
16
|
+
2. **Persist.** The Host route `POST /api/localstate.v1` merges each key into the JSON document and assigns it a monotonically increasing `at` revision. Writes are atomic (`tmp` + `rename`), the file is mode `0600`, and bursts are coalesced over 120 ms.
|
|
17
|
+
3. **Restore.** `webserver/index-inject` writes the snapshot into `<head>` as `globalThis.__DSH_LOCALSTATE__`, immediately followed by an inline script that seeds `localStorage` from it **before the application boots**. No reload is needed, and no plugin can win the race by reading an old value during its own initialization.
|
|
18
|
+
4. **No fighting.** The browser keeps `__dsh.localstate.meta.v1`, recording the revision it has applied per key, and writes a value back only when the Host revision is newer. Deletes are stored as tombstones (`null`), so a deleted key does not come back on the next start.
|
|
19
|
+
5. **Visible conflicts.** Every write carries the revision it was built on (`base`). If that copy has moved on in another browser, the Host does not overwrite it: the response lists the key under `conflicts` with the remote value and revision, and the browser resends once with the fresh base — so the side that just edited wins, on purpose. If that retry clashes again, the local value is kept, the pair is recorded in `globalThis.__DSH_LOCALSTATE_CONFLICTS__`, and the config form shows a line about it. There is no retry loop.
|
|
20
|
+
|
|
21
|
+
## Notices
|
|
22
|
+
|
|
23
|
+
Nothing is announced while the revisions (`at`) already agree. Only two kinds of drift speak up:
|
|
24
|
+
|
|
25
|
+
| Situation | Notice | Then |
|
|
26
|
+
| --- | --- | --- |
|
|
27
|
+
| Saving and pushing while the local revision is older | A bottom-right alert: "Push failed: the synced copy already moved to revision N. Reload to take the newer value." | The local value stays on screen but no longer overwrites the shared copy; the reload picks the shared one up |
|
|
28
|
+
| Booting while the local revision is older | "Restored N keys from the synced copy (the local values were older)." | Already on the shared value |
|
|
29
|
+
|
|
30
|
+
Conflicts are decided on the write path: a batch carries `base` (the `at` each value was written
|
|
31
|
+
on), the Host answers `conflicts` for keys that moved on, the client resends once against the fresh
|
|
32
|
+
revision, and a second conflict reports as above. The configuration page also lists the keys that
|
|
33
|
+
kept their local value.
|
|
34
|
+
|
|
35
|
+
## Configuration
|
|
36
|
+
|
|
37
|
+
Open this bundle's card on the **Plugins** page and the form renders inside it (values are written into the profile's `cordis.patch.yml` patch layer, and the bundle restarts once). The equivalent YAML:
|
|
38
|
+
|
|
39
|
+
```yaml
|
|
40
|
+
- insert:
|
|
41
|
+
- id: localstate-sync
|
|
42
|
+
name: '@leonhoy/dsh-localstate-sync'
|
|
43
|
+
config:
|
|
44
|
+
includePrefixes: ['dsh.'] # collect keys with these prefixes
|
|
45
|
+
includeExact: [] # extra exact keys
|
|
46
|
+
excludeExact: [] # exact keys to skip
|
|
47
|
+
maxBytes: 262144 # per-value and whole-snapshot limit
|
|
48
|
+
maxKeys: 2000 # key cap: tombstones go first, then the oldest
|
|
49
|
+
injectMaxBytes: 131072 # above this the snapshot is not injected; the page GETs it
|
|
50
|
+
injectSnapshot: true # false = save only, never restore automatically
|
|
51
|
+
capture: true # false = stop capturing (existing data is kept)
|
|
52
|
+
file: 'localstate-sync/state.json'
|
|
53
|
+
language: auto # language of the notices and the form: auto | en | zh
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
The form talks to `GET/POST /api/localstate.config.v1`: GET returns the field descriptors, current values, which fields are explicitly overridden, and the resolved state-file path; POST submits only the changed fields, and the Host validates them through `configEditor` before touching the YAML, so an invalid value is rejected (`400`) before it lands. That route keeps working while the bundle is disabled (`enabled: false`), so it can be turned back on from the UI.
|
|
57
|
+
|
|
58
|
+
Session-scoped and pure-UI keys (`CONVERSATION_STORE_KEY.*`, width preferences) are **not** collected by default because their names do not start with `dsh.`. Add them to `includeExact` when you want them.
|
|
59
|
+
|
|
60
|
+
A useful example: the `dsh-purge` "User notice" acknowledgement lives in `localStorage` under `dsh-purge-user-notice-v1` (value `"1"`, **not** a cookie). Its name uses hyphens, not dots, so it misses the `dsh.` prefix and the notice appears again in every new browser. Add it to `includeExact` to remember it across browsers:
|
|
61
|
+
|
|
62
|
+
```json
|
|
63
|
+
{ "config": { "includeExact": ["dsh-purge-user-notice-v1"] } }
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
No reload is needed after changing the allowlist: a successful form save dispatches a page event and the client re-reads its configuration in place. Changes made in another tab take effect on the next load.
|
|
67
|
+
|
|
68
|
+
## Boundaries and known limits
|
|
69
|
+
|
|
70
|
+
- Only `localStorage` **string** values are synchronized. A value above `maxBytes` rejects the whole batch (`413`) instead of being truncated.
|
|
71
|
+
- One document is kept per profile. `localStorage` itself stays per-origin; the point of this bundle is to let different origins see the same values, not to merge the origins.
|
|
72
|
+
- What gets persisted is another plugin's private format. An upstream schema change will feed it an old value; DSH reads its own state defensively (a parse failure drops only that key), so the worst case is one item being reset.
|
|
73
|
+
- Under Desktop (`file://`) there is no `/api` channel, and the client skips itself.
|
|
74
|
+
- Both routes are exact `/api` routes behind the Host's cookie authentication, and only the owner principal can read or write them. They add no permission surface.
|
|
75
|
+
- The form registers on the `plugins.bundle.config` slot, keyed by the package name. On a host without a `slots` service (rare) the form does not appear; capture and restore are unaffected.
|
|
76
|
+
- Conflicts are detected on **write** only. There is no live cross-tab or cross-browser push (no `storage` listener), so the two sides converge on the next load; within one conflict the side that resends last wins — this is not a merge algorithm.
|
|
77
|
+
|
|
78
|
+
## Install
|
|
79
|
+
|
|
80
|
+
Use **Plugins → Add plugin** and pass this directory, or call `plugin_manager` `install_bundle` with it.
|
|
81
|
+
|
|
82
|
+
The bundle is **linked** into the profile, not copied, so editing these files and refreshing the page is enough; conversely, moving or deleting this directory breaks the install. Host-side code is not hot-reloaded: toggle the bundle off and on in the Plugins page (or restart the web server) to re-import it.
|
|
83
|
+
|
|
84
|
+
`package.json` declares a `schemastery` dependency (used by the `Config` schema). A linked install resolves dependencies from this directory's own `node_modules`, so run `npm install` here once.
|
|
85
|
+
|
|
86
|
+
## Verify
|
|
87
|
+
|
|
88
|
+
```bash
|
|
89
|
+
cat "$DSH_HOME/localstate-sync/state.json"
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
Each key looks like `{"v": "...", "at": 12, "t": 1764...}`; `{"del": true}` means the key was deleted and only its tombstone remains.
|
|
93
|
+
|
|
94
|
+
Offline self-check (no browser needed):
|
|
95
|
+
|
|
96
|
+
```bash
|
|
97
|
+
node test/verify.mjs # 73/73 checks passed
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
It drives the real Host half through a fake Cordis context (route registration, index injection, merge, tombstones, allowlist, config route, write-time conflicts), loads the real client bundle with `node:vm` (slot registration, config-cell key, capture patch installed, a conflict resent once and then kept locally without looping), and runs the injected seeder script.
|
|
101
|
+
|
|
102
|
+
## Files
|
|
103
|
+
|
|
104
|
+
| File | Role |
|
|
105
|
+
| --- | --- |
|
|
106
|
+
| `index.js` | Host half: data route, config route, `Config` schema, `index-inject` |
|
|
107
|
+
| `store.js` | Document I/O: merge, revisions, tombstones, pruning, atomic write |
|
|
108
|
+
| `seeder.js` | Inline `<head>` script that seeds `localStorage` before boot |
|
|
109
|
+
| `client.js` | Browser half: capture patch, flush/retry, configuration form |
|
|
110
|
+
| `cordis.patch.yml` | The row inserted into the profile (with default config) |
|
|
111
|
+
| `locale/*.json` | Plugin title/description and the detail-document pointers |
|
package/icon.svg
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" width="36" height="36" viewBox="0 0 36 36">
|
|
2
|
+
<rect x="3" y="8" width="18" height="15" rx="3" fill="none" stroke="#1f8a70" stroke-width="2"/>
|
|
3
|
+
<path d="M3 13h18" fill="none" stroke="#1f8a70" stroke-width="2" stroke-linecap="round"/>
|
|
4
|
+
<circle cx="6.5" cy="10.5" r="1" fill="#1f8a70"/>
|
|
5
|
+
<circle cx="10" cy="10.5" r="1" fill="#1f8a70"/>
|
|
6
|
+
<path d="M26 9v17" fill="none" stroke="#1f8a70" stroke-width="2" stroke-linecap="round"/>
|
|
7
|
+
<path d="M21.5 21.5 26 26l4.5-4.5" fill="none" stroke="#1f8a70" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
|
|
8
|
+
</svg>
|
package/index.js
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Host half of browser-state sync.
|
|
3
|
+
*
|
|
4
|
+
* Serves one exact Fetch route under the shared `/api` channel and injects the
|
|
5
|
+
* current snapshot into the page `<head>` before the application boots, so the
|
|
6
|
+
* browser can restore values without a reload.
|
|
7
|
+
*/
|
|
8
|
+
import { readFileSync } from 'node:fs'
|
|
9
|
+
import { dirname, join } from 'node:path'
|
|
10
|
+
import { fileURLToPath } from 'node:url'
|
|
11
|
+
import Schema from 'schemastery'
|
|
12
|
+
import { DEFAULT_CONFIG, LANGUAGES, createStore, normalizeConfig, resolveStorePath } from './store.js'
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* The row's config schema. It is what the Plugins page renders as a form and
|
|
16
|
+
* what the loader validates before {@link apply} runs.
|
|
17
|
+
*/
|
|
18
|
+
export const Config = Schema.object({
|
|
19
|
+
enabled: Schema.boolean().default(true).description('Turn the whole bundle off without removing it.'),
|
|
20
|
+
capture: Schema.boolean().default(true).description('Record browser localStorage writes. Existing data is kept when this is off.'),
|
|
21
|
+
injectSnapshot: Schema.boolean().default(true).description('Restore the snapshot in the page head before the app boots. When off, values are only saved.'),
|
|
22
|
+
file: Schema.string().default('localstate-sync/state.json').description('State file, relative to the DSH home.'),
|
|
23
|
+
includePrefixes: Schema.array(Schema.string()).default(['dsh.']).description('Collect keys that start with one of these prefixes.'),
|
|
24
|
+
includeExact: Schema.array(Schema.string()).default([]).description('Collect these exact keys in addition to the prefixes.'),
|
|
25
|
+
excludeExact: Schema.array(Schema.string()).default([]).description('Never collect these exact keys.'),
|
|
26
|
+
maxBytes: Schema.number().min(1024).default(262144).description('Largest accepted value and snapshot size, in bytes. A larger batch is rejected, never truncated.'),
|
|
27
|
+
maxKeys: Schema.number().min(1).default(2000).description('Key cap. Tombstones are dropped first, then the oldest values.'),
|
|
28
|
+
injectMaxBytes: Schema.number().min(0).default(131072).description('Above this size the snapshot is not injected; the page pulls it over the route instead.'),
|
|
29
|
+
language: Schema.union(LANGUAGES.map((value) => Schema.const(value))).default('auto').description('Language of the notices and the settings form. auto follows the browser, then the DSH locale.'),
|
|
30
|
+
})
|
|
31
|
+
|
|
32
|
+
/** Route path; it carries the `/api` prefix the shared channel matches on. */
|
|
33
|
+
export const ROUTE_PATH = '/api/localstate.v1'
|
|
34
|
+
|
|
35
|
+
/** Route the Plugins page uses to read and edit this row's config. */
|
|
36
|
+
export const CONFIG_ROUTE_PATH = '/api/localstate.config.v1'
|
|
37
|
+
|
|
38
|
+
/** Global the injected snapshot is published as. */
|
|
39
|
+
export const GLOBAL_NAME = '__DSH_LOCALSTATE__'
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Flatten the config schema into the field list the browser form renders.
|
|
43
|
+
* Reading `Config.dict` keeps the form in step with {@link Config}: a field is
|
|
44
|
+
* added, renamed, or re-typed in exactly one place.
|
|
45
|
+
* @returns one descriptor per config field, in declaration order.
|
|
46
|
+
*/
|
|
47
|
+
// schemastery encodes a union of constants as a refs blob; pull the literal values out so
|
|
48
|
+
// the settings form can render a select without importing the schema library client-side.
|
|
49
|
+
const UNION_OPTIONS = { language: LANGUAGES }
|
|
50
|
+
|
|
51
|
+
export function fieldDescriptors() {
|
|
52
|
+
const dict = Config.dict !== null && typeof Config.dict === 'object' ? Config.dict : {}
|
|
53
|
+
const out = []
|
|
54
|
+
for (const name of Object.keys(dict)) {
|
|
55
|
+
const schema = dict[name]
|
|
56
|
+
const meta = schema?.meta !== null && typeof schema?.meta === 'object' ? schema.meta : {}
|
|
57
|
+
const kind = typeof schema?.type === 'string' ? schema.type : 'string'
|
|
58
|
+
const descriptor = {
|
|
59
|
+
name,
|
|
60
|
+
kind,
|
|
61
|
+
description: typeof meta.description === 'string' ? meta.description : '',
|
|
62
|
+
}
|
|
63
|
+
if (Object.hasOwn(meta, 'default')) descriptor.default = meta.default
|
|
64
|
+
if (typeof meta.min === 'number') descriptor.min = meta.min
|
|
65
|
+
if (typeof meta.max === 'number') descriptor.max = meta.max
|
|
66
|
+
if (kind === 'array') descriptor.item = typeof schema?.inner?.type === 'string' ? schema.inner.type : 'string'
|
|
67
|
+
if (kind === 'union' && Array.isArray(UNION_OPTIONS[name])) descriptor.options = [...UNION_OPTIONS[name]]
|
|
68
|
+
out.push(descriptor)
|
|
69
|
+
}
|
|
70
|
+
return out
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const SEEDER_FILE = join(dirname(fileURLToPath(import.meta.url)), 'seeder.js')
|
|
74
|
+
|
|
75
|
+
let seederText
|
|
76
|
+
function readSeeder() {
|
|
77
|
+
if (seederText === undefined) {
|
|
78
|
+
try {
|
|
79
|
+
seederText = readFileSync(SEEDER_FILE, 'utf8').trim()
|
|
80
|
+
} catch {
|
|
81
|
+
seederText = ''
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return seederText
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function jsonResponse(status, value) {
|
|
88
|
+
return new Response(JSON.stringify(value), {
|
|
89
|
+
status,
|
|
90
|
+
headers: {
|
|
91
|
+
'content-type': 'application/json; charset=utf-8',
|
|
92
|
+
'cache-control': 'no-store',
|
|
93
|
+
},
|
|
94
|
+
})
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Serve the row's own config to the Plugins page and accept edits back into the
|
|
99
|
+
* profile patch layer through the Host config editor.
|
|
100
|
+
* @param ctx - the plugin context.
|
|
101
|
+
* @param cfg - the normalized config the running instance uses.
|
|
102
|
+
* @param raw - the row's raw config, used to mark explicit overrides.
|
|
103
|
+
*/
|
|
104
|
+
function registerConfigRoute(ctx, cfg, raw) {
|
|
105
|
+
const fields = fieldDescriptors()
|
|
106
|
+
|
|
107
|
+
const handle = async (request) => {
|
|
108
|
+
let editor
|
|
109
|
+
let entry
|
|
110
|
+
try {
|
|
111
|
+
editor = ctx.get('configEditor')
|
|
112
|
+
entry = ctx.fiber?.entry
|
|
113
|
+
} catch {
|
|
114
|
+
editor = undefined
|
|
115
|
+
entry = undefined
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
if (request.method === 'GET') {
|
|
119
|
+
return jsonResponse(200, {
|
|
120
|
+
ok: true,
|
|
121
|
+
fields,
|
|
122
|
+
values: cfg,
|
|
123
|
+
explicit: Object.keys(raw),
|
|
124
|
+
filePath: resolveStorePath(cfg),
|
|
125
|
+
writable: editor !== undefined && entry !== undefined,
|
|
126
|
+
})
|
|
127
|
+
}
|
|
128
|
+
if (request.method !== 'POST') return new Response('method not allowed', { status: 405 })
|
|
129
|
+
if (editor === undefined || entry === undefined) {
|
|
130
|
+
return jsonResponse(501, { ok: false, reason: 'config-editor-unavailable' })
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
let body
|
|
134
|
+
try {
|
|
135
|
+
body = await request.json()
|
|
136
|
+
} catch {
|
|
137
|
+
return jsonResponse(400, { ok: false, reason: 'invalid-json' })
|
|
138
|
+
}
|
|
139
|
+
const draft = body !== null && typeof body === 'object' ? body.config : undefined
|
|
140
|
+
if (draft === null || typeof draft !== 'object' || Array.isArray(draft)) {
|
|
141
|
+
return jsonResponse(400, { ok: false, reason: 'invalid-config' })
|
|
142
|
+
}
|
|
143
|
+
const unknown = Object.keys(draft).filter((name) => !Object.hasOwn(DEFAULT_CONFIG, name))
|
|
144
|
+
if (unknown.length > 0) {
|
|
145
|
+
return jsonResponse(400, { ok: false, reason: 'unknown-field', fields: unknown })
|
|
146
|
+
}
|
|
147
|
+
try {
|
|
148
|
+
await editor.edit(entry, (current) => ({ ...current, ...draft }))
|
|
149
|
+
} catch (error) {
|
|
150
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
151
|
+
return jsonResponse(400, { ok: false, reason: 'rejected', message })
|
|
152
|
+
}
|
|
153
|
+
return jsonResponse(200, { ok: true })
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
ctx.inject(['webServer', 'connection', 'configEditor'], (web) => {
|
|
157
|
+
web.effect(
|
|
158
|
+
() => web.connection.fetch.register({ path: CONFIG_ROUTE_PATH, methods: ['GET', 'POST'], requestBody: 'buffered', fetch: handle }),
|
|
159
|
+
'localstate-sync: config route',
|
|
160
|
+
)
|
|
161
|
+
})
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Register the route and the index injection for one profile.
|
|
166
|
+
* @param ctx - the plugin context.
|
|
167
|
+
* @param config - the patch row's config, already normalized by the caller.
|
|
168
|
+
*/
|
|
169
|
+
export function apply(ctx, config) {
|
|
170
|
+
const resolved = config !== null && typeof config === 'object' && !Array.isArray(config) ? config : {}
|
|
171
|
+
// `config` above is the resolved value (defaults filled in); the patch row
|
|
172
|
+
// itself only carries the keys the operator set, which is what "explicit"
|
|
173
|
+
// means in the form.
|
|
174
|
+
const literal = ctx.fiber !== undefined && ctx.fiber.entry !== undefined ? ctx.fiber.entry.options.config : undefined
|
|
175
|
+
const raw = literal !== null && typeof literal === 'object' && !Array.isArray(literal) ? literal : resolved
|
|
176
|
+
const cfg = normalizeConfig({ ...raw, ...resolved })
|
|
177
|
+
|
|
178
|
+
// The config route stays up even with `enabled: false`, so the form on the
|
|
179
|
+
// Plugins page can always turn the bundle back on.
|
|
180
|
+
registerConfigRoute(ctx, cfg, raw)
|
|
181
|
+
|
|
182
|
+
if (!cfg.enabled) return
|
|
183
|
+
|
|
184
|
+
const store = createStore(cfg)
|
|
185
|
+
const log = (level, message) => {
|
|
186
|
+
try {
|
|
187
|
+
ctx.logger?.[level]?.(message)
|
|
188
|
+
} catch {
|
|
189
|
+
// Logging must never break request handling.
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
if (store.recovered !== undefined) {
|
|
193
|
+
log('warn', `[localstate-sync] unreadable state moved to ${store.recovered.aside}: ${store.recovered.message}`)
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// The browser needs the allowlist and the chosen language both at boot (injected global)
|
|
197
|
+
// and after a live config save (this route), so one shape serves both.
|
|
198
|
+
const browserConfig = () => ({
|
|
199
|
+
prefixes: cfg.includePrefixes,
|
|
200
|
+
exact: cfg.includeExact,
|
|
201
|
+
exclude: cfg.excludeExact,
|
|
202
|
+
capture: cfg.capture,
|
|
203
|
+
language: cfg.language,
|
|
204
|
+
})
|
|
205
|
+
|
|
206
|
+
const handle = async (request) => {
|
|
207
|
+
if (request.method === 'GET') {
|
|
208
|
+
return jsonResponse(200, { ...store.injection(cfg.injectMaxBytes), config: browserConfig() })
|
|
209
|
+
}
|
|
210
|
+
if (request.method === 'POST') {
|
|
211
|
+
let body
|
|
212
|
+
try {
|
|
213
|
+
body = await request.json()
|
|
214
|
+
} catch {
|
|
215
|
+
return jsonResponse(400, { ok: false, reason: 'invalid-json' })
|
|
216
|
+
}
|
|
217
|
+
const changes = body !== null && typeof body === 'object' ? body.changes : undefined
|
|
218
|
+
const base = body !== null && typeof body === 'object' ? body.base : undefined
|
|
219
|
+
const result = store.applyChanges(changes, base)
|
|
220
|
+
if (result.ok === false) {
|
|
221
|
+
log('warn', `[localstate-sync] rejected a browser batch: ${result.reason}`)
|
|
222
|
+
return jsonResponse(typeof result.status === 'number' ? result.status : 400, result)
|
|
223
|
+
}
|
|
224
|
+
return jsonResponse(200, result)
|
|
225
|
+
}
|
|
226
|
+
return new Response('method not allowed', { status: 405 })
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
ctx.inject(['webServer', 'connection'], (web) => {
|
|
230
|
+
web.effect(
|
|
231
|
+
() => web.connection.fetch.register({ path: ROUTE_PATH, methods: ['GET', 'POST'], requestBody: 'buffered', fetch: handle }),
|
|
232
|
+
'localstate-sync: exact Fetch route',
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
web.on('webserver/index-inject', (table, peer) => {
|
|
236
|
+
if (cfg.injectSnapshot !== true) return
|
|
237
|
+
if (peer?.principal?.kind !== 'owner') return
|
|
238
|
+
const injection = store.injection(cfg.injectMaxBytes)
|
|
239
|
+
if (injection.truncated === true) {
|
|
240
|
+
log('info', `[localstate-sync] snapshot exceeds injectMaxBytes (${cfg.injectMaxBytes}); the page will pull it over the route instead`)
|
|
241
|
+
return
|
|
242
|
+
}
|
|
243
|
+
if (injection.keys.length === 0) return
|
|
244
|
+
table.push({
|
|
245
|
+
kind: 'global',
|
|
246
|
+
name: GLOBAL_NAME,
|
|
247
|
+
value: { ...injection, config: browserConfig(), prefixes: cfg.includePrefixes },
|
|
248
|
+
})
|
|
249
|
+
const text = readSeeder()
|
|
250
|
+
if (text !== '') table.push({ kind: 'script', placement: 'head', text })
|
|
251
|
+
})
|
|
252
|
+
|
|
253
|
+
web.effect(() => () => store.flush(), 'localstate-sync: flush on unload')
|
|
254
|
+
})
|
|
255
|
+
|
|
256
|
+
log('info', `[localstate-sync] ${store.filePath} (${store.size} keys)`)
|
|
257
|
+
}
|
package/locale/en.json
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"meta": {
|
|
3
|
+
"title": "Browser state sync",
|
|
4
|
+
"description": "Saves localStorage values this browser keeps for plugins into $DSH_HOME/localstate-sync/state.json and restores them before the page boots, so keybindings, panel layouts and other browser-only plugin settings survive a cache wipe or follow you to another address for the same Harness.",
|
|
5
|
+
"detail": "docs/en.md"
|
|
6
|
+
}
|
|
7
|
+
}
|
package/locale/zh.json
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"meta": {
|
|
3
|
+
"title": "浏览器状态同步",
|
|
4
|
+
"description": "把插件存在浏览器里的 localStorage 值保存到 $DSH_HOME/localstate-sync/state.json,并在页面启动前写回,因此快捷键、面板布局等只存在于浏览器的插件设置可以在清缓存后恢复,也能在同一个 Harness 的另一个访问地址上继续使用。默认只收集以 dsh. 开头的键,可用 includePrefixes、includeExact、excludeExact 调整。",
|
|
5
|
+
"detail": "README.md"
|
|
6
|
+
}
|
|
7
|
+
}
|
package/market/README.md
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
# 插件市场索引
|
|
2
|
+
|
|
3
|
+
`index.json` 是 DSH 插件市场索引 **format 1** 的一份文档,用官方校验器
|
|
4
|
+
(`@deepseek-ai/dsh-plugin-market-index` 的 `parseMarketIndex`)验过。
|
|
5
|
+
|
|
6
|
+
它把本插件登记成一条 **git 源**条目,安装参数就是这个仓库的一个固定提交:
|
|
7
|
+
|
|
8
|
+
```
|
|
9
|
+
git+https://github.com/Lxeon/dsh-localstate-sync.git#<commit>
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
固定提交是格式要求(`source.commit` 必须是 40 位小写 hex),所以**每次发版都要重建索引并推送**。
|
|
13
|
+
|
|
14
|
+
## 重建
|
|
15
|
+
|
|
16
|
+
```sh
|
|
17
|
+
node market/build-index.mjs # 或 npm run market
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
脚本从 `package.json` 取名字、版本、`engines.dsh`、`repository.url`,从 git 取 `HEAD`
|
|
21
|
+
与提交时间,从 `icon.svg` 生成内联 base64 图标(608 字节,远低于 32 KiB 上限),然后覆盖
|
|
22
|
+
写 `index.json`。仓库地址只认 `package.json` 的 `repository.url`(可用 `LSYNC_REPO_URL`
|
|
23
|
+
覆盖),**不读本机 git remote** —— 本地 checkout 可能指向别的、不该出现在索引里的地址。
|
|
24
|
+
|
|
25
|
+
顺序上有个先有鸡还是先有蛋:`index.json` 要写的提交是它自己所在的那次提交。做法是
|
|
26
|
+
|
|
27
|
+
1. 提交插件代码(记下提交号);
|
|
28
|
+
2. `node market/build-index.mjs`(此时钉在上一步的提交);
|
|
29
|
+
3. 单独提交 `market/index.json`。
|
|
30
|
+
|
|
31
|
+
于是索引钉的提交永远比仓库 `HEAD` 早一个提交——这没关系,那个提交里的代码是可安装的完整包。
|
|
32
|
+
|
|
33
|
+
## 托管
|
|
34
|
+
|
|
35
|
+
市场索引由 **DSH Host 进程**用 `fetch` 直接读,**不带任何凭据**,也不跟随跳转。
|
|
36
|
+
所以索引 URL 必须能被 Host 匿名取到,安装(pnpm 的 git 拉取)同理:
|
|
37
|
+
|
|
38
|
+
| 托管 | 索引直链 |
|
|
39
|
+
|---|---|
|
|
40
|
+
| GitHub 公开仓库 | `https://raw.githubusercontent.com/Lxeon/dsh-localstate-sync/main/market/index.json` |
|
|
41
|
+
| GitHub Pages / 任意静态站 | 指向 `market/index.json` 的 https 直链 |
|
|
42
|
+
|
|
43
|
+
仓库若是 private,`raw.githubusercontent.com` 会返回 404,Discover 报
|
|
44
|
+
`plugin-market/fetch-failed`,安装也会失败——索引和安装两头都断。
|
|
45
|
+
|
|
46
|
+
## 挂到本地 DSH
|
|
47
|
+
|
|
48
|
+
**Plugins → Discover → Add index source**,填上面的 URL。索引源存在 profile 的
|
|
49
|
+
`plugin-market` 行配置里(`indexes` 字段,volatile,切换不需要重启服务),
|
|
50
|
+
`plugin_market` 工具随后就能列出它。
|
|
51
|
+
|
|
52
|
+
索引里给了 `engines.dsh = ^0.2.2-rc.5`,与之不匹配的 Host 会判为不兼容并拒绝安装。
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Regenerate market/index.json from package.json, the npm registry, and icon.svg.
|
|
3
|
+
//
|
|
4
|
+
// A version is described by one exact source: the npm release when that version is on the
|
|
5
|
+
// registry, otherwise a pinned git commit (the market format does not accept a floating
|
|
6
|
+
// branch). Rebuild and push the index every time the plugin is released.
|
|
7
|
+
// Run: npm run market
|
|
8
|
+
//
|
|
9
|
+
// Value constraints come from @deepseek-ai/dsh-plugin-market-index: an exact SemVer
|
|
10
|
+
// version, an integer publishTimestamp in Unix seconds, a lowercase 40-hex commit, and
|
|
11
|
+
// an icon that is either an inline base64 data URL or a URL on https / the index origin.
|
|
12
|
+
import { execFileSync } from 'node:child_process'
|
|
13
|
+
import { readFileSync, writeFileSync } from 'node:fs'
|
|
14
|
+
import { dirname, join } from 'node:path'
|
|
15
|
+
import { fileURLToPath } from 'node:url'
|
|
16
|
+
|
|
17
|
+
const root = dirname(dirname(fileURLToPath(import.meta.url)))
|
|
18
|
+
const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'))
|
|
19
|
+
const git = (...args) => execFileSync('git', args, { cwd: root, encoding: 'utf8' }).trim()
|
|
20
|
+
|
|
21
|
+
if (pkg.dsh?.bundle === undefined) throw new Error('package.json must declare dsh.bundle, or the entry is not installable')
|
|
22
|
+
|
|
23
|
+
const commit = git('rev-parse', 'HEAD')
|
|
24
|
+
const gitTimestamp = Number(git('log', '-1', '--format=%ct'))
|
|
25
|
+
// The index is read by other machines, so the URL comes from package.json (the public
|
|
26
|
+
// repository), never from this checkout's git remote, which may point somewhere private.
|
|
27
|
+
const remote = String(process.env.LSYNC_REPO_URL ?? pkg.repository?.url ?? '').replace(/\.git$/, '')
|
|
28
|
+
if (remote === '') throw new Error('package.json must declare repository.url, or set LSYNC_REPO_URL to the public repository')
|
|
29
|
+
const icon = `data:image/svg+xml;base64,${readFileSync(join(root, 'icon.svg')).toString('base64')}`
|
|
30
|
+
|
|
31
|
+
// Prefer the npm release: it is what the registry-based markets ingest, and it needs no
|
|
32
|
+
// commit pin. Fall back to a pinned commit when this version is not published yet.
|
|
33
|
+
async function npmRelease(name, version) {
|
|
34
|
+
const url = `https://registry.npmjs.org/${name.replace('/', '%2f')}`
|
|
35
|
+
try {
|
|
36
|
+
const response = await fetch(url, { headers: { accept: 'application/json' } })
|
|
37
|
+
if (!response.ok) return undefined
|
|
38
|
+
const doc = await response.json()
|
|
39
|
+
const published = doc.time?.[version]
|
|
40
|
+
if (typeof published !== 'string') return undefined
|
|
41
|
+
const seconds = Math.floor(Date.parse(published) / 1000)
|
|
42
|
+
if (!Number.isInteger(seconds) || seconds <= 0) return undefined
|
|
43
|
+
return { publishTimestamp: seconds, source: { type: 'npm' } }
|
|
44
|
+
} catch {
|
|
45
|
+
return undefined
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const release = (await npmRelease(pkg.name, pkg.version)) ?? {
|
|
50
|
+
publishTimestamp: gitTimestamp,
|
|
51
|
+
source: { type: 'git', url: `${remote}.git`, commit },
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const index = {
|
|
55
|
+
format: 1,
|
|
56
|
+
title: { en: "Lxeon's DSH plugins", zh: 'Lxeon 的 DSH 插件' },
|
|
57
|
+
description: {
|
|
58
|
+
en: 'DSH plugins published from this repository, installable by pinned commit.',
|
|
59
|
+
zh: '从本仓库发布的 DSH 插件,按固定提交安装。',
|
|
60
|
+
},
|
|
61
|
+
metadata: {
|
|
62
|
+
categories: { ui: { title: { en: 'Interface', zh: '界面' } } },
|
|
63
|
+
labels: {},
|
|
64
|
+
sortKeys: {},
|
|
65
|
+
},
|
|
66
|
+
plugins: [
|
|
67
|
+
{
|
|
68
|
+
name: pkg.name,
|
|
69
|
+
title: { en: 'Browser state sync', zh: '浏览器状态同步' },
|
|
70
|
+
description: {
|
|
71
|
+
en: 'Saves the localStorage values DSH plugins keep in this browser into $DSH_HOME, and restores them before the next boot.',
|
|
72
|
+
zh: '把 DSH 插件留在这个浏览器里的 localStorage 值保存到 $DSH_HOME,并在下次启动前灌回去。',
|
|
73
|
+
},
|
|
74
|
+
icon,
|
|
75
|
+
author: pkg.author ?? 'Lxeon',
|
|
76
|
+
homepage: remote,
|
|
77
|
+
repository: { url: remote },
|
|
78
|
+
metadata: {
|
|
79
|
+
category: 'ui',
|
|
80
|
+
keywords: ['localstorage', 'sync', 'browser-state', 'config'],
|
|
81
|
+
labels: [],
|
|
82
|
+
},
|
|
83
|
+
versions: [
|
|
84
|
+
{
|
|
85
|
+
version: pkg.version,
|
|
86
|
+
publishTimestamp: release.publishTimestamp,
|
|
87
|
+
source: release.source,
|
|
88
|
+
engines: pkg.engines?.dsh === undefined ? {} : { dsh: pkg.engines.dsh },
|
|
89
|
+
},
|
|
90
|
+
],
|
|
91
|
+
},
|
|
92
|
+
],
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const out = join(root, 'market', 'index.json')
|
|
96
|
+
writeFileSync(out, `${JSON.stringify(index, null, 2)}\n`)
|
|
97
|
+
console.log(`wrote ${out}`)
|
|
98
|
+
const where = release.source.type === 'npm' ? 'npm registry' : `git ${commit.slice(0, 8)}`
|
|
99
|
+
console.log(` ${pkg.name}@${pkg.version} -> ${where} (${new Date(release.publishTimestamp * 1000).toISOString()})`)
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
{
|
|
2
|
+
"format": 1,
|
|
3
|
+
"title": {
|
|
4
|
+
"en": "Lxeon's DSH plugins",
|
|
5
|
+
"zh": "Lxeon 的 DSH 插件"
|
|
6
|
+
},
|
|
7
|
+
"description": {
|
|
8
|
+
"en": "DSH plugins published from this repository, installable by pinned commit.",
|
|
9
|
+
"zh": "从本仓库发布的 DSH 插件,按固定提交安装。"
|
|
10
|
+
},
|
|
11
|
+
"metadata": {
|
|
12
|
+
"categories": {
|
|
13
|
+
"ui": {
|
|
14
|
+
"title": {
|
|
15
|
+
"en": "Interface",
|
|
16
|
+
"zh": "界面"
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
},
|
|
20
|
+
"labels": {},
|
|
21
|
+
"sortKeys": {}
|
|
22
|
+
},
|
|
23
|
+
"plugins": [
|
|
24
|
+
{
|
|
25
|
+
"name": "@leonhoy/dsh-localstate-sync",
|
|
26
|
+
"title": {
|
|
27
|
+
"en": "Browser state sync",
|
|
28
|
+
"zh": "浏览器状态同步"
|
|
29
|
+
},
|
|
30
|
+
"description": {
|
|
31
|
+
"en": "Saves the localStorage values DSH plugins keep in this browser into $DSH_HOME, and restores them before the next boot.",
|
|
32
|
+
"zh": "把 DSH 插件留在这个浏览器里的 localStorage 值保存到 $DSH_HOME,并在下次启动前灌回去。"
|
|
33
|
+
},
|
|
34
|
+
"icon": "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIzNiIgaGVpZ2h0PSIzNiIgdmlld0JveD0iMCAwIDM2IDM2Ij4KICA8cmVjdCB4PSIzIiB5PSI4IiB3aWR0aD0iMTgiIGhlaWdodD0iMTUiIHJ4PSIzIiBmaWxsPSJub25lIiBzdHJva2U9IiMxZjhhNzAiIHN0cm9rZS13aWR0aD0iMiIvPgogIDxwYXRoIGQ9Ik0zIDEzaDE4IiBmaWxsPSJub25lIiBzdHJva2U9IiMxZjhhNzAiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIi8+CiAgPGNpcmNsZSBjeD0iNi41IiBjeT0iMTAuNSIgcj0iMSIgZmlsbD0iIzFmOGE3MCIvPgogIDxjaXJjbGUgY3g9IjEwIiBjeT0iMTAuNSIgcj0iMSIgZmlsbD0iIzFmOGE3MCIvPgogIDxwYXRoIGQ9Ik0yNiA5djE3IiBmaWxsPSJub25lIiBzdHJva2U9IiMxZjhhNzAiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIi8+CiAgPHBhdGggZD0iTTIxLjUgMjEuNSAyNiAyNmw0LjUtNC41IiBmaWxsPSJub25lIiBzdHJva2U9IiMxZjhhNzAiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIi8+Cjwvc3ZnPgo=",
|
|
35
|
+
"author": "Lxeon",
|
|
36
|
+
"homepage": "git+https://github.com/Lxeon/dsh-localstate-sync",
|
|
37
|
+
"repository": {
|
|
38
|
+
"url": "git+https://github.com/Lxeon/dsh-localstate-sync"
|
|
39
|
+
},
|
|
40
|
+
"metadata": {
|
|
41
|
+
"category": "ui",
|
|
42
|
+
"keywords": [
|
|
43
|
+
"localstorage",
|
|
44
|
+
"sync",
|
|
45
|
+
"browser-state",
|
|
46
|
+
"config"
|
|
47
|
+
],
|
|
48
|
+
"labels": []
|
|
49
|
+
},
|
|
50
|
+
"versions": [
|
|
51
|
+
{
|
|
52
|
+
"version": "0.2.0",
|
|
53
|
+
"publishTimestamp": 1795705154,
|
|
54
|
+
"source": {
|
|
55
|
+
"type": "git",
|
|
56
|
+
"url": "git+https://github.com/Lxeon/dsh-localstate-sync.git",
|
|
57
|
+
"commit": "7108f6e3fbd7b9aab11ec56f936293d715a7616c"
|
|
58
|
+
},
|
|
59
|
+
"engines": {
|
|
60
|
+
"dsh": "^0.2.2-rc.5"
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
]
|
|
64
|
+
}
|
|
65
|
+
]
|
|
66
|
+
}
|