@poe-platform/safe-bash 0.1.755 → 0.1.757

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 (131) hide show
  1. package/dist/image-ast/index.browser.js +30 -6
  2. package/dist/image-ast/index.js +30 -6
  3. package/dist/pdf-ast/canvas.d.ts +1 -0
  4. package/dist/pdf-ast/index.js +26 -2
  5. package/dist/safe-bash/chunks/{chunk-LESPJ3OG.js → chunk-WNWIBBJZ.js} +15 -2
  6. package/dist/safe-bash/command-chunks/{chunk-S4J6MSLY.js → chunk-444OTXM7.js} +3 -3
  7. package/dist/safe-bash/command-chunks/{chunk-6AIOGLZO.js → chunk-CE6Z2ULX.js} +2 -2
  8. package/dist/safe-bash/command-chunks/{chunk-5VSGEE6J.js → chunk-F4IQCXZG.js} +5 -5
  9. package/dist/safe-bash/command-chunks/{chunk-F5MORDSU.js → chunk-FDNCPZQS.js} +32 -1
  10. package/dist/safe-bash/command-chunks/{chunk-SG3ZDZCX.js → chunk-FLMLM7Y4.js} +2 -2
  11. package/dist/safe-bash/command-chunks/{chunk-XRVNFK7Z.js → chunk-H2FQA4OU.js} +26 -2
  12. package/dist/safe-bash/command-chunks/{chunk-CT3FB722.js → chunk-J7UMKBRK.js} +1 -1
  13. package/dist/safe-bash/command-chunks/{chunk-KB2LQ4HG.js → chunk-KBBI4CSU.js} +2 -2
  14. package/dist/safe-bash/command-chunks/{chunk-QQOAK7JQ.js → chunk-KKJCKPTA.js} +1 -1
  15. package/dist/safe-bash/command-chunks/{chunk-7KS6PX4U.js → chunk-KSIGF4AG.js} +3 -3
  16. package/dist/safe-bash/command-chunks/{chunk-4HQ7WYSI.js → chunk-MED2BOOW.js} +30 -5
  17. package/dist/safe-bash/command-chunks/{chunk-JRNLDPLI.js → chunk-OZSWW23M.js} +1 -1
  18. package/dist/safe-bash/command-chunks/{chunk-DKQ5REXF.js → chunk-QDPRSPHQ.js} +1 -1
  19. package/dist/safe-bash/command-chunks/{chunk-WOPU2VWF.js → chunk-RID3B5RE.js} +1 -1
  20. package/dist/safe-bash/command-chunks/{chunk-DVZCHNB5.js → chunk-S4MLIYSN.js} +7 -7
  21. package/dist/safe-bash/command-chunks/{chunk-REYTQLLB.js → chunk-TT2DMDBY.js} +1 -1
  22. package/dist/safe-bash/command-chunks/{chunk-UGX6MXDD.js → chunk-UIIT4ULR.js} +3 -3
  23. package/dist/safe-bash/command-chunks/{chunk-MENC7RPR.js → chunk-WI35236J.js} +1 -1
  24. package/dist/safe-bash/command-chunks/{chunk-A6NFLWZI.js → chunk-WKPOGTZY.js} +22 -6
  25. package/dist/safe-bash/command-chunks/{chunk-3DOHQQJR.js → chunk-Y64PA6IA.js} +8 -8
  26. package/dist/safe-bash/command-chunks/{chunk-6Z7OS3TZ.js → chunk-ZP5KDHB4.js} +7 -7
  27. package/dist/safe-bash/commands/pandoc/index.d.ts +1 -1
  28. package/dist/safe-bash/commands/pandoc/index.js +5 -3
  29. package/dist/safe-bash/commands/python/index.browser.js +1 -1
  30. package/dist/safe-bash/commands/python/index.js +6 -0
  31. package/dist/safe-bash/commands/python/jspi.js +11 -2
  32. package/dist/safe-bash/core.browser.js +6 -4
  33. package/dist/safe-bash-command-csvkit/index.js +8 -8
  34. package/dist/safe-bash-command-ffmpeg/index.js +20 -2
  35. package/dist/safe-bash-command-imagemagick/index.js +2 -2
  36. package/dist/safe-bash-command-pandoc/command.js +3 -3
  37. package/dist/safe-bash-command-pandoc/index.js +3 -3
  38. package/dist/safe-bash-command-pdfimages/index.js +26 -2
  39. package/dist/safe-bash-command-pdfinfo/index.js +26 -2
  40. package/dist/safe-bash-command-pdftk/index.js +26 -2
  41. package/dist/safe-bash-command-pdftoppm/index.js +26 -2
  42. package/dist/safe-bash-command-pdftotext/index.js +26 -2
  43. package/dist/safe-bash-command-qpdf/index.js +26 -2
  44. package/dist/safe-bash-command-sips/index.js +2 -2
  45. package/dist/safe-bash-command-soffice/index.js +17 -17
  46. package/dist/safe-bash-command-ssconvert/core.js +8 -8
  47. package/dist/safe-bash-command-ssconvert/formats/csv.js +9 -9
  48. package/dist/safe-bash-command-ssconvert/formats/ods.js +8 -8
  49. package/dist/safe-bash-command-ssconvert/formats/spreadsheetml.js +1 -1
  50. package/dist/safe-bash-command-ssconvert/formats/xls.js +9 -8
  51. package/dist/safe-bash-command-ssconvert/formats/xlsx.js +8 -8
  52. package/dist/safe-bash-command-ssconvert/index.js +133 -29
  53. package/dist/safe-bash-command-wkhtmltopdf/index.js +26 -2
  54. package/dist/safe-bash-contracts/filesystem-descriptor.js +1 -1
  55. package/dist/safe-bash-contracts/filesystem-output.js +1 -1
  56. package/dist/safe-bash-mcp/index.js +4 -4
  57. package/dist/spreadsheet-engine/formulas/ast.d.ts +13 -0
  58. package/dist/spreadsheet-engine/formulas/conventions.js +1 -1
  59. package/dist/spreadsheet-engine/formulas/dependencies.js +2 -2
  60. package/dist/spreadsheet-engine/formulas/evaluator.js +2 -2
  61. package/dist/spreadsheet-engine/formulas/named-expressions.d.ts +2 -2
  62. package/dist/spreadsheet-engine/formulas/named-expressions.js +31 -5
  63. package/dist/spreadsheet-engine/formulas/parser.js +34 -0
  64. package/dist/spreadsheet-engine/formulas/rewriting.js +19 -1
  65. package/dist/spreadsheet-engine/formulas/serialization.js +6 -0
  66. package/dist/spreadsheet-format-xls/biff-write-formulas.js +2 -0
  67. package/dist/xlsx-ast/formula-semantics.js +2 -0
  68. package/package.json +2 -2
  69. package/third-party/pdf-ast/THIRD_PARTY_NOTICES.md +1 -1
  70. package/dist/safe-bash/chunks/browser-ECQX6GMK.js +0 -6766
  71. package/dist/safe-bash/chunks/bz2-4OP3OWW3.js +0 -8
  72. package/dist/safe-bash/chunks/chunk-22XPAAOI.js +0 -173
  73. package/dist/safe-bash/chunks/chunk-44WUNUPV.js +0 -649
  74. package/dist/safe-bash/chunks/chunk-4E3SGG37.js +0 -876
  75. package/dist/safe-bash/chunks/chunk-4QTSSQKP.js +0 -898
  76. package/dist/safe-bash/chunks/chunk-5UVGPVXP.js +0 -410
  77. package/dist/safe-bash/chunks/chunk-64OE6Q6X.js +0 -3487
  78. package/dist/safe-bash/chunks/chunk-6IIFUPN2.js +0 -1526
  79. package/dist/safe-bash/chunks/chunk-6XDKK63A.js +0 -38959
  80. package/dist/safe-bash/chunks/chunk-BENDLTQD.js +0 -7065
  81. package/dist/safe-bash/chunks/chunk-BMO5LWEX.js +0 -534
  82. package/dist/safe-bash/chunks/chunk-BPMCPTNP.js +0 -1920
  83. package/dist/safe-bash/chunks/chunk-BRJTAWP5.js +0 -2955
  84. package/dist/safe-bash/chunks/chunk-C3GEIN7Q.js +0 -20054
  85. package/dist/safe-bash/chunks/chunk-CEWCRI6H.js +0 -2813
  86. package/dist/safe-bash/chunks/chunk-CGL53DQQ.js +0 -37
  87. package/dist/safe-bash/chunks/chunk-CTYJJD4O.js +0 -869
  88. package/dist/safe-bash/chunks/chunk-CWSS4MQA.js +0 -7
  89. package/dist/safe-bash/chunks/chunk-DLIGMTCP.js +0 -3266
  90. package/dist/safe-bash/chunks/chunk-EMAJ7WUW.js +0 -1031
  91. package/dist/safe-bash/chunks/chunk-FDKIZ2IJ.js +0 -1950
  92. package/dist/safe-bash/chunks/chunk-FZWJ2A7V.js +0 -3093
  93. package/dist/safe-bash/chunks/chunk-G2VCIF2J.js +0 -22
  94. package/dist/safe-bash/chunks/chunk-GVKBUQDX.js +0 -2649
  95. package/dist/safe-bash/chunks/chunk-IO2OGW3E.js +0 -28051
  96. package/dist/safe-bash/chunks/chunk-ISCZG7WA.js +0 -2648
  97. package/dist/safe-bash/chunks/chunk-JEFBTRY7.js +0 -174814
  98. package/dist/safe-bash/chunks/chunk-KJHDD4A2.js +0 -759
  99. package/dist/safe-bash/chunks/chunk-LB6HVRXS.js +0 -857
  100. package/dist/safe-bash/chunks/chunk-LLWAJOZH.js +0 -15
  101. package/dist/safe-bash/chunks/chunk-LMUKYZIJ.js +0 -708
  102. package/dist/safe-bash/chunks/chunk-M5SCNKIK.js +0 -2012
  103. package/dist/safe-bash/chunks/chunk-MJPFHANT.js +0 -3350
  104. package/dist/safe-bash/chunks/chunk-MZQW2DOL.js +0 -82
  105. package/dist/safe-bash/chunks/chunk-NB2V7EOY.js +0 -1348
  106. package/dist/safe-bash/chunks/chunk-NJVGOIYN.js +0 -17
  107. package/dist/safe-bash/chunks/chunk-OLNZHDIQ.js +0 -5141
  108. package/dist/safe-bash/chunks/chunk-OUUVROTM.js +0 -38
  109. package/dist/safe-bash/chunks/chunk-PA6GYKBQ.js +0 -151
  110. package/dist/safe-bash/chunks/chunk-PEFHZ226.js +0 -6957
  111. package/dist/safe-bash/chunks/chunk-QBB5P5KW.js +0 -4839
  112. package/dist/safe-bash/chunks/chunk-QHB7HBLA.js +0 -2317
  113. package/dist/safe-bash/chunks/chunk-RSAWYAEH.js +0 -973
  114. package/dist/safe-bash/chunks/chunk-UWLYRWT4.js +0 -739
  115. package/dist/safe-bash/chunks/chunk-V463NBQH.js +0 -13
  116. package/dist/safe-bash/chunks/chunk-WPUALYUS.js +0 -843
  117. package/dist/safe-bash/chunks/chunk-XHKFSRGU.js +0 -5747
  118. package/dist/safe-bash/chunks/chunk-XHRCLZ3N.js +0 -13391
  119. package/dist/safe-bash/chunks/chunk-XPF5XHLY.js +0 -15
  120. package/dist/safe-bash/chunks/chunk-ZBFOWARG.js +0 -305
  121. package/dist/safe-bash/chunks/chunk-ZG7GWQ5P.js +0 -1859
  122. package/dist/safe-bash/chunks/model-store-EIY3ZQLZ.js +0 -10
  123. package/dist/safe-bash/chunks/pdf-renderer-XIFUTX34.js +0 -22
  124. package/dist/safe-bash/chunks/pptx-ZL6L7KP2-O425BFIU.js +0 -30658
  125. package/dist/safe-bash/chunks/src-HHEPGR7U.js +0 -18969
  126. package/dist/safe-bash/chunks/src-V4VCM5OX.js +0 -187
  127. package/dist/safe-bash/chunks/usage-6TGVA2OM.js +0 -35
  128. package/dist/safe-bash/chunks/xz-EGQGQUEI.js +0 -8
  129. package/dist/safe-bash/chunks/xz-K2E2WLM6.js +0 -9
  130. package/dist/safe-bash/chunks/zstd-6JBLP5EF.js +0 -8
  131. package/dist/safe-bash/git_rust-C3QYOAZL.wasm +0 -0
@@ -1,973 +0,0 @@
1
- import {
2
- parseSignal
3
- } from "./chunk-LB6HVRXS.js";
4
- import {
5
- shellValueByteLength,
6
- value_exports
7
- } from "./chunk-CGL53DQQ.js";
8
- import {
9
- command_exports
10
- } from "./chunk-G2VCIF2J.js";
11
- import {
12
- builtInDirectContextExecutors,
13
- syncCommandEvaluators
14
- } from "./chunk-ISCZG7WA.js";
15
- import {
16
- init_platform
17
- } from "./chunk-ZG7GWQ5P.js";
18
-
19
- // packages/safe-bash/src/commands/copy-identity.ts
20
- init_platform();
21
- import { compareCopyIdentity, compareObservedEntries } from "../../safe-bash-contracts/filesystem-identity.js";
22
-
23
- // packages/safe-bash-io-engine/src/byte-encoding.ts
24
- init_platform();
25
- var encoder = new TextEncoder();
26
- function bytesToHex(bytes) {
27
- let result = "";
28
- for (const byte of bytes) result += byte.toString(16).padStart(2, "0");
29
- return result;
30
- }
31
- function latin1Bytes(text) {
32
- const bytes = new Uint8Array(text.length);
33
- for (let index = 0; index < text.length; index++) bytes[index] = text.charCodeAt(index) & 255;
34
- return bytes;
35
- }
36
- function latin1Text(bytes) {
37
- let result = "";
38
- for (const byte of bytes) result += String.fromCharCode(byte);
39
- return result;
40
- }
41
- function equalBytes(left, right) {
42
- if (left.byteLength !== right.byteLength) return false;
43
- for (let index = 0; index < left.byteLength; index++) {
44
- if (left[index] !== right[index]) return false;
45
- }
46
- return true;
47
- }
48
- function compareUtf8(left, right) {
49
- const a = encoder.encode(left);
50
- const b = encoder.encode(right);
51
- for (let index = 0; index < Math.min(a.length, b.length); index++) {
52
- if (a[index] !== b[index]) return a[index] - b[index];
53
- }
54
- return a.length - b.length;
55
- }
56
-
57
- // packages/safe-bash-command-timeout/src/index.ts
58
- init_platform();
59
- import { FsError, getCommandArguments, writeBytes } from "../../safe-bash-contracts/index.js";
60
- import { shellValueByteLength as shellValueByteLength2 } from "../../safe-bash-contracts/value.js";
61
-
62
- // packages/safe-bash-command-timeout/src/duration.ts
63
- init_platform();
64
- var maximumFiniteDuration = BigInt(Number.MAX_VALUE);
65
- function multiplier(code) {
66
- if (code === 115) return 1e3;
67
- if (code === 109) return 6e4;
68
- if (code === 104) return 36e5;
69
- if (code === 100) return 864e5;
70
- return void 0;
71
- }
72
- function parseDuration(token) {
73
- const end = token.length;
74
- let index = 0;
75
- while (index < end && (token[index] === " " || token.charCodeAt(index) >= 9 && token.charCodeAt(index) <= 13)) index++;
76
- const negative = token[index] === "-";
77
- if (negative || token[index] === "+") index++;
78
- if (token.slice(index, index + 3).toLowerCase() === "inf") {
79
- index += 3;
80
- if (token.slice(index, index + 5).toLowerCase() === "inity") index += 5;
81
- if (negative || index !== end && (multiplier(token.charCodeAt(index)) === void 0 || index + 1 !== end)) return { kind: "invalid" };
82
- return { kind: "value", milliseconds: Infinity };
83
- }
84
- const hexadecimal = token[index] === "0" && (token[index + 1] === "x" || token[index + 1] === "X");
85
- if (hexadecimal) index += 2;
86
- const radix = hexadecimal ? 16 : 10;
87
- let digits = "";
88
- let fractionalDigits = 0;
89
- let sawPoint = false;
90
- while (index < end) {
91
- const character = token[index];
92
- if (character === "." && !sawPoint) {
93
- sawPoint = true;
94
- index++;
95
- continue;
96
- }
97
- const code = character.toLowerCase().charCodeAt(0);
98
- const digit = code >= 48 && code <= 57 ? code - 48 : code >= 97 && code <= 102 ? code - 87 : radix;
99
- if (digit >= radix) break;
100
- digits += character;
101
- if (sawPoint) fractionalDigits++;
102
- index++;
103
- }
104
- if (digits.length === 0) return { kind: "invalid" };
105
- let exponent = 0;
106
- const exponentMarker = hexadecimal ? "p" : "e";
107
- const exponentLimit = token.length * 4 + 1100;
108
- if (token[index]?.toLowerCase() === exponentMarker) {
109
- index++;
110
- const exponentNegative = token[index] === "-";
111
- if (exponentNegative || token[index] === "+") index++;
112
- const start = index;
113
- while (index < end && token.charCodeAt(index) >= 48 && token.charCodeAt(index) <= 57) {
114
- exponent = Math.min(exponentLimit, exponent * 10 + token.charCodeAt(index) - 48);
115
- index++;
116
- }
117
- if (index === start) return { kind: "invalid" };
118
- if (exponentNegative) exponent = -exponent;
119
- }
120
- const suffixMultiplier = multiplier(token.charCodeAt(index));
121
- if (index !== end && (suffixMultiplier === void 0 || index + 1 !== end)) return { kind: "invalid" };
122
- const significand = BigInt(hexadecimal ? "0x" + digits : digits);
123
- if (significand === 0n) return { kind: "value", milliseconds: 0 };
124
- if (negative) return { kind: "invalid" };
125
- const scale = exponent - fractionalDigits * (hexadecimal ? 4 : 1);
126
- const base = hexadecimal ? 2n : 10n;
127
- let numerator = significand;
128
- let denominator = 1n;
129
- if (scale >= 0) numerator *= base ** BigInt(scale);
130
- else denominator = base ** BigInt(-scale);
131
- const infinityThreshold = (1n << 1024n) - (1n << 970n);
132
- if (numerator >= infinityThreshold * denominator) return { kind: "value", milliseconds: Infinity };
133
- numerator *= BigInt(suffixMultiplier ?? 1e3);
134
- const milliseconds = (numerator + denominator - 1n) / denominator;
135
- return { kind: "value", milliseconds: Number(milliseconds > maximumFiniteDuration ? maximumFiniteDuration : milliseconds) };
136
- }
137
-
138
- // packages/safe-bash-command-timeout/src/scheduler.ts
139
- init_platform();
140
- var defaultSchedulerBinding = Object.freeze({
141
- receiver: globalThis,
142
- now: () => globalThis.performance.now(),
143
- setTimeout: (callback, milliseconds) => globalThis.setTimeout(callback, milliseconds),
144
- clearTimeout: (handle) => globalThis.clearTimeout(handle)
145
- });
146
- function clock(binding, previous) {
147
- const sample = Reflect.apply(binding.now, binding.receiver, []);
148
- if (typeof sample !== "number" || !Number.isFinite(sample) || Math.abs(sample) > Number.MAX_SAFE_INTEGER || previous !== void 0 && sample < previous) {
149
- throw new RangeError("Invalid timeout scheduler clock sample");
150
- }
151
- return sample;
152
- }
153
- function createDeadline(binding, duration, maximumChunk, cancel = true) {
154
- const controller = new AbortController();
155
- const deadlineReason = Object.freeze({});
156
- const timerFailureReason = Object.freeze({});
157
- let admissionOpen = true;
158
- let expired = false;
159
- let remaining = duration;
160
- let previous = 0;
161
- let step = 0;
162
- let handle;
163
- let handleLive = false;
164
- let cleanupFailed = false;
165
- let cleanupFailure;
166
- let retirement;
167
- const rememberCleanupFailure = (error) => {
168
- if (!cleanupFailed) {
169
- cleanupFailed = true;
170
- cleanupFailure = error;
171
- }
172
- };
173
- const clearLiveHandle = () => {
174
- if (!handleLive) return;
175
- const current = handle;
176
- handleLive = false;
177
- handle = void 0;
178
- try {
179
- Reflect.apply(binding.clearTimeout, binding.receiver, [current]);
180
- } catch (error) {
181
- rememberCleanupFailure(error);
182
- throw error;
183
- }
184
- };
185
- const failTimer = () => {
186
- admissionOpen = false;
187
- controller.abort(timerFailureReason);
188
- };
189
- const arm = () => {
190
- step = Math.min(2147483647, maximumChunk, Math.max(1, Math.ceil(remaining)));
191
- handle = Reflect.apply(binding.setTimeout, binding.receiver, [wake, step]);
192
- handleLive = true;
193
- };
194
- const wake = () => {
195
- if (!admissionOpen) return;
196
- let sample;
197
- try {
198
- sample = clock(binding, previous);
199
- } catch {
200
- failTimer();
201
- return;
202
- }
203
- remaining -= Math.max(step, sample - previous);
204
- previous = sample;
205
- if (remaining <= 0) {
206
- admissionOpen = false;
207
- expired = true;
208
- if (cancel) controller.abort(deadlineReason);
209
- return;
210
- }
211
- try {
212
- clearLiveHandle();
213
- arm();
214
- } catch {
215
- failTimer();
216
- }
217
- };
218
- const retire = () => {
219
- if (retirement === void 0) {
220
- admissionOpen = false;
221
- try {
222
- clearLiveHandle();
223
- if (cleanupFailed) throw cleanupFailure;
224
- retirement = Promise.resolve();
225
- } catch (error) {
226
- retirement = Promise.reject(error);
227
- }
228
- }
229
- return retirement;
230
- };
231
- return {
232
- get expired() {
233
- return expired;
234
- },
235
- signal: controller.signal,
236
- deadlineReason,
237
- timerFailureReason,
238
- retire,
239
- start() {
240
- previous = clock(binding);
241
- arm();
242
- }
243
- };
244
- }
245
-
246
- // packages/safe-bash-command-timeout/src/index.ts
247
- var encoder2 = new TextEncoder();
248
- var records = Object.freeze({
249
- missingDuration: encoder2.encode("timeout: missing duration\n"),
250
- invalidDuration: encoder2.encode("timeout: invalid duration\n"),
251
- durationOverflow: encoder2.encode("timeout: duration exceeds supported range\n"),
252
- missingCommand: encoder2.encode("timeout: missing command\n"),
253
- invalidOption: encoder2.encode("timeout: invalid option\n"),
254
- invalidSignal: encoder2.encode("timeout: invalid signal\n"),
255
- invokeUnavailable: encoder2.encode("timeout: command invocation is unavailable\n"),
256
- escalationUnavailable: encoder2.encode("timeout: hard escalation is unavailable on this host\n"),
257
- timerSetupFailed: encoder2.encode("timeout: timer setup failed\n"),
258
- help: encoder2.encode("Usage: timeout [OPTION] DURATION COMMAND [ARG]...\nRun a virtual-bash command with a cooperative time limit.\n"),
259
- version: encoder2.encode("timeout (virtual-bash cooperative profile)\n")
260
- });
261
- function optionsObject(value) {
262
- if (value === void 0) return void 0;
263
- if (value === null || typeof value !== "object" || Array.isArray(value)) throw new TypeError("Timeout options must be an object");
264
- return value;
265
- }
266
- function settings(value, includeReplace) {
267
- const options = optionsObject(value);
268
- const configuredLimits = optionsObject(options?.limits);
269
- const limits = {
270
- maxArguments: Infinity,
271
- maxArgumentBytes: Infinity,
272
- maxOutputBytes: Infinity,
273
- ...configuredLimits
274
- };
275
- for (const [name, limit] of Object.entries(limits)) {
276
- if (limit !== Infinity && (!Number.isSafeInteger(limit) || limit < 1)) throw new RangeError(`Invalid timeout limit: ${name}`);
277
- }
278
- const killAfterPolicy = options?.killAfterPolicy;
279
- if (killAfterPolicy !== void 0 && typeof killAfterPolicy !== "function") throw new TypeError("Timeout killAfterPolicy must be a function");
280
- const invokeValue = options?.invoke;
281
- if (invokeValue !== void 0 && typeof invokeValue !== "function") throw new TypeError("Timeout invoke must be a function");
282
- const invoke = invokeValue;
283
- const scheduler = options?.scheduler;
284
- let binding = defaultSchedulerBinding;
285
- if (scheduler !== void 0) {
286
- if (scheduler === null || typeof scheduler !== "object" || Array.isArray(scheduler)) throw new TypeError("Timeout scheduler must be an object");
287
- const provider = scheduler;
288
- const now = provider.now;
289
- const setTimeout = provider.setTimeout;
290
- const clearTimeout = provider.clearTimeout;
291
- if (typeof now !== "function" || typeof setTimeout !== "function" || typeof clearTimeout !== "function") {
292
- throw new TypeError("Timeout scheduler methods must be functions");
293
- }
294
- binding = {
295
- receiver: scheduler,
296
- now,
297
- setTimeout,
298
- clearTimeout
299
- };
300
- }
301
- const maximum = options?.maxTimerMilliseconds;
302
- if (maximum !== void 0 && typeof maximum !== "number") throw new TypeError("Timeout maxTimerMilliseconds must be a number");
303
- if (maximum !== void 0 && maximum !== Infinity && (!Number.isInteger(maximum) || maximum < 1 || maximum > 2147483647)) {
304
- throw new RangeError("Timeout maxTimerMilliseconds must be an integer from 1 through 2147483647 or Infinity");
305
- }
306
- let replace = false;
307
- if (includeReplace) {
308
- const configured = options?.replace;
309
- if (configured !== void 0 && typeof configured !== "boolean") throw new TypeError("Timeout replace must be a boolean");
310
- replace = configured ?? false;
311
- }
312
- const defaultExecutor = configuredLimits === void 0 && killAfterPolicy === void 0 && invoke === void 0 && scheduler === void 0 && maximum === void 0;
313
- return { defaultExecutor, limits, invoke, killAfterPolicy, scheduler: binding, maxTimerMilliseconds: maximum ?? 2147483647, replace };
314
- }
315
- async function status(configuration, context, bytes, exitCode, stdout = false) {
316
- if (bytes.length > configuration.limits.maxOutputBytes) throw new FsError("EFBIG", { message: "timeout output limit exceeded" });
317
- await writeBytes(stdout ? context.stdout : context.stderr, bytes, context.signal);
318
- return { exitCode };
319
- }
320
- function childInvoker(context, fallback) {
321
- if ("invoke" in context) {
322
- const invoke = context.invoke;
323
- return typeof invoke === "function" ? { invoke, receiver: context } : void 0;
324
- }
325
- return fallback === void 0 ? void 0 : { invoke: fallback, receiver: void 0 };
326
- }
327
- function definition(configuration) {
328
- return Object.freeze({
329
- name: "timeout",
330
- description: "Run a virtual command with a cooperative time limit",
331
- async execute(context) {
332
- context.signal.throwIfAborted();
333
- const originalArgs = context.args;
334
- if (originalArgs.length > configuration.limits.maxArguments) throw new FsError("EFBIG", { message: "timeout argument count limit exceeded" });
335
- const suppliedValues = "argumentValues" in context ? context.argumentValues : void 0;
336
- const ownedArguments = suppliedValues === void 0 ? void 0 : getCommandArguments(context);
337
- let argumentBytes = 0;
338
- for (const argument of ownedArguments?.values ?? originalArgs) {
339
- argumentBytes += shellValueByteLength2(argument);
340
- if (argumentBytes > configuration.limits.maxArgumentBytes) throw new FsError("EFBIG", { message: "timeout argument limit exceeded" });
341
- }
342
- let offset = 0;
343
- let preserveStatus = false;
344
- let verbose = false;
345
- let foreground = false;
346
- let signalNumber = 15;
347
- let killAfterMilliseconds;
348
- while (offset < originalArgs.length) {
349
- const token = originalArgs[offset];
350
- if (token === "--") {
351
- offset++;
352
- break;
353
- }
354
- if (token === "--help") return status(configuration, context, records.help, 0, true);
355
- if (token === "--version") return status(configuration, context, records.version, 0, true);
356
- if (token === "-" || !token.startsWith("-")) break;
357
- if (token === "--verbose") {
358
- verbose = true;
359
- offset++;
360
- continue;
361
- }
362
- if (token === "--foreground") {
363
- foreground = true;
364
- offset++;
365
- continue;
366
- }
367
- if (token === "--preserve-status") {
368
- preserveStatus = true;
369
- offset++;
370
- continue;
371
- }
372
- if (token === "--kill-after" || token.startsWith("--kill-after=")) {
373
- const duration = token === "--kill-after" ? originalArgs[++offset] : token.slice(13);
374
- if (duration === void 0) return status(configuration, context, records.missingDuration, 125);
375
- const killAfter = parseDuration(duration);
376
- if (killAfter.kind === "invalid") return status(configuration, context, records.invalidDuration, 125);
377
- if (killAfter.kind === "overflow") return status(configuration, context, records.durationOverflow, 125);
378
- killAfterMilliseconds = killAfter.milliseconds;
379
- offset++;
380
- continue;
381
- }
382
- if (token === "--signal" || token.startsWith("--signal=")) {
383
- const signalToken = token === "--signal" ? originalArgs[++offset] : token.slice(9);
384
- if (signalToken === void 0) return status(configuration, context, records.invalidSignal, 125);
385
- const parsedSignal = parseSignal(signalToken);
386
- if (parsedSignal === void 0) return status(configuration, context, records.invalidSignal, 125);
387
- signalNumber = parsedSignal;
388
- offset++;
389
- continue;
390
- }
391
- if (!token.startsWith("--")) {
392
- let position = 1;
393
- while (position < token.length) {
394
- const flag = token[position];
395
- if (flag === "v") {
396
- verbose = true;
397
- position++;
398
- continue;
399
- }
400
- if (flag === "f") {
401
- foreground = true;
402
- position++;
403
- continue;
404
- }
405
- if (flag === "p") {
406
- preserveStatus = true;
407
- position++;
408
- continue;
409
- }
410
- if (flag === "k") {
411
- const duration = token.slice(position + 1) || originalArgs[++offset];
412
- if (duration === void 0) return status(configuration, context, records.missingDuration, 125);
413
- const killAfter = parseDuration(duration);
414
- if (killAfter.kind === "invalid") return status(configuration, context, records.invalidDuration, 125);
415
- if (killAfter.kind === "overflow") return status(configuration, context, records.durationOverflow, 125);
416
- killAfterMilliseconds = killAfter.milliseconds;
417
- break;
418
- }
419
- if (flag === "s") {
420
- const signalToken = token.slice(position + 1) || originalArgs[++offset];
421
- if (signalToken === void 0) return status(configuration, context, records.invalidSignal, 125);
422
- const parsedSignal = parseSignal(signalToken);
423
- if (parsedSignal === void 0) return status(configuration, context, records.invalidSignal, 125);
424
- signalNumber = parsedSignal;
425
- break;
426
- }
427
- return status(configuration, context, records.invalidOption, 125);
428
- }
429
- offset++;
430
- continue;
431
- }
432
- return status(configuration, context, records.invalidOption, 125);
433
- }
434
- const durationToken = originalArgs[offset];
435
- if (durationToken === void 0) return status(configuration, context, records.missingDuration, 125);
436
- const parsed = parseDuration(durationToken);
437
- if (parsed.kind === "invalid") return status(configuration, context, records.invalidDuration, 125);
438
- if (parsed.kind === "overflow") return status(configuration, context, records.durationOverflow, 125);
439
- const command = originalArgs[offset + 1];
440
- if (command === void 0) return status(configuration, context, records.missingCommand, 125);
441
- const argumentValues = ownedArguments?.slice(offset + 2);
442
- const args = argumentValues?.args ?? Object.freeze(originalArgs.slice(offset + 2));
443
- const streams = {
444
- ...argumentValues === void 0 ? {} : { argumentValues },
445
- stdin: context.stdin,
446
- ...context.stdinIsDefault === void 0 ? {} : { stdinIsDefault: context.stdinIsDefault },
447
- stdout: context.stdout,
448
- stderr: context.stderr
449
- };
450
- const killAfterPolicy = configuration.killAfterPolicy ?? context.capabilities?.timeoutKillAfterPolicy;
451
- if (killAfterMilliseconds !== void 0 && killAfterMilliseconds !== 0 && parsed.milliseconds !== 0 && parsed.milliseconds !== Infinity) {
452
- context.signal.throwIfAborted();
453
- if (typeof killAfterPolicy !== "function") return status(configuration, context, records.escalationUnavailable, 125);
454
- let result2;
455
- try {
456
- result2 = await killAfterPolicy(context, command, args, { signal: context.signal, ...streams }, Object.freeze({
457
- durationMilliseconds: parsed.milliseconds,
458
- killAfterMilliseconds,
459
- signalNumber,
460
- preserveStatus,
461
- ...foreground ? { foreground: true } : {},
462
- ...verbose ? { verbose: true } : {}
463
- }));
464
- } catch (error) {
465
- context.signal.throwIfAborted();
466
- throw error;
467
- }
468
- context.signal.throwIfAborted();
469
- return result2;
470
- }
471
- const selected = childInvoker(context, configuration.invoke);
472
- if (parsed.milliseconds === 0 || parsed.milliseconds === Infinity) {
473
- if (selected === void 0) return status(configuration, context, records.invokeUnavailable, 125);
474
- context.signal.throwIfAborted();
475
- let result2;
476
- try {
477
- result2 = await Reflect.apply(selected.invoke, selected.receiver, [command, args, { signal: context.signal, ...streams }]);
478
- } catch (error) {
479
- context.signal.throwIfAborted();
480
- throw error;
481
- }
482
- context.signal.throwIfAborted();
483
- return result2;
484
- }
485
- if (selected === void 0) return status(configuration, context, records.invokeUnavailable, 125);
486
- context.signal.throwIfAborted();
487
- const deadline = createDeadline(configuration.scheduler, parsed.milliseconds, configuration.maxTimerMilliseconds, signalNumber !== 0);
488
- context.registerCleanup?.(deadline.retire);
489
- try {
490
- deadline.start();
491
- } catch {
492
- let retirementFailed2 = false;
493
- let retirementFailure2;
494
- try {
495
- await deadline.retire();
496
- } catch (error) {
497
- retirementFailed2 = true;
498
- retirementFailure2 = error;
499
- }
500
- context.signal.throwIfAborted();
501
- if (retirementFailed2) throw retirementFailure2;
502
- return status(configuration, context, records.timerSetupFailed, 125);
503
- }
504
- let returned = false;
505
- let result;
506
- let invocationFailure;
507
- try {
508
- result = await Reflect.apply(selected.invoke, selected.receiver, [command, args, { signal: AbortSignal.any([context.signal, deadline.signal]), ...streams }]);
509
- returned = true;
510
- } catch (error) {
511
- invocationFailure = error;
512
- }
513
- let retirementFailed = false;
514
- let retirementFailure;
515
- try {
516
- await deadline.retire();
517
- } catch (error) {
518
- retirementFailed = true;
519
- retirementFailure = error;
520
- }
521
- context.signal.throwIfAborted();
522
- if (!returned && invocationFailure !== deadline.deadlineReason && invocationFailure !== deadline.timerFailureReason) throw invocationFailure;
523
- if (retirementFailed) throw retirementFailure;
524
- if (verbose && deadline.expired) {
525
- await status(configuration, context, encoder2.encode(`timeout: cooperative deadline expired for command \u2018${command}\u2019
526
- `), 0);
527
- }
528
- if (!returned && invocationFailure === deadline.deadlineReason) return { exitCode: signalNumber === 9 || preserveStatus ? 128 + signalNumber : 124 };
529
- if (deadline.signal.aborted && deadline.signal.reason === deadline.timerFailureReason) return status(configuration, context, records.timerSetupFailed, 125);
530
- if (deadline.expired && (!preserveStatus || signalNumber === 9)) return { exitCode: signalNumber === 9 ? 137 : 124 };
531
- return result;
532
- }
533
- });
534
- }
535
- function createTimeoutCommand(options) {
536
- const configuration = settings(options, false);
537
- const def = definition(configuration);
538
- if (configuration.defaultExecutor) builtInDirectContextExecutors.add(def.execute);
539
- return def;
540
- }
541
- function createTimeoutCommands(options) {
542
- const configuration = settings(options, true);
543
- const def = definition(configuration);
544
- if (configuration.defaultExecutor) builtInDirectContextExecutors.add(def.execute);
545
- return Object.freeze([def]);
546
- }
547
- function evalSyncTimeout(args) {
548
- if (args.length === 1) {
549
- if (args[0] === "--version") return "timeout (virtual-bash cooperative profile)\n";
550
- if (args[0] === "--help") return "Usage: timeout [OPTION] DURATION COMMAND [ARG]...\nRun a virtual-bash command with a cooperative time limit.\n";
551
- }
552
- let i = 0;
553
- let killAfterMs;
554
- while (i < args.length) {
555
- const a = args[i];
556
- if (a === "--") {
557
- i++;
558
- break;
559
- }
560
- if (a === "-" || !a.startsWith("-")) break;
561
- if (a === "--preserve-status" || a === "--foreground" || a === "-v" || a === "--verbose") {
562
- i++;
563
- continue;
564
- }
565
- if (a === "--signal" || a.startsWith("--signal=")) {
566
- const sigTok = a === "--signal" ? args[++i] : a.slice(9);
567
- if (sigTok === void 0 || parseSignal(sigTok) === void 0) return void 0;
568
- i++;
569
- continue;
570
- }
571
- if (a === "--kill-after" || a.startsWith("--kill-after=")) {
572
- const kaTok = a === "--kill-after" ? args[++i] : a.slice(13);
573
- if (kaTok === void 0) return void 0;
574
- const ka = parseDuration(kaTok);
575
- if (ka.kind !== "value") return void 0;
576
- killAfterMs = ka.milliseconds;
577
- i++;
578
- continue;
579
- }
580
- if (!a.startsWith("--")) {
581
- let pos = 1;
582
- let ok = true;
583
- while (pos < a.length) {
584
- const ch = a[pos];
585
- if (ch === "v" || ch === "f" || ch === "p") {
586
- pos++;
587
- continue;
588
- }
589
- if (ch === "s") {
590
- const sigTok = a.slice(pos + 1) || args[++i];
591
- if (sigTok === void 0 || parseSignal(sigTok) === void 0) {
592
- ok = false;
593
- break;
594
- }
595
- break;
596
- }
597
- if (ch === "k") {
598
- const kaTok = a.slice(pos + 1) || args[++i];
599
- if (kaTok === void 0) {
600
- ok = false;
601
- break;
602
- }
603
- const ka = parseDuration(kaTok);
604
- if (ka.kind !== "value") {
605
- ok = false;
606
- break;
607
- }
608
- killAfterMs = ka.milliseconds;
609
- break;
610
- }
611
- ok = false;
612
- break;
613
- }
614
- if (!ok) return void 0;
615
- i++;
616
- continue;
617
- }
618
- return void 0;
619
- }
620
- if (i >= args.length) return void 0;
621
- const durStr = args[i];
622
- const parsed = parseDuration(durStr);
623
- if (parsed.kind !== "value" || parsed.milliseconds <= 0) return void 0;
624
- if (killAfterMs !== void 0 && killAfterMs !== 0 && parsed.milliseconds !== 0 && parsed.milliseconds !== Infinity) {
625
- return void 0;
626
- }
627
- i++;
628
- if (i >= args.length) return void 0;
629
- const subCmd = args[i];
630
- const subArgs = args.slice(i + 1);
631
- if (subCmd === "echo") {
632
- let noNewline = false;
633
- let start = 0;
634
- if (subArgs[0] === "-n") {
635
- if (subArgs[1]?.startsWith("-")) return void 0;
636
- noNewline = true;
637
- start = 1;
638
- } else if (subArgs[0]?.startsWith("-")) return void 0;
639
- return subArgs.slice(start).join(" ") + (noNewline ? "" : "\n");
640
- }
641
- if (subCmd === "true") return "";
642
- if (subCmd === "dirname" && subArgs.length >= 1 && subArgs.every((x) => !x.startsWith("-"))) {
643
- return subArgs.map((p) => {
644
- const s = p.replace(/\/+$/, "");
645
- if (!s) return "/";
646
- const sl = s.lastIndexOf("/");
647
- if (sl < 0) return ".";
648
- return s.slice(0, sl).replace(/\/+$/, "") || "/";
649
- }).join("\n") + "\n";
650
- }
651
- if (subCmd === "basename" && subArgs.length >= 1 && subArgs.length <= 2 && subArgs.every((x) => !x.startsWith("-"))) {
652
- const clean = subArgs[0].replace(/\/+$/, "");
653
- if (!clean) return "/\n";
654
- let base = clean.slice(clean.lastIndexOf("/") + 1);
655
- const suf = subArgs[1];
656
- if (suf && base.length > suf.length && base.endsWith(suf)) base = base.slice(0, -suf.length);
657
- return base + "\n";
658
- }
659
- if (subCmd === "printf" && subArgs.length >= 1) {
660
- const fmt = subArgs[0];
661
- const vals = subArgs.slice(1);
662
- let vIdx = 0;
663
- let res = "";
664
- const applyOnce = () => {
665
- for (let k = 0; k < fmt.length; k++) {
666
- if (fmt[k] === "\\") {
667
- const nxt = fmt[++k];
668
- if (nxt === "n") res += "\n";
669
- else if (nxt === "t") res += " ";
670
- else if (nxt === "\\") res += "\\";
671
- else return false;
672
- } else if (fmt[k] === "%") {
673
- const nxt = fmt[++k];
674
- if (nxt === "%") res += "%";
675
- else if (nxt === "s") res += vals[vIdx++] ?? "";
676
- else if (nxt === "d") {
677
- const raw = vals[vIdx++] ?? "0";
678
- if (!/^-?[0-9]+$/.test(raw)) return false;
679
- res += String(Number(raw));
680
- } else return false;
681
- } else {
682
- res += fmt[k];
683
- }
684
- }
685
- return true;
686
- };
687
- if (vals.length === 0) {
688
- if (!applyOnce()) return void 0;
689
- } else {
690
- while (vIdx < vals.length) {
691
- const before = vIdx;
692
- if (!applyOnce()) return void 0;
693
- if (vIdx === before) break;
694
- }
695
- }
696
- return res;
697
- }
698
- return void 0;
699
- }
700
- function timeoutCommands(options) {
701
- const configuration = settings(options, true);
702
- const commands = Object.freeze([definition(configuration)]);
703
- return {
704
- name: "timeout-commands",
705
- setup(host) {
706
- if (!configuration.replace) for (const command of commands) {
707
- if (host.commands.has(command.name)) throw new Error(`Command already registered: ${command.name}`);
708
- }
709
- for (const command of commands) host.commands.register(command, { replace: configuration.replace });
710
- }
711
- };
712
- }
713
- syncCommandEvaluators.evalSyncTimeout = evalSyncTimeout;
714
-
715
- // packages/safe-bash/src/shell/trap.ts
716
- init_platform();
717
- var idlePortableTrapInstances = /* @__PURE__ */ new WeakMap();
718
- var ignoredPortableTrapSignals = /* @__PURE__ */ new WeakMap();
719
- function captureIgnoredTrapSignals(state) {
720
- const ignored = /* @__PURE__ */ new Set();
721
- for (const entry of state?.entries ?? []) for (const number of ignoredPortableTrapSignals.get(entry.instance)?.() ?? []) ignored.add(number);
722
- return Object.freeze([...ignored]);
723
- }
724
- function isIdlePortableTrapInstance(instance) {
725
- return idlePortableTrapInstances.get(instance)?.() ?? false;
726
- }
727
- function quote(source) {
728
- const bytes = (0, value_exports.shellValueBytes)(source);
729
- const parts = [new TextEncoder().encode("'")];
730
- let start = 0;
731
- for (let index = 0; index < bytes.length; index++) if (bytes[index] === 39) {
732
- parts.push(bytes.subarray(start, index), new TextEncoder().encode("'\\''"));
733
- start = index + 1;
734
- }
735
- parts.push(bytes.subarray(start), new TextEncoder().encode("'"));
736
- const result = new Uint8Array(parts.reduce((length, part) => length + part.byteLength, 0));
737
- let offset = 0;
738
- for (const part of parts) {
739
- result.set(part, offset);
740
- offset += part.byteLength;
741
- }
742
- return result;
743
- }
744
- function portableTrapExtension(configuration = {}) {
745
- const catalog = { ...configuration.signalNames ?? Object.fromEntries(["HUP", "INT", "QUIT", "ILL", "TRAP", "ABRT", "BUS", "FPE", "KILL", "USR1", "SEGV", "USR2", "PIPE", "ALRM", "TERM", "STKFLT", "CHLD", "CONT", "STOP", "TSTP", "TTIN", "TTOU", "URG", "XCPU", "XFSZ", "VTALRM", "PROF", "WINCH", "IO", "PWR", "SYS"].map((name, index) => [`SIG${name}`, index + 1])) };
746
- const names = /* @__PURE__ */ new Map([[0, "EXIT"]]);
747
- const aliases = /* @__PURE__ */ new Map([["EXIT", 0], ["SIGEXIT", 0]]);
748
- for (const [name, number] of Object.entries(catalog)) {
749
- if (!name.startsWith("SIG") || !Number.isSafeInteger(number) || number <= 0 || number > 1024) throw new TypeError("Invalid trap signal catalog");
750
- if (!names.has(number)) names.set(number, name);
751
- aliases.set(name, number);
752
- aliases.set(name.slice(3), number);
753
- }
754
- const pseudoBase = Math.max(...names.keys()) + 1;
755
- for (const [index, name] of ["DEBUG", "ERR", "RETURN"].entries()) {
756
- names.set(pseudoBase + index, name);
757
- aliases.set(name, pseudoBase + index);
758
- aliases.set("SIG" + name, pseudoBase + index);
759
- }
760
- const resolve = (value) => {
761
- const text = String(value).toUpperCase();
762
- const named = aliases.get(text);
763
- if (named !== void 0) return named;
764
- const digits = text[0] === "+" ? text.slice(1) : text;
765
- if (!digits || [...digits].some((character) => character < "0" || character > "9")) return void 0;
766
- const number = Number(digits);
767
- return names.has(number) ? number : void 0;
768
- };
769
- const emptyIgnored = Object.freeze(/* @__PURE__ */ new Set());
770
- const initialIgnored = new Set(configuration.inheritedIgnoredSignals ?? []);
771
- for (const number of initialIgnored) if (!names.has(number) || number === 0 || number === 9 || number === 19) throw new TypeError("Invalid inherited ignored signal");
772
- function instance(actions, errorTrace = false, functionTrace = false, inheritedIgnored = emptyIgnored, extendedDebug = false) {
773
- const options = [{ name: "errtrace", flag: "E", enabled: errorTrace }, { name: "functrace", flag: "T", enabled: functionTrace }];
774
- let running;
775
- let signalScope;
776
- let pending;
777
- let functions;
778
- let sources;
779
- const run = async (number, context) => {
780
- context.signal.throwIfAborted();
781
- const action = actions?.get(number);
782
- if (!action?.active || !shellValueByteLength(action.source) || running?.has(number)) return;
783
- running ??= /* @__PURE__ */ new Set();
784
- running.add(number);
785
- try {
786
- return await context.evaluate(action.source, { name: number === 0 ? "exit trap" : "trap" });
787
- } finally {
788
- running.delete(number);
789
- }
790
- };
791
- const created = {
792
- options,
793
- shoptOptions: [{ name: "extdebug", get enabled() {
794
- return extendedDebug;
795
- }, set enabled(value) {
796
- extendedDebug = value;
797
- for (const option of options) option.enabled = value;
798
- } }],
799
- ...configuration.signalHost ? { async start(context) {
800
- signalScope = context.scope;
801
- let open = true;
802
- const subscription = {};
803
- context.registerCleanup(async () => {
804
- open = false;
805
- pending?.clear();
806
- await subscription.close?.();
807
- });
808
- subscription.close = configuration.signalHost.subscribe((signal) => {
809
- if (!open || context.signal.aborted) return false;
810
- const number = resolve(signal);
811
- if (number === void 0 || number === 0 || number >= pseudoBase || names.get(number) === "SIGKILL" || names.get(number) === "SIGSTOP") return false;
812
- const action = actions?.get(number);
813
- if (!action?.active) return false;
814
- if (shellValueByteLength(action.source)) {
815
- pending ??= /* @__PURE__ */ new Set();
816
- pending.add(number);
817
- context.interruptWait?.((128 + number) % 256);
818
- }
819
- return true;
820
- }, context.scope);
821
- await configuration.signalHost.dispositions?.(context.scope, new Map([...actions ?? []].filter(([number, action]) => number > 0 && number < pseudoBase && action.active).map(([number, action]) => [number, shellValueByteLength(action.source) ? "trap" : "ignore"])));
822
- } } : {},
823
- builtins: [{
824
- name: "trap",
825
- special: true,
826
- async execute(context) {
827
- context.signal.throwIfAborted();
828
- const args = [...context.args];
829
- let print = false, list = false;
830
- while (args[0]?.startsWith("-") && args[0] !== "-") {
831
- const option = args.shift();
832
- if (option === "--") break;
833
- for (const flag of option.slice(1)) {
834
- if (flag === "p") print = true;
835
- else if (flag === "l") list = true;
836
- else {
837
- await context.stderr.write(new TextEncoder().encode(`trap: -${flag}: invalid option
838
- trap: usage: trap [-lp] [arg signal_spec ...]
839
- `));
840
- return 2;
841
- }
842
- }
843
- }
844
- if (list) {
845
- const signals = [...names].filter(([number]) => number > 0 && number < pseudoBase).sort(([left], [right]) => left - right);
846
- let output = "";
847
- for (const [index, [number, name]] of signals.entries()) output += `${String(number).padStart(2, " ")}) ${name}${index % 4 === 3 ? "\n" : " "}`;
848
- if (!output.endsWith("\n")) output += "\n";
849
- await context.stdout.write(new TextEncoder().encode(output));
850
- return 0;
851
- }
852
- if (!args.length) print = true;
853
- let action;
854
- const first = args[0];
855
- const numericReset = !!first && [...first].every((character) => character >= "0" && character <= "9");
856
- if (!print && args.length > 1 && !numericReset) {
857
- action = context.argumentValues[context.args.length - args.length];
858
- args.shift();
859
- }
860
- if (!print && args.length === 1 && args[0] === "-") {
861
- await context.stderr.write(new TextEncoder().encode("trap: usage: trap [-lp] [arg signal_spec ...]\n"));
862
- return 2;
863
- }
864
- if (action !== void 0 && (0, value_exports.shellValueText)(action) !== "-") context.accountSource(action);
865
- const targets = args.length ? args : actions ? [...actions.keys()].sort((left, right) => left - right).map(String) : [];
866
- let status2 = 0;
867
- for (const target of targets) {
868
- const number = resolve(target);
869
- if (number === void 0) {
870
- await context.diagnostic(`trap: ${target}: invalid signal specification`);
871
- status2 = 1;
872
- continue;
873
- }
874
- if (print) {
875
- const current = actions?.get(number);
876
- if (current) {
877
- await context.stdout.write(new TextEncoder().encode("trap -- "));
878
- await context.stdout.write(quote(current.source));
879
- await context.stdout.write(new TextEncoder().encode(` ${names.get(number)}
880
- `));
881
- }
882
- } else if (inheritedIgnored.has(number)) continue;
883
- else if (action === void 0 || (0, value_exports.shellValueText)(action) === "-") actions?.delete(number);
884
- else {
885
- actions ??= /* @__PURE__ */ new Map();
886
- actions.set(number, { source: action, active: true });
887
- }
888
- }
889
- if (!print) await configuration.signalHost?.dispositions?.(signalScope ?? context.scope, new Map([...actions ?? []].filter(([number, action2]) => number > 0 && number < pseudoBase && action2.active).map(([number, action2]) => [number, shellValueByteLength(action2.source) ? "trap" : "ignore"])));
890
- return status2;
891
- }
892
- }],
893
- fork(scope) {
894
- if (!actions?.size && !options[0].enabled && !options[1].enabled && inheritedIgnored.size === 0 && !extendedDebug) {
895
- return instance(void 0, false, false, emptyIgnored, false);
896
- }
897
- const inherited = /* @__PURE__ */ new Map();
898
- for (const [number, action] of actions ?? []) {
899
- if (scope === "process") {
900
- if (number > 0 && number < pseudoBase && !shellValueByteLength(action.source)) inherited.set(number, action);
901
- } else inherited.set(number, { source: action.source, active: !shellValueByteLength(action.source) || names.get(number) === "ERR" && options[0].enabled || ["DEBUG", "RETURN"].includes(names.get(number)) && options[1].enabled });
902
- }
903
- return instance(inherited, scope !== "process" && options[0].enabled, scope !== "process" && options[1].enabled, scope === "process" ? new Set(inherited.keys()) : inheritedIgnored, scope !== "process" && extendedDebug);
904
- },
905
- async event(event, context) {
906
- if (event === "function-enter") {
907
- functions ??= [];
908
- functions.push(new Map(actions));
909
- return;
910
- }
911
- if (event === "function-leave") {
912
- functions?.pop();
913
- return;
914
- }
915
- if (event === "source-enter") {
916
- sources ??= [];
917
- sources.push(actions?.get(aliases.get("DEBUG")));
918
- return;
919
- }
920
- if (event === "source-leave") {
921
- const previous = sources?.pop();
922
- if (previous && !actions?.has(aliases.get("DEBUG"))) {
923
- actions ??= /* @__PURE__ */ new Map();
924
- actions.set(aliases.get("DEBUG"), previous);
925
- }
926
- return;
927
- }
928
- if (pending) for (const number of pending) {
929
- if (running?.has(number)) continue;
930
- pending.delete(number);
931
- await run(number, context);
932
- }
933
- const name = event === "exit" ? "EXIT" : event === "error" ? "ERR" : event === "command" ? "DEBUG" : "RETURN";
934
- if (name === "DEBUG" && context.sourceDepth > 0 && sources?.at(-1) === actions?.get(aliases.get(name)) && !options[1].enabled) return;
935
- const inherited = functions?.at(-1)?.get(aliases.get(name)) === actions?.get(aliases.get(name));
936
- if (context.functionDepth > 0 && inherited && (name === "ERR" && !options[0].enabled || (name === "DEBUG" || name === "RETURN") && !options[1].enabled)) return;
937
- const status2 = await run(aliases.get(name), context);
938
- if (name === "DEBUG" && extendedDebug && status2) return status2 === 2 && (context.functionDepth > 0 || context.sourceDepth > 0) ? { action: "return", status: status2 } : { action: "skip" };
939
- }
940
- };
941
- ignoredPortableTrapSignals.set(created, () => [...actions ?? []].filter(([number, action]) => number > 0 && number < pseudoBase && action.active && !shellValueByteLength(action.source)).map(([number]) => number));
942
- if (!configuration.signalHost) {
943
- idlePortableTrapInstances.set(created, () => (actions?.size ?? 0) === 0 && (pending?.size ?? 0) === 0 && (functions?.length ?? 0) === 0 && (sources?.length ?? 0) === 0);
944
- }
945
- return created;
946
- }
947
- return { name: "trap", runtimeIdentity: command_exports.commandRuntimeIdentity, create: () => instance(
948
- initialIgnored.size ? new Map([...initialIgnored].map((number) => [number, { source: "", active: true }])) : void 0,
949
- false,
950
- false,
951
- initialIgnored
952
- ) };
953
- }
954
- var defaultPortableTrapExtension = portableTrapExtension();
955
-
956
- export {
957
- compareCopyIdentity,
958
- compareObservedEntries,
959
- bytesToHex,
960
- latin1Bytes,
961
- latin1Text,
962
- equalBytes,
963
- compareUtf8,
964
- createTimeoutCommand,
965
- createTimeoutCommands,
966
- evalSyncTimeout,
967
- timeoutCommands,
968
- captureIgnoredTrapSignals,
969
- isIdlePortableTrapInstance,
970
- portableTrapExtension,
971
- defaultPortableTrapExtension
972
- };
973
- //# sourceMappingURL=chunk-RSAWYAEH.js.map