@1337exp/taoux 0.12.0 → 0.12.1

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/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.12.1
4
+
5
+ Nothing to migrate; the behaviour of `zip` does not change.
6
+
7
+ - **`zip`: checks that other checks already cover are gone, and the tests hold the rest.** The reader no longer repeats an absolute-path test (an empty first part of the path already refuses it), a stored-size test and a running total (the size of every file is verified against its declared one, so the total is the declared total, which is judged before unpacking). New tests pin what a mutation check showed to be unguarded: an end record that sits inside the archive comment, the file count of the record, a total-size refusal that comes before the rest of the archive is touched, a declared size bigger than the data with a matching CRC, a packed size running past the data, names that are not UTF-8 (refused with the UTF-8 flag, read as Latin-1 without it) and a date before 1980.
8
+
3
9
  ## 0.12.0
4
10
 
5
11
  Nothing to migrate: a new module and new optional members.
package/dist/zip.js CHANGED
@@ -37,7 +37,7 @@ var encoder = new TextEncoder();
37
37
  * трогать нельзя, поэтому такие имена ни входят, ни выходят.
38
38
  */
39
39
  function assertName(name) {
40
- if (name === "" || name.startsWith("/") || name.includes("\\") || /[\x00-\x1f\x7f]/.test(name) || name.split("/").some((part) => part === "" || part === "." || part === "..")) throw new ZipError("unsafeName", JSON.stringify(name));
40
+ if (name === "" || name.includes("\\") || /[\x00-\x1f\x7f]/.test(name) || name.split("/").some((part) => part === "" || part === "." || part === "..")) throw new ZipError("unsafeName", JSON.stringify(name));
41
41
  }
42
42
  var crcTable = Array.from({ length: 256 }, (_, n) => {
43
43
  let c = n;
@@ -107,7 +107,7 @@ async function createZip(entries, options = {}) {
107
107
  const crc = crc32(entry.data);
108
108
  let method = STORED;
109
109
  let stored = entry.data;
110
- if (options.compress !== "store" && entry.data.length > 0 && !ALREADY_COMPRESSED.test(entry.name)) {
110
+ if (options.compress !== "store" && !ALREADY_COMPRESSED.test(entry.name)) {
111
111
  const packed = await through(entry.data, new CompressionStream("deflate-raw"));
112
112
  if (packed.length < entry.data.length) {
113
113
  method = DEFLATED;
@@ -206,7 +206,6 @@ async function readZip(data, limits = {}) {
206
206
  const seen = /* @__PURE__ */ new Set();
207
207
  let at = directoryOffset;
208
208
  let declaredTotal = 0;
209
- let total = 0;
210
209
  for (let n = 0; n < count; n++) {
211
210
  if (at + 46 > end || view.getUint32(at, true) !== CENTRAL) throw new ZipError("corrupt", "directory");
212
211
  const flags = view.getUint16(at + 8, true);
@@ -238,17 +237,13 @@ async function readZip(data, limits = {}) {
238
237
  if (start + packedSize > directoryOffset) throw new ZipError("corrupt", name);
239
238
  const packed = data.subarray(start, start + packedSize);
240
239
  let bytes;
241
- if (method === STORED) {
242
- if (packedSize !== size) throw new ZipError("corrupt", name);
243
- bytes = packed.slice();
244
- } else try {
240
+ if (method === STORED) bytes = packed.slice();
241
+ else try {
245
242
  bytes = await through(packed, new DecompressionStream("deflate-raw"), size);
246
243
  } catch {
247
244
  throw new ZipError("corrupt", name);
248
245
  }
249
246
  if (bytes.length !== size || crc32(bytes) !== crc) throw new ZipError("corrupt", name);
250
- total += bytes.length;
251
- if (total > maxTotalBytes) throw new ZipError("tooLarge", name);
252
247
  result.push({
253
248
  name,
254
249
  data: bytes
package/dist/zip.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"zip.js","names":[],"sources":["../src/zip.ts"],"sourcesContent":["// ZIP without libraries: the browser's CompressionStream does the deflate. No DOM, no Vue.\n// ZIP без библиотек: deflate делает CompressionStream браузера. Без DOM и Vue.\n\n/**\n * A file in an archive: the path with `/` as the separator (`assets/hero.png`) and its bytes.\n * Файл в архиве: путь с разделителем `/` (`assets/hero.png`) и его байты.\n */\nexport interface ZipEntry {\n name: string;\n data: Uint8Array;\n}\n\nexport type ZipErrorCode =\n | 'notZip' // not an archive at all / это вообще не архив\n | 'unsupported' // encrypted, ZIP64, several disks, an unknown method / шифрование, ZIP64, несколько дисков, незнакомый метод\n | 'corrupt' // damaged: bounds, size, CRC, a failed inflate / повреждён: границы, размер, CRC, сбой распаковки\n | 'unsafeName' // a path that would leave the folder it is unpacked into / путь, который выбрался бы из папки распаковки\n | 'duplicate' // the same name twice / одно имя дважды\n | 'tooMany' // more files than allowed / файлов больше, чем разрешено\n | 'tooLarge'; // a file or the whole archive unpacks bigger than allowed / файл или весь архив распакуется больше, чем разрешено\n\n/**\n * Why an archive was refused or could not be written. The interface builds the user text from `code`.\n * Почему архив отклонён или не записан. Текст для пользователя собирает интерфейс по `code`.\n */\nexport class ZipError extends Error {\n constructor(\n readonly code: ZipErrorCode,\n readonly detail?: string,\n ) {\n super(detail === undefined ? code : `${code}: ${detail}`);\n this.name = 'ZipError';\n }\n}\n\n/**\n * Limits of reading. An archive comes from outside, and a few KB can unpack into gigabytes, so the sizes are checked\n * twice: the declared ones before unpacking and the real ones while unpacking.\n * Пределы чтения. Архив приходит извне, а несколько КБ могут распаковаться в гигабайты, поэтому размеры проверяются\n * дважды: объявленные до распаковки и настоящие во время неё.\n */\nexport interface ZipReadLimits {\n /** Files in the archive. Default 10 000. / Файлов в архиве. По умолчанию 10 000. */\n maxEntries?: number;\n /** Bytes of one unpacked file. Default 512 MiB. / Байт в одном распакованном файле. По умолчанию 512 МиБ. */\n maxEntryBytes?: number;\n /** Bytes of all unpacked files together. Default 1 GiB. / Байт во всех файлах вместе. По умолчанию 1 ГиБ. */\n maxTotalBytes?: number;\n}\n\nexport const ZIP_LIMITS: Required<ZipReadLimits> = { maxEntries: 10_000, maxEntryBytes: 512 * 1024 * 1024, maxTotalBytes: 1024 * 1024 * 1024 };\n\nexport interface ZipWriteOptions {\n /** Modification time written for every file. Now by default. / Время изменения у всех файлов. По умолчанию сейчас. */\n date?: Date;\n /**\n * `auto` (default): a file is deflated unless it is already compressed (PNG, JPEG, WebP, audio, video, archives) and\n * only when that makes it smaller; `store`: everything as it is.\n * `auto` (по умолчанию): файл сжимается, если он ещё не сжат (PNG, JPEG, WebP, звук, видео, архивы) и только когда\n * от этого становится меньше; `store`: всё как есть.\n */\n compress?: 'auto' | 'store';\n}\n\nconst LOCAL = 0x04034b50;\nconst CENTRAL = 0x02014b50;\nconst END = 0x06054b50;\nconst VERSION = 20; // 2.0: the lowest that every unzip tool understands / 2.0: ниже все распаковщики понимают\nconst UTF8_NAMES = 0x0800;\nconst ENCRYPTED = 0x0001 | 0x0040;\nconst STORED = 0;\nconst DEFLATED = 8;\nconst MAX32 = 0xffffffff;\nconst MAX16 = 0xffff;\nconst ALREADY_COMPRESSED = /\\.(png|jpe?g|gif|webp|avif|zip|gz|bz2|7z|rar|mp3|ogg|opus|m4a|aac|mp4|webm|mov|woff2?)$/i;\n\nconst encoder = new TextEncoder();\n\n/**\n * A path that would climb out of the folder it is unpacked into (`../x`, `/etc/x`, `a\\..\\x`) is how a ZIP overwrites\n * files it should not touch, so such names never get in or out.\n * Путь, который выбрался бы из папки распаковки (`../x`, `/etc/x`, `a\\..\\x`), — это способ ZIP затереть то, что ему\n * трогать нельзя, поэтому такие имена ни входят, ни выходят.\n */\nfunction assertName(name: string): void {\n const unsafe =\n name === '' ||\n name.startsWith('/') ||\n name.includes('\\\\') ||\n /[\\x00-\\x1f\\x7f]/.test(name) ||\n name.split('/').some((part) => part === '' || part === '.' || part === '..');\n if (unsafe) throw new ZipError('unsafeName', JSON.stringify(name));\n}\n\nconst crcTable = Array.from({ length: 256 }, (_, n) => {\n let c = n;\n for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;\n return c >>> 0;\n});\n\nfunction crc32(data: Uint8Array): number {\n let c = 0xffffffff;\n for (let i = 0; i < data.length; i++) c = crcTable[(c ^ data[i]!) & 0xff]! ^ (c >>> 8);\n return (c ^ 0xffffffff) >>> 0;\n}\n\n/** Local time as DOS date and time (2 s resolution, from 1980). / Местное время как DOS-дата и время (шаг 2 с, с 1980). */\nfunction dosTime(date: Date): { time: number; day: number } {\n const year = Math.max(1980, date.getFullYear());\n return {\n time: (date.getHours() << 11) | (date.getMinutes() << 5) | (date.getSeconds() >> 1),\n day: ((year - 1980) << 9) | ((date.getMonth() + 1) << 5) | date.getDate(),\n };\n}\n\n/** Passes the bytes through a (de)compression stream. `max` stops a result that grows past what is expected. */\nasync function through(data: Uint8Array, transform: CompressionStream | DecompressionStream, max = Infinity): Promise<Uint8Array> {\n const source = new ReadableStream<Uint8Array>({\n start(controller) {\n controller.enqueue(data);\n controller.close();\n },\n });\n const reader = source.pipeThrough(transform as unknown as ReadableWritablePair<Uint8Array, Uint8Array>).getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.length;\n if (total > max) {\n await reader.cancel();\n throw new ZipError('corrupt', 'size');\n }\n chunks.push(value);\n }\n return concat(chunks, total);\n}\n\nfunction concat(chunks: readonly Uint8Array[], total = chunks.reduce((n, c) => n + c.length, 0)): Uint8Array<ArrayBuffer> {\n const out = new Uint8Array(total);\n let at = 0;\n for (const c of chunks) {\n out.set(c, at);\n at += c.length;\n }\n return out;\n}\n\n//--------------------------------------------------\n// writing / запись\n\n/**\n * Writes a ZIP archive. Names are UTF-8; no ZIP64, so up to 65 535 files and 4 GiB. Files already compressed are stored\n * as they are (see `compress`), the rest are deflated.\n * Пишет ZIP-архив. Имена в UTF-8; без ZIP64: до 65 535 файлов и 4 ГиБ. Уже сжатые файлы кладутся как есть\n * (см. `compress`), остальные сжимаются.\n */\nexport async function createZip(entries: readonly ZipEntry[], options: ZipWriteOptions = {}): Promise<Uint8Array<ArrayBuffer>> {\n if (entries.length > MAX16) throw new ZipError('tooMany', `${entries.length} files do not fit into a ZIP without ZIP64`);\n const { time, day } = dosTime(options.date ?? new Date());\n const seen = new Set<string>();\n const body: Uint8Array[] = [];\n const central: Uint8Array[] = [];\n let offset = 0;\n\n for (const entry of entries) {\n assertName(entry.name);\n if (seen.has(entry.name)) throw new ZipError('duplicate', entry.name);\n seen.add(entry.name);\n\n const name = encoder.encode(entry.name);\n const crc = crc32(entry.data);\n let method = STORED;\n let stored = entry.data;\n if (options.compress !== 'store' && entry.data.length > 0 && !ALREADY_COMPRESSED.test(entry.name)) {\n const packed = await through(entry.data, new CompressionStream('deflate-raw'));\n if (packed.length < entry.data.length) {\n method = DEFLATED;\n stored = packed;\n }\n }\n if (entry.data.length > MAX32 || offset > MAX32) throw new ZipError('tooLarge', entry.name);\n\n const local = new DataView(new ArrayBuffer(30));\n local.setUint32(0, LOCAL, true);\n local.setUint16(4, VERSION, true);\n local.setUint16(6, UTF8_NAMES, true);\n local.setUint16(8, method, true);\n local.setUint16(10, time, true);\n local.setUint16(12, day, true);\n local.setUint32(14, crc, true);\n local.setUint32(18, stored.length, true);\n local.setUint32(22, entry.data.length, true);\n local.setUint16(26, name.length, true);\n local.setUint16(28, 0, true);\n\n const head = new DataView(new ArrayBuffer(46));\n head.setUint32(0, CENTRAL, true);\n head.setUint16(4, VERSION, true);\n head.setUint16(6, VERSION, true);\n head.setUint16(8, UTF8_NAMES, true);\n head.setUint16(10, method, true);\n head.setUint16(12, time, true);\n head.setUint16(14, day, true);\n head.setUint32(16, crc, true);\n head.setUint32(20, stored.length, true);\n head.setUint32(24, entry.data.length, true);\n head.setUint16(28, name.length, true);\n head.setUint32(42, offset, true);\n\n body.push(new Uint8Array(local.buffer), name, stored);\n central.push(new Uint8Array(head.buffer), name);\n offset += 30 + name.length + stored.length;\n }\n\n const directory = concat(central);\n if (offset + directory.length > MAX32) throw new ZipError('tooLarge');\n const end = new DataView(new ArrayBuffer(22));\n end.setUint32(0, END, true);\n end.setUint16(8, entries.length, true);\n end.setUint16(10, entries.length, true);\n end.setUint32(12, directory.length, true);\n end.setUint32(16, offset, true);\n return concat([...body, directory, new Uint8Array(end.buffer)]);\n}\n\n//--------------------------------------------------\n// reading / чтение\n\n/**\n * Whether the bytes start like a ZIP (a file or an empty archive). A quick check to tell an archive from a text file\n * before opening it; `readZip` does the real checking.\n * Начинаются ли байты как ZIP (файл или пустой архив). Быстрая проверка, чтобы отличить архив от текстового файла\n * до открытия; настоящую проверку делает `readZip`.\n */\nexport function looksLikeZip(data: Uint8Array): boolean {\n return data.length >= 4 && data[0] === 0x50 && data[1] === 0x4b && ((data[2] === 3 && data[3] === 4) || (data[2] === 5 && data[3] === 6));\n}\n\nfunction decodeName(bytes: Uint8Array, utf8: boolean): string {\n try {\n return new TextDecoder('utf-8', { fatal: true }).decode(bytes);\n } catch {\n if (utf8) throw new ZipError('corrupt', 'name');\n return String.fromCharCode(...bytes); // an old tool without the UTF-8 flag: Latin-1 at least keeps the letters apart\n }\n}\n\n/**\n * Reads a ZIP archive into its files (folders are skipped). Throws `ZipError`. Never writes anywhere: the names are\n * checked (no `..`, no absolute paths, no backslashes) and the sizes are limited (`limits`), CRC is verified.\n * Reads the central directory, so archives written by any tool open, including those with sizes after the data.\n * Читает ZIP-архив в файлы (папки пропускаются). Бросает `ZipError`. Никуда ничего не пишет: имена проверяются\n * (без `..`, абсолютных путей и обратных косых), размеры ограничены (`limits`), CRC сверяется.\n * Читает центральный каталог, поэтому открываются архивы любой программы, в том числе с размерами после данных.\n */\nexport async function readZip(data: Uint8Array, limits: ZipReadLimits = {}): Promise<ZipEntry[]> {\n const { maxEntries, maxEntryBytes, maxTotalBytes } = { ...ZIP_LIMITS, ...limits };\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n\n // the end record: the last 22 bytes, or before a comment of up to 65 535 bytes\n let end = -1;\n for (let i = data.length - 22; i >= Math.max(0, data.length - 22 - MAX16); i--) {\n if (view.getUint32(i, true) === END && i + 22 + view.getUint16(i + 20, true) === data.length) {\n end = i;\n break;\n }\n }\n if (end < 0) throw new ZipError('notZip');\n\n const count = view.getUint16(end + 10, true);\n const directorySize = view.getUint32(end + 12, true);\n const directoryOffset = view.getUint32(end + 16, true);\n if (view.getUint16(end + 4, true) !== 0 || view.getUint16(end + 6, true) !== 0 || view.getUint16(end + 8, true) !== count) throw new ZipError('unsupported', 'several disks');\n if (count === MAX16 || directorySize === MAX32 || directoryOffset === MAX32) throw new ZipError('unsupported', 'ZIP64');\n if (count > maxEntries) throw new ZipError('tooMany', String(count));\n if (directoryOffset + directorySize > end) throw new ZipError('corrupt', 'directory');\n\n const result: ZipEntry[] = [];\n const seen = new Set<string>();\n let at = directoryOffset;\n let declaredTotal = 0;\n let total = 0;\n\n for (let n = 0; n < count; n++) {\n if (at + 46 > end || view.getUint32(at, true) !== CENTRAL) throw new ZipError('corrupt', 'directory');\n const flags = view.getUint16(at + 8, true);\n const method = view.getUint16(at + 10, true);\n const crc = view.getUint32(at + 16, true);\n const packedSize = view.getUint32(at + 20, true);\n const size = view.getUint32(at + 24, true);\n const nameLength = view.getUint16(at + 28, true);\n const extraLength = view.getUint16(at + 30, true);\n const commentLength = view.getUint16(at + 32, true);\n const localOffset = view.getUint32(at + 42, true);\n if (at + 46 + nameLength + extraLength + commentLength > end) throw new ZipError('corrupt', 'directory');\n const name = decodeName(data.subarray(at + 46, at + 46 + nameLength), (flags & UTF8_NAMES) !== 0);\n at += 46 + nameLength + extraLength + commentLength;\n\n if (name.endsWith('/')) {\n assertName(name.slice(0, -1));\n continue; // a folder: folders follow from the paths / папка: папки следуют из путей\n }\n assertName(name);\n if (seen.has(name)) throw new ZipError('duplicate', name);\n seen.add(name);\n\n if (flags & ENCRYPTED) throw new ZipError('unsupported', 'encrypted');\n if (method !== STORED && method !== DEFLATED) throw new ZipError('unsupported', `method ${method}`);\n if (packedSize === MAX32 || size === MAX32 || localOffset === MAX32) throw new ZipError('unsupported', 'ZIP64');\n declaredTotal += size;\n if (size > maxEntryBytes || declaredTotal > maxTotalBytes) throw new ZipError('tooLarge', name);\n\n if (localOffset + 30 > directoryOffset || view.getUint32(localOffset, true) !== LOCAL) throw new ZipError('corrupt', name);\n const start = localOffset + 30 + view.getUint16(localOffset + 26, true) + view.getUint16(localOffset + 28, true);\n if (start + packedSize > directoryOffset) throw new ZipError('corrupt', name);\n const packed = data.subarray(start, start + packedSize);\n\n let bytes: Uint8Array;\n if (method === STORED) {\n if (packedSize !== size) throw new ZipError('corrupt', name);\n bytes = packed.slice();\n } else {\n try {\n bytes = await through(packed, new DecompressionStream('deflate-raw'), size);\n } catch {\n throw new ZipError('corrupt', name); // bad deflate data, or more than the declared size / плохие данные или больше заявленного размера\n }\n }\n if (bytes.length !== size || crc32(bytes) !== crc) throw new ZipError('corrupt', name);\n total += bytes.length;\n if (total > maxTotalBytes) throw new ZipError('tooLarge', name);\n result.push({ name, data: bytes });\n }\n return result;\n}\n"],"mappings":";;;;;AAyBA,IAAa,WAAb,cAA8B,MAAM;CAEnB;CACA;CAFb,YACI,MACA,QACF;EACE,MAAM,WAAW,KAAA,IAAY,OAAO,GAAG,KAAK,IAAI,QAAQ;EAH/C,KAAA,OAAA;EACA,KAAA,SAAA;EAGT,KAAK,OAAO;CAChB;AACJ;AAiBA,IAAa,aAAsC;CAAE,YAAY;CAAQ,eAAe;CAAmB,eAAe;AAAmB;AAc7I,IAAM,QAAQ;AACd,IAAM,UAAU;AAChB,IAAM,MAAM;AACZ,IAAM,UAAU;AAChB,IAAM,aAAa;AACnB,IAAM,YAAY;AAClB,IAAM,SAAS;AACf,IAAM,WAAW;AACjB,IAAM,QAAQ;AACd,IAAM,QAAQ;AACd,IAAM,qBAAqB;AAE3B,IAAM,UAAU,IAAI,YAAY;;;;;;;AAQhC,SAAS,WAAW,MAAoB;CAOpC,IALI,SAAS,MACT,KAAK,WAAW,GAAG,KACnB,KAAK,SAAS,IAAI,KAClB,kBAAkB,KAAK,IAAI,KAC3B,KAAK,MAAM,GAAG,CAAC,CAAC,MAAM,SAAS,SAAS,MAAM,SAAS,OAAO,SAAS,IAAI,GACnE,MAAM,IAAI,SAAS,cAAc,KAAK,UAAU,IAAI,CAAC;AACrE;AAEA,IAAM,WAAW,MAAM,KAAK,EAAE,QAAQ,IAAI,IAAI,GAAG,MAAM;CACnD,IAAI,IAAI;CACR,KAAK,IAAI,IAAI,GAAG,IAAI,GAAG,KAAK,IAAI,IAAI,IAAI,aAA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ACrC;CACA,OAAO;AACX"}
1
+ {"version":3,"file":"zip.js","names":[],"sources":["../src/zip.ts"],"sourcesContent":["// ZIP without libraries: the browser's CompressionStream does the deflate. No DOM, no Vue.\n// ZIP без библиотек: deflate делает CompressionStream браузера. Без DOM и Vue.\n\n/**\n * A file in an archive: the path with `/` as the separator (`assets/hero.png`) and its bytes.\n * Файл в архиве: путь с разделителем `/` (`assets/hero.png`) и его байты.\n */\nexport interface ZipEntry {\n name: string;\n data: Uint8Array;\n}\n\nexport type ZipErrorCode =\n | 'notZip' // not an archive at all / это вообще не архив\n | 'unsupported' // encrypted, ZIP64, several disks, an unknown method / шифрование, ZIP64, несколько дисков, незнакомый метод\n | 'corrupt' // damaged: bounds, size, CRC, a failed inflate / повреждён: границы, размер, CRC, сбой распаковки\n | 'unsafeName' // a path that would leave the folder it is unpacked into / путь, который выбрался бы из папки распаковки\n | 'duplicate' // the same name twice / одно имя дважды\n | 'tooMany' // more files than allowed / файлов больше, чем разрешено\n | 'tooLarge'; // a file or the whole archive unpacks bigger than allowed / файл или весь архив распакуется больше, чем разрешено\n\n/**\n * Why an archive was refused or could not be written. The interface builds the user text from `code`.\n * Почему архив отклонён или не записан. Текст для пользователя собирает интерфейс по `code`.\n */\nexport class ZipError extends Error {\n constructor(\n readonly code: ZipErrorCode,\n readonly detail?: string,\n ) {\n super(detail === undefined ? code : `${code}: ${detail}`);\n this.name = 'ZipError';\n }\n}\n\n/**\n * Limits of reading. An archive comes from outside, and a few KB can unpack into gigabytes, so the sizes are checked\n * twice: the declared ones before unpacking and the real ones while unpacking.\n * Пределы чтения. Архив приходит извне, а несколько КБ могут распаковаться в гигабайты, поэтому размеры проверяются\n * дважды: объявленные до распаковки и настоящие во время неё.\n */\nexport interface ZipReadLimits {\n /** Files in the archive. Default 10 000. / Файлов в архиве. По умолчанию 10 000. */\n maxEntries?: number;\n /** Bytes of one unpacked file. Default 512 MiB. / Байт в одном распакованном файле. По умолчанию 512 МиБ. */\n maxEntryBytes?: number;\n /** Bytes of all unpacked files together. Default 1 GiB. / Байт во всех файлах вместе. По умолчанию 1 ГиБ. */\n maxTotalBytes?: number;\n}\n\nexport const ZIP_LIMITS: Required<ZipReadLimits> = { maxEntries: 10_000, maxEntryBytes: 512 * 1024 * 1024, maxTotalBytes: 1024 * 1024 * 1024 };\n\nexport interface ZipWriteOptions {\n /** Modification time written for every file. Now by default. / Время изменения у всех файлов. По умолчанию сейчас. */\n date?: Date;\n /**\n * `auto` (default): a file is deflated unless it is already compressed (PNG, JPEG, WebP, audio, video, archives) and\n * only when that makes it smaller; `store`: everything as it is.\n * `auto` (по умолчанию): файл сжимается, если он ещё не сжат (PNG, JPEG, WebP, звук, видео, архивы) и только когда\n * от этого становится меньше; `store`: всё как есть.\n */\n compress?: 'auto' | 'store';\n}\n\nconst LOCAL = 0x04034b50;\nconst CENTRAL = 0x02014b50;\nconst END = 0x06054b50;\nconst VERSION = 20; // 2.0: the lowest that every unzip tool understands / 2.0: ниже все распаковщики понимают\nconst UTF8_NAMES = 0x0800;\nconst ENCRYPTED = 0x0001 | 0x0040;\nconst STORED = 0;\nconst DEFLATED = 8;\nconst MAX32 = 0xffffffff;\nconst MAX16 = 0xffff;\nconst ALREADY_COMPRESSED = /\\.(png|jpe?g|gif|webp|avif|zip|gz|bz2|7z|rar|mp3|ogg|opus|m4a|aac|mp4|webm|mov|woff2?)$/i;\n\nconst encoder = new TextEncoder();\n\n/**\n * A path that would climb out of the folder it is unpacked into (`../x`, `/etc/x`, `a\\..\\x`) is how a ZIP overwrites\n * files it should not touch, so such names never get in or out.\n * Путь, который выбрался бы из папки распаковки (`../x`, `/etc/x`, `a\\..\\x`), — это способ ZIP затереть то, что ему\n * трогать нельзя, поэтому такие имена ни входят, ни выходят.\n */\nfunction assertName(name: string): void {\n const unsafe =\n name === '' ||\n name.includes('\\\\') ||\n /[\\x00-\\x1f\\x7f]/.test(name) ||\n name.split('/').some((part) => part === '' || part === '.' || part === '..');\n if (unsafe) throw new ZipError('unsafeName', JSON.stringify(name));\n}\n\nconst crcTable = Array.from({ length: 256 }, (_, n) => {\n let c = n;\n for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;\n return c >>> 0;\n});\n\nfunction crc32(data: Uint8Array): number {\n let c = 0xffffffff;\n for (let i = 0; i < data.length; i++) c = crcTable[(c ^ data[i]!) & 0xff]! ^ (c >>> 8);\n return (c ^ 0xffffffff) >>> 0;\n}\n\n/** Local time as DOS date and time (2 s resolution, from 1980). / Местное время как DOS-дата и время (шаг 2 с, с 1980). */\nfunction dosTime(date: Date): { time: number; day: number } {\n const year = Math.max(1980, date.getFullYear());\n return {\n time: (date.getHours() << 11) | (date.getMinutes() << 5) | (date.getSeconds() >> 1),\n day: ((year - 1980) << 9) | ((date.getMonth() + 1) << 5) | date.getDate(),\n };\n}\n\n/** Passes the bytes through a (de)compression stream. `max` stops a result that grows past what is expected. */\nasync function through(data: Uint8Array, transform: CompressionStream | DecompressionStream, max = Infinity): Promise<Uint8Array> {\n const source = new ReadableStream<Uint8Array>({\n start(controller) {\n controller.enqueue(data);\n controller.close();\n },\n });\n const reader = source.pipeThrough(transform as unknown as ReadableWritablePair<Uint8Array, Uint8Array>).getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.length;\n if (total > max) {\n await reader.cancel();\n throw new ZipError('corrupt', 'size');\n }\n chunks.push(value);\n }\n return concat(chunks, total);\n}\n\nfunction concat(chunks: readonly Uint8Array[], total = chunks.reduce((n, c) => n + c.length, 0)): Uint8Array<ArrayBuffer> {\n const out = new Uint8Array(total);\n let at = 0;\n for (const c of chunks) {\n out.set(c, at);\n at += c.length;\n }\n return out;\n}\n\n//--------------------------------------------------\n// writing / запись\n\n/**\n * Writes a ZIP archive. Names are UTF-8; no ZIP64, so up to 65 535 files and 4 GiB. Files already compressed are stored\n * as they are (see `compress`), the rest are deflated.\n * Пишет ZIP-архив. Имена в UTF-8; без ZIP64: до 65 535 файлов и 4 ГиБ. Уже сжатые файлы кладутся как есть\n * (см. `compress`), остальные сжимаются.\n */\nexport async function createZip(entries: readonly ZipEntry[], options: ZipWriteOptions = {}): Promise<Uint8Array<ArrayBuffer>> {\n if (entries.length > MAX16) throw new ZipError('tooMany', `${entries.length} files do not fit into a ZIP without ZIP64`);\n const { time, day } = dosTime(options.date ?? new Date());\n const seen = new Set<string>();\n const body: Uint8Array[] = [];\n const central: Uint8Array[] = [];\n let offset = 0;\n\n for (const entry of entries) {\n assertName(entry.name);\n if (seen.has(entry.name)) throw new ZipError('duplicate', entry.name);\n seen.add(entry.name);\n\n const name = encoder.encode(entry.name);\n const crc = crc32(entry.data);\n let method = STORED;\n let stored = entry.data;\n if (options.compress !== 'store' && !ALREADY_COMPRESSED.test(entry.name)) {\n const packed = await through(entry.data, new CompressionStream('deflate-raw'));\n if (packed.length < entry.data.length) {\n method = DEFLATED;\n stored = packed;\n }\n }\n if (entry.data.length > MAX32 || offset > MAX32) throw new ZipError('tooLarge', entry.name);\n\n const local = new DataView(new ArrayBuffer(30));\n local.setUint32(0, LOCAL, true);\n local.setUint16(4, VERSION, true);\n local.setUint16(6, UTF8_NAMES, true);\n local.setUint16(8, method, true);\n local.setUint16(10, time, true);\n local.setUint16(12, day, true);\n local.setUint32(14, crc, true);\n local.setUint32(18, stored.length, true);\n local.setUint32(22, entry.data.length, true);\n local.setUint16(26, name.length, true);\n local.setUint16(28, 0, true);\n\n const head = new DataView(new ArrayBuffer(46));\n head.setUint32(0, CENTRAL, true);\n head.setUint16(4, VERSION, true);\n head.setUint16(6, VERSION, true);\n head.setUint16(8, UTF8_NAMES, true);\n head.setUint16(10, method, true);\n head.setUint16(12, time, true);\n head.setUint16(14, day, true);\n head.setUint32(16, crc, true);\n head.setUint32(20, stored.length, true);\n head.setUint32(24, entry.data.length, true);\n head.setUint16(28, name.length, true);\n head.setUint32(42, offset, true);\n\n body.push(new Uint8Array(local.buffer), name, stored);\n central.push(new Uint8Array(head.buffer), name);\n offset += 30 + name.length + stored.length;\n }\n\n const directory = concat(central);\n if (offset + directory.length > MAX32) throw new ZipError('tooLarge');\n const end = new DataView(new ArrayBuffer(22));\n end.setUint32(0, END, true);\n end.setUint16(8, entries.length, true);\n end.setUint16(10, entries.length, true);\n end.setUint32(12, directory.length, true);\n end.setUint32(16, offset, true);\n return concat([...body, directory, new Uint8Array(end.buffer)]);\n}\n\n//--------------------------------------------------\n// reading / чтение\n\n/**\n * Whether the bytes start like a ZIP (a file or an empty archive). A quick check to tell an archive from a text file\n * before opening it; `readZip` does the real checking.\n * Начинаются ли байты как ZIP (файл или пустой архив). Быстрая проверка, чтобы отличить архив от текстового файла\n * до открытия; настоящую проверку делает `readZip`.\n */\nexport function looksLikeZip(data: Uint8Array): boolean {\n return data.length >= 4 && data[0] === 0x50 && data[1] === 0x4b && ((data[2] === 3 && data[3] === 4) || (data[2] === 5 && data[3] === 6));\n}\n\nfunction decodeName(bytes: Uint8Array, utf8: boolean): string {\n try {\n return new TextDecoder('utf-8', { fatal: true }).decode(bytes);\n } catch {\n if (utf8) throw new ZipError('corrupt', 'name');\n return String.fromCharCode(...bytes); // an old tool without the UTF-8 flag: Latin-1 at least keeps the letters apart\n }\n}\n\n/**\n * Reads a ZIP archive into its files (folders are skipped). Throws `ZipError`. Never writes anywhere: the names are\n * checked (no `..`, no absolute paths, no backslashes) and the sizes are limited (`limits`), CRC is verified.\n * Reads the central directory, so archives written by any tool open, including those with sizes after the data.\n * Читает ZIP-архив в файлы (папки пропускаются). Бросает `ZipError`. Никуда ничего не пишет: имена проверяются\n * (без `..`, абсолютных путей и обратных косых), размеры ограничены (`limits`), CRC сверяется.\n * Читает центральный каталог, поэтому открываются архивы любой программы, в том числе с размерами после данных.\n */\nexport async function readZip(data: Uint8Array, limits: ZipReadLimits = {}): Promise<ZipEntry[]> {\n const { maxEntries, maxEntryBytes, maxTotalBytes } = { ...ZIP_LIMITS, ...limits };\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n\n // the end record: the last 22 bytes, or before a comment of up to 65 535 bytes\n let end = -1;\n for (let i = data.length - 22; i >= Math.max(0, data.length - 22 - MAX16); i--) {\n if (view.getUint32(i, true) === END && i + 22 + view.getUint16(i + 20, true) === data.length) {\n end = i;\n break;\n }\n }\n if (end < 0) throw new ZipError('notZip');\n\n const count = view.getUint16(end + 10, true);\n const directorySize = view.getUint32(end + 12, true);\n const directoryOffset = view.getUint32(end + 16, true);\n if (view.getUint16(end + 4, true) !== 0 || view.getUint16(end + 6, true) !== 0 || view.getUint16(end + 8, true) !== count) throw new ZipError('unsupported', 'several disks');\n if (count === MAX16 || directorySize === MAX32 || directoryOffset === MAX32) throw new ZipError('unsupported', 'ZIP64');\n if (count > maxEntries) throw new ZipError('tooMany', String(count));\n if (directoryOffset + directorySize > end) throw new ZipError('corrupt', 'directory');\n\n const result: ZipEntry[] = [];\n const seen = new Set<string>();\n let at = directoryOffset;\n let declaredTotal = 0;\n\n for (let n = 0; n < count; n++) {\n if (at + 46 > end || view.getUint32(at, true) !== CENTRAL) throw new ZipError('corrupt', 'directory');\n const flags = view.getUint16(at + 8, true);\n const method = view.getUint16(at + 10, true);\n const crc = view.getUint32(at + 16, true);\n const packedSize = view.getUint32(at + 20, true);\n const size = view.getUint32(at + 24, true);\n const nameLength = view.getUint16(at + 28, true);\n const extraLength = view.getUint16(at + 30, true);\n const commentLength = view.getUint16(at + 32, true);\n const localOffset = view.getUint32(at + 42, true);\n if (at + 46 + nameLength + extraLength + commentLength > end) throw new ZipError('corrupt', 'directory');\n const name = decodeName(data.subarray(at + 46, at + 46 + nameLength), (flags & UTF8_NAMES) !== 0);\n at += 46 + nameLength + extraLength + commentLength;\n\n if (name.endsWith('/')) {\n assertName(name.slice(0, -1));\n continue; // a folder: folders follow from the paths / папка: папки следуют из путей\n }\n assertName(name);\n if (seen.has(name)) throw new ZipError('duplicate', name);\n seen.add(name);\n\n if (flags & ENCRYPTED) throw new ZipError('unsupported', 'encrypted');\n if (method !== STORED && method !== DEFLATED) throw new ZipError('unsupported', `method ${method}`);\n if (packedSize === MAX32 || size === MAX32 || localOffset === MAX32) throw new ZipError('unsupported', 'ZIP64');\n declaredTotal += size;\n if (size > maxEntryBytes || declaredTotal > maxTotalBytes) throw new ZipError('tooLarge', name);\n\n if (localOffset + 30 > directoryOffset || view.getUint32(localOffset, true) !== LOCAL) throw new ZipError('corrupt', name);\n const start = localOffset + 30 + view.getUint16(localOffset + 26, true) + view.getUint16(localOffset + 28, true);\n if (start + packedSize > directoryOffset) throw new ZipError('corrupt', name);\n const packed = data.subarray(start, start + packedSize);\n\n let bytes: Uint8Array;\n if (method === STORED) {\n bytes = packed.slice();\n } else {\n try {\n bytes = await through(packed, new DecompressionStream('deflate-raw'), size);\n } catch {\n throw new ZipError('corrupt', name); // bad deflate data, or more than the declared size / плохие данные или больше заявленного размера\n }\n }\n if (bytes.length !== size || crc32(bytes) !== crc) throw new ZipError('corrupt', name);\n result.push({ name, data: bytes });\n }\n return result;\n}\n"],"mappings":";;;;;AAyBA,IAAa,WAAb,cAA8B,MAAM;CAEnB;CACA;CAFb,YACI,MACA,QACF;EACE,MAAM,WAAW,KAAA,IAAY,OAAO,GAAG,KAAK,IAAI,QAAQ;EAH/C,KAAA,OAAA;EACA,KAAA,SAAA;EAGT,KAAK,OAAO;CAChB;AACJ;AAiBA,IAAa,aAAsC;CAAE,YAAY;CAAQ,eAAe;CAAmB,eAAe;AAAmB;AAc7I,IAAM,QAAQ;AACd,IAAM,UAAU;AAChB,IAAM,MAAM;AACZ,IAAM,UAAU;AAChB,IAAM,aAAa;AACnB,IAAM,YAAY;AAClB,IAAM,SAAS;AACf,IAAM,WAAW;AACjB,IAAM,QAAQ;AACd,IAAM,QAAQ;AACd,IAAM,qBAAqB;AAE3B,IAAM,UAAU,IAAI,YAAY;;;;;;;AAQhC,SAAS,WAAW,MAAoB;CAMpC,IAJI,SAAS,MACT,KAAK,SAAS,IAAI,KAClB,kBAAkB,KA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MAAM,WAAW,QAAQ,MAAM,KAAK,MAAM,KAAK,MAAM,IAAI,SAAS,WAAW,IAAI;EACrF,OAAO,KAAK;GAAE;GAAM,MAAM;EAAM,CAAC;CACrC;CACA,OAAO;AACX"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@1337exp/taoux",
3
- "version": "0.12.0",
3
+ "version": "0.12.1",
4
4
  "description": "Interaction and behavior building blocks for Vue apps: curve and gradient editors, canvas, undo/redo, playback. Import only what you need, bring your own design.",
5
5
  "keywords": [
6
6
  "vue",