|
| 1 | +import { platform, tmpdir } from "os"; |
| 2 | +import { getProxyForUrl } from "proxy-from-env"; |
| 3 | +import * as https from "https"; |
| 4 | +import { createWriteStream } from "fs"; |
| 5 | +import { unlink, access, constants, mkdir, chmod } from "fs/promises"; |
| 6 | +import path from "node:path"; |
| 7 | + |
| 8 | +import { x } from "tar"; |
| 9 | +import extract from "extract-zip"; |
| 10 | + |
| 11 | +import * as packageJson from "../package.json" with { type: "json" }; |
| 12 | + |
| 13 | +const tmpDir = path.join(tmpdir(), `rari-cache-${packageJson.version}`); |
| 14 | +const isWindows = platform() === "win32"; |
| 15 | + |
| 16 | +const REPO = "mdn/rari"; |
| 17 | + |
| 18 | +/** |
| 19 | + * This function is adapted from vscode-ripgrep (https://github.com/microsoft/vscode-ripgrep) |
| 20 | + * Copyright (c) Microsoft, licensed under the MIT License |
| 21 | + * |
| 22 | + * @param {string} url |
| 23 | + */ |
| 24 | +function isGithubUrl(url) { |
| 25 | + return URL.parse(url)?.hostname === "api.github.com"; |
| 26 | +} |
| 27 | + |
| 28 | +/** |
| 29 | + * @param {string} path |
| 30 | + */ |
| 31 | +export async function exists(path) { |
| 32 | + try { |
| 33 | + await access(path, constants.F_OK); |
| 34 | + return true; |
| 35 | + } catch { |
| 36 | + return false; |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +/** |
| 41 | + * This function is adapted from vscode-ripgrep (https://github.com/microsoft/vscode-ripgrep) |
| 42 | + * Copyright (c) Microsoft, licensed under the MIT License |
| 43 | + * |
| 44 | + * @param {string} url |
| 45 | + * @param {import("fs").PathLike} dest |
| 46 | + * @param {any} opts |
| 47 | + */ |
| 48 | +export async function do_download(url, dest, opts) { |
| 49 | + const proxy = getProxyForUrl(URL.parse(url)); |
| 50 | + if (proxy !== "") { |
| 51 | + const HttpsProxyAgent = await import("https-proxy-agent"); |
| 52 | + opts = { |
| 53 | + ...opts, |
| 54 | + agent: new HttpsProxyAgent.HttpsProxyAgent(proxy), |
| 55 | + proxy, |
| 56 | + }; |
| 57 | + } |
| 58 | + |
| 59 | + if (opts.headers && opts.headers.authorization && !isGithubUrl(url)) { |
| 60 | + delete opts.headers.authorization; |
| 61 | + } |
| 62 | + |
| 63 | + return await new Promise((resolve, reject) => { |
| 64 | + console.log(`Download options: ${JSON.stringify(opts)}`); |
| 65 | + const outFile = createWriteStream(dest); |
| 66 | + |
| 67 | + https |
| 68 | + .get(url, opts, (response) => { |
| 69 | + console.log("statusCode: " + response.statusCode); |
| 70 | + if (response.statusCode === 302 && response.headers.location) { |
| 71 | + console.log("Following redirect to: " + response.headers.location); |
| 72 | + return do_download(response.headers.location, dest, opts).then( |
| 73 | + resolve, |
| 74 | + reject, |
| 75 | + ); |
| 76 | + } else if (response.statusCode !== 200) { |
| 77 | + reject(new Error("Download failed with " + response.statusCode)); |
| 78 | + return; |
| 79 | + } |
| 80 | + |
| 81 | + response.pipe(outFile); |
| 82 | + outFile.on("finish", () => { |
| 83 | + resolve(null); |
| 84 | + }); |
| 85 | + }) |
| 86 | + .on("error", async (err) => { |
| 87 | + await unlink(dest); |
| 88 | + reject(err); |
| 89 | + }); |
| 90 | + }); |
| 91 | +} |
| 92 | + |
| 93 | +/** |
| 94 | + * This function is adapted from vscode-ripgrep (https://github.com/microsoft/vscode-ripgrep) |
| 95 | + * Copyright (c) Microsoft, licensed under the MIT License |
| 96 | + * |
| 97 | + * @param {string} _url |
| 98 | + * @param {any} opts |
| 99 | + */ |
| 100 | +function get(_url, opts) { |
| 101 | + console.log(`GET ${_url}`); |
| 102 | + |
| 103 | + const proxy = getProxyForUrl(URL.parse(_url)); |
| 104 | + if (proxy !== "") { |
| 105 | + var HttpsProxyAgent = require("https-proxy-agent"); |
| 106 | + opts = { |
| 107 | + ...opts, |
| 108 | + agent: new HttpsProxyAgent.HttpsProxyAgent(proxy), |
| 109 | + }; |
| 110 | + } |
| 111 | + |
| 112 | + return new Promise((resolve, reject) => { |
| 113 | + let result = ""; |
| 114 | + https.get(_url, opts, (response) => { |
| 115 | + if (response.statusCode !== 200) { |
| 116 | + reject(new Error("Request failed: " + response.statusCode)); |
| 117 | + } |
| 118 | + |
| 119 | + response.on("data", (d) => { |
| 120 | + result += d.toString(); |
| 121 | + }); |
| 122 | + |
| 123 | + response.on("end", () => { |
| 124 | + resolve(result); |
| 125 | + }); |
| 126 | + |
| 127 | + response.on("error", (e) => { |
| 128 | + reject(e); |
| 129 | + }); |
| 130 | + }); |
| 131 | + }); |
| 132 | +} |
| 133 | + |
| 134 | +/** |
| 135 | + * @param {string} repo |
| 136 | + * @param {string} tag |
| 137 | + */ |
| 138 | +function getApiUrl(repo, tag) { |
| 139 | + return `https://api.github.com/repos/${repo}/releases/tags/${tag}`; |
| 140 | +} |
| 141 | + |
| 142 | +/** |
| 143 | + * This function is adapted from vscode-ripgrep (https://github.com/microsoft/vscode-ripgrep) |
| 144 | + * Copyright (c) Microsoft, licensed under the MIT License |
| 145 | + * |
| 146 | + * @param {{ force: boolean; token: string | undefined; version: string; }} opts |
| 147 | + * @param {string} assetName |
| 148 | + * @param {string} downloadFolder |
| 149 | + */ |
| 150 | +async function getAssetFromGithubApi(opts, assetName, downloadFolder) { |
| 151 | + const assetDownloadPath = path.join(downloadFolder, assetName); |
| 152 | + |
| 153 | + // We can just use the cached binary |
| 154 | + if (!opts.force && (await exists(assetDownloadPath))) { |
| 155 | + console.log("Using cached download: " + assetDownloadPath); |
| 156 | + return assetDownloadPath; |
| 157 | + } |
| 158 | + |
| 159 | + const downloadOpts = { |
| 160 | + headers: { |
| 161 | + "user-agent": "rari-npm", |
| 162 | + }, |
| 163 | + }; |
| 164 | + |
| 165 | + if (opts.token) { |
| 166 | + downloadOpts.headers.authorization = `token ${opts.token}`; |
| 167 | + } |
| 168 | + |
| 169 | + console.log(`Finding release for ${opts.version}`); |
| 170 | + const release = await get(getApiUrl(REPO, opts.version), downloadOpts); |
| 171 | + let jsonRelease; |
| 172 | + try { |
| 173 | + jsonRelease = JSON.parse(release); |
| 174 | + } catch (e) { |
| 175 | + throw new Error("Malformed API response: " + e.stack); |
| 176 | + } |
| 177 | + |
| 178 | + if (!jsonRelease.assets) { |
| 179 | + throw new Error("Bad API response: " + JSON.stringify(release)); |
| 180 | + } |
| 181 | + |
| 182 | + const asset = jsonRelease.assets.find((a) => a.name === assetName); |
| 183 | + if (!asset) { |
| 184 | + throw new Error("Asset not found with name: " + assetName); |
| 185 | + } |
| 186 | + |
| 187 | + console.log(`Downloading from ${asset.url}`); |
| 188 | + console.log(`Downloading to ${assetDownloadPath}`); |
| 189 | + |
| 190 | + downloadOpts.headers.accept = "application/octet-stream"; |
| 191 | + await do_download(asset.url, assetDownloadPath, downloadOpts); |
| 192 | +} |
| 193 | + |
| 194 | +/** |
| 195 | + * @param {string} packedFilePath |
| 196 | + * @param {string} destinationDir |
| 197 | + */ |
| 198 | +async function unpack(packedFilePath, destinationDir) { |
| 199 | + const rari_name = "rari"; |
| 200 | + if (isWindows) { |
| 201 | + await extract(packedFilePath, { dir: destinationDir }); |
| 202 | + } else { |
| 203 | + await x({ cwd: destinationDir, file: packedFilePath }); |
| 204 | + } |
| 205 | + |
| 206 | + const expectedName = path.join(destinationDir, rari_name); |
| 207 | + if (await exists(expectedName)) { |
| 208 | + return expectedName; |
| 209 | + } |
| 210 | + |
| 211 | + if (await exists(expectedName + ".exe")) { |
| 212 | + return expectedName + ".exe"; |
| 213 | + } |
| 214 | + |
| 215 | + throw new Error( |
| 216 | + `Expecting ${rari_name} or ${rari_name}.exe unzipped into ${destinationDir}, didn't find one.`, |
| 217 | + ); |
| 218 | +} |
| 219 | + |
| 220 | +/** |
| 221 | + * This function is adapted from vscode-ripgrep (https://github.com/microsoft/vscode-ripgrep) |
| 222 | + * Copyright (c) Microsoft, licensed under the MIT License |
| 223 | + * |
| 224 | + * @param {{ |
| 225 | + version: string; |
| 226 | + token: string | undefined; |
| 227 | + target: string; |
| 228 | + destDir: string; |
| 229 | + force: boolean; |
| 230 | + }} options |
| 231 | +*/ |
| 232 | +export async function download(options) { |
| 233 | + if (!options.version) { |
| 234 | + return Promise.reject(new Error("Missing version")); |
| 235 | + } |
| 236 | + |
| 237 | + if (!options.target) { |
| 238 | + return Promise.reject(new Error("Missing target")); |
| 239 | + } |
| 240 | + |
| 241 | + const extension = isWindows ? ".zip" : ".tar.gz"; |
| 242 | + const assetName = ["rari", options.target].join("-") + extension; |
| 243 | + |
| 244 | + if (!(await exists(tmpDir))) { |
| 245 | + await mkdir(tmpDir); |
| 246 | + } |
| 247 | + |
| 248 | + const assetDownloadPath = path.join(tmpDir, assetName); |
| 249 | + try { |
| 250 | + await getAssetFromGithubApi(options, assetName, tmpDir); |
| 251 | + } catch (e) { |
| 252 | + console.log("Deleting invalid download cache"); |
| 253 | + try { |
| 254 | + await unlink(assetDownloadPath); |
| 255 | + } catch (e) {} |
| 256 | + |
| 257 | + throw e; |
| 258 | + } |
| 259 | + |
| 260 | + console.log(`Unpacking to ${options.destDir}`); |
| 261 | + try { |
| 262 | + const destinationPath = await unpack(assetDownloadPath, options.destDir); |
| 263 | + if (!isWindows) { |
| 264 | + await chmod(destinationPath, "755"); |
| 265 | + } |
| 266 | + } catch (e) { |
| 267 | + console.log("Deleting invalid download"); |
| 268 | + |
| 269 | + try { |
| 270 | + await unlink(assetDownloadPath); |
| 271 | + } catch (e) {} |
| 272 | + |
| 273 | + throw e; |
| 274 | + } |
| 275 | +} |
0 commit comments