brsh 1.3.0 → 2.0.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.
Files changed (59) hide show
  1. package/.github/workflows/busybox-compat.yml +166 -0
  2. package/.github/workflows/release.yml +40 -0
  3. package/.releaserc.json +18 -0
  4. package/CHANGELOG.md +355 -0
  5. package/bin/brsh-cmd.js +78 -0
  6. package/bin/exportFileSystem.js +81 -156
  7. package/busybox-testsuite/cat.tests +49 -0
  8. package/busybox-testsuite/cp.tests +206 -0
  9. package/busybox-testsuite/grep.tests +237 -0
  10. package/busybox-testsuite/testing.sh +180 -0
  11. package/dist/brsh.css +2 -0
  12. package/dist/shell.es.js +5667 -0
  13. package/dist/shell.es.js.map +1 -0
  14. package/dist/shell.min.js +14 -219
  15. package/dist/shell.min.js.map +1 -147
  16. package/dist/terminal.es.js +6228 -0
  17. package/dist/terminal.es.js.map +1 -0
  18. package/dist/terminal.min.js +113 -18
  19. package/dist/terminal.min.js.map +1 -21
  20. package/index.js +231 -56
  21. package/lib/Command.js +12 -1
  22. package/lib/Context.js +12 -4
  23. package/lib/FileSystem.js +99 -6
  24. package/lib/NodeFileSystem.js +238 -0
  25. package/lib/Result.js +6 -0
  26. package/lib/ScriptCommand.js +193 -15
  27. package/lib/Terminal.js +192 -11
  28. package/lib/WasmCommand.js +252 -0
  29. package/lib/buildFilesystemStructure.js +58 -0
  30. package/lib/builtins/cat.js +67 -9
  31. package/lib/builtins/echo.js +36 -5
  32. package/lib/builtins/false.js +13 -0
  33. package/lib/builtins/grep.js +267 -0
  34. package/lib/builtins/index.js +9 -2
  35. package/lib/builtins/ls.js +86 -18
  36. package/lib/builtins/test.js +105 -0
  37. package/lib/builtins/true.js +10 -0
  38. package/lib/local/chmod.js +72 -0
  39. package/lib/local/cp.js +156 -0
  40. package/lib/local/index.js +9 -1
  41. package/lib/local/jsfunction.js +58 -0
  42. package/lib/local/mkdir.js +44 -0
  43. package/lib/local/mv.js +96 -0
  44. package/lib/local/pwd.js +13 -0
  45. package/lib/local/read.js +107 -0
  46. package/lib/local/rm.js +71 -0
  47. package/lib/local/which.js +2 -2
  48. package/package.json +31 -34
  49. package/test/builtins.test.js +505 -0
  50. package/test/exportFileSystem.test.js +226 -0
  51. package/test/helpers.js +35 -0
  52. package/test/local-commands.test.js +593 -0
  53. package/test/node-filesystem.test.js +133 -0
  54. package/test/scripts.test.js +277 -0
  55. package/test/shell.test.js +245 -0
  56. package/test/streaming.test.js +113 -0
  57. package/vite.config.shell.js +21 -0
  58. package/vite.config.terminal.js +27 -0
  59. package/vitest.config.js +15 -0
@@ -0,0 +1,238 @@
1
+ 'use strict';
2
+
3
+ const nodeFs = require('fs');
4
+ const nodePath = require('path');
5
+
6
+ class NodeFileSystem {
7
+ constructor(cwd, onChange = null) {
8
+ this._onChange = onChange;
9
+ this._changeScheduled = false;
10
+ this._virtualFiles = {};
11
+ this.cwd = this._normalizeCwd(cwd || process.cwd());
12
+ }
13
+
14
+ get isRealFilesystem() { return true; }
15
+
16
+ _normalizeCwd(cwd) {
17
+ const abs = nodePath.resolve(cwd);
18
+ return abs === '/' ? '/' : abs + '/';
19
+ }
20
+
21
+ absolutePath(path) {
22
+ if (path.startsWith('./')) path = path.slice(2);
23
+ const abs = path.startsWith('/') ? path : nodePath.join(this.cwd, path);
24
+ return nodePath.normalize(abs);
25
+ }
26
+
27
+ setCwd(cwd) {
28
+ const trimmed = cwd.endsWith('/') ? cwd.slice(0, -1) : cwd;
29
+ const abs = this.absolutePath(trimmed);
30
+ this.cwd = abs === '/' ? '/' : abs + '/';
31
+ }
32
+
33
+ getFileByPath(path) {
34
+ const abs = this.absolutePath(path);
35
+
36
+ if (this._virtualFiles[abs] !== undefined) {
37
+ return this._virtualFiles[abs];
38
+ }
39
+
40
+ let stat;
41
+ try {
42
+ stat = nodeFs.statSync(abs);
43
+ } catch(e) {
44
+ return null;
45
+ }
46
+
47
+ if (stat.isDirectory()) {
48
+ const entries = {};
49
+ try {
50
+ for (const name of nodeFs.readdirSync(abs)) {
51
+ const childAbs = nodePath.join(abs, name);
52
+ if (this._virtualFiles[childAbs] !== undefined) {
53
+ entries[name] = this._virtualFiles[childAbs];
54
+ } else {
55
+ try {
56
+ entries[name] = nodeFs.statSync(childAbs).isDirectory() ? {} : '';
57
+ } catch(e) { /* skip unreadable */ }
58
+ }
59
+ }
60
+ } catch(e) { /* directory unreadable */ }
61
+
62
+ // Virtual files in this directory not shadowed by real entries
63
+ const prefix = abs === '/' ? '/' : abs + '/';
64
+ for (const vPath of Object.keys(this._virtualFiles)) {
65
+ if (vPath.startsWith(prefix) && !vPath.slice(prefix.length).includes('/')) {
66
+ const name = vPath.slice(prefix.length);
67
+ if (!(name in entries)) entries[name] = this._virtualFiles[vPath];
68
+ }
69
+ }
70
+
71
+ return entries;
72
+ }
73
+
74
+ try {
75
+ return nodeFs.readFileSync(abs, 'utf8');
76
+ } catch(e) {
77
+ return null;
78
+ }
79
+ }
80
+
81
+ setFileByPath(path, content, createDir = false) {
82
+ const abs = this.absolutePath(path);
83
+
84
+ if (typeof content === 'function') {
85
+ this._virtualFiles[abs] = content;
86
+ return;
87
+ }
88
+
89
+ if (content !== null && content !== undefined && content.constructor === Object) {
90
+ nodeFs.mkdirSync(abs, { recursive: createDir });
91
+ this._triggerChange();
92
+ return;
93
+ }
94
+
95
+ if (createDir) {
96
+ nodeFs.mkdirSync(nodePath.dirname(abs), { recursive: true });
97
+ }
98
+ nodeFs.writeFileSync(abs, String(content));
99
+ this._triggerChange();
100
+ }
101
+
102
+ deleteFileByPath(path) {
103
+ const abs = this.absolutePath(path);
104
+ delete this._virtualFiles[abs];
105
+ try {
106
+ const stat = nodeFs.lstatSync(abs);
107
+ if (stat.isDirectory()) {
108
+ nodeFs.rmdirSync(abs);
109
+ } else {
110
+ nodeFs.unlinkSync(abs);
111
+ }
112
+ this._triggerChange();
113
+ } catch(e) { /* may not exist on real fs */ }
114
+ }
115
+
116
+ getMode(path) {
117
+ const abs = this.absolutePath(path);
118
+ if (this._virtualFiles[abs] !== undefined) {
119
+ return typeof this._virtualFiles[abs] === 'function' ? 0o755 : 0o644;
120
+ }
121
+ try {
122
+ return nodeFs.statSync(abs).mode & 0o777;
123
+ } catch(e) {
124
+ return null;
125
+ }
126
+ }
127
+
128
+ setMode(path, mode) {
129
+ nodeFs.chmodSync(this.absolutePath(path), mode);
130
+ this._triggerChange();
131
+ }
132
+
133
+ isExecutable(path) {
134
+ const mode = this.getMode(path);
135
+ if (mode === null) return false;
136
+ return (mode & 0o100) !== 0;
137
+ }
138
+
139
+ getSize(path) {
140
+ const abs = this.absolutePath(path);
141
+ if (this._virtualFiles[abs] !== undefined) return 0;
142
+ try {
143
+ return nodeFs.statSync(abs).size;
144
+ } catch(e) {
145
+ return 0;
146
+ }
147
+ }
148
+
149
+ isSymlink(path) {
150
+ const abs = this.absolutePath(path);
151
+ try { return nodeFs.lstatSync(abs).isSymbolicLink(); } catch(e) { return false; }
152
+ }
153
+
154
+ readSymlink(path) {
155
+ const abs = this.absolutePath(path);
156
+ try { return nodeFs.readlinkSync(abs); } catch(e) { return null; }
157
+ }
158
+
159
+ createSymlink(target, linkPath) {
160
+ const abs = this.absolutePath(linkPath);
161
+ nodeFs.mkdirSync(nodePath.dirname(abs), { recursive: true });
162
+ nodeFs.symlinkSync(target, abs);
163
+ this._triggerChange();
164
+ }
165
+
166
+ getRaw() {
167
+ return null;
168
+ }
169
+
170
+ getRawPermissions() {
171
+ return {};
172
+ }
173
+
174
+ addFiles(commands) {
175
+ Object.entries(commands).forEach(([path, command]) => {
176
+ this.setFileByPath(path, command, true);
177
+ });
178
+ }
179
+
180
+ autoComplete(initial, commandPath) {
181
+ const abs = this.absolutePath(initial);
182
+ const parts = abs.split('/');
183
+ const end = parts.pop();
184
+ const dirPath = parts.join('/') || '/';
185
+
186
+ let dirEntries = [];
187
+ try {
188
+ dirEntries = nodeFs.readdirSync(dirPath);
189
+ } catch(e) { /* not readable */ }
190
+
191
+ const prefix = dirPath === '/' ? '/' : dirPath + '/';
192
+ for (const vPath of Object.keys(this._virtualFiles)) {
193
+ if (vPath.startsWith(prefix) && !vPath.slice(prefix.length).includes('/')) {
194
+ const name = vPath.slice(prefix.length);
195
+ if (!dirEntries.includes(name)) dirEntries.push(name);
196
+ }
197
+ }
198
+
199
+ let options = dirEntries.filter(item => item.startsWith(end));
200
+
201
+ if (options.length === 0 && !initial.includes('/')) {
202
+ const pathDir = this.getFileByPath(commandPath);
203
+ if (pathDir && pathDir.constructor === Object) {
204
+ options = Object.keys(pathDir).filter(item => item.startsWith(initial));
205
+ if (options.length) return { path: null, options };
206
+ }
207
+ }
208
+
209
+ if (!options.length) return null;
210
+
211
+ const initialParts = initial.split('/');
212
+ initialParts.pop();
213
+
214
+ return {
215
+ path: initialParts.length ? initialParts.join('/') : null,
216
+ options: options.map(name => {
217
+ const fullPath = nodePath.join(dirPath, name);
218
+ if (this._virtualFiles[fullPath] !== undefined) return name;
219
+ try {
220
+ return nodeFs.statSync(fullPath).isDirectory() ? name + '/' : name;
221
+ } catch(e) { return name; }
222
+ })
223
+ };
224
+ }
225
+
226
+ _triggerChange() {
227
+ if (!this._onChange || this._changeScheduled) return;
228
+ this._changeScheduled = true;
229
+ Promise.resolve().then(() => {
230
+ this._changeScheduled = false;
231
+ if (typeof this._onChange === 'function') {
232
+ this._onChange(null, null);
233
+ }
234
+ });
235
+ }
236
+ }
237
+
238
+ module.exports = NodeFileSystem;
package/lib/Result.js CHANGED
@@ -31,6 +31,12 @@ class Result {
31
31
  getExitCode() {
32
32
  return this.exitCode;
33
33
  }
34
+
35
+ flush() {
36
+ const data = this.std;
37
+ this.std = [];
38
+ return data;
39
+ }
34
40
  }
35
41
 
36
42
  module.exports = Result;
@@ -10,7 +10,13 @@ class ScriptCommand extends LocalCommand {
10
10
  }
11
11
 
12
12
  run() {
13
- this.sandbox = new global.shell({cwd: this.context.cwd, filesystem: this.context.fs.getRaw()});
13
+ const fsOpts = this.context.fs.isRealFilesystem
14
+ ? { useRealFilesystem: true }
15
+ : { filesystem: this.context.fs.getRaw(), permissions: this.context.fs.getRawPermissions() };
16
+ this.sandbox = new global.shell({
17
+ cwd: this.context.fs.cwd,
18
+ ...fsOpts
19
+ });
14
20
  this.sandbox.context.source(this.context);
15
21
 
16
22
  this.sandbox.on('stdOut', data => this.stdOut = data);
@@ -18,26 +24,198 @@ class ScriptCommand extends LocalCommand {
18
24
 
19
25
  const lines = this.script.split(/\r?\n/);
20
26
 
21
- //check script has interpreter
22
27
  if(!lines[0].startsWith('#!')) {
23
28
  return Promise.reject('no interpreter set');
24
29
  }
25
30
 
26
- return lines.reduce((chain, line) => {
27
- return chain.then(this.sandbox.onCommand(line)
28
- .then(() => {
29
- if (this.sandbox.lastCode !== 0) {
30
- this.exitCode = this.sandbox.lastCode;
31
- return Promise.reject();
32
- }
33
- }));
34
- }, Promise.resolve())
35
- .then(() => {
36
- if(this.source) {
37
- this.context.source(this.sandbox.context);
31
+ const nodes = this._parseLines(lines.slice(1));
32
+ return this._executeNodes(nodes).then(() => {
33
+ this.exitCode = this.sandbox.lastCode;
34
+ if(this.source) {
35
+ this.context.source(this.sandbox.context);
36
+ }
37
+ });
38
+ }
39
+
40
+ _parseLines(lines) {
41
+ const nodes = [];
42
+ let i = 0;
43
+ while (i < lines.length) {
44
+ const line = lines[i].trim();
45
+ if (!line || line.startsWith('#')) { i++; continue; }
46
+
47
+ if (line.startsWith('if ') || line === 'if') {
48
+ const result = this._parseIf(lines, i);
49
+ nodes.push(result.node);
50
+ i += result.consumed;
51
+ continue;
52
+ }
53
+ if (line.startsWith('while ')) {
54
+ const result = this._parseWhile(lines, i);
55
+ nodes.push(result.node);
56
+ i += result.consumed;
57
+ continue;
58
+ }
59
+ if (line.startsWith('for ')) {
60
+ const result = this._parseFor(lines, i);
61
+ nodes.push(result.node);
62
+ i += result.consumed;
63
+ continue;
64
+ }
65
+ nodes.push({ type: 'command', line });
66
+ i++;
67
+ }
68
+ return nodes;
69
+ }
70
+
71
+ _parseIf(lines, start) {
72
+ let condition = lines[start].trim()
73
+ .replace(/^if\s+/, '')
74
+ .replace(/\s*;\s*then\s*$/, '')
75
+ .replace(/\s+then\s*$/, '')
76
+ .trim();
77
+
78
+ let i = start + 1;
79
+ if (i < lines.length && lines[i].trim() === 'then') i++;
80
+
81
+ const thenLines = [], elseLines = [];
82
+ let inElse = false, inElif = false;
83
+ let depth = 1;
84
+
85
+ while (i < lines.length) {
86
+ const line = lines[i].trim();
87
+
88
+ if (line.startsWith('if ')) depth++;
89
+
90
+ if (line === 'fi') {
91
+ depth--;
92
+ if (depth === 0) {
93
+ if (inElif) elseLines.push('fi');
94
+ i++; break;
38
95
  }
96
+ }
97
+
98
+ if (depth === 1 && (line === 'else' || line.startsWith('elif '))) {
99
+ if (!inElse) inElse = true;
100
+ if (line.startsWith('elif ')) {
101
+ inElif = true;
102
+ elseLines.push(line.replace(/^elif/, 'if'));
103
+ } else if (inElif) {
104
+ // 'else' after an elif belongs to the inner if
105
+ elseLines.push(lines[i]);
106
+ }
107
+ i++; continue;
108
+ }
109
+
110
+ if (inElse) elseLines.push(lines[i]);
111
+ else thenLines.push(lines[i]);
112
+ i++;
113
+ }
114
+
115
+ return { node: { type: 'if', condition, thenLines, elseLines }, consumed: i - start };
116
+ }
117
+
118
+ _parseWhile(lines, start) {
119
+ let condition = lines[start].trim()
120
+ .replace(/^while\s+/, '')
121
+ .replace(/\s*;\s*do\s*$/, '')
122
+ .replace(/\s+do\s*$/, '')
123
+ .trim();
124
+
125
+ let i = start + 1;
126
+ if (i < lines.length && lines[i].trim() === 'do') i++;
127
+
128
+ const bodyLines = [];
129
+ let depth = 1;
130
+
131
+ while (i < lines.length) {
132
+ const line = lines[i].trim();
133
+ if (line.startsWith('while ') || line.startsWith('for ')) depth++;
134
+ if (line === 'done') {
135
+ depth--;
136
+ if (depth === 0) { i++; break; }
137
+ }
138
+ bodyLines.push(lines[i]);
139
+ i++;
140
+ }
141
+
142
+ return { node: { type: 'while', condition, bodyLines }, consumed: i - start };
143
+ }
144
+
145
+ _parseFor(lines, start) {
146
+ const firstLine = lines[start].trim()
147
+ .replace(/\s*;\s*do\s*$/, '')
148
+ .replace(/\s+do\s*$/, '');
149
+ const match = firstLine.match(/^for\s+(\w+)\s+in\s+(.+)$/);
150
+ const variable = match ? match[1] : '';
151
+ const list = match ? match[2].trim() : '';
152
+
153
+ let i = start + 1;
154
+ if (i < lines.length && lines[i].trim() === 'do') i++;
155
+
156
+ const bodyLines = [];
157
+ let depth = 1;
158
+
159
+ while (i < lines.length) {
160
+ const line = lines[i].trim();
161
+ if (line.startsWith('while ') || line.startsWith('for ')) depth++;
162
+ if (line === 'done') {
163
+ depth--;
164
+ if (depth === 0) { i++; break; }
165
+ }
166
+ bodyLines.push(lines[i]);
167
+ i++;
168
+ }
169
+
170
+ return { node: { type: 'for', variable, list, bodyLines }, consumed: i - start };
171
+ }
172
+
173
+ _executeNodes(nodes) {
174
+ return nodes.reduce((chain, node) => {
175
+ return chain.then(() => this._executeNode(node));
176
+ }, Promise.resolve());
177
+ }
178
+
179
+ _executeNode(node) {
180
+ if (node.type === 'command') {
181
+ return this.sandbox.onCommand(node.line, false);
182
+ }
183
+ if (node.type === 'if') return this._executeIf(node);
184
+ if (node.type === 'while') return this._executeWhile(node);
185
+ if (node.type === 'for') return this._executeFor(node);
186
+ return Promise.resolve();
187
+ }
188
+
189
+ _executeIf(node) {
190
+ return this.sandbox.onCommand(node.condition, false).then(() => {
191
+ if (this.sandbox.lastCode === 0) {
192
+ return this._executeNodes(this._parseLines(node.thenLines));
193
+ } else if (node.elseLines.length > 0) {
194
+ return this._executeNodes(this._parseLines(node.elseLines));
195
+ }
196
+ });
197
+ }
198
+
199
+ _executeWhile(node) {
200
+ const step = () => this.sandbox.onCommand(node.condition, false).then(() => {
201
+ if (this.sandbox.lastCode === 0) {
202
+ return this._executeNodes(this._parseLines(node.bodyLines)).then(step);
203
+ }
204
+ });
205
+ return step();
206
+ }
207
+
208
+ _executeFor(node) {
209
+ const expanded = node.list.replace(/\${?([\w\d]+)}?/g, (m, name) =>
210
+ this.sandbox.context.getVar(name) || '');
211
+ const items = expanded.split(/\s+/).filter(Boolean);
212
+ return items.reduce((chain, value) => {
213
+ return chain.then(() => {
214
+ this.sandbox.context.setVar(node.variable, value);
215
+ return this._executeNodes(this._parseLines(node.bodyLines));
39
216
  });
217
+ }, Promise.resolve());
40
218
  }
41
219
  }
42
220
 
43
- module.exports = ScriptCommand;
221
+ module.exports = ScriptCommand;