yukari-dsh-plugin 0.0.0-stage → 0.7.2

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 (105) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +17 -2
  3. package/client.js +8340 -0
  4. package/cordis.patch.yml +95 -0
  5. package/host/browser/index.js +397 -0
  6. package/host/browser/lib/browser.js +885 -0
  7. package/host/browser/lib/cdp.js +302 -0
  8. package/host/browser/lib/libraries.js +309 -0
  9. package/host/browser/lib/page-scripts.js +243 -0
  10. package/host/browser/lib/runtime.js +351 -0
  11. package/host/browser/lib/url-guard.js +122 -0
  12. package/host/browser/locale/en.json +6 -0
  13. package/host/browser/locale/zh.json +6 -0
  14. package/host/chats/index.js +254 -0
  15. package/host/chats/lib/admin.js +893 -0
  16. package/host/chats/lib/cleanup.js +272 -0
  17. package/host/chats/lib/paths.js +108 -0
  18. package/host/chats/lib/preview.js +74 -0
  19. package/host/chats/locale/en.json +6 -0
  20. package/host/chats/locale/zh.json +6 -0
  21. package/host/files/index.js +403 -0
  22. package/host/files/locale/en.json +6 -0
  23. package/host/files/locale/zh.json +6 -0
  24. package/host/github/index.js +121 -0
  25. package/host/github/lib/api.js +310 -0
  26. package/host/github/lib/atomic.js +42 -0
  27. package/host/github/lib/controller.js +450 -0
  28. package/host/github/lib/git.js +389 -0
  29. package/host/github/lib/redact.js +22 -0
  30. package/host/github/lib/signing.js +124 -0
  31. package/host/github/lib/store.js +181 -0
  32. package/host/github/locale/en.json +6 -0
  33. package/host/github/locale/zh.json +6 -0
  34. package/host/presets/index.js +450 -0
  35. package/host/presets/lib/definition.js +267 -0
  36. package/host/presets/lib/sources.js +278 -0
  37. package/host/presets/lib/store.js +136 -0
  38. package/host/presets/locale/en.json +6 -0
  39. package/host/presets/locale/zh.json +6 -0
  40. package/host/proxy/index.js +236 -0
  41. package/host/proxy/lib/controller.js +1151 -0
  42. package/host/proxy/lib/egress.js +120 -0
  43. package/host/proxy/lib/local-proxy.js +422 -0
  44. package/host/proxy/lib/shadowsocks.js +335 -0
  45. package/host/proxy/lib/ss-uri.js +501 -0
  46. package/host/proxy/lib/subscriptions.js +140 -0
  47. package/host/proxy/locale/en.json +6 -0
  48. package/host/proxy/locale/zh.json +6 -0
  49. package/host/purge/index.js +538 -0
  50. package/host/purge/lib/preset.js +140 -0
  51. package/host/purge/lib/prompts.js +95 -0
  52. package/host/purge/lib/retry-gate.js +97 -0
  53. package/host/purge/lib/rewriter.js +322 -0
  54. package/host/purge/lib/settings.js +54 -0
  55. package/host/purge/lib/stream-retry.js +255 -0
  56. package/host/purge/locale/en.json +6 -0
  57. package/host/purge/locale/zh.json +6 -0
  58. package/host/purge/presets/unrestricted/agent.cordis.yml +273 -0
  59. package/host/purge/presets/unrestricted/preset.json +75 -0
  60. package/host/purge/presets/unrestricted/preset.yml +3 -0
  61. package/host/rewind/index.js +127 -0
  62. package/host/rewind/lib/controller.js +449 -0
  63. package/host/rewind/lib/marker.js +53 -0
  64. package/host/rewind/lib/safe-path.js +47 -0
  65. package/host/rewind/lib/store.js +585 -0
  66. package/host/rewind/lib/surface.js +108 -0
  67. package/host/rewind/locale/en.json +6 -0
  68. package/host/rewind/locale/zh.json +6 -0
  69. package/host/rules/index.js +624 -0
  70. package/host/rules/lib/paths.js +87 -0
  71. package/host/rules/lib/render.js +92 -0
  72. package/host/rules/lib/scope.js +146 -0
  73. package/host/rules/lib/settings.js +55 -0
  74. package/host/rules/lib/store.js +222 -0
  75. package/host/rules/locale/en.json +6 -0
  76. package/host/rules/locale/zh.json +6 -0
  77. package/host/runtime/index.js +577 -0
  78. package/host/runtime/lib/npm.js +293 -0
  79. package/host/runtime/lib/restart.js +105 -0
  80. package/host/runtime/lib/update-guard.js +70 -0
  81. package/host/runtime/lib/versions.js +188 -0
  82. package/host/runtime/locale/en.json +6 -0
  83. package/host/runtime/locale/zh.json +6 -0
  84. package/host/shared/busy.js +40 -0
  85. package/host/shared/home.js +27 -0
  86. package/host/shared/http.js +159 -0
  87. package/host/shared/migrate.js +60 -0
  88. package/host/shared/mounted.js +54 -0
  89. package/host/shared/zip-writer.js +319 -0
  90. package/host/shared/zip.js +180 -0
  91. package/host/sites/index.js +258 -0
  92. package/host/sites/lib/sites.js +630 -0
  93. package/host/sites/locale/en.json +6 -0
  94. package/host/sites/locale/zh.json +6 -0
  95. package/host/skills/index.js +176 -0
  96. package/host/skills/lib/frontmatter.js +149 -0
  97. package/host/skills/lib/library.js +408 -0
  98. package/host/skills/lib/upload.js +115 -0
  99. package/host/skills/locale/en.json +6 -0
  100. package/host/skills/locale/zh.json +6 -0
  101. package/icon.png +0 -0
  102. package/index.js +702 -0
  103. package/locale/en.json +5 -0
  104. package/locale/zh.json +5 -0
  105. package/package.json +113 -4
@@ -0,0 +1,293 @@
1
+ /**
2
+ * Talking to npm from inside the running Host.
3
+ *
4
+ * Two details make this different from typing `npm i -g` in a shell:
5
+ *
6
+ * - The cache directory has to be ours. The image leaves `/tmp/npm-cache` owned
7
+ * by root, so an inherited `npm_config_cache` fails every command with EACCES
8
+ * before it reaches the registry. Every call therefore passes `--cache` at a
9
+ * path under `DSH_HOME`.
10
+ * - The running copy has to be told apart from the copy on disk. An upgrade
11
+ * replaces the files under the global prefix while the old modules stay
12
+ * mapped in memory, so "running" and "installed" are separate numbers until
13
+ * the process is re-exec'd.
14
+ * @module @local/dsh-control/lib/npm
15
+ */
16
+ import { execFile } from 'node:child_process'
17
+ import { existsSync, readFileSync, realpathSync } from 'node:fs'
18
+ import { mkdir, readFile } from 'node:fs/promises'
19
+ import { homedir } from 'node:os'
20
+ import path from 'node:path'
21
+
22
+ /** The package this plugin upgrades. */
23
+ export const PACKAGE = '@deepseek-ai/dsh'
24
+
25
+ /** How much command output is kept for the panel. */
26
+ const OUTPUT_LIMIT = 24 * 1024
27
+
28
+ /**
29
+ * Read the manifest at one directory.
30
+ * @param {string} dir - package directory.
31
+ * @returns {Promise<object | null>} parsed manifest, or null when unreadable.
32
+ */
33
+ async function readManifest(dir) {
34
+ try {
35
+ return JSON.parse(await readFile(path.join(dir, 'package.json'), 'utf8'))
36
+ } catch {
37
+ return null
38
+ }
39
+ }
40
+
41
+ /** Synchronous variant used while walking up the tree at load time. */
42
+ function readManifestSync(dir) {
43
+ try {
44
+ return JSON.parse(readFileSync(path.join(dir, 'package.json'), 'utf8'))
45
+ } catch {
46
+ return null
47
+ }
48
+ }
49
+
50
+ /**
51
+ * Find the Harness package that is currently loaded, by walking up from the
52
+ * entry script. Symlinks are resolved first because `dsh` on PATH is one.
53
+ * @param {string[]} [starts] - alternative starting points, for tests.
54
+ * @returns {{ dir: string, version: string } | undefined} the loaded package.
55
+ */
56
+ export function locateRunningPackage(starts = [process.argv[1]]) {
57
+ for (const start of starts) {
58
+ if (typeof start !== 'string' || start === '') continue
59
+ let current
60
+ try {
61
+ current = path.resolve(realpathSync(start))
62
+ } catch {
63
+ continue
64
+ }
65
+ if (!existsSync(current) || readManifestSync(current) === null) {
66
+ // A file: continue from its directory.
67
+ current = path.dirname(current)
68
+ }
69
+ for (let step = 0; step < 8; step += 1) {
70
+ const manifest = readManifestSync(current)
71
+ if (manifest?.name === PACKAGE && typeof manifest.version === 'string') {
72
+ return { dir: current, version: manifest.version }
73
+ }
74
+ const parent = path.dirname(current)
75
+ if (parent === current) break
76
+ current = parent
77
+ }
78
+ }
79
+ return undefined
80
+ }
81
+
82
+ /** Where npm keeps its cache for this plugin. */
83
+ export function defaultCacheDir(env = process.env) {
84
+ const home = env.DSH_HOME ?? path.join(env.HOME ?? homedir(), '.dsh')
85
+ return path.join(home, '.dsh-control', 'npm-cache')
86
+ }
87
+
88
+ /** Trim a command's output to its tail. */
89
+ function tail(text) {
90
+ const value = String(text ?? '')
91
+ return value.length <= OUTPUT_LIMIT ? value : `…\n${value.slice(value.length - OUTPUT_LIMIT)}`
92
+ }
93
+
94
+ /**
95
+ * Run one executable without a shell, bounded by a timeout.
96
+ * @param {string} file - executable.
97
+ * @param {string[]} args - arguments.
98
+ * @param {{ timeoutMs?: number, env?: object }} options - execution bounds.
99
+ * @returns {Promise<{ code: number, stdout: string, stderr: string }>} result.
100
+ */
101
+ function run(file, args, options = {}) {
102
+ return new Promise((resolve, reject) => {
103
+ execFile(
104
+ file,
105
+ args,
106
+ {
107
+ timeout: options.timeoutMs ?? 120_000,
108
+ maxBuffer: 8 * 1024 * 1024,
109
+ env: options.env ?? process.env,
110
+ windowsHide: true,
111
+ },
112
+ (error, stdout, stderr) => {
113
+ if (error !== null && typeof error.code !== 'number') {
114
+ reject(new Error(error.message))
115
+ return
116
+ }
117
+ resolve({
118
+ code: error === null ? 0 : error.code,
119
+ stdout: tail(stdout),
120
+ stderr: tail(stderr),
121
+ })
122
+ },
123
+ )
124
+ })
125
+ }
126
+
127
+ export class NpmRunner {
128
+ /**
129
+ * @param {{ cacheDir?: string, registry?: string, env?: object }} config - paths and registry.
130
+ */
131
+ constructor(config = {}) {
132
+ this.cacheDir = config.cacheDir ?? defaultCacheDir()
133
+ this.registry = String(config.registry ?? '').trim()
134
+ this.env = {
135
+ ...(config.env ?? process.env),
136
+ npm_config_cache: this.cacheDir,
137
+ npm_config_update_notifier: 'false',
138
+ npm_config_fund: 'false',
139
+ npm_config_audit: 'false',
140
+ npm_config_loglevel: 'error',
141
+ COREPACK_ENABLE_DOWNLOAD_PROMPT: '0',
142
+ }
143
+ if (this.registry !== '') this.env.npm_config_registry = this.registry
144
+ this.globalRootCache = null
145
+ }
146
+
147
+ /** Arguments every npm call shares. */
148
+ baseArgs() {
149
+ const args = ['--cache', this.cacheDir, '--no-fund', '--no-audit', '--loglevel=error']
150
+ if (this.registry !== '') args.push('--registry', this.registry)
151
+ return args
152
+ }
153
+
154
+ /** Make sure the cache directory exists and belongs to us. */
155
+ async ready() {
156
+ await mkdir(this.cacheDir, { recursive: true })
157
+ }
158
+
159
+ /**
160
+ * The global installation prefix, asked once and remembered. `npm root -g`
161
+ * resolves through npm's own config, which is the only answer that matches
162
+ * where an install will actually land; the derived guess is the fallback.
163
+ * @returns {Promise<string>} absolute path of the global node_modules.
164
+ */
165
+ async globalRoot() {
166
+ if (this.globalRootCache !== null) return this.globalRootCache
167
+ await this.ready()
168
+ let root
169
+ try {
170
+ const result = await run('npm', ['root', '-g', ...this.baseArgs()], { timeoutMs: 30_000, env: this.env })
171
+ const line = result.stdout.trim().split('\n').filter((part) => part !== '').pop()
172
+ if (result.code === 0 && line !== undefined) root = line
173
+ } catch {
174
+ root = undefined
175
+ }
176
+ if (root === undefined) {
177
+ root = path.join(path.dirname(path.dirname(process.execPath)), 'lib', 'node_modules')
178
+ }
179
+ this.globalRootCache = root
180
+ return root
181
+ }
182
+
183
+ /**
184
+ * Version installed on disk (not necessarily the one running).
185
+ * @returns {Promise<string | null>} version, or null when the package is absent.
186
+ */
187
+ async installedVersion() {
188
+ const root = await this.globalRoot()
189
+ const manifest = await readManifest(path.join(root, PACKAGE))
190
+ return typeof manifest?.version === 'string' ? manifest.version : null
191
+ }
192
+
193
+ /**
194
+ * Every published version of the package.
195
+ * @returns {Promise<string[]>} versions.
196
+ */
197
+ async versions() {
198
+ await this.ready()
199
+ const result = await run('npm', ['view', PACKAGE, 'versions', '--json', '--silent', ...this.baseArgs()], {
200
+ timeoutMs: 90_000,
201
+ env: this.env,
202
+ })
203
+ if (result.code !== 0) {
204
+ throw new Error(
205
+ `npm view failed (exit ${result.code}): ${result.stderr.trim() || result.stdout.trim() || 'no output'}`,
206
+ )
207
+ }
208
+ const text = result.stdout.trim()
209
+ // A package with one published version answers with a bare string.
210
+ const parsed = JSON.parse(text.startsWith('[') ? text : JSON.stringify([text]))
211
+ if (!Array.isArray(parsed)) throw new Error('npm view returned an unexpected payload')
212
+ return parsed.filter((entry) => typeof entry === 'string')
213
+ }
214
+
215
+ /**
216
+ * Install one exact version globally.
217
+ * @param {string} version - version or range to install.
218
+ * @returns {Promise<{ code: number, stdout: string, stderr: string, installed: string | null }>} result.
219
+ */
220
+ async install(version) {
221
+ await this.ready()
222
+ const spec = `${PACKAGE}@${version}`
223
+ const result = await run('npm', ['install', '-g', spec, ...this.baseArgs()], {
224
+ timeoutMs: 600_000,
225
+ env: this.env,
226
+ })
227
+ // npm may rewrite the prefix, so the cached answer is dropped rather than trusted.
228
+ this.globalRootCache = null
229
+ const installed = result.code === 0 ? await this.installedVersion() : null
230
+ return { ...result, installed }
231
+ }
232
+
233
+ /**
234
+ * One metadata field of a published version. A failed lookup answers null:
235
+ * these reads only tighten the upgrade, they must not block one.
236
+ * @param {string} version - exact published version.
237
+ * @param {string} field - `npm view` field name.
238
+ * @returns {Promise<unknown>} parsed value, or null.
239
+ */
240
+ async metadata(version, field) {
241
+ await this.ready()
242
+ const result = await run('npm', ['view', `${PACKAGE}@${version}`, field, '--json', '--silent', ...this.baseArgs()], {
243
+ timeoutMs: 60_000,
244
+ env: this.env,
245
+ })
246
+ if (result.code !== 0) return null
247
+ const text = result.stdout.trim()
248
+ if (text === '') return null
249
+ try {
250
+ return JSON.parse(text)
251
+ } catch {
252
+ return null
253
+ }
254
+ }
255
+
256
+ /**
257
+ * The `engines` a release declares, so an upgrade can refuse a runtime it
258
+ * cannot boot instead of discovering that after the restart.
259
+ * @param {string} version - exact published version.
260
+ * @returns {Promise<object | null>} engines, or null when unknown.
261
+ */
262
+ async enginesOf(version) {
263
+ const value = await this.metadata(version, 'engines')
264
+ return typeof value === 'object' && value !== null ? value : null
265
+ }
266
+
267
+ /**
268
+ * The deprecation notice of a release, when there is one.
269
+ * @param {string} version - exact published version.
270
+ * @returns {Promise<string | null>} notice, or null.
271
+ */
272
+ async deprecationOf(version) {
273
+ const value = await this.metadata(version, 'deprecated')
274
+ return typeof value === 'string' && value.trim() !== '' ? value.trim() : null
275
+ }
276
+
277
+ /**
278
+ * Re-run the image's node-pty repair, when the image ships one. A version bump
279
+ * can replace node-pty with a build that has no prebuilt binary on this
280
+ * platform; the entrypoint script is what fixes that, and it is idempotent.
281
+ * @returns {Promise<string | null>} its output, or null when unavailable.
282
+ */
283
+ async repairNativeModules() {
284
+ const script = '/usr/local/bin/fix-node-pty.sh'
285
+ if (!existsSync(script)) return null
286
+ try {
287
+ const result = await run(script, [], { timeoutMs: 300_000, env: this.env })
288
+ return tail(`${result.stdout}\n${result.stderr}`).trim()
289
+ } catch (error) {
290
+ return `fix-node-pty.sh: ${error instanceof Error ? error.message : String(error)}`
291
+ }
292
+ }
293
+ }
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Restarting the Host from inside the Host.
3
+ *
4
+ * Three ways out, in order of how much they cost:
5
+ *
6
+ * - `command` — run a shell command that restarts whatever supervises us
7
+ * (`docker restart dsh` through the socket, a systemd unit, …). Only useful
8
+ * when the container has that access.
9
+ * - `execve` — replace the process image with a fresh `node <argv>`. Same PID,
10
+ * same container, same env: for a Docker install this is a real restart
11
+ * without waiting for the container lifecycle, and it is the default.
12
+ * - `exit` — die and let `restart: unless-stopped` bring the container back.
13
+ *
14
+ * All of them fire after the HTTP response has been written, so the panel sees
15
+ * its acknowledgement before the socket disappears.
16
+ * @module @local/dsh-control/lib/restart
17
+ */
18
+ import { spawn } from 'node:child_process'
19
+ import { appendFile, mkdir, writeFile } from 'node:fs/promises'
20
+ import path from 'node:path'
21
+
22
+ /** The modes the config accepts. */
23
+ export const MODES = ['auto', 'execve', 'exit', 'command']
24
+
25
+ /** Whether this Node can replace its own image. */
26
+ export const canExecve = typeof process.execve === 'function'
27
+
28
+ /**
29
+ * The argv a fresh copy of this process needs: the interpreter, the V8 flags
30
+ * the launcher passed (`--expose-internals` for live reload), then the script
31
+ * and its own arguments.
32
+ * @returns {string[]} argv for `process.execve`.
33
+ */
34
+ export function execveArgv() {
35
+ return [process.execPath, ...process.execArgv, ...process.argv.slice(1)]
36
+ }
37
+
38
+ /**
39
+ * Pick the strategy for one restart.
40
+ * @param {{ mode?: string, command?: string }} config - plugin config.
41
+ * @returns {{ strategy: 'command' | 'execve' | 'exit', reason: string, argv?: string[] }} the plan.
42
+ */
43
+ export function planRestart(config = {}) {
44
+ const mode = MODES.includes(String(config.mode ?? 'auto')) ? String(config.mode ?? 'auto') : 'auto'
45
+ const command = String(config.command ?? '').trim()
46
+ const argv = execveArgv()
47
+ if (mode === 'command') return { strategy: 'command', reason: 'restartCommand', argv }
48
+ if (mode === 'execve' && canExecve) return { strategy: 'execve', reason: 're-exec in place', argv }
49
+ if (mode === 'exit') return { strategy: 'exit', reason: 'exit and let the supervisor restart', argv }
50
+ if (command !== '') return { strategy: 'command', reason: 'restartCommand', argv }
51
+ if (canExecve) return { strategy: 'execve', reason: 're-exec in place', argv }
52
+ return { strategy: 'exit', reason: 'no execve on this Node; exit and let the supervisor restart', argv }
53
+ }
54
+
55
+ /**
56
+ * Append one line to the restart journal, so a boot that never comes back is
57
+ * still explainable from the volume.
58
+ * @param {string} file - journal path.
59
+ * @param {object} record - what is about to happen.
60
+ */
61
+ async function journal(file, record) {
62
+ try {
63
+ await mkdir(path.dirname(file), { recursive: true })
64
+ await appendFile(file, `${JSON.stringify({ at: new Date().toISOString(), ...record })}\n`, 'utf8')
65
+ } catch {
66
+ // The journal is a courtesy; never let it block a restart.
67
+ }
68
+ }
69
+
70
+ /**
71
+ * Perform the planned restart after `delayMs`.
72
+ * @param {{ strategy: string, argv?: string[], command?: string }} plan - from {@link planRestart}.
73
+ * @param {{ delayMs?: number, journalFile?: string, reason?: string }} options - timing and bookkeeping.
74
+ * @returns {{ scheduled: true, strategy: string, delayMs: number }} acknowledgement.
75
+ */
76
+ export function scheduleRestart(plan, options = {}) {
77
+ const delayMs = Number.isFinite(options.delayMs) ? Math.max(0, Number(options.delayMs)) : 800
78
+ const fire = () => {
79
+ if (plan.strategy === 'command') {
80
+ const child = spawn('sh', ['-c', plan.command], { detached: true, stdio: 'ignore' })
81
+ child.unref()
82
+ return
83
+ }
84
+ if (plan.strategy === 'execve') {
85
+ try {
86
+ process.execve(process.execPath, plan.argv, { ...process.env })
87
+ return
88
+ } catch {
89
+ // Fall through: an image swap that is refused still has to restart.
90
+ }
91
+ }
92
+ process.exit(0)
93
+ }
94
+ if (options.journalFile !== undefined) {
95
+ void journal(options.journalFile, {
96
+ strategy: plan.strategy,
97
+ reason: options.reason ?? '',
98
+ argv: plan.argv ?? null,
99
+ command: plan.command ?? null,
100
+ pid: process.pid,
101
+ })
102
+ }
103
+ setTimeout(fire, delayMs)
104
+ return { scheduled: true, strategy: plan.strategy, delayMs }
105
+ }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * 插件自更新的跨进程锁。
3
+ *
4
+ * 更新本身交给官方 Plugin Manager,回滚也由它负责;这个模块只剩一件事:
5
+ * 同一台机器可能有多个 Host 进程(不同端口/不同 profile 指向同一目录),
6
+ * 进程内的锁管不到它们,这里再加一个 `$DSH_HOME` 下的文件锁;陈旧或损坏的锁
7
+ * 保留并明确报错,不冒险自动接管。
8
+ * @module yukari-dsh-plugin/runtime/update-guard
9
+ */
10
+ import { randomUUID } from 'node:crypto'
11
+ import { linkSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
12
+ import path from 'node:path'
13
+
14
+ /** 进程是否还活着。 */
15
+ function alive(pid) {
16
+ if (!Number.isInteger(pid) || pid <= 0) return false
17
+ try {
18
+ process.kill(pid, 0)
19
+ return true
20
+ } catch (error) {
21
+ return error?.code === 'EPERM'
22
+ }
23
+ }
24
+
25
+ /** 锁文件里记录的持有者,读不到就当没有。 */
26
+ function holderOf(file) {
27
+ try {
28
+ const parsed = JSON.parse(readFileSync(file, 'utf8'))
29
+ return { pid: Number(parsed?.pid), at: typeof parsed?.at === 'string' ? parsed.at : '' }
30
+ } catch {
31
+ return null
32
+ }
33
+ }
34
+
35
+ /**
36
+ * 取一个跨进程的更新锁。
37
+ *
38
+ * 同一个目录被两个 Host 进程同时更新时,后一个会看到前一个的锁文件并直接
39
+ * 409。陈旧或损坏的锁也保留并报告位置:自动删除无法与新锁发布形成原子操作,
40
+ * 两个进程可能互相删除对方的新锁,因此这里选择失败关闭而不是自动接管。
41
+ * @param home - `$DSH_HOME`。
42
+ * @param options - `pid`、`now`,测试用。
43
+ * @returns 释放函数。
44
+ */
45
+ export function acquireUpdateLock(home, options = {}) {
46
+ const pid = options.pid ?? process.pid
47
+ const now = options.now ?? (() => new Date().toISOString())
48
+ const directory = path.join(home, '.update-lock')
49
+ const file = path.join(directory, 'owner.json')
50
+ mkdirSync(directory, { recursive: true, mode: 0o700 })
51
+ // 先在临时文件写完整内容,再用硬链接原子发布。直接创建 owner.json 会让
52
+ // 另一个进程在写入窗口读到空文件,并把仍在运行的持锁者误判为陈旧锁。
53
+ const temporary = path.join(directory, `.${process.pid}-${randomUUID()}.tmp`)
54
+ try {
55
+ writeFileSync(temporary, JSON.stringify({ pid, at: now() }), { flag: 'wx', mode: 0o600 })
56
+ linkSync(temporary, file)
57
+ return () => rmSync(file, { force: true })
58
+ } catch (error) {
59
+ if (error?.code !== 'EEXIST') throw error
60
+ const holder = holderOf(file)
61
+ const detail = holder !== null && alive(holder.pid)
62
+ ? `另一个 Harness 进程(pid ${holder.pid})正在更新插件,请等它完成`
63
+ : `更新锁已陈旧或损坏(${file})。为避免并发更新,未自动删除;确认没有更新正在执行后,删除该文件再试`
64
+ const busy = new Error(detail)
65
+ busy.status = 409
66
+ throw busy
67
+ } finally {
68
+ rmSync(temporary, { force: true })
69
+ }
70
+ }
@@ -0,0 +1,188 @@
1
+ /**
2
+ * Version arithmetic for the release channels.
3
+ *
4
+ * The container's entrypoint picks its upgrade target the same way: filter the
5
+ * published version list by channel, then take the largest semver. Dist-tags are
6
+ * deliberately ignored — "latest" has lagged behind the rc line, so tagging a
7
+ * single tag as the truth loses versions.
8
+ * @module @local/dsh-control/lib/versions
9
+ */
10
+
11
+ /** Channels the panel offers, most conservative first. */
12
+ export const CHANNELS = ['stable', 'rc', 'beta', 'alpha']
13
+
14
+ /**
15
+ * Whether text is a plain version that `npm install pkg@<text>` should accept.
16
+ *
17
+ * Ranges, tags, paths and dist-tag names are not versions: the panel and the
18
+ * agent tool send one exact target, and letting anything else through turns the
19
+ * install into "whatever npm resolves", which is how a plugin update installs a
20
+ * different package than the one it names.
21
+ * @param value - text from a form field or tool argument.
22
+ */
23
+ export function isVersionText(value) {
24
+ return /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(String(value ?? '').trim())
25
+ }
26
+
27
+ /**
28
+ * Split a version into its core numbers and prerelease identifiers.
29
+ * @param {string} version - semver text, build metadata ignored.
30
+ */
31
+ function split(version) {
32
+ const [core, ...rest] = String(version).trim().split('+')[0].split('-')
33
+ const numbers = core.split('.').map((part) => Number.parseInt(part, 10))
34
+ return { numbers, prerelease: rest.length === 0 ? undefined : rest.join('-') }
35
+ }
36
+
37
+ /**
38
+ * Compare two semver strings.
39
+ * @param {string} a - left version.
40
+ * @param {string} b - right version.
41
+ * @returns {number} negative, zero or positive.
42
+ */
43
+ export function compare(a, b) {
44
+ const left = split(a)
45
+ const right = split(b)
46
+ for (let index = 0; index < 3; index += 1) {
47
+ const x = Number.isFinite(left.numbers[index]) ? left.numbers[index] : 0
48
+ const y = Number.isFinite(right.numbers[index]) ? right.numbers[index] : 0
49
+ if (x !== y) return x - y
50
+ }
51
+ if (left.prerelease === undefined || right.prerelease === undefined) {
52
+ if (left.prerelease === right.prerelease) return 0
53
+ // A release outranks any prerelease of the same core version.
54
+ return left.prerelease === undefined ? 1 : -1
55
+ }
56
+ const x = left.prerelease.split('.')
57
+ const y = right.prerelease.split('.')
58
+ for (let index = 0; index < x.length || index < y.length; index += 1) {
59
+ if (x[index] === undefined) return -1
60
+ if (y[index] === undefined) return 1
61
+ const xNumeric = /^\d+$/.test(x[index])
62
+ const yNumeric = /^\d+$/.test(y[index])
63
+ if (xNumeric && yNumeric) {
64
+ const delta = Number(x[index]) - Number(y[index])
65
+ if (delta !== 0) return delta
66
+ } else if (xNumeric !== yNumeric) {
67
+ return xNumeric ? -1 : 1
68
+ } else if (x[index] !== y[index]) {
69
+ return x[index] < y[index] ? -1 : 1
70
+ }
71
+ }
72
+ return 0
73
+ }
74
+
75
+ /**
76
+ * Whether a version belongs to a channel.
77
+ *
78
+ * Releases belong to every channel; prereleases carry the tag that names the
79
+ * line they came from (`rc`, `beta`, `alpha`).
80
+ * @param {string} version - candidate version.
81
+ * @param {string} channel - channel name.
82
+ */
83
+ export function matchChannel(version, channel) {
84
+ const { prerelease } = split(version)
85
+ if (prerelease === undefined) return true
86
+ const tag = prerelease.split('.')[0].toLowerCase()
87
+ switch (String(channel).toLowerCase()) {
88
+ case 'stable':
89
+ return false
90
+ case 'rc':
91
+ return tag === 'rc'
92
+ case 'beta':
93
+ return tag === 'rc' || tag === 'beta'
94
+ case 'alpha':
95
+ case 'all':
96
+ return true
97
+ default:
98
+ return tag === 'rc'
99
+ }
100
+ }
101
+
102
+ /**
103
+ * 一条比较符是否被 `version` 满足。
104
+ * 只覆盖 npm 上真实见得到的写法:比较符、`^`、`~`、x-range;
105
+ * 解析不出来的写法一律当作满足——这是升级前的安全网,不是许可证解析器。
106
+ * @param {string} version - 待判断版本。
107
+ * @param {string} token - 一个比较符。
108
+ */
109
+ function satisfiesComparator(version, token) {
110
+ const match = /^(>=|<=|>|<|=|\^|~)?(.+)$/u.exec(token)
111
+ if (match === null) return true
112
+ const operator = match[1] ?? '='
113
+ const raw = match[2].trim()
114
+ const parts = raw.split('.')
115
+ if (parts.some((part) => /^[xX*]$/u.test(part))) {
116
+ // x-range:只比已经写出来的数字段。
117
+ const known = parts.map((part) => (/^\d+$/u.test(part) ? Number(part) : null)).filter((value) => value !== null)
118
+ if (known.length === 0) return true
119
+ const target = split(version).numbers
120
+ return known.every((value, index) => target[index] === value)
121
+ }
122
+ const bound = split(raw)
123
+ if (bound.numbers.some((value) => !Number.isFinite(value))) return true
124
+ const floor = `${bound.numbers[0]}.${bound.numbers[1] ?? 0}.${bound.numbers[2] ?? 0}`
125
+ const point = bound.prerelease === undefined ? floor : `${floor}-${bound.prerelease}`
126
+ const delta = compare(version, point)
127
+ switch (operator) {
128
+ case '>': return delta > 0
129
+ case '>=': return delta >= 0
130
+ case '<': return delta < 0
131
+ case '<=': return delta <= 0
132
+ case '^': {
133
+ const [major, minor] = bound.numbers
134
+ const ceiling = major > 0 ? `${major + 1}.0.0` : minor > 0 ? `0.${minor + 1}.0` : `0.0.${(bound.numbers[2] ?? 0) + 1}`
135
+ return delta >= 0 && compare(version, ceiling) < 0
136
+ }
137
+ case '~': {
138
+ const [major, minor] = bound.numbers
139
+ return delta >= 0 && compare(version, `${major}.${(minor ?? 0) + 1}.0`) < 0
140
+ }
141
+ default: return delta === 0
142
+ }
143
+ }
144
+
145
+ /**
146
+ * Whether a version satisfies a semver range such as `>=24.9.0` or `^20 || ^22`.
147
+ * @param {string} version - candidate runtime version.
148
+ * @param {string} range - declared range.
149
+ */
150
+ export function satisfiesRange(version, range) {
151
+ const text = String(range ?? '').trim()
152
+ if (text === '') return true
153
+ return text.split('||').some((alternative) => {
154
+ const tokens = alternative.trim().split(/\s+/u).filter((token) => token !== '')
155
+ return tokens.length > 0 && tokens.every((token) => satisfiesComparator(version, token))
156
+ })
157
+ }
158
+
159
+ /**
160
+ * Versions of one channel, newest first. Deprecated releases are still listed;
161
+ * the caller decides whether to skip them.
162
+ * @param {string[]} versions - every published version.
163
+ * @param {string} channel - channel name.
164
+ * @returns {string[]} candidates.
165
+ */
166
+ export function candidatesOf(versions, channel) {
167
+ if (!Array.isArray(versions)) return []
168
+ return versions.filter((version) => matchChannel(version, channel)).sort((left, right) => compare(right, left))
169
+ }
170
+
171
+ /**
172
+ * Largest version of one channel.
173
+ * @param {string[]} versions - every published version.
174
+ * @param {string} channel - channel name.
175
+ * @returns {string | undefined} the newest candidate, or undefined when the channel is empty.
176
+ */
177
+ export function pickLatest(versions, channel) {
178
+ return candidatesOf(versions, channel)[0]
179
+ }
180
+
181
+ /**
182
+ * Normalize whatever a user or a form field supplied.
183
+ * @param {unknown} channel - channel text.
184
+ */
185
+ export function normalizeChannel(channel) {
186
+ const value = String(channel ?? '').trim().toLowerCase()
187
+ return CHANNELS.includes(value) ? value : undefined
188
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Status",
4
+ "description": "Version check, update and restart"
5
+ }
6
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "状态",
4
+ "description": "dsh 版本检查、更新与重启"
5
+ }
6
+ }