dsh-builtin-browser 1.0.3 → 1.0.4

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.
Files changed (293) hide show
  1. package/README.en.md +89 -0
  2. package/browser-extension/constants.mjs +20 -0
  3. package/browser-extension/controller.mjs +293 -0
  4. package/browser-extension/locales.mjs +15 -0
  5. package/browser-extension/manifest.json +12 -0
  6. package/browser-extension/options.html +14 -0
  7. package/browser-extension/options.mjs +9 -0
  8. package/browser-extension/permission-guard.mjs +13 -0
  9. package/browser-extension/worker.mjs +74 -0
  10. package/package.json +20 -2
  11. package/scripts/build-client.mjs +305 -0
  12. package/scripts/build.mjs +69 -0
  13. package/scripts/bundle-host.mjs +28 -0
  14. package/scripts/fix-exports.mjs +40 -0
  15. package/scripts/install-electron.mjs +101 -0
  16. package/scripts/pack.mjs +99 -0
  17. package/scripts/publish-manifest.mjs +56 -0
  18. package/scripts/verify-exports.mjs +58 -0
  19. package/scripts/verify-preview-sdk.mjs +93 -0
  20. package/skills/dsh-builtin-browser/SKILL.md +98 -0
  21. package/skills/dsh-builtin-browser/references/batch.md +68 -0
  22. package/skills/dsh-builtin-browser/references/deliver.md +31 -0
  23. package/skills/dsh-builtin-browser/references/locate.md +11 -0
  24. package/skills/dsh-builtin-browser/references/recover.md +11 -0
  25. package/skills/dsh-builtin-browser/references/verify.md +13 -0
  26. package/skills/dsh-debug-host/SKILL.md +56 -0
  27. package/skills/dsh-debug-self/SKILL.md +50 -0
  28. package/src/bridge-compatibility.ts +39 -0
  29. package/src/browser/anti-bot.ts +251 -0
  30. package/src/browser/deep-dom.ts +40 -0
  31. package/src/browser/handles.ts +89 -0
  32. package/src/browser/runtime.ts +578 -0
  33. package/src/browser/takeover-target.ts +45 -0
  34. package/src/browser/types.ts +870 -0
  35. package/src/browser-electron/authenticated-route.ts +109 -0
  36. package/src/browser-electron/automatic-maintenance.ts +736 -0
  37. package/src/browser-electron/bridge-auto.ts +159 -0
  38. package/src/browser-electron/bridge-connection.ts +386 -0
  39. package/src/browser-electron/bridge-endpoint.ts +129 -0
  40. package/src/browser-electron/bridge-install.ts +290 -0
  41. package/src/browser-electron/bridge-maintenance.ts +189 -0
  42. package/src/browser-electron/bridge-status.ts +386 -0
  43. package/src/browser-electron/desktop-bridge-host.ts +253 -0
  44. package/src/browser-electron/desktop-identity.ts +353 -0
  45. package/src/browser-electron/desktop-shell.ts +100 -0
  46. package/src/browser-electron/document-readiness.ts +45 -0
  47. package/src/browser-electron/electron-provision.ts +347 -0
  48. package/src/browser-electron/entry.ts +1378 -0
  49. package/src/browser-electron/ephemeral-profile.ts +189 -0
  50. package/src/browser-electron/extension-browser.ts +230 -0
  51. package/src/browser-electron/extension-setup.ts +67 -0
  52. package/src/browser-electron/file-write.ts +31 -0
  53. package/src/browser-electron/foreground-watch.ts +142 -0
  54. package/src/browser-electron/guest-cookie-jar.ts +177 -0
  55. package/src/browser-electron/guest-cookie-store.ts +59 -0
  56. package/src/browser-electron/guest-css-runtime.ts +76 -0
  57. package/src/browser-electron/guest-css.ts +68 -0
  58. package/src/browser-electron/guest-route.ts +716 -0
  59. package/src/browser-electron/guest-runtime.ts +408 -0
  60. package/src/browser-electron/guest-storage-runtime.ts +54 -0
  61. package/src/browser-electron/guest-storage.ts +120 -0
  62. package/src/browser-electron/history-store.ts +224 -0
  63. package/src/browser-electron/host-main.ts +1385 -0
  64. package/src/browser-electron/host-patch-maintenance.ts +121 -0
  65. package/src/browser-electron/http-body.ts +65 -0
  66. package/src/browser-electron/json-reply.ts +47 -0
  67. package/src/browser-electron/maintenance-broker.ts +166 -0
  68. package/src/browser-electron/maintenance-lifecycle.ts +91 -0
  69. package/src/browser-electron/maintenance-route.ts +68 -0
  70. package/src/browser-electron/missing-system-browser.ts +114 -0
  71. package/src/browser-electron/open-slot.ts +49 -0
  72. package/src/browser-electron/paths.ts +25 -0
  73. package/src/browser-electron/preferred-browser.ts +130 -0
  74. package/src/browser-electron/preview-route.ts +215 -0
  75. package/src/browser-electron/process-ownership.ts +174 -0
  76. package/src/browser-electron/process.ts +23 -0
  77. package/src/browser-electron/profile-checkpoint.ts +187 -0
  78. package/src/browser-electron/profile-command.ts +47 -0
  79. package/src/browser-electron/profile-extension.ts +129 -0
  80. package/src/browser-electron/profile-lease.ts +211 -0
  81. package/src/browser-electron/profile-residue.ts +49 -0
  82. package/src/browser-electron/provider-core.ts +1107 -0
  83. package/src/browser-electron/provider-interaction.ts +1034 -0
  84. package/src/browser-electron/provider-media.ts +589 -0
  85. package/src/browser-electron/provider-navigation.ts +323 -0
  86. package/src/browser-electron/provider-observation.ts +664 -0
  87. package/src/browser-electron/provider-tabs.ts +372 -0
  88. package/src/browser-electron/provider.ts +666 -0
  89. package/src/browser-electron/reference-route.ts +598 -0
  90. package/src/browser-electron/remote-host.ts +1538 -0
  91. package/src/browser-electron/rpc-input.ts +13 -0
  92. package/src/browser-electron/rpc-ops.ts +41 -0
  93. package/src/browser-electron/runtime-diagnostics.ts +38 -0
  94. package/src/browser-electron/runtime-route.ts +105 -0
  95. package/src/browser-electron/runtime-status.ts +309 -0
  96. package/src/browser-electron/settings-route.ts +64 -0
  97. package/src/browser-electron/settings-store.ts +593 -0
  98. package/src/browser-electron/shortcuts-route.ts +112 -0
  99. package/src/browser-electron/sidebar-only-host.ts +300 -0
  100. package/src/browser-electron/startpage-shortcuts.ts +213 -0
  101. package/src/browser-electron/system-browser.ts +1850 -0
  102. package/src/browser-electron/tauri-host.ts +194 -0
  103. package/src/browser-electron/timing.ts +16 -0
  104. package/src/browser-electron/virtual-cursor.ts +162 -0
  105. package/src/browser-electron/windows-system.ts +24 -0
  106. package/src/browser-reference/delivery.ts +384 -0
  107. package/src/browser-reference/entry.ts +631 -0
  108. package/src/browser-reference/export.ts +339 -0
  109. package/src/browser-reference/import.ts +303 -0
  110. package/src/browser-reference/page-script.ts +1537 -0
  111. package/src/browser-reference/service.ts +1346 -0
  112. package/src/browser-reference/store.ts +172 -0
  113. package/src/browser-reference/text-quote.ts +219 -0
  114. package/src/browser-reference/types.ts +195 -0
  115. package/src/browser-reference/visible.ts +367 -0
  116. package/src/browser-reference/web-sources.ts +106 -0
  117. package/src/client/apply-guard.ts +22 -0
  118. package/src/client/browser/BrowserController.ts +693 -0
  119. package/src/client/browser/BrowserFrame.ts +78 -0
  120. package/src/client/browser/BrowserNavigation.ts +169 -0
  121. package/src/client/browser/BrowserPage.ts +23 -0
  122. package/src/client/browser/BrowserPersistence.ts +44 -0
  123. package/src/client/browser/IframeImpl.ts +182 -0
  124. package/src/client/browser/child-tabs.ts +14 -0
  125. package/src/client/browser/frame-history.ts +125 -0
  126. package/src/client/browser/frame-state.ts +27 -0
  127. package/src/client/browser/iframe-reference.ts +67 -0
  128. package/src/client/browser/initialization.ts +262 -0
  129. package/src/client/browser/omnibox.ts +243 -0
  130. package/src/client/browser/store.ts +38 -0
  131. package/src/client/browser/takeover-channel.ts +72 -0
  132. package/src/client/browser/url.ts +46 -0
  133. package/src/client/browser/web-reference-source.ts +56 -0
  134. package/src/client/css-modules.d.ts +4 -0
  135. package/src/client/definition.tsx +36 -0
  136. package/src/client/electron/ElectronWebViewImpl.ts +371 -0
  137. package/src/client/electron/ElectronWebviewPresentation.ts +140 -0
  138. package/src/client/electron/NativeChildPresentation.ts +53 -0
  139. package/src/client/electron/NativeViewPage.ts +265 -0
  140. package/src/client/electron/pages.ts +23 -0
  141. package/src/client/electron/reference-overlay.ts +53 -0
  142. package/src/client/electron/workspace.ts +33 -0
  143. package/src/client/index.ts +333 -0
  144. package/src/client/locales.ts +860 -0
  145. package/src/client/pages.ts +28 -0
  146. package/src/client/reference/client/BrowserRefLink.tsx +142 -0
  147. package/src/client/reference/client/draft-reference.ts +167 -0
  148. package/src/client/reference/client/index.ts +7 -0
  149. package/src/client/reference/client/ordered-submission.ts +108 -0
  150. package/src/client/reference/client/pending-delivery.ts +216 -0
  151. package/src/client/reference/client/plugin.ts +208 -0
  152. package/src/client/reference/client/production/ReferenceCapsules.tsx +345 -0
  153. package/src/client/reference/client/production/ReferenceDock.module.css +193 -0
  154. package/src/client/reference/client/production/ReferenceDock.tsx +6 -0
  155. package/src/client/reference/client/production/ReferenceFeedback.tsx +15 -0
  156. package/src/client/reference/client/production/ReferenceMath.tsx +44 -0
  157. package/src/client/reference/client/production/ReferenceText.tsx +36 -0
  158. package/src/client/reference/client/production/assembly.ts +447 -0
  159. package/src/client/reference/client/production/asset-store.ts +144 -0
  160. package/src/client/reference/client/production/availability.ts +72 -0
  161. package/src/client/reference/client/production/bytes.ts +36 -0
  162. package/src/client/reference/client/production/composer-attachments.ts +44 -0
  163. package/src/client/reference/client/production/delivery-client.ts +211 -0
  164. package/src/client/reference/client/production/draft-adapter.ts +512 -0
  165. package/src/client/reference/client/production/http-transport.ts +212 -0
  166. package/src/client/reference/client/production/production-submission.ts +70 -0
  167. package/src/client/reference/client/production/protocol.ts +234 -0
  168. package/src/client/reference/client/production/reference-card.ts +240 -0
  169. package/src/client/reference/client/production/reference-labels.ts +29 -0
  170. package/src/client/reference/client/production/reply-link-bridge.ts +222 -0
  171. package/src/client/reference/client/production/reveal.ts +215 -0
  172. package/src/client/reference/client/production/runtime.ts +1056 -0
  173. package/src/client/reference/client/production/snapshot-adapter.ts +154 -0
  174. package/src/client/reference/client/production/source-marker.ts +99 -0
  175. package/src/client/reference/client/production/source-opener.ts +55 -0
  176. package/src/client/reference/client/production/styles.ts +104 -0
  177. package/src/client/reference/client/production/user-text-rule.ts +67 -0
  178. package/src/client/reference/client/reveal.ts +109 -0
  179. package/src/client/reference/client/scheme.ts +114 -0
  180. package/src/client/reference/client/session-schedule.ts +36 -0
  181. package/src/client/reference/client/types.ts +168 -0
  182. package/src/client/reference/css-modules.d.ts +4 -0
  183. package/src/client/reference/index.ts +11 -0
  184. package/src/client/reference-capture-owner.ts +162 -0
  185. package/src/client/reference-intents.ts +36 -0
  186. package/src/client/settings/index.ts +42 -0
  187. package/src/client/settings/mount-guard.ts +31 -0
  188. package/src/client/settings/panel.ts +2768 -0
  189. package/src/client/shortcut-open.ts +30 -0
  190. package/src/client/startpage/binding.ts +99 -0
  191. package/src/client/startpage/controller.ts +300 -0
  192. package/src/client/startpage/model.ts +279 -0
  193. package/src/client/view/Browser.module.css +751 -0
  194. package/src/client/view/BrowserBody.tsx +315 -0
  195. package/src/client/view/BrowserPresentation.ts +9 -0
  196. package/src/client/view/BrowserTitle.tsx +17 -0
  197. package/src/client/view/IframePresentation.ts +365 -0
  198. package/src/client/view/StartPage.tsx +598 -0
  199. package/src/client/view/TakeoverBanner.tsx +21 -0
  200. package/src/compat/host-features.ts +92 -0
  201. package/src/index.ts +110 -0
  202. package/src/reference-owner.ts +5 -0
  203. package/src/reference-page.ts +9 -0
  204. package/src/reference-source.ts +3 -0
  205. package/src/reference-text.ts +219 -0
  206. package/src/startpage-settings.ts +103 -0
  207. package/src/startpage.ts +71 -0
  208. package/src/takeover-protocol.ts +28 -0
  209. package/src/tool-browser/block-recovery.ts +85 -0
  210. package/src/tool-browser/code-tool.ts +555 -0
  211. package/src/tool-browser/code-worker.ts +725 -0
  212. package/src/tool-browser/element-fields.ts +167 -0
  213. package/src/tool-browser/errors.ts +40 -0
  214. package/src/tool-browser/index.ts +265 -0
  215. package/src/tool-browser/page-probe.ts +675 -0
  216. package/src/tool-browser/panel-page.ts +126 -0
  217. package/src/tool-browser/probe-client.ts +183 -0
  218. package/src/tool-browser/screenshot-annotations.ts +131 -0
  219. package/src/tool-browser/screenshot-image.ts +49 -0
  220. package/src/tool-browser/state.ts +375 -0
  221. package/src/tool-browser/takeover.ts +199 -0
  222. package/src/tool-browser/tools-debug.ts +806 -0
  223. package/src/tool-browser/tools-interaction.ts +956 -0
  224. package/src/tool-browser/tools-navigation.ts +786 -0
  225. package/src/tool-browser/tools-observation.ts +474 -0
  226. package/src/tool-browser/tools-reference.ts +294 -0
  227. package/src/types/electron-shim.d.ts +144 -0
  228. package/src/types.ts +85 -0
  229. package/src/web-guest.ts +35 -0
  230. package/tools/accept-desktop.mjs +148 -0
  231. package/dist/client.d.cts +0 -516
  232. package/dist/client.d.mts +0 -516
  233. package/dist/index.cjs +0 -92
  234. package/dist/index.d.mts +0 -2960
  235. package/dist/index.mjs +0 -24
  236. package/dsh-builtin-browser-1.0.3-publish.tgz +0 -0
  237. package/dsh-builtin-browser-1.0.3.tgz +0 -0
  238. package/dsh-host-patch/sources/main/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
  239. package/dsh-host-patch/sources/main/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
  240. package/dsh-host-patch/sources/main/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
  241. package/dsh-host-patch/sources/main/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
  242. package/dsh-host-patch/sources/main/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
  243. package/dsh-host-patch/sources/main/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
  244. package/dsh-host-patch/sources/main/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
  245. package/dsh-host-patch/sources/main/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
  246. package/dsh-host-patch/sources/main/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
  247. package/dsh-host-patch/sources/main/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
  248. package/dsh-host-patch/sources/main/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
  249. package/dsh-host-patch/sources/main/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
  250. package/dsh-host-patch/sources/main/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
  251. package/dsh-host-patch/sources/main/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
  252. package/dsh-host-patch/sources/main/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
  253. package/dsh-host-patch/sources/main/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
  254. package/dsh-host-patch/sources/main/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
  255. package/dsh-host-patch/sources/main/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
  256. package/dsh-host-patch/sources/manifest.json +0 -218
  257. package/dsh-host-patch/sources/rc3/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
  258. package/dsh-host-patch/sources/rc3/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
  259. package/dsh-host-patch/sources/rc3/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
  260. package/dsh-host-patch/sources/rc3/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
  261. package/dsh-host-patch/sources/rc3/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
  262. package/dsh-host-patch/sources/rc3/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
  263. package/dsh-host-patch/sources/rc3/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
  264. package/dsh-host-patch/sources/rc3/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
  265. package/dsh-host-patch/sources/rc3/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
  266. package/dsh-host-patch/sources/rc3/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
  267. package/dsh-host-patch/sources/rc3/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
  268. package/dsh-host-patch/sources/rc3/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
  269. package/dsh-host-patch/sources/rc3/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
  270. package/dsh-host-patch/sources/rc3/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
  271. package/dsh-host-patch/sources/rc3/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
  272. package/dsh-host-patch/sources/rc3/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
  273. package/dsh-host-patch/sources/rc3/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
  274. package/dsh-host-patch/sources/rc3/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
  275. package/dsh-host-patch/sources/rc5/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
  276. package/dsh-host-patch/sources/rc5/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
  277. package/dsh-host-patch/sources/rc5/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
  278. package/dsh-host-patch/sources/rc5/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
  279. package/dsh-host-patch/sources/rc5/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
  280. package/dsh-host-patch/sources/rc5/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
  281. package/dsh-host-patch/sources/rc5/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
  282. package/dsh-host-patch/sources/rc5/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
  283. package/dsh-host-patch/sources/rc5/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
  284. package/dsh-host-patch/sources/rc5/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
  285. package/dsh-host-patch/sources/rc5/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
  286. package/dsh-host-patch/sources/rc5/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
  287. package/dsh-host-patch/sources/rc5/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
  288. package/dsh-host-patch/sources/rc5/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
  289. package/dsh-host-patch/sources/rc5/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
  290. package/dsh-host-patch/sources/rc5/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
  291. package/dsh-host-patch/sources/rc5/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
  292. package/dsh-host-patch/sources/rc5/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
  293. package/dsh-host-patch/sources/series.json +0 -260
@@ -0,0 +1,290 @@
1
+ import { MAINTENANCE_PROCESS_TIMEOUT_MS } from '../../assets/browser-policy.mjs'
2
+ /**
3
+ * Install, repair or remove the desktop bridge from the settings panel.
4
+ *
5
+ * Maintenance changes files after the target Desktop has exited. The installer checks this before
6
+ * writing; the panel never asks it to close or restart its own host. The same packaged installer
7
+ * owns identity checks, backups and patching for both the panel and an external terminal.
8
+ * @module dsh-browser/browser-electron/bridge-install
9
+ */
10
+ import { spawn } from 'node:child_process'
11
+ import { mkdtemp, readFile } from 'node:fs/promises'
12
+ import { tmpdir } from 'node:os'
13
+ import { join } from 'node:path'
14
+ import { fileURLToPath } from 'node:url'
15
+ import { BridgeConnection } from './bridge-connection.ts'
16
+ import { bridgeEndpointPath } from './paths.ts'
17
+ import { extensionHomeId, type InstalledExtension } from './profile-extension.ts'
18
+
19
+ /** What the panel may ask for. */
20
+ export type BridgeAction = 'install' | 'uninstall'
21
+
22
+ /** Independent result of the optional, version-gated DSH host patch. */
23
+ export interface HostPatchResult {
24
+ readonly status: 'absent' | 'applied' | 'unsupported version' | 'anchors mismatch'
25
+ readonly reason?: string
26
+ readonly changed?: boolean
27
+ }
28
+
29
+ /** Everything this module touches from outside, so a test can drive it without spawning. */
30
+ export interface BridgeActionDeps {
31
+ /** Runs the installer; resolves with an exit code and the tail of its output. */
32
+ readonly run: (command: string, argv: readonly string[], environment?: Readonly<Record<string, string>>) => Promise<{ readonly code: number | null; readonly output: string }>
33
+ /** Absolute path of the packaged installer. */
34
+ readonly installer: () => string
35
+ /** Node executable used to run it (the host's own, so no PATH surprises). */
36
+ readonly node: () => string
37
+ /** Follow the installer's atomic completion file. */
38
+ readonly trackResult?: boolean
39
+ /** Completion budget, injectable for a fast failure test. */
40
+ readonly resultTimeoutMs?: number
41
+ /** Poll interval for the installer's atomic completion file. */
42
+ readonly resultPollMs?: number
43
+ }
44
+
45
+ /** What the panel is told. */
46
+ export interface BridgeActionResult {
47
+ /** Whether the requested file maintenance completed successfully. */
48
+ readonly ok: boolean
49
+ /** Its exit code, or null when it was killed. */
50
+ readonly code: number | null
51
+ /** The tail of its output, for the one line the panel shows. */
52
+ readonly output: string
53
+ /** The exact command line, so a failure can be reproduced by hand. */
54
+ readonly command: string
55
+ /** Persisted completion and installer output, retained for diagnosis. */
56
+ readonly resultFile?: string
57
+ readonly logFile?: string
58
+ readonly restarted?: boolean
59
+ readonly pid?: number
60
+ readonly hostPatch?: HostPatchResult
61
+ }
62
+
63
+ export async function runBridgeReinstall(deps: {
64
+ readonly absent: () => boolean
65
+ readonly run: (action: BridgeAction) => Promise<BridgeActionResult>
66
+ }): Promise<BridgeActionResult> {
67
+ const removed = deps.absent() ? undefined : await deps.run('uninstall')
68
+ if (removed && !removed.ok) throw new Error(`REINSTALL_REMOVE_FAILED: ${removed.output}`)
69
+ if (!deps.absent()) throw new Error('REINSTALL_REMOVE_FAILED: bridge remains installed')
70
+ const installed = await deps.run('install')
71
+ if (!installed.ok) throw new Error(`REINSTALL_ADD_FAILED: ${installed.output}`)
72
+ return { ...installed, output: [removed?.output, installed.output].filter(Boolean).join('\n').slice(-20_000) }
73
+ }
74
+
75
+ /** Final record written by the installer that actually performed the operation. */
76
+ export interface BridgeActionCompletion {
77
+ readonly action: BridgeAction
78
+ readonly ok: boolean
79
+ readonly code: number
80
+ readonly restarted: boolean
81
+ readonly pid?: number
82
+ readonly error?: string
83
+ readonly completedAt: string
84
+ readonly hostPatch?: HostPatchResult
85
+ }
86
+
87
+ /** Read-only startup verification, with a private endpoint path available to isolated tests. */
88
+ export interface BridgeReadyOptions {
89
+ readonly endpointPath?: string
90
+ readonly timeoutMs?: number
91
+ readonly pollMs?: number
92
+ readonly extension?: InstalledExtension
93
+ readonly home?: string
94
+ }
95
+
96
+ /**
97
+ * Verify that the restarted process published a working authenticated bridge.
98
+ * A previous shell's endpoint, a listening socket, or an authentication refusal is insufficient.
99
+ */
100
+ export async function waitForRestartedBridge(pid: number, options: BridgeReadyOptions = {}): Promise<void> {
101
+ const path = options.endpointPath ?? bridgeEndpointPath()
102
+ const timeoutMs = options.timeoutMs ?? MAINTENANCE_PROCESS_TIMEOUT_MS
103
+ const deadline = Date.now() + timeoutMs
104
+ while (Date.now() < deadline) {
105
+ try {
106
+ const endpoint = JSON.parse(await readFile(path, 'utf8')) as { port?: unknown; token?: unknown; pid?: unknown }
107
+ if (endpoint !== null && typeof endpoint === 'object' && endpoint.pid === pid
108
+ && Number.isInteger(endpoint.port) && Number(endpoint.port) > 0 && Number(endpoint.port) <= 65535
109
+ && typeof endpoint.token === 'string' && endpoint.token.trim() !== '') {
110
+ const remaining = deadline - Date.now()
111
+ if (remaining <= 0) break
112
+ const connection = new BridgeConnection({ port: Number(endpoint.port), token: endpoint.token, pid })
113
+ try {
114
+ if (options.extension !== undefined) {
115
+ const version = await connection.call({ op: 'version' }, Math.min(1_000, remaining))
116
+ const status = version.mainExtension as { state?: unknown; version?: unknown; loadedAt?: unknown } | undefined
117
+ if (version.ok !== true || version.bridgeVersion !== options.extension.version || version.bridgeBuild !== options.extension.build
118
+ || version.homeId !== extensionHomeId(options.home ?? '') || status?.state !== 'loaded'
119
+ || status.version !== options.extension.version || typeof status.loadedAt !== 'string' || !Number.isFinite(Date.parse(status.loadedAt))) throw new Error('EXTENSION_RESTART_REQUIRED')
120
+ }
121
+ const answer = await connection.call({ op: 'list' }, Math.min(1_000, remaining))
122
+ if (answer.ok === true && Number(answer.protocol) >= 4) return
123
+ } finally { connection.close() }
124
+ }
125
+ } catch {
126
+ // Endpoint publication and the socket can race startup. Diagnostics deliberately exclude
127
+ // the endpoint body and authentication token; the caller retains the installer's own log.
128
+ }
129
+ const remaining = deadline - Date.now()
130
+ if (remaining > 0) await new Promise(resolve => setTimeout(resolve, Math.min(options.pollMs ?? 100, remaining)))
131
+ }
132
+ throw new Error(`the restarted DSH Desktop bridge did not become ready within ${String(timeoutMs)}ms`)
133
+ }
134
+
135
+ /**
136
+ * Wait for completed file maintenance. The installer publishes this file by rename so a reader
137
+ * cannot accept a partial result. A panel operation must report no Desktop restart.
138
+ */
139
+ export async function waitForBridgeActionCompletion(
140
+ path: string,
141
+ action: BridgeAction,
142
+ timeoutMs = 180_000,
143
+ pollMs = 100,
144
+ ): Promise<BridgeActionCompletion> {
145
+ const deadline = Date.now() + timeoutMs
146
+ for (;;) {
147
+ let text: string | undefined
148
+ try { text = await readFile(path, 'utf8') } catch (error) {
149
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
150
+ }
151
+ if (text !== undefined) {
152
+ let record: Partial<BridgeActionCompletion>
153
+ try { record = JSON.parse(text) as Partial<BridgeActionCompletion> } catch {
154
+ throw new Error('the bridge installer wrote an unreadable completion record')
155
+ }
156
+ if (record === null || typeof record !== 'object'
157
+ || record.action !== action || typeof record.ok !== 'boolean'
158
+ || !Number.isSafeInteger(record.code) || record.restarted !== false
159
+ || typeof record.completedAt !== 'string' || !Number.isFinite(Date.parse(record.completedAt))
160
+ || record.pid !== undefined
161
+ || (record.error !== undefined && typeof record.error !== 'string')
162
+ || (record.hostPatch !== undefined && (record.hostPatch === null || typeof record.hostPatch !== 'object'
163
+ || !['absent', 'applied', 'unsupported version', 'anchors mismatch'].includes(record.hostPatch.status)
164
+ || (record.hostPatch.reason !== undefined && typeof record.hostPatch.reason !== 'string')
165
+ || (record.hostPatch.changed !== undefined && typeof record.hostPatch.changed !== 'boolean')))
166
+ || (record.ok !== (record.code === 0))) {
167
+ throw new Error('the bridge installer wrote an invalid completion record')
168
+ }
169
+ return record as BridgeActionCompletion
170
+ }
171
+ if (Date.now() >= deadline) throw new Error(`the bridge installer did not report completion within ${String(timeoutMs)}ms`)
172
+ await new Promise(resolve => setTimeout(resolve, Math.min(pollMs, Math.max(1, deadline - Date.now()))))
173
+ }
174
+ }
175
+
176
+ /**
177
+ * The argv the installer expects, in one place so the panel and a human run the same thing.
178
+ *
179
+ * The target Desktop must already be closed. In particular, the panel cannot grant its child
180
+ * permission to terminate the process that owns the current tool call or settings request.
181
+ * @param action - install/repair, or restore the pre-bridge state.
182
+ * @param installRoot - the desktop install directory that was discovered.
183
+ * @returns argv for the installer.
184
+ */
185
+ export function bridgeActionArgv(action: BridgeAction, installRoot: string): string[] {
186
+ const argv = [installRoot]
187
+ if (action === 'uninstall') argv.push('--revert')
188
+ return argv
189
+ }
190
+
191
+ /** The packaged installer, resolved from this module rather than from a build-time path. */
192
+ export function defaultInstallerPath(): string {
193
+ return fileURLToPath(new URL('../../desktop-bridge/install.mjs', import.meta.url))
194
+ }
195
+
196
+ /** One line from a long output: the tail is what names the failure. */
197
+ function tail(text: string, limit = 600): string {
198
+ const trimmed = text.trim()
199
+ return trimmed.length > limit ? '…' + trimmed.slice(-limit) : trimmed
200
+ }
201
+
202
+ /** Default runner: the host's own node, a bounded wait, and no shell (so a path with spaces is data). */
203
+ function defaultRun(command: string, argv: readonly string[], environment?: Readonly<Record<string, string>>): Promise<{ code: number | null; output: string }> {
204
+ return new Promise(resolve => {
205
+ const child = spawn(command, [...argv], {
206
+ stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true,
207
+ env: environment === undefined ? process.env : { ...process.env, ...environment },
208
+ })
209
+ let output = ''
210
+ const collect = (chunk: unknown): void => { output += String(chunk); if (output.length > 20_000) output = output.slice(-20_000) }
211
+ child.stdout?.on('data', collect)
212
+ child.stderr?.on('data', collect)
213
+ const timer = setTimeout(() => { try { child.kill() } catch { /* already gone */ } }, 180_000)
214
+ child.on('error', error => { clearTimeout(timer); resolve({ code: null, output: `${output}\nfailed to start: ${String(error)}` }) })
215
+ child.on('close', code => { clearTimeout(timer); resolve({ code, output }) })
216
+ })
217
+ }
218
+
219
+ /**
220
+ * Run one bridge action.
221
+ *
222
+ * Never throws for an installer failure: the panel needs the exit code and the line that explains it,
223
+ * and an exception would lose both.
224
+ * @param action - install/repair or uninstall.
225
+ * @param installRoot - the desktop install directory.
226
+ * @param deps - effects; defaulted to this process's.
227
+ * @returns the outcome, with the command line for reproduction.
228
+ */
229
+ export async function runBridgeAction(
230
+ action: BridgeAction,
231
+ installRoot: string,
232
+ deps: BridgeActionDeps = {
233
+ run: defaultRun, installer: defaultInstallerPath, node: () => process.execPath, trackResult: true,
234
+ },
235
+ ): Promise<BridgeActionResult> {
236
+ const command = deps.node()
237
+ const argv = [deps.installer(), ...bridgeActionArgv(action, installRoot)]
238
+ const printable = [command, ...argv].map(part => (/\s/.test(part) ? `"${part}"` : part)).join(' ')
239
+ let resultFile: string | undefined
240
+ let logFile: string | undefined
241
+ let installerOutput = ''
242
+ const recordedOutput = async (): Promise<string> => {
243
+ if (logFile === undefined) return ''
244
+ try { return (await readFile(logFile, 'utf8')).slice(-20_000) }
245
+ catch (error) {
246
+ console.error(`[dsh-browser] cannot read the installer log: ${String(error)}`)
247
+ return ''
248
+ }
249
+ }
250
+ try {
251
+ // Ask the installer to check identity FIRST, without touching anything. It is the same preflight
252
+ // a human can run, and it turns "the button did nothing" into a named reason.
253
+ const preflight = await deps.run(command, [argv[0] as string, installRoot, '--preflight'])
254
+ const verdict = (() => {
255
+ try { return JSON.parse(preflight.output.trim().split('\n').at(-1) ?? '{}') as { ok?: boolean; reason?: string } }
256
+ catch { return {} as { ok?: boolean; reason?: string } }
257
+ })()
258
+ if (preflight.code !== 0 || verdict.ok !== true) {
259
+ return {
260
+ ok: false,
261
+ code: preflight.code,
262
+ output: tail(String(verdict.reason ?? preflight.output)),
263
+ command: printable,
264
+ }
265
+ }
266
+ let environment: Record<string, string> | undefined
267
+ const deadline = Date.now() + (deps.resultTimeoutMs ?? 180_000)
268
+ if (deps.trackResult === true) {
269
+ const directory = await mkdtemp(join(tmpdir(), 'dsh-bridge-action-'))
270
+ resultFile = join(directory, 'result.json')
271
+ logFile = join(directory, 'installer.log')
272
+ environment = { DSH_BRIDGE_ACTION_RESULT_FILE: resultFile, DSH_BRIDGE_ACTION_LOG_FILE: logFile }
273
+ }
274
+ const result = await deps.run(command, argv, environment)
275
+ installerOutput = result.output
276
+ if (result.code !== 0 || resultFile === undefined) {
277
+ return { ok: result.code === 0, code: result.code, output: tail(result.output), command: printable, restarted: false,
278
+ ...resultFile === undefined ? {} : { resultFile, logFile } }
279
+ }
280
+ const final = await waitForBridgeActionCompletion(resultFile, action, Math.max(0, deadline - Date.now()), deps.resultPollMs)
281
+ const output = [installerOutput, await recordedOutput(), final.error].filter(Boolean).join('\n')
282
+ return { ok: final.ok, code: final.code, output: tail(output), command: printable, resultFile, logFile,
283
+ restarted: final.restarted, ...final.pid === undefined ? {} : { pid: final.pid },
284
+ ...final.hostPatch === undefined ? {} : { hostPatch: final.hostPatch } }
285
+ } catch (error) {
286
+ return { ok: false, code: null,
287
+ output: tail([installerOutput, await recordedOutput(), String(error)].filter(Boolean).join('\n')),
288
+ command: printable, ...resultFile === undefined ? {} : { resultFile, logFile } }
289
+ }
290
+ }
@@ -0,0 +1,189 @@
1
+ import { BROWSER_PROFILE_DIR } from '../../assets/browser-policy.mjs'
2
+ /**
3
+ * Prepare bridge maintenance (Windows `.cmd`, macOS `.command`) for the user to run after exiting DSH Desktop.
4
+ * Preparation writes a private launcher and plan; it never starts a process or changes Desktop.
5
+ * The current packaged installer performs identity and running-process checks at execution time.
6
+ * @module dsh-browser/browser-electron/bridge-maintenance
7
+ */
8
+ import { existsSync, realpathSync, statSync } from 'node:fs'
9
+ import { mkdir, mkdtemp, writeFile } from 'node:fs/promises'
10
+ import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path'
11
+ import { fileURLToPath } from 'node:url'
12
+ import { desktopLayout, desktopPaths, readDesktopIdentity } from './desktop-identity.ts'
13
+ import { dshHome as dshHomePath } from './paths.ts'
14
+ import type { BridgeAction } from './bridge-install.ts'
15
+
16
+ export interface BridgeMaintenanceOptions {
17
+ /** Parent of a new, unique maintenance directory; defaults to the user's DSH home. */
18
+ readonly directory?: string
19
+ /** Explicit Node executable; a verified Desktop executable may be used in Electron Node mode. */
20
+ readonly nodePath?: string
21
+ }
22
+
23
+ export interface PreparedBridgeMaintenance {
24
+ readonly ok: true
25
+ readonly prepared: true
26
+ readonly action: BridgeAction
27
+ readonly path: string
28
+ /** Literal-path invocation for the user's terminal (PowerShell on Windows, a POSIX shell on macOS). */
29
+ readonly command: string
30
+ readonly commandShell: 'powershell' | 'sh'
31
+ readonly directory: string
32
+ readonly runnerPath: string
33
+ readonly planPath: string
34
+ }
35
+
36
+ interface MaintenancePlan {
37
+ readonly version: 1
38
+ readonly action: BridgeAction
39
+ readonly installRoot: string
40
+ readonly installerPath: string
41
+ readonly nodePath: string
42
+ readonly electronNode: boolean
43
+ readonly dshHome: string
44
+ }
45
+
46
+ /** Batch literals cannot contain these characters; other path content stays in JSON arguments. */
47
+ function checkedPath(value: string, label: string): string {
48
+ if (!isAbsolute(value) || /[\0\r\n"]/.test(value)) throw new Error(`${label} must be an absolute path without quotes or control characters`)
49
+ return resolve(value)
50
+ }
51
+
52
+ /** Escape only a batch literal. Delayed expansion is disabled before a literal is read. */
53
+ function batchLiteral(value: string): string {
54
+ return value.replace(/%/g, '%%')
55
+ }
56
+
57
+ function withinOrEqual(root: string, path: string): boolean {
58
+ const part = relative(root, path)
59
+ return part === '' || (!isAbsolute(part) && part !== '..' && !part.startsWith('..\\') && !part.startsWith('../'))
60
+ }
61
+
62
+ /** Resolve existing ancestors before mkdir so a redirected output cannot create files in Desktop. */
63
+ function prospectiveRealPath(path: string): string {
64
+ let ancestor = path
65
+ const missing: string[] = []
66
+ while (!existsSync(ancestor)) {
67
+ const parent = dirname(ancestor)
68
+ if (parent === ancestor) throw new Error('maintenance directory has no existing ancestor')
69
+ missing.unshift(basename(ancestor))
70
+ ancestor = parent
71
+ }
72
+ return resolve(realpathSync(ancestor), ...missing)
73
+ }
74
+
75
+ /** Case-insensitive on Windows; elsewhere both sides are already on-disk spellings (`realpathSync.native`). */
76
+ function samePath(a: string, b: string): boolean {
77
+ return process.platform === 'win32' ? a.toLowerCase() === b.toLowerCase() : a === b
78
+ }
79
+
80
+ /** One POSIX shell word: single-quoted, with embedded quotes closed and escaped. */
81
+ function shellLiteral(value: string): string {
82
+ return `'${value.replace(/'/g, `'\\''`)}'`
83
+ }
84
+
85
+ /** The macOS launcher: a `.command` file Finder opens in Terminal; paths stay single-quoted literals. */
86
+ function posixLauncher(nodePath: string, electronNode: boolean): string {
87
+ return [
88
+ '#!/bin/sh',
89
+ 'echo "Quit DSH Desktop normally before running bridge maintenance."',
90
+ 'cd "$(dirname "$0")" || exit 1',
91
+ `${electronNode ? 'ELECTRON_RUN_AS_NODE=1 ' : 'ELECTRON_RUN_AS_NODE= '}${shellLiteral(nodePath)}${electronNode ? ' --expose-internals' : ''} ./run-maintenance.mjs`,
92
+ 'code=$?',
93
+ 'if [ "$code" -eq 0 ]; then echo "Bridge maintenance completed. You can now open DSH Desktop."; else echo "Bridge maintenance failed. Read the reason above, then prepare maintenance again if needed."; fi',
94
+ 'exit "$code"',
95
+ '',
96
+ ].join('\n')
97
+ }
98
+
99
+ /** This runner is deliberately data-driven: paths and actions are never evaluated as shell text. */
100
+ const RUNNER = `import { readFileSync, existsSync } from 'node:fs';
101
+ import { isAbsolute } from 'node:path';
102
+ import { spawnSync } from 'node:child_process';
103
+ const plan = JSON.parse(readFileSync(new URL('./maintenance.json', import.meta.url), 'utf8'));
104
+ if (plan.version !== 1 || !['install', 'uninstall'].includes(plan.action)
105
+ || ![plan.installRoot, plan.installerPath, plan.nodePath, plan.dshHome].every(value => typeof value === 'string' && isAbsolute(value))
106
+ || typeof plan.electronNode !== 'boolean') throw new Error('Invalid bridge maintenance plan');
107
+ if (!existsSync(plan.installerPath)) throw new Error('The browser plugin installer is missing. Install or update the plugin and prepare maintenance again.');
108
+ const environment = { ...process.env };
109
+ for (const key of Object.keys(environment)) {
110
+ if (['DSH_BRIDGE_DETACHED', 'DSH_BRIDGE_HANDOFF_PARENT', 'DSH_BRIDGE_ACTION_RESULT_FILE', 'DSH_BRIDGE_ACTION_LOG_FILE', 'ELECTRON_RUN_AS_NODE'].includes(key.toUpperCase())) delete environment[key];
111
+ }
112
+ if (plan.electronNode) environment.ELECTRON_RUN_AS_NODE = '1';
113
+ // Test boundaries and their private home must survive this launcher unchanged.
114
+ if (environment.DSH_BROWSER_TEST !== '1' && environment.NODE_TEST_CONTEXT === undefined) environment.DSH_HOME = plan.dshHome;
115
+ const args = [...(plan.electronNode ? ['--expose-internals'] : []), plan.installerPath, plan.installRoot, ...(plan.action === 'uninstall' ? ['--revert'] : [])];
116
+ const result = spawnSync(plan.nodePath, args, { shell: false, windowsHide: true, stdio: 'inherit', env: environment });
117
+ if (result.error) { console.error('Bridge maintenance could not start: ' + result.error.message); process.exitCode = 1; }
118
+ else process.exitCode = result.status ?? 1;
119
+ `
120
+
121
+ /**
122
+ * Prepare an offline Windows launcher. The target may still be running during preparation.
123
+ * User execution remains subject to the installer's closed-Desktop and ancestry guards.
124
+ */
125
+ export async function prepareBridgeMaintenance(
126
+ action: BridgeAction,
127
+ installRoot: string,
128
+ options: BridgeMaintenanceOptions = {},
129
+ ): Promise<PreparedBridgeMaintenance> {
130
+ if (action !== 'install' && action !== 'uninstall') throw new Error('bridge maintenance action must be install or uninstall')
131
+ const requestedRoot = checkedPath(installRoot, 'Desktop installation')
132
+ const identity = readDesktopIdentity(requestedRoot)
133
+ if (!identity.ok) throw new Error(`cannot prepare bridge maintenance: ${identity.reason}`)
134
+ const target = realpathSync(requestedRoot)
135
+ const installerPath = fileURLToPath(new URL('../../desktop-bridge/install.mjs', import.meta.url))
136
+ if (!existsSync(installerPath)) throw new Error('the packaged bridge installer is missing')
137
+
138
+ const desktopRuntime = desktopPaths(target).executable
139
+ const currentIsNode = /^(?:node|node\.exe)$/i.test(basename(process.execPath))
140
+ const selected = options.nodePath ?? (currentIsNode ? process.execPath : desktopRuntime)
141
+ const nodePath = checkedPath(selected, 'Maintenance runtime')
142
+ if (!existsSync(nodePath) || !statSync(nodePath).isFile()) throw new Error('the maintenance runtime does not exist')
143
+ const electronNode = !/^(?:node|node\.exe)$/i.test(basename(nodePath))
144
+ if (electronNode && (!existsSync(desktopRuntime) || !samePath(realpathSync.native(nodePath), realpathSync.native(desktopRuntime)))) {
145
+ throw new Error('the Electron maintenance runtime must belong to the verified Desktop installation')
146
+ }
147
+
148
+ const dshHome = checkedPath(dshHomePath(), 'DSH home')
149
+ const testContext = process.env.DSH_BROWSER_TEST === '1' || process.env.NODE_TEST_CONTEXT !== undefined
150
+ if (testContext && options.directory === undefined && process.env.DSH_BRIDGE_TEST_ROOT === undefined) {
151
+ throw new Error('test preparation requires an explicit private maintenance directory')
152
+ }
153
+ const directory = checkedPath(options.directory ?? join(dshHome, BROWSER_PROFILE_DIR, 'maintenance'), 'Maintenance directory')
154
+ if (withinOrEqual(target, directory) || withinOrEqual(target, prospectiveRealPath(directory))) {
155
+ throw new Error('maintenance launchers must be stored outside the Desktop installation')
156
+ }
157
+ await mkdir(directory, { recursive: true, mode: 0o700 })
158
+ if (withinOrEqual(target, realpathSync(directory))) throw new Error('maintenance directory resolves inside the Desktop installation')
159
+ const output = await mkdtemp(join(directory, `${action}-`))
160
+ const runnerPath = join(output, 'run-maintenance.mjs')
161
+ const planPath = join(output, 'maintenance.json')
162
+ const bundle = (desktopLayout(target) as { name?: string }).name === 'macos-bundle'
163
+ const path = join(output, `${action === 'uninstall' ? 'uninstall' : 'install'}-bridge.${bundle ? 'command' : 'cmd'}`)
164
+ const plan: MaintenancePlan = { version: 1, action, installRoot: target, installerPath, nodePath, electronNode, dshHome }
165
+ const command = bundle ? posixLauncher(nodePath, electronNode) : [
166
+ '@echo off',
167
+ 'setlocal DisableDelayedExpansion',
168
+ 'chcp 65001 >nul',
169
+ 'echo Exit DSH Desktop normally before running bridge maintenance.',
170
+ `set "ELECTRON_RUN_AS_NODE=${electronNode ? '1' : ''}"`,
171
+ `"${batchLiteral(nodePath)}"${electronNode ? ' --expose-internals' : ''} "%~dp0run-maintenance.mjs"`,
172
+ 'set "DSH_BRIDGE_MAINTENANCE_EXIT=%ERRORLEVEL%"',
173
+ 'if not "%DSH_BRIDGE_MAINTENANCE_EXIT%"=="0" goto failed',
174
+ 'echo Bridge maintenance completed. You can now open DSH Desktop.',
175
+ 'goto finished',
176
+ ':failed',
177
+ 'echo Bridge maintenance failed. Read the reason above, then prepare maintenance again if needed.',
178
+ ':finished',
179
+ 'if not "%DSH_BRIDGE_MAINTENANCE_NO_PAUSE%"=="1" pause',
180
+ 'exit /b %DSH_BRIDGE_MAINTENANCE_EXIT%',
181
+ '',
182
+ ].join('\r\n')
183
+ await writeFile(planPath, JSON.stringify(plan, null, 2) + '\n', { flag: 'wx', mode: 0o600 })
184
+ await writeFile(runnerPath, RUNNER, { flag: 'wx', mode: 0o600 })
185
+ await writeFile(path, command, { flag: 'wx', mode: bundle ? 0o700 : 0o600 })
186
+ return bundle
187
+ ? { ok: true, prepared: true, action, path, command: shellLiteral(path), commandShell: 'sh', directory: output, runnerPath, planPath }
188
+ : { ok: true, prepared: true, action, path, command: `& '${path.replace(/'/g, "''")}'`, commandShell: 'powershell', directory: output, runnerPath, planPath }
189
+ }