@uipath/common 0.1.8 → 0.1.12

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 +881 -224
  2. package/package.json +7 -5
package/dist/index.js CHANGED
@@ -11,6 +11,12 @@ function catchError(fnOrPromise) {
11
11
  }
12
12
  try {
13
13
  const result = fnOrPromise();
14
+ if (result instanceof Promise) {
15
+ return result.then((data) => [undefined, data]).catch((error) => [
16
+ error instanceof Error ? error : new Error(String(error)),
17
+ undefined
18
+ ]);
19
+ }
14
20
  return [undefined, result];
15
21
  } catch (error) {
16
22
  return [
@@ -4651,10 +4657,8 @@ import { dirname } from "node:path";
4651
4657
 
4652
4658
  // src/output-context.ts
4653
4659
  function createStorage() {
4654
- try {
4655
- const { AsyncLocalStorage } = __require("node:async_hooks");
4656
- return new AsyncLocalStorage;
4657
- } catch {
4660
+ const [error, mod2] = catchError(() => __require("node:async_hooks"));
4661
+ if (error) {
4658
4662
  return {
4659
4663
  getStore: () => {
4660
4664
  return;
@@ -4662,6 +4666,7 @@ function createStorage() {
4662
4666
  run: (_store, fn) => fn()
4663
4667
  };
4664
4668
  }
4669
+ return new mod2.AsyncLocalStorage;
4665
4670
  }
4666
4671
  var outputStorage = createStorage();
4667
4672
  var globalSink;
@@ -4724,13 +4729,19 @@ class SimpleLogger {
4724
4729
  static isNode = typeof process !== "undefined" && !!process.versions?.node;
4725
4730
  static resolveLevel() {
4726
4731
  if (SimpleLogger.isNode) {
4727
- return SimpleLogger.parseLevel(process.env?.UIPCLI_LOG_LEVEL ?? "") ?? (process.env?.DEBUG ? 0 /* DEBUG */ : DEFAULT_LOG_LEVEL);
4728
- }
4729
- try {
4730
- if (typeof localStorage !== "undefined" && localStorage.getItem("debug")) {
4732
+ const explicitLevel = SimpleLogger.parseLevel(process.env?.UIPCLI_LOG_LEVEL ?? "");
4733
+ if (explicitLevel !== undefined)
4734
+ return explicitLevel;
4735
+ const debugVal = process.env?.DEBUG;
4736
+ if (debugVal === "true" || debugVal === "1") {
4731
4737
  return 0 /* DEBUG */;
4732
4738
  }
4733
- } catch {}
4739
+ return DEFAULT_LOG_LEVEL;
4740
+ }
4741
+ const [localStorageError, hasDebug] = catchError(() => typeof localStorage !== "undefined" && !!localStorage.getItem("debug"));
4742
+ if (!localStorageError && hasDebug) {
4743
+ return 0 /* DEBUG */;
4744
+ }
4734
4745
  return DEFAULT_LOG_LEVEL;
4735
4746
  }
4736
4747
  static parseLevel(value) {
@@ -4761,10 +4772,8 @@ class SimpleLogger {
4761
4772
  const path = this.logFilePath || getGlobalLogFilePath();
4762
4773
  if (!path)
4763
4774
  return;
4764
- try {
4765
- const timestamp2 = new Date().toISOString();
4766
- appendFileSync(path, `${timestamp2} ${formatted}`);
4767
- } catch {}
4775
+ const timestamp2 = new Date().toISOString();
4776
+ catchError(() => appendFileSync(path, `${timestamp2} ${formatted}`));
4768
4777
  }
4769
4778
  debug(message, ...args) {
4770
4779
  if (this.level > 0 /* DEBUG */)
@@ -4824,13 +4833,11 @@ class SimpleLogger {
4824
4833
  setGlobalLogFilePath(path);
4825
4834
  if (!path)
4826
4835
  return;
4827
- try {
4836
+ const [error] = catchError(() => {
4828
4837
  mkdirSync(dirname(path), { recursive: true });
4829
4838
  writeFileSync(path, "");
4830
- this.fileLoggingEnabled = true;
4831
- } catch {
4832
- this.fileLoggingEnabled = false;
4833
- }
4839
+ });
4840
+ this.fileLoggingEnabled = !error;
4834
4841
  }
4835
4842
  getLogFilePath() {
4836
4843
  return this.logFilePath || getGlobalLogFilePath();
@@ -4896,137 +4903,8 @@ function getOutputFilter() {
4896
4903
  return currentFilter;
4897
4904
  }
4898
4905
 
4899
- // ../../node_modules/@uipath/telemetry/dist/node.js
4900
- import { AsyncLocalStorage } from "async_hooks";
4901
- function node_context_storage_define_property(obj, key, value) {
4902
- if (key in obj)
4903
- Object.defineProperty(obj, key, {
4904
- value,
4905
- enumerable: true,
4906
- configurable: true,
4907
- writable: true
4908
- });
4909
- else
4910
- obj[key] = value;
4911
- return obj;
4912
- }
4913
-
4914
- class NodeContextStorage {
4915
- run(context, fn) {
4916
- return this.storage.run(context, fn);
4917
- }
4918
- getContext() {
4919
- return this.storage.getStore();
4920
- }
4921
- constructor() {
4922
- node_context_storage_define_property(this, "storage", new AsyncLocalStorage);
4923
- }
4924
- }
4925
- function telemetry_service_define_property(obj, key, value) {
4926
- if (key in obj)
4927
- Object.defineProperty(obj, key, {
4928
- value,
4929
- enumerable: true,
4930
- configurable: true,
4931
- writable: true
4932
- });
4933
- else
4934
- obj[key] = value;
4935
- return obj;
4936
- }
4937
-
4938
- class TelemetryService {
4939
- setOperationId(operationId) {
4940
- this.operationId = operationId;
4941
- }
4942
- setProvider(provider) {
4943
- this.telemetryProvider = provider;
4944
- }
4945
- setDefaultProperties(properties) {
4946
- this.defaultProperties = properties;
4947
- }
4948
- trackEvent(name, properties) {
4949
- const context = this.getCurrentContext();
4950
- const enrichedProperties = this.enrichPropertiesWithContext(properties, context);
4951
- this.telemetryProvider.trackEvent(name, enrichedProperties);
4952
- }
4953
- trackException(error, properties) {
4954
- const context = this.getCurrentContext();
4955
- const enrichedProperties = this.enrichPropertiesWithContext(properties, context);
4956
- this.telemetryProvider.trackException(error, enrichedProperties);
4957
- }
4958
- async trackRequest(name, fn, properties) {
4959
- const context = {
4960
- operationId: this.operationId ?? this.generateId(),
4961
- id: this.generateId()
4962
- };
4963
- const startTime = performance.now();
4964
- try {
4965
- const result = await this.contextStorage.run(context, fn);
4966
- const durationMs = performance.now() - startTime;
4967
- const enrichedProperties = this.enrichPropertiesWithContext(properties, context);
4968
- await this.telemetryProvider.trackRequest(name, durationMs, true, enrichedProperties);
4969
- return result;
4970
- } catch (error) {
4971
- const durationMs = performance.now() - startTime;
4972
- const err = error instanceof Error ? error : new Error(String(error));
4973
- const enrichedProperties = this.enrichPropertiesWithContext({
4974
- ...properties,
4975
- errorMessage: err.message
4976
- }, context);
4977
- await this.telemetryProvider.trackRequest(name, durationMs, false, enrichedProperties);
4978
- throw error;
4979
- }
4980
- }
4981
- async trackDependencyOperation(name, type2, fn, properties) {
4982
- const parentContext = this.getCurrentContext();
4983
- if (!parentContext)
4984
- throw new Error("trackDependencyOperation must be called within a trackRequest block.");
4985
- const childContext = {
4986
- operationId: parentContext.operationId,
4987
- parentId: parentContext.id,
4988
- id: this.generateId()
4989
- };
4990
- const startTime = performance.now();
4991
- try {
4992
- const result = await this.contextStorage.run(childContext, fn);
4993
- const durationMs = performance.now() - startTime;
4994
- const enrichedProperties = this.enrichPropertiesWithContext(properties, childContext);
4995
- await this.telemetryProvider.trackDependency(name, type2, durationMs, true, enrichedProperties);
4996
- return result;
4997
- } catch (error) {
4998
- const durationMs = performance.now() - startTime;
4999
- const err = error instanceof Error ? error : new Error(String(error));
5000
- const enrichedProperties = this.enrichPropertiesWithContext({
5001
- ...properties,
5002
- errorMessage: err.message
5003
- }, childContext);
5004
- await this.telemetryProvider.trackDependency(name, type2, durationMs, false, enrichedProperties);
5005
- throw error;
5006
- }
5007
- }
5008
- getCurrentContext() {
5009
- return this.contextStorage.getContext();
5010
- }
5011
- enrichPropertiesWithContext(properties, context) {
5012
- return {
5013
- ...this.defaultProperties,
5014
- ...properties,
5015
- ...context
5016
- };
5017
- }
5018
- generateId() {
5019
- return crypto.randomUUID().replaceAll("-", "");
5020
- }
5021
- constructor(telemetryProvider, contextStorage) {
5022
- telemetry_service_define_property(this, "telemetryProvider", undefined);
5023
- telemetry_service_define_property(this, "contextStorage", undefined);
5024
- telemetry_service_define_property(this, "operationId", undefined);
5025
- telemetry_service_define_property(this, "defaultProperties", undefined);
5026
- this.telemetryProvider = telemetryProvider;
5027
- this.contextStorage = contextStorage;
5028
- }
5029
- }
4906
+ // src/telemetry.ts
4907
+ import { NodeContextStorage, TelemetryService } from "@uipath/telemetry/node";
5030
4908
 
5031
4909
  // src/registry.ts
5032
4910
  import { execFileSync } from "node:child_process";
@@ -5034,16 +4912,15 @@ function readRegistryValue(keyPath, valueName) {
5034
4912
  if (process.platform !== "win32") {
5035
4913
  return "";
5036
4914
  }
5037
- try {
5038
- const output = execFileSync("reg", ["query", keyPath, "/v", valueName], {
5039
- encoding: "utf-8",
5040
- stdio: ["pipe", "pipe", "pipe"]
5041
- });
5042
- const match = output.match(new RegExp(`${valueName}\\s+REG_SZ\\s+(.+)`));
5043
- return match?.[1]?.trim() ?? "";
5044
- } catch {
4915
+ const [error, output] = catchError(() => execFileSync("reg", ["query", keyPath, "/v", valueName], {
4916
+ encoding: "utf-8",
4917
+ stdio: ["pipe", "pipe", "pipe"]
4918
+ }));
4919
+ if (error) {
5045
4920
  return "";
5046
4921
  }
4922
+ const match = output.match(new RegExp(`${valueName}\\s+REG_SZ\\s+(.+)`));
4923
+ return match?.[1]?.trim() ?? "";
5047
4924
  }
5048
4925
 
5049
4926
  // src/logger-telemetry-provider.ts
@@ -5059,7 +4936,7 @@ class LoggerTelemetryProvider {
5059
4936
  };
5060
4937
  }
5061
4938
  async trackEvent(eventName, properties) {
5062
- logger.info(formatMessage("Event", eventName, this.enrich(properties)));
4939
+ logger.debug(formatMessage("Event", eventName, this.enrich(properties)));
5063
4940
  }
5064
4941
  async trackException(error, properties) {
5065
4942
  logger.error(formatMessage("Exception", error.message, this.enrich({
@@ -5068,7 +4945,7 @@ class LoggerTelemetryProvider {
5068
4945
  })));
5069
4946
  }
5070
4947
  async trackRequest(name, duration, success, properties) {
5071
- logger.info(formatMessage("Request", name, this.enrich({
4948
+ logger.debug(formatMessage("Request", name, this.enrich({
5072
4949
  ...properties,
5073
4950
  duration: `${duration}ms`,
5074
4951
  success
@@ -5108,7 +4985,12 @@ function getGlobalTelemetryProperties() {
5108
4985
  return globalThis[GLOBAL_TELEMETRY_PROPS_KEY];
5109
4986
  }
5110
4987
  async function loadApplicationInsights() {
4988
+ const savedDebug = process.env.DEBUG;
4989
+ delete process.env.DEBUG;
5111
4990
  const [error, mod2] = await catchError(import("applicationinsights"));
4991
+ if (savedDebug !== undefined) {
4992
+ process.env.DEBUG = savedDebug;
4993
+ }
5112
4994
  if (error) {
5113
4995
  logger.warn(`[Telemetry] applicationinsights package not available: ${error.message}. Telemetry will use logger fallback.`);
5114
4996
  return;
@@ -5134,7 +5016,7 @@ class NodeAppInsightsTelemetryProvider {
5134
5016
  return false;
5135
5017
  this.appInsightsModule = mod2;
5136
5018
  logger.debug("[AppInsights] NodeAppInsightsTelemetryProvider initialized");
5137
- const client = new mod2.TelemetryClient(this.connectionString, {});
5019
+ const client = new mod2.TelemetryClient(this.connectionString);
5138
5020
  client.context.tags[client.context.keys.sessionId] = this._sessionId;
5139
5021
  this.client = client;
5140
5022
  this.initialized = true;
@@ -5157,13 +5039,11 @@ class NodeAppInsightsTelemetryProvider {
5157
5039
  if (!client)
5158
5040
  return;
5159
5041
  const merged = this.mergeProperties(properties);
5160
- logger.debug(`[AppInsights] trackEvent: ${eventName}`, merged ? JSON.stringify(merged) : "");
5161
- try {
5162
- client.trackEvent({
5163
- name: eventName,
5164
- properties: merged
5165
- });
5166
- } catch {
5042
+ const [error] = catchError(() => client.trackEvent({
5043
+ name: eventName,
5044
+ properties: merged
5045
+ }));
5046
+ if (error) {
5167
5047
  logger.debug(`[AppInsights] trackEvent failed for: ${eventName}`);
5168
5048
  }
5169
5049
  }
@@ -5172,13 +5052,11 @@ class NodeAppInsightsTelemetryProvider {
5172
5052
  if (!client)
5173
5053
  return;
5174
5054
  const merged = this.mergeProperties(properties);
5175
- logger.debug(`[AppInsights] trackException: ${error.message}`, merged ?? "");
5176
- try {
5177
- client.trackException({
5178
- exception: error,
5179
- properties: merged
5180
- });
5181
- } catch {
5055
+ const [trackError] = catchError(() => client.trackException({
5056
+ exception: error,
5057
+ properties: merged
5058
+ }));
5059
+ if (trackError) {
5182
5060
  logger.debug(`[AppInsights] trackException failed for: ${error.message}`);
5183
5061
  }
5184
5062
  }
@@ -5187,7 +5065,6 @@ class NodeAppInsightsTelemetryProvider {
5187
5065
  if (!client)
5188
5066
  return;
5189
5067
  const merged = this.mergeProperties(properties);
5190
- logger.debug(`[AppInsights] trackRequest: ${name} duration=${duration}ms success=${success}`, merged ?? "");
5191
5068
  client.trackRequest({
5192
5069
  name,
5193
5070
  url: name,
@@ -5202,14 +5079,12 @@ class NodeAppInsightsTelemetryProvider {
5202
5079
  if (!client)
5203
5080
  return;
5204
5081
  const merged = this.mergeProperties(properties);
5205
- logger.debug(`[AppInsights] trackDependency: ${name} type=${type2} duration=${duration}ms success=${success}`, merged ?? "");
5206
5082
  client.trackDependency({
5207
5083
  name,
5208
5084
  dependencyTypeName: type2,
5209
5085
  duration,
5210
5086
  resultCode: success ? "200" : "500",
5211
5087
  success,
5212
- data: name,
5213
5088
  properties: merged
5214
5089
  });
5215
5090
  }
@@ -5219,7 +5094,6 @@ class NodeAppInsightsTelemetryProvider {
5219
5094
  logger.warn(`[AppInsights] flush error (non-fatal): nil client`);
5220
5095
  return;
5221
5096
  }
5222
- logger.debug("[AppInsights] flush: sending buffered telemetry to cloud");
5223
5097
  const [error] = await catchError(new Promise((resolve, reject) => {
5224
5098
  client.flush({
5225
5099
  callback: (response) => {
@@ -5279,17 +5153,7 @@ async function getOrCreateProvider(connectionString) {
5279
5153
  }
5280
5154
 
5281
5155
  // src/telemetry.ts
5282
- var GLOBAL_SESSION_ID_KEY = "__uipcli_telemetry_session_id__";
5283
5156
  var GLOBAL_TELEMETRY_INSTANCE_KEY = "__uipcli_telemetry_instance__";
5284
- function getOrCreateSessionId() {
5285
- const existing = globalThis[GLOBAL_SESSION_ID_KEY];
5286
- if (typeof existing === "string")
5287
- return existing;
5288
- const id = crypto.randomUUID();
5289
- globalThis[GLOBAL_SESSION_ID_KEY] = id;
5290
- return id;
5291
- }
5292
- var sessionId = getOrCreateSessionId();
5293
5157
  var DEFAULT_AI_CONNECTION_STRING = Buffer.from("SW5zdHJ1bWVudGF0aW9uS2V5PTliZDM3NDgyLTgxMGUtNDQyYS1hYWE2LWQzOGVmNjVjNjY3NDtJbmdlc3Rpb25FbmRwb2ludD1odHRwczovL3dlc3RldXJvcGUtNS5pbi5hcHBsaWNhdGlvbmluc2lnaHRzLmF6dXJlLmNvbS87TGl2ZUVuZHBvaW50PWh0dHBzOi8vd2VzdGV1cm9wZS5saXZlZGlhZ25vc3RpY3MubW9uaXRvci5henVyZS5jb20vO0FwcGxpY2F0aW9uSWQ9MzU2OTdlZjEtOGJkMC00ZjE5LWEyN2MtZDg3Y2NhYzY2ZDJj", "base64").toString("utf-8");
5294
5158
  function getConnectionString() {
5295
5159
  return process.env.UIPATH_AI_CONNECTION_STRING || DEFAULT_AI_CONNECTION_STRING;
@@ -5352,15 +5216,14 @@ async function telemetryInit(defaultProperties) {
5352
5216
  const instance = new TelemetryService(provider, new NodeContextStorage);
5353
5217
  setGlobalTelemetryInstance(instance);
5354
5218
  _localTelemetryInstance = instance;
5355
- setGlobalTelemetryProperties({ sessionId, ...defaultProperties });
5356
- telemetry.setDefaultProperties({ sessionId, ...defaultProperties });
5219
+ if (defaultProperties) {
5220
+ setGlobalTelemetryProperties(defaultProperties);
5221
+ telemetry.setDefaultProperties(defaultProperties);
5222
+ }
5357
5223
  const isAppInsights = providerName === "NodeAppInsightsTelemetryProvider";
5358
- if (isAppInsights) {
5359
- logger.debug("[Telemetry] initialized successfully with AppInsights provider");
5360
- } else {
5224
+ if (!isAppInsights) {
5361
5225
  logger.debug(`[Telemetry] initialized with fallback provider (${providerName}). applicationinsights package not available.`);
5362
5226
  }
5363
- logger.debug(`[Telemetry] sessionId=${sessionId}`);
5364
5227
  }
5365
5228
  var FLUSH_SHUTDOWN_TIMEOUT_MS = 5000;
5366
5229
  async function telemetryFlushAndShutdown() {
@@ -5371,13 +5234,7 @@ async function telemetryFlushAndShutdown() {
5371
5234
  timer = setTimeout(() => resolve("timeout"), FLUSH_SHUTDOWN_TIMEOUT_MS);
5372
5235
  });
5373
5236
  const result = await Promise.race([
5374
- provider.flush().then(() => {
5375
- logger.debug("[Telemetry] flush complete");
5376
- return provider.shutdown();
5377
- }).then(() => {
5378
- logger.debug("[Telemetry] shutdown complete");
5379
- return "done";
5380
- }),
5237
+ provider.flush().then(() => provider.shutdown()).then(() => "done"),
5381
5238
  timeout
5382
5239
  ]);
5383
5240
  if (timer)
@@ -5425,7 +5282,7 @@ class FailureOutput {
5425
5282
  }
5426
5283
  }
5427
5284
  }
5428
- function printOutput(data, format = "table", logFn = console.log) {
5285
+ function printOutput(data, format = "table", logFn) {
5429
5286
  if (!data) {
5430
5287
  logFn("Empty response object. No data to display.");
5431
5288
  return;
@@ -5444,8 +5301,6 @@ function printOutput(data, format = "table", logFn = console.log) {
5444
5301
  const values = Object.values(item).map((v) => v ?? "").join("\t");
5445
5302
  logFn(values);
5446
5303
  });
5447
- } else if ("Message" in data && !("Result" in data)) {
5448
- logFn(data.Message);
5449
5304
  } else {
5450
5305
  const values = Object.values(data).map((v) => v ?? "").join("\t");
5451
5306
  logFn(values);
@@ -5453,12 +5308,13 @@ function printOutput(data, format = "table", logFn = console.log) {
5453
5308
  break;
5454
5309
  }
5455
5310
  default: {
5456
- if ("Data" in data && data.Data != null) {
5457
- const items = Array.isArray(data.Data) ? data.Data : [data.Data];
5458
- const logValue = "Log" in data ? data.Log : undefined;
5459
- printTable(items, logFn, logValue);
5460
- } else if ("Message" in data && !("Result" in data)) {
5461
- logFn(data.Message);
5311
+ if ("Data" in data && data.Data != null && !(Array.isArray(data.Data) && data.Data.length === 0)) {
5312
+ const logValue = data.Log;
5313
+ if (Array.isArray(data.Data)) {
5314
+ printResizableTable(data.Data, logFn, logValue);
5315
+ } else {
5316
+ printVerticalTable(data.Data, logFn, logValue);
5317
+ }
5462
5318
  } else {
5463
5319
  printTable([{ ...data }], logFn);
5464
5320
  }
@@ -5471,11 +5327,22 @@ function logOutput(data, format = "table") {
5471
5327
  printOutput(data, format, (msg) => sink.writeOut(`${msg}
5472
5328
  `));
5473
5329
  }
5474
- function printTable(data, logFn = console.log, externalLogValue) {
5330
+ function cellToString(val) {
5331
+ return val != null && typeof val === "object" ? JSON.stringify(val) : String(val ?? "");
5332
+ }
5333
+ function wrapText(text, width) {
5334
+ if (text.length <= width)
5335
+ return [text];
5336
+ const lines = [];
5337
+ for (let pos = 0;pos < text.length; pos += width) {
5338
+ lines.push(text.substring(pos, pos + width));
5339
+ }
5340
+ return lines;
5341
+ }
5342
+ function printTable(data, logFn, externalLogValue) {
5475
5343
  if (data.length === 0)
5476
5344
  return;
5477
5345
  const keys = Object.keys(data[0]).filter((key) => key !== "Code" && key !== "Log");
5478
- const cellToString = (val) => val != null && typeof val === "object" ? JSON.stringify(val) : String(val ?? "");
5479
5346
  const maxWidths = keys.map((key) => Math.max(key.length, ...data.map((item) => cellToString(item[key]).length)));
5480
5347
  const header = keys.map((key, i2) => key.padEnd(maxWidths[i2])).join(" | ");
5481
5348
  logFn(header);
@@ -5489,6 +5356,96 @@ function printTable(data, logFn = console.log, externalLogValue) {
5489
5356
  logFn(`Log: ${externalLogValue}`);
5490
5357
  }
5491
5358
  }
5359
+ function printVerticalTable(data, logFn = console.log, externalLogValue) {
5360
+ const keys = Object.keys(data).filter((key) => key !== "Code" && key !== "Log");
5361
+ if (keys.length === 0)
5362
+ return;
5363
+ const maxKeyWidth = Math.max(...keys.map((key) => key.length));
5364
+ keys.forEach((key) => {
5365
+ const keyCol = key.padEnd(maxKeyWidth);
5366
+ logFn(`${keyCol} | ${cellToString(data[key])}`);
5367
+ });
5368
+ if (externalLogValue) {
5369
+ logFn("");
5370
+ logFn(`Log: ${externalLogValue}`);
5371
+ }
5372
+ }
5373
+ function printResizableTable(data, logFn = console.log, externalLogValue) {
5374
+ if (data.length === 0)
5375
+ return;
5376
+ const keys = Object.keys(data[0]).filter((key) => key !== "Code" && key !== "Log");
5377
+ if (keys.length === 0)
5378
+ return;
5379
+ if (!process.stdout.isTTY) {
5380
+ printTable(data, logFn, externalLogValue);
5381
+ return;
5382
+ }
5383
+ const naturalWidths = keys.map((key) => Math.max(key.length, ...data.map((item) => cellToString(item[key]).length)));
5384
+ const separatorTotal = (keys.length - 1) * 3;
5385
+ const totalWidth = naturalWidths.reduce((a, b) => a + b, 0) + separatorTotal;
5386
+ const termWidth = process.stdout.columns || 120;
5387
+ if (totalWidth <= termWidth) {
5388
+ printTable(data, logFn, externalLogValue);
5389
+ return;
5390
+ }
5391
+ const overflow = totalWidth - termWidth;
5392
+ const MIN_COL_WIDTH = 10;
5393
+ const minWidths = keys.map((key) => Math.max(key.length, MIN_COL_WIDTH));
5394
+ let bestCol = -1;
5395
+ let bestCost = Infinity;
5396
+ for (let i2 = 0;i2 < keys.length; i2++) {
5397
+ const maxShrink = naturalWidths[i2] - minWidths[i2];
5398
+ if (maxShrink < overflow)
5399
+ continue;
5400
+ const newWidth = naturalWidths[i2] - overflow;
5401
+ let extraRows = 0;
5402
+ for (const item of data) {
5403
+ const cellLen = cellToString(item[keys[i2]]).length;
5404
+ if (cellLen > newWidth) {
5405
+ extraRows += Math.ceil(cellLen / newWidth) - 1;
5406
+ }
5407
+ }
5408
+ if (extraRows < bestCost) {
5409
+ bestCost = extraRows;
5410
+ bestCol = i2;
5411
+ }
5412
+ }
5413
+ const finalWidths = [...naturalWidths];
5414
+ if (bestCol !== -1) {
5415
+ finalWidths[bestCol] = naturalWidths[bestCol] - overflow;
5416
+ } else {
5417
+ let remaining = overflow;
5418
+ const colsByShrinkPotential = keys.map((_, i2) => ({
5419
+ index: i2,
5420
+ potential: naturalWidths[i2] - minWidths[i2]
5421
+ })).filter((c) => c.potential > 0).sort((a, b) => b.potential - a.potential);
5422
+ for (const col of colsByShrinkPotential) {
5423
+ if (remaining <= 0)
5424
+ break;
5425
+ const shrink = Math.min(remaining, col.potential);
5426
+ finalWidths[col.index] -= shrink;
5427
+ remaining -= shrink;
5428
+ }
5429
+ }
5430
+ const header = keys.map((key, i2) => key.padEnd(finalWidths[i2])).join(" | ");
5431
+ logFn(header);
5432
+ logFn(keys.map((_, i2) => "-".repeat(finalWidths[i2])).join("-|-"));
5433
+ data.forEach((item) => {
5434
+ const cellLines = keys.map((key, i2) => wrapText(cellToString(item[key]), finalWidths[i2]));
5435
+ const lineCount = Math.max(...cellLines.map((l) => l.length));
5436
+ for (let line = 0;line < lineCount; line++) {
5437
+ const row = keys.map((_, i2) => {
5438
+ const val = line < cellLines[i2].length ? cellLines[i2][line] : "";
5439
+ return val.padEnd(finalWidths[i2]);
5440
+ }).join(" | ");
5441
+ logFn(row);
5442
+ }
5443
+ });
5444
+ if (externalLogValue) {
5445
+ logFn("");
5446
+ logFn(`Log: ${externalLogValue}`);
5447
+ }
5448
+ }
5492
5449
  function toYaml(data) {
5493
5450
  return dump(data);
5494
5451
  }
@@ -5530,11 +5487,14 @@ var OutputFormatter;
5530
5487
  OutputFormatter.error = error;
5531
5488
  function log(data) {
5532
5489
  const format = getOutputFormat();
5490
+ const sink = getOutputSink();
5533
5491
  if (format === "json") {
5534
- console.error(JSON.stringify(data));
5492
+ sink.writeErr(`${JSON.stringify(data)}
5493
+ `);
5535
5494
  } else {
5536
5495
  for (const [key, value] of Object.entries(data)) {
5537
- console.error(`${key}: ${value}`);
5496
+ sink.writeErr(`${key}: ${value}
5497
+ `);
5538
5498
  }
5539
5499
  }
5540
5500
  }
@@ -5635,6 +5595,95 @@ function registerHelpAll(command) {
5635
5595
  throw new CommanderError(0, "commander.helpDisplayed", "(outputHelp)");
5636
5596
  });
5637
5597
  }
5598
+ // src/console-guard.ts
5599
+ function format(first, ...rest) {
5600
+ if (typeof first !== "string") {
5601
+ if (first === undefined && rest.length === 0)
5602
+ return "";
5603
+ return [first, ...rest].map(String).join(" ");
5604
+ }
5605
+ let i2 = 0;
5606
+ const result = first.replace(/%[sdifjoO%]/g, (spec) => {
5607
+ if (spec === "%%")
5608
+ return "%";
5609
+ if (i2 >= rest.length)
5610
+ return spec;
5611
+ const arg = rest[i2++];
5612
+ switch (spec) {
5613
+ case "%s":
5614
+ return String(arg);
5615
+ case "%d":
5616
+ case "%i":
5617
+ return String(parseInt(String(arg), 10));
5618
+ case "%f":
5619
+ return String(parseFloat(String(arg)));
5620
+ case "%j":
5621
+ case "%o":
5622
+ case "%O":
5623
+ try {
5624
+ return JSON.stringify(arg);
5625
+ } catch {
5626
+ return String(arg);
5627
+ }
5628
+ default:
5629
+ return spec;
5630
+ }
5631
+ });
5632
+ const extra = rest.slice(i2);
5633
+ if (extra.length > 0) {
5634
+ return result + " " + extra.map(String).join(" ");
5635
+ }
5636
+ return result;
5637
+ }
5638
+ function formatArgs(args) {
5639
+ return `${format(args[0], ...args.slice(1))}
5640
+ `;
5641
+ }
5642
+ var guardInstalled = false;
5643
+ var savedOriginals;
5644
+ function installConsoleGuard() {
5645
+ if (guardInstalled)
5646
+ return;
5647
+ const originals = {
5648
+ log: console.log,
5649
+ info: console.info,
5650
+ warn: console.warn,
5651
+ error: console.error,
5652
+ debug: console.debug
5653
+ };
5654
+ savedOriginals = originals;
5655
+ let reentrant = false;
5656
+ function guardedWriter(original) {
5657
+ return (...args) => {
5658
+ if (reentrant) {
5659
+ original.apply(console, args);
5660
+ return;
5661
+ }
5662
+ reentrant = true;
5663
+ try {
5664
+ getOutputSink().writeErr(formatArgs(args));
5665
+ } finally {
5666
+ reentrant = false;
5667
+ }
5668
+ };
5669
+ }
5670
+ console.log = guardedWriter(originals.log);
5671
+ console.info = guardedWriter(originals.info);
5672
+ console.warn = guardedWriter(originals.warn);
5673
+ console.error = guardedWriter(originals.error);
5674
+ console.debug = guardedWriter(originals.debug);
5675
+ guardInstalled = true;
5676
+ }
5677
+ function restoreConsole() {
5678
+ if (!savedOriginals)
5679
+ return;
5680
+ console.log = savedOriginals.log;
5681
+ console.info = savedOriginals.info;
5682
+ console.warn = savedOriginals.warn;
5683
+ console.error = savedOriginals.error;
5684
+ console.debug = savedOriginals.debug;
5685
+ guardInstalled = false;
5686
+ }
5638
5687
  // src/constants.ts
5639
5688
  var UIPATH_HOME_DIR = ".uipath";
5640
5689
  var AUTH_FILENAME = ".auth";
@@ -5645,6 +5694,109 @@ var DEFAULT_PAGE_SIZE = 50;
5645
5694
  var DEFAULT_AUTH_TIMEOUT_MS = 5 * 60 * 1000;
5646
5695
  var DEFAULT_FETCH_TIMEOUT_MS = 30000;
5647
5696
  var DEFAULT_REDIRECT_URI = "http://localhost:8104/oidc/login";
5697
+ // src/error-handler.ts
5698
+ var DEFAULT_401 = "Unauthorized (401). Run `uip login` to authenticate.";
5699
+ var DEFAULT_403 = "Forbidden (403). Ensure the account has the required permissions.";
5700
+ var DEFAULT_405 = "Method Not Allowed (405). The endpoint may not exist or the base URL may be incorrect.";
5701
+ async function extractErrorDetails(error, options) {
5702
+ const err = error !== null && error !== undefined && typeof error === "object" ? error : {};
5703
+ const response = err.response;
5704
+ const status = err.status ?? response?.status;
5705
+ let rawBody;
5706
+ let extractedMessage;
5707
+ let parsedBody;
5708
+ const textFn = response?.text?.bind(response);
5709
+ if (textFn) {
5710
+ const [bodyError, body] = await catchError((async () => textFn())());
5711
+ if (!bodyError && body) {
5712
+ rawBody = body;
5713
+ const [parseError, parsed] = catchError(() => JSON.parse(body));
5714
+ if (!parseError && parsed && typeof parsed === "object") {
5715
+ parsedBody = parsed;
5716
+ if (parsedBody.errors && typeof parsedBody.errors === "object") {
5717
+ for (const field of Object.values(parsedBody.errors)) {
5718
+ if (Array.isArray(field) && field.length > 0) {
5719
+ const first = field[0];
5720
+ if (first && typeof first.message === "string") {
5721
+ extractedMessage = first.message;
5722
+ break;
5723
+ }
5724
+ }
5725
+ }
5726
+ }
5727
+ if (!extractedMessage) {
5728
+ extractedMessage = typeof parsedBody.message === "string" ? parsedBody.message : typeof parsedBody.errorMessage === "string" ? parsedBody.errorMessage : typeof parsedBody.title === "string" ? parsedBody.title : undefined;
5729
+ }
5730
+ if (!extractedMessage) {
5731
+ extractedMessage = body;
5732
+ }
5733
+ } else {
5734
+ extractedMessage = body;
5735
+ }
5736
+ }
5737
+ }
5738
+ const rawMessage = typeof err.message === "string" ? err.message : "Unknown error";
5739
+ let message;
5740
+ if (status === 401) {
5741
+ message = DEFAULT_401;
5742
+ } else if (status === 403) {
5743
+ message = options?.forbiddenMessage ?? DEFAULT_403;
5744
+ } else if (status === 405) {
5745
+ message = DEFAULT_405;
5746
+ } else if (extractedMessage) {
5747
+ message = status ? `HTTP ${status}: ${extractedMessage}` : extractedMessage;
5748
+ } else if (status) {
5749
+ if (rawMessage === "Unknown error" && response) {
5750
+ const statusText = response.statusText;
5751
+ message = statusText ? `HTTP ${status} ${statusText}` : `HTTP ${status} - request failed`;
5752
+ } else {
5753
+ message = `HTTP ${status}: ${rawMessage}`;
5754
+ }
5755
+ } else {
5756
+ message = rawMessage;
5757
+ }
5758
+ let details = rawMessage;
5759
+ if (rawBody) {
5760
+ if (parsedBody) {
5761
+ const extra = {};
5762
+ if (parsedBody.errorCode)
5763
+ extra.errorCode = parsedBody.errorCode;
5764
+ if (parsedBody.details)
5765
+ extra.details = parsedBody.details;
5766
+ if (parsedBody.errors != null)
5767
+ extra.errors = parsedBody.errors;
5768
+ if (parsedBody.data && typeof parsedBody.data === "object" && Object.keys(parsedBody.data).length > 0) {
5769
+ extra.data = parsedBody.data;
5770
+ }
5771
+ details = Object.keys(extra).length > 0 ? JSON.stringify(extra) : rawBody;
5772
+ } else {
5773
+ details = rawBody;
5774
+ }
5775
+ } else if (typeof err.message === "string") {
5776
+ details = err.message;
5777
+ } else {
5778
+ details = String(error);
5779
+ }
5780
+ return { message, details };
5781
+ }
5782
+ async function extractErrorMessage(error, options) {
5783
+ const { message } = await extractErrorDetails(error, options);
5784
+ return message;
5785
+ }
5786
+ function extractErrorMessageSync(error) {
5787
+ if (error instanceof Error) {
5788
+ return error.message;
5789
+ }
5790
+ if (typeof error === "object" && error !== null) {
5791
+ if ("status" in error && error.status === 401) {
5792
+ return DEFAULT_401;
5793
+ }
5794
+ if ("message" in error && typeof error.message === "string") {
5795
+ return error.message;
5796
+ }
5797
+ }
5798
+ return String(error);
5799
+ }
5648
5800
  // ../../node_modules/jsonpath-plus/dist/index-node-esm.js
5649
5801
  import vm from "vm";
5650
5802
 
@@ -7068,24 +7220,512 @@ class JsonPathError extends Error {
7068
7220
  this.name = "JsonPathError";
7069
7221
  }
7070
7222
  }
7223
+ // src/polling/abort-controller.ts
7224
+ var created = false;
7225
+ function createPollAbortController() {
7226
+ const controller = new AbortController;
7227
+ if (typeof process === "undefined" || typeof process.on !== "function") {
7228
+ return controller;
7229
+ }
7230
+ if (created) {
7231
+ logger.warn("[pollUntil] createPollAbortController called more than once — listeners may accumulate");
7232
+ }
7233
+ created = true;
7234
+ const onSignal = () => {
7235
+ cleanup();
7236
+ controller.abort(new Error("Process interrupted (SIGINT/SIGTERM)"));
7237
+ };
7238
+ const cleanup = () => {
7239
+ process.removeListener("SIGINT", onSignal);
7240
+ process.removeListener("SIGTERM", onSignal);
7241
+ process.removeListener("exit", cleanup);
7242
+ };
7243
+ process.on("SIGINT", onSignal);
7244
+ process.on("SIGTERM", onSignal);
7245
+ process.on("exit", cleanup);
7246
+ controller.signal.addEventListener("abort", () => {
7247
+ cleanup();
7248
+ }, { once: true });
7249
+ return controller;
7250
+ }
7251
+ // src/polling/format-utils.ts
7252
+ function msToDuration(ms) {
7253
+ if (!Number.isFinite(ms) || ms < 0) {
7254
+ return "00:00:00";
7255
+ }
7256
+ const totalSec = Math.floor(ms / 1000);
7257
+ const h = Math.floor(totalSec / 3600);
7258
+ const m = Math.floor(totalSec % 3600 / 60);
7259
+ const s = totalSec % 60;
7260
+ return [h, m, s].map((v) => String(v).padStart(2, "0")).join(":");
7261
+ }
7262
+ // src/polling/types.ts
7263
+ var PollOutcome = {
7264
+ Completed: "completed",
7265
+ Timeout: "timeout",
7266
+ Interrupted: "interrupted",
7267
+ Aborted: "aborted",
7268
+ Failed: "failed"
7269
+ };
7270
+ var ErrorDecision = {
7271
+ Abort: "abort"
7272
+ };
7273
+ var POLL_DEFAULTS = {
7274
+ intervalMs: 5000,
7275
+ timeoutMs: 1800000,
7276
+ maxConsecutiveErrors: 3,
7277
+ logIntervalMs: 30000,
7278
+ logPrefix: "wait"
7279
+ };
7280
+ var BACKOFF_DEFAULTS = {
7281
+ initialMs: 1000,
7282
+ multiplier: 2,
7283
+ maxMs: 30000,
7284
+ jitter: 0.5
7285
+ };
7286
+ var MIN_INTERVAL_MS = 100;
7287
+
7288
+ // src/polling/poll-until.ts
7289
+ function resolveIntervalFn(options) {
7290
+ if (typeof options.intervalMs === "function") {
7291
+ return options.intervalMs;
7292
+ }
7293
+ const staticInterval = options.intervalMs ?? POLL_DEFAULTS.intervalMs;
7294
+ return () => staticInterval;
7295
+ }
7296
+ function resolveBackoffFn(options) {
7297
+ if (!options.backoff)
7298
+ return;
7299
+ const config = options.backoff === true ? { ...BACKOFF_DEFAULTS } : {
7300
+ initialMs: options.backoff.initialMs ?? BACKOFF_DEFAULTS.initialMs,
7301
+ multiplier: options.backoff.multiplier ?? BACKOFF_DEFAULTS.multiplier,
7302
+ maxMs: options.backoff.maxMs ?? BACKOFF_DEFAULTS.maxMs,
7303
+ jitter: Math.min(1, Math.max(0, options.backoff.jitter ?? BACKOFF_DEFAULTS.jitter))
7304
+ };
7305
+ return (errorCount) => {
7306
+ const exponent = Math.min(errorCount - 1, 30);
7307
+ const raw = Math.min(config.initialMs * config.multiplier ** exponent, config.maxMs);
7308
+ if (config.jitter > 0) {
7309
+ const jitterAmount = raw * config.jitter;
7310
+ return raw - jitterAmount * Math.random();
7311
+ }
7312
+ return raw;
7313
+ };
7314
+ }
7315
+ function clampInterval(raw, label, prefix) {
7316
+ if (!Number.isFinite(raw) || Number.isNaN(raw)) {
7317
+ if (label) {
7318
+ logger.warn(`[${prefix}] ${label} — intervalMs returned ${raw}, falling back to ${POLL_DEFAULTS.intervalMs}ms`);
7319
+ }
7320
+ return POLL_DEFAULTS.intervalMs;
7321
+ }
7322
+ if (raw < MIN_INTERVAL_MS) {
7323
+ if (label) {
7324
+ logger.warn(`[${prefix}] ${label} — intervalMs ${raw}ms clamped to minimum ${MIN_INTERVAL_MS}ms`);
7325
+ }
7326
+ return MIN_INTERVAL_MS;
7327
+ }
7328
+ return raw;
7329
+ }
7330
+ function abortError(signal) {
7331
+ const reason = signal.reason;
7332
+ if (reason instanceof Error && reason.name === "AbortError") {
7333
+ return reason;
7334
+ }
7335
+ const msg = reason instanceof Error ? reason.message : typeof reason === "string" || typeof reason === "number" ? String(reason) : "Aborted";
7336
+ const err = new Error(msg);
7337
+ err.name = "AbortError";
7338
+ return err;
7339
+ }
7340
+ function interruptibleSleep(ms, signal) {
7341
+ return new Promise((resolve, reject) => {
7342
+ if (signal?.aborted) {
7343
+ reject(abortError(signal));
7344
+ return;
7345
+ }
7346
+ let onAbort;
7347
+ const cleanup = () => {
7348
+ if (onAbort) {
7349
+ signal?.removeEventListener("abort", onAbort);
7350
+ }
7351
+ };
7352
+ const timer = setTimeout(() => {
7353
+ cleanup();
7354
+ resolve();
7355
+ }, ms);
7356
+ if (signal) {
7357
+ onAbort = () => {
7358
+ clearTimeout(timer);
7359
+ cleanup();
7360
+ reject(abortError(signal));
7361
+ };
7362
+ signal.addEventListener("abort", onAbort, { once: true });
7363
+ }
7364
+ });
7365
+ }
7366
+ function sanitizeMaxErrors(value) {
7367
+ if (value === undefined)
7368
+ return POLL_DEFAULTS.maxConsecutiveErrors;
7369
+ if (!Number.isFinite(value) || value < 0)
7370
+ return 0;
7371
+ return Math.floor(value);
7372
+ }
7373
+ function resolveConfig(options) {
7374
+ const timeoutMs = Math.max(0, options.timeoutMs ?? POLL_DEFAULTS.timeoutMs);
7375
+ const startTime = Date.now();
7376
+ return {
7377
+ fn: options.fn,
7378
+ until: options.until,
7379
+ getStatus: options.getStatus,
7380
+ signal: options.signal,
7381
+ label: options.label,
7382
+ beforePoll: options.beforePoll,
7383
+ onPoll: options.onPoll,
7384
+ onStatusChange: options.onStatusChange,
7385
+ onError: options.onError,
7386
+ onComplete: options.onComplete,
7387
+ onTimeout: options.onTimeout,
7388
+ onInterrupt: options.onInterrupt,
7389
+ timeoutMs,
7390
+ maxConsecutiveErrors: sanitizeMaxErrors(options.maxConsecutiveErrors),
7391
+ logIntervalMs: options.logIntervalMs ?? POLL_DEFAULTS.logIntervalMs,
7392
+ logPrefix: options.logPrefix ?? POLL_DEFAULTS.logPrefix,
7393
+ getInterval: resolveIntervalFn(options),
7394
+ getErrorInterval: resolveBackoffFn(options),
7395
+ startTime,
7396
+ deadline: timeoutMs > 0 ? startTime + timeoutMs : 0
7397
+ };
7398
+ }
7399
+ function elapsed(cfg) {
7400
+ return Date.now() - cfg.startTime;
7401
+ }
7402
+ function isPastDeadline(cfg) {
7403
+ return cfg.deadline > 0 && Date.now() >= cfg.deadline;
7404
+ }
7405
+ function buildContext(cfg, state) {
7406
+ return {
7407
+ pollCount: state.pollCount,
7408
+ elapsedMs: elapsed(cfg),
7409
+ lastResult: state.lastResult,
7410
+ lastStatus: state.lastStatus
7411
+ };
7412
+ }
7413
+ function truncateMessage(msg, maxLen = 500) {
7414
+ return msg.length > maxLen ? `${msg.slice(0, maxLen)}...` : msg;
7415
+ }
7416
+ async function handlePollError(error, errorSource, cfg, state) {
7417
+ state.consecutiveErrors++;
7418
+ const onError = cfg.onError;
7419
+ if (onError) {
7420
+ const [callbackErr, decision] = await catchError(Promise.resolve().then(() => onError(error, state.consecutiveErrors)));
7421
+ if (callbackErr) {
7422
+ if (cfg.label) {
7423
+ logger.warn(`[${cfg.logPrefix}] ${cfg.label} — onError callback threw: ${callbackErr.message}`);
7424
+ }
7425
+ } else if (decision === ErrorDecision.Abort) {
7426
+ return "abort";
7427
+ }
7428
+ }
7429
+ if (cfg.label) {
7430
+ const maxLabel = cfg.maxConsecutiveErrors === 0 ? "unlimited" : String(cfg.maxConsecutiveErrors);
7431
+ logger.warn(`[${cfg.logPrefix}] ${cfg.label} — ${errorSource} error (${state.consecutiveErrors}/${maxLabel}): ${error.message}, retrying...`);
7432
+ }
7433
+ if (cfg.maxConsecutiveErrors > 0 && state.consecutiveErrors >= cfg.maxConsecutiveErrors) {
7434
+ return "failed";
7435
+ }
7436
+ return;
7437
+ }
7438
+ function boundToDeadline(interval, deadline) {
7439
+ if (deadline > 0) {
7440
+ return Math.min(interval, Math.max(0, deadline - Date.now()));
7441
+ }
7442
+ return interval;
7443
+ }
7444
+ function computeSleepMs(cfg, ctx) {
7445
+ const interval = clampInterval(cfg.getInterval(ctx), cfg.label, cfg.logPrefix);
7446
+ return boundToDeadline(interval, cfg.deadline);
7447
+ }
7448
+ function computeErrorSleepMs(cfg, state, ctx) {
7449
+ if (cfg.getErrorInterval) {
7450
+ const interval = clampInterval(cfg.getErrorInterval(state.consecutiveErrors), cfg.label, cfg.logPrefix);
7451
+ return boundToDeadline(interval, cfg.deadline);
7452
+ }
7453
+ return computeSleepMs(cfg, ctx);
7454
+ }
7455
+ async function doSleep(ms, cfg) {
7456
+ if (ms > 0) {
7457
+ const [err] = await catchError(interruptibleSleep(ms, cfg.signal));
7458
+ if (err) {
7459
+ if (isAbortError(err))
7460
+ return;
7461
+ throw err;
7462
+ }
7463
+ }
7464
+ }
7465
+ function isAbortError(err) {
7466
+ if (!(err instanceof Error))
7467
+ return false;
7468
+ return err.name === "AbortError";
7469
+ }
7470
+ async function safeCallback(label, name, fn, prefix) {
7471
+ const [err] = await catchError(Promise.resolve().then(() => fn()));
7472
+ if (err && label) {
7473
+ logger.warn(`[${prefix}] ${label} — ${name} callback threw: ${err.message}`);
7474
+ }
7475
+ }
7476
+ async function processSuccessfulPoll(result, cfg, state) {
7477
+ state.consecutiveErrors = 0;
7478
+ if (cfg.onPoll) {
7479
+ await safeCallback(cfg.label, "onPoll", () => cfg.onPoll?.(result, elapsed(cfg)), cfg.logPrefix);
7480
+ }
7481
+ if (cfg.getStatus) {
7482
+ const getStatus = cfg.getStatus;
7483
+ const [statusErr, newStatus] = catchError(() => getStatus(result));
7484
+ if (statusErr) {
7485
+ if (cfg.label) {
7486
+ logger.warn(`[${cfg.logPrefix}] ${cfg.label} — getStatus threw: ${statusErr.message}`);
7487
+ }
7488
+ } else {
7489
+ if (state.lastStatus !== undefined && newStatus !== state.lastStatus) {
7490
+ const oldStatus = state.lastStatus ?? "";
7491
+ await safeCallback(cfg.label, "onStatusChange", () => cfg.onStatusChange?.(newStatus, oldStatus, result), cfg.logPrefix);
7492
+ if (cfg.label) {
7493
+ logger.info(`[${cfg.logPrefix}] ${cfg.label} — status changed: ${state.lastStatus} → ${newStatus}`);
7494
+ }
7495
+ }
7496
+ state.lastStatus = newStatus;
7497
+ }
7498
+ }
7499
+ logProgress(cfg, state);
7500
+ state.lastResult = result;
7501
+ state.pollCount++;
7502
+ }
7503
+ function logProgress(cfg, state) {
7504
+ if (!cfg.label || cfg.logIntervalMs <= 0)
7505
+ return;
7506
+ const now = elapsed(cfg);
7507
+ if (now - state.lastLogAt >= cfg.logIntervalMs) {
7508
+ const statusStr = state.lastStatus ? `status: ${state.lastStatus}, ` : "";
7509
+ logger.info(`[${cfg.logPrefix}] ${cfg.label} — ${statusStr}elapsed: ${msToDuration(now)}`);
7510
+ state.lastLogAt = now;
7511
+ }
7512
+ }
7513
+ function buildResult(data, outcome, cfg) {
7514
+ return { data, outcome, elapsedMs: elapsed(cfg) };
7515
+ }
7516
+ async function handleCompleted(result, cfg) {
7517
+ await safeCallback(cfg.label, "onComplete", () => cfg.onComplete?.(result, elapsed(cfg)), cfg.logPrefix);
7518
+ if (cfg.label) {
7519
+ let statusStr = "";
7520
+ if (cfg.getStatus) {
7521
+ const getStatus = cfg.getStatus;
7522
+ const [, status] = catchError(() => getStatus(result));
7523
+ if (status != null)
7524
+ statusStr = ` ${status}`;
7525
+ }
7526
+ logger.info(`[${cfg.logPrefix}] ${cfg.label} — reached terminal status:${statusStr} (took ${msToDuration(elapsed(cfg))})`);
7527
+ }
7528
+ return buildResult(result, PollOutcome.Completed, cfg);
7529
+ }
7530
+ async function handleTimeout(cfg, state) {
7531
+ await safeCallback(cfg.label, "onTimeout", () => cfg.onTimeout?.(state.lastResult, elapsed(cfg)), cfg.logPrefix);
7532
+ if (cfg.label) {
7533
+ const statusStr = state.lastStatus ? ` Last status: ${state.lastStatus}` : "";
7534
+ logger.info(`[${cfg.logPrefix}] ${cfg.label} — timed out after ${msToDuration(elapsed(cfg))}.${statusStr}`);
7535
+ }
7536
+ return buildResult(state.lastResult, PollOutcome.Timeout, cfg);
7537
+ }
7538
+ async function handleInterrupted(cfg, state) {
7539
+ await safeCallback(cfg.label, "onInterrupt", () => cfg.onInterrupt?.(state.lastResult, elapsed(cfg)), cfg.logPrefix);
7540
+ if (cfg.label) {
7541
+ const statusStr = state.lastStatus ? ` Last status: ${state.lastStatus}` : "";
7542
+ logger.info(`[${cfg.logPrefix}] ${cfg.label} — interrupted.${statusStr}`);
7543
+ }
7544
+ return buildResult(state.lastResult, PollOutcome.Interrupted, cfg);
7545
+ }
7546
+ function handleAborted(cfg, state, error) {
7547
+ const result = buildResult(state.lastResult, PollOutcome.Aborted, cfg);
7548
+ if (error) {
7549
+ result.error = error;
7550
+ }
7551
+ return result;
7552
+ }
7553
+ function handleFailed(cfg, state, error) {
7554
+ if (cfg.label) {
7555
+ logger.warn(`[${cfg.logPrefix}] ${cfg.label} — polling failed after ${state.consecutiveErrors} consecutive errors. Last error: ${truncateMessage(error.message)}`);
7556
+ }
7557
+ const result = buildResult(state.lastResult, PollOutcome.Failed, cfg);
7558
+ result.error = error;
7559
+ return result;
7560
+ }
7561
+ function setupSignalGuard(cfg, state) {
7562
+ const onAbort = () => {
7563
+ state.interrupted = true;
7564
+ };
7565
+ if (cfg.signal) {
7566
+ if (cfg.signal.aborted) {
7567
+ state.interrupted = true;
7568
+ } else {
7569
+ cfg.signal.addEventListener("abort", onAbort, { once: true });
7570
+ }
7571
+ }
7572
+ return {
7573
+ cleanup: () => {
7574
+ cfg.signal?.removeEventListener("abort", onAbort);
7575
+ }
7576
+ };
7577
+ }
7578
+ function logStart(options, cfg) {
7579
+ if (!cfg.label)
7580
+ return;
7581
+ let intervalDesc;
7582
+ if (typeof options.intervalMs === "function") {
7583
+ intervalDesc = "dynamic";
7584
+ } else {
7585
+ const [intervalErr, intervalVal] = catchError(() => cfg.getInterval({ pollCount: 0, elapsedMs: 0 }));
7586
+ intervalDesc = intervalErr ? "dynamic" : `${intervalVal}ms`;
7587
+ }
7588
+ const backoffDesc = options.backoff ? ", error backoff enabled" : "";
7589
+ const timeoutDesc = cfg.timeoutMs === 0 ? "none" : `${cfg.timeoutMs}ms`;
7590
+ logger.info(`[${cfg.logPrefix}] Waiting for ${cfg.label} — polling every ${intervalDesc}${backoffDesc}, timeout ${timeoutDesc}`);
7591
+ }
7592
+ function validateConfig(cfg) {
7593
+ if (cfg.maxConsecutiveErrors === 0 && cfg.timeoutMs === 0 && !cfg.signal) {
7594
+ logger.warn(`[${cfg.logPrefix}] Warning: no timeout, no error limit, and no abort signal — polling will continue indefinitely until terminal state.`);
7595
+ }
7596
+ }
7597
+ async function pollUntil(options) {
7598
+ const cfg = resolveConfig(options);
7599
+ const state = {
7600
+ pollCount: 0,
7601
+ consecutiveErrors: 0,
7602
+ lastResult: undefined,
7603
+ lastStatus: undefined,
7604
+ lastLogAt: 0,
7605
+ interrupted: false
7606
+ };
7607
+ validateConfig(cfg);
7608
+ const guard = setupSignalGuard(cfg, state);
7609
+ logStart(options, cfg);
7610
+ try {
7611
+ return await runPollLoop(cfg, state);
7612
+ } finally {
7613
+ guard.cleanup();
7614
+ }
7615
+ }
7616
+ async function runPollLoop(cfg, state) {
7617
+ while (!state.interrupted && !cfg.signal?.aborted) {
7618
+ if (isPastDeadline(cfg)) {
7619
+ return handleTimeout(cfg, state);
7620
+ }
7621
+ const ctx = buildContext(cfg, state);
7622
+ if (cfg.beforePoll) {
7623
+ const [beforePollErr] = await catchError(Promise.resolve().then(() => cfg.beforePoll?.(ctx)));
7624
+ if (beforePollErr) {
7625
+ const outcome = await handleErrorAndSleep(beforePollErr, "beforePoll", cfg, state, ctx);
7626
+ if (outcome)
7627
+ return outcome;
7628
+ continue;
7629
+ }
7630
+ }
7631
+ const [pollErr, result] = await catchError(cfg.fn());
7632
+ if (pollErr) {
7633
+ const outcome = await handleErrorAndSleep(pollErr, "poll", cfg, state, ctx);
7634
+ if (outcome)
7635
+ return outcome;
7636
+ continue;
7637
+ }
7638
+ await processSuccessfulPoll(result, cfg, state);
7639
+ const [untilErr, isTerminal] = catchError(() => cfg.until(result));
7640
+ if (untilErr) {
7641
+ const outcome = await handleErrorAndSleep(untilErr, "until", cfg, state, ctx);
7642
+ if (outcome)
7643
+ return outcome;
7644
+ continue;
7645
+ }
7646
+ if (isTerminal) {
7647
+ return handleCompleted(result, cfg);
7648
+ }
7649
+ const sleepCtx = buildContext(cfg, state);
7650
+ await doSleep(computeSleepMs(cfg, sleepCtx), cfg);
7651
+ }
7652
+ return handleInterrupted(cfg, state);
7653
+ }
7654
+ async function handleErrorAndSleep(error, source, cfg, state, ctx) {
7655
+ const decision = await handlePollError(error, source, cfg, state);
7656
+ if (decision === "abort") {
7657
+ return handleAborted(cfg, state, error);
7658
+ }
7659
+ if (decision === "failed") {
7660
+ return handleFailed(cfg, state, error);
7661
+ }
7662
+ if (isPastDeadline(cfg)) {
7663
+ return handleTimeout(cfg, state);
7664
+ }
7665
+ await doSleep(computeErrorSleepMs(cfg, state, ctx), cfg);
7666
+ return;
7667
+ }
7668
+ // src/polling/terminal-statuses.ts
7669
+ var TERMINAL_STATUSES = new Set([
7670
+ "completed",
7671
+ "successful",
7672
+ "faulted",
7673
+ "failed",
7674
+ "cancelled",
7675
+ "canceled",
7676
+ "stopped",
7677
+ "finished"
7678
+ ]);
7679
+ var FAILURE_STATUSES = new Set([
7680
+ "faulted",
7681
+ "failed",
7682
+ "cancelled",
7683
+ "canceled",
7684
+ "stopped"
7685
+ ]);
7686
+ function isTerminalStatus(status) {
7687
+ return TERMINAL_STATUSES.has(status.toLowerCase());
7688
+ }
7689
+ function isFailureStatus(status) {
7690
+ return FAILURE_STATUSES.has(status.toLowerCase());
7691
+ }
7692
+ function isSuccessStatus(status) {
7693
+ return isTerminalStatus(status) && !isFailureStatus(status);
7694
+ }
7695
+ // src/screen-logger.ts
7696
+ var ScreenLogger;
7697
+ ((ScreenLogger) => {
7698
+ function progress(message) {
7699
+ getOutputSink().writeErr(`${message}
7700
+ `);
7701
+ }
7702
+ ScreenLogger.progress = progress;
7703
+ })(ScreenLogger ||= {});
7071
7704
  // src/tool-provider.ts
7072
- var toolProvider;
7073
- function setToolProvider(provider) {
7074
- toolProvider = provider;
7705
+ var packagerFactoryProvider;
7706
+ function setPackagerFactoryProvider(provider) {
7707
+ packagerFactoryProvider = provider;
7075
7708
  }
7076
- async function ensureToolAvailable(verb) {
7077
- if (!toolProvider) {
7078
- throw new Error(`Tool '${verb}' is required but cannot be auto-installed. ` + `Run 'uip tools install ${verb}' manually.`);
7709
+ async function ensurePackagerFactory(verb) {
7710
+ if (!packagerFactoryProvider) {
7711
+ throw new Error(`Packager factory for '${verb}' is required but no factory provider is registered. ` + `Run 'uip tools install ${verb}' manually.`);
7079
7712
  }
7080
- await toolProvider(verb);
7713
+ await packagerFactoryProvider(verb);
7081
7714
  }
7082
7715
  // src/trackedAction.ts
7083
7716
  import { Command } from "commander";
7717
+ var POLL_SIGNAL_KEY = Symbol.for("@uipath/common/poll-signal");
7084
7718
  var processContext = {
7085
7719
  exit: (code) => {
7086
7720
  process.exitCode = code;
7721
+ },
7722
+ get pollSignal() {
7723
+ return globalThis[POLL_SIGNAL_KEY];
7087
7724
  }
7088
7725
  };
7726
+ function setProcessContextPollSignal(signal) {
7727
+ globalThis[POLL_SIGNAL_KEY] = signal;
7728
+ }
7089
7729
  function deriveCommandPath(cmd) {
7090
7730
  const parts = [];
7091
7731
  let current = cmd;
@@ -7142,19 +7782,26 @@ export {
7142
7782
  telemetryInit,
7143
7783
  telemetryFlushAndShutdown,
7144
7784
  telemetry,
7145
- setToolProvider,
7785
+ setProcessContextPollSignal,
7786
+ setPackagerFactoryProvider,
7146
7787
  setOutputFormat,
7147
7788
  setOutputFilter,
7148
7789
  setGlobalTelemetryProperties,
7149
7790
  setGlobalSink,
7150
7791
  setGlobalLogFilePath,
7151
- sessionId,
7152
7792
  runWithSink,
7793
+ restoreConsole,
7153
7794
  registerHelpAll,
7154
7795
  readRegistryValue,
7155
7796
  processContext,
7797
+ pollUntil,
7798
+ msToDuration,
7156
7799
  logger,
7800
+ isTerminalStatus,
7157
7801
  isTelemetryDisabled,
7802
+ isSuccessStatus,
7803
+ isFailureStatus,
7804
+ installConsoleGuard,
7158
7805
  getOutputSink,
7159
7806
  getOutputFormat,
7160
7807
  getOutputFilter,
@@ -7162,22 +7809,31 @@ export {
7162
7809
  getGlobalLogFilePath,
7163
7810
  formatHelpAll,
7164
7811
  extractFormatFromArgs,
7812
+ extractErrorMessageSync,
7813
+ extractErrorMessage,
7814
+ extractErrorDetails,
7165
7815
  extractCommandHelp,
7166
7816
  evaluateJsonPath,
7167
- ensureToolAvailable,
7817
+ ensurePackagerFactory,
7168
7818
  deriveCommandPath,
7169
7819
  createTelemetryProvider,
7820
+ createPollAbortController,
7170
7821
  createAppInsightsProvider,
7171
7822
  configureLogger,
7172
7823
  collectCommands,
7173
7824
  catchError,
7174
7825
  UIPATH_HOME_DIR,
7175
7826
  SuccessOutput,
7827
+ ScreenLogger,
7828
+ PollOutcome,
7829
+ POLL_DEFAULTS,
7176
7830
  OutputFormatter,
7831
+ MIN_INTERVAL_MS,
7177
7832
  LogLevel,
7178
7833
  LOCAL_CONFIG_FILENAME,
7179
7834
  JsonPathError,
7180
7835
  FailureOutput,
7836
+ ErrorDecision,
7181
7837
  DEFAULT_REDIRECT_URI,
7182
7838
  DEFAULT_PAGE_SIZE,
7183
7839
  DEFAULT_LOG_LEVEL,
@@ -7186,5 +7842,6 @@ export {
7186
7842
  DEFAULT_AUTH_TIMEOUT_MS,
7187
7843
  CommonTelemetryEvents,
7188
7844
  CONFIG_FILENAME,
7845
+ BACKOFF_DEFAULTS,
7189
7846
  AUTH_FILENAME
7190
7847
  };