brsh 3.10.5 → 3.10.7

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
@@ -19,7 +19,6 @@ const BaseFileSystem = require('./lib/BaseFileSystem');
19
19
  const BinaryContainer = require('./lib/BinaryContainer');
20
20
  const { isAsyncFilesystemSource, resolveFilesystemSource } = BinaryContainer;
21
21
 
22
- const variableRegex = /\$(?:\{([\w\d?#@*-]+)\}|([\w\d]+|[?#@*-]))/g;
23
22
 
24
23
 
25
24
  const EventEmitter = events.EventEmitter || events.default || events;
@@ -30,6 +29,9 @@ String.prototype.regexIndexOf = function(regex, startpos) {
30
29
  };
31
30
  require('string.prototype.matchall').shim();
32
31
 
32
+ //stands in for a $ that must not expand (single quoted or backslash escaped) until expansion is done
33
+ const LITERAL_DOLLAR = '\u0000';
34
+
33
35
  class Shell extends EventEmitter {
34
36
  constructor(options) {
35
37
  super();
@@ -1305,6 +1307,15 @@ class Shell extends EventEmitter {
1305
1307
 
1306
1308
  while (i < input.length) {
1307
1309
  const ch = input[i];
1310
+ //operators and quotes inside $(...) / ${...} belong to the group, not to us
1311
+ if (!sq && ch === '$' && (input[i + 1] === '(' || input[i + 1] === '{')) {
1312
+ const end = Shell._skipGroup(input, i);
1313
+ if (end > -1) {
1314
+ current += input.slice(i, end);
1315
+ i = end;
1316
+ continue;
1317
+ }
1318
+ }
1308
1319
  if (ch === "'" && !dq) { sq = !sq; current += ch; i++; continue; }
1309
1320
  if (ch === '"' && !sq) { dq = !dq; current += ch; i++; continue; }
1310
1321
  if (!sq && !dq) {
@@ -1443,7 +1454,7 @@ class Shell extends EventEmitter {
1443
1454
  continue;
1444
1455
  }
1445
1456
 
1446
- const expanded = await this._replaceVariables(rawValue);
1457
+ const expanded = (await this._replaceVariables(rawValue)).replaceAll(LITERAL_DOLLAR, '$');
1447
1458
 
1448
1459
  // Variable / alias assignments (VAR=val, export VAR=val, alias foo=bar)
1449
1460
  // and explicitly quoted tokens do not undergo IFS field splitting.
@@ -1478,31 +1489,107 @@ class Shell extends EventEmitter {
1478
1489
  return array.filter(item => item.length > 0);
1479
1490
  }
1480
1491
 
1492
+ //single left to right pass so substituted output is never re-expanded
1481
1493
  async _replaceVariables(part) {
1482
- // 1. Arithmetic substitution $(( expr ))
1483
- const arithMatches = [...part.matchAll(/\$\(\(([^)]+)\)\)/g)];
1484
- for (const m of arithMatches) {
1485
- part = part.replace(m[0], String(this._evalArithmetic(m[1])));
1494
+ let out = '';
1495
+ for(let i = 0; i < part.length; i++) {
1496
+ if(part[i] !== '$') {
1497
+ out += part[i];
1498
+ continue;
1499
+ }
1500
+
1501
+ if(part[i + 1] === '(' || part[i + 1] === '{') {
1502
+ const end = Shell._skipGroup(part, i);
1503
+ if(end > -1) {
1504
+ out += await this._expandGroup(part.slice(i, end));
1505
+ i = end -1;
1506
+ continue;
1507
+ }
1508
+ }
1509
+
1510
+ const m = /^\$(?:([\w]+)|([?#@*-]))/.exec(part.slice(i, i + 256));
1511
+ if(m) {
1512
+ out += String(this.context.getVar(m[1] || m[2]));
1513
+ i += m[0].length -1;
1514
+ continue;
1515
+ }
1516
+ out += '$';
1517
+ }
1518
+ return out;
1519
+ }
1520
+
1521
+ //text is a whole $(( )), $( ) or ${ } group
1522
+ async _expandGroup(text) {
1523
+ if(text.startsWith('$((') && text.endsWith('))')) {
1524
+ return String(this._evalArithmetic(text.slice(3, -2)));
1525
+ }
1526
+ if(text.startsWith('$(')) {
1527
+ return this._runAndCapture(text.slice(2, -1));
1528
+ }
1529
+
1530
+ const body = text.slice(2, -1);
1531
+ const length = /^#(\w+)$/.exec(body);
1532
+ if(length) {
1533
+ return String(this.context.getVar(length[1]).length);
1486
1534
  }
1487
1535
 
1488
- // 2. Command substitution $( cmd ) — negative lookahead excludes $((
1489
- const cmdMatches = [...part.matchAll(/\$\((?!\()([^)]+)\)/g)];
1490
- for (const m of cmdMatches) {
1491
- const output = await this._runAndCapture(m[1]);
1492
- part = part.replace(m[0], output);
1536
+ //context cant tell unset from empty, so the colon and non colon forms behave the same
1537
+ const m = /^(\w+|[?#@*-])(?::?([-=?+])([\s\S]*))?$/.exec(body);
1538
+ if(!m) {
1539
+ return text;
1493
1540
  }
1494
1541
 
1495
- // 3. Variable substitution $VAR and ${VAR}
1496
- const matches = part.matchAll(variableRegex);
1497
- let match = matches.next();
1498
- while (!match.done) {
1499
- const varName = match.value[1] || match.value[2];
1500
- const value = this.context.getVar(varName);
1501
- part = part.replace(new RegExp(Shell._escapeRegExp(match.value[0]), 'g'), String(value));
1502
- match = matches.next();
1542
+ const [, name, op, word = ''] = m;
1543
+ const value = String(this.context.getVar(name));
1544
+ const expandWord = () => this._replaceVariables(Shell._sanitiseCommandPart(word));
1545
+ if(!op) {
1546
+ return value;
1547
+ }
1548
+ if(op === '+') {
1549
+ return value !== '' ? expandWord() : '';
1550
+ }
1551
+ if(value !== '') {
1552
+ return value;
1553
+ }
1554
+ if(op === '-') {
1555
+ return expandWord();
1556
+ }
1557
+ if(op === '=') {
1558
+ const assigned = await expandWord();
1559
+ this.context.setVar(name, assigned);
1560
+ return assigned;
1503
1561
  }
1562
+ throw new Error(`${name}: ${word || 'parameter null or not set'}`);
1563
+ }
1504
1564
 
1505
- return part;
1565
+ //returns the index after the group opened by the $( or ${ at start, or -1 if never closed.
1566
+ //quotes and nested groups are respected so a ) or } inside them doesnt end it early
1567
+ static _skipGroup(str, start) {
1568
+ const stack = [];
1569
+ for(let i = start; i < str.length; i++) {
1570
+ const ch = str[i];
1571
+ const top = stack[stack.length -1];
1572
+ if(top === "'") {
1573
+ ch === "'" && stack.pop();
1574
+ } else if(ch === '\\') {
1575
+ i++;
1576
+ } else if(ch === '"') {
1577
+ top === '"' ? stack.pop() : stack.push('"');
1578
+ } else if(ch === "'" && top !== '"') {
1579
+ stack.push("'");
1580
+ } else if(ch === '$' && (str[i + 1] === '{' || str[i + 1] === '(')) {
1581
+ stack.push(str[i + 1] === '{' ? '}' : ')');
1582
+ i++;
1583
+ } else if(ch === '(' && top !== '"') {
1584
+ stack.push(')');
1585
+ } else if(ch === top) {
1586
+ stack.pop();
1587
+ if(stack.length < 1) {
1588
+ return i + 1;
1589
+ }
1590
+ }
1591
+ }
1592
+ return -1;
1506
1593
  }
1507
1594
 
1508
1595
  _evalArithmetic(expr) {
@@ -1616,7 +1703,6 @@ class Shell extends EventEmitter {
1616
1703
  const separator = /\s/g;
1617
1704
  let singleQuoteOpen = false;
1618
1705
  let doubleQuoteOpen = false;
1619
- let dollarDepth = 0;
1620
1706
  let tokenBuffer = [];
1621
1707
  let tokenHasQuote = false;
1622
1708
  const parts = [];
@@ -1624,19 +1710,21 @@ class Shell extends EventEmitter {
1624
1710
  for (let i = 0; i < string.length; i++) {
1625
1711
  const ch = string[i];
1626
1712
 
1627
- // Inside $(...) or $((...)) — keep everything verbatim, track nesting
1628
- if (dollarDepth > 0) {
1629
- tokenBuffer.push(ch);
1630
- if (ch === '(') dollarDepth++;
1631
- else if (ch === ')') dollarDepth--;
1632
- continue;
1713
+ //$(...), $((...)) and ${...} are kept verbatim, whatever quotes or spaces are inside
1714
+ if (!singleQuoteOpen && ch === '$' && (string[i + 1] === '(' || string[i + 1] === '{')) {
1715
+ const end = Shell._skipGroup(string, i);
1716
+ if (end > -1) {
1717
+ tokenBuffer.push(string.slice(i, end));
1718
+ i = end -1;
1719
+ continue;
1720
+ }
1633
1721
  }
1634
1722
 
1635
1723
  // Escape handling inside double quotes
1636
1724
  if (doubleQuoteOpen && ch === '\\' && i + 1 < string.length) {
1637
1725
  const next = string[i + 1];
1638
1726
  if (next === '"' || next === '\\' || next === '$') {
1639
- tokenBuffer.push(next);
1727
+ tokenBuffer.push(next === '$' ? LITERAL_DOLLAR : next);
1640
1728
  i++;
1641
1729
  continue;
1642
1730
  }
@@ -1645,7 +1733,7 @@ class Shell extends EventEmitter {
1645
1733
  // Escape handling outside quotes
1646
1734
  if (!singleQuoteOpen && !doubleQuoteOpen && ch === '\\' && i + 1 < string.length) {
1647
1735
  const next = string[++i];
1648
- tokenBuffer.push(next);
1736
+ tokenBuffer.push(next === '$' ? LITERAL_DOLLAR : next);
1649
1737
  if (next === '"' || next === "'") {
1650
1738
  tokenHasQuote = true;
1651
1739
  }
@@ -1665,15 +1753,6 @@ class Shell extends EventEmitter {
1665
1753
  }
1666
1754
 
1667
1755
  if (!singleQuoteOpen && !doubleQuoteOpen) {
1668
- // Start of $( or $(( substitution — consume the opening '(' too
1669
- if (ch === '$' && i + 1 < string.length && string[i + 1] === '(') {
1670
- dollarDepth = 1;
1671
- tokenBuffer.push('$');
1672
- tokenBuffer.push('(');
1673
- i++;
1674
- continue;
1675
- }
1676
-
1677
1756
  // Whitespace splits tokens
1678
1757
  if (ch.match(separator)) {
1679
1758
  if (tokenBuffer.length > 0 || tokenHasQuote) {
@@ -1685,7 +1764,7 @@ class Shell extends EventEmitter {
1685
1764
  }
1686
1765
  }
1687
1766
 
1688
- tokenBuffer.push(ch);
1767
+ tokenBuffer.push(ch === '$' && singleQuoteOpen ? LITERAL_DOLLAR : ch);
1689
1768
  }
1690
1769
 
1691
1770
  if (tokenBuffer.length > 0 || tokenHasQuote) {
@@ -8,6 +8,8 @@ module.exports = [
8
8
  require('./echo'),
9
9
  require('./printf'),
10
10
  require('./grep'),
11
+ require('./sed'),
12
+ require('./tail'),
11
13
  require('./true'),
12
14
  require('./false'),
13
15
  Test,
@@ -0,0 +1,37 @@
1
+ 'use strict';
2
+
3
+ //reads a file (or stdin for '-' / no path) for a builtin, reports errors on the command itself.
4
+ //returns the text, or null if it couldnt be read
5
+ function readInput(cmd, path, label) {
6
+ if(path === undefined || path === '-') {
7
+ if(typeof cmd.stdin !== 'string') {
8
+ cmd.stdErr = `${label}: no input`;
9
+ cmd.exitCode = 1;
10
+ return null;
11
+ }
12
+ return cmd.stdin;
13
+ }
14
+
15
+ const file = cmd.fs.getFileByPath(path);
16
+ if(file === null || file === undefined) {
17
+ cmd.stdErr = `${label}: ${path}: ${cmd.fs.exists(path) ? 'Permission denied' : 'No such file or directory'}`;
18
+ cmd.exitCode = 1;
19
+ return null;
20
+ }
21
+ if(file.constructor === Object) {
22
+ cmd.stdErr = `${label}: ${path}: Is a directory`;
23
+ cmd.exitCode = 1;
24
+ return null;
25
+ }
26
+ return file.toString();
27
+ }
28
+
29
+ //a trailing newline terminates the last line rather than starting a new one
30
+ function toLines(text) {
31
+ if(text === '') {
32
+ return [];
33
+ }
34
+ return (text.endsWith('\n') ? text.slice(0, -1) : text).split('\n');
35
+ }
36
+
37
+ module.exports = {readInput, toLines};
@@ -0,0 +1,361 @@
1
+ 'use strict';
2
+
3
+ const Command = require('../Command');
4
+ const {readInput, toLines} = require('./readInput');
5
+
6
+ const posixClasses = {
7
+ alpha: 'a-zA-Z',
8
+ digit: '0-9',
9
+ alnum: 'a-zA-Z0-9',
10
+ upper: 'A-Z',
11
+ lower: 'a-z',
12
+ space: '\\s',
13
+ blank: ' \\t',
14
+ punct: '!-\\/:-@\\[-`{-~',
15
+ xdigit: '0-9A-Fa-f'
16
+ };
17
+
18
+ //turn a posix BRE (or ERE when ere is set) into a js regex source
19
+ function convertRegex(src, ere) {
20
+ let out = '';
21
+ for(let i = 0; i < src.length; i++) {
22
+ const ch = src[i];
23
+ if(ch === '[') {
24
+ //copy the bracket expression, js needs backslashes escaped and has no [:class:]
25
+ let j = i + 1;
26
+ let set = '[';
27
+ if(src[j] === '^') {
28
+ set += '^';
29
+ j++;
30
+ }
31
+ if(src[j] === ']') {
32
+ set += '\\]';
33
+ j++;
34
+ }
35
+ for(; j < src.length && src[j] !== ']'; j++) {
36
+ const cls = /^\[:(\w+):\]/.exec(src.slice(j));
37
+ if(cls && posixClasses[cls[1]]) {
38
+ set += posixClasses[cls[1]];
39
+ j += cls[0].length -1;
40
+ } else {
41
+ set += src[j] === '\\' ? '\\\\' : src[j];
42
+ }
43
+ }
44
+ if(j >= src.length) {
45
+ throw new Error('unterminated address regex');
46
+ }
47
+ out += `${set}]`;
48
+ i = j;
49
+ } else if(ch === '\\' && i + 1 < src.length) {
50
+ const next = src[++i];
51
+ //in a BRE these escapes are the special operators
52
+ out += !ere && '(){}+?|'.includes(next) ? next : `\\${next}`;
53
+ } else if(!ere && '(){}+?|'.includes(ch)) {
54
+ out += `\\${ch}`;
55
+ } else if(!ere && ch === '*' && (out === '' || out.endsWith('('))) {
56
+ out += '\\*';
57
+ } else {
58
+ out += ch;
59
+ }
60
+ }
61
+ return out;
62
+ }
63
+
64
+ //reads up to an unescaped delimiter, returns [text, indexAfterDelimiter]
65
+ function readUntil(script, i, delim) {
66
+ let text = '';
67
+ for(; i < script.length; i++) {
68
+ if(script[i] === '\\' && i + 1 < script.length) {
69
+ //an escaped delimiter is just the delimiter, anything else is kept for later
70
+ text += script[i + 1] === delim ? delim : `\\${script[i + 1]}`;
71
+ i++;
72
+ } else if(script[i] === delim) {
73
+ return [text, i + 1];
74
+ } else {
75
+ text += script[i];
76
+ }
77
+ }
78
+ throw new Error('unterminated command');
79
+ }
80
+
81
+ function parseReplacement(text) {
82
+ const parts = [];
83
+ let lit = '';
84
+ for(let i = 0; i < text.length; i++) {
85
+ if(text[i] === '\\' && i + 1 < text.length) {
86
+ const next = text[++i];
87
+ if(/\d/.test(next)) {
88
+ lit && parts.push(lit);
89
+ lit = '';
90
+ parts.push(parseInt(next, 10));
91
+ } else {
92
+ lit += next === 'n' ? '\n' : next === 't' ? '\t' : next;
93
+ }
94
+ } else if(text[i] === '&') {
95
+ lit && parts.push(lit);
96
+ lit = '';
97
+ parts.push(0);
98
+ } else {
99
+ lit += text[i];
100
+ }
101
+ }
102
+ lit && parts.push(lit);
103
+ return parts;
104
+ }
105
+
106
+ class Sed extends Command {
107
+ static get name() { return 'sed'; }
108
+
109
+ get requiresFilesystem() {
110
+ return true;
111
+ }
112
+
113
+ run() {
114
+ let quiet = false;
115
+ let ere = false;
116
+ const scripts = [];
117
+ const paths = [];
118
+
119
+ const args = this.arguments;
120
+ for(let i = 0; i < args.length; i++) {
121
+ const arg = args[i];
122
+ if(arg === '--') {
123
+ paths.push(...args.slice(i + 1));
124
+ break;
125
+ }
126
+ if(arg.length < 2 || !arg.startsWith('-')) {
127
+ paths.push(arg);
128
+ continue;
129
+ }
130
+ for(let j = 1; j < arg.length; j++) {
131
+ const flag = arg[j];
132
+ if(flag === 'n') {
133
+ quiet = true;
134
+ } else if(flag === 'E' || flag === 'r') {
135
+ ere = true;
136
+ } else if(flag === 'e') {
137
+ //script is the rest of this arg, or the next one
138
+ scripts.push(j + 1 < arg.length ? arg.slice(j + 1) : args[++i]);
139
+ break;
140
+ } else {
141
+ return this._fail(`invalid option -- ${flag}`);
142
+ }
143
+ }
144
+ }
145
+
146
+ //without -e the first operand is the script
147
+ scripts.length < 1 && paths.length > 0 && scripts.push(paths.shift());
148
+ if(scripts.length < 1 || scripts.some(s => s === undefined)) {
149
+ return this._fail('usage: sed [-nEr] [-e script] script [file ...]');
150
+ }
151
+
152
+ let cmds;
153
+ try {
154
+ this.lastRe = null;
155
+ cmds = this._parse(scripts.join('\n'), ere);
156
+ } catch(e) {
157
+ return this._fail(e.message);
158
+ }
159
+
160
+ const texts = (paths.length > 0 ? paths : [undefined]).map(p => readInput(this, p, 'sed'));
161
+ //an unreadable file already reported itself, carry on with the rest like sed does
162
+ const lines = texts.filter(t => t !== null).flatMap(toLines);
163
+
164
+ this._execute(cmds, lines, quiet);
165
+ return Promise.resolve();
166
+ }
167
+
168
+ _fail(message) {
169
+ this.stdErr = message.startsWith('usage') ? message : `sed: ${message}`;
170
+ this.exitCode = 1;
171
+ return Promise.resolve();
172
+ }
173
+
174
+ _regex(src, ere, flags) {
175
+ //an empty regex means the last one used
176
+ if(src === '') {
177
+ if(!this.lastRe) {
178
+ throw new Error('no previous regular expression');
179
+ }
180
+ return new RegExp(this.lastRe.source, flags);
181
+ }
182
+ const re = new RegExp(convertRegex(src, ere), flags);
183
+ this.lastRe = re;
184
+ return re;
185
+ }
186
+
187
+ _parse(script, ere) {
188
+ const cmds = [];
189
+ let i = 0;
190
+
191
+ const skip = chars => {
192
+ while(i < script.length && chars.includes(script[i])) {
193
+ i++;
194
+ }
195
+ };
196
+ const address = () => {
197
+ if(/\d/.test(script[i] || '')) {
198
+ const start = i;
199
+ skip('0123456789');
200
+ return {type: 'line', n: parseInt(script.slice(start, i), 10)};
201
+ }
202
+ if(script[i] === '$') {
203
+ i++;
204
+ return {type: 'last'};
205
+ }
206
+ if(script[i] === '/') {
207
+ const [src, next] = readUntil(script, i + 1, '/');
208
+ i = next;
209
+ return {type: 're', re: this._regex(src, ere, '')};
210
+ }
211
+ };
212
+
213
+ for(skip(' \t\n;'); i < script.length; skip(' \t\n;')) {
214
+ const cmd = {};
215
+ cmd.a1 = address();
216
+ if(cmd.a1 && script[i] === ',') {
217
+ i++;
218
+ cmd.a2 = address();
219
+ if(!cmd.a2) {
220
+ throw new Error('unexpected `,\'');
221
+ }
222
+ }
223
+ skip(' \t');
224
+ if(script[i] === '!') {
225
+ cmd.negate = true;
226
+ i++;
227
+ skip(' \t');
228
+ }
229
+
230
+ cmd.name = script[i++];
231
+ if(cmd.name === 's') {
232
+ const delim = script[i++];
233
+ if(!delim || delim === '\n' || delim === '\\') {
234
+ throw new Error('unterminated `s\' command');
235
+ }
236
+ const [pattern, afterPattern] = readUntil(script, i, delim);
237
+ const [replacement, afterReplacement] = readUntil(script, afterPattern, delim);
238
+ i = afterReplacement;
239
+
240
+ cmd.global = false;
241
+ cmd.print = false;
242
+ cmd.nth = 1;
243
+ let flags = 'g';
244
+ for(; i < script.length && /[gpiI\d]/.test(script[i]); i++) {
245
+ const f = script[i];
246
+ if(f === 'g') {
247
+ cmd.global = true;
248
+ } else if(f === 'p') {
249
+ cmd.print = true;
250
+ } else if(f === 'i' || f === 'I') {
251
+ flags += 'i';
252
+ } else {
253
+ cmd.nth = parseInt(f, 10) || 1;
254
+ }
255
+ }
256
+ cmd.re = this._regex(pattern, ere, flags);
257
+ cmd.replacement = parseReplacement(replacement);
258
+ } else if(cmd.name === 'y') {
259
+ const delim = script[i++];
260
+ const [from, afterFrom] = readUntil(script, i, delim);
261
+ const [to, afterTo] = readUntil(script, afterFrom, delim);
262
+ i = afterTo;
263
+ if(from.length !== to.length) {
264
+ throw new Error('strings for `y\' command are different lengths');
265
+ }
266
+ cmd.map = Object.fromEntries([...from].map((c, idx) => [c, to[idx]]));
267
+ } else if(!'dpq='.includes(cmd.name || '?')) {
268
+ throw new Error(`unknown command: \`${cmd.name || ''}'`);
269
+ }
270
+
271
+ skip(' \t');
272
+ if(i < script.length && !';\n'.includes(script[i])) {
273
+ throw new Error('extra characters after command');
274
+ }
275
+ cmds.push(cmd);
276
+ }
277
+ return cmds;
278
+ }
279
+
280
+ _matches(a, ln, line, last) {
281
+ return a.type === 'line' ? ln === a.n
282
+ : a.type === 'last' ? ln === last
283
+ : a.re.test(line);
284
+ }
285
+
286
+ _selected(cmd, ln, line, last) {
287
+ if(!cmd.a1) {
288
+ return true;
289
+ }
290
+ if(!cmd.a2) {
291
+ return this._matches(cmd.a1, ln, line, last);
292
+ }
293
+ if(cmd.active) {
294
+ const ends = cmd.a2.type === 'line' ? ln >= cmd.a2.n : this._matches(cmd.a2, ln, line, last);
295
+ ends && delete cmd.active;
296
+ return true;
297
+ }
298
+ if(!this._matches(cmd.a1, ln, line, last)) {
299
+ return false;
300
+ }
301
+ //a regex end address is only checked from the next line, a line number may already be behind us
302
+ if(!(cmd.a2.type === 'line' && cmd.a2.n <= ln)) {
303
+ cmd.active = true;
304
+ }
305
+ return true;
306
+ }
307
+
308
+ _substitute(cmd, line) {
309
+ let count = 0;
310
+ let replaced = false;
311
+ const out = line.replace(cmd.re, (...m) => {
312
+ count++;
313
+ if(count < cmd.nth || (!cmd.global && count > cmd.nth)) {
314
+ return m[0];
315
+ }
316
+ replaced = true;
317
+ const groups = m.slice(0, -2);
318
+ return cmd.replacement.map(p => typeof p === 'number' ? (groups[p] || '') : p).join('');
319
+ });
320
+ return {out, replaced};
321
+ }
322
+
323
+ _execute(cmds, lines, quiet) {
324
+ for(let idx = 0; idx < lines.length; idx++) {
325
+ const ln = idx + 1;
326
+ let line = lines[idx];
327
+ let deleted = false;
328
+ let quit = false;
329
+
330
+ for(const cmd of cmds) {
331
+ if(this._selected(cmd, ln, line, lines.length) === !!cmd.negate) {
332
+ continue;
333
+ }
334
+ if(cmd.name === 's') {
335
+ const {out, replaced} = this._substitute(cmd, line);
336
+ line = out;
337
+ replaced && cmd.print && (this.stdOut = line);
338
+ } else if(cmd.name === 'y') {
339
+ line = [...line].map(c => cmd.map[c] ?? c).join('');
340
+ } else if(cmd.name === 'p') {
341
+ this.stdOut = line;
342
+ } else if(cmd.name === '=') {
343
+ this.stdOut = String(ln);
344
+ } else if(cmd.name === 'd') {
345
+ deleted = true;
346
+ break;
347
+ } else if(cmd.name === 'q') {
348
+ quit = true;
349
+ break;
350
+ }
351
+ }
352
+
353
+ !quiet && !deleted && (this.stdOut = line);
354
+ if(quit) {
355
+ return;
356
+ }
357
+ }
358
+ }
359
+ }
360
+
361
+ module.exports = Sed;