|
| 1 | +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; |
| 2 | +import { tmpdir } from "node:os"; |
| 3 | +import { join } from "node:path"; |
| 4 | +import AdmZip from "adm-zip"; |
| 5 | +import { parseHTML } from "linkedom"; |
| 6 | +import { expect, it, onTestFinished } from "vitest"; |
| 7 | +import { createPublishArchive, readStaged, stagePublishFiles } from "./publishProject.js"; |
| 8 | + |
| 9 | +it.each([Infinity, 1])( |
| 10 | + "preserves existing archive paths when localizing assets (threshold %s)", |
| 11 | + (threshold) => { |
| 12 | + const root = mkdtempSync(join(tmpdir(), "hf-publish-collision-")); |
| 13 | + onTestFinished(() => rmSync(root, { recursive: true, force: true })); |
| 14 | + const project = join(root, "project"); |
| 15 | + mkdirSync(join(project, "_ext", "shared"), { recursive: true }); |
| 16 | + mkdirSync(join(root, "shared")); |
| 17 | + writeFileSync(join(project, "_ext", "shared", "logo.png"), "existing logo"); |
| 18 | + writeFileSync(join(project, "_ext", "shared", "logo_2.png"), "another existing logo"); |
| 19 | + writeFileSync(join(root, "shared", "logo.png"), "new external logo"); |
| 20 | + const html = |
| 21 | + '<html><body><img src="_ext/shared/logo.png"><img src="_ext/shared/logo_2.png"><img src="../shared/logo.png"><img src="../shared/logo.png"></body></html>'; |
| 22 | + writeFileSync(join(project, "index.html"), html); |
| 23 | + |
| 24 | + const files = stagePublishFiles(project, threshold); |
| 25 | + const contents = new Map([...files].map(([path, file]) => [path, readStaged(file).toString()])); |
| 26 | + expect(contents.size).toBe(4); |
| 27 | + expect(contents.get("_ext/shared/logo.png")).toBe("existing logo"); |
| 28 | + expect(contents.get("_ext/shared/logo_2.png")).toBe("another existing logo"); |
| 29 | + expect(contents.get("_ext/shared/logo_3.png")).toBe("new external logo"); |
| 30 | + const { document } = parseHTML(contents.get("index.html") ?? ""); |
| 31 | + expect([...document.querySelectorAll("img")].map((img) => img.getAttribute("src"))).toEqual([ |
| 32 | + "_ext/shared/logo.png", |
| 33 | + "_ext/shared/logo_2.png", |
| 34 | + "_ext/shared/logo_3.png", |
| 35 | + "_ext/shared/logo_3.png", |
| 36 | + ]); |
| 37 | + |
| 38 | + const archive = createPublishArchive(project); |
| 39 | + const zip = new AdmZip(archive.buffer); |
| 40 | + expect(archive.fileCount).toBe(4); |
| 41 | + expect(zip.readAsText("_ext/shared/logo.png")).toBe("existing logo"); |
| 42 | + expect(zip.readAsText("_ext/shared/logo_3.png")).toBe("new external logo"); |
| 43 | + expect(readFileSync(join(project, "index.html"), "utf-8")).toBe(html); |
| 44 | + expect(readFileSync(join(project, "_ext", "shared", "logo.png"), "utf-8")).toBe( |
| 45 | + "existing logo", |
| 46 | + ); |
| 47 | + }, |
| 48 | +); |
0 commit comments