@uipath/coder-tool 1.201.0-preview.133 → 1.202.0-preview.134

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();
@@ -2109,81 +2097,402 @@ var require_commander = __commonJS((exports) => {
2109
2097
  exports.InvalidOptionArgumentError = InvalidArgumentError;
2110
2098
  });
2111
2099
 
2112
- // ../common/src/catch-error.ts
2113
- function isPromiseLike(value) {
2114
- return value !== null && typeof value === "object" && typeof value.then === "function";
2115
- }
2116
- function catchError2(fnOrPromise) {
2117
- if (isPromiseLike(fnOrPromise)) {
2118
- return settlePromiseLike(fnOrPromise);
2100
+ // ../filesystem/src/node.ts
2101
+ import { randomUUID } from "node:crypto";
2102
+ import { existsSync } from "node:fs";
2103
+ import * as fs from "node:fs/promises";
2104
+ import * as os from "node:os";
2105
+ import * as path from "node:path";
2106
+ var LOCK_HEARTBEAT_MS = 5000;
2107
+ var LOCK_STALE_MS = 15000;
2108
+ var LOCK_MAX_WAIT_MS = 20000;
2109
+ var LOCK_MAX_HOLD_MS = 60000;
2110
+ var LOCK_RETRY_MIN_MS = 100;
2111
+ var LOCK_RETRY_JITTER_MS = 200;
2112
+
2113
+ class NodeFileSystem {
2114
+ path = {
2115
+ join: path.join,
2116
+ resolve: path.resolve,
2117
+ relative: path.relative,
2118
+ dirname: path.dirname,
2119
+ isAbsolute: path.isAbsolute,
2120
+ basename: path.basename
2121
+ };
2122
+ env = {
2123
+ cwd: process.cwd,
2124
+ homedir: os.homedir,
2125
+ tmpdir: os.tmpdir,
2126
+ getenv: (key) => process.env[key]
2127
+ };
2128
+ utils = {
2129
+ open: async (url) => {
2130
+ const { default: open } = await import("./index-sby22td6.js");
2131
+ await open(url);
2132
+ }
2133
+ };
2134
+ async readFile(path2, options) {
2135
+ try {
2136
+ if (options) {
2137
+ return await fs.readFile(path2, "utf-8");
2138
+ }
2139
+ return await fs.readFile(path2);
2140
+ } catch (error) {
2141
+ if (this.isEnoent(error))
2142
+ return null;
2143
+ throw error;
2144
+ }
2119
2145
  }
2120
- try {
2121
- const result = fnOrPromise();
2122
- if (isPromiseLike(result)) {
2123
- return settlePromiseLike(result);
2146
+ async writeFile(filePath, data) {
2147
+ const dir = path.dirname(filePath);
2148
+ if (dir) {
2149
+ await fs.mkdir(dir, { recursive: true });
2124
2150
  }
2125
- return [undefined, result];
2126
- } catch (error) {
2127
- return [
2128
- error instanceof Error ? error : new Error(String(error)),
2129
- undefined
2130
- ];
2151
+ await fs.writeFile(filePath, data);
2152
+ }
2153
+ async appendFile(filePath, data) {
2154
+ const dir = path.dirname(filePath);
2155
+ if (dir) {
2156
+ await fs.mkdir(dir, { recursive: true });
2157
+ }
2158
+ await fs.appendFile(filePath, data);
2159
+ }
2160
+ async readdir(dirPath) {
2161
+ try {
2162
+ return await fs.readdir(dirPath);
2163
+ } catch (error) {
2164
+ if (this.isEnoent(error))
2165
+ return [];
2166
+ throw error;
2167
+ }
2168
+ }
2169
+ async stat(filePath) {
2170
+ try {
2171
+ const stats = await fs.stat(filePath);
2172
+ return {
2173
+ isFile: () => stats.isFile(),
2174
+ isDirectory: () => stats.isDirectory(),
2175
+ size: stats.size,
2176
+ mtimeMs: stats.mtimeMs
2177
+ };
2178
+ } catch (error) {
2179
+ if (this.isEnoent(error))
2180
+ return null;
2181
+ throw error;
2182
+ }
2183
+ }
2184
+ async exists(filePath) {
2185
+ return existsSync(filePath);
2186
+ }
2187
+ async mkdir(dirPath) {
2188
+ await fs.mkdir(dirPath, { recursive: true });
2189
+ }
2190
+ async acquireLock(lockPath) {
2191
+ const canonicalPath = await this.canonicalizeLockTarget(lockPath);
2192
+ const lockFile = `${canonicalPath}.lock`;
2193
+ const ownerId = randomUUID();
2194
+ const start = Date.now();
2195
+ while (true) {
2196
+ try {
2197
+ await fs.writeFile(lockFile, ownerId, { flag: "wx" });
2198
+ return this.createLockRelease(lockFile, ownerId);
2199
+ } catch (error) {
2200
+ if (!this.hasErrnoCode(error, "EEXIST")) {
2201
+ throw error;
2202
+ }
2203
+ const stats = await fs.stat(lockFile).catch(() => null);
2204
+ if (stats && Date.now() - stats.mtimeMs > LOCK_STALE_MS) {
2205
+ const reclaimed = await fs.rm(lockFile, { force: true }).then(() => true).catch(() => false);
2206
+ if (reclaimed)
2207
+ continue;
2208
+ }
2209
+ if (Date.now() - start > LOCK_MAX_WAIT_MS) {
2210
+ throw new Error(`ELOCKED: timed out waiting for lock on ${canonicalPath}`);
2211
+ }
2212
+ await new Promise((resolve2) => setTimeout(resolve2, LOCK_RETRY_MIN_MS + Math.random() * LOCK_RETRY_JITTER_MS));
2213
+ }
2214
+ }
2215
+ }
2216
+ async canonicalizeLockTarget(lockPath) {
2217
+ const absolute = path.resolve(lockPath);
2218
+ const fullReal = await fs.realpath(absolute).catch(() => null);
2219
+ if (fullReal)
2220
+ return fullReal;
2221
+ const parent = path.dirname(absolute);
2222
+ const base = path.basename(absolute);
2223
+ const canonicalParent = await fs.realpath(parent).catch(() => parent);
2224
+ return path.join(canonicalParent, base);
2225
+ }
2226
+ createLockRelease(lockFile, ownerId) {
2227
+ const heartbeatStart = Date.now();
2228
+ let heartbeatTimer;
2229
+ let stopped = false;
2230
+ const stopHeartbeat = () => {
2231
+ stopped = true;
2232
+ if (heartbeatTimer)
2233
+ clearTimeout(heartbeatTimer);
2234
+ };
2235
+ const scheduleNextHeartbeat = () => {
2236
+ if (stopped)
2237
+ return;
2238
+ if (Date.now() - heartbeatStart >= LOCK_MAX_HOLD_MS) {
2239
+ stopped = true;
2240
+ return;
2241
+ }
2242
+ heartbeatTimer = setTimeout(() => {
2243
+ runHeartbeat();
2244
+ }, LOCK_HEARTBEAT_MS);
2245
+ heartbeatTimer.unref?.();
2246
+ };
2247
+ const runHeartbeat = async () => {
2248
+ if (stopped)
2249
+ return;
2250
+ const current = await fs.readFile(lockFile, "utf-8").catch(() => null);
2251
+ if (stopped)
2252
+ return;
2253
+ if (current !== ownerId) {
2254
+ stopped = true;
2255
+ return;
2256
+ }
2257
+ const now = Date.now() / 1000;
2258
+ await fs.utimes(lockFile, now, now).catch(() => {});
2259
+ scheduleNextHeartbeat();
2260
+ };
2261
+ scheduleNextHeartbeat();
2262
+ let released = false;
2263
+ return async () => {
2264
+ if (released)
2265
+ return;
2266
+ released = true;
2267
+ stopHeartbeat();
2268
+ const current = await fs.readFile(lockFile, "utf-8").catch(() => null);
2269
+ if (current === ownerId) {
2270
+ await fs.rm(lockFile, { force: true });
2271
+ }
2272
+ };
2273
+ }
2274
+ async rm(filePath) {
2275
+ await fs.rm(filePath, { recursive: true, force: true });
2276
+ }
2277
+ async rename(oldPath, newPath) {
2278
+ await fs.rename(oldPath, newPath);
2279
+ }
2280
+ async realpath(filePath) {
2281
+ try {
2282
+ return await fs.realpath(filePath);
2283
+ } catch (error) {
2284
+ if (this.isEnoent(error))
2285
+ return filePath;
2286
+ throw error;
2287
+ }
2288
+ }
2289
+ async getTempDir() {
2290
+ return await fs.mkdtemp(path.join(os.tmpdir(), "uipath-fs-"));
2291
+ }
2292
+ async copyDirectory(sourcePath, destPath) {
2293
+ const sourceStats = await this.stat(sourcePath);
2294
+ if (!sourceStats) {
2295
+ throw new Error(`Source directory does not exist: ${sourcePath}`);
2296
+ }
2297
+ if (!sourceStats.isDirectory()) {
2298
+ throw new Error(`Source path is not a directory: ${sourcePath}`);
2299
+ }
2300
+ await this.mkdir(destPath);
2301
+ const entries = await this.readdir(sourcePath);
2302
+ for (const entry of entries) {
2303
+ const srcEntry = path.join(sourcePath, entry);
2304
+ const destEntry = path.join(destPath, entry);
2305
+ const entryStats = await this.stat(srcEntry);
2306
+ if (!entryStats)
2307
+ continue;
2308
+ if (entryStats.isDirectory()) {
2309
+ await this.copyDirectory(srcEntry, destEntry);
2310
+ } else if (entryStats.isFile()) {
2311
+ const content = await this.readFile(srcEntry);
2312
+ if (content !== null) {
2313
+ await this.writeFile(destEntry, content);
2314
+ }
2315
+ }
2316
+ }
2317
+ }
2318
+ isEnoent(error) {
2319
+ return this.hasErrnoCode(error, "ENOENT");
2320
+ }
2321
+ hasErrnoCode(error, code) {
2322
+ return typeof error === "object" && error !== null && "code" in error && error.code === code;
2131
2323
  }
2132
- }
2133
- function settlePromiseLike(thenable) {
2134
- return Promise.resolve(thenable).then((data) => [undefined, data]).catch((error) => [
2135
- error instanceof Error ? error : new Error(String(error)),
2136
- undefined
2137
- ]);
2138
2324
  }
2139
2325
 
2140
- // ../common/src/error-handler.ts
2141
- var NETWORK_ERROR_CODES = new Set([
2142
- "ECONNREFUSED",
2143
- "ECONNRESET",
2144
- "ENOTFOUND",
2145
- "EAI_AGAIN",
2146
- "ETIMEDOUT",
2147
- "EPIPE",
2148
- "EHOSTUNREACH",
2149
- "ENETUNREACH",
2150
- "EAI_FAIL"
2326
+ // ../filesystem/src/index.ts
2327
+ var fsInstance = new NodeFileSystem;
2328
+ var getFileSystem = () => fsInstance;
2329
+
2330
+ // ../common/src/telemetry/pseudonymize.ts
2331
+ var PSEUDONYM_DOMAIN = "uipath-cli/telemetry/pseudonym/v1:";
2332
+ var PSEUDONYM_HEX_LENGTH = 32;
2333
+ var SHA256_K = new Uint32Array([
2334
+ 1116352408,
2335
+ 1899447441,
2336
+ 3049323471,
2337
+ 3921009573,
2338
+ 961987163,
2339
+ 1508970993,
2340
+ 2453635748,
2341
+ 2870763221,
2342
+ 3624381080,
2343
+ 310598401,
2344
+ 607225278,
2345
+ 1426881987,
2346
+ 1925078388,
2347
+ 2162078206,
2348
+ 2614888103,
2349
+ 3248222580,
2350
+ 3835390401,
2351
+ 4022224774,
2352
+ 264347078,
2353
+ 604807628,
2354
+ 770255983,
2355
+ 1249150122,
2356
+ 1555081692,
2357
+ 1996064986,
2358
+ 2554220882,
2359
+ 2821834349,
2360
+ 2952996808,
2361
+ 3210313671,
2362
+ 3336571891,
2363
+ 3584528711,
2364
+ 113926993,
2365
+ 338241895,
2366
+ 666307205,
2367
+ 773529912,
2368
+ 1294757372,
2369
+ 1396182291,
2370
+ 1695183700,
2371
+ 1986661051,
2372
+ 2177026350,
2373
+ 2456956037,
2374
+ 2730485921,
2375
+ 2820302411,
2376
+ 3259730800,
2377
+ 3345764771,
2378
+ 3516065817,
2379
+ 3600352804,
2380
+ 4094571909,
2381
+ 275423344,
2382
+ 430227734,
2383
+ 506948616,
2384
+ 659060556,
2385
+ 883997877,
2386
+ 958139571,
2387
+ 1322822218,
2388
+ 1537002063,
2389
+ 1747873779,
2390
+ 1955562222,
2391
+ 2024104815,
2392
+ 2227730452,
2393
+ 2361852424,
2394
+ 2428436474,
2395
+ 2756734187,
2396
+ 3204031479,
2397
+ 3329325298
2151
2398
  ]);
2152
- var TLS_ERROR_CODES = new Set([
2153
- "SELF_SIGNED_CERT_IN_CHAIN",
2154
- "DEPTH_ZERO_SELF_SIGNED_CERT",
2155
- "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
2156
- "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
2157
- "UNABLE_TO_GET_ISSUER_CERT",
2158
- "CERT_HAS_EXPIRED",
2159
- "CERT_UNTRUSTED",
2160
- "ERR_TLS_CERT_ALTNAME_INVALID"
2399
+ var SHA256_INITIAL_STATE = new Uint32Array([
2400
+ 1779033703,
2401
+ 3144134277,
2402
+ 1013904242,
2403
+ 2773480762,
2404
+ 1359893119,
2405
+ 2600822924,
2406
+ 528734635,
2407
+ 1541459225
2161
2408
  ]);
2162
- 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.";
2163
- 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.";
2164
- var LOCAL_PERMISSION_ERROR_CODES = new Set(["EACCES", "EPERM", "EROFS"]);
2165
- // ../../node_modules/commander/esm.mjs
2166
- var import__ = __toESM(require_commander(), 1);
2167
- var {
2168
- program,
2169
- createCommand,
2170
- createArgument,
2171
- createOption,
2172
- CommanderError,
2173
- InvalidArgumentError,
2174
- InvalidOptionArgumentError,
2175
- Command,
2176
- Argument,
2177
- Option,
2178
- Help
2179
- } = import__.default;
2409
+ function rotr(value, bits) {
2410
+ return (value >>> bits | value << 32 - bits) >>> 0;
2411
+ }
2412
+ function sha256Hex(input) {
2413
+ const bytes = new TextEncoder().encode(input);
2414
+ const paddedLength = bytes.length + 9 + 63 >> 6 << 6;
2415
+ const buffer = new Uint8Array(paddedLength);
2416
+ buffer.set(bytes);
2417
+ buffer[bytes.length] = 128;
2418
+ const view = new DataView(buffer.buffer);
2419
+ const bitLength = bytes.length * 8;
2420
+ view.setUint32(paddedLength - 8, Math.floor(bitLength / 4294967296));
2421
+ view.setUint32(paddedLength - 4, bitLength >>> 0);
2422
+ const state = SHA256_INITIAL_STATE.slice();
2423
+ const schedule = new Uint32Array(64);
2424
+ for (let offset = 0;offset < paddedLength; offset += 64) {
2425
+ for (let i = 0;i < 16; i++) {
2426
+ schedule[i] = view.getUint32(offset + i * 4);
2427
+ }
2428
+ for (let i = 16;i < 64; i++) {
2429
+ const x = schedule[i - 15];
2430
+ const y = schedule[i - 2];
2431
+ const s0 = (rotr(x, 7) ^ rotr(x, 18) ^ x >>> 3) >>> 0;
2432
+ const s1 = (rotr(y, 17) ^ rotr(y, 19) ^ y >>> 10) >>> 0;
2433
+ schedule[i] = schedule[i - 16] + s0 + schedule[i - 7] + s1 >>> 0;
2434
+ }
2435
+ let a = state[0];
2436
+ let b = state[1];
2437
+ let c = state[2];
2438
+ let d = state[3];
2439
+ let e = state[4];
2440
+ let f = state[5];
2441
+ let g = state[6];
2442
+ let h = state[7];
2443
+ for (let i = 0;i < 64; i++) {
2444
+ const s1 = (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) >>> 0;
2445
+ const ch = (e & f ^ ~e & g) >>> 0;
2446
+ const temp1 = h + s1 + ch + SHA256_K[i] + schedule[i] >>> 0;
2447
+ const s0 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) >>> 0;
2448
+ const maj = (a & b ^ a & c ^ b & c) >>> 0;
2449
+ const temp2 = s0 + maj >>> 0;
2450
+ h = g;
2451
+ g = f;
2452
+ f = e;
2453
+ e = d + temp1 >>> 0;
2454
+ d = c;
2455
+ c = b;
2456
+ b = a;
2457
+ a = temp1 + temp2 >>> 0;
2458
+ }
2459
+ state[0] = state[0] + a >>> 0;
2460
+ state[1] = state[1] + b >>> 0;
2461
+ state[2] = state[2] + c >>> 0;
2462
+ state[3] = state[3] + d >>> 0;
2463
+ state[4] = state[4] + e >>> 0;
2464
+ state[5] = state[5] + f >>> 0;
2465
+ state[6] = state[6] + g >>> 0;
2466
+ state[7] = state[7] + h >>> 0;
2467
+ }
2468
+ let hex = "";
2469
+ for (const word of state) {
2470
+ hex += word.toString(16).padStart(8, "0");
2471
+ }
2472
+ return hex;
2473
+ }
2474
+ function resolveSha256Hex() {
2475
+ try {
2476
+ const nodeCrypto = __require("node:crypto");
2477
+ const createHash = nodeCrypto?.createHash;
2478
+ if (typeof createHash !== "function") {
2479
+ return sha256Hex;
2480
+ }
2481
+ const native = (input) => createHash("sha256").update(input, "utf8").digest("hex");
2482
+ return native("abc") === sha256Hex("abc") ? native : sha256Hex;
2483
+ } catch {
2484
+ return sha256Hex;
2485
+ }
2486
+ }
2487
+ var cachedSha256Hex;
2488
+ function digest(input) {
2489
+ cachedSha256Hex ??= resolveSha256Hex();
2490
+ return cachedSha256Hex(input);
2491
+ }
2492
+ function pseudonymize(input) {
2493
+ return digest(`${PSEUDONYM_DOMAIN}${input}`).slice(0, PSEUDONYM_HEX_LENGTH);
2494
+ }
2180
2495
 
2181
- // ../common/src/command-examples.ts
2182
- var examplesByCommand = new WeakMap;
2183
- Command.prototype.examples = function(examples) {
2184
- examplesByCommand.set(this, examples);
2185
- return this;
2186
- };
2187
2496
  // ../common/src/singleton.ts
2188
2497
  var PREFIX = "@uipath/common/";
2189
2498
  var _g = globalThis;
@@ -2214,71 +2523,419 @@ function singleton(ctorOrName) {
2214
2523
  };
2215
2524
  }
2216
2525
 
2217
- // ../common/src/preview.ts
2218
- var previewSlot = singleton("PreviewBuild");
2219
- function setPreviewBuild(isPreview) {
2220
- previewSlot.set(isPreview);
2526
+ // ../common/src/telemetry/supplied-values.ts
2527
+ var suppliedValuesSlot = singleton("TelemetrySuppliedArgumentValues");
2528
+ function activeEntries() {
2529
+ const existing = suppliedValuesSlot.get();
2530
+ return Array.isArray(existing) ? existing : [];
2531
+ }
2532
+ var MIN_SCRUBBABLE_LENGTH = 4;
2533
+ function recordSuppliedArgumentValues(values) {
2534
+ const flat = [];
2535
+ const push = (value) => {
2536
+ if (Array.isArray(value)) {
2537
+ for (const item of value) {
2538
+ push(item);
2539
+ }
2540
+ return;
2541
+ }
2542
+ if (typeof value === "string" && value.length >= MIN_SCRUBBABLE_LENGTH) {
2543
+ flat.push(value);
2544
+ }
2545
+ };
2546
+ push(values);
2547
+ const entry = { values: flat };
2548
+ suppliedValuesSlot.set([...activeEntries(), entry]);
2549
+ return entry;
2221
2550
  }
2222
- function isPreviewBuild() {
2223
- return previewSlot.get(false) ?? false;
2551
+ function releaseSuppliedArgumentValues(entry) {
2552
+ suppliedValuesSlot.set(activeEntries().filter((held) => held !== entry));
2224
2553
  }
2225
- function previewOnly(register) {
2226
- if (isPreviewBuild()) {
2227
- register();
2554
+ function getSuppliedArgumentValues() {
2555
+ const all = new Set;
2556
+ for (const entry of activeEntries()) {
2557
+ for (const value of entry.values) {
2558
+ all.add(value);
2559
+ }
2228
2560
  }
2561
+ return [...all].sort((a, b) => b.length - a.length);
2229
2562
  }
2230
- Command.prototype.previewCommand = function(nameAndArgs, opts) {
2231
- if (isPreviewBuild()) {
2232
- return this.command(nameAndArgs, opts);
2233
- }
2234
- return new Command(nameAndArgs.split(/\s+/)[0] ?? nameAndArgs);
2235
- };
2236
2563
 
2237
- // ../common/src/output-context.ts
2238
- function createStorage() {
2239
- const [error, mod] = catchError2(() => __require("node:async_hooks"));
2240
- if (error || typeof mod?.AsyncLocalStorage !== "function") {
2241
- return {
2242
- getStore: () => {
2243
- return;
2244
- },
2245
- run: (_store, fn) => fn()
2246
- };
2247
- }
2248
- return new mod.AsyncLocalStorage;
2564
+ // ../common/src/telemetry/pii-redactor.ts
2565
+ var REDACTED = "[REDACTED]";
2566
+ var MAX_VALUE_LENGTH = 280;
2567
+ var MAX_STACK_LENGTH = 4096;
2568
+ var MAX_SCAN_LENGTH = MAX_STACK_LENGTH;
2569
+ function truncate(value, maxLength) {
2570
+ return value.length > maxLength ? `${value.slice(0, maxLength)}…` : value;
2249
2571
  }
2250
- var storageSingleton = singleton("OutputStorage");
2251
- var sinkSlot = singleton("OutputSink");
2252
- var outputStorage = storageSingleton.getOrInit(createStorage, (v) => ("getStore" in v));
2253
- var CONSOLE_FALLBACK = {
2254
- writeOut: (str) => process.stdout.write(str),
2255
- writeErr: (str) => process.stderr.write(str),
2256
- writeLog: (str) => process.stdout.write(str),
2257
- capabilities: {
2258
- isInteractive: false,
2259
- canReadInput: false,
2260
- supportsColor: false,
2261
- outputWidth: 80
2572
+ var SENSITIVE_NAME_TOKENS = new Set([
2573
+ "token",
2574
+ "tokens",
2575
+ "secret",
2576
+ "secrets",
2577
+ "password",
2578
+ "passwords",
2579
+ "pwd",
2580
+ "credential",
2581
+ "credentials",
2582
+ "auth",
2583
+ "authentication",
2584
+ "authorization",
2585
+ "authority",
2586
+ "cert",
2587
+ "certificate",
2588
+ "certificates"
2589
+ ]);
2590
+ var SENSITIVE_KEY_PREFIXES = new Set([
2591
+ "api",
2592
+ "access",
2593
+ "client",
2594
+ "private",
2595
+ "public",
2596
+ "signing",
2597
+ "encryption",
2598
+ "session",
2599
+ "master",
2600
+ "shared",
2601
+ "root",
2602
+ "ssh",
2603
+ "rsa",
2604
+ "aes",
2605
+ "hmac",
2606
+ "oauth"
2607
+ ]);
2608
+ 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;
2609
+ var EMAIL_PATTERN = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g;
2610
+ var JWT_PATTERN = /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g;
2611
+ var LONG_TOKEN_PATTERN = /\b[A-Za-z0-9_-]{40,}\b/g;
2612
+ var PADDED_BASE64_PATTERN = /[A-Za-z0-9+/]{16,}={1,2}(?![A-Za-z0-9+/=])/g;
2613
+ var BASE64_WITH_PLUS_PATTERN = /[A-Za-z0-9+/]{40,}/g;
2614
+ var USER_HOME_PATTERN = /(?<![A-Za-z0-9._-])([/\\])(Users|home|Profiles)([/\\])([^/\\]+)/gi;
2615
+ var UNC_PATH_PATTERN = /(^|[\s"'<>|=,;([{])(\\\\[^\s"'<>|]+)/g;
2616
+ 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;
2617
+ var SOURCE_FILE_EXTENSIONS = new Set([
2618
+ "ts",
2619
+ "tsx",
2620
+ "js",
2621
+ "jsx",
2622
+ "mjs",
2623
+ "cjs",
2624
+ "cts",
2625
+ "mts",
2626
+ "py",
2627
+ "cs",
2628
+ "java",
2629
+ "go",
2630
+ "rs",
2631
+ "rb",
2632
+ "php",
2633
+ "sh",
2634
+ "ps1",
2635
+ "json",
2636
+ "jsonc",
2637
+ "yaml",
2638
+ "yml",
2639
+ "xml",
2640
+ "xaml",
2641
+ "md",
2642
+ "txt",
2643
+ "log",
2644
+ "css",
2645
+ "html",
2646
+ "htm",
2647
+ "csproj",
2648
+ "nuspec",
2649
+ "sql"
2650
+ ]);
2651
+ var URL_PATTERN = /\bhttps?:\/\/[^\s,;]+/gi;
2652
+ var QUOTED_LITERAL_MAX_SPAN = 200;
2653
+ var QUOTED_LITERAL_PATTERN = new RegExp([
2654
+ `(?<![A-Za-z0-9])'(?:[^\\
2655
+ ]|\\.){2,${QUOTED_LITERAL_MAX_SPAN}}?'(?![A-Za-z0-9])`,
2656
+ `(?<![A-Za-z0-9])"(?:[^\\
2657
+ ]|\\.){2,${QUOTED_LITERAL_MAX_SPAN}}?"(?![A-Za-z0-9])`
2658
+ ].join("|"), "g");
2659
+ var JSON_BODY_PATTERN = /[{[][^{}[\]]*[:,][^{}[\]]*[\]}]/g;
2660
+ var COLLAPSED_BODY = "{…}";
2661
+ var COLLAPSED_BODY_MARKER = "\x01body\x01";
2662
+ var MAX_BODY_NESTING = 8;
2663
+ function collapseJsonBodies(text) {
2664
+ let out = text;
2665
+ for (let pass = 0;pass < MAX_BODY_NESTING; pass++) {
2666
+ const next = out.replace(JSON_BODY_PATTERN, COLLAPSED_BODY_MARKER);
2667
+ if (next === out) {
2668
+ break;
2669
+ }
2670
+ out = next;
2262
2671
  }
2263
- };
2264
- function getOutputSink() {
2265
- return outputStorage.getStore() ?? sinkSlot.get() ?? CONSOLE_FALLBACK;
2672
+ return out.split(COLLAPSED_BODY_MARKER).join(COLLAPSED_BODY);
2266
2673
  }
2267
-
2268
- // ../common/src/logger.ts
2269
- var logFilePathSlot = singleton("logFilePath");
2270
- function setGlobalLogFilePath(path) {
2271
- logFilePathSlot.set(path);
2674
+ var TRAILING_PROSE_PUNCT = /[.,;:!?)\]}>'"]+$/;
2675
+ function peelTrailingPunctuation(match) {
2676
+ const trailing = match.match(TRAILING_PROSE_PUNCT)?.[0] ?? "";
2677
+ return trailing ? [match.slice(0, -trailing.length), trailing] : [match, ""];
2272
2678
  }
2273
- function getGlobalLogFilePath() {
2274
- return logFilePathSlot.get("");
2679
+ function redactUrl(raw) {
2680
+ try {
2681
+ const url = new URL(raw);
2682
+ return `${url.protocol}//${url.host}`;
2683
+ } catch {
2684
+ return `url#${pseudonymize(raw)}`;
2685
+ }
2275
2686
  }
2276
- var DEFAULT_LOG_LEVEL = 3 /* ERROR */;
2277
-
2278
- class SimpleLogger {
2279
- __brand = "SimpleLogger";
2280
- level;
2281
- logFilePath;
2687
+ function redactValueDetectors(value, maxLength = MAX_VALUE_LENGTH) {
2688
+ let out = truncate(value, MAX_SCAN_LENGTH);
2689
+ out = out.replace(JWT_PATTERN, () => REDACTED);
2690
+ out = out.replace(URL_PATTERN, (match) => {
2691
+ const [core, trailing] = peelTrailingPunctuation(match);
2692
+ return `${redactUrl(core)}${trailing}`;
2693
+ });
2694
+ out = out.replace(USER_HOME_PATTERN, (_match, sep1, folder, sep2) => `${sep1}${folder}${sep2}<user>`);
2695
+ out = out.replace(UNC_PATH_PATTERN, (_match, before, path2) => {
2696
+ const [core, trailing] = peelTrailingPunctuation(path2);
2697
+ return `${before}unc#${pseudonymize(core)}${trailing}`;
2698
+ });
2699
+ out = out.replace(EMAIL_PATTERN, (match) => `email#${pseudonymize(match)}`);
2700
+ out = out.replace(UUID_PATTERN, (match) => `uuid#${pseudonymize(match)}`);
2701
+ out = out.replace(HOST_PORT_PATTERN, (match) => {
2702
+ const split = match.lastIndexOf(":");
2703
+ const host = match.slice(0, split);
2704
+ const extension = host.slice(host.lastIndexOf(".") + 1).toLowerCase();
2705
+ if (SOURCE_FILE_EXTENSIONS.has(extension)) {
2706
+ return match;
2707
+ }
2708
+ return `host#${pseudonymize(host)}:${match.slice(split + 1)}`;
2709
+ });
2710
+ out = out.replace(PADDED_BASE64_PATTERN, () => REDACTED);
2711
+ out = out.replace(BASE64_WITH_PLUS_PATTERN, (match) => match.includes("+") ? REDACTED : match);
2712
+ out = out.replace(LONG_TOKEN_PATTERN, () => REDACTED);
2713
+ return truncate(out, maxLength);
2714
+ }
2715
+ function redactSpanName(name) {
2716
+ return redactValueDetectors(truncate(name, MAX_SCAN_LENGTH).replace(QUOTED_LITERAL_PATTERN, (match) => `${match[0]}<redacted>${match[0]}`));
2717
+ }
2718
+ var HTTP_DEPENDENCY_NAME = /^([A-Z]+) (\/.*)$/s;
2719
+ function redactHttpDependencyName(name) {
2720
+ const parts = HTTP_DEPENDENCY_NAME.exec(name);
2721
+ if (!parts) {
2722
+ return redactMessage(name);
2723
+ }
2724
+ return `${parts[1]} ${redactMessage(parts[2])}`;
2725
+ }
2726
+ function redactMessage(value) {
2727
+ let out = collapseJsonBodies(truncate(value, MAX_SCAN_LENGTH)).replace(QUOTED_LITERAL_PATTERN, (match) => `${match[0]}<redacted>${match[0]}`);
2728
+ for (const supplied of getSuppliedArgumentValues()) {
2729
+ out = out.split(supplied).join(REDACTED);
2730
+ }
2731
+ return redactValueDetectors(out);
2732
+ }
2733
+ var MESSAGE_NAMES = new Set([
2734
+ "message",
2735
+ "errormessage",
2736
+ "errmessage",
2737
+ "error_message",
2738
+ "msg",
2739
+ "detail",
2740
+ "details",
2741
+ "reason",
2742
+ "instructions",
2743
+ "warning"
2744
+ ]);
2745
+ function isFreeFormValue(name, value) {
2746
+ return MESSAGE_NAMES.has(name.toLowerCase()) || /['"{[]/.test(value);
2747
+ }
2748
+ function redactError(error) {
2749
+ const safe = new Error(redactMessage(error.message ?? ""));
2750
+ safe.name = error.name;
2751
+ safe.stack = typeof error.stack === "string" ? redactStack(error.stack) : undefined;
2752
+ return safe;
2753
+ }
2754
+ function redactStack(stack) {
2755
+ const bounded = truncate(stack, MAX_STACK_LENGTH);
2756
+ const firstBreak = bounded.indexOf(`
2757
+ `);
2758
+ if (firstBreak === -1) {
2759
+ return redactMessage(bounded);
2760
+ }
2761
+ return `${redactMessage(bounded.slice(0, firstBreak))}
2762
+ ${redactValueDetectors(bounded.slice(firstBreak + 1), MAX_STACK_LENGTH)}`;
2763
+ }
2764
+ function nameTokens(name) {
2765
+ 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);
2766
+ }
2767
+ function isSensitiveName(name) {
2768
+ const tokens = nameTokens(name);
2769
+ for (let i = 0;i < tokens.length; i++) {
2770
+ const token = tokens[i];
2771
+ if (SENSITIVE_NAME_TOKENS.has(token)) {
2772
+ return true;
2773
+ }
2774
+ if (token === "key" || token === "keys") {
2775
+ const prev = tokens[i - 1];
2776
+ if (prev && SENSITIVE_KEY_PREFIXES.has(prev)) {
2777
+ return true;
2778
+ }
2779
+ }
2780
+ }
2781
+ return false;
2782
+ }
2783
+ function redactProperty(name, value) {
2784
+ if (value === undefined || value === null) {
2785
+ return;
2786
+ }
2787
+ if (isSensitiveName(name)) {
2788
+ return REDACTED;
2789
+ }
2790
+ if (typeof value === "boolean" || typeof value === "number") {
2791
+ return value;
2792
+ }
2793
+ if (typeof value !== "string") {
2794
+ return "[OBJECT]";
2795
+ }
2796
+ return isFreeFormValue(name, value) ? redactMessage(value) : redactValueDetectors(value);
2797
+ }
2798
+ function redactProperties(properties) {
2799
+ const out = {};
2800
+ for (const [name, value] of Object.entries(properties)) {
2801
+ const redacted = redactProperty(name, value);
2802
+ if (redacted !== undefined) {
2803
+ out[name] = redacted;
2804
+ }
2805
+ }
2806
+ return out;
2807
+ }
2808
+
2809
+ // ../common/src/catch-error.ts
2810
+ var MAX_SERIALIZED_LENGTH = 500;
2811
+ var TRUNCATION_SUFFIX = "…(truncated)";
2812
+ var REDACTED2 = "[REDACTED]";
2813
+ function cap(text) {
2814
+ return text.length > MAX_SERIALIZED_LENGTH ? `${text.slice(0, MAX_SERIALIZED_LENGTH)}${TRUNCATION_SUFFIX}` : text;
2815
+ }
2816
+ function omitSensitive(key, value) {
2817
+ return key.length > 0 && isSensitiveName(key) ? REDACTED2 : value;
2818
+ }
2819
+ function describeThrownValue(value) {
2820
+ if (typeof value !== "object" || value === null) {
2821
+ return String(value);
2822
+ }
2823
+ let message;
2824
+ try {
2825
+ message = value.message;
2826
+ } catch {
2827
+ message = undefined;
2828
+ }
2829
+ if (typeof message === "string" && message.length > 0) {
2830
+ return cap(message);
2831
+ }
2832
+ try {
2833
+ const json = JSON.stringify(value, omitSensitive);
2834
+ if (json !== undefined) {
2835
+ return cap(json);
2836
+ }
2837
+ } catch {}
2838
+ return String(value);
2839
+ }
2840
+ function toError(error) {
2841
+ return error instanceof Error ? error : new Error(describeThrownValue(error), { cause: error });
2842
+ }
2843
+ function isPromiseLike(value) {
2844
+ return value !== null && typeof value === "object" && typeof value.then === "function";
2845
+ }
2846
+ function catchError(fnOrPromise) {
2847
+ if (isPromiseLike(fnOrPromise)) {
2848
+ return settlePromiseLike(fnOrPromise);
2849
+ }
2850
+ try {
2851
+ const result = fnOrPromise();
2852
+ if (isPromiseLike(result)) {
2853
+ return settlePromiseLike(result);
2854
+ }
2855
+ return [undefined, result];
2856
+ } catch (error) {
2857
+ return [toError(error), undefined];
2858
+ }
2859
+ }
2860
+ function settlePromiseLike(thenable) {
2861
+ return Promise.resolve(thenable).then((data) => [undefined, data]).catch((error) => [toError(error), undefined]);
2862
+ }
2863
+
2864
+ // ../common/src/error-handler.ts
2865
+ var NETWORK_ERROR_CODES = new Set([
2866
+ "ECONNREFUSED",
2867
+ "ECONNRESET",
2868
+ "ENOTFOUND",
2869
+ "EAI_AGAIN",
2870
+ "ETIMEDOUT",
2871
+ "EPIPE",
2872
+ "EHOSTUNREACH",
2873
+ "ENETUNREACH",
2874
+ "EAI_FAIL"
2875
+ ]);
2876
+ var TLS_ERROR_CODES = new Set([
2877
+ "SELF_SIGNED_CERT_IN_CHAIN",
2878
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
2879
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
2880
+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
2881
+ "UNABLE_TO_GET_ISSUER_CERT",
2882
+ "CERT_HAS_EXPIRED",
2883
+ "CERT_UNTRUSTED",
2884
+ "ERR_TLS_CERT_ALTNAME_INVALID"
2885
+ ]);
2886
+ 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.";
2887
+ 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.";
2888
+ var LOCAL_PERMISSION_ERROR_CODES = new Set(["EACCES", "EPERM", "EROFS"]);
2889
+ // ../common/src/exit-code.ts
2890
+ function setExitCode(code) {
2891
+ process.exitCode = code;
2892
+ }
2893
+
2894
+ // ../common/src/output-context.ts
2895
+ function createStorage() {
2896
+ const [error, mod] = catchError(() => __require("node:async_hooks"));
2897
+ if (error || typeof mod?.AsyncLocalStorage !== "function") {
2898
+ return {
2899
+ getStore: () => {
2900
+ return;
2901
+ },
2902
+ run: (_store, fn) => fn()
2903
+ };
2904
+ }
2905
+ return new mod.AsyncLocalStorage;
2906
+ }
2907
+ var storageSingleton = singleton("OutputStorage");
2908
+ var sinkSlot = singleton("OutputSink");
2909
+ var outputStorage = storageSingleton.getOrInit(createStorage, (v) => ("getStore" in v));
2910
+ var CONSOLE_FALLBACK = {
2911
+ writeOut: (str) => process.stdout.write(str),
2912
+ writeErr: (str) => process.stderr.write(str),
2913
+ writeLog: (str) => process.stdout.write(str),
2914
+ capabilities: {
2915
+ isInteractive: false,
2916
+ canReadInput: false,
2917
+ supportsColor: false,
2918
+ outputWidth: 80
2919
+ }
2920
+ };
2921
+ function getOutputSink() {
2922
+ return outputStorage.getStore() ?? sinkSlot.get() ?? CONSOLE_FALLBACK;
2923
+ }
2924
+
2925
+ // ../common/src/logger.ts
2926
+ var logFilePathSlot = singleton("logFilePath");
2927
+ function setGlobalLogFilePath(path2) {
2928
+ logFilePathSlot.set(path2);
2929
+ }
2930
+ function getGlobalLogFilePath() {
2931
+ return logFilePathSlot.get("");
2932
+ }
2933
+ var DEFAULT_LOG_LEVEL = 3 /* ERROR */;
2934
+
2935
+ class SimpleLogger {
2936
+ __brand = "SimpleLogger";
2937
+ level;
2938
+ logFilePath;
2282
2939
  fileLoggingEnabled;
2283
2940
  pendingWrites = Promise.resolve();
2284
2941
  pendingInit = Promise.resolve();
@@ -2305,7 +2962,7 @@ class SimpleLogger {
2305
2962
  }
2306
2963
  return DEFAULT_LOG_LEVEL;
2307
2964
  }
2308
- const [localStorageError, hasDebug] = catchError2(() => typeof localStorage !== "undefined" && !!localStorage.getItem("debug"));
2965
+ const [localStorageError, hasDebug] = catchError(() => typeof localStorage !== "undefined" && !!localStorage.getItem("debug"));
2309
2966
  if (!localStorageError && hasDebug) {
2310
2967
  return 0 /* DEBUG */;
2311
2968
  }
@@ -2336,54 +2993,49 @@ class SimpleLogger {
2336
2993
  return this.fileLoggingEnabled || !!getGlobalLogFilePath();
2337
2994
  }
2338
2995
  writeToFile(formatted) {
2339
- const path = this.logFilePath || getGlobalLogFilePath();
2340
- if (!path)
2996
+ const path2 = this.logFilePath || getGlobalLogFilePath();
2997
+ if (!path2)
2341
2998
  return;
2342
2999
  const timestamp = new Date().toISOString();
2343
3000
  this.pendingWrites = Promise.all([
2344
3001
  this.pendingWrites,
2345
3002
  this.pendingInit
2346
- ]).then(() => getFileSystem().appendFile(path, `${timestamp} ${formatted}`).catch(() => {}));
3003
+ ]).then(() => getFileSystem().appendFile(path2, `${timestamp} ${formatted}`).catch(() => {}));
2347
3004
  }
2348
- debug(message, ...args) {
2349
- if (this.level > 0 /* DEBUG */)
2350
- return;
2351
- const formatted = this.format(`[DEBUG] ${message}`, args);
3005
+ write(formatted) {
2352
3006
  if (this.isFileLoggingActive()) {
2353
3007
  this.writeToFile(formatted);
2354
3008
  } else {
2355
3009
  getOutputSink().writeErr(formatted);
2356
3010
  }
2357
3011
  }
3012
+ debug(message, ...args) {
3013
+ if (this.level > 0 /* DEBUG */)
3014
+ return;
3015
+ const formatted = this.format(`[DEBUG] ${message}`, args);
3016
+ this.write(formatted);
3017
+ }
2358
3018
  info(message, ...args) {
2359
3019
  if (this.level > 1 /* INFO */)
2360
3020
  return;
2361
3021
  const formatted = this.format(message, args);
2362
- if (this.isFileLoggingActive()) {
2363
- this.writeToFile(formatted);
2364
- } else {
2365
- getOutputSink().writeErr(formatted);
2366
- }
3022
+ this.write(formatted);
2367
3023
  }
2368
3024
  warn(message, ...args) {
2369
3025
  if (this.level > 2 /* WARN */)
2370
3026
  return;
2371
3027
  const formatted = this.format(`[WARN] ${message}`, args);
2372
- if (this.isFileLoggingActive()) {
2373
- this.writeToFile(formatted);
2374
- } else {
2375
- getOutputSink().writeErr(formatted);
2376
- }
3028
+ this.write(formatted);
2377
3029
  }
2378
3030
  error(message, ...args) {
2379
3031
  if (this.level > 3 /* ERROR */)
2380
3032
  return;
2381
3033
  const formatted = this.format(`[ERROR] ${message}`, args);
2382
- if (this.isFileLoggingActive()) {
2383
- this.writeToFile(formatted);
2384
- } else {
2385
- getOutputSink().writeErr(formatted);
2386
- }
3034
+ this.write(formatted);
3035
+ }
3036
+ report(message) {
3037
+ const formatted = this.format(message, []);
3038
+ this.write(formatted);
2387
3039
  }
2388
3040
  getLevel() {
2389
3041
  return this.level;
@@ -2398,17 +3050,17 @@ class SimpleLogger {
2398
3050
  setGlobalLogFilePath("");
2399
3051
  }
2400
3052
  }
2401
- setLogFile(path) {
2402
- this.logFilePath = path;
2403
- setGlobalLogFilePath(path);
2404
- if (!path)
3053
+ setLogFile(path2) {
3054
+ this.logFilePath = path2;
3055
+ setGlobalLogFilePath(path2);
3056
+ if (!path2)
2405
3057
  return;
2406
3058
  this.fileLoggingEnabled = true;
2407
- const fs = getFileSystem();
3059
+ const fs2 = getFileSystem();
2408
3060
  this.pendingInit = (async () => {
2409
- const [error] = await catchError2((async () => {
2410
- await fs.mkdir(fs.path.dirname(path));
2411
- await fs.writeFile(path, "");
3061
+ const [error] = await catchError((async () => {
3062
+ await fs2.mkdir(fs2.path.dirname(path2));
3063
+ await fs2.writeFile(path2, "");
2412
3064
  })());
2413
3065
  if (error)
2414
3066
  this.fileLoggingEnabled = false;
@@ -2462,12 +3114,12 @@ var jmespathSlot = singleton("JmespathCodec");
2462
3114
  async function loadOutputCodecsAsync(needed) {
2463
3115
  const loads = [];
2464
3116
  if (needed.yaml && yamlSlot.get() === undefined) {
2465
- loads.push(import("./js-yaml-4ypbq2tt.js").then((mod) => {
3117
+ loads.push(import("./js-yaml-b2jq67kn.js").then((mod) => {
2466
3118
  yamlSlot.set(mod);
2467
3119
  }));
2468
3120
  }
2469
3121
  if (needed.filter && jmespathSlot.get() === undefined) {
2470
- loads.push(import("./index-2fj08e7n.js").then((mod) => {
3122
+ loads.push(import("./index-gpd94m28.js").then((mod) => {
2471
3123
  jmespathSlot.set(mod);
2472
3124
  }));
2473
3125
  }
@@ -2722,7 +3374,7 @@ function readRegistryValue(keyPath, valueName) {
2722
3374
  if (process.platform !== "win32") {
2723
3375
  return "";
2724
3376
  }
2725
- const [error, output] = catchError2(() => execFileSync("reg", ["query", keyPath, "/v", valueName], {
3377
+ const [error, output] = catchError(() => execFileSync("reg", ["query", keyPath, "/v", valueName], {
2726
3378
  encoding: "utf-8",
2727
3379
  stdio: ["pipe", "pipe", "pipe"]
2728
3380
  }));
@@ -2745,27 +3397,41 @@ class LoggerTelemetryProvider {
2745
3397
  ...this.analyticsUniqueId ? { analyticsUniqueId: this.analyticsUniqueId } : {}
2746
3398
  };
2747
3399
  }
2748
- async trackEvent(eventName, properties) {
2749
- logger.debug(formatMessage("Event", eventName, this.enrich(properties)));
3400
+ async trackEvent({ name, properties }) {
3401
+ logger.debug(formatMessage("Event", name, this.enrich(properties)));
2750
3402
  }
2751
- async trackException(error, properties) {
3403
+ async trackException({
3404
+ error,
3405
+ properties
3406
+ }) {
2752
3407
  logger.error(formatMessage("Exception", error.message, this.enrich({
2753
3408
  ...properties,
2754
3409
  stack: error.stack
2755
3410
  })));
2756
3411
  }
2757
- async trackRequest(name, duration, success, properties) {
3412
+ async trackRequest({
3413
+ name,
3414
+ durationMs,
3415
+ success,
3416
+ properties
3417
+ }) {
2758
3418
  logger.debug(formatMessage("Request", name, this.enrich({
2759
3419
  ...properties,
2760
- duration: `${duration}ms`,
3420
+ duration: `${durationMs}ms`,
2761
3421
  success
2762
3422
  })));
2763
3423
  }
2764
- async trackDependency(name, type, duration, success, properties) {
3424
+ async trackDependency({
3425
+ name,
3426
+ type,
3427
+ durationMs,
3428
+ success,
3429
+ properties
3430
+ }) {
2765
3431
  logger.debug(formatMessage("Dependency", name, this.enrich({
2766
3432
  ...properties,
2767
3433
  type,
2768
- duration: `${duration}ms`,
3434
+ duration: `${durationMs}ms`,
2769
3435
  success
2770
3436
  })));
2771
3437
  }
@@ -2992,173 +3658,45 @@ function generateRandomSession() {
2992
3658
  }
2993
3659
  return { id: hex, source: "random" };
2994
3660
  }
2995
- function resolveTelemetrySession() {
2996
- const existing = telemetrySessionSlot.get();
2997
- if (existing) {
2998
- return existing;
2999
- }
3000
- const declaredHandle = getConfiguredTelemetrySessionId();
3001
- const resolved = declaredHandle ? { id: declaredHandle, source: "declared" } : getInheritedSession(getProcessEnv2() ?? {}) ?? generateRandomSession();
3002
- telemetrySessionSlot.set(resolved);
3003
- return resolved;
3004
- }
3005
- function getTelemetrySessionSource() {
3006
- return resolveTelemetrySession().source;
3007
- }
3008
- function getTelemetryOperationId() {
3009
- const existing = telemetryOperationIdSlot.get();
3010
- if (existing) {
3011
- return existing;
3012
- }
3013
- const inboundTraceId = getInboundTraceContext()?.traceId;
3014
- const generated = inboundTraceId ?? crypto.randomUUID().replaceAll("-", "");
3015
- telemetryOperationIdSlot.set(generated);
3016
- return generated;
3017
- }
3018
- // ../common/src/telemetry/global-telemetry-properties.ts
3019
- var telemetryPropsSlot = singleton("TelemetryDefaultProps");
3020
- function getGlobalTelemetryProperties() {
3021
- return telemetryPropsSlot.get();
3022
- }
3023
-
3024
- // ../common/src/telemetry/pii-redactor.ts
3025
- var REDACTED = "[REDACTED]";
3026
- var MAX_VALUE_LENGTH = 200;
3027
- var SENSITIVE_NAME_TOKENS = new Set([
3028
- "token",
3029
- "tokens",
3030
- "secret",
3031
- "secrets",
3032
- "password",
3033
- "passwords",
3034
- "pwd",
3035
- "credential",
3036
- "credentials",
3037
- "auth",
3038
- "authentication",
3039
- "authorization",
3040
- "authority",
3041
- "cert",
3042
- "certificate",
3043
- "certificates"
3044
- ]);
3045
- var SENSITIVE_KEY_PREFIXES = new Set([
3046
- "api",
3047
- "access",
3048
- "client",
3049
- "private",
3050
- "public",
3051
- "signing",
3052
- "encryption",
3053
- "session",
3054
- "master",
3055
- "shared",
3056
- "root",
3057
- "ssh",
3058
- "rsa",
3059
- "aes",
3060
- "hmac",
3061
- "oauth"
3062
- ]);
3063
- 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;
3064
- var EMAIL_PATTERN = /\b[^\s@]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g;
3065
- var JWT_PATTERN = /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g;
3066
- var LONG_TOKEN_PATTERN = /\b[A-Za-z0-9_-]{40,}\b/g;
3067
- var USER_HOME_PATTERN = /([/\\])(Users|home)([/\\])([^/\\]+)/gi;
3068
- var URL_PATTERN = /\bhttps?:\/\/[^\s,;]+/gi;
3069
- var URL_TRAILING_PUNCT = /[.,;:!?)\]}>'"]+$/;
3070
- function shortHash(input) {
3071
- let hash = 2166136261;
3072
- for (let i = 0;i < input.length; i++) {
3073
- hash ^= input.charCodeAt(i);
3074
- hash = Math.imul(hash, 16777619);
3075
- }
3076
- return (hash >>> 0).toString(16).padStart(8, "0");
3077
- }
3078
- function redactUrl(raw) {
3079
- try {
3080
- const url = new URL(raw);
3081
- return `${url.protocol}//${url.host}`;
3082
- } catch {
3083
- return `url#${shortHash(raw)}`;
3084
- }
3085
- }
3086
- function redactValueDetectors(value) {
3087
- let out = value;
3088
- out = out.replace(JWT_PATTERN, () => REDACTED);
3089
- out = out.replace(URL_PATTERN, (match) => {
3090
- const trailing = match.match(URL_TRAILING_PUNCT)?.[0] ?? "";
3091
- const core = trailing ? match.slice(0, -trailing.length) : match;
3092
- return `${redactUrl(core)}${trailing}`;
3093
- });
3094
- out = out.replace(USER_HOME_PATTERN, (_match, sep1, folder, sep2) => `${sep1}${folder}${sep2}<user>`);
3095
- out = out.replace(EMAIL_PATTERN, (match) => `email#${shortHash(match)}`);
3096
- out = out.replace(UUID_PATTERN, (match) => `uuid#${shortHash(match)}`);
3097
- out = out.replace(LONG_TOKEN_PATTERN, () => REDACTED);
3098
- if (out.length > MAX_VALUE_LENGTH) {
3099
- out = `${out.slice(0, MAX_VALUE_LENGTH)}…`;
3100
- }
3101
- return out;
3102
- }
3103
- function redactValue(value) {
3104
- return redactValueDetectors(value);
3105
- }
3106
- function redactError(error) {
3107
- const safe = new Error(redactValueDetectors(error.message ?? ""));
3108
- safe.name = error.name;
3109
- safe.stack = typeof error.stack === "string" ? redactValueDetectors(error.stack) : undefined;
3110
- return safe;
3111
- }
3112
- function nameTokens(name) {
3113
- 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);
3114
- }
3115
- function isSensitiveName(name) {
3116
- const tokens = nameTokens(name);
3117
- for (let i = 0;i < tokens.length; i++) {
3118
- const token = tokens[i];
3119
- if (SENSITIVE_NAME_TOKENS.has(token)) {
3120
- return true;
3121
- }
3122
- if (token === "key" || token === "keys") {
3123
- const prev = tokens[i - 1];
3124
- if (prev && SENSITIVE_KEY_PREFIXES.has(prev)) {
3125
- return true;
3126
- }
3127
- }
3128
- }
3129
- return false;
3130
- }
3131
- function redactProperty(name, value) {
3132
- if (value === undefined || value === null) {
3133
- return;
3134
- }
3135
- if (isSensitiveName(name)) {
3136
- return REDACTED;
3137
- }
3138
- if (typeof value === "boolean" || typeof value === "number") {
3139
- return value;
3140
- }
3141
- if (typeof value !== "string") {
3142
- return "[OBJECT]";
3661
+ function resolveTelemetrySession() {
3662
+ const existing = telemetrySessionSlot.get();
3663
+ if (existing) {
3664
+ return existing;
3143
3665
  }
3144
- return redactValueDetectors(value);
3666
+ const declaredHandle = getConfiguredTelemetrySessionId();
3667
+ const resolved = declaredHandle ? { id: declaredHandle, source: "declared" } : getInheritedSession(getProcessEnv2() ?? {}) ?? generateRandomSession();
3668
+ telemetrySessionSlot.set(resolved);
3669
+ return resolved;
3145
3670
  }
3146
- function redactProperties(properties) {
3147
- const out = {};
3148
- for (const [name, value] of Object.entries(properties)) {
3149
- const redacted = redactProperty(name, value);
3150
- if (redacted !== undefined) {
3151
- out[name] = redacted;
3152
- }
3671
+ function getTelemetrySessionSource() {
3672
+ return resolveTelemetrySession().source;
3673
+ }
3674
+ function getTelemetryOperationId() {
3675
+ const existing = telemetryOperationIdSlot.get();
3676
+ if (existing) {
3677
+ return existing;
3153
3678
  }
3154
- return out;
3679
+ const inboundTraceId = getInboundTraceContext()?.traceId;
3680
+ const generated = inboundTraceId ?? crypto.randomUUID().replaceAll("-", "");
3681
+ telemetryOperationIdSlot.set(generated);
3682
+ return generated;
3683
+ }
3684
+ // ../common/src/telemetry/global-telemetry-properties.ts
3685
+ var telemetryPropsSlot = singleton("TelemetryDefaultProps");
3686
+ function getGlobalTelemetryProperties() {
3687
+ return telemetryPropsSlot.get();
3155
3688
  }
3156
3689
 
3157
- // ../common/src/telemetry/telemetry-service.ts
3158
- var TELEMETRY_OPERATION_ID_PROPERTY = "uip.trace.operation_id";
3159
- var TELEMETRY_PARENT_ID_PROPERTY = "uip.trace.parent_id";
3160
- var TELEMETRY_SPAN_ID_PROPERTY = "uip.trace.span_id";
3690
+ // ../common/src/telemetry/span-clock.ts
3691
+ function startSpanClock() {
3692
+ const started = performance.now();
3693
+ return {
3694
+ startedAt: new Date(performance.timeOrigin + started),
3695
+ elapsedMs: () => performance.now() - started
3696
+ };
3697
+ }
3161
3698
 
3699
+ // ../common/src/telemetry/telemetry-service.ts
3162
3700
  class TelemetryService {
3163
3701
  telemetryProvider;
3164
3702
  contextStorage;
@@ -3178,36 +3716,39 @@ class TelemetryService {
3178
3716
  this.defaultProperties = properties === undefined ? undefined : { ...this.defaultProperties, ...properties };
3179
3717
  }
3180
3718
  trackEvent(name, properties) {
3181
- const context = this.getCurrentContext();
3182
- const enrichedProperties = this.enrichPropertiesWithContext(properties, context);
3183
- this.telemetryProvider.trackEvent(name, enrichedProperties);
3719
+ this.telemetryProvider.trackEvent({
3720
+ name: redactSpanName(name),
3721
+ properties: this.enrichProperties(properties),
3722
+ ...this.leafCorrelation()
3723
+ });
3184
3724
  }
3185
- trackException(error, properties) {
3186
- const context = this.getCurrentContext();
3187
- const enrichedProperties = this.enrichPropertiesWithContext(properties, context);
3188
- this.telemetryProvider.trackException(redactError(error), enrichedProperties);
3725
+ trackException(error, properties, context) {
3726
+ this.telemetryProvider.trackException({
3727
+ error: redactError(error),
3728
+ properties: this.enrichProperties(properties),
3729
+ ...this.leafCorrelation(context)
3730
+ });
3189
3731
  }
3190
3732
  async trackRequest(name, fn, properties) {
3191
- const parentContext = this.getCurrentContext();
3733
+ const parentContext = this.getActiveContext();
3192
3734
  const operationId = parentContext?.operationId ?? this.operationId ?? getTelemetryOperationId();
3193
3735
  const parentId = parentContext ? parentContext.id : this.inboundParentIdFor(operationId);
3736
+ const clock = startSpanClock();
3194
3737
  const context = {
3195
3738
  operationId,
3196
3739
  ...parentId !== undefined ? { parentId } : {},
3197
- id: this.generateId()
3740
+ id: this.generateId(),
3741
+ startedAt: clock.startedAt
3198
3742
  };
3199
- const startTime = performance.now();
3200
3743
  try {
3201
3744
  const result = await this.contextStorage.run(context, fn);
3202
- const durationMs = performance.now() - startTime;
3203
- const enrichedProperties = this.enrichPropertiesWithContext(properties, context);
3204
- await this.telemetryProvider.trackRequest(name, durationMs, true, enrichedProperties);
3745
+ const durationMs = clock.elapsedMs();
3746
+ await this.telemetryProvider.trackRequest(this.spanFor(name, durationMs, true, properties, context));
3205
3747
  return result;
3206
3748
  } catch (error) {
3207
- const durationMs = performance.now() - startTime;
3749
+ const durationMs = clock.elapsedMs();
3208
3750
  const err = error instanceof Error ? error : new Error(String(error));
3209
- const enrichedProperties = this.enrichPropertiesWithContext({ ...properties, errorMessage: err.message }, context);
3210
- await this.telemetryProvider.trackRequest(name, durationMs, false, enrichedProperties);
3751
+ await this.telemetryProvider.trackRequest(this.spanFor(name, durationMs, false, { ...properties, errorMessage: err.message }, context));
3211
3752
  throw error;
3212
3753
  }
3213
3754
  }
@@ -3216,8 +3757,7 @@ class TelemetryService {
3216
3757
  operationId: this.operationId ?? getTelemetryOperationId(),
3217
3758
  id: this.generateId()
3218
3759
  };
3219
- const enrichedProperties = this.enrichPropertiesWithContext(properties, requestContext);
3220
- this.telemetryProvider.trackRequest(name, durationMs, success, enrichedProperties);
3760
+ this.telemetryProvider.trackRequest(this.spanFor(name, durationMs, success, properties, requestContext));
3221
3761
  }
3222
3762
  createRequestContext() {
3223
3763
  const operationId = this.operationId ?? getTelemetryOperationId();
@@ -3225,7 +3765,8 @@ class TelemetryService {
3225
3765
  return {
3226
3766
  operationId,
3227
3767
  ...parentId !== undefined ? { parentId } : {},
3228
- id: this.generateId()
3768
+ id: this.generateId(),
3769
+ startedAt: startSpanClock().startedAt
3229
3770
  };
3230
3771
  }
3231
3772
  inboundParentIdFor(operationId) {
@@ -3236,58 +3777,84 @@ class TelemetryService {
3236
3777
  return this.contextStorage.run(context, fn);
3237
3778
  }
3238
3779
  createDependencyContext() {
3239
- const parentContext = this.getCurrentContext();
3780
+ const parentContext = this.getActiveContext();
3240
3781
  if (!parentContext) {
3241
3782
  return;
3242
3783
  }
3243
3784
  return {
3244
3785
  operationId: parentContext.operationId,
3245
3786
  parentId: parentContext.id,
3246
- id: this.generateId()
3787
+ id: this.generateId(),
3788
+ startedAt: startSpanClock().startedAt
3247
3789
  };
3248
3790
  }
3249
3791
  trackDependencyResult(name, type, durationMs, success, properties, context, resultCode) {
3250
- const enrichedProperties = this.enrichPropertiesWithContext(properties, context);
3251
- this.telemetryProvider.trackDependency(redactValue(name), type, durationMs, success, enrichedProperties, resultCode);
3792
+ this.telemetryProvider.trackDependency({
3793
+ ...this.spanFor(redactHttpDependencyName(name), durationMs, success, properties, context),
3794
+ type,
3795
+ ...resultCode !== undefined ? { resultCode } : {}
3796
+ });
3252
3797
  }
3253
3798
  async trackDependencyOperation(name, type, fn, properties) {
3254
- const parentContext = this.getCurrentContext();
3799
+ const clock = startSpanClock();
3800
+ const parentContext = this.getActiveContext();
3255
3801
  const childContext = parentContext !== undefined ? {
3256
3802
  operationId: parentContext.operationId,
3257
3803
  parentId: parentContext.id,
3258
- id: this.generateId()
3259
- } : this.createRequestContext();
3260
- const startTime = performance.now();
3804
+ id: this.generateId(),
3805
+ startedAt: clock.startedAt
3806
+ } : {
3807
+ ...this.createRequestContext(),
3808
+ startedAt: clock.startedAt
3809
+ };
3261
3810
  try {
3262
3811
  const result = await this.contextStorage.run(childContext, fn);
3263
- const durationMs = performance.now() - startTime;
3264
- const enrichedProperties = this.enrichPropertiesWithContext(properties, childContext);
3265
- await this.telemetryProvider.trackDependency(name, type, durationMs, true, enrichedProperties);
3812
+ const durationMs = clock.elapsedMs();
3813
+ await this.telemetryProvider.trackDependency({
3814
+ ...this.spanFor(name, durationMs, true, properties, childContext),
3815
+ type
3816
+ });
3266
3817
  return result;
3267
3818
  } catch (error) {
3268
- const durationMs = performance.now() - startTime;
3819
+ const durationMs = clock.elapsedMs();
3269
3820
  const err = error instanceof Error ? error : new Error(String(error));
3270
- const enrichedProperties = this.enrichPropertiesWithContext({ ...properties, errorMessage: err.message }, childContext);
3271
- await this.telemetryProvider.trackDependency(name, type, durationMs, false, enrichedProperties);
3821
+ await this.telemetryProvider.trackDependency({
3822
+ ...this.spanFor(name, durationMs, false, { ...properties, errorMessage: err.message }, childContext),
3823
+ type
3824
+ });
3272
3825
  throw error;
3273
3826
  }
3274
3827
  }
3275
- getCurrentContext() {
3828
+ getActiveContext() {
3276
3829
  return this.contextStorage.getContext();
3277
3830
  }
3278
- enrichPropertiesWithContext(properties, context) {
3831
+ leafCorrelation(explicit) {
3832
+ const context = explicit ?? this.getActiveContext();
3833
+ return {
3834
+ operationId: context?.operationId ?? this.operationId ?? getTelemetryOperationId(),
3835
+ ...context !== undefined ? { parentId: context.id } : {}
3836
+ };
3837
+ }
3838
+ spanFor(name, durationMs, success, properties, context) {
3839
+ return {
3840
+ name: redactSpanName(name),
3841
+ durationMs,
3842
+ success,
3843
+ properties: this.enrichProperties(properties),
3844
+ operationId: context.operationId,
3845
+ ...context.parentId !== undefined ? { parentId: context.parentId } : {},
3846
+ id: context.id,
3847
+ ...context.startedAt !== undefined ? { startedAt: context.startedAt } : {}
3848
+ };
3849
+ }
3850
+ enrichProperties(properties) {
3279
3851
  const globalProperties = getGlobalTelemetryProperties();
3280
3852
  const enriched = {
3281
3853
  ...getExecutionContextTelemetryProperties(),
3282
3854
  ...globalProperties,
3283
3855
  ...this.defaultProperties,
3284
3856
  ...redactProperties(properties ?? {}),
3285
- [TELEMETRY_SESSION_SOURCE_PROPERTY]: getTelemetrySessionSource(),
3286
- ...context ? {
3287
- [TELEMETRY_OPERATION_ID_PROPERTY]: context.operationId,
3288
- ...context.parentId !== undefined ? { [TELEMETRY_PARENT_ID_PROPERTY]: context.parentId } : {},
3289
- [TELEMETRY_SPAN_ID_PROPERTY]: context.id
3290
- } : {}
3857
+ [TELEMETRY_SESSION_SOURCE_PROPERTY]: getTelemetrySessionSource()
3291
3858
  };
3292
3859
  return enriched;
3293
3860
  }
@@ -3304,6 +3871,81 @@ class TelemetryService {
3304
3871
  return hex;
3305
3872
  }
3306
3873
  }
3874
+ // ../common/src/timings.ts
3875
+ var TIMINGS_ENV_VAR = "UIP_TIMINGS";
3876
+ function createStorage2() {
3877
+ const [error, mod] = catchError(() => __require("node:async_hooks"));
3878
+ if (error || typeof mod?.AsyncLocalStorage !== "function") {
3879
+ return {
3880
+ getStore: () => {
3881
+ return;
3882
+ },
3883
+ run: (_store, fn) => fn()
3884
+ };
3885
+ }
3886
+ return new mod.AsyncLocalStorage;
3887
+ }
3888
+ var storageSlot = singleton("TimingStorage");
3889
+ var stateSlot = singleton("Timings");
3890
+ var rootStartedSlot = singleton("TimingsRootStarted");
3891
+ var longLivedHostSlot = singleton("TimingsLongLivedHost");
3892
+ var storage = storageSlot.getOrInit(createStorage2, (value) => ("getStore" in value));
3893
+ function newState(baseline) {
3894
+ return { baseline, httpMs: 0, httpCalls: 0 };
3895
+ }
3896
+ function getState() {
3897
+ const scoped = storage.getStore();
3898
+ if (scoped) {
3899
+ return scoped;
3900
+ }
3901
+ const pinned = livePinnedState();
3902
+ if (pinned !== undefined) {
3903
+ return pinned;
3904
+ }
3905
+ return newState(processStartIsInvocationStart() ? 0 : performance.now());
3906
+ }
3907
+ function livePinnedState() {
3908
+ const pinned = stateSlot.get();
3909
+ return pinned !== undefined && "httpCalls" in pinned && !pinned.finished ? pinned : undefined;
3910
+ }
3911
+ function processStartIsInvocationStart() {
3912
+ return !rootStartedSlot.get(false) && !longLivedHostSlot.get(false);
3913
+ }
3914
+ function timingsEnabled() {
3915
+ if (typeof process === "undefined") {
3916
+ return false;
3917
+ }
3918
+ const value = process.env?.[TIMINGS_ENV_VAR];
3919
+ if (value === undefined) {
3920
+ return false;
3921
+ }
3922
+ const normalized = value.trim().toLowerCase();
3923
+ return normalized === "1" || normalized === "true";
3924
+ }
3925
+ function recordExitCode(exitCode) {
3926
+ if (!timingsEnabled()) {
3927
+ return;
3928
+ }
3929
+ getState().exitCode = exitCode;
3930
+ }
3931
+ function invocationStartedAt() {
3932
+ return new Date(performance.timeOrigin + getState().baseline);
3933
+ }
3934
+ function invocationElapsedMs() {
3935
+ return performance.now() - getState().baseline;
3936
+ }
3937
+ function markCommandStart() {
3938
+ if (!timingsEnabled()) {
3939
+ return;
3940
+ }
3941
+ getState().commandStart = performance.now();
3942
+ }
3943
+ function recordCommandDuration(durationMs) {
3944
+ if (!timingsEnabled()) {
3945
+ return;
3946
+ }
3947
+ getState().commandMs = durationMs;
3948
+ }
3307
3949
  // ../common/src/telemetry/proxy-http-agent.ts
3308
3950
  var slot = singleton("ProxyAuthHttpsAgent");
3309
3951
 
@@ -3324,6 +3966,9 @@ function getGlobalTelemetryInstance() {
3324
3966
  }
3325
3967
  return;
3326
3968
  }
3969
+ function setGlobalTelemetryInstance(instance) {
3970
+ telemetryInstanceSlot.set(instance);
3971
+ }
3327
3972
  var _localTelemetryInstance;
3328
3973
  function getTelemetryInstance() {
3329
3974
  const global = getGlobalTelemetryInstance();
@@ -3331,6 +3976,7 @@ function getTelemetryInstance() {
3331
3976
  return global;
3332
3977
  if (!_localTelemetryInstance) {
3333
3978
  _localTelemetryInstance = new TelemetryService(new LoggerTelemetryProvider, new NodeContextStorage);
3979
+ setGlobalTelemetryInstance(_localTelemetryInstance);
3334
3980
  }
3335
3981
  return _localTelemetryInstance;
3336
3982
  }
@@ -3343,6 +3989,14 @@ var telemetry = new Proxy({}, {
3343
3989
  });
3344
3990
 
3345
3991
  // ../common/src/formatter.ts
3992
+ var ANSI_STYLES = {
3993
+ red: "\x1B[31m",
3994
+ dim: "\x1B[2m"
3995
+ };
3996
+ var ANSI_RESET = "\x1B[0m";
3997
+ function styleLine(line, style) {
3998
+ return style ? `${ANSI_STYLES[style]}${line}${ANSI_RESET}` : line;
3999
+ }
3346
4000
  var CLI_ERROR_CODES = [
3347
4001
  "invalid_argument",
3348
4002
  "authentication_required",
@@ -3381,22 +4035,6 @@ var EXIT_CODES = {
3381
4035
  ValidationError: 3,
3382
4036
  TimeoutError: 4
3383
4037
  };
3384
- class SuccessOutput {
3385
- Result = RESULTS.Success;
3386
- Code;
3387
- Data;
3388
- Pagination;
3389
- Instructions;
3390
- Log;
3391
- constructor(code, data) {
3392
- this.Code = code;
3393
- this.Data = data;
3394
- const logPath = getLogFilePath();
3395
- if (logPath) {
3396
- this.Log = logPath;
3397
- }
3398
- }
3399
- }
3400
4038
  function escapeNonAscii(jsonText) {
3401
4039
  return jsonText.replace(/[\u0080-\uffff]/g, (c) => {
3402
4040
  const hex = c.charCodeAt(0).toString(16).padStart(4, "0");
@@ -3461,19 +4099,45 @@ function toPascalCaseKey(key) {
3461
4099
  const lowerCamelKey = toLowerCamelCaseKey(key);
3462
4100
  return lowerCamelKey ? lowerCamelKey.charAt(0).toUpperCase() + lowerCamelKey.slice(1) : lowerCamelKey;
3463
4101
  }
3464
- function toPascalCaseData(value) {
4102
+ function collectVerbatimRefs(value, into) {
4103
+ if (typeof value !== "object" || value === null)
4104
+ return;
4105
+ if (into.has(value))
4106
+ return;
4107
+ into.add(value);
4108
+ for (const nested of Array.isArray(value) ? value : Object.values(value)) {
4109
+ collectVerbatimRefs(nested, into);
4110
+ }
4111
+ }
4112
+ function toPascalCaseData(value, verbatimKeys, subtrees) {
4113
+ if (subtrees?.mode === "skip" && typeof value === "object" && value !== null && subtrees.refs.has(value)) {
4114
+ return value;
4115
+ }
3465
4116
  if (Array.isArray(value))
3466
- return value.map(toPascalCaseData);
4117
+ return value.map((entry) => toPascalCaseData(entry, verbatimKeys, subtrees));
3467
4118
  if (!isPlainRecord(value))
3468
4119
  return value;
3469
4120
  const result = {};
3470
4121
  for (const [key, nestedValue] of Object.entries(value)) {
3471
- result[toPascalCaseKey(key)] = toPascalCaseData(nestedValue);
4122
+ const pascalKey = toPascalCaseKey(key);
4123
+ if (verbatimKeys?.has(pascalKey)) {
4124
+ result[pascalKey] = nestedValue;
4125
+ if (subtrees?.mode === "collect") {
4126
+ collectVerbatimRefs(nestedValue, subtrees.refs);
4127
+ }
4128
+ continue;
4129
+ }
4130
+ result[pascalKey] = toPascalCaseData(nestedValue, verbatimKeys, subtrees);
3472
4131
  }
3473
4132
  return result;
3474
4133
  }
3475
- function normalizeDataKeys(data) {
3476
- return toPascalCaseData(data);
4134
+ function normalizeDataKeys(data, verbatimKeys, subtrees) {
4135
+ return toPascalCaseData(data, verbatimKeys, subtrees);
4136
+ }
4137
+ function toVerbatimKeySet(preserve) {
4138
+ if (!Array.isArray(preserve))
4139
+ return;
4140
+ return new Set(preserve.map(toPascalCaseKey));
3477
4141
  }
3478
4142
  function normalizeOutputKeys(data) {
3479
4143
  const result = {};
@@ -3483,7 +4147,7 @@ function normalizeOutputKeys(data) {
3483
4147
  }
3484
4148
  return result;
3485
4149
  }
3486
- function printOutput(data, format = "json", logFn, asciiSafe = false) {
4150
+ function printOutput(data, format = "json", logFn, asciiSafe = false, tableRowStyle) {
3487
4151
  if (!data) {
3488
4152
  logFn("Empty response object. No data to display.");
3489
4153
  return;
@@ -3518,7 +4182,7 @@ function printOutput(data, format = "json", logFn, asciiSafe = false) {
3518
4182
  if (hasData && !(rows !== null && rows.length === 0)) {
3519
4183
  const logValue = data.Log;
3520
4184
  if (rows !== null) {
3521
- printResizableTable(rows, logFn, logValue);
4185
+ printResizableTable(rows, logFn, logValue, undefined, tableRowStyle);
3522
4186
  } else {
3523
4187
  printVerticalTable(data.Data, logFn, logValue);
3524
4188
  }
@@ -3529,10 +4193,11 @@ function printOutput(data, format = "json", logFn, asciiSafe = false) {
3529
4193
  }
3530
4194
  }
3531
4195
  }
3532
- function logOutput(data, format = "json") {
4196
+ function logOutput(data, format = "json", tableRowStyle) {
3533
4197
  const sink = getOutputSink();
4198
+ const styleFn = sink.capabilities.isInteractive && sink.capabilities.supportsColor ? tableRowStyle : undefined;
3534
4199
  printOutput(data, format, (msg) => sink.writeOut(`${msg}
3535
- `), needsAsciiSafeJson(sink));
4200
+ `), needsAsciiSafeJson(sink), styleFn);
3536
4201
  }
3537
4202
  function cellToString(val) {
3538
4203
  return val != null && typeof val === "object" ? JSON.stringify(val) : String(val ?? "");
@@ -3546,7 +4211,7 @@ function wrapText(text, width) {
3546
4211
  }
3547
4212
  return lines;
3548
4213
  }
3549
- function printTable(data, logFn, externalLogValue) {
4214
+ function printTable(data, logFn, externalLogValue, tableRowStyle) {
3550
4215
  if (data.length === 0)
3551
4216
  return;
3552
4217
  const keys = Object.keys(data[0]).filter((key) => !["code", "log"].includes(key.toLowerCase()));
@@ -3556,7 +4221,7 @@ function printTable(data, logFn, externalLogValue) {
3556
4221
  logFn(keys.map((_, i) => "-".repeat(maxWidths[i])).join("-|-"));
3557
4222
  data.forEach((item) => {
3558
4223
  const row = keys.map((key, i) => cellToString(item[key]).padEnd(maxWidths[i])).join(" | ");
3559
- logFn(row);
4224
+ logFn(styleLine(row, tableRowStyle?.(item)));
3560
4225
  });
3561
4226
  if (externalLogValue) {
3562
4227
  logFn("");
@@ -3599,14 +4264,14 @@ function printVerticalTable(data, logFn = console.log, externalLogValue) {
3599
4264
  logFn(`Log: ${externalLogValue}`);
3600
4265
  }
3601
4266
  }
3602
- function printResizableTable(data, logFn = console.log, externalLogValue, availableWidth) {
4267
+ function printResizableTable(data, logFn = console.log, externalLogValue, availableWidth, tableRowStyle) {
3603
4268
  if (data.length === 0)
3604
4269
  return;
3605
4270
  const keys = Object.keys(data[0]).filter((key) => !["code", "log"].includes(key.toLowerCase()));
3606
4271
  if (keys.length === 0)
3607
4272
  return;
3608
4273
  if (!process.stdout.isTTY) {
3609
- printTable(data, logFn, externalLogValue);
4274
+ printTable(data, logFn, externalLogValue, tableRowStyle);
3610
4275
  return;
3611
4276
  }
3612
4277
  const naturalWidths = keys.map((key) => Math.max(key.length, ...data.map((item) => cellToString(item[key]).length)));
@@ -3614,7 +4279,7 @@ function printResizableTable(data, logFn = console.log, externalLogValue, availa
3614
4279
  const totalWidth = naturalWidths.reduce((a, b) => a + b, 0) + separatorTotal;
3615
4280
  const termWidth = availableWidth ?? (process.stdout.columns || 120);
3616
4281
  if (totalWidth <= termWidth) {
3617
- printTable(data, logFn, externalLogValue);
4282
+ printTable(data, logFn, externalLogValue, tableRowStyle);
3618
4283
  return;
3619
4284
  }
3620
4285
  const overflow = totalWidth - termWidth;
@@ -3660,6 +4325,7 @@ function printResizableTable(data, logFn = console.log, externalLogValue, availa
3660
4325
  logFn(header);
3661
4326
  logFn(keys.map((_, i) => "-".repeat(finalWidths[i])).join("-|-"));
3662
4327
  data.forEach((item) => {
4328
+ const style = tableRowStyle?.(item);
3663
4329
  const cellLines = keys.map((key, i) => wrapText(cellToString(item[key]), finalWidths[i]));
3664
4330
  const lineCount = Math.max(...cellLines.map((l) => l.length));
3665
4331
  for (let line = 0;line < lineCount; line++) {
@@ -3667,7 +4333,7 @@ function printResizableTable(data, logFn = console.log, externalLogValue, availa
3667
4333
  const val = line < cellLines[i].length ? cellLines[i][line] : "";
3668
4334
  return val.padEnd(finalWidths[i]);
3669
4335
  }).join(" | ");
3670
- logFn(row);
4336
+ logFn(styleLine(row, style));
3671
4337
  }
3672
4338
  });
3673
4339
  if (externalLogValue) {
@@ -3811,30 +4477,36 @@ var OutputFormatter;
3811
4477
  ((OutputFormatter) => {
3812
4478
  function success(data, options) {
3813
4479
  data.Log ??= getLogFilePath() || undefined;
3814
- const normalize = !options?.preserveDataKeys;
4480
+ const normalize = options?.preserveDataKeys !== true;
4481
+ const verbatim = toVerbatimKeySet(options?.preserveDataKeys);
4482
+ const subtrees = verbatim && {
4483
+ refs: new Set,
4484
+ mode: "collect"
4485
+ };
3815
4486
  if (normalize) {
3816
- data.Data = normalizeDataKeys(data.Data);
4487
+ data.Data = normalizeDataKeys(data.Data, verbatim, subtrees);
3817
4488
  }
3818
4489
  const filter = getOutputFilter();
3819
4490
  if (filter) {
3820
4491
  const filtered = applyFilter(data.Data, filter);
3821
- data.Data = normalize ? normalizeDataKeys(filtered) : filtered;
4492
+ data.Data = normalize ? normalizeDataKeys(filtered, verbatim, subtrees && { refs: subtrees.refs, mode: "skip" }) : filtered;
3822
4493
  }
3823
- logOutput(normalizeOutputKeys(data), getOutputFormat());
4494
+ logOutput(normalizeOutputKeys(data), getOutputFormat(), options?.tableRowStyle);
3824
4495
  }
3825
4496
  OutputFormatter.success = success;
3826
4497
  function error(data) {
3827
4498
  data.Log ??= getLogFilePath() || undefined;
3828
4499
  data.ErrorCode ??= defaultErrorCodeForFailure(data);
3829
4500
  data.Retry ??= defaultRetryForErrorCode(data.ErrorCode);
3830
- process.exitCode = EXIT_CODES[data.Result] ?? 1;
4501
+ const exitCode = EXIT_CODES[data.Result] ?? 1;
4502
+ setExitCode(exitCode);
3831
4503
  recordCommandFailureTelemetry({
3832
4504
  result: data.Result,
3833
4505
  errorCode: data.ErrorCode,
3834
4506
  retry: data.Retry,
3835
4507
  message: data.Message,
3836
4508
  context: data.Context,
3837
- exitCode: process.exitCode,
4509
+ exitCode,
3838
4510
  errorClass: data.TelemetryErrorClass,
3839
4511
  terminalOutcome: data.TelemetryTerminalOutcome,
3840
4512
  terminalSignal: data.TelemetryTerminalSignal
@@ -3910,6 +4582,47 @@ var OutputFormatter;
3910
4582
  }
3911
4583
  OutputFormatter.formatToString = formatToString;
3912
4584
  })(OutputFormatter ||= {});
4585
+ // ../../node_modules/commander/esm.mjs
4586
+ var import__ = __toESM(require_commander(), 1);
4587
+ var {
4588
+ program,
4589
+ createCommand,
4590
+ createArgument,
4591
+ createOption,
4592
+ CommanderError,
4593
+ InvalidArgumentError,
4594
+ InvalidOptionArgumentError,
4595
+ Command,
4596
+ Argument,
4597
+ Option,
4598
+ Help
4599
+ } = import__.default;
4600
+
4601
+ // ../common/src/command-examples.ts
4602
+ var examplesByCommand = new WeakMap;
4603
+ Command.prototype.examples = function(examples) {
4604
+ examplesByCommand.set(this, examples);
4605
+ return this;
4606
+ };
4607
+ // ../common/src/preview.ts
4608
+ var previewSlot = singleton("PreviewBuild");
4609
+ function setPreviewBuild(isPreview) {
4610
+ previewSlot.set(isPreview);
4611
+ }
4612
+ function isPreviewBuild() {
4613
+ return previewSlot.get(false) ?? false;
4614
+ }
4615
+ function previewOnly(register) {
4616
+ if (isPreviewBuild()) {
4617
+ register();
4618
+ }
4619
+ }
4620
+ Command.prototype.previewCommand = function(nameAndArgs, opts) {
4621
+ if (isPreviewBuild()) {
4622
+ return this.command(nameAndArgs, opts);
4623
+ }
4624
+ return new Command(nameAndArgs.split(/\s+/)[0] ?? nameAndArgs);
4625
+ };
3913
4626
 
3914
4627
  // ../common/src/telemetry/command-attribution.ts
3915
4628
  var LEGACY_SKILL_NAMESPACE = "uipath:";
@@ -4064,6 +4777,57 @@ function buildCommandTelemetryAttribution(commandPath, skillSource) {
4064
4777
  };
4065
4778
  }
4066
4779
 
4780
+ // ../common/src/telemetry/command-name.ts
4781
+ var TELEMETRY_COMMAND_ROOT = "uip";
4782
+ function commandTelemetryName(parts) {
4783
+ const tokens = [];
4784
+ for (const part of parts) {
4785
+ const pieces = String(part ?? "").split(/\s+/).filter((token) => token && !token.startsWith("-") && token !== TELEMETRY_COMMAND_ROOT);
4786
+ if (pieces.every(isCommandToken)) {
4787
+ tokens.push(...pieces);
4788
+ continue;
4789
+ }
4790
+ tokens.push(UNKNOWN_TOKEN);
4791
+ }
4792
+ return [TELEMETRY_COMMAND_ROOT, ...tokens].join(".");
4793
+ }
4794
+ var COMMAND_TOKEN_PATTERN = /^[a-z0-9][a-z0-9-]*$/;
4795
+ var MAX_COMMAND_TOKEN_LENGTH = 32;
4796
+ var GUID_TOKEN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
4797
+ function isCommandToken(token) {
4798
+ return token.length <= MAX_COMMAND_TOKEN_LENGTH && COMMAND_TOKEN_PATTERN.test(token) && !GUID_TOKEN.test(token) && !/^\d+$/.test(token);
4799
+ }
4800
+ var UNKNOWN_TOKEN = "<unknown>";
4801
+
4802
+ // ../common/src/telemetry/invocation-request.ts
4803
+ var requestContextSlot = singleton("TelemetryInvocationRequestContext");
4804
+ function activeContext() {
4805
+ return telemetry.getActiveContext?.();
4806
+ }
4807
+ function runWithInvocationRequest(fn) {
4808
+ const context = telemetry.createRequestContext();
4809
+ context.startedAt = invocationStartedAt();
4810
+ requestContextSlot.set(context);
4811
+ return telemetry.runWithContext(context, fn);
4812
+ }
4813
+ function ensureInvocationRequestScope(fn) {
4814
+ if (activeContext() !== undefined) {
4815
+ return fn();
4816
+ }
4817
+ const kept = requestContextSlot.get();
4818
+ return kept === undefined ? runWithInvocationRequest(fn) : telemetry.runWithContext(kept, fn);
4819
+ }
4820
+ function getInvocationRequestContext() {
4821
+ return activeContext() ?? requestContextSlot.get();
4822
+ }
4823
+ function emitInvocationRequest(name, success, properties) {
4824
+ const context = getInvocationRequestContext();
4825
+ telemetry.trackRequestResult(name, invocationElapsedMs(), success, properties, context);
4826
+ if (context !== undefined && requestContextSlot.get() === context) {
4827
+ requestContextSlot.clear();
4828
+ }
4829
+ }
4830
+
4067
4831
  // ../common/src/trackedAction.ts
4068
4832
  var pollSignalSlot = singleton("PollSignal");
4069
4833
  var cliErrorCodeValues = new Set(CLI_ERROR_CODES);
@@ -4071,28 +4835,74 @@ var retryHintValues = new Set(RETRY_HINTS);
4071
4835
  var TELEMETRY_COMMAND_ARG_PREFIX = "uip.cmd.arg.";
4072
4836
  var processContext = {
4073
4837
  exit: (code) => {
4074
- process.exitCode = code;
4838
+ recordExitCode(code);
4839
+ setExitCode(code);
4075
4840
  },
4076
4841
  get pollSignal() {
4077
4842
  return pollSignalSlot.get();
4078
4843
  }
4079
4844
  };
4845
+ var TELEMETRY_ARG_VALUE_WITHHELD = "<provided>";
4846
+ var TELEMETRY_ARG_VALUE_DEFAULTED = "<default>";
4847
+ function recordableArgValue(value, choices) {
4848
+ if (typeof value === "boolean" || typeof value === "number") {
4849
+ return value;
4850
+ }
4851
+ if (choices && choices.length > 0) {
4852
+ if (typeof value === "string" && choices.includes(value)) {
4853
+ return value;
4854
+ }
4855
+ if (Array.isArray(value) && value.length > 0 && value.every((entry) => typeof entry === "string" && choices.includes(entry))) {
4856
+ return value.join(",");
4857
+ }
4858
+ }
4859
+ return TELEMETRY_ARG_VALUE_WITHHELD;
4860
+ }
4080
4861
  function extractCommandParams(cmd) {
4081
4862
  const params = {};
4082
- const add = (name, value) => {
4083
- if (name && value !== undefined) {
4084
- params[`${TELEMETRY_COMMAND_ARG_PREFIX}${name}`] = value;
4085
- }
4086
- };
4863
+ forEachSuppliedArgument(cmd, (name, value, choices, defaulted) => {
4864
+ const recordable = recordableArgValue(value, choices);
4865
+ params[`${TELEMETRY_COMMAND_ARG_PREFIX}${name}`] = recordable === TELEMETRY_ARG_VALUE_WITHHELD && defaulted ? TELEMETRY_ARG_VALUE_DEFAULTED : recordable;
4866
+ });
4867
+ return params;
4868
+ }
4869
+ function isDefaultedOption(cmd, name) {
4870
+ const source = cmd.getOptionValueSource?.(name);
4871
+ return source === "default" || source === "implied";
4872
+ }
4873
+ function isDefaultedPositional(cmd, index) {
4874
+ return index >= (cmd.args?.length ?? 0);
4875
+ }
4876
+ function forEachSuppliedArgument(cmd, visit) {
4087
4877
  const registered = cmd.registeredArguments ?? [];
4088
4878
  const processed = cmd.processedArgs ?? [];
4089
4879
  for (let i = 0;i < registered.length; i++) {
4090
- add(registered[i].name(), processed[i]);
4880
+ const name = registered[i].name();
4881
+ if (name && processed[i] !== undefined) {
4882
+ visit(name, processed[i], registered[i].argChoices, isDefaultedPositional(cmd, i));
4883
+ }
4884
+ }
4885
+ const choicesByAttribute = new Map;
4886
+ for (const option of cmd.options) {
4887
+ choicesByAttribute.set(option.attributeName(), option.argChoices);
4091
4888
  }
4092
4889
  for (const [key, value] of Object.entries(cmd.opts())) {
4093
- add(key, value);
4890
+ if (key && value !== undefined) {
4891
+ visit(key, value, choicesByAttribute.get(key), isDefaultedOption(cmd, key));
4892
+ }
4094
4893
  }
4095
- return params;
4894
+ }
4895
+ function withheldArgumentValues(cmd) {
4896
+ const values = [];
4897
+ forEachSuppliedArgument(cmd, (_name, value, choices, defaulted) => {
4898
+ if (defaulted) {
4899
+ return;
4900
+ }
4901
+ if (recordableArgValue(value, choices) === TELEMETRY_ARG_VALUE_WITHHELD) {
4902
+ values.push(value);
4903
+ }
4904
+ });
4905
+ return values;
4096
4906
  }
4097
4907
  function deriveCommandPath(cmd) {
4098
4908
  const parts = [];
@@ -4107,7 +4917,7 @@ function deriveCommandPath(cmd) {
4107
4917
  if (parts.length > 1) {
4108
4918
  parts.shift();
4109
4919
  }
4110
- return ["uip", ...parts.filter((p) => p !== "uip")].join(".");
4920
+ return commandTelemetryName(parts);
4111
4921
  }
4112
4922
  function isCliErrorCode(value) {
4113
4923
  return typeof value === "string" && cliErrorCodeValues.has(value);
@@ -4147,68 +4957,77 @@ Command.prototype.trackedAction = function(context, fn, properties) {
4147
4957
  });
4148
4958
  const telemetryName = deriveCommandPath(command);
4149
4959
  const props = typeof properties === "function" ? properties(...args) : properties;
4150
- const requestContext = telemetry.createRequestContext();
4151
- const startTime = performance.now();
4152
- let errorMessage;
4153
- let fallbackExitCode = EXIT_CODES.Success;
4154
- clearRecordedCommandFailureTelemetry();
4155
- const [error] = await catchError2(telemetry.runWithContext(requestContext, () => {
4156
- const violation = implicitLimitViolation(command);
4157
- if (violation) {
4158
- return Promise.reject(violation);
4159
- }
4160
- return fn(...args);
4161
- }));
4162
- if (error) {
4163
- errorMessage = error instanceof Error ? error.message : String(error);
4164
- logger.debug(`[trackedAction] ${telemetryName} failed: ${errorMessage}`);
4165
- const typed = error;
4166
- const customInstructions = typeof typed.instructions === "string" ? typed.instructions : undefined;
4167
- const customResult = typeof typed.result === "string" && typed.result !== RESULTS.Success && Object.values(RESULTS).includes(typed.result) ? typed.result : undefined;
4168
- const finalResult = customResult ?? RESULTS.Failure;
4169
- const typedErrorCode = typed.errorCode ?? typed.ErrorCode;
4170
- const customErrorCode = isCliErrorCode(typedErrorCode) ? typedErrorCode : undefined;
4171
- const typedRetry = typed.retry ?? typed.Retry;
4172
- const customRetry = isRetryHint(typedRetry) ? typedRetry : undefined;
4173
- const typedContext = typed.context ?? typed.Context;
4174
- const customContext = isErrorContext(typedContext) ? typedContext : undefined;
4175
- const cancellationExitCode = typed.exitCode === 130 || isPromptCancellation(error) ? 130 : undefined;
4176
- fallbackExitCode = cancellationExitCode ?? EXIT_CODES[finalResult];
4177
- OutputFormatter.error({
4178
- Result: finalResult,
4179
- ...customErrorCode ? { ErrorCode: customErrorCode } : {},
4180
- Message: errorMessage,
4181
- Instructions: customInstructions ?? commandHelpHint(telemetryName),
4182
- ...customRetry ? { Retry: customRetry } : {},
4183
- ...customContext ? { Context: customContext } : {}
4960
+ markCommandStart();
4961
+ const supplied = recordSuppliedArgumentValues(withheldArgumentValues(command));
4962
+ try {
4963
+ const startTime = performance.now();
4964
+ let errorMessage;
4965
+ let fallbackExitCode = EXIT_CODES.Success;
4966
+ clearRecordedCommandFailureTelemetry();
4967
+ const [error] = await catchError(ensureInvocationRequestScope(() => {
4968
+ const violation = implicitLimitViolation(command);
4969
+ if (violation) {
4970
+ return Promise.reject(violation);
4971
+ }
4972
+ return fn(...args);
4973
+ }));
4974
+ if (error) {
4975
+ errorMessage = error instanceof Error ? error.message : String(error);
4976
+ logger.debug(`[trackedAction] ${telemetryName} failed: ${errorMessage}`);
4977
+ const typed = error;
4978
+ const customInstructions = typeof typed.instructions === "string" ? typed.instructions : undefined;
4979
+ const customResult = typeof typed.result === "string" && typed.result !== RESULTS.Success && Object.values(RESULTS).includes(typed.result) ? typed.result : undefined;
4980
+ const finalResult = customResult ?? RESULTS.Failure;
4981
+ const typedErrorCode = typed.errorCode ?? typed.ErrorCode;
4982
+ const customErrorCode = isCliErrorCode(typedErrorCode) ? typedErrorCode : undefined;
4983
+ const typedRetry = typed.retry ?? typed.Retry;
4984
+ const customRetry = isRetryHint(typedRetry) ? typedRetry : undefined;
4985
+ const typedContext = typed.context ?? typed.Context;
4986
+ const customContext = isErrorContext(typedContext) ? typedContext : undefined;
4987
+ const cancellationExitCode = typed.exitCode === 130 || isPromptCancellation(error) ? 130 : undefined;
4988
+ fallbackExitCode = cancellationExitCode ?? EXIT_CODES[finalResult];
4989
+ OutputFormatter.error({
4990
+ Result: finalResult,
4991
+ ...customErrorCode ? { ErrorCode: customErrorCode } : {},
4992
+ Message: errorMessage,
4993
+ Instructions: customInstructions ?? commandHelpHint(telemetryName),
4994
+ ...customRetry ? { Retry: customRetry } : {},
4995
+ ...customContext ? { Context: customContext } : {}
4996
+ });
4997
+ context.exit(fallbackExitCode);
4998
+ }
4999
+ const durationMs = performance.now() - startTime;
5000
+ recordCommandDuration(durationMs);
5001
+ const exitCode = fallbackExitCode === 130 ? fallbackExitCode : exitCodeFromProcess(fallbackExitCode);
5002
+ const recordedFailure = takeRecordedCommandFailureTelemetry();
5003
+ const success = !error && exitCode === 0;
5004
+ const terminalTelemetry = buildCommandTerminalTelemetryProperties({
5005
+ error,
5006
+ exitCode,
5007
+ recordedFailure,
5008
+ pollSignal: context.pollSignal
4184
5009
  });
4185
- context.exit(fallbackExitCode);
4186
- }
4187
- const durationMs = performance.now() - startTime;
4188
- const exitCode = fallbackExitCode === 130 ? fallbackExitCode : exitCodeFromProcess(fallbackExitCode);
4189
- const recordedFailure = takeRecordedCommandFailureTelemetry();
4190
- const success = !error && exitCode === 0;
4191
- const terminalTelemetry = buildCommandTerminalTelemetryProperties({
4192
- error,
4193
- exitCode,
4194
- recordedFailure,
4195
- pollSignal: context.pollSignal
4196
- });
4197
- const commandParams = extractCommandParams(command);
4198
- if (props) {
4199
- for (const key of Object.keys(props)) {
4200
- delete commandParams[`${TELEMETRY_COMMAND_ARG_PREFIX}${key}`];
4201
- }
4202
- }
4203
- const baseProperties = redactProperties({
4204
- ...commandParams,
4205
- ...props,
4206
- ...buildCommandTelemetryAttribution(telemetryName, process.env.UIPATH_SKILL),
4207
- command: "true",
4208
- ...terminalTelemetry,
4209
- ...errorMessage ? { errorMessage } : {}
4210
- });
4211
- telemetry.trackRequestResult(telemetryName, durationMs, success, baseProperties, requestContext);
5010
+ if (terminalTelemetry.error_class === "internal" && error) {
5011
+ telemetry.trackException(error instanceof Error ? error : new Error(String(error)), { command_name: telemetryName }, getInvocationRequestContext());
5012
+ }
5013
+ const commandParams = extractCommandParams(command);
5014
+ if (props) {
5015
+ for (const key of Object.keys(props)) {
5016
+ delete commandParams[`${TELEMETRY_COMMAND_ARG_PREFIX}${key}`];
5017
+ }
5018
+ }
5019
+ const baseProperties = redactProperties({
5020
+ ...commandParams,
5021
+ ...props,
5022
+ ...buildCommandTelemetryAttribution(telemetryName, process.env.UIPATH_SKILL),
5023
+ command: "true",
5024
+ ...terminalTelemetry,
5025
+ ...errorMessage ? { errorMessage } : {}
5026
+ });
5027
+ emitInvocationRequest(telemetryName, success, baseProperties);
5028
+ } finally {
5029
+ releaseSuppliedArgumentValues(supplied);
5030
+ }
4212
5031
  });
4213
5032
  };
4214
5033
  // ../common/src/completer.ts
@@ -4218,6 +5037,204 @@ var guardInstalledSlot = singleton("ConsoleGuardInstalled");
4218
5037
  var savedOriginalsSlot = singleton("ConsoleGuardOriginals");
4219
5038
  // ../common/src/constants.ts
4220
5039
  var DEFAULT_AUTH_TIMEOUT_MS = 5 * 60 * 1000;
5040
+ // ../common/src/entity-name-rules.ts
5041
+ var RESERVED_SQL_KEYWORDS_LOWER = new Set(["group", "order"]);
5042
+ var RESERVED_FIELD_NAMES_LOWER = new Set([
5043
+ "id",
5044
+ "createdby",
5045
+ "createtime",
5046
+ "updatedby",
5047
+ "updatetime",
5048
+ "recordowner",
5049
+ "version"
5050
+ ]);
5051
+ var RESERVED_KEYWORDS_LOWER = new Set([
5052
+ "abstract",
5053
+ "as",
5054
+ "base",
5055
+ "bool",
5056
+ "break",
5057
+ "byte",
5058
+ "case",
5059
+ "catch",
5060
+ "char",
5061
+ "checked",
5062
+ "class",
5063
+ "const",
5064
+ "continue",
5065
+ "decimal",
5066
+ "default",
5067
+ "delegate",
5068
+ "do",
5069
+ "double",
5070
+ "else",
5071
+ "enum",
5072
+ "event",
5073
+ "explicit",
5074
+ "extern",
5075
+ "false",
5076
+ "finally",
5077
+ "fixed",
5078
+ "float",
5079
+ "for",
5080
+ "foreach",
5081
+ "goto",
5082
+ "if",
5083
+ "implicit",
5084
+ "in",
5085
+ "int",
5086
+ "interface",
5087
+ "internal",
5088
+ "is",
5089
+ "lock",
5090
+ "long",
5091
+ "namespace",
5092
+ "new",
5093
+ "null",
5094
+ "object",
5095
+ "operator",
5096
+ "out",
5097
+ "override",
5098
+ "params",
5099
+ "private",
5100
+ "protected",
5101
+ "public",
5102
+ "readonly",
5103
+ "ref",
5104
+ "return",
5105
+ "sbyte",
5106
+ "sealed",
5107
+ "short",
5108
+ "sizeof",
5109
+ "stackalloc",
5110
+ "static",
5111
+ "string",
5112
+ "struct",
5113
+ "switch",
5114
+ "this",
5115
+ "throw",
5116
+ "true",
5117
+ "try",
5118
+ "typeof",
5119
+ "uint",
5120
+ "ulong",
5121
+ "unchecked",
5122
+ "unsafe",
5123
+ "ushort",
5124
+ "using",
5125
+ "virtual",
5126
+ "void",
5127
+ "volatile",
5128
+ "while",
5129
+ "addhandler",
5130
+ "addressof",
5131
+ "alias",
5132
+ "and",
5133
+ "andalso",
5134
+ "boolean",
5135
+ "byref",
5136
+ "byval",
5137
+ "call",
5138
+ "cbool",
5139
+ "cbyte",
5140
+ "cchar",
5141
+ "cdate",
5142
+ "cdbl",
5143
+ "cdec",
5144
+ "cint",
5145
+ "clng",
5146
+ "cobj",
5147
+ "csbyte",
5148
+ "cshort",
5149
+ "csng",
5150
+ "cstr",
5151
+ "ctype",
5152
+ "cuint",
5153
+ "culng",
5154
+ "cushort",
5155
+ "date",
5156
+ "declare",
5157
+ "dim",
5158
+ "directcast",
5159
+ "each",
5160
+ "elseif",
5161
+ "end",
5162
+ "endif",
5163
+ "erase",
5164
+ "error",
5165
+ "exit",
5166
+ "friend",
5167
+ "function",
5168
+ "get",
5169
+ "gettype",
5170
+ "getxmlnamespace",
5171
+ "global",
5172
+ "gosub",
5173
+ "goto",
5174
+ "handles",
5175
+ "implements",
5176
+ "imports",
5177
+ "inherits",
5178
+ "integer",
5179
+ "isnot",
5180
+ "let",
5181
+ "lib",
5182
+ "like",
5183
+ "loop",
5184
+ "me",
5185
+ "mod",
5186
+ "module",
5187
+ "mustinherit",
5188
+ "mustoverride",
5189
+ "mybase",
5190
+ "myclass",
5191
+ "narrowing",
5192
+ "next",
5193
+ "not",
5194
+ "nothing",
5195
+ "notinheritable",
5196
+ "notoverridable",
5197
+ "of",
5198
+ "on",
5199
+ "option",
5200
+ "optional",
5201
+ "or",
5202
+ "orelse",
5203
+ "overloads",
5204
+ "overridable",
5205
+ "overrides",
5206
+ "paramarray",
5207
+ "partial",
5208
+ "property",
5209
+ "raiseevent",
5210
+ "redim",
5211
+ "rem",
5212
+ "removehandler",
5213
+ "resume",
5214
+ "select",
5215
+ "set",
5216
+ "shadows",
5217
+ "shared",
5218
+ "single",
5219
+ "step",
5220
+ "stop",
5221
+ "structure",
5222
+ "sub",
5223
+ "synclock",
5224
+ "then",
5225
+ "to",
5226
+ "trycast",
5227
+ "uinteger",
5228
+ "ushort",
5229
+ "variant",
5230
+ "wend",
5231
+ "when",
5232
+ "widening",
5233
+ "with",
5234
+ "withevents",
5235
+ "writeonly",
5236
+ "xor"
5237
+ ]);
4221
5238
  // ../common/src/host-global-options.ts
4222
5239
  var HOST_GLOBAL_OPTIONS_WITH_VALUE = [
4223
5240
  "--output",
@@ -4289,7 +5306,7 @@ var factorySlot = singleton("PackagerFactoryProvider");
4289
5306
  var package_default = {
4290
5307
  name: "@uipath/coder-tool",
4291
5308
  license: "MIT",
4292
- version: "1.201.0-preview.133",
5309
+ version: "1.202.0-preview.134",
4293
5310
  description: "Interactive coding agent (Pi) with UiPath LLM Gateway and BYO provider support.",
4294
5311
  publishConfig: {
4295
5312
  registry: "https://npm.pkg.github.com/"
@@ -4326,6 +5343,40 @@ var package_default = {
4326
5343
  // src/commands/chat.ts
4327
5344
  import { fileURLToPath } from "node:url";
4328
5345
 
5346
+ // ../auth/src/catch-error.ts
5347
+ function isPromiseLike2(value) {
5348
+ return value !== null && typeof value === "object" && typeof value.then === "function";
5349
+ }
5350
+ function catchError2(fnOrPromise) {
5351
+ if (isPromiseLike2(fnOrPromise)) {
5352
+ return settlePromiseLike2(fnOrPromise);
5353
+ }
5354
+ try {
5355
+ const result = fnOrPromise();
5356
+ if (isPromiseLike2(result)) {
5357
+ return settlePromiseLike2(result);
5358
+ }
5359
+ return [undefined, result];
5360
+ } catch (error) {
5361
+ return [
5362
+ error instanceof Error ? error : new Error(String(error)),
5363
+ undefined
5364
+ ];
5365
+ }
5366
+ }
5367
+ function settlePromiseLike2(thenable) {
5368
+ return Promise.resolve(thenable).then((data) => [undefined, data]).catch((error) => [
5369
+ error instanceof Error ? error : new Error(String(error)),
5370
+ undefined
5371
+ ]);
5372
+ }
5373
+
5374
+ // ../auth/src/constants.ts
5375
+ var UIPATH_HOME_DIR = ".uipath";
5376
+ var AUTH_FILENAME = ".auth";
5377
+ var DEFAULT_BASE_URL = "https://cloud.uipath.com";
5378
+ var DEFAULT_AUTH_TIMEOUT_MS2 = 5 * 60 * 1000;
5379
+
4329
5380
  // ../auth/src/config.ts
4330
5381
  var DEFAULT_CLIENT_ID = "36dea5b8-e8bb-423d-8e7b-c808df8f1c00";
4331
5382
  var AUTH_FILE_CONFIG_KEY = Symbol.for("@uipath/auth/AuthFileConfig");
@@ -4339,7 +5390,7 @@ class InvalidBaseUrlError extends Error {
4339
5390
  super(`Invalid base URL: "${url}"
4340
5391
  ` + `Reason: ${reason}
4341
5392
 
4342
- ` + `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>).
5393
+ ` + `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>).
4343
5394
  ` + `You can specify the URL via:
4344
5395
  ` + ` • --authority flag
4345
5396
  ` + ` • UIPATH_URL environment variable
@@ -4360,10 +5411,16 @@ var normalizeAndValidateBaseUrl = (rawUrl) => {
4360
5411
  while (baseUrl.endsWith("/")) {
4361
5412
  baseUrl = baseUrl.slice(0, -1);
4362
5413
  }
5414
+ const hasScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(baseUrl);
5415
+ const [hostCandidate] = baseUrl.split(/[/?#]/, 1);
5416
+ if (!hasScheme && hostCandidate.includes(".")) {
5417
+ baseUrl = `https://${baseUrl}`;
5418
+ }
4363
5419
  const resolvedBaseUrl = baseUrl;
4364
- const [urlError, url] = catchError(() => new URL(resolvedBaseUrl));
5420
+ const [urlError, url] = catchError2(() => new URL(resolvedBaseUrl));
4365
5421
  if (urlError) {
4366
- throw new InvalidBaseUrlError(baseUrl, `Malformed URL. ${urlError instanceof Error ? urlError.message : "Unknown error"}`);
5422
+ 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"}`;
5423
+ throw new InvalidBaseUrlError(baseUrl, `Malformed URL.${shapeHint}`);
4367
5424
  }
4368
5425
  if (url.protocol !== "https:") {
4369
5426
  throw new InvalidBaseUrlError(baseUrl, `Authority must use https:// scheme, got ${url.protocol}//. OIDC token exchange requires TLS end-to-end.`);
@@ -4418,6 +5475,11 @@ var resolveConfigAsync = async ({
4418
5475
  };
4419
5476
  };
4420
5477
 
5478
+ // ../auth/src/utils/platform.ts
5479
+ function isBrowser() {
5480
+ return typeof globalThis !== "undefined" && "window" in globalThis && "document" in globalThis;
5481
+ }
5482
+
4421
5483
  // ../auth/src/authProfile.ts
4422
5484
  var DEFAULT_AUTH_PROFILE = "default";
4423
5485
  var PROFILE_DIR = "profiles";
@@ -4429,7 +5491,7 @@ function isAuthProfileStorage(value) {
4429
5491
  return value !== null && typeof value === "object" && "getStore" in value && "run" in value;
4430
5492
  }
4431
5493
  function createProfileStorage() {
4432
- const [error, mod] = catchError(() => __require("node:async_hooks"));
5494
+ const [error, mod] = catchError2(() => __require("node:async_hooks"));
4433
5495
  if (error || typeof mod?.AsyncLocalStorage !== "function") {
4434
5496
  return {
4435
5497
  getStore: () => {
@@ -4445,9 +5507,9 @@ function getProfileStorage() {
4445
5507
  if (isAuthProfileStorage(existing)) {
4446
5508
  return existing;
4447
5509
  }
4448
- const storage = createProfileStorage();
4449
- globalSlot2[AUTH_PROFILE_STORAGE_KEY] = storage;
4450
- return storage;
5510
+ const storage2 = createProfileStorage();
5511
+ globalSlot2[AUTH_PROFILE_STORAGE_KEY] = storage2;
5512
+ return storage2;
4451
5513
  }
4452
5514
  var profileStorage = getProfileStorage();
4453
5515
 
@@ -4478,8 +5540,8 @@ function resolveAuthProfileFilePath(profile) {
4478
5540
  if (normalized === undefined) {
4479
5541
  throw new AuthProfileValidationError(`"${DEFAULT_AUTH_PROFILE}" is the built-in profile and does not have a profile file path.`);
4480
5542
  }
4481
- const fs = getFileSystem();
4482
- return fs.path.join(fs.env.homedir(), UIPATH_HOME_DIR, PROFILE_DIR, normalized, AUTH_FILENAME);
5543
+ const fs2 = getFileSystem();
5544
+ return fs2.path.join(fs2.env.homedir(), UIPATH_HOME_DIR, PROFILE_DIR, normalized, AUTH_FILENAME);
4483
5545
  }
4484
5546
  function getActiveAuthProfileFilePath() {
4485
5547
  const profile = getActiveAuthProfile();
@@ -4560,7 +5622,7 @@ var getTokenExpiration = (accessToken) => {
4560
5622
  // ../auth/src/sessionIdentity.ts
4561
5623
  var parseAuthFlow = (value) => value === "authorization_code" || value === "client_credentials" || value === "federated_credentials" ? value : undefined;
4562
5624
  var decodeClaims = (accessToken) => {
4563
- const [error, claims] = catchError(() => parseJWT(accessToken));
5625
+ const [error, claims] = catchError2(() => parseJWT(accessToken));
4564
5626
  return error ? undefined : claims;
4565
5627
  };
4566
5628
  var asString = (value) => typeof value === "string" && value.length > 0 ? value : undefined;
@@ -4644,27 +5706,48 @@ var requireEnv = (name) => {
4644
5706
  }
4645
5707
  return value;
4646
5708
  };
5709
+ var OPAQUE_TOKEN_BASE_URL_VAR = "UIPATH_URL";
5710
+ var resolveBaseUrl = (rawUrl, failureContext) => {
5711
+ const [baseUrlError, baseUrl] = catchError2(() => normalizeAndValidateBaseUrl(rawUrl));
5712
+ if (baseUrlError) {
5713
+ if (baseUrlError instanceof InvalidBaseUrlError) {
5714
+ throw baseUrlError;
5715
+ }
5716
+ throw new EnvAuthConfigError(`${failureContext}: ` + `${baseUrlError instanceof Error ? baseUrlError.message : String(baseUrlError)}`);
5717
+ }
5718
+ return baseUrl;
5719
+ };
4647
5720
  var readAuthFromEnv = () => {
4648
5721
  const accessToken = requireEnv(ENV_AUTH_VARS.token);
4649
5722
  const organizationName = requireEnv(ENV_AUTH_VARS.organizationName);
4650
5723
  const organizationId = requireEnv(ENV_AUTH_VARS.organizationId);
4651
5724
  const tenantName = requireEnv(ENV_AUTH_VARS.tenantName);
4652
5725
  const tenantId = requireEnv(ENV_AUTH_VARS.tenantId);
4653
- const [parseError, payload] = catchError(() => parseJWT(accessToken));
5726
+ const [parseError, payload] = catchError2(() => parseJWT(accessToken));
4654
5727
  if (parseError) {
4655
- throw new EnvAuthConfigError(`${ENV_AUTH_VARS.token} is not a valid JWT: ` + `${parseError instanceof Error ? parseError.message : String(parseError)}`);
5728
+ const parseErrorMessage = parseError instanceof Error ? parseError.message : String(parseError);
5729
+ const rawUrl = process.env[OPAQUE_TOKEN_BASE_URL_VAR];
5730
+ if (!rawUrl) {
5731
+ 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}).`);
5732
+ }
5733
+ const baseUrl2 = resolveBaseUrl(rawUrl, `Failed to validate ${OPAQUE_TOKEN_BASE_URL_VAR}`);
5734
+ return {
5735
+ loginStatus: "Logged in",
5736
+ accessToken,
5737
+ baseUrl: baseUrl2,
5738
+ organizationName,
5739
+ organizationId,
5740
+ tenantName,
5741
+ tenantId,
5742
+ source: "env-vars" /* EnvironmentVariables */,
5743
+ 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}`
5744
+ };
4656
5745
  }
4657
5746
  const iss = payload.iss;
4658
5747
  if (typeof iss !== "string" || iss.length === 0) {
4659
5748
  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.`);
4660
5749
  }
4661
- const [baseUrlError, baseUrl] = catchError(() => normalizeAndValidateBaseUrl(iss));
4662
- if (baseUrlError) {
4663
- if (baseUrlError instanceof InvalidBaseUrlError) {
4664
- throw baseUrlError;
4665
- }
4666
- throw new EnvAuthConfigError(`Failed to derive server URL from token 'iss' claim: ` + `${baseUrlError instanceof Error ? baseUrlError.message : String(baseUrlError)}`);
4667
- }
5750
+ const baseUrl = resolveBaseUrl(iss, "Failed to derive server URL from token 'iss' claim");
4668
5751
  const expiration = getTokenExpiration(accessToken);
4669
5752
  const loginStatus = expiration && expiration <= new Date ? "Expired" : "Logged in";
4670
5753
  const identity = resolveSessionIdentity(accessToken);
@@ -4690,8 +5773,8 @@ var SURFACE_WINDOW_MS = 60 * 60 * 1000;
4690
5773
  async function refreshTokenFingerprint(refreshToken) {
4691
5774
  const bytes = new TextEncoder().encode(refreshToken);
4692
5775
  if (globalThis.crypto?.subtle) {
4693
- const digest = await globalThis.crypto.subtle.digest("SHA-256", bytes);
4694
- return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("").slice(0, 16);
5776
+ const digest2 = await globalThis.crypto.subtle.digest("SHA-256", bytes);
5777
+ return Array.from(new Uint8Array(digest2), (b) => b.toString(16).padStart(2, "0")).join("").slice(0, 16);
4695
5778
  }
4696
5779
  const { createHash } = await import("node:crypto");
4697
5780
  return createHash("sha256").update(refreshToken).digest("hex").slice(0, 16);
@@ -4700,9 +5783,9 @@ function breakerPathFor(authPath) {
4700
5783
  return `${authPath}${BREAKER_SUFFIX}`;
4701
5784
  }
4702
5785
  async function loadRefreshBreaker(authPath) {
4703
- const fs = getFileSystem();
5786
+ const fs2 = getFileSystem();
4704
5787
  try {
4705
- const content = await fs.readFile(breakerPathFor(authPath), "utf-8");
5788
+ const content = await fs2.readFile(breakerPathFor(authPath), "utf-8");
4706
5789
  if (!content)
4707
5790
  return {};
4708
5791
  const parsed = JSON.parse(content);
@@ -4713,20 +5796,20 @@ async function loadRefreshBreaker(authPath) {
4713
5796
  }
4714
5797
  async function saveRefreshBreaker(authPath, state) {
4715
5798
  try {
4716
- const fs = getFileSystem();
4717
- const path = breakerPathFor(authPath);
4718
- await fs.mkdir(fs.path.dirname(path));
4719
- const tempPath = `${path}.tmp`;
4720
- await fs.writeFile(tempPath, JSON.stringify(state));
4721
- await fs.rename(tempPath, path);
5799
+ const fs2 = getFileSystem();
5800
+ const path2 = breakerPathFor(authPath);
5801
+ await fs2.mkdir(fs2.path.dirname(path2));
5802
+ const tempPath = `${path2}.tmp`;
5803
+ await fs2.writeFile(tempPath, JSON.stringify(state));
5804
+ await fs2.rename(tempPath, path2);
4722
5805
  } catch {}
4723
5806
  }
4724
5807
  async function clearRefreshBreaker(authPath) {
4725
- const fs = getFileSystem();
4726
- const path = breakerPathFor(authPath);
5808
+ const fs2 = getFileSystem();
5809
+ const path2 = breakerPathFor(authPath);
4727
5810
  try {
4728
- if (await fs.exists(path)) {
4729
- await fs.rm(path);
5811
+ if (await fs2.exists(path2)) {
5812
+ await fs2.rm(path2);
4730
5813
  }
4731
5814
  } catch {}
4732
5815
  }
@@ -4747,43 +5830,43 @@ var ROBOT_USER_SERVICES_PIPE = "UiPathUserServices";
4747
5830
  var ROBOT_USER_SERVICES_ALTERNATE_PIPE = `${ROBOT_USER_SERVICES_PIPE}Alternate`;
4748
5831
  var PIPE_NAME_MAX_LENGTH = 103;
4749
5832
  var getRobotIpcPipeNames = async () => {
4750
- const fs = getFileSystem();
4751
- const username = fs.env.getenv("USER") ?? fs.env.getenv("USERNAME");
5833
+ const fs2 = getFileSystem();
5834
+ const username = fs2.env.getenv("USER") ?? fs2.env.getenv("USERNAME");
4752
5835
  if (!username) {
4753
5836
  throw new Error("Unable to determine current username");
4754
5837
  }
4755
- const tempPath = fs.env.getenv("TMPDIR") ?? "/tmp/";
4756
- return [ROBOT_USER_SERVICES_PIPE, ROBOT_USER_SERVICES_ALTERNATE_PIPE].map((baseName) => fs.path.join(tempPath, `${baseName}_${username}`).substring(0, PIPE_NAME_MAX_LENGTH));
5838
+ const tempPath = fs2.env.getenv("TMPDIR") ?? "/tmp/";
5839
+ return [ROBOT_USER_SERVICES_PIPE, ROBOT_USER_SERVICES_ALTERNATE_PIPE].map((baseName) => fs2.path.join(tempPath, `${baseName}_${username}`).substring(0, PIPE_NAME_MAX_LENGTH));
4757
5840
  };
4758
5841
  var defaultIsRobotIpcAvailable = async () => {
4759
5842
  if (process.platform === "win32") {
4760
5843
  return true;
4761
5844
  }
4762
- const [pipeNamesError, pipeNames] = await catchError(getRobotIpcPipeNames());
5845
+ const [pipeNamesError, pipeNames] = await catchError2(getRobotIpcPipeNames());
4763
5846
  if (pipeNamesError || !pipeNames) {
4764
5847
  return false;
4765
5848
  }
4766
- const fs = getFileSystem();
5849
+ const fs2 = getFileSystem();
4767
5850
  for (const pipeName of pipeNames) {
4768
- const [existsError, exists] = await catchError(fs.exists(pipeName));
5851
+ const [existsError, exists] = await catchError2(fs2.exists(pipeName));
4769
5852
  if (!existsError && exists === true) {
4770
5853
  return true;
4771
5854
  }
4772
5855
  }
4773
5856
  return false;
4774
5857
  };
4775
- var withTimeout = (promise, timeoutMs) => new Promise((resolve, reject) => {
5858
+ var withTimeout = (promise, timeoutMs) => new Promise((resolve2, reject) => {
4776
5859
  const timer = setTimeout(() => reject(new Error(`Robot IPC call timed out after ${timeoutMs}ms`)), timeoutMs);
4777
5860
  promise.then((value) => {
4778
5861
  clearTimeout(timer);
4779
- resolve(value);
5862
+ resolve2(value);
4780
5863
  }, (error) => {
4781
5864
  clearTimeout(timer);
4782
5865
  reject(error);
4783
5866
  });
4784
5867
  });
4785
5868
  var parseResourceUrl = (url) => {
4786
- const [error, parsed] = catchError(() => new URL(url));
5869
+ const [error, parsed] = catchError2(() => new URL(url));
4787
5870
  if (error || !parsed)
4788
5871
  return;
4789
5872
  const segments = parsed.pathname.split("/").filter(Boolean);
@@ -4803,7 +5886,7 @@ var defaultLoadModule = async () => {
4803
5886
  if (!hostLoader) {
4804
5887
  return;
4805
5888
  }
4806
- const [error, mod] = await catchError(() => hostLoader());
5889
+ const [error, mod] = await catchError2(() => hostLoader());
4807
5890
  if (error || !mod) {
4808
5891
  return;
4809
5892
  }
@@ -4829,7 +5912,7 @@ var tryRobotClientFallback = async (options = {}) => {
4829
5912
  const mod = await loadModule();
4830
5913
  if (!mod)
4831
5914
  return;
4832
- const [ctorError, proxy] = catchError(() => new mod.RobotProxyConstructor);
5915
+ const [ctorError, proxy] = catchError2(() => new mod.RobotProxyConstructor);
4833
5916
  if (ctorError || !proxy) {
4834
5917
  return;
4835
5918
  }
@@ -4852,7 +5935,7 @@ var tryRobotClientFallback = async (options = {}) => {
4852
5935
  let organizationIdFromToken;
4853
5936
  let tenantIdFromToken;
4854
5937
  let issuerFromToken;
4855
- const [jwtError, claims] = catchError(() => parseJWT(accessToken));
5938
+ const [jwtError, claims] = catchError2(() => parseJWT(accessToken));
4856
5939
  if (!jwtError && claims) {
4857
5940
  const rawOrgId = claims.prtId ?? claims.organizationId ?? claims.prt_id;
4858
5941
  if (typeof rawOrgId === "string" && rawOrgId.length > 0) {
@@ -4879,7 +5962,7 @@ var tryRobotClientFallback = async (options = {}) => {
4879
5962
  } catch {
4880
5963
  return;
4881
5964
  } finally {
4882
- await catchError(() => withTimeout(proxy.CloseAsync(), CLOSE_TIMEOUT_MS));
5965
+ await catchError2(() => withTimeout(proxy.CloseAsync(), CLOSE_TIMEOUT_MS));
4883
5966
  }
4884
5967
  };
4885
5968
 
@@ -4949,9 +6032,9 @@ var errorCode = (err) => {
4949
6032
  }
4950
6033
  return "EUNKNOWN";
4951
6034
  };
4952
- var probeAsync = async (fs, candidate) => {
6035
+ var probeAsync = async (fs2, candidate) => {
4953
6036
  try {
4954
- const stats = await fs.stat(candidate);
6037
+ const stats = await fs2.stat(candidate);
4955
6038
  if (stats === null) {
4956
6039
  return { exists: false };
4957
6040
  }
@@ -4978,9 +6061,9 @@ var probeAsync = async (fs, candidate) => {
4978
6061
  }
4979
6062
  };
4980
6063
  var resolveEnvFileLocationAsync = async (envFilePath = DEFAULT_ENV_FILENAME, opts) => {
4981
- const fs = getFileSystem();
4982
- if (fs.path.isAbsolute(envFilePath)) {
4983
- const probe2 = await probeAsync(fs, envFilePath);
6064
+ const fs2 = getFileSystem();
6065
+ if (fs2.path.isAbsolute(envFilePath)) {
6066
+ const probe2 = await probeAsync(fs2, envFilePath);
4984
6067
  return probe2.exists ? { exists: true, absolutePath: envFilePath, source: "absolute" } : {
4985
6068
  exists: false,
4986
6069
  absolutePath: envFilePath,
@@ -4988,11 +6071,11 @@ var resolveEnvFileLocationAsync = async (envFilePath = DEFAULT_ENV_FILENAME, opt
4988
6071
  ...probe2.unusable ? { unusable: probe2.unusable } : {}
4989
6072
  };
4990
6073
  }
4991
- const cwd = opts?.cwd ?? fs.env.cwd();
6074
+ const cwd = opts?.cwd ?? fs2.env.cwd();
4992
6075
  let searchDir = cwd;
4993
6076
  while (true) {
4994
- const candidate = fs.path.join(searchDir, envFilePath);
4995
- const probe2 = await probeAsync(fs, candidate);
6077
+ const candidate = fs2.path.join(searchDir, envFilePath);
6078
+ const probe2 = await probeAsync(fs2, candidate);
4996
6079
  if (probe2.exists) {
4997
6080
  return {
4998
6081
  exists: true,
@@ -5000,14 +6083,14 @@ var resolveEnvFileLocationAsync = async (envFilePath = DEFAULT_ENV_FILENAME, opt
5000
6083
  source: searchDir === cwd ? "cwd" : "ancestor"
5001
6084
  };
5002
6085
  }
5003
- const parentDir = fs.path.dirname(searchDir);
6086
+ const parentDir = fs2.path.dirname(searchDir);
5004
6087
  if (parentDir === searchDir) {
5005
6088
  break;
5006
6089
  }
5007
6090
  searchDir = parentDir;
5008
6091
  }
5009
- const homePath = fs.path.join(fs.env.homedir(), envFilePath);
5010
- const probe = await probeAsync(fs, homePath);
6092
+ const homePath = fs2.path.join(fs2.env.homedir(), envFilePath);
6093
+ const probe = await probeAsync(fs2, homePath);
5011
6094
  if (probe.exists) {
5012
6095
  return { exists: true, absolutePath: homePath, source: "home" };
5013
6096
  }
@@ -5029,12 +6112,12 @@ var resolveEnvFilePathAsync = async (envFilePath = DEFAULT_ENV_FILENAME, opts) =
5029
6112
  };
5030
6113
  };
5031
6114
  var loadEnvFileAsync = async ({ envPath }) => {
5032
- const fs = getFileSystem();
5033
- const absolutePath = fs.path.isAbsolute(envPath) ? envPath : fs.path.join(fs.env.cwd(), envPath);
5034
- if (!await fs.exists(absolutePath)) {
6115
+ const fs2 = getFileSystem();
6116
+ const absolutePath = fs2.path.isAbsolute(envPath) ? envPath : fs2.path.join(fs2.env.cwd(), envPath);
6117
+ if (!await fs2.exists(absolutePath)) {
5035
6118
  throw new Error(`Environment file not found: ${envPath}`);
5036
6119
  }
5037
- const content = await fs.readFile(absolutePath, "utf-8");
6120
+ const content = await fs2.readFile(absolutePath, "utf-8");
5038
6121
  if (content === null) {
5039
6122
  throw new Error(`Environment file not found: ${envPath}`);
5040
6123
  }
@@ -5063,10 +6146,10 @@ var saveEnvFileAsync = async ({
5063
6146
  data,
5064
6147
  merge = true
5065
6148
  }) => {
5066
- const fs = getFileSystem();
5067
- const absolutePath = fs.path.isAbsolute(envPath) ? envPath : fs.path.join(fs.env.homedir(), envPath);
6149
+ const fs2 = getFileSystem();
6150
+ const absolutePath = fs2.path.isAbsolute(envPath) ? envPath : fs2.path.join(fs2.env.homedir(), envPath);
5068
6151
  let existingData = {};
5069
- if (merge && await fs.exists(absolutePath)) {
6152
+ if (merge && await fs2.exists(absolutePath)) {
5070
6153
  try {
5071
6154
  existingData = await loadEnvFileAsync({ envPath: absolutePath });
5072
6155
  } catch {}
@@ -5084,11 +6167,11 @@ var saveEnvFileAsync = async ({
5084
6167
  const content = `${lines.join(`
5085
6168
  `)}
5086
6169
  `;
5087
- const dir = fs.path.dirname(absolutePath);
5088
- await fs.mkdir(dir);
6170
+ const dir = fs2.path.dirname(absolutePath);
6171
+ await fs2.mkdir(dir);
5089
6172
  const tempPath = `${absolutePath}.tmp`;
5090
- await fs.writeFile(tempPath, content);
5091
- await fs.rename(tempPath, absolutePath);
6173
+ await fs2.writeFile(tempPath, content);
6174
+ await fs2.rename(tempPath, absolutePath);
5092
6175
  };
5093
6176
 
5094
6177
  // ../auth/src/loginStatus.ts
@@ -5202,11 +6285,11 @@ async function loadFileCredentials(loadEnvFile, absolutePath) {
5202
6285
  return { credentials };
5203
6286
  }
5204
6287
  async function getGlobalCredsHint(getFs, loadEnvFile, absolutePath, envFilePath) {
5205
- const fs = getFs();
5206
- const globalPath = fs.path.join(fs.env.homedir(), envFilePath);
6288
+ const fs2 = getFs();
6289
+ const globalPath = fs2.path.join(fs2.env.homedir(), envFilePath);
5207
6290
  if (absolutePath === globalPath)
5208
6291
  return;
5209
- if (!await fs.exists(globalPath))
6292
+ if (!await fs2.exists(globalPath))
5210
6293
  return;
5211
6294
  try {
5212
6295
  const globalCreds = await loadEnvFile({ envPath: globalPath });
@@ -5597,7 +6680,7 @@ var asReadyStatus = (status) => {
5597
6680
  };
5598
6681
  };
5599
6682
  var discoverModels = async (ready) => {
5600
- const [error, response] = await catchError2(fetch(`${ready.gatewayBase}/api/chat/completions`, {
6683
+ const [error, response] = await catchError(fetch(`${ready.gatewayBase}/api/chat/completions`, {
5601
6684
  headers: { Authorization: `Bearer ${ready.accessToken}` },
5602
6685
  signal: AbortSignal.timeout(MODEL_DISCOVERY_TIMEOUT_MS)
5603
6686
  }));
@@ -5605,7 +6688,7 @@ var discoverModels = async (ready) => {
5605
6688
  logger.debug(`[coder-tool] LLM Gateway model discovery failed: ${error?.message ?? response?.status}`);
5606
6689
  return;
5607
6690
  }
5608
- const [parseError, parsed] = await catchError2(response.json());
6691
+ const [parseError, parsed] = await catchError(response.json());
5609
6692
  if (parseError) {
5610
6693
  return;
5611
6694
  }
@@ -5647,7 +6730,7 @@ var createUiPathProviderExtension = () => {
5647
6730
  let cachedModels;
5648
6731
  let tokenExpiration;
5649
6732
  const register = async (pi) => {
5650
- const [error, status] = await catchError2(getLoginStatusAsync({
6733
+ const [error, status] = await catchError(getLoginStatusAsync({
5651
6734
  ensureTokenValidityMinutes: TOKEN_VALIDITY_MINUTES
5652
6735
  }));
5653
6736
  if (error) {
@@ -5698,15 +6781,15 @@ var PI_SUBCOMMANDS = new Set([
5698
6781
  "config"
5699
6782
  ]);
5700
6783
  async function resolveAgentGuide() {
5701
- const fs = getFileSystem();
6784
+ const fs2 = getFileSystem();
5702
6785
  const candidates = [
5703
6786
  new URL("./templates/uipath-cli.md", import.meta.url),
5704
6787
  new URL("../../templates/uipath-cli.md", import.meta.url)
5705
6788
  ];
5706
6789
  for (const url of candidates) {
5707
- const path = fileURLToPath(url);
5708
- if (await fs.exists(path)) {
5709
- const text = await fs.readFile(path, "utf-8");
6790
+ const path2 = fileURLToPath(url);
6791
+ if (await fs2.exists(path2)) {
6792
+ const text = await fs2.readFile(path2, "utf-8");
5710
6793
  return text ?? undefined;
5711
6794
  }
5712
6795
  }
@@ -5727,8 +6810,8 @@ async function runPi(args, hardExit) {
5727
6810
  const originalExit = process.exit;
5728
6811
  let requestedExitCode;
5729
6812
  let resolveExit = () => {};
5730
- const exitRequested = new Promise((resolve) => {
5731
- resolveExit = resolve;
6813
+ const exitRequested = new Promise((resolve2) => {
6814
+ resolveExit = resolve2;
5732
6815
  });
5733
6816
  process.exit = (code) => {
5734
6817
  requestedExitCode = typeof code === "number" ? code : process.exitCode ?? 0;
@@ -5775,4 +6858,4 @@ var registerCommands = async (program2) => {
5775
6858
 
5776
6859
  export { Command, setPreviewBuild, metadata, registerCommands };
5777
6860
 
5778
- //# debugId=41BAB03489CD24B364756E2164756E21
6861
+ //# debugId=9DD9C148C44A6E2564756E2164756E21