/** * The release payload and its place on disk. * * A payload is the sidecar the desktop app ships (service.js, a pinned Node, * native modules, staged node_modules) plus the built web UI, packed as one * tar.gz per release target with a manifest.json at its root. It runs on its * own Node, so native modules always match their ABI and nothing is compiled * on the user's machine. * * Install directory: * app/ the active payload * launcher.mjs a copy of this tool, run by the shim with app/'s Node * install.json what is installed and where it came from * downloads/ archives being fetched */ import { spawnSync } from 'node:child_process'; import { createHash } from 'node:crypto'; import fs from 'node:fs'; import { Readable } from 'node:stream'; import { pipeline } from 'node:stream/promises'; import type { Host } from './platform.js'; import { pathApi } from './platform.js'; export interface Layout { root: string; appDir: string; launcherFile: string; recordFile: string; downloadsDir: string; } export function layoutFor(root: string, platform: NodeJS.Platform): Layout { const p = pathApi(platform); return { root, appDir: p.join(root, 'app'), launcherFile: p.join(root, 'launcher.mjs'), recordFile: p.join(root, 'install.json'), downloadsDir: p.join(root, 'downloads'), }; } export interface InstallRecord { version: string; target: string; /** ISO 8601. */ installedAt: string; /** The path or URL the archive came from. */ source: string; sha256: string | null; /** The command shim install wrote, if any. */ shim: string | null; } export interface PayloadManifest { name: 'waggle-server'; version: string; target: string; /** Version of the bundled Node, without the leading v. */ node: string; } export function readRecord(layout: Layout): InstallRecord | null { try { return JSON.parse(fs.readFileSync(layout.recordFile, 'utf8')) as InstallRecord; } catch { return null; } } export function writeRecord(layout: Layout, record: InstallRecord): void { fs.writeFileSync(layout.recordFile, `${JSON.stringify(record, null, 2)}\n`); } export function readManifest(payloadDir: string, platform: NodeJS.Platform): PayloadManifest { const file = pathApi(platform).join(payloadDir, 'manifest.json'); let manifest: Partial; try { manifest = JSON.parse(fs.readFileSync(file, 'utf8')) as Partial; } catch { throw new Error('The archive has no readable manifest.json; it is not a Waggle server archive.'); } if (manifest.name !== 'waggle-server' || !manifest.version || !manifest.target || !manifest.node) { throw new Error('The archive manifest is not a Waggle server manifest.'); } return manifest as PayloadManifest; } export function nodeBinary(appDir: string, platform: NodeJS.Platform): string { return pathApi(platform).join(appDir, platform === 'win32' ? 'node.exe' : 'node'); } /** Files the sidecar cannot start without. */ export function missingPayloadFiles(appDir: string, platform: NodeJS.Platform): string[] { const p = pathApi(platform); return [ nodeBinary(appDir, platform), p.join(appDir, 'service.js'), p.join(appDir, 'node_modules'), p.join(appDir, 'web', 'index.html'), ].filter((file) => !fs.existsSync(file)); } // ── Checksums ──────────────────────────────────────────────────────────────── export async function sha256File(file: string): Promise { const hash = createHash('sha256'); await pipeline(fs.createReadStream(file), hash); return hash.digest('hex'); } /** Reads ` ` (sha256sum format) or a bare hex digest. */ export function parseChecksum(text: string): string | null { const match = /^\s*([0-9a-fA-F]{64})(?:\s|$)/.exec(text); return match ? match[1].toLowerCase() : null; } // ── Archives ───────────────────────────────────────────────────────────────── /** bsdtar ships with Windows 10 1803 and later; macOS and Linux always have tar. */ export function tarCommand(host: Pick): string { if (host.platform !== 'win32') return 'tar'; const systemRoot = host.env.SystemRoot || host.env.WINDIR || 'C:\\Windows'; return pathApi('win32').join(systemRoot, 'System32', 'tar.exe'); } export function extractArchive(host: Host, archive: string, destination: string): void { fs.mkdirSync(destination, { recursive: true }); const result = spawnSync(tarCommand(host), ['-xzf', archive, '-C', destination], { encoding: 'utf8', windowsHide: true, }); if (result.error || result.status !== 0) { const detail = result.error?.message ?? result.stderr.trim(); throw new Error(`Could not unpack ${archive}: ${detail}`); } } // ── Downloads ──────────────────────────────────────────────────────────────── export function isUrl(source: string): boolean { return /^https?:\/\//i.test(source); } export async function fetchText(url: string): Promise { const response = await fetch(url, { redirect: 'follow' }); if (response.status === 404) return null; if (!response.ok) throw new Error(`GET ${url} failed: HTTP ${response.status}`); return response.text(); } export async function downloadFile( url: string, destination: string, onProgress?: (received: number, total: number | null) => void, ): Promise { const response = await fetch(url, { redirect: 'follow' }); if (!response.ok || !response.body) { throw new Error(`Download of ${url} failed: HTTP ${response.status}`); } const total = Number(response.headers.get('content-length')) || null; let received = 0; const body = Readable.fromWeb(response.body as import('node:stream/web').ReadableStream); body.on('data', (chunk: Buffer) => { received += chunk.length; onProgress?.(received, total); }); const partial = `${destination}.partial`; try { await pipeline(body, fs.createWriteStream(partial)); fs.renameSync(partial, destination); } finally { fs.rmSync(partial, { force: true }); } } // ── Running the payload ────────────────────────────────────────────────────── export interface ServiceEnvOptions { appDir: string; dataDir: string; port: number; platform: NodeJS.Platform; baseEnv: NodeJS.ProcessEnv; /** Pass WAGGLE_DATA_DIR only when the user chose a directory. */ explicitDataDir: boolean; } /** * The environment the desktop shell gives its bundled sidecar * (app/src-tauri/src/service.rs, build_service_command), plus the web UI * directory, since here the sidecar serves the UI itself. */ export function serviceEnvironment(options: ServiceEnvOptions): NodeJS.ProcessEnv { const p = pathApi(options.platform); const runtimeDir = p.join(options.appDir, 'node_modules', 'waggle-node-runtime'); const nativeDir = p.join(options.appDir, 'native'); const env: NodeJS.ProcessEnv = { ...options.baseEnv, WAGGLE_SKIP_LITELLM: '1', WAGGLE_PORT: String(options.port), WAGGLE_FRONTEND_DIR: p.join(options.appDir, 'web'), NODE_PATH: [p.join(options.appDir, 'node_modules'), nativeDir].join(p.delimiter), ONNXRUNTIME_NODE_BINDING_PATH: p.join(nativeDir, 'onnxruntime'), PATH: [p.join(runtimeDir, 'bin'), options.appDir, options.baseEnv.PATH ?? options.baseEnv.Path] .filter(Boolean) .join(p.delimiter), NPM_EXECPATH: p.join(runtimeDir, 'node_modules', 'npm', 'bin', 'npm-cli.js'), NPM_CONFIG_PREFIX: p.join(options.dataDir, 'npm', 'prefix'), NPM_CONFIG_CACHE: p.join(options.dataDir, 'npm', 'cache'), }; // Windows keeps both spellings in process.env; a stale Path would shadow PATH. if (options.platform === 'win32') delete env.Path; if (options.explicitDataDir) env.WAGGLE_DATA_DIR = options.dataDir; else delete env.WAGGLE_DATA_DIR; return env; } // ── Command shim ───────────────────────────────────────────────────────────── export function shimFile(binDir: string, commandName: string, platform: NodeJS.Platform): string { return pathApi(platform).join(binDir, platform === 'win32' ? `${commandName}.cmd` : commandName); } /** Runs this tool with the payload's own Node, so the user's Node is not needed after install. */ export function shimContent(layout: Layout, platform: NodeJS.Platform): string { const node = nodeBinary(layout.appDir, platform); if (platform === 'win32') { return `@echo off\r\n"${node}" "${layout.launcherFile}" %*\r\n`; } const quote = (value: string) => `'${value.replace(/'/g, `'\\''`)}'`; return `#!/bin/sh\nexec ${quote(node)} ${quote(layout.launcherFile)} "$@"\n`; }