Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

refactor(build-tools): one ZIP implementation, read as well as write

esengine7e6a70d842f7
diff --git a/build-tools/utils/zip.d.ts b/build-tools/utils/zip.d.ts
new file mode 100644
index 000000000..73b4915f8
--- /dev/null
+++ b/build-tools/utils/zip.d.ts
@@ -0,0 +1,16 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+//
+// Types for zip.js — the module is plain ESM so the CLI can run it unbuilt, and
+// this is how the editor's TypeScript sees it.
+
+export interface ZipEntry {
+ /** Path inside the archive, with forward slashes. */
+ name: string;
+ data: Buffer;
+}
+
+export function makeZip(entries: readonly ZipEntry[]): Buffer;
+export function zipTree(dir: string, prefix?: string): ZipEntry[];
+export function readZip(buf: Buffer): ZipEntry[];
+export function extractZip(buf: Buffer, destDir: string): string[];
diff --git a/build-tools/utils/zip.js b/build-tools/utils/zip.js
new file mode 100644
index 000000000..5bb100ece
--- /dev/null
+++ b/build-tools/utils/zip.js
@@ -0,0 +1,201 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+//
+// The repo's one ZIP implementation — write and read. Plain ESM so both halves
+// reach it: the CLI writes runtime templates, the editor writes playable ad
+// bundles and reads a template someone installs from a file.
+//
+// Written rather than depended on: what is needed is stored/deflated entries in
+// one flat archive — no zip64, no encryption, no split volumes — and a dependency
+// for that is more surface than the format.
+//
+// Deterministic by construction: entries carry a FIXED DOS timestamp and are
+// written in the order given, so the same input always produces byte-identical
+// output. An artifact that changes only because the clock moved is one you cannot
+// diff, and a checksum that moves on its own is not a checksum.
+
+import { deflateRawSync, inflateRawSync } from 'zlib';
+import { readdirSync, readFileSync, mkdirSync, writeFileSync } from 'fs';
+import path from 'path';
+
+const CRC_TABLE = (() => {
+ const table = new Uint32Array(256);
+ for (let i = 0; i < 256; i++) {
+ let c = i;
+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
+ table[i] = c >>> 0;
+ }
+ return table;
+})();
+
+function crc32(buf) {
+ let c = 0xffffffff;
+ for (let i = 0; i < buf.length; i++) c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8);
+ return (c ^ 0xffffffff) >>> 0;
+}
+
+// 1980-01-01 00:00:00 in DOS date/time — the epoch of the format itself, and the
+// conventional stand-in for "no meaningful time" in reproducible archives.
+const DOS_TIME = 0;
+const DOS_DATE = 0x0021;
+
+/**
+ * Build a ZIP archive holding `entries` ({ name, data }), each deflated.
+ *
+ * @param {ReadonlyArray<{name: string, data: Buffer}>} entries
+ * @returns {Buffer}
+ */
+export function makeZip(entries) {
+ const locals = [];
+ const centrals = [];
+ let offset = 0;
+
+ for (const entry of entries) {
+ const name = Buffer.from(entry.name, 'utf8');
+ const compressed = deflateRawSync(entry.data, { level: 9 });
+ const crc = crc32(entry.data);
+
+ const local = Buffer.alloc(30);
+ local.writeUInt32LE(0x04034b50, 0);
+ local.writeUInt16LE(20, 4); // version needed
+ local.writeUInt16LE(0x0800, 6); // UTF-8 names
+ local.writeUInt16LE(8, 8); // deflate
+ local.writeUInt16LE(DOS_TIME, 10);
+ local.writeUInt16LE(DOS_DATE, 12);
+ local.writeUInt32LE(crc, 14);
+ local.writeUInt32LE(compressed.length, 18);
+ local.writeUInt32LE(entry.data.length, 22);
+ local.writeUInt16LE(name.length, 26);
+ local.writeUInt16LE(0, 28); // no extra field
+ locals.push(local, name, compressed);
+
+ const central = Buffer.alloc(46);
+ central.writeUInt32LE(0x02014b50, 0);
+ central.writeUInt16LE(20, 4); // version made by
+ central.writeUInt16LE(20, 6); // version needed
+ central.writeUInt16LE(0x0800, 8);
+ central.writeUInt16LE(8, 10);
+ central.writeUInt16LE(DOS_TIME, 12);
+ central.writeUInt16LE(DOS_DATE, 14);
+ central.writeUInt32LE(crc, 16);
+ central.writeUInt32LE(compressed.length, 20);
+ central.writeUInt32LE(entry.data.length, 24);
+ central.writeUInt16LE(name.length, 28);
+ central.writeUInt16LE(0, 30); // extra
+ central.writeUInt16LE(0, 32); // comment
+ central.writeUInt16LE(0, 34); // disk
+ central.writeUInt16LE(0, 36); // internal attrs
+ central.writeUInt32LE(0, 38); // external attrs
+ central.writeUInt32LE(offset, 42);
+ centrals.push(central, name);
+
+ offset += local.length + name.length + compressed.length;
+ }
+
+ const centralSize = centrals.reduce((n, b) => n + b.length, 0);
+ const end = Buffer.alloc(22);
+ end.writeUInt32LE(0x06054b50, 0);
+ end.writeUInt16LE(0, 4); // this disk
+ end.writeUInt16LE(0, 6); // disk with central dir
+ end.writeUInt16LE(entries.length, 8);
+ end.writeUInt16LE(entries.length, 10);
+ end.writeUInt32LE(centralSize, 12);
+ end.writeUInt32LE(offset, 16);
+ end.writeUInt16LE(0, 20); // no archive comment
+
+ return Buffer.concat([...locals, ...centrals, end]);
+}
+
+/**
+ * Every file under `dir` as zip entries, named relative to it (forward slashes,
+ * sorted). Directories are implied by the names — a reader creates them — so no
+ * directory entries are written.
+ *
+ * @param {string} dir
+ * @param {string} [prefix] Path to prepend inside the archive.
+ * @returns {Array<{name: string, data: Buffer}>}
+ */
+export function zipTree(dir, prefix = '') {
+ const out = [];
+ const walk = (abs, rel) => {
+ for (const e of readdirSync(abs, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
+ const child = path.join(abs, e.name);
+ const name = rel ? `${rel}/${e.name}` : e.name;
+ if (e.isDirectory()) walk(child, name);
+ else if (e.isFile()) out.push({ name, data: readFileSync(child) });
+ }
+ };
+ walk(dir, prefix);
+ return out;
+}
+
+/**
+ * Read an archive's entries, through its central directory (the authority on what
+ * an archive contains — trailing local headers may be stale).
+ *
+ * @param {Buffer} buf
+ * @returns {Array<{name: string, data: Buffer}>}
+ */
+export function readZip(buf) {
+ // The end-of-central-directory record is last, but a comment may follow it.
+ let eocd = -1;
+ for (let i = buf.length - 22; i >= 0 && i >= buf.length - 22 - 0xffff; i--) {
+ if (buf.readUInt32LE(i) === 0x06054b50) { eocd = i; break; }
+ }
+ if (eocd < 0) throw new Error('not a ZIP archive (no end-of-central-directory record)');
+
+ const count = buf.readUInt16LE(eocd + 10);
+ let p = buf.readUInt32LE(eocd + 16);
+ const out = [];
+ for (let i = 0; i < count; i++) {
+ if (buf.readUInt32LE(p) !== 0x02014b50) throw new Error('corrupt ZIP central directory');
+ const method = buf.readUInt16LE(p + 10);
+ const crc = buf.readUInt32LE(p + 16);
+ const compressedSize = buf.readUInt32LE(p + 20);
+ const size = buf.readUInt32LE(p + 24);
+ const nameLen = buf.readUInt16LE(p + 28);
+ const extraLen = buf.readUInt16LE(p + 30);
+ const commentLen = buf.readUInt16LE(p + 32);
+ const local = buf.readUInt32LE(p + 42);
+ const name = buf.toString('utf8', p + 46, p + 46 + nameLen);
+ p += 46 + nameLen + extraLen + commentLen;
+
+ if (buf.readUInt32LE(local) !== 0x04034b50) throw new Error(`corrupt ZIP entry: ${name}`);
+ const dataAt = local + 30 + buf.readUInt16LE(local + 26) + buf.readUInt16LE(local + 28);
+ const raw = buf.subarray(dataAt, dataAt + compressedSize);
+ const data = method === 0 ? Buffer.from(raw)
+ : method === 8 ? inflateRawSync(raw)
+ : (() => { throw new Error(`unsupported ZIP compression ${method} in ${name}`); })();
+ if (data.length !== size || crc32(data) !== crc) throw new Error(`corrupt ZIP entry: ${name}`);
+ out.push({ name, data });
+ }
+ return out;
+}
+
+/**
+ * Extract an archive into `destDir`.
+ *
+ * Entry names are checked before anything is written: an archive is untrusted
+ * input (it can arrive over the network or from a file someone was handed), and
+ * `../` in a name is how a zip writes outside the directory it was extracted to.
+ *
+ * @param {Buffer} buf
+ * @param {string} destDir
+ * @returns {string[]} The relative paths written.
+ */
+export function extractZip(buf, destDir) {
+ const entries = readZip(buf);
+ const root = path.resolve(destDir);
+ for (const { name } of entries) {
+ const target = path.resolve(root, name);
+ if (name.startsWith('/') || name.includes('\\') || (target !== root && !target.startsWith(root + path.sep))) {
+ throw new Error(`unsafe ZIP entry name: ${name}`);
+ }
+ }
+ for (const { name, data } of entries) {
+ const target = path.resolve(root, name);
+ mkdirSync(path.dirname(target), { recursive: true });
+ writeFileSync(target, data);
+ }
+ return entries.map((e) => e.name);
+}
diff --git a/desktop/electron/exportPlayable.ts b/desktop/electron/exportPlayable.ts
index 99c7140e4..de3f344f4 100644
--- a/desktop/electron/exportPlayable.ts
+++ b/desktop/electron/exportPlayable.ts
@@ -25,7 +25,7 @@ import type { OnExportProgress } from './exportProgress';
import { esengineAlias } from './esengineResolve';
import type { ScreenOrientation } from './orientationHtml';
import { genericPlayableProfile, playableAdInjection, type PlayableAdProfile } from './playableAdProfile';
-import { makeZip } from './zipWriter';
+import { makeZip } from '../../build-tools/utils/zip.js';
import {
sceneUsesPhysics, detectSpineVersion, detectSpineVersionJson,
spineModuleId, SIDE_MODULE_FILE, type SpineVersion,
diff --git a/desktop/electron/zipWriter.ts b/desktop/electron/zipWriter.ts
deleted file mode 100644
index 42e1c76cd..000000000
--- a/desktop/electron/zipWriter.ts
+++ /dev/null
@@ -1,105 +0,0 @@
-// SPDX-License-Identifier: Apache-2.0
-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-/**
- * @file A minimal ZIP writer, for the ad networks that upload a ZIP rather than a
- * bare HTML file (Google App campaigns).
- *
- * Written rather than depended on: what a playable needs is one deflated
- * entry at the archive root, which is the simplest case the format has — no
- * directories, no zip64, no encryption. A dependency for that would be more
- * surface than the format.
- *
- * Deterministic by construction: entries carry a FIXED DOS timestamp, so the
- * same input always produces byte-identical output. An export that changes
- * only because the clock moved is an export you cannot diff.
- */
-import { deflateRawSync } from 'node:zlib';
-
-export interface ZipEntry {
- /** Path inside the archive. Networks want `index.html` at the root. */
- name: string;
- data: Buffer;
-}
-
-const CRC_TABLE = (() => {
- const table = new Uint32Array(256);
- for (let i = 0; i < 256; i++) {
- let c = i;
- for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
- table[i] = c >>> 0;
- }
- return table;
-})();
-
-function crc32(buf: Buffer): number {
- let c = 0xffffffff;
- for (let i = 0; i < buf.length; i++) c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8);
- return (c ^ 0xffffffff) >>> 0;
-}
-
-// 1980-01-01 00:00:00 in DOS date/time — the epoch of the format itself, and the
-// conventional stand-in for "no meaningful time" in reproducible archives.
-const DOS_TIME = 0;
-const DOS_DATE = 0x0021;
-
-/** Build a ZIP archive holding `entries`, each deflated at the archive root. */
-export function makeZip(entries: readonly ZipEntry[]): Buffer {
- const locals: Buffer[] = [];
- const centrals: Buffer[] = [];
- let offset = 0;
-
- for (const entry of entries) {
- const name = Buffer.from(entry.name, 'utf8');
- const compressed = deflateRawSync(entry.data, { level: 9 });
- const crc = crc32(entry.data);
-
- const local = Buffer.alloc(30);
- local.writeUInt32LE(0x04034b50, 0);
- local.writeUInt16LE(20, 4); // version needed
- local.writeUInt16LE(0x0800, 6); // UTF-8 names
- local.writeUInt16LE(8, 8); // deflate
- local.writeUInt16LE(DOS_TIME, 10);
- local.writeUInt16LE(DOS_DATE, 12);
- local.writeUInt32LE(crc, 14);
- local.writeUInt32LE(compressed.length, 18);
- local.writeUInt32LE(entry.data.length, 22);
- local.writeUInt16LE(name.length, 26);
- local.writeUInt16LE(0, 28); // no extra field
- locals.push(local, name, compressed);
-
- const central = Buffer.alloc(46);
- central.writeUInt32LE(0x02014b50, 0);
- central.writeUInt16LE(20, 4); // version made by
- central.writeUInt16LE(20, 6); // version needed
- central.writeUInt16LE(0x0800, 8);
- central.writeUInt16LE(8, 10);
- central.writeUInt16LE(DOS_TIME, 12);
- central.writeUInt16LE(DOS_DATE, 14);
- central.writeUInt32LE(crc, 16);
- central.writeUInt32LE(compressed.length, 20);
- central.writeUInt32LE(entry.data.length, 24);
- central.writeUInt16LE(name.length, 28);
- central.writeUInt16LE(0, 30); // extra
- central.writeUInt16LE(0, 32); // comment
- central.writeUInt16LE(0, 34); // disk
- central.writeUInt16LE(0, 36); // internal attrs
- central.writeUInt32LE(0, 38); // external attrs
- central.writeUInt32LE(offset, 42);
- centrals.push(central, name);
-
- offset += local.length + name.length + compressed.length;
- }
-
- const centralSize = centrals.reduce((n, b) => n + b.length, 0);
- const end = Buffer.alloc(22);
- end.writeUInt32LE(0x06054b50, 0);
- end.writeUInt16LE(0, 4); // this disk
- end.writeUInt16LE(0, 6); // disk with central dir
- end.writeUInt16LE(entries.length, 8);
- end.writeUInt16LE(entries.length, 10);
- end.writeUInt32LE(centralSize, 12);
- end.writeUInt32LE(offset, 16);
- end.writeUInt16LE(0, 20); // no archive comment
-
- return Buffer.concat([...locals, ...centrals, end]);
-}
diff --git a/desktop/tests/zip-writer.test.ts b/desktop/tests/zip-writer.test.ts
deleted file mode 100644
index 4e07c0562..000000000
--- a/desktop/tests/zip-writer.test.ts
+++ /dev/null
@@ -1,68 +0,0 @@
-// SPDX-License-Identifier: Apache-2.0
-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-/**
- * @file The ZIP writer, checked against a REAL unzip rather than against a reader
- * of our own — a hand-rolled archive that only our own code can open is worth
- * nothing, since the thing that opens it for real is an ad network's pipeline.
- */
-import { describe, it, expect, beforeAll, afterAll } from 'vitest';
-import { mkdtempSync, rmSync, writeFileSync, readFileSync } from 'node:fs';
-import { execFileSync } from 'node:child_process';
-import { tmpdir } from 'node:os';
-import path from 'node:path';
-import { makeZip } from '../electron/zipWriter';
-
-let dir: string;
-/** `unzip` ships with macOS and most Linux; skip rather than fail where it doesn't. */
-let hasUnzip = true;
-
-beforeAll(() => {
- dir = mkdtempSync(path.join(tmpdir(), 'es-zip-'));
- try {
- execFileSync('unzip', ['-v'], { stdio: 'ignore' });
- } catch {
- hasUnzip = false;
- }
-});
-afterAll(() => rmSync(dir, { recursive: true, force: true }));
-
-describe('makeZip', () => {
- it('writes an archive a real unzip accepts, with the content intact', () => {
- if (!hasUnzip) return;
- // Repetitive enough that deflate must actually be exercised (a stored-only
- // archive would pass a naive round-trip but not prove the deflate path).
- const html = `<!doctype html><html><body>${'<span>playable</span>'.repeat(500)}</body></html>`;
- const zip = makeZip([{ name: 'index.html', data: Buffer.from(html, 'utf8') }]);
- const file = path.join(dir, 'playable.zip');
- writeFileSync(file, zip);
-
- // -t verifies every entry's CRC — the check that catches a malformed header.
- expect(execFileSync('unzip', ['-t', file], { encoding: 'utf8' })).toContain('No errors detected');
- // The entry must sit at the archive ROOT: networks look for index.html there.
- expect(execFileSync('unzip', ['-Z1', file], { encoding: 'utf8' }).trim()).toBe('index.html');
- expect(execFileSync('unzip', ['-p', file, 'index.html'], { encoding: 'utf8', maxBuffer: 1 << 24 })).toBe(html);
- // Deflate actually happened.
- expect(zip.length).toBeLessThan(html.length / 2);
- });
-
- it('is deterministic, so an export only changes when its content does', () => {
- const data = Buffer.from('same bytes', 'utf8');
- const a = makeZip([{ name: 'index.html', data }]);
- const b = makeZip([{ name: 'index.html', data }]);
- expect(a.equals(b)).toBe(true);
- });
-
- it('round-trips binary content and multiple entries', () => {
- if (!hasUnzip) return;
- const bin = Buffer.from(Array.from({ length: 1024 }, (_, i) => i & 0xff));
- const zip = makeZip([
- { name: 'index.html', data: Buffer.from('<html></html>', 'utf8') },
- { name: 'payload.bin', data: bin },
- ]);
- const file = path.join(dir, 'multi.zip');
- writeFileSync(file, zip);
- expect(execFileSync('unzip', ['-t', file], { encoding: 'utf8' })).toContain('No errors detected');
- execFileSync('unzip', ['-o', file, '-d', path.join(dir, 'out')], { stdio: 'ignore' });
- expect(readFileSync(path.join(dir, 'out', 'payload.bin')).equals(bin)).toBe(true);
- });
-});
diff --git a/desktop/tests/zip.test.ts b/desktop/tests/zip.test.ts
new file mode 100644
index 000000000..b5b2d5087
--- /dev/null
+++ b/desktop/tests/zip.test.ts
@@ -0,0 +1,132 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The repo's ZIP implementation.
+ *
+ * The writer is checked against a REAL unzip rather than against a reader of
+ * our own — a hand-rolled archive that only our own code can open is worth
+ * nothing, since the thing that opens it for real is an ad network's
+ * pipeline. The reader is checked against a real `zip` for the same reason,
+ * and on what it must REFUSE: it opens runtime templates, which arrive as
+ * files someone was handed.
+ */
+import { describe, it, expect, beforeAll, afterAll } from 'vitest';
+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync, existsSync } from 'node:fs';
+import { execFileSync } from 'node:child_process';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { makeZip, readZip, extractZip } from '../../build-tools/utils/zip.js';
+
+let dir: string;
+/** `unzip` ships with macOS and most Linux; skip rather than fail where it doesn't. */
+let hasUnzip = true;
+
+beforeAll(() => {
+ dir = mkdtempSync(path.join(tmpdir(), 'es-zip-'));
+ try {
+ execFileSync('unzip', ['-v'], { stdio: 'ignore' });
+ } catch {
+ hasUnzip = false;
+ }
+});
+afterAll(() => rmSync(dir, { recursive: true, force: true }));
+
+describe('makeZip', () => {
+ it('writes an archive a real unzip accepts, with the content intact', () => {
+ if (!hasUnzip) return;
+ // Repetitive enough that deflate must actually be exercised (a stored-only
+ // archive would pass a naive round-trip but not prove the deflate path).
+ const html = `<!doctype html><html><body>${'<span>playable</span>'.repeat(500)}</body></html>`;
+ const zip = makeZip([{ name: 'index.html', data: Buffer.from(html, 'utf8') }]);
+ const file = path.join(dir, 'playable.zip');
+ writeFileSync(file, zip);
+
+ // -t verifies every entry's CRC — the check that catches a malformed header.
+ expect(execFileSync('unzip', ['-t', file], { encoding: 'utf8' })).toContain('No errors detected');
+ // The entry must sit at the archive ROOT: networks look for index.html there.
+ expect(execFileSync('unzip', ['-Z1', file], { encoding: 'utf8' }).trim()).toBe('index.html');
+ expect(execFileSync('unzip', ['-p', file, 'index.html'], { encoding: 'utf8', maxBuffer: 1 << 24 })).toBe(html);
+ // Deflate actually happened.
+ expect(zip.length).toBeLessThan(html.length / 2);
+ });
+
+ it('is deterministic, so an export only changes when its content does', () => {
+ const data = Buffer.from('same bytes', 'utf8');
+ const a = makeZip([{ name: 'index.html', data }]);
+ const b = makeZip([{ name: 'index.html', data }]);
+ expect(a.equals(b)).toBe(true);
+ });
+
+ it('round-trips binary content and multiple entries', () => {
+ if (!hasUnzip) return;
+ const bin = Buffer.from(Array.from({ length: 1024 }, (_, i) => i & 0xff));
+ const zip = makeZip([
+ { name: 'index.html', data: Buffer.from('<html></html>', 'utf8') },
+ { name: 'payload.bin', data: bin },
+ ]);
+ const file = path.join(dir, 'multi.zip');
+ writeFileSync(file, zip);
+ expect(execFileSync('unzip', ['-t', file], { encoding: 'utf8' })).toContain('No errors detected');
+ execFileSync('unzip', ['-o', file, '-d', path.join(dir, 'out')], { stdio: 'ignore' });
+ expect(readFileSync(path.join(dir, 'out', 'payload.bin')).equals(bin)).toBe(true);
+ });
+});
+
+describe('readZip / extractZip', () => {
+ it('reads an archive a real `zip` produced, deflated and stored alike', () => {
+ let hasZip = true;
+ try {
+ execFileSync('zip', ['-v'], { stdio: 'ignore' });
+ } catch {
+ hasZip = false;
+ }
+ if (!hasZip) return;
+
+ const src = path.join(dir, 'src');
+ mkdirSync(path.join(src, 'nested'), { recursive: true });
+ const text = 'estella'.repeat(400);
+ writeFileSync(path.join(src, 'nested', 'a.txt'), text);
+ writeFileSync(path.join(src, 'b.bin'), Buffer.from([0, 1, 2, 250, 251]));
+ const file = path.join(dir, 'real.zip');
+ // -0 stores the second copy, so both compression methods are exercised.
+ execFileSync('zip', ['-r', file, '.'], { cwd: src, stdio: 'ignore' });
+ execFileSync('zip', ['-0', file, 'b.bin'], { cwd: src, stdio: 'ignore' });
+
+ const entries = readZip(readFileSync(file));
+ const byName = new Map(entries.map((e) => [e.name, e.data]));
+ expect(byName.get('nested/a.txt')?.toString('utf8')).toBe(text);
+ expect([...byName.get('b.bin')!]).toEqual([0, 1, 2, 250, 251]);
+ });
+
+ it('round-trips what makeZip wrote, into a directory tree', () => {
+ const zip = makeZip([
+ { name: 'template.json', data: Buffer.from('{}') },
+ { name: 'App/main.m', data: Buffer.from('int main(){}') },
+ ]);
+ const out = path.join(dir, 'extracted');
+
+ expect(extractZip(zip, out).sort()).toEqual(['App/main.m', 'template.json']);
+ expect(readFileSync(path.join(out, 'App', 'main.m'), 'utf8')).toBe('int main(){}');
+ });
+
+ it('refuses to write outside the destination, before writing anything', () => {
+ const out = path.join(dir, 'guarded');
+ const zip = makeZip([
+ { name: 'ok.txt', data: Buffer.from('ok') },
+ { name: '../escaped.txt', data: Buffer.from('nope') },
+ ]);
+
+ expect(() => extractZip(zip, out)).toThrow(/unsafe/);
+ // The safe entry was not written either: the names are checked as a set.
+ expect(existsSync(path.join(out, 'ok.txt'))).toBe(false);
+ expect(existsSync(path.join(dir, 'escaped.txt'))).toBe(false);
+ });
+
+ it('rejects a corrupt entry rather than handing back wrong bytes', () => {
+ const zip = makeZip([{ name: 'a.txt', data: Buffer.from('hello world') }]);
+ // Flip a byte in the compressed payload; the CRC in the header no longer matches.
+ zip[45] ^= 0xff;
+
+ expect(() => readZip(zip)).toThrow();
+ });
+});