toc-ocra 0.2.27 → 0.2.29

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.
@@ -1,8 +1,7 @@
1
1
  'use strict'
2
2
 
3
- // Shared installation protocol v1. Keep this file identical to
4
- // echo_web/electron/plugins/ocra-installation.cjs (the desktop never executes
5
- // lifecycle scripts from downloaded packages).
3
+ // The npm global package directory is the sole toc-ocra installation. Echo
4
+ // records its location here and reads it in place; it never keeps a copy.
6
5
  const fs = require('node:fs')
7
6
  const path = require('node:path')
8
7
  const os = require('node:os')
@@ -20,110 +19,95 @@ function dataDir() {
20
19
  if (process.platform === 'win32') return path.join(process.env.APPDATA || os.homedir(), PACKAGE_NAME)
21
20
  return path.join(process.env.XDG_STATE_HOME || path.join(os.homedir(), '.local', 'state'), PACKAGE_NAME)
22
21
  }
23
-
24
22
  function installationDir() { return path.join(dataDir(), 'installation') }
25
23
  function readJson(file) { return JSON.parse(fs.readFileSync(file, 'utf8')) }
26
- function atomicText(file, text, mode) {
24
+ function atomicText(file, text, mode = 0o600) {
27
25
  fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 })
28
26
  const temporary = `${file}.${process.pid}.tmp`
29
27
  fs.writeFileSync(temporary, text, { mode })
30
28
  fs.chmodSync(temporary, mode)
31
29
  fs.renameSync(temporary, file)
32
30
  }
33
- function atomicJson(file, value) {
34
- atomicText(file, JSON.stringify(value, null, 2), 0o600)
35
- }
31
+ function atomicJson(file, value) { atomicText(file, JSON.stringify(value, null, 2)) }
36
32
 
37
33
  function packageInfo(root) {
38
34
  const pkg = readJson(path.join(root, 'package.json'))
39
35
  if (pkg.name !== PACKAGE_NAME || pkg.tocPlugin?.id !== PLUGIN_ID || !VERSION.test(pkg.version)) throw new Error('设备代理安装包身份或版本无效')
40
36
  return pkg
41
37
  }
42
-
43
- function currentInstallation() {
44
- const file = path.join(installationDir(), 'current.json')
45
- if (!fs.existsSync(file)) return null
46
- const record = readJson(file)
47
- if (record.schema !== 1 || !VERSION.test(record.version)) throw new Error('设备代理共享安装记录无效')
48
- const root = path.join(installationDir(), 'versions', record.version)
49
- const pkg = packageInfo(root)
50
- if (pkg.version !== record.version || !fs.existsSync(path.join(root, 'dist', 'cli', 'cli.mjs'))) throw new Error('设备代理共享安装不完整,请重新安装')
51
- return { ...record, root, pkg }
52
- }
53
-
54
- function compareVersions(a, b) {
55
- const left = a.split('.').map(Number), right = b.split('.').map(Number)
56
- for (let i = 0; i < 3; i++) if (left[i] !== right[i]) return left[i] - right[i]
57
- return 0
58
- }
59
-
60
38
  function isGlobalPackage(root) {
61
39
  return path.basename(path.dirname(root)) === 'node_modules' &&
62
40
  (process.platform === 'win32' || path.basename(path.dirname(path.dirname(root))) === 'lib')
63
41
  }
64
-
65
- function globalAliases(sourceRoot) {
66
- const aliases = new Set()
67
- try { for (const root of readJson(path.join(installationDir(), 'aliases.json'))) aliases.add(root) } catch { /* first install */ }
68
- if (isGlobalPackage(sourceRoot)) aliases.add(sourceRoot)
69
- for (const directory of (process.env.PATH || '').split(path.delimiter)) {
70
- try {
71
- let root = path.dirname(fs.realpathSync(path.join(directory, 'toc-ocra')))
72
- while (path.dirname(root) !== root) {
73
- if (fs.existsSync(path.join(root, 'package.json'))) {
74
- if (packageInfo(root).name === PACKAGE_NAME && isGlobalPackage(root)) aliases.add(root)
75
- break
76
- }
77
- root = path.dirname(root)
42
+ function runtimeFor(root) {
43
+ const prefix = path.dirname(path.dirname(path.dirname(root)))
44
+ const candidates = process.platform === 'win32'
45
+ ? [path.join(prefix, 'node.exe'), path.join(prefix, 'bin', 'node.exe')]
46
+ : [path.join(prefix, 'bin', 'node')]
47
+ return candidates.find(file => fs.existsSync(file)) || process.execPath
48
+ }
49
+ function packageRootFromBin(directory) {
50
+ try {
51
+ let root = path.dirname(fs.realpathSync(path.join(directory, 'toc-ocra')))
52
+ while (path.dirname(root) !== root) {
53
+ if (fs.existsSync(path.join(root, 'package.json'))) {
54
+ const pkg = packageInfo(root)
55
+ return isGlobalPackage(root) ? { root, version: pkg.version, runtime: runtimeFor(root) } : null
78
56
  }
79
- } catch { /* not an npm toc-ocra command */ }
57
+ root = path.dirname(root)
58
+ }
59
+ } catch { /* not a toc-ocra executable */ }
60
+ return null
61
+ }
62
+ function candidates(sourceRoot) {
63
+ const found = new Map()
64
+ const add = value => {
65
+ try {
66
+ const root = path.resolve(value)
67
+ const pkg = packageInfo(root)
68
+ if (isGlobalPackage(root)) found.set(root, { root, version: pkg.version, runtime: runtimeFor(root) })
69
+ } catch { /* stale alias or unrelated package */ }
70
+ }
71
+ try {
72
+ const old = readJson(path.join(installationDir(), 'aliases.json'))
73
+ if (Array.isArray(old)) old.forEach(add)
74
+ } catch { /* first install */ }
75
+ for (const directory of (process.env.PATH || '').split(path.delimiter)) {
76
+ const item = packageRootFromBin(directory)
77
+ if (item) found.set(item.root, item)
80
78
  }
81
- return [...aliases].filter(root => {
82
- try { return typeof root === 'string' && path.isAbsolute(root) && isGlobalPackage(root) && packageInfo(root).name === PACKAGE_NAME }
83
- catch { return false }
79
+ add(sourceRoot)
80
+ return [...found.values()].sort((a, b) => {
81
+ const anvm = a.root.includes(`${path.sep}.nvm${path.sep}`) ? 0 : 1
82
+ const bnvm = b.root.includes(`${path.sep}.nvm${path.sep}`) ? 0 : 1
83
+ return anvm - bnvm || a.root.localeCompare(b.root)
84
84
  })
85
85
  }
86
-
87
- function syncLaunchers(current, sourceRoot) {
88
- const launcherDir = path.join(installationDir(), 'bin')
89
- fs.mkdirSync(launcherDir, { recursive: true, mode: 0o700 })
90
- const launcher = path.join(launcherDir, 'launch.cjs')
91
- // This stable launcher resolves the current package on every invocation.
92
- const body = `const fs=require('node:fs'),path=require('node:path'),{pathToFileURL}=require('node:url');\nconst base=${JSON.stringify(installationDir())};const r=JSON.parse(fs.readFileSync(path.join(base,'current.json'),'utf8'));if(!/^\\d+\\.\\d+\\.\\d+$/.test(r.version))throw Error('共享安装版本无效');import(pathToFileURL(path.join(base,'versions',r.version,'dist','cli','cli.mjs')).href).catch(e=>{console.error(e.message);process.exitCode=1});\n`
93
- atomicText(launcher, body, 0o600)
94
- const aliases = globalAliases(sourceRoot)
95
- for (const root of aliases) {
96
- const pkg = packageInfo(root)
97
- const relative = typeof pkg.bin === 'string' ? pkg.bin : pkg.bin?.[PACKAGE_NAME]
98
- if (typeof relative !== 'string') continue
99
- const entry = path.resolve(root, relative)
100
- if (!entry.startsWith(root + path.sep)) throw new Error('npm 命令入口超出了设备代理安装目录')
101
- // Preserve npm's bin symlink. Repoint its owned JS entry to the shared
102
- // launcher, so later npm installs can replace it without EEXIST errors.
103
- const entries = new Set([entry, path.join(root, 'dist', 'src', 'index.js')])
104
- for (const file of entries) {
105
- fs.mkdirSync(path.dirname(file), { recursive: true })
106
- atomicText(file, `#!/usr/bin/env node\nimport ${JSON.stringify(require('node:url').pathToFileURL(launcher).href)};\n`, 0o755)
107
- }
108
- for (const relative of ['dist/service/agent.mjs', 'scripts/service.mjs']) {
109
- const file = path.join(root, relative)
110
- if (!fs.existsSync(file)) continue
111
- const wrapper = `#!/usr/bin/env node\nimport fs from 'node:fs';import path from 'node:path';import{pathToFileURL}from'node:url';const base=${JSON.stringify(installationDir())};const r=JSON.parse(fs.readFileSync(path.join(base,'current.json'),'utf8'));if(!/^\\d+\\.\\d+\\.\\d+$/.test(r.version))throw Error('共享安装版本无效');await import(pathToFileURL(path.join(base,'versions',r.version,${JSON.stringify(relative)})).href);\n`
112
- atomicText(file, wrapper, 0o755)
86
+ function currentInstallation() {
87
+ const file = path.join(installationDir(), 'current.json')
88
+ if (fs.existsSync(file)) {
89
+ const record = readJson(file)
90
+ if (record.schema === 2 && typeof record.root === 'string' && path.isAbsolute(record.root)) {
91
+ const root = path.resolve(record.root)
92
+ const pkg = packageInfo(root)
93
+ if (!isGlobalPackage(root) || !fs.existsSync(path.join(root, 'dist', 'cli', 'cli.mjs')))
94
+ throw new Error('设备代理唯一安装位置无效,请重新安装 toc-ocra')
95
+ const current = { ...record, version: pkg.version, runtime: record.runtime && fs.existsSync(record.runtime) ? record.runtime : runtimeFor(root), root, pkg }
96
+ if (record.version !== pkg.version || record.runtime !== current.runtime) {
97
+ atomicJson(file, { schema: 2, root, runtime: current.runtime, version: pkg.version, updatedAt: new Date().toISOString() })
98
+ }
99
+ return current
113
100
  }
114
- atomicJson(path.join(root, 'package.json'), { ...pkg, version: current.version })
115
- }
116
- atomicJson(path.join(installationDir(), 'aliases.json'), aliases)
117
- // A desktop-only installation also has a terminal command, using the same
118
- // Node/Electron runtime; existing npm commands are synchronized above.
119
- if (process.platform !== 'win32') {
120
- const bin = path.join(os.homedir(), '.local', 'bin', PACKAGE_NAME)
121
- fs.mkdirSync(path.dirname(bin), { recursive: true })
122
- const quote = value => `'${value.replaceAll("'", "'\\''")}'`
123
- atomicText(bin, `#!/bin/sh\n# TOC_OCRA_SHARED_LAUNCHER\nELECTRON_RUN_AS_NODE=1 exec ${quote(current.runtime)} ${quote(launcher)} "$@"\n`, 0o755)
124
- } else {
125
- atomicText(path.join(launcherDir, 'toc-ocra.cmd'), `@echo off\r\nset "ELECTRON_RUN_AS_NODE=1"\r\n"${current.runtime}" "${launcher}" %*\r\n`, 0o700)
126
101
  }
102
+ const root = candidates()[0]
103
+ if (!root) return null
104
+ const pkg = packageInfo(root.root)
105
+ return { schema: 2, root: root.root, runtime: root.runtime, version: pkg.version, updatedAt: new Date().toISOString(), pkg }
106
+ }
107
+ function compareVersions(a, b) {
108
+ const left = a.split('.').map(Number), right = b.split('.').map(Number)
109
+ for (let i = 0; i < 3; i++) if (left[i] !== right[i]) return left[i] - right[i]
110
+ return 0
127
111
  }
128
112
 
129
113
  async function endpoint() {
@@ -135,7 +119,6 @@ async function endpoint() {
135
119
  if (host.includes(':')) host = `[${host}]`
136
120
  return `http://${host}:${process.env.TOC_OCRA_HEALTH_PORT || config.healthPort || 17339}`
137
121
  }
138
-
139
122
  async function runningAgent() {
140
123
  const base = await endpoint()
141
124
  const info = await fetch(`${base}/control/info`, { signal: AbortSignal.timeout(2_000) }).then(r => r.ok ? r.json() : null).catch(() => null)
@@ -144,13 +127,11 @@ async function runningAgent() {
144
127
  if (!Number.isInteger(state.activeSessions)) throw new Error('无法确认设备代理的活动任务,请稍后重试')
145
128
  return { base, info, state }
146
129
  }
147
-
148
130
  async function ensureIdle() {
149
131
  const running = await runningAgent()
150
132
  if (running?.state.activeSessions > 0) throw new Error(`本机还有 ${running.state.activeSessions} 个任务运行,请在任务结束后升级`)
151
133
  return running
152
134
  }
153
-
154
135
  function execute(runtime, args) {
155
136
  return new Promise((resolve, reject) => {
156
137
  const child = spawn(runtime, args, { env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' }, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true })
@@ -161,7 +142,6 @@ function execute(runtime, args) {
161
142
  child.once('exit', code => code === 0 ? resolve() : reject(new Error(output.trim() || `更新设备代理服务失败(${code})`)))
162
143
  })
163
144
  }
164
-
165
145
  function instanceRunning() {
166
146
  return new Promise((resolve, reject) => {
167
147
  const socket = net.createConnection({ host: '127.0.0.1', port: 17338 })
@@ -170,20 +150,15 @@ function instanceRunning() {
170
150
  socket.once('error', error => { socket.destroy(); if (error.code === 'ECONNREFUSED') resolve(false); else reject(error) })
171
151
  })
172
152
  }
173
-
174
153
  async function restart(current, running) {
175
154
  if (running) {
176
155
  const tokenFile = path.join(process.env.TOC_OCRA_DATA_DIR || dataDir(), 'control-token')
177
156
  if (fs.existsSync(tokenFile)) {
178
157
  const token = fs.readFileSync(tokenFile, 'utf8').trim()
179
158
  const response = await fetch(`${running.base}/control/shutdown`, { method: 'POST', headers: { authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(3_000) }).catch(() => null)
180
- // Older agents are stopped by the existing OS service installer below.
181
159
  if (response && !response.ok && response.status !== 404) throw new Error('设备代理拒绝升级重启,请确认本机控制凭据有效')
182
160
  if (response?.ok) {
183
161
  await response.arrayBuffer()
184
- // Do not bootout a job while its first SIGTERM is still draining.
185
- // Legacy once-only signal handlers would terminate on the second
186
- // signal and leave a live server lease behind for 90 seconds.
187
162
  for (let attempt = 0; attempt < 120 && await instanceRunning(); attempt++) await delay(500)
188
163
  if (await instanceRunning()) throw new Error('旧设备代理尚未完整退出,已停止升级重启')
189
164
  }
@@ -195,57 +170,70 @@ async function restart(current, running) {
195
170
  if (next?.info.version === current.version) return
196
171
  await delay(500)
197
172
  }
198
- throw new Error('共享安装已更新,但未确认新版设备代理启动,升级未完成')
173
+ throw new Error('设备代理已更新,但未确认新版服务启动')
199
174
  }
200
175
 
176
+ function copyPackage(source, target) {
177
+ fs.mkdirSync(target, { recursive: true, mode: 0o700 })
178
+ for (const name of ['package.json', 'dist/cli', 'dist/service', 'dist/plugin', 'dist/src', 'assets', 'locales', 'scripts', 'README.md', 'LICENSE']) {
179
+ const from = path.join(source, name)
180
+ if (fs.existsSync(from)) fs.cpSync(from, path.join(target, name), { recursive: true, filter: file => !fs.lstatSync(file).isSymbolicLink() })
181
+ }
182
+ packageInfo(target)
183
+ if (!fs.existsSync(path.join(target, 'dist', 'cli', 'cli.mjs'))) throw new Error('toc-ocra 命令入口缺失')
184
+ }
201
185
  async function installShared(sourceRoot, options = {}) {
202
186
  const source = fs.realpathSync(sourceRoot)
203
187
  const pkg = packageInfo(source)
204
- if (!fs.existsSync(path.join(source, 'dist', 'cli', 'cli.mjs'))) throw new Error('此版本尚不支持统一安装,请发布新版 toc-ocra 后再升级')
188
+ if (!fs.existsSync(path.join(source, 'dist', 'cli', 'cli.mjs'))) throw new Error('此版本尚不支持单目录安装,请先构建 toc-ocra')
205
189
  const lock = net.createServer(socket => socket.end())
206
190
  await new Promise((resolve, reject) => {
207
191
  lock.once('error', () => reject(new Error('设备代理正在进行另一项升级,请稍后重试')))
208
192
  lock.listen({ host: '127.0.0.1', port: UPDATE_LOCK_PORT, exclusive: true }, resolve)
209
193
  })
210
- let previous
211
- let changed = false
212
- let wasRunning
194
+ let current, wasRunning, swapped = false
195
+ let staging, backup
213
196
  try {
214
- previous = currentInstallation()
215
- if (previous && compareVersions(pkg.version, previous.version) < 0) throw new Error(`本机已有较新版本 ${previous.version},已阻止降级到 ${pkg.version}`)
197
+ current = currentInstallation() || candidates(source)[0]
198
+ if (!current) throw new Error('找不到现有 npm 全局安装。请先通过 nvm 安装 toc-ocra,再从 Echo 或终端升级')
199
+ if (compareVersions(pkg.version, current.version) < 0) throw new Error(`本机已有较新版本 ${current.version},已阻止降级到 ${pkg.version}`)
200
+ // npm releases are immutable by version. In particular, do not replace a
201
+ // locally repaired install with stale contents from the same registry tag.
202
+ if (pkg.version === current.version) return current
216
203
  wasRunning = await ensureIdle()
217
204
  if (options.beforeInstall) await options.beforeInstall()
218
- const versions = path.join(installationDir(), 'versions')
219
- const target = path.join(versions, pkg.version)
220
- fs.mkdirSync(versions, { recursive: true, mode: 0o700 })
221
- if (!fs.existsSync(target)) {
222
- const staging = fs.mkdtempSync(path.join(versions, '.install-'))
223
- try {
224
- for (const name of ['package.json', 'dist/cli', 'dist/service', 'dist/plugin', 'dist/src', 'assets', 'locales', 'scripts', 'README.md', 'LICENSE']) {
225
- const from = path.join(source, name)
226
- if (fs.existsSync(from)) fs.cpSync(from, path.join(staging, name), { recursive: true, filter: file => !fs.lstatSync(file).isSymbolicLink() })
227
- }
228
- packageInfo(staging)
229
- fs.renameSync(staging, target)
230
- } finally { fs.rmSync(staging, { recursive: true, force: true }) }
231
- }
232
- const record = { schema: 1, version: pkg.version, runtime: previous?.runtime && fs.existsSync(previous.runtime) ? previous.runtime : options.runtime || process.execPath, updatedAt: new Date().toISOString() }
233
- atomicJson(path.join(installationDir(), 'current.json'), record)
234
- changed = true
235
- const current = currentInstallation()
236
- syncLaunchers(current, source)
237
- if (wasRunning || options.startService) await restart(current, wasRunning)
238
- return current
205
+ const root = current.root
206
+ const parent = path.dirname(root)
207
+ staging = fs.mkdtempSync(path.join(parent, '.toc-ocra-install-'))
208
+ fs.rmSync(staging, { recursive: true, force: true })
209
+ copyPackage(source, staging)
210
+ const oldVersion = packageInfo(root).version
211
+ backup = path.join(parent, `.toc-ocra-backup-${process.pid}`)
212
+ if (fs.existsSync(backup)) fs.rmSync(backup, { recursive: true, force: true })
213
+ fs.renameSync(root, backup)
214
+ try { fs.renameSync(staging, root); swapped = true }
215
+ catch (error) { fs.renameSync(backup, root); throw error }
216
+ const nextPkg = packageInfo(root)
217
+ const next = { schema: 2, root, runtime: current.runtime || runtimeFor(root), version: nextPkg.version, updatedAt: new Date().toISOString() }
218
+ atomicJson(path.join(installationDir(), 'current.json'), next)
219
+ if (wasRunning || options.startService) await restart({ ...next, pkg: nextPkg }, wasRunning)
220
+ fs.rmSync(backup, { recursive: true, force: true })
221
+ return { ...next, pkg: nextPkg }
239
222
  } catch (error) {
240
- if (changed) {
241
- if (previous) {
242
- atomicJson(path.join(installationDir(), 'current.json'), previous)
243
- syncLaunchers(previous, source)
244
- if (wasRunning) await restart(previous, await runningAgent()).catch(() => undefined)
245
- } else fs.rmSync(path.join(installationDir(), 'current.json'), { force: true })
223
+ if (swapped && backup && fs.existsSync(backup)) {
224
+ const root = current.root
225
+ fs.rmSync(root, { recursive: true, force: true })
226
+ fs.renameSync(backup, root)
227
+ const pkg = packageInfo(root)
228
+ const restored = { schema: 2, root, runtime: current.runtime || runtimeFor(root), version: pkg.version, updatedAt: new Date().toISOString() }
229
+ atomicJson(path.join(installationDir(), 'current.json'), restored)
230
+ if (wasRunning) await restart({ ...restored, pkg }, await runningAgent()).catch(() => undefined)
246
231
  }
247
232
  throw error
248
- } finally { await new Promise(resolve => lock.close(resolve)) }
233
+ } finally {
234
+ if (staging) fs.rmSync(staging, { recursive: true, force: true })
235
+ await new Promise(resolve => lock.close(resolve))
236
+ }
249
237
  }
250
238
 
251
239
  module.exports = { PLUGIN_ID, PACKAGE_NAME, installationDir, currentInstallation, compareVersions, isGlobalPackage, installShared, ensureIdle }
@@ -1,9 +1,22 @@
1
1
  'use strict'
2
2
  const path = require('node:path')
3
+ const fs = require('node:fs')
3
4
  const { installShared } = require('./installation.cjs')
4
5
 
5
6
  if (process.env.npm_config_global === 'true') {
6
- installShared(path.resolve(__dirname, '..')).then(current => {
7
- console.log(`toc-ocra ${current.version} 已安装到本机共享位置,终端与 Echo 插件共用此版本`)
7
+ const source = path.resolve(__dirname, '..')
8
+ installShared(source).then(current => {
9
+ // npm may have staged this package under a different global prefix. Fold
10
+ // it into the one registered installation, then remove only this package
11
+ // copy and its npm-owned command symlink.
12
+ if (path.resolve(source) !== path.resolve(current.root)) {
13
+ const prefix = path.dirname(path.dirname(path.dirname(source)))
14
+ const bin = path.join(prefix, 'bin', process.platform === 'win32' ? 'toc-ocra.cmd' : 'toc-ocra')
15
+ try {
16
+ if (fs.lstatSync(bin).isSymbolicLink() && path.resolve(path.dirname(bin), fs.readlinkSync(bin)) === path.resolve(source, 'dist', 'cli', 'cli.mjs')) fs.unlinkSync(bin)
17
+ } catch { /* absent or not owned by this package */ }
18
+ fs.rmSync(source, { recursive: true, force: true })
19
+ }
20
+ console.log(`toc-ocra ${current.version} 已更新到唯一安装位置 ${current.root}`)
8
21
  }).catch(error => { console.error(error.message); process.exitCode = 1 })
9
22
  }