@poe-platform/safe-bash 0.1.756 → 0.1.758

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 (161) hide show
  1. package/dist/image-ast/index.browser.js +76 -23
  2. package/dist/image-ast/index.js +76 -23
  3. package/dist/pdf-ast/ast.d.ts +3 -0
  4. package/dist/pdf-ast/index.js +88 -36
  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-F3J5ZLKF.js → chunk-522TDVLS.js} +1 -1
  8. package/dist/safe-bash/command-chunks/{chunk-VFS2MDAB.js → chunk-6YLD37NH.js} +2 -2
  9. package/dist/safe-bash/command-chunks/{chunk-YI3GKJ7Q.js → chunk-766IWMTB.js} +2 -2
  10. package/dist/safe-bash/command-chunks/{chunk-6AIOGLZO.js → chunk-CE6Z2ULX.js} +2 -2
  11. package/dist/safe-bash/command-chunks/{chunk-KSH2F6RG.js → chunk-CUFCNL6G.js} +1 -1
  12. package/dist/safe-bash/command-chunks/{chunk-5VSGEE6J.js → chunk-F4IQCXZG.js} +5 -5
  13. package/dist/safe-bash/command-chunks/{chunk-F5MORDSU.js → chunk-FDNCPZQS.js} +32 -1
  14. package/dist/safe-bash/command-chunks/{chunk-SG3ZDZCX.js → chunk-FLMLM7Y4.js} +2 -2
  15. package/dist/safe-bash/command-chunks/{chunk-DVZCHNB5.js → chunk-J2NPH7DO.js} +11 -7
  16. package/dist/safe-bash/command-chunks/{chunk-CT3FB722.js → chunk-J7UMKBRK.js} +1 -1
  17. package/dist/safe-bash/command-chunks/{chunk-QQOAK7JQ.js → chunk-KKJCKPTA.js} +1 -1
  18. package/dist/safe-bash/command-chunks/{chunk-7KS6PX4U.js → chunk-KSIGF4AG.js} +3 -3
  19. package/dist/safe-bash/command-chunks/{chunk-KBBI4CSU.js → chunk-L2C5TIII.js} +2 -2
  20. package/dist/safe-bash/command-chunks/{chunk-4HQ7WYSI.js → chunk-MED2BOOW.js} +30 -5
  21. package/dist/safe-bash/command-chunks/{chunk-JRNLDPLI.js → chunk-OZSWW23M.js} +1 -1
  22. package/dist/safe-bash/command-chunks/{chunk-DKQ5REXF.js → chunk-QDPRSPHQ.js} +1 -1
  23. package/dist/safe-bash/command-chunks/{chunk-WOPU2VWF.js → chunk-RID3B5RE.js} +1 -1
  24. package/dist/safe-bash/command-chunks/{chunk-H2FQA4OU.js → chunk-TCAGGM44.js} +72 -19
  25. package/dist/safe-bash/command-chunks/{chunk-REYTQLLB.js → chunk-TT2DMDBY.js} +1 -1
  26. package/dist/safe-bash/command-chunks/{chunk-UGX6MXDD.js → chunk-UIIT4ULR.js} +3 -3
  27. package/dist/safe-bash/command-chunks/{chunk-A6NFLWZI.js → chunk-WKPOGTZY.js} +22 -6
  28. package/dist/safe-bash/command-chunks/{chunk-WI35236J.js → chunk-XYCWDGOG.js} +1 -1
  29. package/dist/safe-bash/command-chunks/{chunk-3DOHQQJR.js → chunk-Y64PA6IA.js} +8 -8
  30. package/dist/safe-bash/command-chunks/{chunk-4F6PG2OT.js → chunk-YJWWRCIG.js} +8 -8
  31. package/dist/safe-bash/command-chunks/{chunk-6Z7OS3TZ.js → chunk-ZP5KDHB4.js} +7 -7
  32. package/dist/safe-bash/commands/pandoc/index.d.ts +1 -1
  33. package/dist/safe-bash/commands/pandoc/index.js +5 -3
  34. package/dist/safe-bash/commands/python/index.browser.js +1 -1
  35. package/dist/safe-bash/commands/python/index.js +6 -0
  36. package/dist/safe-bash/commands/python/jspi.js +11 -2
  37. package/dist/safe-bash/core.browser.js +6 -4
  38. package/dist/safe-bash-command-column/column.js +3 -3
  39. package/dist/safe-bash-command-column/index.js +3 -3
  40. package/dist/safe-bash-command-column/layout.js +2 -2
  41. package/dist/safe-bash-command-csvkit/index.js +8 -8
  42. package/dist/safe-bash-command-factor/command.js +2 -2
  43. package/dist/safe-bash-command-factor/index.js +2 -2
  44. package/dist/safe-bash-command-ffmpeg/index.js +5923 -5893
  45. package/dist/safe-bash-command-imagemagick/index.js +2 -2
  46. package/dist/safe-bash-command-pandoc/command.js +3 -3
  47. package/dist/safe-bash-command-pandoc/index.js +3 -3
  48. package/dist/safe-bash-command-pdfimages/index.js +72 -19
  49. package/dist/safe-bash-command-pdfinfo/index.js +88 -36
  50. package/dist/safe-bash-command-pdftk/index.js +72 -19
  51. package/dist/safe-bash-command-pdftoppm/index.js +88 -36
  52. package/dist/safe-bash-command-pdftotext/index.js +72 -19
  53. package/dist/safe-bash-command-qpdf/index.js +72 -19
  54. package/dist/safe-bash-command-sips/index.js +2 -2
  55. package/dist/safe-bash-command-soffice/index.js +17 -17
  56. package/dist/safe-bash-command-ssconvert/command-bindings.d.ts +18 -0
  57. package/dist/safe-bash-command-ssconvert/command.d.ts +5 -14
  58. package/dist/safe-bash-command-ssconvert/commands.d.ts +6 -0
  59. package/dist/safe-bash-command-ssconvert/commands.js +871 -0
  60. package/dist/safe-bash-command-ssconvert/core.js +8 -8
  61. package/dist/safe-bash-command-ssconvert/formats/csv.js +9 -9
  62. package/dist/safe-bash-command-ssconvert/formats/ods.js +8 -8
  63. package/dist/safe-bash-command-ssconvert/formats/spreadsheetml.js +1 -1
  64. package/dist/safe-bash-command-ssconvert/formats/xls.js +9 -8
  65. package/dist/safe-bash-command-ssconvert/formats/xlsx.js +8 -8
  66. package/dist/safe-bash-command-ssconvert/index.js +376 -236
  67. package/dist/safe-bash-command-wkhtmltopdf/index.js +72 -19
  68. package/dist/safe-bash-command-yq/index.js +4 -4
  69. package/dist/safe-bash-compression-engine/files.js +2 -2
  70. package/dist/safe-bash-compression-engine/operand.js +4 -4
  71. package/dist/safe-bash-contracts/filesystem-descriptor.js +1 -1
  72. package/dist/safe-bash-contracts/filesystem-output.js +1 -1
  73. package/dist/safe-bash-markdown-engine/commonmark-blocks.js +4 -4
  74. package/dist/safe-bash-markdown-engine/commonmark-inlines.js +4 -4
  75. package/dist/safe-bash-markdown-engine/commonmark-syntax.js +2 -2
  76. package/dist/safe-bash-markdown-engine/gfm-syntax.js +3 -3
  77. package/dist/safe-bash-markdown-engine/index.js +7 -7
  78. package/dist/safe-bash-mcp/index.js +4 -4
  79. package/dist/safe-bash-query-engine/index.js +5 -5
  80. package/dist/safe-bash-query-engine/interpreter.js +4 -4
  81. package/dist/safe-bash-query-engine/query-core.js +5 -5
  82. package/dist/spreadsheet-engine/formulas/ast.d.ts +13 -0
  83. package/dist/spreadsheet-engine/formulas/conventions.js +1 -1
  84. package/dist/spreadsheet-engine/formulas/dependencies.js +2 -2
  85. package/dist/spreadsheet-engine/formulas/evaluator.js +2 -2
  86. package/dist/spreadsheet-engine/formulas/named-expressions.d.ts +2 -2
  87. package/dist/spreadsheet-engine/formulas/named-expressions.js +31 -5
  88. package/dist/spreadsheet-engine/formulas/parser.js +34 -0
  89. package/dist/spreadsheet-engine/formulas/rewriting.js +19 -1
  90. package/dist/spreadsheet-engine/formulas/serialization.js +6 -0
  91. package/dist/spreadsheet-format-xls/biff-write-formulas.js +2 -0
  92. package/dist/xlsx-ast/formula-semantics.js +2 -0
  93. package/package.json +6 -2
  94. package/third-party/pdf-ast/THIRD_PARTY_NOTICES.md +16 -0
  95. package/dist/safe-bash/chunks/browser-ECQX6GMK.js +0 -6766
  96. package/dist/safe-bash/chunks/bz2-4OP3OWW3.js +0 -8
  97. package/dist/safe-bash/chunks/chunk-22XPAAOI.js +0 -173
  98. package/dist/safe-bash/chunks/chunk-44WUNUPV.js +0 -649
  99. package/dist/safe-bash/chunks/chunk-4E3SGG37.js +0 -876
  100. package/dist/safe-bash/chunks/chunk-4QTSSQKP.js +0 -898
  101. package/dist/safe-bash/chunks/chunk-5UVGPVXP.js +0 -410
  102. package/dist/safe-bash/chunks/chunk-64OE6Q6X.js +0 -3487
  103. package/dist/safe-bash/chunks/chunk-6IIFUPN2.js +0 -1526
  104. package/dist/safe-bash/chunks/chunk-BENDLTQD.js +0 -7065
  105. package/dist/safe-bash/chunks/chunk-BMO5LWEX.js +0 -534
  106. package/dist/safe-bash/chunks/chunk-BPMCPTNP.js +0 -1920
  107. package/dist/safe-bash/chunks/chunk-BRJTAWP5.js +0 -2955
  108. package/dist/safe-bash/chunks/chunk-C3GEIN7Q.js +0 -20054
  109. package/dist/safe-bash/chunks/chunk-CBVANNKK.js +0 -174814
  110. package/dist/safe-bash/chunks/chunk-CEWCRI6H.js +0 -2813
  111. package/dist/safe-bash/chunks/chunk-CGL53DQQ.js +0 -37
  112. package/dist/safe-bash/chunks/chunk-CTYJJD4O.js +0 -869
  113. package/dist/safe-bash/chunks/chunk-CWSS4MQA.js +0 -7
  114. package/dist/safe-bash/chunks/chunk-DLIGMTCP.js +0 -3266
  115. package/dist/safe-bash/chunks/chunk-EMAJ7WUW.js +0 -1031
  116. package/dist/safe-bash/chunks/chunk-FDKIZ2IJ.js +0 -1950
  117. package/dist/safe-bash/chunks/chunk-FZWJ2A7V.js +0 -3093
  118. package/dist/safe-bash/chunks/chunk-G2VCIF2J.js +0 -22
  119. package/dist/safe-bash/chunks/chunk-GVKBUQDX.js +0 -2649
  120. package/dist/safe-bash/chunks/chunk-IO2OGW3E.js +0 -28051
  121. package/dist/safe-bash/chunks/chunk-ISCZG7WA.js +0 -2648
  122. package/dist/safe-bash/chunks/chunk-JCN3FXLP.js +0 -38983
  123. package/dist/safe-bash/chunks/chunk-KJHDD4A2.js +0 -759
  124. package/dist/safe-bash/chunks/chunk-LB6HVRXS.js +0 -857
  125. package/dist/safe-bash/chunks/chunk-LLWAJOZH.js +0 -15
  126. package/dist/safe-bash/chunks/chunk-LMUKYZIJ.js +0 -708
  127. package/dist/safe-bash/chunks/chunk-M5SCNKIK.js +0 -2012
  128. package/dist/safe-bash/chunks/chunk-MJPFHANT.js +0 -3350
  129. package/dist/safe-bash/chunks/chunk-MZQW2DOL.js +0 -82
  130. package/dist/safe-bash/chunks/chunk-NB2V7EOY.js +0 -1348
  131. package/dist/safe-bash/chunks/chunk-NJVGOIYN.js +0 -17
  132. package/dist/safe-bash/chunks/chunk-OLNZHDIQ.js +0 -5141
  133. package/dist/safe-bash/chunks/chunk-OSUXMC43.js +0 -2317
  134. package/dist/safe-bash/chunks/chunk-OUUVROTM.js +0 -38
  135. package/dist/safe-bash/chunks/chunk-PA6GYKBQ.js +0 -151
  136. package/dist/safe-bash/chunks/chunk-PEFHZ226.js +0 -6957
  137. package/dist/safe-bash/chunks/chunk-QBB5P5KW.js +0 -4839
  138. package/dist/safe-bash/chunks/chunk-RSAWYAEH.js +0 -973
  139. package/dist/safe-bash/chunks/chunk-UWLYRWT4.js +0 -739
  140. package/dist/safe-bash/chunks/chunk-V463NBQH.js +0 -13
  141. package/dist/safe-bash/chunks/chunk-WPUALYUS.js +0 -843
  142. package/dist/safe-bash/chunks/chunk-XHKFSRGU.js +0 -5747
  143. package/dist/safe-bash/chunks/chunk-XHRCLZ3N.js +0 -13391
  144. package/dist/safe-bash/chunks/chunk-XPF5XHLY.js +0 -15
  145. package/dist/safe-bash/chunks/chunk-ZBFOWARG.js +0 -305
  146. package/dist/safe-bash/chunks/chunk-ZG7GWQ5P.js +0 -1859
  147. package/dist/safe-bash/chunks/model-store-EIY3ZQLZ.js +0 -10
  148. package/dist/safe-bash/chunks/pdf-renderer-CMF3CSVU.js +0 -22
  149. package/dist/safe-bash/chunks/pptx-ZL6L7KP2-O425BFIU.js +0 -30658
  150. package/dist/safe-bash/chunks/src-HHEPGR7U.js +0 -18969
  151. package/dist/safe-bash/chunks/src-MXIKQCIC.js +0 -187
  152. package/dist/safe-bash/chunks/usage-6TGVA2OM.js +0 -35
  153. package/dist/safe-bash/chunks/xz-EGQGQUEI.js +0 -8
  154. package/dist/safe-bash/chunks/xz-K2E2WLM6.js +0 -9
  155. package/dist/safe-bash/chunks/zstd-6JBLP5EF.js +0 -8
  156. package/dist/safe-bash/git_rust-C3QYOAZL.wasm +0 -0
  157. package/dist/safe-bash/command-chunks/{chunk-OQVIJMBY.js → chunk-7HINP7ZK.js} +4 -4
  158. package/dist/safe-bash/command-chunks/{chunk-XAYEDOV5.js → chunk-CG4JSOK2.js} +3 -3
  159. package/dist/safe-bash/command-chunks/{chunk-YIK4ZYQ4.js → chunk-DC52GWRK.js} +9 -9
  160. package/dist/safe-bash/command-chunks/{chunk-TOTZFBDT.js → chunk-TKACIO4X.js} +4 -4
  161. package/dist/safe-bash/command-chunks/{chunk-VTWKS4RM.js → chunk-WF2LSKMI.js} +3 -3
@@ -1,3093 +0,0 @@
1
- import {
2
- Interpreter,
3
- getLastFastSelectProjectSavedOutBuf,
4
- jsonValues,
5
- moduleProgram,
6
- parse,
7
- parseJson,
8
- rawValues,
9
- sortObjectKeys,
10
- stringify,
11
- tryProcessFlatJsonChunkSync,
12
- tryProcessFlatSelectProjectChunkSync,
13
- tryWriteCompactSync
14
- } from "./chunk-OLNZHDIQ.js";
15
- import {
16
- Budget,
17
- JqError,
18
- JqHalt,
19
- JqLimitError,
20
- copyObject,
21
- interruptible,
22
- object,
23
- put,
24
- resolveJqLimits,
25
- truth,
26
- wellFormed
27
- } from "./chunk-44WUNUPV.js";
28
- import {
29
- RESOLVED_EXIT_ZERO,
30
- builtInDirectContextExecutors,
31
- bytesFrom,
32
- concatBytes,
33
- filledBytes,
34
- inputRequirements,
35
- path_exports,
36
- utf8ByteLength
37
- } from "./chunk-ISCZG7WA.js";
38
- import {
39
- init_platform
40
- } from "./chunk-ZG7GWQ5P.js";
41
-
42
- // packages/safe-bash/src/commands/xml/index.ts
43
- init_platform();
44
-
45
- // packages/safe-bash-command-xmllint/src/index.ts
46
- init_platform();
47
-
48
- // packages/safe-bash-command-xq/src/index.ts
49
- init_platform();
50
-
51
- // packages/safe-bash-xml-engine/src/limits.ts
52
- init_platform();
53
- import { hasYieldCheckpoint, monotonicNow, runYieldCheckpoint, yieldTurn } from "../../safe-bash-contracts/yield.js";
54
- var defaultXmlQueryLimits = Object.freeze({
55
- maxInputBytes: Infinity,
56
- maxOutputBytes: Infinity,
57
- maxSourceBytes: Infinity,
58
- maxDepth: Infinity,
59
- maxNodes: Infinity,
60
- maxAttributes: Infinity,
61
- maxAttributesPerElement: Infinity,
62
- maxNamespaces: Infinity,
63
- maxSteps: Infinity,
64
- maxResults: Infinity
65
- });
66
- var XmlQueryError = class extends Error {
67
- constructor(message, status) {
68
- super(message);
69
- this.status = status;
70
- }
71
- status;
72
- };
73
- var XmlQueryLimitError = class extends XmlQueryError {
74
- constructor(name) {
75
- super(`${name} limit exceeded`, 5);
76
- }
77
- };
78
- function resolveXmlQueryLimits(options = {}) {
79
- const limits = { ...defaultXmlQueryLimits, ...options };
80
- for (const [name, value] of Object.entries(limits)) {
81
- if (!Object.hasOwn(defaultXmlQueryLimits, name) || value !== Infinity && !Number.isSafeInteger(value) || value < 1) {
82
- throw new RangeError(`${name} must be a positive safe integer XML limit`);
83
- }
84
- }
85
- return Object.freeze(limits);
86
- }
87
- var XmlBudget = class {
88
- constructor(limits, signal, checkpointTurn) {
89
- this.limits = limits;
90
- this.signal = signal;
91
- this.checkpointTurn = checkpointTurn;
92
- this.aborted = Boolean(signal?.aborted);
93
- this.pollSignal = Boolean(signal && (typeof signal.addEventListener !== "function" || Object.prototype.hasOwnProperty.call(signal, "aborted")));
94
- if (signal && !this.aborted && !this.pollSignal) {
95
- signal.addEventListener("abort", () => {
96
- this.aborted = true;
97
- }, { once: true });
98
- }
99
- }
100
- limits;
101
- signal;
102
- checkpointTurn;
103
- steps = 0;
104
- checkpoint = 0;
105
- checkpointCount = 0;
106
- lastYield = monotonicNow();
107
- aborted = false;
108
- pollSignal;
109
- outputBytes = 0;
110
- inputBytes = 0;
111
- tick(work = 1) {
112
- if (this.aborted || this.pollSignal && this.signal.aborted) this.signal.throwIfAborted();
113
- this.steps += work;
114
- if (this.steps > this.limits.maxSteps) throw new XmlQueryLimitError("maxSteps");
115
- this.checkpoint += work;
116
- if (this.checkpoint >= 16384) {
117
- this.checkpoint = 0;
118
- const now = monotonicNow();
119
- if ((++this.checkpointCount & 15) === 0 || this.checkpointTurn !== yieldTurn || hasYieldCheckpoint(this.signal) || now - this.lastYield >= 16) {
120
- this.lastYield = now;
121
- return this.checkpointTurn(this.signal).then(() => {
122
- this.lastYield = monotonicNow();
123
- });
124
- }
125
- runYieldCheckpoint(this.signal);
126
- }
127
- }
128
- results(size) {
129
- if (size > this.limits.maxResults) throw new XmlQueryLimitError("maxResults");
130
- }
131
- };
132
-
133
- // packages/safe-bash-command-xq/src/index.ts
134
- import { parseXmlSteps, XmlLimitError } from "@poe-platform/safe-fs/core";
135
- import { getCommandArguments, toByteSource as toByteSource3 } from "../../safe-bash-contracts/index.js";
136
-
137
- // packages/safe-bash-xml-engine/src/io.ts
138
- init_platform();
139
- import {
140
- FsError,
141
- readBytes,
142
- toByteSource
143
- } from "../../safe-bash-contracts/index.js";
144
- async function readXmlInput(context, file, budget, runtime2) {
145
- let source = context.stdin;
146
- if (file !== void 0 && file !== "-") {
147
- const path = runtime2.pathOf(context, file);
148
- const capabilities = context.fs.capabilitiesFor ? await runtime2.interruptible(
149
- () => context.fs.capabilitiesFor(path, { signal: context.signal }),
150
- context.signal
151
- ) : context.fs.capabilities;
152
- context.signal.throwIfAborted();
153
- if (context.fs.readStream && capabilities.streamingRead !== false)
154
- source = context.fs.readStream(path, { signal: context.signal });
155
- else {
156
- try {
157
- source = toByteSource(
158
- await runtime2.interruptible(
159
- () => context.fs.readFile(path, {
160
- signal: context.signal,
161
- ...Number.isFinite(budget.limits.maxInputBytes) ? { maxBytes: budget.limits.maxInputBytes } : {}
162
- }),
163
- context.signal
164
- )
165
- );
166
- } catch (error) {
167
- context.signal.throwIfAborted();
168
- if (error instanceof FsError && error.code === "EFBIG")
169
- throw new XmlQueryLimitError("maxInputBytes");
170
- throw error;
171
- }
172
- }
173
- }
174
- const parts = [];
175
- const decoder = new TextDecoder("utf-8", { fatal: true });
176
- let chunksSinceYield = 0;
177
- for await (const chunk of readBytes(source, context.signal)) {
178
- const checkpoint = budget.tick();
179
- chunksSinceYield++;
180
- if (checkpoint) {
181
- await checkpoint;
182
- chunksSinceYield = 0;
183
- } else if (chunksSinceYield >= 1024) {
184
- await runtime2.yieldTurn(context.signal);
185
- chunksSinceYield = 0;
186
- }
187
- budget.inputBytes += chunk.byteLength;
188
- if (budget.inputBytes > budget.limits.maxInputBytes)
189
- throw new XmlQueryLimitError("maxInputBytes");
190
- for (let offset = 0; offset < chunk.length; offset += 4096) {
191
- await budget.tick(Math.min(4096, chunk.length - offset));
192
- try {
193
- parts.push(decoder.decode(chunk.subarray(offset, offset + 4096), { stream: true }));
194
- } catch {
195
- throw new XmlQueryError("XML input must be UTF-8", 1);
196
- }
197
- }
198
- }
199
- try {
200
- parts.push(decoder.decode());
201
- } catch {
202
- throw new XmlQueryError("XML input must be UTF-8", 1);
203
- }
204
- return parts.join("");
205
- }
206
-
207
- // packages/safe-bash-command-xq/src/index.ts
208
- import { yieldTurn as yieldTurn2 } from "../../safe-bash-contracts/yield.js";
209
- import { shellValueByteLength } from "../../safe-bash-contracts/value.js";
210
- import { writeDiagnostic as writeDiagnostic2 } from "../../safe-bash-contracts/escaping.js";
211
-
212
- // packages/safe-bash-command-jq/src/jq.ts
213
- init_platform();
214
- import { FsError as FsError3, readBytes as readBytes3, toByteSource as toByteSource2, writeBytes } from "../../safe-bash-contracts/index.js";
215
- import { getLastReadMemoryFileSourceRef, tryReadMemoryFileViewSync as tryReadMemoryFileViewSync2, tryResolveMemoryDevicePath as tryResolveMemoryDevicePath2 } from "@poe-platform/safe-fs/core";
216
- import { getRuntimeBackingFileSystem as getRuntimeBackingFileSystem2 } from "../../safe-bash-contracts/runtime-control.js";
217
-
218
- // packages/safe-bash-io-engine/src/commands/search/requirements.ts
219
- init_platform();
220
- import { FsError as FsError2 } from "../../safe-bash-contracts/errors.js";
221
- import { readBytes as readBytes2 } from "../../safe-bash-contracts/io.js";
222
- import { assertCommandRequirements } from "../../safe-bash-contracts/command-requirements.js";
223
- import { tryReadMemoryFileViewSync, tryResolveMemoryDevicePath } from "@poe-platform/safe-fs/core";
224
- import { getRuntimeBackingFileSystem } from "../../safe-bash-contracts/runtime-control.js";
225
- var grepRequirements = [
226
- ...inputRequirements,
227
- { id: "metadata", description: "Inspect recursive grep operands", capabilities: ["stat"] },
228
- { id: "directory", description: "Walk grep directories", capabilities: ["readdir", "realpath"] },
229
- { id: "pattern-file", description: "Read grep pattern files (-f)", capabilities: [], anyOf: [["streamingRead"], ["read"]] }
230
- ];
231
- var searchRequirements = [
232
- ...inputRequirements,
233
- { id: "metadata", description: "Inspect named search operands", capabilities: ["stat"] },
234
- { id: "pattern-file", description: "Read rg pattern files (-f)", capabilities: ["read"] },
235
- { id: "directory", description: "Walk directories, including --files", capabilities: ["stat", "readdir", "realpath"] },
236
- { id: "canonical", description: "Resolve followed directory links for loop detection", capabilities: ["realpath"] },
237
- { id: "ignore-file", description: "Read directory ignore files unless disabled", capabilities: ["read"] }
238
- ];
239
- var sedRequirements = [
240
- ...inputRequirements,
241
- { id: "script-file", description: "Read sed program files (-f)", capabilities: ["read"] },
242
- { id: "script-read", description: "Read files referenced by sed r instructions", capabilities: [], anyOf: [["streamingRead"], ["read"]] },
243
- { id: "script-output", description: "Truncate and append files referenced by sed w instructions", capabilities: ["write", "append"], mutates: true },
244
- { id: "in-place", description: "Inspect and conditionally rewrite retained files (-i)", capabilities: ["stat", "write", "retainedRead", "atomicFileMutation"], mutates: true },
245
- { id: "backup", description: "Conditionally write retained original bytes to backups (-iSUFFIX)", capabilities: ["write", "atomicFileMutation"], mutates: true }
246
- ];
247
- async function assertPathRequirements(context, requirements, modes, paths) {
248
- if (!paths.length) return;
249
- assertCommandRequirements(context, requirements, modes);
250
- if (!context.fs.capabilitiesFor) return;
251
- const backing = getRuntimeBackingFileSystem(context.fs);
252
- if (backing !== void 0 && backing.capabilitiesFor === void 0) {
253
- let allSafe = true;
254
- for (let i = 0; i < paths.length; i++) {
255
- if (tryResolveMemoryDevicePath(backing, (0, path_exports.pathOf)(context, paths[i])) === void 0) {
256
- allSafe = false;
257
- break;
258
- }
259
- }
260
- if (allSafe) return;
261
- }
262
- for (const path of new Set(paths)) {
263
- try {
264
- const capabilities = await context.fs.capabilitiesFor((0, path_exports.pathOf)(context, path), { signal: context.signal });
265
- assertCommandRequirements(context, requirements, modes, capabilities);
266
- } catch (error) {
267
- context.signal.throwIfAborted();
268
- if (!["ENOENT", "ENOTDIR"].includes(error.code ?? "")) throw error;
269
- }
270
- }
271
- }
272
- var SYNC_DONE_RESULT = Object.freeze({ value: void 0, done: true });
273
- var RESOLVED_DONE_RESULT = Promise.resolve(SYNC_DONE_RESULT);
274
- function createSyncSingleChunkByteSource(bytes, signal) {
275
- let consumed = false;
276
- return {
277
- [Symbol.asyncIterator]() {
278
- return this;
279
- },
280
- tryNextSync() {
281
- signal.throwIfAborted();
282
- if (consumed) return SYNC_DONE_RESULT;
283
- consumed = true;
284
- return bytes.byteLength > 0 ? { value: bytes, done: false } : SYNC_DONE_RESULT;
285
- },
286
- next() {
287
- try {
288
- signal.throwIfAborted();
289
- if (consumed) return RESOLVED_DONE_RESULT;
290
- consumed = true;
291
- return bytes.byteLength > 0 ? Promise.resolve({ value: bytes, done: false }) : RESOLVED_DONE_RESULT;
292
- } catch (err) {
293
- return Promise.reject(err);
294
- }
295
- },
296
- return() {
297
- consumed = true;
298
- return RESOLVED_DONE_RESULT;
299
- }
300
- };
301
- }
302
- function requiredFileInput(context, requirements, mode, file, maxBytes) {
303
- if (maxBytes === Infinity) {
304
- const fastMemFs = context._fastMemoryBackingFs;
305
- if (fastMemFs !== void 0 && fastMemFs.capabilitiesFor === void 0 && context._cachedInputBudget === void 0 && !Object.prototype.hasOwnProperty.call(fastMemFs, "readStream") && !Object.prototype.hasOwnProperty.call(fastMemFs, "readFile")) {
306
- const path2 = (0, path_exports.pathOf)(context, file);
307
- if (path2 !== "/dev" && !path2.startsWith("/dev/")) {
308
- try {
309
- const bytes = tryReadMemoryFileViewSync(fastMemFs, path2, void 0, context.signal);
310
- if (bytes !== void 0) {
311
- context._chargeFastFsOp?.();
312
- return createSyncSingleChunkByteSource(bytes, context.signal);
313
- }
314
- } catch {
315
- }
316
- }
317
- }
318
- const path = (0, path_exports.pathOf)(context, file);
319
- const backing = getRuntimeBackingFileSystem(context.fs);
320
- if (backing !== void 0 && backing.capabilitiesFor === void 0 && path !== "/dev" && !path.startsWith("/dev/") && context.fs.readStream && context.fs.capabilities.streamingRead !== false && Object.getPrototypeOf(backing)?.constructor?.name === "MemoryFileSystem" && !Object.prototype.hasOwnProperty.call(backing, "readStream")) {
321
- assertCommandRequirements(context, requirements, [mode]);
322
- return context.fs.readStream(path, { signal: context.signal });
323
- }
324
- }
325
- return requiredFileInputSlow(context, requirements, mode, file, maxBytes);
326
- }
327
- async function* requiredFileInputSlow(context, requirements, mode, file, maxBytes) {
328
- assertCommandRequirements(context, requirements, [mode]);
329
- const path = (0, path_exports.pathOf)(context, file);
330
- let capabilities = context.fs.capabilities;
331
- if (context.fs.capabilitiesFor) {
332
- const backing = getRuntimeBackingFileSystem(context.fs);
333
- if (backing === void 0 || backing.capabilitiesFor !== void 0 || tryResolveMemoryDevicePath(backing, path) === void 0) {
334
- capabilities = await context.fs.capabilitiesFor(path, { signal: context.signal });
335
- assertCommandRequirements(context, requirements, [mode], capabilities);
336
- }
337
- }
338
- if (context.fs.readStream && capabilities.streamingRead !== false && context.fs.capabilities.streamingRead !== false) {
339
- let emitted = false;
340
- let reading = true;
341
- let bytes = 0;
342
- try {
343
- for await (const chunk of readBytes2(context.fs.readStream(path, { signal: context.signal }), context.signal)) {
344
- reading = false;
345
- if (chunk.byteLength > maxBytes - bytes) throw new FsError2("EFBIG", { syscall: "read", path, message: "input file byte limit exceeded" });
346
- bytes += chunk.byteLength;
347
- if (chunk.byteLength) emitted = true;
348
- yield chunk;
349
- reading = true;
350
- }
351
- return;
352
- } catch (error) {
353
- context.signal.throwIfAborted();
354
- if (!reading || emitted || !(error instanceof FsError2) || error.code !== "ENOTSUP") throw error;
355
- }
356
- }
357
- if (capabilities.read !== false && context.fs.capabilities.read !== false) {
358
- yield await context.fs.readFile(path, { signal: context.signal, ...Number.isFinite(maxBytes) ? { maxBytes } : {} });
359
- return;
360
- }
361
- throw new FsError2("ENOTSUP", { syscall: "readFile", path });
362
- }
363
-
364
- // packages/safe-bash-command-jq/src/jq.ts
365
- import { joinPath } from "../../safe-bash-contracts/path.js";
366
- import { escapeText, writeDiagnostic } from "../../safe-bash-contracts/escaping.js";
367
- import { isSyncResolved } from "../../safe-bash-contracts/runtime-control.js";
368
- var DEFAULT_INTERPRETER_RUN = Interpreter.prototype.run;
369
- var JQ_LONG_FLAGS = {
370
- "--raw-output": "r",
371
- "--raw-input": "R",
372
- "--join-output": "j",
373
- "--compact-output": "c",
374
- "--sort-keys": "S",
375
- "--slurp": "s",
376
- "--null-input": "n",
377
- "--exit-status": "e",
378
- "--ascii-output": "a",
379
- "--color-output": "C",
380
- "--monochrome-output": "M"
381
- };
382
- var jqAstCache = /* @__PURE__ */ new Map();
383
- var NEVER_ABORTED_SIGNAL = Object.freeze({
384
- aborted: false,
385
- reason: void 0,
386
- onabort: null,
387
- throwIfAborted() {
388
- },
389
- addEventListener() {
390
- },
391
- removeEventListener() {
392
- },
393
- dispatchEvent() {
394
- return true;
395
- }
396
- });
397
- var OUT_BUF_SIZE = 64 * 1024;
398
- var sharedJqOutBuf = null;
399
- var sharedJqOutBufInUse = false;
400
- var EMPTY_VARS_MAP = /* @__PURE__ */ new Map();
401
- var sharedFastBudget;
402
- var sharedFastInterpreter;
403
- var sharedFastInUse = false;
404
- var sharedFastJqAst;
405
- var sharedFastJqLimits;
406
- var sharedFastJqOutPos = 0;
407
- var sharedFastJqAborted = false;
408
- function sharedFastJqOnValue(input) {
409
- const interpreter = sharedFastInterpreter;
410
- const budget = sharedFastBudget;
411
- const limits = sharedFastJqLimits;
412
- const outBuf = sharedJqOutBuf;
413
- const syncResults = interpreter.tryRunSync(sharedFastJqAst, input);
414
- if (syncResults === void 0) {
415
- sharedFastJqAborted = true;
416
- return Promise.resolve();
417
- }
418
- for (let i = 0; i < syncResults.length; i++) {
419
- const result = syncResults[i];
420
- if (budget.needsYield() || budget.results + 1 > budget.maxResultsSmi && budget.results + 1 > limits.maxResults) {
421
- sharedFastJqAborted = true;
422
- return Promise.resolve();
423
- }
424
- const remSmi = budget.maxOutputBytesSmi - budget.outputBytes;
425
- const maxChunkSmi = remSmi > 1 ? remSmi - 1 : limits.maxOutputBytes === Infinity ? 1073741823 : Math.max(0, limits.maxOutputBytes - budget.outputBytes - 1);
426
- const outPos = sharedFastJqOutPos;
427
- const newPos = tryWriteCompactSync(result, budget, outBuf, outPos, "\n", maxChunkSmi, interpreter.getScratchKeys(result));
428
- if (newPos < 0) {
429
- sharedFastJqAborted = true;
430
- return Promise.resolve();
431
- }
432
- const chunkLen = newPos - outPos;
433
- if (chunkLen > remSmi && chunkLen > limits.maxOutputBytes - budget.outputBytes) {
434
- sharedFastJqAborted = true;
435
- return Promise.resolve();
436
- }
437
- budget.results++;
438
- budget.outputBytes += chunkLen;
439
- sharedFastJqOutPos = newPos;
440
- }
441
- interpreter.releaseScratch();
442
- return void 0;
443
- }
444
- function getFastSelectProjectPlan(ast) {
445
- const cached = ast._fastSelectProjectPlan;
446
- if (cached !== void 0) return cached;
447
- let condKey;
448
- let objAst = ast;
449
- if (ast.kind === "binary" && ast.operator === "|") {
450
- const left = ast.left;
451
- if (left.kind !== "call" || left.name !== "select" || left.args.length !== 1) {
452
- ast._fastSelectProjectPlan = null;
453
- return null;
454
- }
455
- const arg0 = left.args[0];
456
- if (arg0.kind === "index" && arg0.base.kind === "identity" && arg0.index.kind === "literal" && typeof arg0.index.value === "string") {
457
- condKey = arg0.index.value;
458
- } else if (arg0.kind === "binary" && arg0.operator === "==" && arg0.left.kind === "index" && arg0.left.base.kind === "identity" && arg0.left.index.kind === "literal" && typeof arg0.left.index.value === "string" && arg0.right.kind === "literal" && arg0.right.value === true) {
459
- condKey = arg0.left.index.value;
460
- } else {
461
- ast._fastSelectProjectPlan = null;
462
- return null;
463
- }
464
- objAst = ast.right;
465
- }
466
- if (objAst.kind !== "object" || objAst.fields.length < 1 || objAst.fields.length > 16) {
467
- ast._fastSelectProjectPlan = null;
468
- return null;
469
- }
470
- const outKeys = [];
471
- const srcKeys = [];
472
- for (let i = 0; i < objAst.fields.length; i++) {
473
- const f = objAst.fields[i];
474
- if (f.key.kind !== "literal" || typeof f.key.value !== "string") {
475
- ast._fastSelectProjectPlan = null;
476
- return null;
477
- }
478
- const k = f.key.value;
479
- if (!k || k === "__proto__" || k.charCodeAt(0) >= 48 && k.charCodeAt(0) <= 57 || outKeys.includes(k)) {
480
- ast._fastSelectProjectPlan = null;
481
- return null;
482
- }
483
- for (let ci = 0; ci < k.length; ci++) {
484
- const c = k.charCodeAt(ci);
485
- if (c < 32 || c >= 127 || c === 34 || c === 92) {
486
- ast._fastSelectProjectPlan = null;
487
- return null;
488
- }
489
- }
490
- let sk;
491
- if (f.value === void 0) {
492
- sk = k;
493
- } else if (f.value.kind === "index" && f.value.base.kind === "identity" && f.value.index.kind === "literal" && typeof f.value.index.value === "string") {
494
- sk = f.value.index.value;
495
- } else {
496
- ast._fastSelectProjectPlan = null;
497
- return null;
498
- }
499
- outKeys.push(k);
500
- srcKeys.push(sk);
501
- }
502
- const plan = { condKey, outKeys, srcKeys, cachedSchemaPlan: void 0 };
503
- ast._fastSelectProjectPlan = plan;
504
- return plan;
505
- }
506
- function tryExecuteJqFastSync(context, limits) {
507
- if (sharedFastInUse || sharedJqOutBufInUse) return void 0;
508
- const args = context.args;
509
- if (args.length !== 3 || args[0] !== "-c") return void 0;
510
- const source = args[1];
511
- const file = args[2];
512
- if (source.startsWith("-") || file.startsWith("-") || file === "-" || source.includes("$")) return void 0;
513
- let cachedAst = jqAstCache.get(source);
514
- if (!cachedAst && (limits.maxSourceBytes < source.length * 4 || limits.maxAstDepth < 256 || limits.maxSteps < 1e3)) return void 0;
515
- const syncSink = typeof context.stdout.writeSync === "function" ? context.stdout : void 0;
516
- if (!syncSink) return void 0;
517
- const fastMemFs = context._fastMemoryBackingFs;
518
- if (!fastMemFs || fastMemFs.capabilitiesFor !== void 0 || context._cachedInputBudget !== void 0 || Object.prototype.hasOwnProperty.call(fastMemFs, "readStream") || Object.prototype.hasOwnProperty.call(fastMemFs, "readFile")) {
519
- return void 0;
520
- }
521
- const absolute = file.charCodeAt(0) === 47 && file.length > 1 && file.charCodeAt(file.length - 1) !== 47 && !file.includes("//") && !file.includes("/.") ? file : (0, path_exports.pathOf)(context, file);
522
- if (absolute === "/dev" || absolute.startsWith("/dev/")) return void 0;
523
- let rawBytes;
524
- try {
525
- rawBytes = tryReadMemoryFileViewSync2(fastMemFs, absolute, void 0, context.signal, true);
526
- } catch {
527
- return void 0;
528
- }
529
- if (!rawBytes || rawBytes.byteLength === 0 || rawBytes[0] !== 123 || rawBytes[rawBytes.byteLength - 1] !== 10) {
530
- return void 0;
531
- }
532
- let budget = sharedFastBudget;
533
- const rawSourceRef = getLastReadMemoryFileSourceRef(rawBytes);
534
- if (!budget || budget.limits !== limits) {
535
- budget = sharedFastBudget = new Budget(limits, context.signal);
536
- } else {
537
- budget.resetForSyncFastRun(context.signal);
538
- }
539
- if (budget.maxInputBytesSmi < 1073741823 && limits.maxInputBytes !== Infinity) {
540
- const argBytes = 2 + utf8ByteLength(source) + utf8ByteLength(file);
541
- if (argBytes + rawBytes.byteLength > limits.maxInputBytes) return void 0;
542
- }
543
- if (!cachedAst) {
544
- try {
545
- cachedAst = parse(source, EMPTY_VARS_MAP, budget);
546
- } catch {
547
- return void 0;
548
- }
549
- }
550
- if (budget.needsYield()) return void 0;
551
- if (Interpreter.prototype.run !== DEFAULT_INTERPRETER_RUN) return void 0;
552
- let interpreter;
553
- const outBuf = sharedJqOutBuf ??= filledBytes(OUT_BUF_SIZE);
554
- sharedFastInUse = true;
555
- sharedJqOutBufInUse = true;
556
- sharedFastJqAst = cachedAst;
557
- sharedFastJqLimits = limits;
558
- sharedFastJqOutPos = 0;
559
- sharedFastJqAborted = false;
560
- let committing = false;
561
- try {
562
- context.signal.throwIfAborted();
563
- budget.collection(3);
564
- budget.text(source);
565
- budget.inputLocation.name = file;
566
- budget.inputLocation.line = 0;
567
- budget.inputLocation.complete = false;
568
- const spPlan = getFastSelectProjectPlan(cachedAst);
569
- const fastPos = spPlan ? tryProcessFlatSelectProjectChunkSync(rawBytes, budget, spPlan.condKey, spPlan.outKeys, spPlan.srcKeys, outBuf, spPlan, rawSourceRef) : -1;
570
- if (fastPos >= 0) {
571
- sharedFastJqOutPos = fastPos;
572
- } else {
573
- interpreter = sharedFastInterpreter;
574
- if (!interpreter) {
575
- interpreter = sharedFastInterpreter = new Interpreter(budget, EMPTY_VARS_MAP);
576
- } else {
577
- interpreter.resetForRun(budget, EMPTY_VARS_MAP);
578
- }
579
- if (interpreter.run !== DEFAULT_INTERPRETER_RUN) return void 0;
580
- const ok = tryProcessFlatJsonChunkSync(rawBytes, budget, sharedFastJqOnValue);
581
- if (!ok || sharedFastJqAborted) return void 0;
582
- }
583
- context._chargeFastFsOp?.();
584
- const len = sharedFastJqOutPos;
585
- if (len > 0) {
586
- sharedFastJqOutPos = 0;
587
- context.signal.throwIfAborted();
588
- committing = true;
589
- const savedOut = fastPos >= 0 ? getLastFastSelectProjectSavedOutBuf(len) : void 0;
590
- const wrote = savedOut !== void 0 && typeof syncSink.writeImmutableSync === "function" ? syncSink.writeImmutableSync(savedOut) : typeof syncSink.writeRangeSync === "function" ? syncSink.writeRangeSync(outBuf, len) : syncSink.writeSync(outBuf.subarray(0, len));
591
- if (!wrote) return void 0;
592
- }
593
- if (jqAstCache.size < 64) jqAstCache.set(source, cachedAst);
594
- return RESOLVED_EXIT_ZERO;
595
- } catch (error) {
596
- if (committing) throw error;
597
- return void 0;
598
- } finally {
599
- if (interpreter) interpreter.releaseScratch();
600
- sharedFastJqAst = void 0;
601
- sharedFastJqLimits = void 0;
602
- budget.signal = NEVER_ABORTED_SIGNAL;
603
- sharedJqOutBufInUse = false;
604
- sharedFastInUse = false;
605
- }
606
- }
607
- function argumentsFor(context, budget) {
608
- const args = context.args;
609
- for (let i = 0; i < args.length; i++) {
610
- const a = args[i];
611
- if (a === "--rawfile" || a === "--slurpfile") return argumentsForAsync(context, budget);
612
- }
613
- budget.collection(args.length);
614
- let argumentBytes = 0;
615
- for (const argument of args) {
616
- argumentBytes += utf8ByteLength(argument);
617
- if (argumentBytes > budget.limits.maxInputBytes) throw new JqLimitError("maxInputBytes");
618
- }
619
- const options = { stream: false, streamErrors: false, sequence: false, raw: false, rawInput: false, joinOutput: false, rawOutput0: false, monochrome: false, format: { indent: " ", ascii: false, color: false }, sortKeys: false, slurp: false, nullInput: false, exitStatus: false, source: void 0, programFile: void 0, files: [], moduleDirectories: [], variables: /* @__PURE__ */ new Map() };
620
- let named;
621
- const positional = [];
622
- let positionalMode;
623
- let ended = false;
624
- let variableBytes = 0;
625
- for (let index = 0; index < args.length; index++) {
626
- const argument = args[index];
627
- const operand = () => {
628
- const value = args[++index];
629
- if (value === void 0) throw new JqError(`${argument} requires an operand`, 2);
630
- return value;
631
- };
632
- if (!ended && argument === "--") {
633
- ended = true;
634
- continue;
635
- }
636
- if (!ended && (argument === "--args" || argument === "--jsonargs")) {
637
- positionalMode = argument;
638
- continue;
639
- }
640
- if (!ended && argument.startsWith("-L")) {
641
- options.moduleDirectories.push(argument === "-L" ? operand() : argument.slice(2));
642
- continue;
643
- }
644
- if (!ended && (argument === "--arg" || argument === "--argjson")) {
645
- const name = operand();
646
- const text = operand();
647
- budget.text(name);
648
- budget.text(text);
649
- let value;
650
- try {
651
- value = argument === "--arg" ? text : parseJson(text, budget);
652
- } catch (error) {
653
- if (error instanceof JqLimitError) throw error;
654
- throw new JqError(`invalid JSON for --argjson ${name}`, 2);
655
- }
656
- if (!wellFormed(name) || typeof value === "string" && !wellFormed(value)) throw new JqError("arguments must contain well-formed Unicode", 2);
657
- variableBytes += utf8ByteLength(name) + budget.value(value);
658
- if (variableBytes > budget.limits.maxValueBytes) throw new JqLimitError("maxValueBytes");
659
- if (!options.variables.has(name)) {
660
- options.variables.set(name, value);
661
- put(named ??= object(), name, value);
662
- }
663
- continue;
664
- }
665
- if (!ended && (argument === "-f" || argument === "--from-file")) {
666
- if (options.programFile !== void 0 || options.source !== void 0) throw new JqError("provide exactly one filter program", 2);
667
- options.programFile = operand();
668
- continue;
669
- }
670
- if (!ended && (argument === "--stream" || argument === "--stream-errors" || argument === "--seq")) {
671
- if (argument === "--seq") options.sequence = true;
672
- else {
673
- options.stream = true;
674
- options.streamErrors ||= argument === "--stream-errors";
675
- }
676
- continue;
677
- }
678
- if (!ended && argument === "--indent") {
679
- const value = Number.parseInt(operand(), 10) || 0;
680
- if (value < -1 || value > 7) throw new JqError("--indent takes a number between -1 and 7", 2);
681
- options.format.indent = value === -1 ? " " : " ".repeat(value);
682
- continue;
683
- }
684
- if (!ended && argument === "--tab") {
685
- options.format.indent = " ";
686
- continue;
687
- }
688
- if (!ended && argument === "--raw-output0") {
689
- options.rawOutput0 = true;
690
- options.raw = true;
691
- continue;
692
- }
693
- if (!ended && argument === "--unbuffered") continue;
694
- const flagStart = argument[1] ?? "";
695
- const positionalOperand = positionalMode !== void 0 && flagStart !== "-" && !(flagStart >= "a" && flagStart <= "z") && !(flagStart >= "A" && flagStart <= "Z");
696
- if (!ended && argument.startsWith("-") && argument !== "-" && !positionalOperand) {
697
- const flags = Object.hasOwn(JQ_LONG_FLAGS, argument) ? JQ_LONG_FLAGS[argument] : argument.startsWith("--") ? "" : argument.slice(1);
698
- if (!flags || [...flags].some((flag) => !"rRjcSsneaCM".includes(flag))) throw new JqError(`unsupported option ${argument}`, 2);
699
- for (const flag of flags) {
700
- if (flag === "r") options.raw = true;
701
- else if (flag === "R") options.rawInput = true;
702
- else if (flag === "j") {
703
- options.joinOutput = true;
704
- options.raw = true;
705
- } else if (flag === "c") options.format.indent = "";
706
- else if (flag === "a") options.format.ascii = true;
707
- else if (flag === "C") options.format.color = true;
708
- else if (flag === "M") options.monochrome = true;
709
- else if (flag === "S") options.sortKeys = true;
710
- else if (flag === "s") options.slurp = true;
711
- else if (flag === "n") options.nullInput = true;
712
- else options.exitStatus = true;
713
- }
714
- continue;
715
- }
716
- if (options.source === void 0 && options.programFile === void 0) options.source = argument;
717
- else if (positionalMode !== void 0) {
718
- budget.text(argument);
719
- let value;
720
- try {
721
- value = positionalMode === "--args" ? argument : parseJson(argument, budget);
722
- } catch (error) {
723
- if (error instanceof JqLimitError) throw error;
724
- throw new JqError("invalid JSON text passed to --jsonargs", 2);
725
- }
726
- if (typeof value === "string" && !wellFormed(value)) throw new JqError("arguments must contain well-formed Unicode", 2);
727
- variableBytes += budget.value(value) + (positional.length ? 1 : 2);
728
- if (variableBytes > budget.limits.maxValueBytes) throw new JqLimitError("maxValueBytes");
729
- positional.push(value);
730
- } else options.files.push(argument);
731
- }
732
- options.format.color &&= !options.monochrome;
733
- if (positional.length) budget.value(positional);
734
- options.source ??= options.programFile === void 0 ? "." : void 0;
735
- if (positional.length > 0 || named !== void 0 || options.programFile !== void 0 || options.source?.includes("ARGS")) {
736
- options.variables.set("ARGS", copyObject({ positional, named: named ?? object() }));
737
- }
738
- return options;
739
- }
740
- async function argumentsForAsync(context, budget) {
741
- const args = context.args;
742
- budget.collection(args.length);
743
- let argumentBytes = 0;
744
- for (const argument of args) {
745
- argumentBytes += utf8ByteLength(argument);
746
- if (argumentBytes > budget.limits.maxInputBytes) throw new JqLimitError("maxInputBytes");
747
- }
748
- const options = { stream: false, streamErrors: false, sequence: false, raw: false, rawInput: false, joinOutput: false, rawOutput0: false, monochrome: false, format: { indent: " ", ascii: false, color: false }, sortKeys: false, slurp: false, nullInput: false, exitStatus: false, source: void 0, programFile: void 0, files: [], moduleDirectories: [], variables: /* @__PURE__ */ new Map() };
749
- const named = object();
750
- const positional = [];
751
- let positionalMode;
752
- let ended = false;
753
- let variableBytes = 0;
754
- for (let index = 0; index < args.length; index++) {
755
- const argument = args[index];
756
- const operand = () => {
757
- const value = args[++index];
758
- if (value === void 0) throw new JqError(`${argument} requires an operand`, 2);
759
- return value;
760
- };
761
- if (!ended && argument === "--") {
762
- ended = true;
763
- continue;
764
- }
765
- if (!ended && (argument === "--args" || argument === "--jsonargs")) {
766
- positionalMode = argument;
767
- continue;
768
- }
769
- if (!ended && argument.startsWith("-L")) {
770
- options.moduleDirectories.push(argument === "-L" ? operand() : argument.slice(2));
771
- continue;
772
- }
773
- if (!ended && (argument === "--arg" || argument === "--argjson" || argument === "--rawfile" || argument === "--slurpfile")) {
774
- const name = operand();
775
- const text = operand();
776
- budget.text(name);
777
- budget.text(text);
778
- let value;
779
- if (argument === "--rawfile" || argument === "--slurpfile") {
780
- if (!wellFormed(name)) throw new JqError("arguments must contain well-formed Unicode", 2);
781
- if (options.variables.has(name)) continue;
782
- try {
783
- value = await fileVariable(context, text, argument === "--rawfile", budget);
784
- } catch (error) {
785
- context.signal.throwIfAborted();
786
- if (!(error instanceof JqError) || error instanceof JqLimitError) throw error;
787
- throw new JqError(`Bad JSON in ${argument} ${name} ${text}: ${error.message}`, 2);
788
- }
789
- } else {
790
- try {
791
- value = argument === "--arg" ? text : parseJson(text, budget);
792
- } catch (error) {
793
- if (error instanceof JqLimitError) throw error;
794
- throw new JqError(`invalid JSON for --argjson ${name}`, 2);
795
- }
796
- }
797
- if (!wellFormed(name) || typeof value === "string" && !wellFormed(value)) throw new JqError("arguments must contain well-formed Unicode", 2);
798
- variableBytes += utf8ByteLength(name) + budget.value(value);
799
- if (variableBytes > budget.limits.maxValueBytes) throw new JqLimitError("maxValueBytes");
800
- if (!options.variables.has(name)) {
801
- options.variables.set(name, value);
802
- put(named, name, value);
803
- }
804
- continue;
805
- }
806
- if (!ended && (argument === "-f" || argument === "--from-file")) {
807
- if (options.programFile !== void 0 || options.source !== void 0) throw new JqError("provide exactly one filter program", 2);
808
- options.programFile = operand();
809
- continue;
810
- }
811
- if (!ended && (argument === "--stream" || argument === "--stream-errors" || argument === "--seq")) {
812
- if (argument === "--seq") options.sequence = true;
813
- else {
814
- options.stream = true;
815
- options.streamErrors ||= argument === "--stream-errors";
816
- }
817
- continue;
818
- }
819
- if (!ended && argument === "--indent") {
820
- const value = Number.parseInt(operand(), 10) || 0;
821
- if (value < -1 || value > 7) throw new JqError("--indent takes a number between -1 and 7", 2);
822
- options.format.indent = value === -1 ? " " : " ".repeat(value);
823
- continue;
824
- }
825
- if (!ended && argument === "--tab") {
826
- options.format.indent = " ";
827
- continue;
828
- }
829
- if (!ended && argument === "--raw-output0") {
830
- options.rawOutput0 = true;
831
- options.raw = true;
832
- continue;
833
- }
834
- if (!ended && argument === "--unbuffered") continue;
835
- const long = { "--raw-output": "r", "--raw-input": "R", "--join-output": "j", "--compact-output": "c", "--sort-keys": "S", "--slurp": "s", "--null-input": "n", "--exit-status": "e", "--ascii-output": "a", "--color-output": "C", "--monochrome-output": "M" };
836
- const flagStart = argument[1] ?? "";
837
- const positionalOperand = positionalMode !== void 0 && flagStart !== "-" && !(flagStart >= "a" && flagStart <= "z") && !(flagStart >= "A" && flagStart <= "Z");
838
- if (!ended && argument.startsWith("-") && argument !== "-" && !positionalOperand) {
839
- const flags = Object.hasOwn(long, argument) ? long[argument] : argument.startsWith("--") ? "" : argument.slice(1);
840
- if (!flags || [...flags].some((flag) => !"rRjcSsneaCM".includes(flag))) throw new JqError(`unsupported option ${argument}`, 2);
841
- for (const flag of flags) {
842
- if (flag === "r") options.raw = true;
843
- else if (flag === "R") options.rawInput = true;
844
- else if (flag === "j") {
845
- options.joinOutput = true;
846
- options.raw = true;
847
- } else if (flag === "c") options.format.indent = "";
848
- else if (flag === "a") options.format.ascii = true;
849
- else if (flag === "C") options.format.color = true;
850
- else if (flag === "M") options.monochrome = true;
851
- else if (flag === "S") options.sortKeys = true;
852
- else if (flag === "s") options.slurp = true;
853
- else if (flag === "n") options.nullInput = true;
854
- else options.exitStatus = true;
855
- }
856
- continue;
857
- }
858
- if (options.source === void 0 && options.programFile === void 0) options.source = argument;
859
- else if (positionalMode !== void 0) {
860
- budget.text(argument);
861
- let value;
862
- try {
863
- value = positionalMode === "--args" ? argument : parseJson(argument, budget);
864
- } catch (error) {
865
- if (error instanceof JqLimitError) throw error;
866
- throw new JqError("invalid JSON text passed to --jsonargs", 2);
867
- }
868
- if (typeof value === "string" && !wellFormed(value)) throw new JqError("arguments must contain well-formed Unicode", 2);
869
- variableBytes += budget.value(value) + (positional.length ? 1 : 2);
870
- if (variableBytes > budget.limits.maxValueBytes) throw new JqLimitError("maxValueBytes");
871
- positional.push(value);
872
- } else options.files.push(argument);
873
- }
874
- options.format.color &&= !options.monochrome;
875
- if (positional.length) budget.value(positional);
876
- options.variables.set("ARGS", copyObject({ positional, named }));
877
- options.source ??= options.programFile === void 0 ? "." : void 0;
878
- return options;
879
- }
880
- async function readProgram(context, path, limits) {
881
- const absolute = (0, path_exports.pathOf)(context, path);
882
- const chunks = [];
883
- let size = 0;
884
- const capabilities = context.fs.capabilitiesFor ? await interruptible(() => context.fs.capabilitiesFor(absolute, { signal: context.signal }), context.signal) : context.fs.capabilities;
885
- context.signal.throwIfAborted();
886
- if (context.fs.readStream && capabilities.streamingRead !== false) {
887
- for await (const chunk of readBytes3(context.fs.readStream(absolute, { signal: context.signal }), context.signal)) {
888
- size += chunk.byteLength;
889
- if (size > limits.maxSourceBytes) throw new JqLimitError("maxSourceBytes");
890
- if (chunk.byteLength) chunks.push(new Uint8Array(chunk));
891
- }
892
- } else {
893
- const chunk = await interruptible(() => context.fs.readFile(absolute, { signal: context.signal, ...Number.isFinite(limits.maxSourceBytes) ? { maxBytes: limits.maxSourceBytes } : {} }), context.signal);
894
- if (chunk.byteLength > limits.maxSourceBytes) throw new JqLimitError("maxSourceBytes");
895
- chunks.push(chunk);
896
- }
897
- try {
898
- return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(concatBytes(chunks));
899
- } catch {
900
- throw new JqError("program file is not valid UTF-8", 3);
901
- }
902
- }
903
- async function compileProgram(context, options, source, budget) {
904
- if (!options.moduleDirectories.length) return parse(source, options.variables, budget);
905
- let sourceBytes = utf8ByteLength(source);
906
- const active = /* @__PURE__ */ new Set();
907
- const compile = async (text, depth, module) => {
908
- await budget.tick();
909
- if (sourceBytes > budget.limits.maxSourceBytes) throw new JqLimitError("maxSourceBytes");
910
- if (depth > budget.limits.maxAstDepth) throw new JqLimitError("maxAstDepth");
911
- const program = moduleProgram(text, budget);
912
- const definitions = /* @__PURE__ */ new Map();
913
- for (const entry of program.imports) {
914
- const parts = entry.name.split("/");
915
- if (parts.some((part) => !part || part === "." || part === ".." || part.includes("\0"))) throw new JqError("invalid module path", 3);
916
- let loaded;
917
- for (const directory of options.moduleDirectories) {
918
- await budget.tick();
919
- const path = (0, path_exports.pathOf)(context, joinPath(directory, `${entry.name}.jq`));
920
- if (active.has(path)) throw new JqError(`module dependency cycle: ${entry.name}`, 3);
921
- let contents;
922
- try {
923
- contents = await readProgram(context, path, { ...budget.limits, maxSourceBytes: budget.limits.maxSourceBytes - sourceBytes });
924
- } catch (error) {
925
- context.signal.throwIfAborted();
926
- if (error instanceof FsError3 && (error.code === "ENOENT" || error.code === "ENOTDIR")) continue;
927
- throw error;
928
- }
929
- sourceBytes += utf8ByteLength(contents);
930
- active.add(path);
931
- try {
932
- loaded = await compile(contents, depth + 1, true);
933
- } finally {
934
- active.delete(path);
935
- }
936
- break;
937
- }
938
- if (!loaded) throw new JqError(`module not found: ${entry.name}`, 3);
939
- for (const [name, body] of loaded.definitions) {
940
- definitions.set(entry.alias === void 0 ? name : `${entry.alias}::${name}`, body);
941
- budget.collection(definitions.size);
942
- }
943
- }
944
- return { ast: parse(program.source, options.variables, budget, definitions, module), definitions };
945
- };
946
- return (await compile(source, 1, false)).ast;
947
- }
948
- async function* inputSources(context, options, budget, convert) {
949
- const files = options.files.length ? options.files : ["-"];
950
- let usedStdin = false;
951
- for (const file of files) {
952
- let source;
953
- if (file === "-") {
954
- if (options.rawInput && usedStdin) continue;
955
- usedStdin = true;
956
- source = context.stdin;
957
- } else {
958
- const absolute = (0, path_exports.pathOf)(context, file);
959
- const remaining = budget.limits.maxInputBytes - budget.inputBytes;
960
- await budget.tick();
961
- const backing = getRuntimeBackingFileSystem2(context.fs);
962
- const needsCapabilitiesFor = Boolean(
963
- context.fs.capabilitiesFor && (backing === void 0 || backing.capabilitiesFor !== void 0 || tryResolveMemoryDevicePath2(backing, absolute) === void 0)
964
- );
965
- const capabilities = needsCapabilitiesFor ? await interruptible(() => context.fs.capabilitiesFor(absolute, { signal: context.signal }), context.signal) : context.fs.capabilities;
966
- context.signal.throwIfAborted();
967
- if (context.fs.readStream && capabilities.streamingRead !== false) source = context.fs.readStream(absolute, { signal: context.signal });
968
- else source = toByteSource2(await interruptible(() => context.fs.readFile(absolute, { signal: context.signal, ...Number.isFinite(remaining) ? { maxBytes: remaining } : {} }), context.signal));
969
- }
970
- budget.inputLocation = { name: file === "-" ? "<stdin>" : file, line: 0, complete: false };
971
- yield convert ? await convert(source) : source;
972
- }
973
- }
974
- async function fileVariable(context, path, raw, budget) {
975
- const previousLocation = budget.inputLocation;
976
- try {
977
- const sources = inputSources(context, { files: [(0, path_exports.pathOf)(context, path)], rawInput: raw }, budget);
978
- if (raw) {
979
- for await (const value of rawValues(sources, budget, true)) return value;
980
- return "";
981
- }
982
- const values = [];
983
- let bytes = 2;
984
- for await (const source of sources) {
985
- for await (const value of jsonValues(source, budget)) {
986
- budget.collection(values.length + 1);
987
- bytes += budget.value(value) + (values.length ? 1 : 0);
988
- if (bytes > budget.limits.maxValueBytes) throw new JqLimitError("maxValueBytes");
989
- values.push(value);
990
- }
991
- }
992
- budget.value(values);
993
- return values;
994
- } finally {
995
- budget.inputLocation = previousLocation;
996
- }
997
- }
998
- function inputs(context, options, budget, convert, onValue, onChunkEnd, hasPendingDiagnostics, retainValues) {
999
- if (options.rawInput) {
1000
- return rawValues(inputSources(context, options, budget, convert), budget, options.slurp);
1001
- }
1002
- let source;
1003
- if (!options.files.length && !convert) {
1004
- budget.inputLocation = { name: "<stdin>", line: 0, complete: false };
1005
- source = context.stdin;
1006
- } else if (!convert && options.files.length === 1 && options.files[0] !== "-") {
1007
- const file = options.files[0];
1008
- const absolute = (0, path_exports.pathOf)(context, file);
1009
- const fastMemFs = context._fastMemoryBackingFs;
1010
- if (fastMemFs !== void 0 && fastMemFs.capabilitiesFor === void 0 && context._cachedInputBudget === void 0 && absolute !== "/dev" && !absolute.startsWith("/dev/") && !Object.prototype.hasOwnProperty.call(fastMemFs, "readStream") && !Object.prototype.hasOwnProperty.call(fastMemFs, "readFile")) {
1011
- try {
1012
- const rawBytes = tryReadMemoryFileViewSync2(fastMemFs, absolute, void 0, context.signal);
1013
- if (rawBytes !== void 0) {
1014
- const tickPromise = budget.tickSync();
1015
- if (tickPromise) {
1016
- return (async function* () {
1017
- await tickPromise;
1018
- yield* inputs(context, options, budget, convert, onValue, onChunkEnd, hasPendingDiagnostics, retainValues);
1019
- })();
1020
- }
1021
- context._chargeFastFsOp?.();
1022
- budget.inputLocation = { name: file, line: 0, complete: false };
1023
- source = createSyncSingleChunkByteSource(rawBytes, context.signal);
1024
- }
1025
- } catch {
1026
- }
1027
- }
1028
- if (source === void 0) {
1029
- const backing = getRuntimeBackingFileSystem2(context.fs);
1030
- if (backing !== void 0 && backing.capabilitiesFor === void 0 && absolute !== "/dev" && !absolute.startsWith("/dev/") && context.fs.readStream && context.fs.capabilities.streamingRead !== false && Object.getPrototypeOf(backing)?.constructor?.name === "MemoryFileSystem" && !Object.prototype.hasOwnProperty.call(backing, "readStream")) {
1031
- const tickPromise = budget.tickSync();
1032
- if (tickPromise) {
1033
- return (async function* () {
1034
- await tickPromise;
1035
- yield* inputs(context, options, budget, convert, onValue, onChunkEnd, hasPendingDiagnostics);
1036
- })();
1037
- }
1038
- context.signal.throwIfAborted();
1039
- budget.inputLocation = { name: file, line: 0, complete: false };
1040
- source = context.fs.readStream(absolute, { signal: context.signal });
1041
- }
1042
- }
1043
- }
1044
- if (source === void 0) {
1045
- async function* joined() {
1046
- for await (const s of inputSources(context, options, budget, convert)) yield* readBytes3(s, context.signal);
1047
- }
1048
- source = joined();
1049
- }
1050
- return jsonValues(source, budget, {
1051
- stream: options.stream,
1052
- streamErrors: options.streamErrors,
1053
- sequence: options.sequence,
1054
- ...onValue ? { onValue } : {},
1055
- ...retainValues ? { retainValues } : {},
1056
- ...onChunkEnd ? { onChunkEnd } : {},
1057
- ...hasPendingDiagnostics ? { hasPendingDiagnostics } : {},
1058
- warning: async (message) => {
1059
- const bytes = utf8ByteLength(message) + 5;
1060
- budget.outputBytes += bytes;
1061
- if (budget.outputBytes > budget.limits.maxOutputBytes) throw new JqLimitError("maxOutputBytes");
1062
- await writeDiagnostic(context.stderr, `jq: ${message}
1063
- `, context.signal);
1064
- }
1065
- });
1066
- }
1067
- function executeJq(context, limits, convert) {
1068
- if (!convert) {
1069
- const fastRes = tryExecuteJqFastSync(context, limits);
1070
- if (fastRes !== void 0) return fastRes;
1071
- }
1072
- return executeJqAsync(context, limits, convert);
1073
- }
1074
- async function executeJqAsync(context, limits, convert) {
1075
- const budget = new Budget(limits, context.signal);
1076
- context.signal.throwIfAborted();
1077
- const diagnostics = [];
1078
- let diagnosticBytes = 0;
1079
- let diagnosticWriteFailed = false;
1080
- let stdoutWriteFailed = false;
1081
- let outBuf = null;
1082
- let usingSharedOutBuf = false;
1083
- let outPos = 0;
1084
- const releaseOutBuf = () => {
1085
- if (usingSharedOutBuf) {
1086
- if (stdoutWriteFailed) sharedJqOutBuf = null;
1087
- usingSharedOutBuf = false;
1088
- sharedJqOutBufInUse = false;
1089
- outBuf = null;
1090
- }
1091
- };
1092
- const flushStdout = () => {
1093
- if (outPos > 0 && outBuf) {
1094
- const slice = new Uint8Array(outBuf.subarray(0, outPos));
1095
- outPos = 0;
1096
- try {
1097
- const pending = writeBytes(context.stdout, slice, context.signal);
1098
- if (isSyncResolved(pending)) return;
1099
- return pending.catch((error) => {
1100
- stdoutWriteFailed = true;
1101
- throw error;
1102
- });
1103
- } catch (error) {
1104
- stdoutWriteFailed = true;
1105
- throw error;
1106
- }
1107
- }
1108
- };
1109
- const flush = async (force = false) => {
1110
- if (outPos > 0) {
1111
- const p = flushStdout();
1112
- if (p) await p;
1113
- }
1114
- if (!diagnostics.length) return;
1115
- let written = 0;
1116
- try {
1117
- while (written < diagnostics.length && (force || diagnostics[written].location.complete)) {
1118
- const { location, message } = diagnostics[written++];
1119
- const place = location.name === "<unknown>" ? location.name : `${escapeText(location.name, "diagnostic")}:${location.line}`;
1120
- await writeBytes(context.stderr, bytesFrom(`jq: error (at ${place}): ${message}
1121
- `), context.signal);
1122
- }
1123
- } catch (error) {
1124
- diagnosticWriteFailed = true;
1125
- throw error;
1126
- } finally {
1127
- diagnostics.splice(0, written);
1128
- }
1129
- };
1130
- try {
1131
- const optionsOrPromise = argumentsFor(context, budget);
1132
- const options = optionsOrPromise instanceof Promise ? await optionsOrPromise : optionsOrPromise;
1133
- const source = options.programFile === void 0 ? options.source : await readProgram(context, options.programFile, limits);
1134
- let ast;
1135
- if (!options.moduleDirectories.length && options.variables.size === 0 && !source.includes("$") && budget.limits.maxSourceBytes >= source.length * 4 && budget.limits.maxAstDepth >= 256 && budget.limits.maxSteps >= 1e3) {
1136
- let cachedAst = jqAstCache.get(source);
1137
- if (!cachedAst) {
1138
- cachedAst = parse(source, options.variables, budget);
1139
- if (jqAstCache.size < 64) jqAstCache.set(source, cachedAst);
1140
- }
1141
- ast = cachedAst;
1142
- } else if (!options.moduleDirectories.length) {
1143
- ast = parse(source, options.variables, budget);
1144
- } else {
1145
- ast = await compileProgram(context, options, source, budget);
1146
- }
1147
- const interpreter = new Interpreter(budget, options.variables);
1148
- let lastTruth;
1149
- let status = 0;
1150
- const suffix = options.rawOutput0 ? "\0" : options.joinOutput ? "" : "\n";
1151
- const isPlainFormat = !options.format.ascii && !options.format.color && !options.sequence && !options.rawOutput0;
1152
- const isCompactPlain = isPlainFormat && options.format.indent === "" && !options.sortKeys;
1153
- const tryPublishSync = (result) => {
1154
- if (!isPlainFormat || budget.needsYield()) return false;
1155
- const isRawStr = options.raw && typeof result === "string";
1156
- const isScalar = result === null || typeof result !== "object";
1157
- if (!isCompactPlain && !isScalar) return false;
1158
- if (isScalar && !isRawStr) return false;
1159
- if (budget.results + 1 > budget.maxResultsSmi && budget.results + 1 > limits.maxResults) throw new JqLimitError("maxResults");
1160
- let buf = outBuf;
1161
- if (!buf) {
1162
- if (!sharedJqOutBufInUse) {
1163
- sharedJqOutBufInUse = true;
1164
- usingSharedOutBuf = true;
1165
- buf = outBuf = sharedJqOutBuf ??= new Uint8Array(OUT_BUF_SIZE);
1166
- } else {
1167
- buf = outBuf = new Uint8Array(OUT_BUF_SIZE);
1168
- }
1169
- }
1170
- if (isRawStr) {
1171
- const str = result;
1172
- const chunkLen = str.length + suffix.length;
1173
- if (outPos + chunkLen > OUT_BUF_SIZE) return false;
1174
- for (let i = 0; i < str.length; i++) {
1175
- if (str.charCodeAt(i) >= 128) return false;
1176
- }
1177
- const remaining = limits.maxOutputBytes - budget.outputBytes;
1178
- if (chunkLen === 0) return false;
1179
- if (chunkLen > remaining) throw new JqLimitError("maxOutputBytes");
1180
- budget.step();
1181
- budget.value(str);
1182
- budget.results++;
1183
- budget.outputBytes += chunkLen;
1184
- let pos = outPos;
1185
- for (let i = 0; i < str.length; i++) buf[pos++] = str.charCodeAt(i);
1186
- for (let i = 0; i < suffix.length; i++) buf[pos++] = suffix.charCodeAt(i);
1187
- outPos = pos;
1188
- return true;
1189
- }
1190
- const remSmi = budget.maxOutputBytesSmi - budget.outputBytes;
1191
- const maxChunkSmi = remSmi > suffix.length ? remSmi - suffix.length : limits.maxOutputBytes === Infinity ? 1073741823 : Math.max(0, limits.maxOutputBytes - budget.outputBytes - suffix.length);
1192
- if (outPos + 512 > OUT_BUF_SIZE && outPos > 0) return false;
1193
- const newPos = tryWriteCompactSync(result, budget, buf, outPos, suffix, maxChunkSmi, interpreter.getScratchKeys(result));
1194
- if (newPos >= 0) {
1195
- const chunkLen = newPos - outPos;
1196
- if (chunkLen > remSmi && chunkLen > limits.maxOutputBytes - budget.outputBytes) throw new JqLimitError("maxOutputBytes");
1197
- budget.results++;
1198
- budget.outputBytes += chunkLen;
1199
- outPos = newPos;
1200
- return true;
1201
- }
1202
- return false;
1203
- };
1204
- const publishResult = async (result) => {
1205
- await flushStdout();
1206
- const pt = budget.tickSync();
1207
- if (pt) await pt;
1208
- budget.value(result);
1209
- if (++budget.results > limits.maxResults) throw new JqLimitError("maxResults");
1210
- const remaining = limits.maxOutputBytes - budget.outputBytes;
1211
- const prefix = options.sequence && !(options.raw && typeof result === "string") ? "" : "";
1212
- const output = options.sortKeys ? await sortObjectKeys(result, budget) : result;
1213
- const rawString = options.raw && typeof output === "string";
1214
- const format = rawString ? { ...options.format, color: false } : options.format;
1215
- const text = rawString && !format.ascii ? output : await stringify(output, budget, format, Math.max(0, remaining - suffix.length - prefix.length), "maxOutputBytes");
1216
- const chunkText = `${prefix}${text}${suffix}`;
1217
- const chunkBuf = bytesFrom(chunkText);
1218
- const byteLen = chunkBuf.byteLength;
1219
- if (byteLen > remaining) throw new JqLimitError("maxOutputBytes");
1220
- budget.outputBytes += byteLen;
1221
- try {
1222
- await writeBytes(context.stdout, chunkBuf, context.signal);
1223
- } catch (error) {
1224
- stdoutWriteFailed = true;
1225
- throw error;
1226
- }
1227
- };
1228
- const emitRemainingAsync = async (syncResults, startIdx, initialLast) => {
1229
- let invocationLast = initialLast;
1230
- for (let idx = startIdx; idx < syncResults.length; idx++) {
1231
- const r = syncResults[idx];
1232
- await publishResult(r);
1233
- invocationLast = r;
1234
- status = options.exitStatus ? truth(r) ? 0 : 1 : 0;
1235
- }
1236
- if (status < 2 && invocationLast !== void 0) lastTruth = truth(invocationLast);
1237
- if (diagnostics.length) await flush();
1238
- };
1239
- const emitSyncOrAsync = (input) => {
1240
- if (!diagnostics.length && !options.rawOutput0 && interpreter.run === DEFAULT_INTERPRETER_RUN) {
1241
- const syncResults = interpreter.tryRunSync(ast, input);
1242
- if (syncResults !== void 0) {
1243
- status = options.exitStatus ? lastTruth === void 0 ? 4 : lastTruth ? 0 : 1 : 0;
1244
- let invocationLast;
1245
- let idx = 0;
1246
- while (idx < syncResults.length) {
1247
- const result = syncResults[idx];
1248
- if (!tryPublishSync(result)) {
1249
- return emitRemainingAsync(syncResults, idx, invocationLast);
1250
- }
1251
- invocationLast = result;
1252
- status = options.exitStatus ? truth(result) ? 0 : 1 : 0;
1253
- idx++;
1254
- }
1255
- if (status < 2 && invocationLast !== void 0) lastTruth = truth(invocationLast);
1256
- interpreter.releaseScratch();
1257
- return;
1258
- }
1259
- }
1260
- return emit(input);
1261
- };
1262
- const emit = async (input) => {
1263
- if (diagnostics.length) await flush();
1264
- status = options.exitStatus ? lastTruth === void 0 ? 4 : lastTruth ? 0 : 1 : 0;
1265
- let invocationLast;
1266
- if (!options.rawOutput0 && interpreter.run === DEFAULT_INTERPRETER_RUN) {
1267
- const syncResults = interpreter.tryRunSync(ast, input);
1268
- if (syncResults !== void 0) {
1269
- for (let i = 0; i < syncResults.length; i++) {
1270
- const result = syncResults[i];
1271
- if (!tryPublishSync(result)) await publishResult(result);
1272
- invocationLast = result;
1273
- status = options.exitStatus ? truth(result) ? 0 : 1 : 0;
1274
- }
1275
- if (status < 2 && invocationLast !== void 0) lastTruth = truth(invocationLast);
1276
- if (diagnostics.length) await flush();
1277
- return;
1278
- }
1279
- }
1280
- const iterator = interpreter.run(ast, input);
1281
- try {
1282
- while (true) {
1283
- let next;
1284
- try {
1285
- next = await iterator.next();
1286
- if (!next.done && options.rawOutput0 && !options.format.ascii && typeof next.value === "string") {
1287
- await budget.tick(next.value.length);
1288
- if (next.value.includes("\0")) throw new JqError("Cannot dump a string containing NUL with --raw-output0 option");
1289
- }
1290
- } catch (error) {
1291
- context.signal.throwIfAborted();
1292
- if (!(error instanceof JqError) || error instanceof JqLimitError) throw error;
1293
- const message = escapeText(error.message.slice(0, 1e3), "diagnostic");
1294
- diagnosticBytes += utf8ByteLength(message) + utf8ByteLength(escapeText(budget.inputLocation.name, "diagnostic")) + 64;
1295
- if (diagnosticBytes > limits.maxOutputBytes) throw new JqLimitError("maxOutputBytes");
1296
- diagnostics.push({ location: budget.inputLocation, message });
1297
- status = error.exitCode;
1298
- break;
1299
- }
1300
- if (next.done) break;
1301
- const result = next.value;
1302
- if (!tryPublishSync(result)) await publishResult(result);
1303
- const pending = flushStdout();
1304
- if (pending) await pending;
1305
- invocationLast = result;
1306
- status = options.exitStatus ? truth(result) ? 0 : 1 : 0;
1307
- }
1308
- } finally {
1309
- await iterator.return(void 0);
1310
- }
1311
- if (status < 2 && invocationLast !== void 0) lastTruth = truth(invocationLast);
1312
- if (diagnostics.length) await flush();
1313
- };
1314
- if (options.nullInput) {
1315
- await emit(null);
1316
- if (convert) for await (const value of inputs(context, options, budget, convert)) budget.value(value);
1317
- } else if (options.slurp && !options.rawInput) {
1318
- const values = [];
1319
- let bytes = 2;
1320
- const onSlurpValue = (value) => {
1321
- budget.collection(values.length + 1);
1322
- bytes += budget.value(value) + (values.length ? 1 : 0);
1323
- if (bytes > limits.maxValueBytes) throw new JqLimitError("maxValueBytes");
1324
- values.push(value);
1325
- };
1326
- for await (const value of inputs(context, options, budget, convert, onSlurpValue, void 0, void 0, true)) {
1327
- onSlurpValue(value);
1328
- }
1329
- budget.value(values);
1330
- const pEmit = emitSyncOrAsync(values);
1331
- if (pEmit) await pEmit;
1332
- } else for await (const value of inputs(context, options, budget, convert, emitSyncOrAsync, flushStdout, () => diagnostics.length > 0)) {
1333
- const p = emitSyncOrAsync(value);
1334
- if (p) await p;
1335
- const pending = flushStdout();
1336
- if (pending) await pending;
1337
- }
1338
- const pFlush = flushStdout();
1339
- if (pFlush) await pFlush;
1340
- await flush(true);
1341
- options.variables.clear();
1342
- options.files.length = 0;
1343
- interpreter.releaseScratch();
1344
- budget.signal = NEVER_ABORTED_SIGNAL;
1345
- return { exitCode: options.exitStatus && lastTruth === void 0 && status === 0 ? 4 : status };
1346
- } catch (error) {
1347
- if (diagnosticWriteFailed) throw error;
1348
- context.signal.throwIfAborted();
1349
- if (stdoutWriteFailed) throw error;
1350
- if (error instanceof JqHalt) {
1351
- await flush(true);
1352
- await writeBytes(context.stderr, bytesFrom(error.stderr), context.signal);
1353
- return { exitCode: error.exitCode };
1354
- }
1355
- if (!(error instanceof JqError) && !(error instanceof FsError3)) throw error;
1356
- if (error instanceof FsError3 && error.code === "EPIPE") throw error;
1357
- await flush(true);
1358
- await writeDiagnostic(context.stderr, `jq: ${error.message.slice(0, 1e3)}
1359
- `, context.signal);
1360
- return { exitCode: error instanceof JqError ? error.exitCode : 2 };
1361
- } finally {
1362
- releaseOutBuf();
1363
- }
1364
- }
1365
- function createJqCommand(options = {}) {
1366
- const limits = resolveJqLimits(options.limits);
1367
- const definition = { name: "jq", description: "Bounded, dependency-free JSON filter interpreter", execute: (context) => executeJq(context, limits) };
1368
- builtInDirectContextExecutors.add(definition.execute);
1369
- return definition;
1370
- }
1371
-
1372
- // packages/safe-bash-xml-engine/src/json.ts
1373
- init_platform();
1374
- async function xmlToJson(root, budget) {
1375
- async function element(node) {
1376
- await budget.tick();
1377
- const result2 = /* @__PURE__ */ Object.create(null);
1378
- const names = /* @__PURE__ */ new Set();
1379
- for (const attribute of node.attributes) {
1380
- await budget.tick();
1381
- result2["@" + attribute.name] = attribute.value;
1382
- }
1383
- const text = [];
1384
- for (const child of node.content) {
1385
- await budget.tick();
1386
- if (child.kind === "text" || child.kind === "cdata") text.push(child.text);
1387
- else if (child.kind === "element") {
1388
- const value2 = await element(child);
1389
- if (!names.has(child.name)) {
1390
- result2[child.name] = value2;
1391
- names.add(child.name);
1392
- } else {
1393
- const previous = result2[child.name];
1394
- if (Array.isArray(previous)) previous.push(value2);
1395
- else result2[child.name] = [previous, value2];
1396
- }
1397
- }
1398
- }
1399
- const value = text.join("").trim();
1400
- if (Object.keys(result2).length === 0) return value || null;
1401
- if (value) result2["#text"] = value;
1402
- return result2;
1403
- }
1404
- const result = /* @__PURE__ */ Object.create(null);
1405
- result[root.name] = await element(root);
1406
- return result;
1407
- }
1408
-
1409
- // packages/safe-bash-command-xq/src/index.ts
1410
- var runtime = { yieldTurn: yieldTurn2, pathOf: path_exports.pathOf, interruptible, writeDiagnostic: writeDiagnostic2 };
1411
- async function executeXq(context, limits) {
1412
- const budget = new XmlBudget(limits, context.signal, yieldTurn2);
1413
- try {
1414
- const carrier = getCommandArguments(context);
1415
- for (let index = 0; index < carrier.args.length; index++) {
1416
- if (shellValueByteLength(carrier.values[index]) > limits.maxInputBytes)
1417
- throw new XmlQueryLimitError("maxInputBytes");
1418
- let decoded;
1419
- try {
1420
- decoded = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(
1421
- carrier.bytes(index)
1422
- );
1423
- } catch {
1424
- throw new XmlQueryError("filters and filenames require valid UTF-8", 2);
1425
- }
1426
- if (decoded !== carrier.args[index])
1427
- throw new XmlQueryError("filters and filenames require lossless UTF-8", 2);
1428
- await budget.tick(decoded.length);
1429
- }
1430
- const jqLimits = resolveJqLimits({
1431
- maxOutputBytes: limits.maxOutputBytes,
1432
- maxSourceBytes: limits.maxSourceBytes,
1433
- maxDepth: limits.maxDepth * 2 + 2,
1434
- maxSteps: limits.maxSteps,
1435
- maxResults: limits.maxResults
1436
- });
1437
- const conversionBudget = new Budget(jqLimits, context.signal);
1438
- return executeJq(context, jqLimits, async (bytes) => {
1439
- try {
1440
- const source = await readXmlInput({ ...context, stdin: bytes }, void 0, budget, runtime);
1441
- const parser = parseXmlSteps(source, {
1442
- ...limits,
1443
- maxContentNodes: limits.maxNodes,
1444
- expectedEncoding: "UTF-8"
1445
- });
1446
- let parsed = parser.next();
1447
- try {
1448
- while (!parsed.done) {
1449
- await budget.tick(parsed.value);
1450
- parsed = parser.next();
1451
- }
1452
- } finally {
1453
- if (!parsed.done) parser.return(void 0);
1454
- }
1455
- const value = await xmlToJson(parsed.value, budget);
1456
- conversionBudget.value(value);
1457
- return toByteSource3(
1458
- await stringify(
1459
- value,
1460
- conversionBudget,
1461
- false,
1462
- jqLimits.maxValueBytes,
1463
- "maxValueBytes"
1464
- ) + "\n"
1465
- );
1466
- } catch (error) {
1467
- context.signal.throwIfAborted();
1468
- if (error instanceof XmlQueryError) throw new JqError(error.message, error.status);
1469
- if (error instanceof XmlLimitError) throw new JqError(error.message, 5);
1470
- if (error instanceof SyntaxError) throw new JqError(error.message, 1);
1471
- throw error;
1472
- }
1473
- });
1474
- } catch (error) {
1475
- context.signal.throwIfAborted();
1476
- if (!(error instanceof XmlQueryError)) throw error;
1477
- await writeDiagnostic2(
1478
- context.stderr,
1479
- `${context.command}: ${error.message.slice(0, 1e3)}
1480
- `,
1481
- context.signal
1482
- );
1483
- return { exitCode: error.status };
1484
- }
1485
- }
1486
- function createXqCommand(options = {}) {
1487
- const configuredLimits = options.limits;
1488
- const limits = resolveXmlQueryLimits(configuredLimits);
1489
- const definition = { name: "xq", execute: (context) => executeXq(context, limits) };
1490
- if (configuredLimits === void 0) builtInDirectContextExecutors.add(definition.execute);
1491
- return definition;
1492
- }
1493
- var syncXmlDecoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
1494
- function xmlElementToJsonSync(node) {
1495
- const result = /* @__PURE__ */ Object.create(null);
1496
- const names = /* @__PURE__ */ new Set();
1497
- for (const attribute of node.attributes) {
1498
- result["@" + attribute.name] = attribute.value;
1499
- }
1500
- const text = [];
1501
- for (const child of node.content) {
1502
- if (child.kind === "text" || child.kind === "cdata") text.push(child.text);
1503
- else if (child.kind === "element") {
1504
- const value2 = xmlElementToJsonSync(child);
1505
- if (!names.has(child.name)) {
1506
- result[child.name] = value2;
1507
- names.add(child.name);
1508
- } else {
1509
- const previous = result[child.name];
1510
- if (Array.isArray(previous)) previous.push(value2);
1511
- else result[child.name] = [previous, value2];
1512
- }
1513
- }
1514
- }
1515
- const value = text.join("").trim();
1516
- if (Object.keys(result).length === 0) return value || null;
1517
- if (value) result["#text"] = value;
1518
- return result;
1519
- }
1520
- var lastXqXmlText;
1521
- var lastXqJsonStr;
1522
- function evalSyncXq(inBytes, opArgs, readFileSync) {
1523
- if (inBytes.byteLength > 8192 || opArgs.length > 12) return void 0;
1524
- let rawOut = false;
1525
- let compactOut = false;
1526
- let nullInput = false;
1527
- let ended = false;
1528
- const extraJqArgs = [];
1529
- const positional = [];
1530
- for (let i = 0; i < opArgs.length; i++) {
1531
- const a = opArgs[i];
1532
- if (!ended && a === "--") {
1533
- ended = true;
1534
- continue;
1535
- }
1536
- if (!ended && a.startsWith("-") && a !== "-") {
1537
- if (a === "--raw-output") {
1538
- rawOut = true;
1539
- continue;
1540
- }
1541
- if (a === "--compact-output") {
1542
- compactOut = true;
1543
- continue;
1544
- }
1545
- if (a === "--null-input") {
1546
- nullInput = true;
1547
- continue;
1548
- }
1549
- if (a === "--sort-keys") {
1550
- extraJqArgs.push("-S");
1551
- continue;
1552
- }
1553
- if (a === "--join-output") {
1554
- extraJqArgs.push("-j");
1555
- continue;
1556
- }
1557
- if (a === "--tab") {
1558
- extraJqArgs.push("--tab");
1559
- continue;
1560
- }
1561
- if (a === "--indent") {
1562
- if (i + 1 >= opArgs.length) return void 0;
1563
- extraJqArgs.push("--indent", opArgs[++i]);
1564
- continue;
1565
- }
1566
- if (a === "--arg" || a === "--argjson") {
1567
- if (i + 2 >= opArgs.length) return void 0;
1568
- extraJqArgs.push(a, opArgs[i + 1], opArgs[i + 2]);
1569
- i += 2;
1570
- continue;
1571
- }
1572
- if (!a.startsWith("--")) {
1573
- let ok = true;
1574
- for (let j = 1; j < a.length; j++) {
1575
- const ch = a[j];
1576
- if (ch === "r") rawOut = true;
1577
- else if (ch === "c") compactOut = true;
1578
- else if (ch === "n") nullInput = true;
1579
- else if (ch === "S") extraJqArgs.push("-S");
1580
- else if (ch === "j") extraJqArgs.push("-j");
1581
- else {
1582
- ok = false;
1583
- break;
1584
- }
1585
- }
1586
- if (ok) continue;
1587
- }
1588
- return void 0;
1589
- }
1590
- positional.push(a);
1591
- }
1592
- const filter = positional[0] ?? ".";
1593
- const fileArg = positional[1];
1594
- if (positional.length > 2) return void 0;
1595
- let srcBytes = inBytes;
1596
- if (fileArg !== void 0 && fileArg !== "-") {
1597
- if (!readFileSync) return void 0;
1598
- const fBytes = readFileSync(fileArg);
1599
- if (!fBytes || fBytes.byteLength > 8192) return void 0;
1600
- srcBytes = fBytes;
1601
- }
1602
- let xmlText;
1603
- try {
1604
- xmlText = syncXmlDecoder.decode(srcBytes);
1605
- } catch {
1606
- return void 0;
1607
- }
1608
- let jsonStr;
1609
- if (nullInput) {
1610
- jsonStr = "null";
1611
- } else if (xmlText === lastXqXmlText && lastXqJsonStr !== void 0) {
1612
- jsonStr = lastXqJsonStr;
1613
- } else {
1614
- let root;
1615
- try {
1616
- const limits = resolveXmlQueryLimits(void 0);
1617
- const parser = parseXmlSteps(xmlText, { ...limits, maxContentNodes: limits.maxNodes, expectedEncoding: "UTF-8" });
1618
- let step = parser.next();
1619
- while (!step.done) step = parser.next();
1620
- root = step.value;
1621
- } catch {
1622
- return void 0;
1623
- }
1624
- const rootObj = /* @__PURE__ */ Object.create(null);
1625
- rootObj[root.name] = xmlElementToJsonSync(root);
1626
- jsonStr = JSON.stringify(rootObj);
1627
- lastXqXmlText = xmlText;
1628
- lastXqJsonStr = jsonStr;
1629
- }
1630
- const jqArgs = [];
1631
- if (rawOut && compactOut) jqArgs.push("-rc");
1632
- else if (rawOut) jqArgs.push("-r");
1633
- else if (compactOut) jqArgs.push("-c");
1634
- if (nullInput) jqArgs.push("-n");
1635
- jqArgs.push(...extraJqArgs, filter);
1636
- return { jsonStr, jqArgs };
1637
- }
1638
-
1639
- // packages/safe-bash-command-xmllint/src/index.ts
1640
- import { parseXmlSteps as parseXmlSteps2, XmlLimitError as XmlLimitError2 } from "@poe-platform/safe-fs/core";
1641
- import {
1642
- FsError as FsError4,
1643
- getCommandArguments as getCommandArguments2,
1644
- writeBytes as writeBytes2
1645
- } from "../../safe-bash-contracts/index.js";
1646
- import { yieldTurn as yieldTurn3 } from "../../safe-bash-contracts/yield.js";
1647
- import { pathOf as pathOf2 } from "../../safe-bash-contracts/path.js";
1648
- import { writeDiagnostic as writeDiagnostic3 } from "../../safe-bash-contracts/escaping.js";
1649
- import { shellValueByteLength as shellValueByteLength2 } from "../../safe-bash-contracts/value.js";
1650
-
1651
- // packages/safe-bash-xml-engine/src/query.ts
1652
- init_platform();
1653
- var nameStart = (character) => character >= "a" && character <= "z" || character >= "A" && character <= "Z" || character === "_";
1654
- var namePart = (character) => nameStart(character) || character >= "0" && character <= "9" || character === "-" || character === ".";
1655
- async function parseQuery(source, budget) {
1656
- if (source.length > budget.limits.maxSourceBytes || new TextEncoder().encode(source).byteLength > budget.limits.maxSourceBytes)
1657
- throw new XmlQueryLimitError("maxSourceBytes");
1658
- for (let offset = 0; offset < source.length; offset += 256)
1659
- await budget.tick(Math.min(256, source.length - offset));
1660
- let at = 0;
1661
- const fail = () => {
1662
- throw new XmlQueryError(`unsupported XPath syntax at offset ${at}`, 10);
1663
- };
1664
- const space = () => {
1665
- while (source[at] === " " || source[at] === " " || source[at] === "\r" || source[at] === "\n")
1666
- at++;
1667
- };
1668
- const expect = (value) => {
1669
- space();
1670
- if (!source.startsWith(value, at)) fail();
1671
- at += value.length;
1672
- };
1673
- const name = () => {
1674
- space();
1675
- const start = at;
1676
- if (!nameStart(source[at] ?? "")) fail();
1677
- while (namePart(source[at] ?? "")) at++;
1678
- if (source[at] === ":") fail();
1679
- return source.slice(start, at);
1680
- };
1681
- space();
1682
- let scalar;
1683
- if (["string", "count", "boolean"].some(
1684
- (value) => source.startsWith(value, at) && (() => {
1685
- let offset = at + value.length;
1686
- while (" \r\n".includes(source[offset] ?? "") && offset < source.length) offset++;
1687
- return source[offset] === "(";
1688
- })()
1689
- )) {
1690
- const value = name();
1691
- if (value !== "string" && value !== "count" && value !== "boolean") fail();
1692
- scalar = value;
1693
- expect("(");
1694
- }
1695
- const paths = [];
1696
- let morePaths;
1697
- do {
1698
- const steps = [];
1699
- paths.push(steps);
1700
- space();
1701
- do {
1702
- let descendant = false;
1703
- if (source[at] === "/") {
1704
- at++;
1705
- descendant = source[at] === "/";
1706
- if (descendant) at++;
1707
- }
1708
- space();
1709
- let kind = "element";
1710
- if (source[at] === "@") {
1711
- kind = "attribute";
1712
- at++;
1713
- }
1714
- let selected;
1715
- if (source[at] === ".") {
1716
- at++;
1717
- selected = ".";
1718
- kind = source[at] === "." ? "parent" : "self";
1719
- if (kind === "parent") at++;
1720
- } else if (source[at] === "*") {
1721
- selected = "*";
1722
- at++;
1723
- } else {
1724
- selected = name();
1725
- space();
1726
- if (source[at] === "(") {
1727
- if (selected !== "text" || kind !== "element") fail();
1728
- expect("(");
1729
- expect(")");
1730
- kind = "text";
1731
- }
1732
- }
1733
- const predicates = [];
1734
- space();
1735
- while (source[at] === "[") {
1736
- at++;
1737
- space();
1738
- const integer = () => {
1739
- const start = at;
1740
- while ((source[at] ?? "") >= "0" && (source[at] ?? "") <= "9") at++;
1741
- const value = Number(source.slice(start, at));
1742
- if (start === at || !Number.isSafeInteger(value) || value < 1) fail();
1743
- return value;
1744
- };
1745
- if ((source[at] ?? "") >= "0" && (source[at] ?? "") <= "9") {
1746
- predicates.push({ kind: "position", value: integer() });
1747
- } else if (["last", "position"].some(
1748
- (value) => source.startsWith(value, at) && (() => {
1749
- let offset = at + value.length;
1750
- while (offset < source.length && " \r\n".includes(source[offset])) offset++;
1751
- return source[offset] === "(";
1752
- })()
1753
- )) {
1754
- const functionName = name();
1755
- expect("(");
1756
- expect(")");
1757
- if (functionName === "last") predicates.push({ kind: "last" });
1758
- else if (functionName === "position") {
1759
- expect("=");
1760
- space();
1761
- predicates.push({ kind: "position", value: integer() });
1762
- } else fail();
1763
- } else {
1764
- let predicateKind = "child";
1765
- let selectedName = "";
1766
- if (source[at] === "@") {
1767
- at++;
1768
- predicateKind = "attribute";
1769
- selectedName = name();
1770
- } else if (source[at] === ".") {
1771
- at++;
1772
- predicateKind = "self";
1773
- } else {
1774
- selectedName = name();
1775
- space();
1776
- if (source[at] === "(") {
1777
- if (selectedName !== "text") fail();
1778
- expect("(");
1779
- expect(")");
1780
- predicateKind = "text";
1781
- }
1782
- }
1783
- space();
1784
- if (predicateKind === "attribute" && source[at] === "]") {
1785
- predicates.push({ kind: "attribute", name: selectedName });
1786
- } else {
1787
- expect("=");
1788
- space();
1789
- const quote = source[at++];
1790
- if (quote !== "'" && quote !== '"') fail();
1791
- const start = at;
1792
- while (at < source.length && source[at] !== quote) at++;
1793
- if (at === source.length) fail();
1794
- predicates.push({
1795
- kind: predicateKind,
1796
- name: selectedName,
1797
- value: source.slice(start, at++)
1798
- });
1799
- }
1800
- }
1801
- expect("]");
1802
- space();
1803
- }
1804
- steps.push({ descendant, kind, name: selected, predicates });
1805
- if ((kind === "attribute" || kind === "text") && source[at] === "/") fail();
1806
- {
1807
- const _p = budget.tick();
1808
- if (_p) await _p;
1809
- }
1810
- } while (source[at] === "/");
1811
- space();
1812
- morePaths = source[at] === "|";
1813
- if (morePaths) at++;
1814
- } while (morePaths);
1815
- if (scalar !== void 0) expect(")");
1816
- space();
1817
- if (at !== source.length) fail();
1818
- return { scalar, paths };
1819
- }
1820
-
1821
- // packages/safe-bash-xml-engine/src/evaluate.ts
1822
- init_platform();
1823
- var xmlns = "http://www.w3.org/2000/xmlns/";
1824
- async function indexTree(root, budget) {
1825
- const document = { kind: "document", children: [] };
1826
- const order = [document];
1827
- const parentOf = /* @__PURE__ */ new Map();
1828
- const pending = [
1829
- { parent: document, content: root }
1830
- ];
1831
- while (pending.length) {
1832
- {
1833
- const _p = budget.tick();
1834
- if (_p) await _p;
1835
- }
1836
- const { parent, content } = pending.pop();
1837
- if (content.kind === "element") {
1838
- const node = { kind: "element", value: content, children: [], attributes: [] };
1839
- parent.children.push(node);
1840
- parentOf.set(node, parent);
1841
- order.push(node);
1842
- for (const attribute of content.attributes) {
1843
- {
1844
- const _p = budget.tick();
1845
- if (_p) await _p;
1846
- }
1847
- if (attribute.namespace === xmlns) continue;
1848
- const selected = { kind: "attribute", value: attribute };
1849
- node.attributes.push(selected);
1850
- parentOf.set(selected, node);
1851
- order.push(selected);
1852
- }
1853
- for (let index = content.content.length - 1; index >= 0; index--) {
1854
- {
1855
- const _p = budget.tick();
1856
- if (_p) await _p;
1857
- }
1858
- pending.push({ parent: node, content: content.content[index] });
1859
- }
1860
- } else {
1861
- const node = { kind: content.kind, value: content };
1862
- parent.children.push(node);
1863
- parentOf.set(node, parent);
1864
- order.push(node);
1865
- }
1866
- }
1867
- return { document, order, parentOf };
1868
- }
1869
- function matches(node, step) {
1870
- if (step.kind === "self" || step.kind === "parent") return true;
1871
- if (step.kind === "text") return node.kind === "text" || node.kind === "cdata";
1872
- if (node.kind !== step.kind) return false;
1873
- if (node.kind === "element" || node.kind === "attribute") {
1874
- return step.name === "*" || node.value.namespace === "" && node.value.localName === step.name;
1875
- }
1876
- return false;
1877
- }
1878
- async function evaluate(query, root, budget) {
1879
- const { document, order, parentOf } = await indexTree(root, budget);
1880
- const union = /* @__PURE__ */ new Set();
1881
- for (const path of query.paths) {
1882
- let contexts = [document];
1883
- for (const step of path) {
1884
- const parents = /* @__PURE__ */ new Set();
1885
- const pending = [...contexts];
1886
- while (pending.length) {
1887
- {
1888
- const _p = budget.tick();
1889
- if (_p) await _p;
1890
- }
1891
- const node = pending.pop();
1892
- if (parents.has(node)) continue;
1893
- parents.add(node);
1894
- if (step.descendant && (node.kind === "document" || node.kind === "element")) {
1895
- for (const child of node.children) {
1896
- {
1897
- const _p = budget.tick();
1898
- if (_p) await _p;
1899
- }
1900
- pending.push(child);
1901
- }
1902
- }
1903
- }
1904
- const selected = /* @__PURE__ */ new Set();
1905
- for (const parent of parents) {
1906
- {
1907
- const _p = budget.tick();
1908
- if (_p) await _p;
1909
- }
1910
- const candidates = step.kind === "self" ? [parent] : step.kind === "parent" ? parentOf.has(parent) ? [parentOf.get(parent)] : [] : step.kind === "attribute" ? parent.kind === "element" ? parent.attributes : [] : parent.kind === "element" || parent.kind === "document" ? parent.children : [];
1911
- let matched = [];
1912
- for (const candidate of candidates) {
1913
- {
1914
- const _p = budget.tick();
1915
- if (_p) await _p;
1916
- }
1917
- if (matches(candidate, step)) matched.push(candidate);
1918
- }
1919
- for (const predicate of step.predicates) {
1920
- {
1921
- const _p = budget.tick();
1922
- if (_p) await _p;
1923
- }
1924
- if (predicate.kind === "position")
1925
- matched = matched[predicate.value - 1] ? [matched[predicate.value - 1]] : [];
1926
- else if (predicate.kind === "last")
1927
- matched = matched.length ? [matched[matched.length - 1]] : [];
1928
- else {
1929
- const filtered = [];
1930
- for (const candidate of matched) {
1931
- {
1932
- const _p = budget.tick();
1933
- if (_p) await _p;
1934
- }
1935
- if (predicate.kind !== "attribute") {
1936
- const values = [];
1937
- if (predicate.kind === "self") values.push(candidate);
1938
- else if (candidate.kind === "element" || candidate.kind === "document") {
1939
- for (const child of candidate.children) {
1940
- {
1941
- const _p = budget.tick();
1942
- if (_p) await _p;
1943
- }
1944
- if (predicate.kind === "text" ? child.kind === "text" || child.kind === "cdata" : child.kind === "element" && child.value.namespace === "" && child.value.localName === predicate.name)
1945
- values.push(child);
1946
- }
1947
- }
1948
- for (const value of values) {
1949
- {
1950
- const _p = budget.tick();
1951
- if (_p) await _p;
1952
- }
1953
- let text = "";
1954
- for await (const part of stringValue(value, budget)) {
1955
- {
1956
- const _p = budget.tick(part.length);
1957
- if (_p) await _p;
1958
- }
1959
- text += part;
1960
- }
1961
- if (text === predicate.value) {
1962
- filtered.push(candidate);
1963
- break;
1964
- }
1965
- }
1966
- continue;
1967
- }
1968
- if (candidate.kind !== "element") continue;
1969
- for (const attribute of candidate.attributes) {
1970
- {
1971
- const _p = budget.tick(attribute.value.value.length + 1);
1972
- if (_p) await _p;
1973
- }
1974
- if (attribute.value.namespace === "" && attribute.value.localName === predicate.name && (predicate.value === void 0 || attribute.value.value === predicate.value)) {
1975
- filtered.push(candidate);
1976
- break;
1977
- }
1978
- }
1979
- }
1980
- matched = filtered;
1981
- }
1982
- }
1983
- for (const node of matched) {
1984
- {
1985
- const _p = budget.tick();
1986
- if (_p) await _p;
1987
- }
1988
- if (!selected.has(node)) {
1989
- budget.results(selected.size + 1);
1990
- selected.add(node);
1991
- }
1992
- }
1993
- }
1994
- contexts = [];
1995
- for (const node of order) {
1996
- {
1997
- const _p = budget.tick();
1998
- if (_p) await _p;
1999
- }
2000
- if (selected.has(node)) contexts.push(node);
2001
- }
2002
- }
2003
- for (const node of contexts) {
2004
- {
2005
- const _p = budget.tick();
2006
- if (_p) await _p;
2007
- }
2008
- budget.results(union.size + (union.has(node) ? 0 : 1));
2009
- union.add(node);
2010
- }
2011
- }
2012
- const result = [];
2013
- for (const node of order) {
2014
- {
2015
- const _p = budget.tick();
2016
- if (_p) await _p;
2017
- }
2018
- if (union.has(node)) result.push(node);
2019
- }
2020
- return result;
2021
- }
2022
- async function* stringValue(node, budget) {
2023
- if (node === void 0) return;
2024
- if (node.kind === "attribute") {
2025
- yield node.value.value;
2026
- return;
2027
- }
2028
- const pending = [node];
2029
- while (pending.length) {
2030
- {
2031
- const _p = budget.tick();
2032
- if (_p) await _p;
2033
- }
2034
- const current = pending.pop();
2035
- if (current.kind === "element" || current.kind === "document") {
2036
- for (let index = current.children.length - 1; index >= 0; index--) {
2037
- {
2038
- const _p = budget.tick();
2039
- if (_p) await _p;
2040
- }
2041
- pending.push(current.children[index]);
2042
- }
2043
- } else if (current.kind === "text" || current.kind === "cdata") yield current.value.text;
2044
- }
2045
- }
2046
- function serializeSimpleSync(node, budget) {
2047
- if (node.kind === "text" && node.value.text.length > 0 && node.value.text.length < 4096 && !/[&<>"\n\r\t\uD800-\uDFFF]/.test(node.value.text)) {
2048
- if (budget.tick(1 + node.value.text.length)) return void 0;
2049
- return node.value.text;
2050
- }
2051
- return void 0;
2052
- }
2053
- async function* serialize(node, budget) {
2054
- if (node.kind === "text" && node.value.text.length > 0 && node.value.text.length < 4096 && !/[&<>"\n\r\t\uD800-\uDFFF]/.test(node.value.text)) {
2055
- {
2056
- const _p = budget.tick(1 + node.value.text.length);
2057
- if (_p) await _p;
2058
- }
2059
- yield node.value.text;
2060
- return;
2061
- }
2062
- if (node.kind === "attribute") {
2063
- yield ` ${node.value.name}="`;
2064
- yield* escape(node.value.value, true, budget);
2065
- yield '"';
2066
- return;
2067
- }
2068
- if (node.kind === "document") {
2069
- yield '<?xml version="1.0" encoding="UTF-8"?>\n';
2070
- for (const child of node.children) {
2071
- yield* serialize(child, budget);
2072
- yield "\n";
2073
- }
2074
- return;
2075
- }
2076
- const pending = [node.value];
2077
- while (pending.length) {
2078
- {
2079
- const _p = budget.tick();
2080
- if (_p) await _p;
2081
- }
2082
- const current = pending.pop();
2083
- if (typeof current === "string") {
2084
- yield current;
2085
- continue;
2086
- }
2087
- if (current.kind === "element") {
2088
- yield `<${current.name}`;
2089
- for (const attribute of current.attributes) {
2090
- {
2091
- const _p = budget.tick();
2092
- if (_p) await _p;
2093
- }
2094
- yield ` ${attribute.name}="`;
2095
- yield* escape(attribute.value, true, budget);
2096
- yield '"';
2097
- }
2098
- if (!current.content.length) yield "/>";
2099
- else {
2100
- yield ">";
2101
- pending.push(`</${current.name}>`);
2102
- for (let index = current.content.length - 1; index >= 0; index--) {
2103
- {
2104
- const _p = budget.tick();
2105
- if (_p) await _p;
2106
- }
2107
- pending.push(current.content[index]);
2108
- }
2109
- }
2110
- } else if (current.kind === "text") yield* escape(current.text, false, budget);
2111
- else if (current.kind === "cdata") {
2112
- yield "<![CDATA[";
2113
- yield current.text;
2114
- yield "]]>";
2115
- } else if (current.kind === "comment") {
2116
- yield "<!--";
2117
- yield current.text;
2118
- yield "-->";
2119
- } else if (current.kind === "processing-instruction") {
2120
- yield `<?${current.target}`;
2121
- if (current.text) {
2122
- yield " ";
2123
- yield current.text;
2124
- }
2125
- yield "?>";
2126
- }
2127
- }
2128
- }
2129
- async function* escape(value, attribute, budget, options = {}) {
2130
- if (value.length > 0 && value.length < 4096 && !options.ascii && !/[&<>"\n\r\t\uD800-\uDFFF]/.test(value)) {
2131
- {
2132
- const _p = budget.tick(value.length);
2133
- if (_p) await _p;
2134
- }
2135
- yield value;
2136
- return;
2137
- }
2138
- let part = "";
2139
- for (const character of value) {
2140
- {
2141
- const _p = budget.tick();
2142
- if (_p) await _p;
2143
- }
2144
- part += character === "&" ? "&amp;" : character === "<" ? "&lt;" : character === ">" ? "&gt;" : attribute && character === '"' ? "&quot;" : attribute && character === "\n" ? options.canonical ? "&#xA;" : "&#10;" : character === "\r" ? options.canonical ? "&#xD;" : "&#13;" : attribute && character === " " ? options.canonical ? "&#x9;" : "&#9;" : options.ascii && character.codePointAt(0) >= 128 ? `&#x${character.codePointAt(0).toString(16).toUpperCase()};` : character;
2145
- if (part.length >= 4096) {
2146
- yield part;
2147
- part = "";
2148
- }
2149
- }
2150
- if (part) yield part;
2151
- }
2152
-
2153
- // packages/safe-bash-xml-engine/src/document.ts
2154
- init_platform();
2155
- var xmlns2 = "http://www.w3.org/2000/xmlns/";
2156
- var xml = "http://www.w3.org/XML/1998/namespace";
2157
- function compare(left, right) {
2158
- let a = 0, b = 0;
2159
- while (a < left.length && b < right.length) {
2160
- const x = left.codePointAt(a), y = right.codePointAt(b);
2161
- if (x !== y) return x - y;
2162
- a += x > 65535 ? 2 : 1;
2163
- b += y > 65535 ? 2 : 1;
2164
- }
2165
- return left.length - right.length;
2166
- }
2167
- function declaration(source) {
2168
- let result = "<?xml";
2169
- for (const name of ["version", "encoding", "standalone"]) {
2170
- const start = source?.indexOf(name) ?? -1;
2171
- if (start < 0) {
2172
- if (name === "version") result += ' version="1.0"';
2173
- continue;
2174
- }
2175
- let offset = source.indexOf("=", start) + 1;
2176
- while (" \n\r".includes(source[offset])) offset++;
2177
- const quote = source[offset++];
2178
- result += ` ${name}="${source.slice(offset, source.indexOf(quote, offset))}"`;
2179
- }
2180
- return result + "?>\n";
2181
- }
2182
- async function attributes(element, inherited, budget) {
2183
- const selected = [];
2184
- for (const attribute of element.attributes) {
2185
- {
2186
- const _p = budget.tick();
2187
- if (_p) await _p;
2188
- }
2189
- if (attribute.namespace !== xmlns2) selected.push(attribute);
2190
- }
2191
- for (const [prefix, uri] of element.namespaces) {
2192
- {
2193
- const _p = budget.tick(uri.length + prefix.length + 1);
2194
- if (_p) await _p;
2195
- }
2196
- if (prefix === "xml") continue;
2197
- if (uri === (inherited.get(prefix) ?? "")) continue;
2198
- selected.push({
2199
- name: prefix ? `xmlns:${prefix}` : "xmlns",
2200
- namespace: xmlns2,
2201
- localName: prefix,
2202
- value: uri
2203
- });
2204
- }
2205
- const comparisons = Math.ceil(Math.log2(selected.length + 1));
2206
- for (const attribute of selected)
2207
- await budget.tick((attribute.namespace.length + attribute.localName.length + 1) * comparisons);
2208
- selected.sort((left, right) => {
2209
- if (left.namespace === xmlns2 || right.namespace === xmlns2) {
2210
- if (left.namespace !== right.namespace) return left.namespace === xmlns2 ? -1 : 1;
2211
- return compare(left.localName, right.localName);
2212
- }
2213
- return compare(left.namespace, right.namespace) || compare(left.localName, right.localName);
2214
- });
2215
- return selected;
2216
- }
2217
- async function* serializeDocument(root, mode, budget, format = mode === "format") {
2218
- const canonical = mode === "c14n";
2219
- const escaping = { canonical, ascii: !canonical && !root.declaration?.includes("encoding") };
2220
- if (canonical) {
2221
- const elements = [root];
2222
- while (elements.length) {
2223
- const element = elements.pop();
2224
- {
2225
- const _p = budget.tick();
2226
- if (_p) await _p;
2227
- }
2228
- for (const [prefix, uri] of element.namespaces) {
2229
- {
2230
- const _p = budget.tick(prefix.length + uri.length + 1);
2231
- if (_p) await _p;
2232
- }
2233
- if (!uri) continue;
2234
- const colon = uri.indexOf(":");
2235
- let absolute = colon > 0 && "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".includes(uri[0]);
2236
- for (let index = 1; index < colon; index++) {
2237
- if (!"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+.-".includes(
2238
- uri[index]
2239
- ))
2240
- absolute = false;
2241
- }
2242
- if (!absolute) throw new XmlQueryError("Failed to canonicalize: relative namespace URI", 6);
2243
- }
2244
- for (const child of element.children) {
2245
- {
2246
- const _p = budget.tick();
2247
- if (_p) await _p;
2248
- }
2249
- elements.push(child);
2250
- }
2251
- }
2252
- } else yield declaration(root.declaration);
2253
- const namespaces = /* @__PURE__ */ new Map([["xml", xml]]);
2254
- const pending = [];
2255
- for (let index = (root.epilog?.length ?? 0) - 1; index >= 0; index--) {
2256
- const content = root.epilog[index];
2257
- {
2258
- const _p = budget.tick();
2259
- if (_p) await _p;
2260
- }
2261
- if (content.kind === "text") continue;
2262
- if (!canonical) pending.push({ content: "\n", depth: 0, namespaces, preserveSpace: false });
2263
- pending.push({ content, depth: 0, namespaces, preserveSpace: false });
2264
- if (canonical) pending.push({ content: "\n", depth: 0, namespaces, preserveSpace: false });
2265
- }
2266
- if (!canonical) pending.push({ content: "\n", depth: 0, namespaces, preserveSpace: false });
2267
- pending.push({ content: root, depth: 0, namespaces, preserveSpace: false });
2268
- for (let index = (root.prolog?.length ?? 0) - 1; index >= 0; index--) {
2269
- const content = root.prolog[index];
2270
- {
2271
- const _p = budget.tick();
2272
- if (_p) await _p;
2273
- }
2274
- if (content.kind === "text") continue;
2275
- pending.push({ content: "\n", depth: 0, namespaces, preserveSpace: false });
2276
- pending.push({ content, depth: 0, namespaces, preserveSpace: false });
2277
- }
2278
- while (pending.length) {
2279
- {
2280
- const _p = budget.tick();
2281
- if (_p) await _p;
2282
- }
2283
- const frame = pending.pop();
2284
- const current = frame.content;
2285
- if (typeof current === "string") {
2286
- yield current;
2287
- continue;
2288
- }
2289
- if (current.kind === "element") {
2290
- let preserveSpace = frame.preserveSpace;
2291
- for (const attribute of current.attributes) {
2292
- {
2293
- const _p = budget.tick();
2294
- if (_p) await _p;
2295
- }
2296
- if (attribute.namespace === xml && attribute.localName === "space") {
2297
- if (attribute.value === "preserve") preserveSpace = true;
2298
- else if (attribute.value === "default") preserveSpace = false;
2299
- }
2300
- }
2301
- const content = [];
2302
- let mixed = false;
2303
- for (let index = 0; index < current.content.length; index++) {
2304
- const child = current.content[index];
2305
- {
2306
- const _p = budget.tick();
2307
- if (_p) await _p;
2308
- }
2309
- if (child.kind === "text") {
2310
- let blank = true;
2311
- for (const character of child.text) {
2312
- {
2313
- const _p = budget.tick();
2314
- if (_p) await _p;
2315
- }
2316
- if (!" \n\r".includes(character)) blank = false;
2317
- }
2318
- if (format && !preserveSpace && !mixed && blank && (content.length > 0 || index + 1 < current.content.length))
2319
- continue;
2320
- mixed = true;
2321
- } else if (child.kind === "cdata") mixed = true;
2322
- content.push(child);
2323
- }
2324
- const ordered = canonical ? await attributes(current, frame.namespaces, budget) : [];
2325
- if (!canonical) {
2326
- for (const namespace of [true, false])
2327
- for (const attribute of current.attributes) {
2328
- {
2329
- const _p = budget.tick();
2330
- if (_p) await _p;
2331
- }
2332
- if (attribute.namespace === xmlns2 === namespace) ordered.push(attribute);
2333
- }
2334
- }
2335
- yield `<${current.name}`;
2336
- for (const attribute of ordered) {
2337
- {
2338
- const _p = budget.tick();
2339
- if (_p) await _p;
2340
- }
2341
- yield ` ${attribute.name}="`;
2342
- yield* escape(attribute.value, true, budget, escaping);
2343
- yield '"';
2344
- }
2345
- if (!content.length && !canonical) {
2346
- yield "/>";
2347
- continue;
2348
- }
2349
- yield ">";
2350
- const indent = !canonical && format && !mixed && content.length > 0;
2351
- const childNamespaces = canonical ? current.namespaces : frame.namespaces;
2352
- const childFrame = { depth: frame.depth + 1, namespaces: childNamespaces, preserveSpace };
2353
- pending.push({
2354
- ...frame,
2355
- content: `${indent ? "\n" + " ".repeat(frame.depth) : ""}</${current.name}>`
2356
- });
2357
- for (let index = content.length - 1; index >= 0; index--) {
2358
- {
2359
- const _p = budget.tick();
2360
- if (_p) await _p;
2361
- }
2362
- pending.push({ ...childFrame, content: content[index] });
2363
- if (indent) pending.push({ ...childFrame, content: "\n" + " ".repeat(childFrame.depth) });
2364
- }
2365
- } else if (current.kind === "text" || current.kind === "cdata" && canonical)
2366
- yield* escape(current.text, false, budget, escaping);
2367
- else if (current.kind === "cdata") {
2368
- yield "<![CDATA[";
2369
- yield current.text;
2370
- yield "]]>";
2371
- } else if (current.kind === "comment") {
2372
- yield "<!--";
2373
- yield current.text;
2374
- yield "-->";
2375
- } else if (current.kind === "processing-instruction") {
2376
- yield `<?${current.target}`;
2377
- if (current.text) {
2378
- yield " ";
2379
- yield current.text;
2380
- }
2381
- yield "?>";
2382
- }
2383
- }
2384
- }
2385
-
2386
- // packages/safe-bash-command-xmllint/src/index.ts
2387
- var sharedEncoder = new TextEncoder();
2388
- async function argumentsFor2(context, budget) {
2389
- if (context.args.length > 5) throw new XmlQueryError("expected one XML input FILE or -", 2);
2390
- const carrier = getCommandArguments2(context);
2391
- const args = carrier.args;
2392
- async function admitted(position, limit) {
2393
- const text = args[position];
2394
- if (text.length > budget.limits[limit]) throw new XmlQueryLimitError(limit);
2395
- const size = shellValueByteLength2(carrier.values[position]);
2396
- if (size > budget.limits[limit]) throw new XmlQueryLimitError(limit);
2397
- for (let offset = 0; offset < size; offset += 1024)
2398
- await budget.tick(Math.min(1024, size - offset));
2399
- let decoded;
2400
- try {
2401
- decoded = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(
2402
- carrier.bytes(position)
2403
- );
2404
- } catch {
2405
- throw new XmlQueryError("XPath and filenames require valid UTF-8", 2);
2406
- }
2407
- if (decoded !== text) throw new XmlQueryError("XPath and filenames require lossless UTF-8", 2);
2408
- return decoded;
2409
- }
2410
- let index = 0;
2411
- let mode;
2412
- let noout = false;
2413
- let format = false;
2414
- let xpathIndex;
2415
- while (index < args.length) {
2416
- const flag = args[index];
2417
- if (flag === "--noout") {
2418
- noout = true;
2419
- index++;
2420
- } else if (flag === "--format") {
2421
- mode ??= "format";
2422
- format = true;
2423
- index++;
2424
- } else if (flag === "--c14n") {
2425
- mode = "c14n";
2426
- index++;
2427
- } else if (flag === "--xpath") {
2428
- if (xpathIndex !== void 0) throw new XmlQueryError("expected one --xpath QUERY", 2);
2429
- index++;
2430
- if (args[index] === "--") index++;
2431
- const source = args[index];
2432
- if (source === void 0 || source.startsWith("-"))
2433
- throw new XmlQueryError("expected QUERY [FILE|-]", 2);
2434
- xpathIndex = index++;
2435
- } else break;
2436
- }
2437
- if (args[index] === "--") index++;
2438
- const fileIndex = index++;
2439
- const file = args[fileIndex];
2440
- if (index < args.length || file !== void 0 && file.startsWith("-") && file !== "-" && args[fileIndex - 1] !== "--") {
2441
- throw new XmlQueryError("expected one XML input FILE or -", 2);
2442
- }
2443
- if (xpathIndex !== void 0) {
2444
- if (mode !== void 0 || format) throw new XmlQueryError("expected --xpath QUERY [FILE|-]", 2);
2445
- const query = await parseQuery(await admitted(xpathIndex, "maxSourceBytes"), budget);
2446
- return {
2447
- query,
2448
- file: file === void 0 ? void 0 : await admitted(fileIndex, "maxInputBytes")
2449
- };
2450
- }
2451
- mode ??= "format";
2452
- return {
2453
- mode,
2454
- format,
2455
- noout,
2456
- file: file === void 0 ? void 0 : await admitted(fileIndex, "maxInputBytes")
2457
- };
2458
- }
2459
- async function execute(context, limits, runtime2) {
2460
- const budget = new XmlBudget(limits, context.signal, runtime2.yieldTurn);
2461
- let outputFailed = false;
2462
- try {
2463
- const options = await argumentsFor2(context, budget);
2464
- const source = await readXmlInput(context, options.file, budget, runtime2);
2465
- const parser = parseXmlSteps2(source, {
2466
- ...limits,
2467
- maxContentNodes: limits.maxNodes,
2468
- expectedEncoding: "UTF-8"
2469
- });
2470
- let parsed = parser.next();
2471
- try {
2472
- while (!parsed.done) {
2473
- const p = budget.tick(parsed.value);
2474
- if (p) await p;
2475
- parsed = parser.next();
2476
- }
2477
- } finally {
2478
- if (!parsed.done) parser.return(void 0);
2479
- }
2480
- const outBatch = new Uint8Array(16384);
2481
- let outBatchUsed = 0;
2482
- let writesCount = 0;
2483
- async function flushWrite() {
2484
- if (outBatchUsed > 0) {
2485
- const slice = outBatch.subarray(0, outBatchUsed);
2486
- outBatchUsed = 0;
2487
- writesCount++;
2488
- try {
2489
- await writeBytes2(context.stdout, slice, context.signal);
2490
- } catch (error) {
2491
- outputFailed = true;
2492
- throw error;
2493
- }
2494
- }
2495
- }
2496
- async function write(part) {
2497
- for (let offset = 0; offset < part.length; ) {
2498
- let end = Math.min(offset + 4096, part.length);
2499
- if (end < part.length && part.charCodeAt(end - 1) >= 55296 && part.charCodeAt(end - 1) <= 56319)
2500
- end--;
2501
- {
2502
- const _p = budget.tick(end - offset);
2503
- if (_p) await _p;
2504
- }
2505
- const slice = part.slice(offset, end);
2506
- const bytes = sharedEncoder.encode(slice);
2507
- const size = bytes.byteLength;
2508
- if (size > limits.maxOutputBytes - budget.outputBytes) {
2509
- await flushWrite();
2510
- throw new XmlQueryLimitError("maxOutputBytes");
2511
- }
2512
- budget.outputBytes += size;
2513
- if (writesCount < 2 || size >= 8192) {
2514
- await flushWrite();
2515
- writesCount++;
2516
- try {
2517
- await writeBytes2(context.stdout, bytes, context.signal);
2518
- } catch (error) {
2519
- outputFailed = true;
2520
- throw error;
2521
- }
2522
- } else {
2523
- if (outBatchUsed + size > outBatch.byteLength) await flushWrite();
2524
- outBatch.set(bytes, outBatchUsed);
2525
- outBatchUsed += size;
2526
- }
2527
- offset = end;
2528
- }
2529
- }
2530
- if (options.query === void 0) {
2531
- if (!options.noout && options.mode !== void 0) {
2532
- for await (const part of serializeDocument(
2533
- parsed.value,
2534
- options.mode,
2535
- budget,
2536
- options.format
2537
- ))
2538
- await write(part);
2539
- }
2540
- await flushWrite();
2541
- return { exitCode: 0 };
2542
- }
2543
- const nodes = await evaluate(options.query, parsed.value, budget);
2544
- if (options.query.scalar === "count") await write(String(nodes.length));
2545
- else if (options.query.scalar === "boolean") await write(nodes.length ? "true" : "false");
2546
- else if (options.query.scalar === "string") {
2547
- for await (const part of stringValue(nodes[0], budget)) await write(part);
2548
- } else {
2549
- if (!nodes.length) throw new XmlQueryError("XPath set is empty", 11);
2550
- let pendingText = "";
2551
- for (const node of nodes) {
2552
- const simple = writesCount >= 2 ? serializeSimpleSync(node, budget) : void 0;
2553
- if (simple !== void 0) {
2554
- pendingText += simple + "\n";
2555
- if (pendingText.length >= 4096) {
2556
- await write(pendingText);
2557
- pendingText = "";
2558
- }
2559
- } else {
2560
- if (pendingText.length > 0) {
2561
- await write(pendingText);
2562
- pendingText = "";
2563
- }
2564
- for await (const part of serialize(node, budget)) await write(part);
2565
- await write("\n");
2566
- }
2567
- }
2568
- if (pendingText.length > 0) await write(pendingText);
2569
- await flushWrite();
2570
- return { exitCode: 0 };
2571
- }
2572
- await write("\n");
2573
- await flushWrite();
2574
- return { exitCode: 0 };
2575
- } catch (error) {
2576
- context.signal.throwIfAborted();
2577
- if (outputFailed || error instanceof FsError4 && error.code === "EPIPE") throw error;
2578
- const status = error instanceof XmlQueryError ? error.status : error instanceof XmlLimitError2 ? 5 : error instanceof SyntaxError || error instanceof FsError4 ? 1 : void 0;
2579
- if (status === void 0) throw error;
2580
- const message = error instanceof Error ? error.message.slice(0, 1e3) : "XML query failed";
2581
- await runtime2.writeDiagnostic(
2582
- context.stderr,
2583
- `${context.command}: ${message}
2584
- `,
2585
- context.signal
2586
- );
2587
- return { exitCode: status };
2588
- }
2589
- }
2590
- var portableRuntime = {
2591
- yieldTurn: yieldTurn3,
2592
- pathOf: pathOf2,
2593
- writeDiagnostic: writeDiagnostic3,
2594
- async interruptible(operation, signal) {
2595
- signal.throwIfAborted();
2596
- return new Promise((resolve, reject) => {
2597
- const aborted = () => {
2598
- signal.removeEventListener("abort", aborted);
2599
- reject(signal.reason);
2600
- };
2601
- signal.addEventListener("abort", aborted, { once: true });
2602
- try {
2603
- Promise.resolve(operation()).then(
2604
- (result) => {
2605
- signal.removeEventListener("abort", aborted);
2606
- resolve(result);
2607
- },
2608
- (error) => {
2609
- signal.removeEventListener("abort", aborted);
2610
- reject(error);
2611
- }
2612
- );
2613
- } catch (error) {
2614
- signal.removeEventListener("abort", aborted);
2615
- reject(error);
2616
- }
2617
- });
2618
- }
2619
- };
2620
- function createXmllintCommand(options = {}, runtime2 = portableRuntime) {
2621
- const configuredLimits = options.limits;
2622
- const limits = resolveXmlQueryLimits(configuredLimits);
2623
- const definition = { name: "xmllint", execute: (context) => execute(context, limits, runtime2) };
2624
- if (configuredLimits === void 0) builtInDirectContextExecutors.add(definition.execute);
2625
- return definition;
2626
- }
2627
- function createXmllintCommands(options = {}) {
2628
- return [createXmllintCommand(options)];
2629
- }
2630
- function xmllintCommands(options = {}) {
2631
- const commands = createXmllintCommands(options);
2632
- return {
2633
- name: "xmllint-commands",
2634
- setup(host) {
2635
- for (const command of commands) host.commands.register(command, { replace: options.replace ?? false });
2636
- }
2637
- };
2638
- }
2639
- var syncXmlDecoder2 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
2640
- function syncNodeStringValue(node) {
2641
- if (!node) return "";
2642
- if (node.kind === "attribute") return node.value.value;
2643
- let out = "";
2644
- const pending = [node];
2645
- while (pending.length) {
2646
- const cur = pending.pop();
2647
- if (cur.kind === "element" || cur.kind === "document") {
2648
- for (let i = cur.children.length - 1; i >= 0; i--) pending.push(cur.children[i]);
2649
- } else if (cur.kind === "text" || cur.kind === "cdata") {
2650
- out += cur.value.text;
2651
- }
2652
- }
2653
- return out;
2654
- }
2655
- function escapeXmlSync(val, attr) {
2656
- let out = "";
2657
- for (const ch of val) {
2658
- if (ch === "&") out += "&amp;";
2659
- else if (ch === "<") out += "&lt;";
2660
- else if (ch === ">") out += "&gt;";
2661
- else if (attr && ch === '"') out += "&quot;";
2662
- else if (attr && ch === "\n") out += "&#10;";
2663
- else if (ch === "\r") out += "&#13;";
2664
- else if (attr && ch === " ") out += "&#9;";
2665
- else out += ch;
2666
- }
2667
- return out;
2668
- }
2669
- function serializeXmlNodeSync(node) {
2670
- if (node.kind === "attribute") return ` ${node.value.name}="${escapeXmlSync(node.value.value, true)}"`;
2671
- if (node.kind === "document") {
2672
- return '<?xml version="1.0" encoding="UTF-8"?>\n' + node.children.map(serializeXmlNodeSync).join("\n") + "\n";
2673
- }
2674
- let out = "";
2675
- const pending = [node.value];
2676
- while (pending.length) {
2677
- const cur = pending.pop();
2678
- if (typeof cur === "string") {
2679
- out += cur;
2680
- continue;
2681
- }
2682
- if (cur.kind === "element") {
2683
- out += `<${cur.name}`;
2684
- for (const a of cur.attributes) out += ` ${a.name}="${escapeXmlSync(a.value, true)}"`;
2685
- if (!cur.content.length) out += "/>";
2686
- else {
2687
- out += ">";
2688
- pending.push(`</${cur.name}>`);
2689
- for (let i = cur.content.length - 1; i >= 0; i--) pending.push(cur.content[i]);
2690
- }
2691
- } else if (cur.kind === "text") out += escapeXmlSync(cur.text, false);
2692
- else if (cur.kind === "cdata") out += `<![CDATA[${cur.text}]]>`;
2693
- else if (cur.kind === "comment") out += `<!--${cur.text}-->`;
2694
- else if (cur.kind === "processing-instruction") out += `<?${cur.target}${cur.text ? " " + cur.text : ""}?>`;
2695
- }
2696
- return out;
2697
- }
2698
- function evalSyncXmllint(inBytes, opArgs, readFileSync) {
2699
- if (inBytes.byteLength > 8192 || opArgs.length > 5) return void 0;
2700
- let noout = false;
2701
- let format = false;
2702
- let c14n = false;
2703
- let xpathQuery;
2704
- let idx = 0;
2705
- while (idx < opArgs.length) {
2706
- const flag = opArgs[idx];
2707
- if (flag === "--noout") {
2708
- noout = true;
2709
- idx++;
2710
- } else if (flag === "--format") {
2711
- format = true;
2712
- idx++;
2713
- } else if (flag === "--c14n") {
2714
- c14n = true;
2715
- idx++;
2716
- } else if (flag === "--xpath" || flag.startsWith("--xpath=")) {
2717
- if (xpathQuery !== void 0) return void 0;
2718
- if (flag.startsWith("--xpath=")) {
2719
- const q2 = flag.slice(8);
2720
- if (!q2) return void 0;
2721
- xpathQuery = q2;
2722
- idx++;
2723
- } else {
2724
- idx++;
2725
- if (opArgs[idx] === "--") idx++;
2726
- const q2 = opArgs[idx];
2727
- if (!q2 || q2.startsWith("-")) return void 0;
2728
- xpathQuery = q2;
2729
- idx++;
2730
- }
2731
- } else break;
2732
- }
2733
- if (opArgs[idx] === "--") idx++;
2734
- const fileArg = opArgs[idx];
2735
- if (idx + (fileArg !== void 0 ? 1 : 0) < opArgs.length) return void 0;
2736
- if (fileArg !== void 0 && fileArg.startsWith("-") && fileArg !== "-") return void 0;
2737
- if (xpathQuery !== void 0 && (format || c14n || noout)) return void 0;
2738
- let srcBytes = inBytes;
2739
- if (fileArg !== void 0 && fileArg !== "-") {
2740
- if (!readFileSync) return void 0;
2741
- const fBytes = readFileSync(fileArg);
2742
- if (!fBytes || fBytes.byteLength > 8192) return void 0;
2743
- srcBytes = fBytes;
2744
- }
2745
- let xmlText;
2746
- try {
2747
- xmlText = syncXmlDecoder2.decode(srcBytes);
2748
- } catch {
2749
- return void 0;
2750
- }
2751
- let root;
2752
- try {
2753
- const limits = resolveXmlQueryLimits(void 0);
2754
- const parser = parseXmlSteps2(xmlText, { ...limits, maxContentNodes: limits.maxNodes, expectedEncoding: "UTF-8" });
2755
- let step = parser.next();
2756
- while (!step.done) step = parser.next();
2757
- root = step.value;
2758
- } catch {
2759
- return void 0;
2760
- }
2761
- if (noout && xpathQuery === void 0) return "";
2762
- if (xpathQuery === void 0) {
2763
- const escAttr = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/"/g, "&quot;").replace(/\t/g, "&#x9;").replace(/\n/g, "&#xA;").replace(/\r/g, "&#xD;");
2764
- const escText = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\r/g, "&#xD;");
2765
- const renderElem = (el, depth) => {
2766
- const attrs = [...el.attributes].filter((a) => a.namespace !== "http://www.w3.org/2000/xmlns/");
2767
- if (c14n) attrs.sort((a, b) => a.localName.localeCompare(b.localName));
2768
- const attrStr = attrs.map((a) => ` ${a.name}="${escAttr(a.value)}"`).join("");
2769
- const children = [];
2770
- let mixed = false;
2771
- for (let i = 0; i < el.content.length; i++) {
2772
- const ch = el.content[i];
2773
- if (ch.kind === "text") {
2774
- const blank = /^[ \t\n\r]*$/.test(ch.text);
2775
- if (format && !c14n && !mixed && blank && (children.length > 0 || i + 1 < el.content.length)) continue;
2776
- mixed = true;
2777
- } else if (ch.kind === "cdata") mixed = true;
2778
- children.push(ch);
2779
- }
2780
- if (children.length === 0) {
2781
- return c14n ? `<${el.name}${attrStr}></${el.name}>` : `<${el.name}${attrStr}/>`;
2782
- }
2783
- const doIndent = format && !c14n && !mixed;
2784
- let inner = "";
2785
- for (const ch of children) {
2786
- if (doIndent) inner += "\n" + " ".repeat(depth + 1);
2787
- if (ch.kind === "element") inner += renderElem(ch, depth + 1);
2788
- else if (ch.kind === "text" || ch.kind === "cdata" && c14n) inner += escText(ch.text);
2789
- else if (ch.kind === "cdata") inner += `<![CDATA[${ch.text}]]>`;
2790
- else if (ch.kind === "comment") inner += `<!--${ch.text}-->`;
2791
- }
2792
- if (doIndent) inner += "\n" + " ".repeat(depth);
2793
- return `<${el.name}${attrStr}>${inner}</${el.name}>`;
2794
- };
2795
- if (c14n) return renderElem(root, 0);
2796
- return `<?xml version="1.0"?>
2797
- ${renderElem(root, 0)}
2798
- `;
2799
- }
2800
- let q = xpathQuery.trim();
2801
- let scalar;
2802
- for (const s of ["string", "count", "boolean"]) {
2803
- if (q.startsWith(s) && /^\s*\(/.test(q.slice(s.length)) && q.endsWith(")")) {
2804
- scalar = s;
2805
- q = q.slice(q.indexOf("(") + 1, -1).trim();
2806
- break;
2807
- }
2808
- }
2809
- const doc = { kind: "document", children: [] };
2810
- const order = [doc];
2811
- const parentOf = /* @__PURE__ */ new Map();
2812
- const stack = [{ parent: doc, content: root }];
2813
- while (stack.length) {
2814
- const { parent, content } = stack.pop();
2815
- if (content.kind === "element") {
2816
- const elNode = { kind: "element", value: content, children: [], attributes: [] };
2817
- parent.children.push(elNode);
2818
- parentOf.set(elNode, parent);
2819
- order.push(elNode);
2820
- for (const attr of content.attributes) {
2821
- if (attr.namespace === "http://www.w3.org/2000/xmlns/") continue;
2822
- const aNode = { kind: "attribute", value: attr };
2823
- elNode.attributes.push(aNode);
2824
- parentOf.set(aNode, elNode);
2825
- order.push(aNode);
2826
- }
2827
- for (let i = content.content.length - 1; i >= 0; i--) {
2828
- stack.push({ parent: elNode, content: content.content[i] });
2829
- }
2830
- } else {
2831
- const cNode = { kind: content.kind, value: content };
2832
- parent.children.push(cNode);
2833
- parentOf.set(cNode, parent);
2834
- order.push(cNode);
2835
- }
2836
- }
2837
- const unionParts = [];
2838
- {
2839
- let cur = "";
2840
- let inQ;
2841
- let brDepth = 0;
2842
- for (let i = 0; i < q.length; i++) {
2843
- const ch = q[i];
2844
- if (inQ) {
2845
- if (ch === inQ) inQ = void 0;
2846
- cur += ch;
2847
- } else if (ch === '"' || ch === "'") {
2848
- inQ = ch;
2849
- cur += ch;
2850
- } else if (ch === "[") {
2851
- brDepth++;
2852
- cur += ch;
2853
- } else if (ch === "]") {
2854
- brDepth--;
2855
- cur += ch;
2856
- } else if (ch === "|" && brDepth === 0) {
2857
- if (!cur.trim()) return void 0;
2858
- unionParts.push(cur.trim());
2859
- cur = "";
2860
- } else {
2861
- cur += ch;
2862
- }
2863
- }
2864
- if (inQ || brDepth !== 0 || !cur.trim()) return void 0;
2865
- unionParts.push(cur.trim());
2866
- }
2867
- const isNameChar = (c) => /^[A-Za-z0-9_.-]$/.test(c);
2868
- const evalSingleBranch = (branch) => {
2869
- let bContexts = [doc];
2870
- let at = 0;
2871
- let firstStep = true;
2872
- while (at < branch.length) {
2873
- while (at < branch.length && /\s/.test(branch[at])) at++;
2874
- if (!firstStep && branch[at] !== "/") return void 0;
2875
- firstStep = false;
2876
- let descendant = false;
2877
- if (branch[at] === "/") {
2878
- at++;
2879
- if (branch[at] === "/") {
2880
- descendant = true;
2881
- at++;
2882
- }
2883
- }
2884
- while (at < branch.length && /\s/.test(branch[at])) at++;
2885
- let kind = "element";
2886
- if (branch[at] === "@") {
2887
- kind = "attribute";
2888
- at++;
2889
- }
2890
- let selected = "";
2891
- if (branch[at] === ".") {
2892
- at++;
2893
- if (branch[at] === ".") {
2894
- kind = "parent";
2895
- at++;
2896
- selected = ".";
2897
- } else {
2898
- kind = "self";
2899
- selected = ".";
2900
- }
2901
- } else if (branch[at] === "*") {
2902
- selected = "*";
2903
- at++;
2904
- } else {
2905
- const start = at;
2906
- while (at < branch.length && isNameChar(branch[at])) at++;
2907
- if (start === at || branch[at] === ":") return void 0;
2908
- selected = branch.slice(start, at);
2909
- while (at < branch.length && /\s/.test(branch[at])) at++;
2910
- if (branch[at] === "(") {
2911
- if (selected !== "text" || kind !== "element") return void 0;
2912
- at++;
2913
- while (at < branch.length && /\s/.test(branch[at])) at++;
2914
- if (branch[at] !== ")") return void 0;
2915
- at++;
2916
- kind = "text";
2917
- }
2918
- }
2919
- while (at < branch.length && /\s/.test(branch[at])) at++;
2920
- const preds = [];
2921
- while (branch[at] === "[") {
2922
- at++;
2923
- while (at < branch.length && /\s/.test(branch[at])) at++;
2924
- if (/^[0-9]/.test(branch[at] ?? "")) {
2925
- const s = at;
2926
- while (at < branch.length && /^[0-9]$/.test(branch[at])) at++;
2927
- const n = Number(branch.slice(s, at));
2928
- if (!Number.isSafeInteger(n) || n < 1) return void 0;
2929
- preds.push({ kind: "pos", val: n });
2930
- } else if (branch.startsWith("position()", at)) {
2931
- at += 10;
2932
- while (at < branch.length && /\s/.test(branch[at])) at++;
2933
- if (branch[at] !== "=") return void 0;
2934
- at++;
2935
- while (at < branch.length && /\s/.test(branch[at])) at++;
2936
- const s = at;
2937
- while (at < branch.length && /^[0-9]$/.test(branch[at])) at++;
2938
- const n = Number(branch.slice(s, at));
2939
- if (!Number.isSafeInteger(n) || n < 1) return void 0;
2940
- preds.push({ kind: "pos", val: n });
2941
- } else if (branch.startsWith("last()", at)) {
2942
- at += 6;
2943
- preds.push({ kind: "last" });
2944
- } else if (branch.startsWith("text()", at)) {
2945
- at += 6;
2946
- while (at < branch.length && /\s/.test(branch[at])) at++;
2947
- if (branch[at] !== "=") return void 0;
2948
- at++;
2949
- while (at < branch.length && /\s/.test(branch[at])) at++;
2950
- const quote = branch[at++];
2951
- if (quote !== '"' && quote !== "'") return void 0;
2952
- const vs = at;
2953
- while (at < branch.length && branch[at] !== quote) at++;
2954
- if (at >= branch.length) return void 0;
2955
- preds.push({ kind: "textEq", val: branch.slice(vs, at++) });
2956
- } else if (branch[at] === "@") {
2957
- at++;
2958
- const s = at;
2959
- while (at < branch.length && isNameChar(branch[at])) at++;
2960
- if (s === at) return void 0;
2961
- const attrName = branch.slice(s, at);
2962
- while (at < branch.length && /\s/.test(branch[at])) at++;
2963
- if (branch[at] === "]") {
2964
- preds.push({ kind: "attr", name: attrName });
2965
- } else if (branch[at] === "=" || branch[at] === "!" && branch[at + 1] === "=") {
2966
- const neq = branch[at] === "!";
2967
- at += neq ? 2 : 1;
2968
- while (at < branch.length && /\s/.test(branch[at])) at++;
2969
- const quote = branch[at++];
2970
- if (quote !== '"' && quote !== "'") return void 0;
2971
- const vs = at;
2972
- while (at < branch.length && branch[at] !== quote) at++;
2973
- if (at >= branch.length) return void 0;
2974
- preds.push({ kind: "attr", name: attrName, val: branch.slice(vs, at++), neq });
2975
- } else return void 0;
2976
- } else if (isNameChar(branch[at] ?? "")) {
2977
- const s = at;
2978
- while (at < branch.length && isNameChar(branch[at])) at++;
2979
- const childName = branch.slice(s, at);
2980
- while (at < branch.length && /\s/.test(branch[at])) at++;
2981
- if (branch[at] === "]") {
2982
- preds.push({ kind: "child", name: childName });
2983
- } else if (branch[at] === "=") {
2984
- at++;
2985
- while (at < branch.length && /\s/.test(branch[at])) at++;
2986
- const quote = branch[at++];
2987
- if (quote !== '"' && quote !== "'") return void 0;
2988
- const vs = at;
2989
- while (at < branch.length && branch[at] !== quote) at++;
2990
- if (at >= branch.length) return void 0;
2991
- preds.push({ kind: "child", name: childName, val: branch.slice(vs, at++) });
2992
- } else return void 0;
2993
- } else {
2994
- return void 0;
2995
- }
2996
- while (at < branch.length && /\s/.test(branch[at])) at++;
2997
- if (branch[at] !== "]") return void 0;
2998
- at++;
2999
- while (at < branch.length && /\s/.test(branch[at])) at++;
3000
- }
3001
- if ((kind === "attribute" || kind === "text") && at < branch.length) return void 0;
3002
- const parents = /* @__PURE__ */ new Set();
3003
- const pStack = [...bContexts];
3004
- while (pStack.length) {
3005
- const n = pStack.pop();
3006
- if (parents.has(n)) continue;
3007
- parents.add(n);
3008
- if (descendant && (n.kind === "document" || n.kind === "element")) {
3009
- for (const c of n.children) pStack.push(c);
3010
- }
3011
- }
3012
- const selSet = /* @__PURE__ */ new Set();
3013
- for (const p of parents) {
3014
- const cands = kind === "self" ? [p] : kind === "parent" ? parentOf.has(p) ? [parentOf.get(p)] : [] : kind === "attribute" ? p.kind === "element" ? p.attributes : [] : p.kind === "element" || p.kind === "document" ? p.children : [];
3015
- let matched = cands.filter((c) => {
3016
- if (kind === "self" || kind === "parent") return true;
3017
- if (kind === "text") return c.kind === "text" || c.kind === "cdata";
3018
- if (c.kind !== kind) return false;
3019
- if (c.kind === "element" || c.kind === "attribute") {
3020
- return selected === "*" || c.value.namespace === "" && c.value.localName === selected;
3021
- }
3022
- return false;
3023
- });
3024
- for (const pred of preds) {
3025
- if (pred.kind === "pos") matched = matched[pred.val - 1] ? [matched[pred.val - 1]] : [];
3026
- else if (pred.kind === "last") matched = matched.length ? [matched[matched.length - 1]] : [];
3027
- else if (pred.kind === "textEq") {
3028
- matched = matched.filter((c) => c.kind === "element" && syncNodeStringValue(c) === pred.val);
3029
- } else if (pred.kind === "child") {
3030
- matched = matched.filter(
3031
- (c) => c.kind === "element" && c.children.some((ch) => ch.kind === "element" && ch.value.namespace === "" && ch.value.localName === pred.name && (pred.val === void 0 || syncNodeStringValue(ch) === pred.val))
3032
- );
3033
- } else {
3034
- matched = matched.filter(
3035
- (c) => c.kind === "element" && c.attributes.some((a) => a.value.namespace === "" && a.value.localName === pred.name && (pred.val === void 0 || (pred.neq ? a.value.value !== pred.val : a.value.value === pred.val)))
3036
- );
3037
- }
3038
- }
3039
- for (const m of matched) selSet.add(m);
3040
- }
3041
- bContexts = order.filter((n) => selSet.has(n));
3042
- }
3043
- return bContexts;
3044
- };
3045
- const unionSet = /* @__PURE__ */ new Set();
3046
- for (const part of unionParts) {
3047
- const res = evalSingleBranch(part);
3048
- if (!res) return void 0;
3049
- for (const n of res) unionSet.add(n);
3050
- }
3051
- const contexts = order.filter((n) => unionSet.has(n));
3052
- if (scalar === "count") return String(contexts.length) + "\n";
3053
- if (scalar === "boolean") return (contexts.length ? "true" : "false") + "\n";
3054
- if (scalar === "string") return syncNodeStringValue(contexts[0]) + "\n";
3055
- if (contexts.length === 0) return void 0;
3056
- return contexts.map(serializeXmlNodeSync).join("\n") + "\n";
3057
- }
3058
- function createXmlCommands(options = {}) {
3059
- const capturedOptions = { ...options };
3060
- return [createXqCommand(capturedOptions), createXmllintCommand(capturedOptions)];
3061
- }
3062
- function xmlCommands(options = {}) {
3063
- const commands = createXmlCommands(options);
3064
- return {
3065
- name: "xml-commands",
3066
- setup(host) {
3067
- if (!options.replace) {
3068
- for (const command of commands) {
3069
- if (host.commands.has(command.name)) throw new Error(`Command already registered: ${command.name}`);
3070
- }
3071
- }
3072
- for (const command of commands) host.commands.register(command, { replace: options.replace ?? false });
3073
- }
3074
- };
3075
- }
3076
-
3077
- export {
3078
- grepRequirements,
3079
- searchRequirements,
3080
- sedRequirements,
3081
- assertPathRequirements,
3082
- requiredFileInput,
3083
- createJqCommand,
3084
- defaultXmlQueryLimits,
3085
- evalSyncXq,
3086
- createXmllintCommand,
3087
- createXmllintCommands,
3088
- xmllintCommands,
3089
- evalSyncXmllint,
3090
- createXmlCommands,
3091
- xmlCommands
3092
- };
3093
- //# sourceMappingURL=chunk-FZWJ2A7V.js.map