fauxnix-cli 2.1.0 → 2.2.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,4 +1,4 @@
1
- globalThis.__FAUXNIX_VERSION__="2.1.0";globalThis.__FAUXNIX_ENGINES_NODE__=">=22.20.0";
1
+ globalThis.__FAUXNIX_VERSION__="2.2.0";globalThis.__FAUXNIX_ENGINES_NODE__=">=22.20.0";
2
2
  "use strict";
3
3
  var __create = Object.create;
4
4
  var __defProp = Object.defineProperty;
@@ -3967,7 +3967,12 @@ function tokenize(input) {
3967
3967
  else matched = fdDigits + ">";
3968
3968
  }
3969
3969
  advance = matched.length - fdDigits.length;
3970
+ if (matched === "1>") matched = ">";
3971
+ else if (matched === "1>>") matched = ">>";
3970
3972
  fdDigits = "";
3973
+ } else if (matched === ">" && input.startsWith("&2", i + 1) && !/[^\s;|&<>()]/.test(input[i + 3] ?? " ")) {
3974
+ matched = "1>&2";
3975
+ advance = 3;
3971
3976
  }
3972
3977
  if (matched === "<<") {
3973
3978
  throw new FauxnixParseError(
@@ -4890,6 +4895,9 @@ function parseCommand(input) {
4890
4895
  next();
4891
4896
  continue;
4892
4897
  }
4898
+ if (t.type === "OP" && /^\d+[<>]/.test(t.op) && !isRedirectOp(t.op)) {
4899
+ normalizeRedirect(t.op);
4900
+ }
4893
4901
  if (t.type === "OP" && isRedirectOp(t.op)) {
4894
4902
  const op = t.op;
4895
4903
  next();
@@ -5376,7 +5384,7 @@ function varExpr(name, index, param, length = false, extra) {
5376
5384
  }
5377
5385
  switch (name) {
5378
5386
  case "HOME":
5379
- return "$HOME";
5387
+ return "(fx-scalar0 'HOME')";
5380
5388
  case "PWD":
5381
5389
  return "fx-posix([string]$PWD.Path)";
5382
5390
  case "USER":
@@ -5539,6 +5547,41 @@ function operandExpr(w) {
5539
5547
  if (lit !== null) return pathExpr(normalizeLiteralPath(lit));
5540
5548
  return exprOfWord(w);
5541
5549
  }
5550
+ function wcEscapeLiteral(s) {
5551
+ return s.replace(/[*?[]/g, "`$&");
5552
+ }
5553
+ function globOperandExpr(w) {
5554
+ const lit = literalOfWord(w);
5555
+ if (lit !== null && !/[*?[]/.test(lit)) return pathExpr(normalizeLiteralPath(lit));
5556
+ const chunks = [];
5557
+ const mergeable = (s) => typeof s === "string" && s.startsWith("'") && s.endsWith("'") && s.length >= 2;
5558
+ const pushChunk = (s) => {
5559
+ const prev = chunks.length ? chunks[chunks.length - 1] : void 0;
5560
+ if (mergeable(prev) && mergeable(s)) {
5561
+ chunks[chunks.length - 1] = "'" + prev.slice(1, -1) + s.slice(1, -1) + "'";
5562
+ return;
5563
+ }
5564
+ chunks.push(s);
5565
+ };
5566
+ const walk = (parts, quoted) => {
5567
+ for (const p of parts) {
5568
+ if (p.kind === "DoubleQuoted") {
5569
+ walk(p.parts, true);
5570
+ continue;
5571
+ }
5572
+ if (p.kind === "Text" || p.kind === "SingleQuoted") {
5573
+ const literal = quoted || p.kind === "SingleQuoted" || p.kind === "Text" && p.escaped === true;
5574
+ pushChunk(psStr(literal ? wcEscapeLiteral(p.text) : p.text));
5575
+ continue;
5576
+ }
5577
+ const expr = exprOfWord([p]);
5578
+ chunks.push(quoted ? "[WildcardPattern]::Escape([string](" + expr + "))" : "([string](" + expr + "))");
5579
+ }
5580
+ };
5581
+ walk(w, false);
5582
+ if (chunks.length === 1) return chunks[0];
5583
+ return "(" + chunks.join(" + ") + ")";
5584
+ }
5542
5585
  function wordPartsForSplat(w) {
5543
5586
  const out = [];
5544
5587
  const walk = (parts, quoted) => {
@@ -6404,7 +6447,9 @@ function wrapScript(body, opts = {}) {
6404
6447
  " if ($fx_eq -lt 1) { continue }",
6405
6448
  " if ($fx_pair.Substring(0, $fx_eq) -ceq $n) { return (fx-svdec $fx_pair.Substring($fx_eq + 1)) }",
6406
6449
  " }",
6407
- " if ($n -ceq 'HOME') { return [string]$HOME }",
6450
+ // Inherited HOME (Git Bash hosts) first; bare-Windows fallback is the
6451
+ // profile, like a bash login shell seeding HOME from passwd (#255).
6452
+ " if ($n -ceq 'HOME') { return $(if ($env:HOME) { [string]$env:HOME } else { [string]$HOME }) }",
6408
6453
  " if ($n -ceq 'PWD') { return fx-posix([string]$PWD.Path) }",
6409
6454
  " if ($n -ceq 'USER' -or $n -ceq 'LOGNAME') { return [string]$env:USERNAME }",
6410
6455
  " if ($n -ceq 'PATH') { return [string]$env:PATH }",
@@ -6930,6 +6975,14 @@ function fx-capture-bytes($stream) {
6930
6975
  if ($stream -is [System.IO.MemoryStream]) { return $stream.ToArray() }
6931
6976
  return (New-Object byte[] 0)
6932
6977
  }
6978
+ # Captured at startup, from the script's own location (never from the
6979
+ # user-mutable environment).
6980
+ $fx_sd = $null
6981
+ if ($PSCommandPath) {
6982
+ $fx_sd = [IO.Path]::GetDirectoryName($PSCommandPath)
6983
+ if ([IO.Path]::GetFileName($fx_sd) -cnotmatch '^fauxnix-[0-9]+-[0-9a-f]{24}$') { $fx_sd = $null }
6984
+ }
6985
+ Set-Variable -Name fx_hostStateDir -Value $fx_sd -Option Constant
6933
6986
  while ($true) {
6934
6987
  $fx_line = $fx_reader.ReadLine()
6935
6988
  if ($null -eq $fx_line) { break }
@@ -7042,6 +7095,9 @@ while ($true) {
7042
7095
  $fx_proto.WriteLine($fx_json)
7043
7096
  }
7044
7097
  }
7098
+ # stdin EOF: the owner is gone or disposed us. Remove our private state
7099
+ # directory (#256) - only if it is a genuine per-session directory.
7100
+ if ($fx_hostStateDir) { Remove-Item -LiteralPath $fx_hostStateDir -Recurse -Force -ErrorAction SilentlyContinue }
7045
7101
  `.trim();
7046
7102
 
7047
7103
  // src/commands/text-output.ts
@@ -7146,9 +7202,12 @@ var PS_GLOB_FN = [
7146
7202
  "function fx-glob($p) {",
7147
7203
  " if ($p -notlike '*[*?]*') { return @($p) }",
7148
7204
  " $m = @(Get-Item -Path $p -ErrorAction SilentlyContinue)",
7149
- " if ($m.Count -eq 0) { return @($p) }",
7205
+ " if ($m.Count -eq 0) { return @(fx-wclit $p) }",
7150
7206
  " return @($m | ForEach-Object { $_.FullName })",
7151
- "}"
7207
+ "}",
7208
+ // Unescape wildcard-escaped literals (#255): quoted glob characters that
7209
+ // matched nothing keep their shell spelling as the literal operand.
7210
+ "function fx-wclit($p) { return ($p -replace '`(?=[*?[])', '') }"
7152
7211
  ].join("\n");
7153
7212
  var PS_READTEXT_FN = [
7154
7213
  "function fx-read($p) {",
@@ -7190,7 +7249,7 @@ var ls = (args) => {
7190
7249
  const sortByTime = flags.has("t");
7191
7250
  const sortBySize = flags.has("S");
7192
7251
  const reverse = flags.has("r");
7193
- const targets = operandWords.length ? argListExpr(operandWords) : "@('.')";
7252
+ const targets = operandWords.length ? argListExpr(operandWords, globOperandExpr) : "@('.')";
7194
7253
  return [
7195
7254
  PS_GLOB_FN,
7196
7255
  PS_FTIME_FN,
@@ -7268,7 +7327,7 @@ var cp = (args) => {
7268
7327
  const noclobber = flags.has("n") || longs.has("--no-clobber");
7269
7328
  return [
7270
7329
  PS_GLOB_FN,
7271
- "$fx_all = " + argListExpr(operandWords),
7330
+ "$fx_all = " + argListExpr(operandWords, globOperandExpr),
7272
7331
  "if ($fx_all.Count -lt 2) { $fx_srcs = @(); $fx_dst = '' } else { $fx_dst = [string]$fx_all[$fx_all.Count - 1]; $fx_srcs = @($fx_all[0..($fx_all.Count - 2)]) }",
7273
7332
  "$fx_srcs = @($fx_srcs | ForEach-Object { fx-glob $_ })",
7274
7333
  "if ($fx_srcs.Count -eq 0) { [Console]::Error.WriteLine('cp: missing file operand'); $script:fx_exit = 1 }",
@@ -7297,7 +7356,7 @@ var mv = (args) => {
7297
7356
  return [
7298
7357
  PS_GLOB_FN,
7299
7358
  PS_MOVE_REPLACE_FN,
7300
- "$fx_all = " + argListExpr(operandWords),
7359
+ "$fx_all = " + argListExpr(operandWords, globOperandExpr),
7301
7360
  "if ($fx_all.Count -lt 2) { $fx_srcs = @(); $fx_dst = '' } else { $fx_dst = [string]$fx_all[$fx_all.Count - 1]; $fx_srcs = @($fx_all[0..($fx_all.Count - 2)]) }",
7302
7361
  "$fx_srcs = @($fx_srcs | ForEach-Object { fx-glob $_ })",
7303
7362
  "if ($fx_srcs.Count -eq 0) { [Console]::Error.WriteLine('mv: missing file operand'); $script:fx_exit = 1 }",
@@ -7342,27 +7401,104 @@ var mv = (args) => {
7342
7401
  "}"
7343
7402
  ].join("\n");
7344
7403
  };
7404
+ var PS_IOERR_FN = [
7405
+ "function fx-ioerr1($x) {",
7406
+ " if ($x -is [UnauthorizedAccessException] -or $x -is [Security.SecurityException]) { return 'Permission denied' }",
7407
+ " if ($x -is [IO.PathTooLongException]) { return 'File name too long' }",
7408
+ " if ($x -is [IO.DirectoryNotFoundException] -or $x -is [IO.FileNotFoundException] -or $x -is [IO.DriveNotFoundException] -or $x -is [System.Management.Automation.ItemNotFoundException] -or $x -is [System.Management.Automation.DriveNotFoundException]) { return 'No such file or directory' }",
7409
+ " if ((($x.HResult -shr 16) -band 0xFFFF) -ne 0x8007) { return $null }",
7410
+ " switch ($x.HResult -band 0xFFFF) {",
7411
+ " { $_ -in 2, 3 } { return 'No such file or directory' }",
7412
+ " 5 { return 'Permission denied' }",
7413
+ " 19 { return 'Read-only file system' }",
7414
+ " { $_ -in 32, 33 } { return 'Device or resource busy' }",
7415
+ " { $_ -in 80, 183 } { return 'File exists' }",
7416
+ " 112 { return 'No space left on device' }",
7417
+ " 123 { return 'Invalid argument' }",
7418
+ " 145 { return 'Directory not empty' }",
7419
+ " 206 { return 'File name too long' }",
7420
+ " 267 { return 'Not a directory' }",
7421
+ " }",
7422
+ " return $null",
7423
+ "}",
7424
+ "function fx-ioerr($e, [string]$fallback) {",
7425
+ " $x = $e",
7426
+ " if ($x -is [System.Management.Automation.ErrorRecord]) { $x = $x.Exception }",
7427
+ " $fx_depth = 0",
7428
+ " while ($null -ne $x -and $fx_depth -lt 16) {",
7429
+ " $fx_r = fx-ioerr1 $x",
7430
+ " if ($null -ne $fx_r) { return $fx_r }",
7431
+ " $x = $x.InnerException",
7432
+ " $fx_depth++",
7433
+ " }",
7434
+ " return $fallback",
7435
+ "}"
7436
+ ].join("\n");
7437
+ function rmPreservesRoot(args) {
7438
+ let preserve = true;
7439
+ for (const w of args) {
7440
+ const t = wordToString(w);
7441
+ if (t === "--") break;
7442
+ if (t === "--preserve-root") preserve = true;
7443
+ else if (t === "--no-preserve-root") preserve = false;
7444
+ }
7445
+ return preserve;
7446
+ }
7345
7447
  var rm = (args) => {
7346
7448
  const { flags, longs, operandWords } = parseWords(args);
7347
7449
  const recurse = flags.has("r") || flags.has("R") || longs.has("--recursive");
7348
7450
  const force = flags.has("f") || longs.has("--force");
7349
7451
  const verbose = flags.has("v") || longs.has("--verbose");
7452
+ const guardRoot = recurse && rmPreservesRoot(args);
7453
+ const b = (v) => v ? "$true" : "$false";
7454
+ const danger = (operand) => "if (" + operand + ` -eq '/') { [Console]::Error.WriteLine("rm: it is dangerous to operate recursively on '/'") } else { [Console]::Error.WriteLine("rm: it is dangerous to operate recursively on '" + ` + operand + ` + "' (same as '/')") }; [Console]::Error.WriteLine('rm: use --no-preserve-root to override this failsafe'); $script:fx_exit = 1; continue`;
7350
7455
  return [
7351
7456
  PS_GLOB_FN,
7352
- "$fx_files = " + psArray(operandWords),
7353
- "if ($fx_files.Count -eq 0 -and " + (force ? "$false" : "$true") + ") { [Console]::Error.WriteLine('rm: missing operand'); $script:fx_exit = 1 }",
7457
+ PS_IOERR_FN,
7458
+ "$fx_files = " + psArray(operandWords, globOperandExpr),
7459
+ "if ($fx_files.Count -eq 0 -and " + b(!force) + ") { [Console]::Error.WriteLine('rm: missing operand'); $script:fx_exit = 1 }",
7460
+ "$fx_guardroot = " + b(guardRoot),
7354
7461
  "foreach ($fx_f in $fx_files) {",
7462
+ " $fx_s = [string]$fx_f",
7463
+ // GNU always refuses a last component of "." or ".."; on Windows a drive
7464
+ // prefix ("C:..", drive-relative) is also a component boundary.
7465
+ " $fx_leaf = ($fx_s -replace '^[A-Za-z]:', '').TrimEnd([char[]]@('/', '\\'))",
7466
+ " $fx_leaf = $fx_leaf.Substring($fx_leaf.LastIndexOfAny([char[]]@('/', '\\')) + 1)",
7467
+ ` if ($fx_leaf -eq '.' -or $fx_leaf -eq '..') { [Console]::Error.WriteLine("rm: refusing to remove '.' or '..' directory: skipping '" + $fx_s + "'"); $script:fx_exit = 1; continue }`,
7468
+ // "/", "//", "///" all name the root; refuse before Test-Path, which may
7469
+ // treat "//"-prefixed text as a (malformed) UNC path and report it absent.
7470
+ " if ($fx_guardroot -and $fx_s -match '^[/\\\\]+$') { " + danger("$fx_s") + " }",
7355
7471
  " foreach ($fx_g in (fx-glob $fx_f)) {",
7356
7472
  " if (-not (Test-Path -LiteralPath $fx_g)) {",
7357
- " if (" + (force ? "$false" : "$true") + `) { [Console]::Error.WriteLine("rm: cannot remove '" + $fx_g + "': No such file or directory"); $script:fx_exit = 1 }`,
7473
+ " if (" + b(!force) + `) { [Console]::Error.WriteLine("rm: cannot remove '" + $fx_g + "': No such file or directory"); $script:fx_exit = 1 }`,
7358
7474
  " continue",
7359
7475
  " }",
7360
7476
  " $fx_isdir = (Test-Path -LiteralPath $fx_g -PathType Container)",
7361
- " if ($fx_isdir -and " + (recurse ? "$false" : "$true") + `) { [Console]::Error.WriteLine("rm: cannot remove '" + $fx_g + "': Is a directory"); $script:fx_exit = 1; continue }`,
7477
+ " if ($fx_isdir -and " + b(!recurse) + `) { [Console]::Error.WriteLine("rm: cannot remove '" + $fx_g + "': Is a directory"); $script:fx_exit = 1; continue }`,
7478
+ " if ($fx_isdir -and $fx_guardroot) {",
7479
+ // Fail closed: if the path cannot be canonicalized, do not delete it.
7480
+ " $fx_rp = $null",
7481
+ " try { $fx_rp = [IO.Path]::GetFullPath((Resolve-Path -LiteralPath $fx_g -ErrorAction Stop).ProviderPath) } catch {}",
7482
+ ` if ($null -eq $fx_rp) { [Console]::Error.WriteLine("rm: cannot remove '" + $fx_g + "': cannot resolve path for the --preserve-root check"); $script:fx_exit = 1; continue }`,
7483
+ " $fx_root = [IO.Path]::GetPathRoot($fx_rp)",
7484
+ " if ([string]::IsNullOrEmpty($fx_root) -or $fx_rp.TrimEnd([char[]]@('/', '\\')) -ieq ([string]$fx_root).TrimEnd([char[]]@('/', '\\'))) { " + danger("$fx_g") + " }",
7485
+ " }",
7486
+ // A directory symlink/junction is removed as a link; never traverse into
7487
+ // its target (Windows PowerShell 5.1 Remove-Item -Recurse can follow it).
7488
+ " if ($fx_isdir -and " + b(recurse) + ") {",
7489
+ " $fx_item = Get-Item -LiteralPath $fx_g -Force -ErrorAction SilentlyContinue",
7490
+ " if ($null -ne $fx_item -and ($fx_item.Attributes -band [IO.FileAttributes]::ReparsePoint)) {",
7491
+ " try {",
7492
+ " [IO.Directory]::Delete($fx_item.FullName, $false)",
7493
+ " if (" + b(verbose) + `) { [Console]::Error.WriteLine("removed '" + $fx_g + "'") }`,
7494
+ ` } catch { [Console]::Error.WriteLine("rm: cannot remove '" + $fx_g + "': " + (fx-ioerr $_ 'Permission denied')); $script:fx_exit = 1 }`,
7495
+ " continue",
7496
+ " }",
7497
+ " }",
7362
7498
  " try {",
7363
- " Remove-Item -LiteralPath $fx_g -Recurse:" + (recurse ? "$true" : "$false") + " -Force -ErrorAction Stop",
7364
- " if (" + (verbose ? "$true" : "$false") + `) { [Console]::Error.WriteLine("removed '" + $fx_g + "'") }`,
7365
- ` } catch { [Console]::Error.WriteLine("rm: cannot remove '" + $fx_g + "': Permission denied"); $script:fx_exit = 1 }`,
7499
+ " Remove-Item -LiteralPath $fx_g -Recurse:" + b(recurse) + " -Force -ErrorAction Stop",
7500
+ " if (" + b(verbose) + `) { [Console]::Error.WriteLine("removed '" + $fx_g + "'") }`,
7501
+ ` } catch { [Console]::Error.WriteLine("rm: cannot remove '" + $fx_g + "': " + (fx-ioerr $_ 'Permission denied')); $script:fx_exit = 1 }`,
7366
7502
  " }",
7367
7503
  "}"
7368
7504
  ].join("\n");
@@ -7372,6 +7508,7 @@ var mkdir = (args) => {
7372
7508
  const parents = flags.has("p") || longs.has("--parents");
7373
7509
  const verbose = flags.has("v") || longs.has("--verbose");
7374
7510
  return [
7511
+ PS_IOERR_FN,
7375
7512
  "$fx_dirs = " + psArray(operandWords),
7376
7513
  "if ($fx_dirs.Count -eq 0) { [Console]::Error.WriteLine('mkdir: missing operand'); $script:fx_exit = 1 }",
7377
7514
  "foreach ($fx_d in $fx_dirs) {",
@@ -7380,9 +7517,16 @@ var mkdir = (args) => {
7380
7517
  " continue",
7381
7518
  " }",
7382
7519
  " try {",
7383
- " New-Item -ItemType Directory -Path $fx_d -Force:" + (parents ? "$true" : "$false") + " -ErrorAction Stop | Out-Null",
7520
+ // Literal creation (#255): [IO.Directory] never interprets wildcard
7521
+ // characters or PS provider prefixes (Env:, Function:) the way
7522
+ // New-Item -Path does.
7523
+ ...parents ? [" [void][IO.Directory]::CreateDirectory($fx_d)"] : [
7524
+ " $fx_par = [IO.Path]::GetDirectoryName([IO.Path]::GetFullPath($fx_d))",
7525
+ " if ($null -ne $fx_par -and -not (Test-Path -LiteralPath $fx_par -PathType Container)) { throw [IO.DirectoryNotFoundException]::new() }",
7526
+ " [void][IO.Directory]::CreateDirectory($fx_d)"
7527
+ ],
7384
7528
  " if (" + (verbose ? "$true" : "$false") + `) { [Console]::Error.WriteLine("mkdir: created directory '" + $fx_d + "'") }`,
7385
- ` } catch { [Console]::Error.WriteLine("mkdir: cannot create directory '" + $fx_d + "': " + $_.Exception.Message); $script:fx_exit = 1 }`,
7529
+ ` } catch { [Console]::Error.WriteLine("mkdir: cannot create directory '" + $fx_d + "': " + (fx-ioerr $_ 'No such file or directory')); $script:fx_exit = 1 }`,
7386
7530
  "}"
7387
7531
  ].join("\n");
7388
7532
  };
@@ -7402,15 +7546,18 @@ var touch = (args) => {
7402
7546
  const { flags, longs, operandWords } = parseWords(args);
7403
7547
  const noCreate = flags.has("c") || longs.has("--no-create");
7404
7548
  return [
7549
+ PS_IOERR_FN,
7405
7550
  "$fx_files = " + psArray(operandWords),
7406
7551
  "if ($fx_files.Count -eq 0) { [Console]::Error.WriteLine('touch: missing file operand'); $script:fx_exit = 1 }",
7407
7552
  "foreach ($fx_f in $fx_files) {",
7408
7553
  " if (Test-Path -LiteralPath $fx_f) {",
7409
- ` try { (Get-Item -LiteralPath $fx_f).LastWriteTime = Get-Date } catch { [Console]::Error.WriteLine("touch: cannot touch '" + $fx_f + "': Permission denied"); $script:fx_exit = 1 }`,
7554
+ ` try { (Get-Item -LiteralPath $fx_f -Force -ErrorAction Stop).LastWriteTime = Get-Date } catch { [Console]::Error.WriteLine("touch: cannot touch '" + $fx_f + "': " + (fx-ioerr $_ 'Permission denied')); $script:fx_exit = 1 }`,
7410
7555
  " } else {",
7411
7556
  " if (" + (noCreate ? "$true" : "$false") + ") { continue }",
7412
- " try { New-Item -ItemType File -Path $fx_f -ErrorAction Stop | Out-Null }",
7413
- ` catch { [Console]::Error.WriteLine("touch: cannot touch '" + $fx_f + "': No such file or directory"); $script:fx_exit = 1 }`,
7557
+ // Literal creation (#255): .NET File.Create never reads wildcard
7558
+ // characters or PS provider prefixes into the name.
7559
+ " try { $fx_nfs = [IO.File]::Create($fx_f); $fx_nfs.Close() }",
7560
+ ` catch { [Console]::Error.WriteLine("touch: cannot touch '" + $fx_f + "': " + (fx-ioerr $_ 'No such file or directory')); $script:fx_exit = 1 }`,
7414
7561
  " }",
7415
7562
  "}"
7416
7563
  ].join("\n");
@@ -7560,7 +7707,7 @@ var stat = (args, ctx) => {
7560
7707
  PS_FTIME_FN,
7561
7708
  PS_GLOB_FN,
7562
7709
  ...printfMode ? [PS_WRITE_FN, fxTermLine(ctx.position), "$fx_stat_out = New-Object System.Text.StringBuilder"] : [],
7563
- "$fx_files = " + psArray(operandWords),
7710
+ "$fx_files = " + psArray(operandWords, globOperandExpr),
7564
7711
  "if ($fx_files.Count -eq 0) { [Console]::Error.WriteLine('stat: missing operand'); $script:fx_exit = 1 }",
7565
7712
  "foreach ($fx_f in $fx_files) {",
7566
7713
  " foreach ($fx_g in (fx-glob $fx_f)) {",
@@ -7592,7 +7739,7 @@ var file = (args) => {
7592
7739
  return [
7593
7740
  PS_GLOB_FN,
7594
7741
  PS_READTEXT_FN,
7595
- "$fx_files = " + psArray(operandWords),
7742
+ "$fx_files = " + psArray(operandWords, globOperandExpr),
7596
7743
  "if ($fx_files.Count -eq 0) { [Console]::Error.WriteLine('file: missing operand'); $script:fx_exit = 1 }",
7597
7744
  "foreach ($fx_f in $fx_files) {",
7598
7745
  " foreach ($fx_g in (fx-glob $fx_f)) {",
@@ -8072,6 +8219,8 @@ var specs2 = [
8072
8219
  opt("R", "--recursive"),
8073
8220
  opt("f", "--force"),
8074
8221
  opt("v", "--verbose"),
8222
+ opt(void 0, "--preserve-root"),
8223
+ opt(void 0, "--no-preserve-root"),
8075
8224
  opt("i", "--interactive", "unsupported", INTERACTIVE)
8076
8225
  ],
8077
8226
  rm
@@ -8174,9 +8323,12 @@ var PS_GLOB_FN2 = [
8174
8323
  "function fx-glob($p) {",
8175
8324
  " if ($p -notlike '*[*?]*') { return @($p) }",
8176
8325
  " $m = @(Get-Item -Path $p -ErrorAction SilentlyContinue)",
8177
- " if ($m.Count -eq 0) { return @($p) }",
8326
+ " if ($m.Count -eq 0) { return @(fx-wclit $p) }",
8178
8327
  " return @($m | ForEach-Object { $_.FullName })",
8179
- "}"
8328
+ "}",
8329
+ // Unescape wildcard-escaped literals (#255): quoted glob characters that
8330
+ // matched nothing keep their shell spelling as the literal operand.
8331
+ "function fx-wclit($p) { return ($p -replace '`(?=[*?[])', '') }"
8180
8332
  ].join("\n");
8181
8333
  var PS_READTEXT_FN2 = [
8182
8334
  "function fx-read($p) {",
@@ -8544,7 +8696,7 @@ var grep = (args) => {
8544
8696
  lines.push(" }");
8545
8697
  lines.push("}");
8546
8698
  }
8547
- lines.push("foreach ($fx_o in " + psArray2(fileWords) + ") {");
8699
+ lines.push("foreach ($fx_o in " + psArray2(fileWords, globOperandExpr) + ") {");
8548
8700
  lines.push(" foreach ($fx_g in (fx-glob $fx_o)) {");
8549
8701
  lines.push(
8550
8702
  " if (-not (Test-Path -LiteralPath $fx_g)) { [Console]::Error.WriteLine('grep: ' + $fx_g + ': No such file or directory'); $fx_err = $true; continue }"
@@ -8716,8 +8868,12 @@ function sedReplToNet(repl, delim) {
8716
8868
  else if (n === "n") out += "\n";
8717
8869
  else if (n === "t") out += " ";
8718
8870
  else if (n === "&") out += "&";
8719
- else if (/[1-9]/.test(n)) out += "$" + n;
8720
- else out += "\\" + n;
8871
+ else if (n === "0") out += "$&";
8872
+ else if (/[1-9]/.test(n)) {
8873
+ const next = repl[i + 2];
8874
+ if (next !== void 0 && /[0-9]/.test(next)) out += "${" + n + "}";
8875
+ else out += "$" + n;
8876
+ } else out += "\\" + n;
8721
8877
  i += 2;
8722
8878
  continue;
8723
8879
  }
@@ -9205,7 +9361,7 @@ var sed = (args, ctx) => {
9205
9361
  if (operandWords.length > 0) {
9206
9362
  lines.push(
9207
9363
  ...psCollectSources(
9208
- psArray2(operandWords),
9364
+ psArray2(operandWords, globOperandExpr),
9209
9365
  (v) => "[Console]::Error.WriteLine('sed: can''t read ' + " + v + " + ': No such file or directory')",
9210
9366
  true
9211
9367
  )
@@ -9681,6 +9837,46 @@ var AwkParser = class {
9681
9837
  throw new FauxnixParseError("fauxnix: awk unexpected character '" + c + "' in expression");
9682
9838
  }
9683
9839
  };
9840
+ var PS_AWK_IFMT_FN = [
9841
+ "function fx-awk-ifmt($v, $conv, $flags, $width, $prec) {",
9842
+ " $n = [long][math]::Truncate((fx-num $v))",
9843
+ " $prefix = ''",
9844
+ " $digits = ''",
9845
+ " if ($conv -ceq 'd') {",
9846
+ " if ($n -lt 0) {",
9847
+ " $prefix = '-'",
9848
+ " if ($n -eq [long]::MinValue) { $digits = '9223372036854775808' }",
9849
+ " else { $digits = [string]([math]::Abs([long]$n)) }",
9850
+ " } else {",
9851
+ " if ($flags.Contains('+')) { $prefix = '+' }",
9852
+ " elseif ($flags.Contains(' ')) { $prefix = ' ' }",
9853
+ " $digits = [string]$n",
9854
+ " }",
9855
+ " } elseif ($conv -ceq 'o') {",
9856
+ " $digits = [Convert]::ToString([long]$n, 8)",
9857
+ " } elseif ($conv -ceq 'X') {",
9858
+ " $digits = [Convert]::ToString([long]$n, 16).ToUpperInvariant()",
9859
+ " } else {",
9860
+ " $digits = [Convert]::ToString([long]$n, 16)",
9861
+ " }",
9862
+ " if ($null -ne $prec) {",
9863
+ " $p = [int]$prec",
9864
+ " if ($p -eq 0 -and $digits -eq '0') { $digits = '' }",
9865
+ " elseif ($digits.Length -lt $p) { $digits = $digits.PadLeft($p, [char]48) }",
9866
+ " }",
9867
+ " $body = $prefix + $digits",
9868
+ " if ($null -eq $width) { return $body }",
9869
+ " $w = [int]$width",
9870
+ " if ($body.Length -ge $w) { return $body }",
9871
+ " if ($flags.Contains('-')) { return $body.PadRight($w) }",
9872
+ " if ($flags.Contains('0') -and $null -eq $prec) {",
9873
+ " $digits = $digits.PadLeft($w - $prefix.Length, [char]48)",
9874
+ " return $prefix + $digits",
9875
+ " }",
9876
+ " return $body.PadLeft($w)",
9877
+ "}"
9878
+ ].join("\n");
9879
+ var AWK_INT_CONVS = /* @__PURE__ */ new Set(["d", "o", "x", "X"]);
9684
9880
  function awkFmtToPs(fmt) {
9685
9881
  const chunks = [];
9686
9882
  const kinds = [];
@@ -9696,23 +9892,25 @@ function awkFmtToPs(fmt) {
9696
9892
  while (i < fmt.length) {
9697
9893
  const c = fmt[i];
9698
9894
  if (c === "%") {
9699
- const m = fmt.slice(i).match(/^%([-+0 ]*)(\d+)?(?:\.(\d+))?([sdfc])/);
9895
+ const m = fmt.slice(i).match(/^%([-+0 ]*)(\d+)?(?:\.(\d+))?([sdfcioxX])/);
9700
9896
  if (m) {
9701
9897
  const flags = m[1];
9702
9898
  const width = m[2];
9703
9899
  const prec = m[3];
9704
- const conv = m[4];
9900
+ let conv = m[4];
9901
+ if (conv === "i") conv = "d";
9705
9902
  flushLit();
9706
9903
  const idx = kinds.length;
9707
9904
  let spec = "";
9905
+ let align = "";
9708
9906
  if (conv === "f") {
9709
9907
  spec = "F" + (prec === void 0 ? "6" : prec);
9710
- } else if (conv === "d" && prec !== void 0) {
9711
- spec = "D" + prec;
9712
9908
  }
9713
- const align = width === void 0 ? "" : "," + (flags.includes("-") ? "-" : "") + width;
9909
+ if (!AWK_INT_CONVS.has(conv) && width !== void 0) {
9910
+ align = "," + (flags.includes("-") ? "-" : "") + width;
9911
+ }
9714
9912
  chunks.push("'{" + idx + align + (spec === "" ? "" : ":" + spec) + "}'");
9715
- kinds.push({ conv, align, spec });
9913
+ kinds.push({ conv, align, spec, flags, width, prec });
9716
9914
  i += m[0].length;
9717
9915
  continue;
9718
9916
  }
@@ -9750,6 +9948,19 @@ function awkFmtToPs(fmt) {
9750
9948
  const ps2 = chunks.length === 0 ? "''" : "(" + chunks.join(" + ") + ")";
9751
9949
  return { ps: ps2, kinds };
9752
9950
  }
9951
+ function awkUsesIntPrintf(prog) {
9952
+ const stmts = [
9953
+ ...prog.begin,
9954
+ ...prog.items.flatMap((item) => item.act ?? []),
9955
+ ...prog.end
9956
+ ];
9957
+ for (const st of stmts) {
9958
+ if (st.k === "printf" && awkFmtToPs(st.fmt).kinds.some((k) => AWK_INT_CONVS.has(k.conv))) {
9959
+ return true;
9960
+ }
9961
+ }
9962
+ return false;
9963
+ }
9753
9964
  var awk = (args, ctx) => {
9754
9965
  const { values, operandWords } = parseWords(args, ["F", "v"]);
9755
9966
  const vvars = [];
@@ -9922,7 +10133,11 @@ var awk = (args, ctx) => {
9922
10133
  const argExprs = f.kinds.map((kind, idx) => {
9923
10134
  const arg = st.args[idx];
9924
10135
  const raw = gen(arg ?? { k: "num", v: 0 }).ps;
9925
- if (kind.conv === "d") return "([string][math]::Truncate((fx-num " + raw + ")))";
10136
+ if (AWK_INT_CONVS.has(kind.conv)) {
10137
+ const w = kind.width === void 0 ? "$null" : kind.width;
10138
+ const p = kind.prec === void 0 ? "$null" : kind.prec;
10139
+ return "(fx-awk-ifmt " + raw + " " + psStr(kind.conv) + " " + psStr(kind.flags) + " " + w + " " + p + ")";
10140
+ }
9926
10141
  if (kind.conv === "f") return "(fx-num " + raw + ")";
9927
10142
  if (kind.conv === "c") {
9928
10143
  if (arg !== void 0 && arg.k === "num") return "[string][char]" + Math.trunc(arg.v);
@@ -10037,6 +10252,7 @@ var awk = (args, ctx) => {
10037
10252
  " return ''",
10038
10253
  "}"
10039
10254
  );
10255
+ if (awkUsesIntPrintf(prog)) lines.push(PS_AWK_IFMT_FN);
10040
10256
  lines.push(...hoistedRegex);
10041
10257
  for (const v of prog.vars) lines.push("$fxv_" + v + " = $null");
10042
10258
  lines.push("$fxv_OFS = ' '", "$fx_line = ''", "$fx_flds = @()", "$fx_nf = 0");
@@ -10051,7 +10267,7 @@ var awk = (args, ctx) => {
10051
10267
  if (fileWords.length > 0) {
10052
10268
  lines.push(
10053
10269
  ...psCollectSources(
10054
- psArray2(fileWords),
10270
+ psArray2(fileWords, globOperandExpr),
10055
10271
  (v) => "[Console]::Error.WriteLine('awk: fatal: cannot open file ' + [string][char]96 + " + v + " + [string][char]39 + ' for reading (No such file or directory)')",
10056
10272
  true
10057
10273
  )
@@ -10156,7 +10372,7 @@ var sort = (args) => {
10156
10372
  const lines = [PS_READTEXT_FN2, PS_SPLITLINES_FN, PS_GLOB_FN2];
10157
10373
  lines.push(
10158
10374
  ...psCollectSources(
10159
- psArray2(operandWords),
10375
+ psArray2(operandWords, globOperandExpr),
10160
10376
  (v) => "[Console]::Error.WriteLine('sort: cannot read: ' + " + v + " + ': No such file or directory')",
10161
10377
  false
10162
10378
  )
@@ -10330,7 +10546,7 @@ var uniq = (args) => {
10330
10546
  lines.push(PS_GLOB_FN2);
10331
10547
  lines.push(
10332
10548
  ...psCollectSources(
10333
- "@(" + operandExpr(inFile) + ")",
10549
+ "@(" + globOperandExpr(inFile) + ")",
10334
10550
  (v) => "[Console]::Error.WriteLine('uniq: ' + " + v + " + ': No such file or directory')",
10335
10551
  false
10336
10552
  )
@@ -10432,7 +10648,7 @@ var cut = (args) => {
10432
10648
  const lines = [PS_READTEXT_FN2, PS_SPLITLINES_FN, PS_GLOB_FN2];
10433
10649
  lines.push(
10434
10650
  ...psCollectSources(
10435
- psArray2(operandWords),
10651
+ psArray2(operandWords, globOperandExpr),
10436
10652
  (v) => "[Console]::Error.WriteLine('cut: ' + " + v + " + ': No such file or directory')",
10437
10653
  false
10438
10654
  )
@@ -10717,9 +10933,12 @@ var PS_GLOB_FN3 = [
10717
10933
  "function fx-glob($p) {",
10718
10934
  " if ($p -notlike '*[*?]*') { return @($p) }",
10719
10935
  " $m = @(Get-Item -Path $p -ErrorAction SilentlyContinue)",
10720
- " if ($m.Count -eq 0) { return @($p) }",
10936
+ " if ($m.Count -eq 0) { return @(fx-wclit $p) }",
10721
10937
  " return @($m | ForEach-Object { $_.FullName })",
10722
- "}"
10938
+ "}",
10939
+ // Unescape wildcard-escaped literals (#255): quoted glob characters that
10940
+ // matched nothing keep their shell spelling as the literal operand.
10941
+ "function fx-wclit($p) { return ($p -replace '`(?=[*?[])', '') }"
10723
10942
  ].join("\n");
10724
10943
  var PS_READTEXT_FN3 = [
10725
10944
  "function fx-read($p) {",
@@ -10792,7 +11011,7 @@ function psCollectFiles(operandWords, missErr, dirErr, stdinDefault = true) {
10792
11011
  continue;
10793
11012
  }
10794
11013
  const lit = w.every((p) => p.kind === "Text" || p.kind === "SingleQuoted") ? w.map((p) => p.text).join("") : null;
10795
- out.push("foreach ($fx_d in " + argListExpr([w], lit !== null ? operandExpr : exprOfWord) + ") {");
11014
+ out.push("foreach ($fx_d in " + argListExpr([w], globOperandExpr) + ") {");
10796
11015
  out.push("foreach ($fx_g in (fx-glob $fx_d)) {");
10797
11016
  if (dirErr) {
10798
11017
  const dis = lit !== null && /[*?]/.test(lit) ? "$fx_g" : "$fx_d";
@@ -10801,7 +11020,9 @@ function psCollectFiles(operandWords, missErr, dirErr, stdinDefault = true) {
10801
11020
  );
10802
11021
  }
10803
11022
  out.push(
10804
- " if (-not (Test-Path -LiteralPath $fx_g -PathType Leaf)) { " + psErrExpr(missErr("$fx_d")) + "; continue }"
11023
+ " if (-not (Test-Path -LiteralPath $fx_g -PathType Leaf)) { " + // $fx_g: unmatched literals come back unescaped by fx-wclit, keeping
11024
+ // the shell spelling in the message (matched globs resolve anyway).
11025
+ psErrExpr(missErr("$fx_g")) + "; continue }"
10805
11026
  );
10806
11027
  out.push(" $fx_srcs += $fx_g");
10807
11028
  out.push(
@@ -15372,13 +15593,12 @@ var handlers5 = {
15372
15593
 
15373
15594
  // src/runtime-support.ts
15374
15595
  var import_node_fs2 = require("node:fs");
15375
- var import_meta = {};
15376
15596
  var bundledRange = globalThis.__FAUXNIX_ENGINES_NODE__;
15377
15597
  var nodeEngineRange;
15378
15598
  if (typeof bundledRange === "string") {
15379
15599
  nodeEngineRange = bundledRange;
15380
15600
  } else {
15381
- const metadata = JSON.parse((0, import_node_fs2.readFileSync)(new URL("../package.json", import_meta.url), "utf8"));
15601
+ const metadata = JSON.parse((0, import_node_fs2.readFileSync)(new URL("../package.json", "file://fauxnix-sea/"), "utf8"));
15382
15602
  nodeEngineRange = metadata.engines?.node;
15383
15603
  }
15384
15604
  var minimum = /^>=(\d+)\.(\d+)\.(\d+)$/.exec(nodeEngineRange);
@@ -15408,6 +15628,10 @@ const { pipeline } = require('node:stream/promises');
15408
15628
  if (leased) {
15409
15629
  process.stdin.on('end', stopDecoder);
15410
15630
  process.stdin.on('error', stopDecoder);
15631
+ // #240 hardening: 'close' fires when the stream is torn down without a
15632
+ // clean 'end' - exactly the intermittent CI-hang shape. Listening for
15633
+ // both costs nothing and stops the decoder either way.
15634
+ process.stdin.on('close', stopDecoder);
15411
15635
  process.stdin.resume();
15412
15636
  }
15413
15637
  const parent = Number(process.argv[3]);
@@ -15908,6 +16132,7 @@ var unzip = (args) => {
15908
16132
  const arc = operandExpr(rest[0]);
15909
16133
  const dirExpr = dir ? operandExpr(dir) : "'.'";
15910
16134
  return [
16135
+ "Add-Type -AssemblyName System.IO.Compression",
15911
16136
  "Add-Type -AssemblyName System.IO.Compression.FileSystem",
15912
16137
  "$fx_arc = " + arc,
15913
16138
  "if (-not (Test-Path -LiteralPath $fx_arc -PathType Leaf)) {",
@@ -15934,10 +16159,105 @@ var unzip = (args) => {
15934
16159
  " ((([string]$fx_tot).PadLeft(9)) + ' ' + $fx_cnt + ' file' + $fx_pl)",
15935
16160
  " } finally { $fx_z.Dispose() }"
15936
16161
  ].join("\n") : [
16162
+ // Extract entry by entry so every target is proven to stay inside
16163
+ // the destination (zip-slip, #257) regardless of which Archive
16164
+ // module / .NET version the host has. Nothing is written unless
16165
+ // every entry passes validation.
16166
+ // Known limitations: names without the UTF-8 flag are decoded by
16167
+ // .NET (OEM code page on Windows PowerShell 5.1, UTF-8 on pwsh 7);
16168
+ // targets beyond MAX_PATH fail per entry on 5.1 unless long paths
16169
+ // are enabled. Duplicate/case-colliding names: first wins without
16170
+ // -o (warning), last wins with -o.
15937
16171
  " $fx_dir = " + dirExpr,
16172
+ " $fx_z = $null",
15938
16173
  " try {",
15939
- " Expand-Archive -LiteralPath $fx_arc -DestinationPath $fx_dir -Force:" + (over ? "$true" : "$false") + " -ErrorAction Stop",
15940
- " } catch { [Console]::Error.WriteLine('unzip: fauxnix: ' + $_.Exception.Message + ' (use -o to overwrite)'); $script:fx_exit = 1 }"
16174
+ " $fx_root = [IO.Path]::GetFullPath($ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath([string]$fx_dir))",
16175
+ // root with exactly one trailing separator ("C:\" stays "C:\")
16176
+ " $fx_rootT = $fx_root.TrimEnd([char[]]@('\\', '/')) + [IO.Path]::DirectorySeparatorChar",
16177
+ " $fx_z = [IO.Compression.ZipFile]::OpenRead((Resolve-Path -LiteralPath $fx_arc).ProviderPath)",
16178
+ " $fx_bad = @()",
16179
+ " $fx_plan = @()",
16180
+ " foreach ($fx_e in $fx_z.Entries) {",
16181
+ " $fx_n = [string]$fx_e.FullName",
16182
+ " $fx_t = $null",
16183
+ " $fx_why = 'outside destination'",
16184
+ " $fx_dev = @($fx_n -split '[\\\\/]' | Where-Object { (($_ -split '\\.')[0]).TrimEnd(' ') -match '^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$' })",
16185
+ // rooted, drive-qualified (or NTFS stream) names are never relative
16186
+ // Directory entries end in a separator; some writers instead set the
16187
+ // MS-DOS directory attribute (0x10) on a zero-length entry.
16188
+ " $fx_isDir = $fx_n.EndsWith('/') -or $fx_n.EndsWith('\\') -or ($fx_e.Length -eq 0 -and ($fx_e.ExternalAttributes -band 0x10) -ne 0)",
16189
+ " if ($fx_n -match '^[\\\\/]') { $fx_why = 'absolute path' }",
16190
+ " elseif ($fx_n.IndexOf(':') -ge 0) { $fx_why = 'drive or stream name' }",
16191
+ " elseif ($fx_dev.Count -gt 0) { $fx_why = 'reserved device name' }",
16192
+ " else {",
16193
+ " try { $fx_t = [IO.Path]::GetFullPath([IO.Path]::Combine($fx_rootT, $fx_n)) } catch { $fx_why = 'invalid name' }",
16194
+ // "./" or "a/.." resolve to the root itself: inside, not an escape
16195
+ " if ($null -ne $fx_t) {",
16196
+ " $fx_tT = $fx_t.TrimEnd([char[]]@('\\', '/')) + [IO.Path]::DirectorySeparatorChar",
16197
+ " if (-not $fx_tT.StartsWith($fx_rootT, [StringComparison]::OrdinalIgnoreCase)) { $fx_t = $null }",
16198
+ // only a directory entry may name the destination itself
16199
+ " elseif ($fx_tT.Length -eq $fx_rootT.Length -and -not $fx_isDir) { $fx_t = $null; $fx_why = 'names the destination itself' }",
16200
+ " }",
16201
+ " }",
16202
+ " if ($null -eq $fx_t) { $fx_bad += ,@($fx_n, $fx_why) } else { $fx_plan += ,@($fx_e, $fx_t, $fx_isDir) }",
16203
+ " }",
16204
+ " if ($fx_bad.Count -gt 0) {",
16205
+ ` foreach ($fx_b in $fx_bad) { [Console]::Error.WriteLine("unzip: fauxnix: refusing unsafe entry '" + $fx_b[0] + "' (" + $fx_b[1] + ")") }`,
16206
+ " $script:fx_exit = 1",
16207
+ " } else {",
16208
+ // targets written by this run (case-insensitive, like NTFS)
16209
+ " $fx_done = @{}",
16210
+ " foreach ($fx_p in $fx_plan) {",
16211
+ " $fx_e = $fx_p[0]",
16212
+ " $fx_t = $fx_p[1]",
16213
+ " try {",
16214
+ // An existing symlink/junction below the root (or at the target)
16215
+ // would redirect the write outside the destination.
16216
+ " $fx_linked = $false",
16217
+ " $fx_cur = $fx_t.TrimEnd([char[]]@('\\', '/'))",
16218
+ " while ($null -ne $fx_cur -and $fx_cur.Length -ge $fx_rootT.Length) {",
16219
+ " $fx_attr = $null",
16220
+ " try { $fx_attr = [IO.File]::GetAttributes($fx_cur) } catch {}",
16221
+ " if ($null -ne $fx_attr -and ($fx_attr -band [IO.FileAttributes]::ReparsePoint)) { $fx_linked = $true; break }",
16222
+ " $fx_cur = [IO.Path]::GetDirectoryName($fx_cur)",
16223
+ " }",
16224
+ " if ($fx_linked) {",
16225
+ ` [Console]::Error.WriteLine("unzip: fauxnix: refusing entry '" + $fx_e.FullName + "' (path goes through a symbolic link or junction)")`,
16226
+ " $script:fx_exit = 1",
16227
+ " continue",
16228
+ " }",
16229
+ " if ($fx_p[2]) {",
16230
+ " [void][IO.Directory]::CreateDirectory($fx_t)",
16231
+ " continue",
16232
+ " }",
16233
+ // Duplicate or case-colliding names inside the archive: without -o
16234
+ // the first one wins (warning only, like declining unzip's
16235
+ // overwrite prompt); with -o the later one replaces it.
16236
+ over ? " if ($false) {" : " if ($fx_done.ContainsKey($fx_t)) {",
16237
+ " [Console]::Error.WriteLine('unzip: fauxnix: skipping ' + $fx_e.FullName + ': same name as an entry already extracted (' + $fx_done[$fx_t] + ')')",
16238
+ " continue",
16239
+ " }",
16240
+ " if (Test-Path -LiteralPath $fx_t -PathType Container) {",
16241
+ " [Console]::Error.WriteLine('unzip: fauxnix: cannot extract ' + $fx_e.FullName + ': a directory with that name exists')",
16242
+ " $script:fx_exit = 1",
16243
+ " continue",
16244
+ " }",
16245
+ " if ((Test-Path -LiteralPath $fx_t) -and " + (over ? "$false" : "$true") + ") {",
16246
+ " [Console]::Error.WriteLine('unzip: fauxnix: ' + $fx_e.FullName + ' already exists (use -o to overwrite)')",
16247
+ " $script:fx_exit = 1",
16248
+ " continue",
16249
+ " }",
16250
+ " [void][IO.Directory]::CreateDirectory([IO.Path]::GetDirectoryName($fx_t))",
16251
+ ...over ? [
16252
+ // -o: a ReadOnly file would make ExtractToFile throw
16253
+ " if ([IO.File]::Exists($fx_t)) { $fx_a = [IO.File]::GetAttributes($fx_t); if ($fx_a -band [IO.FileAttributes]::ReadOnly) { [IO.File]::SetAttributes($fx_t, $fx_a -band (-bnot [IO.FileAttributes]::ReadOnly)) } }"
16254
+ ] : [],
16255
+ " [IO.Compression.ZipFileExtensions]::ExtractToFile($fx_e, $fx_t, $true)",
16256
+ " $fx_done[$fx_t] = $fx_e.FullName",
16257
+ " } catch { [Console]::Error.WriteLine('unzip: fauxnix: cannot extract ' + $fx_e.FullName + ': ' + $_.Exception.Message); $script:fx_exit = 1 }",
16258
+ " }",
16259
+ " }",
16260
+ " } catch { [Console]::Error.WriteLine('unzip: fauxnix: ' + $_.Exception.Message); $script:fx_exit = 1 } finally { if ($null -ne $fx_z) { $fx_z.Dispose() } }"
15941
16261
  ].join("\n"),
15942
16262
  "}"
15943
16263
  ].join("\n");
@@ -16046,7 +16366,7 @@ installAll();
16046
16366
  var import_node_fs7 = require("node:fs");
16047
16367
 
16048
16368
  // src/executor.ts
16049
- var import_node_crypto = require("node:crypto");
16369
+ var import_node_crypto2 = require("node:crypto");
16050
16370
  var import_node_fs5 = require("node:fs");
16051
16371
  var import_node_os2 = __toESM(require("node:os"), 1);
16052
16372
  var import_node_path3 = __toESM(require("node:path"), 1);
@@ -16108,6 +16428,7 @@ function clipUtf8(text, limit) {
16108
16428
  }
16109
16429
 
16110
16430
  // src/ps-host.ts
16431
+ var import_node_crypto = require("node:crypto");
16111
16432
  var import_node_child_process = require("node:child_process");
16112
16433
  var import_node_fs4 = require("node:fs");
16113
16434
 
@@ -16322,6 +16643,26 @@ var PowerShellHost = class {
16322
16643
  this.stderrChunks = [];
16323
16644
  return b;
16324
16645
  }
16646
+ /**
16647
+ * Synchronous best-effort termination for process-exit paths, where the
16648
+ * async stop() cannot be awaited. Fails pending waiters like stop().
16649
+ */
16650
+ killSync() {
16651
+ this.cancelNativeCapture();
16652
+ const proc = this.proc;
16653
+ this.proc = null;
16654
+ this.closed = true;
16655
+ this.failWaiters(new Error("fauxnix: PowerShell host stopped"));
16656
+ if (!proc) return;
16657
+ try {
16658
+ proc.stdin?.destroy();
16659
+ } catch {
16660
+ }
16661
+ try {
16662
+ proc.kill();
16663
+ } catch {
16664
+ }
16665
+ }
16325
16666
  async stop() {
16326
16667
  this.cancelNativeCapture();
16327
16668
  const proc = this.proc;
@@ -16392,7 +16733,7 @@ var PowerShellHost = class {
16392
16733
  };
16393
16734
  }
16394
16735
  if (started) return { ...started, cancelled: false, truncated: false };
16395
- const id2 = "f" + Date.now().toString(36) + Math.random().toString(36).slice(2, 8);
16736
+ const id2 = "f" + Date.now().toString(36) + (0, import_node_crypto.randomBytes)(6).toString("hex");
16396
16737
  const resolvedLimits = { ...limits };
16397
16738
  if (resolvedLimits.stdoutMode === "spool") {
16398
16739
  resolvedLimits.stdoutSpoolPath = this.hostFile + "." + id2 + ".stdout";
@@ -16580,6 +16921,13 @@ var PowerShellHost = class {
16580
16921
  windowsHide: true
16581
16922
  });
16582
16923
  this.proc = child;
16924
+ child.stdin.on("error", (e) => {
16925
+ if (this.proc !== child) return;
16926
+ this.closeErr = e;
16927
+ this.closed = true;
16928
+ this.failWaiters(e);
16929
+ this.cancelNativeCapture();
16930
+ });
16583
16931
  child.stdout.on("data", (d) => {
16584
16932
  if (this.proc !== child) return;
16585
16933
  this.onStdout(d);
@@ -16593,6 +16941,7 @@ var PowerShellHost = class {
16593
16941
  this.closeErr = e;
16594
16942
  this.closed = true;
16595
16943
  this.failWaiters(e);
16944
+ this.cancelNativeCapture();
16596
16945
  });
16597
16946
  child.on("close", (c) => {
16598
16947
  if (this.proc !== child) return;
@@ -16600,6 +16949,7 @@ var PowerShellHost = class {
16600
16949
  this.closed = true;
16601
16950
  this.proc = null;
16602
16951
  this.failWaiters(new Error("fauxnix: powershell host closed"));
16952
+ this.cancelNativeCapture();
16603
16953
  });
16604
16954
  try {
16605
16955
  const readyLine = await this.nextReadyLine(READY_TIMEOUT_MS);
@@ -16696,7 +17046,7 @@ var PowerShellHost = class {
16696
17046
  limits?.stderrMode ?? "capture",
16697
17047
  limits?.stderrLimit ?? DEFAULT_STDERR_LIMIT,
16698
17048
  limits?.nativeStderrSpoolPath,
16699
- timeoutMs + 2e3
17049
+ timeoutMs
16700
17050
  );
16701
17051
  void nativePromise.catch(() => void 0);
16702
17052
  while (!end) {
@@ -16722,25 +17072,7 @@ var PowerShellHost = class {
16722
17072
  end = f;
16723
17073
  }
16724
17074
  }
16725
- let nativeBytes = 0;
16726
- let markerTimer;
16727
- try {
16728
- const captured = await Promise.race([
16729
- nativePromise,
16730
- new Promise((_, reject) => {
16731
- markerTimer = setTimeout(
16732
- () => reject(new Error("fauxnix: native stderr marker missing")),
16733
- 2e3
16734
- );
16735
- })
16736
- ]);
16737
- nativeBytes = captured.bytesSeen;
16738
- } catch (e) {
16739
- this.cancelNativeCapture();
16740
- if (e instanceof NativeStderrSpoolError) throw e;
16741
- } finally {
16742
- if (markerTimer) clearTimeout(markerTimer);
16743
- }
17075
+ const { bytesSeen: nativeBytes } = await nativePromise;
16744
17076
  const capturedErr = Buffer.from(Buffer.concat(err));
16745
17077
  let native = Buffer.alloc(0);
16746
17078
  let nativeTruncated = false;
@@ -16777,7 +17109,10 @@ var PowerShellHost = class {
16777
17109
  const timer = setTimeout(() => {
16778
17110
  if (this.nativeCapture?.id !== id2) return;
16779
17111
  const state = this.nativeCapture;
16780
- const failure = state.ioError ?? new Error("fauxnix: native stderr marker missing");
17112
+ const failure = state.ioError ?? Object.assign(
17113
+ new Error("fauxnix: native stderr marker timed out"),
17114
+ { timedOut: true }
17115
+ );
16781
17116
  this.closeNativeSpool(state);
16782
17117
  this.nativeCapture = null;
16783
17118
  reject(failure);
@@ -17097,15 +17432,73 @@ function planRedirects(redirects) {
17097
17432
  }
17098
17433
  return r;
17099
17434
  }
17435
+ var STATE_DIR_RE = /^fauxnix-(\d+)-[0-9a-f]{24}$/;
17436
+ var STALE_MIN_AGE_MS = 6e4;
17437
+ var liveSessions = /* @__PURE__ */ new Set();
17438
+ function isProcessAlive(pid) {
17439
+ try {
17440
+ process.kill(pid, 0);
17441
+ return true;
17442
+ } catch (error) {
17443
+ return error.code !== "ESRCH";
17444
+ }
17445
+ }
17446
+ var staleSweepDone = false;
17447
+ function sweepStaleStateDirs(root = import_node_os2.default.tmpdir(), now = Date.now()) {
17448
+ const removed = [];
17449
+ let names;
17450
+ try {
17451
+ names = (0, import_node_fs5.readdirSync)(root);
17452
+ } catch {
17453
+ return removed;
17454
+ }
17455
+ for (const name of names) {
17456
+ const m = STATE_DIR_RE.exec(name);
17457
+ if (!m) continue;
17458
+ const pid = Number(m[1]);
17459
+ if (pid === process.pid || isProcessAlive(pid)) continue;
17460
+ const dir = import_node_path3.default.join(root, name);
17461
+ try {
17462
+ const st = (0, import_node_fs5.lstatSync)(dir);
17463
+ if (!st.isDirectory() || now - st.mtimeMs < STALE_MIN_AGE_MS) continue;
17464
+ (0, import_node_fs5.rmSync)(dir, { recursive: true, force: true });
17465
+ removed.push(dir);
17466
+ } catch {
17467
+ }
17468
+ }
17469
+ return removed;
17470
+ }
17471
+ function cleanupSessionStateSync() {
17472
+ for (const session of [...liveSessions]) session.releaseStateSync();
17473
+ }
17474
+ var exitCleanupInstalled = false;
17475
+ function installSessionExitCleanup() {
17476
+ if (exitCleanupInstalled) return;
17477
+ exitCleanupInstalled = true;
17478
+ process.once("exit", cleanupSessionStateSync);
17479
+ const signals = [
17480
+ ["SIGINT", 130],
17481
+ ["SIGTERM", 143],
17482
+ ["SIGHUP", 129]
17483
+ ];
17484
+ for (const [signal, code] of signals) {
17485
+ process.once(signal, () => {
17486
+ cleanupSessionStateSync();
17487
+ if (process.listenerCount(signal) === 0) process.exit(code);
17488
+ });
17489
+ }
17490
+ }
17100
17491
  var FauxnixSession = class {
17101
17492
  id;
17102
17493
  cwd = null;
17103
17494
  env = {};
17104
17495
  /** Exit code of the previous segment — powers bash's `$?`. */
17105
17496
  prevExit = null;
17497
+ /** Per-session private directory holding every state/spool file (#256). */
17498
+ stateDir;
17499
+ stateDirCreated = false;
17106
17500
  cwdFile;
17107
17501
  envFile;
17108
- scriptFile;
17109
17502
  hostFile;
17110
17503
  host = null;
17111
17504
  lifecycleLock = Promise.resolve();
@@ -17113,16 +17506,55 @@ var FauxnixSession = class {
17113
17506
  hasEnvSnapshot = false;
17114
17507
  powerShell;
17115
17508
  constructor() {
17116
- this.id = (0, import_node_crypto.randomUUID)().slice(0, 8);
17509
+ this.id = (0, import_node_crypto2.randomUUID)().slice(0, 8);
17117
17510
  this.powerShell = resolvePowerShell();
17118
17511
  this.bindFiles(this.id);
17119
17512
  }
17120
17513
  bindFiles(id2) {
17121
17514
  this.id = id2;
17122
- this.cwdFile = import_node_path3.default.join(import_node_os2.default.tmpdir(), "fauxnix-" + id2 + "-cwd.txt");
17123
- this.envFile = import_node_path3.default.join(import_node_os2.default.tmpdir(), "fauxnix-" + id2 + "-env.json");
17124
- this.scriptFile = import_node_path3.default.join(import_node_os2.default.tmpdir(), "fauxnix-" + id2 + "-script.ps1");
17125
- this.hostFile = import_node_path3.default.join(import_node_os2.default.tmpdir(), "fauxnix-" + id2 + "-host.ps1");
17515
+ this.stateDir = import_node_path3.default.join(
17516
+ import_node_os2.default.tmpdir(),
17517
+ "fauxnix-" + process.pid + "-" + (0, import_node_crypto2.randomBytes)(12).toString("hex")
17518
+ );
17519
+ this.stateDirCreated = false;
17520
+ this.cwdFile = import_node_path3.default.join(this.stateDir, "cwd.txt");
17521
+ this.envFile = import_node_path3.default.join(this.stateDir, "env.json");
17522
+ this.hostFile = import_node_path3.default.join(this.stateDir, "host.ps1");
17523
+ }
17524
+ /** Paths of this session's private state (diagnostics and tests). */
17525
+ get statePaths() {
17526
+ return { dir: this.stateDir, cwd: this.cwdFile, env: this.envFile, host: this.hostFile };
17527
+ }
17528
+ /** Lazily create the private state directory (owner-only where POSIX modes apply). */
17529
+ ensureStateDir() {
17530
+ if (this.stateDirCreated) return;
17531
+ if (!staleSweepDone) {
17532
+ staleSweepDone = true;
17533
+ sweepStaleStateDirs();
17534
+ }
17535
+ (0, import_node_fs5.mkdirSync)(this.stateDir, { mode: 448 });
17536
+ this.stateDirCreated = true;
17537
+ liveSessions.add(this);
17538
+ }
17539
+ /**
17540
+ * Synchronous, best-effort release for process-exit paths: terminate the
17541
+ * host first (on Windows its open spool/checkpoint handles would make the
17542
+ * delete fail), then remove the directory with retries. The session stays
17543
+ * usable: the next run recreates a directory and a host.
17544
+ */
17545
+ releaseStateSync() {
17546
+ if (this.host) {
17547
+ this.host.killSync();
17548
+ this.host = null;
17549
+ }
17550
+ if (this.stateDirCreated) {
17551
+ try {
17552
+ (0, import_node_fs5.rmSync)(this.stateDir, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });
17553
+ } catch {
17554
+ }
17555
+ this.stateDirCreated = false;
17556
+ }
17557
+ liveSessions.delete(this);
17126
17558
  }
17127
17559
  withLock(fn) {
17128
17560
  const done = this.lifecycleLock.then(fn, fn);
@@ -17153,6 +17585,7 @@ var FauxnixSession = class {
17153
17585
  }
17154
17586
  ensureHost() {
17155
17587
  if (!this.host) {
17588
+ this.ensureStateDir();
17156
17589
  this.host = new PowerShellHost(this.hostFile, () => this.childEnv(), this.powerShell);
17157
17590
  }
17158
17591
  return this.host;
@@ -17182,13 +17615,12 @@ var FauxnixSession = class {
17182
17615
  this.env = {};
17183
17616
  this.hasEnvSnapshot = false;
17184
17617
  this.prevExit = null;
17185
- await Promise.allSettled([
17186
- import_node_fs5.promises.rm(this.cwdFile, { force: true }),
17187
- import_node_fs5.promises.rm(this.envFile, { force: true }),
17188
- import_node_fs5.promises.rm(this.scriptFile, { force: true }),
17189
- import_node_fs5.promises.rm(this.hostFile, { force: true })
17190
- ]);
17191
- this.bindFiles((0, import_node_crypto.randomUUID)().slice(0, 8));
17618
+ if (this.stateDirCreated) {
17619
+ await import_node_fs5.promises.rm(this.stateDir, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 }).catch(() => void 0);
17620
+ this.stateDirCreated = false;
17621
+ }
17622
+ liveSessions.delete(this);
17623
+ this.bindFiles((0, import_node_crypto2.randomUUID)().slice(0, 8));
17192
17624
  }
17193
17625
  /** env for the child powershell process. */
17194
17626
  childEnv(cwdOverride, stdinFile) {
@@ -17602,12 +18034,11 @@ function writeSpoolToPrepFd(fds, file2, target) {
17602
18034
 
17603
18035
  // src/version.ts
17604
18036
  var import_node_fs6 = require("node:fs");
17605
- var import_meta2 = {};
17606
18037
  var bundled = globalThis.__FAUXNIX_VERSION__;
17607
18038
  var version = bundled;
17608
18039
  if (typeof version !== "string") {
17609
18040
  const metadata = JSON.parse(
17610
- (0, import_node_fs6.readFileSync)(new URL("../package.json", import_meta2.url), "utf8")
18041
+ (0, import_node_fs6.readFileSync)(new URL("../package.json", "file://fauxnix-sea/"), "utf8")
17611
18042
  );
17612
18043
  version = metadata.version;
17613
18044
  }
@@ -17765,9 +18196,10 @@ function parseDashC(argv) {
17765
18196
  }
17766
18197
  async function runFacade(argv) {
17767
18198
  trace("argv", argv.join(" "));
18199
+ installSessionExitCleanup();
17768
18200
  const session = new FauxnixSession();
17769
18201
  try {
17770
- if (argv[0] === "--version") {
18202
+ if (argv.some((a) => a === "--version")) {
17771
18203
  process.stdout.write(VERSION_LINE);
17772
18204
  return 0;
17773
18205
  }