dsh-multi-device-config-sync 0.0.0-stage → 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 ADDED
@@ -0,0 +1,1658 @@
1
+ /** Settings → Multi-device config sync. Plans and credentials live only for the current interaction. */
2
+ window.__ModuleLoader__.load({
3
+ id: 'dsh-multi-device-config-sync',
4
+ factory(require) {
5
+ const React = require('react')
6
+ const h = React.createElement
7
+ // Package identity changed for npm; the settings section and HTTP API did not.
8
+ const NS = 'dsh-profile-gist-sync-plus'
9
+ const API = '/dsh-profile-gist-sync-plus/api'
10
+ const SECTION_ORDER = 16
11
+ const GUIDE = 'https://github.com/Xeonice/dsh-profile-gist-sync-plus#readme'
12
+
13
+ const DICT = {
14
+ zh: {
15
+ section: '多端配置同步',
16
+ localProfile: '本机配置',
17
+ profileName: '配置名称',
18
+ backupContents: '备份内容',
19
+ contents: '配置文件和插件清单',
20
+ unavailable: '状态不可用',
21
+ help: '帮助',
22
+ openGuide: '在新标签页打开使用指南',
23
+ backup: '备份本机',
24
+ restore: '从备份恢复',
25
+ more: '更多',
26
+ back: '返回首页',
27
+ cancel: '取消',
28
+ next: '查看预览',
29
+ previewAgain: '重新预览',
30
+ previewReceiptSource: '重新预览此来源',
31
+ noneYet: '尚未备份',
32
+ unlinked: '未关联备份目标',
33
+ linked: '已关联备份目标',
34
+ linkedGist: '已关联的 Gist',
35
+ gistSource: 'Gist 备份',
36
+ ready: '备份已就绪',
37
+ copy: '复制备份链接',
38
+ copyLink: '复制链接',
39
+ copied: '已复制',
40
+ manualCopy: '未能自动复制,请手动复制下方链接。',
41
+ link: '备份链接',
42
+ openGist: '打开 Gist',
43
+ privacy: '新建备份不公开列出,持链接者可读。配置文本不会自动脱敏。',
44
+ overwriteHint: '再次备份会覆盖已关联目标中的备份文件。',
45
+ overwriteReview: '更新已关联的备份?',
46
+ visibilityKept: '更新不会更改目标的可见性;原本公开的 Gist 仍然公开。',
47
+ uploadConfirm: '确认更新备份',
48
+ uploadRetry: '重新备份',
49
+ uploadScope: '上传配置和插件清单,不含插件本体或凭据库。请先检查文本文件中是否含有私密信息。',
50
+ uploadTarget: '上传目标',
51
+ newGist: '新建未公开列出的 Gist',
52
+ uploadUncertain: '未能核实这次上传的结果。请先检查本机记录和目标 Gist,不要重复上传。',
53
+ refreshFailed: '未能刷新本机状态。请重新读取状态,不必重复刚才的操作。',
54
+ hostMissing: '当前无法读取本机配置状态。',
55
+ staleHost: '当前服务未提供所需的备份接口。请重启 DSH 后再试。',
56
+ statusRetry: '重新读取本机状态',
57
+ localBusy: '正在读取本机状态…',
58
+ uploadBusy: '正在备份本机…',
59
+ previewBusy: '正在查看这次恢复会更改什么…',
60
+ applyBusy: '正在按预览恢复,请勿重复操作。',
61
+ pluginsBusy: '正在核对本机插件清单…',
62
+ installBusy: '正在安装已核对的插件…',
63
+ undoBusy: '正在撤销配置恢复…',
64
+ busy: '处理中…',
65
+ sourceIntro: '粘贴另一台电脑的备份链接,先看看这台电脑会改什么。',
66
+ newMachineStep1: '也可以输入 Gist ID。查看预览不会写入配置、安装插件或更改上传目标。',
67
+ sourceLabel: '备份链接或 Gist ID',
68
+ sourcePlaceholder: '粘贴 gist.github.com 备份链接或 ID',
69
+ changeSource: '换用其他来源',
70
+ source: '来源',
71
+ targetProfile: '本机 profile',
72
+ previewTitle: '恢复预览',
73
+ configMode: '仅恢复配置',
74
+ configPreview: '仅恢复配置:预览',
75
+ localPreview: '本地文件:恢复预览',
76
+ configScope: '仅写配置,不安装插件。使用完整文件范围,备份中的 .npmrc 等包管理策略文件也可能覆盖本机设置。',
77
+ standardTrust: '仅在信任备份和插件来源时恢复。更改影响此 profile 的所有会话;构建脚本如需批准,请单独核对。',
78
+ configTrust: '仅在信任整份备份时恢复。更改影响此 profile 的所有会话。',
79
+ configFiles: '配置文件',
80
+ changeFiles: '变更 %n 个配置文件',
81
+ fileCount: '%n 个文件',
82
+ add: '新增',
83
+ overwrite: '覆盖',
84
+ merge: '合并',
85
+ identical: '不变',
86
+ retained: '保留或跳过',
87
+ showUnchanged: '未变更的文件',
88
+ pluginsToInstall: '安装 %n 个插件',
89
+ unresolved: '无法自动安装,将跳过',
90
+ noSpec: '未记录可核实的来源',
91
+ installSource: '安装来源',
92
+ alreadyEnable: '已安装,恢复后加入启用清单',
93
+ alreadyOther: '其他已安装的包',
94
+ cannotVerify: '无法核实插件清单,不能确认组合恢复。',
95
+ cannotVerifyHint: '可到「插件」页核对本机安装情况;如只想恢复配置,请从「更多」打开范围不同的独立预览。',
96
+ noChanges: '已是备份中的状态',
97
+ filesSame: '没有配置文件需要更改。',
98
+ filesPluginsSame: '没有配置文件需要更改,也没有插件需要安装。',
99
+ noApplicable: '没有可自动应用的更改。请核对保留或需手动处理的项目。',
100
+ confirmCombined: '恢复并安装 %n 个插件',
101
+ confirmOne: '恢复并安装 1 个插件',
102
+ confirmFiles: '确认恢复配置',
103
+ confirmConfig: '确认仅恢复配置',
104
+ noInstall: '此操作不安装插件。',
105
+ reviewDone: '预览已就绪,尚未执行恢复。',
106
+ restoreDone: '恢复完成',
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: '重启不会补装缺失的插件,也不会批准构建脚本。',
152
+ restoreAttention: '配置已恢复,仍有事项需处理',
153
+ changedCount: '已更改 %n 个配置文件',
154
+ installedCount: '已安装 %n 个插件',
155
+ resultDetails: '查看结果',
156
+ warnings: '提醒',
157
+ restart: '重启 DSH 后生效。',
158
+ uncertain: '未取得可核实的结果,部分操作可能已完成。请先核对本机状态和撤销记录,再重新预览。',
159
+ pluginUnknown: '无法核实完整的插件安装结果。',
160
+ pluginResults: '插件安装结果',
161
+ stillMissing: '仍缺少的包',
162
+ installed: '已安装',
163
+ present: '已存在',
164
+ failed: '失败',
165
+ skipped: '跳过',
166
+ pendingBuilds: '待单独批准的构建脚本',
167
+ buildHint: '请到「插件」页核对脚本来源,需要时单独批准;本页不会批准构建。',
168
+ retryHint: '处理这些事项后,重新预览可核实还缺哪些插件。',
169
+ undo: '撤销上次配置恢复',
170
+ undoConfirm: '确认撤销配置',
171
+ undoScope: '还原到这次恢复之前的配置,移除当时新增的文件;之后对这些文件的编辑可能丢失。',
172
+ undoLimit: '撤销只还原配置,不卸载插件。',
173
+ undoWhen: '恢复记录',
174
+ undoNone: '没有可撤销的配置恢复。',
175
+ undoDone: '配置已撤销',
176
+ reverted: '已还原 %n 个文件。',
177
+ local: '本地备份文件',
178
+ localHint: '导入或导出配置 JSON,不必连接 GitHub。',
179
+ import: '选择备份文件',
180
+ export: '导出配置文件',
181
+ chooseAgain: '重新选择文件',
182
+ install: '单独补装插件',
183
+ installHint: '只核对本机 profile 声明的包,不读取云端或恢复配置。',
184
+ installConfirm: '安装已核对的 %n 个插件',
185
+ installOne: '安装已核对的 1 个插件',
186
+ installTrust: '仅安装你信任的来源。插件可能运行代码;本次操作不会批准新的构建脚本。',
187
+ allPresent: '本机清单中声明的包均已安装。',
188
+ installUnknown: '无法核实本机缺少哪些插件。请检查「插件」页。',
189
+ refreshInventory: '重新检查插件',
190
+ inventoryChanged: '本机清单已改变。请核对新的安装来源,再决定是否安装。',
191
+ target: '管理备份目标',
192
+ targetHint: '这里只管理以后上传的位置,不读取或修改云端。恢复时临时填写的来源不会保存为目标。',
193
+ targetNew: '下次备份的目标',
194
+ targetInput: '新的 Gist 链接或 ID',
195
+ targetEmpty: '留空则下次备份新建 Gist',
196
+ targetWarning: '保存后,下次备份将覆盖这个 Gist 中的备份文件。',
197
+ saveTarget: '保存备份目标',
198
+ targetSaved: '备份目标已保存。',
199
+ targetChanged: '本机备份目标或备份选项已改变。请先核对最新范围。',
200
+ diagnostics: '诊断与高级设置',
201
+ diagnosticsHint: '以下为本机记录,不代表已经检查云端。',
202
+ lastUpload: '最近一次上传',
203
+ lastSync: '最近一次云端恢复',
204
+ never: '暂无记录',
205
+ settingsFile: '本机设置文件',
206
+ profileRoot: 'profile 目录',
207
+ includeMachine: '备份和导出时包含本机用量统计(data/usage.json)',
208
+ machineSaved: '已更新备份范围。',
209
+ machineIncluded: '包含本机用量统计。',
210
+ machineExcluded: '不包含本机用量统计。',
211
+ localInventory: '本机文件清单',
212
+ defaultInventory: '基本备份范围(不含可选的用量统计)',
213
+ excluded: '默认排除',
214
+ limits: '大小上限:整份备份 / 单个 Gist 文件',
215
+ droppedDeps: '未上传的本机路径依赖',
216
+ repair: '修复 GitHub 访问',
217
+ tokenLabel: '仅供本次请求的 GitHub 令牌',
218
+ tokenHelp: '可以填写有 gist 权限的令牌;也可在启动环境中设置 DSH_GITHUB_TOKEN / GITHUB_TOKEN 后重启,或在本机执行 gh auth login。更新已有 Gist 还需对它有写权限。',
219
+ tokenPrivacy: '令牌不保存,发送一次后清空;恢复确认不会再次发送。',
220
+ authRetry: '留空重试会使用本机凭据。',
221
+ 'reason.no-plugin-manager': '未提供插件管理服务',
222
+ 'reason.plugin-manager-error': '读取插件清单失败',
223
+ 'note.local-path': '本机路径,无法自动安装',
224
+ 'note.workspace-protocol': 'workspace: 声明,无法在这台电脑解析',
225
+ 'note.missing-source': '缺少可核实的安装来源',
226
+ 'note.unsupported-source': '不支持自动安装此来源',
227
+ 'note.invalid-name': '包名无效',
228
+ 'note.stale-plan': '安装清单已改变,请重新预览',
229
+ 'note.legacy-sync-package': '不自动补装此插件的旧 Git 包,请在「插件」中管理',
230
+ 'note.local-sync-package': '同步插件本身请在「插件」中安装或更新',
231
+ 'code.legacy-sync-package': '已跳过旧版同步插件,不会从备份安装或启用',
232
+ 'code.local-sync-package': '保留本机同步插件的安装来源和启用状态',
233
+ 'code.dependency': '依赖目录',
234
+ 'code.lockfile': '锁文件',
235
+ 'code.hidden-dir': '隐藏目录',
236
+ 'code.backup-copy': '备份副本',
237
+ 'code.symlink': '符号链接',
238
+ 'code.machine-state': '本机用量',
239
+ 'code.credential': '凭据库',
240
+ 'code.binary': '二进制',
241
+ 'code.too-large': '文件过大',
242
+ 'code.tool-state': '临时状态',
243
+ 'code.local-dependency': '本机路径依赖',
244
+ 'code.local-policy': '按本机策略保留,不覆盖',
245
+ 'err.bad-source': '请输入 Gist ID,或标准的 https://gist.github.com 备份链接(不要附加参数、片段或凭据)。',
246
+ 'err.auth': 'GitHub 未授权本次访问。',
247
+ 'err.rate-limit': 'GitHub 已限流,或当前凭据权限不足。可以稍后再试。',
248
+ 'err.session-auth': 'DSH 拒绝了本次请求。请检查 DSH 登录状态和访问地址。',
249
+ 'err.notfound': '未找到资源。请核对备份链接和访问权限;如果服务刚更新,请重启 DSH。',
250
+ 'err.stale-plan': '预览已失效、被使用或本机状态已改变。请重新预览。',
251
+ 'err.busy': '另一项恢复或安装正在进行。请稍后重新预览。',
252
+ 'err.invalid': '备份或请求无效,请核对后重试。',
253
+ 'err.invalidJson': '这不是有效的备份 JSON 文件。',
254
+ 'err.too-large': '备份超出大小上限。',
255
+ 'err.timeout': '请求超时。',
256
+ 'err.network': '无法连接服务。',
257
+ 'err.no-profile': 'DSH 未以 profile 启动,没有可读取的本机配置。',
258
+ 'err.no-cloud': '尚未关联备份,请输入来源链接。',
259
+ 'err.unsafe-path': '备份中含不安全的路径,已拒绝恢复。',
260
+ 'err.nothing-to-undo': '没有可撤销的恢复记录。',
261
+ 'err.bad-response': '服务没有返回可核实的完整数据。',
262
+ 'err.other': '操作未能完成。',
263
+ },
264
+ en: {
265
+ section: 'Multi-device config sync',
266
+ localProfile: 'Local configuration',
267
+ profileName: 'Profile',
268
+ backupContents: 'Backup contents',
269
+ contents: 'Configuration files and plugin manifest',
270
+ unavailable: 'Status unavailable',
271
+ help: 'Help',
272
+ openGuide: 'Open the guide in a new tab',
273
+ backup: 'Back up this machine',
274
+ restore: 'Restore from backup',
275
+ more: 'More',
276
+ back: 'Back to home',
277
+ cancel: 'Cancel',
278
+ next: 'View preview',
279
+ previewAgain: 'Preview again',
280
+ previewReceiptSource: 'Preview this source again',
281
+ noneYet: 'No backup yet',
282
+ unlinked: 'No backup destination linked',
283
+ linked: 'Backup destination linked',
284
+ linkedGist: 'Linked Gist',
285
+ gistSource: 'Gist backup',
286
+ ready: 'Backup ready',
287
+ copy: 'Copy backup link',
288
+ copyLink: 'Copy link',
289
+ copied: 'Copied',
290
+ manualCopy: 'Automatic copy was unavailable. Select and copy the link below.',
291
+ link: 'Backup link',
292
+ openGist: 'Open Gist',
293
+ privacy: 'New backups are unlisted. Anyone with the link can read them. Configuration text is not redacted.',
294
+ overwriteHint: 'Backing up again overwrites the backup file at the linked destination.',
295
+ overwriteReview: 'Update the linked backup?',
296
+ visibilityKept: 'Updating a Gist does not change visibility. A public Gist stays public.',
297
+ uploadConfirm: 'Confirm backup update',
298
+ uploadRetry: 'Retry backup',
299
+ uploadScope: 'Uploads settings and the plugin manifest, not plugin packages or credential stores. Check text files for private information first.',
300
+ uploadTarget: 'Upload destination',
301
+ newGist: 'Create an unlisted Gist',
302
+ uploadUncertain: 'The upload result could not be verified. Check the local record and destination Gist before uploading again.',
303
+ refreshFailed: 'Local status could not be refreshed. Read it again; do not repeat the previous action.',
304
+ hostMissing: 'Local configuration status is unavailable.',
305
+ staleHost: 'The running host does not provide the required backup API. Restart DSH and try again.',
306
+ statusRetry: 'Read local status again',
307
+ localBusy: 'Reading local status…',
308
+ uploadBusy: 'Backing up this machine…',
309
+ previewBusy: 'Checking what this restore would change…',
310
+ applyBusy: 'Applying the reviewed restore. Do not repeat the request.',
311
+ pluginsBusy: 'Checking the local plugin manifest…',
312
+ installBusy: 'Installing the reviewed plugins…',
313
+ undoBusy: 'Undoing the configuration restore…',
314
+ busy: 'Working…',
315
+ sourceIntro: 'Paste the link from the other computer to see what would change here.',
316
+ newMachineStep1: 'A Gist ID also works. A preview does not write settings, install packages or change the upload destination.',
317
+ sourceLabel: 'Backup link or Gist ID',
318
+ sourcePlaceholder: 'Paste a gist.github.com backup link or ID',
319
+ changeSource: 'Use a different source',
320
+ source: 'Source',
321
+ targetProfile: 'Local profile',
322
+ previewTitle: 'Restore preview',
323
+ configMode: 'Restore configuration only',
324
+ configPreview: 'Configuration-only preview',
325
+ localPreview: 'Local file restore preview',
326
+ configScope: 'Restores configuration without installing plugins. Full-file rules apply: package-manager policies such as .npmrc in this backup can overwrite local settings.',
327
+ standardTrust: 'Trust both the backup and package sources before restoring. Changes affect every session in this profile. Review any requested build scripts separately.',
328
+ configTrust: 'Restore only if you trust the entire backup. Changes affect every session in this profile.',
329
+ configFiles: 'Configuration files',
330
+ changeFiles: 'Configuration files to change: %n',
331
+ fileCount: 'Files: %n',
332
+ add: 'Add',
333
+ overwrite: 'Overwrite',
334
+ merge: 'Merge',
335
+ identical: 'Unchanged',
336
+ retained: 'Retained or skipped',
337
+ showUnchanged: 'Unchanged files',
338
+ pluginsToInstall: 'Plugins to install: %n',
339
+ unresolved: 'Cannot install automatically — will skip',
340
+ noSpec: 'No verifiable source recorded',
341
+ installSource: 'Install source',
342
+ alreadyEnable: 'Already installed; will be added to the enabled list',
343
+ alreadyOther: 'Other already-installed packages',
344
+ cannotVerify: 'The plugin inventory could not be verified. Combined restore is unavailable.',
345
+ cannotVerifyHint: 'Check installed packages on the Plugins page. For configuration alone, use the separate, full-scope preview under More.',
346
+ noChanges: 'Already matches this backup',
347
+ filesSame: 'No configuration files need changing.',
348
+ filesPluginsSame: 'No configuration files need changing and no plugins need installing.',
349
+ noApplicable: 'There are no changes that can be applied automatically. Review the retained items or packages that need manual attention.',
350
+ confirmCombined: 'Restore and install %n plugins',
351
+ confirmOne: 'Restore and install 1 plugin',
352
+ confirmFiles: 'Confirm configuration restore',
353
+ confirmConfig: 'Restore configuration only',
354
+ noInstall: 'No plugins will be installed.',
355
+ reviewDone: 'Preview ready. No restore has been performed.',
356
+ restoreDone: 'Restore complete',
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.',
402
+ restoreAttention: 'Configuration restored; some items need attention',
403
+ changedCount: 'Configuration files changed: %n',
404
+ installedCount: 'Plugins installed: %n',
405
+ resultDetails: 'View results',
406
+ warnings: 'Warnings',
407
+ restart: 'Restart DSH for changes to take effect.',
408
+ uncertain: 'The result could not be verified. Some changes may already have been applied. Check local status and undo history, then preview again.',
409
+ pluginUnknown: 'The complete plugin installation result could not be verified.',
410
+ pluginResults: 'Plugin installation results',
411
+ stillMissing: 'Packages still missing',
412
+ installed: 'Installed',
413
+ present: 'Already present',
414
+ failed: 'Failed',
415
+ skipped: 'Skipped',
416
+ pendingBuilds: 'Build scripts awaiting separate approval',
417
+ buildHint: 'Review the script sources on the Plugins page and approve separately if appropriate. This page never approves builds.',
418
+ retryHint: 'After addressing these items, preview again to check what is still missing.',
419
+ undo: 'Undo last configuration restore',
420
+ undoConfirm: 'Confirm undo',
421
+ undoScope: 'Return files to their state before this restore, removing files it added. Later edits to those files may be lost.',
422
+ undoLimit: 'Undo restores configuration only. It does not uninstall plugins.',
423
+ undoWhen: 'Restore record',
424
+ undoNone: 'There is no configuration restore to undo.',
425
+ undoDone: 'Configuration restore undone',
426
+ reverted: 'Files reverted: %n.',
427
+ local: 'Local backup file',
428
+ localHint: 'Import or export a configuration JSON file without connecting to GitHub.',
429
+ import: 'Choose a backup file',
430
+ export: 'Export configuration file',
431
+ chooseAgain: 'Choose the file again',
432
+ install: 'Install missing plugins separately',
433
+ installHint: 'Check packages declared in this local profile, without reading the cloud or restoring configuration.',
434
+ installConfirm: 'Install %n reviewed plugins',
435
+ installOne: 'Install 1 reviewed plugin',
436
+ installTrust: 'Install only sources you trust. Plugins can run code; this action does not approve new build scripts.',
437
+ allPresent: 'Every package declared in this profile is already installed.',
438
+ installUnknown: 'Missing local plugins could not be verified. Check the Plugins page.',
439
+ refreshInventory: 'Check plugins again',
440
+ inventoryChanged: 'The local manifest changed. Review the new sources before installing.',
441
+ target: 'Manage backup destination',
442
+ targetHint: 'Choose where future uploads go. This does not read or change the cloud. A temporary restore source is not saved as a destination.',
443
+ targetNew: 'Next backup destination',
444
+ targetInput: 'New Gist link or ID',
445
+ targetEmpty: 'Leave empty to create a Gist on the next backup',
446
+ targetWarning: 'After saving, the next backup overwrites the backup file in this Gist.',
447
+ saveTarget: 'Save backup destination',
448
+ targetSaved: 'Backup destination saved.',
449
+ targetChanged: 'The local backup destination or options changed. Review the current scope first.',
450
+ diagnostics: 'Diagnostics and settings',
451
+ diagnosticsHint: 'These are local records, not a live check of the cloud.',
452
+ lastUpload: 'Most recent upload',
453
+ lastSync: 'Most recent cloud restore',
454
+ never: 'No record',
455
+ settingsFile: 'Local settings file',
456
+ profileRoot: 'Profile directory',
457
+ includeMachine: 'Include this machine’s usage counters (data/usage.json) in backups and exports',
458
+ machineSaved: 'Backup scope updated.',
459
+ machineIncluded: 'Includes this machine’s usage counters.',
460
+ machineExcluded: 'Excludes this machine’s usage counters.',
461
+ localInventory: 'Local file list',
462
+ defaultInventory: 'Base backup scope (without optional usage counters)',
463
+ excluded: 'Excluded by default',
464
+ limits: 'Size limits: whole backup / Gist file',
465
+ droppedDeps: 'Machine-local dependencies left out of the upload',
466
+ repair: 'Restore GitHub access',
467
+ tokenLabel: 'GitHub token for this request only',
468
+ tokenHelp: 'Enter a token with Gist access below, set DSH_GITHUB_TOKEN / GITHUB_TOKEN in the startup environment and restart DSH, or run gh auth login on this machine. Updating an existing Gist requires write access to it.',
469
+ tokenPrivacy: 'The token is not saved and is cleared after one request. Restore confirmation never sends it again.',
470
+ authRetry: 'Leave empty to retry with local credentials.',
471
+ 'reason.no-plugin-manager': 'Plugin manager unavailable',
472
+ 'reason.plugin-manager-error': 'Plugin inventory could not be read',
473
+ 'note.local-path': 'A local path cannot be installed on this machine',
474
+ 'note.workspace-protocol': 'A workspace: reference cannot be resolved here',
475
+ 'note.missing-source': 'No verifiable installation source',
476
+ 'note.unsupported-source': 'This source does not support automatic installation',
477
+ 'note.invalid-name': 'Invalid package name',
478
+ 'note.stale-plan': 'The install list changed; preview again',
479
+ 'note.legacy-sync-package': 'The old Git edition is not installed automatically. Manage it in Plugins.',
480
+ 'note.local-sync-package': 'Install or update the sync plugin itself in Plugins.',
481
+ 'code.legacy-sync-package': 'Old sync package skipped; it will not be installed or enabled from the backup',
482
+ 'code.local-sync-package': 'The installed sync package keeps its local source and activation setting',
483
+ 'code.dependency': 'Dependencies',
484
+ 'code.lockfile': 'Lockfile',
485
+ 'code.hidden-dir': 'Hidden directory',
486
+ 'code.backup-copy': 'Backup copy',
487
+ 'code.symlink': 'Symbolic link',
488
+ 'code.machine-state': 'Machine usage',
489
+ 'code.credential': 'Credential store',
490
+ 'code.binary': 'Binary',
491
+ 'code.too-large': 'File too large',
492
+ 'code.tool-state': 'Temporary state',
493
+ 'code.local-dependency': 'Machine-local dependency',
494
+ 'code.local-policy': 'Retained by local policy; not overwritten',
495
+ 'err.bad-source': 'Enter a Gist ID or a standard https://gist.github.com backup link without credentials, query or fragment.',
496
+ 'err.auth': 'GitHub did not authorize this request.',
497
+ 'err.rate-limit': 'GitHub rate-limited this request, or the credential lacks permission. You can retry later.',
498
+ 'err.session-auth': 'DSH refused the request. Check the DSH sign-in and address.',
499
+ 'err.notfound': 'Resource not found. Check the link and access. If the host was just updated, restart DSH.',
500
+ 'err.stale-plan': 'This preview expired, was used, or the local state changed. Preview again.',
501
+ 'err.busy': 'Another restore or installation is running. Preview again when it finishes.',
502
+ 'err.invalid': 'The backup or request is not valid. Check it before retrying.',
503
+ 'err.invalidJson': 'This file is not valid backup JSON.',
504
+ 'err.too-large': 'The backup exceeds the size limit.',
505
+ 'err.timeout': 'The request timed out.',
506
+ 'err.network': 'The service is unreachable.',
507
+ 'err.no-profile': 'DSH was not started with a profile. No local configuration is available.',
508
+ 'err.no-cloud': 'No backup is linked. Enter a source link first.',
509
+ 'err.unsafe-path': 'An unsafe path in the backup prevented restoration.',
510
+ 'err.nothing-to-undo': 'There is no restore record to undo.',
511
+ 'err.bad-response': 'The service did not return complete, verifiable data.',
512
+ 'err.other': 'The operation could not be completed.',
513
+ },
514
+ }
515
+
516
+ // Geometry and materials follow the installed Account settings cards. The
517
+ // colored Button pair stays blue with on-color text in both host palettes.
518
+ const CSS = `
519
+ .dpgsp-root {
520
+ --ink:var(--dsw-alias-label-primary); --muted:var(--dsw-alias-label-secondary); --subtle:var(--dsw-alias-label-tertiary,var(--muted));
521
+ --paper:var(--dsw-alias-settings-card-fill,var(--dsw-alias-bg-layer-2)); --stroke:var(--dsw-alias-settings-card-stroke,var(--dsw-alias-border-l2));
522
+ --line:var(--dsw-alias-border-l2); --edge:var(--dsw-alias-border-l3,var(--line)); --hover:var(--dsw-alias-interactive-bg-hover,var(--dsw-alias-bg-layer-1));
523
+ --accent:var(--dsw-alias-state-business-primary,var(--dsw-alias-brand-primary)); --good:var(--dsw-alias-state-success-primary); --warn:var(--dsw-alias-state-warn-primary); --error:var(--dsw-alias-state-error-primary);
524
+ container-type:inline-size; display:flex; flex-direction:column; gap:16px; width:100%; min-width:0; padding:8px 0;
525
+ color:var(--ink); font:inherit; font-size:13px; line-height:22px; overflow-wrap:anywhere;
526
+ }
527
+ .dpgsp-root, .dpgsp-root *, .dpgsp-root *::before, .dpgsp-root *::after { box-sizing:border-box; }
528
+ .dpgsp-root :is(h2,h3,p,ul,dl,dd) { margin:0; }
529
+ .dpgsp-root :is(h2,h3) { font-size:14px; line-height:22px; font-weight:500; }
530
+ .dpgsp-root strong { font-weight:500; }
531
+ .dpgsp-card { width:100%; min-width:0; padding:12px 16px; border:.5px solid var(--stroke); border-radius:var(--dsw-radius-xl,16px); background:var(--paper); }
532
+ .dpgsp-summary, .dpgsp-identity, .dpgsp-status, .dpgsp-line, .dpgsp-source, .dpgsp-actions, .dpgsp-foot, .dpgsp-note, .dpgsp-row, .dpgsp-check { display:flex; align-items:center; }
533
+ .dpgsp-summary { min-height:44px; justify-content:space-between; flex-wrap:wrap; gap:6px 16px; }
534
+ .dpgsp-identity { min-width:0; gap:10px; }
535
+ .dpgsp-mark { display:grid; place-items:center; flex:none; width:32px; height:32px; border-radius:50%; corner-shape:round; color:var(--muted); background:var(--dsw-alias-bg-skeleton,var(--hover)); }
536
+ .dpgsp-icon { display:inline-block; flex:none; vertical-align:middle; }
537
+ .dpgsp-identity > div, .dpgsp-status { min-width:0; }
538
+ .dpgsp-status { justify-content:flex-end; flex-wrap:wrap; gap:4px 8px; color:var(--muted); }
539
+ .dpgsp-status [data-focus=backup-receipt] { color:var(--ink); }
540
+ .dpgsp-status [data-focus=backup-receipt] svg { color:var(--good); }
541
+ .dpgsp-subtitle { color:var(--subtle); }
542
+ .dpgsp-hint, .dpgsp-meta, .dpgsp-note, .dpgsp-intro { color:var(--muted); }
543
+ .dpgsp-note { align-items:flex-start; gap:8px; }
544
+ .dpgsp-note > svg { margin-top:3px; }
545
+ .dpgsp-actions, .dpgsp-foot { justify-content:flex-end; flex-wrap:wrap; gap:8px 10px; }
546
+ .dpgsp-btn { display:inline-flex; align-items:center; justify-content:center; gap:6px; max-width:100%; min-width:min(58px,100%); min-height:36px; padding:6px 14px; border:.5px solid var(--edge); border-radius:var(--dsw-radius-md,12px); background:transparent; color:var(--ink); cursor:pointer; touch-action:manipulation; font:inherit; font-size:14px; line-height:22px; text-align:center; text-decoration:none; white-space:normal; overflow-wrap:anywhere; }
547
+ .dpgsp-btn.dpgsp-primary { --button-fill:var(--dsw-alias-button-info-fill,var(--dsw-alias-button-primary-fill,var(--accent))); --button-l:.56; border-color:transparent; font-weight:500; color:var(--dsw-alias-label-on-color,var(--dsw-alias-label-primary-foreground)); background:var(--button-fill); }
548
+ /* Cap only lightness, retaining the host's hue. The native blue alone is too
549
+ light for 14px white text, especially on the dark palette. */
550
+ @supports (color:oklch(from currentColor min(l,.56) c h)) {
551
+ .dpgsp-btn.dpgsp-primary { background:oklch(from var(--button-fill) min(l,var(--button-l)) c h); }
552
+ }
553
+ .dpgsp-btn.dpgsp-quiet { min-width:0; min-height:32px; padding:4px 6px; border:0; color:var(--muted); font-size:13px; }
554
+ @media (hover:hover) {
555
+ .dpgsp-btn:not(.dpgsp-primary):not(:disabled):hover { background:var(--hover); }
556
+ .dpgsp-btn.dpgsp-primary:not(:disabled):hover { --button-fill:var(--dsw-alias-button-info-hover,var(--dsw-alias-button-primary-hover,var(--accent))); --button-l:.53; }
557
+ .dpgsp-btn.dpgsp-quiet:hover, .dpgsp-help:hover { color:var(--ink); }
558
+ }
559
+ .dpgsp-root :is(button,input):disabled { opacity:.55; cursor:not-allowed; }
560
+ .dpgsp-root :is(button,input,summary,a):focus-visible { outline:2px solid var(--accent); outline-offset:2px; }
561
+ .dpgsp-root :is(h2,h3,span)[tabindex]:focus { outline:none; }
562
+ .dpgsp-body { display:flex; flex-direction:column; min-width:0; }
563
+ .dpgsp-body > * { min-width:0; padding-block:12px; }
564
+ .dpgsp-body > :first-child { padding-top:4px; }
565
+ .dpgsp-body > :last-child { padding-bottom:4px; }
566
+ .dpgsp-body > * + *, .dpgsp-foot, .dpgsp-homefoot, .dpgsp-copy-feedback { border-top:.5px solid var(--line); }
567
+ .dpgsp-foot, .dpgsp-homefoot { margin-top:8px; padding-top:12px; }
568
+ .dpgsp-foot > .dpgsp-note { flex:1 1 230px; }
569
+ .dpgsp-foot > .dpgsp-actions { min-width:0; margin-inline-start:auto; }
570
+ .dpgsp-homefoot { display:grid; align-items:center; grid-template-columns:auto auto minmax(0,1fr); gap:8px 10px; }
571
+ .dpgsp-homefoot .dpgsp-actions { grid-area:1/3; }
572
+ .dpgsp-menuwrap { display:contents; }
573
+ .dpgsp-menuwrap > button { grid-area:1/1; }
574
+ .dpgsp-menuwrap > button[aria-expanded=true] svg { transform:rotate(180deg); }
575
+ /* Disclosure in normal flow: the host's scrolling settings column can reach
576
+ every option, including items below a short viewport. No portal or overlay. */
577
+ .dpgsp-menulist { grid-column:1 / -1; grid-row:2; display:grid; padding-top:6px; border-top:.5px solid var(--line); }
578
+ .dpgsp-menulist .dpgsp-btn { width:100%; min-height:40px; justify-content:flex-start; gap:10px; padding:6px; color:var(--ink); text-align:start; }
579
+ .dpgsp-help { grid-area:1/2; display:inline-flex; align-items:center; gap:3px; width:fit-content; min-height:32px; color:var(--muted); text-decoration:none; }
580
+ .dpgsp-stack, .dpgsp-group, .dpgsp-field, .dpgsp-box, .dpgsp-iteminfo { display:grid; gap:6px; min-width:0; }
581
+ .dpgsp-stack { gap:12px; }
582
+ .dpgsp-field label { font-weight:500; }
583
+ .dpgsp-input { width:100%; min-width:0; min-height:36px; border:.5px solid var(--edge); border-radius:var(--dsw-radius-sm,8px); padding:6px 10px; color:var(--ink); background:var(--dsw-alias-bg-layer-1); font:inherit; font-size:14px; }
584
+ .dpgsp-input::placeholder { color:var(--subtle); }
585
+ .dpgsp-input[aria-invalid=true] { border-color:var(--error); }
586
+ .dpgsp-check { gap:10px; cursor:pointer; }
587
+ .dpgsp-check input { flex:none; accent-color:var(--accent); }
588
+ .dpgsp-line, .dpgsp-source { gap:6px 8px; flex-wrap:wrap; }
589
+ .dpgsp-source { justify-content:space-between; }
590
+ .dpgsp-line > *, .dpgsp-source > * { min-width:0; }
591
+ .dpgsp-box.dpgsp-alert > :first-child, .dpgsp-box.dpgsp-warning > :first-child, .dpgsp-box.dpgsp-success > :first-child { display:flex; align-items:baseline; gap:8px; }
592
+ .dpgsp-box.dpgsp-alert > :first-child::before, .dpgsp-box.dpgsp-warning > :first-child::before, .dpgsp-box.dpgsp-success > :first-child::before { content:''; width:3px; height:1em; flex:none; align-self:center; border-radius:2px; background:var(--warn); }
593
+ .dpgsp-box.dpgsp-alert > :first-child::before { background:var(--error); }
594
+ .dpgsp-box.dpgsp-success > :first-child::before { background:var(--good); }
595
+ .dpgsp-list { list-style:none; padding:0; }
596
+ .dpgsp-row { min-height:40px; min-width:0; padding:6px 0; gap:10px; }
597
+ .dpgsp-row + .dpgsp-row, .dpgsp-facts > div + div { border-top:.5px solid var(--line); }
598
+ .dpgsp-row > .dpgsp-icon, .dpgsp-rowvalue { color:var(--muted); }
599
+ .dpgsp-row .dpgsp-iteminfo { flex:1; gap:0; }
600
+ .dpgsp-rowvalue { min-width:0; text-align:end; }
601
+ .dpgsp-root code { font: .96em/1.55 ui-monospace,SFMono-Regular,Consolas,monospace; white-space:pre-wrap; overflow-wrap:anywhere; unicode-bidi:isolate; }
602
+ .dpgsp-details > summary { min-height:32px; padding:4px 0; color:var(--ink); cursor:pointer; }
603
+ .dpgsp-details[open] > :not(summary) { margin-top:6px; }
604
+ .dpgsp-body > .dpgsp-facts { padding-block:0; }
605
+ .dpgsp-facts > div { display:flex; align-items:baseline; justify-content:space-between; gap:8px 16px; min-height:40px; padding:9px 0; }
606
+ .dpgsp-facts dt { color:var(--muted); }
607
+ .dpgsp-facts dd { min-width:0; text-align:end; }
608
+ .dpgsp-root .dpgsp-link { color:var(--dsw-alias-link,var(--accent)); text-underline-offset:2px; }
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; } }
640
+ .dpgsp-sr { position:absolute; width:1px; height:1px; padding:0; margin:-1px; overflow:hidden; clip-path:inset(50%); white-space:nowrap; border:0; }
641
+ @container (max-width:470px) {
642
+ .dpgsp-homefoot { grid-template-columns:auto minmax(0,1fr); }
643
+ .dpgsp-homefoot .dpgsp-actions { grid-area:3 / 1 / auto / -1; }
644
+ .dpgsp-foot > .dpgsp-note { flex-basis:100%; }
645
+ }
646
+ @container (max-width:340px) {
647
+ .dpgsp-status { justify-content:flex-start; }
648
+ .dpgsp-facts > div { flex-direction:column; gap:0; }
649
+ .dpgsp-facts dd { text-align:start; }
650
+ .dpgsp-actions { width:100%; }
651
+ .dpgsp-actions > .dpgsp-btn { flex:1 1 100%; }
652
+ }
653
+ `
654
+
655
+ const PATHS = {
656
+ sync: 'M3 8h16m-5-5 5 5-5 5M21 16H5m5 5-5-5 5-5',
657
+ up: 'M12 16V3m-5 5 5-5 5 5M4 15v5h16v-5', down: 'M12 3v13m-5-5 5 5 5-5M4 15v5h16v-5',
658
+ chevron: 'm7 10 5 5 5-5', arrow: 'M4 12h15m-6-6 6 6-6 6',
659
+ file: 'M6 3h7l5 5v13H6zM13 3v6h5M9 13h6m-6 4h4',
660
+ pkg: 'm12 3 8 4.5v9L12 21l-8-4.5v-9L12 3zM4 7.5l8 4.5 8-4.5M12 12v9M8 5.3l8 4.5',
661
+ pc: 'M3 4h18v13H3zM8 21h8m-4-4v4', shield: 'm12 3 8 3v5c0 5-4 8-8 10-4-2-8-5-8-10V6zm0 5v5m0 3v.1',
662
+ info: 'M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0zM12 10.5v6m0-9v.2',
663
+ check: 'M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0zM7.8 12.2l2.6 2.8 5.9-6.2',
664
+ copy: 'M8 8h12v13H8zM16 8V3H4v13h4', external: 'M7 17 17 7M7 7h10v10',
665
+ }
666
+ const icon = (key, size = 17) => h('svg', { className: 'dpgsp-icon', width: size, height: size, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 1.65, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true, focusable: false }, h('path', { d: PATHS[key] }))
667
+ const txt = value => typeof value === 'string' && value.trim() !== ''
668
+ const number = value => Number.isSafeInteger(value) && value >= 0
669
+ const names = items => Array.isArray(items) && items.every(item => typeof item === 'string')
670
+ const countText = (t, key, n) => t(key).replace('%n', String(n))
671
+ const fail = code => Object.assign(new Error(code), { code })
672
+ const rowFile = file => txt(file?.path) && number(file.bytes)
673
+ const excludedFile = file => txt(file?.path) && txt(file.code)
674
+ const FILE_STATES = ['add', 'overwrite', 'merge', 'identical']
675
+ const OUTCOMES = { installed: 'installed', 'already-present': 'present', failed: 'failed', skipped: 'skipped' }
676
+
677
+ // Accept the host's bare ID alphabet, or an exact canonical HTTPS Gist path.
678
+ // Never copy/open a raw URL supplied by the network, even on a success receipt.
679
+ const bareId = id => typeof id === 'string' && /^[A-Za-z0-9_-]{1,64}$/.test(id)
680
+ function sourceId(raw) {
681
+ const s = typeof raw === 'string' ? raw.trim() : ''
682
+ if (bareId(s)) return s
683
+ return /^https:\/\/gist\.github\.com\/(?:[a-z\d][a-z\d-]{0,38}\/)?([a-z\d_-]{1,64})\/?$/i.exec(s)?.[1] ?? null
684
+ }
685
+ function gistLink(ref) {
686
+ if (!bareId(ref?.id)) return null
687
+ if (typeof ref.htmlUrl === 'string' && sourceId(ref.htmlUrl) === ref.id && /^https:\/\//i.test(ref.htmlUrl)) return ref.htmlUrl.trim()
688
+ return `https://gist.github.com/${ref.id}`
689
+ }
690
+ function formatTime(value) {
691
+ if (!txt(value)) return '—'
692
+ const date = new Date(value)
693
+ return Number.isNaN(date.getTime()) ? '—' : date.toLocaleString()
694
+ }
695
+ function formatBytes(n) {
696
+ return !number(n) ? '—' : n < 1024 ? `${n} B` : n < 1048576 ? `${(n / 1024).toFixed(1)} KiB` : `${(n / 1048576).toFixed(1)} MiB`
697
+ }
698
+ function codeText(t, group, code) {
699
+ const key = `${group}.${code}`
700
+ return Object.hasOwn(DICT.en, key) ? t(key) : typeof code === 'string' ? code : ''
701
+ }
702
+ const errorText = (t, error) => Object.hasOwn(DICT.en, `err.${error?.code}`) ? t(`err.${error.code}`) : t('err.other')
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) {
707
+ try {
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) }) })
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) {
718
+ const data = await response.json().catch(() => null)
719
+ if (!response.ok) throw responseError(data)
720
+ if (!object(data)) throw fail('bad-response')
721
+ return data
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
+ }
778
+ function validStatus(s) {
779
+ return txt(s?.profile) && number(s.counts?.files) && number(s.counts.bytes)
780
+ && Array.isArray(s.files) && s.files.every(rowFile) && Array.isArray(s.excluded) && s.excluded.every(excludedFile)
781
+ && (s.cloud == null || ((s.cloud.gistId === null || typeof s.cloud.gistId === 'string') && typeof s.cloud.includeMachine === 'boolean'))
782
+ && (s.undo == null || (txt(s.undo.stamp) && number(s.undo.files)))
783
+ }
784
+ function filePlan(p) {
785
+ if (!txt(p?.profile) || !Array.isArray(p.files) || !Array.isArray(p.dropped) || !p.dropped.every(excludedFile)) return false
786
+ const totals = { add: 0, overwrite: 0, merge: 0, identical: 0 }
787
+ for (const f of p.files) {
788
+ if (!txt(f?.path) || !Object.hasOwn(totals, f.status)) return false
789
+ totals[f.status]++
790
+ }
791
+ return FILE_STATES.every(key => totals[key] === p.counts?.[key])
792
+ && (p.manifest == null || names(p.manifest.bundlesAdded))
793
+ }
794
+ const changes = p => p.counts.add + p.counts.overwrite + p.counts.merge
795
+ const skippedCount = p => Math.max(p.dropped.length, number(p.droppedEntries) ? p.droppedEntries : 0)
796
+ const verifiedInventory = p => p?.available === true && names(p.installed) && Array.isArray(p.missing) && p.missing.every(entry =>
797
+ txt(entry?.name) && typeof entry.resolvable === 'boolean' && (entry.spec == null || typeof entry.spec === 'string')
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
800
+ const installable = p => verifiedInventory(p) ? p.missing.filter(row => row.resolvable) : []
801
+ const inventoryShape = p => p?.available === false || verifiedInventory(p)
802
+ function validCloudPlan(p, mode, id) {
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
804
+ if (mode === 'config') return txt(p.planId) && p.plugins == null
805
+ return p.plugins?.available === false ? p.planId === null : verifiedInventory(p.plugins) && txt(p.planId)
806
+ }
807
+ function actionable(p) {
808
+ return !!p && (p.mode !== 'standard' || verifiedInventory(p.plugins)) && (changes(p.preview) > 0 || installable(p.plugins).length > 0)
809
+ }
810
+ function validRestore(r, plan) {
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
887
+ }
888
+ function verifiedReport(p) {
889
+ return verifiedInventory(p) && Array.isArray(p.results) && p.results.every(row => txt(row?.name) && Object.hasOwn(OUTCOMES, row.outcome) && names(row.pendingBuilds))
890
+ && Object.keys(OUTCOMES).every(key => number(p.outcomeCounts?.[key]) && p.outcomeCounts[key] === p.results.filter(row => row.outcome === key).length)
891
+ }
892
+ const pendingBuilds = p => [...new Set((Array.isArray(p?.results) ? p.results : []).flatMap(row => names(row?.pendingBuilds) ? row.pendingBuilds : []))]
893
+ const incomplete = p => !verifiedReport(p) || p.missing.length > 0 || p.outcomeCounts.failed > 0 || p.outcomeCounts.skipped > 0 || pendingBuilds(p).length > 0
894
+ function sourceKind(entry, t) {
895
+ const full = entry.installSpec
896
+ const prefixed = full.startsWith(`${entry.name}@`)
897
+ const spec = prefixed ? full.slice(entry.name.length + 1) : full
898
+ if (/^(?:git(?:\+|:|@)|ssh:|github:|gitlab:|bitbucket:)/i.test(spec) || /\.git(?:$|#)/i.test(spec)) return 'Git'
899
+ if (/^https?:\/\//i.test(spec)) return /^https:/i.test(spec) ? 'HTTPS' : 'HTTP'
900
+ if ((prefixed && /^[a-z\d*^~<>=][a-z\d*^~<>=.|+ -]*$/i.test(spec)) || /^npm:/i.test(spec)) return 'npm'
901
+ return t('installSource')
902
+ }
903
+
904
+ function compatible(s) {
905
+ const v = /^(\d+)\.(\d+)\.\d+(?:[-+].*)?$/.exec(s?.version ?? '')
906
+ return !!s?.cloud && !!v && (+v[1] > 1 || (+v[1] === 1 && +v[2] >= 3))
907
+ }
908
+ function btn(action, label, onClick, { kind, glyph, ...props } = {}) {
909
+ return h('button', { type: 'button', className: `dpgsp-btn${kind ? ` dpgsp-${kind}` : ''}`, 'data-action': action, onClick, ...props },
910
+ glyph ? icon(glyph, 16) : null, label)
911
+ }
912
+ const box = (kind, ...children) => h('div', { className: `dpgsp-box${kind ? ` dpgsp-${kind}` : ''}` }, ...children)
913
+ const note = (text, glyph = 'info') => h('p', { className: 'dpgsp-note' }, icon(glyph, 15), h('span', null, text))
914
+ const hint = text => h('p', { className: 'dpgsp-hint' }, text)
915
+ const details = (label, ...children) => h('details', { className: 'dpgsp-details' }, h('summary', null, label), ...children)
916
+ const title = text => h('h2', { tabIndex: -1, 'data-focus': 'title' }, text)
917
+ const facts = pairs => h('dl', { className: 'dpgsp-facts' }, pairs.filter(Boolean).map(([k, v]) => h('div', { key: k }, h('dt', null, k), h('dd', null, v))))
918
+ const isolated = value => h('bdi', null, value)
919
+ const mono = value => h('code', { dir: 'ltr' }, value)
920
+ const heading = (text, ...children) => h('section', { className: 'dpgsp-group' }, h('h3', null, text), ...children)
921
+ const rowValue = text => h('span', { className: 'dpgsp-rowvalue' }, text)
922
+ const frame = (content, foot, label) => h('section', { className: 'dpgsp-card', 'aria-label': label }, h('div', { className: 'dpgsp-body' }, content), foot)
923
+ const footer = (buttons, guidance) => h('footer', { className: 'dpgsp-foot' }, guidance ? note(guidance, 'shield') : null,
924
+ buttons.some(Boolean) ? h('div', { className: 'dpgsp-actions' }, ...buttons) : null)
925
+ function list(items, makeRow) {
926
+ return h('ul', { className: 'dpgsp-list' }, items.map((item, i) => h('li', { key: i, className: 'dpgsp-row' }, ...makeRow(item))))
927
+ }
928
+ const fileList = (files, t) => list(files, file => [icon('file'), h('div', { className: 'dpgsp-iteminfo' }, mono(file.path)), rowValue(t(file.status))])
929
+ function FileChanges({ p, t }) {
930
+ const changed = p.files.filter(f => f.status !== 'identical')
931
+ const same = p.files.filter(f => f.status === 'identical')
932
+ return h(React.Fragment, null,
933
+ changed.length ? heading(countText(t, 'changeFiles', changed.length), fileList(changed, t)) : null,
934
+ skippedCount(p) ? heading(`${t('retained')} (${skippedCount(p)})`,
935
+ p.dropped.length ? list(p.dropped, f => [icon('file'), h('div', { className: 'dpgsp-iteminfo' }, mono(f.path), hint(codeText(t, 'code', f.code)))]) : null) : null,
936
+ same.length ? details(`${t('showUnchanged')} (${same.length})`, fileList(same, t)) : null)
937
+ }
938
+ function PackageRows({ p, preview, t }) {
939
+ const yes = installable(p)
940
+ const no = p.missing.filter(row => !row.resolvable)
941
+ const add = new Set(preview?.manifest?.bundlesAdded ?? [])
942
+ const enabling = p.installed.filter(name => add.has(name))
943
+ const other = p.installed.filter(name => !add.has(name))
944
+ const group = (rows, resolvable) => list(rows, entry => {
945
+ const spec = resolvable ? entry.installSpec : entry.spec
946
+ // A Git/HTTPS spec can omit the package name. Display the full literal
947
+ // spec, never turn it into a hyperlink, and never invent a registry.
948
+ return [icon('pkg'), h('div', { className: 'dpgsp-iteminfo' },
949
+ !resolvable || !spec.startsWith(`${entry.name}@`) ? h('strong', null, isolated(entry.name)) : null,
950
+ h('div', null, resolvable ? h('span', { className: 'dpgsp-meta' }, sourceKind(entry, t), ' · ') : null, mono(spec ?? t('noSpec'))),
951
+ resolvable ? null : hint(codeText(t, 'note', entry.note))) ]
952
+ })
953
+ const named = values => list(values, value => [icon('pkg'), mono(value)])
954
+ return h(React.Fragment, null,
955
+ yes.length ? heading(countText(t, 'pluginsToInstall', yes.length), group(yes, true)) : null,
956
+ no.length ? heading(`${t('unresolved')} (${no.length})`, group(no, false)) : null,
957
+ enabling.length ? heading(`${t('alreadyEnable')} (${enabling.length})`, named(enabling)) : null,
958
+ other.length ? details(`${t('alreadyOther')} (${other.length})`, named(other)) : null)
959
+ }
960
+ function PlanBody({ plan, t, changeSource }) {
961
+ const p = plan.preview
962
+ const standard = plan.mode === 'standard'
963
+ const unknown = standard && !verifiedInventory(plan.plugins)
964
+ const missing = standard && !unknown ? plan.plugins.missing : []
965
+ const blocked = skippedCount(p) > 0 || missing.some(row => !row.resolvable)
966
+ const work = actionable(plan)
967
+ return h(React.Fragment, null,
968
+ facts([[t('source'), h('div', { className: 'dpgsp-source' },
969
+ h('div', null, isolated([p.sourceProfile, plan.mode === 'local' ? plan.fileName : plan.ref.id].filter(txt).join(' · ')),
970
+ txt(p.createdAt) ? hint(formatTime(p.createdAt)) : null), changeSource)], [t('targetProfile'), isolated(p.profile)]]),
971
+ standard ? null : box(null, h('p', null, t('configScope'))),
972
+ !work && !unknown ? box(blocked ? 'warning' : null,
973
+ blocked ? h('p', null, t('noApplicable')) : h(React.Fragment, null, h('strong', null, t('noChanges')), hint(t(standard ? 'filesPluginsSame' : 'filesSame')))) : null,
974
+ h(FileChanges, { p, t }),
975
+ unknown ? box('warning', h('strong', null, t('cannotVerify')), hint(codeText(t, 'reason', plan.plugins.reason)), h('p', null, t('cannotVerifyHint'))) : null,
976
+ standard && !unknown ? h(PackageRows, { p: plan.plugins, preview: p, t }) : null)
977
+ }
978
+ function PluginReport({ p, t }) {
979
+ if (!p) return null
980
+ const verified = verifiedReport(p)
981
+ const results = Array.isArray(p.results) ? p.results.filter(row => txt(row?.name)) : []
982
+ const scripts = pendingBuilds(p)
983
+ const remaining = Array.isArray(p.missing) ? p.missing.filter(row => txt(row?.name)) : []
984
+ return h('div', { className: 'dpgsp-group' },
985
+ verified ? hint(Object.entries(OUTCOMES).map(([k, label]) => `${t(label)} ${p.outcomeCounts[k]}`).join(' · '))
986
+ : box('warning', h('strong', null, t('pluginUnknown')), hint(codeText(t, 'reason', p.reason))),
987
+ scripts.length ? box('warning', h('strong', null, t('pendingBuilds')), list(scripts, name => [mono(name)]), hint(t('buildHint'))) : null,
988
+ results.length ? list(results, r => [icon('pkg'), h('div', { className: 'dpgsp-iteminfo' },
989
+ h('span', null, isolated(r.name), ' · ', Object.hasOwn(OUTCOMES, r.outcome) ? t(OUTCOMES[r.outcome]) : t('pluginUnknown')),
990
+ txt(r.message) ? hint(r.outcome === 'skipped' ? codeText(t, 'note', r.message) : r.message) : null)]) : null,
991
+ remaining.length ? h('p', null, `${t('stillMissing')}: `, remaining.map(r => r.name).join(', ')) : null)
992
+ }
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'),
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'))
1059
+ const { result: r, mode } = receipt
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
1063
+ return frame(h(React.Fragment, 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,
1070
+ r.warnings?.length ? box('warning', h('strong', null, t('warnings')), list(r.warnings, w => [w])) : null,
1071
+ restartKey ? note([t(restartKey), mode === 'standard' && attention ? t('restartLimit') : null].filter(Boolean).join(' ')) : null,
1072
+ details(t('resultDetails'), h('div', { className: 'dpgsp-stack' },
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)
1077
+ }
1078
+ function ProfileStatus({ profile, stateKey, url, t }) {
1079
+ const [state, setState] = React.useState('idle')
1080
+ const field = React.useRef(null)
1081
+ const alive = React.useRef(false)
1082
+ React.useEffect(() => { alive.current = true; return () => { alive.current = false } }, [])
1083
+ React.useEffect(() => { if (state === 'manual') { field.current?.focus(); field.current?.select() } }, [state])
1084
+ const copy = async () => {
1085
+ try {
1086
+ if (!navigator.clipboard?.writeText) throw Error()
1087
+ await navigator.clipboard.writeText(url)
1088
+ if (alive.current) setState('copied')
1089
+ } catch { if (alive.current) { setState('manual'); field.current?.focus(); field.current?.select() } }
1090
+ }
1091
+ return h('section', { className: 'dpgsp-card', 'aria-label': t('localProfile') },
1092
+ h('div', { className: 'dpgsp-summary' },
1093
+ h('div', { className: 'dpgsp-identity' }, h('span', { className: 'dpgsp-mark' }, icon('pc', 18)),
1094
+ h('div', null, title(t('localProfile')), profile ? h('p', { className: 'dpgsp-subtitle' }, t('profileName'), ': ', isolated(profile)) : null)),
1095
+ h('div', { className: 'dpgsp-status' }, url
1096
+ ? h('span', { tabIndex: -1, 'data-focus': 'backup-receipt' }, t('ready')) : h('span', { role: 'status' }, t(stateKey)),
1097
+ url ? btn('copy', t(state === 'copied' ? 'copied' : 'copyLink'), copy, { glyph: state === 'copied' ? 'check' : 'copy', kind: 'quiet', title: t('copy'), 'aria-label': t('copy') }) : null,
1098
+ h('span', { role: 'status', className: 'dpgsp-sr' }, state === 'copied' ? t('copied') : ''))),
1099
+ state === 'manual' ? h('div', { className: 'dpgsp-copy-feedback dpgsp-group' }, h('p', { role: 'status' }, t('manualCopy')),
1100
+ h('label', { className: 'dpgsp-field' }, t('link'), h('input', { className: 'dpgsp-input', ref: field, readOnly: true, value: url, dir: 'ltr', onFocus: e => e.target.select() }))) : null)
1101
+ }
1102
+ function LocalInventory({ status: s, t }) {
1103
+ return details(t('localInventory'), h('div', { className: 'dpgsp-stack' },
1104
+ heading(`${t('defaultInventory')} (${s.files.length})`, list(s.files, f => [icon('file'), h('div', { className: 'dpgsp-iteminfo' }, mono(f.path)), rowValue(formatBytes(f.bytes))])),
1105
+ heading(`${t('excluded')} (${s.excluded.length})`, list(s.excluded, f => [h('div', { className: 'dpgsp-iteminfo' }, mono(f.path), hint(codeText(t, 'code', f.code)))]))))
1106
+ }
1107
+
1108
+ function Panel({ ctx, t }) {
1109
+ React.useSyncExternalStore(fn => ctx.locale.subscribe(fn), () => ctx.locale.getSnapshot())
1110
+ const uid = React.useId()
1111
+ const root = React.useRef(null)
1112
+ const mounted = React.useRef(false)
1113
+ const flight = React.useRef(null)
1114
+ const selected = React.useRef(null)
1115
+ const focusNext = React.useRef(null)
1116
+ const opener = React.useRef('restore')
1117
+ const fileInput = React.useRef(null)
1118
+ const tokenInput = React.useRef(null)
1119
+ const moreButton = React.useRef(null)
1120
+ const menuList = React.useRef(null)
1121
+ const menuEntry = React.useRef(null)
1122
+ const [page, setPage] = React.useState({ name: 'home' })
1123
+ const [status, setStatus] = React.useState(null)
1124
+ const [statusError, setStatusError] = React.useState(null)
1125
+ const [uploadCheck, setUploadCheck] = React.useState(null)
1126
+ const [busy, setBusy] = React.useState(null)
1127
+ const [issue, setIssue] = React.useState(null)
1128
+ const [menu, setMenu] = React.useState(false)
1129
+ const [sourceDraft, setSourceDraft] = React.useState('')
1130
+ const [targetDraft, setTargetDraft] = React.useState('')
1131
+ const [backupReceipt, setBackupReceipt] = React.useState(null)
1132
+ const [restoreReceipt, setRestoreReceipt] = React.useState(null)
1133
+ const [installReceipt, setInstallReceipt] = React.useState(null)
1134
+ const [announcement, setAnnouncement] = React.useState('')
1135
+
1136
+ // One cancellable read or non-repeatable write at a time. A ref closes the
1137
+ // gap between a button event and React committing its disabled state.
1138
+ async function run(label, write, task, onError) {
1139
+ if (flight.current || !mounted.current) return
1140
+ const job = { write, controller: new AbortController() }
1141
+ const active = () => mounted.current && flight.current === job
1142
+ const call = async (path, body) => {
1143
+ if (!active()) throw fail('cancelled')
1144
+ const data = await api(path, body, job.controller.signal)
1145
+ if (!active()) throw fail('cancelled')
1146
+ return data
1147
+ }
1148
+ flight.current = job
1149
+ setBusy(label)
1150
+ setIssue(null)
1151
+ setAnnouncement('')
1152
+ try { await task(call, active, job.controller.signal) }
1153
+ catch (error) {
1154
+ if (active()) {
1155
+ if (onError) onError(error)
1156
+ else setIssue({ error })
1157
+ }
1158
+ } finally {
1159
+ if (active()) { flight.current = null; setBusy(null) }
1160
+ }
1161
+ }
1162
+ function releaseRead() {
1163
+ const job = flight.current
1164
+ if (job?.write) return false
1165
+ if (job) { flight.current = null; job.controller.abort(); setBusy(null) }
1166
+ return true
1167
+ }
1168
+ function takeToken() {
1169
+ const input = tokenInput.current
1170
+ const value = input?.value.trim() ?? ''
1171
+ if (input) input.value = ''
1172
+ return value ? { token: value } : {}
1173
+ }
1174
+ function move(next, focus = 'title') {
1175
+ // A source or token never lives in a subsequent independent workflow.
1176
+ if (tokenInput.current) tokenInput.current.value = ''
1177
+ selected.current = null
1178
+ setIssue(null)
1179
+ setMenu(false)
1180
+ setSourceDraft('')
1181
+ setTargetDraft('')
1182
+ setAnnouncement('')
1183
+ focusNext.current = focus
1184
+ setPage(next)
1185
+ }
1186
+ function home(focus = opener.current) {
1187
+ if (releaseRead()) move({ name: 'home' }, focus)
1188
+ }
1189
+ async function readStatus(call) {
1190
+ const s = await call('/status')
1191
+ if (!validStatus(s)) throw fail('bad-response')
1192
+ setStatus(s)
1193
+ setStatusError(null)
1194
+ setUploadCheck(null)
1195
+ return s
1196
+ }
1197
+ // This is deliberately isolated from the mutation's try/catch: a failed
1198
+ // local refresh is NOT a failed upload/restore or a reason to replay it.
1199
+ async function afterWrite(call, active) {
1200
+ setBusy('localBusy')
1201
+ try { await readStatus(call) } catch (error) { if (active()) setStatusError(error) }
1202
+ }
1203
+ function retryStatus() {
1204
+ return run('localBusy', false, async call => {
1205
+ const s = await readStatus(call)
1206
+ if (page.name === 'undo') move({ name: 'undo', snapshot: s.undo })
1207
+ else if (page.name === 'backup' || page.name === 'home') move({ name: 'home' }, compatible(s) ? 'backup' : 'title')
1208
+ }, setStatusError)
1209
+ }
1210
+ React.useEffect(() => {
1211
+ mounted.current = true
1212
+ // Mount only reads the local summary. No automatic cloud request,
1213
+ // token lookup, package inventory, install, or settings write.
1214
+ void run('localBusy', false, readStatus, setStatusError)
1215
+ return () => {
1216
+ mounted.current = false
1217
+ if (!flight.current?.write) flight.current?.controller.abort()
1218
+ flight.current = null
1219
+ selected.current = null
1220
+ if (tokenInput.current) tokenInput.current.value = ''
1221
+ }
1222
+ }, [])
1223
+ React.useEffect(() => {
1224
+ const name = focusNext.current
1225
+ if (!name) return
1226
+ const element = root.current?.querySelector(`[data-focus="${name}"]`)
1227
+ if (element?.disabled && busy) return
1228
+ const target = element && !element.disabled ? element : root.current?.querySelector('[data-focus="title"]')
1229
+ if (target) { focusNext.current = null; target.focus() }
1230
+ }, [page, busy, status, issue])
1231
+ const cloud = status?.cloud
1232
+ const targetId = cloud?.gistId ?? null
1233
+ const includeMachine = cloud?.includeMachine === true
1234
+ const stale = !compatible(status) || statusError !== null || uploadCheck !== null
1235
+ const locked = stale || busy !== null
1236
+ const rootAction = (which, action) => () => {
1237
+ if (locked || flight.current) return
1238
+ opener.current = which
1239
+ action()
1240
+ }
1241
+ const repairable = e => e?.code === 'auth' || e?.code === 'rate-limit'
1242
+ const consumedPlanError = e => !['stale-plan', 'busy'].includes(e?.code)
1243
+ const notice = (key, extra = {}) => setIssue({ key, ...extra })
1244
+
1245
+ function sourcePage(mode) {
1246
+ if (releaseRead()) move({ name: 'source', mode }, 'source')
1247
+ }
1248
+ function displayPlan(p) {
1249
+ move({ name: 'preview', mode: p.mode, id: p.ref?.id, fileName: p.fileName, plan: p })
1250
+ selected.current = p
1251
+ setAnnouncement('reviewDone')
1252
+ }
1253
+ function prepare(mode, id, token = {}) {
1254
+ if (stale || flight.current || !bareId(id)) return
1255
+ move({ name: 'preview', mode, id })
1256
+ return run('previewBusy', false, async call => {
1257
+ const data = await call(mode === 'config' ? '/config/preview' : '/sync/preview', { id, ...token })
1258
+ if (!validCloudPlan(data, mode, id) || data.preview.profile !== status.profile) throw fail('bad-response')
1259
+ displayPlan({ ...data, mode })
1260
+ }, error => setIssue({ error, repair: repairable(error) }))
1261
+ }
1262
+ function openRestore(mode) {
1263
+ if (bareId(targetId)) return prepare(mode, targetId)
1264
+ sourcePage(mode)
1265
+ }
1266
+ function sourceSubmit(e) {
1267
+ e.preventDefault()
1268
+ if (locked || flight.current) return
1269
+ const id = sourceId(sourceDraft)
1270
+ if (!id) { focusNext.current = 'source'; setIssue({ error: fail('bad-source') }); return }
1271
+ return prepare(page.mode, id)
1272
+ }
1273
+ function confirmPlan() {
1274
+ const p = selected.current
1275
+ if (locked || flight.current || !p || p !== page.plan || !actionable(p)) return
1276
+ selected.current = null // one-shot; even a lost response needs a new preview
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
+ }))
1287
+ }
1288
+ function chooseFile(event) {
1289
+ const file = event.currentTarget.files?.[0]
1290
+ event.currentTarget.value = ''
1291
+ if (!file || locked || flight.current) return
1292
+ move({ name: 'preview', mode: 'local', fileName: file.name })
1293
+ return run('previewBusy', false, async (call, active) => {
1294
+ // Matches the host's JSON import transport ceiling; the host validates
1295
+ // the actual document and backup byte limits before making a plan.
1296
+ if (file.size > 4 * 1024 * 1024) throw fail('too-large')
1297
+ const text = await file.text()
1298
+ if (!active()) return
1299
+ let backup
1300
+ try { backup = JSON.parse(text) } catch { throw fail('invalidJson') }
1301
+ const r = await call('/preview', { backup, reviewed: true })
1302
+ if (!txt(r.planId) || !filePlan(r.preview) || r.preview.profile !== status.profile || r.ref != null || r.plugins != null) throw fail('bad-response')
1303
+ displayPlan({ mode: 'local', fileName: file.name, planId: r.planId, preview: r.preview })
1304
+ })
1305
+ }
1306
+ function beginUpload(expectedId, expectedMachine, token = {}) {
1307
+ if (locked || flight.current) return
1308
+ let sent = false
1309
+ return run('uploadBusy', true, async (call, active) => {
1310
+ // Verify the displayed destination is still current, including the
1311
+ // distinct “create a new Gist” case. Never use a restore/target draft.
1312
+ const s = await readStatus(call)
1313
+ if (!compatible(s)) throw fail('bad-response')
1314
+ if (s.cloud.gistId !== expectedId || s.cloud.includeMachine !== expectedMachine) {
1315
+ move({ name: 'backup', id: s.cloud.gistId, includeMachine: s.cloud.includeMachine })
1316
+ notice('targetChanged'); return
1317
+ }
1318
+ if (expectedId !== null && !bareId(expectedId)) throw fail('bad-source')
1319
+ sent = true
1320
+ const r = await call('/gist/upload', { expectedTarget: expectedId, includeMachine: expectedMachine, ...token })
1321
+ if (!bareId(r.ref?.id) || (expectedId !== null && r.ref.id !== expectedId) || !number(r.files) || !number(r.bytes)) throw fail('bad-response')
1322
+ setBackupReceipt(r)
1323
+ // The upload receipt confirms the host saved this id; retain the link
1324
+ // even if the GET /status after it fails. Don't invent an upload time.
1325
+ setStatus(old => ({ ...old, cloud: { ...old.cloud, gistId: r.ref.id } }))
1326
+ move({ name: 'home' }, 'backup-receipt')
1327
+ await afterWrite(call, active)
1328
+ }, error => {
1329
+ move({ name: 'backup', id: expectedId, includeMachine: expectedMachine })
1330
+ const repair = sent && repairable(error)
1331
+ const changed = error?.code === 'stale-plan'
1332
+ const unknown = sent && !repair && !['stale-plan', 'notfound', 'too-large', 'busy', 'session-auth'].includes(error?.code)
1333
+ if (changed || unknown) setUploadCheck(changed ? 'targetChanged' : 'uploadUncertain')
1334
+ setIssue(changed ? { key: 'targetChanged' } : { error, repair, uploadUncertain: unknown })
1335
+ })
1336
+ }
1337
+ function backup() {
1338
+ if (targetId === null) return beginUpload(null, includeMachine)
1339
+ move({ name: 'backup', id: targetId, includeMachine })
1340
+ }
1341
+ function openTarget() {
1342
+ move({ name: 'target' }, 'target')
1343
+ setTargetDraft(targetId ?? '')
1344
+ }
1345
+ function saveTarget(e) {
1346
+ e.preventDefault()
1347
+ if (locked || flight.current) return
1348
+ const raw = targetDraft.trim()
1349
+ const id = raw === '' ? null : sourceId(raw)
1350
+ if (raw !== '' && !id) { focusNext.current = 'target'; setIssue({ error: fail('bad-source') }); return }
1351
+ if (id === targetId) return
1352
+ return run('busy', true, async (call, active) => {
1353
+ const r = await call('/settings', { gistId: id ?? '' })
1354
+ if (!r.cloud || r.cloud.gistId !== id || typeof r.cloud.includeMachine !== 'boolean') throw fail('bad-response')
1355
+ setStatus(s => ({ ...s, cloud: r.cloud }))
1356
+ // An old upload is not evidence that a newly linked Gist holds it.
1357
+ setBackupReceipt(old => old?.ref.id === id ? old : null)
1358
+ setTargetDraft(id ?? '')
1359
+ setAnnouncement('targetSaved')
1360
+ await afterWrite(call, active)
1361
+ })
1362
+ }
1363
+ function toggleMachine(value) {
1364
+ if (locked || flight.current) return
1365
+ return run('busy', true, async (call, active) => {
1366
+ const r = await call('/settings', { includeMachine: value })
1367
+ if (r.cloud?.includeMachine !== value) throw fail('bad-response')
1368
+ setStatus(s => ({ ...s, cloud: r.cloud }))
1369
+ setAnnouncement('machineSaved')
1370
+ await afterWrite(call, active)
1371
+ })
1372
+ }
1373
+ function openPlugins() {
1374
+ if (stale || flight.current) return
1375
+ move({ name: 'plugins' })
1376
+ return run('pluginsBusy', false, async call => {
1377
+ const inventory = await call('/plugins')
1378
+ if (!inventoryShape(inventory)) throw fail('bad-response')
1379
+ move({ name: 'plugins', inventory })
1380
+ })
1381
+ }
1382
+ function installPlugins() {
1383
+ const reviewed = page.inventory
1384
+ if (locked || flight.current || !installable(reviewed).length) return
1385
+ let sent = false
1386
+ move({ name: 'plugins' })
1387
+ return run('installBusy', true, async call => {
1388
+ // The standalone endpoint uses the local manifest, not a Gist plan.
1389
+ // If the current inventory no longer matches the review, stop here.
1390
+ const current = await call('/plugins')
1391
+ if (!inventoryShape(current)) throw fail('bad-response')
1392
+ const specs = x => x.missing.map(row => [row.name, row.resolvable, row.installSpec, row.note])
1393
+ if (!verifiedInventory(current) || JSON.stringify(specs(current)) !== JSON.stringify(specs(reviewed))) {
1394
+ move({ name: 'plugins', inventory: current }); notice('inventoryChanged'); return
1395
+ }
1396
+ sent = true
1397
+ const expectedPackages = installable(reviewed).map(({ name, installSpec }) => ({ name, installSpec }))
1398
+ const result = await call('/plugins/install', { expectedPackages })
1399
+ if (typeof result.available !== 'boolean' || !Array.isArray(result.results)) throw fail('bad-response')
1400
+ setInstallReceipt(result)
1401
+ move({ name: 'plugins', showResult: true })
1402
+ }, error => setIssue({ error, uncertain: sent && consumedPlanError(error) }))
1403
+ }
1404
+ function openUndo(expectedStamp = null) {
1405
+ if (stale || flight.current) return
1406
+ move({ name: 'undo' })
1407
+ return run('localBusy', false, async call => {
1408
+ const s = await readStatus(call)
1409
+ if (expectedStamp && s.undo?.stamp !== expectedStamp) { move({ name: 'home' }, 'restore-receipt'); setIssue({ error: fail('stale-plan') }); return }
1410
+ move({ name: 'undo', snapshot: s.undo })
1411
+ })
1412
+ }
1413
+ function doUndo() {
1414
+ if (locked || flight.current || !page.snapshot?.stamp) return
1415
+ const reviewed = page.snapshot
1416
+ let sent = false
1417
+ move({ name: 'undo' })
1418
+ return run('undoBusy', true, async (call, active) => {
1419
+ const s = await readStatus(call)
1420
+ if (!compatible(s) || s.undo?.stamp !== reviewed.stamp || s.undo.files !== reviewed.files) {
1421
+ move({ name: 'home' }, 'more'); setIssue({ error: fail('stale-plan') }); return
1422
+ }
1423
+ sent = true
1424
+ const r = await call('/undo', { expectedStamp: reviewed.stamp })
1425
+ if (r.report?.stamp !== reviewed.stamp || !number(r.report.reverted)) throw fail('bad-response')
1426
+ setRestoreReceipt({ mode: 'undo', profile: s.profile, reverted: r.report.reverted })
1427
+ move({ name: 'home' }, 'restore-receipt')
1428
+ await afterWrite(call, active)
1429
+ }, error => setIssue({ error, uncertain: sent && consumedPlanError(error) }))
1430
+ }
1431
+
1432
+ const alerts = (omitBusy = false) => h(React.Fragment, null,
1433
+ uploadCheck && page.name !== 'backup' ? box('warning', h('p', { role: 'alert' }, t(uploadCheck)), h('div', { className: 'dpgsp-actions' }, btn('retry-status', t('statusRetry'), retryStatus, { disabled: !!busy }))) : null,
1434
+ statusError ? h('div', { className: 'dpgsp-box dpgsp-warning', role: 'alert' },
1435
+ h('strong', null, t(status ? 'refreshFailed' : 'hostMissing')), hint(errorText(t, statusError)),
1436
+ h('div', { className: 'dpgsp-actions' }, btn('retry-status', t('statusRetry'), retryStatus, { disabled: !!busy }))) : null,
1437
+ issue ? h('div', { className: `dpgsp-box dpgsp-${issue.error ? 'alert' : 'warning'}`, role: issue.error ? 'alert' : 'status' },
1438
+ issue.error ? h('p', null, errorText(t, issue.error)) : null, issue.key ? h('p', null, t(issue.key)) : null,
1439
+ issue.uncertain ? h('p', null, t('uncertain')) : null, issue.uploadUncertain ? h('p', null, t('uploadUncertain')) : null) : null,
1440
+ busy && !omitBusy ? h('p', { className: 'dpgsp-hint', role: 'status' }, t(busy)) : null)
1441
+ const isWrite = flight.current?.write === true
1442
+ const cancel = (back = false) => btn('cancel', t(back ? 'back' : 'cancel'), () => home(), { disabled: isWrite })
1443
+ const formId = `${uid}-form`
1444
+ const showRepair = issue?.repair === true && (page.name === 'backup' || (page.name === 'preview' && page.mode !== 'local'))
1445
+ const retryCloudRead = () => prepare(page.mode, page.id, takeToken())
1446
+ const retryUpload = () => beginUpload(page.id, page.includeMachine, takeToken())
1447
+ const repairView = retry => !showRepair ? null : h('form', { id: `${uid}-repair`, className: 'dpgsp-box', onSubmit: e => { e.preventDefault(); retry() } },
1448
+ h('h3', null, t('repair')), hint(t('tokenHelp')),
1449
+ h('div', { className: 'dpgsp-field' }, h('label', { htmlFor: `${uid}-token` }, t('tokenLabel')),
1450
+ h('input', { type: 'password', className: 'dpgsp-input', id: `${uid}-token`, ref: tokenInput, autoComplete: 'off', spellCheck: false, autoCapitalize: 'none',
1451
+ disabled: locked, 'aria-describedby': `${uid}-token-help` })),
1452
+ h('p', { className: 'dpgsp-hint', id: `${uid}-token-help` }, t('tokenPrivacy'), ' ', t('authRetry')))
1453
+ const retryProps = showRepair ? { type: 'submit', form: `${uid}-repair` } : {}
1454
+ const goMore = (key, action, glyph) => btn(key, t(key), rootAction('more', action), { kind: 'quiet', glyph, disabled: locked })
1455
+ // Ordinary disclosure: Tab walks the visible buttons. Arrow keys are a
1456
+ // convenience; focus and selection never leave this component's own list.
1457
+ const menuItems = () => Array.from(menuList.current?.querySelectorAll('button:not(:disabled)') ?? [])
1458
+ React.useEffect(() => {
1459
+ if (menu && menuEntry.current) {
1460
+ const items = menuItems()
1461
+ items[menuEntry.current === 'last' ? items.length - 1 : 0]?.focus()
1462
+ }
1463
+ menuEntry.current = null
1464
+ }, [menu])
1465
+ function menuKeys(e) {
1466
+ if (locked || flight.current || e.defaultPrevented || e.nativeEvent?.isComposing || e.altKey || e.ctrlKey || e.metaKey) return
1467
+ const fromButton = e.target === moreButton.current
1468
+ if (!['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(e.key) || (!menu && (!fromButton || !e.key.startsWith('Arrow')))) return
1469
+ e.preventDefault(); e.stopPropagation()
1470
+ if (!menu) { opener.current = 'more'; menuEntry.current = e.key === 'ArrowUp' ? 'last' : 'first'; setMenu(true); return }
1471
+ const items = menuItems()
1472
+ if (!items.length) return
1473
+ const i = items.indexOf(e.target)
1474
+ const next = e.key === 'Home' ? 0 : e.key === 'End' ? items.length - 1 : e.key === 'ArrowDown' ? (i + 1) % items.length : (i > 0 ? i - 1 : items.length - 1)
1475
+ items[next]?.focus()
1476
+ }
1477
+ function menuView() {
1478
+ return h('div', { className: 'dpgsp-menuwrap', onKeyDown: menuKeys, onBlur: e => { if (!e.currentTarget.contains(e.relatedTarget)) setMenu(false) } },
1479
+ btn('more', h(React.Fragment, null, t('more'), icon('chevron', 13)), rootAction('more', () => setMenu(v => !v)), { kind: 'quiet', ref: moreButton, 'data-focus': 'more',
1480
+ 'aria-expanded': menu, 'aria-controls': menu ? `${uid}-more` : undefined, disabled: locked }),
1481
+ menu ? h('nav', { id: `${uid}-more`, ref: menuList, className: 'dpgsp-menulist', 'aria-label': t('more') },
1482
+ goMore('local', () => move({ name: 'local' }), 'file'), goMore('configMode', () => openRestore('config'), 'down'),
1483
+ goMore('install', openPlugins, 'pkg'), goMore('target', openTarget, 'arrow'), goMore('diagnostics', () => move({ name: 'diagnostics' }), 'info'),
1484
+ status?.undo ? goMore('undo', () => openUndo(), 'shield') : null) : null)
1485
+ }
1486
+ const linkView = id => {
1487
+ const href = gistLink({ id })
1488
+ return href ? h('a', { className: 'dpgsp-link', href, target: '_blank', rel: 'noopener noreferrer', referrerPolicy: 'no-referrer' }, href) : isolated(id ?? t('newGist'))
1489
+ }
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
+ }
1511
+ const intro = (key, subtitle) => h('header', null, title(t(key)), subtitle ? h('p', { className: 'dpgsp-intro' }, t(subtitle)) : null)
1512
+ function homeView() {
1513
+ const uploaded = targetId && backupReceipt?.ref?.id === targetId ? backupReceipt : null
1514
+ const history = cloud?.lastUpload
1515
+ const readyUrl = uploaded ? gistLink(uploaded.ref) : (bareId(targetId) && history?.gistId === targetId && txt(history.at) && number(history.files)
1516
+ ? gistLink({ id: targetId }) : null)
1517
+ const dropped = Array.isArray(uploaded?.dropped) ? uploaded.dropped.filter(row => txt(row?.name)) : []
1518
+ const normal = status && compatible(status)
1519
+ const stateKey = !normal ? (!status && !statusError ? 'localBusy' : 'unavailable') : targetId ? 'linked' : history ? 'unlinked' : 'noneYet'
1520
+ const homeFooter = normal ? h('footer', { className: 'dpgsp-homefoot' }, menuView(),
1521
+ h('a', { className: 'dpgsp-help', href: GUIDE, target: '_blank', rel: 'noopener noreferrer', referrerPolicy: 'no-referrer', 'aria-label': t('openGuide') }, t('help'), icon('external', 12)),
1522
+ h('div', { className: 'dpgsp-actions' },
1523
+ btn('restore', t('restore'), rootAction('restore', () => openRestore('standard')), { disabled: locked, 'data-focus': 'restore' }),
1524
+ btn('backup', t('backup'), rootAction('backup', backup), { kind: 'primary', disabled: locked, 'data-focus': 'backup' }))) : null
1525
+ return h(React.Fragment, null,
1526
+ h(ProfileStatus, { key: (normal && readyUrl) || 'local', profile: status?.profile, stateKey, url: normal ? readyUrl : null, t }),
1527
+ normal ? frame(h(React.Fragment, null,
1528
+ facts([[t('backupContents'), t('contents')], [t('uploadTarget'), t(targetId === null ? 'newGist' : 'linkedGist')]]),
1529
+ note([targetId ? t('overwriteHint') : null, t('privacy')].filter(Boolean).join(' '), 'shield')), homeFooter) : null,
1530
+ statusError || issue || uploadCheck || (status && (busy || !normal)) ? frame(h(React.Fragment, null,
1531
+ alerts(!status && !statusError), status && !normal ? box('warning', h('p', null, t('staleHost')),
1532
+ h('div', { className: 'dpgsp-actions' }, btn('retry-status', t('statusRetry'), retryStatus, { disabled: !!busy }))) : null)) : null,
1533
+ normal && dropped.length ? frame(details(`${t('droppedDeps')} (${uploaded.droppedEntries ?? dropped.length})`, list(dropped, row => [isolated(row.name), mono(row.spec ?? '')]))) : null,
1534
+ normal && restoreReceipt ? receiptView() : null)
1535
+ }
1536
+ function sourceView() {
1537
+ return frame(h(React.Fragment, null, intro(page.mode === 'config' ? 'configMode' : 'restore', 'sourceIntro'),
1538
+ page.mode === 'config' ? note(t('configScope'), 'shield') : null,
1539
+ h('form', { id: formId, onSubmit: sourceSubmit, className: 'dpgsp-group' }, h('div', { className: 'dpgsp-field' },
1540
+ h('label', { htmlFor: `${uid}-source` }, t('sourceLabel')), h('input', { id: `${uid}-source`, className: 'dpgsp-input', 'data-focus': 'source',
1541
+ type: 'text', inputMode: 'url', autoComplete: 'off', spellCheck: false, autoCapitalize: 'none', placeholder: t('sourcePlaceholder'), value: sourceDraft, disabled: locked,
1542
+ 'aria-describedby': `${uid}-source-help`, 'aria-invalid': issue?.error?.code === 'bad-source' || undefined,
1543
+ onChange: e => { setSourceDraft(e.target.value); setIssue(null) } })),
1544
+ h('p', { id: `${uid}-source-help`, className: 'dpgsp-hint' }, t('newMachineStep1'))), alerts()),
1545
+ footer([cancel(), btn('preview', t('next'), undefined, { kind: 'primary', type: 'submit', form: formId, disabled: locked || !sourceDraft.trim() })]))
1546
+ }
1547
+ function previewView() {
1548
+ const p = page.plan
1549
+ const local = page.mode === 'local'
1550
+ const standard = page.mode === 'standard'
1551
+ const canApply = actionable(p)
1552
+ const n = installable(p?.plugins).length
1553
+ const confirmLabel = standard && n > 0 ? countText(t, n === 1 ? 'confirmOne' : 'confirmCombined', n) : t(standard ? 'confirmFiles' : 'confirmConfig')
1554
+ const buttons = [cancel(!!p && !canApply)]
1555
+ if (p && canApply) buttons.push(btn('confirm', confirmLabel, confirmPlan, { kind: 'primary', disabled: locked }))
1556
+ else if (!busy && (!p || (standard && !verifiedInventory(p.plugins)))) {
1557
+ buttons.push(local ? btn('choose-again', t('chooseAgain'), () => move({ name: 'local' }, 'pick'), { kind: 'primary', disabled: locked })
1558
+ : btn('preview', t('previewAgain'), showRepair ? undefined : retryCloudRead, { kind: 'primary', disabled: locked, ...retryProps }))
1559
+ }
1560
+ const changeSource = !local && !isWrite ? btn('change-source', t('changeSource'), () => sourcePage(page.mode), { kind: 'quiet' }) : null
1561
+ return frame(h(React.Fragment, null, intro(standard ? 'previewTitle' : local ? 'localPreview' : 'configPreview'),
1562
+ p ? h(PlanBody, { plan: p, t, changeSource }) : h('div', { className: 'dpgsp-source' }, `${t('source')}: `, isolated(local ? page.fileName : page.id), changeSource),
1563
+ alerts(), repairView(retryCloudRead),
1564
+ p && canApply ? hint(t('undoLimit')) : null),
1565
+ footer(buttons, canApply ? t(standard ? 'standardTrust' : 'configTrust') : null))
1566
+ }
1567
+ function backupView() {
1568
+ const brokenId = page.id !== null && !bareId(page.id)
1569
+ const mustRead = uploadCheck !== null
1570
+ const primary = mustRead ? btn('retry-status', t('statusRetry'), retryStatus, { kind: 'primary', disabled: !!busy })
1571
+ : btn('confirm-backup', t(page.id === null ? 'backup' : 'uploadConfirm'), showRepair ? undefined : retryUpload,
1572
+ { kind: 'primary', disabled: locked || brokenId, ...retryProps })
1573
+ return frame(h(React.Fragment, null, intro(page.id === null ? 'backup' : 'overwriteReview', 'uploadScope'),
1574
+ facts([[t('uploadTarget'), linkView(page.id)], [t('targetProfile'), status?.profile]]),
1575
+ note([page.id ? t('visibilityKept') : null, t('privacy')].filter(Boolean).join(' '), 'shield'),
1576
+ hint(t(page.includeMachine ? 'machineIncluded' : 'machineExcluded')),
1577
+ status ? h(LocalInventory, { status, t }) : null, alerts(), repairView(retryUpload)), footer([cancel(), primary]))
1578
+ }
1579
+ function localView() {
1580
+ return frame(h(React.Fragment, null, intro('local', 'localHint'),
1581
+ h('p', null, t('configScope')), note(t(includeMachine ? 'machineIncluded' : 'machineExcluded')),
1582
+ h('input', { type: 'file', hidden: true, accept: '.json,application/json', ref: fileInput, onChange: chooseFile }), alerts()),
1583
+ footer([cancel(true), !locked ? h('a', { className: 'dpgsp-btn', 'data-action': 'export', href: `${API}/export${includeMachine ? '?include=machine' : ''}`, download: true }, t('export')) : null,
1584
+ btn('pick-file', t('import'), () => fileInput.current?.click(), { kind: 'primary', disabled: locked, 'data-focus': 'pick' })]))
1585
+ }
1586
+ function pluginsView() {
1587
+ const p = page.inventory
1588
+ const n = installable(p).length
1589
+ const result = page.showResult ? installReceipt : null
1590
+ const buttons = [cancel(!n)]
1591
+ if (n) buttons.push(btn('confirm-install', countText(t, n === 1 ? 'installOne' : 'installConfirm', n), installPlugins, { kind: 'primary', disabled: locked }))
1592
+ else if (!busy) buttons.push(btn('check-plugins', t('refreshInventory'), openPlugins, { disabled: locked }))
1593
+ return frame(h(React.Fragment, null, intro('install', 'installHint'), alerts(),
1594
+ p && !verifiedInventory(p) ? box('warning', h('strong', null, t('installUnknown')), hint(codeText(t, 'reason', p.reason))) : null,
1595
+ verifiedInventory(p) ? h(React.Fragment, null, !p.missing.length ? box(null, h('p', null, t('allPresent'))) : null, h(PackageRows, { p, t })) : null,
1596
+ result ? heading(t('pluginResults'), h(PluginReport, { p: result, t }), result.restart ? hint(t('restart')) : null) : null),
1597
+ footer(buttons, n ? t('installTrust') : null))
1598
+ }
1599
+ function targetView() {
1600
+ const raw = targetDraft.trim()
1601
+ const nextId = sourceId(raw)
1602
+ return frame(h(React.Fragment, null, intro('target', 'targetHint'), facts([[t('uploadTarget'), linkView(targetId)]]),
1603
+ h('form', { id: formId, onSubmit: saveTarget, className: 'dpgsp-field' }, h('label', { htmlFor: `${uid}-target` }, t('targetInput')),
1604
+ h('input', { id: `${uid}-target`, className: 'dpgsp-input', type: 'text', inputMode: 'url', autoComplete: 'off', autoCapitalize: 'none', spellCheck: false,
1605
+ value: targetDraft, 'data-focus': 'target', 'aria-invalid': issue?.error?.code === 'bad-source' || undefined, disabled: locked, placeholder: t('targetEmpty'),
1606
+ onChange: e => { setTargetDraft(e.target.value); setIssue(null); setAnnouncement('') } })),
1607
+ !raw || nextId ? box(null, facts([[t('targetNew'), linkView(nextId)]]), nextId ? hint(t('targetWarning')) : null) : null,
1608
+ alerts()), footer([cancel(), btn('save-target', t('saveTarget'), undefined, { type: 'submit', form: formId, kind: 'primary', disabled: locked || (raw ? nextId === targetId && nextId !== null : targetId === null) })]))
1609
+ }
1610
+ function diagnosticsView() {
1611
+ const stamp = record => txt(record?.at) ? [formatTime(record.at), bareId(record.gistId) ? record.gistId : null,
1612
+ number(record.files) ? countText(t, 'fileCount', record.files) : null].filter(Boolean).join(' · ') : t('never')
1613
+ return frame(h(React.Fragment, null, intro('diagnostics', 'diagnosticsHint'),
1614
+ facts([[t('targetProfile'), status.profile], [t('profileRoot'), status.root], [t('settingsFile'), cloud.settingsFile],
1615
+ [t('configFiles'), `${status.counts.files} · ${formatBytes(status.counts.bytes)}`], [t('lastUpload'), stamp(cloud.lastUpload)], [t('lastSync'), stamp(cloud.lastSync)],
1616
+ status.limits && [t('limits'), `${formatBytes(status.limits.maxBackupBytes)} / ${formatBytes(status.limits.gistMaxBytes)}`]]),
1617
+ h('label', { className: 'dpgsp-check' }, h('input', { type: 'checkbox', checked: includeMachine, disabled: locked, onChange: e => toggleMachine(e.target.checked) }), t('includeMachine')),
1618
+ h(LocalInventory, { status, t }), alerts()), footer([cancel(true), btn('retry-status', t('statusRetry'), retryStatus, { disabled: !!busy })]))
1619
+ }
1620
+ function undoView() {
1621
+ const s = page.snapshot
1622
+ const buttons = [cancel(!s)]
1623
+ if (s?.stamp && s.files > 0) buttons.push(btn('confirm-undo', t('undoConfirm'), doUndo, { kind: 'primary', disabled: locked }))
1624
+ else if (!busy) buttons.push(btn('retry-status', t('statusRetry'), retryStatus, { disabled: !!busy }))
1625
+ return frame(h(React.Fragment, null, intro('undo'), s ? h(React.Fragment, null,
1626
+ facts([[t('targetProfile'), status.profile], [t('undoWhen'), formatTime(s.createdAt)], [t('configFiles'), String(s.files)]]),
1627
+ box('warning', h('strong', null, t('undoLimit')), h('p', null, t('undoScope')))) : page.snapshot === null ? hint(t('undoNone')) : null,
1628
+ alerts()), footer(buttons))
1629
+ }
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) : ''
1634
+ return h('div', { ref: root, className: 'dpgsp-root', 'data-view': visible, 'data-mode': page.mode,
1635
+ onKeyDown: e => {
1636
+ if (e.key !== 'Escape' || e.defaultPrevented || e.nativeEvent?.isComposing) return
1637
+ if (page.name === 'receipt') { e.preventDefault(); e.stopPropagation(); leaveReceipt(); return }
1638
+ if (flight.current?.write) { e.preventDefault(); e.stopPropagation(); return }
1639
+ if (menu) { e.preventDefault(); e.stopPropagation(); setMenu(false); moreButton.current?.focus() }
1640
+ else if (page.name !== 'home') { e.preventDefault(); e.stopPropagation(); home() }
1641
+ } }, h('style', null, CSS), views[visible](),
1642
+ h('p', { className: !announcement || announcement === 'reviewDone' ? 'dpgsp-sr' : 'dpgsp-hint', role: 'status', 'aria-live': 'polite', 'aria-atomic': true }, liveText))
1643
+ }
1644
+ return {
1645
+ inject: ['slots', 'locale'],
1646
+ apply(ctx) {
1647
+ ctx.effect(() => ctx.locale.register(NS, DICT), `${NS}: dictionaries`)
1648
+ const t = ctx.locale.bind(NS)
1649
+ ctx.slots.inject('settings.section', () => ctx.slots.register({
1650
+ name: 'settings.section', id: NS, order: SECTION_ORDER, label: () => t('section'), locale: NS,
1651
+ }, () => h(Panel, { ctx, t })))
1652
+ // The shell owns the nav button, selection, size and label. This optional
1653
+ // decorative seat is matched by section id; it does not add a page.
1654
+ ctx.slots.inject('settings.section.icon', () => ctx.slots.register({ name: 'settings.section.icon', id: NS }, ({ size }) => icon('sync', size)))
1655
+ },
1656
+ }
1657
+ },
1658
+ })