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.
- package/LICENSE +21 -0
- package/README.md +180 -0
- package/dist/cli.js +44 -0
- package/dist/index.d.mts +639 -0
- package/dist/index.d.ts +639 -0
- package/dist/index.js +5 -0
- package/dist/index.mjs +5 -0
- package/dist/postinstall.js +3 -0
- package/package.json +84 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Rashed Iqbal
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
# 7zip-wrapper
|
|
2
|
+
|
|
3
|
+
> **A powerful, type-safe Node.js wrapper for 7-Zip with native Stream & Buffer support.**
|
|
4
|
+
|
|
5
|
+
[](https://www.npmjs.com/package/7zip-wrapper)
|
|
6
|
+
[](https://opensource.org/licenses/MIT)
|
|
7
|
+
[](https://www.typescriptlang.org/)
|
|
8
|
+
|
|
9
|
+
**7zip-wrapper** provides a modern, Promise-based API for 7-Zip operations. It bundles the 7-Zip binary for Windows, Linux, and macOS, ensuring zero configuration and reliable execution everywhere.
|
|
10
|
+
|
|
11
|
+
## ✨ Features
|
|
12
|
+
|
|
13
|
+
- **🔋 Bundled Binaries**: No external dependencies or system installations required. Works out of the box.
|
|
14
|
+
- **🌊 Stream Support**: Pipe data directly into archives (`addFromStream`) and out of archives (`extractToStream`).
|
|
15
|
+
- **💾 Buffer Support**: Extract files directly to memory (`extractToBuffer`) or add Buffers to archives.
|
|
16
|
+
- **📦 Multi-Format**: Support for **7z**, **ZIP**, **TAR**, **GZIP**, **XZ**, and reading **RAR**.
|
|
17
|
+
- **🔒 Security**: Full password protection and header encryption support.
|
|
18
|
+
- **🚀 TypeScript**: Written in TypeScript with complete type definitions.
|
|
19
|
+
- **📈 Progress Monitoring**: Real-time progress updates for long-running operations.
|
|
20
|
+
|
|
21
|
+
---
|
|
22
|
+
|
|
23
|
+
## 📦 Installation
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
npm install 7zip-wrapper
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
---
|
|
30
|
+
|
|
31
|
+
## 🚀 Quick Start
|
|
32
|
+
|
|
33
|
+
### Object-Oriented API (Recommended)
|
|
34
|
+
|
|
35
|
+
The `ZipWrapper` class provides a clean, fluent interface for all operations.
|
|
36
|
+
|
|
37
|
+
```typescript
|
|
38
|
+
import { ZipWrapper } from '7zip-wrapper';
|
|
39
|
+
|
|
40
|
+
const zip = new ZipWrapper();
|
|
41
|
+
|
|
42
|
+
// 1. Create an archive
|
|
43
|
+
await zip.add('backup.7z', ['src/', 'package.json'], {
|
|
44
|
+
level: 9,
|
|
45
|
+
password: 'secret-password',
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
// 2. Extract an archive
|
|
49
|
+
await zip.extract('backup.7z', {
|
|
50
|
+
outputDir: './restored',
|
|
51
|
+
overwrite: true,
|
|
52
|
+
});
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
### Functional API
|
|
56
|
+
|
|
57
|
+
If you prefer functions over classes, you can import them directly:
|
|
58
|
+
|
|
59
|
+
```typescript
|
|
60
|
+
import { add, extract, list } from '7zip-wrapper';
|
|
61
|
+
|
|
62
|
+
await add('archive.zip', 'files/', { type: 'zip' });
|
|
63
|
+
await extract('archive.zip', { outputDir: 'out' });
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
---
|
|
67
|
+
|
|
68
|
+
## 🌊 Streams & Buffers (New!)
|
|
69
|
+
|
|
70
|
+
Handle data efficiently without writing to temporary files.
|
|
71
|
+
|
|
72
|
+
### Streaming **Into** an Archive
|
|
73
|
+
|
|
74
|
+
Pipe a Readable stream (or Buffer) directly into an archive entry.
|
|
75
|
+
|
|
76
|
+
```typescript
|
|
77
|
+
import { Readable } from 'stream';
|
|
78
|
+
|
|
79
|
+
const myStream = Readable.from(['Hello World']);
|
|
80
|
+
await zip.addFromStream('archive.7z', 'hello.txt', myStream);
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
### Streaming **Out of** an Archive
|
|
84
|
+
|
|
85
|
+
Get a Readable stream for a file inside an archive.
|
|
86
|
+
|
|
87
|
+
```typescript
|
|
88
|
+
const readStream = zip.extractToStream('archive.7z', 'large-file.log');
|
|
89
|
+
readStream.pipe(process.stdout);
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
### Working with Buffers
|
|
93
|
+
|
|
94
|
+
Read a file from an archive directly into memory.
|
|
95
|
+
|
|
96
|
+
```typescript
|
|
97
|
+
const buffer = await zip.extractToBuffer('assets.7z', 'config.json');
|
|
98
|
+
const config = JSON.parse(buffer.toString());
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
---
|
|
102
|
+
|
|
103
|
+
## 📚 API Reference
|
|
104
|
+
|
|
105
|
+
### Core Operations
|
|
106
|
+
|
|
107
|
+
#### `add(archive, files, options)`
|
|
108
|
+
|
|
109
|
+
Create or update an archive.
|
|
110
|
+
|
|
111
|
+
| Option | Type | Description |
|
|
112
|
+
| ------------------ | --------- | ------------------------------------------------- |
|
|
113
|
+
| `type` | `string` | Archive format (`7z`, `zip`, `tar`, `gzip`, etc.) |
|
|
114
|
+
| `level` | `0-9` | Compression level (0=store, 9=ultra) |
|
|
115
|
+
| `password` | `string` | Password for encryption |
|
|
116
|
+
| `encryptFilenames` | `boolean` | Encrypt file names (Head encryption) |
|
|
117
|
+
| `recursive` | `boolean` | Recurse into subdirectories (default: `true`) |
|
|
118
|
+
|
|
119
|
+
#### `extract(archive, options)`
|
|
120
|
+
|
|
121
|
+
Extract files from an archive.
|
|
122
|
+
|
|
123
|
+
| Option | Type | Description |
|
|
124
|
+
| ----------- | ---------- | ---------------------------------- |
|
|
125
|
+
| `outputDir` | `string` | Destination directory |
|
|
126
|
+
| `files` | `string[]` | Specific files/patterns to extract |
|
|
127
|
+
| `overwrite` | `boolean` | Overwrite existing files |
|
|
128
|
+
| `password` | `string` | Password for decryption |
|
|
129
|
+
|
|
130
|
+
### Advanced Usage
|
|
131
|
+
|
|
132
|
+
#### Progress Events
|
|
133
|
+
|
|
134
|
+
Monitor operation progress for UI feedback.
|
|
135
|
+
|
|
136
|
+
```typescript
|
|
137
|
+
await zip.add('big-archive.7z', 'data/', {
|
|
138
|
+
onProgress: (progress) => {
|
|
139
|
+
console.log(`Processing: ${progress.percent}% (${progress.file})`);
|
|
140
|
+
},
|
|
141
|
+
});
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
#### Quick Helpers
|
|
145
|
+
|
|
146
|
+
For simple, one-off tasks without configuration.
|
|
147
|
+
|
|
148
|
+
```typescript
|
|
149
|
+
import { quick } from '7zip-wrapper';
|
|
150
|
+
|
|
151
|
+
await quick.zip(['file1.txt'], 'archive.zip'); // Max compression ZIP
|
|
152
|
+
await quick.sevenz(['file1.txt'], 'archive.7z'); // Max compression 7z
|
|
153
|
+
await quick.extract('archive.7z', 'output/');
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
---
|
|
157
|
+
|
|
158
|
+
## 📂 Supported Formats
|
|
159
|
+
|
|
160
|
+
| Format | Read | Write |
|
|
161
|
+
| ------ | ---- | ----- |
|
|
162
|
+
| 7z | ✅ | ✅ |
|
|
163
|
+
| ZIP | ✅ | ✅ |
|
|
164
|
+
| TAR | ✅ | ✅ |
|
|
165
|
+
| GZIP | ✅ | ✅ |
|
|
166
|
+
| XZ | ✅ | ✅ |
|
|
167
|
+
| RAR | ✅ | ❌\* |
|
|
168
|
+
|
|
169
|
+
_\*RAR creation is not supported by 7-Zip open source binaries._
|
|
170
|
+
|
|
171
|
+
---
|
|
172
|
+
|
|
173
|
+
## 🛠 Project Structure
|
|
174
|
+
|
|
175
|
+
- **`src/`**: TypeScript source code.
|
|
176
|
+
- **`examples/`**: Ready-to-run usage examples.
|
|
177
|
+
|
|
178
|
+
## 📄 License
|
|
179
|
+
|
|
180
|
+
MIT © [Rashed Iqbal](https://github.com/iqbal-rashed)
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
#!/usr/bin/env node
|
|
3
|
+
"use strict";var At=Object.create;var X=Object.defineProperty;var Rt=Object.getOwnPropertyDescriptor;var wt=Object.getOwnPropertyNames;var vt=Object.getPrototypeOf,bt=Object.prototype.hasOwnProperty;var S=(t,e)=>()=>(t&&(e=t(t=0)),e);var Tt=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of wt(e))!bt.call(t,n)&&n!==r&&X(t,n,{get:()=>e[n],enumerable:!(s=Rt(e,n))||s.enumerable});return t};var x=(t,e,r)=>(r=t!=null?At(vt(t)):{},Tt(e||!t||!t.__esModule?X(r,"default",{value:t,enumerable:!0}):r,t));var l=S(()=>{"use strict"});var w,Y,o,h,Z,v=S(()=>{"use strict";l();w={SUCCESS:0,WARNING:1,FATAL_ERROR:2,COMMAND_LINE_ERROR:7,NOT_ENOUGH_MEMORY:8,USER_STOPPED:255},Y={win32:"7za.exe",linux:"7za",darwin:"7za"},o={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"},h={ADD:"a",EXTRACT:"x",EXTRACT_FLAT:"e",LIST:"l",TEST:"t",UPDATE:"u",DELETE:"d",RENAME:"rn",HASH:"h",INFO:"i",BENCHMARK:"b"},Z=3e4});function K(t,e,r,s){let n=`${t}
|
|
4
|
+
${e}`.toLowerCase();return n.includes("wrong password")||n.includes("incorrect password")?new D(s):n.includes("enter password")||n.includes("password is required")||n.includes("encrypted")?new I(s):n.includes("data error")||n.includes("crc failed")||n.includes("headers error")||n.includes("unexpected end")?new _(s||"unknown",t.trim()):(n.includes("cannot find archive")||n.includes("cannot open"))&&s?new A(s):new L(t.trim()||"Unknown 7-Zip error",r)}var d,b,A,I,D,_,L,T,z=S(()=>{"use strict";l();d=class extends Error{constructor(r,s,n){super(r);this.code=s;this.exitCode=n;this.name="ZipWrapperError",Error.captureStackTrace?.(this,this.constructor)}},b=class extends d{constructor(e=[]){let r=e.length>0?` Searched: ${e.join(", ")}`:"";super(`7-Zip binary not found.${r}`,"BINARY_NOT_FOUND"),this.name="BinaryNotFoundError"}},A=class extends d{constructor(r){super(`Archive not found: ${r}`,"ARCHIVE_NOT_FOUND");this.archivePath=r;this.name="ArchiveNotFoundError"}},I=class extends d{constructor(r){super(r?`Password required for archive: ${r}`:"Password required for encrypted archive","PASSWORD_REQUIRED");this.archivePath=r;this.name="PasswordRequiredError"}},D=class extends d{constructor(r){super(r?`Wrong password for archive: ${r}`:"Wrong password for encrypted archive","WRONG_PASSWORD");this.archivePath=r;this.name="WrongPasswordError"}},_=class extends d{constructor(r,s){super(s?`Corrupt archive: ${r} - ${s}`:`Corrupt archive: ${r}`,"CORRUPT_ARCHIVE");this.archivePath=r;this.details=s;this.name="CorruptArchiveError"}},L=class extends d{constructor(e,r){super(e,"COMPRESSION_ERROR",r),this.name="CompressionError"}},T=class extends d{constructor(r,s){super(s?`Operation '${s}' timed out after ${r}ms`:`Operation timed out after ${r}ms`,"TIMEOUT");this.timeoutMs=r;this.operation=s;this.name="TimeoutError"}}});function zt(t){let e=t;for(;;){if(j.default.existsSync(O.default.join(e,"package.json")))return e;let r=O.default.dirname(e);if(r===e)return t;e=r}}var j,O,Ot,q,G=S(()=>{"use strict";l();j=x(require("fs")),O=x(require("path"));Ot=zt(__dirname),q=O.default.join(Ot,"bin")});function N(){return P||(P=Q.default.join(q,Y[tt.default.platform()]),P)}function Pt(t){return t||N()}function $t(t){let e=t||N();if(!J.default.existsSync(e))return!1;try{return(0,rt.execSync)(`"${e}"`,{timeout:5e3,windowsHide:!0,stdio:"ignore"}),!0}catch{return!0}}function et(t){let e=Pt(t);if(!$t(e)){let r=[e];throw new b(r)}return e}var J,Q,tt,rt,P,Zt,st=S(()=>{"use strict";l();J=x(require("fs")),Q=x(require("path")),tt=x(require("os")),rt=require("child_process");v();z();G();P=null;Zt=N()});function it(t,e){let r=et(e?.binaryPath);try{return(0,nt.spawn)(r,t,{...e,windowsHide:!0,stdio:["pipe","pipe","pipe"]})}catch(s){throw new d(`Failed to spawn 7-Zip process: ${s.message}`)}}async function g(t,e){let r=Date.now(),s=e?.timeout??Z;return new Promise((n,i)=>{let p=[],c=[],u,a,B=!1;try{u=it(t,e)}catch(f){i(f);return}s>0&&(a=setTimeout(()=>{B=!0,u.kill("SIGTERM"),i(new T(s,`7za ${t[0]}`))},s)),u.stdout?.on("data",f=>{p.push(f),e?.onProgress&&Ct(f.toString("utf-8"),e.onProgress)}),u.stderr?.on("data",f=>{c.push(f)}),u.on("close",f=>{if(a&&clearTimeout(a),B)return;let F=Buffer.concat(p).toString("utf-8"),H=Buffer.concat(c).toString("utf-8"),W={success:f===w.SUCCESS,command:`7za ${t.join(" ")}`,stdout:F,stderr:H,exitCode:f};if(f===w.SUCCESS||f===w.WARNING)n(W);else{let V=K(H,F,f,e?.archivePath);Object.assign(V,{result:W}),i(V)}}),u.on("error",f=>{a&&clearTimeout(a),i(new d(`Failed to execute 7-Zip: ${f.message}`))})})}function Ct(t,e){let r=t.match(/(\d+)%/);r&&e({percent:parseInt(r[1],10)});let s=t.match(/- (.+)$/m);s&&e({file:s[1].trim()})}function ot(t){let e=t.split(`
|
|
5
|
+
`),r=[],s=0,n=0,i=0,p=0,c=null;for(let u of e){let a=u.trim();a.startsWith("Path = ")?(c?.path&&r.push(c),c={path:a.substring(7),size:0,packedSize:0,modified:new Date,attributes:"",crc:"",method:"",isDirectory:!1}):c&&(a.startsWith("Size = ")?c.size=parseInt(a.substring(7),10)||0:a.startsWith("Packed Size = ")?c.packedSize=parseInt(a.substring(14),10)||0:a.startsWith("Modified = ")?c.modified=new Date(a.substring(11)):a.startsWith("Attributes = ")?(c.attributes=a.substring(13),c.isDirectory=c.attributes.includes("D")):a.startsWith("CRC = ")?c.crc=a.substring(6):a.startsWith("Method = ")?c.method=a.substring(9):a.startsWith("Encrypted = ")&&(c.encrypted=a.substring(12)==="+"))}c?.path&&r.push(c);for(let u of r)u.isDirectory?p++:(i++,s+=u.size,n+=u.packedSize);return{entries:r,stats:{totalSize:s,totalPackedSize:n,fileCount:i,dirCount:p,ratio:s>0?n/s:0}}}function ct(t){let e=t.split(`
|
|
6
|
+
`),r={};for(let s of e){let n=s.match(/(\w+)\s+for data:\s+([0-9A-Fa-f]+)/);if(n){r[n[1].toLowerCase()]=n[2];continue}let i=s.match(/^([0-9A-Fa-f]+)\s+(.+)$/);if(i){let p=i[1],c=i[2].trim();r[c]=p}}return r}function at(t){let e=t.split(`
|
|
7
|
+
`),r=[],s=!0;for(let n of e){let i=n.toLowerCase();(i.includes("error")||i.includes("failed")||i.includes("cannot")||i.includes("crc failed"))&&(r.push(n.trim()),s=!1)}return t.includes("Everything is Ok")&&(s=!0,r.length=0),{ok:s,errors:r}}function E(t,e,r,s){let n=[t];return n.push(...e),r&&n.push(r),s&&s.length>0&&n.push(...s),n}var nt,ut=S(()=>{"use strict";l();nt=require("child_process");st();z();v()});function $(t){if(!M.default.existsSync(t))throw new A(t)}async function pt(t,e,r){let s=[];if(r?.type&&s.push(`${o.TYPE}${r.type}`),r?.level!==void 0&&s.push(`${o.LEVEL}=${r.level}`),r?.method&&s.push(`${o.METHOD}=${r.method}`),r?.dictionarySize&&s.push(`${o.DICT_SIZE}=${r.dictionarySize}`),r?.wordSize!==void 0&&s.push(`${o.WORD_SIZE}=${r.wordSize}`),r?.threads!==void 0&&s.push(`${o.THREADS}${r.threads}`),r?.solid&&s.push(`${o.SOLID}=on`),r?.sfx&&s.push(o.SFX),r?.volumes&&s.push(`${o.VOLUME}${r.volumes}`),r?.password&&(s.push(`${o.PASSWORD}${r.password}`),r.encryptFilenames&&s.push(`${o.ENCRYPT_HEADERS}=on`)),r?.includePatterns)for(let i of r.includePatterns)s.push(`${o.INCLUDE}${i}`);if(r?.excludePatterns)for(let i of r.excludePatterns)s.push(`${o.EXCLUDE}${i}`);r?.recursive===!1?s.push(o.NO_RECURSE):s.push(o.RECURSE),r?.followSymlinks&&(s.push(`${o.STORE_HARDLINKS}-`),s.push(`${o.STORE_SYMLINKS}-`)),r?.storeSymlinks&&(s.push(o.STORE_HARDLINKS),s.push(o.STORE_SYMLINKS)),s.push(o.YES);let n=Array.isArray(e)?e:[e];return g(E(h.ADD,s,t,n),{onProgress:r?.onProgress,cwd:r?.cwd})}async function lt(t,e){$(t);let r=[o.YES];if(e?.outputDir&&r.push(`${o.OUTPUT}${e.outputDir}`),e?.password&&r.push(`${o.PASSWORD}${e.password}`),e?.includePatterns)for(let i of e.includePatterns)r.push(`${o.INCLUDE}${i}`);if(e?.excludePatterns)for(let i of e.excludePatterns)r.push(`${o.EXCLUDE}${i}`);e?.overwrite===!1?r.push(o.SKIP_EXISTING):e?.overwrite===!0&&r.push(o.OVERWRITE_ALL),e?.preservePermissions&&r.push(o.PRESERVE_PERMISSIONS);let s=e?.files||[],n=e?.flat?h.EXTRACT_FLAT:h.EXTRACT;return g(E(n,r,t,s),{archivePath:t,onProgress:e?.onProgress})}async function ft(t,e){$(t);let r=[o.TECH_INFO];e?.verbose&&r.push(o.VERBOSE),e?.password&&r.push(`${o.PASSWORD}${e.password}`);let s=await g(E(h.LIST,r,t),{archivePath:t}),n=ot(s.stdout);return{archive:t,size:n.stats.totalSize,packedSize:n.stats.totalPackedSize,fileCount:n.stats.fileCount,dirCount:n.stats.dirCount,entries:n.entries}}async function dt(t,e){$(t);let r=[o.TIMESTAMPS];e&&r.push(`${o.PASSWORD}${e}`);let s=await g(E(h.TEST,r,t),{archivePath:t}),n=at(s.stdout+s.stderr);return{archive:t,ok:s.success&&n.ok,errors:n.errors}}async function ht(t,e="crc32"){let r=[`-scrc${e}`],s=Array.isArray(t)?t:[t],n=0;for(let c of s)try{let u=M.default.statSync(c);n+=u.size}catch{}let i=await g(E(h.HASH,r,void 0,s)),p=ct(i.stdout);return{file:Array.isArray(t)?t[0]:t,hashes:p,size:n}}async function mt(t){return $(t),(await g(E(h.INFO,[],t),{archivePath:t})).stdout}async function gt(t,e){let r=[o.VERBOSE];if(t)for(let s of t)r.push(`-mm=${s}`);return e&&r.push(`-mmt=${e}`),g(E(h.BENCHMARK,r))}var M,Et=S(()=>{"use strict";l();M=x(require("fs"));ut();z();v()});l();var St=require("util");l();function C(t,e=2){if(t===0)return"0 B";let r=["B","KB","MB","GB","TB","PB"],s=1024,n=Math.floor(Math.log(t)/Math.log(s));return`${parseFloat((t/Math.pow(s,n)).toFixed(e))} ${r[n]}`}Et();var yt="2.0.0",xt=(0,St.parseArgs)({args:process.argv.slice(2),options:{help:{type:"boolean",short:"h"},version:{type:"boolean",short:"v"},output:{type:"string",short:"o"},password:{type:"string",short:"p"},level:{type:"string",short:"l"},type:{type:"string",short:"t"},verbose:{type:"boolean",short:"V"},hash:{type:"string",short:"H",default:"crc32"}},allowPositionals:!0});function k(){console.log(`
|
|
8
|
+
7-Zip CLI Wrapper v${yt}
|
|
9
|
+
|
|
10
|
+
USAGE:
|
|
11
|
+
7zip <command> [options] [files...]
|
|
12
|
+
|
|
13
|
+
COMMANDS:
|
|
14
|
+
add <archive> <files...> Add files to archive
|
|
15
|
+
extract <archive> Extract archive
|
|
16
|
+
list <archive> List archive contents
|
|
17
|
+
test <archive> Test archive integrity
|
|
18
|
+
hash <files...> Calculate file hashes
|
|
19
|
+
info <archive> Show archive information
|
|
20
|
+
benchmark Run compression benchmark
|
|
21
|
+
|
|
22
|
+
OPTIONS:
|
|
23
|
+
-h, --help Show this help message
|
|
24
|
+
-v, --version Show version
|
|
25
|
+
-o, --output <dir> Output directory (for extract)
|
|
26
|
+
-p, --password <pwd> Password for encrypted archives
|
|
27
|
+
-l, --level <0-9> Compression level (default: 5)
|
|
28
|
+
-t, --type <format> Archive format (7z, zip, gzip, etc.)
|
|
29
|
+
-V, --verbose Verbose output
|
|
30
|
+
-H, --hash <type> Hash type (crc32, sha256, etc.)
|
|
31
|
+
|
|
32
|
+
EXAMPLES:
|
|
33
|
+
7zip add backup.7z ./src ./package.json
|
|
34
|
+
7zip extract backup.7z -o ./output
|
|
35
|
+
7zip list backup.7z
|
|
36
|
+
7zip add archive.zip *.txt -t zip -l 9
|
|
37
|
+
7zip hash ./file.txt -H sha256
|
|
38
|
+
7zip test backup.7z -p mypassword
|
|
39
|
+
|
|
40
|
+
For more information, visit: https://github.com/iqbal-rashed/7zip-wrapper
|
|
41
|
+
`)}function It(){console.log(`7-Zip CLI Wrapper v${yt}`)}function R(t,e=!1){(xt.values.verbose||!e)&&console.log(t)}function U(t){console.log(`\u2713 ${t}`)}function m(t){console.error(`\u2717 ${t}`)}async function Dt(){let{values:t,positionals:e}=xt,[r,...s]=e;t.help&&(k(),process.exit(0)),t.version&&(It(),process.exit(0)),r||(k(),process.exit(1));try{switch(r){case"add":case"a":{let[n,...i]=s;(!n||i.length===0)&&(m("Archive and files required"),console.log("Usage: 7zip add <archive> <files...>"),process.exit(1)),R(`Creating archive: ${n}`,!0),await pt(n,i,{type:t.type||"7z",level:t.level?parseInt(t.level,10):5,password:t.password}),U(`Archive created: ${n}`);break}case"extract":case"x":case"e":{let[n]=s;n||(m("Archive path required"),console.log("Usage: 7zip extract <archive> [-o output]"),process.exit(1));let i=t.output||".";R(`Extracting: ${n}`,!0),await lt(n,{outputDir:i,password:t.password}),U(`Extracted to: ${i}`);break}case"list":case"l":{let[n]=s;n||(m("Archive path required"),console.log("Usage: 7zip list <archive>"),process.exit(1));let i=await ft(n,{password:t.password});if(console.log(`
|
|
42
|
+
Archive: ${n}`),console.log(`Files: ${i.fileCount}`),console.log(`Directories: ${i.dirCount}`),console.log(`Total size: ${C(i.size)}`),console.log(`Compressed: ${C(i.packedSize)}`),console.log(`Ratio: ${(i.packedSize/i.size*100).toFixed(1)}%
|
|
43
|
+
`),t.verbose){console.log("---");for(let p of i.entries){let c=p.isDirectory?"D":"F",u=p.size.toString().padStart(12);console.log(`${c} ${u} ${p.path}`)}}break}case"test":case"t":{let[n]=s;n||(m("Archive path required"),console.log("Usage: 7zip test <archive>"),process.exit(1)),R(`Testing: ${n}`,!0);let i=await dt(n,t.password);if(i.ok)U("Archive is OK");else{m("Archive has errors:");for(let p of i.errors)console.log(` - ${p}`);process.exit(1)}break}case"hash":case"h":{let n=s;n.length===0&&(m("Files required"),console.log("Usage: 7zip hash <files...> [-H hashType]"),process.exit(1));let i=t.hash||"crc32";R(`Calculating ${i} hash...`,!0);let p=await ht(n,i);console.log(`
|
|
44
|
+
Hashes:`);for(let[c,u]of Object.entries(p.hashes))console.log(` ${u} ${c}`);break}case"info":case"i":{let[n]=s;n||(m("Archive path required"),console.log("Usage: 7zip info <archive>"),process.exit(1));let i=await mt(n);console.log(i);break}case"benchmark":case"b":{R("Running benchmark...",!0);let n=await gt();console.log(n.stdout);break}default:m(`Unknown command: ${r}`),k(),process.exit(1)}}catch(n){n instanceof Error&&(m(n.message),t.verbose&&n.stack&&console.error(n.stack)),process.exit(1)}}Dt();
|