From aa248568d0a6742a981a588e1dbabf0248d6f8b4 Mon Sep 17 00:00:00 2001 From: Praveen Perera Date: Tue, 26 Nov 2024 10:29:30 -0600 Subject: [PATCH] Create download-release.js --- npm/lib/download-release.js | 54 +++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 npm/lib/download-release.js diff --git a/npm/lib/download-release.js b/npm/lib/download-release.js new file mode 100644 index 0000000..64b05e6 --- /dev/null +++ b/npm/lib/download-release.js @@ -0,0 +1,54 @@ +// @ts-check +"use strict"; + +const { REPO } = require("./constants"); +const get = require("./get"); + +/** + * @param {string} repo + * @param {string} tag + */ +function getApiUrl(repo, tag) { + return `https://api.github.com/repos/${repo}/releases/tags/${tag}`; +} + +/** + * @param {{ token?: string; version: string; }} opts + */ +async function getReleaseFromGitHubApi(opts) { + const downloadOpts = { + headers: { + "user-agent": "rustywind", + }, + }; + + if (opts.token) { + downloadOpts.headers.authorization = `token ${opts.token}`; + } + + console.log(`Finding rustywind ${opts.version} release`); + const release = await get(getApiUrl(REPO, opts.version), downloadOpts); + let jsonRelease; + try { + jsonRelease = JSON.parse(release); + } catch (e) { + throw new Error("Malformed API response: " + e.stack); + } + + if (!jsonRelease.assets) { + throw new Error("Bad API response: " + JSON.stringify(release)); + } + + return jsonRelease; +} + +/** + * @param {{ token?: string; version: string; }} opts + */ +module.exports = async (opts) => { + if (!opts.version) { + return Promise.reject(new Error("Missing version")); + } + + return getReleaseFromGitHubApi(opts); +};