@uipath/traces-tool 1.196.0 → 1.197.0-preview.59

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 (3) hide show
  1. package/dist/index.js +2 -0
  2. package/dist/tool.js +892 -1927
  3. package/package.json +2 -2
package/dist/tool.js CHANGED
@@ -13520,8 +13520,8 @@ var require_Subscription = __commonJS((exports) => {
13520
13520
  if (_parentOrParents instanceof Subscription2) {
13521
13521
  _parentOrParents.remove(this);
13522
13522
  } else if (_parentOrParents !== null) {
13523
- for (var index2 = 0;index2 < _parentOrParents.length; ++index2) {
13524
- var parent_1 = _parentOrParents[index2];
13523
+ for (var index = 0;index < _parentOrParents.length; ++index) {
13524
+ var parent_1 = _parentOrParents[index];
13525
13525
  parent_1.remove(this);
13526
13526
  }
13527
13527
  }
@@ -13536,10 +13536,10 @@ var require_Subscription = __commonJS((exports) => {
13536
13536
  }
13537
13537
  }
13538
13538
  if (isArray_1.isArray(_subscriptions)) {
13539
- var index2 = -1;
13539
+ var index = -1;
13540
13540
  var len = _subscriptions.length;
13541
- while (++index2 < len) {
13542
- var sub2 = _subscriptions[index2];
13541
+ while (++index < len) {
13542
+ var sub2 = _subscriptions[index];
13543
13543
  if (isObject_1.isObject(sub2)) {
13544
13544
  try {
13545
13545
  sub2.unsubscribe();
@@ -14969,13 +14969,13 @@ var require_AsyncAction = __commonJS((exports) => {
14969
14969
  var id = this.id;
14970
14970
  var scheduler = this.scheduler;
14971
14971
  var actions = scheduler.actions;
14972
- var index2 = actions.indexOf(this);
14972
+ var index = actions.indexOf(this);
14973
14973
  this.work = null;
14974
14974
  this.state = null;
14975
14975
  this.pending = false;
14976
14976
  this.scheduler = null;
14977
- if (index2 !== -1) {
14978
- actions.splice(index2, 1);
14977
+ if (index !== -1) {
14978
+ actions.splice(index, 1);
14979
14979
  }
14980
14980
  if (id != null) {
14981
14981
  this.id = this.recycleAsyncId(scheduler, id, null);
@@ -15819,17 +15819,17 @@ var require_AsapScheduler = __commonJS((exports) => {
15819
15819
  this.scheduled = undefined;
15820
15820
  var actions = this.actions;
15821
15821
  var error;
15822
- var index2 = -1;
15822
+ var index = -1;
15823
15823
  var count = actions.length;
15824
15824
  action = action || actions.shift();
15825
15825
  do {
15826
15826
  if (error = action.execute(action.state, action.delay)) {
15827
15827
  break;
15828
15828
  }
15829
- } while (++index2 < count && (action = actions.shift()));
15829
+ } while (++index < count && (action = actions.shift()));
15830
15830
  this.active = false;
15831
15831
  if (error) {
15832
- while (++index2 < count && (action = actions.shift())) {
15832
+ while (++index < count && (action = actions.shift())) {
15833
15833
  action.unsubscribe();
15834
15834
  }
15835
15835
  throw error;
@@ -15952,17 +15952,17 @@ var require_AnimationFrameScheduler = __commonJS((exports) => {
15952
15952
  this.scheduled = undefined;
15953
15953
  var actions = this.actions;
15954
15954
  var error;
15955
- var index2 = -1;
15955
+ var index = -1;
15956
15956
  var count = actions.length;
15957
15957
  action = action || actions.shift();
15958
15958
  do {
15959
15959
  if (error = action.execute(action.state, action.delay)) {
15960
15960
  break;
15961
15961
  }
15962
- } while (++index2 < count && (action = actions.shift()));
15962
+ } while (++index < count && (action = actions.shift()));
15963
15963
  this.active = false;
15964
15964
  if (error) {
15965
- while (++index2 < count && (action = actions.shift())) {
15965
+ while (++index < count && (action = actions.shift())) {
15966
15966
  action.unsubscribe();
15967
15967
  }
15968
15968
  throw error;
@@ -16046,16 +16046,16 @@ var require_VirtualTimeScheduler = __commonJS((exports) => {
16046
16046
  exports.VirtualTimeScheduler = VirtualTimeScheduler;
16047
16047
  var VirtualAction = function(_super) {
16048
16048
  __extends(VirtualAction2, _super);
16049
- function VirtualAction2(scheduler, work, index2) {
16050
- if (index2 === undefined) {
16051
- index2 = scheduler.index += 1;
16049
+ function VirtualAction2(scheduler, work, index) {
16050
+ if (index === undefined) {
16051
+ index = scheduler.index += 1;
16052
16052
  }
16053
16053
  var _this = _super.call(this, scheduler, work) || this;
16054
16054
  _this.scheduler = scheduler;
16055
16055
  _this.work = work;
16056
- _this.index = index2;
16056
+ _this.index = index;
16057
16057
  _this.active = true;
16058
- _this.index = scheduler.index = index2;
16058
+ _this.index = scheduler.index = index;
16059
16059
  return _this;
16060
16060
  }
16061
16061
  VirtualAction2.prototype.schedule = function(state, delay) {
@@ -17202,9 +17202,9 @@ var require_mergeMap = __commonJS((exports) => {
17202
17202
  };
17203
17203
  MergeMapSubscriber2.prototype._tryNext = function(value) {
17204
17204
  var result;
17205
- var index2 = this.index++;
17205
+ var index = this.index++;
17206
17206
  try {
17207
- result = this.project(value, index2);
17207
+ result = this.project(value, index);
17208
17208
  } catch (err) {
17209
17209
  this.destination.error(err);
17210
17210
  return;
@@ -17784,12 +17784,12 @@ var require_pairs2 = __commonJS((exports) => {
17784
17784
  }
17785
17785
  exports.pairs = pairs;
17786
17786
  function dispatch(state) {
17787
- var { keys, index: index2, subscriber, subscription, obj } = state;
17787
+ var { keys, index, subscriber, subscription, obj } = state;
17788
17788
  if (!subscriber.closed) {
17789
- if (index2 < keys.length) {
17790
- var key = keys[index2];
17789
+ if (index < keys.length) {
17790
+ var key = keys[index];
17791
17791
  subscriber.next([key, obj[key]]);
17792
- subscription.add(this.schedule({ keys, index: index2 + 1, subscriber, subscription, obj }));
17792
+ subscription.add(this.schedule({ keys, index: index + 1, subscriber, subscription, obj }));
17793
17793
  } else {
17794
17794
  subscriber.complete();
17795
17795
  }
@@ -18002,18 +18002,18 @@ var require_range = __commonJS((exports) => {
18002
18002
  count = start;
18003
18003
  start = 0;
18004
18004
  }
18005
- var index2 = 0;
18005
+ var index = 0;
18006
18006
  var current = start;
18007
18007
  if (scheduler) {
18008
18008
  return scheduler.schedule(dispatch, 0, {
18009
- index: index2,
18009
+ index,
18010
18010
  count,
18011
18011
  start,
18012
18012
  subscriber
18013
18013
  });
18014
18014
  } else {
18015
18015
  do {
18016
- if (index2++ >= count) {
18016
+ if (index++ >= count) {
18017
18017
  subscriber.complete();
18018
18018
  break;
18019
18019
  }
@@ -18028,8 +18028,8 @@ var require_range = __commonJS((exports) => {
18028
18028
  }
18029
18029
  exports.range = range;
18030
18030
  function dispatch(state) {
18031
- var { start, index: index2, count, subscriber } = state;
18032
- if (index2 >= count) {
18031
+ var { start, index, count, subscriber } = state;
18032
+ if (index >= count) {
18033
18033
  subscriber.complete();
18034
18034
  return;
18035
18035
  }
@@ -18037,7 +18037,7 @@ var require_range = __commonJS((exports) => {
18037
18037
  if (subscriber.closed) {
18038
18038
  return;
18039
18039
  }
18040
- state.index = index2 + 1;
18040
+ state.index = index + 1;
18041
18041
  state.start = start + 1;
18042
18042
  this.schedule(state);
18043
18043
  }
@@ -18075,14 +18075,14 @@ var require_timer = __commonJS((exports) => {
18075
18075
  }
18076
18076
  exports.timer = timer;
18077
18077
  function dispatch(state) {
18078
- var { index: index2, period, subscriber } = state;
18079
- subscriber.next(index2);
18078
+ var { index, period, subscriber } = state;
18079
+ subscriber.next(index);
18080
18080
  if (subscriber.closed) {
18081
18081
  return;
18082
18082
  } else if (period === -1) {
18083
18083
  return subscriber.complete();
18084
18084
  }
18085
- state.index = index2 + 1;
18085
+ state.index = index + 1;
18086
18086
  this.schedule(state, period);
18087
18087
  }
18088
18088
  });
@@ -21230,7 +21230,7 @@ var init_server = __esm(() => {
21230
21230
  var package_default = {
21231
21231
  name: "@uipath/traces-tool",
21232
21232
  license: "MIT",
21233
- version: "1.196.0",
21233
+ version: "1.197.0-preview.59",
21234
21234
  description: "Query execution traces for UiPath jobs",
21235
21235
  private: false,
21236
21236
  keywords: [
@@ -21312,27 +21312,54 @@ var NETWORK_ERROR_CODES = new Set([
21312
21312
  "ENETUNREACH",
21313
21313
  "EAI_FAIL"
21314
21314
  ]);
21315
- function isHtmlDocument(body) {
21316
- return /^\s*(<!doctype html|<html\b)/i.test(body);
21317
- }
21318
- function extractNetworkErrorCode(error) {
21319
- if (error === null || typeof error !== "object") {
21320
- return;
21321
- }
21322
- const err = error;
21323
- const code = typeof err.code === "string" ? err.code : undefined;
21324
- if (code && NETWORK_ERROR_CODES.has(code)) {
21325
- return code;
21326
- }
21327
- const cause = err.cause;
21328
- if (cause !== null && typeof cause === "object") {
21329
- const causeCode = cause.code;
21330
- if (typeof causeCode === "string" && NETWORK_ERROR_CODES.has(causeCode)) {
21331
- return causeCode;
21315
+ var TLS_ERROR_CODES = new Set([
21316
+ "SELF_SIGNED_CERT_IN_CHAIN",
21317
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
21318
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
21319
+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
21320
+ "UNABLE_TO_GET_ISSUER_CERT",
21321
+ "CERT_HAS_EXPIRED",
21322
+ "CERT_UNTRUSTED",
21323
+ "ERR_TLS_CERT_ALTNAME_INVALID"
21324
+ ]);
21325
+ var TLS_INSTRUCTIONS = "The server's TLS certificate could not be verified. Most often a " + "corporate proxy/firewall re-signs HTTPS with a root CA that Node does " + "not trust — set NODE_EXTRA_CA_CERTS to that CA's PEM file (and HTTPS_PROXY " + "if you connect through a proxy). If the certificate is instead expired or " + "its hostname does not match, fix the endpoint URL or the system clock. " + "Then retry.";
21326
+ var NETWORK_INSTRUCTIONS = "Could not reach the UiPath service. Check your network connection and " + "VPN, confirm any HTTP_PROXY/HTTPS_PROXY/NO_PROXY settings are correct, " + "then retry.";
21327
+ function describeConnectivityError(error) {
21328
+ let current = error;
21329
+ for (let depth = 0;depth < 5 && current !== null && typeof current === "object"; depth++) {
21330
+ const cur = current;
21331
+ const code = typeof cur.code === "string" ? cur.code : undefined;
21332
+ const message = typeof cur.message === "string" ? cur.message : undefined;
21333
+ if (code && TLS_ERROR_CODES.has(code)) {
21334
+ return {
21335
+ code,
21336
+ kind: "tls",
21337
+ message: message ?? code,
21338
+ instructions: TLS_INSTRUCTIONS
21339
+ };
21340
+ }
21341
+ if (code && NETWORK_ERROR_CODES.has(code)) {
21342
+ return {
21343
+ code,
21344
+ kind: "network",
21345
+ message: message ?? code,
21346
+ instructions: NETWORK_INSTRUCTIONS
21347
+ };
21332
21348
  }
21349
+ current = cur.cause;
21333
21350
  }
21334
21351
  return;
21335
21352
  }
21353
+ function parseHttpStatusFromMessage(message) {
21354
+ const match = /^HTTP\s+(\d{3})(?::|\s|-|$)/i.exec(message.trim());
21355
+ if (!match)
21356
+ return;
21357
+ const status = Number(match[1]);
21358
+ return Number.isInteger(status) && status >= 100 && status <= 599 ? status : undefined;
21359
+ }
21360
+ function isHtmlDocument(body) {
21361
+ return /^\s*(<!doctype html|<html\b)/i.test(body);
21362
+ }
21336
21363
  function retryHintForRetryAfter(seconds) {
21337
21364
  if (seconds <= 1) {
21338
21365
  return "RetryAfter1Second";
@@ -21373,15 +21400,28 @@ function classifyError(status, error) {
21373
21400
  if (status !== undefined && status >= 500 && status < 600) {
21374
21401
  return { errorCode: "server_error", retry: "RetryLater" };
21375
21402
  }
21376
- if (extractNetworkErrorCode(error)) {
21377
- return { errorCode: "network_error", retry: "RetryLater" };
21403
+ const connectivity = describeConnectivityError(error);
21404
+ if (connectivity) {
21405
+ return {
21406
+ errorCode: "network_error",
21407
+ retry: connectivity.kind === "tls" ? "RetryWillNotFix" : "RetryLater"
21408
+ };
21378
21409
  }
21379
21410
  return { errorCode: "unknown_error", retry: "RetryWillNotFix" };
21380
21411
  }
21412
+ function formatHttpStatusMessage(status, rawMessage, extractedMessage, inferredStatus) {
21413
+ if (extractedMessage) {
21414
+ return `HTTP ${status}: ${extractedMessage}`;
21415
+ }
21416
+ return inferredStatus !== undefined ? rawMessage : `HTTP ${status}: ${rawMessage}`;
21417
+ }
21381
21418
  async function extractErrorDetails(error, options) {
21382
21419
  const err = error !== null && error !== undefined && typeof error === "object" ? error : {};
21383
21420
  const response = err.response;
21384
- const status = err.status ?? response?.status;
21421
+ const rawMessage = typeof err.message === "string" ? err.message : "Unknown error";
21422
+ const explicitStatus = err.status ?? response?.status;
21423
+ const inferredStatus = explicitStatus === undefined ? parseHttpStatusFromMessage(rawMessage) : undefined;
21424
+ const status = explicitStatus ?? inferredStatus;
21385
21425
  const isSuccessfulResponse = status !== undefined && status >= 200 && status < 300;
21386
21426
  let rawBody;
21387
21427
  let extractedMessage;
@@ -21416,7 +21456,6 @@ async function extractErrorDetails(error, options) {
21416
21456
  }
21417
21457
  }
21418
21458
  }
21419
- const rawMessage = typeof err.message === "string" ? err.message : "Unknown error";
21420
21459
  let message;
21421
21460
  let result = "Failure";
21422
21461
  const classification = classifyError(status, error);
@@ -21430,10 +21469,10 @@ async function extractErrorDetails(error, options) {
21430
21469
  } else if (status === 405) {
21431
21470
  message = DEFAULT_405;
21432
21471
  } else if (status === 400 || status === 422) {
21433
- message = extractedMessage ? `HTTP ${status}: ${extractedMessage}` : `HTTP ${status}: ${rawMessage}`;
21472
+ message = formatHttpStatusMessage(status, rawMessage, extractedMessage, inferredStatus);
21434
21473
  result = "ValidationError";
21435
21474
  } else if (status === 429) {
21436
- message = extractedMessage ? `HTTP ${status}: ${extractedMessage}` : `HTTP ${status}: ${rawMessage}`;
21475
+ message = formatHttpStatusMessage(status, rawMessage, extractedMessage, inferredStatus);
21437
21476
  } else if (extractedMessage) {
21438
21477
  if (isSuccessfulResponse && rawMessage !== "Unknown error") {
21439
21478
  message = rawMessage;
@@ -21441,7 +21480,9 @@ async function extractErrorDetails(error, options) {
21441
21480
  message = status ? `HTTP ${status}: ${extractedMessage}` : extractedMessage;
21442
21481
  }
21443
21482
  } else if (status) {
21444
- if (rawMessage === "Unknown error" && response) {
21483
+ if (inferredStatus !== undefined) {
21484
+ message = rawMessage;
21485
+ } else if (rawMessage === "Unknown error" && response) {
21445
21486
  const statusText = response.statusText;
21446
21487
  message = statusText ? `HTTP ${status} ${statusText}` : `HTTP ${status} - request failed`;
21447
21488
  } else {
@@ -21450,6 +21491,12 @@ async function extractErrorDetails(error, options) {
21450
21491
  } else {
21451
21492
  message = rawMessage;
21452
21493
  }
21494
+ if (status === undefined) {
21495
+ const connectivity = describeConnectivityError(error);
21496
+ if (connectivity && connectivity.message !== message && !message.includes(connectivity.message)) {
21497
+ message = `${message}: ${connectivity.message}`;
21498
+ }
21499
+ }
21453
21500
  let details = rawMessage;
21454
21501
  if (rawBody) {
21455
21502
  if (parsedBody) {
@@ -21617,6 +21664,7 @@ var CONSOLE_FALLBACK = {
21617
21664
  writeLog: (str) => process.stdout.write(str),
21618
21665
  capabilities: {
21619
21666
  isInteractive: false,
21667
+ canReadInput: false,
21620
21668
  supportsColor: false,
21621
21669
  outputWidth: 80
21622
21670
  }
@@ -26817,6 +26865,29 @@ function isPlainRecord(value) {
26817
26865
  const prototype = Object.getPrototypeOf(value);
26818
26866
  return prototype === Object.prototype || prototype === null;
26819
26867
  }
26868
+ function extractPagedRows(value) {
26869
+ if (Array.isArray(value) || !isPlainRecord(value))
26870
+ return null;
26871
+ const entries = Object.values(value);
26872
+ if (entries.length === 0)
26873
+ return null;
26874
+ let rows = null;
26875
+ let hasScalarSibling = false;
26876
+ for (const entry of entries) {
26877
+ if (Array.isArray(entry)) {
26878
+ if (rows !== null)
26879
+ return null;
26880
+ rows = entry;
26881
+ } else if (entry !== null && typeof entry === "object") {
26882
+ return null;
26883
+ } else {
26884
+ hasScalarSibling = true;
26885
+ }
26886
+ }
26887
+ if (rows === null || !hasScalarSibling)
26888
+ return null;
26889
+ return rows;
26890
+ }
26820
26891
  function toLowerCamelCaseKey(key) {
26821
26892
  if (!key)
26822
26893
  return key;
@@ -26881,7 +26952,8 @@ function printOutput(data, format = "json", logFn, asciiSafe = false) {
26881
26952
  break;
26882
26953
  case "plain": {
26883
26954
  if ("Data" in data && data.Data != null) {
26884
- const items = Array.isArray(data.Data) ? data.Data : [data.Data];
26955
+ const pagedRows = extractPagedRows(data.Data);
26956
+ const items = pagedRows ?? (Array.isArray(data.Data) ? data.Data : [data.Data]);
26885
26957
  items.forEach((item) => {
26886
26958
  const values = Object.values(item).map((v) => v ?? "").join("\t");
26887
26959
  logFn(values);
@@ -26893,10 +26965,13 @@ function printOutput(data, format = "json", logFn, asciiSafe = false) {
26893
26965
  break;
26894
26966
  }
26895
26967
  default: {
26896
- if ("Data" in data && data.Data != null && !(Array.isArray(data.Data) && data.Data.length === 0)) {
26968
+ const hasData = "Data" in data && data.Data != null;
26969
+ const pagedRows = hasData ? extractPagedRows(data.Data) : null;
26970
+ const rows = pagedRows ? pagedRows : Array.isArray(data.Data) ? data.Data : null;
26971
+ if (hasData && !(rows !== null && rows.length === 0)) {
26897
26972
  const logValue = data.Log;
26898
- if (Array.isArray(data.Data)) {
26899
- printResizableTable(data.Data, logFn, logValue);
26973
+ if (rows !== null) {
26974
+ printResizableTable(rows, logFn, logValue);
26900
26975
  } else {
26901
26976
  printVerticalTable(data.Data, logFn, logValue);
26902
26977
  }
@@ -27084,6 +27159,44 @@ function defaultErrorCodeForResult(result) {
27084
27159
  return "unknown_error";
27085
27160
  }
27086
27161
  }
27162
+ function parseHttpStatusFromMessage2(message) {
27163
+ const match = /^HTTP\s+(\d{3})(?::|\s|-|$)/i.exec(message.trim());
27164
+ if (!match)
27165
+ return;
27166
+ const status = Number(match[1]);
27167
+ return Number.isInteger(status) && status >= 100 && status <= 599 ? status : undefined;
27168
+ }
27169
+ function defaultErrorCodeForHttpStatus(status) {
27170
+ if (status === undefined)
27171
+ return;
27172
+ if (status === 400 || status === 409 || status === 422) {
27173
+ return "invalid_argument";
27174
+ }
27175
+ if (status === 401)
27176
+ return "authentication_required";
27177
+ if (status === 403)
27178
+ return "permission_denied";
27179
+ if (status === 404)
27180
+ return "not_found";
27181
+ if (status === 405)
27182
+ return "method_not_allowed";
27183
+ if (status === 408)
27184
+ return "timeout";
27185
+ if (status === 429)
27186
+ return "rate_limited";
27187
+ if (status >= 500 && status < 600)
27188
+ return "server_error";
27189
+ return;
27190
+ }
27191
+ function defaultErrorCodeForFailure(data) {
27192
+ if (data.Result === RESULTS.Failure) {
27193
+ const status = data.Context?.httpStatus ?? parseHttpStatusFromMessage2(data.Message);
27194
+ const errorCode = defaultErrorCodeForHttpStatus(status);
27195
+ if (errorCode)
27196
+ return errorCode;
27197
+ }
27198
+ return defaultErrorCodeForResult(data.Result);
27199
+ }
27087
27200
  function defaultRetryForErrorCode(errorCode) {
27088
27201
  switch (errorCode) {
27089
27202
  case "network_error":
@@ -27113,16 +27226,19 @@ var OutputFormatter;
27113
27226
  OutputFormatter.success = success;
27114
27227
  function error(data) {
27115
27228
  data.Log ??= getLogFilePath() || undefined;
27116
- data.ErrorCode ??= defaultErrorCodeForResult(data.Result);
27229
+ data.ErrorCode ??= defaultErrorCodeForFailure(data);
27117
27230
  data.Retry ??= defaultRetryForErrorCode(data.ErrorCode);
27118
27231
  process.exitCode = EXIT_CODES[data.Result] ?? 1;
27119
- telemetry.trackEvent(CommonTelemetryEvents.Error, {
27120
- result: data.Result,
27121
- errorCode: data.ErrorCode,
27122
- retry: data.Retry,
27123
- message: data.Message
27124
- });
27125
- logOutput(normalizeOutputKeys(data), getOutputFormat());
27232
+ const { SuppressTelemetry, ...envelope } = data;
27233
+ if (!SuppressTelemetry) {
27234
+ telemetry.trackEvent(CommonTelemetryEvents.Error, {
27235
+ result: data.Result,
27236
+ errorCode: data.ErrorCode,
27237
+ retry: data.Retry,
27238
+ message: data.Message
27239
+ });
27240
+ }
27241
+ logOutput(normalizeOutputKeys(envelope), getOutputFormat());
27126
27242
  }
27127
27243
  OutputFormatter.error = error;
27128
27244
  function emitList(code, items, opts) {
@@ -27426,1651 +27542,240 @@ var savedOriginalsSlot = singleton("ConsoleGuardOriginals");
27426
27542
  var DEFAULT_AUTH_TIMEOUT_MS = 5 * 60 * 1000;
27427
27543
  // ../common/src/interactivity-context.ts
27428
27544
  var modeSlot = singleton("InteractivityMode");
27429
- // ../../node_modules/jsonpath-plus/dist/index-node-esm.js
27430
- import vm from "vm";
27431
-
27432
- class Hooks {
27433
- add(name, callback, first) {
27434
- if (typeof arguments[0] != "string") {
27435
- for (let name2 in arguments[0]) {
27436
- this.add(name2, arguments[0][name2], arguments[1]);
27545
+ // ../common/src/option-aliases.ts
27546
+ function resolveDeprecatedOptionAlias({
27547
+ preferredValue,
27548
+ deprecatedValue,
27549
+ preferredFlag,
27550
+ deprecatedFlag
27551
+ }) {
27552
+ const hasPreferred = preferredValue !== undefined;
27553
+ const hasDeprecated = deprecatedValue !== undefined;
27554
+ if (hasPreferred && hasDeprecated) {
27555
+ return {
27556
+ value: undefined,
27557
+ usedDeprecated: true,
27558
+ error: {
27559
+ message: `${deprecatedFlag} and ${preferredFlag} are aliases. Use only ${preferredFlag}.`,
27560
+ instructions: `Replace ${deprecatedFlag} with ${preferredFlag}.`
27437
27561
  }
27438
- } else {
27439
- (Array.isArray(name) ? name : [name]).forEach(function(name2) {
27440
- this[name2] = this[name2] || [];
27441
- if (callback) {
27442
- this[name2][first ? "unshift" : "push"](callback);
27443
- }
27444
- }, this);
27445
- }
27446
- }
27447
- run(name, env) {
27448
- this[name] = this[name] || [];
27449
- this[name].forEach(function(callback) {
27450
- callback.call(env && env.context ? env.context : env, env);
27451
- });
27562
+ };
27452
27563
  }
27564
+ return {
27565
+ value: hasPreferred ? preferredValue : deprecatedValue,
27566
+ usedDeprecated: hasDeprecated
27567
+ };
27453
27568
  }
27454
-
27455
- class Plugins {
27456
- constructor(jsep) {
27457
- this.jsep = jsep;
27458
- this.registered = {};
27459
- }
27460
- register(...plugins) {
27461
- plugins.forEach((plugin) => {
27462
- if (typeof plugin !== "object" || !plugin.name || !plugin.init) {
27463
- throw new Error("Invalid JSEP plugin format");
27464
- }
27465
- if (this.registered[plugin.name]) {
27466
- return;
27467
- }
27468
- plugin.init(this.jsep);
27469
- this.registered[plugin.name] = plugin;
27470
- });
27471
- }
27569
+ function warnDeprecatedOptionAlias(deprecatedFlag, preferredFlag) {
27570
+ getOutputSink().writeErr(`[WARN] ${deprecatedFlag} is deprecated. Use ${preferredFlag} instead.
27571
+ `);
27572
+ }
27573
+ var TENANT_SWITCH_COMMAND = "uip login tenant set <tenant>";
27574
+ function createHiddenDeprecatedTenantOption(flags = "-t, --tenant <tenant-name>") {
27575
+ return new Option(flags, `Tenant name. Deprecated; use ${TENANT_SWITCH_COMMAND} to switch active tenants.`).hideHelp().argParser((tenant) => {
27576
+ warnDeprecatedTenantOption(tenant);
27577
+ return tenant;
27578
+ });
27579
+ }
27580
+ function warnDeprecatedTenantOption(tenant) {
27581
+ if (tenant === undefined)
27582
+ return;
27583
+ warnDeprecatedOptionAlias("--tenant", TENANT_SWITCH_COMMAND);
27472
27584
  }
27585
+ // ../common/src/polling/types.ts
27586
+ var PollOutcome = {
27587
+ Completed: "completed",
27588
+ Timeout: "timeout",
27589
+ Interrupted: "interrupted",
27590
+ Aborted: "aborted",
27591
+ Failed: "failed"
27592
+ };
27473
27593
 
27474
- class Jsep {
27475
- static get version() {
27476
- return "1.4.0";
27477
- }
27478
- static toString() {
27479
- return "JavaScript Expression Parser (JSEP) v" + Jsep.version;
27594
+ // ../common/src/polling/poll-failure-mapping.ts
27595
+ var REASON_BY_OUTCOME = {
27596
+ [PollOutcome.Timeout]: "poll_timeout",
27597
+ [PollOutcome.Failed]: "poll_failed",
27598
+ [PollOutcome.Interrupted]: "poll_failed",
27599
+ [PollOutcome.Aborted]: "poll_aborted"
27600
+ };
27601
+ // ../common/src/polling/terminal-statuses.ts
27602
+ var TERMINAL_STATUSES = new Set([
27603
+ "completed",
27604
+ "successful",
27605
+ "faulted",
27606
+ "failed",
27607
+ "cancelled",
27608
+ "canceled",
27609
+ "stopped",
27610
+ "finished"
27611
+ ]);
27612
+ var FAILURE_STATUSES = new Set([
27613
+ "faulted",
27614
+ "failed",
27615
+ "cancelled",
27616
+ "canceled",
27617
+ "stopped"
27618
+ ]);
27619
+ // ../common/src/preview.ts
27620
+ var previewSlot = singleton("PreviewBuild");
27621
+ function isPreviewBuild() {
27622
+ return previewSlot.get(false) ?? false;
27623
+ }
27624
+ Command.prototype.previewCommand = function(nameAndArgs, opts) {
27625
+ if (isPreviewBuild()) {
27626
+ return this.command(nameAndArgs, opts);
27480
27627
  }
27481
- static addUnaryOp(op_name) {
27482
- Jsep.max_unop_len = Math.max(op_name.length, Jsep.max_unop_len);
27483
- Jsep.unary_ops[op_name] = 1;
27484
- return Jsep;
27628
+ return new Command(nameAndArgs.split(/\s+/)[0] ?? nameAndArgs);
27629
+ };
27630
+ // ../common/src/screen-logger.ts
27631
+ var ScreenLogger;
27632
+ ((ScreenLogger) => {
27633
+ function progress(message) {
27634
+ getOutputSink().writeErr(`${message}
27635
+ `);
27485
27636
  }
27486
- static addBinaryOp(op_name, precedence, isRightAssociative) {
27487
- Jsep.max_binop_len = Math.max(op_name.length, Jsep.max_binop_len);
27488
- Jsep.binary_ops[op_name] = precedence;
27489
- if (isRightAssociative) {
27490
- Jsep.right_associative.add(op_name);
27491
- } else {
27492
- Jsep.right_associative.delete(op_name);
27637
+ ScreenLogger.progress = progress;
27638
+ })(ScreenLogger ||= {});
27639
+ // ../common/src/sdk-user-agent.ts
27640
+ var USER_AGENT_HEADER = "User-Agent";
27641
+ var sdkUserAgentHostToken = singleton("SdkUserAgentHostToken");
27642
+ function userAgentPatchKey(userAgent) {
27643
+ return Symbol.for(`@uipath/common/sdk-user-agent/${userAgent}`);
27644
+ }
27645
+ function splitUserAgentTokens(value) {
27646
+ return value?.trim().split(/\s+/).filter(Boolean) ?? [];
27647
+ }
27648
+ function appendUserAgentToken(value, userAgent) {
27649
+ const tokens = splitUserAgentTokens(value);
27650
+ const seen = new Set(tokens);
27651
+ for (const token of splitUserAgentTokens(userAgent)) {
27652
+ if (!seen.has(token)) {
27653
+ tokens.push(token);
27654
+ seen.add(token);
27493
27655
  }
27494
- return Jsep;
27495
27656
  }
27496
- static addIdentifierChar(char) {
27497
- Jsep.additional_identifier_chars.add(char);
27498
- return Jsep;
27657
+ return tokens.join(" ");
27658
+ }
27659
+ function getEffectiveUserAgent(userAgent) {
27660
+ return appendUserAgentToken(sdkUserAgentHostToken.get(), userAgent);
27661
+ }
27662
+ function getHeaderName(headers, headerName) {
27663
+ return Object.keys(headers).find((key) => key.toLowerCase() === headerName.toLowerCase());
27664
+ }
27665
+ function getSdkUserAgentToken(pkg) {
27666
+ const packageName = pkg.name.replace(/^@uipath\//, "");
27667
+ return getEffectiveUserAgent(`${packageName}/${pkg.version}`);
27668
+ }
27669
+ function addSdkUserAgentHeader(headers, userAgent) {
27670
+ const result = { ...headers ?? {} };
27671
+ const headerName = getHeaderName(result, USER_AGENT_HEADER);
27672
+ result[headerName ?? USER_AGENT_HEADER] = appendUserAgentToken(headerName ? result[headerName] : undefined, getEffectiveUserAgent(userAgent));
27673
+ return result;
27674
+ }
27675
+ function asHeaderRecord(headers) {
27676
+ return typeof headers === "object" && headers !== null ? { ...headers } : {};
27677
+ }
27678
+ function withForwardedHeadersInitOverride(initOverrides, forward) {
27679
+ return async (requestContext) => {
27680
+ const initWithHeaders = {
27681
+ ...requestContext.init,
27682
+ headers: forward(asHeaderRecord(requestContext.init.headers))
27683
+ };
27684
+ const override = typeof initOverrides === "function" ? await initOverrides({
27685
+ ...requestContext,
27686
+ init: initWithHeaders
27687
+ }) : initOverrides;
27688
+ return {
27689
+ ...override ?? {},
27690
+ headers: forward(asHeaderRecord(override?.headers ?? initWithHeaders.headers))
27691
+ };
27692
+ };
27693
+ }
27694
+ function installRequestHeaderForwarding(BaseApiClass, patchKey, forward) {
27695
+ const prototype = BaseApiClass.prototype;
27696
+ if (prototype[patchKey]) {
27697
+ return;
27499
27698
  }
27500
- static addLiteral(literal_name, literal_value) {
27501
- Jsep.literals[literal_name] = literal_value;
27502
- return Jsep;
27699
+ if (typeof prototype.request !== "function") {
27700
+ throw new Error("Generated BaseAPI request function not found.");
27503
27701
  }
27504
- static removeUnaryOp(op_name) {
27505
- delete Jsep.unary_ops[op_name];
27506
- if (op_name.length === Jsep.max_unop_len) {
27507
- Jsep.max_unop_len = Jsep.getMaxKeyLen(Jsep.unary_ops);
27508
- }
27509
- return Jsep;
27702
+ const originalRequest = prototype.request;
27703
+ prototype.request = function requestWithForwardedHeaders(context, initOverrides) {
27704
+ return originalRequest.call(this, context, withForwardedHeadersInitOverride(initOverrides, forward));
27705
+ };
27706
+ Object.defineProperty(prototype, patchKey, {
27707
+ value: true
27708
+ });
27709
+ }
27710
+ function installSdkUserAgentHeader(BaseApiClass, userAgent) {
27711
+ installRequestHeaderForwarding(BaseApiClass, userAgentPatchKey(userAgent), (headers) => addSdkUserAgentHeader(headers, userAgent));
27712
+ }
27713
+ // ../common/src/tool-provider.ts
27714
+ var factorySlot = singleton("PackagerFactoryProvider");
27715
+ // ../auth/src/config.ts
27716
+ init_constants();
27717
+ var DEFAULT_CLIENT_ID = "36dea5b8-e8bb-423d-8e7b-c808df8f1c00";
27718
+ var AUTH_FILE_CONFIG_KEY = Symbol.for("@uipath/auth/AuthFileConfig");
27719
+ var globalSlot = globalThis;
27720
+ var getAuthFileConfig = () => globalSlot[AUTH_FILE_CONFIG_KEY] ?? {};
27721
+
27722
+ class InvalidBaseUrlError extends Error {
27723
+ url;
27724
+ reason;
27725
+ constructor(url, reason) {
27726
+ super(`Invalid base URL: "${url}"
27727
+ ` + `Reason: ${reason}
27728
+
27729
+ ` + `Expected format: an https:// URL, e.g. https://cloud.uipath.com (commercial), https://govcloud.uipath.us (Public Sector), or your Automation Suite host (https://<your-host>).
27730
+ ` + `You can specify the URL via:
27731
+ ` + ` • --authority flag
27732
+ ` + ` • UIPATH_URL environment variable
27733
+ ` + ` • auth.authority in config file`);
27734
+ this.url = url;
27735
+ this.reason = reason;
27736
+ this.name = "InvalidBaseUrlError";
27510
27737
  }
27511
- static removeAllUnaryOps() {
27512
- Jsep.unary_ops = {};
27513
- Jsep.max_unop_len = 0;
27514
- return Jsep;
27738
+ }
27739
+ var DEFAULT_SCOPES = ["openid", "profile", "offline_access"];
27740
+ var normalizeAndValidateBaseUrl = (rawUrl) => {
27741
+ let baseUrl = rawUrl;
27742
+ if (baseUrl.endsWith("/identity_/")) {
27743
+ baseUrl = baseUrl.slice(0, -11);
27744
+ } else if (baseUrl.endsWith("/identity_")) {
27745
+ baseUrl = baseUrl.slice(0, -10);
27515
27746
  }
27516
- static removeIdentifierChar(char) {
27517
- Jsep.additional_identifier_chars.delete(char);
27518
- return Jsep;
27747
+ while (baseUrl.endsWith("/")) {
27748
+ baseUrl = baseUrl.slice(0, -1);
27519
27749
  }
27520
- static removeBinaryOp(op_name) {
27521
- delete Jsep.binary_ops[op_name];
27522
- if (op_name.length === Jsep.max_binop_len) {
27523
- Jsep.max_binop_len = Jsep.getMaxKeyLen(Jsep.binary_ops);
27524
- }
27525
- Jsep.right_associative.delete(op_name);
27526
- return Jsep;
27750
+ const resolvedBaseUrl = baseUrl;
27751
+ const [urlError, url] = catchError2(() => new URL(resolvedBaseUrl));
27752
+ if (urlError) {
27753
+ throw new InvalidBaseUrlError(baseUrl, `Malformed URL. ${urlError instanceof Error ? urlError.message : "Unknown error"}`);
27527
27754
  }
27528
- static removeAllBinaryOps() {
27529
- Jsep.binary_ops = {};
27530
- Jsep.max_binop_len = 0;
27531
- return Jsep;
27755
+ if (url.protocol !== "https:") {
27756
+ throw new InvalidBaseUrlError(baseUrl, `Authority must use https:// scheme, got ${url.protocol}//. OIDC token exchange requires TLS end-to-end.`);
27532
27757
  }
27533
- static removeLiteral(literal_name) {
27534
- delete Jsep.literals[literal_name];
27535
- return Jsep;
27758
+ return url.pathname.length > 1 ? url.origin : baseUrl;
27759
+ };
27760
+ var resolveScopes = (isExternalAppAuth, customScopes, fileScopes) => {
27761
+ const requestedScopes = customScopes?.length ? customScopes : fileScopes ?? [];
27762
+ if (isExternalAppAuth)
27763
+ return requestedScopes;
27764
+ return [...new Set([...DEFAULT_SCOPES, ...requestedScopes])];
27765
+ };
27766
+ var resolveConfigAsync = async ({
27767
+ customAuthority,
27768
+ customClientId,
27769
+ customClientSecret,
27770
+ customScopes
27771
+ } = {}) => {
27772
+ const fileAuth = getAuthFileConfig();
27773
+ let baseUrl = customAuthority;
27774
+ if (!baseUrl) {
27775
+ baseUrl = process.env.UIPATH_URL;
27536
27776
  }
27537
- static removeAllLiterals() {
27538
- Jsep.literals = {};
27539
- return Jsep;
27540
- }
27541
- get char() {
27542
- return this.expr.charAt(this.index);
27543
- }
27544
- get code() {
27545
- return this.expr.charCodeAt(this.index);
27546
- }
27547
- constructor(expr) {
27548
- this.expr = expr;
27549
- this.index = 0;
27550
- }
27551
- static parse(expr) {
27552
- return new Jsep(expr).parse();
27553
- }
27554
- static getMaxKeyLen(obj) {
27555
- return Math.max(0, ...Object.keys(obj).map((k) => k.length));
27556
- }
27557
- static isDecimalDigit(ch) {
27558
- return ch >= 48 && ch <= 57;
27559
- }
27560
- static binaryPrecedence(op_val) {
27561
- return Jsep.binary_ops[op_val] || 0;
27562
- }
27563
- static isIdentifierStart(ch) {
27564
- return ch >= 65 && ch <= 90 || ch >= 97 && ch <= 122 || ch >= 128 && !Jsep.binary_ops[String.fromCharCode(ch)] || Jsep.additional_identifier_chars.has(String.fromCharCode(ch));
27565
- }
27566
- static isIdentifierPart(ch) {
27567
- return Jsep.isIdentifierStart(ch) || Jsep.isDecimalDigit(ch);
27568
- }
27569
- throwError(message) {
27570
- const error = new Error(message + " at character " + this.index);
27571
- error.index = this.index;
27572
- error.description = message;
27573
- throw error;
27574
- }
27575
- runHook(name, node) {
27576
- if (Jsep.hooks[name]) {
27577
- const env = {
27578
- context: this,
27579
- node
27580
- };
27581
- Jsep.hooks.run(name, env);
27582
- return env.node;
27583
- }
27584
- return node;
27585
- }
27586
- searchHook(name) {
27587
- if (Jsep.hooks[name]) {
27588
- const env = {
27589
- context: this
27590
- };
27591
- Jsep.hooks[name].find(function(callback) {
27592
- callback.call(env.context, env);
27593
- return env.node;
27594
- });
27595
- return env.node;
27596
- }
27597
- }
27598
- gobbleSpaces() {
27599
- let ch = this.code;
27600
- while (ch === Jsep.SPACE_CODE || ch === Jsep.TAB_CODE || ch === Jsep.LF_CODE || ch === Jsep.CR_CODE) {
27601
- ch = this.expr.charCodeAt(++this.index);
27602
- }
27603
- this.runHook("gobble-spaces");
27604
- }
27605
- parse() {
27606
- this.runHook("before-all");
27607
- const nodes = this.gobbleExpressions();
27608
- const node = nodes.length === 1 ? nodes[0] : {
27609
- type: Jsep.COMPOUND,
27610
- body: nodes
27611
- };
27612
- return this.runHook("after-all", node);
27613
- }
27614
- gobbleExpressions(untilICode) {
27615
- let nodes = [], ch_i, node;
27616
- while (this.index < this.expr.length) {
27617
- ch_i = this.code;
27618
- if (ch_i === Jsep.SEMCOL_CODE || ch_i === Jsep.COMMA_CODE) {
27619
- this.index++;
27620
- } else {
27621
- if (node = this.gobbleExpression()) {
27622
- nodes.push(node);
27623
- } else if (this.index < this.expr.length) {
27624
- if (ch_i === untilICode) {
27625
- break;
27626
- }
27627
- this.throwError('Unexpected "' + this.char + '"');
27628
- }
27629
- }
27630
- }
27631
- return nodes;
27632
- }
27633
- gobbleExpression() {
27634
- const node = this.searchHook("gobble-expression") || this.gobbleBinaryExpression();
27635
- this.gobbleSpaces();
27636
- return this.runHook("after-expression", node);
27637
- }
27638
- gobbleBinaryOp() {
27639
- this.gobbleSpaces();
27640
- let to_check = this.expr.substr(this.index, Jsep.max_binop_len);
27641
- let tc_len = to_check.length;
27642
- while (tc_len > 0) {
27643
- if (Jsep.binary_ops.hasOwnProperty(to_check) && (!Jsep.isIdentifierStart(this.code) || this.index + to_check.length < this.expr.length && !Jsep.isIdentifierPart(this.expr.charCodeAt(this.index + to_check.length)))) {
27644
- this.index += tc_len;
27645
- return to_check;
27646
- }
27647
- to_check = to_check.substr(0, --tc_len);
27648
- }
27649
- return false;
27650
- }
27651
- gobbleBinaryExpression() {
27652
- let node, biop, prec, stack, biop_info, left, right, i, cur_biop;
27653
- left = this.gobbleToken();
27654
- if (!left) {
27655
- return left;
27656
- }
27657
- biop = this.gobbleBinaryOp();
27658
- if (!biop) {
27659
- return left;
27660
- }
27661
- biop_info = {
27662
- value: biop,
27663
- prec: Jsep.binaryPrecedence(biop),
27664
- right_a: Jsep.right_associative.has(biop)
27665
- };
27666
- right = this.gobbleToken();
27667
- if (!right) {
27668
- this.throwError("Expected expression after " + biop);
27669
- }
27670
- stack = [left, biop_info, right];
27671
- while (biop = this.gobbleBinaryOp()) {
27672
- prec = Jsep.binaryPrecedence(biop);
27673
- if (prec === 0) {
27674
- this.index -= biop.length;
27675
- break;
27676
- }
27677
- biop_info = {
27678
- value: biop,
27679
- prec,
27680
- right_a: Jsep.right_associative.has(biop)
27681
- };
27682
- cur_biop = biop;
27683
- const comparePrev = (prev) => biop_info.right_a && prev.right_a ? prec > prev.prec : prec <= prev.prec;
27684
- while (stack.length > 2 && comparePrev(stack[stack.length - 2])) {
27685
- right = stack.pop();
27686
- biop = stack.pop().value;
27687
- left = stack.pop();
27688
- node = {
27689
- type: Jsep.BINARY_EXP,
27690
- operator: biop,
27691
- left,
27692
- right
27693
- };
27694
- stack.push(node);
27695
- }
27696
- node = this.gobbleToken();
27697
- if (!node) {
27698
- this.throwError("Expected expression after " + cur_biop);
27699
- }
27700
- stack.push(biop_info, node);
27701
- }
27702
- i = stack.length - 1;
27703
- node = stack[i];
27704
- while (i > 1) {
27705
- node = {
27706
- type: Jsep.BINARY_EXP,
27707
- operator: stack[i - 1].value,
27708
- left: stack[i - 2],
27709
- right: node
27710
- };
27711
- i -= 2;
27712
- }
27713
- return node;
27714
- }
27715
- gobbleToken() {
27716
- let ch, to_check, tc_len, node;
27717
- this.gobbleSpaces();
27718
- node = this.searchHook("gobble-token");
27719
- if (node) {
27720
- return this.runHook("after-token", node);
27721
- }
27722
- ch = this.code;
27723
- if (Jsep.isDecimalDigit(ch) || ch === Jsep.PERIOD_CODE) {
27724
- return this.gobbleNumericLiteral();
27725
- }
27726
- if (ch === Jsep.SQUOTE_CODE || ch === Jsep.DQUOTE_CODE) {
27727
- node = this.gobbleStringLiteral();
27728
- } else if (ch === Jsep.OBRACK_CODE) {
27729
- node = this.gobbleArray();
27730
- } else {
27731
- to_check = this.expr.substr(this.index, Jsep.max_unop_len);
27732
- tc_len = to_check.length;
27733
- while (tc_len > 0) {
27734
- if (Jsep.unary_ops.hasOwnProperty(to_check) && (!Jsep.isIdentifierStart(this.code) || this.index + to_check.length < this.expr.length && !Jsep.isIdentifierPart(this.expr.charCodeAt(this.index + to_check.length)))) {
27735
- this.index += tc_len;
27736
- const argument = this.gobbleToken();
27737
- if (!argument) {
27738
- this.throwError("missing unaryOp argument");
27739
- }
27740
- return this.runHook("after-token", {
27741
- type: Jsep.UNARY_EXP,
27742
- operator: to_check,
27743
- argument,
27744
- prefix: true
27745
- });
27746
- }
27747
- to_check = to_check.substr(0, --tc_len);
27748
- }
27749
- if (Jsep.isIdentifierStart(ch)) {
27750
- node = this.gobbleIdentifier();
27751
- if (Jsep.literals.hasOwnProperty(node.name)) {
27752
- node = {
27753
- type: Jsep.LITERAL,
27754
- value: Jsep.literals[node.name],
27755
- raw: node.name
27756
- };
27757
- } else if (node.name === Jsep.this_str) {
27758
- node = {
27759
- type: Jsep.THIS_EXP
27760
- };
27761
- }
27762
- } else if (ch === Jsep.OPAREN_CODE) {
27763
- node = this.gobbleGroup();
27764
- }
27765
- }
27766
- if (!node) {
27767
- return this.runHook("after-token", false);
27768
- }
27769
- node = this.gobbleTokenProperty(node);
27770
- return this.runHook("after-token", node);
27771
- }
27772
- gobbleTokenProperty(node) {
27773
- this.gobbleSpaces();
27774
- let ch = this.code;
27775
- while (ch === Jsep.PERIOD_CODE || ch === Jsep.OBRACK_CODE || ch === Jsep.OPAREN_CODE || ch === Jsep.QUMARK_CODE) {
27776
- let optional;
27777
- if (ch === Jsep.QUMARK_CODE) {
27778
- if (this.expr.charCodeAt(this.index + 1) !== Jsep.PERIOD_CODE) {
27779
- break;
27780
- }
27781
- optional = true;
27782
- this.index += 2;
27783
- this.gobbleSpaces();
27784
- ch = this.code;
27785
- }
27786
- this.index++;
27787
- if (ch === Jsep.OBRACK_CODE) {
27788
- node = {
27789
- type: Jsep.MEMBER_EXP,
27790
- computed: true,
27791
- object: node,
27792
- property: this.gobbleExpression()
27793
- };
27794
- if (!node.property) {
27795
- this.throwError('Unexpected "' + this.char + '"');
27796
- }
27797
- this.gobbleSpaces();
27798
- ch = this.code;
27799
- if (ch !== Jsep.CBRACK_CODE) {
27800
- this.throwError("Unclosed [");
27801
- }
27802
- this.index++;
27803
- } else if (ch === Jsep.OPAREN_CODE) {
27804
- node = {
27805
- type: Jsep.CALL_EXP,
27806
- arguments: this.gobbleArguments(Jsep.CPAREN_CODE),
27807
- callee: node
27808
- };
27809
- } else if (ch === Jsep.PERIOD_CODE || optional) {
27810
- if (optional) {
27811
- this.index--;
27812
- }
27813
- this.gobbleSpaces();
27814
- node = {
27815
- type: Jsep.MEMBER_EXP,
27816
- computed: false,
27817
- object: node,
27818
- property: this.gobbleIdentifier()
27819
- };
27820
- }
27821
- if (optional) {
27822
- node.optional = true;
27823
- }
27824
- this.gobbleSpaces();
27825
- ch = this.code;
27826
- }
27827
- return node;
27828
- }
27829
- gobbleNumericLiteral() {
27830
- let number = "", ch, chCode;
27831
- while (Jsep.isDecimalDigit(this.code)) {
27832
- number += this.expr.charAt(this.index++);
27833
- }
27834
- if (this.code === Jsep.PERIOD_CODE) {
27835
- number += this.expr.charAt(this.index++);
27836
- while (Jsep.isDecimalDigit(this.code)) {
27837
- number += this.expr.charAt(this.index++);
27838
- }
27839
- }
27840
- ch = this.char;
27841
- if (ch === "e" || ch === "E") {
27842
- number += this.expr.charAt(this.index++);
27843
- ch = this.char;
27844
- if (ch === "+" || ch === "-") {
27845
- number += this.expr.charAt(this.index++);
27846
- }
27847
- while (Jsep.isDecimalDigit(this.code)) {
27848
- number += this.expr.charAt(this.index++);
27849
- }
27850
- if (!Jsep.isDecimalDigit(this.expr.charCodeAt(this.index - 1))) {
27851
- this.throwError("Expected exponent (" + number + this.char + ")");
27852
- }
27853
- }
27854
- chCode = this.code;
27855
- if (Jsep.isIdentifierStart(chCode)) {
27856
- this.throwError("Variable names cannot start with a number (" + number + this.char + ")");
27857
- } else if (chCode === Jsep.PERIOD_CODE || number.length === 1 && number.charCodeAt(0) === Jsep.PERIOD_CODE) {
27858
- this.throwError("Unexpected period");
27859
- }
27860
- return {
27861
- type: Jsep.LITERAL,
27862
- value: parseFloat(number),
27863
- raw: number
27864
- };
27865
- }
27866
- gobbleStringLiteral() {
27867
- let str = "";
27868
- const startIndex = this.index;
27869
- const quote = this.expr.charAt(this.index++);
27870
- let closed = false;
27871
- while (this.index < this.expr.length) {
27872
- let ch = this.expr.charAt(this.index++);
27873
- if (ch === quote) {
27874
- closed = true;
27875
- break;
27876
- } else if (ch === "\\") {
27877
- ch = this.expr.charAt(this.index++);
27878
- switch (ch) {
27879
- case "n":
27880
- str += `
27881
- `;
27882
- break;
27883
- case "r":
27884
- str += "\r";
27885
- break;
27886
- case "t":
27887
- str += "\t";
27888
- break;
27889
- case "b":
27890
- str += "\b";
27891
- break;
27892
- case "f":
27893
- str += "\f";
27894
- break;
27895
- case "v":
27896
- str += "\v";
27897
- break;
27898
- default:
27899
- str += ch;
27900
- }
27901
- } else {
27902
- str += ch;
27903
- }
27904
- }
27905
- if (!closed) {
27906
- this.throwError('Unclosed quote after "' + str + '"');
27907
- }
27908
- return {
27909
- type: Jsep.LITERAL,
27910
- value: str,
27911
- raw: this.expr.substring(startIndex, this.index)
27912
- };
27913
- }
27914
- gobbleIdentifier() {
27915
- let ch = this.code, start = this.index;
27916
- if (Jsep.isIdentifierStart(ch)) {
27917
- this.index++;
27918
- } else {
27919
- this.throwError("Unexpected " + this.char);
27920
- }
27921
- while (this.index < this.expr.length) {
27922
- ch = this.code;
27923
- if (Jsep.isIdentifierPart(ch)) {
27924
- this.index++;
27925
- } else {
27926
- break;
27927
- }
27928
- }
27929
- return {
27930
- type: Jsep.IDENTIFIER,
27931
- name: this.expr.slice(start, this.index)
27932
- };
27933
- }
27934
- gobbleArguments(termination) {
27935
- const args = [];
27936
- let closed = false;
27937
- let separator_count = 0;
27938
- while (this.index < this.expr.length) {
27939
- this.gobbleSpaces();
27940
- let ch_i = this.code;
27941
- if (ch_i === termination) {
27942
- closed = true;
27943
- this.index++;
27944
- if (termination === Jsep.CPAREN_CODE && separator_count && separator_count >= args.length) {
27945
- this.throwError("Unexpected token " + String.fromCharCode(termination));
27946
- }
27947
- break;
27948
- } else if (ch_i === Jsep.COMMA_CODE) {
27949
- this.index++;
27950
- separator_count++;
27951
- if (separator_count !== args.length) {
27952
- if (termination === Jsep.CPAREN_CODE) {
27953
- this.throwError("Unexpected token ,");
27954
- } else if (termination === Jsep.CBRACK_CODE) {
27955
- for (let arg = args.length;arg < separator_count; arg++) {
27956
- args.push(null);
27957
- }
27958
- }
27959
- }
27960
- } else if (args.length !== separator_count && separator_count !== 0) {
27961
- this.throwError("Expected comma");
27962
- } else {
27963
- const node = this.gobbleExpression();
27964
- if (!node || node.type === Jsep.COMPOUND) {
27965
- this.throwError("Expected comma");
27966
- }
27967
- args.push(node);
27968
- }
27969
- }
27970
- if (!closed) {
27971
- this.throwError("Expected " + String.fromCharCode(termination));
27972
- }
27973
- return args;
27974
- }
27975
- gobbleGroup() {
27976
- this.index++;
27977
- let nodes = this.gobbleExpressions(Jsep.CPAREN_CODE);
27978
- if (this.code === Jsep.CPAREN_CODE) {
27979
- this.index++;
27980
- if (nodes.length === 1) {
27981
- return nodes[0];
27982
- } else if (!nodes.length) {
27983
- return false;
27984
- } else {
27985
- return {
27986
- type: Jsep.SEQUENCE_EXP,
27987
- expressions: nodes
27988
- };
27989
- }
27990
- } else {
27991
- this.throwError("Unclosed (");
27992
- }
27993
- }
27994
- gobbleArray() {
27995
- this.index++;
27996
- return {
27997
- type: Jsep.ARRAY_EXP,
27998
- elements: this.gobbleArguments(Jsep.CBRACK_CODE)
27999
- };
28000
- }
28001
- }
28002
- var hooks = new Hooks;
28003
- Object.assign(Jsep, {
28004
- hooks,
28005
- plugins: new Plugins(Jsep),
28006
- COMPOUND: "Compound",
28007
- SEQUENCE_EXP: "SequenceExpression",
28008
- IDENTIFIER: "Identifier",
28009
- MEMBER_EXP: "MemberExpression",
28010
- LITERAL: "Literal",
28011
- THIS_EXP: "ThisExpression",
28012
- CALL_EXP: "CallExpression",
28013
- UNARY_EXP: "UnaryExpression",
28014
- BINARY_EXP: "BinaryExpression",
28015
- ARRAY_EXP: "ArrayExpression",
28016
- TAB_CODE: 9,
28017
- LF_CODE: 10,
28018
- CR_CODE: 13,
28019
- SPACE_CODE: 32,
28020
- PERIOD_CODE: 46,
28021
- COMMA_CODE: 44,
28022
- SQUOTE_CODE: 39,
28023
- DQUOTE_CODE: 34,
28024
- OPAREN_CODE: 40,
28025
- CPAREN_CODE: 41,
28026
- OBRACK_CODE: 91,
28027
- CBRACK_CODE: 93,
28028
- QUMARK_CODE: 63,
28029
- SEMCOL_CODE: 59,
28030
- COLON_CODE: 58,
28031
- unary_ops: {
28032
- "-": 1,
28033
- "!": 1,
28034
- "~": 1,
28035
- "+": 1
28036
- },
28037
- binary_ops: {
28038
- "||": 1,
28039
- "??": 1,
28040
- "&&": 2,
28041
- "|": 3,
28042
- "^": 4,
28043
- "&": 5,
28044
- "==": 6,
28045
- "!=": 6,
28046
- "===": 6,
28047
- "!==": 6,
28048
- "<": 7,
28049
- ">": 7,
28050
- "<=": 7,
28051
- ">=": 7,
28052
- "<<": 8,
28053
- ">>": 8,
28054
- ">>>": 8,
28055
- "+": 9,
28056
- "-": 9,
28057
- "*": 10,
28058
- "/": 10,
28059
- "%": 10,
28060
- "**": 11
28061
- },
28062
- right_associative: new Set(["**"]),
28063
- additional_identifier_chars: new Set(["$", "_"]),
28064
- literals: {
28065
- true: true,
28066
- false: false,
28067
- null: null
28068
- },
28069
- this_str: "this"
28070
- });
28071
- Jsep.max_unop_len = Jsep.getMaxKeyLen(Jsep.unary_ops);
28072
- Jsep.max_binop_len = Jsep.getMaxKeyLen(Jsep.binary_ops);
28073
- var jsep = (expr) => new Jsep(expr).parse();
28074
- var stdClassProps = Object.getOwnPropertyNames(class Test {
28075
- });
28076
- Object.getOwnPropertyNames(Jsep).filter((prop) => !stdClassProps.includes(prop) && jsep[prop] === undefined).forEach((m) => {
28077
- jsep[m] = Jsep[m];
28078
- });
28079
- jsep.Jsep = Jsep;
28080
- var CONDITIONAL_EXP = "ConditionalExpression";
28081
- var ternary = {
28082
- name: "ternary",
28083
- init(jsep2) {
28084
- jsep2.hooks.add("after-expression", function gobbleTernary(env) {
28085
- if (env.node && this.code === jsep2.QUMARK_CODE) {
28086
- this.index++;
28087
- const test = env.node;
28088
- const consequent = this.gobbleExpression();
28089
- if (!consequent) {
28090
- this.throwError("Expected expression");
28091
- }
28092
- this.gobbleSpaces();
28093
- if (this.code === jsep2.COLON_CODE) {
28094
- this.index++;
28095
- const alternate = this.gobbleExpression();
28096
- if (!alternate) {
28097
- this.throwError("Expected expression");
28098
- }
28099
- env.node = {
28100
- type: CONDITIONAL_EXP,
28101
- test,
28102
- consequent,
28103
- alternate
28104
- };
28105
- if (test.operator && jsep2.binary_ops[test.operator] <= 0.9) {
28106
- let newTest = test;
28107
- while (newTest.right.operator && jsep2.binary_ops[newTest.right.operator] <= 0.9) {
28108
- newTest = newTest.right;
28109
- }
28110
- env.node.test = newTest.right;
28111
- newTest.right = env.node;
28112
- env.node = test;
28113
- }
28114
- } else {
28115
- this.throwError("Expected :");
28116
- }
28117
- }
28118
- });
28119
- }
28120
- };
28121
- jsep.plugins.register(ternary);
28122
- var FSLASH_CODE = 47;
28123
- var BSLASH_CODE = 92;
28124
- var index = {
28125
- name: "regex",
28126
- init(jsep2) {
28127
- jsep2.hooks.add("gobble-token", function gobbleRegexLiteral(env) {
28128
- if (this.code === FSLASH_CODE) {
28129
- const patternIndex = ++this.index;
28130
- let inCharSet = false;
28131
- while (this.index < this.expr.length) {
28132
- if (this.code === FSLASH_CODE && !inCharSet) {
28133
- const pattern = this.expr.slice(patternIndex, this.index);
28134
- let flags = "";
28135
- while (++this.index < this.expr.length) {
28136
- const code = this.code;
28137
- if (code >= 97 && code <= 122 || code >= 65 && code <= 90 || code >= 48 && code <= 57) {
28138
- flags += this.char;
28139
- } else {
28140
- break;
28141
- }
28142
- }
28143
- let value;
28144
- try {
28145
- value = new RegExp(pattern, flags);
28146
- } catch (e) {
28147
- this.throwError(e.message);
28148
- }
28149
- env.node = {
28150
- type: jsep2.LITERAL,
28151
- value,
28152
- raw: this.expr.slice(patternIndex - 1, this.index)
28153
- };
28154
- env.node = this.gobbleTokenProperty(env.node);
28155
- return env.node;
28156
- }
28157
- if (this.code === jsep2.OBRACK_CODE) {
28158
- inCharSet = true;
28159
- } else if (inCharSet && this.code === jsep2.CBRACK_CODE) {
28160
- inCharSet = false;
28161
- }
28162
- this.index += this.code === BSLASH_CODE ? 2 : 1;
28163
- }
28164
- this.throwError("Unclosed Regex");
28165
- }
28166
- });
28167
- }
28168
- };
28169
- var PLUS_CODE = 43;
28170
- var MINUS_CODE = 45;
28171
- var plugin = {
28172
- name: "assignment",
28173
- assignmentOperators: new Set(["=", "*=", "**=", "/=", "%=", "+=", "-=", "<<=", ">>=", ">>>=", "&=", "^=", "|=", "||=", "&&=", "??="]),
28174
- updateOperators: [PLUS_CODE, MINUS_CODE],
28175
- assignmentPrecedence: 0.9,
28176
- init(jsep2) {
28177
- const updateNodeTypes = [jsep2.IDENTIFIER, jsep2.MEMBER_EXP];
28178
- plugin.assignmentOperators.forEach((op) => jsep2.addBinaryOp(op, plugin.assignmentPrecedence, true));
28179
- jsep2.hooks.add("gobble-token", function gobbleUpdatePrefix(env) {
28180
- const code = this.code;
28181
- if (plugin.updateOperators.some((c) => c === code && c === this.expr.charCodeAt(this.index + 1))) {
28182
- this.index += 2;
28183
- env.node = {
28184
- type: "UpdateExpression",
28185
- operator: code === PLUS_CODE ? "++" : "--",
28186
- argument: this.gobbleTokenProperty(this.gobbleIdentifier()),
28187
- prefix: true
28188
- };
28189
- if (!env.node.argument || !updateNodeTypes.includes(env.node.argument.type)) {
28190
- this.throwError(`Unexpected ${env.node.operator}`);
28191
- }
28192
- }
28193
- });
28194
- jsep2.hooks.add("after-token", function gobbleUpdatePostfix(env) {
28195
- if (env.node) {
28196
- const code = this.code;
28197
- if (plugin.updateOperators.some((c) => c === code && c === this.expr.charCodeAt(this.index + 1))) {
28198
- if (!updateNodeTypes.includes(env.node.type)) {
28199
- this.throwError(`Unexpected ${env.node.operator}`);
28200
- }
28201
- this.index += 2;
28202
- env.node = {
28203
- type: "UpdateExpression",
28204
- operator: code === PLUS_CODE ? "++" : "--",
28205
- argument: env.node,
28206
- prefix: false
28207
- };
28208
- }
28209
- }
28210
- });
28211
- jsep2.hooks.add("after-expression", function gobbleAssignment(env) {
28212
- if (env.node) {
28213
- updateBinariesToAssignments(env.node);
28214
- }
28215
- });
28216
- function updateBinariesToAssignments(node) {
28217
- if (plugin.assignmentOperators.has(node.operator)) {
28218
- node.type = "AssignmentExpression";
28219
- updateBinariesToAssignments(node.left);
28220
- updateBinariesToAssignments(node.right);
28221
- } else if (!node.operator) {
28222
- Object.values(node).forEach((val) => {
28223
- if (val && typeof val === "object") {
28224
- updateBinariesToAssignments(val);
28225
- }
28226
- });
28227
- }
28228
- }
28229
- }
28230
- };
28231
- jsep.plugins.register(index, plugin);
28232
- jsep.addUnaryOp("typeof");
28233
- jsep.addUnaryOp("void");
28234
- jsep.addLiteral("null", null);
28235
- jsep.addLiteral("undefined", undefined);
28236
- var BLOCKED_PROTO_PROPERTIES = new Set(["constructor", "__proto__", "__defineGetter__", "__defineSetter__", "__lookupGetter__", "__lookupSetter__"]);
28237
- var SafeEval = {
28238
- evalAst(ast, subs) {
28239
- switch (ast.type) {
28240
- case "BinaryExpression":
28241
- case "LogicalExpression":
28242
- return SafeEval.evalBinaryExpression(ast, subs);
28243
- case "Compound":
28244
- return SafeEval.evalCompound(ast, subs);
28245
- case "ConditionalExpression":
28246
- return SafeEval.evalConditionalExpression(ast, subs);
28247
- case "Identifier":
28248
- return SafeEval.evalIdentifier(ast, subs);
28249
- case "Literal":
28250
- return SafeEval.evalLiteral(ast, subs);
28251
- case "MemberExpression":
28252
- return SafeEval.evalMemberExpression(ast, subs);
28253
- case "UnaryExpression":
28254
- return SafeEval.evalUnaryExpression(ast, subs);
28255
- case "ArrayExpression":
28256
- return SafeEval.evalArrayExpression(ast, subs);
28257
- case "CallExpression":
28258
- return SafeEval.evalCallExpression(ast, subs);
28259
- case "AssignmentExpression":
28260
- return SafeEval.evalAssignmentExpression(ast, subs);
28261
- default:
28262
- throw SyntaxError("Unexpected expression", ast);
28263
- }
28264
- },
28265
- evalBinaryExpression(ast, subs) {
28266
- const result = {
28267
- "||": (a, b) => a || b(),
28268
- "&&": (a, b) => a && b(),
28269
- "|": (a, b) => a | b(),
28270
- "^": (a, b) => a ^ b(),
28271
- "&": (a, b) => a & b(),
28272
- "==": (a, b) => a == b(),
28273
- "!=": (a, b) => a != b(),
28274
- "===": (a, b) => a === b(),
28275
- "!==": (a, b) => a !== b(),
28276
- "<": (a, b) => a < b(),
28277
- ">": (a, b) => a > b(),
28278
- "<=": (a, b) => a <= b(),
28279
- ">=": (a, b) => a >= b(),
28280
- "<<": (a, b) => a << b(),
28281
- ">>": (a, b) => a >> b(),
28282
- ">>>": (a, b) => a >>> b(),
28283
- "+": (a, b) => a + b(),
28284
- "-": (a, b) => a - b(),
28285
- "*": (a, b) => a * b(),
28286
- "/": (a, b) => a / b(),
28287
- "%": (a, b) => a % b()
28288
- }[ast.operator](SafeEval.evalAst(ast.left, subs), () => SafeEval.evalAst(ast.right, subs));
28289
- return result;
28290
- },
28291
- evalCompound(ast, subs) {
28292
- let last;
28293
- for (let i = 0;i < ast.body.length; i++) {
28294
- if (ast.body[i].type === "Identifier" && ["var", "let", "const"].includes(ast.body[i].name) && ast.body[i + 1] && ast.body[i + 1].type === "AssignmentExpression") {
28295
- i += 1;
28296
- }
28297
- const expr = ast.body[i];
28298
- last = SafeEval.evalAst(expr, subs);
28299
- }
28300
- return last;
28301
- },
28302
- evalConditionalExpression(ast, subs) {
28303
- if (SafeEval.evalAst(ast.test, subs)) {
28304
- return SafeEval.evalAst(ast.consequent, subs);
28305
- }
28306
- return SafeEval.evalAst(ast.alternate, subs);
28307
- },
28308
- evalIdentifier(ast, subs) {
28309
- if (Object.hasOwn(subs, ast.name)) {
28310
- return subs[ast.name];
28311
- }
28312
- throw ReferenceError(`${ast.name} is not defined`);
28313
- },
28314
- evalLiteral(ast) {
28315
- return ast.value;
28316
- },
28317
- evalMemberExpression(ast, subs) {
28318
- const prop = String(ast.computed ? SafeEval.evalAst(ast.property) : ast.property.name);
28319
- const obj = SafeEval.evalAst(ast.object, subs);
28320
- if (obj === undefined || obj === null) {
28321
- throw TypeError(`Cannot read properties of ${obj} (reading '${prop}')`);
28322
- }
28323
- if (!Object.hasOwn(obj, prop) && BLOCKED_PROTO_PROPERTIES.has(prop)) {
28324
- throw TypeError(`Cannot read properties of ${obj} (reading '${prop}')`);
28325
- }
28326
- const result = obj[prop];
28327
- if (typeof result === "function") {
28328
- return result.bind(obj);
28329
- }
28330
- return result;
28331
- },
28332
- evalUnaryExpression(ast, subs) {
28333
- const result = {
28334
- "-": (a) => -SafeEval.evalAst(a, subs),
28335
- "!": (a) => !SafeEval.evalAst(a, subs),
28336
- "~": (a) => ~SafeEval.evalAst(a, subs),
28337
- "+": (a) => +SafeEval.evalAst(a, subs),
28338
- typeof: (a) => typeof SafeEval.evalAst(a, subs),
28339
- void: (a) => void SafeEval.evalAst(a, subs)
28340
- }[ast.operator](ast.argument);
28341
- return result;
28342
- },
28343
- evalArrayExpression(ast, subs) {
28344
- return ast.elements.map((el) => SafeEval.evalAst(el, subs));
28345
- },
28346
- evalCallExpression(ast, subs) {
28347
- const args = ast.arguments.map((arg) => SafeEval.evalAst(arg, subs));
28348
- const func = SafeEval.evalAst(ast.callee, subs);
28349
- if (func === Function) {
28350
- throw new Error("Function constructor is disabled");
28351
- }
28352
- return func(...args);
28353
- },
28354
- evalAssignmentExpression(ast, subs) {
28355
- if (ast.left.type !== "Identifier") {
28356
- throw SyntaxError("Invalid left-hand side in assignment");
28357
- }
28358
- const id = ast.left.name;
28359
- const value = SafeEval.evalAst(ast.right, subs);
28360
- subs[id] = value;
28361
- return subs[id];
28362
- }
28363
- };
28364
-
28365
- class SafeScript {
28366
- constructor(expr) {
28367
- this.code = expr;
28368
- this.ast = jsep(this.code);
28369
- }
28370
- runInNewContext(context) {
28371
- const keyMap = Object.assign(Object.create(null), context);
28372
- return SafeEval.evalAst(this.ast, keyMap);
28373
- }
28374
- }
28375
- function push(arr, item) {
28376
- arr = arr.slice();
28377
- arr.push(item);
28378
- return arr;
28379
- }
28380
- function unshift(item, arr) {
28381
- arr = arr.slice();
28382
- arr.unshift(item);
28383
- return arr;
28384
- }
28385
-
28386
- class NewError extends Error {
28387
- constructor(value) {
28388
- super('JSONPath should not be called with "new" (it prevents return ' + "of (unwrapped) scalar values)");
28389
- this.avoidNew = true;
28390
- this.value = value;
28391
- this.name = "NewError";
28392
- }
28393
- }
28394
- function JSONPath(opts, expr, obj, callback, otherTypeCallback) {
28395
- if (!(this instanceof JSONPath)) {
28396
- try {
28397
- return new JSONPath(opts, expr, obj, callback, otherTypeCallback);
28398
- } catch (e) {
28399
- if (!e.avoidNew) {
28400
- throw e;
28401
- }
28402
- return e.value;
28403
- }
28404
- }
28405
- if (typeof opts === "string") {
28406
- otherTypeCallback = callback;
28407
- callback = obj;
28408
- obj = expr;
28409
- expr = opts;
28410
- opts = null;
28411
- }
28412
- const optObj = opts && typeof opts === "object";
28413
- opts = opts || {};
28414
- this.json = opts.json || obj;
28415
- this.path = opts.path || expr;
28416
- this.resultType = opts.resultType || "value";
28417
- this.flatten = opts.flatten || false;
28418
- this.wrap = Object.hasOwn(opts, "wrap") ? opts.wrap : true;
28419
- this.sandbox = opts.sandbox || {};
28420
- this.eval = opts.eval === undefined ? "safe" : opts.eval;
28421
- this.ignoreEvalErrors = typeof opts.ignoreEvalErrors === "undefined" ? false : opts.ignoreEvalErrors;
28422
- this.parent = opts.parent || null;
28423
- this.parentProperty = opts.parentProperty || null;
28424
- this.callback = opts.callback || callback || null;
28425
- this.otherTypeCallback = opts.otherTypeCallback || otherTypeCallback || function() {
28426
- throw new TypeError("You must supply an otherTypeCallback callback option " + "with the @other() operator.");
28427
- };
28428
- if (opts.autostart !== false) {
28429
- const args = {
28430
- path: optObj ? opts.path : expr
28431
- };
28432
- if (!optObj) {
28433
- args.json = obj;
28434
- } else if ("json" in opts) {
28435
- args.json = opts.json;
28436
- }
28437
- const ret = this.evaluate(args);
28438
- if (!ret || typeof ret !== "object") {
28439
- throw new NewError(ret);
28440
- }
28441
- return ret;
28442
- }
28443
- }
28444
- JSONPath.prototype.evaluate = function(expr, json, callback, otherTypeCallback) {
28445
- let currParent = this.parent, currParentProperty = this.parentProperty;
28446
- let {
28447
- flatten,
28448
- wrap
28449
- } = this;
28450
- this.currResultType = this.resultType;
28451
- this.currEval = this.eval;
28452
- this.currSandbox = this.sandbox;
28453
- callback = callback || this.callback;
28454
- this.currOtherTypeCallback = otherTypeCallback || this.otherTypeCallback;
28455
- json = json || this.json;
28456
- expr = expr || this.path;
28457
- if (expr && typeof expr === "object" && !Array.isArray(expr)) {
28458
- if (!expr.path && expr.path !== "") {
28459
- throw new TypeError('You must supply a "path" property when providing an object ' + "argument to JSONPath.evaluate().");
28460
- }
28461
- if (!Object.hasOwn(expr, "json")) {
28462
- throw new TypeError('You must supply a "json" property when providing an object ' + "argument to JSONPath.evaluate().");
28463
- }
28464
- ({
28465
- json
28466
- } = expr);
28467
- flatten = Object.hasOwn(expr, "flatten") ? expr.flatten : flatten;
28468
- this.currResultType = Object.hasOwn(expr, "resultType") ? expr.resultType : this.currResultType;
28469
- this.currSandbox = Object.hasOwn(expr, "sandbox") ? expr.sandbox : this.currSandbox;
28470
- wrap = Object.hasOwn(expr, "wrap") ? expr.wrap : wrap;
28471
- this.currEval = Object.hasOwn(expr, "eval") ? expr.eval : this.currEval;
28472
- callback = Object.hasOwn(expr, "callback") ? expr.callback : callback;
28473
- this.currOtherTypeCallback = Object.hasOwn(expr, "otherTypeCallback") ? expr.otherTypeCallback : this.currOtherTypeCallback;
28474
- currParent = Object.hasOwn(expr, "parent") ? expr.parent : currParent;
28475
- currParentProperty = Object.hasOwn(expr, "parentProperty") ? expr.parentProperty : currParentProperty;
28476
- expr = expr.path;
28477
- }
28478
- currParent = currParent || null;
28479
- currParentProperty = currParentProperty || null;
28480
- if (Array.isArray(expr)) {
28481
- expr = JSONPath.toPathString(expr);
28482
- }
28483
- if (!expr && expr !== "" || !json) {
28484
- return;
28485
- }
28486
- const exprList = JSONPath.toPathArray(expr);
28487
- if (exprList[0] === "$" && exprList.length > 1) {
28488
- exprList.shift();
28489
- }
28490
- this._hasParentSelector = null;
28491
- const result = this._trace(exprList, json, ["$"], currParent, currParentProperty, callback).filter(function(ea) {
28492
- return ea && !ea.isParentSelector;
28493
- });
28494
- if (!result.length) {
28495
- return wrap ? [] : undefined;
28496
- }
28497
- if (!wrap && result.length === 1 && !result[0].hasArrExpr) {
28498
- return this._getPreferredOutput(result[0]);
28499
- }
28500
- return result.reduce((rslt, ea) => {
28501
- const valOrPath = this._getPreferredOutput(ea);
28502
- if (flatten && Array.isArray(valOrPath)) {
28503
- rslt = rslt.concat(valOrPath);
28504
- } else {
28505
- rslt.push(valOrPath);
28506
- }
28507
- return rslt;
28508
- }, []);
28509
- };
28510
- JSONPath.prototype._getPreferredOutput = function(ea) {
28511
- const resultType = this.currResultType;
28512
- switch (resultType) {
28513
- case "all": {
28514
- const path3 = Array.isArray(ea.path) ? ea.path : JSONPath.toPathArray(ea.path);
28515
- ea.pointer = JSONPath.toPointer(path3);
28516
- ea.path = typeof ea.path === "string" ? ea.path : JSONPath.toPathString(ea.path);
28517
- return ea;
28518
- }
28519
- case "value":
28520
- case "parent":
28521
- case "parentProperty":
28522
- return ea[resultType];
28523
- case "path":
28524
- return JSONPath.toPathString(ea[resultType]);
28525
- case "pointer":
28526
- return JSONPath.toPointer(ea.path);
28527
- default:
28528
- throw new TypeError("Unknown result type");
28529
- }
28530
- };
28531
- JSONPath.prototype._handleCallback = function(fullRetObj, callback, type) {
28532
- if (callback) {
28533
- const preferredOutput = this._getPreferredOutput(fullRetObj);
28534
- fullRetObj.path = typeof fullRetObj.path === "string" ? fullRetObj.path : JSONPath.toPathString(fullRetObj.path);
28535
- callback(preferredOutput, type, fullRetObj);
28536
- }
28537
- };
28538
- JSONPath.prototype._trace = function(expr, val, path3, parent, parentPropName, callback, hasArrExpr, literalPriority) {
28539
- let retObj;
28540
- if (!expr.length) {
28541
- retObj = {
28542
- path: path3,
28543
- value: val,
28544
- parent,
28545
- parentProperty: parentPropName,
28546
- hasArrExpr
28547
- };
28548
- this._handleCallback(retObj, callback, "value");
28549
- return retObj;
28550
- }
28551
- const loc = expr[0], x = expr.slice(1);
28552
- const ret = [];
28553
- function addRet(elems) {
28554
- if (Array.isArray(elems)) {
28555
- elems.forEach((t) => {
28556
- ret.push(t);
28557
- });
28558
- } else {
28559
- ret.push(elems);
28560
- }
28561
- }
28562
- if ((typeof loc !== "string" || literalPriority) && val && Object.hasOwn(val, loc)) {
28563
- addRet(this._trace(x, val[loc], push(path3, loc), val, loc, callback, hasArrExpr));
28564
- } else if (loc === "*") {
28565
- this._walk(val, (m) => {
28566
- addRet(this._trace(x, val[m], push(path3, m), val, m, callback, true, true));
28567
- });
28568
- } else if (loc === "..") {
28569
- addRet(this._trace(x, val, path3, parent, parentPropName, callback, hasArrExpr));
28570
- this._walk(val, (m) => {
28571
- if (typeof val[m] === "object") {
28572
- addRet(this._trace(expr.slice(), val[m], push(path3, m), val, m, callback, true));
28573
- }
28574
- });
28575
- } else if (loc === "^") {
28576
- this._hasParentSelector = true;
28577
- return {
28578
- path: path3.slice(0, -1),
28579
- expr: x,
28580
- isParentSelector: true
28581
- };
28582
- } else if (loc === "~") {
28583
- retObj = {
28584
- path: push(path3, loc),
28585
- value: parentPropName,
28586
- parent,
28587
- parentProperty: null
28588
- };
28589
- this._handleCallback(retObj, callback, "property");
28590
- return retObj;
28591
- } else if (loc === "$") {
28592
- addRet(this._trace(x, val, path3, null, null, callback, hasArrExpr));
28593
- } else if (/^(-?\d*):(-?\d*):?(\d*)$/u.test(loc)) {
28594
- addRet(this._slice(loc, x, val, path3, parent, parentPropName, callback));
28595
- } else if (loc.indexOf("?(") === 0) {
28596
- if (this.currEval === false) {
28597
- throw new Error("Eval [?(expr)] prevented in JSONPath expression.");
28598
- }
28599
- const safeLoc = loc.replace(/^\?\((.*?)\)$/u, "$1");
28600
- const nested = /@.?([^?]*)[['](\??\(.*?\))(?!.\)\])[\]']/gu.exec(safeLoc);
28601
- if (nested) {
28602
- this._walk(val, (m) => {
28603
- const npath = [nested[2]];
28604
- const nvalue = nested[1] ? val[m][nested[1]] : val[m];
28605
- const filterResults = this._trace(npath, nvalue, path3, parent, parentPropName, callback, true);
28606
- if (filterResults.length > 0) {
28607
- addRet(this._trace(x, val[m], push(path3, m), val, m, callback, true));
28608
- }
28609
- });
28610
- } else {
28611
- this._walk(val, (m) => {
28612
- if (this._eval(safeLoc, val[m], m, path3, parent, parentPropName)) {
28613
- addRet(this._trace(x, val[m], push(path3, m), val, m, callback, true));
28614
- }
28615
- });
28616
- }
28617
- } else if (loc[0] === "(") {
28618
- if (this.currEval === false) {
28619
- throw new Error("Eval [(expr)] prevented in JSONPath expression.");
28620
- }
28621
- addRet(this._trace(unshift(this._eval(loc, val, path3.at(-1), path3.slice(0, -1), parent, parentPropName), x), val, path3, parent, parentPropName, callback, hasArrExpr));
28622
- } else if (loc[0] === "@") {
28623
- let addType = false;
28624
- const valueType = loc.slice(1, -2);
28625
- switch (valueType) {
28626
- case "scalar":
28627
- if (!val || !["object", "function"].includes(typeof val)) {
28628
- addType = true;
28629
- }
28630
- break;
28631
- case "boolean":
28632
- case "string":
28633
- case "undefined":
28634
- case "function":
28635
- if (typeof val === valueType) {
28636
- addType = true;
28637
- }
28638
- break;
28639
- case "integer":
28640
- if (Number.isFinite(val) && !(val % 1)) {
28641
- addType = true;
28642
- }
28643
- break;
28644
- case "number":
28645
- if (Number.isFinite(val)) {
28646
- addType = true;
28647
- }
28648
- break;
28649
- case "nonFinite":
28650
- if (typeof val === "number" && !Number.isFinite(val)) {
28651
- addType = true;
28652
- }
28653
- break;
28654
- case "object":
28655
- if (val && typeof val === valueType) {
28656
- addType = true;
28657
- }
28658
- break;
28659
- case "array":
28660
- if (Array.isArray(val)) {
28661
- addType = true;
28662
- }
28663
- break;
28664
- case "other":
28665
- addType = this.currOtherTypeCallback(val, path3, parent, parentPropName);
28666
- break;
28667
- case "null":
28668
- if (val === null) {
28669
- addType = true;
28670
- }
28671
- break;
28672
- default:
28673
- throw new TypeError("Unknown value type " + valueType);
28674
- }
28675
- if (addType) {
28676
- retObj = {
28677
- path: path3,
28678
- value: val,
28679
- parent,
28680
- parentProperty: parentPropName
28681
- };
28682
- this._handleCallback(retObj, callback, "value");
28683
- return retObj;
28684
- }
28685
- } else if (loc[0] === "`" && val && Object.hasOwn(val, loc.slice(1))) {
28686
- const locProp = loc.slice(1);
28687
- addRet(this._trace(x, val[locProp], push(path3, locProp), val, locProp, callback, hasArrExpr, true));
28688
- } else if (loc.includes(",")) {
28689
- const parts = loc.split(",");
28690
- for (const part of parts) {
28691
- addRet(this._trace(unshift(part, x), val, path3, parent, parentPropName, callback, true));
28692
- }
28693
- } else if (!literalPriority && val && Object.hasOwn(val, loc)) {
28694
- addRet(this._trace(x, val[loc], push(path3, loc), val, loc, callback, hasArrExpr, true));
28695
- }
28696
- if (this._hasParentSelector) {
28697
- for (let t = 0;t < ret.length; t++) {
28698
- const rett = ret[t];
28699
- if (rett && rett.isParentSelector) {
28700
- const tmp = this._trace(rett.expr, val, rett.path, parent, parentPropName, callback, hasArrExpr);
28701
- if (Array.isArray(tmp)) {
28702
- ret[t] = tmp[0];
28703
- const tl = tmp.length;
28704
- for (let tt = 1;tt < tl; tt++) {
28705
- t++;
28706
- ret.splice(t, 0, tmp[tt]);
28707
- }
28708
- } else {
28709
- ret[t] = tmp;
28710
- }
28711
- }
28712
- }
28713
- }
28714
- return ret;
28715
- };
28716
- JSONPath.prototype._walk = function(val, f) {
28717
- if (Array.isArray(val)) {
28718
- const n = val.length;
28719
- for (let i = 0;i < n; i++) {
28720
- f(i);
28721
- }
28722
- } else if (val && typeof val === "object") {
28723
- Object.keys(val).forEach((m) => {
28724
- f(m);
28725
- });
28726
- }
28727
- };
28728
- JSONPath.prototype._slice = function(loc, expr, val, path3, parent, parentPropName, callback) {
28729
- if (!Array.isArray(val)) {
28730
- return;
28731
- }
28732
- const len = val.length, parts = loc.split(":"), step = parts[2] && Number.parseInt(parts[2]) || 1;
28733
- let start = parts[0] && Number.parseInt(parts[0]) || 0, end = parts[1] && Number.parseInt(parts[1]) || len;
28734
- start = start < 0 ? Math.max(0, start + len) : Math.min(len, start);
28735
- end = end < 0 ? Math.max(0, end + len) : Math.min(len, end);
28736
- const ret = [];
28737
- for (let i = start;i < end; i += step) {
28738
- const tmp = this._trace(unshift(i, expr), val, path3, parent, parentPropName, callback, true);
28739
- tmp.forEach((t) => {
28740
- ret.push(t);
28741
- });
28742
- }
28743
- return ret;
28744
- };
28745
- JSONPath.prototype._eval = function(code, _v, _vname, path3, parent, parentPropName) {
28746
- this.currSandbox._$_parentProperty = parentPropName;
28747
- this.currSandbox._$_parent = parent;
28748
- this.currSandbox._$_property = _vname;
28749
- this.currSandbox._$_root = this.json;
28750
- this.currSandbox._$_v = _v;
28751
- const containsPath = code.includes("@path");
28752
- if (containsPath) {
28753
- this.currSandbox._$_path = JSONPath.toPathString(path3.concat([_vname]));
28754
- }
28755
- const scriptCacheKey = this.currEval + "Script:" + code;
28756
- if (!JSONPath.cache[scriptCacheKey]) {
28757
- let script = code.replaceAll("@parentProperty", "_$_parentProperty").replaceAll("@parent", "_$_parent").replaceAll("@property", "_$_property").replaceAll("@root", "_$_root").replaceAll(/@([.\s)[])/gu, "_$_v$1");
28758
- if (containsPath) {
28759
- script = script.replaceAll("@path", "_$_path");
28760
- }
28761
- if (this.currEval === "safe" || this.currEval === true || this.currEval === undefined) {
28762
- JSONPath.cache[scriptCacheKey] = new this.safeVm.Script(script);
28763
- } else if (this.currEval === "native") {
28764
- JSONPath.cache[scriptCacheKey] = new this.vm.Script(script);
28765
- } else if (typeof this.currEval === "function" && this.currEval.prototype && Object.hasOwn(this.currEval.prototype, "runInNewContext")) {
28766
- const CurrEval = this.currEval;
28767
- JSONPath.cache[scriptCacheKey] = new CurrEval(script);
28768
- } else if (typeof this.currEval === "function") {
28769
- JSONPath.cache[scriptCacheKey] = {
28770
- runInNewContext: (context) => this.currEval(script, context)
28771
- };
28772
- } else {
28773
- throw new TypeError(`Unknown "eval" property "${this.currEval}"`);
28774
- }
28775
- }
28776
- try {
28777
- return JSONPath.cache[scriptCacheKey].runInNewContext(this.currSandbox);
28778
- } catch (e) {
28779
- if (this.ignoreEvalErrors) {
28780
- return false;
28781
- }
28782
- throw new Error("jsonPath: " + e.message + ": " + code);
28783
- }
28784
- };
28785
- JSONPath.cache = {};
28786
- JSONPath.toPathString = function(pathArr) {
28787
- const x = pathArr, n = x.length;
28788
- let p = "$";
28789
- for (let i = 1;i < n; i++) {
28790
- if (!/^(~|\^|@.*?\(\))$/u.test(x[i])) {
28791
- p += /^[0-9*]+$/u.test(x[i]) ? "[" + x[i] + "]" : "['" + x[i] + "']";
28792
- }
28793
- }
28794
- return p;
28795
- };
28796
- JSONPath.toPointer = function(pointer) {
28797
- const x = pointer, n = x.length;
28798
- let p = "";
28799
- for (let i = 1;i < n; i++) {
28800
- if (!/^(~|\^|@.*?\(\))$/u.test(x[i])) {
28801
- p += "/" + x[i].toString().replaceAll("~", "~0").replaceAll("/", "~1");
28802
- }
28803
- }
28804
- return p;
28805
- };
28806
- JSONPath.toPathArray = function(expr) {
28807
- const {
28808
- cache
28809
- } = JSONPath;
28810
- if (cache[expr]) {
28811
- return cache[expr].concat();
28812
- }
28813
- const subx = [];
28814
- const normalized = expr.replaceAll(/@(?:null|boolean|number|string|integer|undefined|nonFinite|scalar|array|object|function|other)\(\)/gu, ";$&;").replaceAll(/[['](\??\(.*?\))[\]'](?!.\])/gu, function($0, $1) {
28815
- return "[#" + (subx.push($1) - 1) + "]";
28816
- }).replaceAll(/\[['"]([^'\]]*)['"]\]/gu, function($0, prop) {
28817
- return "['" + prop.replaceAll(".", "%@%").replaceAll("~", "%%@@%%") + "']";
28818
- }).replaceAll("~", ";~;").replaceAll(/['"]?\.['"]?(?![^[]*\])|\[['"]?/gu, ";").replaceAll("%@%", ".").replaceAll("%%@@%%", "~").replaceAll(/(?:;)?(\^+)(?:;)?/gu, function($0, ups) {
28819
- return ";" + ups.split("").join(";") + ";";
28820
- }).replaceAll(/;;;|;;/gu, ";..;").replaceAll(/;$|'?\]|'$/gu, "");
28821
- const exprList = normalized.split(";").map(function(exp) {
28822
- const match = exp.match(/#(\d+)/u);
28823
- return !match || !match[1] ? exp : subx[match[1]];
28824
- });
28825
- cache[expr] = exprList;
28826
- return cache[expr].concat();
28827
- };
28828
- JSONPath.prototype.safeVm = {
28829
- Script: SafeScript
28830
- };
28831
- JSONPath.prototype.vm = vm;
28832
- // ../common/src/option-aliases.ts
28833
- function resolveDeprecatedOptionAlias({
28834
- preferredValue,
28835
- deprecatedValue,
28836
- preferredFlag,
28837
- deprecatedFlag
28838
- }) {
28839
- const hasPreferred = preferredValue !== undefined;
28840
- const hasDeprecated = deprecatedValue !== undefined;
28841
- if (hasPreferred && hasDeprecated) {
28842
- return {
28843
- value: undefined,
28844
- usedDeprecated: true,
28845
- error: {
28846
- message: `${deprecatedFlag} and ${preferredFlag} are aliases. Use only ${preferredFlag}.`,
28847
- instructions: `Replace ${deprecatedFlag} with ${preferredFlag}.`
28848
- }
28849
- };
28850
- }
28851
- return {
28852
- value: hasPreferred ? preferredValue : deprecatedValue,
28853
- usedDeprecated: hasDeprecated
28854
- };
28855
- }
28856
- function warnDeprecatedOptionAlias(deprecatedFlag, preferredFlag) {
28857
- getOutputSink().writeErr(`[WARN] ${deprecatedFlag} is deprecated. Use ${preferredFlag} instead.
28858
- `);
28859
- }
28860
- var TENANT_SWITCH_COMMAND = "uip login tenant set <tenant>";
28861
- function createHiddenDeprecatedTenantOption(flags = "-t, --tenant <tenant-name>") {
28862
- return new Option(flags, `Tenant name. Deprecated; use ${TENANT_SWITCH_COMMAND} to switch active tenants.`).hideHelp().argParser((tenant) => {
28863
- warnDeprecatedTenantOption(tenant);
28864
- return tenant;
28865
- });
28866
- }
28867
- function warnDeprecatedTenantOption(tenant) {
28868
- if (tenant === undefined)
28869
- return;
28870
- warnDeprecatedOptionAlias("--tenant", TENANT_SWITCH_COMMAND);
28871
- }
28872
- // ../common/src/polling/types.ts
28873
- var PollOutcome = {
28874
- Completed: "completed",
28875
- Timeout: "timeout",
28876
- Interrupted: "interrupted",
28877
- Aborted: "aborted",
28878
- Failed: "failed"
28879
- };
28880
-
28881
- // ../common/src/polling/poll-failure-mapping.ts
28882
- var REASON_BY_OUTCOME = {
28883
- [PollOutcome.Timeout]: "poll_timeout",
28884
- [PollOutcome.Failed]: "poll_failed",
28885
- [PollOutcome.Interrupted]: "poll_failed",
28886
- [PollOutcome.Aborted]: "poll_aborted"
28887
- };
28888
- // ../common/src/polling/terminal-statuses.ts
28889
- var TERMINAL_STATUSES = new Set([
28890
- "completed",
28891
- "successful",
28892
- "faulted",
28893
- "failed",
28894
- "cancelled",
28895
- "canceled",
28896
- "stopped",
28897
- "finished"
28898
- ]);
28899
- var FAILURE_STATUSES = new Set([
28900
- "faulted",
28901
- "failed",
28902
- "cancelled",
28903
- "canceled",
28904
- "stopped"
28905
- ]);
28906
- // ../common/src/screen-logger.ts
28907
- var ScreenLogger;
28908
- ((ScreenLogger) => {
28909
- function progress(message) {
28910
- getOutputSink().writeErr(`${message}
28911
- `);
28912
- }
28913
- ScreenLogger.progress = progress;
28914
- })(ScreenLogger ||= {});
28915
- // ../common/src/sdk-user-agent.ts
28916
- var USER_AGENT_HEADER = "User-Agent";
28917
- var sdkUserAgentHostToken = singleton("SdkUserAgentHostToken");
28918
- function userAgentPatchKey(userAgent) {
28919
- return Symbol.for(`@uipath/common/sdk-user-agent/${userAgent}`);
28920
- }
28921
- function splitUserAgentTokens(value) {
28922
- return value?.trim().split(/\s+/).filter(Boolean) ?? [];
28923
- }
28924
- function appendUserAgentToken(value, userAgent) {
28925
- const tokens = splitUserAgentTokens(value);
28926
- const seen = new Set(tokens);
28927
- for (const token of splitUserAgentTokens(userAgent)) {
28928
- if (!seen.has(token)) {
28929
- tokens.push(token);
28930
- seen.add(token);
28931
- }
28932
- }
28933
- return tokens.join(" ");
28934
- }
28935
- function getEffectiveUserAgent(userAgent) {
28936
- return appendUserAgentToken(sdkUserAgentHostToken.get(), userAgent);
28937
- }
28938
- function isHeadersLike(headers) {
28939
- return typeof headers === "object" && headers !== null && "get" in headers && typeof headers.get === "function" && "set" in headers && typeof headers.set === "function";
28940
- }
28941
- function getSdkUserAgentToken(pkg) {
28942
- const packageName = pkg.name.replace(/^@uipath\//, "");
28943
- return getEffectiveUserAgent(`${packageName}/${pkg.version}`);
28944
- }
28945
- function addSdkUserAgentHeader(headers, userAgent) {
28946
- const result = { ...headers ?? {} };
28947
- const effectiveUserAgent = getEffectiveUserAgent(userAgent);
28948
- const headerName = Object.keys(result).find((key) => key.toLowerCase() === USER_AGENT_HEADER.toLowerCase());
28949
- if (headerName) {
28950
- result[headerName] = appendUserAgentToken(result[headerName], effectiveUserAgent);
28951
- } else {
28952
- result[USER_AGENT_HEADER] = effectiveUserAgent;
28953
- }
28954
- return result;
28955
- }
28956
- function withSdkUserAgentHeader(headers, userAgent) {
28957
- const effectiveUserAgent = getEffectiveUserAgent(userAgent);
28958
- if (isHeadersLike(headers)) {
28959
- headers.set(USER_AGENT_HEADER, appendUserAgentToken(headers.get(USER_AGENT_HEADER), effectiveUserAgent));
28960
- return headers;
28961
- }
28962
- if (Array.isArray(headers)) {
28963
- const result = headers.map((entry) => {
28964
- const [key, value] = entry;
28965
- return [key, value];
28966
- });
28967
- const headerIndex = result.findIndex(([key]) => key.toLowerCase() === USER_AGENT_HEADER.toLowerCase());
28968
- if (headerIndex >= 0) {
28969
- const [key, value] = result[headerIndex];
28970
- result[headerIndex] = [
28971
- key,
28972
- appendUserAgentToken(value, effectiveUserAgent)
28973
- ];
28974
- } else {
28975
- result.push([USER_AGENT_HEADER, effectiveUserAgent]);
28976
- }
28977
- return result;
28978
- }
28979
- return addSdkUserAgentHeader(typeof headers === "object" && headers !== null ? { ...headers } : {}, effectiveUserAgent);
28980
- }
28981
- function withUserAgentInitOverride(initOverrides, userAgent) {
28982
- return async (requestContext) => {
28983
- const initWithUserAgent = {
28984
- ...requestContext.init,
28985
- headers: withSdkUserAgentHeader(requestContext.init.headers, userAgent)
28986
- };
28987
- const override = typeof initOverrides === "function" ? await initOverrides({
28988
- ...requestContext,
28989
- init: initWithUserAgent
28990
- }) : initOverrides;
28991
- return {
28992
- ...override ?? {},
28993
- headers: withSdkUserAgentHeader(override?.headers ?? initWithUserAgent.headers, userAgent)
28994
- };
28995
- };
28996
- }
28997
- function installSdkUserAgentHeader(BaseApiClass, userAgent) {
28998
- const prototype = BaseApiClass.prototype;
28999
- const patchKey = userAgentPatchKey(userAgent);
29000
- if (prototype[patchKey]) {
29001
- return;
29002
- }
29003
- if (typeof prototype.request !== "function") {
29004
- throw new Error("Generated BaseAPI request function not found.");
29005
- }
29006
- const originalRequest = prototype.request;
29007
- prototype.request = function requestWithUserAgent(context, initOverrides) {
29008
- return originalRequest.call(this, context, withUserAgentInitOverride(initOverrides, userAgent));
29009
- };
29010
- Object.defineProperty(prototype, patchKey, {
29011
- value: true
29012
- });
29013
- }
29014
- // ../common/src/tool-provider.ts
29015
- var factorySlot = singleton("PackagerFactoryProvider");
29016
- // ../auth/src/config.ts
29017
- init_constants();
29018
- var DEFAULT_CLIENT_ID = "36dea5b8-e8bb-423d-8e7b-c808df8f1c00";
29019
- var AUTH_FILE_CONFIG_KEY = Symbol.for("@uipath/auth/AuthFileConfig");
29020
- var globalSlot = globalThis;
29021
- var getAuthFileConfig = () => globalSlot[AUTH_FILE_CONFIG_KEY] ?? {};
29022
-
29023
- class InvalidBaseUrlError extends Error {
29024
- url;
29025
- reason;
29026
- constructor(url, reason) {
29027
- super(`Invalid base URL: "${url}"
29028
- ` + `Reason: ${reason}
29029
-
29030
- ` + `Expected format: an https:// URL, e.g. https://cloud.uipath.com (commercial), https://govcloud.uipath.us (Public Sector), or your Automation Suite host (https://<your-host>).
29031
- ` + `You can specify the URL via:
29032
- ` + ` • --authority flag
29033
- ` + ` • UIPATH_URL environment variable
29034
- ` + ` • auth.authority in config file`);
29035
- this.url = url;
29036
- this.reason = reason;
29037
- this.name = "InvalidBaseUrlError";
29038
- }
29039
- }
29040
- var DEFAULT_SCOPES = ["openid", "profile", "offline_access"];
29041
- var normalizeAndValidateBaseUrl = (rawUrl) => {
29042
- let baseUrl = rawUrl;
29043
- if (baseUrl.endsWith("/identity_/")) {
29044
- baseUrl = baseUrl.slice(0, -11);
29045
- } else if (baseUrl.endsWith("/identity_")) {
29046
- baseUrl = baseUrl.slice(0, -10);
29047
- }
29048
- while (baseUrl.endsWith("/")) {
29049
- baseUrl = baseUrl.slice(0, -1);
29050
- }
29051
- const resolvedBaseUrl = baseUrl;
29052
- const [urlError, url] = catchError2(() => new URL(resolvedBaseUrl));
29053
- if (urlError) {
29054
- throw new InvalidBaseUrlError(baseUrl, `Malformed URL. ${urlError instanceof Error ? urlError.message : "Unknown error"}`);
29055
- }
29056
- if (url.protocol !== "https:") {
29057
- throw new InvalidBaseUrlError(baseUrl, `Authority must use https:// scheme, got ${url.protocol}//. OIDC token exchange requires TLS end-to-end.`);
29058
- }
29059
- return url.pathname.length > 1 ? url.origin : baseUrl;
29060
- };
29061
- var resolveConfigAsync = async ({
29062
- customAuthority,
29063
- customClientId,
29064
- customClientSecret,
29065
- customScopes
29066
- } = {}) => {
29067
- const fileAuth = getAuthFileConfig();
29068
- let baseUrl = customAuthority;
29069
- if (!baseUrl) {
29070
- baseUrl = process.env.UIPATH_URL;
29071
- }
29072
- if (!baseUrl && fileAuth.authority) {
29073
- baseUrl = fileAuth.authority;
27777
+ if (!baseUrl && fileAuth.authority) {
27778
+ baseUrl = fileAuth.authority;
29074
27779
  }
29075
27780
  if (!baseUrl) {
29076
27781
  baseUrl = DEFAULT_BASE_URL;
@@ -29088,7 +27793,7 @@ var resolveConfigAsync = async ({
29088
27793
  clientSecret = fileAuth.clientSecret;
29089
27794
  }
29090
27795
  const isExternalAppAuth = clientId !== DEFAULT_CLIENT_ID && Boolean(clientSecret);
29091
- const scopes = customScopes && customScopes.length > 0 ? customScopes : fileAuth.scopes && fileAuth.scopes.length > 0 ? fileAuth.scopes : isExternalAppAuth ? [] : DEFAULT_SCOPES;
27796
+ const scopes = resolveScopes(isExternalAppAuth, customScopes, fileAuth.scopes);
29092
27797
  return {
29093
27798
  clientId,
29094
27799
  clientSecret,
@@ -29103,6 +27808,76 @@ var resolveConfigAsync = async ({
29103
27808
  init_constants();
29104
27809
  // ../auth/src/loginStatus.ts
29105
27810
  init_src();
27811
+
27812
+ // ../auth/src/authProfile.ts
27813
+ init_src();
27814
+ init_constants();
27815
+ var DEFAULT_AUTH_PROFILE = "default";
27816
+ var PROFILE_DIR = "profiles";
27817
+ var PROFILE_NAME_RE = /^[A-Za-z0-9._-]+$/;
27818
+ var ACTIVE_AUTH_PROFILE_KEY = Symbol.for("@uipath/auth/ActiveAuthProfile");
27819
+ var AUTH_PROFILE_STORAGE_KEY = Symbol.for("@uipath/auth/ProfileStorage");
27820
+ var globalSlot2 = globalThis;
27821
+ function isAuthProfileStorage(value) {
27822
+ return value !== null && typeof value === "object" && "getStore" in value && "run" in value;
27823
+ }
27824
+ function createProfileStorage() {
27825
+ const [error, mod2] = catchError2(() => __require("node:async_hooks"));
27826
+ if (error || typeof mod2?.AsyncLocalStorage !== "function") {
27827
+ return {
27828
+ getStore: () => {
27829
+ return;
27830
+ },
27831
+ run: (_store, fn) => fn()
27832
+ };
27833
+ }
27834
+ return new mod2.AsyncLocalStorage;
27835
+ }
27836
+ function getProfileStorage() {
27837
+ const existing = globalSlot2[AUTH_PROFILE_STORAGE_KEY];
27838
+ if (isAuthProfileStorage(existing)) {
27839
+ return existing;
27840
+ }
27841
+ const storage = createProfileStorage();
27842
+ globalSlot2[AUTH_PROFILE_STORAGE_KEY] = storage;
27843
+ return storage;
27844
+ }
27845
+ var profileStorage = getProfileStorage();
27846
+
27847
+ class AuthProfileValidationError extends Error {
27848
+ constructor(message) {
27849
+ super(message);
27850
+ this.name = "AuthProfileValidationError";
27851
+ }
27852
+ }
27853
+ function normalizeAuthProfileName(profile) {
27854
+ if (profile === undefined || profile === DEFAULT_AUTH_PROFILE) {
27855
+ return;
27856
+ }
27857
+ if (profile.length === 0 || profile === "." || profile === ".." || !PROFILE_NAME_RE.test(profile)) {
27858
+ throw new AuthProfileValidationError(`Invalid profile name "${profile}". Profile names may contain only letters, numbers, '.', '_', and '-'.`);
27859
+ }
27860
+ return profile;
27861
+ }
27862
+ function getActiveAuthProfile() {
27863
+ const scopedState = profileStorage.getStore();
27864
+ if (scopedState !== undefined) {
27865
+ return scopedState.profile;
27866
+ }
27867
+ return globalSlot2[ACTIVE_AUTH_PROFILE_KEY]?.profile;
27868
+ }
27869
+ function resolveAuthProfileFilePath(profile) {
27870
+ const normalized = normalizeAuthProfileName(profile);
27871
+ if (normalized === undefined) {
27872
+ throw new AuthProfileValidationError(`"${DEFAULT_AUTH_PROFILE}" is the built-in profile and does not have a profile file path.`);
27873
+ }
27874
+ const fs7 = getFileSystem();
27875
+ return fs7.path.join(fs7.env.homedir(), UIPATH_HOME_DIR, PROFILE_DIR, normalized, AUTH_FILENAME);
27876
+ }
27877
+ function getActiveAuthProfileFilePath() {
27878
+ const profile = getActiveAuthProfile();
27879
+ return profile ? resolveAuthProfileFilePath(profile) : undefined;
27880
+ }
29106
27881
  // ../auth/src/utils/jwt.ts
29107
27882
  class InvalidIssuerError extends Error {
29108
27883
  expected;
@@ -29231,23 +28006,74 @@ var readAuthFromEnv = () => {
29231
28006
  organizationId,
29232
28007
  tenantName,
29233
28008
  tenantId,
29234
- expiration
28009
+ expiration,
28010
+ source: "env" /* Env */
29235
28011
  };
29236
28012
  };
29237
28013
 
28014
+ // ../auth/src/refreshCircuitBreaker.ts
28015
+ init_src();
28016
+ var BREAKER_SUFFIX = ".refresh-state";
28017
+ var BACKOFF_BASE_MS = 60000;
28018
+ var BACKOFF_CAP_MS = 60 * 60 * 1000;
28019
+ var SURFACE_WINDOW_MS = 60 * 60 * 1000;
28020
+ async function refreshTokenFingerprint(refreshToken) {
28021
+ const bytes = new TextEncoder().encode(refreshToken);
28022
+ if (globalThis.crypto?.subtle) {
28023
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", bytes);
28024
+ return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("").slice(0, 16);
28025
+ }
28026
+ const { createHash } = await import("node:crypto");
28027
+ return createHash("sha256").update(refreshToken).digest("hex").slice(0, 16);
28028
+ }
28029
+ function breakerPathFor(authPath) {
28030
+ return `${authPath}${BREAKER_SUFFIX}`;
28031
+ }
28032
+ async function loadRefreshBreaker(authPath) {
28033
+ const fs7 = getFileSystem();
28034
+ try {
28035
+ const content = await fs7.readFile(breakerPathFor(authPath), "utf-8");
28036
+ if (!content)
28037
+ return {};
28038
+ const parsed = JSON.parse(content);
28039
+ return parsed && typeof parsed === "object" ? parsed : {};
28040
+ } catch {
28041
+ return {};
28042
+ }
28043
+ }
28044
+ async function saveRefreshBreaker(authPath, state) {
28045
+ try {
28046
+ const fs7 = getFileSystem();
28047
+ const path3 = breakerPathFor(authPath);
28048
+ await fs7.mkdir(fs7.path.dirname(path3));
28049
+ const tempPath = `${path3}.tmp`;
28050
+ await fs7.writeFile(tempPath, JSON.stringify(state));
28051
+ await fs7.rename(tempPath, path3);
28052
+ } catch {}
28053
+ }
28054
+ async function clearRefreshBreaker(authPath) {
28055
+ const fs7 = getFileSystem();
28056
+ const path3 = breakerPathFor(authPath);
28057
+ try {
28058
+ if (await fs7.exists(path3)) {
28059
+ await fs7.rm(path3);
28060
+ }
28061
+ } catch {}
28062
+ }
28063
+ function nextBackoffMs(attempts) {
28064
+ const shift = Math.max(0, attempts - 1);
28065
+ return Math.min(BACKOFF_BASE_MS * 2 ** shift, BACKOFF_CAP_MS);
28066
+ }
28067
+ function shouldSurface(state, nowMs) {
28068
+ if (state.lastSurfacedAtMs === undefined)
28069
+ return true;
28070
+ return nowMs - state.lastSurfacedAtMs >= SURFACE_WINDOW_MS;
28071
+ }
28072
+
29238
28073
  // ../auth/src/robotClientFallback.ts
29239
28074
  init_src();
29240
28075
  var DEFAULT_TIMEOUT_MS = 1000;
29241
28076
  var CLOSE_TIMEOUT_MS = 500;
29242
- var NOTICE_SENTINEL = Symbol.for("@uipath/auth/robotFallbackNoticePrinted");
29243
- var printNoticeOnce = () => {
29244
- const slot = globalThis;
29245
- if (slot[NOTICE_SENTINEL])
29246
- return;
29247
- slot[NOTICE_SENTINEL] = true;
29248
- catchError2(() => process.stderr.write(`Using UiPath Robot credentials. Run 'uip login' for a dedicated session.
29249
- `));
29250
- };
29251
28077
  var ROBOT_USER_SERVICES_PIPE = "UiPathUserServices";
29252
28078
  var ROBOT_USER_SERVICES_ALTERNATE_PIPE = `${ROBOT_USER_SERVICES_PIPE}Alternate`;
29253
28079
  var PIPE_NAME_MAX_LENGTH = 103;
@@ -29363,7 +28189,6 @@ var tryRobotClientFallback = async (options = {}) => {
29363
28189
  issuerFromToken = issClaim;
29364
28190
  }
29365
28191
  }
29366
- printNoticeOnce();
29367
28192
  return {
29368
28193
  accessToken,
29369
28194
  baseUrl: parsedUrl.baseUrl,
@@ -29588,18 +28413,327 @@ var saveEnvFileAsync = async ({
29588
28413
  };
29589
28414
 
29590
28415
  // ../auth/src/loginStatus.ts
29591
- function normalizeTokenRefreshFailure() {
29592
- return "stored refresh token is invalid or expired";
28416
+ var getLoginStatusAsync = async (options = {}) => {
28417
+ return getLoginStatusWithDeps(options);
28418
+ };
28419
+ var getLoginStatusWithDeps = async (options = {}, deps = {}) => {
28420
+ const {
28421
+ resolveEnvFilePath = resolveEnvFilePathAsync,
28422
+ loadEnvFile = loadEnvFileAsync,
28423
+ saveEnvFile = saveEnvFileAsync,
28424
+ getFs = getFileSystem,
28425
+ refreshToken: refreshTokenFn = refreshAccessToken,
28426
+ resolveConfig = resolveConfigAsync,
28427
+ robotFallback = tryRobotClientFallback,
28428
+ loadBreaker = loadRefreshBreaker,
28429
+ saveBreaker = saveRefreshBreaker,
28430
+ clearBreaker = clearRefreshBreaker
28431
+ } = deps;
28432
+ if (isRobotAuthEnforced()) {
28433
+ return resolveRobotEnforcedStatus(robotFallback);
28434
+ }
28435
+ if (isEnvAuthEnabled()) {
28436
+ return readAuthFromEnv();
28437
+ }
28438
+ const activeProfile = getActiveAuthProfile();
28439
+ const activeProfileFilePath = getActiveAuthProfileFilePath();
28440
+ const usingActiveProfile = activeProfile !== undefined && (options.envFilePath === undefined || options.envFilePath === activeProfileFilePath);
28441
+ const envFilePath = options.envFilePath ?? activeProfileFilePath ?? DEFAULT_ENV_FILENAME;
28442
+ const { ensureTokenValidityMinutes } = options;
28443
+ const { absolutePath } = await resolveEnvFilePath(envFilePath);
28444
+ if (absolutePath === undefined) {
28445
+ if (usingActiveProfile) {
28446
+ return {
28447
+ loginStatus: "Not logged in",
28448
+ hint: `No credentials found for profile "${activeProfile}". Run 'uip login --profile ${activeProfile}' to authenticate this profile.`
28449
+ };
28450
+ }
28451
+ return resolveBorrowedRobotStatus(robotFallback);
28452
+ }
28453
+ const loaded = await loadFileCredentials(loadEnvFile, absolutePath);
28454
+ if ("status" in loaded) {
28455
+ return loaded.status;
28456
+ }
28457
+ const { credentials } = loaded;
28458
+ const globalHint = () => usingActiveProfile ? Promise.resolve(undefined) : getGlobalCredsHint(getFs, loadEnvFile, absolutePath, envFilePath);
28459
+ const expiration = getTokenExpiration(credentials.UIPATH_ACCESS_TOKEN);
28460
+ const outerThreshold = computeExpirationThreshold(ensureTokenValidityMinutes);
28461
+ let tokens = {
28462
+ accessToken: credentials.UIPATH_ACCESS_TOKEN,
28463
+ refreshToken: credentials.UIPATH_REFRESH_TOKEN,
28464
+ expiration,
28465
+ lockReleaseFailed: false
28466
+ };
28467
+ const refreshToken = credentials.UIPATH_REFRESH_TOKEN;
28468
+ if (expiration && expiration <= outerThreshold && refreshToken) {
28469
+ const refreshed = await attemptRefresh({
28470
+ absolutePath,
28471
+ credentials,
28472
+ accessToken: credentials.UIPATH_ACCESS_TOKEN,
28473
+ refreshToken,
28474
+ expiration,
28475
+ ensureTokenValidityMinutes,
28476
+ getFs,
28477
+ loadEnvFile,
28478
+ saveEnvFile,
28479
+ refreshFn: refreshTokenFn,
28480
+ resolveConfig,
28481
+ loadBreaker,
28482
+ saveBreaker,
28483
+ clearBreaker,
28484
+ globalHint
28485
+ });
28486
+ if (refreshed.kind === "terminal") {
28487
+ return refreshed.status;
28488
+ }
28489
+ tokens = refreshed.tokens;
28490
+ }
28491
+ return buildFileStatus(tokens, credentials, globalHint);
28492
+ };
28493
+ async function resolveRobotEnforcedStatus(robotFallback) {
28494
+ if (isEnvAuthEnabled()) {
28495
+ throw new EnvAuthConfigError(`${ENV_AUTH_ENABLE_VAR}=true and ${ENFORCE_ROBOT_AUTH_VAR}=true ` + `are mutually exclusive. Unset one of them and re-run.`);
28496
+ }
28497
+ const robotCreds = await robotFallback({ force: true });
28498
+ if (!robotCreds) {
28499
+ return {
28500
+ loginStatus: "Not logged in",
28501
+ hint: `${ENFORCE_ROBOT_AUTH_VAR}=true but the UiPath Robot ` + `session is unavailable. Start and sign in to the Assistant, ` + `or unset ${ENFORCE_ROBOT_AUTH_VAR} to fall back to file or ` + `env-var authentication.`
28502
+ };
28503
+ }
28504
+ return buildRobotStatus(robotCreds);
29593
28505
  }
29594
- function normalizeTokenRefreshUnavailableFailure() {
29595
- return "token refresh failed before authentication completed";
28506
+ async function resolveBorrowedRobotStatus(robotFallback) {
28507
+ const robotCreds = await robotFallback();
28508
+ return robotCreds ? buildRobotStatus(robotCreds) : { loginStatus: "Not logged in" };
29596
28509
  }
29597
- function errorMessage(error) {
29598
- return error instanceof Error ? error.message : String(error);
28510
+ async function loadFileCredentials(loadEnvFile, absolutePath) {
28511
+ let credentials;
28512
+ try {
28513
+ credentials = await loadEnvFile({ envPath: absolutePath });
28514
+ } catch (error) {
28515
+ if (isFileNotFoundError(error)) {
28516
+ return { status: { loginStatus: "Not logged in" } };
28517
+ }
28518
+ throw error;
28519
+ }
28520
+ if (!credentials.UIPATH_ACCESS_TOKEN) {
28521
+ return { status: { loginStatus: "Not logged in" } };
28522
+ }
28523
+ return { credentials };
28524
+ }
28525
+ async function getGlobalCredsHint(getFs, loadEnvFile, absolutePath, envFilePath) {
28526
+ const fs7 = getFs();
28527
+ const globalPath = fs7.path.join(fs7.env.homedir(), envFilePath);
28528
+ if (absolutePath === globalPath)
28529
+ return;
28530
+ if (!await fs7.exists(globalPath))
28531
+ return;
28532
+ try {
28533
+ const globalCreds = await loadEnvFile({ envPath: globalPath });
28534
+ if (!globalCreds.UIPATH_ACCESS_TOKEN)
28535
+ return;
28536
+ const globalExp = getTokenExpiration(globalCreds.UIPATH_ACCESS_TOKEN);
28537
+ if (globalExp && globalExp <= new Date)
28538
+ return;
28539
+ return `Local credentials file at ${absolutePath} has expired credentials. Valid credentials exist in ${globalPath}. Remove the local file or run 'uip login' to re-authenticate.`;
28540
+ } catch {
28541
+ return;
28542
+ }
29599
28543
  }
29600
28544
  function computeExpirationThreshold(ensureTokenValidityMinutes) {
29601
28545
  return new Date(Date.now() + (ensureTokenValidityMinutes ?? 0) * 60 * 1000);
29602
28546
  }
28547
+ async function attemptRefresh(ctx) {
28548
+ const shortCircuit = await circuitBreakerShortCircuit(ctx);
28549
+ if (shortCircuit) {
28550
+ return { kind: "terminal", status: shortCircuit };
28551
+ }
28552
+ let release;
28553
+ try {
28554
+ release = await ctx.getFs().acquireLock(ctx.absolutePath);
28555
+ } catch (error) {
28556
+ return {
28557
+ kind: "terminal",
28558
+ status: await lockAcquireFailureStatus(ctx, error)
28559
+ };
28560
+ }
28561
+ let lockedFailure;
28562
+ let lockReleaseFailed = false;
28563
+ let success;
28564
+ try {
28565
+ const outcome = await runRefreshLocked({
28566
+ absolutePath: ctx.absolutePath,
28567
+ refreshToken: ctx.refreshToken,
28568
+ customAuthority: ctx.credentials.UIPATH_URL,
28569
+ ensureTokenValidityMinutes: ctx.ensureTokenValidityMinutes,
28570
+ loadEnvFile: ctx.loadEnvFile,
28571
+ saveEnvFile: ctx.saveEnvFile,
28572
+ refreshFn: ctx.refreshFn,
28573
+ resolveConfig: ctx.resolveConfig,
28574
+ loadBreaker: ctx.loadBreaker,
28575
+ saveBreaker: ctx.saveBreaker,
28576
+ clearBreaker: ctx.clearBreaker
28577
+ });
28578
+ if (outcome.kind === "fail") {
28579
+ lockedFailure = outcome.status;
28580
+ } else {
28581
+ success = outcome;
28582
+ }
28583
+ } finally {
28584
+ try {
28585
+ await release();
28586
+ } catch {
28587
+ lockReleaseFailed = true;
28588
+ }
28589
+ }
28590
+ if (lockedFailure) {
28591
+ const globalHint = await ctx.globalHint();
28592
+ const base = globalHint ? { ...lockedFailure, loginStatus: "Expired", hint: globalHint } : lockedFailure;
28593
+ return {
28594
+ kind: "terminal",
28595
+ status: lockReleaseFailed ? { ...base, lockReleaseFailed: true } : base
28596
+ };
28597
+ }
28598
+ return {
28599
+ kind: "refreshed",
28600
+ tokens: {
28601
+ accessToken: success?.accessToken,
28602
+ refreshToken: success?.refreshToken,
28603
+ expiration: success?.expiration,
28604
+ tokenRefresh: success?.tokenRefresh,
28605
+ persistenceWarning: success?.persistenceWarning,
28606
+ lockReleaseFailed
28607
+ }
28608
+ };
28609
+ }
28610
+ async function buildFileStatus(tokens, credentials, globalHint) {
28611
+ const result = {
28612
+ loginStatus: tokens.expiration && tokens.expiration <= new Date ? "Expired" : "Logged in",
28613
+ accessToken: tokens.accessToken,
28614
+ refreshToken: tokens.refreshToken,
28615
+ baseUrl: credentials.UIPATH_URL,
28616
+ organizationName: credentials.UIPATH_ORGANIZATION_NAME,
28617
+ organizationId: credentials.UIPATH_ORGANIZATION_ID,
28618
+ tenantName: credentials.UIPATH_TENANT_NAME,
28619
+ tenantId: credentials.UIPATH_TENANT_ID,
28620
+ expiration: tokens.expiration,
28621
+ source: "file" /* File */,
28622
+ ...tokens.persistenceWarning ? { hint: tokens.persistenceWarning, persistenceFailed: true } : {},
28623
+ ...tokens.lockReleaseFailed ? { lockReleaseFailed: true } : {},
28624
+ ...tokens.tokenRefresh ? { tokenRefresh: tokens.tokenRefresh } : {}
28625
+ };
28626
+ if (result.loginStatus === "Expired") {
28627
+ const hint = await globalHint();
28628
+ if (hint) {
28629
+ result.hint = hint;
28630
+ }
28631
+ }
28632
+ return result;
28633
+ }
28634
+ function buildRobotStatus(robotCreds) {
28635
+ return {
28636
+ loginStatus: "Logged in",
28637
+ accessToken: robotCreds.accessToken,
28638
+ baseUrl: robotCreds.baseUrl,
28639
+ organizationName: robotCreds.organizationName,
28640
+ organizationId: robotCreds.organizationId,
28641
+ tenantName: robotCreds.tenantName,
28642
+ tenantId: robotCreds.tenantId,
28643
+ issuer: robotCreds.issuer,
28644
+ expiration: getTokenExpiration(robotCreds.accessToken),
28645
+ source: "robot" /* Robot */
28646
+ };
28647
+ }
28648
+ var isFileNotFoundError = (error) => {
28649
+ if (!(error instanceof Object))
28650
+ return false;
28651
+ return error.code === "ENOENT";
28652
+ };
28653
+ async function circuitBreakerShortCircuit(ctx) {
28654
+ const {
28655
+ absolutePath,
28656
+ refreshToken,
28657
+ accessToken,
28658
+ credentials,
28659
+ expiration,
28660
+ loadBreaker,
28661
+ saveBreaker,
28662
+ clearBreaker
28663
+ } = ctx;
28664
+ const fingerprint = await refreshTokenFingerprint(refreshToken);
28665
+ const breaker = await loadBreaker(absolutePath).catch(() => ({}));
28666
+ if (breaker.deadTokenFp && breaker.deadTokenFp !== fingerprint) {
28667
+ await clearBreaker(absolutePath);
28668
+ breaker.deadTokenFp = undefined;
28669
+ }
28670
+ const nowMs = Date.now();
28671
+ const tokenIsDead = breaker.deadTokenFp === fingerprint;
28672
+ const inBackoff = breaker.backoffUntilMs !== undefined && nowMs < breaker.backoffUntilMs;
28673
+ if (!tokenIsDead && !inBackoff)
28674
+ return;
28675
+ const globalHint = await ctx.globalHint();
28676
+ const suppressed = !shouldSurface(breaker, nowMs);
28677
+ if (!suppressed) {
28678
+ await saveBreaker(absolutePath, {
28679
+ ...breaker,
28680
+ lastSurfacedAtMs: nowMs
28681
+ });
28682
+ }
28683
+ const deadHint = "Run 'uip login' to re-authenticate — the stored refresh token is invalid or expired. In a non-interactive context, authenticate with: uip login --client-id <id> --client-secret <secret> -t <tenant>.";
28684
+ const backoffHint = "Token refresh is temporarily backed off after a recent network error and will retry automatically once the backoff window elapses.";
28685
+ return {
28686
+ loginStatus: globalHint ? "Expired" : "Refresh Failed",
28687
+ ...globalHint ? {
28688
+ accessToken,
28689
+ refreshToken,
28690
+ baseUrl: credentials.UIPATH_URL,
28691
+ organizationName: credentials.UIPATH_ORGANIZATION_NAME,
28692
+ organizationId: credentials.UIPATH_ORGANIZATION_ID,
28693
+ tenantName: credentials.UIPATH_TENANT_NAME,
28694
+ tenantId: credentials.UIPATH_TENANT_ID,
28695
+ expiration,
28696
+ source: "file" /* File */
28697
+ } : {},
28698
+ hint: globalHint ?? (tokenIsDead ? deadHint : backoffHint),
28699
+ refreshCircuitOpen: true,
28700
+ refreshTelemetrySuppressed: suppressed,
28701
+ tokenRefresh: { attempted: false, success: false }
28702
+ };
28703
+ }
28704
+ async function lockAcquireFailureStatus(ctx, error) {
28705
+ const msg = errorMessage(error);
28706
+ const globalHint = await ctx.globalHint();
28707
+ if (globalHint) {
28708
+ return {
28709
+ loginStatus: "Expired",
28710
+ accessToken: ctx.accessToken,
28711
+ refreshToken: ctx.refreshToken,
28712
+ baseUrl: ctx.credentials.UIPATH_URL,
28713
+ organizationName: ctx.credentials.UIPATH_ORGANIZATION_NAME,
28714
+ organizationId: ctx.credentials.UIPATH_ORGANIZATION_ID,
28715
+ tenantName: ctx.credentials.UIPATH_TENANT_NAME,
28716
+ tenantId: ctx.credentials.UIPATH_TENANT_ID,
28717
+ expiration: ctx.expiration,
28718
+ source: "file" /* File */,
28719
+ hint: globalHint,
28720
+ tokenRefresh: {
28721
+ attempted: false,
28722
+ success: false,
28723
+ errorMessage: `lock acquisition failed: ${msg}`
28724
+ }
28725
+ };
28726
+ }
28727
+ return {
28728
+ loginStatus: "Refresh Failed",
28729
+ hint: "Could not acquire the auth-file lock — too many concurrent `uip` processes, or a permission issue on the auth directory. Retry, or run 'uip login' to re-authenticate.",
28730
+ tokenRefresh: {
28731
+ attempted: false,
28732
+ success: false,
28733
+ errorMessage: `lock acquisition failed: ${msg}`
28734
+ }
28735
+ };
28736
+ }
29603
28737
  async function runRefreshLocked(inputs) {
29604
28738
  const {
29605
28739
  absolutePath,
@@ -29609,7 +28743,10 @@ async function runRefreshLocked(inputs) {
29609
28743
  loadEnvFile,
29610
28744
  saveEnvFile,
29611
28745
  refreshFn,
29612
- resolveConfig
28746
+ resolveConfig,
28747
+ loadBreaker,
28748
+ saveBreaker,
28749
+ clearBreaker
29613
28750
  } = inputs;
29614
28751
  const expirationThreshold = computeExpirationThreshold(ensureTokenValidityMinutes);
29615
28752
  let fresh;
@@ -29632,6 +28769,7 @@ async function runRefreshLocked(inputs) {
29632
28769
  const freshAccess = fresh.UIPATH_ACCESS_TOKEN;
29633
28770
  const freshExp = freshAccess ? getTokenExpiration(freshAccess) : undefined;
29634
28771
  if (freshAccess && freshExp && freshExp > expirationThreshold) {
28772
+ await clearBreaker(absolutePath);
29635
28773
  return {
29636
28774
  kind: "ok",
29637
28775
  accessToken: freshAccess,
@@ -29655,8 +28793,21 @@ async function runRefreshLocked(inputs) {
29655
28793
  refreshedRefresh = refreshed.refreshToken;
29656
28794
  } catch (error) {
29657
28795
  const isOAuthFailure = isTokenRefreshOAuthFailure(error);
29658
- const hint = isOAuthFailure ? "Run 'uip login' to re-authenticate — the stored refresh token is invalid or expired." : "Token refresh failed. Check your network connection, then retry or run 'uip login' to re-authenticate.";
28796
+ const hint = isOAuthFailure ? "Run 'uip login' to re-authenticate — the stored refresh token is invalid or expired. In a non-interactive context, authenticate with: uip login --client-id <id> --client-secret <secret> -t <tenant>." : "Token refresh failed. Check your network connection, then retry or run 'uip login' to re-authenticate.";
29659
28797
  const message = isOAuthFailure ? normalizeTokenRefreshFailure() : normalizeTokenRefreshUnavailableFailure();
28798
+ const fp = await refreshTokenFingerprint(tokenForIdP);
28799
+ if (isOAuthFailure) {
28800
+ await saveBreaker(absolutePath, { deadTokenFp: fp });
28801
+ } else {
28802
+ const prior = await loadBreaker(absolutePath).catch(() => ({}));
28803
+ const attempts = (prior.attempts ?? 0) + 1;
28804
+ await saveBreaker(absolutePath, {
28805
+ ...prior,
28806
+ deadTokenFp: undefined,
28807
+ attempts,
28808
+ backoffUntilMs: Date.now() + nextBackoffMs(attempts)
28809
+ });
28810
+ }
29660
28811
  return {
29661
28812
  kind: "fail",
29662
28813
  status: {
@@ -29685,6 +28836,7 @@ async function runRefreshLocked(inputs) {
29685
28836
  }
29686
28837
  };
29687
28838
  }
28839
+ await clearBreaker(absolutePath);
29688
28840
  try {
29689
28841
  await saveEnvFile({
29690
28842
  envPath: absolutePath,
@@ -29717,212 +28869,15 @@ async function runRefreshLocked(inputs) {
29717
28869
  };
29718
28870
  }
29719
28871
  }
29720
- var getLoginStatusWithDeps = async (options = {}, deps = {}) => {
29721
- const {
29722
- resolveEnvFilePath = resolveEnvFilePathAsync,
29723
- loadEnvFile = loadEnvFileAsync,
29724
- saveEnvFile = saveEnvFileAsync,
29725
- getFs = getFileSystem,
29726
- refreshToken: refreshTokenFn = refreshAccessToken,
29727
- resolveConfig = resolveConfigAsync,
29728
- robotFallback = tryRobotClientFallback
29729
- } = deps;
29730
- if (isRobotAuthEnforced()) {
29731
- if (isEnvAuthEnabled()) {
29732
- throw new EnvAuthConfigError(`${ENV_AUTH_ENABLE_VAR}=true and ${ENFORCE_ROBOT_AUTH_VAR}=true ` + `are mutually exclusive. Unset one of them and re-run.`);
29733
- }
29734
- const robotCreds = await robotFallback({ force: true });
29735
- if (!robotCreds) {
29736
- return {
29737
- loginStatus: "Not logged in",
29738
- hint: `${ENFORCE_ROBOT_AUTH_VAR}=true but the UiPath Robot ` + `session is unavailable. Start and sign in to the Assistant, ` + `or unset ${ENFORCE_ROBOT_AUTH_VAR} to fall back to file or ` + `env-var authentication.`
29739
- };
29740
- }
29741
- const expiration2 = getTokenExpiration(robotCreds.accessToken);
29742
- return {
29743
- loginStatus: "Logged in",
29744
- accessToken: robotCreds.accessToken,
29745
- baseUrl: robotCreds.baseUrl,
29746
- organizationName: robotCreds.organizationName,
29747
- organizationId: robotCreds.organizationId,
29748
- tenantName: robotCreds.tenantName,
29749
- tenantId: robotCreds.tenantId,
29750
- issuer: robotCreds.issuer,
29751
- expiration: expiration2,
29752
- source: "robot" /* Robot */
29753
- };
29754
- }
29755
- if (isEnvAuthEnabled()) {
29756
- return readAuthFromEnv();
29757
- }
29758
- const { envFilePath = DEFAULT_ENV_FILENAME, ensureTokenValidityMinutes } = options;
29759
- const { absolutePath } = await resolveEnvFilePath(envFilePath);
29760
- if (absolutePath === undefined) {
29761
- const robotCreds = await robotFallback();
29762
- if (robotCreds) {
29763
- const expiration2 = getTokenExpiration(robotCreds.accessToken);
29764
- const status = {
29765
- loginStatus: "Logged in",
29766
- accessToken: robotCreds.accessToken,
29767
- baseUrl: robotCreds.baseUrl,
29768
- organizationName: robotCreds.organizationName,
29769
- organizationId: robotCreds.organizationId,
29770
- tenantName: robotCreds.tenantName,
29771
- tenantId: robotCreds.tenantId,
29772
- issuer: robotCreds.issuer,
29773
- expiration: expiration2,
29774
- source: "robot" /* Robot */
29775
- };
29776
- return status;
29777
- }
29778
- return { loginStatus: "Not logged in" };
29779
- }
29780
- let credentials;
29781
- try {
29782
- credentials = await loadEnvFile({ envPath: absolutePath });
29783
- } catch (error) {
29784
- if (isFileNotFoundError(error)) {
29785
- return { loginStatus: "Not logged in" };
29786
- }
29787
- throw error;
29788
- }
29789
- if (!credentials.UIPATH_ACCESS_TOKEN) {
29790
- return { loginStatus: "Not logged in" };
29791
- }
29792
- let accessToken = credentials.UIPATH_ACCESS_TOKEN;
29793
- let refreshToken = credentials.UIPATH_REFRESH_TOKEN;
29794
- let expiration = getTokenExpiration(accessToken);
29795
- let persistenceWarning;
29796
- let lockReleaseFailed = false;
29797
- let tokenRefresh;
29798
- const outerThreshold = computeExpirationThreshold(ensureTokenValidityMinutes);
29799
- const tryGlobalCredsHint = async () => {
29800
- const fs7 = getFs();
29801
- const globalPath = fs7.path.join(fs7.env.homedir(), envFilePath);
29802
- if (absolutePath === globalPath)
29803
- return;
29804
- if (!await fs7.exists(globalPath))
29805
- return;
29806
- try {
29807
- const globalCreds = await loadEnvFile({ envPath: globalPath });
29808
- if (!globalCreds.UIPATH_ACCESS_TOKEN)
29809
- return;
29810
- const globalExp = getTokenExpiration(globalCreds.UIPATH_ACCESS_TOKEN);
29811
- if (globalExp && globalExp <= new Date)
29812
- return;
29813
- return `Local credentials file at ${absolutePath} has expired credentials. Valid credentials exist in ${globalPath}. Remove the local file or run 'uip login' to re-authenticate.`;
29814
- } catch {
29815
- return;
29816
- }
29817
- };
29818
- if (expiration && expiration <= outerThreshold && refreshToken) {
29819
- let release;
29820
- try {
29821
- release = await getFs().acquireLock(absolutePath);
29822
- } catch (error) {
29823
- const msg = errorMessage(error);
29824
- const globalHint = await tryGlobalCredsHint();
29825
- if (globalHint) {
29826
- return {
29827
- loginStatus: "Expired",
29828
- accessToken,
29829
- refreshToken,
29830
- baseUrl: credentials.UIPATH_URL,
29831
- organizationName: credentials.UIPATH_ORGANIZATION_NAME,
29832
- organizationId: credentials.UIPATH_ORGANIZATION_ID,
29833
- tenantName: credentials.UIPATH_TENANT_NAME,
29834
- tenantId: credentials.UIPATH_TENANT_ID,
29835
- expiration,
29836
- source: "file" /* File */,
29837
- hint: globalHint,
29838
- tokenRefresh: {
29839
- attempted: false,
29840
- success: false,
29841
- errorMessage: `lock acquisition failed: ${msg}`
29842
- }
29843
- };
29844
- }
29845
- return {
29846
- loginStatus: "Refresh Failed",
29847
- hint: "Could not acquire the auth-file lock — too many concurrent `uip` processes, or a permission issue on the auth directory. Retry, or run 'uip login' to re-authenticate.",
29848
- tokenRefresh: {
29849
- attempted: false,
29850
- success: false,
29851
- errorMessage: `lock acquisition failed: ${msg}`
29852
- }
29853
- };
29854
- }
29855
- let lockedFailure;
29856
- try {
29857
- const outcome = await runRefreshLocked({
29858
- absolutePath,
29859
- refreshToken,
29860
- customAuthority: credentials.UIPATH_URL,
29861
- ensureTokenValidityMinutes,
29862
- loadEnvFile,
29863
- saveEnvFile,
29864
- refreshFn: refreshTokenFn,
29865
- resolveConfig
29866
- });
29867
- if (outcome.kind === "fail") {
29868
- lockedFailure = outcome.status;
29869
- } else {
29870
- accessToken = outcome.accessToken;
29871
- refreshToken = outcome.refreshToken;
29872
- expiration = outcome.expiration;
29873
- tokenRefresh = outcome.tokenRefresh;
29874
- if (outcome.persistenceWarning) {
29875
- persistenceWarning = outcome.persistenceWarning;
29876
- }
29877
- }
29878
- } finally {
29879
- try {
29880
- await release();
29881
- } catch {
29882
- lockReleaseFailed = true;
29883
- }
29884
- }
29885
- if (lockedFailure) {
29886
- const globalHint = await tryGlobalCredsHint();
29887
- const base = globalHint ? {
29888
- ...lockedFailure,
29889
- loginStatus: "Expired",
29890
- hint: globalHint
29891
- } : lockedFailure;
29892
- return lockReleaseFailed ? { ...base, lockReleaseFailed: true } : base;
29893
- }
29894
- }
29895
- const result = {
29896
- loginStatus: expiration && expiration <= new Date ? "Expired" : "Logged in",
29897
- accessToken,
29898
- refreshToken,
29899
- baseUrl: credentials.UIPATH_URL,
29900
- organizationName: credentials.UIPATH_ORGANIZATION_NAME,
29901
- organizationId: credentials.UIPATH_ORGANIZATION_ID,
29902
- tenantName: credentials.UIPATH_TENANT_NAME,
29903
- tenantId: credentials.UIPATH_TENANT_ID,
29904
- expiration,
29905
- source: "file" /* File */,
29906
- ...persistenceWarning ? { hint: persistenceWarning, persistenceFailed: true } : {},
29907
- ...lockReleaseFailed ? { lockReleaseFailed: true } : {},
29908
- ...tokenRefresh ? { tokenRefresh } : {}
29909
- };
29910
- if (result.loginStatus === "Expired") {
29911
- const globalHint = await tryGlobalCredsHint();
29912
- if (globalHint) {
29913
- result.hint = globalHint;
29914
- }
29915
- }
29916
- return result;
29917
- };
29918
- var isFileNotFoundError = (error) => {
29919
- if (!(error instanceof Object))
29920
- return false;
29921
- return error.code === "ENOENT";
29922
- };
29923
- var getLoginStatusAsync = async (options = {}) => {
29924
- return getLoginStatusWithDeps(options);
29925
- };
28872
+ function normalizeTokenRefreshFailure() {
28873
+ return "stored refresh token is invalid or expired";
28874
+ }
28875
+ function normalizeTokenRefreshUnavailableFailure() {
28876
+ return "token refresh failed before authentication completed";
28877
+ }
28878
+ function errorMessage(error) {
28879
+ return error instanceof Error ? error.message : String(error);
28880
+ }
29926
28881
 
29927
28882
  // ../auth/src/authContext.ts
29928
28883
  var getAuthContext = async (options = {}) => {
@@ -29957,6 +28912,14 @@ var getAuthContext = async (options = {}) => {
29957
28912
  };
29958
28913
  // ../auth/src/interactive.ts
29959
28914
  init_src();
28915
+
28916
+ // ../auth/src/selectTenant.ts
28917
+ var TENANT_SELECTION_REQUIRED_CODE = "TENANT_SELECTION_REQUIRED";
28918
+ var INVALID_TENANT_CODE = "INVALID_TENANT";
28919
+ var TENANT_SELECTION_CODES = new Set([
28920
+ TENANT_SELECTION_REQUIRED_CODE,
28921
+ INVALID_TENANT_CODE
28922
+ ]);
29960
28923
  // ../auth/src/logout.ts
29961
28924
  init_src();
29962
28925
 
@@ -30940,7 +29903,7 @@ class TextApiResponse {
30940
29903
  var package_default2 = {
30941
29904
  name: "@uipath/orchestrator-sdk",
30942
29905
  license: "MIT",
30943
- version: "1.196.0",
29906
+ version: "1.197.0",
30944
29907
  repository: {
30945
29908
  type: "git",
30946
29909
  url: "https://github.com/UiPath/cli.git",
@@ -30974,7 +29937,7 @@ var package_default2 = {
30974
29937
  ],
30975
29938
  private: true,
30976
29939
  scripts: {
30977
- build: "bun build ./src/index.ts --outdir dist --format esm --target node && bun build ./src/index.browser.ts --outdir dist --format esm --target browser --external @uipath/auth --external @uipath/common && tsc -p tsconfig.build.json --noCheck",
29940
+ build: "bun build ./src/index.ts --outdir dist --format esm --target node --sourcemap=linked && bun build ./src/index.browser.ts --outdir dist --format esm --target browser --external @uipath/auth --external @uipath/common --sourcemap=linked && tsc -p tsconfig.build.json --noCheck",
30978
29941
  generate: "bun run src/scripts/generate-sdk.ts",
30979
29942
  lint: "biome check .",
30980
29943
  test: "vitest run",
@@ -34912,3 +33875,5 @@ export {
34912
33875
  registerCommands,
34913
33876
  metadata
34914
33877
  };
33878
+
33879
+ //# debugId=B0C05EB33F8752E564756E2164756E21