@stll/docx-core 0.39.2 → 0.40.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/archive-yBR7X-Qc.js +456 -0
- package/dist/errors-Dm3jsb5q.d.ts +57 -0
- package/dist/format-DXPXB02u.js +378 -0
- package/dist/index.d.ts +0 -7
- package/dist/index.js +106 -193
- package/dist/zip/archive.d.ts +114 -0
- package/dist/zip/archive.js +3 -0
- package/dist/zip/stream.d.ts +30 -0
- package/dist/zip/stream.js +117 -0
- package/package.json +10 -6
- package/dist/zip/writeZipPart.d.ts +0 -10
- package/dist/zip/writeZipPart.js +0 -16
|
@@ -0,0 +1,456 @@
|
|
|
1
|
+
import { _ as ZipError, a as UINT16_SENTINEL, d as encodeEndOfCentralDirectory, f as encodeEntryName, g as toDosDateTime, h as isSafeZipPath, l as encodeCentralHeader, m as fromDosDateTime, p as encodeLocalHeader, r as FIXED_DOS_DATE_TIME, v as copyBytes, y as platformZipCodec } from "./format-DXPXB02u.js";
|
|
2
|
+
import { Result } from "better-result";
|
|
3
|
+
import { decodeText, encodeUtf8 } from "@stll/utf8-boundaries";
|
|
4
|
+
// src/zip/read.ts
|
|
5
|
+
/**
|
|
6
|
+
* Central-directory reading with every size an archive states about itself
|
|
7
|
+
* checked before anything is inflated.
|
|
8
|
+
*
|
|
9
|
+
* An archive is a set of claims written by whoever produced it: the entry
|
|
10
|
+
* count, each entry's sizes and offsets, the names. The reader accepts the
|
|
11
|
+
* archive only when the end record, the central directory and every local
|
|
12
|
+
* header agree, the entries occupy disjoint byte ranges inside the archive,
|
|
13
|
+
* and the declared sizes fit the limits. Inflation later stops at the
|
|
14
|
+
* declared size, so a size that passed here bounds every read.
|
|
15
|
+
*/
|
|
16
|
+
const MEBIBYTE = 1048576;
|
|
17
|
+
/**
|
|
18
|
+
* Defaults sized for office packages. A DEFLATE stream tops out near 1032:1;
|
|
19
|
+
* markup in real documents stays under 75:1.
|
|
20
|
+
*/
|
|
21
|
+
const ZIP_DEFAULT_READ_LIMITS = {
|
|
22
|
+
maxEntries: 1e4,
|
|
23
|
+
maxEntryBytes: 256 * MEBIBYTE,
|
|
24
|
+
maxTotalBytes: 512 * MEBIBYTE,
|
|
25
|
+
maxCompressionRatio: 200,
|
|
26
|
+
compressionRatioGraceBytes: 4 * MEBIBYTE
|
|
27
|
+
};
|
|
28
|
+
const fail = (reason, message, path) => Result.err(path === void 0 ? new ZipError({
|
|
29
|
+
message,
|
|
30
|
+
reason
|
|
31
|
+
}) : new ZipError({
|
|
32
|
+
message,
|
|
33
|
+
reason,
|
|
34
|
+
path
|
|
35
|
+
}));
|
|
36
|
+
const malformed = (message) => fail("malformed", message);
|
|
37
|
+
const toSafeNumber = (value) => value <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(value) : null;
|
|
38
|
+
const findEndRecord = (bytes, view) => {
|
|
39
|
+
const earliest = Math.max(0, bytes.byteLength - 22 - UINT16_SENTINEL);
|
|
40
|
+
for (let offset = bytes.byteLength - 22; offset >= earliest; offset--) if (view.getUint32(offset, true) === 101010256 && offset + 22 + view.getUint16(offset + 20, true) === bytes.byteLength) return offset;
|
|
41
|
+
return -1;
|
|
42
|
+
};
|
|
43
|
+
const readZip64Directory = (view, end) => {
|
|
44
|
+
const locator = end - 20;
|
|
45
|
+
if (locator < 56 || view.getUint32(locator, true) !== 117853008) return malformed("Zip64 end locator is missing");
|
|
46
|
+
if (view.getUint32(locator + 4, true) !== 0 || view.getUint32(locator + 16, true) !== 1) return fail("unsupported", "Multi-disk archives are not supported");
|
|
47
|
+
const record = toSafeNumber(view.getBigUint64(locator + 8, true));
|
|
48
|
+
if (record === null || record + 56 !== locator || view.getUint32(record, true) !== 101075792 || view.getBigUint64(record + 4, true) !== BigInt(44)) return malformed("Zip64 end record is malformed");
|
|
49
|
+
if (view.getUint32(record + 16, true) !== 0 || view.getUint32(record + 20, true) !== 0) return fail("unsupported", "Multi-disk archives are not supported");
|
|
50
|
+
const diskCount = view.getBigUint64(record + 24, true);
|
|
51
|
+
const count = view.getBigUint64(record + 32, true);
|
|
52
|
+
const size = toSafeNumber(view.getBigUint64(record + 40, true));
|
|
53
|
+
const offset = toSafeNumber(view.getBigUint64(record + 48, true));
|
|
54
|
+
const entryCount = toSafeNumber(count);
|
|
55
|
+
if (diskCount !== count || size === null || offset === null || entryCount === null || offset + size !== record) return malformed("Zip64 end record disagrees with the central directory");
|
|
56
|
+
return Result.ok({
|
|
57
|
+
count: entryCount,
|
|
58
|
+
offset,
|
|
59
|
+
end: record
|
|
60
|
+
});
|
|
61
|
+
};
|
|
62
|
+
const readDirectory = (bytes, view) => {
|
|
63
|
+
const end = findEndRecord(bytes, view);
|
|
64
|
+
if (end === -1) return malformed("End of central directory is missing");
|
|
65
|
+
if (view.getUint16(end + 4, true) !== 0 || view.getUint16(end + 6, true) !== 0) return fail("unsupported", "Multi-disk archives are not supported");
|
|
66
|
+
const diskCount = view.getUint16(end + 8, true);
|
|
67
|
+
const count = view.getUint16(end + 10, true);
|
|
68
|
+
const size = view.getUint32(end + 12, true);
|
|
69
|
+
const offset = view.getUint32(end + 16, true);
|
|
70
|
+
const deferred = count === 65535 || diskCount === 65535 || size === 4294967295 || offset === 4294967295;
|
|
71
|
+
const hasLocator = end >= 20 && view.getUint32(end - 20, true) === 117853008;
|
|
72
|
+
if (deferred || hasLocator) {
|
|
73
|
+
const zip64 = readZip64Directory(view, end);
|
|
74
|
+
if (Result.isError(zip64)) return zip64;
|
|
75
|
+
const directory = zip64.value;
|
|
76
|
+
if (count !== 65535 && count !== directory.count || offset !== 4294967295 && offset !== directory.offset || size !== 4294967295 && size !== directory.end - directory.offset) return malformed("End records disagree");
|
|
77
|
+
return Result.ok(directory);
|
|
78
|
+
}
|
|
79
|
+
if (diskCount !== count || offset + size !== end) return malformed("End record disagrees with the central directory");
|
|
80
|
+
return Result.ok({
|
|
81
|
+
count,
|
|
82
|
+
offset,
|
|
83
|
+
end
|
|
84
|
+
});
|
|
85
|
+
};
|
|
86
|
+
const readZip64Extra = (view, start, end, fields) => {
|
|
87
|
+
let cursor = start;
|
|
88
|
+
let seen = false;
|
|
89
|
+
const resolved = { ...fields };
|
|
90
|
+
while (cursor < end) {
|
|
91
|
+
if (cursor + 4 > end) return malformed("Extra field is truncated");
|
|
92
|
+
const tag = view.getUint16(cursor, true);
|
|
93
|
+
const length = view.getUint16(cursor + 2, true);
|
|
94
|
+
const payload = cursor + 4;
|
|
95
|
+
if (payload + length > end) return malformed("Extra field is truncated");
|
|
96
|
+
if (tag === 1) {
|
|
97
|
+
if (seen) return malformed("Duplicate Zip64 extra field");
|
|
98
|
+
seen = true;
|
|
99
|
+
let field = payload;
|
|
100
|
+
for (const key of [
|
|
101
|
+
"uncompressedSize",
|
|
102
|
+
"compressedSize",
|
|
103
|
+
"localOffset"
|
|
104
|
+
]) {
|
|
105
|
+
if (fields[key] !== 4294967295) continue;
|
|
106
|
+
if (field + 8 > payload + length) return malformed("Zip64 extra field is truncated");
|
|
107
|
+
const value = toSafeNumber(view.getBigUint64(field, true));
|
|
108
|
+
if (value === null) return malformed("Zip64 size is out of range");
|
|
109
|
+
resolved[key] = value;
|
|
110
|
+
field += 8;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
cursor = payload + length;
|
|
114
|
+
}
|
|
115
|
+
if (!seen && (fields.uncompressedSize === 4294967295 || fields.compressedSize === 4294967295 || fields.localOffset === 4294967295)) return malformed("Zip64 extra field is missing");
|
|
116
|
+
return Result.ok(resolved);
|
|
117
|
+
};
|
|
118
|
+
const decodeName = (name) => {
|
|
119
|
+
const decoded = Result.try(() => decodeText(name, { fatal: true }));
|
|
120
|
+
return Result.isOk(decoded) ? decoded.value : null;
|
|
121
|
+
};
|
|
122
|
+
const LOCAL_FLAGS_THAT_MUST_AGREE = 9;
|
|
123
|
+
const bytesEqual = (left, right) => left.byteLength === right.byteLength && left.every((byte, index) => byte === right[index]);
|
|
124
|
+
const exceedsRatio = (inflated, compressed, limits) => inflated > limits.compressionRatioGraceBytes && inflated > compressed * limits.maxCompressionRatio;
|
|
125
|
+
/**
|
|
126
|
+
* Read and validate the archive's directory. Nothing is inflated; the
|
|
127
|
+
* returned entries carry the sizes every later inflation is held to.
|
|
128
|
+
*/
|
|
129
|
+
const readEntries = (bytes, { limits, isCompressionRatioExempt }) => {
|
|
130
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
131
|
+
const directory = readDirectory(bytes, view);
|
|
132
|
+
if (Result.isError(directory)) return directory;
|
|
133
|
+
const { count, offset: directoryStart, end: directoryEnd } = directory.value;
|
|
134
|
+
if (count > limits.maxEntries) return fail("too-many-entries", "Archive declares too many entries");
|
|
135
|
+
const entries = [];
|
|
136
|
+
const names = /* @__PURE__ */ new Set();
|
|
137
|
+
const spans = [];
|
|
138
|
+
let totalBytes = 0;
|
|
139
|
+
let cursor = directoryStart;
|
|
140
|
+
for (let index = 0; index < count; index++) {
|
|
141
|
+
if (cursor + 46 > directoryEnd || view.getUint32(cursor, true) !== 33639248) return malformed("Central directory record is malformed");
|
|
142
|
+
const flags = view.getUint16(cursor + 8, true);
|
|
143
|
+
const method = view.getUint16(cursor + 10, true);
|
|
144
|
+
const nameLength = view.getUint16(cursor + 28, true);
|
|
145
|
+
const extraLength = view.getUint16(cursor + 30, true);
|
|
146
|
+
const commentLength = view.getUint16(cursor + 32, true);
|
|
147
|
+
const nameStart = cursor + 46;
|
|
148
|
+
const extraStart = nameStart + nameLength;
|
|
149
|
+
const next = extraStart + extraLength + commentLength;
|
|
150
|
+
if (next > directoryEnd || nameLength === 0) return malformed("Central directory record is malformed");
|
|
151
|
+
if (view.getUint16(cursor + 34, true) !== 0) return fail("unsupported", "Multi-disk archives are not supported");
|
|
152
|
+
const name = bytes.subarray(nameStart, extraStart);
|
|
153
|
+
const path = decodeName(name);
|
|
154
|
+
if (path === null || !isSafeZipPath(path)) return fail("invalid-entry-name", "Archive contains an unsafe entry name");
|
|
155
|
+
if (names.has(path)) return fail("duplicate-entry", "Archive names an entry twice", path);
|
|
156
|
+
names.add(path);
|
|
157
|
+
if ((flags & 65) !== 0) return fail("unsupported", "Encrypted entries are not supported", path);
|
|
158
|
+
if (method !== 0 && method !== 8) return fail("unsupported", "Unsupported compression method", path);
|
|
159
|
+
const sizes = readZip64Extra(view, extraStart, extraStart + extraLength, {
|
|
160
|
+
uncompressedSize: view.getUint32(cursor + 24, true),
|
|
161
|
+
compressedSize: view.getUint32(cursor + 20, true),
|
|
162
|
+
localOffset: view.getUint32(cursor + 42, true)
|
|
163
|
+
});
|
|
164
|
+
if (Result.isError(sizes)) return sizes;
|
|
165
|
+
const { uncompressedSize, compressedSize, localOffset } = sizes.value;
|
|
166
|
+
if (method === 0 && compressedSize !== uncompressedSize) return malformed("Stored entry sizes disagree");
|
|
167
|
+
if (localOffset + 30 > directoryStart || view.getUint32(localOffset, true) !== 67324752) return malformed("Local header is missing");
|
|
168
|
+
const localFlags = view.getUint16(localOffset + 6, true);
|
|
169
|
+
const localNameLength = view.getUint16(localOffset + 26, true);
|
|
170
|
+
const localExtraLength = view.getUint16(localOffset + 28, true);
|
|
171
|
+
const dataOffset = localOffset + 30 + localNameLength + localExtraLength;
|
|
172
|
+
if (view.getUint16(localOffset + 8, true) !== method || (localFlags & LOCAL_FLAGS_THAT_MUST_AGREE) !== (flags & LOCAL_FLAGS_THAT_MUST_AGREE) || dataOffset + compressedSize > directoryStart || !bytesEqual(bytes.subarray(localOffset + 30, localOffset + 30 + localNameLength), name)) return malformed("Local header disagrees with the central directory");
|
|
173
|
+
if ((flags & 8) === 0) {
|
|
174
|
+
const localCrc = view.getUint32(localOffset + 14, true);
|
|
175
|
+
const localCompressed = view.getUint32(localOffset + 18, true);
|
|
176
|
+
const localUncompressed = view.getUint32(localOffset + 22, true);
|
|
177
|
+
if (localCrc !== view.getUint32(cursor + 16, true) || localCompressed !== 4294967295 && localCompressed !== compressedSize || localUncompressed !== 4294967295 && localUncompressed !== uncompressedSize) return malformed("Local header disagrees with the central directory");
|
|
178
|
+
}
|
|
179
|
+
spans.push({
|
|
180
|
+
start: localOffset,
|
|
181
|
+
end: dataOffset + compressedSize
|
|
182
|
+
});
|
|
183
|
+
if (path.endsWith("/")) {
|
|
184
|
+
if (uncompressedSize !== 0) return malformed("Directory entry has data");
|
|
185
|
+
cursor = next;
|
|
186
|
+
continue;
|
|
187
|
+
}
|
|
188
|
+
if (uncompressedSize > limits.maxEntryBytes) return fail("entry-too-large", "Archive entry is too large", path);
|
|
189
|
+
totalBytes += uncompressedSize;
|
|
190
|
+
if (totalBytes > limits.maxTotalBytes) return fail("total-too-large", "Archive expands beyond its limit");
|
|
191
|
+
if (method === 8 && !isCompressionRatioExempt(path) && exceedsRatio(uncompressedSize, compressedSize, limits)) return fail("compression-ratio", "Archive entry exceeds the compression ratio limit", path);
|
|
192
|
+
entries.push({
|
|
193
|
+
path,
|
|
194
|
+
name,
|
|
195
|
+
flags,
|
|
196
|
+
method,
|
|
197
|
+
dateTime: {
|
|
198
|
+
time: view.getUint16(cursor + 12, true),
|
|
199
|
+
date: view.getUint16(cursor + 14, true)
|
|
200
|
+
},
|
|
201
|
+
crc32: view.getUint32(cursor + 16, true),
|
|
202
|
+
compressedSize,
|
|
203
|
+
uncompressedSize,
|
|
204
|
+
dataOffset
|
|
205
|
+
});
|
|
206
|
+
cursor = next;
|
|
207
|
+
}
|
|
208
|
+
if (cursor !== directoryEnd) return malformed("Central directory size disagrees with its records");
|
|
209
|
+
if (exceedsRatio(totalBytes, bytes.byteLength, limits)) return fail("compression-ratio", "Archive exceeds the compression ratio limit");
|
|
210
|
+
spans.sort((left, right) => left.start - right.start);
|
|
211
|
+
for (let index = 1; index < spans.length; index++) if (spans[index].start < spans[index - 1].end) return malformed("Archive entries overlap");
|
|
212
|
+
return Result.ok(entries);
|
|
213
|
+
};
|
|
214
|
+
// src/zip/archive.ts
|
|
215
|
+
/**
|
|
216
|
+
* An editable ZIP archive held in memory.
|
|
217
|
+
*
|
|
218
|
+
* Reading parses and validates the central directory without inflating
|
|
219
|
+
* anything; each entry inflates on demand and stops at its declared size, so
|
|
220
|
+
* the limits checked at read bound every later read. Writing passes entries
|
|
221
|
+
* that were read and not replaced through as their original compressed
|
|
222
|
+
* bytes, and deflates only what changed.
|
|
223
|
+
*/
|
|
224
|
+
const DEFAULT_DEFLATE_LEVEL = 6;
|
|
225
|
+
const toEntryBytes = (data) => {
|
|
226
|
+
if (typeof data === "string") return encodeUtf8(data);
|
|
227
|
+
if (data instanceof ArrayBuffer) return new Uint8Array(data.slice(0));
|
|
228
|
+
return copyBytes(data);
|
|
229
|
+
};
|
|
230
|
+
const toSourceBytes = (input) => input instanceof ArrayBuffer ? new Uint8Array(input) : input;
|
|
231
|
+
var ArchiveEntry = class {
|
|
232
|
+
/** Entry name, a relative forward-slash path. */
|
|
233
|
+
path;
|
|
234
|
+
/** Inflated size in bytes. */
|
|
235
|
+
size;
|
|
236
|
+
/** Entry timestamp, read as UTC with two seconds of resolution. */
|
|
237
|
+
modified;
|
|
238
|
+
#stored;
|
|
239
|
+
#source;
|
|
240
|
+
#codec;
|
|
241
|
+
constructor(path, stored, archive) {
|
|
242
|
+
this.path = path;
|
|
243
|
+
this.size = stored.type === "source" ? stored.entry.uncompressedSize : stored.bytes.byteLength;
|
|
244
|
+
this.modified = fromDosDateTime(stored.type === "source" ? stored.entry.dateTime : stored.dateTime);
|
|
245
|
+
this.#stored = stored;
|
|
246
|
+
this.#source = archive.source;
|
|
247
|
+
this.#codec = archive.codec;
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* The entry's bytes. A read entry inflates at most its declared size and
|
|
251
|
+
* must match its CRC-32; anything else rejects with a {@link ZipError}.
|
|
252
|
+
*/
|
|
253
|
+
async bytes() {
|
|
254
|
+
const stored = this.#stored;
|
|
255
|
+
if (stored.type === "data") return copyBytes(stored.bytes);
|
|
256
|
+
const { entry } = stored;
|
|
257
|
+
const raw = this.#source.subarray(entry.dataOffset, entry.dataOffset + entry.compressedSize);
|
|
258
|
+
let bytes;
|
|
259
|
+
if (entry.method === 0) bytes = copyBytes(raw);
|
|
260
|
+
else {
|
|
261
|
+
const outcome = await this.#codec.inflate(raw, {
|
|
262
|
+
size: entry.uncompressedSize,
|
|
263
|
+
crc32: entry.crc32
|
|
264
|
+
});
|
|
265
|
+
if (outcome.type === "overflow") throw new ZipError({
|
|
266
|
+
message: "Archive entry inflates past its declared size",
|
|
267
|
+
reason: "declared-size-exceeded",
|
|
268
|
+
path: entry.path
|
|
269
|
+
});
|
|
270
|
+
if (outcome.type === "corrupt") throw new ZipError({
|
|
271
|
+
message: "Archive entry data is corrupt",
|
|
272
|
+
reason: "corrupt-entry",
|
|
273
|
+
path: entry.path,
|
|
274
|
+
cause: outcome.cause
|
|
275
|
+
});
|
|
276
|
+
({bytes} = outcome);
|
|
277
|
+
}
|
|
278
|
+
if (this.#codec.crc32(bytes) !== entry.crc32) throw new ZipError({
|
|
279
|
+
message: "Archive entry fails its CRC-32 check",
|
|
280
|
+
reason: "corrupt-entry",
|
|
281
|
+
path: entry.path
|
|
282
|
+
});
|
|
283
|
+
return bytes;
|
|
284
|
+
}
|
|
285
|
+
/** The entry decoded as UTF-8, keeping any byte-order mark. */
|
|
286
|
+
async text() {
|
|
287
|
+
return decodeText(await this.bytes(), { ignoreBOM: true });
|
|
288
|
+
}
|
|
289
|
+
/** The entry's bytes in an `ArrayBuffer` of exactly their length. */
|
|
290
|
+
async arrayBuffer() {
|
|
291
|
+
return (await this.bytes()).buffer;
|
|
292
|
+
}
|
|
293
|
+
};
|
|
294
|
+
/** An editable, bounded, in-memory ZIP archive. */
|
|
295
|
+
var ZipArchive = class ZipArchive {
|
|
296
|
+
#entries = /* @__PURE__ */ new Map();
|
|
297
|
+
#codec;
|
|
298
|
+
#source = /* @__PURE__ */ new Uint8Array(0);
|
|
299
|
+
constructor(options = {}) {
|
|
300
|
+
this.#codec = options.codec ?? platformZipCodec();
|
|
301
|
+
}
|
|
302
|
+
/**
|
|
303
|
+
* Read an archive. Rejects with a {@link ZipError} when the archive is
|
|
304
|
+
* malformed or exceeds a limit; entries inflate later, on demand. The
|
|
305
|
+
* archive keeps a reference to `input`, which must not change afterwards.
|
|
306
|
+
*/
|
|
307
|
+
static read(input, options = {}) {
|
|
308
|
+
const bytes = toSourceBytes(input);
|
|
309
|
+
const entries = readEntries(bytes, {
|
|
310
|
+
limits: {
|
|
311
|
+
...ZIP_DEFAULT_READ_LIMITS,
|
|
312
|
+
...options.limits
|
|
313
|
+
},
|
|
314
|
+
isCompressionRatioExempt: options.isCompressionRatioExempt ?? (() => false)
|
|
315
|
+
});
|
|
316
|
+
if (Result.isError(entries)) return Promise.reject(entries.error);
|
|
317
|
+
const archive = new ZipArchive(options.codec === void 0 ? {} : { codec: options.codec });
|
|
318
|
+
archive.#source = bytes;
|
|
319
|
+
for (const entry of entries.value) archive.#entries.set(entry.path, {
|
|
320
|
+
type: "source",
|
|
321
|
+
entry
|
|
322
|
+
});
|
|
323
|
+
return Promise.resolve(archive);
|
|
324
|
+
}
|
|
325
|
+
/** Entry names in archive order. */
|
|
326
|
+
paths() {
|
|
327
|
+
return [...this.#entries.keys()];
|
|
328
|
+
}
|
|
329
|
+
/** Entries in archive order. */
|
|
330
|
+
entries() {
|
|
331
|
+
return [...this.#entries].map(([path, stored]) => this.#wrap(path, stored));
|
|
332
|
+
}
|
|
333
|
+
/** Whether an entry named `path` exists. */
|
|
334
|
+
has(path) {
|
|
335
|
+
return this.#entries.has(path);
|
|
336
|
+
}
|
|
337
|
+
/** The entry named `path`, or `undefined`. */
|
|
338
|
+
entry(path) {
|
|
339
|
+
const stored = this.#entries.get(path);
|
|
340
|
+
return stored === void 0 ? void 0 : this.#wrap(path, stored);
|
|
341
|
+
}
|
|
342
|
+
/**
|
|
343
|
+
* Add or replace one entry. A replaced entry keeps its position. No parent
|
|
344
|
+
* directory entries are created.
|
|
345
|
+
*/
|
|
346
|
+
set(path, data, options = {}) {
|
|
347
|
+
if (!isSafeZipPath(path) || path.endsWith("/")) throw new ZipError({
|
|
348
|
+
message: "Archive entry name must be a relative file path",
|
|
349
|
+
reason: "invalid-entry-name",
|
|
350
|
+
path
|
|
351
|
+
});
|
|
352
|
+
this.#entries.set(path, {
|
|
353
|
+
type: "data",
|
|
354
|
+
bytes: toEntryBytes(data),
|
|
355
|
+
compression: options.compression,
|
|
356
|
+
level: options.level,
|
|
357
|
+
dateTime: options.modified === void 0 ? FIXED_DOS_DATE_TIME : toDosDateTime(options.modified)
|
|
358
|
+
});
|
|
359
|
+
}
|
|
360
|
+
/**
|
|
361
|
+
* An independent copy: later edits to either archive leave the other
|
|
362
|
+
* unchanged. Entry content is shared, never copied, since it is immutable.
|
|
363
|
+
*/
|
|
364
|
+
clone() {
|
|
365
|
+
const copy = new ZipArchive({ codec: this.#codec });
|
|
366
|
+
copy.#source = this.#source;
|
|
367
|
+
for (const [path, stored] of this.#entries) copy.#entries.set(path, stored);
|
|
368
|
+
return copy;
|
|
369
|
+
}
|
|
370
|
+
/** Remove an entry; returns whether it existed. */
|
|
371
|
+
delete(path) {
|
|
372
|
+
return this.#entries.delete(path);
|
|
373
|
+
}
|
|
374
|
+
/** Write the archive. Entries read and not replaced keep their bytes. */
|
|
375
|
+
async generate({ compression = "deflate", level = DEFAULT_DEFLATE_LEVEL, modified } = {}) {
|
|
376
|
+
const dateTime = modified === void 0 ? void 0 : toDosDateTime(modified);
|
|
377
|
+
const prepared = await Promise.all([...this.#entries].map(async ([path, stored]) => await this.#prepare({
|
|
378
|
+
path,
|
|
379
|
+
stored,
|
|
380
|
+
compression,
|
|
381
|
+
level,
|
|
382
|
+
dateTime
|
|
383
|
+
})));
|
|
384
|
+
const locals = prepared.map(({ record }) => encodeLocalHeader(record));
|
|
385
|
+
let offset = 0;
|
|
386
|
+
const offsets = [];
|
|
387
|
+
for (const [index, { payload }] of prepared.entries()) {
|
|
388
|
+
offsets.push(offset);
|
|
389
|
+
offset += locals[index].byteLength + payload.byteLength;
|
|
390
|
+
}
|
|
391
|
+
const centrals = prepared.map(({ record }, index) => encodeCentralHeader(record, offsets[index]));
|
|
392
|
+
const directorySize = centrals.reduce((total, header) => total + header.byteLength, 0);
|
|
393
|
+
const end = encodeEndOfCentralDirectory({
|
|
394
|
+
entryCount: prepared.length,
|
|
395
|
+
offset,
|
|
396
|
+
size: directorySize
|
|
397
|
+
});
|
|
398
|
+
const output = new Uint8Array(offset + directorySize + end.byteLength);
|
|
399
|
+
let cursor = 0;
|
|
400
|
+
for (const [index, { payload }] of prepared.entries()) {
|
|
401
|
+
const local = locals[index];
|
|
402
|
+
output.set(local, cursor);
|
|
403
|
+
cursor += local.byteLength;
|
|
404
|
+
output.set(payload, cursor);
|
|
405
|
+
cursor += payload.byteLength;
|
|
406
|
+
}
|
|
407
|
+
for (const header of centrals) {
|
|
408
|
+
output.set(header, cursor);
|
|
409
|
+
cursor += header.byteLength;
|
|
410
|
+
}
|
|
411
|
+
output.set(end, cursor);
|
|
412
|
+
return output;
|
|
413
|
+
}
|
|
414
|
+
#wrap(path, stored) {
|
|
415
|
+
return new ArchiveEntry(path, stored, {
|
|
416
|
+
source: this.#source,
|
|
417
|
+
codec: this.#codec
|
|
418
|
+
});
|
|
419
|
+
}
|
|
420
|
+
async #prepare({ path, stored, compression, level, dateTime }) {
|
|
421
|
+
const name = encodeEntryName(path);
|
|
422
|
+
if (stored.type === "source") {
|
|
423
|
+
const { entry } = stored;
|
|
424
|
+
return {
|
|
425
|
+
record: {
|
|
426
|
+
name: name.bytes,
|
|
427
|
+
flags: name.flags,
|
|
428
|
+
method: entry.method,
|
|
429
|
+
dateTime: dateTime ?? entry.dateTime,
|
|
430
|
+
crc32: entry.crc32,
|
|
431
|
+
compressedSize: entry.compressedSize,
|
|
432
|
+
uncompressedSize: entry.uncompressedSize,
|
|
433
|
+
directory: false
|
|
434
|
+
},
|
|
435
|
+
payload: this.#source.subarray(entry.dataOffset, entry.dataOffset + entry.compressedSize)
|
|
436
|
+
};
|
|
437
|
+
}
|
|
438
|
+
const { bytes } = stored;
|
|
439
|
+
const deflate = (stored.compression ?? compression) === "deflate";
|
|
440
|
+
const payload = deflate ? await this.#codec.deflate(bytes, stored.level ?? level) : bytes;
|
|
441
|
+
return {
|
|
442
|
+
record: {
|
|
443
|
+
name: name.bytes,
|
|
444
|
+
flags: name.flags,
|
|
445
|
+
method: deflate ? 8 : 0,
|
|
446
|
+
dateTime: dateTime ?? stored.dateTime,
|
|
447
|
+
crc32: this.#codec.crc32(bytes),
|
|
448
|
+
compressedSize: payload.byteLength,
|
|
449
|
+
uncompressedSize: bytes.byteLength,
|
|
450
|
+
directory: false
|
|
451
|
+
},
|
|
452
|
+
payload
|
|
453
|
+
};
|
|
454
|
+
}
|
|
455
|
+
};
|
|
456
|
+
export { ZIP_DEFAULT_READ_LIMITS as n, ZipArchive as t };
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { TaggedErrorClass } from "better-result";
|
|
2
|
+
/** How an inflation ended. `overflow` means the data inflates past `size`. */
|
|
3
|
+
type InflateOutcome = {
|
|
4
|
+
readonly type: "ok";
|
|
5
|
+
readonly bytes: Uint8Array<ArrayBuffer>;
|
|
6
|
+
} | {
|
|
7
|
+
readonly type: "overflow";
|
|
8
|
+
} | {
|
|
9
|
+
readonly type: "corrupt";
|
|
10
|
+
readonly cause: unknown;
|
|
11
|
+
};
|
|
12
|
+
/** What an entry declares about its inflated content. */
|
|
13
|
+
type InflateExpectation = {
|
|
14
|
+
/** Inflated size in bytes. */
|
|
15
|
+
readonly size: number;
|
|
16
|
+
/** CRC-32 of the inflated content. */
|
|
17
|
+
readonly crc32: number;
|
|
18
|
+
};
|
|
19
|
+
/** DEFLATE and CRC-32 for one platform. */
|
|
20
|
+
type ZipCodec = {
|
|
21
|
+
/**
|
|
22
|
+
* Inflate raw DEFLATE `data` that must produce exactly `expected.size`
|
|
23
|
+
* bytes. Output stops at that size, so memory never exceeds it.
|
|
24
|
+
*/
|
|
25
|
+
readonly inflate: (data: Uint8Array, expected: InflateExpectation) => Promise<InflateOutcome>;
|
|
26
|
+
/** Raw DEFLATE at `level` (0-9). */
|
|
27
|
+
readonly deflate: (data: Uint8Array, level: number) => Promise<Uint8Array<ArrayBuffer>>;
|
|
28
|
+
/** CRC-32 of `data`, continuing from `previous` when given. */
|
|
29
|
+
readonly crc32: (data: Uint8Array, previous?: number) => number;
|
|
30
|
+
};
|
|
31
|
+
/**
|
|
32
|
+
* Why an archive or entry was refused.
|
|
33
|
+
*
|
|
34
|
+
* - `malformed`: the records cannot be read, or disagree with each other.
|
|
35
|
+
* - `unsupported`: encryption, a compression method other than STORE or
|
|
36
|
+
* DEFLATE, or a multi-disk archive.
|
|
37
|
+
* - `invalid-entry-name`: an absolute, parent-relative, backslash, NUL or
|
|
38
|
+
* non-UTF-8 entry name.
|
|
39
|
+
* - `duplicate-entry`: two records name the same entry.
|
|
40
|
+
* - `too-many-entries`, `entry-too-large`, `total-too-large`,
|
|
41
|
+
* `compression-ratio`: a read limit.
|
|
42
|
+
* - `declared-size-exceeded`: entry data inflates past its declared size;
|
|
43
|
+
* inflation stops there.
|
|
44
|
+
* - `corrupt-entry`: entry data does not inflate, inflates short of its
|
|
45
|
+
* declared size, or fails its CRC-32.
|
|
46
|
+
*/
|
|
47
|
+
type ZipErrorReason = "malformed" | "unsupported" | "invalid-entry-name" | "duplicate-entry" | "too-many-entries" | "entry-too-large" | "total-too-large" | "compression-ratio" | "declared-size-exceeded" | "corrupt-entry";
|
|
48
|
+
declare const ZipErrorBase: TaggedErrorClass<"ZipError">;
|
|
49
|
+
/** A ZIP archive or entry the module refuses to read or write. */
|
|
50
|
+
declare class ZipError extends ZipErrorBase<{
|
|
51
|
+
message: string;
|
|
52
|
+
reason: ZipErrorReason;
|
|
53
|
+
/** The entry the error concerns, when it concerns one. */
|
|
54
|
+
path?: string;
|
|
55
|
+
cause?: unknown;
|
|
56
|
+
}> {}
|
|
57
|
+
export { ZipCodec as a, InflateOutcome as i, ZipErrorReason as n, InflateExpectation as r, ZipError as t };
|