bestzip 4.0.0 → 4.0.2

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/README.md CHANGED
@@ -114,4 +114,5 @@ When symlinks are present and the `followSymLinks` option has not been set expli
114
114
  To follow symlinks, set `followSymLinks: true` (programmatic API) or pass `--follow-sym-links` on the command line. To keep the link entries (the default behavior) while suppressing the warning, set `followSymLinks: false` or pass `--no-follow-sym-links` on the command line.
115
115
 
116
116
  When archiving symlinks without following them, bestzip uses the native `zip` command when available. Some native `zip` builds (notably the Windows build of Info-ZIP) cannot store symlinks as link entries at all, so bestzip falls back to its built-in Node.js implementation in that case.
117
- Note that calling `nativeZip()` directly with `followSymLinks` unset/false on such a platform throws an error; use the `bestZip()` entry point, which routes to the Node.js implementation automatically. Use `nativeZipSupportsSymlinks()` to check whether the available native `zip` can store symlinks as links; it returns `true`/`false` and caches its result after the first call. `bestzip.hasNativeZip()` checks whether a native `zip` is installed at all.
117
+
118
+ Note that calling `nativeZip()` directly with `followSymLinks` unset/false on such a platform throws an error; use the `bestZip()` entry point, which routes to the Node.js implementation automatically. Use `nativeZipSupportsSymlinks()` to check whether the available native `zip` can store symlinks as links; it returns `true`/`false` and caches its result after the first call. `bestzip.hasNativeZip()` checks whether a native `zip` is installed at all.
package/bin/cli.js CHANGED
@@ -1,60 +1,4 @@
1
1
  #!/usr/bin/env node
2
+ import { main } from "../lib/cli.js";
2
3
 
3
- import * as bestzip from "../lib/bestzip.js";
4
-
5
- import yargs from "yargs";
6
- import { hideBin } from "yargs/helpers";
7
-
8
- // Rewrite -0 … -9 into --level 0 … --level 9 before yargs parses them
9
- const preprocessed = hideBin(process.argv).flatMap((arg) => {
10
- const match = /^-([0-9])$/.exec(arg);
11
- return match ? ["--level", match[1]] : [arg];
12
- });
13
-
14
- const argv = yargs(preprocessed)
15
- .usage("\nUsage: bestzip destination.zip sources/")
16
- .option("force", {
17
- describe: "Force use of node.js or native zip methods",
18
- choices: ["node", "native"],
19
- })
20
- .option("level", {
21
- describe: "Level of compression",
22
- type: "number",
23
- })
24
- .option("follow-sym-links", {
25
- describe:
26
- "Follow symbolic links and include their target contents in the archive",
27
- type: "boolean",
28
- })
29
- .demand(2).argv;
30
-
31
- const destination = argv._.shift();
32
- const source = argv._;
33
-
34
- console.log("Writing %s to %s...", source.join(", "), destination);
35
-
36
- let zip;
37
-
38
- if (argv.force === "node") {
39
- zip = bestzip.nodeZip;
40
- } else if (argv.force === "native") {
41
- zip = bestzip.nativeZip;
42
- } else {
43
- zip = bestzip.zip;
44
- }
45
-
46
- zip({
47
- source,
48
- destination,
49
- verbose: !!argv.verbose,
50
- level: argv.level,
51
- followSymLinks: argv.followSymLinks,
52
- viaCli: true,
53
- })
54
- .then(function () {
55
- console.log("zipped!");
56
- })
57
- .catch(function (err) {
58
- console.error(err);
59
- process.exit(1);
60
- });
4
+ main();
package/lib/bestzip.js CHANGED
@@ -1,312 +1,12 @@
1
1
  // creates a zip file using either the native `zip` command if available,
2
2
  // or a node.js zip implementation otherwise.
3
3
 
4
- import cp, { spawnSync } from "node:child_process";
5
- import fs from "node:fs";
6
- import fsp from "node:fs/promises";
7
- import path from "node:path";
8
- import os from "node:os";
9
-
10
- import { ZipArchive } from "archiver";
11
- import { glob, hasMagic } from "glob";
12
- import which from "which";
13
-
14
- function hasNativeZip() {
15
- return Boolean(which.sync("zip", { nothrow: true }));
16
- }
17
-
18
- let nativeSymlinkCapability;
19
-
20
- // The native zip command needs the --symlinks flag to store symlinks as links
21
- // rather than following them. Not every build supports it (notably the
22
- // Windows build of Info-ZIP). This probes the installed zip for support, since
23
- // the version string isn't a reliable indicator.
24
- function nativeZipSupportsSymlinks() {
25
- if (nativeSymlinkCapability !== undefined) {
26
- return nativeSymlinkCapability;
27
- }
28
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), "bestzip-symlink-check"));
29
- try {
30
- const file = path.join(dir, "file");
31
- const link = path.join(dir, "link");
32
- fs.writeFileSync(file, "bestzip symlink check");
33
- try {
34
- fs.symlinkSync("file", link);
35
- } catch (e) {
36
- nativeSymlinkCapability = false;
37
- return nativeSymlinkCapability;
38
- }
39
- const res = spawnSync(
40
- "zip",
41
- ["-q", "--symlinks", "check.zip", "file", "link"],
42
- {
43
- cwd: dir,
44
- encoding: "utf8",
45
- }
46
- );
47
- nativeSymlinkCapability = res.status === 0;
48
- } catch (e) {
49
- nativeSymlinkCapability = false;
50
- } finally {
51
- fs.rmSync(dir, { recursive: true, force: true });
52
- }
53
- return nativeSymlinkCapability;
54
- }
55
-
56
- async function expandSources(cwd, source) {
57
- // options to behave more like the native zip's glob support
58
- const globOpts = {
59
- cwd,
60
- dot: false, // ignore .dotfiles
61
- noglobstar: true, // treat ** as *
62
- noext: true, // no (a|b)
63
- nobrace: true, // no {a,b}
64
- };
65
-
66
- // first handle arrays
67
- if (Array.isArray(source)) {
68
- const results = await Promise.all(source.map((s) => expandSources(cwd, s)));
69
- return results.flat();
70
- }
71
-
72
- // then expand magic
73
- if (typeof source !== "string") {
74
- throw new Error(`source is (${typeof source}) `);
75
- }
76
-
77
- if (hasMagic(source, globOpts)) {
78
- // archiver uses this library but somehow ends up with different results on windows:
79
- // archiver.glob('*') will include subdirectories, but omit their contents on windows
80
- // so we'll use glob directly, and add all of the files it finds
81
- return await glob(source, globOpts);
82
- } else {
83
- // or just trigger the callback with the source string if there is no magic
84
- // always return an array
85
- return [source];
86
- }
87
- }
88
-
89
- async function walkTree(fullPath, followSymLinks) {
90
- let stats;
91
- if (followSymLinks) {
92
- stats = await fsp.stat(fullPath);
93
- } else {
94
- stats = await fsp.lstat(fullPath);
95
- }
96
- if (stats.isSymbolicLink() || !stats.isDirectory()) {
97
- return [{ path: fullPath, stats }];
98
- }
99
- const entries = await fsp.readdir(fullPath);
100
- const children = await Promise.all(
101
- entries.map((entry) => walkTree(path.join(fullPath, entry), followSymLinks))
102
- );
103
- return children.flat();
104
- }
105
-
106
- // Validates the compression level. A level of exactly 0-9 (an integer) is
107
- // accepted; anything else that is set causes an error. An unset level is
108
- // allowed and left to each implementation's default.
109
- function validateLevel(level) {
110
- if (typeof level === "undefined") {
111
- return;
112
- }
113
- if (
114
- typeof level !== "number" ||
115
- !Number.isInteger(level) ||
116
- level < 0 ||
117
- level > 9
118
- ) {
119
- const typehint = typeof level === "number" ? "" : ` (${typeof level})`;
120
- throw new Error(
121
- `bestzip: level should be an integer from 0 to 9, got ${level}${typehint}`
122
- );
123
- }
124
- }
125
-
126
- async function detectSymlinks(cwd, sources) {
127
- const results = await Promise.all(
128
- sources.map(async (source) => {
129
- const fullPath = path.resolve(cwd, source);
130
- const entries = await walkTree(fullPath, false);
131
- return entries
132
- .filter((entry) => entry.stats.isSymbolicLink())
133
- .map((entry) => entry.path);
134
- })
135
- );
136
- return results.flat();
137
- }
138
-
139
- function maybeWarnAboutSymlinks(options, symlinks, cwd) {
140
- if (options.followSymLinks !== undefined || symlinks.length === 0) {
141
- return;
142
- }
143
- const cli = options.viaCli;
144
- const optIn = cli ? "pass --follow-sym-links" : "set followSymLinks: true";
145
- const optOut = cli
146
- ? "pass --no-follow-sym-links"
147
- : "set followSymLinks: false";
148
- let lines = symlinks.map((p) => path.relative(cwd, p));
149
- if (lines.length > 4) {
150
- lines = lines.slice(0, 3);
151
- lines.push(`...and ${symlinks.length - 3} more`);
152
- }
153
- console.warn(
154
- "Warning: Symbolic links are stored as the link itself rather than the destination by default.\n" +
155
- `To keep the default behavior and prevent this warning, ${optOut}.\n` +
156
- `To follow symlinks and include their target contents, ${optIn}.\n` +
157
- "Detected symlinks:\n" +
158
- lines.join("\n")
159
- );
160
- }
161
-
162
- const nativeZip = async (options) => {
163
- const cwd = options.cwd || process.cwd();
164
- const command = "zip";
165
- const sources = await expandSources(cwd, options.source);
166
- const destination = path.resolve(cwd, options.destination);
167
- validateLevel(options.level);
168
- // followSymLinks: true opts into following symlinks (archiving their target
169
- // contents); the default (unset or false) stores symlinks as links.
170
- const followSymLinks = options.followSymLinks === true;
171
-
172
- if (!followSymLinks && !nativeZipSupportsSymlinks()) {
173
- // The native zip command cannot store symlinks as links on this platform
174
- // (e.g. the Windows build of Info-ZIP). nodeZip can, so the bestzip()
175
- // entry point routes accordingly — but a direct nativeZip() call can't
176
- // fulfill this request.
177
- throw new Error(
178
- "The native zip command on this platform cannot store symlinks as links. Use the bestzip() entry point, which will select the node implementation, or set followSymLinks to true to follow symlinks instead."
179
- );
180
- }
181
-
182
- const args = ["--quiet", "--recurse-paths"];
183
- if (typeof options.level === "number") {
184
- args.push("-" + options.level.toString());
185
- }
186
- if (!followSymLinks) {
187
- args.push("--symlinks");
188
- }
189
- args.push(destination, "--", ...sources);
190
-
191
- // Scan for symlinks to warn about in parallel with the zip command. The
192
- // scan is best-effort: if it fails (e.g. it races the zip command touching
193
- // the same paths), log and fall back to no warning rather than aborting the
194
- // zip, and never let it reject before the zip process has completed.
195
- const warnScan = (async () => {
196
- if (options.followSymLinks !== undefined) {
197
- return [];
198
- }
199
- try {
200
- return await detectSymlinks(cwd, sources);
201
- } catch (err) {
202
- console.warn(
203
- `bestzip: failed to scan for symlinks to warn about: ${err.message}`
204
- );
205
- return [];
206
- }
207
- })();
208
-
209
- const zipPromise = new Promise((resolve, reject) => {
210
- const zipProcess = cp.spawn(command, args, {
211
- stdio: "inherit",
212
- cwd,
213
- });
214
- zipProcess.on("error", reject);
215
- zipProcess.on("close", (exitCode) => {
216
- if (exitCode === 0) {
217
- resolve();
218
- } else {
219
- reject(
220
- new Error(
221
- `Unexpected exit code from native zip: ${exitCode}\n executed command '${command} ${args.join(
222
- " "
223
- )}'\n executed in directory '${cwd}'`
224
- )
225
- );
226
- }
227
- });
228
- });
229
-
230
- const [symlinks] = await Promise.all([warnScan, zipPromise]);
231
- maybeWarnAboutSymlinks(options, symlinks, cwd);
232
- };
233
-
234
- // based on http://stackoverflow.com/questions/15641243/need-to-zip-an-entire-directory-using-node-js/18775083#18775083
235
- const nodeZip = async (options) => {
236
- const cwd = options.cwd || process.cwd();
237
- validateLevel(options.level);
238
- // followSymLinks: true follows symlinks and archives their target contents;
239
- // the default (unset or false) stores symlinks as links.
240
- const followSymLinks = options.followSymLinks === true;
241
- const trackSymLinks = typeof options.followSymLinks === "undefined";
242
- const symlinks = [];
243
- const outputFile = await fsp.open(
244
- path.resolve(cwd, options.destination),
245
- "w"
246
- );
247
- const output = outputFile.createWriteStream();
248
- const archive = new ZipArchive({
249
- zlib: { level: options.level },
250
- });
251
-
252
- output.on("close", async () => {
253
- await outputFile.close();
254
- resolvePromise();
255
- });
256
- archive.on("error", (err) => rejectPromise(err));
257
- archive.on("warning", (err) => console.warn(err && err.message));
258
-
259
- archive.pipe(output);
260
-
261
- let resolvePromise;
262
- let rejectPromise;
263
- const promise = new Promise((resolve, reject) => {
264
- resolvePromise = resolve;
265
- rejectPromise = reject;
266
- });
267
-
268
- async function addSource(source) {
269
- const fullPath = path.resolve(cwd, source);
270
- const destPath = source;
271
-
272
- // Walk the source once in the requested mode: an lstat walk when storing
273
- // links (symlinks are emitted as their own entries and stored as links),
274
- // or a stat walk when following (symlinks are dereferenced and their
275
- // target contents archived, matching the native zip implementation).
276
- const entries = await walkTree(fullPath, followSymLinks);
277
- for (const entry of entries) {
278
- const archiveName = destPath + entry.path.substring(fullPath.length);
279
- if (entry.stats.isSymbolicLink()) {
280
- // Storing a link: keep the raw link target and record it for the
281
- // default warning (an explicit followSymLinks setting suppresses it).
282
- if (trackSymLinks) {
283
- symlinks.push(entry.path);
284
- }
285
- archive.symlink(
286
- archiveName,
287
- await fsp.readlink(entry.path),
288
- entry.stats.mode
289
- );
290
- } else {
291
- archive.file(entry.path, {
292
- name: archiveName,
293
- stats: entry.stats,
294
- });
295
- }
296
- }
297
- }
298
-
299
- try {
300
- const expandedSources = await expandSources(cwd, options.source);
301
- await Promise.all(expandedSources.map(addSource));
302
- maybeWarnAboutSymlinks(options, symlinks, cwd);
303
- archive.finalize();
304
- } catch (err) {
305
- rejectPromise(err);
306
- }
307
-
308
- return promise;
309
- };
4
+ import {
5
+ nativeZip,
6
+ hasNativeZip,
7
+ nativeZipSupportsSymlinks,
8
+ } from "./nativezip.js";
9
+ import { nodeZip } from "./nodezip.js";
310
10
 
311
11
  function zip(options) {
312
12
  const compatMode = typeof options === "string";
package/lib/cli.js ADDED
@@ -0,0 +1,66 @@
1
+ import { fileURLToPath } from "node:url";
2
+ import process from "node:process";
3
+
4
+ import yargs from "yargs";
5
+ import { hideBin } from "yargs/helpers";
6
+
7
+ import * as bestzip from "../lib/bestzip.js";
8
+
9
+ export function main() {
10
+ // Rewrite -0 … -9 into --level 0 … --level 9 before yargs parses them
11
+ const preprocessed = hideBin(process.argv).flatMap((arg) => {
12
+ const match = /^-([0-9])$/.exec(arg);
13
+ return match ? ["--level", match[1]] : [arg];
14
+ });
15
+
16
+ const argv = yargs(preprocessed)
17
+ .usage("\nUsage: bestzip destination.zip sources/")
18
+ .option("force", {
19
+ describe: "Force use of node.js or native zip methods",
20
+ choices: ["node", "native"],
21
+ })
22
+ .option("level", {
23
+ describe: "Level of compression",
24
+ type: "number",
25
+ })
26
+ .option("follow-sym-links", {
27
+ describe:
28
+ "Follow symbolic links and include their target contents in the archive",
29
+ type: "boolean",
30
+ })
31
+ .demand(2).argv;
32
+
33
+ const destination = argv._.shift();
34
+ const source = argv._;
35
+
36
+ console.log("Writing %s to %s...", source.join(", "), destination);
37
+
38
+ let zip;
39
+
40
+ if (argv.force === "node") {
41
+ zip = bestzip.nodeZip;
42
+ } else if (argv.force === "native") {
43
+ zip = bestzip.nativeZip;
44
+ } else {
45
+ zip = bestzip.zip;
46
+ }
47
+
48
+ zip({
49
+ source,
50
+ destination,
51
+ level: argv.level,
52
+ followSymLinks: argv.followSymLinks,
53
+ viaCli: true,
54
+ })
55
+ .then(function () {
56
+ console.log("zipped!");
57
+ })
58
+ .catch(function (err) {
59
+ console.error(err);
60
+ process.exit(1);
61
+ });
62
+ }
63
+
64
+ if (process.argv[1] === fileURLToPath(import.meta.url)) {
65
+ main();
66
+ }
@@ -0,0 +1,82 @@
1
+ import fs from "node:fs";
2
+ import fsp from "node:fs/promises";
3
+ import path from "node:path";
4
+
5
+ import { glob, hasMagic } from "glob";
6
+
7
+ export function isExecutableFile(file) {
8
+ try {
9
+ fs.accessSync(file, fs.constants.X_OK);
10
+ return fs.statSync(file).isFile();
11
+ } catch (e) {
12
+ return false;
13
+ }
14
+ }
15
+
16
+ export function findInDir(dir, names) {
17
+ for (const name of names) {
18
+ const candidate = path.join(dir, name);
19
+ if (isExecutableFile(candidate)) {
20
+ return candidate;
21
+ }
22
+ }
23
+ return null;
24
+ }
25
+
26
+ export async function expandSources(cwd, source) {
27
+ // options to behave more like the native zip's glob support
28
+ const globOpts = {
29
+ cwd,
30
+ dot: false, // ignore .dotfiles
31
+ noglobstar: true, // treat ** as *
32
+ noext: true, // no (a|b)
33
+ nobrace: true, // no {a,b}
34
+ };
35
+
36
+ // first handle arrays
37
+ if (Array.isArray(source)) {
38
+ const results = await Promise.all(source.map((s) => expandSources(cwd, s)));
39
+ return results.flat();
40
+ }
41
+
42
+ // then expand magic
43
+ if (typeof source !== "string") {
44
+ throw new Error(`source is (${typeof source}) `);
45
+ }
46
+
47
+ if (hasMagic(source, globOpts)) {
48
+ // archiver uses this library but somehow ends up with different results on windows:
49
+ // archiver.glob('*') will include subdirectories, but omit their contents on windows
50
+ // so we'll use glob directly, and add all of the files it finds
51
+ return await glob(source, globOpts);
52
+ } else {
53
+ // or just trigger the callback with the source string if there is no magic
54
+ // always return an array
55
+ return [source];
56
+ }
57
+ }
58
+
59
+ export async function walkTree(fullPath, followSymLinks) {
60
+ let stats;
61
+ if (followSymLinks) {
62
+ stats = await fsp.stat(fullPath);
63
+ } else {
64
+ stats = await fsp.lstat(fullPath);
65
+ }
66
+ if (stats.isSymbolicLink() || !stats.isDirectory()) {
67
+ return [{ path: fullPath, stats }];
68
+ }
69
+ const entries = await fsp.readdir(fullPath);
70
+ const children = await Promise.all(
71
+ entries.map((entry) => walkTree(path.join(fullPath, entry), followSymLinks))
72
+ );
73
+ return [{ path: fullPath, stats }, ...children.flat()];
74
+ }
75
+
76
+ export async function safeStat(path) {
77
+ try {
78
+ return await fsp.stat(path);
79
+ } catch (err) {
80
+ return null;
81
+ }
82
+ }
@@ -0,0 +1,234 @@
1
+ import process from "node:process";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import cp, { spawnSync } from "node:child_process";
5
+ import os from "node:os";
6
+ import { isDeepStrictEqual } from "node:util";
7
+
8
+ import { expandSources, findInDir, safeStat } from "./fs-utils.js";
9
+ import {
10
+ detectSymlinks,
11
+ maybeWarnAboutSymlinks,
12
+ validateLevel,
13
+ } from "./validate.js";
14
+
15
+ export const nativeZip = async (options) => {
16
+ const cwd = options.cwd || process.cwd();
17
+ // Resolve the absolute path in the parent's context and pass that to the
18
+ // child. Resolving the bare `zip` name inside the spawned process would let
19
+ // the archive directory's contents shadow the real binary when PATH has a
20
+ // relative or empty element (CWE-426/CWE-427).
21
+ const command = getNativeZipCommand();
22
+ if (!command) {
23
+ throw new Error(
24
+ "The native zip command was not found at a trusted location on this system."
25
+ );
26
+ }
27
+ const sources = await expandSources(cwd, options.source);
28
+ const destination = path.resolve(cwd, options.destination);
29
+ validateLevel(options.level);
30
+ const destStatBefore = await safeStat(destination);
31
+ // followSymLinks: true opts into following symlinks (archiving their target
32
+ // contents); the default (unset or false) stores symlinks as links.
33
+ const followSymLinks = options.followSymLinks === true;
34
+
35
+ if (!followSymLinks && !nativeZipSupportsSymlinks()) {
36
+ // The native zip command cannot store symlinks as links on this platform
37
+ // (e.g. the Windows build of Info-ZIP). nodeZip can, so the bestzip()
38
+ // entry point routes accordingly — but a direct nativeZip() call can't
39
+ // fulfill this request.
40
+ throw new Error(
41
+ "The native zip command on this platform cannot store symlinks as links. Use the bestzip() entry point, which will select the node implementation, or set followSymLinks to true to follow symlinks instead."
42
+ );
43
+ }
44
+
45
+ const args = ["--quiet", "--recurse-paths"];
46
+ if (typeof options.level === "number") {
47
+ args.push("-" + options.level.toString());
48
+ }
49
+ if (!followSymLinks) {
50
+ args.push("--symlinks");
51
+ }
52
+ args.push(destination, "--", ...sources);
53
+
54
+ // Scan for symlinks to warn about in parallel with the zip command. The
55
+ // scan is best-effort: if it fails (e.g. it races the zip command touching
56
+ // the same paths), log and fall back to no warning rather than aborting the
57
+ // zip, and never let it reject before the zip process has completed.
58
+ const warnScan = (async () => {
59
+ if (options.followSymLinks !== undefined) {
60
+ return [];
61
+ }
62
+ try {
63
+ return await detectSymlinks(cwd, sources);
64
+ } catch (err) {
65
+ console.warn(
66
+ `bestzip: failed to scan for symlinks to warn about: ${err.message}`
67
+ );
68
+ return [];
69
+ }
70
+ })();
71
+
72
+ const zipPromise = new Promise((resolve, reject) => {
73
+ const zipProcess = cp.spawn(command, args, {
74
+ stdio: "inherit",
75
+ cwd,
76
+ });
77
+ zipProcess.on("error", reject);
78
+ zipProcess.on("close", async (exitCode) => {
79
+ if (exitCode === 0) {
80
+ // The native zip reported success. Make sure it actually wrote the
81
+ // archive — the zip exits 0 without creating or updating the
82
+ // destination, that's a silent no-op, not a real archive.
83
+ const destStatAfter = await safeStat(destination);
84
+ if (
85
+ destStatAfter &&
86
+ !isDeepStrictEqual(destStatBefore, destStatAfter)
87
+ ) {
88
+ resolve();
89
+ } else {
90
+ reject(
91
+ new Error(
92
+ `The native zip command exited 0 but did not ${
93
+ destStatBefore ? "update" : "create"
94
+ } the destination archive '${destination}'. This may indicate a broken or incompatible native zip command, or a filesystem issue. Consider using ${
95
+ options.viaCli ? "--force=node" : `{force: 'node'}`
96
+ }.\n Executed command: '${command} ${args.join(
97
+ " "
98
+ )}'\n Executed in directory: '${cwd}'`
99
+ )
100
+ );
101
+ }
102
+ } else {
103
+ reject(
104
+ new Error(
105
+ `Unexpected exit code from native zip: ${exitCode}\n Executed command: '${command} ${args.join(
106
+ " "
107
+ )}'\n Executed in directory '${cwd}'`
108
+ )
109
+ );
110
+ }
111
+ });
112
+ });
113
+
114
+ const [symlinks] = await Promise.all([warnScan, zipPromise]);
115
+ maybeWarnAboutSymlinks(options, symlinks, cwd);
116
+ };
117
+
118
+ // Directories where the system `zip` command is expected to live. Only these
119
+ // are ever consulted, so a file named `zip` anywhere else — committed into an
120
+ // archived directory, delivered through a relative/empty PATH element, or
121
+ // dropped into node_modules/.bin by a dependency — is never executed
122
+ // (CWE-426/CWE-427).
123
+ const DEFAULT_ZIP_DIRS = (() => {
124
+ if (process.platform === "win32") {
125
+ // note, some node.js environments, like MINGW64 (git-bash), report SystemRoot
126
+ // and ProgramFiles as uppercase, but they still support the version here
127
+ const systemRoot = process.env.SystemRoot || "C:\\Windows";
128
+ const programFiles = process.env.ProgramFiles || "C:\\Program Files";
129
+ const programFilesX86 =
130
+ process.env["ProgramFiles(x86)"] || "C:\\Program Files (x86)";
131
+ const localAppData = process.env.LOCALAPPDATA;
132
+ const userProfile = process.env.USERPROFILE;
133
+
134
+ const dirs = [
135
+ path.join(systemRoot, "System32"),
136
+ systemRoot,
137
+ "C:\\ProgramData\\chocolatey\\bin",
138
+ path.join(programFiles, "Git\\usr\\bin"),
139
+ path.join(programFilesX86, "Git\\usr\\bin"),
140
+ ];
141
+
142
+ if (localAppData) {
143
+ dirs.push(path.join(localAppData, "Microsoft\\WinGet\\Links"));
144
+ }
145
+ if (userProfile) {
146
+ dirs.push(path.join(userProfile, "scoop\\shims"));
147
+ }
148
+
149
+ return dirs;
150
+ }
151
+
152
+ return [
153
+ "/usr/bin",
154
+ "/bin",
155
+ "/usr/local/bin",
156
+ "/opt/homebrew/bin", // Homebrew on Apple Silicon
157
+ "/opt/local/bin", // MacPorts
158
+ "/snap/bin", // Linux Snap packages
159
+ "/nix/var/nix/profiles/default/bin", // Nix OS/Package Manager
160
+ ];
161
+ })();
162
+
163
+ const ZIP_EXECUTABLE_NAMES =
164
+ process.platform === "win32" ? ["zip.exe", "zip"] : ["zip"];
165
+
166
+ // Resolves the native `zip` binary's absolute path, or null when none is
167
+ // usable (so callers fall back to the node implementation). PATH is never
168
+ // consulted: the child process chdirs into the (possibly untrusted) archive
169
+ // directory before running, so a bare command name could be shadowed by a
170
+ // `zip` planted there or in the dependency tree (CWE-426/CWE-427). Only the
171
+ // allowlisted system directories above are ever checked, and the resolved
172
+ // absolute path — never the bare `zip` name — is what gets spawned.
173
+ let nativeZipCommand;
174
+ function getNativeZipCommand() {
175
+ if (nativeZipCommand !== undefined) {
176
+ return nativeZipCommand;
177
+ }
178
+ nativeZipCommand = null;
179
+ for (const dir of DEFAULT_ZIP_DIRS) {
180
+ const found = findInDir(dir, ZIP_EXECUTABLE_NAMES);
181
+ if (found) {
182
+ nativeZipCommand = found;
183
+ break;
184
+ }
185
+ }
186
+ return nativeZipCommand;
187
+ }
188
+
189
+ export function hasNativeZip() {
190
+ return Boolean(getNativeZipCommand());
191
+ }
192
+
193
+ let nativeSymlinkCapability;
194
+
195
+ // The native zip command needs the --symlinks flag to store symlinks as links
196
+ // rather than following them. Not every build supports it (notably the
197
+ // Windows build of Info-ZIP). This probes the installed zip for support, since
198
+ // the version string isn't a reliable indicator.
199
+ export function nativeZipSupportsSymlinks() {
200
+ if (nativeSymlinkCapability !== undefined) {
201
+ return nativeSymlinkCapability;
202
+ }
203
+ const command = getNativeZipCommand();
204
+ if (!command) {
205
+ nativeSymlinkCapability = false;
206
+ return nativeSymlinkCapability;
207
+ }
208
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "bestzip-symlink-check"));
209
+ try {
210
+ const file = path.join(dir, "file");
211
+ const link = path.join(dir, "link");
212
+ fs.writeFileSync(file, "bestzip symlink check");
213
+ try {
214
+ fs.symlinkSync("file", link);
215
+ } catch (e) {
216
+ nativeSymlinkCapability = false;
217
+ return nativeSymlinkCapability;
218
+ }
219
+ const res = spawnSync(
220
+ command,
221
+ ["-q", "--symlinks", "check.zip", "file", "link"],
222
+ {
223
+ cwd: dir,
224
+ encoding: "utf8",
225
+ }
226
+ );
227
+ nativeSymlinkCapability = res.status === 0;
228
+ } catch (e) {
229
+ nativeSymlinkCapability = false;
230
+ } finally {
231
+ fs.rmSync(dir, { recursive: true, force: true });
232
+ }
233
+ return nativeSymlinkCapability;
234
+ }
package/lib/nodezip.js ADDED
@@ -0,0 +1,91 @@
1
+ import fsp from "node:fs/promises";
2
+ import path from "node:path";
3
+
4
+ import { ZipArchive } from "archiver";
5
+
6
+ import { expandSources, walkTree } from "./fs-utils.js";
7
+ import { maybeWarnAboutSymlinks, validateLevel } from "./validate.js";
8
+
9
+ export async function nodeZip(options) {
10
+ const cwd = options.cwd || process.cwd();
11
+ validateLevel(options.level);
12
+ // followSymLinks: true follows symlinks and archives their target contents;
13
+ // the default (unset or false) stores symlinks as links.
14
+ const followSymLinks = options.followSymLinks === true;
15
+ const trackSymLinks = typeof options.followSymLinks === "undefined";
16
+ const symlinks = [];
17
+ const outputFile = await fsp.open(
18
+ path.resolve(cwd, options.destination),
19
+ "w"
20
+ );
21
+ const output = outputFile.createWriteStream();
22
+ const archive = new ZipArchive({
23
+ zlib: { level: options.level },
24
+ });
25
+
26
+ output.on("close", async () => {
27
+ await outputFile.close();
28
+ resolvePromise();
29
+ });
30
+ archive.on("error", (err) => rejectPromise(err));
31
+ archive.on("warning", (err) => console.warn(err && err.message));
32
+
33
+ archive.pipe(output);
34
+
35
+ let resolvePromise;
36
+ let rejectPromise;
37
+ const promise = new Promise((resolve, reject) => {
38
+ resolvePromise = resolve;
39
+ rejectPromise = reject;
40
+ });
41
+
42
+ async function addSource(source) {
43
+ const fullPath = path.resolve(cwd, source);
44
+ const destPath = source;
45
+
46
+ // Walk the source once in the requested mode: an lstat walk when storing
47
+ // links (symlinks are emitted as their own entries and stored as links),
48
+ // or a stat walk when following (symlinks are dereferenced and their
49
+ // target contents archived, matching the native zip implementation).
50
+ const entries = await walkTree(fullPath, followSymLinks);
51
+ for (const entry of entries) {
52
+ const archiveName = destPath + entry.path.substring(fullPath.length);
53
+ if (entry.stats.isSymbolicLink()) {
54
+ // Storing a link: keep the raw link target and record it for the
55
+ // default warning (an explicit followSymLinks setting suppresses it).
56
+ if (trackSymLinks) {
57
+ symlinks.push(entry.path);
58
+ }
59
+ archive.symlink(
60
+ archiveName,
61
+ await fsp.readlink(entry.path),
62
+ entry.stats.mode
63
+ );
64
+ } else {
65
+ if (
66
+ entry.stats.isDirectory() &&
67
+ [".", ""].includes(path.basename(archiveName))
68
+ ) {
69
+ continue;
70
+ }
71
+ archive.file(entry.path, {
72
+ name: archiveName,
73
+ stats: entry.stats,
74
+ });
75
+ }
76
+ }
77
+ }
78
+
79
+ try {
80
+ const expandedSources = await expandSources(cwd, options.source);
81
+ for (const source of expandedSources) {
82
+ await addSource(source);
83
+ }
84
+ maybeWarnAboutSymlinks(options, symlinks, cwd);
85
+ archive.finalize();
86
+ } catch (err) {
87
+ rejectPromise(err);
88
+ }
89
+
90
+ return promise;
91
+ }
@@ -0,0 +1,59 @@
1
+ import path from "node:path";
2
+
3
+ import { walkTree } from "./fs-utils.js";
4
+
5
+ // Validates the compression level. A level of exactly 0-9 (an integer) is
6
+ // accepted; anything else that is set causes an error. An unset level is
7
+ // allowed and left to each implementation's default.
8
+ export function validateLevel(level) {
9
+ if (typeof level === "undefined") {
10
+ return;
11
+ }
12
+ if (
13
+ typeof level !== "number" ||
14
+ !Number.isInteger(level) ||
15
+ level < 0 ||
16
+ level > 9
17
+ ) {
18
+ const typehint = typeof level === "number" ? "" : ` (${typeof level})`;
19
+ throw new Error(
20
+ `bestzip: level should be an integer from 0 to 9, got ${level}${typehint}`
21
+ );
22
+ }
23
+ }
24
+
25
+ export async function detectSymlinks(cwd, sources) {
26
+ const results = await Promise.all(
27
+ sources.map(async (source) => {
28
+ const fullPath = path.resolve(cwd, source);
29
+ const entries = await walkTree(fullPath, false);
30
+ return entries
31
+ .filter((entry) => entry.stats.isSymbolicLink())
32
+ .map((entry) => entry.path);
33
+ })
34
+ );
35
+ return results.flat();
36
+ }
37
+
38
+ export function maybeWarnAboutSymlinks(options, symlinks, cwd) {
39
+ if (options.followSymLinks !== undefined || symlinks.length === 0) {
40
+ return;
41
+ }
42
+ const cli = options.viaCli;
43
+ const optIn = cli ? "pass --follow-sym-links" : "set followSymLinks: true";
44
+ const optOut = cli
45
+ ? "pass --no-follow-sym-links"
46
+ : "set followSymLinks: false";
47
+ let lines = symlinks.map((p) => path.relative(cwd, p));
48
+ if (lines.length > 4) {
49
+ lines = lines.slice(0, 3);
50
+ lines.push(`...and ${symlinks.length - 3} more`);
51
+ }
52
+ console.warn(
53
+ "Warning: Symbolic links are stored as the link itself rather than the destination by default.\n" +
54
+ `To keep the default behavior and prevent this warning, ${optOut}.\n` +
55
+ `To follow symlinks and include their target contents, ${optIn}.\n` +
56
+ "Detected symlinks:\n" +
57
+ lines.join("\n")
58
+ );
59
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bestzip",
3
- "version": "4.0.0",
3
+ "version": "4.0.2",
4
4
  "description": "Uses OS zip command if available (for better performance and speed) or node.js version if there is no system command available. Can be called via node or command line.",
5
5
  "type": "module",
6
6
  "exports": "./lib/bestzip.js",
@@ -13,8 +13,8 @@
13
13
  "scripts": {
14
14
  "lint": "eslint .",
15
15
  "lint-fix": "eslint --fix .",
16
- "unit-test": "node --experimental-test-snapshots --test",
17
- "update-snapshot": "npm run unit-test -- --test-update-snapshots",
16
+ "unit-test": "node --experimental-test-snapshots --test \"test/**/*.test.js\"",
17
+ "update-snapshot": "node --experimental-test-snapshots --test-update-snapshots --test \"test/**/*.test.js\"",
18
18
  "test": "npm run lint && npm run unit-test"
19
19
  },
20
20
  "author": "Nathan Friedly - http://nfriedly.com/",
@@ -31,7 +31,6 @@
31
31
  "dependencies": {
32
32
  "archiver": "^8.0.0",
33
33
  "glob": "^13.0.6",
34
- "which": "^6.0.1",
35
34
  "yargs": "^16.2.0"
36
35
  },
37
36
  "devDependencies": {