@vltpkg/tar 1.1.0 → 1.2.0

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
@@ -5,7 +5,8 @@
5
5
  A library for unpacking JavaScript package tarballs (gzip-compressed
6
6
  or raw) into a specified folder.
7
7
 
8
- **[Usage](#usage)** · **[Caveats](#caveats)**
8
+ **[Usage](#usage)** · **[Global store](#global-store)** ·
9
+ **[Caveats](#caveats)**
9
10
 
10
11
  ## Overview
11
12
 
@@ -50,7 +51,7 @@ straight out of a cache entry whose file starts with a header block.
50
51
 
51
52
  ### `class Pool`
52
53
 
53
- The interface the vlt CLI extracts through. Both methods are `async`
54
+ The interface the vlt CLI extracts through. All methods are `async`
54
55
  for the caller's convenience; the work itself is synchronous and runs
55
56
  on the main thread.
56
57
 
@@ -65,6 +66,87 @@ Unpack the supplied Buffer of data into the target folder.
65
66
 
66
67
  Unpack a tarball read from `file`, skipping `offset` leading bytes.
67
68
 
69
+ #### `pool.linkFromStore(storeEntry, target, opts?) => Promise<{ how, index } | false>`
70
+
71
+ #### `pool.unpackToStore(tarData, dir) => Promise<{ index }>`
72
+
73
+ See [Global store](#global-store).
74
+
75
+ ## Global store
76
+
77
+ A global store entry is a tarball exploded once into a directory, with
78
+ a sidecar index at `<entry>.json` (`StoreIndex`). Packages are then
79
+ materialized by hardlinking files instead of unpacking the tarball
80
+ again. Publishing entries atomically (sidecar, then rename the dir
81
+ into place) is up to the caller.
82
+
83
+ The vlt CLI keeps its global store under `<cache>/store/v1`, filled by
84
+ a background process, and installs from it with the `store-linker`
85
+ config (`auto` by default, `hardlink`, `copy`; `unpack` skips it).
86
+ `auto` only links on Linux and means `unpack` everywhere else.
87
+
88
+ ### unpackToStoreSync(tarData, dir)
89
+
90
+ Explode a gzipped or raw tarball into `dir` (must not exist) and
91
+ return `{ index }`. Same parsing, path safety and modes as
92
+ `unpackSync`; package.json `bin` targets also get every exec bit, so
93
+ nothing has to chmod them later. Throws, writing nothing, without a
94
+ valid package.json.
95
+
96
+ The index has files (`[path, size, exec]`, sorted), every directory
97
+ (shortest first), `scripts` (install scripts or a root `binding.gyp`),
98
+ normalized `bins`, `name`, `version` and `manifest` (package.json as
99
+ compact JSON text, if valid; lets reify skip reading it back).
100
+
101
+ ### linkFromStore(storeEntry, target, { copy })
102
+
103
+ Hardlink every file of a store entry into a sibling temp dir
104
+ (package.json last), then rename it to `target`. Returns
105
+ `{ how, index }`: `how` is `'link'`, or `'copy'` when files were
106
+ copied instead (see below). Returns `false`, creating nothing, if the
107
+ sidecar is missing or invalid, the entry is not a directory, or the
108
+ target's parent is a symlink. An entry with a missing file is removed
109
+ and `false` returned. Two index paths that collide on a
110
+ case-insensitive target (`EEXIST`) also return `false`.
111
+
112
+ `EXDEV`, `EPERM`, `EACCES` and `ENOTSUP` switch the process to copying
113
+ (read + write into a fresh file); `ENOENT` while both the source and
114
+ the target's parent exist (overlayfs cross-layer links) does the same.
115
+ `EMLINK` copies that file only. Other link errors throw. Every file is
116
+ copied with `copy: true` or when the index has `scripts`, so install
117
+ scripts never write into the store. A copy creates the entry's copied
118
+ marker (`<entry>.copied`), once.
119
+
120
+ `VLT_STORE_VERIFY=1` checks the linked package.json size against the
121
+ index and removes the entry on a mismatch (debugging aid).
122
+
123
+ ### readStoreIndex(storeEntry)
124
+
125
+ The sidecar index, or `undefined` if missing or invalid.
126
+
127
+ ### storeIndexPath(storeEntry)
128
+
129
+ Sidecar path: `<storeEntry>.json`.
130
+
131
+ ### Maintenance
132
+
133
+ - `storeEntryNames(root)`: integrity hex names of the entries under a
134
+ store root (entry dir, sidecar or copied marker).
135
+ - `verifyStoreEntry(storeEntry, tarData)`: compare an entry with its
136
+ tarball (sidecar, file list, bytes). Returns why it differs, or
137
+ `undefined`.
138
+ - `storeEntryLinked(storeEntry, index?)`: true if any file has another
139
+ hardlink, i.e. some `node_modules` uses it.
140
+ - `storeEntryCopied(storeEntry, index?)`: true if the entry has a
141
+ copied marker or install scripts (always copied), i.e. nlink cannot
142
+ show use.
143
+ - `storeCopiedPath(storeEntry)`, `markStoreEntryCopied(storeEntry)`:
144
+ the copied marker, and its exclusive create.
145
+ - `storeEntryTime(storeEntry)`: sidecar mtime in ms (dir mtime without
146
+ one, else 0).
147
+ - `removeStoreEntry(storeEntry)`: remove the dir, then the sidecar and
148
+ copied marker.
149
+
68
150
  ## Caveats
69
151
 
70
152
  As stated above, **this is not a general purpose tar implementation**.
package/dist/index.d.ts CHANGED
@@ -1,2 +1,6 @@
1
- export { unpack } from './unpack.ts';
1
+ export { unpack, unpackToStoreSync } from './unpack.ts';
2
+ export * from './link-tree.ts';
2
3
  export * from './pool.ts';
4
+ export * from './store-entry.ts';
5
+ export { readStoreIndex, storeIndexPath } from './store-index.ts';
6
+ export type { StoreIndex, StoreIndexFile } from './store-index.ts';
package/dist/index.js CHANGED
@@ -1,2 +1,5 @@
1
- export { unpack } from "./unpack.js";
1
+ export { unpack, unpackToStoreSync } from "./unpack.js";
2
+ export * from "./link-tree.js";
2
3
  export * from "./pool.js";
4
+ export * from "./store-entry.js";
5
+ export { readStoreIndex, storeIndexPath } from "./store-index.js";
@@ -0,0 +1,32 @@
1
+ import type { StoreIndex } from './store-index.ts';
2
+ /**
3
+ * How reify places packages: `auto` and `hardlink` link from the global
4
+ * store, `copy` copies from it, `unpack` skips it.
5
+ */
6
+ export type StoreLinker = 'auto' | 'hardlink' | 'copy' | 'unpack';
7
+ /**
8
+ * How a store entry was placed (`copy`: every file copied, for install
9
+ * scripts, `copy` or a downgrade) and its index, or false on a miss.
10
+ */
11
+ export type StoreLinkResult = {
12
+ how: 'link' | 'copy';
13
+ index: StoreIndex;
14
+ } | false;
15
+ export type LinkFromStoreOptions = {
16
+ /**
17
+ * copy every file instead of hardlinking. Implied when the index says
18
+ * the package runs install scripts, which must not write into the store.
19
+ */
20
+ copy?: boolean;
21
+ };
22
+ /**
23
+ * Materialize a global store entry at `target` from its sidecar index:
24
+ * hardlink each file into a sibling temp dir (package.json last), then
25
+ * rename it into place. Files that cannot be linked are copied, as is
26
+ * every file of a package with install scripts. Returns how, with the
27
+ * index, or false, leaving `target` untouched, on a store miss (no
28
+ * valid index, entry not a directory, symlinked target parent), a name
29
+ * clash on a case-insensitive target, or a damaged entry, which is
30
+ * removed.
31
+ */
32
+ export declare const linkFromStore: (storeEntry: string, target: string, { copy }?: LinkFromStoreOptions) => StoreLinkResult;
@@ -0,0 +1,163 @@
1
+ import { chmodSync, linkSync, lstatSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync, } from 'node:fs';
2
+ import { dirname, sep } from 'node:path';
3
+ import { debuglog } from 'node:util';
4
+ import { rimrafSync } from 'rimraf';
5
+ import { markStoreEntryCopied, removeStoreEntry, } from "./store-entry.js";
6
+ import { readStoreIndex } from "./store-index.js";
7
+ import { tmpName } from "./unpack.js";
8
+ const debug = debuglog('vlt');
9
+ const noThrow = { throwIfNoEntry: false };
10
+ // debug spot-check: linked package.json size must match the index
11
+ const verify = process.env.VLT_STORE_VERIFY === '1';
12
+ // Process-wide: once links fail for a reason that will not go away
13
+ // (other device, no hardlink support, permissions), stop trying.
14
+ let copyAll = false;
15
+ const downgrade = (code) => {
16
+ copyAll = true;
17
+ debug('global store: linking failed, copying from now on', code);
18
+ };
19
+ // false: the source is gone, i.e. the store entry is damaged
20
+ const place = (src, dst, exec, copy) => {
21
+ if (!copy && !copyAll) {
22
+ try {
23
+ linkSync(src, dst);
24
+ return true;
25
+ }
26
+ catch (er) {
27
+ const { code = '' } = er;
28
+ if (code === 'ENOENT') {
29
+ if (!lstatSync(src, noThrow))
30
+ return false;
31
+ // target side vanished (node_modules removed mid-install)
32
+ if (!lstatSync(dirname(dst), noThrow))
33
+ throw er;
34
+ // overlayfs can fail cross-layer links with ENOENT
35
+ downgrade(code);
36
+ }
37
+ else if (code === 'EXDEV' ||
38
+ code === 'EPERM' ||
39
+ code === 'EACCES' ||
40
+ code === 'ENOTSUP') {
41
+ downgrade(code);
42
+ }
43
+ else if (code !== 'EMLINK') {
44
+ throw er;
45
+ }
46
+ }
47
+ }
48
+ let body;
49
+ try {
50
+ body = readFileSync(src);
51
+ }
52
+ catch (er) {
53
+ if (er.code === 'ENOENT')
54
+ return false;
55
+ throw er;
56
+ }
57
+ // `wx`: only ever a fresh file, never truncate what may be a link
58
+ writeFileSync(dst, body, { mode: exec ? 0o777 : 0o666, flag: 'wx' });
59
+ // store bins have every exec bit, whatever the umask
60
+ if (exec)
61
+ chmodSync(dst, statSync(src).mode & 0o777);
62
+ return true;
63
+ };
64
+ /**
65
+ * Fill `tmp` from the entry. 'damaged': a source file is gone (or,
66
+ * with VLT_STORE_VERIFY=1, package.json changed size). 'clash': two
67
+ * index paths map to one name on a case-insensitive target.
68
+ */
69
+ const fill = (storeEntry, tmp, index, copy) => {
70
+ // Index paths are validated relative '/'-paths: concatenation is
71
+ // safe and much cheaper than join() on this per-file hot path.
72
+ const native = sep === '/' ?
73
+ (p) => p
74
+ : (p) => p.replaceAll('/', sep);
75
+ const put = ([p, , exec]) => place(storeEntry + sep + native(p), tmp + sep + native(p), exec, copy);
76
+ try {
77
+ for (const d of index.dirs)
78
+ mkdirSync(tmp + sep + native(d));
79
+ let pj;
80
+ for (const f of index.files) {
81
+ if (f[0] === 'package.json')
82
+ pj = f;
83
+ else if (!put(f))
84
+ return 'damaged';
85
+ }
86
+ if (!pj)
87
+ return;
88
+ // last, so an interrupted tmp dir never looks complete
89
+ if (!put(pj))
90
+ return 'damaged';
91
+ if (verify && statSync(tmp + sep + pj[0]).size !== pj[1]) {
92
+ return 'damaged';
93
+ }
94
+ }
95
+ catch (er) {
96
+ if (er.code === 'EEXIST')
97
+ return 'clash';
98
+ throw er;
99
+ }
100
+ };
101
+ /**
102
+ * Materialize a global store entry at `target` from its sidecar index:
103
+ * hardlink each file into a sibling temp dir (package.json last), then
104
+ * rename it into place. Files that cannot be linked are copied, as is
105
+ * every file of a package with install scripts. Returns how, with the
106
+ * index, or false, leaving `target` untouched, on a store miss (no
107
+ * valid index, entry not a directory, symlinked target parent), a name
108
+ * clash on a case-insensitive target, or a damaged entry, which is
109
+ * removed.
110
+ */
111
+ export const linkFromStore = (storeEntry, target, { copy = false } = {}) => {
112
+ const index = readStoreIndex(storeEntry);
113
+ if (!index || !lstatSync(storeEntry, noThrow)?.isDirectory()) {
114
+ return false;
115
+ }
116
+ const parent = lstatSync(dirname(target), noThrow);
117
+ if (parent?.isSymbolicLink())
118
+ return false;
119
+ if (!parent)
120
+ mkdirSync(dirname(target), { recursive: true });
121
+ const tmp = tmpName(target);
122
+ const og = tmp + '.ORIGINAL';
123
+ let succeeded = false;
124
+ try {
125
+ mkdirSync(tmp);
126
+ const copied = copy || index.scripts;
127
+ const miss = fill(storeEntry, tmp, index, copied);
128
+ if (miss === 'clash') {
129
+ debug('global store: name clash in target', storeEntry);
130
+ return false;
131
+ }
132
+ if (miss) {
133
+ debug('global store: removing damaged entry', storeEntry);
134
+ try {
135
+ removeStoreEntry(storeEntry);
136
+ }
137
+ catch { }
138
+ return false;
139
+ }
140
+ const targetExists = !!lstatSync(target, noThrow);
141
+ if (targetExists)
142
+ renameSync(target, og);
143
+ renameSync(tmp, target);
144
+ if (targetExists)
145
+ rimrafSync(og);
146
+ // nlink stays 1: tell prune-store it is used
147
+ if (copied || copyAll)
148
+ markStoreEntryCopied(storeEntry);
149
+ succeeded = true;
150
+ return { how: copied || copyAll ? 'copy' : 'link', index };
151
+ }
152
+ finally {
153
+ if (!succeeded) {
154
+ /* c8 ignore start */
155
+ if (lstatSync(og, noThrow)) {
156
+ rimrafSync(target);
157
+ renameSync(og, target);
158
+ }
159
+ /* c8 ignore stop */
160
+ rimrafSync(tmp);
161
+ }
162
+ }
163
+ };
package/dist/pool.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import type { LinkFromStoreOptions, StoreLinkResult } from './link-tree.ts';
2
+ import type { StoreIndex } from './store-index.ts';
1
3
  /**
2
4
  * Unpacks tarballs into place.
3
5
  *
@@ -22,4 +24,17 @@ export declare class Pool {
22
24
  * registry client's in-memory cache.
23
25
  */
24
26
  unpackFile(file: string, target: string, offset?: number): Promise<void>;
27
+ /**
28
+ * Hardlink (or copy) a global store entry into `target`. Resolves
29
+ * how, with the index, or false on a store miss. See
30
+ * {@link linkFromStore}.
31
+ */
32
+ linkFromStore(storeEntry: string, target: string, opts?: LinkFromStoreOptions): Promise<StoreLinkResult>;
33
+ /**
34
+ * Explode a tarball into `dir` for the global store. See
35
+ * {@link unpackToStoreSync}.
36
+ */
37
+ unpackToStore(tarData: Buffer, dir: string): Promise<{
38
+ index: StoreIndex;
39
+ }>;
25
40
  }
package/dist/pool.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { readFile } from 'node:fs/promises';
2
- import { unpack, unpackFileSync, unpackSync } from "./unpack.js";
2
+ import { linkFromStore } from "./link-tree.js";
3
+ import { unpack, unpackFileSync, unpackSync, unpackToStoreSync, } from "./unpack.js";
3
4
  // Field kill switch: restores the async writer without a release.
4
5
  const syncUnpack = process.env.VLT_TAR_SYNC !== '0';
5
6
  /**
@@ -35,4 +36,19 @@ export class Pool {
35
36
  }
36
37
  unpackFileSync(file, target, offset);
37
38
  }
39
+ /**
40
+ * Hardlink (or copy) a global store entry into `target`. Resolves
41
+ * how, with the index, or false on a store miss. See
42
+ * {@link linkFromStore}.
43
+ */
44
+ async linkFromStore(storeEntry, target, opts) {
45
+ return linkFromStore(storeEntry, target, opts);
46
+ }
47
+ /**
48
+ * Explode a tarball into `dir` for the global store. See
49
+ * {@link unpackToStoreSync}.
50
+ */
51
+ async unpackToStore(tarData, dir) {
52
+ return unpackToStoreSync(tarData, dir);
53
+ }
38
54
  }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Integrity hex names of the global store entries under `root`, each
3
+ * with an entry dir, a sidecar index or a copied marker. Sorted.
4
+ */
5
+ export declare const storeEntryNames: (root: string) => string[];
6
+ /**
7
+ * Marker next to a global store entry: some install copied from it, so
8
+ * its files' nlink cannot show use. See {@link markStoreEntryCopied}.
9
+ */
10
+ export declare const storeCopiedPath: (storeEntry: string) => string;
11
+ /**
12
+ * Mark a global store entry as copied from. Called on copies only:
13
+ * one exclusive create per entry, a failed open after that.
14
+ */
15
+ export declare const markStoreEntryCopied: (storeEntry: string) => void;
16
+ /**
17
+ * Remove a global store entry. Dir first: a sidecar without its dir is
18
+ * a plain miss. Projects linked from it keep their files.
19
+ */
20
+ export declare const removeStoreEntry: (storeEntry: string) => void;
21
+ /**
22
+ * When a global store entry was written, in ms: its sidecar's mtime,
23
+ * else its dir's, else 0.
24
+ */
25
+ export declare const storeEntryTime: (storeEntry: string) => number;
26
+ /**
27
+ * True if the global store entry has a valid sidecar and dir, and was
28
+ * copied from (marker) or has install scripts (always copied). `index`:
29
+ * the sidecar, if already read.
30
+ */
31
+ export declare const storeEntryCopied: (storeEntry: string, index?: import("./store-index.ts").StoreIndex | undefined) => boolean;
32
+ /**
33
+ * True if a file of the global store entry has another hardlink
34
+ * (nlink > 1), i.e. some `node_modules` uses it. Without a valid
35
+ * sidecar nothing can link from it, so false. `index`: the sidecar, if
36
+ * already read.
37
+ */
38
+ export declare const storeEntryLinked: (storeEntry: string, index?: import("./store-index.ts").StoreIndex | undefined) => boolean;
39
+ /**
40
+ * Check a global store entry against the tarball it was exploded from:
41
+ * sidecar index, file list, every file's bytes and exec bit (not on
42
+ * Windows). Returns why it does not match, or undefined if it does.
43
+ */
44
+ export declare const verifyStoreEntry: (storeEntry: string, tarData: Buffer) => string | undefined;
@@ -0,0 +1,146 @@
1
+ import { closeSync, lstatSync, openSync, readdirSync, readFileSync, statSync, } from 'node:fs';
2
+ import { join, relative } from 'node:path';
3
+ import { isDeepStrictEqual } from 'node:util';
4
+ import { rimrafSync } from 'rimraf';
5
+ import { readStoreIndex, storeIndexPath } from "./store-index.js";
6
+ import { storeLayout } from "./unpack.js";
7
+ const noThrow = { throwIfNoEntry: false };
8
+ const entryName = /^([0-9a-f]{128})(?:\.json|\.copied)?$/;
9
+ const relPath = (from, to) => relative(from, to).replace(/\\/g, '/');
10
+ /**
11
+ * Integrity hex names of the global store entries under `root`, each
12
+ * with an entry dir, a sidecar index or a copied marker. Sorted.
13
+ */
14
+ export const storeEntryNames = (root) => {
15
+ let names;
16
+ try {
17
+ names = readdirSync(root);
18
+ }
19
+ catch {
20
+ return [];
21
+ }
22
+ const hexes = new Set();
23
+ for (const name of names) {
24
+ const hex = entryName.exec(name)?.[1];
25
+ if (hex)
26
+ hexes.add(hex);
27
+ }
28
+ return [...hexes].sort();
29
+ };
30
+ /**
31
+ * Marker next to a global store entry: some install copied from it, so
32
+ * its files' nlink cannot show use. See {@link markStoreEntryCopied}.
33
+ */
34
+ export const storeCopiedPath = (storeEntry) => storeEntry + '.copied';
35
+ /**
36
+ * Mark a global store entry as copied from. Called on copies only:
37
+ * one exclusive create per entry, a failed open after that.
38
+ */
39
+ export const markStoreEntryCopied = (storeEntry) => {
40
+ try {
41
+ closeSync(openSync(storeCopiedPath(storeEntry), 'wx'));
42
+ }
43
+ catch {
44
+ // EEXIST: marked. Else prune-store may drop it: only a re-explode.
45
+ }
46
+ };
47
+ /**
48
+ * Remove a global store entry. Dir first: a sidecar without its dir is
49
+ * a plain miss. Projects linked from it keep their files.
50
+ */
51
+ export const removeStoreEntry = (storeEntry) => {
52
+ rimrafSync(storeEntry);
53
+ rimrafSync(storeIndexPath(storeEntry));
54
+ rimrafSync(storeCopiedPath(storeEntry));
55
+ };
56
+ /**
57
+ * When a global store entry was written, in ms: its sidecar's mtime,
58
+ * else its dir's, else 0.
59
+ */
60
+ export const storeEntryTime = (storeEntry) => (statSync(storeIndexPath(storeEntry), noThrow) ??
61
+ statSync(storeEntry, noThrow))?.mtimeMs ?? 0;
62
+ /**
63
+ * True if the global store entry has a valid sidecar and dir, and was
64
+ * copied from (marker) or has install scripts (always copied). `index`:
65
+ * the sidecar, if already read.
66
+ */
67
+ export const storeEntryCopied = (storeEntry, index = readStoreIndex(storeEntry)) => !!index &&
68
+ (index.scripts ||
69
+ !!lstatSync(storeCopiedPath(storeEntry), noThrow)) &&
70
+ !!lstatSync(storeEntry, noThrow)?.isDirectory();
71
+ /**
72
+ * True if a file of the global store entry has another hardlink
73
+ * (nlink > 1), i.e. some `node_modules` uses it. Without a valid
74
+ * sidecar nothing can link from it, so false. `index`: the sidecar, if
75
+ * already read.
76
+ */
77
+ export const storeEntryLinked = (storeEntry, index = readStoreIndex(storeEntry)) => !!index?.files.some(([p]) => (lstatSync(join(storeEntry, p), noThrow)?.nlink ?? 1) > 1);
78
+ // v1 fields; `manifest` only if present (older sidecars lack it);
79
+ // optional fields added later stay unchecked
80
+ const indexKeys = [
81
+ 'v',
82
+ 'files',
83
+ 'dirs',
84
+ 'scripts',
85
+ 'bins',
86
+ 'name',
87
+ 'version',
88
+ ];
89
+ /**
90
+ * Check a global store entry against the tarball it was exploded from:
91
+ * sidecar index, file list, every file's bytes and exec bit (not on
92
+ * Windows). Returns why it does not match, or undefined if it does.
93
+ */
94
+ export const verifyStoreEntry = (storeEntry, tarData) => {
95
+ let layout;
96
+ try {
97
+ layout = storeLayout(tarData, storeEntry);
98
+ }
99
+ catch {
100
+ return 'bad tarball';
101
+ }
102
+ const index = readStoreIndex(storeEntry);
103
+ if (!index)
104
+ return 'no index';
105
+ if (indexKeys.some(k => !isDeepStrictEqual(index[k], layout.index[k])) ||
106
+ (index.manifest !== undefined &&
107
+ index.manifest !== layout.index.manifest)) {
108
+ return 'index differs';
109
+ }
110
+ const found = new Set();
111
+ try {
112
+ for (const d of readdirSync(storeEntry, {
113
+ recursive: true,
114
+ withFileTypes: true,
115
+ })) {
116
+ if (!d.isDirectory()) {
117
+ found.add(relPath(storeEntry, join(d.parentPath, d.name)));
118
+ }
119
+ }
120
+ }
121
+ catch {
122
+ return 'missing';
123
+ }
124
+ const modes = process.platform !== 'win32';
125
+ for (const f of layout.files) {
126
+ const p = relPath(storeEntry, f.path);
127
+ if (!found.delete(p))
128
+ return `missing ${p}`;
129
+ let body;
130
+ let mode;
131
+ try {
132
+ mode = statSync(f.path).mode;
133
+ body = readFileSync(f.path);
134
+ }
135
+ catch {
136
+ return `unreadable ${p}`;
137
+ }
138
+ if (!body.equals(f.body))
139
+ return `modified ${p}`;
140
+ if (modes && ((mode & 0o111) !== 0) !== f.executable) {
141
+ return `mode ${p}`;
142
+ }
143
+ }
144
+ const [extra] = found;
145
+ return extra === undefined ? undefined : `extra ${extra}`;
146
+ };
@@ -0,0 +1,43 @@
1
+ /** `[path, size, exec]` of one file in a global store entry. */
2
+ export type StoreIndexFile = [path: string, size: number, exec: 0 | 1];
3
+ /**
4
+ * Sidecar index of a global store entry, stored at
5
+ * {@link storeIndexPath}. Lets a reader materialize the entry without
6
+ * walking it, and know before touching it whether the package runs
7
+ * install scripts.
8
+ */
9
+ export type StoreIndex = {
10
+ v: 1;
11
+ /** relative, `/`-separated, sorted by path */
12
+ files: StoreIndexFile[];
13
+ /** every directory, shortest first */
14
+ dirs: string[];
15
+ /** has an install/preinstall/postinstall script or a root binding.gyp */
16
+ scripts: boolean;
17
+ /** normalized package.json `bin` */
18
+ bins?: Record<string, string>;
19
+ name?: string;
20
+ version?: string;
21
+ /**
22
+ * package.json as compact JSON text, if a valid manifest, so reify
23
+ * need not read it back from disk. Text, so a reader that does not
24
+ * need it skips the parse. Absent in entries written before it.
25
+ */
26
+ manifest?: string;
27
+ };
28
+ /** Index fields read from the tarball's own package.json. */
29
+ export type StoreIndexManifest = Pick<StoreIndex, 'scripts' | 'bins' | 'name' | 'version' | 'manifest'>;
30
+ /** The sidecar is a sibling, so it is never linked with the tree. */
31
+ export declare const storeIndexPath: (storeEntry: string) => string;
32
+ /**
33
+ * Read the sidecar index of a global store entry. Missing, unparseable
34
+ * or malformed is a store miss (undefined), never an error.
35
+ */
36
+ export declare const readStoreIndex: (storeEntry: string) => StoreIndex | undefined;
37
+ /**
38
+ * Index fields from a tarball's package.json. `scripts` uses the same
39
+ * predicate as reify's build check: an install lifecycle script, or a
40
+ * root binding.gyp (implicit `node-gyp rebuild`). Throws on anything
41
+ * but a JSON object, so such tarballs never become store entries.
42
+ */
43
+ export declare const storeIndexManifest: (packageJson: Buffer, bindingGyp: boolean) => StoreIndexManifest;
@@ -0,0 +1,86 @@
1
+ import { error } from '@vltpkg/error-cause';
2
+ import { isManifest, normalizeBinPaths } from '@vltpkg/types';
3
+ import { readFileSync } from 'node:fs';
4
+ import { debuglog } from 'node:util';
5
+ const debug = debuglog('vlt');
6
+ /** The sidecar is a sibling, so it is never linked with the tree. */
7
+ export const storeIndexPath = (storeEntry) => storeEntry + '.json';
8
+ const isRecord = (x) => !!x && typeof x === 'object' && !Array.isArray(x);
9
+ const isOptString = (x) => x === undefined || typeof x === 'string';
10
+ // empty, `.` or `..` segment, or a backslash: could escape when joined
11
+ const unsafePath = /(?:^|\/)\.{0,2}(?:\/|$)|\\/;
12
+ const isRelPath = (p) => typeof p === 'string' && !unsafePath.test(p);
13
+ const isIndexFile = (f) => Array.isArray(f) &&
14
+ f.length === 3 &&
15
+ isRelPath(f[0]) &&
16
+ typeof f[1] === 'number' &&
17
+ (f[2] === 0 || f[2] === 1);
18
+ const isStoreIndex = (x) => isRecord(x) &&
19
+ x.v === 1 &&
20
+ typeof x.scripts === 'boolean' &&
21
+ isOptString(x.name) &&
22
+ isOptString(x.version) &&
23
+ (x.bins === undefined ||
24
+ (isRecord(x.bins) &&
25
+ Object.values(x.bins).every(b => typeof b === 'string'))) &&
26
+ Array.isArray(x.dirs) &&
27
+ x.dirs.every(isRelPath) &&
28
+ Array.isArray(x.files) &&
29
+ x.files.every(isIndexFile) &&
30
+ isOptString(x.manifest);
31
+ /**
32
+ * Read the sidecar index of a global store entry. Missing, unparseable
33
+ * or malformed is a store miss (undefined), never an error.
34
+ */
35
+ export const readStoreIndex = (storeEntry) => {
36
+ let index;
37
+ try {
38
+ index = JSON.parse(readFileSync(storeIndexPath(storeEntry), 'utf8'));
39
+ }
40
+ catch (er) {
41
+ if (er.code !== 'ENOENT') {
42
+ debug('global store: invalid index', storeEntry);
43
+ }
44
+ return undefined;
45
+ }
46
+ if (isStoreIndex(index))
47
+ return index;
48
+ debug('global store: invalid index', storeEntry);
49
+ return undefined;
50
+ };
51
+ /**
52
+ * Index fields from a tarball's package.json. `scripts` uses the same
53
+ * predicate as reify's build check: an install lifecycle script, or a
54
+ * root binding.gyp (implicit `node-gyp rebuild`). Throws on anything
55
+ * but a JSON object, so such tarballs never become store entries.
56
+ */
57
+ export const storeIndexManifest = (packageJson, bindingGyp) => {
58
+ let pkg;
59
+ try {
60
+ pkg = JSON.parse(packageJson.toString('utf8').replace(/^\uFEFF/, ''));
61
+ }
62
+ catch (cause) {
63
+ throw error('invalid package.json in tarball', { cause });
64
+ }
65
+ if (!isRecord(pkg)) {
66
+ throw error('invalid package.json in tarball', { found: pkg });
67
+ }
68
+ const { name, version, scripts, bin } = pkg;
69
+ const s = isRecord(scripts) ? scripts : {};
70
+ const result = {
71
+ scripts: !!(s.install || s.preinstall || s.postinstall) || bindingGyp,
72
+ };
73
+ const bins = normalizeBinPaths({
74
+ name: typeof name === 'string' ? name : undefined,
75
+ bin: bin,
76
+ });
77
+ if (bins && Object.keys(bins).length)
78
+ result.bins = bins;
79
+ if (typeof name === 'string')
80
+ result.name = name;
81
+ if (typeof version === 'string')
82
+ result.version = version;
83
+ if (isManifest(pkg))
84
+ result.manifest = JSON.stringify(pkg);
85
+ return result;
86
+ };
package/dist/unpack.d.ts CHANGED
@@ -1,3 +1,12 @@
1
+ import type { StoreIndex } from './store-index.ts';
2
+ /** A file parsed out of a tarball, at its destination path. */
3
+ export type FileEntry = {
4
+ path: string;
5
+ body: Buffer;
6
+ /** written with the exec bit: world-executable in the tar header */
7
+ executable: boolean;
8
+ dir: false;
9
+ };
1
10
  export declare const checkFs: (h: {
2
11
  path?: string;
3
12
  }, tarDir: string | undefined, target: string) => h is {
@@ -15,3 +24,27 @@ export declare const unpackSync: (tarData: Buffer, target: string) => void;
15
24
  * tarball never lands in the registry client's in-memory cache.
16
25
  */
17
26
  export declare const unpackFileSync: (file: string, target: string, offset?: number) => void;
27
+ /** Sibling temp path used to build `target` before renaming it in. */
28
+ export declare const tmpName: (target: string) => string;
29
+ /**
30
+ * What a gzipped or raw tarball explodes to in the global store at
31
+ * `dir`: its sidecar index, files and package.json `bin` target paths.
32
+ * Same parsing and path safety as {@link unpackSync}. No IO. Throws if
33
+ * the tarball has no valid package.json.
34
+ */
35
+ export declare const storeLayout: (tarData: Buffer, dir: string) => {
36
+ index: StoreIndex;
37
+ files: FileEntry[];
38
+ binFiles: string[];
39
+ };
40
+ /**
41
+ * Explode a gzipped or raw tarball into `dir` for the global store and
42
+ * return its sidecar index (see {@link storeLayout}), written straight
43
+ * into `dir` (which must not exist; the caller renames it into place).
44
+ * Same modes as {@link unpackSync} followed by reify's bin chmod.
45
+ * Throws, writing nothing, without a valid package.json. Removes `dir`
46
+ * on failure.
47
+ */
48
+ export declare const unpackToStoreSync: (tarData: Buffer, dir: string) => {
49
+ index: StoreIndex;
50
+ };
package/dist/unpack.js CHANGED
@@ -1,13 +1,14 @@
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
+ import { chmodSync, lstatSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync, } from 'node:fs';
4
4
  import { lstat, mkdir, rename, writeFile } from 'node:fs/promises';
5
- import { basename, dirname, isAbsolute, relative, resolve, sep, } from 'node:path';
5
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep, } from 'node:path';
6
6
  import { rimraf, rimrafSync } from 'rimraf';
7
7
  import { Header } from 'tar/header';
8
8
  import { Pax } from 'tar/pax';
9
9
  import { unzip as unzipCB, unzipSync as unzipSyncCB } from 'node:zlib';
10
10
  import { findTarDir } from "./find-tar-dir.js";
11
+ import { storeIndexManifest } from "./store-index.js";
11
12
  // Matches node-tar's MAX_DECOMPRESSION_RATIO, which npm uses via pacote.
12
13
  const MAX_DECOMPRESSION_RATIO = 1000;
13
14
  // node-tar streams, so its ratio alone bounds peak memory. We inflate into
@@ -188,10 +189,11 @@ export const unpackSync = (tarData, target) => {
188
189
  * tarball never lands in the registry client's in-memory cache.
189
190
  */
190
191
  export const unpackFileSync = (file, target, offset = 0) => unpackSync(readFileSync(file).subarray(offset), target);
191
- const tmpName = (target) => dirname(target) + sep + '.' + basename(target) + '.' + tmpSuffix();
192
+ /** Sibling temp path used to build `target` before renaming it in. */
193
+ export const tmpName = (target) => dirname(target) + sep + '.' + basename(target) + '.' + tmpSuffix();
192
194
  /**
193
195
  * 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.
196
+ * all writers share it and cannot drift on path sanitization.
195
197
  */
196
198
  const parseTarball = (buffer, tmp) => {
197
199
  /* c8 ignore start */
@@ -386,3 +388,88 @@ const unpackUnzippedSync = (buffer, target) => {
386
388
  }
387
389
  }
388
390
  };
391
+ /**
392
+ * What a gzipped or raw tarball explodes to in the global store at
393
+ * `dir`: its sidecar index, files and package.json `bin` target paths.
394
+ * Same parsing and path safety as {@link unpackSync}. No IO. Throws if
395
+ * the tarball has no valid package.json.
396
+ */
397
+ export const storeLayout = (tarData, dir) => {
398
+ const isGzip = tarData[0] === 0x1f && tarData[1] === 0x8b;
399
+ const { dirs, files } = parseTarball(isGzip ? unzipSync(tarData) : tarData, dir);
400
+ const rel = (p) => relative(dir, p).replace(/\\/g, '/');
401
+ const list = files.map(f => [rel(f.path), f]);
402
+ const pj = list.find(([p]) => p === 'package.json')?.[1];
403
+ if (!pj)
404
+ throw error('no package.json in tarball', { path: dir });
405
+ const manifest = storeIndexManifest(pj.body, list.some(([p]) => p === 'binding.gyp'));
406
+ const bins = new Set(Object.values(manifest.bins ?? {}).map(entryKey));
407
+ const indexFiles = [];
408
+ const binFiles = [];
409
+ for (const [p, f] of list) {
410
+ if (bins.has(entryKey(p))) {
411
+ f.executable = true;
412
+ binFiles.push(f.path);
413
+ }
414
+ indexFiles.push([p, f.body.length, f.executable ? 1 : 0]);
415
+ }
416
+ const allDirs = new Set();
417
+ for (const d of dirs) {
418
+ for (let p = rel(d); p && !allDirs.has(p);) {
419
+ allDirs.add(p);
420
+ p = p.slice(0, Math.max(0, p.lastIndexOf('/')));
421
+ }
422
+ }
423
+ // stable sort: lexical within each length
424
+ const indexDirs = [...allDirs]
425
+ .sort()
426
+ .sort((a, b) => a.length - b.length);
427
+ return {
428
+ index: {
429
+ v: 1,
430
+ files: indexFiles.sort((a, b) => (a[0] < b[0] ? -1 : 1)),
431
+ dirs: indexDirs,
432
+ ...manifest,
433
+ },
434
+ files,
435
+ binFiles,
436
+ };
437
+ };
438
+ /**
439
+ * Explode a gzipped or raw tarball into `dir` for the global store and
440
+ * return its sidecar index (see {@link storeLayout}), written straight
441
+ * into `dir` (which must not exist; the caller renames it into place).
442
+ * Same modes as {@link unpackSync} followed by reify's bin chmod.
443
+ * Throws, writing nothing, without a valid package.json. Removes `dir`
444
+ * on failure.
445
+ */
446
+ export const unpackToStoreSync = (tarData, dir) => {
447
+ const { index, files, binFiles } = storeLayout(tarData, dir);
448
+ mkdirSync(dirname(dir), { recursive: true });
449
+ mkdirSync(dir, { mode: 0o777 });
450
+ let succeeded = false;
451
+ try {
452
+ // recursive: tolerates dirs that differ only by case, like unpackSync
453
+ for (const d of index.dirs) {
454
+ mkdirSync(join(dir, d), { recursive: true, mode: 0o777 });
455
+ }
456
+ for (const f of files) {
457
+ writeFileSync(f.path, f.body, {
458
+ mode: f.executable ? 0o777 : 0o666,
459
+ });
460
+ }
461
+ // reify's bin chmod result (umask'd mode plus all exec bits), so it
462
+ // never has to chmod a store inode through a link
463
+ let binMode = 0;
464
+ for (const p of binFiles) {
465
+ binMode ||= (statSync(p).mode & 0o777) | 0o111;
466
+ chmodSync(p, binMode);
467
+ }
468
+ succeeded = true;
469
+ }
470
+ finally {
471
+ if (!succeeded)
472
+ rimrafSync(dir);
473
+ }
474
+ return { index };
475
+ };
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.1.0",
4
+ "version": "1.2.0",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "git+https://github.com/vltpkg/vltpkg.git",
@@ -13,7 +13,8 @@
13
13
  "url": "http://vlt.sh"
14
14
  },
15
15
  "dependencies": {
16
- "@vltpkg/error-cause": "1.1.0",
16
+ "@vltpkg/error-cause": "1.2.0",
17
+ "@vltpkg/types": "1.2.0",
17
18
  "rimraf": "^6.1.2",
18
19
  "tar": "^7.5.2"
19
20
  },
@@ -25,7 +26,7 @@
25
26
  "eslint": "^9.39.1",
26
27
  "pacote": "^21.0.4",
27
28
  "prettier": "^3.7.4",
28
- "tap": "^21.5.0",
29
+ "tap": "^21.8.0",
29
30
  "typedoc": "~0.27.9",
30
31
  "typescript": "5.7.3",
31
32
  "typescript-eslint": "^8.49.0"
@@ -59,11 +60,26 @@
59
60
  "default": "./dist/index.js"
60
61
  }
61
62
  },
63
+ "./link-tree": {
64
+ "import": {
65
+ "default": "./dist/link-tree.js"
66
+ }
67
+ },
62
68
  "./pool": {
63
69
  "import": {
64
70
  "default": "./dist/pool.js"
65
71
  }
66
72
  },
73
+ "./store-entry": {
74
+ "import": {
75
+ "default": "./dist/store-entry.js"
76
+ }
77
+ },
78
+ "./store-index": {
79
+ "import": {
80
+ "default": "./dist/store-index.js"
81
+ }
82
+ },
67
83
  "./unpack": {
68
84
  "import": {
69
85
  "default": "./dist/unpack.js"