@uipath/maestro-sdk 0.1.5 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +1017 -912
  2. package/package.json +35 -37
package/dist/index.js CHANGED
@@ -4,25 +4,43 @@ var __getProtoOf = Object.getPrototypeOf;
4
4
  var __defProp = Object.defineProperty;
5
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
6
  var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ function __accessProp(key) {
8
+ return this[key];
9
+ }
10
+ var __toESMCache_node;
11
+ var __toESMCache_esm;
7
12
  var __toESM = (mod, isNodeMode, target) => {
13
+ var canCache = mod != null && typeof mod === "object";
14
+ if (canCache) {
15
+ var cache = isNodeMode ? __toESMCache_node ??= new WeakMap : __toESMCache_esm ??= new WeakMap;
16
+ var cached = cache.get(mod);
17
+ if (cached)
18
+ return cached;
19
+ }
8
20
  target = mod != null ? __create(__getProtoOf(mod)) : {};
9
21
  const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
10
22
  for (let key of __getOwnPropNames(mod))
11
23
  if (!__hasOwnProp.call(to, key))
12
24
  __defProp(to, key, {
13
- get: () => mod[key],
25
+ get: __accessProp.bind(mod, key),
14
26
  enumerable: true
15
27
  });
28
+ if (canCache)
29
+ cache.set(mod, to);
16
30
  return to;
17
31
  };
18
32
  var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
33
+ var __returnValue = (v) => v;
34
+ function __exportSetter(name, newValue) {
35
+ this[name] = __returnValue.bind(null, newValue);
36
+ }
19
37
  var __export = (target, all) => {
20
38
  for (var name in all)
21
39
  __defProp(target, name, {
22
40
  get: all[name],
23
41
  enumerable: true,
24
42
  configurable: true,
25
- set: (newValue) => all[name] = () => newValue
43
+ set: __exportSetter.bind(all, name)
26
44
  });
27
45
  };
28
46
  var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
@@ -38,6 +56,12 @@ function catchError(fnOrPromise) {
38
56
  }
39
57
  try {
40
58
  const result = fnOrPromise();
59
+ if (result instanceof Promise) {
60
+ return result.then((data) => [undefined, data]).catch((error) => [
61
+ error instanceof Error ? error : new Error(String(error)),
62
+ undefined
63
+ ]);
64
+ }
41
65
  return [undefined, result];
42
66
  } catch (error) {
43
67
  return [
@@ -6692,33 +6716,60 @@ var init_js_yaml = __esm(() => {
6692
6716
  safeDump = renamed("safeDump", "dump");
6693
6717
  });
6694
6718
 
6695
- // ../common/src/output-context.ts
6696
- function getSharedStorage() {
6697
- const g = globalThis;
6698
- if (!g[STORAGE_KEY]) {
6699
- try {
6700
- const { AsyncLocalStorage } = __require("node:async_hooks");
6701
- g[STORAGE_KEY] = new AsyncLocalStorage;
6702
- } catch {
6703
- g[STORAGE_KEY] = {
6704
- getStore: () => {
6705
- return;
6706
- },
6707
- run: (_store, fn) => fn()
6708
- };
6719
+ // ../common/src/singleton.ts
6720
+ function singleton(ctorOrName) {
6721
+ const name = typeof ctorOrName === "string" ? ctorOrName : ctorOrName.name;
6722
+ const key = Symbol.for(PREFIX + name);
6723
+ return {
6724
+ get(fallback) {
6725
+ return _g[key] ?? fallback;
6726
+ },
6727
+ set(value) {
6728
+ _g[key] = value;
6729
+ },
6730
+ clear() {
6731
+ delete _g[key];
6732
+ },
6733
+ getOrInit(factory, guard) {
6734
+ const existing = _g[key];
6735
+ if (existing != null && typeof existing === "object") {
6736
+ if (!guard || guard(existing)) {
6737
+ return existing;
6738
+ }
6739
+ }
6740
+ const instance = factory();
6741
+ _g[key] = instance;
6742
+ return instance;
6709
6743
  }
6744
+ };
6745
+ }
6746
+ var PREFIX = "@uipath/common/", _g;
6747
+ var init_singleton = __esm(() => {
6748
+ _g = globalThis;
6749
+ });
6750
+
6751
+ // ../common/src/output-context.ts
6752
+ function createStorage() {
6753
+ const [error, mod2] = catchError(() => __require("node:async_hooks"));
6754
+ if (error) {
6755
+ return {
6756
+ getStore: () => {
6757
+ return;
6758
+ },
6759
+ run: (_store, fn) => fn()
6760
+ };
6710
6761
  }
6711
- return g[STORAGE_KEY];
6762
+ return new mod2.AsyncLocalStorage;
6712
6763
  }
6713
6764
  function getOutputSink() {
6714
- const g = globalThis;
6715
- return outputStorage.getStore() ?? g[GLOBAL_SINK_KEY] ?? CONSOLE_FALLBACK;
6765
+ return outputStorage.getStore() ?? sinkSlot.get() ?? CONSOLE_FALLBACK;
6716
6766
  }
6717
- var STORAGE_KEY, GLOBAL_SINK_KEY, outputStorage, CONSOLE_FALLBACK;
6767
+ var storageSingleton, sinkSlot, outputStorage, CONSOLE_FALLBACK;
6718
6768
  var init_output_context = __esm(() => {
6719
- STORAGE_KEY = Symbol.for("@uipath/common/output-storage");
6720
- GLOBAL_SINK_KEY = Symbol.for("@uipath/common/global-sink");
6721
- outputStorage = getSharedStorage();
6769
+ init_singleton();
6770
+ storageSingleton = singleton("OutputStorage");
6771
+ sinkSlot = singleton("OutputSink");
6772
+ outputStorage = storageSingleton.getOrInit(createStorage, (v) => ("getStore" in v));
6722
6773
  CONSOLE_FALLBACK = {
6723
6774
  writeOut: (str2) => process.stdout.write(str2),
6724
6775
  writeErr: (str2) => process.stderr.write(str2),
@@ -6735,237 +6786,218 @@ var init_output_context = __esm(() => {
6735
6786
  import { appendFileSync, mkdirSync, writeFileSync } from "node:fs";
6736
6787
  import { dirname } from "node:path";
6737
6788
  function setGlobalLogFilePath(path) {
6738
- globalThis[GLOBAL_KEY] = path;
6789
+ logFilePathSlot.set(path);
6739
6790
  }
6740
6791
  function getGlobalLogFilePath() {
6741
- return globalThis[GLOBAL_KEY] ?? "";
6792
+ return logFilePathSlot.get("");
6742
6793
  }
6743
-
6744
- class SimpleLogger {
6745
- static instance;
6746
- level;
6747
- logFilePath;
6748
- fileLoggingEnabled;
6749
- constructor() {
6750
- this.level = SimpleLogger.resolveLevel();
6751
- this.logFilePath = "";
6752
- this.fileLoggingEnabled = false;
6753
- }
6754
- static getInstance() {
6755
- if (!SimpleLogger.instance) {
6756
- SimpleLogger.instance = new SimpleLogger;
6794
+ function getLogFilePath() {
6795
+ return logger.getLogFilePath();
6796
+ }
6797
+ var logFilePathSlot, DEFAULT_LOG_LEVEL = 3 /* ERROR */, SimpleLogger, loggerSingleton, logger;
6798
+ var init_logger = __esm(() => {
6799
+ init_output_context();
6800
+ init_singleton();
6801
+ logFilePathSlot = singleton("logFilePath");
6802
+ SimpleLogger = class SimpleLogger {
6803
+ __brand = "SimpleLogger";
6804
+ level;
6805
+ logFilePath;
6806
+ fileLoggingEnabled;
6807
+ constructor() {
6808
+ this.level = SimpleLogger.resolveLevel();
6809
+ this.logFilePath = "";
6810
+ this.fileLoggingEnabled = false;
6757
6811
  }
6758
- return SimpleLogger.instance;
6759
- }
6760
- static resetInstance() {
6761
- SimpleLogger.instance = undefined;
6762
- }
6763
- static resolveLevel() {
6764
- if (typeof process !== "undefined" && process.env?.UIPCLI_LOG_LEVEL) {
6765
- const parsed = SimpleLogger.parseLevel(process.env.UIPCLI_LOG_LEVEL);
6766
- if (parsed !== undefined)
6767
- return parsed;
6812
+ static getInstance() {
6813
+ return loggerSingleton.getOrInit(() => new SimpleLogger, (v) => ("__brand" in v) && v.__brand === "SimpleLogger");
6768
6814
  }
6769
- if (typeof process !== "undefined" && process.env?.DEBUG) {
6770
- return 0 /* DEBUG */;
6815
+ static resetInstance() {
6816
+ loggerSingleton.clear();
6771
6817
  }
6772
- try {
6773
- if (typeof localStorage !== "undefined" && localStorage.getItem("debug")) {
6774
- return 0 /* DEBUG */;
6818
+ static isNode = typeof process !== "undefined" && !!process.versions?.node;
6819
+ static resolveLevel() {
6820
+ if (SimpleLogger.isNode) {
6821
+ const explicitLevel = SimpleLogger.parseLevel(process.env?.UIPCLI_LOG_LEVEL ?? "");
6822
+ if (explicitLevel !== undefined)
6823
+ return explicitLevel;
6824
+ const debugVal = process.env?.DEBUG;
6825
+ if (debugVal === "true" || debugVal === "1") {
6826
+ return 0 /* DEBUG */;
6827
+ }
6828
+ return DEFAULT_LOG_LEVEL;
6775
6829
  }
6776
- } catch {}
6777
- return 3 /* ERROR */;
6778
- }
6779
- static parseLevel(value) {
6780
- switch (value.toLowerCase()) {
6781
- case "debug":
6830
+ const [localStorageError, hasDebug] = catchError(() => typeof localStorage !== "undefined" && !!localStorage.getItem("debug"));
6831
+ if (!localStorageError && hasDebug) {
6782
6832
  return 0 /* DEBUG */;
6783
- case "info":
6784
- return 1 /* INFO */;
6785
- case "warn":
6786
- return 2 /* WARN */;
6787
- case "error":
6788
- return 3 /* ERROR */;
6789
- default:
6790
- return;
6833
+ }
6834
+ return DEFAULT_LOG_LEVEL;
6835
+ }
6836
+ static parseLevel(value) {
6837
+ switch (value.toLowerCase()) {
6838
+ case "debug":
6839
+ return 0 /* DEBUG */;
6840
+ case "info":
6841
+ return 1 /* INFO */;
6842
+ case "warn":
6843
+ return 2 /* WARN */;
6844
+ case "error":
6845
+ return 3 /* ERROR */;
6846
+ default:
6847
+ return;
6848
+ }
6791
6849
  }
6792
- }
6793
- format(message, args) {
6794
- if (args.length === 0)
6795
- return `${message}
6850
+ format(message, args) {
6851
+ if (args.length === 0)
6852
+ return `${message}
6796
6853
  `;
6797
- return `${message} ${args.map(String).join(" ")}
6854
+ return `${message} ${args.map(String).join(" ")}
6798
6855
  `;
6799
- }
6800
- isFileLoggingActive() {
6801
- return this.fileLoggingEnabled || !!getGlobalLogFilePath();
6802
- }
6803
- writeToFile(formatted) {
6804
- const path = this.logFilePath || getGlobalLogFilePath();
6805
- if (!path)
6806
- return;
6807
- try {
6856
+ }
6857
+ isFileLoggingActive() {
6858
+ return this.fileLoggingEnabled || !!getGlobalLogFilePath();
6859
+ }
6860
+ writeToFile(formatted) {
6861
+ const path = this.logFilePath || getGlobalLogFilePath();
6862
+ if (!path)
6863
+ return;
6808
6864
  const timestamp2 = new Date().toISOString();
6809
- appendFileSync(path, `${timestamp2} ${formatted}`);
6810
- } catch {}
6811
- }
6812
- debug(message, ...args) {
6813
- if (this.level > 0 /* DEBUG */)
6814
- return;
6815
- const formatted = this.format(`[DEBUG] ${message}`, args);
6816
- if (this.isFileLoggingActive()) {
6817
- this.writeToFile(formatted);
6818
- } else {
6819
- getOutputSink().writeErr(formatted);
6865
+ catchError(() => appendFileSync(path, `${timestamp2} ${formatted}`));
6820
6866
  }
6821
- }
6822
- info(message, ...args) {
6823
- if (this.level > 1 /* INFO */)
6824
- return;
6825
- const formatted = this.format(message, args);
6826
- if (this.isFileLoggingActive()) {
6827
- this.writeToFile(formatted);
6828
- } else {
6829
- getOutputSink().writeErr(formatted);
6867
+ debug(message, ...args) {
6868
+ if (this.level > 0 /* DEBUG */)
6869
+ return;
6870
+ const formatted = this.format(`[DEBUG] ${message}`, args);
6871
+ if (this.isFileLoggingActive()) {
6872
+ this.writeToFile(formatted);
6873
+ } else {
6874
+ getOutputSink().writeErr(formatted);
6875
+ }
6830
6876
  }
6831
- }
6832
- warn(message, ...args) {
6833
- if (this.level > 2 /* WARN */)
6834
- return;
6835
- const formatted = this.format(`[WARN] ${message}`, args);
6836
- if (this.isFileLoggingActive()) {
6837
- this.writeToFile(formatted);
6838
- } else {
6839
- getOutputSink().writeErr(formatted);
6877
+ info(message, ...args) {
6878
+ if (this.level > 1 /* INFO */)
6879
+ return;
6880
+ const formatted = this.format(message, args);
6881
+ if (this.isFileLoggingActive()) {
6882
+ this.writeToFile(formatted);
6883
+ } else {
6884
+ getOutputSink().writeErr(formatted);
6885
+ }
6840
6886
  }
6841
- }
6842
- error(message, ...args) {
6843
- if (this.level > 3 /* ERROR */)
6844
- return;
6845
- const formatted = this.format(`[ERROR] ${message}`, args);
6846
- if (this.isFileLoggingActive()) {
6847
- this.writeToFile(formatted);
6848
- } else {
6849
- getOutputSink().writeErr(formatted);
6887
+ warn(message, ...args) {
6888
+ if (this.level > 2 /* WARN */)
6889
+ return;
6890
+ const formatted = this.format(`[WARN] ${message}`, args);
6891
+ if (this.isFileLoggingActive()) {
6892
+ this.writeToFile(formatted);
6893
+ } else {
6894
+ getOutputSink().writeErr(formatted);
6895
+ }
6850
6896
  }
6851
- }
6852
- getLevel() {
6853
- return this.level;
6854
- }
6855
- setLevel(level) {
6856
- this.level = level;
6857
- }
6858
- setFileLogging(enabled) {
6859
- this.fileLoggingEnabled = enabled;
6860
- if (!enabled) {
6861
- this.logFilePath = "";
6862
- setGlobalLogFilePath("");
6897
+ error(message, ...args) {
6898
+ if (this.level > 3 /* ERROR */)
6899
+ return;
6900
+ const formatted = this.format(`[ERROR] ${message}`, args);
6901
+ if (this.isFileLoggingActive()) {
6902
+ this.writeToFile(formatted);
6903
+ } else {
6904
+ getOutputSink().writeErr(formatted);
6905
+ }
6863
6906
  }
6864
- }
6865
- setLogFile(path) {
6866
- this.logFilePath = path;
6867
- setGlobalLogFilePath(path);
6868
- if (!path)
6869
- return;
6870
- try {
6871
- mkdirSync(dirname(path), { recursive: true });
6872
- writeFileSync(path, "");
6873
- this.fileLoggingEnabled = true;
6874
- } catch {
6875
- this.fileLoggingEnabled = false;
6907
+ getLevel() {
6908
+ return this.level;
6876
6909
  }
6877
- }
6878
- getLogFilePath() {
6879
- return this.logFilePath || getGlobalLogFilePath();
6880
- }
6881
- handleLog = (logMessage) => {
6882
- const parts = [];
6883
- if (logMessage.source) {
6884
- parts.push(`[${logMessage.source}]`);
6910
+ setLevel(level) {
6911
+ this.level = level;
6885
6912
  }
6886
- if (logMessage.sourceTarget) {
6887
- parts.push(`[${logMessage.sourceTarget}]`);
6913
+ setFileLogging(enabled) {
6914
+ this.fileLoggingEnabled = enabled;
6915
+ if (!enabled) {
6916
+ this.logFilePath = "";
6917
+ setGlobalLogFilePath("");
6918
+ }
6888
6919
  }
6889
- parts.push(logMessage.message);
6890
- const msg = parts.join(" ");
6891
- switch (logMessage.logLevel) {
6892
- case "Debug":
6893
- this.debug(msg);
6894
- break;
6895
- case "Warning":
6896
- this.warn(msg);
6897
- break;
6898
- case "Error":
6899
- this.error(msg);
6900
- break;
6901
- default:
6902
- this.info(msg);
6903
- break;
6920
+ setLogFile(path) {
6921
+ this.logFilePath = path;
6922
+ setGlobalLogFilePath(path);
6923
+ if (!path)
6924
+ return;
6925
+ const [error] = catchError(() => {
6926
+ mkdirSync(dirname(path), { recursive: true });
6927
+ writeFileSync(path, "");
6928
+ });
6929
+ this.fileLoggingEnabled = !error;
6904
6930
  }
6931
+ getLogFilePath() {
6932
+ return this.logFilePath || getGlobalLogFilePath();
6933
+ }
6934
+ handleLog = (logMessage) => {
6935
+ const parts = [];
6936
+ if (logMessage.source) {
6937
+ parts.push(`[${logMessage.source}]`);
6938
+ }
6939
+ if (logMessage.sourceTarget) {
6940
+ parts.push(`[${logMessage.sourceTarget}]`);
6941
+ }
6942
+ parts.push(logMessage.message);
6943
+ const msg = parts.join(" ");
6944
+ switch (logMessage.logLevel) {
6945
+ case "Debug":
6946
+ this.debug(msg);
6947
+ break;
6948
+ case "Warning":
6949
+ this.warn(msg);
6950
+ break;
6951
+ case "Error":
6952
+ this.error(msg);
6953
+ break;
6954
+ default:
6955
+ this.info(msg);
6956
+ break;
6957
+ }
6958
+ };
6905
6959
  };
6906
- }
6907
- function getLogFilePath() {
6908
- return logger.getLogFilePath();
6909
- }
6910
- var GLOBAL_KEY = "__uipcli_log_file_path__", logger;
6911
- var init_logger = __esm(() => {
6912
- init_output_context();
6960
+ loggerSingleton = singleton(SimpleLogger);
6913
6961
  logger = SimpleLogger.getInstance();
6914
6962
  });
6915
6963
 
6916
6964
  // ../common/src/output-format-context.ts
6917
6965
  function getOutputFormat() {
6918
- return globalThis[FORMAT_KEY] ?? "table";
6966
+ return formatSlot.get("table");
6919
6967
  }
6920
6968
  function getOutputFilter() {
6921
- return globalThis[FILTER_KEY];
6969
+ return filterSlot.get();
6922
6970
  }
6923
- var FORMAT_KEY, FILTER_KEY;
6971
+ var formatSlot, filterSlot;
6924
6972
  var init_output_format_context = __esm(() => {
6925
- FORMAT_KEY = Symbol.for("@uipath/common/output-format");
6926
- FILTER_KEY = Symbol.for("@uipath/common/output-filter");
6973
+ init_singleton();
6974
+ formatSlot = singleton("OutputFormat");
6975
+ filterSlot = singleton("OutputFilter");
6927
6976
  });
6928
-
6929
- // ../../node_modules/@uipath/telemetry/dist/node.js
6930
- import { AsyncLocalStorage } from "async_hooks";
6931
- function node_context_storage_define_property(obj, key, value) {
6932
- if (key in obj)
6933
- Object.defineProperty(obj, key, {
6934
- value,
6935
- enumerable: true,
6936
- configurable: true,
6937
- writable: true
6938
- });
6939
- else
6940
- obj[key] = value;
6941
- return obj;
6942
- }
6977
+ // ../telemetry/src/contextstorage/adapters/node-context-storage.ts
6978
+ import { AsyncLocalStorage } from "node:async_hooks";
6943
6979
 
6944
6980
  class NodeContextStorage {
6981
+ storage = new AsyncLocalStorage;
6945
6982
  run(context, fn) {
6946
6983
  return this.storage.run(context, fn);
6947
6984
  }
6948
6985
  getContext() {
6949
6986
  return this.storage.getStore();
6950
6987
  }
6951
- constructor() {
6952
- node_context_storage_define_property(this, "storage", new AsyncLocalStorage);
6953
- }
6954
- }
6955
- function telemetry_service_define_property(obj, key, value) {
6956
- if (key in obj)
6957
- Object.defineProperty(obj, key, {
6958
- value,
6959
- enumerable: true,
6960
- configurable: true,
6961
- writable: true
6962
- });
6963
- else
6964
- obj[key] = value;
6965
- return obj;
6966
6988
  }
6989
+ var init_node_context_storage = () => {};
6967
6990
 
6991
+ // ../telemetry/src/telemetry-service.ts
6968
6992
  class TelemetryService {
6993
+ telemetryProvider;
6994
+ contextStorage;
6995
+ operationId;
6996
+ defaultProperties;
6997
+ constructor(telemetryProvider, contextStorage) {
6998
+ this.telemetryProvider = telemetryProvider;
6999
+ this.contextStorage = contextStorage;
7000
+ }
6969
7001
  setOperationId(operationId) {
6970
7002
  this.operationId = operationId;
6971
7003
  }
@@ -7000,18 +7032,16 @@ class TelemetryService {
7000
7032
  } catch (error) {
7001
7033
  const durationMs = performance.now() - startTime;
7002
7034
  const err = error instanceof Error ? error : new Error(String(error));
7003
- const enrichedProperties = this.enrichPropertiesWithContext({
7004
- ...properties,
7005
- errorMessage: err.message
7006
- }, context);
7035
+ const enrichedProperties = this.enrichPropertiesWithContext({ ...properties, errorMessage: err.message }, context);
7007
7036
  await this.telemetryProvider.trackRequest(name, durationMs, false, enrichedProperties);
7008
7037
  throw error;
7009
7038
  }
7010
7039
  }
7011
7040
  async trackDependencyOperation(name, type2, fn, properties) {
7012
7041
  const parentContext = this.getCurrentContext();
7013
- if (!parentContext)
7042
+ if (!parentContext) {
7014
7043
  throw new Error("trackDependencyOperation must be called within a trackRequest block.");
7044
+ }
7015
7045
  const childContext = {
7016
7046
  operationId: parentContext.operationId,
7017
7047
  parentId: parentContext.id,
@@ -7027,10 +7057,7 @@ class TelemetryService {
7027
7057
  } catch (error) {
7028
7058
  const durationMs = performance.now() - startTime;
7029
7059
  const err = error instanceof Error ? error : new Error(String(error));
7030
- const enrichedProperties = this.enrichPropertiesWithContext({
7031
- ...properties,
7032
- errorMessage: err.message
7033
- }, childContext);
7060
+ const enrichedProperties = this.enrichPropertiesWithContext({ ...properties, errorMessage: err.message }, childContext);
7034
7061
  await this.telemetryProvider.trackDependency(name, type2, durationMs, false, enrichedProperties);
7035
7062
  throw error;
7036
7063
  }
@@ -7048,16 +7075,12 @@ class TelemetryService {
7048
7075
  generateId() {
7049
7076
  return crypto.randomUUID().replaceAll("-", "");
7050
7077
  }
7051
- constructor(telemetryProvider, contextStorage) {
7052
- telemetry_service_define_property(this, "telemetryProvider", undefined);
7053
- telemetry_service_define_property(this, "contextStorage", undefined);
7054
- telemetry_service_define_property(this, "operationId", undefined);
7055
- telemetry_service_define_property(this, "defaultProperties", undefined);
7056
- this.telemetryProvider = telemetryProvider;
7057
- this.contextStorage = contextStorage;
7058
- }
7059
7078
  }
7060
- var init_node = () => {};
7079
+
7080
+ // ../telemetry/src/node.ts
7081
+ var init_node = __esm(() => {
7082
+ init_node_context_storage();
7083
+ });
7061
7084
 
7062
7085
  // ../common/src/registry.ts
7063
7086
  import { execFileSync } from "node:child_process";
@@ -7065,16 +7088,15 @@ function readRegistryValue(keyPath, valueName) {
7065
7088
  if (process.platform !== "win32") {
7066
7089
  return "";
7067
7090
  }
7068
- try {
7069
- const output = execFileSync("reg", ["query", keyPath, "/v", valueName], {
7070
- encoding: "utf-8",
7071
- stdio: ["pipe", "pipe", "pipe"]
7072
- });
7073
- const match = output.match(new RegExp(`${valueName}\\s+REG_SZ\\s+(.+)`));
7074
- return match?.[1]?.trim() ?? "";
7075
- } catch {
7091
+ const [error, output] = catchError(() => execFileSync("reg", ["query", keyPath, "/v", valueName], {
7092
+ encoding: "utf-8",
7093
+ stdio: ["pipe", "pipe", "pipe"]
7094
+ }));
7095
+ if (error) {
7076
7096
  return "";
7077
7097
  }
7098
+ const match = output.match(new RegExp(`${valueName}\\s+REG_SZ\\s+(.+)`));
7099
+ return match?.[1]?.trim() ?? "";
7078
7100
  }
7079
7101
  var init_registry = () => {};
7080
7102
 
@@ -7091,7 +7113,7 @@ class LoggerTelemetryProvider {
7091
7113
  };
7092
7114
  }
7093
7115
  async trackEvent(eventName, properties) {
7094
- logger.info(formatMessage("Event", eventName, this.enrich(properties)));
7116
+ logger.debug(formatMessage("Event", eventName, this.enrich(properties)));
7095
7117
  }
7096
7118
  async trackException(error, properties) {
7097
7119
  logger.error(formatMessage("Exception", error.message, this.enrich({
@@ -7100,7 +7122,7 @@ class LoggerTelemetryProvider {
7100
7122
  })));
7101
7123
  }
7102
7124
  async trackRequest(name, duration, success, properties) {
7103
- logger.info(formatMessage("Request", name, this.enrich({
7125
+ logger.debug(formatMessage("Request", name, this.enrich({
7104
7126
  ...properties,
7105
7127
  duration: `${duration}ms`,
7106
7128
  success
@@ -7133,30 +7155,22 @@ var init_logger_telemetry_provider = __esm(() => {
7133
7155
  // ../common/src/node-appinsights-telemetry-provider.ts
7134
7156
  function setGlobalTelemetryProperties(properties) {
7135
7157
  const existing = getGlobalTelemetryProperties();
7136
- globalThis[GLOBAL_TELEMETRY_PROPS_KEY] = {
7137
- ...existing,
7138
- ...properties
7139
- };
7158
+ telemetryPropsSlot.set({ ...existing, ...properties });
7140
7159
  }
7141
7160
  function getGlobalTelemetryProperties() {
7142
- return globalThis[GLOBAL_TELEMETRY_PROPS_KEY];
7161
+ return telemetryPropsSlot.get();
7143
7162
  }
7144
- var GLOBAL_TELEMETRY_PROPS_KEY = "__uipcli_telemetry_default_props__";
7163
+ var telemetryPropsSlot, providerSlot;
7145
7164
  var init_node_appinsights_telemetry_provider = __esm(() => {
7146
7165
  init_logger();
7166
+ init_singleton();
7167
+ telemetryPropsSlot = singleton("TelemetryDefaultProps");
7168
+ providerSlot = singleton("TelemetryProvider");
7147
7169
  });
7148
7170
 
7149
7171
  // ../common/src/telemetry.ts
7150
- function getOrCreateSessionId() {
7151
- const existing = globalThis[GLOBAL_SESSION_ID_KEY];
7152
- if (typeof existing === "string")
7153
- return existing;
7154
- const id = crypto.randomUUID();
7155
- globalThis[GLOBAL_SESSION_ID_KEY] = id;
7156
- return id;
7157
- }
7158
7172
  function getGlobalTelemetryInstance() {
7159
- const existing = globalThis[GLOBAL_TELEMETRY_INSTANCE_KEY];
7173
+ const existing = telemetryInstanceSlot.get();
7160
7174
  if (existing && typeof existing === "object" && "trackEvent" in existing && typeof existing.trackEvent === "function") {
7161
7175
  return existing;
7162
7176
  }
@@ -7171,14 +7185,15 @@ function getTelemetryInstance() {
7171
7185
  }
7172
7186
  return _localTelemetryInstance;
7173
7187
  }
7174
- var GLOBAL_SESSION_ID_KEY = "__uipcli_telemetry_session_id__", GLOBAL_TELEMETRY_INSTANCE_KEY = "__uipcli_telemetry_instance__", sessionId, DEFAULT_AI_CONNECTION_STRING, _localTelemetryInstance, telemetry;
7188
+ var telemetryInstanceSlot, DEFAULT_AI_CONNECTION_STRING, _localTelemetryInstance, telemetry;
7175
7189
  var init_telemetry = __esm(() => {
7176
7190
  init_node();
7177
7191
  init_logger();
7178
7192
  init_logger_telemetry_provider();
7179
7193
  init_node_appinsights_telemetry_provider();
7180
- sessionId = getOrCreateSessionId();
7181
- DEFAULT_AI_CONNECTION_STRING = Buffer.from("SW5zdHJ1bWVudGF0aW9uS2V5PTYwNjQ5ZGY3LTk4ZmYtNDk2My1iMWQ0LWE3MGQwMzA2MTc0ZjtJbmdlc3Rpb25FbmRwb2ludD1odHRwczovL3dlc3RldXJvcGUtNS5pbi5hcHBsaWNhdGlvbmluc2lnaHRzLmF6dXJlLmNvbS87TGl2ZUVuZHBvaW50PWh0dHBzOi8vd2VzdGV1cm9wZS5saXZlZGlhZ25vc3RpY3MubW9uaXRvci5henVyZS5jb20vO0FwcGxpY2F0aW9uSWQ9ZjlmYWNiNTctM2QxMS00Njc4LWJiOGItMDI0YmJhYmM1Y2Fl", "base64").toString("utf-8");
7194
+ init_singleton();
7195
+ telemetryInstanceSlot = singleton("TelemetryService");
7196
+ DEFAULT_AI_CONNECTION_STRING = Buffer.from("SW5zdHJ1bWVudGF0aW9uS2V5PTliZDM3NDgyLTgxMGUtNDQyYS1hYWE2LWQzOGVmNjVjNjY3NDtJbmdlc3Rpb25FbmRwb2ludD1odHRwczovL3dlc3RldXJvcGUtNS5pbi5hcHBsaWNhdGlvbmluc2lnaHRzLmF6dXJlLmNvbS87TGl2ZUVuZHBvaW50PWh0dHBzOi8vd2VzdGV1cm9wZS5saXZlZGlhZ25vc3RpY3MubW9uaXRvci5henVyZS5jb20vO0FwcGxpY2F0aW9uSWQ9MzU2OTdlZjEtOGJkMC00ZjE5LWEyN2MtZDg3Y2NhYzY2ZDJj", "base64").toString("utf-8");
7182
7197
  telemetry = new Proxy({}, {
7183
7198
  get(_, prop) {
7184
7199
  const instance = getTelemetryInstance();
@@ -7192,12 +7207,12 @@ var init_telemetry = __esm(() => {
7192
7207
  var CommonTelemetryEvents;
7193
7208
  var init_telemetry_events = __esm(() => {
7194
7209
  CommonTelemetryEvents = {
7195
- Error: "Error"
7210
+ Error: "uip.error"
7196
7211
  };
7197
7212
  });
7198
7213
 
7199
7214
  // ../common/src/formatter.ts
7200
- function printOutput(data, format = "table", logFn = console.log) {
7215
+ function printOutput(data, format = "table", logFn) {
7201
7216
  if (!data) {
7202
7217
  logFn("Empty response object. No data to display.");
7203
7218
  return;
@@ -7216,8 +7231,6 @@ function printOutput(data, format = "table", logFn = console.log) {
7216
7231
  const values = Object.values(item).map((v) => v ?? "").join("\t");
7217
7232
  logFn(values);
7218
7233
  });
7219
- } else if ("Message" in data && !("Result" in data)) {
7220
- logFn(data.Message);
7221
7234
  } else {
7222
7235
  const values = Object.values(data).map((v) => v ?? "").join("\t");
7223
7236
  logFn(values);
@@ -7225,12 +7238,13 @@ function printOutput(data, format = "table", logFn = console.log) {
7225
7238
  break;
7226
7239
  }
7227
7240
  default: {
7228
- if ("Data" in data && data.Data != null) {
7229
- const items = Array.isArray(data.Data) ? data.Data : [data.Data];
7230
- const logValue = "Log" in data ? data.Log : undefined;
7231
- printTable(items, logFn, logValue);
7232
- } else if ("Message" in data && !("Result" in data)) {
7233
- logFn(data.Message);
7241
+ if ("Data" in data && data.Data != null && !(Array.isArray(data.Data) && data.Data.length === 0)) {
7242
+ const logValue = data.Log;
7243
+ if (Array.isArray(data.Data)) {
7244
+ printResizableTable(data.Data, logFn, logValue);
7245
+ } else {
7246
+ printVerticalTable(data.Data, logFn, logValue);
7247
+ }
7234
7248
  } else {
7235
7249
  printTable([{ ...data }], logFn);
7236
7250
  }
@@ -7243,16 +7257,22 @@ function logOutput(data, format = "table") {
7243
7257
  printOutput(data, format, (msg) => sink.writeOut(`${msg}
7244
7258
  `));
7245
7259
  }
7246
- function errorOutput(data, format = "table") {
7247
- const sink = getOutputSink();
7248
- printOutput(data, format, (msg) => sink.writeErr(`${msg}
7249
- `));
7260
+ function cellToString(val) {
7261
+ return val != null && typeof val === "object" ? JSON.stringify(val) : String(val ?? "");
7250
7262
  }
7251
- function printTable(data, logFn = console.log, externalLogValue) {
7263
+ function wrapText(text, width) {
7264
+ if (text.length <= width)
7265
+ return [text];
7266
+ const lines = [];
7267
+ for (let pos = 0;pos < text.length; pos += width) {
7268
+ lines.push(text.substring(pos, pos + width));
7269
+ }
7270
+ return lines;
7271
+ }
7272
+ function printTable(data, logFn, externalLogValue) {
7252
7273
  if (data.length === 0)
7253
7274
  return;
7254
7275
  const keys = Object.keys(data[0]).filter((key) => key !== "Code" && key !== "Log");
7255
- const cellToString = (val) => val != null && typeof val === "object" ? JSON.stringify(val) : String(val ?? "");
7256
7276
  const maxWidths = keys.map((key) => Math.max(key.length, ...data.map((item) => cellToString(item[key]).length)));
7257
7277
  const header = keys.map((key, i2) => key.padEnd(maxWidths[i2])).join(" | ");
7258
7278
  logFn(header);
@@ -7266,6 +7286,96 @@ function printTable(data, logFn = console.log, externalLogValue) {
7266
7286
  logFn(`Log: ${externalLogValue}`);
7267
7287
  }
7268
7288
  }
7289
+ function printVerticalTable(data, logFn = console.log, externalLogValue) {
7290
+ const keys = Object.keys(data).filter((key) => key !== "Code" && key !== "Log");
7291
+ if (keys.length === 0)
7292
+ return;
7293
+ const maxKeyWidth = Math.max(...keys.map((key) => key.length));
7294
+ keys.forEach((key) => {
7295
+ const keyCol = key.padEnd(maxKeyWidth);
7296
+ logFn(`${keyCol} | ${cellToString(data[key])}`);
7297
+ });
7298
+ if (externalLogValue) {
7299
+ logFn("");
7300
+ logFn(`Log: ${externalLogValue}`);
7301
+ }
7302
+ }
7303
+ function printResizableTable(data, logFn = console.log, externalLogValue) {
7304
+ if (data.length === 0)
7305
+ return;
7306
+ const keys = Object.keys(data[0]).filter((key) => key !== "Code" && key !== "Log");
7307
+ if (keys.length === 0)
7308
+ return;
7309
+ if (!process.stdout.isTTY) {
7310
+ printTable(data, logFn, externalLogValue);
7311
+ return;
7312
+ }
7313
+ const naturalWidths = keys.map((key) => Math.max(key.length, ...data.map((item) => cellToString(item[key]).length)));
7314
+ const separatorTotal = (keys.length - 1) * 3;
7315
+ const totalWidth = naturalWidths.reduce((a, b) => a + b, 0) + separatorTotal;
7316
+ const termWidth = process.stdout.columns || 120;
7317
+ if (totalWidth <= termWidth) {
7318
+ printTable(data, logFn, externalLogValue);
7319
+ return;
7320
+ }
7321
+ const overflow = totalWidth - termWidth;
7322
+ const MIN_COL_WIDTH = 10;
7323
+ const minWidths = keys.map((key) => Math.max(key.length, MIN_COL_WIDTH));
7324
+ let bestCol = -1;
7325
+ let bestCost = Infinity;
7326
+ for (let i2 = 0;i2 < keys.length; i2++) {
7327
+ const maxShrink = naturalWidths[i2] - minWidths[i2];
7328
+ if (maxShrink < overflow)
7329
+ continue;
7330
+ const newWidth = naturalWidths[i2] - overflow;
7331
+ let extraRows = 0;
7332
+ for (const item of data) {
7333
+ const cellLen = cellToString(item[keys[i2]]).length;
7334
+ if (cellLen > newWidth) {
7335
+ extraRows += Math.ceil(cellLen / newWidth) - 1;
7336
+ }
7337
+ }
7338
+ if (extraRows < bestCost) {
7339
+ bestCost = extraRows;
7340
+ bestCol = i2;
7341
+ }
7342
+ }
7343
+ const finalWidths = [...naturalWidths];
7344
+ if (bestCol !== -1) {
7345
+ finalWidths[bestCol] = naturalWidths[bestCol] - overflow;
7346
+ } else {
7347
+ let remaining = overflow;
7348
+ const colsByShrinkPotential = keys.map((_, i2) => ({
7349
+ index: i2,
7350
+ potential: naturalWidths[i2] - minWidths[i2]
7351
+ })).filter((c) => c.potential > 0).sort((a, b) => b.potential - a.potential);
7352
+ for (const col of colsByShrinkPotential) {
7353
+ if (remaining <= 0)
7354
+ break;
7355
+ const shrink = Math.min(remaining, col.potential);
7356
+ finalWidths[col.index] -= shrink;
7357
+ remaining -= shrink;
7358
+ }
7359
+ }
7360
+ const header = keys.map((key, i2) => key.padEnd(finalWidths[i2])).join(" | ");
7361
+ logFn(header);
7362
+ logFn(keys.map((_, i2) => "-".repeat(finalWidths[i2])).join("-|-"));
7363
+ data.forEach((item) => {
7364
+ const cellLines = keys.map((key, i2) => wrapText(cellToString(item[key]), finalWidths[i2]));
7365
+ const lineCount = Math.max(...cellLines.map((l) => l.length));
7366
+ for (let line = 0;line < lineCount; line++) {
7367
+ const row = keys.map((_, i2) => {
7368
+ const val = line < cellLines[i2].length ? cellLines[i2][line] : "";
7369
+ return val.padEnd(finalWidths[i2]);
7370
+ }).join(" | ");
7371
+ logFn(row);
7372
+ }
7373
+ });
7374
+ if (externalLogValue) {
7375
+ logFn("");
7376
+ logFn(`Log: ${externalLogValue}`);
7377
+ }
7378
+ }
7269
7379
  function toYaml(data) {
7270
7380
  return dump(data);
7271
7381
  }
@@ -7310,16 +7420,19 @@ var init_formatter = __esm(() => {
7310
7420
  result: data.Result,
7311
7421
  message: data.Message
7312
7422
  });
7313
- errorOutput(data, getOutputFormat());
7423
+ logOutput(data, getOutputFormat());
7314
7424
  }
7315
7425
  OutputFormatter.error = error;
7316
7426
  function log(data) {
7317
7427
  const format = getOutputFormat();
7428
+ const sink = getOutputSink();
7318
7429
  if (format === "json") {
7319
- console.error(JSON.stringify(data));
7430
+ sink.writeErr(`${JSON.stringify(data)}
7431
+ `);
7320
7432
  } else {
7321
7433
  for (const [key, value] of Object.entries(data)) {
7322
- console.error(`${key}: ${value}`);
7434
+ sink.writeErr(`${key}: ${value}
7435
+ `);
7323
7436
  }
7324
7437
  }
7325
7438
  }
@@ -7348,6 +7461,109 @@ var init_command_help = __esm(() => {
7348
7461
  init_output_format_context();
7349
7462
  });
7350
7463
 
7464
+ // ../common/src/console-guard.ts
7465
+ var guardInstalledSlot, savedOriginalsSlot;
7466
+ var init_console_guard = __esm(() => {
7467
+ init_output_context();
7468
+ init_singleton();
7469
+ guardInstalledSlot = singleton("ConsoleGuardInstalled");
7470
+ savedOriginalsSlot = singleton("ConsoleGuardOriginals");
7471
+ });
7472
+
7473
+ // ../common/src/constants.ts
7474
+ var UIPATH_HOME_DIR = ".uipath", AUTH_FILENAME = ".auth", CONFIG_FILENAME = "config.json", LOCAL_CONFIG_FILENAME = "uipath.config.json", DEFAULT_BASE_URL = "https://cloud.uipath.com", DEFAULT_AUTH_TIMEOUT_MS;
7475
+ var init_constants = __esm(() => {
7476
+ DEFAULT_AUTH_TIMEOUT_MS = 5 * 60 * 1000;
7477
+ });
7478
+ // ../common/src/error-handler.ts
7479
+ async function extractErrorDetails(error, options) {
7480
+ const err = error !== null && error !== undefined && typeof error === "object" ? error : {};
7481
+ const response = err.response;
7482
+ const status = err.status ?? response?.status;
7483
+ let rawBody;
7484
+ let extractedMessage;
7485
+ let parsedBody;
7486
+ const textFn = response?.text?.bind(response);
7487
+ if (textFn) {
7488
+ const [bodyError, body] = await catchError((async () => textFn())());
7489
+ if (!bodyError && body) {
7490
+ rawBody = body;
7491
+ const [parseError, parsed] = catchError(() => JSON.parse(body));
7492
+ if (!parseError && parsed && typeof parsed === "object") {
7493
+ parsedBody = parsed;
7494
+ if (parsedBody.errors && typeof parsedBody.errors === "object") {
7495
+ for (const field of Object.values(parsedBody.errors)) {
7496
+ if (Array.isArray(field) && field.length > 0) {
7497
+ const first = field[0];
7498
+ if (first && typeof first.message === "string") {
7499
+ extractedMessage = first.message;
7500
+ break;
7501
+ }
7502
+ }
7503
+ }
7504
+ }
7505
+ if (!extractedMessage) {
7506
+ extractedMessage = typeof parsedBody.message === "string" ? parsedBody.message : typeof parsedBody.errorMessage === "string" ? parsedBody.errorMessage : typeof parsedBody.title === "string" ? parsedBody.title : undefined;
7507
+ }
7508
+ if (!extractedMessage) {
7509
+ extractedMessage = body;
7510
+ }
7511
+ } else {
7512
+ extractedMessage = body;
7513
+ }
7514
+ }
7515
+ }
7516
+ const rawMessage = typeof err.message === "string" ? err.message : "Unknown error";
7517
+ let message;
7518
+ if (status === 401) {
7519
+ message = DEFAULT_401;
7520
+ } else if (status === 403) {
7521
+ message = options?.forbiddenMessage ?? DEFAULT_403;
7522
+ } else if (status === 405) {
7523
+ message = DEFAULT_405;
7524
+ } else if (extractedMessage) {
7525
+ message = status ? `HTTP ${status}: ${extractedMessage}` : extractedMessage;
7526
+ } else if (status) {
7527
+ if (rawMessage === "Unknown error" && response) {
7528
+ const statusText = response.statusText;
7529
+ message = statusText ? `HTTP ${status} ${statusText}` : `HTTP ${status} - request failed`;
7530
+ } else {
7531
+ message = `HTTP ${status}: ${rawMessage}`;
7532
+ }
7533
+ } else {
7534
+ message = rawMessage;
7535
+ }
7536
+ let details = rawMessage;
7537
+ if (rawBody) {
7538
+ if (parsedBody) {
7539
+ const extra = {};
7540
+ if (parsedBody.errorCode)
7541
+ extra.errorCode = parsedBody.errorCode;
7542
+ if (parsedBody.details)
7543
+ extra.details = parsedBody.details;
7544
+ if (parsedBody.errors != null)
7545
+ extra.errors = parsedBody.errors;
7546
+ if (parsedBody.data && typeof parsedBody.data === "object" && Object.keys(parsedBody.data).length > 0) {
7547
+ extra.data = parsedBody.data;
7548
+ }
7549
+ details = Object.keys(extra).length > 0 ? JSON.stringify(extra) : rawBody;
7550
+ } else {
7551
+ details = rawBody;
7552
+ }
7553
+ } else if (typeof err.message === "string") {
7554
+ details = err.message;
7555
+ } else {
7556
+ details = String(error);
7557
+ }
7558
+ return { message, details };
7559
+ }
7560
+ async function extractErrorMessage(error, options) {
7561
+ const { message } = await extractErrorDetails(error, options);
7562
+ return message;
7563
+ }
7564
+ var DEFAULT_401 = "Unauthorized (401). Run `uip login` to authenticate.", DEFAULT_403 = "Forbidden (403). Ensure the account has the required permissions.", DEFAULT_405 = "Method Not Allowed (405). The endpoint may not exist or the base URL may be incorrect.";
7565
+ var init_error_handler = () => {};
7566
+
7351
7567
  // ../../node_modules/jsonpath-plus/dist/index-node-esm.js
7352
7568
  import vm from "vm";
7353
7569
 
@@ -8752,14 +8968,105 @@ var init_index_node_esm = __esm(() => {
8752
8968
  var init_jsonpath = __esm(() => {
8753
8969
  init_index_node_esm();
8754
8970
  });
8971
+ // ../common/src/polling/abort-controller.ts
8972
+ var init_abort_controller = __esm(() => {
8973
+ init_logger();
8974
+ });
8975
+ // ../common/src/polling/types.ts
8976
+ var init_types = () => {};
8977
+
8978
+ // ../common/src/polling/poll-until.ts
8979
+ var init_poll_until = __esm(() => {
8980
+ init_logger();
8981
+ init_types();
8982
+ });
8983
+
8984
+ // ../common/src/polling/terminal-statuses.ts
8985
+ var TERMINAL_STATUSES, FAILURE_STATUSES;
8986
+ var init_terminal_statuses = __esm(() => {
8987
+ TERMINAL_STATUSES = new Set([
8988
+ "completed",
8989
+ "successful",
8990
+ "faulted",
8991
+ "failed",
8992
+ "cancelled",
8993
+ "canceled",
8994
+ "stopped",
8995
+ "finished"
8996
+ ]);
8997
+ FAILURE_STATUSES = new Set([
8998
+ "faulted",
8999
+ "failed",
9000
+ "cancelled",
9001
+ "canceled",
9002
+ "stopped"
9003
+ ]);
9004
+ });
9005
+
9006
+ // ../common/src/polling/index.ts
9007
+ var init_polling = __esm(() => {
9008
+ init_abort_controller();
9009
+ init_poll_until();
9010
+ init_terminal_statuses();
9011
+ init_types();
9012
+ });
9013
+
9014
+ // ../common/src/screen-logger.ts
9015
+ var ScreenLogger;
9016
+ var init_screen_logger = __esm(() => {
9017
+ init_output_context();
9018
+ ((ScreenLogger) => {
9019
+ function progress(message) {
9020
+ getOutputSink().writeErr(`${message}
9021
+ `);
9022
+ }
9023
+ ScreenLogger.progress = progress;
9024
+ })(ScreenLogger ||= {});
9025
+ });
9026
+
9027
+ // ../common/src/tool-provider.ts
9028
+ var factorySlot;
9029
+ var init_tool_provider = __esm(() => {
9030
+ init_singleton();
9031
+ factorySlot = singleton("PackagerFactoryProvider");
9032
+ });
9033
+
8755
9034
  // ../common/src/trackedAction.ts
9035
+ function deriveCommandPath(cmd) {
9036
+ const parts = [];
9037
+ let current = cmd;
9038
+ while (current) {
9039
+ const name = current.name();
9040
+ if (name) {
9041
+ parts.unshift(name);
9042
+ }
9043
+ current = current.parent;
9044
+ }
9045
+ if (parts.length > 1) {
9046
+ parts.shift();
9047
+ }
9048
+ return ["uip", ...parts.filter((p) => p !== "uip")].join(".");
9049
+ }
9050
+ var pollSignalSlot, processContext;
8756
9051
  var init_trackedAction = __esm(() => {
8757
9052
  init_esm();
8758
9053
  init_formatter();
8759
9054
  init_logger();
9055
+ init_singleton();
8760
9056
  init_telemetry();
8761
- Command.prototype.trackedAction = function(context, telemetryName, fn, properties) {
9057
+ pollSignalSlot = singleton("PollSignal");
9058
+ processContext = {
9059
+ exit: (code) => {
9060
+ process.exitCode = code;
9061
+ },
9062
+ get pollSignal() {
9063
+ return pollSignalSlot.get();
9064
+ }
9065
+ };
9066
+ Command.prototype.trackedAction = function(context, fn, properties) {
9067
+ const command = this;
8762
9068
  return this.action(async (...args) => {
9069
+ const telemetryName = deriveCommandPath(command);
8763
9070
  const props = typeof properties === "function" ? properties(...args) : properties;
8764
9071
  const startTime = performance.now();
8765
9072
  let errorMessage;
@@ -8788,16 +9095,22 @@ var init_trackedAction = __esm(() => {
8788
9095
 
8789
9096
  // ../common/src/index.ts
8790
9097
  var init_src = __esm(() => {
9098
+ init_console_guard();
8791
9099
  init_node_appinsights_telemetry_provider();
8792
9100
  init_command_help();
9101
+ init_constants();
9102
+ init_error_handler();
8793
9103
  init_formatter();
8794
9104
  init_jsonpath();
8795
9105
  init_logger();
8796
9106
  init_output_context();
8797
9107
  init_output_format_context();
9108
+ init_polling();
8798
9109
  init_registry();
9110
+ init_screen_logger();
8799
9111
  init_telemetry();
8800
9112
  init_telemetry_events();
9113
+ init_tool_provider();
8801
9114
  init_trackedAction();
8802
9115
  });
8803
9116
 
@@ -9568,65 +9881,8 @@ var init_src2 = __esm(() => {
9568
9881
  init_node2();
9569
9882
  fsInstance = new NodeFileSystem;
9570
9883
  });
9571
- // ../../node_modules/sisteransi/src/index.js
9572
- var require_src = __commonJS((exports, module) => {
9573
- var ESC = "\x1B";
9574
- var CSI = `${ESC}[`;
9575
- var beep = "\x07";
9576
- var cursor = {
9577
- to(x, y) {
9578
- if (!y)
9579
- return `${CSI}${x + 1}G`;
9580
- return `${CSI}${y + 1};${x + 1}H`;
9581
- },
9582
- move(x, y) {
9583
- let ret = "";
9584
- if (x < 0)
9585
- ret += `${CSI}${-x}D`;
9586
- else if (x > 0)
9587
- ret += `${CSI}${x}C`;
9588
- if (y < 0)
9589
- ret += `${CSI}${-y}A`;
9590
- else if (y > 0)
9591
- ret += `${CSI}${y}B`;
9592
- return ret;
9593
- },
9594
- up: (count = 1) => `${CSI}${count}A`,
9595
- down: (count = 1) => `${CSI}${count}B`,
9596
- forward: (count = 1) => `${CSI}${count}C`,
9597
- backward: (count = 1) => `${CSI}${count}D`,
9598
- nextLine: (count = 1) => `${CSI}E`.repeat(count),
9599
- prevLine: (count = 1) => `${CSI}F`.repeat(count),
9600
- left: `${CSI}G`,
9601
- hide: `${CSI}?25l`,
9602
- show: `${CSI}?25h`,
9603
- save: `${ESC}7`,
9604
- restore: `${ESC}8`
9605
- };
9606
- var scroll = {
9607
- up: (count = 1) => `${CSI}S`.repeat(count),
9608
- down: (count = 1) => `${CSI}T`.repeat(count)
9609
- };
9610
- var erase = {
9611
- screen: `${CSI}2J`,
9612
- up: (count = 1) => `${CSI}1J`.repeat(count),
9613
- down: (count = 1) => `${CSI}J`.repeat(count),
9614
- line: `${CSI}2K`,
9615
- lineEnd: `${CSI}K`,
9616
- lineStart: `${CSI}1K`,
9617
- lines(count) {
9618
- let clear = "";
9619
- for (let i2 = 0;i2 < count; i2++)
9620
- clear += this.line + (i2 < count - 1 ? cursor.up() : "");
9621
- if (count)
9622
- clear += cursor.left;
9623
- return clear;
9624
- }
9625
- };
9626
- module.exports = { cursor, scroll, erase, beep };
9627
- });
9628
-
9629
9884
  // src/client.ts
9885
+ init_src();
9630
9886
  function buildPimsUrl(config, path) {
9631
9887
  return `${config.baseUrl}/${config.organizationId}/${config.tenantId}/pims_/api/v1${path}`;
9632
9888
  }
@@ -9656,7 +9912,13 @@ async function pimsGet(config, path, options) {
9656
9912
  if (contentType.includes("application/xml") || contentType.includes("text/xml")) {
9657
9913
  return await response.text();
9658
9914
  }
9659
- return response.json();
9915
+ const text = await response.text();
9916
+ if (!text)
9917
+ return {};
9918
+ const [parseErr, parsed] = catchError(() => JSON.parse(text));
9919
+ if (parseErr)
9920
+ throw new Error(`Failed to parse API response body: ${parseErr.message}`);
9921
+ return parsed;
9660
9922
  }
9661
9923
  async function pimsPost(config, path, body, options) {
9662
9924
  const url = buildPimsUrl(config, path);
@@ -9671,8 +9933,20 @@ async function pimsPost(config, path, body, options) {
9671
9933
  throw new Error(`API request failed: ${response.status} ${response.statusText} - ${errorText}`);
9672
9934
  }
9673
9935
  const text = await response.text();
9674
- return text ? JSON.parse(text) : {};
9936
+ if (!text)
9937
+ return {};
9938
+ const [parseErr, parsed] = catchError(() => JSON.parse(text));
9939
+ if (parseErr) {
9940
+ throw new Error(`Failed to parse API response body: ${parseErr.message}`);
9941
+ }
9942
+ return parsed;
9675
9943
  }
9944
+ // ../auth/src/index.ts
9945
+ init_src();
9946
+
9947
+ // ../auth/src/config.ts
9948
+ init_src();
9949
+
9676
9950
  // ../auth/src/utils/loadConfig.ts
9677
9951
  init_src();
9678
9952
 
@@ -23259,11 +23533,11 @@ var loadConfigAsync = async () => {
23259
23533
  const fs7 = await getFs();
23260
23534
  let configPath = fs7.env.getenv("UIPATH_CONFIG_PATH");
23261
23535
  if (!configPath) {
23262
- const localPath = fs7.path.join(fs7.env.cwd(), "uipath.config.json");
23536
+ const localPath = fs7.path.join(fs7.env.cwd(), LOCAL_CONFIG_FILENAME);
23263
23537
  if (await fs7.exists(localPath)) {
23264
23538
  configPath = localPath;
23265
23539
  } else {
23266
- configPath = fs7.path.join(fs7.env.homedir(), ".uipcli", "config.json");
23540
+ configPath = fs7.path.join(fs7.env.homedir(), UIPATH_HOME_DIR, CONFIG_FILENAME);
23267
23541
  }
23268
23542
  }
23269
23543
  if (!await fs7.exists(configPath)) {
@@ -23296,7 +23570,6 @@ Please ensure your config file contains valid JSON.`;
23296
23570
  };
23297
23571
 
23298
23572
  // ../auth/src/config.ts
23299
- var DEFAULT_BASE_URL = "https://cloud.uipath.com";
23300
23573
  var DEFAULT_CLIENT_ID = "36dea5b8-e8bb-423d-8e7b-c808df8f1c00";
23301
23574
 
23302
23575
  class InvalidBaseUrlError extends Error {
@@ -23340,25 +23613,19 @@ var resolveConfigAsync = async ({
23340
23613
  while (baseUrl.endsWith("/")) {
23341
23614
  baseUrl = baseUrl.slice(0, -1);
23342
23615
  }
23343
- try {
23344
- const url2 = new URL(baseUrl);
23345
- const isValidUiPathDomain = url2.hostname === "uipath.com" || url2.hostname.endsWith(".uipath.com");
23346
- if (!isValidUiPathDomain) {
23347
- throw new InvalidBaseUrlError(baseUrl, `Domain "${url2.hostname}" is not a valid UiPath domain. Only uipath.com and its subdomains are allowed.`);
23348
- }
23349
- if (url2.pathname.length > 1) {
23350
- baseUrl = url2.origin;
23351
- }
23352
- } catch (error48) {
23353
- if (error48 instanceof InvalidBaseUrlError) {
23354
- throw error48;
23355
- }
23356
- throw new InvalidBaseUrlError(baseUrl, `Malformed URL. ${error48 instanceof Error ? error48.message : "Unknown error"}`);
23616
+ const resolvedBaseUrl = baseUrl;
23617
+ const [urlError, url2] = catchError(() => new URL(resolvedBaseUrl));
23618
+ if (urlError) {
23619
+ throw new InvalidBaseUrlError(baseUrl, `Malformed URL. ${urlError instanceof Error ? urlError.message : "Unknown error"}`);
23357
23620
  }
23358
- let clientId = customClientId;
23359
- if (!clientId) {
23360
- clientId = process.env.UIPATH_CLIENT_ID;
23621
+ const isValidUiPathDomain = url2.hostname === "uipath.com" || url2.hostname.endsWith(".uipath.com");
23622
+ if (!isValidUiPathDomain) {
23623
+ throw new InvalidBaseUrlError(baseUrl, `Domain "${url2.hostname}" is not a valid UiPath domain. Only uipath.com and its subdomains are allowed.`);
23361
23624
  }
23625
+ if (url2.pathname.length > 1) {
23626
+ baseUrl = url2.origin;
23627
+ }
23628
+ let clientId = customClientId;
23362
23629
  if (!clientId && config2.auth?.clientId) {
23363
23630
  clientId = config2.auth.clientId;
23364
23631
  }
@@ -23366,9 +23633,6 @@ var resolveConfigAsync = async ({
23366
23633
  clientId = DEFAULT_CLIENT_ID;
23367
23634
  }
23368
23635
  let clientSecret = customClientSecret;
23369
- if (!clientSecret) {
23370
- clientSecret = process.env.UIPATH_CLIENT_SECRET;
23371
- }
23372
23636
  if (!clientSecret && config2.auth?.clientSecret) {
23373
23637
  clientSecret = config2.auth.clientSecret;
23374
23638
  }
@@ -23391,533 +23655,19 @@ init_src2();
23391
23655
 
23392
23656
  // ../auth/src/telemetry-events.ts
23393
23657
  var AuthTelemetryEvents = {
23394
- Login: "Auth.Login",
23395
- TenantSelected: "Auth.TenantSelected",
23396
- TokenRefresh: "Auth.TokenRefresh",
23397
- Logout: "Auth.Logout"
23658
+ Login: "uip.auth.login",
23659
+ TenantSelected: "uip.auth.tenant-selected",
23660
+ TokenRefresh: "uip.auth.token-refresh",
23661
+ Logout: "uip.auth.logout"
23398
23662
  };
23399
23663
 
23400
23664
  // ../auth/src/tenantSelection.ts
23401
23665
  init_src();
23402
23666
 
23403
- // ../../node_modules/@clack/core/dist/index.mjs
23404
- import { styleText as D } from "node:util";
23405
- import { stdout as R, stdin as q } from "node:process";
23406
- var import_sisteransi = __toESM(require_src(), 1);
23407
- import ot from "node:readline";
23408
- function x(t, e, s) {
23409
- if (!s.some((u) => !u.disabled))
23410
- return t;
23411
- const i2 = t + e, r = Math.max(s.length - 1, 0), n = i2 < 0 ? r : i2 > r ? 0 : i2;
23412
- return s[n].disabled ? x(n, e < 0 ? -1 : 1, s) : n;
23413
- }
23414
- var at = (t) => t === 161 || t === 164 || t === 167 || t === 168 || t === 170 || t === 173 || t === 174 || t >= 176 && t <= 180 || t >= 182 && t <= 186 || t >= 188 && t <= 191 || t === 198 || t === 208 || t === 215 || t === 216 || t >= 222 && t <= 225 || t === 230 || t >= 232 && t <= 234 || t === 236 || t === 237 || t === 240 || t === 242 || t === 243 || t >= 247 && t <= 250 || t === 252 || t === 254 || t === 257 || t === 273 || t === 275 || t === 283 || t === 294 || t === 295 || t === 299 || t >= 305 && t <= 307 || t === 312 || t >= 319 && t <= 322 || t === 324 || t >= 328 && t <= 331 || t === 333 || t === 338 || t === 339 || t === 358 || t === 359 || t === 363 || t === 462 || t === 464 || t === 466 || t === 468 || t === 470 || t === 472 || t === 474 || t === 476 || t === 593 || t === 609 || t === 708 || t === 711 || t >= 713 && t <= 715 || t === 717 || t === 720 || t >= 728 && t <= 731 || t === 733 || t === 735 || t >= 768 && t <= 879 || t >= 913 && t <= 929 || t >= 931 && t <= 937 || t >= 945 && t <= 961 || t >= 963 && t <= 969 || t === 1025 || t >= 1040 && t <= 1103 || t === 1105 || t === 8208 || t >= 8211 && t <= 8214 || t === 8216 || t === 8217 || t === 8220 || t === 8221 || t >= 8224 && t <= 8226 || t >= 8228 && t <= 8231 || t === 8240 || t === 8242 || t === 8243 || t === 8245 || t === 8251 || t === 8254 || t === 8308 || t === 8319 || t >= 8321 && t <= 8324 || t === 8364 || t === 8451 || t === 8453 || t === 8457 || t === 8467 || t === 8470 || t === 8481 || t === 8482 || t === 8486 || t === 8491 || t === 8531 || t === 8532 || t >= 8539 && t <= 8542 || t >= 8544 && t <= 8555 || t >= 8560 && t <= 8569 || t === 8585 || t >= 8592 && t <= 8601 || t === 8632 || t === 8633 || t === 8658 || t === 8660 || t === 8679 || t === 8704 || t === 8706 || t === 8707 || t === 8711 || t === 8712 || t === 8715 || t === 8719 || t === 8721 || t === 8725 || t === 8730 || t >= 8733 && t <= 8736 || t === 8739 || t === 8741 || t >= 8743 && t <= 8748 || t === 8750 || t >= 8756 && t <= 8759 || t === 8764 || t === 8765 || t === 8776 || t === 8780 || t === 8786 || t === 8800 || t === 8801 || t >= 8804 && t <= 8807 || t === 8810 || t === 8811 || t === 8814 || t === 8815 || t === 8834 || t === 8835 || t === 8838 || t === 8839 || t === 8853 || t === 8857 || t === 8869 || t === 8895 || t === 8978 || t >= 9312 && t <= 9449 || t >= 9451 && t <= 9547 || t >= 9552 && t <= 9587 || t >= 9600 && t <= 9615 || t >= 9618 && t <= 9621 || t === 9632 || t === 9633 || t >= 9635 && t <= 9641 || t === 9650 || t === 9651 || t === 9654 || t === 9655 || t === 9660 || t === 9661 || t === 9664 || t === 9665 || t >= 9670 && t <= 9672 || t === 9675 || t >= 9678 && t <= 9681 || t >= 9698 && t <= 9701 || t === 9711 || t === 9733 || t === 9734 || t === 9737 || t === 9742 || t === 9743 || t === 9756 || t === 9758 || t === 9792 || t === 9794 || t === 9824 || t === 9825 || t >= 9827 && t <= 9829 || t >= 9831 && t <= 9834 || t === 9836 || t === 9837 || t === 9839 || t === 9886 || t === 9887 || t === 9919 || t >= 9926 && t <= 9933 || t >= 9935 && t <= 9939 || t >= 9941 && t <= 9953 || t === 9955 || t === 9960 || t === 9961 || t >= 9963 && t <= 9969 || t === 9972 || t >= 9974 && t <= 9977 || t === 9979 || t === 9980 || t === 9982 || t === 9983 || t === 10045 || t >= 10102 && t <= 10111 || t >= 11094 && t <= 11097 || t >= 12872 && t <= 12879 || t >= 57344 && t <= 63743 || t >= 65024 && t <= 65039 || t === 65533 || t >= 127232 && t <= 127242 || t >= 127248 && t <= 127277 || t >= 127280 && t <= 127337 || t >= 127344 && t <= 127373 || t === 127375 || t === 127376 || t >= 127387 && t <= 127404 || t >= 917760 && t <= 917999 || t >= 983040 && t <= 1048573 || t >= 1048576 && t <= 1114109;
23415
- var lt = (t) => t === 12288 || t >= 65281 && t <= 65376 || t >= 65504 && t <= 65510;
23416
- var ht = (t) => t >= 4352 && t <= 4447 || t === 8986 || t === 8987 || t === 9001 || t === 9002 || t >= 9193 && t <= 9196 || t === 9200 || t === 9203 || t === 9725 || t === 9726 || t === 9748 || t === 9749 || t >= 9800 && t <= 9811 || t === 9855 || t === 9875 || t === 9889 || t === 9898 || t === 9899 || t === 9917 || t === 9918 || t === 9924 || t === 9925 || t === 9934 || t === 9940 || t === 9962 || t === 9970 || t === 9971 || t === 9973 || t === 9978 || t === 9981 || t === 9989 || t === 9994 || t === 9995 || t === 10024 || t === 10060 || t === 10062 || t >= 10067 && t <= 10069 || t === 10071 || t >= 10133 && t <= 10135 || t === 10160 || t === 10175 || t === 11035 || t === 11036 || t === 11088 || t === 11093 || t >= 11904 && t <= 11929 || t >= 11931 && t <= 12019 || t >= 12032 && t <= 12245 || t >= 12272 && t <= 12287 || t >= 12289 && t <= 12350 || t >= 12353 && t <= 12438 || t >= 12441 && t <= 12543 || t >= 12549 && t <= 12591 || t >= 12593 && t <= 12686 || t >= 12688 && t <= 12771 || t >= 12783 && t <= 12830 || t >= 12832 && t <= 12871 || t >= 12880 && t <= 19903 || t >= 19968 && t <= 42124 || t >= 42128 && t <= 42182 || t >= 43360 && t <= 43388 || t >= 44032 && t <= 55203 || t >= 63744 && t <= 64255 || t >= 65040 && t <= 65049 || t >= 65072 && t <= 65106 || t >= 65108 && t <= 65126 || t >= 65128 && t <= 65131 || t >= 94176 && t <= 94180 || t === 94192 || t === 94193 || t >= 94208 && t <= 100343 || t >= 100352 && t <= 101589 || t >= 101632 && t <= 101640 || t >= 110576 && t <= 110579 || t >= 110581 && t <= 110587 || t === 110589 || t === 110590 || t >= 110592 && t <= 110882 || t === 110898 || t >= 110928 && t <= 110930 || t === 110933 || t >= 110948 && t <= 110951 || t >= 110960 && t <= 111355 || t === 126980 || t === 127183 || t === 127374 || t >= 127377 && t <= 127386 || t >= 127488 && t <= 127490 || t >= 127504 && t <= 127547 || t >= 127552 && t <= 127560 || t === 127568 || t === 127569 || t >= 127584 && t <= 127589 || t >= 127744 && t <= 127776 || t >= 127789 && t <= 127797 || t >= 127799 && t <= 127868 || t >= 127870 && t <= 127891 || t >= 127904 && t <= 127946 || t >= 127951 && t <= 127955 || t >= 127968 && t <= 127984 || t === 127988 || t >= 127992 && t <= 128062 || t === 128064 || t >= 128066 && t <= 128252 || t >= 128255 && t <= 128317 || t >= 128331 && t <= 128334 || t >= 128336 && t <= 128359 || t === 128378 || t === 128405 || t === 128406 || t === 128420 || t >= 128507 && t <= 128591 || t >= 128640 && t <= 128709 || t === 128716 || t >= 128720 && t <= 128722 || t >= 128725 && t <= 128727 || t >= 128732 && t <= 128735 || t === 128747 || t === 128748 || t >= 128756 && t <= 128764 || t >= 128992 && t <= 129003 || t === 129008 || t >= 129292 && t <= 129338 || t >= 129340 && t <= 129349 || t >= 129351 && t <= 129535 || t >= 129648 && t <= 129660 || t >= 129664 && t <= 129672 || t >= 129680 && t <= 129725 || t >= 129727 && t <= 129733 || t >= 129742 && t <= 129755 || t >= 129760 && t <= 129768 || t >= 129776 && t <= 129784 || t >= 131072 && t <= 196605 || t >= 196608 && t <= 262141;
23417
- var O = /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y;
23418
- var y = /[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y;
23419
- var L = /\t{1,1000}/y;
23420
- var P = /[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/yu;
23421
- var M = /(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y;
23422
- var ct = /\p{M}+/gu;
23423
- var ft = { limit: 1 / 0, ellipsis: "" };
23424
- var X = (t, e = {}, s = {}) => {
23425
- const i2 = e.limit ?? 1 / 0, r = e.ellipsis ?? "", n = e?.ellipsisWidth ?? (r ? X(r, ft, s).width : 0), u = s.ansiWidth ?? 0, a = s.controlWidth ?? 0, l = s.tabWidth ?? 8, E = s.ambiguousWidth ?? 1, g = s.emojiWidth ?? 2, m = s.fullWidthWidth ?? 2, A = s.regularWidth ?? 1, V = s.wideWidth ?? 2;
23426
- let h = 0, o = 0, p = t.length, v = 0, F = false, d = p, b = Math.max(0, i2 - n), C = 0, w = 0, c = 0, f = 0;
23427
- t:
23428
- for (;; ) {
23429
- if (w > C || o >= p && o > h) {
23430
- const ut = t.slice(C, w) || t.slice(h, o);
23431
- v = 0;
23432
- for (const Y of ut.replaceAll(ct, "")) {
23433
- const $ = Y.codePointAt(0) || 0;
23434
- if (lt($) ? f = m : ht($) ? f = V : E !== A && at($) ? f = E : f = A, c + f > b && (d = Math.min(d, Math.max(C, h) + v)), c + f > i2) {
23435
- F = true;
23436
- break t;
23437
- }
23438
- v += Y.length, c += f;
23439
- }
23440
- C = w = 0;
23441
- }
23442
- if (o >= p)
23443
- break;
23444
- if (M.lastIndex = o, M.test(t)) {
23445
- if (v = M.lastIndex - o, f = v * A, c + f > b && (d = Math.min(d, o + Math.floor((b - c) / A))), c + f > i2) {
23446
- F = true;
23447
- break;
23448
- }
23449
- c += f, C = h, w = o, o = h = M.lastIndex;
23450
- continue;
23451
- }
23452
- if (O.lastIndex = o, O.test(t)) {
23453
- if (c + u > b && (d = Math.min(d, o)), c + u > i2) {
23454
- F = true;
23455
- break;
23456
- }
23457
- c += u, C = h, w = o, o = h = O.lastIndex;
23458
- continue;
23459
- }
23460
- if (y.lastIndex = o, y.test(t)) {
23461
- if (v = y.lastIndex - o, f = v * a, c + f > b && (d = Math.min(d, o + Math.floor((b - c) / a))), c + f > i2) {
23462
- F = true;
23463
- break;
23464
- }
23465
- c += f, C = h, w = o, o = h = y.lastIndex;
23466
- continue;
23467
- }
23468
- if (L.lastIndex = o, L.test(t)) {
23469
- if (v = L.lastIndex - o, f = v * l, c + f > b && (d = Math.min(d, o + Math.floor((b - c) / l))), c + f > i2) {
23470
- F = true;
23471
- break;
23472
- }
23473
- c += f, C = h, w = o, o = h = L.lastIndex;
23474
- continue;
23475
- }
23476
- if (P.lastIndex = o, P.test(t)) {
23477
- if (c + g > b && (d = Math.min(d, o)), c + g > i2) {
23478
- F = true;
23479
- break;
23480
- }
23481
- c += g, C = h, w = o, o = h = P.lastIndex;
23482
- continue;
23483
- }
23484
- o += 1;
23485
- }
23486
- return { width: F ? b : c, index: F ? d : p, truncated: F, ellipsed: F && i2 >= n };
23487
- };
23488
- var pt = { limit: 1 / 0, ellipsis: "", ellipsisWidth: 0 };
23489
- var S = (t, e = {}) => X(t, pt, e).width;
23490
- var T = "\x1B";
23491
- var Z = "›";
23492
- var Ft = 39;
23493
- var j = "\x07";
23494
- var Q = "[";
23495
- var dt = "]";
23496
- var tt = "m";
23497
- var U = `${dt}8;;`;
23498
- var et = new RegExp(`(?:\\${Q}(?<code>\\d+)m|\\${U}(?<uri>.*)${j})`, "y");
23499
- var mt = (t) => {
23500
- if (t >= 30 && t <= 37 || t >= 90 && t <= 97)
23501
- return 39;
23502
- if (t >= 40 && t <= 47 || t >= 100 && t <= 107)
23503
- return 49;
23504
- if (t === 1 || t === 2)
23505
- return 22;
23506
- if (t === 3)
23507
- return 23;
23508
- if (t === 4)
23509
- return 24;
23510
- if (t === 7)
23511
- return 27;
23512
- if (t === 8)
23513
- return 28;
23514
- if (t === 9)
23515
- return 29;
23516
- if (t === 0)
23517
- return 0;
23518
- };
23519
- var st = (t) => `${T}${Q}${t}${tt}`;
23520
- var it = (t) => `${T}${U}${t}${j}`;
23521
- var gt = (t) => t.map((e) => S(e));
23522
- var G = (t, e, s) => {
23523
- const i2 = e[Symbol.iterator]();
23524
- let r = false, n = false, u = t.at(-1), a = u === undefined ? 0 : S(u), l = i2.next(), E = i2.next(), g = 0;
23525
- for (;!l.done; ) {
23526
- const m = l.value, A = S(m);
23527
- a + A <= s ? t[t.length - 1] += m : (t.push(m), a = 0), (m === T || m === Z) && (r = true, n = e.startsWith(U, g + 1)), r ? n ? m === j && (r = false, n = false) : m === tt && (r = false) : (a += A, a === s && !E.done && (t.push(""), a = 0)), l = E, E = i2.next(), g += m.length;
23528
- }
23529
- u = t.at(-1), !a && u !== undefined && u.length > 0 && t.length > 1 && (t[t.length - 2] += t.pop());
23530
- };
23531
- var vt = (t) => {
23532
- const e = t.split(" ");
23533
- let s = e.length;
23534
- for (;s > 0 && !(S(e[s - 1]) > 0); )
23535
- s--;
23536
- return s === e.length ? t : e.slice(0, s).join(" ") + e.slice(s).join("");
23537
- };
23538
- var Et = (t, e, s = {}) => {
23539
- if (s.trim !== false && t.trim() === "")
23540
- return "";
23541
- let i2 = "", r, n;
23542
- const u = t.split(" "), a = gt(u);
23543
- let l = [""];
23544
- for (const [h, o] of u.entries()) {
23545
- s.trim !== false && (l[l.length - 1] = (l.at(-1) ?? "").trimStart());
23546
- let p = S(l.at(-1) ?? "");
23547
- if (h !== 0 && (p >= e && (s.wordWrap === false || s.trim === false) && (l.push(""), p = 0), (p > 0 || s.trim === false) && (l[l.length - 1] += " ", p++)), s.hard && a[h] > e) {
23548
- const v = e - p, F = 1 + Math.floor((a[h] - v - 1) / e);
23549
- Math.floor((a[h] - 1) / e) < F && l.push(""), G(l, o, e);
23550
- continue;
23551
- }
23552
- if (p + a[h] > e && p > 0 && a[h] > 0) {
23553
- if (s.wordWrap === false && p < e) {
23554
- G(l, o, e);
23555
- continue;
23556
- }
23557
- l.push("");
23558
- }
23559
- if (p + a[h] > e && s.wordWrap === false) {
23560
- G(l, o, e);
23561
- continue;
23562
- }
23563
- l[l.length - 1] += o;
23564
- }
23565
- s.trim !== false && (l = l.map((h) => vt(h)));
23566
- const E = l.join(`
23567
- `), g = E[Symbol.iterator]();
23568
- let m = g.next(), A = g.next(), V = 0;
23569
- for (;!m.done; ) {
23570
- const h = m.value, o = A.value;
23571
- if (i2 += h, h === T || h === Z) {
23572
- et.lastIndex = V + 1;
23573
- const F = et.exec(E)?.groups;
23574
- if (F?.code !== undefined) {
23575
- const d = Number.parseFloat(F.code);
23576
- r = d === Ft ? undefined : d;
23577
- } else
23578
- F?.uri !== undefined && (n = F.uri.length === 0 ? undefined : F.uri);
23579
- }
23580
- const p = r ? mt(r) : undefined;
23581
- o === `
23582
- ` ? (n && (i2 += it("")), r && p && (i2 += st(p))) : h === `
23583
- ` && (r && p && (i2 += st(r)), n && (i2 += it(n))), V += h.length, m = A, A = g.next();
23584
- }
23585
- return i2;
23586
- };
23587
- function K(t, e, s) {
23588
- return String(t).normalize().replaceAll(`\r
23589
- `, `
23590
- `).split(`
23591
- `).map((i2) => Et(i2, e, s)).join(`
23592
- `);
23593
- }
23594
- var At = ["up", "down", "left", "right", "space", "enter", "cancel"];
23595
- var _ = { actions: new Set(At), aliases: new Map([["k", "up"], ["j", "down"], ["h", "left"], ["l", "right"], ["\x03", "cancel"], ["escape", "cancel"]]), messages: { cancel: "Canceled", error: "Something went wrong" }, withGuide: true };
23596
- function H(t, e) {
23597
- if (typeof t == "string")
23598
- return _.aliases.get(t) === e;
23599
- for (const s of t)
23600
- if (s !== undefined && H(s, e))
23601
- return true;
23602
- return false;
23603
- }
23604
- function _t(t, e) {
23605
- if (t === e)
23606
- return;
23607
- const s = t.split(`
23608
- `), i2 = e.split(`
23609
- `), r = Math.max(s.length, i2.length), n = [];
23610
- for (let u = 0;u < r; u++)
23611
- s[u] !== i2[u] && n.push(u);
23612
- return { lines: n, numLinesBefore: s.length, numLinesAfter: i2.length, numLines: r };
23613
- }
23614
- var bt = globalThis.process.platform.startsWith("win");
23615
- var z2 = Symbol("clack:cancel");
23616
- function W(t, e) {
23617
- const s = t;
23618
- s.isTTY && s.setRawMode(e);
23619
- }
23620
- var nt = (t) => ("rows" in t) && typeof t.rows == "number" ? t.rows : 20;
23621
- class B {
23622
- input;
23623
- output;
23624
- _abortSignal;
23625
- rl;
23626
- opts;
23627
- _render;
23628
- _track = false;
23629
- _prevFrame = "";
23630
- _subscribers = new Map;
23631
- _cursor = 0;
23632
- state = "initial";
23633
- error = "";
23634
- value;
23635
- userInput = "";
23636
- constructor(e, s = true) {
23637
- const { input: i2 = q, output: r = R, render: n, signal: u, ...a } = e;
23638
- this.opts = a, this.onKeypress = this.onKeypress.bind(this), this.close = this.close.bind(this), this.render = this.render.bind(this), this._render = n.bind(this), this._track = s, this._abortSignal = u, this.input = i2, this.output = r;
23639
- }
23640
- unsubscribe() {
23641
- this._subscribers.clear();
23642
- }
23643
- setSubscriber(e, s) {
23644
- const i2 = this._subscribers.get(e) ?? [];
23645
- i2.push(s), this._subscribers.set(e, i2);
23646
- }
23647
- on(e, s) {
23648
- this.setSubscriber(e, { cb: s });
23649
- }
23650
- once(e, s) {
23651
- this.setSubscriber(e, { cb: s, once: true });
23652
- }
23653
- emit(e, ...s) {
23654
- const i2 = this._subscribers.get(e) ?? [], r = [];
23655
- for (const n of i2)
23656
- n.cb(...s), n.once && r.push(() => i2.splice(i2.indexOf(n), 1));
23657
- for (const n of r)
23658
- n();
23659
- }
23660
- prompt() {
23661
- return new Promise((e) => {
23662
- if (this._abortSignal) {
23663
- if (this._abortSignal.aborted)
23664
- return this.state = "cancel", this.close(), e(z2);
23665
- this._abortSignal.addEventListener("abort", () => {
23666
- this.state = "cancel", this.close();
23667
- }, { once: true });
23668
- }
23669
- this.rl = ot.createInterface({ input: this.input, tabSize: 2, prompt: "", escapeCodeTimeout: 50, terminal: true }), this.rl.prompt(), this.opts.initialUserInput !== undefined && this._setUserInput(this.opts.initialUserInput, true), this.input.on("keypress", this.onKeypress), W(this.input, true), this.output.on("resize", this.render), this.render(), this.once("submit", () => {
23670
- this.output.write(import_sisteransi.cursor.show), this.output.off("resize", this.render), W(this.input, false), e(this.value);
23671
- }), this.once("cancel", () => {
23672
- this.output.write(import_sisteransi.cursor.show), this.output.off("resize", this.render), W(this.input, false), e(z2);
23673
- });
23674
- });
23675
- }
23676
- _isActionKey(e, s) {
23677
- return e === "\t";
23678
- }
23679
- _setValue(e) {
23680
- this.value = e, this.emit("value", this.value);
23681
- }
23682
- _setUserInput(e, s) {
23683
- this.userInput = e ?? "", this.emit("userInput", this.userInput), s && this._track && this.rl && (this.rl.write(this.userInput), this._cursor = this.rl.cursor);
23684
- }
23685
- _clearUserInput() {
23686
- this.rl?.write(null, { ctrl: true, name: "u" }), this._setUserInput("");
23687
- }
23688
- onKeypress(e, s) {
23689
- if (this._track && s.name !== "return" && (s.name && this._isActionKey(e, s) && this.rl?.write(null, { ctrl: true, name: "h" }), this._cursor = this.rl?.cursor ?? 0, this._setUserInput(this.rl?.line)), this.state === "error" && (this.state = "active"), s?.name && (!this._track && _.aliases.has(s.name) && this.emit("cursor", _.aliases.get(s.name)), _.actions.has(s.name) && this.emit("cursor", s.name)), e && (e.toLowerCase() === "y" || e.toLowerCase() === "n") && this.emit("confirm", e.toLowerCase() === "y"), this.emit("key", e?.toLowerCase(), s), s?.name === "return") {
23690
- if (this.opts.validate) {
23691
- const i2 = this.opts.validate(this.value);
23692
- i2 && (this.error = i2 instanceof Error ? i2.message : i2, this.state = "error", this.rl?.write(this.userInput));
23693
- }
23694
- this.state !== "error" && (this.state = "submit");
23695
- }
23696
- H([e, s?.name, s?.sequence], "cancel") && (this.state = "cancel"), (this.state === "submit" || this.state === "cancel") && this.emit("finalize"), this.render(), (this.state === "submit" || this.state === "cancel") && this.close();
23697
- }
23698
- close() {
23699
- this.input.unpipe(), this.input.removeListener("keypress", this.onKeypress), this.output.write(`
23700
- `), W(this.input, false), this.rl?.close(), this.rl = undefined, this.emit(`${this.state}`, this.value), this.unsubscribe();
23701
- }
23702
- restoreCursor() {
23703
- const e = K(this._prevFrame, process.stdout.columns, { hard: true, trim: false }).split(`
23704
- `).length - 1;
23705
- this.output.write(import_sisteransi.cursor.move(-999, e * -1));
23706
- }
23707
- render() {
23708
- const e = K(this._render(this) ?? "", process.stdout.columns, { hard: true, trim: false });
23709
- if (e !== this._prevFrame) {
23710
- if (this.state === "initial")
23711
- this.output.write(import_sisteransi.cursor.hide);
23712
- else {
23713
- const s = _t(this._prevFrame, e), i2 = nt(this.output);
23714
- if (this.restoreCursor(), s) {
23715
- const r = Math.max(0, s.numLinesAfter - i2), n = Math.max(0, s.numLinesBefore - i2);
23716
- let u = s.lines.find((a) => a >= r);
23717
- if (u === undefined) {
23718
- this._prevFrame = e;
23719
- return;
23720
- }
23721
- if (s.lines.length === 1) {
23722
- this.output.write(import_sisteransi.cursor.move(0, u - n)), this.output.write(import_sisteransi.erase.lines(1));
23723
- const a = e.split(`
23724
- `);
23725
- this.output.write(a[u]), this._prevFrame = e, this.output.write(import_sisteransi.cursor.move(0, a.length - u - 1));
23726
- return;
23727
- } else if (s.lines.length > 1) {
23728
- if (r < n)
23729
- u = r;
23730
- else {
23731
- const l = u - n;
23732
- l > 0 && this.output.write(import_sisteransi.cursor.move(0, l));
23733
- }
23734
- this.output.write(import_sisteransi.erase.down());
23735
- const a = e.split(`
23736
- `).slice(u);
23737
- this.output.write(a.join(`
23738
- `)), this._prevFrame = e;
23739
- return;
23740
- }
23741
- }
23742
- this.output.write(import_sisteransi.erase.down());
23743
- }
23744
- this.output.write(e), this.state === "initial" && (this.state = "active"), this._prevFrame = e;
23745
- }
23746
- }
23747
- }
23748
- function wt(t, e) {
23749
- if (t === undefined || e.length === 0)
23750
- return 0;
23751
- const s = e.findIndex((i2) => i2.value === t);
23752
- return s !== -1 ? s : 0;
23753
- }
23754
- function Dt(t, e) {
23755
- return (e.label ?? String(e.value)).toLowerCase().includes(t.toLowerCase());
23756
- }
23757
- function St(t, e) {
23758
- if (e)
23759
- return t ? e : e[0];
23760
- }
23761
-
23762
- class Vt extends B {
23763
- filteredOptions;
23764
- multiple;
23765
- isNavigating = false;
23766
- selectedValues = [];
23767
- focusedValue;
23768
- #t = 0;
23769
- #s = "";
23770
- #i;
23771
- #e;
23772
- get cursor() {
23773
- return this.#t;
23774
- }
23775
- get userInputWithCursor() {
23776
- if (!this.userInput)
23777
- return D(["inverse", "hidden"], "_");
23778
- if (this._cursor >= this.userInput.length)
23779
- return `${this.userInput}█`;
23780
- const e = this.userInput.slice(0, this._cursor), [s, ...i2] = this.userInput.slice(this._cursor);
23781
- return `${e}${D("inverse", s)}${i2.join("")}`;
23782
- }
23783
- get options() {
23784
- return typeof this.#e == "function" ? this.#e() : this.#e;
23785
- }
23786
- constructor(e) {
23787
- super(e), this.#e = e.options;
23788
- const s = this.options;
23789
- this.filteredOptions = [...s], this.multiple = e.multiple === true, this.#i = e.filter ?? Dt;
23790
- let i2;
23791
- if (e.initialValue && Array.isArray(e.initialValue) ? this.multiple ? i2 = e.initialValue : i2 = e.initialValue.slice(0, 1) : !this.multiple && this.options.length > 0 && (i2 = [this.options[0].value]), i2)
23792
- for (const r of i2) {
23793
- const n = s.findIndex((u) => u.value === r);
23794
- n !== -1 && (this.toggleSelected(r), this.#t = n);
23795
- }
23796
- this.focusedValue = this.options[this.#t]?.value, this.on("key", (r, n) => this.#r(r, n)), this.on("userInput", (r) => this.#n(r));
23797
- }
23798
- _isActionKey(e, s) {
23799
- return e === "\t" || this.multiple && this.isNavigating && s.name === "space" && e !== undefined && e !== "";
23800
- }
23801
- #r(e, s) {
23802
- const i2 = s.name === "up", r = s.name === "down", n = s.name === "return";
23803
- i2 || r ? (this.#t = x(this.#t, i2 ? -1 : 1, this.filteredOptions), this.focusedValue = this.filteredOptions[this.#t]?.value, this.multiple || (this.selectedValues = [this.focusedValue]), this.isNavigating = true) : n ? this.value = St(this.multiple, this.selectedValues) : this.multiple ? this.focusedValue !== undefined && (s.name === "tab" || this.isNavigating && s.name === "space") ? this.toggleSelected(this.focusedValue) : this.isNavigating = false : (this.focusedValue && (this.selectedValues = [this.focusedValue]), this.isNavigating = false);
23804
- }
23805
- deselectAll() {
23806
- this.selectedValues = [];
23807
- }
23808
- toggleSelected(e) {
23809
- this.filteredOptions.length !== 0 && (this.multiple ? this.selectedValues.includes(e) ? this.selectedValues = this.selectedValues.filter((s) => s !== e) : this.selectedValues = [...this.selectedValues, e] : this.selectedValues = [e]);
23810
- }
23811
- #n(e) {
23812
- if (e !== this.#s) {
23813
- this.#s = e;
23814
- const s = this.options;
23815
- e ? this.filteredOptions = s.filter((n) => this.#i(e, n)) : this.filteredOptions = [...s];
23816
- const i2 = wt(this.focusedValue, this.filteredOptions);
23817
- this.#t = x(i2, 0, this.filteredOptions);
23818
- const r = this.filteredOptions[this.#t];
23819
- r && !r.disabled ? this.focusedValue = r.value : this.focusedValue = undefined, this.multiple || (this.focusedValue !== undefined ? this.toggleSelected(this.focusedValue) : this.deselectAll());
23820
- }
23821
- }
23822
- }
23823
- class yt extends B {
23824
- options;
23825
- cursor = 0;
23826
- #t;
23827
- getGroupItems(e) {
23828
- return this.options.filter((s) => s.group === e);
23829
- }
23830
- isGroupSelected(e) {
23831
- const s = this.getGroupItems(e), i2 = this.value;
23832
- return i2 === undefined ? false : s.every((r) => i2.includes(r.value));
23833
- }
23834
- toggleValue() {
23835
- const e = this.options[this.cursor];
23836
- if (this.value === undefined && (this.value = []), e.group === true) {
23837
- const s = e.value, i2 = this.getGroupItems(s);
23838
- this.isGroupSelected(s) ? this.value = this.value.filter((r) => i2.findIndex((n) => n.value === r) === -1) : this.value = [...this.value, ...i2.map((r) => r.value)], this.value = Array.from(new Set(this.value));
23839
- } else {
23840
- const s = this.value.includes(e.value);
23841
- this.value = s ? this.value.filter((i2) => i2 !== e.value) : [...this.value, e.value];
23842
- }
23843
- }
23844
- constructor(e) {
23845
- super(e, false);
23846
- const { options: s } = e;
23847
- this.#t = e.selectableGroups !== false, this.options = Object.entries(s).flatMap(([i2, r]) => [{ value: i2, group: true, label: i2 }, ...r.map((n) => ({ ...n, group: i2 }))]), this.value = [...e.initialValues ?? []], this.cursor = Math.max(this.options.findIndex(({ value: i2 }) => i2 === e.cursorAt), this.#t ? 0 : 1), this.on("cursor", (i2) => {
23848
- switch (i2) {
23849
- case "left":
23850
- case "up": {
23851
- this.cursor = this.cursor === 0 ? this.options.length - 1 : this.cursor - 1;
23852
- const r = this.options[this.cursor]?.group === true;
23853
- !this.#t && r && (this.cursor = this.cursor === 0 ? this.options.length - 1 : this.cursor - 1);
23854
- break;
23855
- }
23856
- case "down":
23857
- case "right": {
23858
- this.cursor = this.cursor === this.options.length - 1 ? 0 : this.cursor + 1;
23859
- const r = this.options[this.cursor]?.group === true;
23860
- !this.#t && r && (this.cursor = this.cursor === this.options.length - 1 ? 0 : this.cursor + 1);
23861
- break;
23862
- }
23863
- case "space":
23864
- this.toggleValue();
23865
- break;
23866
- }
23867
- });
23868
- }
23869
- }
23870
-
23871
- // ../../node_modules/@clack/prompts/dist/index.mjs
23872
- import { styleText as t, stripVTControlCharacters as ue } from "node:util";
23873
- import N2 from "node:process";
23874
- var import_sisteransi2 = __toESM(require_src(), 1);
23875
- function pt2() {
23876
- return N2.platform !== "win32" ? N2.env.TERM !== "linux" : !!N2.env.CI || !!N2.env.WT_SESSION || !!N2.env.TERMINUS_SUBLIME || N2.env.ConEmuTask === "{cmd::Cmder}" || N2.env.TERM_PROGRAM === "Terminus-Sublime" || N2.env.TERM_PROGRAM === "vscode" || N2.env.TERM === "xterm-256color" || N2.env.TERM === "alacritty" || N2.env.TERMINAL_EMULATOR === "JetBrains-JediTerm";
23877
- }
23878
- var ee = pt2();
23879
- var I2 = (e, r) => ee ? e : r;
23880
- var Re = I2("◆", "*");
23881
- var $e = I2("■", "x");
23882
- var de = I2("▲", "x");
23883
- var V = I2("◇", "o");
23884
- var he = I2("┌", "T");
23885
- var h = I2("│", "|");
23886
- var x2 = I2("└", "—");
23887
- var Oe = I2("┐", "T");
23888
- var Pe = I2("┘", "—");
23889
- var z3 = I2("●", ">");
23890
- var H2 = I2("○", " ");
23891
- var te = I2("◻", "[•]");
23892
- var U2 = I2("◼", "[+]");
23893
- var q2 = I2("◻", "[ ]");
23894
- var Ne = I2("▪", "•");
23895
- var se = I2("─", "-");
23896
- var pe = I2("╮", "+");
23897
- var We = I2("├", "+");
23898
- var me = I2("╯", "+");
23899
- var ge = I2("╰", "+");
23900
- var Ge = I2("╭", "+");
23901
- var fe = I2("●", "•");
23902
- var Fe = I2("◆", "*");
23903
- var ye = I2("▲", "!");
23904
- var Ee = I2("■", "x");
23905
- var yt2 = { limit: 1 / 0, ellipsis: "" };
23906
- var Et2 = { limit: 1 / 0, ellipsis: "", ellipsisWidth: 0 };
23907
- var Ce = "\x07";
23908
- var ke = "[";
23909
- var wt2 = "]";
23910
- var Se = `${wt2}8;;`;
23911
- var He = new RegExp(`(?:\\${ke}(?<code>\\d+)m|\\${Se}(?<uri>.*)${Ce})`, "y");
23912
- var ze = { light: I2("─", "-"), heavy: I2("━", "="), block: I2("█", "#") };
23913
- var Qe = `${t("gray", h)} `;
23914
-
23915
23667
  // ../auth/src/utils/envFile.ts
23916
23668
  init_src();
23917
23669
  init_src2();
23918
- var DEFAULT_AUTH_FILENAME = ".auth";
23919
- var DEFAULT_AUTH_DIR = ".uipath";
23920
- var DEFAULT_ENV_FILENAME = `${DEFAULT_AUTH_DIR}/${DEFAULT_AUTH_FILENAME}`;
23670
+ var DEFAULT_ENV_FILENAME = `${UIPATH_HOME_DIR}/${AUTH_FILENAME}`;
23921
23671
  var resolveEnvFilePathAsync = async (envFilePath = DEFAULT_ENV_FILENAME) => {
23922
23672
  const fs7 = getFileSystem();
23923
23673
  if (fs7.path.isAbsolute(envFilePath)) {
@@ -24085,11 +23835,7 @@ var getUserIdFromToken = (accessToken) => {
24085
23835
  }
24086
23836
  };
24087
23837
  var getLoginStatusWithDeps = async (options = {}, deps = {}) => {
24088
- const {
24089
- envFilePath = DEFAULT_ENV_FILENAME,
24090
- log = { verbose: false, format: "text", level: 1 },
24091
- ensureTokenValidityMinutes
24092
- } = options;
23838
+ const { envFilePath = DEFAULT_ENV_FILENAME, ensureTokenValidityMinutes } = options;
24093
23839
  const {
24094
23840
  resolveEnvFilePath = resolveEnvFilePathAsync,
24095
23841
  loadEnvFile = loadEnvFileAsync,
@@ -24101,7 +23847,7 @@ var getLoginStatusWithDeps = async (options = {}, deps = {}) => {
24101
23847
  try {
24102
23848
  const { absolutePath, errorMessage } = await resolveEnvFilePath(envFilePath);
24103
23849
  if (absolutePath === undefined) {
24104
- logger.error(errorMessage ?? "Failed to resolve env file path");
23850
+ logger.debug(errorMessage ?? "Failed to resolve env file path");
24105
23851
  return { loginStatus: "Not logged in" };
24106
23852
  }
24107
23853
  const credentials = await loadEnvFile({ envPath: absolutePath });
@@ -24120,8 +23866,7 @@ var getLoginStatusWithDeps = async (options = {}, deps = {}) => {
24120
23866
  const refreshed = await refreshTokenFn({
24121
23867
  refreshToken,
24122
23868
  tokenEndpoint: config2.tokenEndpoint,
24123
- clientId: config2.clientId,
24124
- log
23869
+ clientId: config2.clientId
24125
23870
  });
24126
23871
  accessToken = refreshed.accessToken;
24127
23872
  refreshToken = refreshed.refreshToken;
@@ -24161,7 +23906,6 @@ var getLoginStatusWithDeps = async (options = {}, deps = {}) => {
24161
23906
  if (result.loginStatus === "Logged in") {
24162
23907
  const userId = getUserIdFromToken(accessToken);
24163
23908
  const defaultProps = {
24164
- sessionId,
24165
23909
  ...userId ? { userId } : {},
24166
23910
  ...result.tenantId ? { tenantId: result.tenantId } : {},
24167
23911
  ...result.organizationId ? { organizationId: result.organizationId } : {},
@@ -24220,31 +23964,376 @@ async function createPimsConfig() {
24220
23964
  authToken: status.accessToken
24221
23965
  };
24222
23966
  }
24223
- // src/extract-error-message.ts
23967
+ // src/debug-http-client.ts
24224
23968
  init_src();
24225
- async function extractErrorMessage(error48) {
24226
- const err = error48;
24227
- const status = err.status || err.response?.status;
24228
- let extractedMessage;
24229
- if (err.response) {
24230
- const [bodyError, rawBody] = await catchError(err.response.text?.() ?? Promise.resolve(undefined));
24231
- if (!bodyError && rawBody) {
24232
- const [parseError, parsed] = catchError(() => JSON.parse(rawBody));
24233
- if (!parseError) {
24234
- extractedMessage = parsed?.message || parsed?.errorMessage || parsed?.title;
24235
- } else {
24236
- extractedMessage = rawBody;
24237
- }
23969
+ function buildCommonHeaders(config2, options) {
23970
+ const headers = {
23971
+ Authorization: `Bearer ${config2.authToken}`,
23972
+ Accept: "application/json"
23973
+ };
23974
+ if (options?.includeContentType !== false) {
23975
+ headers["Content-Type"] = "application/json";
23976
+ }
23977
+ if (config2.organizationUnitId) {
23978
+ headers["X-UIPATH-OrganizationUnitId"] = config2.organizationUnitId.toString();
23979
+ }
23980
+ if (config2.folderKey) {
23981
+ headers["x-uipath-folderkey"] = config2.folderKey;
23982
+ }
23983
+ return headers;
23984
+ }
23985
+ function buildOrchestratorUrl(config2, path3) {
23986
+ return `${config2.baseUrl}/${config2.organizationId}/${config2.tenantName}/orchestrator_${path3}`;
23987
+ }
23988
+ function buildPimsUrl2(config2, path3) {
23989
+ return `${config2.baseUrl}/${config2.organizationId}/${config2.tenantId}/pims_${path3}`;
23990
+ }
23991
+ async function orchestratorGet(config2, path3) {
23992
+ const url2 = buildOrchestratorUrl(config2, path3);
23993
+ const headers = buildCommonHeaders(config2);
23994
+ if (typeof process !== "undefined" && process.env?.DEBUG) {
23995
+ logger.info(`DEBUG GET: ${url2}`);
23996
+ }
23997
+ const response = await fetch(url2, { method: "GET", headers });
23998
+ if (!response.ok) {
23999
+ const errorText = await response.text();
24000
+ throw new Error(`API request failed: ${response.status} ${response.statusText} - ${errorText}`);
24001
+ }
24002
+ return response.json();
24003
+ }
24004
+ async function orchestratorPost(config2, path3, body) {
24005
+ const url2 = buildOrchestratorUrl(config2, path3);
24006
+ const headers = buildCommonHeaders(config2);
24007
+ if (typeof process !== "undefined" && process.env?.DEBUG) {
24008
+ logger.info(`DEBUG POST: ${url2}`);
24009
+ }
24010
+ const response = await fetch(url2, {
24011
+ method: "POST",
24012
+ headers,
24013
+ body: JSON.stringify(body)
24014
+ });
24015
+ if (!response.ok) {
24016
+ const errorText = await response.text();
24017
+ throw new Error(`API request failed: ${response.status} ${response.statusText} - ${errorText}`);
24018
+ }
24019
+ return response.json();
24020
+ }
24021
+ async function debugPimsGet(config2, path3) {
24022
+ const url2 = buildPimsUrl2(config2, path3);
24023
+ const headers = buildCommonHeaders(config2, { includeContentType: false });
24024
+ if (typeof process !== "undefined" && process.env?.DEBUG) {
24025
+ logger.info(`DEBUG PIMS GET: ${url2}`);
24026
+ }
24027
+ const response = await fetch(url2, { method: "GET", headers });
24028
+ if (!response.ok) {
24029
+ const errorText = await response.text();
24030
+ throw new Error(`PIMS API request failed: ${response.status} ${response.statusText} - ${errorText}`);
24031
+ }
24032
+ return response.json();
24033
+ }
24034
+ async function debugPimsPost(config2, path3, body) {
24035
+ const url2 = buildPimsUrl2(config2, path3);
24036
+ const headers = buildCommonHeaders(config2);
24037
+ if (typeof process !== "undefined" && process.env?.DEBUG) {
24038
+ logger.info(`DEBUG PIMS POST: ${url2}`);
24039
+ }
24040
+ const response = await fetch(url2, {
24041
+ method: "POST",
24042
+ headers,
24043
+ body: JSON.stringify(body)
24044
+ });
24045
+ if (!response.ok) {
24046
+ const errorText = await response.text();
24047
+ throw new Error(`PIMS API request failed: ${response.status} ${response.statusText} - ${errorText}`);
24048
+ }
24049
+ return response.json();
24050
+ }
24051
+ async function studioWebPost(config2, organizationName, path3, body, extraHeaders) {
24052
+ const url2 = `${config2.baseUrl}/${organizationName}/studio_/backend/api${path3}`;
24053
+ const headers = {
24054
+ Authorization: `Bearer ${config2.authToken}`,
24055
+ ...extraHeaders
24056
+ };
24057
+ if (typeof process !== "undefined" && process.env?.DEBUG) {
24058
+ logger.info(`DEBUG STUDIO POST: ${url2}`);
24059
+ }
24060
+ const isFormData = body instanceof FormData;
24061
+ const response = await fetch(url2, {
24062
+ method: "POST",
24063
+ headers: isFormData ? headers : { ...headers, "Content-Type": "application/json" },
24064
+ body: isFormData ? body : JSON.stringify(body)
24065
+ });
24066
+ if (!response.ok) {
24067
+ const errorText = await response.text();
24068
+ throw new Error(`Studio Web API request failed: ${response.status} ${response.statusText} - ${errorText}`);
24069
+ }
24070
+ return response.json();
24071
+ }
24072
+ async function studioWebDelete(config2, organizationName, path3) {
24073
+ const url2 = `${config2.baseUrl}/${organizationName}/studio_/backend/api${path3}`;
24074
+ const headers = {
24075
+ Authorization: `Bearer ${config2.authToken}`
24076
+ };
24077
+ if (typeof process !== "undefined" && process.env?.DEBUG) {
24078
+ logger.info(`DEBUG STUDIO DELETE: ${url2}`);
24079
+ }
24080
+ const response = await fetch(url2, { method: "DELETE", headers });
24081
+ if (!response.ok) {
24082
+ const errorText = await response.text();
24083
+ throw new Error(`Studio Web API delete failed: ${response.status} ${response.statusText} - ${errorText}`);
24084
+ }
24085
+ }
24086
+ // src/debug-service.ts
24087
+ init_src();
24088
+ function extractStartEventId(bpmnXml) {
24089
+ const match = bpmnXml.match(/<bpmn:startEvent\s+id="([^"]+)"/);
24090
+ return match?.[1] ?? "start";
24091
+ }
24092
+ async function getPersonalFolderKey(config2) {
24093
+ const result = await orchestratorGet(config2, "/api/Folders/GetAllForCurrentUser");
24094
+ const personal = result.PageItems?.find((f) => f.FolderType === "Personal");
24095
+ if (!personal) {
24096
+ throw new Error("No personal workspace folder found. Ensure your account has a personal workspace.");
24097
+ }
24098
+ return { key: personal.Key, id: personal.Id };
24099
+ }
24100
+ async function beginDebugSession(config2, inputArguments = "{}") {
24101
+ const body = {
24102
+ JobsCount: 1,
24103
+ JobPriority: null,
24104
+ SpecificPriorityValue: null,
24105
+ Strategy: "ModernJobsCount",
24106
+ AutopilotForRobots: {},
24107
+ ResumeOnSameContext: false,
24108
+ RunAsMe: false,
24109
+ RuntimeType: "Flow",
24110
+ Source: "StudioWeb",
24111
+ InputArguments: inputArguments
24112
+ };
24113
+ const result = await orchestratorPost(config2, "/api/robotdebug/BeginSession", body);
24114
+ if (!result.jobKey) {
24115
+ throw new Error("BeginSession returned success but no jobKey was provided");
24116
+ }
24117
+ return result;
24118
+ }
24119
+ async function createDebugInstance(config2, jobKey, solutionId, studioWebProjectId, entryPoint, processType = "Flow") {
24120
+ const body = {
24121
+ jobKey,
24122
+ debugArgs: {
24123
+ breakPoints: [],
24124
+ debugMode: 1,
24125
+ entryPoint,
24126
+ processType,
24127
+ simulationMode: 0,
24128
+ solutionId,
24129
+ studioWebProjectId,
24130
+ variables: {}
24238
24131
  }
24132
+ };
24133
+ const result = await debugPimsPost(config2, "/api/v1/debug-instances", body);
24134
+ if (!result.instanceId) {
24135
+ throw new Error(`debug-instances API returned no instanceId: ${JSON.stringify(result)}`);
24239
24136
  }
24240
- if (status === 401) {
24241
- return "Unauthorized (401). Run `uip login` to authenticate.";
24137
+ return result;
24138
+ }
24139
+ async function pollDebugInstanceStatus(config2, instanceId, callbacks, pollInterval = 2000, maxPolls = 300, jobKey) {
24140
+ let pollCount = 0;
24141
+ let lastStatus = "";
24142
+ const terminalStatuses = ["Completed", "Faulted", "Cancelled", "Failed"];
24143
+ const orchestratorTerminalStatuses = [
24144
+ "Successful",
24145
+ "Faulted",
24146
+ "Stopped",
24147
+ "Suspended"
24148
+ ];
24149
+ while (pollCount < maxPolls) {
24150
+ const status = await debugPimsGet(config2, `/api/v1/debug-instances/${instanceId}/element-executions`);
24151
+ if (status.status !== lastStatus) {
24152
+ lastStatus = status.status;
24153
+ const elementExecutions = status.elementExecutions.map((e) => ({
24154
+ elementId: e.elementId,
24155
+ elementType: e.elementType,
24156
+ status: e.status,
24157
+ startedAt: e.startedTimeUtc,
24158
+ completedAt: e.completedTimeUtc || undefined
24159
+ }));
24160
+ callbacks?.onStatusChange?.(status.status, elementExecutions);
24161
+ } else if (pollCount % 5 === 0) {
24162
+ const elapsed = (pollCount + 1) * pollInterval / 1000;
24163
+ logger.info(`Still polling... status: ${lastStatus} (${elapsed}s elapsed)`);
24164
+ }
24165
+ if (terminalStatuses.includes(status.status)) {
24166
+ logger.info(`Debug session reached terminal status: ${status.status}`);
24167
+ return status;
24168
+ }
24169
+ if (jobKey && pollCount > 0 && pollCount % 5 === 0) {
24170
+ const [, jobResponse] = await catchError(orchestratorGet(config2, `/odata/Jobs?$filter=Key eq '${jobKey}'&$top=1`));
24171
+ const jobState = jobResponse?.value?.[0]?.State;
24172
+ if (jobState && orchestratorTerminalStatuses.includes(jobState)) {
24173
+ const jobInfo = jobResponse?.value?.[0]?.Info ?? "";
24174
+ logger.info(`Orchestrator job reached terminal status: ${jobState}${jobInfo ? ` — ${jobInfo}` : ""}`);
24175
+ return { ...status, status: jobState };
24176
+ }
24177
+ }
24178
+ await new Promise((resolve2) => setTimeout(resolve2, pollInterval));
24179
+ pollCount++;
24180
+ }
24181
+ throw new Error(`Debug polling timed out after ${maxPolls * pollInterval / 1000}s`);
24182
+ }
24183
+ async function uploadSolutionToStudioWeb(config2, organizationName, uisFilePath, fs7) {
24184
+ const content = await fs7.readFile(uisFilePath);
24185
+ if (content === null) {
24186
+ throw new Error(`Failed to read file: ${uisFilePath}`);
24187
+ }
24188
+ const fileBuffer = content;
24189
+ const fileName = fs7.path.basename(uisFilePath);
24190
+ const formData = new FormData;
24191
+ const fileBlob = new Blob([fileBuffer], {
24192
+ type: "application/octet-stream"
24193
+ });
24194
+ formData.append("uploadFile", fileBlob, fileName);
24195
+ formData.append("telemetryData", JSON.stringify({ FirstRun: false }));
24196
+ const result = await studioWebPost(config2, organizationName, "/Solution/Import?desktopJit=true&useFileRest=true&enableUnifiedBuild=true", formData, { "x-uipath-tenantid": config2.tenantId || "" });
24197
+ if (!result.id || !result.projects || result.projects.length === 0) {
24198
+ throw new Error(`Solution import returned unexpected response: ${JSON.stringify(result)}`);
24199
+ }
24200
+ return result;
24201
+ }
24202
+ async function overwriteSolutionOnStudioWeb(config2, organizationName, uisFilePath, solutionId, fs7) {
24203
+ const content = await fs7.readFile(uisFilePath);
24204
+ if (content === null) {
24205
+ throw new Error(`Failed to read file: ${uisFilePath}`);
24206
+ }
24207
+ const fileBuffer = content;
24208
+ const fileName = fs7.path.basename(uisFilePath);
24209
+ const formData = new FormData;
24210
+ const fileBlob = new Blob([fileBuffer], {
24211
+ type: "application/octet-stream"
24212
+ });
24213
+ formData.append("UploadFile", fileBlob, fileName);
24214
+ const result = await studioWebPost(config2, organizationName, `/Solution/${solutionId}/Overwrite`, formData, { "x-uipath-tenantid": config2.tenantId || "" });
24215
+ if (!result.id || !result.projects || result.projects.length === 0) {
24216
+ throw new Error(`Solution overwrite returned unexpected response: ${JSON.stringify(result)}`);
24242
24217
  }
24243
- if (status === 403) {
24244
- return "Forbidden (403). Ensure the account has the required permissions.";
24218
+ return result;
24219
+ }
24220
+ async function uploadOrOverwriteSolution(config2, organizationName, uisFilePath, solutionId, fs7) {
24221
+ if (solutionId) {
24222
+ logger.info(`Attempting to overwrite existing solution ${solutionId} on Studio Web...`);
24223
+ const [overwriteError, overwriteResult] = await catchError(overwriteSolutionOnStudioWeb(config2, organizationName, uisFilePath, solutionId, fs7));
24224
+ if (!overwriteError) {
24225
+ return overwriteResult;
24226
+ }
24227
+ if (overwriteError.message.includes("404")) {
24228
+ logger.info(`Solution ${solutionId} not found on Studio Web. Importing as new solution...`);
24229
+ } else {
24230
+ throw overwriteError;
24231
+ }
24232
+ }
24233
+ logger.info("Importing new solution to Studio Web...");
24234
+ return uploadSolutionToStudioWeb(config2, organizationName, uisFilePath, fs7);
24235
+ }
24236
+ async function findSolutionFile(fs7, projectPath) {
24237
+ const parentDir = fs7.path.resolve(projectPath, "..");
24238
+ const [dirError, entries] = await catchError(fs7.readdir(parentDir));
24239
+ if (dirError) {
24240
+ logger.error(`Could not read parent directory for .uipx file: ${dirError.message}`);
24241
+ return;
24242
+ }
24243
+ const uipxFile = entries.find((entry) => entry.endsWith(".uipx"));
24244
+ if (!uipxFile) {
24245
+ logger.info("No .uipx solution file found in parent directory.");
24246
+ return;
24247
+ }
24248
+ const uipxPath = fs7.path.join(parentDir, uipxFile);
24249
+ const [readError, content] = await catchError(fs7.readFile(uipxPath, "utf-8"));
24250
+ if (readError || content === null) {
24251
+ logger.error(`Could not read .uipx file: ${readError?.message ?? "file returned null"}`);
24252
+ return;
24253
+ }
24254
+ const [parseError, parsed] = catchError(() => JSON.parse(content));
24255
+ if (parseError) {
24256
+ logger.error(`Could not parse .uipx file: ${parseError.message}`);
24257
+ return;
24258
+ }
24259
+ const solutionId = parsed.SolutionId;
24260
+ const projectId = parsed.Projects?.[0]?.Id;
24261
+ if (!solutionId) {
24262
+ logger.info("No SolutionId found in .uipx file.");
24263
+ return;
24264
+ }
24265
+ logger.info(`Found solution file: ${uipxFile} (SolutionId: ${solutionId})`);
24266
+ return {
24267
+ solutionId,
24268
+ projectId: projectId ?? crypto.randomUUID()
24269
+ };
24270
+ }
24271
+ async function buildSolutionPackage(fs7, solutionDir, execZip) {
24272
+ const absoluteSolutionDir = fs7.path.resolve(solutionDir);
24273
+ const solutionName = fs7.path.basename(absoluteSolutionDir) || "Solution";
24274
+ const tmpDir = fs7.env.tmpdir();
24275
+ const stagingDir = fs7.path.join(tmpDir, `.debug-solution-${Date.now()}`);
24276
+ await fs7.mkdir(stagingDir);
24277
+ await fs7.copyDirectory(absoluteSolutionDir, stagingDir);
24278
+ const uipxFiles = (await fs7.readdir(stagingDir)).filter((f) => f.endsWith(".uipx"));
24279
+ if (uipxFiles.length > 0) {
24280
+ const uipxContent = await fs7.readFile(fs7.path.join(stagingDir, uipxFiles[0]), "utf-8");
24281
+ if (uipxContent) {
24282
+ const uipx = JSON.parse(uipxContent);
24283
+ const storageJson = {
24284
+ SolutionId: uipx.SolutionId ?? crypto.randomUUID(),
24285
+ Projects: (uipx.Projects ?? []).map((p) => ({
24286
+ ProjectId: p.Id ?? crypto.randomUUID(),
24287
+ ProjectRelativePath: p.ProjectRelativePath ?? ""
24288
+ }))
24289
+ };
24290
+ await fs7.writeFile(fs7.path.join(stagingDir, "SolutionStorage.json"), JSON.stringify(storageJson));
24291
+ }
24292
+ }
24293
+ const allFiles = await collectFilesRecursive(fs7, stagingDir);
24294
+ const relFiles = allFiles.map((f) => fs7.path.relative(stagingDir, f));
24295
+ const uisPath = fs7.path.join(tmpDir, `${solutionName}-${Date.now()}.uis`);
24296
+ await fs7.rm(uisPath).catch(() => {});
24297
+ await execZip([uisPath, ...relFiles], stagingDir);
24298
+ await fs7.rm(stagingDir).catch(() => {});
24299
+ return uisPath;
24300
+ }
24301
+ async function collectFilesRecursive(fs7, dir) {
24302
+ const results = [];
24303
+ const entries = await fs7.readdir(dir);
24304
+ for (const entry of entries) {
24305
+ const fullPath = fs7.path.join(dir, entry);
24306
+ const stat2 = await fs7.stat(fullPath);
24307
+ if (stat2?.isDirectory()) {
24308
+ results.push(...await collectFilesRecursive(fs7, fullPath));
24309
+ } else {
24310
+ results.push(fullPath);
24311
+ }
24312
+ }
24313
+ return results;
24314
+ }
24315
+ async function updateSolutionFile(fs7, projectPath, newSolutionId) {
24316
+ const parentDir = fs7.path.resolve(projectPath, "..");
24317
+ const [dirError, entries] = await catchError(fs7.readdir(parentDir));
24318
+ if (dirError)
24319
+ return;
24320
+ const uipxFile = entries.find((entry) => entry.endsWith(".uipx"));
24321
+ if (!uipxFile)
24322
+ return;
24323
+ const uipxPath = fs7.path.join(parentDir, uipxFile);
24324
+ const [readError, content] = await catchError(fs7.readFile(uipxPath, "utf-8"));
24325
+ if (readError || content === null)
24326
+ return;
24327
+ const [parseError, parsed] = catchError(() => JSON.parse(content));
24328
+ if (parseError)
24329
+ return;
24330
+ parsed.SolutionId = newSolutionId;
24331
+ const [writeError] = await catchError(fs7.writeFile(uipxPath, JSON.stringify(parsed, null, 2)));
24332
+ if (writeError) {
24333
+ logger.error(`Warning: Could not update .uipx with new SolutionId: ${writeError.message}`);
24334
+ } else {
24335
+ logger.info(`Updated .uipx with Studio Web SolutionId: ${newSolutionId}`);
24245
24336
  }
24246
- const baseMessage = extractedMessage || err.message || "Unknown error";
24247
- return status ? `HTTP ${status}: ${baseMessage}` : baseMessage;
24248
24337
  }
24249
24338
  // src/query-string.ts
24250
24339
  function buildQueryString(params) {
@@ -24264,7 +24353,7 @@ async function withPimsCall(fn, errorMessage) {
24264
24353
  Message: errorMessage,
24265
24354
  Instructions: configError.message
24266
24355
  });
24267
- process.exitCode = 1;
24356
+ processContext.exit(1);
24268
24357
  return;
24269
24358
  }
24270
24359
  const [error48, result] = await catchError(fn(config2));
@@ -24276,16 +24365,32 @@ async function withPimsCall(fn, errorMessage) {
24276
24365
  Message: errorMessage,
24277
24366
  Instructions: msg
24278
24367
  });
24279
- process.exitCode = 1;
24368
+ processContext.exit(1);
24280
24369
  return;
24281
24370
  }
24282
24371
  return result;
24283
24372
  }
24284
24373
  export {
24285
24374
  withPimsCall,
24375
+ uploadSolutionToStudioWeb,
24376
+ uploadOrOverwriteSolution,
24377
+ updateSolutionFile,
24378
+ studioWebPost,
24379
+ studioWebDelete,
24380
+ pollDebugInstanceStatus,
24286
24381
  pimsPost,
24287
24382
  pimsGet,
24288
- extractErrorMessage,
24383
+ overwriteSolutionOnStudioWeb,
24384
+ orchestratorPost,
24385
+ orchestratorGet,
24386
+ getPersonalFolderKey,
24387
+ findSolutionFile,
24388
+ extractStartEventId,
24389
+ debugPimsPost,
24390
+ debugPimsGet,
24289
24391
  createPimsConfig,
24290
- buildQueryString
24392
+ createDebugInstance,
24393
+ buildSolutionPackage,
24394
+ buildQueryString,
24395
+ beginDebugSession
24291
24396
  };