dsh-remote 0.8.93 → 1.0.1

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 (186) hide show
  1. package/LICENSE +21 -21
  2. package/README.en.md +408 -370
  3. package/README.md +391 -355
  4. package/cordis.patch.yml +9 -9
  5. package/lib/audit.js +45 -45
  6. package/lib/auto-update.js +70 -0
  7. package/lib/binding.js +172 -172
  8. package/lib/boot.js +42 -0
  9. package/lib/client.js +5615 -4648
  10. package/lib/credential.js +277 -270
  11. package/lib/errors.js +141 -141
  12. package/lib/exec-job.js +245 -242
  13. package/lib/file-reference.js +457 -457
  14. package/lib/forwards.js +258 -258
  15. package/lib/host-api.js +822 -822
  16. package/lib/hostkey.js +108 -108
  17. package/lib/http-transport.js +201 -201
  18. package/lib/ignore.js +202 -202
  19. package/lib/index.js +4564 -4488
  20. package/lib/instructions-dynamic.js +415 -415
  21. package/lib/instructions.js +288 -288
  22. package/lib/open-folder.js +56 -56
  23. package/lib/openssh.js +950 -940
  24. package/lib/paths.js +292 -292
  25. package/lib/pool.js +1029 -1029
  26. package/lib/posix-shell.cjs +34 -34
  27. package/lib/registry.js +296 -296
  28. package/lib/remote-fs.js +173 -173
  29. package/lib/remote-sandbox.js +183 -183
  30. package/lib/remote-shell-child.cjs +413 -397
  31. package/lib/remote-shell.js +697 -697
  32. package/lib/remote-skills.js +312 -312
  33. package/lib/routes-audit.js +58 -58
  34. package/lib/routes-forwards.js +72 -72
  35. package/lib/routes-fs.js +251 -251
  36. package/lib/routes-machines.js +217 -186
  37. package/lib/routes-misc.js +187 -187
  38. package/lib/routes-term.js +169 -169
  39. package/lib/routes-update.js +147 -143
  40. package/lib/routes-web-attach.js +121 -112
  41. package/lib/routes-workspace.js +325 -312
  42. package/lib/search.js +235 -235
  43. package/lib/self-heal.js +130 -0
  44. package/lib/sftp-surface.js +119 -119
  45. package/lib/sshconfig.js +779 -779
  46. package/lib/sync-status.js +31 -0
  47. package/lib/sync.js +350 -350
  48. package/lib/tasks.js +95 -95
  49. package/lib/telemetry.js +247 -247
  50. package/lib/terminal.js +205 -205
  51. package/lib/tui/flow.js +130 -130
  52. package/lib/tui/format.js +380 -380
  53. package/lib/tui/i18n.js +350 -350
  54. package/lib/tui/index.js +531 -531
  55. package/lib/tui/provider.js +344 -344
  56. package/lib/tui/scene.js +986 -986
  57. package/lib/update.js +497 -490
  58. package/lib/web-attach.js +1081 -860
  59. package/lib/workspace-cleanup.js +337 -337
  60. package/node_modules/buildcheck/.eslintrc.js +5 -0
  61. package/node_modules/buildcheck/.github/workflows/ci.yml +88 -0
  62. package/node_modules/buildcheck/.github/workflows/lint.yml +27 -0
  63. package/node_modules/buildcheck/.npmignore +3 -0
  64. package/node_modules/buildcheck/LICENSE +19 -0
  65. package/node_modules/buildcheck/README.md +106 -0
  66. package/node_modules/buildcheck/deps/Find-VisualStudio.cs +250 -0
  67. package/node_modules/buildcheck/lib/findvs.js +361 -0
  68. package/node_modules/buildcheck/lib/index.js +738 -0
  69. package/node_modules/buildcheck/package.json +36 -0
  70. package/node_modules/buildcheck/test/test.js +8 -0
  71. package/node_modules/cpu-features/.eslintrc.js +5 -0
  72. package/node_modules/cpu-features/.github/workflows/ci.yml +74 -0
  73. package/node_modules/cpu-features/.github/workflows/lint.yml +27 -0
  74. package/node_modules/cpu-features/LICENSE +19 -0
  75. package/node_modules/cpu-features/README.md +59 -0
  76. package/node_modules/cpu-features/binding.gyp +16 -0
  77. package/node_modules/cpu-features/buildcheck.js +32 -0
  78. package/node_modules/cpu-features/deps/cpu_features/.clang-format +4 -0
  79. package/node_modules/cpu-features/deps/cpu_features/.dockerignore +31 -0
  80. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/Dockerfile +5 -0
  81. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/aarch64_linux_cmake.yml +30 -0
  82. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/amd64_freebsd_cmake.yml +22 -0
  83. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/amd64_linux_bazel.yml +26 -0
  84. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/amd64_linux_cmake.yml +31 -0
  85. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/amd64_macos_cmake.yml +43 -0
  86. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/amd64_windows_cmake.yml +25 -0
  87. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/arm_linux_cmake.yml +31 -0
  88. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/clang_format.yml +24 -0
  89. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/mips_linux_cmake.yml +30 -0
  90. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/power_linux_cmake.yml +29 -0
  91. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/riscv_linux_cmake.yml +28 -0
  92. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/s390x_linux_cmake.yml +27 -0
  93. package/node_modules/cpu-features/deps/cpu_features/.grenrc.yml +21 -0
  94. package/node_modules/cpu-features/deps/cpu_features/BUILD.bazel +329 -0
  95. package/node_modules/cpu-features/deps/cpu_features/CMakeLists.txt +261 -0
  96. package/node_modules/cpu-features/deps/cpu_features/CONTRIBUTING.md +23 -0
  97. package/node_modules/cpu-features/deps/cpu_features/LICENSE +230 -0
  98. package/node_modules/cpu-features/deps/cpu_features/README.md +272 -0
  99. package/node_modules/cpu-features/deps/cpu_features/WORKSPACE +19 -0
  100. package/node_modules/cpu-features/deps/cpu_features/bazel/ci/README.md +5 -0
  101. package/node_modules/cpu-features/deps/cpu_features/bazel/platforms.bzl +11 -0
  102. package/node_modules/cpu-features/deps/cpu_features/cmake/CpuFeaturesConfig.cmake.in +3 -0
  103. package/node_modules/cpu-features/deps/cpu_features/cmake/CpuFeaturesNdkCompatConfig.cmake.in +3 -0
  104. package/node_modules/cpu-features/deps/cpu_features/cmake/README.md +30 -0
  105. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/Makefile +252 -0
  106. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/README.md +40 -0
  107. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/doc/docker.dot +64 -0
  108. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/doc/docker.svg +312 -0
  109. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/doc/generate_image.sh +7 -0
  110. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/docker/amd64/Dockerfile +48 -0
  111. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/docker/toolchain/Dockerfile +34 -0
  112. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/sample/CMakeLists.txt +22 -0
  113. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/sample/main.cpp +11 -0
  114. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/vagrant/freebsd/Vagrantfile +107 -0
  115. package/node_modules/cpu-features/deps/cpu_features/cmake/googletest.CMakeLists.txt.in +15 -0
  116. package/node_modules/cpu-features/deps/cpu_features/cpu_features.gyp +105 -0
  117. package/node_modules/cpu-features/deps/cpu_features/include/cpu_features_cache_info.h +54 -0
  118. package/node_modules/cpu-features/deps/cpu_features/include/cpu_features_macros.h +384 -0
  119. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_aarch64.h +259 -0
  120. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_arm.h +121 -0
  121. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_mips.h +74 -0
  122. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_ppc.h +149 -0
  123. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_riscv.h +72 -0
  124. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_s390x.h +108 -0
  125. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_x86.h +288 -0
  126. package/node_modules/cpu-features/deps/cpu_features/include/internal/bit_utils.h +40 -0
  127. package/node_modules/cpu-features/deps/cpu_features/include/internal/cpuid_x86.h +37 -0
  128. package/node_modules/cpu-features/deps/cpu_features/include/internal/filesystem.h +39 -0
  129. package/node_modules/cpu-features/deps/cpu_features/include/internal/hwcaps.h +240 -0
  130. package/node_modules/cpu-features/deps/cpu_features/include/internal/stack_line_reader.h +49 -0
  131. package/node_modules/cpu-features/deps/cpu_features/include/internal/string_view.h +110 -0
  132. package/node_modules/cpu-features/deps/cpu_features/include/internal/windows_utils.h +70 -0
  133. package/node_modules/cpu-features/deps/cpu_features/ndk_compat/CMakeLists.txt +60 -0
  134. package/node_modules/cpu-features/deps/cpu_features/ndk_compat/README.md +4 -0
  135. package/node_modules/cpu-features/deps/cpu_features/ndk_compat/cpu-features.c +205 -0
  136. package/node_modules/cpu-features/deps/cpu_features/ndk_compat/cpu-features.h +320 -0
  137. package/node_modules/cpu-features/deps/cpu_features/ndk_compat/ndk-compat-test.c +12 -0
  138. package/node_modules/cpu-features/deps/cpu_features/patches/0001-Add-Apple-Silicon-Support.patch +456 -0
  139. package/node_modules/cpu-features/deps/cpu_features/scripts/generate_badges.d +165 -0
  140. package/node_modules/cpu-features/deps/cpu_features/scripts/make_release.sh +75 -0
  141. package/node_modules/cpu-features/deps/cpu_features/scripts/run_integration.sh +490 -0
  142. package/node_modules/cpu-features/deps/cpu_features/scripts/test_integration.sh +79 -0
  143. package/node_modules/cpu-features/deps/cpu_features/src/copy.inl +19 -0
  144. package/node_modules/cpu-features/deps/cpu_features/src/define_introspection.inl +86 -0
  145. package/node_modules/cpu-features/deps/cpu_features/src/define_introspection_and_hwcaps.inl +26 -0
  146. package/node_modules/cpu-features/deps/cpu_features/src/equals.inl +22 -0
  147. package/node_modules/cpu-features/deps/cpu_features/src/filesystem.c +62 -0
  148. package/node_modules/cpu-features/deps/cpu_features/src/hwcaps.c +169 -0
  149. package/node_modules/cpu-features/deps/cpu_features/src/impl_aarch64__base_implementation.inl +88 -0
  150. package/node_modules/cpu-features/deps/cpu_features/src/impl_aarch64_linux_or_android.c +79 -0
  151. package/node_modules/cpu-features/deps/cpu_features/src/impl_aarch64_macos_or_iphone.c +82 -0
  152. package/node_modules/cpu-features/deps/cpu_features/src/impl_aarch64_windows.c +138 -0
  153. package/node_modules/cpu-features/deps/cpu_features/src/impl_arm_linux_or_android.c +212 -0
  154. package/node_modules/cpu-features/deps/cpu_features/src/impl_mips_linux_or_android.c +93 -0
  155. package/node_modules/cpu-features/deps/cpu_features/src/impl_ppc_linux.c +163 -0
  156. package/node_modules/cpu-features/deps/cpu_features/src/impl_riscv_linux.c +111 -0
  157. package/node_modules/cpu-features/deps/cpu_features/src/impl_s390x_linux.c +120 -0
  158. package/node_modules/cpu-features/deps/cpu_features/src/impl_x86__base_implementation.inl +2055 -0
  159. package/node_modules/cpu-features/deps/cpu_features/src/impl_x86_freebsd.c +68 -0
  160. package/node_modules/cpu-features/deps/cpu_features/src/impl_x86_linux_or_android.c +58 -0
  161. package/node_modules/cpu-features/deps/cpu_features/src/impl_x86_macos.c +57 -0
  162. package/node_modules/cpu-features/deps/cpu_features/src/impl_x86_windows.c +58 -0
  163. package/node_modules/cpu-features/deps/cpu_features/src/stack_line_reader.c +132 -0
  164. package/node_modules/cpu-features/deps/cpu_features/src/string_view.c +192 -0
  165. package/node_modules/cpu-features/deps/cpu_features/src/utils/list_cpu_features.c +461 -0
  166. package/node_modules/cpu-features/deps/cpu_features/test/CMakeLists.txt +114 -0
  167. package/node_modules/cpu-features/deps/cpu_features/test/bit_utils_test.cc +53 -0
  168. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_aarch64_test.cc +396 -0
  169. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_arm_test.cc +384 -0
  170. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_mips_test.cc +176 -0
  171. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_ppc_test.cc +131 -0
  172. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_riscv_test.cc +180 -0
  173. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_s390x_test.cc +82 -0
  174. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_x86_test.cc +1729 -0
  175. package/node_modules/cpu-features/deps/cpu_features/test/filesystem_for_testing.cc +103 -0
  176. package/node_modules/cpu-features/deps/cpu_features/test/filesystem_for_testing.h +61 -0
  177. package/node_modules/cpu-features/deps/cpu_features/test/hwcaps_for_testing.cc +52 -0
  178. package/node_modules/cpu-features/deps/cpu_features/test/hwcaps_for_testing.h +31 -0
  179. package/node_modules/cpu-features/deps/cpu_features/test/stack_line_reader_test.cc +132 -0
  180. package/node_modules/cpu-features/deps/cpu_features/test/string_view_test.cc +202 -0
  181. package/node_modules/cpu-features/lib/index.js +5 -0
  182. package/node_modules/cpu-features/package.json +40 -0
  183. package/node_modules/cpu-features/src/binding.cc +151 -0
  184. package/node_modules/cpu-features/test/test.js +12 -0
  185. package/node_modules/nan/tools/1to2.js +0 -0
  186. package/package.json +106 -103
package/lib/update.js CHANGED
@@ -1,490 +1,497 @@
1
- // dsh-remote — self-update support.
2
- //
3
- // dsh-remote is a zero-build plugin: the host half (lib/index.js) is loaded
4
- // straight from the installed package, so "updating" = replacing the package
5
- // files with the newer npm tarball. This module owns the version check and the
6
- // tarball apply:
7
- //
8
- // • checkLatestVersion() — query the npm registry for the `latest` dist-tag;
9
- // • applyUpdate() — download the tarball, extract package/{lib,package.json,
10
- // cordis.patch.yml} with a minimal tar reader, verify the version, then
11
- // replace the installed files atomically (temp file + rename, never a
12
- // half-written lib/*.js). A `.dsh-remote-updated` marker records the version
13
- // that landed; the host half removes it once that version is the code it is
14
- // actually running (see LOADED_VERSION), so the marker means "restart still
15
- // required" rather than "an update once happened".
16
- // • reloadSelf() — swap the RUNNING host half to the code now on disk: drop
17
- // Node's module caches for this package's own files, then dispose + re-init
18
- // the loader entry so apply() runs again from the fresh module. Without it
19
- // an update only takes effect on the next process start, which is what left
20
- // the served client half newer than the loaded host half.
21
- //
22
- // Every failure aborts without touching the installed files (a bad download or
23
- // a version mismatch must never break the running plugin).
24
-
25
- import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
26
- import { createRequire } from 'node:module'
27
- import path from 'node:path'
28
- import { fileURLToPath, pathToFileURL } from 'node:url'
29
-
30
- const NPM_PACKAGE = 'dsh-remote'
31
- const REGISTRY_URL = 'https://registry.npmjs.org/' + NPM_PACKAGE + '/latest'
32
-
33
- /** Absolute directory holding this plugin's installed files (lib/ + package.json). */
34
- export function selfDir() {
35
- try {
36
- return path.dirname(path.dirname(fileURLToPath(import.meta.url)))
37
- } catch {
38
- return path.dirname(path.dirname(process.argv[1] || ''))
39
- }
40
- }
41
-
42
- /**
43
- * 本插件是否装在 `node_modules` 之下(即真正的"安装副本")。
44
- *
45
- * ★ 为什么必须有这道判断(实测依据,不是防御性猜测):
46
- * `selfDir()` 基于 `import.meta.url`,而 **Node 的 ESM 解析会对符号链接做
47
- * realpath**(已实测:经由 symlink 导入时 `import.meta.url` 报告的是
48
- * `/real/mod.mjs` 而不是 `/link/mod.mjs`)。于是当插件以 `link:` / 开发模式
49
- * 安装时,`selfDir()` 指向的是**用户的源码仓库**,而不是安装副本。
50
- * 一旦 `auto` 更新落地,`applyUpdate` 就会拿 npm 包覆盖那份源码
51
- * (丢改动、脏工作树)。默认改成 `auto` 之后这个风险从"手点才触发"
52
- * 变成"自动发生",所以在此拦下:不在 node_modules 下就不自更新。
53
- *
54
- * 代价:少数把插件放在非标准路径的部署不会被自动更新——他们仍可手动更新。
55
- * 这个方向的取舍是正确的:宁可少更新,也不能悄悄毁掉源码。
56
- * @param dir - 要判定的目录(默认本插件的 selfDir())。
57
- */
58
- export function isInstalledCopy(dir = selfDir()) {
59
- // 同时认 `/` 与 `\`:本函数要对两种平台的路径都给出正确答案,而调用方
60
- // (尤其测试)会传另一种分隔符的路径。先前只按 path.sep 切分,导致
61
- // 在 Linux 上判断 Windows 风格路径时误判为"非安装副本"(CI 直接红了)。
62
- const normalized = String(dir).replace(/\\/g, '/').toLowerCase()
63
- return normalized.includes('/node_modules/')
64
- }
65
-
66
- /** Read the installed package.json version; "0.0.0" when unreadable. */
67
- export function readVersion() {
68
- try {
69
- const pkg = JSON.parse(readFileSync(path.join(selfDir(), 'package.json'), 'utf8'))
70
- return String(pkg.version || '0.0.0')
71
- } catch {
72
- return '0.0.0'
73
- }
74
- }
75
-
76
- /** Version of the code this process actually loaded (snapshot at import time).
77
- * `readVersion()` reads package.json from disk, so after an update lands it
78
- * reports the NEW version while the running module is still the old one —
79
- * comparing the two is the only way to tell "applied" from "active". */
80
- export const LOADED_VERSION = readVersion()
81
-
82
- /** Package version currently on disk (may be newer than {@link LOADED_VERSION}). */
83
- export function diskVersion() {
84
- return readVersion()
85
- }
86
-
87
- /** Compare dotted versions; returns true when a > b. */
88
- export function gtVersion(a, b) {
89
- const pa = String(a || '').split('.').map((n) => parseInt(n, 10) || 0)
90
- const pb = String(b || '').split('.').map((n) => parseInt(n, 10) || 0)
91
- for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
92
- const da = pa[i] || 0
93
- const db = pb[i] || 0
94
- if (da !== db) return da > db
95
- }
96
- return false
97
- }
98
-
99
- /**
100
- * 查询 npm registry 的最新版本。
101
- *
102
- * 返回 `{ version }` 或 `{ error }`(**不再把一切失败压成 null**)。
103
- *
104
- * 为什么要区分失败原因:原先任何失败都返回 `null`,调用方只能笼统报
105
- * "无法连接 npm registry"。实测踩过:本机被 npm 限流(`/latest` 返回 **429**,
106
- * 而同一时刻 registry 根路径是 200、CI 从另一个出口 IP 也能正常取到),
107
- * 却被显示成"连不上"——把"等一下就好"误导成"网络坏了"。429/超时/离线
108
- * 三者的处置完全不同,必须让用户看到真实原因。
109
- * @param timeoutMs - 超时(看门狗只负责中止,不影响进程存活)。
110
- */
111
- export async function fetchLatestVersion(timeoutMs = 8000) {
112
- try {
113
- const controller = new AbortController()
114
- const timer = setTimeout(() => controller.abort(), timeoutMs)
115
- // 纯看门狗:调用方并不 await 它,所以必须 unref,否则这一段超时窗口
116
- // 会拖住事件循环、让本该退出的短命进程(脚本、测试)多挂数秒。
117
- if (typeof timer.unref === 'function') timer.unref()
118
- let res
119
- try {
120
- res = await fetch(REGISTRY_URL, { signal: controller.signal, headers: { accept: 'application/json' } })
121
- } finally {
122
- clearTimeout(timer)
123
- }
124
- if (res.status === 429) {
125
- return { error: 'npm registry 限流(HTTP 429)——请求过于频繁,稍后会自动恢复', reason: 'rate-limited', status: 429 }
126
- }
127
- if (!res.ok) {
128
- return { error: `npm registry 返回 HTTP ${res.status}`, reason: 'http', status: res.status }
129
- }
130
- const data = await res.json().catch(() => null)
131
- const version = typeof data?.version === 'string' && data.version ? data.version : null
132
- if (!version) return { error: 'npm registry 响应里没有可用的版本号', reason: 'malformed' }
133
- return { version }
134
- } catch (err) {
135
- const aborted = err?.name === 'AbortError'
136
- return {
137
- error: aborted ? `连接 npm registry 超时(${timeoutMs}ms)` : '无法连接 npm registry',
138
- reason: aborted ? 'timeout' : 'network',
139
- }
140
- }
141
- }
142
-
143
- /** Minimal POSIX ustar reader (regular files only) — npm tarballs are gzipped tar. */
144
- function parseTar(buf) {
145
- const files = []
146
- let off = 0
147
- while (off + 512 <= buf.length) {
148
- const header = buf.subarray(off, off + 512)
149
- const name = header.subarray(0, 100).toString('utf8').replace(/\0.*$/, '')
150
- if (!name) break
151
- const sizeStr = header.subarray(124, 136).toString('utf8').replace(/\0.*$/, '').trim()
152
- const size = parseInt(sizeStr, 8) || 0
153
- const type = String.fromCharCode(header[156] || 48)
154
- off += 512
155
- const data = type === '48' || type === '0' ? Buffer.from(buf.subarray(off, off + size)) : null
156
- if (data) files.push({ name, data })
157
- off += Math.ceil(size / 512) * 512
158
- }
159
- return files
160
- }
161
-
162
- /**
163
- * Download the given version's tarball and atomically replace the installed
164
- * package files (lib/*.js, cordis.patch.yml, package.json). On success writes
165
- * `.dsh-remote-updated` in the install dir; throws on any failure (leaves the
166
- * installed files untouched).
167
- * @param targetVersion - exact npm version to install (e.g. "0.8.0").
168
- */
169
- export async function applyUpdate(targetVersion, options = {}) {
170
- // 拒绝对非安装副本自更新:`auto` 默认开启后,一次自动更新就会覆盖
171
- // `selfDir()` 指向的目录,而以 link:/开发模式安装时那正是用户的源码仓库
172
- // (见 isInstalledCopy 的实测说明)。测试用 options.dir 指向临时目录,
173
- // 因此不受此限(options.dir 存在即视为显式指定,跳过检查)。
174
- if (!options.dir && !isInstalledCopy()) {
175
- throw new Error('refusing to self-update: this copy is not under node_modules (link/dev install) — update it from its source repo instead')
176
- }
177
- const tarballUrl = `https://registry.npmjs.org/${NPM_PACKAGE}/-/${NPM_PACKAGE}-${targetVersion}.tgz`
178
- const dir = options.dir || selfDir()
179
- const doFetch = options.fetchImpl || fetch
180
- const tmpRoot = path.join(dir, `.dsh-remote-update-${Date.now()}`)
181
- const tmpPkg = path.join(tmpRoot, 'package')
182
- try {
183
- const controller = new AbortController()
184
- const timer = setTimeout(() => controller.abort(), 60000)
185
- let res
186
- try {
187
- res = await doFetch(tarballUrl, { signal: controller.signal })
188
- } finally {
189
- clearTimeout(timer)
190
- }
191
- if (!res.ok) throw new Error(`download failed (HTTP ${res.status})`)
192
- const buf = Buffer.from(await res.arrayBuffer())
193
- // npm tarballs are gzipped tar; extract the package/ directory.
194
- const { gunzipSync } = await import('node:zlib')
195
- const tar = gunzipSync(buf)
196
- const files = parseTar(tar)
197
- mkdirSync(tmpPkg, { recursive: true })
198
- let extracted = 0
199
- for (const f of files) {
200
- const rel = f.name.replace(/^package\//, '')
201
- if (!rel || rel === 'package/' || rel.endsWith('/')) continue
202
- if (rel !== 'package.json' && rel !== 'cordis.patch.yml' && !rel.startsWith('lib/')) continue
203
- const dest = path.join(tmpPkg, rel)
204
- mkdirSync(path.dirname(dest), { recursive: true })
205
- writeFileSync(dest, f.data)
206
- extracted++
207
- }
208
- if (extracted === 0) throw new Error('tarball contained no package files')
209
- // Verify the downloaded package.json matches the requested version.
210
- const newPkg = JSON.parse(readFileSync(path.join(tmpPkg, 'package.json'), 'utf8'))
211
- if (newPkg.version !== targetVersion) throw new Error(`tarball version mismatch: ${newPkg.version}`)
212
- // Sanity: the new host half must at least parse (a corrupt index.js would
213
- // break the next boot — check the file size and that it is not empty).
214
- const newIndex = path.join(tmpPkg, 'lib', 'index.js')
215
- if (!existsSync(newIndex) || statSize(newIndex) < 100) throw new Error('tarball missing lib/index.js')
216
- // Swap the installed files one at a time: atomic, and idempotent.
217
- //
218
- // Atomicity (temp file + rename) is not cosmetic here — since the browser
219
- // half is hot-swapped by dsh-client-hmr, which stat-polls lib/client.js
220
- // every 500 ms, a torn write would be re-hashed and served mid-copy.
221
- // Skipping byte-identical files keeps a re-apply of the same version from
222
- // churning mtimes (and the host half from reloading for nothing).
223
- const installLib = path.join(dir, 'lib')
224
- const tmpLib = path.join(tmpPkg, 'lib')
225
- const changed = []
226
- const install = (src, dest) => {
227
- const bytes = readFileSync(src)
228
- if (sameFileContent(dest, bytes)) return
229
- try { mkdirSync(path.dirname(dest), { recursive: true }) } catch {}
230
- writeFileAtomic(dest, bytes)
231
- changed.push(path.relative(dir, dest).split(path.sep).join('/'))
232
- }
233
- // Install *everything* the tarball ships under lib/, not just top-level
234
- // `.js`. A filter here is how 0.8.92 shipped a half-updated tree: the
235
- // updater skipped `.cjs` helpers and subdirectories such as `lib/tui/`, so
236
- // `lib/web-attach.js` ended up importing a `./posix-shell.cjs` that was
237
- // never written and the whole plugin failed to import on the next boot.
238
- for (const rel of listFilesRecursive(tmpLib)) {
239
- install(path.join(tmpLib, rel), path.join(installLib, rel))
240
- }
241
- for (const rel of ['package.json', 'cordis.patch.yml']) {
242
- const src = path.join(tmpPkg, rel)
243
- if (existsSync(src)) install(src, path.join(dir, rel))
244
- }
245
- writeFileSync(path.join(dir, '.dsh-remote-updated'), String(targetVersion))
246
- return { ok: true, to: targetVersion, changed }
247
- } catch (err) {
248
- throw new Error('update failed: ' + ((err && err.message) || err))
249
- } finally {
250
- try { rmSync(tmpRoot, { recursive: true, force: true }) } catch {}
251
- }
252
- }
253
-
254
- /** File size helper (missing/unreadable → 0). */
255
- function statSize(p) {
256
- try {
257
- return statSync(p).size
258
- } catch {
259
- return 0
260
- }
261
- }
262
-
263
- /**
264
- * List the regular files under `dir`, recursively, as POSIX-style paths
265
- * relative to it. Used to install and to evict whatever the package ships
266
- * under `lib/` — both used to look only at top-level names, which missed
267
- * `.cjs` helpers and subdirectories such as `lib/tui/`.
268
- *
269
- * @param dir - directory to walk.
270
- * @param prefix - internal recursion state; callers omit it.
271
- * @returns relative paths, `[]` when the directory cannot be read.
272
- */
273
- function listFilesRecursive(dir, prefix = '') {
274
- const out = []
275
- let entries
276
- try { entries = readdirSync(dir, { withFileTypes: true }) } catch { return out }
277
- for (const entry of entries) {
278
- const rel = prefix ? `${prefix}/${entry.name}` : entry.name
279
- if (entry.isDirectory()) out.push(...listFilesRecursive(path.join(dir, entry.name), rel))
280
- else if (entry.isFile()) out.push(rel)
281
- }
282
- return out
283
- }
284
-
285
- /**
286
- * Write `data` to `dest` atomically: the bytes land in a sibling temp file and
287
- * are then renamed over the target, so a concurrent reader (the client-half HMR
288
- * poll, or the next boot) never observes a truncated file. Falls back to an
289
- * in-place copy if the platform refuses the replace, and never leaves the temp
290
- * file behind.
291
- * @param dest - absolute destination path.
292
- * @param data - bytes to write.
293
- */
294
- export function writeFileAtomic(dest, data) {
295
- const tmp = `${dest}.dsh-tmp-${process.pid}-${Date.now().toString(36)}`
296
- writeFileSync(tmp, data)
297
- try {
298
- renameSync(tmp, dest)
299
- return
300
- } catch {
301
- try {
302
- copyFileSync(tmp, dest)
303
- } finally {
304
- try { rmSync(tmp, { force: true }) } catch {}
305
- }
306
- }
307
- }
308
-
309
- /** Whether the file at `p` already holds exactly `bytes` (missing/short → false). */
310
- function sameFileContent(p, bytes) {
311
- try {
312
- return readFileSync(p).equals(bytes)
313
- } catch {
314
- return false
315
- }
316
- }
317
-
318
- // ── hot swap of the running host half ─────────────────────────────────────
319
-
320
- /** Loader entry ids this package can own. */
321
- const SELF_ENTRY_NAMES = ['dsh-remote']
322
-
323
- /**
324
- * Find our own loader entry (by id, then by module specifier). Returns undefined
325
- * when the tree does not contain us (e.g. a test loader, or a renamed row).
326
- * @param loader - the cordis Loader service (`ctx.loader`).
327
- */
328
- function findSelfEntry(loader) {
329
- let entries = []
330
- try {
331
- entries = [...(loader?.entries?.() ?? [])]
332
- } catch {
333
- return undefined
334
- }
335
- for (const want of SELF_ENTRY_NAMES) {
336
- const byId = entries.find((entry) => entry?.options?.id === want)
337
- if (byId) return byId
338
- }
339
- for (const want of SELF_ENTRY_NAMES) {
340
- const byName = entries.find((entry) => entry?.options?.name === want)
341
- if (byName) return byName
342
- }
343
- return undefined
344
- }
345
-
346
- /**
347
- * Drop Node's module caches for this package's own files, so the next import of
348
- * the plugin actually re-reads disk instead of handing back the cached module.
349
- * Both caches matter: the ESM `loadCache` (a plain Map on Node 22/23, a
350
- * `LoadCache extends Map` on Node 24 — hence the explicit `Map.prototype` calls)
351
- * and, for CJS modules pulled in through `import()`, `require.cache`.
352
- * @param loader - the cordis Loader service.
353
- * @param dir - package directory whose `lib/` to evict (defaults to this
354
- * package's own install dir; overridable so the swap can be exercised against
355
- * a fixture install).
356
- * @returns how many ESM entries were dropped.
357
- */
358
- export function clearSelfModuleCache(loader, dir = selfDir()) {
359
- const libDir = path.join(dir, 'lib')
360
- const loadCache = loader?.internal?.loadCache
361
- const req = (() => {
362
- try { return createRequire(import.meta.url) } catch { return undefined }
363
- })()
364
- let cleared = 0
365
- for (const rel of listFilesRecursive(libDir)) {
366
- // `.cjs` matters as much as `.js` here: `posix-shell.cjs` is imported from
367
- // `web-attach.js` and would otherwise survive a hot swap in both caches.
368
- if (!/\.(js|cjs|mjs)$/.test(rel)) continue
369
- const url = pathToFileURL(path.join(libDir, rel)).href
370
- try {
371
- if (loadCache && Map.prototype.has.call(loadCache, url)) {
372
- Map.prototype.delete.call(loadCache, url)
373
- cleared += 1
374
- }
375
- } catch {}
376
- try {
377
- const file = fileURLToPath(url)
378
- if (req?.cache && req.cache[file]) delete req.cache[file]
379
- } catch {}
380
- }
381
- return cleared
382
- }
383
-
384
- /**
385
- * Swap the RUNNING host half to the code now on disk: clear the module caches
386
- * for our own files, dispose our loader entry (tools, JSON routes, SSH pools and
387
- * every `ctx.effect` disposer go with the fiber), then re-init it so `apply()`
388
- * runs again from the freshly imported module.
389
- *
390
- * Callers must not depend on this plugin after a successful reload — the fiber
391
- * that served the current request is gone. Schedule it (see
392
- * {@link scheduleSelfReload}) rather than awaiting it from a request handler.
393
- * @param loader - the cordis Loader service (`ctx.loader`).
394
- * @returns a small result object; never throws.
395
- */
396
- export async function reloadSelf(loader) {
397
- const entry = findSelfEntry(loader)
398
- if (!entry) return { ok: false, reason: 'own loader entry not found' }
399
- try {
400
- const cleared = clearSelfModuleCache(loader)
401
- // ★ 卸载必须走 entry.fiber.dispose()。
402
- //
403
- // 原实现找 `entry._dispose` / `entry.dispose`,但 cordis 的 Entry **两个都没有**
404
- // (0.2.0 实测方法集只有 constructor/disabledOf/evaluate/_patchContext/refresh/
405
- // update/_commitVolatile/init/_init),所以这里每次都直接返回
406
- // "entry exposes no dispose hook" —— 热切换从未真正执行过,而
407
- // scheduleSelfReload 里的 `.catch(() => {})` 把它彻底吞掉,
408
- // UI 于是永远停在"已落盘但未切换"(用户报的 0.8.35 -> 0.8.36)。
409
- //
410
- // 也不能用 entry.refresh():它是 `if (this.fiber) return; await this.init()`,
411
- // fiber 还活着时直接返回,等于没重启。真正卸载 fiber 的地方在 Entry.update()
412
- // 里(`this.fiber?.dispose()`),这里照它做。
413
- //
414
- // 保留对 _dispose/dispose 的探测:那是宿主可能提供的扩展钩子,有则优先用,
415
- // 没有就用 fiber.dispose()——两条路都必须能真正卸载,否则应如实报错。
416
- // DSH 0.2 的 loader 在 fiber 被卸载时把 entry.options.disabled 写成 true
417
- // 并写回配置树。客户端扫描会跳过禁用行,于是热切换之后宿主能起来、
418
- // 设置页的 client 不再下发。这里记下卸载前的状态:只有 loader 在
419
- // dispose 期间新打上的禁用才清掉。用户本来就禁用的行不要重新打开。
420
- const disabledBefore = entry.options?.disabled === true
421
- if (typeof entry._dispose === 'function') await entry._dispose()
422
- else if (typeof entry.dispose === 'function') await entry.dispose()
423
- else if (entry.fiber && typeof entry.fiber.dispose === 'function') await entry.fiber.dispose()
424
- else return { ok: false, reason: 'entry exposes no dispose hook' }
425
- if (!disabledBefore && entry.options?.disabled === true) {
426
- delete entry.options.disabled
427
- entry.parent?.tree?.write?.()
428
- }
429
- await entry.init()
430
- return { ok: true, cleared }
431
- } catch (err) {
432
- return { ok: false, reason: String((err && err.message) || err) }
433
- }
434
- }
435
-
436
- /**
437
- * Fire-and-forget {@link reloadSelf} after a short delay, so the caller can
438
- * finish answering an HTTP request (or an update check) before its own module is
439
- * torn down. A failed swap leaves the running code in place, which is the
440
- * pre-hot-update behaviour, not a crash — so we do not throw.
441
- *
442
- * We DO record the outcome, though. Silently discarding it is precisely how the
443
- * "entry exposes no dispose hook" defect stayed invisible: the panel reported a
444
- * scheduled swap, the swap never ran, and nothing anywhere said so.
445
- * {@link lastSelfReload} exposes the result for diagnostics (the settings panel
446
- * and `/dsh-remote/update-check` surface it), and a non-ok result is logged once.
447
- *
448
- * @param loader - the cordis Loader service.
449
- * @param delayMs - grace period before the swap (default 300 ms).
450
- * @returns true when the swap was scheduled.
451
- */
452
- export function scheduleSelfReload(loader, delayMs = 300) {
453
- const timer = setTimeout(() => {
454
- void reloadSelf(loader).then(
455
- (res) => { lastReloadResult = res; if (res && res.ok === false) console.warn('[dsh-remote] self-update swap failed:', res.reason) },
456
- (err) => { lastReloadResult = { ok: false, reason: String((err && err.message) || err) }; console.warn('[dsh-remote] self-update swap threw:', lastReloadResult.reason) },
457
- )
458
- }, Math.max(0, delayMs))
459
- if (typeof timer.unref === 'function') timer.unref()
460
- return true
461
- }
462
-
463
- /** Result of the most recent {@link scheduleSelfReload} attempt, for diagnostics. */
464
- let lastReloadResult = null
465
-
466
- /** @returns the last self-reload outcome (`{ok,reason?}`, or null if never attempted). */
467
- export function lastSelfReload() {
468
- return lastReloadResult
469
- }
470
-
471
- /** Write the persisted update-mode override (settings UI). */
472
- export function persistUpdateMode(mode) {
473
- if (!['manual', 'auto', 'off'].includes(mode)) return false
474
- try {
475
- writeFileSync(path.join(selfDir(), 'update-mode'), mode)
476
- return true
477
- } catch {
478
- return false
479
- }
480
- }
481
-
482
- /** Read a persisted update-mode override, or null when absent/invalid. */
483
- export function readUpdateMode() {
484
- try {
485
- const m = readFileSync(path.join(selfDir(), 'update-mode'), 'utf8').trim()
486
- return ['manual', 'auto', 'off'].includes(m) ? m : null
487
- } catch {
488
- return null
489
- }
490
- }
1
+ // dsh-remote — self-update support.
2
+ //
3
+ // dsh-remote is a zero-build plugin: the host half (lib/index.js) is loaded
4
+ // straight from the installed package, so "updating" = replacing the package
5
+ // files with the newer npm tarball. This module owns the version check and the
6
+ // tarball apply:
7
+ //
8
+ // • checkLatestVersion() — query the npm registry for the `latest` dist-tag;
9
+ // • applyUpdate() — download the tarball, extract package/{lib,package.json,
10
+ // cordis.patch.yml} with a minimal tar reader, verify the version, then
11
+ // replace the installed files atomically (temp file + rename, never a
12
+ // half-written lib/*.js). A `.dsh-remote-updated` marker records the version
13
+ // that landed; the host half removes it once that version is the code it is
14
+ // actually running (see LOADED_VERSION), so the marker means "restart still
15
+ // required" rather than "an update once happened".
16
+ // • reloadSelf() — swap the RUNNING host half to the code now on disk: drop
17
+ // Node's module caches for this package's own files, then dispose + re-init
18
+ // the loader entry so apply() runs again from the fresh module. Without it
19
+ // an update only takes effect on the next process start, which is what left
20
+ // the served client half newer than the loaded host half.
21
+ //
22
+ // Every failure aborts without touching the installed files (a bad download or
23
+ // a version mismatch must never break the running plugin).
24
+
25
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
26
+ import { createRequire } from 'node:module'
27
+ import path from 'node:path'
28
+ import { fileURLToPath, pathToFileURL } from 'node:url'
29
+
30
+ const NPM_PACKAGE = 'dsh-remote'
31
+ const REGISTRY_URL = 'https://registry.npmjs.org/' + NPM_PACKAGE + '/latest'
32
+
33
+ /** Absolute directory holding this plugin's installed files (lib/ + package.json). */
34
+ export function selfDir() {
35
+ try {
36
+ return path.dirname(path.dirname(fileURLToPath(import.meta.url)))
37
+ } catch {
38
+ return path.dirname(path.dirname(process.argv[1] || ''))
39
+ }
40
+ }
41
+
42
+ /**
43
+ * 本插件是否装在 `node_modules` 之下(即真正的"安装副本")。
44
+ *
45
+ * ★ 为什么必须有这道判断(实测依据,不是防御性猜测):
46
+ * `selfDir()` 基于 `import.meta.url`,而 **Node 的 ESM 解析会对符号链接做
47
+ * realpath**(已实测:经由 symlink 导入时 `import.meta.url` 报告的是
48
+ * `/real/mod.mjs` 而不是 `/link/mod.mjs`)。于是当插件以 `link:` / 开发模式
49
+ * 安装时,`selfDir()` 指向的是**用户的源码仓库**,而不是安装副本。
50
+ * 一旦 `auto` 更新落地,`applyUpdate` 就会拿 npm 包覆盖那份源码
51
+ * (丢改动、脏工作树)。默认改成 `auto` 之后这个风险从"手点才触发"
52
+ * 变成"自动发生",所以在此拦下:不在 node_modules 下就不自更新。
53
+ *
54
+ * 代价:少数把插件放在非标准路径的部署不会被自动更新——他们仍可手动更新。
55
+ * 这个方向的取舍是正确的:宁可少更新,也不能悄悄毁掉源码。
56
+ * @param dir - 要判定的目录(默认本插件的 selfDir())。
57
+ */
58
+ export function isInstalledCopy(dir = selfDir()) {
59
+ // 同时认 `/` 与 `\`:本函数要对两种平台的路径都给出正确答案,而调用方
60
+ // (尤其测试)会传另一种分隔符的路径。先前只按 path.sep 切分,导致
61
+ // 在 Linux 上判断 Windows 风格路径时误判为"非安装副本"(CI 直接红了)。
62
+ const normalized = String(dir).replace(/\\/g, '/').toLowerCase()
63
+ return normalized.includes('/node_modules/')
64
+ }
65
+
66
+ /** Read the installed package.json version; "0.0.0" when unreadable. */
67
+ export function readVersion() {
68
+ try {
69
+ const pkg = JSON.parse(readFileSync(path.join(selfDir(), 'package.json'), 'utf8'))
70
+ return String(pkg.version || '0.0.0')
71
+ } catch {
72
+ return '0.0.0'
73
+ }
74
+ }
75
+
76
+ /** Version of the code this process actually loaded (snapshot at import time).
77
+ * `readVersion()` reads package.json from disk, so after an update lands it
78
+ * reports the NEW version while the running module is still the old one —
79
+ * comparing the two is the only way to tell "applied" from "active". */
80
+ export const LOADED_VERSION = readVersion()
81
+
82
+ /** Package version currently on disk (may be newer than {@link LOADED_VERSION}). */
83
+ export function diskVersion() {
84
+ return readVersion()
85
+ }
86
+
87
+ /** Compare dotted versions; returns true when a > b. */
88
+ export function gtVersion(a, b) {
89
+ const pa = String(a || '').split('.').map((n) => parseInt(n, 10) || 0)
90
+ const pb = String(b || '').split('.').map((n) => parseInt(n, 10) || 0)
91
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
92
+ const da = pa[i] || 0
93
+ const db = pb[i] || 0
94
+ if (da !== db) return da > db
95
+ }
96
+ return false
97
+ }
98
+
99
+ /**
100
+ * 查询 npm registry 的最新版本。
101
+ *
102
+ * 返回 `{ version }` 或 `{ error }`(**不再把一切失败压成 null**)。
103
+ *
104
+ * 为什么要区分失败原因:原先任何失败都返回 `null`,调用方只能笼统报
105
+ * "无法连接 npm registry"。实测踩过:本机被 npm 限流(`/latest` 返回 **429**,
106
+ * 而同一时刻 registry 根路径是 200、CI 从另一个出口 IP 也能正常取到),
107
+ * 却被显示成"连不上"——把"等一下就好"误导成"网络坏了"。429/超时/离线
108
+ * 三者的处置完全不同,必须让用户看到真实原因。
109
+ * @param timeoutMs - 超时(看门狗只负责中止,不影响进程存活)。
110
+ */
111
+ export async function fetchLatestVersion(timeoutMs = 8000) {
112
+ try {
113
+ const controller = new AbortController()
114
+ const timer = setTimeout(() => controller.abort(), timeoutMs)
115
+ // 纯看门狗:调用方并不 await 它,所以必须 unref,否则这一段超时窗口
116
+ // 会拖住事件循环、让本该退出的短命进程(脚本、测试)多挂数秒。
117
+ if (typeof timer.unref === 'function') timer.unref()
118
+ let res
119
+ try {
120
+ res = await fetch(REGISTRY_URL, { signal: controller.signal, headers: { accept: 'application/json' } })
121
+ } finally {
122
+ clearTimeout(timer)
123
+ }
124
+ if (res.status === 429) {
125
+ return { error: 'npm registry 限流(HTTP 429)——请求过于频繁,稍后会自动恢复', reason: 'rate-limited', status: 429 }
126
+ }
127
+ if (!res.ok) {
128
+ return { error: `npm registry 返回 HTTP ${res.status}`, reason: 'http', status: res.status }
129
+ }
130
+ const data = await res.json().catch(() => null)
131
+ const version = typeof data?.version === 'string' && data.version ? data.version : null
132
+ if (!version) return { error: 'npm registry 响应里没有可用的版本号', reason: 'malformed' }
133
+ return { version }
134
+ } catch (err) {
135
+ const aborted = err?.name === 'AbortError'
136
+ return {
137
+ error: aborted ? `连接 npm registry 超时(${timeoutMs}ms)` : '无法连接 npm registry',
138
+ reason: aborted ? 'timeout' : 'network',
139
+ }
140
+ }
141
+ }
142
+
143
+ /** Minimal POSIX ustar reader (regular files only) — npm tarballs are gzipped tar. */
144
+ function parseTar(buf) {
145
+ const files = []
146
+ let off = 0
147
+ while (off + 512 <= buf.length) {
148
+ const header = buf.subarray(off, off + 512)
149
+ const name = header.subarray(0, 100).toString('utf8').replace(/\0.*$/, '')
150
+ if (!name) break
151
+ const sizeStr = header.subarray(124, 136).toString('utf8').replace(/\0.*$/, '').trim()
152
+ const size = parseInt(sizeStr, 8) || 0
153
+ const type = String.fromCharCode(header[156] || 48)
154
+ off += 512
155
+ const data = type === '48' || type === '0' ? Buffer.from(buf.subarray(off, off + size)) : null
156
+ if (data) files.push({ name, data })
157
+ off += Math.ceil(size / 512) * 512
158
+ }
159
+ return files
160
+ }
161
+
162
+ /**
163
+ * Download the given version's tarball and atomically replace the installed
164
+ * package files (lib/*.js, cordis.patch.yml, package.json). On success writes
165
+ * `.dsh-remote-updated` in the install dir; throws on any failure (leaves the
166
+ * installed files untouched).
167
+ * @param targetVersion - exact npm version to install (e.g. "0.8.0").
168
+ */
169
+ export async function applyUpdate(targetVersion, options = {}) {
170
+ // 拒绝对非安装副本自更新:`auto` 默认开启后,一次自动更新就会覆盖
171
+ // `selfDir()` 指向的目录,而以 link:/开发模式安装时那正是用户的源码仓库
172
+ // (见 isInstalledCopy 的实测说明)。测试用 options.dir 指向临时目录,
173
+ // 因此不受此限(options.dir 存在即视为显式指定,跳过检查)。
174
+ if (!options.dir && !isInstalledCopy()) {
175
+ throw new Error('refusing to self-update: this copy is not under node_modules (link/dev install) — update it from its source repo instead')
176
+ }
177
+ const tarballUrl = `https://registry.npmjs.org/${NPM_PACKAGE}/-/${NPM_PACKAGE}-${targetVersion}.tgz`
178
+ const dir = options.dir || selfDir()
179
+ const doFetch = options.fetchImpl || fetch
180
+ const tmpRoot = path.join(dir, `.dsh-remote-update-${Date.now()}`)
181
+ const tmpPkg = path.join(tmpRoot, 'package')
182
+ try {
183
+ const controller = new AbortController()
184
+ const timer = setTimeout(() => controller.abort(), 60000)
185
+ let res
186
+ try {
187
+ res = await doFetch(tarballUrl, { signal: controller.signal })
188
+ } finally {
189
+ clearTimeout(timer)
190
+ }
191
+ if (!res.ok) throw new Error(`download failed (HTTP ${res.status})`)
192
+ const buf = Buffer.from(await res.arrayBuffer())
193
+ // npm tarballs are gzipped tar; extract the package/ directory.
194
+ const { gunzipSync } = await import('node:zlib')
195
+ const tar = gunzipSync(buf)
196
+ const files = parseTar(tar)
197
+ mkdirSync(tmpPkg, { recursive: true })
198
+ let extracted = 0
199
+ for (const f of files) {
200
+ const rel = f.name.replace(/^package\//, '')
201
+ if (!rel || rel === 'package/' || rel.endsWith('/')) continue
202
+ if (rel !== 'package.json' && rel !== 'cordis.patch.yml' && !rel.startsWith('lib/')) continue
203
+ const dest = path.join(tmpPkg, rel)
204
+ mkdirSync(path.dirname(dest), { recursive: true })
205
+ writeFileSync(dest, f.data)
206
+ extracted++
207
+ }
208
+ if (extracted === 0) throw new Error('tarball contained no package files')
209
+ // Verify the downloaded package.json matches the requested version.
210
+ const newPkg = JSON.parse(readFileSync(path.join(tmpPkg, 'package.json'), 'utf8'))
211
+ if (newPkg.version !== targetVersion) throw new Error(`tarball version mismatch: ${newPkg.version}`)
212
+ // Sanity: the new host half must at least parse (a corrupt index.js would
213
+ // break the next boot — check the file size and that it is not empty).
214
+ const newIndex = path.join(tmpPkg, 'lib', 'index.js')
215
+ if (!existsSync(newIndex) || statSize(newIndex) < 100) throw new Error('tarball missing lib/index.js')
216
+ // Swap the installed files one at a time: atomic, and idempotent.
217
+ //
218
+ // Atomicity (temp file + rename) is not cosmetic here — since the browser
219
+ // half is hot-swapped by dsh-client-hmr, which stat-polls lib/client.js
220
+ // every 500 ms, a torn write would be re-hashed and served mid-copy.
221
+ // Skipping byte-identical files keeps a re-apply of the same version from
222
+ // churning mtimes (and the host half from reloading for nothing).
223
+ const installLib = path.join(dir, 'lib')
224
+ const tmpLib = path.join(tmpPkg, 'lib')
225
+ const changed = []
226
+ const install = (src, dest) => {
227
+ const bytes = readFileSync(src)
228
+ if (sameFileContent(dest, bytes)) return
229
+ try { mkdirSync(path.dirname(dest), { recursive: true }) } catch {}
230
+ writeFileAtomic(dest, bytes)
231
+ changed.push(path.relative(dir, dest).split(path.sep).join('/'))
232
+ }
233
+ // Install *everything* the tarball ships under lib/, not just top-level
234
+ // `.js`. A filter here is how 0.8.92 shipped a half-updated tree: the
235
+ // updater skipped `.cjs` helpers and subdirectories such as `lib/tui/`, so
236
+ // `lib/web-attach.js` ended up importing a `./posix-shell.cjs` that was
237
+ // never written and the whole plugin failed to import on the next boot.
238
+ for (const rel of listFilesRecursive(tmpLib)) {
239
+ install(path.join(tmpLib, rel), path.join(installLib, rel))
240
+ }
241
+ for (const rel of ['package.json', 'cordis.patch.yml']) {
242
+ const src = path.join(tmpPkg, rel)
243
+ if (existsSync(src)) install(src, path.join(dir, rel))
244
+ }
245
+ writeFileSync(path.join(dir, '.dsh-remote-updated'), String(targetVersion))
246
+ return { ok: true, to: targetVersion, changed }
247
+ } catch (err) {
248
+ throw new Error('update failed: ' + ((err && err.message) || err))
249
+ } finally {
250
+ try { rmSync(tmpRoot, { recursive: true, force: true }) } catch {}
251
+ }
252
+ }
253
+
254
+ /** File size helper (missing/unreadable → 0). */
255
+ function statSize(p) {
256
+ try {
257
+ return statSync(p).size
258
+ } catch {
259
+ return 0
260
+ }
261
+ }
262
+
263
+ /**
264
+ * List the regular files under `dir`, recursively, as POSIX-style paths
265
+ * relative to it. Used to install and to evict whatever the package ships
266
+ * under `lib/` — both used to look only at top-level names, which missed
267
+ * `.cjs` helpers and subdirectories such as `lib/tui/`.
268
+ *
269
+ * @param dir - directory to walk.
270
+ * @param prefix - internal recursion state; callers omit it.
271
+ * @returns relative paths, `[]` when the directory cannot be read.
272
+ */
273
+ function listFilesRecursive(dir, prefix = '') {
274
+ const out = []
275
+ let entries
276
+ try { entries = readdirSync(dir, { withFileTypes: true }) } catch { return out }
277
+ for (const entry of entries) {
278
+ const rel = prefix ? `${prefix}/${entry.name}` : entry.name
279
+ if (entry.isDirectory()) out.push(...listFilesRecursive(path.join(dir, entry.name), rel))
280
+ else if (entry.isFile()) out.push(rel)
281
+ }
282
+ return out
283
+ }
284
+
285
+ /**
286
+ * Write `data` to `dest` atomically: the bytes land in a sibling temp file and
287
+ * are then renamed over the target, so a concurrent reader (the client-half HMR
288
+ * poll, or the next boot) never observes a truncated file. Falls back to an
289
+ * in-place copy if the platform refuses the replace, and never leaves the temp
290
+ * file behind.
291
+ * @param dest - absolute destination path.
292
+ * @param data - bytes to write.
293
+ */
294
+ export function writeFileAtomic(dest, data) {
295
+ const tmp = `${dest}.dsh-tmp-${process.pid}-${Date.now().toString(36)}`
296
+ writeFileSync(tmp, data)
297
+ try {
298
+ renameSync(tmp, dest)
299
+ return
300
+ } catch {
301
+ try {
302
+ copyFileSync(tmp, dest)
303
+ } finally {
304
+ try { rmSync(tmp, { force: true }) } catch {}
305
+ }
306
+ }
307
+ }
308
+
309
+ /** Whether the file at `p` already holds exactly `bytes` (missing/short → false). */
310
+ function sameFileContent(p, bytes) {
311
+ try {
312
+ return readFileSync(p).equals(bytes)
313
+ } catch {
314
+ return false
315
+ }
316
+ }
317
+
318
+ // ── hot swap of the running host half ─────────────────────────────────────
319
+
320
+ /** Loader entry ids this package can own. */
321
+ const SELF_ENTRY_NAMES = ['dsh-remote']
322
+
323
+ /**
324
+ * Find our own loader entry (by id, then by module specifier). Returns undefined
325
+ * when the tree does not contain us (e.g. a test loader, or a renamed row).
326
+ * @param loader - the cordis Loader service (`ctx.loader`).
327
+ */
328
+ function findSelfEntry(loader) {
329
+ let entries = []
330
+ try {
331
+ entries = [...(loader?.entries?.() ?? [])]
332
+ } catch {
333
+ return undefined
334
+ }
335
+ for (const want of SELF_ENTRY_NAMES) {
336
+ const byId = entries.find((entry) => entry?.options?.id === want)
337
+ if (byId) return byId
338
+ }
339
+ for (const want of SELF_ENTRY_NAMES) {
340
+ const byName = entries.find((entry) => entry?.options?.name === want)
341
+ if (byName) return byName
342
+ }
343
+ return undefined
344
+ }
345
+
346
+ /**
347
+ * Drop Node's module caches for this package's own files, so the next import of
348
+ * the plugin actually re-reads disk instead of handing back the cached module.
349
+ * Both caches matter: the ESM `loadCache` (a plain Map on Node 22/23, a
350
+ * `LoadCache extends Map` on Node 24 — hence the explicit `Map.prototype` calls)
351
+ * and, for CJS modules pulled in through `import()`, `require.cache`.
352
+ * @param loader - the cordis Loader service.
353
+ * @param dir - package directory whose `lib/` to evict (defaults to this
354
+ * package's own install dir; overridable so the swap can be exercised against
355
+ * a fixture install).
356
+ * @returns how many ESM entries were dropped.
357
+ */
358
+ export function clearSelfModuleCache(loader, dir = selfDir()) {
359
+ const libDir = path.join(dir, 'lib')
360
+ const loadCache = loader?.internal?.loadCache
361
+ const req = (() => {
362
+ try { return createRequire(import.meta.url) } catch { return undefined }
363
+ })()
364
+ let cleared = 0
365
+ for (const rel of listFilesRecursive(libDir)) {
366
+ // `.cjs` matters as much as `.js` here: `posix-shell.cjs` is imported from
367
+ // `web-attach.js` and would otherwise survive a hot swap in both caches.
368
+ if (!/\.(js|cjs|mjs)$/.test(rel)) continue
369
+ const url = pathToFileURL(path.join(libDir, rel)).href
370
+ try {
371
+ if (loadCache && Map.prototype.has.call(loadCache, url)) {
372
+ Map.prototype.delete.call(loadCache, url)
373
+ cleared += 1
374
+ }
375
+ } catch {}
376
+ try {
377
+ const file = fileURLToPath(url)
378
+ if (req?.cache && req.cache[file]) delete req.cache[file]
379
+ } catch {}
380
+ }
381
+ return cleared
382
+ }
383
+
384
+ /**
385
+ * Swap the RUNNING host half to the code now on disk: clear the module caches
386
+ * for our own files, dispose our loader entry (tools, JSON routes, SSH pools and
387
+ * every `ctx.effect` disposer go with the fiber), then re-init it so `apply()`
388
+ * runs again from the freshly imported module.
389
+ *
390
+ * Callers must not depend on this plugin after a successful reload — the fiber
391
+ * that served the current request is gone. Schedule it (see
392
+ * {@link scheduleSelfReload}) rather than awaiting it from a request handler.
393
+ * @param loader - the cordis Loader service (`ctx.loader`).
394
+ * @returns a small result object; never throws.
395
+ */
396
+ export async function reloadSelf(loader) {
397
+ const entry = findSelfEntry(loader)
398
+ if (!entry) return { ok: false, reason: 'own loader entry not found' }
399
+ try {
400
+ const cleared = clearSelfModuleCache(loader)
401
+ // ★ 卸载必须走 entry.fiber.dispose()。
402
+ //
403
+ // 原实现找 `entry._dispose` / `entry.dispose`,但 cordis 的 Entry **两个都没有**
404
+ // (0.2.0 实测方法集只有 constructor/disabledOf/evaluate/_patchContext/refresh/
405
+ // update/_commitVolatile/init/_init),所以这里每次都直接返回
406
+ // "entry exposes no dispose hook" —— 热切换从未真正执行过,而
407
+ // scheduleSelfReload 里的 `.catch(() => {})` 把它彻底吞掉,
408
+ // UI 于是永远停在"已落盘但未切换"(用户报的 0.8.35 -> 0.8.36)。
409
+ //
410
+ // 也不能用 entry.refresh():它是 `if (this.fiber) return; await this.init()`,
411
+ // fiber 还活着时直接返回,等于没重启。真正卸载 fiber 的地方在 Entry.update()
412
+ // 里(`this.fiber?.dispose()`),这里照它做。
413
+ //
414
+ // 保留对 _dispose/dispose 的探测:那是宿主可能提供的扩展钩子,有则优先用,
415
+ // 没有就用 fiber.dispose()——两条路都必须能真正卸载,否则应如实报错。
416
+ // DSH 0.2 的 loader 在 fiber 被卸载时把 entry.options.disabled 写成 true
417
+ // 并写回配置树。客户端扫描会跳过禁用行,于是热切换之后宿主能起来、
418
+ // 设置页的 client 不再下发。这里记下卸载前的状态:只有 loader 在
419
+ // dispose 期间新打上的禁用才清掉。用户本来就禁用的行不要重新打开。
420
+ const disabledBefore = entry.options?.disabled === true
421
+ if (typeof entry._dispose === 'function') await entry._dispose()
422
+ else if (typeof entry.dispose === 'function') await entry.dispose()
423
+ else if (entry.fiber && typeof entry.fiber.dispose === 'function') await entry.fiber.dispose()
424
+ else return { ok: false, reason: 'entry exposes no dispose hook' }
425
+ if (!disabledBefore && entry.options?.disabled === true) {
426
+ const legacy = { ...entry.options }
427
+ delete entry.options.disabled
428
+ const tree = entry.parent?.tree
429
+ // Loader 1.1 (DSH 0.2.2) replaced write() with a change journal.
430
+ // Without committing the restored flag its persisted unload mutation
431
+ // arrives later and disables the newly started plugin again.
432
+ if (typeof tree?.commit === 'function') tree.commit({ id: entry.options.id, group: entry.parent, options: entry.options, legacy })
433
+ else tree?.write?.()
434
+ }
435
+ await entry.init()
436
+ await entry.fiber?.await?.()
437
+ return { ok: true, cleared }
438
+ } catch (err) {
439
+ return { ok: false, reason: String((err && err.message) || err) }
440
+ }
441
+ }
442
+
443
+ /**
444
+ * Fire-and-forget {@link reloadSelf} after a short delay, so the caller can
445
+ * finish answering an HTTP request (or an update check) before its own module is
446
+ * torn down. A failed swap leaves the running code in place, which is the
447
+ * pre-hot-update behaviour, not a crash — so we do not throw.
448
+ *
449
+ * We DO record the outcome, though. Silently discarding it is precisely how the
450
+ * "entry exposes no dispose hook" defect stayed invisible: the panel reported a
451
+ * scheduled swap, the swap never ran, and nothing anywhere said so.
452
+ * {@link lastSelfReload} exposes the result for diagnostics (the settings panel
453
+ * and `/dsh-remote/update-check` surface it), and a non-ok result is logged once.
454
+ *
455
+ * @param loader - the cordis Loader service.
456
+ * @param delayMs - grace period before the swap (default 300 ms).
457
+ * @returns true when the swap was scheduled.
458
+ */
459
+ export function scheduleSelfReload(loader, delayMs = 300) {
460
+ const timer = setTimeout(() => {
461
+ void reloadSelf(loader).then(
462
+ (res) => { lastReloadResult = res; if (res && res.ok === false) console.warn('[dsh-remote] self-update swap failed:', res.reason) },
463
+ (err) => { lastReloadResult = { ok: false, reason: String((err && err.message) || err) }; console.warn('[dsh-remote] self-update swap threw:', lastReloadResult.reason) },
464
+ )
465
+ }, Math.max(0, delayMs))
466
+ if (typeof timer.unref === 'function') timer.unref()
467
+ return true
468
+ }
469
+
470
+ /** Result of the most recent {@link scheduleSelfReload} attempt, for diagnostics. */
471
+ let lastReloadResult = null
472
+
473
+ /** @returns the last self-reload outcome (`{ok,reason?}`, or null if never attempted). */
474
+ export function lastSelfReload() {
475
+ return lastReloadResult
476
+ }
477
+
478
+ /** Write the persisted update-mode override (settings UI). */
479
+ export function persistUpdateMode(mode) {
480
+ if (!['manual', 'auto', 'off'].includes(mode)) return false
481
+ try {
482
+ writeFileSync(path.join(selfDir(), 'update-mode'), mode)
483
+ return true
484
+ } catch {
485
+ return false
486
+ }
487
+ }
488
+
489
+ /** Read a persisted update-mode override, or null when absent/invalid. */
490
+ export function readUpdateMode() {
491
+ try {
492
+ const m = readFileSync(path.join(selfDir(), 'update-mode'), 'utf8').trim()
493
+ return ['manual', 'auto', 'off'].includes(m) ? m : null
494
+ } catch {
495
+ return null
496
+ }
497
+ }