import assert from "node:assert/strict"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import test from "node:test"; import { downloadInstaller } from "../main/updates/update-download"; test("downloadInstaller writes into the update temp directory and removes staging files", async () => { const previousFetch = globalThis.fetch; const tempDirectory = fs.mkdtempSync(path.join(os.tmpdir(), "scoreko-update-download-")); globalThis.fetch = async () => new Response("installer-bytes"); try { const installerPath = await downloadInstaller( { version: "0.2.0", title: "Scoreko 0.2.0", installer: { name: "Scoreko/setup:0.2.0.exe", downloadUrl: "https://updates.local/Scoreko-setup-0.2.0.exe", }, }, { tempDirectory, allowInsecureHttp: false }, ); const downloadDirectory = path.join(tempDirectory, "scoreko-updates"); assert.equal(installerPath, path.join(downloadDirectory, "Scoreko_setup_0.2.0.exe")); assert.equal(fs.readFileSync(installerPath, "utf8"), "installer-bytes"); assert.deepEqual( fs.readdirSync(downloadDirectory).filter((entry) => entry.endsWith(".download")), [], ); } finally { globalThis.fetch = previousFetch; } }); test("downloadInstaller rejects insecure production download URLs", async () => { const tempDirectory = fs.mkdtempSync(path.join(os.tmpdir(), "scoreko-update-download-")); await assert.rejects( () => downloadInstaller( { version: "0.2.0", title: "Scoreko 0.2.0", installer: { name: "Scoreko-setup-0.2.0.exe", downloadUrl: "http://updates.local/Scoreko-setup-0.2.0.exe", }, }, { tempDirectory, allowInsecureHttp: false }, ), /unsupported protocol/, ); }); test("downloadInstaller reuses existing file if size matches and does not download again", async () => { const tempDirectory = fs.mkdtempSync(path.join(os.tmpdir(), "scoreko-update-download-")); const downloadDirectory = path.join(tempDirectory, "scoreko-updates"); fs.mkdirSync(downloadDirectory, { recursive: true }); const installerPath = path.join(downloadDirectory, "Scoreko_setup_0.2.0.exe"); fs.writeFileSync(installerPath, "cached-installer-bytes"); const cachedSize = fs.statSync(installerPath).size; const previousFetch = globalThis.fetch; globalThis.fetch = async () => { throw new Error("Should not fetch when using cached file!"); }; try { const resultPath = await downloadInstaller( { version: "0.2.0", title: "Scoreko 0.2.0", installer: { name: "Scoreko/setup:0.2.0.exe", downloadUrl: "https://updates.local/Scoreko-setup-0.2.0.exe", size: cachedSize, }, }, { tempDirectory, allowInsecureHttp: false }, ); assert.equal(resultPath, installerPath); assert.equal(fs.readFileSync(resultPath, "utf8"), "cached-installer-bytes"); } finally { globalThis.fetch = previousFetch; } });