smartdeno/ts/classes.denodownloader.ts
2024-03-17 21:24:25 +01:00

81 lines
2.6 KiB
TypeScript

import * as plugins from './plugins.js';
import * as paths from './paths.js';
import { promises as fs } from 'fs';
import { platform } from 'os';
interface IDenoRelease {
name: string;
assets: IAsset[];
}
interface IAsset {
name: string;
browser_download_url: string;
}
export class DenoDownloader {
private async getDenoDownloadUrl(): Promise<string> {
const osPlatform = platform(); // 'darwin', 'linux', 'win32', etc.
const arch = process.arch; // 'x64', 'arm64', etc.
let osPart: string;
switch (osPlatform) {
case 'darwin':
osPart = 'apple-darwin';
break;
case 'win32':
osPart = 'pc-windows-msvc';
break;
case 'linux':
osPart = 'unknown-linux-gnu';
break;
default:
throw new Error(`Unsupported platform: ${osPlatform}`);
}
const archPart = arch === 'x64' ? 'x86_64' : 'aarch64';
const releasesResponse = await fetch('https://api.github.com/repos/denoland/deno/releases/latest');
const release: IDenoRelease = await releasesResponse.json();
const executableName = `deno-${archPart}-${osPart}.zip`; // Adjust if naming convention changes
const asset = release.assets.find(a => a.name === executableName);
if (!asset) {
throw new Error(`Deno release for ${osPlatform} (${arch}) not found.`);
}
return asset.browser_download_url;
}
private async downloadDeno(url: string, outputPath: string): Promise<void> {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Failed to download Deno: ${response.statusText}`);
}
const buffer = await response.arrayBuffer();
await fs.writeFile(outputPath, Buffer.from(buffer));
}
public async download(outputPath: string = './deno.zip'): Promise<void> {
try {
const url = await this.getDenoDownloadUrl();
await this.downloadDeno(url, outputPath);
console.log(`Deno downloaded successfully to ${outputPath}`);
} catch (error) {
console.error(`Error downloading Deno: ${error.message}`);
}
if (await plugins.smartfile.fs.fileExists(plugins.path.join(paths.nogitDir, 'deno'))) {
return;
}
const smartarchive = await plugins.smartarchive.SmartArchive.fromArchiveFile(outputPath);
const directory = plugins.path.dirname(outputPath);
console.log(`Extracting deno.zip to ${directory}`);
await smartarchive.exportToFs(directory);
const smartshellInstance = new plugins.smarthshell.Smartshell({
executor: 'bash'
});
await smartshellInstance.exec(`(cd ${paths.nogitDir} && chmod +x deno)`);
}
}