@uipath/solution-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.
package/dist/resource.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
  });
@@ -21963,10 +21963,10 @@ var require_Reflect = __commonJS(() => {
21963
21963
  return this;
21964
21964
  };
21965
21965
  MapIterator2.prototype.next = function() {
21966
- var index2 = this._index;
21967
- if (index2 >= 0 && index2 < this._keys.length) {
21968
- var result = this._selector(this._keys[index2], this._values[index2]);
21969
- if (index2 + 1 >= this._keys.length) {
21966
+ var index = this._index;
21967
+ if (index >= 0 && index < this._keys.length) {
21968
+ var result = this._selector(this._keys[index], this._values[index]);
21969
+ if (index + 1 >= this._keys.length) {
21970
21970
  this._index = -1;
21971
21971
  this._keys = arraySentinel;
21972
21972
  this._values = arraySentinel;
@@ -22013,19 +22013,19 @@ var require_Reflect = __commonJS(() => {
22013
22013
  return this._find(key, false) >= 0;
22014
22014
  };
22015
22015
  Map3.prototype.get = function(key) {
22016
- var index2 = this._find(key, false);
22017
- return index2 >= 0 ? this._values[index2] : undefined;
22016
+ var index = this._find(key, false);
22017
+ return index >= 0 ? this._values[index] : undefined;
22018
22018
  };
22019
22019
  Map3.prototype.set = function(key, value) {
22020
- var index2 = this._find(key, true);
22021
- this._values[index2] = value;
22020
+ var index = this._find(key, true);
22021
+ this._values[index] = value;
22022
22022
  return this;
22023
22023
  };
22024
22024
  Map3.prototype.delete = function(key) {
22025
- var index2 = this._find(key, false);
22026
- if (index2 >= 0) {
22025
+ var index = this._find(key, false);
22026
+ if (index >= 0) {
22027
22027
  var size = this._keys.length;
22028
- for (var i = index2 + 1;i < size; i++) {
22028
+ for (var i = index + 1;i < size; i++) {
22029
22029
  this._keys[i - 1] = this._keys[i];
22030
22030
  this._values[i - 1] = this._values[i];
22031
22031
  }
@@ -23301,7 +23301,7 @@ var require_auto_injectable = __commonJS((exports) => {
23301
23301
  const paramInfo = reflection_helpers_1.getParamInfo(target);
23302
23302
  return class extends target {
23303
23303
  constructor(...args) {
23304
- super(...args.concat(paramInfo.slice(args.length).map((type, index2) => {
23304
+ super(...args.concat(paramInfo.slice(args.length).map((type, index) => {
23305
23305
  try {
23306
23306
  if (injection_token_1.isTokenDescriptor(type)) {
23307
23307
  if (injection_token_1.isTransformDescriptor(type)) {
@@ -23314,7 +23314,7 @@ var require_auto_injectable = __commonJS((exports) => {
23314
23314
  }
23315
23315
  return dependency_container_1.instance.resolve(type);
23316
23316
  } catch (e) {
23317
- const argIndex = index2 + args.length;
23317
+ const argIndex = index + args.length;
23318
23318
  throw new Error(error_helpers_1.formatErrorCtor(target, argIndex, e));
23319
23319
  }
23320
23320
  })));
@@ -23636,27 +23636,54 @@ var NETWORK_ERROR_CODES = new Set([
23636
23636
  "ENETUNREACH",
23637
23637
  "EAI_FAIL"
23638
23638
  ]);
23639
- function isHtmlDocument(body) {
23640
- return /^\s*(<!doctype html|<html\b)/i.test(body);
23641
- }
23642
- function extractNetworkErrorCode(error) {
23643
- if (error === null || typeof error !== "object") {
23644
- return;
23645
- }
23646
- const err = error;
23647
- const code = typeof err.code === "string" ? err.code : undefined;
23648
- if (code && NETWORK_ERROR_CODES.has(code)) {
23649
- return code;
23650
- }
23651
- const cause = err.cause;
23652
- if (cause !== null && typeof cause === "object") {
23653
- const causeCode = cause.code;
23654
- if (typeof causeCode === "string" && NETWORK_ERROR_CODES.has(causeCode)) {
23655
- return causeCode;
23639
+ var TLS_ERROR_CODES = new Set([
23640
+ "SELF_SIGNED_CERT_IN_CHAIN",
23641
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
23642
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
23643
+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
23644
+ "UNABLE_TO_GET_ISSUER_CERT",
23645
+ "CERT_HAS_EXPIRED",
23646
+ "CERT_UNTRUSTED",
23647
+ "ERR_TLS_CERT_ALTNAME_INVALID"
23648
+ ]);
23649
+ 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.";
23650
+ 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.";
23651
+ function describeConnectivityError(error) {
23652
+ let current = error;
23653
+ for (let depth = 0;depth < 5 && current !== null && typeof current === "object"; depth++) {
23654
+ const cur = current;
23655
+ const code = typeof cur.code === "string" ? cur.code : undefined;
23656
+ const message = typeof cur.message === "string" ? cur.message : undefined;
23657
+ if (code && TLS_ERROR_CODES.has(code)) {
23658
+ return {
23659
+ code,
23660
+ kind: "tls",
23661
+ message: message ?? code,
23662
+ instructions: TLS_INSTRUCTIONS
23663
+ };
23664
+ }
23665
+ if (code && NETWORK_ERROR_CODES.has(code)) {
23666
+ return {
23667
+ code,
23668
+ kind: "network",
23669
+ message: message ?? code,
23670
+ instructions: NETWORK_INSTRUCTIONS
23671
+ };
23656
23672
  }
23673
+ current = cur.cause;
23657
23674
  }
23658
23675
  return;
23659
23676
  }
23677
+ function parseHttpStatusFromMessage(message) {
23678
+ const match = /^HTTP\s+(\d{3})(?::|\s|-|$)/i.exec(message.trim());
23679
+ if (!match)
23680
+ return;
23681
+ const status = Number(match[1]);
23682
+ return Number.isInteger(status) && status >= 100 && status <= 599 ? status : undefined;
23683
+ }
23684
+ function isHtmlDocument(body) {
23685
+ return /^\s*(<!doctype html|<html\b)/i.test(body);
23686
+ }
23660
23687
  function retryHintForRetryAfter(seconds) {
23661
23688
  if (seconds <= 1) {
23662
23689
  return "RetryAfter1Second";
@@ -23697,15 +23724,28 @@ function classifyError(status, error) {
23697
23724
  if (status !== undefined && status >= 500 && status < 600) {
23698
23725
  return { errorCode: "server_error", retry: "RetryLater" };
23699
23726
  }
23700
- if (extractNetworkErrorCode(error)) {
23701
- return { errorCode: "network_error", retry: "RetryLater" };
23727
+ const connectivity = describeConnectivityError(error);
23728
+ if (connectivity) {
23729
+ return {
23730
+ errorCode: "network_error",
23731
+ retry: connectivity.kind === "tls" ? "RetryWillNotFix" : "RetryLater"
23732
+ };
23702
23733
  }
23703
23734
  return { errorCode: "unknown_error", retry: "RetryWillNotFix" };
23704
23735
  }
23736
+ function formatHttpStatusMessage(status, rawMessage, extractedMessage, inferredStatus) {
23737
+ if (extractedMessage) {
23738
+ return `HTTP ${status}: ${extractedMessage}`;
23739
+ }
23740
+ return inferredStatus !== undefined ? rawMessage : `HTTP ${status}: ${rawMessage}`;
23741
+ }
23705
23742
  async function extractErrorDetails(error, options) {
23706
23743
  const err = error !== null && error !== undefined && typeof error === "object" ? error : {};
23707
23744
  const response = err.response;
23708
- const status = err.status ?? response?.status;
23745
+ const rawMessage = typeof err.message === "string" ? err.message : "Unknown error";
23746
+ const explicitStatus = err.status ?? response?.status;
23747
+ const inferredStatus = explicitStatus === undefined ? parseHttpStatusFromMessage(rawMessage) : undefined;
23748
+ const status = explicitStatus ?? inferredStatus;
23709
23749
  const isSuccessfulResponse = status !== undefined && status >= 200 && status < 300;
23710
23750
  let rawBody;
23711
23751
  let extractedMessage;
@@ -23740,7 +23780,6 @@ async function extractErrorDetails(error, options) {
23740
23780
  }
23741
23781
  }
23742
23782
  }
23743
- const rawMessage = typeof err.message === "string" ? err.message : "Unknown error";
23744
23783
  let message;
23745
23784
  let result = "Failure";
23746
23785
  const classification = classifyError(status, error);
@@ -23754,10 +23793,10 @@ async function extractErrorDetails(error, options) {
23754
23793
  } else if (status === 405) {
23755
23794
  message = DEFAULT_405;
23756
23795
  } else if (status === 400 || status === 422) {
23757
- message = extractedMessage ? `HTTP ${status}: ${extractedMessage}` : `HTTP ${status}: ${rawMessage}`;
23796
+ message = formatHttpStatusMessage(status, rawMessage, extractedMessage, inferredStatus);
23758
23797
  result = "ValidationError";
23759
23798
  } else if (status === 429) {
23760
- message = extractedMessage ? `HTTP ${status}: ${extractedMessage}` : `HTTP ${status}: ${rawMessage}`;
23799
+ message = formatHttpStatusMessage(status, rawMessage, extractedMessage, inferredStatus);
23761
23800
  } else if (extractedMessage) {
23762
23801
  if (isSuccessfulResponse && rawMessage !== "Unknown error") {
23763
23802
  message = rawMessage;
@@ -23765,7 +23804,9 @@ async function extractErrorDetails(error, options) {
23765
23804
  message = status ? `HTTP ${status}: ${extractedMessage}` : extractedMessage;
23766
23805
  }
23767
23806
  } else if (status) {
23768
- if (rawMessage === "Unknown error" && response) {
23807
+ if (inferredStatus !== undefined) {
23808
+ message = rawMessage;
23809
+ } else if (rawMessage === "Unknown error" && response) {
23769
23810
  const statusText = response.statusText;
23770
23811
  message = statusText ? `HTTP ${status} ${statusText}` : `HTTP ${status} - request failed`;
23771
23812
  } else {
@@ -23774,6 +23815,12 @@ async function extractErrorDetails(error, options) {
23774
23815
  } else {
23775
23816
  message = rawMessage;
23776
23817
  }
23818
+ if (status === undefined) {
23819
+ const connectivity = describeConnectivityError(error);
23820
+ if (connectivity && connectivity.message !== message && !message.includes(connectivity.message)) {
23821
+ message = `${message}: ${connectivity.message}`;
23822
+ }
23823
+ }
23777
23824
  let details = rawMessage;
23778
23825
  if (rawBody) {
23779
23826
  if (parsedBody) {
@@ -23941,6 +23988,7 @@ var CONSOLE_FALLBACK = {
23941
23988
  writeLog: (str) => process.stdout.write(str),
23942
23989
  capabilities: {
23943
23990
  isInteractive: false,
23991
+ canReadInput: false,
23944
23992
  supportsColor: false,
23945
23993
  outputWidth: 80
23946
23994
  }
@@ -29141,6 +29189,29 @@ function isPlainRecord(value) {
29141
29189
  const prototype = Object.getPrototypeOf(value);
29142
29190
  return prototype === Object.prototype || prototype === null;
29143
29191
  }
29192
+ function extractPagedRows(value) {
29193
+ if (Array.isArray(value) || !isPlainRecord(value))
29194
+ return null;
29195
+ const entries = Object.values(value);
29196
+ if (entries.length === 0)
29197
+ return null;
29198
+ let rows = null;
29199
+ let hasScalarSibling = false;
29200
+ for (const entry of entries) {
29201
+ if (Array.isArray(entry)) {
29202
+ if (rows !== null)
29203
+ return null;
29204
+ rows = entry;
29205
+ } else if (entry !== null && typeof entry === "object") {
29206
+ return null;
29207
+ } else {
29208
+ hasScalarSibling = true;
29209
+ }
29210
+ }
29211
+ if (rows === null || !hasScalarSibling)
29212
+ return null;
29213
+ return rows;
29214
+ }
29144
29215
  function toLowerCamelCaseKey(key) {
29145
29216
  if (!key)
29146
29217
  return key;
@@ -29205,7 +29276,8 @@ function printOutput(data, format = "json", logFn, asciiSafe = false) {
29205
29276
  break;
29206
29277
  case "plain": {
29207
29278
  if ("Data" in data && data.Data != null) {
29208
- const items = Array.isArray(data.Data) ? data.Data : [data.Data];
29279
+ const pagedRows = extractPagedRows(data.Data);
29280
+ const items = pagedRows ?? (Array.isArray(data.Data) ? data.Data : [data.Data]);
29209
29281
  items.forEach((item) => {
29210
29282
  const values = Object.values(item).map((v) => v ?? "").join("\t");
29211
29283
  logFn(values);
@@ -29217,10 +29289,13 @@ function printOutput(data, format = "json", logFn, asciiSafe = false) {
29217
29289
  break;
29218
29290
  }
29219
29291
  default: {
29220
- if ("Data" in data && data.Data != null && !(Array.isArray(data.Data) && data.Data.length === 0)) {
29292
+ const hasData = "Data" in data && data.Data != null;
29293
+ const pagedRows = hasData ? extractPagedRows(data.Data) : null;
29294
+ const rows = pagedRows ? pagedRows : Array.isArray(data.Data) ? data.Data : null;
29295
+ if (hasData && !(rows !== null && rows.length === 0)) {
29221
29296
  const logValue = data.Log;
29222
- if (Array.isArray(data.Data)) {
29223
- printResizableTable(data.Data, logFn, logValue);
29297
+ if (rows !== null) {
29298
+ printResizableTable(rows, logFn, logValue);
29224
29299
  } else {
29225
29300
  printVerticalTable(data.Data, logFn, logValue);
29226
29301
  }
@@ -29408,6 +29483,44 @@ function defaultErrorCodeForResult(result) {
29408
29483
  return "unknown_error";
29409
29484
  }
29410
29485
  }
29486
+ function parseHttpStatusFromMessage2(message) {
29487
+ const match = /^HTTP\s+(\d{3})(?::|\s|-|$)/i.exec(message.trim());
29488
+ if (!match)
29489
+ return;
29490
+ const status = Number(match[1]);
29491
+ return Number.isInteger(status) && status >= 100 && status <= 599 ? status : undefined;
29492
+ }
29493
+ function defaultErrorCodeForHttpStatus(status) {
29494
+ if (status === undefined)
29495
+ return;
29496
+ if (status === 400 || status === 409 || status === 422) {
29497
+ return "invalid_argument";
29498
+ }
29499
+ if (status === 401)
29500
+ return "authentication_required";
29501
+ if (status === 403)
29502
+ return "permission_denied";
29503
+ if (status === 404)
29504
+ return "not_found";
29505
+ if (status === 405)
29506
+ return "method_not_allowed";
29507
+ if (status === 408)
29508
+ return "timeout";
29509
+ if (status === 429)
29510
+ return "rate_limited";
29511
+ if (status >= 500 && status < 600)
29512
+ return "server_error";
29513
+ return;
29514
+ }
29515
+ function defaultErrorCodeForFailure(data) {
29516
+ if (data.Result === RESULTS.Failure) {
29517
+ const status = data.Context?.httpStatus ?? parseHttpStatusFromMessage2(data.Message);
29518
+ const errorCode = defaultErrorCodeForHttpStatus(status);
29519
+ if (errorCode)
29520
+ return errorCode;
29521
+ }
29522
+ return defaultErrorCodeForResult(data.Result);
29523
+ }
29411
29524
  function defaultRetryForErrorCode(errorCode) {
29412
29525
  switch (errorCode) {
29413
29526
  case "network_error":
@@ -29437,16 +29550,19 @@ var OutputFormatter;
29437
29550
  OutputFormatter.success = success;
29438
29551
  function error(data) {
29439
29552
  data.Log ??= getLogFilePath() || undefined;
29440
- data.ErrorCode ??= defaultErrorCodeForResult(data.Result);
29553
+ data.ErrorCode ??= defaultErrorCodeForFailure(data);
29441
29554
  data.Retry ??= defaultRetryForErrorCode(data.ErrorCode);
29442
29555
  process.exitCode = EXIT_CODES[data.Result] ?? 1;
29443
- telemetry.trackEvent(CommonTelemetryEvents.Error, {
29444
- result: data.Result,
29445
- errorCode: data.ErrorCode,
29446
- retry: data.Retry,
29447
- message: data.Message
29448
- });
29449
- logOutput(normalizeOutputKeys(data), getOutputFormat());
29556
+ const { SuppressTelemetry, ...envelope } = data;
29557
+ if (!SuppressTelemetry) {
29558
+ telemetry.trackEvent(CommonTelemetryEvents.Error, {
29559
+ result: data.Result,
29560
+ errorCode: data.ErrorCode,
29561
+ retry: data.Retry,
29562
+ message: data.Message
29563
+ });
29564
+ }
29565
+ logOutput(normalizeOutputKeys(envelope), getOutputFormat());
29450
29566
  }
29451
29567
  OutputFormatter.error = error;
29452
29568
  function emitList(code, items, opts) {
@@ -29733,1646 +29849,305 @@ function isGuid(value) {
29733
29849
  }
29734
29850
  // ../common/src/interactivity-context.ts
29735
29851
  var modeSlot = singleton("InteractivityMode");
29736
- // ../../node_modules/jsonpath-plus/dist/index-node-esm.js
29737
- import vm from "vm";
29852
+ // ../common/src/polling/types.ts
29853
+ var PollOutcome = {
29854
+ Completed: "completed",
29855
+ Timeout: "timeout",
29856
+ Interrupted: "interrupted",
29857
+ Aborted: "aborted",
29858
+ Failed: "failed"
29859
+ };
29738
29860
 
29739
- class Hooks {
29740
- add(name, callback, first) {
29741
- if (typeof arguments[0] != "string") {
29742
- for (let name2 in arguments[0]) {
29743
- this.add(name2, arguments[0][name2], arguments[1]);
29744
- }
29745
- } else {
29746
- (Array.isArray(name) ? name : [name]).forEach(function(name2) {
29747
- this[name2] = this[name2] || [];
29748
- if (callback) {
29749
- this[name2][first ? "unshift" : "push"](callback);
29750
- }
29751
- }, this);
29752
- }
29861
+ // ../common/src/polling/poll-failure-mapping.ts
29862
+ var REASON_BY_OUTCOME = {
29863
+ [PollOutcome.Timeout]: "poll_timeout",
29864
+ [PollOutcome.Failed]: "poll_failed",
29865
+ [PollOutcome.Interrupted]: "poll_failed",
29866
+ [PollOutcome.Aborted]: "poll_aborted"
29867
+ };
29868
+ // ../common/src/polling/terminal-statuses.ts
29869
+ var TERMINAL_STATUSES = new Set([
29870
+ "completed",
29871
+ "successful",
29872
+ "faulted",
29873
+ "failed",
29874
+ "cancelled",
29875
+ "canceled",
29876
+ "stopped",
29877
+ "finished"
29878
+ ]);
29879
+ var FAILURE_STATUSES = new Set([
29880
+ "faulted",
29881
+ "failed",
29882
+ "cancelled",
29883
+ "canceled",
29884
+ "stopped"
29885
+ ]);
29886
+ // ../common/src/preview.ts
29887
+ var previewSlot = singleton("PreviewBuild");
29888
+ function isPreviewBuild() {
29889
+ return previewSlot.get(false) ?? false;
29890
+ }
29891
+ Command.prototype.previewCommand = function(nameAndArgs, opts) {
29892
+ if (isPreviewBuild()) {
29893
+ return this.command(nameAndArgs, opts);
29753
29894
  }
29754
- run(name, env) {
29755
- this[name] = this[name] || [];
29756
- this[name].forEach(function(callback) {
29757
- callback.call(env && env.context ? env.context : env, env);
29758
- });
29895
+ return new Command(nameAndArgs.split(/\s+/)[0] ?? nameAndArgs);
29896
+ };
29897
+ // ../common/src/screen-logger.ts
29898
+ var ScreenLogger;
29899
+ ((ScreenLogger) => {
29900
+ function progress(message) {
29901
+ getOutputSink().writeErr(`${message}
29902
+ `);
29759
29903
  }
29904
+ ScreenLogger.progress = progress;
29905
+ })(ScreenLogger ||= {});
29906
+ // ../common/src/sdk-user-agent.ts
29907
+ var USER_AGENT_HEADER = "User-Agent";
29908
+ var sdkUserAgentHostToken = singleton("SdkUserAgentHostToken");
29909
+ function userAgentPatchKey(userAgent) {
29910
+ return Symbol.for(`@uipath/common/sdk-user-agent/${userAgent}`);
29760
29911
  }
29761
-
29762
- class Plugins {
29763
- constructor(jsep) {
29764
- this.jsep = jsep;
29765
- this.registered = {};
29912
+ function splitUserAgentTokens(value) {
29913
+ return value?.trim().split(/\s+/).filter(Boolean) ?? [];
29914
+ }
29915
+ function appendUserAgentToken(value, userAgent) {
29916
+ const tokens = splitUserAgentTokens(value);
29917
+ const seen = new Set(tokens);
29918
+ for (const token of splitUserAgentTokens(userAgent)) {
29919
+ if (!seen.has(token)) {
29920
+ tokens.push(token);
29921
+ seen.add(token);
29922
+ }
29766
29923
  }
29767
- register(...plugins) {
29768
- plugins.forEach((plugin) => {
29769
- if (typeof plugin !== "object" || !plugin.name || !plugin.init) {
29770
- throw new Error("Invalid JSEP plugin format");
29771
- }
29772
- if (this.registered[plugin.name]) {
29773
- return;
29774
- }
29775
- plugin.init(this.jsep);
29776
- this.registered[plugin.name] = plugin;
29777
- });
29924
+ return tokens.join(" ");
29925
+ }
29926
+ function getEffectiveUserAgent(userAgent) {
29927
+ return appendUserAgentToken(sdkUserAgentHostToken.get(), userAgent);
29928
+ }
29929
+ function getHeaderName(headers, headerName) {
29930
+ return Object.keys(headers).find((key) => key.toLowerCase() === headerName.toLowerCase());
29931
+ }
29932
+ function getSdkUserAgentToken(pkg) {
29933
+ const packageName = pkg.name.replace(/^@uipath\//, "");
29934
+ return getEffectiveUserAgent(`${packageName}/${pkg.version}`);
29935
+ }
29936
+ function addSdkUserAgentHeader(headers, userAgent) {
29937
+ const result = { ...headers ?? {} };
29938
+ const headerName = getHeaderName(result, USER_AGENT_HEADER);
29939
+ result[headerName ?? USER_AGENT_HEADER] = appendUserAgentToken(headerName ? result[headerName] : undefined, getEffectiveUserAgent(userAgent));
29940
+ return result;
29941
+ }
29942
+ function asHeaderRecord(headers) {
29943
+ return typeof headers === "object" && headers !== null ? { ...headers } : {};
29944
+ }
29945
+ function withForwardedHeadersInitOverride(initOverrides, forward) {
29946
+ return async (requestContext) => {
29947
+ const initWithHeaders = {
29948
+ ...requestContext.init,
29949
+ headers: forward(asHeaderRecord(requestContext.init.headers))
29950
+ };
29951
+ const override = typeof initOverrides === "function" ? await initOverrides({
29952
+ ...requestContext,
29953
+ init: initWithHeaders
29954
+ }) : initOverrides;
29955
+ return {
29956
+ ...override ?? {},
29957
+ headers: forward(asHeaderRecord(override?.headers ?? initWithHeaders.headers))
29958
+ };
29959
+ };
29960
+ }
29961
+ function installRequestHeaderForwarding(BaseApiClass, patchKey, forward) {
29962
+ const prototype = BaseApiClass.prototype;
29963
+ if (prototype[patchKey]) {
29964
+ return;
29965
+ }
29966
+ if (typeof prototype.request !== "function") {
29967
+ throw new Error("Generated BaseAPI request function not found.");
29778
29968
  }
29969
+ const originalRequest = prototype.request;
29970
+ prototype.request = function requestWithForwardedHeaders(context, initOverrides) {
29971
+ return originalRequest.call(this, context, withForwardedHeadersInitOverride(initOverrides, forward));
29972
+ };
29973
+ Object.defineProperty(prototype, patchKey, {
29974
+ value: true
29975
+ });
29976
+ }
29977
+ function installSdkUserAgentHeader(BaseApiClass, userAgent) {
29978
+ installRequestHeaderForwarding(BaseApiClass, userAgentPatchKey(userAgent), (headers) => addSdkUserAgentHeader(headers, userAgent));
29779
29979
  }
29980
+ // ../common/src/tool-provider.ts
29981
+ var factorySlot = singleton("PackagerFactoryProvider");
29982
+ // src/services/resource-refresh-service.ts
29983
+ init_src();
29780
29984
 
29781
- class Jsep {
29782
- static get version() {
29783
- return "1.4.0";
29784
- }
29785
- static toString() {
29786
- return "JavaScript Expression Parser (JSEP) v" + Jsep.version;
29985
+ // ../auth/src/config.ts
29986
+ init_constants();
29987
+ var DEFAULT_CLIENT_ID = "36dea5b8-e8bb-423d-8e7b-c808df8f1c00";
29988
+ var AUTH_FILE_CONFIG_KEY = Symbol.for("@uipath/auth/AuthFileConfig");
29989
+ var globalSlot = globalThis;
29990
+ var getAuthFileConfig = () => globalSlot[AUTH_FILE_CONFIG_KEY] ?? {};
29991
+
29992
+ class InvalidBaseUrlError extends Error {
29993
+ url;
29994
+ reason;
29995
+ constructor(url, reason) {
29996
+ super(`Invalid base URL: "${url}"
29997
+ ` + `Reason: ${reason}
29998
+
29999
+ ` + `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>).
30000
+ ` + `You can specify the URL via:
30001
+ ` + ` • --authority flag
30002
+ ` + ` • UIPATH_URL environment variable
30003
+ ` + ` • auth.authority in config file`);
30004
+ this.url = url;
30005
+ this.reason = reason;
30006
+ this.name = "InvalidBaseUrlError";
29787
30007
  }
29788
- static addUnaryOp(op_name) {
29789
- Jsep.max_unop_len = Math.max(op_name.length, Jsep.max_unop_len);
29790
- Jsep.unary_ops[op_name] = 1;
29791
- return Jsep;
30008
+ }
30009
+ var DEFAULT_SCOPES = ["openid", "profile", "offline_access"];
30010
+ var normalizeAndValidateBaseUrl = (rawUrl) => {
30011
+ let baseUrl = rawUrl;
30012
+ if (baseUrl.endsWith("/identity_/")) {
30013
+ baseUrl = baseUrl.slice(0, -11);
30014
+ } else if (baseUrl.endsWith("/identity_")) {
30015
+ baseUrl = baseUrl.slice(0, -10);
29792
30016
  }
29793
- static addBinaryOp(op_name, precedence, isRightAssociative) {
29794
- Jsep.max_binop_len = Math.max(op_name.length, Jsep.max_binop_len);
29795
- Jsep.binary_ops[op_name] = precedence;
29796
- if (isRightAssociative) {
29797
- Jsep.right_associative.add(op_name);
29798
- } else {
29799
- Jsep.right_associative.delete(op_name);
29800
- }
29801
- return Jsep;
30017
+ while (baseUrl.endsWith("/")) {
30018
+ baseUrl = baseUrl.slice(0, -1);
29802
30019
  }
29803
- static addIdentifierChar(char) {
29804
- Jsep.additional_identifier_chars.add(char);
29805
- return Jsep;
30020
+ const resolvedBaseUrl = baseUrl;
30021
+ const [urlError, url] = catchError2(() => new URL(resolvedBaseUrl));
30022
+ if (urlError) {
30023
+ throw new InvalidBaseUrlError(baseUrl, `Malformed URL. ${urlError instanceof Error ? urlError.message : "Unknown error"}`);
29806
30024
  }
29807
- static addLiteral(literal_name, literal_value) {
29808
- Jsep.literals[literal_name] = literal_value;
29809
- return Jsep;
30025
+ if (url.protocol !== "https:") {
30026
+ throw new InvalidBaseUrlError(baseUrl, `Authority must use https:// scheme, got ${url.protocol}//. OIDC token exchange requires TLS end-to-end.`);
29810
30027
  }
29811
- static removeUnaryOp(op_name) {
29812
- delete Jsep.unary_ops[op_name];
29813
- if (op_name.length === Jsep.max_unop_len) {
29814
- Jsep.max_unop_len = Jsep.getMaxKeyLen(Jsep.unary_ops);
29815
- }
29816
- return Jsep;
30028
+ return url.pathname.length > 1 ? url.origin : baseUrl;
30029
+ };
30030
+ var resolveScopes = (isExternalAppAuth, customScopes, fileScopes) => {
30031
+ const requestedScopes = customScopes?.length ? customScopes : fileScopes ?? [];
30032
+ if (isExternalAppAuth)
30033
+ return requestedScopes;
30034
+ return [...new Set([...DEFAULT_SCOPES, ...requestedScopes])];
30035
+ };
30036
+ var resolveConfigAsync = async ({
30037
+ customAuthority,
30038
+ customClientId,
30039
+ customClientSecret,
30040
+ customScopes
30041
+ } = {}) => {
30042
+ const fileAuth = getAuthFileConfig();
30043
+ let baseUrl = customAuthority;
30044
+ if (!baseUrl) {
30045
+ baseUrl = process.env.UIPATH_URL;
29817
30046
  }
29818
- static removeAllUnaryOps() {
29819
- Jsep.unary_ops = {};
29820
- Jsep.max_unop_len = 0;
29821
- return Jsep;
30047
+ if (!baseUrl && fileAuth.authority) {
30048
+ baseUrl = fileAuth.authority;
29822
30049
  }
29823
- static removeIdentifierChar(char) {
29824
- Jsep.additional_identifier_chars.delete(char);
29825
- return Jsep;
30050
+ if (!baseUrl) {
30051
+ baseUrl = DEFAULT_BASE_URL;
29826
30052
  }
29827
- static removeBinaryOp(op_name) {
29828
- delete Jsep.binary_ops[op_name];
29829
- if (op_name.length === Jsep.max_binop_len) {
29830
- Jsep.max_binop_len = Jsep.getMaxKeyLen(Jsep.binary_ops);
29831
- }
29832
- Jsep.right_associative.delete(op_name);
29833
- return Jsep;
30053
+ baseUrl = normalizeAndValidateBaseUrl(baseUrl);
30054
+ let clientId = customClientId;
30055
+ if (!clientId && fileAuth.clientId) {
30056
+ clientId = fileAuth.clientId;
29834
30057
  }
29835
- static removeAllBinaryOps() {
29836
- Jsep.binary_ops = {};
29837
- Jsep.max_binop_len = 0;
29838
- return Jsep;
30058
+ if (!clientId) {
30059
+ clientId = DEFAULT_CLIENT_ID;
29839
30060
  }
29840
- static removeLiteral(literal_name) {
29841
- delete Jsep.literals[literal_name];
29842
- return Jsep;
30061
+ let clientSecret = customClientSecret;
30062
+ if (!clientSecret && fileAuth.clientSecret) {
30063
+ clientSecret = fileAuth.clientSecret;
29843
30064
  }
29844
- static removeAllLiterals() {
29845
- Jsep.literals = {};
29846
- return Jsep;
30065
+ const isExternalAppAuth = clientId !== DEFAULT_CLIENT_ID && Boolean(clientSecret);
30066
+ const scopes = resolveScopes(isExternalAppAuth, customScopes, fileAuth.scopes);
30067
+ return {
30068
+ clientId,
30069
+ clientSecret,
30070
+ scopes,
30071
+ baseUrl,
30072
+ authorizationEndpoint: `${baseUrl}/identity_/connect/authorize`,
30073
+ tokenEndpoint: `${baseUrl}/identity_/connect/token`
30074
+ };
30075
+ };
30076
+
30077
+ // ../auth/src/index.ts
30078
+ init_constants();
30079
+ // ../auth/src/loginStatus.ts
30080
+ init_src();
30081
+
30082
+ // ../auth/src/authProfile.ts
30083
+ init_src();
30084
+ init_constants();
30085
+ var DEFAULT_AUTH_PROFILE = "default";
30086
+ var PROFILE_DIR = "profiles";
30087
+ var PROFILE_NAME_RE = /^[A-Za-z0-9._-]+$/;
30088
+ var ACTIVE_AUTH_PROFILE_KEY = Symbol.for("@uipath/auth/ActiveAuthProfile");
30089
+ var AUTH_PROFILE_STORAGE_KEY = Symbol.for("@uipath/auth/ProfileStorage");
30090
+ var globalSlot2 = globalThis;
30091
+ function isAuthProfileStorage(value) {
30092
+ return value !== null && typeof value === "object" && "getStore" in value && "run" in value;
30093
+ }
30094
+ function createProfileStorage() {
30095
+ const [error, mod2] = catchError2(() => __require("node:async_hooks"));
30096
+ if (error || typeof mod2?.AsyncLocalStorage !== "function") {
30097
+ return {
30098
+ getStore: () => {
30099
+ return;
30100
+ },
30101
+ run: (_store, fn) => fn()
30102
+ };
29847
30103
  }
29848
- get char() {
29849
- return this.expr.charAt(this.index);
30104
+ return new mod2.AsyncLocalStorage;
30105
+ }
30106
+ function getProfileStorage() {
30107
+ const existing = globalSlot2[AUTH_PROFILE_STORAGE_KEY];
30108
+ if (isAuthProfileStorage(existing)) {
30109
+ return existing;
29850
30110
  }
29851
- get code() {
29852
- return this.expr.charCodeAt(this.index);
29853
- }
29854
- constructor(expr) {
29855
- this.expr = expr;
29856
- this.index = 0;
29857
- }
29858
- static parse(expr) {
29859
- return new Jsep(expr).parse();
29860
- }
29861
- static getMaxKeyLen(obj) {
29862
- return Math.max(0, ...Object.keys(obj).map((k) => k.length));
29863
- }
29864
- static isDecimalDigit(ch) {
29865
- return ch >= 48 && ch <= 57;
29866
- }
29867
- static binaryPrecedence(op_val) {
29868
- return Jsep.binary_ops[op_val] || 0;
29869
- }
29870
- static isIdentifierStart(ch) {
29871
- 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));
29872
- }
29873
- static isIdentifierPart(ch) {
29874
- return Jsep.isIdentifierStart(ch) || Jsep.isDecimalDigit(ch);
29875
- }
29876
- throwError(message) {
29877
- const error = new Error(message + " at character " + this.index);
29878
- error.index = this.index;
29879
- error.description = message;
29880
- throw error;
29881
- }
29882
- runHook(name, node) {
29883
- if (Jsep.hooks[name]) {
29884
- const env = {
29885
- context: this,
29886
- node
29887
- };
29888
- Jsep.hooks.run(name, env);
29889
- return env.node;
29890
- }
29891
- return node;
29892
- }
29893
- searchHook(name) {
29894
- if (Jsep.hooks[name]) {
29895
- const env = {
29896
- context: this
29897
- };
29898
- Jsep.hooks[name].find(function(callback) {
29899
- callback.call(env.context, env);
29900
- return env.node;
29901
- });
29902
- return env.node;
29903
- }
29904
- }
29905
- gobbleSpaces() {
29906
- let ch = this.code;
29907
- while (ch === Jsep.SPACE_CODE || ch === Jsep.TAB_CODE || ch === Jsep.LF_CODE || ch === Jsep.CR_CODE) {
29908
- ch = this.expr.charCodeAt(++this.index);
29909
- }
29910
- this.runHook("gobble-spaces");
29911
- }
29912
- parse() {
29913
- this.runHook("before-all");
29914
- const nodes = this.gobbleExpressions();
29915
- const node = nodes.length === 1 ? nodes[0] : {
29916
- type: Jsep.COMPOUND,
29917
- body: nodes
29918
- };
29919
- return this.runHook("after-all", node);
29920
- }
29921
- gobbleExpressions(untilICode) {
29922
- let nodes = [], ch_i, node;
29923
- while (this.index < this.expr.length) {
29924
- ch_i = this.code;
29925
- if (ch_i === Jsep.SEMCOL_CODE || ch_i === Jsep.COMMA_CODE) {
29926
- this.index++;
29927
- } else {
29928
- if (node = this.gobbleExpression()) {
29929
- nodes.push(node);
29930
- } else if (this.index < this.expr.length) {
29931
- if (ch_i === untilICode) {
29932
- break;
29933
- }
29934
- this.throwError('Unexpected "' + this.char + '"');
29935
- }
29936
- }
29937
- }
29938
- return nodes;
29939
- }
29940
- gobbleExpression() {
29941
- const node = this.searchHook("gobble-expression") || this.gobbleBinaryExpression();
29942
- this.gobbleSpaces();
29943
- return this.runHook("after-expression", node);
29944
- }
29945
- gobbleBinaryOp() {
29946
- this.gobbleSpaces();
29947
- let to_check = this.expr.substr(this.index, Jsep.max_binop_len);
29948
- let tc_len = to_check.length;
29949
- while (tc_len > 0) {
29950
- 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)))) {
29951
- this.index += tc_len;
29952
- return to_check;
29953
- }
29954
- to_check = to_check.substr(0, --tc_len);
29955
- }
29956
- return false;
29957
- }
29958
- gobbleBinaryExpression() {
29959
- let node, biop, prec, stack, biop_info, left, right, i, cur_biop;
29960
- left = this.gobbleToken();
29961
- if (!left) {
29962
- return left;
29963
- }
29964
- biop = this.gobbleBinaryOp();
29965
- if (!biop) {
29966
- return left;
29967
- }
29968
- biop_info = {
29969
- value: biop,
29970
- prec: Jsep.binaryPrecedence(biop),
29971
- right_a: Jsep.right_associative.has(biop)
29972
- };
29973
- right = this.gobbleToken();
29974
- if (!right) {
29975
- this.throwError("Expected expression after " + biop);
29976
- }
29977
- stack = [left, biop_info, right];
29978
- while (biop = this.gobbleBinaryOp()) {
29979
- prec = Jsep.binaryPrecedence(biop);
29980
- if (prec === 0) {
29981
- this.index -= biop.length;
29982
- break;
29983
- }
29984
- biop_info = {
29985
- value: biop,
29986
- prec,
29987
- right_a: Jsep.right_associative.has(biop)
29988
- };
29989
- cur_biop = biop;
29990
- const comparePrev = (prev) => biop_info.right_a && prev.right_a ? prec > prev.prec : prec <= prev.prec;
29991
- while (stack.length > 2 && comparePrev(stack[stack.length - 2])) {
29992
- right = stack.pop();
29993
- biop = stack.pop().value;
29994
- left = stack.pop();
29995
- node = {
29996
- type: Jsep.BINARY_EXP,
29997
- operator: biop,
29998
- left,
29999
- right
30000
- };
30001
- stack.push(node);
30002
- }
30003
- node = this.gobbleToken();
30004
- if (!node) {
30005
- this.throwError("Expected expression after " + cur_biop);
30006
- }
30007
- stack.push(biop_info, node);
30008
- }
30009
- i = stack.length - 1;
30010
- node = stack[i];
30011
- while (i > 1) {
30012
- node = {
30013
- type: Jsep.BINARY_EXP,
30014
- operator: stack[i - 1].value,
30015
- left: stack[i - 2],
30016
- right: node
30017
- };
30018
- i -= 2;
30019
- }
30020
- return node;
30021
- }
30022
- gobbleToken() {
30023
- let ch, to_check, tc_len, node;
30024
- this.gobbleSpaces();
30025
- node = this.searchHook("gobble-token");
30026
- if (node) {
30027
- return this.runHook("after-token", node);
30028
- }
30029
- ch = this.code;
30030
- if (Jsep.isDecimalDigit(ch) || ch === Jsep.PERIOD_CODE) {
30031
- return this.gobbleNumericLiteral();
30032
- }
30033
- if (ch === Jsep.SQUOTE_CODE || ch === Jsep.DQUOTE_CODE) {
30034
- node = this.gobbleStringLiteral();
30035
- } else if (ch === Jsep.OBRACK_CODE) {
30036
- node = this.gobbleArray();
30037
- } else {
30038
- to_check = this.expr.substr(this.index, Jsep.max_unop_len);
30039
- tc_len = to_check.length;
30040
- while (tc_len > 0) {
30041
- 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)))) {
30042
- this.index += tc_len;
30043
- const argument = this.gobbleToken();
30044
- if (!argument) {
30045
- this.throwError("missing unaryOp argument");
30046
- }
30047
- return this.runHook("after-token", {
30048
- type: Jsep.UNARY_EXP,
30049
- operator: to_check,
30050
- argument,
30051
- prefix: true
30052
- });
30053
- }
30054
- to_check = to_check.substr(0, --tc_len);
30055
- }
30056
- if (Jsep.isIdentifierStart(ch)) {
30057
- node = this.gobbleIdentifier();
30058
- if (Jsep.literals.hasOwnProperty(node.name)) {
30059
- node = {
30060
- type: Jsep.LITERAL,
30061
- value: Jsep.literals[node.name],
30062
- raw: node.name
30063
- };
30064
- } else if (node.name === Jsep.this_str) {
30065
- node = {
30066
- type: Jsep.THIS_EXP
30067
- };
30068
- }
30069
- } else if (ch === Jsep.OPAREN_CODE) {
30070
- node = this.gobbleGroup();
30071
- }
30072
- }
30073
- if (!node) {
30074
- return this.runHook("after-token", false);
30075
- }
30076
- node = this.gobbleTokenProperty(node);
30077
- return this.runHook("after-token", node);
30078
- }
30079
- gobbleTokenProperty(node) {
30080
- this.gobbleSpaces();
30081
- let ch = this.code;
30082
- while (ch === Jsep.PERIOD_CODE || ch === Jsep.OBRACK_CODE || ch === Jsep.OPAREN_CODE || ch === Jsep.QUMARK_CODE) {
30083
- let optional;
30084
- if (ch === Jsep.QUMARK_CODE) {
30085
- if (this.expr.charCodeAt(this.index + 1) !== Jsep.PERIOD_CODE) {
30086
- break;
30087
- }
30088
- optional = true;
30089
- this.index += 2;
30090
- this.gobbleSpaces();
30091
- ch = this.code;
30092
- }
30093
- this.index++;
30094
- if (ch === Jsep.OBRACK_CODE) {
30095
- node = {
30096
- type: Jsep.MEMBER_EXP,
30097
- computed: true,
30098
- object: node,
30099
- property: this.gobbleExpression()
30100
- };
30101
- if (!node.property) {
30102
- this.throwError('Unexpected "' + this.char + '"');
30103
- }
30104
- this.gobbleSpaces();
30105
- ch = this.code;
30106
- if (ch !== Jsep.CBRACK_CODE) {
30107
- this.throwError("Unclosed [");
30108
- }
30109
- this.index++;
30110
- } else if (ch === Jsep.OPAREN_CODE) {
30111
- node = {
30112
- type: Jsep.CALL_EXP,
30113
- arguments: this.gobbleArguments(Jsep.CPAREN_CODE),
30114
- callee: node
30115
- };
30116
- } else if (ch === Jsep.PERIOD_CODE || optional) {
30117
- if (optional) {
30118
- this.index--;
30119
- }
30120
- this.gobbleSpaces();
30121
- node = {
30122
- type: Jsep.MEMBER_EXP,
30123
- computed: false,
30124
- object: node,
30125
- property: this.gobbleIdentifier()
30126
- };
30127
- }
30128
- if (optional) {
30129
- node.optional = true;
30130
- }
30131
- this.gobbleSpaces();
30132
- ch = this.code;
30133
- }
30134
- return node;
30135
- }
30136
- gobbleNumericLiteral() {
30137
- let number = "", ch, chCode;
30138
- while (Jsep.isDecimalDigit(this.code)) {
30139
- number += this.expr.charAt(this.index++);
30140
- }
30141
- if (this.code === Jsep.PERIOD_CODE) {
30142
- number += this.expr.charAt(this.index++);
30143
- while (Jsep.isDecimalDigit(this.code)) {
30144
- number += this.expr.charAt(this.index++);
30145
- }
30146
- }
30147
- ch = this.char;
30148
- if (ch === "e" || ch === "E") {
30149
- number += this.expr.charAt(this.index++);
30150
- ch = this.char;
30151
- if (ch === "+" || ch === "-") {
30152
- number += this.expr.charAt(this.index++);
30153
- }
30154
- while (Jsep.isDecimalDigit(this.code)) {
30155
- number += this.expr.charAt(this.index++);
30156
- }
30157
- if (!Jsep.isDecimalDigit(this.expr.charCodeAt(this.index - 1))) {
30158
- this.throwError("Expected exponent (" + number + this.char + ")");
30159
- }
30160
- }
30161
- chCode = this.code;
30162
- if (Jsep.isIdentifierStart(chCode)) {
30163
- this.throwError("Variable names cannot start with a number (" + number + this.char + ")");
30164
- } else if (chCode === Jsep.PERIOD_CODE || number.length === 1 && number.charCodeAt(0) === Jsep.PERIOD_CODE) {
30165
- this.throwError("Unexpected period");
30166
- }
30167
- return {
30168
- type: Jsep.LITERAL,
30169
- value: parseFloat(number),
30170
- raw: number
30171
- };
30172
- }
30173
- gobbleStringLiteral() {
30174
- let str = "";
30175
- const startIndex = this.index;
30176
- const quote = this.expr.charAt(this.index++);
30177
- let closed = false;
30178
- while (this.index < this.expr.length) {
30179
- let ch = this.expr.charAt(this.index++);
30180
- if (ch === quote) {
30181
- closed = true;
30182
- break;
30183
- } else if (ch === "\\") {
30184
- ch = this.expr.charAt(this.index++);
30185
- switch (ch) {
30186
- case "n":
30187
- str += `
30188
- `;
30189
- break;
30190
- case "r":
30191
- str += "\r";
30192
- break;
30193
- case "t":
30194
- str += "\t";
30195
- break;
30196
- case "b":
30197
- str += "\b";
30198
- break;
30199
- case "f":
30200
- str += "\f";
30201
- break;
30202
- case "v":
30203
- str += "\v";
30204
- break;
30205
- default:
30206
- str += ch;
30207
- }
30208
- } else {
30209
- str += ch;
30210
- }
30211
- }
30212
- if (!closed) {
30213
- this.throwError('Unclosed quote after "' + str + '"');
30214
- }
30215
- return {
30216
- type: Jsep.LITERAL,
30217
- value: str,
30218
- raw: this.expr.substring(startIndex, this.index)
30219
- };
30220
- }
30221
- gobbleIdentifier() {
30222
- let ch = this.code, start = this.index;
30223
- if (Jsep.isIdentifierStart(ch)) {
30224
- this.index++;
30225
- } else {
30226
- this.throwError("Unexpected " + this.char);
30227
- }
30228
- while (this.index < this.expr.length) {
30229
- ch = this.code;
30230
- if (Jsep.isIdentifierPart(ch)) {
30231
- this.index++;
30232
- } else {
30233
- break;
30234
- }
30235
- }
30236
- return {
30237
- type: Jsep.IDENTIFIER,
30238
- name: this.expr.slice(start, this.index)
30239
- };
30240
- }
30241
- gobbleArguments(termination) {
30242
- const args = [];
30243
- let closed = false;
30244
- let separator_count = 0;
30245
- while (this.index < this.expr.length) {
30246
- this.gobbleSpaces();
30247
- let ch_i = this.code;
30248
- if (ch_i === termination) {
30249
- closed = true;
30250
- this.index++;
30251
- if (termination === Jsep.CPAREN_CODE && separator_count && separator_count >= args.length) {
30252
- this.throwError("Unexpected token " + String.fromCharCode(termination));
30253
- }
30254
- break;
30255
- } else if (ch_i === Jsep.COMMA_CODE) {
30256
- this.index++;
30257
- separator_count++;
30258
- if (separator_count !== args.length) {
30259
- if (termination === Jsep.CPAREN_CODE) {
30260
- this.throwError("Unexpected token ,");
30261
- } else if (termination === Jsep.CBRACK_CODE) {
30262
- for (let arg = args.length;arg < separator_count; arg++) {
30263
- args.push(null);
30264
- }
30265
- }
30266
- }
30267
- } else if (args.length !== separator_count && separator_count !== 0) {
30268
- this.throwError("Expected comma");
30269
- } else {
30270
- const node = this.gobbleExpression();
30271
- if (!node || node.type === Jsep.COMPOUND) {
30272
- this.throwError("Expected comma");
30273
- }
30274
- args.push(node);
30275
- }
30276
- }
30277
- if (!closed) {
30278
- this.throwError("Expected " + String.fromCharCode(termination));
30279
- }
30280
- return args;
30281
- }
30282
- gobbleGroup() {
30283
- this.index++;
30284
- let nodes = this.gobbleExpressions(Jsep.CPAREN_CODE);
30285
- if (this.code === Jsep.CPAREN_CODE) {
30286
- this.index++;
30287
- if (nodes.length === 1) {
30288
- return nodes[0];
30289
- } else if (!nodes.length) {
30290
- return false;
30291
- } else {
30292
- return {
30293
- type: Jsep.SEQUENCE_EXP,
30294
- expressions: nodes
30295
- };
30296
- }
30297
- } else {
30298
- this.throwError("Unclosed (");
30299
- }
30300
- }
30301
- gobbleArray() {
30302
- this.index++;
30303
- return {
30304
- type: Jsep.ARRAY_EXP,
30305
- elements: this.gobbleArguments(Jsep.CBRACK_CODE)
30306
- };
30307
- }
30308
- }
30309
- var hooks = new Hooks;
30310
- Object.assign(Jsep, {
30311
- hooks,
30312
- plugins: new Plugins(Jsep),
30313
- COMPOUND: "Compound",
30314
- SEQUENCE_EXP: "SequenceExpression",
30315
- IDENTIFIER: "Identifier",
30316
- MEMBER_EXP: "MemberExpression",
30317
- LITERAL: "Literal",
30318
- THIS_EXP: "ThisExpression",
30319
- CALL_EXP: "CallExpression",
30320
- UNARY_EXP: "UnaryExpression",
30321
- BINARY_EXP: "BinaryExpression",
30322
- ARRAY_EXP: "ArrayExpression",
30323
- TAB_CODE: 9,
30324
- LF_CODE: 10,
30325
- CR_CODE: 13,
30326
- SPACE_CODE: 32,
30327
- PERIOD_CODE: 46,
30328
- COMMA_CODE: 44,
30329
- SQUOTE_CODE: 39,
30330
- DQUOTE_CODE: 34,
30331
- OPAREN_CODE: 40,
30332
- CPAREN_CODE: 41,
30333
- OBRACK_CODE: 91,
30334
- CBRACK_CODE: 93,
30335
- QUMARK_CODE: 63,
30336
- SEMCOL_CODE: 59,
30337
- COLON_CODE: 58,
30338
- unary_ops: {
30339
- "-": 1,
30340
- "!": 1,
30341
- "~": 1,
30342
- "+": 1
30343
- },
30344
- binary_ops: {
30345
- "||": 1,
30346
- "??": 1,
30347
- "&&": 2,
30348
- "|": 3,
30349
- "^": 4,
30350
- "&": 5,
30351
- "==": 6,
30352
- "!=": 6,
30353
- "===": 6,
30354
- "!==": 6,
30355
- "<": 7,
30356
- ">": 7,
30357
- "<=": 7,
30358
- ">=": 7,
30359
- "<<": 8,
30360
- ">>": 8,
30361
- ">>>": 8,
30362
- "+": 9,
30363
- "-": 9,
30364
- "*": 10,
30365
- "/": 10,
30366
- "%": 10,
30367
- "**": 11
30368
- },
30369
- right_associative: new Set(["**"]),
30370
- additional_identifier_chars: new Set(["$", "_"]),
30371
- literals: {
30372
- true: true,
30373
- false: false,
30374
- null: null
30375
- },
30376
- this_str: "this"
30377
- });
30378
- Jsep.max_unop_len = Jsep.getMaxKeyLen(Jsep.unary_ops);
30379
- Jsep.max_binop_len = Jsep.getMaxKeyLen(Jsep.binary_ops);
30380
- var jsep = (expr) => new Jsep(expr).parse();
30381
- var stdClassProps = Object.getOwnPropertyNames(class Test {
30382
- });
30383
- Object.getOwnPropertyNames(Jsep).filter((prop) => !stdClassProps.includes(prop) && jsep[prop] === undefined).forEach((m) => {
30384
- jsep[m] = Jsep[m];
30385
- });
30386
- jsep.Jsep = Jsep;
30387
- var CONDITIONAL_EXP = "ConditionalExpression";
30388
- var ternary = {
30389
- name: "ternary",
30390
- init(jsep2) {
30391
- jsep2.hooks.add("after-expression", function gobbleTernary(env) {
30392
- if (env.node && this.code === jsep2.QUMARK_CODE) {
30393
- this.index++;
30394
- const test = env.node;
30395
- const consequent = this.gobbleExpression();
30396
- if (!consequent) {
30397
- this.throwError("Expected expression");
30398
- }
30399
- this.gobbleSpaces();
30400
- if (this.code === jsep2.COLON_CODE) {
30401
- this.index++;
30402
- const alternate = this.gobbleExpression();
30403
- if (!alternate) {
30404
- this.throwError("Expected expression");
30405
- }
30406
- env.node = {
30407
- type: CONDITIONAL_EXP,
30408
- test,
30409
- consequent,
30410
- alternate
30411
- };
30412
- if (test.operator && jsep2.binary_ops[test.operator] <= 0.9) {
30413
- let newTest = test;
30414
- while (newTest.right.operator && jsep2.binary_ops[newTest.right.operator] <= 0.9) {
30415
- newTest = newTest.right;
30416
- }
30417
- env.node.test = newTest.right;
30418
- newTest.right = env.node;
30419
- env.node = test;
30420
- }
30421
- } else {
30422
- this.throwError("Expected :");
30423
- }
30424
- }
30425
- });
30426
- }
30427
- };
30428
- jsep.plugins.register(ternary);
30429
- var FSLASH_CODE = 47;
30430
- var BSLASH_CODE = 92;
30431
- var index = {
30432
- name: "regex",
30433
- init(jsep2) {
30434
- jsep2.hooks.add("gobble-token", function gobbleRegexLiteral(env) {
30435
- if (this.code === FSLASH_CODE) {
30436
- const patternIndex = ++this.index;
30437
- let inCharSet = false;
30438
- while (this.index < this.expr.length) {
30439
- if (this.code === FSLASH_CODE && !inCharSet) {
30440
- const pattern = this.expr.slice(patternIndex, this.index);
30441
- let flags = "";
30442
- while (++this.index < this.expr.length) {
30443
- const code = this.code;
30444
- if (code >= 97 && code <= 122 || code >= 65 && code <= 90 || code >= 48 && code <= 57) {
30445
- flags += this.char;
30446
- } else {
30447
- break;
30448
- }
30449
- }
30450
- let value;
30451
- try {
30452
- value = new RegExp(pattern, flags);
30453
- } catch (e) {
30454
- this.throwError(e.message);
30455
- }
30456
- env.node = {
30457
- type: jsep2.LITERAL,
30458
- value,
30459
- raw: this.expr.slice(patternIndex - 1, this.index)
30460
- };
30461
- env.node = this.gobbleTokenProperty(env.node);
30462
- return env.node;
30463
- }
30464
- if (this.code === jsep2.OBRACK_CODE) {
30465
- inCharSet = true;
30466
- } else if (inCharSet && this.code === jsep2.CBRACK_CODE) {
30467
- inCharSet = false;
30468
- }
30469
- this.index += this.code === BSLASH_CODE ? 2 : 1;
30470
- }
30471
- this.throwError("Unclosed Regex");
30472
- }
30473
- });
30474
- }
30475
- };
30476
- var PLUS_CODE = 43;
30477
- var MINUS_CODE = 45;
30478
- var plugin = {
30479
- name: "assignment",
30480
- assignmentOperators: new Set(["=", "*=", "**=", "/=", "%=", "+=", "-=", "<<=", ">>=", ">>>=", "&=", "^=", "|=", "||=", "&&=", "??="]),
30481
- updateOperators: [PLUS_CODE, MINUS_CODE],
30482
- assignmentPrecedence: 0.9,
30483
- init(jsep2) {
30484
- const updateNodeTypes = [jsep2.IDENTIFIER, jsep2.MEMBER_EXP];
30485
- plugin.assignmentOperators.forEach((op) => jsep2.addBinaryOp(op, plugin.assignmentPrecedence, true));
30486
- jsep2.hooks.add("gobble-token", function gobbleUpdatePrefix(env) {
30487
- const code = this.code;
30488
- if (plugin.updateOperators.some((c) => c === code && c === this.expr.charCodeAt(this.index + 1))) {
30489
- this.index += 2;
30490
- env.node = {
30491
- type: "UpdateExpression",
30492
- operator: code === PLUS_CODE ? "++" : "--",
30493
- argument: this.gobbleTokenProperty(this.gobbleIdentifier()),
30494
- prefix: true
30495
- };
30496
- if (!env.node.argument || !updateNodeTypes.includes(env.node.argument.type)) {
30497
- this.throwError(`Unexpected ${env.node.operator}`);
30498
- }
30499
- }
30500
- });
30501
- jsep2.hooks.add("after-token", function gobbleUpdatePostfix(env) {
30502
- if (env.node) {
30503
- const code = this.code;
30504
- if (plugin.updateOperators.some((c) => c === code && c === this.expr.charCodeAt(this.index + 1))) {
30505
- if (!updateNodeTypes.includes(env.node.type)) {
30506
- this.throwError(`Unexpected ${env.node.operator}`);
30507
- }
30508
- this.index += 2;
30509
- env.node = {
30510
- type: "UpdateExpression",
30511
- operator: code === PLUS_CODE ? "++" : "--",
30512
- argument: env.node,
30513
- prefix: false
30514
- };
30515
- }
30516
- }
30517
- });
30518
- jsep2.hooks.add("after-expression", function gobbleAssignment(env) {
30519
- if (env.node) {
30520
- updateBinariesToAssignments(env.node);
30521
- }
30522
- });
30523
- function updateBinariesToAssignments(node) {
30524
- if (plugin.assignmentOperators.has(node.operator)) {
30525
- node.type = "AssignmentExpression";
30526
- updateBinariesToAssignments(node.left);
30527
- updateBinariesToAssignments(node.right);
30528
- } else if (!node.operator) {
30529
- Object.values(node).forEach((val) => {
30530
- if (val && typeof val === "object") {
30531
- updateBinariesToAssignments(val);
30532
- }
30533
- });
30534
- }
30535
- }
30536
- }
30537
- };
30538
- jsep.plugins.register(index, plugin);
30539
- jsep.addUnaryOp("typeof");
30540
- jsep.addUnaryOp("void");
30541
- jsep.addLiteral("null", null);
30542
- jsep.addLiteral("undefined", undefined);
30543
- var BLOCKED_PROTO_PROPERTIES = new Set(["constructor", "__proto__", "__defineGetter__", "__defineSetter__", "__lookupGetter__", "__lookupSetter__"]);
30544
- var SafeEval = {
30545
- evalAst(ast, subs) {
30546
- switch (ast.type) {
30547
- case "BinaryExpression":
30548
- case "LogicalExpression":
30549
- return SafeEval.evalBinaryExpression(ast, subs);
30550
- case "Compound":
30551
- return SafeEval.evalCompound(ast, subs);
30552
- case "ConditionalExpression":
30553
- return SafeEval.evalConditionalExpression(ast, subs);
30554
- case "Identifier":
30555
- return SafeEval.evalIdentifier(ast, subs);
30556
- case "Literal":
30557
- return SafeEval.evalLiteral(ast, subs);
30558
- case "MemberExpression":
30559
- return SafeEval.evalMemberExpression(ast, subs);
30560
- case "UnaryExpression":
30561
- return SafeEval.evalUnaryExpression(ast, subs);
30562
- case "ArrayExpression":
30563
- return SafeEval.evalArrayExpression(ast, subs);
30564
- case "CallExpression":
30565
- return SafeEval.evalCallExpression(ast, subs);
30566
- case "AssignmentExpression":
30567
- return SafeEval.evalAssignmentExpression(ast, subs);
30568
- default:
30569
- throw SyntaxError("Unexpected expression", ast);
30570
- }
30571
- },
30572
- evalBinaryExpression(ast, subs) {
30573
- const result = {
30574
- "||": (a, b) => a || b(),
30575
- "&&": (a, b) => a && b(),
30576
- "|": (a, b) => a | b(),
30577
- "^": (a, b) => a ^ b(),
30578
- "&": (a, b) => a & b(),
30579
- "==": (a, b) => a == b(),
30580
- "!=": (a, b) => a != b(),
30581
- "===": (a, b) => a === b(),
30582
- "!==": (a, b) => a !== b(),
30583
- "<": (a, b) => a < b(),
30584
- ">": (a, b) => a > b(),
30585
- "<=": (a, b) => a <= b(),
30586
- ">=": (a, b) => a >= b(),
30587
- "<<": (a, b) => a << b(),
30588
- ">>": (a, b) => a >> b(),
30589
- ">>>": (a, b) => a >>> b(),
30590
- "+": (a, b) => a + b(),
30591
- "-": (a, b) => a - b(),
30592
- "*": (a, b) => a * b(),
30593
- "/": (a, b) => a / b(),
30594
- "%": (a, b) => a % b()
30595
- }[ast.operator](SafeEval.evalAst(ast.left, subs), () => SafeEval.evalAst(ast.right, subs));
30596
- return result;
30597
- },
30598
- evalCompound(ast, subs) {
30599
- let last;
30600
- for (let i = 0;i < ast.body.length; i++) {
30601
- if (ast.body[i].type === "Identifier" && ["var", "let", "const"].includes(ast.body[i].name) && ast.body[i + 1] && ast.body[i + 1].type === "AssignmentExpression") {
30602
- i += 1;
30603
- }
30604
- const expr = ast.body[i];
30605
- last = SafeEval.evalAst(expr, subs);
30606
- }
30607
- return last;
30608
- },
30609
- evalConditionalExpression(ast, subs) {
30610
- if (SafeEval.evalAst(ast.test, subs)) {
30611
- return SafeEval.evalAst(ast.consequent, subs);
30612
- }
30613
- return SafeEval.evalAst(ast.alternate, subs);
30614
- },
30615
- evalIdentifier(ast, subs) {
30616
- if (Object.hasOwn(subs, ast.name)) {
30617
- return subs[ast.name];
30618
- }
30619
- throw ReferenceError(`${ast.name} is not defined`);
30620
- },
30621
- evalLiteral(ast) {
30622
- return ast.value;
30623
- },
30624
- evalMemberExpression(ast, subs) {
30625
- const prop = String(ast.computed ? SafeEval.evalAst(ast.property) : ast.property.name);
30626
- const obj = SafeEval.evalAst(ast.object, subs);
30627
- if (obj === undefined || obj === null) {
30628
- throw TypeError(`Cannot read properties of ${obj} (reading '${prop}')`);
30629
- }
30630
- if (!Object.hasOwn(obj, prop) && BLOCKED_PROTO_PROPERTIES.has(prop)) {
30631
- throw TypeError(`Cannot read properties of ${obj} (reading '${prop}')`);
30632
- }
30633
- const result = obj[prop];
30634
- if (typeof result === "function") {
30635
- return result.bind(obj);
30636
- }
30637
- return result;
30638
- },
30639
- evalUnaryExpression(ast, subs) {
30640
- const result = {
30641
- "-": (a) => -SafeEval.evalAst(a, subs),
30642
- "!": (a) => !SafeEval.evalAst(a, subs),
30643
- "~": (a) => ~SafeEval.evalAst(a, subs),
30644
- "+": (a) => +SafeEval.evalAst(a, subs),
30645
- typeof: (a) => typeof SafeEval.evalAst(a, subs),
30646
- void: (a) => void SafeEval.evalAst(a, subs)
30647
- }[ast.operator](ast.argument);
30648
- return result;
30649
- },
30650
- evalArrayExpression(ast, subs) {
30651
- return ast.elements.map((el) => SafeEval.evalAst(el, subs));
30652
- },
30653
- evalCallExpression(ast, subs) {
30654
- const args = ast.arguments.map((arg) => SafeEval.evalAst(arg, subs));
30655
- const func = SafeEval.evalAst(ast.callee, subs);
30656
- if (func === Function) {
30657
- throw new Error("Function constructor is disabled");
30658
- }
30659
- return func(...args);
30660
- },
30661
- evalAssignmentExpression(ast, subs) {
30662
- if (ast.left.type !== "Identifier") {
30663
- throw SyntaxError("Invalid left-hand side in assignment");
30664
- }
30665
- const id = ast.left.name;
30666
- const value = SafeEval.evalAst(ast.right, subs);
30667
- subs[id] = value;
30668
- return subs[id];
30669
- }
30670
- };
30671
-
30672
- class SafeScript {
30673
- constructor(expr) {
30674
- this.code = expr;
30675
- this.ast = jsep(this.code);
30676
- }
30677
- runInNewContext(context) {
30678
- const keyMap = Object.assign(Object.create(null), context);
30679
- return SafeEval.evalAst(this.ast, keyMap);
30680
- }
30681
- }
30682
- function push(arr, item) {
30683
- arr = arr.slice();
30684
- arr.push(item);
30685
- return arr;
30111
+ const storage = createProfileStorage();
30112
+ globalSlot2[AUTH_PROFILE_STORAGE_KEY] = storage;
30113
+ return storage;
30686
30114
  }
30687
- function unshift(item, arr) {
30688
- arr = arr.slice();
30689
- arr.unshift(item);
30690
- return arr;
30691
- }
30692
-
30693
- class NewError extends Error {
30694
- constructor(value) {
30695
- super('JSONPath should not be called with "new" (it prevents return ' + "of (unwrapped) scalar values)");
30696
- this.avoidNew = true;
30697
- this.value = value;
30698
- this.name = "NewError";
30699
- }
30700
- }
30701
- function JSONPath(opts, expr, obj, callback, otherTypeCallback) {
30702
- if (!(this instanceof JSONPath)) {
30703
- try {
30704
- return new JSONPath(opts, expr, obj, callback, otherTypeCallback);
30705
- } catch (e) {
30706
- if (!e.avoidNew) {
30707
- throw e;
30708
- }
30709
- return e.value;
30710
- }
30711
- }
30712
- if (typeof opts === "string") {
30713
- otherTypeCallback = callback;
30714
- callback = obj;
30715
- obj = expr;
30716
- expr = opts;
30717
- opts = null;
30718
- }
30719
- const optObj = opts && typeof opts === "object";
30720
- opts = opts || {};
30721
- this.json = opts.json || obj;
30722
- this.path = opts.path || expr;
30723
- this.resultType = opts.resultType || "value";
30724
- this.flatten = opts.flatten || false;
30725
- this.wrap = Object.hasOwn(opts, "wrap") ? opts.wrap : true;
30726
- this.sandbox = opts.sandbox || {};
30727
- this.eval = opts.eval === undefined ? "safe" : opts.eval;
30728
- this.ignoreEvalErrors = typeof opts.ignoreEvalErrors === "undefined" ? false : opts.ignoreEvalErrors;
30729
- this.parent = opts.parent || null;
30730
- this.parentProperty = opts.parentProperty || null;
30731
- this.callback = opts.callback || callback || null;
30732
- this.otherTypeCallback = opts.otherTypeCallback || otherTypeCallback || function() {
30733
- throw new TypeError("You must supply an otherTypeCallback callback option " + "with the @other() operator.");
30734
- };
30735
- if (opts.autostart !== false) {
30736
- const args = {
30737
- path: optObj ? opts.path : expr
30738
- };
30739
- if (!optObj) {
30740
- args.json = obj;
30741
- } else if ("json" in opts) {
30742
- args.json = opts.json;
30743
- }
30744
- const ret = this.evaluate(args);
30745
- if (!ret || typeof ret !== "object") {
30746
- throw new NewError(ret);
30747
- }
30748
- return ret;
30749
- }
30750
- }
30751
- JSONPath.prototype.evaluate = function(expr, json, callback, otherTypeCallback) {
30752
- let currParent = this.parent, currParentProperty = this.parentProperty;
30753
- let {
30754
- flatten,
30755
- wrap
30756
- } = this;
30757
- this.currResultType = this.resultType;
30758
- this.currEval = this.eval;
30759
- this.currSandbox = this.sandbox;
30760
- callback = callback || this.callback;
30761
- this.currOtherTypeCallback = otherTypeCallback || this.otherTypeCallback;
30762
- json = json || this.json;
30763
- expr = expr || this.path;
30764
- if (expr && typeof expr === "object" && !Array.isArray(expr)) {
30765
- if (!expr.path && expr.path !== "") {
30766
- throw new TypeError('You must supply a "path" property when providing an object ' + "argument to JSONPath.evaluate().");
30767
- }
30768
- if (!Object.hasOwn(expr, "json")) {
30769
- throw new TypeError('You must supply a "json" property when providing an object ' + "argument to JSONPath.evaluate().");
30770
- }
30771
- ({
30772
- json
30773
- } = expr);
30774
- flatten = Object.hasOwn(expr, "flatten") ? expr.flatten : flatten;
30775
- this.currResultType = Object.hasOwn(expr, "resultType") ? expr.resultType : this.currResultType;
30776
- this.currSandbox = Object.hasOwn(expr, "sandbox") ? expr.sandbox : this.currSandbox;
30777
- wrap = Object.hasOwn(expr, "wrap") ? expr.wrap : wrap;
30778
- this.currEval = Object.hasOwn(expr, "eval") ? expr.eval : this.currEval;
30779
- callback = Object.hasOwn(expr, "callback") ? expr.callback : callback;
30780
- this.currOtherTypeCallback = Object.hasOwn(expr, "otherTypeCallback") ? expr.otherTypeCallback : this.currOtherTypeCallback;
30781
- currParent = Object.hasOwn(expr, "parent") ? expr.parent : currParent;
30782
- currParentProperty = Object.hasOwn(expr, "parentProperty") ? expr.parentProperty : currParentProperty;
30783
- expr = expr.path;
30784
- }
30785
- currParent = currParent || null;
30786
- currParentProperty = currParentProperty || null;
30787
- if (Array.isArray(expr)) {
30788
- expr = JSONPath.toPathString(expr);
30789
- }
30790
- if (!expr && expr !== "" || !json) {
30791
- return;
30792
- }
30793
- const exprList = JSONPath.toPathArray(expr);
30794
- if (exprList[0] === "$" && exprList.length > 1) {
30795
- exprList.shift();
30796
- }
30797
- this._hasParentSelector = null;
30798
- const result = this._trace(exprList, json, ["$"], currParent, currParentProperty, callback).filter(function(ea) {
30799
- return ea && !ea.isParentSelector;
30800
- });
30801
- if (!result.length) {
30802
- return wrap ? [] : undefined;
30803
- }
30804
- if (!wrap && result.length === 1 && !result[0].hasArrExpr) {
30805
- return this._getPreferredOutput(result[0]);
30806
- }
30807
- return result.reduce((rslt, ea) => {
30808
- const valOrPath = this._getPreferredOutput(ea);
30809
- if (flatten && Array.isArray(valOrPath)) {
30810
- rslt = rslt.concat(valOrPath);
30811
- } else {
30812
- rslt.push(valOrPath);
30813
- }
30814
- return rslt;
30815
- }, []);
30816
- };
30817
- JSONPath.prototype._getPreferredOutput = function(ea) {
30818
- const resultType = this.currResultType;
30819
- switch (resultType) {
30820
- case "all": {
30821
- const path3 = Array.isArray(ea.path) ? ea.path : JSONPath.toPathArray(ea.path);
30822
- ea.pointer = JSONPath.toPointer(path3);
30823
- ea.path = typeof ea.path === "string" ? ea.path : JSONPath.toPathString(ea.path);
30824
- return ea;
30825
- }
30826
- case "value":
30827
- case "parent":
30828
- case "parentProperty":
30829
- return ea[resultType];
30830
- case "path":
30831
- return JSONPath.toPathString(ea[resultType]);
30832
- case "pointer":
30833
- return JSONPath.toPointer(ea.path);
30834
- default:
30835
- throw new TypeError("Unknown result type");
30836
- }
30837
- };
30838
- JSONPath.prototype._handleCallback = function(fullRetObj, callback, type) {
30839
- if (callback) {
30840
- const preferredOutput = this._getPreferredOutput(fullRetObj);
30841
- fullRetObj.path = typeof fullRetObj.path === "string" ? fullRetObj.path : JSONPath.toPathString(fullRetObj.path);
30842
- callback(preferredOutput, type, fullRetObj);
30843
- }
30844
- };
30845
- JSONPath.prototype._trace = function(expr, val, path3, parent, parentPropName, callback, hasArrExpr, literalPriority) {
30846
- let retObj;
30847
- if (!expr.length) {
30848
- retObj = {
30849
- path: path3,
30850
- value: val,
30851
- parent,
30852
- parentProperty: parentPropName,
30853
- hasArrExpr
30854
- };
30855
- this._handleCallback(retObj, callback, "value");
30856
- return retObj;
30857
- }
30858
- const loc = expr[0], x = expr.slice(1);
30859
- const ret = [];
30860
- function addRet(elems) {
30861
- if (Array.isArray(elems)) {
30862
- elems.forEach((t) => {
30863
- ret.push(t);
30864
- });
30865
- } else {
30866
- ret.push(elems);
30867
- }
30868
- }
30869
- if ((typeof loc !== "string" || literalPriority) && val && Object.hasOwn(val, loc)) {
30870
- addRet(this._trace(x, val[loc], push(path3, loc), val, loc, callback, hasArrExpr));
30871
- } else if (loc === "*") {
30872
- this._walk(val, (m) => {
30873
- addRet(this._trace(x, val[m], push(path3, m), val, m, callback, true, true));
30874
- });
30875
- } else if (loc === "..") {
30876
- addRet(this._trace(x, val, path3, parent, parentPropName, callback, hasArrExpr));
30877
- this._walk(val, (m) => {
30878
- if (typeof val[m] === "object") {
30879
- addRet(this._trace(expr.slice(), val[m], push(path3, m), val, m, callback, true));
30880
- }
30881
- });
30882
- } else if (loc === "^") {
30883
- this._hasParentSelector = true;
30884
- return {
30885
- path: path3.slice(0, -1),
30886
- expr: x,
30887
- isParentSelector: true
30888
- };
30889
- } else if (loc === "~") {
30890
- retObj = {
30891
- path: push(path3, loc),
30892
- value: parentPropName,
30893
- parent,
30894
- parentProperty: null
30895
- };
30896
- this._handleCallback(retObj, callback, "property");
30897
- return retObj;
30898
- } else if (loc === "$") {
30899
- addRet(this._trace(x, val, path3, null, null, callback, hasArrExpr));
30900
- } else if (/^(-?\d*):(-?\d*):?(\d*)$/u.test(loc)) {
30901
- addRet(this._slice(loc, x, val, path3, parent, parentPropName, callback));
30902
- } else if (loc.indexOf("?(") === 0) {
30903
- if (this.currEval === false) {
30904
- throw new Error("Eval [?(expr)] prevented in JSONPath expression.");
30905
- }
30906
- const safeLoc = loc.replace(/^\?\((.*?)\)$/u, "$1");
30907
- const nested = /@.?([^?]*)[['](\??\(.*?\))(?!.\)\])[\]']/gu.exec(safeLoc);
30908
- if (nested) {
30909
- this._walk(val, (m) => {
30910
- const npath = [nested[2]];
30911
- const nvalue = nested[1] ? val[m][nested[1]] : val[m];
30912
- const filterResults = this._trace(npath, nvalue, path3, parent, parentPropName, callback, true);
30913
- if (filterResults.length > 0) {
30914
- addRet(this._trace(x, val[m], push(path3, m), val, m, callback, true));
30915
- }
30916
- });
30917
- } else {
30918
- this._walk(val, (m) => {
30919
- if (this._eval(safeLoc, val[m], m, path3, parent, parentPropName)) {
30920
- addRet(this._trace(x, val[m], push(path3, m), val, m, callback, true));
30921
- }
30922
- });
30923
- }
30924
- } else if (loc[0] === "(") {
30925
- if (this.currEval === false) {
30926
- throw new Error("Eval [(expr)] prevented in JSONPath expression.");
30927
- }
30928
- addRet(this._trace(unshift(this._eval(loc, val, path3.at(-1), path3.slice(0, -1), parent, parentPropName), x), val, path3, parent, parentPropName, callback, hasArrExpr));
30929
- } else if (loc[0] === "@") {
30930
- let addType = false;
30931
- const valueType = loc.slice(1, -2);
30932
- switch (valueType) {
30933
- case "scalar":
30934
- if (!val || !["object", "function"].includes(typeof val)) {
30935
- addType = true;
30936
- }
30937
- break;
30938
- case "boolean":
30939
- case "string":
30940
- case "undefined":
30941
- case "function":
30942
- if (typeof val === valueType) {
30943
- addType = true;
30944
- }
30945
- break;
30946
- case "integer":
30947
- if (Number.isFinite(val) && !(val % 1)) {
30948
- addType = true;
30949
- }
30950
- break;
30951
- case "number":
30952
- if (Number.isFinite(val)) {
30953
- addType = true;
30954
- }
30955
- break;
30956
- case "nonFinite":
30957
- if (typeof val === "number" && !Number.isFinite(val)) {
30958
- addType = true;
30959
- }
30960
- break;
30961
- case "object":
30962
- if (val && typeof val === valueType) {
30963
- addType = true;
30964
- }
30965
- break;
30966
- case "array":
30967
- if (Array.isArray(val)) {
30968
- addType = true;
30969
- }
30970
- break;
30971
- case "other":
30972
- addType = this.currOtherTypeCallback(val, path3, parent, parentPropName);
30973
- break;
30974
- case "null":
30975
- if (val === null) {
30976
- addType = true;
30977
- }
30978
- break;
30979
- default:
30980
- throw new TypeError("Unknown value type " + valueType);
30981
- }
30982
- if (addType) {
30983
- retObj = {
30984
- path: path3,
30985
- value: val,
30986
- parent,
30987
- parentProperty: parentPropName
30988
- };
30989
- this._handleCallback(retObj, callback, "value");
30990
- return retObj;
30991
- }
30992
- } else if (loc[0] === "`" && val && Object.hasOwn(val, loc.slice(1))) {
30993
- const locProp = loc.slice(1);
30994
- addRet(this._trace(x, val[locProp], push(path3, locProp), val, locProp, callback, hasArrExpr, true));
30995
- } else if (loc.includes(",")) {
30996
- const parts = loc.split(",");
30997
- for (const part of parts) {
30998
- addRet(this._trace(unshift(part, x), val, path3, parent, parentPropName, callback, true));
30999
- }
31000
- } else if (!literalPriority && val && Object.hasOwn(val, loc)) {
31001
- addRet(this._trace(x, val[loc], push(path3, loc), val, loc, callback, hasArrExpr, true));
31002
- }
31003
- if (this._hasParentSelector) {
31004
- for (let t = 0;t < ret.length; t++) {
31005
- const rett = ret[t];
31006
- if (rett && rett.isParentSelector) {
31007
- const tmp = this._trace(rett.expr, val, rett.path, parent, parentPropName, callback, hasArrExpr);
31008
- if (Array.isArray(tmp)) {
31009
- ret[t] = tmp[0];
31010
- const tl = tmp.length;
31011
- for (let tt = 1;tt < tl; tt++) {
31012
- t++;
31013
- ret.splice(t, 0, tmp[tt]);
31014
- }
31015
- } else {
31016
- ret[t] = tmp;
31017
- }
31018
- }
31019
- }
31020
- }
31021
- return ret;
31022
- };
31023
- JSONPath.prototype._walk = function(val, f) {
31024
- if (Array.isArray(val)) {
31025
- const n = val.length;
31026
- for (let i = 0;i < n; i++) {
31027
- f(i);
31028
- }
31029
- } else if (val && typeof val === "object") {
31030
- Object.keys(val).forEach((m) => {
31031
- f(m);
31032
- });
31033
- }
31034
- };
31035
- JSONPath.prototype._slice = function(loc, expr, val, path3, parent, parentPropName, callback) {
31036
- if (!Array.isArray(val)) {
31037
- return;
31038
- }
31039
- const len = val.length, parts = loc.split(":"), step = parts[2] && Number.parseInt(parts[2]) || 1;
31040
- let start = parts[0] && Number.parseInt(parts[0]) || 0, end = parts[1] && Number.parseInt(parts[1]) || len;
31041
- start = start < 0 ? Math.max(0, start + len) : Math.min(len, start);
31042
- end = end < 0 ? Math.max(0, end + len) : Math.min(len, end);
31043
- const ret = [];
31044
- for (let i = start;i < end; i += step) {
31045
- const tmp = this._trace(unshift(i, expr), val, path3, parent, parentPropName, callback, true);
31046
- tmp.forEach((t) => {
31047
- ret.push(t);
31048
- });
31049
- }
31050
- return ret;
31051
- };
31052
- JSONPath.prototype._eval = function(code, _v, _vname, path3, parent, parentPropName) {
31053
- this.currSandbox._$_parentProperty = parentPropName;
31054
- this.currSandbox._$_parent = parent;
31055
- this.currSandbox._$_property = _vname;
31056
- this.currSandbox._$_root = this.json;
31057
- this.currSandbox._$_v = _v;
31058
- const containsPath = code.includes("@path");
31059
- if (containsPath) {
31060
- this.currSandbox._$_path = JSONPath.toPathString(path3.concat([_vname]));
31061
- }
31062
- const scriptCacheKey = this.currEval + "Script:" + code;
31063
- if (!JSONPath.cache[scriptCacheKey]) {
31064
- let script = code.replaceAll("@parentProperty", "_$_parentProperty").replaceAll("@parent", "_$_parent").replaceAll("@property", "_$_property").replaceAll("@root", "_$_root").replaceAll(/@([.\s)[])/gu, "_$_v$1");
31065
- if (containsPath) {
31066
- script = script.replaceAll("@path", "_$_path");
31067
- }
31068
- if (this.currEval === "safe" || this.currEval === true || this.currEval === undefined) {
31069
- JSONPath.cache[scriptCacheKey] = new this.safeVm.Script(script);
31070
- } else if (this.currEval === "native") {
31071
- JSONPath.cache[scriptCacheKey] = new this.vm.Script(script);
31072
- } else if (typeof this.currEval === "function" && this.currEval.prototype && Object.hasOwn(this.currEval.prototype, "runInNewContext")) {
31073
- const CurrEval = this.currEval;
31074
- JSONPath.cache[scriptCacheKey] = new CurrEval(script);
31075
- } else if (typeof this.currEval === "function") {
31076
- JSONPath.cache[scriptCacheKey] = {
31077
- runInNewContext: (context) => this.currEval(script, context)
31078
- };
31079
- } else {
31080
- throw new TypeError(`Unknown "eval" property "${this.currEval}"`);
31081
- }
31082
- }
31083
- try {
31084
- return JSONPath.cache[scriptCacheKey].runInNewContext(this.currSandbox);
31085
- } catch (e) {
31086
- if (this.ignoreEvalErrors) {
31087
- return false;
31088
- }
31089
- throw new Error("jsonPath: " + e.message + ": " + code);
31090
- }
31091
- };
31092
- JSONPath.cache = {};
31093
- JSONPath.toPathString = function(pathArr) {
31094
- const x = pathArr, n = x.length;
31095
- let p = "$";
31096
- for (let i = 1;i < n; i++) {
31097
- if (!/^(~|\^|@.*?\(\))$/u.test(x[i])) {
31098
- p += /^[0-9*]+$/u.test(x[i]) ? "[" + x[i] + "]" : "['" + x[i] + "']";
31099
- }
31100
- }
31101
- return p;
31102
- };
31103
- JSONPath.toPointer = function(pointer) {
31104
- const x = pointer, n = x.length;
31105
- let p = "";
31106
- for (let i = 1;i < n; i++) {
31107
- if (!/^(~|\^|@.*?\(\))$/u.test(x[i])) {
31108
- p += "/" + x[i].toString().replaceAll("~", "~0").replaceAll("/", "~1");
31109
- }
31110
- }
31111
- return p;
31112
- };
31113
- JSONPath.toPathArray = function(expr) {
31114
- const {
31115
- cache
31116
- } = JSONPath;
31117
- if (cache[expr]) {
31118
- return cache[expr].concat();
31119
- }
31120
- const subx = [];
31121
- const normalized = expr.replaceAll(/@(?:null|boolean|number|string|integer|undefined|nonFinite|scalar|array|object|function|other)\(\)/gu, ";$&;").replaceAll(/[['](\??\(.*?\))[\]'](?!.\])/gu, function($0, $1) {
31122
- return "[#" + (subx.push($1) - 1) + "]";
31123
- }).replaceAll(/\[['"]([^'\]]*)['"]\]/gu, function($0, prop) {
31124
- return "['" + prop.replaceAll(".", "%@%").replaceAll("~", "%%@@%%") + "']";
31125
- }).replaceAll("~", ";~;").replaceAll(/['"]?\.['"]?(?![^[]*\])|\[['"]?/gu, ";").replaceAll("%@%", ".").replaceAll("%%@@%%", "~").replaceAll(/(?:;)?(\^+)(?:;)?/gu, function($0, ups) {
31126
- return ";" + ups.split("").join(";") + ";";
31127
- }).replaceAll(/;;;|;;/gu, ";..;").replaceAll(/;$|'?\]|'$/gu, "");
31128
- const exprList = normalized.split(";").map(function(exp) {
31129
- const match = exp.match(/#(\d+)/u);
31130
- return !match || !match[1] ? exp : subx[match[1]];
31131
- });
31132
- cache[expr] = exprList;
31133
- return cache[expr].concat();
31134
- };
31135
- JSONPath.prototype.safeVm = {
31136
- Script: SafeScript
31137
- };
31138
- JSONPath.prototype.vm = vm;
31139
- // ../common/src/polling/types.ts
31140
- var PollOutcome = {
31141
- Completed: "completed",
31142
- Timeout: "timeout",
31143
- Interrupted: "interrupted",
31144
- Aborted: "aborted",
31145
- Failed: "failed"
31146
- };
30115
+ var profileStorage = getProfileStorage();
31147
30116
 
31148
- // ../common/src/polling/poll-failure-mapping.ts
31149
- var REASON_BY_OUTCOME = {
31150
- [PollOutcome.Timeout]: "poll_timeout",
31151
- [PollOutcome.Failed]: "poll_failed",
31152
- [PollOutcome.Interrupted]: "poll_failed",
31153
- [PollOutcome.Aborted]: "poll_aborted"
31154
- };
31155
- // ../common/src/polling/terminal-statuses.ts
31156
- var TERMINAL_STATUSES = new Set([
31157
- "completed",
31158
- "successful",
31159
- "faulted",
31160
- "failed",
31161
- "cancelled",
31162
- "canceled",
31163
- "stopped",
31164
- "finished"
31165
- ]);
31166
- var FAILURE_STATUSES = new Set([
31167
- "faulted",
31168
- "failed",
31169
- "cancelled",
31170
- "canceled",
31171
- "stopped"
31172
- ]);
31173
- // ../common/src/screen-logger.ts
31174
- var ScreenLogger;
31175
- ((ScreenLogger) => {
31176
- function progress(message) {
31177
- getOutputSink().writeErr(`${message}
31178
- `);
31179
- }
31180
- ScreenLogger.progress = progress;
31181
- })(ScreenLogger ||= {});
31182
- // ../common/src/sdk-user-agent.ts
31183
- var USER_AGENT_HEADER = "User-Agent";
31184
- var sdkUserAgentHostToken = singleton("SdkUserAgentHostToken");
31185
- function userAgentPatchKey(userAgent) {
31186
- return Symbol.for(`@uipath/common/sdk-user-agent/${userAgent}`);
31187
- }
31188
- function splitUserAgentTokens(value) {
31189
- return value?.trim().split(/\s+/).filter(Boolean) ?? [];
31190
- }
31191
- function appendUserAgentToken(value, userAgent) {
31192
- const tokens = splitUserAgentTokens(value);
31193
- const seen = new Set(tokens);
31194
- for (const token of splitUserAgentTokens(userAgent)) {
31195
- if (!seen.has(token)) {
31196
- tokens.push(token);
31197
- seen.add(token);
31198
- }
31199
- }
31200
- return tokens.join(" ");
31201
- }
31202
- function getEffectiveUserAgent(userAgent) {
31203
- return appendUserAgentToken(sdkUserAgentHostToken.get(), userAgent);
31204
- }
31205
- function isHeadersLike(headers) {
31206
- return typeof headers === "object" && headers !== null && "get" in headers && typeof headers.get === "function" && "set" in headers && typeof headers.set === "function";
31207
- }
31208
- function getSdkUserAgentToken(pkg) {
31209
- const packageName = pkg.name.replace(/^@uipath\//, "");
31210
- return getEffectiveUserAgent(`${packageName}/${pkg.version}`);
31211
- }
31212
- function addSdkUserAgentHeader(headers, userAgent) {
31213
- const result = { ...headers ?? {} };
31214
- const effectiveUserAgent = getEffectiveUserAgent(userAgent);
31215
- const headerName = Object.keys(result).find((key) => key.toLowerCase() === USER_AGENT_HEADER.toLowerCase());
31216
- if (headerName) {
31217
- result[headerName] = appendUserAgentToken(result[headerName], effectiveUserAgent);
31218
- } else {
31219
- result[USER_AGENT_HEADER] = effectiveUserAgent;
31220
- }
31221
- return result;
31222
- }
31223
- function withSdkUserAgentHeader(headers, userAgent) {
31224
- const effectiveUserAgent = getEffectiveUserAgent(userAgent);
31225
- if (isHeadersLike(headers)) {
31226
- headers.set(USER_AGENT_HEADER, appendUserAgentToken(headers.get(USER_AGENT_HEADER), effectiveUserAgent));
31227
- return headers;
31228
- }
31229
- if (Array.isArray(headers)) {
31230
- const result = headers.map((entry) => {
31231
- const [key, value] = entry;
31232
- return [key, value];
31233
- });
31234
- const headerIndex = result.findIndex(([key]) => key.toLowerCase() === USER_AGENT_HEADER.toLowerCase());
31235
- if (headerIndex >= 0) {
31236
- const [key, value] = result[headerIndex];
31237
- result[headerIndex] = [
31238
- key,
31239
- appendUserAgentToken(value, effectiveUserAgent)
31240
- ];
31241
- } else {
31242
- result.push([USER_AGENT_HEADER, effectiveUserAgent]);
31243
- }
31244
- return result;
30117
+ class AuthProfileValidationError extends Error {
30118
+ constructor(message) {
30119
+ super(message);
30120
+ this.name = "AuthProfileValidationError";
31245
30121
  }
31246
- return addSdkUserAgentHeader(typeof headers === "object" && headers !== null ? { ...headers } : {}, effectiveUserAgent);
31247
- }
31248
- function withUserAgentInitOverride(initOverrides, userAgent) {
31249
- return async (requestContext) => {
31250
- const initWithUserAgent = {
31251
- ...requestContext.init,
31252
- headers: withSdkUserAgentHeader(requestContext.init.headers, userAgent)
31253
- };
31254
- const override = typeof initOverrides === "function" ? await initOverrides({
31255
- ...requestContext,
31256
- init: initWithUserAgent
31257
- }) : initOverrides;
31258
- return {
31259
- ...override ?? {},
31260
- headers: withSdkUserAgentHeader(override?.headers ?? initWithUserAgent.headers, userAgent)
31261
- };
31262
- };
31263
30122
  }
31264
- function installSdkUserAgentHeader(BaseApiClass, userAgent) {
31265
- const prototype = BaseApiClass.prototype;
31266
- const patchKey = userAgentPatchKey(userAgent);
31267
- if (prototype[patchKey]) {
30123
+ function normalizeAuthProfileName(profile) {
30124
+ if (profile === undefined || profile === DEFAULT_AUTH_PROFILE) {
31268
30125
  return;
31269
30126
  }
31270
- if (typeof prototype.request !== "function") {
31271
- throw new Error("Generated BaseAPI request function not found.");
30127
+ if (profile.length === 0 || profile === "." || profile === ".." || !PROFILE_NAME_RE.test(profile)) {
30128
+ throw new AuthProfileValidationError(`Invalid profile name "${profile}". Profile names may contain only letters, numbers, '.', '_', and '-'.`);
31272
30129
  }
31273
- const originalRequest = prototype.request;
31274
- prototype.request = function requestWithUserAgent(context, initOverrides) {
31275
- return originalRequest.call(this, context, withUserAgentInitOverride(initOverrides, userAgent));
31276
- };
31277
- Object.defineProperty(prototype, patchKey, {
31278
- value: true
31279
- });
31280
- }
31281
- // ../common/src/tool-provider.ts
31282
- var factorySlot = singleton("PackagerFactoryProvider");
31283
- // src/services/resource-refresh-service.ts
31284
- init_src();
31285
-
31286
- // ../auth/src/config.ts
31287
- init_constants();
31288
- var DEFAULT_CLIENT_ID = "36dea5b8-e8bb-423d-8e7b-c808df8f1c00";
31289
- var AUTH_FILE_CONFIG_KEY = Symbol.for("@uipath/auth/AuthFileConfig");
31290
- var globalSlot = globalThis;
31291
- var getAuthFileConfig = () => globalSlot[AUTH_FILE_CONFIG_KEY] ?? {};
31292
-
31293
- class InvalidBaseUrlError extends Error {
31294
- url;
31295
- reason;
31296
- constructor(url, reason) {
31297
- super(`Invalid base URL: "${url}"
31298
- ` + `Reason: ${reason}
31299
-
31300
- ` + `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>).
31301
- ` + `You can specify the URL via:
31302
- ` + ` • --authority flag
31303
- ` + ` • UIPATH_URL environment variable
31304
- ` + ` • auth.authority in config file`);
31305
- this.url = url;
31306
- this.reason = reason;
31307
- this.name = "InvalidBaseUrlError";
31308
- }
31309
- }
31310
- var DEFAULT_SCOPES = ["openid", "profile", "offline_access"];
31311
- var normalizeAndValidateBaseUrl = (rawUrl) => {
31312
- let baseUrl = rawUrl;
31313
- if (baseUrl.endsWith("/identity_/")) {
31314
- baseUrl = baseUrl.slice(0, -11);
31315
- } else if (baseUrl.endsWith("/identity_")) {
31316
- baseUrl = baseUrl.slice(0, -10);
31317
- }
31318
- while (baseUrl.endsWith("/")) {
31319
- baseUrl = baseUrl.slice(0, -1);
31320
- }
31321
- const resolvedBaseUrl = baseUrl;
31322
- const [urlError, url] = catchError2(() => new URL(resolvedBaseUrl));
31323
- if (urlError) {
31324
- throw new InvalidBaseUrlError(baseUrl, `Malformed URL. ${urlError instanceof Error ? urlError.message : "Unknown error"}`);
31325
- }
31326
- if (url.protocol !== "https:") {
31327
- throw new InvalidBaseUrlError(baseUrl, `Authority must use https:// scheme, got ${url.protocol}//. OIDC token exchange requires TLS end-to-end.`);
31328
- }
31329
- return url.pathname.length > 1 ? url.origin : baseUrl;
31330
- };
31331
- var resolveConfigAsync = async ({
31332
- customAuthority,
31333
- customClientId,
31334
- customClientSecret,
31335
- customScopes
31336
- } = {}) => {
31337
- const fileAuth = getAuthFileConfig();
31338
- let baseUrl = customAuthority;
31339
- if (!baseUrl) {
31340
- baseUrl = process.env.UIPATH_URL;
31341
- }
31342
- if (!baseUrl && fileAuth.authority) {
31343
- baseUrl = fileAuth.authority;
31344
- }
31345
- if (!baseUrl) {
31346
- baseUrl = DEFAULT_BASE_URL;
31347
- }
31348
- baseUrl = normalizeAndValidateBaseUrl(baseUrl);
31349
- let clientId = customClientId;
31350
- if (!clientId && fileAuth.clientId) {
31351
- clientId = fileAuth.clientId;
31352
- }
31353
- if (!clientId) {
31354
- clientId = DEFAULT_CLIENT_ID;
30130
+ return profile;
30131
+ }
30132
+ function getActiveAuthProfile() {
30133
+ const scopedState = profileStorage.getStore();
30134
+ if (scopedState !== undefined) {
30135
+ return scopedState.profile;
31355
30136
  }
31356
- let clientSecret = customClientSecret;
31357
- if (!clientSecret && fileAuth.clientSecret) {
31358
- clientSecret = fileAuth.clientSecret;
30137
+ return globalSlot2[ACTIVE_AUTH_PROFILE_KEY]?.profile;
30138
+ }
30139
+ function resolveAuthProfileFilePath(profile) {
30140
+ const normalized = normalizeAuthProfileName(profile);
30141
+ if (normalized === undefined) {
30142
+ throw new AuthProfileValidationError(`"${DEFAULT_AUTH_PROFILE}" is the built-in profile and does not have a profile file path.`);
31359
30143
  }
31360
- const isExternalAppAuth = clientId !== DEFAULT_CLIENT_ID && Boolean(clientSecret);
31361
- const scopes = customScopes && customScopes.length > 0 ? customScopes : fileAuth.scopes && fileAuth.scopes.length > 0 ? fileAuth.scopes : isExternalAppAuth ? [] : DEFAULT_SCOPES;
31362
- return {
31363
- clientId,
31364
- clientSecret,
31365
- scopes,
31366
- baseUrl,
31367
- authorizationEndpoint: `${baseUrl}/identity_/connect/authorize`,
31368
- tokenEndpoint: `${baseUrl}/identity_/connect/token`
31369
- };
31370
- };
31371
-
31372
- // ../auth/src/index.ts
31373
- init_constants();
31374
- // ../auth/src/loginStatus.ts
31375
- init_src();
30144
+ const fs7 = getFileSystem();
30145
+ return fs7.path.join(fs7.env.homedir(), UIPATH_HOME_DIR, PROFILE_DIR, normalized, AUTH_FILENAME);
30146
+ }
30147
+ function getActiveAuthProfileFilePath() {
30148
+ const profile = getActiveAuthProfile();
30149
+ return profile ? resolveAuthProfileFilePath(profile) : undefined;
30150
+ }
31376
30151
  // ../auth/src/utils/jwt.ts
31377
30152
  class InvalidIssuerError extends Error {
31378
30153
  expected;
@@ -31501,23 +30276,74 @@ var readAuthFromEnv = () => {
31501
30276
  organizationId,
31502
30277
  tenantName,
31503
30278
  tenantId,
31504
- expiration
30279
+ expiration,
30280
+ source: "env" /* Env */
31505
30281
  };
31506
30282
  };
31507
30283
 
30284
+ // ../auth/src/refreshCircuitBreaker.ts
30285
+ init_src();
30286
+ var BREAKER_SUFFIX = ".refresh-state";
30287
+ var BACKOFF_BASE_MS = 60000;
30288
+ var BACKOFF_CAP_MS = 60 * 60 * 1000;
30289
+ var SURFACE_WINDOW_MS = 60 * 60 * 1000;
30290
+ async function refreshTokenFingerprint(refreshToken) {
30291
+ const bytes = new TextEncoder().encode(refreshToken);
30292
+ if (globalThis.crypto?.subtle) {
30293
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", bytes);
30294
+ return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("").slice(0, 16);
30295
+ }
30296
+ const { createHash } = await import("node:crypto");
30297
+ return createHash("sha256").update(refreshToken).digest("hex").slice(0, 16);
30298
+ }
30299
+ function breakerPathFor(authPath) {
30300
+ return `${authPath}${BREAKER_SUFFIX}`;
30301
+ }
30302
+ async function loadRefreshBreaker(authPath) {
30303
+ const fs7 = getFileSystem();
30304
+ try {
30305
+ const content = await fs7.readFile(breakerPathFor(authPath), "utf-8");
30306
+ if (!content)
30307
+ return {};
30308
+ const parsed = JSON.parse(content);
30309
+ return parsed && typeof parsed === "object" ? parsed : {};
30310
+ } catch {
30311
+ return {};
30312
+ }
30313
+ }
30314
+ async function saveRefreshBreaker(authPath, state) {
30315
+ try {
30316
+ const fs7 = getFileSystem();
30317
+ const path3 = breakerPathFor(authPath);
30318
+ await fs7.mkdir(fs7.path.dirname(path3));
30319
+ const tempPath = `${path3}.tmp`;
30320
+ await fs7.writeFile(tempPath, JSON.stringify(state));
30321
+ await fs7.rename(tempPath, path3);
30322
+ } catch {}
30323
+ }
30324
+ async function clearRefreshBreaker(authPath) {
30325
+ const fs7 = getFileSystem();
30326
+ const path3 = breakerPathFor(authPath);
30327
+ try {
30328
+ if (await fs7.exists(path3)) {
30329
+ await fs7.rm(path3);
30330
+ }
30331
+ } catch {}
30332
+ }
30333
+ function nextBackoffMs(attempts) {
30334
+ const shift = Math.max(0, attempts - 1);
30335
+ return Math.min(BACKOFF_BASE_MS * 2 ** shift, BACKOFF_CAP_MS);
30336
+ }
30337
+ function shouldSurface(state, nowMs) {
30338
+ if (state.lastSurfacedAtMs === undefined)
30339
+ return true;
30340
+ return nowMs - state.lastSurfacedAtMs >= SURFACE_WINDOW_MS;
30341
+ }
30342
+
31508
30343
  // ../auth/src/robotClientFallback.ts
31509
30344
  init_src();
31510
30345
  var DEFAULT_TIMEOUT_MS = 1000;
31511
30346
  var CLOSE_TIMEOUT_MS = 500;
31512
- var NOTICE_SENTINEL = Symbol.for("@uipath/auth/robotFallbackNoticePrinted");
31513
- var printNoticeOnce = () => {
31514
- const slot = globalThis;
31515
- if (slot[NOTICE_SENTINEL])
31516
- return;
31517
- slot[NOTICE_SENTINEL] = true;
31518
- catchError2(() => process.stderr.write(`Using UiPath Robot credentials. Run 'uip login' for a dedicated session.
31519
- `));
31520
- };
31521
30347
  var ROBOT_USER_SERVICES_PIPE = "UiPathUserServices";
31522
30348
  var ROBOT_USER_SERVICES_ALTERNATE_PIPE = `${ROBOT_USER_SERVICES_PIPE}Alternate`;
31523
30349
  var PIPE_NAME_MAX_LENGTH = 103;
@@ -31633,7 +30459,6 @@ var tryRobotClientFallback = async (options = {}) => {
31633
30459
  issuerFromToken = issClaim;
31634
30460
  }
31635
30461
  }
31636
- printNoticeOnce();
31637
30462
  return {
31638
30463
  accessToken,
31639
30464
  baseUrl: parsedUrl.baseUrl,
@@ -31858,18 +30683,327 @@ var saveEnvFileAsync = async ({
31858
30683
  };
31859
30684
 
31860
30685
  // ../auth/src/loginStatus.ts
31861
- function normalizeTokenRefreshFailure() {
31862
- return "stored refresh token is invalid or expired";
30686
+ var getLoginStatusAsync = async (options = {}) => {
30687
+ return getLoginStatusWithDeps(options);
30688
+ };
30689
+ var getLoginStatusWithDeps = async (options = {}, deps = {}) => {
30690
+ const {
30691
+ resolveEnvFilePath = resolveEnvFilePathAsync,
30692
+ loadEnvFile = loadEnvFileAsync,
30693
+ saveEnvFile = saveEnvFileAsync,
30694
+ getFs = getFileSystem,
30695
+ refreshToken: refreshTokenFn = refreshAccessToken,
30696
+ resolveConfig = resolveConfigAsync,
30697
+ robotFallback = tryRobotClientFallback,
30698
+ loadBreaker = loadRefreshBreaker,
30699
+ saveBreaker = saveRefreshBreaker,
30700
+ clearBreaker = clearRefreshBreaker
30701
+ } = deps;
30702
+ if (isRobotAuthEnforced()) {
30703
+ return resolveRobotEnforcedStatus(robotFallback);
30704
+ }
30705
+ if (isEnvAuthEnabled()) {
30706
+ return readAuthFromEnv();
30707
+ }
30708
+ const activeProfile = getActiveAuthProfile();
30709
+ const activeProfileFilePath = getActiveAuthProfileFilePath();
30710
+ const usingActiveProfile = activeProfile !== undefined && (options.envFilePath === undefined || options.envFilePath === activeProfileFilePath);
30711
+ const envFilePath = options.envFilePath ?? activeProfileFilePath ?? DEFAULT_ENV_FILENAME;
30712
+ const { ensureTokenValidityMinutes } = options;
30713
+ const { absolutePath } = await resolveEnvFilePath(envFilePath);
30714
+ if (absolutePath === undefined) {
30715
+ if (usingActiveProfile) {
30716
+ return {
30717
+ loginStatus: "Not logged in",
30718
+ hint: `No credentials found for profile "${activeProfile}". Run 'uip login --profile ${activeProfile}' to authenticate this profile.`
30719
+ };
30720
+ }
30721
+ return resolveBorrowedRobotStatus(robotFallback);
30722
+ }
30723
+ const loaded = await loadFileCredentials(loadEnvFile, absolutePath);
30724
+ if ("status" in loaded) {
30725
+ return loaded.status;
30726
+ }
30727
+ const { credentials } = loaded;
30728
+ const globalHint = () => usingActiveProfile ? Promise.resolve(undefined) : getGlobalCredsHint(getFs, loadEnvFile, absolutePath, envFilePath);
30729
+ const expiration = getTokenExpiration(credentials.UIPATH_ACCESS_TOKEN);
30730
+ const outerThreshold = computeExpirationThreshold(ensureTokenValidityMinutes);
30731
+ let tokens = {
30732
+ accessToken: credentials.UIPATH_ACCESS_TOKEN,
30733
+ refreshToken: credentials.UIPATH_REFRESH_TOKEN,
30734
+ expiration,
30735
+ lockReleaseFailed: false
30736
+ };
30737
+ const refreshToken = credentials.UIPATH_REFRESH_TOKEN;
30738
+ if (expiration && expiration <= outerThreshold && refreshToken) {
30739
+ const refreshed = await attemptRefresh({
30740
+ absolutePath,
30741
+ credentials,
30742
+ accessToken: credentials.UIPATH_ACCESS_TOKEN,
30743
+ refreshToken,
30744
+ expiration,
30745
+ ensureTokenValidityMinutes,
30746
+ getFs,
30747
+ loadEnvFile,
30748
+ saveEnvFile,
30749
+ refreshFn: refreshTokenFn,
30750
+ resolveConfig,
30751
+ loadBreaker,
30752
+ saveBreaker,
30753
+ clearBreaker,
30754
+ globalHint
30755
+ });
30756
+ if (refreshed.kind === "terminal") {
30757
+ return refreshed.status;
30758
+ }
30759
+ tokens = refreshed.tokens;
30760
+ }
30761
+ return buildFileStatus(tokens, credentials, globalHint);
30762
+ };
30763
+ async function resolveRobotEnforcedStatus(robotFallback) {
30764
+ if (isEnvAuthEnabled()) {
30765
+ throw new EnvAuthConfigError(`${ENV_AUTH_ENABLE_VAR}=true and ${ENFORCE_ROBOT_AUTH_VAR}=true ` + `are mutually exclusive. Unset one of them and re-run.`);
30766
+ }
30767
+ const robotCreds = await robotFallback({ force: true });
30768
+ if (!robotCreds) {
30769
+ return {
30770
+ loginStatus: "Not logged in",
30771
+ 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.`
30772
+ };
30773
+ }
30774
+ return buildRobotStatus(robotCreds);
31863
30775
  }
31864
- function normalizeTokenRefreshUnavailableFailure() {
31865
- return "token refresh failed before authentication completed";
30776
+ async function resolveBorrowedRobotStatus(robotFallback) {
30777
+ const robotCreds = await robotFallback();
30778
+ return robotCreds ? buildRobotStatus(robotCreds) : { loginStatus: "Not logged in" };
31866
30779
  }
31867
- function errorMessage(error) {
31868
- return error instanceof Error ? error.message : String(error);
30780
+ async function loadFileCredentials(loadEnvFile, absolutePath) {
30781
+ let credentials;
30782
+ try {
30783
+ credentials = await loadEnvFile({ envPath: absolutePath });
30784
+ } catch (error) {
30785
+ if (isFileNotFoundError(error)) {
30786
+ return { status: { loginStatus: "Not logged in" } };
30787
+ }
30788
+ throw error;
30789
+ }
30790
+ if (!credentials.UIPATH_ACCESS_TOKEN) {
30791
+ return { status: { loginStatus: "Not logged in" } };
30792
+ }
30793
+ return { credentials };
30794
+ }
30795
+ async function getGlobalCredsHint(getFs, loadEnvFile, absolutePath, envFilePath) {
30796
+ const fs7 = getFs();
30797
+ const globalPath = fs7.path.join(fs7.env.homedir(), envFilePath);
30798
+ if (absolutePath === globalPath)
30799
+ return;
30800
+ if (!await fs7.exists(globalPath))
30801
+ return;
30802
+ try {
30803
+ const globalCreds = await loadEnvFile({ envPath: globalPath });
30804
+ if (!globalCreds.UIPATH_ACCESS_TOKEN)
30805
+ return;
30806
+ const globalExp = getTokenExpiration(globalCreds.UIPATH_ACCESS_TOKEN);
30807
+ if (globalExp && globalExp <= new Date)
30808
+ return;
30809
+ 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.`;
30810
+ } catch {
30811
+ return;
30812
+ }
31869
30813
  }
31870
30814
  function computeExpirationThreshold(ensureTokenValidityMinutes) {
31871
30815
  return new Date(Date.now() + (ensureTokenValidityMinutes ?? 0) * 60 * 1000);
31872
30816
  }
30817
+ async function attemptRefresh(ctx) {
30818
+ const shortCircuit = await circuitBreakerShortCircuit(ctx);
30819
+ if (shortCircuit) {
30820
+ return { kind: "terminal", status: shortCircuit };
30821
+ }
30822
+ let release;
30823
+ try {
30824
+ release = await ctx.getFs().acquireLock(ctx.absolutePath);
30825
+ } catch (error) {
30826
+ return {
30827
+ kind: "terminal",
30828
+ status: await lockAcquireFailureStatus(ctx, error)
30829
+ };
30830
+ }
30831
+ let lockedFailure;
30832
+ let lockReleaseFailed = false;
30833
+ let success;
30834
+ try {
30835
+ const outcome = await runRefreshLocked({
30836
+ absolutePath: ctx.absolutePath,
30837
+ refreshToken: ctx.refreshToken,
30838
+ customAuthority: ctx.credentials.UIPATH_URL,
30839
+ ensureTokenValidityMinutes: ctx.ensureTokenValidityMinutes,
30840
+ loadEnvFile: ctx.loadEnvFile,
30841
+ saveEnvFile: ctx.saveEnvFile,
30842
+ refreshFn: ctx.refreshFn,
30843
+ resolveConfig: ctx.resolveConfig,
30844
+ loadBreaker: ctx.loadBreaker,
30845
+ saveBreaker: ctx.saveBreaker,
30846
+ clearBreaker: ctx.clearBreaker
30847
+ });
30848
+ if (outcome.kind === "fail") {
30849
+ lockedFailure = outcome.status;
30850
+ } else {
30851
+ success = outcome;
30852
+ }
30853
+ } finally {
30854
+ try {
30855
+ await release();
30856
+ } catch {
30857
+ lockReleaseFailed = true;
30858
+ }
30859
+ }
30860
+ if (lockedFailure) {
30861
+ const globalHint = await ctx.globalHint();
30862
+ const base = globalHint ? { ...lockedFailure, loginStatus: "Expired", hint: globalHint } : lockedFailure;
30863
+ return {
30864
+ kind: "terminal",
30865
+ status: lockReleaseFailed ? { ...base, lockReleaseFailed: true } : base
30866
+ };
30867
+ }
30868
+ return {
30869
+ kind: "refreshed",
30870
+ tokens: {
30871
+ accessToken: success?.accessToken,
30872
+ refreshToken: success?.refreshToken,
30873
+ expiration: success?.expiration,
30874
+ tokenRefresh: success?.tokenRefresh,
30875
+ persistenceWarning: success?.persistenceWarning,
30876
+ lockReleaseFailed
30877
+ }
30878
+ };
30879
+ }
30880
+ async function buildFileStatus(tokens, credentials, globalHint) {
30881
+ const result = {
30882
+ loginStatus: tokens.expiration && tokens.expiration <= new Date ? "Expired" : "Logged in",
30883
+ accessToken: tokens.accessToken,
30884
+ refreshToken: tokens.refreshToken,
30885
+ baseUrl: credentials.UIPATH_URL,
30886
+ organizationName: credentials.UIPATH_ORGANIZATION_NAME,
30887
+ organizationId: credentials.UIPATH_ORGANIZATION_ID,
30888
+ tenantName: credentials.UIPATH_TENANT_NAME,
30889
+ tenantId: credentials.UIPATH_TENANT_ID,
30890
+ expiration: tokens.expiration,
30891
+ source: "file" /* File */,
30892
+ ...tokens.persistenceWarning ? { hint: tokens.persistenceWarning, persistenceFailed: true } : {},
30893
+ ...tokens.lockReleaseFailed ? { lockReleaseFailed: true } : {},
30894
+ ...tokens.tokenRefresh ? { tokenRefresh: tokens.tokenRefresh } : {}
30895
+ };
30896
+ if (result.loginStatus === "Expired") {
30897
+ const hint = await globalHint();
30898
+ if (hint) {
30899
+ result.hint = hint;
30900
+ }
30901
+ }
30902
+ return result;
30903
+ }
30904
+ function buildRobotStatus(robotCreds) {
30905
+ return {
30906
+ loginStatus: "Logged in",
30907
+ accessToken: robotCreds.accessToken,
30908
+ baseUrl: robotCreds.baseUrl,
30909
+ organizationName: robotCreds.organizationName,
30910
+ organizationId: robotCreds.organizationId,
30911
+ tenantName: robotCreds.tenantName,
30912
+ tenantId: robotCreds.tenantId,
30913
+ issuer: robotCreds.issuer,
30914
+ expiration: getTokenExpiration(robotCreds.accessToken),
30915
+ source: "robot" /* Robot */
30916
+ };
30917
+ }
30918
+ var isFileNotFoundError = (error) => {
30919
+ if (!(error instanceof Object))
30920
+ return false;
30921
+ return error.code === "ENOENT";
30922
+ };
30923
+ async function circuitBreakerShortCircuit(ctx) {
30924
+ const {
30925
+ absolutePath,
30926
+ refreshToken,
30927
+ accessToken,
30928
+ credentials,
30929
+ expiration,
30930
+ loadBreaker,
30931
+ saveBreaker,
30932
+ clearBreaker
30933
+ } = ctx;
30934
+ const fingerprint = await refreshTokenFingerprint(refreshToken);
30935
+ const breaker = await loadBreaker(absolutePath).catch(() => ({}));
30936
+ if (breaker.deadTokenFp && breaker.deadTokenFp !== fingerprint) {
30937
+ await clearBreaker(absolutePath);
30938
+ breaker.deadTokenFp = undefined;
30939
+ }
30940
+ const nowMs = Date.now();
30941
+ const tokenIsDead = breaker.deadTokenFp === fingerprint;
30942
+ const inBackoff = breaker.backoffUntilMs !== undefined && nowMs < breaker.backoffUntilMs;
30943
+ if (!tokenIsDead && !inBackoff)
30944
+ return;
30945
+ const globalHint = await ctx.globalHint();
30946
+ const suppressed = !shouldSurface(breaker, nowMs);
30947
+ if (!suppressed) {
30948
+ await saveBreaker(absolutePath, {
30949
+ ...breaker,
30950
+ lastSurfacedAtMs: nowMs
30951
+ });
30952
+ }
30953
+ 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>.";
30954
+ const backoffHint = "Token refresh is temporarily backed off after a recent network error and will retry automatically once the backoff window elapses.";
30955
+ return {
30956
+ loginStatus: globalHint ? "Expired" : "Refresh Failed",
30957
+ ...globalHint ? {
30958
+ accessToken,
30959
+ refreshToken,
30960
+ baseUrl: credentials.UIPATH_URL,
30961
+ organizationName: credentials.UIPATH_ORGANIZATION_NAME,
30962
+ organizationId: credentials.UIPATH_ORGANIZATION_ID,
30963
+ tenantName: credentials.UIPATH_TENANT_NAME,
30964
+ tenantId: credentials.UIPATH_TENANT_ID,
30965
+ expiration,
30966
+ source: "file" /* File */
30967
+ } : {},
30968
+ hint: globalHint ?? (tokenIsDead ? deadHint : backoffHint),
30969
+ refreshCircuitOpen: true,
30970
+ refreshTelemetrySuppressed: suppressed,
30971
+ tokenRefresh: { attempted: false, success: false }
30972
+ };
30973
+ }
30974
+ async function lockAcquireFailureStatus(ctx, error) {
30975
+ const msg = errorMessage(error);
30976
+ const globalHint = await ctx.globalHint();
30977
+ if (globalHint) {
30978
+ return {
30979
+ loginStatus: "Expired",
30980
+ accessToken: ctx.accessToken,
30981
+ refreshToken: ctx.refreshToken,
30982
+ baseUrl: ctx.credentials.UIPATH_URL,
30983
+ organizationName: ctx.credentials.UIPATH_ORGANIZATION_NAME,
30984
+ organizationId: ctx.credentials.UIPATH_ORGANIZATION_ID,
30985
+ tenantName: ctx.credentials.UIPATH_TENANT_NAME,
30986
+ tenantId: ctx.credentials.UIPATH_TENANT_ID,
30987
+ expiration: ctx.expiration,
30988
+ source: "file" /* File */,
30989
+ hint: globalHint,
30990
+ tokenRefresh: {
30991
+ attempted: false,
30992
+ success: false,
30993
+ errorMessage: `lock acquisition failed: ${msg}`
30994
+ }
30995
+ };
30996
+ }
30997
+ return {
30998
+ loginStatus: "Refresh Failed",
30999
+ 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.",
31000
+ tokenRefresh: {
31001
+ attempted: false,
31002
+ success: false,
31003
+ errorMessage: `lock acquisition failed: ${msg}`
31004
+ }
31005
+ };
31006
+ }
31873
31007
  async function runRefreshLocked(inputs) {
31874
31008
  const {
31875
31009
  absolutePath,
@@ -31879,7 +31013,10 @@ async function runRefreshLocked(inputs) {
31879
31013
  loadEnvFile,
31880
31014
  saveEnvFile,
31881
31015
  refreshFn,
31882
- resolveConfig
31016
+ resolveConfig,
31017
+ loadBreaker,
31018
+ saveBreaker,
31019
+ clearBreaker
31883
31020
  } = inputs;
31884
31021
  const expirationThreshold = computeExpirationThreshold(ensureTokenValidityMinutes);
31885
31022
  let fresh;
@@ -31902,6 +31039,7 @@ async function runRefreshLocked(inputs) {
31902
31039
  const freshAccess = fresh.UIPATH_ACCESS_TOKEN;
31903
31040
  const freshExp = freshAccess ? getTokenExpiration(freshAccess) : undefined;
31904
31041
  if (freshAccess && freshExp && freshExp > expirationThreshold) {
31042
+ await clearBreaker(absolutePath);
31905
31043
  return {
31906
31044
  kind: "ok",
31907
31045
  accessToken: freshAccess,
@@ -31925,8 +31063,21 @@ async function runRefreshLocked(inputs) {
31925
31063
  refreshedRefresh = refreshed.refreshToken;
31926
31064
  } catch (error) {
31927
31065
  const isOAuthFailure = isTokenRefreshOAuthFailure(error);
31928
- 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.";
31066
+ 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.";
31929
31067
  const message = isOAuthFailure ? normalizeTokenRefreshFailure() : normalizeTokenRefreshUnavailableFailure();
31068
+ const fp = await refreshTokenFingerprint(tokenForIdP);
31069
+ if (isOAuthFailure) {
31070
+ await saveBreaker(absolutePath, { deadTokenFp: fp });
31071
+ } else {
31072
+ const prior = await loadBreaker(absolutePath).catch(() => ({}));
31073
+ const attempts = (prior.attempts ?? 0) + 1;
31074
+ await saveBreaker(absolutePath, {
31075
+ ...prior,
31076
+ deadTokenFp: undefined,
31077
+ attempts,
31078
+ backoffUntilMs: Date.now() + nextBackoffMs(attempts)
31079
+ });
31080
+ }
31930
31081
  return {
31931
31082
  kind: "fail",
31932
31083
  status: {
@@ -31955,6 +31106,7 @@ async function runRefreshLocked(inputs) {
31955
31106
  }
31956
31107
  };
31957
31108
  }
31109
+ await clearBreaker(absolutePath);
31958
31110
  try {
31959
31111
  await saveEnvFile({
31960
31112
  envPath: absolutePath,
@@ -31977,222 +31129,25 @@ async function runRefreshLocked(inputs) {
31977
31129
  kind: "ok",
31978
31130
  accessToken: refreshedAccess,
31979
31131
  refreshToken: refreshedRefresh,
31980
- expiration: refreshedExp,
31981
- persistenceWarning: `Access token refreshed in memory but could not be written to ${absolutePath}: ${msg}. The next CLI invocation will fail until the file can be updated — run 'uip login' to re-authenticate.`,
31982
- tokenRefresh: {
31983
- attempted: true,
31984
- success: true,
31985
- errorMessage: `persistence failed: ${msg}`
31986
- }
31987
- };
31988
- }
31989
- }
31990
- var getLoginStatusWithDeps = async (options = {}, deps = {}) => {
31991
- const {
31992
- resolveEnvFilePath = resolveEnvFilePathAsync,
31993
- loadEnvFile = loadEnvFileAsync,
31994
- saveEnvFile = saveEnvFileAsync,
31995
- getFs = getFileSystem,
31996
- refreshToken: refreshTokenFn = refreshAccessToken,
31997
- resolveConfig = resolveConfigAsync,
31998
- robotFallback = tryRobotClientFallback
31999
- } = deps;
32000
- if (isRobotAuthEnforced()) {
32001
- if (isEnvAuthEnabled()) {
32002
- throw new EnvAuthConfigError(`${ENV_AUTH_ENABLE_VAR}=true and ${ENFORCE_ROBOT_AUTH_VAR}=true ` + `are mutually exclusive. Unset one of them and re-run.`);
32003
- }
32004
- const robotCreds = await robotFallback({ force: true });
32005
- if (!robotCreds) {
32006
- return {
32007
- loginStatus: "Not logged in",
32008
- 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.`
32009
- };
32010
- }
32011
- const expiration2 = getTokenExpiration(robotCreds.accessToken);
32012
- return {
32013
- loginStatus: "Logged in",
32014
- accessToken: robotCreds.accessToken,
32015
- baseUrl: robotCreds.baseUrl,
32016
- organizationName: robotCreds.organizationName,
32017
- organizationId: robotCreds.organizationId,
32018
- tenantName: robotCreds.tenantName,
32019
- tenantId: robotCreds.tenantId,
32020
- issuer: robotCreds.issuer,
32021
- expiration: expiration2,
32022
- source: "robot" /* Robot */
32023
- };
32024
- }
32025
- if (isEnvAuthEnabled()) {
32026
- return readAuthFromEnv();
32027
- }
32028
- const { envFilePath = DEFAULT_ENV_FILENAME, ensureTokenValidityMinutes } = options;
32029
- const { absolutePath } = await resolveEnvFilePath(envFilePath);
32030
- if (absolutePath === undefined) {
32031
- const robotCreds = await robotFallback();
32032
- if (robotCreds) {
32033
- const expiration2 = getTokenExpiration(robotCreds.accessToken);
32034
- const status = {
32035
- loginStatus: "Logged in",
32036
- accessToken: robotCreds.accessToken,
32037
- baseUrl: robotCreds.baseUrl,
32038
- organizationName: robotCreds.organizationName,
32039
- organizationId: robotCreds.organizationId,
32040
- tenantName: robotCreds.tenantName,
32041
- tenantId: robotCreds.tenantId,
32042
- issuer: robotCreds.issuer,
32043
- expiration: expiration2,
32044
- source: "robot" /* Robot */
32045
- };
32046
- return status;
32047
- }
32048
- return { loginStatus: "Not logged in" };
32049
- }
32050
- let credentials;
32051
- try {
32052
- credentials = await loadEnvFile({ envPath: absolutePath });
32053
- } catch (error) {
32054
- if (isFileNotFoundError(error)) {
32055
- return { loginStatus: "Not logged in" };
32056
- }
32057
- throw error;
32058
- }
32059
- if (!credentials.UIPATH_ACCESS_TOKEN) {
32060
- return { loginStatus: "Not logged in" };
32061
- }
32062
- let accessToken = credentials.UIPATH_ACCESS_TOKEN;
32063
- let refreshToken = credentials.UIPATH_REFRESH_TOKEN;
32064
- let expiration = getTokenExpiration(accessToken);
32065
- let persistenceWarning;
32066
- let lockReleaseFailed = false;
32067
- let tokenRefresh;
32068
- const outerThreshold = computeExpirationThreshold(ensureTokenValidityMinutes);
32069
- const tryGlobalCredsHint = async () => {
32070
- const fs7 = getFs();
32071
- const globalPath = fs7.path.join(fs7.env.homedir(), envFilePath);
32072
- if (absolutePath === globalPath)
32073
- return;
32074
- if (!await fs7.exists(globalPath))
32075
- return;
32076
- try {
32077
- const globalCreds = await loadEnvFile({ envPath: globalPath });
32078
- if (!globalCreds.UIPATH_ACCESS_TOKEN)
32079
- return;
32080
- const globalExp = getTokenExpiration(globalCreds.UIPATH_ACCESS_TOKEN);
32081
- if (globalExp && globalExp <= new Date)
32082
- return;
32083
- 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.`;
32084
- } catch {
32085
- return;
32086
- }
32087
- };
32088
- if (expiration && expiration <= outerThreshold && refreshToken) {
32089
- let release;
32090
- try {
32091
- release = await getFs().acquireLock(absolutePath);
32092
- } catch (error) {
32093
- const msg = errorMessage(error);
32094
- const globalHint = await tryGlobalCredsHint();
32095
- if (globalHint) {
32096
- return {
32097
- loginStatus: "Expired",
32098
- accessToken,
32099
- refreshToken,
32100
- baseUrl: credentials.UIPATH_URL,
32101
- organizationName: credentials.UIPATH_ORGANIZATION_NAME,
32102
- organizationId: credentials.UIPATH_ORGANIZATION_ID,
32103
- tenantName: credentials.UIPATH_TENANT_NAME,
32104
- tenantId: credentials.UIPATH_TENANT_ID,
32105
- expiration,
32106
- source: "file" /* File */,
32107
- hint: globalHint,
32108
- tokenRefresh: {
32109
- attempted: false,
32110
- success: false,
32111
- errorMessage: `lock acquisition failed: ${msg}`
32112
- }
32113
- };
32114
- }
32115
- return {
32116
- loginStatus: "Refresh Failed",
32117
- 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.",
32118
- tokenRefresh: {
32119
- attempted: false,
32120
- success: false,
32121
- errorMessage: `lock acquisition failed: ${msg}`
32122
- }
32123
- };
32124
- }
32125
- let lockedFailure;
32126
- try {
32127
- const outcome = await runRefreshLocked({
32128
- absolutePath,
32129
- refreshToken,
32130
- customAuthority: credentials.UIPATH_URL,
32131
- ensureTokenValidityMinutes,
32132
- loadEnvFile,
32133
- saveEnvFile,
32134
- refreshFn: refreshTokenFn,
32135
- resolveConfig
32136
- });
32137
- if (outcome.kind === "fail") {
32138
- lockedFailure = outcome.status;
32139
- } else {
32140
- accessToken = outcome.accessToken;
32141
- refreshToken = outcome.refreshToken;
32142
- expiration = outcome.expiration;
32143
- tokenRefresh = outcome.tokenRefresh;
32144
- if (outcome.persistenceWarning) {
32145
- persistenceWarning = outcome.persistenceWarning;
32146
- }
32147
- }
32148
- } finally {
32149
- try {
32150
- await release();
32151
- } catch {
32152
- lockReleaseFailed = true;
31132
+ expiration: refreshedExp,
31133
+ persistenceWarning: `Access token refreshed in memory but could not be written to ${absolutePath}: ${msg}. The next CLI invocation will fail until the file can be updated — run 'uip login' to re-authenticate.`,
31134
+ tokenRefresh: {
31135
+ attempted: true,
31136
+ success: true,
31137
+ errorMessage: `persistence failed: ${msg}`
32153
31138
  }
32154
- }
32155
- if (lockedFailure) {
32156
- const globalHint = await tryGlobalCredsHint();
32157
- const base = globalHint ? {
32158
- ...lockedFailure,
32159
- loginStatus: "Expired",
32160
- hint: globalHint
32161
- } : lockedFailure;
32162
- return lockReleaseFailed ? { ...base, lockReleaseFailed: true } : base;
32163
- }
32164
- }
32165
- const result = {
32166
- loginStatus: expiration && expiration <= new Date ? "Expired" : "Logged in",
32167
- accessToken,
32168
- refreshToken,
32169
- baseUrl: credentials.UIPATH_URL,
32170
- organizationName: credentials.UIPATH_ORGANIZATION_NAME,
32171
- organizationId: credentials.UIPATH_ORGANIZATION_ID,
32172
- tenantName: credentials.UIPATH_TENANT_NAME,
32173
- tenantId: credentials.UIPATH_TENANT_ID,
32174
- expiration,
32175
- source: "file" /* File */,
32176
- ...persistenceWarning ? { hint: persistenceWarning, persistenceFailed: true } : {},
32177
- ...lockReleaseFailed ? { lockReleaseFailed: true } : {},
32178
- ...tokenRefresh ? { tokenRefresh } : {}
32179
- };
32180
- if (result.loginStatus === "Expired") {
32181
- const globalHint = await tryGlobalCredsHint();
32182
- if (globalHint) {
32183
- result.hint = globalHint;
32184
- }
31139
+ };
32185
31140
  }
32186
- return result;
32187
- };
32188
- var isFileNotFoundError = (error) => {
32189
- if (!(error instanceof Object))
32190
- return false;
32191
- return error.code === "ENOENT";
32192
- };
32193
- var getLoginStatusAsync = async (options = {}) => {
32194
- return getLoginStatusWithDeps(options);
32195
- };
31141
+ }
31142
+ function normalizeTokenRefreshFailure() {
31143
+ return "stored refresh token is invalid or expired";
31144
+ }
31145
+ function normalizeTokenRefreshUnavailableFailure() {
31146
+ return "token refresh failed before authentication completed";
31147
+ }
31148
+ function errorMessage(error) {
31149
+ return error instanceof Error ? error.message : String(error);
31150
+ }
32196
31151
 
32197
31152
  // ../auth/src/authContext.ts
32198
31153
  var getAuthContext = async (options = {}) => {
@@ -32227,6 +31182,14 @@ var getAuthContext = async (options = {}) => {
32227
31182
  };
32228
31183
  // ../auth/src/interactive.ts
32229
31184
  init_src();
31185
+
31186
+ // ../auth/src/selectTenant.ts
31187
+ var TENANT_SELECTION_REQUIRED_CODE = "TENANT_SELECTION_REQUIRED";
31188
+ var INVALID_TENANT_CODE = "INVALID_TENANT";
31189
+ var TENANT_SELECTION_CODES = new Set([
31190
+ TENANT_SELECTION_REQUIRED_CODE,
31191
+ INVALID_TENANT_CODE
31192
+ ]);
32230
31193
  // ../auth/src/logout.ts
32231
31194
  init_src();
32232
31195
 
@@ -32446,6 +31409,7 @@ var ErrorCodes = {
32446
31409
  MissingFileDependencies: "2022",
32447
31410
  ResourceAttributeMismatch: "2023",
32448
31411
  AppSystemNameConflict: "2024",
31412
+ InvalidResourceFile: "2025",
32449
31413
  ResourceNotFound: "1000",
32450
31414
  ResourceAlreadyExists: "Resources.ResourceAlreadyExists",
32451
31415
  ResourceDependencyNotFound: "Resources.ResourceDependencyNotFound",
@@ -32484,8 +31448,8 @@ class BadRequestException extends Error {
32484
31448
  }
32485
31449
  }
32486
31450
  function formatMessage2(template, params) {
32487
- return template.replace(/{(\d+)}/g, (match, index2) => {
32488
- const paramIndex = parseInt(index2, 10);
31451
+ return template.replace(/{(\d+)}/g, (match, index) => {
31452
+ const paramIndex = parseInt(index, 10);
32489
31453
  if (paramIndex < params.length) {
32490
31454
  const param = params[paramIndex];
32491
31455
  return param != null ? String(param) : "";
@@ -32495,10 +31459,10 @@ function formatMessage2(template, params) {
32495
31459
  }
32496
31460
 
32497
31461
  class NotFoundException extends Error {
32498
- constructor(resourceType, resourceKey, message) {
31462
+ constructor(resourceType, resourceKey, message, errorCode2 = ErrorCodes.ResourceNotFound) {
32499
31463
  super(message ?? `${resourceType} with key '${resourceKey}' was not found`);
32500
31464
  this.name = "NotFoundException";
32501
- this.errorCode = ErrorCodes.ResourceNotFound;
31465
+ this.errorCode = errorCode2;
32502
31466
  this.resourceType = resourceType;
32503
31467
  this.resourceKey = resourceKey;
32504
31468
  if (Error.captureStackTrace)
@@ -33302,11 +32266,12 @@ function addResource(solution, resource) {
33302
32266
  solution.resources.push(resource);
33303
32267
  }
33304
32268
  function addResourceWithUniqueName(solution, resource) {
33305
- const escapedName = escapeRegex(resource.name);
33306
- const sameNameRegex = new RegExp(`^${escapedName}(_\\d+)?$`, "i");
33307
- const matchingResources = solution.resources.filter((r) => sameNameRegex.test(r.name) && r.kind.toLowerCase() === resource.kind.toLowerCase());
33308
32269
  resource.originalName = resource.name;
33309
- if (matchingResources.length > 0) {
32270
+ const exactNameTaken = solution.resources.some((r) => r.name.toLowerCase() === resource.name.toLowerCase() && r.kind.toLowerCase() === resource.kind.toLowerCase());
32271
+ if (exactNameTaken) {
32272
+ const escapedName = escapeRegex(resource.name);
32273
+ const sameNameRegex = new RegExp(`^${escapedName}(_\\d+)?$`, "i");
32274
+ const matchingResources = solution.resources.filter((r) => sameNameRegex.test(r.name) && r.kind.toLowerCase() === resource.kind.toLowerCase());
33310
32275
  const lastResourceNumber = Math.max(...matchingResources.map((x) => getResourceNumber(x.name)));
33311
32276
  resource.name += `_${lastResourceNumber + 1}`;
33312
32277
  if (resource.spec && WellKnownPropertyNames.Name in resource.spec)
@@ -33362,6 +32327,7 @@ class MultiFileSolutionDefinitionProvider {
33362
32327
  pathsByKind.clear();
33363
32328
  const parseErrors = [];
33364
32329
  const missingFiles = [];
32330
+ const invalidFiles = [];
33365
32331
  context.items[SolutionContextKeys.PARSE_ERRORS_ITEM_KEY] = parseErrors;
33366
32332
  if (!context.isReadOnly) {
33367
32333
  hashes = this.getHashes(context);
@@ -33424,7 +32390,7 @@ class MultiFileSolutionDefinitionProvider {
33424
32390
  }
33425
32391
  } else {
33426
32392
  this.logger.error("Failed to read resource file %s for solution %s: invalid content", undefined, resourceFile, context.path);
33427
- parseErrors.push(resourceFile);
32393
+ invalidFiles.push(resourceFile);
33428
32394
  }
33429
32395
  } catch (ex) {
33430
32396
  if (isFileNotFoundError2(ex)) {
@@ -33437,6 +32403,8 @@ class MultiFileSolutionDefinitionProvider {
33437
32403
  }
33438
32404
  if (missingFiles.length > 0)
33439
32405
  throw new BadRequestException(ErrorCodes.Resources.MissingFileDependencies, `Solution has missing files: ${missingFiles.join(", ")}`);
32406
+ if (invalidFiles.length > 0)
32407
+ throw new BadRequestException(ErrorCodes.Resources.InvalidResourceFile, `Solution has resource files with invalid content: ${invalidFiles.join(", ")}`);
33440
32408
  if (parseErrors.length > 0)
33441
32409
  throw new Error(`Failed to read resource files for solution ${context.path}: ${parseErrors.join(", ")}`);
33442
32410
  const folderMap = new Map;
@@ -33785,6 +32753,7 @@ function createCommandHandlerToken(commandName) {
33785
32753
  var RequestHandlerTokens = {
33786
32754
  ValidateSolutionDefinitionRequest: createRequestHandlerToken("ValidateSolutionDefinitionRequest"),
33787
32755
  SolutionPublishLocationRequest: createRequestHandlerToken("SolutionPublishLocationRequest"),
32756
+ SolutionPublishLocationRequestV2: createRequestHandlerToken("SolutionPublishLocationRequestV2"),
33788
32757
  SettingsRequest: createRequestHandlerToken("SettingsRequest"),
33789
32758
  GetExportableItemsBasedOnBindingsRequest: createRequestHandlerToken("GetExportableItemsBasedOnBindingsRequest")
33790
32759
  };
@@ -33827,6 +32796,9 @@ class ValidateSolutionDefinitionRequest {
33827
32796
  class SolutionPublishLocationRequest {
33828
32797
  }
33829
32798
 
32799
+ class SolutionPublishLocationRequestV2 {
32800
+ }
32801
+
33830
32802
  class SettingsRequest {
33831
32803
  }
33832
32804
  function _ts_decorate(decorators, target, key, desc) {
@@ -33956,6 +32928,53 @@ SolutionPublishLocationRequestHandler = solution_publish_location_handler_ts_dec
33956
32928
  "u" < typeof ILoggerFactory ? Object : ILoggerFactory
33957
32929
  ])
33958
32930
  ], SolutionPublishLocationRequestHandler);
32931
+ function solution_publish_location_v2_handler_ts_decorate(decorators, target, key, desc) {
32932
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
32933
+ if (typeof Reflect == "object" && typeof Reflect.decorate == "function")
32934
+ r = Reflect.decorate(decorators, target, key, desc);
32935
+ else
32936
+ for (var i = decorators.length - 1;i >= 0; i--)
32937
+ if (d = decorators[i])
32938
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
32939
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
32940
+ }
32941
+ function solution_publish_location_v2_handler_ts_metadata(k, v) {
32942
+ if (typeof Reflect == "object" && typeof Reflect.metadata == "function")
32943
+ return Reflect.metadata(k, v);
32944
+ }
32945
+ function solution_publish_location_v2_handler_ts_param(paramIndex, decorator) {
32946
+ return function(target, key) {
32947
+ decorator(target, key, paramIndex);
32948
+ };
32949
+ }
32950
+
32951
+ class SolutionPublishLocationRequestV2Handler {
32952
+ async handleAsync(_request, cancellationToken) {
32953
+ try {
32954
+ const orchestratorClient = await this.orchestratorClientFactory.getClientAsync(cancellationToken);
32955
+ if (!orchestratorClient)
32956
+ throw new InvalidOperationException("Failed to create Orchestrator client");
32957
+ return await orchestratorClient.getPublishLocationsAsync(cancellationToken);
32958
+ } catch (error) {
32959
+ this.logger.error("An unexpected error occurred while retrieving publish locations from Automation Solutions service.", error);
32960
+ throw error;
32961
+ }
32962
+ }
32963
+ constructor(orchestratorClientFactory, loggerFactory) {
32964
+ this.orchestratorClientFactory = orchestratorClientFactory;
32965
+ this.logger = loggerFactory.create("SolutionPublishLocationRequestV2Handler");
32966
+ }
32967
+ }
32968
+ SolutionPublishLocationRequestV2Handler = solution_publish_location_v2_handler_ts_decorate([
32969
+ import_tsyringe.injectable(),
32970
+ solution_publish_location_v2_handler_ts_param(0, import_tsyringe.inject(Tokens.IOrchestratorClientFactory)),
32971
+ solution_publish_location_v2_handler_ts_param(1, import_tsyringe.inject(ServiceTokens.LoggerFactory)),
32972
+ solution_publish_location_v2_handler_ts_metadata("design:type", Function),
32973
+ solution_publish_location_v2_handler_ts_metadata("design:paramtypes", [
32974
+ "u" < typeof IOrchestratorClientFactory ? Object : IOrchestratorClientFactory,
32975
+ "u" < typeof ILoggerFactory ? Object : ILoggerFactory
32976
+ ])
32977
+ ], SolutionPublishLocationRequestV2Handler);
33959
32978
  function settings_handler_ts_decorate(decorators, target, key, desc) {
33960
32979
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
33961
32980
  if (typeof Reflect == "object" && typeof Reflect.decorate == "function")
@@ -34345,6 +33364,70 @@ class ResourceOverwritesService {
34345
33364
  }
34346
33365
  async getOverwritesValidationErrors(solution, resourceOverwrites, cancellationToken) {
34347
33366
  this.logger.info("Validate overwrites for solution", solution.key);
33367
+ return this.useGetByKeysOverwriteValidation ? this.getOverwritesValidationErrorsByKeys(solution, resourceOverwrites, cancellationToken) : this.getOverwritesValidationErrorsPaginatedByFolder(solution, resourceOverwrites, cancellationToken);
33368
+ }
33369
+ async getOverwritesValidationErrorsByKeys(solution, resourceOverwrites, cancellationToken) {
33370
+ const resourceDictionary = new Map(solution.resources.map((r) => [
33371
+ r.key.toLowerCase(),
33372
+ r
33373
+ ]));
33374
+ const validOverwrites = [];
33375
+ for (const [key, overwrite] of resourceOverwrites)
33376
+ if (resourceDictionary.has(key.toLowerCase()) && overwrite)
33377
+ validOverwrites.push({
33378
+ solutionResourceKey: key,
33379
+ overwrite
33380
+ });
33381
+ const results = new Map;
33382
+ if (validOverwrites.length === 0)
33383
+ return results;
33384
+ const allResourceGuids = [
33385
+ ...new Set(validOverwrites.map((x) => x.overwrite?.resourceKey).filter((k) => !!k && isGuid2(k)))
33386
+ ];
33387
+ const entities = await this.resourceCatalogReader.getEntitiesByKeysAsync(allResourceGuids, cancellationToken);
33388
+ const entitiesById = new Map;
33389
+ for (const entity of entities)
33390
+ if (entity.entityKey)
33391
+ entitiesById.set(entity.entityKey.toLowerCase(), entity);
33392
+ const overwritesByFolder = new Map;
33393
+ for (const overwrite of validOverwrites) {
33394
+ const folderKey = overwrite.overwrite?.folderKey;
33395
+ const group = overwritesByFolder.get(folderKey) ?? [];
33396
+ group.push(overwrite);
33397
+ overwritesByFolder.set(folderKey, group);
33398
+ }
33399
+ for (const [folderKey, folderGroup] of overwritesByFolder) {
33400
+ const folderFQN = folderGroup[0]?.overwrite?.folderFullyQualifiedName;
33401
+ const folderFoundInAnyEntity = !!folderKey && folderGroup.some((overwrite) => {
33402
+ const resourceKey = overwrite.overwrite?.resourceKey;
33403
+ if (!resourceKey || !isGuid2(resourceKey))
33404
+ return false;
33405
+ const entity = entitiesById.get(resourceKey.toLowerCase());
33406
+ return !!entity && (entity.folders ?? []).some((f) => sameGuid(f.key, folderKey));
33407
+ });
33408
+ for (const overwrite of folderGroup) {
33409
+ const resourceKey = overwrite.overwrite?.resourceKey;
33410
+ const entity = resourceKey && isGuid2(resourceKey) ? entitiesById.get(resourceKey.toLowerCase()) : undefined;
33411
+ if (!entity) {
33412
+ results.set(overwrite.solutionResourceKey, {
33413
+ message: createLocalizableMessage("ResourceNotFoundInRCS", overwrite.overwrite?.resourceName ?? ""),
33414
+ severity: "Critical"
33415
+ });
33416
+ continue;
33417
+ }
33418
+ if (folderKey && !(entity.folders ?? []).some((f) => sameGuid(f.key, folderKey)))
33419
+ results.set(overwrite.solutionResourceKey, folderFoundInAnyEntity ? {
33420
+ message: createLocalizableMessage("ResourceNotFoundInRCS", overwrite.overwrite?.resourceName ?? ""),
33421
+ severity: "Critical"
33422
+ } : {
33423
+ message: createLocalizableMessage("FolderNotFoundInRCS", folderFQN ?? ""),
33424
+ severity: "Critical"
33425
+ });
33426
+ }
33427
+ }
33428
+ return results;
33429
+ }
33430
+ async getOverwritesValidationErrorsPaginatedByFolder(solution, resourceOverwrites, cancellationToken) {
34348
33431
  const resourceDictionary = new Map(solution.resources.map((r) => [
34349
33432
  r.key.toLowerCase(),
34350
33433
  r
@@ -34470,7 +33553,8 @@ class ResourceOverwritesService {
34470
33553
  const result = await this.resourceCatalogReader.getEntities({
34471
33554
  entityTypes: kinds,
34472
33555
  skip,
34473
- take: pageSize
33556
+ take: pageSize,
33557
+ folderKey
34474
33558
  }, cancellationToken);
34475
33559
  totalCount = result.count ?? 0;
34476
33560
  const entities = result.value ?? [];
@@ -34586,7 +33670,7 @@ class ResourceOverwritesService {
34586
33670
  return false;
34587
33671
  return true;
34588
33672
  }
34589
- constructor(fileStorageProviderFactory, clientProxy, serializerProxy, resourceBuilderAccessProvider, metadataReader, resourceCatalogReader, importResourceHelper, loggerFactory) {
33673
+ constructor(fileStorageProviderFactory, clientProxy, serializerProxy, resourceBuilderAccessProvider, metadataReader, resourceCatalogReader, importResourceHelper, loggerFactory, useGetByKeysOverwriteValidation = false) {
34590
33674
  this.fileStorageProviderFactory = fileStorageProviderFactory;
34591
33675
  this.clientProxy = clientProxy;
34592
33676
  this.serializerProxy = serializerProxy;
@@ -34594,10 +33678,20 @@ class ResourceOverwritesService {
34594
33678
  this.metadataReader = metadataReader;
34595
33679
  this.resourceCatalogReader = resourceCatalogReader;
34596
33680
  this.importResourceHelper = importResourceHelper;
33681
+ this.useGetByKeysOverwriteValidation = useGetByKeysOverwriteValidation;
34597
33682
  this._overwritesPath = DebugOverwritesConstants.ResourceOverwritesFileName;
34598
33683
  this.logger = loggerFactory.create("ResourceOverwritesService");
34599
33684
  }
34600
33685
  }
33686
+ var GUID_REGEX2 = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
33687
+ function isGuid2(value) {
33688
+ return GUID_REGEX2.test(value);
33689
+ }
33690
+ function sameGuid(a, b) {
33691
+ if (!a || !b)
33692
+ return false;
33693
+ return a.toLowerCase() === b.toLowerCase();
33694
+ }
34601
33695
 
34602
33696
  class ResourceDependencyNotFoundException extends BadRequestException {
34603
33697
  get missingDependencies() {
@@ -34643,9 +33737,9 @@ class AsyncSemaphore {
34643
33737
  return void this._permits--;
34644
33738
  return new Promise((resolve2, reject) => {
34645
33739
  const onAbort = () => {
34646
- const index2 = this._queue.indexOf(resolver);
34647
- if (index2 !== -1)
34648
- this._queue.splice(index2, 1);
33740
+ const index = this._queue.indexOf(resolver);
33741
+ if (index !== -1)
33742
+ this._queue.splice(index, 1);
34649
33743
  reject(new OperationCancelledException);
34650
33744
  };
34651
33745
  const resolver = () => {
@@ -34965,6 +34059,50 @@ var import_resource_helper_WellKnownPropertyNames = {
34965
34059
  Name: "name",
34966
34060
  Description: "description"
34967
34061
  };
34062
+ function mapFpsResourceToResourceDefinition(source) {
34063
+ const runtimeDependencies = source.runtimeDependencies?.map((rd) => ({
34064
+ bindingType: rd.bindingType,
34065
+ bindingKey: rd.bindingKey ?? undefined,
34066
+ bindingValues: rd.bindingValues ?? undefined,
34067
+ bindingMetadata: rd.bindingMetadata ?? undefined,
34068
+ resourceKind: rd.resourceKind,
34069
+ resourceType: rd.resourceType ?? undefined,
34070
+ resourceKey: rd.resourceKey ?? undefined,
34071
+ resourceName: rd.resourceName ?? undefined,
34072
+ folderKey: rd.folderKey ?? undefined
34073
+ })) ?? [];
34074
+ const specObj = source.spec;
34075
+ const nameValue = specObj?.[import_resource_helper_WellKnownPropertyNames.Name];
34076
+ const resourceName = nameValue != null ? String(nameValue) : "";
34077
+ return {
34078
+ key: source.key,
34079
+ apiVersion: source.apiVersion,
34080
+ name: resourceName,
34081
+ kind: source.kind,
34082
+ type: source.type ?? undefined,
34083
+ isOverridable: source.isOverridable ?? true,
34084
+ runtimeDependencies,
34085
+ spec: source.spec ?? {},
34086
+ dependencies: source.dependencies?.filter((d) => !!d.name && d.name.length > 0).map((d) => ({
34087
+ name: d.name ?? "",
34088
+ kind: d.kind
34089
+ })) ?? [],
34090
+ folders: [],
34091
+ files: [],
34092
+ locks: []
34093
+ };
34094
+ }
34095
+ function toExportResourceIdentifier(resourceReference) {
34096
+ return {
34097
+ key: resourceReference.key,
34098
+ kind: resourceReference.kind,
34099
+ type: resourceReference.type ?? null,
34100
+ folderKey: resourceReference.folder?.folderKey ?? null,
34101
+ folderKeys: resourceReference.folder?.folderKey ? [
34102
+ resourceReference.folder.folderKey
34103
+ ] : []
34104
+ };
34105
+ }
34968
34106
 
34969
34107
  class ImportResourceHelper {
34970
34108
  async exportResourceAsync(resourceReference, cancellationToken) {
@@ -35021,7 +34159,7 @@ class ImportResourceHelper {
35021
34159
  folderKey: resourceOverwrite.folderKey
35022
34160
  }
35023
34161
  };
35024
- const exportModel = this.toExportResourceIdentifier(resourceReference, serviceName);
34162
+ const exportModel = toExportResourceIdentifier(resourceReference);
35025
34163
  try {
35026
34164
  const exportedPayload = await this.fpsClientProxy.exportResourcesAsync(serviceName, exportModel, cancellationToken);
35027
34165
  if (!exportedPayload) {
@@ -35056,7 +34194,7 @@ class ImportResourceHelper {
35056
34194
  async exportResourceInternalAsync(resourceReference, serviceName, cancellationToken) {
35057
34195
  this.logger.info(`ExportResourceAsync: Exporting resource ${resourceReference.key} from ${serviceName}`);
35058
34196
  this.logger.info("ExportResourceAsync: Resource reference:", JSON.stringify(resourceReference, null, 2));
35059
- const exportModel = this.toExportResourceIdentifier(resourceReference, serviceName);
34197
+ const exportModel = toExportResourceIdentifier(resourceReference);
35060
34198
  this.logger.info("ExportResourceAsync: Export model:", JSON.stringify(exportModel, null, 2));
35061
34199
  const exportedPayload = await this.fpsClientProxy.exportResourcesAsync(serviceName, exportModel, cancellationToken);
35062
34200
  if (!exportedPayload)
@@ -35221,7 +34359,7 @@ class ImportResourceHelper {
35221
34359
  const otherFolderDetails = await this.extractDetailsForUnknownFolders(resourcesArray, resourceFolders, foldersDictionary, cancellationToken);
35222
34360
  for (const { resource, identifier } of resourcesToBeProcessed.values()) {
35223
34361
  const metadata = this.findMetadata(resourceMetadataMap, identifier);
35224
- const base = this.mapToResourceDefinition(resource);
34362
+ const base = mapFpsResourceToResourceDefinition(resource);
35225
34363
  base.dependencies = [];
35226
34364
  const definition = this.toEnhancedResourceDefinition(base, metadata);
35227
34365
  for (const dep of resource.dependencies ?? []) {
@@ -35263,39 +34401,6 @@ class ImportResourceHelper {
35263
34401
  }
35264
34402
  return this.resourceCatalogReader.mapEntityFolderInfoAsync(otherFolderDependencies, cancellationToken);
35265
34403
  }
35266
- mapToResourceDefinition(source) {
35267
- const runtimeDependencies = source.runtimeDependencies?.map((rd) => ({
35268
- bindingType: rd.bindingType,
35269
- bindingKey: rd.bindingKey ?? undefined,
35270
- bindingValues: rd.bindingValues ?? undefined,
35271
- bindingMetadata: rd.bindingMetadata ?? undefined,
35272
- resourceKind: rd.resourceKind,
35273
- resourceType: rd.resourceType ?? undefined,
35274
- resourceKey: rd.resourceKey ?? undefined,
35275
- resourceName: rd.resourceName ?? undefined,
35276
- folderKey: rd.folderKey ?? undefined
35277
- })) ?? [];
35278
- const specObj = source.spec;
35279
- const nameValue = specObj?.[import_resource_helper_WellKnownPropertyNames.Name];
35280
- const resourceName = nameValue != null ? String(nameValue) : "";
35281
- return {
35282
- key: source.key,
35283
- apiVersion: source.apiVersion,
35284
- name: resourceName,
35285
- kind: source.kind,
35286
- type: source.type ?? undefined,
35287
- isOverridable: source.isOverridable ?? true,
35288
- runtimeDependencies,
35289
- spec: source.spec ?? {},
35290
- dependencies: source.dependencies?.filter((d) => !!d.name && d.name.length > 0).map((d) => ({
35291
- name: d.name ?? "",
35292
- kind: d.kind
35293
- })) ?? [],
35294
- folders: [],
35295
- files: [],
35296
- locks: []
35297
- };
35298
- }
35299
34404
  mapToFileDefinition(source) {
35300
34405
  return {
35301
34406
  key: source.key,
@@ -35320,18 +34425,6 @@ class ImportResourceHelper {
35320
34425
  }
35321
34426
  return folder;
35322
34427
  }
35323
- toExportResourceIdentifier(resourceReference, _serviceName) {
35324
- const identifier = {
35325
- key: resourceReference.key,
35326
- kind: resourceReference.kind,
35327
- type: resourceReference.type ?? null,
35328
- folderKey: resourceReference.folder?.folderKey ?? null,
35329
- folderKeys: resourceReference.folder?.folderKey ? [
35330
- resourceReference.folder.folderKey
35331
- ] : []
35332
- };
35333
- return identifier;
35334
- }
35335
34428
  toEnhancedResourceDefinition(rd, metadata) {
35336
34429
  const effectiveMetadata = metadata ?? {
35337
34430
  visibleInDesigner: false,
@@ -35687,10 +34780,11 @@ class UpdateResourceCommand {
35687
34780
  }
35688
34781
 
35689
34782
  class AddOrUpdateResourceToSolutionCommand {
35690
- constructor(context, resourceReference, updateConfirmation) {
34783
+ constructor(context, resourceReference, updateConfirmation, existingSolutionResourceKey) {
35691
34784
  this.context = context;
35692
34785
  this.resourceReference = resourceReference;
35693
34786
  this.updateConfirmation = updateConfirmation;
34787
+ this.existingSolutionResourceKey = existingSolutionResourceKey;
35694
34788
  }
35695
34789
  }
35696
34790
 
@@ -35943,7 +35037,6 @@ var models_ResourceAdditionStatus = /* @__PURE__ */ function(ResourceAdditionSta
35943
35037
  ResourceAdditionStatus["Unchanged"] = "Unchanged";
35944
35038
  return ResourceAdditionStatus;
35945
35039
  }({});
35946
-
35947
35040
  class ResourceDefinitionRequestHandler {
35948
35041
  async handleAsync(request, cancellationToken) {
35949
35042
  const solution = await request.context.loadAsync(cancellationToken);
@@ -36101,17 +35194,37 @@ class ResourceConfigurationRequestHandler {
36101
35194
  }
36102
35195
 
36103
35196
  class RetrieveConfigurationRequestHandler {
36104
- async handleAsync(request, _cancellationToken) {
35197
+ async handleAsync(request, cancellationToken) {
36105
35198
  const { resourceReference } = request;
36106
- return {
36107
- key: resourceReference.key,
36108
- spec: {},
36109
- locks: []
36110
- };
35199
+ this.logger.info(`Retrieving resource configuration for resource ${resourceReference.key} of kind ${resourceReference.kind} from solution ${request.context.path}`);
35200
+ const solution = await request.context.loadAsync(cancellationToken);
35201
+ const resource = getResourceOrDefault(solution, resourceReference.key);
35202
+ if (resource)
35203
+ return this.mediator.sendAsync(new GetMappedResourceConfigurationRequest(request.context, resource), cancellationToken);
35204
+ const serviceName = await this.metadataReader.getServiceNameAsync(resourceReference.kind, resourceReference.type, cancellationToken);
35205
+ if (!serviceName) {
35206
+ this.logger.error(`Resource kind ${resourceReference.kind} or type ${resourceReference.type} are invalid solution resource metadata identifiers`);
35207
+ throw new BadRequestException(ErrorCodes.Resources.InvalidResourceMetadataIdentifier, `Invalid resource metadata identifier: kind=${resourceReference.kind}, type=${resourceReference.type ?? "(none)"}`);
35208
+ }
35209
+ const exportModel = toExportResourceIdentifier(resourceReference);
35210
+ const exportedPayload = await this.fpsClientProxy.exportResourcesAsync(serviceName, exportModel, cancellationToken);
35211
+ if (!exportedPayload) {
35212
+ this.logger.error(`Failed to export resource ${resourceReference.key} from ${serviceName}`);
35213
+ throw new NotFoundException("Configuration", resourceReference.key, `Missing configuration for resource ${resourceReference.key} in service ${serviceName}`, ErrorCodes.Solutions.ConfigurationNotFound);
35214
+ }
35215
+ const exportedResource = exportedPayload.resources?.find((x) => x.key === resourceReference.key);
35216
+ if (!exportedResource) {
35217
+ this.logger.error(`Exported payload from ${serviceName} does not include a resource with key ${resourceReference.key}`);
35218
+ throw new NotFoundException("Configuration", resourceReference.key, `Missing configuration for resource ${resourceReference.key} in service ${serviceName}`, ErrorCodes.Solutions.ConfigurationNotFound);
35219
+ }
35220
+ const definition = mapFpsResourceToResourceDefinition(exportedResource);
35221
+ return this.mediator.sendAsync(new GetMappedResourceConfigurationRequest(request.context, definition), cancellationToken);
36111
35222
  }
36112
- constructor(metadataReader, resourceCatalogClientProxy) {
35223
+ constructor(metadataReader, fpsClientProxy, mediator, loggerFactory) {
36113
35224
  this.metadataReader = metadataReader;
36114
- this.resourceCatalogClientProxy = resourceCatalogClientProxy;
35225
+ this.fpsClientProxy = fpsClientProxy;
35226
+ this.mediator = mediator;
35227
+ this.logger = loggerFactory.create(RetrieveConfigurationRequestHandler);
36115
35228
  }
36116
35229
  }
36117
35230
 
@@ -36471,14 +35584,14 @@ class CreateVirtualResourceCommandHandler {
36471
35584
  const nameSpec = version.spec.find((x) => x.property.toLowerCase() === WellKnownPropertyNames.Name.toLowerCase());
36472
35585
  const defaultName = nameSpec?.defaultValue ?? kind.charAt(0).toUpperCase() + kind.slice(1);
36473
35586
  const resourcesWithSimilarName = solution.resources.filter((x) => x.kind.toLowerCase() === kind.toLowerCase() && x.name.toLowerCase().startsWith(defaultName.toLowerCase()));
36474
- let index2 = 1;
35587
+ let index = 1;
36475
35588
  let suggestedName = defaultName;
36476
35589
  if (resourcesWithSimilarName.length > 0)
36477
35590
  while (true) {
36478
- suggestedName = `${defaultName}_${index2}`;
35591
+ suggestedName = `${defaultName}_${index}`;
36479
35592
  if (!resourcesWithSimilarName.some((x) => x.name.toLowerCase() === suggestedName.toLowerCase()))
36480
35593
  break;
36481
- index2++;
35594
+ index++;
36482
35595
  }
36483
35596
  return suggestedName;
36484
35597
  }
@@ -36704,8 +35817,23 @@ class AddOrUpdateResourceToSolutionCommandHandler {
36704
35817
  return currentStatus;
36705
35818
  }
36706
35819
  async handleResourceAsync(resourceDefinition, cancellationToken) {
36707
- const solutionResource = getResourceOrDefault(this._solution, resourceDefinition.key);
36708
- return solutionResource === undefined ? this.addResourceToSolution(resourceDefinition).status : await this.updateResourceInSolution(resourceDefinition, solutionResource, cancellationToken);
35820
+ const solutionResource = this.tryAlignWithExistingSolutionResource(resourceDefinition) ?? getResourceOrDefault(this._solution, resourceDefinition.key);
35821
+ if (solutionResource === undefined)
35822
+ return this.addResourceToSolution(resourceDefinition).status;
35823
+ return await this.updateResourceInSolution(resourceDefinition, solutionResource, cancellationToken);
35824
+ }
35825
+ tryAlignWithExistingSolutionResource(resourceDefinition) {
35826
+ const existingKey = this._command.existingSolutionResourceKey;
35827
+ if (!existingKey || !invariantEquals(resourceDefinition.key, this._command.resourceReference.key))
35828
+ return;
35829
+ const solutionResource = getResourceOrDefault(this._solution, existingKey);
35830
+ if (!solutionResource)
35831
+ return;
35832
+ resourceDefinition.key = solutionResource.key;
35833
+ resourceDefinition.name = solutionResource.name;
35834
+ if (resourceDefinition.spec && WellKnownPropertyNames.Name in resourceDefinition.spec)
35835
+ resourceDefinition.spec[WellKnownPropertyNames.Name] = solutionResource.name;
35836
+ return solutionResource;
36709
35837
  }
36710
35838
  addResourceToSolution(resourceDefinition) {
36711
35839
  this.logger.warn(`Try add resource with key ${resourceDefinition.key} in solution ${this._solution.key}.`);
@@ -36822,7 +35950,8 @@ class AddOrUpdateResourceToSolutionCommandHandler {
36822
35950
  }
36823
35951
  throw new NotFoundException("SolutionResource", resourceRef.key);
36824
35952
  }
36825
- const solutionResource = getResourceOrDefault(this._solution, requestedResource.key);
35953
+ const solutionLookupKey = this._command.existingSolutionResourceKey ? this._command.existingSolutionResourceKey : requestedResource.key;
35954
+ const solutionResource = getResourceOrDefault(this._solution, solutionLookupKey);
36826
35955
  const ret = solutionResource === undefined ? models_ResourceAdditionStatus.Added : models_ResourceAdditionStatus.Unchanged;
36827
35956
  return {
36828
35957
  status: ret,
@@ -37270,7 +36399,7 @@ class SyncResourceConfigurationBasedOnOverwriteCommandHandler {
37270
36399
  path: overwrite.folderPath,
37271
36400
  folderKey: overwrite.folderKey
37272
36401
  }
37273
- }, true), cancellationToken);
36402
+ }, true, command.resourceKey), cancellationToken);
37274
36403
  await command.context.saveChangesAsync(cancellationToken);
37275
36404
  const updatedSolution = await command.context.loadAsync(true, cancellationToken);
37276
36405
  const typedResult = result;
@@ -38715,12 +37844,38 @@ class ResourceCatalogClientProxy {
38715
37844
  const client = await this.getClient(cancellationToken);
38716
37845
  if (!client)
38717
37846
  throw new InvalidOperationException("Unable to create Resource Catalog client. Check authentication and configuration.");
37847
+ const { folderKey, ...query } = options ?? {};
37848
+ const requestParams = folderKey ? {
37849
+ signal: cancellationToken,
37850
+ headers: {
37851
+ "X-UIPATH-FolderKey": folderKey
37852
+ }
37853
+ } : {
37854
+ signal: cancellationToken
37855
+ };
37856
+ try {
37857
+ return await client.entities.entitiesGet(query, requestParams);
37858
+ } catch (error) {
37859
+ const errorMessage2 = `Failed to retrieve entities from Resource Catalog: ${extractHttpErrorDetails(error)}`;
37860
+ this.logger.error(errorMessage2, error instanceof Error ? error : new Error(errorMessage2));
37861
+ throw new InvalidOperationException(errorMessage2);
37862
+ }
37863
+ }
37864
+ async getEntitiesByKeysAsync(resourceKeys, cancellationToken) {
37865
+ if (resourceKeys.length === 0)
37866
+ return [];
37867
+ const client = await this.getClient(cancellationToken);
37868
+ if (!client) {
37869
+ this.logger.info("No Resource Catalog Service URL retrieved.");
37870
+ return [];
37871
+ }
38718
37872
  try {
38719
- return await client.entities.entitiesGet(options, {
37873
+ const entities = await client.entities.entitiesGetEntitiesByKeys(resourceKeys, {}, {
38720
37874
  signal: cancellationToken
38721
37875
  });
37876
+ return entities ?? [];
38722
37877
  } catch (error) {
38723
- const errorMessage2 = `Failed to retrieve entities from Resource Catalog: ${extractHttpErrorDetails(error)}`;
37878
+ const errorMessage2 = `An unexpected error occurred while retrieving entities by keys from Resource Catalog: ${extractHttpErrorDetails(error)}`;
38724
37879
  this.logger.error(errorMessage2, error instanceof Error ? error : new Error(errorMessage2));
38725
37880
  throw new InvalidOperationException(errorMessage2);
38726
37881
  }
@@ -41012,6 +40167,24 @@ class automation_solutions_client_proxy_AutomationSolutionsClientProxy {
41012
40167
  }
41013
40168
 
41014
40169
  class OrchestratorClient {
40170
+ async getPublishLocationsAsync(cancellationToken) {
40171
+ const url = `${this.options.baseUrl}api/v2/AutomationSolutions/publish_locations`;
40172
+ const headers = OrchestratorClientFactory.buildHeaders(this.options.securityData);
40173
+ const response = await fetch(url, {
40174
+ method: "GET",
40175
+ headers,
40176
+ signal: cancellationToken
40177
+ });
40178
+ if (!response.ok) {
40179
+ const errorText = await this.readResponseTextSafe(response);
40180
+ throw new Error(`Request failed with status ${response.status}: ${errorText}`);
40181
+ }
40182
+ const responseJson = await response.text();
40183
+ const result = this.jsonSerializer.deserialize(responseJson);
40184
+ if (!result)
40185
+ throw new Error("Failed to deserialize publish locations response.");
40186
+ return result;
40187
+ }
41015
40188
  async patchResourceOverwritesAsync(request, cancellationToken) {
41016
40189
  if (!request)
41017
40190
  throw new Error("request is required");
@@ -41607,9 +40780,9 @@ class ReconcileProjectsCommandHandler {
41607
40780
  solutionKey
41608
40781
  });
41609
40782
  for (const resource of resources) {
41610
- const index2 = solution.resources.indexOf(resource);
41611
- if (index2 !== -1)
41612
- solution.resources.splice(index2, 1);
40783
+ const index = solution.resources.indexOf(resource);
40784
+ if (index !== -1)
40785
+ solution.resources.splice(index, 1);
41613
40786
  }
41614
40787
  }
41615
40788
  await command.context.forceSaveChangesAsync(cancellationToken);
@@ -42336,7 +41509,8 @@ class ApplyTestConfigurationCommandHandler {
42336
41509
  }
42337
41510
  const patchOverwritesRequest = {
42338
41511
  processKeys: processesNeedingBindingOverwrites,
42339
- overwrites: allOverwrites
41512
+ overwrites: allOverwrites,
41513
+ replace: true
42340
41514
  };
42341
41515
  const orchestratorClient = await this.orchestratorClientFactory.getClientAsync(cancellationToken);
42342
41516
  if (!orchestratorClient) {
@@ -42406,6 +41580,11 @@ class ResourceBuilder {
42406
41580
  const request = new SolutionPublishLocationRequest;
42407
41581
  return this._mediator.sendAsync(request, cancellationToken);
42408
41582
  }
41583
+ async getAvailablePublishLocationsV2Async(cancellationToken) {
41584
+ this.throwIfCancelled(cancellationToken);
41585
+ const request = new SolutionPublishLocationRequestV2;
41586
+ return this._mediator.sendAsync(request, cancellationToken);
41587
+ }
42409
41588
  async getSettingsAsync(cancellationToken) {
42410
41589
  this.throwIfCancelled(cancellationToken);
42411
41590
  const request = new SettingsRequest;
@@ -42519,18 +41698,31 @@ class BindingsMetadataSerializer {
42519
41698
  const prop = value;
42520
41699
  result[key] = {
42521
41700
  defaultValue: prop["defaultValue"] ?? "",
42522
- isExpression: prop["isExpression"] ?? false
41701
+ isExpression: this.parseBoolean(prop["isExpression"], false)
42523
41702
  };
42524
41703
  }
42525
41704
  return result;
42526
41705
  }
41706
+ parseBoolean(value, defaultValue) {
41707
+ if (typeof value == "boolean")
41708
+ return value;
41709
+ if (typeof value == "string") {
41710
+ const normalized = value.trim().toLowerCase();
41711
+ if (normalized === "true")
41712
+ return true;
41713
+ if (normalized === "false")
41714
+ return false;
41715
+ }
41716
+ return defaultValue;
41717
+ }
42527
41718
  parseMetadata(type, metadataNode) {
42528
- const get = (key) => {
41719
+ const getValue = (key) => {
42529
41720
  const lowerKey = key.toLowerCase();
42530
41721
  for (const [k, v] of Object.entries(metadataNode))
42531
41722
  if (k.toLowerCase() === lowerKey)
42532
41723
  return v;
42533
41724
  };
41725
+ const get = (key) => getValue(key);
42534
41726
  const base = {
42535
41727
  activityName: get("activityName"),
42536
41728
  bindingsVersion: get("bindingsVersion"),
@@ -42559,8 +41751,7 @@ class BindingsMetadataSerializer {
42559
41751
  objectName: get("objectName"),
42560
41752
  triggerCreateParameters: get("triggerCreateParameters")
42561
41753
  };
42562
- const overwritable = get("overwritable");
42563
- meta.overwritable = overwritable !== undefined ? overwritable.toLowerCase() !== "false" : true;
41754
+ meta.overwritable = this.parseBoolean(getValue("overwritable"), true);
42564
41755
  return meta;
42565
41756
  }
42566
41757
  case models_BindingsResourceType.EventTrigger: {
@@ -42630,13 +41821,19 @@ class BindingOverwritesHandler {
42630
41821
  if (!resourceOverwrite)
42631
41822
  continue;
42632
41823
  let overwrite;
42633
- overwrite = bindingResource.binding.resourceType === models_BindingsResourceType.Connection || bindingResource.binding.resourceType === models_BindingsResourceType.EventTrigger ? {
42634
- [BindingsKnownKeys.ConnectionIdPropertyName]: resourceOverwrite.resourceKey ?? "",
42635
- [BindingsKnownKeys.FolderKeyPropertyName]: resourceOverwrite.folderKey ?? ""
42636
- } : {
42637
- [BindingsKnownKeys.FolderPathPropertyName]: resourceOverwrite.folderFullyQualifiedName ?? "",
42638
- [BindingsKnownKeys.NamePropertyName]: resourceOverwrite.resourceName
42639
- };
41824
+ if (bindingResource.binding.resourceType === models_BindingsResourceType.Connection || bindingResource.binding.resourceType === models_BindingsResourceType.EventTrigger)
41825
+ overwrite = {
41826
+ [BindingsKnownKeys.ConnectionIdPropertyName]: resourceOverwrite.resourceKey ?? "",
41827
+ [BindingsKnownKeys.FolderKeyPropertyName]: resourceOverwrite.folderKey ?? ""
41828
+ };
41829
+ else {
41830
+ overwrite = {
41831
+ [BindingsKnownKeys.FolderPathPropertyName]: resourceOverwrite.folderFullyQualifiedName ?? "",
41832
+ [BindingsKnownKeys.NamePropertyName]: resourceOverwrite.resourceName
41833
+ };
41834
+ if (bindingResource.binding.resourceType === models_BindingsResourceType.Entity)
41835
+ overwrite[BindingsKnownKeys.FolderKeyPropertyName] = resourceOverwrite.folderKey ?? "";
41836
+ }
42640
41837
  const key = getOverrideKey(bindingResource.binding);
42641
41838
  result[key] = overwrite;
42642
41839
  }
@@ -43524,14 +42721,20 @@ class FileService {
43524
42721
  failedDownloads.add(file.name);
43525
42722
  return;
43526
42723
  }
42724
+ const originalUrl = file.url;
43527
42725
  try {
43528
42726
  this.logger.info(`Testing download of file ${file.name}.`);
43529
- const fileUrl = await this.resolveFileUrlAsync(file.url, cancellationToken);
43530
- const ok = await this.headProbe(fileUrl, accessToken, ipBypass, cancellationToken);
42727
+ const { resolvedUrl, isUiPathServiceUrl } = await this.resolveFileUrlAsync(originalUrl, cancellationToken);
42728
+ const ok = await this.headProbe(resolvedUrl, accessToken, ipBypass, cancellationToken);
43531
42729
  if (ok)
43532
42730
  return;
42731
+ if (isUiPathServiceUrl) {
42732
+ this.logger.error(`Download failed for file ${file.name} from a UiPath service endpoint; skipping no-token retry.`);
42733
+ failedDownloads.add(file.name);
42734
+ return;
42735
+ }
43533
42736
  this.logger.warn(`First attempt failed for file ${file.name}. Retrying without access token.`);
43534
- const retryOk = await this.headProbe(fileUrl, null, ipBypass, cancellationToken);
42737
+ const retryOk = await this.headProbe(resolvedUrl, null, ipBypass, cancellationToken);
43535
42738
  if (!retryOk) {
43536
42739
  this.logger.error(`Retry without access token also failed for file ${file.name}.`);
43537
42740
  failedDownloads.add(file.name);
@@ -43563,7 +42766,10 @@ class FileService {
43563
42766
  try {
43564
42767
  originalUri = new URL(fileUrl);
43565
42768
  } catch {
43566
- return fileUrl;
42769
+ return {
42770
+ resolvedUrl: fileUrl,
42771
+ isUiPathServiceUrl: false
42772
+ };
43567
42773
  }
43568
42774
  const pathSegments = originalUri.pathname.split("/").filter((s) => s.length > 0);
43569
42775
  let serviceScope;
@@ -43577,22 +42783,32 @@ class FileService {
43577
42783
  }
43578
42784
  }
43579
42785
  if (serviceSegmentIndex < 0 || !serviceScope)
43580
- return fileUrl;
42786
+ return {
42787
+ resolvedUrl: fileUrl,
42788
+ isUiPathServiceUrl: false
42789
+ };
43581
42790
  const resolvedServiceUrl = await this.accessProvider.getResourceUrlAsync(serviceScope, cancellationToken);
43582
42791
  if (!resolvedServiceUrl)
43583
- return fileUrl;
42792
+ return {
42793
+ resolvedUrl: fileUrl,
42794
+ isUiPathServiceUrl: true
42795
+ };
43584
42796
  let resolvedServiceUri;
43585
42797
  try {
43586
42798
  resolvedServiceUri = new URL(resolvedServiceUrl);
43587
42799
  } catch {
43588
- return fileUrl;
42800
+ return {
42801
+ resolvedUrl: fileUrl,
42802
+ isUiPathServiceUrl: true
42803
+ };
43589
42804
  }
43590
- const remainingPath = pathSegments.slice(serviceSegmentIndex + 1).join("/");
43591
- const combinedPath = combinePaths(resolvedServiceUri.pathname, remainingPath);
43592
- const resolved = new URL(resolvedServiceUri.toString());
43593
- resolved.pathname = combinedPath;
43594
- resolved.search = originalUri.search;
43595
- return resolved.toString();
42805
+ const resolved = new URL(originalUri.toString());
42806
+ resolved.protocol = resolvedServiceUri.protocol;
42807
+ resolved.host = resolvedServiceUri.host;
42808
+ return {
42809
+ resolvedUrl: resolved.toString(),
42810
+ isUiPathServiceUrl: true
42811
+ };
43596
42812
  }
43597
42813
  constructor(accessProvider, ipRangeBypassSecretProvider, loggerFactory) {
43598
42814
  this.accessProvider = accessProvider;
@@ -43600,12 +42816,6 @@ class FileService {
43600
42816
  this.logger = loggerFactory.create("FileService");
43601
42817
  }
43602
42818
  }
43603
- function combinePaths(basePath, relativePath) {
43604
- const normalizedBase = basePath.replace(/\/+$/, "");
43605
- if (!relativePath)
43606
- return normalizedBase || "/";
43607
- return `${normalizedBase}/${relativePath.replace(/^\/+/, "")}`;
43608
- }
43609
42819
 
43610
42820
  class ProjectResourcesDescriptorFactory {
43611
42821
  async createAsync(_projectType, language, cancellationToken) {
@@ -43900,6 +43110,13 @@ function registerHandlers(diContainer) {
43900
43110
  return new SolutionPublishLocationRequestHandler(automationSolutionsClient, loggerFactory);
43901
43111
  }
43902
43112
  });
43113
+ diContainer.register(createRequestHandlerToken(SolutionPublishLocationRequestV2.name), {
43114
+ useFactory: (c) => {
43115
+ const orchestratorClientFactory = c.resolve(Tokens.IOrchestratorClientFactory);
43116
+ const loggerFactory = c.resolve(ServiceTokens.LoggerFactory);
43117
+ return new SolutionPublishLocationRequestV2Handler(orchestratorClientFactory, loggerFactory);
43118
+ }
43119
+ });
43903
43120
  diContainer.register(createRequestHandlerToken(SettingsRequest.name), {
43904
43121
  useFactory: (c) => {
43905
43122
  const projectConfigurationService = c.resolve(ServiceTokens.ProjectConfigurationService);
@@ -43937,8 +43154,10 @@ function registerHandlers(diContainer) {
43937
43154
  diContainer.register(createRequestHandlerToken(RetrieveConfigurationRequest.name), {
43938
43155
  useFactory: (c) => {
43939
43156
  const metadataReader = c.resolve(ServiceTokens.MetadataReader);
43940
- const resourceCatalogClientProxy = c.resolve(Tokens.IResourceCatalogClientProxy);
43941
- return new RetrieveConfigurationRequestHandler(metadataReader, resourceCatalogClientProxy);
43157
+ const fpsClientProxy = c.resolve(ServiceTokens.FirstPartyServiceClientProxy);
43158
+ const mediator = c.resolve(ServiceTokens.Mediator);
43159
+ const loggerFactory = c.resolve(ServiceTokens.LoggerFactory);
43160
+ return new RetrieveConfigurationRequestHandler(metadataReader, fpsClientProxy, mediator, loggerFactory);
43942
43161
  }
43943
43162
  });
43944
43163
  diContainer.register(createRequestHandlerToken(GetResourceConfigurationsComparisonRequest.name), {
@@ -44982,7 +44201,7 @@ class VoidApiResponse {
44982
44201
  var package_default = {
44983
44202
  name: "@uipath/orchestrator-sdk",
44984
44203
  license: "MIT",
44985
- version: "1.196.0",
44204
+ version: "1.197.0",
44986
44205
  repository: {
44987
44206
  type: "git",
44988
44207
  url: "https://github.com/UiPath/cli.git",
@@ -45016,7 +44235,7 @@ var package_default = {
45016
44235
  ],
45017
44236
  private: true,
45018
44237
  scripts: {
45019
- 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",
44238
+ 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",
45020
44239
  generate: "bun run src/scripts/generate-sdk.ts",
45021
44240
  lint: "biome check .",
45022
44241
  test: "vitest run",
@@ -46805,7 +46024,7 @@ async function syncResourcesFromBindings(solutionDir, projectPaths) {
46805
46024
  }
46806
46025
  const virtualCandidatesSeen = new Set;
46807
46026
  const dedupedVirtuals = virtualCandidates.filter((c) => {
46808
- const key = `${c.kind}:${c.name}:${normalizeFolderPath(c.folderPath) ?? ""}`.toLowerCase();
46027
+ const key = `${c.kind}:${c.name}`.toLowerCase();
46809
46028
  if (virtualCandidatesSeen.has(key))
46810
46029
  return false;
46811
46030
  virtualCandidatesSeen.add(key);
@@ -46851,22 +46070,8 @@ function uniqueNameForResource(name, kind, excludeKey, solution) {
46851
46070
  }));
46852
46071
  return `${name}_${lastIndex + 1}`;
46853
46072
  }
46854
- async function createVirtualForBinding(builder, _binding, kind, type, metadata, name, folderPath, result) {
46855
- const virtualizable = metadata?.virtualizable ?? false;
46856
- const preLoadSolution = await builder.context.loadAsync();
46857
- const folderNorm = normalizeFolderPath(folderPath);
46858
- const escapedName = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
46859
- const suffixRegex = new RegExp(`^${escapedName}(_\\d+)?$`, "i");
46860
- const alreadyVirtualized = preLoadSolution.resources.find((r) => (r.kind ?? "").toLowerCase() === kind.toLowerCase() && normalizeFolderPath(r.folders?.[0]?.fullyQualifiedName) === folderNorm && !!r.name && suffixRegex.test(r.name));
46861
- if (alreadyVirtualized) {
46862
- result.skipped++;
46863
- logger.info(`Skipping virtual ${kind} "${name}" — existing resource "${alreadyVirtualized.name}" at "${folderPath}" already covers this binding`);
46864
- return;
46865
- }
46866
- const res = await builder.createVirtualResourceAsync({
46867
- kind,
46868
- type
46869
- });
46073
+ async function mintVirtualResource(builder, kind, type, name, metadata) {
46074
+ const res = await builder.createVirtualResourceAsync({ kind, type });
46870
46075
  const key = res.key;
46871
46076
  if (!key) {
46872
46077
  logger.warn(`createVirtualResourceAsync returned no key for ${kind}`);
@@ -46874,25 +46079,36 @@ async function createVirtualForBinding(builder, _binding, kind, type, metadata,
46874
46079
  }
46875
46080
  const solution = await builder.context.loadAsync();
46876
46081
  const resource = solution.resources.find((r) => r.key === key);
46877
- if (resource) {
46878
- const uniqueName = uniqueNameForResource(name, kind, key, solution);
46879
- resource.name = uniqueName;
46880
- if (resource.spec) {
46881
- resource.spec.name = uniqueName;
46882
- const specBag = resource.spec;
46883
- for (const {
46884
- property,
46885
- placeholder
46886
- } of metadata?.requiredDefaults ?? []) {
46887
- if (specBag[property] === undefined) {
46888
- specBag[property] = placeholder;
46889
- }
46082
+ if (!resource) {
46083
+ return { finalName: name };
46084
+ }
46085
+ const uniqueName = uniqueNameForResource(name, kind, key, solution);
46086
+ resource.name = uniqueName;
46087
+ if (resource.spec) {
46088
+ resource.spec.name = uniqueName;
46089
+ const specBag = resource.spec;
46090
+ for (const { property, placeholder } of metadata?.requiredDefaults ?? []) {
46091
+ if (specBag[property] === undefined) {
46092
+ specBag[property] = placeholder;
46890
46093
  }
46891
46094
  }
46892
- if (normalizeFolderPath(folderPath)) {
46893
- resource.folders = [{ fullyQualifiedName: folderPath }];
46894
- }
46895
46095
  }
46096
+ return { resource, finalName: uniqueName };
46097
+ }
46098
+ async function createVirtualForBinding(builder, _binding, kind, type, metadata, name, folderPath, result) {
46099
+ const virtualizable = metadata?.virtualizable ?? false;
46100
+ const preLoadSolution = await builder.context.loadAsync();
46101
+ const escapedName = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
46102
+ const suffixRegex = new RegExp(`^${escapedName}(_\\d+)?$`, "i");
46103
+ const alreadyVirtualized = preLoadSolution.resources.find((r) => (r.kind ?? "").toLowerCase() === kind.toLowerCase() && normalizeFolderPath(r.folders?.[0]?.fullyQualifiedName) === undefined && !!r.name && suffixRegex.test(r.name));
46104
+ if (alreadyVirtualized) {
46105
+ result.skipped++;
46106
+ logger.info(`Skipping virtual ${kind} "${name}" — existing resource "${alreadyVirtualized.name}" in solution_folder already covers this binding (requested folder "${folderPath}")`);
46107
+ return;
46108
+ }
46109
+ const minted = await mintVirtualResource(builder, kind, type, name, metadata);
46110
+ if (!minted)
46111
+ return;
46896
46112
  result.created++;
46897
46113
  logger.info(`Created ${kind} "${name}" in solution`);
46898
46114
  if (!virtualizable) {
@@ -46901,7 +46117,7 @@ async function createVirtualForBinding(builder, _binding, kind, type, metadata,
46901
46117
  logger.warn(warning);
46902
46118
  }
46903
46119
  }
46904
- async function findResourceByKeyInRcs(builder, kind, expectedKey, folderPath) {
46120
+ async function findResourceByKeyInRcs(builder, kind, expectedKey, folderPath, propagateErrors = false) {
46905
46121
  const expectedLower = expectedKey.toLowerCase();
46906
46122
  const normalizedFolder = normalizeFolderPath(folderPath);
46907
46123
  const mismatchedFolders = [];
@@ -46909,6 +46125,9 @@ async function findResourceByKeyInRcs(builder, kind, expectedKey, folderPath) {
46909
46125
  do {
46910
46126
  const [searchError, result] = await catchError(builder.searchResourcesAsync(kind, undefined, undefined, pageCursor, 100, undefined, false));
46911
46127
  if (searchError) {
46128
+ if (propagateErrors) {
46129
+ throw searchError;
46130
+ }
46912
46131
  logger.warn(`Failed to search ${kind} resources in RCS: ${searchError.message}`);
46913
46132
  return;
46914
46133
  }
@@ -46918,6 +46137,7 @@ async function findResourceByKeyInRcs(builder, kind, expectedKey, folderPath) {
46918
46137
  const match = {
46919
46138
  key: resource.key,
46920
46139
  name: resource.name,
46140
+ type: resource.type,
46921
46141
  folder: {
46922
46142
  fullyQualifiedName: folderResources.fullyQualifiedName,
46923
46143
  folderKey: folderResources.key,
@@ -46951,8 +46171,8 @@ async function searchRcsResources(builder, kind, name) {
46951
46171
  return [];
46952
46172
  }
46953
46173
  for (const folderResources of result.availableResources) {
46954
- const match = folderResources.resources.find((r) => r.name.toLowerCase() === name.toLowerCase());
46955
- if (match) {
46174
+ const matches = folderResources.resources.filter((r) => r.name.toLowerCase() === name.toLowerCase());
46175
+ for (const match of matches) {
46956
46176
  allMatches.push({
46957
46177
  key: match.key,
46958
46178
  name: match.name,
@@ -46979,9 +46199,13 @@ async function findResourceInRcs(builder, kind, name, folderPath) {
46979
46199
  }
46980
46200
  const normalized = normalizeFolderPath(folderPath);
46981
46201
  if (normalized) {
46982
- const folderMatch = allMatches.find((m) => m.folder?.fullyQualifiedName?.toLowerCase() === normalized);
46983
- if (folderMatch) {
46984
- return folderMatch;
46202
+ const inFolder = allMatches.filter((m) => m.folder?.fullyQualifiedName?.toLowerCase() === normalized);
46203
+ if (inFolder.length === 1) {
46204
+ return inFolder[0];
46205
+ }
46206
+ if (inFolder.length > 1) {
46207
+ logger.warn(`Found ${inFolder.length} ${kind} resources named "${name}" in folder "${folderPath}" (same name, different subtype). Marking unresolved.`);
46208
+ return;
46985
46209
  }
46986
46210
  logger.warn(`Found ${allMatches.length} ${kind} resources named "${name}", none in folder "${folderPath}". Marking unresolved.`);
46987
46211
  return;
@@ -47213,3 +46437,5 @@ async function resourceRefreshAsync(solutionPath = ".", options = {}) {
47213
46437
  export {
47214
46438
  resourceRefreshAsync
47215
46439
  };
46440
+
46441
+ //# debugId=B16417EB1BA06B7F64756E2164756E21