poe-code 14.0.24 → 14.0.25

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 (44) hide show
  1. package/dist/index.js +1 -1
  2. package/dist/index.js.map +1 -1
  3. package/dist/metafile.json +1 -1
  4. package/package.json +1 -1
  5. package/packages/safe-bash/dist/browser.js +776 -447
  6. package/packages/safe-bash/dist/browser.js.map +4 -4
  7. package/packages/safe-bash/dist/commands/metadata/stat.d.ts.map +1 -1
  8. package/packages/safe-bash/dist/commands/metadata/stat.js +22 -5
  9. package/packages/safe-bash/dist/commands/metadata/stat.js.map +1 -1
  10. package/packages/safe-bash/dist/commands/regex-execution/bounded-provider.d.ts +15 -0
  11. package/packages/safe-bash/dist/commands/regex-execution/bounded-provider.d.ts.map +1 -0
  12. package/packages/safe-bash/dist/commands/regex-execution/bounded-provider.js +319 -0
  13. package/packages/safe-bash/dist/commands/regex-execution/bounded-provider.js.map +1 -0
  14. package/packages/safe-bash/dist/commands/regex-execution/public.d.ts +1 -0
  15. package/packages/safe-bash/dist/commands/regex-execution/public.d.ts.map +1 -1
  16. package/packages/safe-bash/dist/commands/regex-execution/public.js +1 -0
  17. package/packages/safe-bash/dist/commands/regex-execution/public.js.map +1 -1
  18. package/packages/safe-bash/dist/commands/search/grep.d.ts +1 -1
  19. package/packages/safe-bash/dist/commands/search/grep.d.ts.map +1 -1
  20. package/packages/safe-bash/dist/commands/search/grep.js +45 -12
  21. package/packages/safe-bash/dist/commands/search/grep.js.map +1 -1
  22. package/packages/safe-bash/dist/commands/text-programs/awk-runtime.d.ts +1 -0
  23. package/packages/safe-bash/dist/commands/text-programs/awk-runtime.d.ts.map +1 -1
  24. package/packages/safe-bash/dist/commands/text-programs/awk-runtime.js +103 -34
  25. package/packages/safe-bash/dist/commands/text-programs/awk-runtime.js.map +1 -1
  26. package/packages/safe-bash/dist/commands/text-programs/sed.d.ts.map +1 -1
  27. package/packages/safe-bash/dist/commands/text-programs/sed.js +11 -2
  28. package/packages/safe-bash/dist/commands/text-programs/sed.js.map +1 -1
  29. package/packages/safe-bash/dist/commands/text-programs/shared.d.ts +1 -0
  30. package/packages/safe-bash/dist/commands/text-programs/shared.d.ts.map +1 -1
  31. package/packages/safe-bash/dist/commands/text-programs/shared.js +6 -2
  32. package/packages/safe-bash/dist/commands/text-programs/shared.js.map +1 -1
  33. package/packages/safe-bash/dist/shell/runtime.d.ts +1 -0
  34. package/packages/safe-bash/dist/shell/runtime.d.ts.map +1 -1
  35. package/packages/safe-bash/dist/shell/runtime.js +40 -8
  36. package/packages/safe-bash/dist/shell/runtime.js.map +1 -1
  37. package/packages/safe-bash/dist/shell/shell.js +2 -2
  38. package/packages/safe-bash/dist/shell/shell.js.map +1 -1
  39. package/packages/safe-bash/dist/shell/types.d.ts +3 -0
  40. package/packages/safe-bash/dist/shell/types.d.ts.map +1 -1
  41. package/packages/safe-bash/dist/shell/types.js.map +1 -1
  42. package/packages/safe-bash/dist/shell/worker-limits.d.ts.map +1 -1
  43. package/packages/safe-bash/dist/shell/worker-limits.js +1 -0
  44. package/packages/safe-bash/dist/shell/worker-limits.js.map +1 -1
@@ -41,7 +41,7 @@ var require_base64_js = __commonJS({
41
41
  "node_modules/base64-js/index.js"(exports) {
42
42
  "use strict";
43
43
  init_platform();
44
- exports.byteLength = byteLength;
44
+ exports.byteLength = byteLength2;
45
45
  exports.toByteArray = toByteArray;
46
46
  exports.fromByteArray = fromByteArray;
47
47
  var lookup = [];
@@ -66,7 +66,7 @@ var require_base64_js = __commonJS({
66
66
  var placeHoldersLen = validLen === len2 ? 0 : 4 - validLen % 4;
67
67
  return [validLen, placeHoldersLen];
68
68
  }
69
- function byteLength(b64) {
69
+ function byteLength2(b64) {
70
70
  var lens = getLens(b64);
71
71
  var validLen = lens[0];
72
72
  var placeHoldersLen = lens[1];
@@ -366,7 +366,7 @@ var require_buffer = __commonJS({
366
366
  if (!Buffer3.isEncoding(encoding)) {
367
367
  throw new TypeError("Unknown encoding: " + encoding);
368
368
  }
369
- const length = byteLength(string, encoding) | 0;
369
+ const length = byteLength2(string, encoding) | 0;
370
370
  let buf = createBuffer(length);
371
371
  const actual = buf.write(string, encoding);
372
372
  if (actual !== length) {
@@ -374,11 +374,11 @@ var require_buffer = __commonJS({
374
374
  }
375
375
  return buf;
376
376
  }
377
- function fromArrayLike(array) {
378
- const length = array.length < 0 ? 0 : checked(array.length) | 0;
377
+ function fromArrayLike(array2) {
378
+ const length = array2.length < 0 ? 0 : checked(array2.length) | 0;
379
379
  const buf = createBuffer(length);
380
380
  for (let i = 0; i < length; i += 1) {
381
- buf[i] = array[i] & 255;
381
+ buf[i] = array2[i] & 255;
382
382
  }
383
383
  return buf;
384
384
  }
@@ -389,20 +389,20 @@ var require_buffer = __commonJS({
389
389
  }
390
390
  return fromArrayLike(arrayView);
391
391
  }
392
- function fromArrayBuffer(array, byteOffset, length) {
393
- if (byteOffset < 0 || array.byteLength < byteOffset) {
392
+ function fromArrayBuffer(array2, byteOffset2, length) {
393
+ if (byteOffset2 < 0 || array2.byteLength < byteOffset2) {
394
394
  throw new RangeError('"offset" is outside of buffer bounds');
395
395
  }
396
- if (array.byteLength < byteOffset + (length || 0)) {
396
+ if (array2.byteLength < byteOffset2 + (length || 0)) {
397
397
  throw new RangeError('"length" is outside of buffer bounds');
398
398
  }
399
399
  let buf;
400
- if (byteOffset === void 0 && length === void 0) {
401
- buf = new Uint8Array(array);
400
+ if (byteOffset2 === void 0 && length === void 0) {
401
+ buf = new Uint8Array(array2);
402
402
  } else if (length === void 0) {
403
- buf = new Uint8Array(array, byteOffset);
403
+ buf = new Uint8Array(array2, byteOffset2);
404
404
  } else {
405
- buf = new Uint8Array(array, byteOffset, length);
405
+ buf = new Uint8Array(array2, byteOffset2, length);
406
406
  }
407
407
  Object.setPrototypeOf(buf, Buffer3.prototype);
408
408
  return buf;
@@ -520,7 +520,7 @@ var require_buffer = __commonJS({
520
520
  }
521
521
  return buffer;
522
522
  };
523
- function byteLength(string, encoding) {
523
+ function byteLength2(string, encoding) {
524
524
  if (Buffer3.isBuffer(string)) {
525
525
  return string.length;
526
526
  }
@@ -563,7 +563,7 @@ var require_buffer = __commonJS({
563
563
  }
564
564
  }
565
565
  }
566
- Buffer3.byteLength = byteLength;
566
+ Buffer3.byteLength = byteLength2;
567
567
  function slowToString(encoding, start, end) {
568
568
  let loweredCase = false;
569
569
  if (start === void 0 || start < 0) {
@@ -726,26 +726,26 @@ var require_buffer = __commonJS({
726
726
  if (y < x) return 1;
727
727
  return 0;
728
728
  };
729
- function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) {
729
+ function bidirectionalIndexOf(buffer, val, byteOffset2, encoding, dir) {
730
730
  if (buffer.length === 0) return -1;
731
- if (typeof byteOffset === "string") {
732
- encoding = byteOffset;
733
- byteOffset = 0;
734
- } else if (byteOffset > 2147483647) {
735
- byteOffset = 2147483647;
736
- } else if (byteOffset < -2147483648) {
737
- byteOffset = -2147483648;
738
- }
739
- byteOffset = +byteOffset;
740
- if (numberIsNaN(byteOffset)) {
741
- byteOffset = dir ? 0 : buffer.length - 1;
742
- }
743
- if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
744
- if (byteOffset >= buffer.length) {
731
+ if (typeof byteOffset2 === "string") {
732
+ encoding = byteOffset2;
733
+ byteOffset2 = 0;
734
+ } else if (byteOffset2 > 2147483647) {
735
+ byteOffset2 = 2147483647;
736
+ } else if (byteOffset2 < -2147483648) {
737
+ byteOffset2 = -2147483648;
738
+ }
739
+ byteOffset2 = +byteOffset2;
740
+ if (numberIsNaN(byteOffset2)) {
741
+ byteOffset2 = dir ? 0 : buffer.length - 1;
742
+ }
743
+ if (byteOffset2 < 0) byteOffset2 = buffer.length + byteOffset2;
744
+ if (byteOffset2 >= buffer.length) {
745
745
  if (dir) return -1;
746
- else byteOffset = buffer.length - 1;
747
- } else if (byteOffset < 0) {
748
- if (dir) byteOffset = 0;
746
+ else byteOffset2 = buffer.length - 1;
747
+ } else if (byteOffset2 < 0) {
748
+ if (dir) byteOffset2 = 0;
749
749
  else return -1;
750
750
  }
751
751
  if (typeof val === "string") {
@@ -755,21 +755,21 @@ var require_buffer = __commonJS({
755
755
  if (val.length === 0) {
756
756
  return -1;
757
757
  }
758
- return arrayIndexOf(buffer, val, byteOffset, encoding, dir);
758
+ return arrayIndexOf(buffer, val, byteOffset2, encoding, dir);
759
759
  } else if (typeof val === "number") {
760
760
  val = val & 255;
761
761
  if (typeof Uint8Array.prototype.indexOf === "function") {
762
762
  if (dir) {
763
- return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset);
763
+ return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset2);
764
764
  } else {
765
- return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset);
765
+ return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset2);
766
766
  }
767
767
  }
768
- return arrayIndexOf(buffer, [val], byteOffset, encoding, dir);
768
+ return arrayIndexOf(buffer, [val], byteOffset2, encoding, dir);
769
769
  }
770
770
  throw new TypeError("val must be string, number or Buffer");
771
771
  }
772
- function arrayIndexOf(arr, val, byteOffset, encoding, dir) {
772
+ function arrayIndexOf(arr, val, byteOffset2, encoding, dir) {
773
773
  let indexSize = 1;
774
774
  let arrLength = arr.length;
775
775
  let valLength = val.length;
@@ -782,7 +782,7 @@ var require_buffer = __commonJS({
782
782
  indexSize = 2;
783
783
  arrLength /= 2;
784
784
  valLength /= 2;
785
- byteOffset /= 2;
785
+ byteOffset2 /= 2;
786
786
  }
787
787
  }
788
788
  function read(buf, i2) {
@@ -795,7 +795,7 @@ var require_buffer = __commonJS({
795
795
  let i;
796
796
  if (dir) {
797
797
  let foundIndex = -1;
798
- for (i = byteOffset; i < arrLength; i++) {
798
+ for (i = byteOffset2; i < arrLength; i++) {
799
799
  if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
800
800
  if (foundIndex === -1) foundIndex = i;
801
801
  if (i - foundIndex + 1 === valLength) return foundIndex * indexSize;
@@ -805,8 +805,8 @@ var require_buffer = __commonJS({
805
805
  }
806
806
  }
807
807
  } else {
808
- if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
809
- for (i = byteOffset; i >= 0; i--) {
808
+ if (byteOffset2 + valLength > arrLength) byteOffset2 = arrLength - valLength;
809
+ for (i = byteOffset2; i >= 0; i--) {
810
810
  let found = true;
811
811
  for (let j = 0; j < valLength; j++) {
812
812
  if (read(arr, i + j) !== read(val, j)) {
@@ -819,14 +819,14 @@ var require_buffer = __commonJS({
819
819
  }
820
820
  return -1;
821
821
  }
822
- Buffer3.prototype.includes = function includes(val, byteOffset, encoding) {
823
- return this.indexOf(val, byteOffset, encoding) !== -1;
822
+ Buffer3.prototype.includes = function includes(val, byteOffset2, encoding) {
823
+ return this.indexOf(val, byteOffset2, encoding) !== -1;
824
824
  };
825
- Buffer3.prototype.indexOf = function indexOf(val, byteOffset, encoding) {
826
- return bidirectionalIndexOf(this, val, byteOffset, encoding, true);
825
+ Buffer3.prototype.indexOf = function indexOf(val, byteOffset2, encoding) {
826
+ return bidirectionalIndexOf(this, val, byteOffset2, encoding, true);
827
827
  };
828
- Buffer3.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) {
829
- return bidirectionalIndexOf(this, val, byteOffset, encoding, false);
828
+ Buffer3.prototype.lastIndexOf = function lastIndexOf(val, byteOffset2, encoding) {
829
+ return bidirectionalIndexOf(this, val, byteOffset2, encoding, false);
830
830
  };
831
831
  function hexWrite(buf, string, offset, length) {
832
832
  offset = Number(offset) || 0;
@@ -1066,28 +1066,28 @@ var require_buffer = __commonJS({
1066
1066
  if (offset % 1 !== 0 || offset < 0) throw new RangeError("offset is not uint");
1067
1067
  if (offset + ext > length) throw new RangeError("Trying to access beyond buffer length");
1068
1068
  }
1069
- Buffer3.prototype.readUintLE = Buffer3.prototype.readUIntLE = function readUIntLE(offset, byteLength2, noAssert) {
1069
+ Buffer3.prototype.readUintLE = Buffer3.prototype.readUIntLE = function readUIntLE(offset, byteLength3, noAssert) {
1070
1070
  offset = offset >>> 0;
1071
- byteLength2 = byteLength2 >>> 0;
1072
- if (!noAssert) checkOffset(offset, byteLength2, this.length);
1071
+ byteLength3 = byteLength3 >>> 0;
1072
+ if (!noAssert) checkOffset(offset, byteLength3, this.length);
1073
1073
  let val = this[offset];
1074
1074
  let mul = 1;
1075
1075
  let i = 0;
1076
- while (++i < byteLength2 && (mul *= 256)) {
1076
+ while (++i < byteLength3 && (mul *= 256)) {
1077
1077
  val += this[offset + i] * mul;
1078
1078
  }
1079
1079
  return val;
1080
1080
  };
1081
- Buffer3.prototype.readUintBE = Buffer3.prototype.readUIntBE = function readUIntBE(offset, byteLength2, noAssert) {
1081
+ Buffer3.prototype.readUintBE = Buffer3.prototype.readUIntBE = function readUIntBE(offset, byteLength3, noAssert) {
1082
1082
  offset = offset >>> 0;
1083
- byteLength2 = byteLength2 >>> 0;
1083
+ byteLength3 = byteLength3 >>> 0;
1084
1084
  if (!noAssert) {
1085
- checkOffset(offset, byteLength2, this.length);
1085
+ checkOffset(offset, byteLength3, this.length);
1086
1086
  }
1087
- let val = this[offset + --byteLength2];
1087
+ let val = this[offset + --byteLength3];
1088
1088
  let mul = 1;
1089
- while (byteLength2 > 0 && (mul *= 256)) {
1090
- val += this[offset + --byteLength2] * mul;
1089
+ while (byteLength3 > 0 && (mul *= 256)) {
1090
+ val += this[offset + --byteLength3] * mul;
1091
1091
  }
1092
1092
  return val;
1093
1093
  };
@@ -1140,32 +1140,32 @@ var require_buffer = __commonJS({
1140
1140
  const lo = this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last;
1141
1141
  return (BigInt(hi) << BigInt(32)) + BigInt(lo);
1142
1142
  });
1143
- Buffer3.prototype.readIntLE = function readIntLE(offset, byteLength2, noAssert) {
1143
+ Buffer3.prototype.readIntLE = function readIntLE(offset, byteLength3, noAssert) {
1144
1144
  offset = offset >>> 0;
1145
- byteLength2 = byteLength2 >>> 0;
1146
- if (!noAssert) checkOffset(offset, byteLength2, this.length);
1145
+ byteLength3 = byteLength3 >>> 0;
1146
+ if (!noAssert) checkOffset(offset, byteLength3, this.length);
1147
1147
  let val = this[offset];
1148
1148
  let mul = 1;
1149
1149
  let i = 0;
1150
- while (++i < byteLength2 && (mul *= 256)) {
1150
+ while (++i < byteLength3 && (mul *= 256)) {
1151
1151
  val += this[offset + i] * mul;
1152
1152
  }
1153
1153
  mul *= 128;
1154
- if (val >= mul) val -= Math.pow(2, 8 * byteLength2);
1154
+ if (val >= mul) val -= Math.pow(2, 8 * byteLength3);
1155
1155
  return val;
1156
1156
  };
1157
- Buffer3.prototype.readIntBE = function readIntBE(offset, byteLength2, noAssert) {
1157
+ Buffer3.prototype.readIntBE = function readIntBE(offset, byteLength3, noAssert) {
1158
1158
  offset = offset >>> 0;
1159
- byteLength2 = byteLength2 >>> 0;
1160
- if (!noAssert) checkOffset(offset, byteLength2, this.length);
1161
- let i = byteLength2;
1159
+ byteLength3 = byteLength3 >>> 0;
1160
+ if (!noAssert) checkOffset(offset, byteLength3, this.length);
1161
+ let i = byteLength3;
1162
1162
  let mul = 1;
1163
1163
  let val = this[offset + --i];
1164
1164
  while (i > 0 && (mul *= 256)) {
1165
1165
  val += this[offset + --i] * mul;
1166
1166
  }
1167
1167
  mul *= 128;
1168
- if (val >= mul) val -= Math.pow(2, 8 * byteLength2);
1168
+ if (val >= mul) val -= Math.pow(2, 8 * byteLength3);
1169
1169
  return val;
1170
1170
  };
1171
1171
  Buffer3.prototype.readInt8 = function readInt8(offset, noAssert) {
@@ -1244,37 +1244,37 @@ var require_buffer = __commonJS({
1244
1244
  if (value2 > max || value2 < min) throw new RangeError('"value" argument is out of bounds');
1245
1245
  if (offset + ext > buf.length) throw new RangeError("Index out of range");
1246
1246
  }
1247
- Buffer3.prototype.writeUintLE = Buffer3.prototype.writeUIntLE = function writeUIntLE(value2, offset, byteLength2, noAssert) {
1247
+ Buffer3.prototype.writeUintLE = Buffer3.prototype.writeUIntLE = function writeUIntLE(value2, offset, byteLength3, noAssert) {
1248
1248
  value2 = +value2;
1249
1249
  offset = offset >>> 0;
1250
- byteLength2 = byteLength2 >>> 0;
1250
+ byteLength3 = byteLength3 >>> 0;
1251
1251
  if (!noAssert) {
1252
- const maxBytes = Math.pow(2, 8 * byteLength2) - 1;
1253
- checkInt(this, value2, offset, byteLength2, maxBytes, 0);
1252
+ const maxBytes = Math.pow(2, 8 * byteLength3) - 1;
1253
+ checkInt(this, value2, offset, byteLength3, maxBytes, 0);
1254
1254
  }
1255
1255
  let mul = 1;
1256
1256
  let i = 0;
1257
1257
  this[offset] = value2 & 255;
1258
- while (++i < byteLength2 && (mul *= 256)) {
1258
+ while (++i < byteLength3 && (mul *= 256)) {
1259
1259
  this[offset + i] = value2 / mul & 255;
1260
1260
  }
1261
- return offset + byteLength2;
1261
+ return offset + byteLength3;
1262
1262
  };
1263
- Buffer3.prototype.writeUintBE = Buffer3.prototype.writeUIntBE = function writeUIntBE(value2, offset, byteLength2, noAssert) {
1263
+ Buffer3.prototype.writeUintBE = Buffer3.prototype.writeUIntBE = function writeUIntBE(value2, offset, byteLength3, noAssert) {
1264
1264
  value2 = +value2;
1265
1265
  offset = offset >>> 0;
1266
- byteLength2 = byteLength2 >>> 0;
1266
+ byteLength3 = byteLength3 >>> 0;
1267
1267
  if (!noAssert) {
1268
- const maxBytes = Math.pow(2, 8 * byteLength2) - 1;
1269
- checkInt(this, value2, offset, byteLength2, maxBytes, 0);
1268
+ const maxBytes = Math.pow(2, 8 * byteLength3) - 1;
1269
+ checkInt(this, value2, offset, byteLength3, maxBytes, 0);
1270
1270
  }
1271
- let i = byteLength2 - 1;
1271
+ let i = byteLength3 - 1;
1272
1272
  let mul = 1;
1273
1273
  this[offset + i] = value2 & 255;
1274
1274
  while (--i >= 0 && (mul *= 256)) {
1275
1275
  this[offset + i] = value2 / mul & 255;
1276
1276
  }
1277
- return offset + byteLength2;
1277
+ return offset + byteLength3;
1278
1278
  };
1279
1279
  Buffer3.prototype.writeUint8 = Buffer3.prototype.writeUInt8 = function writeUInt8(value2, offset, noAssert) {
1280
1280
  value2 = +value2;
@@ -1365,33 +1365,33 @@ var require_buffer = __commonJS({
1365
1365
  Buffer3.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE(value2, offset = 0) {
1366
1366
  return wrtBigUInt64BE(this, value2, offset, BigInt(0), BigInt("0xffffffffffffffff"));
1367
1367
  });
1368
- Buffer3.prototype.writeIntLE = function writeIntLE(value2, offset, byteLength2, noAssert) {
1368
+ Buffer3.prototype.writeIntLE = function writeIntLE(value2, offset, byteLength3, noAssert) {
1369
1369
  value2 = +value2;
1370
1370
  offset = offset >>> 0;
1371
1371
  if (!noAssert) {
1372
- const limit = Math.pow(2, 8 * byteLength2 - 1);
1373
- checkInt(this, value2, offset, byteLength2, limit - 1, -limit);
1372
+ const limit = Math.pow(2, 8 * byteLength3 - 1);
1373
+ checkInt(this, value2, offset, byteLength3, limit - 1, -limit);
1374
1374
  }
1375
1375
  let i = 0;
1376
1376
  let mul = 1;
1377
1377
  let sub = 0;
1378
1378
  this[offset] = value2 & 255;
1379
- while (++i < byteLength2 && (mul *= 256)) {
1379
+ while (++i < byteLength3 && (mul *= 256)) {
1380
1380
  if (value2 < 0 && sub === 0 && this[offset + i - 1] !== 0) {
1381
1381
  sub = 1;
1382
1382
  }
1383
1383
  this[offset + i] = (value2 / mul >> 0) - sub & 255;
1384
1384
  }
1385
- return offset + byteLength2;
1385
+ return offset + byteLength3;
1386
1386
  };
1387
- Buffer3.prototype.writeIntBE = function writeIntBE(value2, offset, byteLength2, noAssert) {
1387
+ Buffer3.prototype.writeIntBE = function writeIntBE(value2, offset, byteLength3, noAssert) {
1388
1388
  value2 = +value2;
1389
1389
  offset = offset >>> 0;
1390
1390
  if (!noAssert) {
1391
- const limit = Math.pow(2, 8 * byteLength2 - 1);
1392
- checkInt(this, value2, offset, byteLength2, limit - 1, -limit);
1391
+ const limit = Math.pow(2, 8 * byteLength3 - 1);
1392
+ checkInt(this, value2, offset, byteLength3, limit - 1, -limit);
1393
1393
  }
1394
- let i = byteLength2 - 1;
1394
+ let i = byteLength3 - 1;
1395
1395
  let mul = 1;
1396
1396
  let sub = 0;
1397
1397
  this[offset + i] = value2 & 255;
@@ -1401,7 +1401,7 @@ var require_buffer = __commonJS({
1401
1401
  }
1402
1402
  this[offset + i] = (value2 / mul >> 0) - sub & 255;
1403
1403
  }
1404
- return offset + byteLength2;
1404
+ return offset + byteLength3;
1405
1405
  };
1406
1406
  Buffer3.prototype.writeInt8 = function writeInt8(value2, offset, noAssert) {
1407
1407
  value2 = +value2;
@@ -1646,28 +1646,28 @@ var require_buffer = __commonJS({
1646
1646
  }
1647
1647
  return `${val.slice(0, i)}${res}`;
1648
1648
  }
1649
- function checkBounds(buf, offset, byteLength2) {
1649
+ function checkBounds(buf, offset, byteLength3) {
1650
1650
  validateNumber(offset, "offset");
1651
- if (buf[offset] === void 0 || buf[offset + byteLength2] === void 0) {
1652
- boundsError(offset, buf.length - (byteLength2 + 1));
1651
+ if (buf[offset] === void 0 || buf[offset + byteLength3] === void 0) {
1652
+ boundsError(offset, buf.length - (byteLength3 + 1));
1653
1653
  }
1654
1654
  }
1655
- function checkIntBI(value2, min, max, buf, offset, byteLength2) {
1655
+ function checkIntBI(value2, min, max, buf, offset, byteLength3) {
1656
1656
  if (value2 > max || value2 < min) {
1657
1657
  const n = typeof min === "bigint" ? "n" : "";
1658
1658
  let range;
1659
- if (byteLength2 > 3) {
1659
+ if (byteLength3 > 3) {
1660
1660
  if (min === 0 || min === BigInt(0)) {
1661
- range = `>= 0${n} and < 2${n} ** ${(byteLength2 + 1) * 8}${n}`;
1661
+ range = `>= 0${n} and < 2${n} ** ${(byteLength3 + 1) * 8}${n}`;
1662
1662
  } else {
1663
- range = `>= -(2${n} ** ${(byteLength2 + 1) * 8 - 1}${n}) and < 2 ** ${(byteLength2 + 1) * 8 - 1}${n}`;
1663
+ range = `>= -(2${n} ** ${(byteLength3 + 1) * 8 - 1}${n}) and < 2 ** ${(byteLength3 + 1) * 8 - 1}${n}`;
1664
1664
  }
1665
1665
  } else {
1666
1666
  range = `>= ${min}${n} and <= ${max}${n}`;
1667
1667
  }
1668
1668
  throw new errors.ERR_OUT_OF_RANGE("value", range, value2);
1669
1669
  }
1670
- checkBounds(buf, offset, byteLength2);
1670
+ checkBounds(buf, offset, byteLength3);
1671
1671
  }
1672
1672
  function validateNumber(value2, name2) {
1673
1673
  if (typeof value2 !== "number") {
@@ -2179,18 +2179,18 @@ var CommandRegistry = class {
2179
2179
  constructor(commands = []) {
2180
2180
  for (const command2 of commands) this.register(command2);
2181
2181
  }
2182
- register(command2, options2 = {}) {
2183
- const { name: name2, execute: execute2 } = command2;
2182
+ register(command2, options3 = {}) {
2183
+ const { name: name2, execute: execute3 } = command2;
2184
2184
  if (typeof name2 !== "string" || !name2 || /[\s/\0]/u.test(name2)) {
2185
2185
  throw new TypeError("Command names must be nonempty and contain no whitespace, slash, or NUL");
2186
2186
  }
2187
- if (typeof execute2 !== "function") {
2187
+ if (typeof execute3 !== "function") {
2188
2188
  throw new TypeError("Command execute must be a function");
2189
2189
  }
2190
- if (this.#commands.has(name2) && !options2.replace) {
2190
+ if (this.#commands.has(name2) && !options3.replace) {
2191
2191
  throw new Error(`Command already registered: ${name2}`);
2192
2192
  }
2193
- this.#commands.set(name2, Object.freeze({ ...command2, name: name2, execute: execute2 }));
2193
+ this.#commands.set(name2, Object.freeze({ ...command2, name: name2, execute: execute3 }));
2194
2194
  return this;
2195
2195
  }
2196
2196
  get(name2) {
@@ -2273,9 +2273,9 @@ init_platform();
2273
2273
  import { collectBytes, readBytes } from "poe-code/safe-fs/core";
2274
2274
  import { collectBytes as collectBytes2, readBytes as readBytes2, toByteSource } from "poe-code/safe-fs/core";
2275
2275
  var outputFailure = /* @__PURE__ */ Symbol("output failure");
2276
- function createBytePipe(options2 = {}) {
2277
- const highWaterMark = options2.highWaterMark ?? 64 * 1024;
2278
- const signal = options2.signal;
2276
+ function createBytePipe(options3 = {}) {
2277
+ const highWaterMark = options3.highWaterMark ?? 64 * 1024;
2278
+ const signal = options3.signal;
2279
2279
  if (!Number.isSafeInteger(highWaterMark) || highWaterMark < 1) {
2280
2280
  throw new RangeError("highWaterMark must be a positive safe integer");
2281
2281
  }
@@ -2390,8 +2390,8 @@ async function pipeBytes(source, sink, signal) {
2390
2390
  }
2391
2391
  signal?.throwIfAborted();
2392
2392
  }
2393
- async function collectText(source, options2) {
2394
- return new TextDecoder().decode(await collectBytes(source, options2));
2393
+ async function collectText(source, options3) {
2394
+ return new TextDecoder().decode(await collectBytes(source, options3));
2395
2395
  }
2396
2396
  async function abortable(operation, signal) {
2397
2397
  signal?.throwIfAborted();
@@ -2796,17 +2796,6 @@ function concatenate(chunks, size = chunks.reduce((sum, chunk) => sum + chunk.le
2796
2796
  }
2797
2797
  return result;
2798
2798
  }
2799
- async function collect(source, signal, limit = bufferLimit) {
2800
- const chunks = [];
2801
- let size = 0;
2802
- for await (const chunk of source) {
2803
- signal.throwIfAborted();
2804
- size += chunk.length;
2805
- if (size > limit) throw new FsError("EFBIG", { message: `buffer limit exceeded (${limit} bytes)` });
2806
- chunks.push(new Uint8Array(chunk));
2807
- }
2808
- return concatenate(chunks, size);
2809
- }
2810
2799
  async function* lines(source, separator = 10) {
2811
2800
  let pending = [];
2812
2801
  let size = 0;
@@ -3128,23 +3117,23 @@ function compareCopyIdentity(left, right) {
3128
3117
  if (!left || !right || !complete(left) || !complete(right)) return "unknown";
3129
3118
  return left.identityScope === right.identityScope && left.dev === right.dev && left.ino === right.ino ? "same" : "distinct";
3130
3119
  }
3131
- async function compareObservedEntries(fs, path, stat, peer, peerPath, peerStat, options2 = {}) {
3132
- options2.signal?.throwIfAborted();
3120
+ async function compareObservedEntries(fs, path, stat, peer, peerPath, peerStat, options3 = {}) {
3121
+ options3.signal?.throwIfAborted();
3133
3122
  const identity = compareCopyIdentity(stat, peerStat);
3134
3123
  if (identity !== "unknown") return identity;
3135
3124
  let result = "unknown";
3136
3125
  const operands = fs === peer ? [[fs, path, peer, peerPath]] : [[fs, path, peer, peerPath], [peer, peerPath, fs, path]];
3137
3126
  for (const [owner, ownPath, other, otherPath] of operands) {
3138
- options2.signal?.throwIfAborted();
3127
+ options3.signal?.throwIfAborted();
3139
3128
  if (!owner.compareEntry) continue;
3140
3129
  let answer;
3141
3130
  try {
3142
- answer = await owner.compareEntry(ownPath, other, otherPath, options2);
3131
+ answer = await owner.compareEntry(ownPath, other, otherPath, options3);
3143
3132
  } catch (error) {
3144
- options2.signal?.throwIfAborted();
3133
+ options3.signal?.throwIfAborted();
3145
3134
  throw error;
3146
3135
  }
3147
- options2.signal?.throwIfAborted();
3136
+ options3.signal?.throwIfAborted();
3148
3137
  if (answer !== "same" && answer !== "distinct" && answer !== "unknown") {
3149
3138
  throw new FsError("EIO", { path, dest: peerPath, message: "invalid entry comparison answer" });
3150
3139
  }
@@ -4772,15 +4761,15 @@ function textCommands() {
4772
4761
  if (numericKey && numericKeyFlags.has("n") && !["b", "f"].some((flag) => numericKeyFlags.has(flag)) && !parsed.flags.has("c")) {
4773
4762
  const keyedNumericValues = /* @__PURE__ */ new Map();
4774
4763
  let retainedKeyBytes = 0;
4775
- const keyedNumericValue = (record3) => {
4776
- const cached = keyedNumericValues.get(record3);
4764
+ const keyedNumericValue = (record4) => {
4765
+ const cached = keyedNumericValues.get(record4);
4777
4766
  if (cached !== void 0) return cached;
4778
4767
  context.signal.throwIfAborted();
4779
- const bytes2 = keyBytes(record3, numericKey, separator, false);
4768
+ const bytes2 = keyBytes(record4, numericKey, separator, false);
4780
4769
  const charge2 = 6 * bytes2.length + 2;
4781
4770
  if (keyedNumericValues.size >= 16384 || charge2 > 1048576 - retainedKeyBytes) return parseNumeric(bytes2);
4782
4771
  const parsedValue = parseNumeric(bytes2);
4783
- keyedNumericValues.set(record3, parsedValue);
4772
+ keyedNumericValues.set(record4, parsedValue);
4784
4773
  retainedKeyBytes += charge2;
4785
4774
  return parsedValue;
4786
4775
  };
@@ -4826,13 +4815,13 @@ function textCommands() {
4826
4815
  let previous;
4827
4816
  let buffer = new Uint8Array(64 * 1024);
4828
4817
  let used = 0;
4829
- for (const record3 of records) {
4818
+ for (const record4 of records) {
4830
4819
  context.signal.throwIfAborted();
4831
- if (parsed.flags.has("u") && previous !== void 0 && keyCompare(previous, record3) === 0) continue;
4820
+ if (parsed.flags.has("u") && previous !== void 0 && keyCompare(previous, record4) === 0) continue;
4832
4821
  let offset = 0;
4833
- while (offset < record3.length) {
4834
- const length = Math.min(record3.length - offset, buffer.length - used);
4835
- buffer.set(record3.subarray(offset, offset + length), used);
4822
+ while (offset < record4.length) {
4823
+ const length = Math.min(record4.length - offset, buffer.length - used);
4824
+ buffer.set(record4.subarray(offset, offset + length), used);
4836
4825
  offset += length;
4837
4826
  used += length;
4838
4827
  if (used === buffer.length) {
@@ -4847,7 +4836,7 @@ function textCommands() {
4847
4836
  buffer = new Uint8Array(64 * 1024);
4848
4837
  used = 0;
4849
4838
  }
4850
- previous = record3;
4839
+ previous = record4;
4851
4840
  }
4852
4841
  if (used) yield buffer.subarray(0, used);
4853
4842
  })();
@@ -4878,19 +4867,19 @@ function textCommands() {
4878
4867
  let previousKey;
4879
4868
  let count2 = 0;
4880
4869
  const selected = () => (!parsed.flags.has("d") || count2 > 1) && (!parsed.flags.has("u") || count2 === 1);
4881
- const record3 = () => concatenate([...parsed.flags.has("c") ? [encoder2.encode(`${String(count2).padStart(7)} `)] : [], previous, Uint8Array.of(delimiter)]);
4870
+ const record4 = () => concatenate([...parsed.flags.has("c") ? [encoder2.encode(`${String(count2).padStart(7)} `)] : [], previous, Uint8Array.of(delimiter)]);
4882
4871
  for await (const line of lines(input(context, parsed.operands[0]), delimiter)) {
4883
4872
  context.signal.throwIfAborted();
4884
4873
  const currentKey = key(line.bytes);
4885
4874
  if (previousKey && compareBytes(previousKey, currentKey) === 0) count2++;
4886
4875
  else {
4887
- if (previous !== void 0 && selected()) yield record3();
4876
+ if (previous !== void 0 && selected()) yield record4();
4888
4877
  previous = line.bytes;
4889
4878
  previousKey = currentKey;
4890
4879
  count2 = 1;
4891
4880
  }
4892
4881
  }
4893
- if (previous !== void 0 && selected()) yield record3();
4882
+ if (previous !== void 0 && selected()) yield record4();
4894
4883
  })();
4895
4884
  if (parsed.operands[1] !== void 0 && parsed.operands[0] !== "-" && pathOf(context, parsed.operands[0]) === pathOf(context, parsed.operands[1])) throw new UsageError("input and output must be different files");
4896
4885
  await emitRecords(context, records, parsed.operands[1]);
@@ -4923,9 +4912,9 @@ function textCommands() {
4923
4912
  context.signal.throwIfAborted();
4924
4913
  let bytes2;
4925
4914
  if (mode === "f") {
4926
- const record3 = import_buffer.Buffer.from(line.bytes.buffer, line.bytes.byteOffset, line.bytes.byteLength);
4915
+ const record4 = import_buffer.Buffer.from(line.bytes.buffer, line.bytes.byteOffset, line.bytes.byteLength);
4927
4916
  const separator = import_buffer.Buffer.from(delimiter);
4928
- let boundary = record3.indexOf(separator);
4917
+ let boundary = record4.indexOf(separator);
4929
4918
  if (boundary < 0) {
4930
4919
  if (parsed.flags.has("s")) continue;
4931
4920
  bytes2 = line.bytes;
@@ -4938,12 +4927,12 @@ function textCommands() {
4938
4927
  while (true) {
4939
4928
  if (selected(field++)) {
4940
4929
  if (emitted) pieces.push(joiner);
4941
- pieces.push(record3.subarray(start, boundary < 0 ? record3.length : boundary));
4930
+ pieces.push(record4.subarray(start, boundary < 0 ? record4.length : boundary));
4942
4931
  emitted = true;
4943
4932
  }
4944
4933
  if (boundary < 0) break;
4945
4934
  start = boundary + separator.length;
4946
- boundary = record3.indexOf(separator, start);
4935
+ boundary = record4.indexOf(separator, start);
4947
4936
  }
4948
4937
  bytes2 = concatenate(pieces);
4949
4938
  }
@@ -6327,7 +6316,7 @@ var Parser = class {
6327
6316
  this.advance();
6328
6317
  let nodes = 0;
6329
6318
  const grouped = /* @__PURE__ */ new WeakSet();
6330
- const admit = () => {
6319
+ const admit2 = () => {
6331
6320
  if (nodes >= 4096) this.error("Conditional syntax exceeds 4096 nodes");
6332
6321
  nodes++;
6333
6322
  };
@@ -6338,7 +6327,7 @@ var Parser = class {
6338
6327
  const primary = (depth) => {
6339
6328
  if (depth > 64) this.error("Conditional syntax nesting exceeds 64");
6340
6329
  if (this.is("!")) {
6341
- admit();
6330
+ admit2();
6342
6331
  this.advance();
6343
6332
  const expression2 = primary(depth + 1);
6344
6333
  return expression2.kind === "not" && !grouped.has(expression2) ? expression2.operand : { kind: "not", operand: expression2 };
@@ -6350,7 +6339,7 @@ var Parser = class {
6350
6339
  grouped.add(expression2);
6351
6340
  return expression2;
6352
6341
  }
6353
- admit();
6342
+ admit2();
6354
6343
  const first = operand();
6355
6344
  if (conditionalBinary.has(this.current.value)) {
6356
6345
  const operator = this.current.value;
@@ -6365,7 +6354,7 @@ var Parser = class {
6365
6354
  const conjunction = (depth) => {
6366
6355
  let expression2 = primary(depth);
6367
6356
  while (this.is("&&")) {
6368
- admit();
6357
+ admit2();
6369
6358
  this.advance();
6370
6359
  expression2 = { kind: "and", left: expression2, right: primary(depth) };
6371
6360
  }
@@ -6374,7 +6363,7 @@ var Parser = class {
6374
6363
  const disjunction = (depth) => {
6375
6364
  let expression2 = conjunction(depth);
6376
6365
  while (this.is("||")) {
6377
- admit();
6366
+ admit2();
6378
6367
  this.advance();
6379
6368
  expression2 = { kind: "or", left: expression2, right: conjunction(depth) };
6380
6369
  }
@@ -6539,18 +6528,18 @@ var Parser = class {
6539
6528
  return script;
6540
6529
  }
6541
6530
  redirect() {
6542
- let descriptor;
6531
+ let descriptor2;
6543
6532
  if (this.current.kind === "word" && /^\d+$/u.test(this.current.value)) {
6544
6533
  const next = this.peek();
6545
- if (/^(?:>|>>|<|<<|<<-|<<<|>&|<&|>\|)$/u.test(next.value) && this.current.end === next.offset) descriptor = Number(this.advance().value);
6534
+ if (/^(?:>|>>|<|<<|<<-|<<<|>&|<&|>\|)$/u.test(next.value) && this.current.end === next.offset) descriptor2 = Number(this.advance().value);
6546
6535
  }
6547
6536
  if (!/^(?:>|>>|<|<<|<<-|<<<|>&|<&|>\||&>)$/u.test(this.current.value) || this.current.kind !== "operator") return void 0;
6548
6537
  const operator = this.advance().value;
6549
- descriptor ??= operator.startsWith("<") ? 0 : 1;
6550
- if (!Number.isSafeInteger(descriptor) || descriptor > 255) this.error("File descriptor must be between 0 and 255");
6538
+ descriptor2 ??= operator.startsWith("<") ? 0 : 1;
6539
+ if (!Number.isSafeInteger(descriptor2) || descriptor2 > 255) this.error("File descriptor must be between 0 and 255");
6551
6540
  if (!this.current.word) this.error("Expected redirect target");
6552
6541
  const target = this.advance();
6553
- return { descriptor, operator, target: target.word, line: this.lexer.lineAt(Math.max(target.offset, target.end - 1)), ...(operator === "<&" || operator === ">&") && this.lexer.source[target.end - 1] === "-" ? { move: true } : {}, ...target.document ? { document: target.document } : {} };
6542
+ return { descriptor: descriptor2, operator, target: target.word, line: this.lexer.lineAt(Math.max(target.offset, target.end - 1)), ...(operator === "<&" || operator === ">&") && this.lexer.source[target.end - 1] === "-" ? { move: true } : {}, ...target.document ? { document: target.document } : {} };
6554
6543
  }
6555
6544
  };
6556
6545
  function parseShell(source, depth = 0) {
@@ -6599,13 +6588,13 @@ init_platform();
6599
6588
  // packages/safe-bash/src/shell/value-state.ts
6600
6589
  init_platform();
6601
6590
  var ValueArena = class {
6602
- constructor(maximumBytes, maximumSlots, checkpoint, fail = (limit) => {
6591
+ constructor(maximumBytes, maximumSlots, checkpoint, fail2 = (limit) => {
6603
6592
  throw new ShellLimitError(limit);
6604
6593
  }) {
6605
6594
  this.maximumBytes = maximumBytes;
6606
6595
  this.maximumSlots = maximumSlots;
6607
6596
  this.checkpoint = checkpoint;
6608
- this.fail = fail;
6597
+ this.fail = fail2;
6609
6598
  }
6610
6599
  maximumBytes;
6611
6600
  maximumSlots;
@@ -6635,25 +6624,25 @@ var ValueArena = class {
6635
6624
  if (!Number.isSafeInteger(bytes2) || bytes2 < 0 || !Number.isSafeInteger(slots) || slots < 0) throw new RangeError("Invalid shell value allocation");
6636
6625
  if (bytes2 > this.maximumBytes - this.#bytes) this.fail("maxExpansionBytes");
6637
6626
  if (slots > this.maximumSlots - this.#slots) this.fail("maxExpansionFields");
6638
- const record3 = { bytes: bytes2, slots, references: 1 };
6627
+ const record4 = { bytes: bytes2, slots, references: 1 };
6639
6628
  this.#bytes += bytes2;
6640
6629
  this.#slots += slots;
6641
- this.#records.add(record3);
6642
- return record3;
6630
+ this.#records.add(record4);
6631
+ return record4;
6643
6632
  }
6644
- commit(record3, object) {
6633
+ commit(record4, object) {
6645
6634
  this.assertOpen();
6646
- if (!this.#records.has(record3) || record3.object || this.#objects.has(object)) throw new Error("Shell value reservation is not fresh");
6647
- record3.object = object;
6648
- this.#objects.set(object, record3);
6649
- }
6650
- release(record3) {
6651
- if (!this.#records.has(record3)) return;
6652
- if (--record3.references) return;
6653
- this.#records.delete(record3);
6654
- if (record3.object) this.#objects.delete(record3.object);
6655
- this.#bytes -= record3.bytes;
6656
- this.#slots -= record3.slots;
6635
+ if (!this.#records.has(record4) || record4.object || this.#objects.has(object)) throw new Error("Shell value reservation is not fresh");
6636
+ record4.object = object;
6637
+ this.#objects.set(object, record4);
6638
+ }
6639
+ release(record4) {
6640
+ if (!this.#records.has(record4)) return;
6641
+ if (--record4.references) return;
6642
+ this.#records.delete(record4);
6643
+ if (record4.object) this.#objects.delete(record4.object);
6644
+ this.#bytes -= record4.bytes;
6645
+ this.#slots -= record4.slots;
6657
6646
  }
6658
6647
  hold(value2) {
6659
6648
  this.assertOpen();
@@ -6696,7 +6685,7 @@ var ValueArena = class {
6696
6685
  }
6697
6686
  close() {
6698
6687
  this.#closed = true;
6699
- for (const record3 of this.#records) if (record3.object) this.#objects.delete(record3.object);
6688
+ for (const record4 of this.#records) if (record4.object) this.#objects.delete(record4.object);
6700
6689
  this.#records.clear();
6701
6690
  this.#bytes = 0;
6702
6691
  this.#slots = 0;
@@ -6718,19 +6707,19 @@ var ValueScope = class {
6718
6707
  reserve(bytes2, slots) {
6719
6708
  this.assertOpen();
6720
6709
  this.#enrollment ??= this.arena.allocate(64, 1);
6721
- const record3 = this.arena.allocate(bytes2, slots);
6710
+ const record4 = this.arena.allocate(bytes2, slots);
6722
6711
  let released = false;
6723
6712
  const release = () => {
6724
6713
  if (released) return;
6725
6714
  released = true;
6726
6715
  this.#releases.delete(release);
6727
- this.arena.release(record3);
6716
+ this.arena.release(record4);
6728
6717
  };
6729
6718
  this.#releases.add(release);
6730
6719
  return { commit: (value2) => {
6731
6720
  this.assertOpen();
6732
6721
  if (released) throw new Error("Shell value reservation is released");
6733
- this.arena.commit(record3, value2);
6722
+ this.arena.commit(record4, value2);
6734
6723
  }, release };
6735
6724
  }
6736
6725
  hold(value2) {
@@ -6898,28 +6887,28 @@ function positionalTemplate(source, checkpoint) {
6898
6887
  }
6899
6888
  return found;
6900
6889
  }
6901
- function positionalValue(name2, options2) {
6890
+ function positionalValue(name2, options3) {
6902
6891
  let index = 0;
6903
6892
  let outside = false;
6904
6893
  for (let position = 0; position < name2.length; position++) {
6905
- if (position % 128 === 0) options2.checkpoint();
6894
+ if (position % 128 === 0) options3.checkpoint();
6906
6895
  const next = name2.charCodeAt(position) - 48;
6907
- if (index > Math.floor((options2.positional.length - next) / 10)) outside = true;
6896
+ if (index > Math.floor((options3.positional.length - next) / 10)) outside = true;
6908
6897
  if (!outside) index = index * 10 + next;
6909
6898
  }
6910
- return outside ? void 0 : index === 0 ? options2.arg0 : options2.positional[index - 1];
6899
+ return outside ? void 0 : index === 0 ? options3.arg0 : options3.positional[index - 1];
6911
6900
  }
6912
- function evaluatePositionalArithmetic(program, options2, evaluate) {
6901
+ function evaluatePositionalArithmetic(program, options3, evaluate) {
6913
6902
  const source = program.source;
6914
6903
  if (!source.includes("$")) return evaluate(program);
6915
- options2.checkpoint();
6916
- if (!positionalTemplate(source, options2.checkpoint)) return evaluate(program);
6917
- const header = options2.owner?.reserve({ metadata: 128, allocatedSlots: 2, work: source.length * 2 + 8 });
6904
+ options3.checkpoint();
6905
+ if (!positionalTemplate(source, options3.checkpoint)) return evaluate(program);
6906
+ const header = options3.owner?.reserve({ metadata: 128, allocatedSlots: 2, work: source.length * 2 + 8 });
6918
6907
  const admissions = [];
6919
6908
  const chunks = [];
6920
6909
  let bytes2 = 0;
6921
6910
  const reserve = (payload) => {
6922
- const admission = options2.owner?.reserve({ payload, metadata: 64, allocatedSlots: 2, work: 4 });
6911
+ const admission = options3.owner?.reserve({ payload, metadata: 64, allocatedSlots: 2, work: 4 });
6923
6912
  if (admission) admissions.push(admission);
6924
6913
  };
6925
6914
  const length = (text, start, end, maximum) => {
@@ -6927,7 +6916,7 @@ function evaluatePositionalArithmetic(program, options2, evaluate) {
6927
6916
  let nextCheckpoint = start;
6928
6917
  for (let position = start; position < end; ) {
6929
6918
  if (position >= nextCheckpoint) {
6930
- options2.checkpoint();
6919
+ options3.checkpoint();
6931
6920
  nextCheckpoint = position + 128;
6932
6921
  }
6933
6922
  const code = text.charCodeAt(position++);
@@ -6937,14 +6926,14 @@ function evaluatePositionalArithmetic(program, options2, evaluate) {
6937
6926
  size += 4;
6938
6927
  position++;
6939
6928
  } else size += 3;
6940
- if (size > maximum) options2.limit();
6929
+ if (size > maximum) options3.limit();
6941
6930
  }
6942
- options2.owner?.reserve({ work: end - start }).release();
6931
+ options3.owner?.reserve({ work: end - start }).release();
6943
6932
  return size;
6944
6933
  };
6945
6934
  const literal = (start, end) => {
6946
6935
  if (start === end) return;
6947
- const size = length(source, start, end, options2.maximumBytes - bytes2);
6936
+ const size = length(source, start, end, options3.maximumBytes - bytes2);
6948
6937
  reserve(size);
6949
6938
  chunks.push(source.slice(start, end));
6950
6939
  bytes2 += size;
@@ -6954,7 +6943,7 @@ function evaluatePositionalArithmetic(program, options2, evaluate) {
6954
6943
  let nextCheckpoint = 0;
6955
6944
  for (let position = 0; position < source.length; ) {
6956
6945
  if (position >= nextCheckpoint) {
6957
- options2.checkpoint();
6946
+ options3.checkpoint();
6958
6947
  nextCheckpoint = position + 128;
6959
6948
  }
6960
6949
  if (source[position] !== "$") {
@@ -6967,17 +6956,17 @@ function evaluatePositionalArithmetic(program, options2, evaluate) {
6967
6956
  let nameEnd = nameStart + 1;
6968
6957
  if (braced) while (digit(source, nameEnd)) {
6969
6958
  if (nameEnd >= nextCheckpoint) {
6970
- options2.checkpoint();
6959
+ options3.checkpoint();
6971
6960
  nextCheckpoint = nameEnd + 128;
6972
6961
  }
6973
6962
  nameEnd++;
6974
6963
  }
6975
6964
  reserve(nameEnd - nameStart);
6976
6965
  const name2 = source.slice(nameStart, nameEnd);
6977
- const value2 = positionalValue(name2, options2);
6978
- options2.requireParameter(name2, value2);
6966
+ const value2 = positionalValue(name2, options3);
6967
+ options3.requireParameter(name2, value2);
6979
6968
  const text = value2 ?? "";
6980
- const size = length(text, 0, text.length, options2.maximumBytes - bytes2);
6969
+ const size = length(text, 0, text.length, options3.maximumBytes - bytes2);
6981
6970
  reserve(size);
6982
6971
  chunks.push(text);
6983
6972
  bytes2 += size;
@@ -6985,10 +6974,10 @@ function evaluatePositionalArithmetic(program, options2, evaluate) {
6985
6974
  start = position;
6986
6975
  }
6987
6976
  literal(start, source.length);
6988
- options2.checkpoint();
6977
+ options3.checkpoint();
6989
6978
  reserve(bytes2);
6990
6979
  const expanded = chunks.join("");
6991
- options2.checkpoint();
6980
+ options3.checkpoint();
6992
6981
  return evaluate(prepareArithmetic(expanded));
6993
6982
  } finally {
6994
6983
  for (let position = admissions.length - 1; position >= 0; position--) admissions[position].release();
@@ -7522,7 +7511,7 @@ async function* argumentsFrom(source, signal, delimiter, replacement = false) {
7522
7511
  if (quote || escaped) throw new UsageError(quote ? "unmatched quote in input" : "trailing backslash in input");
7523
7512
  if (active) yield current;
7524
7513
  }
7525
- function executionCommands(execute2) {
7514
+ function executionCommands(execute3) {
7526
7515
  return [
7527
7516
  define("env", async (context) => {
7528
7517
  const argumentValues = getCommandArguments(context);
@@ -7573,7 +7562,7 @@ function executionCommands(execute2) {
7573
7562
  stderr: context.stderr,
7574
7563
  ...context.stdinIsDefault === void 0 ? {} : { stdinIsDefault: context.stdinIsDefault }
7575
7564
  });
7576
- return execute2({ ...context, command: parsed.operands[offset], args: childArguments.args, argumentValues: childArguments, env: childEnv, cwd });
7565
+ return execute3({ ...context, command: parsed.operands[offset], args: childArguments.args, argumentValues: childArguments, env: childEnv, cwd });
7577
7566
  }
7578
7567
  for (const name2 of names) await output(context, `${name2}=${env[name2]}${parsed.flags.has("0") ? "\0" : "\n"}`);
7579
7568
  return { exitCode: 0 };
@@ -7613,7 +7602,7 @@ function executionCommands(execute2) {
7613
7602
  const size = encoder2.encode(command2).length + 1 + childArguments.values.reduce((sum, argument) => sum + shellValueByteLength(argument) + 1, 0);
7614
7603
  if (size > maxBytes) throw new UsageError("expanded arguments exceed command size limit");
7615
7604
  if (parsed.flags.has("t")) await writeBytes(context.stderr, encoder2.encode([command2, ...args].map((argument) => /^[A-Za-z0-9_./-]+$/u.test(argument) ? argument : `'${argument.replaceAll("'", "'\\''")}'`).join(" ") + "\n"), context.signal);
7616
- const result = await execute2({ ...context, command: command2, args, argumentValues: childArguments, stdin: emptyInput(), stdinIsDefault: true, env: { ...context.env } });
7605
+ const result = await execute3({ ...context, command: command2, args, argumentValues: childArguments, stdin: emptyInput(), stdinIsDefault: true, env: { ...context.env } });
7617
7606
  executed = true;
7618
7607
  if (result.exitCode === 255) {
7619
7608
  status = 124;
@@ -7770,9 +7759,9 @@ async function validateString(value2, work, optstring = false) {
7770
7759
  else work.addBytes(3);
7771
7760
  }
7772
7761
  }
7773
- async function scanGetopts(state, optstring, args, options2) {
7774
- if (!record2(options2) || typeof options2.reportErrors !== "boolean") throw new GetoptsError("INVALID_INPUT", "Getopts requires explicit diagnostic policy and work controls");
7775
- const work = new ScanWork(options2.work);
7762
+ async function scanGetopts(state, optstring, args, options3) {
7763
+ if (!record2(options3) || typeof options3.reportErrors !== "boolean") throw new GetoptsError("INVALID_INPUT", "Getopts requires explicit diagnostic policy and work controls");
7764
+ const work = new ScanWork(options3.work);
7776
7765
  const original = cloneGetoptsState(state);
7777
7766
  if (!Array.isArray(args)) throw new GetoptsError("INVALID_INPUT", "Getopts requires an argument array");
7778
7767
  if (args.length > work.maxArguments) throw new GetoptsError("ARGUMENT_LIMIT", "Getopts argument limit exceeded");
@@ -7827,7 +7816,7 @@ async function scanGetopts(state, optstring, args, options2) {
7827
7816
  active = attached ? { argument: active.argument, offset } : void 0;
7828
7817
  if (!attached) index++;
7829
7818
  if (specification[code] === -1) {
7830
- return finish("unknown-option", "?", silent ? { kind: "set", value: option } : { kind: "unset" }, !silent && options2.reportErrors ? { kind: "unknown-option", option } : null);
7819
+ return finish("unknown-option", "?", silent ? { kind: "set", value: option } : { kind: "unset" }, !silent && options3.reportErrors ? { kind: "unknown-option", option } : null);
7831
7820
  }
7832
7821
  if (specification[code] === 1) {
7833
7822
  if (attached) {
@@ -7840,7 +7829,7 @@ async function scanGetopts(state, optstring, args, options2) {
7840
7829
  index++;
7841
7830
  return finish("option", option, { kind: "set", value: value2 }, null);
7842
7831
  }
7843
- return finish("missing-argument", silent ? ":" : "?", silent ? { kind: "set", value: option } : { kind: "unset" }, !silent && options2.reportErrors ? { kind: "missing-argument", option } : null);
7832
+ return finish("missing-argument", silent ? ":" : "?", silent ? { kind: "set", value: option } : { kind: "unset" }, !silent && options3.reportErrors ? { kind: "missing-argument", option } : null);
7844
7833
  }
7845
7834
  return finish("option", option, { kind: "unset" }, null);
7846
7835
  }
@@ -8179,17 +8168,17 @@ function throwLocalActivationFailure(state) {
8179
8168
  const failure = localActivationFailure(state);
8180
8169
  if (failure.failed) throw failure.reason;
8181
8170
  }
8182
- function prepareChildCancellation(parent, options2, snapshot, controls) {
8171
+ function prepareChildCancellation(parent, options3, snapshot, controls) {
8183
8172
  const parentState = requireLink(parent);
8184
8173
  throwAdmissionFailure(parentState);
8185
8174
  let localSignal;
8186
- if (options2 !== void 0) {
8187
- if (options2 === null || typeof options2 !== "object" && typeof options2 !== "function") {
8175
+ if (options3 !== void 0) {
8176
+ if (options3 === null || typeof options3 !== "object" && typeof options3 !== "function") {
8188
8177
  return stagedFailure(parentState, new TypeError("Cancellation options must be an object or function"));
8189
8178
  }
8190
8179
  let candidate;
8191
8180
  try {
8192
- candidate = options2.signal;
8181
+ candidate = options3.signal;
8193
8182
  } catch (error) {
8194
8183
  return stagedFailure(parentState, error);
8195
8184
  }
@@ -9154,10 +9143,10 @@ var StateMonitor = class {
9154
9143
  monitor.finish(tickets, name2);
9155
9144
  return result;
9156
9145
  },
9157
- defineProperty(target, key, descriptor) {
9146
+ defineProperty(target, key, descriptor2) {
9158
9147
  const name2 = named ? String(key) : void 0;
9159
9148
  const tickets = monitor.mutation(name2);
9160
- const result = Reflect.defineProperty(target, key, descriptor);
9149
+ const result = Reflect.defineProperty(target, key, descriptor2);
9161
9150
  if (result) monitor.changedValue(target, field, key);
9162
9151
  monitor.finish(tickets, name2);
9163
9152
  return result;
@@ -9954,6 +9943,7 @@ var defaultLimits = {
9954
9943
  maxInputBytes: 32 * 1024 * 1024,
9955
9944
  maxOutputBytes: 16 * 1024 * 1024,
9956
9945
  maxCommands: 1e4,
9946
+ maxRedirects: 64,
9957
9947
  maxPipelineStages: 64,
9958
9948
  maxLoopIterations: 1e4,
9959
9949
  maxSubstitutionDepth: 64,
@@ -10178,12 +10168,21 @@ var Capture = class {
10178
10168
  }
10179
10169
  return bytes2;
10180
10170
  }
10171
+ takeBytes() {
10172
+ const chunk = this.chunks.length === 1 ? this.chunks[0] : void 0;
10173
+ const bytes2 = chunk && chunk.byteLength === chunk.buffer.byteLength ? chunk : this.bytes();
10174
+ this.chunks.length = 0;
10175
+ this.length = 0;
10176
+ this.#tail = void 0;
10177
+ this.#tailLength = 0;
10178
+ return bytes2;
10179
+ }
10181
10180
  };
10182
10181
  var typedSavedVariables = /* @__PURE__ */ new WeakMap();
10183
10182
  var valueScope = /* @__PURE__ */ Symbol("shell value allocation scope");
10184
10183
  var invokedValues = /* @__PURE__ */ new WeakMap();
10185
10184
  function isolateIO(io) {
10186
- return { ...io, ...io.descriptors ? { descriptors: new Map([...io.descriptors].map(([number, descriptor]) => [number, { ...descriptor }])) } : {} };
10185
+ return { ...io, ...io.descriptors ? { descriptors: new Map([...io.descriptors].map(([number, descriptor2]) => [number, { ...descriptor2 }])) } : {} };
10187
10186
  }
10188
10187
  function activeIO(io) {
10189
10188
  const input3 = io.descriptors?.get(0);
@@ -10197,6 +10196,13 @@ function activeIO(io) {
10197
10196
  ...error?.closed && error.output === io.stderr ? { stderr: closedSink } : {}
10198
10197
  };
10199
10198
  }
10199
+ function appendOutputBytes(current, chunk) {
10200
+ const length = current.length + chunk.length;
10201
+ const bytes2 = current.buffer.byteLength - current.byteOffset >= length ? new Uint8Array(current.buffer, current.byteOffset, length) : new Uint8Array(Math.max(length, current.length * 2, 64));
10202
+ if (bytes2.buffer !== current.buffer) bytes2.set(current);
10203
+ bytes2.set(chunk, current.length);
10204
+ return bytes2.subarray(0, length);
10205
+ }
10200
10206
  var Flow = class extends Error {
10201
10207
  constructor(kind, status, levels = 1) {
10202
10208
  super(kind);
@@ -10654,11 +10660,11 @@ var DirectoryStackWork = class {
10654
10660
  await writeText(this.stdout, text);
10655
10661
  this.signal.throwIfAborted();
10656
10662
  }
10657
- async display(cwd, entries, options2, home) {
10663
+ async display(cwd, entries, options3, home) {
10658
10664
  await this.scan(cwd, "path");
10659
- const homeBytes = !options2.long && home !== void 0 ? await this.scan(home, "HOME") : 0;
10660
- const start = options2.index ?? 0;
10661
- const end = options2.index ?? entries.length;
10665
+ const homeBytes = !options3.long && home !== void 0 ? await this.scan(home, "HOME") : 0;
10666
+ const start = options3.index ?? 0;
10667
+ const end = options3.index ?? entries.length;
10662
10668
  for (let index = start; index <= end; index++) {
10663
10669
  await this.charge(1);
10664
10670
  let entry = index === 0 ? cwd : entries[index - 1];
@@ -10676,12 +10682,12 @@ var DirectoryStackWork = class {
10676
10682
  if (entry.length === home.length || entry[home.length] === "/") entry = `~${entry.slice(home.length)}`;
10677
10683
  }
10678
10684
  }
10679
- if (index !== start && !options2.lines && !options2.verbose) await this.emit(" ");
10680
- if (options2.verbose) await this.emit(`${String(index).padStart(2, " ")} `);
10685
+ if (index !== start && !options3.lines && !options3.verbose) await this.emit(" ");
10686
+ if (options3.verbose) await this.emit(`${String(index).padStart(2, " ")} `);
10681
10687
  await this.emit(entry);
10682
- if (options2.lines || options2.verbose) await this.emit("\n");
10688
+ if (options3.lines || options3.verbose) await this.emit("\n");
10683
10689
  }
10684
- if (!options2.lines && !options2.verbose) await this.emit("\n");
10690
+ if (!options3.lines && !options3.verbose) await this.emit("\n");
10685
10691
  await this.flushOutput();
10686
10692
  }
10687
10693
  };
@@ -10739,34 +10745,34 @@ var RuntimeCancellationState = class {
10739
10745
  }
10740
10746
  bind(promise, boundary) {
10741
10747
  if (this.#closed) throw new Error("Cancellation outcome admission is closed");
10742
- const record3 = { promise, boundary, finalized: false, consumed: false };
10743
- this.#records.add(record3);
10744
- return record3;
10748
+ const record4 = { promise, boundary, finalized: false, consumed: false };
10749
+ this.#records.add(record4);
10750
+ return record4;
10745
10751
  }
10746
- finalize(record3, selection) {
10747
- if (record3.consumed || !this.#records.has(record3)) return;
10748
- record3.selection = selection;
10749
- record3.finalized = true;
10752
+ finalize(record4, selection) {
10753
+ if (record4.consumed || !this.#records.has(record4)) return;
10754
+ record4.selection = selection;
10755
+ record4.finalized = true;
10750
10756
  }
10751
10757
  consume(rawReturn, capturedReason) {
10752
- for (const record3 of this.#records) {
10753
- if (record3.promise !== rawReturn) continue;
10754
- record3.consumed = true;
10755
- this.#records.delete(record3);
10756
- const selection = record3.selection;
10757
- if (!record3.finalized || selection?.outcome.kind !== "throw" || !Object.is(selection.outcome.reason, capturedReason)) return void 0;
10758
+ for (const record4 of this.#records) {
10759
+ if (record4.promise !== rawReturn) continue;
10760
+ record4.consumed = true;
10761
+ this.#records.delete(record4);
10762
+ const selection = record4.selection;
10763
+ if (!record4.finalized || selection?.outcome.kind !== "throw" || !Object.is(selection.outcome.reason, capturedReason)) return void 0;
10758
10764
  return selection.report;
10759
10765
  }
10760
10766
  return void 0;
10761
10767
  }
10762
- discard(record3) {
10763
- if (!record3) return;
10764
- record3.consumed = true;
10765
- this.#records.delete(record3);
10768
+ discard(record4) {
10769
+ if (!record4) return;
10770
+ record4.consumed = true;
10771
+ this.#records.delete(record4);
10766
10772
  }
10767
10773
  close() {
10768
10774
  this.#closed = true;
10769
- for (const record3 of this.#records) record3.consumed = true;
10775
+ for (const record4 of this.#records) record4.consumed = true;
10770
10776
  this.#records.clear();
10771
10777
  this.#diagnostics = /* @__PURE__ */ new WeakMap();
10772
10778
  }
@@ -10820,7 +10826,7 @@ var InvocationCancellationOwner = class {
10820
10826
  throw error;
10821
10827
  }
10822
10828
  }
10823
- capture(execute2, frame) {
10829
+ capture(execute3, frame) {
10824
10830
  return new Promise((resolve) => {
10825
10831
  let settled = false;
10826
10832
  let raw;
@@ -10842,7 +10848,7 @@ var InvocationCancellationOwner = class {
10842
10848
  });
10843
10849
  };
10844
10850
  try {
10845
- raw = Promise.resolve(execute2());
10851
+ raw = Promise.resolve(execute3());
10846
10852
  } catch (reason) {
10847
10853
  settle({ kind: "throw", reason });
10848
10854
  return;
@@ -11080,13 +11086,13 @@ var Runtime = class _Runtime {
11080
11086
  }
11081
11087
  );
11082
11088
  }
11083
- invokeChild(options2, state, parent, validate, execute2) {
11089
+ invokeChild(options3, state, parent, validate, execute3) {
11084
11090
  const publicPromise = Promise.resolve().then(async () => {
11085
11091
  if (!this.cancellation.deliverySignal.aborted) parent.assertOpen();
11086
11092
  const childDepth = this.cancellationDepth + 1;
11087
11093
  const prepared = prepareChildCancellation(
11088
11094
  this.cancellation,
11089
- options2,
11095
+ options3,
11090
11096
  this.cancellationAdmission(childDepth)
11091
11097
  );
11092
11098
  this.cancellationOwner?.assertAdmissionOpen();
@@ -11126,7 +11132,7 @@ var Runtime = class _Runtime {
11126
11132
  frame
11127
11133
  );
11128
11134
  let captured;
11129
- const executeChild = () => execute2(runtime, scope);
11135
+ const executeChild = () => execute3(runtime, scope);
11130
11136
  if (owner) captured = await owner.capture(executeChild, frame);
11131
11137
  else {
11132
11138
  try {
@@ -11275,8 +11281,8 @@ var Runtime = class _Runtime {
11275
11281
  if (!typedSavedVariables.has(saved)) await this.prepareVariable(state, name2, saved);
11276
11282
  await owner.ledger.checkpoint(this.signal);
11277
11283
  }
11278
- for (const frame of stateMonitor(state).overlayFrames()) for (const [name2, record3] of frame) {
11279
- const saved = record3;
11284
+ for (const frame of stateMonitor(state).overlayFrames()) for (const [name2, record4] of frame) {
11285
+ const saved = record4;
11280
11286
  if (!saved.superseded && !typedSavedVariables.has(saved)) await this.prepareVariable(state, name2, saved, true);
11281
11287
  await owner.ledger.checkpoint(this.signal);
11282
11288
  }
@@ -11805,7 +11811,7 @@ var Runtime = class _Runtime {
11805
11811
  let io = originalIO;
11806
11812
  let diagnosticFailure;
11807
11813
  try {
11808
- const execute2 = async () => {
11814
+ const execute3 = async () => {
11809
11815
  if (command2.kind === "function") {
11810
11816
  if (state.profile === "sh" && specialBuiltinNames.has(command2.name)) {
11811
11817
  await this.diagnostic(io, `\`${command2.name}': is a special builtin`);
@@ -11958,7 +11964,7 @@ var Runtime = class _Runtime {
11958
11964
  }
11959
11965
  return status2;
11960
11966
  };
11961
- const status = await execute2();
11967
+ const status = await execute3();
11962
11968
  await finishOutputs(status);
11963
11969
  return status;
11964
11970
  } catch (caught) {
@@ -12052,6 +12058,8 @@ var Runtime = class _Runtime {
12052
12058
  return value2;
12053
12059
  }
12054
12060
  async redirect(redirects, state, io, inputs, outputs, isolatedInlineInput = false, persistMoves = false, fileShortcut = false, line) {
12061
+ this.signal.throwIfAborted();
12062
+ if (redirects.length > this.budget.limits.maxRedirects) this.budget.fail("maxRedirects");
12055
12063
  io.descriptors ??= /* @__PURE__ */ new Map([
12056
12064
  [0, { input: io.stdin, ...io.stdinIsDefault === void 0 ? {} : { stdinIsDefault: io.stdinIsDefault } }],
12057
12065
  [1, { output: io.stdout }],
@@ -12072,8 +12080,8 @@ var Runtime = class _Runtime {
12072
12080
  if (io.stdout === closedSink) descriptors.delete(1);
12073
12081
  if (io.stderr === closedSink) descriptors.delete(2);
12074
12082
  const currentIO = () => {
12075
- const descriptor = descriptors.get(0)?.closed ? void 0 : descriptors.get(0);
12076
- const stdinIsDefault = descriptor?.input ? descriptor.stdinIsDefault : false;
12083
+ const descriptor2 = descriptors.get(0)?.closed ? void 0 : descriptors.get(0);
12084
+ const stdinIsDefault = descriptor2?.input ? descriptor2.stdinIsDefault : false;
12077
12085
  return {
12078
12086
  [invocationScope]: io[invocationScope],
12079
12087
  ...io.execution === void 0 ? {} : { execution: io.execution },
@@ -12082,7 +12090,7 @@ var Runtime = class _Runtime {
12082
12090
  ...io.scriptName === void 0 ? {} : { scriptName: io.scriptName },
12083
12091
  ...io.substitutionDiagnosticLine === void 0 ? {} : { substitutionDiagnosticLine: io.substitutionDiagnosticLine },
12084
12092
  ...io.substitutionDiagnosticLines === void 0 ? {} : { substitutionDiagnosticLines: io.substitutionDiagnosticLines },
12085
- stdin: descriptor?.input ?? closedSource,
12093
+ stdin: descriptor2?.input ?? closedSource,
12086
12094
  ...stdinIsDefault === void 0 ? {} : { stdinIsDefault },
12087
12095
  stdout: descriptors.get(1)?.closed ? closedSink : descriptors.get(1)?.output ?? closedSink,
12088
12096
  stderr: descriptors.get(2)?.closed ? closedSink : descriptors.get(2)?.output ?? closedSink,
@@ -12124,20 +12132,20 @@ var Runtime = class _Runtime {
12124
12132
  const move = target.endsWith("-");
12125
12133
  if (move && !redirect.move) throw new Error(`${target}: ambiguous redirect`);
12126
12134
  const sourceDescriptor = Number(move ? target.slice(0, -1) : target);
12127
- const descriptor = descriptors.get(sourceDescriptor);
12128
- if (!descriptor || descriptor.closed || !move && (redirect.operator === "<&" ? !descriptor.input : !descriptor.output)) throw new Error(`${move ? sourceDescriptor : target}: Bad file descriptor`);
12129
- descriptors.set(redirect.descriptor, { ...descriptor });
12135
+ const descriptor2 = descriptors.get(sourceDescriptor);
12136
+ if (!descriptor2 || descriptor2.closed || !move && (redirect.operator === "<&" ? !descriptor2.input : !descriptor2.output)) throw new Error(`${move ? sourceDescriptor : target}: Bad file descriptor`);
12137
+ descriptors.set(redirect.descriptor, { ...descriptor2 });
12130
12138
  if (move && sourceDescriptor !== redirect.descriptor) {
12131
12139
  descriptors.delete(sourceDescriptor);
12132
- if (persistMoves && !replaced.has(sourceDescriptor)) descriptor.closed = true;
12140
+ if (persistMoves && !replaced.has(sourceDescriptor)) descriptor2.closed = true;
12133
12141
  }
12134
12142
  }
12135
12143
  } else {
12136
12144
  const path = resolvePath(state.cwd, target);
12137
- const options2 = { signal: this.signal };
12145
+ const options3 = { signal: this.signal };
12138
12146
  if (redirect.operator === "<") {
12139
- await interruptible(this.fs.access(path, 4, options2), this.signal);
12140
- const stat = await interruptible(this.fs.stat(path, options2), this.signal);
12147
+ await interruptible(this.fs.access(path, 4, options3), this.signal);
12148
+ const stat = await interruptible(this.fs.stat(path, options3), this.signal);
12141
12149
  if (stat.type === "directory" && !fileShortcut) throw new Error(`${target}: Is a directory`);
12142
12150
  const source = stat.type === "directory" ? toByteSource("") : await fileInput(this.fs, path, this.budget.limits.maxInputBytes, this.signal);
12143
12151
  const input3 = new ShellInput(source, this.budget, this.signal);
@@ -12145,7 +12153,7 @@ var Runtime = class _Runtime {
12145
12153
  descriptors.set(redirect.descriptor, { input: input3, stdinIsDefault: false });
12146
12154
  } else {
12147
12155
  const append = redirect.operator === ">>";
12148
- const capabilities = await this.fs.capabilitiesFor?.(path, options2) ?? this.fs.capabilities;
12156
+ const capabilities = await this.fs.capabilitiesFor?.(path, options3) ?? this.fs.capabilities;
12149
12157
  const random = capabilities.randomAccessWrite === true;
12150
12158
  let file;
12151
12159
  await this.fileOperation(path, async () => {
@@ -12158,8 +12166,8 @@ var Runtime = class _Runtime {
12158
12166
  let offset = 0;
12159
12167
  const incremental = async () => {
12160
12168
  await this.fileOperation(path, async () => {
12161
- if (append) await this.fs.appendFile(path, new Uint8Array(), options2);
12162
- else await this.fs.writeFile(path, new Uint8Array(), { ...options2, flag: "w" });
12169
+ if (append) await this.fs.appendFile(path, new Uint8Array(), options3);
12170
+ else await this.fs.writeFile(path, new Uint8Array(), { ...options3, flag: "w" });
12163
12171
  if (!append) file.data = new Uint8Array();
12164
12172
  });
12165
12173
  return { write: (chunk) => {
@@ -12167,22 +12175,27 @@ var Runtime = class _Runtime {
12167
12175
  return this.fileOperation(path, async () => {
12168
12176
  if (closed) throw new Error("Output descriptor is closed");
12169
12177
  const current = file.data;
12170
- if (append) {
12171
- await this.fs.appendFile(path, copy2, options2);
12172
- if (current) {
12173
- const bytes2 = new Uint8Array(current.length + copy2.length);
12174
- bytes2.set(current);
12175
- bytes2.set(copy2, current.length);
12176
- file.data = bytes2;
12178
+ let atEOF = false;
12179
+ if (!append && current && offset === current.length && capabilities.append === true && capabilities.stat !== false) {
12180
+ try {
12181
+ atEOF = (await interruptible(this.fs.stat(path, options3), this.signal)).size === offset;
12182
+ } catch {
12183
+ this.signal.throwIfAborted();
12177
12184
  }
12185
+ this.signal.throwIfAborted();
12186
+ }
12187
+ if (append || atEOF) {
12188
+ const bytes2 = current ? appendOutputBytes(current, copy2) : void 0;
12189
+ await this.fs.appendFile(path, copy2, options3);
12190
+ file.data = bytes2;
12178
12191
  } else {
12179
12192
  const bytes2 = new Uint8Array(Math.max(current?.length ?? 0, offset + copy2.length));
12180
12193
  if (current) bytes2.set(current);
12181
12194
  bytes2.set(copy2, offset);
12182
- await this.fs.writeFile(path, bytes2, options2);
12195
+ await this.fs.writeFile(path, bytes2, options3);
12183
12196
  file.data = bytes2;
12184
- offset += copy2.length;
12185
12197
  }
12198
+ if (!append) offset += copy2.length;
12186
12199
  });
12187
12200
  } };
12188
12201
  };
@@ -12448,8 +12461,8 @@ var Runtime = class _Runtime {
12448
12461
  fs: this.fs,
12449
12462
  signal: this.commandSignal,
12450
12463
  registerCleanup: (cleanup) => scope.register(cleanup),
12451
- invoke: (name3, args, options2) => {
12452
- const invocation = this.invoke(name3, args, options2, context, state, scope);
12464
+ invoke: (name3, args, options3) => {
12465
+ const invocation = this.invoke(name3, args, options3, context, state, scope);
12453
12466
  void invocation.catch(() => void 0);
12454
12467
  return invocation;
12455
12468
  }
@@ -12465,7 +12478,7 @@ var Runtime = class _Runtime {
12465
12478
  });
12466
12479
  return this.observeRuntimeReturn(raw, runtimeFrame, () => downstream);
12467
12480
  });
12468
- const execute2 = composeMiddleware(middleware, (forwarded) => scope.run(async () => {
12481
+ const execute3 = composeMiddleware(middleware, (forwarded) => scope.run(async () => {
12469
12482
  scope.assertOpen();
12470
12483
  const forwardedValues = getCommandArguments(forwarded);
12471
12484
  const admitted = forwardedValues === argumentValues ? argumentValues : this.admitArguments(forwardedValues.values, allocation);
@@ -12678,7 +12691,7 @@ var Runtime = class _Runtime {
12678
12691
  }
12679
12692
  }));
12680
12693
  try {
12681
- return validateExitCode((await interruptible(execute2(context), this.signal)).exitCode);
12694
+ return validateExitCode((await interruptible(execute3(context), this.signal)).exitCode);
12682
12695
  } catch (error) {
12683
12696
  if (builtinFailure && error === builtinFailure.error) throw new ExecutionFailure(error, io, builtinFailure.diagnostic);
12684
12697
  if (runtimeFrame.report && Object.is(runtimeFrame.report.origin.signal.reason, error) && this.outcomeFrame) {
@@ -12812,10 +12825,10 @@ ${functionDisplay(name2, state.functions.get(name2))}`;
12812
12825
  const target = component === void 0 ? name2 : `${component || "."}${component?.endsWith("/") ? "" : "/"}${name2}`;
12813
12826
  const resolved = resolvePath(state.cwd, target);
12814
12827
  try {
12815
- const options2 = { signal: this.signal };
12816
- if ((await interruptible(this.fs.stat(resolved, options2), this.signal)).type !== "file") continue;
12828
+ const options3 = { signal: this.signal };
12829
+ if ((await interruptible(this.fs.stat(resolved, options3), this.signal)).type !== "file") continue;
12817
12830
  if (this.fs.capabilities.permissions !== true) throw new CommandFailure(`${target}: execution permissions are not supported by this filesystem`, 126);
12818
- await interruptible(this.fs.access(resolved, ACCESS_MODES.X_OK, options2), this.signal);
12831
+ await interruptible(this.fs.access(resolved, ACCESS_MODES.X_OK, options3), this.signal);
12819
12832
  matches.push(target);
12820
12833
  if (!all) return matches;
12821
12834
  } catch (error) {
@@ -13039,8 +13052,8 @@ ${prefix2} line ${offset + line}: \`${source.split("\n")[line - 1] ?? ""}'
13039
13052
  stderr: this.budget.sink(incoming.stderr, runtime.signal),
13040
13053
  signal: this.commandSignal,
13041
13054
  registerCleanup: (cleanup) => scope.register(cleanup),
13042
- invoke: (name2, args, options2) => {
13043
- const invocation = invocationOverride.current ? invocationOverride.current(name2, args, options2) : runtime.invoke(name2, args, options2, context, child, scope);
13055
+ invoke: (name2, args, options3) => {
13056
+ const invocation = invocationOverride.current ? invocationOverride.current(name2, args, options3) : runtime.invoke(name2, args, options3, context, child, scope);
13044
13057
  void invocation.catch(() => void 0);
13045
13058
  return invocation;
13046
13059
  }
@@ -13060,7 +13073,7 @@ ${prefix2} line ${offset + line}: \`${source.split("\n")[line - 1] ?? ""}'
13060
13073
  });
13061
13074
  return runtime.observeRuntimeReturn(raw, runtimeFrame, () => downstream);
13062
13075
  });
13063
- const execute2 = composeMiddleware(middleware, async () => {
13076
+ const execute3 = composeMiddleware(middleware, async () => {
13064
13077
  scope.assertOpen();
13065
13078
  const forwardedValues = getCommandArguments(context);
13066
13079
  const admitted = forwardedValues === argumentValues ? argumentValues : runtime.admitArguments(forwardedValues.values, allocation);
@@ -13071,7 +13084,7 @@ ${prefix2} line ${offset + line}: \`${source.split("\n")[line - 1] ?? ""}'
13071
13084
  return await runtime.observeRuntimeReturn(raw, runtimeFrame);
13072
13085
  });
13073
13086
  try {
13074
- const result = await interruptible(execute2(context), runtime.signal);
13087
+ const result = await interruptible(execute3(context), runtime.signal);
13075
13088
  runtime.signal.throwIfAborted();
13076
13089
  return validateExitCode(result.exitCode);
13077
13090
  } catch (error) {
@@ -13084,8 +13097,8 @@ ${prefix2} line ${offset + line}: \`${source.split("\n")[line - 1] ?? ""}'
13084
13097
  if (ownsScope) await scope.close();
13085
13098
  }
13086
13099
  }
13087
- shebangTarget(context, state, io, command2, args, options2, target, loadedSource) {
13088
- return this.invokeChild(options2, state, io[invocationScope], () => {
13100
+ shebangTarget(context, state, io, command2, args, options3, target, loadedSource) {
13101
+ return this.invokeChild(options3, state, io[invocationScope], () => {
13089
13102
  this.signal.throwIfAborted();
13090
13103
  io[invocationScope].assertOpen();
13091
13104
  if (typeof command2 !== "string" || command2.includes("\0") || !Array.isArray(args) || args.some((argument) => typeof argument !== "string" || argument.includes("\0"))) {
@@ -13096,14 +13109,14 @@ ${prefix2} line ${offset + line}: \`${source.split("\n")[line - 1] ?? ""}'
13096
13109
  for (const argument of [command2, ...args]) {
13097
13110
  if (import_buffer.Buffer.byteLength(argument) > this.budget.limits.maxExpansionBytes) this.budget.fail("maxExpansionBytes");
13098
13111
  }
13099
- }, (runtime, scope) => runtime.shebangTargetScoped(context, state, io, command2, args, options2, target, loadedSource, scope));
13112
+ }, (runtime, scope) => runtime.shebangTargetScoped(context, state, io, command2, args, options3, target, loadedSource, scope));
13100
13113
  }
13101
- async shebangTargetScoped(context, state, io, command2, args, options2, target, loadedSource, scope) {
13114
+ async shebangTargetScoped(context, state, io, command2, args, options3, target, loadedSource, scope) {
13102
13115
  const reserved = command2 === "bash" || command2 === "sh";
13103
13116
  const direct = command2.includes("/");
13104
13117
  const definition = this.commands.get(command2);
13105
13118
  const child = await this.shebangState(context, state);
13106
- child.cwd = resolvePath(context.cwd, options2.cwd ?? ".");
13119
+ child.cwd = resolvePath(context.cwd, options3.cwd ?? ".");
13107
13120
  if (!reserved) {
13108
13121
  if (child.depth >= this.budget.limits.maxSubstitutionDepth) this.budget.fail("maxSubstitutionDepth");
13109
13122
  child.depth++;
@@ -13112,18 +13125,18 @@ ${prefix2} line ${offset + line}: \`${source.split("\n")[line - 1] ?? ""}'
13112
13125
  child.sourceDepth = 0;
13113
13126
  child.locals = [];
13114
13127
  }
13115
- const stdinIsDefault = options2.stdin === void 0 ? context.stdinIsDefault : options2.stdinIsDefault ?? false;
13116
- const argumentValues = getCommandArguments({ args, ...options2.argumentValues ? { argumentValues: options2.argumentValues } : {} });
13128
+ const stdinIsDefault = options3.stdin === void 0 ? context.stdinIsDefault : options3.stdinIsDefault ?? false;
13129
+ const argumentValues = getCommandArguments({ args, ...options3.argumentValues ? { argumentValues: options3.argumentValues } : {} });
13117
13130
  const selected = {
13118
13131
  ...context,
13119
13132
  command: command2,
13120
13133
  args: argumentValues.args,
13121
13134
  argumentValues,
13122
13135
  cwd: child.cwd,
13123
- env: options2.replaceEnv ? { ...options2.env } : { ...context.env, ...options2.env, PWD: child.cwd },
13124
- stdin: options2.stdin ?? context.stdin,
13125
- stdout: options2.stdout ?? context.stdout,
13126
- stderr: options2.stderr ?? context.stderr,
13136
+ env: options3.replaceEnv ? { ...options3.env } : { ...context.env, ...options3.env, PWD: child.cwd },
13137
+ stdin: options3.stdin ?? context.stdin,
13138
+ stdout: options3.stdout ?? context.stdout,
13139
+ stderr: options3.stderr ?? context.stderr,
13127
13140
  ...stdinIsDefault === void 0 ? {} : { stdinIsDefault }
13128
13141
  };
13129
13142
  const exitCode = await this.shebangStage(selected, child, io, async (runtime, forwarded, state2, childIO) => {
@@ -13139,7 +13152,7 @@ ${prefix2} line ${offset + line}: \`${source.split("\n")[line - 1] ?? ""}'
13139
13152
  await writeText(forwarded.stderr, `env: ${command2}: command not found
13140
13153
  `);
13141
13154
  return { exitCode: 127 };
13142
- }, void 0, options2.stdin !== context.stdin ? options2.stdin : void 0, scope);
13155
+ }, void 0, options3.stdin !== context.stdin ? options3.stdin : void 0, scope);
13143
13156
  return { exitCode };
13144
13157
  }
13145
13158
  async envShebang(context, state, io, optionalArgument, target, args, loadedSource) {
@@ -13160,8 +13173,8 @@ ${prefix2} line ${offset + line}: \`${source.split("\n")[line - 1] ?? ""}'
13160
13173
  let failureReport;
13161
13174
  const result = await interruptible(Promise.resolve(definition.execute({
13162
13175
  ...forwarded,
13163
- invoke: (command2, arguments_, options2) => {
13164
- const raw = forwarded.invoke(command2, arguments_, options2);
13176
+ invoke: (command2, arguments_, options3) => {
13177
+ const raw = forwarded.invoke(command2, arguments_, options3);
13165
13178
  return raw.catch((error) => {
13166
13179
  failed = true;
13167
13180
  failure = error;
@@ -13176,7 +13189,7 @@ ${prefix2} line ${offset + line}: \`${source.split("\n")[line - 1] ?? ""}'
13176
13189
  throw failure;
13177
13190
  }
13178
13191
  return { exitCode: validateExitCode(result.exitCode) };
13179
- }, (runtime, forwarded, child, childIO) => (command2, arguments_, options2 = {}) => runtime.shebangTarget(forwarded, child, childIO, command2, arguments_, options2, target, loadedSource));
13192
+ }, (runtime, forwarded, child, childIO) => (command2, arguments_, options3 = {}) => runtime.shebangTarget(forwarded, child, childIO, command2, arguments_, options3, target, loadedSource));
13180
13193
  }
13181
13194
  async scriptFile(context, state, io, target, args, direct, errexit = false, loadedSource) {
13182
13195
  if (target === "") throw new CommandFailure(`${context.command}: : No such file or directory`, 127);
@@ -13188,14 +13201,14 @@ ${prefix2} line ${offset + line}: \`${source.split("\n")[line - 1] ?? ""}'
13188
13201
  try {
13189
13202
  if (loadedSource?.path === path) source = loadedSource.source;
13190
13203
  else {
13191
- const options2 = { signal: this.signal };
13192
- const stat = await interruptible(this.fs.stat(path, options2), this.signal);
13204
+ const options3 = { signal: this.signal };
13205
+ const stat = await interruptible(this.fs.stat(path, options3), this.signal);
13193
13206
  if (stat.type !== "file") throw new CommandFailure(`${target}: ${stat.type === "directory" ? "Is a directory" : "not a regular file"}`, 126);
13194
13207
  if (direct && this.fs.capabilities.permissions !== true) throw new CommandFailure(`${target}: execution permissions are not supported by this filesystem`, 126);
13195
- await interruptible(this.fs.access(path, ACCESS_MODES.R_OK | (direct ? ACCESS_MODES.X_OK : 0), options2), this.signal);
13208
+ await interruptible(this.fs.access(path, ACCESS_MODES.R_OK | (direct ? ACCESS_MODES.X_OK : 0), options3), this.signal);
13196
13209
  const maxBytes = this.budget.limits.maxSourceBytes - this.budget.sourceBytes;
13197
13210
  if (stat.size > maxBytes) this.budget.fail("maxSourceBytes");
13198
- const bytes2 = await interruptible(this.fs.readFile(path, { ...options2, maxBytes }), this.signal);
13211
+ const bytes2 = await interruptible(this.fs.readFile(path, { ...options3, maxBytes }), this.signal);
13199
13212
  this.budget.source(bytes2.byteLength);
13200
13213
  source = this.sourceText(bytes2, target);
13201
13214
  }
@@ -13322,7 +13335,7 @@ ${prefix2} line ${offset + line}: \`${source.split("\n")[line - 1] ?? ""}'
13322
13335
  let target = filename;
13323
13336
  let source;
13324
13337
  try {
13325
- const options2 = { signal: this.signal };
13338
+ const options3 = { signal: this.signal };
13326
13339
  if (filename && !filename.includes("/") && state.variables.PATH) {
13327
13340
  if (import_buffer.Buffer.byteLength(state.variables.PATH) > this.budget.limits.maxExpansionBytes) this.budget.fail("maxExpansionBytes");
13328
13341
  const components = state.variables.PATH.split(":");
@@ -13333,8 +13346,8 @@ ${prefix2} line ${offset + line}: \`${source.split("\n")[line - 1] ?? ""}'
13333
13346
  const candidate = `${component || "."}${component.endsWith("/") ? "" : "/"}${filename}`;
13334
13347
  const path2 = resolvePath(state.cwd, candidate);
13335
13348
  try {
13336
- if ((await interruptible(this.fs.stat(path2, options2), this.signal)).type !== "file") continue;
13337
- await interruptible(this.fs.access(path2, ACCESS_MODES.R_OK, options2), this.signal);
13349
+ if ((await interruptible(this.fs.stat(path2, options3), this.signal)).type !== "file") continue;
13350
+ await interruptible(this.fs.access(path2, ACCESS_MODES.R_OK, options3), this.signal);
13338
13351
  target = candidate;
13339
13352
  found = true;
13340
13353
  break;
@@ -13347,13 +13360,13 @@ ${prefix2} line ${offset + line}: \`${source.split("\n")[line - 1] ?? ""}'
13347
13360
  }
13348
13361
  if (!filename) throw new CommandFailure(": No such file or directory", 1);
13349
13362
  const path = resolvePath(state.cwd, target);
13350
- const stat = await interruptible(this.fs.stat(path, options2), this.signal);
13363
+ const stat = await interruptible(this.fs.stat(path, options3), this.signal);
13351
13364
  if (stat.type === "directory") throw new CommandFailure(`${context.command}: ${target}: is a directory`, 1);
13352
13365
  if (stat.type !== "file") throw new CommandFailure(`${target}: not a regular file`, 1);
13353
- await interruptible(this.fs.access(path, ACCESS_MODES.R_OK, options2), this.signal);
13366
+ await interruptible(this.fs.access(path, ACCESS_MODES.R_OK, options3), this.signal);
13354
13367
  const maxBytes = this.budget.limits.maxSourceBytes - this.budget.sourceBytes;
13355
13368
  if (stat.size > maxBytes) this.budget.fail("maxSourceBytes");
13356
- const bytes2 = await interruptible(this.fs.readFile(path, { ...options2, maxBytes }), this.signal);
13369
+ const bytes2 = await interruptible(this.fs.readFile(path, { ...options3, maxBytes }), this.signal);
13357
13370
  this.budget.source(bytes2.byteLength);
13358
13371
  source = this.sourceText(bytes2, target);
13359
13372
  } catch (error) {
@@ -13418,22 +13431,22 @@ ${prefix2} line ${offset + line}: \`${source.split("\n")[line - 1] ?? ""}'
13418
13431
  }
13419
13432
  }
13420
13433
  }
13421
- invoke(name2, args, options2 = {}, context, state, parent) {
13422
- return this.invokeChild(options2, state, parent, () => {
13434
+ invoke(name2, args, options3 = {}, context, state, parent) {
13435
+ return this.invokeChild(options3, state, parent, () => {
13423
13436
  if (typeof name2 !== "string" || name2.includes("\0") || !Array.isArray(args) || args.some((arg) => typeof arg !== "string" || arg.includes("\0"))) {
13424
13437
  throw new TypeError("invoke requires a command and literal string arguments without NUL");
13425
13438
  }
13426
13439
  if (state.depth >= this.budget.limits.maxSubstitutionDepth) this.budget.fail("maxSubstitutionDepth");
13427
- }, (runtime, scope) => runtime.invokeScoped(name2, args, options2, context, state, scope));
13440
+ }, (runtime, scope) => runtime.invokeScoped(name2, args, options3, context, state, scope));
13428
13441
  }
13429
- async invokeScoped(name2, args, options2, context, state, scope) {
13442
+ async invokeScoped(name2, args, options3, context, state, scope) {
13430
13443
  this.signal.throwIfAborted();
13431
13444
  const allocation = this.budget.values.scope();
13432
13445
  scope.register(() => allocation.close());
13433
- const carrier = this.admitArguments(getCommandArguments({ args, ...options2.argumentValues ? { argumentValues: options2.argumentValues } : {} }).values, allocation);
13446
+ const carrier = this.admitArguments(getCommandArguments({ args, ...options3.argumentValues ? { argumentValues: options3.argumentValues } : {} }).values, allocation);
13434
13447
  const child = await cloneState(state, this.signal);
13435
- child.cwd = resolvePath(context.cwd, options2.cwd ?? ".");
13436
- const env = options2.replaceEnv ? { ...options2.env } : { ...context.env, ...options2.env, PWD: child.cwd };
13448
+ child.cwd = resolvePath(context.cwd, options3.cwd ?? ".");
13449
+ const env = options3.replaceEnv ? { ...options3.env } : { ...context.env, ...options3.env, PWD: child.cwd };
13437
13450
  if (guestArrays(child) || Object.keys(env).some((key) => arrayStore(child)?.get(key))) await this.indexedEnvironment(child, env);
13438
13451
  else {
13439
13452
  for (const key of child.exported) delete child.variables[key];
@@ -13449,15 +13462,15 @@ ${prefix2} line ${offset + line}: \`${source.split("\n")[line - 1] ?? ""}'
13449
13462
  child.functionDepth = 0;
13450
13463
  child.sourceDepth = 0;
13451
13464
  child.locals = [];
13452
- const input3 = options2.stdin === void 0 ? void 0 : new ShellInput(options2.stdin, this.budget, this.signal);
13453
- const stdinIsDefault = options2.stdin === void 0 ? context.stdinIsDefault : options2.stdinIsDefault ?? false;
13465
+ const input3 = options3.stdin === void 0 ? void 0 : new ShellInput(options3.stdin, this.budget, this.signal);
13466
+ const stdinIsDefault = options3.stdin === void 0 ? context.stdinIsDefault : options3.stdinIsDefault ?? false;
13454
13467
  const io = {
13455
13468
  ...context,
13456
13469
  [invocationScope]: scope,
13457
13470
  stdin: input3 ?? context.stdin,
13458
13471
  ...stdinIsDefault === void 0 ? {} : { stdinIsDefault },
13459
- stdout: options2.stdout ? this.budget.sink(options2.stdout, this.signal) : context.stdout,
13460
- stderr: options2.stderr ? this.budget.sink(options2.stderr, this.signal) : context.stderr
13472
+ stdout: options3.stdout ? this.budget.sink(options3.stdout, this.signal) : context.stdout,
13473
+ stderr: options3.stderr ? this.budget.sink(options3.stderr, this.signal) : context.stderr
13461
13474
  };
13462
13475
  const command2 = {
13463
13476
  kind: "simple",
@@ -13505,8 +13518,8 @@ ${prefix2} line ${offset + line}: \`${source.split("\n")[line - 1] ?? ""}'
13505
13518
  else if (flag === "o" && position === option.length - 1) {
13506
13519
  const name2 = args[index + 1];
13507
13520
  if (name2 === void 0) {
13508
- const options2 = [["errexit", !!state.errexit], ["nounset", !!state.nounset], ["pipefail", state.pipefail]];
13509
- for (const [name3, active] of options2) await writeText(stdout, enabled ? `${name3} ${active ? "on" : "off"}
13521
+ const options3 = [["errexit", !!state.errexit], ["nounset", !!state.nounset], ["pipefail", state.pipefail]];
13522
+ for (const [name3, active] of options3) await writeText(stdout, enabled ? `${name3} ${active ? "on" : "off"}
13510
13523
  ` : `set ${active ? "-" : "+"}o ${name3}
13511
13524
  `);
13512
13525
  } else {
@@ -13537,7 +13550,7 @@ ${prefix2} line ${offset + line}: \`${source.split("\n")[line - 1] ?? ""}'
13537
13550
  async letBuiltin(context, state) {
13538
13551
  this.signal.throwIfAborted();
13539
13552
  const { maxExpansionBytes: bytes2, maxExpansionFields: fields } = this.budget.limits;
13540
- const admit = (value3) => {
13553
+ const admit2 = (value3) => {
13541
13554
  if (typeof value3 !== "string" || value3.includes("\0")) throw new CommandFailure("let: arguments must be strings without NUL", 2);
13542
13555
  if (value3.length > bytes2 || import_buffer.Buffer.byteLength(value3) > bytes2) this.budget.fail("maxExpansionBytes");
13543
13556
  };
@@ -13549,10 +13562,10 @@ ${prefix2} line ${offset + line}: \`${source.split("\n")[line - 1] ?? ""}'
13549
13562
  const { args } = context;
13550
13563
  if (!Array.isArray(args)) throw new CommandFailure("let: argument array required", 2);
13551
13564
  if (args.length + 1 > fields) this.budget.fail("maxExpansionFields");
13552
- admit(context.command);
13565
+ admit2(context.command);
13553
13566
  for (let index = 0; index < args.length; index++) {
13554
13567
  this.signal.throwIfAborted();
13555
- admit(args[index]);
13568
+ admit2(args[index]);
13556
13569
  if ((index + 1) % 128 === 0) await checkpoint();
13557
13570
  }
13558
13571
  if (args[0] === "--help") throw new CommandFailure("let: --help: unsupported option", 2);
@@ -13581,7 +13594,7 @@ ${prefix2} line ${offset + line}: \`${source.split("\n")[line - 1] ?? ""}'
13581
13594
  async getoptsBuiltin(context, state) {
13582
13595
  this.signal.throwIfAborted();
13583
13596
  const { maxExpansionBytes: bytes2, maxExpansionFields: fields } = this.budget.limits;
13584
- const admit = (value2) => {
13597
+ const admit2 = (value2) => {
13585
13598
  if (typeof value2 !== "string") throw new CommandFailure("getopts: arguments must be strings without NUL", 2);
13586
13599
  if (value2.length > bytes2 || import_buffer.Buffer.byteLength(value2) > bytes2) this.budget.fail("maxExpansionBytes");
13587
13600
  if (value2.includes("\0")) throw new CommandFailure("getopts: arguments must be strings without NUL", 2);
@@ -13593,10 +13606,10 @@ ${prefix2} line ${offset + line}: \`${source.split("\n")[line - 1] ?? ""}'
13593
13606
  };
13594
13607
  if (!Array.isArray(context.args)) throw new CommandFailure("getopts: argument array required", 2);
13595
13608
  if (context.args.length + 1 > fields) this.budget.fail("maxExpansionFields");
13596
- admit(context.command);
13609
+ admit2(context.command);
13597
13610
  for (let index = 0; index < context.args.length; index++) {
13598
13611
  this.signal.throwIfAborted();
13599
- admit(context.args[index]);
13612
+ admit2(context.args[index]);
13600
13613
  if ((index + 1) % 128 === 0) await checkpoint();
13601
13614
  }
13602
13615
  const offset = context.args[0] === "--" ? 1 : 0;
@@ -13615,7 +13628,7 @@ ${prefix2} line ${offset + line}: \`${source.split("\n")[line - 1] ?? ""}'
13615
13628
  if (args.length > fields) this.budget.fail("maxExpansionFields");
13616
13629
  for (let index = 0; index < args.length; index++) {
13617
13630
  this.signal.throwIfAborted();
13618
- admit(args[index]);
13631
+ admit2(args[index]);
13619
13632
  if ((index + 1) % 128 === 0) await checkpoint();
13620
13633
  }
13621
13634
  const maxBytes = saturatedProduct(bytes2, saturatedSum(args.length, 1));
@@ -13976,14 +13989,14 @@ ${prefix2} line ${offset + line}: \`${source.split("\n")[line - 1] ?? ""}'
13976
13989
  const declarationArgs = [...args];
13977
13990
  let indexedLocal = false;
13978
13991
  if (command2 === "local") {
13979
- const options2 = localDeclarationOptions(declarationArgs, this.signal);
13980
- if (options2.error !== void 0) {
13981
- await writeText(stderr, `local: ${options2.error}: unsupported option
13992
+ const options3 = localDeclarationOptions(declarationArgs, this.signal);
13993
+ if (options3.error !== void 0) {
13994
+ await writeText(stderr, `local: ${options3.error}: unsupported option
13982
13995
  `);
13983
13996
  return 2;
13984
13997
  }
13985
- indexedLocal = options2.indexed;
13986
- declarationArgs.splice(0, options2.offset);
13998
+ indexedLocal = options3.indexed;
13999
+ declarationArgs.splice(0, options3.offset);
13987
14000
  if (indexedLocal && declarationArgs.length === 0) {
13988
14001
  await writeText(stderr, "local: -a requires a variable name\n");
13989
14002
  return 2;
@@ -15178,15 +15191,15 @@ var ShellInput = class _ShellInput {
15178
15191
  return bytes2;
15179
15192
  });
15180
15193
  }
15181
- line(raw, options2) {
15182
- return this.#cursor.consume(this.signal, () => options2 ? this.readBounded(raw, options2) : this.readLine(raw));
15194
+ line(raw, options3) {
15195
+ return this.#cursor.consume(this.signal, () => options3 ? this.readBounded(raw, options3) : this.readLine(raw));
15183
15196
  }
15184
- async readBounded(raw, options2) {
15197
+ async readBounded(raw, options3) {
15185
15198
  const text = new ReadText();
15186
15199
  let characters = 0;
15187
15200
  const escaped = /* @__PURE__ */ new Set();
15188
15201
  const decoder3 = new TextDecoder("utf-8", { fatal: true });
15189
- const delimiter = options2.delimiter ?? 10;
15202
+ const delimiter = options3.delimiter ?? 10;
15190
15203
  let chunk = new Uint8Array();
15191
15204
  let offset = 0;
15192
15205
  let length = 0;
@@ -15194,7 +15207,7 @@ var ShellInput = class _ShellInput {
15194
15207
  let escapedCharacter = false;
15195
15208
  let units = 0;
15196
15209
  let pulls = 0;
15197
- let terminated = options2.count === 0;
15210
+ let terminated = options3.count === 0;
15198
15211
  try {
15199
15212
  while (!terminated) {
15200
15213
  if (offset === chunk.length) {
@@ -15208,7 +15221,7 @@ var ShellInput = class _ShellInput {
15208
15221
  if (!chunk.length) continue;
15209
15222
  }
15210
15223
  const byte = chunk[offset++];
15211
- if (!options2.exact && !escaping && byte === delimiter) {
15224
+ if (!options3.exact && !escaping && byte === delimiter) {
15212
15225
  terminated = true;
15213
15226
  break;
15214
15227
  }
@@ -15238,8 +15251,8 @@ var ShellInput = class _ShellInput {
15238
15251
  characters++;
15239
15252
  decodedCharacters++;
15240
15253
  }
15241
- units += options2.byteCount ? 1 : decodedCharacters;
15242
- if (units === options2.count) terminated = true;
15254
+ units += options3.byteCount ? 1 : decodedCharacters;
15255
+ if (units === options3.count) terminated = true;
15243
15256
  }
15244
15257
  decoder3.decode();
15245
15258
  return { value: text.finish(), escaped, terminated };
@@ -15349,7 +15362,7 @@ var RootInvocationCancellationOwner = class {
15349
15362
  assertAdmissionOpen() {
15350
15363
  if (!this.#admissionOpen) throw new Error("Root cancellation admission is closed");
15351
15364
  }
15352
- capture(execute2) {
15365
+ capture(execute3) {
15353
15366
  return new Promise((resolve) => {
15354
15367
  let settled = false;
15355
15368
  let raw;
@@ -15371,7 +15384,7 @@ var RootInvocationCancellationOwner = class {
15371
15384
  });
15372
15385
  };
15373
15386
  try {
15374
- raw = Promise.resolve(execute2());
15387
+ raw = Promise.resolve(execute3());
15375
15388
  } catch (reason) {
15376
15389
  settle({ kind: "throw", reason });
15377
15390
  return;
@@ -15412,12 +15425,12 @@ var Shell = class {
15412
15425
  #disposed = false;
15413
15426
  #disposal;
15414
15427
  #active = /* @__PURE__ */ new Set();
15415
- constructor(options2) {
15416
- if (!options2?.fs) throw new TypeError("Shell requires an explicit filesystem");
15417
- warnIfHostProcessEnv(options2.env);
15418
- resolveLimits(options2.limits);
15419
- this.#options = { ...options2, cwd: resolvePath("/", options2.cwd ?? "/"), env: { ...options2.env }, limits: { ...options2.limits } };
15420
- this.commands = options2.commands ?? new CommandRegistry();
15428
+ constructor(options3) {
15429
+ if (!options3?.fs) throw new TypeError("Shell requires an explicit filesystem");
15430
+ warnIfHostProcessEnv(options3.env);
15431
+ resolveLimits(options3.limits);
15432
+ this.#options = { ...options3, cwd: resolvePath("/", options3.cwd ?? "/"), env: { ...options3.env }, limits: { ...options3.limits } };
15433
+ this.commands = options3.commands ?? new CommandRegistry();
15421
15434
  }
15422
15435
  use(middleware) {
15423
15436
  if (this.#disposed) throw new Error("Shell is disposed");
@@ -15430,17 +15443,17 @@ var Shell = class {
15430
15443
  if (!middleware || typeof middleware.setup !== "function") throw new TypeError("Expected middleware or shell plugin");
15431
15444
  this.#ready = this.#ready.then(async () => {
15432
15445
  let active = true;
15433
- const admit = () => {
15446
+ const admit2 = () => {
15434
15447
  if (this.#disposed && !active) throw new Error("Shell is disposed");
15435
15448
  };
15436
15449
  const host = {
15437
15450
  commands: this.commands,
15438
15451
  use: (middleware2) => {
15439
- admit();
15452
+ admit2();
15440
15453
  this.#install(middleware2);
15441
15454
  },
15442
15455
  registerFileSystem: (scheme, factory) => {
15443
- admit();
15456
+ admit2();
15444
15457
  this.#registerFileSystem(scheme, factory);
15445
15458
  }
15446
15459
  };
@@ -15454,9 +15467,9 @@ var Shell = class {
15454
15467
  void this.#ready.catch(() => void 0);
15455
15468
  }
15456
15469
  }
15457
- register(command2, options2) {
15470
+ register(command2, options3) {
15458
15471
  if (this.#disposed) throw new Error("Shell is disposed");
15459
- this.commands.register(command2, options2);
15472
+ this.commands.register(command2, options3);
15460
15473
  return this;
15461
15474
  }
15462
15475
  registerFileSystem(scheme, factory) {
@@ -15468,23 +15481,23 @@ var Shell = class {
15468
15481
  if (this.#filesystems.has(scheme)) throw new Error(`Filesystem already registered: ${scheme}`);
15469
15482
  this.#filesystems.set(scheme, factory);
15470
15483
  }
15471
- async createFileSystem(scheme, options2 = {}) {
15484
+ async createFileSystem(scheme, options3 = {}) {
15472
15485
  if (this.#disposed) throw new Error("Shell is disposed");
15473
15486
  await this.#ready;
15474
15487
  const factory = this.#filesystems.get(scheme);
15475
15488
  if (!factory) throw new Error(`Unknown filesystem scheme: ${scheme}`);
15476
- return factory(options2);
15489
+ return factory(options3);
15477
15490
  }
15478
- async exec(source, options2 = {}) {
15491
+ async exec(source, options3 = {}) {
15479
15492
  if (this.#disposed) throw new Error("Shell is disposed");
15480
- warnIfHostProcessEnv(options2.env);
15481
- const budget = new Budget(resolveLimits(this.#options.limits, options2.limits), options2.signal);
15482
- const scope = new InvocationScope(options2.signal);
15493
+ warnIfHostProcessEnv(options3.env);
15494
+ const budget = new Budget(resolveLimits(this.#options.limits, options3.limits), options3.signal);
15495
+ const scope = new InvocationScope(options3.signal);
15483
15496
  const cancellationState = new RuntimeCancellationState();
15484
15497
  const owner = new RootInvocationCancellationOwner(scope);
15485
15498
  const boundary = createRootCancellationLink({
15486
15499
  admission: Runtime.rootCancellationAdmission(budget),
15487
- callerSignal: options2.signal,
15500
+ callerSignal: options3.signal,
15488
15501
  controls: [{ role: "budget-control", signal: budget.controller.signal }]
15489
15502
  });
15490
15503
  try {
@@ -15499,7 +15512,7 @@ var Shell = class {
15499
15512
  this.#active.add(active);
15500
15513
  let captured;
15501
15514
  try {
15502
- captured = await owner.capture(() => this.#execute(source, options2, scope, budget, boundary, cancellationState, owner));
15515
+ captured = await owner.capture(() => this.#execute(source, options3, scope, budget, boundary, cancellationState, owner));
15503
15516
  } finally {
15504
15517
  budget.close();
15505
15518
  await scope.close();
@@ -15511,7 +15524,7 @@ var Shell = class {
15511
15524
  throwCleanupFailures(scope.failures);
15512
15525
  return selection.outcome.value;
15513
15526
  }
15514
- async #execute(source, options2, scope, budget, cancellation, cancellationState, owner) {
15527
+ async #execute(source, options3, scope, budget, cancellation, cancellationState, owner) {
15515
15528
  if (typeof source !== "string") throw new TypeError("Shell source must be a string");
15516
15529
  if (import_buffer.Buffer.byteLength(source) > budget.limits.maxSourceBytes) throw new ShellLimitError("maxSourceBytes");
15517
15530
  budget.source(import_buffer.Buffer.byteLength(source));
@@ -15535,20 +15548,20 @@ var Shell = class {
15535
15548
  const io = {
15536
15549
  [invocationScope]: scope,
15537
15550
  stdin: toByteSource(""),
15538
- stdinIsDefault: options2.stdin === void 0,
15539
- stdout: sink(stdout, options2.stdout),
15540
- stderr: sink(stderr, options2.stderr)
15551
+ stdinIsDefault: options3.stdin === void 0,
15552
+ stdout: sink(stdout, options3.stdout),
15553
+ stderr: sink(stderr, options3.stderr)
15541
15554
  };
15542
15555
  let exitCode;
15543
15556
  let failed = false;
15544
15557
  try {
15545
15558
  try {
15546
- let unit = parseShellUnit(source, 0, byteLocale({ ...this.#options.env, ...options2.env }));
15547
- stdin = new ShellInput(typeof options2.stdin === "string" || options2.stdin instanceof Uint8Array ? toByteSource(options2.stdin) : options2.stdin ?? toByteSource(""), budget);
15559
+ let unit = parseShellUnit(source, 0, byteLocale({ ...this.#options.env, ...options3.env }));
15560
+ stdin = new ShellInput(typeof options3.stdin === "string" || options3.stdin instanceof Uint8Array ? toByteSource(options3.stdin) : options3.stdin ?? toByteSource(""), budget);
15548
15561
  io.stdin = stdin;
15549
15562
  await interruptible(this.#ready, budget.signal);
15550
- const cwd = resolvePath("/", options2.cwd ?? this.#options.cwd ?? "/");
15551
- const variables = Object.assign(/* @__PURE__ */ Object.create(null), this.#options.env, options2.env, { PWD: cwd });
15563
+ const cwd = resolvePath("/", options3.cwd ?? this.#options.cwd ?? "/");
15564
+ const variables = Object.assign(/* @__PURE__ */ Object.create(null), this.#options.env, options3.env, { PWD: cwd });
15552
15565
  for (const [name2, value2] of Object.entries(variables)) {
15553
15566
  if (name2.includes("\0") || name2.includes("=") || typeof value2 !== "string" || value2.includes("\0")) throw new TypeError("Invalid environment entry");
15554
15567
  }
@@ -15575,7 +15588,7 @@ var Shell = class {
15575
15588
  };
15576
15589
  const admission = Runtime.rootCancellationAdmission(budget);
15577
15590
  const runtime = new Runtime(
15578
- options2.fs ?? this.#options.fs,
15591
+ options3.fs ?? this.#options.fs,
15579
15592
  this.commands,
15580
15593
  [...this.#middleware],
15581
15594
  budget,
@@ -15629,8 +15642,8 @@ shell: -c: line ${line}: \`${source.split("\n")[line - 1] ?? ""}'
15629
15642
  });
15630
15643
  else await stdin?.close();
15631
15644
  }
15632
- const stdoutBytes = stdout.bytes();
15633
- const stderrBytes = stderr.bytes();
15645
+ const stdoutBytes = stdout.takeBytes();
15646
+ const stderrBytes = stderr.takeBytes();
15634
15647
  return {
15635
15648
  stdout: new TextDecoder("utf-8", { ignoreBOM: true }).decode(stdoutBytes),
15636
15649
  stderr: new TextDecoder("utf-8", { ignoreBOM: true }).decode(stderrBytes),
@@ -15680,6 +15693,7 @@ var cloudflareWorkerLimits = Object.freeze({
15680
15693
  maxInputBytes: 4 * 1024 * 1024,
15681
15694
  maxOutputBytes: 4 * 1024 * 1024,
15682
15695
  maxCommands: 1e3,
15696
+ maxRedirects: 64,
15683
15697
  maxPipelineStages: 64,
15684
15698
  maxLoopIterations: 1e3,
15685
15699
  maxSubstitutionDepth: 16,
@@ -15761,8 +15775,8 @@ function requestBody(source, signal) {
15761
15775
  }
15762
15776
  });
15763
15777
  }
15764
- function createFetchTransport(options2 = {}) {
15765
- const fetchRequest = options2.fetch ?? globalThis.fetch;
15778
+ function createFetchTransport(options3 = {}) {
15779
+ const fetchRequest = options3.fetch ?? globalThis.fetch;
15766
15780
  if (typeof fetchRequest !== "function") throw new TypeError("Fetch is unavailable");
15767
15781
  return async (input3) => {
15768
15782
  input3.signal.throwIfAborted();
@@ -15829,7 +15843,7 @@ function privateHostname(input3) {
15829
15843
  const [first, second] = octets;
15830
15844
  return first === 10 || first === 127 || first === 0 || first === 169 && second === 254 || first === 192 && second === 168 || first === 172 && second >= 16 && second <= 31;
15831
15845
  }
15832
- function createOriginAuthorizer(allowlist = "*", options2 = {}) {
15846
+ function createOriginAuthorizer(allowlist = "*", options3 = {}) {
15833
15847
  const origins = /* @__PURE__ */ new Set();
15834
15848
  const hosts = /* @__PURE__ */ new Set();
15835
15849
  for (const entry of allowlist === "*" ? [] : allowlist) {
@@ -15849,7 +15863,7 @@ function createOriginAuthorizer(allowlist = "*", options2 = {}) {
15849
15863
  return (request) => {
15850
15864
  const url = new URL(request.url);
15851
15865
  const hostname = url.hostname.toLowerCase().replace(/\.$/u, "");
15852
- if (options2.denyPrivateNetworks && privateHostname(hostname)) return false;
15866
+ if (options3.denyPrivateNetworks && privateHostname(hostname)) return false;
15853
15867
  return allowlist === "*" || origins.has(url.origin) || hosts.has(hostname);
15854
15868
  };
15855
15869
  }
@@ -15899,25 +15913,25 @@ var ExprMatchError = class extends Error {
15899
15913
  function exactObject(value2, keys) {
15900
15914
  return value2 !== null && typeof value2 === "object" && !Array.isArray(value2) && Object.keys(value2).length === keys.length && keys.every((key) => Object.hasOwn(value2, key));
15901
15915
  }
15902
- function validateExprInput(descriptor, rows, signal) {
15916
+ function validateExprInput(descriptor2, rows, signal) {
15903
15917
  signal.throwIfAborted();
15904
15918
  const invalid = () => {
15905
15919
  throw new RegexExecutionError("PROTOCOL", "invalid expr request");
15906
15920
  };
15907
- if (!exactObject(descriptor, ["kind", "pattern", "profile", "limits"]) || descriptor.kind !== "expr-match" || !(descriptor.pattern instanceof Uint8Array) || !["byte", "utf8-scalar"].includes(descriptor.profile)) invalid();
15921
+ if (!exactObject(descriptor2, ["kind", "pattern", "profile", "limits"]) || descriptor2.kind !== "expr-match" || !(descriptor2.pattern instanceof Uint8Array) || !["byte", "utf8-scalar"].includes(descriptor2.profile)) invalid();
15908
15922
  const keys = Object.keys(exprMatchCeilings);
15909
- if (!exactObject(descriptor.limits, keys)) invalid();
15923
+ if (!exactObject(descriptor2.limits, keys)) invalid();
15910
15924
  for (const key of keys) {
15911
- if (!Number.isSafeInteger(descriptor.limits[key]) || descriptor.limits[key] < 1 || descriptor.limits[key] > exprMatchCeilings[key]) invalid();
15925
+ if (!Number.isSafeInteger(descriptor2.limits[key]) || descriptor2.limits[key] < 1 || descriptor2.limits[key] > exprMatchCeilings[key]) invalid();
15912
15926
  }
15913
15927
  if (!Array.isArray(rows) || rows.length !== 1) invalid();
15914
15928
  const row = rows[0];
15915
15929
  if (!exactObject(row, ["bytes", "all", "terminated"]) || !(row.bytes instanceof Uint8Array) || row.all !== false || row.terminated !== false) invalid();
15916
- if (descriptor.pattern.length > descriptor.limits.maxPatternBytes || row.bytes.length > descriptor.limits.maxSubjectBytes) {
15930
+ if (descriptor2.pattern.length > descriptor2.limits.maxPatternBytes || row.bytes.length > descriptor2.limits.maxSubjectBytes) {
15917
15931
  throw new ExprMatchError("limit", "regex input bytes limit exceeded");
15918
15932
  }
15919
15933
  }
15920
- function validateExprReply(value2, id, descriptor, subject, signal) {
15934
+ function validateExprReply(value2, id, descriptor2, subject, signal) {
15921
15935
  signal.throwIfAborted();
15922
15936
  const invalid = () => {
15923
15937
  throw new RegexExecutionError("PROTOCOL", "invalid expr reply");
@@ -15931,13 +15945,13 @@ function validateExprReply(value2, id, descriptor, subject, signal) {
15931
15945
  }
15932
15946
  if (!exactObject(reply, ["id", "operation", "result"])) return invalid();
15933
15947
  const result = reply.result;
15934
- if (!exactObject(result, ["offsetUnit", "matched", "hasCapture", "overall", "capture", "steps"]) || result.offsetUnit !== "byte" || typeof result.matched !== "boolean" || typeof result.hasCapture !== "boolean" || !Number.isSafeInteger(result.steps) || result.steps < 1 || result.steps > descriptor.limits.maxSteps) return invalid();
15948
+ if (!exactObject(result, ["offsetUnit", "matched", "hasCapture", "overall", "capture", "steps"]) || result.offsetUnit !== "byte" || typeof result.matched !== "boolean" || typeof result.hasCapture !== "boolean" || !Number.isSafeInteger(result.steps) || result.steps < 1 || result.steps > descriptor2.limits.maxSteps) return invalid();
15935
15949
  const span = (value3) => {
15936
15950
  if (value3 === null) return null;
15937
15951
  if (!exactObject(value3, ["start", "end"]) || !Number.isSafeInteger(value3.start) || !Number.isSafeInteger(value3.end)) return invalid();
15938
15952
  const start = value3.start, end = value3.end;
15939
15953
  if (start < 0 || end < start || end > subject.length) return invalid();
15940
- if (descriptor.profile === "utf8-scalar") {
15954
+ if (descriptor2.profile === "utf8-scalar") {
15941
15955
  for (const offset of [start, end]) if (offset < subject.length && subject[offset] >= 128 && subject[offset] <= 191) return invalid();
15942
15956
  }
15943
15957
  return { start, end };
@@ -15946,8 +15960,8 @@ function validateExprReply(value2, id, descriptor, subject, signal) {
15946
15960
  if (result.matched !== (overall !== null) || overall && overall.start !== 0 || capture && (!result.hasCapture || !overall || capture.start < overall.start || capture.end > overall.end)) return invalid();
15947
15961
  return { offsetUnit: "byte", matched: result.matched, hasCapture: result.hasCapture, overall, capture, steps: result.steps };
15948
15962
  }
15949
- function policy(options2) {
15950
- const result = { ...defaults, ...options2 };
15963
+ function policy(options3) {
15964
+ const result = { ...defaults, ...options3 };
15951
15965
  for (const key of Object.keys(defaults)) {
15952
15966
  const minimum = key === "maxQueuedRequests" || key === "maxQueuedBytes" ? 0 : 1;
15953
15967
  if (!Number.isSafeInteger(result[key]) || result[key] < minimum) throw new RangeError(`regex ${key} must be a safe integer >= ${minimum}`);
@@ -15957,9 +15971,9 @@ function policy(options2) {
15957
15971
  }
15958
15972
  return Object.freeze(result);
15959
15973
  }
15960
- function inputBytes(descriptor, rows, signal) {
15961
- let total = 128 + (descriptor.kind === "glob" ? descriptor.globOptions.length * 32 : 0);
15962
- for (const pattern of descriptor.patterns) {
15974
+ function inputBytes(descriptor2, rows, signal) {
15975
+ let total = 128 + (descriptor2.kind === "glob" ? descriptor2.globOptions.length * 32 : 0);
15976
+ for (const pattern of descriptor2.patterns) {
15963
15977
  signal.throwIfAborted();
15964
15978
  total += 16 + pattern.length * 2;
15965
15979
  if (!Number.isSafeInteger(total)) throw new RegexExecutionError("QUEUE_EXHAUSTED", "input accounting overflow");
@@ -16004,7 +16018,7 @@ async function awaitRetirements(retirements) {
16004
16018
  if (failures.length === 1) throw failures[0];
16005
16019
  if (failures.length > 1) throw new AggregateError(failures, "regex retirement failed");
16006
16020
  }
16007
- async function withRegexSession(context, executor, execute2) {
16021
+ async function withRegexSession(context, executor, execute3) {
16008
16022
  context.signal.throwIfAborted();
16009
16023
  let session;
16010
16024
  let closing;
@@ -16022,7 +16036,7 @@ async function withRegexSession(context, executor, execute2) {
16022
16036
  context.signal.throwIfAborted();
16023
16037
  if (closing) throw new RegexExecutionError("CLOSED", "invocation is closed");
16024
16038
  session = executor.open(context.signal);
16025
- outcome = { result: await execute2(session) };
16039
+ outcome = { result: await execute3(session) };
16026
16040
  } catch (error) {
16027
16041
  outcome = { error };
16028
16042
  }
@@ -16114,10 +16128,10 @@ var Slot = class {
16114
16128
  }
16115
16129
  };
16116
16130
  var RegexExecutor = class {
16117
- constructor(provider, options2 = defaults) {
16131
+ constructor(provider, options3 = defaults) {
16118
16132
  this.provider = provider;
16119
16133
  if (!provider || typeof provider.createWorker !== "function") throw new TypeError("a bounded regex provider is required");
16120
- this.options = policy(options2);
16134
+ this.options = policy(options3);
16121
16135
  }
16122
16136
  provider;
16123
16137
  options;
@@ -16152,21 +16166,21 @@ var RegexExecutor = class {
16152
16166
  this.slots.delete(slot);
16153
16167
  this.pump();
16154
16168
  }
16155
- request(descriptor, rows, signal, retirements = /* @__PURE__ */ new Set()) {
16169
+ request(descriptor2, rows, signal, retirements = /* @__PURE__ */ new Set()) {
16156
16170
  signal.throwIfAborted();
16157
16171
  if (this.disposed) return Promise.reject(new RegexExecutionError("CLOSED", "executor is disposed"));
16158
- if (descriptor.kind === "expr-match") validateExprInput(descriptor, rows, signal);
16159
- const bytes2 = descriptor.kind === "expr-match" ? 256 + descriptor.pattern.length + rows[0].bytes.length : inputBytes(descriptor, rows, signal);
16172
+ if (descriptor2.kind === "expr-match") validateExprInput(descriptor2, rows, signal);
16173
+ const bytes2 = descriptor2.kind === "expr-match" ? 256 + descriptor2.pattern.length + rows[0].bytes.length : inputBytes(descriptor2, rows, signal);
16160
16174
  const available = this.queue.length === 0 && ([...this.slots].some((slot) => !slot.busy && !slot.retired) || this.slots.size < this.options.maxWorkers);
16161
16175
  if (!available && (this.queue.length >= this.options.maxQueuedRequests || bytes2 > this.options.maxQueuedBytes - this.queuedBytes)) return Promise.reject(new RegexExecutionError("QUEUE_EXHAUSTED", "queued request count or input byte limit exceeded"));
16162
- const ownedDescriptor = descriptor.kind === "expr-match" ? { ...descriptor, pattern: Uint8Array.from(descriptor.pattern), limits: { ...descriptor.limits } } : { ...descriptor, patterns: descriptor.patterns.map((pattern) => {
16176
+ const ownedDescriptor = descriptor2.kind === "expr-match" ? { ...descriptor2, pattern: Uint8Array.from(descriptor2.pattern), limits: { ...descriptor2.limits } } : { ...descriptor2, patterns: descriptor2.patterns.map((pattern) => {
16163
16177
  signal.throwIfAborted();
16164
16178
  return pattern;
16165
16179
  }) };
16166
16180
  if (ownedDescriptor.kind === "glob") {
16167
- const globOptions = ownedDescriptor.globOptions.map((options2) => {
16181
+ const globOptions = ownedDescriptor.globOptions.map((options3) => {
16168
16182
  signal.throwIfAborted();
16169
- return { ...options2 };
16183
+ return { ...options3 };
16170
16184
  });
16171
16185
  Object.assign(ownedDescriptor, { globOptions });
16172
16186
  }
@@ -16284,18 +16298,18 @@ var RegexSession = class {
16284
16298
  retirements = /* @__PURE__ */ new Set();
16285
16299
  controller = new AbortController();
16286
16300
  requestSignal;
16287
- run(descriptor, rows) {
16301
+ run(descriptor2, rows) {
16288
16302
  this.signal.throwIfAborted();
16289
16303
  if (this.closed) throw new RegexExecutionError("CLOSED", "invocation is closed");
16290
- const result = this.executor.request(descriptor, rows, this.requestSignal, this.retirements);
16304
+ const result = this.executor.request(descriptor2, rows, this.requestSignal, this.retirements);
16291
16305
  this.pending.add(result);
16292
16306
  void result.then(() => this.pending.delete(result), () => this.pending.delete(result));
16293
16307
  return result;
16294
16308
  }
16295
- matchExpr(descriptor, subject) {
16309
+ matchExpr(descriptor2, subject) {
16296
16310
  this.signal.throwIfAborted();
16297
16311
  if (this.closed) throw new RegexExecutionError("CLOSED", "invocation is closed");
16298
- const result = this.executor.request(descriptor, [{ bytes: subject, all: false, terminated: false }], this.requestSignal, this.retirements);
16312
+ const result = this.executor.request(descriptor2, [{ bytes: subject, all: false, terminated: false }], this.requestSignal, this.retirements);
16299
16313
  this.pending.add(result);
16300
16314
  void result.then(() => this.pending.delete(result), () => this.pending.delete(result));
16301
16315
  return result;
@@ -16428,10 +16442,10 @@ async function* requiredFileInput(context, requirements, mode, file, maxBytes) {
16428
16442
  var ProgramError = class extends Error {
16429
16443
  };
16430
16444
  var Budget3 = class {
16431
- constructor(context, options2) {
16445
+ constructor(context, options3) {
16432
16446
  this.context = context;
16433
- this.remaining = options2.maxSteps ?? 5e6;
16434
- this.maxBufferBytes = options2.maxBufferBytes ?? 32 * 1024 * 1024;
16447
+ this.remaining = options3.maxSteps ?? 5e6;
16448
+ this.maxBufferBytes = options3.maxBufferBytes ?? 32 * 1024 * 1024;
16435
16449
  for (const value2 of [this.remaining, this.maxBufferBytes]) {
16436
16450
  if (!Number.isSafeInteger(value2) || value2 < 1) throw new ProgramError("limits must be positive safe integers");
16437
16451
  }
@@ -16440,6 +16454,7 @@ var Budget3 = class {
16440
16454
  maxBufferBytes;
16441
16455
  remaining;
16442
16456
  checkpoints = 0;
16457
+ lastYield = monotonicNow();
16443
16458
  step(count2 = 1) {
16444
16459
  this.context.signal.throwIfAborted();
16445
16460
  this.remaining -= count2;
@@ -16450,7 +16465,11 @@ var Budget3 = class {
16450
16465
  return text;
16451
16466
  }
16452
16467
  async checkpoint() {
16453
- if (++this.checkpoints % 256 === 0) await yieldTurn(this.context.signal);
16468
+ this.context.signal.throwIfAborted();
16469
+ if (++this.checkpoints % 256 === 0 || monotonicNow() - this.lastYield >= 25) {
16470
+ await yieldTurn(this.context.signal);
16471
+ this.lastYield = monotonicNow();
16472
+ }
16454
16473
  this.context.signal.throwIfAborted();
16455
16474
  }
16456
16475
  };
@@ -17048,10 +17067,10 @@ async function execute(program, context, files, quiet, budget) {
17048
17067
  following = void 0;
17049
17068
  return next;
17050
17069
  };
17051
- const prepareRecord = async (record3) => {
17052
- if (record3.terminated || files.length < 2) return record3;
17070
+ const prepareRecord = async (record4) => {
17071
+ if (record4.terminated || files.length < 2) return record4;
17053
17072
  const next = await peekNext();
17054
- return !next.done && next.value.fileIndex !== record3.fileIndex ? { ...record3, terminated: true } : record3;
17073
+ return !next.done && next.value.fileIndex !== record4.fileIndex ? { ...record4, terminated: true } : record4;
17055
17074
  };
17056
17075
  let number = 0;
17057
17076
  let hold = "";
@@ -17066,8 +17085,8 @@ async function execute(program, context, files, quiet, budget) {
17066
17085
  while (!current.done) {
17067
17086
  budget.step();
17068
17087
  number++;
17069
- let record3 = await prepareRecord(current.value);
17070
- let pattern = record3.text;
17088
+ let record4 = await prepareRecord(current.value);
17089
+ let pattern = record4.text;
17071
17090
  const appended = [];
17072
17091
  let appendedSize = 0;
17073
17092
  const append = (item) => {
@@ -17079,7 +17098,7 @@ async function execute(program, context, files, quiet, budget) {
17079
17098
  let deleted = false;
17080
17099
  let quit = false;
17081
17100
  let status = 0;
17082
- const print = () => write(context, pattern + (record3.terminated ? "\n" : ""));
17101
+ const print = () => write(context, pattern + (record4.terminated ? "\n" : ""));
17083
17102
  const flush = async () => {
17084
17103
  await assertPathRequirements(context, sedRequirements, ["script-read"], appended.flatMap((item) => item.file === void 0 ? [] : [item.file]));
17085
17104
  if (!quiet && !deleted) await print();
@@ -17140,7 +17159,7 @@ async function execute(program, context, files, quiet, budget) {
17140
17159
  break;
17141
17160
  case "P": {
17142
17161
  const end = pattern.indexOf("\n");
17143
- await write(context, end < 0 ? pattern + (record3.terminated ? "\n" : "") : pattern.slice(0, end + 1));
17162
+ await write(context, end < 0 ? pattern + (record4.terminated ? "\n" : "") : pattern.slice(0, end + 1));
17144
17163
  break;
17145
17164
  }
17146
17165
  case "=":
@@ -17230,9 +17249,16 @@ async function execute(program, context, files, quiet, budget) {
17230
17249
  }
17231
17250
  break;
17232
17251
  }
17233
- case "y":
17234
- pattern = [...pattern].map((character) => instruction.translation.get(character) ?? character).join("");
17252
+ case "y": {
17253
+ budget.step(pattern.length);
17254
+ const translated = import_buffer.Buffer.allocUnsafe(pattern.length);
17255
+ for (let index = 0; index < pattern.length; index++) {
17256
+ if (index % 256 === 0) await budget.checkpoint();
17257
+ translated[index] = (instruction.translation.get(pattern[index]) ?? pattern[index]).charCodeAt(0);
17258
+ }
17259
+ pattern = translated.toString("latin1");
17235
17260
  break;
17261
+ }
17236
17262
  case "b":
17237
17263
  pc = instruction.jump;
17238
17264
  continue;
@@ -17254,9 +17280,9 @@ async function execute(program, context, files, quiet, budget) {
17254
17280
  if (instruction.kind === "N") await flush();
17255
17281
  return { status: 0, quit: false };
17256
17282
  }
17257
- record3 = await prepareRecord(next.value);
17283
+ record4 = await prepareRecord(next.value);
17258
17284
  number++;
17259
- pattern = instruction.kind === "N" ? budget.check(pattern + "\n" + record3.text) : record3.text;
17285
+ pattern = instruction.kind === "N" ? budget.check(pattern + "\n" + record4.text) : record4.text;
17260
17286
  substituted = false;
17261
17287
  break;
17262
17288
  }
@@ -17272,9 +17298,9 @@ async function execute(program, context, files, quiet, budget) {
17272
17298
  await source.return(void 0);
17273
17299
  }
17274
17300
  }
17275
- function sedCommand(options2 = {}) {
17301
+ function sedCommand(options3 = {}) {
17276
17302
  const definition = command("sed", async (context) => {
17277
- const budget = new Budget3(context, options2);
17303
+ const budget = new Budget3(context, options3);
17278
17304
  const sources = [];
17279
17305
  const files = [];
17280
17306
  let quiet = false;
@@ -17370,6 +17396,7 @@ function sedCommand(options2 = {}) {
17370
17396
 
17371
17397
  // packages/safe-bash/src/commands/search/grep.ts
17372
17398
  init_platform();
17399
+ var maxPatternCount = 1024;
17373
17400
  function createGrepCommands(executor) {
17374
17401
  return [{ name: "grep", filesystemRequirements: grepRequirements, execute: (context) => withRegexSession(context, executor, async (session) => {
17375
17402
  try {
@@ -17382,20 +17409,46 @@ function createGrepCommands(executor) {
17382
17409
  const names = parsed.operands.length ? parsed.operands : ["-"];
17383
17410
  const patternFiles = parsed.values.get("f") ?? [];
17384
17411
  const patterns2 = [];
17385
- const addPatterns = (text, file) => {
17386
- if (file && text === "") return;
17387
- const parts = text.split("\n");
17388
- if (parts.length > 1 && parts.at(-1) === "") parts.pop();
17389
- patterns2.push(...parts);
17412
+ let patternCount = 0;
17413
+ let patternBytes = 0;
17414
+ const admit2 = (chunk, atStart) => {
17415
+ context.signal.throwIfAborted();
17416
+ const size = typeof chunk === "string" ? import_buffer.Buffer.byteLength(chunk) : chunk.length;
17417
+ if (size > bufferLimit - patternBytes) throw new UsageError(`pattern byte limit exceeded (${bufferLimit} bytes)`);
17418
+ patternBytes += size;
17419
+ for (let offset = 0; offset < chunk.length; ) {
17420
+ if (atStart && ++patternCount > maxPatternCount) throw new UsageError(`pattern count limit exceeded (${maxPatternCount})`);
17421
+ const newline = typeof chunk === "string" ? chunk.indexOf("\n", offset) : chunk.indexOf(10, offset);
17422
+ if (newline < 0) return false;
17423
+ offset = newline + 1;
17424
+ atStart = true;
17425
+ }
17426
+ return atStart;
17427
+ };
17428
+ const addArgument = async (pattern) => {
17429
+ admit2(pattern, true);
17430
+ if (pattern === "") {
17431
+ if (++patternCount > maxPatternCount) throw new UsageError(`pattern count limit exceeded (${maxPatternCount})`);
17432
+ patterns2.push("");
17433
+ } else {
17434
+ for await (const line of lines(toByteSource(pattern))) patterns2.push(import_buffer.Buffer.from(line.bytes).toString("latin1"));
17435
+ }
17390
17436
  };
17391
- for (const pattern of parsed.values.get("e") ?? []) addPatterns(import_buffer.Buffer.from(pattern).toString("latin1"), false);
17437
+ async function* admitted(source) {
17438
+ let atStart = true;
17439
+ for await (const chunk of source) {
17440
+ atStart = admit2(chunk, atStart);
17441
+ yield chunk;
17442
+ }
17443
+ }
17444
+ for (const pattern of parsed.values.get("e") ?? []) await addArgument(pattern);
17392
17445
  for (const name2 of patternFiles) {
17393
- const source = name2 === "-" ? input(context) : requiredFileInput(context, grepRequirements, "pattern-file", name2, bufferLimit);
17394
- addPatterns(import_buffer.Buffer.from(await collect(source, context.signal)).toString("latin1"), true);
17446
+ const source = name2 === "-" ? input(context) : requiredFileInput(context, grepRequirements, "pattern-file", name2, bufferLimit - patternBytes);
17447
+ for await (const line of lines(admitted(source))) patterns2.push(import_buffer.Buffer.from(line.bytes).toString("latin1"));
17395
17448
  }
17396
- if (positionalPattern !== void 0) addPatterns(import_buffer.Buffer.from(positionalPattern).toString("latin1"), false);
17449
+ if (positionalPattern !== void 0) await addArgument(positionalPattern);
17397
17450
  if (parsed.flags.has("E") && parsed.flags.has("F")) throw new UsageError("conflicting matchers specified");
17398
- const descriptor = {
17451
+ const descriptor2 = {
17399
17452
  kind: "grep",
17400
17453
  patterns: patterns2,
17401
17454
  fixed: parsed.flags.has("F"),
@@ -17404,7 +17457,7 @@ function createGrepCommands(executor) {
17404
17457
  whole: parsed.flags.has("x"),
17405
17458
  word: parsed.flags.has("w")
17406
17459
  };
17407
- await session.run(descriptor, []);
17460
+ await session.run(descriptor2, []);
17408
17461
  const maxCount = value(parsed, "m") === void 0 ? Infinity : integer(value(parsed, "m"));
17409
17462
  const batchSize = Number.isFinite(maxCount) || parsed.flags.has("q") || parsed.flags.has("l") || parsed.flags.has("L") ? 1 : 128;
17410
17463
  const delimiter = parsed.flags.has("z") ? "\0" : "\n";
@@ -17419,7 +17472,7 @@ function createGrepCommands(executor) {
17419
17472
  const available = new AvailableRecords(parsed.flags.has("z") ? 0 : 10, bufferLimit);
17420
17473
  const source = name2 === "-" ? input(context) : requiredFileInput(context, grepRequirements, "file", name2, bufferLimit);
17421
17474
  records: if (maxCount > 0) for await (const batch of available.batches(lines(available.source(source), parsed.flags.has("z") ? 0 : 10), (line) => line.bytes.length, () => batchSize)) {
17422
- const results = await session.run(descriptor, batch.map((line) => ({ bytes: line.bytes, all: parsed.flags.has("o"), terminated: line.terminated })));
17475
+ const results = await session.run(descriptor2, batch.map((line) => ({ bytes: line.bytes, all: parsed.flags.has("o"), terminated: line.terminated })));
17423
17476
  for (let index = 0; index < batch.length; index++) {
17424
17477
  const line = batch[index];
17425
17478
  context.signal.throwIfAborted();
@@ -17839,13 +17892,13 @@ function pathFor(context, path) {
17839
17892
  var OutputClosed = class extends SearchError {
17840
17893
  };
17841
17894
  var Limits = class {
17842
- constructor(context, options2) {
17895
+ constructor(context, options3) {
17843
17896
  this.context = context;
17844
17897
  this.signal = AbortSignal.any([context.signal, this.stopped.signal]);
17845
- this.maxOutputBytes = options2.maxOutputBytes ?? 16 * 1024 * 1024;
17846
- this.maxLineBytes = options2.maxLineBytes ?? 1024 * 1024;
17847
- this.maxFileBytes = options2.maxFileBytes ?? 64 * 1024 * 1024;
17848
- this.maxFiles = options2.maxFiles ?? 1e5;
17898
+ this.maxOutputBytes = options3.maxOutputBytes ?? 16 * 1024 * 1024;
17899
+ this.maxLineBytes = options3.maxLineBytes ?? 1024 * 1024;
17900
+ this.maxFileBytes = options3.maxFileBytes ?? 64 * 1024 * 1024;
17901
+ this.maxFiles = options3.maxFiles ?? 1e5;
17849
17902
  for (const limit of [this.maxOutputBytes, this.maxLineBytes, this.maxFileBytes, this.maxFiles]) {
17850
17903
  if (!Number.isSafeInteger(limit) || limit < 1) throw new SearchError("search limits must be positive safe integers");
17851
17904
  }
@@ -18030,13 +18083,13 @@ async function matchGlobs(globs, candidates, session) {
18030
18083
  bytes2 += size;
18031
18084
  offset++;
18032
18085
  }
18033
- const descriptor = {
18086
+ const descriptor2 = {
18034
18087
  kind: "glob",
18035
18088
  patterns: batch.map((glob) => glob.source),
18036
18089
  globOptions: batch.map((glob) => ({ insensitive: glob.insensitive, literalUnclosedClass: glob.literalUnclosedClass }))
18037
18090
  };
18038
18091
  try {
18039
- results.push(...(await session.run(descriptor, rows)).map((result) => result.length > 0));
18092
+ results.push(...(await session.run(descriptor2, rows)).map((result) => result.length > 0));
18040
18093
  } catch (error) {
18041
18094
  if (error instanceof RegexExecutionError && error.code === "MATCH") throw new SearchError(error.message);
18042
18095
  throw error;
@@ -18235,10 +18288,10 @@ var Walker = class {
18235
18288
  };
18236
18289
 
18237
18290
  // packages/safe-bash/src/commands/search/rg-command.ts
18238
- function selectInput(context, args, options2) {
18291
+ function selectInput(context, args, options3) {
18239
18292
  if (args.paths.length) return { paths: args.paths, implicit: false };
18240
- if (args.mode === "files" || options2.defaultInput === "cwd" || args.patternFiles.includes("-")) return { paths: ["."], implicit: true };
18241
- const stdin = options2.defaultInput === "stdin" || context.stdinIsDefault === false;
18293
+ if (args.mode === "files" || options3.defaultInput === "cwd" || args.patternFiles.includes("-")) return { paths: ["."], implicit: true };
18294
+ const stdin = options3.defaultInput === "stdin" || context.stdinIsDefault === false;
18242
18295
  return { paths: stdin ? ["-"] : ["."], implicit: !stdin };
18243
18296
  }
18244
18297
  async function patterns(context, args) {
@@ -18360,7 +18413,7 @@ async function searchFile(context, args, limits, matcher, printer, target, stdin
18360
18413
  }
18361
18414
  return { found, stats: totals };
18362
18415
  }
18363
- function createRgCommand(executor, options2 = {}) {
18416
+ function createRgCommand(executor, options3 = {}) {
18364
18417
  return {
18365
18418
  name: "rg",
18366
18419
  filesystemRequirements: searchRequirements,
@@ -18371,12 +18424,12 @@ function createRgCommand(executor, options2 = {}) {
18371
18424
  let failed = false;
18372
18425
  let found = false;
18373
18426
  try {
18374
- const limits = new Limits(context, options2);
18427
+ const limits = new Limits(context, options3);
18375
18428
  args = parse2(context.args);
18376
18429
  if (args.mode !== "files" && args.patternFiles.includes("-") && args.paths.includes("-")) {
18377
18430
  throw new SearchError("cannot search stdin while also reading patterns from stdin");
18378
18431
  }
18379
- const selection = selectInput(context, args, options2);
18432
+ const selection = selectInput(context, args, options3);
18380
18433
  const report = async (error) => {
18381
18434
  context.signal.throwIfAborted();
18382
18435
  failed = true;
@@ -18426,16 +18479,16 @@ function createRgCommand(executor, options2 = {}) {
18426
18479
  }
18427
18480
 
18428
18481
  // packages/safe-bash/src/commands/search/portable.ts
18429
- function portableSearchCommands(options2) {
18430
- const executor = new RegexExecutor(options2.provider, options2.regex);
18431
- const commands = [...createGrepCommands(executor), createRgCommand(executor, options2.search), sedCommand(options2.sed)];
18482
+ function portableSearchCommands(options3) {
18483
+ const executor = new RegexExecutor(options3.provider, options3.regex);
18484
+ const commands = [...createGrepCommands(executor), createRgCommand(executor, options3.search), sedCommand(options3.sed)];
18432
18485
  return {
18433
18486
  name: "portable-search-commands",
18434
18487
  setup(host) {
18435
- if (!options2.replace) for (const command2 of commands) {
18488
+ if (!options3.replace) for (const command2 of commands) {
18436
18489
  if (host.commands.has(command2.name)) throw new Error(`Command already registered: ${command2.name}`);
18437
18490
  }
18438
- for (const command2 of commands) host.commands.register(command2, { replace: options2.replace ?? false });
18491
+ for (const command2 of commands) host.commands.register(command2, { replace: options3.replace ?? false });
18439
18492
  },
18440
18493
  dispose: () => executor.dispose()
18441
18494
  };
@@ -18444,6 +18497,281 @@ function portableSearchCommands(options2) {
18444
18497
  // packages/safe-bash/src/commands/regex-execution/public.ts
18445
18498
  init_platform();
18446
18499
 
18500
+ // packages/safe-bash/src/commands/regex-execution/bounded-provider.ts
18501
+ init_platform();
18502
+ var defaults2 = Object.freeze({
18503
+ maxWorkers: 2,
18504
+ maxPatterns: 32,
18505
+ maxPatternBytes: 8192,
18506
+ maxRows: 128,
18507
+ maxInputBytes: 65536,
18508
+ maxResultBytes: 2048,
18509
+ maxWork: 2e6,
18510
+ maxAllocationUnits: 1e6,
18511
+ maxStates: 65536
18512
+ });
18513
+ var ceilings = Object.freeze({
18514
+ maxWorkers: 32,
18515
+ maxPatterns: 128,
18516
+ maxPatternBytes: 65532,
18517
+ maxRows: 4096,
18518
+ maxInputBytes: 1048576,
18519
+ maxResultBytes: 65536,
18520
+ maxWork: 33554432,
18521
+ maxAllocationUnits: 4e6,
18522
+ maxStates: 65536
18523
+ });
18524
+ var typedArrayPrototype2 = Object.getPrototypeOf(Uint8Array.prototype);
18525
+ var byteLength = Object.getOwnPropertyDescriptor(typedArrayPrototype2, "byteLength").get;
18526
+ var byteOffset = Object.getOwnPropertyDescriptor(typedArrayPrototype2, "byteOffset").get;
18527
+ var byteBuffer = Object.getOwnPropertyDescriptor(typedArrayPrototype2, "buffer").get;
18528
+ function fail(kind, message2) {
18529
+ throw new Error(`bounded regex ${kind}: ${message2}`);
18530
+ }
18531
+ function record3(value2, keys, optional = []) {
18532
+ if (value2 === null || typeof value2 !== "object" || Array.isArray(value2)) fail("protocol", "expected a data record");
18533
+ const ownKeys = Reflect.ownKeys(value2);
18534
+ if (ownKeys.length < keys.length || ownKeys.length > keys.length + optional.length || ownKeys.some((key) => typeof key !== "string" || !keys.includes(key) && !optional.includes(key))) fail("protocol", "unexpected data-record fields");
18535
+ for (const key of [...keys, ...optional]) {
18536
+ const property = Object.getOwnPropertyDescriptor(value2, key);
18537
+ if (property === void 0 ? keys.includes(key) : !("value" in property)) fail("protocol", "missing field or accessor");
18538
+ }
18539
+ }
18540
+ function array(value2, limit, label) {
18541
+ if (!Array.isArray(value2)) fail("protocol", `${label} must be an array`);
18542
+ if (value2.length > limit) fail("limit", `${label} count limit exceeded`);
18543
+ const keys = Reflect.ownKeys(value2);
18544
+ if (keys.length !== value2.length + 1) fail("protocol", `${label} must be a dense data array`);
18545
+ for (let index = 0; index < value2.length; index++) {
18546
+ const property = Object.getOwnPropertyDescriptor(value2, index);
18547
+ if (!property || !("value" in property)) fail("protocol", `${label} must be a dense data array`);
18548
+ }
18549
+ }
18550
+ function options2(input3) {
18551
+ const keys = Object.keys(defaults2);
18552
+ try {
18553
+ record3(input3, [], keys);
18554
+ } catch {
18555
+ throw new TypeError("bounded regex options require supported own data fields");
18556
+ }
18557
+ const result = { ...defaults2 };
18558
+ for (const key of keys) {
18559
+ if (!Object.hasOwn(input3, key)) continue;
18560
+ const value2 = input3[key];
18561
+ if (typeof value2 !== "number" || !Number.isSafeInteger(value2) || value2 < 1 || value2 > ceilings[key]) throw new RangeError(`bounded regex option ${key} is outside its limit`);
18562
+ result[key] = value2;
18563
+ }
18564
+ return Object.freeze(result);
18565
+ }
18566
+ function descriptor(value2, limits) {
18567
+ if (value2 === null || typeof value2 !== "object") fail("protocol", "invalid descriptor");
18568
+ const kind = Object.getOwnPropertyDescriptor(value2, "kind");
18569
+ if (!kind || !("value" in kind)) fail("protocol", "invalid descriptor kind");
18570
+ if (kind.value !== "grep" && kind.value !== "rg") fail("unsupported", "only grep and fixed rg selection descriptors are supported");
18571
+ const flags = kind.value === "grep" ? ["fixed", "extended", "insensitive", "whole", "word"] : ["fixed", "whole", "word", "nullData"];
18572
+ record3(value2, ["kind", "patterns", ...flags, ...kind.value === "rg" ? ["case"] : []]);
18573
+ for (const flag of flags) if (typeof value2[flag] !== "boolean") fail("protocol", `invalid ${flag} flag`);
18574
+ if (kind.value === "rg" && !["sensitive", "insensitive", "smart"].includes(value2.case)) fail("protocol", "invalid case flag");
18575
+ if (value2.word || kind.value === "grep" && value2.insensitive || kind.value === "rg" && value2.case !== "sensitive") fail("unsupported", "only case-sensitive, non-word selection is supported");
18576
+ if (kind.value === "rg" && !value2.fixed) fail("unsupported", "rg regex and Unicode modes are unsupported; use fixed ASCII patterns");
18577
+ array(value2.patterns, limits.maxPatterns, "pattern");
18578
+ let bytes2 = 0;
18579
+ for (let index = 0; index < value2.patterns.length; index++) {
18580
+ const pattern = value2.patterns[index];
18581
+ if (typeof pattern !== "string") fail("protocol", "patterns must be strings");
18582
+ if (pattern.length > limits.maxPatternBytes - bytes2) fail("limit", "aggregate pattern byte limit exceeded");
18583
+ bytes2 += pattern.length;
18584
+ }
18585
+ return value2;
18586
+ }
18587
+ function admit(input3, limits, signal) {
18588
+ record3(input3, ["id", "descriptor", "rows"]);
18589
+ const selected = descriptor(input3.descriptor, limits);
18590
+ array(input3.rows, limits.maxRows, "row");
18591
+ if (input3.rows.length > Math.floor(limits.maxResultBytes / 16)) fail("limit", "result byte limit exceeded");
18592
+ let bytes2 = 0;
18593
+ for (let index = 0; index < input3.rows.length; index++) {
18594
+ const row = input3.rows[index];
18595
+ record3(row, ["bytes", "all", "terminated"], ["directory", "ancestors"]);
18596
+ if (!(row.bytes instanceof Uint8Array) || typeof row.all !== "boolean" || typeof row.terminated !== "boolean" || Object.hasOwn(row, "directory") && typeof row.directory !== "boolean" || Object.hasOwn(row, "ancestors") && typeof row.ancestors !== "boolean") fail("protocol", "invalid row");
18597
+ if (Object.hasOwn(row, "directory") || Object.hasOwn(row, "ancestors")) fail("unsupported", "glob row flags are unsupported");
18598
+ if (row.all) fail("unsupported", "all-match enumeration is unsupported");
18599
+ const length = byteLength.call(row.bytes);
18600
+ if (length > limits.maxInputBytes - bytes2) fail("limit", "aggregate input byte limit exceeded");
18601
+ bytes2 += length;
18602
+ }
18603
+ const ledger = new EreLedger({ maxExpansionBytes: 1048576, maxExpansionFields: 8192 }, {
18604
+ patternBytes: limits.maxPatternBytes + 4,
18605
+ subjectBytes: limits.maxInputBytes,
18606
+ work: limits.maxWork,
18607
+ allocationUnits: limits.maxAllocationUnits,
18608
+ states: limits.maxStates
18609
+ });
18610
+ ledger.charge("allocationUnits", bytes2 + input3.rows.length * 12 + selected.patterns.length * 2 + 16, signal);
18611
+ const patterns2 = [];
18612
+ for (let index = 0; index < selected.patterns.length; index++) patterns2.push(selected.patterns[index]);
18613
+ const ownedDescriptor = selected.kind === "grep" ? { kind: "grep", patterns: patterns2, fixed: selected.fixed, extended: selected.extended, insensitive: selected.insensitive, whole: selected.whole, word: selected.word } : { kind: "rg", patterns: patterns2, fixed: selected.fixed, case: selected.case, whole: selected.whole, word: selected.word, nullData: selected.nullData };
18614
+ const rows = [];
18615
+ for (let index = 0; index < input3.rows.length; index++) {
18616
+ const row = input3.rows[index];
18617
+ const source = new Uint8Array(byteBuffer.call(row.bytes), byteOffset.call(row.bytes), byteLength.call(row.bytes));
18618
+ const copy2 = new Uint8Array(source.length);
18619
+ copy2.set(source);
18620
+ rows.push({ bytes: copy2, all: false, terminated: row.terminated });
18621
+ }
18622
+ return { id: input3.id, descriptor: ownedDescriptor, rows, ledger };
18623
+ }
18624
+ async function admitBre(pattern, ledger, signal) {
18625
+ let bracket = -1;
18626
+ let member = false;
18627
+ let namedClass = false;
18628
+ for (let index = 0; index < pattern.length; index++) {
18629
+ ledger.charge("work", 1, signal);
18630
+ await ledger.checkpoint(signal);
18631
+ const character = pattern[index];
18632
+ if ("\\()+?{}|".includes(character)) fail("unsupported", "BRE escapes, groups and interval/operator extensions are unsupported; use grep -E");
18633
+ if (bracket >= 0) {
18634
+ if (index === bracket + 1 && character === "^") continue;
18635
+ if (namedClass) {
18636
+ if (character === "]" && pattern[index - 1] === ":") namedClass = false;
18637
+ } else if (character === "]" && member) bracket = -1;
18638
+ else if (character === "[" && pattern[index + 1] === ":") namedClass = true;
18639
+ member = true;
18640
+ } else if (character === "[") {
18641
+ bracket = index;
18642
+ member = false;
18643
+ } else if (character === "^" && index !== 0 || character === "$" && index !== pattern.length - 1) {
18644
+ fail("unsupported", "BRE anchors are supported only at record boundaries");
18645
+ } else if (character === "*" && (index === 0 || index === 1 && pattern[0] === "^")) {
18646
+ fail("unsupported", "BRE leading literal star is unsupported; use fixed matching");
18647
+ }
18648
+ }
18649
+ }
18650
+ async function execute2(input3, signal) {
18651
+ const { descriptor: selected, rows, ledger } = input3;
18652
+ const programs2 = [];
18653
+ for (const pattern of selected.patterns) {
18654
+ if (selected.kind === "grep" && !selected.fixed && !selected.extended) await admitBre(pattern, ledger, signal);
18655
+ if (selected.kind === "rg" && !selected.nullData && pattern.includes("\n")) fail("unsupported", "rg multiline matching is unsupported");
18656
+ ledger.charge("allocationUnits", (selected.whole ? 3 : 1) * 3 + 2, signal);
18657
+ const fragments = selected.whole ? [{ text: "^(", literal: false }, { text: pattern, literal: selected.fixed }, { text: ")$", literal: false }] : [{ text: pattern, literal: selected.fixed }];
18658
+ programs2.push(await compileEre(fragments, ledger, signal));
18659
+ }
18660
+ const results = [];
18661
+ for (const row of rows) {
18662
+ ledger.charge("allocationUnits", row.bytes.length * 2 + 2, signal);
18663
+ const characters = [];
18664
+ for (const byte of row.bytes) {
18665
+ ledger.charge("work", 1, signal);
18666
+ if (byte === 0 || byte > 127) fail("unsupported", "subjects require non-NUL ASCII; Unicode and invalid UTF-8 are unsupported");
18667
+ characters.push(String.fromCharCode(byte));
18668
+ await ledger.checkpoint(signal);
18669
+ }
18670
+ const subject = characters.join("");
18671
+ let span;
18672
+ for (const program of programs2) {
18673
+ const match = await matchEre(program, subject, ledger, signal);
18674
+ if (!match.matched) continue;
18675
+ const candidate = match.captures[0];
18676
+ if (selected.kind === "grep") {
18677
+ span = candidate;
18678
+ break;
18679
+ }
18680
+ if (!span || candidate.start < span.start) span = candidate;
18681
+ }
18682
+ signal.throwIfAborted();
18683
+ results.push(span ? new Float64Array([span.start, span.end]) : new Float64Array());
18684
+ }
18685
+ return { id: input3.id, results };
18686
+ }
18687
+ var CooperativeWorker = class {
18688
+ constructor(limits, release) {
18689
+ this.limits = limits;
18690
+ this.release = release;
18691
+ queueMicrotask(() => {
18692
+ if (!this.#closing) this.emit({ ready: true });
18693
+ });
18694
+ }
18695
+ limits;
18696
+ release;
18697
+ #controller = new AbortController();
18698
+ #listeners = /* @__PURE__ */ new Map();
18699
+ #tasks = /* @__PURE__ */ new Set();
18700
+ #busy = false;
18701
+ #closing;
18702
+ on(event, listener) {
18703
+ if (this.#closing) return;
18704
+ let listeners = this.#listeners.get(event);
18705
+ if (!listeners) {
18706
+ listeners = /* @__PURE__ */ new Set();
18707
+ this.#listeners.set(event, listeners);
18708
+ }
18709
+ listeners.add(listener);
18710
+ }
18711
+ off(event, listener) {
18712
+ this.#listeners.get(event)?.delete(listener);
18713
+ }
18714
+ emit(value2) {
18715
+ for (const listener of this.#listeners.get("message") ?? []) listener(value2);
18716
+ }
18717
+ postMessage(input3) {
18718
+ if (this.#closing) throw new Error("bounded regex worker is closed");
18719
+ if (this.#busy) throw new Error("bounded regex worker is busy");
18720
+ const identity = input3 !== null && typeof input3 === "object" ? Object.getOwnPropertyDescriptor(input3, "id") : void 0;
18721
+ if (!identity || !("value" in identity) || !Number.isSafeInteger(identity.value) || identity.value < 1) fail("protocol", "invalid request identity");
18722
+ const id = identity.value;
18723
+ const submitted = Object.getOwnPropertyDescriptor(input3, "descriptor")?.value;
18724
+ const expression = submitted !== null && typeof submitted === "object" && Object.getOwnPropertyDescriptor(submitted, "kind")?.value === "expr-match";
18725
+ let owned;
18726
+ let failure;
18727
+ try {
18728
+ owned = admit(input3, this.limits, this.#controller.signal);
18729
+ } catch (error) {
18730
+ failure = error instanceof Error ? error.message.slice(0, 512) : "bounded regex protocol: request admission failed";
18731
+ }
18732
+ this.#busy = true;
18733
+ const task = Promise.resolve().then(async () => {
18734
+ let reply;
18735
+ try {
18736
+ this.#controller.signal.throwIfAborted();
18737
+ reply = owned ? await execute2(owned, this.#controller.signal) : { id, error: failure };
18738
+ } catch (error) {
18739
+ reply = { id, error: error instanceof Error ? error.message.slice(0, 512) : "bounded regex request failed" };
18740
+ }
18741
+ if (expression && "error" in reply) reply = { id, operation: "expr-match", category: "unsupported", error: reply.error };
18742
+ owned = void 0;
18743
+ this.#busy = false;
18744
+ if (!this.#closing) this.emit(reply);
18745
+ });
18746
+ this.#tasks.add(task);
18747
+ void task.then(() => this.#tasks.delete(task), () => this.#tasks.delete(task));
18748
+ }
18749
+ terminate() {
18750
+ if (!this.#closing) {
18751
+ this.#closing = Promise.allSettled([...this.#tasks]).then(() => {
18752
+ this.#listeners.clear();
18753
+ this.#tasks.clear();
18754
+ this.release();
18755
+ });
18756
+ this.#controller.abort(new Error("bounded regex worker terminated"));
18757
+ }
18758
+ return this.#closing;
18759
+ }
18760
+ };
18761
+ function createBoundedRegexProvider(input3 = {}) {
18762
+ const limits = options2(input3);
18763
+ let active = 0;
18764
+ return Object.freeze({
18765
+ createWorker() {
18766
+ if (active >= limits.maxWorkers) fail("limit", "worker count limit exceeded");
18767
+ active++;
18768
+ return new CooperativeWorker(limits, () => {
18769
+ active--;
18770
+ });
18771
+ }
18772
+ });
18773
+ }
18774
+
18447
18775
  // packages/safe-bash/src/browser.ts
18448
18776
  function createBrowserCommands() {
18449
18777
  return [
@@ -18454,17 +18782,17 @@ function createBrowserCommands() {
18454
18782
  ...textCommands()
18455
18783
  ];
18456
18784
  }
18457
- function browserCommands(options2 = {}) {
18785
+ function browserCommands(options3 = {}) {
18458
18786
  return {
18459
18787
  name: "browser-commands",
18460
18788
  setup(host) {
18461
18789
  const commands = createBrowserCommands();
18462
- if (!options2.replace) {
18790
+ if (!options3.replace) {
18463
18791
  for (const command2 of commands) {
18464
18792
  if (host.commands.has(command2.name)) throw new Error(`Command already registered: ${command2.name}`);
18465
18793
  }
18466
18794
  }
18467
- for (const command2 of commands) host.commands.register(command2, { replace: options2.replace ?? false });
18795
+ for (const command2 of commands) host.commands.register(command2, { replace: options3.replace ?? false });
18468
18796
  }
18469
18797
  };
18470
18798
  }
@@ -18495,6 +18823,7 @@ export {
18495
18823
  collectText,
18496
18824
  compileEre,
18497
18825
  composeMiddleware,
18826
+ createBoundedRegexProvider,
18498
18827
  createBrowserCommands,
18499
18828
  createBytePipe,
18500
18829
  createCommandArguments,