Skill Tracer
Skills › HyperFrames › media-use › npx-sync.mjs

npx-sync.mjs

57 lines · skills/media-use/scripts/lib/npx-sync.mjs at a595755

1import { existsSync } from "node:fs";
2import { dirname, join } from "node:path";
3
4function resolveNpxCliPath(env, pathExists) {
5 const npmExecPath = env.npm_execpath;
6 const nodeExecPath = env.npm_node_execpath || process.execPath;
7 if (npmExecPath) {
8 const fileName = npmExecPath.replace(/\\/g, "/").split("/").pop()?.toLowerCase();
9 const candidate =
10 fileName === "npx-cli.js" ? npmExecPath : join(dirname(npmExecPath), "npx-cli.js");
11 if (pathExists(candidate)) return candidate;
12 }
13 const besideNode = join(dirname(nodeExecPath), "node_modules", "npm", "bin", "npx-cli.js");
14 return pathExists(besideNode) ? besideNode : null;
17// Sync-spawn analog of the audio engine's spawnP, for execFileSync call sites
18// that must hard-fail (rather than fall through to another provider) when npx
19// cannot be resolved. On Windows a bare "npx" is npx.cmd, which
20// execFileSync/spawnSync cannot exec (spawnSync npx ENOENT) —
21// resolveSpawnCommand reroutes it through node + npx-cli.js, no shell:true.
22//
23// `platform`/`env`/`pathExists` params (defaulting to the real values) exist
24// so tests can exercise the win32 branch without mocking node:child_process
25// (its ESM exports are non-configurable) — same idiom as spawnP and
26// localTtsGenerate.
27export function resolveNpxInvocation(
28 argv,
29 opts,
30 platform = process.platform,
31 env = process.env,
32 pathExists = existsSync,
33) {
34 const resolved =
35 platform !== "win32"
36 ? { cmd: "npx", args: argv, opts: { stdio: "ignore", ...opts } }
37 : (() => {
38 const nodeExecPath = env.npm_node_execpath || process.execPath;
39 const npxCliPath = resolveNpxCliPath(env, pathExists);
40 return npxCliPath
41 ? {
42 cmd: nodeExecPath,
43 args: [npxCliPath, ...argv.map((arg) => String(arg))],
44 opts: { stdio: "ignore", windowsHide: true, ...opts },
45 }
46 : null;
47 })();
48 if (!resolved) {
49 // npx-on-win32 with no resolvable npx-cli.js — same terminal condition
50 // spawnP warns about, surfaced as a throw for callers with no fallback.
51 throw new Error(
52 "cannot run npx on Windows: npm's npx-cli.js was not found " +
53 "(install npm with Node, or run via npx/npm run so npm_execpath is set)",
54 );
55 }
56 return resolved;