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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/index.js +2 -0
  2. package/dist/tool.js +734 -1750
  3. package/package.json +2 -2
package/dist/tool.js CHANGED
@@ -13540,8 +13540,8 @@ var require_Subscription = __commonJS((exports) => {
13540
13540
  if (_parentOrParents instanceof Subscription2) {
13541
13541
  _parentOrParents.remove(this);
13542
13542
  } else if (_parentOrParents !== null) {
13543
- for (var index2 = 0;index2 < _parentOrParents.length; ++index2) {
13544
- var parent_1 = _parentOrParents[index2];
13543
+ for (var index = 0;index < _parentOrParents.length; ++index) {
13544
+ var parent_1 = _parentOrParents[index];
13545
13545
  parent_1.remove(this);
13546
13546
  }
13547
13547
  }
@@ -13556,10 +13556,10 @@ var require_Subscription = __commonJS((exports) => {
13556
13556
  }
13557
13557
  }
13558
13558
  if (isArray_1.isArray(_subscriptions)) {
13559
- var index2 = -1;
13559
+ var index = -1;
13560
13560
  var len = _subscriptions.length;
13561
- while (++index2 < len) {
13562
- var sub2 = _subscriptions[index2];
13561
+ while (++index < len) {
13562
+ var sub2 = _subscriptions[index];
13563
13563
  if (isObject_1.isObject(sub2)) {
13564
13564
  try {
13565
13565
  sub2.unsubscribe();
@@ -14989,13 +14989,13 @@ var require_AsyncAction = __commonJS((exports) => {
14989
14989
  var id = this.id;
14990
14990
  var scheduler = this.scheduler;
14991
14991
  var actions = scheduler.actions;
14992
- var index2 = actions.indexOf(this);
14992
+ var index = actions.indexOf(this);
14993
14993
  this.work = null;
14994
14994
  this.state = null;
14995
14995
  this.pending = false;
14996
14996
  this.scheduler = null;
14997
- if (index2 !== -1) {
14998
- actions.splice(index2, 1);
14997
+ if (index !== -1) {
14998
+ actions.splice(index, 1);
14999
14999
  }
15000
15000
  if (id != null) {
15001
15001
  this.id = this.recycleAsyncId(scheduler, id, null);
@@ -15839,17 +15839,17 @@ var require_AsapScheduler = __commonJS((exports) => {
15839
15839
  this.scheduled = undefined;
15840
15840
  var actions = this.actions;
15841
15841
  var error;
15842
- var index2 = -1;
15842
+ var index = -1;
15843
15843
  var count = actions.length;
15844
15844
  action = action || actions.shift();
15845
15845
  do {
15846
15846
  if (error = action.execute(action.state, action.delay)) {
15847
15847
  break;
15848
15848
  }
15849
- } while (++index2 < count && (action = actions.shift()));
15849
+ } while (++index < count && (action = actions.shift()));
15850
15850
  this.active = false;
15851
15851
  if (error) {
15852
- while (++index2 < count && (action = actions.shift())) {
15852
+ while (++index < count && (action = actions.shift())) {
15853
15853
  action.unsubscribe();
15854
15854
  }
15855
15855
  throw error;
@@ -15972,17 +15972,17 @@ var require_AnimationFrameScheduler = __commonJS((exports) => {
15972
15972
  this.scheduled = undefined;
15973
15973
  var actions = this.actions;
15974
15974
  var error;
15975
- var index2 = -1;
15975
+ var index = -1;
15976
15976
  var count = actions.length;
15977
15977
  action = action || actions.shift();
15978
15978
  do {
15979
15979
  if (error = action.execute(action.state, action.delay)) {
15980
15980
  break;
15981
15981
  }
15982
- } while (++index2 < count && (action = actions.shift()));
15982
+ } while (++index < count && (action = actions.shift()));
15983
15983
  this.active = false;
15984
15984
  if (error) {
15985
- while (++index2 < count && (action = actions.shift())) {
15985
+ while (++index < count && (action = actions.shift())) {
15986
15986
  action.unsubscribe();
15987
15987
  }
15988
15988
  throw error;
@@ -16066,16 +16066,16 @@ var require_VirtualTimeScheduler = __commonJS((exports) => {
16066
16066
  exports.VirtualTimeScheduler = VirtualTimeScheduler;
16067
16067
  var VirtualAction = function(_super) {
16068
16068
  __extends(VirtualAction2, _super);
16069
- function VirtualAction2(scheduler, work, index2) {
16070
- if (index2 === undefined) {
16071
- index2 = scheduler.index += 1;
16069
+ function VirtualAction2(scheduler, work, index) {
16070
+ if (index === undefined) {
16071
+ index = scheduler.index += 1;
16072
16072
  }
16073
16073
  var _this = _super.call(this, scheduler, work) || this;
16074
16074
  _this.scheduler = scheduler;
16075
16075
  _this.work = work;
16076
- _this.index = index2;
16076
+ _this.index = index;
16077
16077
  _this.active = true;
16078
- _this.index = scheduler.index = index2;
16078
+ _this.index = scheduler.index = index;
16079
16079
  return _this;
16080
16080
  }
16081
16081
  VirtualAction2.prototype.schedule = function(state, delay) {
@@ -17222,9 +17222,9 @@ var require_mergeMap = __commonJS((exports) => {
17222
17222
  };
17223
17223
  MergeMapSubscriber2.prototype._tryNext = function(value) {
17224
17224
  var result;
17225
- var index2 = this.index++;
17225
+ var index = this.index++;
17226
17226
  try {
17227
- result = this.project(value, index2);
17227
+ result = this.project(value, index);
17228
17228
  } catch (err) {
17229
17229
  this.destination.error(err);
17230
17230
  return;
@@ -17804,12 +17804,12 @@ var require_pairs2 = __commonJS((exports) => {
17804
17804
  }
17805
17805
  exports.pairs = pairs;
17806
17806
  function dispatch(state) {
17807
- var { keys, index: index2, subscriber, subscription, obj } = state;
17807
+ var { keys, index, subscriber, subscription, obj } = state;
17808
17808
  if (!subscriber.closed) {
17809
- if (index2 < keys.length) {
17810
- var key = keys[index2];
17809
+ if (index < keys.length) {
17810
+ var key = keys[index];
17811
17811
  subscriber.next([key, obj[key]]);
17812
- subscription.add(this.schedule({ keys, index: index2 + 1, subscriber, subscription, obj }));
17812
+ subscription.add(this.schedule({ keys, index: index + 1, subscriber, subscription, obj }));
17813
17813
  } else {
17814
17814
  subscriber.complete();
17815
17815
  }
@@ -18022,18 +18022,18 @@ var require_range = __commonJS((exports) => {
18022
18022
  count = start;
18023
18023
  start = 0;
18024
18024
  }
18025
- var index2 = 0;
18025
+ var index = 0;
18026
18026
  var current = start;
18027
18027
  if (scheduler) {
18028
18028
  return scheduler.schedule(dispatch, 0, {
18029
- index: index2,
18029
+ index,
18030
18030
  count,
18031
18031
  start,
18032
18032
  subscriber
18033
18033
  });
18034
18034
  } else {
18035
18035
  do {
18036
- if (index2++ >= count) {
18036
+ if (index++ >= count) {
18037
18037
  subscriber.complete();
18038
18038
  break;
18039
18039
  }
@@ -18048,8 +18048,8 @@ var require_range = __commonJS((exports) => {
18048
18048
  }
18049
18049
  exports.range = range;
18050
18050
  function dispatch(state) {
18051
- var { start, index: index2, count, subscriber } = state;
18052
- if (index2 >= count) {
18051
+ var { start, index, count, subscriber } = state;
18052
+ if (index >= count) {
18053
18053
  subscriber.complete();
18054
18054
  return;
18055
18055
  }
@@ -18057,7 +18057,7 @@ var require_range = __commonJS((exports) => {
18057
18057
  if (subscriber.closed) {
18058
18058
  return;
18059
18059
  }
18060
- state.index = index2 + 1;
18060
+ state.index = index + 1;
18061
18061
  state.start = start + 1;
18062
18062
  this.schedule(state);
18063
18063
  }
@@ -18095,14 +18095,14 @@ var require_timer = __commonJS((exports) => {
18095
18095
  }
18096
18096
  exports.timer = timer;
18097
18097
  function dispatch(state) {
18098
- var { index: index2, period, subscriber } = state;
18099
- subscriber.next(index2);
18098
+ var { index, period, subscriber } = state;
18099
+ subscriber.next(index);
18100
18100
  if (subscriber.closed) {
18101
18101
  return;
18102
18102
  } else if (period === -1) {
18103
18103
  return subscriber.complete();
18104
18104
  }
18105
- state.index = index2 + 1;
18105
+ state.index = index + 1;
18106
18106
  this.schedule(state, period);
18107
18107
  }
18108
18108
  });
@@ -21250,7 +21250,7 @@ var init_server = __esm(() => {
21250
21250
  var package_default = {
21251
21251
  name: "@uipath/orchestrator-tool",
21252
21252
  license: "MIT",
21253
- version: "1.196.0",
21253
+ version: "1.197.0-preview.59",
21254
21254
  description: "Manage Orchestrator folders, jobs, processes, and releases.",
21255
21255
  private: false,
21256
21256
  repository: {
@@ -21341,27 +21341,54 @@ var NETWORK_ERROR_CODES = new Set([
21341
21341
  "ENETUNREACH",
21342
21342
  "EAI_FAIL"
21343
21343
  ]);
21344
- function isHtmlDocument(body) {
21345
- return /^\s*(<!doctype html|<html\b)/i.test(body);
21346
- }
21347
- function extractNetworkErrorCode(error) {
21348
- if (error === null || typeof error !== "object") {
21349
- return;
21350
- }
21351
- const err = error;
21352
- const code = typeof err.code === "string" ? err.code : undefined;
21353
- if (code && NETWORK_ERROR_CODES.has(code)) {
21354
- return code;
21355
- }
21356
- const cause = err.cause;
21357
- if (cause !== null && typeof cause === "object") {
21358
- const causeCode = cause.code;
21359
- if (typeof causeCode === "string" && NETWORK_ERROR_CODES.has(causeCode)) {
21360
- return causeCode;
21344
+ var TLS_ERROR_CODES = new Set([
21345
+ "SELF_SIGNED_CERT_IN_CHAIN",
21346
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
21347
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
21348
+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
21349
+ "UNABLE_TO_GET_ISSUER_CERT",
21350
+ "CERT_HAS_EXPIRED",
21351
+ "CERT_UNTRUSTED",
21352
+ "ERR_TLS_CERT_ALTNAME_INVALID"
21353
+ ]);
21354
+ 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.";
21355
+ 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.";
21356
+ function describeConnectivityError(error) {
21357
+ let current = error;
21358
+ for (let depth = 0;depth < 5 && current !== null && typeof current === "object"; depth++) {
21359
+ const cur = current;
21360
+ const code = typeof cur.code === "string" ? cur.code : undefined;
21361
+ const message = typeof cur.message === "string" ? cur.message : undefined;
21362
+ if (code && TLS_ERROR_CODES.has(code)) {
21363
+ return {
21364
+ code,
21365
+ kind: "tls",
21366
+ message: message ?? code,
21367
+ instructions: TLS_INSTRUCTIONS
21368
+ };
21361
21369
  }
21370
+ if (code && NETWORK_ERROR_CODES.has(code)) {
21371
+ return {
21372
+ code,
21373
+ kind: "network",
21374
+ message: message ?? code,
21375
+ instructions: NETWORK_INSTRUCTIONS
21376
+ };
21377
+ }
21378
+ current = cur.cause;
21362
21379
  }
21363
21380
  return;
21364
21381
  }
21382
+ function parseHttpStatusFromMessage(message) {
21383
+ const match = /^HTTP\s+(\d{3})(?::|\s|-|$)/i.exec(message.trim());
21384
+ if (!match)
21385
+ return;
21386
+ const status = Number(match[1]);
21387
+ return Number.isInteger(status) && status >= 100 && status <= 599 ? status : undefined;
21388
+ }
21389
+ function isHtmlDocument(body) {
21390
+ return /^\s*(<!doctype html|<html\b)/i.test(body);
21391
+ }
21365
21392
  function retryHintForRetryAfter(seconds) {
21366
21393
  if (seconds <= 1) {
21367
21394
  return "RetryAfter1Second";
@@ -21402,15 +21429,28 @@ function classifyError(status, error) {
21402
21429
  if (status !== undefined && status >= 500 && status < 600) {
21403
21430
  return { errorCode: "server_error", retry: "RetryLater" };
21404
21431
  }
21405
- if (extractNetworkErrorCode(error)) {
21406
- return { errorCode: "network_error", retry: "RetryLater" };
21432
+ const connectivity = describeConnectivityError(error);
21433
+ if (connectivity) {
21434
+ return {
21435
+ errorCode: "network_error",
21436
+ retry: connectivity.kind === "tls" ? "RetryWillNotFix" : "RetryLater"
21437
+ };
21407
21438
  }
21408
21439
  return { errorCode: "unknown_error", retry: "RetryWillNotFix" };
21409
21440
  }
21441
+ function formatHttpStatusMessage(status, rawMessage, extractedMessage, inferredStatus) {
21442
+ if (extractedMessage) {
21443
+ return `HTTP ${status}: ${extractedMessage}`;
21444
+ }
21445
+ return inferredStatus !== undefined ? rawMessage : `HTTP ${status}: ${rawMessage}`;
21446
+ }
21410
21447
  async function extractErrorDetails(error, options) {
21411
21448
  const err = error !== null && error !== undefined && typeof error === "object" ? error : {};
21412
21449
  const response = err.response;
21413
- const status = err.status ?? response?.status;
21450
+ const rawMessage = typeof err.message === "string" ? err.message : "Unknown error";
21451
+ const explicitStatus = err.status ?? response?.status;
21452
+ const inferredStatus = explicitStatus === undefined ? parseHttpStatusFromMessage(rawMessage) : undefined;
21453
+ const status = explicitStatus ?? inferredStatus;
21414
21454
  const isSuccessfulResponse = status !== undefined && status >= 200 && status < 300;
21415
21455
  let rawBody;
21416
21456
  let extractedMessage;
@@ -21445,7 +21485,6 @@ async function extractErrorDetails(error, options) {
21445
21485
  }
21446
21486
  }
21447
21487
  }
21448
- const rawMessage = typeof err.message === "string" ? err.message : "Unknown error";
21449
21488
  let message;
21450
21489
  let result = "Failure";
21451
21490
  const classification = classifyError(status, error);
@@ -21459,10 +21498,10 @@ async function extractErrorDetails(error, options) {
21459
21498
  } else if (status === 405) {
21460
21499
  message = DEFAULT_405;
21461
21500
  } else if (status === 400 || status === 422) {
21462
- message = extractedMessage ? `HTTP ${status}: ${extractedMessage}` : `HTTP ${status}: ${rawMessage}`;
21501
+ message = formatHttpStatusMessage(status, rawMessage, extractedMessage, inferredStatus);
21463
21502
  result = "ValidationError";
21464
21503
  } else if (status === 429) {
21465
- message = extractedMessage ? `HTTP ${status}: ${extractedMessage}` : `HTTP ${status}: ${rawMessage}`;
21504
+ message = formatHttpStatusMessage(status, rawMessage, extractedMessage, inferredStatus);
21466
21505
  } else if (extractedMessage) {
21467
21506
  if (isSuccessfulResponse && rawMessage !== "Unknown error") {
21468
21507
  message = rawMessage;
@@ -21470,7 +21509,9 @@ async function extractErrorDetails(error, options) {
21470
21509
  message = status ? `HTTP ${status}: ${extractedMessage}` : extractedMessage;
21471
21510
  }
21472
21511
  } else if (status) {
21473
- if (rawMessage === "Unknown error" && response) {
21512
+ if (inferredStatus !== undefined) {
21513
+ message = rawMessage;
21514
+ } else if (rawMessage === "Unknown error" && response) {
21474
21515
  const statusText = response.statusText;
21475
21516
  message = statusText ? `HTTP ${status} ${statusText}` : `HTTP ${status} - request failed`;
21476
21517
  } else {
@@ -21479,6 +21520,12 @@ async function extractErrorDetails(error, options) {
21479
21520
  } else {
21480
21521
  message = rawMessage;
21481
21522
  }
21523
+ if (status === undefined) {
21524
+ const connectivity = describeConnectivityError(error);
21525
+ if (connectivity && connectivity.message !== message && !message.includes(connectivity.message)) {
21526
+ message = `${message}: ${connectivity.message}`;
21527
+ }
21528
+ }
21482
21529
  let details = rawMessage;
21483
21530
  if (rawBody) {
21484
21531
  if (parsedBody) {
@@ -21660,6 +21707,7 @@ var CONSOLE_FALLBACK = {
21660
21707
  writeLog: (str) => process.stdout.write(str),
21661
21708
  capabilities: {
21662
21709
  isInteractive: false,
21710
+ canReadInput: false,
21663
21711
  supportsColor: false,
21664
21712
  outputWidth: 80
21665
21713
  }
@@ -26881,6 +26929,29 @@ function isPlainRecord(value) {
26881
26929
  const prototype = Object.getPrototypeOf(value);
26882
26930
  return prototype === Object.prototype || prototype === null;
26883
26931
  }
26932
+ function extractPagedRows(value) {
26933
+ if (Array.isArray(value) || !isPlainRecord(value))
26934
+ return null;
26935
+ const entries = Object.values(value);
26936
+ if (entries.length === 0)
26937
+ return null;
26938
+ let rows = null;
26939
+ let hasScalarSibling = false;
26940
+ for (const entry of entries) {
26941
+ if (Array.isArray(entry)) {
26942
+ if (rows !== null)
26943
+ return null;
26944
+ rows = entry;
26945
+ } else if (entry !== null && typeof entry === "object") {
26946
+ return null;
26947
+ } else {
26948
+ hasScalarSibling = true;
26949
+ }
26950
+ }
26951
+ if (rows === null || !hasScalarSibling)
26952
+ return null;
26953
+ return rows;
26954
+ }
26884
26955
  function toLowerCamelCaseKey(key) {
26885
26956
  if (!key)
26886
26957
  return key;
@@ -26945,7 +27016,8 @@ function printOutput(data, format = "json", logFn, asciiSafe = false) {
26945
27016
  break;
26946
27017
  case "plain": {
26947
27018
  if ("Data" in data && data.Data != null) {
26948
- const items = Array.isArray(data.Data) ? data.Data : [data.Data];
27019
+ const pagedRows = extractPagedRows(data.Data);
27020
+ const items = pagedRows ?? (Array.isArray(data.Data) ? data.Data : [data.Data]);
26949
27021
  items.forEach((item) => {
26950
27022
  const values = Object.values(item).map((v) => v ?? "").join("\t");
26951
27023
  logFn(values);
@@ -26957,10 +27029,13 @@ function printOutput(data, format = "json", logFn, asciiSafe = false) {
26957
27029
  break;
26958
27030
  }
26959
27031
  default: {
26960
- if ("Data" in data && data.Data != null && !(Array.isArray(data.Data) && data.Data.length === 0)) {
27032
+ const hasData = "Data" in data && data.Data != null;
27033
+ const pagedRows = hasData ? extractPagedRows(data.Data) : null;
27034
+ const rows = pagedRows ? pagedRows : Array.isArray(data.Data) ? data.Data : null;
27035
+ if (hasData && !(rows !== null && rows.length === 0)) {
26961
27036
  const logValue = data.Log;
26962
- if (Array.isArray(data.Data)) {
26963
- printResizableTable(data.Data, logFn, logValue);
27037
+ if (rows !== null) {
27038
+ printResizableTable(rows, logFn, logValue);
26964
27039
  } else {
26965
27040
  printVerticalTable(data.Data, logFn, logValue);
26966
27041
  }
@@ -27148,6 +27223,44 @@ function defaultErrorCodeForResult(result) {
27148
27223
  return "unknown_error";
27149
27224
  }
27150
27225
  }
27226
+ function parseHttpStatusFromMessage2(message) {
27227
+ const match = /^HTTP\s+(\d{3})(?::|\s|-|$)/i.exec(message.trim());
27228
+ if (!match)
27229
+ return;
27230
+ const status = Number(match[1]);
27231
+ return Number.isInteger(status) && status >= 100 && status <= 599 ? status : undefined;
27232
+ }
27233
+ function defaultErrorCodeForHttpStatus(status) {
27234
+ if (status === undefined)
27235
+ return;
27236
+ if (status === 400 || status === 409 || status === 422) {
27237
+ return "invalid_argument";
27238
+ }
27239
+ if (status === 401)
27240
+ return "authentication_required";
27241
+ if (status === 403)
27242
+ return "permission_denied";
27243
+ if (status === 404)
27244
+ return "not_found";
27245
+ if (status === 405)
27246
+ return "method_not_allowed";
27247
+ if (status === 408)
27248
+ return "timeout";
27249
+ if (status === 429)
27250
+ return "rate_limited";
27251
+ if (status >= 500 && status < 600)
27252
+ return "server_error";
27253
+ return;
27254
+ }
27255
+ function defaultErrorCodeForFailure(data) {
27256
+ if (data.Result === RESULTS.Failure) {
27257
+ const status = data.Context?.httpStatus ?? parseHttpStatusFromMessage2(data.Message);
27258
+ const errorCode = defaultErrorCodeForHttpStatus(status);
27259
+ if (errorCode)
27260
+ return errorCode;
27261
+ }
27262
+ return defaultErrorCodeForResult(data.Result);
27263
+ }
27151
27264
  function defaultRetryForErrorCode(errorCode) {
27152
27265
  switch (errorCode) {
27153
27266
  case "network_error":
@@ -27177,16 +27290,19 @@ var OutputFormatter;
27177
27290
  OutputFormatter.success = success;
27178
27291
  function error(data) {
27179
27292
  data.Log ??= getLogFilePath() || undefined;
27180
- data.ErrorCode ??= defaultErrorCodeForResult(data.Result);
27293
+ data.ErrorCode ??= defaultErrorCodeForFailure(data);
27181
27294
  data.Retry ??= defaultRetryForErrorCode(data.ErrorCode);
27182
27295
  process.exitCode = EXIT_CODES[data.Result] ?? 1;
27183
- telemetry.trackEvent(CommonTelemetryEvents.Error, {
27184
- result: data.Result,
27185
- errorCode: data.ErrorCode,
27186
- retry: data.Retry,
27187
- message: data.Message
27188
- });
27189
- logOutput(normalizeOutputKeys(data), getOutputFormat());
27296
+ const { SuppressTelemetry, ...envelope } = data;
27297
+ if (!SuppressTelemetry) {
27298
+ telemetry.trackEvent(CommonTelemetryEvents.Error, {
27299
+ result: data.Result,
27300
+ errorCode: data.ErrorCode,
27301
+ retry: data.Retry,
27302
+ message: data.Message
27303
+ });
27304
+ }
27305
+ logOutput(normalizeOutputKeys(envelope), getOutputFormat());
27190
27306
  }
27191
27307
  OutputFormatter.error = error;
27192
27308
  function emitList(code, items, opts) {
@@ -27496,1409 +27612,6 @@ function isGuid(value) {
27496
27612
  }
27497
27613
  // ../common/src/interactivity-context.ts
27498
27614
  var modeSlot = singleton("InteractivityMode");
27499
- // ../../node_modules/jsonpath-plus/dist/index-node-esm.js
27500
- import vm from "vm";
27501
-
27502
- class Hooks {
27503
- add(name, callback, first) {
27504
- if (typeof arguments[0] != "string") {
27505
- for (let name2 in arguments[0]) {
27506
- this.add(name2, arguments[0][name2], arguments[1]);
27507
- }
27508
- } else {
27509
- (Array.isArray(name) ? name : [name]).forEach(function(name2) {
27510
- this[name2] = this[name2] || [];
27511
- if (callback) {
27512
- this[name2][first ? "unshift" : "push"](callback);
27513
- }
27514
- }, this);
27515
- }
27516
- }
27517
- run(name, env) {
27518
- this[name] = this[name] || [];
27519
- this[name].forEach(function(callback) {
27520
- callback.call(env && env.context ? env.context : env, env);
27521
- });
27522
- }
27523
- }
27524
-
27525
- class Plugins {
27526
- constructor(jsep) {
27527
- this.jsep = jsep;
27528
- this.registered = {};
27529
- }
27530
- register(...plugins) {
27531
- plugins.forEach((plugin) => {
27532
- if (typeof plugin !== "object" || !plugin.name || !plugin.init) {
27533
- throw new Error("Invalid JSEP plugin format");
27534
- }
27535
- if (this.registered[plugin.name]) {
27536
- return;
27537
- }
27538
- plugin.init(this.jsep);
27539
- this.registered[plugin.name] = plugin;
27540
- });
27541
- }
27542
- }
27543
-
27544
- class Jsep {
27545
- static get version() {
27546
- return "1.4.0";
27547
- }
27548
- static toString() {
27549
- return "JavaScript Expression Parser (JSEP) v" + Jsep.version;
27550
- }
27551
- static addUnaryOp(op_name) {
27552
- Jsep.max_unop_len = Math.max(op_name.length, Jsep.max_unop_len);
27553
- Jsep.unary_ops[op_name] = 1;
27554
- return Jsep;
27555
- }
27556
- static addBinaryOp(op_name, precedence, isRightAssociative) {
27557
- Jsep.max_binop_len = Math.max(op_name.length, Jsep.max_binop_len);
27558
- Jsep.binary_ops[op_name] = precedence;
27559
- if (isRightAssociative) {
27560
- Jsep.right_associative.add(op_name);
27561
- } else {
27562
- Jsep.right_associative.delete(op_name);
27563
- }
27564
- return Jsep;
27565
- }
27566
- static addIdentifierChar(char) {
27567
- Jsep.additional_identifier_chars.add(char);
27568
- return Jsep;
27569
- }
27570
- static addLiteral(literal_name, literal_value) {
27571
- Jsep.literals[literal_name] = literal_value;
27572
- return Jsep;
27573
- }
27574
- static removeUnaryOp(op_name) {
27575
- delete Jsep.unary_ops[op_name];
27576
- if (op_name.length === Jsep.max_unop_len) {
27577
- Jsep.max_unop_len = Jsep.getMaxKeyLen(Jsep.unary_ops);
27578
- }
27579
- return Jsep;
27580
- }
27581
- static removeAllUnaryOps() {
27582
- Jsep.unary_ops = {};
27583
- Jsep.max_unop_len = 0;
27584
- return Jsep;
27585
- }
27586
- static removeIdentifierChar(char) {
27587
- Jsep.additional_identifier_chars.delete(char);
27588
- return Jsep;
27589
- }
27590
- static removeBinaryOp(op_name) {
27591
- delete Jsep.binary_ops[op_name];
27592
- if (op_name.length === Jsep.max_binop_len) {
27593
- Jsep.max_binop_len = Jsep.getMaxKeyLen(Jsep.binary_ops);
27594
- }
27595
- Jsep.right_associative.delete(op_name);
27596
- return Jsep;
27597
- }
27598
- static removeAllBinaryOps() {
27599
- Jsep.binary_ops = {};
27600
- Jsep.max_binop_len = 0;
27601
- return Jsep;
27602
- }
27603
- static removeLiteral(literal_name) {
27604
- delete Jsep.literals[literal_name];
27605
- return Jsep;
27606
- }
27607
- static removeAllLiterals() {
27608
- Jsep.literals = {};
27609
- return Jsep;
27610
- }
27611
- get char() {
27612
- return this.expr.charAt(this.index);
27613
- }
27614
- get code() {
27615
- return this.expr.charCodeAt(this.index);
27616
- }
27617
- constructor(expr) {
27618
- this.expr = expr;
27619
- this.index = 0;
27620
- }
27621
- static parse(expr) {
27622
- return new Jsep(expr).parse();
27623
- }
27624
- static getMaxKeyLen(obj) {
27625
- return Math.max(0, ...Object.keys(obj).map((k) => k.length));
27626
- }
27627
- static isDecimalDigit(ch) {
27628
- return ch >= 48 && ch <= 57;
27629
- }
27630
- static binaryPrecedence(op_val) {
27631
- return Jsep.binary_ops[op_val] || 0;
27632
- }
27633
- static isIdentifierStart(ch) {
27634
- 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));
27635
- }
27636
- static isIdentifierPart(ch) {
27637
- return Jsep.isIdentifierStart(ch) || Jsep.isDecimalDigit(ch);
27638
- }
27639
- throwError(message) {
27640
- const error = new Error(message + " at character " + this.index);
27641
- error.index = this.index;
27642
- error.description = message;
27643
- throw error;
27644
- }
27645
- runHook(name, node) {
27646
- if (Jsep.hooks[name]) {
27647
- const env = {
27648
- context: this,
27649
- node
27650
- };
27651
- Jsep.hooks.run(name, env);
27652
- return env.node;
27653
- }
27654
- return node;
27655
- }
27656
- searchHook(name) {
27657
- if (Jsep.hooks[name]) {
27658
- const env = {
27659
- context: this
27660
- };
27661
- Jsep.hooks[name].find(function(callback) {
27662
- callback.call(env.context, env);
27663
- return env.node;
27664
- });
27665
- return env.node;
27666
- }
27667
- }
27668
- gobbleSpaces() {
27669
- let ch = this.code;
27670
- while (ch === Jsep.SPACE_CODE || ch === Jsep.TAB_CODE || ch === Jsep.LF_CODE || ch === Jsep.CR_CODE) {
27671
- ch = this.expr.charCodeAt(++this.index);
27672
- }
27673
- this.runHook("gobble-spaces");
27674
- }
27675
- parse() {
27676
- this.runHook("before-all");
27677
- const nodes = this.gobbleExpressions();
27678
- const node = nodes.length === 1 ? nodes[0] : {
27679
- type: Jsep.COMPOUND,
27680
- body: nodes
27681
- };
27682
- return this.runHook("after-all", node);
27683
- }
27684
- gobbleExpressions(untilICode) {
27685
- let nodes = [], ch_i, node;
27686
- while (this.index < this.expr.length) {
27687
- ch_i = this.code;
27688
- if (ch_i === Jsep.SEMCOL_CODE || ch_i === Jsep.COMMA_CODE) {
27689
- this.index++;
27690
- } else {
27691
- if (node = this.gobbleExpression()) {
27692
- nodes.push(node);
27693
- } else if (this.index < this.expr.length) {
27694
- if (ch_i === untilICode) {
27695
- break;
27696
- }
27697
- this.throwError('Unexpected "' + this.char + '"');
27698
- }
27699
- }
27700
- }
27701
- return nodes;
27702
- }
27703
- gobbleExpression() {
27704
- const node = this.searchHook("gobble-expression") || this.gobbleBinaryExpression();
27705
- this.gobbleSpaces();
27706
- return this.runHook("after-expression", node);
27707
- }
27708
- gobbleBinaryOp() {
27709
- this.gobbleSpaces();
27710
- let to_check = this.expr.substr(this.index, Jsep.max_binop_len);
27711
- let tc_len = to_check.length;
27712
- while (tc_len > 0) {
27713
- 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)))) {
27714
- this.index += tc_len;
27715
- return to_check;
27716
- }
27717
- to_check = to_check.substr(0, --tc_len);
27718
- }
27719
- return false;
27720
- }
27721
- gobbleBinaryExpression() {
27722
- let node, biop, prec, stack, biop_info, left, right, i, cur_biop;
27723
- left = this.gobbleToken();
27724
- if (!left) {
27725
- return left;
27726
- }
27727
- biop = this.gobbleBinaryOp();
27728
- if (!biop) {
27729
- return left;
27730
- }
27731
- biop_info = {
27732
- value: biop,
27733
- prec: Jsep.binaryPrecedence(biop),
27734
- right_a: Jsep.right_associative.has(biop)
27735
- };
27736
- right = this.gobbleToken();
27737
- if (!right) {
27738
- this.throwError("Expected expression after " + biop);
27739
- }
27740
- stack = [left, biop_info, right];
27741
- while (biop = this.gobbleBinaryOp()) {
27742
- prec = Jsep.binaryPrecedence(biop);
27743
- if (prec === 0) {
27744
- this.index -= biop.length;
27745
- break;
27746
- }
27747
- biop_info = {
27748
- value: biop,
27749
- prec,
27750
- right_a: Jsep.right_associative.has(biop)
27751
- };
27752
- cur_biop = biop;
27753
- const comparePrev = (prev) => biop_info.right_a && prev.right_a ? prec > prev.prec : prec <= prev.prec;
27754
- while (stack.length > 2 && comparePrev(stack[stack.length - 2])) {
27755
- right = stack.pop();
27756
- biop = stack.pop().value;
27757
- left = stack.pop();
27758
- node = {
27759
- type: Jsep.BINARY_EXP,
27760
- operator: biop,
27761
- left,
27762
- right
27763
- };
27764
- stack.push(node);
27765
- }
27766
- node = this.gobbleToken();
27767
- if (!node) {
27768
- this.throwError("Expected expression after " + cur_biop);
27769
- }
27770
- stack.push(biop_info, node);
27771
- }
27772
- i = stack.length - 1;
27773
- node = stack[i];
27774
- while (i > 1) {
27775
- node = {
27776
- type: Jsep.BINARY_EXP,
27777
- operator: stack[i - 1].value,
27778
- left: stack[i - 2],
27779
- right: node
27780
- };
27781
- i -= 2;
27782
- }
27783
- return node;
27784
- }
27785
- gobbleToken() {
27786
- let ch, to_check, tc_len, node;
27787
- this.gobbleSpaces();
27788
- node = this.searchHook("gobble-token");
27789
- if (node) {
27790
- return this.runHook("after-token", node);
27791
- }
27792
- ch = this.code;
27793
- if (Jsep.isDecimalDigit(ch) || ch === Jsep.PERIOD_CODE) {
27794
- return this.gobbleNumericLiteral();
27795
- }
27796
- if (ch === Jsep.SQUOTE_CODE || ch === Jsep.DQUOTE_CODE) {
27797
- node = this.gobbleStringLiteral();
27798
- } else if (ch === Jsep.OBRACK_CODE) {
27799
- node = this.gobbleArray();
27800
- } else {
27801
- to_check = this.expr.substr(this.index, Jsep.max_unop_len);
27802
- tc_len = to_check.length;
27803
- while (tc_len > 0) {
27804
- 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)))) {
27805
- this.index += tc_len;
27806
- const argument = this.gobbleToken();
27807
- if (!argument) {
27808
- this.throwError("missing unaryOp argument");
27809
- }
27810
- return this.runHook("after-token", {
27811
- type: Jsep.UNARY_EXP,
27812
- operator: to_check,
27813
- argument,
27814
- prefix: true
27815
- });
27816
- }
27817
- to_check = to_check.substr(0, --tc_len);
27818
- }
27819
- if (Jsep.isIdentifierStart(ch)) {
27820
- node = this.gobbleIdentifier();
27821
- if (Jsep.literals.hasOwnProperty(node.name)) {
27822
- node = {
27823
- type: Jsep.LITERAL,
27824
- value: Jsep.literals[node.name],
27825
- raw: node.name
27826
- };
27827
- } else if (node.name === Jsep.this_str) {
27828
- node = {
27829
- type: Jsep.THIS_EXP
27830
- };
27831
- }
27832
- } else if (ch === Jsep.OPAREN_CODE) {
27833
- node = this.gobbleGroup();
27834
- }
27835
- }
27836
- if (!node) {
27837
- return this.runHook("after-token", false);
27838
- }
27839
- node = this.gobbleTokenProperty(node);
27840
- return this.runHook("after-token", node);
27841
- }
27842
- gobbleTokenProperty(node) {
27843
- this.gobbleSpaces();
27844
- let ch = this.code;
27845
- while (ch === Jsep.PERIOD_CODE || ch === Jsep.OBRACK_CODE || ch === Jsep.OPAREN_CODE || ch === Jsep.QUMARK_CODE) {
27846
- let optional;
27847
- if (ch === Jsep.QUMARK_CODE) {
27848
- if (this.expr.charCodeAt(this.index + 1) !== Jsep.PERIOD_CODE) {
27849
- break;
27850
- }
27851
- optional = true;
27852
- this.index += 2;
27853
- this.gobbleSpaces();
27854
- ch = this.code;
27855
- }
27856
- this.index++;
27857
- if (ch === Jsep.OBRACK_CODE) {
27858
- node = {
27859
- type: Jsep.MEMBER_EXP,
27860
- computed: true,
27861
- object: node,
27862
- property: this.gobbleExpression()
27863
- };
27864
- if (!node.property) {
27865
- this.throwError('Unexpected "' + this.char + '"');
27866
- }
27867
- this.gobbleSpaces();
27868
- ch = this.code;
27869
- if (ch !== Jsep.CBRACK_CODE) {
27870
- this.throwError("Unclosed [");
27871
- }
27872
- this.index++;
27873
- } else if (ch === Jsep.OPAREN_CODE) {
27874
- node = {
27875
- type: Jsep.CALL_EXP,
27876
- arguments: this.gobbleArguments(Jsep.CPAREN_CODE),
27877
- callee: node
27878
- };
27879
- } else if (ch === Jsep.PERIOD_CODE || optional) {
27880
- if (optional) {
27881
- this.index--;
27882
- }
27883
- this.gobbleSpaces();
27884
- node = {
27885
- type: Jsep.MEMBER_EXP,
27886
- computed: false,
27887
- object: node,
27888
- property: this.gobbleIdentifier()
27889
- };
27890
- }
27891
- if (optional) {
27892
- node.optional = true;
27893
- }
27894
- this.gobbleSpaces();
27895
- ch = this.code;
27896
- }
27897
- return node;
27898
- }
27899
- gobbleNumericLiteral() {
27900
- let number = "", ch, chCode;
27901
- while (Jsep.isDecimalDigit(this.code)) {
27902
- number += this.expr.charAt(this.index++);
27903
- }
27904
- if (this.code === Jsep.PERIOD_CODE) {
27905
- number += this.expr.charAt(this.index++);
27906
- while (Jsep.isDecimalDigit(this.code)) {
27907
- number += this.expr.charAt(this.index++);
27908
- }
27909
- }
27910
- ch = this.char;
27911
- if (ch === "e" || ch === "E") {
27912
- number += this.expr.charAt(this.index++);
27913
- ch = this.char;
27914
- if (ch === "+" || ch === "-") {
27915
- number += this.expr.charAt(this.index++);
27916
- }
27917
- while (Jsep.isDecimalDigit(this.code)) {
27918
- number += this.expr.charAt(this.index++);
27919
- }
27920
- if (!Jsep.isDecimalDigit(this.expr.charCodeAt(this.index - 1))) {
27921
- this.throwError("Expected exponent (" + number + this.char + ")");
27922
- }
27923
- }
27924
- chCode = this.code;
27925
- if (Jsep.isIdentifierStart(chCode)) {
27926
- this.throwError("Variable names cannot start with a number (" + number + this.char + ")");
27927
- } else if (chCode === Jsep.PERIOD_CODE || number.length === 1 && number.charCodeAt(0) === Jsep.PERIOD_CODE) {
27928
- this.throwError("Unexpected period");
27929
- }
27930
- return {
27931
- type: Jsep.LITERAL,
27932
- value: parseFloat(number),
27933
- raw: number
27934
- };
27935
- }
27936
- gobbleStringLiteral() {
27937
- let str = "";
27938
- const startIndex = this.index;
27939
- const quote = this.expr.charAt(this.index++);
27940
- let closed = false;
27941
- while (this.index < this.expr.length) {
27942
- let ch = this.expr.charAt(this.index++);
27943
- if (ch === quote) {
27944
- closed = true;
27945
- break;
27946
- } else if (ch === "\\") {
27947
- ch = this.expr.charAt(this.index++);
27948
- switch (ch) {
27949
- case "n":
27950
- str += `
27951
- `;
27952
- break;
27953
- case "r":
27954
- str += "\r";
27955
- break;
27956
- case "t":
27957
- str += "\t";
27958
- break;
27959
- case "b":
27960
- str += "\b";
27961
- break;
27962
- case "f":
27963
- str += "\f";
27964
- break;
27965
- case "v":
27966
- str += "\v";
27967
- break;
27968
- default:
27969
- str += ch;
27970
- }
27971
- } else {
27972
- str += ch;
27973
- }
27974
- }
27975
- if (!closed) {
27976
- this.throwError('Unclosed quote after "' + str + '"');
27977
- }
27978
- return {
27979
- type: Jsep.LITERAL,
27980
- value: str,
27981
- raw: this.expr.substring(startIndex, this.index)
27982
- };
27983
- }
27984
- gobbleIdentifier() {
27985
- let ch = this.code, start = this.index;
27986
- if (Jsep.isIdentifierStart(ch)) {
27987
- this.index++;
27988
- } else {
27989
- this.throwError("Unexpected " + this.char);
27990
- }
27991
- while (this.index < this.expr.length) {
27992
- ch = this.code;
27993
- if (Jsep.isIdentifierPart(ch)) {
27994
- this.index++;
27995
- } else {
27996
- break;
27997
- }
27998
- }
27999
- return {
28000
- type: Jsep.IDENTIFIER,
28001
- name: this.expr.slice(start, this.index)
28002
- };
28003
- }
28004
- gobbleArguments(termination) {
28005
- const args = [];
28006
- let closed = false;
28007
- let separator_count = 0;
28008
- while (this.index < this.expr.length) {
28009
- this.gobbleSpaces();
28010
- let ch_i = this.code;
28011
- if (ch_i === termination) {
28012
- closed = true;
28013
- this.index++;
28014
- if (termination === Jsep.CPAREN_CODE && separator_count && separator_count >= args.length) {
28015
- this.throwError("Unexpected token " + String.fromCharCode(termination));
28016
- }
28017
- break;
28018
- } else if (ch_i === Jsep.COMMA_CODE) {
28019
- this.index++;
28020
- separator_count++;
28021
- if (separator_count !== args.length) {
28022
- if (termination === Jsep.CPAREN_CODE) {
28023
- this.throwError("Unexpected token ,");
28024
- } else if (termination === Jsep.CBRACK_CODE) {
28025
- for (let arg = args.length;arg < separator_count; arg++) {
28026
- args.push(null);
28027
- }
28028
- }
28029
- }
28030
- } else if (args.length !== separator_count && separator_count !== 0) {
28031
- this.throwError("Expected comma");
28032
- } else {
28033
- const node = this.gobbleExpression();
28034
- if (!node || node.type === Jsep.COMPOUND) {
28035
- this.throwError("Expected comma");
28036
- }
28037
- args.push(node);
28038
- }
28039
- }
28040
- if (!closed) {
28041
- this.throwError("Expected " + String.fromCharCode(termination));
28042
- }
28043
- return args;
28044
- }
28045
- gobbleGroup() {
28046
- this.index++;
28047
- let nodes = this.gobbleExpressions(Jsep.CPAREN_CODE);
28048
- if (this.code === Jsep.CPAREN_CODE) {
28049
- this.index++;
28050
- if (nodes.length === 1) {
28051
- return nodes[0];
28052
- } else if (!nodes.length) {
28053
- return false;
28054
- } else {
28055
- return {
28056
- type: Jsep.SEQUENCE_EXP,
28057
- expressions: nodes
28058
- };
28059
- }
28060
- } else {
28061
- this.throwError("Unclosed (");
28062
- }
28063
- }
28064
- gobbleArray() {
28065
- this.index++;
28066
- return {
28067
- type: Jsep.ARRAY_EXP,
28068
- elements: this.gobbleArguments(Jsep.CBRACK_CODE)
28069
- };
28070
- }
28071
- }
28072
- var hooks = new Hooks;
28073
- Object.assign(Jsep, {
28074
- hooks,
28075
- plugins: new Plugins(Jsep),
28076
- COMPOUND: "Compound",
28077
- SEQUENCE_EXP: "SequenceExpression",
28078
- IDENTIFIER: "Identifier",
28079
- MEMBER_EXP: "MemberExpression",
28080
- LITERAL: "Literal",
28081
- THIS_EXP: "ThisExpression",
28082
- CALL_EXP: "CallExpression",
28083
- UNARY_EXP: "UnaryExpression",
28084
- BINARY_EXP: "BinaryExpression",
28085
- ARRAY_EXP: "ArrayExpression",
28086
- TAB_CODE: 9,
28087
- LF_CODE: 10,
28088
- CR_CODE: 13,
28089
- SPACE_CODE: 32,
28090
- PERIOD_CODE: 46,
28091
- COMMA_CODE: 44,
28092
- SQUOTE_CODE: 39,
28093
- DQUOTE_CODE: 34,
28094
- OPAREN_CODE: 40,
28095
- CPAREN_CODE: 41,
28096
- OBRACK_CODE: 91,
28097
- CBRACK_CODE: 93,
28098
- QUMARK_CODE: 63,
28099
- SEMCOL_CODE: 59,
28100
- COLON_CODE: 58,
28101
- unary_ops: {
28102
- "-": 1,
28103
- "!": 1,
28104
- "~": 1,
28105
- "+": 1
28106
- },
28107
- binary_ops: {
28108
- "||": 1,
28109
- "??": 1,
28110
- "&&": 2,
28111
- "|": 3,
28112
- "^": 4,
28113
- "&": 5,
28114
- "==": 6,
28115
- "!=": 6,
28116
- "===": 6,
28117
- "!==": 6,
28118
- "<": 7,
28119
- ">": 7,
28120
- "<=": 7,
28121
- ">=": 7,
28122
- "<<": 8,
28123
- ">>": 8,
28124
- ">>>": 8,
28125
- "+": 9,
28126
- "-": 9,
28127
- "*": 10,
28128
- "/": 10,
28129
- "%": 10,
28130
- "**": 11
28131
- },
28132
- right_associative: new Set(["**"]),
28133
- additional_identifier_chars: new Set(["$", "_"]),
28134
- literals: {
28135
- true: true,
28136
- false: false,
28137
- null: null
28138
- },
28139
- this_str: "this"
28140
- });
28141
- Jsep.max_unop_len = Jsep.getMaxKeyLen(Jsep.unary_ops);
28142
- Jsep.max_binop_len = Jsep.getMaxKeyLen(Jsep.binary_ops);
28143
- var jsep = (expr) => new Jsep(expr).parse();
28144
- var stdClassProps = Object.getOwnPropertyNames(class Test {
28145
- });
28146
- Object.getOwnPropertyNames(Jsep).filter((prop) => !stdClassProps.includes(prop) && jsep[prop] === undefined).forEach((m) => {
28147
- jsep[m] = Jsep[m];
28148
- });
28149
- jsep.Jsep = Jsep;
28150
- var CONDITIONAL_EXP = "ConditionalExpression";
28151
- var ternary = {
28152
- name: "ternary",
28153
- init(jsep2) {
28154
- jsep2.hooks.add("after-expression", function gobbleTernary(env) {
28155
- if (env.node && this.code === jsep2.QUMARK_CODE) {
28156
- this.index++;
28157
- const test = env.node;
28158
- const consequent = this.gobbleExpression();
28159
- if (!consequent) {
28160
- this.throwError("Expected expression");
28161
- }
28162
- this.gobbleSpaces();
28163
- if (this.code === jsep2.COLON_CODE) {
28164
- this.index++;
28165
- const alternate = this.gobbleExpression();
28166
- if (!alternate) {
28167
- this.throwError("Expected expression");
28168
- }
28169
- env.node = {
28170
- type: CONDITIONAL_EXP,
28171
- test,
28172
- consequent,
28173
- alternate
28174
- };
28175
- if (test.operator && jsep2.binary_ops[test.operator] <= 0.9) {
28176
- let newTest = test;
28177
- while (newTest.right.operator && jsep2.binary_ops[newTest.right.operator] <= 0.9) {
28178
- newTest = newTest.right;
28179
- }
28180
- env.node.test = newTest.right;
28181
- newTest.right = env.node;
28182
- env.node = test;
28183
- }
28184
- } else {
28185
- this.throwError("Expected :");
28186
- }
28187
- }
28188
- });
28189
- }
28190
- };
28191
- jsep.plugins.register(ternary);
28192
- var FSLASH_CODE = 47;
28193
- var BSLASH_CODE = 92;
28194
- var index = {
28195
- name: "regex",
28196
- init(jsep2) {
28197
- jsep2.hooks.add("gobble-token", function gobbleRegexLiteral(env) {
28198
- if (this.code === FSLASH_CODE) {
28199
- const patternIndex = ++this.index;
28200
- let inCharSet = false;
28201
- while (this.index < this.expr.length) {
28202
- if (this.code === FSLASH_CODE && !inCharSet) {
28203
- const pattern = this.expr.slice(patternIndex, this.index);
28204
- let flags = "";
28205
- while (++this.index < this.expr.length) {
28206
- const code = this.code;
28207
- if (code >= 97 && code <= 122 || code >= 65 && code <= 90 || code >= 48 && code <= 57) {
28208
- flags += this.char;
28209
- } else {
28210
- break;
28211
- }
28212
- }
28213
- let value;
28214
- try {
28215
- value = new RegExp(pattern, flags);
28216
- } catch (e) {
28217
- this.throwError(e.message);
28218
- }
28219
- env.node = {
28220
- type: jsep2.LITERAL,
28221
- value,
28222
- raw: this.expr.slice(patternIndex - 1, this.index)
28223
- };
28224
- env.node = this.gobbleTokenProperty(env.node);
28225
- return env.node;
28226
- }
28227
- if (this.code === jsep2.OBRACK_CODE) {
28228
- inCharSet = true;
28229
- } else if (inCharSet && this.code === jsep2.CBRACK_CODE) {
28230
- inCharSet = false;
28231
- }
28232
- this.index += this.code === BSLASH_CODE ? 2 : 1;
28233
- }
28234
- this.throwError("Unclosed Regex");
28235
- }
28236
- });
28237
- }
28238
- };
28239
- var PLUS_CODE = 43;
28240
- var MINUS_CODE = 45;
28241
- var plugin = {
28242
- name: "assignment",
28243
- assignmentOperators: new Set(["=", "*=", "**=", "/=", "%=", "+=", "-=", "<<=", ">>=", ">>>=", "&=", "^=", "|=", "||=", "&&=", "??="]),
28244
- updateOperators: [PLUS_CODE, MINUS_CODE],
28245
- assignmentPrecedence: 0.9,
28246
- init(jsep2) {
28247
- const updateNodeTypes = [jsep2.IDENTIFIER, jsep2.MEMBER_EXP];
28248
- plugin.assignmentOperators.forEach((op) => jsep2.addBinaryOp(op, plugin.assignmentPrecedence, true));
28249
- jsep2.hooks.add("gobble-token", function gobbleUpdatePrefix(env) {
28250
- const code = this.code;
28251
- if (plugin.updateOperators.some((c) => c === code && c === this.expr.charCodeAt(this.index + 1))) {
28252
- this.index += 2;
28253
- env.node = {
28254
- type: "UpdateExpression",
28255
- operator: code === PLUS_CODE ? "++" : "--",
28256
- argument: this.gobbleTokenProperty(this.gobbleIdentifier()),
28257
- prefix: true
28258
- };
28259
- if (!env.node.argument || !updateNodeTypes.includes(env.node.argument.type)) {
28260
- this.throwError(`Unexpected ${env.node.operator}`);
28261
- }
28262
- }
28263
- });
28264
- jsep2.hooks.add("after-token", function gobbleUpdatePostfix(env) {
28265
- if (env.node) {
28266
- const code = this.code;
28267
- if (plugin.updateOperators.some((c) => c === code && c === this.expr.charCodeAt(this.index + 1))) {
28268
- if (!updateNodeTypes.includes(env.node.type)) {
28269
- this.throwError(`Unexpected ${env.node.operator}`);
28270
- }
28271
- this.index += 2;
28272
- env.node = {
28273
- type: "UpdateExpression",
28274
- operator: code === PLUS_CODE ? "++" : "--",
28275
- argument: env.node,
28276
- prefix: false
28277
- };
28278
- }
28279
- }
28280
- });
28281
- jsep2.hooks.add("after-expression", function gobbleAssignment(env) {
28282
- if (env.node) {
28283
- updateBinariesToAssignments(env.node);
28284
- }
28285
- });
28286
- function updateBinariesToAssignments(node) {
28287
- if (plugin.assignmentOperators.has(node.operator)) {
28288
- node.type = "AssignmentExpression";
28289
- updateBinariesToAssignments(node.left);
28290
- updateBinariesToAssignments(node.right);
28291
- } else if (!node.operator) {
28292
- Object.values(node).forEach((val) => {
28293
- if (val && typeof val === "object") {
28294
- updateBinariesToAssignments(val);
28295
- }
28296
- });
28297
- }
28298
- }
28299
- }
28300
- };
28301
- jsep.plugins.register(index, plugin);
28302
- jsep.addUnaryOp("typeof");
28303
- jsep.addUnaryOp("void");
28304
- jsep.addLiteral("null", null);
28305
- jsep.addLiteral("undefined", undefined);
28306
- var BLOCKED_PROTO_PROPERTIES = new Set(["constructor", "__proto__", "__defineGetter__", "__defineSetter__", "__lookupGetter__", "__lookupSetter__"]);
28307
- var SafeEval = {
28308
- evalAst(ast, subs) {
28309
- switch (ast.type) {
28310
- case "BinaryExpression":
28311
- case "LogicalExpression":
28312
- return SafeEval.evalBinaryExpression(ast, subs);
28313
- case "Compound":
28314
- return SafeEval.evalCompound(ast, subs);
28315
- case "ConditionalExpression":
28316
- return SafeEval.evalConditionalExpression(ast, subs);
28317
- case "Identifier":
28318
- return SafeEval.evalIdentifier(ast, subs);
28319
- case "Literal":
28320
- return SafeEval.evalLiteral(ast, subs);
28321
- case "MemberExpression":
28322
- return SafeEval.evalMemberExpression(ast, subs);
28323
- case "UnaryExpression":
28324
- return SafeEval.evalUnaryExpression(ast, subs);
28325
- case "ArrayExpression":
28326
- return SafeEval.evalArrayExpression(ast, subs);
28327
- case "CallExpression":
28328
- return SafeEval.evalCallExpression(ast, subs);
28329
- case "AssignmentExpression":
28330
- return SafeEval.evalAssignmentExpression(ast, subs);
28331
- default:
28332
- throw SyntaxError("Unexpected expression", ast);
28333
- }
28334
- },
28335
- evalBinaryExpression(ast, subs) {
28336
- const result = {
28337
- "||": (a, b) => a || b(),
28338
- "&&": (a, b) => a && b(),
28339
- "|": (a, b) => a | b(),
28340
- "^": (a, b) => a ^ b(),
28341
- "&": (a, b) => a & b(),
28342
- "==": (a, b) => a == b(),
28343
- "!=": (a, b) => a != b(),
28344
- "===": (a, b) => a === b(),
28345
- "!==": (a, b) => a !== b(),
28346
- "<": (a, b) => a < b(),
28347
- ">": (a, b) => a > b(),
28348
- "<=": (a, b) => a <= b(),
28349
- ">=": (a, b) => a >= b(),
28350
- "<<": (a, b) => a << b(),
28351
- ">>": (a, b) => a >> b(),
28352
- ">>>": (a, b) => a >>> b(),
28353
- "+": (a, b) => a + b(),
28354
- "-": (a, b) => a - b(),
28355
- "*": (a, b) => a * b(),
28356
- "/": (a, b) => a / b(),
28357
- "%": (a, b) => a % b()
28358
- }[ast.operator](SafeEval.evalAst(ast.left, subs), () => SafeEval.evalAst(ast.right, subs));
28359
- return result;
28360
- },
28361
- evalCompound(ast, subs) {
28362
- let last;
28363
- for (let i = 0;i < ast.body.length; i++) {
28364
- if (ast.body[i].type === "Identifier" && ["var", "let", "const"].includes(ast.body[i].name) && ast.body[i + 1] && ast.body[i + 1].type === "AssignmentExpression") {
28365
- i += 1;
28366
- }
28367
- const expr = ast.body[i];
28368
- last = SafeEval.evalAst(expr, subs);
28369
- }
28370
- return last;
28371
- },
28372
- evalConditionalExpression(ast, subs) {
28373
- if (SafeEval.evalAst(ast.test, subs)) {
28374
- return SafeEval.evalAst(ast.consequent, subs);
28375
- }
28376
- return SafeEval.evalAst(ast.alternate, subs);
28377
- },
28378
- evalIdentifier(ast, subs) {
28379
- if (Object.hasOwn(subs, ast.name)) {
28380
- return subs[ast.name];
28381
- }
28382
- throw ReferenceError(`${ast.name} is not defined`);
28383
- },
28384
- evalLiteral(ast) {
28385
- return ast.value;
28386
- },
28387
- evalMemberExpression(ast, subs) {
28388
- const prop = String(ast.computed ? SafeEval.evalAst(ast.property) : ast.property.name);
28389
- const obj = SafeEval.evalAst(ast.object, subs);
28390
- if (obj === undefined || obj === null) {
28391
- throw TypeError(`Cannot read properties of ${obj} (reading '${prop}')`);
28392
- }
28393
- if (!Object.hasOwn(obj, prop) && BLOCKED_PROTO_PROPERTIES.has(prop)) {
28394
- throw TypeError(`Cannot read properties of ${obj} (reading '${prop}')`);
28395
- }
28396
- const result = obj[prop];
28397
- if (typeof result === "function") {
28398
- return result.bind(obj);
28399
- }
28400
- return result;
28401
- },
28402
- evalUnaryExpression(ast, subs) {
28403
- const result = {
28404
- "-": (a) => -SafeEval.evalAst(a, subs),
28405
- "!": (a) => !SafeEval.evalAst(a, subs),
28406
- "~": (a) => ~SafeEval.evalAst(a, subs),
28407
- "+": (a) => +SafeEval.evalAst(a, subs),
28408
- typeof: (a) => typeof SafeEval.evalAst(a, subs),
28409
- void: (a) => void SafeEval.evalAst(a, subs)
28410
- }[ast.operator](ast.argument);
28411
- return result;
28412
- },
28413
- evalArrayExpression(ast, subs) {
28414
- return ast.elements.map((el) => SafeEval.evalAst(el, subs));
28415
- },
28416
- evalCallExpression(ast, subs) {
28417
- const args = ast.arguments.map((arg) => SafeEval.evalAst(arg, subs));
28418
- const func = SafeEval.evalAst(ast.callee, subs);
28419
- if (func === Function) {
28420
- throw new Error("Function constructor is disabled");
28421
- }
28422
- return func(...args);
28423
- },
28424
- evalAssignmentExpression(ast, subs) {
28425
- if (ast.left.type !== "Identifier") {
28426
- throw SyntaxError("Invalid left-hand side in assignment");
28427
- }
28428
- const id = ast.left.name;
28429
- const value = SafeEval.evalAst(ast.right, subs);
28430
- subs[id] = value;
28431
- return subs[id];
28432
- }
28433
- };
28434
-
28435
- class SafeScript {
28436
- constructor(expr) {
28437
- this.code = expr;
28438
- this.ast = jsep(this.code);
28439
- }
28440
- runInNewContext(context) {
28441
- const keyMap = Object.assign(Object.create(null), context);
28442
- return SafeEval.evalAst(this.ast, keyMap);
28443
- }
28444
- }
28445
- function push(arr, item) {
28446
- arr = arr.slice();
28447
- arr.push(item);
28448
- return arr;
28449
- }
28450
- function unshift(item, arr) {
28451
- arr = arr.slice();
28452
- arr.unshift(item);
28453
- return arr;
28454
- }
28455
-
28456
- class NewError extends Error {
28457
- constructor(value) {
28458
- super('JSONPath should not be called with "new" (it prevents return ' + "of (unwrapped) scalar values)");
28459
- this.avoidNew = true;
28460
- this.value = value;
28461
- this.name = "NewError";
28462
- }
28463
- }
28464
- function JSONPath(opts, expr, obj, callback, otherTypeCallback) {
28465
- if (!(this instanceof JSONPath)) {
28466
- try {
28467
- return new JSONPath(opts, expr, obj, callback, otherTypeCallback);
28468
- } catch (e) {
28469
- if (!e.avoidNew) {
28470
- throw e;
28471
- }
28472
- return e.value;
28473
- }
28474
- }
28475
- if (typeof opts === "string") {
28476
- otherTypeCallback = callback;
28477
- callback = obj;
28478
- obj = expr;
28479
- expr = opts;
28480
- opts = null;
28481
- }
28482
- const optObj = opts && typeof opts === "object";
28483
- opts = opts || {};
28484
- this.json = opts.json || obj;
28485
- this.path = opts.path || expr;
28486
- this.resultType = opts.resultType || "value";
28487
- this.flatten = opts.flatten || false;
28488
- this.wrap = Object.hasOwn(opts, "wrap") ? opts.wrap : true;
28489
- this.sandbox = opts.sandbox || {};
28490
- this.eval = opts.eval === undefined ? "safe" : opts.eval;
28491
- this.ignoreEvalErrors = typeof opts.ignoreEvalErrors === "undefined" ? false : opts.ignoreEvalErrors;
28492
- this.parent = opts.parent || null;
28493
- this.parentProperty = opts.parentProperty || null;
28494
- this.callback = opts.callback || callback || null;
28495
- this.otherTypeCallback = opts.otherTypeCallback || otherTypeCallback || function() {
28496
- throw new TypeError("You must supply an otherTypeCallback callback option " + "with the @other() operator.");
28497
- };
28498
- if (opts.autostart !== false) {
28499
- const args = {
28500
- path: optObj ? opts.path : expr
28501
- };
28502
- if (!optObj) {
28503
- args.json = obj;
28504
- } else if ("json" in opts) {
28505
- args.json = opts.json;
28506
- }
28507
- const ret = this.evaluate(args);
28508
- if (!ret || typeof ret !== "object") {
28509
- throw new NewError(ret);
28510
- }
28511
- return ret;
28512
- }
28513
- }
28514
- JSONPath.prototype.evaluate = function(expr, json, callback, otherTypeCallback) {
28515
- let currParent = this.parent, currParentProperty = this.parentProperty;
28516
- let {
28517
- flatten,
28518
- wrap
28519
- } = this;
28520
- this.currResultType = this.resultType;
28521
- this.currEval = this.eval;
28522
- this.currSandbox = this.sandbox;
28523
- callback = callback || this.callback;
28524
- this.currOtherTypeCallback = otherTypeCallback || this.otherTypeCallback;
28525
- json = json || this.json;
28526
- expr = expr || this.path;
28527
- if (expr && typeof expr === "object" && !Array.isArray(expr)) {
28528
- if (!expr.path && expr.path !== "") {
28529
- throw new TypeError('You must supply a "path" property when providing an object ' + "argument to JSONPath.evaluate().");
28530
- }
28531
- if (!Object.hasOwn(expr, "json")) {
28532
- throw new TypeError('You must supply a "json" property when providing an object ' + "argument to JSONPath.evaluate().");
28533
- }
28534
- ({
28535
- json
28536
- } = expr);
28537
- flatten = Object.hasOwn(expr, "flatten") ? expr.flatten : flatten;
28538
- this.currResultType = Object.hasOwn(expr, "resultType") ? expr.resultType : this.currResultType;
28539
- this.currSandbox = Object.hasOwn(expr, "sandbox") ? expr.sandbox : this.currSandbox;
28540
- wrap = Object.hasOwn(expr, "wrap") ? expr.wrap : wrap;
28541
- this.currEval = Object.hasOwn(expr, "eval") ? expr.eval : this.currEval;
28542
- callback = Object.hasOwn(expr, "callback") ? expr.callback : callback;
28543
- this.currOtherTypeCallback = Object.hasOwn(expr, "otherTypeCallback") ? expr.otherTypeCallback : this.currOtherTypeCallback;
28544
- currParent = Object.hasOwn(expr, "parent") ? expr.parent : currParent;
28545
- currParentProperty = Object.hasOwn(expr, "parentProperty") ? expr.parentProperty : currParentProperty;
28546
- expr = expr.path;
28547
- }
28548
- currParent = currParent || null;
28549
- currParentProperty = currParentProperty || null;
28550
- if (Array.isArray(expr)) {
28551
- expr = JSONPath.toPathString(expr);
28552
- }
28553
- if (!expr && expr !== "" || !json) {
28554
- return;
28555
- }
28556
- const exprList = JSONPath.toPathArray(expr);
28557
- if (exprList[0] === "$" && exprList.length > 1) {
28558
- exprList.shift();
28559
- }
28560
- this._hasParentSelector = null;
28561
- const result = this._trace(exprList, json, ["$"], currParent, currParentProperty, callback).filter(function(ea) {
28562
- return ea && !ea.isParentSelector;
28563
- });
28564
- if (!result.length) {
28565
- return wrap ? [] : undefined;
28566
- }
28567
- if (!wrap && result.length === 1 && !result[0].hasArrExpr) {
28568
- return this._getPreferredOutput(result[0]);
28569
- }
28570
- return result.reduce((rslt, ea) => {
28571
- const valOrPath = this._getPreferredOutput(ea);
28572
- if (flatten && Array.isArray(valOrPath)) {
28573
- rslt = rslt.concat(valOrPath);
28574
- } else {
28575
- rslt.push(valOrPath);
28576
- }
28577
- return rslt;
28578
- }, []);
28579
- };
28580
- JSONPath.prototype._getPreferredOutput = function(ea) {
28581
- const resultType = this.currResultType;
28582
- switch (resultType) {
28583
- case "all": {
28584
- const path3 = Array.isArray(ea.path) ? ea.path : JSONPath.toPathArray(ea.path);
28585
- ea.pointer = JSONPath.toPointer(path3);
28586
- ea.path = typeof ea.path === "string" ? ea.path : JSONPath.toPathString(ea.path);
28587
- return ea;
28588
- }
28589
- case "value":
28590
- case "parent":
28591
- case "parentProperty":
28592
- return ea[resultType];
28593
- case "path":
28594
- return JSONPath.toPathString(ea[resultType]);
28595
- case "pointer":
28596
- return JSONPath.toPointer(ea.path);
28597
- default:
28598
- throw new TypeError("Unknown result type");
28599
- }
28600
- };
28601
- JSONPath.prototype._handleCallback = function(fullRetObj, callback, type) {
28602
- if (callback) {
28603
- const preferredOutput = this._getPreferredOutput(fullRetObj);
28604
- fullRetObj.path = typeof fullRetObj.path === "string" ? fullRetObj.path : JSONPath.toPathString(fullRetObj.path);
28605
- callback(preferredOutput, type, fullRetObj);
28606
- }
28607
- };
28608
- JSONPath.prototype._trace = function(expr, val, path3, parent, parentPropName, callback, hasArrExpr, literalPriority) {
28609
- let retObj;
28610
- if (!expr.length) {
28611
- retObj = {
28612
- path: path3,
28613
- value: val,
28614
- parent,
28615
- parentProperty: parentPropName,
28616
- hasArrExpr
28617
- };
28618
- this._handleCallback(retObj, callback, "value");
28619
- return retObj;
28620
- }
28621
- const loc = expr[0], x = expr.slice(1);
28622
- const ret = [];
28623
- function addRet(elems) {
28624
- if (Array.isArray(elems)) {
28625
- elems.forEach((t) => {
28626
- ret.push(t);
28627
- });
28628
- } else {
28629
- ret.push(elems);
28630
- }
28631
- }
28632
- if ((typeof loc !== "string" || literalPriority) && val && Object.hasOwn(val, loc)) {
28633
- addRet(this._trace(x, val[loc], push(path3, loc), val, loc, callback, hasArrExpr));
28634
- } else if (loc === "*") {
28635
- this._walk(val, (m) => {
28636
- addRet(this._trace(x, val[m], push(path3, m), val, m, callback, true, true));
28637
- });
28638
- } else if (loc === "..") {
28639
- addRet(this._trace(x, val, path3, parent, parentPropName, callback, hasArrExpr));
28640
- this._walk(val, (m) => {
28641
- if (typeof val[m] === "object") {
28642
- addRet(this._trace(expr.slice(), val[m], push(path3, m), val, m, callback, true));
28643
- }
28644
- });
28645
- } else if (loc === "^") {
28646
- this._hasParentSelector = true;
28647
- return {
28648
- path: path3.slice(0, -1),
28649
- expr: x,
28650
- isParentSelector: true
28651
- };
28652
- } else if (loc === "~") {
28653
- retObj = {
28654
- path: push(path3, loc),
28655
- value: parentPropName,
28656
- parent,
28657
- parentProperty: null
28658
- };
28659
- this._handleCallback(retObj, callback, "property");
28660
- return retObj;
28661
- } else if (loc === "$") {
28662
- addRet(this._trace(x, val, path3, null, null, callback, hasArrExpr));
28663
- } else if (/^(-?\d*):(-?\d*):?(\d*)$/u.test(loc)) {
28664
- addRet(this._slice(loc, x, val, path3, parent, parentPropName, callback));
28665
- } else if (loc.indexOf("?(") === 0) {
28666
- if (this.currEval === false) {
28667
- throw new Error("Eval [?(expr)] prevented in JSONPath expression.");
28668
- }
28669
- const safeLoc = loc.replace(/^\?\((.*?)\)$/u, "$1");
28670
- const nested = /@.?([^?]*)[['](\??\(.*?\))(?!.\)\])[\]']/gu.exec(safeLoc);
28671
- if (nested) {
28672
- this._walk(val, (m) => {
28673
- const npath = [nested[2]];
28674
- const nvalue = nested[1] ? val[m][nested[1]] : val[m];
28675
- const filterResults = this._trace(npath, nvalue, path3, parent, parentPropName, callback, true);
28676
- if (filterResults.length > 0) {
28677
- addRet(this._trace(x, val[m], push(path3, m), val, m, callback, true));
28678
- }
28679
- });
28680
- } else {
28681
- this._walk(val, (m) => {
28682
- if (this._eval(safeLoc, val[m], m, path3, parent, parentPropName)) {
28683
- addRet(this._trace(x, val[m], push(path3, m), val, m, callback, true));
28684
- }
28685
- });
28686
- }
28687
- } else if (loc[0] === "(") {
28688
- if (this.currEval === false) {
28689
- throw new Error("Eval [(expr)] prevented in JSONPath expression.");
28690
- }
28691
- addRet(this._trace(unshift(this._eval(loc, val, path3.at(-1), path3.slice(0, -1), parent, parentPropName), x), val, path3, parent, parentPropName, callback, hasArrExpr));
28692
- } else if (loc[0] === "@") {
28693
- let addType = false;
28694
- const valueType = loc.slice(1, -2);
28695
- switch (valueType) {
28696
- case "scalar":
28697
- if (!val || !["object", "function"].includes(typeof val)) {
28698
- addType = true;
28699
- }
28700
- break;
28701
- case "boolean":
28702
- case "string":
28703
- case "undefined":
28704
- case "function":
28705
- if (typeof val === valueType) {
28706
- addType = true;
28707
- }
28708
- break;
28709
- case "integer":
28710
- if (Number.isFinite(val) && !(val % 1)) {
28711
- addType = true;
28712
- }
28713
- break;
28714
- case "number":
28715
- if (Number.isFinite(val)) {
28716
- addType = true;
28717
- }
28718
- break;
28719
- case "nonFinite":
28720
- if (typeof val === "number" && !Number.isFinite(val)) {
28721
- addType = true;
28722
- }
28723
- break;
28724
- case "object":
28725
- if (val && typeof val === valueType) {
28726
- addType = true;
28727
- }
28728
- break;
28729
- case "array":
28730
- if (Array.isArray(val)) {
28731
- addType = true;
28732
- }
28733
- break;
28734
- case "other":
28735
- addType = this.currOtherTypeCallback(val, path3, parent, parentPropName);
28736
- break;
28737
- case "null":
28738
- if (val === null) {
28739
- addType = true;
28740
- }
28741
- break;
28742
- default:
28743
- throw new TypeError("Unknown value type " + valueType);
28744
- }
28745
- if (addType) {
28746
- retObj = {
28747
- path: path3,
28748
- value: val,
28749
- parent,
28750
- parentProperty: parentPropName
28751
- };
28752
- this._handleCallback(retObj, callback, "value");
28753
- return retObj;
28754
- }
28755
- } else if (loc[0] === "`" && val && Object.hasOwn(val, loc.slice(1))) {
28756
- const locProp = loc.slice(1);
28757
- addRet(this._trace(x, val[locProp], push(path3, locProp), val, locProp, callback, hasArrExpr, true));
28758
- } else if (loc.includes(",")) {
28759
- const parts = loc.split(",");
28760
- for (const part of parts) {
28761
- addRet(this._trace(unshift(part, x), val, path3, parent, parentPropName, callback, true));
28762
- }
28763
- } else if (!literalPriority && val && Object.hasOwn(val, loc)) {
28764
- addRet(this._trace(x, val[loc], push(path3, loc), val, loc, callback, hasArrExpr, true));
28765
- }
28766
- if (this._hasParentSelector) {
28767
- for (let t = 0;t < ret.length; t++) {
28768
- const rett = ret[t];
28769
- if (rett && rett.isParentSelector) {
28770
- const tmp = this._trace(rett.expr, val, rett.path, parent, parentPropName, callback, hasArrExpr);
28771
- if (Array.isArray(tmp)) {
28772
- ret[t] = tmp[0];
28773
- const tl = tmp.length;
28774
- for (let tt = 1;tt < tl; tt++) {
28775
- t++;
28776
- ret.splice(t, 0, tmp[tt]);
28777
- }
28778
- } else {
28779
- ret[t] = tmp;
28780
- }
28781
- }
28782
- }
28783
- }
28784
- return ret;
28785
- };
28786
- JSONPath.prototype._walk = function(val, f) {
28787
- if (Array.isArray(val)) {
28788
- const n = val.length;
28789
- for (let i = 0;i < n; i++) {
28790
- f(i);
28791
- }
28792
- } else if (val && typeof val === "object") {
28793
- Object.keys(val).forEach((m) => {
28794
- f(m);
28795
- });
28796
- }
28797
- };
28798
- JSONPath.prototype._slice = function(loc, expr, val, path3, parent, parentPropName, callback) {
28799
- if (!Array.isArray(val)) {
28800
- return;
28801
- }
28802
- const len = val.length, parts = loc.split(":"), step = parts[2] && Number.parseInt(parts[2]) || 1;
28803
- let start = parts[0] && Number.parseInt(parts[0]) || 0, end = parts[1] && Number.parseInt(parts[1]) || len;
28804
- start = start < 0 ? Math.max(0, start + len) : Math.min(len, start);
28805
- end = end < 0 ? Math.max(0, end + len) : Math.min(len, end);
28806
- const ret = [];
28807
- for (let i = start;i < end; i += step) {
28808
- const tmp = this._trace(unshift(i, expr), val, path3, parent, parentPropName, callback, true);
28809
- tmp.forEach((t) => {
28810
- ret.push(t);
28811
- });
28812
- }
28813
- return ret;
28814
- };
28815
- JSONPath.prototype._eval = function(code, _v, _vname, path3, parent, parentPropName) {
28816
- this.currSandbox._$_parentProperty = parentPropName;
28817
- this.currSandbox._$_parent = parent;
28818
- this.currSandbox._$_property = _vname;
28819
- this.currSandbox._$_root = this.json;
28820
- this.currSandbox._$_v = _v;
28821
- const containsPath = code.includes("@path");
28822
- if (containsPath) {
28823
- this.currSandbox._$_path = JSONPath.toPathString(path3.concat([_vname]));
28824
- }
28825
- const scriptCacheKey = this.currEval + "Script:" + code;
28826
- if (!JSONPath.cache[scriptCacheKey]) {
28827
- let script = code.replaceAll("@parentProperty", "_$_parentProperty").replaceAll("@parent", "_$_parent").replaceAll("@property", "_$_property").replaceAll("@root", "_$_root").replaceAll(/@([.\s)[])/gu, "_$_v$1");
28828
- if (containsPath) {
28829
- script = script.replaceAll("@path", "_$_path");
28830
- }
28831
- if (this.currEval === "safe" || this.currEval === true || this.currEval === undefined) {
28832
- JSONPath.cache[scriptCacheKey] = new this.safeVm.Script(script);
28833
- } else if (this.currEval === "native") {
28834
- JSONPath.cache[scriptCacheKey] = new this.vm.Script(script);
28835
- } else if (typeof this.currEval === "function" && this.currEval.prototype && Object.hasOwn(this.currEval.prototype, "runInNewContext")) {
28836
- const CurrEval = this.currEval;
28837
- JSONPath.cache[scriptCacheKey] = new CurrEval(script);
28838
- } else if (typeof this.currEval === "function") {
28839
- JSONPath.cache[scriptCacheKey] = {
28840
- runInNewContext: (context) => this.currEval(script, context)
28841
- };
28842
- } else {
28843
- throw new TypeError(`Unknown "eval" property "${this.currEval}"`);
28844
- }
28845
- }
28846
- try {
28847
- return JSONPath.cache[scriptCacheKey].runInNewContext(this.currSandbox);
28848
- } catch (e) {
28849
- if (this.ignoreEvalErrors) {
28850
- return false;
28851
- }
28852
- throw new Error("jsonPath: " + e.message + ": " + code);
28853
- }
28854
- };
28855
- JSONPath.cache = {};
28856
- JSONPath.toPathString = function(pathArr) {
28857
- const x = pathArr, n = x.length;
28858
- let p = "$";
28859
- for (let i = 1;i < n; i++) {
28860
- if (!/^(~|\^|@.*?\(\))$/u.test(x[i])) {
28861
- p += /^[0-9*]+$/u.test(x[i]) ? "[" + x[i] + "]" : "['" + x[i] + "']";
28862
- }
28863
- }
28864
- return p;
28865
- };
28866
- JSONPath.toPointer = function(pointer) {
28867
- const x = pointer, n = x.length;
28868
- let p = "";
28869
- for (let i = 1;i < n; i++) {
28870
- if (!/^(~|\^|@.*?\(\))$/u.test(x[i])) {
28871
- p += "/" + x[i].toString().replaceAll("~", "~0").replaceAll("/", "~1");
28872
- }
28873
- }
28874
- return p;
28875
- };
28876
- JSONPath.toPathArray = function(expr) {
28877
- const {
28878
- cache
28879
- } = JSONPath;
28880
- if (cache[expr]) {
28881
- return cache[expr].concat();
28882
- }
28883
- const subx = [];
28884
- const normalized = expr.replaceAll(/@(?:null|boolean|number|string|integer|undefined|nonFinite|scalar|array|object|function|other)\(\)/gu, ";$&;").replaceAll(/[['](\??\(.*?\))[\]'](?!.\])/gu, function($0, $1) {
28885
- return "[#" + (subx.push($1) - 1) + "]";
28886
- }).replaceAll(/\[['"]([^'\]]*)['"]\]/gu, function($0, prop) {
28887
- return "['" + prop.replaceAll(".", "%@%").replaceAll("~", "%%@@%%") + "']";
28888
- }).replaceAll("~", ";~;").replaceAll(/['"]?\.['"]?(?![^[]*\])|\[['"]?/gu, ";").replaceAll("%@%", ".").replaceAll("%%@@%%", "~").replaceAll(/(?:;)?(\^+)(?:;)?/gu, function($0, ups) {
28889
- return ";" + ups.split("").join(";") + ";";
28890
- }).replaceAll(/;;;|;;/gu, ";..;").replaceAll(/;$|'?\]|'$/gu, "");
28891
- const exprList = normalized.split(";").map(function(exp) {
28892
- const match = exp.match(/#(\d+)/u);
28893
- return !match || !match[1] ? exp : subx[match[1]];
28894
- });
28895
- cache[expr] = exprList;
28896
- return cache[expr].concat();
28897
- };
28898
- JSONPath.prototype.safeVm = {
28899
- Script: SafeScript
28900
- };
28901
- JSONPath.prototype.vm = vm;
28902
27615
  // ../common/src/option-aliases.ts
28903
27616
  function warnDeprecatedOptionAlias(deprecatedFlag, preferredFlag) {
28904
27617
  getOutputSink().writeErr(`[WARN] ${deprecatedFlag} is deprecated. Use ${preferredFlag} instead.
@@ -29358,6 +28071,17 @@ var FAILURE_STATUSES = new Set([
29358
28071
  "canceled",
29359
28072
  "stopped"
29360
28073
  ]);
28074
+ // ../common/src/preview.ts
28075
+ var previewSlot = singleton("PreviewBuild");
28076
+ function isPreviewBuild() {
28077
+ return previewSlot.get(false) ?? false;
28078
+ }
28079
+ Command.prototype.previewCommand = function(nameAndArgs, opts) {
28080
+ if (isPreviewBuild()) {
28081
+ return this.command(nameAndArgs, opts);
28082
+ }
28083
+ return new Command(nameAndArgs.split(/\s+/)[0] ?? nameAndArgs);
28084
+ };
29361
28085
  // ../common/src/screen-logger.ts
29362
28086
  var ScreenLogger;
29363
28087
  ((ScreenLogger) => {
@@ -29390,8 +28114,8 @@ function appendUserAgentToken(value, userAgent) {
29390
28114
  function getEffectiveUserAgent(userAgent) {
29391
28115
  return appendUserAgentToken(sdkUserAgentHostToken.get(), userAgent);
29392
28116
  }
29393
- function isHeadersLike(headers) {
29394
- return typeof headers === "object" && headers !== null && "get" in headers && typeof headers.get === "function" && "set" in headers && typeof headers.set === "function";
28117
+ function getHeaderName(headers, headerName) {
28118
+ return Object.keys(headers).find((key) => key.toLowerCase() === headerName.toLowerCase());
29395
28119
  }
29396
28120
  function getSdkUserAgentToken(pkg) {
29397
28121
  const packageName = pkg.name.replace(/^@uipath\//, "");
@@ -29399,59 +28123,31 @@ function getSdkUserAgentToken(pkg) {
29399
28123
  }
29400
28124
  function addSdkUserAgentHeader(headers, userAgent) {
29401
28125
  const result = { ...headers ?? {} };
29402
- const effectiveUserAgent = getEffectiveUserAgent(userAgent);
29403
- const headerName = Object.keys(result).find((key) => key.toLowerCase() === USER_AGENT_HEADER.toLowerCase());
29404
- if (headerName) {
29405
- result[headerName] = appendUserAgentToken(result[headerName], effectiveUserAgent);
29406
- } else {
29407
- result[USER_AGENT_HEADER] = effectiveUserAgent;
29408
- }
28126
+ const headerName = getHeaderName(result, USER_AGENT_HEADER);
28127
+ result[headerName ?? USER_AGENT_HEADER] = appendUserAgentToken(headerName ? result[headerName] : undefined, getEffectiveUserAgent(userAgent));
29409
28128
  return result;
29410
28129
  }
29411
- function withSdkUserAgentHeader(headers, userAgent) {
29412
- const effectiveUserAgent = getEffectiveUserAgent(userAgent);
29413
- if (isHeadersLike(headers)) {
29414
- headers.set(USER_AGENT_HEADER, appendUserAgentToken(headers.get(USER_AGENT_HEADER), effectiveUserAgent));
29415
- return headers;
29416
- }
29417
- if (Array.isArray(headers)) {
29418
- const result = headers.map((entry) => {
29419
- const [key, value] = entry;
29420
- return [key, value];
29421
- });
29422
- const headerIndex = result.findIndex(([key]) => key.toLowerCase() === USER_AGENT_HEADER.toLowerCase());
29423
- if (headerIndex >= 0) {
29424
- const [key, value] = result[headerIndex];
29425
- result[headerIndex] = [
29426
- key,
29427
- appendUserAgentToken(value, effectiveUserAgent)
29428
- ];
29429
- } else {
29430
- result.push([USER_AGENT_HEADER, effectiveUserAgent]);
29431
- }
29432
- return result;
29433
- }
29434
- return addSdkUserAgentHeader(typeof headers === "object" && headers !== null ? { ...headers } : {}, effectiveUserAgent);
28130
+ function asHeaderRecord(headers) {
28131
+ return typeof headers === "object" && headers !== null ? { ...headers } : {};
29435
28132
  }
29436
- function withUserAgentInitOverride(initOverrides, userAgent) {
28133
+ function withForwardedHeadersInitOverride(initOverrides, forward) {
29437
28134
  return async (requestContext) => {
29438
- const initWithUserAgent = {
28135
+ const initWithHeaders = {
29439
28136
  ...requestContext.init,
29440
- headers: withSdkUserAgentHeader(requestContext.init.headers, userAgent)
28137
+ headers: forward(asHeaderRecord(requestContext.init.headers))
29441
28138
  };
29442
28139
  const override = typeof initOverrides === "function" ? await initOverrides({
29443
28140
  ...requestContext,
29444
- init: initWithUserAgent
28141
+ init: initWithHeaders
29445
28142
  }) : initOverrides;
29446
28143
  return {
29447
28144
  ...override ?? {},
29448
- headers: withSdkUserAgentHeader(override?.headers ?? initWithUserAgent.headers, userAgent)
28145
+ headers: forward(asHeaderRecord(override?.headers ?? initWithHeaders.headers))
29449
28146
  };
29450
28147
  };
29451
28148
  }
29452
- function installSdkUserAgentHeader(BaseApiClass, userAgent) {
28149
+ function installRequestHeaderForwarding(BaseApiClass, patchKey, forward) {
29453
28150
  const prototype = BaseApiClass.prototype;
29454
- const patchKey = userAgentPatchKey(userAgent);
29455
28151
  if (prototype[patchKey]) {
29456
28152
  return;
29457
28153
  }
@@ -29459,13 +28155,16 @@ function installSdkUserAgentHeader(BaseApiClass, userAgent) {
29459
28155
  throw new Error("Generated BaseAPI request function not found.");
29460
28156
  }
29461
28157
  const originalRequest = prototype.request;
29462
- prototype.request = function requestWithUserAgent(context, initOverrides) {
29463
- return originalRequest.call(this, context, withUserAgentInitOverride(initOverrides, userAgent));
28158
+ prototype.request = function requestWithForwardedHeaders(context, initOverrides) {
28159
+ return originalRequest.call(this, context, withForwardedHeadersInitOverride(initOverrides, forward));
29464
28160
  };
29465
28161
  Object.defineProperty(prototype, patchKey, {
29466
28162
  value: true
29467
28163
  });
29468
28164
  }
28165
+ function installSdkUserAgentHeader(BaseApiClass, userAgent) {
28166
+ installRequestHeaderForwarding(BaseApiClass, userAgentPatchKey(userAgent), (headers) => addSdkUserAgentHeader(headers, userAgent));
28167
+ }
29469
28168
  // ../common/src/tool-provider.ts
29470
28169
  var factorySlot = singleton("PackagerFactoryProvider");
29471
28170
  // ../orchestrator-sdk/generated/src/runtime.ts
@@ -29757,7 +28456,7 @@ class TextApiResponse {
29757
28456
  var package_default2 = {
29758
28457
  name: "@uipath/orchestrator-sdk",
29759
28458
  license: "MIT",
29760
- version: "1.196.0",
28459
+ version: "1.197.0",
29761
28460
  repository: {
29762
28461
  type: "git",
29763
28462
  url: "https://github.com/UiPath/cli.git",
@@ -29791,7 +28490,7 @@ var package_default2 = {
29791
28490
  ],
29792
28491
  private: true,
29793
28492
  scripts: {
29794
- build: "bun build ./src/index.ts --outdir dist --format esm --target node && bun build ./src/index.browser.ts --outdir dist --format esm --target browser --external @uipath/auth --external @uipath/common && tsc -p tsconfig.build.json --noCheck",
28493
+ build: "bun build ./src/index.ts --outdir dist --format esm --target node --sourcemap=linked && bun build ./src/index.browser.ts --outdir dist --format esm --target browser --external @uipath/auth --external @uipath/common --sourcemap=linked && tsc -p tsconfig.build.json --noCheck",
29795
28494
  generate: "bun run src/scripts/generate-sdk.ts",
29796
28495
  lint: "biome check .",
29797
28496
  test: "vitest run",
@@ -50211,6 +48910,12 @@ var normalizeAndValidateBaseUrl = (rawUrl) => {
50211
48910
  }
50212
48911
  return url.pathname.length > 1 ? url.origin : baseUrl;
50213
48912
  };
48913
+ var resolveScopes = (isExternalAppAuth, customScopes, fileScopes) => {
48914
+ const requestedScopes = customScopes?.length ? customScopes : fileScopes ?? [];
48915
+ if (isExternalAppAuth)
48916
+ return requestedScopes;
48917
+ return [...new Set([...DEFAULT_SCOPES, ...requestedScopes])];
48918
+ };
50214
48919
  var resolveConfigAsync = async ({
50215
48920
  customAuthority,
50216
48921
  customClientId,
@@ -50241,7 +48946,7 @@ var resolveConfigAsync = async ({
50241
48946
  clientSecret = fileAuth.clientSecret;
50242
48947
  }
50243
48948
  const isExternalAppAuth = clientId !== DEFAULT_CLIENT_ID && Boolean(clientSecret);
50244
- const scopes = customScopes && customScopes.length > 0 ? customScopes : fileAuth.scopes && fileAuth.scopes.length > 0 ? fileAuth.scopes : isExternalAppAuth ? [] : DEFAULT_SCOPES;
48949
+ const scopes = resolveScopes(isExternalAppAuth, customScopes, fileAuth.scopes);
50245
48950
  return {
50246
48951
  clientId,
50247
48952
  clientSecret,
@@ -50256,6 +48961,76 @@ var resolveConfigAsync = async ({
50256
48961
  init_constants();
50257
48962
  // ../auth/src/loginStatus.ts
50258
48963
  init_src();
48964
+
48965
+ // ../auth/src/authProfile.ts
48966
+ init_src();
48967
+ init_constants();
48968
+ var DEFAULT_AUTH_PROFILE = "default";
48969
+ var PROFILE_DIR = "profiles";
48970
+ var PROFILE_NAME_RE = /^[A-Za-z0-9._-]+$/;
48971
+ var ACTIVE_AUTH_PROFILE_KEY = Symbol.for("@uipath/auth/ActiveAuthProfile");
48972
+ var AUTH_PROFILE_STORAGE_KEY = Symbol.for("@uipath/auth/ProfileStorage");
48973
+ var globalSlot2 = globalThis;
48974
+ function isAuthProfileStorage(value) {
48975
+ return value !== null && typeof value === "object" && "getStore" in value && "run" in value;
48976
+ }
48977
+ function createProfileStorage() {
48978
+ const [error, mod2] = catchError2(() => __require("node:async_hooks"));
48979
+ if (error || typeof mod2?.AsyncLocalStorage !== "function") {
48980
+ return {
48981
+ getStore: () => {
48982
+ return;
48983
+ },
48984
+ run: (_store, fn) => fn()
48985
+ };
48986
+ }
48987
+ return new mod2.AsyncLocalStorage;
48988
+ }
48989
+ function getProfileStorage() {
48990
+ const existing = globalSlot2[AUTH_PROFILE_STORAGE_KEY];
48991
+ if (isAuthProfileStorage(existing)) {
48992
+ return existing;
48993
+ }
48994
+ const storage = createProfileStorage();
48995
+ globalSlot2[AUTH_PROFILE_STORAGE_KEY] = storage;
48996
+ return storage;
48997
+ }
48998
+ var profileStorage = getProfileStorage();
48999
+
49000
+ class AuthProfileValidationError extends Error {
49001
+ constructor(message) {
49002
+ super(message);
49003
+ this.name = "AuthProfileValidationError";
49004
+ }
49005
+ }
49006
+ function normalizeAuthProfileName(profile) {
49007
+ if (profile === undefined || profile === DEFAULT_AUTH_PROFILE) {
49008
+ return;
49009
+ }
49010
+ if (profile.length === 0 || profile === "." || profile === ".." || !PROFILE_NAME_RE.test(profile)) {
49011
+ throw new AuthProfileValidationError(`Invalid profile name "${profile}". Profile names may contain only letters, numbers, '.', '_', and '-'.`);
49012
+ }
49013
+ return profile;
49014
+ }
49015
+ function getActiveAuthProfile() {
49016
+ const scopedState = profileStorage.getStore();
49017
+ if (scopedState !== undefined) {
49018
+ return scopedState.profile;
49019
+ }
49020
+ return globalSlot2[ACTIVE_AUTH_PROFILE_KEY]?.profile;
49021
+ }
49022
+ function resolveAuthProfileFilePath(profile) {
49023
+ const normalized = normalizeAuthProfileName(profile);
49024
+ if (normalized === undefined) {
49025
+ throw new AuthProfileValidationError(`"${DEFAULT_AUTH_PROFILE}" is the built-in profile and does not have a profile file path.`);
49026
+ }
49027
+ const fs7 = getFileSystem();
49028
+ return fs7.path.join(fs7.env.homedir(), UIPATH_HOME_DIR, PROFILE_DIR, normalized, AUTH_FILENAME);
49029
+ }
49030
+ function getActiveAuthProfileFilePath() {
49031
+ const profile = getActiveAuthProfile();
49032
+ return profile ? resolveAuthProfileFilePath(profile) : undefined;
49033
+ }
50259
49034
  // ../auth/src/utils/jwt.ts
50260
49035
  class InvalidIssuerError extends Error {
50261
49036
  expected;
@@ -50384,23 +49159,74 @@ var readAuthFromEnv = () => {
50384
49159
  organizationId,
50385
49160
  tenantName,
50386
49161
  tenantId,
50387
- expiration
49162
+ expiration,
49163
+ source: "env" /* Env */
50388
49164
  };
50389
49165
  };
50390
49166
 
49167
+ // ../auth/src/refreshCircuitBreaker.ts
49168
+ init_src();
49169
+ var BREAKER_SUFFIX = ".refresh-state";
49170
+ var BACKOFF_BASE_MS = 60000;
49171
+ var BACKOFF_CAP_MS = 60 * 60 * 1000;
49172
+ var SURFACE_WINDOW_MS = 60 * 60 * 1000;
49173
+ async function refreshTokenFingerprint(refreshToken) {
49174
+ const bytes = new TextEncoder().encode(refreshToken);
49175
+ if (globalThis.crypto?.subtle) {
49176
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", bytes);
49177
+ return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("").slice(0, 16);
49178
+ }
49179
+ const { createHash } = await import("node:crypto");
49180
+ return createHash("sha256").update(refreshToken).digest("hex").slice(0, 16);
49181
+ }
49182
+ function breakerPathFor(authPath) {
49183
+ return `${authPath}${BREAKER_SUFFIX}`;
49184
+ }
49185
+ async function loadRefreshBreaker(authPath) {
49186
+ const fs7 = getFileSystem();
49187
+ try {
49188
+ const content = await fs7.readFile(breakerPathFor(authPath), "utf-8");
49189
+ if (!content)
49190
+ return {};
49191
+ const parsed = JSON.parse(content);
49192
+ return parsed && typeof parsed === "object" ? parsed : {};
49193
+ } catch {
49194
+ return {};
49195
+ }
49196
+ }
49197
+ async function saveRefreshBreaker(authPath, state) {
49198
+ try {
49199
+ const fs7 = getFileSystem();
49200
+ const path3 = breakerPathFor(authPath);
49201
+ await fs7.mkdir(fs7.path.dirname(path3));
49202
+ const tempPath = `${path3}.tmp`;
49203
+ await fs7.writeFile(tempPath, JSON.stringify(state));
49204
+ await fs7.rename(tempPath, path3);
49205
+ } catch {}
49206
+ }
49207
+ async function clearRefreshBreaker(authPath) {
49208
+ const fs7 = getFileSystem();
49209
+ const path3 = breakerPathFor(authPath);
49210
+ try {
49211
+ if (await fs7.exists(path3)) {
49212
+ await fs7.rm(path3);
49213
+ }
49214
+ } catch {}
49215
+ }
49216
+ function nextBackoffMs(attempts) {
49217
+ const shift = Math.max(0, attempts - 1);
49218
+ return Math.min(BACKOFF_BASE_MS * 2 ** shift, BACKOFF_CAP_MS);
49219
+ }
49220
+ function shouldSurface(state, nowMs) {
49221
+ if (state.lastSurfacedAtMs === undefined)
49222
+ return true;
49223
+ return nowMs - state.lastSurfacedAtMs >= SURFACE_WINDOW_MS;
49224
+ }
49225
+
50391
49226
  // ../auth/src/robotClientFallback.ts
50392
49227
  init_src();
50393
49228
  var DEFAULT_TIMEOUT_MS = 1000;
50394
49229
  var CLOSE_TIMEOUT_MS = 500;
50395
- var NOTICE_SENTINEL = Symbol.for("@uipath/auth/robotFallbackNoticePrinted");
50396
- var printNoticeOnce = () => {
50397
- const slot = globalThis;
50398
- if (slot[NOTICE_SENTINEL])
50399
- return;
50400
- slot[NOTICE_SENTINEL] = true;
50401
- catchError2(() => process.stderr.write(`Using UiPath Robot credentials. Run 'uip login' for a dedicated session.
50402
- `));
50403
- };
50404
49230
  var ROBOT_USER_SERVICES_PIPE = "UiPathUserServices";
50405
49231
  var ROBOT_USER_SERVICES_ALTERNATE_PIPE = `${ROBOT_USER_SERVICES_PIPE}Alternate`;
50406
49232
  var PIPE_NAME_MAX_LENGTH = 103;
@@ -50516,7 +49342,6 @@ var tryRobotClientFallback = async (options = {}) => {
50516
49342
  issuerFromToken = issClaim;
50517
49343
  }
50518
49344
  }
50519
- printNoticeOnce();
50520
49345
  return {
50521
49346
  accessToken,
50522
49347
  baseUrl: parsedUrl.baseUrl,
@@ -50741,18 +49566,327 @@ var saveEnvFileAsync = async ({
50741
49566
  };
50742
49567
 
50743
49568
  // ../auth/src/loginStatus.ts
50744
- function normalizeTokenRefreshFailure() {
50745
- return "stored refresh token is invalid or expired";
49569
+ var getLoginStatusAsync = async (options = {}) => {
49570
+ return getLoginStatusWithDeps(options);
49571
+ };
49572
+ var getLoginStatusWithDeps = async (options = {}, deps = {}) => {
49573
+ const {
49574
+ resolveEnvFilePath = resolveEnvFilePathAsync,
49575
+ loadEnvFile = loadEnvFileAsync,
49576
+ saveEnvFile = saveEnvFileAsync,
49577
+ getFs = getFileSystem,
49578
+ refreshToken: refreshTokenFn = refreshAccessToken,
49579
+ resolveConfig: resolveConfig2 = resolveConfigAsync,
49580
+ robotFallback = tryRobotClientFallback,
49581
+ loadBreaker = loadRefreshBreaker,
49582
+ saveBreaker = saveRefreshBreaker,
49583
+ clearBreaker = clearRefreshBreaker
49584
+ } = deps;
49585
+ if (isRobotAuthEnforced()) {
49586
+ return resolveRobotEnforcedStatus(robotFallback);
49587
+ }
49588
+ if (isEnvAuthEnabled()) {
49589
+ return readAuthFromEnv();
49590
+ }
49591
+ const activeProfile = getActiveAuthProfile();
49592
+ const activeProfileFilePath = getActiveAuthProfileFilePath();
49593
+ const usingActiveProfile = activeProfile !== undefined && (options.envFilePath === undefined || options.envFilePath === activeProfileFilePath);
49594
+ const envFilePath = options.envFilePath ?? activeProfileFilePath ?? DEFAULT_ENV_FILENAME;
49595
+ const { ensureTokenValidityMinutes } = options;
49596
+ const { absolutePath } = await resolveEnvFilePath(envFilePath);
49597
+ if (absolutePath === undefined) {
49598
+ if (usingActiveProfile) {
49599
+ return {
49600
+ loginStatus: "Not logged in",
49601
+ hint: `No credentials found for profile "${activeProfile}". Run 'uip login --profile ${activeProfile}' to authenticate this profile.`
49602
+ };
49603
+ }
49604
+ return resolveBorrowedRobotStatus(robotFallback);
49605
+ }
49606
+ const loaded = await loadFileCredentials(loadEnvFile, absolutePath);
49607
+ if ("status" in loaded) {
49608
+ return loaded.status;
49609
+ }
49610
+ const { credentials } = loaded;
49611
+ const globalHint = () => usingActiveProfile ? Promise.resolve(undefined) : getGlobalCredsHint(getFs, loadEnvFile, absolutePath, envFilePath);
49612
+ const expiration = getTokenExpiration(credentials.UIPATH_ACCESS_TOKEN);
49613
+ const outerThreshold = computeExpirationThreshold(ensureTokenValidityMinutes);
49614
+ let tokens = {
49615
+ accessToken: credentials.UIPATH_ACCESS_TOKEN,
49616
+ refreshToken: credentials.UIPATH_REFRESH_TOKEN,
49617
+ expiration,
49618
+ lockReleaseFailed: false
49619
+ };
49620
+ const refreshToken = credentials.UIPATH_REFRESH_TOKEN;
49621
+ if (expiration && expiration <= outerThreshold && refreshToken) {
49622
+ const refreshed = await attemptRefresh({
49623
+ absolutePath,
49624
+ credentials,
49625
+ accessToken: credentials.UIPATH_ACCESS_TOKEN,
49626
+ refreshToken,
49627
+ expiration,
49628
+ ensureTokenValidityMinutes,
49629
+ getFs,
49630
+ loadEnvFile,
49631
+ saveEnvFile,
49632
+ refreshFn: refreshTokenFn,
49633
+ resolveConfig: resolveConfig2,
49634
+ loadBreaker,
49635
+ saveBreaker,
49636
+ clearBreaker,
49637
+ globalHint
49638
+ });
49639
+ if (refreshed.kind === "terminal") {
49640
+ return refreshed.status;
49641
+ }
49642
+ tokens = refreshed.tokens;
49643
+ }
49644
+ return buildFileStatus(tokens, credentials, globalHint);
49645
+ };
49646
+ async function resolveRobotEnforcedStatus(robotFallback) {
49647
+ if (isEnvAuthEnabled()) {
49648
+ throw new EnvAuthConfigError(`${ENV_AUTH_ENABLE_VAR}=true and ${ENFORCE_ROBOT_AUTH_VAR}=true ` + `are mutually exclusive. Unset one of them and re-run.`);
49649
+ }
49650
+ const robotCreds = await robotFallback({ force: true });
49651
+ if (!robotCreds) {
49652
+ return {
49653
+ loginStatus: "Not logged in",
49654
+ 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.`
49655
+ };
49656
+ }
49657
+ return buildRobotStatus(robotCreds);
50746
49658
  }
50747
- function normalizeTokenRefreshUnavailableFailure() {
50748
- return "token refresh failed before authentication completed";
49659
+ async function resolveBorrowedRobotStatus(robotFallback) {
49660
+ const robotCreds = await robotFallback();
49661
+ return robotCreds ? buildRobotStatus(robotCreds) : { loginStatus: "Not logged in" };
50749
49662
  }
50750
- function errorMessage(error) {
50751
- return error instanceof Error ? error.message : String(error);
49663
+ async function loadFileCredentials(loadEnvFile, absolutePath) {
49664
+ let credentials;
49665
+ try {
49666
+ credentials = await loadEnvFile({ envPath: absolutePath });
49667
+ } catch (error) {
49668
+ if (isFileNotFoundError(error)) {
49669
+ return { status: { loginStatus: "Not logged in" } };
49670
+ }
49671
+ throw error;
49672
+ }
49673
+ if (!credentials.UIPATH_ACCESS_TOKEN) {
49674
+ return { status: { loginStatus: "Not logged in" } };
49675
+ }
49676
+ return { credentials };
49677
+ }
49678
+ async function getGlobalCredsHint(getFs, loadEnvFile, absolutePath, envFilePath) {
49679
+ const fs7 = getFs();
49680
+ const globalPath = fs7.path.join(fs7.env.homedir(), envFilePath);
49681
+ if (absolutePath === globalPath)
49682
+ return;
49683
+ if (!await fs7.exists(globalPath))
49684
+ return;
49685
+ try {
49686
+ const globalCreds = await loadEnvFile({ envPath: globalPath });
49687
+ if (!globalCreds.UIPATH_ACCESS_TOKEN)
49688
+ return;
49689
+ const globalExp = getTokenExpiration(globalCreds.UIPATH_ACCESS_TOKEN);
49690
+ if (globalExp && globalExp <= new Date)
49691
+ return;
49692
+ 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.`;
49693
+ } catch {
49694
+ return;
49695
+ }
50752
49696
  }
50753
49697
  function computeExpirationThreshold(ensureTokenValidityMinutes) {
50754
49698
  return new Date(Date.now() + (ensureTokenValidityMinutes ?? 0) * 60 * 1000);
50755
49699
  }
49700
+ async function attemptRefresh(ctx) {
49701
+ const shortCircuit = await circuitBreakerShortCircuit(ctx);
49702
+ if (shortCircuit) {
49703
+ return { kind: "terminal", status: shortCircuit };
49704
+ }
49705
+ let release;
49706
+ try {
49707
+ release = await ctx.getFs().acquireLock(ctx.absolutePath);
49708
+ } catch (error) {
49709
+ return {
49710
+ kind: "terminal",
49711
+ status: await lockAcquireFailureStatus(ctx, error)
49712
+ };
49713
+ }
49714
+ let lockedFailure;
49715
+ let lockReleaseFailed = false;
49716
+ let success;
49717
+ try {
49718
+ const outcome = await runRefreshLocked({
49719
+ absolutePath: ctx.absolutePath,
49720
+ refreshToken: ctx.refreshToken,
49721
+ customAuthority: ctx.credentials.UIPATH_URL,
49722
+ ensureTokenValidityMinutes: ctx.ensureTokenValidityMinutes,
49723
+ loadEnvFile: ctx.loadEnvFile,
49724
+ saveEnvFile: ctx.saveEnvFile,
49725
+ refreshFn: ctx.refreshFn,
49726
+ resolveConfig: ctx.resolveConfig,
49727
+ loadBreaker: ctx.loadBreaker,
49728
+ saveBreaker: ctx.saveBreaker,
49729
+ clearBreaker: ctx.clearBreaker
49730
+ });
49731
+ if (outcome.kind === "fail") {
49732
+ lockedFailure = outcome.status;
49733
+ } else {
49734
+ success = outcome;
49735
+ }
49736
+ } finally {
49737
+ try {
49738
+ await release();
49739
+ } catch {
49740
+ lockReleaseFailed = true;
49741
+ }
49742
+ }
49743
+ if (lockedFailure) {
49744
+ const globalHint = await ctx.globalHint();
49745
+ const base = globalHint ? { ...lockedFailure, loginStatus: "Expired", hint: globalHint } : lockedFailure;
49746
+ return {
49747
+ kind: "terminal",
49748
+ status: lockReleaseFailed ? { ...base, lockReleaseFailed: true } : base
49749
+ };
49750
+ }
49751
+ return {
49752
+ kind: "refreshed",
49753
+ tokens: {
49754
+ accessToken: success?.accessToken,
49755
+ refreshToken: success?.refreshToken,
49756
+ expiration: success?.expiration,
49757
+ tokenRefresh: success?.tokenRefresh,
49758
+ persistenceWarning: success?.persistenceWarning,
49759
+ lockReleaseFailed
49760
+ }
49761
+ };
49762
+ }
49763
+ async function buildFileStatus(tokens, credentials, globalHint) {
49764
+ const result = {
49765
+ loginStatus: tokens.expiration && tokens.expiration <= new Date ? "Expired" : "Logged in",
49766
+ accessToken: tokens.accessToken,
49767
+ refreshToken: tokens.refreshToken,
49768
+ baseUrl: credentials.UIPATH_URL,
49769
+ organizationName: credentials.UIPATH_ORGANIZATION_NAME,
49770
+ organizationId: credentials.UIPATH_ORGANIZATION_ID,
49771
+ tenantName: credentials.UIPATH_TENANT_NAME,
49772
+ tenantId: credentials.UIPATH_TENANT_ID,
49773
+ expiration: tokens.expiration,
49774
+ source: "file" /* File */,
49775
+ ...tokens.persistenceWarning ? { hint: tokens.persistenceWarning, persistenceFailed: true } : {},
49776
+ ...tokens.lockReleaseFailed ? { lockReleaseFailed: true } : {},
49777
+ ...tokens.tokenRefresh ? { tokenRefresh: tokens.tokenRefresh } : {}
49778
+ };
49779
+ if (result.loginStatus === "Expired") {
49780
+ const hint = await globalHint();
49781
+ if (hint) {
49782
+ result.hint = hint;
49783
+ }
49784
+ }
49785
+ return result;
49786
+ }
49787
+ function buildRobotStatus(robotCreds) {
49788
+ return {
49789
+ loginStatus: "Logged in",
49790
+ accessToken: robotCreds.accessToken,
49791
+ baseUrl: robotCreds.baseUrl,
49792
+ organizationName: robotCreds.organizationName,
49793
+ organizationId: robotCreds.organizationId,
49794
+ tenantName: robotCreds.tenantName,
49795
+ tenantId: robotCreds.tenantId,
49796
+ issuer: robotCreds.issuer,
49797
+ expiration: getTokenExpiration(robotCreds.accessToken),
49798
+ source: "robot" /* Robot */
49799
+ };
49800
+ }
49801
+ var isFileNotFoundError = (error) => {
49802
+ if (!(error instanceof Object))
49803
+ return false;
49804
+ return error.code === "ENOENT";
49805
+ };
49806
+ async function circuitBreakerShortCircuit(ctx) {
49807
+ const {
49808
+ absolutePath,
49809
+ refreshToken,
49810
+ accessToken,
49811
+ credentials,
49812
+ expiration,
49813
+ loadBreaker,
49814
+ saveBreaker,
49815
+ clearBreaker
49816
+ } = ctx;
49817
+ const fingerprint = await refreshTokenFingerprint(refreshToken);
49818
+ const breaker = await loadBreaker(absolutePath).catch(() => ({}));
49819
+ if (breaker.deadTokenFp && breaker.deadTokenFp !== fingerprint) {
49820
+ await clearBreaker(absolutePath);
49821
+ breaker.deadTokenFp = undefined;
49822
+ }
49823
+ const nowMs = Date.now();
49824
+ const tokenIsDead = breaker.deadTokenFp === fingerprint;
49825
+ const inBackoff = breaker.backoffUntilMs !== undefined && nowMs < breaker.backoffUntilMs;
49826
+ if (!tokenIsDead && !inBackoff)
49827
+ return;
49828
+ const globalHint = await ctx.globalHint();
49829
+ const suppressed = !shouldSurface(breaker, nowMs);
49830
+ if (!suppressed) {
49831
+ await saveBreaker(absolutePath, {
49832
+ ...breaker,
49833
+ lastSurfacedAtMs: nowMs
49834
+ });
49835
+ }
49836
+ 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>.";
49837
+ const backoffHint = "Token refresh is temporarily backed off after a recent network error and will retry automatically once the backoff window elapses.";
49838
+ return {
49839
+ loginStatus: globalHint ? "Expired" : "Refresh Failed",
49840
+ ...globalHint ? {
49841
+ accessToken,
49842
+ refreshToken,
49843
+ baseUrl: credentials.UIPATH_URL,
49844
+ organizationName: credentials.UIPATH_ORGANIZATION_NAME,
49845
+ organizationId: credentials.UIPATH_ORGANIZATION_ID,
49846
+ tenantName: credentials.UIPATH_TENANT_NAME,
49847
+ tenantId: credentials.UIPATH_TENANT_ID,
49848
+ expiration,
49849
+ source: "file" /* File */
49850
+ } : {},
49851
+ hint: globalHint ?? (tokenIsDead ? deadHint : backoffHint),
49852
+ refreshCircuitOpen: true,
49853
+ refreshTelemetrySuppressed: suppressed,
49854
+ tokenRefresh: { attempted: false, success: false }
49855
+ };
49856
+ }
49857
+ async function lockAcquireFailureStatus(ctx, error) {
49858
+ const msg = errorMessage(error);
49859
+ const globalHint = await ctx.globalHint();
49860
+ if (globalHint) {
49861
+ return {
49862
+ loginStatus: "Expired",
49863
+ accessToken: ctx.accessToken,
49864
+ refreshToken: ctx.refreshToken,
49865
+ baseUrl: ctx.credentials.UIPATH_URL,
49866
+ organizationName: ctx.credentials.UIPATH_ORGANIZATION_NAME,
49867
+ organizationId: ctx.credentials.UIPATH_ORGANIZATION_ID,
49868
+ tenantName: ctx.credentials.UIPATH_TENANT_NAME,
49869
+ tenantId: ctx.credentials.UIPATH_TENANT_ID,
49870
+ expiration: ctx.expiration,
49871
+ source: "file" /* File */,
49872
+ hint: globalHint,
49873
+ tokenRefresh: {
49874
+ attempted: false,
49875
+ success: false,
49876
+ errorMessage: `lock acquisition failed: ${msg}`
49877
+ }
49878
+ };
49879
+ }
49880
+ return {
49881
+ loginStatus: "Refresh Failed",
49882
+ 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.",
49883
+ tokenRefresh: {
49884
+ attempted: false,
49885
+ success: false,
49886
+ errorMessage: `lock acquisition failed: ${msg}`
49887
+ }
49888
+ };
49889
+ }
50756
49890
  async function runRefreshLocked(inputs) {
50757
49891
  const {
50758
49892
  absolutePath,
@@ -50762,7 +49896,10 @@ async function runRefreshLocked(inputs) {
50762
49896
  loadEnvFile,
50763
49897
  saveEnvFile,
50764
49898
  refreshFn,
50765
- resolveConfig: resolveConfig2
49899
+ resolveConfig: resolveConfig2,
49900
+ loadBreaker,
49901
+ saveBreaker,
49902
+ clearBreaker
50766
49903
  } = inputs;
50767
49904
  const expirationThreshold = computeExpirationThreshold(ensureTokenValidityMinutes);
50768
49905
  let fresh;
@@ -50785,6 +49922,7 @@ async function runRefreshLocked(inputs) {
50785
49922
  const freshAccess = fresh.UIPATH_ACCESS_TOKEN;
50786
49923
  const freshExp = freshAccess ? getTokenExpiration(freshAccess) : undefined;
50787
49924
  if (freshAccess && freshExp && freshExp > expirationThreshold) {
49925
+ await clearBreaker(absolutePath);
50788
49926
  return {
50789
49927
  kind: "ok",
50790
49928
  accessToken: freshAccess,
@@ -50808,8 +49946,21 @@ async function runRefreshLocked(inputs) {
50808
49946
  refreshedRefresh = refreshed.refreshToken;
50809
49947
  } catch (error) {
50810
49948
  const isOAuthFailure = isTokenRefreshOAuthFailure(error);
50811
- 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.";
49949
+ 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.";
50812
49950
  const message = isOAuthFailure ? normalizeTokenRefreshFailure() : normalizeTokenRefreshUnavailableFailure();
49951
+ const fp = await refreshTokenFingerprint(tokenForIdP);
49952
+ if (isOAuthFailure) {
49953
+ await saveBreaker(absolutePath, { deadTokenFp: fp });
49954
+ } else {
49955
+ const prior = await loadBreaker(absolutePath).catch(() => ({}));
49956
+ const attempts = (prior.attempts ?? 0) + 1;
49957
+ await saveBreaker(absolutePath, {
49958
+ ...prior,
49959
+ deadTokenFp: undefined,
49960
+ attempts,
49961
+ backoffUntilMs: Date.now() + nextBackoffMs(attempts)
49962
+ });
49963
+ }
50813
49964
  return {
50814
49965
  kind: "fail",
50815
49966
  status: {
@@ -50838,6 +49989,7 @@ async function runRefreshLocked(inputs) {
50838
49989
  }
50839
49990
  };
50840
49991
  }
49992
+ await clearBreaker(absolutePath);
50841
49993
  try {
50842
49994
  await saveEnvFile({
50843
49995
  envPath: absolutePath,
@@ -50870,212 +50022,15 @@ async function runRefreshLocked(inputs) {
50870
50022
  };
50871
50023
  }
50872
50024
  }
50873
- var getLoginStatusWithDeps = async (options = {}, deps = {}) => {
50874
- const {
50875
- resolveEnvFilePath = resolveEnvFilePathAsync,
50876
- loadEnvFile = loadEnvFileAsync,
50877
- saveEnvFile = saveEnvFileAsync,
50878
- getFs = getFileSystem,
50879
- refreshToken: refreshTokenFn = refreshAccessToken,
50880
- resolveConfig: resolveConfig2 = resolveConfigAsync,
50881
- robotFallback = tryRobotClientFallback
50882
- } = deps;
50883
- if (isRobotAuthEnforced()) {
50884
- if (isEnvAuthEnabled()) {
50885
- throw new EnvAuthConfigError(`${ENV_AUTH_ENABLE_VAR}=true and ${ENFORCE_ROBOT_AUTH_VAR}=true ` + `are mutually exclusive. Unset one of them and re-run.`);
50886
- }
50887
- const robotCreds = await robotFallback({ force: true });
50888
- if (!robotCreds) {
50889
- return {
50890
- loginStatus: "Not logged in",
50891
- 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.`
50892
- };
50893
- }
50894
- const expiration2 = getTokenExpiration(robotCreds.accessToken);
50895
- return {
50896
- loginStatus: "Logged in",
50897
- accessToken: robotCreds.accessToken,
50898
- baseUrl: robotCreds.baseUrl,
50899
- organizationName: robotCreds.organizationName,
50900
- organizationId: robotCreds.organizationId,
50901
- tenantName: robotCreds.tenantName,
50902
- tenantId: robotCreds.tenantId,
50903
- issuer: robotCreds.issuer,
50904
- expiration: expiration2,
50905
- source: "robot" /* Robot */
50906
- };
50907
- }
50908
- if (isEnvAuthEnabled()) {
50909
- return readAuthFromEnv();
50910
- }
50911
- const { envFilePath = DEFAULT_ENV_FILENAME, ensureTokenValidityMinutes } = options;
50912
- const { absolutePath } = await resolveEnvFilePath(envFilePath);
50913
- if (absolutePath === undefined) {
50914
- const robotCreds = await robotFallback();
50915
- if (robotCreds) {
50916
- const expiration2 = getTokenExpiration(robotCreds.accessToken);
50917
- const status = {
50918
- loginStatus: "Logged in",
50919
- accessToken: robotCreds.accessToken,
50920
- baseUrl: robotCreds.baseUrl,
50921
- organizationName: robotCreds.organizationName,
50922
- organizationId: robotCreds.organizationId,
50923
- tenantName: robotCreds.tenantName,
50924
- tenantId: robotCreds.tenantId,
50925
- issuer: robotCreds.issuer,
50926
- expiration: expiration2,
50927
- source: "robot" /* Robot */
50928
- };
50929
- return status;
50930
- }
50931
- return { loginStatus: "Not logged in" };
50932
- }
50933
- let credentials;
50934
- try {
50935
- credentials = await loadEnvFile({ envPath: absolutePath });
50936
- } catch (error) {
50937
- if (isFileNotFoundError(error)) {
50938
- return { loginStatus: "Not logged in" };
50939
- }
50940
- throw error;
50941
- }
50942
- if (!credentials.UIPATH_ACCESS_TOKEN) {
50943
- return { loginStatus: "Not logged in" };
50944
- }
50945
- let accessToken = credentials.UIPATH_ACCESS_TOKEN;
50946
- let refreshToken = credentials.UIPATH_REFRESH_TOKEN;
50947
- let expiration = getTokenExpiration(accessToken);
50948
- let persistenceWarning;
50949
- let lockReleaseFailed = false;
50950
- let tokenRefresh;
50951
- const outerThreshold = computeExpirationThreshold(ensureTokenValidityMinutes);
50952
- const tryGlobalCredsHint = async () => {
50953
- const fs7 = getFs();
50954
- const globalPath = fs7.path.join(fs7.env.homedir(), envFilePath);
50955
- if (absolutePath === globalPath)
50956
- return;
50957
- if (!await fs7.exists(globalPath))
50958
- return;
50959
- try {
50960
- const globalCreds = await loadEnvFile({ envPath: globalPath });
50961
- if (!globalCreds.UIPATH_ACCESS_TOKEN)
50962
- return;
50963
- const globalExp = getTokenExpiration(globalCreds.UIPATH_ACCESS_TOKEN);
50964
- if (globalExp && globalExp <= new Date)
50965
- return;
50966
- 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.`;
50967
- } catch {
50968
- return;
50969
- }
50970
- };
50971
- if (expiration && expiration <= outerThreshold && refreshToken) {
50972
- let release;
50973
- try {
50974
- release = await getFs().acquireLock(absolutePath);
50975
- } catch (error) {
50976
- const msg = errorMessage(error);
50977
- const globalHint = await tryGlobalCredsHint();
50978
- if (globalHint) {
50979
- return {
50980
- loginStatus: "Expired",
50981
- accessToken,
50982
- refreshToken,
50983
- baseUrl: credentials.UIPATH_URL,
50984
- organizationName: credentials.UIPATH_ORGANIZATION_NAME,
50985
- organizationId: credentials.UIPATH_ORGANIZATION_ID,
50986
- tenantName: credentials.UIPATH_TENANT_NAME,
50987
- tenantId: credentials.UIPATH_TENANT_ID,
50988
- expiration,
50989
- source: "file" /* File */,
50990
- hint: globalHint,
50991
- tokenRefresh: {
50992
- attempted: false,
50993
- success: false,
50994
- errorMessage: `lock acquisition failed: ${msg}`
50995
- }
50996
- };
50997
- }
50998
- return {
50999
- loginStatus: "Refresh Failed",
51000
- 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.",
51001
- tokenRefresh: {
51002
- attempted: false,
51003
- success: false,
51004
- errorMessage: `lock acquisition failed: ${msg}`
51005
- }
51006
- };
51007
- }
51008
- let lockedFailure;
51009
- try {
51010
- const outcome = await runRefreshLocked({
51011
- absolutePath,
51012
- refreshToken,
51013
- customAuthority: credentials.UIPATH_URL,
51014
- ensureTokenValidityMinutes,
51015
- loadEnvFile,
51016
- saveEnvFile,
51017
- refreshFn: refreshTokenFn,
51018
- resolveConfig: resolveConfig2
51019
- });
51020
- if (outcome.kind === "fail") {
51021
- lockedFailure = outcome.status;
51022
- } else {
51023
- accessToken = outcome.accessToken;
51024
- refreshToken = outcome.refreshToken;
51025
- expiration = outcome.expiration;
51026
- tokenRefresh = outcome.tokenRefresh;
51027
- if (outcome.persistenceWarning) {
51028
- persistenceWarning = outcome.persistenceWarning;
51029
- }
51030
- }
51031
- } finally {
51032
- try {
51033
- await release();
51034
- } catch {
51035
- lockReleaseFailed = true;
51036
- }
51037
- }
51038
- if (lockedFailure) {
51039
- const globalHint = await tryGlobalCredsHint();
51040
- const base = globalHint ? {
51041
- ...lockedFailure,
51042
- loginStatus: "Expired",
51043
- hint: globalHint
51044
- } : lockedFailure;
51045
- return lockReleaseFailed ? { ...base, lockReleaseFailed: true } : base;
51046
- }
51047
- }
51048
- const result = {
51049
- loginStatus: expiration && expiration <= new Date ? "Expired" : "Logged in",
51050
- accessToken,
51051
- refreshToken,
51052
- baseUrl: credentials.UIPATH_URL,
51053
- organizationName: credentials.UIPATH_ORGANIZATION_NAME,
51054
- organizationId: credentials.UIPATH_ORGANIZATION_ID,
51055
- tenantName: credentials.UIPATH_TENANT_NAME,
51056
- tenantId: credentials.UIPATH_TENANT_ID,
51057
- expiration,
51058
- source: "file" /* File */,
51059
- ...persistenceWarning ? { hint: persistenceWarning, persistenceFailed: true } : {},
51060
- ...lockReleaseFailed ? { lockReleaseFailed: true } : {},
51061
- ...tokenRefresh ? { tokenRefresh } : {}
51062
- };
51063
- if (result.loginStatus === "Expired") {
51064
- const globalHint = await tryGlobalCredsHint();
51065
- if (globalHint) {
51066
- result.hint = globalHint;
51067
- }
51068
- }
51069
- return result;
51070
- };
51071
- var isFileNotFoundError = (error) => {
51072
- if (!(error instanceof Object))
51073
- return false;
51074
- return error.code === "ENOENT";
51075
- };
51076
- var getLoginStatusAsync = async (options = {}) => {
51077
- return getLoginStatusWithDeps(options);
51078
- };
50025
+ function normalizeTokenRefreshFailure() {
50026
+ return "stored refresh token is invalid or expired";
50027
+ }
50028
+ function normalizeTokenRefreshUnavailableFailure() {
50029
+ return "token refresh failed before authentication completed";
50030
+ }
50031
+ function errorMessage(error) {
50032
+ return error instanceof Error ? error.message : String(error);
50033
+ }
51079
50034
 
51080
50035
  // ../auth/src/authContext.ts
51081
50036
  var getAuthContext = async (options = {}) => {
@@ -51110,6 +50065,14 @@ var getAuthContext = async (options = {}) => {
51110
50065
  };
51111
50066
  // ../auth/src/interactive.ts
51112
50067
  init_src();
50068
+
50069
+ // ../auth/src/selectTenant.ts
50070
+ var TENANT_SELECTION_REQUIRED_CODE = "TENANT_SELECTION_REQUIRED";
50071
+ var INVALID_TENANT_CODE = "INVALID_TENANT";
50072
+ var TENANT_SELECTION_CODES = new Set([
50073
+ TENANT_SELECTION_REQUIRED_CODE,
50074
+ INVALID_TENANT_CODE
50075
+ ]);
51113
50076
  // ../auth/src/logout.ts
51114
50077
  init_src();
51115
50078
 
@@ -54357,13 +53320,18 @@ async function resolveCalendar(calendarKey, options) {
54357
53320
  const errorMessage2 = await extractErrorMessage(error);
54358
53321
  throw new Error(`Failed to resolve calendar '${calendarKey}': ${errorMessage2}`);
54359
53322
  }
54360
- const calendar = result.value?.[0];
54361
- if (!calendar?.id) {
53323
+ const summary = result.value?.[0];
53324
+ if (!summary?.id) {
54362
53325
  throw new Error(`Calendar not found for key: '${calendarKey}'. Use 'calendars list' to find available calendars.`);
54363
53326
  }
53327
+ const [detailError, calendar] = await catchError(api.calendarsGetById({ key: summary.id }));
53328
+ if (detailError) {
53329
+ const errorMessage2 = await extractErrorMessage(detailError);
53330
+ throw new Error(`Failed to resolve calendar '${calendarKey}': ${errorMessage2}`);
53331
+ }
54364
53332
  return {
54365
- id: calendar.id,
54366
- key: calendar.key || calendarKey,
53333
+ id: calendar.id ?? summary.id,
53334
+ key: calendar.key || summary.key || calendarKey,
54367
53335
  name: calendar.name || "",
54368
53336
  calendar
54369
53337
  };
@@ -65624,6 +64592,20 @@ async function createScheduleTrigger(options, isCronType) {
65624
64592
  return;
65625
64593
  machineRobots = resolved;
65626
64594
  }
64595
+ let calendarId;
64596
+ if (options.calendarKey !== undefined) {
64597
+ const [calendarError, resolvedCalendar] = await catchError(resolveCalendar(options.calendarKey, { tenant: options.tenant }));
64598
+ if (calendarError) {
64599
+ OutputFormatter.error({
64600
+ Result: RESULTS.Failure,
64601
+ Message: "Error resolving calendar",
64602
+ Instructions: await extractErrorMessage(calendarError)
64603
+ });
64604
+ processContext.exit(1);
64605
+ return;
64606
+ }
64607
+ calendarId = resolvedCalendar.id;
64608
+ }
65627
64609
  const scheduleData = {
65628
64610
  name: options.name,
65629
64611
  description: options.description,
@@ -65639,8 +64621,8 @@ async function createScheduleTrigger(options, isCronType) {
65639
64621
  killProcessExpression: options.killProcessExpression,
65640
64622
  runAsMe: options.runAsMe ?? false,
65641
64623
  isConnected: false,
65642
- useCalendar: !!options.calendarKey,
65643
- calendarKey: options.calendarKey,
64624
+ useCalendar: calendarId !== undefined,
64625
+ calendarId,
65644
64626
  executorRobots: [],
65645
64627
  machineRobots,
65646
64628
  tags: [],
@@ -67709,3 +66691,5 @@ export {
67709
66691
  registerCommands,
67710
66692
  metadata
67711
66693
  };
66694
+
66695
+ //# debugId=759FF9EAE2ADDBC064756E2164756E21