cc-viewer 1.9.24 → 1.9.25
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli.js +14 -0
- package/dist/assets/App-BUIwNK3C.js +2 -0
- package/dist/assets/{App-BwRRqrP5.css → App-C5xq-7nS.css} +1 -1
- package/dist/assets/{ArchivePreview-dKWXN9Zp.js → ArchivePreview-BuFE-N7z.js} +1 -1
- package/dist/assets/{MdxEditorPanel-CT6w8hjl.js → MdxEditorPanel-BiKPuJGb.js} +1 -1
- package/dist/assets/{Mobile-noWViQpL.js → Mobile-D2UvqCIN.js} +1 -1
- package/dist/assets/{ProxyStatsModal-BeCRPqaC.js → ProxyStatsModal-CBdBgS9_.js} +1 -1
- package/dist/assets/{_baseUniq-BGBEhBne.js → _baseUniq-h4hafO2D.js} +1 -1
- package/dist/assets/{arc-4pbWOEmh.js → arc-CN5nAVn-.js} +1 -1
- package/dist/assets/{architectureDiagram-Q4EWVU46-BHZPDnby.js → architectureDiagram-Q4EWVU46-NTnIUsWP.js} +1 -1
- package/dist/assets/{blockDiagram-DXYQGD6D-DszLU7Pg.js → blockDiagram-DXYQGD6D-BPFMPOwn.js} +1 -1
- package/dist/assets/{c4Diagram-AHTNJAMY-DbDJNYxl.js → c4Diagram-AHTNJAMY-CAPyXRVj.js} +1 -1
- package/dist/assets/{channel-BpIsxDHj.js → channel-BULnUStk.js} +1 -1
- package/dist/assets/{chunk-4BX2VUAB-ChcBwBh2.js → chunk-4BX2VUAB-BeSOU8fB.js} +1 -1
- package/dist/assets/{chunk-4TB4RGXK-DzBEAck_.js → chunk-4TB4RGXK-BVCrVLA0.js} +1 -1
- package/dist/assets/{chunk-55IACEB6-9UDvmw07.js → chunk-55IACEB6-D0XHzdzo.js} +1 -1
- package/dist/assets/{chunk-EDXVE4YY-DHEU2DKg.js → chunk-EDXVE4YY-DizHN_m_.js} +1 -1
- package/dist/assets/{chunk-FMBD7UC4-sysT0Sy2.js → chunk-FMBD7UC4-3r0oXmep.js} +1 -1
- package/dist/assets/{chunk-OYMX7WX6-DLXt2vYo.js → chunk-OYMX7WX6-C701FNEA.js} +1 -1
- package/dist/assets/{chunk-QZHKN3VN-CDIkC7QK.js → chunk-QZHKN3VN-KAdMyJai.js} +1 -1
- package/dist/assets/{chunk-YZCP3GAM-D9b_INz7.js → chunk-YZCP3GAM-Cn2gaRZ3.js} +1 -1
- package/dist/assets/classDiagram-6PBFFD2Q-7MJg98xK.js +1 -0
- package/dist/assets/classDiagram-v2-HSJHXN6E-7MJg98xK.js +1 -0
- package/dist/assets/clone-Bddq99Xt.js +1 -0
- package/dist/assets/{cose-bilkent-S5V4N54A-DJQwV_Dp.js → cose-bilkent-S5V4N54A-URab8isi.js} +1 -1
- package/dist/assets/{dagre-KV5264BT-bl9Pq21t.js → dagre-KV5264BT-Cq24tJ6h.js} +1 -1
- package/dist/assets/{diagram-5BDNPKRD-BA8CJxzI.js → diagram-5BDNPKRD-D4KEpJ0T.js} +1 -1
- package/dist/assets/{diagram-G4DWMVQ6-DzSQULuz.js → diagram-G4DWMVQ6-DZLa6S7S.js} +1 -1
- package/dist/assets/{diagram-MMDJMWI5-DhfHWnT4.js → diagram-MMDJMWI5-BBhsOBKy.js} +1 -1
- package/dist/assets/{diagram-TYMM5635-BbAoFfGS.js → diagram-TYMM5635-ClWpYbD-.js} +1 -1
- package/dist/assets/{erDiagram-SMLLAGMA-CMjA2eBk.js → erDiagram-SMLLAGMA-5RXRgGvh.js} +1 -1
- package/dist/assets/{flowDiagram-DWJPFMVM-bOubqgJ6.js → flowDiagram-DWJPFMVM-DXiHDbOU.js} +1 -1
- package/dist/assets/{ganttDiagram-T4ZO3ILL-BUIu7WwI.js → ganttDiagram-T4ZO3ILL-Db5oVw9h.js} +1 -1
- package/dist/assets/{gitGraphDiagram-UUTBAWPF-B_vrztDU.js → gitGraphDiagram-UUTBAWPF-CCPK1X9H.js} +1 -1
- package/dist/assets/{graph-BR3YGx52.js → graph-DNxO4J9w.js} +1 -1
- package/dist/assets/{index-DtZAmvwJ.js → index-Bc_IaWe7.js} +1 -1
- package/dist/assets/{index-mvm_Pxcf.js → index-CXW8X8EW.js} +1 -1
- package/dist/assets/{index-DwMyfQJq.js → index-DDo6Z3Ov.js} +1 -1
- package/dist/assets/{index-ClTuiPoz.js → index-DR_FOzBM.js} +1 -1
- package/dist/assets/{index-BMpUfdYI.js → index-DaP3fzs1.js} +1 -1
- package/dist/assets/{index-B88yR2TU.js → index-Do02L044.js} +1 -1
- package/dist/assets/{index-BQx5MOpr.js → index-HLRCpKmY.js} +1 -1
- package/dist/assets/{index-Ca3a2tOc.js → index-ev1Hmm1O.js} +2 -2
- package/dist/assets/{infoDiagram-42DDH7IO-Co9Db2ir.js → infoDiagram-42DDH7IO-CzPZsFEc.js} +1 -1
- package/dist/assets/{ishikawaDiagram-UXIWVN3A-4z7EydCd.js → ishikawaDiagram-UXIWVN3A-eEVseuO_.js} +1 -1
- package/dist/assets/{journeyDiagram-VCZTEJTY-CtLfbhYE.js → journeyDiagram-VCZTEJTY-CmMKnKhj.js} +1 -1
- package/dist/assets/{jszip.min-DtbrAiWv.js → jszip.min-JnHXMwa-.js} +1 -1
- package/dist/assets/{kanban-definition-6JOO6SKY-9ZrhOvdX.js → kanban-definition-6JOO6SKY-CZMggR3M.js} +1 -1
- package/dist/assets/{layout-Ddo06NJO.js → layout-DVqRDfNO.js} +1 -1
- package/dist/assets/{linear-BZUsBSwS.js → linear-BHB3KNeC.js} +1 -1
- package/dist/assets/{mermaid.core-O-x0KuTp.js → mermaid.core-DOjmjAg3.js} +2 -2
- package/dist/assets/{min-PzJh19JL.js → min-DxJCEK6c.js} +1 -1
- package/dist/assets/{mindmap-definition-QFDTVHPH-C3MVo-7p.js → mindmap-definition-QFDTVHPH-B6W3RjCJ.js} +1 -1
- package/dist/assets/{pieDiagram-DEJITSTG-CMn9-kQc.js → pieDiagram-DEJITSTG-BRNQVuFX.js} +1 -1
- package/dist/assets/{quadrantDiagram-34T5L4WZ-9eyqTdkj.js → quadrantDiagram-34T5L4WZ-CUCnCkJJ.js} +1 -1
- package/dist/assets/{requirementDiagram-MS252O5E-BJbuDOpR.js → requirementDiagram-MS252O5E-Ds-5hLni.js} +1 -1
- package/dist/assets/{sankeyDiagram-XADWPNL6-CzQ1KxD3.js → sankeyDiagram-XADWPNL6-Cxi30RZc.js} +1 -1
- package/dist/assets/{seqResourceLoaders-DeqzMajS.js → seqResourceLoaders-B8ZIXCeg.js} +2 -2
- package/dist/assets/{sequenceDiagram-FGHM5R23-CfmSEAYp.js → sequenceDiagram-FGHM5R23-C6CukZv8.js} +1 -1
- package/dist/assets/{stateDiagram-FHFEXIEX-Brw2ZXQC.js → stateDiagram-FHFEXIEX-iPJCU2Ja.js} +1 -1
- package/dist/assets/{stateDiagram-v2-QKLJ7IA2-Dnyo23Rp.js → stateDiagram-v2-QKLJ7IA2-DMFhwtNH.js} +1 -1
- package/dist/assets/{timeline-definition-GMOUNBTQ-DNi7GnlG.js → timeline-definition-GMOUNBTQ-Dqd-tCUs.js} +1 -1
- package/dist/assets/{vendor-antd-DWLgSkPo.js → vendor-antd-D1L_UwKJ.js} +1 -1
- package/dist/assets/{vendor-codemirror-CKsm_iG4.js → vendor-codemirror-DOZOjrWx.js} +1 -1
- package/dist/assets/{vendor-mdxeditor-Dah6NK0y.js → vendor-mdxeditor-8ZUcYZ6G.js} +2 -2
- package/dist/assets/{vendor-qrcode-CDcb8weP.js → vendor-qrcode-Pw_LHfBZ.js} +1 -1
- package/dist/assets/{vendor-virtuoso-DKUobZpA.js → vendor-virtuoso-AhfR22q5.js} +1 -1
- package/dist/assets/{vennDiagram-DHZGUBPP-Cdkdx7gB.js → vennDiagram-DHZGUBPP-CrOJisSD.js} +1 -1
- package/dist/assets/{wardley-RL74JXVD-YKzsVN4U.js → wardley-RL74JXVD-By8Ltw9G.js} +1 -1
- package/dist/assets/{wardleyDiagram-NUSXRM2D-gBsb6aut.js → wardleyDiagram-NUSXRM2D-5SnzlvF9.js} +1 -1
- package/dist/assets/{xychartDiagram-5P7HB3ND-Bh63NWof.js → xychartDiagram-5P7HB3ND-CJ4uNjoK.js} +1 -1
- package/dist/index.html +4 -4
- package/package.json +1 -1
- package/server/lib/restart-helper.js +65 -0
- package/server/lib/restart.js +83 -0
- package/server/lib/update-instances.js +42 -0
- package/server/lib/update-job.js +260 -0
- package/server/lib/updater.js +37 -220
- package/server/pty-manager.js +1 -0
- package/server/routes/project-meta.js +11 -7
- package/server/routes/update.js +58 -0
- package/server/server.js +17 -5
- package/dist/assets/App-Cfmm41z0.js +0 -2
- package/dist/assets/classDiagram-6PBFFD2Q-4Lh0SB4X.js +0 -1
- package/dist/assets/classDiagram-v2-HSJHXN6E-4Lh0SB4X.js +0 -1
- package/dist/assets/clone-cWiXtXrO.js +0 -1
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { fileURLToPath } from 'node:url';
|
|
2
|
+
import { spawn } from 'node:child_process';
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
|
|
5
|
+
import { dirname } from 'node:path';
|
|
6
|
+
import { isPidAlive } from './pid-alive.js';
|
|
7
|
+
import { UPDATE_STATE_FILE, RESTART_CONFIG_FILE, RESTART_READY_FILE } from './update-job.js';
|
|
8
|
+
|
|
9
|
+
export const RESTART_HELPER_PATH = fileURLToPath(new URL('./restart-helper.js', import.meta.url));
|
|
10
|
+
|
|
11
|
+
export async function launchRestart({ pid = process.pid, args, cwd, version, cliPath, spawnImpl = spawn, timeoutMs = 5000 } = {}) {
|
|
12
|
+
if (!Number.isInteger(pid) || pid <= 0 || !Array.isArray(args) || typeof cwd !== 'string' || typeof version !== 'string' || !/^\d+\.\d+\.\d+$/.test(version) || typeof cliPath !== 'string') {
|
|
13
|
+
throw new Error('Invalid restart configuration');
|
|
14
|
+
}
|
|
15
|
+
const token = randomUUID();
|
|
16
|
+
await mkdir(dirname(RESTART_CONFIG_FILE), { recursive: true, mode: 0o700 });
|
|
17
|
+
await writeFile(RESTART_CONFIG_FILE, JSON.stringify({ pid, args, cwd, version, cliPath, token }), { mode: 0o600 });
|
|
18
|
+
await rm(RESTART_READY_FILE, { force: true });
|
|
19
|
+
let child;
|
|
20
|
+
try {
|
|
21
|
+
child = spawnImpl(process.execPath, [RESTART_HELPER_PATH, UPDATE_STATE_FILE, RESTART_CONFIG_FILE], {
|
|
22
|
+
detached: true, stdio: 'inherit', windowsHide: true, env: process.env,
|
|
23
|
+
});
|
|
24
|
+
} catch (err) {
|
|
25
|
+
await rm(RESTART_CONFIG_FILE, { force: true });
|
|
26
|
+
throw err;
|
|
27
|
+
}
|
|
28
|
+
return new Promise((resolve, reject) => {
|
|
29
|
+
let settled = false;
|
|
30
|
+
const finish = (err) => {
|
|
31
|
+
if (settled) return;
|
|
32
|
+
settled = true;
|
|
33
|
+
clearTimeout(timer);
|
|
34
|
+
clearInterval(poll);
|
|
35
|
+
child.off('error', onError);
|
|
36
|
+
child.off('exit', onExit);
|
|
37
|
+
if (err) {
|
|
38
|
+
try { child.kill('SIGKILL'); } catch { }
|
|
39
|
+
Promise.all([rm(RESTART_CONFIG_FILE, { force: true }), rm(RESTART_READY_FILE, { force: true })])
|
|
40
|
+
.catch(() => {})
|
|
41
|
+
.finally(() => reject(err));
|
|
42
|
+
} else {
|
|
43
|
+
child.unref();
|
|
44
|
+
resolve(child);
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
const onError = (err) => finish(err);
|
|
48
|
+
const onExit = (code) => { checkReady().then(ok => { if (!ok) finish(new Error(`Restart helper exited before it was ready (${code})`)); }); };
|
|
49
|
+
child.once('error', onError);
|
|
50
|
+
child.once('exit', onExit);
|
|
51
|
+
const checkReady = async () => {
|
|
52
|
+
try {
|
|
53
|
+
const ready = JSON.parse(await readFile(RESTART_READY_FILE, 'utf8'));
|
|
54
|
+
if (ready.token === token) { finish(); return true; }
|
|
55
|
+
} catch { /* Wait for the helper's bounded readiness signal. */ }
|
|
56
|
+
return false;
|
|
57
|
+
};
|
|
58
|
+
const poll = setInterval(checkReady, 50);
|
|
59
|
+
checkReady();
|
|
60
|
+
const timer = setTimeout(() => finish(new Error('Restart helper readiness timed out')), timeoutMs);
|
|
61
|
+
timer.unref?.();
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export async function waitForExit(pid, { alive = isPidAlive, sleep = (ms) => new Promise(r => setTimeout(r, ms)), timeoutMs = 15000 } = {}) {
|
|
66
|
+
const deadline = Date.now() + timeoutMs;
|
|
67
|
+
while (alive(pid)) {
|
|
68
|
+
if (Date.now() >= deadline) throw new Error('Timed out waiting for the old ccv process to stop');
|
|
69
|
+
await sleep(100);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export async function restartFromHelper(config, { spawnImpl = spawn, wait = waitForExit } = {}) {
|
|
74
|
+
await wait(config.pid);
|
|
75
|
+
const child = spawnImpl(process.execPath, [config.cliPath, ...config.args], { cwd: config.cwd, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: false, env: { ...process.env, CCV_NO_OPEN: '1' } });
|
|
76
|
+
child.stdout?.on('data', (chunk) => { try { process.stdout.write(chunk); } catch { } });
|
|
77
|
+
child.stderr?.on('data', (chunk) => { try { process.stderr.write(chunk); } catch { } });
|
|
78
|
+
console.error(`[CC Viewer] Restarted in the background with PID ${child.pid}. Stop it with: kill ${child.pid}`);
|
|
79
|
+
return new Promise((resolve, reject) => {
|
|
80
|
+
child.once('error', reject);
|
|
81
|
+
child.once('exit', (code, signal) => resolve(code ?? (signal ? 1 : 0)));
|
|
82
|
+
});
|
|
83
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { request } from 'node:http';
|
|
2
|
+
|
|
3
|
+
const DEFAULT_START_PORT = 7008;
|
|
4
|
+
const DEFAULT_MAX_PORT = 7049;
|
|
5
|
+
|
|
6
|
+
export function normalInstancePortRange(env = process.env) {
|
|
7
|
+
if (env.CCV_IM_PLATFORM || env.CCV_WORKSPACE_MODE) return [];
|
|
8
|
+
const start = Number(env.CCV_START_PORT) || DEFAULT_START_PORT;
|
|
9
|
+
const end = Number(env.CCV_MAX_PORT) || DEFAULT_MAX_PORT;
|
|
10
|
+
return start >= DEFAULT_START_PORT && end <= DEFAULT_MAX_PORT && start <= end ? [start, end] : [];
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function probeInstance(port, { requestImpl = request, timeoutMs = 300 } = {}) {
|
|
14
|
+
return new Promise((resolve) => {
|
|
15
|
+
let settled = false;
|
|
16
|
+
const done = (value) => { if (!settled) { settled = true; resolve(value); } };
|
|
17
|
+
let req;
|
|
18
|
+
try {
|
|
19
|
+
req = requestImpl({ hostname: '127.0.0.1', port, path: '/api/version-info', timeout: timeoutMs }, (res) => {
|
|
20
|
+
let body = '';
|
|
21
|
+
res.setEncoding('utf8');
|
|
22
|
+
res.on('data', chunk => { body += chunk; });
|
|
23
|
+
res.on('end', () => {
|
|
24
|
+
try {
|
|
25
|
+
const data = JSON.parse(body);
|
|
26
|
+
done(res.statusCode === 200 && /^\d+\.\d+\.\d+$/.test(data.version || '') && data.instanceKind === 'normal' && data.instancePort === port);
|
|
27
|
+
} catch { done(false); }
|
|
28
|
+
});
|
|
29
|
+
});
|
|
30
|
+
req.on('error', () => done(false));
|
|
31
|
+
req.on('timeout', () => { req.destroy(); done(false); });
|
|
32
|
+
req.end();
|
|
33
|
+
} catch { done(false); }
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export async function hasOtherNormalInstance({ portRange = normalInstancePortRange(), currentPort, probe = probeInstance } = {}) {
|
|
38
|
+
if (!Array.isArray(portRange) || portRange.length !== 2) return false;
|
|
39
|
+
const ports = Array.from({ length: portRange[1] - portRange[0] + 1 }, (_, i) => portRange[0] + i).filter(port => port !== currentPort);
|
|
40
|
+
const results = await Promise.all(ports.map(port => probe(port)));
|
|
41
|
+
return results.some(Boolean);
|
|
42
|
+
}
|
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { readFileSync, writeFileSync } from 'node:fs';import { mkdir, open, readFile, realpath, rm, stat, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { dirname, join, resolve } from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { spawn, execFile, spawnSync } from 'node:child_process';
|
|
6
|
+
import { once } from 'node:events';
|
|
7
|
+
import { finished } from 'node:stream/promises';
|
|
8
|
+
import { PACKAGE_ROOT } from '../_paths.js';
|
|
9
|
+
import { getClaudeConfigDir, buildNpmRootCommand, parseNpmRootOutput } from '../../findcc.js';
|
|
10
|
+
import { checkAndUpdate, detectHomebrewInstall, detectPnpmGlobalInstall, STABLE_VERSION_RE, isNewer, getCurrentVersion } from './updater.js';
|
|
11
|
+
import { hasOtherNormalInstance } from './update-instances.js';
|
|
12
|
+
import { reportSwallowed } from './error-report.js';
|
|
13
|
+
import { withFileLockAsync } from './async-file-lock.js';
|
|
14
|
+
import { isPidAlive } from './pid-alive.js';
|
|
15
|
+
|
|
16
|
+
const DOWNLOAD_TIMEOUT_MS = 10 * 60 * 1000;
|
|
17
|
+
const INSTALL_TIMEOUT_MS = 15 * 60 * 1000;
|
|
18
|
+
export const UPDATE_STATE_FILE = join(getClaudeConfigDir(), 'cc-viewer', 'update-state.json');
|
|
19
|
+
export const RESTART_CONFIG_FILE = join(getClaudeConfigDir(), 'cc-viewer', 'restart-config.json');
|
|
20
|
+
export const RESTART_READY_FILE = join(getClaudeConfigDir(), 'cc-viewer', 'restart-ready.json');
|
|
21
|
+
const CURRENT_CLI_PATH = fileURLToPath(new URL('../../cli.js', import.meta.url));
|
|
22
|
+
function updateError(message, code) { return Object.assign(new Error(message), { code }); }
|
|
23
|
+
export function readRestartConfig(file = RESTART_CONFIG_FILE) { return JSON.parse(readFileSync(file, 'utf8')); }
|
|
24
|
+
const npmRoot = () => new Promise((resolveRoot, reject) => {
|
|
25
|
+
const { cmd, args, windowsVerbatimArguments } = buildNpmRootCommand();
|
|
26
|
+
execFile(cmd, args, { encoding: 'utf8', timeout: 10000, windowsHide: true, windowsVerbatimArguments }, (err, stdout) => {
|
|
27
|
+
if (err) { reject(Object.assign(new Error('Unable to resolve the npm global directory'), { code: 'npm_unavailable' })); return; }
|
|
28
|
+
const root = parseNpmRootOutput(stdout);
|
|
29
|
+
if (!root) reject(Object.assign(new Error('Unable to resolve the npm global directory'), { code: 'npm_unavailable' }));
|
|
30
|
+
else resolveRoot(root);
|
|
31
|
+
});
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
function isStableRelease(release, version) {
|
|
35
|
+
try {
|
|
36
|
+
const url = typeof release?.dist?.tarball === 'string' ? new URL(release.dist.tarball) : null;
|
|
37
|
+
return release?.version === version && STABLE_VERSION_RE.test(version)
|
|
38
|
+
&& url?.protocol === 'https:' && url.hostname === 'registry.npmjs.org'
|
|
39
|
+
&& Boolean(release.dist.integrity || release.dist.shasum);
|
|
40
|
+
} catch { return false; }
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export async function resolveNpmInstallRoot({ rootImpl = npmRoot, packageRoot = PACKAGE_ROOT, detectImpl = () => detectHomebrewInstall() || detectPnpmGlobalInstall() } = {}) {
|
|
44
|
+
if (process.versions.electron) throw Object.assign(new Error('Electron uses its installer'), { code: 'unsupported_channel' });
|
|
45
|
+
if (detectImpl()) throw Object.assign(new Error('Use the package manager that installed cc-viewer'), { code: 'unsupported_channel' });
|
|
46
|
+
const [actualRoot, actualPackage] = await Promise.all([Promise.resolve(rootImpl()).then(root => realpath(root)), realpath(packageRoot)]);
|
|
47
|
+
if (actualPackage !== resolve(actualRoot, 'cc-viewer')) {
|
|
48
|
+
throw Object.assign(new Error('This is not a direct npm global installation'), { code: 'unsupported_layout' });
|
|
49
|
+
}
|
|
50
|
+
return actualRoot;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function buildNpmInstallCommand(tarballPath, { platform = process.platform, env = process.env, root } = {}) {
|
|
54
|
+
const quote = (s) => `"${String(s).replaceAll('"', '""')}"`;
|
|
55
|
+
const args = ['install', '-g', tarballPath, '--no-audit', '--no-fund', '--registry=https://registry.npmjs.org'];
|
|
56
|
+
if (root) args.push(`--prefix=${platform === 'win32' ? resolve(root, '..') : resolve(root, '..', '..')}`);
|
|
57
|
+
if (platform === 'win32') {
|
|
58
|
+
return { cmd: env.COMSPEC || 'cmd.exe', args: ['/d', '/s', '/c', `"${['npm', ...args].map(quote).join(' ')}"`], options: { windowsHide: true, windowsVerbatimArguments: true } };
|
|
59
|
+
}
|
|
60
|
+
return { cmd: 'npm', args, options: { windowsHide: true } };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function verifyDigest(buffer, dist) {
|
|
64
|
+
if (dist?.integrity) {
|
|
65
|
+
const [algorithm, expected] = dist.integrity.split('-');
|
|
66
|
+
if (['sha256', 'sha384', 'sha512'].includes(algorithm) && /^[A-Za-z0-9+/]+={0,2}$/.test(expected || '')) {
|
|
67
|
+
if (createHash(algorithm).update(buffer).digest('base64') === expected) return true;
|
|
68
|
+
}
|
|
69
|
+
return false;
|
|
70
|
+
}
|
|
71
|
+
if (/^[a-f0-9]{40}$/i.test(dist?.shasum || '')) return createHash('sha1').update(buffer).digest('hex') === dist.shasum.toLowerCase();
|
|
72
|
+
return false;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export async function downloadRelease({ release, directory, fetchImpl = fetch, onProgress = () => {}, timeoutMs = DOWNLOAD_TIMEOUT_MS, uuid = randomUUID, openImpl = open, finishedImpl = finished }) {
|
|
76
|
+
if (!isStableRelease(release, release?.version)) throw Object.assign(new Error('Invalid package download metadata'), { code: 'invalid_release' });
|
|
77
|
+
const url = release.dist.tarball;
|
|
78
|
+
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
79
|
+
const file = join(directory, `cc-viewer-${uuid()}.tgz`);
|
|
80
|
+
const controller = new AbortController();
|
|
81
|
+
const timeout = setTimeout(() => controller.abort(), timeoutMs);
|
|
82
|
+
let handle;
|
|
83
|
+
let output;
|
|
84
|
+
let outputError;
|
|
85
|
+
try {
|
|
86
|
+
handle = await openImpl(file, 'wx', 0o600);
|
|
87
|
+
output = handle.createWriteStream();
|
|
88
|
+
output.on('error', (err) => { outputError = err; });
|
|
89
|
+
const streamDone = finishedImpl(output).catch((err) => { outputError ??= err; });
|
|
90
|
+
const response = await fetchImpl(url, { signal: controller.signal, redirect: 'error' });
|
|
91
|
+
if (!response.ok || !response.body) throw new Error(`Download failed: HTTP ${response.status}`);
|
|
92
|
+
const total = Number(response.headers.get('content-length')) || null;
|
|
93
|
+
let downloaded = 0;
|
|
94
|
+
try {
|
|
95
|
+
for await (const chunk of response.body) {
|
|
96
|
+
if (outputError) throw outputError;
|
|
97
|
+
downloaded += chunk.length;
|
|
98
|
+
if (!output.write(chunk)) await Promise.race([once(output, 'drain'), once(output, 'close').then(() => { throw outputError || new Error('Package output closed'); })]);
|
|
99
|
+
onProgress({ downloaded, total });
|
|
100
|
+
}
|
|
101
|
+
output.end();
|
|
102
|
+
await streamDone;
|
|
103
|
+
} catch (err) {
|
|
104
|
+
output.destroy();
|
|
105
|
+
throw err;
|
|
106
|
+
}
|
|
107
|
+
if (!verifyDigest(await readFile(file), release.dist)) throw Object.assign(new Error('Package integrity check failed'), { code: 'integrity_mismatch' });
|
|
108
|
+
return file;
|
|
109
|
+
} catch (err) {
|
|
110
|
+
if (output) {
|
|
111
|
+
output.destroy();
|
|
112
|
+
await finishedImpl(output).catch(() => {});
|
|
113
|
+
} else await handle?.close().catch(() => {});
|
|
114
|
+
await rm(file, { force: true }).catch((rmErr) => reportSwallowed('update-job.download-cleanup', rmErr));
|
|
115
|
+
throw err;
|
|
116
|
+
} finally { clearTimeout(timeout); }
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export function runInstallProcess(command, { spawnImpl = spawn, timeoutMs = INSTALL_TIMEOUT_MS, onLog = () => {}, killTreeImpl } = {}) {
|
|
120
|
+
return new Promise((resolvePromise, reject) => {
|
|
121
|
+
let child;
|
|
122
|
+
try { child = spawnImpl(command.cmd, command.args, { ...command.options, detached: process.platform !== 'win32', stdio: ['ignore', 'pipe', 'pipe'] }); }
|
|
123
|
+
catch (err) { reject(err); return; }
|
|
124
|
+
let settled = false;
|
|
125
|
+
const finish = (fn, value) => { if (settled) return; settled = true; clearTimeout(timer); fn(value); };
|
|
126
|
+
let timedOut = false;
|
|
127
|
+
const timer = setTimeout(() => {
|
|
128
|
+
timedOut = true;
|
|
129
|
+
try {
|
|
130
|
+
if (killTreeImpl) killTreeImpl(child);
|
|
131
|
+
else if (process.platform === 'win32') spawnSync('taskkill', ['/pid', String(child.pid), '/T', '/F'], { timeout: 2000, windowsHide: true });
|
|
132
|
+
else process.kill(-child.pid, 'SIGKILL');
|
|
133
|
+
} catch (err) { reportSwallowed('update-job.kill', err); try { child.kill('SIGKILL'); } catch { } }
|
|
134
|
+
}, timeoutMs);
|
|
135
|
+
timer.unref?.();
|
|
136
|
+
child.on('error', (err) => finish(reject, err));
|
|
137
|
+
child.stdout?.on('data', (buf) => onLog(String(buf).slice(-4000)));
|
|
138
|
+
child.stderr?.on('data', (buf) => onLog(String(buf).slice(-4000)));
|
|
139
|
+
child.on('close', (code, signal) => {
|
|
140
|
+
if (timedOut) { finish(reject, Object.assign(new Error('Installation timed out'), { code: 'install_timeout' })); return; }
|
|
141
|
+
if (code === 0) finish(resolvePromise);
|
|
142
|
+
else finish(reject, Object.assign(new Error(`npm install failed (${code ?? signal})`), { code: 'install_failed' }));
|
|
143
|
+
});
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export async function installStagedUpdate(config, { installImpl = runInstallProcess, log = console.error, stateFile = UPDATE_STATE_FILE, ownerPid, resolveRootImpl = resolveNpmInstallRoot, cliPath = CURRENT_CLI_PATH, packageRoot = PACKAGE_ROOT } = {}) {
|
|
148
|
+
const file = config?.tarballPath;
|
|
149
|
+
if (!file || typeof config.root !== 'string' || !STABLE_VERSION_RE.test(config.version || '')) throw new Error('Invalid staged update');
|
|
150
|
+
const root = await realpath(config.root);
|
|
151
|
+
const filePath = await realpath(file);
|
|
152
|
+
if (dirname(filePath) !== await realpath(dirname(stateFile))) throw new Error('Staged package is outside the update directory');
|
|
153
|
+
if (ownerPid !== undefined && config.pid !== ownerPid && isPidAlive(config.pid)) throw updateError('Staged update belongs to a different live process', 'another_instance');
|
|
154
|
+
if (!isNewer(config.version, getCurrentVersion())) throw updateError('Staged update is not newer than the installed version', 'not_newer');
|
|
155
|
+
const command = buildNpmInstallCommand(filePath, { root });
|
|
156
|
+
let logTail = '';
|
|
157
|
+
await withFileLockAsync(join(dirname(stateFile), 'update-install.lock'), async () => {
|
|
158
|
+
try {
|
|
159
|
+
const activeRoot = await resolveRootImpl({ packageRoot });
|
|
160
|
+
if (activeRoot !== root) throw updateError('The active npm global directory has changed; stage the update again', 'unsupported_layout');
|
|
161
|
+
if (dirname(await realpath(cliPath)) !== resolve(root, 'cc-viewer')) throw updateError('The running CLI does not belong to the staged npm global directory', 'unsupported_layout');
|
|
162
|
+
if (ownerPid !== undefined && config.pid !== ownerPid && isPidAlive(config.pid)) throw updateError('Staged update belongs to a different live process', 'another_instance');
|
|
163
|
+
if (!isNewer(config.version, getCurrentVersion())) throw updateError('Staged update is not newer than the installed version', 'not_newer');
|
|
164
|
+
if (!verifyDigest(await readFile(filePath), config.dist)) throw new Error('Staged package integrity check failed');
|
|
165
|
+
await installImpl(command, { onLog: (text) => { logTail = (logTail + text).slice(-12000); } });
|
|
166
|
+
const installed = JSON.parse(await readFile(join(root, 'cc-viewer', 'package.json'), 'utf8'));
|
|
167
|
+
if (installed.version !== config.version || !(await stat(join(root, 'cc-viewer', 'cli.js'))).isFile()) throw new Error('Installed version could not be verified');
|
|
168
|
+
} catch (err) {
|
|
169
|
+
err.message = `${err.message}${logTail ? `\n${logTail}` : ''}`;
|
|
170
|
+
throw err;
|
|
171
|
+
}
|
|
172
|
+
}, { ensureDir: dirname(stateFile), deadline: INSTALL_TIMEOUT_MS + 30000 });
|
|
173
|
+
log(`[CC Viewer] Installed v${config.version}`);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
export class UpdateJob {
|
|
177
|
+
constructor(options = {}) {
|
|
178
|
+
this.options = options;
|
|
179
|
+
this.listeners = new Set();
|
|
180
|
+
this.lastBroadcastAt = 0;
|
|
181
|
+
this.state = { status: 'idle', currentVersion: null, version: null, downloaded: 0, total: null, error: null, updatedAt: Date.now() };
|
|
182
|
+
if (!options.disableRestore) {
|
|
183
|
+
try {
|
|
184
|
+
const pending = JSON.parse(readFileSync(UPDATE_STATE_FILE, 'utf8'));
|
|
185
|
+
if (pending.status === 'failed' && pending.error) this.state = { ...this.state, status: 'error', error: pending.error, version: pending.version || null };
|
|
186
|
+
else if (!pending.status && STABLE_VERSION_RE.test(pending.version || '') && pending.tarballPath && pending.root && isNewer(pending.version, getCurrentVersion())) {
|
|
187
|
+
this.state = { ...this.state, status: 'restart_required', version: pending.version };
|
|
188
|
+
if (pending.pid !== process.pid) {
|
|
189
|
+
try { writeFileSync(UPDATE_STATE_FILE, JSON.stringify({ ...pending, pid: process.pid }), { mode: 0o600 }); }
|
|
190
|
+
catch (err) { reportSwallowed('update-job.restore', err); }
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
} catch (err) {
|
|
194
|
+
if (err?.code !== 'ENOENT') reportSwallowed('update-job.restore', err);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
getState() { const { release, log, ...state } = this.state; return state; }
|
|
199
|
+
subscribe(listener) { this.listeners.add(listener); listener(this.getState()); return () => this.listeners.delete(listener); }
|
|
200
|
+
setState(patch) { this.state = { ...this.state, ...patch, updatedAt: Date.now() }; for (const listener of this.listeners) { try { listener(this.getState()); } catch (err) { reportSwallowed('update-job.listener', err); } } }
|
|
201
|
+
async check() {
|
|
202
|
+
if (['checking', 'downloading', 'installing', 'restarting', 'restart_required'].includes(this.state.status)) return this.getState();
|
|
203
|
+
this.setState({ status: 'checking', error: null, version: null, release: null });
|
|
204
|
+
try {
|
|
205
|
+
const result = await (this.options.checkImpl || checkAndUpdate)({ force: true, interactive: true, allowDisabled: true });
|
|
206
|
+
const release = result.release || null;
|
|
207
|
+
if (result.status === 'error') throw new Error(result.error);
|
|
208
|
+
if (result.status === 'disabled') throw Object.assign(new Error('Update checks are disabled by Claude settings'), { code: 'disabled' });
|
|
209
|
+
this.setState({ status: result.status, currentVersion: result.currentVersion, version: result.status === 'latest' ? null : result.remoteVersion, release, error: null, errorCode: null, checkedAt: Date.now() });
|
|
210
|
+
} catch (err) { this.setState({ status: 'error', error: err.message, errorCode: err.code || 'check_failed', version: null, release: null }); }
|
|
211
|
+
return this.getState();
|
|
212
|
+
}
|
|
213
|
+
async restart(handler) {
|
|
214
|
+
if (this.state.status === 'restarting') return this.getState();
|
|
215
|
+
if (this.state.status !== 'restart_required') throw new Error('No verified update is ready');
|
|
216
|
+
this.setState({ status: 'restarting' });
|
|
217
|
+
try { await handler(this.state.version); }
|
|
218
|
+
catch (err) { this.setState({ status: 'restart_required', error: err.message }); throw err; }
|
|
219
|
+
}
|
|
220
|
+
async start() {
|
|
221
|
+
if (['checking', 'downloading', 'installing', 'restarting', 'restart_required'].includes(this.state.status)) return this.getState();
|
|
222
|
+
if (!this.state.version || !this.state.release) {
|
|
223
|
+
const state = await this.check();
|
|
224
|
+
if (state.status !== 'available') return state;
|
|
225
|
+
}
|
|
226
|
+
let { version, release } = this.state;
|
|
227
|
+
if (!isStableRelease(release, version)) {
|
|
228
|
+
const state = await this.check();
|
|
229
|
+
if (state.status !== 'available') return state;
|
|
230
|
+
({ version, release } = this.state);
|
|
231
|
+
if (!isStableRelease(release, version)) {
|
|
232
|
+
this.setState({ status: 'error', error: 'Invalid package download metadata', errorCode: 'invalid_release' });
|
|
233
|
+
return this.getState();
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
this.setState({ status: 'downloading', error: null, downloaded: 0, total: null });
|
|
237
|
+
const directory = dirname(UPDATE_STATE_FILE);
|
|
238
|
+
let file;
|
|
239
|
+
try {
|
|
240
|
+
if (await (this.options.hasOtherInstanceImpl || hasOtherNormalInstance)({ currentPort: this.options.currentPort })) throw updateError('Exit other cc-viewer instances before updating', 'another_instance');
|
|
241
|
+
const root = await (this.options.resolveRootImpl || resolveNpmInstallRoot)();
|
|
242
|
+
const actualRoot = await realpath(root);
|
|
243
|
+
await withFileLockAsync(join(dirname(UPDATE_STATE_FILE), 'update-install.lock'), async () => {
|
|
244
|
+
file = await (this.options.downloadImpl || downloadRelease)({ release, directory, fetchImpl: this.options.fetchImpl, onProgress: (p) => {
|
|
245
|
+
const now = Date.now();
|
|
246
|
+
if (p.downloaded === p.total || now - this.lastBroadcastAt >= 100) {
|
|
247
|
+
this.lastBroadcastAt = now;
|
|
248
|
+
this.setState({ status: 'downloading', ...p });
|
|
249
|
+
}
|
|
250
|
+
} });
|
|
251
|
+
await writeFile(UPDATE_STATE_FILE, JSON.stringify({ version, tarballPath: file, root: actualRoot, pid: process.pid, dist: release.dist }), { mode: 0o600 });
|
|
252
|
+
this.setState({ status: 'restart_required', error: null, errorCode: null });
|
|
253
|
+
}, { ensureDir: directory, deadline: DOWNLOAD_TIMEOUT_MS + 30000 });
|
|
254
|
+
} catch (err) {
|
|
255
|
+
await rm(file, { force: true }).catch((rmErr) => reportSwallowed('update-job.cleanup', rmErr));
|
|
256
|
+
this.setState({ status: 'error', error: err.message, errorCode: err.code || 'update_failed' });
|
|
257
|
+
}
|
|
258
|
+
return this.getState();
|
|
259
|
+
}
|
|
260
|
+
}
|