@poe-platform/safe-bash 0.1.745 → 0.1.747

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.
Files changed (59) hide show
  1. package/README.md +5 -1
  2. package/dist/image-ast/browser/sharp.d.ts +1 -1
  3. package/dist/image-ast/index.js +133 -35
  4. package/dist/image-ast/sharp.d.ts +1 -1
  5. package/dist/safe-bash/chunks/{chunk-2F7Q532M.js → chunk-4GK4FAT6.js} +3 -3
  6. package/dist/safe-bash/chunks/{chunk-EAUCLWEZ.js → chunk-55AGFLG5.js} +540 -284
  7. package/dist/safe-bash/chunks/{chunk-WCNFCN2G.js → chunk-BS6QFRNX.js} +2 -2
  8. package/dist/safe-bash/chunks/{chunk-IZZ7KX4E.js → chunk-JCXAGOEK.js} +40 -3
  9. package/dist/safe-bash/chunks/{chunk-I3DOFJSJ.js → chunk-MUWJPSGN.js} +2 -2
  10. package/dist/safe-bash/chunks/{chunk-7RP6WOWK.js → chunk-OF2PDE3W.js} +2 -2
  11. package/dist/safe-bash/chunks/{src-FTMTU65U.js → src-T672TQJC.js} +2 -2
  12. package/dist/safe-bash/command-chunks/{chunk-DRCPJVZF.js → chunk-44N2IRVP.js} +17 -5
  13. package/dist/safe-bash/command-chunks/{chunk-LYKC7WJB.js → chunk-6742OVAC.js} +37 -3
  14. package/dist/safe-bash/command-chunks/{chunk-BMBXSLVX.js → chunk-6QU5OLPJ.js} +2 -2
  15. package/dist/safe-bash/command-chunks/{chunk-YHANNN7I.js → chunk-S3BO2NJT.js} +7 -0
  16. package/dist/safe-bash/commands/basic.d.ts +2 -0
  17. package/dist/safe-bash/commands/basic.js +236 -9
  18. package/dist/safe-bash/commands/pr/index.browser.js +1 -1
  19. package/dist/safe-bash/commands/streams.js +9 -56
  20. package/dist/safe-bash/commands/table-text/index.js +5 -1
  21. package/dist/safe-bash/commands/text.js +13 -2
  22. package/dist/safe-bash/commands/time-env/shared.js +2 -2
  23. package/dist/safe-bash/commands/time-env/sleep.js +6 -4
  24. package/dist/safe-bash/commands/timeout/index.d.ts +7 -0
  25. package/dist/safe-bash/commands/timeout/index.js +52 -32
  26. package/dist/safe-bash/commands/timeout/scheduler.js +7 -6
  27. package/dist/safe-bash/core.browser.js +2698 -543
  28. package/dist/safe-bash/opt-in/commands/shuf/random.js +2 -3
  29. package/dist/safe-bash/opt-in/shell/extensions/read/index.js +1 -1
  30. package/dist/safe-bash/opt-in/shell/extensions/trap/index.d.ts +1 -2
  31. package/dist/safe-bash/opt-in/shell/extensions/trap/index.js +1 -8
  32. package/dist/safe-bash/playwright/adapter.d.ts +2 -0
  33. package/dist/safe-bash/playwright/private-target-transport.d.ts +1 -0
  34. package/dist/safe-bash/playwright/private-target-transport.js +21 -21
  35. package/dist/safe-bash/shell/runtime.d.ts +20 -1
  36. package/dist/safe-bash/shell/runtime.js +3021 -532
  37. package/dist/safe-bash/shell/sync-jq-expression.d.ts +6 -0
  38. package/dist/safe-bash/shell/sync-jq-expression.js +46 -0
  39. package/dist/safe-bash-command-cal/index.js +32 -12
  40. package/dist/safe-bash-command-hostname/index.js +22 -7
  41. package/dist/safe-bash-command-id/index.js +28 -9
  42. package/dist/safe-bash-command-pandoc/command.js +1 -1
  43. package/dist/safe-bash-command-pandoc/index.js +1 -1
  44. package/dist/safe-bash-command-ssconvert/command.d.ts +2 -2
  45. package/dist/safe-bash-command-ssconvert/contracts.d.ts +4 -0
  46. package/dist/safe-bash-command-ssconvert/engine.d.ts +2 -2
  47. package/dist/safe-bash-command-ssconvert/index.js +524 -276
  48. package/dist/safe-bash-command-whoami/index.js +26 -12
  49. package/dist/safe-bash-query-engine/index.js +3 -3
  50. package/dist/safe-bash-query-engine/interpreter.js +1 -1
  51. package/dist/safe-bash-query-engine/parser.js +1 -1
  52. package/dist/safe-bash-query-engine/query-core.js +3 -3
  53. package/dist/safe-playwright-cloudflare/browser-private-transport.js +8 -13
  54. package/dist/safe-playwright-cloudflare/browser-storage-control.js +13 -4
  55. package/dist/safe-playwright-cloudflare/browser-trace-archive.js +1 -1
  56. package/package.json +18 -14
  57. package/dist/image-ast/streams/node.d.ts +0 -10
  58. package/dist/image-ast/streams/node.js +0 -5
  59. package/dist/image-ast/streams/web.js +0 -94
@@ -12,7 +12,7 @@ import {
12
12
  parseDate,
13
13
  prCommands,
14
14
  settings
15
- } from "./chunks/chunk-I3DOFJSJ.js";
15
+ } from "./chunks/chunk-MUWJPSGN.js";
16
16
  import {
17
17
  createTsortCommand,
18
18
  createTsortCommands,
@@ -310,7 +310,7 @@ __export(core_browser_exports, {
310
310
  EreSyntaxError: () => errors_exports2.EreSyntaxError,
311
311
  EreUnsupportedError: () => errors_exports2.EreUnsupportedError,
312
312
  EreUsageUnknownError: () => errors_exports2.EreUsageUnknownError,
313
- FsError: () => FsError60,
313
+ FsError: () => FsError61,
314
314
  MdqError: () => MdqError,
315
315
  MemoryFileSystem: () => MemoryFileSystem,
316
316
  MountFileSystem: () => MountFileSystem,
@@ -1310,6 +1310,7 @@ async function parsePrintfDirective(format3, start, signal) {
1310
1310
  }
1311
1311
 
1312
1312
  // packages/safe-bash/src/commands/basic.ts
1313
+ var utf8Encoder = new TextEncoder();
1313
1314
  var defaultEchoExecutors = /* @__PURE__ */ new WeakSet();
1314
1315
  function basicCommands() {
1315
1316
  return [
@@ -1392,7 +1393,7 @@ function basicCommands() {
1392
1393
  await output(context2, result + (parsed.flags.has("z") ? "\0" : "\n"));
1393
1394
  }
1394
1395
  return { exitCode: 0 };
1395
- }),
1396
+ }, 1, 1),
1396
1397
  define("dirname", async (context2) => {
1397
1398
  const parsed = options(context2.args, "z", { zero: "z" });
1398
1399
  requireOperands(parsed.operands);
@@ -1403,7 +1404,7 @@ function basicCommands() {
1403
1404
  await output(context2, parent.slice(0, end) + (parsed.flags.has("z") ? "\0" : "\n"));
1404
1405
  }
1405
1406
  return { exitCode: 0 };
1406
- }),
1407
+ }, 1, 1),
1407
1408
  printfCommand
1408
1409
  ].map((command7) => {
1409
1410
  if (command7.name === "echo") defaultEchoExecutors.add(command7.execute);
@@ -1617,6 +1618,72 @@ function tryFastPrintf(args) {
1617
1618
  offset += 2;
1618
1619
  continue;
1619
1620
  }
1621
+ if (next === 97) {
1622
+ result += "\x07";
1623
+ offset += 2;
1624
+ continue;
1625
+ }
1626
+ if (next === 98) {
1627
+ result += "\b";
1628
+ offset += 2;
1629
+ continue;
1630
+ }
1631
+ if (next === 102) {
1632
+ result += "\f";
1633
+ offset += 2;
1634
+ continue;
1635
+ }
1636
+ if (next === 118) {
1637
+ result += "\v";
1638
+ offset += 2;
1639
+ continue;
1640
+ }
1641
+ if (next === 101 || next === 69) {
1642
+ result += "\x1B";
1643
+ offset += 2;
1644
+ continue;
1645
+ }
1646
+ if (next === 34) {
1647
+ result += '"';
1648
+ offset += 2;
1649
+ continue;
1650
+ }
1651
+ if (next === 39) {
1652
+ result += "'";
1653
+ offset += 2;
1654
+ continue;
1655
+ }
1656
+ if (next >= 48 && next <= 55) {
1657
+ let cur2 = offset + 1;
1658
+ const end = Math.min(format3.length, cur2 + 3);
1659
+ let val = 0;
1660
+ while (cur2 < end && format3.charCodeAt(cur2) >= 48 && format3.charCodeAt(cur2) <= 55) {
1661
+ val = val * 8 + (format3.charCodeAt(cur2++) - 48);
1662
+ }
1663
+ const byte = val & 255;
1664
+ if (byte === 0 || byte >= 128) return void 0;
1665
+ result += String.fromCharCode(byte);
1666
+ offset = cur2;
1667
+ continue;
1668
+ }
1669
+ if (next === 120) {
1670
+ let cur2 = offset + 2;
1671
+ const end = Math.min(format3.length, cur2 + 2);
1672
+ let val = 0;
1673
+ let digits = 0;
1674
+ while (cur2 < end) {
1675
+ const d = format3.charCodeAt(cur2);
1676
+ const n = d >= 48 && d <= 57 ? d - 48 : d >= 65 && d <= 70 ? d - 55 : d >= 97 && d <= 102 ? d - 87 : -1;
1677
+ if (n < 0) break;
1678
+ val = val * 16 + n;
1679
+ digits++;
1680
+ cur2++;
1681
+ }
1682
+ if (digits === 0 || val === 0 || val >= 128) return void 0;
1683
+ result += String.fromCharCode(val);
1684
+ offset = cur2;
1685
+ continue;
1686
+ }
1620
1687
  return void 0;
1621
1688
  }
1622
1689
  if (ch !== 37) {
@@ -1674,12 +1741,29 @@ function tryFastPrintf(args) {
1674
1741
  if (conv === 115 && !zeroPad) {
1675
1742
  const rawVal = args[argument2++] ?? "";
1676
1743
  if (rawVal.includes("\0")) return void 0;
1744
+ let val = rawVal;
1745
+ let valByteLen = rawVal.length;
1677
1746
  if (precision >= 0 || width > 0) {
1678
- for (let i = 0; i < rawVal.length; i++) if (rawVal.charCodeAt(i) >= 128) return void 0;
1747
+ let isAscii = true;
1748
+ for (let i = 0; i < rawVal.length; i++) {
1749
+ if (rawVal.charCodeAt(i) >= 128) {
1750
+ isAscii = false;
1751
+ break;
1752
+ }
1753
+ }
1754
+ if (isAscii) {
1755
+ if (precision >= 0 && precision < rawVal.length) {
1756
+ val = rawVal.slice(0, precision);
1757
+ valByteLen = val.length;
1758
+ }
1759
+ } else if (precision < 0) {
1760
+ valByteLen = utf8Encoder.encode(rawVal).byteLength;
1761
+ } else {
1762
+ return void 0;
1763
+ }
1679
1764
  }
1680
- const val = precision >= 0 ? rawVal.slice(0, precision) : rawVal;
1681
- if (width > val.length) {
1682
- const pad = " ".repeat(width - val.length);
1765
+ if (width > valByteLen) {
1766
+ const pad = " ".repeat(width - valByteLen);
1683
1767
  result += leftAlign ? val + pad : pad + val;
1684
1768
  } else {
1685
1769
  result += val;
@@ -1687,6 +1771,21 @@ function tryFastPrintf(args) {
1687
1771
  offset = cur + 1;
1688
1772
  continue;
1689
1773
  }
1774
+ if (conv === 99 && !zeroPad) {
1775
+ const rawVal = args[argument2++] ?? "";
1776
+ if (rawVal.length === 0) return void 0;
1777
+ const c0 = rawVal.charCodeAt(0);
1778
+ if (c0 === 0 || c0 >= 128) return void 0;
1779
+ const ch0 = rawVal[0];
1780
+ if (width > 1) {
1781
+ const pad = " ".repeat(width - 1);
1782
+ result += leftAlign ? ch0 + pad : pad + ch0;
1783
+ } else {
1784
+ result += ch0;
1785
+ }
1786
+ offset = cur + 1;
1787
+ continue;
1788
+ }
1690
1789
  if (conv === 100 || conv === 105) {
1691
1790
  const rawVal = args[argument2++] ?? "0";
1692
1791
  const val = rawVal.length === 0 ? "0" : rawVal;
@@ -1765,6 +1864,115 @@ function tryFastPrintf(args) {
1765
1864
  } while (argument2 < args.length);
1766
1865
  return result;
1767
1866
  }
1867
+ function extractFastPrintfSpecifiers(format3) {
1868
+ if (format3.length > 256) return void 0;
1869
+ const specs = [];
1870
+ for (let offset = 0; offset < format3.length; ) {
1871
+ const ch = format3.charCodeAt(offset);
1872
+ if (ch === 92) {
1873
+ const next = format3.charCodeAt(offset + 1);
1874
+ if (next === 110 || next === 116 || next === 114 || next === 92 || next === 97 || next === 98 || next === 102 || next === 118 || next === 101 || next === 69 || next === 34 || next === 39) {
1875
+ offset += 2;
1876
+ continue;
1877
+ }
1878
+ if (next >= 48 && next <= 55) {
1879
+ let cur2 = offset + 1;
1880
+ const end = Math.min(format3.length, cur2 + 3);
1881
+ let val = 0;
1882
+ while (cur2 < end && format3.charCodeAt(cur2) >= 48 && format3.charCodeAt(cur2) <= 55) {
1883
+ val = val * 8 + (format3.charCodeAt(cur2++) - 48);
1884
+ }
1885
+ if ((val & 255) === 0 || (val & 255) >= 128) return void 0;
1886
+ offset = cur2;
1887
+ continue;
1888
+ }
1889
+ if (next === 120) {
1890
+ let cur2 = offset + 2;
1891
+ const end = Math.min(format3.length, cur2 + 2);
1892
+ let val = 0;
1893
+ let digits = 0;
1894
+ while (cur2 < end) {
1895
+ const d = format3.charCodeAt(cur2);
1896
+ const n = d >= 48 && d <= 57 ? d - 48 : d >= 65 && d <= 70 ? d - 55 : d >= 97 && d <= 102 ? d - 87 : -1;
1897
+ if (n < 0) break;
1898
+ val = val * 16 + n;
1899
+ digits++;
1900
+ cur2++;
1901
+ }
1902
+ if (digits === 0 || val === 0 || val >= 128) return void 0;
1903
+ offset = cur2;
1904
+ continue;
1905
+ }
1906
+ return void 0;
1907
+ }
1908
+ if (ch !== 37) {
1909
+ offset++;
1910
+ continue;
1911
+ }
1912
+ const spec = format3.charCodeAt(offset + 1);
1913
+ if (spec === 37) {
1914
+ offset += 2;
1915
+ continue;
1916
+ }
1917
+ let cur = offset + 1;
1918
+ let leftAlign = false;
1919
+ let zeroPad = false;
1920
+ while (cur < format3.length) {
1921
+ const fc = format3.charCodeAt(cur);
1922
+ if (fc === 45) {
1923
+ leftAlign = true;
1924
+ cur++;
1925
+ } else if (fc === 48) {
1926
+ zeroPad = true;
1927
+ cur++;
1928
+ } else break;
1929
+ }
1930
+ if (leftAlign) zeroPad = false;
1931
+ let width = 0;
1932
+ while (cur < format3.length) {
1933
+ const dc = format3.charCodeAt(cur);
1934
+ if (dc < 48 || dc > 57) break;
1935
+ width = width * 10 + (dc - 48);
1936
+ if (width > 128) return void 0;
1937
+ cur++;
1938
+ }
1939
+ let precision = -1;
1940
+ if (format3.charCodeAt(cur) === 46) {
1941
+ cur++;
1942
+ precision = 0;
1943
+ while (cur < format3.length) {
1944
+ const dc = format3.charCodeAt(cur);
1945
+ if (dc < 48 || dc > 57) break;
1946
+ precision = precision * 10 + (dc - 48);
1947
+ if (precision > 128) return void 0;
1948
+ cur++;
1949
+ }
1950
+ }
1951
+ const conv = format3.charCodeAt(cur);
1952
+ if (conv === 115 && !zeroPad) {
1953
+ specs.push(precision < 0 ? "s" : "s_prec");
1954
+ offset = cur + 1;
1955
+ continue;
1956
+ }
1957
+ if (conv === 99 && !zeroPad) {
1958
+ specs.push("c");
1959
+ offset = cur + 1;
1960
+ continue;
1961
+ }
1962
+ if (conv === 100 || conv === 105) {
1963
+ specs.push("d");
1964
+ offset = cur + 1;
1965
+ continue;
1966
+ }
1967
+ if (conv === 120 || conv === 88 || conv === 111 || conv === 117) {
1968
+ specs.push("u");
1969
+ offset = cur + 1;
1970
+ continue;
1971
+ }
1972
+ return void 0;
1973
+ }
1974
+ return specs;
1975
+ }
1768
1976
  var printfCommand = define("printf", formatPrintf, 1, 1);
1769
1977
 
1770
1978
  // packages/safe-bash/src/commands/filesystem.ts
@@ -7759,7 +7967,7 @@ async function executeHeadTailSlow(name2, maxTailFollowHandles, context2) {
7759
7967
  }
7760
7968
  function headTail(name2, maxTailFollowHandles = Infinity) {
7761
7969
  return define(name2, (context2) => {
7762
- if (name2 === "head" || name2 === "tail") {
7970
+ if (name2 === "head") {
7763
7971
  const a = context2.args;
7764
7972
  let fastCount = -1;
7765
7973
  if (a.length === 0) {
@@ -7790,55 +7998,13 @@ function headTail(name2, maxTailFollowHandles = Infinity) {
7790
7998
  fastCount = n;
7791
7999
  }
7792
8000
  if (fastCount >= 0) {
7793
- if (name2 === "head") {
7794
- (0, command_requirements_exports.assertCommandRequirements)(context2, inspectedInputRequirements, STDIN_REQUIREMENT_MODES);
7795
- try {
7796
- const p = prefixSyncOrAsync(context2, input(context2, "-"), fastCount, false, false, 10);
7797
- if (p === void 0) return RESOLVED_EXIT_ZERO;
7798
- return finishHeadTailPromise(context2, p);
7799
- } catch (error) {
7800
- return diagnostic(context2, error).then(RETURN_EXIT_ONE);
7801
- }
7802
- } else {
7803
- const req = assertInputRequirements(context2, SINGLE_STDIN_OPERAND);
7804
- if (!req) {
7805
- (0, command_requirements_exports.assertCommandRequirements)(context2, inspectedInputRequirements, STDIN_REQUIREMENT_MODES);
7806
- const iter = input(context2, "-")[Symbol.asyncIterator]();
7807
- if (typeof iter.tryNextSync === "function") {
7808
- try {
7809
- const res1 = iter.tryNextSync();
7810
- if (res1 !== void 0) {
7811
- if (res1.done) return RESOLVED_EXIT_ZERO;
7812
- const chunk = res1.value;
7813
- const res2 = iter.tryNextSync();
7814
- if (res2 !== void 0 && res2.done && chunk.length <= bufferLimit) {
7815
- if (fastCount === 0 || chunk.length === 0) return RESOLVED_EXIT_ZERO;
7816
- let pos = chunk[chunk.length - 1] === 10 ? chunk.length - 2 : chunk.length - 1;
7817
- let startIdx = 0;
7818
- for (let rem = fastCount; rem > 0; rem--) {
7819
- if (pos < 0) {
7820
- startIdx = 0;
7821
- break;
7822
- }
7823
- const nl = chunk.lastIndexOf(10, pos);
7824
- if (nl === -1) {
7825
- startIdx = 0;
7826
- break;
7827
- }
7828
- startIdx = nl + 1;
7829
- pos = nl - 1;
7830
- }
7831
- const slice = startIdx === 0 ? chunk : chunk.subarray(startIdx);
7832
- const p = output(context2, slice);
7833
- if (isSyncResolved(p)) return RESOLVED_EXIT_ZERO;
7834
- return finishHeadTailPromise(context2, p);
7835
- }
7836
- }
7837
- } catch (error) {
7838
- return diagnostic(context2, error).then(RETURN_EXIT_ONE);
7839
- }
7840
- }
7841
- }
8001
+ (0, command_requirements_exports.assertCommandRequirements)(context2, inspectedInputRequirements, STDIN_REQUIREMENT_MODES);
8002
+ try {
8003
+ const p = prefixSyncOrAsync(context2, input(context2, "-"), fastCount, false, false, 10);
8004
+ if (p === void 0) return RESOLVED_EXIT_ZERO;
8005
+ return finishHeadTailPromise(context2, p);
8006
+ } catch (error) {
8007
+ return diagnostic(context2, error).then(RETURN_EXIT_ONE);
7842
8008
  }
7843
8009
  }
7844
8010
  }
@@ -10685,6 +10851,7 @@ async function executeUniqGeneral(context2, preReadSource) {
10685
10851
  const onlyRepeated = parsed.flags.has("d");
10686
10852
  const onlyUnique = parsed.flags.has("u");
10687
10853
  const identityKey = skipFields === 0 && skipCharacters === 0 && width === Infinity && !ignoreCase;
10854
+ const uniqDecoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
10688
10855
  const key = (bytes2) => {
10689
10856
  if (identityKey) return bytes2;
10690
10857
  let offset = 0;
@@ -10692,8 +10859,15 @@ async function executeUniqGeneral(context2, preReadSource) {
10692
10859
  while (offset < bytes2.length && (bytes2[offset] === 32 || bytes2[offset] === 9)) offset++;
10693
10860
  while (offset < bytes2.length && bytes2[offset] !== 32 && bytes2[offset] !== 9) offset++;
10694
10861
  }
10695
- offset += skipCharacters;
10696
- const result = bytes2.subarray(offset, width === Infinity ? void 0 : offset + width);
10862
+ let result;
10863
+ try {
10864
+ const chars = Array.from(uniqDecoder.decode(bytes2.subarray(offset)));
10865
+ result = encoder.encode((width === Infinity ? chars.slice(skipCharacters) : chars.slice(skipCharacters, skipCharacters + width)).join(""));
10866
+ } catch (error) {
10867
+ if (!(error instanceof TypeError)) throw error;
10868
+ offset += skipCharacters;
10869
+ result = bytes2.subarray(offset, width === Infinity ? void 0 : offset + width);
10870
+ }
10697
10871
  return ignoreCase ? fold(result) : result;
10698
10872
  };
10699
10873
  const records5 = (async function* () {
@@ -44261,7 +44435,9 @@ function createJoinCommand(factory = {}) {
44261
44435
  // packages/safe-bash/src/commands/table-text/index.ts
44262
44436
  function createTableTextCommands(options2 = {}) {
44263
44437
  settings4(options2);
44264
- return [createPasteCommand(options2), createCommCommand(options2), createJoinCommand(options2)];
44438
+ const defs = [createPasteCommand(options2), createCommCommand(options2), createJoinCommand(options2)];
44439
+ for (let i = 0; i < defs.length; i++) builtInDirectContextExecutors.add(defs[i].execute);
44440
+ return defs;
44265
44441
  }
44266
44442
  function tableTextCommands(options2 = {}) {
44267
44443
  const commands = createTableTextCommands(options2);
@@ -47323,7 +47499,8 @@ function delay(milliseconds, signal, configuration) {
47323
47499
  let handle;
47324
47500
  let armed = false;
47325
47501
  let settled = false;
47326
- let started;
47502
+ let remaining = milliseconds;
47503
+ let step = 0;
47327
47504
  let previous;
47328
47505
  const finish = (failed, reason) => {
47329
47506
  if (settled) return;
@@ -47350,20 +47527,17 @@ function delay(milliseconds, signal, configuration) {
47350
47527
  if (!Number.isFinite(now) || Math.abs(now) > Number.MAX_SAFE_INTEGER || previous !== void 0 && now < previous) {
47351
47528
  throw new RangeError("sleep scheduler must supply finite monotonic milliseconds");
47352
47529
  }
47353
- started ??= now;
47530
+ if (previous !== void 0) remaining -= Math.max(step, now - previous);
47354
47531
  previous = now;
47355
- const remaining = milliseconds - (now - started);
47356
47532
  if (remaining <= 0) {
47357
47533
  finish(false);
47358
47534
  return;
47359
47535
  }
47360
- const timer = scheduler.setTimeout(
47361
- () => {
47362
- armed = false;
47363
- schedule();
47364
- },
47365
- Math.min(configuration.maxTimerMilliseconds, Math.max(1, Math.ceil(remaining)))
47366
- );
47536
+ step = Math.min(2147483647, configuration.maxTimerMilliseconds, Math.max(1, Math.ceil(remaining)));
47537
+ const timer = scheduler.setTimeout(() => {
47538
+ armed = false;
47539
+ schedule();
47540
+ }, step);
47367
47541
  if (settled) scheduler.clearTimeout(timer);
47368
47542
  else {
47369
47543
  handle = timer;
@@ -48173,7 +48347,7 @@ var FileFailure = class extends Error {
48173
48347
  };
48174
48348
  var FileLimitError = class extends FileFailure {
48175
48349
  };
48176
- var utf8Encoder = new TextEncoder();
48350
+ var utf8Encoder2 = new TextEncoder();
48177
48351
  var printableAsciiNoBackslash = /^[\x20-\x5b\x5d-\x7e]*$/;
48178
48352
  var hostAbortWaiters = /* @__PURE__ */ new WeakMap();
48179
48353
  function subscribeHostAbort(signal, fn) {
@@ -48297,7 +48471,7 @@ var SharedBudget = class {
48297
48471
  const size = import_buffer.Buffer.byteLength(text3);
48298
48472
  this.check(size, this.limits.maxOutputBytes - this.outputBytes, "output");
48299
48473
  this.outputBytes += size;
48300
- const bytes2 = utf8Encoder.encode(text3);
48474
+ const bytes2 = utf8Encoder2.encode(text3);
48301
48475
  const width = Math.min(16384, this.limits.maxChunkBytes);
48302
48476
  for (let offset = 0; offset < bytes2.length; offset += width) {
48303
48477
  await (0, contracts_exports.writeBytes)(sink, bytes2.slice(offset, offset + width), signal);
@@ -48318,7 +48492,7 @@ var SharedBudget = class {
48318
48492
  bounded2 += character;
48319
48493
  }
48320
48494
  this.outputBytes += size;
48321
- const bytes2 = utf8Encoder.encode(bounded2);
48495
+ const bytes2 = utf8Encoder2.encode(bounded2);
48322
48496
  const width = Math.min(16384, this.limits.maxChunkBytes);
48323
48497
  for (let offset = 0; offset < bytes2.length; offset += width) {
48324
48498
  await (0, contracts_exports.writeBytes)(this.context.stderr, bytes2.slice(offset, offset + width), this.signal);
@@ -51707,7 +51881,7 @@ Traversal and output limits apply; adapters may have their own side effects.
51707
51881
 
51708
51882
  // packages/safe-bash/src/commands/du/budget.ts
51709
51883
  init_platform();
51710
- var utf8Encoder2 = new TextEncoder();
51884
+ var utf8Encoder3 = new TextEncoder();
51711
51885
  var DuLimitError = class extends contracts_exports.FsError {
51712
51886
  constructor(label) {
51713
51887
  super("EFBIG", { message: `du ${label} limit exceeded` });
@@ -51839,7 +52013,7 @@ var Budget24 = class {
51839
52013
  const size = import_buffer.Buffer.byteLength(text3);
51840
52014
  this.check(size, this.limits.maxOutputBytes - this.output, "output", signal);
51841
52015
  this.output += size;
51842
- const bytes2 = utf8Encoder2.encode(text3);
52016
+ const bytes2 = utf8Encoder3.encode(text3);
51843
52017
  const ioSignal = signal === this.caller.signal ? this.ioSignal : this.outputSignal ??= AbortSignal.any([signal, this.cancellation.signal]);
51844
52018
  for (let offset = 0; offset < bytes2.length; offset += 16384) {
51845
52019
  this.active(signal);
@@ -53073,9 +53247,9 @@ function parseDuration(token) {
53073
53247
  init_platform();
53074
53248
  var defaultSchedulerBinding = Object.freeze({
53075
53249
  receiver: globalThis,
53076
- now: globalThis.performance.now.bind(globalThis.performance),
53077
- setTimeout: globalThis.setTimeout.bind(globalThis),
53078
- clearTimeout: globalThis.clearTimeout.bind(globalThis)
53250
+ now: () => globalThis.performance.now(),
53251
+ setTimeout: (callback, milliseconds) => globalThis.setTimeout(callback, milliseconds),
53252
+ clearTimeout: (handle) => globalThis.clearTimeout(handle)
53079
53253
  });
53080
53254
  function clock(binding, previous) {
53081
53255
  const sample = Reflect.apply(binding.now, binding.receiver, []);
@@ -53092,6 +53266,7 @@ function createDeadline(binding, duration2, maximumChunk, cancel = true) {
53092
53266
  let expired = false;
53093
53267
  let remaining = duration2;
53094
53268
  let previous = 0;
53269
+ let step = 0;
53095
53270
  let handle;
53096
53271
  let handleLive = false;
53097
53272
  let cleanupFailed = false;
@@ -53120,8 +53295,8 @@ function createDeadline(binding, duration2, maximumChunk, cancel = true) {
53120
53295
  controller.abort(timerFailureReason);
53121
53296
  };
53122
53297
  const arm = () => {
53123
- const milliseconds = Math.min(maximumChunk, Math.max(1, Math.ceil(remaining)));
53124
- handle = Reflect.apply(binding.setTimeout, binding.receiver, [wake, milliseconds]);
53298
+ step = Math.min(2147483647, maximumChunk, Math.max(1, Math.ceil(remaining)));
53299
+ handle = Reflect.apply(binding.setTimeout, binding.receiver, [wake, step]);
53125
53300
  handleLive = true;
53126
53301
  };
53127
53302
  const wake = () => {
@@ -53133,7 +53308,7 @@ function createDeadline(binding, duration2, maximumChunk, cancel = true) {
53133
53308
  failTimer();
53134
53309
  return;
53135
53310
  }
53136
- remaining -= sample - previous;
53311
+ remaining -= Math.max(step, sample - previous);
53137
53312
  previous = sample;
53138
53313
  if (remaining <= 0) {
53139
53314
  admissionOpen = false;
@@ -53198,6 +53373,16 @@ function optionsObject(value2) {
53198
53373
  }
53199
53374
  function settings15(value2, includeReplace) {
53200
53375
  const options2 = optionsObject(value2);
53376
+ const configuredLimits = optionsObject(options2?.limits);
53377
+ const limits = {
53378
+ maxArguments: Infinity,
53379
+ maxArgumentBytes: Infinity,
53380
+ maxOutputBytes: Infinity,
53381
+ ...configuredLimits
53382
+ };
53383
+ for (const [name2, limit] of Object.entries(limits)) {
53384
+ if (limit !== Infinity && (!Number.isSafeInteger(limit) || limit < 1)) throw new RangeError(`Invalid timeout limit: ${name2}`);
53385
+ }
53201
53386
  const killAfterPolicy = options2?.killAfterPolicy;
53202
53387
  if (killAfterPolicy !== void 0 && typeof killAfterPolicy !== "function") throw new TypeError("Timeout killAfterPolicy must be a function");
53203
53388
  const invokeValue = options2?.invoke;
@@ -53223,8 +53408,8 @@ function settings15(value2, includeReplace) {
53223
53408
  }
53224
53409
  const maximum = options2?.maxTimerMilliseconds;
53225
53410
  if (maximum !== void 0 && typeof maximum !== "number") throw new TypeError("Timeout maxTimerMilliseconds must be a number");
53226
- if (maximum !== void 0 && (!Number.isInteger(maximum) || maximum < 1 || maximum > 2147483647)) {
53227
- throw new RangeError("Timeout maxTimerMilliseconds must be an integer from 1 through 2147483647");
53411
+ if (maximum !== void 0 && maximum !== Infinity && (!Number.isInteger(maximum) || maximum < 1 || maximum > 2147483647)) {
53412
+ throw new RangeError("Timeout maxTimerMilliseconds must be an integer from 1 through 2147483647 or Infinity");
53228
53413
  }
53229
53414
  let replace = false;
53230
53415
  if (includeReplace) {
@@ -53232,9 +53417,10 @@ function settings15(value2, includeReplace) {
53232
53417
  if (configured !== void 0 && typeof configured !== "boolean") throw new TypeError("Timeout replace must be a boolean");
53233
53418
  replace = configured ?? false;
53234
53419
  }
53235
- return { invoke, killAfterPolicy, scheduler: binding, maxTimerMilliseconds: maximum ?? 2147483647, replace };
53420
+ return { limits, invoke, killAfterPolicy, scheduler: binding, maxTimerMilliseconds: maximum ?? 2147483647, replace };
53236
53421
  }
53237
- async function status(context2, bytes2, exitCode, stdout = false) {
53422
+ async function status(configuration, context2, bytes2, exitCode, stdout = false) {
53423
+ if (bytes2.length > configuration.limits.maxOutputBytes) throw new contracts_exports.FsError("EFBIG", { message: "timeout output limit exceeded" });
53238
53424
  await (0, contracts_exports.writeBytes)(stdout ? context2.stdout : context2.stderr, bytes2, context2.signal);
53239
53425
  return { exitCode };
53240
53426
  }
@@ -53250,7 +53436,16 @@ function definition2(configuration) {
53250
53436
  name: "timeout",
53251
53437
  description: "Run a virtual command with a cooperative time limit",
53252
53438
  async execute(context2) {
53439
+ context2.signal.throwIfAborted();
53253
53440
  const originalArgs = context2.args;
53441
+ if (originalArgs.length > configuration.limits.maxArguments) throw new contracts_exports.FsError("EFBIG", { message: "timeout argument count limit exceeded" });
53442
+ const suppliedValues = "argumentValues" in context2 ? context2.argumentValues : void 0;
53443
+ const ownedArguments = suppliedValues === void 0 ? void 0 : (0, contracts_exports.getCommandArguments)(context2);
53444
+ let argumentBytes = 0;
53445
+ for (const argument2 of ownedArguments?.values ?? originalArgs) {
53446
+ argumentBytes += shellValueByteLength(argument2);
53447
+ if (argumentBytes > configuration.limits.maxArgumentBytes) throw new contracts_exports.FsError("EFBIG", { message: "timeout argument limit exceeded" });
53448
+ }
53254
53449
  let offset = 0;
53255
53450
  let preserveStatus = false;
53256
53451
  let verbose2 = false;
@@ -53263,8 +53458,8 @@ function definition2(configuration) {
53263
53458
  offset++;
53264
53459
  break;
53265
53460
  }
53266
- if (token === "--help") return status(context2, records3.help, 0, true);
53267
- if (token === "--version") return status(context2, records3.version, 0, true);
53461
+ if (token === "--help") return status(configuration, context2, records3.help, 0, true);
53462
+ if (token === "--version") return status(configuration, context2, records3.version, 0, true);
53268
53463
  if (token === "-" || !token.startsWith("-")) break;
53269
53464
  if (token === "--verbose") {
53270
53465
  verbose2 = true;
@@ -53283,19 +53478,19 @@ function definition2(configuration) {
53283
53478
  }
53284
53479
  if (token === "--kill-after" || token.startsWith("--kill-after=")) {
53285
53480
  const duration2 = token === "--kill-after" ? originalArgs[++offset] : token.slice(13);
53286
- if (duration2 === void 0) return status(context2, records3.missingDuration, 125);
53481
+ if (duration2 === void 0) return status(configuration, context2, records3.missingDuration, 125);
53287
53482
  const killAfter = parseDuration(duration2);
53288
- if (killAfter.kind === "invalid") return status(context2, records3.invalidDuration, 125);
53289
- if (killAfter.kind === "overflow") return status(context2, records3.durationOverflow, 125);
53483
+ if (killAfter.kind === "invalid") return status(configuration, context2, records3.invalidDuration, 125);
53484
+ if (killAfter.kind === "overflow") return status(configuration, context2, records3.durationOverflow, 125);
53290
53485
  killAfterMilliseconds = killAfter.milliseconds;
53291
53486
  offset++;
53292
53487
  continue;
53293
53488
  }
53294
53489
  if (token === "--signal" || token.startsWith("--signal=")) {
53295
53490
  const signalToken = token === "--signal" ? originalArgs[++offset] : token.slice(9);
53296
- if (signalToken === void 0) return status(context2, records3.invalidSignal, 125);
53491
+ if (signalToken === void 0) return status(configuration, context2, records3.invalidSignal, 125);
53297
53492
  const parsedSignal = parseSignal(signalToken);
53298
- if (parsedSignal === void 0) return status(context2, records3.invalidSignal, 125);
53493
+ if (parsedSignal === void 0) return status(configuration, context2, records3.invalidSignal, 125);
53299
53494
  signalNumber = parsedSignal;
53300
53495
  offset++;
53301
53496
  continue;
@@ -53321,37 +53516,36 @@ function definition2(configuration) {
53321
53516
  }
53322
53517
  if (flag === "k") {
53323
53518
  const duration2 = token.slice(position + 1) || originalArgs[++offset];
53324
- if (duration2 === void 0) return status(context2, records3.missingDuration, 125);
53519
+ if (duration2 === void 0) return status(configuration, context2, records3.missingDuration, 125);
53325
53520
  const killAfter = parseDuration(duration2);
53326
- if (killAfter.kind === "invalid") return status(context2, records3.invalidDuration, 125);
53327
- if (killAfter.kind === "overflow") return status(context2, records3.durationOverflow, 125);
53521
+ if (killAfter.kind === "invalid") return status(configuration, context2, records3.invalidDuration, 125);
53522
+ if (killAfter.kind === "overflow") return status(configuration, context2, records3.durationOverflow, 125);
53328
53523
  killAfterMilliseconds = killAfter.milliseconds;
53329
53524
  break;
53330
53525
  }
53331
53526
  if (flag === "s") {
53332
53527
  const signalToken = token.slice(position + 1) || originalArgs[++offset];
53333
- if (signalToken === void 0) return status(context2, records3.invalidSignal, 125);
53528
+ if (signalToken === void 0) return status(configuration, context2, records3.invalidSignal, 125);
53334
53529
  const parsedSignal = parseSignal(signalToken);
53335
- if (parsedSignal === void 0) return status(context2, records3.invalidSignal, 125);
53530
+ if (parsedSignal === void 0) return status(configuration, context2, records3.invalidSignal, 125);
53336
53531
  signalNumber = parsedSignal;
53337
53532
  break;
53338
53533
  }
53339
- return status(context2, records3.invalidOption, 125);
53534
+ return status(configuration, context2, records3.invalidOption, 125);
53340
53535
  }
53341
53536
  offset++;
53342
53537
  continue;
53343
53538
  }
53344
- return status(context2, records3.invalidOption, 125);
53539
+ return status(configuration, context2, records3.invalidOption, 125);
53345
53540
  }
53346
53541
  const durationToken = originalArgs[offset];
53347
- if (durationToken === void 0) return status(context2, records3.missingDuration, 125);
53542
+ if (durationToken === void 0) return status(configuration, context2, records3.missingDuration, 125);
53348
53543
  const parsed = parseDuration(durationToken);
53349
- if (parsed.kind === "invalid") return status(context2, records3.invalidDuration, 125);
53350
- if (parsed.kind === "overflow") return status(context2, records3.durationOverflow, 125);
53544
+ if (parsed.kind === "invalid") return status(configuration, context2, records3.invalidDuration, 125);
53545
+ if (parsed.kind === "overflow") return status(configuration, context2, records3.durationOverflow, 125);
53351
53546
  const command7 = originalArgs[offset + 1];
53352
- if (command7 === void 0) return status(context2, records3.missingCommand, 125);
53353
- const suppliedValues = "argumentValues" in context2 ? context2.argumentValues : void 0;
53354
- const argumentValues = suppliedValues === void 0 ? void 0 : (0, contracts_exports.getCommandArguments)({ args: originalArgs, argumentValues: suppliedValues }).slice(offset + 2);
53547
+ if (command7 === void 0) return status(configuration, context2, records3.missingCommand, 125);
53548
+ const argumentValues = ownedArguments?.slice(offset + 2);
53355
53549
  const args = argumentValues?.args ?? Object.freeze(originalArgs.slice(offset + 2));
53356
53550
  const streams = {
53357
53551
  ...argumentValues === void 0 ? {} : { argumentValues },
@@ -53363,7 +53557,7 @@ function definition2(configuration) {
53363
53557
  const killAfterPolicy = configuration.killAfterPolicy ?? context2.capabilities?.timeoutKillAfterPolicy;
53364
53558
  if (killAfterMilliseconds !== void 0 && killAfterMilliseconds !== 0 && parsed.milliseconds !== 0 && parsed.milliseconds !== Infinity) {
53365
53559
  context2.signal.throwIfAborted();
53366
- if (typeof killAfterPolicy !== "function") return status(context2, records3.escalationUnavailable, 125);
53560
+ if (typeof killAfterPolicy !== "function") return status(configuration, context2, records3.escalationUnavailable, 125);
53367
53561
  let result2;
53368
53562
  try {
53369
53563
  result2 = await killAfterPolicy(context2, command7, args, { signal: context2.signal, ...streams }, Object.freeze({
@@ -53383,7 +53577,7 @@ function definition2(configuration) {
53383
53577
  }
53384
53578
  const selected2 = childInvoker(context2, configuration.invoke);
53385
53579
  if (parsed.milliseconds === 0 || parsed.milliseconds === Infinity) {
53386
- if (selected2 === void 0) return status(context2, records3.invokeUnavailable, 125);
53580
+ if (selected2 === void 0) return status(configuration, context2, records3.invokeUnavailable, 125);
53387
53581
  context2.signal.throwIfAborted();
53388
53582
  let result2;
53389
53583
  try {
@@ -53395,7 +53589,7 @@ function definition2(configuration) {
53395
53589
  context2.signal.throwIfAborted();
53396
53590
  return result2;
53397
53591
  }
53398
- if (selected2 === void 0) return status(context2, records3.invokeUnavailable, 125);
53592
+ if (selected2 === void 0) return status(configuration, context2, records3.invokeUnavailable, 125);
53399
53593
  context2.signal.throwIfAborted();
53400
53594
  const deadline = createDeadline(configuration.scheduler, parsed.milliseconds, configuration.maxTimerMilliseconds, signalNumber !== 0);
53401
53595
  context2.registerCleanup?.(deadline.retire);
@@ -53412,7 +53606,7 @@ function definition2(configuration) {
53412
53606
  }
53413
53607
  context2.signal.throwIfAborted();
53414
53608
  if (retirementFailed2) throw retirementFailure2;
53415
- return status(context2, records3.timerSetupFailed, 125);
53609
+ return status(configuration, context2, records3.timerSetupFailed, 125);
53416
53610
  }
53417
53611
  let returned = false;
53418
53612
  let result;
@@ -53435,11 +53629,11 @@ function definition2(configuration) {
53435
53629
  if (!returned && invocationFailure !== deadline.deadlineReason && invocationFailure !== deadline.timerFailureReason) throw invocationFailure;
53436
53630
  if (retirementFailed) throw retirementFailure;
53437
53631
  if (verbose2 && deadline.expired) {
53438
- await (0, contracts_exports.writeBytes)(context2.stderr, encoder4.encode(`timeout: cooperative deadline expired for command \u2018${command7}\u2019
53439
- `), context2.signal);
53632
+ await status(configuration, context2, encoder4.encode(`timeout: cooperative deadline expired for command \u2018${command7}\u2019
53633
+ `), 0);
53440
53634
  }
53441
53635
  if (!returned && invocationFailure === deadline.deadlineReason) return { exitCode: signalNumber === 9 || preserveStatus ? 128 + signalNumber : 124 };
53442
- if (deadline.signal.aborted && deadline.signal.reason === deadline.timerFailureReason) return status(context2, records3.timerSetupFailed, 125);
53636
+ if (deadline.signal.aborted && deadline.signal.reason === deadline.timerFailureReason) return status(configuration, context2, records3.timerSetupFailed, 125);
53443
53637
  if (deadline.expired && (!preserveStatus || signalNumber === 9)) return { exitCode: signalNumber === 9 ? 137 : 124 };
53444
53638
  return result;
53445
53639
  }
@@ -59919,6 +60113,47 @@ var ShellInput = class _ShellInput {
59919
60113
  // packages/safe-bash/src/shell/runtime.ts
59920
60114
  init_platform();
59921
60115
 
60116
+ // packages/safe-bash/src/shell/sync-jq-expression.ts
60117
+ init_platform();
60118
+ function splitSyncJqExpression(expression, separator) {
60119
+ const parts = [];
60120
+ const stack = [];
60121
+ let quoted2 = false;
60122
+ let escaped3 = false;
60123
+ let start = 0;
60124
+ let wrapped = expression.startsWith("(");
60125
+ for (let i = 0; i < expression.length; i++) {
60126
+ const ch = expression[i];
60127
+ if (quoted2) {
60128
+ if (escaped3) escaped3 = false;
60129
+ else if (ch === "\\") escaped3 = true;
60130
+ else if (ch === '"') quoted2 = false;
60131
+ continue;
60132
+ }
60133
+ if (ch === '"') {
60134
+ quoted2 = true;
60135
+ continue;
60136
+ }
60137
+ if (ch === "(" || ch === "[" || ch === "{") {
60138
+ stack.push(ch === "(" ? ")" : ch === "[" ? "]" : "}");
60139
+ continue;
60140
+ }
60141
+ if (ch === ")" || ch === "]" || ch === "}") {
60142
+ if (stack.pop() !== ch) return void 0;
60143
+ if (stack.length === 0 && i !== expression.length - 1) wrapped = false;
60144
+ continue;
60145
+ }
60146
+ if (stack.length === 0 && expression.startsWith(separator, i)) {
60147
+ parts.push(expression.slice(start, i).trim());
60148
+ i += separator.length - 1;
60149
+ start = i + 1;
60150
+ }
60151
+ }
60152
+ if (quoted2 || stack.length > 0) return void 0;
60153
+ parts.push(expression.slice(start).trim());
60154
+ return { parts, wrapped };
60155
+ }
60156
+
59922
60157
  // packages/safe-bash/src/worker/runtime-context.ts
59923
60158
  init_platform();
59924
60159
  var shellDescriptorAdmissions = /* @__PURE__ */ new WeakMap();
@@ -69552,6 +69787,12 @@ var closedSource = { [Symbol.asyncIterator]() {
69552
69787
  };
69553
69788
  return iterator;
69554
69789
  } };
69790
+ var syncAwkArithAtom = `(?:\\$(?:[0-9]+|NF)|NR|NF|-?[0-9]+(?:\\.[0-9]+)?|[a-zA-Z_][a-zA-Z0-9_]*)`;
69791
+ var syncAwkArithPat = `(?:${syncAwkArithAtom}(?:\\s*[+*\\/%-]\\s*${syncAwkArithAtom})+)`;
69792
+ var syncAwkTernaryPat = `(?:(?:\\$(?:[0-9]+|NF)|NR|NF)\\s*(?:==|!=|>=|<=|>|<)\\s*(?:-?[0-9]+(?:\\.[0-9]+)?|"[^"$\\\\]*")\\s*\\?\\s*(?:\\$(?:[0-9]+|NF)|"[^"$\\\\]*"|-?[0-9]+(?:\\.[0-9]+)?)\\s*:\\s*(?:\\$(?:[0-9]+|NF)|"[^"$\\\\]*"|-?[0-9]+(?:\\.[0-9]+)?))`;
69793
+ var syncAwkItemPat = `(?:${syncAwkTernaryPat}|int\\(\\$(?:[0-9]+|NF)\\)|(?:toupper|tolower)\\(\\$(?:[0-9]+|NF)\\)|substr\\(\\$(?:[0-9]+|NF)\\s*,\\s*[0-9]+(?:\\s*,\\s*[0-9]+)?\\)|index\\(\\$(?:[0-9]+|NF)\\s*,\\s*"[^"$\\\\]*"\\)|${syncAwkArithPat}|\\$(?:[0-9]+|NF)|\\$\\(NF\\s*-\\s*[0-9]+\\)|length(?:\\(\\$(?:[0-9]+|NF)\\))?|NR|NF|[a-zA-Z_][a-zA-Z0-9_]*|"[^"$\\\\]*")`;
69794
+ var syncAwkPrintRe = new RegExp(`^\\{\\s*(?:(g?sub)\\(\\s*\\/(\\^?[a-zA-Z0-9_ :;,=-]+\\$?)\\/\\s*,\\s*"([^"\\\\]*)"(?:\\s*,\\s*\\$([0-9]+|NF))?\\s*\\)\\s*;\\s*)?(?:print(?:\\s+(${syncAwkItemPat}(?:\\s*,?\\s*${syncAwkItemPat})*))?|printf\\s+"([^"$\\\\]*(?:\\\\[nt\\\\"][^"$\\\\]*)*)"\\s*,\\s*(${syncAwkItemPat}(?:\\s*,\\s*${syncAwkItemPat})*))\\s*;?\\s*\\}\\s*$`);
69795
+ var syncAwkTokenRe = new RegExp(`(${syncAwkTernaryPat})|int\\(\\$([0-9]+|NF)\\)|(toupper|tolower)\\(\\$([0-9]+|NF)\\)|substr\\(\\$([0-9]+|NF)\\s*,\\s*([0-9]+)(?:\\s*,\\s*([0-9]+))?\\)|index\\(\\$([0-9]+|NF)\\s*,\\s*"([^"$\\\\]*)"\\)|(${syncAwkArithPat})|\\$\\(NF\\s*-\\s*([0-9]+)\\)|\\$([0-9]+|NF)|length\\b(?:\\(\\$([0-9]+|NF)\\))?|(NR|NF)\\b|"([^"$\\\\]*)"|([a-zA-Z_][a-zA-Z0-9_]*)|(,)`, "g");
69555
69796
  var RuntimeCancellationState = class {
69556
69797
  _records;
69557
69798
  _diagnostics;
@@ -69848,7 +70089,7 @@ function hasGlobOrEscape(text3, extglob = false) {
69848
70089
  var nextProcessSubstitutionId = 0;
69849
70090
  var defaultRuntimeMuscleMemoryMap;
69850
70091
  function getRuntimeMuscleMemoryCommand(name2) {
69851
- defaultRuntimeMuscleMemoryMap ??= new Map([...(0, bc_exports.createBcCommands)(), ...(0, sponge_exports.createSpongeCommands)(), ...(0, fd_exports.createFdCommands)(), ...(0, less_exports.createLessCommands)(), ...(0, id_exports.createIdCommands)(), ...(0, whoami_exports.createWhoamiCommands)(), ...(0, uname_exports.createUnameCommands)(), ...(0, hostname_exports.createHostnameCommands)(), ...(0, nproc_exports.createNprocCommands)(), ...createShufCommands2(), ...createDdCommands2(), ...(0, numfmt_exports.createNumfmtCommands)(), ...(0, envsubst_exports.createEnvsubstCommands)(), ...(0, cal_exports.createCalCommands)(), ...(0, pathchk_exports.createPathchkCommands)(), ...(0, getconf_exports.createGetconfCommands)(), ...(0, locale_exports.createLocaleCommands)(), ...(0, df_exports.createDfCommands)(), ...(0, sqlite3_exports.createSqlite3Commands)()].map((cmd) => [cmd.name, cmd]));
70092
+ defaultRuntimeMuscleMemoryMap ??= new Map([...createStreamFormatCommands(), ...createStreamInspectionCommands(), ...(0, bc_exports.createBcCommands)(), ...(0, sponge_exports.createSpongeCommands)(), ...(0, fd_exports.createFdCommands)(), ...(0, less_exports.createLessCommands)(), ...(0, id_exports.createIdCommands)(), ...(0, whoami_exports.createWhoamiCommands)(), ...(0, uname_exports.createUnameCommands)(), ...(0, hostname_exports.createHostnameCommands)(), ...(0, nproc_exports.createNprocCommands)(), ...createShufCommands2(), ...createDdCommands2(), ...(0, numfmt_exports.createNumfmtCommands)(), ...(0, envsubst_exports.createEnvsubstCommands)(), ...(0, cal_exports.createCalCommands)(), ...(0, pathchk_exports.createPathchkCommands)(), ...(0, getconf_exports.createGetconfCommands)(), ...(0, locale_exports.createLocaleCommands)(), ...(0, df_exports.createDfCommands)(), ...(0, sqlite3_exports.createSqlite3Commands)()].map((cmd) => [cmd.name, cmd]));
69852
70093
  return defaultRuntimeMuscleMemoryMap.get(name2);
69853
70094
  }
69854
70095
  var fastSubScratchArgs = [];
@@ -72386,6 +72627,7 @@ var Runtime = class _Runtime {
72386
72627
  for (let i = 0; i < assignment.entries.length; i++) {
72387
72628
  const entry = assignment.entries[i];
72388
72629
  if (entry.append) return false;
72630
+ if (entry.value.parts.some((p) => p.kind === "variable" && p.prefixNames === "@") && !this.canSyncArrayMembersWord(entry.value, rawState)) return false;
72389
72631
  if (entry.index === void 0 && rawState.braceexpand !== false && this.budget.limits.maxExpansionFields === Infinity && this.budget.limits.maxExpansionBytes === Infinity && entry.value.parts.length === 1 && !entry.value.parts[0].quoted && entry.value.parts[0].kind === "text" && entry.value.parts[0].value.includes("{")) {
72390
72632
  const braceItems = tryFastExpandBraceRange(entry.value, this.budget, void 0);
72391
72633
  if (braceItems && braceItems.length <= 1500) {
@@ -78728,6 +78970,7 @@ var Runtime = class _Runtime {
78728
78970
  if (part.kind === "variable") {
78729
78971
  if (this._syncLoopFnCheckDepth > 0 && (part.substring || getArraySelector(part)?.kind === "element")) return false;
78730
78972
  if (part.prefixNames !== void 0) {
78973
+ if (part.prefixNames === "@") return false;
78731
78974
  if (part.indirect || part.specialParameter || part.length || part.substring || part.transform !== void 0 || part.operator !== void 0 || getArraySelector(part) !== void 0 || this.budget.limits.maxExpansionFields !== Infinity || this.budget.limits.maxExpansionBytes !== Infinity || !isShellIdentifier(part.name)) {
78732
78975
  return false;
78733
78976
  }
@@ -78869,6 +79112,7 @@ var Runtime = class _Runtime {
78869
79112
  }
78870
79113
  }
78871
79114
  }
79115
+ if (w0Plain === "tac" || w0Plain === "nl" || w0Plain === "base64" && cmd.words.length > 1) return false;
78872
79116
  if (w0Plain === "pwd") {
78873
79117
  if (p.commands.length === 1 && (cmd.words.length === 1 || cmd.words.length === 2 && (cmd.words[1]?.plain === "-L" || cmd.words[1]?.plain === "--logical")) && !rawState.functions.has("pwd") && !rawState.extensions?.builtins.has("pwd")) continue;
78874
79118
  return false;
@@ -78879,11 +79123,11 @@ var Runtime = class _Runtime {
78879
79123
  }
78880
79124
  return false;
78881
79125
  }
78882
- const isFileCommand = w0Plain === "cat" || w0Plain === "head" || w0Plain === "tail" || w0Plain === "jq" || w0Plain === "awk" || w0Plain === "grep" || w0Plain === "sed" || w0Plain === "cut" || w0Plain === "wc" || w0Plain === "sort" || w0Plain === "uniq" || w0Plain === "tr" || hasSingleHereStringRedir && (w0Plain === "base64" || w0Plain === "rev" || w0Plain === "tac" || w0Plain === "nl");
78883
- const def = w0Plain ? this.commands.get(w0Plain) ?? (w0Plain === "rev" || w0Plain === "tac" ? this.getExternalCommand(w0Plain) : void 0) : void 0;
79126
+ const isFileCommand = w0Plain === "cat" || w0Plain === "head" || w0Plain === "tail" || w0Plain === "jq" || w0Plain === "awk" || w0Plain === "grep" || w0Plain === "sed" || w0Plain === "cut" || w0Plain === "wc" || w0Plain === "sort" || w0Plain === "uniq" || w0Plain === "tr" || hasSingleHereStringRedir && (w0Plain === "base64" || w0Plain === "rev" || w0Plain === "tac" || w0Plain === "nl" || w0Plain === "paste" || w0Plain === "numfmt");
79127
+ const def = w0Plain ? this.commands.get(w0Plain) ?? (w0Plain === "rev" || w0Plain === "tac" || w0Plain === "nl" || w0Plain === "paste" || w0Plain === "jq" ? this.getExternalCommand(w0Plain) : void 0) : void 0;
78884
79128
  if (!w0Plain || w0Plain !== "printf" && w0Plain !== "echo" && w0Plain !== "dirname" && w0Plain !== "basename" && w0Plain !== "seq" && !isFileCommand || !def || rawState.functions.has(w0Plain) || rawState.extensions?.builtins.has(w0Plain)) return false;
78885
79129
  if ((hasSingleStdinRedir || hasSingleHereStringRedir) && !isFileCommand) return false;
78886
- if (w0Plain === "printf" ? def.execute !== printfCommand.execute : w0Plain === "echo" ? !defaultEchoExecutors.has(def.execute) : w0Plain === "seq" || w0Plain === "rev" || w0Plain === "tac" ? !builtInDirectContextExecutors.has(def.execute) && (customRegisteredCommands.has(def.execute) || customRegisteredRegistries.has(this.commands)) : !builtInDirectContextExecutors.has(def.execute)) return false;
79130
+ if (w0Plain === "printf" ? def.execute !== printfCommand.execute : w0Plain === "echo" ? !defaultEchoExecutors.has(def.execute) : w0Plain === "seq" || w0Plain === "rev" || w0Plain === "tac" || w0Plain === "nl" || w0Plain === "paste" || w0Plain === "jq" ? !builtInDirectContextExecutors.has(def.execute) && customRegisteredCommands.has(def.execute) : !builtInDirectContextExecutors.has(def.execute)) return false;
78887
79131
  if (!cmd.words.slice(1).every((w) => this.isPureSyncValueWord(w, rawState))) return false;
78888
79132
  if (isFileCommand) {
78889
79133
  if (w0Plain === "tr" && !hasSingleStdinRedir && !hasSingleHereStringRedir) return false;
@@ -78898,12 +79142,12 @@ var Runtime = class _Runtime {
78898
79142
  const opCount = opWords.length;
78899
79143
  const op0 = opWords[0]?.plain;
78900
79144
  const op1 = opWords[1]?.plain;
78901
- if (w0Plain === "cat" || w0Plain === "rev" || w0Plain === "tac" || w0Plain === "nl") {
79145
+ if (w0Plain === "cat" || w0Plain === "rev" || w0Plain === "tac") {
78902
79146
  if (opCount !== 0) return false;
78903
79147
  } else {
78904
79148
  if (p.commands.length !== 1 && !hasSingleHereStringRedir) return false;
78905
79149
  if (w0Plain === "head" || w0Plain === "tail") {
78906
- const validHT = opCount === 0 || opCount === 1 && op0 !== void 0 && /^-(?:n|c)?[0-9]{1,5}$/.test(op0) || opCount === 2 && (op0 === "-n" || op0 === "-c") && op1 !== void 0 && /^[0-9]{1,5}$/.test(op1);
79150
+ const validHT = opCount === 0 || opCount === 1 && op0 !== void 0 && (/^-(?:n|c|--lines=|--bytes=)?[0-9]{1,5}$/.test(op0) || /^--(?:lines|bytes)=[0-9]{1,5}$/.test(op0) || w0Plain === "tail" && /^(?:-n|--lines=)\+[0-9]{1,5}$/.test(op0) || w0Plain === "head" && /^(?:-n|--lines=)-[0-9]{1,5}$/.test(op0)) || opCount === 2 && (op0 === "-n" && op1 !== void 0 && (/^[0-9]{1,5}$/.test(op1) || w0Plain === "tail" && /^\+[0-9]{1,5}$/.test(op1) || w0Plain === "head" && /^-[0-9]{1,5}$/.test(op1)) || op0 === "-c" && op1 !== void 0 && /^[0-9]{1,5}$/.test(op1));
78907
79151
  if (!validHT) return false;
78908
79152
  }
78909
79153
  const plainOps = [];
@@ -78914,7 +79158,7 @@ var Runtime = class _Runtime {
78914
79158
  plainOps.push(pw);
78915
79159
  }
78916
79160
  if (w0Plain === "cut") {
78917
- if (plainOps.length !== opCount || this.evalSyncCut([], plainOps, byteLocale(rawState.variables)) === void 0) return false;
79161
+ if (plainOps.length !== opCount || this.evalSyncCut(["\xE9"], plainOps, byteLocale(rawState.variables)) === void 0) return false;
78918
79162
  } else if (w0Plain === "sed") {
78919
79163
  if (plainOps.length !== opCount || this.evalSyncSed([], plainOps) === void 0) return false;
78920
79164
  } else if (w0Plain === "grep") {
@@ -78922,30 +79166,53 @@ var Runtime = class _Runtime {
78922
79166
  } else if (w0Plain === "awk") {
78923
79167
  if (plainOps.length !== opCount || this.evalSyncAwk([], plainOps) === void 0) return false;
78924
79168
  } else if (w0Plain === "jq") {
78925
- if (plainOps.length !== opCount || this.evalSyncJq("null", plainOps) === void 0) return false;
79169
+ if (plainOps.length !== opCount) return false;
79170
+ const jqIn = this.extractLoopInvariantJqInput(cmd, hasSingleStdinRedir, hasSingleHereStringRedir, rawState);
79171
+ if (jqIn === void 0 || this.evalSyncJq(jqIn, plainOps) === void 0) return false;
78926
79172
  } else if (w0Plain === "wc") {
78927
- if (opCount !== 1 || op0 !== "-l" && op0 !== "-c" && op0 !== "-w") return false;
79173
+ if (opCount !== 1 || this.normalizeSyncWcFlag(op0) === void 0) return false;
78928
79174
  } else if (w0Plain === "sort") {
78929
- if (byteLocale(rawState.variables) || opCount > 1 || opCount === 1 && op0 !== "-r" && op0 !== "-u" && op0 !== "-n" && op0 !== "-rn" && op0 !== "-nr" && op0 !== "-ru" && op0 !== "-ur") return false;
79175
+ if (plainOps.length !== opCount || this.evalSyncSort([], plainOps, byteLocale(rawState.variables)) === void 0) return false;
78930
79176
  } else if (w0Plain === "uniq") {
78931
- if (opCount > 1 || opCount === 1 && op0 !== "-d" && op0 !== "-u" && op0 !== "-c") return false;
79177
+ if (plainOps.length !== opCount || this.evalSyncUniq([], plainOps) === void 0) return false;
78932
79178
  } else if (w0Plain === "base64") {
78933
79179
  if (opCount > 1 || opCount === 1 && op0 !== "-d" && op0 !== "--decode") return false;
78934
79180
  } else if (w0Plain === "tr") {
78935
79181
  if (plainOps.length !== opCount || this.evalSyncTr("", plainOps) === void 0) return false;
79182
+ } else if (w0Plain === "nl") {
79183
+ if (plainOps.length !== opCount || this.evalSyncNl([], plainOps) === void 0) return false;
79184
+ } else if (w0Plain === "paste") {
79185
+ if (plainOps.length !== opCount || this.evalSyncPaste([], plainOps) === void 0) return false;
79186
+ } else if (w0Plain === "numfmt") {
79187
+ const nmCheck = this.extractLoopInvariantJqInput(cmd, hasSingleStdinRedir, hasSingleHereStringRedir, rawState);
79188
+ if (nmCheck === void 0 || plainOps.length !== opCount || this.evalSyncNumfmt(nmCheck.split("\n"), plainOps) === void 0) return false;
78936
79189
  }
78937
79190
  }
78938
79191
  }
78939
79192
  if (w0Plain === "printf") {
78940
- const fmtW = cmd.words[1];
78941
- const fmtP = fmtW?.plain ?? (fmtW?.parts.length === 1 && fmtW.parts[0].kind === "text" ? fmtW.parts[0].value : void 0);
78942
- if (fmtP === void 0 || fmtP.startsWith("-") || !/^(?:[^%]|%%|%[-0]*\d*(?:\.\d+)?[sdxXouc]|\\n)*$/.test(fmtP)) return false;
79193
+ if (!this.isSyncPrintfCallOk(cmd, 1, rawState, this._activePrintfInductionName)) return false;
78943
79194
  } else if (w0Plain === "echo") {
78944
- if (cmd.words.length > 1 && (cmd.words[1].plain === void 0 ? cmd.words[1].parts[0]?.kind === "text" && cmd.words[1].parts[0].value.startsWith("-") : cmd.words[1].plain.startsWith("-"))) return false;
78945
- } else if (w0Plain === "dirname") {
78946
- if (cmd.words.length !== 2) return false;
78947
- } else if (w0Plain === "basename") {
78948
- if (cmd.words.length !== 2 && cmd.words.length !== 3 && !(cmd.words.length === 4 && cmd.words[1]?.plain === "-s")) return false;
79195
+ const firstArg = cmd.words[1];
79196
+ if (firstArg) {
79197
+ const prefix3 = firstArg.parts.find((part2) => part2.kind !== "text" || part2.value.length > 0);
79198
+ if (prefix3?.kind !== "text" || prefix3.value.startsWith("-")) return false;
79199
+ }
79200
+ } else if (w0Plain === "dirname" || w0Plain === "basename") {
79201
+ const simArgs = [];
79202
+ let seenDoubleDash = false;
79203
+ for (let wi = 1; wi < cmd.words.length; wi++) {
79204
+ const w = cmd.words[wi];
79205
+ if (w.parts[0]?.kind === "text" && !w.parts[0].quoted && w.parts[0].value.startsWith("~")) return false;
79206
+ const st = w.plain ?? (w.parts.length > 0 && w.parts.every((pt) => pt.kind === "text") ? w.parts.map((pt) => pt.value).join("") : void 0);
79207
+ if (st !== void 0) {
79208
+ if (st === "--") seenDoubleDash = true;
79209
+ simArgs.push(st);
79210
+ } else {
79211
+ if (!seenDoubleDash) return false;
79212
+ simArgs.push("x");
79213
+ }
79214
+ }
79215
+ if ((w0Plain === "dirname" ? this.evalSyncDirname(simArgs) : this.evalSyncBasename(simArgs)) === void 0) return false;
78949
79216
  } else if (w0Plain === "seq") {
78950
79217
  const isSeqIntWord = (w) => {
78951
79218
  if (w.plain !== void 0) return /^-?[0-9]{1,7}$/.test(w.plain);
@@ -78963,21 +79230,23 @@ var Runtime = class _Runtime {
78963
79230
  }
78964
79231
  if (p.commands.length >= 2) {
78965
79232
  if (w0Plain !== "printf" && w0Plain !== "echo" && w0Plain !== "seq" && w0Plain !== "cat" && !hasSingleHereStringRedir || syncPurePipelineSlotInUse || !this.budget.canSyncPurePipe || rawState.errexit || rawState.nounset) return false;
78966
- if (w0Plain === "printf" && !this.isSyncPrintfCallOk(cmd, 1, rawState)) return false;
79233
+ if (w0Plain === "printf") {
79234
+ if (!this.isSyncPrintfCallOk(cmd, 1, rawState, this._activePrintfInductionName)) return false;
79235
+ }
78967
79236
  for (let sIdx = 1; sIdx < p.commands.length; sIdx++) {
78968
79237
  const sCmd = p.commands[sIdx];
78969
79238
  if (sCmd.kind !== "simple" || sCmd.redirects.length !== 0 || sCmd.words.length === 0) return false;
78970
79239
  const sName = sCmd.words[0].plain;
78971
- if (!sName || sName !== "cut" && sName !== "tr" && sName !== "sort" && sName !== "head" && sName !== "tail" && sName !== "wc" && sName !== "sed" && sName !== "uniq" && sName !== "rev" && sName !== "awk" && sName !== "grep" && sName !== "jq" && sName !== "base64" && sName !== "tac" && sName !== "nl") return false;
78972
- const sDef = this.commands.get(sName);
78973
- if (!sDef || customRegisteredCommands.has(sDef.execute) || sName !== "rev" && sName !== "tac" && !builtInDirectContextExecutors.has(sDef.execute)) return false;
79240
+ if (!sName || sName !== "cut" && sName !== "tr" && sName !== "sort" && sName !== "head" && sName !== "tail" && sName !== "wc" && sName !== "sed" && sName !== "uniq" && sName !== "rev" && sName !== "awk" && sName !== "grep" && sName !== "jq" && sName !== "base64" && sName !== "tac" && sName !== "nl" && sName !== "paste" && sName !== "numfmt") return false;
79241
+ const sDef = this.commands.get(sName) ?? (sName === "rev" || sName === "tac" || sName === "nl" || sName === "paste" || sName === "jq" ? this.getExternalCommand(sName) : void 0);
79242
+ if (!sDef || customRegisteredCommands.has(sDef.execute) || sName !== "rev" && sName !== "tac" && sName !== "nl" && sName !== "paste" && sName !== "jq" && !builtInDirectContextExecutors.has(sDef.execute)) return false;
78974
79243
  if (rawState.functions.has(sName) || rawState.extensions?.builtins.has(sName)) return false;
78975
79244
  const sArgWords = sCmd.words.slice(1);
78976
79245
  const sPlainArgs = [];
78977
79246
  let allPlainStageArgs = true;
78978
79247
  for (let k = 0; k < sArgWords.length; k++) {
78979
79248
  const sw = sArgWords[k];
78980
- const sp = sw.plain ?? (sw.parts.length === 1 && sw.parts[0].kind === "text" ? sw.parts[0].value : void 0);
79249
+ const sp = sw.plain ?? (sw.parts.length > 0 && sw.parts.every((pt) => pt.kind === "text") ? sw.parts.map((pt) => pt.value).join("") : void 0);
78981
79250
  if (sp === void 0) {
78982
79251
  allPlainStageArgs = false;
78983
79252
  break;
@@ -78985,43 +79254,44 @@ var Runtime = class _Runtime {
78985
79254
  sPlainArgs.push(sp);
78986
79255
  }
78987
79256
  if (!allPlainStageArgs) return false;
78988
- if (sName === "sort" && (sPlainArgs.length > 1 || sPlainArgs.length === 1 && sPlainArgs[0] !== "-r")) return false;
78989
- if (sName === "wc" && (sPlainArgs.length !== 1 || sPlainArgs[0] !== "-l" && sPlainArgs[0] !== "-c" && sPlainArgs[0] !== "-w")) return false;
78990
- if (sName === "head" || sName === "tail") {
78991
- const okHT = sPlainArgs.length === 2 && sPlainArgs[0] === "-n" && /^[0-9]+$/.test(sPlainArgs[1]) || sPlainArgs.length === 1 && /^-(?:n)?[0-9]+$/.test(sPlainArgs[0]);
79257
+ if (sName === "sort") {
79258
+ if (this.evalSyncSort([], sPlainArgs, byteLocale(rawState.variables)) === void 0) return false;
79259
+ } else if (sName === "uniq") {
79260
+ if (this.evalSyncUniq([], sPlainArgs) === void 0) return false;
79261
+ } else if (sName === "wc") {
79262
+ if (sPlainArgs.length !== 1 || this.normalizeSyncWcFlag(sPlainArgs[0]) === void 0) return false;
79263
+ } else if (sName === "head" || sName === "tail") {
79264
+ const okHT = sPlainArgs.length === 0 || sPlainArgs.length === 1 && (/^-(?:n|c)?[0-9]{1,5}$/.test(sPlainArgs[0]) || /^--(?:lines|bytes)=[0-9]{1,5}$/.test(sPlainArgs[0]) || sName === "tail" && /^(?:-n|--lines=)\+[0-9]{1,5}$/.test(sPlainArgs[0]) || sName === "head" && /^(?:-n|--lines=)-[0-9]{1,5}$/.test(sPlainArgs[0])) || sPlainArgs.length === 2 && (sPlainArgs[0] === "-n" && (/^[0-9]{1,5}$/.test(sPlainArgs[1]) || sName === "tail" && /^\+[0-9]{1,5}$/.test(sPlainArgs[1]) || sName === "head" && /^-[0-9]{1,5}$/.test(sPlainArgs[1])) || sPlainArgs[0] === "-c" && /^[0-9]{1,5}$/.test(sPlainArgs[1]));
78992
79265
  if (!okHT) return false;
79266
+ } else if (sName === "cut") {
79267
+ if (this.evalSyncCut(["\xE9"], sPlainArgs, byteLocale(rawState.variables)) === void 0) return false;
79268
+ } else if (sName === "sed") {
79269
+ if (this.evalSyncSed([], sPlainArgs) === void 0) return false;
79270
+ } else if (sName === "awk") {
79271
+ if (this.evalSyncAwk([], sPlainArgs) === void 0) return false;
79272
+ } else if (sName === "grep") {
79273
+ if (this.evalSyncGrep([], sPlainArgs, Boolean(rawState.errexit)) === void 0) return false;
79274
+ } else if (sName === "tr") {
79275
+ if (this.evalSyncTr("", sPlainArgs) === void 0) return false;
79276
+ } else if (sName === "jq") {
79277
+ if (sIdx !== 1) return false;
79278
+ const jqIn = this.extractLoopInvariantJqInput(cmd, hasSingleStdinRedir, hasSingleHereStringRedir, rawState);
79279
+ if (jqIn === void 0 || this.evalSyncJq(jqIn, sPlainArgs) === void 0) return false;
79280
+ } else if (sName === "base64") {
79281
+ if (sPlainArgs.length !== 0) return false;
79282
+ } else if (sName === "tac") {
79283
+ if (sPlainArgs.length !== 0 || w0Plain !== "echo" && !hasSingleHereStringRedir) return false;
79284
+ } else if (sName === "nl") {
79285
+ if (w0Plain !== "echo" && !hasSingleHereStringRedir || this.evalSyncNl([], sPlainArgs) === void 0) return false;
79286
+ } else if (sName === "paste") {
79287
+ if (this.evalSyncPaste([], sPlainArgs) === void 0) return false;
79288
+ } else if (sName === "numfmt") {
79289
+ if (sIdx !== 1) return false;
79290
+ const nmCheck = this.extractLoopInvariantJqInput(cmd, hasSingleStdinRedir, hasSingleHereStringRedir, rawState);
79291
+ if (nmCheck === void 0 || this.evalSyncNumfmt(nmCheck.split("\n"), sPlainArgs) === void 0) return false;
79292
+ } else if (sName === "rev") {
79293
+ if (sPlainArgs.length !== 0) return false;
78993
79294
  }
78994
- if (sName === "cut") {
78995
- const normCut = [];
78996
- for (let ci = 0; ci < sPlainArgs.length; ci++) {
78997
- const ca = sPlainArgs[ci];
78998
- if ((ca === "-d" || ca === "-f") && ci + 1 < sPlainArgs.length) {
78999
- normCut.push(ca + sPlainArgs[++ci]);
79000
- } else {
79001
- normCut.push(ca);
79002
- }
79003
- }
79004
- const vc2 = normCut.length === 2 && (normCut[0].length === 3 && normCut[0].startsWith("-d") && normCut[1].length >= 3 && normCut[1].startsWith("-f") || normCut[0] === "-c" && /^[1-9][0-9]*-[1-9][0-9]*$/.test(normCut[1]));
79005
- const vc1 = normCut.length === 1 && normCut[0].length >= 3 && normCut[0].startsWith("-f");
79006
- if (!vc1 && !vc2) return false;
79007
- }
79008
- if (sName === "awk") {
79009
- const normAwk = sPlainArgs.length === 3 && sPlainArgs[0] === "-F" ? ["-F" + sPlainArgs[1], sPlainArgs[2]] : sPlainArgs;
79010
- const awkSepOk = normAwk.length === 1 || normAwk.length === 2 && normAwk[0].length === 3 && normAwk[0].startsWith("-F") && normAwk[0][2] !== "\\";
79011
- const awkProg = normAwk[normAwk.length - 1] ?? "";
79012
- if (!awkSepOk || !/^\s*\{\s*print(?:\s+(\$(?:[0-9]+|NF)(?:\s*,\s*\$(?:[0-9]+|NF))*))?\s*;?\s*\}\s*$/.test(awkProg)) return false;
79013
- }
79014
- if (sName === "grep") {
79015
- const grepOk = sPlainArgs.length === 1 && !sPlainArgs[0].startsWith("-") && /^[a-zA-Z0-9_ :;,/-]+$/.test(sPlainArgs[0]) || sPlainArgs.length === 2 && (sPlainArgs[0] === "-v" || sPlainArgs[0] === "-i" || sPlainArgs[0] === "-c" || sPlainArgs[0] === "-F") && /^[a-zA-Z0-9_ :;,/-]+$/.test(sPlainArgs[1]);
79016
- if (!grepOk) return false;
79017
- }
79018
- if (sName === "jq") {
79019
- return false;
79020
- }
79021
- if (sName === "base64") {
79022
- if (sPlainArgs.length > 1 || sPlainArgs.length === 1 && sPlainArgs[0] !== "-d" && sPlainArgs[0] !== "--decode") return false;
79023
- }
79024
- if ((sName === "tac" || sName === "nl") && sPlainArgs.length !== 0) return false;
79025
79295
  }
79026
79296
  }
79027
79297
  continue;
@@ -79353,7 +79623,7 @@ var Runtime = class _Runtime {
79353
79623
  argIdx += 2;
79354
79624
  } else if (p === "-n" || p === "-rn" || p === "-nr" || p === "-N" || p === "-rN" || p === "-Nr") {
79355
79625
  if (p.includes("r")) rawMode = true;
79356
- exactChars = p.includes("N");
79626
+ exactChars ||= p.includes("N");
79357
79627
  const nPlain = cmd.words[argIdx + 1]?.plain;
79358
79628
  if (!nPlain || !/^[1-9][0-9]{0,5}$/.test(nPlain) || byteLocale(rawState.variables)) return void 0;
79359
79629
  maxChars = Number(nPlain);
@@ -79361,7 +79631,7 @@ var Runtime = class _Runtime {
79361
79631
  } else if ((p.startsWith("-n") || p.startsWith("-rn") || p.startsWith("-N") || p.startsWith("-rN")) && /^[1-9][0-9]{0,5}$/.test(p.slice(p.startsWith("-r") ? 3 : 2))) {
79362
79632
  if (byteLocale(rawState.variables)) return void 0;
79363
79633
  if (p.startsWith("-r")) rawMode = true;
79364
- exactChars = p.includes("N");
79634
+ exactChars ||= p.includes("N");
79365
79635
  maxChars = Number(p.slice(p.startsWith("-r") ? 3 : 2));
79366
79636
  argIdx++;
79367
79637
  } else if (p === "-ra" || p === "-ar" || p === "-a") {
@@ -79519,12 +79789,12 @@ var Runtime = class _Runtime {
79519
79789
  ifOk = false;
79520
79790
  break;
79521
79791
  }
79522
- if (!this.canSyncLoopBody(br.body, rawState, io, true)) {
79792
+ if (!this.canSyncLoopBody(br.body, rawState, io, true, printfInductionName)) {
79523
79793
  ifOk = false;
79524
79794
  break;
79525
79795
  }
79526
79796
  }
79527
- if (ifOk && cmd.otherwise && !this.canSyncLoopBody(cmd.otherwise, rawState, io, true)) ifOk = false;
79797
+ if (ifOk && cmd.otherwise && !this.canSyncLoopBody(cmd.otherwise, rawState, io, true, printfInductionName)) ifOk = false;
79528
79798
  if (ifOk) continue;
79529
79799
  return false;
79530
79800
  }
@@ -79542,7 +79812,7 @@ var Runtime = class _Runtime {
79542
79812
  caseOk = false;
79543
79813
  break;
79544
79814
  }
79545
- if (!this.canSyncLoopBody(cl.body, rawState, io, true)) {
79815
+ if (!this.canSyncLoopBody(cl.body, rawState, io, true, printfInductionName)) {
79546
79816
  caseOk = false;
79547
79817
  break;
79548
79818
  }
@@ -80163,9 +80433,31 @@ var Runtime = class _Runtime {
80163
80433
  const condition = command7.kind === "arithmetic-for" ? command7.expressions[1]?.tree : void 0;
80164
80434
  const increment = command7.kind === "arithmetic-for" ? command7.expressions[2]?.tree : void 0;
80165
80435
  const whileCondCmd = command7.kind === "while" && command7.condition.lists.length === 1 && command7.condition.lists[0].pipelines.length === 1 ? command7.condition.lists[0].pipelines[0].commands[0] : void 0;
80166
- const whilePrintfInd = whileCondCmd?.kind === "arithmetic" && !whileCondCmd.expression.error && whileCondCmd.expression.tree?.kind === "binary" && (whileCondCmd.expression.tree.left.kind === "name" ? whileCondCmd.expression.tree.left.name : whileCondCmd.expression.tree.left.kind === "unary" && whileCondCmd.expression.tree.left.operand.kind === "name" ? whileCondCmd.expression.tree.left.operand.name : void 0);
80167
- const printfInductionName = initializer?.kind === "binary" && initializer.operator === "=" && initializer.left.kind === "name" && initializer.right.kind === "literal" && initializer.right.value >= 0n && initializer.right.value <= 2000n && condition?.kind === "binary" && (condition.operator === "<" || condition.operator === "<=") && condition.left.kind === "name" && condition.left.name === initializer.left.name && condition.right.kind === "literal" && condition.right.value >= 0n && condition.right.value <= 2000n && increment?.kind === "unary" && increment.operator === "++" && increment.operand.kind === "name" && increment.operand.name === initializer.left.name && this.canSyncPrintfInductionBody(command7.body, rawState) ? initializer.left.name : whilePrintfInd && this.canSyncPrintfInductionBody(command7.body, rawState) ? whilePrintfInd : void 0;
80168
- if (guestArrays(rawState) && (guestArrays(rawState).watches.size > 0 || this.budget.limits.maxExpansionBytes < 65536) || !this.canSyncLoopBody(command7.body, rawState, io, false, printfInductionName)) {
80436
+ const whileTree = whileCondCmd?.kind === "arithmetic" && !whileCondCmd.expression.error ? whileCondCmd.expression.tree : void 0;
80437
+ const whileName = whileTree?.kind === "binary" && (whileTree.operator === "<" || whileTree.operator === "<=") && whileTree.left.kind === "name" && whileTree.right.kind === "literal" && whileTree.right.value >= 0n && whileTree.right.value <= 2000n ? whileTree.left.name : void 0;
80438
+ const whileValue = whileName === void 0 ? void 0 : rawState.variables[whileName];
80439
+ const whileStart = typeof whileValue === "string" ? Number(whileValue) : NaN;
80440
+ const whilePrintfInd = Number.isInteger(whileStart) && whileStart >= 0 && whileStart <= 2e3 && String(whileStart) === whileValue ? whileName : void 0;
80441
+ const forPrintfInd = command7.kind === "for" && command7.words?.length === 1 && /^\{[0-9]{1,4}\.\.[0-9]{1,4}(?:\.\.[1-9][0-9]{0,2})?\}$/.test(command7.words[0].plain ?? "") ? command7.name : void 0;
80442
+ const printfInductionName = initializer?.kind === "binary" && initializer.operator === "=" && initializer.left.kind === "name" && initializer.right.kind === "literal" && initializer.right.value >= 0n && initializer.right.value <= 2000n && condition?.kind === "binary" && (condition.operator === "<" || condition.operator === "<=") && condition.left.kind === "name" && condition.left.name === initializer.left.name && condition.right.kind === "literal" && condition.right.value >= 0n && condition.right.value <= 2000n && increment?.kind === "unary" && increment.operator === "++" && increment.operand.kind === "name" && increment.operand.name === initializer.left.name && this.canSyncPrintfInductionBody(command7.body, rawState, initializer.left.name) ? initializer.left.name : whilePrintfInd && this.canSyncPrintfInductionBody(command7.body, rawState, whilePrintfInd) ? whilePrintfInd : forPrintfInd && this.canSyncPrintfInductionBody(command7.body, rawState, forPrintfInd) ? forPrintfInd : void 0;
80443
+ const prevActivePrintfInd = this._activePrintfInductionName;
80444
+ const prevActiveLoopScript = this._activeLoopBodyScript;
80445
+ const prevActiveLoopCond = this._activeLoopCondScript;
80446
+ const prevActiveLoopVar = this._activeLoopVarName;
80447
+ this._activePrintfInductionName = printfInductionName;
80448
+ this._activeLoopBodyScript = command7.body;
80449
+ this._activeLoopCondScript = command7.kind === "while" ? command7.condition : void 0;
80450
+ this._activeLoopVarName = command7.kind === "for" ? command7.name : printfInductionName ?? (whilePrintfInd || void 0);
80451
+ let bodySyncOk = false;
80452
+ try {
80453
+ bodySyncOk = !(guestArrays(rawState) && (guestArrays(rawState).watches.size > 0 || this.budget.limits.maxExpansionBytes < 65536)) && this.canSyncLoopBody(command7.body, rawState, io, false, printfInductionName);
80454
+ } finally {
80455
+ this._activePrintfInductionName = prevActivePrintfInd;
80456
+ this._activeLoopBodyScript = prevActiveLoopScript;
80457
+ this._activeLoopCondScript = prevActiveLoopCond;
80458
+ this._activeLoopVarName = prevActiveLoopVar;
80459
+ }
80460
+ if (!bodySyncOk) {
80169
80461
  command7._skipTrySyncLoop = true;
80170
80462
  return void 0;
80171
80463
  }
@@ -80303,7 +80595,7 @@ var Runtime = class _Runtime {
80303
80595
  intSteps2[b] = intStep;
80304
80596
  continue;
80305
80597
  }
80306
- const wordsToScan = step.arrayAssign?.kind === "compound" ? step.arrayAssign.entries.map((e) => e.value) : step.value ? [step.value] : [];
80598
+ const wordsToScan = step.arrayAssign?.kind === "compound" ? step.arrayAssign.entries.map((e) => e.value) : step.printfVArgs ? step.printfVArgs : step.value ? [step.value] : [];
80307
80599
  for (let wIdx = 0; wIdx < wordsToScan.length; wIdx++) {
80308
80600
  const wVal = wordsToScan[wIdx];
80309
80601
  for (let i = 0; i < wVal.parts.length; i++) {
@@ -81402,18 +81694,172 @@ ${s1}
81402
81694
  }
81403
81695
  return pos <= 128 ? fastRedirectScratchViews[pos] : fastRedirectScratchBytes.subarray(0, pos);
81404
81696
  }
81405
- canSyncPrintfInductionBody(script2, rawState) {
81697
+ _activePrintfInductionName = void 0;
81698
+ _activeLoopBodyScript = void 0;
81699
+ _activeLoopCondScript = void 0;
81700
+ _activeLoopVarName = void 0;
81701
+ isVarUnmutatedInScript(varName, script2) {
81702
+ for (const list of script2.lists) {
81703
+ for (const pipeline of list.pipelines) {
81704
+ for (const cmd of pipeline.commands) {
81705
+ if (cmd.kind === "arithmetic") {
81706
+ if (cmd.expression.hasMutation && cmd.expression.source.includes(varName)) return false;
81707
+ continue;
81708
+ }
81709
+ if (cmd.kind === "if") {
81710
+ for (const br of cmd.branches) {
81711
+ if (!this.isVarUnmutatedInScript(varName, br.condition) || !this.isVarUnmutatedInScript(varName, br.body)) return false;
81712
+ }
81713
+ if (cmd.otherwise && !this.isVarUnmutatedInScript(varName, cmd.otherwise)) return false;
81714
+ continue;
81715
+ }
81716
+ if (cmd.kind === "case") {
81717
+ for (const cl of cmd.clauses) {
81718
+ if (!this.isVarUnmutatedInScript(varName, cl.body)) return false;
81719
+ }
81720
+ continue;
81721
+ }
81722
+ if (cmd.kind === "for") {
81723
+ if (cmd.name === varName || !this.isVarUnmutatedInScript(varName, cmd.body)) return false;
81724
+ continue;
81725
+ }
81726
+ if (cmd.kind === "arithmetic-for") {
81727
+ if (cmd.expressions.some((e) => e && e.hasMutation && e.source.includes(varName)) || !this.isVarUnmutatedInScript(varName, cmd.body)) return false;
81728
+ continue;
81729
+ }
81730
+ if (cmd.kind === "while") {
81731
+ if (!this.isVarUnmutatedInScript(varName, cmd.condition) || !this.isVarUnmutatedInScript(varName, cmd.body)) return false;
81732
+ continue;
81733
+ }
81734
+ if (cmd.kind === "group" || cmd.kind === "subshell") {
81735
+ if (!this.isVarUnmutatedInScript(varName, cmd.body)) return false;
81736
+ continue;
81737
+ }
81738
+ if (cmd.kind !== "simple") return false;
81739
+ for (const w of cmd.words) {
81740
+ const arrAss = getArrayAssignment(w);
81741
+ if (arrAss && arrAss.name === varName) return false;
81742
+ const p02 = w.parts[0];
81743
+ if (p02?.kind === "text" && !p02.quoted && (p02.value.startsWith(varName + "=") || p02.value.startsWith(varName + "+=") || p02.value.startsWith(varName + "["))) return false;
81744
+ }
81745
+ const w0 = cmd.words[0]?.plain;
81746
+ if (w0 === "read" || w0 === "unset" || w0 === "declare" || w0 === "typeset" || w0 === "local" || w0 === "export" || w0 === "mapfile" || w0 === "readarray") {
81747
+ if (w0 === "read" && varName === "REPLY") return false;
81748
+ if (cmd.words.slice(1).some((w) => (w.plain ?? "").includes(varName))) return false;
81749
+ }
81750
+ if (w0 === "printf" && cmd.words[1]?.plain === "-v" && (cmd.words[2]?.plain ?? "").startsWith(varName)) return false;
81751
+ for (const w of [...cmd.words, ...cmd.redirects.map((r) => r.target)]) {
81752
+ for (const pt of w.parts) {
81753
+ if (pt.kind === "arithmetic" && pt.expression.hasMutation && pt.expression.source.includes(varName)) return false;
81754
+ if (pt.kind === "substitution" && !this.isVarUnmutatedInScript(varName, pt.script)) return false;
81755
+ }
81756
+ }
81757
+ }
81758
+ }
81759
+ }
81760
+ return true;
81761
+ }
81762
+ isVarUnmutatedInActiveLoop(varName) {
81763
+ if (varName === this._activeLoopVarName || varName === this._activePrintfInductionName) return false;
81764
+ if (this._activeLoopCondScript && !this.isVarUnmutatedInScript(varName, this._activeLoopCondScript)) return false;
81765
+ if (this._activeLoopBodyScript && !this.isVarUnmutatedInScript(varName, this._activeLoopBodyScript)) return false;
81766
+ return true;
81767
+ }
81768
+ isFileReadOnlyScript(script2, rawState) {
81769
+ const visit = (value2) => {
81770
+ if (value2 === null || typeof value2 !== "object") return true;
81771
+ if (Array.isArray(value2)) return value2.every(visit);
81772
+ const node = value2;
81773
+ if (typeof node.operator === "string" && "target" in node && !["<", "<<<", "<<", "<<-"].includes(node.operator)) return false;
81774
+ if (node.kind === "simple") {
81775
+ const cmd = value2;
81776
+ const name2 = cmd.words[0]?.plain;
81777
+ if (name2 === void 0 && !cmd.words.every((word) => this.assignment(word) || getArrayAssignment(word))) return false;
81778
+ if (name2 !== void 0 && (hasShellFunction(rawState, name2) || !["jq", "cat", "echo", "printf", "test", "[", ":", "true", "false"].includes(name2))) return false;
81779
+ }
81780
+ return Object.values(node).every(visit);
81781
+ };
81782
+ return visit(script2);
81783
+ }
81784
+ extractLoopInvariantJqInput(cmd, hasSingleStdinRedir, hasSingleHereStringRedir, rawState) {
81785
+ const w0 = cmd.words[0]?.plain;
81786
+ const resolveInvariantWord = (w) => {
81787
+ if (w.plain !== void 0) return w.plain;
81788
+ if (w.parts.length > 0 && w.parts.every((pt) => pt.kind === "text")) return w.parts.map((pt) => pt.value).join("");
81789
+ if (w.parts.length === 1 && w.parts[0].kind === "variable") {
81790
+ const vp = w.parts[0];
81791
+ if (!vp.indirect && !vp.operator && !vp.substring && !vp.transform && !vp.length && !vp.prefixNames && getArraySelector(vp) === void 0 && this.isVarUnmutatedInActiveLoop(vp.name)) {
81792
+ const val = rawState.variables[vp.name];
81793
+ if (typeof val === "string") return val;
81794
+ }
81795
+ }
81796
+ return void 0;
81797
+ };
81798
+ if (w0 === "jq" || w0 === "numfmt") {
81799
+ if (hasSingleHereStringRedir) {
81800
+ const resolved = resolveInvariantWord(cmd.redirects[0].target);
81801
+ return resolved !== void 0 ? resolved.trim() : void 0;
81802
+ }
81803
+ if (this._fileWrites?.size || this._outputFiles?.size) return void 0;
81804
+ if ([this._activeLoopBodyScript, this._activeLoopCondScript].some((script2) => script2 && !this.isFileReadOnlyScript(script2, rawState))) return void 0;
81805
+ const fPlain = hasSingleStdinRedir ? cmd.redirects[0].target.plain : cmd.words[cmd.words.length - 1]?.plain;
81806
+ if (!fPlain || fPlain.startsWith("-") || fPlain === "/dev/stdin") return void 0;
81807
+ const vCheck = this.tryReadMemoryFileViewSync(resolvePath(rawState.cwd, fPlain), false);
81808
+ if (!vCheck || vCheck.byteLength > 16384 || vCheck.includes(0)) return void 0;
81809
+ return sharedSyncPipeDecoder.decode(vCheck).trim();
81810
+ }
81811
+ if (w0 === "cat") {
81812
+ if (hasSingleHereStringRedir) {
81813
+ const resolved = resolveInvariantWord(cmd.redirects[0].target);
81814
+ return resolved !== void 0 ? resolved.trim() : void 0;
81815
+ }
81816
+ if (this._fileWrites?.size || this._outputFiles?.size) return void 0;
81817
+ if ([this._activeLoopBodyScript, this._activeLoopCondScript].some((script2) => script2 && !this.isFileReadOnlyScript(script2, rawState))) return void 0;
81818
+ const fPlain = hasSingleStdinRedir ? cmd.redirects[0].target.plain : cmd.words[1]?.plain;
81819
+ if (!fPlain || fPlain.startsWith("-") || fPlain === "/dev/stdin") return void 0;
81820
+ const vCheck = this.tryReadMemoryFileViewSync(resolvePath(rawState.cwd, fPlain), false);
81821
+ if (!vCheck || vCheck.byteLength > 16384 || vCheck.includes(0)) return void 0;
81822
+ return sharedSyncPipeDecoder.decode(vCheck).trim();
81823
+ }
81824
+ if (w0 === "echo" && cmd.words.length === 2) {
81825
+ const resolved = resolveInvariantWord(cmd.words[1]);
81826
+ if (resolved !== void 0 && !resolved.startsWith("-")) return resolved.trim();
81827
+ return void 0;
81828
+ }
81829
+ if (w0 === "printf" && cmd.words.length >= 2) {
81830
+ const args = [];
81831
+ for (let i = 1; i < cmd.words.length; i++) {
81832
+ const r = resolveInvariantWord(cmd.words[i]);
81833
+ if (r === void 0) return void 0;
81834
+ args.push(r);
81835
+ }
81836
+ const formatted3 = tryFastPrintf(args);
81837
+ return formatted3 !== void 0 ? formatted3.trim() : void 0;
81838
+ }
81839
+ return void 0;
81840
+ }
81841
+ canSyncPrintfInductionBody(script2, rawState, inductionName) {
81406
81842
  for (const list of script2.lists) for (const pipeline of list.pipelines) for (const command7 of pipeline.commands) {
81407
81843
  if (command7.kind === "arithmetic") {
81408
- if (command7.redirects.length === 0 && !command7.expression.error && !command7.expression.hasSubscript && isSafeSmiProgram(command7.expression) && command7.expression.tree?.kind === "unary" && (command7.expression.tree.operator === "++" || command7.expression.tree.operator === "--") && command7.expression.tree.operand.kind === "name") continue;
81844
+ if (command7.redirects.length === 0 && !command7.expression.error && !command7.expression.hasSubscript && isSafeSmiProgram(command7.expression) && command7.expression.tree?.kind === "unary" && (command7.expression.tree.operator === "++" || command7.expression.tree.operator === "--" && command7.expression.tree.operand.kind === "name" && command7.expression.tree.operand.name !== inductionName) && command7.expression.tree.operand.kind === "name") continue;
81409
81845
  return false;
81410
81846
  }
81411
81847
  if (command7.kind !== "simple" || hasShellFunction(rawState, command7.words[0]?.plain ?? "") || command7.words.some((word) => getArrayAssignment(word) !== void 0)) return false;
81848
+ const w0 = command7.words[0]?.plain;
81849
+ if (w0 === "let" || w0 === "declare" || w0 === "typeset" || w0 === "local" || w0 === "export" || w0 === "unset" || w0 === "mapfile" || w0 === "readarray") return false;
81850
+ if (inductionName !== void 0) {
81851
+ if (command7.words.some((w) => {
81852
+ const p02 = w.parts[0];
81853
+ return p02?.kind === "text" && !p02.quoted && (p02.value.startsWith(inductionName + "=") || p02.value.startsWith(inductionName + "+="));
81854
+ })) return false;
81855
+ if (w0 === "read" && (inductionName === "REPLY" || command7.words.slice(1).some((w) => w.plain === inductionName || w.plain === "-a" || w.plain === "-ra" || w.plain === "-ar"))) return false;
81856
+ if (w0 === "printf" && command7.words[1]?.plain === "-v" && command7.words[2]?.plain === inductionName) return false;
81857
+ }
81412
81858
  for (const word of [...command7.words, ...command7.redirects.map((redirect) => redirect.target)]) for (const part of word.parts) {
81413
81859
  if (part.kind === "text") continue;
81414
- if (part.kind === "variable" && !part.indirect && !part.length && !part.substring && !part.transform && !part.prefixNames && part.operator === void 0 && getArraySelector(part) === void 0) continue;
81860
+ if (part.kind === "variable" && !part.indirect && !part.substring && !part.prefixNames && getArraySelector(part) === void 0 && (part.operator === void 0 || (part.operator === "#" || part.operator === "##" || part.operator === "%" || part.operator === "%%") && part.alternate !== void 0 && part.alternate.parts.every((p) => p.kind === "text"))) continue;
81415
81861
  if (part.kind === "arithmetic" && !part.expression.error && !part.expression.hasMutation && !part.expression.hasSubscript && isSafeSmiProgram(part.expression) && /^[a-zA-Z0-9_ +*-]+$/.test(part.expression.source)) continue;
81416
- if (part.kind === "substitution" && this.canSyncPrintfInductionBody(part.script, rawState)) continue;
81862
+ if (part.kind === "substitution" && this.canSyncPrintfInductionBody(part.script, rawState, inductionName)) continue;
81417
81863
  return false;
81418
81864
  }
81419
81865
  }
@@ -81422,26 +81868,66 @@ ${s1}
81422
81868
  isSyncPrintfCallOk(cmd, argStartIdx, rawState, inductionName) {
81423
81869
  const printfDef = this.commands.get("printf");
81424
81870
  if (hasShellFunction(rawState, "printf") || rawState.extensions?.builtins.has("printf") || printfDef?.execute !== printfCommand.execute) return false;
81425
- const args = [];
81871
+ const effInductionName = inductionName ?? this._activePrintfInductionName;
81872
+ const unsignedUpperBound = (tree) => {
81873
+ if (!tree) return void 0;
81874
+ let bound;
81875
+ if (tree.kind === "literal") bound = tree.value;
81876
+ else if (tree.kind === "name" && tree.name === effInductionName && tree.subscript === void 0) bound = 2147483647n;
81877
+ else if (tree.kind === "binary" && (tree.operator === "+" || tree.operator === "*")) {
81878
+ const left = unsignedUpperBound(tree.left);
81879
+ const right = unsignedUpperBound(tree.right);
81880
+ if (left !== void 0 && right !== void 0) bound = tree.operator === "+" ? left + right : left * right;
81881
+ }
81882
+ return bound !== void 0 && bound >= 0n && bound <= 2147483647n ? bound : void 0;
81883
+ };
81426
81884
  const fmtWordIdx = cmd.words[argStartIdx]?.plain === "--" ? argStartIdx + 1 : argStartIdx;
81427
81885
  if (fmtWordIdx >= cmd.words.length) return false;
81428
- for (let i = argStartIdx; i < cmd.words.length; i++) {
81886
+ const fmtWord = cmd.words[fmtWordIdx];
81887
+ if (!this.isPureSyncValueWord(fmtWord, rawState)) return false;
81888
+ let fmtStr = "";
81889
+ for (const part of fmtWord.parts) {
81890
+ if (part.kind !== "text" || !part.quoted && (part.value.length === 0 || part.value.includes(" ") || part.value.includes(" ") || part.value.includes("\n") || part.value.includes("{") || hasGlobOrEscape(part.value, true))) return false;
81891
+ fmtStr += part.value;
81892
+ }
81893
+ if (fmtWordIdx === argStartIdx && fmtStr.startsWith("-")) return false;
81894
+ const specs = extractFastPrintfSpecifiers(fmtStr);
81895
+ if (!specs) return false;
81896
+ const args = [];
81897
+ if (fmtWordIdx > argStartIdx) args.push("--");
81898
+ args.push(fmtStr);
81899
+ for (let i = fmtWordIdx + 1; i < cmd.words.length; i++) {
81429
81900
  const w = cmd.words[i];
81430
81901
  if (!this.isPureSyncValueWord(w, rawState)) return false;
81431
- const valueParts = w.parts.filter((part2) => part2.kind !== "text" || part2.value.length > 0);
81432
- const part = valueParts[0];
81433
- if (i > fmtWordIdx && valueParts.length === 1 && part?.kind === "variable" && part.name === inductionName && part.quoted && !part.indirect && !part.length && !part.substring && !part.transform && part.operator === void 0 && getArraySelector(part) === void 0) {
81434
- args.push("0");
81902
+ const argIdx = i - fmtWordIdx - 1;
81903
+ const spec = specs.length > 0 ? specs[argIdx % specs.length] : "s";
81904
+ const nonSplitting = w.parts.length > 0 && w.parts.every(
81905
+ (part2) => part2.quoted || part2.kind === "text" && part2.value.length > 0 && !part2.value.includes(" ") && !part2.value.includes(" ") && !part2.value.includes("\n") && !part2.value.includes("{") && !hasGlobOrEscape(part2.value, true)
81906
+ );
81907
+ if (spec === "s" && nonSplitting) {
81908
+ args.push("");
81435
81909
  continue;
81436
81910
  }
81437
- if (i > fmtWordIdx && inductionName !== void 0 && valueParts.length === 1 && part?.kind === "arithmetic" && part.quoted && !part.expression.error && !part.expression.hasMutation && !part.expression.hasSubscript && isSafeSmiProgram(part.expression) && /^[a-zA-Z0-9_ +*-]+$/.test(part.expression.source) && this.canSyncArithmeticWithoutFault(part.expression.tree, rawState, cmd.line ?? 1)) {
81438
- args.push("0");
81439
- continue;
81911
+ const valueParts = w.parts.filter((part2) => part2.kind !== "text" || part2.value.length > 0);
81912
+ const part = valueParts[0];
81913
+ if ((spec === "d" || spec === "u") && valueParts.length === 1 && part?.quoted) {
81914
+ if (part.kind === "variable" && part.name === effInductionName && !part.indirect && !part.length && !part.substring && !part.transform && part.operator === void 0 && getArraySelector(part) === void 0) {
81915
+ args.push("0");
81916
+ continue;
81917
+ }
81918
+ if (part.kind === "variable" && part.length && !part.indirect && !part.prefixNames && getArraySelector(part) === void 0) {
81919
+ args.push("0");
81920
+ continue;
81921
+ }
81922
+ if (part.kind === "arithmetic" && !part.expression.error && !part.expression.hasMutation && !part.expression.hasSubscript && isSafeSmiProgram(part.expression) && /^[a-zA-Z0-9_ +*-]+$/.test(part.expression.source) && this.canSyncArithmeticWithoutFault(part.expression.tree, rawState, cmd.line ?? 1) && (spec === "d" || unsignedUpperBound(part.expression.tree) !== void 0)) {
81923
+ args.push("0");
81924
+ continue;
81925
+ }
81440
81926
  }
81441
81927
  let arg = "";
81442
- for (const part2 of w.parts) {
81443
- if (part2.kind !== "text" || !part2.quoted && (part2.value.length === 0 || part2.value.includes(" ") || part2.value.includes(" ") || part2.value.includes("\n") || part2.value.includes("{") || hasGlobOrEscape(part2.value, true))) return false;
81444
- arg += part2.value;
81928
+ for (const p of w.parts) {
81929
+ if (p.kind !== "text" || !p.quoted && (p.value.length === 0 || p.value.includes(" ") || p.value.includes(" ") || p.value.includes("\n") || p.value.includes("{") || hasGlobOrEscape(p.value, true))) return false;
81930
+ arg += p.value;
81445
81931
  }
81446
81932
  args.push(arg);
81447
81933
  }
@@ -81452,6 +81938,15 @@ ${s1}
81452
81938
  if (!p02 || p02.kind !== "text" || p02.value.length === 0 || p02.value.startsWith("-")) return false;
81453
81939
  return w.parts.every((p) => p.kind === "text" || p.kind === "variable" && !p.indirect && !p.prefixNames && !p.length && !p.substring && p.operator === void 0 && getArraySelector(p) === void 0);
81454
81940
  }
81941
+ syncStringLength(value2, byteCount2) {
81942
+ let length = 0;
81943
+ for (let offset = 0; offset < value2.length; ) {
81944
+ const point = value2.codePointAt(offset);
81945
+ length += byteCount2 ? point <= 127 ? 1 : point <= 2047 ? 2 : point <= 65535 ? 3 : 4 : 1;
81946
+ offset += point > 65535 ? 2 : 1;
81947
+ }
81948
+ return length;
81949
+ }
81455
81950
  execSyncReadHereStringStep(rs, step, rawState, io, monitor, touched) {
81456
81951
  const rawInput = this.fastValueWord(rs.inputWord, rawState, io, false, false, false, false, 0, step.line);
81457
81952
  const delim = rs.delimChar ?? "\n";
@@ -81459,15 +81954,16 @@ ${s1}
81459
81954
  let status2 = 0;
81460
81955
  if (rs.maxChars !== void 0) {
81461
81956
  const fullInput = rawInput + "\n";
81462
- if (rs.exactChars) {
81463
- lineStr = fullInput.length > rs.maxChars ? fullInput.slice(0, rs.maxChars) : fullInput;
81464
- status2 = fullInput.length >= rs.maxChars ? 0 : 1;
81465
- } else {
81466
- const nlIdx = fullInput.indexOf(delim);
81467
- const untilDelim = nlIdx === -1 ? fullInput : fullInput.slice(0, nlIdx);
81468
- lineStr = untilDelim.length > rs.maxChars ? untilDelim.slice(0, rs.maxChars) : untilDelim;
81469
- status2 = nlIdx !== -1 || fullInput.length >= rs.maxChars ? 0 : 1;
81957
+ const nlIdx = rs.exactChars ? -1 : fullInput.indexOf(delim);
81958
+ const end = nlIdx === -1 ? fullInput.length : nlIdx;
81959
+ let position = 0;
81960
+ let count2 = 0;
81961
+ while (position < end && count2 < rs.maxChars) {
81962
+ position = nextCodePointOffset(fullInput, position);
81963
+ count2++;
81470
81964
  }
81965
+ lineStr = fullInput.slice(0, position);
81966
+ status2 = count2 >= rs.maxChars || nlIdx !== -1 ? 0 : 1;
81471
81967
  } else {
81472
81968
  const fullInput = delim === "\n" ? rawInput : rawInput + "\n";
81473
81969
  const nlIdx = rs.isMapfile ? -1 : fullInput.indexOf(delim);
@@ -88198,7 +88694,7 @@ ${prefix3} line ${offset + line}: \`${source2.split("\n")[line - 1] ?? ""}'
88198
88694
  invalid = true;
88199
88695
  break;
88200
88696
  }
88201
- if (flag === "n" || flag === "N") exact = flag === "N";
88697
+ if (flag === "N") exact = true;
88202
88698
  const value2 = option.slice(index + 1) || names.shift();
88203
88699
  if (value2 === void 0) invalid = true;
88204
88700
  else if (flag === "p") {
@@ -88603,7 +89099,7 @@ ${prefix3} line ${offset + line}: \`${source2.split("\n")[line - 1] ?? ""}'
88603
89099
  }
88604
89100
  if (part.kind === "variable" && part.prefixNames) {
88605
89101
  const ifs = state.variables.IFS ?? " ";
88606
- const separator = io.nameExpansionContext === "document" || io.nameExpansionContext === "conditional" && part.prefixNames === "@" ? " " : ifs.length ? String.fromCodePoint(ifs.codePointAt(0)) : "";
89102
+ const separator = io.nameExpansionContext === "document" || part.prefixNames === "@" && (io.nameExpansionContext === "conditional" || ifs.length === 0) ? " " : ifs.length ? String.fromCodePoint(ifs.codePointAt(0)) : "";
88607
89103
  const fragments2 = [];
88608
89104
  let bytes2 = 0;
88609
89105
  for await (const name2 of this.prefixNames(part.name, state)) {
@@ -89432,7 +89928,7 @@ ${prefix3} line ${offset + line}: \`${source2.split("\n")[line - 1] ?? ""}'
89432
89928
  const pNames = this.collectSyncPrefixNames(part.name, rawState);
89433
89929
  if (pNames === void 0) return void 0;
89434
89930
  const ifs = rawState.variables.IFS ?? " ";
89435
- const sep = io.nameExpansionContext === "document" || io.nameExpansionContext === "conditional" && part.prefixNames === "@" ? " " : ifs.length ? String.fromCodePoint(ifs.codePointAt(0)) : "";
89931
+ const sep = io.nameExpansionContext === "document" || part.prefixNames === "@" && (io.nameExpansionContext === "conditional" || ifs.length === 0) ? " " : ifs.length ? String.fromCodePoint(ifs.codePointAt(0)) : "";
89436
89932
  const joined = pNames.join(sep);
89437
89933
  if (split3 && !part.quoted) {
89438
89934
  if (joined.length === 0 || joined.includes(" ") || joined.includes(" ") || joined.includes("\n")) return void 0;
@@ -89674,10 +90170,7 @@ ${prefix3} line ${offset + line}: \`${source2.split("\n")[line - 1] ?? ""}'
89674
90170
  if (part.length) {
89675
90171
  if (part.operator !== void 0) return void 0;
89676
90172
  const s = elemVal ?? "";
89677
- for (let k = 0; k < s.length; k++) {
89678
- if (s.charCodeAt(k) >= 128) return void 0;
89679
- }
89680
- out += String(s.length);
90173
+ out += String(this.syncStringLength(s, byteLocale(rawVars)));
89681
90174
  continue;
89682
90175
  }
89683
90176
  let resolvedElem;
@@ -89783,10 +90276,7 @@ ${prefix3} line ${offset + line}: \`${source2.split("\n")[line - 1] ?? ""}'
89783
90276
  this.requireParameter(raw2, part.name, state, io, part.line ?? overrideDiagnosticLine);
89784
90277
  const val2 = raw2 === void 0 ? "" : this._syncArithRawWriteOnly && this._syncArithTouched?.has(part.name) ? raw2 : monitor?.values.get(part.name, raw2) ?? raw2;
89785
90278
  if (typeof val2 !== "string") return void 0;
89786
- for (let k = 0; k < val2.length; k++) {
89787
- if (val2.charCodeAt(k) >= 128) return void 0;
89788
- }
89789
- out += String(val2.length);
90279
+ out += String(this.syncStringLength(val2, byteLocale(rawVars)));
89790
90280
  continue;
89791
90281
  }
89792
90282
  if (part.operator !== void 0) {
@@ -90021,6 +90511,7 @@ ${prefix3} line ${offset + line}: \`${source2.split("\n")[line - 1] ?? ""}'
90021
90511
  }
90022
90512
  expandSyncTrCharArray(spec) {
90023
90513
  if (spec.length === 0) return void 0;
90514
+ if (spec.includes("\\") && spec.includes("-")) return void 0;
90024
90515
  const posixClasses = {
90025
90516
  "[:lower:]": "abcdefghijklmnopqrstuvwxyz",
90026
90517
  "[:upper:]": "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
@@ -90052,7 +90543,15 @@ ${prefix3} line ${offset + line}: \`${source2.split("\n")[line - 1] ?? ""}'
90052
90543
  else if (next === "t") out.push(" ");
90053
90544
  else if (next === "r") out.push("\r");
90054
90545
  else if (next === "\\") out.push("\\");
90055
- else return void 0;
90546
+ else if (next >= "0" && next <= "7") {
90547
+ let oct = next;
90548
+ while (oct.length < 3 && i + 1 < spec.length && spec[i + 1] >= "0" && spec[i + 1] <= "7") {
90549
+ oct += spec[++i];
90550
+ }
90551
+ const code = parseInt(oct, 8);
90552
+ if (code <= 0 || code >= 128) return void 0;
90553
+ out.push(String.fromCharCode(code));
90554
+ } else return void 0;
90056
90555
  continue;
90057
90556
  }
90058
90557
  if (i + 2 < spec.length && spec[i + 1] === "-" && spec[i + 2] !== "\\") {
@@ -90070,11 +90569,107 @@ ${prefix3} line ${offset + line}: \`${source2.split("\n")[line - 1] ?? ""}'
90070
90569
  return out;
90071
90570
  }
90072
90571
  evalSyncTr(input3, opArgs) {
90073
- if (opArgs.length === 2 && !opArgs[0].startsWith("-") && !opArgs[1].startsWith("-")) {
90074
- return this.translateSyncTr(input3, opArgs[0], opArgs[1]);
90572
+ let idx = 0;
90573
+ let flagC = false;
90574
+ let flagD = false;
90575
+ let flagS = false;
90576
+ let flagT = false;
90577
+ while (idx < opArgs.length) {
90578
+ const a = opArgs[idx];
90579
+ if (a === "--") {
90580
+ idx++;
90581
+ break;
90582
+ }
90583
+ if (!a.startsWith("-") || a === "-") break;
90584
+ if (!/^-[cCdst]+$/.test(a)) return void 0;
90585
+ for (let k = 1; k < a.length; k++) {
90586
+ const ch = a[k];
90587
+ if (ch === "c" || ch === "C") flagC = true;
90588
+ else if (ch === "d") flagD = true;
90589
+ else if (ch === "s") flagS = true;
90590
+ else if (ch === "t") flagT = true;
90591
+ }
90592
+ idx++;
90593
+ }
90594
+ if (flagT && flagC) return void 0;
90595
+ const sets = opArgs.slice(idx);
90596
+ if (flagC) {
90597
+ if (sets.some((s) => {
90598
+ for (let i = 0; i < s.length; i++) if (s.charCodeAt(i) >= 128) return true;
90599
+ return false;
90600
+ })) return void 0;
90601
+ if (flagD && !flagS && sets.length === 1) {
90602
+ const arr = this.expandSyncTrCharArray(sets[0]);
90603
+ if (!arr) return void 0;
90604
+ const keepSet = new Set(arr);
90605
+ let out = "";
90606
+ for (let i = 0; i < input3.length; i++) {
90607
+ const ch = input3[i];
90608
+ if (keepSet.has(ch)) out += ch;
90609
+ }
90610
+ return out;
90611
+ }
90612
+ if (!flagD && sets.length === 2) {
90613
+ if (sets[1].includes("[:")) return void 0;
90614
+ const arr1 = this.expandSyncTrCharArray(sets[0]);
90615
+ const arr2 = this.expandSyncTrCharArray(sets[1]);
90616
+ if (!arr1 || !arr2 || arr2.length !== 1) return void 0;
90617
+ const keepSet = new Set(arr1);
90618
+ const repl = arr2[arr2.length - 1];
90619
+ const sqSet = flagS ? new Set(arr2) : void 0;
90620
+ let hasNonAscii = false;
90621
+ for (let i = 0; i < input3.length; i++) {
90622
+ if (input3.charCodeAt(i) >= 128) {
90623
+ hasNonAscii = true;
90624
+ break;
90625
+ }
90626
+ }
90627
+ let out = "";
90628
+ let prev = "";
90629
+ if (hasNonAscii) {
90630
+ const bytes2 = fastSharedTextEncoder.encode(input3);
90631
+ for (let i = 0; i < bytes2.length; i++) {
90632
+ const rawCh = String.fromCharCode(bytes2[i]);
90633
+ const ch = keepSet.has(rawCh) ? rawCh : repl;
90634
+ if (sqSet && sqSet.has(ch) && ch === prev) continue;
90635
+ out += ch;
90636
+ prev = ch;
90637
+ }
90638
+ } else {
90639
+ for (let i = 0; i < input3.length; i++) {
90640
+ const rawCh = input3[i];
90641
+ const ch = keepSet.has(rawCh) ? rawCh : repl;
90642
+ if (sqSet && sqSet.has(ch) && ch === prev) continue;
90643
+ out += ch;
90644
+ prev = ch;
90645
+ }
90646
+ }
90647
+ return out;
90648
+ }
90649
+ if (flagD && flagS && sets.length === 2) {
90650
+ const arr1 = this.expandSyncTrCharArray(sets[0]);
90651
+ const arr2 = this.expandSyncTrCharArray(sets[1]);
90652
+ if (!arr1 || !arr2) return void 0;
90653
+ const keepSet = new Set(arr1);
90654
+ const sqSet = new Set(arr2);
90655
+ let out = "";
90656
+ let prev = "";
90657
+ for (let i = 0; i < input3.length; i++) {
90658
+ const ch = input3[i];
90659
+ if (!keepSet.has(ch)) continue;
90660
+ if (sqSet.has(ch) && ch === prev) continue;
90661
+ out += ch;
90662
+ prev = ch;
90663
+ }
90664
+ return out;
90665
+ }
90666
+ return void 0;
90667
+ }
90668
+ if (!flagD && !flagS && sets.length === 2) {
90669
+ return this.translateSyncTr(input3, sets[0], sets[1], flagT);
90075
90670
  }
90076
- if (opArgs.length === 2 && opArgs[0] === "-d" && !opArgs[1].startsWith("-")) {
90077
- const arr = this.expandSyncTrCharArray(opArgs[1]);
90671
+ if (flagD && !flagS && sets.length === 1) {
90672
+ const arr = this.expandSyncTrCharArray(sets[0]);
90078
90673
  if (!arr) return void 0;
90079
90674
  const delSet = new Set(arr);
90080
90675
  let out = "";
@@ -90084,8 +90679,8 @@ ${prefix3} line ${offset + line}: \`${source2.split("\n")[line - 1] ?? ""}'
90084
90679
  }
90085
90680
  return out;
90086
90681
  }
90087
- if (opArgs.length === 2 && opArgs[0] === "-s" && !opArgs[1].startsWith("-")) {
90088
- const arr = this.expandSyncTrCharArray(opArgs[1]);
90682
+ if (!flagD && flagS && sets.length === 1) {
90683
+ const arr = this.expandSyncTrCharArray(sets[0]);
90089
90684
  if (!arr) return void 0;
90090
90685
  const sqSet = new Set(arr);
90091
90686
  let out = "";
@@ -90098,110 +90693,516 @@ ${prefix3} line ${offset + line}: \`${source2.split("\n")[line - 1] ?? ""}'
90098
90693
  }
90099
90694
  return out;
90100
90695
  }
90101
- if (opArgs.length === 3 && (opArgs[0] === "-s" || opArgs[0] === "-ds" || opArgs[0] === "-sd") && !opArgs[1].startsWith("-") && !opArgs[2].startsWith("-")) {
90102
- const stage1 = opArgs[0] === "-s" ? this.translateSyncTr(input3, opArgs[1], opArgs[2]) : this.evalSyncTr(input3, ["-d", opArgs[1]]);
90696
+ if (sets.length === 2 && (flagS || flagD)) {
90697
+ const stage1 = !flagD ? this.translateSyncTr(input3, sets[0], sets[1], flagT) : this.evalSyncTr(input3, ["-d", sets[0]]);
90103
90698
  if (stage1 === void 0) return void 0;
90104
- return this.evalSyncTr(stage1, ["-s", opArgs[2]]);
90699
+ return this.evalSyncTr(stage1, ["-s", sets[1]]);
90105
90700
  }
90106
90701
  return void 0;
90107
90702
  }
90703
+ evalSyncJqPathOps(item, expr) {
90704
+ let st = expr.trim();
90705
+ let alternatives = splitSyncJqExpression(st, "//");
90706
+ if (!alternatives) return void 0;
90707
+ while (alternatives.wrapped) {
90708
+ st = st.slice(1, -1).trim();
90709
+ alternatives = splitSyncJqExpression(st, "//");
90710
+ if (!alternatives) return void 0;
90711
+ }
90712
+ if (alternatives.parts.length > 1) {
90713
+ const lhs = alternatives.parts[0];
90714
+ const rhs = alternatives.parts.slice(1).join("//");
90715
+ const lVals = this.evalSyncJqPathOps(item, lhs);
90716
+ if (lVals === void 0) return void 0;
90717
+ let rVals = this.evalSyncJqPathOps(item, rhs);
90718
+ if (rVals === void 0) {
90719
+ try {
90720
+ rVals = [JSON.parse(rhs)];
90721
+ } catch {
90722
+ return void 0;
90723
+ }
90724
+ }
90725
+ const truthy = lVals.filter((v) => v !== null && v !== void 0 && v !== false);
90726
+ return truthy.length > 0 ? truthy : rVals;
90727
+ }
90728
+ const pipeSplit = splitSyncJqExpression(st, "|");
90729
+ if (pipeSplit && pipeSplit.parts.length > 1) {
90730
+ let cur2 = [item];
90731
+ for (const pStage of pipeSplit.parts) {
90732
+ const next = [];
90733
+ for (const it of cur2) {
90734
+ const r = this.evalSyncJqPathOps(it, pStage);
90735
+ if (r === void 0) return void 0;
90736
+ for (const rv of r) next.push(rv);
90737
+ }
90738
+ cur2 = next;
90739
+ }
90740
+ return cur2;
90741
+ }
90742
+ if (st === ".") return [item];
90743
+ const dotArithM = /^\.\s*([+*\/%-])\s*(-?[0-9]+(?:\.[0-9]+)?)$/.exec(st);
90744
+ if (dotArithM && typeof item === "number") {
90745
+ const op = dotArithM[1];
90746
+ const rhs = Number(dotArithM[2]);
90747
+ if ((op === "/" || op === "%") && rhs === 0) return void 0;
90748
+ return [op === "+" ? item + rhs : op === "-" ? item - rhs : op === "*" ? item * rhs : op === "/" ? item / rhs : item % rhs];
90749
+ }
90750
+ if (st === "floor") return typeof item === "number" ? [Math.floor(item)] : void 0;
90751
+ if (st === "ceil") return typeof item === "number" ? [Math.ceil(item)] : void 0;
90752
+ if (st === "round") return typeof item === "number" ? [Math.round(item)] : void 0;
90753
+ if (st === "abs") return typeof item === "number" ? [Math.abs(item)] : void 0;
90754
+ if (st === "utf8bytelength") return typeof item === "string" ? [import_buffer.Buffer.byteLength(item, "utf8")] : void 0;
90755
+ if (st === "explode") return typeof item === "string" ? [Array.from(item, (c) => c.codePointAt(0))] : void 0;
90756
+ if (st === "implode") {
90757
+ if (!Array.isArray(item) || !item.every((x) => typeof x === "number" && Number.isInteger(x) && x >= 0 && x <= 1114111)) return void 0;
90758
+ return [String.fromCodePoint(...item)];
90759
+ }
90760
+ if (st === "transpose") {
90761
+ if (!Array.isArray(item) || !item.every((row) => Array.isArray(row))) return void 0;
90762
+ const rows = item;
90763
+ const maxCols = rows.reduce((m, r) => Math.max(m, r.length), 0);
90764
+ const trans = [];
90765
+ for (let c = 0; c < maxCols; c++) {
90766
+ trans.push(rows.map((r) => c < r.length ? r[c] : null));
90767
+ }
90768
+ return [trans];
90769
+ }
90770
+ const idxFnM = /^(index|rindex|indices)\(\s*"([^"\\]*)"\s*\)$/.exec(st);
90771
+ if (idxFnM && typeof item === "string") {
90772
+ const fn = idxFnM[1];
90773
+ const sub = idxFnM[2];
90774
+ const found = [];
90775
+ if (sub.length > 0) {
90776
+ let pos = 0;
90777
+ while ((pos = item.indexOf(sub, pos)) !== -1) {
90778
+ found.push(Array.from(item.slice(0, pos)).length);
90779
+ pos += 1;
90780
+ }
90781
+ }
90782
+ if (fn === "indices") return [found];
90783
+ if (fn === "index") return [found.length > 0 ? found[0] : null];
90784
+ return [found.length > 0 ? found[found.length - 1] : null];
90785
+ }
90786
+ if (st === "length") {
90787
+ if (item === null || item === void 0) return [0];
90788
+ if (typeof item === "string") return [Array.from(item).length];
90789
+ if (typeof item === "number") return [Math.abs(item)];
90790
+ if (Array.isArray(item)) return [item.length];
90791
+ if (typeof item === "object") return [Object.keys(item).length];
90792
+ return void 0;
90793
+ }
90794
+ if (st === "keys") {
90795
+ if (Array.isArray(item)) return [item.map((_, idx) => idx)];
90796
+ if (item && typeof item === "object") return [Object.keys(item).sort()];
90797
+ return void 0;
90798
+ }
90799
+ if (st === "keys[]") {
90800
+ if (Array.isArray(item)) return item.map((_, idx) => idx);
90801
+ if (item && typeof item === "object") return Object.keys(item).sort();
90802
+ return void 0;
90803
+ }
90804
+ if (st === "values") {
90805
+ return item === null || item === void 0 ? [] : [item];
90806
+ }
90807
+ if (st === "empty") return [];
90808
+ if (st === "not") return [!(item !== false && item !== null && item !== void 0)];
90809
+ if (st === "any") return Array.isArray(item) ? [item.some((x) => x !== false && x !== null && x !== void 0)] : void 0;
90810
+ if (st === "all") return Array.isArray(item) ? [item.every((x) => x !== false && x !== null && x !== void 0)] : void 0;
90811
+ if (st === "keys_unsorted") {
90812
+ if (Array.isArray(item)) return [item.map((_, idx) => idx)];
90813
+ if (item && typeof item === "object") return [Object.keys(item)];
90814
+ return void 0;
90815
+ }
90816
+ if (st === "flatten") return Array.isArray(item) ? [item.flat(Infinity)] : void 0;
90817
+ const flatM = /^flatten\(\s*([0-9]{1,2})\s*\)$/.exec(st);
90818
+ if (flatM) return Array.isArray(item) ? [item.flat(Number(flatM[1]))] : void 0;
90819
+ if (st === "sort") {
90820
+ if (!Array.isArray(item)) return void 0;
90821
+ if (item.every((x) => typeof x === "number")) return [[...item].sort((a, b) => a - b)];
90822
+ if (item.every((x) => typeof x === "string")) return [[...item].sort()];
90823
+ return void 0;
90824
+ }
90825
+ if (st === "tojson") return [JSON.stringify(item)];
90826
+ if (st === "fromjson") {
90827
+ if (typeof item !== "string") return void 0;
90828
+ try {
90829
+ return [JSON.parse(item)];
90830
+ } catch {
90831
+ return void 0;
90832
+ }
90833
+ }
90834
+ const mvM = /^map_values\(\s*(.+)\s*\)$/.exec(st);
90835
+ if (mvM && item && typeof item === "object") {
90836
+ const subExpr = mvM[1];
90837
+ if (Array.isArray(item)) {
90838
+ const outArr = [];
90839
+ for (const el of item) {
90840
+ const r = this.evalSyncJqPathOps(el, subExpr);
90841
+ if (!r || r.length !== 1) return void 0;
90842
+ outArr.push(r[0]);
90843
+ }
90844
+ return [outArr];
90845
+ }
90846
+ const outObj = {};
90847
+ for (const [k, v] of Object.entries(item)) {
90848
+ const r = this.evalSyncJqPathOps(v, subExpr);
90849
+ if (!r || r.length !== 1) return void 0;
90850
+ outObj[k] = r[0];
90851
+ }
90852
+ return [outObj];
90853
+ }
90854
+ const byM = /^(sort_by|unique_by|group_by|min_by|max_by)\(\s*(\.[a-zA-Z_][a-zA-Z0-9_.]*)\s*\)$/.exec(st);
90855
+ if (byM && Array.isArray(item)) {
90856
+ const fn = byM[1];
90857
+ const kPath = byM[2];
90858
+ const keyed = [];
90859
+ for (const el of item) {
90860
+ const kv = this.evalSyncJqPathOps(el, kPath);
90861
+ if (!kv || kv.length !== 1) return void 0;
90862
+ const k0 = kv[0];
90863
+ if (typeof k0 !== "string" && typeof k0 !== "number" && typeof k0 !== "boolean" && k0 !== null) return void 0;
90864
+ keyed.push({ el, k: k0 });
90865
+ }
90866
+ const cmpK = (a, b) => {
90867
+ const rank2 = (value2) => value2 === null ? 0 : value2 === false ? 1 : value2 === true ? 2 : typeof value2 === "number" ? 3 : 4;
90868
+ const typeOrder = rank2(a) - rank2(b);
90869
+ if (typeOrder !== 0) return typeOrder;
90870
+ if (typeof a === "number" && typeof b === "number") return a - b;
90871
+ const sa = String(a);
90872
+ const sb = String(b);
90873
+ return sa < sb ? -1 : sa > sb ? 1 : 0;
90874
+ };
90875
+ keyed.sort((a, b) => cmpK(a.k, b.k));
90876
+ if (fn === "min_by") return [keyed.length > 0 ? keyed[0].el : null];
90877
+ if (fn === "max_by") return [keyed.length > 0 ? keyed[keyed.length - 1].el : null];
90878
+ if (fn === "sort_by") return [keyed.map((p) => p.el)];
90879
+ if (fn === "unique_by") {
90880
+ const u = [];
90881
+ for (let i = 0; i < keyed.length; i++) {
90882
+ if (i === 0 || cmpK(keyed[i].k, keyed[i - 1].k) !== 0) u.push(keyed[i].el);
90883
+ }
90884
+ return [u];
90885
+ }
90886
+ const groups = [];
90887
+ for (let i = 0; i < keyed.length; i++) {
90888
+ if (i === 0 || cmpK(keyed[i].k, keyed[i - 1].k) !== 0) groups.push([keyed[i].el]);
90889
+ else groups[groups.length - 1].push(keyed[i].el);
90890
+ }
90891
+ return [groups];
90892
+ }
90893
+ if (st === "first") {
90894
+ return Array.isArray(item) ? [item.length > 0 ? item[0] : null] : void 0;
90895
+ }
90896
+ if (st === "last") {
90897
+ return Array.isArray(item) ? [item.length > 0 ? item[item.length - 1] : null] : void 0;
90898
+ }
90899
+ if (st === "reverse") {
90900
+ return Array.isArray(item) ? [[...item].reverse()] : void 0;
90901
+ }
90902
+ if (st === "unique") return void 0;
90903
+ if (st === "add") {
90904
+ if (!Array.isArray(item)) return void 0;
90905
+ if (item.length === 0) return [null];
90906
+ if (item.every((x) => typeof x === "number")) return [item.reduce((a, b) => a + b, 0)];
90907
+ if (item.every((x) => typeof x === "string")) return [item.join("")];
90908
+ if (item.every((x) => Array.isArray(x))) return [item.flat()];
90909
+ return void 0;
90910
+ }
90911
+ if (st === "min" || st === "max") {
90912
+ if (!Array.isArray(item)) return void 0;
90913
+ if (item.length === 0) return [null];
90914
+ if (item.every((x) => typeof x === "number")) {
90915
+ return [st === "min" ? Math.min(...item) : Math.max(...item)];
90916
+ }
90917
+ if (item.every((x) => typeof x === "string")) {
90918
+ const sorted = [...item].sort();
90919
+ return [st === "min" ? sorted[0] : sorted[sorted.length - 1]];
90920
+ }
90921
+ return void 0;
90922
+ }
90923
+ if (st === "to_entries") {
90924
+ if (item && typeof item === "object" && !Array.isArray(item)) {
90925
+ return [Object.entries(item).map(([key, value2]) => ({ key, value: value2 }))];
90926
+ }
90927
+ return void 0;
90928
+ }
90929
+ if (st === "from_entries") {
90930
+ if (!Array.isArray(item)) return void 0;
90931
+ const obj = {};
90932
+ for (const el of item) {
90933
+ if (!el || typeof el !== "object" || Array.isArray(el)) return void 0;
90934
+ const rec = el;
90935
+ const k = rec.key ?? rec.name ?? rec.k;
90936
+ if (typeof k !== "string") return void 0;
90937
+ obj[k] = Object.hasOwn(rec, "value") ? rec.value : Object.hasOwn(rec, "v") ? rec.v : null;
90938
+ }
90939
+ return [obj];
90940
+ }
90941
+ if (st === "tonumber") {
90942
+ if (typeof item === "number") return [item];
90943
+ if (typeof item === "string" && /^[ \t]*[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?[ \t]*$/.test(item)) return [Number(item)];
90944
+ return void 0;
90945
+ }
90946
+ if (st === "tostring") {
90947
+ return [typeof item === "string" ? item : JSON.stringify(item)];
90948
+ }
90949
+ if (st === "type") {
90950
+ return [item === null ? "null" : Array.isArray(item) ? "array" : typeof item];
90951
+ }
90952
+ if (st === "ascii_upcase") {
90953
+ return typeof item === "string" ? [item.replace(/[a-z]/g, (ch) => String.fromCharCode(ch.charCodeAt(0) - 32))] : void 0;
90954
+ }
90955
+ if (st === "ascii_downcase") {
90956
+ return typeof item === "string" ? [item.replace(/[A-Z]/g, (ch) => String.fromCharCode(ch.charCodeAt(0) + 32))] : void 0;
90957
+ }
90958
+ const strFnM = /^(join|split|ltrimstr|rtrimstr|startswith|endswith|contains)\(\s*"([^"\\]*)"\s*\)$/.exec(st);
90959
+ if (strFnM) {
90960
+ const fn = strFnM[1];
90961
+ const arg = strFnM[2];
90962
+ if (fn === "join") {
90963
+ if (!Array.isArray(item) || !item.every((x) => typeof x === "string" || typeof x === "number" || typeof x === "boolean" || x === null)) return void 0;
90964
+ return [item.map((x) => x === null ? "" : String(x)).join(arg)];
90965
+ }
90966
+ if (fn === "split") return typeof item === "string" ? [item.split(arg)] : void 0;
90967
+ if (fn === "ltrimstr") return typeof item === "string" ? [item.startsWith(arg) ? item.slice(arg.length) : item] : void 0;
90968
+ if (fn === "rtrimstr") return typeof item === "string" ? [arg.length > 0 && item.endsWith(arg) ? item.slice(0, -arg.length) : item] : void 0;
90969
+ if (fn === "startswith") return typeof item === "string" ? [item.startsWith(arg)] : void 0;
90970
+ if (fn === "endswith") return typeof item === "string" ? [item.endsWith(arg)] : void 0;
90971
+ if (fn === "contains") {
90972
+ if (typeof item === "string") return [item.includes(arg)];
90973
+ return void 0;
90974
+ }
90975
+ }
90976
+ const hasM = /^has\(\s*"([^"\\]+)"\s*\)$/.exec(st);
90977
+ if (hasM) {
90978
+ if (item && typeof item === "object" && !Array.isArray(item)) return [Object.hasOwn(item, hasM[1])];
90979
+ return void 0;
90980
+ }
90981
+ const mapM = /^map\(\s*(.+)\s*\)$/.exec(st);
90982
+ if (mapM) {
90983
+ if (!Array.isArray(item)) return void 0;
90984
+ const mapped = [];
90985
+ for (const el of item) {
90986
+ const subRes = this.evalSyncJqPathOps(el, mapM[1]);
90987
+ if (subRes === void 0) return void 0;
90988
+ for (const v of subRes) mapped.push(v);
90989
+ }
90990
+ return [mapped];
90991
+ }
90992
+ const selM = /^select\(\s*(\.[a-zA-Z_][a-zA-Z0-9_.]*)\s*(?:(==|!=|>=|<=|>|<)\s*(.+))?\s*\)$/.exec(st);
90993
+ if (selM) {
90994
+ const fVals = this.evalSyncJqPathOps(item, selM[1]);
90995
+ if (!fVals || fVals.length !== 1) return void 0;
90996
+ const lv = fVals[0];
90997
+ if (!selM[2]) {
90998
+ return lv !== null && lv !== void 0 && lv !== false ? [item] : [];
90999
+ }
91000
+ let rv;
91001
+ try {
91002
+ rv = JSON.parse(selM[3].trim());
91003
+ } catch {
91004
+ return void 0;
91005
+ }
91006
+ if (typeof lv === "object" && lv !== null || typeof rv === "object" && rv !== null) return void 0;
91007
+ const op = selM[2];
91008
+ let ok = false;
91009
+ if (op === "==") ok = lv === rv;
91010
+ else if (op === "!=") ok = lv !== rv;
91011
+ else if (typeof lv === "number" && typeof rv === "number") {
91012
+ if (op === ">") ok = lv > rv;
91013
+ else if (op === ">=") ok = lv >= rv;
91014
+ else if (op === "<") ok = lv < rv;
91015
+ else if (op === "<=") ok = lv <= rv;
91016
+ } else return void 0;
91017
+ return ok ? [item] : [];
91018
+ }
91019
+ if (!st.startsWith(".")) return void 0;
91020
+ let rest = st.slice(1);
91021
+ const ops = [];
91022
+ while (rest.length > 0) {
91023
+ if (rest.startsWith(".")) rest = rest.slice(1);
91024
+ const propM = /^([a-zA-Z_][a-zA-Z0-9_]*)/.exec(rest);
91025
+ if (propM) {
91026
+ ops.push({ kind: "prop", key: propM[1] });
91027
+ rest = rest.slice(propM[1].length);
91028
+ continue;
91029
+ }
91030
+ if (rest.startsWith("[]")) {
91031
+ ops.push({ kind: "iter" });
91032
+ rest = rest.slice(2);
91033
+ continue;
91034
+ }
91035
+ const idxM = /^\[(-?[0-9]+)\]/.exec(rest);
91036
+ if (idxM) {
91037
+ ops.push({ kind: "index", idx: Number(idxM[1]) });
91038
+ rest = rest.slice(idxM[0].length);
91039
+ continue;
91040
+ }
91041
+ return void 0;
91042
+ }
91043
+ let cur = [item];
91044
+ for (const op of ops) {
91045
+ const next = [];
91046
+ for (const it of cur) {
91047
+ if (op.kind === "prop") {
91048
+ if (it === null || it === void 0) next.push(null);
91049
+ else if (typeof it === "object" && !Array.isArray(it)) next.push(Object.hasOwn(it, op.key) ? it[op.key] ?? null : null);
91050
+ else return void 0;
91051
+ } else if (op.kind === "index") {
91052
+ if (it === null || it === void 0) next.push(null);
91053
+ else if (Array.isArray(it)) {
91054
+ const i = op.idx < 0 ? it.length + op.idx : op.idx;
91055
+ next.push(i >= 0 && i < it.length ? it[i] : null);
91056
+ } else return void 0;
91057
+ } else if (op.kind === "iter") {
91058
+ if (Array.isArray(it)) {
91059
+ for (const el of it) next.push(el);
91060
+ } else if (it && typeof it === "object") {
91061
+ for (const k of Object.keys(it)) next.push(it[k]);
91062
+ } else return void 0;
91063
+ }
91064
+ }
91065
+ cur = next;
91066
+ }
91067
+ return cur;
91068
+ }
90108
91069
  evalSyncJq(input3, opArgs) {
90109
91070
  let rawOut = false;
91071
+ let compactOut = false;
90110
91072
  let filter;
90111
91073
  if (opArgs.length === 1 && !opArgs[0].startsWith("-")) {
90112
91074
  filter = opArgs[0];
90113
91075
  } else if (opArgs.length === 2 && (opArgs[0] === "-r" || opArgs[0] === "--raw-output" || opArgs[0] === "-c" || opArgs[0] === "--compact-output" || opArgs[0] === "-rc" || opArgs[0] === "-cr")) {
90114
- rawOut = opArgs[0].includes("r");
91076
+ rawOut = ["-r", "-rc", "-cr", "--raw-output"].includes(opArgs[0]);
91077
+ compactOut = ["-c", "-rc", "-cr", "--compact-output"].includes(opArgs[0]);
90115
91078
  filter = opArgs[1];
90116
91079
  }
90117
91080
  if (!filter) return void 0;
90118
- const stages = filter.split("|").map((s) => s.trim());
90119
- const compiledStages = [];
90120
- for (const st of stages) {
90121
- if (st === ".") {
90122
- compiledStages.push([]);
90123
- continue;
91081
+ let current = [];
91082
+ try {
91083
+ current = [JSON.parse(input3)];
91084
+ } catch {
91085
+ if (!input3.includes("\n")) return void 0;
91086
+ try {
91087
+ for (const line of input3.split("\n")) {
91088
+ const t = line.trim();
91089
+ if (t.length > 0) current.push(JSON.parse(t));
91090
+ }
91091
+ if (current.length === 0) return void 0;
91092
+ } catch {
91093
+ return void 0;
90124
91094
  }
90125
- if (st === "length") {
90126
- compiledStages.push([{ kind: "length" }]);
90127
- continue;
91095
+ }
91096
+ const trimmedFilter = filter.trim();
91097
+ if (trimmedFilter.startsWith("[") && trimmedFilter.endsWith("]")) {
91098
+ const innerFilter = trimmedFilter.slice(1, -1).trim();
91099
+ const innerArgs = rawOut || compactOut ? [compactOut ? "-c" : "-r", innerFilter] : [innerFilter];
91100
+ const outArrays = [];
91101
+ for (const item of current) {
91102
+ const innerStages = splitSyncJqExpression(innerFilter, "|");
91103
+ if (!innerStages) return void 0;
91104
+ let subCur = [item];
91105
+ for (const st of innerStages.parts) {
91106
+ const commas = splitSyncJqExpression(st, ",");
91107
+ if (!commas) return void 0;
91108
+ const commaParts = commas.parts;
91109
+ const next = [];
91110
+ for (const it of subCur) {
91111
+ for (const part of commaParts) {
91112
+ const res = this.evalSyncJqPathOps(it, part);
91113
+ if (res === void 0) return void 0;
91114
+ for (const v of res) next.push(v);
91115
+ }
91116
+ }
91117
+ subCur = next;
91118
+ }
91119
+ outArrays.push(subCur);
91120
+ }
91121
+ void innerArgs;
91122
+ return outArrays.map((val) => JSON.stringify(val ?? null, null, compactOut ? void 0 : 2));
91123
+ }
91124
+ const stages = splitSyncJqExpression(filter, "|");
91125
+ if (!stages) return void 0;
91126
+ for (const st of stages.parts) {
91127
+ const commas = splitSyncJqExpression(st, ",");
91128
+ if (!commas) return void 0;
91129
+ const commaParts = commas.parts;
91130
+ const next = [];
91131
+ for (const item of current) {
91132
+ for (const part of commaParts) {
91133
+ const res = this.evalSyncJqPathOps(item, part);
91134
+ if (res === void 0) return void 0;
91135
+ for (const v of res) next.push(v);
91136
+ }
90128
91137
  }
90129
- if (st === "keys") {
90130
- compiledStages.push([{ kind: "keys" }]);
90131
- continue;
91138
+ current = next;
91139
+ }
91140
+ return current.map((val) => rawOut && typeof val === "string" ? val : JSON.stringify(val ?? null, null, compactOut ? void 0 : 2));
91141
+ }
91142
+ evalSyncDirname(args) {
91143
+ let idx = 0;
91144
+ if (args[0] === "--") idx = 1;
91145
+ else if (args[0] !== void 0 && args[0].startsWith("-") && args[0] !== "-") return void 0;
91146
+ if (idx >= args.length) return void 0;
91147
+ const out = [];
91148
+ for (let i = idx; i < args.length; i++) {
91149
+ const p = args[i];
91150
+ if (p.includes("\0")) return void 0;
91151
+ if (idx === 0 && p.startsWith("-") && p !== "-") return void 0;
91152
+ const parent = dirname(p);
91153
+ let pEnd = parent.length;
91154
+ while (pEnd > 1 && parent[pEnd - 1] === "/") pEnd--;
91155
+ out.push(parent.slice(0, pEnd));
91156
+ }
91157
+ return out.join("\n");
91158
+ }
91159
+ evalSyncBasename(args) {
91160
+ let multiple = false;
91161
+ let suffix2;
91162
+ let idx = 0;
91163
+ const operands = [];
91164
+ while (idx < args.length) {
91165
+ const a = args[idx];
91166
+ if (a === "--") {
91167
+ operands.push(...args.slice(idx + 1));
91168
+ break;
90132
91169
  }
90133
- if (st === "keys[]") {
90134
- compiledStages.push([{ kind: "keys" }, { kind: "iter" }]);
91170
+ if (!a.startsWith("-") || a === "-") {
91171
+ operands.push(a);
91172
+ idx++;
90135
91173
  continue;
90136
91174
  }
90137
- if (!st.startsWith(".")) return void 0;
90138
- let rest = st.slice(1);
90139
- const ops = [];
90140
- while (rest.length > 0) {
90141
- if (rest.startsWith(".")) rest = rest.slice(1);
90142
- const propM = /^([a-zA-Z_][a-zA-Z0-9_]*)/.exec(rest);
90143
- if (propM) {
90144
- ops.push({ kind: "prop", key: propM[1] });
90145
- rest = rest.slice(propM[1].length);
90146
- continue;
90147
- }
90148
- if (rest.startsWith("[]")) {
90149
- ops.push({ kind: "iter" });
90150
- rest = rest.slice(2);
90151
- continue;
90152
- }
90153
- const idxM = /^\[(-?[0-9]+)\]/.exec(rest);
90154
- if (idxM) {
90155
- ops.push({ kind: "index", idx: Number(idxM[1]) });
90156
- rest = rest.slice(idxM[0].length);
90157
- continue;
90158
- }
91175
+ if (a === "-a" || a === "--multiple") {
91176
+ multiple = true;
91177
+ idx++;
91178
+ } else if (a === "-s" || a === "-as" || a === "-sa") {
91179
+ multiple = true;
91180
+ if (idx + 1 >= args.length) return void 0;
91181
+ suffix2 = args[idx + 1];
91182
+ idx += 2;
91183
+ } else if (a.startsWith("-s") && a.length > 2) {
91184
+ multiple = true;
91185
+ suffix2 = a.slice(2);
91186
+ idx++;
91187
+ } else {
90159
91188
  return void 0;
90160
91189
  }
90161
- compiledStages.push(ops);
90162
91190
  }
90163
- let parsed;
90164
- try {
90165
- parsed = JSON.parse(input3);
90166
- } catch {
90167
- return void 0;
90168
- }
90169
- let current = [parsed];
90170
- for (const ops of compiledStages) {
90171
- for (const op of ops) {
90172
- const next = [];
90173
- for (const item of current) {
90174
- if (op.kind === "prop") {
90175
- if (item === null || item === void 0) next.push(null);
90176
- else if (typeof item === "object" && !Array.isArray(item)) next.push(item[op.key] ?? null);
90177
- else return void 0;
90178
- } else if (op.kind === "index") {
90179
- if (item === null || item === void 0) next.push(null);
90180
- else if (Array.isArray(item)) {
90181
- const i = op.idx < 0 ? item.length + op.idx : op.idx;
90182
- next.push(i >= 0 && i < item.length ? item[i] : null);
90183
- } else return void 0;
90184
- } else if (op.kind === "iter") {
90185
- if (Array.isArray(item)) {
90186
- for (const el of item) next.push(el);
90187
- } else if (item && typeof item === "object") {
90188
- for (const k of Object.keys(item)) next.push(item[k]);
90189
- } else return void 0;
90190
- } else if (op.kind === "length") {
90191
- if (item === null || item === void 0) next.push(0);
90192
- else if (typeof item === "string" || Array.isArray(item)) next.push(item.length);
90193
- else if (typeof item === "object") next.push(Object.keys(item).length);
90194
- else return void 0;
90195
- } else if (op.kind === "keys") {
90196
- if (Array.isArray(item)) next.push(item.map((_, idx) => idx));
90197
- else if (item && typeof item === "object") next.push(Object.keys(item).sort());
90198
- else return void 0;
90199
- }
90200
- }
90201
- current = next;
91191
+ if (operands.length === 0) return void 0;
91192
+ if (!multiple && operands.length > 2) return void 0;
91193
+ const effSuffix = multiple ? suffix2 : operands[1];
91194
+ if (effSuffix !== void 0 && effSuffix.includes("\0")) return void 0;
91195
+ const paths = multiple ? operands : [operands[0]];
91196
+ const out = [];
91197
+ for (const p of paths) {
91198
+ if (p.includes("\0")) return void 0;
91199
+ let res = /^\/+$/u.test(p) ? "/" : basename(p);
91200
+ if (effSuffix && res !== effSuffix && res.endsWith(effSuffix)) {
91201
+ res = res.slice(0, -effSuffix.length);
90202
91202
  }
91203
+ out.push(res);
90203
91204
  }
90204
- return current.map((val) => rawOut && typeof val === "string" ? val : JSON.stringify(val ?? null));
91205
+ return out.join("\n");
90205
91206
  }
90206
91207
  parseSyncCutSpec(spec) {
90207
91208
  if (!/^(?:[1-9][0-9]{0,4}|[1-9][0-9]{0,4}-[1-9][0-9]{0,4}|[1-9][0-9]{0,4}-|-[1-9][0-9]{0,4})(?:,(?:[1-9][0-9]{0,4}|[1-9][0-9]{0,4}-[1-9][0-9]{0,4}|[1-9][0-9]{0,4}-|-[1-9][0-9]{0,4}))*$/.test(spec)) {
@@ -90243,28 +91244,50 @@ ${prefix3} line ${offset + line}: \`${source2.split("\n")[line - 1] ?? ""}'
90243
91244
  evalSyncCut(rawLines, opArgs, byteLocaleMode) {
90244
91245
  const norm = [];
90245
91246
  let suppressNoDelim = false;
91247
+ let isComplement = false;
91248
+ let outDelim;
90246
91249
  for (let ci = 0; ci < opArgs.length; ci++) {
90247
91250
  const ca = opArgs[ci];
90248
91251
  if (ca === "-s" || ca === "--only-delimited") {
90249
91252
  suppressNoDelim = true;
91253
+ } else if (ca === "--complement") {
91254
+ isComplement = true;
91255
+ } else if (ca.startsWith("--output-delimiter=")) {
91256
+ outDelim = ca.slice("--output-delimiter=".length);
91257
+ if (outDelim.length === 0 || outDelim.includes("\0")) return void 0;
91258
+ } else if (ca === "--output-delimiter") {
91259
+ if (ci + 1 >= opArgs.length) return void 0;
91260
+ outDelim = opArgs[++ci];
91261
+ if (outDelim.length === 0 || outDelim.includes("\0")) return void 0;
90250
91262
  } else if (ca.startsWith("-sd") || ca.startsWith("-ds")) {
90251
91263
  suppressNoDelim = true;
90252
91264
  const rest = ca.slice(3);
90253
91265
  if (rest.length > 0) norm.push("-d" + rest);
90254
91266
  else if (ci + 1 < opArgs.length) norm.push("-d" + opArgs[++ci]);
90255
91267
  else return void 0;
90256
- } else if ((ca === "-d" || ca === "-f" || ca === "-c") && ci + 1 < opArgs.length) {
91268
+ } else if ((ca === "-d" || ca === "-f" || ca === "-c" || ca === "-b") && ci + 1 < opArgs.length) {
90257
91269
  norm.push(ca + opArgs[++ci]);
90258
91270
  } else {
90259
91271
  norm.push(ca);
90260
91272
  }
90261
91273
  }
90262
- if (!suppressNoDelim && norm.length === 1 && norm[0].startsWith("-c")) {
90263
- if (byteLocaleMode) return void 0;
90264
- const picker2 = this.parseSyncCutSpec(norm[0].slice(2));
90265
- if (!picker2) return void 0;
91274
+ if (!suppressNoDelim && outDelim === void 0 && norm.length === 1 && (norm[0].startsWith("-c") || norm[0].startsWith("-b"))) {
91275
+ const isByteMode = norm[0].startsWith("-b");
91276
+ if (!isByteMode && byteLocaleMode) return void 0;
91277
+ if (isByteMode && rawLines.some((l) => {
91278
+ for (let i = 0; i < l.length; i++) if (l.charCodeAt(i) >= 128) return true;
91279
+ return false;
91280
+ })) return void 0;
91281
+ const basePicker2 = this.parseSyncCutSpec(norm[0].slice(2));
91282
+ if (!basePicker2) return void 0;
91283
+ const picker2 = isComplement ? (len) => {
91284
+ const s = new Set(basePicker2(len));
91285
+ const r = [];
91286
+ for (let i = 0; i < len; i++) if (!s.has(i)) r.push(i);
91287
+ return r;
91288
+ } : basePicker2;
90266
91289
  return rawLines.map((l) => {
90267
- const chars = Array.from(l);
91290
+ const chars = isByteMode ? l.split("") : Array.from(l);
90268
91291
  const idxs = picker2(chars.length);
90269
91292
  return idxs.map((i) => chars[i]).join("");
90270
91293
  });
@@ -90282,8 +91305,15 @@ ${prefix3} line ${offset + line}: \`${source2.split("\n")[line - 1] ?? ""}'
90282
91305
  }
90283
91306
  }
90284
91307
  if (!fArg || !fArg.startsWith("-f")) return void 0;
90285
- const picker = this.parseSyncCutSpec(fArg.slice(2));
90286
- if (!picker) return void 0;
91308
+ const basePicker = this.parseSyncCutSpec(fArg.slice(2));
91309
+ if (!basePicker) return void 0;
91310
+ const picker = isComplement ? (len) => {
91311
+ const s = new Set(basePicker(len));
91312
+ const r = [];
91313
+ for (let i = 0; i < len; i++) if (!s.has(i)) r.push(i);
91314
+ return r;
91315
+ } : basePicker;
91316
+ const joinDelim = outDelim ?? delim;
90287
91317
  const out = [];
90288
91318
  for (let li = 0; li < rawLines.length; li++) {
90289
91319
  const l = rawLines[li];
@@ -90293,115 +91323,408 @@ ${prefix3} line ${offset + line}: \`${source2.split("\n")[line - 1] ?? ""}'
90293
91323
  }
90294
91324
  const parts = l.split(delim);
90295
91325
  const idxs = picker(parts.length);
90296
- out.push(idxs.map((i) => parts[i]).join(delim));
91326
+ out.push(idxs.map((i) => parts[i]).join(joinDelim));
90297
91327
  }
90298
91328
  return out;
90299
91329
  }
90300
91330
  evalSyncSed(rawLines, opArgs) {
90301
91331
  let quiet = false;
90302
- let expr;
90303
- if (opArgs.length === 1 && !opArgs[0].startsWith("-")) {
90304
- expr = opArgs[0];
90305
- } else if (opArgs.length === 2 && opArgs[0] === "-e") {
90306
- expr = opArgs[1];
90307
- } else if (opArgs.length === 2 && opArgs[0] === "-n") {
90308
- quiet = true;
90309
- expr = opArgs[1];
90310
- } else if (opArgs.length === 3 && (opArgs[0] === "-n" && opArgs[1] === "-e" || opArgs[0] === "-e" && opArgs[1] === "-n")) {
90311
- quiet = true;
90312
- expr = opArgs[2];
90313
- }
90314
- if (!expr) return void 0;
90315
- const addrCmdM = /^(?:([1-9][0-9]{0,4}|\$)(?:,([1-9][0-9]{0,4}|\$))?|\/(\^?[a-zA-Z0-9_ :;,.-]+\$?)\/)([dp])$/.exec(expr);
90316
- if (addrCmdM) {
90317
- const cmdChar = addrCmdM[4];
90318
- if (quiet && cmdChar !== "p" || !quiet && cmdChar !== "d") return void 0;
90319
- const startSpec = addrCmdM[1];
90320
- const endSpec = addrCmdM[2];
90321
- const patSpec = addrCmdM[3];
90322
- const matchLine = (l, idx1, total) => {
90323
- if (patSpec !== void 0) {
90324
- const aStart = patSpec.startsWith("^");
90325
- const c1 = aStart ? patSpec.slice(1) : patSpec;
90326
- const aEnd = c1.endsWith("$");
90327
- const core2 = aEnd ? c1.slice(0, -1) : c1;
90328
- if (aStart && aEnd) return l === core2;
90329
- if (aStart) return l.startsWith(core2);
90330
- if (aEnd) return l.endsWith(core2);
90331
- return l.includes(core2);
90332
- }
90333
- const sNum = startSpec === "$" ? total : Number(startSpec);
90334
- if (endSpec === void 0) return idx1 === sNum;
90335
- const eNum = endSpec === "$" ? total : Number(endSpec);
90336
- return idx1 >= sNum && idx1 <= eNum;
90337
- };
90338
- const out = [];
90339
- for (let i = 0; i < rawLines.length; i++) {
90340
- const hit = matchLine(rawLines[i], i + 1, rawLines.length);
90341
- if (cmdChar === "p" && hit) out.push(rawLines[i]);
90342
- else if (cmdChar === "d" && !hit) out.push(rawLines[i]);
91332
+ let isExtended = false;
91333
+ const rawExprs = [];
91334
+ for (let i = 0; i < opArgs.length; i++) {
91335
+ const a = opArgs[i];
91336
+ if (a === "-n" || a === "--quiet" || a === "--silent") quiet = true;
91337
+ else if (a === "-E" || a === "-r" || a === "--regexp-extended") isExtended = true;
91338
+ else if (a === "-En" || a === "-nE" || a === "-rn" || a === "-nr") {
91339
+ quiet = true;
91340
+ isExtended = true;
91341
+ } else if (a === "-e") {
91342
+ if (i + 1 >= opArgs.length) return void 0;
91343
+ rawExprs.push(opArgs[++i]);
91344
+ } else if (!a.startsWith("-") && rawExprs.length === 0 && i === opArgs.length - 1) {
91345
+ rawExprs.push(a);
91346
+ } else {
91347
+ return void 0;
90343
91348
  }
90344
- return out;
90345
91349
  }
90346
- if (quiet) return void 0;
90347
- if (!expr.startsWith("s") || expr.length < 4) return void 0;
90348
- const delim = expr[1];
90349
- if (!"/#|:@,;%!".includes(delim)) return void 0;
90350
- const parts = expr.slice(2).split(delim);
90351
- if (parts.length !== 3) return void 0;
90352
- const [pat, rep, flags3] = parts;
90353
- if (flags3 !== "" && flags3 !== "g" || /[&\\\n]/.test(rep)) return void 0;
90354
- const anchorStart = pat.startsWith("^");
90355
- const core1 = anchorStart ? pat.slice(1) : pat;
90356
- const anchorEnd = core1.endsWith("$");
90357
- const core = anchorEnd ? core1.slice(0, -1) : core1;
90358
- if (core.length === 0 || !/^[a-zA-Z0-9_ :;,/-]+$/.test(core)) return void 0;
90359
- const isGlobal = flags3 === "g";
90360
- return rawLines.map((l) => {
90361
- if (anchorStart && anchorEnd) return l === core ? rep : l;
90362
- if (anchorStart) return l.startsWith(core) ? rep + l.slice(core.length) : l;
90363
- if (anchorEnd) return l.endsWith(core) ? l.slice(0, l.length - core.length) + rep : l;
90364
- return isGlobal ? l.split(core).join(rep) : l.replace(core, () => rep);
90365
- });
91350
+ if (rawExprs.length === 0) return void 0;
91351
+ const subExprs = [];
91352
+ for (const re of rawExprs) {
91353
+ if (re.includes(";") && !re.startsWith("s;") && !re.startsWith("y;")) {
91354
+ for (const p of re.split(";")) {
91355
+ const t = p.trim();
91356
+ if (t.length > 0) subExprs.push(t);
91357
+ }
91358
+ } else {
91359
+ subExprs.push(re.trim());
91360
+ }
91361
+ }
91362
+ if (subExprs.length === 0) return void 0;
91363
+ const steps = [];
91364
+ for (const rawE of subExprs) {
91365
+ let rest = rawE;
91366
+ let addr;
91367
+ let negated = false;
91368
+ const addrM = /^(?:([1-9][0-9]{0,4}|\$)(?:,([1-9][0-9]{0,4}|\$))?|\/(\^?[a-zA-Z0-9_ :;,=-]+\$?)\/)\s*/.exec(rest);
91369
+ if (addrM) {
91370
+ const startSpec = addrM[1];
91371
+ const endSpec = addrM[2];
91372
+ const patSpec = addrM[3];
91373
+ rest = rest.slice(addrM[0].length);
91374
+ addr = (l, idx1, total2) => {
91375
+ if (patSpec !== void 0) {
91376
+ const aStart = patSpec.startsWith("^");
91377
+ const c1 = aStart ? patSpec.slice(1) : patSpec;
91378
+ const aEnd = c1.endsWith("$");
91379
+ const core = aEnd ? c1.slice(0, -1) : c1;
91380
+ if (aStart && aEnd) return l === core;
91381
+ if (aStart) return l.startsWith(core);
91382
+ if (aEnd) return l.endsWith(core);
91383
+ return l.includes(core);
91384
+ }
91385
+ const sNum = startSpec === "$" ? total2 : Number(startSpec);
91386
+ if (endSpec === void 0) return idx1 === sNum;
91387
+ const eNum = endSpec === "$" ? total2 : Number(endSpec);
91388
+ return idx1 >= sNum && idx1 <= Math.max(sNum, eNum);
91389
+ };
91390
+ }
91391
+ if (rest.startsWith("!")) {
91392
+ negated = true;
91393
+ rest = rest.slice(1).trim();
91394
+ }
91395
+ if (rest === "d") {
91396
+ steps.push({ addr, negated, kind: "d" });
91397
+ continue;
91398
+ }
91399
+ if (rest === "p") {
91400
+ steps.push({ addr, negated, kind: "p" });
91401
+ continue;
91402
+ }
91403
+ if (rest === "q") {
91404
+ steps.push({ addr, negated, kind: "q" });
91405
+ continue;
91406
+ }
91407
+ if (rest === "=") {
91408
+ steps.push({ addr, negated, kind: "=" });
91409
+ continue;
91410
+ }
91411
+ if (rest.startsWith("i") || rest.startsWith("a") || rest.startsWith("c")) return void 0;
91412
+ if (rest.startsWith("y") && rest.length >= 4) {
91413
+ const delim = rest[1];
91414
+ if (!"/#|:@,;%!".includes(delim)) return void 0;
91415
+ const parts = rest.slice(2).split(delim);
91416
+ if (parts.length !== 3 || parts[2] !== "") return void 0;
91417
+ const srcStr = parts[0];
91418
+ const dstStr = parts[1];
91419
+ if (srcStr.includes("\\") || dstStr.includes("\\")) return void 0;
91420
+ const srcChars = Array.from(srcStr);
91421
+ const dstChars = Array.from(dstStr);
91422
+ if (srcChars.length !== dstChars.length) return void 0;
91423
+ const map = /* @__PURE__ */ new Map();
91424
+ for (let i = 0; i < srcChars.length; i++) {
91425
+ if (!map.has(srcChars[i])) map.set(srcChars[i], dstChars[i]);
91426
+ }
91427
+ steps.push({ addr, negated, kind: "y", map });
91428
+ continue;
91429
+ }
91430
+ if (rest.startsWith("s") && rest.length >= 4) {
91431
+ const delim = rest[1];
91432
+ if (!"/#|:@,;%!".includes(delim)) return void 0;
91433
+ const parts = rest.slice(2).split(delim);
91434
+ if (parts.length !== 3) return void 0;
91435
+ const [pat, rep, flags3] = parts;
91436
+ if (!/^[giIp1-9]*$/.test(flags3) || /\n|\\(?![1-9])/.test(rep)) return void 0;
91437
+ const nthDigits = flags3.match(/[1-9]/g);
91438
+ if (nthDigits && (nthDigits.length > 1 || flags3.includes("g"))) return void 0;
91439
+ const nth = nthDigits ? Number(nthDigits[0]) : 0;
91440
+ const global = flags3.includes("g") || nth > 0;
91441
+ const ignoreCase = flags3.includes("i") || flags3.includes("I");
91442
+ const printOnMatch = flags3.includes("p");
91443
+ const anchorStart = pat.startsWith("^");
91444
+ const core1 = anchorStart ? pat.slice(1) : pat;
91445
+ const anchorEnd = core1.endsWith("$");
91446
+ const core = anchorEnd ? core1.slice(0, -1) : core1;
91447
+ if (core.length === 0 && !anchorStart && !anchorEnd) return void 0;
91448
+ let reSrc;
91449
+ if (/^[a-zA-Z0-9_ :;,=-]*$/.test(core)) {
91450
+ if (/\\[1-9]/.test(rep)) return void 0;
91451
+ reSrc = core.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
91452
+ } else if (core === "[ ]*" || core === "[ ]+" || core === "[ \\t]*" || core === "[ \\t]+" || core === "[[:space:]]*" || core === "[[:space:]]+" || core === "[0-9]+" || core === "[0-9]*" || core === "[a-zA-Z]+" || core === "[a-zA-Z0-9_]+") {
91453
+ if (/\\[1-9]/.test(rep)) return void 0;
91454
+ reSrc = core.replace("[[:space:]]", "[ \\t\\r\\n\\v\\f]");
91455
+ } else if (isExtended && /^[a-zA-Z0-9_ :;,=.+*?|()^\-[\]]+$/.test(core) && !/\([^)]*[+*][^)]*\)[+*?]/.test(core)) {
91456
+ try {
91457
+ const expanded = core.replace(/\[:space:\]/g, " \\t\\r\\n\\v\\f");
91458
+ void new RegExp(expanded);
91459
+ reSrc = expanded;
91460
+ } catch {
91461
+ reSrc = void 0;
91462
+ }
91463
+ }
91464
+ if (reSrc === void 0) return void 0;
91465
+ const fullRe = new RegExp((anchorStart ? "^" : "") + reSrc + (anchorEnd ? "$" : ""), (global ? "g" : "") + (ignoreCase ? "i" : ""));
91466
+ steps.push({ addr, negated, kind: "s", re: fullRe, rep, printOnMatch, nth });
91467
+ continue;
91468
+ }
91469
+ return void 0;
91470
+ }
91471
+ const out = [];
91472
+ const total = rawLines.length;
91473
+ let lastInputIndex = -1;
91474
+ for (let i = 0; i < total; i++) {
91475
+ let l = rawLines[i];
91476
+ const idx1 = i + 1;
91477
+ let deleted = false;
91478
+ let quitNow = false;
91479
+ for (let si = 0; si < steps.length; si++) {
91480
+ const st = steps[si];
91481
+ const addrMatched = st.addr ? st.addr(l, idx1, total) : true;
91482
+ if (st.negated ? addrMatched : !addrMatched) continue;
91483
+ if (st.kind === "d") {
91484
+ deleted = true;
91485
+ break;
91486
+ }
91487
+ if (st.kind === "p") {
91488
+ out.push(l);
91489
+ lastInputIndex = i;
91490
+ continue;
91491
+ }
91492
+ if (st.kind === "=") {
91493
+ out.push(String(idx1));
91494
+ lastInputIndex = i;
91495
+ continue;
91496
+ }
91497
+ if (st.kind === "q") {
91498
+ if (!quiet) {
91499
+ out.push(l);
91500
+ lastInputIndex = i;
91501
+ }
91502
+ quitNow = true;
91503
+ break;
91504
+ }
91505
+ if (st.kind === "y") {
91506
+ l = Array.from(l).map((c) => st.map.get(c) ?? c).join("");
91507
+ continue;
91508
+ }
91509
+ let matchedOnce = false;
91510
+ let matchIdx = 0;
91511
+ let previousEnd = -1;
91512
+ l = l.replace(st.re, (matched, ...groups) => {
91513
+ const offset = groups[groups.length - 2];
91514
+ if (matched.length === 0 && offset === previousEnd) return "";
91515
+ previousEnd = offset + matched.length;
91516
+ matchIdx++;
91517
+ if (st.nth > 0 && matchIdx !== st.nth) return matched;
91518
+ matchedOnce = true;
91519
+ let replacement = "";
91520
+ for (let ri = 0; ri < st.rep.length; ri++) {
91521
+ const c = st.rep[ri];
91522
+ if (c === "&") replacement += matched;
91523
+ else if (c === "\\" && ri + 1 < st.rep.length) {
91524
+ const next = st.rep[++ri];
91525
+ const group = next >= "1" && next <= "9" ? groups[Number(next) - 1] : next;
91526
+ replacement += typeof group === "string" ? group : "";
91527
+ } else replacement += c;
91528
+ }
91529
+ return replacement;
91530
+ });
91531
+ if (matchedOnce && st.printOnMatch) out.push(l);
91532
+ }
91533
+ if (quitNow) {
91534
+ break;
91535
+ }
91536
+ if (!deleted && !quiet) {
91537
+ out.push(l);
91538
+ lastInputIndex = i;
91539
+ }
91540
+ }
91541
+ return { lines: out, lastInputIndex };
90366
91542
  }
90367
91543
  evalSyncGrep(rawLines, opArgs, errexit) {
90368
- if (errexit || opArgs.length !== 1 && opArgs.length !== 2) return void 0;
90369
- const mode = opArgs.length === 2 ? opArgs[0] : "";
90370
- const pat = opArgs[opArgs.length - 1];
90371
- if (pat.startsWith("-")) return void 0;
90372
- if (opArgs.length === 2 && mode !== "-v" && mode !== "-i" && mode !== "-c" && mode !== "-F" && mode !== "-E" && mode !== "-Ei" && mode !== "-iE" && mode !== "-Ev" && mode !== "-vE") {
90373
- return void 0;
91544
+ if (errexit || opArgs.length < 1 || opArgs.length > 8) return void 0;
91545
+ let mode = "";
91546
+ let maxCount2 = Infinity;
91547
+ let beforeCtx = 0;
91548
+ let afterCtx = 0;
91549
+ const rawPatterns = [];
91550
+ for (let i = 0; i < opArgs.length; i++) {
91551
+ const a = opArgs[i];
91552
+ if ((a === "-A" || a === "-B" || a === "-C") && i + 1 < opArgs.length && /^[0-9]{1,4}$/.test(opArgs[i + 1])) {
91553
+ const n = Number(opArgs[++i]);
91554
+ if (a === "-A" || a === "-C") afterCtx = n;
91555
+ if (a === "-B" || a === "-C") beforeCtx = n;
91556
+ } else if (/^-[ABC][0-9]{1,4}$/.test(a)) {
91557
+ const n = Number(a.slice(2));
91558
+ if (a[1] === "A" || a[1] === "C") afterCtx = n;
91559
+ if (a[1] === "B" || a[1] === "C") beforeCtx = n;
91560
+ } else if (/^--(?:after-context|before-context|context)=[0-9]{1,4}$/.test(a)) {
91561
+ const eq = a.indexOf("=");
91562
+ const n = Number(a.slice(eq + 1));
91563
+ if (a.startsWith("--after") || a.startsWith("--context")) afterCtx = n;
91564
+ if (a.startsWith("--before") || a.startsWith("--context")) beforeCtx = n;
91565
+ } else if (a === "-e") {
91566
+ if (i + 1 >= opArgs.length) return void 0;
91567
+ rawPatterns.push(opArgs[++i]);
91568
+ } else if (a.startsWith("-e") && a.length > 2) {
91569
+ rawPatterns.push(a.slice(2));
91570
+ } else if (a === "-m") {
91571
+ if (i + 1 >= opArgs.length || !/^[1-9][0-9]{0,5}$/.test(opArgs[i + 1])) return void 0;
91572
+ maxCount2 = Number(opArgs[++i]);
91573
+ } else if (a.startsWith("-m") && /^[1-9][0-9]{0,5}$/.test(a.slice(2))) {
91574
+ maxCount2 = Number(a.slice(2));
91575
+ } else if (a.startsWith("--max-count=") && /^[1-9][0-9]{0,5}$/.test(a.slice(12))) {
91576
+ maxCount2 = Number(a.slice(12));
91577
+ } else if (a.startsWith("--") && a !== "--" && rawPatterns.length === 0 && i < opArgs.length - 1) {
91578
+ if (a === "--extended-regexp") mode += "E";
91579
+ else if (a === "--fixed-strings") mode += "F";
91580
+ else if (a === "--ignore-case") mode += "i";
91581
+ else if (a === "--invert-match") mode += "v";
91582
+ else if (a === "--only-matching") mode += "o";
91583
+ else if (a === "--line-number") mode += "n";
91584
+ else if (a === "--count") mode += "c";
91585
+ else if (a === "--word-regexp") mode += "w";
91586
+ else if (a === "--line-regexp") mode += "x";
91587
+ else return void 0;
91588
+ } else if (a.startsWith("-") && a !== "-" && a !== "--" && rawPatterns.length === 0 && i < opArgs.length - 1) {
91589
+ mode += a.slice(1);
91590
+ } else if (!a.startsWith("-") && rawPatterns.length === 0 && i === opArgs.length - 1) {
91591
+ rawPatterns.push(a);
91592
+ } else {
91593
+ return void 0;
91594
+ }
90374
91595
  }
91596
+ if (rawPatterns.length === 0 || !/^[vicFEonxw]*$/.test(mode)) return void 0;
91597
+ const isLineNumber = mode.includes("n");
91598
+ const isLineRegexp = mode.includes("x");
91599
+ const isWordRegexp = mode.includes("w");
90375
91600
  const isCaseInsensitive = mode.includes("i");
91601
+ const foldCase = (value2) => value2.replace(/[A-Z]/g, (ch) => ch.toLowerCase());
90376
91602
  const isInvert = mode.includes("v");
90377
- const isCount = mode === "-c";
91603
+ const isCount = mode.includes("c");
90378
91604
  const isExtended = mode.includes("E");
90379
91605
  const isFixed = mode.includes("F");
90380
- const branches = isExtended ? pat.split("|") : [pat];
91606
+ const isOnlyMatching = mode.includes("o");
91607
+ if (isExtended && !isFixed && rawPatterns.some((pattern) => pattern.includes("[:") || pattern.includes("[.") || pattern.includes("[="))) return void 0;
91608
+ if (isCount && (isLineNumber || isOnlyMatching || beforeCtx > 0 || afterCtx > 0)) return void 0;
91609
+ if (isOnlyMatching && (beforeCtx > 0 || afterCtx > 0)) return void 0;
91610
+ if (isOnlyMatching) {
91611
+ if (rawPatterns.length !== 1 || isInvert || isLineRegexp || isWordRegexp || isFixed) return void 0;
91612
+ const pat = rawPatterns[0];
91613
+ const reFlags = isCaseInsensitive ? "gi" : "g";
91614
+ let re;
91615
+ if (isExtended && !pat.includes("|") && /^[a-zA-Z0-9_ :;,=.+*?()^\-[\]]+$/.test(pat) && !/\([^)]*[+*][^)]*\)[+*?]/.test(pat)) {
91616
+ try {
91617
+ re = new RegExp(pat, reFlags);
91618
+ } catch {
91619
+ re = void 0;
91620
+ }
91621
+ } else {
91622
+ const branches2 = isExtended ? pat.split("|") : [pat];
91623
+ if (branches2.every((b) => b.length > 0 && /^[a-zA-Z0-9_ :;,/-]+$/.test(b))) {
91624
+ branches2.sort((a, b) => b.length - a.length);
91625
+ re = new RegExp(branches2.join("|"), reFlags);
91626
+ }
91627
+ }
91628
+ if (!re) return void 0;
91629
+ const out = [];
91630
+ for (let li = 0; li < rawLines.length; li++) {
91631
+ const matches2 = rawLines[li].match(re);
91632
+ if (matches2) {
91633
+ for (let mi = 0; mi < matches2.length; mi++) {
91634
+ out.push(isLineNumber ? `${li + 1}:${matches2[mi]}` : matches2[mi]);
91635
+ }
91636
+ }
91637
+ }
91638
+ return { lines: out, status: out.length > 0 ? 0 : 1 };
91639
+ }
91640
+ if (isExtended && isFixed) return void 0;
91641
+ const branches = [];
91642
+ for (const rp of rawPatterns) {
91643
+ for (const b of isFixed ? rp.split("\n") : isExtended ? rp.split("|") : [rp]) {
91644
+ branches.push(b);
91645
+ }
91646
+ }
90381
91647
  const compiledBranches = [];
90382
91648
  for (const br of branches) {
90383
91649
  if (br.length === 0) return void 0;
90384
- const anchorStart = !isFixed && br.startsWith("^");
90385
- const c1 = anchorStart ? br.slice(1) : br;
90386
- const anchorEnd = !isFixed && c1.endsWith("$");
90387
- const core = anchorEnd ? c1.slice(0, -1) : c1;
90388
- if (core.length === 0 || !/^[a-zA-Z0-9_ :;,/-]+$/.test(core)) return void 0;
90389
- compiledBranches.push({ anchorStart, anchorEnd, needle: isCaseInsensitive ? core.toLowerCase() : core });
91650
+ if (isFixed) {
91651
+ if (br.includes("\0")) return void 0;
91652
+ compiledBranches.push({ anchorStart: isLineRegexp, anchorEnd: isLineRegexp, needle: isCaseInsensitive ? foldCase(br) : br, re: void 0 });
91653
+ } else {
91654
+ const anchorStart = isLineRegexp || br.startsWith("^");
91655
+ const c1 = br.startsWith("^") ? br.slice(1) : br;
91656
+ const anchorEnd = isLineRegexp || c1.endsWith("$");
91657
+ const core = c1.endsWith("$") ? c1.slice(0, -1) : c1;
91658
+ if (core.length > 0 && /^[a-zA-Z0-9_ :;,/-]+$/.test(core)) {
91659
+ compiledBranches.push({ anchorStart, anchorEnd, needle: isCaseInsensitive ? foldCase(core) : core, re: void 0 });
91660
+ } else if (isExtended && !isWordRegexp && core.length > 0 && /^[a-zA-Z0-9_ :;,=.+*?^\-[\]]+$/.test(core) && !/\([^)]*[+*][^)]*\)[+*?]/.test(core)) {
91661
+ try {
91662
+ const fullSrc = (anchorStart ? "^" : "") + core + (anchorEnd ? "$" : "");
91663
+ compiledBranches.push({ anchorStart, anchorEnd, needle: "", re: new RegExp(fullSrc, isCaseInsensitive ? "i" : "") });
91664
+ } catch {
91665
+ return void 0;
91666
+ }
91667
+ } else {
91668
+ return void 0;
91669
+ }
91670
+ }
90390
91671
  }
91672
+ const isWordChar = (ch) => ch !== void 0 && /^[a-zA-Z0-9_]$/.test(ch);
91673
+ const hasWordMatch = (hay, needle, aStart, aEnd) => {
91674
+ if (aStart && aEnd) return hay === needle;
91675
+ if (aStart) return hay.startsWith(needle) && !isWordChar(hay[needle.length]);
91676
+ if (aEnd) return hay.endsWith(needle) && !isWordChar(hay[hay.length - needle.length - 1]);
91677
+ let from = 0;
91678
+ while (from <= hay.length - needle.length) {
91679
+ const idx = hay.indexOf(needle, from);
91680
+ if (idx === -1) return false;
91681
+ if (!isWordChar(hay[idx - 1]) && !isWordChar(hay[idx + needle.length])) return true;
91682
+ from = idx + 1;
91683
+ }
91684
+ return false;
91685
+ };
90391
91686
  const matched = [];
91687
+ const matchedIndices = [];
90392
91688
  for (let li = 0; li < rawLines.length; li++) {
90393
91689
  const l = rawLines[li];
90394
- const hay = isCaseInsensitive ? l.toLowerCase() : l;
91690
+ const hay = isCaseInsensitive ? foldCase(l) : l;
90395
91691
  let hit = false;
90396
91692
  for (let bi = 0; bi < compiledBranches.length; bi++) {
90397
91693
  const b = compiledBranches[bi];
90398
- const ok = b.anchorStart && b.anchorEnd ? hay === b.needle : b.anchorStart ? hay.startsWith(b.needle) : b.anchorEnd ? hay.endsWith(b.needle) : hay.includes(b.needle);
91694
+ const ok = b.re !== void 0 ? b.re.test(l) : isWordRegexp ? hasWordMatch(hay, b.needle, b.anchorStart, b.anchorEnd) : b.anchorStart && b.anchorEnd ? hay === b.needle : b.anchorStart ? hay.startsWith(b.needle) : b.anchorEnd ? hay.endsWith(b.needle) : hay.includes(b.needle);
90399
91695
  if (ok) {
90400
91696
  hit = true;
90401
91697
  break;
90402
91698
  }
90403
91699
  }
90404
- if (isInvert ? !hit : hit) matched.push(l);
91700
+ if (isInvert ? !hit : hit) {
91701
+ matchedIndices.push(li);
91702
+ matched.push(isLineNumber ? `${li + 1}:${l}` : l);
91703
+ if (matched.length >= maxCount2) break;
91704
+ }
91705
+ }
91706
+ if ((beforeCtx > 0 || afterCtx > 0) && matchedIndices.length > 0) {
91707
+ const matchedSet = new Set(matchedIndices);
91708
+ const outCtx = [];
91709
+ let prevEnd = -1;
91710
+ for (const mIdx of matchedIndices) {
91711
+ const start = Math.max(0, mIdx - beforeCtx);
91712
+ const end = Math.min(rawLines.length - 1, mIdx + afterCtx);
91713
+ if (prevEnd !== -1 && start > prevEnd + 1) {
91714
+ outCtx.push("--");
91715
+ }
91716
+ const from = prevEnd !== -1 ? Math.max(start, prevEnd + 1) : start;
91717
+ for (let k = from; k <= end; k++) {
91718
+ const lineText = rawLines[k];
91719
+ if (isLineNumber) {
91720
+ outCtx.push(`${k + 1}${matchedSet.has(k) ? ":" : "-"}${lineText}`);
91721
+ } else {
91722
+ outCtx.push(lineText);
91723
+ }
91724
+ }
91725
+ prevEnd = Math.max(prevEnd, end);
91726
+ }
91727
+ return { lines: outCtx, status: 0 };
90405
91728
  }
90406
91729
  return {
90407
91730
  lines: isCount ? [String(matched.length)] : matched,
@@ -90409,46 +91732,338 @@ ${prefix3} line ${offset + line}: \`${source2.split("\n")[line - 1] ?? ""}'
90409
91732
  };
90410
91733
  }
90411
91734
  evalSyncAwk(rawLines, opArgs) {
90412
- if (opArgs.length < 1 || opArgs.length > 3) return void 0;
90413
- const norm = opArgs.length === 3 && opArgs[0] === "-F" ? ["-F" + opArgs[1], opArgs[2]] : opArgs;
91735
+ if (opArgs.length < 1 || opArgs.length > 8) return void 0;
90414
91736
  let awkSep;
90415
91737
  let awkProg;
90416
- if (norm.length === 1) awkProg = norm[0];
90417
- else if (norm.length === 2 && norm[0].length === 3 && norm[0].startsWith("-F") && norm[0][2] !== "\\") {
90418
- awkSep = norm[0].slice(2);
90419
- awkProg = norm[1];
91738
+ let ofs = " ";
91739
+ const userVars = /* @__PURE__ */ new Map();
91740
+ for (let i = 0; i < opArgs.length; i++) {
91741
+ const a = opArgs[i];
91742
+ if (a === "-F") {
91743
+ if (i + 1 >= opArgs.length || opArgs[i + 1].length !== 1 || opArgs[i + 1] === "\\") return void 0;
91744
+ awkSep = opArgs[++i];
91745
+ } else if (a.startsWith("-F") && a.length === 3 && a[2] !== "\\") {
91746
+ awkSep = a.slice(2);
91747
+ } else if (a === "-v") {
91748
+ if (i + 1 >= opArgs.length) return void 0;
91749
+ const kv = opArgs[++i];
91750
+ const eq = kv.indexOf("=");
91751
+ if (eq <= 0 || !/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(kv.slice(0, eq))) return void 0;
91752
+ const k = kv.slice(0, eq);
91753
+ const v = kv.slice(eq + 1);
91754
+ if (v.includes("\\")) return void 0;
91755
+ if (k === "OFS") ofs = v;
91756
+ else if (k === "FS") {
91757
+ if (v.length !== 1) return void 0;
91758
+ awkSep = v;
91759
+ } else userVars.set(k, v);
91760
+ } else if (a.startsWith("-v") && a.length > 2) {
91761
+ const kv = a.slice(2);
91762
+ const eq = kv.indexOf("=");
91763
+ if (eq <= 0 || !/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(kv.slice(0, eq))) return void 0;
91764
+ const k = kv.slice(0, eq);
91765
+ const v = kv.slice(eq + 1);
91766
+ if (v.includes("\\")) return void 0;
91767
+ if (k === "OFS") ofs = v;
91768
+ else if (k === "FS") {
91769
+ if (v.length !== 1) return void 0;
91770
+ awkSep = v;
91771
+ } else userVars.set(k, v);
91772
+ } else if (!a.startsWith("-") && i === opArgs.length - 1) {
91773
+ awkProg = a;
91774
+ } else {
91775
+ return void 0;
91776
+ }
90420
91777
  }
90421
91778
  if (!awkProg) return void 0;
90422
- const awkM = /^\s*\{\s*print(?:\s+((?:\$(?:[0-9]+|NF)|"[^"$\\]*")(?:\s*,?\s*(?:\$(?:[0-9]+|NF)|"[^"$\\]*"))*))?\s*;?\s*\}\s*$/.exec(awkProg);
91779
+ let progRest = awkProg.trim();
91780
+ const beginFsM = /^BEGIN\s*\{([^}]*)\}\s*/.exec(progRest);
91781
+ let initVarName;
91782
+ let initVarVal = 0;
91783
+ if (beginFsM) {
91784
+ const bStmts = beginFsM[1].split(";").map((s) => s.trim()).filter(Boolean);
91785
+ for (const bs of bStmts) {
91786
+ const ofsM = /^OFS\s*=\s*"([^"\\]*)"$/.exec(bs);
91787
+ if (ofsM) {
91788
+ ofs = ofsM[1];
91789
+ continue;
91790
+ }
91791
+ const fsM = /^FS\s*=\s*"([^"\\])"$/.exec(bs);
91792
+ if (fsM) {
91793
+ awkSep = fsM[1];
91794
+ continue;
91795
+ }
91796
+ const numInitM = /^([a-zA-Z_][a-zA-Z0-9_]*)\s*=\s*(-?[0-9]+(?:\.[0-9]+)?)$/.exec(bs);
91797
+ if (numInitM) {
91798
+ initVarName = numInitM[1];
91799
+ initVarVal = Number(numInitM[2]);
91800
+ continue;
91801
+ }
91802
+ return void 0;
91803
+ }
91804
+ progRest = progRest.slice(beginFsM[0].length).trim();
91805
+ }
91806
+ const sumEndM = /^\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*(\+=|-=)\s*(?:\$([0-9]+|NF)|(-?[0-9]+(?:\.[0-9]+)?))\s*;?\s*\}\s*END\s*\{\s*print\s+\1\s*;?\s*\}$/.exec(progRest);
91807
+ if (sumEndM) {
91808
+ const varName = sumEndM[1];
91809
+ if (["NR", "NF", "FNR", "OFS", "FS", "ORS", "RS", "OFMT", "CONVFMT", "ARGC", "ARGIND", "FILENAME", "RSTART", "RLENGTH", "SUBSEP", "IGNORECASE", "FIELDWIDTHS", "FPAT", "BINMODE", "TEXTDOMAIN"].includes(varName)) return void 0;
91810
+ if (initVarName !== void 0 && initVarName !== varName) return void 0;
91811
+ const op = sumEndM[2];
91812
+ const fTok = sumEndM[3];
91813
+ const constVal = sumEndM[4] !== void 0 ? Number(sumEndM[4]) : void 0;
91814
+ const initial = userVars.get(varName);
91815
+ if (initial !== void 0 && !Number.isFinite(Number(initial))) return void 0;
91816
+ let acc = initVarName === varName ? initVarVal : Number(initial ?? 0);
91817
+ let touched = initVarName === varName || initial !== void 0;
91818
+ for (let li = 0; li < rawLines.length; li++) {
91819
+ const l = rawLines[li];
91820
+ const fields3 = awkSep === void 0 || awkSep === " " ? l.split(/[ \t]+/).filter(Boolean) : l.length === 0 ? [] : l.split(awkSep);
91821
+ let delta = 0;
91822
+ if (constVal !== void 0) {
91823
+ delta = constVal;
91824
+ } else {
91825
+ const idx = fTok === "NF" ? fields3.length : Number(fTok);
91826
+ const rawField = idx === 0 ? l : idx >= 1 && idx <= fields3.length ? fields3[idx - 1] : "";
91827
+ const n = /^[ \t]*([+-]?(?:\d+(?:\.\d*)?|\.\d+))/.exec(rawField);
91828
+ delta = n ? Number(n[1]) : 0;
91829
+ }
91830
+ acc = op === "+=" ? acc + delta : acc - delta;
91831
+ touched = true;
91832
+ }
91833
+ return [touched ? text({ kind: "number", number: acc }) : ""];
91834
+ }
91835
+ if (initVarName !== void 0) return void 0;
91836
+ let rowPred;
91837
+ const patCondM = /^\/(\^?[a-zA-Z0-9_ :;,=-]+\$?)\/\s*/.exec(progRest);
91838
+ if (patCondM) {
91839
+ const pSpec = patCondM[1];
91840
+ const aS = pSpec.startsWith("^");
91841
+ const c1 = aS ? pSpec.slice(1) : pSpec;
91842
+ const aE = c1.endsWith("$");
91843
+ const core = aE ? c1.slice(0, -1) : c1;
91844
+ rowPred = (l) => aS && aE ? l === core : aS ? l.startsWith(core) : aE ? l.endsWith(core) : l.includes(core);
91845
+ progRest = progRest.slice(patCondM[0].length).trim();
91846
+ } else {
91847
+ const cmpCondM = /^(?:(NR|NF)|\$([0-9]+|NF))\s*(==|!=|>=|<=|>|<)\s*(?:"([^"\\]*)"|(-?[0-9]+(?:\.[0-9]+)?)|([a-zA-Z_][a-zA-Z0-9_]*))\s*/.exec(progRest);
91848
+ if (cmpCondM) {
91849
+ const nrNf = cmpCondM[1];
91850
+ const fTok = cmpCondM[2];
91851
+ const op = cmpCondM[3];
91852
+ const varRhs = cmpCondM[6] !== void 0 ? userVars.get(cmpCondM[6]) : void 0;
91853
+ if (cmpCondM[6] !== void 0 && varRhs === void 0) return void 0;
91854
+ const varAsNum = varRhs !== void 0 && /^-?(?:\d+(?:\.\d*)?|\.\d+)$/.test(varRhs) ? Number(varRhs) : void 0;
91855
+ const strRhs = cmpCondM[4] ?? (varAsNum === void 0 ? varRhs : void 0);
91856
+ const numRhs = cmpCondM[5] !== void 0 ? Number(cmpCondM[5]) : varAsNum;
91857
+ if (strRhs !== void 0 && op !== "==" && op !== "!=") return void 0;
91858
+ rowPred = (l, fields3, nr) => {
91859
+ let rawVal;
91860
+ if (nrNf !== void 0) rawVal = nrNf === "NR" ? nr : fields3.length;
91861
+ else {
91862
+ const idx = fTok === "NF" ? fields3.length : Number(fTok);
91863
+ rawVal = idx === 0 ? l : idx >= 1 && idx <= fields3.length ? fields3[idx - 1] : "";
91864
+ }
91865
+ const left = typeof rawVal === "number" ? numeric2(rawVal) : inputValue(rawVal);
91866
+ const right = strRhs !== void 0 ? string(strRhs) : numeric2(numRhs);
91867
+ const comparison = compare2(left, right, "%.6g");
91868
+ return op === "==" ? comparison === 0 : op === "!=" ? comparison !== 0 : op === ">=" ? comparison >= 0 : op === "<=" ? comparison <= 0 : op === ">" ? comparison > 0 : comparison < 0;
91869
+ };
91870
+ progRest = progRest.slice(cmpCondM[0].length).trim();
91871
+ }
91872
+ }
91873
+ const awkM = syncAwkPrintRe.exec(progRest);
90423
91874
  if (!awkM) return void 0;
90424
- const exprBody = awkM[1]?.trim();
91875
+ const subFn = awkM[1];
91876
+ const subPat = awkM[2];
91877
+ const subRep = awkM[3] ?? "";
91878
+ const subTarget = awkM[4] ?? "0";
91879
+ if (awkM[6] !== void 0) return void 0;
91880
+ const exprBody = awkM[5]?.trim();
91881
+ let subRe;
91882
+ if (subFn && subPat !== void 0) {
91883
+ const aS = subPat.startsWith("^");
91884
+ const c1 = aS ? subPat.slice(1) : subPat;
91885
+ const aE = c1.endsWith("$");
91886
+ const core = aE ? c1.slice(0, -1) : c1;
91887
+ const esc = core.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
91888
+ subRe = new RegExp((aS ? "^" : "") + esc + (aE ? "$" : ""), subFn === "gsub" ? "g" : "");
91889
+ }
90425
91890
  const parts = [];
90426
91891
  if (!exprBody) {
90427
91892
  parts.push({ kind: "field", token: "0" });
90428
91893
  } else {
90429
- const tokenRe = /\$([0-9]+|NF)|"([^"$\\]*)"|(,)/g;
91894
+ syncAwkTokenRe.lastIndex = 0;
91895
+ const tokenRe = syncAwkTokenRe;
90430
91896
  let m;
90431
91897
  while ((m = tokenRe.exec(exprBody)) !== null) {
90432
- if (m[1] !== void 0) parts.push({ kind: "field", token: m[1] });
90433
- else if (m[2] !== void 0) parts.push({ kind: "lit", text: m[2] });
90434
- else if (m[3] !== void 0) parts.push({ kind: "lit", text: " " });
91898
+ if (m[1] !== void 0) {
91899
+ const tm = /^(\$(?:[0-9]+|NF)|NR|NF)\s*(==|!=|>=|<=|>|<)\s*(-?[0-9]+(?:\.[0-9]+)?|"[^"$\\]*")\s*\?\s*(\$(?:[0-9]+|NF)|"[^"$\\]*"|-?[0-9]+(?:\.[0-9]+)?)\s*:\s*(\$(?:[0-9]+|NF)|"[^"$\\]*"|-?[0-9]+(?:\.[0-9]+)?)$/.exec(m[1].trim());
91900
+ if (!tm) return void 0;
91901
+ parts.push({ kind: "ternary", lhs: tm[1], op: tm[2], rhs: tm[3], yes: tm[4], no: tm[5] });
91902
+ } else if (m[2] !== void 0) parts.push({ kind: "int", token: m[2] });
91903
+ else if (m[3] !== void 0) parts.push({ kind: "case", fn: m[3] === "toupper" ? "upper" : "lower", token: m[4] });
91904
+ else if (m[5] !== void 0) parts.push({ kind: "substr", token: m[5], start: Number(m[6]), len: m[7] !== void 0 ? Number(m[7]) : void 0 });
91905
+ else if (m[8] !== void 0) parts.push({ kind: "index", token: m[8], sub: m[9] });
91906
+ else if (m[10] !== void 0) {
91907
+ const aToks = m[10].trim().split(/\s*([+*\/%-])\s*/);
91908
+ for (let ti = 0; ti < aToks.length; ti += 2) {
91909
+ const at = aToks[ti];
91910
+ if (!at.startsWith("$") && at !== "NR" && at !== "NF" && !/^-?[0-9]+(?:\.[0-9]+)?$/.test(at) && !userVars.has(at)) return void 0;
91911
+ }
91912
+ for (let ti = 1; ti < aToks.length; ti += 2) {
91913
+ if (aToks[ti] === "/" || aToks[ti] === "%") {
91914
+ const divisor = Number(aToks[ti + 1]);
91915
+ if (!Number.isFinite(divisor) || divisor === 0) return void 0;
91916
+ }
91917
+ }
91918
+ parts.push({ kind: "arith", tokens: aToks });
91919
+ } else if (m[11] !== void 0) {
91920
+ const offset = Number(m[11]);
91921
+ if (offset > 0) return void 0;
91922
+ parts.push({ kind: "nf_minus", offset });
91923
+ } else if (m[12] !== void 0) parts.push({ kind: "field", token: m[12] });
91924
+ else if (m[0] === "length" || m[0].startsWith("length(")) parts.push({ kind: "length", token: m[13] ?? "0" });
91925
+ else if (m[14] !== void 0) parts.push({ kind: "var", name: m[14] });
91926
+ else if (m[15] !== void 0) parts.push({ kind: "lit", text: m[15] });
91927
+ else if (m[16] !== void 0) {
91928
+ const uv = userVars.get(m[16]);
91929
+ if (uv === void 0) return void 0;
91930
+ parts.push({ kind: "lit", text: uv });
91931
+ } else if (m[17] !== void 0) parts.push({ kind: "lit", text: ofs });
91932
+ }
91933
+ }
91934
+ const outLines = [];
91935
+ for (let li = 0; li < rawLines.length; li++) {
91936
+ let l = rawLines[li];
91937
+ let fields3 = awkSep === void 0 || awkSep === " " ? l.split(/[ \t]+/).filter(Boolean) : l.length === 0 ? [] : l.split(awkSep);
91938
+ if (rowPred && !rowPred(l, fields3, li + 1)) continue;
91939
+ if (subRe) {
91940
+ if (subTarget === "0") {
91941
+ l = l.replace(subRe, (matched) => subRep.split("&").join(matched));
91942
+ fields3 = awkSep === void 0 || awkSep === " " ? l.split(/[ \t]+/).filter(Boolean) : l.length === 0 ? [] : l.split(awkSep);
91943
+ } else {
91944
+ const tIdx = subTarget === "NF" ? fields3.length : Number(subTarget);
91945
+ if (tIdx >= 1 && tIdx <= fields3.length) {
91946
+ fields3 = [...fields3];
91947
+ fields3[tIdx - 1] = fields3[tIdx - 1].replace(subRe, (matched) => subRep.split("&").join(matched));
91948
+ l = fields3.join(ofs);
91949
+ }
91950
+ }
91951
+ }
91952
+ if (parts.length === 1 && parts[0].kind === "field" && parts[0].token === "0") {
91953
+ outLines.push(l);
91954
+ continue;
90435
91955
  }
90436
- }
90437
- return rawLines.map((l) => {
90438
- if (parts.length === 1 && parts[0].kind === "field" && parts[0].token === "0") return l;
90439
- const fields3 = awkSep !== void 0 ? awkSep === " " ? l.trim().split(/\s+/).filter(Boolean) : l.length === 0 ? [] : l.split(awkSep) : l.trim().split(/\s+/).filter(Boolean);
90440
91956
  let out = "";
90441
91957
  for (let pi = 0; pi < parts.length; pi++) {
90442
91958
  const p = parts[pi];
90443
91959
  if (p.kind === "lit") out += p.text;
90444
- else if (p.token === "0") out += l;
91960
+ else if (p.kind === "var") out += String(p.name === "NR" ? li + 1 : fields3.length);
91961
+ else if (p.kind === "nf_minus") {
91962
+ const idx = fields3.length - p.offset;
91963
+ if (idx < 0) return void 0;
91964
+ out += idx === 0 ? l : idx >= 1 && idx <= fields3.length ? fields3[idx - 1] : "";
91965
+ } else if (p.kind === "case") {
91966
+ const idx = p.token === "NF" ? fields3.length : Number(p.token);
91967
+ const s = idx === 0 ? l : idx >= 1 && idx <= fields3.length ? fields3[idx - 1] : "";
91968
+ out += p.fn === "upper" ? s.toUpperCase() : s.toLowerCase();
91969
+ } else if (p.kind === "substr") {
91970
+ const idx = p.token === "NF" ? fields3.length : Number(p.token);
91971
+ const s = idx === 0 ? l : idx >= 1 && idx <= fields3.length ? fields3[idx - 1] : "";
91972
+ const chars = Array.from(s);
91973
+ const s0 = Math.max(0, p.start - 1);
91974
+ out += (p.len !== void 0 ? chars.slice(s0, s0 + Math.max(0, p.len)) : chars.slice(s0)).join("");
91975
+ } else if (p.kind === "index") {
91976
+ const idx = p.token === "NF" ? fields3.length : Number(p.token);
91977
+ const s = idx === 0 ? l : idx >= 1 && idx <= fields3.length ? fields3[idx - 1] : "";
91978
+ const pos = p.sub.length === 0 ? -1 : s.indexOf(p.sub);
91979
+ out += String(pos === -1 ? 0 : pos + 1);
91980
+ } else if (p.kind === "int") {
91981
+ const idx = p.token === "NF" ? fields3.length : Number(p.token);
91982
+ const s = idx === 0 ? l : idx >= 1 && idx <= fields3.length ? fields3[idx - 1] : "";
91983
+ const n = Number(/^[ \t]*([+-]?(?:\d+(?:\.\d*)?|\.\d+))/.exec(s)?.[1] ?? 0);
91984
+ out += String(Math.trunc(n));
91985
+ } else if (p.kind === "ternary") {
91986
+ const resolveAtom = (tok) => {
91987
+ if (tok.startsWith('"') && tok.endsWith('"')) return tok.slice(1, -1);
91988
+ if (tok === "NR") return String(li + 1);
91989
+ if (tok === "NF") return String(fields3.length);
91990
+ if (tok.startsWith("$")) {
91991
+ const fIdx = tok === "$NF" ? fields3.length : Number(tok.slice(1));
91992
+ return fIdx === 0 ? l : fIdx >= 1 && fIdx <= fields3.length ? fields3[fIdx - 1] : "";
91993
+ }
91994
+ return tok;
91995
+ };
91996
+ const lv = resolveAtom(p.lhs);
91997
+ const rv = resolveAtom(p.rhs);
91998
+ const isStrCmp = p.rhs.startsWith('"');
91999
+ let cond = false;
92000
+ if (isStrCmp) {
92001
+ cond = p.op === "==" ? lv === rv : p.op === "!=" ? lv !== rv : p.op === ">" ? lv > rv : p.op === "<" ? lv < rv : p.op === ">=" ? lv >= rv : lv <= rv;
92002
+ } else {
92003
+ const ln = Number(lv) || 0;
92004
+ const rn = Number(rv) || 0;
92005
+ cond = p.op === "==" ? ln === rn : p.op === "!=" ? ln !== rn : p.op === ">" ? ln > rn : p.op === "<" ? ln < rn : p.op === ">=" ? ln >= rn : ln <= rn;
92006
+ }
92007
+ out += resolveAtom(cond ? p.yes : p.no);
92008
+ } else if (p.kind === "arith") {
92009
+ const vals = [];
92010
+ const ops = [];
92011
+ for (let ti = 0; ti < p.tokens.length; ti++) {
92012
+ const tk = p.tokens[ti];
92013
+ if (ti % 2 === 1) {
92014
+ ops.push(tk);
92015
+ } else {
92016
+ let v = 0;
92017
+ if (tk === "NR") v = li + 1;
92018
+ else if (tk === "NF") v = fields3.length;
92019
+ else if (tk.startsWith("$")) {
92020
+ const fSub = tk.slice(1);
92021
+ const idx = fSub === "NF" ? fields3.length : Number(fSub);
92022
+ const rawF = idx === 0 ? l : idx >= 1 && idx <= fields3.length ? fields3[idx - 1] : "";
92023
+ const nm = /^[ \t]*([+-]?(?:\d+(?:\.\d*)?|\.\d+))/.exec(rawF);
92024
+ v = nm ? Number(nm[1]) : 0;
92025
+ } else if (/^-?[0-9]+(?:\.[0-9]+)?$/.test(tk)) {
92026
+ v = Number(tk);
92027
+ } else {
92028
+ const uv = userVars.get(tk) ?? "";
92029
+ const nm = /^[ \t]*([+-]?(?:\d+(?:\.\d*)?|\.\d+))/.exec(uv);
92030
+ v = nm ? Number(nm[1]) : 0;
92031
+ }
92032
+ vals.push(v);
92033
+ }
92034
+ }
92035
+ const addVals = [vals[0]];
92036
+ const addOps = [];
92037
+ for (let oi = 0; oi < ops.length; oi++) {
92038
+ const op = ops[oi];
92039
+ const rhs = vals[oi + 1];
92040
+ if (op === "*" || op === "/" || op === "%") {
92041
+ if ((op === "/" || op === "%") && rhs === 0) return void 0;
92042
+ const lhs = addVals.pop();
92043
+ addVals.push(op === "*" ? lhs * rhs : op === "/" ? lhs / rhs : lhs % rhs);
92044
+ } else {
92045
+ addOps.push(op);
92046
+ addVals.push(rhs);
92047
+ }
92048
+ }
92049
+ let acc = addVals[0];
92050
+ for (let oi = 0; oi < addOps.length; oi++) {
92051
+ acc = addOps[oi] === "+" ? acc + addVals[oi + 1] : acc - addVals[oi + 1];
92052
+ }
92053
+ out += text(numeric2(acc));
92054
+ } else if (p.kind === "length") {
92055
+ const idx = p.token === "NF" ? fields3.length : Number(p.token);
92056
+ const s = idx === 0 ? l : idx >= 1 && idx <= fields3.length ? fields3[idx - 1] : "";
92057
+ out += String(Array.from(s).length);
92058
+ } else if (p.token === "0") out += l;
90445
92059
  else {
90446
92060
  const idx = p.token === "NF" ? fields3.length : Number(p.token);
90447
92061
  out += idx === 0 ? l : idx >= 1 && idx <= fields3.length ? fields3[idx - 1] : "";
90448
92062
  }
90449
92063
  }
90450
- return out;
90451
- });
92064
+ outLines.push(out);
92065
+ }
92066
+ return outLines;
90452
92067
  }
90453
92068
  formatSyncTransformQ(val) {
90454
92069
  let ansi = false;
@@ -90485,35 +92100,558 @@ ${prefix3} line ${offset + line}: \`${source2.split("\n")[line - 1] ?? ""}'
90485
92100
  }
90486
92101
  return out + "'";
90487
92102
  }
90488
- sortSyncLines(rawLines, flag) {
90489
- const rev = flag !== void 0 && flag.includes("r");
90490
- const num = flag !== void 0 && flag.includes("n");
90491
- const uniq = flag !== void 0 && flag.includes("u");
92103
+ wcMaxLineWidth(text3, singleByte) {
92104
+ let columns = 0;
92105
+ let maximum = 0;
92106
+ for (const char of text3) {
92107
+ const point = char.codePointAt(0);
92108
+ if (point === 10 || point === 13 || point === 12) {
92109
+ maximum = Math.max(maximum, columns);
92110
+ columns = 0;
92111
+ } else if (point === 9) columns += 8 - columns % 8;
92112
+ else columns += singleByte ? Number(point >= 32 && point < 127) : wcDisplayWidth(point);
92113
+ }
92114
+ return Math.max(maximum, columns);
92115
+ }
92116
+ compareSyncVersion(a, b) {
92117
+ let ia = 0;
92118
+ let ib = 0;
92119
+ while (ia < a.length || ib < b.length) {
92120
+ while (ia < a.length && !(a[ia] >= "0" && a[ia] <= "9") || ib < b.length && !(b[ib] >= "0" && b[ib] <= "9")) {
92121
+ const ca = ia < a.length ? a[ia] : void 0;
92122
+ const cb = ib < b.length ? b[ib] : void 0;
92123
+ const da = ca !== void 0 && ca >= "0" && ca <= "9";
92124
+ const db = cb !== void 0 && cb >= "0" && cb <= "9";
92125
+ if (da && db) break;
92126
+ if (ca !== cb) {
92127
+ if (ca === void 0) return -1;
92128
+ if (cb === void 0) return 1;
92129
+ if (da) return 1;
92130
+ if (db) return -1;
92131
+ return ca < cb ? -1 : 1;
92132
+ }
92133
+ ia++;
92134
+ ib++;
92135
+ }
92136
+ const sa = ia;
92137
+ while (ia < a.length && a[ia] >= "0" && a[ia] <= "9") ia++;
92138
+ const sb = ib;
92139
+ while (ib < b.length && b[ib] >= "0" && b[ib] <= "9") ib++;
92140
+ if (sa < ia || sb < ib) {
92141
+ const na = BigInt(sa < ia ? a.slice(sa, ia) : "0");
92142
+ const nb = BigInt(sb < ib ? b.slice(sb, ib) : "0");
92143
+ if (na !== nb) return na < nb ? -1 : 1;
92144
+ }
92145
+ }
92146
+ return 0;
92147
+ }
92148
+ evalSyncNl(rawLines, opArgs) {
92149
+ let bodyStyle = "t";
92150
+ let format3 = "rn";
92151
+ let width = 6;
92152
+ let sep = " ";
92153
+ let start = 1;
92154
+ let inc = 1;
92155
+ for (let i = 0; i < opArgs.length; i++) {
92156
+ const a = opArgs[i];
92157
+ if ((a === "-b" || a === "--body-numbering") && i + 1 < opArgs.length) {
92158
+ const v = opArgs[++i];
92159
+ if (v !== "a" && v !== "t" && v !== "n") return void 0;
92160
+ bodyStyle = v;
92161
+ } else if (a === "-ba" || a === "-bt" || a === "-bn") {
92162
+ bodyStyle = a[2];
92163
+ } else if ((a === "-n" || a === "--number-format") && i + 1 < opArgs.length) {
92164
+ const v = opArgs[++i];
92165
+ if (v !== "ln" && v !== "rn" && v !== "rz") return void 0;
92166
+ format3 = v;
92167
+ } else if (a === "-nln" || a === "-nrn" || a === "-nrz") {
92168
+ format3 = a.slice(2);
92169
+ } else if ((a === "-w" || a === "--number-width") && i + 1 < opArgs.length && /^[1-9][0-9]{0,2}$/.test(opArgs[i + 1])) {
92170
+ width = Number(opArgs[++i]);
92171
+ } else if (/^-w[1-9][0-9]{0,2}$/.test(a)) {
92172
+ width = Number(a.slice(2));
92173
+ } else if ((a === "-s" || a === "--number-separator") && i + 1 < opArgs.length) {
92174
+ sep = opArgs[++i];
92175
+ } else if (a.startsWith("-s") && a.length > 2) {
92176
+ sep = a.slice(2);
92177
+ } else if ((a === "-v" || a === "--starting-line-number") && i + 1 < opArgs.length && /^-?[0-9]{1,9}$/.test(opArgs[i + 1])) {
92178
+ start = Number(opArgs[++i]);
92179
+ } else if (/^-v-?[0-9]{1,9}$/.test(a)) {
92180
+ start = Number(a.slice(2));
92181
+ } else if ((a === "-i" || a === "--line-increment") && i + 1 < opArgs.length && /^-?[0-9]{1,9}$/.test(opArgs[i + 1])) {
92182
+ inc = Number(opArgs[++i]);
92183
+ } else if (/^-i-?[0-9]{1,9}$/.test(a)) {
92184
+ inc = Number(a.slice(2));
92185
+ } else {
92186
+ return void 0;
92187
+ }
92188
+ }
92189
+ const out = [];
92190
+ let curStyle = bodyStyle;
92191
+ let num = start;
92192
+ const unnumberedPrefix = " ".repeat(width + sep.length);
92193
+ for (let i = 0; i < rawLines.length; i++) {
92194
+ const l = rawLines[i];
92195
+ if (l === "\\:" || l === "\\:\\:" || l === "\\:\\:\\:") {
92196
+ curStyle = l === "\\:\\:" ? bodyStyle : "n";
92197
+ num = start;
92198
+ out.push("");
92199
+ continue;
92200
+ }
92201
+ const numbered = curStyle === "a" || curStyle === "t" && l.length > 0;
92202
+ if (!numbered) {
92203
+ out.push(l.length === 0 && sep === " " ? " ".repeat(width + 1) : unnumberedPrefix + l);
92204
+ continue;
92205
+ }
92206
+ const label = String(num);
92207
+ const pad = Math.max(0, width - label.length);
92208
+ let prefix3;
92209
+ if (format3 === "ln") prefix3 = label + " ".repeat(pad);
92210
+ else if (format3 === "rz") prefix3 = num < 0 ? "-" + "0".repeat(pad) + label.slice(1) : "0".repeat(pad) + label;
92211
+ else prefix3 = " ".repeat(pad) + label;
92212
+ out.push(prefix3 + sep + l);
92213
+ num += inc;
92214
+ }
92215
+ return out;
92216
+ }
92217
+ evalSyncPaste(rawLines, opArgs) {
92218
+ let serial = false;
92219
+ let delims = [" "];
92220
+ let literal = false;
92221
+ const files = [];
92222
+ const parseDelims = (s) => {
92223
+ if (s.length === 0) return [""];
92224
+ const res = [];
92225
+ const escapes2 = { b: "\b", f: "\f", n: "\n", r: "\r", t: " ", v: "\v", "0": "" };
92226
+ for (let i = 0; i < s.length; i++) {
92227
+ const ch = s[i];
92228
+ if (ch === "\\") {
92229
+ if (i + 1 >= s.length) return void 0;
92230
+ const esc = s[++i];
92231
+ res.push(escapes2[esc] ?? esc);
92232
+ } else {
92233
+ res.push(ch);
92234
+ }
92235
+ }
92236
+ return res.length > 0 ? res : [""];
92237
+ };
92238
+ for (let i = 0; i < opArgs.length; i++) {
92239
+ const a = opArgs[i];
92240
+ if (literal || a === "-" || !a.startsWith("-")) {
92241
+ files.push(a);
92242
+ continue;
92243
+ }
92244
+ if (a === "--") {
92245
+ literal = true;
92246
+ continue;
92247
+ }
92248
+ if (a === "--serial") {
92249
+ serial = true;
92250
+ continue;
92251
+ }
92252
+ if (a === "--delimiters" && i + 1 < opArgs.length) {
92253
+ const d = parseDelims(opArgs[++i]);
92254
+ if (!d) return void 0;
92255
+ delims = d;
92256
+ continue;
92257
+ }
92258
+ if (a.startsWith("--delimiters=")) {
92259
+ const d = parseDelims(a.slice(13));
92260
+ if (!d) return void 0;
92261
+ delims = d;
92262
+ continue;
92263
+ }
92264
+ if (a.startsWith("--")) return void 0;
92265
+ for (let k = 1; k < a.length; k++) {
92266
+ const f = a[k];
92267
+ if (f === "s") serial = true;
92268
+ else if (f === "d") {
92269
+ const rest = a.slice(k + 1);
92270
+ const rawD = rest.length > 0 ? rest : i + 1 < opArgs.length ? opArgs[++i] : void 0;
92271
+ if (rawD === void 0) return void 0;
92272
+ const d = parseDelims(rawD);
92273
+ if (!d) return void 0;
92274
+ delims = d;
92275
+ break;
92276
+ } else return void 0;
92277
+ }
92278
+ }
92279
+ if (files.length === 0) files.push("-");
92280
+ if (!files.every((f) => f === "-")) return void 0;
92281
+ if (serial) {
92282
+ if (files.length !== 1) return void 0;
92283
+ if (rawLines.length === 0) return [];
92284
+ let joined = rawLines[0];
92285
+ for (let i = 1; i < rawLines.length; i++) {
92286
+ joined += delims[(i - 1) % delims.length] + rawLines[i];
92287
+ }
92288
+ return joined.split("\n");
92289
+ }
92290
+ const cols = files.length;
92291
+ const out = [];
92292
+ for (let i = 0; i < rawLines.length; i += cols) {
92293
+ let row = rawLines[i] ?? "";
92294
+ for (let c = 1; c < cols; c++) {
92295
+ row += delims[(c - 1) % delims.length] + (rawLines[i + c] ?? "");
92296
+ }
92297
+ out.push(row);
92298
+ }
92299
+ return out;
92300
+ }
92301
+ evalSyncNumfmt(rawLines, opArgs) {
92302
+ let fromScale = "none";
92303
+ let toScale = "none";
92304
+ let padding2 = 0;
92305
+ let suffix2 = "";
92306
+ for (let i = 0; i < opArgs.length; i++) {
92307
+ const a = opArgs[i];
92308
+ if (a.startsWith("--from=")) {
92309
+ const v = a.slice(7);
92310
+ if (v === "none" || v === "iec" || v === "iec-i" || v === "si" || v === "auto") fromScale = v;
92311
+ else return void 0;
92312
+ } else if (a.startsWith("--to=")) {
92313
+ const v = a.slice(5);
92314
+ if (v === "none" || v === "iec" || v === "iec-i" || v === "si") toScale = v;
92315
+ else return void 0;
92316
+ } else if (a.startsWith("--padding=")) {
92317
+ const v = a.slice(10);
92318
+ if (!/^-?[1-9][0-9]{0,2}$/.test(v)) return void 0;
92319
+ padding2 = Number(v);
92320
+ } else if (a.startsWith("--suffix=")) {
92321
+ suffix2 = a.slice(9);
92322
+ } else {
92323
+ return void 0;
92324
+ }
92325
+ }
92326
+ const units = "KMGTPEZY";
92327
+ const out = [];
92328
+ for (let i = 0; i < rawLines.length; i++) {
92329
+ const raw = rawLines[i].trim();
92330
+ if (raw.length === 0) {
92331
+ out.push("");
92332
+ continue;
92333
+ }
92334
+ const m = /^([+-]?(?:\d+(?:\.\d*)?|\.\d+))([KMGTPEZYkmgtpezy]i?)?$/.exec(raw);
92335
+ if (!m) return void 0;
92336
+ let val = Number(m[1]);
92337
+ const suf = m[2] ?? "";
92338
+ if (suf.length > 0) {
92339
+ if (fromScale === "none") return void 0;
92340
+ const uChar = suf[0].toUpperCase();
92341
+ const pIdx = units.indexOf(uChar) + 1;
92342
+ if (pIdx <= 0) return void 0;
92343
+ const hasI = suf.length === 2 && suf[1].toLowerCase() === "i";
92344
+ if (fromScale === "iec-i" && !hasI) return void 0;
92345
+ if ((fromScale === "iec" || fromScale === "si") && hasI) return void 0;
92346
+ const fBase = fromScale === "iec" || fromScale === "iec-i" || fromScale === "auto" && hasI ? 1024 : 1e3;
92347
+ val = val * Math.pow(fBase, pIdx);
92348
+ } else if (fromScale === "iec-i") {
92349
+ }
92350
+ val = val >= 0 ? Math.ceil(val - 1e-12) : -Math.ceil(Math.abs(val) - 1e-12);
92351
+ let rendered;
92352
+ if (toScale === "none") {
92353
+ rendered = String(Math.trunc(val));
92354
+ } else {
92355
+ const tBase = toScale === "iec" || toScale === "iec-i" ? 1024 : 1e3;
92356
+ let pIdx = 0;
92357
+ let scaled = val;
92358
+ while (Math.abs(scaled) >= tBase && pIdx < units.length) {
92359
+ scaled /= tBase;
92360
+ pIdx++;
92361
+ }
92362
+ if (pIdx === 0) {
92363
+ rendered = String(Math.trunc(scaled));
92364
+ } else {
92365
+ if (Math.abs(scaled) < 10) {
92366
+ scaled = (scaled >= 0 ? Math.ceil(scaled * 10 - 1e-12) : -Math.ceil(Math.abs(scaled) * 10 - 1e-12)) / 10;
92367
+ if (Math.abs(scaled) >= tBase && pIdx < units.length) {
92368
+ scaled /= tBase;
92369
+ pIdx++;
92370
+ }
92371
+ } else {
92372
+ scaled = scaled >= 0 ? Math.ceil(scaled - 1e-12) : -Math.ceil(Math.abs(scaled) - 1e-12);
92373
+ if (Math.abs(scaled) >= tBase && pIdx < units.length) {
92374
+ scaled /= tBase;
92375
+ pIdx++;
92376
+ }
92377
+ }
92378
+ const numText = Math.abs(scaled) < 10 ? scaled.toFixed(1) : scaled.toFixed(0);
92379
+ const uText = (toScale === "si" && pIdx === 1 ? "k" : units[pIdx - 1]) + (toScale === "iec-i" ? "i" : "");
92380
+ rendered = numText + uText;
92381
+ }
92382
+ }
92383
+ rendered += suffix2;
92384
+ if (padding2 !== 0) {
92385
+ const w = Math.abs(padding2);
92386
+ if (rendered.length < w) {
92387
+ const pad = " ".repeat(w - rendered.length);
92388
+ rendered = padding2 < 0 ? rendered + pad : pad + rendered;
92389
+ }
92390
+ }
92391
+ out.push(rendered);
92392
+ }
92393
+ return out;
92394
+ }
92395
+ evalSyncSort(rawLines, opArgs, isByteLocale) {
92396
+ if (isByteLocale) return void 0;
92397
+ let rev = false;
92398
+ let num = false;
92399
+ let human = false;
92400
+ let month = false;
92401
+ let dict = false;
92402
+ let uniq = false;
92403
+ let fold2 = false;
92404
+ let blanks = false;
92405
+ let stable = false;
92406
+ let ver = false;
92407
+ let sep;
92408
+ let keySpec;
92409
+ for (let i = 0; i < opArgs.length; i++) {
92410
+ const a = opArgs[i];
92411
+ if (/^-[runfbsVhMd]+$/.test(a)) {
92412
+ if (a.includes("r")) rev = true;
92413
+ if (a.includes("n")) num = true;
92414
+ if (a.includes("h")) human = true;
92415
+ if (a.includes("M")) month = true;
92416
+ if (a.includes("d")) dict = true;
92417
+ if (a.includes("u")) uniq = true;
92418
+ if (a.includes("f")) fold2 = true;
92419
+ if (a.includes("b")) blanks = true;
92420
+ if (a.includes("s")) stable = true;
92421
+ if (a.includes("V")) ver = true;
92422
+ } else if (a === "--reverse") rev = true;
92423
+ else if (a === "--numeric-sort") num = true;
92424
+ else if (a === "--human-numeric-sort") human = true;
92425
+ else if (a === "--month-sort") month = true;
92426
+ else if (a === "--dictionary-order") dict = true;
92427
+ else if (a === "--unique") uniq = true;
92428
+ else if (a === "--ignore-case") fold2 = true;
92429
+ else if (a === "--ignore-leading-blanks") blanks = true;
92430
+ else if (a === "--stable") stable = true;
92431
+ else if (a === "--version-sort") ver = true;
92432
+ else if (a === "-t" && i + 1 < opArgs.length && opArgs[i + 1].length === 1) {
92433
+ sep = opArgs[++i];
92434
+ } else if (a.startsWith("-t") && a.length === 3) {
92435
+ sep = a[2];
92436
+ } else if (a.startsWith("--field-separator=") && a.length === 19) {
92437
+ sep = a[18];
92438
+ } else if (a === "-k" && i + 1 < opArgs.length) {
92439
+ if (keySpec !== void 0) return void 0;
92440
+ keySpec = opArgs[++i];
92441
+ } else if (a.startsWith("-k") && a.length > 2) {
92442
+ if (keySpec !== void 0) return void 0;
92443
+ keySpec = a.slice(2);
92444
+ } else {
92445
+ return void 0;
92446
+ }
92447
+ }
92448
+ if (ver || keySpec?.includes("V")) return void 0;
92449
+ let startField = 1;
92450
+ let endField;
92451
+ let keyNum = num;
92452
+ let keyHuman = human;
92453
+ let keyMonth = month;
92454
+ let keyDict = dict;
92455
+ let keyRev = rev;
92456
+ let keyFold = fold2;
92457
+ let keyBlanks = blanks;
92458
+ let keyVer = ver;
92459
+ if (keySpec !== void 0) {
92460
+ const km = /^([1-9][0-9]{0,2})(?:,([1-9][0-9]{0,2}))?([nrbfVhMd]*)$/.exec(keySpec);
92461
+ if (!km) return void 0;
92462
+ startField = Number(km[1]);
92463
+ endField = km[2] !== void 0 ? Number(km[2]) : void 0;
92464
+ if (endField !== void 0 && endField < startField) return void 0;
92465
+ const kf = km[3] ?? "";
92466
+ if (kf.includes("n")) keyNum = true;
92467
+ if (kf.includes("h")) keyHuman = true;
92468
+ if (kf.includes("M")) keyMonth = true;
92469
+ if (kf.includes("d")) keyDict = true;
92470
+ if (kf.includes("r")) keyRev = true;
92471
+ if (kf.includes("f")) keyFold = true;
92472
+ if (kf.includes("b")) keyBlanks = true;
92473
+ if (kf.includes("V")) keyVer = true;
92474
+ }
92475
+ const extractKey = (l) => {
92476
+ let raw = keySpec === void 0 ? l : (() => {
92477
+ if (sep !== void 0) {
92478
+ const fields3 = l.split(sep);
92479
+ return fields3.slice(startField - 1, endField).join(sep);
92480
+ }
92481
+ let offset = 0;
92482
+ let start = l.length;
92483
+ let end = l.length;
92484
+ for (let field2 = 1; offset < l.length; field2++) {
92485
+ if (field2 === startField) start = offset;
92486
+ while (l[offset] === " " || l[offset] === " ") offset++;
92487
+ while (offset < l.length && l[offset] !== " " && l[offset] !== " ") offset++;
92488
+ if (field2 === endField) {
92489
+ end = offset;
92490
+ break;
92491
+ }
92492
+ }
92493
+ return l.slice(start, end);
92494
+ })();
92495
+ if (keyBlanks) raw = raw.replace(/^[ \t]+/, "");
92496
+ if (keyDict) raw = raw.replace(/[^a-zA-Z0-9 \t]+/g, "");
92497
+ return keyFold ? raw.toUpperCase() : raw;
92498
+ };
90492
92499
  const parseNum = (s) => {
90493
- const m = /^[ \t]*([+-]?(?:\d+(?:\.\d*)?|\.\d+))/.exec(s);
92500
+ const m = /^[ \t]*(-?(?:\d+(?:\.\d*)?|\.\d+))/.exec(s);
90494
92501
  return m ? Number(m[1]) : 0;
90495
92502
  };
92503
+ const compareHuman = (sa, sb) => {
92504
+ const parseH = (s) => {
92505
+ const m = /^[ \t]*(-?(?:\d+(?:\.\d*)?|\.\d+))([KMGTPEZYkmgtpezy])?/.exec(s);
92506
+ if (!m) return { sign: 0, unit: 0, val: 0 };
92507
+ const val = Number(m[1]);
92508
+ if (val === 0) return { sign: 0, unit: 0, val: 0 };
92509
+ const uChar = m[2] ? m[2].toUpperCase() : "";
92510
+ const unit = uChar === "" ? 0 : "KMGTPEZY".indexOf(uChar) + 1;
92511
+ return { sign: val < 0 ? -1 : 1, unit, val };
92512
+ };
92513
+ const ha = parseH(sa);
92514
+ const hb = parseH(sb);
92515
+ if (ha.sign !== hb.sign) return ha.sign - hb.sign;
92516
+ if (ha.unit !== hb.unit) return ha.sign < 0 ? hb.unit - ha.unit : ha.unit - hb.unit;
92517
+ return ha.val - hb.val;
92518
+ };
92519
+ const parseMonth = (s) => {
92520
+ const m = /^[ \t]*([a-zA-Z]{3})/.exec(s);
92521
+ if (!m) return 0;
92522
+ const idx = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"].indexOf(m[1].toUpperCase());
92523
+ return idx === -1 ? 0 : idx + 1;
92524
+ };
90496
92525
  const sorted = [...rawLines].sort((a, b) => {
90497
- if (num) {
90498
- const na = parseNum(a);
90499
- const nb = parseNum(b);
90500
- if (na !== nb) return rev ? nb - na : na - nb;
90501
- }
92526
+ const ka = extractKey(a);
92527
+ const kb = extractKey(b);
92528
+ if (keyHuman) {
92529
+ const hc = compareHuman(ka, kb);
92530
+ if (hc !== 0) return keyRev ? -hc : hc;
92531
+ } else if (keyMonth) {
92532
+ const ma = parseMonth(ka);
92533
+ const mb = parseMonth(kb);
92534
+ if (ma !== mb) return keyRev ? mb - ma : ma - mb;
92535
+ } else if (keyNum) {
92536
+ const na = parseNum(ka);
92537
+ const nb = parseNum(kb);
92538
+ if (na !== nb) return keyRev ? nb - na : na - nb;
92539
+ } else if (keyVer) {
92540
+ const vc = this.compareSyncVersion(ka, kb);
92541
+ if (vc !== 0) return keyRev ? -vc : vc;
92542
+ } else if (ka !== kb) {
92543
+ return ka < kb ? keyRev ? 1 : -1 : keyRev ? -1 : 1;
92544
+ }
92545
+ if (uniq || stable) return 0;
92546
+ const fa = fold2 ? a.toUpperCase() : a;
92547
+ const fb = fold2 ? b.toUpperCase() : b;
92548
+ if (fa !== fb) return fa < fb ? rev ? 1 : -1 : rev ? -1 : 1;
90502
92549
  return a < b ? rev ? 1 : -1 : a > b ? rev ? -1 : 1 : 0;
90503
92550
  });
90504
92551
  if (!uniq) return sorted;
90505
92552
  const dedup = [];
90506
92553
  for (let i = 0; i < sorted.length; i++) {
90507
- if (i === 0 || sorted[i] !== sorted[i - 1]) dedup.push(sorted[i]);
92554
+ if (i === 0) {
92555
+ dedup.push(sorted[i]);
92556
+ } else {
92557
+ const ka = extractKey(sorted[i]);
92558
+ const kb = extractKey(sorted[i - 1]);
92559
+ const same = keyHuman ? compareHuman(ka, kb) === 0 : keyMonth ? parseMonth(ka) === parseMonth(kb) : keyNum ? parseNum(ka) === parseNum(kb) : keyVer ? this.compareSyncVersion(ka, kb) === 0 : ka === kb;
92560
+ if (!same) dedup.push(sorted[i]);
92561
+ }
90508
92562
  }
90509
92563
  return dedup;
90510
92564
  }
90511
- translateSyncTr(input3, set1Spec, set2Spec) {
90512
- if (set1Spec === "a-z" && set2Spec === "A-Z") return input3.toUpperCase();
90513
- if (set1Spec === "A-Z" && set2Spec === "a-z") return input3.toLowerCase();
90514
- const s1 = this.expandSyncTrCharArray(set1Spec);
92565
+ normalizeSyncWcFlag(arg) {
92566
+ if (arg === "-l" || arg === "--lines") return "-l";
92567
+ if (arg === "-c" || arg === "--bytes") return "-c";
92568
+ if (arg === "-w" || arg === "--words") return "-w";
92569
+ if (arg === "-m" || arg === "--chars") return "-m";
92570
+ if (arg === "-L" || arg === "--max-line-length") return "-L";
92571
+ return void 0;
92572
+ }
92573
+ evalSyncUniq(rawLines, opArgs) {
92574
+ let ignoreCase = false;
92575
+ let hasCount = false;
92576
+ let onlyRepeated = false;
92577
+ let onlyUnique = false;
92578
+ let skipFields = 0;
92579
+ let skipChars = 0;
92580
+ let checkChars = Infinity;
92581
+ for (let i = 0; i < opArgs.length; i++) {
92582
+ const a = opArgs[i];
92583
+ if (a === "--ignore-case") ignoreCase = true;
92584
+ else if (a === "--count") hasCount = true;
92585
+ else if (a === "--repeated") onlyRepeated = true;
92586
+ else if (a === "--unique") onlyUnique = true;
92587
+ else if (/^--skip-fields=[0-9]{1,4}$/.test(a)) skipFields = Number(a.slice(14));
92588
+ else if (/^--skip-chars=[0-9]{1,4}$/.test(a)) skipChars = Number(a.slice(13));
92589
+ else if (/^--check-chars=[0-9]{1,4}$/.test(a)) checkChars = Number(a.slice(14));
92590
+ else if ((a === "-f" || a === "-s" || a === "-w") && i + 1 < opArgs.length && /^[0-9]{1,4}$/.test(opArgs[i + 1])) {
92591
+ const n = Number(opArgs[++i]);
92592
+ if (a === "-f") skipFields = n;
92593
+ else if (a === "-s") skipChars = n;
92594
+ else checkChars = n;
92595
+ } else if (/^-[fsw][0-9]{1,4}$/.test(a)) {
92596
+ const n = Number(a.slice(2));
92597
+ if (a[1] === "f") skipFields = n;
92598
+ else if (a[1] === "s") skipChars = n;
92599
+ else checkChars = n;
92600
+ } else if (/^-[cdui]+$/.test(a)) {
92601
+ for (let k = 1; k < a.length; k++) {
92602
+ const ch = a[k];
92603
+ if (ch === "i") ignoreCase = true;
92604
+ else if (ch === "c") hasCount = true;
92605
+ else if (ch === "d") onlyRepeated = true;
92606
+ else if (ch === "u") onlyUnique = true;
92607
+ }
92608
+ } else {
92609
+ return void 0;
92610
+ }
92611
+ }
92612
+ const keyOf = (l) => {
92613
+ let offset = 0;
92614
+ for (let f = 0; f < skipFields; f++) {
92615
+ while (offset < l.length && (l[offset] === " " || l[offset] === " ")) offset++;
92616
+ while (offset < l.length && l[offset] !== " " && l[offset] !== " ") offset++;
92617
+ }
92618
+ if (skipChars === 0 && checkChars === Infinity) {
92619
+ const sub2 = l.slice(offset);
92620
+ return ignoreCase ? sub2.toLowerCase() : sub2;
92621
+ }
92622
+ const chars = Array.from(l.slice(offset));
92623
+ const sub = (checkChars === Infinity ? chars.slice(skipChars) : chars.slice(skipChars, skipChars + checkChars)).join("");
92624
+ return ignoreCase ? sub.toLowerCase() : sub;
92625
+ };
92626
+ const outLines = [];
92627
+ let uIdx = 0;
92628
+ while (uIdx < rawLines.length) {
92629
+ const k0 = keyOf(rawLines[uIdx]);
92630
+ let uEnd = uIdx + 1;
92631
+ while (uEnd < rawLines.length && keyOf(rawLines[uEnd]) === k0) uEnd++;
92632
+ const count2 = uEnd - uIdx;
92633
+ if ((!onlyRepeated || count2 > 1) && (!onlyUnique || count2 === 1)) {
92634
+ outLines.push(hasCount ? `${String(count2).padStart(7, " ")} ${rawLines[uIdx]}` : rawLines[uIdx]);
92635
+ }
92636
+ uIdx = uEnd;
92637
+ }
92638
+ return outLines;
92639
+ }
92640
+ sortSyncLines(rawLines, flag) {
92641
+ return this.evalSyncSort(rawLines, flag !== void 0 ? [flag] : [], false) ?? [...rawLines];
92642
+ }
92643
+ translateSyncTr(input3, set1Spec, set2Spec, truncateSet1 = false) {
92644
+ if ((set1Spec === "a-z" || set1Spec === "[:lower:]") && (set2Spec === "A-Z" || set2Spec === "[:upper:]")) {
92645
+ return input3.replace(/[a-z]/g, (ch) => String.fromCharCode(ch.charCodeAt(0) - 32));
92646
+ }
92647
+ if ((set1Spec === "A-Z" || set1Spec === "[:upper:]") && (set2Spec === "a-z" || set2Spec === "[:lower:]")) {
92648
+ return input3.replace(/[A-Z]/g, (ch) => String.fromCharCode(ch.charCodeAt(0) + 32));
92649
+ }
92650
+ const rawS1 = this.expandSyncTrCharArray(set1Spec);
90515
92651
  const s2 = this.expandSyncTrCharArray(set2Spec);
90516
- if (!s1 || !s2 || s1.length === 0 || s2.length === 0) return void 0;
92652
+ if (!rawS1 || !s2 || rawS1.length === 0 || s2.length === 0) return void 0;
92653
+ const s1 = truncateSet1 ? rawS1.slice(0, s2.length) : rawS1;
92654
+ if (s1.length === 0) return input3;
90517
92655
  if (s1.length === 1 && s2.length === 1) return input3.split(s1[0]).join(s2[0]);
90518
92656
  const map = /* @__PURE__ */ new Map();
90519
92657
  for (let i = 0; i < s1.length; i++) {
@@ -90657,7 +92795,7 @@ ${prefix3} line ${offset + line}: \`${source2.split("\n")[line - 1] ?? ""}'
90657
92795
  const sName = sCmd.words[0].plain;
90658
92796
  if (!sName || hasShellFunction(rawState, sName) || rawState.extensions?.builtins.has(sName)) return void 0;
90659
92797
  const extDef = this.getExternalCommand(sName);
90660
- if (!extDef || sName !== "rev" && sName !== "tac" && !builtInDirectContextExecutors.has(extDef.execute) || (sName === "rev" || sName === "tac") && customRegisteredRegistries.has(this.commands) || customRegisteredCommands.has(extDef.execute)) return void 0;
92798
+ if (!extDef || sName !== "rev" && sName !== "tac" && sName !== "nl" && sName !== "paste" && sName !== "jq" && !builtInDirectContextExecutors.has(extDef.execute) || customRegisteredCommands.has(extDef.execute)) return void 0;
90661
92799
  if (!this.arePureArgWords(sCmd.words, rawState)) return void 0;
90662
92800
  const sArgs = [];
90663
92801
  for (let w = 1; w < sCmd.words.length; w++) {
@@ -90670,21 +92808,24 @@ ${prefix3} line ${offset + line}: \`${source2.split("\n")[line - 1] ?? ""}'
90670
92808
  } else if (sName === "tr") {
90671
92809
  if (this.evalSyncTr("", sArgs) === void 0) return void 0;
90672
92810
  } else if (sName === "uniq") {
90673
- if (sArgs.length > 1 || sArgs.length === 1 && sArgs[0] !== "-c" && sArgs[0] !== "-d" && sArgs[0] !== "-u" && sArgs[0] !== "-i") return void 0;
92811
+ if (this.evalSyncUniq([], sArgs) === void 0) return void 0;
90674
92812
  } else if (sName === "sort") {
90675
- if (sArgs.length > 1 || sArgs.length === 1 && sArgs[0] !== "-r" && sArgs[0] !== "-u" && sArgs[0] !== "-n" && sArgs[0] !== "-rn" && sArgs[0] !== "-nr" && sArgs[0] !== "-ru" && sArgs[0] !== "-ur") return void 0;
92813
+ if (this.evalSyncSort([], sArgs, byteLocale(rawState.variables)) === void 0) return void 0;
90676
92814
  } else if (sName === "head" || sName === "tail") {
90677
92815
  if (sArgs.length === 0) {
90678
92816
  sArgs.push("-n", "10");
90679
- } else if (sArgs.length === 1 && /^-(?:n|c)?[0-9]+$/.test(sArgs[0])) {
90680
- const flag = sArgs[0].startsWith("-c") ? "-c" : "-n";
90681
- const numStr = sArgs[0].startsWith("-n") || sArgs[0].startsWith("-c") ? sArgs[0].slice(2) : sArgs[0].slice(1);
92817
+ } else if (sArgs.length === 1 && (/^-(?:n|c)?[0-9]+$/.test(sArgs[0]) || /^--(?:lines|bytes)=[0-9]+$/.test(sArgs[0]) || sName === "tail" && /^(?:-n|--lines=)\+[0-9]+$/.test(sArgs[0]) || sName === "head" && /^(?:-n|--lines=)-[0-9]+$/.test(sArgs[0]))) {
92818
+ const flag = sArgs[0].startsWith("-c") || sArgs[0].startsWith("--bytes=") ? "-c" : "-n";
92819
+ const numStr = sArgs[0].startsWith("--") ? sArgs[0].slice(sArgs[0].indexOf("=") + 1) : sArgs[0].startsWith("-n") || sArgs[0].startsWith("-c") ? sArgs[0].slice(2) : sArgs[0].slice(1);
90682
92820
  sArgs.length = 0;
90683
92821
  sArgs.push(flag, numStr);
90684
92822
  }
90685
- if (sArgs.length !== 2 || sArgs[0] !== "-n" && sArgs[0] !== "-c" || !/^[0-9]+$/.test(sArgs[1])) return void 0;
92823
+ const validNum = sArgs.length === 2 && (sArgs[0] === "-n" && (/^[0-9]+$/.test(sArgs[1]) || sName === "tail" && /^\+[0-9]+$/.test(sArgs[1]) || sName === "head" && /^-[0-9]+$/.test(sArgs[1])) || sArgs[0] === "-c" && /^[0-9]+$/.test(sArgs[1]));
92824
+ if (!validNum) return void 0;
90686
92825
  } else if (sName === "wc") {
90687
- if (sArgs.length !== 1 || sArgs[0] !== "-l" && sArgs[0] !== "-c" && sArgs[0] !== "-w") return void 0;
92826
+ const normWc = sArgs.length === 1 ? this.normalizeSyncWcFlag(sArgs[0]) : void 0;
92827
+ if (!normWc) return void 0;
92828
+ sArgs[0] = normWc;
90688
92829
  } else if (sName === "sed") {
90689
92830
  if (this.evalSyncSed([], sArgs) === void 0) return void 0;
90690
92831
  } else if (sName === "rev") {
@@ -90694,11 +92835,19 @@ ${prefix3} line ${offset + line}: \`${source2.split("\n")[line - 1] ?? ""}'
90694
92835
  } else if (sName === "grep") {
90695
92836
  if (this.evalSyncGrep([], sArgs, Boolean(rawState.errexit)) === void 0) return void 0;
90696
92837
  } else if (sName === "jq") {
90697
- if (this.evalSyncJq("null", sArgs) === void 0) return void 0;
92838
+ if (sArgs.length === 0 || sArgs.length > 2) return void 0;
92839
+ if (sArgs.length === 1 && sArgs[0].startsWith("-")) return void 0;
92840
+ if (sArgs.length === 2 && !["-r", "--raw-output", "-c", "--compact-output", "-rc", "-cr"].includes(sArgs[0])) return void 0;
90698
92841
  } else if (sName === "base64") {
90699
92842
  if (sArgs.length > 1 || sArgs.length === 1 && sArgs[0] !== "-d" && sArgs[0] !== "--decode") return void 0;
90700
- } else if (sName === "tac" || sName === "nl") {
92843
+ } else if (sName === "tac") {
90701
92844
  if (sArgs.length !== 0) return void 0;
92845
+ } else if (sName === "nl") {
92846
+ if (this.evalSyncNl([], sArgs) === void 0) return void 0;
92847
+ } else if (sName === "paste") {
92848
+ if (this.evalSyncPaste([], sArgs) === void 0) return void 0;
92849
+ } else if (sName === "numfmt") {
92850
+ if (this.evalSyncNumfmt([], sArgs) === void 0) return void 0;
90702
92851
  } else {
90703
92852
  return void 0;
90704
92853
  }
@@ -90776,13 +92925,16 @@ ${prefix3} line ${offset + line}: \`${source2.split("\n")[line - 1] ?? ""}'
90776
92925
  const isInlineBase64 = firstName === "base64";
90777
92926
  const isInlineTac = firstName === "tac";
90778
92927
  const isInlineNl = firstName === "nl";
90779
- const isInlineSort = firstName === "sort" && !byteLocale(rawState.variables) && (stageArgs.length === 0 || stageArgs.length === 1 && (stageArgs[0] === "-r" || stageArgs[0] === "-u" || stageArgs[0] === "-n" || stageArgs[0] === "-rn" || stageArgs[0] === "-nr" || stageArgs[0] === "-ru" || stageArgs[0] === "-ur"));
90780
- const isInlineUniq = firstName === "uniq" && (stageArgs.length === 0 || stageArgs.length === 1 && (stageArgs[0] === "-d" || stageArgs[0] === "-u" || stageArgs[0] === "-c"));
92928
+ const isInlinePaste = firstName === "paste";
92929
+ const isInlineNumfmt = firstName === "numfmt";
92930
+ const isInlineSort = firstName === "sort" && !byteLocale(rawState.variables);
92931
+ const isInlineUniq = firstName === "uniq";
90781
92932
  const inlineSedMatch = firstName === "sed";
90782
- if (firstName === "rev" || firstName === "head" || firstName === "tail" || firstName === "wc" || firstName === "cut" && stageArgs.length === 2 && stageArgs[0] === "-c" || isInlineCutField || isInlineTr || isInlineSort || isInlineUniq || inlineSedMatch || isInlineAwk || isInlineGrep || isInlineJq || isInlineBase64 || isInlineTac || isInlineNl) {
92933
+ if (firstName === "rev" || firstName === "head" || firstName === "tail" || firstName === "wc" || firstName === "cut" && stageArgs.length === 2 && stageArgs[0] === "-c" || isInlineCutField || isInlineTr || isInlineSort || isInlineUniq || inlineSedMatch || isInlineAwk || isInlineGrep || isInlineJq || isInlineBase64 || isInlineTac || isInlineNl || isInlinePaste || isInlineNumfmt) {
90783
92934
  const inStr = prevLen === 0 ? "" : sharedSyncPipeDecoder.decode(prevBuf.subarray(0, prevLen));
90784
92935
  const rawLines = inStr.length === 0 ? [] : inStr.endsWith("\n") ? inStr.slice(0, -1).split("\n") : inStr.split("\n");
90785
92936
  let outLines = [];
92937
+ let sedTerminated = false;
90786
92938
  if (firstName === "rev") {
90787
92939
  outLines = rawLines.map((l) => Array.from(l).reverse().join(""));
90788
92940
  } else if (firstName === "head" || firstName === "tail") {
@@ -90797,7 +92949,14 @@ ${prefix3} line ${offset + line}: \`${source2.split("\n")[line - 1] ?? ""}'
90797
92949
  prevLen = sub.byteLength;
90798
92950
  continue;
90799
92951
  }
90800
- outLines = firstName === "head" ? rawLines.slice(0, count2) : count2 === 0 ? [] : rawLines.slice(-count2);
92952
+ if (firstName === "tail" && stageArgs[1].startsWith("+")) {
92953
+ outLines = rawLines.slice(Math.max(0, count2 - 1));
92954
+ } else if (firstName === "head" && stageArgs[1].startsWith("-")) {
92955
+ const drop = Math.abs(count2);
92956
+ outLines = drop === 0 ? [...rawLines] : rawLines.slice(0, Math.max(0, rawLines.length - drop));
92957
+ } else {
92958
+ outLines = firstName === "head" ? rawLines.slice(0, count2) : count2 === 0 ? [] : rawLines.slice(-count2);
92959
+ }
90801
92960
  } else if (firstName === "wc") {
90802
92961
  if (stageArgs[0] === "-l") {
90803
92962
  let nl = 0;
@@ -90806,6 +92965,10 @@ ${prefix3} line ${offset + line}: \`${source2.split("\n")[line - 1] ?? ""}'
90806
92965
  } else if (stageArgs[0] === "-w") {
90807
92966
  const trimmed = inStr.trim();
90808
92967
  outLines = [String(trimmed.length === 0 ? 0 : trimmed.split(/[ \t\n\r\f\v]+/).length)];
92968
+ } else if (stageArgs[0] === "-m") {
92969
+ outLines = [String(byteLocale(rawState.variables) ? prevLen : Array.from(inStr).length)];
92970
+ } else if (stageArgs[0] === "-L") {
92971
+ outLines = [String(this.wcMaxLineWidth(inStr, byteLocale(rawState.variables)))];
90809
92972
  } else {
90810
92973
  outLines = [String(prevLen)];
90811
92974
  }
@@ -90826,24 +92989,16 @@ ${prefix3} line ${offset + line}: \`${source2.split("\n")[line - 1] ?? ""}'
90826
92989
  prevLen = written2;
90827
92990
  continue;
90828
92991
  } else if (isInlineSort) {
90829
- outLines = this.sortSyncLines(rawLines, stageArgs[0]);
92992
+ outLines = this.evalSyncSort(rawLines, stageArgs, false) ?? [];
90830
92993
  } else if (isInlineUniq) {
90831
- const mode = stageArgs[0];
90832
- outLines = [];
90833
- let uIdx = 0;
90834
- while (uIdx < rawLines.length) {
90835
- let uEnd = uIdx + 1;
90836
- while (uEnd < rawLines.length && rawLines[uEnd] === rawLines[uIdx]) uEnd++;
90837
- const count2 = uEnd - uIdx;
90838
- if (mode === "-d" ? count2 > 1 : mode === "-u" ? count2 === 1 : true) {
90839
- outLines.push(mode === "-c" ? `${String(count2).padStart(7, " ")} ${rawLines[uIdx]}` : rawLines[uIdx]);
90840
- }
90841
- uIdx = uEnd;
90842
- }
92994
+ const uniqRes = this.evalSyncUniq(rawLines, stageArgs);
92995
+ if (uniqRes === void 0) return void 0;
92996
+ outLines = uniqRes;
90843
92997
  } else if (inlineSedMatch) {
90844
92998
  const sedRes = this.evalSyncSed(rawLines, stageArgs);
90845
92999
  if (sedRes === void 0) return void 0;
90846
- outLines = sedRes;
93000
+ outLines = sedRes.lines;
93001
+ sedTerminated = sedRes.lastInputIndex < rawLines.length - 1;
90847
93002
  } else if (isInlineAwk) {
90848
93003
  const awkRes = this.evalSyncAwk(rawLines, stageArgs);
90849
93004
  if (awkRes === void 0) return void 0;
@@ -90858,14 +93013,17 @@ ${prefix3} line ${offset + line}: \`${source2.split("\n")[line - 1] ?? ""}'
90858
93013
  if (inStr.length > 0 && !inStr.endsWith("\n")) return void 0;
90859
93014
  outLines = [...rawLines].reverse();
90860
93015
  } else if (isInlineNl) {
90861
- outLines = [];
90862
- let nlNum = 1;
90863
- for (let li = 0; li < rawLines.length; li++) {
90864
- const l = rawLines[li];
90865
- if (l === "\\:" || l === "\\:\\:" || l === "\\:\\:\\:") return void 0;
90866
- if (l.length === 0) outLines.push(" ");
90867
- else outLines.push(String(nlNum++).padStart(6, " ") + " " + l);
90868
- }
93016
+ const nlRes = this.evalSyncNl(rawLines, stageArgs);
93017
+ if (nlRes === void 0) return void 0;
93018
+ outLines = nlRes;
93019
+ } else if (isInlinePaste) {
93020
+ const pasteRes = this.evalSyncPaste(rawLines, stageArgs);
93021
+ if (pasteRes === void 0) return void 0;
93022
+ outLines = pasteRes;
93023
+ } else if (isInlineNumfmt) {
93024
+ const nmRes = this.evalSyncNumfmt(rawLines, stageArgs);
93025
+ if (nmRes === void 0) return void 0;
93026
+ outLines = nmRes;
90869
93027
  } else if (isInlineBase64) {
90870
93028
  if (stageArgs.length === 0) {
90871
93029
  const b64Wrapped = this.syncBase64Encode(prevBuf.subarray(0, prevLen));
@@ -90874,7 +93032,7 @@ ${prefix3} line ${offset + line}: \`${source2.split("\n")[line - 1] ?? ""}'
90874
93032
  const cleaned = inStr.replace(/[ \t\r\n]+/g, "");
90875
93033
  if (cleaned.length % 4 !== 0 || cleaned.length > 0 && !/^[A-Za-z0-9+/]+={0,2}$/.test(cleaned)) return void 0;
90876
93034
  const decoded = this.syncBase64DecodeBytes(cleaned);
90877
- if (decoded.includes(0) || decoded.byteLength > nextBuf.byteLength) return void 0;
93035
+ if (decoded.some((byte) => byte === 0 || byte >= 128) || decoded.byteLength > nextBuf.byteLength) return void 0;
90878
93036
  const nextTotalBytes2 = this.budget.bytes + decoded.byteLength;
90879
93037
  if (nextTotalBytes2 > this.budget.maxOutputBytesSmi && decoded.byteLength > this.budget.limits.maxOutputBytes - this.budget.bytes) this.budget.fail("maxOutputBytes");
90880
93038
  this.budget.bytes = nextTotalBytes2;
@@ -90889,7 +93047,7 @@ ${prefix3} line ${offset + line}: \`${source2.split("\n")[line - 1] ?? ""}'
90889
93047
  outLines = jqRes;
90890
93048
  }
90891
93049
  const preservesTerminator = firstName === "head" || firstName === "tail" || firstName === "rev" || firstName === "sed";
90892
- const terminated = !preservesTerminator || inStr.endsWith("\n") || firstName === "head" && outLines.length < rawLines.length;
93050
+ const terminated = sedTerminated || !preservesTerminator || inStr.endsWith("\n") || firstName === "head" && outLines.length < rawLines.length;
90893
93051
  const outStr2 = outLines.length > 0 ? outLines.join("\n") + (terminated ? "\n" : "") : "";
90894
93052
  const outByteLen = shellValueByteLength(outStr2);
90895
93053
  if (outByteLen > nextBuf.byteLength) return void 0;
@@ -91012,8 +93170,8 @@ ${prefix3} line ${offset + line}: \`${source2.split("\n")[line - 1] ?? ""}'
91012
93170
  if (cmd.kind !== "simple" || cmd.redirects.length > 0 && !hasSingleStdinRedir && !hasSingleHereStringRedir || cmd.words.length === 0) return void 0;
91013
93171
  let w0Plain = cmd.words[0].plain;
91014
93172
  if (!w0Plain || rawState.extensions?.builtins.has(w0Plain)) return void 0;
91015
- const isSingleFileTool = w0Plain === "cat" || w0Plain === "head" || w0Plain === "tail" || w0Plain === "jq" || w0Plain === "awk" || w0Plain === "grep" || w0Plain === "sed" || w0Plain === "cut" || w0Plain === "wc" || w0Plain === "sort" || w0Plain === "uniq" || w0Plain === "tr" || hasSingleHereStringRedir && (w0Plain === "base64" || w0Plain === "rev" || w0Plain === "tac" || w0Plain === "nl");
91016
- if (isSingleFileTool && !hasShellFunction(rawState, w0Plain) && (this.commands.has(w0Plain) || (w0Plain === "rev" || w0Plain === "tac") && Boolean(this.getExternalCommand(w0Plain)))) {
93173
+ const isSingleFileTool = w0Plain === "cat" || w0Plain === "head" || w0Plain === "tail" || w0Plain === "jq" || w0Plain === "awk" || w0Plain === "grep" || w0Plain === "sed" || w0Plain === "cut" || w0Plain === "wc" || w0Plain === "sort" || w0Plain === "uniq" || w0Plain === "tr" || hasSingleHereStringRedir && (w0Plain === "base64" || w0Plain === "rev" || w0Plain === "tac" || w0Plain === "nl" || w0Plain === "paste" || w0Plain === "numfmt");
93174
+ if (isSingleFileTool && !hasShellFunction(rawState, w0Plain) && (this.commands.has(w0Plain) || (w0Plain === "rev" || w0Plain === "tac" || w0Plain === "nl" || w0Plain === "paste") && Boolean(this.getExternalCommand(w0Plain)))) {
91017
93175
  const allArgs = [];
91018
93176
  let fOk = true;
91019
93177
  for (let i = 1; i < cmd.words.length; i++) {
@@ -91046,6 +93204,8 @@ ${prefix3} line ${offset + line}: \`${source2.split("\n")[line - 1] ?? ""}'
91046
93204
  const view = hasSingleHereStringRedir ? fastSharedTextEncoder.encode(hereStrVal) : this.tryReadMemoryFileViewSync(resolvePath(rawState.cwd, fileArg));
91047
93205
  if (view && view.byteLength <= 16384 && !view.includes(0) && (hasSingleHereStringRedir || view.every((byte) => byte < 128))) {
91048
93206
  const fileStr = hasSingleHereStringRedir ? hereStrVal : sharedSyncPipeDecoder.decode(view);
93207
+ if (fileStr.length > 0 && !fileStr.endsWith("\n") && (w0Plain === "head" || w0Plain === "tail" || w0Plain === "sed" || w0Plain === "cut" || w0Plain === "uniq")) return void 0;
93208
+ const renderLines = (lines3) => lines3.length === 0 ? "" : lines3.join("\n") + "\n";
91049
93209
  const rawLines = fileStr.endsWith("\n") ? fileStr.slice(0, -1).split("\n") : fileStr.length === 0 ? [] : fileStr.split("\n");
91050
93210
  let fileRes;
91051
93211
  let exitStatus = 0;
@@ -91054,81 +93214,99 @@ ${prefix3} line ${offset + line}: \`${source2.split("\n")[line - 1] ?? ""}'
91054
93214
  } else if ((w0Plain === "head" || w0Plain === "tail") && opArgs.length <= 2) {
91055
93215
  let count2 = opArgs.length === 0 ? 10 : void 0;
91056
93216
  let byteCount2;
91057
- if (opArgs.length === 1 && opArgs[0].startsWith("-n") && /^[0-9]{1,5}$/.test(opArgs[0].slice(2))) count2 = Number(opArgs[0].slice(2));
91058
- else if (opArgs.length === 1 && opArgs[0].startsWith("-c") && /^[0-9]{1,5}$/.test(opArgs[0].slice(2))) byteCount2 = Number(opArgs[0].slice(2));
91059
- else if (opArgs.length === 1 && /^-[0-9]{1,5}$/.test(opArgs[0])) count2 = Number(opArgs[0].slice(1));
91060
- else if (opArgs.length === 2 && opArgs[0] === "-n" && /^[0-9]{1,5}$/.test(opArgs[1])) count2 = Number(opArgs[1]);
93217
+ let countRaw = opArgs.length === 0 ? "10" : void 0;
93218
+ if (opArgs.length === 1 && (opArgs[0].startsWith("-n") || opArgs[0].startsWith("--lines="))) {
93219
+ const sub = opArgs[0].startsWith("--lines=") ? opArgs[0].slice(8) : opArgs[0].slice(2);
93220
+ if (/^[0-9]{1,5}$/.test(sub) || w0Plain === "tail" && /^\+[0-9]{1,5}$/.test(sub) || w0Plain === "head" && /^-[0-9]{1,5}$/.test(sub)) countRaw = sub;
93221
+ } else if (opArgs.length === 1 && (opArgs[0].startsWith("-c") || opArgs[0].startsWith("--bytes="))) {
93222
+ const sub = opArgs[0].startsWith("--bytes=") ? opArgs[0].slice(8) : opArgs[0].slice(2);
93223
+ if (/^[0-9]{1,5}$/.test(sub)) byteCount2 = Number(sub);
93224
+ } else if (opArgs.length === 1 && /^-[0-9]{1,5}$/.test(opArgs[0])) countRaw = opArgs[0].slice(1);
93225
+ else if (opArgs.length === 2 && opArgs[0] === "-n" && (/^[0-9]{1,5}$/.test(opArgs[1]) || w0Plain === "tail" && /^\+[0-9]{1,5}$/.test(opArgs[1]) || w0Plain === "head" && /^-[0-9]{1,5}$/.test(opArgs[1]))) countRaw = opArgs[1];
91061
93226
  else if (opArgs.length === 2 && opArgs[0] === "-c" && /^[0-9]{1,5}$/.test(opArgs[1])) byteCount2 = Number(opArgs[1]);
91062
- if (count2 !== void 0) {
91063
- const sliced = w0Plain === "head" ? rawLines.slice(0, count2) : count2 === 0 ? [] : rawLines.slice(-count2);
91064
- fileRes = sliced.join("\n");
93227
+ if (countRaw !== void 0) {
93228
+ count2 = Number(countRaw);
93229
+ let sliced;
93230
+ if (w0Plain === "tail" && countRaw.startsWith("+")) sliced = rawLines.slice(Math.max(0, count2 - 1));
93231
+ else if (w0Plain === "head" && countRaw.startsWith("-")) {
93232
+ const drop = Math.abs(count2);
93233
+ sliced = drop === 0 ? [...rawLines] : rawLines.slice(0, Math.max(0, rawLines.length - drop));
93234
+ } else {
93235
+ sliced = w0Plain === "head" ? rawLines.slice(0, count2) : count2 === 0 ? [] : rawLines.slice(-count2);
93236
+ }
93237
+ fileRes = renderLines(sliced);
91065
93238
  } else if (byteCount2 !== void 0) {
91066
93239
  const slicedBytes = w0Plain === "head" ? view.subarray(0, Math.min(view.byteLength, byteCount2)) : byteCount2 === 0 ? view.subarray(0, 0) : view.subarray(Math.max(0, view.byteLength - byteCount2), view.byteLength);
91067
93240
  fileRes = sharedSyncPipeDecoder.decode(slicedBytes);
91068
93241
  }
91069
93242
  } else if (w0Plain === "jq") {
91070
93243
  const jqRes = this.evalSyncJq(fileStr.trim(), opArgs);
91071
- if (jqRes !== void 0) fileRes = jqRes.join("\n");
93244
+ if (jqRes !== void 0) fileRes = renderLines(jqRes);
91072
93245
  } else if (w0Plain === "awk") {
91073
93246
  const awkRes = this.evalSyncAwk(rawLines, opArgs);
91074
- if (awkRes !== void 0) fileRes = awkRes.join("\n");
93247
+ if (awkRes !== void 0) fileRes = renderLines(awkRes);
91075
93248
  } else if (w0Plain === "grep") {
91076
93249
  const grepRes = this.evalSyncGrep(rawLines, opArgs, Boolean(rawState.errexit));
91077
93250
  if (grepRes !== void 0) {
91078
93251
  exitStatus = grepRes.status;
91079
- fileRes = grepRes.lines.join("\n");
93252
+ fileRes = renderLines(grepRes.lines);
91080
93253
  }
91081
93254
  } else if (w0Plain === "sed") {
91082
93255
  const sedRes = this.evalSyncSed(rawLines, opArgs);
91083
- if (sedRes !== void 0) fileRes = sedRes.join("\n");
93256
+ if (sedRes !== void 0) fileRes = renderLines(sedRes.lines);
91084
93257
  } else if (w0Plain === "cut") {
91085
93258
  const cutRes = this.evalSyncCut(rawLines, opArgs, byteLocale(rawState.variables));
91086
- if (cutRes !== void 0) fileRes = cutRes.join("\n");
91087
- } else if (w0Plain === "wc" && opArgs.length === 1 && (opArgs[0] === "-l" || opArgs[0] === "-c" || opArgs[0] === "-w")) {
93259
+ if (cutRes !== void 0) fileRes = renderLines(cutRes);
93260
+ } else if (w0Plain === "wc" && opArgs.length === 1 && this.normalizeSyncWcFlag(opArgs[0]) !== void 0) {
93261
+ const wcMode = this.normalizeSyncWcFlag(opArgs[0]);
91088
93262
  let count2 = 0;
91089
- if (opArgs[0] === "-l") {
93263
+ if (wcMode === "-l") {
91090
93264
  for (let k = 0; k < view.byteLength; k++) if (view[k] === 10) count2++;
91091
- } else if (opArgs[0] === "-c") {
93265
+ } else if (wcMode === "-c") {
91092
93266
  count2 = view.byteLength;
93267
+ } else if (wcMode === "-m") {
93268
+ count2 = byteLocale(rawState.variables) ? view.byteLength : Array.from(fileStr).length;
93269
+ } else if (wcMode === "-L") {
93270
+ count2 = this.wcMaxLineWidth(fileStr, byteLocale(rawState.variables));
91093
93271
  } else {
91094
- const trimmed = fileStr.trim();
91095
- count2 = trimmed.length === 0 ? 0 : trimmed.split(/\s+/).length;
91096
- }
91097
- fileRes = hasSingleStdinRedir || hasSingleHereStringRedir ? String(count2) : `${count2} ${fileArg}`;
91098
- } else if (w0Plain === "sort" && !byteLocale(rawState.variables) && (opArgs.length === 0 || opArgs.length === 1 && (opArgs[0] === "-r" || opArgs[0] === "-u" || opArgs[0] === "-n" || opArgs[0] === "-rn" || opArgs[0] === "-nr" || opArgs[0] === "-ru" || opArgs[0] === "-ur"))) {
91099
- fileRes = this.sortSyncLines(rawLines, opArgs[0]).join("\n");
91100
- } else if (w0Plain === "uniq" && (opArgs.length === 0 || opArgs.length === 1 && (opArgs[0] === "-d" || opArgs[0] === "-u" || opArgs[0] === "-c"))) {
91101
- const mode = opArgs[0];
91102
- const outLines = [];
91103
- let uIdx = 0;
91104
- while (uIdx < rawLines.length) {
91105
- let uEnd = uIdx + 1;
91106
- while (uEnd < rawLines.length && rawLines[uEnd] === rawLines[uIdx]) uEnd++;
91107
- const count2 = uEnd - uIdx;
91108
- if (mode === "-d" ? count2 > 1 : mode === "-u" ? count2 === 1 : true) {
91109
- outLines.push(mode === "-c" ? `${String(count2).padStart(7, " ")} ${rawLines[uIdx]}` : rawLines[uIdx]);
91110
- }
91111
- uIdx = uEnd;
93272
+ if (!byteLocale(rawState.variables) && view.some((byte) => byte > 127)) return void 0;
93273
+ count2 = fileStr.split(/[ \t\n\r\f\v]+/).filter(Boolean).length;
91112
93274
  }
91113
- fileRes = outLines.join("\n");
93275
+ fileRes = (hasSingleStdinRedir || hasSingleHereStringRedir ? String(count2) : `${count2} ${fileArg}`) + "\n";
93276
+ } else if (w0Plain === "sort" && !byteLocale(rawState.variables)) {
93277
+ const sortRes = this.evalSyncSort(rawLines, opArgs, false);
93278
+ if (sortRes !== void 0) fileRes = renderLines(sortRes);
93279
+ } else if (w0Plain === "uniq") {
93280
+ const uniqRes = this.evalSyncUniq(rawLines, opArgs);
93281
+ if (uniqRes !== void 0) fileRes = renderLines(uniqRes);
91114
93282
  } else if (w0Plain === "tr" && (hasSingleStdinRedir || hasSingleHereStringRedir)) {
91115
93283
  fileRes = this.evalSyncTr(fileStr, opArgs);
91116
93284
  } else if (hasSingleHereStringRedir && w0Plain === "base64" && (opArgs.length === 0 || opArgs.length === 1 && (opArgs[0] === "-d" || opArgs[0] === "--decode"))) {
91117
- if (opArgs.length === 0) fileRes = this.syncBase64Encode(view);
91118
- else fileRes = sharedSyncPipeDecoder.decode(this.syncBase64DecodeBytes(fileStr));
93285
+ if (opArgs.length === 0) fileRes = this.syncBase64Encode(view) + "\n";
93286
+ else {
93287
+ const decoded = this.syncBase64DecodeBytes(fileStr);
93288
+ if (decoded.some((byte) => byte === 0 || byte >= 128)) return void 0;
93289
+ fileRes = sharedSyncPipeDecoder.decode(decoded);
93290
+ }
91119
93291
  } else if (hasSingleHereStringRedir && w0Plain === "rev" && opArgs.length === 0) {
91120
- fileRes = rawLines.map((l) => Array.from(l).reverse().join("")).join("\n");
93292
+ fileRes = renderLines(rawLines.map((l) => Array.from(l).reverse().join("")));
91121
93293
  } else if (hasSingleHereStringRedir && w0Plain === "tac" && opArgs.length === 0) {
91122
- fileRes = [...rawLines].reverse().join("\n");
91123
- } else if (hasSingleHereStringRedir && w0Plain === "nl" && opArgs.length === 0) {
91124
- let lineNo = 0;
91125
- fileRes = rawLines.map((l) => l.length === 0 ? " " : `${String(++lineNo).padStart(6, " ")} ${l}`).join("\n");
93294
+ fileRes = renderLines([...rawLines].reverse());
93295
+ } else if (hasSingleHereStringRedir && w0Plain === "nl") {
93296
+ const nlRes = this.evalSyncNl(rawLines, opArgs);
93297
+ if (nlRes !== void 0) fileRes = renderLines(nlRes);
93298
+ } else if (hasSingleHereStringRedir && w0Plain === "paste") {
93299
+ const pasteRes = this.evalSyncPaste(rawLines, opArgs);
93300
+ if (pasteRes !== void 0) fileRes = renderLines(pasteRes);
93301
+ } else if (hasSingleHereStringRedir && w0Plain === "numfmt") {
93302
+ const nmRes = this.evalSyncNumfmt(rawLines, opArgs);
93303
+ if (nmRes !== void 0) fileRes = renderLines(nmRes);
91126
93304
  }
91127
93305
  if (fileRes !== void 0) {
93306
+ const outBytes = shellValueByteLength(fileRes);
91128
93307
  let end = fileRes.length;
91129
93308
  while (end > 0 && fileRes.charCodeAt(end - 1) === 10) end--;
91130
93309
  if (end < fileRes.length) fileRes = fileRes.slice(0, end);
91131
- const outBytes = (fileRes.length * 3 > 127 ? shellValueByteLength(fileRes) : fileRes.length) + 1;
91132
93310
  const nextTotalBytes = this.budget.bytes + outBytes;
91133
93311
  if (nextTotalBytes > this.budget.maxOutputBytesSmi && outBytes > this.budget.limits.maxOutputBytes - this.budget.bytes) this.budget.fail("maxOutputBytes");
91134
93312
  this.budget.bytes = nextTotalBytes;
@@ -91208,38 +93386,15 @@ ${prefix3} line ${offset + line}: \`${source2.split("\n")[line - 1] ?? ""}'
91208
93386
  for (let i = 0; i < cmd.words.length; i++) {
91209
93387
  if (!this.isPureArgWord(cmd.words[i], rawState)) return void 0;
91210
93388
  }
91211
- if (w0Plain === "dirname" && cmd.words.length === 2) {
91212
- const wVal = this.fastValueWord(cmd.words[1], state, io, true, false, false, true, void 0, part.line);
91213
- if (typeof wVal !== "string" || wVal.startsWith("-") || wVal.includes("\0")) return void 0;
91214
- const parent = dirname(wVal);
91215
- let pEnd = parent.length;
91216
- while (pEnd > 1 && parent[pEnd - 1] === "/") pEnd--;
91217
- let res = parent.slice(0, pEnd);
91218
- const byteLength2 = shellValueByteLength(res) + 1;
91219
- while (res.endsWith("\n")) res = res.slice(0, -1);
91220
- const nextBytes2 = this.budget.bytes + byteLength2;
91221
- if (nextBytes2 > this.budget.maxOutputBytesSmi && byteLength2 > this.budget.limits.maxOutputBytes - this.budget.bytes) this.budget.fail("maxOutputBytes");
91222
- this.budget.bytes = nextBytes2;
91223
- this.budget.tick();
91224
- if (fnPositional !== void 0) this.budget.tick();
91225
- rawState.substitutionStatus = 0;
91226
- rawState.status = 0;
91227
- return res;
91228
- }
91229
- if (w0Plain === "basename" && (cmd.words.length === 2 || cmd.words.length === 3 || cmd.words.length === 4 && cmd.words[1]?.plain === "-s")) {
91230
- const isFlagS = cmd.words.length === 4 && cmd.words[1]?.plain === "-s";
91231
- const pathWord = isFlagS ? cmd.words[3] : cmd.words[1];
91232
- const suffixWord = isFlagS ? cmd.words[2] : cmd.words.length === 3 ? cmd.words[2] : void 0;
91233
- const wVal1 = this.fastValueWord(pathWord, state, io, true, false, false, true, void 0, part.line);
91234
- if (typeof wVal1 !== "string" || wVal1.startsWith("-") || wVal1.includes("\0")) return void 0;
91235
- let wVal2;
91236
- if (suffixWord !== void 0) {
91237
- const v2 = this.fastValueWord(suffixWord, state, io, true, false, false, true, void 0, part.line);
91238
- if (typeof v2 !== "string" || v2.includes("\0")) return void 0;
91239
- wVal2 = v2;
91240
- }
91241
- let res = /^\/+$/u.test(wVal1) ? "/" : basename(wVal1);
91242
- if (wVal2 && res !== wVal2 && res.endsWith(wVal2)) res = res.slice(0, -wVal2.length);
93389
+ if (w0Plain === "dirname" || w0Plain === "basename") {
93390
+ const dbArgs = [];
93391
+ for (let i = 1; i < cmd.words.length; i++) {
93392
+ const v = this.fastValueWord(cmd.words[i], state, io, true, false, false, true, void 0, part.line);
93393
+ if (typeof v !== "string") return void 0;
93394
+ dbArgs.push(v);
93395
+ }
93396
+ let res = w0Plain === "dirname" ? this.evalSyncDirname(dbArgs) : this.evalSyncBasename(dbArgs);
93397
+ if (res === void 0) return void 0;
91243
93398
  const byteLength2 = shellValueByteLength(res) + 1;
91244
93399
  while (res.endsWith("\n")) res = res.slice(0, -1);
91245
93400
  const nextBytes2 = this.budget.bytes + byteLength2;
@@ -94091,7 +96246,7 @@ import * as safe_bash_command_xz_star from "../safe-bash-command-xz/index.js";
94091
96246
  __reExport(core_browser_exports, core_exports);
94092
96247
  import { CommandArgumentIdentityError, createCommandArguments as createCommandArguments5, getCommandArguments as getCommandArguments16, commandRuntimeIdentity as commandRuntimeIdentity2, CommandRegistry as CommandRegistry3, validateExitCode as validateExitCode2 } from "../safe-bash-contracts/command.js";
94093
96248
  import { evaluateCommandSupport, assertCommandRequirements as assertCommandRequirements16 } from "../safe-bash-contracts/command-requirements.js";
94094
- import { isErrnoCode, isFsError as isFsError11, toFsError, FsError as FsError60 } from "../safe-bash-contracts/errors.js";
96249
+ import { isErrnoCode, isFsError as isFsError11, toFsError, FsError as FsError61 } from "../safe-bash-contracts/errors.js";
94095
96250
  import { ACCESS_MODES as ACCESS_MODES3 } from "../safe-bash-contracts/filesystem.js";
94096
96251
  import { collectBytes as collectBytes14, readBytes as readBytes29, toByteSource as toByteSource7, outputFailure as outputFailure3, createBytePipe as createBytePipe2, writeText as writeText4, writeBytes as writeBytes30, pipeBytes as pipeBytes2, collectText } from "../safe-bash-contracts/io.js";
94097
96252
  import { createOutputOperation as createOutputOperation10 } from "../safe-bash-contracts/output.js";
@@ -94255,7 +96410,7 @@ export {
94255
96410
  export_EreSyntaxError as EreSyntaxError,
94256
96411
  export_EreUnsupportedError as EreUnsupportedError,
94257
96412
  export_EreUsageUnknownError as EreUsageUnknownError,
94258
- FsError60 as FsError,
96413
+ FsError61 as FsError,
94259
96414
  MdqError,
94260
96415
  MemoryFileSystem,
94261
96416
  MountFileSystem,