fauxnix-cli 1.0.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.
@@ -1,6 +1,7 @@
1
1
  import { wordToString } from '../ast.js';
2
2
  import { lookup, parseWords, psStr } from '../registry.js';
3
3
  import { argListExpr, exprOfWord, operandExpr } from '../translator.js';
4
+ import { PS_WRITE_FN, fxTermLine } from './text-output.js';
4
5
  /* ------------------------------------------------------------------ */
5
6
  /* Shared PS snippets (same shape as files.ts / text-filters.ts) */
6
7
  /* ------------------------------------------------------------------ */
@@ -66,35 +67,6 @@ const PS_UNESQ_FN = [
66
67
  ' $sb.ToString()',
67
68
  '}',
68
69
  ].join('\n');
69
- /**
70
- * Terminal-aware write. When this block's output goes straight to the console
71
- * (a lone `& { }` scriptblock — $MyInvocation name is empty — or the last
72
- * stage of a pipeline):
73
- * - a string ending in \n is emitted as line items (the console formatter
74
- * appends the final newline; still correct inside $(...) substitution);
75
- * - a string without a trailing newline is written with the exact bytes so
76
- * `echo -n`, `printf 'x'`, `base64 -w0`, `head -c N` stay GNU-exact.
77
- * Inside a pipeline stage emit one string item instead (line semantics
78
- * downstream; embedded \n is preserved for consumers that re-split).
79
- */
80
- const PS_WRITE_FN = [
81
- 'function fx-write($s, $term) {',
82
- " if ($s -eq '') { return }",
83
- // Inside quoted/assignment $(...) the collector wants one string object
84
- // so interior newlines survive (PS would otherwise join lines with spaces).
85
- ' if ($script:fx_csub) { $s; return }',
86
- ' if (-not $term) { $s; return }',
87
- ' if (-not $s.EndsWith([string][char]10)) { [Console]::Out.Write($s); return }',
88
- ' $t = $s.Substring(0, $s.Length - 1)',
89
- ' foreach ($fx_l in $t.Split([char]10)) { $fx_l }',
90
- '}',
91
- ].join('\n');
92
- /** $fx_term: is this block's output console-terminal? (see PS_WRITE_FN) */
93
- function fxTermLine(position) {
94
- return ("$fx_term = (($MyInvocation.MyCommand.Name -eq '') -or " +
95
- (position === 'last' ? '$true' : '$false') +
96
- ')');
97
- }
98
70
  /** PS boolean literal. */
99
71
  function pb(v) {
100
72
  return v ? '$true' : '$false';
@@ -175,12 +147,12 @@ const echo = (args, ctx) => {
175
147
  else if (t === '-E')
176
148
  esc = false;
177
149
  else if (/^-[neE]{2,}$/.test(t)) {
178
- if (t.includes('n'))
179
- noNewline = true;
180
- if (t.includes('e'))
181
- esc = true;
182
- if (t.includes('E'))
183
- esc = false;
150
+ for (const flag of t.slice(1)) {
151
+ if (flag === 'n')
152
+ noNewline = true;
153
+ else
154
+ esc = flag === 'e';
155
+ }
184
156
  }
185
157
  else
186
158
  break;
@@ -331,12 +303,7 @@ const PS_PRINTF_FNS = [
331
303
  ].join('\n');
332
304
  const printf = (args, ctx) => {
333
305
  // no options; skip a single leading `--` separator
334
- const ops = [];
335
- for (const w of args) {
336
- if (ops.length === 0 && wordToString(w) === '--')
337
- continue;
338
- ops.push(w);
339
- }
306
+ const ops = args.length > 0 && wordToString(args[0]) === '--' ? args.slice(1) : args;
340
307
  if (ops.length === 0) {
341
308
  return psErrExpr(psStr('printf: usage: printf format [arguments]'), '2');
342
309
  }
@@ -346,6 +313,9 @@ const printf = (args, ctx) => {
346
313
  fxTermLine(ctx.position),
347
314
  '$fx_fmt = ' + exprOfWord(ops[0]),
348
315
  '$fx_av = ' + psArray(ops.slice(1), exprOfWord),
316
+ // A substitution can fail while producing an argument. printf's status
317
+ // belongs to printf itself; later formatting/write exceptions still fail.
318
+ '$script:fx_exit = 0',
349
319
  'fx-write (fx-printf $fx_fmt $fx_av) $fx_term',
350
320
  ].join('\n');
351
321
  };
@@ -400,9 +370,27 @@ const head = (args, ctx) => {
400
370
  // option scan (legacy `head -N` supported; -n/-c take values, incl. negative)
401
371
  let nLines = null;
402
372
  let nBytes = null;
373
+ let dropLast = false;
403
374
  const operandWords = [];
404
375
  let quiet = false;
405
376
  let verbose = false;
377
+ const setCount = (kind, raw) => {
378
+ const literal = countMagnitudeLiteral(raw);
379
+ if (literal === null) {
380
+ return psErrExpr(psStr("head: invalid number of " + kind + ": '" + raw + "'"));
381
+ }
382
+ dropLast = raw.startsWith('-');
383
+ const signedLiteral = dropLast && literal !== '0' ? '-' + literal : literal;
384
+ if (kind === 'bytes') {
385
+ nBytes = signedLiteral;
386
+ nLines = null;
387
+ }
388
+ else {
389
+ nLines = signedLiteral;
390
+ nBytes = null;
391
+ }
392
+ return null;
393
+ };
406
394
  {
407
395
  let i = 0;
408
396
  let onlyOps = false;
@@ -434,19 +422,20 @@ const head = (args, ctx) => {
434
422
  else {
435
423
  i++;
436
424
  }
437
- if (name === '--bytes')
438
- nBytes = val;
439
- else
440
- nLines = val;
425
+ const err = setCount(name === '--bytes' ? 'bytes' : 'lines', val);
426
+ if (err !== null)
427
+ return err;
441
428
  continue;
442
429
  }
443
430
  if (name === '--quiet' || name === '--silent') {
444
431
  quiet = true;
432
+ verbose = false;
445
433
  i++;
446
434
  continue;
447
435
  }
448
436
  if (name === '--verbose') {
449
437
  verbose = true;
438
+ quiet = false;
450
439
  i++;
451
440
  continue;
452
441
  }
@@ -454,39 +443,42 @@ const head = (args, ctx) => {
454
443
  continue;
455
444
  }
456
445
  let m;
457
- if (t === '-n' || t === '-c') {
458
- const val = i + 1 < args.length ? wordToString(args[i + 1]) : null;
459
- if (val === null) {
460
- return psErrExpr(psStr('head: option requires an argument -- ' + t.slice(1)));
461
- }
462
- if (t === '-c')
463
- nBytes = val;
464
- else
465
- nLines = val;
466
- i += 2;
467
- continue;
468
- }
469
- if ((m = t.match(/^-[nc](.+)$/)) !== null) {
470
- if (t[1] === 'c')
471
- nBytes = m[1];
472
- else
473
- nLines = m[1];
474
- i++;
475
- continue;
476
- }
477
446
  if ((m = t.match(/^-(\d+)$/)) !== null) {
478
- nLines = m[1];
447
+ const err = setCount('lines', m[1]);
448
+ if (err !== null)
449
+ return err;
479
450
  i++;
480
451
  continue;
481
452
  }
482
453
  if (t.startsWith('-') && t.length > 1) {
483
- for (const ch of t.slice(1)) {
484
- if (ch === 'q')
454
+ const body = t.slice(1);
455
+ let usedNext = false;
456
+ for (let c = 0; c < body.length; c++) {
457
+ const ch = body[c];
458
+ if (ch === 'q') {
485
459
  quiet = true;
486
- else if (ch === 'v')
460
+ verbose = false;
461
+ }
462
+ else if (ch === 'v') {
487
463
  verbose = true;
464
+ quiet = false;
465
+ }
466
+ else if (ch === 'n' || ch === 'c') {
467
+ let val = body.slice(c + 1);
468
+ if (val === '') {
469
+ if (i + 1 >= args.length) {
470
+ return psErrExpr(psStr('head: option requires an argument -- ' + ch));
471
+ }
472
+ val = wordToString(args[i + 1]);
473
+ usedNext = true;
474
+ }
475
+ const err = setCount(ch === 'c' ? 'bytes' : 'lines', val);
476
+ if (err !== null)
477
+ return err;
478
+ break;
479
+ }
488
480
  }
489
- i++;
481
+ i += usedNext ? 2 : 1;
490
482
  continue;
491
483
  }
492
484
  operandWords.push(args[i]);
@@ -495,9 +487,6 @@ const head = (args, ctx) => {
495
487
  }
496
488
  const bytesMode = nBytes !== null;
497
489
  const countLit = bytesMode ? nBytes : nLines !== null ? nLines : '10';
498
- if (!/^[+-]?\d+$/.test(countLit)) {
499
- return psErrExpr(psStr("head: invalid number of " + (bytesMode ? 'bytes' : 'lines') + ": '" + countLit + "'"));
500
- }
501
490
  const lines = [
502
491
  PS_GLOB_FN,
503
492
  PS_READTEXT_FN,
@@ -509,22 +498,22 @@ const head = (args, ctx) => {
509
498
  lines.push(STDIN_ITEMS, PS_STDINRAW_FN);
510
499
  else
511
500
  lines.push(STDIN_INLINES);
512
- lines.push(...psCollectFiles(operandWords, (g) => qErr('head', g, 'No such file or directory'), (g) => qErr('head', g, 'Is a directory', 'error reading ')), '$fx_count = [int](' + countLit + ')', '$fx_hdr = ((($fx_srcs.Count -gt 1) -and ' + pb(!quiet) + ') -or ' + pb(verbose) + ')', '$fx_first = $true');
501
+ lines.push(...psCollectFiles(operandWords, (g) => qErr('head', g, 'No such file or directory'), (g) => qErr('head', g, 'Is a directory', 'error reading ')), '$fx_count = [int](' + countLit + ')', '$fx_dropLast = ' + pb(dropLast), '$fx_hdr = ((($fx_srcs.Count -gt 1) -and ' + pb(!quiet) + ') -or ' + pb(verbose) + ')', '$fx_first = $true');
513
502
  if (bytesMode) {
514
503
  lines.push('$fx_out = New-Object System.Text.StringBuilder', 'for ($fx_k = 0; $fx_k -lt $fx_srcs.Count; $fx_k++) {', ' $fx_g = $fx_srcs[$fx_k]', " if ($fx_g -eq '-') { $fx_txt = (fx-stdinraw $fx_items); $fx_disp = 'standard input' }", ' else { $fx_txt = fx-read $fx_g; $fx_disp = $fx_names[$fx_k] }', ' if ($fx_hdr) {', ' if (-not $fx_first) { [void]$fx_out.Append([string][char]10) }', " [void]$fx_out.Append('==> ' + $fx_disp + ' <==' + [string][char]10)", ' }', ' $fx_first = $false',
515
- // GNU: --bytes=-N prints all but last N; -0 / N≥size → empty
516
- ' if ($fx_count -lt 0) { $fx_len = [math]::Max(0, $fx_txt.Length + $fx_count) }', ' else { $fx_len = [math]::Min($fx_count, $fx_txt.Length) }', ' if ($fx_len -gt 0) { [void]$fx_out.Append($fx_txt.Substring(0, $fx_len)) }', '}', 'fx-write $fx_out.ToString() $fx_term');
504
+ // GNU: --bytes=-N prints all but last N, including the whole input for -0.
505
+ ' if ($fx_count -lt 0) { $fx_len = [math]::Max(0, $fx_txt.Length + $fx_count) }', ' elseif ($fx_dropLast) { $fx_len = $fx_txt.Length }', ' else { $fx_len = [math]::Min($fx_count, $fx_txt.Length) }', ' if ($fx_len -gt 0) { [void]$fx_out.Append($fx_txt.Substring(0, $fx_len)) }', '}', 'fx-write $fx_out.ToString() $fx_term');
517
506
  }
518
507
  else {
519
- lines.push('for ($fx_k = 0; $fx_k -lt $fx_srcs.Count; $fx_k++) {', ' $fx_g = $fx_srcs[$fx_k]', " if ($fx_g -eq '-') { $fx_ls = @($fx_in); $fx_disp = 'standard input' }", ' else { $fx_ls = @(fx-splitlines (fx-read $fx_g)); $fx_disp = $fx_names[$fx_k] }', ' if ($fx_hdr) {', " if (-not $fx_first) { '' }", " '==> ' + $fx_disp + ' <=='", ' }', ' $fx_first = $false', ' $fx_lim = $fx_ls.Count', ' if ($fx_count -lt 0) { $fx_lim = $fx_ls.Count + $fx_count }', ' elseif ($fx_lim -gt $fx_count) { $fx_lim = $fx_count }', ' if ($fx_lim -lt 0) { $fx_lim = 0 }', ' for ($fx_i = 0; $fx_i -lt $fx_lim; $fx_i++) { $fx_ls[$fx_i] }', '}');
508
+ lines.push('for ($fx_k = 0; $fx_k -lt $fx_srcs.Count; $fx_k++) {', ' $fx_g = $fx_srcs[$fx_k]', " if ($fx_g -eq '-') { $fx_ls = @($fx_in); $fx_disp = 'standard input' }", ' else { $fx_ls = @(fx-splitlines (fx-read $fx_g)); $fx_disp = $fx_names[$fx_k] }', ' if ($fx_hdr) {', " if (-not $fx_first) { '' }", " '==> ' + $fx_disp + ' <=='", ' }', ' $fx_first = $false', ' $fx_lim = $fx_ls.Count', ' if ($fx_count -lt 0) { $fx_lim = $fx_ls.Count + $fx_count }', ' elseif ($fx_dropLast) { $fx_lim = $fx_ls.Count }', ' elseif ($fx_lim -gt $fx_count) { $fx_lim = $fx_count }', ' if ($fx_lim -lt 0) { $fx_lim = 0 }', ' for ($fx_i = 0; $fx_i -lt $fx_lim; $fx_i++) { $fx_ls[$fx_i] }', '}');
520
509
  }
521
510
  return lines.join('\n');
522
511
  };
523
512
  /* ------------------------------------------------------------------ */
524
513
  /* tail */
525
514
  /* ------------------------------------------------------------------ */
526
- /** A count embedded in generated PS must be a canonical Int32 literal. */
527
- function tailCountLiteral(raw) {
515
+ /** A count magnitude embedded in generated PS must be a canonical Int32 literal. */
516
+ function countMagnitudeLiteral(raw) {
528
517
  if (!/^[+-]?\d+$/.test(raw))
529
518
  return null;
530
519
  try {
@@ -552,7 +541,7 @@ const tail = (args, ctx) => {
552
541
  let quiet = false;
553
542
  let verbose = false;
554
543
  const setCount = (kind, raw) => {
555
- const literal = tailCountLiteral(raw);
544
+ const literal = countMagnitudeLiteral(raw);
556
545
  if (literal === null) {
557
546
  return psErrExpr(psStr("tail: invalid number of " + kind + ": '" + raw + "'"));
558
547
  }
@@ -614,11 +603,13 @@ const tail = (args, ctx) => {
614
603
  }
615
604
  if (name === '--quiet' || name === '--silent') {
616
605
  quiet = true;
606
+ verbose = false;
617
607
  i++;
618
608
  continue;
619
609
  }
620
610
  if (name === '--verbose') {
621
611
  verbose = true;
612
+ quiet = false;
622
613
  i++;
623
614
  continue;
624
615
  }
@@ -645,10 +636,14 @@ const tail = (args, ctx) => {
645
636
  let usedNext = false;
646
637
  for (let c = 0; c < body.length; c++) {
647
638
  const ch = body[c];
648
- if (ch === 'q')
639
+ if (ch === 'q') {
649
640
  quiet = true;
650
- else if (ch === 'v')
641
+ verbose = false;
642
+ }
643
+ else if (ch === 'v') {
651
644
  verbose = true;
645
+ quiet = false;
646
+ }
652
647
  else if (ch === 'n' || ch === 'c') {
653
648
  let val = body.slice(c + 1);
654
649
  if (val === '') {
@@ -712,12 +707,23 @@ const wc = (args) => {
712
707
  // GNU: stdin (implicit or `-`) prints the classic 7-wide columns; real
713
708
  // file operands use dynamic widths; `-` displays the name '-'.
714
709
  const fromFiles = operandWords.some((w) => wordToString(w) !== '-');
710
+ const charCount = wantM ? '(fx-charcount $fx_txt)' : '$fx_txt.Length';
715
711
  return [
716
712
  PS_GLOB_FN,
717
713
  PS_READTEXT_FN,
718
714
  PS_SPLITLINES_FN,
719
715
  STDIN_ITEMS,
720
716
  PS_STDINRAW_FN,
717
+ ...(wantM ? [
718
+ 'function fx-charcount($t) {',
719
+ ' $n = 0',
720
+ ' for ($i = 0; $i -lt $t.Length; $i++) {',
721
+ ' $n++',
722
+ ' if ([char]::IsHighSurrogate($t[$i]) -and ($i + 1) -lt $t.Length -and [char]::IsLowSurrogate($t[$i + 1])) { $i++ }',
723
+ ' }',
724
+ ' return $n',
725
+ '}',
726
+ ] : []),
721
727
  ...psCollectFiles(operandWords, (g) => sErr('wc', g, 'No such file or directory'), (g) => sErr('wc', g, 'Is a directory')),
722
728
  'function fx-wdcount($ls) {',
723
729
  ' $t = 0',
@@ -740,14 +746,14 @@ const wc = (args) => {
740
746
  " if ($fx_txt -ne '' -and -not $fx_txt.EndsWith([string][char]10)) { $fx_nl = $fx_nl + 1 }",
741
747
  ' $fx_ww = fx-wdcount @(fx-splitlines $fx_txt)',
742
748
  ' $fx_bc = [System.Text.Encoding]::UTF8.GetByteCount($fx_txt)',
743
- " $fx_rows += ,@($fx_nl, $fx_ww, $fx_bc, $fx_txt.Length, $fx_names[$fx_k])",
749
+ ' $fx_rows += ,@($fx_nl, $fx_ww, $fx_bc, ' + charCount + ', $fx_names[$fx_k])',
744
750
  ' } else {',
745
751
  ' $fx_txt = fx-read $fx_g',
746
752
  ' $fx_txt2 = $fx_txt.Replace([string][char]13 + [string][char]10, [string][char]10)',
747
753
  " $fx_nl = [regex]::Matches($fx_txt2, '\\n').Count",
748
754
  ' $fx_bytes = [IO.File]::ReadAllBytes($fx_g).Length',
749
755
  ' $fx_ww = fx-wdcount @(fx-splitlines $fx_txt)',
750
- ' $fx_rows += ,@($fx_nl, $fx_ww, $fx_bytes, $fx_txt.Length, $fx_names[$fx_k])',
756
+ ' $fx_rows += ,@($fx_nl, $fx_ww, $fx_bytes, ' + charCount + ', $fx_names[$fx_k])',
751
757
  ' }',
752
758
  '}',
753
759
  '$fx_tot = @(0, 0, 0, 0)',
@@ -960,12 +966,21 @@ const sha256sum = hashSum('sha256sum', '[System.Security.Cryptography.SHA256]::C
960
966
  /* base64 */
961
967
  /* ------------------------------------------------------------------ */
962
968
  const base64 = (args, ctx) => {
963
- const { flags, longs, values, operandWords } = parseWords(args, ['w'], ['--wrap']);
969
+ const { flags, longs, valueEntries, missingValue, operandWords } = parseWords(args, ['w'], ['--wrap']);
964
970
  const decode = flags.has('d') || longs.has('--decode');
971
+ if (missingValue.length > 0) {
972
+ return psErrExpr(psStr('base64: option requires an argument -- ' + missingValue[0]));
973
+ }
965
974
  let wrap = 76;
966
- const wv = values.get('-w') ?? values.get('--wrap');
967
- if (wv !== undefined && /^\d+$/.test(wv))
968
- wrap = parseInt(wv, 10);
975
+ for (const { name, value } of valueEntries) {
976
+ if (name !== '-w' && name !== '--wrap')
977
+ continue;
978
+ const literal = /^\d+$/.test(value) ? countMagnitudeLiteral(value) : null;
979
+ if (literal === null) {
980
+ return psErrExpr(psStr("base64: invalid wrap size: '" + value + "'"));
981
+ }
982
+ wrap = Number(literal);
983
+ }
969
984
  const pre = [
970
985
  PS_GLOB_FN,
971
986
  PS_READTEXT_FN,
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Terminal-aware write. When this block's output goes straight to the console
3
+ * (a lone `& { }` scriptblock — $MyInvocation name is empty — or the last
4
+ * stage of a pipeline):
5
+ * - a string ending in \n is emitted as line items (the console formatter
6
+ * appends the final newline; still correct inside $(...) substitution);
7
+ * - a string without a trailing newline is written with the exact bytes so
8
+ * `echo -n`, `printf 'x'`, `base64 -w0`, `head -c N` stay GNU-exact.
9
+ * Inside a pipeline stage emit one string item instead (line semantics
10
+ * downstream; embedded \n is preserved for consumers that re-split).
11
+ */
12
+ export declare const PS_WRITE_FN: string;
13
+ /** $fx_term: is this block's output console-terminal? (see PS_WRITE_FN) */
14
+ export declare function fxTermLine(position: 'first' | 'middle' | 'last'): string;
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Terminal-aware write. When this block's output goes straight to the console
3
+ * (a lone `& { }` scriptblock — $MyInvocation name is empty — or the last
4
+ * stage of a pipeline):
5
+ * - a string ending in \n is emitted as line items (the console formatter
6
+ * appends the final newline; still correct inside $(...) substitution);
7
+ * - a string without a trailing newline is written with the exact bytes so
8
+ * `echo -n`, `printf 'x'`, `base64 -w0`, `head -c N` stay GNU-exact.
9
+ * Inside a pipeline stage emit one string item instead (line semantics
10
+ * downstream; embedded \n is preserved for consumers that re-split).
11
+ */
12
+ export const PS_WRITE_FN = [
13
+ 'function fx-write($s, $term) {',
14
+ " if ($s -eq '') { return }",
15
+ // Inside quoted/assignment $(...) the collector wants one string object
16
+ // so interior newlines survive (PS would otherwise join lines with spaces).
17
+ ' if ($script:fx_csub) { $s; return }',
18
+ ' if (-not $term) { $s; return }',
19
+ ' if (-not $s.EndsWith([string][char]10)) { [Console]::Out.Write($s); return }',
20
+ ' $t = $s.Substring(0, $s.Length - 1)',
21
+ ' foreach ($fx_l in $t.Split([char]10)) { $fx_l }',
22
+ '}',
23
+ ].join('\n');
24
+ /** $fx_term: is this block's output console-terminal? (see PS_WRITE_FN) */
25
+ export function fxTermLine(position) {
26
+ return ("$fx_term = (($MyInvocation.MyCommand.Name -eq '') -or " +
27
+ (position === 'last' ? '$true' : '$false') +
28
+ ')');
29
+ }
package/dist/doctor.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { existsSync, readFileSync } from 'node:fs';
2
+ import { nodeEngineRange, supportsNode } from './runtime-support.js';
2
3
  import { homedir } from 'node:os';
3
4
  import { join } from 'node:path';
4
5
  import { resolveQwenLaunchTuple, sameQwenLaunchTuple } from './qwen-launch.js';
@@ -121,14 +122,15 @@ function detectCodex(home, env) {
121
122
  return `found ${path}, fauxnix MCP not listed — run: codex mcp add fauxnix -- fauxnix mcp`;
122
123
  }
123
124
  export function hasCodexFauxnix(text) {
124
- if (/^\s*\[mcp_servers\.(?:fauxnix|"fauxnix"|'fauxnix')\]/im.test(text))
125
- return true;
126
125
  const tables = text.split(/^\s*\[/m);
127
126
  for (const table of tables) {
128
- if (!/^mcp_servers\./i.test(table))
129
- continue;
130
127
  const header = (table.split(/[\]\r\n]/, 1)[0] ?? '').trim();
131
- if (/^mcp_servers\.(?:fauxnix|"fauxnix"|'fauxnix')$/i.test(header))
128
+ // TOML allows quoted key components and whitespace around dots and brackets.
129
+ // Recognize those equivalent spellings before install appends a duplicate table.
130
+ const server = /^(?:mcp_servers|"mcp_servers"|'mcp_servers')\s*\.\s*(.+)$/i.exec(header);
131
+ if (!server)
132
+ continue;
133
+ if (/^(?:fauxnix|"fauxnix"|'fauxnix')$/i.test(server[1]))
132
134
  return true;
133
135
  const cmd = /^\s*command\s*=\s*(?:"([^"]*)"|'([^']*)')/im.exec(table);
134
136
  const command = cmd?.[1] ?? cmd?.[2];
@@ -251,8 +253,7 @@ function isFauxnixExecutable(s) {
251
253
  return /^fauxnix(-cli)?(\.cmd|\.exe)?$/i.test(base);
252
254
  }
253
255
  async function mcpLines(nodeVersion, loadMcp) {
254
- const major = nodeMajor(nodeVersion);
255
- const nodeOk = major >= 18;
256
+ const nodeOk = supportsNode(nodeVersion);
256
257
  let moduleOk = false;
257
258
  let moduleDetail = '';
258
259
  try {
@@ -266,7 +267,7 @@ async function mcpLines(nodeVersion, loadMcp) {
266
267
  moduleDetail = e instanceof Error ? e.message : String(e);
267
268
  }
268
269
  const lines = [
269
- field('node', `${nodeVersion.startsWith('v') ? nodeVersion : 'v' + nodeVersion}${nodeOk ? ' (>=18 required)' : ' FAILED (requires >=18)'}`),
270
+ field('node', `${nodeVersion.startsWith('v') ? nodeVersion : 'v' + nodeVersion}${nodeOk ? ` (${nodeEngineRange} required)` : ` FAILED (requires ${nodeEngineRange})`}`),
270
271
  field('mcp', moduleOk ? 'module loads' : `FAILED to load${moduleDetail ? ': ' + moduleDetail : ''}`),
271
272
  VALUE_INDENT + 'start with: fauxnix mcp',
272
273
  ];
@@ -275,10 +276,6 @@ async function mcpLines(nodeVersion, loadMcp) {
275
276
  async function defaultLoadMcp() {
276
277
  return import('./mcp.js');
277
278
  }
278
- function nodeMajor(version) {
279
- const m = /^v?(\d+)/.exec(version);
280
- return m ? Number(m[1]) : 0;
281
- }
282
279
  function stripBom(text) {
283
280
  return text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
284
281
  }
@@ -25,3 +25,8 @@ export declare function decodeOutput(buf: Buffer, prefer?: NativeEncodingPref):
25
25
  export declare function normalizeHostNewlines(s: string): string;
26
26
  /** Encode a PowerShell script for -EncodedCommand (UTF-16LE base64). */
27
27
  export declare function encodeCommand(script: string): string;
28
+ /** Keep the longest whole-codepoint prefix within a caller's UTF-8 byte budget. */
29
+ export declare function clipUtf8(text: string, limit: number): {
30
+ text: string;
31
+ truncated: boolean;
32
+ };
package/dist/encoding.js CHANGED
@@ -56,3 +56,43 @@ export function normalizeHostNewlines(s) {
56
56
  export function encodeCommand(script) {
57
57
  return Buffer.from(script, 'utf16le').toString('base64');
58
58
  }
59
+ /** Keep the longest whole-codepoint prefix within a caller's UTF-8 byte budget. */
60
+ export function clipUtf8(text, limit) {
61
+ const total = Buffer.byteLength(text, 'utf8');
62
+ if (total <= limit)
63
+ return { text, truncated: false };
64
+ // Captures normally exceed the caller budget by at most one codepoint.
65
+ // Trim that small suffix rather than walking megabytes of retained output.
66
+ // For a small budget, use the forward path instead; neither path allocates
67
+ // another full UTF-8 buffer or splits a surrogate pair.
68
+ if (total - limit <= limit) {
69
+ let used = total;
70
+ let end = text.length;
71
+ while (used > limit && end > 0) {
72
+ const last = text.charCodeAt(end - 1);
73
+ const previous = end > 1 ? text.charCodeAt(end - 2) : 0;
74
+ if (last >= 0xdc00 && last <= 0xdfff && previous >= 0xd800 && previous <= 0xdbff) {
75
+ used -= 4;
76
+ end -= 2;
77
+ }
78
+ else {
79
+ // Lone surrogates encode as a three-byte replacement character,
80
+ // but retain their original JS spelling just as the forward path does.
81
+ used -= last < 0x80 ? 1 : last < 0x800 ? 2 : 3;
82
+ end--;
83
+ }
84
+ }
85
+ return { text: text.slice(0, end), truncated: true };
86
+ }
87
+ let used = 0;
88
+ let end = 0;
89
+ for (const codepoint of text) {
90
+ const value = codepoint.codePointAt(0);
91
+ const size = value < 0x80 ? 1 : value < 0x800 ? 2 : value < 0x10000 ? 3 : 4;
92
+ if (used + size > limit)
93
+ break;
94
+ used += size;
95
+ end += codepoint.length;
96
+ }
97
+ return { text: text.slice(0, end), truncated: true };
98
+ }
package/dist/executor.js CHANGED
@@ -3,7 +3,7 @@ import { promises as fs, readFileSync, existsSync, openSync, closeSync, readSync
3
3
  import os from 'node:os';
4
4
  import path from 'node:path';
5
5
  import { normalizeLiteralPath, wrapScript } from './translator.js';
6
- import { decodeOutput, resolveNativePref } from './encoding.js';
6
+ import { clipUtf8, decodeOutput, resolveNativePref } from './encoding.js';
7
7
  import { normalizeStderr } from './errors.js';
8
8
  import { DEFAULT_STDERR_LIMIT, DEFAULT_STDOUT_LIMIT, PowerShellHost, } from './ps-host.js';
9
9
  import { resolvePowerShell } from './powershell.js';
@@ -727,20 +727,6 @@ async function runPlans(plans, session, opts, afterSegment, ensureHost) {
727
727
  spawnError,
728
728
  };
729
729
  }
730
- function clipUtf8(text, limit) {
731
- if (Buffer.byteLength(text, 'utf8') <= limit)
732
- return { text, truncated: false };
733
- let used = 0;
734
- let end = 0;
735
- for (const codepoint of text) {
736
- const size = Buffer.byteLength(codepoint, 'utf8');
737
- if (used + size > limit)
738
- break;
739
- used += size;
740
- end += codepoint.length;
741
- }
742
- return { text: text.slice(0, end), truncated: true };
743
- }
744
730
  /** Copy a host spool into an already-open redirect fd with bounded memory. */
745
731
  function writeSpoolToPrepFd(fds, file, target) {
746
732
  const outFd = fds.get(target);
package/dist/facade.js CHANGED
@@ -29,12 +29,20 @@ function bashQuote(word) {
29
29
  return "'" + word.replaceAll("'", `'\\''`) + "'";
30
30
  }
31
31
  async function runOneShot(session, script, positionals) {
32
+ // bash -c '' is a successful no-op, distinct from a missing operand.
33
+ if (script === '')
34
+ return 0;
32
35
  // bash: trailing operands set $0, then $1.. via `set --`.
33
- process.env['FAUXNIX_ARG0'] = positionals[0] ?? 'bash';
36
+ session.env['FAUXNIX_ARG0'] = positionals[0] ?? 'bash';
34
37
  if (positionals.length > 1) {
35
38
  const r = await runScript(session, 'set -- ' + positionals.slice(1).map(bashQuote).join(' '));
36
- if (r.exitCode !== 0)
39
+ if (r.exitCode !== 0) {
40
+ if (r.stdout)
41
+ process.stdout.write(r.stdout);
42
+ if (r.stderr)
43
+ process.stderr.write(r.stderr);
37
44
  return r.exitCode;
45
+ }
38
46
  }
39
47
  const r = await runScript(session, script);
40
48
  if (r.stdout)
@@ -66,7 +74,8 @@ async function runMarkerSession(session) {
66
74
  process.stdout.write(`<bash-exit>${r.exitCode}</bash-exit>\n`);
67
75
  }
68
76
  catch (err) {
69
- process.stderr.write(`fauxnix: facade: ${err.message}\n`);
77
+ const msg = err instanceof Error ? err.message : String(err);
78
+ process.stderr.write(`fauxnix: facade: ${msg}\n`);
70
79
  process.stdout.write('<bash-exit>127</bash-exit>\n');
71
80
  }
72
81
  });
@@ -86,7 +95,7 @@ export async function runFacade(argv) {
86
95
  }
87
96
  if (argv[0] === '-c' || argv[0] === '-e') {
88
97
  const [script, ...positionals] = argv.slice(1);
89
- if (!script) {
98
+ if (script === undefined) {
90
99
  process.stderr.write('bash: -c: option requires an argument\n');
91
100
  return 2;
92
101
  }
@@ -96,7 +105,7 @@ export async function runFacade(argv) {
96
105
  }
97
106
  catch (err) {
98
107
  // bash -c exits 2 on syntax errors; 127 covers the not-found family
99
- const msg = err.message ?? String(err);
108
+ const msg = err instanceof Error ? err.message : String(err);
100
109
  process.stderr.write('bash: -c: ' + msg + '\n');
101
110
  return msg.includes('not found') ? 127 : 2;
102
111
  }
package/dist/index.js CHANGED
@@ -1,6 +1,12 @@
1
1
  #!/usr/bin/env node
2
- import { runCli } from './cli.js';
3
- runCli(process.argv.slice(2)).catch((e) => {
4
- console.error(e instanceof Error ? e.message : String(e));
5
- process.exit(1);
6
- });
2
+ import { nodeEngineRange, supportsNode } from './runtime-support.js';
3
+ if (!supportsNode(process.version)) {
4
+ console.error(`fauxnix: Node.js ${nodeEngineRange} is required; found ${process.version}`);
5
+ process.exitCode = 1;
6
+ }
7
+ else {
8
+ await import('./cli.js').then(({ runCli }) => runCli(process.argv.slice(2))).catch((e) => {
9
+ console.error(e instanceof Error ? e.message : String(e));
10
+ process.exitCode = 1;
11
+ });
12
+ }
package/dist/mcp.d.ts CHANGED
@@ -32,7 +32,7 @@ export declare function batchToolResult(inputs: BatchStepInput[], batch: BatchEx
32
32
  id?: string | undefined;
33
33
  index: number;
34
34
  } | {
35
- status: "cancelled" | "completed" | "timed_out" | "failed" | "infrastructure_error";
35
+ status: "cancelled" | "timed_out" | "completed" | "failed" | "infrastructure_error";
36
36
  stdout: string;
37
37
  stderr: string;
38
38
  exitCode: number;