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/client.js CHANGED
@@ -104,7 +104,51 @@ window.__ModuleLoader__.load({
104
104
  noInstall: '此操作不安装插件。',
105
105
  reviewDone: '预览已就绪,尚未执行恢复。',
106
106
  restoreDone: '恢复完成',
107
- restoreUnverified: '上次恢复的结果尚未核实',
107
+ restoreUnverified: '未收到可核实的恢复回执',
108
+ progressTitle: '恢复到本机',
109
+ inProgress: '恢复中',
110
+ waitingReceipt: '正在恢复,等待结果',
111
+ waitHint: '收到回执后,结果会显示在这里。',
112
+ waitMeter: '正在等待恢复回执,进度未知',
113
+ noRepeat: '请等待恢复回执,不要重复发起恢复。',
114
+ restoreSteps: '本次恢复步骤',
115
+ stageCheck: '核对恢复清单',
116
+ stageWrite: '写入配置文件',
117
+ stageInstall: '安装缺失插件',
118
+ verifyPackages: '核对安装结果',
119
+ verifyFiles: '核对写入结果',
120
+ verifyLocal: '核对本机状态',
121
+ checked: '已核对',
122
+ stageActive: '进行中',
123
+ stagePending: '等待中',
124
+ awaitingCheck: '等待核对',
125
+ checkHint: '正在核对已确认的恢复范围。',
126
+ writeHint: '正在处理配置文件,尚未收到写入回执。',
127
+ verifyHint: '正在核对本机插件清单,以最终回执为准。',
128
+ verifyWriteHint: '正在比对配置写入回执与已确认的文件清单。',
129
+ processed: '已处理 %n / %m 个',
130
+ approvedMeter: '本次批准的插件中已有处理结果的数量',
131
+ meterHint: '只数本次批准且已有结果的插件,失败或跳过也计入;不是安装成功数。',
132
+ currentPackage: '正在安装',
133
+ finished: '已完成',
134
+ needsAttention: '需处理',
135
+ needsCheck: '待核实',
136
+ partialTitle: '配置已恢复,仍缺 %n 个插件',
137
+ buildTitle: '配置已恢复,构建脚本待审',
138
+ unknownPluginsTitle: '配置已恢复,插件结果待核实',
139
+ missingOnly: '仍缺 %n 个插件',
140
+ buildsOnly: '插件构建脚本待审',
141
+ unknownOnly: '插件结果待核实',
142
+ otherAttention: '本次恢复仍有事项需处理',
143
+ inspectLocal: '核对本机状态',
144
+ inspectConfigHint: '请比对本机配置与恢复前的清单。本次更改数尚未核实。',
145
+ inspectPackagesHint: '请同时到「插件」页核对实际安装情况。',
146
+ unknownUndo: '尚未取得与本次恢复匹配的撤销记录。「更多」里的上次恢复记录可能属于更早的操作。',
147
+ readOnlyPreview: '重新预览只会比对当前状态,不会写入配置、安装插件或批准脚本。',
148
+ inspectInstall: '请到「插件」页核对此包的安装状态和来源,再重新预览。',
149
+ restartConfig: '重启 DSH 后,已写入的配置生效。',
150
+ restartPackages: '插件管理器提示重启 DSH,以应用已安装项的更改。',
151
+ restartLimit: '重启不会补装缺失的插件,也不会批准构建脚本。',
108
152
  restoreAttention: '配置已恢复,仍有事项需处理',
109
153
  changedCount: '已更改 %n 个配置文件',
110
154
  installedCount: '已安装 %n 个插件',
@@ -310,7 +354,51 @@ window.__ModuleLoader__.load({
310
354
  noInstall: 'No plugins will be installed.',
311
355
  reviewDone: 'Preview ready. No restore has been performed.',
312
356
  restoreDone: 'Restore complete',
313
- restoreUnverified: 'Last restore result not verified',
357
+ restoreUnverified: 'Restore receipt not verified',
358
+ progressTitle: 'Restore to this machine',
359
+ inProgress: 'Restoring',
360
+ waitingReceipt: 'Waiting for the restore result',
361
+ waitHint: 'The result will appear here when the host sends a receipt.',
362
+ waitMeter: 'Waiting for the restore receipt; progress unknown',
363
+ noRepeat: 'Wait for the receipt. Do not submit the restore again.',
364
+ restoreSteps: 'Steps in this restore',
365
+ stageCheck: 'Check the reviewed plan',
366
+ stageWrite: 'Write configuration files',
367
+ stageInstall: 'Install missing plugins',
368
+ verifyPackages: 'Check installation results',
369
+ verifyFiles: 'Check the file changes',
370
+ verifyLocal: 'Check local state',
371
+ checked: 'Checked',
372
+ stageActive: 'In progress',
373
+ stagePending: 'Waiting',
374
+ awaitingCheck: 'Awaiting verification',
375
+ checkHint: 'Checking the scope you confirmed.',
376
+ writeHint: 'Processing configuration files. The write has not yet been acknowledged.',
377
+ verifyHint: 'Checking the local plugin inventory. The final receipt will show the result.',
378
+ verifyWriteHint: 'Comparing the configuration write receipt with the reviewed file list.',
379
+ processed: 'Processed %n / %m',
380
+ approvedMeter: 'Approved plugins with a processing outcome',
381
+ meterHint: 'Counts only approved plugins with an outcome, including failures and skips. This is not a count of successful installations.',
382
+ currentPackage: 'Installing',
383
+ finished: 'Complete',
384
+ needsAttention: 'Needs attention',
385
+ needsCheck: 'Not verified',
386
+ partialTitle: 'Configuration restored; plugins still missing: %n',
387
+ buildTitle: 'Configuration restored; build scripts await review',
388
+ unknownPluginsTitle: 'Configuration restored; plugin results not verified',
389
+ missingOnly: 'Plugins still missing: %n',
390
+ buildsOnly: 'Plugin build scripts await review',
391
+ unknownOnly: 'Plugin results not verified',
392
+ otherAttention: 'Some items still need attention',
393
+ inspectLocal: 'Check local state',
394
+ inspectConfigHint: 'Compare local configuration with the reviewed file list. The number of changes has not been verified.',
395
+ inspectPackagesHint: 'Also check which packages are actually installed on the Plugins page.',
396
+ unknownUndo: 'No undo record has been matched to this restore. The last record under More may belong to an earlier operation.',
397
+ readOnlyPreview: 'A new preview compares current state. It does not rewrite files, install plugins or approve scripts.',
398
+ inspectInstall: 'Check this package and its install source on the Plugins page, then preview again.',
399
+ restartConfig: 'Restart DSH for the restored configuration to take effect.',
400
+ restartPackages: 'Restart DSH to apply the installed package changes.',
401
+ restartLimit: 'Restarting does not install missing plugins or approve build scripts.',
314
402
  restoreAttention: 'Configuration restored; some items need attention',
315
403
  changedCount: 'Configuration files changed: %n',
316
404
  installedCount: 'Plugins installed: %n',
@@ -519,6 +607,36 @@ window.__ModuleLoader__.load({
519
607
  .dpgsp-facts dd { min-width:0; text-align:end; }
520
608
  .dpgsp-root .dpgsp-link { color:var(--dsw-alias-link,var(--accent)); text-underline-offset:2px; }
521
609
  .dpgsp-copy-feedback { margin-top:8px; padding-top:8px; }
610
+ .dpgsp-restore-head { display:flex; justify-content:space-between; align-items:flex-start; flex-wrap:wrap; gap:6px 12px; }
611
+ .dpgsp-restore-head .dpgsp-mark { border-radius:var(--dsw-radius-md,12px); width:36px; height:36px; }
612
+ .dpgsp-restore-head h2 { font-size:17px; font-weight:600; line-height:24px; }
613
+ .dpgsp-badge { align-self:center; border:.5px solid var(--line); border-radius:99px; padding:0 9px; font-size:12px; }
614
+ .dpgsp-restore-head[data-tone=active] :is(.dpgsp-mark,.dpgsp-badge) { color:var(--accent); }
615
+ .dpgsp-restore-head[data-tone=good] :is(.dpgsp-mark,.dpgsp-badge) { color:var(--good); }
616
+ .dpgsp-restore-head[data-tone=attention] :is(.dpgsp-mark,.dpgsp-badge) { color:var(--warn); }
617
+ .dpgsp-timeline { list-style:none; margin:0; padding-inline:0; }
618
+ .dpgsp-step { display:grid; grid-template-columns:20px minmax(0,1fr); gap:8px; position:relative; }
619
+ .dpgsp-step + .dpgsp-step { margin-top:14px; }
620
+ .dpgsp-step:not(:last-child)::before { content:''; position:absolute; inset-inline-start:9px; top:21px; bottom:-13px; border-inline-start:1px solid var(--line); }
621
+ .dpgsp-step-mark { display:grid; place-items:center; align-self:start; height:20px; color:var(--muted); }
622
+ .dpgsp-step-mark:empty::before { content:''; width:12px; height:12px; border:1px solid currentColor; border-radius:50%; corner-shape:round; }
623
+ .dpgsp-step[data-state=done] .dpgsp-step-mark { color:var(--good); }
624
+ .dpgsp-step[aria-current=step] :is(.dpgsp-step-mark,.dpgsp-step-line) { color:var(--accent); }
625
+ .dpgsp-step[aria-current=step] .dpgsp-step-mark::before { background:currentColor; box-shadow:inset 0 0 0 2px var(--paper); }
626
+ .dpgsp-step-line { display:flex; justify-content:space-between; align-items:baseline; gap:0 8px; flex-wrap:wrap; }
627
+ .dpgsp-step-line > :last-child { font-size:12px; }
628
+ .dpgsp-step[data-state=pending] .dpgsp-step-line { color:var(--muted); }
629
+ .dpgsp-meterbox { display:grid; gap:5px; margin-top:6px; border:.5px solid var(--line); border-radius:var(--dsw-radius-sm,8px); padding:8px 12px; background:var(--dsw-alias-bg-layer-1); }
630
+ .dpgsp-meterbox strong { color:var(--accent); font-variant-numeric:tabular-nums; }
631
+ .dpgsp-body > .dpgsp-issue { padding:9px 12px; border:.5px solid var(--line); border-radius:var(--dsw-radius-sm,8px); background:var(--dsw-alias-state-warn-tertiary,var(--hover)); }
632
+ .dpgsp-issue .dpgsp-icon { color:var(--warn); }
633
+ .dpgsp-meter { height:7px; border-radius:99px; background:var(--edge); overflow:hidden; }
634
+ .dpgsp-fill { display:block; height:100%; border-radius:inherit; background:var(--accent); }
635
+ /* Waiting stripes do not encode a duration, stage, or percentage. */
636
+ .dpgsp-meter.dpgsp-indeterminate { background:repeating-linear-gradient(110deg,var(--edge) 0 8px,var(--hover) 8px 16px); background-size:34px 100%; animation:dpgsp-wait 2.6s linear infinite; }
637
+ @keyframes dpgsp-wait { to { background-position:34px 0; } }
638
+ @media (prefers-reduced-motion:reduce) { .dpgsp-meter.dpgsp-indeterminate { animation:none; } }
639
+ @media (forced-colors:active) { .dpgsp-meter { outline:1px solid; } .dpgsp-fill { border-block-start:7px solid; } }
522
640
  .dpgsp-sr { position:absolute; width:1px; height:1px; padding:0; margin:-1px; overflow:hidden; clip-path:inset(50%); white-space:nowrap; border:0; }
523
641
  @container (max-width:470px) {
524
642
  .dpgsp-homefoot { grid-template-columns:auto minmax(0,1fr); }
@@ -582,21 +700,81 @@ window.__ModuleLoader__.load({
582
700
  return Object.hasOwn(DICT.en, key) ? t(key) : typeof code === 'string' ? code : ''
583
701
  }
584
702
  const errorText = (t, error) => Object.hasOwn(DICT.en, `err.${error?.code}`) ? t(`err.${error.code}`) : t('err.other')
585
- async function api(path, body, signal) {
586
- let response
703
+ const object = value => !!value && typeof value === 'object' && !Array.isArray(value)
704
+ const NDJSON = 'application/x-ndjson'
705
+ const RESTORE_ROUTES = { standard: '/sync/install', config: '/config/restore', local: '/restore' }
706
+ async function request(path, body, signal, accept) {
587
707
  try {
588
- response = await fetch(`${API}${path}`, { method: body === undefined ? 'GET' : 'POST', credentials: 'same-origin', redirect: 'error', cache: 'no-store', signal,
589
- ...(body === undefined ? {} : { headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }) })
708
+ return await fetch(`${API}${path}`, { method: body === undefined ? 'GET' : 'POST', credentials: 'same-origin', redirect: 'error', cache: 'no-store', signal,
709
+ ...(body === undefined ? {} : { headers: { 'content-type': 'application/json', ...(accept ? { Accept: accept } : {}) }, body: JSON.stringify(body) }) })
590
710
  } catch (error) { throw signal?.aborted ? error : fail('network') }
711
+ }
712
+ function responseError(data) {
713
+ // An origin/login rejection from DSH is not a reason to ask for a GitHub token.
714
+ const localDenial = data?.code === 'auth' && /^(?:DSH refused|refused: the Host)/i.test(data?.error ?? '')
715
+ return fail(localDenial ? 'session-auth' : txt(data?.code) ? data.code : 'other')
716
+ }
717
+ async function readJson(response) {
591
718
  const data = await response.json().catch(() => null)
592
- if (!response.ok) {
593
- // An origin/login rejection from DSH is not a reason to ask for a GitHub token.
594
- const localDenial = data?.code === 'auth' && /^(?:DSH refused|refused: the Host)/i.test(data?.error ?? '')
595
- throw fail(localDenial ? 'session-auth' : data?.code ?? 'other')
596
- }
597
- if (!data || typeof data !== 'object' || Array.isArray(data)) throw fail('bad-response')
719
+ if (!response.ok) throw responseError(data)
720
+ if (!object(data)) throw fail('bad-response')
598
721
  return data
599
722
  }
723
+ async function api(path, body, signal) { return readJson(await request(path, body, signal)) }
724
+
725
+ // Only reviewed confirmations negotiate streaming, on the original request.
726
+ // In particular there is no capability probe, replacement POST, or cloud read.
727
+ async function confirmReviewed(plan, signal, onProgress = () => {}) {
728
+ if (!Object.hasOwn(RESTORE_ROUTES, plan?.mode) || !txt(plan.planId)) throw fail('bad-response')
729
+ const streaming = typeof TextDecoder === 'function' && typeof ReadableStream === 'function'
730
+ && typeof ReadableStream.prototype.getReader === 'function' && typeof Response === 'function' && 'body' in Response.prototype
731
+ const response = await request(RESTORE_ROUTES[plan.mode], { planId: plan.planId, confirm: true }, signal, streaming ? NDJSON : null)
732
+ const type = response.headers?.get('content-type')?.split(';')[0].trim().toLowerCase()
733
+ let result
734
+ if (type === NDJSON) {
735
+ if (!streaming || typeof response.body?.getReader !== 'function') throw fail('bad-response')
736
+ const scope = progressScope(plan)
737
+ let last = null
738
+ result = await readFrames(response.body, frame => {
739
+ const next = checkedProgress(scope, frame, last)
740
+ if (next) last = next // keep the monotonic floor even across unusable frames
741
+ onProgress(response.ok ? next : null)
742
+ })
743
+ if (!response.ok) throw fail('bad-response')
744
+ } else result = await readJson(response) // Older hosts ignore Accept. Never submit again.
745
+ if (!validRestore(result, plan)) throw fail('bad-response')
746
+ return result
747
+ }
748
+ async function readFrames(body, progress) {
749
+ const reader = body.getReader()
750
+ const decoder = new TextDecoder('utf-8', { fatal: true })
751
+ let buffer = '', terminal = null
752
+ // Bound a single unterminated line, not the number of packages or chunks.
753
+ const maxLine = 8 * 1024 * 1024
754
+ function line(text) {
755
+ if (text.length > maxLine) throw fail('bad-response')
756
+ if (!text.trim()) return
757
+ if (terminal) throw fail('bad-response') // no ambiguous second outcome or trailing event
758
+ const frame = JSON.parse(text)
759
+ if (frame?.type === 'progress') progress(frame)
760
+ else if ((frame?.type === 'result' && object(frame.result)) || (frame?.type === 'error' && txt(frame.code) && txt(frame.error))) terminal = frame
761
+ else throw fail('bad-response')
762
+ }
763
+ try {
764
+ for (;;) {
765
+ const { done, value } = await reader.read()
766
+ buffer += done ? decoder.decode() : decoder.decode(value, { stream: true })
767
+ const lines = buffer.split('\n')
768
+ buffer = lines.pop()
769
+ for (const text of lines) line(text)
770
+ if (buffer.length > maxLine) throw fail('bad-response')
771
+ if (done) { line(buffer); break } // also accept an intact last record at EOF
772
+ }
773
+ } catch { throw fail('bad-response') } finally { reader.releaseLock() }
774
+ if (!terminal) throw fail('bad-response')
775
+ if (terminal.type === 'error') throw responseError(terminal)
776
+ return terminal.result
777
+ }
600
778
  function validStatus(s) {
601
779
  return txt(s?.profile) && number(s.counts?.files) && number(s.counts.bytes)
602
780
  && Array.isArray(s.files) && s.files.every(rowFile) && Array.isArray(s.excluded) && s.excluded.every(excludedFile)
@@ -618,10 +796,11 @@ window.__ModuleLoader__.load({
618
796
  const verifiedInventory = p => p?.available === true && names(p.installed) && Array.isArray(p.missing) && p.missing.every(entry =>
619
797
  txt(entry?.name) && typeof entry.resolvable === 'boolean' && (entry.spec == null || typeof entry.spec === 'string')
620
798
  && (entry.resolvable ? txt(entry.installSpec) : entry.installSpec === null))
799
+ && new Set([...p.installed, ...p.missing.map(row => row.name)]).size === p.installed.length + p.missing.length
621
800
  const installable = p => verifiedInventory(p) ? p.missing.filter(row => row.resolvable) : []
622
801
  const inventoryShape = p => p?.available === false || verifiedInventory(p)
623
802
  function validCloudPlan(p, mode, id) {
624
- if (!bareId(p?.ref?.id) || p.ref.id !== id || !filePlan(p.preview)) return false
803
+ if (!['standard', 'config'].includes(mode) || !bareId(p?.ref?.id) || p.ref.id !== id || !filePlan(p.preview) || (p.mode !== undefined && p.mode !== mode)) return false
625
804
  if (mode === 'config') return txt(p.planId) && p.plugins == null
626
805
  return p.plugins?.available === false ? p.planId === null : verifiedInventory(p.plugins) && txt(p.planId)
627
806
  }
@@ -629,10 +808,82 @@ window.__ModuleLoader__.load({
629
808
  return !!p && (p.mode !== 'standard' || verifiedInventory(p.plugins)) && (changes(p.preview) > 0 || installable(p.plugins).length > 0)
630
809
  }
631
810
  function validRestore(r, plan) {
632
- if (!filePlan(r?.report) || !number(r.report.restored)) return false
633
- if (plan.mode === 'local') return true
634
- if (r.ref?.id !== plan.ref.id || typeof r.restart !== 'boolean' || !names(r.warnings ?? [])) return false
635
- return plan.mode === 'config' || (typeof r.complete === 'boolean' && typeof r.plugins?.available === 'boolean')
811
+ const p = plan?.preview, report = r?.report
812
+ if (!Object.hasOwn(RESTORE_ROUTES, plan?.mode) || !filePlan(p) || !filePlan(report) || !number(report.restored)
813
+ || report.restored !== changes(report) || report.profile !== p.profile || report.root !== p.root || report.sourceProfile !== p.sourceProfile
814
+ || report.createdAt !== p.createdAt || report.files.length !== p.files.length || !names(r.warnings ?? []) || (r.mode !== undefined && r.mode !== plan.mode)) return false
815
+ if (!report.files.every((row, i) => row.path === p.files[i].path && row.status === p.files[i].status)) return false
816
+ if (plan.mode === 'local') return r.ref == null && r.plugins == null && r.complete == null
817
+ if (!bareId(plan.ref?.id) || r.ref?.id !== plan.ref.id || typeof r.restart !== 'boolean') return false
818
+ if (plan.mode === 'config') return r.plugins == null && r.complete == null
819
+ if (typeof r.complete !== 'boolean') return false
820
+ if (r.plugins?.available === false) return !r.complete
821
+ if (!verifiedReport(r.plugins) || !verifiedInventory(plan.plugins)) return false
822
+ const approved = new Map(installable(plan.plugins).map(row => [row.name, row.installSpec]))
823
+ const declared = new Set([...plan.plugins.installed, ...plan.plugins.missing.map(row => row.name)])
824
+ const observed = [...r.plugins.installed, ...r.plugins.missing.map(row => row.name)]
825
+ return observed.length === declared.size && observed.every(name => declared.has(name))
826
+ && r.plugins.results.every(row => declared.has(row.name) && (row.outcome === 'skipped' ||
827
+ (approved.has(row.name) && (row.installSpec === undefined || row.installSpec === approved.get(row.name)))))
828
+ && (!r.complete || !incomplete(r.plugins))
829
+ }
830
+
831
+ // The stream is scoped by the selected POST and the reviewed plan, not by
832
+ // identifiers supplied by an event. No progress frame is a restore receipt.
833
+ function progressScope(plan) {
834
+ const approved = new Set(installable(plan.plugins).map(row => row.name))
835
+ return { mode: plan.mode, approved, fileLimit: changes(plan.preview) }
836
+ }
837
+ const STAGES = ['check', 'write', 'install', 'verify']
838
+ function checkedProgress(scope, frame, last) {
839
+ if (!scope || !Object.hasOwn(RESTORE_ROUTES, scope.mode) || frame?.type !== 'progress') return null
840
+ const { stage, files, processed, total, current } = frame
841
+ const rank = STAGES.indexOf(stage)
842
+ if (rank < 0 || (last && rank < STAGES.indexOf(last.stage))) return null
843
+ const late = stage === 'install' || stage === 'verify'
844
+ const allowed = ['type', 'stage', ...(late ? ['files', 'processed', 'total'] : []), ...(stage === 'install' ? ['current'] : [])]
845
+ if (Object.keys(frame).some(key => !allowed.includes(key))) return null
846
+ if (!late) return { stage }
847
+ if (!number(files) || files > scope.fileLimit || (last?.files !== undefined && files !== last.files)) return null
848
+ if (stage === 'install' || processed !== undefined || total !== undefined) {
849
+ if (scope.mode !== 'standard' || !number(total) || total !== scope.approved.size || !number(processed) || processed > total || processed < (last?.processed ?? 0)) return null
850
+ if (stage === 'install') {
851
+ if (!total || (current !== null && (!scope.approved.has(current) || processed === total))) return null
852
+ return { stage, files, processed, total, current }
853
+ }
854
+ if (total > 0) return { stage, files, processed, total }
855
+ }
856
+ return { stage, files }
857
+ }
858
+ function restoreDestination(plan, result, error) {
859
+ const { mode, fileName } = plan, id = plan.ref?.id, profile = plan.preview.profile
860
+ // Even a busy/expired plan loses its local confirmation. The only path
861
+ // back to a write is a fresh, user-requested read-only preview.
862
+ if (error && ['stale-plan', 'busy'].includes(error.code)) return { name: 'preview', mode, id, fileName }
863
+ const receipt = error ? { mode: 'unknown', reviewedMode: mode, profile, source: id ?? fileName, error }
864
+ : { mode, profile, result, fileName, restart: mode === 'local' ? result.report.restored > 0 : result.restart }
865
+ return { name: 'receipt', mode, receipt }
866
+ }
867
+ function progressPage(plan) {
868
+ return { name: 'progress', mode: plan.mode, profile: plan.preview.profile,
869
+ hasPackages: plan.mode === 'standard' && installable(plan.plugins).length > 0, step: null }
870
+ }
871
+ async function runReviewed(plan, signal, { active, progress, settle, refresh }) {
872
+ let result
873
+ try { result = await confirmReviewed(plan, signal, step => { if (active()) progress(step) }) }
874
+ catch (error) {
875
+ if (active()) settle(restoreDestination(plan, null, error), error)
876
+ return
877
+ }
878
+ if (!active()) return
879
+ settle(restoreDestination(plan, result))
880
+ // Outside the confirmation catch: even a broken /status cannot turn a
881
+ // verified write into a lost receipt or send another confirmation.
882
+ await refresh()
883
+ }
884
+ function matchingUndo(receipt, status) {
885
+ const report = receipt?.result?.report, stamp = report?.undoStamp
886
+ return txt(stamp) && receipt.profile === status?.profile && stamp === status.undo?.stamp && report.restored === status.undo.files ? stamp : null
636
887
  }
637
888
  function verifiedReport(p) {
638
889
  return verifiedInventory(p) && Array.isArray(p.results) && p.results.every(row => txt(row?.name) && Object.hasOwn(OUTCOMES, row.outcome) && names(row.pendingBuilds))
@@ -739,36 +990,90 @@ window.__ModuleLoader__.load({
739
990
  txt(r.message) ? hint(r.outcome === 'skipped' ? codeText(t, 'note', r.message) : r.message) : null)]) : null,
740
991
  remaining.length ? h('p', null, `${t('stillMissing')}: `, remaining.map(r => r.name).join(', ')) : null)
741
992
  }
742
- function RestoreReceipt({ receipt, t, undoButton, onRepreview, locked }) {
743
- if (!receipt) return null
744
- const resultTitle = (key, glyph) => h('h3', { tabIndex: -1, 'data-focus': 'restore-receipt', className: 'dpgsp-line' }, icon(glyph), t(key))
745
- if (receipt.mode === 'unknown') return frame(h(React.Fragment, null, resultTitle('restoreUnverified', 'info'),
746
- facts([[t('source'), receipt.local ? isolated(receipt.source) : t('gistSource')]]), note(t('uncertain')),
747
- !receipt.local ? details(t('resultDetails'), facts([[t('source'), mono(receipt.source)]])) : null), undoButton ? footer([undoButton]) : null)
748
- if (receipt.mode === 'undo') return frame(h(React.Fragment, null, resultTitle('undoDone', 'check'),
993
+ function restoreHeader(text, badge, tone, glyph, profile, t, focus) {
994
+ return h('header', { className: 'dpgsp-restore-head', 'data-tone': tone },
995
+ h('div', { className: 'dpgsp-identity' }, h('span', { className: 'dpgsp-mark' }, icon(glyph, 20)),
996
+ h('div', null, h('h2', { tabIndex: -1, 'data-focus': focus }, text), hint(h(React.Fragment, null, t('localProfile'), ' · ', isolated(profile))))),
997
+ h('span', { className: 'dpgsp-badge' }, t(badge)))
998
+ }
999
+ const tally = (t, step) => countText(t, 'processed', step.processed).replace('%m', String(step.total))
1000
+ const progressStages = hasPackages => hasPackages ? STAGES : ['check', 'write', 'verify']
1001
+ const stageLabel = (stage, page) => ({ check: 'stageCheck', write: 'stageWrite', install: 'stageInstall',
1002
+ verify: page.mode !== 'standard' ? 'verifyFiles' : page.hasPackages ? 'verifyPackages' : 'verifyLocal' })[stage]
1003
+ function progressStatus(page, t) {
1004
+ const s = page.step
1005
+ if (!s) return t('waitingReceipt')
1006
+ return [t(stageLabel(s.stage, page)), s.total > 0 ? tally(t, s) : null,
1007
+ s.current ? `${t('currentPackage')} ${s.current}` : null].filter(Boolean).join(' · ')
1008
+ }
1009
+ function RestoreProgress({ page, t }) {
1010
+ const step = page.step, stages = progressStages(page.hasPackages)
1011
+ const header = restoreHeader(t('progressTitle'), 'inProgress', 'active', 'sync', page.profile, t, 'title')
1012
+ const waiting = h('div', { className: 'dpgsp-group' }, h('strong', null, t('waitingReceipt')),
1013
+ h('div', { className: 'dpgsp-meter dpgsp-indeterminate', role: 'progressbar', 'aria-label': t('waitMeter') }), hint(t('waitHint')))
1014
+ const list = step && h('ol', { className: 'dpgsp-timeline', 'aria-label': t('restoreSteps') }, stages.map((id, i) => {
1015
+ const active = id === step.stage, done = i < stages.indexOf(step.stage)
1016
+ const state = !done ? t(active ? 'stageActive' : 'stagePending') : id === 'check' ? t('checked')
1017
+ : id === 'write' ? countText(t, 'changedCount', step.files) : step.total > 0 ? tally(t, step) : t('awaitingCheck')
1018
+ const extra = !active ? null : id === 'install' ? h('div', { className: 'dpgsp-meterbox' },
1019
+ h('strong', null, tally(t, step)), h('div', { className: 'dpgsp-meter', role: 'progressbar', 'aria-label': t('approvedMeter'),
1020
+ 'aria-valuemin': 0, 'aria-valuemax': step.total, 'aria-valuenow': step.processed, 'aria-valuetext': `${tally(t, step)}. ${t('meterHint')}` },
1021
+ h('span', { className: 'dpgsp-fill', style: { width: `${100 * step.processed / step.total}%` } })),
1022
+ step.current ? h('p', null, t('currentPackage'), ' ', mono(step.current)) : null, hint(t('meterHint')))
1023
+ : hint(t(id === 'check' ? 'checkHint' : id === 'write' ? 'writeHint' : page.mode === 'standard' ? 'verifyHint' : 'verifyWriteHint'))
1024
+ return h('li', { key: id, className: 'dpgsp-step', 'data-state': active ? 'active' : done ? 'done' : 'pending', 'aria-current': active ? 'step' : undefined },
1025
+ h('span', { className: 'dpgsp-step-mark', 'aria-hidden': true }, done ? icon('check', 17) : null),
1026
+ h('div', null, h('div', { className: 'dpgsp-step-line' }, h('strong', null, t(stageLabel(id, page))), h('span', null, state)), extra))
1027
+ }))
1028
+ return frame(h(React.Fragment, null, header, list || waiting), footer([], t('noRepeat')), t('progressTitle'))
1029
+ }
1030
+
1031
+ function receiptSummary(receipt) {
1032
+ const { result: r, mode } = receipt
1033
+ const combined = mode === 'standard', verified = combined && verifiedReport(r.plugins)
1034
+ const scripts = combined ? pendingBuilds(r.plugins) : []
1035
+ const missing = verified ? r.plugins.missing.length : null
1036
+ const wrote = r.report.restored > 0, unknown = combined && !verified
1037
+ const key = unknown ? (wrote ? 'unknownPluginsTitle' : 'unknownOnly') : missing ? (wrote ? 'partialTitle' : 'missingOnly')
1038
+ : scripts.length ? (wrote ? 'buildTitle' : 'buildsOnly') : r.warnings?.length || (combined && (!r.complete || incomplete(r.plugins)))
1039
+ ? (wrote ? 'restoreAttention' : 'otherAttention') : 'restoreDone'
1040
+ // Surface one verifiable problem before the disclosure. Do not guess why
1041
+ // a package is missing or interpolate arbitrary installer output here.
1042
+ const row = verified && (r.plugins.results.find(x => x.outcome === 'failed') ?? r.plugins.results.find(x => x.outcome === 'skipped'))
1043
+ const problem = row ? { name: row.name, state: OUTCOMES[row.outcome],
1044
+ reason: row.outcome === 'skipped' && txt(row.message) && Object.hasOwn(DICT.en, `note.${row.message}`) ? `note.${row.message}` : 'inspectInstall' }
1045
+ : missing ? { name: r.plugins.missing[0].name, state: 'stillMissing', reason: 'inspectInstall' } : null
1046
+ const restartKey = !receipt.restart ? null : wrote ? 'restartConfig' : 'restartPackages'
1047
+ return { key, verified, unknown, missing, scripts, problem, restartKey, attention: key !== 'restoreDone' }
1048
+ }
1049
+ function RestoreReceipt({ receipt, t, undoButton, repreviewButton, backButton, alerts }) {
1050
+ const head = (text, badge, tone, glyph) => restoreHeader(text, badge, tone, glyph, receipt.profile, t, 'restore-receipt')
1051
+ if (receipt.mode === 'undo') return frame(h(React.Fragment, null, head(t('undoDone'), 'finished', 'good', 'check'),
749
1052
  h('p', null, countText(t, 'reverted', receipt.reverted), ' ', t('undoLimit'))))
1053
+ if (receipt.mode === 'unknown') return frame(h(React.Fragment, null,
1054
+ head(t('restoreUnverified'), 'needsCheck', 'attention', 'info'), h('p', null, t('uncertain')),
1055
+ facts([[t('source'), isolated(receipt.source)]]), hint(errorText(t, receipt.error)),
1056
+ details(t('inspectLocal'), hint(t('inspectConfigHint')), receipt.reviewedMode === 'standard' ? hint(t('inspectPackagesHint')) : null),
1057
+ details(t('undoWhen'), hint(t('unknownUndo')), hint(t('undoScope')), hint(t('undoLimit'))), alerts),
1058
+ footer([backButton, repreviewButton], t('readOnlyPreview')), t('restoreUnverified'))
750
1059
  const { result: r, mode } = receipt
751
- const attention = !!r.warnings?.length || (mode === 'standard' && (r.complete !== true || incomplete(r.plugins)))
752
- const scripts = pendingBuilds(r.plugins)
753
- const missing = verifiedInventory(r.plugins) ? r.plugins.missing : null
754
- const retry = mode === 'standard' && missing?.length > 0
755
- const results = Array.isArray(r.plugins?.results) ? r.plugins.results : []
756
- const failed = results.filter(item => item?.outcome === 'failed').length
757
- const skipped = results.filter(item => item?.outcome === 'skipped').length
1060
+ const { key, verified, unknown, missing, scripts, problem, restartKey, attention } = receiptSummary(receipt)
1061
+ const text = missing ? countText(t, key, missing) : t(key)
1062
+ const counts = verified ? r.plugins.outcomeCounts : null
758
1063
  return frame(h(React.Fragment, null,
759
- h('header', null, resultTitle(attention ? 'restoreAttention' : 'restoreDone', attention ? 'info' : 'check'),
760
- hint([countText(t, 'changedCount', changes(r.report)), verifiedReport(r.plugins) ? countText(t, 'installedCount', r.plugins.outcomeCounts.installed) : null,
761
- receipt.restart ? t('restart') : null].filter(Boolean).join(' · '))),
762
- facts([[t('source'), mode === 'local' ? isolated(receipt.fileName) : t('gistSource')]]),
763
- scripts.length ? note(`${t('pendingBuilds')}: ${scripts.join(', ')}. ${t('buildHint')}`, 'shield') : null,
1064
+ head(text, unknown ? 'needsCheck' : attention ? 'needsAttention' : 'finished', attention ? 'attention' : 'good', attention ? 'info' : 'check'),
1065
+ facts([[t('configFiles'), r.report.restored ? countText(t, 'changedCount', r.report.restored) : t('filesSame')], counts && [t('pluginResults'),
1066
+ [countText(t, 'installedCount', counts.installed), ...['already-present', 'failed', 'skipped'].filter(k => counts[k]).map(k => `${t(OUTCOMES[k])} ${counts[k]}`)].join(' · ')]]),
1067
+ problem ? h('div', { className: 'dpgsp-group dpgsp-issue' }, h('strong', { className: 'dpgsp-line' }, icon('pkg', 16), mono(problem.name), ' · ', t(problem.state)), hint(t(problem.reason))) : null,
1068
+ scripts.length ? box('warning', h('strong', null, t('pendingBuilds')), list(scripts, name => [mono(name)]), hint(t('buildHint'))) : null,
1069
+ mode === 'standard' && !verified ? note(t('pluginUnknown')) : null,
764
1070
  r.warnings?.length ? box('warning', h('strong', null, t('warnings')), list(r.warnings, w => [w])) : null,
765
- mode === 'standard' && !verifiedReport(r.plugins) ? hint(t('pluginUnknown')) : null,
766
- failed || skipped || missing?.length ? h('p', null, [failed ? `${t('failed')} ${failed}` : null, skipped ? `${t('skipped')} ${skipped}` : null, missing?.length ? `${t('stillMissing')} ${missing.length}` : null].filter(Boolean).join(' · ')) : null,
767
- retry ? hint(t('retryHint')) : null,
1071
+ restartKey ? note([t(restartKey), mode === 'standard' && attention ? t('restartLimit') : null].filter(Boolean).join(' ')) : null,
768
1072
  details(t('resultDetails'), h('div', { className: 'dpgsp-stack' },
769
- mode === 'local' ? null : facts([[t('source'), mono(r.ref.id)]]), h(FileChanges, { p: r.report, t }),
770
- r.plugins ? heading(t('pluginResults'), h(PluginReport, { p: r.plugins, t })) : null))),
771
- footer([undoButton, retry ? btn('preview-receipt-source', t('previewReceiptSource'), onRepreview, { disabled: locked }) : null], t('undoLimit')))
1073
+ facts([[t('source'), mode === 'local' ? isolated(receipt.fileName) : mono(r.ref.id)]]), h(FileChanges, { p: r.report, t }),
1074
+ mode === 'standard' && verified ? heading(t('pluginResults'), h(PluginReport, { p: r.plugins, t })) : null,
1075
+ hint(t('undoLimit')))), alerts),
1076
+ footer([backButton, undoButton, repreviewButton], repreviewButton ? t('readOnlyPreview') : null), text)
772
1077
  }
773
1078
  function ProfileStatus({ profile, stateKey, url, t }) {
774
1079
  const [state, setState] = React.useState('idle')
@@ -844,7 +1149,7 @@ window.__ModuleLoader__.load({
844
1149
  setBusy(label)
845
1150
  setIssue(null)
846
1151
  setAnnouncement('')
847
- try { await task(call, active) }
1152
+ try { await task(call, active, job.controller.signal) }
848
1153
  catch (error) {
849
1154
  if (active()) {
850
1155
  if (onError) onError(error)
@@ -950,7 +1255,7 @@ window.__ModuleLoader__.load({
950
1255
  move({ name: 'preview', mode, id })
951
1256
  return run('previewBusy', false, async call => {
952
1257
  const data = await call(mode === 'config' ? '/config/preview' : '/sync/preview', { id, ...token })
953
- if (!validCloudPlan(data, mode, id)) throw fail('bad-response')
1258
+ if (!validCloudPlan(data, mode, id) || data.preview.profile !== status.profile) throw fail('bad-response')
954
1259
  displayPlan({ ...data, mode })
955
1260
  }, error => setIssue({ error, repair: repairable(error) }))
956
1261
  }
@@ -969,19 +1274,16 @@ window.__ModuleLoader__.load({
969
1274
  const p = selected.current
970
1275
  if (locked || flight.current || !p || p !== page.plan || !actionable(p)) return
971
1276
  selected.current = null // one-shot; even a lost response needs a new preview
972
- move({ name: 'preview', mode: p.mode, id: p.ref?.id, fileName: p.fileName })
973
- return run('applyBusy', true, async (call, active) => {
974
- const route = p.mode === 'local' ? '/restore' : p.mode === 'config' ? '/config/restore' : '/sync/install'
975
- const r = await call(route, { planId: p.planId, confirm: true })
976
- if (!validRestore(r, p)) throw fail('bad-response')
977
- setRestoreReceipt({ mode: p.mode, result: r, fileName: p.fileName, restart: p.mode === 'local' ? changes(r.report) > 0 : r.restart })
978
- move({ name: 'home' }, 'restore-receipt')
979
- await afterWrite(call, active)
980
- }, error => {
981
- const uncertain = consumedPlanError(error)
982
- if (uncertain) setRestoreReceipt({ mode: 'unknown', local: p.mode === 'local', source: p.ref?.id ?? p.fileName })
983
- setIssue({ error, uncertain })
984
- })
1277
+ move(progressPage(p))
1278
+ return run('applyBusy', true, (call, active, signal) => runReviewed(p, signal, {
1279
+ active, progress: step => setPage(old => old.name === 'progress' ? { ...old, step } : old),
1280
+ settle(next, error) {
1281
+ if (next.receipt) setRestoreReceipt(next.receipt)
1282
+ move(next, next.receipt ? 'restore-receipt' : 'title')
1283
+ if (!next.receipt) setIssue({ error })
1284
+ },
1285
+ refresh: () => afterWrite(call, active), // local GET only
1286
+ }))
985
1287
  }
986
1288
  function chooseFile(event) {
987
1289
  const file = event.currentTarget.files?.[0]
@@ -997,7 +1299,7 @@ window.__ModuleLoader__.load({
997
1299
  let backup
998
1300
  try { backup = JSON.parse(text) } catch { throw fail('invalidJson') }
999
1301
  const r = await call('/preview', { backup, reviewed: true })
1000
- if (!txt(r.planId) || !filePlan(r.preview)) throw fail('bad-response')
1302
+ if (!txt(r.planId) || !filePlan(r.preview) || r.preview.profile !== status.profile || r.ref != null || r.plugins != null) throw fail('bad-response')
1001
1303
  displayPlan({ mode: 'local', fileName: file.name, planId: r.planId, preview: r.preview })
1002
1304
  })
1003
1305
  }
@@ -1121,7 +1423,7 @@ window.__ModuleLoader__.load({
1121
1423
  sent = true
1122
1424
  const r = await call('/undo', { expectedStamp: reviewed.stamp })
1123
1425
  if (r.report?.stamp !== reviewed.stamp || !number(r.report.reverted)) throw fail('bad-response')
1124
- setRestoreReceipt({ mode: 'undo', reverted: r.report.reverted })
1426
+ setRestoreReceipt({ mode: 'undo', profile: s.profile, reverted: r.report.reverted })
1125
1427
  move({ name: 'home' }, 'restore-receipt')
1126
1428
  await afterWrite(call, active)
1127
1429
  }, error => setIssue({ error, uncertain: sent && consumedPlanError(error) }))
@@ -1185,8 +1487,27 @@ window.__ModuleLoader__.load({
1185
1487
  const href = gistLink({ id })
1186
1488
  return href ? h('a', { className: 'dpgsp-link', href, target: '_blank', rel: 'noopener noreferrer', referrerPolicy: 'no-referrer' }, href) : isolated(id ?? t('newGist'))
1187
1489
  }
1188
- const receiptStamp = restoreReceipt?.result?.report?.undoStamp
1189
- const receiptUndo = txt(receiptStamp) && receiptStamp === status?.undo?.stamp ? btn('undo-review', t('undo'), rootAction('restore', () => openUndo(receiptStamp)), { disabled: locked }) : null
1490
+ // The local status read that follows a receipt may still be in flight.
1491
+ // Returning home does not cancel it or unlock any other operation early.
1492
+ const leaveReceipt = () => move({ name: 'home' }, opener.current)
1493
+ function receiptView(main = false) {
1494
+ const receipt = main ? page.receipt : restoreReceipt
1495
+ if (!receipt) return null
1496
+ const mode = receipt.reviewedMode ?? receipt.mode
1497
+ const recheck = receipt.mode === 'unknown' || (receipt.result && receiptSummary(receipt).attention)
1498
+ const readAgain = () => {
1499
+ if (locked || flight.current) return
1500
+ opener.current = mode === 'standard' ? 'restore' : 'more'
1501
+ if (mode === 'local') move({ name: 'local' }, 'pick')
1502
+ else prepare(mode, receipt.result?.ref.id ?? receipt.source)
1503
+ }
1504
+ const stamp = matchingUndo(receipt, status)
1505
+ return h(RestoreReceipt, { receipt, t,
1506
+ backButton: main ? btn('back', t('back'), leaveReceipt) : null,
1507
+ undoButton: stamp ? btn('undo-review', t('undo'), () => openUndo(stamp), { disabled: locked }) : null,
1508
+ repreviewButton: recheck ? btn('preview-receipt-source', t(mode === 'local' ? 'chooseAgain' : 'previewReceiptSource'), readAgain, { disabled: locked }) : null,
1509
+ alerts: main && (statusError || issue || uploadCheck) ? alerts(true) : null })
1510
+ }
1190
1511
  const intro = (key, subtitle) => h('header', null, title(t(key)), subtitle ? h('p', { className: 'dpgsp-intro' }, t(subtitle)) : null)
1191
1512
  function homeView() {
1192
1513
  const uploaded = targetId && backupReceipt?.ref?.id === targetId ? backupReceipt : null
@@ -1210,7 +1531,7 @@ window.__ModuleLoader__.load({
1210
1531
  alerts(!status && !statusError), status && !normal ? box('warning', h('p', null, t('staleHost')),
1211
1532
  h('div', { className: 'dpgsp-actions' }, btn('retry-status', t('statusRetry'), retryStatus, { disabled: !!busy }))) : null)) : null,
1212
1533
  normal && dropped.length ? frame(details(`${t('droppedDeps')} (${uploaded.droppedEntries ?? dropped.length})`, list(dropped, row => [isolated(row.name), mono(row.spec ?? '')]))) : null,
1213
- normal && restoreReceipt ? h(RestoreReceipt, { receipt: restoreReceipt, t, undoButton: receiptUndo, locked, onRepreview: rootAction('restore', () => prepare('standard', restoreReceipt.result.ref.id)) }) : null)
1534
+ normal && restoreReceipt ? receiptView() : null)
1214
1535
  }
1215
1536
  function sourceView() {
1216
1537
  return frame(h(React.Fragment, null, intro(page.mode === 'config' ? 'configMode' : 'restore', 'sourceIntro'),
@@ -1306,16 +1627,19 @@ window.__ModuleLoader__.load({
1306
1627
  box('warning', h('strong', null, t('undoLimit')), h('p', null, t('undoScope')))) : page.snapshot === null ? hint(t('undoNone')) : null,
1307
1628
  alerts()), footer(buttons))
1308
1629
  }
1309
- const views = { home: homeView, source: sourceView, preview: previewView, backup: backupView, local: localView, plugins: pluginsView, target: targetView, diagnostics: diagnosticsView, undo: undoView }
1310
- const visible = !status || !compatible(status) ? 'home' : page.name
1630
+ const views = { home: homeView, source: sourceView, preview: previewView, progress: () => h(RestoreProgress, { page, t }), receipt: () => receiptView(true),
1631
+ backup: backupView, local: localView, plugins: pluginsView, target: targetView, diagnostics: diagnosticsView, undo: undoView }
1632
+ const visible = page.name === 'receipt' || (status && compatible(status)) ? page.name : 'home'
1633
+ const liveText = visible === 'progress' ? progressStatus(page, t) : announcement ? t(announcement) : ''
1311
1634
  return h('div', { ref: root, className: 'dpgsp-root', 'data-view': visible, 'data-mode': page.mode,
1312
1635
  onKeyDown: e => {
1313
1636
  if (e.key !== 'Escape' || e.defaultPrevented || e.nativeEvent?.isComposing) return
1637
+ if (page.name === 'receipt') { e.preventDefault(); e.stopPropagation(); leaveReceipt(); return }
1314
1638
  if (flight.current?.write) { e.preventDefault(); e.stopPropagation(); return }
1315
1639
  if (menu) { e.preventDefault(); e.stopPropagation(); setMenu(false); moreButton.current?.focus() }
1316
1640
  else if (page.name !== 'home') { e.preventDefault(); e.stopPropagation(); home() }
1317
1641
  } }, h('style', null, CSS), views[visible](),
1318
- h('p', { className: !announcement || announcement === 'reviewDone' ? 'dpgsp-sr' : 'dpgsp-hint', role: 'status', 'aria-live': 'polite', 'aria-atomic': true }, announcement ? t(announcement) : ''))
1642
+ h('p', { className: !announcement || announcement === 'reviewDone' ? 'dpgsp-sr' : 'dpgsp-hint', role: 'status', 'aria-live': 'polite', 'aria-atomic': true }, liveText))
1319
1643
  }
1320
1644
  return {
1321
1645
  inject: ['slots', 'locale'],