brsh 2.5.5 → 2.6.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/index.js CHANGED
@@ -12,7 +12,7 @@ const localCommands = require('./lib/local');
12
12
  const events = require('events');
13
13
  const BaseFileSystem = require('./lib/BaseFileSystem');
14
14
 
15
- const variableRegex = /\${?([\w\d]+)}?/g;
15
+ const variableRegex = /\$(?:\{([\w\d?#-]+)\}|([\w\d]+|[?#-]))/g;
16
16
 
17
17
 
18
18
  const EventEmitter = events.EventEmitter || events.default || events;
@@ -26,7 +26,20 @@ require('string.prototype.matchall').shim();
26
26
  class Shell extends EventEmitter {
27
27
  constructor(options) {
28
28
  super();
29
- const {path = '/bin', profile, hostname = 'browser', filesystem = {}, permissions = {}, cwd = '/', onFsChange, useRealFilesystem = false} = options;
29
+ const {
30
+ path = '/bin',
31
+ profile,
32
+ motd,
33
+ command,
34
+ interactive = true,
35
+ subshell = false,
36
+ hostname = 'browser',
37
+ filesystem = {},
38
+ permissions = {},
39
+ cwd = '/',
40
+ onFsChange,
41
+ useRealFilesystem = false
42
+ } = options;
30
43
 
31
44
  this.context = new Context(Object.assign({}, options, {
32
45
  clearFn: this.clear.bind(this),
@@ -42,6 +55,12 @@ class Shell extends EventEmitter {
42
55
 
43
56
  this.context.setVar('PATH', path);
44
57
  this.context.setVar('HOST', hostname);
58
+ if (!subshell) {
59
+ const initialFlags = (interactive ? 'i' : '') + (command ? 'c' : '');
60
+ if (initialFlags) {
61
+ this.context.setVar('-', initialFlags);
62
+ }
63
+ }
45
64
  if (useRealFilesystem) {
46
65
  this.context.setNodeFilesystem(cwd);
47
66
  } else {
@@ -54,11 +73,18 @@ class Shell extends EventEmitter {
54
73
  this._loadBuiltinCommands(pathDirExisted);
55
74
 
56
75
  this._lastCode = 0;
57
-
58
- if(profile) {
59
- this._loadProfile(profile);
76
+ this._subshell = subshell;
77
+ this._useRealFilesystem = useRealFilesystem;
78
+ this._profile = profile;
79
+ this._motd = motd;
80
+ this._initialCommand = command || null;
81
+ this._suppressMotd = Boolean(command);
82
+
83
+ if (!subshell) {
84
+ this._initializing = true;
85
+ setTimeout(() => this._init(), 0);
60
86
  } else {
61
- setTimeout(() => this.emit('status', Shell.STATUS_READY), 0);
87
+ this._initializing = false;
62
88
  }
63
89
  }
64
90
 
@@ -67,7 +93,7 @@ class Shell extends EventEmitter {
67
93
  }
68
94
 
69
95
  set lastCode(code) {
70
- this.context.setVar('?', code);
96
+ this.context.setVar('?', String(code));
71
97
  this._lastCode = code;
72
98
  }
73
99
 
@@ -114,8 +140,117 @@ class Shell extends EventEmitter {
114
140
  }
115
141
  }
116
142
 
117
- _loadProfile(profile) {
118
- this.onCommand(`source ${profile}`);
143
+ suppressMotd() {
144
+ this._suppressMotd = true;
145
+ const flags = this.context.getVar('-');
146
+ if (!flags.includes('c')) {
147
+ this.context.setVar('-', flags + 'c');
148
+ }
149
+ }
150
+
151
+ async _init() {
152
+ try {
153
+ if (!this._suppressMotd && !this._initialCommand) {
154
+ await this._runMotd();
155
+ }
156
+ await this._loadProfile(this._profile);
157
+ if (this._initialCommand) {
158
+ await this.onCommand(this._initialCommand, false);
159
+ const flags = this.context.getVar('-');
160
+ if (flags.includes('c')) {
161
+ this.context.setVar('-', flags.replace(/c/g, ''));
162
+ }
163
+ }
164
+ } finally {
165
+ this._initializing = false;
166
+ if (!this.destroyed) {
167
+ this.emit('status', Shell.STATUS_READY);
168
+ }
169
+ }
170
+ }
171
+
172
+ _hasHushlogin() {
173
+ if (this.context.fs.exists('.hushlogin')) return true;
174
+ const home = this.context.getVar('HOME');
175
+ if (home && this.context.fs.exists(`${home.replace(/\/$/, '')}/.hushlogin`)) return true;
176
+ return false;
177
+ }
178
+
179
+ async _runMotd() {
180
+ if (this._motd === false || this._hasHushlogin()) return;
181
+ if (typeof this._motd === 'string') {
182
+ await this._renderMotdPath(this._motd);
183
+ return;
184
+ }
185
+ if (!this._useRealFilesystem) {
186
+ if (this.context.fs.exists('/etc/update-motd.d')) {
187
+ await this._runMotdDir('/etc/update-motd.d');
188
+ }
189
+ if (this.context.fs.exists('/etc/motd')) {
190
+ await this._renderMotdPath('/etc/motd');
191
+ }
192
+ }
193
+ }
194
+
195
+ async _runMotdDir(dirPath) {
196
+ const dir = this.context.fs.getFileByPath(dirPath);
197
+ if (!dir || dir.constructor !== Object) return;
198
+ const entries = Object.keys(dir).sort();
199
+ const cleanDir = dirPath.endsWith('/') ? dirPath.slice(0, -1) : dirPath;
200
+ for (const name of entries) {
201
+ const fullPath = `${cleanDir}/${name}`;
202
+ const stat = this.context.fs.stat(fullPath);
203
+ if (!stat || stat.isDirectory) continue;
204
+ if (this.context.fs.isExecutable(fullPath)) {
205
+ await this.onCommand(fullPath, false);
206
+ }
207
+ }
208
+ }
209
+
210
+ async _renderMotdPath(motdPath) {
211
+ if (!this.context.fs.exists(motdPath)) return;
212
+ const stat = this.context.fs.stat(motdPath);
213
+ if (!stat) return;
214
+ if (stat.isDirectory) {
215
+ await this._runMotdDir(motdPath);
216
+ return;
217
+ }
218
+ const content = this.context.fs.getFileByPath(motdPath);
219
+ if (content === null || content === undefined) return;
220
+
221
+ if (typeof content === 'function') {
222
+ if (this.context.fs.isExecutable(motdPath)) {
223
+ await this.onCommand(motdPath, false);
224
+ }
225
+ return;
226
+ }
227
+
228
+ if (typeof content === 'string' && content.startsWith('#!')) {
229
+ if (this.context.fs.isExecutable(motdPath)) {
230
+ await this.onCommand(motdPath, false);
231
+ } else {
232
+ await this.onCommand(`source ${motdPath}`, false);
233
+ }
234
+ return;
235
+ }
236
+
237
+ let text = content.toString();
238
+ if (text.endsWith('\n')) text = text.slice(0, -1);
239
+ text.split(/\r?\n/).forEach(line => {
240
+ this.emit('stdOut', line);
241
+ });
242
+ }
243
+
244
+ async _loadProfile(profile) {
245
+ if (!this._useRealFilesystem && profile !== '/etc/profile' && this.context.fs.exists('/etc/profile')) {
246
+ const etcProfile = this.context.fs.getFileByPath('/etc/profile');
247
+ if (typeof etcProfile === 'string' && etcProfile.startsWith('#!')) {
248
+ await this.onCommand('source /etc/profile', false);
249
+ }
250
+ }
251
+ if (profile) {
252
+ await this.onCommand(`source ${profile}`, false);
253
+ }
119
254
  }
120
255
 
121
256
  onCommand(raw, events = true) {
@@ -160,7 +295,9 @@ class Shell extends EventEmitter {
160
295
  return;
161
296
  }
162
297
 
163
- this.emit('status', Shell.STATUS_WORKING);
298
+ if (!this._initializing) {
299
+ this.emit('status', Shell.STATUS_WORKING);
300
+ }
164
301
 
165
302
  let args;
166
303
  try {
@@ -456,7 +593,8 @@ class Shell extends EventEmitter {
456
593
  const matches = part.matchAll(variableRegex);
457
594
  let match = matches.next();
458
595
  while (!match.done) {
459
- const value = this.context.getVar(match.value[1]);
596
+ const varName = match.value[1] || match.value[2];
597
+ const value = this.context.getVar(varName);
460
598
  part = part.replace(new RegExp(Shell._escapeRegExp(match.value[0]), 'g'), String(value));
461
599
  match = matches.next();
462
600
  }
@@ -483,7 +621,8 @@ class Shell extends EventEmitter {
483
621
  const subshell = new global.shell({
484
622
  cwd: this.context.fs.cwd,
485
623
  filesystem: this.context.fs.getRaw(),
486
- permissions: this.context.fs.getRawPermissions()
624
+ permissions: this.context.fs.getRawPermissions(),
625
+ subshell: true
487
626
  });
488
627
  subshell.context.source(this.context);
489
628
 
@@ -532,7 +671,8 @@ class Shell extends EventEmitter {
532
671
  const subshell = new global.shell({
533
672
  cwd: this.context.fs.cwd,
534
673
  filesystem: this.context.fs.getRaw(),
535
- permissions: this.context.fs.getRawPermissions()
674
+ permissions: this.context.fs.getRawPermissions(),
675
+ subshell: true
536
676
  });
537
677
  subshell.context.source(this.context);
538
678
  if (stdin !== undefined) subshell.stdin = stdin;
@@ -38,7 +38,8 @@ class ScriptCommand extends LocalCommand {
38
38
  : { filesystem: this.context.fs.getRaw(), permissions: this.context.fs.getRawPermissions() };
39
39
  this.sandbox = new global.shell({
40
40
  cwd: this.context.fs.cwd,
41
- ...fsOpts
41
+ ...fsOpts,
42
+ subshell: true
42
43
  });
43
44
  this.sandbox.context.source(this.context);
44
45
 
package/lib/Terminal.js CHANGED
@@ -17,7 +17,8 @@ class Terminal {
17
17
  animateSpeed = 1,
18
18
  onExit = null,
19
19
  mobileInput = 'click',
20
- lineWrap = false
20
+ lineWrap = false,
21
+ command = null
21
22
  } = options;
22
23
 
23
24
  if(!el) {
@@ -41,8 +42,9 @@ class Terminal {
41
42
  this._outputAnimation = outputAnimation;
42
43
  this._animateSpeed = animateSpeed;
43
44
  this._lineWrap = lineWrap;
44
- this._working = false;
45
- this.cli = new Shell(options);
45
+ this._working = true;
46
+ this._pendingCommands = [];
47
+ this.cli = new Shell(Object.assign({}, options, { command: undefined }));
46
48
  this._buffer = [];
47
49
  this._cursorPos = 0;
48
50
  this._history = [];
@@ -63,6 +65,10 @@ class Terminal {
63
65
  this._setupDom(this._el, font);
64
66
  this._attachShellListeners();
65
67
 
68
+ if (command) {
69
+ this.onCommand(command);
70
+ }
71
+
66
72
  if(mobileInput === 'click') {
67
73
  this._mobileInput();
68
74
  }
@@ -82,7 +88,11 @@ class Terminal {
82
88
 
83
89
  onCommand(command) {
84
90
  if(!this._currentLine) {
85
- return setTimeout(this.onCommand.bind(this, command), 10);
91
+ if (this.cli) {
92
+ this.cli.suppressMotd();
93
+ }
94
+ this._pendingCommands.push(command);
95
+ return;
86
96
  }
87
97
 
88
98
  const onUpdate = this._setCurrentLine.bind(this);
@@ -311,6 +321,16 @@ class Terminal {
311
321
  return requestAnimationFrame(this._statusCheck.bind(this, status));
312
322
  }
313
323
  this._newPrompt(this._setCurrentLine.bind(this, this._buffer));
324
+ if (this._pendingCommands && this._pendingCommands.length > 0) {
325
+ const nextCmd = this._pendingCommands.shift();
326
+ if (this._pendingCommands.length === 0 && this.cli) {
327
+ const flags = this.cli.context.getVar('-');
328
+ if (flags.includes('c')) {
329
+ this.cli.context.setVar('-', flags.replace(/c/g, ''));
330
+ }
331
+ }
332
+ this.onCommand(nextCmd);
333
+ }
314
334
  } else {
315
335
  this._clearCursor();
316
336
  this._working = true;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "brsh",
3
- "version": "2.5.5",
3
+ "version": "2.6.0",
4
4
  "description": "A unix like shell written in javascript",
5
5
  "main": "./dist/shell.min.js",
6
6
  "module": "./dist/shell.es.js",
@@ -335,3 +335,223 @@ describe('. (dot) command', () => {
335
335
  expect(shell.context.getVar('GREETED')).toBe('yes');
336
336
  });
337
337
  });
338
+
339
+ describe('MOTD, profile, and initial command startup chain', () => {
340
+ function bootShell(options) {
341
+ return new Promise((resolve) => {
342
+ const output = [];
343
+ const errors = [];
344
+ const shell = new Shell({ filesystem: {}, ...options });
345
+ shell.on('stdOut', (line) => output.push(line));
346
+ shell.on('stdErr', (line) => errors.push(line));
347
+ shell.once('status', (status) => {
348
+ resolve({ shell, output, errors, status });
349
+ });
350
+ });
351
+ }
352
+
353
+ it('prints static /etc/motd before sourcing profile', async () => {
354
+ const { output, shell } = await bootShell({
355
+ profile: '/home/.profile',
356
+ cwd: '/home',
357
+ filesystem: {
358
+ etc: {
359
+ motd: 'Welcome to the system!\nSecond MOTD line\n'
360
+ },
361
+ home: {
362
+ '.profile': '#!/bin/brsh\nexport PROFILE_LOADED=1\necho "profile ran"'
363
+ }
364
+ }
365
+ });
366
+
367
+ expect(output).toEqual([
368
+ 'Welcome to the system!',
369
+ 'Second MOTD line',
370
+ 'profile ran'
371
+ ]);
372
+ expect(shell.context.getVar('PROFILE_LOADED')).toBe('1');
373
+ });
374
+
375
+ it('runs executable scripts in /etc/update-motd.d in lexical order before /etc/motd and profile', async () => {
376
+ const { output } = await bootShell({
377
+ profile: '/home/.profile',
378
+ cwd: '/home',
379
+ filesystem: {
380
+ etc: {
381
+ 'update-motd.d': {
382
+ '20-second': '#!/bin/brsh\necho "motd-20"',
383
+ '10-first': '#!/bin/brsh\necho "motd-10"',
384
+ '30-disabled': '#!/bin/brsh\necho "motd-disabled"'
385
+ },
386
+ motd: 'static-motd'
387
+ },
388
+ home: {
389
+ '.profile': '#!/bin/brsh\necho "profile-last"'
390
+ }
391
+ },
392
+ permissions: {
393
+ '/etc/update-motd.d/10-first': 0o755,
394
+ '/etc/update-motd.d/20-second': 0o755,
395
+ '/etc/update-motd.d/30-disabled': 0o644
396
+ }
397
+ });
398
+
399
+ expect(output).toEqual([
400
+ 'motd-10',
401
+ 'motd-20',
402
+ 'static-motd',
403
+ 'profile-last'
404
+ ]);
405
+ });
406
+
407
+ it('supports a script file at /etc/motd or custom motd option', async () => {
408
+ const { output } = await bootShell({
409
+ motd: '/home/.motd',
410
+ cwd: '/home',
411
+ filesystem: {
412
+ home: {
413
+ '.motd': '#!/bin/brsh\necho "dynamic motd banner"'
414
+ }
415
+ }
416
+ });
417
+
418
+ expect(output).toEqual(['dynamic motd banner']);
419
+ });
420
+
421
+ it('suppresses MOTD when .hushlogin exists in cwd', async () => {
422
+ const { output, shell } = await bootShell({
423
+ profile: '/home/.profile',
424
+ cwd: '/home',
425
+ filesystem: {
426
+ etc: {
427
+ motd: 'Should not be shown'
428
+ },
429
+ home: {
430
+ '.hushlogin': '',
431
+ '.profile': '#!/bin/brsh\nexport HUSHED=yes'
432
+ }
433
+ }
434
+ });
435
+
436
+ expect(output).toEqual([]);
437
+ expect(shell.context.getVar('HUSHED')).toBe('yes');
438
+ });
439
+
440
+ it('suppresses MOTD when motd: false is set', async () => {
441
+ const { output } = await bootShell({
442
+ motd: false,
443
+ filesystem: {
444
+ etc: {
445
+ motd: 'Should not be shown'
446
+ }
447
+ }
448
+ });
449
+
450
+ expect(output).toEqual([]);
451
+ });
452
+
453
+ it('sources /etc/profile before user profile', async () => {
454
+ const { output } = await bootShell({
455
+ profile: '/home/.profile',
456
+ cwd: '/home',
457
+ filesystem: {
458
+ etc: {
459
+ profile: '#!/bin/brsh\nexport ORDER="etc"'
460
+ },
461
+ home: {
462
+ '.profile': '#!/bin/brsh\nexport ORDER="${ORDER}->user"\necho $ORDER'
463
+ }
464
+ }
465
+ });
466
+
467
+ expect(output).toEqual(['etc->user']);
468
+ });
469
+
470
+ it('skips MOTD when an initial command is provided, but still sources profile so aliases work', async () => {
471
+ const { output, shell } = await bootShell({
472
+ profile: '/home/.profile',
473
+ command: 'cv',
474
+ cwd: '/home',
475
+ filesystem: {
476
+ etc: {
477
+ 'update-motd.d': {
478
+ '00-info': '#!/bin/brsh\necho "MOTD INFO BANNER"'
479
+ },
480
+ motd: 'STATIC MOTD BANNER'
481
+ },
482
+ home: {
483
+ '.profile': '#!/bin/brsh\nalias cv="echo rendering-cv"'
484
+ }
485
+ },
486
+ permissions: {
487
+ '/etc/update-motd.d/00-info': 0o755
488
+ }
489
+ });
490
+
491
+ expect(output).toEqual(['rendering-cv']);
492
+ expect(output).not.toContain('MOTD INFO BANNER');
493
+ expect(output).not.toContain('STATIC MOTD BANNER');
494
+ expect(shell.context.getVar('-')).toBe('i');
495
+ });
496
+
497
+ it('skips MOTD when suppressMotd() is called synchronously before init (like Terminal.onCommand)', async () => {
498
+ const output = [];
499
+ const shell = new Shell({
500
+ profile: '/home/.profile',
501
+ cwd: '/home',
502
+ filesystem: {
503
+ etc: {
504
+ motd: 'STATIC MOTD BANNER'
505
+ },
506
+ home: {
507
+ '.profile': '#!/bin/brsh\nalias cv="echo rendering-cv"'
508
+ }
509
+ }
510
+ });
511
+ shell.suppressMotd();
512
+ shell.on('stdOut', (line) => output.push(line));
513
+
514
+ await new Promise((resolve) => shell.once('status', resolve));
515
+ await shell.onCommand('cv');
516
+
517
+ expect(output).toEqual(['rendering-cv']);
518
+ });
519
+
520
+ it('sets c in $- during profile execution when an initial command is run', async () => {
521
+ const { output } = await bootShell({
522
+ profile: '/home/.profile',
523
+ command: 'echo "ran command"',
524
+ cwd: '/home',
525
+ filesystem: {
526
+ home: {
527
+ '.profile': '#!/bin/brsh\ncase "$-" in\n *c*) echo "non-motd mode" ;;\n *) echo "motd mode" ;;\nesac'
528
+ }
529
+ }
530
+ });
531
+
532
+ expect(output).toEqual(['non-motd mode', 'ran command']);
533
+ });
534
+
535
+ it('does not re-run MOTD in subshells (pipes, command substitution, scripts)', async () => {
536
+ const { shell, output } = await bootShell({
537
+ cwd: '/home',
538
+ filesystem: {
539
+ etc: {
540
+ motd: 'WELCOME_MOTD'
541
+ },
542
+ home: {
543
+ 'script.sh': '#!/bin/brsh\necho $(echo sub) | cat'
544
+ }
545
+ },
546
+ permissions: {
547
+ '/home/script.sh': 0o755
548
+ }
549
+ });
550
+
551
+ expect(output).toEqual(['WELCOME_MOTD']);
552
+
553
+ const res = await run(shell, '/home/script.sh');
554
+ expect(res.output).toEqual(['sub']);
555
+ });
556
+ });
557
+