@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/test/verify.mjs
ADDED
|
@@ -0,0 +1,435 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Offline verification for @leonhoy/dsh-localstate-sync.
|
|
3
|
+
*
|
|
4
|
+
* Run from the package root: node test/verify.mjs
|
|
5
|
+
*
|
|
6
|
+
* Exercises the Host half with a fake Cordis context (route registration, index
|
|
7
|
+
* injection, store merge, tombstones, allowlist) and the injected seeder against
|
|
8
|
+
* a fake localStorage. No browser and no live profile required.
|
|
9
|
+
*/
|
|
10
|
+
import { mkdtempSync, readFileSync, rmSync } from 'node:fs'
|
|
11
|
+
import { createContext, runInContext } from 'node:vm'
|
|
12
|
+
import { tmpdir } from 'node:os'
|
|
13
|
+
import { join } from 'node:path'
|
|
14
|
+
import { createStore, normalizeConfig, resolveStorePath } from '../store.js'
|
|
15
|
+
|
|
16
|
+
const home = mkdtempSync(join(tmpdir(), 'localstate-sync-'))
|
|
17
|
+
process.env.DSH_HOME = home
|
|
18
|
+
|
|
19
|
+
const checks = []
|
|
20
|
+
function check(label, condition, extra) {
|
|
21
|
+
checks.push({ label, ok: Boolean(condition), extra })
|
|
22
|
+
if (!condition) console.error(`FAIL ${label}`, extra ?? '')
|
|
23
|
+
else console.log(`ok ${label}`)
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// ---------------------------------------------------------------- fake Cordis
|
|
27
|
+
function fakeContext() {
|
|
28
|
+
const captured = { route: undefined, routes: [], listeners: [], effects: [], edits: [] }
|
|
29
|
+
const logger = { info() {}, warn() {}, error() {}, debug() {} }
|
|
30
|
+
const web = {
|
|
31
|
+
effect(fn) {
|
|
32
|
+
const dispose = fn()
|
|
33
|
+
captured.effects.push(dispose)
|
|
34
|
+
return dispose
|
|
35
|
+
},
|
|
36
|
+
on(event, listener) {
|
|
37
|
+
captured.listeners.push([event, listener])
|
|
38
|
+
return () => {}
|
|
39
|
+
},
|
|
40
|
+
connection: {
|
|
41
|
+
fetch: {
|
|
42
|
+
register(route) {
|
|
43
|
+
captured.routes.push(route)
|
|
44
|
+
return async () => {}
|
|
45
|
+
},
|
|
46
|
+
},
|
|
47
|
+
},
|
|
48
|
+
}
|
|
49
|
+
const configEditor = {
|
|
50
|
+
async edit(entry, change) {
|
|
51
|
+
const next = change({ ...entry.options.config })
|
|
52
|
+
captured.edits.push({ id: entry.id, config: next })
|
|
53
|
+
return undefined
|
|
54
|
+
},
|
|
55
|
+
}
|
|
56
|
+
const ctx = {
|
|
57
|
+
logger,
|
|
58
|
+
fiber: {
|
|
59
|
+
entry: {
|
|
60
|
+
id: 'localstate-sync',
|
|
61
|
+
name: '@leonhoy/dsh-localstate-sync',
|
|
62
|
+
options: { config: { includePrefixes: ['dsh.'], maxBytes: 262144, maxKeys: 2000, injectSnapshot: true, capture: true } },
|
|
63
|
+
},
|
|
64
|
+
},
|
|
65
|
+
get(name) {
|
|
66
|
+
return name === 'configEditor' ? configEditor : undefined
|
|
67
|
+
},
|
|
68
|
+
inject(_services, callback) {
|
|
69
|
+
callback(web)
|
|
70
|
+
},
|
|
71
|
+
}
|
|
72
|
+
return { ctx, captured }
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// ---------------------------------------------------------------- store tests
|
|
76
|
+
const config = normalizeConfig({ includePrefixes: ['dsh.'], maxBytes: 262144, maxKeys: 2000 })
|
|
77
|
+
check('resolveStorePath honours DSH_HOME', resolveStorePath(config) === join(home, 'localstate-sync/state.json'), resolveStorePath(config))
|
|
78
|
+
|
|
79
|
+
const store = createStore(config)
|
|
80
|
+
const first = store.applyChanges({
|
|
81
|
+
'dsh.keybindings.v1': '{"submit":"Enter"}',
|
|
82
|
+
'CONVERSATION_STORE_KEY.abc': 'not-collected',
|
|
83
|
+
'dsh.sidebar-right.v1.s1': '{"tabs":2}',
|
|
84
|
+
})
|
|
85
|
+
check('batch accepted', first.ok === true && first.accepted.length === 2, first)
|
|
86
|
+
check('disallowed key ignored', Array.isArray(first.ignored) && first.ignored[0] === 'CONVERSATION_STORE_KEY.abc', first.ignored)
|
|
87
|
+
check('revisions are monotonic per key', first.accepted[0][1] === 1 && first.accepted[1][1] === 2, first.accepted)
|
|
88
|
+
|
|
89
|
+
const del = store.applyChanges({ 'dsh.sidebar-right.v1.s1': null })
|
|
90
|
+
check('deletion becomes a tombstone', del.ok === true && store.snapshot().keys['dsh.sidebar-right.v1.s1'].del === true, store.snapshot().keys)
|
|
91
|
+
|
|
92
|
+
const injection = store.injection(131072)
|
|
93
|
+
check('injection carries triples in revision order', injection.v === 1 && injection.keys.length === 2 && injection.keys[0][0] === 'dsh.keybindings.v1' && injection.keys[1][1] === null, injection.keys)
|
|
94
|
+
check('injection not truncated', injection.truncated === false, injection.truncated)
|
|
95
|
+
|
|
96
|
+
const tooLarge = store.applyChanges({ 'dsh.big': 'x'.repeat(300000) })
|
|
97
|
+
check('oversized value rejected', tooLarge.ok === false && tooLarge.status === 413, tooLarge.reason)
|
|
98
|
+
|
|
99
|
+
const badValue = store.applyChanges({ 'dsh.bad': { nested: true } })
|
|
100
|
+
check('non-string value rejected', badValue.ok === false && badValue.reason === 'invalid-value', badValue.reason)
|
|
101
|
+
|
|
102
|
+
const badBatch = store.applyChanges([])
|
|
103
|
+
check('non-object batch rejected', badBatch.ok === false && badBatch.reason === 'invalid-changes', badBatch.reason)
|
|
104
|
+
|
|
105
|
+
store.flush()
|
|
106
|
+
const onDisk = JSON.parse(readFileSync(join(home, 'localstate-sync/state.json'), 'utf8'))
|
|
107
|
+
check('snapshot is on disk with 0600 mode', onDisk.version === 1 && onDisk.keys['dsh.keybindings.v1'].v === '{"submit":"Enter"}', Object.keys(onDisk.keys))
|
|
108
|
+
const mode = (await import('node:fs')).statSync(join(home, 'localstate-sync/state.json')).mode & 0o777
|
|
109
|
+
check('file mode is 0600', mode === 0o600, mode.toString(8))
|
|
110
|
+
|
|
111
|
+
const reloaded = createStore(config)
|
|
112
|
+
check('store reloads what it wrote', reloaded.snapshot().keys['dsh.keybindings.v1'].v === '{"submit":"Enter"}' && reloaded.snapshot().seq === 3, reloaded.snapshot().seq)
|
|
113
|
+
|
|
114
|
+
// ---------------------------------------------------------------- write conflicts
|
|
115
|
+
const clashConfig = normalizeConfig({ includePrefixes: ['dsh.'], file: 'clash/state.json' })
|
|
116
|
+
const clash = createStore(clashConfig)
|
|
117
|
+
const base = clash.applyChanges({ 'dsh.shared': 'from-a' }, {})
|
|
118
|
+
check('first write with an empty base applies', base.ok === true && base.accepted.length === 1 && base.conflicts.length === 0, base)
|
|
119
|
+
const staleAt = clash.snapshot().keys['dsh.shared'].at
|
|
120
|
+
const stale = clash.applyChanges({ 'dsh.shared': 'from-b' }, { 'dsh.shared': staleAt - 1 })
|
|
121
|
+
check('a stale base is reported as a conflict, not applied', stale.ok === true && stale.accepted.length === 0 && stale.conflicts.length === 1, stale)
|
|
122
|
+
check('the conflict carries the copy on the host', stale.conflicts[0].value === 'from-a' && stale.conflicts[0].current === staleAt && stale.conflicts[0].expected === staleAt - 1, stale.conflicts[0])
|
|
123
|
+
check('the rejected write left the value alone', clash.snapshot().keys['dsh.shared'].v === 'from-a', clash.snapshot().keys['dsh.shared'])
|
|
124
|
+
const retried = clash.applyChanges({ 'dsh.shared': 'from-b' }, { 'dsh.shared': staleAt })
|
|
125
|
+
check('resending with the fresh base applies', retried.ok === true && retried.accepted.length === 1 && retried.conflicts.length === 0 && clash.snapshot().keys['dsh.shared'].v === 'from-b', retried)
|
|
126
|
+
const mixedAt = clash.snapshot().keys['dsh.shared'].at
|
|
127
|
+
const mixed = clash.applyChanges({ 'dsh.shared': 'from-b2', 'dsh.fresh': 'new' }, { 'dsh.shared': mixedAt - 1, 'dsh.fresh': 0 })
|
|
128
|
+
check('a mixed batch applies the clean key and reports the clash', mixed.accepted.length === 1 && mixed.accepted[0][0] === 'dsh.fresh' && mixed.conflicts[0].key === 'dsh.shared', mixed)
|
|
129
|
+
check('the clean key in a mixed batch landed', clash.snapshot().keys['dsh.fresh'].v === 'new', clash.snapshot().keys['dsh.fresh'])
|
|
130
|
+
const clashDel = clash.applyChanges({ 'dsh.gone2': 'v' }, {})
|
|
131
|
+
const goneAt = clash.snapshot().keys['dsh.gone2'].at
|
|
132
|
+
clash.applyChanges({ 'dsh.gone2': null }, { 'dsh.gone2': goneAt })
|
|
133
|
+
const onTombstone = clash.applyChanges({ 'dsh.gone2': 'resurrect' }, { 'dsh.gone2': goneAt })
|
|
134
|
+
check('a tombstone also conflicts on a stale base', onTombstone.accepted.length === 0 && onTombstone.conflicts[0].value === null && onTombstone.conflicts[0].current > goneAt, onTombstone.conflicts[0])
|
|
135
|
+
const legacy = clash.applyChanges({ 'dsh.legacy': 'no-base-sent' })
|
|
136
|
+
check('a batch without base still applies (old clients)', legacy.ok === true && legacy.accepted.length === 1 && legacy.conflicts.length === 0, legacy)
|
|
137
|
+
clash.flush()
|
|
138
|
+
|
|
139
|
+
// ---------------------------------------------------------------- host plugin
|
|
140
|
+
const { apply } = await import('../index.js')
|
|
141
|
+
const { ctx, captured } = fakeContext()
|
|
142
|
+
apply(ctx, { includePrefixes: ['dsh.'] })
|
|
143
|
+
captured.route = captured.routes.find((route) => route.path === '/api/localstate.v1')
|
|
144
|
+
check('route registered on /api prefix', captured.route?.path === '/api/localstate.v1', captured.routes.map((route) => route.path))
|
|
145
|
+
check('route declares GET and POST', captured.route?.methods.includes('GET') && captured.route?.methods.includes('POST'), captured.route?.methods)
|
|
146
|
+
check('route declares buffered bodies', captured.route?.requestBody === 'buffered', captured.route?.requestBody)
|
|
147
|
+
check('index-inject listener attached', captured.listeners.some(([event]) => event === 'webserver/index-inject'), captured.listeners.map(([event]) => event))
|
|
148
|
+
|
|
149
|
+
const getResponse = await captured.route.fetch(new Request('http://127.0.0.1:3080/api/localstate.v1', { method: 'GET' }))
|
|
150
|
+
const getBody = await getResponse.json()
|
|
151
|
+
check('GET returns the snapshot plus client config', getResponse.status === 200 && Array.isArray(getBody.keys) && getBody.config.prefixes[0] === 'dsh.' && getBody.config.language === 'auto', { status: getResponse.status, config: getBody.config })
|
|
152
|
+
|
|
153
|
+
const postResponse = await captured.route.fetch(new Request('http://127.0.0.1:3080/api/localstate.v1', {
|
|
154
|
+
method: 'POST',
|
|
155
|
+
headers: { 'content-type': 'application/json' },
|
|
156
|
+
body: JSON.stringify({ changes: { 'dsh.keybindings.v1': '{"submit":"Mod+Enter"}' } }),
|
|
157
|
+
}))
|
|
158
|
+
const postBody = await postResponse.json()
|
|
159
|
+
check('POST merges and reports the new revision', postResponse.status === 200 && postBody.ok === true && postBody.accepted.length === 1 && postBody.accepted[0][1] === 4, postBody)
|
|
160
|
+
|
|
161
|
+
const badJson = await captured.route.fetch(new Request('http://127.0.0.1:3080/api/localstate.v1', { method: 'POST', body: '{' }))
|
|
162
|
+
check('malformed body answered with 400', badJson.status === 400, badJson.status)
|
|
163
|
+
|
|
164
|
+
const putResponse = await captured.route.fetch(new Request('http://127.0.0.1:3080/api/localstate.v1', { method: 'PUT' }))
|
|
165
|
+
check('unsupported method answered with 405', putResponse.status === 405, putResponse.status)
|
|
166
|
+
|
|
167
|
+
// ---------------------------------------------------------------- config route
|
|
168
|
+
const configRoute = captured.routes.find((route) => route.path === '/api/localstate.config.v1')
|
|
169
|
+
check('config route registered beside the data route', configRoute !== undefined && configRoute.methods.join(',') === 'GET,POST', captured.routes.map((route) => route.path))
|
|
170
|
+
|
|
171
|
+
const { fieldDescriptors } = await import('../index.js')
|
|
172
|
+
const fields = fieldDescriptors()
|
|
173
|
+
check('descriptors cover every config field', fields.length === 11 && fields[0].name === 'enabled' && fields[10].name === 'language', fields.map((field) => field.name))
|
|
174
|
+
check('descriptors carry kind and description', fields[0].kind === 'boolean' && fields[0].description.includes('Turn the whole bundle off') && fields[4].kind === 'array' && fields[4].item === 'string', fields.slice(0, 5))
|
|
175
|
+
check('numeric descriptors carry their minimum', fields[7].min === 1024 && fields[7].default === 262144, fields[7])
|
|
176
|
+
const languageField = fields.find((field) => field.name === 'language')
|
|
177
|
+
check('the language field is a union with its literals', languageField?.kind === 'union' && languageField.default === 'auto' && JSON.stringify(languageField.options) === '["auto","en","zh"]', languageField)
|
|
178
|
+
|
|
179
|
+
const configGet = await configRoute.fetch(new Request('http://127.0.0.1:3080/api/localstate.config.v1', { method: 'GET' }))
|
|
180
|
+
const configGetBody = await configGet.json()
|
|
181
|
+
check('config GET reports values, fields and writability', configGet.status === 200 && configGetBody.ok === true && configGetBody.writable === true && configGetBody.values.maxKeys === 2000 && configGetBody.fields.length === 11, { status: configGet.status, writable: configGetBody.writable })
|
|
182
|
+
check('config GET reports the resolved file path', configGetBody.filePath === join(home, 'localstate-sync/state.json'), configGetBody.filePath)
|
|
183
|
+
check('config GET marks the explicit override keys', Array.isArray(configGetBody.explicit) && configGetBody.explicit.includes('includePrefixes'), configGetBody.explicit)
|
|
184
|
+
|
|
185
|
+
const configPost = await configRoute.fetch(new Request('http://127.0.0.1:3080/api/localstate.config.v1', {
|
|
186
|
+
method: 'POST',
|
|
187
|
+
headers: { 'content-type': 'application/json' },
|
|
188
|
+
body: JSON.stringify({ config: { maxKeys: 5 } }),
|
|
189
|
+
}))
|
|
190
|
+
const configPostBody = await configPost.json()
|
|
191
|
+
check('config POST accepts a partial draft', configPost.status === 200 && configPostBody.ok === true, configPostBody)
|
|
192
|
+
check('config POST merges into the row config', captured.edits.length === 1 && captured.edits[0].config.maxKeys === 5 && captured.edits[0].config.includePrefixes[0] === 'dsh.', captured.edits)
|
|
193
|
+
|
|
194
|
+
const unknownField = await configRoute.fetch(new Request('http://127.0.0.1:3080/api/localstate.config.v1', {
|
|
195
|
+
method: 'POST',
|
|
196
|
+
headers: { 'content-type': 'application/json' },
|
|
197
|
+
body: JSON.stringify({ config: { nope: 1 } }),
|
|
198
|
+
}))
|
|
199
|
+
const unknownBody = await unknownField.json()
|
|
200
|
+
check('config POST refuses an unknown field', unknownField.status === 400 && unknownBody.reason === 'unknown-field' && unknownBody.fields[0] === 'nope', unknownBody)
|
|
201
|
+
|
|
202
|
+
const badDraft = await configRoute.fetch(new Request('http://127.0.0.1:3080/api/localstate.config.v1', {
|
|
203
|
+
method: 'POST',
|
|
204
|
+
headers: { 'content-type': 'application/json' },
|
|
205
|
+
body: JSON.stringify({ config: [] }),
|
|
206
|
+
}))
|
|
207
|
+
check('config POST refuses a non-object draft', badDraft.status === 400, badDraft.status)
|
|
208
|
+
|
|
209
|
+
// A disabled bundle keeps the config route so the form can turn it back on.
|
|
210
|
+
const disabled = fakeContext()
|
|
211
|
+
apply(disabled.ctx, { enabled: false })
|
|
212
|
+
check('disabled bundle still serves the config route', disabled.captured.routes.length === 1 && disabled.captured.routes[0].path === '/api/localstate.config.v1', disabled.captured.routes.map((route) => route.path))
|
|
213
|
+
|
|
214
|
+
// ---------------------------------------------------------------- index inject
|
|
215
|
+
function injectFor(principalKind) {
|
|
216
|
+
const table = []
|
|
217
|
+
const listener = captured.listeners.find(([event]) => event === 'webserver/index-inject')[1]
|
|
218
|
+
listener(table, { principal: { kind: principalKind } })
|
|
219
|
+
return table
|
|
220
|
+
}
|
|
221
|
+
const ownerRows = injectFor('owner')
|
|
222
|
+
check('owner gets a global row and the seeder script', ownerRows.length === 2 && ownerRows[0].kind === 'global' && ownerRows[0].name === '__DSH_LOCALSTATE__' && ownerRows[1].kind === 'script' && ownerRows[1].placement === 'head', ownerRows.map((row) => row.kind))
|
|
223
|
+
check('injected global carries triples', Array.isArray(ownerRows[0]?.value?.keys) && ownerRows[0].value.prefixes[0] === 'dsh.', ownerRows[0]?.value?.prefixes)
|
|
224
|
+
check('injected global carries the configured language', ownerRows[0]?.value?.config?.language === 'auto', ownerRows[0]?.value?.config)
|
|
225
|
+
check('non-owner peer receives nothing', injectFor('shared').length === 0, injectFor('shared').length)
|
|
226
|
+
check('seeder script is the file text', ownerRows[1].text.startsWith('/* Injected into <head>'), ownerRows[1].text.slice(0, 40))
|
|
227
|
+
|
|
228
|
+
// ---------------------------------------------------------------- seeder logic
|
|
229
|
+
const seederText = readFileSync(join(import.meta.dirname, '..', 'seeder.js'), 'utf8')
|
|
230
|
+
const seederBody = seederText.replace(/^\/\*[\s\S]*?\*\/\s*/, '')
|
|
231
|
+
function runSeeder(globalValue, seed) {
|
|
232
|
+
const map = new Map(Object.entries(seed))
|
|
233
|
+
const localStorage = {
|
|
234
|
+
getItem: (key) => (map.has(key) ? map.get(key) : null),
|
|
235
|
+
setItem: (key, value) => void map.set(key, String(value)),
|
|
236
|
+
removeItem: (key) => void map.delete(key),
|
|
237
|
+
}
|
|
238
|
+
const globalThisStub = { __DSH_LOCALSTATE__: globalValue }
|
|
239
|
+
const run = new Function('globalThis', 'localStorage', seederBody)
|
|
240
|
+
run(globalThisStub, localStorage)
|
|
241
|
+
return { map, applied: globalThisStub.__DSH_LOCALSTATE_APPLIED__ }
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
const seeded = runSeeder(
|
|
245
|
+
{ v: 1, seq: 7, keys: [['dsh.keybindings.v1', '{"submit":"Mod+Enter"}', 4], ['dsh.gone', null, 5]] },
|
|
246
|
+
{ 'dsh.keybindings.v1': '{"submit":"Enter"}', 'dsh.gone': 'stale' },
|
|
247
|
+
)
|
|
248
|
+
check('seeder overwrites an older local value', seeded.map.get('dsh.keybindings.v1') === '{"submit":"Mod+Enter"}', seeded.map.get('dsh.keybindings.v1'))
|
|
249
|
+
check('seeder removes a tombstoned key', seeded.map.has('dsh.gone') === false, [...seeded.map.keys()])
|
|
250
|
+
check('seeder records applied revisions', seeded.applied === 2 && JSON.parse(seeded.map.get('__dsh.localstate.meta.v1')).at['dsh.gone'] === 5, seeded.map.get('__dsh.localstate.meta.v1'))
|
|
251
|
+
|
|
252
|
+
const skipped = runSeeder(
|
|
253
|
+
{ v: 1, seq: 7, keys: [['dsh.keybindings.v1', '{"submit":"stale-host"}', 2]] },
|
|
254
|
+
{ 'dsh.keybindings.v1': '{"submit":"newer-local"}', '__dsh.localstate.meta.v1': JSON.stringify({ seq: 9, at: { 'dsh.keybindings.v1': 6 } }) },
|
|
255
|
+
)
|
|
256
|
+
check('seeder keeps a newer local value', skipped.map.get('dsh.keybindings.v1') === '{"submit":"newer-local"}' && skipped.applied === 0, skipped.applied)
|
|
257
|
+
|
|
258
|
+
// ---------------------------------------------------------------- client bundle
|
|
259
|
+
const clientText = readFileSync(join(import.meta.dirname, '..', 'client.js'), 'utf8')
|
|
260
|
+
check('client registers under the package name', clientText.includes("id: '@leonhoy/dsh-localstate-sync'"))
|
|
261
|
+
check('client patches the three storage methods', ['setItem', 'removeItem', 'clear'].every((name) => clientText.includes(`${name}: proto.${name}`)))
|
|
262
|
+
check('client flushes on pagehide with a beacon', clientText.includes("addEventListener('pagehide'") && clientText.includes('sendBeacon'))
|
|
263
|
+
check('client skips file:// origins', clientText.includes("location.protocol === 'file:'"))
|
|
264
|
+
|
|
265
|
+
const loaded = {}
|
|
266
|
+
const styles = []
|
|
267
|
+
const requests = []
|
|
268
|
+
const replies = []
|
|
269
|
+
const sandbox = {
|
|
270
|
+
document: {
|
|
271
|
+
baseURI: 'http://127.0.0.1:3080/',
|
|
272
|
+
visibilityState: 'visible',
|
|
273
|
+
documentElement: { getAttribute: () => 'zh' },
|
|
274
|
+
head: { appendChild: (node) => styles.push(node) },
|
|
275
|
+
createElement: () => ({ setAttribute() {}, textContent: '' }),
|
|
276
|
+
addEventListener() {},
|
|
277
|
+
removeEventListener() {},
|
|
278
|
+
},
|
|
279
|
+
navigator: { language: 'zh-CN' },
|
|
280
|
+
location: { protocol: 'http:' },
|
|
281
|
+
fetch: async (url, init) => {
|
|
282
|
+
requests.push({ url, method: init?.method ?? 'GET', body: init?.body })
|
|
283
|
+
if ((init?.method ?? 'GET') !== 'POST') return { ok: false, status: 503, json: async () => ({}) }
|
|
284
|
+
const next = replies.shift()
|
|
285
|
+
if (next === undefined) return { ok: true, status: 200, json: async () => ({ ok: true, seq: 99, accepted: [], conflicts: [] }) }
|
|
286
|
+
return { ok: true, status: 200, json: async () => next }
|
|
287
|
+
},
|
|
288
|
+
setTimeout,
|
|
289
|
+
clearTimeout,
|
|
290
|
+
URL,
|
|
291
|
+
Blob,
|
|
292
|
+
Map,
|
|
293
|
+
__ModuleLoader__: { load(definition) { loaded.definition = definition } },
|
|
294
|
+
}
|
|
295
|
+
const sites = new Map()
|
|
296
|
+
sandbox.Storage = function Storage() {}
|
|
297
|
+
sandbox.Storage.prototype = {
|
|
298
|
+
getItem(key) {
|
|
299
|
+
return sites.has(key) ? sites.get(key) : null
|
|
300
|
+
},
|
|
301
|
+
setItem(key, value) {
|
|
302
|
+
sites.set(key, String(value))
|
|
303
|
+
},
|
|
304
|
+
removeItem(key) {
|
|
305
|
+
sites.delete(key)
|
|
306
|
+
},
|
|
307
|
+
clear() {
|
|
308
|
+
sites.clear()
|
|
309
|
+
},
|
|
310
|
+
}
|
|
311
|
+
// localStorage must reach its methods through the prototype so the capture patch sees the writes.
|
|
312
|
+
sandbox.localStorage = Object.create(sandbox.Storage.prototype)
|
|
313
|
+
// The notices follow the browser before the DSH locale, so the sandbox needs a language.
|
|
314
|
+
sandbox.navigator = { language: 'zh-CN', languages: ['zh-CN'] }
|
|
315
|
+
sandbox.window = sandbox
|
|
316
|
+
sandbox.addEventListener = () => {}
|
|
317
|
+
sandbox.removeEventListener = () => {}
|
|
318
|
+
runInContext(clientText, createContext(sandbox))
|
|
319
|
+
check('client bundle registers itself with the loader', loaded.definition?.id === '@leonhoy/dsh-localstate-sync', loaded.definition?.id)
|
|
320
|
+
|
|
321
|
+
const ReactShim = {
|
|
322
|
+
createElement: (type, props, ...children) => ({ type, props: props ?? {}, children }),
|
|
323
|
+
useState: (initial) => [typeof initial === 'function' ? initial() : initial, () => {}],
|
|
324
|
+
useEffect: () => {},
|
|
325
|
+
}
|
|
326
|
+
const bundle = loaded.definition.factory((name) => {
|
|
327
|
+
if (name === 'react') return ReactShim
|
|
328
|
+
throw new Error('unexpected require: ' + name)
|
|
329
|
+
})
|
|
330
|
+
|
|
331
|
+
const cells = []
|
|
332
|
+
const clientCtx = {
|
|
333
|
+
slots: {
|
|
334
|
+
inject(name, callback) { cells.push({ name, callback }) },
|
|
335
|
+
register(definition, Component) { cells.push({ definition, Component }); return () => {} },
|
|
336
|
+
},
|
|
337
|
+
locale: { getSnapshot: () => ({ active: 'zh' }) },
|
|
338
|
+
effect(fn) { fn(); return () => {} },
|
|
339
|
+
}
|
|
340
|
+
bundle.apply(clientCtx)
|
|
341
|
+
const injectCall = cells.find((entry) => entry.name === 'plugins.bundle.config')
|
|
342
|
+
check('client injects into the bundle config slot', injectCall !== undefined, cells.map((entry) => entry.name))
|
|
343
|
+
injectCall.callback()
|
|
344
|
+
const cell = cells.find((entry) => entry.definition !== undefined)
|
|
345
|
+
check('config cell is keyed by the package name', cell?.definition.name === 'plugins.bundle.config' && cell?.definition.key === '@leonhoy/dsh-localstate-sync', cell?.definition)
|
|
346
|
+
check('config cell exposes a component', typeof cell.Component === 'function')
|
|
347
|
+
const rendered = cell.Component({ view: 'page' })
|
|
348
|
+
check('config form renders its loading state', rendered.type === 'p', rendered.type)
|
|
349
|
+
check('config form renders nothing in summary view', cell.Component({ view: 'summary' }) === null)
|
|
350
|
+
check('capture patch installs on the page', sandbox.__DSH_LOCALSTATE_CAPTURE__ === true, sandbox.__DSH_LOCALSTATE_CAPTURE__)
|
|
351
|
+
|
|
352
|
+
// ---------------------------------------------------------------- client write conflicts
|
|
353
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
|
|
354
|
+
const posts = () => requests.filter((entry) => entry.method === 'POST')
|
|
355
|
+
const bodyOf = (entry) => JSON.parse(entry.body)
|
|
356
|
+
|
|
357
|
+
replies.push({ ok: true, seq: 10, accepted: [], conflicts: [{ key: 'dsh.probe', expected: 0, current: 7, at: 7, value: 'remote-a' }] })
|
|
358
|
+
replies.push({ ok: true, seq: 11, accepted: [], conflicts: [{ key: 'dsh.probe', expected: 7, current: 11, at: 11, value: 'remote-b' }] })
|
|
359
|
+
sandbox.localStorage.setItem('dsh.probe', 'local-1')
|
|
360
|
+
await sleep(520)
|
|
361
|
+
const firstPost = posts()[0]
|
|
362
|
+
check('the browser sends the write as a plain batch', firstPost !== undefined && bodyOf(firstPost).changes['dsh.probe'] === 'local-1', firstPost && bodyOf(firstPost))
|
|
363
|
+
check('no base is sent for a key the browser has no revision for', firstPost !== undefined && bodyOf(firstPost).base === undefined, firstPost && bodyOf(firstPost).base)
|
|
364
|
+
|
|
365
|
+
await sleep(620)
|
|
366
|
+
const secondPost = posts()[1]
|
|
367
|
+
check('a conflict is resent once with the fresh base', secondPost !== undefined && bodyOf(secondPost).base['dsh.probe'] === 7, secondPost && bodyOf(secondPost))
|
|
368
|
+
check('the resent batch keeps the local value', secondPost !== undefined && bodyOf(secondPost).changes['dsh.probe'] === 'local-1', secondPost && bodyOf(secondPost).changes)
|
|
369
|
+
|
|
370
|
+
await sleep(700)
|
|
371
|
+
const kept = sandbox.__DSH_LOCALSTATE_CONFLICTS__?.['dsh.probe']
|
|
372
|
+
check('a second conflict keeps the local value', kept !== undefined && kept.local === 'local-1' && kept.remote === 'remote-b' && kept.at === 11, kept)
|
|
373
|
+
check('the retry does not loop', posts().length === 2, posts().length)
|
|
374
|
+
check('the local value survives the conflict', sites.get('dsh.probe') === 'local-1', sites.get('dsh.probe'))
|
|
375
|
+
|
|
376
|
+
// ---------------------------------------------------------------- conflict notices
|
|
377
|
+
const notices = sandbox.__DSH_LOCALSTATE_NOTICES__ ?? []
|
|
378
|
+
const pushFail = notices.find((entry) => entry.kind === 'error')
|
|
379
|
+
check('a refused write raises a push-failed notice', pushFail !== undefined && pushFail.text.includes('11'), pushFail)
|
|
380
|
+
check('the notice names the key that failed', pushFail?.key === 'dsh.probe', pushFail?.key)
|
|
381
|
+
check('nothing is announced when the revisions already agree', notices.every((entry) => entry.kind !== 'info'), notices.map((entry) => entry.kind))
|
|
382
|
+
|
|
383
|
+
sandbox.localStorage.setItem('dsh.probe', 'local-2')
|
|
384
|
+
await sleep(520)
|
|
385
|
+
const thirdPost = posts()[2]
|
|
386
|
+
check('after a failed push the base stays stale, so only a reload can pull', thirdPost !== undefined && bodyOf(thirdPost).base['dsh.probe'] === 7, thirdPost && bodyOf(thirdPost).base)
|
|
387
|
+
|
|
388
|
+
// ---------------------------------------------------------------- boot notice
|
|
389
|
+
const bootSites = new Map()
|
|
390
|
+
let bootDefinition
|
|
391
|
+
const bootGlobals = {
|
|
392
|
+
Storage: function Storage() {},
|
|
393
|
+
location: { protocol: 'http:', reload() {} },
|
|
394
|
+
document: {
|
|
395
|
+
baseURI: 'http://127.0.0.1:3081/',
|
|
396
|
+
visibilityState: 'visible',
|
|
397
|
+
documentElement: { getAttribute: () => 'en' },
|
|
398
|
+
head: { appendChild() {} },
|
|
399
|
+
createElement: () => ({ setAttribute() {}, textContent: '' }),
|
|
400
|
+
addEventListener() {},
|
|
401
|
+
removeEventListener() {},
|
|
402
|
+
},
|
|
403
|
+
__DSH_LOCALSTATE__: { v: 1, seq: 5, keys: [['dsh.a', 'remote-a', 5]], prefixes: ['dsh.'], truncated: false },
|
|
404
|
+
__DSH_LOCALSTATE_APPLIED__: 3,
|
|
405
|
+
__ModuleLoader__: { load(definition) { bootDefinition = definition } },
|
|
406
|
+
URL,
|
|
407
|
+
Blob,
|
|
408
|
+
Map,
|
|
409
|
+
setTimeout,
|
|
410
|
+
clearTimeout,
|
|
411
|
+
addEventListener() {},
|
|
412
|
+
removeEventListener() {},
|
|
413
|
+
fetch: async () => ({ ok: true, status: 200, json: async () => ({ ok: true, seq: 5, keys: [], truncated: false }) }),
|
|
414
|
+
}
|
|
415
|
+
bootGlobals.Storage.prototype = {
|
|
416
|
+
getItem: (key) => (bootSites.has(key) ? bootSites.get(key) : null),
|
|
417
|
+
setItem: (key, value) => { bootSites.set(key, String(value)) },
|
|
418
|
+
removeItem: (key) => { bootSites.delete(key) },
|
|
419
|
+
clear: () => { bootSites.clear() },
|
|
420
|
+
}
|
|
421
|
+
bootGlobals.localStorage = Object.create(bootGlobals.Storage.prototype)
|
|
422
|
+
bootGlobals.window = bootGlobals
|
|
423
|
+
runInContext(clientText, createContext(bootGlobals))
|
|
424
|
+
const bootBundle = bootDefinition.factory((name) => {
|
|
425
|
+
if (name === 'react') return ReactShim
|
|
426
|
+
throw new Error('unexpected require: ' + name)
|
|
427
|
+
})
|
|
428
|
+
bootBundle.apply({ locale: { getSnapshot: () => ({ active: 'en' }) }, effect(fn) { fn(); return () => {} } })
|
|
429
|
+
const bootNotices = bootGlobals.__DSH_LOCALSTATE_NOTICES__ ?? []
|
|
430
|
+
check('a boot that replaced values announces the newer synced revision', bootNotices.some((entry) => entry.kind === 'info' && entry.text.includes('3')), bootNotices)
|
|
431
|
+
|
|
432
|
+
rmSync(home, { recursive: true, force: true })
|
|
433
|
+
const failed = checks.filter((entry) => entry.ok !== true)
|
|
434
|
+
console.log(`\n${checks.length - failed.length}/${checks.length} checks passed`)
|
|
435
|
+
if (failed.length > 0) process.exitCode = 1
|