dsh-multi-device-config-sync 1.5.0 → 1.6.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/README.md +15 -7
- package/client.js +389 -65
- package/lib/plugins.js +25 -4
- package/lib/routes.js +74 -5
- package/lib/sync-install.js +39 -9
- package/locale/en.json +2 -2
- package/locale/zh.json +2 -2
- package/package.json +1 -1
- package/test/package.test.mjs +5 -2
- package/test/progress-client.test.mjs +225 -0
- package/test/progress-engine.test.mjs +235 -0
- package/test/progress-http.test.mjs +340 -0
package/lib/plugins.js
CHANGED
|
@@ -397,16 +397,35 @@ function emptyOutcomes() {
|
|
|
397
397
|
* @param {unknown} ctx - the host context.
|
|
398
398
|
* @returns {Promise<object>} the `/api/plugins/install` answer.
|
|
399
399
|
*/
|
|
400
|
-
export async function installMissingPlugins(ctx, { declarations = null, approved = null, selected = null } = {}) {
|
|
400
|
+
export async function installMissingPlugins(ctx, { declarations = null, approved = null, selected = null, progress } = {}) {
|
|
401
|
+
// The combined confirmation supplies its own non-throwing observer. The
|
|
402
|
+
// denominator stays bound to what was reviewed, not this second inventory.
|
|
403
|
+
const total = approved?.size ?? 0
|
|
404
|
+
const settled = new Set()
|
|
405
|
+
const installing = current => {
|
|
406
|
+
if (total > 0) progress?.({ stage: 'install', processed: settled.size, total, current })
|
|
407
|
+
}
|
|
408
|
+
const verifying = () => progress?.({ stage: 'verify', ...(total > 0 ? { processed: settled.size, total } : {}) })
|
|
409
|
+
if (total > 0) installing(null) // rechecking eligibility; no handoff yet
|
|
410
|
+
else verifying() // no approved installations: only the inventory checks remain
|
|
401
411
|
const before = await pluginInventory(ctx, declarations)
|
|
402
412
|
if (before.available !== true) {
|
|
403
413
|
return { ...before, results: [], outcomeCounts: emptyOutcomes(), restart: false }
|
|
404
414
|
}
|
|
405
415
|
const manager = /** @type {object} */ (managerOf(ctx))
|
|
406
416
|
const results = []
|
|
417
|
+
function record(result) {
|
|
418
|
+
results.push(result)
|
|
419
|
+
// A reviewed name skipped for a changed source has a real result; an
|
|
420
|
+
// unapproved skip or a name found only in the installed list does not.
|
|
421
|
+
if (progress && approved?.has(result.name)) {
|
|
422
|
+
settled.add(result.name)
|
|
423
|
+
installing(null)
|
|
424
|
+
}
|
|
425
|
+
}
|
|
407
426
|
for (const entry of before.missing) {
|
|
408
427
|
if (entry.installSpec === null || (approved && approved.get(entry.name) !== entry.installSpec)) {
|
|
409
|
-
|
|
428
|
+
record({
|
|
410
429
|
name: entry.name,
|
|
411
430
|
spec: entry.spec,
|
|
412
431
|
installSpec: null,
|
|
@@ -424,9 +443,10 @@ export async function installMissingPlugins(ctx, { declarations = null, approved
|
|
|
424
443
|
options.expected = { name: entry.name, version: entry.spec }
|
|
425
444
|
options.saveExact = true
|
|
426
445
|
}
|
|
427
|
-
|
|
446
|
+
if (progress && typeof manager?.installBundle === 'function') installing(entry.name)
|
|
447
|
+
record(outcomeOf(entry, await manager.installBundle(entry.installSpec, options)))
|
|
428
448
|
} catch (error) {
|
|
429
|
-
|
|
449
|
+
record({
|
|
430
450
|
name: entry.name,
|
|
431
451
|
spec: entry.spec,
|
|
432
452
|
installSpec: entry.installSpec,
|
|
@@ -441,6 +461,7 @@ export async function installMissingPlugins(ctx, { declarations = null, approved
|
|
|
441
461
|
// Re-read rather than assume: an installation that saved its dependency and
|
|
442
462
|
// one that failed to are told apart by what the manager reports now, not by
|
|
443
463
|
// what this run asked for.
|
|
464
|
+
if (total > 0) verifying()
|
|
444
465
|
const after = await pluginInventory(ctx, declarations)
|
|
445
466
|
if (declarations && after.available) {
|
|
446
467
|
const stillMissing = new Set(after.missing.map(row => row.name))
|
package/lib/routes.js
CHANGED
|
@@ -56,6 +56,78 @@ function sendJson(response, status, payload) {
|
|
|
56
56
|
response.end(body)
|
|
57
57
|
}
|
|
58
58
|
|
|
59
|
+
const NDJSON = 'application/x-ndjson'
|
|
60
|
+
const count = n => Number.isSafeInteger(n) && n >= 0
|
|
61
|
+
|
|
62
|
+
// An ordinary browser/old Client asking for */* still receives its original JSON.
|
|
63
|
+
function acceptsProgress(accept) {
|
|
64
|
+
return typeof accept === 'string' && accept.split(',').some(range => {
|
|
65
|
+
const [media, ...params] = range.toLowerCase().split(';').map(s => s.trim())
|
|
66
|
+
const q = params.find(p => /^q\s*=/.test(p))
|
|
67
|
+
return media === NDJSON && (q === undefined || Number(q.slice(q.indexOf('=') + 1)) > 0)
|
|
68
|
+
})
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// Do not serialize arbitrary internal objects onto the progress channel. In
|
|
72
|
+
// particular a source URL, path, plan ID or installation log is not a progress field.
|
|
73
|
+
function progressFrame(p) {
|
|
74
|
+
if (p?.stage === 'check' || p?.stage === 'write') return { type: 'progress', stage: p.stage }
|
|
75
|
+
if (!count(p?.files)) return null
|
|
76
|
+
if (p.stage === 'verify') {
|
|
77
|
+
const meter = count(p.processed) && count(p.total) && p.total > 0 && p.processed <= p.total
|
|
78
|
+
? { processed: p.processed, total: p.total } : {}
|
|
79
|
+
return { type: 'progress', stage: 'verify', files: p.files, ...meter }
|
|
80
|
+
}
|
|
81
|
+
if (p.stage !== 'install' || !count(p.processed) || !count(p.total) || p.total === 0 || p.processed > p.total
|
|
82
|
+
|| !(p.current === null || validPackageName(p.current))) return null
|
|
83
|
+
return { type: 'progress', stage: 'install', files: p.files, processed: p.processed, total: p.total, current: p.current }
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Same one-use operation for both protocols. Never start a second write to obtain progress or to recover a receipt. */
|
|
87
|
+
async function confirmReviewed(request, response, body, apply) {
|
|
88
|
+
if (!body || typeof body !== 'object' || Array.isArray(body) || Object.keys(body).some(k => k !== 'planId' && k !== 'confirm')) {
|
|
89
|
+
throw new ConfigSyncError('A reviewed restore accepts only the plan ID and confirmation.', 'invalid')
|
|
90
|
+
}
|
|
91
|
+
if (!acceptsProgress(request.headers.accept)) {
|
|
92
|
+
sendJson(response, 200, await apply(body.planId, body.confirm))
|
|
93
|
+
return
|
|
94
|
+
}
|
|
95
|
+
// The route's independent writer lock belongs to the operation, not the
|
|
96
|
+
// socket. A closed tab discards feedback; it does not cancel or repeat work.
|
|
97
|
+
let disconnected = false
|
|
98
|
+
const detach = () => { disconnected = true }
|
|
99
|
+
response.once('error', detach)
|
|
100
|
+
response.once('close', detach)
|
|
101
|
+
const send = (frame, final = false) => {
|
|
102
|
+
if (disconnected || response.destroyed || response.writableEnded || (!final && response.writableNeedDrain)) return
|
|
103
|
+
if (!response.headersSent) response.writeHead(200, {
|
|
104
|
+
'content-type': `${NDJSON}; charset=utf-8`, 'cache-control': 'no-store, no-transform',
|
|
105
|
+
'x-accel-buffering': 'no', 'x-content-type-options': 'nosniff', vary: 'Accept',
|
|
106
|
+
})
|
|
107
|
+
const line = `${JSON.stringify(frame)}\n`
|
|
108
|
+
if (final) response.end(line)
|
|
109
|
+
else {
|
|
110
|
+
// Flush each small stage as one HTTP chunk now, rather than leaving the
|
|
111
|
+
// default next-tick cork closed during a synchronous configuration write.
|
|
112
|
+
response.cork()
|
|
113
|
+
try { response.write(line) } finally { response.uncork() }
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
try {
|
|
117
|
+
const result = await apply(body.planId, body.confirm, event => {
|
|
118
|
+
const frame = progressFrame(event)
|
|
119
|
+
if (frame) send(frame)
|
|
120
|
+
})
|
|
121
|
+
send({ type: 'result', result }, true)
|
|
122
|
+
} catch (error) {
|
|
123
|
+
// Preserve HTTP errors before the stream starts; after that the final
|
|
124
|
+
// error record, not the 200 handshake, carries the terminal outcome.
|
|
125
|
+
if (disconnected || response.destroyed || response.writableEnded) return
|
|
126
|
+
if (!response.headersSent) throw error
|
|
127
|
+
send({ type: 'error', ...describeError(error) }, true)
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
59
131
|
/** Read and parse a JSON request body. */
|
|
60
132
|
async function readJsonBody(request) {
|
|
61
133
|
const chunks = []
|
|
@@ -273,10 +345,7 @@ async function handleRequest(ctx, session, request, response) {
|
|
|
273
345
|
}
|
|
274
346
|
if (method === 'POST' && (route === '/api/sync/install' || route === '/api/config/restore')) {
|
|
275
347
|
const body = await readJsonBody(request)
|
|
276
|
-
|
|
277
|
-
? session.confirmConfig(body?.planId, body?.confirm)
|
|
278
|
-
: await session.confirm(body?.planId, body?.confirm)
|
|
279
|
-
sendJson(response, 200, result)
|
|
348
|
+
await confirmReviewed(request, response, body, route === '/api/config/restore' ? session.confirmConfig : session.confirm)
|
|
280
349
|
return
|
|
281
350
|
}
|
|
282
351
|
|
|
@@ -309,7 +378,7 @@ async function handleRequest(ctx, session, request, response) {
|
|
|
309
378
|
const body = await readJsonBody(request)
|
|
310
379
|
if (body?.planId !== undefined) {
|
|
311
380
|
if (body.backup !== undefined) throw new ConfigSyncError('A reviewed import accepts a plan ID, not a replacement backup.', 'invalid')
|
|
312
|
-
|
|
381
|
+
await confirmReviewed(request, response, body, session.confirmLocal)
|
|
313
382
|
return
|
|
314
383
|
}
|
|
315
384
|
if (body?.confirm !== true) {
|
package/lib/sync-install.js
CHANGED
|
@@ -11,6 +11,26 @@ const PLAN_TTL_MS = 5 * 60_000
|
|
|
11
11
|
const stale = () => new ConfigSyncError('This preview expired or the local state changed. Preview the restore again.', 'stale-plan')
|
|
12
12
|
const busyError = () => new ConfigSyncError('Another restore or installation is running.', 'busy')
|
|
13
13
|
|
|
14
|
+
// An observer belongs only to this confirmation. A closed response, a throwing
|
|
15
|
+
// listener or a rejected delivery promise must not cancel (or hold up) a write.
|
|
16
|
+
function notify(listener, event) {
|
|
17
|
+
if (typeof listener !== 'function') return
|
|
18
|
+
try {
|
|
19
|
+
const delivery = listener(event)
|
|
20
|
+
if (delivery && typeof delivery.then === 'function') Promise.resolve(delivery).catch(() => {})
|
|
21
|
+
} catch { /* the transaction does not depend on progress delivery */ }
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// File-only modes check the commit receipt, not a plugin inventory or a second
|
|
25
|
+
// read of every file. restored counts completed writes; counts came from the write plan.
|
|
26
|
+
function verifyWriteReceipt(report, onProgress) {
|
|
27
|
+
notify(onProgress, { stage: 'verify', files: report.restored })
|
|
28
|
+
const { add, overwrite, merge } = report.counts
|
|
29
|
+
if (report.restored !== add + overwrite + merge) {
|
|
30
|
+
throw new ConfigSyncError('Configuration writes finished, but the receipt does not match the write plan. Check the local files before retrying.', 'other')
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
14
34
|
// Standard DSH state plus additional plugins' ordinary text configuration. Do
|
|
15
35
|
// not bring across package-manager policy, env files or unmanaged executables.
|
|
16
36
|
function isConfiguration(path) {
|
|
@@ -135,10 +155,12 @@ export function createRestoreSession(ctx) {
|
|
|
135
155
|
const planId = slot.save({ config, digest, ...source })
|
|
136
156
|
return { planId, preview }
|
|
137
157
|
}
|
|
138
|
-
function takeFiles(slot, planId, confirm) {
|
|
158
|
+
function takeFiles(slot, planId, confirm, onProgress) {
|
|
139
159
|
if (confirm !== true) throw new ConfigSyncError('Review the plan and explicitly confirm the configuration restore.', 'invalid')
|
|
140
160
|
const plan = slot.take(planId)
|
|
161
|
+
notify(onProgress, { stage: 'check' })
|
|
141
162
|
verify(plan)
|
|
163
|
+
notify(onProgress, { stage: 'write' })
|
|
142
164
|
return plan
|
|
143
165
|
}
|
|
144
166
|
return {
|
|
@@ -149,14 +171,18 @@ export function createRestoreSession(ctx) {
|
|
|
149
171
|
return () => { busy = false }
|
|
150
172
|
},
|
|
151
173
|
previewConfig(ref, backup) { return { ...previewFiles(configOnly, backup, { ref }), ref } },
|
|
152
|
-
confirmConfig(planId, confirm) {
|
|
153
|
-
const plan = takeFiles(configOnly, planId, confirm)
|
|
154
|
-
|
|
174
|
+
confirmConfig(planId, confirm, onProgress) {
|
|
175
|
+
const plan = takeFiles(configOnly, planId, confirm, onProgress)
|
|
176
|
+
const result = restoreGistConfiguration(plan.ref, plan.config)
|
|
177
|
+
verifyWriteReceipt(result.report, onProgress)
|
|
178
|
+
return result
|
|
155
179
|
},
|
|
156
180
|
previewLocal(backup) { return previewFiles(local, backup) },
|
|
157
|
-
confirmLocal(planId, confirm) {
|
|
158
|
-
const plan = takeFiles(local, planId, confirm)
|
|
159
|
-
|
|
181
|
+
confirmLocal(planId, confirm, onProgress) {
|
|
182
|
+
const plan = takeFiles(local, planId, confirm, onProgress)
|
|
183
|
+
const report = restoreValidatedFiles(plan.config)
|
|
184
|
+
verifyWriteReceipt(report, onProgress)
|
|
185
|
+
return { report }
|
|
160
186
|
},
|
|
161
187
|
async preview(ref, backup) {
|
|
162
188
|
requireIdle()
|
|
@@ -171,9 +197,10 @@ export function createRestoreSession(ctx) {
|
|
|
171
197
|
const planId = combined.save({ ref, config, declarations, wanted, digest: fingerprint(config, plugins) })
|
|
172
198
|
return { planId, ref, preview, plugins }
|
|
173
199
|
},
|
|
174
|
-
async confirm(planId, confirm) {
|
|
200
|
+
async confirm(planId, confirm, onProgress) {
|
|
175
201
|
if (confirm !== true) throw new ConfigSyncError('Review the plan and explicitly confirm the restore and installation.', 'invalid')
|
|
176
202
|
const plan = combined.take(planId)
|
|
203
|
+
notify(onProgress, { stage: 'check' })
|
|
177
204
|
const { ref, config, declarations, wanted } = plan
|
|
178
205
|
const pluginsBefore = await pluginInventory(ctx, declarations)
|
|
179
206
|
if (!pluginsBefore.available) throw stale()
|
|
@@ -182,10 +209,13 @@ export function createRestoreSession(ctx) {
|
|
|
182
209
|
const current = JSON.parse(readFileSync(join(profileRoot(), 'package.json'), 'utf8'))
|
|
183
210
|
const localBundles = current?.dsh?.profile?.bundles
|
|
184
211
|
const selected = new Set([...(Array.isArray(localBundles) ? localBundles : []), ...wanted])
|
|
212
|
+
notify(onProgress, { stage: 'write' })
|
|
185
213
|
const restored = restoreGistConfiguration(ref, config) // if writing fails, do not start an installation
|
|
186
214
|
let plugins
|
|
187
215
|
try {
|
|
188
|
-
|
|
216
|
+
const progress = typeof onProgress === 'function'
|
|
217
|
+
? event => notify(onProgress, { ...event, files: restored.report.restored }) : undefined
|
|
218
|
+
plugins = await installMissingPlugins(ctx, { declarations, approved, selected, progress })
|
|
189
219
|
} catch (error) {
|
|
190
220
|
// The configuration is already on disk and can be undone. Never report
|
|
191
221
|
// an installer/inventory error as if the restore had not happened.
|
package/locale/en.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"meta": {
|
|
3
3
|
"title": "Multi-device config sync",
|
|
4
|
-
"description": "Back up your DSH profile to a GitHub Gist. Open Multi-device config sync in the Settings sidebar to preview file changes and
|
|
4
|
+
"description": "Back up your DSH profile to a GitHub Gist. Open Multi-device config sync in the Settings sidebar to preview file changes and plugin sources. After confirmation, follow the restore steps, package progress and individual results. Use a trusted Gist; undo restores configuration only, not packages."
|
|
5
5
|
},
|
|
6
6
|
"tab": "Multi-device config sync",
|
|
7
7
|
"title": "Multi-device config sync",
|
|
@@ -19,6 +19,6 @@
|
|
|
19
19
|
"newMachineStep1": "Install Multi-device config sync in the target profile.",
|
|
20
20
|
"newMachineStep2": "Choose Restore from backup and use the linked backup or paste a trusted link from another machine.",
|
|
21
21
|
"newMachineStep3": "Review file changes, plugin sources and items that need manual setup. Address GitHub access only if prompted.",
|
|
22
|
-
"newMachineStep4": "Confirm only if you trust the plan.
|
|
22
|
+
"newMachineStep4": "Confirm only if you trust the plan. Follow progress and read the receipt in place. Review pending builds separately and restart DSH if indicated.",
|
|
23
23
|
"tokenHelp": "Use the token field, DSH_GITHUB_TOKEN / GITHUB_TOKEN on the host, or a signed-in gh CLI. Do not share tokens or Gist links."
|
|
24
24
|
}
|
package/locale/zh.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"meta": {
|
|
3
3
|
"title": "多端配置同步",
|
|
4
|
-
"description": "将 DSH 配置备份到 GitHub Gist
|
|
4
|
+
"description": "将 DSH 配置备份到 GitHub Gist。在设置左侧打开「多端配置同步」,先预览文件变更和插件来源,确认后可查看恢复步骤、插件处理进度和逐项结果。只使用可信 Gist;撤销只恢复配置,不卸载软件包。"
|
|
5
5
|
},
|
|
6
6
|
"tab": "多端配置同步",
|
|
7
7
|
"title": "多端配置同步",
|
|
@@ -19,6 +19,6 @@
|
|
|
19
19
|
"newMachineStep1": "在目标配置中安装「多端配置同步」。",
|
|
20
20
|
"newMachineStep2": "点「从备份恢复」,使用已关联的备份,或粘贴另一台电脑生成的链接。",
|
|
21
21
|
"newMachineStep3": "查看预览,核对文件变更、插件来源和需手动处理的项目。若 GitHub 拒绝访问,再按提示配置凭据。",
|
|
22
|
-
"newMachineStep4": "
|
|
22
|
+
"newMachineStep4": "信任该计划才确认。可在原位置查看恢复阶段和最终结果;单独核对待审批的构建脚本,并按提示重启 DSH。",
|
|
23
23
|
"tokenHelp": "可使用页面令牌栏、宿主环境的 DSH_GITHUB_TOKEN / GITHUB_TOKEN 或已登录的 gh CLI;不要分享令牌或 Gist 链接。"
|
|
24
24
|
}
|
package/package.json
CHANGED
package/test/package.test.mjs
CHANGED
|
@@ -85,7 +85,7 @@ check('the client half is shipped', shipped.includes('client.js'))
|
|
|
85
85
|
check('the bundle patch is shipped', shipped.includes('cordis.patch.yml'))
|
|
86
86
|
const packedManifest = JSON.parse(readFileSync(join(installed, 'package.json'), 'utf8'))
|
|
87
87
|
check('the tarball identifies the public npm release and its source repository',
|
|
88
|
-
packedManifest.name === 'dsh-multi-device-config-sync' && packedManifest.version === '1.
|
|
88
|
+
packedManifest.name === 'dsh-multi-device-config-sync' && packedManifest.version === '1.6.0'
|
|
89
89
|
&& packedManifest.publishConfig.access === 'public' && packedManifest.publishConfig.registry === 'https://registry.npmjs.org/'
|
|
90
90
|
&& packedManifest.repository.url === 'git+https://github.com/Xeonice/dsh-profile-gist-sync-plus.git')
|
|
91
91
|
check('installing the public bundle introduces no dependencies and runs no lifecycle scripts',
|
|
@@ -104,7 +104,10 @@ check('both icon forms and the README are shipped', ['icon.svg', 'assets/icon-25
|
|
|
104
104
|
check('the tarball does not advertise or include upstream screenshots', !shipped.some(file => /screenshot/i.test(file)))
|
|
105
105
|
check('the original author and MIT licence travel with it', packedManifest.author === 'Meta-Virgo' && packedManifest.license === 'MIT'
|
|
106
106
|
&& readFileSync(join(installed, 'LICENSE'), 'utf8').includes('Copyright (c) 2026 Meta-Virgo'))
|
|
107
|
-
check('the checks travel with it, so a reader can run them',
|
|
107
|
+
check('the checks travel with it, so a reader can run them',
|
|
108
|
+
readdirSync(join(PLUGIN, 'test')).filter(name => name.endsWith('.mjs')).every(name => shipped.includes(`test/${name}`)))
|
|
109
|
+
check('design mockups, generated previews and release archives stay out of the runtime package',
|
|
110
|
+
!shipped.some(file => /(?:^|\/)(?:design-previews|release-artifacts|prototype\.html|restore-progress\.png)(?:\/|$)|\.tgz$/i.test(file)))
|
|
108
111
|
if (packed.size !== null) check(`the tarball is below 200 KiB (${packed.size} bytes)`, packed.size < 200 * 1024)
|
|
109
112
|
check('no working state leaked into the package',
|
|
110
113
|
!shipped.some(file => file.includes('.dsh-config-sync') || file.includes('node_modules') || file.endsWith('settings.json')),
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
/** Exercise the shipped single-file client with real Web Streams and fixture fetch only.
|
|
2
|
+
* Expose its transport and pure view decisions inside this VM, never in the bundle.
|
|
3
|
+
* No React renderer, DOM, profile, sockets, Gist operations or package installation.
|
|
4
|
+
*/
|
|
5
|
+
import assert from 'node:assert/strict'
|
|
6
|
+
import { readFileSync } from 'node:fs'
|
|
7
|
+
import vm from 'node:vm'
|
|
8
|
+
import { createReport, TEST_GIST_ID } from './harness.mjs'
|
|
9
|
+
|
|
10
|
+
const { check, finish } = createReport('restore progress client')
|
|
11
|
+
const source = readFileSync(new URL('../client.js', import.meta.url), 'utf8')
|
|
12
|
+
const marker = ' function Panel('
|
|
13
|
+
assert.equal(source.split(marker).length, 2)
|
|
14
|
+
const exposed = 'api, confirmReviewed, runReviewed, progressPage, progressStages, stageLabel, progressStatus, progressScope, checkedProgress, validRestore, restoreDestination, receiptSummary, matchingUndo, DICT'
|
|
15
|
+
const program = new vm.Script(source.replace(marker, ` globalThis.subject = { ${exposed} }\n${marker}`), { filename: 'client.js' })
|
|
16
|
+
function client(replies = [], modern = true) {
|
|
17
|
+
const calls = [], queue = [...replies]
|
|
18
|
+
const sandbox = { TextDecoder, Response, ReadableStream: modern ? ReadableStream : undefined,
|
|
19
|
+
window: { __ModuleLoader__: { load: m => m.factory(key => { assert.equal(key, 'react'); return Object.freeze({}) }) } },
|
|
20
|
+
async fetch(url, init) {
|
|
21
|
+
calls.push({ url, method: init.method, headers: new Headers(init.headers), body: init.body && JSON.parse(init.body),
|
|
22
|
+
credentials: init.credentials, redirect: init.redirect, cache: init.cache, signal: init.signal })
|
|
23
|
+
assert.ok(queue.length, 'unexpected extra network call')
|
|
24
|
+
const reply = queue.shift()
|
|
25
|
+
return typeof reply === 'function' ? reply() : reply
|
|
26
|
+
},
|
|
27
|
+
}
|
|
28
|
+
program.runInNewContext(sandbox, { timeout: 500 })
|
|
29
|
+
return { f: sandbox.subject, calls }
|
|
30
|
+
}
|
|
31
|
+
async function scenario(name, run) {
|
|
32
|
+
try { await run(); check(name, true) } catch (error) { check(name, false, error.stack) }
|
|
33
|
+
}
|
|
34
|
+
const clone = x => JSON.parse(JSON.stringify(x)) // strip only VM realm prototypes
|
|
35
|
+
const signal = new AbortController().signal
|
|
36
|
+
const API = '/dsh-profile-gist-sync-plus/api'
|
|
37
|
+
const streamType = 'application/x-ndjson'
|
|
38
|
+
const byMode = { standard: '/sync/install', config: '/config/restore', local: '/restore' }
|
|
39
|
+
const json = (value, status = 200) => new Response(JSON.stringify(value), { status, headers: { 'content-type': 'application/json' } })
|
|
40
|
+
const record = (stage, extra) => ({ type: 'progress', stage, ...extra })
|
|
41
|
+
const final = result => ({ type: 'result', result })
|
|
42
|
+
const buf = value => new TextEncoder().encode(value)
|
|
43
|
+
const lines = (...rows) => rows.map(x => JSON.stringify(x)).join('\r\n') + '\n'
|
|
44
|
+
const response = body => new Response(body, { headers: { 'content-type': `${streamType}; charset=utf-8` } })
|
|
45
|
+
function chunks(...parts) {
|
|
46
|
+
return response(new ReadableStream({ pull(controller) {
|
|
47
|
+
if (!parts.length) return controller.close()
|
|
48
|
+
const next = parts.shift()
|
|
49
|
+
if (next instanceof Error) controller.error(next)
|
|
50
|
+
else controller.enqueue(typeof next === 'string' ? buf(next) : next)
|
|
51
|
+
} }))
|
|
52
|
+
}
|
|
53
|
+
const pkg = (name, resolvable = true) => ({ name, resolvable, spec: resolvable ? '1.0.0' : 'workspace:*', installSpec: resolvable ? `${name}@1.0.0` : null })
|
|
54
|
+
const first = pkg('@fixture/notes'), second = pkg('fixture-reader'), skipped = pkg('fixture-unresolved', false)
|
|
55
|
+
function plan(mode, missing = [first, second], write = true) {
|
|
56
|
+
return { mode, planId: `fixture-${mode}`, preview: { profile: '本机', sourceProfile: '原设备', createdAt: '2026-01-01T00:00:00Z',
|
|
57
|
+
files: [{ path: '中文.json', status: write ? 'add' : 'identical' }], counts: { add: Number(write), overwrite: 0, merge: 0, identical: Number(!write) }, dropped: [] },
|
|
58
|
+
...(mode === 'local' ? { fileName: '备份.json' } : { ref: { id: TEST_GIST_ID } }),
|
|
59
|
+
...(mode === 'standard' ? { plugins: { available: true, installed: [], missing } } : {}) }
|
|
60
|
+
}
|
|
61
|
+
function result(p, outcomes = {}, scripts = {}) {
|
|
62
|
+
const report = { ...p.preview, restored: p.preview.counts.add, undoStamp: p.preview.counts.add ? 'fixture-undo' : null }
|
|
63
|
+
if (p.mode === 'local') return { report }
|
|
64
|
+
const base = { report, ref: p.ref, warnings: [], restart: report.restored > 0 }
|
|
65
|
+
if (p.mode === 'config') return base
|
|
66
|
+
const results = p.plugins.missing.map(entry => ({ name: entry.name, installSpec: entry.installSpec,
|
|
67
|
+
outcome: outcomes[entry.name] ?? (entry.resolvable ? 'installed' : 'skipped'), pendingBuilds: scripts[entry.name] ?? [] }))
|
|
68
|
+
const outcomeCounts = Object.fromEntries(['installed', 'already-present', 'failed', 'skipped'].map(k => [k, results.filter(row => row.outcome === k).length]))
|
|
69
|
+
const present = results.filter(r => ['installed', 'already-present'].includes(r.outcome)).map(r => r.name)
|
|
70
|
+
return { ...base, plugins: { available: true, results, outcomeCounts, installed: present, missing: p.plugins.missing.filter(row => !present.includes(row.name)) },
|
|
71
|
+
complete: !outcomeCounts.failed && !outcomeCounts.skipped && !results.some(r => r.pendingBuilds.length) }
|
|
72
|
+
}
|
|
73
|
+
const install = (processed, current = null, total = 2) => record('install', { files: 1, processed, total, current })
|
|
74
|
+
const p = plan('standard'), ok = result(p)
|
|
75
|
+
|
|
76
|
+
for (const mode of Object.keys(byMode)) await scenario(`${mode}: same reviewed POST, original JSON receipt, authenticated fetch policy`, async () => {
|
|
77
|
+
const review = plan(mode), receipt = result(review)
|
|
78
|
+
for (const modern of [true, false]) {
|
|
79
|
+
const { f, calls } = client([json(receipt)], modern), events = []
|
|
80
|
+
assert.deepEqual(clone(await f.confirmReviewed({ ...review, token: 'must-not-send', backup: {} }, signal, x => events.push(x))), receipt)
|
|
81
|
+
assert.equal(calls.length, 1)
|
|
82
|
+
const [req] = calls
|
|
83
|
+
assert.deepEqual([req.method, req.url, req.headers.get('accept'), req.headers.get('content-type')], ['POST', API + byMode[mode], modern ? streamType : null, 'application/json'])
|
|
84
|
+
assert.deepEqual(req.body, { planId: review.planId, confirm: true })
|
|
85
|
+
assert.deepEqual([req.credentials, req.redirect, req.cache, req.signal], ['same-origin', 'error', 'no-store', signal])
|
|
86
|
+
assert.deepEqual(events, [], 'no simulated stages or counters for JSON')
|
|
87
|
+
assert.equal(f.progressPage(review).step, null)
|
|
88
|
+
}
|
|
89
|
+
})
|
|
90
|
+
await scenario('preview, status, standalone install, upload, undo and legacy imports do not request NDJSON', async () => {
|
|
91
|
+
const routes = [['/status'], ['/config/preview', {}], ['/sync/preview', {}], ['/preview', {}], ['/restore', { confirm: true, backup: {} }], ['/plugins/install', {}], ['/undo', {}], ['/gist/upload', {}]]
|
|
92
|
+
const { f, calls } = client(routes.map(() => json({})))
|
|
93
|
+
for (const [path, body] of routes) await f.api(path, body, signal)
|
|
94
|
+
assert.ok(calls.every(req => !req.headers.has('accept')))
|
|
95
|
+
await assert.rejects(f.confirmReviewed({ ...p, mode: 'plugins' }, signal), { code: 'bad-response' })
|
|
96
|
+
assert.equal(calls.length, routes.length)
|
|
97
|
+
})
|
|
98
|
+
await scenario('split UTF-8, split records, multiple lines/CRLF and a final record at EOF', async () => {
|
|
99
|
+
const events = [record('check'), record('write'), install(0, first.name), install(1, second.name), install(2), record('verify', { files: 1 })]
|
|
100
|
+
const bytes = buf(lines(...events) + '\r\n' + JSON.stringify(final(ok)))
|
|
101
|
+
const inScalar = Buffer.from(bytes).indexOf(Buffer.from('本机')) + 1
|
|
102
|
+
const { f, calls } = client([chunks(bytes.slice(0, 4), bytes.slice(4, inScalar), bytes.slice(inScalar, inScalar + 1), bytes.slice(inScalar + 1))])
|
|
103
|
+
const received = []
|
|
104
|
+
assert.deepEqual(clone(await f.confirmReviewed(p, signal, x => received.push(x))), ok)
|
|
105
|
+
assert.deepEqual(clone(received), events.map(({ type, ...detail }) => detail))
|
|
106
|
+
assert.equal(calls.length, 1)
|
|
107
|
+
})
|
|
108
|
+
await scenario('all approved outcomes do not settle a restore before the final receipt', async () => {
|
|
109
|
+
let controller, observed, settled = false
|
|
110
|
+
const ready = new Promise(resolve => { observed = resolve })
|
|
111
|
+
const { f, calls } = client([response(new ReadableStream({ start(c) { controller = c; c.enqueue(buf(lines(install(2)))) } }))])
|
|
112
|
+
const finished = f.confirmReviewed(p, signal, frame => { assert.equal(frame.processed, 2); observed() }).then(r => { settled = true; return r })
|
|
113
|
+
await Promise.race([ready, finished.then(() => { throw Error('settled without a receipt') })])
|
|
114
|
+
assert.equal(settled, false)
|
|
115
|
+
const partial = result(p, { [second.name]: 'failed' })
|
|
116
|
+
controller.enqueue(buf(lines(final(partial)))); controller.close()
|
|
117
|
+
assert.deepEqual(clone(await finished), partial)
|
|
118
|
+
assert.equal(calls.length, 1)
|
|
119
|
+
})
|
|
120
|
+
await scenario('progress requires post-commit evidence, approved names/counts and monotonic stages', async () => {
|
|
121
|
+
const review = plan('standard', [first, second, skipped]), valid = install(1, second.name)
|
|
122
|
+
const bad = [record('other'), record('check', { files: 1 }), record('write', { files: 1 }), record('check', { source: 'other' }),
|
|
123
|
+
record('write', { mode: 'config' }), install(-1), install(2.1), install(3), install(1, first.name, 3), install(2, second.name), install(1, skipped.name),
|
|
124
|
+
install(1, 'unreviewed'), { ...valid, current: undefined }, { ...valid, files: null }, { ...valid, files: 2 }, record('verify'), record('verify', { files: 1, processed: 1 })]
|
|
125
|
+
const badAfter = [install(0), record('write'), { ...valid, files: 0 }]
|
|
126
|
+
const events = [...bad, valid, ...badAfter, record('verify', { files: 1, processed: 1, total: 2 })]
|
|
127
|
+
const { f } = client([chunks(lines(...events, final(result(review))))]), steps = []
|
|
128
|
+
await f.confirmReviewed(review, signal, x => steps.push(x))
|
|
129
|
+
assert.deepEqual(clone(steps.filter(Boolean)), [{ stage: 'install', files: 1, processed: 1, total: 2, current: second.name }, { stage: 'verify', files: 1, processed: 1, total: 2 }])
|
|
130
|
+
assert.equal(steps.filter(x => x === null).length, bad.length + badAfter.length)
|
|
131
|
+
const { approved } = f.progressScope(review)
|
|
132
|
+
assert.deepEqual([...approved], [first.name, second.name])
|
|
133
|
+
})
|
|
134
|
+
await scenario('no install step for local, configuration-only or zero approved packages; verify without optional counters', async () => {
|
|
135
|
+
for (const mode of Object.keys(byMode)) {
|
|
136
|
+
const review = plan(mode, []), { f } = client([chunks(lines(record('check'), record('write'), install(0, null, 0), record('verify', { files: 1 }), final(result(review))))])
|
|
137
|
+
const page = f.progressPage(review), steps = []
|
|
138
|
+
assert.equal(page.hasPackages, false)
|
|
139
|
+
assert.deepEqual([...f.progressStages(page.hasPackages)], ['check', 'write', 'verify'])
|
|
140
|
+
assert.equal(f.stageLabel('verify', page), mode === 'standard' ? 'verifyLocal' : 'verifyFiles')
|
|
141
|
+
await f.confirmReviewed(review, signal, x => steps.push(x))
|
|
142
|
+
assert.deepEqual(clone(steps), [{ stage: 'check' }, { stage: 'write' }, null, { stage: 'verify', files: 1 }])
|
|
143
|
+
for (const dict of Object.values(f.DICT)) {
|
|
144
|
+
assert.ok(!f.progressStatus({ ...page, step: steps.at(-1) }, k => dict[k]).includes('/'))
|
|
145
|
+
assert.equal(f.progressStatus(page, k => dict[k]), dict.waitingReceipt)
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
})
|
|
149
|
+
await scenario('broken transport, incomplete UTF-8/JSON, missing/duplicate terminal or bad receipt: unverified, no replay', async () => {
|
|
150
|
+
const broken = [() => { throw Error('offline') }, chunks(lines(install(2))), chunks('{"type":"res'), chunks(lines(install(2)), new Uint8Array([0xe4])),
|
|
151
|
+
chunks(lines(install(2)), Error('disconnected')), chunks(lines(final(ok)), Error('unclean end')), chunks(lines(final(ok), final(ok))),
|
|
152
|
+
chunks(lines(final(ok), record('check'))), chunks(lines(final({}))), chunks(lines({ type: 'error', code: 'stale-plan' })), json(null), response(null)]
|
|
153
|
+
for (const reply of broken) {
|
|
154
|
+
const { f, calls } = client([reply]), screens = []
|
|
155
|
+
await f.runReviewed(p, signal, { active: () => true, progress() {}, settle: next => screens.push(next), refresh: () => assert.fail('no speculative refresh') })
|
|
156
|
+
assert.equal(calls.length, 1)
|
|
157
|
+
assert.equal(screens.length, 1)
|
|
158
|
+
const [screen] = screens
|
|
159
|
+
assert.deepEqual([screen.name, screen.receipt.mode, screen.receipt.reviewedMode, screen.receipt.source, screen.receipt.profile], ['receipt', 'unknown', 'standard', TEST_GIST_ID, '本机'])
|
|
160
|
+
assert.equal(screen.receipt.result, undefined); assert.equal(screen.plan, undefined)
|
|
161
|
+
}
|
|
162
|
+
})
|
|
163
|
+
await scenario('JSON and stream terminal errors preserve the reason; a busy/expired plan is never confirmable again', async () => {
|
|
164
|
+
for (const code of ['busy', 'stale-plan', 'other', 'auth']) {
|
|
165
|
+
const payload = { code, error: code === 'auth' ? 'DSH refused this request' : 'fixture error' }
|
|
166
|
+
for (const reply of [json(payload, 409), chunks(lines(record('check'), { type: 'error', ...payload }))]) {
|
|
167
|
+
const { f, calls } = client([reply]), screens = []
|
|
168
|
+
await f.runReviewed(p, signal, { active: () => true, progress() {}, settle: (dest, error) => screens.push([dest, error.code]), refresh: () => assert.fail() })
|
|
169
|
+
const [[dest, reason]] = screens
|
|
170
|
+
assert.equal(reason, code === 'auth' ? 'session-auth' : code)
|
|
171
|
+
assert.equal(dest.name, ['busy', 'stale-plan'].includes(code) ? 'preview' : 'receipt')
|
|
172
|
+
assert.equal(dest.plan, undefined); assert.equal(dest.planId, undefined); assert.equal(calls.length, 1)
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
})
|
|
176
|
+
await scenario('final result must belong to the reviewed source, mode, target, files and package authority', () => {
|
|
177
|
+
const { f } = client(), config = plan('config'), local = plan('local')
|
|
178
|
+
assert.ok(f.validRestore(ok, p) && f.validRestore(result(config), config) && f.validRestore(result(local), local))
|
|
179
|
+
for (const mismatch of [{ ...ok, ref: { id: 'other' } }, { ...ok, mode: 'local' }, { ...ok, report: { ...ok.report, restored: -1 } },
|
|
180
|
+
{ ...ok, report: { ...ok.report, restored: 0 } }, { ...ok, report: { ...ok.report, profile: 'other' } }, { ...ok, report: { ...ok.report, sourceProfile: 'other' } },
|
|
181
|
+
{ ...ok, report: { ...ok.report, files: [{ path: 'other.txt', status: 'add' }] } }, { ...ok, plugins: { available: true } },
|
|
182
|
+
{ ...ok, plugins: { ...ok.plugins, results: ok.plugins.results.map(row => ({ ...row, installSpec: 'wrong-source' })) } }]) assert.equal(f.validRestore(mismatch, p), false)
|
|
183
|
+
assert.ok(!f.validRestore(ok, config) && !f.validRestore(ok, local) && !f.validRestore(result(local), config))
|
|
184
|
+
})
|
|
185
|
+
await scenario('receipt separates change count, missing packages, pending scripts, unknown inventory and restart', () => {
|
|
186
|
+
const { f } = client()
|
|
187
|
+
for (const wrote of [true, false]) {
|
|
188
|
+
const review = plan('standard', [first, second], wrote)
|
|
189
|
+
const receipts = [result(review), result(review, { [second.name]: 'failed' }), result(review, {}, { [first.name]: ['fixture-build'] }),
|
|
190
|
+
{ ...result(review), complete: false, plugins: { available: false, reason: 'plugin-manager-error', results: [] } }]
|
|
191
|
+
for (const [i, r] of receipts.entries()) {
|
|
192
|
+
assert.ok(f.validRestore(r, review))
|
|
193
|
+
const dest = f.restoreDestination(review, r), summary = f.receiptSummary(dest.receipt)
|
|
194
|
+
assert.deepEqual([dest.name, dest.receipt.profile, dest.receipt.restart], ['receipt', '本机', wrote])
|
|
195
|
+
assert.equal(summary.key, (wrote ? ['restoreDone', 'partialTitle', 'buildTitle', 'unknownPluginsTitle'] : ['restoreDone', 'missingOnly', 'buildsOnly', 'unknownOnly'])[i])
|
|
196
|
+
if (i === 2) { assert.deepEqual([...summary.scripts], ['fixture-build']); assert.equal(r.plugins.outcomeCounts.installed, 2) }
|
|
197
|
+
if (i === 3) assert.equal(summary.missing, null)
|
|
198
|
+
}
|
|
199
|
+
assert.equal(f.restoreDestination(review, { ...receipts[0], restart: true }).receipt.restart, true, 'a plugin can require restart even with zero changed files')
|
|
200
|
+
}
|
|
201
|
+
})
|
|
202
|
+
await scenario('first verified problem is visible without echoing manager diagnostics; restart has independent scope', () => {
|
|
203
|
+
const { f } = client(), review = plan('standard', [skipped, first, second]), partial = result(review, { [second.name]: 'failed' })
|
|
204
|
+
partial.plugins.results.find(r => r.outcome === 'failed').message = 'fixture private path and token-like text; not inline copy'
|
|
205
|
+
const summary = r => f.receiptSummary(f.restoreDestination(review, r).receipt)
|
|
206
|
+
assert.deepEqual(clone(summary(partial).problem), { name: second.name, state: 'failed', reason: 'inspectInstall' })
|
|
207
|
+
assert.equal(summary(partial).restartKey, 'restartConfig')
|
|
208
|
+
const unresolved = result(review)
|
|
209
|
+
unresolved.plugins.results.find(r => r.outcome === 'skipped').message = 'workspace-protocol'
|
|
210
|
+
assert.deepEqual(clone(summary(unresolved).problem), { name: skipped.name, state: 'skipped', reason: 'note.workspace-protocol' })
|
|
211
|
+
const unchanged = plan('standard', [first], false), packagesOnly = { ...result(unchanged), restart: true }
|
|
212
|
+
assert.equal(f.receiptSummary(f.restoreDestination(unchanged, packagesOnly).receipt).restartKey, 'restartPackages')
|
|
213
|
+
for (const dict of Object.values(f.DICT)) for (const key of ['inspectInstall', 'restartConfig', 'restartPackages', 'restartLimit']) assert.ok(dict[key])
|
|
214
|
+
})
|
|
215
|
+
await scenario('commit the inline receipt before the read-only status refresh; failure cannot replace it', async () => {
|
|
216
|
+
const { f, calls } = client([json(ok), () => { throw Error('status offline') }]), screens = []
|
|
217
|
+
await assert.rejects(f.runReviewed(p, signal, { active: () => true, progress() {}, settle: next => screens.push(next), refresh: () => f.api('/status', undefined, signal) }), { code: 'network' })
|
|
218
|
+
assert.deepEqual(calls.map(c => [c.method, c.url]), [['POST', API + byMode.standard], ['GET', API + '/status']])
|
|
219
|
+
assert.equal(screens.length, 1); assert.equal(screens[0].name, 'receipt'); assert.deepEqual(clone(screens[0].receipt.result), ok)
|
|
220
|
+
const stamp = ok.report.undoStamp, status = { profile: p.preview.profile, undo: { stamp, files: ok.report.restored } }
|
|
221
|
+
assert.equal(f.matchingUndo(screens[0].receipt, status), stamp)
|
|
222
|
+
for (const other of [{ ...status, profile: 'other' }, { ...status, undo: { ...status.undo, stamp: 'older' } }, { ...status, undo: { ...status.undo, files: 2 } }]) assert.equal(f.matchingUndo(screens[0].receipt, other), null)
|
|
223
|
+
assert.equal(f.matchingUndo(f.restoreDestination(p, null, { code: 'network' }).receipt, status), null)
|
|
224
|
+
})
|
|
225
|
+
process.exit(finish())
|