All files / src binary-manager.ts

100% Statements 89/89
100% Branches 43/43
100% Functions 8/8
100% Lines 89/89

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 1421x                                         1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x   1x 9x 9x 9x 9x 9x 9x 1x 1x                                 5x 5x 5x 5x 5x 5x 4x 4x 4x 5x 3x 3x   1x 3x 3x   1x 1x   1x 29x 29x 29x   1x 6x 6x   1x 3x 2x 3x 2x 2x 3x   1x 11x 2x 2x   11x 11x 11x   10x 10x   11x 9x 9x   11x 3x 3x 3x   1x 3x   11x 11x 1x  
import { requestUrl } from "obsidian";
import { execFile, spawn } from "child_process";
import {
    existsSync,
    mkdirSync,
    chmodSync,
    writeFileSync,
    readFileSync,
    unlinkSync,
    copyFileSync,
    cpSync,
    statSync,
    renameSync,
    readdirSync,
    rmSync,
} from "fs";
import { basename, join, resolve, dirname } from "path";
import { createHash } from "crypto";
import { promisify } from "util";
import { ARCH, PLATFORM } from "./types";
 
const execFileAsync = promisify(execFile);
 
/** Exported for test mocking. */
export const node = {
    spawn,
    execFile: execFileAsync,
    existsSync,
    mkdirSync,
    chmodSync,
    writeFileSync,
    readFileSync,
    unlinkSync,
    copyFileSync,
    cpSync,
    statSync,
    renameSync,
    readdirSync,
    rmSync,
    join,
    basename,
    resolve,
    dirname,
    createHash,
    processKill: process.kill.bind(process),
    requestUrl,
    fetch: globalThis.fetch.bind(globalThis) as typeof globalThis.fetch,
};
 
const GITHUB_REPO = "tobocop2/lilbee";
const RELEASES_API = `https://api.github.com/repos/${GITHUB_REPO}/releases/latest`;
 
export function getPlatformAssetName(): string {
    const platform = process.platform;
    const arch = process.arch;
    if (platform === PLATFORM.DARWIN && arch === ARCH.ARM64) return "lilbee-macos-arm64";
    if (platform === PLATFORM.DARWIN && arch === ARCH.X64) return "lilbee-macos-x86_64";
    if (platform === PLATFORM.LINUX && arch === ARCH.X64) return "lilbee-linux-x86_64";
    if (platform === PLATFORM.WIN32 && arch === ARCH.X64) return "lilbee-windows-x86_64.exe";
    throw new Error(`Unsupported platform: ${platform}/${arch}`);
}
 
interface GitHubAsset {
    name: string;
    browser_download_url: string;
}
 
interface GitHubRelease {
    tag_name: string;
    assets: GitHubAsset[];
}
 
export interface ReleaseInfo {
    tag: string;
    assetUrl: string;
}
 
export async function getLatestRelease(): Promise<ReleaseInfo> {
    const res = await node.requestUrl({
        url: RELEASES_API,
        headers: { Accept: "application/vnd.github.v3+json" },
    });
    if (res.status >= 400) throw new Error(`GitHub API responded ${res.status}`);
    const data = res.json as GitHubRelease;
    const assetName = getPlatformAssetName();
    const asset = data.assets.find((a) => a.name === assetName);
    if (!asset) throw new Error(`No asset "${assetName}" in release ${data.tag_name}`);
    return { tag: data.tag_name, assetUrl: asset.browser_download_url };
}
 
export function checkForUpdate(currentVersion: string, latestTag: string): boolean {
    return currentVersion !== latestTag && latestTag !== "";
}
 
export class BinaryManager {
    constructor(private binDir: string) {}
 
    get binaryPath(): string {
        const name = process.platform === PLATFORM.WIN32 ? "lilbee.exe" : "lilbee";
        return join(this.binDir, name);
    }
 
    binaryExists(): boolean {
        return node.existsSync(this.binaryPath);
    }
 
    async ensureBinary(onProgress?: (msg: string, url?: string) => void): Promise<string> {
        if (this.binaryExists()) return this.binaryPath;
        onProgress?.("Fetching latest release info...");
        const release = await getLatestRelease();
        await this.download(release.assetUrl, onProgress);
        return this.binaryPath;
    }
 
    async download(assetUrl: string, onProgress?: (msg: string, url?: string) => void): Promise<void> {
        if (!node.existsSync(this.binDir)) {
            node.mkdirSync(this.binDir, { recursive: true });
        }
 
        onProgress?.("Downloading...", assetUrl);
        const res = await node.requestUrl({ url: assetUrl });
        if (res.status >= 400) throw new Error(`Download failed: ${res.status}`);
 
        const dest = this.binaryPath;
        node.writeFileSync(dest, Buffer.from(res.arrayBuffer));
 
        if (process.platform !== PLATFORM.WIN32) {
            node.chmodSync(dest, 0o755);
        }
 
        if (process.platform === PLATFORM.DARWIN) {
            try {
                await node.execFile("xattr", ["-cr", dest]);
            } catch {
                // xattr failure is non-fatal — user may need to allow in System Preferences
            }
        }
 
        onProgress?.("Download complete.", assetUrl);
    }
}