sharpify-ai / src /lib /imageArchive.ts
suplo6669's picture
Publish Sharpify AI static frontend
1d8be9a verified
Raw History Blame Contribute Delete
2.3 kB
import { Zip, ZipPassThrough } from "fflate";
export type ImageArchiveEntry = {
filename: string;
blob: Blob;
};
function archiveFilename(filename: string, index: number): string {
const baseName = filename
.split(/[\\/]/)
.pop()
?.replace(/[^A-Za-z0-9._-]/g, "_")
.replace(/^\.+/, "");
const safeName = baseName || `enhanced-image-${index + 1}.png`;
return `${String(index + 1).padStart(2, "0")}-${safeName}`;
}
export async function createImageArchive(
entries: ImageArchiveEntry[],
onProgress?: (completed: number, total: number) => void,
): Promise<Blob> {
if (entries.length === 0) throw new Error("There are no completed images to archive.");
const archiveParts: BlobPart[] = [];
let archiveError: Error | null = null;
let archiveFinished = false;
const zip = new Zip((error, chunk, final) => {
if (error) {
archiveError = error;
return;
}
if (chunk) {
const buffer = new ArrayBuffer(chunk.byteLength);
new Uint8Array(buffer).set(chunk);
archiveParts.push(buffer);
}
if (final) archiveFinished = true;
});
try {
for (const [index, entry] of entries.entries()) {
const zipEntry = new ZipPassThrough(archiveFilename(entry.filename, index));
zip.add(zipEntry);
if (typeof entry.blob.stream !== "function") {
zipEntry.push(new Uint8Array(await entry.blob.arrayBuffer()), true);
} else {
const reader = entry.blob.stream().getReader();
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
zipEntry.push(value);
if (archiveError) throw archiveError;
}
zipEntry.push(new Uint8Array(0), true);
} catch (error) {
await reader.cancel(error).catch(() => undefined);
throw error;
} finally {
reader.releaseLock();
}
}
if (archiveError) throw archiveError;
onProgress?.(index + 1, entries.length);
}
zip.end();
if (archiveError) throw archiveError;
if (!archiveFinished) throw new Error("The image archive could not be finalized.");
return new Blob(archiveParts, { type: "application/zip" });
} catch (error) {
zip.terminate();
throw error;
}
}