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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/index.js +895 -1930
  2. package/dist/tool.js +880 -1914
  3. package/package.json +2 -2
package/dist/tool.js CHANGED
@@ -11427,8 +11427,8 @@ var require_Subscription = __commonJS((exports) => {
11427
11427
  if (_parentOrParents instanceof Subscription2) {
11428
11428
  _parentOrParents.remove(this);
11429
11429
  } else if (_parentOrParents !== null) {
11430
- for (var index2 = 0;index2 < _parentOrParents.length; ++index2) {
11431
- var parent_1 = _parentOrParents[index2];
11430
+ for (var index = 0;index < _parentOrParents.length; ++index) {
11431
+ var parent_1 = _parentOrParents[index];
11432
11432
  parent_1.remove(this);
11433
11433
  }
11434
11434
  }
@@ -11443,10 +11443,10 @@ var require_Subscription = __commonJS((exports) => {
11443
11443
  }
11444
11444
  }
11445
11445
  if (isArray_1.isArray(_subscriptions)) {
11446
- var index2 = -1;
11446
+ var index = -1;
11447
11447
  var len = _subscriptions.length;
11448
- while (++index2 < len) {
11449
- var sub2 = _subscriptions[index2];
11448
+ while (++index < len) {
11449
+ var sub2 = _subscriptions[index];
11450
11450
  if (isObject_1.isObject(sub2)) {
11451
11451
  try {
11452
11452
  sub2.unsubscribe();
@@ -12876,13 +12876,13 @@ var require_AsyncAction = __commonJS((exports) => {
12876
12876
  var id = this.id;
12877
12877
  var scheduler = this.scheduler;
12878
12878
  var actions = scheduler.actions;
12879
- var index2 = actions.indexOf(this);
12879
+ var index = actions.indexOf(this);
12880
12880
  this.work = null;
12881
12881
  this.state = null;
12882
12882
  this.pending = false;
12883
12883
  this.scheduler = null;
12884
- if (index2 !== -1) {
12885
- actions.splice(index2, 1);
12884
+ if (index !== -1) {
12885
+ actions.splice(index, 1);
12886
12886
  }
12887
12887
  if (id != null) {
12888
12888
  this.id = this.recycleAsyncId(scheduler, id, null);
@@ -13726,17 +13726,17 @@ var require_AsapScheduler = __commonJS((exports) => {
13726
13726
  this.scheduled = undefined;
13727
13727
  var actions = this.actions;
13728
13728
  var error;
13729
- var index2 = -1;
13729
+ var index = -1;
13730
13730
  var count = actions.length;
13731
13731
  action = action || actions.shift();
13732
13732
  do {
13733
13733
  if (error = action.execute(action.state, action.delay)) {
13734
13734
  break;
13735
13735
  }
13736
- } while (++index2 < count && (action = actions.shift()));
13736
+ } while (++index < count && (action = actions.shift()));
13737
13737
  this.active = false;
13738
13738
  if (error) {
13739
- while (++index2 < count && (action = actions.shift())) {
13739
+ while (++index < count && (action = actions.shift())) {
13740
13740
  action.unsubscribe();
13741
13741
  }
13742
13742
  throw error;
@@ -13859,17 +13859,17 @@ var require_AnimationFrameScheduler = __commonJS((exports) => {
13859
13859
  this.scheduled = undefined;
13860
13860
  var actions = this.actions;
13861
13861
  var error;
13862
- var index2 = -1;
13862
+ var index = -1;
13863
13863
  var count = actions.length;
13864
13864
  action = action || actions.shift();
13865
13865
  do {
13866
13866
  if (error = action.execute(action.state, action.delay)) {
13867
13867
  break;
13868
13868
  }
13869
- } while (++index2 < count && (action = actions.shift()));
13869
+ } while (++index < count && (action = actions.shift()));
13870
13870
  this.active = false;
13871
13871
  if (error) {
13872
- while (++index2 < count && (action = actions.shift())) {
13872
+ while (++index < count && (action = actions.shift())) {
13873
13873
  action.unsubscribe();
13874
13874
  }
13875
13875
  throw error;
@@ -13953,16 +13953,16 @@ var require_VirtualTimeScheduler = __commonJS((exports) => {
13953
13953
  exports.VirtualTimeScheduler = VirtualTimeScheduler;
13954
13954
  var VirtualAction = function(_super) {
13955
13955
  __extends(VirtualAction2, _super);
13956
- function VirtualAction2(scheduler, work, index2) {
13957
- if (index2 === undefined) {
13958
- index2 = scheduler.index += 1;
13956
+ function VirtualAction2(scheduler, work, index) {
13957
+ if (index === undefined) {
13958
+ index = scheduler.index += 1;
13959
13959
  }
13960
13960
  var _this = _super.call(this, scheduler, work) || this;
13961
13961
  _this.scheduler = scheduler;
13962
13962
  _this.work = work;
13963
- _this.index = index2;
13963
+ _this.index = index;
13964
13964
  _this.active = true;
13965
- _this.index = scheduler.index = index2;
13965
+ _this.index = scheduler.index = index;
13966
13966
  return _this;
13967
13967
  }
13968
13968
  VirtualAction2.prototype.schedule = function(state, delay) {
@@ -15109,9 +15109,9 @@ var require_mergeMap = __commonJS((exports) => {
15109
15109
  };
15110
15110
  MergeMapSubscriber2.prototype._tryNext = function(value) {
15111
15111
  var result;
15112
- var index2 = this.index++;
15112
+ var index = this.index++;
15113
15113
  try {
15114
- result = this.project(value, index2);
15114
+ result = this.project(value, index);
15115
15115
  } catch (err) {
15116
15116
  this.destination.error(err);
15117
15117
  return;
@@ -15691,12 +15691,12 @@ var require_pairs2 = __commonJS((exports) => {
15691
15691
  }
15692
15692
  exports.pairs = pairs;
15693
15693
  function dispatch(state) {
15694
- var { keys, index: index2, subscriber, subscription, obj } = state;
15694
+ var { keys, index, subscriber, subscription, obj } = state;
15695
15695
  if (!subscriber.closed) {
15696
- if (index2 < keys.length) {
15697
- var key = keys[index2];
15696
+ if (index < keys.length) {
15697
+ var key = keys[index];
15698
15698
  subscriber.next([key, obj[key]]);
15699
- subscription.add(this.schedule({ keys, index: index2 + 1, subscriber, subscription, obj }));
15699
+ subscription.add(this.schedule({ keys, index: index + 1, subscriber, subscription, obj }));
15700
15700
  } else {
15701
15701
  subscriber.complete();
15702
15702
  }
@@ -15909,18 +15909,18 @@ var require_range = __commonJS((exports) => {
15909
15909
  count = start;
15910
15910
  start = 0;
15911
15911
  }
15912
- var index2 = 0;
15912
+ var index = 0;
15913
15913
  var current = start;
15914
15914
  if (scheduler) {
15915
15915
  return scheduler.schedule(dispatch, 0, {
15916
- index: index2,
15916
+ index,
15917
15917
  count,
15918
15918
  start,
15919
15919
  subscriber
15920
15920
  });
15921
15921
  } else {
15922
15922
  do {
15923
- if (index2++ >= count) {
15923
+ if (index++ >= count) {
15924
15924
  subscriber.complete();
15925
15925
  break;
15926
15926
  }
@@ -15935,8 +15935,8 @@ var require_range = __commonJS((exports) => {
15935
15935
  }
15936
15936
  exports.range = range;
15937
15937
  function dispatch(state) {
15938
- var { start, index: index2, count, subscriber } = state;
15939
- if (index2 >= count) {
15938
+ var { start, index, count, subscriber } = state;
15939
+ if (index >= count) {
15940
15940
  subscriber.complete();
15941
15941
  return;
15942
15942
  }
@@ -15944,7 +15944,7 @@ var require_range = __commonJS((exports) => {
15944
15944
  if (subscriber.closed) {
15945
15945
  return;
15946
15946
  }
15947
- state.index = index2 + 1;
15947
+ state.index = index + 1;
15948
15948
  state.start = start + 1;
15949
15949
  this.schedule(state);
15950
15950
  }
@@ -15982,14 +15982,14 @@ var require_timer = __commonJS((exports) => {
15982
15982
  }
15983
15983
  exports.timer = timer;
15984
15984
  function dispatch(state) {
15985
- var { index: index2, period, subscriber } = state;
15986
- subscriber.next(index2);
15985
+ var { index, period, subscriber } = state;
15986
+ subscriber.next(index);
15987
15987
  if (subscriber.closed) {
15988
15988
  return;
15989
15989
  } else if (period === -1) {
15990
15990
  return subscriber.complete();
15991
15991
  }
15992
- state.index = index2 + 1;
15992
+ state.index = index + 1;
15993
15993
  this.schedule(state, period);
15994
15994
  }
15995
15995
  });
@@ -19137,7 +19137,7 @@ var init_server = __esm(() => {
19137
19137
  var package_default = {
19138
19138
  name: "@uipath/resourcecatalog-tool",
19139
19139
  license: "MIT",
19140
- version: "1.196.0",
19140
+ version: "1.197.0-preview.59",
19141
19141
  description: "CLI plugin for the UiPath Resource Catalog Service.",
19142
19142
  private: false,
19143
19143
  repository: {
@@ -19163,7 +19163,7 @@ var package_default = {
19163
19163
  "dist"
19164
19164
  ],
19165
19165
  scripts: {
19166
- build: "bun build ./src/tool.ts --outdir dist --format esm --target node --external commander && bun build ./src/index.ts --outdir dist --format esm --target node",
19166
+ build: "bun build ./src/tool.ts --outdir dist --format esm --target node --external commander --sourcemap=linked && bun build ./src/index.ts --outdir dist --format esm --target node --sourcemap=linked",
19167
19167
  package: "bun run build && bun pm pack",
19168
19168
  lint: "biome check .",
19169
19169
  "lint:fix": "biome check --write .",
@@ -19226,27 +19226,54 @@ var NETWORK_ERROR_CODES = new Set([
19226
19226
  "ENETUNREACH",
19227
19227
  "EAI_FAIL"
19228
19228
  ]);
19229
- function isHtmlDocument(body) {
19230
- return /^\s*(<!doctype html|<html\b)/i.test(body);
19231
- }
19232
- function extractNetworkErrorCode(error) {
19233
- if (error === null || typeof error !== "object") {
19234
- return;
19235
- }
19236
- const err = error;
19237
- const code = typeof err.code === "string" ? err.code : undefined;
19238
- if (code && NETWORK_ERROR_CODES.has(code)) {
19239
- return code;
19240
- }
19241
- const cause = err.cause;
19242
- if (cause !== null && typeof cause === "object") {
19243
- const causeCode = cause.code;
19244
- if (typeof causeCode === "string" && NETWORK_ERROR_CODES.has(causeCode)) {
19245
- return causeCode;
19229
+ var TLS_ERROR_CODES = new Set([
19230
+ "SELF_SIGNED_CERT_IN_CHAIN",
19231
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
19232
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
19233
+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
19234
+ "UNABLE_TO_GET_ISSUER_CERT",
19235
+ "CERT_HAS_EXPIRED",
19236
+ "CERT_UNTRUSTED",
19237
+ "ERR_TLS_CERT_ALTNAME_INVALID"
19238
+ ]);
19239
+ 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.";
19240
+ 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.";
19241
+ function describeConnectivityError(error) {
19242
+ let current = error;
19243
+ for (let depth = 0;depth < 5 && current !== null && typeof current === "object"; depth++) {
19244
+ const cur = current;
19245
+ const code = typeof cur.code === "string" ? cur.code : undefined;
19246
+ const message = typeof cur.message === "string" ? cur.message : undefined;
19247
+ if (code && TLS_ERROR_CODES.has(code)) {
19248
+ return {
19249
+ code,
19250
+ kind: "tls",
19251
+ message: message ?? code,
19252
+ instructions: TLS_INSTRUCTIONS
19253
+ };
19254
+ }
19255
+ if (code && NETWORK_ERROR_CODES.has(code)) {
19256
+ return {
19257
+ code,
19258
+ kind: "network",
19259
+ message: message ?? code,
19260
+ instructions: NETWORK_INSTRUCTIONS
19261
+ };
19246
19262
  }
19263
+ current = cur.cause;
19247
19264
  }
19248
19265
  return;
19249
19266
  }
19267
+ function parseHttpStatusFromMessage(message) {
19268
+ const match = /^HTTP\s+(\d{3})(?::|\s|-|$)/i.exec(message.trim());
19269
+ if (!match)
19270
+ return;
19271
+ const status = Number(match[1]);
19272
+ return Number.isInteger(status) && status >= 100 && status <= 599 ? status : undefined;
19273
+ }
19274
+ function isHtmlDocument(body) {
19275
+ return /^\s*(<!doctype html|<html\b)/i.test(body);
19276
+ }
19250
19277
  function retryHintForRetryAfter(seconds) {
19251
19278
  if (seconds <= 1) {
19252
19279
  return "RetryAfter1Second";
@@ -19287,15 +19314,28 @@ function classifyError(status, error) {
19287
19314
  if (status !== undefined && status >= 500 && status < 600) {
19288
19315
  return { errorCode: "server_error", retry: "RetryLater" };
19289
19316
  }
19290
- if (extractNetworkErrorCode(error)) {
19291
- return { errorCode: "network_error", retry: "RetryLater" };
19317
+ const connectivity = describeConnectivityError(error);
19318
+ if (connectivity) {
19319
+ return {
19320
+ errorCode: "network_error",
19321
+ retry: connectivity.kind === "tls" ? "RetryWillNotFix" : "RetryLater"
19322
+ };
19292
19323
  }
19293
19324
  return { errorCode: "unknown_error", retry: "RetryWillNotFix" };
19294
19325
  }
19326
+ function formatHttpStatusMessage(status, rawMessage, extractedMessage, inferredStatus) {
19327
+ if (extractedMessage) {
19328
+ return `HTTP ${status}: ${extractedMessage}`;
19329
+ }
19330
+ return inferredStatus !== undefined ? rawMessage : `HTTP ${status}: ${rawMessage}`;
19331
+ }
19295
19332
  async function extractErrorDetails(error, options) {
19296
19333
  const err = error !== null && error !== undefined && typeof error === "object" ? error : {};
19297
19334
  const response = err.response;
19298
- const status = err.status ?? response?.status;
19335
+ const rawMessage = typeof err.message === "string" ? err.message : "Unknown error";
19336
+ const explicitStatus = err.status ?? response?.status;
19337
+ const inferredStatus = explicitStatus === undefined ? parseHttpStatusFromMessage(rawMessage) : undefined;
19338
+ const status = explicitStatus ?? inferredStatus;
19299
19339
  const isSuccessfulResponse = status !== undefined && status >= 200 && status < 300;
19300
19340
  let rawBody;
19301
19341
  let extractedMessage;
@@ -19330,7 +19370,6 @@ async function extractErrorDetails(error, options) {
19330
19370
  }
19331
19371
  }
19332
19372
  }
19333
- const rawMessage = typeof err.message === "string" ? err.message : "Unknown error";
19334
19373
  let message;
19335
19374
  let result = "Failure";
19336
19375
  const classification = classifyError(status, error);
@@ -19344,10 +19383,10 @@ async function extractErrorDetails(error, options) {
19344
19383
  } else if (status === 405) {
19345
19384
  message = DEFAULT_405;
19346
19385
  } else if (status === 400 || status === 422) {
19347
- message = extractedMessage ? `HTTP ${status}: ${extractedMessage}` : `HTTP ${status}: ${rawMessage}`;
19386
+ message = formatHttpStatusMessage(status, rawMessage, extractedMessage, inferredStatus);
19348
19387
  result = "ValidationError";
19349
19388
  } else if (status === 429) {
19350
- message = extractedMessage ? `HTTP ${status}: ${extractedMessage}` : `HTTP ${status}: ${rawMessage}`;
19389
+ message = formatHttpStatusMessage(status, rawMessage, extractedMessage, inferredStatus);
19351
19390
  } else if (extractedMessage) {
19352
19391
  if (isSuccessfulResponse && rawMessage !== "Unknown error") {
19353
19392
  message = rawMessage;
@@ -19355,7 +19394,9 @@ async function extractErrorDetails(error, options) {
19355
19394
  message = status ? `HTTP ${status}: ${extractedMessage}` : extractedMessage;
19356
19395
  }
19357
19396
  } else if (status) {
19358
- if (rawMessage === "Unknown error" && response) {
19397
+ if (inferredStatus !== undefined) {
19398
+ message = rawMessage;
19399
+ } else if (rawMessage === "Unknown error" && response) {
19359
19400
  const statusText = response.statusText;
19360
19401
  message = statusText ? `HTTP ${status} ${statusText}` : `HTTP ${status} - request failed`;
19361
19402
  } else {
@@ -19364,6 +19405,12 @@ async function extractErrorDetails(error, options) {
19364
19405
  } else {
19365
19406
  message = rawMessage;
19366
19407
  }
19408
+ if (status === undefined) {
19409
+ const connectivity = describeConnectivityError(error);
19410
+ if (connectivity && connectivity.message !== message && !message.includes(connectivity.message)) {
19411
+ message = `${message}: ${connectivity.message}`;
19412
+ }
19413
+ }
19367
19414
  let details = rawMessage;
19368
19415
  if (rawBody) {
19369
19416
  if (parsedBody) {
@@ -19516,6 +19563,7 @@ var CONSOLE_FALLBACK = {
19516
19563
  writeLog: (str) => process.stdout.write(str),
19517
19564
  capabilities: {
19518
19565
  isInteractive: false,
19566
+ canReadInput: false,
19519
19567
  supportsColor: false,
19520
19568
  outputWidth: 80
19521
19569
  }
@@ -24716,6 +24764,29 @@ function isPlainRecord(value) {
24716
24764
  const prototype = Object.getPrototypeOf(value);
24717
24765
  return prototype === Object.prototype || prototype === null;
24718
24766
  }
24767
+ function extractPagedRows(value) {
24768
+ if (Array.isArray(value) || !isPlainRecord(value))
24769
+ return null;
24770
+ const entries = Object.values(value);
24771
+ if (entries.length === 0)
24772
+ return null;
24773
+ let rows = null;
24774
+ let hasScalarSibling = false;
24775
+ for (const entry of entries) {
24776
+ if (Array.isArray(entry)) {
24777
+ if (rows !== null)
24778
+ return null;
24779
+ rows = entry;
24780
+ } else if (entry !== null && typeof entry === "object") {
24781
+ return null;
24782
+ } else {
24783
+ hasScalarSibling = true;
24784
+ }
24785
+ }
24786
+ if (rows === null || !hasScalarSibling)
24787
+ return null;
24788
+ return rows;
24789
+ }
24719
24790
  function toLowerCamelCaseKey(key) {
24720
24791
  if (!key)
24721
24792
  return key;
@@ -24780,7 +24851,8 @@ function printOutput(data, format = "json", logFn, asciiSafe = false) {
24780
24851
  break;
24781
24852
  case "plain": {
24782
24853
  if ("Data" in data && data.Data != null) {
24783
- const items = Array.isArray(data.Data) ? data.Data : [data.Data];
24854
+ const pagedRows = extractPagedRows(data.Data);
24855
+ const items = pagedRows ?? (Array.isArray(data.Data) ? data.Data : [data.Data]);
24784
24856
  items.forEach((item) => {
24785
24857
  const values = Object.values(item).map((v) => v ?? "").join("\t");
24786
24858
  logFn(values);
@@ -24792,10 +24864,13 @@ function printOutput(data, format = "json", logFn, asciiSafe = false) {
24792
24864
  break;
24793
24865
  }
24794
24866
  default: {
24795
- if ("Data" in data && data.Data != null && !(Array.isArray(data.Data) && data.Data.length === 0)) {
24867
+ const hasData = "Data" in data && data.Data != null;
24868
+ const pagedRows = hasData ? extractPagedRows(data.Data) : null;
24869
+ const rows = pagedRows ? pagedRows : Array.isArray(data.Data) ? data.Data : null;
24870
+ if (hasData && !(rows !== null && rows.length === 0)) {
24796
24871
  const logValue = data.Log;
24797
- if (Array.isArray(data.Data)) {
24798
- printResizableTable(data.Data, logFn, logValue);
24872
+ if (rows !== null) {
24873
+ printResizableTable(rows, logFn, logValue);
24799
24874
  } else {
24800
24875
  printVerticalTable(data.Data, logFn, logValue);
24801
24876
  }
@@ -24983,6 +25058,44 @@ function defaultErrorCodeForResult(result) {
24983
25058
  return "unknown_error";
24984
25059
  }
24985
25060
  }
25061
+ function parseHttpStatusFromMessage2(message) {
25062
+ const match = /^HTTP\s+(\d{3})(?::|\s|-|$)/i.exec(message.trim());
25063
+ if (!match)
25064
+ return;
25065
+ const status = Number(match[1]);
25066
+ return Number.isInteger(status) && status >= 100 && status <= 599 ? status : undefined;
25067
+ }
25068
+ function defaultErrorCodeForHttpStatus(status) {
25069
+ if (status === undefined)
25070
+ return;
25071
+ if (status === 400 || status === 409 || status === 422) {
25072
+ return "invalid_argument";
25073
+ }
25074
+ if (status === 401)
25075
+ return "authentication_required";
25076
+ if (status === 403)
25077
+ return "permission_denied";
25078
+ if (status === 404)
25079
+ return "not_found";
25080
+ if (status === 405)
25081
+ return "method_not_allowed";
25082
+ if (status === 408)
25083
+ return "timeout";
25084
+ if (status === 429)
25085
+ return "rate_limited";
25086
+ if (status >= 500 && status < 600)
25087
+ return "server_error";
25088
+ return;
25089
+ }
25090
+ function defaultErrorCodeForFailure(data) {
25091
+ if (data.Result === RESULTS.Failure) {
25092
+ const status = data.Context?.httpStatus ?? parseHttpStatusFromMessage2(data.Message);
25093
+ const errorCode = defaultErrorCodeForHttpStatus(status);
25094
+ if (errorCode)
25095
+ return errorCode;
25096
+ }
25097
+ return defaultErrorCodeForResult(data.Result);
25098
+ }
24986
25099
  function defaultRetryForErrorCode(errorCode) {
24987
25100
  switch (errorCode) {
24988
25101
  case "network_error":
@@ -25012,16 +25125,19 @@ var OutputFormatter;
25012
25125
  OutputFormatter.success = success;
25013
25126
  function error(data) {
25014
25127
  data.Log ??= getLogFilePath() || undefined;
25015
- data.ErrorCode ??= defaultErrorCodeForResult(data.Result);
25128
+ data.ErrorCode ??= defaultErrorCodeForFailure(data);
25016
25129
  data.Retry ??= defaultRetryForErrorCode(data.ErrorCode);
25017
25130
  process.exitCode = EXIT_CODES[data.Result] ?? 1;
25018
- telemetry.trackEvent(CommonTelemetryEvents.Error, {
25019
- result: data.Result,
25020
- errorCode: data.ErrorCode,
25021
- retry: data.Retry,
25022
- message: data.Message
25023
- });
25024
- logOutput(normalizeOutputKeys(data), getOutputFormat());
25131
+ const { SuppressTelemetry, ...envelope } = data;
25132
+ if (!SuppressTelemetry) {
25133
+ telemetry.trackEvent(CommonTelemetryEvents.Error, {
25134
+ result: data.Result,
25135
+ errorCode: data.ErrorCode,
25136
+ retry: data.Retry,
25137
+ message: data.Message
25138
+ });
25139
+ }
25140
+ logOutput(normalizeOutputKeys(envelope), getOutputFormat());
25025
25141
  }
25026
25142
  OutputFormatter.error = error;
25027
25143
  function emitList(code, items, opts) {
@@ -25315,1644 +25431,228 @@ var DEFAULT_PAGE_SIZE = 50;
25315
25431
  var DEFAULT_AUTH_TIMEOUT_MS = 5 * 60 * 1000;
25316
25432
  // ../../common/src/interactivity-context.ts
25317
25433
  var modeSlot = singleton("InteractivityMode");
25318
- // ../../../node_modules/jsonpath-plus/dist/index-node-esm.js
25319
- import vm from "vm";
25320
-
25321
- class Hooks {
25322
- add(name, callback, first) {
25323
- if (typeof arguments[0] != "string") {
25324
- for (let name2 in arguments[0]) {
25325
- this.add(name2, arguments[0][name2], arguments[1]);
25434
+ // ../../common/src/option-aliases.ts
25435
+ import { Option } from "commander";
25436
+ function resolveDeprecatedOptionAlias({
25437
+ preferredValue,
25438
+ deprecatedValue,
25439
+ preferredFlag,
25440
+ deprecatedFlag
25441
+ }) {
25442
+ const hasPreferred = preferredValue !== undefined;
25443
+ const hasDeprecated = deprecatedValue !== undefined;
25444
+ if (hasPreferred && hasDeprecated) {
25445
+ return {
25446
+ value: undefined,
25447
+ usedDeprecated: true,
25448
+ error: {
25449
+ message: `${deprecatedFlag} and ${preferredFlag} are aliases. Use only ${preferredFlag}.`,
25450
+ instructions: `Replace ${deprecatedFlag} with ${preferredFlag}.`
25326
25451
  }
25327
- } else {
25328
- (Array.isArray(name) ? name : [name]).forEach(function(name2) {
25329
- this[name2] = this[name2] || [];
25330
- if (callback) {
25331
- this[name2][first ? "unshift" : "push"](callback);
25332
- }
25333
- }, this);
25334
- }
25335
- }
25336
- run(name, env) {
25337
- this[name] = this[name] || [];
25338
- this[name].forEach(function(callback) {
25339
- callback.call(env && env.context ? env.context : env, env);
25340
- });
25452
+ };
25341
25453
  }
25454
+ return {
25455
+ value: hasPreferred ? preferredValue : deprecatedValue,
25456
+ usedDeprecated: hasDeprecated
25457
+ };
25342
25458
  }
25343
-
25344
- class Plugins {
25345
- constructor(jsep) {
25346
- this.jsep = jsep;
25347
- this.registered = {};
25348
- }
25349
- register(...plugins) {
25350
- plugins.forEach((plugin) => {
25351
- if (typeof plugin !== "object" || !plugin.name || !plugin.init) {
25352
- throw new Error("Invalid JSEP plugin format");
25353
- }
25354
- if (this.registered[plugin.name]) {
25355
- return;
25356
- }
25357
- plugin.init(this.jsep);
25358
- this.registered[plugin.name] = plugin;
25359
- });
25360
- }
25459
+ function warnDeprecatedOptionAlias(deprecatedFlag, preferredFlag) {
25460
+ getOutputSink().writeErr(`[WARN] ${deprecatedFlag} is deprecated. Use ${preferredFlag} instead.
25461
+ `);
25462
+ }
25463
+ var TENANT_SWITCH_COMMAND = "uip login tenant set <tenant>";
25464
+ function createHiddenDeprecatedTenantOption(flags = "-t, --tenant <tenant-name>") {
25465
+ return new Option(flags, `Tenant name. Deprecated; use ${TENANT_SWITCH_COMMAND} to switch active tenants.`).hideHelp().argParser((tenant) => {
25466
+ warnDeprecatedTenantOption(tenant);
25467
+ return tenant;
25468
+ });
25469
+ }
25470
+ function warnDeprecatedTenantOption(tenant) {
25471
+ if (tenant === undefined)
25472
+ return;
25473
+ warnDeprecatedOptionAlias("--tenant", TENANT_SWITCH_COMMAND);
25361
25474
  }
25475
+ // ../../common/src/option-validators.ts
25476
+ import { InvalidArgumentError } from "commander";
25477
+ // ../../common/src/polling/types.ts
25478
+ var PollOutcome = {
25479
+ Completed: "completed",
25480
+ Timeout: "timeout",
25481
+ Interrupted: "interrupted",
25482
+ Aborted: "aborted",
25483
+ Failed: "failed"
25484
+ };
25362
25485
 
25363
- class Jsep {
25364
- static get version() {
25365
- return "1.4.0";
25366
- }
25367
- static toString() {
25368
- return "JavaScript Expression Parser (JSEP) v" + Jsep.version;
25369
- }
25370
- static addUnaryOp(op_name) {
25371
- Jsep.max_unop_len = Math.max(op_name.length, Jsep.max_unop_len);
25372
- Jsep.unary_ops[op_name] = 1;
25373
- return Jsep;
25374
- }
25375
- static addBinaryOp(op_name, precedence, isRightAssociative) {
25376
- Jsep.max_binop_len = Math.max(op_name.length, Jsep.max_binop_len);
25377
- Jsep.binary_ops[op_name] = precedence;
25378
- if (isRightAssociative) {
25379
- Jsep.right_associative.add(op_name);
25380
- } else {
25381
- Jsep.right_associative.delete(op_name);
25382
- }
25383
- return Jsep;
25384
- }
25385
- static addIdentifierChar(char) {
25386
- Jsep.additional_identifier_chars.add(char);
25387
- return Jsep;
25388
- }
25389
- static addLiteral(literal_name, literal_value) {
25390
- Jsep.literals[literal_name] = literal_value;
25391
- return Jsep;
25392
- }
25393
- static removeUnaryOp(op_name) {
25394
- delete Jsep.unary_ops[op_name];
25395
- if (op_name.length === Jsep.max_unop_len) {
25396
- Jsep.max_unop_len = Jsep.getMaxKeyLen(Jsep.unary_ops);
25397
- }
25398
- return Jsep;
25399
- }
25400
- static removeAllUnaryOps() {
25401
- Jsep.unary_ops = {};
25402
- Jsep.max_unop_len = 0;
25403
- return Jsep;
25486
+ // ../../common/src/polling/poll-failure-mapping.ts
25487
+ var REASON_BY_OUTCOME = {
25488
+ [PollOutcome.Timeout]: "poll_timeout",
25489
+ [PollOutcome.Failed]: "poll_failed",
25490
+ [PollOutcome.Interrupted]: "poll_failed",
25491
+ [PollOutcome.Aborted]: "poll_aborted"
25492
+ };
25493
+ // ../../common/src/polling/terminal-statuses.ts
25494
+ var TERMINAL_STATUSES = new Set([
25495
+ "completed",
25496
+ "successful",
25497
+ "faulted",
25498
+ "failed",
25499
+ "cancelled",
25500
+ "canceled",
25501
+ "stopped",
25502
+ "finished"
25503
+ ]);
25504
+ var FAILURE_STATUSES = new Set([
25505
+ "faulted",
25506
+ "failed",
25507
+ "cancelled",
25508
+ "canceled",
25509
+ "stopped"
25510
+ ]);
25511
+ // ../../common/src/preview.ts
25512
+ import { Command as Command3 } from "commander";
25513
+ var previewSlot = singleton("PreviewBuild");
25514
+ function isPreviewBuild() {
25515
+ return previewSlot.get(false) ?? false;
25516
+ }
25517
+ Command3.prototype.previewCommand = function(nameAndArgs, opts) {
25518
+ if (isPreviewBuild()) {
25519
+ return this.command(nameAndArgs, opts);
25404
25520
  }
25405
- static removeIdentifierChar(char) {
25406
- Jsep.additional_identifier_chars.delete(char);
25407
- return Jsep;
25521
+ return new Command3(nameAndArgs.split(/\s+/)[0] ?? nameAndArgs);
25522
+ };
25523
+ // ../../common/src/screen-logger.ts
25524
+ var ScreenLogger;
25525
+ ((ScreenLogger) => {
25526
+ function progress(message) {
25527
+ getOutputSink().writeErr(`${message}
25528
+ `);
25408
25529
  }
25409
- static removeBinaryOp(op_name) {
25410
- delete Jsep.binary_ops[op_name];
25411
- if (op_name.length === Jsep.max_binop_len) {
25412
- Jsep.max_binop_len = Jsep.getMaxKeyLen(Jsep.binary_ops);
25530
+ ScreenLogger.progress = progress;
25531
+ })(ScreenLogger ||= {});
25532
+ // ../../common/src/sdk-user-agent.ts
25533
+ var USER_AGENT_HEADER = "User-Agent";
25534
+ var sdkUserAgentHostToken = singleton("SdkUserAgentHostToken");
25535
+ function userAgentPatchKey(userAgent) {
25536
+ return Symbol.for(`@uipath/common/sdk-user-agent/${userAgent}`);
25537
+ }
25538
+ function splitUserAgentTokens(value) {
25539
+ return value?.trim().split(/\s+/).filter(Boolean) ?? [];
25540
+ }
25541
+ function appendUserAgentToken(value, userAgent) {
25542
+ const tokens = splitUserAgentTokens(value);
25543
+ const seen = new Set(tokens);
25544
+ for (const token of splitUserAgentTokens(userAgent)) {
25545
+ if (!seen.has(token)) {
25546
+ tokens.push(token);
25547
+ seen.add(token);
25413
25548
  }
25414
- Jsep.right_associative.delete(op_name);
25415
- return Jsep;
25416
25549
  }
25417
- static removeAllBinaryOps() {
25418
- Jsep.binary_ops = {};
25419
- Jsep.max_binop_len = 0;
25420
- return Jsep;
25421
- }
25422
- static removeLiteral(literal_name) {
25423
- delete Jsep.literals[literal_name];
25424
- return Jsep;
25425
- }
25426
- static removeAllLiterals() {
25427
- Jsep.literals = {};
25428
- return Jsep;
25429
- }
25430
- get char() {
25431
- return this.expr.charAt(this.index);
25550
+ return tokens.join(" ");
25551
+ }
25552
+ function getEffectiveUserAgent(userAgent) {
25553
+ return appendUserAgentToken(sdkUserAgentHostToken.get(), userAgent);
25554
+ }
25555
+ function getHeaderName(headers, headerName) {
25556
+ return Object.keys(headers).find((key) => key.toLowerCase() === headerName.toLowerCase());
25557
+ }
25558
+ function getSdkUserAgentToken(pkg) {
25559
+ const packageName = pkg.name.replace(/^@uipath\//, "");
25560
+ return getEffectiveUserAgent(`${packageName}/${pkg.version}`);
25561
+ }
25562
+ function addSdkUserAgentHeader(headers, userAgent) {
25563
+ const result = { ...headers ?? {} };
25564
+ const headerName = getHeaderName(result, USER_AGENT_HEADER);
25565
+ result[headerName ?? USER_AGENT_HEADER] = appendUserAgentToken(headerName ? result[headerName] : undefined, getEffectiveUserAgent(userAgent));
25566
+ return result;
25567
+ }
25568
+ function asHeaderRecord(headers) {
25569
+ return typeof headers === "object" && headers !== null ? { ...headers } : {};
25570
+ }
25571
+ function withForwardedHeadersInitOverride(initOverrides, forward) {
25572
+ return async (requestContext) => {
25573
+ const initWithHeaders = {
25574
+ ...requestContext.init,
25575
+ headers: forward(asHeaderRecord(requestContext.init.headers))
25576
+ };
25577
+ const override = typeof initOverrides === "function" ? await initOverrides({
25578
+ ...requestContext,
25579
+ init: initWithHeaders
25580
+ }) : initOverrides;
25581
+ return {
25582
+ ...override ?? {},
25583
+ headers: forward(asHeaderRecord(override?.headers ?? initWithHeaders.headers))
25584
+ };
25585
+ };
25586
+ }
25587
+ function installRequestHeaderForwarding(BaseApiClass, patchKey, forward) {
25588
+ const prototype = BaseApiClass.prototype;
25589
+ if (prototype[patchKey]) {
25590
+ return;
25432
25591
  }
25433
- get code() {
25434
- return this.expr.charCodeAt(this.index);
25592
+ if (typeof prototype.request !== "function") {
25593
+ throw new Error("Generated BaseAPI request function not found.");
25435
25594
  }
25436
- constructor(expr) {
25437
- this.expr = expr;
25438
- this.index = 0;
25595
+ const originalRequest = prototype.request;
25596
+ prototype.request = function requestWithForwardedHeaders(context, initOverrides) {
25597
+ return originalRequest.call(this, context, withForwardedHeadersInitOverride(initOverrides, forward));
25598
+ };
25599
+ Object.defineProperty(prototype, patchKey, {
25600
+ value: true
25601
+ });
25602
+ }
25603
+ function installSdkUserAgentHeader(BaseApiClass, userAgent) {
25604
+ installRequestHeaderForwarding(BaseApiClass, userAgentPatchKey(userAgent), (headers) => addSdkUserAgentHeader(headers, userAgent));
25605
+ }
25606
+ // ../../common/src/tool-provider.ts
25607
+ var factorySlot = singleton("PackagerFactoryProvider");
25608
+ // ../resourcecatalog-sdk/generated/src/runtime.ts
25609
+ var BASE_PATH = "http://localhost".replace(/\/+$/, "");
25610
+
25611
+ class Configuration {
25612
+ configuration;
25613
+ constructor(configuration = {}) {
25614
+ this.configuration = configuration;
25439
25615
  }
25440
- static parse(expr) {
25441
- return new Jsep(expr).parse();
25616
+ set config(configuration) {
25617
+ this.configuration = configuration;
25442
25618
  }
25443
- static getMaxKeyLen(obj) {
25444
- return Math.max(0, ...Object.keys(obj).map((k) => k.length));
25619
+ get basePath() {
25620
+ return this.configuration.basePath != null ? this.configuration.basePath : BASE_PATH;
25445
25621
  }
25446
- static isDecimalDigit(ch) {
25447
- return ch >= 48 && ch <= 57;
25622
+ get fetchApi() {
25623
+ return this.configuration.fetchApi;
25448
25624
  }
25449
- static binaryPrecedence(op_val) {
25450
- return Jsep.binary_ops[op_val] || 0;
25625
+ get middleware() {
25626
+ return this.configuration.middleware || [];
25451
25627
  }
25452
- static isIdentifierStart(ch) {
25453
- 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));
25628
+ get queryParamsStringify() {
25629
+ return this.configuration.queryParamsStringify || querystring;
25454
25630
  }
25455
- static isIdentifierPart(ch) {
25456
- return Jsep.isIdentifierStart(ch) || Jsep.isDecimalDigit(ch);
25631
+ get username() {
25632
+ return this.configuration.username;
25457
25633
  }
25458
- throwError(message) {
25459
- const error = new Error(message + " at character " + this.index);
25460
- error.index = this.index;
25461
- error.description = message;
25462
- throw error;
25634
+ get password() {
25635
+ return this.configuration.password;
25463
25636
  }
25464
- runHook(name, node) {
25465
- if (Jsep.hooks[name]) {
25466
- const env = {
25467
- context: this,
25468
- node
25469
- };
25470
- Jsep.hooks.run(name, env);
25471
- return env.node;
25637
+ get apiKey() {
25638
+ const apiKey = this.configuration.apiKey;
25639
+ if (apiKey) {
25640
+ return typeof apiKey === "function" ? apiKey : () => apiKey;
25472
25641
  }
25473
- return node;
25642
+ return;
25474
25643
  }
25475
- searchHook(name) {
25476
- if (Jsep.hooks[name]) {
25477
- const env = {
25478
- context: this
25479
- };
25480
- Jsep.hooks[name].find(function(callback) {
25481
- callback.call(env.context, env);
25482
- return env.node;
25483
- });
25484
- return env.node;
25644
+ get accessToken() {
25645
+ const accessToken = this.configuration.accessToken;
25646
+ if (accessToken) {
25647
+ return typeof accessToken === "function" ? accessToken : async () => accessToken;
25485
25648
  }
25649
+ return;
25486
25650
  }
25487
- gobbleSpaces() {
25488
- let ch = this.code;
25489
- while (ch === Jsep.SPACE_CODE || ch === Jsep.TAB_CODE || ch === Jsep.LF_CODE || ch === Jsep.CR_CODE) {
25490
- ch = this.expr.charCodeAt(++this.index);
25491
- }
25492
- this.runHook("gobble-spaces");
25651
+ get headers() {
25652
+ return this.configuration.headers;
25493
25653
  }
25494
- parse() {
25495
- this.runHook("before-all");
25496
- const nodes = this.gobbleExpressions();
25497
- const node = nodes.length === 1 ? nodes[0] : {
25498
- type: Jsep.COMPOUND,
25499
- body: nodes
25500
- };
25501
- return this.runHook("after-all", node);
25502
- }
25503
- gobbleExpressions(untilICode) {
25504
- let nodes = [], ch_i, node;
25505
- while (this.index < this.expr.length) {
25506
- ch_i = this.code;
25507
- if (ch_i === Jsep.SEMCOL_CODE || ch_i === Jsep.COMMA_CODE) {
25508
- this.index++;
25509
- } else {
25510
- if (node = this.gobbleExpression()) {
25511
- nodes.push(node);
25512
- } else if (this.index < this.expr.length) {
25513
- if (ch_i === untilICode) {
25514
- break;
25515
- }
25516
- this.throwError('Unexpected "' + this.char + '"');
25517
- }
25518
- }
25519
- }
25520
- return nodes;
25521
- }
25522
- gobbleExpression() {
25523
- const node = this.searchHook("gobble-expression") || this.gobbleBinaryExpression();
25524
- this.gobbleSpaces();
25525
- return this.runHook("after-expression", node);
25526
- }
25527
- gobbleBinaryOp() {
25528
- this.gobbleSpaces();
25529
- let to_check = this.expr.substr(this.index, Jsep.max_binop_len);
25530
- let tc_len = to_check.length;
25531
- while (tc_len > 0) {
25532
- 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)))) {
25533
- this.index += tc_len;
25534
- return to_check;
25535
- }
25536
- to_check = to_check.substr(0, --tc_len);
25537
- }
25538
- return false;
25539
- }
25540
- gobbleBinaryExpression() {
25541
- let node, biop, prec, stack, biop_info, left, right, i, cur_biop;
25542
- left = this.gobbleToken();
25543
- if (!left) {
25544
- return left;
25545
- }
25546
- biop = this.gobbleBinaryOp();
25547
- if (!biop) {
25548
- return left;
25549
- }
25550
- biop_info = {
25551
- value: biop,
25552
- prec: Jsep.binaryPrecedence(biop),
25553
- right_a: Jsep.right_associative.has(biop)
25554
- };
25555
- right = this.gobbleToken();
25556
- if (!right) {
25557
- this.throwError("Expected expression after " + biop);
25558
- }
25559
- stack = [left, biop_info, right];
25560
- while (biop = this.gobbleBinaryOp()) {
25561
- prec = Jsep.binaryPrecedence(biop);
25562
- if (prec === 0) {
25563
- this.index -= biop.length;
25564
- break;
25565
- }
25566
- biop_info = {
25567
- value: biop,
25568
- prec,
25569
- right_a: Jsep.right_associative.has(biop)
25570
- };
25571
- cur_biop = biop;
25572
- const comparePrev = (prev) => biop_info.right_a && prev.right_a ? prec > prev.prec : prec <= prev.prec;
25573
- while (stack.length > 2 && comparePrev(stack[stack.length - 2])) {
25574
- right = stack.pop();
25575
- biop = stack.pop().value;
25576
- left = stack.pop();
25577
- node = {
25578
- type: Jsep.BINARY_EXP,
25579
- operator: biop,
25580
- left,
25581
- right
25582
- };
25583
- stack.push(node);
25584
- }
25585
- node = this.gobbleToken();
25586
- if (!node) {
25587
- this.throwError("Expected expression after " + cur_biop);
25588
- }
25589
- stack.push(biop_info, node);
25590
- }
25591
- i = stack.length - 1;
25592
- node = stack[i];
25593
- while (i > 1) {
25594
- node = {
25595
- type: Jsep.BINARY_EXP,
25596
- operator: stack[i - 1].value,
25597
- left: stack[i - 2],
25598
- right: node
25599
- };
25600
- i -= 2;
25601
- }
25602
- return node;
25603
- }
25604
- gobbleToken() {
25605
- let ch, to_check, tc_len, node;
25606
- this.gobbleSpaces();
25607
- node = this.searchHook("gobble-token");
25608
- if (node) {
25609
- return this.runHook("after-token", node);
25610
- }
25611
- ch = this.code;
25612
- if (Jsep.isDecimalDigit(ch) || ch === Jsep.PERIOD_CODE) {
25613
- return this.gobbleNumericLiteral();
25614
- }
25615
- if (ch === Jsep.SQUOTE_CODE || ch === Jsep.DQUOTE_CODE) {
25616
- node = this.gobbleStringLiteral();
25617
- } else if (ch === Jsep.OBRACK_CODE) {
25618
- node = this.gobbleArray();
25619
- } else {
25620
- to_check = this.expr.substr(this.index, Jsep.max_unop_len);
25621
- tc_len = to_check.length;
25622
- while (tc_len > 0) {
25623
- 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)))) {
25624
- this.index += tc_len;
25625
- const argument = this.gobbleToken();
25626
- if (!argument) {
25627
- this.throwError("missing unaryOp argument");
25628
- }
25629
- return this.runHook("after-token", {
25630
- type: Jsep.UNARY_EXP,
25631
- operator: to_check,
25632
- argument,
25633
- prefix: true
25634
- });
25635
- }
25636
- to_check = to_check.substr(0, --tc_len);
25637
- }
25638
- if (Jsep.isIdentifierStart(ch)) {
25639
- node = this.gobbleIdentifier();
25640
- if (Jsep.literals.hasOwnProperty(node.name)) {
25641
- node = {
25642
- type: Jsep.LITERAL,
25643
- value: Jsep.literals[node.name],
25644
- raw: node.name
25645
- };
25646
- } else if (node.name === Jsep.this_str) {
25647
- node = {
25648
- type: Jsep.THIS_EXP
25649
- };
25650
- }
25651
- } else if (ch === Jsep.OPAREN_CODE) {
25652
- node = this.gobbleGroup();
25653
- }
25654
- }
25655
- if (!node) {
25656
- return this.runHook("after-token", false);
25657
- }
25658
- node = this.gobbleTokenProperty(node);
25659
- return this.runHook("after-token", node);
25660
- }
25661
- gobbleTokenProperty(node) {
25662
- this.gobbleSpaces();
25663
- let ch = this.code;
25664
- while (ch === Jsep.PERIOD_CODE || ch === Jsep.OBRACK_CODE || ch === Jsep.OPAREN_CODE || ch === Jsep.QUMARK_CODE) {
25665
- let optional;
25666
- if (ch === Jsep.QUMARK_CODE) {
25667
- if (this.expr.charCodeAt(this.index + 1) !== Jsep.PERIOD_CODE) {
25668
- break;
25669
- }
25670
- optional = true;
25671
- this.index += 2;
25672
- this.gobbleSpaces();
25673
- ch = this.code;
25674
- }
25675
- this.index++;
25676
- if (ch === Jsep.OBRACK_CODE) {
25677
- node = {
25678
- type: Jsep.MEMBER_EXP,
25679
- computed: true,
25680
- object: node,
25681
- property: this.gobbleExpression()
25682
- };
25683
- if (!node.property) {
25684
- this.throwError('Unexpected "' + this.char + '"');
25685
- }
25686
- this.gobbleSpaces();
25687
- ch = this.code;
25688
- if (ch !== Jsep.CBRACK_CODE) {
25689
- this.throwError("Unclosed [");
25690
- }
25691
- this.index++;
25692
- } else if (ch === Jsep.OPAREN_CODE) {
25693
- node = {
25694
- type: Jsep.CALL_EXP,
25695
- arguments: this.gobbleArguments(Jsep.CPAREN_CODE),
25696
- callee: node
25697
- };
25698
- } else if (ch === Jsep.PERIOD_CODE || optional) {
25699
- if (optional) {
25700
- this.index--;
25701
- }
25702
- this.gobbleSpaces();
25703
- node = {
25704
- type: Jsep.MEMBER_EXP,
25705
- computed: false,
25706
- object: node,
25707
- property: this.gobbleIdentifier()
25708
- };
25709
- }
25710
- if (optional) {
25711
- node.optional = true;
25712
- }
25713
- this.gobbleSpaces();
25714
- ch = this.code;
25715
- }
25716
- return node;
25717
- }
25718
- gobbleNumericLiteral() {
25719
- let number = "", ch, chCode;
25720
- while (Jsep.isDecimalDigit(this.code)) {
25721
- number += this.expr.charAt(this.index++);
25722
- }
25723
- if (this.code === Jsep.PERIOD_CODE) {
25724
- number += this.expr.charAt(this.index++);
25725
- while (Jsep.isDecimalDigit(this.code)) {
25726
- number += this.expr.charAt(this.index++);
25727
- }
25728
- }
25729
- ch = this.char;
25730
- if (ch === "e" || ch === "E") {
25731
- number += this.expr.charAt(this.index++);
25732
- ch = this.char;
25733
- if (ch === "+" || ch === "-") {
25734
- number += this.expr.charAt(this.index++);
25735
- }
25736
- while (Jsep.isDecimalDigit(this.code)) {
25737
- number += this.expr.charAt(this.index++);
25738
- }
25739
- if (!Jsep.isDecimalDigit(this.expr.charCodeAt(this.index - 1))) {
25740
- this.throwError("Expected exponent (" + number + this.char + ")");
25741
- }
25742
- }
25743
- chCode = this.code;
25744
- if (Jsep.isIdentifierStart(chCode)) {
25745
- this.throwError("Variable names cannot start with a number (" + number + this.char + ")");
25746
- } else if (chCode === Jsep.PERIOD_CODE || number.length === 1 && number.charCodeAt(0) === Jsep.PERIOD_CODE) {
25747
- this.throwError("Unexpected period");
25748
- }
25749
- return {
25750
- type: Jsep.LITERAL,
25751
- value: parseFloat(number),
25752
- raw: number
25753
- };
25754
- }
25755
- gobbleStringLiteral() {
25756
- let str = "";
25757
- const startIndex = this.index;
25758
- const quote = this.expr.charAt(this.index++);
25759
- let closed = false;
25760
- while (this.index < this.expr.length) {
25761
- let ch = this.expr.charAt(this.index++);
25762
- if (ch === quote) {
25763
- closed = true;
25764
- break;
25765
- } else if (ch === "\\") {
25766
- ch = this.expr.charAt(this.index++);
25767
- switch (ch) {
25768
- case "n":
25769
- str += `
25770
- `;
25771
- break;
25772
- case "r":
25773
- str += "\r";
25774
- break;
25775
- case "t":
25776
- str += "\t";
25777
- break;
25778
- case "b":
25779
- str += "\b";
25780
- break;
25781
- case "f":
25782
- str += "\f";
25783
- break;
25784
- case "v":
25785
- str += "\v";
25786
- break;
25787
- default:
25788
- str += ch;
25789
- }
25790
- } else {
25791
- str += ch;
25792
- }
25793
- }
25794
- if (!closed) {
25795
- this.throwError('Unclosed quote after "' + str + '"');
25796
- }
25797
- return {
25798
- type: Jsep.LITERAL,
25799
- value: str,
25800
- raw: this.expr.substring(startIndex, this.index)
25801
- };
25802
- }
25803
- gobbleIdentifier() {
25804
- let ch = this.code, start = this.index;
25805
- if (Jsep.isIdentifierStart(ch)) {
25806
- this.index++;
25807
- } else {
25808
- this.throwError("Unexpected " + this.char);
25809
- }
25810
- while (this.index < this.expr.length) {
25811
- ch = this.code;
25812
- if (Jsep.isIdentifierPart(ch)) {
25813
- this.index++;
25814
- } else {
25815
- break;
25816
- }
25817
- }
25818
- return {
25819
- type: Jsep.IDENTIFIER,
25820
- name: this.expr.slice(start, this.index)
25821
- };
25822
- }
25823
- gobbleArguments(termination) {
25824
- const args = [];
25825
- let closed = false;
25826
- let separator_count = 0;
25827
- while (this.index < this.expr.length) {
25828
- this.gobbleSpaces();
25829
- let ch_i = this.code;
25830
- if (ch_i === termination) {
25831
- closed = true;
25832
- this.index++;
25833
- if (termination === Jsep.CPAREN_CODE && separator_count && separator_count >= args.length) {
25834
- this.throwError("Unexpected token " + String.fromCharCode(termination));
25835
- }
25836
- break;
25837
- } else if (ch_i === Jsep.COMMA_CODE) {
25838
- this.index++;
25839
- separator_count++;
25840
- if (separator_count !== args.length) {
25841
- if (termination === Jsep.CPAREN_CODE) {
25842
- this.throwError("Unexpected token ,");
25843
- } else if (termination === Jsep.CBRACK_CODE) {
25844
- for (let arg = args.length;arg < separator_count; arg++) {
25845
- args.push(null);
25846
- }
25847
- }
25848
- }
25849
- } else if (args.length !== separator_count && separator_count !== 0) {
25850
- this.throwError("Expected comma");
25851
- } else {
25852
- const node = this.gobbleExpression();
25853
- if (!node || node.type === Jsep.COMPOUND) {
25854
- this.throwError("Expected comma");
25855
- }
25856
- args.push(node);
25857
- }
25858
- }
25859
- if (!closed) {
25860
- this.throwError("Expected " + String.fromCharCode(termination));
25861
- }
25862
- return args;
25863
- }
25864
- gobbleGroup() {
25865
- this.index++;
25866
- let nodes = this.gobbleExpressions(Jsep.CPAREN_CODE);
25867
- if (this.code === Jsep.CPAREN_CODE) {
25868
- this.index++;
25869
- if (nodes.length === 1) {
25870
- return nodes[0];
25871
- } else if (!nodes.length) {
25872
- return false;
25873
- } else {
25874
- return {
25875
- type: Jsep.SEQUENCE_EXP,
25876
- expressions: nodes
25877
- };
25878
- }
25879
- } else {
25880
- this.throwError("Unclosed (");
25881
- }
25882
- }
25883
- gobbleArray() {
25884
- this.index++;
25885
- return {
25886
- type: Jsep.ARRAY_EXP,
25887
- elements: this.gobbleArguments(Jsep.CBRACK_CODE)
25888
- };
25889
- }
25890
- }
25891
- var hooks = new Hooks;
25892
- Object.assign(Jsep, {
25893
- hooks,
25894
- plugins: new Plugins(Jsep),
25895
- COMPOUND: "Compound",
25896
- SEQUENCE_EXP: "SequenceExpression",
25897
- IDENTIFIER: "Identifier",
25898
- MEMBER_EXP: "MemberExpression",
25899
- LITERAL: "Literal",
25900
- THIS_EXP: "ThisExpression",
25901
- CALL_EXP: "CallExpression",
25902
- UNARY_EXP: "UnaryExpression",
25903
- BINARY_EXP: "BinaryExpression",
25904
- ARRAY_EXP: "ArrayExpression",
25905
- TAB_CODE: 9,
25906
- LF_CODE: 10,
25907
- CR_CODE: 13,
25908
- SPACE_CODE: 32,
25909
- PERIOD_CODE: 46,
25910
- COMMA_CODE: 44,
25911
- SQUOTE_CODE: 39,
25912
- DQUOTE_CODE: 34,
25913
- OPAREN_CODE: 40,
25914
- CPAREN_CODE: 41,
25915
- OBRACK_CODE: 91,
25916
- CBRACK_CODE: 93,
25917
- QUMARK_CODE: 63,
25918
- SEMCOL_CODE: 59,
25919
- COLON_CODE: 58,
25920
- unary_ops: {
25921
- "-": 1,
25922
- "!": 1,
25923
- "~": 1,
25924
- "+": 1
25925
- },
25926
- binary_ops: {
25927
- "||": 1,
25928
- "??": 1,
25929
- "&&": 2,
25930
- "|": 3,
25931
- "^": 4,
25932
- "&": 5,
25933
- "==": 6,
25934
- "!=": 6,
25935
- "===": 6,
25936
- "!==": 6,
25937
- "<": 7,
25938
- ">": 7,
25939
- "<=": 7,
25940
- ">=": 7,
25941
- "<<": 8,
25942
- ">>": 8,
25943
- ">>>": 8,
25944
- "+": 9,
25945
- "-": 9,
25946
- "*": 10,
25947
- "/": 10,
25948
- "%": 10,
25949
- "**": 11
25950
- },
25951
- right_associative: new Set(["**"]),
25952
- additional_identifier_chars: new Set(["$", "_"]),
25953
- literals: {
25954
- true: true,
25955
- false: false,
25956
- null: null
25957
- },
25958
- this_str: "this"
25959
- });
25960
- Jsep.max_unop_len = Jsep.getMaxKeyLen(Jsep.unary_ops);
25961
- Jsep.max_binop_len = Jsep.getMaxKeyLen(Jsep.binary_ops);
25962
- var jsep = (expr) => new Jsep(expr).parse();
25963
- var stdClassProps = Object.getOwnPropertyNames(class Test {
25964
- });
25965
- Object.getOwnPropertyNames(Jsep).filter((prop) => !stdClassProps.includes(prop) && jsep[prop] === undefined).forEach((m) => {
25966
- jsep[m] = Jsep[m];
25967
- });
25968
- jsep.Jsep = Jsep;
25969
- var CONDITIONAL_EXP = "ConditionalExpression";
25970
- var ternary = {
25971
- name: "ternary",
25972
- init(jsep2) {
25973
- jsep2.hooks.add("after-expression", function gobbleTernary(env) {
25974
- if (env.node && this.code === jsep2.QUMARK_CODE) {
25975
- this.index++;
25976
- const test = env.node;
25977
- const consequent = this.gobbleExpression();
25978
- if (!consequent) {
25979
- this.throwError("Expected expression");
25980
- }
25981
- this.gobbleSpaces();
25982
- if (this.code === jsep2.COLON_CODE) {
25983
- this.index++;
25984
- const alternate = this.gobbleExpression();
25985
- if (!alternate) {
25986
- this.throwError("Expected expression");
25987
- }
25988
- env.node = {
25989
- type: CONDITIONAL_EXP,
25990
- test,
25991
- consequent,
25992
- alternate
25993
- };
25994
- if (test.operator && jsep2.binary_ops[test.operator] <= 0.9) {
25995
- let newTest = test;
25996
- while (newTest.right.operator && jsep2.binary_ops[newTest.right.operator] <= 0.9) {
25997
- newTest = newTest.right;
25998
- }
25999
- env.node.test = newTest.right;
26000
- newTest.right = env.node;
26001
- env.node = test;
26002
- }
26003
- } else {
26004
- this.throwError("Expected :");
26005
- }
26006
- }
26007
- });
26008
- }
26009
- };
26010
- jsep.plugins.register(ternary);
26011
- var FSLASH_CODE = 47;
26012
- var BSLASH_CODE = 92;
26013
- var index = {
26014
- name: "regex",
26015
- init(jsep2) {
26016
- jsep2.hooks.add("gobble-token", function gobbleRegexLiteral(env) {
26017
- if (this.code === FSLASH_CODE) {
26018
- const patternIndex = ++this.index;
26019
- let inCharSet = false;
26020
- while (this.index < this.expr.length) {
26021
- if (this.code === FSLASH_CODE && !inCharSet) {
26022
- const pattern = this.expr.slice(patternIndex, this.index);
26023
- let flags = "";
26024
- while (++this.index < this.expr.length) {
26025
- const code = this.code;
26026
- if (code >= 97 && code <= 122 || code >= 65 && code <= 90 || code >= 48 && code <= 57) {
26027
- flags += this.char;
26028
- } else {
26029
- break;
26030
- }
26031
- }
26032
- let value;
26033
- try {
26034
- value = new RegExp(pattern, flags);
26035
- } catch (e) {
26036
- this.throwError(e.message);
26037
- }
26038
- env.node = {
26039
- type: jsep2.LITERAL,
26040
- value,
26041
- raw: this.expr.slice(patternIndex - 1, this.index)
26042
- };
26043
- env.node = this.gobbleTokenProperty(env.node);
26044
- return env.node;
26045
- }
26046
- if (this.code === jsep2.OBRACK_CODE) {
26047
- inCharSet = true;
26048
- } else if (inCharSet && this.code === jsep2.CBRACK_CODE) {
26049
- inCharSet = false;
26050
- }
26051
- this.index += this.code === BSLASH_CODE ? 2 : 1;
26052
- }
26053
- this.throwError("Unclosed Regex");
26054
- }
26055
- });
26056
- }
26057
- };
26058
- var PLUS_CODE = 43;
26059
- var MINUS_CODE = 45;
26060
- var plugin = {
26061
- name: "assignment",
26062
- assignmentOperators: new Set(["=", "*=", "**=", "/=", "%=", "+=", "-=", "<<=", ">>=", ">>>=", "&=", "^=", "|=", "||=", "&&=", "??="]),
26063
- updateOperators: [PLUS_CODE, MINUS_CODE],
26064
- assignmentPrecedence: 0.9,
26065
- init(jsep2) {
26066
- const updateNodeTypes = [jsep2.IDENTIFIER, jsep2.MEMBER_EXP];
26067
- plugin.assignmentOperators.forEach((op) => jsep2.addBinaryOp(op, plugin.assignmentPrecedence, true));
26068
- jsep2.hooks.add("gobble-token", function gobbleUpdatePrefix(env) {
26069
- const code = this.code;
26070
- if (plugin.updateOperators.some((c) => c === code && c === this.expr.charCodeAt(this.index + 1))) {
26071
- this.index += 2;
26072
- env.node = {
26073
- type: "UpdateExpression",
26074
- operator: code === PLUS_CODE ? "++" : "--",
26075
- argument: this.gobbleTokenProperty(this.gobbleIdentifier()),
26076
- prefix: true
26077
- };
26078
- if (!env.node.argument || !updateNodeTypes.includes(env.node.argument.type)) {
26079
- this.throwError(`Unexpected ${env.node.operator}`);
26080
- }
26081
- }
26082
- });
26083
- jsep2.hooks.add("after-token", function gobbleUpdatePostfix(env) {
26084
- if (env.node) {
26085
- const code = this.code;
26086
- if (plugin.updateOperators.some((c) => c === code && c === this.expr.charCodeAt(this.index + 1))) {
26087
- if (!updateNodeTypes.includes(env.node.type)) {
26088
- this.throwError(`Unexpected ${env.node.operator}`);
26089
- }
26090
- this.index += 2;
26091
- env.node = {
26092
- type: "UpdateExpression",
26093
- operator: code === PLUS_CODE ? "++" : "--",
26094
- argument: env.node,
26095
- prefix: false
26096
- };
26097
- }
26098
- }
26099
- });
26100
- jsep2.hooks.add("after-expression", function gobbleAssignment(env) {
26101
- if (env.node) {
26102
- updateBinariesToAssignments(env.node);
26103
- }
26104
- });
26105
- function updateBinariesToAssignments(node) {
26106
- if (plugin.assignmentOperators.has(node.operator)) {
26107
- node.type = "AssignmentExpression";
26108
- updateBinariesToAssignments(node.left);
26109
- updateBinariesToAssignments(node.right);
26110
- } else if (!node.operator) {
26111
- Object.values(node).forEach((val) => {
26112
- if (val && typeof val === "object") {
26113
- updateBinariesToAssignments(val);
26114
- }
26115
- });
26116
- }
26117
- }
26118
- }
26119
- };
26120
- jsep.plugins.register(index, plugin);
26121
- jsep.addUnaryOp("typeof");
26122
- jsep.addUnaryOp("void");
26123
- jsep.addLiteral("null", null);
26124
- jsep.addLiteral("undefined", undefined);
26125
- var BLOCKED_PROTO_PROPERTIES = new Set(["constructor", "__proto__", "__defineGetter__", "__defineSetter__", "__lookupGetter__", "__lookupSetter__"]);
26126
- var SafeEval = {
26127
- evalAst(ast, subs) {
26128
- switch (ast.type) {
26129
- case "BinaryExpression":
26130
- case "LogicalExpression":
26131
- return SafeEval.evalBinaryExpression(ast, subs);
26132
- case "Compound":
26133
- return SafeEval.evalCompound(ast, subs);
26134
- case "ConditionalExpression":
26135
- return SafeEval.evalConditionalExpression(ast, subs);
26136
- case "Identifier":
26137
- return SafeEval.evalIdentifier(ast, subs);
26138
- case "Literal":
26139
- return SafeEval.evalLiteral(ast, subs);
26140
- case "MemberExpression":
26141
- return SafeEval.evalMemberExpression(ast, subs);
26142
- case "UnaryExpression":
26143
- return SafeEval.evalUnaryExpression(ast, subs);
26144
- case "ArrayExpression":
26145
- return SafeEval.evalArrayExpression(ast, subs);
26146
- case "CallExpression":
26147
- return SafeEval.evalCallExpression(ast, subs);
26148
- case "AssignmentExpression":
26149
- return SafeEval.evalAssignmentExpression(ast, subs);
26150
- default:
26151
- throw SyntaxError("Unexpected expression", ast);
26152
- }
26153
- },
26154
- evalBinaryExpression(ast, subs) {
26155
- const result = {
26156
- "||": (a, b) => a || b(),
26157
- "&&": (a, b) => a && b(),
26158
- "|": (a, b) => a | b(),
26159
- "^": (a, b) => a ^ b(),
26160
- "&": (a, b) => a & b(),
26161
- "==": (a, b) => a == b(),
26162
- "!=": (a, b) => a != b(),
26163
- "===": (a, b) => a === b(),
26164
- "!==": (a, b) => a !== b(),
26165
- "<": (a, b) => a < b(),
26166
- ">": (a, b) => a > b(),
26167
- "<=": (a, b) => a <= b(),
26168
- ">=": (a, b) => a >= b(),
26169
- "<<": (a, b) => a << b(),
26170
- ">>": (a, b) => a >> b(),
26171
- ">>>": (a, b) => a >>> b(),
26172
- "+": (a, b) => a + b(),
26173
- "-": (a, b) => a - b(),
26174
- "*": (a, b) => a * b(),
26175
- "/": (a, b) => a / b(),
26176
- "%": (a, b) => a % b()
26177
- }[ast.operator](SafeEval.evalAst(ast.left, subs), () => SafeEval.evalAst(ast.right, subs));
26178
- return result;
26179
- },
26180
- evalCompound(ast, subs) {
26181
- let last;
26182
- for (let i = 0;i < ast.body.length; i++) {
26183
- if (ast.body[i].type === "Identifier" && ["var", "let", "const"].includes(ast.body[i].name) && ast.body[i + 1] && ast.body[i + 1].type === "AssignmentExpression") {
26184
- i += 1;
26185
- }
26186
- const expr = ast.body[i];
26187
- last = SafeEval.evalAst(expr, subs);
26188
- }
26189
- return last;
26190
- },
26191
- evalConditionalExpression(ast, subs) {
26192
- if (SafeEval.evalAst(ast.test, subs)) {
26193
- return SafeEval.evalAst(ast.consequent, subs);
26194
- }
26195
- return SafeEval.evalAst(ast.alternate, subs);
26196
- },
26197
- evalIdentifier(ast, subs) {
26198
- if (Object.hasOwn(subs, ast.name)) {
26199
- return subs[ast.name];
26200
- }
26201
- throw ReferenceError(`${ast.name} is not defined`);
26202
- },
26203
- evalLiteral(ast) {
26204
- return ast.value;
26205
- },
26206
- evalMemberExpression(ast, subs) {
26207
- const prop = String(ast.computed ? SafeEval.evalAst(ast.property) : ast.property.name);
26208
- const obj = SafeEval.evalAst(ast.object, subs);
26209
- if (obj === undefined || obj === null) {
26210
- throw TypeError(`Cannot read properties of ${obj} (reading '${prop}')`);
26211
- }
26212
- if (!Object.hasOwn(obj, prop) && BLOCKED_PROTO_PROPERTIES.has(prop)) {
26213
- throw TypeError(`Cannot read properties of ${obj} (reading '${prop}')`);
26214
- }
26215
- const result = obj[prop];
26216
- if (typeof result === "function") {
26217
- return result.bind(obj);
26218
- }
26219
- return result;
26220
- },
26221
- evalUnaryExpression(ast, subs) {
26222
- const result = {
26223
- "-": (a) => -SafeEval.evalAst(a, subs),
26224
- "!": (a) => !SafeEval.evalAst(a, subs),
26225
- "~": (a) => ~SafeEval.evalAst(a, subs),
26226
- "+": (a) => +SafeEval.evalAst(a, subs),
26227
- typeof: (a) => typeof SafeEval.evalAst(a, subs),
26228
- void: (a) => void SafeEval.evalAst(a, subs)
26229
- }[ast.operator](ast.argument);
26230
- return result;
26231
- },
26232
- evalArrayExpression(ast, subs) {
26233
- return ast.elements.map((el) => SafeEval.evalAst(el, subs));
26234
- },
26235
- evalCallExpression(ast, subs) {
26236
- const args = ast.arguments.map((arg) => SafeEval.evalAst(arg, subs));
26237
- const func = SafeEval.evalAst(ast.callee, subs);
26238
- if (func === Function) {
26239
- throw new Error("Function constructor is disabled");
26240
- }
26241
- return func(...args);
26242
- },
26243
- evalAssignmentExpression(ast, subs) {
26244
- if (ast.left.type !== "Identifier") {
26245
- throw SyntaxError("Invalid left-hand side in assignment");
26246
- }
26247
- const id = ast.left.name;
26248
- const value = SafeEval.evalAst(ast.right, subs);
26249
- subs[id] = value;
26250
- return subs[id];
26251
- }
26252
- };
26253
-
26254
- class SafeScript {
26255
- constructor(expr) {
26256
- this.code = expr;
26257
- this.ast = jsep(this.code);
26258
- }
26259
- runInNewContext(context) {
26260
- const keyMap = Object.assign(Object.create(null), context);
26261
- return SafeEval.evalAst(this.ast, keyMap);
26262
- }
26263
- }
26264
- function push(arr, item) {
26265
- arr = arr.slice();
26266
- arr.push(item);
26267
- return arr;
26268
- }
26269
- function unshift(item, arr) {
26270
- arr = arr.slice();
26271
- arr.unshift(item);
26272
- return arr;
26273
- }
26274
-
26275
- class NewError extends Error {
26276
- constructor(value) {
26277
- super('JSONPath should not be called with "new" (it prevents return ' + "of (unwrapped) scalar values)");
26278
- this.avoidNew = true;
26279
- this.value = value;
26280
- this.name = "NewError";
26281
- }
26282
- }
26283
- function JSONPath(opts, expr, obj, callback, otherTypeCallback) {
26284
- if (!(this instanceof JSONPath)) {
26285
- try {
26286
- return new JSONPath(opts, expr, obj, callback, otherTypeCallback);
26287
- } catch (e) {
26288
- if (!e.avoidNew) {
26289
- throw e;
26290
- }
26291
- return e.value;
26292
- }
26293
- }
26294
- if (typeof opts === "string") {
26295
- otherTypeCallback = callback;
26296
- callback = obj;
26297
- obj = expr;
26298
- expr = opts;
26299
- opts = null;
26300
- }
26301
- const optObj = opts && typeof opts === "object";
26302
- opts = opts || {};
26303
- this.json = opts.json || obj;
26304
- this.path = opts.path || expr;
26305
- this.resultType = opts.resultType || "value";
26306
- this.flatten = opts.flatten || false;
26307
- this.wrap = Object.hasOwn(opts, "wrap") ? opts.wrap : true;
26308
- this.sandbox = opts.sandbox || {};
26309
- this.eval = opts.eval === undefined ? "safe" : opts.eval;
26310
- this.ignoreEvalErrors = typeof opts.ignoreEvalErrors === "undefined" ? false : opts.ignoreEvalErrors;
26311
- this.parent = opts.parent || null;
26312
- this.parentProperty = opts.parentProperty || null;
26313
- this.callback = opts.callback || callback || null;
26314
- this.otherTypeCallback = opts.otherTypeCallback || otherTypeCallback || function() {
26315
- throw new TypeError("You must supply an otherTypeCallback callback option " + "with the @other() operator.");
26316
- };
26317
- if (opts.autostart !== false) {
26318
- const args = {
26319
- path: optObj ? opts.path : expr
26320
- };
26321
- if (!optObj) {
26322
- args.json = obj;
26323
- } else if ("json" in opts) {
26324
- args.json = opts.json;
26325
- }
26326
- const ret = this.evaluate(args);
26327
- if (!ret || typeof ret !== "object") {
26328
- throw new NewError(ret);
26329
- }
26330
- return ret;
26331
- }
26332
- }
26333
- JSONPath.prototype.evaluate = function(expr, json, callback, otherTypeCallback) {
26334
- let currParent = this.parent, currParentProperty = this.parentProperty;
26335
- let {
26336
- flatten,
26337
- wrap
26338
- } = this;
26339
- this.currResultType = this.resultType;
26340
- this.currEval = this.eval;
26341
- this.currSandbox = this.sandbox;
26342
- callback = callback || this.callback;
26343
- this.currOtherTypeCallback = otherTypeCallback || this.otherTypeCallback;
26344
- json = json || this.json;
26345
- expr = expr || this.path;
26346
- if (expr && typeof expr === "object" && !Array.isArray(expr)) {
26347
- if (!expr.path && expr.path !== "") {
26348
- throw new TypeError('You must supply a "path" property when providing an object ' + "argument to JSONPath.evaluate().");
26349
- }
26350
- if (!Object.hasOwn(expr, "json")) {
26351
- throw new TypeError('You must supply a "json" property when providing an object ' + "argument to JSONPath.evaluate().");
26352
- }
26353
- ({
26354
- json
26355
- } = expr);
26356
- flatten = Object.hasOwn(expr, "flatten") ? expr.flatten : flatten;
26357
- this.currResultType = Object.hasOwn(expr, "resultType") ? expr.resultType : this.currResultType;
26358
- this.currSandbox = Object.hasOwn(expr, "sandbox") ? expr.sandbox : this.currSandbox;
26359
- wrap = Object.hasOwn(expr, "wrap") ? expr.wrap : wrap;
26360
- this.currEval = Object.hasOwn(expr, "eval") ? expr.eval : this.currEval;
26361
- callback = Object.hasOwn(expr, "callback") ? expr.callback : callback;
26362
- this.currOtherTypeCallback = Object.hasOwn(expr, "otherTypeCallback") ? expr.otherTypeCallback : this.currOtherTypeCallback;
26363
- currParent = Object.hasOwn(expr, "parent") ? expr.parent : currParent;
26364
- currParentProperty = Object.hasOwn(expr, "parentProperty") ? expr.parentProperty : currParentProperty;
26365
- expr = expr.path;
26366
- }
26367
- currParent = currParent || null;
26368
- currParentProperty = currParentProperty || null;
26369
- if (Array.isArray(expr)) {
26370
- expr = JSONPath.toPathString(expr);
26371
- }
26372
- if (!expr && expr !== "" || !json) {
26373
- return;
26374
- }
26375
- const exprList = JSONPath.toPathArray(expr);
26376
- if (exprList[0] === "$" && exprList.length > 1) {
26377
- exprList.shift();
26378
- }
26379
- this._hasParentSelector = null;
26380
- const result = this._trace(exprList, json, ["$"], currParent, currParentProperty, callback).filter(function(ea) {
26381
- return ea && !ea.isParentSelector;
26382
- });
26383
- if (!result.length) {
26384
- return wrap ? [] : undefined;
26385
- }
26386
- if (!wrap && result.length === 1 && !result[0].hasArrExpr) {
26387
- return this._getPreferredOutput(result[0]);
26388
- }
26389
- return result.reduce((rslt, ea) => {
26390
- const valOrPath = this._getPreferredOutput(ea);
26391
- if (flatten && Array.isArray(valOrPath)) {
26392
- rslt = rslt.concat(valOrPath);
26393
- } else {
26394
- rslt.push(valOrPath);
26395
- }
26396
- return rslt;
26397
- }, []);
26398
- };
26399
- JSONPath.prototype._getPreferredOutput = function(ea) {
26400
- const resultType = this.currResultType;
26401
- switch (resultType) {
26402
- case "all": {
26403
- const path3 = Array.isArray(ea.path) ? ea.path : JSONPath.toPathArray(ea.path);
26404
- ea.pointer = JSONPath.toPointer(path3);
26405
- ea.path = typeof ea.path === "string" ? ea.path : JSONPath.toPathString(ea.path);
26406
- return ea;
26407
- }
26408
- case "value":
26409
- case "parent":
26410
- case "parentProperty":
26411
- return ea[resultType];
26412
- case "path":
26413
- return JSONPath.toPathString(ea[resultType]);
26414
- case "pointer":
26415
- return JSONPath.toPointer(ea.path);
26416
- default:
26417
- throw new TypeError("Unknown result type");
26418
- }
26419
- };
26420
- JSONPath.prototype._handleCallback = function(fullRetObj, callback, type) {
26421
- if (callback) {
26422
- const preferredOutput = this._getPreferredOutput(fullRetObj);
26423
- fullRetObj.path = typeof fullRetObj.path === "string" ? fullRetObj.path : JSONPath.toPathString(fullRetObj.path);
26424
- callback(preferredOutput, type, fullRetObj);
26425
- }
26426
- };
26427
- JSONPath.prototype._trace = function(expr, val, path3, parent, parentPropName, callback, hasArrExpr, literalPriority) {
26428
- let retObj;
26429
- if (!expr.length) {
26430
- retObj = {
26431
- path: path3,
26432
- value: val,
26433
- parent,
26434
- parentProperty: parentPropName,
26435
- hasArrExpr
26436
- };
26437
- this._handleCallback(retObj, callback, "value");
26438
- return retObj;
26439
- }
26440
- const loc = expr[0], x = expr.slice(1);
26441
- const ret = [];
26442
- function addRet(elems) {
26443
- if (Array.isArray(elems)) {
26444
- elems.forEach((t) => {
26445
- ret.push(t);
26446
- });
26447
- } else {
26448
- ret.push(elems);
26449
- }
26450
- }
26451
- if ((typeof loc !== "string" || literalPriority) && val && Object.hasOwn(val, loc)) {
26452
- addRet(this._trace(x, val[loc], push(path3, loc), val, loc, callback, hasArrExpr));
26453
- } else if (loc === "*") {
26454
- this._walk(val, (m) => {
26455
- addRet(this._trace(x, val[m], push(path3, m), val, m, callback, true, true));
26456
- });
26457
- } else if (loc === "..") {
26458
- addRet(this._trace(x, val, path3, parent, parentPropName, callback, hasArrExpr));
26459
- this._walk(val, (m) => {
26460
- if (typeof val[m] === "object") {
26461
- addRet(this._trace(expr.slice(), val[m], push(path3, m), val, m, callback, true));
26462
- }
26463
- });
26464
- } else if (loc === "^") {
26465
- this._hasParentSelector = true;
26466
- return {
26467
- path: path3.slice(0, -1),
26468
- expr: x,
26469
- isParentSelector: true
26470
- };
26471
- } else if (loc === "~") {
26472
- retObj = {
26473
- path: push(path3, loc),
26474
- value: parentPropName,
26475
- parent,
26476
- parentProperty: null
26477
- };
26478
- this._handleCallback(retObj, callback, "property");
26479
- return retObj;
26480
- } else if (loc === "$") {
26481
- addRet(this._trace(x, val, path3, null, null, callback, hasArrExpr));
26482
- } else if (/^(-?\d*):(-?\d*):?(\d*)$/u.test(loc)) {
26483
- addRet(this._slice(loc, x, val, path3, parent, parentPropName, callback));
26484
- } else if (loc.indexOf("?(") === 0) {
26485
- if (this.currEval === false) {
26486
- throw new Error("Eval [?(expr)] prevented in JSONPath expression.");
26487
- }
26488
- const safeLoc = loc.replace(/^\?\((.*?)\)$/u, "$1");
26489
- const nested = /@.?([^?]*)[['](\??\(.*?\))(?!.\)\])[\]']/gu.exec(safeLoc);
26490
- if (nested) {
26491
- this._walk(val, (m) => {
26492
- const npath = [nested[2]];
26493
- const nvalue = nested[1] ? val[m][nested[1]] : val[m];
26494
- const filterResults = this._trace(npath, nvalue, path3, parent, parentPropName, callback, true);
26495
- if (filterResults.length > 0) {
26496
- addRet(this._trace(x, val[m], push(path3, m), val, m, callback, true));
26497
- }
26498
- });
26499
- } else {
26500
- this._walk(val, (m) => {
26501
- if (this._eval(safeLoc, val[m], m, path3, parent, parentPropName)) {
26502
- addRet(this._trace(x, val[m], push(path3, m), val, m, callback, true));
26503
- }
26504
- });
26505
- }
26506
- } else if (loc[0] === "(") {
26507
- if (this.currEval === false) {
26508
- throw new Error("Eval [(expr)] prevented in JSONPath expression.");
26509
- }
26510
- addRet(this._trace(unshift(this._eval(loc, val, path3.at(-1), path3.slice(0, -1), parent, parentPropName), x), val, path3, parent, parentPropName, callback, hasArrExpr));
26511
- } else if (loc[0] === "@") {
26512
- let addType = false;
26513
- const valueType = loc.slice(1, -2);
26514
- switch (valueType) {
26515
- case "scalar":
26516
- if (!val || !["object", "function"].includes(typeof val)) {
26517
- addType = true;
26518
- }
26519
- break;
26520
- case "boolean":
26521
- case "string":
26522
- case "undefined":
26523
- case "function":
26524
- if (typeof val === valueType) {
26525
- addType = true;
26526
- }
26527
- break;
26528
- case "integer":
26529
- if (Number.isFinite(val) && !(val % 1)) {
26530
- addType = true;
26531
- }
26532
- break;
26533
- case "number":
26534
- if (Number.isFinite(val)) {
26535
- addType = true;
26536
- }
26537
- break;
26538
- case "nonFinite":
26539
- if (typeof val === "number" && !Number.isFinite(val)) {
26540
- addType = true;
26541
- }
26542
- break;
26543
- case "object":
26544
- if (val && typeof val === valueType) {
26545
- addType = true;
26546
- }
26547
- break;
26548
- case "array":
26549
- if (Array.isArray(val)) {
26550
- addType = true;
26551
- }
26552
- break;
26553
- case "other":
26554
- addType = this.currOtherTypeCallback(val, path3, parent, parentPropName);
26555
- break;
26556
- case "null":
26557
- if (val === null) {
26558
- addType = true;
26559
- }
26560
- break;
26561
- default:
26562
- throw new TypeError("Unknown value type " + valueType);
26563
- }
26564
- if (addType) {
26565
- retObj = {
26566
- path: path3,
26567
- value: val,
26568
- parent,
26569
- parentProperty: parentPropName
26570
- };
26571
- this._handleCallback(retObj, callback, "value");
26572
- return retObj;
26573
- }
26574
- } else if (loc[0] === "`" && val && Object.hasOwn(val, loc.slice(1))) {
26575
- const locProp = loc.slice(1);
26576
- addRet(this._trace(x, val[locProp], push(path3, locProp), val, locProp, callback, hasArrExpr, true));
26577
- } else if (loc.includes(",")) {
26578
- const parts = loc.split(",");
26579
- for (const part of parts) {
26580
- addRet(this._trace(unshift(part, x), val, path3, parent, parentPropName, callback, true));
26581
- }
26582
- } else if (!literalPriority && val && Object.hasOwn(val, loc)) {
26583
- addRet(this._trace(x, val[loc], push(path3, loc), val, loc, callback, hasArrExpr, true));
26584
- }
26585
- if (this._hasParentSelector) {
26586
- for (let t = 0;t < ret.length; t++) {
26587
- const rett = ret[t];
26588
- if (rett && rett.isParentSelector) {
26589
- const tmp = this._trace(rett.expr, val, rett.path, parent, parentPropName, callback, hasArrExpr);
26590
- if (Array.isArray(tmp)) {
26591
- ret[t] = tmp[0];
26592
- const tl = tmp.length;
26593
- for (let tt = 1;tt < tl; tt++) {
26594
- t++;
26595
- ret.splice(t, 0, tmp[tt]);
26596
- }
26597
- } else {
26598
- ret[t] = tmp;
26599
- }
26600
- }
26601
- }
26602
- }
26603
- return ret;
26604
- };
26605
- JSONPath.prototype._walk = function(val, f) {
26606
- if (Array.isArray(val)) {
26607
- const n = val.length;
26608
- for (let i = 0;i < n; i++) {
26609
- f(i);
26610
- }
26611
- } else if (val && typeof val === "object") {
26612
- Object.keys(val).forEach((m) => {
26613
- f(m);
26614
- });
26615
- }
26616
- };
26617
- JSONPath.prototype._slice = function(loc, expr, val, path3, parent, parentPropName, callback) {
26618
- if (!Array.isArray(val)) {
26619
- return;
26620
- }
26621
- const len = val.length, parts = loc.split(":"), step = parts[2] && Number.parseInt(parts[2]) || 1;
26622
- let start = parts[0] && Number.parseInt(parts[0]) || 0, end = parts[1] && Number.parseInt(parts[1]) || len;
26623
- start = start < 0 ? Math.max(0, start + len) : Math.min(len, start);
26624
- end = end < 0 ? Math.max(0, end + len) : Math.min(len, end);
26625
- const ret = [];
26626
- for (let i = start;i < end; i += step) {
26627
- const tmp = this._trace(unshift(i, expr), val, path3, parent, parentPropName, callback, true);
26628
- tmp.forEach((t) => {
26629
- ret.push(t);
26630
- });
26631
- }
26632
- return ret;
26633
- };
26634
- JSONPath.prototype._eval = function(code, _v, _vname, path3, parent, parentPropName) {
26635
- this.currSandbox._$_parentProperty = parentPropName;
26636
- this.currSandbox._$_parent = parent;
26637
- this.currSandbox._$_property = _vname;
26638
- this.currSandbox._$_root = this.json;
26639
- this.currSandbox._$_v = _v;
26640
- const containsPath = code.includes("@path");
26641
- if (containsPath) {
26642
- this.currSandbox._$_path = JSONPath.toPathString(path3.concat([_vname]));
26643
- }
26644
- const scriptCacheKey = this.currEval + "Script:" + code;
26645
- if (!JSONPath.cache[scriptCacheKey]) {
26646
- let script = code.replaceAll("@parentProperty", "_$_parentProperty").replaceAll("@parent", "_$_parent").replaceAll("@property", "_$_property").replaceAll("@root", "_$_root").replaceAll(/@([.\s)[])/gu, "_$_v$1");
26647
- if (containsPath) {
26648
- script = script.replaceAll("@path", "_$_path");
26649
- }
26650
- if (this.currEval === "safe" || this.currEval === true || this.currEval === undefined) {
26651
- JSONPath.cache[scriptCacheKey] = new this.safeVm.Script(script);
26652
- } else if (this.currEval === "native") {
26653
- JSONPath.cache[scriptCacheKey] = new this.vm.Script(script);
26654
- } else if (typeof this.currEval === "function" && this.currEval.prototype && Object.hasOwn(this.currEval.prototype, "runInNewContext")) {
26655
- const CurrEval = this.currEval;
26656
- JSONPath.cache[scriptCacheKey] = new CurrEval(script);
26657
- } else if (typeof this.currEval === "function") {
26658
- JSONPath.cache[scriptCacheKey] = {
26659
- runInNewContext: (context) => this.currEval(script, context)
26660
- };
26661
- } else {
26662
- throw new TypeError(`Unknown "eval" property "${this.currEval}"`);
26663
- }
26664
- }
26665
- try {
26666
- return JSONPath.cache[scriptCacheKey].runInNewContext(this.currSandbox);
26667
- } catch (e) {
26668
- if (this.ignoreEvalErrors) {
26669
- return false;
26670
- }
26671
- throw new Error("jsonPath: " + e.message + ": " + code);
26672
- }
26673
- };
26674
- JSONPath.cache = {};
26675
- JSONPath.toPathString = function(pathArr) {
26676
- const x = pathArr, n = x.length;
26677
- let p = "$";
26678
- for (let i = 1;i < n; i++) {
26679
- if (!/^(~|\^|@.*?\(\))$/u.test(x[i])) {
26680
- p += /^[0-9*]+$/u.test(x[i]) ? "[" + x[i] + "]" : "['" + x[i] + "']";
26681
- }
26682
- }
26683
- return p;
26684
- };
26685
- JSONPath.toPointer = function(pointer) {
26686
- const x = pointer, n = x.length;
26687
- let p = "";
26688
- for (let i = 1;i < n; i++) {
26689
- if (!/^(~|\^|@.*?\(\))$/u.test(x[i])) {
26690
- p += "/" + x[i].toString().replaceAll("~", "~0").replaceAll("/", "~1");
26691
- }
26692
- }
26693
- return p;
26694
- };
26695
- JSONPath.toPathArray = function(expr) {
26696
- const {
26697
- cache
26698
- } = JSONPath;
26699
- if (cache[expr]) {
26700
- return cache[expr].concat();
26701
- }
26702
- const subx = [];
26703
- const normalized = expr.replaceAll(/@(?:null|boolean|number|string|integer|undefined|nonFinite|scalar|array|object|function|other)\(\)/gu, ";$&;").replaceAll(/[['](\??\(.*?\))[\]'](?!.\])/gu, function($0, $1) {
26704
- return "[#" + (subx.push($1) - 1) + "]";
26705
- }).replaceAll(/\[['"]([^'\]]*)['"]\]/gu, function($0, prop) {
26706
- return "['" + prop.replaceAll(".", "%@%").replaceAll("~", "%%@@%%") + "']";
26707
- }).replaceAll("~", ";~;").replaceAll(/['"]?\.['"]?(?![^[]*\])|\[['"]?/gu, ";").replaceAll("%@%", ".").replaceAll("%%@@%%", "~").replaceAll(/(?:;)?(\^+)(?:;)?/gu, function($0, ups) {
26708
- return ";" + ups.split("").join(";") + ";";
26709
- }).replaceAll(/;;;|;;/gu, ";..;").replaceAll(/;$|'?\]|'$/gu, "");
26710
- const exprList = normalized.split(";").map(function(exp) {
26711
- const match = exp.match(/#(\d+)/u);
26712
- return !match || !match[1] ? exp : subx[match[1]];
26713
- });
26714
- cache[expr] = exprList;
26715
- return cache[expr].concat();
26716
- };
26717
- JSONPath.prototype.safeVm = {
26718
- Script: SafeScript
26719
- };
26720
- JSONPath.prototype.vm = vm;
26721
- // ../../common/src/option-aliases.ts
26722
- import { Option } from "commander";
26723
- function resolveDeprecatedOptionAlias({
26724
- preferredValue,
26725
- deprecatedValue,
26726
- preferredFlag,
26727
- deprecatedFlag
26728
- }) {
26729
- const hasPreferred = preferredValue !== undefined;
26730
- const hasDeprecated = deprecatedValue !== undefined;
26731
- if (hasPreferred && hasDeprecated) {
26732
- return {
26733
- value: undefined,
26734
- usedDeprecated: true,
26735
- error: {
26736
- message: `${deprecatedFlag} and ${preferredFlag} are aliases. Use only ${preferredFlag}.`,
26737
- instructions: `Replace ${deprecatedFlag} with ${preferredFlag}.`
26738
- }
26739
- };
26740
- }
26741
- return {
26742
- value: hasPreferred ? preferredValue : deprecatedValue,
26743
- usedDeprecated: hasDeprecated
26744
- };
26745
- }
26746
- function warnDeprecatedOptionAlias(deprecatedFlag, preferredFlag) {
26747
- getOutputSink().writeErr(`[WARN] ${deprecatedFlag} is deprecated. Use ${preferredFlag} instead.
26748
- `);
26749
- }
26750
- var TENANT_SWITCH_COMMAND = "uip login tenant set <tenant>";
26751
- function createHiddenDeprecatedTenantOption(flags = "-t, --tenant <tenant-name>") {
26752
- return new Option(flags, `Tenant name. Deprecated; use ${TENANT_SWITCH_COMMAND} to switch active tenants.`).hideHelp().argParser((tenant) => {
26753
- warnDeprecatedTenantOption(tenant);
26754
- return tenant;
26755
- });
26756
- }
26757
- function warnDeprecatedTenantOption(tenant) {
26758
- if (tenant === undefined)
26759
- return;
26760
- warnDeprecatedOptionAlias("--tenant", TENANT_SWITCH_COMMAND);
26761
- }
26762
- // ../../common/src/option-validators.ts
26763
- import { InvalidArgumentError } from "commander";
26764
- // ../../common/src/polling/types.ts
26765
- var PollOutcome = {
26766
- Completed: "completed",
26767
- Timeout: "timeout",
26768
- Interrupted: "interrupted",
26769
- Aborted: "aborted",
26770
- Failed: "failed"
26771
- };
26772
-
26773
- // ../../common/src/polling/poll-failure-mapping.ts
26774
- var REASON_BY_OUTCOME = {
26775
- [PollOutcome.Timeout]: "poll_timeout",
26776
- [PollOutcome.Failed]: "poll_failed",
26777
- [PollOutcome.Interrupted]: "poll_failed",
26778
- [PollOutcome.Aborted]: "poll_aborted"
26779
- };
26780
- // ../../common/src/polling/terminal-statuses.ts
26781
- var TERMINAL_STATUSES = new Set([
26782
- "completed",
26783
- "successful",
26784
- "faulted",
26785
- "failed",
26786
- "cancelled",
26787
- "canceled",
26788
- "stopped",
26789
- "finished"
26790
- ]);
26791
- var FAILURE_STATUSES = new Set([
26792
- "faulted",
26793
- "failed",
26794
- "cancelled",
26795
- "canceled",
26796
- "stopped"
26797
- ]);
26798
- // ../../common/src/screen-logger.ts
26799
- var ScreenLogger;
26800
- ((ScreenLogger) => {
26801
- function progress(message) {
26802
- getOutputSink().writeErr(`${message}
26803
- `);
26804
- }
26805
- ScreenLogger.progress = progress;
26806
- })(ScreenLogger ||= {});
26807
- // ../../common/src/sdk-user-agent.ts
26808
- var USER_AGENT_HEADER = "User-Agent";
26809
- var sdkUserAgentHostToken = singleton("SdkUserAgentHostToken");
26810
- function userAgentPatchKey(userAgent) {
26811
- return Symbol.for(`@uipath/common/sdk-user-agent/${userAgent}`);
26812
- }
26813
- function splitUserAgentTokens(value) {
26814
- return value?.trim().split(/\s+/).filter(Boolean) ?? [];
26815
- }
26816
- function appendUserAgentToken(value, userAgent) {
26817
- const tokens = splitUserAgentTokens(value);
26818
- const seen = new Set(tokens);
26819
- for (const token of splitUserAgentTokens(userAgent)) {
26820
- if (!seen.has(token)) {
26821
- tokens.push(token);
26822
- seen.add(token);
26823
- }
26824
- }
26825
- return tokens.join(" ");
26826
- }
26827
- function getEffectiveUserAgent(userAgent) {
26828
- return appendUserAgentToken(sdkUserAgentHostToken.get(), userAgent);
26829
- }
26830
- function isHeadersLike(headers) {
26831
- return typeof headers === "object" && headers !== null && "get" in headers && typeof headers.get === "function" && "set" in headers && typeof headers.set === "function";
26832
- }
26833
- function getSdkUserAgentToken(pkg) {
26834
- const packageName = pkg.name.replace(/^@uipath\//, "");
26835
- return getEffectiveUserAgent(`${packageName}/${pkg.version}`);
26836
- }
26837
- function addSdkUserAgentHeader(headers, userAgent) {
26838
- const result = { ...headers ?? {} };
26839
- const effectiveUserAgent = getEffectiveUserAgent(userAgent);
26840
- const headerName = Object.keys(result).find((key) => key.toLowerCase() === USER_AGENT_HEADER.toLowerCase());
26841
- if (headerName) {
26842
- result[headerName] = appendUserAgentToken(result[headerName], effectiveUserAgent);
26843
- } else {
26844
- result[USER_AGENT_HEADER] = effectiveUserAgent;
26845
- }
26846
- return result;
26847
- }
26848
- function withSdkUserAgentHeader(headers, userAgent) {
26849
- const effectiveUserAgent = getEffectiveUserAgent(userAgent);
26850
- if (isHeadersLike(headers)) {
26851
- headers.set(USER_AGENT_HEADER, appendUserAgentToken(headers.get(USER_AGENT_HEADER), effectiveUserAgent));
26852
- return headers;
26853
- }
26854
- if (Array.isArray(headers)) {
26855
- const result = headers.map((entry) => {
26856
- const [key, value] = entry;
26857
- return [key, value];
26858
- });
26859
- const headerIndex = result.findIndex(([key]) => key.toLowerCase() === USER_AGENT_HEADER.toLowerCase());
26860
- if (headerIndex >= 0) {
26861
- const [key, value] = result[headerIndex];
26862
- result[headerIndex] = [
26863
- key,
26864
- appendUserAgentToken(value, effectiveUserAgent)
26865
- ];
26866
- } else {
26867
- result.push([USER_AGENT_HEADER, effectiveUserAgent]);
26868
- }
26869
- return result;
26870
- }
26871
- return addSdkUserAgentHeader(typeof headers === "object" && headers !== null ? { ...headers } : {}, effectiveUserAgent);
26872
- }
26873
- function withUserAgentInitOverride(initOverrides, userAgent) {
26874
- return async (requestContext) => {
26875
- const initWithUserAgent = {
26876
- ...requestContext.init,
26877
- headers: withSdkUserAgentHeader(requestContext.init.headers, userAgent)
26878
- };
26879
- const override = typeof initOverrides === "function" ? await initOverrides({
26880
- ...requestContext,
26881
- init: initWithUserAgent
26882
- }) : initOverrides;
26883
- return {
26884
- ...override ?? {},
26885
- headers: withSdkUserAgentHeader(override?.headers ?? initWithUserAgent.headers, userAgent)
26886
- };
26887
- };
26888
- }
26889
- function installSdkUserAgentHeader(BaseApiClass, userAgent) {
26890
- const prototype = BaseApiClass.prototype;
26891
- const patchKey = userAgentPatchKey(userAgent);
26892
- if (prototype[patchKey]) {
26893
- return;
26894
- }
26895
- if (typeof prototype.request !== "function") {
26896
- throw new Error("Generated BaseAPI request function not found.");
26897
- }
26898
- const originalRequest = prototype.request;
26899
- prototype.request = function requestWithUserAgent(context, initOverrides) {
26900
- return originalRequest.call(this, context, withUserAgentInitOverride(initOverrides, userAgent));
26901
- };
26902
- Object.defineProperty(prototype, patchKey, {
26903
- value: true
26904
- });
26905
- }
26906
- // ../../common/src/tool-provider.ts
26907
- var factorySlot = singleton("PackagerFactoryProvider");
26908
- // ../resourcecatalog-sdk/generated/src/runtime.ts
26909
- var BASE_PATH = "http://localhost".replace(/\/+$/, "");
26910
-
26911
- class Configuration {
26912
- configuration;
26913
- constructor(configuration = {}) {
26914
- this.configuration = configuration;
26915
- }
26916
- set config(configuration) {
26917
- this.configuration = configuration;
26918
- }
26919
- get basePath() {
26920
- return this.configuration.basePath != null ? this.configuration.basePath : BASE_PATH;
26921
- }
26922
- get fetchApi() {
26923
- return this.configuration.fetchApi;
26924
- }
26925
- get middleware() {
26926
- return this.configuration.middleware || [];
26927
- }
26928
- get queryParamsStringify() {
26929
- return this.configuration.queryParamsStringify || querystring;
26930
- }
26931
- get username() {
26932
- return this.configuration.username;
26933
- }
26934
- get password() {
26935
- return this.configuration.password;
26936
- }
26937
- get apiKey() {
26938
- const apiKey = this.configuration.apiKey;
26939
- if (apiKey) {
26940
- return typeof apiKey === "function" ? apiKey : () => apiKey;
26941
- }
26942
- return;
26943
- }
26944
- get accessToken() {
26945
- const accessToken = this.configuration.accessToken;
26946
- if (accessToken) {
26947
- return typeof accessToken === "function" ? accessToken : async () => accessToken;
26948
- }
26949
- return;
26950
- }
26951
- get headers() {
26952
- return this.configuration.headers;
26953
- }
26954
- get credentials() {
26955
- return this.configuration.credentials;
25654
+ get credentials() {
25655
+ return this.configuration.credentials;
26956
25656
  }
26957
25657
  }
26958
25658
  var DefaultConfig = new Configuration;
@@ -27158,7 +25858,7 @@ class VoidApiResponse {
27158
25858
  var package_default2 = {
27159
25859
  name: "@uipath/resourcecatalog-sdk",
27160
25860
  license: "MIT",
27161
- version: "1.196.0",
25861
+ version: "1.197.0",
27162
25862
  description: "SDK for the UiPath Resource Catalog Service API.",
27163
25863
  repository: {
27164
25864
  type: "git",
@@ -27187,7 +25887,7 @@ var package_default2 = {
27187
25887
  ],
27188
25888
  private: true,
27189
25889
  scripts: {
27190
- build: "bun build ./src/index.ts --outdir dist --format esm --target node && tsc -p tsconfig.build.json --noCheck",
25890
+ build: "bun build ./src/index.ts --outdir dist --format esm --target node --sourcemap=linked && tsc -p tsconfig.build.json --noCheck",
27191
25891
  generate: "bun run src/scripts/generate-sdk.ts",
27192
25892
  lint: "biome check ."
27193
25893
  },
@@ -28590,6 +27290,12 @@ var normalizeAndValidateBaseUrl = (rawUrl) => {
28590
27290
  }
28591
27291
  return url.pathname.length > 1 ? url.origin : baseUrl;
28592
27292
  };
27293
+ var resolveScopes = (isExternalAppAuth, customScopes, fileScopes) => {
27294
+ const requestedScopes = customScopes?.length ? customScopes : fileScopes ?? [];
27295
+ if (isExternalAppAuth)
27296
+ return requestedScopes;
27297
+ return [...new Set([...DEFAULT_SCOPES, ...requestedScopes])];
27298
+ };
28593
27299
  var resolveConfigAsync = async ({
28594
27300
  customAuthority,
28595
27301
  customClientId,
@@ -28620,7 +27326,7 @@ var resolveConfigAsync = async ({
28620
27326
  clientSecret = fileAuth.clientSecret;
28621
27327
  }
28622
27328
  const isExternalAppAuth = clientId !== DEFAULT_CLIENT_ID && Boolean(clientSecret);
28623
- const scopes = customScopes && customScopes.length > 0 ? customScopes : fileAuth.scopes && fileAuth.scopes.length > 0 ? fileAuth.scopes : isExternalAppAuth ? [] : DEFAULT_SCOPES;
27329
+ const scopes = resolveScopes(isExternalAppAuth, customScopes, fileAuth.scopes);
28624
27330
  return {
28625
27331
  clientId,
28626
27332
  clientSecret,
@@ -28635,6 +27341,76 @@ var resolveConfigAsync = async ({
28635
27341
  init_constants();
28636
27342
  // ../../auth/src/loginStatus.ts
28637
27343
  init_src();
27344
+
27345
+ // ../../auth/src/authProfile.ts
27346
+ init_src();
27347
+ init_constants();
27348
+ var DEFAULT_AUTH_PROFILE = "default";
27349
+ var PROFILE_DIR = "profiles";
27350
+ var PROFILE_NAME_RE = /^[A-Za-z0-9._-]+$/;
27351
+ var ACTIVE_AUTH_PROFILE_KEY = Symbol.for("@uipath/auth/ActiveAuthProfile");
27352
+ var AUTH_PROFILE_STORAGE_KEY = Symbol.for("@uipath/auth/ProfileStorage");
27353
+ var globalSlot2 = globalThis;
27354
+ function isAuthProfileStorage(value) {
27355
+ return value !== null && typeof value === "object" && "getStore" in value && "run" in value;
27356
+ }
27357
+ function createProfileStorage() {
27358
+ const [error, mod2] = catchError2(() => __require("node:async_hooks"));
27359
+ if (error || typeof mod2?.AsyncLocalStorage !== "function") {
27360
+ return {
27361
+ getStore: () => {
27362
+ return;
27363
+ },
27364
+ run: (_store, fn) => fn()
27365
+ };
27366
+ }
27367
+ return new mod2.AsyncLocalStorage;
27368
+ }
27369
+ function getProfileStorage() {
27370
+ const existing = globalSlot2[AUTH_PROFILE_STORAGE_KEY];
27371
+ if (isAuthProfileStorage(existing)) {
27372
+ return existing;
27373
+ }
27374
+ const storage = createProfileStorage();
27375
+ globalSlot2[AUTH_PROFILE_STORAGE_KEY] = storage;
27376
+ return storage;
27377
+ }
27378
+ var profileStorage = getProfileStorage();
27379
+
27380
+ class AuthProfileValidationError extends Error {
27381
+ constructor(message) {
27382
+ super(message);
27383
+ this.name = "AuthProfileValidationError";
27384
+ }
27385
+ }
27386
+ function normalizeAuthProfileName(profile) {
27387
+ if (profile === undefined || profile === DEFAULT_AUTH_PROFILE) {
27388
+ return;
27389
+ }
27390
+ if (profile.length === 0 || profile === "." || profile === ".." || !PROFILE_NAME_RE.test(profile)) {
27391
+ throw new AuthProfileValidationError(`Invalid profile name "${profile}". Profile names may contain only letters, numbers, '.', '_', and '-'.`);
27392
+ }
27393
+ return profile;
27394
+ }
27395
+ function getActiveAuthProfile() {
27396
+ const scopedState = profileStorage.getStore();
27397
+ if (scopedState !== undefined) {
27398
+ return scopedState.profile;
27399
+ }
27400
+ return globalSlot2[ACTIVE_AUTH_PROFILE_KEY]?.profile;
27401
+ }
27402
+ function resolveAuthProfileFilePath(profile) {
27403
+ const normalized = normalizeAuthProfileName(profile);
27404
+ if (normalized === undefined) {
27405
+ throw new AuthProfileValidationError(`"${DEFAULT_AUTH_PROFILE}" is the built-in profile and does not have a profile file path.`);
27406
+ }
27407
+ const fs7 = getFileSystem();
27408
+ return fs7.path.join(fs7.env.homedir(), UIPATH_HOME_DIR, PROFILE_DIR, normalized, AUTH_FILENAME);
27409
+ }
27410
+ function getActiveAuthProfileFilePath() {
27411
+ const profile = getActiveAuthProfile();
27412
+ return profile ? resolveAuthProfileFilePath(profile) : undefined;
27413
+ }
28638
27414
  // ../../auth/src/utils/jwt.ts
28639
27415
  class InvalidIssuerError extends Error {
28640
27416
  expected;
@@ -28763,23 +27539,74 @@ var readAuthFromEnv = () => {
28763
27539
  organizationId,
28764
27540
  tenantName,
28765
27541
  tenantId,
28766
- expiration
27542
+ expiration,
27543
+ source: "env" /* Env */
28767
27544
  };
28768
27545
  };
28769
27546
 
27547
+ // ../../auth/src/refreshCircuitBreaker.ts
27548
+ init_src();
27549
+ var BREAKER_SUFFIX = ".refresh-state";
27550
+ var BACKOFF_BASE_MS = 60000;
27551
+ var BACKOFF_CAP_MS = 60 * 60 * 1000;
27552
+ var SURFACE_WINDOW_MS = 60 * 60 * 1000;
27553
+ async function refreshTokenFingerprint(refreshToken) {
27554
+ const bytes = new TextEncoder().encode(refreshToken);
27555
+ if (globalThis.crypto?.subtle) {
27556
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", bytes);
27557
+ return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("").slice(0, 16);
27558
+ }
27559
+ const { createHash } = await import("node:crypto");
27560
+ return createHash("sha256").update(refreshToken).digest("hex").slice(0, 16);
27561
+ }
27562
+ function breakerPathFor(authPath) {
27563
+ return `${authPath}${BREAKER_SUFFIX}`;
27564
+ }
27565
+ async function loadRefreshBreaker(authPath) {
27566
+ const fs7 = getFileSystem();
27567
+ try {
27568
+ const content = await fs7.readFile(breakerPathFor(authPath), "utf-8");
27569
+ if (!content)
27570
+ return {};
27571
+ const parsed = JSON.parse(content);
27572
+ return parsed && typeof parsed === "object" ? parsed : {};
27573
+ } catch {
27574
+ return {};
27575
+ }
27576
+ }
27577
+ async function saveRefreshBreaker(authPath, state) {
27578
+ try {
27579
+ const fs7 = getFileSystem();
27580
+ const path3 = breakerPathFor(authPath);
27581
+ await fs7.mkdir(fs7.path.dirname(path3));
27582
+ const tempPath = `${path3}.tmp`;
27583
+ await fs7.writeFile(tempPath, JSON.stringify(state));
27584
+ await fs7.rename(tempPath, path3);
27585
+ } catch {}
27586
+ }
27587
+ async function clearRefreshBreaker(authPath) {
27588
+ const fs7 = getFileSystem();
27589
+ const path3 = breakerPathFor(authPath);
27590
+ try {
27591
+ if (await fs7.exists(path3)) {
27592
+ await fs7.rm(path3);
27593
+ }
27594
+ } catch {}
27595
+ }
27596
+ function nextBackoffMs(attempts) {
27597
+ const shift = Math.max(0, attempts - 1);
27598
+ return Math.min(BACKOFF_BASE_MS * 2 ** shift, BACKOFF_CAP_MS);
27599
+ }
27600
+ function shouldSurface(state, nowMs) {
27601
+ if (state.lastSurfacedAtMs === undefined)
27602
+ return true;
27603
+ return nowMs - state.lastSurfacedAtMs >= SURFACE_WINDOW_MS;
27604
+ }
27605
+
28770
27606
  // ../../auth/src/robotClientFallback.ts
28771
27607
  init_src();
28772
27608
  var DEFAULT_TIMEOUT_MS = 1000;
28773
27609
  var CLOSE_TIMEOUT_MS = 500;
28774
- var NOTICE_SENTINEL = Symbol.for("@uipath/auth/robotFallbackNoticePrinted");
28775
- var printNoticeOnce = () => {
28776
- const slot = globalThis;
28777
- if (slot[NOTICE_SENTINEL])
28778
- return;
28779
- slot[NOTICE_SENTINEL] = true;
28780
- catchError2(() => process.stderr.write(`Using UiPath Robot credentials. Run 'uip login' for a dedicated session.
28781
- `));
28782
- };
28783
27610
  var ROBOT_USER_SERVICES_PIPE = "UiPathUserServices";
28784
27611
  var ROBOT_USER_SERVICES_ALTERNATE_PIPE = `${ROBOT_USER_SERVICES_PIPE}Alternate`;
28785
27612
  var PIPE_NAME_MAX_LENGTH = 103;
@@ -28895,7 +27722,6 @@ var tryRobotClientFallback = async (options = {}) => {
28895
27722
  issuerFromToken = issClaim;
28896
27723
  }
28897
27724
  }
28898
- printNoticeOnce();
28899
27725
  return {
28900
27726
  accessToken,
28901
27727
  baseUrl: parsedUrl.baseUrl,
@@ -29120,18 +27946,327 @@ var saveEnvFileAsync = async ({
29120
27946
  };
29121
27947
 
29122
27948
  // ../../auth/src/loginStatus.ts
29123
- function normalizeTokenRefreshFailure() {
29124
- return "stored refresh token is invalid or expired";
27949
+ var getLoginStatusAsync = async (options = {}) => {
27950
+ return getLoginStatusWithDeps(options);
27951
+ };
27952
+ var getLoginStatusWithDeps = async (options = {}, deps = {}) => {
27953
+ const {
27954
+ resolveEnvFilePath = resolveEnvFilePathAsync,
27955
+ loadEnvFile = loadEnvFileAsync,
27956
+ saveEnvFile = saveEnvFileAsync,
27957
+ getFs = getFileSystem,
27958
+ refreshToken: refreshTokenFn = refreshAccessToken,
27959
+ resolveConfig = resolveConfigAsync,
27960
+ robotFallback = tryRobotClientFallback,
27961
+ loadBreaker = loadRefreshBreaker,
27962
+ saveBreaker = saveRefreshBreaker,
27963
+ clearBreaker = clearRefreshBreaker
27964
+ } = deps;
27965
+ if (isRobotAuthEnforced()) {
27966
+ return resolveRobotEnforcedStatus(robotFallback);
27967
+ }
27968
+ if (isEnvAuthEnabled()) {
27969
+ return readAuthFromEnv();
27970
+ }
27971
+ const activeProfile = getActiveAuthProfile();
27972
+ const activeProfileFilePath = getActiveAuthProfileFilePath();
27973
+ const usingActiveProfile = activeProfile !== undefined && (options.envFilePath === undefined || options.envFilePath === activeProfileFilePath);
27974
+ const envFilePath = options.envFilePath ?? activeProfileFilePath ?? DEFAULT_ENV_FILENAME;
27975
+ const { ensureTokenValidityMinutes } = options;
27976
+ const { absolutePath } = await resolveEnvFilePath(envFilePath);
27977
+ if (absolutePath === undefined) {
27978
+ if (usingActiveProfile) {
27979
+ return {
27980
+ loginStatus: "Not logged in",
27981
+ hint: `No credentials found for profile "${activeProfile}". Run 'uip login --profile ${activeProfile}' to authenticate this profile.`
27982
+ };
27983
+ }
27984
+ return resolveBorrowedRobotStatus(robotFallback);
27985
+ }
27986
+ const loaded = await loadFileCredentials(loadEnvFile, absolutePath);
27987
+ if ("status" in loaded) {
27988
+ return loaded.status;
27989
+ }
27990
+ const { credentials } = loaded;
27991
+ const globalHint = () => usingActiveProfile ? Promise.resolve(undefined) : getGlobalCredsHint(getFs, loadEnvFile, absolutePath, envFilePath);
27992
+ const expiration = getTokenExpiration(credentials.UIPATH_ACCESS_TOKEN);
27993
+ const outerThreshold = computeExpirationThreshold(ensureTokenValidityMinutes);
27994
+ let tokens = {
27995
+ accessToken: credentials.UIPATH_ACCESS_TOKEN,
27996
+ refreshToken: credentials.UIPATH_REFRESH_TOKEN,
27997
+ expiration,
27998
+ lockReleaseFailed: false
27999
+ };
28000
+ const refreshToken = credentials.UIPATH_REFRESH_TOKEN;
28001
+ if (expiration && expiration <= outerThreshold && refreshToken) {
28002
+ const refreshed = await attemptRefresh({
28003
+ absolutePath,
28004
+ credentials,
28005
+ accessToken: credentials.UIPATH_ACCESS_TOKEN,
28006
+ refreshToken,
28007
+ expiration,
28008
+ ensureTokenValidityMinutes,
28009
+ getFs,
28010
+ loadEnvFile,
28011
+ saveEnvFile,
28012
+ refreshFn: refreshTokenFn,
28013
+ resolveConfig,
28014
+ loadBreaker,
28015
+ saveBreaker,
28016
+ clearBreaker,
28017
+ globalHint
28018
+ });
28019
+ if (refreshed.kind === "terminal") {
28020
+ return refreshed.status;
28021
+ }
28022
+ tokens = refreshed.tokens;
28023
+ }
28024
+ return buildFileStatus(tokens, credentials, globalHint);
28025
+ };
28026
+ async function resolveRobotEnforcedStatus(robotFallback) {
28027
+ if (isEnvAuthEnabled()) {
28028
+ throw new EnvAuthConfigError(`${ENV_AUTH_ENABLE_VAR}=true and ${ENFORCE_ROBOT_AUTH_VAR}=true ` + `are mutually exclusive. Unset one of them and re-run.`);
28029
+ }
28030
+ const robotCreds = await robotFallback({ force: true });
28031
+ if (!robotCreds) {
28032
+ return {
28033
+ loginStatus: "Not logged in",
28034
+ 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.`
28035
+ };
28036
+ }
28037
+ return buildRobotStatus(robotCreds);
29125
28038
  }
29126
- function normalizeTokenRefreshUnavailableFailure() {
29127
- return "token refresh failed before authentication completed";
28039
+ async function resolveBorrowedRobotStatus(robotFallback) {
28040
+ const robotCreds = await robotFallback();
28041
+ return robotCreds ? buildRobotStatus(robotCreds) : { loginStatus: "Not logged in" };
29128
28042
  }
29129
- function errorMessage(error) {
29130
- return error instanceof Error ? error.message : String(error);
28043
+ async function loadFileCredentials(loadEnvFile, absolutePath) {
28044
+ let credentials;
28045
+ try {
28046
+ credentials = await loadEnvFile({ envPath: absolutePath });
28047
+ } catch (error) {
28048
+ if (isFileNotFoundError(error)) {
28049
+ return { status: { loginStatus: "Not logged in" } };
28050
+ }
28051
+ throw error;
28052
+ }
28053
+ if (!credentials.UIPATH_ACCESS_TOKEN) {
28054
+ return { status: { loginStatus: "Not logged in" } };
28055
+ }
28056
+ return { credentials };
28057
+ }
28058
+ async function getGlobalCredsHint(getFs, loadEnvFile, absolutePath, envFilePath) {
28059
+ const fs7 = getFs();
28060
+ const globalPath = fs7.path.join(fs7.env.homedir(), envFilePath);
28061
+ if (absolutePath === globalPath)
28062
+ return;
28063
+ if (!await fs7.exists(globalPath))
28064
+ return;
28065
+ try {
28066
+ const globalCreds = await loadEnvFile({ envPath: globalPath });
28067
+ if (!globalCreds.UIPATH_ACCESS_TOKEN)
28068
+ return;
28069
+ const globalExp = getTokenExpiration(globalCreds.UIPATH_ACCESS_TOKEN);
28070
+ if (globalExp && globalExp <= new Date)
28071
+ return;
28072
+ 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.`;
28073
+ } catch {
28074
+ return;
28075
+ }
29131
28076
  }
29132
28077
  function computeExpirationThreshold(ensureTokenValidityMinutes) {
29133
28078
  return new Date(Date.now() + (ensureTokenValidityMinutes ?? 0) * 60 * 1000);
29134
28079
  }
28080
+ async function attemptRefresh(ctx) {
28081
+ const shortCircuit = await circuitBreakerShortCircuit(ctx);
28082
+ if (shortCircuit) {
28083
+ return { kind: "terminal", status: shortCircuit };
28084
+ }
28085
+ let release;
28086
+ try {
28087
+ release = await ctx.getFs().acquireLock(ctx.absolutePath);
28088
+ } catch (error) {
28089
+ return {
28090
+ kind: "terminal",
28091
+ status: await lockAcquireFailureStatus(ctx, error)
28092
+ };
28093
+ }
28094
+ let lockedFailure;
28095
+ let lockReleaseFailed = false;
28096
+ let success;
28097
+ try {
28098
+ const outcome = await runRefreshLocked({
28099
+ absolutePath: ctx.absolutePath,
28100
+ refreshToken: ctx.refreshToken,
28101
+ customAuthority: ctx.credentials.UIPATH_URL,
28102
+ ensureTokenValidityMinutes: ctx.ensureTokenValidityMinutes,
28103
+ loadEnvFile: ctx.loadEnvFile,
28104
+ saveEnvFile: ctx.saveEnvFile,
28105
+ refreshFn: ctx.refreshFn,
28106
+ resolveConfig: ctx.resolveConfig,
28107
+ loadBreaker: ctx.loadBreaker,
28108
+ saveBreaker: ctx.saveBreaker,
28109
+ clearBreaker: ctx.clearBreaker
28110
+ });
28111
+ if (outcome.kind === "fail") {
28112
+ lockedFailure = outcome.status;
28113
+ } else {
28114
+ success = outcome;
28115
+ }
28116
+ } finally {
28117
+ try {
28118
+ await release();
28119
+ } catch {
28120
+ lockReleaseFailed = true;
28121
+ }
28122
+ }
28123
+ if (lockedFailure) {
28124
+ const globalHint = await ctx.globalHint();
28125
+ const base = globalHint ? { ...lockedFailure, loginStatus: "Expired", hint: globalHint } : lockedFailure;
28126
+ return {
28127
+ kind: "terminal",
28128
+ status: lockReleaseFailed ? { ...base, lockReleaseFailed: true } : base
28129
+ };
28130
+ }
28131
+ return {
28132
+ kind: "refreshed",
28133
+ tokens: {
28134
+ accessToken: success?.accessToken,
28135
+ refreshToken: success?.refreshToken,
28136
+ expiration: success?.expiration,
28137
+ tokenRefresh: success?.tokenRefresh,
28138
+ persistenceWarning: success?.persistenceWarning,
28139
+ lockReleaseFailed
28140
+ }
28141
+ };
28142
+ }
28143
+ async function buildFileStatus(tokens, credentials, globalHint) {
28144
+ const result = {
28145
+ loginStatus: tokens.expiration && tokens.expiration <= new Date ? "Expired" : "Logged in",
28146
+ accessToken: tokens.accessToken,
28147
+ refreshToken: tokens.refreshToken,
28148
+ baseUrl: credentials.UIPATH_URL,
28149
+ organizationName: credentials.UIPATH_ORGANIZATION_NAME,
28150
+ organizationId: credentials.UIPATH_ORGANIZATION_ID,
28151
+ tenantName: credentials.UIPATH_TENANT_NAME,
28152
+ tenantId: credentials.UIPATH_TENANT_ID,
28153
+ expiration: tokens.expiration,
28154
+ source: "file" /* File */,
28155
+ ...tokens.persistenceWarning ? { hint: tokens.persistenceWarning, persistenceFailed: true } : {},
28156
+ ...tokens.lockReleaseFailed ? { lockReleaseFailed: true } : {},
28157
+ ...tokens.tokenRefresh ? { tokenRefresh: tokens.tokenRefresh } : {}
28158
+ };
28159
+ if (result.loginStatus === "Expired") {
28160
+ const hint = await globalHint();
28161
+ if (hint) {
28162
+ result.hint = hint;
28163
+ }
28164
+ }
28165
+ return result;
28166
+ }
28167
+ function buildRobotStatus(robotCreds) {
28168
+ return {
28169
+ loginStatus: "Logged in",
28170
+ accessToken: robotCreds.accessToken,
28171
+ baseUrl: robotCreds.baseUrl,
28172
+ organizationName: robotCreds.organizationName,
28173
+ organizationId: robotCreds.organizationId,
28174
+ tenantName: robotCreds.tenantName,
28175
+ tenantId: robotCreds.tenantId,
28176
+ issuer: robotCreds.issuer,
28177
+ expiration: getTokenExpiration(robotCreds.accessToken),
28178
+ source: "robot" /* Robot */
28179
+ };
28180
+ }
28181
+ var isFileNotFoundError = (error) => {
28182
+ if (!(error instanceof Object))
28183
+ return false;
28184
+ return error.code === "ENOENT";
28185
+ };
28186
+ async function circuitBreakerShortCircuit(ctx) {
28187
+ const {
28188
+ absolutePath,
28189
+ refreshToken,
28190
+ accessToken,
28191
+ credentials,
28192
+ expiration,
28193
+ loadBreaker,
28194
+ saveBreaker,
28195
+ clearBreaker
28196
+ } = ctx;
28197
+ const fingerprint = await refreshTokenFingerprint(refreshToken);
28198
+ const breaker = await loadBreaker(absolutePath).catch(() => ({}));
28199
+ if (breaker.deadTokenFp && breaker.deadTokenFp !== fingerprint) {
28200
+ await clearBreaker(absolutePath);
28201
+ breaker.deadTokenFp = undefined;
28202
+ }
28203
+ const nowMs = Date.now();
28204
+ const tokenIsDead = breaker.deadTokenFp === fingerprint;
28205
+ const inBackoff = breaker.backoffUntilMs !== undefined && nowMs < breaker.backoffUntilMs;
28206
+ if (!tokenIsDead && !inBackoff)
28207
+ return;
28208
+ const globalHint = await ctx.globalHint();
28209
+ const suppressed = !shouldSurface(breaker, nowMs);
28210
+ if (!suppressed) {
28211
+ await saveBreaker(absolutePath, {
28212
+ ...breaker,
28213
+ lastSurfacedAtMs: nowMs
28214
+ });
28215
+ }
28216
+ 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>.";
28217
+ const backoffHint = "Token refresh is temporarily backed off after a recent network error and will retry automatically once the backoff window elapses.";
28218
+ return {
28219
+ loginStatus: globalHint ? "Expired" : "Refresh Failed",
28220
+ ...globalHint ? {
28221
+ accessToken,
28222
+ refreshToken,
28223
+ baseUrl: credentials.UIPATH_URL,
28224
+ organizationName: credentials.UIPATH_ORGANIZATION_NAME,
28225
+ organizationId: credentials.UIPATH_ORGANIZATION_ID,
28226
+ tenantName: credentials.UIPATH_TENANT_NAME,
28227
+ tenantId: credentials.UIPATH_TENANT_ID,
28228
+ expiration,
28229
+ source: "file" /* File */
28230
+ } : {},
28231
+ hint: globalHint ?? (tokenIsDead ? deadHint : backoffHint),
28232
+ refreshCircuitOpen: true,
28233
+ refreshTelemetrySuppressed: suppressed,
28234
+ tokenRefresh: { attempted: false, success: false }
28235
+ };
28236
+ }
28237
+ async function lockAcquireFailureStatus(ctx, error) {
28238
+ const msg = errorMessage(error);
28239
+ const globalHint = await ctx.globalHint();
28240
+ if (globalHint) {
28241
+ return {
28242
+ loginStatus: "Expired",
28243
+ accessToken: ctx.accessToken,
28244
+ refreshToken: ctx.refreshToken,
28245
+ baseUrl: ctx.credentials.UIPATH_URL,
28246
+ organizationName: ctx.credentials.UIPATH_ORGANIZATION_NAME,
28247
+ organizationId: ctx.credentials.UIPATH_ORGANIZATION_ID,
28248
+ tenantName: ctx.credentials.UIPATH_TENANT_NAME,
28249
+ tenantId: ctx.credentials.UIPATH_TENANT_ID,
28250
+ expiration: ctx.expiration,
28251
+ source: "file" /* File */,
28252
+ hint: globalHint,
28253
+ tokenRefresh: {
28254
+ attempted: false,
28255
+ success: false,
28256
+ errorMessage: `lock acquisition failed: ${msg}`
28257
+ }
28258
+ };
28259
+ }
28260
+ return {
28261
+ loginStatus: "Refresh Failed",
28262
+ 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.",
28263
+ tokenRefresh: {
28264
+ attempted: false,
28265
+ success: false,
28266
+ errorMessage: `lock acquisition failed: ${msg}`
28267
+ }
28268
+ };
28269
+ }
29135
28270
  async function runRefreshLocked(inputs) {
29136
28271
  const {
29137
28272
  absolutePath,
@@ -29141,7 +28276,10 @@ async function runRefreshLocked(inputs) {
29141
28276
  loadEnvFile,
29142
28277
  saveEnvFile,
29143
28278
  refreshFn,
29144
- resolveConfig
28279
+ resolveConfig,
28280
+ loadBreaker,
28281
+ saveBreaker,
28282
+ clearBreaker
29145
28283
  } = inputs;
29146
28284
  const expirationThreshold = computeExpirationThreshold(ensureTokenValidityMinutes);
29147
28285
  let fresh;
@@ -29164,6 +28302,7 @@ async function runRefreshLocked(inputs) {
29164
28302
  const freshAccess = fresh.UIPATH_ACCESS_TOKEN;
29165
28303
  const freshExp = freshAccess ? getTokenExpiration(freshAccess) : undefined;
29166
28304
  if (freshAccess && freshExp && freshExp > expirationThreshold) {
28305
+ await clearBreaker(absolutePath);
29167
28306
  return {
29168
28307
  kind: "ok",
29169
28308
  accessToken: freshAccess,
@@ -29187,8 +28326,21 @@ async function runRefreshLocked(inputs) {
29187
28326
  refreshedRefresh = refreshed.refreshToken;
29188
28327
  } catch (error) {
29189
28328
  const isOAuthFailure = isTokenRefreshOAuthFailure(error);
29190
- 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.";
28329
+ 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.";
29191
28330
  const message = isOAuthFailure ? normalizeTokenRefreshFailure() : normalizeTokenRefreshUnavailableFailure();
28331
+ const fp = await refreshTokenFingerprint(tokenForIdP);
28332
+ if (isOAuthFailure) {
28333
+ await saveBreaker(absolutePath, { deadTokenFp: fp });
28334
+ } else {
28335
+ const prior = await loadBreaker(absolutePath).catch(() => ({}));
28336
+ const attempts = (prior.attempts ?? 0) + 1;
28337
+ await saveBreaker(absolutePath, {
28338
+ ...prior,
28339
+ deadTokenFp: undefined,
28340
+ attempts,
28341
+ backoffUntilMs: Date.now() + nextBackoffMs(attempts)
28342
+ });
28343
+ }
29192
28344
  return {
29193
28345
  kind: "fail",
29194
28346
  status: {
@@ -29217,6 +28369,7 @@ async function runRefreshLocked(inputs) {
29217
28369
  }
29218
28370
  };
29219
28371
  }
28372
+ await clearBreaker(absolutePath);
29220
28373
  try {
29221
28374
  await saveEnvFile({
29222
28375
  envPath: absolutePath,
@@ -29249,214 +28402,25 @@ async function runRefreshLocked(inputs) {
29249
28402
  };
29250
28403
  }
29251
28404
  }
29252
- var getLoginStatusWithDeps = async (options = {}, deps = {}) => {
29253
- const {
29254
- resolveEnvFilePath = resolveEnvFilePathAsync,
29255
- loadEnvFile = loadEnvFileAsync,
29256
- saveEnvFile = saveEnvFileAsync,
29257
- getFs = getFileSystem,
29258
- refreshToken: refreshTokenFn = refreshAccessToken,
29259
- resolveConfig = resolveConfigAsync,
29260
- robotFallback = tryRobotClientFallback
29261
- } = deps;
29262
- if (isRobotAuthEnforced()) {
29263
- if (isEnvAuthEnabled()) {
29264
- throw new EnvAuthConfigError(`${ENV_AUTH_ENABLE_VAR}=true and ${ENFORCE_ROBOT_AUTH_VAR}=true ` + `are mutually exclusive. Unset one of them and re-run.`);
29265
- }
29266
- const robotCreds = await robotFallback({ force: true });
29267
- if (!robotCreds) {
29268
- return {
29269
- loginStatus: "Not logged in",
29270
- 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.`
29271
- };
29272
- }
29273
- const expiration2 = getTokenExpiration(robotCreds.accessToken);
29274
- return {
29275
- loginStatus: "Logged in",
29276
- accessToken: robotCreds.accessToken,
29277
- baseUrl: robotCreds.baseUrl,
29278
- organizationName: robotCreds.organizationName,
29279
- organizationId: robotCreds.organizationId,
29280
- tenantName: robotCreds.tenantName,
29281
- tenantId: robotCreds.tenantId,
29282
- issuer: robotCreds.issuer,
29283
- expiration: expiration2,
29284
- source: "robot" /* Robot */
29285
- };
29286
- }
29287
- if (isEnvAuthEnabled()) {
29288
- return readAuthFromEnv();
29289
- }
29290
- const { envFilePath = DEFAULT_ENV_FILENAME, ensureTokenValidityMinutes } = options;
29291
- const { absolutePath } = await resolveEnvFilePath(envFilePath);
29292
- if (absolutePath === undefined) {
29293
- const robotCreds = await robotFallback();
29294
- if (robotCreds) {
29295
- const expiration2 = getTokenExpiration(robotCreds.accessToken);
29296
- const status = {
29297
- loginStatus: "Logged in",
29298
- accessToken: robotCreds.accessToken,
29299
- baseUrl: robotCreds.baseUrl,
29300
- organizationName: robotCreds.organizationName,
29301
- organizationId: robotCreds.organizationId,
29302
- tenantName: robotCreds.tenantName,
29303
- tenantId: robotCreds.tenantId,
29304
- issuer: robotCreds.issuer,
29305
- expiration: expiration2,
29306
- source: "robot" /* Robot */
29307
- };
29308
- return status;
29309
- }
29310
- return { loginStatus: "Not logged in" };
29311
- }
29312
- let credentials;
29313
- try {
29314
- credentials = await loadEnvFile({ envPath: absolutePath });
29315
- } catch (error) {
29316
- if (isFileNotFoundError(error)) {
29317
- return { loginStatus: "Not logged in" };
29318
- }
29319
- throw error;
29320
- }
29321
- if (!credentials.UIPATH_ACCESS_TOKEN) {
29322
- return { loginStatus: "Not logged in" };
29323
- }
29324
- let accessToken = credentials.UIPATH_ACCESS_TOKEN;
29325
- let refreshToken = credentials.UIPATH_REFRESH_TOKEN;
29326
- let expiration = getTokenExpiration(accessToken);
29327
- let persistenceWarning;
29328
- let lockReleaseFailed = false;
29329
- let tokenRefresh;
29330
- const outerThreshold = computeExpirationThreshold(ensureTokenValidityMinutes);
29331
- const tryGlobalCredsHint = async () => {
29332
- const fs7 = getFs();
29333
- const globalPath = fs7.path.join(fs7.env.homedir(), envFilePath);
29334
- if (absolutePath === globalPath)
29335
- return;
29336
- if (!await fs7.exists(globalPath))
29337
- return;
29338
- try {
29339
- const globalCreds = await loadEnvFile({ envPath: globalPath });
29340
- if (!globalCreds.UIPATH_ACCESS_TOKEN)
29341
- return;
29342
- const globalExp = getTokenExpiration(globalCreds.UIPATH_ACCESS_TOKEN);
29343
- if (globalExp && globalExp <= new Date)
29344
- return;
29345
- 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.`;
29346
- } catch {
29347
- return;
29348
- }
29349
- };
29350
- if (expiration && expiration <= outerThreshold && refreshToken) {
29351
- let release;
29352
- try {
29353
- release = await getFs().acquireLock(absolutePath);
29354
- } catch (error) {
29355
- const msg = errorMessage(error);
29356
- const globalHint = await tryGlobalCredsHint();
29357
- if (globalHint) {
29358
- return {
29359
- loginStatus: "Expired",
29360
- accessToken,
29361
- refreshToken,
29362
- baseUrl: credentials.UIPATH_URL,
29363
- organizationName: credentials.UIPATH_ORGANIZATION_NAME,
29364
- organizationId: credentials.UIPATH_ORGANIZATION_ID,
29365
- tenantName: credentials.UIPATH_TENANT_NAME,
29366
- tenantId: credentials.UIPATH_TENANT_ID,
29367
- expiration,
29368
- source: "file" /* File */,
29369
- hint: globalHint,
29370
- tokenRefresh: {
29371
- attempted: false,
29372
- success: false,
29373
- errorMessage: `lock acquisition failed: ${msg}`
29374
- }
29375
- };
29376
- }
29377
- return {
29378
- loginStatus: "Refresh Failed",
29379
- 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.",
29380
- tokenRefresh: {
29381
- attempted: false,
29382
- success: false,
29383
- errorMessage: `lock acquisition failed: ${msg}`
29384
- }
29385
- };
29386
- }
29387
- let lockedFailure;
29388
- try {
29389
- const outcome = await runRefreshLocked({
29390
- absolutePath,
29391
- refreshToken,
29392
- customAuthority: credentials.UIPATH_URL,
29393
- ensureTokenValidityMinutes,
29394
- loadEnvFile,
29395
- saveEnvFile,
29396
- refreshFn: refreshTokenFn,
29397
- resolveConfig
29398
- });
29399
- if (outcome.kind === "fail") {
29400
- lockedFailure = outcome.status;
29401
- } else {
29402
- accessToken = outcome.accessToken;
29403
- refreshToken = outcome.refreshToken;
29404
- expiration = outcome.expiration;
29405
- tokenRefresh = outcome.tokenRefresh;
29406
- if (outcome.persistenceWarning) {
29407
- persistenceWarning = outcome.persistenceWarning;
29408
- }
29409
- }
29410
- } finally {
29411
- try {
29412
- await release();
29413
- } catch {
29414
- lockReleaseFailed = true;
29415
- }
29416
- }
29417
- if (lockedFailure) {
29418
- const globalHint = await tryGlobalCredsHint();
29419
- const base = globalHint ? {
29420
- ...lockedFailure,
29421
- loginStatus: "Expired",
29422
- hint: globalHint
29423
- } : lockedFailure;
29424
- return lockReleaseFailed ? { ...base, lockReleaseFailed: true } : base;
29425
- }
29426
- }
29427
- const result = {
29428
- loginStatus: expiration && expiration <= new Date ? "Expired" : "Logged in",
29429
- accessToken,
29430
- refreshToken,
29431
- baseUrl: credentials.UIPATH_URL,
29432
- organizationName: credentials.UIPATH_ORGANIZATION_NAME,
29433
- organizationId: credentials.UIPATH_ORGANIZATION_ID,
29434
- tenantName: credentials.UIPATH_TENANT_NAME,
29435
- tenantId: credentials.UIPATH_TENANT_ID,
29436
- expiration,
29437
- source: "file" /* File */,
29438
- ...persistenceWarning ? { hint: persistenceWarning, persistenceFailed: true } : {},
29439
- ...lockReleaseFailed ? { lockReleaseFailed: true } : {},
29440
- ...tokenRefresh ? { tokenRefresh } : {}
29441
- };
29442
- if (result.loginStatus === "Expired") {
29443
- const globalHint = await tryGlobalCredsHint();
29444
- if (globalHint) {
29445
- result.hint = globalHint;
29446
- }
29447
- }
29448
- return result;
29449
- };
29450
- var isFileNotFoundError = (error) => {
29451
- if (!(error instanceof Object))
29452
- return false;
29453
- return error.code === "ENOENT";
29454
- };
29455
- var getLoginStatusAsync = async (options = {}) => {
29456
- return getLoginStatusWithDeps(options);
29457
- };
28405
+ function normalizeTokenRefreshFailure() {
28406
+ return "stored refresh token is invalid or expired";
28407
+ }
28408
+ function normalizeTokenRefreshUnavailableFailure() {
28409
+ return "token refresh failed before authentication completed";
28410
+ }
28411
+ function errorMessage(error) {
28412
+ return error instanceof Error ? error.message : String(error);
28413
+ }
29458
28414
  // ../../auth/src/interactive.ts
29459
28415
  init_src();
28416
+
28417
+ // ../../auth/src/selectTenant.ts
28418
+ var TENANT_SELECTION_REQUIRED_CODE = "TENANT_SELECTION_REQUIRED";
28419
+ var INVALID_TENANT_CODE = "INVALID_TENANT";
28420
+ var TENANT_SELECTION_CODES = new Set([
28421
+ TENANT_SELECTION_REQUIRED_CODE,
28422
+ INVALID_TENANT_CODE
28423
+ ]);
29460
28424
  // ../../auth/src/logout.ts
29461
28425
  init_src();
29462
28426
 
@@ -29731,3 +28695,5 @@ export {
29731
28695
  registerCommands,
29732
28696
  metadata
29733
28697
  };
28698
+
28699
+ //# debugId=720FEB77491ED6BB64756E2164756E21