claude-rpc 1.7.1 → 1.7.3
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/package.json +1 -1
- package/src/daemon.js +23 -19
- package/src/doctor.js +5 -2
- package/src/install.js +49 -22
- package/src/presence.js +25 -0
- package/src/scanner.js +28 -8
- package/src/shell-path.js +46 -0
- package/src/version.js +1 -1
package/package.json
CHANGED
package/src/daemon.js
CHANGED
|
@@ -4,7 +4,7 @@ import { existsSync, unlinkSync, watch, appendFileSync, mkdirSync, statSync, ren
|
|
|
4
4
|
import { basename, dirname, join } from 'node:path';
|
|
5
5
|
import { Client, isBridgeUser } from './discord-ipc.js';
|
|
6
6
|
import { readState, sweepStaleStateTmp, listSessionStates, sweepStaleSessionStates } from './state.js';
|
|
7
|
-
import { makeRotationCursor, pickFrames, selectFrame, resolveLargeImageKey, shouldShowGithubButton, pickActiveSession, throttleDecision } from './presence.js';
|
|
7
|
+
import { makeRotationCursor, pickFrames, selectFrame, resolveLargeImageKey, shouldShowGithubButton, pickActiveSession, throttleDecision, reconnectPlan, RECONNECT_BASE_MS } from './presence.js';
|
|
8
8
|
import { buildVars, fillTemplate, framePasses, applyIdle, applyShipped, applyTrigger, humanProject } from './format.js';
|
|
9
9
|
import { scan, readAggregate, findLiveSessions, readSessionTokens, readSessionModel } from './scanner.js';
|
|
10
10
|
import { detectClaudeProcess } from './claude-proc.js';
|
|
@@ -139,14 +139,15 @@ let recentSends = [];
|
|
|
139
139
|
// Tracked separately from the render hash so we fire once per transition.
|
|
140
140
|
let lastNotifiedStatus = null;
|
|
141
141
|
let reconnectTimer = null;
|
|
142
|
-
//
|
|
143
|
-
//
|
|
144
|
-
//
|
|
145
|
-
// running both packaged and dev simultaneously) from synchronizing
|
|
146
|
-
// reconnect storms against Discord's IPC socket.
|
|
147
|
-
const RECONNECT_BASE_MS = 5_000;
|
|
148
|
-
const RECONNECT_CAP_MS = 300_000;
|
|
142
|
+
// Current Discord reconnect step — pacing lives in presence.reconnectPlan
|
|
143
|
+
// (fast flat poll while Discord isn't running, exponential backoff to 5min
|
|
144
|
+
// when a live client keeps failing). Reset on a successful connect.
|
|
149
145
|
let reconnectDelayMs = RECONNECT_BASE_MS;
|
|
146
|
+
// The "Discord isn't running" poll is every ~15s; logging each miss would
|
|
147
|
+
// write ~5,700 lines a day. One line per this interval keeps the log quiet
|
|
148
|
+
// while still landing inside the tail doctor reads for IPC state.
|
|
149
|
+
const ABSENT_LOG_EVERY_MS = 5 * 60_000;
|
|
150
|
+
let lastAbsentLogAt = 0;
|
|
150
151
|
// Rotation cursor (index + lastAt + status). selectFrame in presence.js resets
|
|
151
152
|
// it on a status transition — otherwise the cursor carries over from idle's
|
|
152
153
|
// 12-frame rotation into a single-frame working state and back, producing a
|
|
@@ -622,6 +623,7 @@ async function connect() {
|
|
|
622
623
|
connected = true;
|
|
623
624
|
// Reset backoff so the next outage also starts at RECONNECT_BASE_MS.
|
|
624
625
|
reconnectDelayMs = RECONNECT_BASE_MS;
|
|
626
|
+
lastAbsentLogAt = 0;
|
|
625
627
|
bridgeClient = isBridgeUser(client.user);
|
|
626
628
|
if (bridgeClient) {
|
|
627
629
|
// Doctor greps this line: "connected as" feeds ipcStateFromLog, "arrpc"
|
|
@@ -641,24 +643,26 @@ async function connect() {
|
|
|
641
643
|
});
|
|
642
644
|
try { await self.login(); }
|
|
643
645
|
catch (e) {
|
|
644
|
-
|
|
646
|
+
// ECONNREFUSED is login()'s "no IPC socket accepted" — Discord isn't
|
|
647
|
+
// running, as opposed to a client that answered and then failed.
|
|
648
|
+
if (client === self) scheduleReconnect(`Discord login failed: ${e.message}`, { absent: e.code === 'ECONNREFUSED' });
|
|
645
649
|
} finally {
|
|
646
650
|
if (client === self) connecting = false;
|
|
647
651
|
}
|
|
648
652
|
}
|
|
649
653
|
|
|
650
|
-
function scheduleReconnect(reason = 'reconnect') {
|
|
654
|
+
function scheduleReconnect(reason = 'reconnect', { absent = false } = {}) {
|
|
651
655
|
connected = false;
|
|
652
656
|
if (reconnectTimer) return;
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
reconnectDelayMs =
|
|
657
|
+
const { waitMs, nextDelayMs } = reconnectPlan({ delayMs: reconnectDelayMs, absent });
|
|
658
|
+
const now = Date.now();
|
|
659
|
+
if (!absent || now - lastAbsentLogAt >= ABSENT_LOG_EVERY_MS) {
|
|
660
|
+
// Doctor greps "retry in Ns" (ipcStateFromLog) — keep the token if rewording.
|
|
661
|
+
log(`${reason} — retry in ${Math.round(waitMs / 1000)}s. Is Discord desktop running?`);
|
|
662
|
+
if (absent) lastAbsentLogAt = now;
|
|
663
|
+
}
|
|
664
|
+
reconnectTimer = setTimeout(() => { reconnectTimer = null; connect(); }, waitMs);
|
|
665
|
+
reconnectDelayMs = nextDelayMs;
|
|
662
666
|
}
|
|
663
667
|
|
|
664
668
|
function watchFiles() {
|
package/src/doctor.js
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
|
|
8
8
|
import { existsSync, readFileSync, statSync, readdirSync } from 'node:fs';
|
|
9
9
|
import { join } from 'node:path';
|
|
10
|
+
import { hookWord } from './shell-path.js';
|
|
10
11
|
import {
|
|
11
12
|
IS_PACKAGED, IS_NPM_INSTALL,
|
|
12
13
|
CONFIG_PATH, CANONICAL_EXE, USER_CONFIG_DIR, HOOK_SCRIPT,
|
|
@@ -113,8 +114,10 @@ export function classifyHookCommand(cmd, {
|
|
|
113
114
|
const launcher = m ? (m[1] ?? m[2]) : '';
|
|
114
115
|
if (launcher && !launcher.includes('/') && !launcher.includes('\\')) return 'legacy';
|
|
115
116
|
if (launcher && !exists(launcher)) return 'dead';
|
|
116
|
-
|
|
117
|
-
|
|
117
|
+
// Windows hooks may carry the 8.3 short form of the path (shell-path.js).
|
|
118
|
+
const wired = (p) => c.includes(p) || c.includes(p.replace(/\\/g, '/')) || c.includes(hookWord(p).replace(/"/g, ''));
|
|
119
|
+
if (packaged && !wired(canonicalExe)) return 'stale';
|
|
120
|
+
if (npm && !wired(hookScript)) return 'stale';
|
|
118
121
|
return 'ok';
|
|
119
122
|
}
|
|
120
123
|
|
package/src/install.js
CHANGED
|
@@ -23,6 +23,7 @@ import { DEFAULT_CONFIG } from './default-config.js';
|
|
|
23
23
|
import { VERSION } from './version.js';
|
|
24
24
|
import { c, SYM_OK, SYM_WARN, SYM_FAIL, SYM_INFO, hintLine } from './ui.js';
|
|
25
25
|
import { inferLegacyVerifyIntent } from './verify.js';
|
|
26
|
+
import { hookWord } from './shell-path.js';
|
|
26
27
|
|
|
27
28
|
const STARTUP_KEY = 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run';
|
|
28
29
|
const STARTUP_VALUE = 'ClaudeRPC';
|
|
@@ -161,6 +162,20 @@ export function isOurHook(h) {
|
|
|
161
162
|
return !!h && (h._claudeRpc === true || isOurHookCommand(h.command));
|
|
162
163
|
}
|
|
163
164
|
|
|
165
|
+
// The scripts hooks and autostart launch. Normally this install's own; setup
|
|
166
|
+
// under npx repoints them at the global copy it just installed (see
|
|
167
|
+
// useGlobalInstall) — the _npx cache can be evicted at any time.
|
|
168
|
+
let hookScript = HOOK_SCRIPT;
|
|
169
|
+
let daemonScript = DAEMON_SCRIPT;
|
|
170
|
+
|
|
171
|
+
// The command Claude Code runs for `event`. See shell-path.js for why Windows
|
|
172
|
+
// paths are emitted bare / 8.3 instead of quoted (PowerShell hook shells).
|
|
173
|
+
export function hookCommand(exePath, event, { script = hookScript, node = process.execPath } = {}) {
|
|
174
|
+
return IS_PACKAGED
|
|
175
|
+
? `${hookWord(exePath)} hook ${event}`
|
|
176
|
+
: `${hookWord(node)} ${hookWord(script)} ${event}`;
|
|
177
|
+
}
|
|
178
|
+
|
|
164
179
|
export function installHooks(exePath, { silent = false, ccVersion = detectClaudeCodeVersion() } = {}) {
|
|
165
180
|
const settings = readJson(CLAUDE_SETTINGS, {});
|
|
166
181
|
const before = JSON.stringify(settings.hooks || {});
|
|
@@ -174,10 +189,7 @@ export function installHooks(exePath, { silent = false, ccVersion = detectClaude
|
|
|
174
189
|
// for both npm and dev installs; only the packaged exe is self-contained. This
|
|
175
190
|
// survives `npm update` (HOOK_SCRIPT is stable) and an nvm version switch (nvm
|
|
176
191
|
// keeps prior versions on disk); re-run setup only if that node is removed.
|
|
177
|
-
const
|
|
178
|
-
const cmdFor = IS_PACKAGED
|
|
179
|
-
? (event) => `"${exePath}" hook ${event}`
|
|
180
|
-
: (event) => `"${node}" "${HOOK_SCRIPT.replace(/\\/g, '/')}" ${event}`;
|
|
192
|
+
const cmdFor = (event) => hookCommand(exePath, event);
|
|
181
193
|
|
|
182
194
|
const optional = supportedOptionalEvents(ccVersion);
|
|
183
195
|
for (const event of Object.keys(OPTIONAL_EVENTS)) {
|
|
@@ -245,7 +257,7 @@ const SYSTEMD_UNIT = join(homedir(), '.config', 'systemd', 'user', SYSTEMD_UNIT_
|
|
|
245
257
|
// (absolute node, like the hooks — login shells under nvm have no node on PATH).
|
|
246
258
|
function daemonLaunch(exePath) {
|
|
247
259
|
if (IS_PACKAGED) return { exe: exePath, args: ['daemon'] };
|
|
248
|
-
return { exe: process.execPath, args: [
|
|
260
|
+
return { exe: process.execPath, args: [daemonScript] };
|
|
249
261
|
}
|
|
250
262
|
|
|
251
263
|
// `npm` with the flags every call here needs: npm is npm.cmd on Windows (so a
|
|
@@ -709,20 +721,22 @@ export function migrateConfig({ silent = false } = {}) {
|
|
|
709
721
|
// command and report success, leaving the user to discover the breakage
|
|
710
722
|
// the next time they open Claude Code. Returns { ok, detail }.
|
|
711
723
|
function verifyHookPipe(exePath) {
|
|
712
|
-
//
|
|
713
|
-
//
|
|
714
|
-
//
|
|
715
|
-
//
|
|
716
|
-
|
|
717
|
-
const
|
|
724
|
+
// Run the exact command installHooks wired, through a shell Claude Code may
|
|
725
|
+
// use for hooks: sh on POSIX; on Windows, PowerShell — the strictest of its
|
|
726
|
+
// hook shells (a quoted-first command parses there as an expression, #48).
|
|
727
|
+
// Spawning node directly, as this used to, passed while every real hook
|
|
728
|
+
// failed.
|
|
729
|
+
const command = hookCommand(exePath, 'SessionStart');
|
|
730
|
+
const opts = { input: '', encoding: 'utf8', timeout: 8000, windowsHide: true };
|
|
718
731
|
let result;
|
|
719
732
|
try {
|
|
720
|
-
result =
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
733
|
+
result = process.platform === 'win32'
|
|
734
|
+
? spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', command], opts)
|
|
735
|
+
: spawnSync('/bin/sh', ['-c', command], opts);
|
|
736
|
+
// No PowerShell on this box (stripped image) — fall back to cmd.
|
|
737
|
+
if (result.error?.code === 'ENOENT' && process.platform === 'win32') {
|
|
738
|
+
result = spawnSync(command, { ...opts, shell: true });
|
|
739
|
+
}
|
|
726
740
|
} catch (e) {
|
|
727
741
|
return { ok: false, detail: `spawn failed: ${e.message}` };
|
|
728
742
|
}
|
|
@@ -759,15 +773,27 @@ function globalInstalledVersion() {
|
|
|
759
773
|
} catch { return null; } // not installed / npm missing / unreadable
|
|
760
774
|
}
|
|
761
775
|
|
|
776
|
+
// Point hooks + autostart at the global copy promoteNpxToGlobal installed,
|
|
777
|
+
// not this _npx cache tree. The global daemon's selfHealOnUpdate can't fix it
|
|
778
|
+
// later: the version stamp already matches, so it never re-wires (#48).
|
|
779
|
+
function useGlobalInstall() {
|
|
780
|
+
try {
|
|
781
|
+
const root = (npmSync(['root', '-g'], { timeout: 8000 }).stdout || '').trim();
|
|
782
|
+
const dir = root && join(root, 'claude-rpc', 'src');
|
|
783
|
+
if (dir && existsSync(join(dir, 'hook.js')) && existsSync(join(dir, 'daemon.js'))) {
|
|
784
|
+
hookScript = join(dir, 'hook.js');
|
|
785
|
+
daemonScript = join(dir, 'daemon.js');
|
|
786
|
+
}
|
|
787
|
+
} catch { /* npm unavailable — keep this tree; the next setup heals it */ }
|
|
788
|
+
}
|
|
789
|
+
|
|
762
790
|
// `npx claude-rpc setup` runs from npm's _npx cache, which npm may evict at
|
|
763
791
|
// any time, so first install the same version globally (`npm install -g`).
|
|
764
792
|
// Best-effort + loud: a failed -g (perms, offline) returns false so the caller
|
|
765
793
|
// stops with the manual command. What happens next: the rest of setup still
|
|
766
|
-
// runs in THIS process
|
|
767
|
-
//
|
|
768
|
-
//
|
|
769
|
-
// selfHealOnUpdate then re-wires hooks + autostart to the global paths — but
|
|
770
|
-
// only when the version stamp doesn't already match this version.
|
|
794
|
+
// runs in THIS process; useGlobalInstall then repoints installHooks and
|
|
795
|
+
// addStartupEntry at the global copy, and the daemon launch (cli.js `setup`)
|
|
796
|
+
// runs the global copy explicitly.
|
|
771
797
|
function promoteNpxToGlobal() {
|
|
772
798
|
// Already promoted on a previous run AND current? Skip the redundant -g (also
|
|
773
799
|
// lets setup succeed when a correct global exists but `npm -g` would fail —
|
|
@@ -867,6 +893,7 @@ export async function install({ exePath } = {}) {
|
|
|
867
893
|
throw err;
|
|
868
894
|
}
|
|
869
895
|
step(SYM_OK, 'global install', `claude-rpc@${VERSION}`);
|
|
896
|
+
useGlobalInstall();
|
|
870
897
|
}
|
|
871
898
|
const incoming = exePath || process.execPath;
|
|
872
899
|
// Canonicalize first so hook + startup entries point at a stable location,
|
package/src/presence.js
CHANGED
|
@@ -162,6 +162,31 @@ export function throttleDecision({ hash, lastSentHash, lastSentAt, now, gapMs, f
|
|
|
162
162
|
return { action: 'defer', waitMs };
|
|
163
163
|
}
|
|
164
164
|
|
|
165
|
+
// Discord reconnect pacing. Two different outages, two different caps:
|
|
166
|
+
//
|
|
167
|
+
// absent — no IPC socket accepted at all (Discord isn't running). A probe is
|
|
168
|
+
// a handful of local connects that fail instantly and touches no
|
|
169
|
+
// Discord process, so we keep polling fast. Otherwise someone who
|
|
170
|
+
// opens Discord after Claude Code waits out a multi-minute backoff
|
|
171
|
+
// and reads it as "presence doesn't work".
|
|
172
|
+
// present — a socket answered and then failed (handshake error, drop). Here
|
|
173
|
+
// the backoff protects a struggling client, so it climbs to 5min.
|
|
174
|
+
//
|
|
175
|
+
// `delayMs` is the current step; the caller stores `nextDelayMs` for the next
|
|
176
|
+
// failure and resets to RECONNECT_BASE_MS on a successful connect. ±30% jitter
|
|
177
|
+
// keeps sibling daemons from retrying in lockstep.
|
|
178
|
+
export const RECONNECT_BASE_MS = 5_000;
|
|
179
|
+
export const RECONNECT_CAP_MS = 300_000;
|
|
180
|
+
export const RECONNECT_ABSENT_CAP_MS = 15_000;
|
|
181
|
+
export function reconnectPlan({ delayMs, absent, rand = Math.random() }) {
|
|
182
|
+
const cap = absent ? RECONNECT_ABSENT_CAP_MS : RECONNECT_CAP_MS;
|
|
183
|
+
const step = Math.min(cap, Math.max(RECONNECT_BASE_MS, delayMs || 0));
|
|
184
|
+
return {
|
|
185
|
+
waitMs: Math.round(step * (0.7 + rand * 0.6)),
|
|
186
|
+
nextDelayMs: Math.min(cap, step * 2),
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
|
|
165
190
|
// Large-image key precedence (returns the TEMPLATE string; the caller fills it):
|
|
166
191
|
// 1. statusAssets[status] per-status art ("working" gif, etc.)
|
|
167
192
|
// 2. modelAssets[fable|opus|sonnet|haiku|default] per-model art, never stale
|
package/src/scanner.js
CHANGED
|
@@ -819,8 +819,14 @@ function readCache() {
|
|
|
819
819
|
if (!existsSync(SCAN_CACHE_PATH)) return { _v: CACHE_VERSION, files: {} };
|
|
820
820
|
try {
|
|
821
821
|
const raw = JSON.parse(readFileSync(SCAN_CACHE_PATH, 'utf8'));
|
|
822
|
-
if (!raw || raw.
|
|
823
|
-
return raw;
|
|
822
|
+
if (!raw || typeof raw.files !== 'object') return { _v: CACHE_VERSION, files: {} };
|
|
823
|
+
if (raw._v === CACHE_VERSION) return raw;
|
|
824
|
+
// A version bump re-parses everything still on disk, but `_gone` entries
|
|
825
|
+
// (transcripts Claude Code already pruned) can't be re-parsed — carry them
|
|
826
|
+
// over or the bump erases that history for good.
|
|
827
|
+
const files = {};
|
|
828
|
+
for (const [k, v] of Object.entries(raw.files || {})) if (v && v._gone) files[k] = v;
|
|
829
|
+
return { _v: CACHE_VERSION, files };
|
|
824
830
|
} catch { return { _v: CACHE_VERSION, files: {} }; }
|
|
825
831
|
}
|
|
826
832
|
|
|
@@ -1283,7 +1289,7 @@ export function scan({ projectsDir, projectsDirs, onProgress, force = false, ext
|
|
|
1283
1289
|
let st;
|
|
1284
1290
|
try { st = statSync(fp); } catch { continue; }
|
|
1285
1291
|
const sig = `${st.mtimeMs}:${st.size}`;
|
|
1286
|
-
if (!force && cache.files[fp]?._sig === sig) {
|
|
1292
|
+
if (!force && cache.files[fp]?._sig === sig && !cache.files[fp]._gone) {
|
|
1287
1293
|
skipped += 1;
|
|
1288
1294
|
continue;
|
|
1289
1295
|
}
|
|
@@ -1300,18 +1306,32 @@ export function scan({ projectsDir, projectsDirs, onProgress, force = false, ext
|
|
|
1300
1306
|
// skip corrupt file but keep prior cache entry
|
|
1301
1307
|
}
|
|
1302
1308
|
}
|
|
1303
|
-
//
|
|
1304
|
-
//
|
|
1305
|
-
//
|
|
1306
|
-
//
|
|
1309
|
+
// Transcripts that disappeared from disk are KEPT as `_gone` entries, not
|
|
1310
|
+
// deleted. Claude Code prunes transcripts older than cleanupPeriodDays (30 by
|
|
1311
|
+
// default), and dropping them made every "lifetime" total — and the profile
|
|
1312
|
+
// slice the worker SETs from it — shrink as history aged out. A gone entry is
|
|
1313
|
+
// dropped only when the same transcript is still on disk under another path (a
|
|
1314
|
+
// moved/renamed project dir), which would otherwise count it twice. Only
|
|
1315
|
+
// entries under the dirs we just scanned are touched, so a one-off backfill
|
|
1316
|
+
// against a subset of dirs leaves unrelated paths alone.
|
|
1307
1317
|
let removed = 0;
|
|
1308
1318
|
const sep = process.platform === 'win32' ? '\\' : '/';
|
|
1309
1319
|
const dirPrefixes = dirs.map((d) => d.replace(/[/\\]+$/, '') + sep);
|
|
1320
|
+
// Transcript basenames are the session (or subagent) id, so they survive a move.
|
|
1321
|
+
const baseOf = (p) => p.slice(Math.max(p.lastIndexOf('/'), p.lastIndexOf('\\')) + 1);
|
|
1322
|
+
const liveNames = new Set([...seen].map(baseOf));
|
|
1310
1323
|
for (const key of Object.keys(cache.files)) {
|
|
1311
1324
|
if (seen.has(key)) continue;
|
|
1312
|
-
if (dirPrefixes.some((p) => key.startsWith(p)))
|
|
1325
|
+
if (!dirPrefixes.some((p) => key.startsWith(p))) continue;
|
|
1326
|
+
const entry = cache.files[key];
|
|
1327
|
+
if (!entry || liveNames.has(baseOf(key))) {
|
|
1313
1328
|
delete cache.files[key];
|
|
1314
1329
|
removed += 1;
|
|
1330
|
+
} else if (!entry._gone) {
|
|
1331
|
+
// Append-parse bookkeeping is useless for a file that no longer exists.
|
|
1332
|
+
const { _parse, _offset, _size, ...kept } = entry;
|
|
1333
|
+
cache.files[key] = { ...kept, _gone: true };
|
|
1334
|
+
removed += 1;
|
|
1315
1335
|
}
|
|
1316
1336
|
}
|
|
1317
1337
|
const changed = scanned > 0 || removed > 0;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
// Paths for hook commands that every hook shell parses the same way.
|
|
2
|
+
//
|
|
3
|
+
// Claude Code runs hook commands through whatever shell the user has: sh /
|
|
4
|
+
// Git Bash, cmd, or PowerShell (issue #48). A line that STARTS with a quoted
|
|
5
|
+
// string is an expression in PowerShell, not a command, so the old
|
|
6
|
+
// `"C:/Program Files/nodejs/node.exe" "…/hook.js" Stop` form failed with
|
|
7
|
+
// "Unexpected token" on every event. PowerShell needs `& "…"`, which sh
|
|
8
|
+
// rejects. The shape all three accept is an unquoted path, so on Windows a
|
|
9
|
+
// path with spaces or shell metacharacters is swapped for its 8.3 short name
|
|
10
|
+
// (C:/PROGRA~1/nodejs/node.exe). Only when that isn't possible (8.3 names
|
|
11
|
+
// disabled on the volume) does it fall back to quoting.
|
|
12
|
+
import { existsSync } from 'node:fs';
|
|
13
|
+
import { spawnSync } from 'node:child_process';
|
|
14
|
+
|
|
15
|
+
// Characters no hook shell treats specially in a bare word.
|
|
16
|
+
const BARE_SAFE = /^[\w:./\\~+-]+$/;
|
|
17
|
+
const shortCache = new Map();
|
|
18
|
+
|
|
19
|
+
// 8.3 short form of an existing Windows path via cmd's %~s modifier, or null.
|
|
20
|
+
// `/c` without `/s` keeps cmd from stripping the quotes around the path.
|
|
21
|
+
export function shortPathWin(p, { spawn = spawnSync, exists = existsSync } = {}) {
|
|
22
|
+
if (shortCache.has(p)) return shortCache.get(p);
|
|
23
|
+
let out = null;
|
|
24
|
+
if (exists(p)) {
|
|
25
|
+
try {
|
|
26
|
+
const r = spawn('cmd.exe', ['/d', '/c', `for %I in ("${p.replace(/\//g, '\\')}") do @echo %~sI`], {
|
|
27
|
+
encoding: 'utf8', timeout: 4000, windowsHide: true, windowsVerbatimArguments: true,
|
|
28
|
+
});
|
|
29
|
+
const line = String(r.stdout || '').trim().split(/\r?\n/).pop();
|
|
30
|
+
if (r.status === 0 && line) out = line.replace(/\\/g, '/');
|
|
31
|
+
} catch { /* cmd unavailable — caller quotes */ }
|
|
32
|
+
}
|
|
33
|
+
shortCache.set(p, out);
|
|
34
|
+
return out;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// One argv word of a hook command. POSIX keeps the long-standing quoted form
|
|
38
|
+
// (sh is the only hook shell there). Windows: bare when safe, else the short
|
|
39
|
+
// path, else quoted as a last resort.
|
|
40
|
+
export function hookWord(p, { platform = process.platform, shortPath = shortPathWin } = {}) {
|
|
41
|
+
const fwd = String(p).replace(/\\/g, '/');
|
|
42
|
+
if (platform !== 'win32') return `"${fwd}"`;
|
|
43
|
+
if (BARE_SAFE.test(fwd)) return fwd;
|
|
44
|
+
const short = shortPath(fwd);
|
|
45
|
+
return short && BARE_SAFE.test(short) ? short : `"${fwd}"`;
|
|
46
|
+
}
|