@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/package.json CHANGED
@@ -1,6 +1,68 @@
1
1
  {
2
2
  "name": "@leonhoy/dsh-localstate-sync",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "type": "module",
5
+ "description": "Persist browser localStorage state into a JSON file under the DSH home and restore it before the page boots.",
6
+ "dependencies": {
7
+ "schemastery": "^3.18.0"
8
+ },
9
+ "exports": {
10
+ ".": "./index.js",
11
+ "./client": "./client.js",
12
+ "./seeder.js": "./seeder.js",
13
+ "./locale/*.json": "./locale/*.json",
14
+ "./icon": "./icon.svg"
15
+ },
16
+ "engines": {
17
+ "dsh": "^0.2.2-rc.5"
18
+ },
19
+ "files": [
20
+ "index.js",
21
+ "client.js",
22
+ "seeder.js",
23
+ "store.js",
24
+ "cordis.patch.yml",
25
+ "locale/*.json",
26
+ "docs",
27
+ "icon.svg",
28
+ "README.md",
29
+ "LICENSE",
30
+ "test",
31
+ "market"
32
+ ],
33
+ "dsh": {
34
+ "bundle": {
35
+ "patch": "./cordis.patch.yml"
36
+ },
37
+ "client": {
38
+ "platform": "web",
39
+ "immediately": true,
40
+ "inject": [
41
+ "@deepseek-ai/dsh-client-connection"
42
+ ]
43
+ }
44
+ },
45
+ "repository": {
46
+ "type": "git",
47
+ "url": "git+https://github.com/Lxeon/dsh-localstate-sync.git"
48
+ },
49
+ "homepage": "https://github.com/Lxeon/dsh-localstate-sync",
50
+ "author": "Lxeon",
51
+ "scripts": {
52
+ "verify": "node test/verify.mjs",
53
+ "market": "node market/build-index.mjs"
54
+ },
55
+ "publishConfig": {
56
+ "access": "public"
57
+ },
58
+ "license": "MIT",
59
+ "keywords": [
60
+ "dsh",
61
+ "dsh-plugin",
62
+ "deepseek-harness",
63
+ "localstorage",
64
+ "sync",
65
+ "browser-state",
66
+ "config"
67
+ ]
68
+ }
package/seeder.js ADDED
@@ -0,0 +1,45 @@
1
+ /* Injected into <head> before the application boots. Restores snapshot keys
2
+ whose revision is newer than the one this browser already applied, so a
3
+ value written in another tab or another origin is not overwritten by a stale
4
+ page. Deliberately dependency-free and failure-tolerant. */
5
+ ;(function () {
6
+ var data = globalThis.__DSH_LOCALSTATE__
7
+ if (!data || data.v !== 1 || !Array.isArray(data.keys)) return
8
+ var META_KEY = '__dsh.localstate.meta.v1'
9
+ var meta
10
+ try {
11
+ meta = JSON.parse(localStorage.getItem(META_KEY) || 'null')
12
+ } catch (error) {
13
+ meta = null
14
+ }
15
+ if (!meta || typeof meta !== 'object' || !meta.at || typeof meta.at !== 'object') meta = { at: {} }
16
+ var applied = 0
17
+ for (var index = 0; index < data.keys.length; index += 1) {
18
+ var row = data.keys[index]
19
+ if (!Array.isArray(row) || row.length < 3) continue
20
+ var key = row[0]
21
+ var value = row[1]
22
+ var revision = row[2]
23
+ if (typeof key !== 'string' || typeof revision !== 'number') continue
24
+ var known = typeof meta.at[key] === 'number' ? meta.at[key] : 0
25
+ if (revision <= known) continue
26
+ try {
27
+ if (value === null) localStorage.removeItem(key)
28
+ else if (typeof value === 'string') localStorage.setItem(key, value)
29
+ else continue
30
+ meta.at[key] = revision
31
+ applied += 1
32
+ } catch (error) {
33
+ // Quota or a storage-denied frame leaves the key for the next boot.
34
+ }
35
+ }
36
+ if (typeof data.seq === 'number' && data.seq > (typeof meta.seq === 'number' ? meta.seq : 0)) meta.seq = data.seq
37
+ if (applied > 0 || data.seq !== undefined) {
38
+ try {
39
+ localStorage.setItem(META_KEY, JSON.stringify(meta))
40
+ } catch (error) {
41
+ // Metadata is an optimisation; a failed write only costs a redundant restore.
42
+ }
43
+ }
44
+ globalThis.__DSH_LOCALSTATE_APPLIED__ = applied
45
+ })()
package/store.js ADDED
@@ -0,0 +1,330 @@
1
+ /**
2
+ * Durable store for browser localStorage snapshots.
3
+ *
4
+ * The document lives in one JSON file under `$DSH_HOME`. Every accepted change
5
+ * takes the next monotonic `at` value, which the browser compares against its
6
+ * own per-key bookkeeping before writing a restored value. Writes are
7
+ * write-behind: a short timer coalesces a burst of browser flushes into one
8
+ * atomic rename.
9
+ */
10
+ import {
11
+ chmodSync,
12
+ existsSync,
13
+ mkdirSync,
14
+ readFileSync,
15
+ renameSync,
16
+ writeFileSync,
17
+ } from 'node:fs'
18
+ import { homedir } from 'node:os'
19
+ import { dirname, isAbsolute, join } from 'node:path'
20
+
21
+ /** Document schema version written into the JSON file. */
22
+ export const DOC_VERSION = 1
23
+
24
+ /** Resolved DSH home: an explicit `$DSH_HOME` wins over `~/.dsh`. */
25
+ export function dshHome() {
26
+ const configured = process.env.DSH_HOME
27
+ if (typeof configured === 'string' && configured.trim() !== '') return configured.trim()
28
+ return join(homedir(), '.dsh')
29
+ }
30
+
31
+ /** Configuration defaults; every field is optional in the patch row. */
32
+ export const DEFAULT_CONFIG = {
33
+ enabled: true,
34
+ file: 'localstate-sync/state.json',
35
+ includePrefixes: ['dsh.'],
36
+ includeExact: [],
37
+ excludeExact: [],
38
+ maxBytes: 262144,
39
+ maxKeys: 2000,
40
+ injectMaxBytes: 131072,
41
+ injectSnapshot: true,
42
+ capture: true,
43
+ language: 'auto',
44
+ }
45
+
46
+ /** Languages the browser-facing text can be rendered in. */
47
+ export const LANGUAGES = ['auto', 'en', 'zh']
48
+
49
+ function stringList(value, fallback) {
50
+ if (value === undefined || value === null) return [...fallback]
51
+ const items = typeof value === 'string' ? [value] : Array.isArray(value) ? value : undefined
52
+ if (items === undefined) return [...fallback]
53
+ const kept = []
54
+ for (const item of items) {
55
+ if (typeof item !== 'string') continue
56
+ const trimmed = item.trim()
57
+ if (trimmed === '') continue
58
+ kept.push(trimmed)
59
+ }
60
+ return kept
61
+ }
62
+
63
+ function positiveInt(value, fallback, min = 1) {
64
+ if (typeof value !== 'number' || !Number.isFinite(value)) return fallback
65
+ const rounded = Math.floor(value)
66
+ return rounded >= min ? rounded : fallback
67
+ }
68
+
69
+ /**
70
+ * Apply defaults and drop values the store cannot use.
71
+ * @param raw - the patch row's `config` object, possibly undefined.
72
+ * @returns a complete configuration.
73
+ */
74
+ export function normalizeConfig(raw) {
75
+ const input = raw !== null && typeof raw === 'object' && !Array.isArray(raw) ? raw : {}
76
+ const config = { ...DEFAULT_CONFIG }
77
+ if (typeof input.enabled === 'boolean') config.enabled = input.enabled
78
+ if (typeof input.injectSnapshot === 'boolean') config.injectSnapshot = input.injectSnapshot
79
+ if (typeof input.capture === 'boolean') config.capture = input.capture
80
+ if (typeof input.language === 'string' && LANGUAGES.includes(input.language.trim())) {
81
+ config.language = input.language.trim()
82
+ }
83
+ if (typeof input.file === 'string' && input.file.trim() !== '') config.file = input.file.trim()
84
+ config.includePrefixes = stringList(input.includePrefixes, DEFAULT_CONFIG.includePrefixes)
85
+ config.includeExact = stringList(input.includeExact, [])
86
+ config.excludeExact = stringList(input.excludeExact, [])
87
+ config.maxBytes = positiveInt(input.maxBytes, DEFAULT_CONFIG.maxBytes)
88
+ config.maxKeys = positiveInt(input.maxKeys, DEFAULT_CONFIG.maxKeys)
89
+ config.injectMaxBytes = positiveInt(input.injectMaxBytes, DEFAULT_CONFIG.injectMaxBytes)
90
+ return config
91
+ }
92
+
93
+ /** Absolute path of the store file for one configuration. */
94
+ export function resolveStorePath(config) {
95
+ return isAbsolute(config.file) ? config.file : join(dshHome(), config.file)
96
+ }
97
+
98
+ function emptyDoc() {
99
+ return { version: DOC_VERSION, seq: 0, updatedAt: null, keys: {} }
100
+ }
101
+
102
+ function isRecord(value) {
103
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
104
+ }
105
+
106
+ function loadDoc(filePath) {
107
+ if (!existsSync(filePath)) return { doc: emptyDoc(), recovered: undefined }
108
+ let text
109
+ try {
110
+ text = readFileSync(filePath, 'utf8')
111
+ } catch {
112
+ return { doc: emptyDoc(), recovered: undefined }
113
+ }
114
+ try {
115
+ const parsed = JSON.parse(text)
116
+ if (!isRecord(parsed) || !isRecord(parsed.keys)) throw new Error('state document has no keys map')
117
+ const keys = {}
118
+ for (const [key, row] of Object.entries(parsed.keys)) {
119
+ if (typeof key !== 'string' || !isRecord(row)) continue
120
+ const at = typeof row.at === 'number' && Number.isFinite(row.at) ? row.at : 0
121
+ const t = typeof row.t === 'number' && Number.isFinite(row.t) ? row.t : at
122
+ if (row.del === true) keys[key] = { del: true, at, t }
123
+ else if (typeof row.v === 'string') keys[key] = { v: row.v, at, t }
124
+ }
125
+ const seq = typeof parsed.seq === 'number' && Number.isFinite(parsed.seq) ? parsed.seq : 0
126
+ const updatedAt = typeof parsed.updatedAt === 'string' ? parsed.updatedAt : null
127
+ return { doc: { version: DOC_VERSION, seq, updatedAt, keys }, recovered: undefined }
128
+ } catch (error) {
129
+ const aside = `${filePath}.corrupt-${Date.now()}`
130
+ try {
131
+ renameSync(filePath, aside)
132
+ } catch {
133
+ // Keep serving an empty document even when the bad file cannot be moved aside.
134
+ }
135
+ return { doc: emptyDoc(), recovered: { aside, message: String(error) } }
136
+ }
137
+ }
138
+
139
+ /**
140
+ * Create the store for one resolved configuration.
141
+ * @param config - normalized configuration.
142
+ * @returns the store handle plus load diagnostics.
143
+ */
144
+ export function createStore(config) {
145
+ const filePath = resolveStorePath(config)
146
+ const { doc: initialDoc, recovered } = loadDoc(filePath)
147
+ let doc = initialDoc
148
+ let timer
149
+ let dirty = false
150
+ let lastWriteAt = null
151
+ let lastWriteError = null
152
+
153
+ const allows = (key) => {
154
+ if (typeof key !== 'string' || key === '' || key.length > 512) return false
155
+ if (config.excludeExact.includes(key)) return false
156
+ if (config.includeExact.includes(key)) return true
157
+ return config.includePrefixes.some((prefix) => key.startsWith(prefix))
158
+ }
159
+
160
+ const writeNow = () => {
161
+ if (!dirty) return
162
+ dirty = false
163
+ try {
164
+ mkdirSync(dirname(filePath), { recursive: true, mode: 0o700 })
165
+ const body = `${JSON.stringify(doc, null, 2)}\n`
166
+ const tmp = `${filePath}.${process.pid}.tmp`
167
+ writeFileSync(tmp, body, { mode: 0o600 })
168
+ renameSync(tmp, filePath)
169
+ try {
170
+ chmodSync(filePath, 0o600)
171
+ } catch {
172
+ // A missing chmod on some filesystems is not a reason to fail the write.
173
+ }
174
+ lastWriteAt = new Date().toISOString()
175
+ lastWriteError = null
176
+ } catch (error) {
177
+ dirty = true
178
+ lastWriteError = String(error)
179
+ }
180
+ }
181
+
182
+ const scheduleWrite = () => {
183
+ dirty = true
184
+ if (timer !== undefined) return
185
+ timer = setTimeout(() => {
186
+ timer = undefined
187
+ writeNow()
188
+ }, 120)
189
+ if (typeof timer.unref === 'function') timer.unref()
190
+ }
191
+
192
+ /** Drop the oldest keys once the key cap is exceeded; tombstones go first. */
193
+ const prune = (keys) => {
194
+ const entries = Object.entries(keys)
195
+ if (entries.length <= config.maxKeys) return keys
196
+ const ranked = entries.sort((left, right) => {
197
+ const leftDel = left[1].del === true ? 0 : 1
198
+ const rightDel = right[1].del === true ? 0 : 1
199
+ if (leftDel !== rightDel) return leftDel - rightDel
200
+ return (left[1].t ?? 0) - (right[1].t ?? 0)
201
+ })
202
+ const keep = new Set(ranked.slice(entries.length - config.maxKeys).map(([key]) => key))
203
+ const next = {}
204
+ for (const [key, row] of entries) {
205
+ if (keep.has(key)) next[key] = row
206
+ }
207
+ return next
208
+ }
209
+
210
+ return {
211
+ filePath,
212
+ recovered,
213
+ allows,
214
+ get seq() {
215
+ return doc.seq
216
+ },
217
+ get size() {
218
+ return Object.keys(doc.keys).length
219
+ },
220
+ diagnostics() {
221
+ return {
222
+ file: filePath,
223
+ seq: doc.seq,
224
+ keys: Object.keys(doc.keys).length,
225
+ updatedAt: doc.updatedAt,
226
+ recovered,
227
+ lastWriteAt,
228
+ lastWriteError,
229
+ pendingWrite: dirty,
230
+ }
231
+ },
232
+ /** Complete key map for the GET route. */
233
+ snapshot() {
234
+ const keys = {}
235
+ for (const [key, row] of Object.entries(doc.keys)) {
236
+ if (!allows(key)) continue
237
+ keys[key] = row.del === true ? { del: true, at: row.at, t: row.t } : { v: row.v, at: row.at, t: row.t }
238
+ }
239
+ return { version: DOC_VERSION, seq: doc.seq, updatedAt: doc.updatedAt, keys }
240
+ },
241
+ /**
242
+ * Render the boot-injection payload: `[key, valueOrNull, at]` triples in
243
+ * ascending revision order, so a seeder applies them in one pass.
244
+ */
245
+ injection(limit) {
246
+ const keys = []
247
+ let truncated = false
248
+ const ranked = Object.entries(doc.keys)
249
+ .filter(([key]) => allows(key))
250
+ .sort((left, right) => (left[1].at ?? 0) - (right[1].at ?? 0))
251
+ for (const [key, row] of ranked) {
252
+ const triple = [key, row.del === true ? null : row.v, row.at]
253
+ keys.push(triple)
254
+ if (limit !== undefined && JSON.stringify({ v: DOC_VERSION, seq: doc.seq, keys }).length > limit) {
255
+ keys.pop()
256
+ truncated = true
257
+ break
258
+ }
259
+ }
260
+ return { v: DOC_VERSION, seq: doc.seq, keys, truncated }
261
+ },
262
+ /**
263
+ * Merge one browser batch. Keys outside the allowlist are ignored.
264
+ * @param changes - `{ key: string | null }`; null records a deletion.
265
+ * @param base - optional `{ key: number }` of the revisions the browser
266
+ * built its values on. A key whose revision moved on since then is not
267
+ * applied; it comes back as a conflict instead of overwriting silently.
268
+ * @returns the wire result for the POST route.
269
+ */
270
+ applyChanges(changes, base) {
271
+ if (!isRecord(changes)) return { ok: false, status: 400, reason: 'invalid-changes' }
272
+ const guard = isRecord(base) ? base : undefined
273
+ const accepted = []
274
+ const ignored = []
275
+ const conflicts = []
276
+ const next = { ...doc, keys: { ...doc.keys } }
277
+ let seq = doc.seq
278
+ const now = Date.now()
279
+ for (const [key, value] of Object.entries(changes)) {
280
+ if (!allows(key)) {
281
+ ignored.push(key)
282
+ continue
283
+ }
284
+ if (value !== null && typeof value !== 'string') {
285
+ return { ok: false, status: 400, reason: 'invalid-value', key }
286
+ }
287
+ if (typeof value === 'string' && value.length > config.maxBytes) {
288
+ return { ok: false, status: 413, reason: 'value-too-large', key, bytes: value.length }
289
+ }
290
+ const existing = next.keys[key]
291
+ const current = existing === undefined ? 0 : existing.at
292
+ const expected = guard !== undefined && Object.hasOwn(guard, key) ? guard[key] : undefined
293
+ if (typeof expected === 'number' && expected !== current) {
294
+ conflicts.push({
295
+ key,
296
+ expected,
297
+ current,
298
+ at: current,
299
+ value: existing === undefined || existing.del === true ? null : existing.v,
300
+ })
301
+ continue
302
+ }
303
+ seq += 1
304
+ next.keys[key] = value === null ? { del: true, at: seq, t: now } : { v: value, at: seq, t: now }
305
+ accepted.push([key, seq])
306
+ }
307
+ if (accepted.length === 0) {
308
+ return { ok: true, seq: doc.seq, accepted: [], ignored, conflicts }
309
+ }
310
+ next.keys = prune(next.keys)
311
+ next.seq = seq
312
+ next.updatedAt = new Date(now).toISOString()
313
+ const bytes = JSON.stringify(next).length
314
+ if (bytes > config.maxBytes) {
315
+ return { ok: false, status: 413, reason: 'snapshot-too-large', bytes, maxBytes: config.maxBytes }
316
+ }
317
+ doc = next
318
+ scheduleWrite()
319
+ return { ok: true, seq, accepted, ignored, conflicts }
320
+ },
321
+ /** Coalesced write, synchronous flush for shutdown. */
322
+ flush() {
323
+ if (timer !== undefined) {
324
+ clearTimeout(timer)
325
+ timer = undefined
326
+ }
327
+ writeNow()
328
+ },
329
+ }
330
+ }