brsh 2.5.1 → 2.5.3

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.
@@ -8,7 +8,7 @@ const SANDBOX_ALLOWED = new Set([
8
8
  'getMode', 'setMode',
9
9
  'isReadable', 'isWritable', 'isExecutable',
10
10
  'getSize', 'autoComplete',
11
- 'isRealFilesystem', 'isSymlink',
11
+ 'isRealFilesystem', 'isSymlink', 'readSymlink', 'createSymlink',
12
12
  ]);
13
13
 
14
14
  /**
package/lib/FileSystem.js CHANGED
@@ -28,6 +28,18 @@ class BinaryFile extends Uint8Array {
28
28
  }
29
29
  }
30
30
 
31
+ /**
32
+ * Represents a symbolic link stored in the virtual filesystem.
33
+ * Acts as an opaque marker: `_resolveByAbsolutePath` follows these
34
+ * transparently during file access, while lstat-like calls return the
35
+ * SymlinkRef itself so callers can detect and report symlinks.
36
+ */
37
+ class SymlinkRef {
38
+ constructor(target) {
39
+ this.target = target;
40
+ }
41
+ }
42
+
31
43
  /**
32
44
  * Recursively converts `data:<mime>;base64,<...>` strings in a filesystem
33
45
  * node to BinaryFile instances (Uint8Array subclass), saving the ~33%
@@ -37,7 +49,7 @@ class BinaryFile extends Uint8Array {
37
49
  function decodeBinaryFiles(node) {
38
50
  for (const key of Object.keys(node)) {
39
51
  const value = node[key];
40
- if (value !== null && typeof value === 'object' && !(value instanceof Uint8Array)) {
52
+ if (value !== null && typeof value === 'object' && !(value instanceof Uint8Array) && !(value instanceof SymlinkRef)) {
41
53
  decodeBinaryFiles(value);
42
54
  } else if (typeof value === 'string' && value.startsWith('data:')) {
43
55
  const semicolon = value.indexOf(';');
@@ -71,9 +83,9 @@ class FileSystem extends BaseFileSystem {
71
83
  }
72
84
 
73
85
  // Returns file content if the path exists AND is readable; null otherwise.
74
- // Use exists() or stat() for permission-free existence/type checks.
86
+ // Follows symlinks transparently. Use exists() or stat() for permission-free checks.
75
87
  getFileByPath(path) {
76
- const file = this._getFileByAbsolutePath(this._pathToAbsolute(path));
88
+ const file = this._resolveByAbsolutePath(this._pathToAbsolute(path), true);
77
89
  if (file === null || file === undefined) return null;
78
90
  if (!this.isReadable(path)) return null;
79
91
  return file;
@@ -84,22 +96,38 @@ class FileSystem extends BaseFileSystem {
84
96
  return this._getFileByAbsolutePath(this._pathToAbsolute(path));
85
97
  }
86
98
 
87
- // Returns true if the path exists regardless of permissions.
99
+ // Returns true if the path exists (and for symlinks, the target resolves too).
88
100
  exists(path) {
89
- const file = this._getFileByAbsolutePath(this._pathToAbsolute(path));
101
+ const file = this._resolveByAbsolutePath(this._pathToAbsolute(path), true);
90
102
  return file !== null && file !== undefined;
91
103
  }
92
104
 
93
- // Returns type metadata without content access or permission checks.
105
+ isSymlink(path) {
106
+ const file = this._resolveByAbsolutePath(this._pathToAbsolute(path), false);
107
+ return file instanceof SymlinkRef;
108
+ }
109
+ readSymlink(path) {
110
+ const file = this._resolveByAbsolutePath(this._pathToAbsolute(path), false);
111
+ return file instanceof SymlinkRef ? file.target : null;
112
+ }
113
+ createSymlink(target, linkPath) {
114
+ this._setFileRaw(linkPath, new SymlinkRef(target));
115
+ }
116
+
117
+ // Returns type metadata without following the final symlink (like lstat).
94
118
  // Returns null if the path does not exist.
95
119
  stat(path) {
96
- const file = this._getFileByAbsolutePath(this._pathToAbsolute(path));
120
+ const file = this._resolveByAbsolutePath(this._pathToAbsolute(path), false);
97
121
  if (file === null || file === undefined) return null;
122
+ if (file instanceof SymlinkRef) {
123
+ return { isDirectory: false, isFile: false, isCommand: false, isBinary: false, isSymlink: true };
124
+ }
98
125
  return {
99
126
  isDirectory: file.constructor === Object,
100
127
  isFile: typeof file === 'string' || file instanceof Uint8Array,
101
128
  isCommand: typeof file === 'function',
102
129
  isBinary: file instanceof Uint8Array,
130
+ isSymlink: false,
103
131
  };
104
132
  }
105
133
 
@@ -156,22 +184,65 @@ class FileSystem extends BaseFileSystem {
156
184
  _setFileByAbsolutePath(absolute, content, createDir = true) {
157
185
  const parts = absolute.split('/');
158
186
  parts.shift();
159
-
160
187
  const filename = parts.pop();
161
188
 
162
- const dir = parts.reduce((pointer, handle) => {
163
- if(!pointer[handle]) {
164
- if(!createDir) {
165
- throw new Error(`${handle}: No such file or directory`)
189
+ let dir = this.fileSystem;
190
+ const pathSoFar = [];
191
+ for (const handle of parts) {
192
+ pathSoFar.push(handle);
193
+ if (!Object.prototype.hasOwnProperty.call(dir, handle)) {
194
+ if (!createDir) throw new Error(`${handle}: No such file or directory`);
195
+ dir[handle] = {};
196
+ }
197
+ let next = dir[handle];
198
+ // Follow symlinks to directories in intermediate path components
199
+ if (next instanceof SymlinkRef) {
200
+ const symlinkDir = '/' + pathSoFar.slice(0, -1).join('/');
201
+ const target = next.target.startsWith('/')
202
+ ? this._traverseComplexAbsolutePath(next.target)
203
+ : this._traverseComplexAbsolutePath(symlinkDir + '/' + next.target);
204
+ next = this._resolveByAbsolutePath(target, true);
205
+ if (next == null || typeof next !== 'object' || next instanceof SymlinkRef) {
206
+ throw new Error(`${handle}: Not a directory`);
166
207
  }
167
- pointer[handle] = {};
168
208
  }
169
- return pointer[handle];
170
- }, this.fileSystem);
171
-
209
+ dir = next;
210
+ }
172
211
  dir[filename] = content;
173
212
  }
174
213
 
214
+ // Resolves a path, optionally following the final symlink component.
215
+ // followLast=true → like stat() — follows everything (for reading through symlinks)
216
+ // followLast=false → like lstat() — stops at a final SymlinkRef (for isSymlink/readSymlink/stat)
217
+ // Intermediate symlinks in directory components are always followed.
218
+ // Returns null on a missing path or a symlink loop (depth > 10).
219
+ _resolveByAbsolutePath(absolute, followLast = true, depth = 0) {
220
+ if (depth > 10) return null; // loop protection
221
+ const parts = absolute.split('/');
222
+ parts.shift();
223
+ if (parts.length > 0 && parts[parts.length - 1].length < 1) parts.pop();
224
+
225
+ let pointer = this.fileSystem;
226
+ const pathSoFar = [];
227
+ for (let i = 0; i < parts.length; i++) {
228
+ const handle = parts[i];
229
+ const isLast = i === parts.length - 1;
230
+ if (pointer == null || typeof pointer !== 'object' || pointer instanceof SymlinkRef) return null;
231
+ if (!Object.prototype.hasOwnProperty.call(pointer, handle)) return null;
232
+ pointer = pointer[handle];
233
+ pathSoFar.push(handle);
234
+ if (pointer instanceof SymlinkRef && (!isLast || followLast)) {
235
+ const symlinkDir = '/' + pathSoFar.slice(0, -1).join('/');
236
+ const target = pointer.target.startsWith('/')
237
+ ? this._traverseComplexAbsolutePath(pointer.target)
238
+ : this._traverseComplexAbsolutePath(symlinkDir + '/' + pointer.target);
239
+ pointer = this._resolveByAbsolutePath(target, true, depth + 1);
240
+ if (pointer == null) return null;
241
+ }
242
+ }
243
+ return pointer;
244
+ }
245
+
175
246
  _getFileByAbsolutePath(absolute) {
176
247
  const parts = absolute.split('/');
177
248
  parts.shift();
@@ -181,10 +252,9 @@ class FileSystem extends BaseFileSystem {
181
252
  }
182
253
 
183
254
  return parts.reduce((pointer, handle) => {
184
- if(pointer && pointer[handle]) {
185
- return pointer[handle];
186
- }
187
- return null;
255
+ if (pointer == null || typeof pointer !== 'object') return null;
256
+ if (!Object.prototype.hasOwnProperty.call(pointer, handle)) return null;
257
+ return pointer[handle];
188
258
  }, this.fileSystem);
189
259
  }
190
260
 
@@ -217,10 +287,22 @@ class FileSystem extends BaseFileSystem {
217
287
  const filename = parts.pop();
218
288
  if (!filename) return;
219
289
 
220
- const parent = parts.reduce((pointer, handle) => {
221
- if (pointer && pointer[handle]) return pointer[handle];
222
- return null;
223
- }, this.fileSystem);
290
+ let parent = this.fileSystem;
291
+ const pathSoFar = [];
292
+ for (const handle of parts) {
293
+ pathSoFar.push(handle);
294
+ if (!Object.prototype.hasOwnProperty.call(parent, handle)) return;
295
+ let next = parent[handle];
296
+ if (next instanceof SymlinkRef) {
297
+ const symlinkDir = '/' + pathSoFar.slice(0, -1).join('/');
298
+ const target = next.target.startsWith('/')
299
+ ? this._traverseComplexAbsolutePath(next.target)
300
+ : this._traverseComplexAbsolutePath(symlinkDir + '/' + next.target);
301
+ next = this._resolveByAbsolutePath(target, true);
302
+ if (next == null || typeof next !== 'object' || next instanceof SymlinkRef) return;
303
+ }
304
+ parent = next;
305
+ }
224
306
 
225
307
  if (parent && filename in parent) {
226
308
  delete parent[filename];
@@ -232,7 +314,7 @@ class FileSystem extends BaseFileSystem {
232
314
  if (this.permissions[absolute] !== undefined) {
233
315
  return this.permissions[absolute];
234
316
  }
235
- const file = this._getFileByAbsolutePath(absolute);
317
+ const file = this._resolveByAbsolutePath(absolute, true);
236
318
  if (file === null || file === undefined) return null;
237
319
  if (file.constructor === Object) return 0o755;
238
320
  if (typeof file === 'function') return 0o555;
@@ -247,7 +329,7 @@ class FileSystem extends BaseFileSystem {
247
329
 
248
330
  getSize(path) {
249
331
  const absolute = this._pathToAbsolute(path);
250
- const file = this._getFileByAbsolutePath(absolute);
332
+ const file = this._resolveByAbsolutePath(absolute, true);
251
333
  if (file === null || file === undefined) return 0;
252
334
  if (file.constructor === Object) return JSON.stringify(file).length;
253
335
  if (file instanceof Uint8Array) return file.length;
@@ -311,3 +393,4 @@ class FileSystem extends BaseFileSystem {
311
393
 
312
394
  module.exports = FileSystem;
313
395
  module.exports.BinaryFile = BinaryFile;
396
+ module.exports.SymlinkRef = SymlinkRef;
package/lib/Terminal.js CHANGED
@@ -149,15 +149,23 @@ class Terminal {
149
149
  this._screen.style.fontFamily = `'${font}', monospace`;
150
150
  parent.appendChild(this._screen);
151
151
 
152
- // Hidden single-character span for measuring character cell dimensions
152
+ // Hidden single-character span for measuring character cell dimensions.
153
+ // fontFamily must be set explicitly to match _cmdList — without it the span
154
+ // inherits from the page font, giving a wrong character width.
153
155
  this._charMeasure = document.createElement('span');
154
156
  this._charMeasure.className = 'terminal__char-measure';
157
+ this._charMeasure.style.fontFamily = `'${font}', monospace`;
155
158
  this._charMeasure.textContent = 'X';
156
159
  this._charMeasure.setAttribute('aria-hidden', 'true');
157
160
  parent.appendChild(this._charMeasure);
158
161
 
159
- // Measure on first paint, then track container resizes
162
+ // Measure on first paint, then re-measure once the webfont is ready
163
+ // (the setTimeout fires before the Google Font downloads, so the initial
164
+ // measurement uses the fallback font; document.fonts.ready corrects it).
160
165
  setTimeout(() => this._measureAndSetSize(), 0);
166
+ if (document.fonts) {
167
+ document.fonts.ready.then(() => this._measureAndSetSize());
168
+ }
161
169
  if (typeof ResizeObserver !== 'undefined') {
162
170
  new ResizeObserver(() => this._measureAndSetSize()).observe(parent);
163
171
  }
@@ -6,10 +6,13 @@ module.exports = [
6
6
  require('./cd'),
7
7
  require('./chmod'),
8
8
  require('./cp'),
9
+ require('./ln'),
9
10
  require('./mkdir'),
10
11
  require('./mv'),
11
12
  require('./pwd'),
12
13
  require('./rm'),
14
+ require('./stat'),
15
+ require('./touch'),
13
16
  require('./which'),
14
17
  require('./source'),
15
18
  require('./clear'),
@@ -0,0 +1,101 @@
1
+ 'use strict';
2
+
3
+ const LocalCommand = require('./LocalCommand');
4
+ const nodeFs = (() => { try { return require('fs'); } catch { return null; } })();
5
+
6
+ class Ln extends LocalCommand {
7
+ static get name() { return 'ln'; }
8
+ get requiresFilesystem() { return true; }
9
+
10
+ run() {
11
+ let symbolic = false;
12
+ let force = false;
13
+ const paths = [];
14
+
15
+ const args = [...this.arguments];
16
+ let i = 0;
17
+ while (i < args.length) {
18
+ const arg = args[i];
19
+ if (arg === '--') { i++; break; }
20
+ if (arg.startsWith('-') && arg.length > 1) {
21
+ for (const ch of arg.slice(1)) {
22
+ switch (ch) {
23
+ case 's': symbolic = true; break;
24
+ case 'f': force = true; break;
25
+ case 'n': break; // --no-dereference, no-op
26
+ case 'v': break; // verbose, no-op
27
+ }
28
+ }
29
+ } else {
30
+ paths.push(arg);
31
+ }
32
+ i++;
33
+ }
34
+ while (i < args.length) paths.push(args[i++]);
35
+
36
+ if (paths.length < 2) {
37
+ this.stdErr = paths.length === 0
38
+ ? 'ln: missing file operand'
39
+ : `ln: missing destination file operand after '${paths[0]}'`;
40
+ this.exitCode = 1;
41
+ return Promise.resolve();
42
+ }
43
+
44
+ const dest = paths[paths.length - 1];
45
+ const sources = paths.slice(0, -1);
46
+ const destStat = this.fs.stat(dest);
47
+ const destIsDir = destStat !== null && destStat.isDirectory;
48
+
49
+ for (const src of sources) {
50
+ const linkPath = destIsDir
51
+ ? dest.replace(/\/$/, '') + '/' + src.split('/').pop()
52
+ : dest;
53
+
54
+ // Remove existing target if -f
55
+ if (force && this.fs.exists(linkPath)) {
56
+ const ls = this.fs.stat(linkPath);
57
+ if (!ls?.isDirectory) {
58
+ try { this.fs.deleteFileByPath(linkPath); } catch(e) { /* ignore */ }
59
+ }
60
+ }
61
+
62
+ if (symbolic) {
63
+ if (!this.fs.createSymlink) {
64
+ this.stdErr = `ln: cannot create symlink '${linkPath}': Operation not supported`;
65
+ this.exitCode = 1;
66
+ continue;
67
+ }
68
+ try {
69
+ this.fs.createSymlink(src, linkPath);
70
+ } catch(e) {
71
+ this.stdErr = `ln: cannot create symlink '${linkPath}': ${e.message}`;
72
+ this.exitCode = 1;
73
+ }
74
+ } else {
75
+ // Hard link — only supported on real FS
76
+ if (!this.fs.isRealFilesystem || !nodeFs) {
77
+ this.stdErr = `ln: cannot create hard link '${linkPath}': Operation not supported`;
78
+ this.exitCode = 1;
79
+ continue;
80
+ }
81
+ if (!this.fs.exists(src)) {
82
+ this.stdErr = `ln: failed to create hard link '${linkPath}' => '${src}': No such file or directory`;
83
+ this.exitCode = 1;
84
+ continue;
85
+ }
86
+ try {
87
+ nodeFs.linkSync(
88
+ this.fs.absolutePath(src),
89
+ this.fs.absolutePath(linkPath)
90
+ );
91
+ } catch(e) {
92
+ this.stdErr = `ln: failed to create hard link '${linkPath}' => '${src}': ${e.message}`;
93
+ this.exitCode = 1;
94
+ }
95
+ }
96
+ }
97
+ return Promise.resolve();
98
+ }
99
+ }
100
+
101
+ module.exports = Ln;
@@ -0,0 +1,94 @@
1
+ 'use strict';
2
+
3
+ const LocalCommand = require('./LocalCommand');
4
+ const nodeFs = (() => { try { return require('fs'); } catch { return null; } })();
5
+
6
+ class Stat extends LocalCommand {
7
+ static get name() { return 'stat'; }
8
+ get requiresFilesystem() { return true; }
9
+
10
+ run() {
11
+ const paths = [];
12
+ for (const arg of this.arguments) {
13
+ if (arg === '--' ) break;
14
+ if (!arg.startsWith('-')) paths.push(arg);
15
+ // -L (follow symlinks) is already our default; other flags ignored
16
+ }
17
+
18
+ if (paths.length === 0) {
19
+ this.stdErr = 'stat: missing operand';
20
+ this.exitCode = 1;
21
+ return Promise.resolve();
22
+ }
23
+
24
+ for (const path of paths) {
25
+ const isLink = this.fs.isSymlink ? this.fs.isSymlink(path) : false;
26
+ if (!this.fs.exists(path) && !isLink) {
27
+ this.stdErr = `stat: cannot stat '${path}': No such file or directory`;
28
+ this.exitCode = 1;
29
+ continue;
30
+ }
31
+ this.stdOut = this._format(path, isLink);
32
+ }
33
+ return Promise.resolve();
34
+ }
35
+
36
+ _format(path, isLink) {
37
+ const abs = this.fs.absolutePath(path);
38
+
39
+ // Real filesystem — use lstat for accurate info
40
+ if (this.fs.isRealFilesystem && nodeFs) {
41
+ try {
42
+ const st = nodeFs.lstatSync(abs);
43
+ const typChar = st.isSymbolicLink() ? 'l'
44
+ : st.isDirectory() ? 'd'
45
+ : '-';
46
+ const typeName = st.isSymbolicLink() ? 'symbolic link'
47
+ : st.isDirectory() ? 'directory'
48
+ : 'regular file';
49
+ const modeOctal = (st.mode & 0o777).toString(8).padStart(4, '0');
50
+ const modeStr = typChar + this._rwxBits(st.mode & 0o777);
51
+ const linkTarget = st.isSymbolicLink() ? ` -> ${nodeFs.readlinkSync(abs)}` : '';
52
+ return [
53
+ ` File: ${abs}${linkTarget}`,
54
+ ` Size: ${st.size}\t\tBlocks: ${st.blocks}\t\tIO Block: ${st.blksize}\t${typeName}`,
55
+ `Device: ${st.dev}\t\tInode: ${st.ino}\t\tLinks: ${st.nlink}`,
56
+ `Access: (${modeOctal}/${modeStr})\tUid: ${st.uid}\tGid: ${st.gid}`,
57
+ `Access: ${st.atime.toISOString()}`,
58
+ `Modify: ${st.mtime.toISOString()}`,
59
+ `Change: ${st.ctime.toISOString()}`,
60
+ ].join('\n');
61
+ } catch(e) {
62
+ return `stat: cannot stat '${path}': ${e.message}`;
63
+ }
64
+ }
65
+
66
+ // Virtual filesystem — derive info from what we have
67
+ const s = this.fs.stat(path);
68
+ const mode = this.fs.getMode(path) ?? 0o644;
69
+ const size = this.fs.getSize(path);
70
+ const typChar = isLink ? 'l' : s?.isDirectory ? 'd' : '-';
71
+ const typeName = isLink ? 'symbolic link'
72
+ : s?.isDirectory ? 'directory'
73
+ : s?.isCommand ? 'regular file'
74
+ : 'regular file';
75
+ const modeOctal = mode.toString(8).padStart(4, '0');
76
+ const modeStr = typChar + this._rwxBits(mode);
77
+ const linkTarget = isLink && this.fs.readSymlink ? ` -> ${this.fs.readSymlink(path)}` : '';
78
+ return [
79
+ ` File: ${abs}${linkTarget}`,
80
+ ` Size: ${size}\t\tType: ${typeName}`,
81
+ `Access: (${modeOctal}/${modeStr})`,
82
+ ].join('\n');
83
+ }
84
+
85
+ _rwxBits(mode) {
86
+ return [
87
+ (mode & 0o400) ? 'r' : '-', (mode & 0o200) ? 'w' : '-', (mode & 0o100) ? 'x' : '-',
88
+ (mode & 0o040) ? 'r' : '-', (mode & 0o020) ? 'w' : '-', (mode & 0o010) ? 'x' : '-',
89
+ (mode & 0o004) ? 'r' : '-', (mode & 0o002) ? 'w' : '-', (mode & 0o001) ? 'x' : '-',
90
+ ].join('');
91
+ }
92
+ }
93
+
94
+ module.exports = Stat;
@@ -0,0 +1,59 @@
1
+ 'use strict';
2
+
3
+ const LocalCommand = require('./LocalCommand');
4
+ const nodeFs = (() => { try { return require('fs'); } catch { return null; } })();
5
+
6
+ class Touch extends LocalCommand {
7
+ static get name() { return 'touch'; }
8
+ get requiresFilesystem() { return true; }
9
+
10
+ run() {
11
+ let noCreate = false;
12
+ const paths = [];
13
+
14
+ for (const arg of this.arguments) {
15
+ if (arg === '--') break;
16
+ if (arg.startsWith('-') && arg.length > 1) {
17
+ for (const ch of arg.slice(1)) {
18
+ if (ch === 'c') noCreate = true;
19
+ // -a, -m, -t, -d: timestamp flags — update timestamps but
20
+ // ignore the specific value (no mtime tracking in virtual FS)
21
+ }
22
+ } else {
23
+ paths.push(arg);
24
+ }
25
+ }
26
+
27
+ if (paths.length === 0) {
28
+ this.stdErr = 'touch: missing file operand';
29
+ this.exitCode = 1;
30
+ return Promise.resolve();
31
+ }
32
+
33
+ const now = new Date();
34
+ for (const path of paths) {
35
+ if (this.fs.exists(path)) {
36
+ // File exists — update timestamps on real FS; no-op on virtual FS
37
+ if (nodeFs && this.fs.isRealFilesystem) {
38
+ try {
39
+ nodeFs.utimesSync(this.fs.absolutePath(path), now, now);
40
+ } catch(e) {
41
+ this.stdErr = `touch: cannot touch '${path}': ${e.message}`;
42
+ this.exitCode = 1;
43
+ }
44
+ }
45
+ } else {
46
+ if (noCreate) continue;
47
+ try {
48
+ this.fs.setFileByPath(path, '', true);
49
+ } catch(e) {
50
+ this.stdErr = `touch: cannot touch '${path}': ${e.message}`;
51
+ this.exitCode = 1;
52
+ }
53
+ }
54
+ }
55
+ return Promise.resolve();
56
+ }
57
+ }
58
+
59
+ module.exports = Touch;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "brsh",
3
- "version": "2.5.1",
3
+ "version": "2.5.3",
4
4
  "description": "A unix like shell written in javascript",
5
5
  "main": "./dist/shell.min.js",
6
6
  "module": "./dist/shell.es.js",
@@ -4,7 +4,7 @@ import { createShell, run } from './helpers.js';
4
4
 
5
5
  const require = createRequire(import.meta.url);
6
6
  const FileSystem = require('../lib/FileSystem.js');
7
- const { BinaryFile } = require('../lib/FileSystem.js');
7
+ const { BinaryFile, SymlinkRef } = require('../lib/FileSystem.js');
8
8
 
9
9
  // Small 1x1 red PNG (base64)
10
10
  const RED_PNG_B64 = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwADhQGAWjR9awAAAABJRU5ErkJggg==';
@@ -89,3 +89,86 @@ describe('FileSystem binary conversion', () => {
89
89
  expect(output.join('')).toBe(RED_PNG_DATA_URI);
90
90
  });
91
91
  });
92
+
93
+ describe('FileSystem virtual symlinks', () => {
94
+ it('createSymlink stores a SymlinkRef', () => {
95
+ const fs = new FileSystem('/', { file: 'hello' });
96
+ fs.createSymlink('/file', '/link');
97
+ const raw = fs._getFileByAbsolutePath('/link');
98
+ expect(raw instanceof SymlinkRef).toBe(true);
99
+ expect(raw.target).toBe('/file');
100
+ });
101
+
102
+ it('isSymlink returns true for a symlink', () => {
103
+ const fs = new FileSystem('/', { file: 'hello' });
104
+ fs.createSymlink('/file', '/link');
105
+ expect(fs.isSymlink('/link')).toBe(true);
106
+ expect(fs.isSymlink('/file')).toBe(false);
107
+ });
108
+
109
+ it('readSymlink returns the target path', () => {
110
+ const fs = new FileSystem('/', { file: 'hello' });
111
+ fs.createSymlink('/file', '/link');
112
+ expect(fs.readSymlink('/link')).toBe('/file');
113
+ });
114
+
115
+ it('getFileByPath follows a symlink', () => {
116
+ const fs = new FileSystem('/', { file: 'hello' });
117
+ fs.createSymlink('/file', '/link');
118
+ expect(fs.getFileByPath('/link')).toBe('hello');
119
+ });
120
+
121
+ it('exists follows a symlink to a valid target', () => {
122
+ const fs = new FileSystem('/', { file: 'hello' });
123
+ fs.createSymlink('/file', '/link');
124
+ expect(fs.exists('/link')).toBe(true);
125
+ });
126
+
127
+ it('exists returns false for a broken symlink', () => {
128
+ const fs = new FileSystem('/', {});
129
+ fs.createSymlink('/missing', '/link');
130
+ expect(fs.exists('/link')).toBe(false);
131
+ });
132
+
133
+ it('stat returns isSymlink:true without following', () => {
134
+ const fs = new FileSystem('/', { file: 'hello' });
135
+ fs.createSymlink('/file', '/link');
136
+ const s = fs.stat('/link');
137
+ expect(s.isSymlink).toBe(true);
138
+ expect(s.isFile).toBe(false);
139
+ });
140
+
141
+ it('stat follows symlinks for a regular file', () => {
142
+ const fs = new FileSystem('/', { file: 'hello' });
143
+ const s = fs.stat('/file');
144
+ expect(s.isFile).toBe(true);
145
+ expect(s.isSymlink).toBe(false);
146
+ });
147
+
148
+ it('follows a chain of symlinks', () => {
149
+ const fs = new FileSystem('/', { file: 'hi' });
150
+ fs.createSymlink('/file', '/a');
151
+ fs.createSymlink('/a', '/b');
152
+ expect(fs.getFileByPath('/b')).toBe('hi');
153
+ });
154
+
155
+ it('returns null for a symlink loop', () => {
156
+ const fs = new FileSystem('/', {});
157
+ fs.createSymlink('/b', '/a');
158
+ fs.createSymlink('/a', '/b');
159
+ expect(fs.getFileByPath('/a')).toBeNull();
160
+ });
161
+
162
+ it('symlink in a subdirectory resolves relative target', () => {
163
+ const fs = new FileSystem('/', { dir: { file: 'content' } });
164
+ fs.createSymlink('file', '/dir/link'); // relative target
165
+ expect(fs.getFileByPath('/dir/link')).toBe('content');
166
+ });
167
+
168
+ it('cat reads through a symlink via the shell', async () => {
169
+ const shell = await createShell({ filesystem: { real: 'symlinked content' } });
170
+ await run(shell, 'ln -s /real /lnk');
171
+ const { output } = await run(shell, 'cat /lnk');
172
+ expect(output.join('')).toBe('symlinked content');
173
+ });
174
+ });