Files
epub-tools/tests/epub/fixture.ts
T
2026-09-01 02:39:03 +02:00

52 lines
2.5 KiB
TypeScript

import {
BlobWriter,
TextReader,
Uint8ArrayReader,
ZipWriter,
} from "@zip.js/zip.js";
export async function createEpubFixture(
options: {
brokenLink?: boolean;
activeContent?: boolean;
compressedMimetype?: boolean;
} = {},
): Promise<File> {
const writer = new ZipWriter(new BlobWriter("application/epub+zip"));
await writer.add("mimetype", new TextReader("application/epub+zip"), {
level: options.compressedMimetype ? 6 : 0,
});
await writer.add(
"META-INF/container.xml",
new TextReader(
`<?xml version="1.0"?><container xmlns="urn:oasis:names:tc:opendocument:xmlns:container"><rootfiles><rootfile full-path="EPUB/package.opf" media-type="application/oebps-package+xml"/></rootfiles></container>`,
),
);
await writer.add(
"EPUB/package.opf",
new TextReader(
`<?xml version="1.0" encoding="UTF-8"?><package xmlns="http://www.idpf.org/2007/opf" version="3.0" unique-identifier="book-id"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:identifier id="book-id">urn:test:book</dc:identifier><dc:title>Fixture Book</dc:title><dc:language>en</dc:language><dc:creator>Ada Example</dc:creator></metadata><manifest><item id="nav" href="nav.xhtml" media-type="application/xhtml+xml" properties="nav"/><item id="chapter" href="chapter.xhtml" media-type="application/xhtml+xml"/><item id="cover" href="cover.png" media-type="image/png" properties="cover-image"/></manifest><spine><itemref idref="chapter"/></spine></package>`,
),
);
await writer.add(
"EPUB/nav.xhtml",
new TextReader(
`<?xml version="1.0"?><html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops"><head><title>Contents</title></head><body><nav epub:type="toc"><ol><li><a href="chapter.xhtml">Opening chapter</a></li></ol></nav></body></html>`,
),
);
await writer.add(
"EPUB/chapter.xhtml",
new TextReader(
`<?xml version="1.0"?><html xmlns="http://www.w3.org/1999/xhtml"><head><title>Opening chapter</title></head><body><h1>Hello</h1><p>Local reading.</p>${options.activeContent ? "<script>globalThis.pwned=true</script><form><input/></form>" : ""}<img src="cover.png"/><a href="${options.brokenLink ? "missing.xhtml" : "nav.xhtml"}">Next</a></body></html>`,
),
);
await writer.add(
"EPUB/cover.png",
new Uint8ArrayReader(
new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
),
);
const blob = await writer.close();
return new File([blob], "fixture.epub", { type: "application/epub+zip" });
}