brsh 2.1.5 → 2.2.1

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/index.js CHANGED
@@ -156,6 +156,15 @@ class Shell extends EventEmitter {
156
156
  if (!args.length) return;
157
157
  let bin = args.shift().value;
158
158
 
159
+ // Bare variable assignment: VAR=value (only when no additional args)
160
+ if (args.length === 0 && /^[A-Za-z_]\w*=/.test(bin)) {
161
+ const eqIdx = bin.indexOf('=');
162
+ this.context.setVar(bin.slice(0, eqIdx), bin.slice(eqIdx + 1));
163
+ this.lastCode = 0;
164
+ this.emit('exitCode', 0);
165
+ return;
166
+ }
167
+
159
168
  // Parse output redirection (> and >>)
160
169
  // Quoted tokens (hasQuote: true) are never treated as redirects.
161
170
  let redirectPath = null;
package/lib/Command.js CHANGED
@@ -38,7 +38,7 @@ class Command extends EventEmitter {
38
38
  }
39
39
 
40
40
  onInput(char) {
41
- //ignnored by default, can be overridden in a command if needed to get input
41
+ //ignored by default, can be overridden in a command if needed to get input
42
42
  }
43
43
 
44
44
  set exitCode(code) {
@@ -54,7 +54,6 @@ class Command extends EventEmitter {
54
54
  }
55
55
 
56
56
  flush() {
57
- console.log("flush now");
58
57
  this.emit('flush', this.result.flush());
59
58
  }
60
59
  }
@@ -2,6 +2,14 @@
2
2
 
3
3
  const LocalCommand = require('./local/LocalCommand');
4
4
 
5
+ /**
6
+ * Returns true if the first line of a file is a shebang for a known/supported
7
+ * interpreter: #!/sh.js (legacy), #!/bin/sh, or #!/bin/brsh.
8
+ */
9
+ function isKnownInterpreter(firstLine) {
10
+ return /^#!\/(sh\.js|bin\/(sh|brsh))/.test(firstLine);
11
+ }
12
+
5
13
  class ScriptCommand extends LocalCommand {
6
14
  constructor(script, args, context, source = false) {
7
15
  super(args, context);
@@ -9,6 +17,21 @@ class ScriptCommand extends LocalCommand {
9
17
  this.source = source;
10
18
  }
11
19
 
20
+ // Only capture input when the sandbox itself has a command waiting for it
21
+ // (e.g. an active `read`). This prevents swallowing keystrokes during
22
+ // normal command execution.
23
+ get captureInput() {
24
+ return !!(this.sandbox
25
+ && this.sandbox.runningCommand
26
+ && this.sandbox.runningCommand.captureInput);
27
+ }
28
+
29
+ onInput(char) {
30
+ if (this.sandbox) {
31
+ this.sandbox.onInput(char);
32
+ }
33
+ }
34
+
12
35
  run() {
13
36
  const fsOpts = this.context.fs.isRealFilesystem
14
37
  ? { useRealFilesystem: true }
@@ -19,22 +42,35 @@ class ScriptCommand extends LocalCommand {
19
42
  });
20
43
  this.sandbox.context.source(this.context);
21
44
 
22
- this.sandbox.on('stdOut', data => this.stdOut = data);
23
- this.sandbox.on('stdErr', data => this.stdErr = data);
45
+ this.sandbox.on('stdOut', data => { this.stdOut = data; this.flush(); });
46
+ this.sandbox.on('stdErr', data => { this.stdErr = data; this.flush(); });
47
+
48
+ this._scriptFunctions = {};
24
49
 
25
50
  const lines = this.script.split(/\r?\n/);
26
51
 
27
- if(!lines[0].startsWith('#!')) {
28
- return Promise.reject('no interpreter set');
52
+ if (!isKnownInterpreter(lines[0])) {
53
+ const interpreter = lines[0].startsWith('#!')
54
+ ? lines[0].slice(2).split(/\s/)[0]
55
+ : lines[0];
56
+ return Promise.reject(`${interpreter}: bad interpreter: No such file or directory`);
29
57
  }
30
58
 
31
59
  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
- });
60
+ return this._executeNodes(nodes)
61
+ .catch(e => {
62
+ if (e && e.__type === 'return') {
63
+ this.sandbox.lastCode = e.code;
64
+ } else {
65
+ return Promise.reject(e);
66
+ }
67
+ })
68
+ .then(() => {
69
+ this.exitCode = this.sandbox.lastCode;
70
+ if(this.source) {
71
+ this.context.source(this.sandbox.context);
72
+ }
73
+ });
38
74
  }
39
75
 
40
76
  _parseLines(lines) {
@@ -62,6 +98,18 @@ class ScriptCommand extends LocalCommand {
62
98
  i += result.consumed;
63
99
  continue;
64
100
  }
101
+ if (line.startsWith('case ') || line === 'case') {
102
+ const result = this._parseCase(lines, i);
103
+ nodes.push(result.node);
104
+ i += result.consumed;
105
+ continue;
106
+ }
107
+ if (/^(?:function\s+[\w\d_]+|[\w\d_]+\s*\(\s*\))\s*(?:\{.*)?$/.test(line)) {
108
+ const result = this._parseFunction(lines, i);
109
+ nodes.push(result.node);
110
+ i += result.consumed;
111
+ continue;
112
+ }
65
113
  nodes.push({ type: 'command', line });
66
114
  i++;
67
115
  }
@@ -69,50 +117,51 @@ class ScriptCommand extends LocalCommand {
69
117
  }
70
118
 
71
119
  _parseIf(lines, start) {
72
- let condition = lines[start].trim()
73
- .replace(/^if\s+/, '')
120
+ const parseCondition = str => str
121
+ .replace(/^(?:if|elif)\s+/, '')
74
122
  .replace(/\s*;\s*then\s*$/, '')
75
123
  .replace(/\s+then\s*$/, '')
76
124
  .trim();
77
125
 
126
+ const clauses = [{ condition: parseCondition(lines[start].trim()), bodyLines: [] }];
127
+ const elseLines = [];
128
+ let currentClause = clauses[0];
129
+ let inElse = false;
130
+ let depth = 1;
131
+
78
132
  let i = start + 1;
79
133
  if (i < lines.length && lines[i].trim() === 'then') i++;
80
134
 
81
- const thenLines = [], elseLines = [];
82
- let inElse = false, inElif = false;
83
- let depth = 1;
84
-
85
135
  while (i < lines.length) {
86
136
  const line = lines[i].trim();
87
137
 
88
- if (line.startsWith('if ')) depth++;
138
+ if (line.startsWith('if ') || line === 'if') depth++;
89
139
 
90
140
  if (line === 'fi') {
91
141
  depth--;
92
- if (depth === 0) {
93
- if (inElif) elseLines.push('fi');
94
- i++; break;
95
- }
142
+ if (depth === 0) { i++; break; }
96
143
  }
97
144
 
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
- }
145
+ if (depth === 1 && line.startsWith('elif ')) {
146
+ const newClause = { condition: parseCondition(line), bodyLines: [] };
147
+ clauses.push(newClause);
148
+ currentClause = newClause;
149
+ i++;
150
+ if (i < lines.length && lines[i].trim() === 'then') i++;
151
+ continue;
152
+ }
153
+
154
+ if (depth === 1 && line === 'else') {
155
+ inElse = true;
107
156
  i++; continue;
108
157
  }
109
158
 
110
159
  if (inElse) elseLines.push(lines[i]);
111
- else thenLines.push(lines[i]);
160
+ else currentClause.bodyLines.push(lines[i]);
112
161
  i++;
113
162
  }
114
163
 
115
- return { node: { type: 'if', condition, thenLines, elseLines }, consumed: i - start };
164
+ return { node: { type: 'if', clauses, elseLines }, consumed: i - start };
116
165
  }
117
166
 
118
167
  _parseWhile(lines, start) {
@@ -177,23 +226,71 @@ class ScriptCommand extends LocalCommand {
177
226
  }
178
227
 
179
228
  _executeNode(node) {
229
+ if (node.type === 'function') {
230
+ const funcName = node.name;
231
+ const funcBody = node.bodyLines;
232
+ const self = this;
233
+ const LocalCmdBase = require('./local/LocalCommand');
234
+ const FuncCmd = class extends LocalCmdBase {
235
+ static get name() { return funcName; }
236
+ run() {
237
+ // Set positional parameters ($1, $2, ...) from call arguments
238
+ const saved = this.arguments.map((arg, i) => ({
239
+ key: String(i + 1),
240
+ prev: self.sandbox.context.getVar(String(i + 1))
241
+ }));
242
+ this.arguments.forEach((arg, i) =>
243
+ self.sandbox.context.setVar(String(i + 1), arg));
244
+ const restore = () => saved.forEach(({ key, prev }) =>
245
+ prev ? self.sandbox.context.setVar(key, prev)
246
+ : self.sandbox.context.unsetVar(key));
247
+ return self._executeFunctionBody(funcBody)
248
+ .then(() => { restore(); })
249
+ .catch(e => {
250
+ restore();
251
+ if (e && e.__type === 'return') {
252
+ this.exitCode = e.code;
253
+ return;
254
+ }
255
+ return Promise.reject(e);
256
+ });
257
+ }
258
+ };
259
+ this.sandbox.context.setCommand(FuncCmd);
260
+ return Promise.resolve();
261
+ }
180
262
  if (node.type === 'command') {
263
+ // Intercept 'return [n]' before it reaches the sandbox
264
+ if (/^return(\s+\d+)?\s*$/.test(node.line.trim())) {
265
+ const match = node.line.trim().match(/^return\s+(\d+)/);
266
+ const code = match ? parseInt(match[1], 10) : 0;
267
+ return Promise.reject({ __type: 'return', code });
268
+ }
181
269
  return this.sandbox.onCommand(node.line, false);
182
270
  }
183
271
  if (node.type === 'if') return this._executeIf(node);
184
272
  if (node.type === 'while') return this._executeWhile(node);
185
273
  if (node.type === 'for') return this._executeFor(node);
274
+ if (node.type === 'case') return this._executeCase(node);
186
275
  return Promise.resolve();
187
276
  }
188
277
 
189
278
  _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));
279
+ const tryClause = (i) => {
280
+ if (i >= node.clauses.length) {
281
+ return node.elseLines.length > 0
282
+ ? this._executeNodes(this._parseLines(node.elseLines))
283
+ : Promise.resolve();
195
284
  }
196
- });
285
+ const clause = node.clauses[i];
286
+ return this.sandbox.onCommand(clause.condition, false).then(() => {
287
+ if (this.sandbox.lastCode === 0) {
288
+ return this._executeNodes(this._parseLines(clause.bodyLines));
289
+ }
290
+ return tryClause(i + 1);
291
+ });
292
+ };
293
+ return tryClause(0);
197
294
  }
198
295
 
199
296
  _executeWhile(node) {
@@ -216,6 +313,150 @@ class ScriptCommand extends LocalCommand {
216
313
  });
217
314
  }, Promise.resolve());
218
315
  }
316
+
317
+ _parseFunction(lines, start) {
318
+ const line = lines[start].trim();
319
+ const nameMatch = line.match(/^function\s+([\w\d_]+)/)
320
+ || line.match(/^([\w\d_]+)\s*\(/);
321
+ const name = nameMatch ? nameMatch[1] : '';
322
+
323
+ let i = start + 1;
324
+ // If opening brace not on the definition line, find it
325
+ if (!line.includes('{')) {
326
+ while (i < lines.length && !lines[i].includes('{')) i++;
327
+ i++; // skip the { line
328
+ }
329
+
330
+ const bodyLines = [];
331
+ let depth = 1;
332
+ while (i < lines.length) {
333
+ const trimmed = lines[i].trim();
334
+ if (trimmed === '}') { i++; break; }
335
+ // Track nested brace depth
336
+ const opens = (lines[i].match(/\{/g) || []).length;
337
+ const closes = (lines[i].match(/\}/g) || []).length;
338
+ depth += opens - closes;
339
+ if (depth <= 0) { i++; break; }
340
+ bodyLines.push(lines[i]);
341
+ i++;
342
+ }
343
+
344
+ return { node: { type: 'function', name, bodyLines }, consumed: i - start };
345
+ }
346
+
347
+ _parseCase(lines, start) {
348
+ const firstLine = lines[start].trim();
349
+ const match = firstLine.match(/^case\s+(.+?)\s+in\s*$/);
350
+ const word = match ? match[1] : '';
351
+
352
+ let i = start + 1;
353
+ const clauses = [];
354
+ let currentPattern = null;
355
+ let currentBody = [];
356
+
357
+ while (i < lines.length) {
358
+ const raw = lines[i];
359
+ const line = raw.trim();
360
+ i++;
361
+
362
+ if (!line || line.startsWith('#')) continue;
363
+ if (line === 'esac') break;
364
+
365
+ if (currentPattern === null) {
366
+ // Pattern line: "pattern) rest" or "pattern)"
367
+ const patMatch = line.match(/^(.+?)\)\s*(.*)$/);
368
+ if (patMatch) {
369
+ currentPattern = patMatch[1].trim();
370
+ const rest = patMatch[2].trim();
371
+ if (rest === ';;') {
372
+ clauses.push({ pattern: currentPattern, bodyLines: [] });
373
+ currentPattern = null;
374
+ } else if (rest.endsWith(';;')) {
375
+ const body = rest.slice(0, -2).trim();
376
+ clauses.push({ pattern: currentPattern, bodyLines: body ? [body] : [] });
377
+ currentPattern = null;
378
+ } else if (rest) {
379
+ currentBody = [rest];
380
+ } else {
381
+ currentBody = [];
382
+ }
383
+ }
384
+ } else if (line === ';;') {
385
+ clauses.push({ pattern: currentPattern, bodyLines: currentBody });
386
+ currentPattern = null;
387
+ currentBody = [];
388
+ } else if (line.endsWith(';;')) {
389
+ currentBody.push(line.slice(0, -2).trim());
390
+ clauses.push({ pattern: currentPattern, bodyLines: currentBody });
391
+ currentPattern = null;
392
+ currentBody = [];
393
+ } else {
394
+ currentBody.push(raw);
395
+ }
396
+ }
397
+
398
+ // Handle an unclosed final clause
399
+ if (currentPattern !== null) {
400
+ clauses.push({ pattern: currentPattern, bodyLines: currentBody });
401
+ }
402
+
403
+ return { node: { type: 'case', word, clauses }, consumed: i - start };
404
+ }
405
+
406
+ _executeFunctionBody(bodyLines) {
407
+ return this._executeNodes(this._parseLines(bodyLines));
408
+ }
409
+
410
+ _executeCase(node) {
411
+ return this.sandbox._replaceVariables(node.word).then(expanded => {
412
+ // Strip outer quotes produced by variable expansion
413
+ const value = ((expanded.startsWith('"') && expanded.endsWith('"'))
414
+ || (expanded.startsWith("'") && expanded.endsWith("'")))
415
+ ? expanded.slice(1, -1) : expanded;
416
+
417
+ for (const clause of node.clauses) {
418
+ if (this._matchPattern(clause.pattern, value)) {
419
+ return this._executeNodes(this._parseLines(clause.bodyLines));
420
+ }
421
+ }
422
+ });
423
+ }
424
+
425
+ _matchPattern(pattern, value) {
426
+ let regexStr = '';
427
+ let i = 0;
428
+ while (i < pattern.length) {
429
+ const ch = pattern[i];
430
+ if (ch === '[') {
431
+ const end = pattern.indexOf(']', i + 1);
432
+ if (end !== -1) {
433
+ regexStr += pattern.slice(i, end + 1);
434
+ i = end + 1;
435
+ } else {
436
+ regexStr += '\\[';
437
+ i++;
438
+ }
439
+ } else if (ch === '*') {
440
+ regexStr += '.*';
441
+ i++;
442
+ } else if (ch === '?') {
443
+ regexStr += '.';
444
+ i++;
445
+ } else if (/[.+^${}()|\\]/.test(ch)) {
446
+ regexStr += '\\' + ch;
447
+ i++;
448
+ } else {
449
+ regexStr += ch;
450
+ i++;
451
+ }
452
+ }
453
+ try {
454
+ return new RegExp('^' + regexStr + '$').test(value);
455
+ } catch (_) {
456
+ return false;
457
+ }
458
+ }
219
459
  }
220
460
 
221
461
  module.exports = ScriptCommand;
462
+ module.exports.isKnownInterpreter = isKnownInterpreter;
@@ -6,6 +6,7 @@ module.exports = [
6
6
  require('./cat'),
7
7
  require('./ls'),
8
8
  require('./echo'),
9
+ require('./printf'),
9
10
  require('./grep'),
10
11
  require('./true'),
11
12
  require('./false'),
@@ -0,0 +1,48 @@
1
+ 'use strict';
2
+
3
+ const Command = require('../Command');
4
+
5
+ class Printf extends Command {
6
+ static get name() { return 'printf'; }
7
+
8
+ run() {
9
+ const args = [...this.arguments];
10
+ if (!args.length) return Promise.resolve();
11
+
12
+ let fmt = args.shift();
13
+
14
+ // Process escape sequences in the format string
15
+ fmt = fmt
16
+ .replace(/\\n/g, '\n')
17
+ .replace(/\\t/g, '\t')
18
+ .replace(/\\r/g, '\r')
19
+ .replace(/\\a/g, '\x07')
20
+ .replace(/\\b/g, '\x08')
21
+ .replace(/\\e/g, '\x1b')
22
+ .replace(/\\f/g, '\x0c')
23
+ .replace(/\\v/g, '\x0b')
24
+ .replace(/\\\\/g, '\\');
25
+
26
+ // Process format specifiers
27
+ let result = '';
28
+ let argIdx = 0;
29
+ for (let i = 0; i < fmt.length; i++) {
30
+ if (fmt[i] === '%' && i + 1 < fmt.length) {
31
+ const spec = fmt[i + 1];
32
+ if (spec === 's') { result += String(args[argIdx++] ?? ''); i++; }
33
+ else if (spec === 'd' || spec === 'i') { result += String(parseInt(args[argIdx++]) || 0); i++; }
34
+ else if (spec === 'f') { result += String(parseFloat(args[argIdx++]) || 0); i++; }
35
+ else if (spec === '%') { result += '%'; i++; }
36
+ else { result += fmt[i]; }
37
+ } else {
38
+ result += fmt[i];
39
+ }
40
+ }
41
+
42
+ // Emit each line directly — no automatic trailing newline (unlike echo)
43
+ result.split(/\r?\n/).forEach(line => this.stdOut = line);
44
+ return Promise.resolve();
45
+ }
46
+ }
47
+
48
+ module.exports = Printf;
package/lib/local/read.js CHANGED
@@ -58,6 +58,16 @@ class Read extends LocalCommand {
58
58
  this.inputBuffer += key;
59
59
  }
60
60
 
61
+ if (key === 'Enter') {
62
+ if (this.var) {
63
+ this.context.setVar(this.var, this.inputBuffer || '');
64
+ this.completionCallback();
65
+ } else {
66
+ this.completionCallback(this.inputBuffer || '');
67
+ }
68
+ return;
69
+ }
70
+
61
71
  if(this.inputBuffer.length === this.nchars) {
62
72
  if(this.var) {
63
73
  this.context.setVar(this.var, this.inputBuffer)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "brsh",
3
- "version": "2.1.5",
3
+ "version": "2.2.1",
4
4
  "description": "A unix like shell written in javascript",
5
5
  "main": "./dist/shell.min.js",
6
6
  "module": "./dist/shell.es.js",