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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,23 +1,11 @@
1
- import {
2
- isBrowser
3
- } from "./tool-eb3gcj08.js";
4
- import {
5
- catchError,
6
- getFileSystem
7
- } from "./tool-rr9mn0nz.js";
8
- import {
9
- AUTH_FILENAME,
10
- DEFAULT_BASE_URL,
11
- UIPATH_HOME_DIR
12
- } from "./tool-yy8n2117.js";
13
1
  import {
14
2
  __commonJS,
15
3
  __require,
16
4
  __toESM
17
- } from "./tool-0v6na3yp.js";
5
+ } from "./tool-1de529jm.js";
18
6
 
19
7
  // ../../../node_modules/commander/lib/error.js
20
- var require_error = __commonJS((exports) => {
8
+ var require_error = __commonJS(function(exports) {
21
9
  class CommanderError extends Error {
22
10
  constructor(exitCode, code, message) {
23
11
  super(message);
@@ -41,7 +29,7 @@ var require_error = __commonJS((exports) => {
41
29
  });
42
30
 
43
31
  // ../../../node_modules/commander/lib/argument.js
44
- var require_argument = __commonJS((exports) => {
32
+ var require_argument = __commonJS(function(exports) {
45
33
  var { InvalidArgumentError } = require_error();
46
34
 
47
35
  class Argument {
@@ -121,7 +109,7 @@ var require_argument = __commonJS((exports) => {
121
109
  });
122
110
 
123
111
  // ../../../node_modules/commander/lib/help.js
124
- var require_help = __commonJS((exports) => {
112
+ var require_help = __commonJS(function(exports) {
125
113
  var { humanReadableArgName } = require_argument();
126
114
 
127
115
  class Help {
@@ -478,7 +466,7 @@ ${itemIndentStr}`);
478
466
  });
479
467
 
480
468
  // ../../../node_modules/commander/lib/option.js
481
- var require_option = __commonJS((exports) => {
469
+ var require_option = __commonJS(function(exports) {
482
470
  var { InvalidArgumentError } = require_error();
483
471
 
484
472
  class Option {
@@ -662,7 +650,7 @@ var require_option = __commonJS((exports) => {
662
650
  });
663
651
 
664
652
  // ../../../node_modules/commander/lib/suggestSimilar.js
665
- var require_suggestSimilar = __commonJS((exports) => {
653
+ var require_suggestSimilar = __commonJS(function(exports) {
666
654
  var maxDistance = 3;
667
655
  function editDistance(a, b) {
668
656
  if (Math.abs(a.length - b.length) > maxDistance)
@@ -735,11 +723,11 @@ var require_suggestSimilar = __commonJS((exports) => {
735
723
  });
736
724
 
737
725
  // ../../../node_modules/commander/lib/command.js
738
- var require_command = __commonJS((exports) => {
726
+ var require_command = __commonJS(function(exports) {
739
727
  var EventEmitter = __require("node:events").EventEmitter;
740
728
  var childProcess = __require("node:child_process");
741
- var path = __require("node:path");
742
- var fs = __require("node:fs");
729
+ var path2 = __require("node:path");
730
+ var fs2 = __require("node:fs");
743
731
  var process2 = __require("node:process");
744
732
  var { Argument, humanReadableArgName } = require_argument();
745
733
  var { CommanderError } = require_error();
@@ -1274,7 +1262,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
1274
1262
  this.processedArgs = [];
1275
1263
  }
1276
1264
  _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
1277
- if (fs.existsSync(executableFile))
1265
+ if (fs2.existsSync(executableFile))
1278
1266
  return;
1279
1267
  const executableDirMessage = executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory";
1280
1268
  const executableMissing = `'${executableFile}' does not exist
@@ -1288,12 +1276,12 @@ Expecting one of '${allowedValues.join("', '")}'`);
1288
1276
  let launchWithNode = false;
1289
1277
  const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
1290
1278
  function findFile(baseDir, baseName) {
1291
- const localBin = path.resolve(baseDir, baseName);
1292
- if (fs.existsSync(localBin))
1279
+ const localBin = path2.resolve(baseDir, baseName);
1280
+ if (fs2.existsSync(localBin))
1293
1281
  return localBin;
1294
- if (sourceExt.includes(path.extname(baseName)))
1282
+ if (sourceExt.includes(path2.extname(baseName)))
1295
1283
  return;
1296
- const foundExt = sourceExt.find((ext) => fs.existsSync(`${localBin}${ext}`));
1284
+ const foundExt = sourceExt.find((ext) => fs2.existsSync(`${localBin}${ext}`));
1297
1285
  if (foundExt)
1298
1286
  return `${localBin}${foundExt}`;
1299
1287
  return;
@@ -1305,23 +1293,23 @@ Expecting one of '${allowedValues.join("', '")}'`);
1305
1293
  if (this._scriptPath) {
1306
1294
  let resolvedScriptPath;
1307
1295
  try {
1308
- resolvedScriptPath = fs.realpathSync(this._scriptPath);
1296
+ resolvedScriptPath = fs2.realpathSync(this._scriptPath);
1309
1297
  } catch {
1310
1298
  resolvedScriptPath = this._scriptPath;
1311
1299
  }
1312
- executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
1300
+ executableDir = path2.resolve(path2.dirname(resolvedScriptPath), executableDir);
1313
1301
  }
1314
1302
  if (executableDir) {
1315
1303
  let localFile = findFile(executableDir, executableFile);
1316
1304
  if (!localFile && !subcommand._executableFile && this._scriptPath) {
1317
- const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
1305
+ const legacyName = path2.basename(this._scriptPath, path2.extname(this._scriptPath));
1318
1306
  if (legacyName !== this._name) {
1319
1307
  localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
1320
1308
  }
1321
1309
  }
1322
1310
  executableFile = localFile || executableFile;
1323
1311
  }
1324
- launchWithNode = sourceExt.includes(path.extname(executableFile));
1312
+ launchWithNode = sourceExt.includes(path2.extname(executableFile));
1325
1313
  let proc;
1326
1314
  if (process2.platform !== "win32") {
1327
1315
  if (launchWithNode) {
@@ -1910,13 +1898,13 @@ Expecting one of '${allowedValues.join("', '")}'`);
1910
1898
  cmd.helpGroup(this._defaultCommandGroup);
1911
1899
  }
1912
1900
  nameFromFilename(filename) {
1913
- this._name = path.basename(filename, path.extname(filename));
1901
+ this._name = path2.basename(filename, path2.extname(filename));
1914
1902
  return this;
1915
1903
  }
1916
- executableDir(path2) {
1917
- if (path2 === undefined)
1904
+ executableDir(path3) {
1905
+ if (path3 === undefined)
1918
1906
  return this._executableDir;
1919
- this._executableDir = path2;
1907
+ this._executableDir = path3;
1920
1908
  return this;
1921
1909
  }
1922
1910
  helpInformation(contextOptions) {
@@ -2090,7 +2078,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
2090
2078
  });
2091
2079
 
2092
2080
  // ../../../node_modules/commander/index.js
2093
- var require_commander = __commonJS((exports) => {
2081
+ var require_commander = __commonJS(function(exports) {
2094
2082
  var { Argument } = require_argument();
2095
2083
  var { Command } = require_command();
2096
2084
  var { CommanderError, InvalidArgumentError } = require_error();
@@ -2112,7 +2100,7 @@ var require_commander = __commonJS((exports) => {
2112
2100
  var package_default = {
2113
2101
  name: "@uipath/apms-tool",
2114
2102
  license: "MIT",
2115
- version: "1.201.0",
2103
+ version: "1.202.0-preview.136",
2116
2104
  description: "CLI plugin for the UiPath Access Policy Management Service.",
2117
2105
  private: false,
2118
2106
  repository: {
@@ -2520,7 +2508,7 @@ class VoidApiResponse {
2520
2508
  var package_default2 = {
2521
2509
  name: "@uipath/apms-sdk",
2522
2510
  license: "MIT",
2523
- version: "1.201.0",
2511
+ version: "1.202.0",
2524
2512
  description: "SDK for the UiPath Access Policy Management Service API.",
2525
2513
  repository: {
2526
2514
  type: "git",
@@ -3546,6 +3534,40 @@ class RegexBypassApi extends BaseAPI {
3546
3534
  return await response.value();
3547
3535
  }
3548
3536
  }
3537
+ // ../../auth/src/catch-error.ts
3538
+ function isPromiseLike(value) {
3539
+ return value !== null && typeof value === "object" && typeof value.then === "function";
3540
+ }
3541
+ function catchError(fnOrPromise) {
3542
+ if (isPromiseLike(fnOrPromise)) {
3543
+ return settlePromiseLike(fnOrPromise);
3544
+ }
3545
+ try {
3546
+ const result = fnOrPromise();
3547
+ if (isPromiseLike(result)) {
3548
+ return settlePromiseLike(result);
3549
+ }
3550
+ return [undefined, result];
3551
+ } catch (error) {
3552
+ return [
3553
+ error instanceof Error ? error : new Error(String(error)),
3554
+ undefined
3555
+ ];
3556
+ }
3557
+ }
3558
+ function settlePromiseLike(thenable) {
3559
+ return Promise.resolve(thenable).then((data) => [undefined, data]).catch((error) => [
3560
+ error instanceof Error ? error : new Error(String(error)),
3561
+ undefined
3562
+ ]);
3563
+ }
3564
+
3565
+ // ../../auth/src/constants.ts
3566
+ var UIPATH_HOME_DIR = ".uipath";
3567
+ var AUTH_FILENAME = ".auth";
3568
+ var DEFAULT_BASE_URL = "https://cloud.uipath.com";
3569
+ var DEFAULT_AUTH_TIMEOUT_MS = 5 * 60 * 1000;
3570
+
3549
3571
  // ../../auth/src/config.ts
3550
3572
  var DEFAULT_CLIENT_ID = "36dea5b8-e8bb-423d-8e7b-c808df8f1c00";
3551
3573
  var AUTH_FILE_CONFIG_KEY = Symbol.for("@uipath/auth/AuthFileConfig");
@@ -3559,7 +3581,7 @@ class InvalidBaseUrlError extends Error {
3559
3581
  super(`Invalid base URL: "${url}"
3560
3582
  ` + `Reason: ${reason}
3561
3583
 
3562
- ` + `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>).
3584
+ ` + `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>).
3563
3585
  ` + `You can specify the URL via:
3564
3586
  ` + ` • --authority flag
3565
3587
  ` + ` • UIPATH_URL environment variable
@@ -3580,10 +3602,16 @@ var normalizeAndValidateBaseUrl = (rawUrl) => {
3580
3602
  while (baseUrl.endsWith("/")) {
3581
3603
  baseUrl = baseUrl.slice(0, -1);
3582
3604
  }
3605
+ const hasScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(baseUrl);
3606
+ const [hostCandidate] = baseUrl.split(/[/?#]/, 1);
3607
+ if (!hasScheme && hostCandidate.includes(".")) {
3608
+ baseUrl = `https://${baseUrl}`;
3609
+ }
3583
3610
  const resolvedBaseUrl = baseUrl;
3584
3611
  const [urlError, url] = catchError(() => new URL(resolvedBaseUrl));
3585
3612
  if (urlError) {
3586
- throw new InvalidBaseUrlError(baseUrl, `Malformed URL. ${urlError instanceof Error ? urlError.message : "Unknown error"}`);
3613
+ 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"}`;
3614
+ throw new InvalidBaseUrlError(baseUrl, `Malformed URL.${shapeHint}`);
3587
3615
  }
3588
3616
  if (url.protocol !== "https:") {
3589
3617
  throw new InvalidBaseUrlError(baseUrl, `Authority must use https:// scheme, got ${url.protocol}//. OIDC token exchange requires TLS end-to-end.`);
@@ -3638,6 +3666,241 @@ var resolveConfigAsync = async ({
3638
3666
  };
3639
3667
  };
3640
3668
 
3669
+ // ../../auth/src/utils/platform.ts
3670
+ function isBrowser() {
3671
+ return typeof globalThis !== "undefined" && "window" in globalThis && "document" in globalThis;
3672
+ }
3673
+
3674
+ // ../../filesystem/src/node.ts
3675
+ import { randomUUID } from "node:crypto";
3676
+ import { existsSync } from "node:fs";
3677
+ import * as fs from "node:fs/promises";
3678
+ import * as os from "node:os";
3679
+ import * as path from "node:path";
3680
+ var LOCK_HEARTBEAT_MS = 5000;
3681
+ var LOCK_STALE_MS = 15000;
3682
+ var LOCK_MAX_WAIT_MS = 20000;
3683
+ var LOCK_MAX_HOLD_MS = 60000;
3684
+ var LOCK_RETRY_MIN_MS = 100;
3685
+ var LOCK_RETRY_JITTER_MS = 200;
3686
+
3687
+ class NodeFileSystem {
3688
+ path = {
3689
+ join: path.join,
3690
+ resolve: path.resolve,
3691
+ relative: path.relative,
3692
+ dirname: path.dirname,
3693
+ isAbsolute: path.isAbsolute,
3694
+ basename: path.basename
3695
+ };
3696
+ env = {
3697
+ cwd: process.cwd,
3698
+ homedir: os.homedir,
3699
+ tmpdir: os.tmpdir,
3700
+ getenv: (key) => process.env[key]
3701
+ };
3702
+ utils = {
3703
+ open: async (url) => {
3704
+ const { default: open } = await import("./index-xnzgkhtg.js");
3705
+ await open(url);
3706
+ }
3707
+ };
3708
+ async readFile(path2, options) {
3709
+ try {
3710
+ if (options) {
3711
+ return await fs.readFile(path2, "utf-8");
3712
+ }
3713
+ return await fs.readFile(path2);
3714
+ } catch (error) {
3715
+ if (this.isEnoent(error))
3716
+ return null;
3717
+ throw error;
3718
+ }
3719
+ }
3720
+ async writeFile(filePath, data) {
3721
+ const dir = path.dirname(filePath);
3722
+ if (dir) {
3723
+ await fs.mkdir(dir, { recursive: true });
3724
+ }
3725
+ await fs.writeFile(filePath, data);
3726
+ }
3727
+ async appendFile(filePath, data) {
3728
+ const dir = path.dirname(filePath);
3729
+ if (dir) {
3730
+ await fs.mkdir(dir, { recursive: true });
3731
+ }
3732
+ await fs.appendFile(filePath, data);
3733
+ }
3734
+ async readdir(dirPath) {
3735
+ try {
3736
+ return await fs.readdir(dirPath);
3737
+ } catch (error) {
3738
+ if (this.isEnoent(error))
3739
+ return [];
3740
+ throw error;
3741
+ }
3742
+ }
3743
+ async stat(filePath) {
3744
+ try {
3745
+ const stats = await fs.stat(filePath);
3746
+ return {
3747
+ isFile: () => stats.isFile(),
3748
+ isDirectory: () => stats.isDirectory(),
3749
+ size: stats.size,
3750
+ mtimeMs: stats.mtimeMs
3751
+ };
3752
+ } catch (error) {
3753
+ if (this.isEnoent(error))
3754
+ return null;
3755
+ throw error;
3756
+ }
3757
+ }
3758
+ async exists(filePath) {
3759
+ return existsSync(filePath);
3760
+ }
3761
+ async mkdir(dirPath) {
3762
+ await fs.mkdir(dirPath, { recursive: true });
3763
+ }
3764
+ async acquireLock(lockPath) {
3765
+ const canonicalPath = await this.canonicalizeLockTarget(lockPath);
3766
+ const lockFile = `${canonicalPath}.lock`;
3767
+ const ownerId = randomUUID();
3768
+ const start = Date.now();
3769
+ while (true) {
3770
+ try {
3771
+ await fs.writeFile(lockFile, ownerId, { flag: "wx" });
3772
+ return this.createLockRelease(lockFile, ownerId);
3773
+ } catch (error) {
3774
+ if (!this.hasErrnoCode(error, "EEXIST")) {
3775
+ throw error;
3776
+ }
3777
+ const stats = await fs.stat(lockFile).catch(() => null);
3778
+ if (stats && Date.now() - stats.mtimeMs > LOCK_STALE_MS) {
3779
+ const reclaimed = await fs.rm(lockFile, { force: true }).then(() => true).catch(() => false);
3780
+ if (reclaimed)
3781
+ continue;
3782
+ }
3783
+ if (Date.now() - start > LOCK_MAX_WAIT_MS) {
3784
+ throw new Error(`ELOCKED: timed out waiting for lock on ${canonicalPath}`);
3785
+ }
3786
+ await new Promise((resolve2) => setTimeout(resolve2, LOCK_RETRY_MIN_MS + Math.random() * LOCK_RETRY_JITTER_MS));
3787
+ }
3788
+ }
3789
+ }
3790
+ async canonicalizeLockTarget(lockPath) {
3791
+ const absolute = path.resolve(lockPath);
3792
+ const fullReal = await fs.realpath(absolute).catch(() => null);
3793
+ if (fullReal)
3794
+ return fullReal;
3795
+ const parent = path.dirname(absolute);
3796
+ const base = path.basename(absolute);
3797
+ const canonicalParent = await fs.realpath(parent).catch(() => parent);
3798
+ return path.join(canonicalParent, base);
3799
+ }
3800
+ createLockRelease(lockFile, ownerId) {
3801
+ const heartbeatStart = Date.now();
3802
+ let heartbeatTimer;
3803
+ let stopped = false;
3804
+ const stopHeartbeat = () => {
3805
+ stopped = true;
3806
+ if (heartbeatTimer)
3807
+ clearTimeout(heartbeatTimer);
3808
+ };
3809
+ const scheduleNextHeartbeat = () => {
3810
+ if (stopped)
3811
+ return;
3812
+ if (Date.now() - heartbeatStart >= LOCK_MAX_HOLD_MS) {
3813
+ stopped = true;
3814
+ return;
3815
+ }
3816
+ heartbeatTimer = setTimeout(() => {
3817
+ runHeartbeat();
3818
+ }, LOCK_HEARTBEAT_MS);
3819
+ heartbeatTimer.unref?.();
3820
+ };
3821
+ const runHeartbeat = async () => {
3822
+ if (stopped)
3823
+ return;
3824
+ const current = await fs.readFile(lockFile, "utf-8").catch(() => null);
3825
+ if (stopped)
3826
+ return;
3827
+ if (current !== ownerId) {
3828
+ stopped = true;
3829
+ return;
3830
+ }
3831
+ const now = Date.now() / 1000;
3832
+ await fs.utimes(lockFile, now, now).catch(() => {});
3833
+ scheduleNextHeartbeat();
3834
+ };
3835
+ scheduleNextHeartbeat();
3836
+ let released = false;
3837
+ return async () => {
3838
+ if (released)
3839
+ return;
3840
+ released = true;
3841
+ stopHeartbeat();
3842
+ const current = await fs.readFile(lockFile, "utf-8").catch(() => null);
3843
+ if (current === ownerId) {
3844
+ await fs.rm(lockFile, { force: true });
3845
+ }
3846
+ };
3847
+ }
3848
+ async rm(filePath) {
3849
+ await fs.rm(filePath, { recursive: true, force: true });
3850
+ }
3851
+ async rename(oldPath, newPath) {
3852
+ await fs.rename(oldPath, newPath);
3853
+ }
3854
+ async realpath(filePath) {
3855
+ try {
3856
+ return await fs.realpath(filePath);
3857
+ } catch (error) {
3858
+ if (this.isEnoent(error))
3859
+ return filePath;
3860
+ throw error;
3861
+ }
3862
+ }
3863
+ async getTempDir() {
3864
+ return await fs.mkdtemp(path.join(os.tmpdir(), "uipath-fs-"));
3865
+ }
3866
+ async copyDirectory(sourcePath, destPath) {
3867
+ const sourceStats = await this.stat(sourcePath);
3868
+ if (!sourceStats) {
3869
+ throw new Error(`Source directory does not exist: ${sourcePath}`);
3870
+ }
3871
+ if (!sourceStats.isDirectory()) {
3872
+ throw new Error(`Source path is not a directory: ${sourcePath}`);
3873
+ }
3874
+ await this.mkdir(destPath);
3875
+ const entries = await this.readdir(sourcePath);
3876
+ for (const entry of entries) {
3877
+ const srcEntry = path.join(sourcePath, entry);
3878
+ const destEntry = path.join(destPath, entry);
3879
+ const entryStats = await this.stat(srcEntry);
3880
+ if (!entryStats)
3881
+ continue;
3882
+ if (entryStats.isDirectory()) {
3883
+ await this.copyDirectory(srcEntry, destEntry);
3884
+ } else if (entryStats.isFile()) {
3885
+ const content = await this.readFile(srcEntry);
3886
+ if (content !== null) {
3887
+ await this.writeFile(destEntry, content);
3888
+ }
3889
+ }
3890
+ }
3891
+ }
3892
+ isEnoent(error) {
3893
+ return this.hasErrnoCode(error, "ENOENT");
3894
+ }
3895
+ hasErrnoCode(error, code) {
3896
+ return typeof error === "object" && error !== null && "code" in error && error.code === code;
3897
+ }
3898
+ }
3899
+
3900
+ // ../../filesystem/src/index.ts
3901
+ var fsInstance = new NodeFileSystem;
3902
+ var getFileSystem = () => fsInstance;
3903
+
3641
3904
  // ../../auth/src/authProfile.ts
3642
3905
  var DEFAULT_AUTH_PROFILE = "default";
3643
3906
  var PROFILE_DIR = "profiles";
@@ -3698,8 +3961,8 @@ function resolveAuthProfileFilePath(profile) {
3698
3961
  if (normalized === undefined) {
3699
3962
  throw new AuthProfileValidationError(`"${DEFAULT_AUTH_PROFILE}" is the built-in profile and does not have a profile file path.`);
3700
3963
  }
3701
- const fs = getFileSystem();
3702
- return fs.path.join(fs.env.homedir(), UIPATH_HOME_DIR, PROFILE_DIR, normalized, AUTH_FILENAME);
3964
+ const fs2 = getFileSystem();
3965
+ return fs2.path.join(fs2.env.homedir(), UIPATH_HOME_DIR, PROFILE_DIR, normalized, AUTH_FILENAME);
3703
3966
  }
3704
3967
  function getActiveAuthProfileFilePath() {
3705
3968
  const profile = getActiveAuthProfile();
@@ -3864,6 +4127,17 @@ var requireEnv = (name) => {
3864
4127
  }
3865
4128
  return value;
3866
4129
  };
4130
+ var OPAQUE_TOKEN_BASE_URL_VAR = "UIPATH_URL";
4131
+ var resolveBaseUrl = (rawUrl, failureContext) => {
4132
+ const [baseUrlError, baseUrl] = catchError(() => normalizeAndValidateBaseUrl(rawUrl));
4133
+ if (baseUrlError) {
4134
+ if (baseUrlError instanceof InvalidBaseUrlError) {
4135
+ throw baseUrlError;
4136
+ }
4137
+ throw new EnvAuthConfigError(`${failureContext}: ` + `${baseUrlError instanceof Error ? baseUrlError.message : String(baseUrlError)}`);
4138
+ }
4139
+ return baseUrl;
4140
+ };
3867
4141
  var readAuthFromEnv = () => {
3868
4142
  const accessToken = requireEnv(ENV_AUTH_VARS.token);
3869
4143
  const organizationName = requireEnv(ENV_AUTH_VARS.organizationName);
@@ -3872,19 +4146,29 @@ var readAuthFromEnv = () => {
3872
4146
  const tenantId = requireEnv(ENV_AUTH_VARS.tenantId);
3873
4147
  const [parseError, payload] = catchError(() => parseJWT(accessToken));
3874
4148
  if (parseError) {
3875
- throw new EnvAuthConfigError(`${ENV_AUTH_VARS.token} is not a valid JWT: ` + `${parseError instanceof Error ? parseError.message : String(parseError)}`);
4149
+ const parseErrorMessage = parseError instanceof Error ? parseError.message : String(parseError);
4150
+ const rawUrl = process.env[OPAQUE_TOKEN_BASE_URL_VAR];
4151
+ if (!rawUrl) {
4152
+ 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}).`);
4153
+ }
4154
+ const baseUrl2 = resolveBaseUrl(rawUrl, `Failed to validate ${OPAQUE_TOKEN_BASE_URL_VAR}`);
4155
+ return {
4156
+ loginStatus: "Logged in",
4157
+ accessToken,
4158
+ baseUrl: baseUrl2,
4159
+ organizationName,
4160
+ organizationId,
4161
+ tenantName,
4162
+ tenantId,
4163
+ source: "env-vars" /* EnvironmentVariables */,
4164
+ 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}`
4165
+ };
3876
4166
  }
3877
4167
  const iss = payload.iss;
3878
4168
  if (typeof iss !== "string" || iss.length === 0) {
3879
4169
  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.`);
3880
4170
  }
3881
- const [baseUrlError, baseUrl] = catchError(() => normalizeAndValidateBaseUrl(iss));
3882
- if (baseUrlError) {
3883
- if (baseUrlError instanceof InvalidBaseUrlError) {
3884
- throw baseUrlError;
3885
- }
3886
- throw new EnvAuthConfigError(`Failed to derive server URL from token 'iss' claim: ` + `${baseUrlError instanceof Error ? baseUrlError.message : String(baseUrlError)}`);
3887
- }
4171
+ const baseUrl = resolveBaseUrl(iss, "Failed to derive server URL from token 'iss' claim");
3888
4172
  const expiration = getTokenExpiration(accessToken);
3889
4173
  const loginStatus = expiration && expiration <= new Date ? "Expired" : "Logged in";
3890
4174
  const identity = resolveSessionIdentity(accessToken);
@@ -3920,9 +4204,9 @@ function breakerPathFor(authPath) {
3920
4204
  return `${authPath}${BREAKER_SUFFIX}`;
3921
4205
  }
3922
4206
  async function loadRefreshBreaker(authPath) {
3923
- const fs = getFileSystem();
4207
+ const fs2 = getFileSystem();
3924
4208
  try {
3925
- const content = await fs.readFile(breakerPathFor(authPath), "utf-8");
4209
+ const content = await fs2.readFile(breakerPathFor(authPath), "utf-8");
3926
4210
  if (!content)
3927
4211
  return {};
3928
4212
  const parsed = JSON.parse(content);
@@ -3933,20 +4217,20 @@ async function loadRefreshBreaker(authPath) {
3933
4217
  }
3934
4218
  async function saveRefreshBreaker(authPath, state) {
3935
4219
  try {
3936
- const fs = getFileSystem();
3937
- const path = breakerPathFor(authPath);
3938
- await fs.mkdir(fs.path.dirname(path));
3939
- const tempPath = `${path}.tmp`;
3940
- await fs.writeFile(tempPath, JSON.stringify(state));
3941
- await fs.rename(tempPath, path);
4220
+ const fs2 = getFileSystem();
4221
+ const path2 = breakerPathFor(authPath);
4222
+ await fs2.mkdir(fs2.path.dirname(path2));
4223
+ const tempPath = `${path2}.tmp`;
4224
+ await fs2.writeFile(tempPath, JSON.stringify(state));
4225
+ await fs2.rename(tempPath, path2);
3942
4226
  } catch {}
3943
4227
  }
3944
4228
  async function clearRefreshBreaker(authPath) {
3945
- const fs = getFileSystem();
3946
- const path = breakerPathFor(authPath);
4229
+ const fs2 = getFileSystem();
4230
+ const path2 = breakerPathFor(authPath);
3947
4231
  try {
3948
- if (await fs.exists(path)) {
3949
- await fs.rm(path);
4232
+ if (await fs2.exists(path2)) {
4233
+ await fs2.rm(path2);
3950
4234
  }
3951
4235
  } catch {}
3952
4236
  }
@@ -3967,13 +4251,13 @@ var ROBOT_USER_SERVICES_PIPE = "UiPathUserServices";
3967
4251
  var ROBOT_USER_SERVICES_ALTERNATE_PIPE = `${ROBOT_USER_SERVICES_PIPE}Alternate`;
3968
4252
  var PIPE_NAME_MAX_LENGTH = 103;
3969
4253
  var getRobotIpcPipeNames = async () => {
3970
- const fs = getFileSystem();
3971
- const username = fs.env.getenv("USER") ?? fs.env.getenv("USERNAME");
4254
+ const fs2 = getFileSystem();
4255
+ const username = fs2.env.getenv("USER") ?? fs2.env.getenv("USERNAME");
3972
4256
  if (!username) {
3973
4257
  throw new Error("Unable to determine current username");
3974
4258
  }
3975
- const tempPath = fs.env.getenv("TMPDIR") ?? "/tmp/";
3976
- return [ROBOT_USER_SERVICES_PIPE, ROBOT_USER_SERVICES_ALTERNATE_PIPE].map((baseName) => fs.path.join(tempPath, `${baseName}_${username}`).substring(0, PIPE_NAME_MAX_LENGTH));
4259
+ const tempPath = fs2.env.getenv("TMPDIR") ?? "/tmp/";
4260
+ return [ROBOT_USER_SERVICES_PIPE, ROBOT_USER_SERVICES_ALTERNATE_PIPE].map((baseName) => fs2.path.join(tempPath, `${baseName}_${username}`).substring(0, PIPE_NAME_MAX_LENGTH));
3977
4261
  };
3978
4262
  var defaultIsRobotIpcAvailable = async () => {
3979
4263
  if (process.platform === "win32") {
@@ -3983,20 +4267,20 @@ var defaultIsRobotIpcAvailable = async () => {
3983
4267
  if (pipeNamesError || !pipeNames) {
3984
4268
  return false;
3985
4269
  }
3986
- const fs = getFileSystem();
4270
+ const fs2 = getFileSystem();
3987
4271
  for (const pipeName of pipeNames) {
3988
- const [existsError, exists] = await catchError(fs.exists(pipeName));
4272
+ const [existsError, exists] = await catchError(fs2.exists(pipeName));
3989
4273
  if (!existsError && exists === true) {
3990
4274
  return true;
3991
4275
  }
3992
4276
  }
3993
4277
  return false;
3994
4278
  };
3995
- var withTimeout = (promise, timeoutMs) => new Promise((resolve, reject) => {
4279
+ var withTimeout = (promise, timeoutMs) => new Promise((resolve2, reject) => {
3996
4280
  const timer = setTimeout(() => reject(new Error(`Robot IPC call timed out after ${timeoutMs}ms`)), timeoutMs);
3997
4281
  promise.then((value) => {
3998
4282
  clearTimeout(timer);
3999
- resolve(value);
4283
+ resolve2(value);
4000
4284
  }, (error) => {
4001
4285
  clearTimeout(timer);
4002
4286
  reject(error);
@@ -4169,9 +4453,9 @@ var errorCode = (err) => {
4169
4453
  }
4170
4454
  return "EUNKNOWN";
4171
4455
  };
4172
- var probeAsync = async (fs, candidate) => {
4456
+ var probeAsync = async (fs2, candidate) => {
4173
4457
  try {
4174
- const stats = await fs.stat(candidate);
4458
+ const stats = await fs2.stat(candidate);
4175
4459
  if (stats === null) {
4176
4460
  return { exists: false };
4177
4461
  }
@@ -4198,9 +4482,9 @@ var probeAsync = async (fs, candidate) => {
4198
4482
  }
4199
4483
  };
4200
4484
  var resolveEnvFileLocationAsync = async (envFilePath = DEFAULT_ENV_FILENAME, opts) => {
4201
- const fs = getFileSystem();
4202
- if (fs.path.isAbsolute(envFilePath)) {
4203
- const probe2 = await probeAsync(fs, envFilePath);
4485
+ const fs2 = getFileSystem();
4486
+ if (fs2.path.isAbsolute(envFilePath)) {
4487
+ const probe2 = await probeAsync(fs2, envFilePath);
4204
4488
  return probe2.exists ? { exists: true, absolutePath: envFilePath, source: "absolute" } : {
4205
4489
  exists: false,
4206
4490
  absolutePath: envFilePath,
@@ -4208,11 +4492,11 @@ var resolveEnvFileLocationAsync = async (envFilePath = DEFAULT_ENV_FILENAME, opt
4208
4492
  ...probe2.unusable ? { unusable: probe2.unusable } : {}
4209
4493
  };
4210
4494
  }
4211
- const cwd = opts?.cwd ?? fs.env.cwd();
4495
+ const cwd = opts?.cwd ?? fs2.env.cwd();
4212
4496
  let searchDir = cwd;
4213
4497
  while (true) {
4214
- const candidate = fs.path.join(searchDir, envFilePath);
4215
- const probe2 = await probeAsync(fs, candidate);
4498
+ const candidate = fs2.path.join(searchDir, envFilePath);
4499
+ const probe2 = await probeAsync(fs2, candidate);
4216
4500
  if (probe2.exists) {
4217
4501
  return {
4218
4502
  exists: true,
@@ -4220,14 +4504,14 @@ var resolveEnvFileLocationAsync = async (envFilePath = DEFAULT_ENV_FILENAME, opt
4220
4504
  source: searchDir === cwd ? "cwd" : "ancestor"
4221
4505
  };
4222
4506
  }
4223
- const parentDir = fs.path.dirname(searchDir);
4507
+ const parentDir = fs2.path.dirname(searchDir);
4224
4508
  if (parentDir === searchDir) {
4225
4509
  break;
4226
4510
  }
4227
4511
  searchDir = parentDir;
4228
4512
  }
4229
- const homePath = fs.path.join(fs.env.homedir(), envFilePath);
4230
- const probe = await probeAsync(fs, homePath);
4513
+ const homePath = fs2.path.join(fs2.env.homedir(), envFilePath);
4514
+ const probe = await probeAsync(fs2, homePath);
4231
4515
  if (probe.exists) {
4232
4516
  return { exists: true, absolutePath: homePath, source: "home" };
4233
4517
  }
@@ -4249,12 +4533,12 @@ var resolveEnvFilePathAsync = async (envFilePath = DEFAULT_ENV_FILENAME, opts) =
4249
4533
  };
4250
4534
  };
4251
4535
  var loadEnvFileAsync = async ({ envPath }) => {
4252
- const fs = getFileSystem();
4253
- const absolutePath = fs.path.isAbsolute(envPath) ? envPath : fs.path.join(fs.env.cwd(), envPath);
4254
- if (!await fs.exists(absolutePath)) {
4536
+ const fs2 = getFileSystem();
4537
+ const absolutePath = fs2.path.isAbsolute(envPath) ? envPath : fs2.path.join(fs2.env.cwd(), envPath);
4538
+ if (!await fs2.exists(absolutePath)) {
4255
4539
  throw new Error(`Environment file not found: ${envPath}`);
4256
4540
  }
4257
- const content = await fs.readFile(absolutePath, "utf-8");
4541
+ const content = await fs2.readFile(absolutePath, "utf-8");
4258
4542
  if (content === null) {
4259
4543
  throw new Error(`Environment file not found: ${envPath}`);
4260
4544
  }
@@ -4283,10 +4567,10 @@ var saveEnvFileAsync = async ({
4283
4567
  data,
4284
4568
  merge = true
4285
4569
  }) => {
4286
- const fs = getFileSystem();
4287
- const absolutePath = fs.path.isAbsolute(envPath) ? envPath : fs.path.join(fs.env.homedir(), envPath);
4570
+ const fs2 = getFileSystem();
4571
+ const absolutePath = fs2.path.isAbsolute(envPath) ? envPath : fs2.path.join(fs2.env.homedir(), envPath);
4288
4572
  let existingData = {};
4289
- if (merge && await fs.exists(absolutePath)) {
4573
+ if (merge && await fs2.exists(absolutePath)) {
4290
4574
  try {
4291
4575
  existingData = await loadEnvFileAsync({ envPath: absolutePath });
4292
4576
  } catch {}
@@ -4304,11 +4588,11 @@ var saveEnvFileAsync = async ({
4304
4588
  const content = `${lines.join(`
4305
4589
  `)}
4306
4590
  `;
4307
- const dir = fs.path.dirname(absolutePath);
4308
- await fs.mkdir(dir);
4591
+ const dir = fs2.path.dirname(absolutePath);
4592
+ await fs2.mkdir(dir);
4309
4593
  const tempPath = `${absolutePath}.tmp`;
4310
- await fs.writeFile(tempPath, content);
4311
- await fs.rename(tempPath, absolutePath);
4594
+ await fs2.writeFile(tempPath, content);
4595
+ await fs2.rename(tempPath, absolutePath);
4312
4596
  };
4313
4597
 
4314
4598
  // ../../auth/src/loginStatus.ts
@@ -4422,11 +4706,11 @@ async function loadFileCredentials(loadEnvFile, absolutePath) {
4422
4706
  return { credentials };
4423
4707
  }
4424
4708
  async function getGlobalCredsHint(getFs, loadEnvFile, absolutePath, envFilePath) {
4425
- const fs = getFs();
4426
- const globalPath = fs.path.join(fs.env.homedir(), envFilePath);
4709
+ const fs2 = getFs();
4710
+ const globalPath = fs2.path.join(fs2.env.homedir(), envFilePath);
4427
4711
  if (absolutePath === globalPath)
4428
4712
  return;
4429
- if (!await fs.exists(globalPath))
4713
+ if (!await fs2.exists(globalPath))
4430
4714
  return;
4431
4715
  try {
4432
4716
  const globalCreds = await loadEnvFile({ envPath: globalPath });
@@ -4839,155 +5123,631 @@ async function createApiClient(ApiClass, options) {
4839
5123
  organizationId
4840
5124
  };
4841
5125
  }
4842
- // ../../common/src/catch-error.ts
4843
- function isPromiseLike(value) {
4844
- return value !== null && typeof value === "object" && typeof value.then === "function";
4845
- }
4846
- function catchError2(fnOrPromise) {
4847
- if (isPromiseLike(fnOrPromise)) {
4848
- return settlePromiseLike(fnOrPromise);
5126
+ // ../../common/src/telemetry/pseudonymize.ts
5127
+ var PSEUDONYM_DOMAIN = "uipath-cli/telemetry/pseudonym/v1:";
5128
+ var PSEUDONYM_HEX_LENGTH = 32;
5129
+ var SHA256_K = new Uint32Array([
5130
+ 1116352408,
5131
+ 1899447441,
5132
+ 3049323471,
5133
+ 3921009573,
5134
+ 961987163,
5135
+ 1508970993,
5136
+ 2453635748,
5137
+ 2870763221,
5138
+ 3624381080,
5139
+ 310598401,
5140
+ 607225278,
5141
+ 1426881987,
5142
+ 1925078388,
5143
+ 2162078206,
5144
+ 2614888103,
5145
+ 3248222580,
5146
+ 3835390401,
5147
+ 4022224774,
5148
+ 264347078,
5149
+ 604807628,
5150
+ 770255983,
5151
+ 1249150122,
5152
+ 1555081692,
5153
+ 1996064986,
5154
+ 2554220882,
5155
+ 2821834349,
5156
+ 2952996808,
5157
+ 3210313671,
5158
+ 3336571891,
5159
+ 3584528711,
5160
+ 113926993,
5161
+ 338241895,
5162
+ 666307205,
5163
+ 773529912,
5164
+ 1294757372,
5165
+ 1396182291,
5166
+ 1695183700,
5167
+ 1986661051,
5168
+ 2177026350,
5169
+ 2456956037,
5170
+ 2730485921,
5171
+ 2820302411,
5172
+ 3259730800,
5173
+ 3345764771,
5174
+ 3516065817,
5175
+ 3600352804,
5176
+ 4094571909,
5177
+ 275423344,
5178
+ 430227734,
5179
+ 506948616,
5180
+ 659060556,
5181
+ 883997877,
5182
+ 958139571,
5183
+ 1322822218,
5184
+ 1537002063,
5185
+ 1747873779,
5186
+ 1955562222,
5187
+ 2024104815,
5188
+ 2227730452,
5189
+ 2361852424,
5190
+ 2428436474,
5191
+ 2756734187,
5192
+ 3204031479,
5193
+ 3329325298
5194
+ ]);
5195
+ var SHA256_INITIAL_STATE = new Uint32Array([
5196
+ 1779033703,
5197
+ 3144134277,
5198
+ 1013904242,
5199
+ 2773480762,
5200
+ 1359893119,
5201
+ 2600822924,
5202
+ 528734635,
5203
+ 1541459225
5204
+ ]);
5205
+ function rotr(value, bits) {
5206
+ return (value >>> bits | value << 32 - bits) >>> 0;
5207
+ }
5208
+ function sha256Hex(input) {
5209
+ const bytes = new TextEncoder().encode(input);
5210
+ const paddedLength = bytes.length + 9 + 63 >> 6 << 6;
5211
+ const buffer = new Uint8Array(paddedLength);
5212
+ buffer.set(bytes);
5213
+ buffer[bytes.length] = 128;
5214
+ const view = new DataView(buffer.buffer);
5215
+ const bitLength = bytes.length * 8;
5216
+ view.setUint32(paddedLength - 8, Math.floor(bitLength / 4294967296));
5217
+ view.setUint32(paddedLength - 4, bitLength >>> 0);
5218
+ const state = SHA256_INITIAL_STATE.slice();
5219
+ const schedule = new Uint32Array(64);
5220
+ for (let offset = 0;offset < paddedLength; offset += 64) {
5221
+ for (let i = 0;i < 16; i++) {
5222
+ schedule[i] = view.getUint32(offset + i * 4);
5223
+ }
5224
+ for (let i = 16;i < 64; i++) {
5225
+ const x = schedule[i - 15];
5226
+ const y = schedule[i - 2];
5227
+ const s0 = (rotr(x, 7) ^ rotr(x, 18) ^ x >>> 3) >>> 0;
5228
+ const s1 = (rotr(y, 17) ^ rotr(y, 19) ^ y >>> 10) >>> 0;
5229
+ schedule[i] = schedule[i - 16] + s0 + schedule[i - 7] + s1 >>> 0;
5230
+ }
5231
+ let a = state[0];
5232
+ let b = state[1];
5233
+ let c = state[2];
5234
+ let d = state[3];
5235
+ let e = state[4];
5236
+ let f = state[5];
5237
+ let g = state[6];
5238
+ let h = state[7];
5239
+ for (let i = 0;i < 64; i++) {
5240
+ const s1 = (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) >>> 0;
5241
+ const ch = (e & f ^ ~e & g) >>> 0;
5242
+ const temp1 = h + s1 + ch + SHA256_K[i] + schedule[i] >>> 0;
5243
+ const s0 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) >>> 0;
5244
+ const maj = (a & b ^ a & c ^ b & c) >>> 0;
5245
+ const temp2 = s0 + maj >>> 0;
5246
+ h = g;
5247
+ g = f;
5248
+ f = e;
5249
+ e = d + temp1 >>> 0;
5250
+ d = c;
5251
+ c = b;
5252
+ b = a;
5253
+ a = temp1 + temp2 >>> 0;
5254
+ }
5255
+ state[0] = state[0] + a >>> 0;
5256
+ state[1] = state[1] + b >>> 0;
5257
+ state[2] = state[2] + c >>> 0;
5258
+ state[3] = state[3] + d >>> 0;
5259
+ state[4] = state[4] + e >>> 0;
5260
+ state[5] = state[5] + f >>> 0;
5261
+ state[6] = state[6] + g >>> 0;
5262
+ state[7] = state[7] + h >>> 0;
4849
5263
  }
5264
+ let hex = "";
5265
+ for (const word of state) {
5266
+ hex += word.toString(16).padStart(8, "0");
5267
+ }
5268
+ return hex;
5269
+ }
5270
+ function resolveSha256Hex() {
4850
5271
  try {
4851
- const result = fnOrPromise();
4852
- if (isPromiseLike(result)) {
4853
- return settlePromiseLike(result);
5272
+ const nodeCrypto = __require("node:crypto");
5273
+ const createHash = nodeCrypto?.createHash;
5274
+ if (typeof createHash !== "function") {
5275
+ return sha256Hex;
4854
5276
  }
4855
- return [undefined, result];
4856
- } catch (error) {
4857
- return [
4858
- error instanceof Error ? error : new Error(String(error)),
4859
- undefined
4860
- ];
5277
+ const native = (input) => createHash("sha256").update(input, "utf8").digest("hex");
5278
+ return native("abc") === sha256Hex("abc") ? native : sha256Hex;
5279
+ } catch {
5280
+ return sha256Hex;
4861
5281
  }
4862
5282
  }
4863
- function settlePromiseLike(thenable) {
4864
- return Promise.resolve(thenable).then((data) => [undefined, data]).catch((error) => [
4865
- error instanceof Error ? error : new Error(String(error)),
4866
- undefined
4867
- ]);
5283
+ var cachedSha256Hex;
5284
+ function digest(input) {
5285
+ cachedSha256Hex ??= resolveSha256Hex();
5286
+ return cachedSha256Hex(input);
4868
5287
  }
4869
-
4870
- // ../../common/src/error-handler.ts
4871
- var DEFAULT_401 = "Unauthorized (401). Run `uip login` to authenticate.";
4872
- var DEFAULT_403 = "Forbidden (403). Ensure the account has the required permissions.";
4873
- var DEFAULT_405 = "Method Not Allowed (405). The endpoint may not exist or the base URL may be incorrect.";
4874
- var DEFAULT_413 = "Payload too large (413). The upload exceeded the server or CDN size limit. Reduce the package size — for example, exclude unused dependencies or remove large files from the project — and try again.";
4875
- var HTML_RESPONSE_MESSAGE = "Received HTML instead of the expected JSON response.";
4876
- var NETWORK_ERROR_CODES = new Set([
4877
- "ECONNREFUSED",
4878
- "ECONNRESET",
4879
- "ENOTFOUND",
4880
- "EAI_AGAIN",
4881
- "ETIMEDOUT",
4882
- "EPIPE",
4883
- "EHOSTUNREACH",
4884
- "ENETUNREACH",
4885
- "EAI_FAIL"
4886
- ]);
4887
- var TLS_ERROR_CODES = new Set([
4888
- "SELF_SIGNED_CERT_IN_CHAIN",
4889
- "DEPTH_ZERO_SELF_SIGNED_CERT",
4890
- "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
4891
- "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
4892
- "UNABLE_TO_GET_ISSUER_CERT",
4893
- "CERT_HAS_EXPIRED",
4894
- "CERT_UNTRUSTED",
4895
- "ERR_TLS_CERT_ALTNAME_INVALID"
4896
- ]);
4897
- 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.";
4898
- 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.";
4899
- var LOCAL_PERMISSION_ERROR_CODES = new Set(["EACCES", "EPERM", "EROFS"]);
4900
- var LOCAL_PERMISSION_MESSAGE_PATTERN = /\b(EACCES|EPERM|EROFS)\b/;
4901
- function localPermissionInstructions(code, path) {
4902
- const target = path !== undefined ? `'${path}'` : "a local file or resource";
4903
- if (code === "EROFS") {
4904
- return `The filesystem containing ${target} is read-only (EROFS), so the ` + "CLI could not write to it. This is a local environment problem, " + "not a UiPath service error — retrying will not help. Use a " + "writable location, or give this environment write access to the " + "path.";
4905
- }
4906
- const remedy = process.platform === "win32" ? "Re-run from an elevated terminal, close any program holding " + "the file open, or grant your user access to the path." : "Grant this user (or the sandbox the command runs in) access " + "to the path, or run the command outside the sandbox.";
4907
- return `The operating system denied access to ${target} (${code}). This is ` + "a local permission problem, not a UiPath service error — retrying " + `without a permission change will not help. ${remedy}`;
5288
+ function pseudonymize(input) {
5289
+ return digest(`${PSEUDONYM_DOMAIN}${input}`).slice(0, PSEUDONYM_HEX_LENGTH);
4908
5290
  }
4909
- function describeConnectivityError(error) {
4910
- for (const cur of walkErrorGraph(error)) {
4911
- const code = typeof cur.code === "string" ? cur.code : undefined;
4912
- const message = typeof cur.message === "string" ? cur.message : undefined;
4913
- if (code && TLS_ERROR_CODES.has(code)) {
4914
- return {
4915
- code,
4916
- kind: "tls",
4917
- message: message ?? code,
4918
- instructions: TLS_INSTRUCTIONS
4919
- };
5291
+
5292
+ // ../../common/src/telemetry/supplied-values.ts
5293
+ var suppliedValuesSlot = singleton("TelemetrySuppliedArgumentValues");
5294
+ function activeEntries() {
5295
+ const existing = suppliedValuesSlot.get();
5296
+ return Array.isArray(existing) ? existing : [];
5297
+ }
5298
+ var MIN_SCRUBBABLE_LENGTH = 4;
5299
+ function recordSuppliedArgumentValues(values) {
5300
+ const flat = [];
5301
+ const push = (value) => {
5302
+ if (Array.isArray(value)) {
5303
+ for (const item of value) {
5304
+ push(item);
5305
+ }
5306
+ return;
4920
5307
  }
4921
- if (code && NETWORK_ERROR_CODES.has(code)) {
4922
- return {
4923
- code,
4924
- kind: "network",
4925
- message: message ?? code,
4926
- instructions: NETWORK_INSTRUCTIONS
4927
- };
5308
+ if (typeof value === "string" && value.length >= MIN_SCRUBBABLE_LENGTH) {
5309
+ flat.push(value);
4928
5310
  }
4929
- }
4930
- return;
4931
- }
4932
- function describePermissionError(error) {
4933
- for (const cur of walkErrorGraph(error)) {
4934
- const message = typeof cur.message === "string" ? cur.message : undefined;
4935
- const code = matchLocalPermissionCode(cur.code, message);
4936
- if (!code)
4937
- continue;
4938
- const path = localPermissionPath(cur.path, message);
4939
- return {
4940
- code,
4941
- message: message ?? code,
4942
- ...path !== undefined ? { path } : {},
4943
- instructions: localPermissionInstructions(code, path)
4944
- };
4945
- }
4946
- return;
4947
- }
4948
- function matchLocalPermissionCode(code, message) {
4949
- if (typeof code === "string" && LOCAL_PERMISSION_ERROR_CODES.has(code)) {
4950
- return code;
4951
- }
4952
- const match = message ? LOCAL_PERMISSION_MESSAGE_PATTERN.exec(message) : null;
4953
- return match ? match[1] : undefined;
5311
+ };
5312
+ push(values);
5313
+ const entry = { values: flat };
5314
+ suppliedValuesSlot.set([...activeEntries(), entry]);
5315
+ return entry;
4954
5316
  }
4955
- function localPermissionPath(path, message) {
4956
- if (typeof path === "string")
4957
- return path;
4958
- return message ? /'([^']+)'/.exec(message)?.[1] : undefined;
5317
+ function releaseSuppliedArgumentValues(entry) {
5318
+ suppliedValuesSlot.set(activeEntries().filter((held) => held !== entry));
4959
5319
  }
4960
- function* walkErrorGraph(error) {
4961
- const queue = [error];
4962
- const seen = new Set;
4963
- for (let steps = 0;queue.length > 0 && steps < 32; steps++) {
4964
- const current = queue.shift();
4965
- if (current === null || typeof current !== "object")
4966
- continue;
4967
- if (seen.has(current))
4968
- continue;
4969
- seen.add(current);
4970
- const cur = current;
4971
- yield cur;
4972
- if (cur.cause !== undefined)
4973
- queue.push(cur.cause);
4974
- if (Array.isArray(cur.errors))
4975
- queue.push(...cur.errors);
5320
+ function getSuppliedArgumentValues() {
5321
+ const all = new Set;
5322
+ for (const entry of activeEntries()) {
5323
+ for (const value of entry.values) {
5324
+ all.add(value);
5325
+ }
4976
5326
  }
4977
- return;
4978
- }
4979
- function parseHttpStatusFromMessage(message) {
4980
- const match = /^HTTP\s+(\d{3})(?::|\s|-|$)/i.exec(message.trim());
4981
- if (!match)
4982
- return;
4983
- const status = Number(match[1]);
4984
- return Number.isInteger(status) && status >= 100 && status <= 599 ? status : undefined;
5327
+ return [...all].sort((a, b) => b.length - a.length);
4985
5328
  }
4986
- function isHtmlDocument(body) {
4987
- return /^\s*(<!doctype html|<html\b)/i.test(body);
5329
+
5330
+ // ../../common/src/telemetry/pii-redactor.ts
5331
+ var REDACTED = "[REDACTED]";
5332
+ var MAX_VALUE_LENGTH = 280;
5333
+ var MAX_STACK_LENGTH = 4096;
5334
+ var MAX_SCAN_LENGTH = MAX_STACK_LENGTH;
5335
+ function truncate(value, maxLength) {
5336
+ return value.length > maxLength ? `${value.slice(0, maxLength)}…` : value;
4988
5337
  }
4989
- function retryHintForRetryAfter(seconds) {
4990
- if (seconds <= 1) {
5338
+ var SENSITIVE_NAME_TOKENS = new Set([
5339
+ "token",
5340
+ "tokens",
5341
+ "secret",
5342
+ "secrets",
5343
+ "password",
5344
+ "passwords",
5345
+ "pwd",
5346
+ "credential",
5347
+ "credentials",
5348
+ "auth",
5349
+ "authentication",
5350
+ "authorization",
5351
+ "authority",
5352
+ "cert",
5353
+ "certificate",
5354
+ "certificates"
5355
+ ]);
5356
+ var SENSITIVE_KEY_PREFIXES = new Set([
5357
+ "api",
5358
+ "access",
5359
+ "client",
5360
+ "private",
5361
+ "public",
5362
+ "signing",
5363
+ "encryption",
5364
+ "session",
5365
+ "master",
5366
+ "shared",
5367
+ "root",
5368
+ "ssh",
5369
+ "rsa",
5370
+ "aes",
5371
+ "hmac",
5372
+ "oauth"
5373
+ ]);
5374
+ 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;
5375
+ var EMAIL_PATTERN = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g;
5376
+ var JWT_PATTERN = /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g;
5377
+ var LONG_TOKEN_PATTERN = /\b[A-Za-z0-9_-]{40,}\b/g;
5378
+ var PADDED_BASE64_PATTERN = /[A-Za-z0-9+/]{16,}={1,2}(?![A-Za-z0-9+/=])/g;
5379
+ var BASE64_WITH_PLUS_PATTERN = /[A-Za-z0-9+/]{40,}/g;
5380
+ var USER_HOME_PATTERN = /(?<![A-Za-z0-9._-])([/\\])(Users|home|Profiles)([/\\])([^/\\]+)/gi;
5381
+ var UNC_PATH_PATTERN = /(^|[\s"'<>|=,;([{])(\\\\[^\s"'<>|]+)/g;
5382
+ 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;
5383
+ var SOURCE_FILE_EXTENSIONS = new Set([
5384
+ "ts",
5385
+ "tsx",
5386
+ "js",
5387
+ "jsx",
5388
+ "mjs",
5389
+ "cjs",
5390
+ "cts",
5391
+ "mts",
5392
+ "py",
5393
+ "cs",
5394
+ "java",
5395
+ "go",
5396
+ "rs",
5397
+ "rb",
5398
+ "php",
5399
+ "sh",
5400
+ "ps1",
5401
+ "json",
5402
+ "jsonc",
5403
+ "yaml",
5404
+ "yml",
5405
+ "xml",
5406
+ "xaml",
5407
+ "md",
5408
+ "txt",
5409
+ "log",
5410
+ "css",
5411
+ "html",
5412
+ "htm",
5413
+ "csproj",
5414
+ "nuspec",
5415
+ "sql"
5416
+ ]);
5417
+ var URL_PATTERN = /\bhttps?:\/\/[^\s,;]+/gi;
5418
+ var QUOTED_LITERAL_MAX_SPAN = 200;
5419
+ var QUOTED_LITERAL_PATTERN = new RegExp([
5420
+ `(?<![A-Za-z0-9])'(?:[^\\
5421
+ ]|\\.){2,${QUOTED_LITERAL_MAX_SPAN}}?'(?![A-Za-z0-9])`,
5422
+ `(?<![A-Za-z0-9])"(?:[^\\
5423
+ ]|\\.){2,${QUOTED_LITERAL_MAX_SPAN}}?"(?![A-Za-z0-9])`
5424
+ ].join("|"), "g");
5425
+ var JSON_BODY_PATTERN = /[{[][^{}[\]]*[:,][^{}[\]]*[\]}]/g;
5426
+ var COLLAPSED_BODY = "{…}";
5427
+ var COLLAPSED_BODY_MARKER = "\x01body\x01";
5428
+ var MAX_BODY_NESTING = 8;
5429
+ function collapseJsonBodies(text) {
5430
+ let out = text;
5431
+ for (let pass = 0;pass < MAX_BODY_NESTING; pass++) {
5432
+ const next = out.replace(JSON_BODY_PATTERN, COLLAPSED_BODY_MARKER);
5433
+ if (next === out) {
5434
+ break;
5435
+ }
5436
+ out = next;
5437
+ }
5438
+ return out.split(COLLAPSED_BODY_MARKER).join(COLLAPSED_BODY);
5439
+ }
5440
+ var TRAILING_PROSE_PUNCT = /[.,;:!?)\]}>'"]+$/;
5441
+ function peelTrailingPunctuation(match) {
5442
+ const trailing = match.match(TRAILING_PROSE_PUNCT)?.[0] ?? "";
5443
+ return trailing ? [match.slice(0, -trailing.length), trailing] : [match, ""];
5444
+ }
5445
+ function redactUrl(raw) {
5446
+ try {
5447
+ const url = new URL(raw);
5448
+ return `${url.protocol}//${url.host}`;
5449
+ } catch {
5450
+ return `url#${pseudonymize(raw)}`;
5451
+ }
5452
+ }
5453
+ function redactValueDetectors(value, maxLength = MAX_VALUE_LENGTH) {
5454
+ let out = truncate(value, MAX_SCAN_LENGTH);
5455
+ out = out.replace(JWT_PATTERN, () => REDACTED);
5456
+ out = out.replace(URL_PATTERN, (match) => {
5457
+ const [core, trailing] = peelTrailingPunctuation(match);
5458
+ return `${redactUrl(core)}${trailing}`;
5459
+ });
5460
+ out = out.replace(USER_HOME_PATTERN, (_match, sep1, folder, sep2) => `${sep1}${folder}${sep2}<user>`);
5461
+ out = out.replace(UNC_PATH_PATTERN, (_match, before, path2) => {
5462
+ const [core, trailing] = peelTrailingPunctuation(path2);
5463
+ return `${before}unc#${pseudonymize(core)}${trailing}`;
5464
+ });
5465
+ out = out.replace(EMAIL_PATTERN, (match) => `email#${pseudonymize(match)}`);
5466
+ out = out.replace(UUID_PATTERN, (match) => `uuid#${pseudonymize(match)}`);
5467
+ out = out.replace(HOST_PORT_PATTERN, (match) => {
5468
+ const split = match.lastIndexOf(":");
5469
+ const host = match.slice(0, split);
5470
+ const extension = host.slice(host.lastIndexOf(".") + 1).toLowerCase();
5471
+ if (SOURCE_FILE_EXTENSIONS.has(extension)) {
5472
+ return match;
5473
+ }
5474
+ return `host#${pseudonymize(host)}:${match.slice(split + 1)}`;
5475
+ });
5476
+ out = out.replace(PADDED_BASE64_PATTERN, () => REDACTED);
5477
+ out = out.replace(BASE64_WITH_PLUS_PATTERN, (match) => match.includes("+") ? REDACTED : match);
5478
+ out = out.replace(LONG_TOKEN_PATTERN, () => REDACTED);
5479
+ return truncate(out, maxLength);
5480
+ }
5481
+ function redactSpanName(name) {
5482
+ return redactValueDetectors(truncate(name, MAX_SCAN_LENGTH).replace(QUOTED_LITERAL_PATTERN, (match) => `${match[0]}<redacted>${match[0]}`));
5483
+ }
5484
+ var HTTP_DEPENDENCY_NAME = /^([A-Z]+) (\/.*)$/s;
5485
+ function redactHttpDependencyName(name) {
5486
+ const parts = HTTP_DEPENDENCY_NAME.exec(name);
5487
+ if (!parts) {
5488
+ return redactMessage(name);
5489
+ }
5490
+ return `${parts[1]} ${redactMessage(parts[2])}`;
5491
+ }
5492
+ function redactMessage(value) {
5493
+ let out = collapseJsonBodies(truncate(value, MAX_SCAN_LENGTH)).replace(QUOTED_LITERAL_PATTERN, (match) => `${match[0]}<redacted>${match[0]}`);
5494
+ for (const supplied of getSuppliedArgumentValues()) {
5495
+ out = out.split(supplied).join(REDACTED);
5496
+ }
5497
+ return redactValueDetectors(out);
5498
+ }
5499
+ var MESSAGE_NAMES = new Set([
5500
+ "message",
5501
+ "errormessage",
5502
+ "errmessage",
5503
+ "error_message",
5504
+ "msg",
5505
+ "detail",
5506
+ "details",
5507
+ "reason",
5508
+ "instructions",
5509
+ "warning"
5510
+ ]);
5511
+ function isFreeFormValue(name, value) {
5512
+ return MESSAGE_NAMES.has(name.toLowerCase()) || /['"{[]/.test(value);
5513
+ }
5514
+ function redactError(error) {
5515
+ const safe = new Error(redactMessage(error.message ?? ""));
5516
+ safe.name = error.name;
5517
+ safe.stack = typeof error.stack === "string" ? redactStack(error.stack) : undefined;
5518
+ return safe;
5519
+ }
5520
+ function redactStack(stack) {
5521
+ const bounded = truncate(stack, MAX_STACK_LENGTH);
5522
+ const firstBreak = bounded.indexOf(`
5523
+ `);
5524
+ if (firstBreak === -1) {
5525
+ return redactMessage(bounded);
5526
+ }
5527
+ return `${redactMessage(bounded.slice(0, firstBreak))}
5528
+ ${redactValueDetectors(bounded.slice(firstBreak + 1), MAX_STACK_LENGTH)}`;
5529
+ }
5530
+ function nameTokens(name) {
5531
+ 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);
5532
+ }
5533
+ function isSensitiveName(name) {
5534
+ const tokens = nameTokens(name);
5535
+ for (let i = 0;i < tokens.length; i++) {
5536
+ const token = tokens[i];
5537
+ if (SENSITIVE_NAME_TOKENS.has(token)) {
5538
+ return true;
5539
+ }
5540
+ if (token === "key" || token === "keys") {
5541
+ const prev = tokens[i - 1];
5542
+ if (prev && SENSITIVE_KEY_PREFIXES.has(prev)) {
5543
+ return true;
5544
+ }
5545
+ }
5546
+ }
5547
+ return false;
5548
+ }
5549
+ function redactProperty(name, value) {
5550
+ if (value === undefined || value === null) {
5551
+ return;
5552
+ }
5553
+ if (isSensitiveName(name)) {
5554
+ return REDACTED;
5555
+ }
5556
+ if (typeof value === "boolean" || typeof value === "number") {
5557
+ return value;
5558
+ }
5559
+ if (typeof value !== "string") {
5560
+ return "[OBJECT]";
5561
+ }
5562
+ return isFreeFormValue(name, value) ? redactMessage(value) : redactValueDetectors(value);
5563
+ }
5564
+ function redactProperties(properties) {
5565
+ const out = {};
5566
+ for (const [name, value] of Object.entries(properties)) {
5567
+ const redacted = redactProperty(name, value);
5568
+ if (redacted !== undefined) {
5569
+ out[name] = redacted;
5570
+ }
5571
+ }
5572
+ return out;
5573
+ }
5574
+
5575
+ // ../../common/src/catch-error.ts
5576
+ var MAX_SERIALIZED_LENGTH = 500;
5577
+ var TRUNCATION_SUFFIX = "…(truncated)";
5578
+ var REDACTED2 = "[REDACTED]";
5579
+ function cap(text) {
5580
+ return text.length > MAX_SERIALIZED_LENGTH ? `${text.slice(0, MAX_SERIALIZED_LENGTH)}${TRUNCATION_SUFFIX}` : text;
5581
+ }
5582
+ function omitSensitive(key, value) {
5583
+ return key.length > 0 && isSensitiveName(key) ? REDACTED2 : value;
5584
+ }
5585
+ function describeThrownValue(value) {
5586
+ if (typeof value !== "object" || value === null) {
5587
+ return String(value);
5588
+ }
5589
+ let message;
5590
+ try {
5591
+ message = value.message;
5592
+ } catch {
5593
+ message = undefined;
5594
+ }
5595
+ if (typeof message === "string" && message.length > 0) {
5596
+ return cap(message);
5597
+ }
5598
+ try {
5599
+ const json = JSON.stringify(value, omitSensitive);
5600
+ if (json !== undefined) {
5601
+ return cap(json);
5602
+ }
5603
+ } catch {}
5604
+ return String(value);
5605
+ }
5606
+ function toError(error) {
5607
+ return error instanceof Error ? error : new Error(describeThrownValue(error), { cause: error });
5608
+ }
5609
+ function isPromiseLike2(value) {
5610
+ return value !== null && typeof value === "object" && typeof value.then === "function";
5611
+ }
5612
+ function catchError2(fnOrPromise) {
5613
+ if (isPromiseLike2(fnOrPromise)) {
5614
+ return settlePromiseLike2(fnOrPromise);
5615
+ }
5616
+ try {
5617
+ const result = fnOrPromise();
5618
+ if (isPromiseLike2(result)) {
5619
+ return settlePromiseLike2(result);
5620
+ }
5621
+ return [undefined, result];
5622
+ } catch (error) {
5623
+ return [toError(error), undefined];
5624
+ }
5625
+ }
5626
+ function settlePromiseLike2(thenable) {
5627
+ return Promise.resolve(thenable).then((data) => [undefined, data]).catch((error) => [toError(error), undefined]);
5628
+ }
5629
+
5630
+ // ../../common/src/error-handler.ts
5631
+ var DEFAULT_401 = "Unauthorized (401). Run `uip login` to authenticate.";
5632
+ var DEFAULT_403 = "Forbidden (403). Ensure the account has the required permissions.";
5633
+ var DEFAULT_405 = "Method Not Allowed (405). The endpoint may not exist or the base URL may be incorrect.";
5634
+ var DEFAULT_413 = "Payload too large (413). The upload exceeded the server or CDN size limit. Reduce the package size — for example, exclude unused dependencies or remove large files from the project — and try again.";
5635
+ var HTML_RESPONSE_MESSAGE = "Received HTML instead of the expected JSON response.";
5636
+ var NETWORK_ERROR_CODES = new Set([
5637
+ "ECONNREFUSED",
5638
+ "ECONNRESET",
5639
+ "ENOTFOUND",
5640
+ "EAI_AGAIN",
5641
+ "ETIMEDOUT",
5642
+ "EPIPE",
5643
+ "EHOSTUNREACH",
5644
+ "ENETUNREACH",
5645
+ "EAI_FAIL"
5646
+ ]);
5647
+ var TLS_ERROR_CODES = new Set([
5648
+ "SELF_SIGNED_CERT_IN_CHAIN",
5649
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
5650
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
5651
+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
5652
+ "UNABLE_TO_GET_ISSUER_CERT",
5653
+ "CERT_HAS_EXPIRED",
5654
+ "CERT_UNTRUSTED",
5655
+ "ERR_TLS_CERT_ALTNAME_INVALID"
5656
+ ]);
5657
+ 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.";
5658
+ 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.";
5659
+ var LOCAL_PERMISSION_ERROR_CODES = new Set(["EACCES", "EPERM", "EROFS"]);
5660
+ var LOCAL_PERMISSION_MESSAGE_PATTERN = /\b(EACCES|EPERM|EROFS)\b/;
5661
+ function localPermissionInstructions(code, path2) {
5662
+ const target = path2 !== undefined ? `'${path2}'` : "a local file or resource";
5663
+ if (code === "EROFS") {
5664
+ return `The filesystem containing ${target} is read-only (EROFS), so the ` + "CLI could not write to it. This is a local environment problem, " + "not a UiPath service error — retrying will not help. Use a " + "writable location, or give this environment write access to the " + "path.";
5665
+ }
5666
+ const remedy = process.platform === "win32" ? "Re-run from an elevated terminal, close any program holding " + "the file open, or grant your user access to the path." : "Grant this user (or the sandbox the command runs in) access " + "to the path, or run the command outside the sandbox.";
5667
+ return `The operating system denied access to ${target} (${code}). This is ` + "a local permission problem, not a UiPath service error — retrying " + `without a permission change will not help. ${remedy}`;
5668
+ }
5669
+ function describeConnectivityError(error) {
5670
+ for (const cur of walkErrorGraph(error)) {
5671
+ const code = typeof cur.code === "string" ? cur.code : undefined;
5672
+ const message = typeof cur.message === "string" ? cur.message : undefined;
5673
+ if (code && TLS_ERROR_CODES.has(code)) {
5674
+ return {
5675
+ code,
5676
+ kind: "tls",
5677
+ message: message ?? code,
5678
+ instructions: TLS_INSTRUCTIONS
5679
+ };
5680
+ }
5681
+ if (code && NETWORK_ERROR_CODES.has(code)) {
5682
+ return {
5683
+ code,
5684
+ kind: "network",
5685
+ message: message ?? code,
5686
+ instructions: NETWORK_INSTRUCTIONS
5687
+ };
5688
+ }
5689
+ }
5690
+ return;
5691
+ }
5692
+ function describePermissionError(error) {
5693
+ for (const cur of walkErrorGraph(error)) {
5694
+ const message = typeof cur.message === "string" ? cur.message : undefined;
5695
+ const code = matchLocalPermissionCode(cur.code, message);
5696
+ if (!code)
5697
+ continue;
5698
+ const path2 = localPermissionPath(cur.path, message);
5699
+ return {
5700
+ code,
5701
+ message: message ?? code,
5702
+ ...path2 !== undefined ? { path: path2 } : {},
5703
+ instructions: localPermissionInstructions(code, path2)
5704
+ };
5705
+ }
5706
+ return;
5707
+ }
5708
+ function matchLocalPermissionCode(code, message) {
5709
+ if (typeof code === "string" && LOCAL_PERMISSION_ERROR_CODES.has(code)) {
5710
+ return code;
5711
+ }
5712
+ const match = message ? LOCAL_PERMISSION_MESSAGE_PATTERN.exec(message) : null;
5713
+ return match ? match[1] : undefined;
5714
+ }
5715
+ function localPermissionPath(path2, message) {
5716
+ if (typeof path2 === "string")
5717
+ return path2;
5718
+ return message ? /'([^']+)'/.exec(message)?.[1] : undefined;
5719
+ }
5720
+ function* walkErrorGraph(error) {
5721
+ const queue = [error];
5722
+ const seen = new Set;
5723
+ for (let steps = 0;queue.length > 0 && steps < 32; steps++) {
5724
+ const current = queue.shift();
5725
+ if (current === null || typeof current !== "object")
5726
+ continue;
5727
+ if (seen.has(current))
5728
+ continue;
5729
+ seen.add(current);
5730
+ const cur = current;
5731
+ yield cur;
5732
+ if (cur.cause !== undefined)
5733
+ queue.push(cur.cause);
5734
+ if (Array.isArray(cur.errors))
5735
+ queue.push(...cur.errors);
5736
+ }
5737
+ return;
5738
+ }
5739
+ function parseHttpStatusFromMessage(message) {
5740
+ const match = /^HTTP\s+(\d{3})(?::|\s|-|$)/i.exec(message.trim());
5741
+ if (!match)
5742
+ return;
5743
+ const status = Number(match[1]);
5744
+ return Number.isInteger(status) && status >= 100 && status <= 599 ? status : undefined;
5745
+ }
5746
+ function isHtmlDocument(body) {
5747
+ return /^\s*(<!doctype html|<html\b)/i.test(body);
5748
+ }
5749
+ function retryHintForRetryAfter(seconds) {
5750
+ if (seconds <= 1) {
4991
5751
  return "RetryAfter1Second";
4992
5752
  }
4993
5753
  if (seconds <= 10) {
@@ -5169,7 +5929,7 @@ async function extractErrorDetails(error, options) {
5169
5929
  } else if (typeof err.message === "string") {
5170
5930
  details = err.message;
5171
5931
  } else {
5172
- details = String(error);
5932
+ details = describeThrownValue(error);
5173
5933
  }
5174
5934
  const context = {};
5175
5935
  if (status) {
@@ -5245,39 +6005,10 @@ async function extractErrorMessage(error, options) {
5245
6005
  const { message } = await extractErrorDetails(error, options);
5246
6006
  return message;
5247
6007
  }
5248
- // ../../../node_modules/commander/esm.mjs
5249
- var import__2 = __toESM(require_commander(), 1);
5250
- var {
5251
- program,
5252
- createCommand,
5253
- createArgument,
5254
- createOption,
5255
- CommanderError,
5256
- InvalidArgumentError,
5257
- InvalidOptionArgumentError,
5258
- Command,
5259
- Argument,
5260
- Option,
5261
- Help
5262
- } = import__2.default;
5263
-
5264
- // ../../common/src/command-examples.ts
5265
- var examplesByCommand = new WeakMap;
5266
- Command.prototype.examples = function(examples) {
5267
- examplesByCommand.set(this, examples);
5268
- return this;
5269
- };
5270
- // ../../common/src/preview.ts
5271
- var previewSlot = singleton("PreviewBuild");
5272
- function isPreviewBuild() {
5273
- return previewSlot.get(false) ?? false;
6008
+ // ../../common/src/exit-code.ts
6009
+ function setExitCode(code) {
6010
+ process.exitCode = code;
5274
6011
  }
5275
- Command.prototype.previewCommand = function(nameAndArgs, opts) {
5276
- if (isPreviewBuild()) {
5277
- return this.command(nameAndArgs, opts);
5278
- }
5279
- return new Command(nameAndArgs.split(/\s+/)[0] ?? nameAndArgs);
5280
- };
5281
6012
 
5282
6013
  // ../../common/src/output-context.ts
5283
6014
  function createStorage() {
@@ -5312,8 +6043,8 @@ function getOutputSink() {
5312
6043
 
5313
6044
  // ../../common/src/logger.ts
5314
6045
  var logFilePathSlot = singleton("logFilePath");
5315
- function setGlobalLogFilePath(path) {
5316
- logFilePathSlot.set(path);
6046
+ function setGlobalLogFilePath(path2) {
6047
+ logFilePathSlot.set(path2);
5317
6048
  }
5318
6049
  function getGlobalLogFilePath() {
5319
6050
  return logFilePathSlot.get("");
@@ -5381,54 +6112,49 @@ class SimpleLogger {
5381
6112
  return this.fileLoggingEnabled || !!getGlobalLogFilePath();
5382
6113
  }
5383
6114
  writeToFile(formatted) {
5384
- const path = this.logFilePath || getGlobalLogFilePath();
5385
- if (!path)
6115
+ const path2 = this.logFilePath || getGlobalLogFilePath();
6116
+ if (!path2)
5386
6117
  return;
5387
6118
  const timestamp = new Date().toISOString();
5388
6119
  this.pendingWrites = Promise.all([
5389
6120
  this.pendingWrites,
5390
6121
  this.pendingInit
5391
- ]).then(() => getFileSystem().appendFile(path, `${timestamp} ${formatted}`).catch(() => {}));
6122
+ ]).then(() => getFileSystem().appendFile(path2, `${timestamp} ${formatted}`).catch(() => {}));
5392
6123
  }
5393
- debug(message, ...args) {
5394
- if (this.level > 0 /* DEBUG */)
5395
- return;
5396
- const formatted = this.format(`[DEBUG] ${message}`, args);
6124
+ write(formatted) {
5397
6125
  if (this.isFileLoggingActive()) {
5398
6126
  this.writeToFile(formatted);
5399
6127
  } else {
5400
6128
  getOutputSink().writeErr(formatted);
5401
6129
  }
5402
6130
  }
6131
+ debug(message, ...args) {
6132
+ if (this.level > 0 /* DEBUG */)
6133
+ return;
6134
+ const formatted = this.format(`[DEBUG] ${message}`, args);
6135
+ this.write(formatted);
6136
+ }
5403
6137
  info(message, ...args) {
5404
6138
  if (this.level > 1 /* INFO */)
5405
6139
  return;
5406
6140
  const formatted = this.format(message, args);
5407
- if (this.isFileLoggingActive()) {
5408
- this.writeToFile(formatted);
5409
- } else {
5410
- getOutputSink().writeErr(formatted);
5411
- }
6141
+ this.write(formatted);
5412
6142
  }
5413
6143
  warn(message, ...args) {
5414
6144
  if (this.level > 2 /* WARN */)
5415
6145
  return;
5416
6146
  const formatted = this.format(`[WARN] ${message}`, args);
5417
- if (this.isFileLoggingActive()) {
5418
- this.writeToFile(formatted);
5419
- } else {
5420
- getOutputSink().writeErr(formatted);
5421
- }
6147
+ this.write(formatted);
5422
6148
  }
5423
6149
  error(message, ...args) {
5424
6150
  if (this.level > 3 /* ERROR */)
5425
6151
  return;
5426
6152
  const formatted = this.format(`[ERROR] ${message}`, args);
5427
- if (this.isFileLoggingActive()) {
5428
- this.writeToFile(formatted);
5429
- } else {
5430
- getOutputSink().writeErr(formatted);
5431
- }
6153
+ this.write(formatted);
6154
+ }
6155
+ report(message) {
6156
+ const formatted = this.format(message, []);
6157
+ this.write(formatted);
5432
6158
  }
5433
6159
  getLevel() {
5434
6160
  return this.level;
@@ -5443,17 +6169,17 @@ class SimpleLogger {
5443
6169
  setGlobalLogFilePath("");
5444
6170
  }
5445
6171
  }
5446
- setLogFile(path) {
5447
- this.logFilePath = path;
5448
- setGlobalLogFilePath(path);
5449
- if (!path)
6172
+ setLogFile(path2) {
6173
+ this.logFilePath = path2;
6174
+ setGlobalLogFilePath(path2);
6175
+ if (!path2)
5450
6176
  return;
5451
6177
  this.fileLoggingEnabled = true;
5452
- const fs = getFileSystem();
6178
+ const fs2 = getFileSystem();
5453
6179
  this.pendingInit = (async () => {
5454
6180
  const [error] = await catchError2((async () => {
5455
- await fs.mkdir(fs.path.dirname(path));
5456
- await fs.writeFile(path, "");
6181
+ await fs2.mkdir(fs2.path.dirname(path2));
6182
+ await fs2.writeFile(path2, "");
5457
6183
  })());
5458
6184
  if (error)
5459
6185
  this.fileLoggingEnabled = false;
@@ -5507,12 +6233,12 @@ var jmespathSlot = singleton("JmespathCodec");
5507
6233
  async function loadOutputCodecsAsync(needed) {
5508
6234
  const loads = [];
5509
6235
  if (needed.yaml && yamlSlot.get() === undefined) {
5510
- loads.push(import("./js-yaml-eydtmn4r.js").then((mod) => {
6236
+ loads.push(import("./js-yaml-71wj4em9.js").then((mod) => {
5511
6237
  yamlSlot.set(mod);
5512
6238
  }));
5513
6239
  }
5514
6240
  if (needed.filter && jmespathSlot.get() === undefined) {
5515
- loads.push(import("./index-xaqpc626.js").then((mod) => {
6241
+ loads.push(import("./index-q6vc5bja.js").then((mod) => {
5516
6242
  jmespathSlot.set(mod);
5517
6243
  }));
5518
6244
  }
@@ -5790,27 +6516,41 @@ class LoggerTelemetryProvider {
5790
6516
  ...this.analyticsUniqueId ? { analyticsUniqueId: this.analyticsUniqueId } : {}
5791
6517
  };
5792
6518
  }
5793
- async trackEvent(eventName, properties) {
5794
- logger.debug(formatMessage("Event", eventName, this.enrich(properties)));
6519
+ async trackEvent({ name, properties }) {
6520
+ logger.debug(formatMessage("Event", name, this.enrich(properties)));
5795
6521
  }
5796
- async trackException(error, properties) {
6522
+ async trackException({
6523
+ error,
6524
+ properties
6525
+ }) {
5797
6526
  logger.error(formatMessage("Exception", error.message, this.enrich({
5798
6527
  ...properties,
5799
6528
  stack: error.stack
5800
6529
  })));
5801
6530
  }
5802
- async trackRequest(name, duration, success, properties) {
6531
+ async trackRequest({
6532
+ name,
6533
+ durationMs,
6534
+ success,
6535
+ properties
6536
+ }) {
5803
6537
  logger.debug(formatMessage("Request", name, this.enrich({
5804
6538
  ...properties,
5805
- duration: `${duration}ms`,
6539
+ duration: `${durationMs}ms`,
5806
6540
  success
5807
6541
  })));
5808
6542
  }
5809
- async trackDependency(name, type, duration, success, properties) {
6543
+ async trackDependency({
6544
+ name,
6545
+ type,
6546
+ durationMs,
6547
+ success,
6548
+ properties
6549
+ }) {
5810
6550
  logger.debug(formatMessage("Dependency", name, this.enrich({
5811
6551
  ...properties,
5812
6552
  type,
5813
- duration: `${duration}ms`,
6553
+ duration: `${durationMs}ms`,
5814
6554
  success
5815
6555
  })));
5816
6556
  }
@@ -6004,200 +6744,72 @@ var INHERITED_SESSION_SOURCES = [
6004
6744
  { envVar: "TERM_SESSION_ID", source: "terminal" },
6005
6745
  { envVar: "WT_SESSION", source: "terminal" }
6006
6746
  ];
6007
- var telemetrySessionSlot = singleton("TelemetrySession");
6008
- var telemetryOperationIdSlot = singleton("TelemetryOperationId");
6009
- function getProcessEnv2() {
6010
- return globalThis.process?.env;
6011
- }
6012
- function normalizeSessionId(value) {
6013
- if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") {
6014
- return;
6015
- }
6016
- const cleaned = String(value).replace(CONTROL_CHARACTERS, "").trim().slice(0, SESSION_ID_MAX_LENGTH);
6017
- return cleaned || undefined;
6018
- }
6019
- function getConfiguredTelemetrySessionId() {
6020
- return normalizeSessionId(getProcessEnv2()?.[TELEMETRY_SESSION_ID_ENV]);
6021
- }
6022
- function getInheritedSession(env) {
6023
- for (const candidate of INHERITED_SESSION_SOURCES) {
6024
- const handle = normalizeSessionId(env[candidate.envVar]);
6025
- if (handle) {
6026
- return { id: handle, source: candidate.source };
6027
- }
6028
- }
6029
- return;
6030
- }
6031
- function generateRandomSession() {
6032
- const bytes = new Uint8Array(RANDOM_SESSION_ID_LENGTH / 2);
6033
- crypto.getRandomValues(bytes);
6034
- let hex = "";
6035
- for (const byte of bytes) {
6036
- hex += byte.toString(16).padStart(2, "0");
6037
- }
6038
- return { id: hex, source: "random" };
6039
- }
6040
- function resolveTelemetrySession() {
6041
- const existing = telemetrySessionSlot.get();
6042
- if (existing) {
6043
- return existing;
6044
- }
6045
- const declaredHandle = getConfiguredTelemetrySessionId();
6046
- const resolved = declaredHandle ? { id: declaredHandle, source: "declared" } : getInheritedSession(getProcessEnv2() ?? {}) ?? generateRandomSession();
6047
- telemetrySessionSlot.set(resolved);
6048
- return resolved;
6049
- }
6050
- function getTelemetrySessionSource() {
6051
- return resolveTelemetrySession().source;
6052
- }
6053
- function getTelemetryOperationId() {
6054
- const existing = telemetryOperationIdSlot.get();
6055
- if (existing) {
6056
- return existing;
6057
- }
6058
- const inboundTraceId = getInboundTraceContext()?.traceId;
6059
- const generated = inboundTraceId ?? crypto.randomUUID().replaceAll("-", "");
6060
- telemetryOperationIdSlot.set(generated);
6061
- return generated;
6062
- }
6063
- // ../../common/src/telemetry/pii-redactor.ts
6064
- var REDACTED = "[REDACTED]";
6065
- var MAX_VALUE_LENGTH = 200;
6066
- var SENSITIVE_NAME_TOKENS = new Set([
6067
- "token",
6068
- "tokens",
6069
- "secret",
6070
- "secrets",
6071
- "password",
6072
- "passwords",
6073
- "pwd",
6074
- "credential",
6075
- "credentials",
6076
- "auth",
6077
- "authentication",
6078
- "authorization",
6079
- "authority",
6080
- "cert",
6081
- "certificate",
6082
- "certificates"
6083
- ]);
6084
- var SENSITIVE_KEY_PREFIXES = new Set([
6085
- "api",
6086
- "access",
6087
- "client",
6088
- "private",
6089
- "public",
6090
- "signing",
6091
- "encryption",
6092
- "session",
6093
- "master",
6094
- "shared",
6095
- "root",
6096
- "ssh",
6097
- "rsa",
6098
- "aes",
6099
- "hmac",
6100
- "oauth"
6101
- ]);
6102
- 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;
6103
- var EMAIL_PATTERN = /\b[^\s@]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g;
6104
- var JWT_PATTERN = /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g;
6105
- var LONG_TOKEN_PATTERN = /\b[A-Za-z0-9_-]{40,}\b/g;
6106
- var USER_HOME_PATTERN = /([/\\])(Users|home)([/\\])([^/\\]+)/gi;
6107
- var URL_PATTERN = /\bhttps?:\/\/[^\s,;]+/gi;
6108
- var URL_TRAILING_PUNCT = /[.,;:!?)\]}>'"]+$/;
6109
- function shortHash(input) {
6110
- let hash = 2166136261;
6111
- for (let i = 0;i < input.length; i++) {
6112
- hash ^= input.charCodeAt(i);
6113
- hash = Math.imul(hash, 16777619);
6114
- }
6115
- return (hash >>> 0).toString(16).padStart(8, "0");
6116
- }
6117
- function redactUrl(raw) {
6118
- try {
6119
- const url = new URL(raw);
6120
- return `${url.protocol}//${url.host}`;
6121
- } catch {
6122
- return `url#${shortHash(raw)}`;
6123
- }
6124
- }
6125
- function redactValueDetectors(value) {
6126
- let out = value;
6127
- out = out.replace(JWT_PATTERN, () => REDACTED);
6128
- out = out.replace(URL_PATTERN, (match) => {
6129
- const trailing = match.match(URL_TRAILING_PUNCT)?.[0] ?? "";
6130
- const core = trailing ? match.slice(0, -trailing.length) : match;
6131
- return `${redactUrl(core)}${trailing}`;
6132
- });
6133
- out = out.replace(USER_HOME_PATTERN, (_match, sep1, folder, sep2) => `${sep1}${folder}${sep2}<user>`);
6134
- out = out.replace(EMAIL_PATTERN, (match) => `email#${shortHash(match)}`);
6135
- out = out.replace(UUID_PATTERN, (match) => `uuid#${shortHash(match)}`);
6136
- out = out.replace(LONG_TOKEN_PATTERN, () => REDACTED);
6137
- if (out.length > MAX_VALUE_LENGTH) {
6138
- out = `${out.slice(0, MAX_VALUE_LENGTH)}…`;
6139
- }
6140
- return out;
6141
- }
6142
- function redactValue(value) {
6143
- return redactValueDetectors(value);
6747
+ var telemetrySessionSlot = singleton("TelemetrySession");
6748
+ var telemetryOperationIdSlot = singleton("TelemetryOperationId");
6749
+ function getProcessEnv2() {
6750
+ return globalThis.process?.env;
6144
6751
  }
6145
- function redactError(error) {
6146
- const safe = new Error(redactValueDetectors(error.message ?? ""));
6147
- safe.name = error.name;
6148
- safe.stack = typeof error.stack === "string" ? redactValueDetectors(error.stack) : undefined;
6149
- return safe;
6752
+ function normalizeSessionId(value) {
6753
+ if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") {
6754
+ return;
6755
+ }
6756
+ const cleaned = String(value).replace(CONTROL_CHARACTERS, "").trim().slice(0, SESSION_ID_MAX_LENGTH);
6757
+ return cleaned || undefined;
6150
6758
  }
6151
- function nameTokens(name) {
6152
- 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);
6759
+ function getConfiguredTelemetrySessionId() {
6760
+ return normalizeSessionId(getProcessEnv2()?.[TELEMETRY_SESSION_ID_ENV]);
6153
6761
  }
6154
- function isSensitiveName(name) {
6155
- const tokens = nameTokens(name);
6156
- for (let i = 0;i < tokens.length; i++) {
6157
- const token = tokens[i];
6158
- if (SENSITIVE_NAME_TOKENS.has(token)) {
6159
- return true;
6160
- }
6161
- if (token === "key" || token === "keys") {
6162
- const prev = tokens[i - 1];
6163
- if (prev && SENSITIVE_KEY_PREFIXES.has(prev)) {
6164
- return true;
6165
- }
6762
+ function getInheritedSession(env) {
6763
+ for (const candidate of INHERITED_SESSION_SOURCES) {
6764
+ const handle = normalizeSessionId(env[candidate.envVar]);
6765
+ if (handle) {
6766
+ return { id: handle, source: candidate.source };
6166
6767
  }
6167
6768
  }
6168
- return false;
6769
+ return;
6169
6770
  }
6170
- function redactProperty(name, value) {
6171
- if (value === undefined || value === null) {
6172
- return;
6173
- }
6174
- if (isSensitiveName(name)) {
6175
- return REDACTED;
6176
- }
6177
- if (typeof value === "boolean" || typeof value === "number") {
6178
- return value;
6771
+ function generateRandomSession() {
6772
+ const bytes = new Uint8Array(RANDOM_SESSION_ID_LENGTH / 2);
6773
+ crypto.getRandomValues(bytes);
6774
+ let hex = "";
6775
+ for (const byte of bytes) {
6776
+ hex += byte.toString(16).padStart(2, "0");
6179
6777
  }
6180
- if (typeof value !== "string") {
6181
- return "[OBJECT]";
6778
+ return { id: hex, source: "random" };
6779
+ }
6780
+ function resolveTelemetrySession() {
6781
+ const existing = telemetrySessionSlot.get();
6782
+ if (existing) {
6783
+ return existing;
6182
6784
  }
6183
- return redactValueDetectors(value);
6785
+ const declaredHandle = getConfiguredTelemetrySessionId();
6786
+ const resolved = declaredHandle ? { id: declaredHandle, source: "declared" } : getInheritedSession(getProcessEnv2() ?? {}) ?? generateRandomSession();
6787
+ telemetrySessionSlot.set(resolved);
6788
+ return resolved;
6184
6789
  }
6185
- function redactProperties(properties) {
6186
- const out = {};
6187
- for (const [name, value] of Object.entries(properties)) {
6188
- const redacted = redactProperty(name, value);
6189
- if (redacted !== undefined) {
6190
- out[name] = redacted;
6191
- }
6790
+ function getTelemetrySessionSource() {
6791
+ return resolveTelemetrySession().source;
6792
+ }
6793
+ function getTelemetryOperationId() {
6794
+ const existing = telemetryOperationIdSlot.get();
6795
+ if (existing) {
6796
+ return existing;
6192
6797
  }
6193
- return out;
6798
+ const inboundTraceId = getInboundTraceContext()?.traceId;
6799
+ const generated = inboundTraceId ?? crypto.randomUUID().replaceAll("-", "");
6800
+ telemetryOperationIdSlot.set(generated);
6801
+ return generated;
6802
+ }
6803
+ // ../../common/src/telemetry/span-clock.ts
6804
+ function startSpanClock() {
6805
+ const started = performance.now();
6806
+ return {
6807
+ startedAt: new Date(performance.timeOrigin + started),
6808
+ elapsedMs: () => performance.now() - started
6809
+ };
6194
6810
  }
6195
6811
 
6196
6812
  // ../../common/src/telemetry/telemetry-service.ts
6197
- var TELEMETRY_OPERATION_ID_PROPERTY = "uip.trace.operation_id";
6198
- var TELEMETRY_PARENT_ID_PROPERTY = "uip.trace.parent_id";
6199
- var TELEMETRY_SPAN_ID_PROPERTY = "uip.trace.span_id";
6200
-
6201
6813
  class TelemetryService {
6202
6814
  telemetryProvider;
6203
6815
  contextStorage;
@@ -6217,36 +6829,39 @@ class TelemetryService {
6217
6829
  this.defaultProperties = properties === undefined ? undefined : { ...this.defaultProperties, ...properties };
6218
6830
  }
6219
6831
  trackEvent(name, properties) {
6220
- const context = this.getCurrentContext();
6221
- const enrichedProperties = this.enrichPropertiesWithContext(properties, context);
6222
- this.telemetryProvider.trackEvent(name, enrichedProperties);
6832
+ this.telemetryProvider.trackEvent({
6833
+ name: redactSpanName(name),
6834
+ properties: this.enrichProperties(properties),
6835
+ ...this.leafCorrelation()
6836
+ });
6223
6837
  }
6224
- trackException(error, properties) {
6225
- const context = this.getCurrentContext();
6226
- const enrichedProperties = this.enrichPropertiesWithContext(properties, context);
6227
- this.telemetryProvider.trackException(redactError(error), enrichedProperties);
6838
+ trackException(error, properties, context) {
6839
+ this.telemetryProvider.trackException({
6840
+ error: redactError(error),
6841
+ properties: this.enrichProperties(properties),
6842
+ ...this.leafCorrelation(context)
6843
+ });
6228
6844
  }
6229
6845
  async trackRequest(name, fn, properties) {
6230
- const parentContext = this.getCurrentContext();
6846
+ const parentContext = this.getActiveContext();
6231
6847
  const operationId = parentContext?.operationId ?? this.operationId ?? getTelemetryOperationId();
6232
6848
  const parentId = parentContext ? parentContext.id : this.inboundParentIdFor(operationId);
6849
+ const clock = startSpanClock();
6233
6850
  const context = {
6234
6851
  operationId,
6235
6852
  ...parentId !== undefined ? { parentId } : {},
6236
- id: this.generateId()
6853
+ id: this.generateId(),
6854
+ startedAt: clock.startedAt
6237
6855
  };
6238
- const startTime = performance.now();
6239
6856
  try {
6240
6857
  const result = await this.contextStorage.run(context, fn);
6241
- const durationMs = performance.now() - startTime;
6242
- const enrichedProperties = this.enrichPropertiesWithContext(properties, context);
6243
- await this.telemetryProvider.trackRequest(name, durationMs, true, enrichedProperties);
6858
+ const durationMs = clock.elapsedMs();
6859
+ await this.telemetryProvider.trackRequest(this.spanFor(name, durationMs, true, properties, context));
6244
6860
  return result;
6245
6861
  } catch (error) {
6246
- const durationMs = performance.now() - startTime;
6862
+ const durationMs = clock.elapsedMs();
6247
6863
  const err = error instanceof Error ? error : new Error(String(error));
6248
- const enrichedProperties = this.enrichPropertiesWithContext({ ...properties, errorMessage: err.message }, context);
6249
- await this.telemetryProvider.trackRequest(name, durationMs, false, enrichedProperties);
6864
+ await this.telemetryProvider.trackRequest(this.spanFor(name, durationMs, false, { ...properties, errorMessage: err.message }, context));
6250
6865
  throw error;
6251
6866
  }
6252
6867
  }
@@ -6255,8 +6870,7 @@ class TelemetryService {
6255
6870
  operationId: this.operationId ?? getTelemetryOperationId(),
6256
6871
  id: this.generateId()
6257
6872
  };
6258
- const enrichedProperties = this.enrichPropertiesWithContext(properties, requestContext);
6259
- this.telemetryProvider.trackRequest(name, durationMs, success, enrichedProperties);
6873
+ this.telemetryProvider.trackRequest(this.spanFor(name, durationMs, success, properties, requestContext));
6260
6874
  }
6261
6875
  createRequestContext() {
6262
6876
  const operationId = this.operationId ?? getTelemetryOperationId();
@@ -6264,7 +6878,8 @@ class TelemetryService {
6264
6878
  return {
6265
6879
  operationId,
6266
6880
  ...parentId !== undefined ? { parentId } : {},
6267
- id: this.generateId()
6881
+ id: this.generateId(),
6882
+ startedAt: startSpanClock().startedAt
6268
6883
  };
6269
6884
  }
6270
6885
  inboundParentIdFor(operationId) {
@@ -6275,58 +6890,84 @@ class TelemetryService {
6275
6890
  return this.contextStorage.run(context, fn);
6276
6891
  }
6277
6892
  createDependencyContext() {
6278
- const parentContext = this.getCurrentContext();
6893
+ const parentContext = this.getActiveContext();
6279
6894
  if (!parentContext) {
6280
6895
  return;
6281
6896
  }
6282
6897
  return {
6283
6898
  operationId: parentContext.operationId,
6284
6899
  parentId: parentContext.id,
6285
- id: this.generateId()
6900
+ id: this.generateId(),
6901
+ startedAt: startSpanClock().startedAt
6286
6902
  };
6287
6903
  }
6288
6904
  trackDependencyResult(name, type, durationMs, success, properties, context, resultCode) {
6289
- const enrichedProperties = this.enrichPropertiesWithContext(properties, context);
6290
- this.telemetryProvider.trackDependency(redactValue(name), type, durationMs, success, enrichedProperties, resultCode);
6905
+ this.telemetryProvider.trackDependency({
6906
+ ...this.spanFor(redactHttpDependencyName(name), durationMs, success, properties, context),
6907
+ type,
6908
+ ...resultCode !== undefined ? { resultCode } : {}
6909
+ });
6291
6910
  }
6292
6911
  async trackDependencyOperation(name, type, fn, properties) {
6293
- const parentContext = this.getCurrentContext();
6912
+ const clock = startSpanClock();
6913
+ const parentContext = this.getActiveContext();
6294
6914
  const childContext = parentContext !== undefined ? {
6295
6915
  operationId: parentContext.operationId,
6296
6916
  parentId: parentContext.id,
6297
- id: this.generateId()
6298
- } : this.createRequestContext();
6299
- const startTime = performance.now();
6917
+ id: this.generateId(),
6918
+ startedAt: clock.startedAt
6919
+ } : {
6920
+ ...this.createRequestContext(),
6921
+ startedAt: clock.startedAt
6922
+ };
6300
6923
  try {
6301
6924
  const result = await this.contextStorage.run(childContext, fn);
6302
- const durationMs = performance.now() - startTime;
6303
- const enrichedProperties = this.enrichPropertiesWithContext(properties, childContext);
6304
- await this.telemetryProvider.trackDependency(name, type, durationMs, true, enrichedProperties);
6925
+ const durationMs = clock.elapsedMs();
6926
+ await this.telemetryProvider.trackDependency({
6927
+ ...this.spanFor(name, durationMs, true, properties, childContext),
6928
+ type
6929
+ });
6305
6930
  return result;
6306
6931
  } catch (error) {
6307
- const durationMs = performance.now() - startTime;
6932
+ const durationMs = clock.elapsedMs();
6308
6933
  const err = error instanceof Error ? error : new Error(String(error));
6309
- const enrichedProperties = this.enrichPropertiesWithContext({ ...properties, errorMessage: err.message }, childContext);
6310
- await this.telemetryProvider.trackDependency(name, type, durationMs, false, enrichedProperties);
6934
+ await this.telemetryProvider.trackDependency({
6935
+ ...this.spanFor(name, durationMs, false, { ...properties, errorMessage: err.message }, childContext),
6936
+ type
6937
+ });
6311
6938
  throw error;
6312
6939
  }
6313
6940
  }
6314
- getCurrentContext() {
6941
+ getActiveContext() {
6315
6942
  return this.contextStorage.getContext();
6316
6943
  }
6317
- enrichPropertiesWithContext(properties, context) {
6944
+ leafCorrelation(explicit) {
6945
+ const context = explicit ?? this.getActiveContext();
6946
+ return {
6947
+ operationId: context?.operationId ?? this.operationId ?? getTelemetryOperationId(),
6948
+ ...context !== undefined ? { parentId: context.id } : {}
6949
+ };
6950
+ }
6951
+ spanFor(name, durationMs, success, properties, context) {
6952
+ return {
6953
+ name: redactSpanName(name),
6954
+ durationMs,
6955
+ success,
6956
+ properties: this.enrichProperties(properties),
6957
+ operationId: context.operationId,
6958
+ ...context.parentId !== undefined ? { parentId: context.parentId } : {},
6959
+ id: context.id,
6960
+ ...context.startedAt !== undefined ? { startedAt: context.startedAt } : {}
6961
+ };
6962
+ }
6963
+ enrichProperties(properties) {
6318
6964
  const globalProperties = getGlobalTelemetryProperties();
6319
6965
  const enriched = {
6320
6966
  ...getExecutionContextTelemetryProperties(),
6321
6967
  ...globalProperties,
6322
6968
  ...this.defaultProperties,
6323
6969
  ...redactProperties(properties ?? {}),
6324
- [TELEMETRY_SESSION_SOURCE_PROPERTY]: getTelemetrySessionSource(),
6325
- ...context ? {
6326
- [TELEMETRY_OPERATION_ID_PROPERTY]: context.operationId,
6327
- ...context.parentId !== undefined ? { [TELEMETRY_PARENT_ID_PROPERTY]: context.parentId } : {},
6328
- [TELEMETRY_SPAN_ID_PROPERTY]: context.id
6329
- } : {}
6970
+ [TELEMETRY_SESSION_SOURCE_PROPERTY]: getTelemetrySessionSource()
6330
6971
  };
6331
6972
  return enriched;
6332
6973
  }
@@ -6343,6 +6984,81 @@ class TelemetryService {
6343
6984
  return hex;
6344
6985
  }
6345
6986
  }
6987
+ // ../../common/src/timings.ts
6988
+ var TIMINGS_ENV_VAR = "UIP_TIMINGS";
6989
+ function createStorage2() {
6990
+ const [error, mod] = catchError2(() => __require("node:async_hooks"));
6991
+ if (error || typeof mod?.AsyncLocalStorage !== "function") {
6992
+ return {
6993
+ getStore: () => {
6994
+ return;
6995
+ },
6996
+ run: (_store, fn) => fn()
6997
+ };
6998
+ }
6999
+ return new mod.AsyncLocalStorage;
7000
+ }
7001
+ var storageSlot = singleton("TimingStorage");
7002
+ var stateSlot = singleton("Timings");
7003
+ var rootStartedSlot = singleton("TimingsRootStarted");
7004
+ var longLivedHostSlot = singleton("TimingsLongLivedHost");
7005
+ var storage = storageSlot.getOrInit(createStorage2, (value) => ("getStore" in value));
7006
+ function newState(baseline) {
7007
+ return { baseline, httpMs: 0, httpCalls: 0 };
7008
+ }
7009
+ function getState() {
7010
+ const scoped = storage.getStore();
7011
+ if (scoped) {
7012
+ return scoped;
7013
+ }
7014
+ const pinned = livePinnedState();
7015
+ if (pinned !== undefined) {
7016
+ return pinned;
7017
+ }
7018
+ return newState(processStartIsInvocationStart() ? 0 : performance.now());
7019
+ }
7020
+ function livePinnedState() {
7021
+ const pinned = stateSlot.get();
7022
+ return pinned !== undefined && "httpCalls" in pinned && !pinned.finished ? pinned : undefined;
7023
+ }
7024
+ function processStartIsInvocationStart() {
7025
+ return !rootStartedSlot.get(false) && !longLivedHostSlot.get(false);
7026
+ }
7027
+ function timingsEnabled() {
7028
+ if (typeof process === "undefined") {
7029
+ return false;
7030
+ }
7031
+ const value = process.env?.[TIMINGS_ENV_VAR];
7032
+ if (value === undefined) {
7033
+ return false;
7034
+ }
7035
+ const normalized = value.trim().toLowerCase();
7036
+ return normalized === "1" || normalized === "true";
7037
+ }
7038
+ function recordExitCode(exitCode) {
7039
+ if (!timingsEnabled()) {
7040
+ return;
7041
+ }
7042
+ getState().exitCode = exitCode;
7043
+ }
7044
+ function invocationStartedAt() {
7045
+ return new Date(performance.timeOrigin + getState().baseline);
7046
+ }
7047
+ function invocationElapsedMs() {
7048
+ return performance.now() - getState().baseline;
7049
+ }
7050
+ function markCommandStart() {
7051
+ if (!timingsEnabled()) {
7052
+ return;
7053
+ }
7054
+ getState().commandStart = performance.now();
7055
+ }
7056
+ function recordCommandDuration(durationMs) {
7057
+ if (!timingsEnabled()) {
7058
+ return;
7059
+ }
7060
+ getState().commandMs = durationMs;
7061
+ }
6346
7062
  // ../../common/src/telemetry/proxy-http-agent.ts
6347
7063
  var slot = singleton("ProxyAuthHttpsAgent");
6348
7064
 
@@ -6363,6 +7079,9 @@ function getGlobalTelemetryInstance() {
6363
7079
  }
6364
7080
  return;
6365
7081
  }
7082
+ function setGlobalTelemetryInstance(instance) {
7083
+ telemetryInstanceSlot.set(instance);
7084
+ }
6366
7085
  var _localTelemetryInstance;
6367
7086
  function getTelemetryInstance() {
6368
7087
  const global = getGlobalTelemetryInstance();
@@ -6370,6 +7089,7 @@ function getTelemetryInstance() {
6370
7089
  return global;
6371
7090
  if (!_localTelemetryInstance) {
6372
7091
  _localTelemetryInstance = new TelemetryService(new LoggerTelemetryProvider, new NodeContextStorage);
7092
+ setGlobalTelemetryInstance(_localTelemetryInstance);
6373
7093
  }
6374
7094
  return _localTelemetryInstance;
6375
7095
  }
@@ -6382,6 +7102,14 @@ var telemetry = new Proxy({}, {
6382
7102
  });
6383
7103
 
6384
7104
  // ../../common/src/formatter.ts
7105
+ var ANSI_STYLES = {
7106
+ red: "\x1B[31m",
7107
+ dim: "\x1B[2m"
7108
+ };
7109
+ var ANSI_RESET = "\x1B[0m";
7110
+ function styleLine(line, style) {
7111
+ return style ? `${ANSI_STYLES[style]}${line}${ANSI_RESET}` : line;
7112
+ }
6385
7113
  var CLI_ERROR_CODES = [
6386
7114
  "invalid_argument",
6387
7115
  "authentication_required",
@@ -6420,22 +7148,6 @@ var EXIT_CODES = {
6420
7148
  ValidationError: 3,
6421
7149
  TimeoutError: 4
6422
7150
  };
6423
- class SuccessOutput {
6424
- Result = RESULTS.Success;
6425
- Code;
6426
- Data;
6427
- Pagination;
6428
- Instructions;
6429
- Log;
6430
- constructor(code, data) {
6431
- this.Code = code;
6432
- this.Data = data;
6433
- const logPath = getLogFilePath();
6434
- if (logPath) {
6435
- this.Log = logPath;
6436
- }
6437
- }
6438
- }
6439
7151
  function escapeNonAscii(jsonText) {
6440
7152
  return jsonText.replace(/[\u0080-\uffff]/g, (c) => {
6441
7153
  const hex = c.charCodeAt(0).toString(16).padStart(4, "0");
@@ -6500,19 +7212,45 @@ function toPascalCaseKey(key) {
6500
7212
  const lowerCamelKey = toLowerCamelCaseKey(key);
6501
7213
  return lowerCamelKey ? lowerCamelKey.charAt(0).toUpperCase() + lowerCamelKey.slice(1) : lowerCamelKey;
6502
7214
  }
6503
- function toPascalCaseData(value) {
7215
+ function collectVerbatimRefs(value, into) {
7216
+ if (typeof value !== "object" || value === null)
7217
+ return;
7218
+ if (into.has(value))
7219
+ return;
7220
+ into.add(value);
7221
+ for (const nested of Array.isArray(value) ? value : Object.values(value)) {
7222
+ collectVerbatimRefs(nested, into);
7223
+ }
7224
+ }
7225
+ function toPascalCaseData(value, verbatimKeys, subtrees) {
7226
+ if (subtrees?.mode === "skip" && typeof value === "object" && value !== null && subtrees.refs.has(value)) {
7227
+ return value;
7228
+ }
6504
7229
  if (Array.isArray(value))
6505
- return value.map(toPascalCaseData);
7230
+ return value.map((entry) => toPascalCaseData(entry, verbatimKeys, subtrees));
6506
7231
  if (!isPlainRecord(value))
6507
7232
  return value;
6508
7233
  const result = {};
6509
7234
  for (const [key, nestedValue] of Object.entries(value)) {
6510
- result[toPascalCaseKey(key)] = toPascalCaseData(nestedValue);
7235
+ const pascalKey = toPascalCaseKey(key);
7236
+ if (verbatimKeys?.has(pascalKey)) {
7237
+ result[pascalKey] = nestedValue;
7238
+ if (subtrees?.mode === "collect") {
7239
+ collectVerbatimRefs(nestedValue, subtrees.refs);
7240
+ }
7241
+ continue;
7242
+ }
7243
+ result[pascalKey] = toPascalCaseData(nestedValue, verbatimKeys, subtrees);
6511
7244
  }
6512
7245
  return result;
6513
7246
  }
6514
- function normalizeDataKeys(data) {
6515
- return toPascalCaseData(data);
7247
+ function normalizeDataKeys(data, verbatimKeys, subtrees) {
7248
+ return toPascalCaseData(data, verbatimKeys, subtrees);
7249
+ }
7250
+ function toVerbatimKeySet(preserve) {
7251
+ if (!Array.isArray(preserve))
7252
+ return;
7253
+ return new Set(preserve.map(toPascalCaseKey));
6516
7254
  }
6517
7255
  function normalizeOutputKeys(data) {
6518
7256
  const result = {};
@@ -6522,7 +7260,7 @@ function normalizeOutputKeys(data) {
6522
7260
  }
6523
7261
  return result;
6524
7262
  }
6525
- function printOutput(data, format = "json", logFn, asciiSafe = false) {
7263
+ function printOutput(data, format = "json", logFn, asciiSafe = false, tableRowStyle) {
6526
7264
  if (!data) {
6527
7265
  logFn("Empty response object. No data to display.");
6528
7266
  return;
@@ -6557,7 +7295,7 @@ function printOutput(data, format = "json", logFn, asciiSafe = false) {
6557
7295
  if (hasData && !(rows !== null && rows.length === 0)) {
6558
7296
  const logValue = data.Log;
6559
7297
  if (rows !== null) {
6560
- printResizableTable(rows, logFn, logValue);
7298
+ printResizableTable(rows, logFn, logValue, undefined, tableRowStyle);
6561
7299
  } else {
6562
7300
  printVerticalTable(data.Data, logFn, logValue);
6563
7301
  }
@@ -6568,10 +7306,11 @@ function printOutput(data, format = "json", logFn, asciiSafe = false) {
6568
7306
  }
6569
7307
  }
6570
7308
  }
6571
- function logOutput(data, format = "json") {
7309
+ function logOutput(data, format = "json", tableRowStyle) {
6572
7310
  const sink = getOutputSink();
7311
+ const styleFn = sink.capabilities.isInteractive && sink.capabilities.supportsColor ? tableRowStyle : undefined;
6573
7312
  printOutput(data, format, (msg) => sink.writeOut(`${msg}
6574
- `), needsAsciiSafeJson(sink));
7313
+ `), needsAsciiSafeJson(sink), styleFn);
6575
7314
  }
6576
7315
  function cellToString(val) {
6577
7316
  return val != null && typeof val === "object" ? JSON.stringify(val) : String(val ?? "");
@@ -6585,7 +7324,7 @@ function wrapText(text, width) {
6585
7324
  }
6586
7325
  return lines;
6587
7326
  }
6588
- function printTable(data, logFn, externalLogValue) {
7327
+ function printTable(data, logFn, externalLogValue, tableRowStyle) {
6589
7328
  if (data.length === 0)
6590
7329
  return;
6591
7330
  const keys = Object.keys(data[0]).filter((key) => !["code", "log"].includes(key.toLowerCase()));
@@ -6595,7 +7334,7 @@ function printTable(data, logFn, externalLogValue) {
6595
7334
  logFn(keys.map((_, i) => "-".repeat(maxWidths[i])).join("-|-"));
6596
7335
  data.forEach((item) => {
6597
7336
  const row = keys.map((key, i) => cellToString(item[key]).padEnd(maxWidths[i])).join(" | ");
6598
- logFn(row);
7337
+ logFn(styleLine(row, tableRowStyle?.(item)));
6599
7338
  });
6600
7339
  if (externalLogValue) {
6601
7340
  logFn("");
@@ -6638,14 +7377,14 @@ function printVerticalTable(data, logFn = console.log, externalLogValue) {
6638
7377
  logFn(`Log: ${externalLogValue}`);
6639
7378
  }
6640
7379
  }
6641
- function printResizableTable(data, logFn = console.log, externalLogValue, availableWidth) {
7380
+ function printResizableTable(data, logFn = console.log, externalLogValue, availableWidth, tableRowStyle) {
6642
7381
  if (data.length === 0)
6643
7382
  return;
6644
7383
  const keys = Object.keys(data[0]).filter((key) => !["code", "log"].includes(key.toLowerCase()));
6645
7384
  if (keys.length === 0)
6646
7385
  return;
6647
7386
  if (!process.stdout.isTTY) {
6648
- printTable(data, logFn, externalLogValue);
7387
+ printTable(data, logFn, externalLogValue, tableRowStyle);
6649
7388
  return;
6650
7389
  }
6651
7390
  const naturalWidths = keys.map((key) => Math.max(key.length, ...data.map((item) => cellToString(item[key]).length)));
@@ -6653,7 +7392,7 @@ function printResizableTable(data, logFn = console.log, externalLogValue, availa
6653
7392
  const totalWidth = naturalWidths.reduce((a, b) => a + b, 0) + separatorTotal;
6654
7393
  const termWidth = availableWidth ?? (process.stdout.columns || 120);
6655
7394
  if (totalWidth <= termWidth) {
6656
- printTable(data, logFn, externalLogValue);
7395
+ printTable(data, logFn, externalLogValue, tableRowStyle);
6657
7396
  return;
6658
7397
  }
6659
7398
  const overflow = totalWidth - termWidth;
@@ -6699,6 +7438,7 @@ function printResizableTable(data, logFn = console.log, externalLogValue, availa
6699
7438
  logFn(header);
6700
7439
  logFn(keys.map((_, i) => "-".repeat(finalWidths[i])).join("-|-"));
6701
7440
  data.forEach((item) => {
7441
+ const style = tableRowStyle?.(item);
6702
7442
  const cellLines = keys.map((key, i) => wrapText(cellToString(item[key]), finalWidths[i]));
6703
7443
  const lineCount = Math.max(...cellLines.map((l) => l.length));
6704
7444
  for (let line = 0;line < lineCount; line++) {
@@ -6706,7 +7446,7 @@ function printResizableTable(data, logFn = console.log, externalLogValue, availa
6706
7446
  const val = line < cellLines[i].length ? cellLines[i][line] : "";
6707
7447
  return val.padEnd(finalWidths[i]);
6708
7448
  }).join(" | ");
6709
- logFn(row);
7449
+ logFn(styleLine(row, style));
6710
7450
  }
6711
7451
  });
6712
7452
  if (externalLogValue) {
@@ -6850,30 +7590,36 @@ var OutputFormatter;
6850
7590
  ((OutputFormatter) => {
6851
7591
  function success(data, options) {
6852
7592
  data.Log ??= getLogFilePath() || undefined;
6853
- const normalize = !options?.preserveDataKeys;
7593
+ const normalize = options?.preserveDataKeys !== true;
7594
+ const verbatim = toVerbatimKeySet(options?.preserveDataKeys);
7595
+ const subtrees = verbatim && {
7596
+ refs: new Set,
7597
+ mode: "collect"
7598
+ };
6854
7599
  if (normalize) {
6855
- data.Data = normalizeDataKeys(data.Data);
7600
+ data.Data = normalizeDataKeys(data.Data, verbatim, subtrees);
6856
7601
  }
6857
7602
  const filter = getOutputFilter();
6858
7603
  if (filter) {
6859
7604
  const filtered = applyFilter(data.Data, filter);
6860
- data.Data = normalize ? normalizeDataKeys(filtered) : filtered;
7605
+ data.Data = normalize ? normalizeDataKeys(filtered, verbatim, subtrees && { refs: subtrees.refs, mode: "skip" }) : filtered;
6861
7606
  }
6862
- logOutput(normalizeOutputKeys(data), getOutputFormat());
7607
+ logOutput(normalizeOutputKeys(data), getOutputFormat(), options?.tableRowStyle);
6863
7608
  }
6864
7609
  OutputFormatter.success = success;
6865
7610
  function error(data) {
6866
7611
  data.Log ??= getLogFilePath() || undefined;
6867
7612
  data.ErrorCode ??= defaultErrorCodeForFailure(data);
6868
7613
  data.Retry ??= defaultRetryForErrorCode(data.ErrorCode);
6869
- process.exitCode = EXIT_CODES[data.Result] ?? 1;
7614
+ const exitCode = EXIT_CODES[data.Result] ?? 1;
7615
+ setExitCode(exitCode);
6870
7616
  recordCommandFailureTelemetry({
6871
7617
  result: data.Result,
6872
7618
  errorCode: data.ErrorCode,
6873
7619
  retry: data.Retry,
6874
7620
  message: data.Message,
6875
7621
  context: data.Context,
6876
- exitCode: process.exitCode,
7622
+ exitCode,
6877
7623
  errorClass: data.TelemetryErrorClass,
6878
7624
  terminalOutcome: data.TelemetryTerminalOutcome,
6879
7625
  terminalSignal: data.TelemetryTerminalSignal
@@ -6949,6 +7695,39 @@ var OutputFormatter;
6949
7695
  }
6950
7696
  OutputFormatter.formatToString = formatToString;
6951
7697
  })(OutputFormatter ||= {});
7698
+ // ../../../node_modules/commander/esm.mjs
7699
+ var import__2 = __toESM(require_commander(), 1);
7700
+ var {
7701
+ program,
7702
+ createCommand,
7703
+ createArgument,
7704
+ createOption,
7705
+ CommanderError,
7706
+ InvalidArgumentError,
7707
+ InvalidOptionArgumentError,
7708
+ Command,
7709
+ Argument,
7710
+ Option,
7711
+ Help
7712
+ } = import__2.default;
7713
+
7714
+ // ../../common/src/command-examples.ts
7715
+ var examplesByCommand = new WeakMap;
7716
+ Command.prototype.examples = function(examples) {
7717
+ examplesByCommand.set(this, examples);
7718
+ return this;
7719
+ };
7720
+ // ../../common/src/preview.ts
7721
+ var previewSlot = singleton("PreviewBuild");
7722
+ function isPreviewBuild() {
7723
+ return previewSlot.get(false) ?? false;
7724
+ }
7725
+ Command.prototype.previewCommand = function(nameAndArgs, opts) {
7726
+ if (isPreviewBuild()) {
7727
+ return this.command(nameAndArgs, opts);
7728
+ }
7729
+ return new Command(nameAndArgs.split(/\s+/)[0] ?? nameAndArgs);
7730
+ };
6952
7731
 
6953
7732
  // ../../common/src/telemetry/command-attribution.ts
6954
7733
  var LEGACY_SKILL_NAMESPACE = "uipath:";
@@ -7103,6 +7882,57 @@ function buildCommandTelemetryAttribution(commandPath, skillSource) {
7103
7882
  };
7104
7883
  }
7105
7884
 
7885
+ // ../../common/src/telemetry/command-name.ts
7886
+ var TELEMETRY_COMMAND_ROOT = "uip";
7887
+ function commandTelemetryName(parts) {
7888
+ const tokens = [];
7889
+ for (const part of parts) {
7890
+ const pieces = String(part ?? "").split(/\s+/).filter((token) => token && !token.startsWith("-") && token !== TELEMETRY_COMMAND_ROOT);
7891
+ if (pieces.every(isCommandToken)) {
7892
+ tokens.push(...pieces);
7893
+ continue;
7894
+ }
7895
+ tokens.push(UNKNOWN_TOKEN);
7896
+ }
7897
+ return [TELEMETRY_COMMAND_ROOT, ...tokens].join(".");
7898
+ }
7899
+ var COMMAND_TOKEN_PATTERN = /^[a-z0-9][a-z0-9-]*$/;
7900
+ var MAX_COMMAND_TOKEN_LENGTH = 32;
7901
+ var GUID_TOKEN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
7902
+ function isCommandToken(token) {
7903
+ return token.length <= MAX_COMMAND_TOKEN_LENGTH && COMMAND_TOKEN_PATTERN.test(token) && !GUID_TOKEN.test(token) && !/^\d+$/.test(token);
7904
+ }
7905
+ var UNKNOWN_TOKEN = "<unknown>";
7906
+
7907
+ // ../../common/src/telemetry/invocation-request.ts
7908
+ var requestContextSlot = singleton("TelemetryInvocationRequestContext");
7909
+ function activeContext() {
7910
+ return telemetry.getActiveContext?.();
7911
+ }
7912
+ function runWithInvocationRequest(fn) {
7913
+ const context = telemetry.createRequestContext();
7914
+ context.startedAt = invocationStartedAt();
7915
+ requestContextSlot.set(context);
7916
+ return telemetry.runWithContext(context, fn);
7917
+ }
7918
+ function ensureInvocationRequestScope(fn) {
7919
+ if (activeContext() !== undefined) {
7920
+ return fn();
7921
+ }
7922
+ const kept = requestContextSlot.get();
7923
+ return kept === undefined ? runWithInvocationRequest(fn) : telemetry.runWithContext(kept, fn);
7924
+ }
7925
+ function getInvocationRequestContext() {
7926
+ return activeContext() ?? requestContextSlot.get();
7927
+ }
7928
+ function emitInvocationRequest(name, success, properties) {
7929
+ const context = getInvocationRequestContext();
7930
+ telemetry.trackRequestResult(name, invocationElapsedMs(), success, properties, context);
7931
+ if (context !== undefined && requestContextSlot.get() === context) {
7932
+ requestContextSlot.clear();
7933
+ }
7934
+ }
7935
+
7106
7936
  // ../../common/src/trackedAction.ts
7107
7937
  var pollSignalSlot = singleton("PollSignal");
7108
7938
  var cliErrorCodeValues = new Set(CLI_ERROR_CODES);
@@ -7110,28 +7940,74 @@ var retryHintValues = new Set(RETRY_HINTS);
7110
7940
  var TELEMETRY_COMMAND_ARG_PREFIX = "uip.cmd.arg.";
7111
7941
  var processContext = {
7112
7942
  exit: (code) => {
7113
- process.exitCode = code;
7943
+ recordExitCode(code);
7944
+ setExitCode(code);
7114
7945
  },
7115
7946
  get pollSignal() {
7116
7947
  return pollSignalSlot.get();
7117
7948
  }
7118
7949
  };
7950
+ var TELEMETRY_ARG_VALUE_WITHHELD = "<provided>";
7951
+ var TELEMETRY_ARG_VALUE_DEFAULTED = "<default>";
7952
+ function recordableArgValue(value, choices) {
7953
+ if (typeof value === "boolean" || typeof value === "number") {
7954
+ return value;
7955
+ }
7956
+ if (choices && choices.length > 0) {
7957
+ if (typeof value === "string" && choices.includes(value)) {
7958
+ return value;
7959
+ }
7960
+ if (Array.isArray(value) && value.length > 0 && value.every((entry) => typeof entry === "string" && choices.includes(entry))) {
7961
+ return value.join(",");
7962
+ }
7963
+ }
7964
+ return TELEMETRY_ARG_VALUE_WITHHELD;
7965
+ }
7119
7966
  function extractCommandParams(cmd) {
7120
7967
  const params = {};
7121
- const add = (name, value) => {
7122
- if (name && value !== undefined) {
7123
- params[`${TELEMETRY_COMMAND_ARG_PREFIX}${name}`] = value;
7124
- }
7125
- };
7968
+ forEachSuppliedArgument(cmd, (name, value, choices, defaulted) => {
7969
+ const recordable = recordableArgValue(value, choices);
7970
+ params[`${TELEMETRY_COMMAND_ARG_PREFIX}${name}`] = recordable === TELEMETRY_ARG_VALUE_WITHHELD && defaulted ? TELEMETRY_ARG_VALUE_DEFAULTED : recordable;
7971
+ });
7972
+ return params;
7973
+ }
7974
+ function isDefaultedOption(cmd, name) {
7975
+ const source = cmd.getOptionValueSource?.(name);
7976
+ return source === "default" || source === "implied";
7977
+ }
7978
+ function isDefaultedPositional(cmd, index) {
7979
+ return index >= (cmd.args?.length ?? 0);
7980
+ }
7981
+ function forEachSuppliedArgument(cmd, visit) {
7126
7982
  const registered = cmd.registeredArguments ?? [];
7127
7983
  const processed = cmd.processedArgs ?? [];
7128
7984
  for (let i = 0;i < registered.length; i++) {
7129
- add(registered[i].name(), processed[i]);
7985
+ const name = registered[i].name();
7986
+ if (name && processed[i] !== undefined) {
7987
+ visit(name, processed[i], registered[i].argChoices, isDefaultedPositional(cmd, i));
7988
+ }
7989
+ }
7990
+ const choicesByAttribute = new Map;
7991
+ for (const option of cmd.options) {
7992
+ choicesByAttribute.set(option.attributeName(), option.argChoices);
7130
7993
  }
7131
7994
  for (const [key, value] of Object.entries(cmd.opts())) {
7132
- add(key, value);
7995
+ if (key && value !== undefined) {
7996
+ visit(key, value, choicesByAttribute.get(key), isDefaultedOption(cmd, key));
7997
+ }
7133
7998
  }
7134
- return params;
7999
+ }
8000
+ function withheldArgumentValues(cmd) {
8001
+ const values = [];
8002
+ forEachSuppliedArgument(cmd, (_name, value, choices, defaulted) => {
8003
+ if (defaulted) {
8004
+ return;
8005
+ }
8006
+ if (recordableArgValue(value, choices) === TELEMETRY_ARG_VALUE_WITHHELD) {
8007
+ values.push(value);
8008
+ }
8009
+ });
8010
+ return values;
7135
8011
  }
7136
8012
  function deriveCommandPath(cmd) {
7137
8013
  const parts = [];
@@ -7146,7 +8022,7 @@ function deriveCommandPath(cmd) {
7146
8022
  if (parts.length > 1) {
7147
8023
  parts.shift();
7148
8024
  }
7149
- return ["uip", ...parts.filter((p) => p !== "uip")].join(".");
8025
+ return commandTelemetryName(parts);
7150
8026
  }
7151
8027
  function isCliErrorCode(value) {
7152
8028
  return typeof value === "string" && cliErrorCodeValues.has(value);
@@ -7186,68 +8062,77 @@ Command.prototype.trackedAction = function(context, fn, properties) {
7186
8062
  });
7187
8063
  const telemetryName = deriveCommandPath(command);
7188
8064
  const props = typeof properties === "function" ? properties(...args) : properties;
7189
- const requestContext = telemetry.createRequestContext();
7190
- const startTime = performance.now();
7191
- let errorMessage2;
7192
- let fallbackExitCode = EXIT_CODES.Success;
7193
- clearRecordedCommandFailureTelemetry();
7194
- const [error] = await catchError2(telemetry.runWithContext(requestContext, () => {
7195
- const violation = implicitLimitViolation(command);
7196
- if (violation) {
7197
- return Promise.reject(violation);
7198
- }
7199
- return fn(...args);
7200
- }));
7201
- if (error) {
7202
- errorMessage2 = error instanceof Error ? error.message : String(error);
7203
- logger.debug(`[trackedAction] ${telemetryName} failed: ${errorMessage2}`);
7204
- const typed = error;
7205
- const customInstructions = typeof typed.instructions === "string" ? typed.instructions : undefined;
7206
- const customResult = typeof typed.result === "string" && typed.result !== RESULTS.Success && Object.values(RESULTS).includes(typed.result) ? typed.result : undefined;
7207
- const finalResult = customResult ?? RESULTS.Failure;
7208
- const typedErrorCode = typed.errorCode ?? typed.ErrorCode;
7209
- const customErrorCode = isCliErrorCode(typedErrorCode) ? typedErrorCode : undefined;
7210
- const typedRetry = typed.retry ?? typed.Retry;
7211
- const customRetry = isRetryHint(typedRetry) ? typedRetry : undefined;
7212
- const typedContext = typed.context ?? typed.Context;
7213
- const customContext = isErrorContext(typedContext) ? typedContext : undefined;
7214
- const cancellationExitCode = typed.exitCode === 130 || isPromptCancellation(error) ? 130 : undefined;
7215
- fallbackExitCode = cancellationExitCode ?? EXIT_CODES[finalResult];
7216
- OutputFormatter.error({
7217
- Result: finalResult,
7218
- ...customErrorCode ? { ErrorCode: customErrorCode } : {},
7219
- Message: errorMessage2,
7220
- Instructions: customInstructions ?? commandHelpHint(telemetryName),
7221
- ...customRetry ? { Retry: customRetry } : {},
7222
- ...customContext ? { Context: customContext } : {}
8065
+ markCommandStart();
8066
+ const supplied = recordSuppliedArgumentValues(withheldArgumentValues(command));
8067
+ try {
8068
+ const startTime = performance.now();
8069
+ let errorMessage2;
8070
+ let fallbackExitCode = EXIT_CODES.Success;
8071
+ clearRecordedCommandFailureTelemetry();
8072
+ const [error] = await catchError2(ensureInvocationRequestScope(() => {
8073
+ const violation = implicitLimitViolation(command);
8074
+ if (violation) {
8075
+ return Promise.reject(violation);
8076
+ }
8077
+ return fn(...args);
8078
+ }));
8079
+ if (error) {
8080
+ errorMessage2 = error instanceof Error ? error.message : String(error);
8081
+ logger.debug(`[trackedAction] ${telemetryName} failed: ${errorMessage2}`);
8082
+ const typed = error;
8083
+ const customInstructions = typeof typed.instructions === "string" ? typed.instructions : undefined;
8084
+ const customResult = typeof typed.result === "string" && typed.result !== RESULTS.Success && Object.values(RESULTS).includes(typed.result) ? typed.result : undefined;
8085
+ const finalResult = customResult ?? RESULTS.Failure;
8086
+ const typedErrorCode = typed.errorCode ?? typed.ErrorCode;
8087
+ const customErrorCode = isCliErrorCode(typedErrorCode) ? typedErrorCode : undefined;
8088
+ const typedRetry = typed.retry ?? typed.Retry;
8089
+ const customRetry = isRetryHint(typedRetry) ? typedRetry : undefined;
8090
+ const typedContext = typed.context ?? typed.Context;
8091
+ const customContext = isErrorContext(typedContext) ? typedContext : undefined;
8092
+ const cancellationExitCode = typed.exitCode === 130 || isPromptCancellation(error) ? 130 : undefined;
8093
+ fallbackExitCode = cancellationExitCode ?? EXIT_CODES[finalResult];
8094
+ OutputFormatter.error({
8095
+ Result: finalResult,
8096
+ ...customErrorCode ? { ErrorCode: customErrorCode } : {},
8097
+ Message: errorMessage2,
8098
+ Instructions: customInstructions ?? commandHelpHint(telemetryName),
8099
+ ...customRetry ? { Retry: customRetry } : {},
8100
+ ...customContext ? { Context: customContext } : {}
8101
+ });
8102
+ context.exit(fallbackExitCode);
8103
+ }
8104
+ const durationMs = performance.now() - startTime;
8105
+ recordCommandDuration(durationMs);
8106
+ const exitCode = fallbackExitCode === 130 ? fallbackExitCode : exitCodeFromProcess(fallbackExitCode);
8107
+ const recordedFailure = takeRecordedCommandFailureTelemetry();
8108
+ const success = !error && exitCode === 0;
8109
+ const terminalTelemetry = buildCommandTerminalTelemetryProperties({
8110
+ error,
8111
+ exitCode,
8112
+ recordedFailure,
8113
+ pollSignal: context.pollSignal
7223
8114
  });
7224
- context.exit(fallbackExitCode);
7225
- }
7226
- const durationMs = performance.now() - startTime;
7227
- const exitCode = fallbackExitCode === 130 ? fallbackExitCode : exitCodeFromProcess(fallbackExitCode);
7228
- const recordedFailure = takeRecordedCommandFailureTelemetry();
7229
- const success = !error && exitCode === 0;
7230
- const terminalTelemetry = buildCommandTerminalTelemetryProperties({
7231
- error,
7232
- exitCode,
7233
- recordedFailure,
7234
- pollSignal: context.pollSignal
7235
- });
7236
- const commandParams = extractCommandParams(command);
7237
- if (props) {
7238
- for (const key of Object.keys(props)) {
7239
- delete commandParams[`${TELEMETRY_COMMAND_ARG_PREFIX}${key}`];
7240
- }
7241
- }
7242
- const baseProperties = redactProperties({
7243
- ...commandParams,
7244
- ...props,
7245
- ...buildCommandTelemetryAttribution(telemetryName, process.env.UIPATH_SKILL),
7246
- command: "true",
7247
- ...terminalTelemetry,
7248
- ...errorMessage2 ? { errorMessage: errorMessage2 } : {}
7249
- });
7250
- telemetry.trackRequestResult(telemetryName, durationMs, success, baseProperties, requestContext);
8115
+ if (terminalTelemetry.error_class === "internal" && error) {
8116
+ telemetry.trackException(error instanceof Error ? error : new Error(String(error)), { command_name: telemetryName }, getInvocationRequestContext());
8117
+ }
8118
+ const commandParams = extractCommandParams(command);
8119
+ if (props) {
8120
+ for (const key of Object.keys(props)) {
8121
+ delete commandParams[`${TELEMETRY_COMMAND_ARG_PREFIX}${key}`];
8122
+ }
8123
+ }
8124
+ const baseProperties = redactProperties({
8125
+ ...commandParams,
8126
+ ...props,
8127
+ ...buildCommandTelemetryAttribution(telemetryName, process.env.UIPATH_SKILL),
8128
+ command: "true",
8129
+ ...terminalTelemetry,
8130
+ ...errorMessage2 ? { errorMessage: errorMessage2 } : {}
8131
+ });
8132
+ emitInvocationRequest(telemetryName, success, baseProperties);
8133
+ } finally {
8134
+ releaseSuppliedArgumentValues(supplied);
8135
+ }
7251
8136
  });
7252
8137
  };
7253
8138
  // ../../common/src/completer.ts
@@ -7257,6 +8142,204 @@ var guardInstalledSlot = singleton("ConsoleGuardInstalled");
7257
8142
  var savedOriginalsSlot = singleton("ConsoleGuardOriginals");
7258
8143
  // ../../common/src/constants.ts
7259
8144
  var DEFAULT_AUTH_TIMEOUT_MS2 = 5 * 60 * 1000;
8145
+ // ../../common/src/entity-name-rules.ts
8146
+ var RESERVED_SQL_KEYWORDS_LOWER = new Set(["group", "order"]);
8147
+ var RESERVED_FIELD_NAMES_LOWER = new Set([
8148
+ "id",
8149
+ "createdby",
8150
+ "createtime",
8151
+ "updatedby",
8152
+ "updatetime",
8153
+ "recordowner",
8154
+ "version"
8155
+ ]);
8156
+ var RESERVED_KEYWORDS_LOWER = new Set([
8157
+ "abstract",
8158
+ "as",
8159
+ "base",
8160
+ "bool",
8161
+ "break",
8162
+ "byte",
8163
+ "case",
8164
+ "catch",
8165
+ "char",
8166
+ "checked",
8167
+ "class",
8168
+ "const",
8169
+ "continue",
8170
+ "decimal",
8171
+ "default",
8172
+ "delegate",
8173
+ "do",
8174
+ "double",
8175
+ "else",
8176
+ "enum",
8177
+ "event",
8178
+ "explicit",
8179
+ "extern",
8180
+ "false",
8181
+ "finally",
8182
+ "fixed",
8183
+ "float",
8184
+ "for",
8185
+ "foreach",
8186
+ "goto",
8187
+ "if",
8188
+ "implicit",
8189
+ "in",
8190
+ "int",
8191
+ "interface",
8192
+ "internal",
8193
+ "is",
8194
+ "lock",
8195
+ "long",
8196
+ "namespace",
8197
+ "new",
8198
+ "null",
8199
+ "object",
8200
+ "operator",
8201
+ "out",
8202
+ "override",
8203
+ "params",
8204
+ "private",
8205
+ "protected",
8206
+ "public",
8207
+ "readonly",
8208
+ "ref",
8209
+ "return",
8210
+ "sbyte",
8211
+ "sealed",
8212
+ "short",
8213
+ "sizeof",
8214
+ "stackalloc",
8215
+ "static",
8216
+ "string",
8217
+ "struct",
8218
+ "switch",
8219
+ "this",
8220
+ "throw",
8221
+ "true",
8222
+ "try",
8223
+ "typeof",
8224
+ "uint",
8225
+ "ulong",
8226
+ "unchecked",
8227
+ "unsafe",
8228
+ "ushort",
8229
+ "using",
8230
+ "virtual",
8231
+ "void",
8232
+ "volatile",
8233
+ "while",
8234
+ "addhandler",
8235
+ "addressof",
8236
+ "alias",
8237
+ "and",
8238
+ "andalso",
8239
+ "boolean",
8240
+ "byref",
8241
+ "byval",
8242
+ "call",
8243
+ "cbool",
8244
+ "cbyte",
8245
+ "cchar",
8246
+ "cdate",
8247
+ "cdbl",
8248
+ "cdec",
8249
+ "cint",
8250
+ "clng",
8251
+ "cobj",
8252
+ "csbyte",
8253
+ "cshort",
8254
+ "csng",
8255
+ "cstr",
8256
+ "ctype",
8257
+ "cuint",
8258
+ "culng",
8259
+ "cushort",
8260
+ "date",
8261
+ "declare",
8262
+ "dim",
8263
+ "directcast",
8264
+ "each",
8265
+ "elseif",
8266
+ "end",
8267
+ "endif",
8268
+ "erase",
8269
+ "error",
8270
+ "exit",
8271
+ "friend",
8272
+ "function",
8273
+ "get",
8274
+ "gettype",
8275
+ "getxmlnamespace",
8276
+ "global",
8277
+ "gosub",
8278
+ "goto",
8279
+ "handles",
8280
+ "implements",
8281
+ "imports",
8282
+ "inherits",
8283
+ "integer",
8284
+ "isnot",
8285
+ "let",
8286
+ "lib",
8287
+ "like",
8288
+ "loop",
8289
+ "me",
8290
+ "mod",
8291
+ "module",
8292
+ "mustinherit",
8293
+ "mustoverride",
8294
+ "mybase",
8295
+ "myclass",
8296
+ "narrowing",
8297
+ "next",
8298
+ "not",
8299
+ "nothing",
8300
+ "notinheritable",
8301
+ "notoverridable",
8302
+ "of",
8303
+ "on",
8304
+ "option",
8305
+ "optional",
8306
+ "or",
8307
+ "orelse",
8308
+ "overloads",
8309
+ "overridable",
8310
+ "overrides",
8311
+ "paramarray",
8312
+ "partial",
8313
+ "property",
8314
+ "raiseevent",
8315
+ "redim",
8316
+ "rem",
8317
+ "removehandler",
8318
+ "resume",
8319
+ "select",
8320
+ "set",
8321
+ "shadows",
8322
+ "shared",
8323
+ "single",
8324
+ "step",
8325
+ "stop",
8326
+ "structure",
8327
+ "sub",
8328
+ "synclock",
8329
+ "then",
8330
+ "to",
8331
+ "trycast",
8332
+ "uinteger",
8333
+ "ushort",
8334
+ "variant",
8335
+ "wend",
8336
+ "when",
8337
+ "widening",
8338
+ "with",
8339
+ "withevents",
8340
+ "writeonly",
8341
+ "xor"
8342
+ ]);
7260
8343
  // ../../common/src/host-global-options.ts
7261
8344
  var HOST_GLOBAL_OPTIONS_WITH_VALUE = [
7262
8345
  "--output",
@@ -7341,8 +8424,8 @@ var withLoginValidity = (cmd) => {
7341
8424
  return cmd;
7342
8425
  };
7343
8426
  async function loadJsonFile(file, typeLabel) {
7344
- const fs = getFileSystem();
7345
- const [readErr, content] = await catchError2(fs.readFile(file, "utf-8"));
8427
+ const fs2 = getFileSystem();
8428
+ const [readErr, content] = await catchError2(fs2.readFile(file, "utf-8"));
7346
8429
  if (readErr || content === null) {
7347
8430
  return [
7348
8431
  {
@@ -8463,4 +9546,4 @@ var registerCommands = async (program2) => {
8463
9546
 
8464
9547
  export { Command, metadata, registerCommands };
8465
9548
 
8466
- //# debugId=1B5DA10D030248D164756E2164756E21
9549
+ //# debugId=41427B55E35A133F64756E2164756E21