@uipath/common 1.205.0-preview.277 → 1.206.0-preview.279

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 (41) hide show
  1. package/dist/attachment-binding.d.ts +2 -2
  2. package/dist/catch-error.d.ts +1 -0
  3. package/dist/catch-error.js +146 -15
  4. package/dist/classified-failure.d.ts +15 -17
  5. package/dist/command-examples.d.ts +5 -1
  6. package/dist/concurrency.d.ts +7 -0
  7. package/dist/entity-field-rules.js +1 -17
  8. package/dist/entity-name-rules.js +1 -17
  9. package/dist/error-codes.d.ts +41 -0
  10. package/dist/error-handler.d.ts +18 -1
  11. package/dist/error-handler.js +283 -58
  12. package/dist/error-instructions.d.ts +2 -1
  13. package/dist/exit-code.d.ts +30 -3
  14. package/dist/formatter.d.ts +18 -44
  15. package/dist/guid.js +1 -17
  16. package/dist/http-status.d.ts +18 -0
  17. package/dist/index.browser.d.ts +6 -0
  18. package/dist/index.browser.js +4010 -3568
  19. package/dist/index.d.ts +6 -0
  20. package/dist/index.js +7931 -7202
  21. package/dist/named-second.d.ts +27 -0
  22. package/dist/pass-through-tail.d.ts +54 -0
  23. package/dist/polling/poll-failure-mapping.d.ts +10 -7
  24. package/dist/polling/types.d.ts +8 -2
  25. package/dist/project-telemetry.d.ts +84 -0
  26. package/dist/report-failure.d.ts +31 -0
  27. package/dist/result-types.d.ts +12 -0
  28. package/dist/sdk-user-agent.js +19 -2
  29. package/dist/telemetry/index.d.ts +2 -0
  30. package/dist/telemetry/index.js +1816 -1734
  31. package/dist/telemetry/project-identity.d.ts +35 -0
  32. package/dist/telemetry/ship-succeeded.d.ts +7 -1
  33. package/dist/telemetry/telemetry-config.d.ts +2 -0
  34. package/dist/telemetry/telemetry-dimensions.d.ts +19 -1
  35. package/dist/telemetry/telemetry-events.d.ts +1 -0
  36. package/dist/telemetry/telemetry-init.d.ts +9 -3
  37. package/dist/testing.d.ts +57 -0
  38. package/dist/testing.js +3623 -0
  39. package/dist/timings.d.ts +4 -3
  40. package/dist/zip.js +139 -115
  41. package/package.json +6 -2
@@ -0,0 +1,3623 @@
1
+ import { createRequire } from "node:module";
2
+ var __esm = (fn, res, err) => () => {
3
+ if (fn)
4
+ try {
5
+ res = fn(fn = 0);
6
+ } catch (e) {
7
+ err = [e];
8
+ }
9
+ if (err)
10
+ throw err[0];
11
+ return res;
12
+ };
13
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
14
+
15
+ // ../../node_modules/is-inside-container/node_modules/is-docker/index.js
16
+ import fs from "node:fs";
17
+ function hasDockerEnv() {
18
+ try {
19
+ fs.statSync("/.dockerenv");
20
+ return true;
21
+ } catch {
22
+ return false;
23
+ }
24
+ }
25
+ function hasDockerCGroup() {
26
+ try {
27
+ return fs.readFileSync("/proc/self/cgroup", "utf8").includes("docker");
28
+ } catch {
29
+ return false;
30
+ }
31
+ }
32
+ function isDocker() {
33
+ if (isDockerCached === undefined) {
34
+ isDockerCached = hasDockerEnv() || hasDockerCGroup();
35
+ }
36
+ return isDockerCached;
37
+ }
38
+ var isDockerCached;
39
+ var init_is_docker = () => {};
40
+
41
+ // ../../node_modules/is-inside-container/index.js
42
+ import fs2 from "node:fs";
43
+ function isInsideContainer() {
44
+ if (cachedResult === undefined) {
45
+ cachedResult = hasContainerEnv() || isDocker();
46
+ }
47
+ return cachedResult;
48
+ }
49
+ var cachedResult, hasContainerEnv = () => {
50
+ try {
51
+ fs2.statSync("/run/.containerenv");
52
+ return true;
53
+ } catch {
54
+ return false;
55
+ }
56
+ };
57
+ var init_is_inside_container = __esm(() => {
58
+ init_is_docker();
59
+ });
60
+
61
+ // ../../node_modules/wsl-utils/node_modules/is-wsl/index.js
62
+ import process2 from "node:process";
63
+ import os from "node:os";
64
+ import fs3 from "node:fs";
65
+ var isWsl = () => {
66
+ if (process2.platform !== "linux") {
67
+ return false;
68
+ }
69
+ if (os.release().toLowerCase().includes("microsoft")) {
70
+ if (isInsideContainer()) {
71
+ return false;
72
+ }
73
+ return true;
74
+ }
75
+ try {
76
+ if (fs3.readFileSync("/proc/version", "utf8").toLowerCase().includes("microsoft")) {
77
+ return !isInsideContainer();
78
+ }
79
+ } catch {}
80
+ if (fs3.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop") || fs3.existsSync("/run/WSL")) {
81
+ return !isInsideContainer();
82
+ }
83
+ return false;
84
+ }, is_wsl_default;
85
+ var init_is_wsl = __esm(() => {
86
+ init_is_inside_container();
87
+ is_wsl_default = process2.env.__IS_WSL_TEST__ ? isWsl : isWsl();
88
+ });
89
+
90
+ // ../../node_modules/powershell-utils/index.js
91
+ import process3 from "node:process";
92
+ import { Buffer as Buffer2 } from "node:buffer";
93
+ import { promisify } from "node:util";
94
+ import childProcess from "node:child_process";
95
+ var execFile, powerShellPath = () => `${process3.env.SYSTEMROOT || process3.env.windir || String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`, executePowerShell = async (command, options = {}) => {
96
+ const {
97
+ powerShellPath: psPath,
98
+ ...execFileOptions
99
+ } = options;
100
+ const encodedCommand = executePowerShell.encodeCommand(command);
101
+ return execFile(psPath ?? powerShellPath(), [
102
+ ...executePowerShell.argumentsPrefix,
103
+ encodedCommand
104
+ ], {
105
+ encoding: "utf8",
106
+ ...execFileOptions
107
+ });
108
+ };
109
+ var init_powershell_utils = __esm(() => {
110
+ execFile = promisify(childProcess.execFile);
111
+ executePowerShell.argumentsPrefix = [
112
+ "-NoProfile",
113
+ "-NonInteractive",
114
+ "-ExecutionPolicy",
115
+ "Bypass",
116
+ "-EncodedCommand"
117
+ ];
118
+ executePowerShell.encodeCommand = (command) => Buffer2.from(command, "utf16le").toString("base64");
119
+ executePowerShell.escapeArgument = (value) => `'${String(value).replaceAll("'", "''")}'`;
120
+ });
121
+
122
+ // ../../node_modules/wsl-utils/utilities.js
123
+ function parseMountPointFromConfig(content) {
124
+ for (const line of content.split(`
125
+ `)) {
126
+ if (/^\s*#/.test(line)) {
127
+ continue;
128
+ }
129
+ const match = /^\s*root\s*=\s*(?<mountPoint>"[^"]*"|'[^']*'|[^#]*)/.exec(line);
130
+ if (!match) {
131
+ continue;
132
+ }
133
+ return match.groups.mountPoint.trim().replaceAll(/^["']|["']$/g, "");
134
+ }
135
+ }
136
+
137
+ // ../../node_modules/wsl-utils/index.js
138
+ import { promisify as promisify2 } from "node:util";
139
+ import childProcess2 from "node:child_process";
140
+ import fs4, { constants as fsConstants } from "node:fs/promises";
141
+ var execFile2, wslDrivesMountPoint, powerShellPathFromWsl = async () => {
142
+ const mountPoint = await wslDrivesMountPoint();
143
+ return `${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`;
144
+ }, powerShellPath2, canAccessPowerShellPromise, canAccessPowerShell = async () => {
145
+ canAccessPowerShellPromise ??= (async () => {
146
+ try {
147
+ const psPath = await powerShellPath2();
148
+ await fs4.access(psPath, fsConstants.X_OK);
149
+ return true;
150
+ } catch {
151
+ return false;
152
+ }
153
+ })();
154
+ return canAccessPowerShellPromise;
155
+ }, wslDefaultBrowser = async () => {
156
+ const psPath = await powerShellPath2();
157
+ const command = String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`;
158
+ const { stdout } = await executePowerShell(command, { powerShellPath: psPath });
159
+ return stdout.trim();
160
+ }, convertWslPathToWindows = async (path) => {
161
+ if (/^[a-z]+:\/\//i.test(path)) {
162
+ return path;
163
+ }
164
+ try {
165
+ const { stdout } = await execFile2("wslpath", ["-aw", path], { encoding: "utf8" });
166
+ return stdout.trim();
167
+ } catch {
168
+ return path;
169
+ }
170
+ };
171
+ var init_wsl_utils = __esm(() => {
172
+ init_is_wsl();
173
+ init_powershell_utils();
174
+ init_is_wsl();
175
+ execFile2 = promisify2(childProcess2.execFile);
176
+ wslDrivesMountPoint = (() => {
177
+ const defaultMountPoint = "/mnt/";
178
+ let mountPoint;
179
+ return async function() {
180
+ if (mountPoint) {
181
+ return mountPoint;
182
+ }
183
+ const configFilePath = "/etc/wsl.conf";
184
+ let isConfigFileExists = false;
185
+ try {
186
+ await fs4.access(configFilePath, fsConstants.F_OK);
187
+ isConfigFileExists = true;
188
+ } catch {}
189
+ if (!isConfigFileExists) {
190
+ return defaultMountPoint;
191
+ }
192
+ const configContent = await fs4.readFile(configFilePath, { encoding: "utf8" });
193
+ const parsedMountPoint = parseMountPointFromConfig(configContent);
194
+ if (parsedMountPoint === undefined) {
195
+ return defaultMountPoint;
196
+ }
197
+ mountPoint = parsedMountPoint;
198
+ mountPoint = mountPoint.endsWith("/") ? mountPoint : `${mountPoint}/`;
199
+ return mountPoint;
200
+ };
201
+ })();
202
+ powerShellPath2 = is_wsl_default ? powerShellPathFromWsl : powerShellPath;
203
+ });
204
+
205
+ // ../../node_modules/open/node_modules/define-lazy-prop/index.js
206
+ function defineLazyProperty(object, propertyName, valueGetter) {
207
+ const define = (value) => Object.defineProperty(object, propertyName, { value, enumerable: true, writable: true });
208
+ Object.defineProperty(object, propertyName, {
209
+ configurable: true,
210
+ enumerable: true,
211
+ get() {
212
+ const result = valueGetter();
213
+ define(result);
214
+ return result;
215
+ },
216
+ set(value) {
217
+ define(value);
218
+ }
219
+ });
220
+ return object;
221
+ }
222
+
223
+ // ../../node_modules/default-browser-id/index.js
224
+ import { promisify as promisify3 } from "node:util";
225
+ import process4 from "node:process";
226
+ import { execFile as execFile3 } from "node:child_process";
227
+ async function defaultBrowserId() {
228
+ if (process4.platform !== "darwin") {
229
+ throw new Error("macOS only");
230
+ }
231
+ const { stdout } = await execFileAsync("defaults", ["read", "com.apple.LaunchServices/com.apple.launchservices.secure", "LSHandlers"]);
232
+ const match = /LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(stdout);
233
+ const browserId = match?.groups.id ?? "com.apple.Safari";
234
+ if (browserId === "com.apple.safari") {
235
+ return "com.apple.Safari";
236
+ }
237
+ return browserId;
238
+ }
239
+ var execFileAsync;
240
+ var init_default_browser_id = __esm(() => {
241
+ execFileAsync = promisify3(execFile3);
242
+ });
243
+
244
+ // ../../node_modules/run-applescript/index.js
245
+ import process5 from "node:process";
246
+ import { promisify as promisify4 } from "node:util";
247
+ import { execFile as execFile4, execFileSync } from "node:child_process";
248
+ async function runAppleScript(script, { humanReadableOutput = true, signal } = {}) {
249
+ if (process5.platform !== "darwin") {
250
+ throw new Error("macOS only");
251
+ }
252
+ const outputArguments = humanReadableOutput ? [] : ["-ss"];
253
+ const execOptions = {};
254
+ if (signal) {
255
+ execOptions.signal = signal;
256
+ }
257
+ const { stdout } = await execFileAsync2("osascript", ["-e", script, outputArguments], execOptions);
258
+ return stdout.trim();
259
+ }
260
+ var execFileAsync2;
261
+ var init_run_applescript = __esm(() => {
262
+ execFileAsync2 = promisify4(execFile4);
263
+ });
264
+
265
+ // ../../node_modules/bundle-name/index.js
266
+ async function bundleName(bundleId) {
267
+ return runAppleScript(`tell application "Finder" to set app_path to application file id "${bundleId}" as string
268
+ tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`);
269
+ }
270
+ var init_bundle_name = __esm(() => {
271
+ init_run_applescript();
272
+ });
273
+
274
+ // ../../node_modules/default-browser/windows.js
275
+ import { promisify as promisify5 } from "node:util";
276
+ import { execFile as execFile5 } from "node:child_process";
277
+ async function defaultBrowser(_execFileAsync = execFileAsync3) {
278
+ const { stdout } = await _execFileAsync("reg", [
279
+ "QUERY",
280
+ " HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice",
281
+ "/v",
282
+ "ProgId"
283
+ ]);
284
+ const match = /ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(stdout);
285
+ if (!match) {
286
+ throw new UnknownBrowserError(`Cannot find Windows browser in stdout: ${JSON.stringify(stdout)}`);
287
+ }
288
+ const { id } = match.groups;
289
+ const dotIndex = id.lastIndexOf(".");
290
+ const hyphenIndex = id.lastIndexOf("-");
291
+ const baseIdByDot = dotIndex === -1 ? undefined : id.slice(0, dotIndex);
292
+ const baseIdByHyphen = hyphenIndex === -1 ? undefined : id.slice(0, hyphenIndex);
293
+ return windowsBrowserProgIds[id] ?? windowsBrowserProgIds[baseIdByDot] ?? windowsBrowserProgIds[baseIdByHyphen] ?? { name: id, id };
294
+ }
295
+ var execFileAsync3, windowsBrowserProgIds, _windowsBrowserProgIdMap, UnknownBrowserError;
296
+ var init_windows = __esm(() => {
297
+ execFileAsync3 = promisify5(execFile5);
298
+ windowsBrowserProgIds = {
299
+ MSEdgeHTM: { name: "Edge", id: "com.microsoft.edge" },
300
+ MSEdgeBHTML: { name: "Edge Beta", id: "com.microsoft.edge.beta" },
301
+ MSEdgeDHTML: { name: "Edge Dev", id: "com.microsoft.edge.dev" },
302
+ AppXq0fevzme2pys62n3e0fbqa7peapykr8v: { name: "Edge", id: "com.microsoft.edge.old" },
303
+ ChromeHTML: { name: "Chrome", id: "com.google.chrome" },
304
+ ChromeBHTML: { name: "Chrome Beta", id: "com.google.chrome.beta" },
305
+ ChromeDHTML: { name: "Chrome Dev", id: "com.google.chrome.dev" },
306
+ ChromiumHTM: { name: "Chromium", id: "org.chromium.Chromium" },
307
+ BraveHTML: { name: "Brave", id: "com.brave.Browser" },
308
+ BraveBHTML: { name: "Brave Beta", id: "com.brave.Browser.beta" },
309
+ BraveDHTML: { name: "Brave Dev", id: "com.brave.Browser.dev" },
310
+ BraveSSHTM: { name: "Brave Nightly", id: "com.brave.Browser.nightly" },
311
+ FirefoxURL: { name: "Firefox", id: "org.mozilla.firefox" },
312
+ OperaStable: { name: "Opera", id: "com.operasoftware.Opera" },
313
+ VivaldiHTM: { name: "Vivaldi", id: "com.vivaldi.Vivaldi" },
314
+ "IE.HTTP": { name: "Internet Explorer", id: "com.microsoft.ie" }
315
+ };
316
+ _windowsBrowserProgIdMap = new Map(Object.entries(windowsBrowserProgIds));
317
+ UnknownBrowserError = class UnknownBrowserError extends Error {
318
+ };
319
+ });
320
+
321
+ // ../../node_modules/default-browser/index.js
322
+ import { promisify as promisify6 } from "node:util";
323
+ import process6 from "node:process";
324
+ import { execFile as execFile6 } from "node:child_process";
325
+ async function defaultBrowser2() {
326
+ if (process6.platform === "darwin") {
327
+ const id = await defaultBrowserId();
328
+ const name = await bundleName(id);
329
+ return { name, id };
330
+ }
331
+ if (process6.platform === "linux") {
332
+ const { stdout } = await execFileAsync4("xdg-mime", ["query", "default", "x-scheme-handler/http"]);
333
+ const id = stdout.trim();
334
+ const name = titleize(id.replace(/.desktop$/, "").replace("-", " "));
335
+ return { name, id };
336
+ }
337
+ if (process6.platform === "win32") {
338
+ return defaultBrowser();
339
+ }
340
+ throw new Error("Only macOS, Linux, and Windows are supported");
341
+ }
342
+ var execFileAsync4, titleize = (string) => string.toLowerCase().replaceAll(/(?:^|\s|-)\S/g, (x) => x.toUpperCase());
343
+ var init_default_browser = __esm(() => {
344
+ init_default_browser_id();
345
+ init_bundle_name();
346
+ init_windows();
347
+ init_windows();
348
+ execFileAsync4 = promisify6(execFile6);
349
+ });
350
+
351
+ // ../../node_modules/is-in-ssh/index.js
352
+ import process7 from "node:process";
353
+ var isInSsh, is_in_ssh_default;
354
+ var init_is_in_ssh = __esm(() => {
355
+ isInSsh = Boolean(process7.env.SSH_CONNECTION || process7.env.SSH_CLIENT || process7.env.SSH_TTY);
356
+ is_in_ssh_default = isInSsh;
357
+ });
358
+
359
+ // ../../node_modules/open/index.js
360
+ import process8 from "node:process";
361
+ import path from "node:path";
362
+ import { fileURLToPath } from "node:url";
363
+ import childProcess3 from "node:child_process";
364
+ import fs5, { constants as fsConstants2 } from "node:fs/promises";
365
+ function detectArchBinary(binary) {
366
+ if (typeof binary === "string" || Array.isArray(binary)) {
367
+ return binary;
368
+ }
369
+ const { [arch]: archBinary } = binary;
370
+ if (!archBinary) {
371
+ throw new Error(`${arch} is not supported`);
372
+ }
373
+ return archBinary;
374
+ }
375
+ function detectPlatformBinary({ [platform]: platformBinary }, { wsl } = {}) {
376
+ if (wsl && is_wsl_default) {
377
+ return detectArchBinary(wsl);
378
+ }
379
+ if (!platformBinary) {
380
+ throw new Error(`${platform} is not supported`);
381
+ }
382
+ return detectArchBinary(platformBinary);
383
+ }
384
+ var fallbackAttemptSymbol, __dirname2, localXdgOpenPath, platform, arch, tryEachApp = async (apps, opener) => {
385
+ if (apps.length === 0) {
386
+ return;
387
+ }
388
+ const errors = [];
389
+ for (const app of apps) {
390
+ try {
391
+ return await opener(app);
392
+ } catch (error) {
393
+ errors.push(error);
394
+ }
395
+ }
396
+ throw new AggregateError(errors, "Failed to open in all supported apps");
397
+ }, baseOpen = async (options) => {
398
+ options = {
399
+ wait: false,
400
+ background: false,
401
+ newInstance: false,
402
+ allowNonzeroExitCode: false,
403
+ ...options
404
+ };
405
+ const isFallbackAttempt = options[fallbackAttemptSymbol] === true;
406
+ delete options[fallbackAttemptSymbol];
407
+ if (Array.isArray(options.app)) {
408
+ return tryEachApp(options.app, (singleApp) => baseOpen({
409
+ ...options,
410
+ app: singleApp,
411
+ [fallbackAttemptSymbol]: true
412
+ }));
413
+ }
414
+ let { name: app, arguments: appArguments = [] } = options.app ?? {};
415
+ appArguments = [...appArguments];
416
+ if (Array.isArray(app)) {
417
+ return tryEachApp(app, (appName) => baseOpen({
418
+ ...options,
419
+ app: {
420
+ name: appName,
421
+ arguments: appArguments
422
+ },
423
+ [fallbackAttemptSymbol]: true
424
+ }));
425
+ }
426
+ if (app === "browser" || app === "browserPrivate") {
427
+ const ids = {
428
+ "com.google.chrome": "chrome",
429
+ "google-chrome.desktop": "chrome",
430
+ "com.brave.browser": "brave",
431
+ "org.mozilla.firefox": "firefox",
432
+ "firefox.desktop": "firefox",
433
+ "com.microsoft.msedge": "edge",
434
+ "com.microsoft.edge": "edge",
435
+ "com.microsoft.edgemac": "edge",
436
+ "microsoft-edge.desktop": "edge",
437
+ "com.apple.safari": "safari"
438
+ };
439
+ const flags = {
440
+ chrome: "--incognito",
441
+ brave: "--incognito",
442
+ firefox: "--private-window",
443
+ edge: "--inPrivate"
444
+ };
445
+ let browser;
446
+ if (is_wsl_default) {
447
+ const progId = await wslDefaultBrowser();
448
+ const browserInfo = _windowsBrowserProgIdMap.get(progId);
449
+ browser = browserInfo ?? {};
450
+ } else {
451
+ browser = await defaultBrowser2();
452
+ }
453
+ if (browser.id in ids) {
454
+ const browserName = ids[browser.id.toLowerCase()];
455
+ if (app === "browserPrivate") {
456
+ if (browserName === "safari") {
457
+ throw new Error("Safari doesn't support opening in private mode via command line");
458
+ }
459
+ appArguments.push(flags[browserName]);
460
+ }
461
+ return baseOpen({
462
+ ...options,
463
+ app: {
464
+ name: apps[browserName],
465
+ arguments: appArguments
466
+ }
467
+ });
468
+ }
469
+ throw new Error(`${browser.name} is not supported as a default browser`);
470
+ }
471
+ let command;
472
+ const cliArguments = [];
473
+ const childProcessOptions = {};
474
+ let shouldUseWindowsInWsl = false;
475
+ if (is_wsl_default && !isInsideContainer() && !is_in_ssh_default && !app) {
476
+ shouldUseWindowsInWsl = await canAccessPowerShell();
477
+ }
478
+ if (platform === "darwin") {
479
+ command = "open";
480
+ if (options.wait) {
481
+ cliArguments.push("--wait-apps");
482
+ }
483
+ if (options.background) {
484
+ cliArguments.push("--background");
485
+ }
486
+ if (options.newInstance) {
487
+ cliArguments.push("--new");
488
+ }
489
+ if (app) {
490
+ cliArguments.push("-a", app);
491
+ }
492
+ } else if (platform === "win32" || shouldUseWindowsInWsl) {
493
+ command = await powerShellPath2();
494
+ cliArguments.push(...executePowerShell.argumentsPrefix);
495
+ if (!is_wsl_default) {
496
+ childProcessOptions.windowsVerbatimArguments = true;
497
+ }
498
+ if (is_wsl_default && options.target) {
499
+ options.target = await convertWslPathToWindows(options.target);
500
+ }
501
+ const encodedArguments = ["$ProgressPreference = 'SilentlyContinue';", "Start"];
502
+ if (options.wait) {
503
+ encodedArguments.push("-Wait");
504
+ }
505
+ if (app) {
506
+ encodedArguments.push(executePowerShell.escapeArgument(app));
507
+ if (options.target) {
508
+ appArguments.push(options.target);
509
+ }
510
+ } else if (options.target) {
511
+ encodedArguments.push(executePowerShell.escapeArgument(options.target));
512
+ }
513
+ if (appArguments.length > 0) {
514
+ appArguments = appArguments.map((argument) => executePowerShell.escapeArgument(argument));
515
+ encodedArguments.push("-ArgumentList", appArguments.join(","));
516
+ }
517
+ options.target = executePowerShell.encodeCommand(encodedArguments.join(" "));
518
+ if (!options.wait) {
519
+ childProcessOptions.stdio = "ignore";
520
+ }
521
+ } else {
522
+ if (app) {
523
+ command = app;
524
+ } else {
525
+ const isBundled = !__dirname2 || __dirname2 === "/";
526
+ let exeLocalXdgOpen = false;
527
+ try {
528
+ await fs5.access(localXdgOpenPath, fsConstants2.X_OK);
529
+ exeLocalXdgOpen = true;
530
+ } catch {}
531
+ const useSystemXdgOpen = process8.versions.electron ?? (platform === "android" || isBundled || !exeLocalXdgOpen);
532
+ command = useSystemXdgOpen ? "xdg-open" : localXdgOpenPath;
533
+ }
534
+ if (appArguments.length > 0) {
535
+ cliArguments.push(...appArguments);
536
+ }
537
+ if (!options.wait) {
538
+ childProcessOptions.stdio = "ignore";
539
+ childProcessOptions.detached = true;
540
+ }
541
+ }
542
+ if (platform === "darwin" && appArguments.length > 0) {
543
+ cliArguments.push("--args", ...appArguments);
544
+ }
545
+ if (options.target) {
546
+ cliArguments.push(options.target);
547
+ }
548
+ const subprocess = childProcess3.spawn(command, cliArguments, childProcessOptions);
549
+ if (options.wait) {
550
+ return new Promise((resolve, reject) => {
551
+ subprocess.once("error", reject);
552
+ subprocess.once("close", (exitCode) => {
553
+ if (!options.allowNonzeroExitCode && exitCode !== 0) {
554
+ reject(new Error(`Exited with code ${exitCode}`));
555
+ return;
556
+ }
557
+ resolve(subprocess);
558
+ });
559
+ });
560
+ }
561
+ if (isFallbackAttempt) {
562
+ return new Promise((resolve, reject) => {
563
+ subprocess.once("error", reject);
564
+ subprocess.once("spawn", () => {
565
+ subprocess.once("close", (exitCode) => {
566
+ subprocess.off("error", reject);
567
+ if (exitCode !== 0) {
568
+ reject(new Error(`Exited with code ${exitCode}`));
569
+ return;
570
+ }
571
+ subprocess.unref();
572
+ resolve(subprocess);
573
+ });
574
+ });
575
+ });
576
+ }
577
+ subprocess.unref();
578
+ return new Promise((resolve, reject) => {
579
+ subprocess.once("error", reject);
580
+ subprocess.once("spawn", () => {
581
+ subprocess.off("error", reject);
582
+ resolve(subprocess);
583
+ });
584
+ });
585
+ }, open = (target, options) => {
586
+ if (typeof target !== "string") {
587
+ throw new TypeError("Expected a `target`");
588
+ }
589
+ return baseOpen({
590
+ ...options,
591
+ target
592
+ });
593
+ }, apps, open_default;
594
+ var init_open = __esm(() => {
595
+ init_wsl_utils();
596
+ init_powershell_utils();
597
+ init_default_browser();
598
+ init_is_inside_container();
599
+ init_is_in_ssh();
600
+ fallbackAttemptSymbol = Symbol("fallbackAttempt");
601
+ __dirname2 = import.meta.url ? path.dirname(fileURLToPath(import.meta.url)) : "";
602
+ localXdgOpenPath = path.join(__dirname2, "xdg-open");
603
+ ({ platform, arch } = process8);
604
+ apps = {
605
+ browser: "browser",
606
+ browserPrivate: "browserPrivate"
607
+ };
608
+ defineLazyProperty(apps, "chrome", () => detectPlatformBinary({
609
+ darwin: "google chrome",
610
+ win32: "chrome",
611
+ linux: ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser"]
612
+ }, {
613
+ wsl: {
614
+ ia32: "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",
615
+ x64: ["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe", "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]
616
+ }
617
+ }));
618
+ defineLazyProperty(apps, "brave", () => detectPlatformBinary({
619
+ darwin: "brave browser",
620
+ win32: "brave",
621
+ linux: ["brave-browser", "brave"]
622
+ }, {
623
+ wsl: {
624
+ ia32: "/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",
625
+ x64: ["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe", "/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]
626
+ }
627
+ }));
628
+ defineLazyProperty(apps, "firefox", () => detectPlatformBinary({
629
+ darwin: "firefox",
630
+ win32: String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,
631
+ linux: "firefox"
632
+ }, {
633
+ wsl: "/mnt/c/Program Files/Mozilla Firefox/firefox.exe"
634
+ }));
635
+ defineLazyProperty(apps, "edge", () => detectPlatformBinary({
636
+ darwin: "microsoft edge",
637
+ win32: "msedge",
638
+ linux: ["microsoft-edge", "microsoft-edge-dev"]
639
+ }, {
640
+ wsl: "/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"
641
+ }));
642
+ defineLazyProperty(apps, "safari", () => detectPlatformBinary({
643
+ darwin: "Safari"
644
+ }));
645
+ open_default = open;
646
+ });
647
+
648
+ // ../filesystem/src/node.ts
649
+ import { createHash, randomUUID } from "node:crypto";
650
+ import { existsSync } from "node:fs";
651
+ import * as fs6 from "node:fs/promises";
652
+ import * as os2 from "node:os";
653
+ import * as path2 from "node:path";
654
+ var LOCK_HEARTBEAT_MS = 5000;
655
+ var LOCK_STALE_MS = 15000;
656
+ var LOCK_MAX_WAIT_MS = 20000;
657
+ var LOCK_MAX_HOLD_MS = 60000;
658
+ var LOCK_RETRY_MIN_MS = 100;
659
+ var LOCK_RETRY_JITTER_MS = 200;
660
+ var HASH_CHUNK_BYTES = 256 * 1024;
661
+ var hashBuffers = [];
662
+ var HASH_BUFFERS_KEPT = 64;
663
+
664
+ class NodeFileSystem {
665
+ path = {
666
+ join: path2.join,
667
+ resolve: path2.resolve,
668
+ relative: path2.relative,
669
+ dirname: path2.dirname,
670
+ isAbsolute: path2.isAbsolute,
671
+ basename: path2.basename
672
+ };
673
+ env = {
674
+ cwd: process.cwd,
675
+ homedir: os2.homedir,
676
+ tmpdir: os2.tmpdir,
677
+ getenv: (key) => process.env[key]
678
+ };
679
+ utils = {
680
+ open: async (url) => {
681
+ await Promise.resolve().then(() => init_open());
682
+ await open_default(url);
683
+ }
684
+ };
685
+ async readFile(path, options) {
686
+ try {
687
+ if (options) {
688
+ return await fs6.readFile(path, "utf-8");
689
+ }
690
+ return await fs6.readFile(path);
691
+ } catch (error) {
692
+ if (this.isEnoent(error))
693
+ return null;
694
+ throw error;
695
+ }
696
+ }
697
+ async writeFile(filePath, data) {
698
+ const dir = path2.dirname(filePath);
699
+ if (dir) {
700
+ await fs6.mkdir(dir, { recursive: true });
701
+ }
702
+ await fs6.writeFile(filePath, data);
703
+ }
704
+ async appendFile(filePath, data) {
705
+ const dir = path2.dirname(filePath);
706
+ if (dir) {
707
+ await fs6.mkdir(dir, { recursive: true });
708
+ }
709
+ await fs6.appendFile(filePath, data);
710
+ }
711
+ async readdir(dirPath) {
712
+ try {
713
+ return await fs6.readdir(dirPath);
714
+ } catch (error) {
715
+ if (this.isEnoent(error))
716
+ return [];
717
+ throw error;
718
+ }
719
+ }
720
+ async readdirEntries(dirPath) {
721
+ try {
722
+ return await fs6.readdir(dirPath, { withFileTypes: true });
723
+ } catch (error) {
724
+ if (this.isEnoent(error))
725
+ return [];
726
+ throw error;
727
+ }
728
+ }
729
+ async stat(filePath) {
730
+ try {
731
+ const stats = await fs6.stat(filePath);
732
+ return {
733
+ isFile: () => stats.isFile(),
734
+ isDirectory: () => stats.isDirectory(),
735
+ size: stats.size,
736
+ mtimeMs: stats.mtimeMs,
737
+ ctimeMs: stats.ctimeMs
738
+ };
739
+ } catch (error) {
740
+ if (this.isEnoent(error))
741
+ return null;
742
+ throw error;
743
+ }
744
+ }
745
+ async exists(filePath) {
746
+ return existsSync(filePath);
747
+ }
748
+ async mkdir(dirPath) {
749
+ await fs6.mkdir(dirPath, { recursive: true });
750
+ }
751
+ async acquireLock(lockPath) {
752
+ const canonicalPath = await this.canonicalizeLockTarget(lockPath);
753
+ const lockFile = `${canonicalPath}.lock`;
754
+ const ownerId = randomUUID();
755
+ const start = Date.now();
756
+ while (true) {
757
+ try {
758
+ await fs6.writeFile(lockFile, ownerId, { flag: "wx" });
759
+ return this.createLockRelease(lockFile, ownerId);
760
+ } catch (error) {
761
+ if (!this.hasErrnoCode(error, "EEXIST")) {
762
+ throw error;
763
+ }
764
+ const stats = await fs6.stat(lockFile).catch(() => null);
765
+ if (stats && Date.now() - stats.mtimeMs > LOCK_STALE_MS) {
766
+ const reclaimed = await fs6.rm(lockFile, { force: true }).then(() => true).catch(() => false);
767
+ if (reclaimed)
768
+ continue;
769
+ }
770
+ if (Date.now() - start > LOCK_MAX_WAIT_MS) {
771
+ throw new Error(`ELOCKED: timed out waiting for lock on ${canonicalPath}`);
772
+ }
773
+ await new Promise((resolve2) => setTimeout(resolve2, LOCK_RETRY_MIN_MS + Math.random() * LOCK_RETRY_JITTER_MS));
774
+ }
775
+ }
776
+ }
777
+ async canonicalizeLockTarget(lockPath) {
778
+ const absolute = path2.resolve(lockPath);
779
+ const fullReal = await fs6.realpath(absolute).catch(() => null);
780
+ if (fullReal)
781
+ return fullReal;
782
+ const parent = path2.dirname(absolute);
783
+ const base = path2.basename(absolute);
784
+ const canonicalParent = await fs6.realpath(parent).catch(() => parent);
785
+ return path2.join(canonicalParent, base);
786
+ }
787
+ createLockRelease(lockFile, ownerId) {
788
+ const heartbeatStart = Date.now();
789
+ let heartbeatTimer;
790
+ let stopped = false;
791
+ const stopHeartbeat = () => {
792
+ stopped = true;
793
+ if (heartbeatTimer)
794
+ clearTimeout(heartbeatTimer);
795
+ };
796
+ const scheduleNextHeartbeat = () => {
797
+ if (stopped)
798
+ return;
799
+ if (Date.now() - heartbeatStart >= LOCK_MAX_HOLD_MS) {
800
+ stopped = true;
801
+ return;
802
+ }
803
+ heartbeatTimer = setTimeout(() => {
804
+ runHeartbeat();
805
+ }, LOCK_HEARTBEAT_MS);
806
+ heartbeatTimer.unref?.();
807
+ };
808
+ const runHeartbeat = async () => {
809
+ if (stopped)
810
+ return;
811
+ const current = await fs6.readFile(lockFile, "utf-8").catch(() => null);
812
+ if (stopped)
813
+ return;
814
+ if (current !== ownerId) {
815
+ stopped = true;
816
+ return;
817
+ }
818
+ const now = Date.now() / 1000;
819
+ await fs6.utimes(lockFile, now, now).catch(() => {});
820
+ scheduleNextHeartbeat();
821
+ };
822
+ scheduleNextHeartbeat();
823
+ let released = false;
824
+ return async () => {
825
+ if (released)
826
+ return;
827
+ released = true;
828
+ stopHeartbeat();
829
+ const current = await fs6.readFile(lockFile, "utf-8").catch(() => null);
830
+ if (current === ownerId) {
831
+ await fs6.rm(lockFile, { force: true });
832
+ }
833
+ };
834
+ }
835
+ async rm(filePath) {
836
+ await fs6.rm(filePath, { recursive: true, force: true });
837
+ }
838
+ async rename(oldPath, newPath) {
839
+ await fs6.rename(oldPath, newPath);
840
+ }
841
+ async isSymbolicLink(filePath) {
842
+ try {
843
+ return (await fs6.lstat(filePath)).isSymbolicLink();
844
+ } catch (error) {
845
+ if (this.isEnoent(error) || this.hasErrnoCode(error, "ENOTDIR")) {
846
+ return false;
847
+ }
848
+ throw error;
849
+ }
850
+ }
851
+ async hashFile(filePath) {
852
+ let handle;
853
+ try {
854
+ handle = await fs6.open(filePath, "r");
855
+ } catch (error) {
856
+ if (this.isEnoent(error))
857
+ return null;
858
+ throw error;
859
+ }
860
+ const buffer = hashBuffers.pop() ?? Buffer.allocUnsafe(HASH_CHUNK_BYTES);
861
+ try {
862
+ const opened = await handle.stat();
863
+ const stats = {
864
+ isFile: () => opened.isFile(),
865
+ isDirectory: () => opened.isDirectory(),
866
+ size: opened.size,
867
+ mtimeMs: opened.mtimeMs,
868
+ ctimeMs: opened.ctimeMs
869
+ };
870
+ const hash = createHash("sha256");
871
+ let size = 0;
872
+ for (;; ) {
873
+ const { bytesRead } = await handle.read(buffer, 0, buffer.byteLength, null);
874
+ if (bytesRead === 0)
875
+ break;
876
+ hash.update(buffer.subarray(0, bytesRead));
877
+ size += bytesRead;
878
+ }
879
+ return { sha256: hash.digest("hex"), size, stats };
880
+ } finally {
881
+ if (hashBuffers.length < HASH_BUFFERS_KEPT) {
882
+ hashBuffers.push(buffer);
883
+ }
884
+ await handle.close();
885
+ }
886
+ }
887
+ async realpath(filePath) {
888
+ try {
889
+ return await fs6.realpath(filePath);
890
+ } catch (error) {
891
+ if (this.isEnoent(error))
892
+ return filePath;
893
+ throw error;
894
+ }
895
+ }
896
+ async getTempDir() {
897
+ return await fs6.mkdtemp(path2.join(os2.tmpdir(), "uipath-fs-"));
898
+ }
899
+ async copyDirectory(sourcePath, destPath) {
900
+ const sourceStats = await this.stat(sourcePath);
901
+ if (!sourceStats) {
902
+ throw new Error(`Source directory does not exist: ${sourcePath}`);
903
+ }
904
+ if (!sourceStats.isDirectory()) {
905
+ throw new Error(`Source path is not a directory: ${sourcePath}`);
906
+ }
907
+ await this.mkdir(destPath);
908
+ const entries = await this.readdir(sourcePath);
909
+ for (const entry of entries) {
910
+ const srcEntry = path2.join(sourcePath, entry);
911
+ const destEntry = path2.join(destPath, entry);
912
+ const entryStats = await this.stat(srcEntry);
913
+ if (!entryStats)
914
+ continue;
915
+ if (entryStats.isDirectory()) {
916
+ await this.copyDirectory(srcEntry, destEntry);
917
+ } else if (entryStats.isFile()) {
918
+ const content = await this.readFile(srcEntry);
919
+ if (content !== null) {
920
+ await this.writeFile(destEntry, content);
921
+ }
922
+ }
923
+ }
924
+ }
925
+ isEnoent(error) {
926
+ return this.hasErrnoCode(error, "ENOENT");
927
+ }
928
+ hasErrnoCode(error, code) {
929
+ return typeof error === "object" && error !== null && "code" in error && error.code === code;
930
+ }
931
+ }
932
+
933
+ // ../filesystem/src/index.ts
934
+ var fsInstance = new NodeFileSystem;
935
+ var getFileSystem = () => fsInstance;
936
+
937
+ // src/telemetry/telemetry-dimensions.ts
938
+ var BaseDimensions = {
939
+ ApplicationName: "ApplicationName",
940
+ ProductVersion: "ProductVersion",
941
+ InstallationId: "InstallationId",
942
+ CloudUserId: "CloudUserId",
943
+ CloudTenantId: "CloudTenantId",
944
+ CloudOrganizationId: "CloudOrganizationId",
945
+ IsInternalUser: "IsInternalUser",
946
+ Environment: "Environment",
947
+ BaseUrl: "BaseUrl",
948
+ Region: "Region",
949
+ Agent: "Agent",
950
+ AgentVersion: "AgentVersion",
951
+ AgentModel: "AgentModel",
952
+ ToolName: "ToolName",
953
+ ToolVersion: "ToolVersion",
954
+ ExecutionContext: "ExecutionContext",
955
+ CiProvider: "CiProvider",
956
+ SessionIdSource: "SessionIdSource",
957
+ SessionId: "SessionId"
958
+ };
959
+ var CommandDimensions = {
960
+ IsCommand: "IsCommand",
961
+ IsReexec: "IsReexec",
962
+ CommandName: "CommandName",
963
+ ExitCode: "ExitCode",
964
+ TerminalOutcome: "TerminalOutcome",
965
+ ErrorClass: "ErrorClass",
966
+ TerminalSignal: "TerminalSignal",
967
+ ErrorMessage: "ErrorMessage",
968
+ SkillName: "SkillName",
969
+ ProductArea: "ProductArea",
970
+ Mode: "Mode"
971
+ };
972
+ var ProjectDimensions = {
973
+ ProjectKey: "ProjectKey",
974
+ ProjectType: "ProjectType",
975
+ ProjectIdentityStatus: "ProjectIdentityStatus",
976
+ SolutionKey: "SolutionKey",
977
+ SolutionProjectKey: "SolutionProjectKey",
978
+ SolutionIdentityStatus: "SolutionIdentityStatus",
979
+ PreviousSolutionKey: "PreviousSolutionKey"
980
+ };
981
+ var GUID_KEY_DIMENSIONS = new Set([
982
+ ProjectDimensions.ProjectKey,
983
+ ProjectDimensions.SolutionKey,
984
+ ProjectDimensions.SolutionProjectKey,
985
+ ProjectDimensions.PreviousSolutionKey
986
+ ]);
987
+ var ShipDimensions = {
988
+ ShipKind: "ShipKind",
989
+ Target: "Target",
990
+ ProjectType: "ProjectType",
991
+ ProjectTypes: "ProjectTypes",
992
+ ArtifactCorrelationKey: "ArtifactCorrelationKey",
993
+ PackageName: "PackageName",
994
+ PackageVersion: "PackageVersion",
995
+ PackageVersionKey: "PackageVersionKey",
996
+ DeploymentKey: "DeploymentKey",
997
+ SolutionId: "SolutionId",
998
+ FolderKey: "FolderKey",
999
+ FeedId: "FeedId"
1000
+ };
1001
+ var ErrorDimensions = {
1002
+ Result: "Result",
1003
+ ErrorCode: "ErrorCode",
1004
+ Retry: "Retry",
1005
+ ErrorMessage: "ErrorMessage",
1006
+ HttpStatus: "HttpStatus",
1007
+ UpstreamErrorCode: "UpstreamErrorCode"
1008
+ };
1009
+ var AuthDimensions = {
1010
+ AuthenticationMethod: "AuthenticationMethod",
1011
+ Success: "Success",
1012
+ Reason: "Reason"
1013
+ };
1014
+ var SkillsDimensions = {
1015
+ SchemaVersion: "SchemaVersion",
1016
+ AgentType: "AgentType",
1017
+ SkillsVersion: "SkillsVersion",
1018
+ UipSubcommand: "UipSubcommand",
1019
+ FileExtension: "FileExtension",
1020
+ SubagentModel: "SubagentModel",
1021
+ SubagentType: "SubagentType",
1022
+ PermissionMode: "PermissionMode",
1023
+ EffortLevel: "EffortLevel",
1024
+ SessionSource: "SessionSource",
1025
+ Outcome: "Outcome",
1026
+ DurationMs: "DurationMs",
1027
+ Source: "Source"
1028
+ };
1029
+ var PackagerDimensions = {
1030
+ ProjectId: "ProjectId",
1031
+ ProjectType: "ProjectType",
1032
+ SolutionId: "SolutionId"
1033
+ };
1034
+ var ScopeDimensions = {
1035
+ FolderId: "FolderId"
1036
+ };
1037
+ var ID_DIMENSIONS = new Set([
1038
+ BaseDimensions.CloudUserId,
1039
+ BaseDimensions.CloudTenantId,
1040
+ BaseDimensions.CloudOrganizationId,
1041
+ BaseDimensions.InstallationId,
1042
+ ShipDimensions.ArtifactCorrelationKey,
1043
+ ShipDimensions.PackageVersionKey,
1044
+ ShipDimensions.DeploymentKey,
1045
+ ShipDimensions.SolutionId,
1046
+ ShipDimensions.FolderKey,
1047
+ ShipDimensions.FeedId,
1048
+ PackagerDimensions.ProjectId
1049
+ ]);
1050
+ var NON_IDENTIFIER_PLACEHOLDER_PATTERN = /^(?:\[[A-Z_]+\]|<[^>]+>)$/;
1051
+ var RESERVED_DIMENSION_NAMES = new Set([
1052
+ ...Object.values(BaseDimensions),
1053
+ ...Object.values(CommandDimensions),
1054
+ ...Object.values(ShipDimensions),
1055
+ ...Object.values(ProjectDimensions),
1056
+ ...Object.values(ErrorDimensions),
1057
+ ...Object.values(AuthDimensions),
1058
+ ...Object.values(SkillsDimensions),
1059
+ ...Object.values(PackagerDimensions),
1060
+ ...Object.values(ScopeDimensions)
1061
+ ]);
1062
+ var CURATED_DIMENSIONS = new Set([
1063
+ BaseDimensions.ApplicationName,
1064
+ BaseDimensions.ProductVersion,
1065
+ BaseDimensions.InstallationId,
1066
+ BaseDimensions.CloudUserId,
1067
+ BaseDimensions.CloudTenantId,
1068
+ BaseDimensions.CloudOrganizationId,
1069
+ BaseDimensions.IsInternalUser,
1070
+ BaseDimensions.Environment,
1071
+ BaseDimensions.BaseUrl,
1072
+ BaseDimensions.Region,
1073
+ BaseDimensions.Agent,
1074
+ BaseDimensions.AgentVersion,
1075
+ BaseDimensions.ToolVersion,
1076
+ BaseDimensions.ExecutionContext,
1077
+ BaseDimensions.CiProvider,
1078
+ BaseDimensions.SessionIdSource,
1079
+ BaseDimensions.SessionId,
1080
+ ...Object.values(CommandDimensions),
1081
+ ...Object.values(ShipDimensions),
1082
+ ...Object.values(ProjectDimensions)
1083
+ ]);
1084
+ function lowercaseIdDimensionValues(properties) {
1085
+ let changed = false;
1086
+ const result = {
1087
+ ...properties
1088
+ };
1089
+ for (const key of Object.keys(result)) {
1090
+ const value = result[key];
1091
+ if (!ID_DIMENSIONS.has(key) || typeof value !== "string" || NON_IDENTIFIER_PLACEHOLDER_PATTERN.test(value)) {
1092
+ continue;
1093
+ }
1094
+ const lowered = value.toLowerCase();
1095
+ if (lowered !== value) {
1096
+ result[key] = lowered;
1097
+ changed = true;
1098
+ }
1099
+ }
1100
+ return changed ? result : properties;
1101
+ }
1102
+
1103
+ // src/telemetry/project-identity.ts
1104
+ function projectKey(id) {
1105
+ if (typeof id !== "string")
1106
+ return;
1107
+ const key = id.trim().toLowerCase().replaceAll("-", "");
1108
+ return /^[0-9a-f]{32}$/.test(key) ? key : undefined;
1109
+ }
1110
+
1111
+ // src/telemetry/pseudonymize.ts
1112
+ var PSEUDONYM_DOMAIN = "uipath-cli/telemetry/pseudonym/v1:";
1113
+ var PSEUDONYM_HEX_LENGTH = 32;
1114
+ var SHA256_K = new Uint32Array([
1115
+ 1116352408,
1116
+ 1899447441,
1117
+ 3049323471,
1118
+ 3921009573,
1119
+ 961987163,
1120
+ 1508970993,
1121
+ 2453635748,
1122
+ 2870763221,
1123
+ 3624381080,
1124
+ 310598401,
1125
+ 607225278,
1126
+ 1426881987,
1127
+ 1925078388,
1128
+ 2162078206,
1129
+ 2614888103,
1130
+ 3248222580,
1131
+ 3835390401,
1132
+ 4022224774,
1133
+ 264347078,
1134
+ 604807628,
1135
+ 770255983,
1136
+ 1249150122,
1137
+ 1555081692,
1138
+ 1996064986,
1139
+ 2554220882,
1140
+ 2821834349,
1141
+ 2952996808,
1142
+ 3210313671,
1143
+ 3336571891,
1144
+ 3584528711,
1145
+ 113926993,
1146
+ 338241895,
1147
+ 666307205,
1148
+ 773529912,
1149
+ 1294757372,
1150
+ 1396182291,
1151
+ 1695183700,
1152
+ 1986661051,
1153
+ 2177026350,
1154
+ 2456956037,
1155
+ 2730485921,
1156
+ 2820302411,
1157
+ 3259730800,
1158
+ 3345764771,
1159
+ 3516065817,
1160
+ 3600352804,
1161
+ 4094571909,
1162
+ 275423344,
1163
+ 430227734,
1164
+ 506948616,
1165
+ 659060556,
1166
+ 883997877,
1167
+ 958139571,
1168
+ 1322822218,
1169
+ 1537002063,
1170
+ 1747873779,
1171
+ 1955562222,
1172
+ 2024104815,
1173
+ 2227730452,
1174
+ 2361852424,
1175
+ 2428436474,
1176
+ 2756734187,
1177
+ 3204031479,
1178
+ 3329325298
1179
+ ]);
1180
+ var SHA256_INITIAL_STATE = new Uint32Array([
1181
+ 1779033703,
1182
+ 3144134277,
1183
+ 1013904242,
1184
+ 2773480762,
1185
+ 1359893119,
1186
+ 2600822924,
1187
+ 528734635,
1188
+ 1541459225
1189
+ ]);
1190
+ function rotr(value, bits) {
1191
+ return (value >>> bits | value << 32 - bits) >>> 0;
1192
+ }
1193
+ function sha256Hex(input) {
1194
+ const bytes = new TextEncoder().encode(input);
1195
+ const paddedLength = bytes.length + 9 + 63 >> 6 << 6;
1196
+ const buffer = new Uint8Array(paddedLength);
1197
+ buffer.set(bytes);
1198
+ buffer[bytes.length] = 128;
1199
+ const view = new DataView(buffer.buffer);
1200
+ const bitLength = bytes.length * 8;
1201
+ view.setUint32(paddedLength - 8, Math.floor(bitLength / 4294967296));
1202
+ view.setUint32(paddedLength - 4, bitLength >>> 0);
1203
+ const state = SHA256_INITIAL_STATE.slice();
1204
+ const schedule = new Uint32Array(64);
1205
+ for (let offset = 0;offset < paddedLength; offset += 64) {
1206
+ for (let i = 0;i < 16; i++) {
1207
+ schedule[i] = view.getUint32(offset + i * 4);
1208
+ }
1209
+ for (let i = 16;i < 64; i++) {
1210
+ const x = schedule[i - 15];
1211
+ const y = schedule[i - 2];
1212
+ const s0 = (rotr(x, 7) ^ rotr(x, 18) ^ x >>> 3) >>> 0;
1213
+ const s1 = (rotr(y, 17) ^ rotr(y, 19) ^ y >>> 10) >>> 0;
1214
+ schedule[i] = schedule[i - 16] + s0 + schedule[i - 7] + s1 >>> 0;
1215
+ }
1216
+ let a = state[0];
1217
+ let b = state[1];
1218
+ let c = state[2];
1219
+ let d = state[3];
1220
+ let e = state[4];
1221
+ let f = state[5];
1222
+ let g = state[6];
1223
+ let h = state[7];
1224
+ for (let i = 0;i < 64; i++) {
1225
+ const s1 = (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) >>> 0;
1226
+ const ch = (e & f ^ ~e & g) >>> 0;
1227
+ const temp1 = h + s1 + ch + SHA256_K[i] + schedule[i] >>> 0;
1228
+ const s0 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) >>> 0;
1229
+ const maj = (a & b ^ a & c ^ b & c) >>> 0;
1230
+ const temp2 = s0 + maj >>> 0;
1231
+ h = g;
1232
+ g = f;
1233
+ f = e;
1234
+ e = d + temp1 >>> 0;
1235
+ d = c;
1236
+ c = b;
1237
+ b = a;
1238
+ a = temp1 + temp2 >>> 0;
1239
+ }
1240
+ state[0] = state[0] + a >>> 0;
1241
+ state[1] = state[1] + b >>> 0;
1242
+ state[2] = state[2] + c >>> 0;
1243
+ state[3] = state[3] + d >>> 0;
1244
+ state[4] = state[4] + e >>> 0;
1245
+ state[5] = state[5] + f >>> 0;
1246
+ state[6] = state[6] + g >>> 0;
1247
+ state[7] = state[7] + h >>> 0;
1248
+ }
1249
+ let hex = "";
1250
+ for (const word of state) {
1251
+ hex += word.toString(16).padStart(8, "0");
1252
+ }
1253
+ return hex;
1254
+ }
1255
+ function resolveSha256Hex() {
1256
+ try {
1257
+ const nodeCrypto = __require("node:crypto");
1258
+ const createHash = nodeCrypto?.createHash;
1259
+ if (typeof createHash !== "function") {
1260
+ return sha256Hex;
1261
+ }
1262
+ const native = (input) => createHash("sha256").update(input, "utf8").digest("hex");
1263
+ return native("abc") === sha256Hex("abc") ? native : sha256Hex;
1264
+ } catch {
1265
+ return sha256Hex;
1266
+ }
1267
+ }
1268
+ var cachedSha256Hex;
1269
+ function digest(input) {
1270
+ cachedSha256Hex ??= resolveSha256Hex();
1271
+ return cachedSha256Hex(input);
1272
+ }
1273
+ function pseudonymize(input) {
1274
+ return digest(`${PSEUDONYM_DOMAIN}${input}`).slice(0, PSEUDONYM_HEX_LENGTH);
1275
+ }
1276
+
1277
+ // src/singleton.ts
1278
+ var PREFIX = "@uipath/common/";
1279
+ var _g = globalThis;
1280
+ function singleton(ctorOrName) {
1281
+ const name = typeof ctorOrName === "string" ? ctorOrName : ctorOrName.name;
1282
+ const key = Symbol.for(PREFIX + name);
1283
+ return {
1284
+ get(fallback) {
1285
+ return _g[key] ?? fallback;
1286
+ },
1287
+ set(value) {
1288
+ _g[key] = value;
1289
+ },
1290
+ clear() {
1291
+ delete _g[key];
1292
+ },
1293
+ getOrInit(factory, guard) {
1294
+ const existing = _g[key];
1295
+ if (existing != null && typeof existing === "object") {
1296
+ if (!guard || guard(existing)) {
1297
+ return existing;
1298
+ }
1299
+ }
1300
+ const instance = factory();
1301
+ _g[key] = instance;
1302
+ return instance;
1303
+ }
1304
+ };
1305
+ }
1306
+
1307
+ // src/telemetry/supplied-values.ts
1308
+ var suppliedValuesSlot = singleton("TelemetrySuppliedArgumentValues");
1309
+ function activeEntries() {
1310
+ const existing = suppliedValuesSlot.get();
1311
+ return Array.isArray(existing) ? existing : [];
1312
+ }
1313
+ function getSuppliedArgumentValues() {
1314
+ const all = new Set;
1315
+ for (const entry of activeEntries()) {
1316
+ for (const value of entry.values) {
1317
+ all.add(value);
1318
+ }
1319
+ }
1320
+ return [...all].sort((a, b) => b.length - a.length);
1321
+ }
1322
+
1323
+ // src/telemetry/pii-redactor.ts
1324
+ var REDACTED = "[REDACTED]";
1325
+ var MAX_VALUE_LENGTH = 280;
1326
+ var MAX_STACK_LENGTH = 4096;
1327
+ var MAX_SCAN_LENGTH = MAX_STACK_LENGTH;
1328
+ function truncate(value, maxLength) {
1329
+ return value.length > maxLength ? `${value.slice(0, maxLength)}…` : value;
1330
+ }
1331
+ var SENSITIVE_NAME_TOKENS = new Set([
1332
+ "token",
1333
+ "tokens",
1334
+ "secret",
1335
+ "secrets",
1336
+ "password",
1337
+ "passwords",
1338
+ "pwd",
1339
+ "credential",
1340
+ "credentials",
1341
+ "auth",
1342
+ "authentication",
1343
+ "authorization",
1344
+ "authority",
1345
+ "cert",
1346
+ "certificate",
1347
+ "certificates"
1348
+ ]);
1349
+ var SENSITIVE_KEY_PREFIXES = new Set([
1350
+ "api",
1351
+ "access",
1352
+ "client",
1353
+ "private",
1354
+ "public",
1355
+ "signing",
1356
+ "encryption",
1357
+ "session",
1358
+ "master",
1359
+ "shared",
1360
+ "root",
1361
+ "ssh",
1362
+ "rsa",
1363
+ "aes",
1364
+ "hmac",
1365
+ "oauth"
1366
+ ]);
1367
+ var UUID_PATTERN = /\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi;
1368
+ var EMAIL_PATTERN = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g;
1369
+ var JWT_PATTERN = /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g;
1370
+ var LONG_TOKEN_PATTERN = /\b[A-Za-z0-9_-]{40,}\b/g;
1371
+ var PADDED_BASE64_PATTERN = /(?<![A-Za-z0-9+/])[A-Za-z0-9+/]{16,}={1,2}(?![A-Za-z0-9+/=])/g;
1372
+ var BASE64_WITH_PLUS_PATTERN = /[A-Za-z0-9+/]{40,}/g;
1373
+ var USER_HOME_PATTERN = /(?<![A-Za-z0-9._-])([/\\])(Users|home|Profiles)([/\\])([^/\\]+)/gi;
1374
+ var UNC_PATH_PATTERN = /(^|[\s"'<>|=,;([{])(\\\\[^\s"'<>|]+)/g;
1375
+ var HOST_PORT_PATTERN = /(?<![/@.\w-])(?!\d+\.\d+\.\d+\.\d+:)[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)+:\d{1,5}\b/g;
1376
+ var SOURCE_FILE_EXTENSIONS = new Set([
1377
+ "ts",
1378
+ "tsx",
1379
+ "js",
1380
+ "jsx",
1381
+ "mjs",
1382
+ "cjs",
1383
+ "cts",
1384
+ "mts",
1385
+ "py",
1386
+ "cs",
1387
+ "java",
1388
+ "go",
1389
+ "rs",
1390
+ "rb",
1391
+ "php",
1392
+ "sh",
1393
+ "ps1",
1394
+ "json",
1395
+ "jsonc",
1396
+ "yaml",
1397
+ "yml",
1398
+ "xml",
1399
+ "xaml",
1400
+ "md",
1401
+ "txt",
1402
+ "log",
1403
+ "css",
1404
+ "html",
1405
+ "htm",
1406
+ "csproj",
1407
+ "nuspec",
1408
+ "sql"
1409
+ ]);
1410
+ var URL_PATTERN = /\bhttps?:\/\/[^\s,;]+/gi;
1411
+ var QUOTED_LITERAL_MAX_SPAN = 200;
1412
+ var QUOTED_LITERAL_PATTERN = new RegExp([
1413
+ `(?<![A-Za-z0-9])'(?:[^\\
1414
+ ]|\\.){2,${QUOTED_LITERAL_MAX_SPAN}}?'(?![A-Za-z0-9])`,
1415
+ `(?<![A-Za-z0-9])"(?:[^\\
1416
+ ]|\\.){2,${QUOTED_LITERAL_MAX_SPAN}}?"(?![A-Za-z0-9])`
1417
+ ].join("|"), "g");
1418
+ var JSON_BODY_PATTERN = /[{[][^{}[\]:,]*[:,][^{}[\]]*[\]}]/g;
1419
+ var COLLAPSED_BODY = "{…}";
1420
+ var COLLAPSED_BODY_MARKER = "\x01body\x01";
1421
+ var MAX_BODY_NESTING = 8;
1422
+ function collapseJsonBodies(text) {
1423
+ let out = text;
1424
+ for (let pass = 0;pass < MAX_BODY_NESTING; pass++) {
1425
+ const next = out.replace(JSON_BODY_PATTERN, COLLAPSED_BODY_MARKER);
1426
+ if (next === out) {
1427
+ break;
1428
+ }
1429
+ out = next;
1430
+ }
1431
+ return out.split(COLLAPSED_BODY_MARKER).join(COLLAPSED_BODY);
1432
+ }
1433
+ var TRAILING_PROSE_PUNCT = `.,;:!?)]}>'"`;
1434
+ function peelTrailingPunctuation(match) {
1435
+ let end = match.length;
1436
+ while (end > 0 && TRAILING_PROSE_PUNCT.includes(match[end - 1])) {
1437
+ end -= 1;
1438
+ }
1439
+ return [match.slice(0, end), match.slice(end)];
1440
+ }
1441
+ function redactUrl(raw) {
1442
+ try {
1443
+ const url = new URL(raw);
1444
+ return `${url.protocol}//${url.host}`;
1445
+ } catch {
1446
+ return `url#${pseudonymize(raw)}`;
1447
+ }
1448
+ }
1449
+ function redactValueDetectors(value, maxLength = MAX_VALUE_LENGTH) {
1450
+ let out = truncate(value, MAX_SCAN_LENGTH);
1451
+ out = out.replace(JWT_PATTERN, () => REDACTED);
1452
+ out = out.replace(URL_PATTERN, (match) => {
1453
+ const [core, trailing] = peelTrailingPunctuation(match);
1454
+ return `${redactUrl(core)}${trailing}`;
1455
+ });
1456
+ out = out.replace(USER_HOME_PATTERN, (_match, sep1, folder, sep2) => `${sep1}${folder}${sep2}<user>`);
1457
+ out = out.replace(UNC_PATH_PATTERN, (_match, before, path) => {
1458
+ const [core, trailing] = peelTrailingPunctuation(path);
1459
+ return `${before}unc#${pseudonymize(core)}${trailing}`;
1460
+ });
1461
+ out = out.replace(EMAIL_PATTERN, (match) => `email#${pseudonymize(match)}`);
1462
+ out = out.replace(UUID_PATTERN, (match) => `uuid#${pseudonymize(match)}`);
1463
+ out = out.replace(HOST_PORT_PATTERN, (match) => {
1464
+ const split = match.lastIndexOf(":");
1465
+ const host = match.slice(0, split);
1466
+ const extension = host.slice(host.lastIndexOf(".") + 1).toLowerCase();
1467
+ if (SOURCE_FILE_EXTENSIONS.has(extension)) {
1468
+ return match;
1469
+ }
1470
+ return `host#${pseudonymize(host)}:${match.slice(split + 1)}`;
1471
+ });
1472
+ out = out.replace(PADDED_BASE64_PATTERN, () => REDACTED);
1473
+ out = out.replace(BASE64_WITH_PLUS_PATTERN, (match) => match.includes("+") ? REDACTED : match);
1474
+ out = out.replace(LONG_TOKEN_PATTERN, () => REDACTED);
1475
+ return truncate(out, maxLength);
1476
+ }
1477
+ function redactSpanName(name) {
1478
+ return redactValueDetectors(truncate(name, MAX_SCAN_LENGTH).replace(QUOTED_LITERAL_PATTERN, (match) => `${match[0]}<redacted>${match[0]}`));
1479
+ }
1480
+ var HTTP_DEPENDENCY_NAME = /^([A-Z]+) (\/.*)$/s;
1481
+ function redactHttpDependencyName(name) {
1482
+ const parts = HTTP_DEPENDENCY_NAME.exec(name);
1483
+ if (!parts) {
1484
+ return redactMessage(name);
1485
+ }
1486
+ return `${parts[1]} ${redactMessage(parts[2])}`;
1487
+ }
1488
+ function redactMessage(value) {
1489
+ let out = collapseJsonBodies(truncate(value, MAX_SCAN_LENGTH)).replace(QUOTED_LITERAL_PATTERN, (match) => `${match[0]}<redacted>${match[0]}`);
1490
+ for (const supplied of getSuppliedArgumentValues()) {
1491
+ out = out.split(supplied).join(REDACTED);
1492
+ }
1493
+ return redactValueDetectors(out);
1494
+ }
1495
+ var MESSAGE_NAMES = new Set([
1496
+ "message",
1497
+ "errormessage",
1498
+ "errmessage",
1499
+ "error_message",
1500
+ "msg",
1501
+ "detail",
1502
+ "details",
1503
+ "reason",
1504
+ "instructions",
1505
+ "warning"
1506
+ ]);
1507
+ function isFreeFormValue(name, value) {
1508
+ return MESSAGE_NAMES.has(name.toLowerCase()) || /['"{[]/.test(value);
1509
+ }
1510
+ function redactError(error) {
1511
+ const safe = new Error(redactMessage(error.message ?? ""));
1512
+ safe.name = error.name;
1513
+ safe.stack = typeof error.stack === "string" ? redactStack(error.stack) : undefined;
1514
+ return safe;
1515
+ }
1516
+ function redactStack(stack) {
1517
+ const bounded = truncate(stack, MAX_STACK_LENGTH);
1518
+ const firstBreak = bounded.indexOf(`
1519
+ `);
1520
+ if (firstBreak === -1) {
1521
+ return redactMessage(bounded);
1522
+ }
1523
+ return `${redactMessage(bounded.slice(0, firstBreak))}
1524
+ ${redactValueDetectors(bounded.slice(firstBreak + 1), MAX_STACK_LENGTH)}`;
1525
+ }
1526
+ function nameTokens(name) {
1527
+ return name.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").split(/[\s._-]+/).map((t) => t.toLowerCase()).filter(Boolean);
1528
+ }
1529
+ function isSensitiveName(name) {
1530
+ const tokens = nameTokens(name);
1531
+ for (let i = 0;i < tokens.length; i++) {
1532
+ const token = tokens[i];
1533
+ if (SENSITIVE_NAME_TOKENS.has(token)) {
1534
+ return true;
1535
+ }
1536
+ if (token === "key" || token === "keys") {
1537
+ const prev = tokens[i - 1];
1538
+ if (prev && SENSITIVE_KEY_PREFIXES.has(prev)) {
1539
+ return true;
1540
+ }
1541
+ }
1542
+ }
1543
+ return false;
1544
+ }
1545
+ function redactProperty(name, value) {
1546
+ if (value === undefined || value === null) {
1547
+ return;
1548
+ }
1549
+ if (isSensitiveName(name)) {
1550
+ return REDACTED;
1551
+ }
1552
+ if (GUID_KEY_DIMENSIONS.has(name))
1553
+ return projectKey(value);
1554
+ if (typeof value === "boolean" || typeof value === "number") {
1555
+ return value;
1556
+ }
1557
+ if (typeof value !== "string") {
1558
+ return "[OBJECT]";
1559
+ }
1560
+ return isFreeFormValue(name, value) ? redactMessage(value) : redactValueDetectors(value);
1561
+ }
1562
+ function redactProperties(properties) {
1563
+ const out = {};
1564
+ for (const [name, value] of Object.entries(properties)) {
1565
+ const redacted = redactProperty(name, value);
1566
+ if (redacted !== undefined) {
1567
+ out[name] = redacted;
1568
+ }
1569
+ }
1570
+ return out;
1571
+ }
1572
+
1573
+ // src/catch-error.ts
1574
+ var MAX_SERIALIZED_LENGTH = 500;
1575
+ var TRUNCATION_SUFFIX = "…(truncated)";
1576
+ var REDACTED2 = "[REDACTED]";
1577
+ function cap(text) {
1578
+ return text.length > MAX_SERIALIZED_LENGTH ? `${text.slice(0, MAX_SERIALIZED_LENGTH)}${TRUNCATION_SUFFIX}` : text;
1579
+ }
1580
+ function omitSensitive(key, value) {
1581
+ return key.length > 0 && isSensitiveName(key) ? REDACTED2 : value;
1582
+ }
1583
+ function describeThrownValue(value) {
1584
+ if (typeof value !== "object" || value === null) {
1585
+ return String(value);
1586
+ }
1587
+ let message;
1588
+ try {
1589
+ message = value.message;
1590
+ } catch {
1591
+ message = undefined;
1592
+ }
1593
+ if (typeof message === "string" && message.length > 0) {
1594
+ return cap(message);
1595
+ }
1596
+ try {
1597
+ const json = JSON.stringify(value, omitSensitive);
1598
+ if (json !== undefined) {
1599
+ return cap(json);
1600
+ }
1601
+ } catch {}
1602
+ return String(value);
1603
+ }
1604
+ function toError(error) {
1605
+ return error instanceof Error ? error : new Error(describeThrownValue(error), { cause: error });
1606
+ }
1607
+ function isPromiseLike(value) {
1608
+ return value !== null && typeof value === "object" && typeof value.then === "function";
1609
+ }
1610
+ function catchError(fnOrPromise) {
1611
+ if (isPromiseLike(fnOrPromise)) {
1612
+ return settlePromiseLike(fnOrPromise);
1613
+ }
1614
+ try {
1615
+ const result = fnOrPromise();
1616
+ if (isPromiseLike(result)) {
1617
+ return settlePromiseLike(result);
1618
+ }
1619
+ return [undefined, result];
1620
+ } catch (error) {
1621
+ return [toError(error), undefined];
1622
+ }
1623
+ }
1624
+ function settlePromiseLike(thenable) {
1625
+ return Promise.resolve(thenable).then((data) => [undefined, data]).catch((error) => [toError(error), undefined]);
1626
+ }
1627
+
1628
+ // src/output-context.ts
1629
+ function createStorage() {
1630
+ const [error, mod] = catchError(() => __require("node:async_hooks"));
1631
+ if (error || typeof mod?.AsyncLocalStorage !== "function") {
1632
+ return {
1633
+ getStore: () => {
1634
+ return;
1635
+ },
1636
+ run: (_store, fn) => fn()
1637
+ };
1638
+ }
1639
+ return new mod.AsyncLocalStorage;
1640
+ }
1641
+ var storageSingleton = singleton("OutputStorage");
1642
+ var sinkSlot = singleton("OutputSink");
1643
+ var outputStorage = storageSingleton.getOrInit(createStorage, (v) => ("getStore" in v));
1644
+ var CONSOLE_FALLBACK = {
1645
+ writeOut: (str) => process.stdout.write(str),
1646
+ writeErr: (str) => process.stderr.write(str),
1647
+ writeLog: (str) => process.stdout.write(str),
1648
+ capabilities: {
1649
+ isInteractive: false,
1650
+ canReadInput: false,
1651
+ supportsColor: false,
1652
+ outputWidth: 80
1653
+ }
1654
+ };
1655
+ function getOutputSink() {
1656
+ return outputStorage.getStore() ?? sinkSlot.get() ?? CONSOLE_FALLBACK;
1657
+ }
1658
+
1659
+ // src/logger.ts
1660
+ var logFilePathSlot = singleton("logFilePath");
1661
+ function setGlobalLogFilePath(path) {
1662
+ logFilePathSlot.set(path);
1663
+ }
1664
+ function getGlobalLogFilePath() {
1665
+ return logFilePathSlot.get("");
1666
+ }
1667
+ var DEFAULT_LOG_LEVEL = 2 /* WARN */;
1668
+
1669
+ class SimpleLogger {
1670
+ __brand = "SimpleLogger";
1671
+ level;
1672
+ logFilePath;
1673
+ fileLoggingEnabled;
1674
+ pendingWrites = Promise.resolve();
1675
+ pendingInit = Promise.resolve();
1676
+ constructor() {
1677
+ this.level = SimpleLogger.resolveLevel();
1678
+ this.logFilePath = "";
1679
+ this.fileLoggingEnabled = false;
1680
+ }
1681
+ static getInstance() {
1682
+ return loggerSingleton.getOrInit(() => new SimpleLogger, (v) => ("__brand" in v) && v.__brand === "SimpleLogger");
1683
+ }
1684
+ static resetInstance() {
1685
+ loggerSingleton.clear();
1686
+ }
1687
+ static isNode = typeof process !== "undefined" && !!process.versions?.node;
1688
+ static resolveLevel() {
1689
+ if (SimpleLogger.isNode) {
1690
+ const explicitLevel = SimpleLogger.parseLevel(process.env?.UIP_LOG_LEVEL ?? "");
1691
+ if (explicitLevel !== undefined)
1692
+ return explicitLevel;
1693
+ const debugVal = process.env?.DEBUG;
1694
+ if (debugVal === "true" || debugVal === "1") {
1695
+ return 0 /* DEBUG */;
1696
+ }
1697
+ return DEFAULT_LOG_LEVEL;
1698
+ }
1699
+ const [localStorageError, hasDebug] = catchError(() => typeof localStorage !== "undefined" && !!localStorage.getItem("debug"));
1700
+ if (!localStorageError && hasDebug) {
1701
+ return 0 /* DEBUG */;
1702
+ }
1703
+ return DEFAULT_LOG_LEVEL;
1704
+ }
1705
+ static parseLevel(value) {
1706
+ switch (value.toLowerCase()) {
1707
+ case "debug":
1708
+ return 0 /* DEBUG */;
1709
+ case "info":
1710
+ return 1 /* INFO */;
1711
+ case "warn":
1712
+ return 2 /* WARN */;
1713
+ case "error":
1714
+ return 3 /* ERROR */;
1715
+ default:
1716
+ return;
1717
+ }
1718
+ }
1719
+ format(message, args) {
1720
+ if (args.length === 0)
1721
+ return `${message}
1722
+ `;
1723
+ return `${message} ${args.map(String).join(" ")}
1724
+ `;
1725
+ }
1726
+ isFileLoggingActive() {
1727
+ return this.fileLoggingEnabled || !!getGlobalLogFilePath();
1728
+ }
1729
+ writeToFile(formatted) {
1730
+ const path = this.logFilePath || getGlobalLogFilePath();
1731
+ if (!path)
1732
+ return;
1733
+ const timestamp = new Date().toISOString();
1734
+ this.pendingWrites = Promise.all([
1735
+ this.pendingWrites,
1736
+ this.pendingInit
1737
+ ]).then(() => getFileSystem().appendFile(path, `${timestamp} ${formatted}`).catch(() => {}));
1738
+ }
1739
+ write(formatted) {
1740
+ if (this.isFileLoggingActive()) {
1741
+ this.writeToFile(formatted);
1742
+ } else {
1743
+ getOutputSink().writeErr(formatted);
1744
+ }
1745
+ }
1746
+ debug(message, ...args) {
1747
+ if (this.level > 0 /* DEBUG */)
1748
+ return;
1749
+ const formatted = this.format(`[DEBUG] ${message}`, args);
1750
+ this.write(formatted);
1751
+ }
1752
+ info(message, ...args) {
1753
+ if (this.level > 1 /* INFO */)
1754
+ return;
1755
+ const formatted = this.format(message, args);
1756
+ this.write(formatted);
1757
+ }
1758
+ warn(message, ...args) {
1759
+ if (this.level > 2 /* WARN */)
1760
+ return;
1761
+ const formatted = this.format(`[WARN] ${message}`, args);
1762
+ this.write(formatted);
1763
+ }
1764
+ error(message, ...args) {
1765
+ if (this.level > 3 /* ERROR */)
1766
+ return;
1767
+ const formatted = this.format(`[ERROR] ${message}`, args);
1768
+ this.write(formatted);
1769
+ }
1770
+ report(message) {
1771
+ const formatted = this.format(message, []);
1772
+ this.write(formatted);
1773
+ }
1774
+ getLevel() {
1775
+ return this.level;
1776
+ }
1777
+ setLevel(level) {
1778
+ this.level = level;
1779
+ }
1780
+ setFileLogging(enabled) {
1781
+ this.fileLoggingEnabled = enabled;
1782
+ if (!enabled) {
1783
+ this.logFilePath = "";
1784
+ setGlobalLogFilePath("");
1785
+ }
1786
+ }
1787
+ setLogFile(path) {
1788
+ this.logFilePath = path;
1789
+ setGlobalLogFilePath(path);
1790
+ if (!path)
1791
+ return;
1792
+ this.fileLoggingEnabled = true;
1793
+ const fs = getFileSystem();
1794
+ this.pendingInit = (async () => {
1795
+ const [error] = await catchError((async () => {
1796
+ await fs.mkdir(fs.path.dirname(path));
1797
+ await fs.writeFile(path, "");
1798
+ })());
1799
+ if (error)
1800
+ this.fileLoggingEnabled = false;
1801
+ })();
1802
+ }
1803
+ async flushFile() {
1804
+ await this.pendingInit;
1805
+ await this.pendingWrites;
1806
+ }
1807
+ getLogFilePath() {
1808
+ return this.logFilePath || getGlobalLogFilePath();
1809
+ }
1810
+ handleLog = (logMessage) => {
1811
+ const parts = [];
1812
+ if (logMessage.source) {
1813
+ parts.push(`[${logMessage.source}]`);
1814
+ }
1815
+ if (logMessage.sourceTarget) {
1816
+ parts.push(`[${logMessage.sourceTarget}]`);
1817
+ }
1818
+ parts.push(logMessage.message);
1819
+ const msg = parts.join(" ");
1820
+ switch (logMessage.logLevel) {
1821
+ case "Debug":
1822
+ this.debug(msg);
1823
+ break;
1824
+ case "Information":
1825
+ this.info(msg);
1826
+ break;
1827
+ case "Warning":
1828
+ this.warn(msg);
1829
+ break;
1830
+ case "Error":
1831
+ this.error(msg);
1832
+ break;
1833
+ default:
1834
+ this.info(msg);
1835
+ break;
1836
+ }
1837
+ };
1838
+ }
1839
+ var loggerSingleton = singleton(SimpleLogger);
1840
+ var logger = SimpleLogger.getInstance();
1841
+ function getLogFilePath() {
1842
+ return logger.getLogFilePath();
1843
+ }
1844
+
1845
+ // src/timings.ts
1846
+ var TIMINGS_ENV_VAR = "UIP_TIMINGS";
1847
+ function createStorage2() {
1848
+ const [error, mod] = catchError(() => __require("node:async_hooks"));
1849
+ if (error || typeof mod?.AsyncLocalStorage !== "function") {
1850
+ return {
1851
+ getStore: () => {
1852
+ return;
1853
+ },
1854
+ run: (_store, fn) => fn()
1855
+ };
1856
+ }
1857
+ return new mod.AsyncLocalStorage;
1858
+ }
1859
+ var storageSlot = singleton("TimingStorage");
1860
+ var stateSlot = singleton("Timings");
1861
+ var rootStartedSlot = singleton("TimingsRootStarted");
1862
+ var longLivedHostSlot = singleton("TimingsLongLivedHost");
1863
+ var storage = storageSlot.getOrInit(createStorage2, (value) => ("getStore" in value));
1864
+ function newState(baseline) {
1865
+ return { baseline, httpMs: 0, httpCalls: 0 };
1866
+ }
1867
+ function getState() {
1868
+ const scoped = storage.getStore();
1869
+ if (scoped) {
1870
+ return scoped;
1871
+ }
1872
+ const pinned = livePinnedState();
1873
+ if (pinned !== undefined) {
1874
+ return pinned;
1875
+ }
1876
+ return newState(processStartIsInvocationStart() ? 0 : performance.now());
1877
+ }
1878
+ function livePinnedState() {
1879
+ const pinned = stateSlot.get();
1880
+ return pinned !== undefined && "httpCalls" in pinned && !pinned.finished ? pinned : undefined;
1881
+ }
1882
+ function processStartIsInvocationStart() {
1883
+ return !rootStartedSlot.get(false) && !longLivedHostSlot.get(false);
1884
+ }
1885
+ function timingsEnabled() {
1886
+ if (typeof process === "undefined") {
1887
+ return false;
1888
+ }
1889
+ const value = process.env?.[TIMINGS_ENV_VAR];
1890
+ if (value === undefined) {
1891
+ return false;
1892
+ }
1893
+ const normalized = value.trim().toLowerCase();
1894
+ return normalized === "1" || normalized === "true";
1895
+ }
1896
+ function recordExitCode(exitCode) {
1897
+ if (!timingsEnabled()) {
1898
+ return;
1899
+ }
1900
+ getState().exitCode = exitCode;
1901
+ }
1902
+
1903
+ // src/exit-code.ts
1904
+ function setExitCode(code) {
1905
+ process.exitCode = code;
1906
+ recordExitCode(code);
1907
+ }
1908
+
1909
+ // src/error-codes.ts
1910
+ var CLI_ERROR_CODES = [
1911
+ "invalid_argument",
1912
+ "authentication_required",
1913
+ "permission_denied",
1914
+ "local_permission_denied",
1915
+ "not_found",
1916
+ "rate_limited",
1917
+ "network_error",
1918
+ "timeout",
1919
+ "server_error",
1920
+ "method_not_allowed",
1921
+ "not_supported",
1922
+ "configuration_error",
1923
+ "execution_failed",
1924
+ "unknown_error"
1925
+ ];
1926
+ var RETRY_HINTS = [
1927
+ "RetryWillNotFix",
1928
+ "RetryLater",
1929
+ "RetryAfter1Second",
1930
+ "RetryAfter10Seconds",
1931
+ "RetryAfter30Seconds",
1932
+ "RetryAfter60Seconds"
1933
+ ];
1934
+ var CLI_ERROR_CODE_VALUES = new Set(CLI_ERROR_CODES);
1935
+ var RETRY_HINT_VALUES = new Set(RETRY_HINTS);
1936
+ function defaultRetryForErrorCode(errorCode) {
1937
+ switch (errorCode) {
1938
+ case "network_error":
1939
+ case "rate_limited":
1940
+ case "server_error":
1941
+ case "timeout":
1942
+ return "RetryLater";
1943
+ default:
1944
+ return "RetryWillNotFix";
1945
+ }
1946
+ }
1947
+
1948
+ // src/error-graph.ts
1949
+ function parseHttpStatusFromMessage(message) {
1950
+ const match = /^HTTP\s+(\d{3})(?::|\s|-|$)/i.exec(message.trim());
1951
+ if (!match)
1952
+ return;
1953
+ const status = Number(match[1]);
1954
+ return Number.isInteger(status) && status >= 100 && status <= 599 ? status : undefined;
1955
+ }
1956
+
1957
+ // src/http-status.ts
1958
+ function classifyHttpStatus(status) {
1959
+ if (status === undefined)
1960
+ return;
1961
+ if (status === 400 || status === 409 || status === 413 || status === 422) {
1962
+ return { errorCode: "invalid_argument", retry: "RetryWillNotFix" };
1963
+ }
1964
+ if (status === 401) {
1965
+ return {
1966
+ errorCode: "authentication_required",
1967
+ retry: "RetryWillNotFix"
1968
+ };
1969
+ }
1970
+ if (status === 403) {
1971
+ return { errorCode: "permission_denied", retry: "RetryWillNotFix" };
1972
+ }
1973
+ if (status === 404) {
1974
+ return { errorCode: "not_found", retry: "RetryWillNotFix" };
1975
+ }
1976
+ if (status === 405) {
1977
+ return { errorCode: "method_not_allowed", retry: "RetryWillNotFix" };
1978
+ }
1979
+ if (status === 408) {
1980
+ return { errorCode: "timeout", retry: "RetryLater" };
1981
+ }
1982
+ if (status === 429) {
1983
+ return { errorCode: "rate_limited", retry: "RetryLater" };
1984
+ }
1985
+ if (status >= 500 && status < 600) {
1986
+ return { errorCode: "server_error", retry: "RetryLater" };
1987
+ }
1988
+ return;
1989
+ }
1990
+
1991
+ // src/local-permission-codes.ts
1992
+ var LOCAL_PERMISSION_ERROR_CODES = new Set([
1993
+ "EACCES",
1994
+ "EPERM",
1995
+ "EROFS"
1996
+ ]);
1997
+
1998
+ // src/output-codecs.ts
1999
+ var yamlSlot = singleton("YamlCodec");
2000
+ var jmespathSlot = singleton("JmespathCodec");
2001
+ function getYamlCodec() {
2002
+ return yamlSlot.get();
2003
+ }
2004
+ function getJmespathCodec() {
2005
+ return jmespathSlot.get();
2006
+ }
2007
+
2008
+ // src/output-format-context.ts
2009
+ var formatSlot = singleton("OutputFormat");
2010
+ var formatExplicitSlot = singleton("OutputFormatExplicit");
2011
+ var helpRequestedSlot = singleton("HelpRequested");
2012
+ var filterSlot = singleton("OutputFilter");
2013
+ function getOutputFormat() {
2014
+ return formatSlot.get("json");
2015
+ }
2016
+ function getOutputFilter() {
2017
+ return filterSlot.get();
2018
+ }
2019
+
2020
+ // src/result-types.ts
2021
+ var RESULTS = {
2022
+ Success: "Success",
2023
+ Failure: "Failure",
2024
+ ConfigError: "ConfigError",
2025
+ AuthenticationError: "AuthenticationError",
2026
+ ValidationError: "ValidationError",
2027
+ TimeoutError: "TimeoutError"
2028
+ };
2029
+
2030
+ // src/telemetry/command-terminal.ts
2031
+ var recordedFailureSlot = singleton("CommandTelemetryFailure");
2032
+ var AUTH_ERROR_CODES = new Set([
2033
+ "authentication_required",
2034
+ "permission_denied"
2035
+ ]);
2036
+ var LOCAL_PERMISSION_CLI_ERROR_CODES = new Set([
2037
+ "local_permission_denied"
2038
+ ]);
2039
+ var VALIDATION_ERROR_CODES = new Set(["invalid_argument"]);
2040
+ var NETWORK_HTTP_ERROR_CODES = new Set([
2041
+ "network_error",
2042
+ "rate_limited",
2043
+ "server_error",
2044
+ "not_found",
2045
+ "method_not_allowed"
2046
+ ]);
2047
+ var TIMEOUT_ERROR_CODES = new Set(["timeout"]);
2048
+ var NETWORK_OS_ERROR_CODES = new Set([
2049
+ "ECONNREFUSED",
2050
+ "ECONNRESET",
2051
+ "ENOTFOUND",
2052
+ "EAI_AGAIN",
2053
+ "EPIPE",
2054
+ "EHOSTUNREACH",
2055
+ "ENETUNREACH",
2056
+ "EAI_FAIL"
2057
+ ]);
2058
+ var TIMEOUT_OS_ERROR_CODES = new Set(["ETIMEDOUT", "ESOCKETTIMEDOUT"]);
2059
+ var TLS_ERROR_CODES = new Set([
2060
+ "SELF_SIGNED_CERT_IN_CHAIN",
2061
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
2062
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
2063
+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
2064
+ "UNABLE_TO_GET_ISSUER_CERT",
2065
+ "CERT_HAS_EXPIRED",
2066
+ "CERT_UNTRUSTED",
2067
+ "ERR_TLS_CERT_ALTNAME_INVALID"
2068
+ ]);
2069
+ var MISSING_DEPENDENCY_CODES = new Set([
2070
+ "MODULE_NOT_FOUND",
2071
+ "ERR_MODULE_NOT_FOUND"
2072
+ ]);
2073
+ var INTERNAL_ERROR_NAMES = new Set([
2074
+ "TypeError",
2075
+ "ReferenceError",
2076
+ "SyntaxError",
2077
+ "RangeError"
2078
+ ]);
2079
+ function recordCommandFailureTelemetry(failure) {
2080
+ recordedFailureSlot.set(failure);
2081
+ }
2082
+
2083
+ // src/telemetry/telemetry-events.ts
2084
+ var CommonTelemetryEvents = {
2085
+ Start: "Application.Start",
2086
+ Error: "Application.Error",
2087
+ ProjectActivity: "Cli.ProjectActivity",
2088
+ ShipSucceeded: "Cli.ShipSucceeded"
2089
+ };
2090
+
2091
+ // src/registry.ts
2092
+ import { execFileSync as execFileSync2 } from "node:child_process";
2093
+ function readRegistryValue(keyPath, valueName) {
2094
+ if (process.platform !== "win32") {
2095
+ return "";
2096
+ }
2097
+ const [error, output] = catchError(() => execFileSync2("reg", ["query", keyPath, "/v", valueName], {
2098
+ encoding: "utf-8",
2099
+ stdio: ["pipe", "pipe", "pipe"],
2100
+ windowsHide: true
2101
+ }));
2102
+ if (error) {
2103
+ return "";
2104
+ }
2105
+ const match = output.match(new RegExp(`${valueName}\\s+REG_SZ\\s+(.+)`));
2106
+ return match?.[1]?.trim() ?? "";
2107
+ }
2108
+
2109
+ // src/telemetry/logger-telemetry-provider.ts
2110
+ class LoggerTelemetryProvider {
2111
+ analyticsUniqueId;
2112
+ constructor() {
2113
+ this.analyticsUniqueId = readRegistryValue("HKCU\\Software\\UiPath", "AnalyticsUniqueId");
2114
+ }
2115
+ enrich(properties) {
2116
+ return {
2117
+ ...properties,
2118
+ ...this.analyticsUniqueId ? { analyticsUniqueId: this.analyticsUniqueId } : {}
2119
+ };
2120
+ }
2121
+ async trackEvent({ name, properties }) {
2122
+ logger.debug(formatMessage("Event", name, this.enrich(properties)));
2123
+ }
2124
+ async trackException({
2125
+ error,
2126
+ properties
2127
+ }) {
2128
+ logger.error(formatMessage("Exception", error.message, this.enrich({
2129
+ ...properties,
2130
+ stack: error.stack
2131
+ })));
2132
+ }
2133
+ async trackRequest({
2134
+ name,
2135
+ durationMs,
2136
+ success,
2137
+ properties
2138
+ }) {
2139
+ logger.debug(formatMessage("Request", name, this.enrich({
2140
+ ...properties,
2141
+ duration: `${durationMs}ms`,
2142
+ success
2143
+ })));
2144
+ }
2145
+ async trackDependency({
2146
+ name,
2147
+ type,
2148
+ durationMs,
2149
+ success,
2150
+ properties
2151
+ }) {
2152
+ logger.debug(formatMessage("Dependency", name, this.enrich({
2153
+ ...properties,
2154
+ type,
2155
+ duration: `${durationMs}ms`,
2156
+ success
2157
+ })));
2158
+ }
2159
+ }
2160
+ function formatMessage(category, name, properties) {
2161
+ let message = `[Telemetry] [${category}] ${name}`;
2162
+ if (properties && Object.keys(properties).length > 0) {
2163
+ const propsStr = Object.entries(properties).filter(([_, value]) => value !== undefined).map(([key, value]) => `${key}=${value}`).join(", ");
2164
+ if (propsStr) {
2165
+ message += ` | ${propsStr}`;
2166
+ }
2167
+ }
2168
+ return message;
2169
+ }
2170
+ // src/telemetry/detect-agent.ts
2171
+ var KNOWN_AGENTS = [
2172
+ { envVar: "CLAUDECODE", value: "1", id: "claude-code" },
2173
+ { envVar: "CURSOR_AGENT", value: "1", id: "cursor" },
2174
+ { envVar: "GEMINI_CLI", value: "1", id: "gemini-cli" },
2175
+ { envVar: "CODEX_THREAD_ID", id: "codex" },
2176
+ { envVar: "CODEX_SANDBOX", id: "codex" },
2177
+ { envVar: "AUGMENT_AGENT", value: "1", id: "augment" },
2178
+ { envVar: "CLINE_ACTIVE", value: "true", id: "cline" }
2179
+ ];
2180
+ function detectAgentFromEnv(env) {
2181
+ for (const agent of KNOWN_AGENTS) {
2182
+ const envValue = env[agent.envVar];
2183
+ if (agent.value !== undefined) {
2184
+ if (envValue === agent.value)
2185
+ return agent.id;
2186
+ } else {
2187
+ if (envValue)
2188
+ return agent.id;
2189
+ }
2190
+ }
2191
+ const agentEnv = env.AGENT;
2192
+ if (agentEnv) {
2193
+ if (agentEnv === "1" || agentEnv === "true")
2194
+ return "unknown";
2195
+ if (agentEnv.length <= 32)
2196
+ return agentEnv.toLowerCase();
2197
+ }
2198
+ return;
2199
+ }
2200
+ // src/telemetry/environment-info.ts
2201
+ var LOCAL_HOSTS = new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
2202
+ // src/telemetry/execution-context.ts
2203
+ var authSignalSlot = singleton("TelemetryExecutionContextAuthSignal");
2204
+ var isTruthy = (value) => value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
2205
+ var isEqual = (value, expected) => value?.toLowerCase() === expected;
2206
+ var CI_SIGNATURES = [
2207
+ {
2208
+ provider: "github_actions",
2209
+ matches: (env) => isTruthy(env.GITHUB_ACTIONS),
2210
+ isScheduler: (env) => env.GITHUB_EVENT_NAME === "schedule"
2211
+ },
2212
+ {
2213
+ provider: "azure_devops",
2214
+ matches: (env) => isTruthy(env.TF_BUILD),
2215
+ isScheduler: (env) => isEqual(env.BUILD_REASON, "schedule")
2216
+ },
2217
+ {
2218
+ provider: "gitlab",
2219
+ matches: (env) => isTruthy(env.GITLAB_CI),
2220
+ isScheduler: (env) => env.CI_PIPELINE_SOURCE === "schedule"
2221
+ },
2222
+ {
2223
+ provider: "circleci",
2224
+ matches: (env) => isTruthy(env.CIRCLECI),
2225
+ isScheduler: (env) => env.CIRCLE_PIPELINE_TRIGGER_SOURCE === "scheduled_pipeline"
2226
+ },
2227
+ {
2228
+ provider: "jenkins",
2229
+ matches: (env) => isTruthy(env.JENKINS_URL) || isTruthy(env.JENKINS_HOME)
2230
+ },
2231
+ {
2232
+ provider: "teamcity",
2233
+ matches: (env) => isTruthy(env.TEAMCITY_VERSION)
2234
+ },
2235
+ {
2236
+ provider: "buildkite",
2237
+ matches: (env) => isTruthy(env.BUILDKITE),
2238
+ isScheduler: (env) => env.BUILDKITE_SOURCE === "schedule"
2239
+ },
2240
+ {
2241
+ provider: "bitbucket",
2242
+ matches: (env) => isTruthy(env.BITBUCKET_BUILD_NUMBER)
2243
+ },
2244
+ {
2245
+ provider: "travis",
2246
+ matches: (env) => isTruthy(env.TRAVIS)
2247
+ },
2248
+ {
2249
+ provider: "appveyor",
2250
+ matches: (env) => isTruthy(env.APPVEYOR)
2251
+ },
2252
+ {
2253
+ provider: "generic",
2254
+ matches: (env) => isTruthy(env.CI)
2255
+ }
2256
+ ];
2257
+ function currentEnv() {
2258
+ return typeof process === "undefined" ? {} : process.env;
2259
+ }
2260
+ function currentTtyState() {
2261
+ if (typeof process === "undefined")
2262
+ return false;
2263
+ return Boolean(process.stdout?.isTTY || process.stdin?.isTTY || process.stderr?.isTTY);
2264
+ }
2265
+ function detectCi(env) {
2266
+ const signature = CI_SIGNATURES.find((candidate) => candidate.matches(env));
2267
+ if (!signature)
2268
+ return;
2269
+ return {
2270
+ executionContext: signature.isScheduler?.(env) ? "scheduler" : "ci",
2271
+ ciProvider: signature.provider
2272
+ };
2273
+ }
2274
+ function detectExecutionContext(options = {}) {
2275
+ const env = options.env ?? currentEnv();
2276
+ const ci = detectCi(env);
2277
+ if (ci)
2278
+ return ci;
2279
+ const agent = options.agent ?? detectAgentFromEnv(env);
2280
+ if (agent) {
2281
+ return { executionContext: "agent" };
2282
+ }
2283
+ const authSignal = options.authSignal ?? authSignalSlot.get();
2284
+ if (authSignal === "service_account") {
2285
+ return { executionContext: "service_account" };
2286
+ }
2287
+ const isTty = options.isTty ?? currentTtyState();
2288
+ if (isTty) {
2289
+ return { executionContext: "manual" };
2290
+ }
2291
+ return { executionContext: "unknown" };
2292
+ }
2293
+ function getExecutionContextTelemetryProperties() {
2294
+ const detected = detectExecutionContext();
2295
+ return {
2296
+ [BaseDimensions.ExecutionContext]: detected.executionContext,
2297
+ ...detected.ciProvider ? { [BaseDimensions.CiProvider]: detected.ciProvider } : {}
2298
+ };
2299
+ }
2300
+ // src/telemetry/node-context-storage.ts
2301
+ import { AsyncLocalStorage } from "node:async_hooks";
2302
+
2303
+ class NodeContextStorage {
2304
+ storage = new AsyncLocalStorage;
2305
+ run(context, fn) {
2306
+ return this.storage.run(context, fn);
2307
+ }
2308
+ getContext() {
2309
+ return this.storage.getStore();
2310
+ }
2311
+ }
2312
+ // src/telemetry/trace-context.ts
2313
+ var TELEMETRY_TRACEPARENT_ENV = "TRACEPARENT";
2314
+ var TRACEPARENT_PATTERN = /^00-([0-9a-f]{32})-([0-9a-f]{16})-[0-9a-f]{2}$/;
2315
+ function getProcessEnv() {
2316
+ return globalThis.process?.env;
2317
+ }
2318
+ function parseInboundTraceparent(value) {
2319
+ if (!value) {
2320
+ return;
2321
+ }
2322
+ const match = TRACEPARENT_PATTERN.exec(value.trim().toLowerCase());
2323
+ if (!match) {
2324
+ return;
2325
+ }
2326
+ const [, traceId, parentSpanId] = match;
2327
+ if (/^0+$/.test(traceId) || /^0+$/.test(parentSpanId)) {
2328
+ return;
2329
+ }
2330
+ return { traceId, parentSpanId };
2331
+ }
2332
+ function getInboundTraceContext() {
2333
+ return parseInboundTraceparent(getProcessEnv()?.[TELEMETRY_TRACEPARENT_ENV]);
2334
+ }
2335
+
2336
+ // src/telemetry/session-id.ts
2337
+ var TELEMETRY_SESSION_ID_ENV = "UIPATH_SESSION_ID";
2338
+ var SESSION_ID_MAX_LENGTH = 64;
2339
+ var RANDOM_SESSION_ID_LENGTH = 32;
2340
+ var TELEMETRY_SESSION_SOURCE_PROPERTY = "SessionIdSource";
2341
+ var CONTROL_CHARACTERS = /\p{Cc}/gu;
2342
+ var INHERITED_SESSION_SOURCES = [
2343
+ { envVar: "CLAUDE_CODE_SESSION_ID", source: "claude-code" },
2344
+ { envVar: "CODEX_THREAD_ID", source: "codex" },
2345
+ { envVar: "ANTIGRAVITY_TRAJECTORY_ID", source: "antigravity" },
2346
+ { envVar: "TERM_SESSION_ID", source: "terminal" },
2347
+ { envVar: "WT_SESSION", source: "terminal" }
2348
+ ];
2349
+ var telemetrySessionSlot = singleton("TelemetrySession");
2350
+ var telemetryOperationIdSlot = singleton("TelemetryOperationId");
2351
+ function getProcessEnv2() {
2352
+ return globalThis.process?.env;
2353
+ }
2354
+ function normalizeSessionId(value) {
2355
+ if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") {
2356
+ return;
2357
+ }
2358
+ const cleaned = String(value).replace(CONTROL_CHARACTERS, "").trim().slice(0, SESSION_ID_MAX_LENGTH);
2359
+ return cleaned || undefined;
2360
+ }
2361
+ function getConfiguredTelemetrySessionId() {
2362
+ return normalizeSessionId(getProcessEnv2()?.[TELEMETRY_SESSION_ID_ENV]);
2363
+ }
2364
+ function getInheritedSession(env) {
2365
+ for (const candidate of INHERITED_SESSION_SOURCES) {
2366
+ const handle = normalizeSessionId(env[candidate.envVar]);
2367
+ if (handle) {
2368
+ return { id: handle, source: candidate.source };
2369
+ }
2370
+ }
2371
+ return;
2372
+ }
2373
+ function generateRandomSession() {
2374
+ const bytes = new Uint8Array(RANDOM_SESSION_ID_LENGTH / 2);
2375
+ crypto.getRandomValues(bytes);
2376
+ let hex = "";
2377
+ for (const byte of bytes) {
2378
+ hex += byte.toString(16).padStart(2, "0");
2379
+ }
2380
+ return { id: hex, source: "random" };
2381
+ }
2382
+ function resolveTelemetrySession() {
2383
+ const existing = telemetrySessionSlot.get();
2384
+ if (existing) {
2385
+ return existing;
2386
+ }
2387
+ const declaredHandle = getConfiguredTelemetrySessionId();
2388
+ const resolved = declaredHandle ? { id: declaredHandle, source: "declared" } : getInheritedSession(getProcessEnv2() ?? {}) ?? generateRandomSession();
2389
+ telemetrySessionSlot.set(resolved);
2390
+ return resolved;
2391
+ }
2392
+ function getTelemetrySessionId() {
2393
+ return resolveTelemetrySession().id;
2394
+ }
2395
+ function getTelemetrySessionSource() {
2396
+ return resolveTelemetrySession().source;
2397
+ }
2398
+ function getTelemetryOperationId() {
2399
+ const existing = telemetryOperationIdSlot.get();
2400
+ if (existing) {
2401
+ return existing;
2402
+ }
2403
+ const inboundTraceId = getInboundTraceContext()?.traceId;
2404
+ const generated = inboundTraceId ?? crypto.randomUUID().replaceAll("-", "");
2405
+ telemetryOperationIdSlot.set(generated);
2406
+ return generated;
2407
+ }
2408
+ // src/telemetry/global-telemetry-properties.ts
2409
+ var telemetryPropsSlot = singleton("TelemetryDefaultProps");
2410
+ function getGlobalTelemetryProperties() {
2411
+ return telemetryPropsSlot.get();
2412
+ }
2413
+
2414
+ // src/telemetry/span-clock.ts
2415
+ function startSpanClock() {
2416
+ const started = performance.now();
2417
+ return {
2418
+ startedAt: new Date(performance.timeOrigin + started),
2419
+ elapsedMs: () => performance.now() - started
2420
+ };
2421
+ }
2422
+
2423
+ // src/telemetry/telemetry-service.ts
2424
+ class TelemetryService {
2425
+ telemetryProvider;
2426
+ contextStorage;
2427
+ operationId;
2428
+ defaultProperties;
2429
+ constructor(telemetryProvider, contextStorage) {
2430
+ this.telemetryProvider = telemetryProvider;
2431
+ this.contextStorage = contextStorage;
2432
+ }
2433
+ setOperationId(operationId) {
2434
+ this.operationId = operationId;
2435
+ }
2436
+ setProvider(provider) {
2437
+ this.telemetryProvider = provider;
2438
+ }
2439
+ setDefaultProperties(properties) {
2440
+ this.defaultProperties = properties === undefined ? undefined : { ...this.defaultProperties, ...properties };
2441
+ }
2442
+ trackEvent(name, properties) {
2443
+ this.telemetryProvider.trackEvent({
2444
+ name: redactSpanName(name),
2445
+ properties: this.enrichProperties(properties),
2446
+ ...this.leafCorrelation()
2447
+ });
2448
+ }
2449
+ trackException(error, properties, context) {
2450
+ this.telemetryProvider.trackException({
2451
+ error: redactError(error),
2452
+ properties: this.enrichProperties(properties),
2453
+ ...this.leafCorrelation(context)
2454
+ });
2455
+ }
2456
+ async trackRequest(name, fn, properties) {
2457
+ const parentContext = this.getActiveContext();
2458
+ const operationId = parentContext?.operationId ?? this.operationId ?? getTelemetryOperationId();
2459
+ const parentId = parentContext ? parentContext.id : this.inboundParentIdFor(operationId);
2460
+ const clock = startSpanClock();
2461
+ const context = {
2462
+ operationId,
2463
+ ...parentId !== undefined ? { parentId } : {},
2464
+ id: this.generateId(),
2465
+ startedAt: clock.startedAt
2466
+ };
2467
+ try {
2468
+ const result = await this.contextStorage.run(context, fn);
2469
+ const durationMs = clock.elapsedMs();
2470
+ await this.telemetryProvider.trackRequest(this.spanFor(name, durationMs, true, properties, context));
2471
+ return result;
2472
+ } catch (error) {
2473
+ const durationMs = clock.elapsedMs();
2474
+ const err = error instanceof Error ? error : new Error(String(error));
2475
+ await this.telemetryProvider.trackRequest(this.spanFor(name, durationMs, false, {
2476
+ ...properties,
2477
+ [CommandDimensions.ErrorMessage]: err.message
2478
+ }, context));
2479
+ throw error;
2480
+ }
2481
+ }
2482
+ trackRequestResult(name, durationMs, success, properties, context) {
2483
+ const requestContext = context ?? {
2484
+ operationId: this.operationId ?? getTelemetryOperationId(),
2485
+ id: this.generateId()
2486
+ };
2487
+ this.telemetryProvider.trackRequest(this.spanFor(name, durationMs, success, properties, requestContext));
2488
+ }
2489
+ createRequestContext() {
2490
+ const operationId = this.operationId ?? getTelemetryOperationId();
2491
+ const parentId = this.inboundParentIdFor(operationId);
2492
+ return {
2493
+ operationId,
2494
+ ...parentId !== undefined ? { parentId } : {},
2495
+ id: this.generateId(),
2496
+ startedAt: startSpanClock().startedAt
2497
+ };
2498
+ }
2499
+ inboundParentIdFor(operationId) {
2500
+ const inbound = getInboundTraceContext();
2501
+ return inbound && inbound.traceId === operationId ? inbound.parentSpanId : undefined;
2502
+ }
2503
+ runWithContext(context, fn) {
2504
+ return this.contextStorage.run(context, fn);
2505
+ }
2506
+ createDependencyContext() {
2507
+ const parentContext = this.getActiveContext();
2508
+ if (!parentContext) {
2509
+ return;
2510
+ }
2511
+ return {
2512
+ operationId: parentContext.operationId,
2513
+ parentId: parentContext.id,
2514
+ id: this.generateId(),
2515
+ startedAt: startSpanClock().startedAt
2516
+ };
2517
+ }
2518
+ trackDependencyResult(name, type, durationMs, success, properties, context, resultCode) {
2519
+ this.telemetryProvider.trackDependency({
2520
+ ...this.spanFor(redactHttpDependencyName(name), durationMs, success, properties, context),
2521
+ type,
2522
+ ...resultCode !== undefined ? { resultCode } : {}
2523
+ });
2524
+ }
2525
+ async trackDependencyOperation(name, type, fn, properties) {
2526
+ const clock = startSpanClock();
2527
+ const parentContext = this.getActiveContext();
2528
+ const childContext = parentContext !== undefined ? {
2529
+ operationId: parentContext.operationId,
2530
+ parentId: parentContext.id,
2531
+ id: this.generateId(),
2532
+ startedAt: clock.startedAt
2533
+ } : {
2534
+ ...this.createRequestContext(),
2535
+ startedAt: clock.startedAt
2536
+ };
2537
+ try {
2538
+ const result = await this.contextStorage.run(childContext, fn);
2539
+ const durationMs = clock.elapsedMs();
2540
+ await this.telemetryProvider.trackDependency({
2541
+ ...this.spanFor(name, durationMs, true, properties, childContext),
2542
+ type
2543
+ });
2544
+ return result;
2545
+ } catch (error) {
2546
+ const durationMs = clock.elapsedMs();
2547
+ const err = error instanceof Error ? error : new Error(String(error));
2548
+ await this.telemetryProvider.trackDependency({
2549
+ ...this.spanFor(name, durationMs, false, {
2550
+ ...properties,
2551
+ [CommandDimensions.ErrorMessage]: err.message
2552
+ }, childContext),
2553
+ type
2554
+ });
2555
+ throw error;
2556
+ }
2557
+ }
2558
+ getActiveContext() {
2559
+ return this.contextStorage.getContext();
2560
+ }
2561
+ leafCorrelation(explicit) {
2562
+ const context = explicit ?? this.getActiveContext();
2563
+ return {
2564
+ operationId: context?.operationId ?? this.operationId ?? getTelemetryOperationId(),
2565
+ ...context !== undefined ? { parentId: context.id } : {}
2566
+ };
2567
+ }
2568
+ spanFor(name, durationMs, success, properties, context) {
2569
+ return {
2570
+ name: redactSpanName(name),
2571
+ durationMs,
2572
+ success,
2573
+ properties: this.enrichProperties(properties),
2574
+ operationId: context.operationId,
2575
+ ...context.parentId !== undefined ? { parentId: context.parentId } : {},
2576
+ id: context.id,
2577
+ ...context.startedAt !== undefined ? { startedAt: context.startedAt } : {}
2578
+ };
2579
+ }
2580
+ enrichProperties(properties) {
2581
+ const globalProperties = getGlobalTelemetryProperties();
2582
+ const enriched = {
2583
+ ...getExecutionContextTelemetryProperties(),
2584
+ ...globalProperties,
2585
+ ...this.defaultProperties,
2586
+ ...redactProperties(properties ?? {}),
2587
+ [TELEMETRY_SESSION_SOURCE_PROPERTY]: getTelemetrySessionSource(),
2588
+ [BaseDimensions.SessionId]: this.telemetryProvider.getSessionId?.() ?? getTelemetrySessionId()
2589
+ };
2590
+ return lowercaseIdDimensionValues(enriched);
2591
+ }
2592
+ generateId() {
2593
+ const bytes = new Uint8Array(8);
2594
+ let hex = "";
2595
+ do {
2596
+ crypto.getRandomValues(bytes);
2597
+ hex = "";
2598
+ for (const byte of bytes) {
2599
+ hex += byte.toString(16).padStart(2, "0");
2600
+ }
2601
+ } while (/^0+$/.test(hex));
2602
+ return hex;
2603
+ }
2604
+ }
2605
+ // src/telemetry/proxy-http-agent.ts
2606
+ var slot = singleton("ProxyAuthHttpsAgent");
2607
+
2608
+ // src/telemetry/node-appinsights-telemetry-provider.ts
2609
+ var providerSlot = singleton("TelemetryProvider");
2610
+
2611
+ // src/telemetry/telemetry-spool.ts
2612
+ var sidecarEntrySlot = singleton("TelemetrySidecarEntry");
2613
+ var MAX_SPOOL_AGE_MS = 72 * 60 * 60 * 1000;
2614
+
2615
+ // src/telemetry/telemetry-init.ts
2616
+ var telemetryInstanceSlot = singleton("TelemetryService");
2617
+ var DEFAULT_AI_CONNECTION_STRING = atob("SW5zdHJ1bWVudGF0aW9uS2V5PTliZDM3NDgyLTgxMGUtNDQyYS1hYWE2LWQzOGVmNjVjNjY3NDtJbmdlc3Rpb25FbmRwb2ludD1odHRwczovL3dlc3RldXJvcGUtNS5pbi5hcHBsaWNhdGlvbmluc2lnaHRzLmF6dXJlLmNvbS87TGl2ZUVuZHBvaW50PWh0dHBzOi8vd2VzdGV1cm9wZS5saXZlZGlhZ25vc3RpY3MubW9uaXRvci5henVyZS5jb20vO0FwcGxpY2F0aW9uSWQ9MzU2OTdlZjEtOGJkMC00ZjE5LWEyN2MtZDg3Y2NhYzY2ZDJj");
2618
+ function getGlobalTelemetryInstance() {
2619
+ const existing = telemetryInstanceSlot.get();
2620
+ if (existing && typeof existing === "object" && "trackEvent" in existing && typeof existing.trackEvent === "function") {
2621
+ return existing;
2622
+ }
2623
+ return;
2624
+ }
2625
+ function setGlobalTelemetryInstance(instance) {
2626
+ telemetryInstanceSlot.set(instance);
2627
+ }
2628
+ var _localTelemetryInstance;
2629
+ function getTelemetryInstance() {
2630
+ const global = getGlobalTelemetryInstance();
2631
+ if (global)
2632
+ return global;
2633
+ if (!_localTelemetryInstance) {
2634
+ _localTelemetryInstance = new TelemetryService(new LoggerTelemetryProvider, new NodeContextStorage);
2635
+ setGlobalTelemetryInstance(_localTelemetryInstance);
2636
+ }
2637
+ return _localTelemetryInstance;
2638
+ }
2639
+ var telemetry = new Proxy({}, {
2640
+ get(_, prop) {
2641
+ const instance = getTelemetryInstance();
2642
+ const value = instance[prop];
2643
+ return typeof value === "function" ? value.bind(instance) : value;
2644
+ }
2645
+ });
2646
+ // src/formatter.ts
2647
+ var ANSI_STYLES = {
2648
+ red: "\x1B[31m",
2649
+ dim: "\x1B[2m"
2650
+ };
2651
+ var ANSI_RESET = "\x1B[0m";
2652
+ function styleLine(line, style) {
2653
+ return style ? `${ANSI_STYLES[style]}${line}${ANSI_RESET}` : line;
2654
+ }
2655
+ var EXIT_CODES = {
2656
+ Success: 0,
2657
+ Failure: 1,
2658
+ ConfigError: 1,
2659
+ AuthenticationError: 2,
2660
+ ValidationError: 3,
2661
+ TimeoutError: 4
2662
+ };
2663
+ function exitCodeForResult(result) {
2664
+ return EXIT_CODES[result] ?? EXIT_CODES.Failure;
2665
+ }
2666
+ function escapeNonAscii(jsonText) {
2667
+ return jsonText.replace(/[\u0080-\uffff]/g, (c) => {
2668
+ const hex = c.charCodeAt(0).toString(16).padStart(4, "0");
2669
+ return `\\u${hex}`;
2670
+ });
2671
+ }
2672
+ function needsAsciiSafeJson(sink) {
2673
+ return process.platform === "win32" && !sink.capabilities.isInteractive;
2674
+ }
2675
+ function isPlainRecord(value) {
2676
+ if (value === null || typeof value !== "object")
2677
+ return false;
2678
+ const prototype = Object.getPrototypeOf(value);
2679
+ return prototype === Object.prototype || prototype === null;
2680
+ }
2681
+ function splitPagedEnvelope(value) {
2682
+ if (Array.isArray(value) || !isPlainRecord(value))
2683
+ return null;
2684
+ const entries = Object.entries(value);
2685
+ if (entries.length === 0)
2686
+ return null;
2687
+ let found = null;
2688
+ const meta = Object.create(null);
2689
+ for (const [key, entry] of entries) {
2690
+ if (Array.isArray(entry)) {
2691
+ if (found !== null)
2692
+ return null;
2693
+ found = { key, rows: entry };
2694
+ } else if (entry !== null && typeof entry === "object") {
2695
+ return null;
2696
+ } else {
2697
+ meta[key] = entry;
2698
+ }
2699
+ }
2700
+ if (found === null || Object.keys(meta).length === 0)
2701
+ return null;
2702
+ return { ...found, meta };
2703
+ }
2704
+ function extractPagedRows(value) {
2705
+ const paged = splitPagedEnvelope(value);
2706
+ return paged === null ? null : paged.rows;
2707
+ }
2708
+ function toLowerCamelCaseKey(key) {
2709
+ if (!key)
2710
+ return key;
2711
+ if (/[_\-\s]/.test(key)) {
2712
+ const [firstPart, ...restParts] = key.split(/[_\-\s]+/).filter(Boolean);
2713
+ if (!firstPart)
2714
+ return key;
2715
+ return [
2716
+ toLowerCamelCaseSimpleKey(firstPart),
2717
+ ...restParts.map((part) => {
2718
+ const normalized = toLowerCamelCaseSimpleKey(part);
2719
+ return normalized.charAt(0).toUpperCase() + normalized.slice(1);
2720
+ })
2721
+ ].join("");
2722
+ }
2723
+ return toLowerCamelCaseSimpleKey(key);
2724
+ }
2725
+ function toLowerCamelCaseSimpleKey(key) {
2726
+ if (/^[A-Z0-9]+$/.test(key))
2727
+ return key.toLowerCase();
2728
+ return key.replace(/^[A-Z]+(?=[A-Z][a-z]|\d|$)|^[A-Z]/, (match) => match.toLowerCase());
2729
+ }
2730
+ function toPascalCaseKey(key) {
2731
+ const lowerCamelKey = toLowerCamelCaseKey(key);
2732
+ return lowerCamelKey ? lowerCamelKey.charAt(0).toUpperCase() + lowerCamelKey.slice(1) : lowerCamelKey;
2733
+ }
2734
+ function collectVerbatimRefs(value, into) {
2735
+ if (typeof value !== "object" || value === null)
2736
+ return;
2737
+ if (into.has(value))
2738
+ return;
2739
+ into.add(value);
2740
+ for (const nested of Array.isArray(value) ? value : Object.values(value)) {
2741
+ collectVerbatimRefs(nested, into);
2742
+ }
2743
+ }
2744
+ function toPascalCaseData(value, verbatimKeys, subtrees) {
2745
+ if (subtrees?.mode === "skip" && typeof value === "object" && value !== null && subtrees.refs.has(value)) {
2746
+ return value;
2747
+ }
2748
+ if (Array.isArray(value))
2749
+ return value.map((entry) => toPascalCaseData(entry, verbatimKeys, subtrees));
2750
+ if (!isPlainRecord(value))
2751
+ return value;
2752
+ const result = {};
2753
+ for (const [key, nestedValue] of Object.entries(value)) {
2754
+ const pascalKey = toPascalCaseKey(key);
2755
+ if (verbatimKeys?.has(pascalKey)) {
2756
+ result[pascalKey] = nestedValue;
2757
+ if (subtrees?.mode === "collect") {
2758
+ collectVerbatimRefs(nestedValue, subtrees.refs);
2759
+ }
2760
+ continue;
2761
+ }
2762
+ result[pascalKey] = toPascalCaseData(nestedValue, verbatimKeys, subtrees);
2763
+ }
2764
+ return result;
2765
+ }
2766
+ function normalizeDataKeys(data, verbatimKeys, subtrees) {
2767
+ return toPascalCaseData(data, verbatimKeys, subtrees);
2768
+ }
2769
+ function toVerbatimKeySet(preserve) {
2770
+ if (!Array.isArray(preserve))
2771
+ return;
2772
+ return new Set(preserve.map(toPascalCaseKey));
2773
+ }
2774
+ function normalizeOutputKeys(data) {
2775
+ const result = {};
2776
+ for (const [key, value] of Object.entries(data)) {
2777
+ const pascalKey = toPascalCaseKey(key);
2778
+ result[pascalKey] = pascalKey === "Data" ? value : toPascalCaseData(value);
2779
+ }
2780
+ return result;
2781
+ }
2782
+ function printOutput(data, format = "json", logFn, asciiSafe = false, tableRowStyle) {
2783
+ if (!data) {
2784
+ logFn("Empty response object. No data to display.");
2785
+ return;
2786
+ }
2787
+ switch (format) {
2788
+ case "json": {
2789
+ const json = JSON.stringify(data, null, 2);
2790
+ logFn(asciiSafe ? escapeNonAscii(json) : json);
2791
+ break;
2792
+ }
2793
+ case "yaml":
2794
+ logFn(toYaml(data));
2795
+ break;
2796
+ case "plain": {
2797
+ if ("Data" in data && data.Data != null) {
2798
+ const pagedRows = extractPagedRows(data.Data);
2799
+ const items = pagedRows ?? (Array.isArray(data.Data) ? data.Data : [data.Data]);
2800
+ items.forEach((item) => {
2801
+ const values = Object.values(item).map((v) => v ?? "").join("\t");
2802
+ logFn(values);
2803
+ });
2804
+ } else {
2805
+ const values = Object.values(data).map((v) => v ?? "").join("\t");
2806
+ logFn(values);
2807
+ }
2808
+ break;
2809
+ }
2810
+ case "markdown":
2811
+ logFn(renderMarkdown(data));
2812
+ break;
2813
+ default: {
2814
+ const hasData = "Data" in data && data.Data != null;
2815
+ const pagedRows = hasData ? extractPagedRows(data.Data) : null;
2816
+ const rows = pagedRows ? pagedRows : Array.isArray(data.Data) ? data.Data : null;
2817
+ if (hasData && !(rows !== null && rows.length === 0)) {
2818
+ const logValue = data.Log;
2819
+ if (rows !== null) {
2820
+ printResizableTable(rows, logFn, logValue, undefined, tableRowStyle);
2821
+ } else {
2822
+ printVerticalTable(data.Data, logFn, logValue);
2823
+ }
2824
+ } else {
2825
+ printTable([{ ...data }], logFn);
2826
+ }
2827
+ break;
2828
+ }
2829
+ }
2830
+ }
2831
+ function logOutput(data, format = "json", tableRowStyle) {
2832
+ const sink = getOutputSink();
2833
+ const styleFn = sink.capabilities.isInteractive && sink.capabilities.supportsColor ? tableRowStyle : undefined;
2834
+ printOutput(data, format, (msg) => sink.writeOut(`${msg}
2835
+ `), needsAsciiSafeJson(sink), styleFn);
2836
+ }
2837
+ var PLUMBING_KEYS = new Set(["code", "log"]);
2838
+ function isPlumbingKey(key) {
2839
+ return PLUMBING_KEYS.has(key.toLowerCase());
2840
+ }
2841
+ function cellToString(val) {
2842
+ return val != null && typeof val === "object" ? JSON.stringify(val) : String(val ?? "");
2843
+ }
2844
+ function wrapText(text, width) {
2845
+ if (text.length <= width)
2846
+ return [text];
2847
+ const lines = [];
2848
+ for (let pos = 0;pos < text.length; pos += width) {
2849
+ lines.push(text.substring(pos, pos + width));
2850
+ }
2851
+ return lines;
2852
+ }
2853
+ function printTable(data, logFn, externalLogValue, tableRowStyle) {
2854
+ if (data.length === 0)
2855
+ return;
2856
+ const keys = Object.keys(data[0]).filter((key) => !isPlumbingKey(key));
2857
+ const maxWidths = keys.map((key) => Math.max(key.length, ...data.map((item) => cellToString(item[key]).length)));
2858
+ const header = keys.map((key, i) => key.padEnd(maxWidths[i])).join(" | ");
2859
+ logFn(header);
2860
+ logFn(keys.map((_, i) => "-".repeat(maxWidths[i])).join("-|-"));
2861
+ data.forEach((item) => {
2862
+ const row = keys.map((key, i) => cellToString(item[key]).padEnd(maxWidths[i])).join(" | ");
2863
+ logFn(styleLine(row, tableRowStyle?.(item)));
2864
+ });
2865
+ if (externalLogValue) {
2866
+ logFn("");
2867
+ logFn(`Log: ${externalLogValue}`);
2868
+ }
2869
+ }
2870
+ function isPlainObjectArray(value) {
2871
+ return Array.isArray(value) && value.length > 0 && value.every(isPlainRecord);
2872
+ }
2873
+ function isNonEmptyPlainObject(value) {
2874
+ return isPlainRecord(value) && Object.keys(value).length > 0;
2875
+ }
2876
+ var NESTED_INDENT = " ";
2877
+ function printVerticalTable(data, logFn = console.log, externalLogValue) {
2878
+ const keys = Object.keys(data).filter((key) => !isPlumbingKey(key));
2879
+ if (keys.length === 0)
2880
+ return;
2881
+ const isBlockValue = (value) => isPlainObjectArray(value) || isNonEmptyPlainObject(value);
2882
+ const scalarKeys = keys.filter((key) => !isBlockValue(data[key]));
2883
+ const maxKeyWidth = scalarKeys.length > 0 ? Math.max(...scalarKeys.map((key) => key.length)) : 0;
2884
+ const termWidth = process.stdout.columns || 120;
2885
+ const nestedWidth = Math.max(termWidth - NESTED_INDENT.length, 1);
2886
+ keys.forEach((key) => {
2887
+ const value = data[key];
2888
+ if (isPlainObjectArray(value)) {
2889
+ logFn(`${key}:`);
2890
+ printResizableTable(value, (line) => logFn(`${NESTED_INDENT}${line}`), undefined, nestedWidth);
2891
+ return;
2892
+ }
2893
+ if (isNonEmptyPlainObject(value)) {
2894
+ logFn(`${key}:`);
2895
+ printVerticalTable(value, (line) => logFn(`${NESTED_INDENT}${line}`));
2896
+ return;
2897
+ }
2898
+ const keyCol = key.padEnd(maxKeyWidth);
2899
+ logFn(`${keyCol} | ${cellToString(value)}`);
2900
+ });
2901
+ if (externalLogValue) {
2902
+ logFn("");
2903
+ logFn(`Log: ${externalLogValue}`);
2904
+ }
2905
+ }
2906
+ function printResizableTable(data, logFn = console.log, externalLogValue, availableWidth, tableRowStyle) {
2907
+ if (data.length === 0)
2908
+ return;
2909
+ const keys = Object.keys(data[0]).filter((key) => !isPlumbingKey(key));
2910
+ if (keys.length === 0)
2911
+ return;
2912
+ if (!process.stdout.isTTY) {
2913
+ printTable(data, logFn, externalLogValue, tableRowStyle);
2914
+ return;
2915
+ }
2916
+ const naturalWidths = keys.map((key) => Math.max(key.length, ...data.map((item) => cellToString(item[key]).length)));
2917
+ const separatorTotal = (keys.length - 1) * 3;
2918
+ const totalWidth = naturalWidths.reduce((a, b) => a + b, 0) + separatorTotal;
2919
+ const termWidth = availableWidth ?? (process.stdout.columns || 120);
2920
+ if (totalWidth <= termWidth) {
2921
+ printTable(data, logFn, externalLogValue, tableRowStyle);
2922
+ return;
2923
+ }
2924
+ const overflow = totalWidth - termWidth;
2925
+ const MIN_COL_WIDTH = 10;
2926
+ const minWidths = keys.map((key) => Math.max(key.length, MIN_COL_WIDTH));
2927
+ let bestCol = -1;
2928
+ let bestCost = Infinity;
2929
+ for (let i = 0;i < keys.length; i++) {
2930
+ const maxShrink = naturalWidths[i] - minWidths[i];
2931
+ if (maxShrink < overflow)
2932
+ continue;
2933
+ const newWidth = naturalWidths[i] - overflow;
2934
+ let extraRows = 0;
2935
+ for (const item of data) {
2936
+ const cellLen = cellToString(item[keys[i]]).length;
2937
+ if (cellLen > newWidth) {
2938
+ extraRows += Math.ceil(cellLen / newWidth) - 1;
2939
+ }
2940
+ }
2941
+ if (extraRows < bestCost) {
2942
+ bestCost = extraRows;
2943
+ bestCol = i;
2944
+ }
2945
+ }
2946
+ const finalWidths = [...naturalWidths];
2947
+ if (bestCol !== -1) {
2948
+ finalWidths[bestCol] = naturalWidths[bestCol] - overflow;
2949
+ } else {
2950
+ let remaining = overflow;
2951
+ const colsByShrinkPotential = keys.map((_, i) => ({
2952
+ index: i,
2953
+ potential: naturalWidths[i] - minWidths[i]
2954
+ })).filter((c) => c.potential > 0).sort((a, b) => b.potential - a.potential);
2955
+ for (const col of colsByShrinkPotential) {
2956
+ if (remaining <= 0)
2957
+ break;
2958
+ const shrink = Math.min(remaining, col.potential);
2959
+ finalWidths[col.index] -= shrink;
2960
+ remaining -= shrink;
2961
+ }
2962
+ }
2963
+ const header = keys.map((key, i) => key.padEnd(finalWidths[i])).join(" | ");
2964
+ logFn(header);
2965
+ logFn(keys.map((_, i) => "-".repeat(finalWidths[i])).join("-|-"));
2966
+ data.forEach((item) => {
2967
+ const style = tableRowStyle?.(item);
2968
+ const cellLines = keys.map((key, i) => wrapText(cellToString(item[key]), finalWidths[i]));
2969
+ const lineCount = Math.max(...cellLines.map((l) => l.length));
2970
+ for (let line = 0;line < lineCount; line++) {
2971
+ const row = keys.map((_, i) => {
2972
+ const val = line < cellLines[i].length ? cellLines[i][line] : "";
2973
+ return val.padEnd(finalWidths[i]);
2974
+ }).join(" | ");
2975
+ logFn(styleLine(row, style));
2976
+ }
2977
+ });
2978
+ if (externalLogValue) {
2979
+ logFn("");
2980
+ logFn(`Log: ${externalLogValue}`);
2981
+ }
2982
+ }
2983
+ var MARKDOWN_MAX_CELL = 200;
2984
+ var MARKDOWN_MAX_DEPTH = 3;
2985
+ function markdownHeading(depth) {
2986
+ return "#".repeat(Math.min(3 + depth, 6));
2987
+ }
2988
+ var BACKTICK_RUN = /`+/g;
2989
+ function fencedBlock(text) {
2990
+ const first = text.trimStart()[0];
2991
+ const language = first === "<" ? "xml" : first === "{" || first === "[" ? "json" : "";
2992
+ const longestRun = Math.max(0, ...Array.from(text.matchAll(BACKTICK_RUN), (match) => match[0].length));
2993
+ const fence = "`".repeat(Math.max(3, longestRun + 1));
2994
+ return `${fence}${language}
2995
+ ${text}
2996
+ ${fence}`;
2997
+ }
2998
+ function collapseNewlineRuns(text) {
2999
+ return text.split(/(\s+)/).map((part, index) => index % 2 === 1 && part.includes(`
3000
+ `) ? " " : part).join("");
3001
+ }
3002
+ function markdownCell(value) {
3003
+ const text = value instanceof Date ? value.toISOString() : cellToString(value);
3004
+ return collapseNewlineRuns(text).replace(/\|/g, "\\|");
3005
+ }
3006
+ function markdownLabel(key) {
3007
+ return collapseNewlineRuns(key).replace(/[\\`*|]/g, "\\$&");
3008
+ }
3009
+ function withoutPlumbing(record) {
3010
+ const kept = Object.create(null);
3011
+ for (const [key, value] of Object.entries(record)) {
3012
+ if (!isPlumbingKey(key))
3013
+ kept[key] = value;
3014
+ }
3015
+ return kept;
3016
+ }
3017
+ function rowsWithoutPlumbing(rows) {
3018
+ return rows.map((row) => isPlainRecord(row) ? withoutPlumbing(row) : row);
3019
+ }
3020
+ function markdownTable(rows) {
3021
+ const columns = [];
3022
+ const seen = new Set;
3023
+ for (const row of rows) {
3024
+ for (const key of Object.keys(row)) {
3025
+ if (!seen.has(key)) {
3026
+ seen.add(key);
3027
+ columns.push(key);
3028
+ }
3029
+ }
3030
+ }
3031
+ if (columns.length === 0)
3032
+ return null;
3033
+ const cells = rows.map((row) => columns.map((key) => markdownCell(row[key])));
3034
+ if (cells.some((row) => row.some((c) => c.length > MARKDOWN_MAX_CELL))) {
3035
+ return null;
3036
+ }
3037
+ return [
3038
+ `| ${columns.map(markdownLabel).join(" | ")} |`,
3039
+ `| ${columns.map(() => "---").join(" | ")} |`,
3040
+ ...cells.map((row) => `| ${row.join(" | ")} |`)
3041
+ ].join(`
3042
+ `);
3043
+ }
3044
+ function extractMessageSequence(rows) {
3045
+ const messages = [];
3046
+ for (const row of rows) {
3047
+ const message = extractSingleMessage(row);
3048
+ if (message === null)
3049
+ return null;
3050
+ messages.push(message);
3051
+ }
3052
+ return messages.join(`
3053
+
3054
+ `);
3055
+ }
3056
+ function markdownRows(rows, depth) {
3057
+ if (rows.length === 0)
3058
+ return "(none)";
3059
+ if (!isPlainObjectArray(rows)) {
3060
+ return rows.map((item) => `- ${markdownCell(item)}`).join(`
3061
+ `);
3062
+ }
3063
+ const prose = extractMessageSequence(rows);
3064
+ if (prose !== null)
3065
+ return prose;
3066
+ const table = markdownTable(rows);
3067
+ if (table !== null)
3068
+ return table;
3069
+ if (depth >= MARKDOWN_MAX_DEPTH) {
3070
+ return fencedBlock(JSON.stringify(rows, null, 2));
3071
+ }
3072
+ return rows.map((row, index) => [
3073
+ `${markdownHeading(depth)} ${index + 1}`,
3074
+ markdownObject(row, depth + 1)
3075
+ ].join(`
3076
+
3077
+ `)).join(`
3078
+
3079
+ `);
3080
+ }
3081
+ function markdownObject(obj, depth) {
3082
+ const scalars = [];
3083
+ const blocks = [];
3084
+ for (const [key, value] of Object.entries(obj)) {
3085
+ if (value === undefined)
3086
+ continue;
3087
+ const label = markdownLabel(key);
3088
+ if (Array.isArray(value)) {
3089
+ blocks.push(`${markdownHeading(depth)} ${label}
3090
+
3091
+ ${markdownRows(value, depth + 1)}`);
3092
+ } else if (isNonEmptyPlainObject(value)) {
3093
+ const nested = depth < MARKDOWN_MAX_DEPTH ? markdownObject(value, depth + 1) : fencedBlock(JSON.stringify(value, null, 2));
3094
+ if (nested !== "") {
3095
+ blocks.push(`${markdownHeading(depth)} ${label}
3096
+
3097
+ ${nested}`);
3098
+ }
3099
+ } else if (typeof value === "string" && value.includes(`
3100
+ `)) {
3101
+ blocks.push(`**${label}:**
3102
+
3103
+ ${fencedBlock(value)}`);
3104
+ } else {
3105
+ scalars.push(`**${label}:** ${markdownCell(value)}`);
3106
+ }
3107
+ }
3108
+ const sections = scalars.length > 0 ? [scalars.join(`
3109
+ `)] : [];
3110
+ sections.push(...blocks);
3111
+ return sections.join(`
3112
+
3113
+ `);
3114
+ }
3115
+ function extractSingleMessage(payload) {
3116
+ if (!isPlainRecord(payload))
3117
+ return null;
3118
+ const keys = Object.keys(payload);
3119
+ if (keys.length !== 1 || keys[0].toLowerCase() !== "message")
3120
+ return null;
3121
+ const value = payload[keys[0]];
3122
+ return typeof value === "string" ? value : null;
3123
+ }
3124
+ function markdownPayload(payload) {
3125
+ const message = extractSingleMessage(payload);
3126
+ if (message !== null)
3127
+ return message;
3128
+ if (Array.isArray(payload)) {
3129
+ return markdownRows(rowsWithoutPlumbing(payload), 0);
3130
+ }
3131
+ const visible = withoutPlumbing(payload);
3132
+ const paged = splitPagedEnvelope(visible);
3133
+ if (paged !== null) {
3134
+ const meta = markdownObject(paged.meta, 0);
3135
+ const rows = `${markdownHeading(0)} ${markdownLabel(paged.key)}
3136
+
3137
+ ${markdownRows(rowsWithoutPlumbing(paged.rows), 1)}`;
3138
+ return meta === "" ? rows : `${meta}
3139
+
3140
+ ${rows}`;
3141
+ }
3142
+ return markdownObject(visible, 0);
3143
+ }
3144
+ function isPaginationWorthShowing(value) {
3145
+ if (typeof value !== "object" || value === null)
3146
+ return false;
3147
+ const page = value;
3148
+ return page.HasMore === true || typeof page.Offset === "number" && page.Offset > 0;
3149
+ }
3150
+ function markdownEnvelopeNotes(data) {
3151
+ const envelope = data;
3152
+ const notes = [];
3153
+ const warning = envelope.Warning;
3154
+ if (typeof warning === "string" && warning !== "") {
3155
+ notes.push(`> **Warning:** ${warning}`);
3156
+ }
3157
+ const instructions = envelope.Instructions;
3158
+ if (typeof instructions === "string" && instructions !== "") {
3159
+ notes.push(`> ${instructions}`);
3160
+ }
3161
+ const pagination = envelope.Pagination;
3162
+ if (isPaginationWorthShowing(pagination)) {
3163
+ const body = markdownObject(pagination, 1);
3164
+ if (body !== "") {
3165
+ notes.push(`${markdownHeading(0)} Pagination
3166
+
3167
+ ${body}`);
3168
+ }
3169
+ }
3170
+ const log = envelope.Log;
3171
+ if (typeof log === "string" && log !== "") {
3172
+ notes.push(`**Log:** ${log}`);
3173
+ }
3174
+ return notes;
3175
+ }
3176
+ function renderMarkdown(data) {
3177
+ if (data.Result !== RESULTS.Success) {
3178
+ const failure = data;
3179
+ const sections = [`**Failed:** ${failure.Message}`];
3180
+ if (failure.Data != null) {
3181
+ sections.push(markdownPayload(failure.Data));
3182
+ }
3183
+ if (failure.Instructions) {
3184
+ sections.push(`> ${failure.Instructions}`);
3185
+ }
3186
+ return sections.filter((section) => section !== "").join(`
3187
+
3188
+ `);
3189
+ }
3190
+ if (!("Data" in data) || data.Data == null) {
3191
+ return markdownObject(withoutPlumbing(data), 0);
3192
+ }
3193
+ return [markdownPayload(data.Data), ...markdownEnvelopeNotes(data)].filter((section) => section !== "").join(`
3194
+
3195
+ `);
3196
+ }
3197
+ function toYaml(data) {
3198
+ const codec = getYamlCodec();
3199
+ if (!codec) {
3200
+ throw new Error("YAML output requested before the YAML codec was loaded. " + "Call loadOutputCodecsAsync({ yaml: true }) first.");
3201
+ }
3202
+ return codec.dump(data);
3203
+ }
3204
+ function requireJmespath() {
3205
+ const codec = getJmespathCodec();
3206
+ if (!codec) {
3207
+ throw new Error("An --output-filter was applied before the JMESPath codec was loaded. " + "Call loadOutputCodecsAsync({ filter: true }) first.");
3208
+ }
3209
+ return codec;
3210
+ }
3211
+
3212
+ class FilterEvaluationError extends Error {
3213
+ __brand = "FilterEvaluationError";
3214
+ filter;
3215
+ errorCode = "invalid_argument";
3216
+ instructions;
3217
+ retry = "RetryWillNotFix";
3218
+ result = RESULTS.ValidationError;
3219
+ constructor(filter, cause) {
3220
+ const underlying = cause instanceof Error ? cause.message : String(cause);
3221
+ super(`Filter '${filter}' failed to evaluate: ${underlying}`);
3222
+ this.name = "FilterEvaluationError";
3223
+ this.filter = filter;
3224
+ this.instructions = `The --output-filter expression '${filter}' failed at evaluation time. ` + "Note that --output-filter operates on the 'Data' field of the envelope, not the full object. " + "For example, on a list result use 'length(@)' instead of 'Data | length(@)'.";
3225
+ }
3226
+ }
3227
+ function countRecords(data) {
3228
+ if (Array.isArray(data))
3229
+ return data.length;
3230
+ return data == null ? 0 : 1;
3231
+ }
3232
+ function availableFields(data) {
3233
+ const records = Array.isArray(data) ? data : [data];
3234
+ const keys = new Set;
3235
+ for (const record of records) {
3236
+ if (record && typeof record === "object" && !Array.isArray(record)) {
3237
+ for (const key of Object.keys(record))
3238
+ keys.add(key);
3239
+ }
3240
+ }
3241
+ return [...keys];
3242
+ }
3243
+ function decodeQuotedIdentifier(whole, inner) {
3244
+ const [error, decoded] = catchError(() => JSON.parse(whole));
3245
+ if (!error && typeof decoded === "string")
3246
+ return decoded;
3247
+ return inner.replace(/\\(.)/g, "$1");
3248
+ }
3249
+ function referencedFields(filter) {
3250
+ const top = new Set;
3251
+ const nested = new Set;
3252
+ const withoutValueLiterals = filter.replace(/'(?:\\.|[^'\\])*'/g, " ").replace(/`(?:\\.|[^`\\])*`/g, " ");
3253
+ const isPathTail = (text, index) => text[index - 1] === "." && /[A-Za-z0-9_"]/.test(text[index - 2] ?? "");
3254
+ const quoted = [];
3255
+ const withoutLiterals = withoutValueLiterals.replace(/"((?:\\.|[^"\\])*)"/g, (whole, name, index) => {
3256
+ const isAlias = /^\s*:/.test(withoutValueLiterals.slice(index + whole.length));
3257
+ if (!isAlias) {
3258
+ quoted.push({
3259
+ name: decodeQuotedIdentifier(whole, name),
3260
+ index,
3261
+ tail: isPathTail(withoutValueLiterals, index)
3262
+ });
3263
+ }
3264
+ return `"${" ".repeat(whole.length - 2)}"`;
3265
+ });
3266
+ const descent = /[A-Za-z0-9_"]\s*[.[]/.exec(withoutLiterals);
3267
+ const rootEnd = descent ? descent.index + 1 : Number.POSITIVE_INFINITY;
3268
+ const place = (name, index, tail) => {
3269
+ if (tail || index >= rootEnd)
3270
+ nested.add(name);
3271
+ else
3272
+ top.add(name);
3273
+ };
3274
+ for (const entry of quoted)
3275
+ place(entry.name, entry.index, entry.tail);
3276
+ const identifiers = withoutLiterals.matchAll(/([A-Za-z_][A-Za-z0-9_]*)(\s*[:(])?/g);
3277
+ const reserved = new Set(["true", "false", "null", "and", "or", "not"]);
3278
+ for (const match of identifiers) {
3279
+ const [, name, trailing] = match;
3280
+ if (trailing || reserved.has(name))
3281
+ continue;
3282
+ place(name, match.index, isPathTail(withoutLiterals, match.index));
3283
+ }
3284
+ return {
3285
+ top: [...top],
3286
+ nested: [...nested].filter((name) => !top.has(name)),
3287
+ hasPredicate: /\[\s*\?/.test(withoutValueLiterals)
3288
+ };
3289
+ }
3290
+ function appearsBelowTopLevel(data, name) {
3291
+ let budget = 2000;
3292
+ const visit = (value, depth) => {
3293
+ if (budget-- <= 0 || depth > 4)
3294
+ return false;
3295
+ if (value === null || typeof value !== "object")
3296
+ return false;
3297
+ if (Array.isArray(value))
3298
+ return value.some((entry) => visit(entry, depth));
3299
+ const record = value;
3300
+ if (depth > 0 && Object.hasOwn(record, name))
3301
+ return true;
3302
+ return Object.values(record).some((entry) => visit(entry, depth + 1));
3303
+ };
3304
+ return visit(data, 0);
3305
+ }
3306
+ function alwaysNullKeys(records) {
3307
+ const objects = records.filter((r) => r != null && typeof r === "object" && !Array.isArray(r));
3308
+ if (objects.length === 0 || objects.length !== records.length)
3309
+ return [];
3310
+ const keys = [...new Set(objects.flatMap((o) => Object.keys(o)))];
3311
+ if (keys.length === 0)
3312
+ return [];
3313
+ const nullKeys = keys.filter((key) => objects.every((record) => record[key] === null));
3314
+ return nullKeys.length === keys.length ? nullKeys : [];
3315
+ }
3316
+ function carriesOnlyNulls(value) {
3317
+ if (value === null)
3318
+ return true;
3319
+ if (Array.isArray(value)) {
3320
+ return value.length > 0 && value.every(carriesOnlyNulls);
3321
+ }
3322
+ if (typeof value === "object" && value !== undefined) {
3323
+ const values = Object.values(value);
3324
+ return values.length > 0 && values.every(carriesOnlyNulls);
3325
+ }
3326
+ return false;
3327
+ }
3328
+ function nameList(names, cap = 12) {
3329
+ const shown = names.slice(0, cap).map((n) => `\`${n}\``);
3330
+ const rest = names.length - shown.length;
3331
+ return shown.join(", ") + (rest > 0 ? `, and ${rest} more` : "");
3332
+ }
3333
+ function buildFilterWarning(filter, data, outcome) {
3334
+ const present = availableFields(data);
3335
+ const refs = referencedFields(filter);
3336
+ const unknown = refs.top.filter((name) => !present.includes(name) && !appearsBelowTopLevel(data, name));
3337
+ const unchecked = refs.nested.filter((name) => !present.includes(name));
3338
+ const count = countRecords(data);
3339
+ const scope = `${count} record(s)`;
3340
+ const isNotAField = (names) => `${nameList(names)} ${names.length === 1 ? "is not a field" : "are not fields"} on the ${scope} it read`;
3341
+ const soundness = unchecked.length > 0 ? `${nameList(unchecked)} ${unchecked.length === 1 ? "reads" : "read"} below the top level, so ${unchecked.length === 1 ? "it was" : "they were"} not checked against the record keys` : refs.top.length > 0 ? "every field it names exists" : "";
3342
+ const withSoundness = (base) => soundness ? `${base}, and ${soundness}` : base;
3343
+ let detail;
3344
+ let lede;
3345
+ if (outcome.kind === "null-elements") {
3346
+ lede = "returned only null values";
3347
+ const projected = `all ${outcome.count} of the elements it projected are null`;
3348
+ if (unknown.length > 0) {
3349
+ detail = `${projected}, because ${isNotAField(unknown)}`;
3350
+ } else if (unchecked.length > 0) {
3351
+ detail = withSoundness(projected);
3352
+ } else {
3353
+ detail = `${projected}, and every field it names exists — a multi-select list ` + `(\`[A, B]\`) reads each entry against \`Data\` itself, so on a list ` + `result use \`[].[A, B]\` or \`[].{a: A, b: B}\` to read the records`;
3354
+ }
3355
+ } else if (outcome.kind === "null-rows") {
3356
+ lede = "returned only null values";
3357
+ const projected = `every value it projected is null on all ${outcome.count} row(s)`;
3358
+ detail = unknown.length > 0 ? `${projected}, because ${isNotAField(unknown)}` : withSoundness(projected);
3359
+ } else if (outcome.kind === "null-values") {
3360
+ lede = "returned only null values";
3361
+ const projected = `every key it projected (${nameList(outcome.keys)}) is null`;
3362
+ const sameSet = unknown.length === outcome.keys.length && outcome.keys.every((k) => unknown.includes(k));
3363
+ if (sameSet) {
3364
+ detail = `${isNotAField(outcome.keys)}, so every key it projected is null`;
3365
+ } else if (unknown.length > 0) {
3366
+ detail = `${projected}, because ${isNotAField(unknown)}`;
3367
+ } else {
3368
+ detail = withSoundness(`${projected} on all ${scope}`);
3369
+ }
3370
+ } else {
3371
+ lede = "returned nothing";
3372
+ if (unknown.length > 0) {
3373
+ detail = isNotAField(unknown);
3374
+ } else {
3375
+ const selection = refs.hasPredicate ? "no record matched" : "the expression resolved to no value";
3376
+ detail = withSoundness(`${selection} — it read ${scope}`);
3377
+ }
3378
+ }
3379
+ const fields = present.length > 0 ? ` Available fields: ${nameList(present)}.` : "";
3380
+ return `--output-filter ${JSON.stringify(filter)} ${lede}: ${detail}.${fields}`;
3381
+ }
3382
+ function appendWarning(existing, note) {
3383
+ return existing ? `${existing} ${note}` : note;
3384
+ }
3385
+ function applyFilter(data, filter, onWarning) {
3386
+ const codec = requireJmespath();
3387
+ let result;
3388
+ try {
3389
+ result = codec.search(data, filter);
3390
+ } catch (err) {
3391
+ throw new FilterEvaluationError(filter, err);
3392
+ }
3393
+ const inputCount = countRecords(data);
3394
+ const warn = (outcome) => {
3395
+ if (inputCount === 0)
3396
+ return;
3397
+ const note = buildFilterWarning(filter, data, outcome);
3398
+ getOutputSink().writeErr(`[WARN] ${note}
3399
+ `);
3400
+ onWarning?.(note);
3401
+ };
3402
+ const warnIfAllNull = (records) => {
3403
+ const keys = alwaysNullKeys(records);
3404
+ if (keys.length > 0)
3405
+ warn({ kind: "null-values", keys });
3406
+ };
3407
+ if (result == null) {
3408
+ warn({ kind: "empty" });
3409
+ return [];
3410
+ }
3411
+ if (Array.isArray(result)) {
3412
+ if (result.length === 0) {
3413
+ warn({ kind: "empty" });
3414
+ } else if (result.every((entry) => entry === null)) {
3415
+ warn({ kind: "null-elements", count: result.length });
3416
+ } else if (result.every((entry) => Array.isArray(entry)) && carriesOnlyNulls(result)) {
3417
+ warn({ kind: "null-rows", count: result.length });
3418
+ } else {
3419
+ warnIfAllNull(result);
3420
+ }
3421
+ if (result.length > 0 && typeof result[0] !== "object") {
3422
+ const fieldMatch = filter.match(/\.(\w+)$/);
3423
+ const key = fieldMatch ? fieldMatch[1] : "Value";
3424
+ return result.map((v) => ({ [key]: v }));
3425
+ }
3426
+ return result;
3427
+ }
3428
+ if (typeof result === "object") {
3429
+ warnIfAllNull([result]);
3430
+ return result;
3431
+ }
3432
+ return { Value: result };
3433
+ }
3434
+ function filterFailureData(envelope) {
3435
+ const filter = getOutputFilter();
3436
+ const data = envelope.Data;
3437
+ if (!filter || data == null)
3438
+ return;
3439
+ let note;
3440
+ const [filterError, filtered] = catchError(() => applyFilter(data, filter, (n) => {
3441
+ note = n;
3442
+ }));
3443
+ if (filterError) {
3444
+ envelope.Warning = appendWarning(envelope.Warning, `--output-filter was not applied, so Data is shown in full: ${filterError.message}`);
3445
+ return;
3446
+ }
3447
+ envelope.Data = filtered;
3448
+ if (note) {
3449
+ envelope.Warning = appendWarning(envelope.Warning, note);
3450
+ }
3451
+ }
3452
+ function defaultErrorCodeForResult(result) {
3453
+ switch (result) {
3454
+ case RESULTS.AuthenticationError:
3455
+ return "authentication_required";
3456
+ case RESULTS.ConfigError:
3457
+ return "configuration_error";
3458
+ case RESULTS.ValidationError:
3459
+ return "invalid_argument";
3460
+ case RESULTS.TimeoutError:
3461
+ return "timeout";
3462
+ default:
3463
+ return "unknown_error";
3464
+ }
3465
+ }
3466
+ var LOCAL_PERMISSION_TEXT_PATTERN = new RegExp(`(?:\\b|\\()(?:${[...LOCAL_PERMISSION_ERROR_CODES].join("|")})(?::\\s|\\))`);
3467
+ function defaultErrorCodeForFailure(data) {
3468
+ if (data.Result === RESULTS.Failure) {
3469
+ const status = data.Context?.httpStatus ?? parseHttpStatusFromMessage(data.Message);
3470
+ const errorCode = classifyHttpStatus(status)?.errorCode;
3471
+ if (errorCode)
3472
+ return errorCode;
3473
+ if (status === undefined && (LOCAL_PERMISSION_TEXT_PATTERN.test(data.Message) || LOCAL_PERMISSION_TEXT_PATTERN.test(data.Instructions))) {
3474
+ return "local_permission_denied";
3475
+ }
3476
+ }
3477
+ return defaultErrorCodeForResult(data.Result);
3478
+ }
3479
+ var OutputFormatter;
3480
+ ((OutputFormatter) => {
3481
+ function success(data, options) {
3482
+ data.Log ??= getLogFilePath() || undefined;
3483
+ const normalize = options?.preserveDataKeys !== true;
3484
+ const verbatim = toVerbatimKeySet(options?.preserveDataKeys);
3485
+ const subtrees = verbatim && {
3486
+ refs: new Set,
3487
+ mode: "collect"
3488
+ };
3489
+ if (normalize) {
3490
+ data.Data = normalizeDataKeys(data.Data, verbatim, subtrees);
3491
+ }
3492
+ const filter = getOutputFilter();
3493
+ if (filter) {
3494
+ let note;
3495
+ const filtered = applyFilter(data.Data, filter, (n) => {
3496
+ note = n;
3497
+ });
3498
+ data.Data = normalize ? normalizeDataKeys(filtered, verbatim, subtrees && { refs: subtrees.refs, mode: "skip" }) : filtered;
3499
+ if (note) {
3500
+ data.Warning = appendWarning(data.Warning, note);
3501
+ }
3502
+ }
3503
+ logOutput(normalizeOutputKeys(data), getOutputFormat(), options?.tableRowStyle);
3504
+ }
3505
+ OutputFormatter.success = success;
3506
+ function error(data) {
3507
+ data.Log ??= getLogFilePath() || undefined;
3508
+ data.ErrorCode ??= defaultErrorCodeForFailure(data);
3509
+ data.Retry ??= defaultRetryForErrorCode(data.ErrorCode);
3510
+ const exitCode = exitCodeForResult(data.Result);
3511
+ setExitCode(exitCode);
3512
+ recordCommandFailureTelemetry({
3513
+ result: data.Result,
3514
+ errorCode: data.ErrorCode,
3515
+ retry: data.Retry,
3516
+ message: data.Message,
3517
+ context: data.Context,
3518
+ exitCode,
3519
+ errorClass: data.TelemetryErrorClass,
3520
+ terminalOutcome: data.TelemetryTerminalOutcome,
3521
+ terminalSignal: data.TelemetryTerminalSignal
3522
+ });
3523
+ const suppressTelemetry = data.SuppressTelemetry === true;
3524
+ const envelope = { ...data };
3525
+ delete envelope.SuppressTelemetry;
3526
+ delete envelope.TelemetryErrorClass;
3527
+ delete envelope.TelemetryTerminalOutcome;
3528
+ delete envelope.TelemetryTerminalSignal;
3529
+ filterFailureData(envelope);
3530
+ if (!suppressTelemetry) {
3531
+ telemetry.trackEvent(CommonTelemetryEvents.Error, {
3532
+ [ErrorDimensions.Result]: data.Result,
3533
+ [ErrorDimensions.ErrorCode]: data.ErrorCode,
3534
+ [ErrorDimensions.Retry]: data.Retry,
3535
+ [ErrorDimensions.ErrorMessage]: data.Message,
3536
+ [ErrorDimensions.HttpStatus]: data.Context?.httpStatus?.toString(),
3537
+ [ErrorDimensions.UpstreamErrorCode]: data.Context?.errorCode
3538
+ });
3539
+ }
3540
+ logOutput(normalizeOutputKeys(envelope), getOutputFormat());
3541
+ }
3542
+ OutputFormatter.error = error;
3543
+ function emitList(code, items, opts) {
3544
+ const data = {
3545
+ Result: RESULTS.Success,
3546
+ Code: code,
3547
+ Data: items
3548
+ };
3549
+ if (items.length === 0 && opts?.emptyInstructions) {
3550
+ data.Instructions = opts.emptyInstructions;
3551
+ }
3552
+ if (opts?.warning) {
3553
+ data.Warning = opts.warning;
3554
+ }
3555
+ if (opts?.pagination) {
3556
+ data.Pagination = opts.pagination;
3557
+ }
3558
+ success(data);
3559
+ }
3560
+ OutputFormatter.emitList = emitList;
3561
+ function log(data) {
3562
+ const format = getOutputFormat();
3563
+ const sink = getOutputSink();
3564
+ const normalized = toPascalCaseData(data);
3565
+ if (format === "json") {
3566
+ const json = JSON.stringify(normalized);
3567
+ const safe = needsAsciiSafeJson(sink) ? escapeNonAscii(json) : json;
3568
+ sink.writeErr(`${safe}
3569
+ `);
3570
+ } else {
3571
+ for (const [key, value] of Object.entries(normalized)) {
3572
+ sink.writeErr(`${key}: ${value}
3573
+ `);
3574
+ }
3575
+ }
3576
+ }
3577
+ OutputFormatter.log = log;
3578
+ function formatToString(data) {
3579
+ const filter = getOutputFilter();
3580
+ const envelope = data;
3581
+ if ("Data" in data && data.Data != null) {
3582
+ data.Data = normalizeDataKeys(data.Data);
3583
+ if (filter) {
3584
+ let note;
3585
+ data.Data = normalizeDataKeys(applyFilter(data.Data, filter, (n) => {
3586
+ note = n;
3587
+ }));
3588
+ if (note) {
3589
+ envelope.Warning = appendWarning(envelope.Warning, note);
3590
+ }
3591
+ }
3592
+ }
3593
+ const output = normalizeOutputKeys(envelope);
3594
+ const lines = [];
3595
+ const sink = getOutputSink();
3596
+ printOutput(output, getOutputFormat(), (msg) => {
3597
+ lines.push(msg);
3598
+ }, needsAsciiSafeJson(sink));
3599
+ return lines.join(`
3600
+ `);
3601
+ }
3602
+ OutputFormatter.formatToString = formatToString;
3603
+ })(OutputFormatter ||= {});
3604
+
3605
+ // src/testing.ts
3606
+ function installFormatterFakes(fakes) {
3607
+ const real = OutputFormatter;
3608
+ real.success = (...args) => fakes.success(...args);
3609
+ real.error = (data) => {
3610
+ fakes.error(data);
3611
+ recordFailureExit(data);
3612
+ };
3613
+ return fakes;
3614
+ }
3615
+ function recordFailureExit(data) {
3616
+ setExitCode(exitCodeForResult(data.Result));
3617
+ }
3618
+ export {
3619
+ installFormatterFakes,
3620
+ recordFailureExit
3621
+ };
3622
+
3623
+ //# debugId=5DC6B46BF9D47B6F64756E2164756E21