7zip-wrapper 0.0.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.
@@ -0,0 +1,639 @@
1
+ import { ExecOptions } from 'child_process';
2
+ import { Readable } from 'stream';
3
+
4
+ /**
5
+ * Archive-related types
6
+ */
7
+ /**
8
+ * Supported archive formats for reading
9
+ */
10
+ type ArchiveFormat = '7z' | 'zip' | 'gzip' | 'bzip2' | 'tar' | 'rar' | 'iso' | 'cab' | 'lzma' | 'lzma2' | 'xz' | 'wim' | 'arj' | 'cpio' | 'rpm' | 'deb' | 'vhd' | 'fat' | 'ntfs';
11
+ /**
12
+ * Archive types for creation
13
+ */
14
+ type ArchiveType = '7z' | 'zip' | 'gzip' | 'bzip2' | 'tar' | 'xz' | 'wim';
15
+ /**
16
+ * Archive entry information
17
+ */
18
+ interface ArchiveEntry {
19
+ /** File path within archive */
20
+ path: string;
21
+ /** Original file size in bytes */
22
+ size: number;
23
+ /** Compressed size in bytes */
24
+ packedSize: number;
25
+ /** Last modified date */
26
+ modified: Date;
27
+ /** File attributes (e.g., 'D' for directory, 'A' for archive) */
28
+ attributes: string;
29
+ /** CRC checksum */
30
+ crc: string;
31
+ /** Compression method used */
32
+ method: string;
33
+ /** Whether entry is a directory */
34
+ isDirectory: boolean;
35
+ /** Whether entry is encrypted */
36
+ encrypted?: boolean;
37
+ /** Whether entry is a symbolic link */
38
+ isSymlink?: boolean;
39
+ }
40
+ /**
41
+ * Archive operation result
42
+ */
43
+ interface ArchiveResult {
44
+ /** Whether operation succeeded */
45
+ success: boolean;
46
+ /** Full command that was executed */
47
+ command: string;
48
+ /** Standard output from 7-Zip */
49
+ stdout: string;
50
+ /** Standard error from 7-Zip */
51
+ stderr: string;
52
+ /** Exit code (0 = success) */
53
+ exitCode: number | null;
54
+ }
55
+ /**
56
+ * List operation result
57
+ */
58
+ interface ListResult {
59
+ /** Archive file path */
60
+ archive: string;
61
+ /** Total uncompressed size in bytes */
62
+ size: number;
63
+ /** Total compressed size in bytes */
64
+ packedSize: number;
65
+ /** Number of files in archive */
66
+ fileCount: number;
67
+ /** Number of directories in archive */
68
+ dirCount: number;
69
+ /** Array of archive entries */
70
+ entries: ArchiveEntry[];
71
+ /** Archive format (if detected) */
72
+ format?: string;
73
+ /** Whether archive is encrypted */
74
+ encrypted?: boolean;
75
+ /** Whether archive is solid */
76
+ solid?: boolean;
77
+ }
78
+ /**
79
+ * Hash calculation result
80
+ */
81
+ interface HashResult {
82
+ /** File path */
83
+ file: string;
84
+ /** Hash values keyed by filename */
85
+ hashes: Record<string, string>;
86
+ /** Total file size in bytes */
87
+ size: number;
88
+ }
89
+ /**
90
+ * Test result
91
+ */
92
+ interface TestResult {
93
+ /** Archive file path */
94
+ archive: string;
95
+ /** Whether all files passed integrity check */
96
+ ok: boolean;
97
+ /** List of any errors encountered */
98
+ errors: string[];
99
+ /** Number of files tested */
100
+ filesTested?: number;
101
+ }
102
+ /**
103
+ * Statistics for operations
104
+ */
105
+ interface OperationStats {
106
+ /** Number of files processed */
107
+ filesProcessed: number;
108
+ /** Total uncompressed size in bytes */
109
+ totalSize: number;
110
+ /** Total compressed size in bytes */
111
+ compressedSize: number;
112
+ /** Compression ratio (compressed/original) */
113
+ ratio: number;
114
+ /** Time elapsed in milliseconds */
115
+ elapsed: number;
116
+ }
117
+ /**
118
+ * Archive information
119
+ */
120
+ interface ArchiveInfo {
121
+ /** Archive file path */
122
+ path: string;
123
+ /** Archive format */
124
+ format: string;
125
+ /** Physical size on disk */
126
+ physicalSize: number;
127
+ /** Headers size */
128
+ headersSize?: number;
129
+ /** Whether archive is solid */
130
+ solid?: boolean;
131
+ /** Number of blocks (for solid archives) */
132
+ blocks?: number;
133
+ /** Compression method */
134
+ method?: string;
135
+ }
136
+
137
+ /**
138
+ * Compression-related types
139
+ */
140
+ /**
141
+ * Compression levels (0 = store, 9 = ultra)
142
+ */
143
+ type CompressionLevel = 0 | 1 | 3 | 5 | 7 | 9;
144
+ /**
145
+ * Compression methods
146
+ */
147
+ type CompressionMethod = 'copy' | 'deflate' | 'deflate64' | 'bzip2' | 'lzma' | 'lzma2' | 'lz77' | 'ppmd' | 'delta';
148
+ /**
149
+ * Volume size for splitting (e.g., '10m', '100k', '1g')
150
+ */
151
+ type VolumeSize = string;
152
+ /**
153
+ * Hash types
154
+ */
155
+ type HashType = 'crc32' | 'crc64' | 'sha1' | 'sha256' | 'blake2sp';
156
+ /**
157
+ * Compression options
158
+ */
159
+ interface CompressionOptions {
160
+ /** Compression level (0-9) */
161
+ level?: CompressionLevel;
162
+ /** Compression method */
163
+ method?: CompressionMethod;
164
+ /** Dictionary size (e.g., '32m', '64m') */
165
+ dictionarySize?: string;
166
+ /** Word size */
167
+ wordSize?: number;
168
+ /** Block size for solid compression */
169
+ blockSize?: string;
170
+ /** Number of CPU threads */
171
+ threads?: number;
172
+ }
173
+ /**
174
+ * Compression presets for common use cases
175
+ */
176
+ interface CompressionPreset {
177
+ name: string;
178
+ level: CompressionLevel;
179
+ method?: CompressionMethod;
180
+ dictionarySize?: string;
181
+ solid?: boolean;
182
+ }
183
+ /**
184
+ * Predefined compression presets
185
+ */
186
+ declare const COMPRESSION_PRESETS: Record<string, CompressionPreset>;
187
+
188
+ /**
189
+ * Option interfaces for 7-Zip operations
190
+ */
191
+
192
+ /**
193
+ * Password protection options
194
+ */
195
+ interface PasswordOptions {
196
+ /** Password to encrypt/decrypt archive */
197
+ password: string;
198
+ /** Encrypt filenames (7z format only) */
199
+ encryptFilenames?: boolean;
200
+ }
201
+ /**
202
+ * Progress callback type
203
+ */
204
+ type ProgressCallback = (progress: {
205
+ /** Current file being processed */
206
+ file?: string;
207
+ /** Percentage complete (0-100) */
208
+ percent?: number;
209
+ /** Total bytes to process */
210
+ total?: number;
211
+ /** Bytes processed so far */
212
+ processed?: number;
213
+ }) => void;
214
+ /**
215
+ * Options for add operation
216
+ */
217
+ interface AddOptions extends Partial<PasswordOptions> {
218
+ /** Archive type (default: '7z') */
219
+ type?: ArchiveType;
220
+ /** Compression level (0-9) */
221
+ level?: CompressionLevel;
222
+ /** Compression method */
223
+ method?: CompressionMethod;
224
+ /** Dictionary size (e.g., '32m', '64m') */
225
+ dictionarySize?: string;
226
+ /** Word size for compression */
227
+ wordSize?: number;
228
+ /** Number of CPU threads to use */
229
+ threads?: number;
230
+ /** Create solid archive (better compression, slower random access) */
231
+ solid?: boolean;
232
+ /** Create self-extracting archive */
233
+ sfx?: boolean;
234
+ /** Create multi-volume archive (e.g., '10m', '100k') */
235
+ volumes?: VolumeSize;
236
+ /** Wildcard patterns for files to exclude */
237
+ excludePatterns?: string[];
238
+ /** Wildcard patterns for files to include */
239
+ includePatterns?: string[];
240
+ /** Recurse into subdirectories (default: true) */
241
+ recursive?: boolean;
242
+ /** Follow symbolic links instead of storing them */
243
+ followSymlinks?: boolean;
244
+ /** Store symlinks as symlinks (Unix only) */
245
+ storeSymlinks?: boolean;
246
+ /** Progress callback */
247
+ onProgress?: ProgressCallback;
248
+ /** Store file timestamps */
249
+ storeTimestamps?: boolean;
250
+ /** Working directory */
251
+ cwd?: string;
252
+ }
253
+ /**
254
+ * Options for extract operation
255
+ */
256
+ interface ExtractOptions extends Partial<PasswordOptions> {
257
+ /** Output directory */
258
+ outputDir?: string;
259
+ /** Specific files to extract (wildcards supported) */
260
+ files?: string[];
261
+ /** Wildcard patterns for files to exclude */
262
+ excludePatterns?: string[];
263
+ /** Wildcard patterns for files to include */
264
+ includePatterns?: string[];
265
+ /** Overwrite existing files */
266
+ overwrite?: boolean;
267
+ /** Preserve file permissions (Unix only) */
268
+ preservePermissions?: boolean;
269
+ /** Extract with full paths */
270
+ fullPaths?: boolean;
271
+ /** Progress callback */
272
+ onProgress?: ProgressCallback;
273
+ /** Flatten directory structure */
274
+ flat?: boolean;
275
+ }
276
+ /**
277
+ * Options for list operation
278
+ */
279
+ interface ListOptions {
280
+ /** Include technical information */
281
+ technical?: boolean;
282
+ /** Enable verbose mode */
283
+ verbose?: boolean;
284
+ /** Exclude paths from output */
285
+ excludePaths?: boolean;
286
+ /** Password for encrypted archives */
287
+ password?: string;
288
+ }
289
+ /**
290
+ * Options for update operation
291
+ */
292
+ interface UpdateOptions {
293
+ /** Files to add to archive */
294
+ add?: string[];
295
+ /** Files to update (freshen) in archive */
296
+ update?: string[];
297
+ /** Files/patterns to delete from archive */
298
+ delete?: string[];
299
+ /** Progress callback */
300
+ /** Progress callback */
301
+ onProgress?: ProgressCallback;
302
+ /** Working directory */
303
+ cwd?: string;
304
+ }
305
+ /**
306
+ * Options for rename operation
307
+ */
308
+ interface RenameOptions {
309
+ /** Progress callback */
310
+ onProgress?: ProgressCallback;
311
+ }
312
+ /**
313
+ * Extended exec options with 7-Zip specific settings
314
+ */
315
+ interface ExtendedExecOptions extends ExecOptions {
316
+ /** Override 7-Zip binary path */
317
+ binaryPath?: string;
318
+ /** Timeout in milliseconds */
319
+ timeout?: number;
320
+ /** Progress callback */
321
+ onProgress?: ProgressCallback;
322
+ }
323
+ /**
324
+ * Generic command options
325
+ */
326
+ interface CommandOptions extends Partial<PasswordOptions>, ExtendedExecOptions {
327
+ }
328
+
329
+ /**
330
+ * Type definitions for 7-Zip wrapper
331
+ *
332
+ * Re-exports all types from domain-specific files for convenience.
333
+ */
334
+
335
+ /**
336
+ * File matching patterns (glob-style)
337
+ */
338
+ type WildcardPattern = string;
339
+
340
+ /**
341
+ * 7-Zip command implementations
342
+ */
343
+
344
+ /**
345
+ * Add files to archive
346
+ */
347
+ declare function add(archive: string, files: string | string[], options?: AddOptions): Promise<ArchiveResult>;
348
+ /**
349
+ * Extract files from archive
350
+ */
351
+ declare function extract(archive: string, options?: ExtractOptions): Promise<ArchiveResult>;
352
+ /**
353
+ * List archive contents
354
+ */
355
+ declare function list(archive: string, options?: ListOptions): Promise<ListResult>;
356
+ /**
357
+ * Update existing archive
358
+ */
359
+ declare function update(archive: string, options: UpdateOptions): Promise<ArchiveResult>;
360
+ /**
361
+ * Delete files from archive
362
+ */
363
+ declare function deleteFiles(archive: string, wildcards: string | string[]): Promise<ArchiveResult>;
364
+ /**
365
+ * Test archive integrity
366
+ */
367
+ declare function test(archive: string, password?: string): Promise<TestResult>;
368
+ /**
369
+ * Calculate file hashes
370
+ */
371
+ declare function hash(files: string | string[], hashType?: HashType): Promise<HashResult>;
372
+ /**
373
+ * Calculate archive hashes
374
+ */
375
+ declare function hashArchive(archive: string, hashType?: HashType): Promise<HashResult>;
376
+ /**
377
+ * Get archive info
378
+ */
379
+ declare function info(archive: string): Promise<string>;
380
+ /**
381
+ * Rename files in archive
382
+ */
383
+ declare function rename(archive: string, oldName: string, newName: string): Promise<ArchiveResult>;
384
+ /**
385
+ * Extract and repack to different format
386
+ */
387
+ declare function convert(sourceArchive: string, targetFormat: string, outputArchive?: string): Promise<ArchiveResult>;
388
+ /**
389
+ * Benchmark compression
390
+ */
391
+ declare function benchmark(methods?: string[], iterations?: number): Promise<ArchiveResult>;
392
+
393
+ /**
394
+ * Custom error classes for 7-Zip wrapper
395
+ */
396
+ /**
397
+ * Base error class for all 7-Zip related errors
398
+ */
399
+ declare class ZipWrapperError extends Error {
400
+ readonly code?: string | undefined;
401
+ readonly exitCode?: number | null | undefined;
402
+ constructor(message: string, code?: string | undefined, exitCode?: number | null | undefined);
403
+ }
404
+ /**
405
+ * Thrown when the 7-Zip binary cannot be found
406
+ */
407
+ declare class BinaryNotFoundError extends ZipWrapperError {
408
+ constructor(searchedPaths?: string[]);
409
+ }
410
+ /**
411
+ * Thrown when an archive file cannot be found
412
+ */
413
+ declare class ArchiveNotFoundError extends ZipWrapperError {
414
+ readonly archivePath: string;
415
+ constructor(archivePath: string);
416
+ }
417
+ /**
418
+ * Thrown when a password is required but not provided
419
+ */
420
+ declare class PasswordRequiredError extends ZipWrapperError {
421
+ readonly archivePath?: string | undefined;
422
+ constructor(archivePath?: string | undefined);
423
+ }
424
+ /**
425
+ * Thrown when the provided password is incorrect
426
+ */
427
+ declare class WrongPasswordError extends ZipWrapperError {
428
+ readonly archivePath?: string | undefined;
429
+ constructor(archivePath?: string | undefined);
430
+ }
431
+ /**
432
+ * Thrown when an archive is corrupted or damaged
433
+ */
434
+ declare class CorruptArchiveError extends ZipWrapperError {
435
+ readonly archivePath: string;
436
+ readonly details?: string | undefined;
437
+ constructor(archivePath: string, details?: string | undefined);
438
+ }
439
+ /**
440
+ * Thrown when compression fails
441
+ */
442
+ declare class CompressionError extends ZipWrapperError {
443
+ constructor(message: string, exitCode?: number | null);
444
+ }
445
+ /**
446
+ * Thrown when extraction fails
447
+ */
448
+ declare class ExtractionError extends ZipWrapperError {
449
+ constructor(message: string, exitCode?: number | null);
450
+ }
451
+ /**
452
+ * Thrown when an unsupported format is encountered
453
+ */
454
+ declare class UnsupportedFormatError extends ZipWrapperError {
455
+ readonly format: string;
456
+ constructor(format: string);
457
+ }
458
+ /**
459
+ * Thrown when the operation times out
460
+ */
461
+ declare class TimeoutError extends ZipWrapperError {
462
+ readonly timeoutMs: number;
463
+ readonly operation?: string | undefined;
464
+ constructor(timeoutMs: number, operation?: string | undefined);
465
+ }
466
+ /**
467
+ * Parse error message from 7-Zip output and return appropriate error
468
+ */
469
+ declare function parseZipWrapperError(stderr: string, stdout: string, exitCode: number | null, archivePath?: string): ZipWrapperError;
470
+
471
+ /**
472
+ * 7-Zip wrapper for Node.js
473
+ *
474
+ * A comprehensive wrapper around the 7-Zip command-line utility.
475
+ * Provides a clean, promise-based API for all 7-Zip operations.
476
+ *
477
+ * @packageDocumentation
478
+ */
479
+
480
+ /**
481
+ * Main ZipWrapper class for object-oriented usage
482
+ *
483
+ * @example
484
+ * ```typescript
485
+ * const zip = new ZipWrapper();
486
+ *
487
+ * // Create archive
488
+ * await zip.add('backup.7z', ['src/', 'package.json']);
489
+ *
490
+ * // Extract archive
491
+ * await zip.extract('backup.7z', { outputDir: 'restored/' });
492
+ * ```
493
+ */
494
+ declare class ZipWrapper {
495
+ binaryPath?: string | undefined;
496
+ /**
497
+ * Create a new ZipWrapper instance
498
+ * @param binaryPath - Optional custom path to 7za binary
499
+ */
500
+ constructor(binaryPath?: string | undefined);
501
+ /**
502
+ * Add files to archive
503
+ * @param archive - Path to the archive file
504
+ * @param files - Files or directories to add (supports wildcards)
505
+ * @param options - Compression options
506
+ *
507
+ * @example
508
+ * ```typescript
509
+ * await zip.add('archive.7z', 'src/', {
510
+ * level: 9,
511
+ * method: 'lzma2',
512
+ * password: 'secret'
513
+ * });
514
+ * ```
515
+ */
516
+ add(archive: string, files: string | string[], options?: AddOptions): Promise<ArchiveResult>;
517
+ /**
518
+ * Extract files from archive
519
+ * @param archive - Path to the archive file
520
+ * @param options - Extraction options
521
+ */
522
+ extract(archive: string, options?: ExtractOptions): Promise<ArchiveResult>;
523
+ /**
524
+ * List archive contents
525
+ * @param archive - Path to the archive file
526
+ * @param options - List options
527
+ */
528
+ list(archive: string, options?: ListOptions): Promise<ListResult>;
529
+ /**
530
+ * Update existing archive
531
+ * @param archive - Path to the archive file
532
+ * @param options - Update options
533
+ */
534
+ update(archive: string, options: UpdateOptions): Promise<ArchiveResult>;
535
+ /**
536
+ * Delete files from archive
537
+ * @param archive - Path to the archive file
538
+ * @param wildcards - Patterns to match files to delete
539
+ */
540
+ delete(archive: string, wildcards: string | string[]): Promise<ArchiveResult>;
541
+ /**
542
+ * Test archive integrity
543
+ * @param archive - Path to the archive file
544
+ * @param password - Optional password for encrypted archives
545
+ */
546
+ test(archive: string, password?: string): Promise<TestResult>;
547
+ /**
548
+ * Add file to archive from stream
549
+ * @param archive Path to archive
550
+ * @param filename Filename inside archive
551
+ * @param stream Input stream
552
+ * @param options Compression options
553
+ */
554
+ addFromStream(archive: string, filename: string, stream: Readable, options?: AddOptions): Promise<void>;
555
+ /**
556
+ * Extract file from archive to stream
557
+ * @param archive Path to archive
558
+ * @param filename Filename to extract
559
+ * @returns Readable stream of file content
560
+ */
561
+ extractToStream(archive: string, filename: string, options?: CommandOptions): Readable;
562
+ /**
563
+ * Extract file from archive to buffer
564
+ * @param archive Path to archive
565
+ * @param filename Filename to extract
566
+ * @returns Promise resolving to Buffer of file content
567
+ */
568
+ extractToBuffer(archive: string, filename: string, options?: CommandOptions): Promise<Buffer>;
569
+ /**
570
+ * Calculate file hashes
571
+ * @param files - Files to hash (e.g. `['file.txt']` or `'*.txt'`)
572
+ * @param hashType - Hash algorithm (default: 'crc32')
573
+ * @returns Map of file paths to hashes
574
+ *
575
+ * @example
576
+ * ```typescript
577
+ * const hashes = await zip.hash(['file.txt'], 'sha256');
578
+ * console.log(hashes.get('file.txt'));
579
+ * ```
580
+ */
581
+ hash(files: string | string[], hashType?: HashType): Promise<HashResult>;
582
+ /**
583
+ * Get archive info
584
+ * @param archive - Path to the archive file
585
+ */
586
+ info(archive: string): Promise<string>;
587
+ /**
588
+ * Run benchmark
589
+ * @param methods - Optional compression methods to benchmark
590
+ * @param iterations - Optional number of iterations
591
+ */
592
+ benchmark(methods?: string[], iterations?: number): Promise<ArchiveResult>;
593
+ /**
594
+ * Convert archive to different format
595
+ * @param sourceArchive - Source archive path
596
+ * @param targetFormat - Target format (7z, zip, etc.)
597
+ * @param outputArchive - Optional output path
598
+ */
599
+ convert(sourceArchive: string, targetFormat: string, outputArchive?: string): Promise<ArchiveResult>;
600
+ }
601
+ /**
602
+ * Default ZipWrapper instance
603
+ */
604
+ declare const zipWrapper: ZipWrapper;
605
+ /**
606
+ * Quick helper functions for common operations
607
+ */
608
+ declare const quick: {
609
+ /**
610
+ * Quick ZIP creation with max compression
611
+ * @param files - Files to archive
612
+ * @param output - Output archive path
613
+ */
614
+ zip(files: string | string[], output: string): Promise<ArchiveResult>;
615
+ /**
616
+ * Quick 7z creation with max compression
617
+ * @param files - Files to archive
618
+ * @param output - Output archive path
619
+ */
620
+ sevenz(files: string | string[], output: string): Promise<ArchiveResult>;
621
+ /**
622
+ * Quick extraction to directory
623
+ * @param archive - Archive to extract
624
+ * @param outputDir - Optional output directory
625
+ */
626
+ extract(archive: string, outputDir?: string): Promise<ArchiveResult>;
627
+ /**
628
+ * Quick listing
629
+ * @param archive - Archive to list
630
+ */
631
+ list(archive: string): Promise<ListResult>;
632
+ /**
633
+ * Quick integrity test
634
+ * @param archive - Archive to test
635
+ */
636
+ test(archive: string): Promise<TestResult>;
637
+ };
638
+
639
+ export { type AddOptions, type ArchiveEntry, type ArchiveFormat, type ArchiveInfo, ArchiveNotFoundError, type ArchiveResult, type ArchiveType, BinaryNotFoundError, COMPRESSION_PRESETS, CompressionError, type CompressionLevel, type CompressionMethod, type CompressionOptions, type CompressionPreset, CorruptArchiveError, type ExtendedExecOptions, type ExtractOptions, ExtractionError, type HashResult, type HashType, type ListOptions, type ListResult, type OperationStats, type PasswordOptions, PasswordRequiredError, type ProgressCallback, type RenameOptions, type TestResult, TimeoutError, UnsupportedFormatError, type UpdateOptions, type VolumeSize, type WildcardPattern, WrongPasswordError, ZipWrapper, ZipWrapperError, add, benchmark, convert, deleteFiles, extract, hash, hashArchive, info, list, parseZipWrapperError, quick, rename, test, update, zipWrapper };
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ 'use strict';var O=require('fs'),child_process=require('child_process'),N=require('path'),lt=require('os');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var O__default=/*#__PURE__*/_interopDefault(O);var N__default=/*#__PURE__*/_interopDefault(N);var lt__default=/*#__PURE__*/_interopDefault(lt);var J={fastest:{name:"Fastest",level:1},fast:{name:"Fast",level:3},normal:{name:"Normal",level:5},maximum:{name:"Maximum",level:7},ultra:{name:"Ultra",level:9,method:"lzma2",dictionarySize:"64m",solid:true}};var A={SUCCESS:0,WARNING:1};var Q={win32:"7za.exe",linux:"7za",darwin:"7za"},i={TYPE:"-t",LEVEL:"-mx",METHOD:"-m0",DICT_SIZE:"-md",WORD_SIZE:"-mfbc",THREADS:"-mmt",SOLID:"-ms",ENCRYPT_HEADERS:"-mhe",PASSWORD:"-p",OUTPUT:"-o",OVERWRITE_ALL:"-aoa",SKIP_EXISTING:"-aos",TECH_INFO:"-slt",VERBOSE:"-bb1",RECURSE:"-r",NO_RECURSE:"-r-",INCLUDE:"-i!",EXCLUDE:"-x!",STORE_SYMLINKS:"-snl",STORE_HARDLINKS:"-snh",TIMESTAMPS:"-bt",YES:"-y",SFX:"-sfx",VOLUME:"-v",PRESERVE_PERMISSIONS:"-spf"},d={ADD:"a",EXTRACT:"x",EXTRACT_FLAT:"e",LIST:"l",TEST:"t",UPDATE:"u",DELETE:"d",RENAME:"rn",HASH:"h",INFO:"i",BENCHMARK:"b"};var tt=3e4;var p=class extends Error{constructor(t,s,n){super(t);this.code=s;this.exitCode=n;this.name="ZipWrapperError",Error.captureStackTrace?.(this,this.constructor);}},y=class extends p{constructor(r=[]){let t=r.length>0?` Searched: ${r.join(", ")}`:"";super(`7-Zip binary not found.${t}`,"BINARY_NOT_FOUND"),this.name="BinaryNotFoundError";}},S=class extends p{constructor(t){super(`Archive not found: ${t}`,"ARCHIVE_NOT_FOUND");this.archivePath=t;this.name="ArchiveNotFoundError";}},T=class extends p{constructor(t){super(t?`Password required for archive: ${t}`:"Password required for encrypted archive","PASSWORD_REQUIRED");this.archivePath=t;this.name="PasswordRequiredError";}},C=class extends p{constructor(t){super(t?`Wrong password for archive: ${t}`:"Wrong password for encrypted archive","WRONG_PASSWORD");this.archivePath=t;this.name="WrongPasswordError";}},w=class extends p{constructor(t,s){super(s?`Corrupt archive: ${t} - ${s}`:`Corrupt archive: ${t}`,"CORRUPT_ARCHIVE");this.archivePath=t;this.details=s;this.name="CorruptArchiveError";}},b=class extends p{constructor(r,t){super(r,"COMPRESSION_ERROR",t),this.name="CompressionError";}},_=class extends p{constructor(r,t){super(r,"EXTRACTION_ERROR",t),this.name="ExtractionError";}},D=class extends p{constructor(t){super(`Unsupported archive format: ${t}`,"UNSUPPORTED_FORMAT");this.format=t;this.name="UnsupportedFormatError";}},x=class extends p{constructor(t,s){super(s?`Operation '${s}' timed out after ${t}ms`:`Operation timed out after ${t}ms`,"TIMEOUT");this.timeoutMs=t;this.operation=s;this.name="TimeoutError";}};function L(e,r,t,s){let n=`${e}
2
+ ${r}`.toLowerCase();return n.includes("wrong password")||n.includes("incorrect password")?new C(s):n.includes("enter password")||n.includes("password is required")||n.includes("encrypted")?new T(s):n.includes("data error")||n.includes("crc failed")||n.includes("headers error")||n.includes("unexpected end")?new w(s||"unknown",e.trim()):(n.includes("cannot find archive")||n.includes("cannot open"))&&s?new S(s):new b(e.trim()||"Unknown 7-Zip error",t)}function ct(e){let r=e;for(;;){if(O__default.default.existsSync(N__default.default.join(r,"package.json")))return r;let t=N__default.default.dirname(r);if(t===r)return e;r=t;}}var ut=ct(__dirname),rt=N__default.default.join(ut,"bin");var I=null;function M(){return I||(I=N__default.default.join(rt,Q[lt__default.default.platform()]),I)}M();function ft(e){return e||M()}function ht(e){let r=e||M();if(!O__default.default.existsSync(r))return false;try{return child_process.execSync(`"${r}"`,{timeout:5e3,windowsHide:!0,stdio:"ignore"}),!0}catch{return true}}function et(e){let r=ft(e);if(!ht(r)){let t=[r];throw new y(t)}return r}function z(e,r){let t=et(r?.binaryPath);try{return child_process.spawn(t,e,{...r,windowsHide:!0,stdio:["pipe","pipe","pipe"]})}catch(s){throw new p(`Failed to spawn 7-Zip process: ${s.message}`)}}async function h(e,r){let s=r?.timeout??tt;return new Promise((n,o)=>{let l=[],a=[],u,c,Z=false;try{u=z(e,r);}catch(m){o(m);return}s>0&&(c=setTimeout(()=>{Z=true,u.kill("SIGTERM"),o(new x(s,`7za ${e[0]}`));},s)),u.stdout?.on("data",m=>{l.push(m),r?.onProgress&&gt(m.toString("utf-8"),r.onProgress);}),u.stderr?.on("data",m=>{a.push(m);}),u.on("close",m=>{if(c&&clearTimeout(c),Z)return;let K=Buffer.concat(l).toString("utf-8"),j=Buffer.concat(a).toString("utf-8"),G={success:m===A.SUCCESS,command:`7za ${e.join(" ")}`,stdout:K,stderr:j,exitCode:m};if(m===A.SUCCESS||m===A.WARNING)n(G);else {let q=L(j,K,m,r?.archivePath);Object.assign(q,{result:G}),o(q);}}),u.on("error",m=>{c&&clearTimeout(c),o(new p(`Failed to execute 7-Zip: ${m.message}`));});})}function gt(e,r){let t=e.match(/(\d+)%/);t&&r({percent:parseInt(t[1],10)});let s=e.match(/- (.+)$/m);s&&r({file:s[1].trim()});}function st(e){let r=e.split(`
3
+ `),t=[],s=0,n=0,o=0,l=0,a=null;for(let u of r){let c=u.trim();c.startsWith("Path = ")?(a?.path&&t.push(a),a={path:c.substring(7),size:0,packedSize:0,modified:new Date,attributes:"",crc:"",method:"",isDirectory:false}):a&&(c.startsWith("Size = ")?a.size=parseInt(c.substring(7),10)||0:c.startsWith("Packed Size = ")?a.packedSize=parseInt(c.substring(14),10)||0:c.startsWith("Modified = ")?a.modified=new Date(c.substring(11)):c.startsWith("Attributes = ")?(a.attributes=c.substring(13),a.isDirectory=a.attributes.includes("D")):c.startsWith("CRC = ")?a.crc=c.substring(6):c.startsWith("Method = ")?a.method=c.substring(9):c.startsWith("Encrypted = ")&&(a.encrypted=c.substring(12)==="+"));}a?.path&&t.push(a);for(let u of t)u.isDirectory?l++:(o++,s+=u.size,n+=u.packedSize);return {entries:t,stats:{totalSize:s,totalPackedSize:n,fileCount:o,dirCount:l,ratio:s>0?n/s:0}}}function U(e){let r=e.split(`
4
+ `),t={};for(let s of r){let n=s.match(/(\w+)\s+for data:\s+([0-9A-Fa-f]+)/);if(n){t[n[1].toLowerCase()]=n[2];continue}let o=s.match(/^([0-9A-Fa-f]+)\s+(.+)$/);if(o){let l=o[1],a=o[2].trim();t[a]=l;}}return t}function nt(e){let r=e.split(`
5
+ `),t=[],s=true;for(let n of r){let o=n.toLowerCase();(o.includes("error")||o.includes("failed")||o.includes("cannot")||o.includes("crc failed"))&&(t.push(n.trim()),s=false);}return e.includes("Everything is Ok")&&(s=true,t.length=0),{ok:s,errors:t}}function f(e,r,t,s){let n=[e];return n.push(...r),t&&n.push(t),s&&s.length>0&&n.push(...s),n}function E(e){if(!O__default.default.existsSync(e))throw new S(e)}async function it(e,r,t,s={}){let n=[`-si${r}`];s.password&&n.push(`-p${s.password}`),s.level&&n.push(`-mx=${s.level}`),s.method&&n.push(`-m0=${s.method}`),n.push(i.YES);let o=f(d.ADD,n,e);return new Promise((l,a)=>{try{let u=z(o,{...s,archivePath:e});t.pipe(u.stdin),u.on("close",c=>{c===0?l():a(new Error(`7-Zip exited with code ${c}`));}),u.on("error",c=>a(c)),t.on("error",c=>a(c));}catch(u){a(u);}})}function H(e,r,t={}){E(e);let s=["-so"];t.password&&s.push(`-p${t.password}`),s.push(i.YES);let n=f(d.EXTRACT,s,e,[r]),o=z(n,{...t,archivePath:e});if(!o.stdout)throw new p("Failed to get stdout from 7-Zip process");return o.stdout}async function ot(e,r,t={}){let s=H(e,r,t);return new Promise((n,o)=>{let l=[];s.on("data",a=>l.push(Buffer.from(a))),s.on("error",a=>o(a)),s.on("end",()=>n(Buffer.concat(l)));})}async function R(e,r,t){let s=[];if(t?.type&&s.push(`${i.TYPE}${t.type}`),t?.level!==void 0&&s.push(`${i.LEVEL}=${t.level}`),t?.method&&s.push(`${i.METHOD}=${t.method}`),t?.dictionarySize&&s.push(`${i.DICT_SIZE}=${t.dictionarySize}`),t?.wordSize!==void 0&&s.push(`${i.WORD_SIZE}=${t.wordSize}`),t?.threads!==void 0&&s.push(`${i.THREADS}${t.threads}`),t?.solid&&s.push(`${i.SOLID}=on`),t?.sfx&&s.push(i.SFX),t?.volumes&&s.push(`${i.VOLUME}${t.volumes}`),t?.password&&(s.push(`${i.PASSWORD}${t.password}`),t.encryptFilenames&&s.push(`${i.ENCRYPT_HEADERS}=on`)),t?.includePatterns)for(let o of t.includePatterns)s.push(`${i.INCLUDE}${o}`);if(t?.excludePatterns)for(let o of t.excludePatterns)s.push(`${i.EXCLUDE}${o}`);t?.recursive===false?s.push(i.NO_RECURSE):s.push(i.RECURSE),t?.followSymlinks&&(s.push(`${i.STORE_HARDLINKS}-`),s.push(`${i.STORE_SYMLINKS}-`)),t?.storeSymlinks&&(s.push(i.STORE_HARDLINKS),s.push(i.STORE_SYMLINKS)),s.push(i.YES);let n=Array.isArray(r)?r:[r];return h(f(d.ADD,s,e,n),{onProgress:t?.onProgress,cwd:t?.cwd})}async function P(e,r){E(e);let t=[i.YES];if(r?.outputDir&&t.push(`${i.OUTPUT}${r.outputDir}`),r?.password&&t.push(`${i.PASSWORD}${r.password}`),r?.includePatterns)for(let o of r.includePatterns)t.push(`${i.INCLUDE}${o}`);if(r?.excludePatterns)for(let o of r.excludePatterns)t.push(`${i.EXCLUDE}${o}`);r?.overwrite===false?t.push(i.SKIP_EXISTING):r?.overwrite===true&&t.push(i.OVERWRITE_ALL),r?.preservePermissions&&t.push(i.PRESERVE_PERMISSIONS);let s=r?.files||[],n=r?.flat?d.EXTRACT_FLAT:d.EXTRACT;return h(f(n,t,e,s),{archivePath:e,onProgress:r?.onProgress})}async function v(e,r){E(e);let t=[i.TECH_INFO];r?.verbose&&t.push(i.VERBOSE),r?.password&&t.push(`${i.PASSWORD}${r.password}`);let s=await h(f(d.LIST,t,e),{archivePath:e}),n=st(s.stdout);return {archive:e,size:n.stats.totalSize,packedSize:n.stats.totalPackedSize,fileCount:n.stats.fileCount,dirCount:n.stats.dirCount,entries:n.entries}}async function B(e,r){E(e);let t=[i.YES],s=[];if(r.add&&s.push(...r.add),r.update)for(let n of r.update)s.push(`!${n}`);return h(f(d.UPDATE,t,e,s),{archivePath:e,onProgress:r.onProgress,cwd:r.cwd})}async function F(e,r){E(e);let t=[i.YES],s=Array.isArray(r)?r:[r];return h(f(d.DELETE,t,e,s),{archivePath:e})}async function $(e,r){E(e);let t=[i.TIMESTAMPS];r&&t.push(`${i.PASSWORD}${r}`);let s=await h(f(d.TEST,t,e),{archivePath:e}),n=nt(s.stdout+s.stderr);return {archive:e,ok:s.success&&n.ok,errors:n.errors}}async function k(e,r="crc32"){let t=[`-scrc${r}`],s=Array.isArray(e)?e:[e],n=0;for(let a of s)try{let u=O__default.default.statSync(a);n+=u.size;}catch{}let o=await h(f(d.HASH,t,void 0,s)),l=U(o.stdout);return {file:Array.isArray(e)?e[0]:e,hashes:l,size:n}}async function St(e,r="crc32"){E(e);let t=[`-scrc${r}`],s=await h(f(d.HASH,t,e),{archivePath:e}),n=U(s.stdout),o=O__default.default.statSync(e);return {file:e,hashes:n,size:o.size}}async function W(e){return E(e),(await h(f(d.INFO,[],e),{archivePath:e})).stdout}async function Rt(e,r,t){E(e);let s=[i.YES];return h(f(d.RENAME,s,e,[r,t]),{archivePath:e})}async function Y(e,r,t){E(e);let s=`${e}_temp_${Date.now()}`;O__default.default.mkdirSync(s,{recursive:true});try{await P(e,{outputDir:s});let n=t||e.replace(/\.[^.]+$/,`.${r}`);return await R(n,s,{type:r})}finally{O__default.default.rmSync(s,{recursive:true,force:true});}}async function X(e,r){let t=[i.VERBOSE];if(e)for(let s of e)t.push(`-mm=${s}`);return r&&t.push(`-mmt=${r}`),h(f(d.BENCHMARK,t))}var V=class{constructor(r){this.binaryPath=r;}async add(r,t,s){return R(r,t,s)}async extract(r,t){return P(r,t)}async list(r,t){return v(r,t)}async update(r,t){return B(r,t)}async delete(r,t){return F(r,t)}async test(r,t){return $(r,t)}async addFromStream(r,t,s,n){return it(r,t,s,n)}extractToStream(r,t,s){return H(r,t,s)}async extractToBuffer(r,t,s){return ot(r,t,s)}async hash(r,t){return k(r,t)}async info(r){return W(r)}async benchmark(r,t){return X(r,t)}async convert(r,t,s){return Y(r,t,s)}},rr=new V,er={async zip(e,r){return R(r,e,{type:"zip",level:9})},async sevenz(e,r){return R(r,e,{type:"7z",level:9})},async extract(e,r){return P(e,{outputDir:r})},async list(e){return v(e)},async test(e){return $(e)}};exports.ArchiveNotFoundError=S;exports.BinaryNotFoundError=y;exports.COMPRESSION_PRESETS=J;exports.CompressionError=b;exports.CorruptArchiveError=w;exports.ExtractionError=_;exports.PasswordRequiredError=T;exports.TimeoutError=x;exports.UnsupportedFormatError=D;exports.WrongPasswordError=C;exports.ZipWrapper=V;exports.ZipWrapperError=p;exports.add=R;exports.benchmark=X;exports.convert=Y;exports.deleteFiles=F;exports.extract=P;exports.hash=k;exports.hashArchive=St;exports.info=W;exports.list=v;exports.parseZipWrapperError=L;exports.quick=er;exports.rename=Rt;exports.test=$;exports.update=B;exports.zipWrapper=rr;