@vltpkg/tar 1.0.8 → 1.0.10

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
@@ -24,7 +24,7 @@ Pass your gzip-compressed or raw uncompressed JavaScript package
24
24
  tarball in a Buffer (or Uint8Array, or ArrayBuffer slice) into the
25
25
  function, along with the folder you want to drop it in.
26
26
 
27
- It will unpack as fast as possible, using synchronous I/O.
27
+ It will unpack as fast as possible.
28
28
 
29
29
  ```js
30
30
  import { unpack } from '@vltpkg/tar'
@@ -37,40 +37,33 @@ const unzipped = gunzipSync(gzipped)
37
37
  unpack(unzipped, 'node_modules/target')
38
38
  ```
39
39
 
40
- ### `class Pool`
41
-
42
- Create a pool of worker threads which will service unpack requests in
43
- parallel.
44
-
45
- New requests that get added will be assigned to workers as those
46
- workers become available. When a worker completes its task, and there
47
- are no more tasks to assign, it is terminated. If not enough workers
48
- are available to service requests, then new ones will be spawned.
49
-
50
- #### `pool.jobs`
40
+ ### unpackSync(tarData, targetFolder)
51
41
 
52
- The number of worker threads that will be created.
42
+ Same as `unpack`, but blocking. Faster: the async writers pay a libuv
43
+ round trip per file, which costs more than the IO itself.
53
44
 
54
- #### `pool.workers`
45
+ ### unpackFileSync(file, targetFolder, offset = 0)
55
46
 
56
- Set of currently active worker threads.
47
+ Read the tarball from a file on disk, skipping `offset` leading bytes,
48
+ and unpack it synchronously. The offset lets a tarball be extracted
49
+ straight out of a cache entry whose file starts with a header block.
57
50
 
58
- #### `pool.queue`
59
-
60
- Queue of requests awaiting an available worker.
51
+ ### `class Pool`
61
52
 
62
- #### `pool.pending`
53
+ The interface the vlt CLI extracts through. Both methods are `async`
54
+ for the caller's convenience; the work itself is synchronous and runs
55
+ on the main thread.
63
56
 
64
- All unpack requests that have not yet completed, both those currently
65
- assigned to a worker and those still waiting in the queue. Entries are
66
- removed once the request resolves or rejects.
57
+ The pool holds no queue and imposes no limit -- callers are expected
58
+ to cap their own concurrency. (`@vltpkg/graph`'s reify does.)
67
59
 
68
60
  #### `pool.unpack(tarData: Buffer, target: string) => Promise<void>`
69
61
 
70
- Unpack the supplied Buffer of data into the target folder, using
71
- synchronous I/O in a worker thread.
62
+ Unpack the supplied Buffer of data into the target folder.
63
+
64
+ #### `pool.unpackFile(file: string, target: string, offset = 0) => Promise<void>`
72
65
 
73
- Promise resolves when this unpack request has been completed.
66
+ Unpack a tarball read from `file`, skipping `offset` leading bytes.
74
67
 
75
68
  ## Caveats
76
69
 
@@ -96,6 +89,8 @@ It does not do any of the binary linking or other stuff that a package
96
89
  manager will need to do. It _just_ does the unpack, as ruthlessly fast
97
90
  as possible, and that's all.
98
91
 
99
- Synchronous IO is used because that's faster and requires less CPU
100
- utilization. The `Pool` class manages multiple worker threads doing
101
- this work, so faster sync IO for the whole thing is much more optimal.
92
+ Synchronous IO is used because it is faster and costs less CPU than
93
+ the async writers, which pay a libuv round trip per file. The cost is
94
+ that extraction blocks the event loop while it runs. Set
95
+ `VLT_TAR_SYNC=0` to make `Pool` use the async writers instead -- a
96
+ kill switch, not a supported mode.
package/dist/index.d.ts CHANGED
@@ -1,3 +1,2 @@
1
1
  export { unpack } from './unpack.ts';
2
2
  export * from './pool.ts';
3
- export * from './unpack-request.ts';
package/dist/index.js CHANGED
@@ -1,3 +1,2 @@
1
1
  export { unpack } from "./unpack.js";
2
2
  export * from "./pool.js";
3
- export * from "./unpack-request.js";
package/dist/pool.d.ts CHANGED
@@ -1,42 +1,25 @@
1
- import { UnpackRequest } from './unpack-request.ts';
2
- import { Worker } from './worker.ts';
3
- export * from './worker.ts';
4
1
  /**
5
- * Automatically expanding/contracting set of workers to maximize parallelism
6
- * of unpack operations up to 1 less than the number of CPUs (or 1).
2
+ * Unpacks tarballs into place.
7
3
  *
8
- * `pool.unpack(tarData, target)` will perform the unpack operation
9
- * synchronously, in one of these workers, and returns a promise when the
10
- * worker has confirmed completion of the task.
4
+ * Unpacking runs synchronously on the main thread, which is measurably
5
+ * faster than the async writers (the libuv round trip per file costs
6
+ * more than the IO).
7
+ *
8
+ * There is no queue here. The only limiter is the caller's: reify caps
9
+ * extraction at `Math.max(availableParallelism() - 1, 1) * 8` in flight
10
+ * (`@vltpkg/graph`, `src/reify/index.ts`). A consumer that is not reify
11
+ * is unbounded -- add your own cap.
11
12
  */
12
13
  export declare class Pool {
13
- #private;
14
- /**
15
- * Number of workers to employ. Defaults to 8 times one less than
16
- * the number of available CPUs, with a minimum of 8.
17
- */
18
- jobs: number;
19
- /**
20
- * Set of currently active worker threads
21
- */
22
- workers: Set<Worker>;
23
- /**
24
- * Queue of requests awaiting an available worker
25
- */
26
- queue: UnpackRequest[];
27
- /**
28
- * All requests that have not yet been confirmed completed, both
29
- * those currently assigned to a worker and those still waiting in
30
- * the queue. Entries are removed once the request resolves or
31
- * rejects, releasing the reference to its tarball buffer.
32
- */
33
- pending: Map<number, UnpackRequest>;
34
14
  /**
35
15
  * Provide the tardata to be unpacked, and the location where it's to be
36
- * placed. Will create a new worker up to the `jobs` value, and then start
37
- * pushing in the queue for workers to pick up as they become available.
38
- *
39
- * Returned promise resolves when the provided tarball has been extracted.
16
+ * placed. Resolves when the tarball has been extracted.
40
17
  */
41
18
  unpack(tarData: Buffer, target: string): Promise<void>;
19
+ /**
20
+ * Same, reading the tarball from a file and skipping `offset` leading
21
+ * bytes, so a cache entry is unpacked without loading it into the
22
+ * registry client's in-memory cache.
23
+ */
24
+ unpackFile(file: string, target: string, offset?: number): Promise<void>;
42
25
  }
package/dist/pool.js CHANGED
@@ -1,91 +1,38 @@
1
- import { error } from '@vltpkg/error-cause';
2
- import { asError } from '@vltpkg/types';
3
- import os from 'node:os';
4
- import { UnpackRequest } from "./unpack-request.js";
5
- import { isResponseOK, Worker } from "./worker.js";
6
- export * from "./worker.js";
1
+ import { readFile } from 'node:fs/promises';
2
+ import { unpack, unpackFileSync, unpackSync } from "./unpack.js";
3
+ // Field kill switch: restores the async writer without a release.
4
+ const syncUnpack = process.env.VLT_TAR_SYNC !== '0';
7
5
  /**
8
- * Automatically expanding/contracting set of workers to maximize parallelism
9
- * of unpack operations up to 1 less than the number of CPUs (or 1).
6
+ * Unpacks tarballs into place.
10
7
  *
11
- * `pool.unpack(tarData, target)` will perform the unpack operation
12
- * synchronously, in one of these workers, and returns a promise when the
13
- * worker has confirmed completion of the task.
8
+ * Unpacking runs synchronously on the main thread, which is measurably
9
+ * faster than the async writers (the libuv round trip per file costs
10
+ * more than the IO).
11
+ *
12
+ * There is no queue here. The only limiter is the caller's: reify caps
13
+ * extraction at `Math.max(availableParallelism() - 1, 1) * 8` in flight
14
+ * (`@vltpkg/graph`, `src/reify/index.ts`). A consumer that is not reify
15
+ * is unbounded -- add your own cap.
14
16
  */
15
17
  export class Pool {
16
18
  /**
17
- * Number of workers to employ. Defaults to 8 times one less than
18
- * the number of available CPUs, with a minimum of 8.
19
- */
20
- /* c8 ignore next */
21
- jobs = 8 * (Math.max(os.availableParallelism(), 2) - 1);
22
- /**
23
- * Set of currently active worker threads
24
- */
25
- workers = new Set();
26
- /**
27
- * Queue of requests awaiting an available worker
28
- */
29
- queue = [];
30
- /**
31
- * All requests that have not yet been confirmed completed, both
32
- * those currently assigned to a worker and those still waiting in
33
- * the queue. Entries are removed once the request resolves or
34
- * rejects, releasing the reference to its tarball buffer.
19
+ * Provide the tardata to be unpacked, and the location where it's to be
20
+ * placed. Resolves when the tarball has been extracted.
35
21
  */
36
- pending = new Map();
37
- // handle a message from the worker
38
- #onMessage(w, m) {
39
- const { id } = m;
40
- // a request has been met or failed, report and either
41
- // pick up the next item in the queue, or terminate worker
42
- const ur = this.pending.get(id);
43
- /* c8 ignore next */
44
- if (!ur)
45
- return;
46
- // request is done, stop holding its tarball buffer in memory
47
- this.pending.delete(id);
48
- if (isResponseOK(m)) {
49
- ur.resolve();
50
- /* c8 ignore start - nearly impossible in normal circumstances */
51
- }
52
- else {
53
- ur.reject(error(asError(m.error, 'failed without error message').message, {
54
- found: m,
55
- cause: m.error,
56
- }));
57
- }
58
- /* c8 ignore stop */
59
- const next = this.queue.shift();
60
- if (!next) {
61
- this.workers.delete(w);
62
- }
63
- else {
64
- void w.process(next);
65
- }
66
- }
67
- // create a new worker
68
- #createWorker(req) {
69
- const w = new Worker((m) => this.#onMessage(w, m));
70
- this.workers.add(w);
71
- void w.process(req);
22
+ async unpack(tarData, target) {
23
+ if (!syncUnpack)
24
+ return unpack(tarData, target);
25
+ unpackSync(tarData, target);
72
26
  }
73
27
  /**
74
- * Provide the tardata to be unpacked, and the location where it's to be
75
- * placed. Will create a new worker up to the `jobs` value, and then start
76
- * pushing in the queue for workers to pick up as they become available.
77
- *
78
- * Returned promise resolves when the provided tarball has been extracted.
28
+ * Same, reading the tarball from a file and skipping `offset` leading
29
+ * bytes, so a cache entry is unpacked without loading it into the
30
+ * registry client's in-memory cache.
79
31
  */
80
- async unpack(tarData, target) {
81
- const ur = new UnpackRequest(tarData, target);
82
- this.pending.set(ur.id, ur);
83
- if (this.workers.size < this.jobs) {
84
- this.#createWorker(ur);
85
- }
86
- else {
87
- this.queue.push(ur);
32
+ async unpackFile(file, target, offset = 0) {
33
+ if (!syncUnpack) {
34
+ return unpack((await readFile(file)).subarray(offset), target);
88
35
  }
89
- return ur.promise;
36
+ unpackFileSync(file, target, offset);
90
37
  }
91
38
  }
package/dist/unpack.d.ts CHANGED
@@ -4,3 +4,14 @@ export declare const checkFs: (h: {
4
4
  path: string;
5
5
  };
6
6
  export declare const unpack: (tarData: Buffer, target: string) => Promise<void>;
7
+ /**
8
+ * Same as {@link unpack}, but blocking. Faster: the async writers pay a
9
+ * libuv round trip per file, which costs more than the IO itself.
10
+ */
11
+ export declare const unpackSync: (tarData: Buffer, target: string) => void;
12
+ /**
13
+ * Unpack a tarball straight from a file on disk, skipping `offset`
14
+ * leading bytes. Used to extract from a cache entry in place, so the
15
+ * tarball never lands in the registry client's in-memory cache.
16
+ */
17
+ export declare const unpackFileSync: (file: string, target: string, offset?: number) => void;
package/dist/unpack.js CHANGED
@@ -1,11 +1,12 @@
1
1
  import { error } from '@vltpkg/error-cause';
2
2
  import { randomBytes } from 'node:crypto';
3
+ import { lstatSync, mkdirSync, readFileSync, renameSync, writeFileSync, } from 'node:fs';
3
4
  import { lstat, mkdir, rename, writeFile } from 'node:fs/promises';
4
5
  import { basename, dirname, isAbsolute, relative, resolve, sep, } from 'node:path';
5
- import { rimraf } from 'rimraf';
6
+ import { rimraf, rimrafSync } from 'rimraf';
6
7
  import { Header } from 'tar/header';
7
8
  import { Pax } from 'tar/pax';
8
- import { unzip as unzipCB } from 'node:zlib';
9
+ import { unzip as unzipCB, unzipSync as unzipSyncCB } from 'node:zlib';
9
10
  import { findTarDir } from "./find-tar-dir.js";
10
11
  // Matches node-tar's MAX_DECOMPRESSION_RATIO, which npm uses via pacote.
11
12
  const MAX_DECOMPRESSION_RATIO = 1000;
@@ -20,20 +21,26 @@ const parseMaxUnpackedBytes = (raw) => {
20
21
  : defaultMaxUnpackedBytes;
21
22
  };
22
23
  const maxUnpackedBytes = parseMaxUnpackedBytes(process.env.VLT_TAR_MAX_UNPACKED_BYTES);
24
+ const unzipMax = (len) => Math.min(maxUnpackedBytes, len * MAX_DECOMPRESSION_RATIO);
25
+ const unzipError = (er, found, max) => er.code === 'ERR_BUFFER_TOO_LARGE' ?
26
+ error('tarball exceeds maximum unpacked size', {
27
+ found,
28
+ max,
29
+ cause: er,
30
+ })
31
+ : er;
23
32
  const unzip = async (input) => {
24
- const max = Math.min(maxUnpackedBytes, input.length * MAX_DECOMPRESSION_RATIO);
25
- return new Promise((res, rej) => unzipCB(input, { maxOutputLength: max }, (er, result) => {
26
- if (!er)
27
- return res(result);
28
- return rej((er.code ===
29
- 'ERR_BUFFER_TOO_LARGE') ?
30
- error('tarball exceeds maximum unpacked size', {
31
- found: input.length,
32
- max,
33
- cause: er,
34
- })
35
- : er);
36
- }));
33
+ const max = unzipMax(input.length);
34
+ return new Promise((res, rej) => unzipCB(input, { maxOutputLength: max }, (er, result) => er ? rej(unzipError(er, input.length, max)) : res(result)));
35
+ };
36
+ const unzipSync = (input) => {
37
+ const max = unzipMax(input.length);
38
+ try {
39
+ return unzipSyncCB(input, { maxOutputLength: max });
40
+ }
41
+ catch (er) {
42
+ throw unzipError(er, input.length, max);
43
+ }
37
44
  };
38
45
  const exists = async (path) => {
39
46
  try {
@@ -167,7 +174,26 @@ export const unpack = async (tarData, target) => {
167
174
  const isGzip = tarData[0] === 0x1f && tarData[1] === 0x8b;
168
175
  await unpackUnzipped(isGzip ? await unzip(tarData) : tarData, target);
169
176
  };
170
- const unpackUnzipped = async (buffer, target) => {
177
+ /**
178
+ * Same as {@link unpack}, but blocking. Faster: the async writers pay a
179
+ * libuv round trip per file, which costs more than the IO itself.
180
+ */
181
+ export const unpackSync = (tarData, target) => {
182
+ const isGzip = tarData[0] === 0x1f && tarData[1] === 0x8b;
183
+ unpackUnzippedSync(isGzip ? unzipSync(tarData) : tarData, target);
184
+ };
185
+ /**
186
+ * Unpack a tarball straight from a file on disk, skipping `offset`
187
+ * leading bytes. Used to extract from a cache entry in place, so the
188
+ * tarball never lands in the registry client's in-memory cache.
189
+ */
190
+ export const unpackFileSync = (file, target, offset = 0) => unpackSync(readFileSync(file).subarray(offset), target);
191
+ const tmpName = (target) => dirname(target) + sep + '.' + basename(target) + '.' + tmpSuffix();
192
+ /**
193
+ * Walk the tar headers and collect what has to be written. No IO, so
194
+ * both writers share it and cannot drift on path sanitization.
195
+ */
196
+ const parseTarball = (buffer, tmp) => {
171
197
  /* c8 ignore start */
172
198
  const isGzip = buffer[0] === 0x1f && buffer[1] === 0x8b;
173
199
  if (isGzip) {
@@ -184,7 +210,9 @@ const unpackUnzipped = async (buffer, target) => {
184
210
  });
185
211
  }
186
212
  if (buffer.length < 1024) {
187
- throw error('Invalid tarball: not terminated by 1024 null bytes', { found: buffer.length });
213
+ throw error('Invalid tarball: not terminated by 1024 null bytes', {
214
+ found: buffer.length,
215
+ });
188
216
  }
189
217
  // make sure the last kb is all zeros
190
218
  for (let i = buffer.length - 1024; i < buffer.length; i++) {
@@ -192,105 +220,109 @@ const unpackUnzipped = async (buffer, target) => {
192
220
  throw error('Invalid tarball: not terminated by 1024 null bytes', { found: buffer.subarray(i, i + 10) });
193
221
  }
194
222
  }
195
- const tmp = dirname(target) + sep + '.' + basename(target) + '.' + tmpSuffix();
196
- const og = tmp + '.ORIGINAL';
197
- let succeeded = false;
198
- try {
199
- const entries = new Map();
200
- let tarDir = undefined;
201
- let offset = 0;
202
- let h;
203
- let ex = undefined;
204
- let gex = undefined;
205
- while (offset < buffer.length &&
206
- !(h = new Header(buffer, offset, ex, gex)).nullBlock) {
207
- offset += 512;
208
- ex = undefined;
209
- gex = undefined;
210
- const size = h.size ?? 0;
211
- const body = buffer.subarray(offset, offset + size);
212
- // skip invalid headers
213
- if (!h.cksumValid)
214
- continue;
215
- offset += 512 * Math.ceil(size / 512);
216
- // TODO: tarDir might not be named "package/"
217
- // find the first tarDir in the first entry, and use that.
218
- switch (h.type) {
219
- case 'File':
220
- if (!tarDir)
221
- tarDir = findTarDir(h.path, tarDir);
222
- /* c8 ignore next */
223
- if (!tarDir)
224
- continue;
225
- if (!checkFs(h, tarDir, tmp))
226
- continue;
227
- {
228
- const dest = resolve(tmp, h.path.substring(tarDir.length));
229
- const key = entryKey(dest);
230
- // a repeated path is fine (last wins), but flipping between
231
- // file and directory would silently discard data.
232
- if (entries.get(key)?.dir === true) {
233
- throw error('file/directory collision in tarball', {
234
- path: dest,
235
- });
236
- }
237
- entries.set(key, {
223
+ const entries = new Map();
224
+ let tarDir = undefined;
225
+ let offset = 0;
226
+ let h;
227
+ let ex = undefined;
228
+ let gex = undefined;
229
+ while (offset < buffer.length &&
230
+ !(h = new Header(buffer, offset, ex, gex)).nullBlock) {
231
+ offset += 512;
232
+ ex = undefined;
233
+ gex = undefined;
234
+ const size = h.size ?? 0;
235
+ const body = buffer.subarray(offset, offset + size);
236
+ // skip invalid headers
237
+ if (!h.cksumValid)
238
+ continue;
239
+ offset += 512 * Math.ceil(size / 512);
240
+ // TODO: tarDir might not be named "package/"
241
+ // find the first tarDir in the first entry, and use that.
242
+ switch (h.type) {
243
+ case 'File':
244
+ if (!tarDir)
245
+ tarDir = findTarDir(h.path, tarDir);
246
+ /* c8 ignore next */
247
+ if (!tarDir)
248
+ continue;
249
+ if (!checkFs(h, tarDir, tmp))
250
+ continue;
251
+ {
252
+ const dest = resolve(tmp, h.path.substring(tarDir.length));
253
+ const key = entryKey(dest);
254
+ // a repeated path is fine (last wins), but flipping between
255
+ // file and directory would silently discard data.
256
+ if (entries.get(key)?.dir === true) {
257
+ throw error('file/directory collision in tarball', {
238
258
  path: dest,
239
- body,
240
- executable: 1 === ((h.mode ?? 0x666) & 1),
241
- dir: false,
242
259
  });
243
260
  }
244
- break;
245
- case 'Directory':
246
- /* c8 ignore next 2 */
247
- if (!tarDir)
248
- tarDir = findTarDir(h.path, tarDir);
249
- if (!tarDir)
250
- continue;
251
- if (!checkFs(h, tarDir, tmp))
252
- continue;
253
- {
254
- const dest = resolve(tmp, h.path.substring(tarDir.length));
255
- const key = entryKey(dest);
256
- if (entries.get(key)?.dir === false) {
257
- throw error('file/directory collision in tarball', {
258
- path: dest,
259
- });
260
- }
261
- entries.set(key, {
261
+ entries.set(key, {
262
+ path: dest,
263
+ body,
264
+ executable: 1 === ((h.mode ?? 0x666) & 1),
265
+ dir: false,
266
+ });
267
+ }
268
+ break;
269
+ case 'Directory':
270
+ /* c8 ignore next 2 */
271
+ if (!tarDir)
272
+ tarDir = findTarDir(h.path, tarDir);
273
+ if (!tarDir)
274
+ continue;
275
+ if (!checkFs(h, tarDir, tmp))
276
+ continue;
277
+ {
278
+ const dest = resolve(tmp, h.path.substring(tarDir.length));
279
+ const key = entryKey(dest);
280
+ if (entries.get(key)?.dir === false) {
281
+ throw error('file/directory collision in tarball', {
262
282
  path: dest,
263
- dir: true,
264
283
  });
265
284
  }
266
- break;
267
- case 'GlobalExtendedHeader':
268
- gex = Pax.parse(body.toString(), gex, true);
269
- break;
270
- case 'ExtendedHeader':
271
- case 'OldExtendedHeader':
272
- ex = Pax.parse(body.toString(), ex, false);
273
- break;
274
- case 'NextFileHasLongPath':
275
- case 'OldGnuLongPath':
276
- ex ??= Object.create(null);
277
- ex.path = body.toString().replace(/\0.*/, '');
278
- break;
279
- }
285
+ entries.set(key, {
286
+ path: dest,
287
+ dir: true,
288
+ });
289
+ }
290
+ break;
291
+ case 'GlobalExtendedHeader':
292
+ gex = Pax.parse(body.toString(), gex, true);
293
+ break;
294
+ case 'ExtendedHeader':
295
+ case 'OldExtendedHeader':
296
+ ex = Pax.parse(body.toString(), ex, false);
297
+ break;
298
+ case 'NextFileHasLongPath':
299
+ case 'OldGnuLongPath':
300
+ ex ??= Object.create(null);
301
+ ex.path = body.toString().replace(/\0.*/, '');
302
+ break;
280
303
  }
281
- // Per-unpack memo: paths are tmp-scoped and never reused across
282
- // unpacks. The unique dir set is the memo; making/made globals
283
- // previously leaked ~18k strings per install.
284
- const dirs = new Set();
285
- const files = [];
286
- for (const e of entries.values()) {
287
- if (e.dir)
288
- dirs.add(e.path);
289
- else {
290
- dirs.add(dirname(e.path));
291
- files.push(e);
292
- }
304
+ }
305
+ // Per-unpack memo: paths are tmp-scoped and never reused across
306
+ // unpacks. The unique dir set is the memo; making/made globals
307
+ // previously leaked ~18k strings per install.
308
+ const dirs = new Set();
309
+ const files = [];
310
+ for (const e of entries.values()) {
311
+ if (e.dir)
312
+ dirs.add(e.path);
313
+ else {
314
+ dirs.add(dirname(e.path));
315
+ files.push(e);
293
316
  }
317
+ }
318
+ return { dirs, files };
319
+ };
320
+ const unpackUnzipped = async (buffer, target) => {
321
+ const tmp = tmpName(target);
322
+ const og = tmp + '.ORIGINAL';
323
+ let succeeded = false;
324
+ try {
325
+ const { dirs, files } = parseTarball(buffer, tmp);
294
326
  rethrowFirst(await Promise.allSettled([...dirs].map(d => mkdir(d, { recursive: true, mode: 0o777 }))));
295
327
  rethrowFirst(await Promise.allSettled(files.map(f => withWriteLane(() => write(f.path, f.body, f.executable)))));
296
328
  const targetExists = await exists(target);
@@ -315,3 +347,42 @@ const unpackUnzipped = async (buffer, target) => {
315
347
  }
316
348
  }
317
349
  };
350
+ const unpackUnzippedSync = (buffer, target) => {
351
+ const tmp = tmpName(target);
352
+ const og = tmp + '.ORIGINAL';
353
+ let succeeded = false;
354
+ try {
355
+ const { dirs, files } = parseTarball(buffer, tmp);
356
+ for (const d of dirs) {
357
+ mkdirSync(d, { recursive: true, mode: 0o777 });
358
+ }
359
+ for (const f of files) {
360
+ // if the mode is world-executable, then make it executable
361
+ // this is needed for some packages that have a file that is
362
+ // not a declared bin, but still used as a cli executable.
363
+ writeFileSync(f.path, f.body, {
364
+ mode: f.executable ? 0o777 : 0o666,
365
+ });
366
+ }
367
+ const targetExists = !!lstatSync(target, {
368
+ throwIfNoEntry: false,
369
+ });
370
+ if (targetExists)
371
+ renameSync(target, og);
372
+ renameSync(tmp, target);
373
+ if (targetExists)
374
+ rimrafSync(og);
375
+ succeeded = true;
376
+ }
377
+ finally {
378
+ if (!succeeded) {
379
+ /* c8 ignore start */
380
+ if (lstatSync(og, { throwIfNoEntry: false })) {
381
+ rimrafSync(target);
382
+ renameSync(og, target);
383
+ }
384
+ /* c8 ignore stop */
385
+ rimrafSync(tmp);
386
+ }
387
+ }
388
+ };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@vltpkg/tar",
3
3
  "description": "An extremely limited and very fast tar extractor",
4
- "version": "1.0.8",
4
+ "version": "1.0.10",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "git+https://github.com/vltpkg/vltpkg.git",
@@ -13,8 +13,7 @@
13
13
  "url": "http://vlt.sh"
14
14
  },
15
15
  "dependencies": {
16
- "@vltpkg/error-cause": "1.0.8",
17
- "@vltpkg/types": "1.0.8",
16
+ "@vltpkg/error-cause": "1.0.10",
18
17
  "rimraf": "^6.1.2",
19
18
  "tar": "^7.5.2"
20
19
  },
@@ -69,11 +68,6 @@
69
68
  "import": {
70
69
  "default": "./dist/unpack.js"
71
70
  }
72
- },
73
- "./unpack-request": {
74
- "import": {
75
- "default": "./dist/unpack-request.js"
76
- }
77
71
  }
78
72
  },
79
73
  "files": [
@@ -1,9 +0,0 @@
1
- export declare class UnpackRequest {
2
- id: number;
3
- tarData: Buffer;
4
- target: string;
5
- resolve: () => void;
6
- reject: (reason?: any) => void;
7
- promise: Promise<void>;
8
- constructor(tarData: Buffer, target: string);
9
- }
@@ -1,16 +0,0 @@
1
- let ID = 1;
2
- export class UnpackRequest {
3
- id = ID++;
4
- tarData;
5
- target;
6
- resolve;
7
- reject;
8
- promise = new Promise((res, rej) => {
9
- this.resolve = res;
10
- this.reject = rej;
11
- });
12
- constructor(tarData, target) {
13
- this.tarData = tarData;
14
- this.target = target;
15
- }
16
- }
package/dist/worker.d.ts DELETED
@@ -1,19 +0,0 @@
1
- import type { UnpackRequest } from './unpack-request.ts';
2
- export type ResponseError = {
3
- id: number;
4
- error: unknown;
5
- };
6
- export type ResponseOK = {
7
- id: number;
8
- ok: true;
9
- };
10
- export declare const isResponseOK: (o: unknown) => o is ResponseOK;
11
- /**
12
- * Basically just a queue of unpack requests,
13
- * to keep them throttled to a reasonable amount of parallelism
14
- */
15
- export declare class Worker {
16
- onMessage: (m: ResponseError | ResponseOK) => void;
17
- constructor(onMessage: (m: ResponseError | ResponseOK) => void);
18
- process(req: UnpackRequest): Promise<void>;
19
- }
package/dist/worker.js DELETED
@@ -1,25 +0,0 @@
1
- import { unpack } from "./unpack.js";
2
- const isObj = (o) => !!o && typeof o === 'object';
3
- export const isResponseOK = (o) => isObj(o) && typeof o.id === 'number' && o.ok === true;
4
- /**
5
- * Basically just a queue of unpack requests,
6
- * to keep them throttled to a reasonable amount of parallelism
7
- */
8
- export class Worker {
9
- onMessage;
10
- constructor(onMessage) {
11
- this.onMessage = onMessage;
12
- }
13
- async process(req) {
14
- const { target, tarData, id } = req;
15
- try {
16
- await unpack(tarData, target);
17
- const m = { id, ok: true };
18
- this.onMessage(m);
19
- }
20
- catch (error) {
21
- const m = { id, error };
22
- this.onMessage(m);
23
- }
24
- }
25
- }