@uipath/traces-tool 1.201.0 → 1.202.0-preview.136

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.
@@ -1,23 +1,11 @@
1
- import {
2
- isBrowser
3
- } from "./tool-9qecd4wb.js";
4
- import {
5
- catchError,
6
- getFileSystem
7
- } from "./tool-7eva0peq.js";
8
- import {
9
- AUTH_FILENAME,
10
- DEFAULT_BASE_URL,
11
- UIPATH_HOME_DIR
12
- } from "./tool-5arsyj36.js";
13
1
  import {
14
2
  __commonJS,
15
3
  __require,
16
4
  __toESM
17
- } from "./tool-0v6na3yp.js";
5
+ } from "./tool-1de529jm.js";
18
6
 
19
7
  // ../../node_modules/commander/lib/error.js
20
- var require_error = __commonJS((exports) => {
8
+ var require_error = __commonJS(function(exports) {
21
9
  class CommanderError extends Error {
22
10
  constructor(exitCode, code, message) {
23
11
  super(message);
@@ -41,7 +29,7 @@ var require_error = __commonJS((exports) => {
41
29
  });
42
30
 
43
31
  // ../../node_modules/commander/lib/argument.js
44
- var require_argument = __commonJS((exports) => {
32
+ var require_argument = __commonJS(function(exports) {
45
33
  var { InvalidArgumentError } = require_error();
46
34
 
47
35
  class Argument {
@@ -121,7 +109,7 @@ var require_argument = __commonJS((exports) => {
121
109
  });
122
110
 
123
111
  // ../../node_modules/commander/lib/help.js
124
- var require_help = __commonJS((exports) => {
112
+ var require_help = __commonJS(function(exports) {
125
113
  var { humanReadableArgName } = require_argument();
126
114
 
127
115
  class Help {
@@ -478,7 +466,7 @@ ${itemIndentStr}`);
478
466
  });
479
467
 
480
468
  // ../../node_modules/commander/lib/option.js
481
- var require_option = __commonJS((exports) => {
469
+ var require_option = __commonJS(function(exports) {
482
470
  var { InvalidArgumentError } = require_error();
483
471
 
484
472
  class Option {
@@ -662,7 +650,7 @@ var require_option = __commonJS((exports) => {
662
650
  });
663
651
 
664
652
  // ../../node_modules/commander/lib/suggestSimilar.js
665
- var require_suggestSimilar = __commonJS((exports) => {
653
+ var require_suggestSimilar = __commonJS(function(exports) {
666
654
  var maxDistance = 3;
667
655
  function editDistance(a, b) {
668
656
  if (Math.abs(a.length - b.length) > maxDistance)
@@ -735,11 +723,11 @@ var require_suggestSimilar = __commonJS((exports) => {
735
723
  });
736
724
 
737
725
  // ../../node_modules/commander/lib/command.js
738
- var require_command = __commonJS((exports) => {
726
+ var require_command = __commonJS(function(exports) {
739
727
  var EventEmitter = __require("node:events").EventEmitter;
740
728
  var childProcess = __require("node:child_process");
741
- var path = __require("node:path");
742
- var fs = __require("node:fs");
729
+ var path2 = __require("node:path");
730
+ var fs2 = __require("node:fs");
743
731
  var process2 = __require("node:process");
744
732
  var { Argument, humanReadableArgName } = require_argument();
745
733
  var { CommanderError } = require_error();
@@ -1274,7 +1262,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
1274
1262
  this.processedArgs = [];
1275
1263
  }
1276
1264
  _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
1277
- if (fs.existsSync(executableFile))
1265
+ if (fs2.existsSync(executableFile))
1278
1266
  return;
1279
1267
  const executableDirMessage = executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory";
1280
1268
  const executableMissing = `'${executableFile}' does not exist
@@ -1288,12 +1276,12 @@ Expecting one of '${allowedValues.join("', '")}'`);
1288
1276
  let launchWithNode = false;
1289
1277
  const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
1290
1278
  function findFile(baseDir, baseName) {
1291
- const localBin = path.resolve(baseDir, baseName);
1292
- if (fs.existsSync(localBin))
1279
+ const localBin = path2.resolve(baseDir, baseName);
1280
+ if (fs2.existsSync(localBin))
1293
1281
  return localBin;
1294
- if (sourceExt.includes(path.extname(baseName)))
1282
+ if (sourceExt.includes(path2.extname(baseName)))
1295
1283
  return;
1296
- const foundExt = sourceExt.find((ext) => fs.existsSync(`${localBin}${ext}`));
1284
+ const foundExt = sourceExt.find((ext) => fs2.existsSync(`${localBin}${ext}`));
1297
1285
  if (foundExt)
1298
1286
  return `${localBin}${foundExt}`;
1299
1287
  return;
@@ -1305,23 +1293,23 @@ Expecting one of '${allowedValues.join("', '")}'`);
1305
1293
  if (this._scriptPath) {
1306
1294
  let resolvedScriptPath;
1307
1295
  try {
1308
- resolvedScriptPath = fs.realpathSync(this._scriptPath);
1296
+ resolvedScriptPath = fs2.realpathSync(this._scriptPath);
1309
1297
  } catch {
1310
1298
  resolvedScriptPath = this._scriptPath;
1311
1299
  }
1312
- executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
1300
+ executableDir = path2.resolve(path2.dirname(resolvedScriptPath), executableDir);
1313
1301
  }
1314
1302
  if (executableDir) {
1315
1303
  let localFile = findFile(executableDir, executableFile);
1316
1304
  if (!localFile && !subcommand._executableFile && this._scriptPath) {
1317
- const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
1305
+ const legacyName = path2.basename(this._scriptPath, path2.extname(this._scriptPath));
1318
1306
  if (legacyName !== this._name) {
1319
1307
  localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
1320
1308
  }
1321
1309
  }
1322
1310
  executableFile = localFile || executableFile;
1323
1311
  }
1324
- launchWithNode = sourceExt.includes(path.extname(executableFile));
1312
+ launchWithNode = sourceExt.includes(path2.extname(executableFile));
1325
1313
  let proc;
1326
1314
  if (process2.platform !== "win32") {
1327
1315
  if (launchWithNode) {
@@ -1910,13 +1898,13 @@ Expecting one of '${allowedValues.join("', '")}'`);
1910
1898
  cmd.helpGroup(this._defaultCommandGroup);
1911
1899
  }
1912
1900
  nameFromFilename(filename) {
1913
- this._name = path.basename(filename, path.extname(filename));
1901
+ this._name = path2.basename(filename, path2.extname(filename));
1914
1902
  return this;
1915
1903
  }
1916
- executableDir(path2) {
1917
- if (path2 === undefined)
1904
+ executableDir(path3) {
1905
+ if (path3 === undefined)
1918
1906
  return this._executableDir;
1919
- this._executableDir = path2;
1907
+ this._executableDir = path3;
1920
1908
  return this;
1921
1909
  }
1922
1910
  helpInformation(contextOptions) {
@@ -2090,7 +2078,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
2090
2078
  });
2091
2079
 
2092
2080
  // ../../node_modules/commander/index.js
2093
- var require_commander = __commonJS((exports) => {
2081
+ var require_commander = __commonJS(function(exports) {
2094
2082
  var { Argument } = require_argument();
2095
2083
  var { Command } = require_command();
2096
2084
  var { CommanderError, InvalidArgumentError } = require_error();
@@ -2112,7 +2100,7 @@ var require_commander = __commonJS((exports) => {
2112
2100
  var package_default = {
2113
2101
  name: "@uipath/traces-tool",
2114
2102
  license: "MIT",
2115
- version: "1.201.0",
2103
+ version: "1.202.0-preview.136",
2116
2104
  description: "Query execution traces for UiPath jobs",
2117
2105
  private: false,
2118
2106
  publishConfig: {
@@ -2151,243 +2139,979 @@ var package_default = {
2151
2139
  }
2152
2140
  };
2153
2141
 
2154
- // ../common/src/catch-error.ts
2155
- function isPromiseLike(value) {
2156
- return value !== null && typeof value === "object" && typeof value.then === "function";
2157
- }
2158
- function catchError2(fnOrPromise) {
2159
- if (isPromiseLike(fnOrPromise)) {
2160
- return settlePromiseLike(fnOrPromise);
2142
+ // ../filesystem/src/node.ts
2143
+ import { randomUUID } from "node:crypto";
2144
+ import { existsSync } from "node:fs";
2145
+ import * as fs from "node:fs/promises";
2146
+ import * as os from "node:os";
2147
+ import * as path from "node:path";
2148
+ var LOCK_HEARTBEAT_MS = 5000;
2149
+ var LOCK_STALE_MS = 15000;
2150
+ var LOCK_MAX_WAIT_MS = 20000;
2151
+ var LOCK_MAX_HOLD_MS = 60000;
2152
+ var LOCK_RETRY_MIN_MS = 100;
2153
+ var LOCK_RETRY_JITTER_MS = 200;
2154
+
2155
+ class NodeFileSystem {
2156
+ path = {
2157
+ join: path.join,
2158
+ resolve: path.resolve,
2159
+ relative: path.relative,
2160
+ dirname: path.dirname,
2161
+ isAbsolute: path.isAbsolute,
2162
+ basename: path.basename
2163
+ };
2164
+ env = {
2165
+ cwd: process.cwd,
2166
+ homedir: os.homedir,
2167
+ tmpdir: os.tmpdir,
2168
+ getenv: (key) => process.env[key]
2169
+ };
2170
+ utils = {
2171
+ open: async (url) => {
2172
+ const { default: open } = await import("./index-sby22td6.js");
2173
+ await open(url);
2174
+ }
2175
+ };
2176
+ async readFile(path2, options) {
2177
+ try {
2178
+ if (options) {
2179
+ return await fs.readFile(path2, "utf-8");
2180
+ }
2181
+ return await fs.readFile(path2);
2182
+ } catch (error) {
2183
+ if (this.isEnoent(error))
2184
+ return null;
2185
+ throw error;
2186
+ }
2161
2187
  }
2162
- try {
2163
- const result = fnOrPromise();
2164
- if (isPromiseLike(result)) {
2165
- return settlePromiseLike(result);
2188
+ async writeFile(filePath, data) {
2189
+ const dir = path.dirname(filePath);
2190
+ if (dir) {
2191
+ await fs.mkdir(dir, { recursive: true });
2166
2192
  }
2167
- return [undefined, result];
2168
- } catch (error) {
2169
- return [
2170
- error instanceof Error ? error : new Error(String(error)),
2171
- undefined
2172
- ];
2193
+ await fs.writeFile(filePath, data);
2173
2194
  }
2174
- }
2175
- function settlePromiseLike(thenable) {
2176
- return Promise.resolve(thenable).then((data) => [undefined, data]).catch((error) => [
2177
- error instanceof Error ? error : new Error(String(error)),
2178
- undefined
2179
- ]);
2180
- }
2181
-
2182
- // ../common/src/error-handler.ts
2183
- var DEFAULT_401 = "Unauthorized (401). Run `uip login` to authenticate.";
2184
- var DEFAULT_403 = "Forbidden (403). Ensure the account has the required permissions.";
2185
- var DEFAULT_405 = "Method Not Allowed (405). The endpoint may not exist or the base URL may be incorrect.";
2186
- var DEFAULT_413 = "Payload too large (413). The upload exceeded the server or CDN size limit. Reduce the package size — for example, exclude unused dependencies or remove large files from the project — and try again.";
2187
- var HTML_RESPONSE_MESSAGE = "Received HTML instead of the expected JSON response.";
2188
- var NETWORK_ERROR_CODES = new Set([
2189
- "ECONNREFUSED",
2190
- "ECONNRESET",
2191
- "ENOTFOUND",
2192
- "EAI_AGAIN",
2193
- "ETIMEDOUT",
2194
- "EPIPE",
2195
- "EHOSTUNREACH",
2196
- "ENETUNREACH",
2197
- "EAI_FAIL"
2198
- ]);
2199
- var TLS_ERROR_CODES = new Set([
2200
- "SELF_SIGNED_CERT_IN_CHAIN",
2201
- "DEPTH_ZERO_SELF_SIGNED_CERT",
2202
- "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
2203
- "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
2204
- "UNABLE_TO_GET_ISSUER_CERT",
2205
- "CERT_HAS_EXPIRED",
2206
- "CERT_UNTRUSTED",
2207
- "ERR_TLS_CERT_ALTNAME_INVALID"
2208
- ]);
2209
- var TLS_INSTRUCTIONS = "The server's TLS certificate could not be verified. Most often a " + "corporate proxy/firewall re-signs HTTPS with a root CA that Node does " + "not trust — set NODE_EXTRA_CA_CERTS to that CA's PEM file (and HTTPS_PROXY " + "if you connect through a proxy). If the certificate is instead expired or " + "its hostname does not match, fix the endpoint URL or the system clock. " + "Then retry.";
2210
- var NETWORK_INSTRUCTIONS = "Could not reach the UiPath service. Check your network connection and " + "VPN, confirm any HTTP_PROXY/HTTPS_PROXY/NO_PROXY settings are correct, " + "then retry.";
2211
- var LOCAL_PERMISSION_ERROR_CODES = new Set(["EACCES", "EPERM", "EROFS"]);
2212
- var LOCAL_PERMISSION_MESSAGE_PATTERN = /\b(EACCES|EPERM|EROFS)\b/;
2213
- function localPermissionInstructions(code, path) {
2214
- const target = path !== undefined ? `'${path}'` : "a local file or resource";
2215
- if (code === "EROFS") {
2216
- return `The filesystem containing ${target} is read-only (EROFS), so the ` + "CLI could not write to it. This is a local environment problem, " + "not a UiPath service error — retrying will not help. Use a " + "writable location, or give this environment write access to the " + "path.";
2195
+ async appendFile(filePath, data) {
2196
+ const dir = path.dirname(filePath);
2197
+ if (dir) {
2198
+ await fs.mkdir(dir, { recursive: true });
2199
+ }
2200
+ await fs.appendFile(filePath, data);
2217
2201
  }
2218
- const remedy = process.platform === "win32" ? "Re-run from an elevated terminal, close any program holding " + "the file open, or grant your user access to the path." : "Grant this user (or the sandbox the command runs in) access " + "to the path, or run the command outside the sandbox.";
2219
- return `The operating system denied access to ${target} (${code}). This is ` + "a local permission problem, not a UiPath service error — retrying " + `without a permission change will not help. ${remedy}`;
2220
- }
2221
- function describeConnectivityError(error) {
2222
- for (const cur of walkErrorGraph(error)) {
2223
- const code = typeof cur.code === "string" ? cur.code : undefined;
2224
- const message = typeof cur.message === "string" ? cur.message : undefined;
2225
- if (code && TLS_ERROR_CODES.has(code)) {
2226
- return {
2227
- code,
2228
- kind: "tls",
2229
- message: message ?? code,
2230
- instructions: TLS_INSTRUCTIONS
2231
- };
2202
+ async readdir(dirPath) {
2203
+ try {
2204
+ return await fs.readdir(dirPath);
2205
+ } catch (error) {
2206
+ if (this.isEnoent(error))
2207
+ return [];
2208
+ throw error;
2232
2209
  }
2233
- if (code && NETWORK_ERROR_CODES.has(code)) {
2210
+ }
2211
+ async stat(filePath) {
2212
+ try {
2213
+ const stats = await fs.stat(filePath);
2234
2214
  return {
2235
- code,
2236
- kind: "network",
2237
- message: message ?? code,
2238
- instructions: NETWORK_INSTRUCTIONS
2215
+ isFile: () => stats.isFile(),
2216
+ isDirectory: () => stats.isDirectory(),
2217
+ size: stats.size,
2218
+ mtimeMs: stats.mtimeMs
2239
2219
  };
2220
+ } catch (error) {
2221
+ if (this.isEnoent(error))
2222
+ return null;
2223
+ throw error;
2240
2224
  }
2241
2225
  }
2242
- return;
2243
- }
2244
- function describePermissionError(error) {
2245
- for (const cur of walkErrorGraph(error)) {
2246
- const message = typeof cur.message === "string" ? cur.message : undefined;
2247
- const code = matchLocalPermissionCode(cur.code, message);
2248
- if (!code)
2249
- continue;
2250
- const path = localPermissionPath(cur.path, message);
2251
- return {
2252
- code,
2253
- message: message ?? code,
2254
- ...path !== undefined ? { path } : {},
2255
- instructions: localPermissionInstructions(code, path)
2256
- };
2257
- }
2258
- return;
2259
- }
2260
- function matchLocalPermissionCode(code, message) {
2261
- if (typeof code === "string" && LOCAL_PERMISSION_ERROR_CODES.has(code)) {
2262
- return code;
2263
- }
2264
- const match = message ? LOCAL_PERMISSION_MESSAGE_PATTERN.exec(message) : null;
2265
- return match ? match[1] : undefined;
2266
- }
2267
- function localPermissionPath(path, message) {
2268
- if (typeof path === "string")
2269
- return path;
2270
- return message ? /'([^']+)'/.exec(message)?.[1] : undefined;
2271
- }
2272
- function* walkErrorGraph(error) {
2273
- const queue = [error];
2274
- const seen = new Set;
2275
- for (let steps = 0;queue.length > 0 && steps < 32; steps++) {
2276
- const current = queue.shift();
2277
- if (current === null || typeof current !== "object")
2278
- continue;
2279
- if (seen.has(current))
2280
- continue;
2281
- seen.add(current);
2282
- const cur = current;
2283
- yield cur;
2284
- if (cur.cause !== undefined)
2285
- queue.push(cur.cause);
2286
- if (Array.isArray(cur.errors))
2287
- queue.push(...cur.errors);
2288
- }
2289
- return;
2290
- }
2291
- function parseHttpStatusFromMessage(message) {
2292
- const match = /^HTTP\s+(\d{3})(?::|\s|-|$)/i.exec(message.trim());
2293
- if (!match)
2294
- return;
2295
- const status = Number(match[1]);
2296
- return Number.isInteger(status) && status >= 100 && status <= 599 ? status : undefined;
2297
- }
2298
- function isHtmlDocument(body) {
2299
- return /^\s*(<!doctype html|<html\b)/i.test(body);
2300
- }
2301
- function retryHintForRetryAfter(seconds) {
2302
- if (seconds <= 1) {
2303
- return "RetryAfter1Second";
2304
- }
2305
- if (seconds <= 10) {
2306
- return "RetryAfter10Seconds";
2307
- }
2308
- if (seconds <= 30) {
2309
- return "RetryAfter30Seconds";
2226
+ async exists(filePath) {
2227
+ return existsSync(filePath);
2310
2228
  }
2311
- return "RetryAfter60Seconds";
2312
- }
2313
- function classifyError(status, error) {
2314
- if (status === 400 || status === 409 || status === 422) {
2315
- return { errorCode: "invalid_argument", retry: "RetryWillNotFix" };
2229
+ async mkdir(dirPath) {
2230
+ await fs.mkdir(dirPath, { recursive: true });
2316
2231
  }
2317
- if (status === 401) {
2318
- return {
2319
- errorCode: "authentication_required",
2320
- retry: "RetryWillNotFix"
2232
+ async acquireLock(lockPath) {
2233
+ const canonicalPath = await this.canonicalizeLockTarget(lockPath);
2234
+ const lockFile = `${canonicalPath}.lock`;
2235
+ const ownerId = randomUUID();
2236
+ const start = Date.now();
2237
+ while (true) {
2238
+ try {
2239
+ await fs.writeFile(lockFile, ownerId, { flag: "wx" });
2240
+ return this.createLockRelease(lockFile, ownerId);
2241
+ } catch (error) {
2242
+ if (!this.hasErrnoCode(error, "EEXIST")) {
2243
+ throw error;
2244
+ }
2245
+ const stats = await fs.stat(lockFile).catch(() => null);
2246
+ if (stats && Date.now() - stats.mtimeMs > LOCK_STALE_MS) {
2247
+ const reclaimed = await fs.rm(lockFile, { force: true }).then(() => true).catch(() => false);
2248
+ if (reclaimed)
2249
+ continue;
2250
+ }
2251
+ if (Date.now() - start > LOCK_MAX_WAIT_MS) {
2252
+ throw new Error(`ELOCKED: timed out waiting for lock on ${canonicalPath}`);
2253
+ }
2254
+ await new Promise((resolve2) => setTimeout(resolve2, LOCK_RETRY_MIN_MS + Math.random() * LOCK_RETRY_JITTER_MS));
2255
+ }
2256
+ }
2257
+ }
2258
+ async canonicalizeLockTarget(lockPath) {
2259
+ const absolute = path.resolve(lockPath);
2260
+ const fullReal = await fs.realpath(absolute).catch(() => null);
2261
+ if (fullReal)
2262
+ return fullReal;
2263
+ const parent = path.dirname(absolute);
2264
+ const base = path.basename(absolute);
2265
+ const canonicalParent = await fs.realpath(parent).catch(() => parent);
2266
+ return path.join(canonicalParent, base);
2267
+ }
2268
+ createLockRelease(lockFile, ownerId) {
2269
+ const heartbeatStart = Date.now();
2270
+ let heartbeatTimer;
2271
+ let stopped = false;
2272
+ const stopHeartbeat = () => {
2273
+ stopped = true;
2274
+ if (heartbeatTimer)
2275
+ clearTimeout(heartbeatTimer);
2276
+ };
2277
+ const scheduleNextHeartbeat = () => {
2278
+ if (stopped)
2279
+ return;
2280
+ if (Date.now() - heartbeatStart >= LOCK_MAX_HOLD_MS) {
2281
+ stopped = true;
2282
+ return;
2283
+ }
2284
+ heartbeatTimer = setTimeout(() => {
2285
+ runHeartbeat();
2286
+ }, LOCK_HEARTBEAT_MS);
2287
+ heartbeatTimer.unref?.();
2288
+ };
2289
+ const runHeartbeat = async () => {
2290
+ if (stopped)
2291
+ return;
2292
+ const current = await fs.readFile(lockFile, "utf-8").catch(() => null);
2293
+ if (stopped)
2294
+ return;
2295
+ if (current !== ownerId) {
2296
+ stopped = true;
2297
+ return;
2298
+ }
2299
+ const now = Date.now() / 1000;
2300
+ await fs.utimes(lockFile, now, now).catch(() => {});
2301
+ scheduleNextHeartbeat();
2302
+ };
2303
+ scheduleNextHeartbeat();
2304
+ let released = false;
2305
+ return async () => {
2306
+ if (released)
2307
+ return;
2308
+ released = true;
2309
+ stopHeartbeat();
2310
+ const current = await fs.readFile(lockFile, "utf-8").catch(() => null);
2311
+ if (current === ownerId) {
2312
+ await fs.rm(lockFile, { force: true });
2313
+ }
2321
2314
  };
2322
2315
  }
2323
- if (status === 403) {
2324
- return { errorCode: "permission_denied", retry: "RetryWillNotFix" };
2325
- }
2326
- if (status === 404) {
2327
- return { errorCode: "not_found", retry: "RetryWillNotFix" };
2316
+ async rm(filePath) {
2317
+ await fs.rm(filePath, { recursive: true, force: true });
2328
2318
  }
2329
- if (status === 405) {
2330
- return { errorCode: "method_not_allowed", retry: "RetryWillNotFix" };
2319
+ async rename(oldPath, newPath) {
2320
+ await fs.rename(oldPath, newPath);
2331
2321
  }
2332
- if (status === 413) {
2333
- return { errorCode: "invalid_argument", retry: "RetryWillNotFix" };
2322
+ async realpath(filePath) {
2323
+ try {
2324
+ return await fs.realpath(filePath);
2325
+ } catch (error) {
2326
+ if (this.isEnoent(error))
2327
+ return filePath;
2328
+ throw error;
2329
+ }
2334
2330
  }
2335
- if (status === 408) {
2336
- return { errorCode: "timeout", retry: "RetryLater" };
2331
+ async getTempDir() {
2332
+ return await fs.mkdtemp(path.join(os.tmpdir(), "uipath-fs-"));
2333
+ }
2334
+ async copyDirectory(sourcePath, destPath) {
2335
+ const sourceStats = await this.stat(sourcePath);
2336
+ if (!sourceStats) {
2337
+ throw new Error(`Source directory does not exist: ${sourcePath}`);
2338
+ }
2339
+ if (!sourceStats.isDirectory()) {
2340
+ throw new Error(`Source path is not a directory: ${sourcePath}`);
2341
+ }
2342
+ await this.mkdir(destPath);
2343
+ const entries = await this.readdir(sourcePath);
2344
+ for (const entry of entries) {
2345
+ const srcEntry = path.join(sourcePath, entry);
2346
+ const destEntry = path.join(destPath, entry);
2347
+ const entryStats = await this.stat(srcEntry);
2348
+ if (!entryStats)
2349
+ continue;
2350
+ if (entryStats.isDirectory()) {
2351
+ await this.copyDirectory(srcEntry, destEntry);
2352
+ } else if (entryStats.isFile()) {
2353
+ const content = await this.readFile(srcEntry);
2354
+ if (content !== null) {
2355
+ await this.writeFile(destEntry, content);
2356
+ }
2357
+ }
2358
+ }
2337
2359
  }
2338
- if (status === 429) {
2339
- return { errorCode: "rate_limited", retry: "RetryLater" };
2360
+ isEnoent(error) {
2361
+ return this.hasErrnoCode(error, "ENOENT");
2340
2362
  }
2341
- if (status !== undefined && status >= 500 && status < 600) {
2342
- return { errorCode: "server_error", retry: "RetryLater" };
2363
+ hasErrnoCode(error, code) {
2364
+ return typeof error === "object" && error !== null && "code" in error && error.code === code;
2343
2365
  }
2344
- if (status === undefined && describePermissionError(error)) {
2345
- return {
2346
- errorCode: "local_permission_denied",
2347
- retry: "RetryWillNotFix"
2348
- };
2366
+ }
2367
+
2368
+ // ../filesystem/src/index.ts
2369
+ var fsInstance = new NodeFileSystem;
2370
+ var getFileSystem = () => fsInstance;
2371
+
2372
+ // ../common/src/telemetry/pseudonymize.ts
2373
+ var PSEUDONYM_DOMAIN = "uipath-cli/telemetry/pseudonym/v1:";
2374
+ var PSEUDONYM_HEX_LENGTH = 32;
2375
+ var SHA256_K = new Uint32Array([
2376
+ 1116352408,
2377
+ 1899447441,
2378
+ 3049323471,
2379
+ 3921009573,
2380
+ 961987163,
2381
+ 1508970993,
2382
+ 2453635748,
2383
+ 2870763221,
2384
+ 3624381080,
2385
+ 310598401,
2386
+ 607225278,
2387
+ 1426881987,
2388
+ 1925078388,
2389
+ 2162078206,
2390
+ 2614888103,
2391
+ 3248222580,
2392
+ 3835390401,
2393
+ 4022224774,
2394
+ 264347078,
2395
+ 604807628,
2396
+ 770255983,
2397
+ 1249150122,
2398
+ 1555081692,
2399
+ 1996064986,
2400
+ 2554220882,
2401
+ 2821834349,
2402
+ 2952996808,
2403
+ 3210313671,
2404
+ 3336571891,
2405
+ 3584528711,
2406
+ 113926993,
2407
+ 338241895,
2408
+ 666307205,
2409
+ 773529912,
2410
+ 1294757372,
2411
+ 1396182291,
2412
+ 1695183700,
2413
+ 1986661051,
2414
+ 2177026350,
2415
+ 2456956037,
2416
+ 2730485921,
2417
+ 2820302411,
2418
+ 3259730800,
2419
+ 3345764771,
2420
+ 3516065817,
2421
+ 3600352804,
2422
+ 4094571909,
2423
+ 275423344,
2424
+ 430227734,
2425
+ 506948616,
2426
+ 659060556,
2427
+ 883997877,
2428
+ 958139571,
2429
+ 1322822218,
2430
+ 1537002063,
2431
+ 1747873779,
2432
+ 1955562222,
2433
+ 2024104815,
2434
+ 2227730452,
2435
+ 2361852424,
2436
+ 2428436474,
2437
+ 2756734187,
2438
+ 3204031479,
2439
+ 3329325298
2440
+ ]);
2441
+ var SHA256_INITIAL_STATE = new Uint32Array([
2442
+ 1779033703,
2443
+ 3144134277,
2444
+ 1013904242,
2445
+ 2773480762,
2446
+ 1359893119,
2447
+ 2600822924,
2448
+ 528734635,
2449
+ 1541459225
2450
+ ]);
2451
+ function rotr(value, bits) {
2452
+ return (value >>> bits | value << 32 - bits) >>> 0;
2453
+ }
2454
+ function sha256Hex(input) {
2455
+ const bytes = new TextEncoder().encode(input);
2456
+ const paddedLength = bytes.length + 9 + 63 >> 6 << 6;
2457
+ const buffer = new Uint8Array(paddedLength);
2458
+ buffer.set(bytes);
2459
+ buffer[bytes.length] = 128;
2460
+ const view = new DataView(buffer.buffer);
2461
+ const bitLength = bytes.length * 8;
2462
+ view.setUint32(paddedLength - 8, Math.floor(bitLength / 4294967296));
2463
+ view.setUint32(paddedLength - 4, bitLength >>> 0);
2464
+ const state = SHA256_INITIAL_STATE.slice();
2465
+ const schedule = new Uint32Array(64);
2466
+ for (let offset = 0;offset < paddedLength; offset += 64) {
2467
+ for (let i = 0;i < 16; i++) {
2468
+ schedule[i] = view.getUint32(offset + i * 4);
2469
+ }
2470
+ for (let i = 16;i < 64; i++) {
2471
+ const x = schedule[i - 15];
2472
+ const y = schedule[i - 2];
2473
+ const s0 = (rotr(x, 7) ^ rotr(x, 18) ^ x >>> 3) >>> 0;
2474
+ const s1 = (rotr(y, 17) ^ rotr(y, 19) ^ y >>> 10) >>> 0;
2475
+ schedule[i] = schedule[i - 16] + s0 + schedule[i - 7] + s1 >>> 0;
2476
+ }
2477
+ let a = state[0];
2478
+ let b = state[1];
2479
+ let c = state[2];
2480
+ let d = state[3];
2481
+ let e = state[4];
2482
+ let f = state[5];
2483
+ let g = state[6];
2484
+ let h = state[7];
2485
+ for (let i = 0;i < 64; i++) {
2486
+ const s1 = (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) >>> 0;
2487
+ const ch = (e & f ^ ~e & g) >>> 0;
2488
+ const temp1 = h + s1 + ch + SHA256_K[i] + schedule[i] >>> 0;
2489
+ const s0 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) >>> 0;
2490
+ const maj = (a & b ^ a & c ^ b & c) >>> 0;
2491
+ const temp2 = s0 + maj >>> 0;
2492
+ h = g;
2493
+ g = f;
2494
+ f = e;
2495
+ e = d + temp1 >>> 0;
2496
+ d = c;
2497
+ c = b;
2498
+ b = a;
2499
+ a = temp1 + temp2 >>> 0;
2500
+ }
2501
+ state[0] = state[0] + a >>> 0;
2502
+ state[1] = state[1] + b >>> 0;
2503
+ state[2] = state[2] + c >>> 0;
2504
+ state[3] = state[3] + d >>> 0;
2505
+ state[4] = state[4] + e >>> 0;
2506
+ state[5] = state[5] + f >>> 0;
2507
+ state[6] = state[6] + g >>> 0;
2508
+ state[7] = state[7] + h >>> 0;
2349
2509
  }
2350
- const connectivity = describeConnectivityError(error);
2351
- if (connectivity) {
2352
- return {
2353
- errorCode: "network_error",
2354
- retry: connectivity.kind === "tls" ? "RetryWillNotFix" : "RetryLater"
2355
- };
2510
+ let hex = "";
2511
+ for (const word of state) {
2512
+ hex += word.toString(16).padStart(8, "0");
2356
2513
  }
2357
- return { errorCode: "unknown_error", retry: "RetryWillNotFix" };
2514
+ return hex;
2358
2515
  }
2359
- function formatHttpStatusMessage(status, rawMessage, extractedMessage, inferredStatus) {
2360
- if (extractedMessage) {
2361
- return `HTTP ${status}: ${extractedMessage}`;
2516
+ function resolveSha256Hex() {
2517
+ try {
2518
+ const nodeCrypto = __require("node:crypto");
2519
+ const createHash = nodeCrypto?.createHash;
2520
+ if (typeof createHash !== "function") {
2521
+ return sha256Hex;
2522
+ }
2523
+ const native = (input) => createHash("sha256").update(input, "utf8").digest("hex");
2524
+ return native("abc") === sha256Hex("abc") ? native : sha256Hex;
2525
+ } catch {
2526
+ return sha256Hex;
2362
2527
  }
2363
- return inferredStatus !== undefined ? rawMessage : `HTTP ${status}: ${rawMessage}`;
2364
2528
  }
2365
- async function extractErrorDetails(error, options) {
2366
- const err = error !== null && error !== undefined && typeof error === "object" ? error : {};
2367
- const response = err.response;
2368
- const rawMessage = typeof err.message === "string" ? err.message : "Unknown error";
2369
- const explicitStatus = err.status ?? response?.status;
2370
- const inferredStatus = explicitStatus === undefined ? parseHttpStatusFromMessage(rawMessage) : undefined;
2371
- const status = explicitStatus ?? inferredStatus;
2372
- const isSuccessfulResponse = status !== undefined && status >= 200 && status < 300;
2373
- let rawBody;
2374
- let extractedMessage;
2375
- let parsedBody;
2376
- const textFn = response?.text?.bind(response);
2377
- if (textFn) {
2378
- const [bodyError, body] = await catchError2((async () => textFn())());
2379
- if (!bodyError && body) {
2380
- rawBody = body;
2381
- const [parseError, parsed] = catchError2(() => JSON.parse(body));
2382
- if (!parseError && parsed && typeof parsed === "object") {
2383
- parsedBody = parsed;
2384
- if (parsedBody.errors && typeof parsedBody.errors === "object") {
2385
- for (const field of Object.values(parsedBody.errors)) {
2386
- if (Array.isArray(field) && field.length > 0) {
2387
- const first = field[0];
2388
- if (first && typeof first.message === "string") {
2389
- extractedMessage = first.message;
2390
- break;
2529
+ var cachedSha256Hex;
2530
+ function digest(input) {
2531
+ cachedSha256Hex ??= resolveSha256Hex();
2532
+ return cachedSha256Hex(input);
2533
+ }
2534
+ function pseudonymize(input) {
2535
+ return digest(`${PSEUDONYM_DOMAIN}${input}`).slice(0, PSEUDONYM_HEX_LENGTH);
2536
+ }
2537
+
2538
+ // ../common/src/singleton.ts
2539
+ var PREFIX = "@uipath/common/";
2540
+ var _g = globalThis;
2541
+ function singleton(ctorOrName) {
2542
+ const name = typeof ctorOrName === "string" ? ctorOrName : ctorOrName.name;
2543
+ const key = Symbol.for(PREFIX + name);
2544
+ return {
2545
+ get(fallback) {
2546
+ return _g[key] ?? fallback;
2547
+ },
2548
+ set(value) {
2549
+ _g[key] = value;
2550
+ },
2551
+ clear() {
2552
+ delete _g[key];
2553
+ },
2554
+ getOrInit(factory, guard) {
2555
+ const existing = _g[key];
2556
+ if (existing != null && typeof existing === "object") {
2557
+ if (!guard || guard(existing)) {
2558
+ return existing;
2559
+ }
2560
+ }
2561
+ const instance = factory();
2562
+ _g[key] = instance;
2563
+ return instance;
2564
+ }
2565
+ };
2566
+ }
2567
+
2568
+ // ../common/src/telemetry/supplied-values.ts
2569
+ var suppliedValuesSlot = singleton("TelemetrySuppliedArgumentValues");
2570
+ function activeEntries() {
2571
+ const existing = suppliedValuesSlot.get();
2572
+ return Array.isArray(existing) ? existing : [];
2573
+ }
2574
+ var MIN_SCRUBBABLE_LENGTH = 4;
2575
+ function recordSuppliedArgumentValues(values) {
2576
+ const flat = [];
2577
+ const push = (value) => {
2578
+ if (Array.isArray(value)) {
2579
+ for (const item of value) {
2580
+ push(item);
2581
+ }
2582
+ return;
2583
+ }
2584
+ if (typeof value === "string" && value.length >= MIN_SCRUBBABLE_LENGTH) {
2585
+ flat.push(value);
2586
+ }
2587
+ };
2588
+ push(values);
2589
+ const entry = { values: flat };
2590
+ suppliedValuesSlot.set([...activeEntries(), entry]);
2591
+ return entry;
2592
+ }
2593
+ function releaseSuppliedArgumentValues(entry) {
2594
+ suppliedValuesSlot.set(activeEntries().filter((held) => held !== entry));
2595
+ }
2596
+ function getSuppliedArgumentValues() {
2597
+ const all = new Set;
2598
+ for (const entry of activeEntries()) {
2599
+ for (const value of entry.values) {
2600
+ all.add(value);
2601
+ }
2602
+ }
2603
+ return [...all].sort((a, b) => b.length - a.length);
2604
+ }
2605
+
2606
+ // ../common/src/telemetry/pii-redactor.ts
2607
+ var REDACTED = "[REDACTED]";
2608
+ var MAX_VALUE_LENGTH = 280;
2609
+ var MAX_STACK_LENGTH = 4096;
2610
+ var MAX_SCAN_LENGTH = MAX_STACK_LENGTH;
2611
+ function truncate(value, maxLength) {
2612
+ return value.length > maxLength ? `${value.slice(0, maxLength)}…` : value;
2613
+ }
2614
+ var SENSITIVE_NAME_TOKENS = new Set([
2615
+ "token",
2616
+ "tokens",
2617
+ "secret",
2618
+ "secrets",
2619
+ "password",
2620
+ "passwords",
2621
+ "pwd",
2622
+ "credential",
2623
+ "credentials",
2624
+ "auth",
2625
+ "authentication",
2626
+ "authorization",
2627
+ "authority",
2628
+ "cert",
2629
+ "certificate",
2630
+ "certificates"
2631
+ ]);
2632
+ var SENSITIVE_KEY_PREFIXES = new Set([
2633
+ "api",
2634
+ "access",
2635
+ "client",
2636
+ "private",
2637
+ "public",
2638
+ "signing",
2639
+ "encryption",
2640
+ "session",
2641
+ "master",
2642
+ "shared",
2643
+ "root",
2644
+ "ssh",
2645
+ "rsa",
2646
+ "aes",
2647
+ "hmac",
2648
+ "oauth"
2649
+ ]);
2650
+ 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;
2651
+ var EMAIL_PATTERN = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g;
2652
+ var JWT_PATTERN = /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g;
2653
+ var LONG_TOKEN_PATTERN = /\b[A-Za-z0-9_-]{40,}\b/g;
2654
+ var PADDED_BASE64_PATTERN = /[A-Za-z0-9+/]{16,}={1,2}(?![A-Za-z0-9+/=])/g;
2655
+ var BASE64_WITH_PLUS_PATTERN = /[A-Za-z0-9+/]{40,}/g;
2656
+ var USER_HOME_PATTERN = /(?<![A-Za-z0-9._-])([/\\])(Users|home|Profiles)([/\\])([^/\\]+)/gi;
2657
+ var UNC_PATH_PATTERN = /(^|[\s"'<>|=,;([{])(\\\\[^\s"'<>|]+)/g;
2658
+ 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;
2659
+ var SOURCE_FILE_EXTENSIONS = new Set([
2660
+ "ts",
2661
+ "tsx",
2662
+ "js",
2663
+ "jsx",
2664
+ "mjs",
2665
+ "cjs",
2666
+ "cts",
2667
+ "mts",
2668
+ "py",
2669
+ "cs",
2670
+ "java",
2671
+ "go",
2672
+ "rs",
2673
+ "rb",
2674
+ "php",
2675
+ "sh",
2676
+ "ps1",
2677
+ "json",
2678
+ "jsonc",
2679
+ "yaml",
2680
+ "yml",
2681
+ "xml",
2682
+ "xaml",
2683
+ "md",
2684
+ "txt",
2685
+ "log",
2686
+ "css",
2687
+ "html",
2688
+ "htm",
2689
+ "csproj",
2690
+ "nuspec",
2691
+ "sql"
2692
+ ]);
2693
+ var URL_PATTERN = /\bhttps?:\/\/[^\s,;]+/gi;
2694
+ var QUOTED_LITERAL_MAX_SPAN = 200;
2695
+ var QUOTED_LITERAL_PATTERN = new RegExp([
2696
+ `(?<![A-Za-z0-9])'(?:[^\\
2697
+ ]|\\.){2,${QUOTED_LITERAL_MAX_SPAN}}?'(?![A-Za-z0-9])`,
2698
+ `(?<![A-Za-z0-9])"(?:[^\\
2699
+ ]|\\.){2,${QUOTED_LITERAL_MAX_SPAN}}?"(?![A-Za-z0-9])`
2700
+ ].join("|"), "g");
2701
+ var JSON_BODY_PATTERN = /[{[][^{}[\]]*[:,][^{}[\]]*[\]}]/g;
2702
+ var COLLAPSED_BODY = "{…}";
2703
+ var COLLAPSED_BODY_MARKER = "\x01body\x01";
2704
+ var MAX_BODY_NESTING = 8;
2705
+ function collapseJsonBodies(text) {
2706
+ let out = text;
2707
+ for (let pass = 0;pass < MAX_BODY_NESTING; pass++) {
2708
+ const next = out.replace(JSON_BODY_PATTERN, COLLAPSED_BODY_MARKER);
2709
+ if (next === out) {
2710
+ break;
2711
+ }
2712
+ out = next;
2713
+ }
2714
+ return out.split(COLLAPSED_BODY_MARKER).join(COLLAPSED_BODY);
2715
+ }
2716
+ var TRAILING_PROSE_PUNCT = /[.,;:!?)\]}>'"]+$/;
2717
+ function peelTrailingPunctuation(match) {
2718
+ const trailing = match.match(TRAILING_PROSE_PUNCT)?.[0] ?? "";
2719
+ return trailing ? [match.slice(0, -trailing.length), trailing] : [match, ""];
2720
+ }
2721
+ function redactUrl(raw) {
2722
+ try {
2723
+ const url = new URL(raw);
2724
+ return `${url.protocol}//${url.host}`;
2725
+ } catch {
2726
+ return `url#${pseudonymize(raw)}`;
2727
+ }
2728
+ }
2729
+ function redactValueDetectors(value, maxLength = MAX_VALUE_LENGTH) {
2730
+ let out = truncate(value, MAX_SCAN_LENGTH);
2731
+ out = out.replace(JWT_PATTERN, () => REDACTED);
2732
+ out = out.replace(URL_PATTERN, (match) => {
2733
+ const [core, trailing] = peelTrailingPunctuation(match);
2734
+ return `${redactUrl(core)}${trailing}`;
2735
+ });
2736
+ out = out.replace(USER_HOME_PATTERN, (_match, sep1, folder, sep2) => `${sep1}${folder}${sep2}<user>`);
2737
+ out = out.replace(UNC_PATH_PATTERN, (_match, before, path2) => {
2738
+ const [core, trailing] = peelTrailingPunctuation(path2);
2739
+ return `${before}unc#${pseudonymize(core)}${trailing}`;
2740
+ });
2741
+ out = out.replace(EMAIL_PATTERN, (match) => `email#${pseudonymize(match)}`);
2742
+ out = out.replace(UUID_PATTERN, (match) => `uuid#${pseudonymize(match)}`);
2743
+ out = out.replace(HOST_PORT_PATTERN, (match) => {
2744
+ const split = match.lastIndexOf(":");
2745
+ const host = match.slice(0, split);
2746
+ const extension = host.slice(host.lastIndexOf(".") + 1).toLowerCase();
2747
+ if (SOURCE_FILE_EXTENSIONS.has(extension)) {
2748
+ return match;
2749
+ }
2750
+ return `host#${pseudonymize(host)}:${match.slice(split + 1)}`;
2751
+ });
2752
+ out = out.replace(PADDED_BASE64_PATTERN, () => REDACTED);
2753
+ out = out.replace(BASE64_WITH_PLUS_PATTERN, (match) => match.includes("+") ? REDACTED : match);
2754
+ out = out.replace(LONG_TOKEN_PATTERN, () => REDACTED);
2755
+ return truncate(out, maxLength);
2756
+ }
2757
+ function redactSpanName(name) {
2758
+ return redactValueDetectors(truncate(name, MAX_SCAN_LENGTH).replace(QUOTED_LITERAL_PATTERN, (match) => `${match[0]}<redacted>${match[0]}`));
2759
+ }
2760
+ var HTTP_DEPENDENCY_NAME = /^([A-Z]+) (\/.*)$/s;
2761
+ function redactHttpDependencyName(name) {
2762
+ const parts = HTTP_DEPENDENCY_NAME.exec(name);
2763
+ if (!parts) {
2764
+ return redactMessage(name);
2765
+ }
2766
+ return `${parts[1]} ${redactMessage(parts[2])}`;
2767
+ }
2768
+ function redactMessage(value) {
2769
+ let out = collapseJsonBodies(truncate(value, MAX_SCAN_LENGTH)).replace(QUOTED_LITERAL_PATTERN, (match) => `${match[0]}<redacted>${match[0]}`);
2770
+ for (const supplied of getSuppliedArgumentValues()) {
2771
+ out = out.split(supplied).join(REDACTED);
2772
+ }
2773
+ return redactValueDetectors(out);
2774
+ }
2775
+ var MESSAGE_NAMES = new Set([
2776
+ "message",
2777
+ "errormessage",
2778
+ "errmessage",
2779
+ "error_message",
2780
+ "msg",
2781
+ "detail",
2782
+ "details",
2783
+ "reason",
2784
+ "instructions",
2785
+ "warning"
2786
+ ]);
2787
+ function isFreeFormValue(name, value) {
2788
+ return MESSAGE_NAMES.has(name.toLowerCase()) || /['"{[]/.test(value);
2789
+ }
2790
+ function redactError(error) {
2791
+ const safe = new Error(redactMessage(error.message ?? ""));
2792
+ safe.name = error.name;
2793
+ safe.stack = typeof error.stack === "string" ? redactStack(error.stack) : undefined;
2794
+ return safe;
2795
+ }
2796
+ function redactStack(stack) {
2797
+ const bounded = truncate(stack, MAX_STACK_LENGTH);
2798
+ const firstBreak = bounded.indexOf(`
2799
+ `);
2800
+ if (firstBreak === -1) {
2801
+ return redactMessage(bounded);
2802
+ }
2803
+ return `${redactMessage(bounded.slice(0, firstBreak))}
2804
+ ${redactValueDetectors(bounded.slice(firstBreak + 1), MAX_STACK_LENGTH)}`;
2805
+ }
2806
+ function nameTokens(name) {
2807
+ 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);
2808
+ }
2809
+ function isSensitiveName(name) {
2810
+ const tokens = nameTokens(name);
2811
+ for (let i = 0;i < tokens.length; i++) {
2812
+ const token = tokens[i];
2813
+ if (SENSITIVE_NAME_TOKENS.has(token)) {
2814
+ return true;
2815
+ }
2816
+ if (token === "key" || token === "keys") {
2817
+ const prev = tokens[i - 1];
2818
+ if (prev && SENSITIVE_KEY_PREFIXES.has(prev)) {
2819
+ return true;
2820
+ }
2821
+ }
2822
+ }
2823
+ return false;
2824
+ }
2825
+ function redactProperty(name, value) {
2826
+ if (value === undefined || value === null) {
2827
+ return;
2828
+ }
2829
+ if (isSensitiveName(name)) {
2830
+ return REDACTED;
2831
+ }
2832
+ if (typeof value === "boolean" || typeof value === "number") {
2833
+ return value;
2834
+ }
2835
+ if (typeof value !== "string") {
2836
+ return "[OBJECT]";
2837
+ }
2838
+ return isFreeFormValue(name, value) ? redactMessage(value) : redactValueDetectors(value);
2839
+ }
2840
+ function redactProperties(properties) {
2841
+ const out = {};
2842
+ for (const [name, value] of Object.entries(properties)) {
2843
+ const redacted = redactProperty(name, value);
2844
+ if (redacted !== undefined) {
2845
+ out[name] = redacted;
2846
+ }
2847
+ }
2848
+ return out;
2849
+ }
2850
+
2851
+ // ../common/src/catch-error.ts
2852
+ var MAX_SERIALIZED_LENGTH = 500;
2853
+ var TRUNCATION_SUFFIX = "…(truncated)";
2854
+ var REDACTED2 = "[REDACTED]";
2855
+ function cap(text) {
2856
+ return text.length > MAX_SERIALIZED_LENGTH ? `${text.slice(0, MAX_SERIALIZED_LENGTH)}${TRUNCATION_SUFFIX}` : text;
2857
+ }
2858
+ function omitSensitive(key, value) {
2859
+ return key.length > 0 && isSensitiveName(key) ? REDACTED2 : value;
2860
+ }
2861
+ function describeThrownValue(value) {
2862
+ if (typeof value !== "object" || value === null) {
2863
+ return String(value);
2864
+ }
2865
+ let message;
2866
+ try {
2867
+ message = value.message;
2868
+ } catch {
2869
+ message = undefined;
2870
+ }
2871
+ if (typeof message === "string" && message.length > 0) {
2872
+ return cap(message);
2873
+ }
2874
+ try {
2875
+ const json = JSON.stringify(value, omitSensitive);
2876
+ if (json !== undefined) {
2877
+ return cap(json);
2878
+ }
2879
+ } catch {}
2880
+ return String(value);
2881
+ }
2882
+ function toError(error) {
2883
+ return error instanceof Error ? error : new Error(describeThrownValue(error), { cause: error });
2884
+ }
2885
+ function isPromiseLike(value) {
2886
+ return value !== null && typeof value === "object" && typeof value.then === "function";
2887
+ }
2888
+ function catchError(fnOrPromise) {
2889
+ if (isPromiseLike(fnOrPromise)) {
2890
+ return settlePromiseLike(fnOrPromise);
2891
+ }
2892
+ try {
2893
+ const result = fnOrPromise();
2894
+ if (isPromiseLike(result)) {
2895
+ return settlePromiseLike(result);
2896
+ }
2897
+ return [undefined, result];
2898
+ } catch (error) {
2899
+ return [toError(error), undefined];
2900
+ }
2901
+ }
2902
+ function settlePromiseLike(thenable) {
2903
+ return Promise.resolve(thenable).then((data) => [undefined, data]).catch((error) => [toError(error), undefined]);
2904
+ }
2905
+
2906
+ // ../common/src/error-handler.ts
2907
+ var DEFAULT_401 = "Unauthorized (401). Run `uip login` to authenticate.";
2908
+ var DEFAULT_403 = "Forbidden (403). Ensure the account has the required permissions.";
2909
+ var DEFAULT_405 = "Method Not Allowed (405). The endpoint may not exist or the base URL may be incorrect.";
2910
+ var DEFAULT_413 = "Payload too large (413). The upload exceeded the server or CDN size limit. Reduce the package size — for example, exclude unused dependencies or remove large files from the project — and try again.";
2911
+ var HTML_RESPONSE_MESSAGE = "Received HTML instead of the expected JSON response.";
2912
+ var NETWORK_ERROR_CODES = new Set([
2913
+ "ECONNREFUSED",
2914
+ "ECONNRESET",
2915
+ "ENOTFOUND",
2916
+ "EAI_AGAIN",
2917
+ "ETIMEDOUT",
2918
+ "EPIPE",
2919
+ "EHOSTUNREACH",
2920
+ "ENETUNREACH",
2921
+ "EAI_FAIL"
2922
+ ]);
2923
+ var TLS_ERROR_CODES = new Set([
2924
+ "SELF_SIGNED_CERT_IN_CHAIN",
2925
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
2926
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
2927
+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
2928
+ "UNABLE_TO_GET_ISSUER_CERT",
2929
+ "CERT_HAS_EXPIRED",
2930
+ "CERT_UNTRUSTED",
2931
+ "ERR_TLS_CERT_ALTNAME_INVALID"
2932
+ ]);
2933
+ var TLS_INSTRUCTIONS = "The server's TLS certificate could not be verified. Most often a " + "corporate proxy/firewall re-signs HTTPS with a root CA that Node does " + "not trust — set NODE_EXTRA_CA_CERTS to that CA's PEM file (and HTTPS_PROXY " + "if you connect through a proxy). If the certificate is instead expired or " + "its hostname does not match, fix the endpoint URL or the system clock. " + "Then retry.";
2934
+ var NETWORK_INSTRUCTIONS = "Could not reach the UiPath service. Check your network connection and " + "VPN, confirm any HTTP_PROXY/HTTPS_PROXY/NO_PROXY settings are correct, " + "then retry.";
2935
+ var LOCAL_PERMISSION_ERROR_CODES = new Set(["EACCES", "EPERM", "EROFS"]);
2936
+ var LOCAL_PERMISSION_MESSAGE_PATTERN = /\b(EACCES|EPERM|EROFS)\b/;
2937
+ function localPermissionInstructions(code, path2) {
2938
+ const target = path2 !== undefined ? `'${path2}'` : "a local file or resource";
2939
+ if (code === "EROFS") {
2940
+ return `The filesystem containing ${target} is read-only (EROFS), so the ` + "CLI could not write to it. This is a local environment problem, " + "not a UiPath service error — retrying will not help. Use a " + "writable location, or give this environment write access to the " + "path.";
2941
+ }
2942
+ const remedy = process.platform === "win32" ? "Re-run from an elevated terminal, close any program holding " + "the file open, or grant your user access to the path." : "Grant this user (or the sandbox the command runs in) access " + "to the path, or run the command outside the sandbox.";
2943
+ return `The operating system denied access to ${target} (${code}). This is ` + "a local permission problem, not a UiPath service error — retrying " + `without a permission change will not help. ${remedy}`;
2944
+ }
2945
+ function describeConnectivityError(error) {
2946
+ for (const cur of walkErrorGraph(error)) {
2947
+ const code = typeof cur.code === "string" ? cur.code : undefined;
2948
+ const message = typeof cur.message === "string" ? cur.message : undefined;
2949
+ if (code && TLS_ERROR_CODES.has(code)) {
2950
+ return {
2951
+ code,
2952
+ kind: "tls",
2953
+ message: message ?? code,
2954
+ instructions: TLS_INSTRUCTIONS
2955
+ };
2956
+ }
2957
+ if (code && NETWORK_ERROR_CODES.has(code)) {
2958
+ return {
2959
+ code,
2960
+ kind: "network",
2961
+ message: message ?? code,
2962
+ instructions: NETWORK_INSTRUCTIONS
2963
+ };
2964
+ }
2965
+ }
2966
+ return;
2967
+ }
2968
+ function describePermissionError(error) {
2969
+ for (const cur of walkErrorGraph(error)) {
2970
+ const message = typeof cur.message === "string" ? cur.message : undefined;
2971
+ const code = matchLocalPermissionCode(cur.code, message);
2972
+ if (!code)
2973
+ continue;
2974
+ const path2 = localPermissionPath(cur.path, message);
2975
+ return {
2976
+ code,
2977
+ message: message ?? code,
2978
+ ...path2 !== undefined ? { path: path2 } : {},
2979
+ instructions: localPermissionInstructions(code, path2)
2980
+ };
2981
+ }
2982
+ return;
2983
+ }
2984
+ function matchLocalPermissionCode(code, message) {
2985
+ if (typeof code === "string" && LOCAL_PERMISSION_ERROR_CODES.has(code)) {
2986
+ return code;
2987
+ }
2988
+ const match = message ? LOCAL_PERMISSION_MESSAGE_PATTERN.exec(message) : null;
2989
+ return match ? match[1] : undefined;
2990
+ }
2991
+ function localPermissionPath(path2, message) {
2992
+ if (typeof path2 === "string")
2993
+ return path2;
2994
+ return message ? /'([^']+)'/.exec(message)?.[1] : undefined;
2995
+ }
2996
+ function* walkErrorGraph(error) {
2997
+ const queue = [error];
2998
+ const seen = new Set;
2999
+ for (let steps = 0;queue.length > 0 && steps < 32; steps++) {
3000
+ const current = queue.shift();
3001
+ if (current === null || typeof current !== "object")
3002
+ continue;
3003
+ if (seen.has(current))
3004
+ continue;
3005
+ seen.add(current);
3006
+ const cur = current;
3007
+ yield cur;
3008
+ if (cur.cause !== undefined)
3009
+ queue.push(cur.cause);
3010
+ if (Array.isArray(cur.errors))
3011
+ queue.push(...cur.errors);
3012
+ }
3013
+ return;
3014
+ }
3015
+ function parseHttpStatusFromMessage(message) {
3016
+ const match = /^HTTP\s+(\d{3})(?::|\s|-|$)/i.exec(message.trim());
3017
+ if (!match)
3018
+ return;
3019
+ const status = Number(match[1]);
3020
+ return Number.isInteger(status) && status >= 100 && status <= 599 ? status : undefined;
3021
+ }
3022
+ function isHtmlDocument(body) {
3023
+ return /^\s*(<!doctype html|<html\b)/i.test(body);
3024
+ }
3025
+ function retryHintForRetryAfter(seconds) {
3026
+ if (seconds <= 1) {
3027
+ return "RetryAfter1Second";
3028
+ }
3029
+ if (seconds <= 10) {
3030
+ return "RetryAfter10Seconds";
3031
+ }
3032
+ if (seconds <= 30) {
3033
+ return "RetryAfter30Seconds";
3034
+ }
3035
+ return "RetryAfter60Seconds";
3036
+ }
3037
+ function classifyError(status, error) {
3038
+ if (status === 400 || status === 409 || status === 422) {
3039
+ return { errorCode: "invalid_argument", retry: "RetryWillNotFix" };
3040
+ }
3041
+ if (status === 401) {
3042
+ return {
3043
+ errorCode: "authentication_required",
3044
+ retry: "RetryWillNotFix"
3045
+ };
3046
+ }
3047
+ if (status === 403) {
3048
+ return { errorCode: "permission_denied", retry: "RetryWillNotFix" };
3049
+ }
3050
+ if (status === 404) {
3051
+ return { errorCode: "not_found", retry: "RetryWillNotFix" };
3052
+ }
3053
+ if (status === 405) {
3054
+ return { errorCode: "method_not_allowed", retry: "RetryWillNotFix" };
3055
+ }
3056
+ if (status === 413) {
3057
+ return { errorCode: "invalid_argument", retry: "RetryWillNotFix" };
3058
+ }
3059
+ if (status === 408) {
3060
+ return { errorCode: "timeout", retry: "RetryLater" };
3061
+ }
3062
+ if (status === 429) {
3063
+ return { errorCode: "rate_limited", retry: "RetryLater" };
3064
+ }
3065
+ if (status !== undefined && status >= 500 && status < 600) {
3066
+ return { errorCode: "server_error", retry: "RetryLater" };
3067
+ }
3068
+ if (status === undefined && describePermissionError(error)) {
3069
+ return {
3070
+ errorCode: "local_permission_denied",
3071
+ retry: "RetryWillNotFix"
3072
+ };
3073
+ }
3074
+ const connectivity = describeConnectivityError(error);
3075
+ if (connectivity) {
3076
+ return {
3077
+ errorCode: "network_error",
3078
+ retry: connectivity.kind === "tls" ? "RetryWillNotFix" : "RetryLater"
3079
+ };
3080
+ }
3081
+ return { errorCode: "unknown_error", retry: "RetryWillNotFix" };
3082
+ }
3083
+ function formatHttpStatusMessage(status, rawMessage, extractedMessage, inferredStatus) {
3084
+ if (extractedMessage) {
3085
+ return `HTTP ${status}: ${extractedMessage}`;
3086
+ }
3087
+ return inferredStatus !== undefined ? rawMessage : `HTTP ${status}: ${rawMessage}`;
3088
+ }
3089
+ async function extractErrorDetails(error, options) {
3090
+ const err = error !== null && error !== undefined && typeof error === "object" ? error : {};
3091
+ const response = err.response;
3092
+ const rawMessage = typeof err.message === "string" ? err.message : "Unknown error";
3093
+ const explicitStatus = err.status ?? response?.status;
3094
+ const inferredStatus = explicitStatus === undefined ? parseHttpStatusFromMessage(rawMessage) : undefined;
3095
+ const status = explicitStatus ?? inferredStatus;
3096
+ const isSuccessfulResponse = status !== undefined && status >= 200 && status < 300;
3097
+ let rawBody;
3098
+ let extractedMessage;
3099
+ let parsedBody;
3100
+ const textFn = response?.text?.bind(response);
3101
+ if (textFn) {
3102
+ const [bodyError, body] = await catchError((async () => textFn())());
3103
+ if (!bodyError && body) {
3104
+ rawBody = body;
3105
+ const [parseError, parsed] = catchError(() => JSON.parse(body));
3106
+ if (!parseError && parsed && typeof parsed === "object") {
3107
+ parsedBody = parsed;
3108
+ if (parsedBody.errors && typeof parsedBody.errors === "object") {
3109
+ for (const field of Object.values(parsedBody.errors)) {
3110
+ if (Array.isArray(field) && field.length > 0) {
3111
+ const first = field[0];
3112
+ if (first && typeof first.message === "string") {
3113
+ extractedMessage = first.message;
3114
+ break;
2391
3115
  }
2392
3116
  }
2393
3117
  }
@@ -2481,7 +3205,7 @@ async function extractErrorDetails(error, options) {
2481
3205
  } else if (typeof err.message === "string") {
2482
3206
  details = err.message;
2483
3207
  } else {
2484
- details = String(error);
3208
+ details = describeThrownValue(error);
2485
3209
  }
2486
3210
  const context = {};
2487
3211
  if (status) {
@@ -2512,118 +3236,59 @@ async function extractErrorDetails(error, options) {
2512
3236
  const headers = headersObj;
2513
3237
  retryAfterValue = headers["retry-after"] ?? headers["Retry-After"];
2514
3238
  }
2515
- if (retryAfterValue) {
2516
- const seconds = Number(retryAfterValue);
2517
- if (!Number.isNaN(seconds)) {
2518
- context.retryAfter = seconds;
2519
- retry = retryHintForRetryAfter(seconds);
2520
- }
2521
- }
2522
- }
2523
- const hasContext = Object.keys(context).length > 0;
2524
- let parsedErrors;
2525
- if (parsedBody?.errors && typeof parsedBody.errors === "object") {
2526
- const errors = {};
2527
- for (const [field, raw] of Object.entries(parsedBody.errors)) {
2528
- if (Array.isArray(raw)) {
2529
- const messages = raw.map((entry) => {
2530
- if (typeof entry === "string")
2531
- return entry;
2532
- if (entry && typeof entry === "object" && typeof entry.message === "string") {
2533
- return entry.message;
2534
- }
2535
- return String(entry);
2536
- }).filter(Boolean);
2537
- if (messages.length > 0)
2538
- errors[field] = messages;
2539
- } else if (typeof raw === "string") {
2540
- errors[field] = [raw];
2541
- }
2542
- }
2543
- if (Object.keys(errors).length > 0)
2544
- parsedErrors = errors;
2545
- }
2546
- return {
2547
- result,
2548
- errorCode: classification.errorCode,
2549
- message,
2550
- retry,
2551
- details,
2552
- ...hasContext ? { context } : {},
2553
- ...parsedErrors ? { parsedErrors } : {}
2554
- };
2555
- }
2556
- async function extractErrorMessage(error, options) {
2557
- const { message } = await extractErrorDetails(error, options);
2558
- return message;
2559
- }
2560
- // ../../node_modules/commander/esm.mjs
2561
- var import__ = __toESM(require_commander(), 1);
2562
- var {
2563
- program,
2564
- createCommand,
2565
- createArgument,
2566
- createOption,
2567
- CommanderError,
2568
- InvalidArgumentError,
2569
- InvalidOptionArgumentError,
2570
- Command,
2571
- Argument,
2572
- Option,
2573
- Help
2574
- } = import__.default;
2575
-
2576
- // ../common/src/command-examples.ts
2577
- var examplesByCommand = new WeakMap;
2578
- Command.prototype.examples = function(examples) {
2579
- examplesByCommand.set(this, examples);
2580
- return this;
2581
- };
2582
- // ../common/src/singleton.ts
2583
- var PREFIX = "@uipath/common/";
2584
- var _g = globalThis;
2585
- function singleton(ctorOrName) {
2586
- const name = typeof ctorOrName === "string" ? ctorOrName : ctorOrName.name;
2587
- const key = Symbol.for(PREFIX + name);
2588
- return {
2589
- get(fallback) {
2590
- return _g[key] ?? fallback;
2591
- },
2592
- set(value) {
2593
- _g[key] = value;
2594
- },
2595
- clear() {
2596
- delete _g[key];
2597
- },
2598
- getOrInit(factory, guard) {
2599
- const existing = _g[key];
2600
- if (existing != null && typeof existing === "object") {
2601
- if (!guard || guard(existing)) {
2602
- return existing;
2603
- }
3239
+ if (retryAfterValue) {
3240
+ const seconds = Number(retryAfterValue);
3241
+ if (!Number.isNaN(seconds)) {
3242
+ context.retryAfter = seconds;
3243
+ retry = retryHintForRetryAfter(seconds);
3244
+ }
3245
+ }
3246
+ }
3247
+ const hasContext = Object.keys(context).length > 0;
3248
+ let parsedErrors;
3249
+ if (parsedBody?.errors && typeof parsedBody.errors === "object") {
3250
+ const errors = {};
3251
+ for (const [field, raw] of Object.entries(parsedBody.errors)) {
3252
+ if (Array.isArray(raw)) {
3253
+ const messages = raw.map((entry) => {
3254
+ if (typeof entry === "string")
3255
+ return entry;
3256
+ if (entry && typeof entry === "object" && typeof entry.message === "string") {
3257
+ return entry.message;
3258
+ }
3259
+ return String(entry);
3260
+ }).filter(Boolean);
3261
+ if (messages.length > 0)
3262
+ errors[field] = messages;
3263
+ } else if (typeof raw === "string") {
3264
+ errors[field] = [raw];
2604
3265
  }
2605
- const instance = factory();
2606
- _g[key] = instance;
2607
- return instance;
2608
3266
  }
3267
+ if (Object.keys(errors).length > 0)
3268
+ parsedErrors = errors;
3269
+ }
3270
+ return {
3271
+ result,
3272
+ errorCode: classification.errorCode,
3273
+ message,
3274
+ retry,
3275
+ details,
3276
+ ...hasContext ? { context } : {},
3277
+ ...parsedErrors ? { parsedErrors } : {}
2609
3278
  };
2610
3279
  }
2611
-
2612
- // ../common/src/preview.ts
2613
- var previewSlot = singleton("PreviewBuild");
2614
- function isPreviewBuild() {
2615
- return previewSlot.get(false) ?? false;
3280
+ async function extractErrorMessage(error, options) {
3281
+ const { message } = await extractErrorDetails(error, options);
3282
+ return message;
3283
+ }
3284
+ // ../common/src/exit-code.ts
3285
+ function setExitCode(code) {
3286
+ process.exitCode = code;
2616
3287
  }
2617
- Command.prototype.previewCommand = function(nameAndArgs, opts) {
2618
- if (isPreviewBuild()) {
2619
- return this.command(nameAndArgs, opts);
2620
- }
2621
- return new Command(nameAndArgs.split(/\s+/)[0] ?? nameAndArgs);
2622
- };
2623
3288
 
2624
3289
  // ../common/src/output-context.ts
2625
3290
  function createStorage() {
2626
- const [error, mod] = catchError2(() => __require("node:async_hooks"));
3291
+ const [error, mod] = catchError(() => __require("node:async_hooks"));
2627
3292
  if (error || typeof mod?.AsyncLocalStorage !== "function") {
2628
3293
  return {
2629
3294
  getStore: () => {
@@ -2654,8 +3319,8 @@ function getOutputSink() {
2654
3319
 
2655
3320
  // ../common/src/logger.ts
2656
3321
  var logFilePathSlot = singleton("logFilePath");
2657
- function setGlobalLogFilePath(path) {
2658
- logFilePathSlot.set(path);
3322
+ function setGlobalLogFilePath(path2) {
3323
+ logFilePathSlot.set(path2);
2659
3324
  }
2660
3325
  function getGlobalLogFilePath() {
2661
3326
  return logFilePathSlot.get("");
@@ -2692,7 +3357,7 @@ class SimpleLogger {
2692
3357
  }
2693
3358
  return DEFAULT_LOG_LEVEL;
2694
3359
  }
2695
- const [localStorageError, hasDebug] = catchError2(() => typeof localStorage !== "undefined" && !!localStorage.getItem("debug"));
3360
+ const [localStorageError, hasDebug] = catchError(() => typeof localStorage !== "undefined" && !!localStorage.getItem("debug"));
2696
3361
  if (!localStorageError && hasDebug) {
2697
3362
  return 0 /* DEBUG */;
2698
3363
  }
@@ -2723,54 +3388,49 @@ class SimpleLogger {
2723
3388
  return this.fileLoggingEnabled || !!getGlobalLogFilePath();
2724
3389
  }
2725
3390
  writeToFile(formatted) {
2726
- const path = this.logFilePath || getGlobalLogFilePath();
2727
- if (!path)
3391
+ const path2 = this.logFilePath || getGlobalLogFilePath();
3392
+ if (!path2)
2728
3393
  return;
2729
3394
  const timestamp = new Date().toISOString();
2730
3395
  this.pendingWrites = Promise.all([
2731
3396
  this.pendingWrites,
2732
3397
  this.pendingInit
2733
- ]).then(() => getFileSystem().appendFile(path, `${timestamp} ${formatted}`).catch(() => {}));
3398
+ ]).then(() => getFileSystem().appendFile(path2, `${timestamp} ${formatted}`).catch(() => {}));
2734
3399
  }
2735
- debug(message, ...args) {
2736
- if (this.level > 0 /* DEBUG */)
2737
- return;
2738
- const formatted = this.format(`[DEBUG] ${message}`, args);
3400
+ write(formatted) {
2739
3401
  if (this.isFileLoggingActive()) {
2740
3402
  this.writeToFile(formatted);
2741
3403
  } else {
2742
3404
  getOutputSink().writeErr(formatted);
2743
3405
  }
2744
3406
  }
3407
+ debug(message, ...args) {
3408
+ if (this.level > 0 /* DEBUG */)
3409
+ return;
3410
+ const formatted = this.format(`[DEBUG] ${message}`, args);
3411
+ this.write(formatted);
3412
+ }
2745
3413
  info(message, ...args) {
2746
3414
  if (this.level > 1 /* INFO */)
2747
3415
  return;
2748
3416
  const formatted = this.format(message, args);
2749
- if (this.isFileLoggingActive()) {
2750
- this.writeToFile(formatted);
2751
- } else {
2752
- getOutputSink().writeErr(formatted);
2753
- }
3417
+ this.write(formatted);
2754
3418
  }
2755
3419
  warn(message, ...args) {
2756
3420
  if (this.level > 2 /* WARN */)
2757
3421
  return;
2758
3422
  const formatted = this.format(`[WARN] ${message}`, args);
2759
- if (this.isFileLoggingActive()) {
2760
- this.writeToFile(formatted);
2761
- } else {
2762
- getOutputSink().writeErr(formatted);
2763
- }
3423
+ this.write(formatted);
2764
3424
  }
2765
3425
  error(message, ...args) {
2766
3426
  if (this.level > 3 /* ERROR */)
2767
3427
  return;
2768
3428
  const formatted = this.format(`[ERROR] ${message}`, args);
2769
- if (this.isFileLoggingActive()) {
2770
- this.writeToFile(formatted);
2771
- } else {
2772
- getOutputSink().writeErr(formatted);
2773
- }
3429
+ this.write(formatted);
3430
+ }
3431
+ report(message) {
3432
+ const formatted = this.format(message, []);
3433
+ this.write(formatted);
2774
3434
  }
2775
3435
  getLevel() {
2776
3436
  return this.level;
@@ -2785,17 +3445,17 @@ class SimpleLogger {
2785
3445
  setGlobalLogFilePath("");
2786
3446
  }
2787
3447
  }
2788
- setLogFile(path) {
2789
- this.logFilePath = path;
2790
- setGlobalLogFilePath(path);
2791
- if (!path)
3448
+ setLogFile(path2) {
3449
+ this.logFilePath = path2;
3450
+ setGlobalLogFilePath(path2);
3451
+ if (!path2)
2792
3452
  return;
2793
3453
  this.fileLoggingEnabled = true;
2794
- const fs = getFileSystem();
3454
+ const fs2 = getFileSystem();
2795
3455
  this.pendingInit = (async () => {
2796
- const [error] = await catchError2((async () => {
2797
- await fs.mkdir(fs.path.dirname(path));
2798
- await fs.writeFile(path, "");
3456
+ const [error] = await catchError((async () => {
3457
+ await fs2.mkdir(fs2.path.dirname(path2));
3458
+ await fs2.writeFile(path2, "");
2799
3459
  })());
2800
3460
  if (error)
2801
3461
  this.fileLoggingEnabled = false;
@@ -2849,12 +3509,12 @@ var jmespathSlot = singleton("JmespathCodec");
2849
3509
  async function loadOutputCodecsAsync(needed) {
2850
3510
  const loads = [];
2851
3511
  if (needed.yaml && yamlSlot.get() === undefined) {
2852
- loads.push(import("./js-yaml-4ypbq2tt.js").then((mod) => {
3512
+ loads.push(import("./js-yaml-88tdqrtd.js").then((mod) => {
2853
3513
  yamlSlot.set(mod);
2854
3514
  }));
2855
3515
  }
2856
3516
  if (needed.filter && jmespathSlot.get() === undefined) {
2857
- loads.push(import("./index-2fj08e7n.js").then((mod) => {
3517
+ loads.push(import("./index-gpd94m28.js").then((mod) => {
2858
3518
  jmespathSlot.set(mod);
2859
3519
  }));
2860
3520
  }
@@ -3109,7 +3769,7 @@ function readRegistryValue(keyPath, valueName) {
3109
3769
  if (process.platform !== "win32") {
3110
3770
  return "";
3111
3771
  }
3112
- const [error, output] = catchError2(() => execFileSync("reg", ["query", keyPath, "/v", valueName], {
3772
+ const [error, output] = catchError(() => execFileSync("reg", ["query", keyPath, "/v", valueName], {
3113
3773
  encoding: "utf-8",
3114
3774
  stdio: ["pipe", "pipe", "pipe"]
3115
3775
  }));
@@ -3132,27 +3792,41 @@ class LoggerTelemetryProvider {
3132
3792
  ...this.analyticsUniqueId ? { analyticsUniqueId: this.analyticsUniqueId } : {}
3133
3793
  };
3134
3794
  }
3135
- async trackEvent(eventName, properties) {
3136
- logger.debug(formatMessage("Event", eventName, this.enrich(properties)));
3795
+ async trackEvent({ name, properties }) {
3796
+ logger.debug(formatMessage("Event", name, this.enrich(properties)));
3137
3797
  }
3138
- async trackException(error, properties) {
3798
+ async trackException({
3799
+ error,
3800
+ properties
3801
+ }) {
3139
3802
  logger.error(formatMessage("Exception", error.message, this.enrich({
3140
3803
  ...properties,
3141
3804
  stack: error.stack
3142
3805
  })));
3143
3806
  }
3144
- async trackRequest(name, duration, success, properties) {
3807
+ async trackRequest({
3808
+ name,
3809
+ durationMs,
3810
+ success,
3811
+ properties
3812
+ }) {
3145
3813
  logger.debug(formatMessage("Request", name, this.enrich({
3146
3814
  ...properties,
3147
- duration: `${duration}ms`,
3815
+ duration: `${durationMs}ms`,
3148
3816
  success
3149
3817
  })));
3150
3818
  }
3151
- async trackDependency(name, type, duration, success, properties) {
3819
+ async trackDependency({
3820
+ name,
3821
+ type,
3822
+ durationMs,
3823
+ success,
3824
+ properties
3825
+ }) {
3152
3826
  logger.debug(formatMessage("Dependency", name, this.enrich({
3153
3827
  ...properties,
3154
3828
  type,
3155
- duration: `${duration}ms`,
3829
+ duration: `${durationMs}ms`,
3156
3830
  success
3157
3831
  })));
3158
3832
  }
@@ -3408,144 +4082,16 @@ function getGlobalTelemetryProperties() {
3408
4082
  return telemetryPropsSlot.get();
3409
4083
  }
3410
4084
 
3411
- // ../common/src/telemetry/pii-redactor.ts
3412
- var REDACTED = "[REDACTED]";
3413
- var MAX_VALUE_LENGTH = 200;
3414
- var SENSITIVE_NAME_TOKENS = new Set([
3415
- "token",
3416
- "tokens",
3417
- "secret",
3418
- "secrets",
3419
- "password",
3420
- "passwords",
3421
- "pwd",
3422
- "credential",
3423
- "credentials",
3424
- "auth",
3425
- "authentication",
3426
- "authorization",
3427
- "authority",
3428
- "cert",
3429
- "certificate",
3430
- "certificates"
3431
- ]);
3432
- var SENSITIVE_KEY_PREFIXES = new Set([
3433
- "api",
3434
- "access",
3435
- "client",
3436
- "private",
3437
- "public",
3438
- "signing",
3439
- "encryption",
3440
- "session",
3441
- "master",
3442
- "shared",
3443
- "root",
3444
- "ssh",
3445
- "rsa",
3446
- "aes",
3447
- "hmac",
3448
- "oauth"
3449
- ]);
3450
- 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;
3451
- var EMAIL_PATTERN = /\b[^\s@]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g;
3452
- var JWT_PATTERN = /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g;
3453
- var LONG_TOKEN_PATTERN = /\b[A-Za-z0-9_-]{40,}\b/g;
3454
- var USER_HOME_PATTERN = /([/\\])(Users|home)([/\\])([^/\\]+)/gi;
3455
- var URL_PATTERN = /\bhttps?:\/\/[^\s,;]+/gi;
3456
- var URL_TRAILING_PUNCT = /[.,;:!?)\]}>'"]+$/;
3457
- function shortHash(input) {
3458
- let hash = 2166136261;
3459
- for (let i = 0;i < input.length; i++) {
3460
- hash ^= input.charCodeAt(i);
3461
- hash = Math.imul(hash, 16777619);
3462
- }
3463
- return (hash >>> 0).toString(16).padStart(8, "0");
3464
- }
3465
- function redactUrl(raw) {
3466
- try {
3467
- const url = new URL(raw);
3468
- return `${url.protocol}//${url.host}`;
3469
- } catch {
3470
- return `url#${shortHash(raw)}`;
3471
- }
3472
- }
3473
- function redactValueDetectors(value) {
3474
- let out = value;
3475
- out = out.replace(JWT_PATTERN, () => REDACTED);
3476
- out = out.replace(URL_PATTERN, (match) => {
3477
- const trailing = match.match(URL_TRAILING_PUNCT)?.[0] ?? "";
3478
- const core = trailing ? match.slice(0, -trailing.length) : match;
3479
- return `${redactUrl(core)}${trailing}`;
3480
- });
3481
- out = out.replace(USER_HOME_PATTERN, (_match, sep1, folder, sep2) => `${sep1}${folder}${sep2}<user>`);
3482
- out = out.replace(EMAIL_PATTERN, (match) => `email#${shortHash(match)}`);
3483
- out = out.replace(UUID_PATTERN, (match) => `uuid#${shortHash(match)}`);
3484
- out = out.replace(LONG_TOKEN_PATTERN, () => REDACTED);
3485
- if (out.length > MAX_VALUE_LENGTH) {
3486
- out = `${out.slice(0, MAX_VALUE_LENGTH)}…`;
3487
- }
3488
- return out;
3489
- }
3490
- function redactValue(value) {
3491
- return redactValueDetectors(value);
3492
- }
3493
- function redactError(error) {
3494
- const safe = new Error(redactValueDetectors(error.message ?? ""));
3495
- safe.name = error.name;
3496
- safe.stack = typeof error.stack === "string" ? redactValueDetectors(error.stack) : undefined;
3497
- return safe;
3498
- }
3499
- function nameTokens(name) {
3500
- 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);
3501
- }
3502
- function isSensitiveName(name) {
3503
- const tokens = nameTokens(name);
3504
- for (let i = 0;i < tokens.length; i++) {
3505
- const token = tokens[i];
3506
- if (SENSITIVE_NAME_TOKENS.has(token)) {
3507
- return true;
3508
- }
3509
- if (token === "key" || token === "keys") {
3510
- const prev = tokens[i - 1];
3511
- if (prev && SENSITIVE_KEY_PREFIXES.has(prev)) {
3512
- return true;
3513
- }
3514
- }
3515
- }
3516
- return false;
3517
- }
3518
- function redactProperty(name, value) {
3519
- if (value === undefined || value === null) {
3520
- return;
3521
- }
3522
- if (isSensitiveName(name)) {
3523
- return REDACTED;
3524
- }
3525
- if (typeof value === "boolean" || typeof value === "number") {
3526
- return value;
3527
- }
3528
- if (typeof value !== "string") {
3529
- return "[OBJECT]";
3530
- }
3531
- return redactValueDetectors(value);
3532
- }
3533
- function redactProperties(properties) {
3534
- const out = {};
3535
- for (const [name, value] of Object.entries(properties)) {
3536
- const redacted = redactProperty(name, value);
3537
- if (redacted !== undefined) {
3538
- out[name] = redacted;
3539
- }
3540
- }
3541
- return out;
4085
+ // ../common/src/telemetry/span-clock.ts
4086
+ function startSpanClock() {
4087
+ const started = performance.now();
4088
+ return {
4089
+ startedAt: new Date(performance.timeOrigin + started),
4090
+ elapsedMs: () => performance.now() - started
4091
+ };
3542
4092
  }
3543
4093
 
3544
4094
  // ../common/src/telemetry/telemetry-service.ts
3545
- var TELEMETRY_OPERATION_ID_PROPERTY = "uip.trace.operation_id";
3546
- var TELEMETRY_PARENT_ID_PROPERTY = "uip.trace.parent_id";
3547
- var TELEMETRY_SPAN_ID_PROPERTY = "uip.trace.span_id";
3548
-
3549
4095
  class TelemetryService {
3550
4096
  telemetryProvider;
3551
4097
  contextStorage;
@@ -3565,36 +4111,39 @@ class TelemetryService {
3565
4111
  this.defaultProperties = properties === undefined ? undefined : { ...this.defaultProperties, ...properties };
3566
4112
  }
3567
4113
  trackEvent(name, properties) {
3568
- const context = this.getCurrentContext();
3569
- const enrichedProperties = this.enrichPropertiesWithContext(properties, context);
3570
- this.telemetryProvider.trackEvent(name, enrichedProperties);
4114
+ this.telemetryProvider.trackEvent({
4115
+ name: redactSpanName(name),
4116
+ properties: this.enrichProperties(properties),
4117
+ ...this.leafCorrelation()
4118
+ });
3571
4119
  }
3572
- trackException(error, properties) {
3573
- const context = this.getCurrentContext();
3574
- const enrichedProperties = this.enrichPropertiesWithContext(properties, context);
3575
- this.telemetryProvider.trackException(redactError(error), enrichedProperties);
4120
+ trackException(error, properties, context) {
4121
+ this.telemetryProvider.trackException({
4122
+ error: redactError(error),
4123
+ properties: this.enrichProperties(properties),
4124
+ ...this.leafCorrelation(context)
4125
+ });
3576
4126
  }
3577
4127
  async trackRequest(name, fn, properties) {
3578
- const parentContext = this.getCurrentContext();
4128
+ const parentContext = this.getActiveContext();
3579
4129
  const operationId = parentContext?.operationId ?? this.operationId ?? getTelemetryOperationId();
3580
4130
  const parentId = parentContext ? parentContext.id : this.inboundParentIdFor(operationId);
4131
+ const clock = startSpanClock();
3581
4132
  const context = {
3582
4133
  operationId,
3583
4134
  ...parentId !== undefined ? { parentId } : {},
3584
- id: this.generateId()
4135
+ id: this.generateId(),
4136
+ startedAt: clock.startedAt
3585
4137
  };
3586
- const startTime = performance.now();
3587
4138
  try {
3588
4139
  const result = await this.contextStorage.run(context, fn);
3589
- const durationMs = performance.now() - startTime;
3590
- const enrichedProperties = this.enrichPropertiesWithContext(properties, context);
3591
- await this.telemetryProvider.trackRequest(name, durationMs, true, enrichedProperties);
4140
+ const durationMs = clock.elapsedMs();
4141
+ await this.telemetryProvider.trackRequest(this.spanFor(name, durationMs, true, properties, context));
3592
4142
  return result;
3593
4143
  } catch (error) {
3594
- const durationMs = performance.now() - startTime;
4144
+ const durationMs = clock.elapsedMs();
3595
4145
  const err = error instanceof Error ? error : new Error(String(error));
3596
- const enrichedProperties = this.enrichPropertiesWithContext({ ...properties, errorMessage: err.message }, context);
3597
- await this.telemetryProvider.trackRequest(name, durationMs, false, enrichedProperties);
4146
+ await this.telemetryProvider.trackRequest(this.spanFor(name, durationMs, false, { ...properties, errorMessage: err.message }, context));
3598
4147
  throw error;
3599
4148
  }
3600
4149
  }
@@ -3603,8 +4152,7 @@ class TelemetryService {
3603
4152
  operationId: this.operationId ?? getTelemetryOperationId(),
3604
4153
  id: this.generateId()
3605
4154
  };
3606
- const enrichedProperties = this.enrichPropertiesWithContext(properties, requestContext);
3607
- this.telemetryProvider.trackRequest(name, durationMs, success, enrichedProperties);
4155
+ this.telemetryProvider.trackRequest(this.spanFor(name, durationMs, success, properties, requestContext));
3608
4156
  }
3609
4157
  createRequestContext() {
3610
4158
  const operationId = this.operationId ?? getTelemetryOperationId();
@@ -3612,7 +4160,8 @@ class TelemetryService {
3612
4160
  return {
3613
4161
  operationId,
3614
4162
  ...parentId !== undefined ? { parentId } : {},
3615
- id: this.generateId()
4163
+ id: this.generateId(),
4164
+ startedAt: startSpanClock().startedAt
3616
4165
  };
3617
4166
  }
3618
4167
  inboundParentIdFor(operationId) {
@@ -3623,73 +4172,174 @@ class TelemetryService {
3623
4172
  return this.contextStorage.run(context, fn);
3624
4173
  }
3625
4174
  createDependencyContext() {
3626
- const parentContext = this.getCurrentContext();
4175
+ const parentContext = this.getActiveContext();
3627
4176
  if (!parentContext) {
3628
4177
  return;
3629
4178
  }
3630
4179
  return {
3631
4180
  operationId: parentContext.operationId,
3632
4181
  parentId: parentContext.id,
3633
- id: this.generateId()
4182
+ id: this.generateId(),
4183
+ startedAt: startSpanClock().startedAt
3634
4184
  };
3635
4185
  }
3636
4186
  trackDependencyResult(name, type, durationMs, success, properties, context, resultCode) {
3637
- const enrichedProperties = this.enrichPropertiesWithContext(properties, context);
3638
- this.telemetryProvider.trackDependency(redactValue(name), type, durationMs, success, enrichedProperties, resultCode);
4187
+ this.telemetryProvider.trackDependency({
4188
+ ...this.spanFor(redactHttpDependencyName(name), durationMs, success, properties, context),
4189
+ type,
4190
+ ...resultCode !== undefined ? { resultCode } : {}
4191
+ });
3639
4192
  }
3640
4193
  async trackDependencyOperation(name, type, fn, properties) {
3641
- const parentContext = this.getCurrentContext();
4194
+ const clock = startSpanClock();
4195
+ const parentContext = this.getActiveContext();
3642
4196
  const childContext = parentContext !== undefined ? {
3643
4197
  operationId: parentContext.operationId,
3644
4198
  parentId: parentContext.id,
3645
- id: this.generateId()
3646
- } : this.createRequestContext();
3647
- const startTime = performance.now();
4199
+ id: this.generateId(),
4200
+ startedAt: clock.startedAt
4201
+ } : {
4202
+ ...this.createRequestContext(),
4203
+ startedAt: clock.startedAt
4204
+ };
3648
4205
  try {
3649
4206
  const result = await this.contextStorage.run(childContext, fn);
3650
- const durationMs = performance.now() - startTime;
3651
- const enrichedProperties = this.enrichPropertiesWithContext(properties, childContext);
3652
- await this.telemetryProvider.trackDependency(name, type, durationMs, true, enrichedProperties);
4207
+ const durationMs = clock.elapsedMs();
4208
+ await this.telemetryProvider.trackDependency({
4209
+ ...this.spanFor(name, durationMs, true, properties, childContext),
4210
+ type
4211
+ });
3653
4212
  return result;
3654
4213
  } catch (error) {
3655
- const durationMs = performance.now() - startTime;
4214
+ const durationMs = clock.elapsedMs();
3656
4215
  const err = error instanceof Error ? error : new Error(String(error));
3657
- const enrichedProperties = this.enrichPropertiesWithContext({ ...properties, errorMessage: err.message }, childContext);
3658
- await this.telemetryProvider.trackDependency(name, type, durationMs, false, enrichedProperties);
4216
+ await this.telemetryProvider.trackDependency({
4217
+ ...this.spanFor(name, durationMs, false, { ...properties, errorMessage: err.message }, childContext),
4218
+ type
4219
+ });
3659
4220
  throw error;
3660
4221
  }
3661
4222
  }
3662
- getCurrentContext() {
4223
+ getActiveContext() {
3663
4224
  return this.contextStorage.getContext();
3664
4225
  }
3665
- enrichPropertiesWithContext(properties, context) {
4226
+ leafCorrelation(explicit) {
4227
+ const context = explicit ?? this.getActiveContext();
4228
+ return {
4229
+ operationId: context?.operationId ?? this.operationId ?? getTelemetryOperationId(),
4230
+ ...context !== undefined ? { parentId: context.id } : {}
4231
+ };
4232
+ }
4233
+ spanFor(name, durationMs, success, properties, context) {
4234
+ return {
4235
+ name: redactSpanName(name),
4236
+ durationMs,
4237
+ success,
4238
+ properties: this.enrichProperties(properties),
4239
+ operationId: context.operationId,
4240
+ ...context.parentId !== undefined ? { parentId: context.parentId } : {},
4241
+ id: context.id,
4242
+ ...context.startedAt !== undefined ? { startedAt: context.startedAt } : {}
4243
+ };
4244
+ }
4245
+ enrichProperties(properties) {
3666
4246
  const globalProperties = getGlobalTelemetryProperties();
3667
4247
  const enriched = {
3668
4248
  ...getExecutionContextTelemetryProperties(),
3669
4249
  ...globalProperties,
3670
4250
  ...this.defaultProperties,
3671
4251
  ...redactProperties(properties ?? {}),
3672
- [TELEMETRY_SESSION_SOURCE_PROPERTY]: getTelemetrySessionSource(),
3673
- ...context ? {
3674
- [TELEMETRY_OPERATION_ID_PROPERTY]: context.operationId,
3675
- ...context.parentId !== undefined ? { [TELEMETRY_PARENT_ID_PROPERTY]: context.parentId } : {},
3676
- [TELEMETRY_SPAN_ID_PROPERTY]: context.id
3677
- } : {}
4252
+ [TELEMETRY_SESSION_SOURCE_PROPERTY]: getTelemetrySessionSource()
3678
4253
  };
3679
4254
  return enriched;
3680
4255
  }
3681
- generateId() {
3682
- const bytes = new Uint8Array(8);
3683
- let hex = "";
3684
- do {
3685
- crypto.getRandomValues(bytes);
3686
- hex = "";
3687
- for (const byte of bytes) {
3688
- hex += byte.toString(16).padStart(2, "0");
3689
- }
3690
- } while (/^0+$/.test(hex));
3691
- return hex;
4256
+ generateId() {
4257
+ const bytes = new Uint8Array(8);
4258
+ let hex = "";
4259
+ do {
4260
+ crypto.getRandomValues(bytes);
4261
+ hex = "";
4262
+ for (const byte of bytes) {
4263
+ hex += byte.toString(16).padStart(2, "0");
4264
+ }
4265
+ } while (/^0+$/.test(hex));
4266
+ return hex;
4267
+ }
4268
+ }
4269
+ // ../common/src/timings.ts
4270
+ var TIMINGS_ENV_VAR = "UIP_TIMINGS";
4271
+ function createStorage2() {
4272
+ const [error, mod] = catchError(() => __require("node:async_hooks"));
4273
+ if (error || typeof mod?.AsyncLocalStorage !== "function") {
4274
+ return {
4275
+ getStore: () => {
4276
+ return;
4277
+ },
4278
+ run: (_store, fn) => fn()
4279
+ };
4280
+ }
4281
+ return new mod.AsyncLocalStorage;
4282
+ }
4283
+ var storageSlot = singleton("TimingStorage");
4284
+ var stateSlot = singleton("Timings");
4285
+ var rootStartedSlot = singleton("TimingsRootStarted");
4286
+ var longLivedHostSlot = singleton("TimingsLongLivedHost");
4287
+ var storage = storageSlot.getOrInit(createStorage2, (value) => ("getStore" in value));
4288
+ function newState(baseline) {
4289
+ return { baseline, httpMs: 0, httpCalls: 0 };
4290
+ }
4291
+ function getState() {
4292
+ const scoped = storage.getStore();
4293
+ if (scoped) {
4294
+ return scoped;
4295
+ }
4296
+ const pinned = livePinnedState();
4297
+ if (pinned !== undefined) {
4298
+ return pinned;
4299
+ }
4300
+ return newState(processStartIsInvocationStart() ? 0 : performance.now());
4301
+ }
4302
+ function livePinnedState() {
4303
+ const pinned = stateSlot.get();
4304
+ return pinned !== undefined && "httpCalls" in pinned && !pinned.finished ? pinned : undefined;
4305
+ }
4306
+ function processStartIsInvocationStart() {
4307
+ return !rootStartedSlot.get(false) && !longLivedHostSlot.get(false);
4308
+ }
4309
+ function timingsEnabled() {
4310
+ if (typeof process === "undefined") {
4311
+ return false;
4312
+ }
4313
+ const value = process.env?.[TIMINGS_ENV_VAR];
4314
+ if (value === undefined) {
4315
+ return false;
4316
+ }
4317
+ const normalized = value.trim().toLowerCase();
4318
+ return normalized === "1" || normalized === "true";
4319
+ }
4320
+ function recordExitCode(exitCode) {
4321
+ if (!timingsEnabled()) {
4322
+ return;
4323
+ }
4324
+ getState().exitCode = exitCode;
4325
+ }
4326
+ function invocationStartedAt() {
4327
+ return new Date(performance.timeOrigin + getState().baseline);
4328
+ }
4329
+ function invocationElapsedMs() {
4330
+ return performance.now() - getState().baseline;
4331
+ }
4332
+ function markCommandStart() {
4333
+ if (!timingsEnabled()) {
4334
+ return;
4335
+ }
4336
+ getState().commandStart = performance.now();
4337
+ }
4338
+ function recordCommandDuration(durationMs) {
4339
+ if (!timingsEnabled()) {
4340
+ return;
3692
4341
  }
4342
+ getState().commandMs = durationMs;
3693
4343
  }
3694
4344
  // ../common/src/telemetry/proxy-http-agent.ts
3695
4345
  var slot = singleton("ProxyAuthHttpsAgent");
@@ -3711,6 +4361,9 @@ function getGlobalTelemetryInstance() {
3711
4361
  }
3712
4362
  return;
3713
4363
  }
4364
+ function setGlobalTelemetryInstance(instance) {
4365
+ telemetryInstanceSlot.set(instance);
4366
+ }
3714
4367
  var _localTelemetryInstance;
3715
4368
  function getTelemetryInstance() {
3716
4369
  const global = getGlobalTelemetryInstance();
@@ -3718,6 +4371,7 @@ function getTelemetryInstance() {
3718
4371
  return global;
3719
4372
  if (!_localTelemetryInstance) {
3720
4373
  _localTelemetryInstance = new TelemetryService(new LoggerTelemetryProvider, new NodeContextStorage);
4374
+ setGlobalTelemetryInstance(_localTelemetryInstance);
3721
4375
  }
3722
4376
  return _localTelemetryInstance;
3723
4377
  }
@@ -3730,6 +4384,14 @@ var telemetry = new Proxy({}, {
3730
4384
  });
3731
4385
 
3732
4386
  // ../common/src/formatter.ts
4387
+ var ANSI_STYLES = {
4388
+ red: "\x1B[31m",
4389
+ dim: "\x1B[2m"
4390
+ };
4391
+ var ANSI_RESET = "\x1B[0m";
4392
+ function styleLine(line, style) {
4393
+ return style ? `${ANSI_STYLES[style]}${line}${ANSI_RESET}` : line;
4394
+ }
3733
4395
  var CLI_ERROR_CODES = [
3734
4396
  "invalid_argument",
3735
4397
  "authentication_required",
@@ -3768,22 +4430,6 @@ var EXIT_CODES = {
3768
4430
  ValidationError: 3,
3769
4431
  TimeoutError: 4
3770
4432
  };
3771
- class SuccessOutput {
3772
- Result = RESULTS.Success;
3773
- Code;
3774
- Data;
3775
- Pagination;
3776
- Instructions;
3777
- Log;
3778
- constructor(code, data) {
3779
- this.Code = code;
3780
- this.Data = data;
3781
- const logPath = getLogFilePath();
3782
- if (logPath) {
3783
- this.Log = logPath;
3784
- }
3785
- }
3786
- }
3787
4433
  function escapeNonAscii(jsonText) {
3788
4434
  return jsonText.replace(/[\u0080-\uffff]/g, (c) => {
3789
4435
  const hex = c.charCodeAt(0).toString(16).padStart(4, "0");
@@ -3848,19 +4494,45 @@ function toPascalCaseKey(key) {
3848
4494
  const lowerCamelKey = toLowerCamelCaseKey(key);
3849
4495
  return lowerCamelKey ? lowerCamelKey.charAt(0).toUpperCase() + lowerCamelKey.slice(1) : lowerCamelKey;
3850
4496
  }
3851
- function toPascalCaseData(value) {
4497
+ function collectVerbatimRefs(value, into) {
4498
+ if (typeof value !== "object" || value === null)
4499
+ return;
4500
+ if (into.has(value))
4501
+ return;
4502
+ into.add(value);
4503
+ for (const nested of Array.isArray(value) ? value : Object.values(value)) {
4504
+ collectVerbatimRefs(nested, into);
4505
+ }
4506
+ }
4507
+ function toPascalCaseData(value, verbatimKeys, subtrees) {
4508
+ if (subtrees?.mode === "skip" && typeof value === "object" && value !== null && subtrees.refs.has(value)) {
4509
+ return value;
4510
+ }
3852
4511
  if (Array.isArray(value))
3853
- return value.map(toPascalCaseData);
4512
+ return value.map((entry) => toPascalCaseData(entry, verbatimKeys, subtrees));
3854
4513
  if (!isPlainRecord(value))
3855
4514
  return value;
3856
4515
  const result = {};
3857
4516
  for (const [key, nestedValue] of Object.entries(value)) {
3858
- result[toPascalCaseKey(key)] = toPascalCaseData(nestedValue);
4517
+ const pascalKey = toPascalCaseKey(key);
4518
+ if (verbatimKeys?.has(pascalKey)) {
4519
+ result[pascalKey] = nestedValue;
4520
+ if (subtrees?.mode === "collect") {
4521
+ collectVerbatimRefs(nestedValue, subtrees.refs);
4522
+ }
4523
+ continue;
4524
+ }
4525
+ result[pascalKey] = toPascalCaseData(nestedValue, verbatimKeys, subtrees);
3859
4526
  }
3860
4527
  return result;
3861
4528
  }
3862
- function normalizeDataKeys(data) {
3863
- return toPascalCaseData(data);
4529
+ function normalizeDataKeys(data, verbatimKeys, subtrees) {
4530
+ return toPascalCaseData(data, verbatimKeys, subtrees);
4531
+ }
4532
+ function toVerbatimKeySet(preserve) {
4533
+ if (!Array.isArray(preserve))
4534
+ return;
4535
+ return new Set(preserve.map(toPascalCaseKey));
3864
4536
  }
3865
4537
  function normalizeOutputKeys(data) {
3866
4538
  const result = {};
@@ -3870,7 +4542,7 @@ function normalizeOutputKeys(data) {
3870
4542
  }
3871
4543
  return result;
3872
4544
  }
3873
- function printOutput(data, format = "json", logFn, asciiSafe = false) {
4545
+ function printOutput(data, format = "json", logFn, asciiSafe = false, tableRowStyle) {
3874
4546
  if (!data) {
3875
4547
  logFn("Empty response object. No data to display.");
3876
4548
  return;
@@ -3905,7 +4577,7 @@ function printOutput(data, format = "json", logFn, asciiSafe = false) {
3905
4577
  if (hasData && !(rows !== null && rows.length === 0)) {
3906
4578
  const logValue = data.Log;
3907
4579
  if (rows !== null) {
3908
- printResizableTable(rows, logFn, logValue);
4580
+ printResizableTable(rows, logFn, logValue, undefined, tableRowStyle);
3909
4581
  } else {
3910
4582
  printVerticalTable(data.Data, logFn, logValue);
3911
4583
  }
@@ -3916,10 +4588,11 @@ function printOutput(data, format = "json", logFn, asciiSafe = false) {
3916
4588
  }
3917
4589
  }
3918
4590
  }
3919
- function logOutput(data, format = "json") {
4591
+ function logOutput(data, format = "json", tableRowStyle) {
3920
4592
  const sink = getOutputSink();
4593
+ const styleFn = sink.capabilities.isInteractive && sink.capabilities.supportsColor ? tableRowStyle : undefined;
3921
4594
  printOutput(data, format, (msg) => sink.writeOut(`${msg}
3922
- `), needsAsciiSafeJson(sink));
4595
+ `), needsAsciiSafeJson(sink), styleFn);
3923
4596
  }
3924
4597
  function cellToString(val) {
3925
4598
  return val != null && typeof val === "object" ? JSON.stringify(val) : String(val ?? "");
@@ -3933,7 +4606,7 @@ function wrapText(text, width) {
3933
4606
  }
3934
4607
  return lines;
3935
4608
  }
3936
- function printTable(data, logFn, externalLogValue) {
4609
+ function printTable(data, logFn, externalLogValue, tableRowStyle) {
3937
4610
  if (data.length === 0)
3938
4611
  return;
3939
4612
  const keys = Object.keys(data[0]).filter((key) => !["code", "log"].includes(key.toLowerCase()));
@@ -3943,7 +4616,7 @@ function printTable(data, logFn, externalLogValue) {
3943
4616
  logFn(keys.map((_, i) => "-".repeat(maxWidths[i])).join("-|-"));
3944
4617
  data.forEach((item) => {
3945
4618
  const row = keys.map((key, i) => cellToString(item[key]).padEnd(maxWidths[i])).join(" | ");
3946
- logFn(row);
4619
+ logFn(styleLine(row, tableRowStyle?.(item)));
3947
4620
  });
3948
4621
  if (externalLogValue) {
3949
4622
  logFn("");
@@ -3986,14 +4659,14 @@ function printVerticalTable(data, logFn = console.log, externalLogValue) {
3986
4659
  logFn(`Log: ${externalLogValue}`);
3987
4660
  }
3988
4661
  }
3989
- function printResizableTable(data, logFn = console.log, externalLogValue, availableWidth) {
4662
+ function printResizableTable(data, logFn = console.log, externalLogValue, availableWidth, tableRowStyle) {
3990
4663
  if (data.length === 0)
3991
4664
  return;
3992
4665
  const keys = Object.keys(data[0]).filter((key) => !["code", "log"].includes(key.toLowerCase()));
3993
4666
  if (keys.length === 0)
3994
4667
  return;
3995
4668
  if (!process.stdout.isTTY) {
3996
- printTable(data, logFn, externalLogValue);
4669
+ printTable(data, logFn, externalLogValue, tableRowStyle);
3997
4670
  return;
3998
4671
  }
3999
4672
  const naturalWidths = keys.map((key) => Math.max(key.length, ...data.map((item) => cellToString(item[key]).length)));
@@ -4001,7 +4674,7 @@ function printResizableTable(data, logFn = console.log, externalLogValue, availa
4001
4674
  const totalWidth = naturalWidths.reduce((a, b) => a + b, 0) + separatorTotal;
4002
4675
  const termWidth = availableWidth ?? (process.stdout.columns || 120);
4003
4676
  if (totalWidth <= termWidth) {
4004
- printTable(data, logFn, externalLogValue);
4677
+ printTable(data, logFn, externalLogValue, tableRowStyle);
4005
4678
  return;
4006
4679
  }
4007
4680
  const overflow = totalWidth - termWidth;
@@ -4047,6 +4720,7 @@ function printResizableTable(data, logFn = console.log, externalLogValue, availa
4047
4720
  logFn(header);
4048
4721
  logFn(keys.map((_, i) => "-".repeat(finalWidths[i])).join("-|-"));
4049
4722
  data.forEach((item) => {
4723
+ const style = tableRowStyle?.(item);
4050
4724
  const cellLines = keys.map((key, i) => wrapText(cellToString(item[key]), finalWidths[i]));
4051
4725
  const lineCount = Math.max(...cellLines.map((l) => l.length));
4052
4726
  for (let line = 0;line < lineCount; line++) {
@@ -4054,7 +4728,7 @@ function printResizableTable(data, logFn = console.log, externalLogValue, availa
4054
4728
  const val = line < cellLines[i].length ? cellLines[i][line] : "";
4055
4729
  return val.padEnd(finalWidths[i]);
4056
4730
  }).join(" | ");
4057
- logFn(row);
4731
+ logFn(styleLine(row, style));
4058
4732
  }
4059
4733
  });
4060
4734
  if (externalLogValue) {
@@ -4198,30 +4872,36 @@ var OutputFormatter;
4198
4872
  ((OutputFormatter) => {
4199
4873
  function success(data, options) {
4200
4874
  data.Log ??= getLogFilePath() || undefined;
4201
- const normalize = !options?.preserveDataKeys;
4875
+ const normalize = options?.preserveDataKeys !== true;
4876
+ const verbatim = toVerbatimKeySet(options?.preserveDataKeys);
4877
+ const subtrees = verbatim && {
4878
+ refs: new Set,
4879
+ mode: "collect"
4880
+ };
4202
4881
  if (normalize) {
4203
- data.Data = normalizeDataKeys(data.Data);
4882
+ data.Data = normalizeDataKeys(data.Data, verbatim, subtrees);
4204
4883
  }
4205
4884
  const filter = getOutputFilter();
4206
4885
  if (filter) {
4207
4886
  const filtered = applyFilter(data.Data, filter);
4208
- data.Data = normalize ? normalizeDataKeys(filtered) : filtered;
4887
+ data.Data = normalize ? normalizeDataKeys(filtered, verbatim, subtrees && { refs: subtrees.refs, mode: "skip" }) : filtered;
4209
4888
  }
4210
- logOutput(normalizeOutputKeys(data), getOutputFormat());
4889
+ logOutput(normalizeOutputKeys(data), getOutputFormat(), options?.tableRowStyle);
4211
4890
  }
4212
4891
  OutputFormatter.success = success;
4213
4892
  function error(data) {
4214
4893
  data.Log ??= getLogFilePath() || undefined;
4215
4894
  data.ErrorCode ??= defaultErrorCodeForFailure(data);
4216
4895
  data.Retry ??= defaultRetryForErrorCode(data.ErrorCode);
4217
- process.exitCode = EXIT_CODES[data.Result] ?? 1;
4896
+ const exitCode = EXIT_CODES[data.Result] ?? 1;
4897
+ setExitCode(exitCode);
4218
4898
  recordCommandFailureTelemetry({
4219
4899
  result: data.Result,
4220
4900
  errorCode: data.ErrorCode,
4221
4901
  retry: data.Retry,
4222
4902
  message: data.Message,
4223
4903
  context: data.Context,
4224
- exitCode: process.exitCode,
4904
+ exitCode,
4225
4905
  errorClass: data.TelemetryErrorClass,
4226
4906
  terminalOutcome: data.TelemetryTerminalOutcome,
4227
4907
  terminalSignal: data.TelemetryTerminalSignal
@@ -4297,6 +4977,39 @@ var OutputFormatter;
4297
4977
  }
4298
4978
  OutputFormatter.formatToString = formatToString;
4299
4979
  })(OutputFormatter ||= {});
4980
+ // ../../node_modules/commander/esm.mjs
4981
+ var import__ = __toESM(require_commander(), 1);
4982
+ var {
4983
+ program,
4984
+ createCommand,
4985
+ createArgument,
4986
+ createOption,
4987
+ CommanderError,
4988
+ InvalidArgumentError,
4989
+ InvalidOptionArgumentError,
4990
+ Command,
4991
+ Argument,
4992
+ Option,
4993
+ Help
4994
+ } = import__.default;
4995
+
4996
+ // ../common/src/command-examples.ts
4997
+ var examplesByCommand = new WeakMap;
4998
+ Command.prototype.examples = function(examples) {
4999
+ examplesByCommand.set(this, examples);
5000
+ return this;
5001
+ };
5002
+ // ../common/src/preview.ts
5003
+ var previewSlot = singleton("PreviewBuild");
5004
+ function isPreviewBuild() {
5005
+ return previewSlot.get(false) ?? false;
5006
+ }
5007
+ Command.prototype.previewCommand = function(nameAndArgs, opts) {
5008
+ if (isPreviewBuild()) {
5009
+ return this.command(nameAndArgs, opts);
5010
+ }
5011
+ return new Command(nameAndArgs.split(/\s+/)[0] ?? nameAndArgs);
5012
+ };
4300
5013
 
4301
5014
  // ../common/src/telemetry/command-attribution.ts
4302
5015
  var LEGACY_SKILL_NAMESPACE = "uipath:";
@@ -4451,6 +5164,57 @@ function buildCommandTelemetryAttribution(commandPath, skillSource) {
4451
5164
  };
4452
5165
  }
4453
5166
 
5167
+ // ../common/src/telemetry/command-name.ts
5168
+ var TELEMETRY_COMMAND_ROOT = "uip";
5169
+ function commandTelemetryName(parts) {
5170
+ const tokens = [];
5171
+ for (const part of parts) {
5172
+ const pieces = String(part ?? "").split(/\s+/).filter((token) => token && !token.startsWith("-") && token !== TELEMETRY_COMMAND_ROOT);
5173
+ if (pieces.every(isCommandToken)) {
5174
+ tokens.push(...pieces);
5175
+ continue;
5176
+ }
5177
+ tokens.push(UNKNOWN_TOKEN);
5178
+ }
5179
+ return [TELEMETRY_COMMAND_ROOT, ...tokens].join(".");
5180
+ }
5181
+ var COMMAND_TOKEN_PATTERN = /^[a-z0-9][a-z0-9-]*$/;
5182
+ var MAX_COMMAND_TOKEN_LENGTH = 32;
5183
+ var GUID_TOKEN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
5184
+ function isCommandToken(token) {
5185
+ return token.length <= MAX_COMMAND_TOKEN_LENGTH && COMMAND_TOKEN_PATTERN.test(token) && !GUID_TOKEN.test(token) && !/^\d+$/.test(token);
5186
+ }
5187
+ var UNKNOWN_TOKEN = "<unknown>";
5188
+
5189
+ // ../common/src/telemetry/invocation-request.ts
5190
+ var requestContextSlot = singleton("TelemetryInvocationRequestContext");
5191
+ function activeContext() {
5192
+ return telemetry.getActiveContext?.();
5193
+ }
5194
+ function runWithInvocationRequest(fn) {
5195
+ const context = telemetry.createRequestContext();
5196
+ context.startedAt = invocationStartedAt();
5197
+ requestContextSlot.set(context);
5198
+ return telemetry.runWithContext(context, fn);
5199
+ }
5200
+ function ensureInvocationRequestScope(fn) {
5201
+ if (activeContext() !== undefined) {
5202
+ return fn();
5203
+ }
5204
+ const kept = requestContextSlot.get();
5205
+ return kept === undefined ? runWithInvocationRequest(fn) : telemetry.runWithContext(kept, fn);
5206
+ }
5207
+ function getInvocationRequestContext() {
5208
+ return activeContext() ?? requestContextSlot.get();
5209
+ }
5210
+ function emitInvocationRequest(name, success, properties) {
5211
+ const context = getInvocationRequestContext();
5212
+ telemetry.trackRequestResult(name, invocationElapsedMs(), success, properties, context);
5213
+ if (context !== undefined && requestContextSlot.get() === context) {
5214
+ requestContextSlot.clear();
5215
+ }
5216
+ }
5217
+
4454
5218
  // ../common/src/trackedAction.ts
4455
5219
  var pollSignalSlot = singleton("PollSignal");
4456
5220
  var cliErrorCodeValues = new Set(CLI_ERROR_CODES);
@@ -4458,28 +5222,74 @@ var retryHintValues = new Set(RETRY_HINTS);
4458
5222
  var TELEMETRY_COMMAND_ARG_PREFIX = "uip.cmd.arg.";
4459
5223
  var processContext = {
4460
5224
  exit: (code) => {
4461
- process.exitCode = code;
5225
+ recordExitCode(code);
5226
+ setExitCode(code);
4462
5227
  },
4463
5228
  get pollSignal() {
4464
5229
  return pollSignalSlot.get();
4465
5230
  }
4466
5231
  };
5232
+ var TELEMETRY_ARG_VALUE_WITHHELD = "<provided>";
5233
+ var TELEMETRY_ARG_VALUE_DEFAULTED = "<default>";
5234
+ function recordableArgValue(value, choices) {
5235
+ if (typeof value === "boolean" || typeof value === "number") {
5236
+ return value;
5237
+ }
5238
+ if (choices && choices.length > 0) {
5239
+ if (typeof value === "string" && choices.includes(value)) {
5240
+ return value;
5241
+ }
5242
+ if (Array.isArray(value) && value.length > 0 && value.every((entry) => typeof entry === "string" && choices.includes(entry))) {
5243
+ return value.join(",");
5244
+ }
5245
+ }
5246
+ return TELEMETRY_ARG_VALUE_WITHHELD;
5247
+ }
4467
5248
  function extractCommandParams(cmd) {
4468
5249
  const params = {};
4469
- const add = (name, value) => {
4470
- if (name && value !== undefined) {
4471
- params[`${TELEMETRY_COMMAND_ARG_PREFIX}${name}`] = value;
4472
- }
4473
- };
5250
+ forEachSuppliedArgument(cmd, (name, value, choices, defaulted) => {
5251
+ const recordable = recordableArgValue(value, choices);
5252
+ params[`${TELEMETRY_COMMAND_ARG_PREFIX}${name}`] = recordable === TELEMETRY_ARG_VALUE_WITHHELD && defaulted ? TELEMETRY_ARG_VALUE_DEFAULTED : recordable;
5253
+ });
5254
+ return params;
5255
+ }
5256
+ function isDefaultedOption(cmd, name) {
5257
+ const source = cmd.getOptionValueSource?.(name);
5258
+ return source === "default" || source === "implied";
5259
+ }
5260
+ function isDefaultedPositional(cmd, index) {
5261
+ return index >= (cmd.args?.length ?? 0);
5262
+ }
5263
+ function forEachSuppliedArgument(cmd, visit) {
4474
5264
  const registered = cmd.registeredArguments ?? [];
4475
5265
  const processed = cmd.processedArgs ?? [];
4476
5266
  for (let i = 0;i < registered.length; i++) {
4477
- add(registered[i].name(), processed[i]);
5267
+ const name = registered[i].name();
5268
+ if (name && processed[i] !== undefined) {
5269
+ visit(name, processed[i], registered[i].argChoices, isDefaultedPositional(cmd, i));
5270
+ }
5271
+ }
5272
+ const choicesByAttribute = new Map;
5273
+ for (const option of cmd.options) {
5274
+ choicesByAttribute.set(option.attributeName(), option.argChoices);
4478
5275
  }
4479
5276
  for (const [key, value] of Object.entries(cmd.opts())) {
4480
- add(key, value);
5277
+ if (key && value !== undefined) {
5278
+ visit(key, value, choicesByAttribute.get(key), isDefaultedOption(cmd, key));
5279
+ }
4481
5280
  }
4482
- return params;
5281
+ }
5282
+ function withheldArgumentValues(cmd) {
5283
+ const values = [];
5284
+ forEachSuppliedArgument(cmd, (_name, value, choices, defaulted) => {
5285
+ if (defaulted) {
5286
+ return;
5287
+ }
5288
+ if (recordableArgValue(value, choices) === TELEMETRY_ARG_VALUE_WITHHELD) {
5289
+ values.push(value);
5290
+ }
5291
+ });
5292
+ return values;
4483
5293
  }
4484
5294
  function deriveCommandPath(cmd) {
4485
5295
  const parts = [];
@@ -4494,7 +5304,7 @@ function deriveCommandPath(cmd) {
4494
5304
  if (parts.length > 1) {
4495
5305
  parts.shift();
4496
5306
  }
4497
- return ["uip", ...parts.filter((p) => p !== "uip")].join(".");
5307
+ return commandTelemetryName(parts);
4498
5308
  }
4499
5309
  function isCliErrorCode(value) {
4500
5310
  return typeof value === "string" && cliErrorCodeValues.has(value);
@@ -4534,68 +5344,77 @@ Command.prototype.trackedAction = function(context, fn, properties) {
4534
5344
  });
4535
5345
  const telemetryName = deriveCommandPath(command);
4536
5346
  const props = typeof properties === "function" ? properties(...args) : properties;
4537
- const requestContext = telemetry.createRequestContext();
4538
- const startTime = performance.now();
4539
- let errorMessage;
4540
- let fallbackExitCode = EXIT_CODES.Success;
4541
- clearRecordedCommandFailureTelemetry();
4542
- const [error] = await catchError2(telemetry.runWithContext(requestContext, () => {
4543
- const violation = implicitLimitViolation(command);
4544
- if (violation) {
4545
- return Promise.reject(violation);
4546
- }
4547
- return fn(...args);
4548
- }));
4549
- if (error) {
4550
- errorMessage = error instanceof Error ? error.message : String(error);
4551
- logger.debug(`[trackedAction] ${telemetryName} failed: ${errorMessage}`);
4552
- const typed = error;
4553
- const customInstructions = typeof typed.instructions === "string" ? typed.instructions : undefined;
4554
- const customResult = typeof typed.result === "string" && typed.result !== RESULTS.Success && Object.values(RESULTS).includes(typed.result) ? typed.result : undefined;
4555
- const finalResult = customResult ?? RESULTS.Failure;
4556
- const typedErrorCode = typed.errorCode ?? typed.ErrorCode;
4557
- const customErrorCode = isCliErrorCode(typedErrorCode) ? typedErrorCode : undefined;
4558
- const typedRetry = typed.retry ?? typed.Retry;
4559
- const customRetry = isRetryHint(typedRetry) ? typedRetry : undefined;
4560
- const typedContext = typed.context ?? typed.Context;
4561
- const customContext = isErrorContext(typedContext) ? typedContext : undefined;
4562
- const cancellationExitCode = typed.exitCode === 130 || isPromptCancellation(error) ? 130 : undefined;
4563
- fallbackExitCode = cancellationExitCode ?? EXIT_CODES[finalResult];
4564
- OutputFormatter.error({
4565
- Result: finalResult,
4566
- ...customErrorCode ? { ErrorCode: customErrorCode } : {},
4567
- Message: errorMessage,
4568
- Instructions: customInstructions ?? commandHelpHint(telemetryName),
4569
- ...customRetry ? { Retry: customRetry } : {},
4570
- ...customContext ? { Context: customContext } : {}
5347
+ markCommandStart();
5348
+ const supplied = recordSuppliedArgumentValues(withheldArgumentValues(command));
5349
+ try {
5350
+ const startTime = performance.now();
5351
+ let errorMessage;
5352
+ let fallbackExitCode = EXIT_CODES.Success;
5353
+ clearRecordedCommandFailureTelemetry();
5354
+ const [error] = await catchError(ensureInvocationRequestScope(() => {
5355
+ const violation = implicitLimitViolation(command);
5356
+ if (violation) {
5357
+ return Promise.reject(violation);
5358
+ }
5359
+ return fn(...args);
5360
+ }));
5361
+ if (error) {
5362
+ errorMessage = error instanceof Error ? error.message : String(error);
5363
+ logger.debug(`[trackedAction] ${telemetryName} failed: ${errorMessage}`);
5364
+ const typed = error;
5365
+ const customInstructions = typeof typed.instructions === "string" ? typed.instructions : undefined;
5366
+ const customResult = typeof typed.result === "string" && typed.result !== RESULTS.Success && Object.values(RESULTS).includes(typed.result) ? typed.result : undefined;
5367
+ const finalResult = customResult ?? RESULTS.Failure;
5368
+ const typedErrorCode = typed.errorCode ?? typed.ErrorCode;
5369
+ const customErrorCode = isCliErrorCode(typedErrorCode) ? typedErrorCode : undefined;
5370
+ const typedRetry = typed.retry ?? typed.Retry;
5371
+ const customRetry = isRetryHint(typedRetry) ? typedRetry : undefined;
5372
+ const typedContext = typed.context ?? typed.Context;
5373
+ const customContext = isErrorContext(typedContext) ? typedContext : undefined;
5374
+ const cancellationExitCode = typed.exitCode === 130 || isPromptCancellation(error) ? 130 : undefined;
5375
+ fallbackExitCode = cancellationExitCode ?? EXIT_CODES[finalResult];
5376
+ OutputFormatter.error({
5377
+ Result: finalResult,
5378
+ ...customErrorCode ? { ErrorCode: customErrorCode } : {},
5379
+ Message: errorMessage,
5380
+ Instructions: customInstructions ?? commandHelpHint(telemetryName),
5381
+ ...customRetry ? { Retry: customRetry } : {},
5382
+ ...customContext ? { Context: customContext } : {}
5383
+ });
5384
+ context.exit(fallbackExitCode);
5385
+ }
5386
+ const durationMs = performance.now() - startTime;
5387
+ recordCommandDuration(durationMs);
5388
+ const exitCode = fallbackExitCode === 130 ? fallbackExitCode : exitCodeFromProcess(fallbackExitCode);
5389
+ const recordedFailure = takeRecordedCommandFailureTelemetry();
5390
+ const success = !error && exitCode === 0;
5391
+ const terminalTelemetry = buildCommandTerminalTelemetryProperties({
5392
+ error,
5393
+ exitCode,
5394
+ recordedFailure,
5395
+ pollSignal: context.pollSignal
4571
5396
  });
4572
- context.exit(fallbackExitCode);
4573
- }
4574
- const durationMs = performance.now() - startTime;
4575
- const exitCode = fallbackExitCode === 130 ? fallbackExitCode : exitCodeFromProcess(fallbackExitCode);
4576
- const recordedFailure = takeRecordedCommandFailureTelemetry();
4577
- const success = !error && exitCode === 0;
4578
- const terminalTelemetry = buildCommandTerminalTelemetryProperties({
4579
- error,
4580
- exitCode,
4581
- recordedFailure,
4582
- pollSignal: context.pollSignal
4583
- });
4584
- const commandParams = extractCommandParams(command);
4585
- if (props) {
4586
- for (const key of Object.keys(props)) {
4587
- delete commandParams[`${TELEMETRY_COMMAND_ARG_PREFIX}${key}`];
4588
- }
4589
- }
4590
- const baseProperties = redactProperties({
4591
- ...commandParams,
4592
- ...props,
4593
- ...buildCommandTelemetryAttribution(telemetryName, process.env.UIPATH_SKILL),
4594
- command: "true",
4595
- ...terminalTelemetry,
4596
- ...errorMessage ? { errorMessage } : {}
4597
- });
4598
- telemetry.trackRequestResult(telemetryName, durationMs, success, baseProperties, requestContext);
5397
+ if (terminalTelemetry.error_class === "internal" && error) {
5398
+ telemetry.trackException(error instanceof Error ? error : new Error(String(error)), { command_name: telemetryName }, getInvocationRequestContext());
5399
+ }
5400
+ const commandParams = extractCommandParams(command);
5401
+ if (props) {
5402
+ for (const key of Object.keys(props)) {
5403
+ delete commandParams[`${TELEMETRY_COMMAND_ARG_PREFIX}${key}`];
5404
+ }
5405
+ }
5406
+ const baseProperties = redactProperties({
5407
+ ...commandParams,
5408
+ ...props,
5409
+ ...buildCommandTelemetryAttribution(telemetryName, process.env.UIPATH_SKILL),
5410
+ command: "true",
5411
+ ...terminalTelemetry,
5412
+ ...errorMessage ? { errorMessage } : {}
5413
+ });
5414
+ emitInvocationRequest(telemetryName, success, baseProperties);
5415
+ } finally {
5416
+ releaseSuppliedArgumentValues(supplied);
5417
+ }
4599
5418
  });
4600
5419
  };
4601
5420
  // ../common/src/completer.ts
@@ -4618,6 +5437,204 @@ var guardInstalledSlot = singleton("ConsoleGuardInstalled");
4618
5437
  var savedOriginalsSlot = singleton("ConsoleGuardOriginals");
4619
5438
  // ../common/src/constants.ts
4620
5439
  var DEFAULT_AUTH_TIMEOUT_MS = 5 * 60 * 1000;
5440
+ // ../common/src/entity-name-rules.ts
5441
+ var RESERVED_SQL_KEYWORDS_LOWER = new Set(["group", "order"]);
5442
+ var RESERVED_FIELD_NAMES_LOWER = new Set([
5443
+ "id",
5444
+ "createdby",
5445
+ "createtime",
5446
+ "updatedby",
5447
+ "updatetime",
5448
+ "recordowner",
5449
+ "version"
5450
+ ]);
5451
+ var RESERVED_KEYWORDS_LOWER = new Set([
5452
+ "abstract",
5453
+ "as",
5454
+ "base",
5455
+ "bool",
5456
+ "break",
5457
+ "byte",
5458
+ "case",
5459
+ "catch",
5460
+ "char",
5461
+ "checked",
5462
+ "class",
5463
+ "const",
5464
+ "continue",
5465
+ "decimal",
5466
+ "default",
5467
+ "delegate",
5468
+ "do",
5469
+ "double",
5470
+ "else",
5471
+ "enum",
5472
+ "event",
5473
+ "explicit",
5474
+ "extern",
5475
+ "false",
5476
+ "finally",
5477
+ "fixed",
5478
+ "float",
5479
+ "for",
5480
+ "foreach",
5481
+ "goto",
5482
+ "if",
5483
+ "implicit",
5484
+ "in",
5485
+ "int",
5486
+ "interface",
5487
+ "internal",
5488
+ "is",
5489
+ "lock",
5490
+ "long",
5491
+ "namespace",
5492
+ "new",
5493
+ "null",
5494
+ "object",
5495
+ "operator",
5496
+ "out",
5497
+ "override",
5498
+ "params",
5499
+ "private",
5500
+ "protected",
5501
+ "public",
5502
+ "readonly",
5503
+ "ref",
5504
+ "return",
5505
+ "sbyte",
5506
+ "sealed",
5507
+ "short",
5508
+ "sizeof",
5509
+ "stackalloc",
5510
+ "static",
5511
+ "string",
5512
+ "struct",
5513
+ "switch",
5514
+ "this",
5515
+ "throw",
5516
+ "true",
5517
+ "try",
5518
+ "typeof",
5519
+ "uint",
5520
+ "ulong",
5521
+ "unchecked",
5522
+ "unsafe",
5523
+ "ushort",
5524
+ "using",
5525
+ "virtual",
5526
+ "void",
5527
+ "volatile",
5528
+ "while",
5529
+ "addhandler",
5530
+ "addressof",
5531
+ "alias",
5532
+ "and",
5533
+ "andalso",
5534
+ "boolean",
5535
+ "byref",
5536
+ "byval",
5537
+ "call",
5538
+ "cbool",
5539
+ "cbyte",
5540
+ "cchar",
5541
+ "cdate",
5542
+ "cdbl",
5543
+ "cdec",
5544
+ "cint",
5545
+ "clng",
5546
+ "cobj",
5547
+ "csbyte",
5548
+ "cshort",
5549
+ "csng",
5550
+ "cstr",
5551
+ "ctype",
5552
+ "cuint",
5553
+ "culng",
5554
+ "cushort",
5555
+ "date",
5556
+ "declare",
5557
+ "dim",
5558
+ "directcast",
5559
+ "each",
5560
+ "elseif",
5561
+ "end",
5562
+ "endif",
5563
+ "erase",
5564
+ "error",
5565
+ "exit",
5566
+ "friend",
5567
+ "function",
5568
+ "get",
5569
+ "gettype",
5570
+ "getxmlnamespace",
5571
+ "global",
5572
+ "gosub",
5573
+ "goto",
5574
+ "handles",
5575
+ "implements",
5576
+ "imports",
5577
+ "inherits",
5578
+ "integer",
5579
+ "isnot",
5580
+ "let",
5581
+ "lib",
5582
+ "like",
5583
+ "loop",
5584
+ "me",
5585
+ "mod",
5586
+ "module",
5587
+ "mustinherit",
5588
+ "mustoverride",
5589
+ "mybase",
5590
+ "myclass",
5591
+ "narrowing",
5592
+ "next",
5593
+ "not",
5594
+ "nothing",
5595
+ "notinheritable",
5596
+ "notoverridable",
5597
+ "of",
5598
+ "on",
5599
+ "option",
5600
+ "optional",
5601
+ "or",
5602
+ "orelse",
5603
+ "overloads",
5604
+ "overridable",
5605
+ "overrides",
5606
+ "paramarray",
5607
+ "partial",
5608
+ "property",
5609
+ "raiseevent",
5610
+ "redim",
5611
+ "rem",
5612
+ "removehandler",
5613
+ "resume",
5614
+ "select",
5615
+ "set",
5616
+ "shadows",
5617
+ "shared",
5618
+ "single",
5619
+ "step",
5620
+ "stop",
5621
+ "structure",
5622
+ "sub",
5623
+ "synclock",
5624
+ "then",
5625
+ "to",
5626
+ "trycast",
5627
+ "uinteger",
5628
+ "ushort",
5629
+ "variant",
5630
+ "wend",
5631
+ "when",
5632
+ "widening",
5633
+ "with",
5634
+ "withevents",
5635
+ "writeonly",
5636
+ "xor"
5637
+ ]);
4621
5638
  // ../common/src/host-global-options.ts
4622
5639
  var HOST_GLOBAL_OPTIONS_WITH_VALUE = [
4623
5640
  "--output",
@@ -4797,6 +5814,40 @@ function installSdkUserAgentHeader(BaseApiClass, userAgent) {
4797
5814
  var shippedKeysSlot = singleton("ShipSucceededDedupeKeys");
4798
5815
  // ../common/src/tool-provider.ts
4799
5816
  var factorySlot = singleton("PackagerFactoryProvider");
5817
+ // ../auth/src/catch-error.ts
5818
+ function isPromiseLike2(value) {
5819
+ return value !== null && typeof value === "object" && typeof value.then === "function";
5820
+ }
5821
+ function catchError2(fnOrPromise) {
5822
+ if (isPromiseLike2(fnOrPromise)) {
5823
+ return settlePromiseLike2(fnOrPromise);
5824
+ }
5825
+ try {
5826
+ const result = fnOrPromise();
5827
+ if (isPromiseLike2(result)) {
5828
+ return settlePromiseLike2(result);
5829
+ }
5830
+ return [undefined, result];
5831
+ } catch (error) {
5832
+ return [
5833
+ error instanceof Error ? error : new Error(String(error)),
5834
+ undefined
5835
+ ];
5836
+ }
5837
+ }
5838
+ function settlePromiseLike2(thenable) {
5839
+ return Promise.resolve(thenable).then((data) => [undefined, data]).catch((error) => [
5840
+ error instanceof Error ? error : new Error(String(error)),
5841
+ undefined
5842
+ ]);
5843
+ }
5844
+
5845
+ // ../auth/src/constants.ts
5846
+ var UIPATH_HOME_DIR = ".uipath";
5847
+ var AUTH_FILENAME = ".auth";
5848
+ var DEFAULT_BASE_URL = "https://cloud.uipath.com";
5849
+ var DEFAULT_AUTH_TIMEOUT_MS2 = 5 * 60 * 1000;
5850
+
4800
5851
  // ../auth/src/config.ts
4801
5852
  var DEFAULT_CLIENT_ID = "36dea5b8-e8bb-423d-8e7b-c808df8f1c00";
4802
5853
  var AUTH_FILE_CONFIG_KEY = Symbol.for("@uipath/auth/AuthFileConfig");
@@ -4810,7 +5861,7 @@ class InvalidBaseUrlError extends Error {
4810
5861
  super(`Invalid base URL: "${url}"
4811
5862
  ` + `Reason: ${reason}
4812
5863
 
4813
- ` + `Expected format: an https:// URL, e.g. https://cloud.uipath.com (commercial), https://govcloud.uipath.us (Public Sector), or your Automation Suite host (https://<your-host>).
5864
+ ` + `Expected format: an https:// URL (or bare host — https:// is assumed), e.g. https://cloud.uipath.com (commercial), https://govcloud.uipath.us (Public Sector), or your Automation Suite host (https://<your-host>).
4814
5865
  ` + `You can specify the URL via:
4815
5866
  ` + ` • --authority flag
4816
5867
  ` + ` • UIPATH_URL environment variable
@@ -4831,10 +5882,16 @@ var normalizeAndValidateBaseUrl = (rawUrl) => {
4831
5882
  while (baseUrl.endsWith("/")) {
4832
5883
  baseUrl = baseUrl.slice(0, -1);
4833
5884
  }
5885
+ const hasScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(baseUrl);
5886
+ const [hostCandidate] = baseUrl.split(/[/?#]/, 1);
5887
+ if (!hasScheme && hostCandidate.includes(".")) {
5888
+ baseUrl = `https://${baseUrl}`;
5889
+ }
4834
5890
  const resolvedBaseUrl = baseUrl;
4835
- const [urlError, url] = catchError(() => new URL(resolvedBaseUrl));
5891
+ const [urlError, url] = catchError2(() => new URL(resolvedBaseUrl));
4836
5892
  if (urlError) {
4837
- throw new InvalidBaseUrlError(baseUrl, `Malformed URL. ${urlError instanceof Error ? urlError.message : "Unknown error"}`);
5893
+ const shapeHint = !hasScheme && !hostCandidate.includes(".") ? ` "${rawUrl.trim()}" is not a URL or a host name. Pass the full authority URL — https://<host>, or just <host> (https:// is assumed).` : ` ${urlError instanceof Error ? urlError.message : "Unknown error"}`;
5894
+ throw new InvalidBaseUrlError(baseUrl, `Malformed URL.${shapeHint}`);
4838
5895
  }
4839
5896
  if (url.protocol !== "https:") {
4840
5897
  throw new InvalidBaseUrlError(baseUrl, `Authority must use https:// scheme, got ${url.protocol}//. OIDC token exchange requires TLS end-to-end.`);
@@ -4889,6 +5946,11 @@ var resolveConfigAsync = async ({
4889
5946
  };
4890
5947
  };
4891
5948
 
5949
+ // ../auth/src/utils/platform.ts
5950
+ function isBrowser() {
5951
+ return typeof globalThis !== "undefined" && "window" in globalThis && "document" in globalThis;
5952
+ }
5953
+
4892
5954
  // ../auth/src/authProfile.ts
4893
5955
  var DEFAULT_AUTH_PROFILE = "default";
4894
5956
  var PROFILE_DIR = "profiles";
@@ -4900,7 +5962,7 @@ function isAuthProfileStorage(value) {
4900
5962
  return value !== null && typeof value === "object" && "getStore" in value && "run" in value;
4901
5963
  }
4902
5964
  function createProfileStorage() {
4903
- const [error, mod] = catchError(() => __require("node:async_hooks"));
5965
+ const [error, mod] = catchError2(() => __require("node:async_hooks"));
4904
5966
  if (error || typeof mod?.AsyncLocalStorage !== "function") {
4905
5967
  return {
4906
5968
  getStore: () => {
@@ -4916,9 +5978,9 @@ function getProfileStorage() {
4916
5978
  if (isAuthProfileStorage(existing)) {
4917
5979
  return existing;
4918
5980
  }
4919
- const storage = createProfileStorage();
4920
- globalSlot2[AUTH_PROFILE_STORAGE_KEY] = storage;
4921
- return storage;
5981
+ const storage2 = createProfileStorage();
5982
+ globalSlot2[AUTH_PROFILE_STORAGE_KEY] = storage2;
5983
+ return storage2;
4922
5984
  }
4923
5985
  var profileStorage = getProfileStorage();
4924
5986
 
@@ -4949,8 +6011,8 @@ function resolveAuthProfileFilePath(profile) {
4949
6011
  if (normalized === undefined) {
4950
6012
  throw new AuthProfileValidationError(`"${DEFAULT_AUTH_PROFILE}" is the built-in profile and does not have a profile file path.`);
4951
6013
  }
4952
- const fs = getFileSystem();
4953
- return fs.path.join(fs.env.homedir(), UIPATH_HOME_DIR, PROFILE_DIR, normalized, AUTH_FILENAME);
6014
+ const fs2 = getFileSystem();
6015
+ return fs2.path.join(fs2.env.homedir(), UIPATH_HOME_DIR, PROFILE_DIR, normalized, AUTH_FILENAME);
4954
6016
  }
4955
6017
  function getActiveAuthProfileFilePath() {
4956
6018
  const profile = getActiveAuthProfile();
@@ -5031,7 +6093,7 @@ var getTokenExpiration = (accessToken) => {
5031
6093
  // ../auth/src/sessionIdentity.ts
5032
6094
  var parseAuthFlow = (value) => value === "authorization_code" || value === "client_credentials" || value === "federated_credentials" ? value : undefined;
5033
6095
  var decodeClaims = (accessToken) => {
5034
- const [error, claims] = catchError(() => parseJWT(accessToken));
6096
+ const [error, claims] = catchError2(() => parseJWT(accessToken));
5035
6097
  return error ? undefined : claims;
5036
6098
  };
5037
6099
  var asString = (value) => typeof value === "string" && value.length > 0 ? value : undefined;
@@ -5115,27 +6177,48 @@ var requireEnv = (name) => {
5115
6177
  }
5116
6178
  return value;
5117
6179
  };
6180
+ var OPAQUE_TOKEN_BASE_URL_VAR = "UIPATH_URL";
6181
+ var resolveBaseUrl = (rawUrl, failureContext) => {
6182
+ const [baseUrlError, baseUrl] = catchError2(() => normalizeAndValidateBaseUrl(rawUrl));
6183
+ if (baseUrlError) {
6184
+ if (baseUrlError instanceof InvalidBaseUrlError) {
6185
+ throw baseUrlError;
6186
+ }
6187
+ throw new EnvAuthConfigError(`${failureContext}: ` + `${baseUrlError instanceof Error ? baseUrlError.message : String(baseUrlError)}`);
6188
+ }
6189
+ return baseUrl;
6190
+ };
5118
6191
  var readAuthFromEnv = () => {
5119
6192
  const accessToken = requireEnv(ENV_AUTH_VARS.token);
5120
6193
  const organizationName = requireEnv(ENV_AUTH_VARS.organizationName);
5121
6194
  const organizationId = requireEnv(ENV_AUTH_VARS.organizationId);
5122
6195
  const tenantName = requireEnv(ENV_AUTH_VARS.tenantName);
5123
6196
  const tenantId = requireEnv(ENV_AUTH_VARS.tenantId);
5124
- const [parseError, payload] = catchError(() => parseJWT(accessToken));
6197
+ const [parseError, payload] = catchError2(() => parseJWT(accessToken));
5125
6198
  if (parseError) {
5126
- throw new EnvAuthConfigError(`${ENV_AUTH_VARS.token} is not a valid JWT: ` + `${parseError instanceof Error ? parseError.message : String(parseError)}`);
6199
+ const parseErrorMessage = parseError instanceof Error ? parseError.message : String(parseError);
6200
+ const rawUrl = process.env[OPAQUE_TOKEN_BASE_URL_VAR];
6201
+ if (!rawUrl) {
6202
+ throw new EnvAuthConfigError(`${ENV_AUTH_VARS.token} is not a JWT (treating it as an opaque token, ` + `e.g. a Personal Access Token). Set ${OPAQUE_TOKEN_BASE_URL_VAR} to the ` + `UiPath base URL if this is a PAT, or fix the token if it was meant to ` + `be a JWT (parse error: ${parseErrorMessage}).`);
6203
+ }
6204
+ const baseUrl2 = resolveBaseUrl(rawUrl, `Failed to validate ${OPAQUE_TOKEN_BASE_URL_VAR}`);
6205
+ return {
6206
+ loginStatus: "Logged in",
6207
+ accessToken,
6208
+ baseUrl: baseUrl2,
6209
+ organizationName,
6210
+ organizationId,
6211
+ tenantName,
6212
+ tenantId,
6213
+ source: "env-vars" /* EnvironmentVariables */,
6214
+ hint: "Token is opaque (not a JWT) - expiration and identity cannot be " + "determined locally. Commands will fail with 401 once it is revoked or " + `expired. If this was meant to be a JWT instead of a PAT, note: ${parseErrorMessage}`
6215
+ };
5127
6216
  }
5128
6217
  const iss = payload.iss;
5129
6218
  if (typeof iss !== "string" || iss.length === 0) {
5130
6219
  throw new EnvAuthConfigError(`${ENV_AUTH_VARS.token} has no 'iss' claim; cannot determine ` + `the UiPath server. Ensure the token was issued by a UiPath identity server.`);
5131
6220
  }
5132
- const [baseUrlError, baseUrl] = catchError(() => normalizeAndValidateBaseUrl(iss));
5133
- if (baseUrlError) {
5134
- if (baseUrlError instanceof InvalidBaseUrlError) {
5135
- throw baseUrlError;
5136
- }
5137
- throw new EnvAuthConfigError(`Failed to derive server URL from token 'iss' claim: ` + `${baseUrlError instanceof Error ? baseUrlError.message : String(baseUrlError)}`);
5138
- }
6221
+ const baseUrl = resolveBaseUrl(iss, "Failed to derive server URL from token 'iss' claim");
5139
6222
  const expiration = getTokenExpiration(accessToken);
5140
6223
  const loginStatus = expiration && expiration <= new Date ? "Expired" : "Logged in";
5141
6224
  const identity = resolveSessionIdentity(accessToken);
@@ -5161,8 +6244,8 @@ var SURFACE_WINDOW_MS = 60 * 60 * 1000;
5161
6244
  async function refreshTokenFingerprint(refreshToken) {
5162
6245
  const bytes = new TextEncoder().encode(refreshToken);
5163
6246
  if (globalThis.crypto?.subtle) {
5164
- const digest = await globalThis.crypto.subtle.digest("SHA-256", bytes);
5165
- return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("").slice(0, 16);
6247
+ const digest2 = await globalThis.crypto.subtle.digest("SHA-256", bytes);
6248
+ return Array.from(new Uint8Array(digest2), (b) => b.toString(16).padStart(2, "0")).join("").slice(0, 16);
5166
6249
  }
5167
6250
  const { createHash } = await import("node:crypto");
5168
6251
  return createHash("sha256").update(refreshToken).digest("hex").slice(0, 16);
@@ -5171,9 +6254,9 @@ function breakerPathFor(authPath) {
5171
6254
  return `${authPath}${BREAKER_SUFFIX}`;
5172
6255
  }
5173
6256
  async function loadRefreshBreaker(authPath) {
5174
- const fs = getFileSystem();
6257
+ const fs2 = getFileSystem();
5175
6258
  try {
5176
- const content = await fs.readFile(breakerPathFor(authPath), "utf-8");
6259
+ const content = await fs2.readFile(breakerPathFor(authPath), "utf-8");
5177
6260
  if (!content)
5178
6261
  return {};
5179
6262
  const parsed = JSON.parse(content);
@@ -5184,20 +6267,20 @@ async function loadRefreshBreaker(authPath) {
5184
6267
  }
5185
6268
  async function saveRefreshBreaker(authPath, state) {
5186
6269
  try {
5187
- const fs = getFileSystem();
5188
- const path = breakerPathFor(authPath);
5189
- await fs.mkdir(fs.path.dirname(path));
5190
- const tempPath = `${path}.tmp`;
5191
- await fs.writeFile(tempPath, JSON.stringify(state));
5192
- await fs.rename(tempPath, path);
6270
+ const fs2 = getFileSystem();
6271
+ const path2 = breakerPathFor(authPath);
6272
+ await fs2.mkdir(fs2.path.dirname(path2));
6273
+ const tempPath = `${path2}.tmp`;
6274
+ await fs2.writeFile(tempPath, JSON.stringify(state));
6275
+ await fs2.rename(tempPath, path2);
5193
6276
  } catch {}
5194
6277
  }
5195
6278
  async function clearRefreshBreaker(authPath) {
5196
- const fs = getFileSystem();
5197
- const path = breakerPathFor(authPath);
6279
+ const fs2 = getFileSystem();
6280
+ const path2 = breakerPathFor(authPath);
5198
6281
  try {
5199
- if (await fs.exists(path)) {
5200
- await fs.rm(path);
6282
+ if (await fs2.exists(path2)) {
6283
+ await fs2.rm(path2);
5201
6284
  }
5202
6285
  } catch {}
5203
6286
  }
@@ -5218,43 +6301,43 @@ var ROBOT_USER_SERVICES_PIPE = "UiPathUserServices";
5218
6301
  var ROBOT_USER_SERVICES_ALTERNATE_PIPE = `${ROBOT_USER_SERVICES_PIPE}Alternate`;
5219
6302
  var PIPE_NAME_MAX_LENGTH = 103;
5220
6303
  var getRobotIpcPipeNames = async () => {
5221
- const fs = getFileSystem();
5222
- const username = fs.env.getenv("USER") ?? fs.env.getenv("USERNAME");
6304
+ const fs2 = getFileSystem();
6305
+ const username = fs2.env.getenv("USER") ?? fs2.env.getenv("USERNAME");
5223
6306
  if (!username) {
5224
6307
  throw new Error("Unable to determine current username");
5225
6308
  }
5226
- const tempPath = fs.env.getenv("TMPDIR") ?? "/tmp/";
5227
- return [ROBOT_USER_SERVICES_PIPE, ROBOT_USER_SERVICES_ALTERNATE_PIPE].map((baseName) => fs.path.join(tempPath, `${baseName}_${username}`).substring(0, PIPE_NAME_MAX_LENGTH));
6309
+ const tempPath = fs2.env.getenv("TMPDIR") ?? "/tmp/";
6310
+ return [ROBOT_USER_SERVICES_PIPE, ROBOT_USER_SERVICES_ALTERNATE_PIPE].map((baseName) => fs2.path.join(tempPath, `${baseName}_${username}`).substring(0, PIPE_NAME_MAX_LENGTH));
5228
6311
  };
5229
6312
  var defaultIsRobotIpcAvailable = async () => {
5230
6313
  if (process.platform === "win32") {
5231
6314
  return true;
5232
6315
  }
5233
- const [pipeNamesError, pipeNames] = await catchError(getRobotIpcPipeNames());
6316
+ const [pipeNamesError, pipeNames] = await catchError2(getRobotIpcPipeNames());
5234
6317
  if (pipeNamesError || !pipeNames) {
5235
6318
  return false;
5236
6319
  }
5237
- const fs = getFileSystem();
6320
+ const fs2 = getFileSystem();
5238
6321
  for (const pipeName of pipeNames) {
5239
- const [existsError, exists] = await catchError(fs.exists(pipeName));
6322
+ const [existsError, exists] = await catchError2(fs2.exists(pipeName));
5240
6323
  if (!existsError && exists === true) {
5241
6324
  return true;
5242
6325
  }
5243
6326
  }
5244
6327
  return false;
5245
6328
  };
5246
- var withTimeout = (promise, timeoutMs) => new Promise((resolve, reject) => {
6329
+ var withTimeout = (promise, timeoutMs) => new Promise((resolve2, reject) => {
5247
6330
  const timer = setTimeout(() => reject(new Error(`Robot IPC call timed out after ${timeoutMs}ms`)), timeoutMs);
5248
6331
  promise.then((value) => {
5249
6332
  clearTimeout(timer);
5250
- resolve(value);
6333
+ resolve2(value);
5251
6334
  }, (error) => {
5252
6335
  clearTimeout(timer);
5253
6336
  reject(error);
5254
6337
  });
5255
6338
  });
5256
6339
  var parseResourceUrl = (url) => {
5257
- const [error, parsed] = catchError(() => new URL(url));
6340
+ const [error, parsed] = catchError2(() => new URL(url));
5258
6341
  if (error || !parsed)
5259
6342
  return;
5260
6343
  const segments = parsed.pathname.split("/").filter(Boolean);
@@ -5274,7 +6357,7 @@ var defaultLoadModule = async () => {
5274
6357
  if (!hostLoader) {
5275
6358
  return;
5276
6359
  }
5277
- const [error, mod] = await catchError(() => hostLoader());
6360
+ const [error, mod] = await catchError2(() => hostLoader());
5278
6361
  if (error || !mod) {
5279
6362
  return;
5280
6363
  }
@@ -5300,7 +6383,7 @@ var tryRobotClientFallback = async (options = {}) => {
5300
6383
  const mod = await loadModule();
5301
6384
  if (!mod)
5302
6385
  return;
5303
- const [ctorError, proxy] = catchError(() => new mod.RobotProxyConstructor);
6386
+ const [ctorError, proxy] = catchError2(() => new mod.RobotProxyConstructor);
5304
6387
  if (ctorError || !proxy) {
5305
6388
  return;
5306
6389
  }
@@ -5323,7 +6406,7 @@ var tryRobotClientFallback = async (options = {}) => {
5323
6406
  let organizationIdFromToken;
5324
6407
  let tenantIdFromToken;
5325
6408
  let issuerFromToken;
5326
- const [jwtError, claims] = catchError(() => parseJWT(accessToken));
6409
+ const [jwtError, claims] = catchError2(() => parseJWT(accessToken));
5327
6410
  if (!jwtError && claims) {
5328
6411
  const rawOrgId = claims.prtId ?? claims.organizationId ?? claims.prt_id;
5329
6412
  if (typeof rawOrgId === "string" && rawOrgId.length > 0) {
@@ -5350,7 +6433,7 @@ var tryRobotClientFallback = async (options = {}) => {
5350
6433
  } catch {
5351
6434
  return;
5352
6435
  } finally {
5353
- await catchError(() => withTimeout(proxy.CloseAsync(), CLOSE_TIMEOUT_MS));
6436
+ await catchError2(() => withTimeout(proxy.CloseAsync(), CLOSE_TIMEOUT_MS));
5354
6437
  }
5355
6438
  };
5356
6439
 
@@ -5420,9 +6503,9 @@ var errorCode = (err) => {
5420
6503
  }
5421
6504
  return "EUNKNOWN";
5422
6505
  };
5423
- var probeAsync = async (fs, candidate) => {
6506
+ var probeAsync = async (fs2, candidate) => {
5424
6507
  try {
5425
- const stats = await fs.stat(candidate);
6508
+ const stats = await fs2.stat(candidate);
5426
6509
  if (stats === null) {
5427
6510
  return { exists: false };
5428
6511
  }
@@ -5449,9 +6532,9 @@ var probeAsync = async (fs, candidate) => {
5449
6532
  }
5450
6533
  };
5451
6534
  var resolveEnvFileLocationAsync = async (envFilePath = DEFAULT_ENV_FILENAME, opts) => {
5452
- const fs = getFileSystem();
5453
- if (fs.path.isAbsolute(envFilePath)) {
5454
- const probe2 = await probeAsync(fs, envFilePath);
6535
+ const fs2 = getFileSystem();
6536
+ if (fs2.path.isAbsolute(envFilePath)) {
6537
+ const probe2 = await probeAsync(fs2, envFilePath);
5455
6538
  return probe2.exists ? { exists: true, absolutePath: envFilePath, source: "absolute" } : {
5456
6539
  exists: false,
5457
6540
  absolutePath: envFilePath,
@@ -5459,11 +6542,11 @@ var resolveEnvFileLocationAsync = async (envFilePath = DEFAULT_ENV_FILENAME, opt
5459
6542
  ...probe2.unusable ? { unusable: probe2.unusable } : {}
5460
6543
  };
5461
6544
  }
5462
- const cwd = opts?.cwd ?? fs.env.cwd();
6545
+ const cwd = opts?.cwd ?? fs2.env.cwd();
5463
6546
  let searchDir = cwd;
5464
6547
  while (true) {
5465
- const candidate = fs.path.join(searchDir, envFilePath);
5466
- const probe2 = await probeAsync(fs, candidate);
6548
+ const candidate = fs2.path.join(searchDir, envFilePath);
6549
+ const probe2 = await probeAsync(fs2, candidate);
5467
6550
  if (probe2.exists) {
5468
6551
  return {
5469
6552
  exists: true,
@@ -5471,14 +6554,14 @@ var resolveEnvFileLocationAsync = async (envFilePath = DEFAULT_ENV_FILENAME, opt
5471
6554
  source: searchDir === cwd ? "cwd" : "ancestor"
5472
6555
  };
5473
6556
  }
5474
- const parentDir = fs.path.dirname(searchDir);
6557
+ const parentDir = fs2.path.dirname(searchDir);
5475
6558
  if (parentDir === searchDir) {
5476
6559
  break;
5477
6560
  }
5478
6561
  searchDir = parentDir;
5479
6562
  }
5480
- const homePath = fs.path.join(fs.env.homedir(), envFilePath);
5481
- const probe = await probeAsync(fs, homePath);
6563
+ const homePath = fs2.path.join(fs2.env.homedir(), envFilePath);
6564
+ const probe = await probeAsync(fs2, homePath);
5482
6565
  if (probe.exists) {
5483
6566
  return { exists: true, absolutePath: homePath, source: "home" };
5484
6567
  }
@@ -5500,12 +6583,12 @@ var resolveEnvFilePathAsync = async (envFilePath = DEFAULT_ENV_FILENAME, opts) =
5500
6583
  };
5501
6584
  };
5502
6585
  var loadEnvFileAsync = async ({ envPath }) => {
5503
- const fs = getFileSystem();
5504
- const absolutePath = fs.path.isAbsolute(envPath) ? envPath : fs.path.join(fs.env.cwd(), envPath);
5505
- if (!await fs.exists(absolutePath)) {
6586
+ const fs2 = getFileSystem();
6587
+ const absolutePath = fs2.path.isAbsolute(envPath) ? envPath : fs2.path.join(fs2.env.cwd(), envPath);
6588
+ if (!await fs2.exists(absolutePath)) {
5506
6589
  throw new Error(`Environment file not found: ${envPath}`);
5507
6590
  }
5508
- const content = await fs.readFile(absolutePath, "utf-8");
6591
+ const content = await fs2.readFile(absolutePath, "utf-8");
5509
6592
  if (content === null) {
5510
6593
  throw new Error(`Environment file not found: ${envPath}`);
5511
6594
  }
@@ -5534,10 +6617,10 @@ var saveEnvFileAsync = async ({
5534
6617
  data,
5535
6618
  merge = true
5536
6619
  }) => {
5537
- const fs = getFileSystem();
5538
- const absolutePath = fs.path.isAbsolute(envPath) ? envPath : fs.path.join(fs.env.homedir(), envPath);
6620
+ const fs2 = getFileSystem();
6621
+ const absolutePath = fs2.path.isAbsolute(envPath) ? envPath : fs2.path.join(fs2.env.homedir(), envPath);
5539
6622
  let existingData = {};
5540
- if (merge && await fs.exists(absolutePath)) {
6623
+ if (merge && await fs2.exists(absolutePath)) {
5541
6624
  try {
5542
6625
  existingData = await loadEnvFileAsync({ envPath: absolutePath });
5543
6626
  } catch {}
@@ -5555,11 +6638,11 @@ var saveEnvFileAsync = async ({
5555
6638
  const content = `${lines.join(`
5556
6639
  `)}
5557
6640
  `;
5558
- const dir = fs.path.dirname(absolutePath);
5559
- await fs.mkdir(dir);
6641
+ const dir = fs2.path.dirname(absolutePath);
6642
+ await fs2.mkdir(dir);
5560
6643
  const tempPath = `${absolutePath}.tmp`;
5561
- await fs.writeFile(tempPath, content);
5562
- await fs.rename(tempPath, absolutePath);
6644
+ await fs2.writeFile(tempPath, content);
6645
+ await fs2.rename(tempPath, absolutePath);
5563
6646
  };
5564
6647
 
5565
6648
  // ../auth/src/loginStatus.ts
@@ -5673,11 +6756,11 @@ async function loadFileCredentials(loadEnvFile, absolutePath) {
5673
6756
  return { credentials };
5674
6757
  }
5675
6758
  async function getGlobalCredsHint(getFs, loadEnvFile, absolutePath, envFilePath) {
5676
- const fs = getFs();
5677
- const globalPath = fs.path.join(fs.env.homedir(), envFilePath);
6759
+ const fs2 = getFs();
6760
+ const globalPath = fs2.path.join(fs2.env.homedir(), envFilePath);
5678
6761
  if (absolutePath === globalPath)
5679
6762
  return;
5680
- if (!await fs.exists(globalPath))
6763
+ if (!await fs2.exists(globalPath))
5681
6764
  return;
5682
6765
  try {
5683
6766
  const globalCreds = await loadEnvFile({ envPath: globalPath });
@@ -6083,7 +7166,7 @@ var TENANT_SELECTION_CODES = new Set([
6083
7166
  var GUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
6084
7167
  var ZERO_GUID = "00000000-0000-0000-0000-000000000000";
6085
7168
  async function resolveAuth(tenant) {
6086
- const [loginError, loginStatus2] = await catchError2(getLoginStatusAsync());
7169
+ const [loginError, loginStatus2] = await catchError(getLoginStatusAsync());
6087
7170
  if (loginError) {
6088
7171
  throw new Error(loginError.message);
6089
7172
  }
@@ -6153,18 +7236,20 @@ async function createFeedback(req, opts) {
6153
7236
  }
6154
7237
  return response.json();
6155
7238
  }
6156
- async function getFeedback(id, opts) {
6157
- if (!GUID_RE.test(id)) {
6158
- throw new Error(`Invalid feedback ID format: ${id}`);
6159
- }
6160
- const { baseUrl, orgId, tenantName, token } = await resolveAuth(opts.tenant);
6161
- const url = `${feedbackBaseUrl(baseUrl, orgId, tenantName)}/${id}`;
6162
- const response = await apiFetch(url, token, opts.folderKey);
7239
+ async function fetchFeedback(id, auth, opts) {
7240
+ const url = `${feedbackBaseUrl(auth.baseUrl, auth.orgId, auth.tenantName)}/${id}`;
7241
+ const response = await apiFetch(url, auth.token, opts.folderKey);
6163
7242
  if (!response.ok) {
6164
7243
  await handleErrorResponse(response, `Feedback ${id}`);
6165
7244
  }
6166
7245
  return response.json();
6167
7246
  }
7247
+ async function getFeedback(id, opts) {
7248
+ if (!GUID_RE.test(id)) {
7249
+ throw new Error(`Invalid feedback ID format: ${id}`);
7250
+ }
7251
+ return fetchFeedback(id, await resolveAuth(opts.tenant), opts);
7252
+ }
6168
7253
  async function listFeedback(filters, opts) {
6169
7254
  const { baseUrl, orgId, tenantName, token } = await resolveAuth(opts.tenant);
6170
7255
  const params = new URLSearchParams;
@@ -6229,16 +7314,42 @@ async function listDetailedFeedback(filters, opts) {
6229
7314
  }
6230
7315
  return response.json();
6231
7316
  }
7317
+ function readField(source, name) {
7318
+ const lower = name.charAt(0).toLowerCase() + name.slice(1);
7319
+ const upper = name.charAt(0).toUpperCase() + name.slice(1);
7320
+ return source[lower] ?? source[upper];
7321
+ }
7322
+ function existingText(existing, name) {
7323
+ const value = readField(existing, name);
7324
+ return typeof value === "string" ? value : undefined;
7325
+ }
7326
+ function existingCategories(existing) {
7327
+ const raw = readField(existing, "feedbackCategories");
7328
+ if (!Array.isArray(raw)) {
7329
+ return [];
7330
+ }
7331
+ const names = [];
7332
+ for (const entry of raw) {
7333
+ const name = readField(entry, "category");
7334
+ if (typeof name === "string") {
7335
+ names.push({ Id: ZERO_GUID, Category: name });
7336
+ }
7337
+ }
7338
+ return names;
7339
+ }
6232
7340
  async function updateFeedback(id, req, opts) {
6233
7341
  if (!GUID_RE.test(id)) {
6234
7342
  throw new Error(`Invalid feedback ID format: ${id}`);
6235
7343
  }
6236
- const { baseUrl, orgId, tenantName, token } = await resolveAuth(opts.tenant);
7344
+ const auth = await resolveAuth(opts.tenant);
7345
+ const existing = await fetchFeedback(id, auth, opts);
7346
+ const { baseUrl, orgId, tenantName, token } = auth;
6237
7347
  const url = `${feedbackBaseUrl(baseUrl, orgId, tenantName)}/${id}`;
6238
7348
  const body = {
6239
7349
  IsPositive: req.isPositive,
6240
- Comment: req.comment,
6241
- Categories: req.categories.map((c) => ({
7350
+ Comment: req.comment ?? existingText(existing, "comment"),
7351
+ Metadata: req.metadata ?? existingText(existing, "metadata"),
7352
+ Categories: (req.categories ?? existingCategories(existing)).map((c) => ({
6242
7353
  Id: ZERO_GUID,
6243
7354
  Category: c.Category
6244
7355
  }))
@@ -6265,7 +7376,7 @@ async function deleteFeedback(id, opts) {
6265
7376
  function collect(val, prev) {
6266
7377
  return [...prev, val];
6267
7378
  }
6268
- async function readCommentFile(filePath) {
7379
+ async function readTextFile(filePath, label = "Comment") {
6269
7380
  if (filePath === "-") {
6270
7381
  const chunks = [];
6271
7382
  for await (const chunk of process.stdin) {
@@ -6273,14 +7384,69 @@ async function readCommentFile(filePath) {
6273
7384
  }
6274
7385
  return Buffer.concat(chunks).toString("utf8");
6275
7386
  }
6276
- const fs = getFileSystem();
6277
- const content = await fs.readFile(filePath, "utf-8");
7387
+ const fs2 = getFileSystem();
7388
+ const content = await fs2.readFile(filePath, "utf-8");
6278
7389
  if (content === null) {
6279
- throw new Error(`Comment file not found: ${filePath}`);
7390
+ throw new Error(`${label} file not found: ${filePath}`);
6280
7391
  }
6281
7392
  return content;
6282
7393
  }
6283
7394
 
7395
+ class TextOptionConflictError extends Error {
7396
+ instructions;
7397
+ constructor(message, instructions) {
7398
+ super(message);
7399
+ this.instructions = instructions;
7400
+ this.name = "TextOptionConflictError";
7401
+ }
7402
+ }
7403
+ async function resolveTextOptions(sources) {
7404
+ for (const source of sources) {
7405
+ if (source.inline && source.file) {
7406
+ throw new TextOptionConflictError(`--${source.flag} and --${source.flag}-file are mutually exclusive`, `Provide either --${source.flag} or --${source.flag}-file`);
7407
+ }
7408
+ }
7409
+ const stdinFlags = sources.filter((source) => source.file === "-").map((source) => `--${source.flag}-file`);
7410
+ if (stdinFlags.length > 1) {
7411
+ throw new TextOptionConflictError(`${stdinFlags.join(" and ")} cannot both read stdin`, `Pass a file path to at least one of ${stdinFlags.join(" or ")}`);
7412
+ }
7413
+ const resolved = [];
7414
+ for (const source of sources) {
7415
+ resolved.push(source.file ? await readTextFile(source.file, source.label) : source.inline);
7416
+ }
7417
+ return resolved;
7418
+ }
7419
+ function commentSource(opts) {
7420
+ return {
7421
+ inline: opts.comment,
7422
+ file: opts.commentFile,
7423
+ flag: "comment",
7424
+ label: "Comment"
7425
+ };
7426
+ }
7427
+ function metadataSource(opts) {
7428
+ return {
7429
+ inline: opts.metadata,
7430
+ file: opts.metadataFile,
7431
+ flag: "metadata",
7432
+ label: "Metadata"
7433
+ };
7434
+ }
7435
+ async function resolveFeedbackText(code, sources) {
7436
+ const [error, values] = await catchError(resolveTextOptions(sources));
7437
+ if (error) {
7438
+ OutputFormatter.error({
7439
+ Result: RESULTS.Failure,
7440
+ Code: code,
7441
+ Message: error.message,
7442
+ Instructions: error instanceof TextOptionConflictError ? error.instructions : "Check the file path is readable, or pass the value inline instead."
7443
+ });
7444
+ processContext.exit(1);
7445
+ return;
7446
+ }
7447
+ return values;
7448
+ }
7449
+
6284
7450
  // src/commands/feedback/create.ts
6285
7451
  var FEEDBACK_CREATE_EXAMPLES = [
6286
7452
  {
@@ -6293,7 +7459,7 @@ var FEEDBACK_CREATE_EXAMPLES = [
6293
7459
  }
6294
7460
  ];
6295
7461
  function registerCreateCommand(program2) {
6296
- program2.command("create").description("Create feedback for a trace").examples(FEEDBACK_CREATE_EXAMPLES).option("--trace-id <id>", "Trace ID (32-char hex or GUID)").option("--positive", "Mark as positive feedback").option("--negative", "Mark as negative feedback").option("--span-id <id>", "Span ID (defaults to root span of trace)").option("--comment <text>", "Free-text annotation (max 4000 chars)").option("--comment-file <file>", "Read comment from file; use '-' for stdin").option("--category <tag>", 'Category tag, repeatable. Built-in defaults: "Output", "Agent Error", "Agent Plan Execution"', collect, []).option("--agent-id <guid>", "Agent reference ID").option("--agent-version <str>", "Agent version (max 100 chars)").option("--folder-key <guid>", "Folder key (required for write ops)").addOption(createHiddenDeprecatedTenantOption("--tenant <name>")).trackedAction(processContext, async (opts) => {
7462
+ program2.command("create").description("Create feedback for a trace").examples(FEEDBACK_CREATE_EXAMPLES).option("--trace-id <id>", "Trace ID (32-char hex or GUID)").option("--positive", "Mark as positive feedback").option("--negative", "Mark as negative feedback").option("--span-id <id>", "Span ID (defaults to root span of trace)").option("--comment <text>", "Free-text annotation (max 1048576 chars)").option("--comment-file <file>", "Read comment from file; use '-' for stdin").option("--category <tag>", 'Category tag, repeatable. Built-in defaults: "Output", "Agent Error", "Agent Plan Execution"', collect, []).option("--agent-id <guid>", "Agent reference ID").option("--agent-version <str>", "Agent version (max 100 chars)").option("--folder-key <guid>", "Folder key (required for write ops)").addOption(createHiddenDeprecatedTenantOption("--tenant <name>")).trackedAction(processContext, async (opts) => {
6297
7463
  if (!opts.traceId) {
6298
7464
  OutputFormatter.error({
6299
7465
  Result: RESULTS.Failure,
@@ -6334,31 +7500,14 @@ function registerCreateCommand(program2) {
6334
7500
  processContext.exit(1);
6335
7501
  return;
6336
7502
  }
6337
- if (opts.comment && opts.commentFile) {
6338
- OutputFormatter.error({
6339
- Result: RESULTS.Failure,
6340
- Code: "FeedbackCreate",
6341
- Message: "--comment and --comment-file are mutually exclusive",
6342
- Instructions: "Provide either --comment or --comment-file"
6343
- });
6344
- processContext.exit(1);
7503
+ const texts = await resolveFeedbackText("FeedbackCreate", [
7504
+ commentSource(opts)
7505
+ ]);
7506
+ if (!texts) {
6345
7507
  return;
6346
7508
  }
6347
- let comment = opts.comment;
6348
- if (opts.commentFile) {
6349
- const [readError, text] = await catchError2(readCommentFile(opts.commentFile));
6350
- if (readError) {
6351
- OutputFormatter.error({
6352
- Result: RESULTS.Failure,
6353
- Code: "FeedbackCreate",
6354
- Message: readError.message
6355
- });
6356
- processContext.exit(1);
6357
- return;
6358
- }
6359
- comment = text;
6360
- }
6361
- const [error, result] = await catchError2(createFeedback({
7509
+ const [comment] = texts;
7510
+ const [error, result] = await catchError(createFeedback({
6362
7511
  traceId: opts.traceId,
6363
7512
  spanId: opts.spanId,
6364
7513
  isPositive: !!opts.positive,
@@ -6423,7 +7572,7 @@ function registerDeleteCommand(program2) {
6423
7572
  if (!requireConfirmation(opts, `delete feedback '${id}'`)) {
6424
7573
  return;
6425
7574
  }
6426
- const [error] = await catchError2(deleteFeedback(id, {
7575
+ const [error] = await catchError(deleteFeedback(id, {
6427
7576
  tenant: opts.tenant,
6428
7577
  folderKey: opts.folderKey
6429
7578
  }));
@@ -6470,7 +7619,7 @@ function registerGetCommand(program2) {
6470
7619
  processContext.exit(1);
6471
7620
  return;
6472
7621
  }
6473
- const [error, result] = await catchError2(getFeedback(id, {
7622
+ const [error, result] = await catchError(getFeedback(id, {
6474
7623
  tenant: opts.tenant,
6475
7624
  folderKey: opts.folderKey
6476
7625
  }));
@@ -6539,7 +7688,7 @@ function registerListCommand(program2) {
6539
7688
  if (offset.usedDeprecated) {
6540
7689
  warnDeprecatedOptionAlias("--skip", "--offset");
6541
7690
  }
6542
- const [error, result] = await catchError2(listFeedback({
7691
+ const [error, result] = await catchError(listFeedback({
6543
7692
  agentId: opts.agentId,
6544
7693
  agentVersion: opts.agentVersion,
6545
7694
  traceId: opts.traceId,
@@ -6633,7 +7782,7 @@ function registerListDetailedCommand(program2) {
6633
7782
  }
6634
7783
  after = new Date(Date.now() - sinceMs).toISOString();
6635
7784
  }
6636
- const [error, result] = await catchError2(listDetailedFeedback({
7785
+ const [error, result] = await catchError(listDetailedFeedback({
6637
7786
  agentId: opts.agentId,
6638
7787
  agentVersion: opts.agentVersion,
6639
7788
  traceId: opts.traceId,
@@ -6687,10 +7836,30 @@ var FEEDBACK_UPDATE_EXAMPLES = [
6687
7836
  IsPositive: false
6688
7837
  }
6689
7838
  }
7839
+ },
7840
+ {
7841
+ Description: "Attach metadata read from a file",
7842
+ Command: "uip traces feedback update a1b2c3d4-0000-0000-0000-000000000002 --positive --metadata-file review.json --folder-key a1b2c3d4-0000-0000-0000-000000000001",
7843
+ Output: {
7844
+ Code: "FeedbackUpdate",
7845
+ Data: {
7846
+ Id: "a1b2c3d4-0000-0000-0000-000000000002",
7847
+ IsPositive: true
7848
+ }
7849
+ }
6690
7850
  }
6691
7851
  ];
7852
+ function updateInstructions(message) {
7853
+ if (message.startsWith("Not authenticated")) {
7854
+ return "Run 'uip auth login', then run this command again.";
7855
+ }
7856
+ if (message.startsWith("Insufficient permissions")) {
7857
+ return "Ask a tenant admin to grant Logs.View and Logs.Create on this folder.";
7858
+ }
7859
+ return "Verify the feedback ID and --folder-key, then retry.";
7860
+ }
6692
7861
  function registerUpdateCommand(program2) {
6693
- program2.command("update [id]").description("Update feedback (isPositive, comment, categories)").examples(FEEDBACK_UPDATE_EXAMPLES).option("--positive", "Change to positive feedback").option("--negative", "Change to negative feedback").option("--comment <text>", "Updated comment (max 4000 chars)").option("--comment-file <file>", "Read updated comment from file; use '-' for stdin").option("--category <tag>", "Replacement category tags (repeatable)", collect, []).option("--folder-key <guid>", "Folder key (required)").addOption(createHiddenDeprecatedTenantOption("--tenant <name>")).trackedAction(processContext, async (id, opts) => {
7862
+ program2.command("update [id]").description("Update feedback (isPositive, comment, metadata, categories)").examples(FEEDBACK_UPDATE_EXAMPLES).option("--positive", "Change to positive feedback").option("--negative", "Change to negative feedback").option("--comment <text>", "Updated comment (max 1048576 chars)").option("--comment-file <file>", "Read updated comment from file; use '-' for stdin").option("--metadata <json>", "Updated metadata; must be valid JSON (max 1048576 chars)").option("--metadata-file <file>", "Read updated metadata from file; use '-' for stdin").option("--category <tag>", "Replacement category tags (repeatable)", collect, []).option("--folder-key <guid>", "Folder key (required)").addOption(createHiddenDeprecatedTenantOption("--tenant <name>")).trackedAction(processContext, async (id, opts) => {
6694
7863
  if (!id) {
6695
7864
  OutputFormatter.error({
6696
7865
  Result: RESULTS.Failure,
@@ -6731,43 +7900,29 @@ function registerUpdateCommand(program2) {
6731
7900
  processContext.exit(1);
6732
7901
  return;
6733
7902
  }
6734
- if (opts.comment && opts.commentFile) {
6735
- OutputFormatter.error({
6736
- Result: RESULTS.Failure,
6737
- Code: "FeedbackUpdate",
6738
- Message: "--comment and --comment-file are mutually exclusive",
6739
- Instructions: "Provide either --comment or --comment-file"
6740
- });
6741
- processContext.exit(1);
7903
+ const texts = await resolveFeedbackText("FeedbackUpdate", [
7904
+ commentSource(opts),
7905
+ metadataSource(opts)
7906
+ ]);
7907
+ if (!texts) {
6742
7908
  return;
6743
7909
  }
6744
- let comment = opts.comment;
6745
- if (opts.commentFile) {
6746
- const [readError, text] = await catchError2(readCommentFile(opts.commentFile));
6747
- if (readError) {
6748
- OutputFormatter.error({
6749
- Result: RESULTS.Failure,
6750
- Code: "FeedbackUpdate",
6751
- Message: readError.message
6752
- });
6753
- processContext.exit(1);
6754
- return;
6755
- }
6756
- comment = text;
6757
- }
6758
- const [error, result] = await catchError2(updateFeedback(id, {
7910
+ const [comment, metadata] = texts;
7911
+ const [error, result] = await catchError(updateFeedback(id, {
6759
7912
  isPositive: !!opts.positive,
6760
7913
  comment,
6761
- categories: opts.category.map((c) => ({
7914
+ metadata,
7915
+ categories: opts.category.length > 0 ? opts.category.map((c) => ({
6762
7916
  Id: "00000000-0000-0000-0000-000000000000",
6763
7917
  Category: c
6764
- }))
7918
+ })) : undefined
6765
7919
  }, { tenant: opts.tenant, folderKey: opts.folderKey }));
6766
7920
  if (error) {
6767
7921
  OutputFormatter.error({
6768
7922
  Result: RESULTS.Failure,
6769
7923
  Code: "FeedbackUpdate",
6770
- Message: error.message
7924
+ Message: error.message,
7925
+ Instructions: updateInstructions(error.message)
6771
7926
  });
6772
7927
  processContext.exit(1);
6773
7928
  return;
@@ -7060,7 +8215,7 @@ class TextApiResponse {
7060
8215
  var package_default2 = {
7061
8216
  name: "@uipath/orchestrator-sdk",
7062
8217
  license: "MIT",
7063
- version: "1.201.0",
8218
+ version: "1.202.0",
7064
8219
  repository: {
7065
8220
  type: "git",
7066
8221
  url: "https://github.com/UiPath/cli.git",
@@ -10894,14 +12049,14 @@ async function getTraceIdForJob(jobKey, options) {
10894
12049
  throw new Error(`Invalid job key format: ${jobKey}`);
10895
12050
  }
10896
12051
  const folder = await resolveFolder({ folderPath: options.folderPath, folderKey: options.folderKey }, { tenant: options.tenant });
10897
- const [apiError, api] = await catchError2(createApiClient(JobsApi, {
12052
+ const [apiError, api] = await catchError(createApiClient(JobsApi, {
10898
12053
  tenant: options.tenant,
10899
12054
  folderId: folder?.id.toString()
10900
12055
  }));
10901
12056
  if (apiError) {
10902
12057
  throw new Error(apiError.message);
10903
12058
  }
10904
- const [jobsError, response] = await catchError2(api.jobsGet({
12059
+ const [jobsError, response] = await catchError(api.jobsGet({
10905
12060
  $filter: `Key eq ${quoteODataStringLiteral(jobKey)}`,
10906
12061
  $top: 1
10907
12062
  }));
@@ -10917,7 +12072,7 @@ async function getTraceIdForJob(jobKey, options) {
10917
12072
  return jobTraceId ?? resolvedJobKey;
10918
12073
  }
10919
12074
  async function getSpansForTrace(traceId, options) {
10920
- const [loginError, loginStatus2] = await catchError2(getLoginStatusAsync());
12075
+ const [loginError, loginStatus2] = await catchError(getLoginStatusAsync());
10921
12076
  if (loginError) {
10922
12077
  throw new Error(loginError.message);
10923
12078
  }
@@ -10977,7 +12132,7 @@ var registerSpansCommand = (program2) => {
10977
12132
  spans.command("get").description("Get all spans by trace ID, or by job key as an alternative").argument("[trace-id]", "Trace ID (32-char hex or GUID format)").option("--job-key <guid>", "Orchestrator job key (GUID) — alternative to trace-id").addOption(createHiddenDeprecatedTenantOption("-t, --tenant <name>")).option("--folder-path <path>", "Orchestrator folder path").option("--folder-key <guid>", "Orchestrator folder key (GUID)").examples(SPANS_GET_EXAMPLES).trackedAction(processContext, async (traceId, options) => {
10978
12133
  let resolvedTraceId;
10979
12134
  if (options.jobKey) {
10980
- const [traceIdError, tid] = await catchError2(getTraceIdForJob(options.jobKey, options));
12135
+ const [traceIdError, tid] = await catchError(getTraceIdForJob(options.jobKey, options));
10981
12136
  if (traceIdError) {
10982
12137
  OutputFormatter.error({
10983
12138
  Result: RESULTS.Failure,
@@ -10999,7 +12154,7 @@ var registerSpansCommand = (program2) => {
10999
12154
  processContext.exit(1);
11000
12155
  return;
11001
12156
  }
11002
- const [spansError, spans2] = await catchError2(getSpansForTrace(resolvedTraceId, options));
12157
+ const [spansError, spans2] = await catchError(getSpansForTrace(resolvedTraceId, options));
11003
12158
  if (spansError) {
11004
12159
  OutputFormatter.error({
11005
12160
  Result: RESULTS.Failure,
@@ -11031,4 +12186,4 @@ var registerCommands = async (program2) => {
11031
12186
 
11032
12187
  export { Command, metadata, registerCommands };
11033
12188
 
11034
- //# debugId=901F89C24966375F64756E2164756E21
12189
+ //# debugId=631FFFA7A2D1C45964756E2164756E21