UNPKG

zignet

Version:

MCP server for Zig — AI-powered code analysis, validation, and documentation with fine-tuned LLM

310 lines (307 loc) 9.55 kB
const require_chunk = require('./chunk-DWy1uDak.cjs'); const require_config = require('./config-C2ufArDU.cjs'); let child_process = require("child_process"); child_process = require_chunk.__toESM(child_process); let fs = require("fs"); fs = require_chunk.__toESM(fs); let path = require("path"); path = require_chunk.__toESM(path); let os = require("os"); os = require_chunk.__toESM(os); //#region src/zig/manager.ts /** * Detect system-installed Zig version * @returns Zig version string (e.g., "0.15.0") or null if not found */ function detectSystemZig() { try { const version = (0, child_process.execSync)("zig version", { encoding: "utf-8", stdio: [ "pipe", "pipe", "ignore" ] }).trim(); console.log(`🔍 Found system Zig: ${version}`); return version; } catch { return null; } } /** * Get path to system Zig binary (if available) * @returns Absolute path to system zig binary or null */ function getSystemZigPath() { try { return (0, child_process.execSync)(process.platform === "win32" ? "where zig" : "which zig", { encoding: "utf-8", stdio: [ "pipe", "pipe", "ignore" ] }).trim(); } catch { return null; } } /** * Detect current platform */ function detectPlatform() { const platform = process.platform; const arch = process.arch; let detectedPlatform; let detectedArch; if (platform === "linux") detectedPlatform = "linux"; else if (platform === "darwin") detectedPlatform = "macos"; else if (platform === "win32") detectedPlatform = "windows"; else throw new Error(`Unsupported platform: ${platform}`); if (arch === "x64") detectedArch = "x86_64"; else if (arch === "arm64") detectedArch = "aarch64"; else throw new Error(`Unsupported architecture: ${arch}`); return { platform: detectedPlatform, arch: detectedArch, ext: detectedPlatform === "windows" ? ".zip" : ".tar.xz" }; } /** * Get Zig download URL for a specific version */ function getZigDownloadUrl(version) { const { platform, arch, ext } = detectPlatform(); const zigPlatform = { linux: "linux", macos: "macos", windows: "windows" }[platform]; return `https://ziglang.org/download/${version}/${parseFloat(version) >= .15 ? `zig-${arch}-${zigPlatform}-${version}${ext}` : `zig-${zigPlatform}-${arch}-${version}${ext}`}`; } /** * Get cache directory for Zig installations */ function getZigCacheDir() { const cacheDir = (0, path.join)((0, os.homedir)(), ".zignet", "zig-versions"); if (!(0, fs.existsSync)(cacheDir)) (0, fs.mkdirSync)(cacheDir, { recursive: true }); return cacheDir; } /** * Get installation path for a specific Zig version */ function getZigInstallPath(version) { return (0, path.join)(getZigCacheDir(), version); } /** * Get Zig binary path for a specific version */ function getZigBinaryPath(version) { const installPath = getZigInstallPath(version); const { platform, arch } = detectPlatform(); const binaryName = platform === "windows" ? "zig.exe" : "zig"; const zigPlatform = { linux: "linux", macos: "macos", windows: "windows" }[platform]; return (0, path.join)(installPath, parseFloat(version) >= .15 ? `zig-${arch}-${zigPlatform}-${version}` : `zig-${zigPlatform}-${arch}-${version}`, binaryName); } /** * Check if a specific Zig version is installed */ function isZigInstalled(version) { return (0, fs.existsSync)(getZigBinaryPath(version)); } /** * Download and install a specific Zig version */ function installZig(version) { if (isZigInstalled(version)) { console.log(`✅ Zig ${version} already installed`); return; } console.log(`📥 Downloading Zig ${version}...`); const url = getZigDownloadUrl(version); const installPath = getZigInstallPath(version); if (!(0, fs.existsSync)(installPath)) (0, fs.mkdirSync)(installPath, { recursive: true }); try { const { platform } = detectPlatform(); if (platform === "windows") { const tempFile = (0, path.join)(installPath, `zig-${version}.zip`); console.log(`📥 Downloading ${url}...`); (0, child_process.execSync)(`powershell -Command "(New-Object System.Net.WebClient).DownloadFile('${url}', '${tempFile}')"`, { stdio: "inherit" }); console.log(`📦 Extracting Zig ${version}...`); try { (0, child_process.execSync)(`tar -xf "${tempFile}" -C "${installPath}"`, { stdio: "inherit" }); } catch { console.warn("⚠️ tar.exe not found, falling back to Expand-Archive (slower)..."); (0, child_process.execSync)(`powershell -Command "Expand-Archive -Path '${tempFile}' -DestinationPath '${installPath}' -Force"`, { stdio: "inherit" }); } (0, child_process.execSync)(`del "${tempFile}"`, { stdio: "inherit" }); } else { const tempFile = (0, path.join)(installPath, `zig-${version}.tar.xz`); (0, child_process.execSync)(`curl -fSL "${url}" -o "${tempFile}"`, { stdio: "inherit" }); console.log(`📦 Extracting Zig ${version}...`); (0, child_process.execSync)(`tar -xJf "${tempFile}" -C "${installPath}"`, { stdio: "inherit" }); (0, child_process.execSync)(`rm "${tempFile}"`); } const binaryPath = getZigBinaryPath(version); if (!(0, fs.existsSync)(binaryPath)) throw new Error(`Installation failed: binary not found at ${binaryPath}`); (0, fs.chmodSync)(binaryPath, 493); console.log(`✅ Zig ${version} installed successfully at ${binaryPath}`); } catch (error) { const message = error instanceof Error ? error.message : String(error); throw new Error(`Failed to install Zig ${version}: ${message}`); } } /** * Ensure a specific Zig version is installed (install if needed) * First checks system PATH, then falls back to downloading * @param version Zig version to ensure * @returns Absolute path to Zig binary */ function ensureZig(version) { if (isZigInstalled(version)) return getZigBinaryPath(version); if (detectSystemZig() === version) { const systemPath = getSystemZigPath(); if (systemPath) { console.log(`✅ Using system Zig ${version} at ${systemPath}`); return systemPath; } } console.log(`📥 Zig ${version} not found in system, downloading...`); installZig(version); return getZigBinaryPath(version); } //#endregion //#region src/zig/executor.ts /** * Parse Zig compiler output to extract diagnostics * * Zig error format: * /tmp/file.zig:2:5: error: expected type 'i32', found '[]const u8' * return "hello"; * ^~~~~~~~~~~~~~ */ function parseZigOutput(output) { const diagnostics = []; const lines = output.split("\n"); for (let i = 0; i < lines.length; i++) { const line = lines[i]; const match = line.match(/^(.+?):(\d+):(\d+):\s+(error|warning|note):\s+(.+)$/); if (match) { const [, file, lineNum, colNum, severity, message] = match; diagnostics.push({ message: message.trim(), file, line: parseInt(lineNum, 10), column: parseInt(colNum, 10), severity }); } else if (line.trim().startsWith("error:")) diagnostics.push({ message: line.replace(/^error:\s+/, "").trim(), severity: "error" }); } return diagnostics; } /** * Execute Zig AST check on code * * @param code - Zig source code to check * @param version - Zig version to use (default: from ZIG_DEFAULT env var) * @returns Result with success status and diagnostics */ function zigAstCheck(code, version = require_config.DEFAULT_ZIG_VERSION) { const zigBinary = ensureZig(version); const tempFile = (0, path.join)((0, fs.mkdtempSync)((0, path.join)((0, os.tmpdir)(), "zignet-")), "check.zig"); try { (0, fs.writeFileSync)(tempFile, code, "utf8"); try { return { success: true, output: (0, child_process.execSync)(`"${zigBinary}" ast-check "${tempFile}"`, { encoding: "utf8", stdio: "pipe" }).trim(), diagnostics: [] }; } catch (error) { const errorObj = error; const stderr = (errorObj.stderr ?? errorObj.stdout ?? Buffer.from("")).toString(); const diagnostics = parseZigOutput(stderr); return { success: false, output: stderr.trim(), diagnostics }; } } finally { try { (0, fs.unlinkSync)(tempFile); } catch {} } } /** * Execute Zig format on code * * @param code - Zig source code to format * @param version - Zig version to use (default: from ZIG_DEFAULT env var) * @returns Formatted code or error */ function zigFormat(code, version = require_config.DEFAULT_ZIG_VERSION) { const zigBinary = ensureZig(version); const tempFile = (0, path.join)((0, fs.mkdtempSync)((0, path.join)((0, os.tmpdir)(), "zignet-")), "format.zig"); try { (0, fs.writeFileSync)(tempFile, code, "utf8"); try { (0, child_process.execSync)(`"${zigBinary}" fmt --check "${tempFile}"`, { encoding: "utf8", stdio: "pipe" }); return { success: true, output: code, diagnostics: [] }; } catch { try { (0, child_process.execSync)(`"${zigBinary}" fmt "${tempFile}"`, { stdio: "pipe" }); return { success: true, output: (0, fs.readFileSync)(tempFile, "utf8"), diagnostics: [] }; } catch (fmtError) { const errorObj = fmtError; const stderr = (errorObj.stderr ?? errorObj.stdout ?? Buffer.from("")).toString(); const diagnostics = parseZigOutput(stderr); return { success: false, output: stderr.trim(), diagnostics }; } } } finally { try { (0, fs.unlinkSync)(tempFile); } catch {} } } //#endregion Object.defineProperty(exports, 'zigAstCheck', { enumerable: true, get: function () { return zigAstCheck; } }); Object.defineProperty(exports, 'zigFormat', { enumerable: true, get: function () { return zigFormat; } }); //# sourceMappingURL=executor-ON2Rt60w.cjs.map