File size: 2,304 Bytes
1d8be9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
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;
  }
}