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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/publish.js CHANGED
@@ -13520,8 +13520,8 @@ var require_Subscription = __commonJS((exports) => {
13520
13520
  if (_parentOrParents instanceof Subscription2) {
13521
13521
  _parentOrParents.remove(this);
13522
13522
  } else if (_parentOrParents !== null) {
13523
- for (var index2 = 0;index2 < _parentOrParents.length; ++index2) {
13524
- var parent_1 = _parentOrParents[index2];
13523
+ for (var index = 0;index < _parentOrParents.length; ++index) {
13524
+ var parent_1 = _parentOrParents[index];
13525
13525
  parent_1.remove(this);
13526
13526
  }
13527
13527
  }
@@ -13536,10 +13536,10 @@ var require_Subscription = __commonJS((exports) => {
13536
13536
  }
13537
13537
  }
13538
13538
  if (isArray_1.isArray(_subscriptions)) {
13539
- var index2 = -1;
13539
+ var index = -1;
13540
13540
  var len = _subscriptions.length;
13541
- while (++index2 < len) {
13542
- var sub2 = _subscriptions[index2];
13541
+ while (++index < len) {
13542
+ var sub2 = _subscriptions[index];
13543
13543
  if (isObject_1.isObject(sub2)) {
13544
13544
  try {
13545
13545
  sub2.unsubscribe();
@@ -14969,13 +14969,13 @@ var require_AsyncAction = __commonJS((exports) => {
14969
14969
  var id = this.id;
14970
14970
  var scheduler = this.scheduler;
14971
14971
  var actions = scheduler.actions;
14972
- var index2 = actions.indexOf(this);
14972
+ var index = actions.indexOf(this);
14973
14973
  this.work = null;
14974
14974
  this.state = null;
14975
14975
  this.pending = false;
14976
14976
  this.scheduler = null;
14977
- if (index2 !== -1) {
14978
- actions.splice(index2, 1);
14977
+ if (index !== -1) {
14978
+ actions.splice(index, 1);
14979
14979
  }
14980
14980
  if (id != null) {
14981
14981
  this.id = this.recycleAsyncId(scheduler, id, null);
@@ -15819,17 +15819,17 @@ var require_AsapScheduler = __commonJS((exports) => {
15819
15819
  this.scheduled = undefined;
15820
15820
  var actions = this.actions;
15821
15821
  var error;
15822
- var index2 = -1;
15822
+ var index = -1;
15823
15823
  var count = actions.length;
15824
15824
  action = action || actions.shift();
15825
15825
  do {
15826
15826
  if (error = action.execute(action.state, action.delay)) {
15827
15827
  break;
15828
15828
  }
15829
- } while (++index2 < count && (action = actions.shift()));
15829
+ } while (++index < count && (action = actions.shift()));
15830
15830
  this.active = false;
15831
15831
  if (error) {
15832
- while (++index2 < count && (action = actions.shift())) {
15832
+ while (++index < count && (action = actions.shift())) {
15833
15833
  action.unsubscribe();
15834
15834
  }
15835
15835
  throw error;
@@ -15952,17 +15952,17 @@ var require_AnimationFrameScheduler = __commonJS((exports) => {
15952
15952
  this.scheduled = undefined;
15953
15953
  var actions = this.actions;
15954
15954
  var error;
15955
- var index2 = -1;
15955
+ var index = -1;
15956
15956
  var count = actions.length;
15957
15957
  action = action || actions.shift();
15958
15958
  do {
15959
15959
  if (error = action.execute(action.state, action.delay)) {
15960
15960
  break;
15961
15961
  }
15962
- } while (++index2 < count && (action = actions.shift()));
15962
+ } while (++index < count && (action = actions.shift()));
15963
15963
  this.active = false;
15964
15964
  if (error) {
15965
- while (++index2 < count && (action = actions.shift())) {
15965
+ while (++index < count && (action = actions.shift())) {
15966
15966
  action.unsubscribe();
15967
15967
  }
15968
15968
  throw error;
@@ -16046,16 +16046,16 @@ var require_VirtualTimeScheduler = __commonJS((exports) => {
16046
16046
  exports.VirtualTimeScheduler = VirtualTimeScheduler;
16047
16047
  var VirtualAction = function(_super) {
16048
16048
  __extends(VirtualAction2, _super);
16049
- function VirtualAction2(scheduler, work, index2) {
16050
- if (index2 === undefined) {
16051
- index2 = scheduler.index += 1;
16049
+ function VirtualAction2(scheduler, work, index) {
16050
+ if (index === undefined) {
16051
+ index = scheduler.index += 1;
16052
16052
  }
16053
16053
  var _this = _super.call(this, scheduler, work) || this;
16054
16054
  _this.scheduler = scheduler;
16055
16055
  _this.work = work;
16056
- _this.index = index2;
16056
+ _this.index = index;
16057
16057
  _this.active = true;
16058
- _this.index = scheduler.index = index2;
16058
+ _this.index = scheduler.index = index;
16059
16059
  return _this;
16060
16060
  }
16061
16061
  VirtualAction2.prototype.schedule = function(state, delay) {
@@ -17202,9 +17202,9 @@ var require_mergeMap = __commonJS((exports) => {
17202
17202
  };
17203
17203
  MergeMapSubscriber2.prototype._tryNext = function(value) {
17204
17204
  var result;
17205
- var index2 = this.index++;
17205
+ var index = this.index++;
17206
17206
  try {
17207
- result = this.project(value, index2);
17207
+ result = this.project(value, index);
17208
17208
  } catch (err) {
17209
17209
  this.destination.error(err);
17210
17210
  return;
@@ -17784,12 +17784,12 @@ var require_pairs2 = __commonJS((exports) => {
17784
17784
  }
17785
17785
  exports.pairs = pairs;
17786
17786
  function dispatch(state) {
17787
- var { keys, index: index2, subscriber, subscription, obj } = state;
17787
+ var { keys, index, subscriber, subscription, obj } = state;
17788
17788
  if (!subscriber.closed) {
17789
- if (index2 < keys.length) {
17790
- var key = keys[index2];
17789
+ if (index < keys.length) {
17790
+ var key = keys[index];
17791
17791
  subscriber.next([key, obj[key]]);
17792
- subscription.add(this.schedule({ keys, index: index2 + 1, subscriber, subscription, obj }));
17792
+ subscription.add(this.schedule({ keys, index: index + 1, subscriber, subscription, obj }));
17793
17793
  } else {
17794
17794
  subscriber.complete();
17795
17795
  }
@@ -18002,18 +18002,18 @@ var require_range = __commonJS((exports) => {
18002
18002
  count = start;
18003
18003
  start = 0;
18004
18004
  }
18005
- var index2 = 0;
18005
+ var index = 0;
18006
18006
  var current = start;
18007
18007
  if (scheduler) {
18008
18008
  return scheduler.schedule(dispatch, 0, {
18009
- index: index2,
18009
+ index,
18010
18010
  count,
18011
18011
  start,
18012
18012
  subscriber
18013
18013
  });
18014
18014
  } else {
18015
18015
  do {
18016
- if (index2++ >= count) {
18016
+ if (index++ >= count) {
18017
18017
  subscriber.complete();
18018
18018
  break;
18019
18019
  }
@@ -18028,8 +18028,8 @@ var require_range = __commonJS((exports) => {
18028
18028
  }
18029
18029
  exports.range = range;
18030
18030
  function dispatch(state) {
18031
- var { start, index: index2, count, subscriber } = state;
18032
- if (index2 >= count) {
18031
+ var { start, index, count, subscriber } = state;
18032
+ if (index >= count) {
18033
18033
  subscriber.complete();
18034
18034
  return;
18035
18035
  }
@@ -18037,7 +18037,7 @@ var require_range = __commonJS((exports) => {
18037
18037
  if (subscriber.closed) {
18038
18038
  return;
18039
18039
  }
18040
- state.index = index2 + 1;
18040
+ state.index = index + 1;
18041
18041
  state.start = start + 1;
18042
18042
  this.schedule(state);
18043
18043
  }
@@ -18075,14 +18075,14 @@ var require_timer = __commonJS((exports) => {
18075
18075
  }
18076
18076
  exports.timer = timer;
18077
18077
  function dispatch(state) {
18078
- var { index: index2, period, subscriber } = state;
18079
- subscriber.next(index2);
18078
+ var { index, period, subscriber } = state;
18079
+ subscriber.next(index);
18080
18080
  if (subscriber.closed) {
18081
18081
  return;
18082
18082
  } else if (period === -1) {
18083
18083
  return subscriber.complete();
18084
18084
  }
18085
- state.index = index2 + 1;
18085
+ state.index = index + 1;
18086
18086
  this.schedule(state, period);
18087
18087
  }
18088
18088
  });
@@ -21274,27 +21274,54 @@ var NETWORK_ERROR_CODES = new Set([
21274
21274
  "ENETUNREACH",
21275
21275
  "EAI_FAIL"
21276
21276
  ]);
21277
- function isHtmlDocument(body) {
21278
- return /^\s*(<!doctype html|<html\b)/i.test(body);
21279
- }
21280
- function extractNetworkErrorCode(error) {
21281
- if (error === null || typeof error !== "object") {
21282
- return;
21283
- }
21284
- const err = error;
21285
- const code = typeof err.code === "string" ? err.code : undefined;
21286
- if (code && NETWORK_ERROR_CODES.has(code)) {
21287
- return code;
21288
- }
21289
- const cause = err.cause;
21290
- if (cause !== null && typeof cause === "object") {
21291
- const causeCode = cause.code;
21292
- if (typeof causeCode === "string" && NETWORK_ERROR_CODES.has(causeCode)) {
21293
- return causeCode;
21277
+ var TLS_ERROR_CODES = new Set([
21278
+ "SELF_SIGNED_CERT_IN_CHAIN",
21279
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
21280
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
21281
+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
21282
+ "UNABLE_TO_GET_ISSUER_CERT",
21283
+ "CERT_HAS_EXPIRED",
21284
+ "CERT_UNTRUSTED",
21285
+ "ERR_TLS_CERT_ALTNAME_INVALID"
21286
+ ]);
21287
+ 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.";
21288
+ 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.";
21289
+ function describeConnectivityError(error) {
21290
+ let current = error;
21291
+ for (let depth = 0;depth < 5 && current !== null && typeof current === "object"; depth++) {
21292
+ const cur = current;
21293
+ const code = typeof cur.code === "string" ? cur.code : undefined;
21294
+ const message = typeof cur.message === "string" ? cur.message : undefined;
21295
+ if (code && TLS_ERROR_CODES.has(code)) {
21296
+ return {
21297
+ code,
21298
+ kind: "tls",
21299
+ message: message ?? code,
21300
+ instructions: TLS_INSTRUCTIONS
21301
+ };
21302
+ }
21303
+ if (code && NETWORK_ERROR_CODES.has(code)) {
21304
+ return {
21305
+ code,
21306
+ kind: "network",
21307
+ message: message ?? code,
21308
+ instructions: NETWORK_INSTRUCTIONS
21309
+ };
21294
21310
  }
21311
+ current = cur.cause;
21295
21312
  }
21296
21313
  return;
21297
21314
  }
21315
+ function parseHttpStatusFromMessage(message) {
21316
+ const match = /^HTTP\s+(\d{3})(?::|\s|-|$)/i.exec(message.trim());
21317
+ if (!match)
21318
+ return;
21319
+ const status = Number(match[1]);
21320
+ return Number.isInteger(status) && status >= 100 && status <= 599 ? status : undefined;
21321
+ }
21322
+ function isHtmlDocument(body) {
21323
+ return /^\s*(<!doctype html|<html\b)/i.test(body);
21324
+ }
21298
21325
  function retryHintForRetryAfter(seconds) {
21299
21326
  if (seconds <= 1) {
21300
21327
  return "RetryAfter1Second";
@@ -21335,15 +21362,28 @@ function classifyError(status, error) {
21335
21362
  if (status !== undefined && status >= 500 && status < 600) {
21336
21363
  return { errorCode: "server_error", retry: "RetryLater" };
21337
21364
  }
21338
- if (extractNetworkErrorCode(error)) {
21339
- return { errorCode: "network_error", retry: "RetryLater" };
21365
+ const connectivity = describeConnectivityError(error);
21366
+ if (connectivity) {
21367
+ return {
21368
+ errorCode: "network_error",
21369
+ retry: connectivity.kind === "tls" ? "RetryWillNotFix" : "RetryLater"
21370
+ };
21340
21371
  }
21341
21372
  return { errorCode: "unknown_error", retry: "RetryWillNotFix" };
21342
21373
  }
21374
+ function formatHttpStatusMessage(status, rawMessage, extractedMessage, inferredStatus) {
21375
+ if (extractedMessage) {
21376
+ return `HTTP ${status}: ${extractedMessage}`;
21377
+ }
21378
+ return inferredStatus !== undefined ? rawMessage : `HTTP ${status}: ${rawMessage}`;
21379
+ }
21343
21380
  async function extractErrorDetails(error, options) {
21344
21381
  const err = error !== null && error !== undefined && typeof error === "object" ? error : {};
21345
21382
  const response = err.response;
21346
- const status = err.status ?? response?.status;
21383
+ const rawMessage = typeof err.message === "string" ? err.message : "Unknown error";
21384
+ const explicitStatus = err.status ?? response?.status;
21385
+ const inferredStatus = explicitStatus === undefined ? parseHttpStatusFromMessage(rawMessage) : undefined;
21386
+ const status = explicitStatus ?? inferredStatus;
21347
21387
  const isSuccessfulResponse = status !== undefined && status >= 200 && status < 300;
21348
21388
  let rawBody;
21349
21389
  let extractedMessage;
@@ -21378,7 +21418,6 @@ async function extractErrorDetails(error, options) {
21378
21418
  }
21379
21419
  }
21380
21420
  }
21381
- const rawMessage = typeof err.message === "string" ? err.message : "Unknown error";
21382
21421
  let message;
21383
21422
  let result = "Failure";
21384
21423
  const classification = classifyError(status, error);
@@ -21392,10 +21431,10 @@ async function extractErrorDetails(error, options) {
21392
21431
  } else if (status === 405) {
21393
21432
  message = DEFAULT_405;
21394
21433
  } else if (status === 400 || status === 422) {
21395
- message = extractedMessage ? `HTTP ${status}: ${extractedMessage}` : `HTTP ${status}: ${rawMessage}`;
21434
+ message = formatHttpStatusMessage(status, rawMessage, extractedMessage, inferredStatus);
21396
21435
  result = "ValidationError";
21397
21436
  } else if (status === 429) {
21398
- message = extractedMessage ? `HTTP ${status}: ${extractedMessage}` : `HTTP ${status}: ${rawMessage}`;
21437
+ message = formatHttpStatusMessage(status, rawMessage, extractedMessage, inferredStatus);
21399
21438
  } else if (extractedMessage) {
21400
21439
  if (isSuccessfulResponse && rawMessage !== "Unknown error") {
21401
21440
  message = rawMessage;
@@ -21403,7 +21442,9 @@ async function extractErrorDetails(error, options) {
21403
21442
  message = status ? `HTTP ${status}: ${extractedMessage}` : extractedMessage;
21404
21443
  }
21405
21444
  } else if (status) {
21406
- if (rawMessage === "Unknown error" && response) {
21445
+ if (inferredStatus !== undefined) {
21446
+ message = rawMessage;
21447
+ } else if (rawMessage === "Unknown error" && response) {
21407
21448
  const statusText = response.statusText;
21408
21449
  message = statusText ? `HTTP ${status} ${statusText}` : `HTTP ${status} - request failed`;
21409
21450
  } else {
@@ -21412,6 +21453,12 @@ async function extractErrorDetails(error, options) {
21412
21453
  } else {
21413
21454
  message = rawMessage;
21414
21455
  }
21456
+ if (status === undefined) {
21457
+ const connectivity = describeConnectivityError(error);
21458
+ if (connectivity && connectivity.message !== message && !message.includes(connectivity.message)) {
21459
+ message = `${message}: ${connectivity.message}`;
21460
+ }
21461
+ }
21415
21462
  let details = rawMessage;
21416
21463
  if (rawBody) {
21417
21464
  if (parsedBody) {
@@ -21575,6 +21622,7 @@ var CONSOLE_FALLBACK = {
21575
21622
  writeLog: (str) => process.stdout.write(str),
21576
21623
  capabilities: {
21577
21624
  isInteractive: false,
21625
+ canReadInput: false,
21578
21626
  supportsColor: false,
21579
21627
  outputWidth: 80
21580
21628
  }
@@ -26775,6 +26823,29 @@ function isPlainRecord(value) {
26775
26823
  const prototype = Object.getPrototypeOf(value);
26776
26824
  return prototype === Object.prototype || prototype === null;
26777
26825
  }
26826
+ function extractPagedRows(value) {
26827
+ if (Array.isArray(value) || !isPlainRecord(value))
26828
+ return null;
26829
+ const entries = Object.values(value);
26830
+ if (entries.length === 0)
26831
+ return null;
26832
+ let rows = null;
26833
+ let hasScalarSibling = false;
26834
+ for (const entry of entries) {
26835
+ if (Array.isArray(entry)) {
26836
+ if (rows !== null)
26837
+ return null;
26838
+ rows = entry;
26839
+ } else if (entry !== null && typeof entry === "object") {
26840
+ return null;
26841
+ } else {
26842
+ hasScalarSibling = true;
26843
+ }
26844
+ }
26845
+ if (rows === null || !hasScalarSibling)
26846
+ return null;
26847
+ return rows;
26848
+ }
26778
26849
  function toLowerCamelCaseKey(key) {
26779
26850
  if (!key)
26780
26851
  return key;
@@ -26839,7 +26910,8 @@ function printOutput(data, format = "json", logFn, asciiSafe = false) {
26839
26910
  break;
26840
26911
  case "plain": {
26841
26912
  if ("Data" in data && data.Data != null) {
26842
- const items = Array.isArray(data.Data) ? data.Data : [data.Data];
26913
+ const pagedRows = extractPagedRows(data.Data);
26914
+ const items = pagedRows ?? (Array.isArray(data.Data) ? data.Data : [data.Data]);
26843
26915
  items.forEach((item) => {
26844
26916
  const values = Object.values(item).map((v) => v ?? "").join("\t");
26845
26917
  logFn(values);
@@ -26851,10 +26923,13 @@ function printOutput(data, format = "json", logFn, asciiSafe = false) {
26851
26923
  break;
26852
26924
  }
26853
26925
  default: {
26854
- if ("Data" in data && data.Data != null && !(Array.isArray(data.Data) && data.Data.length === 0)) {
26926
+ const hasData = "Data" in data && data.Data != null;
26927
+ const pagedRows = hasData ? extractPagedRows(data.Data) : null;
26928
+ const rows = pagedRows ? pagedRows : Array.isArray(data.Data) ? data.Data : null;
26929
+ if (hasData && !(rows !== null && rows.length === 0)) {
26855
26930
  const logValue = data.Log;
26856
- if (Array.isArray(data.Data)) {
26857
- printResizableTable(data.Data, logFn, logValue);
26931
+ if (rows !== null) {
26932
+ printResizableTable(rows, logFn, logValue);
26858
26933
  } else {
26859
26934
  printVerticalTable(data.Data, logFn, logValue);
26860
26935
  }
@@ -27042,6 +27117,44 @@ function defaultErrorCodeForResult(result) {
27042
27117
  return "unknown_error";
27043
27118
  }
27044
27119
  }
27120
+ function parseHttpStatusFromMessage2(message) {
27121
+ const match = /^HTTP\s+(\d{3})(?::|\s|-|$)/i.exec(message.trim());
27122
+ if (!match)
27123
+ return;
27124
+ const status = Number(match[1]);
27125
+ return Number.isInteger(status) && status >= 100 && status <= 599 ? status : undefined;
27126
+ }
27127
+ function defaultErrorCodeForHttpStatus(status) {
27128
+ if (status === undefined)
27129
+ return;
27130
+ if (status === 400 || status === 409 || status === 422) {
27131
+ return "invalid_argument";
27132
+ }
27133
+ if (status === 401)
27134
+ return "authentication_required";
27135
+ if (status === 403)
27136
+ return "permission_denied";
27137
+ if (status === 404)
27138
+ return "not_found";
27139
+ if (status === 405)
27140
+ return "method_not_allowed";
27141
+ if (status === 408)
27142
+ return "timeout";
27143
+ if (status === 429)
27144
+ return "rate_limited";
27145
+ if (status >= 500 && status < 600)
27146
+ return "server_error";
27147
+ return;
27148
+ }
27149
+ function defaultErrorCodeForFailure(data) {
27150
+ if (data.Result === RESULTS.Failure) {
27151
+ const status = data.Context?.httpStatus ?? parseHttpStatusFromMessage2(data.Message);
27152
+ const errorCode = defaultErrorCodeForHttpStatus(status);
27153
+ if (errorCode)
27154
+ return errorCode;
27155
+ }
27156
+ return defaultErrorCodeForResult(data.Result);
27157
+ }
27045
27158
  function defaultRetryForErrorCode(errorCode) {
27046
27159
  switch (errorCode) {
27047
27160
  case "network_error":
@@ -27071,16 +27184,19 @@ var OutputFormatter;
27071
27184
  OutputFormatter.success = success;
27072
27185
  function error(data) {
27073
27186
  data.Log ??= getLogFilePath() || undefined;
27074
- data.ErrorCode ??= defaultErrorCodeForResult(data.Result);
27187
+ data.ErrorCode ??= defaultErrorCodeForFailure(data);
27075
27188
  data.Retry ??= defaultRetryForErrorCode(data.ErrorCode);
27076
27189
  process.exitCode = EXIT_CODES[data.Result] ?? 1;
27077
- telemetry.trackEvent(CommonTelemetryEvents.Error, {
27078
- result: data.Result,
27079
- errorCode: data.ErrorCode,
27080
- retry: data.Retry,
27081
- message: data.Message
27082
- });
27083
- logOutput(normalizeOutputKeys(data), getOutputFormat());
27190
+ const { SuppressTelemetry, ...envelope } = data;
27191
+ if (!SuppressTelemetry) {
27192
+ telemetry.trackEvent(CommonTelemetryEvents.Error, {
27193
+ result: data.Result,
27194
+ errorCode: data.ErrorCode,
27195
+ retry: data.Retry,
27196
+ message: data.Message
27197
+ });
27198
+ }
27199
+ logOutput(normalizeOutputKeys(envelope), getOutputFormat());
27084
27200
  }
27085
27201
  OutputFormatter.error = error;
27086
27202
  function emitList(code, items, opts) {
@@ -27362,1543 +27478,140 @@ var savedOriginalsSlot = singleton("ConsoleGuardOriginals");
27362
27478
  var DEFAULT_AUTH_TIMEOUT_MS = 5 * 60 * 1000;
27363
27479
  // ../common/src/interactivity-context.ts
27364
27480
  var modeSlot = singleton("InteractivityMode");
27365
- // ../../node_modules/jsonpath-plus/dist/index-node-esm.js
27366
- import vm from "vm";
27367
-
27368
- class Hooks {
27369
- add(name, callback, first) {
27370
- if (typeof arguments[0] != "string") {
27371
- for (let name2 in arguments[0]) {
27372
- this.add(name2, arguments[0][name2], arguments[1]);
27373
- }
27374
- } else {
27375
- (Array.isArray(name) ? name : [name]).forEach(function(name2) {
27376
- this[name2] = this[name2] || [];
27377
- if (callback) {
27378
- this[name2][first ? "unshift" : "push"](callback);
27379
- }
27380
- }, this);
27381
- }
27382
- }
27383
- run(name, env) {
27384
- this[name] = this[name] || [];
27385
- this[name].forEach(function(callback) {
27386
- callback.call(env && env.context ? env.context : env, env);
27387
- });
27481
+ // ../common/src/polling/format-utils.ts
27482
+ function msToDuration(ms) {
27483
+ if (!Number.isFinite(ms) || ms < 0) {
27484
+ return "00:00:00";
27388
27485
  }
27486
+ const totalSec = Math.floor(ms / 1000);
27487
+ const h = Math.floor(totalSec / 3600);
27488
+ const m = Math.floor(totalSec % 3600 / 60);
27489
+ const s = totalSec % 60;
27490
+ return [h, m, s].map((v) => String(v).padStart(2, "0")).join(":");
27389
27491
  }
27492
+ // ../common/src/polling/types.ts
27493
+ var PollOutcome = {
27494
+ Completed: "completed",
27495
+ Timeout: "timeout",
27496
+ Interrupted: "interrupted",
27497
+ Aborted: "aborted",
27498
+ Failed: "failed"
27499
+ };
27500
+ var ErrorDecision = {
27501
+ Abort: "abort"
27502
+ };
27503
+ var POLL_DEFAULTS = {
27504
+ intervalMs: 5000,
27505
+ timeoutMs: 1800000,
27506
+ maxConsecutiveErrors: 3,
27507
+ logIntervalMs: 30000,
27508
+ logPrefix: "wait"
27509
+ };
27510
+ var BACKOFF_DEFAULTS = {
27511
+ initialMs: 1000,
27512
+ multiplier: 2,
27513
+ maxMs: 30000,
27514
+ jitter: 0.5
27515
+ };
27516
+ var MIN_INTERVAL_MS = 100;
27390
27517
 
27391
- class Plugins {
27392
- constructor(jsep) {
27393
- this.jsep = jsep;
27394
- this.registered = {};
27395
- }
27396
- register(...plugins) {
27397
- plugins.forEach((plugin) => {
27398
- if (typeof plugin !== "object" || !plugin.name || !plugin.init) {
27399
- throw new Error("Invalid JSEP plugin format");
27400
- }
27401
- if (this.registered[plugin.name]) {
27402
- return;
27403
- }
27404
- plugin.init(this.jsep);
27405
- this.registered[plugin.name] = plugin;
27406
- });
27407
- }
27518
+ // ../common/src/polling/poll-failure-mapping.ts
27519
+ var REASON_BY_OUTCOME = {
27520
+ [PollOutcome.Timeout]: "poll_timeout",
27521
+ [PollOutcome.Failed]: "poll_failed",
27522
+ [PollOutcome.Interrupted]: "poll_failed",
27523
+ [PollOutcome.Aborted]: "poll_aborted"
27524
+ };
27525
+ function mapPollFailure(pollResult, label) {
27526
+ const outcome = pollResult.outcome;
27527
+ const errMsg = pollResult.error?.message ?? "too many consecutive errors";
27528
+ const messageByOutcome = {
27529
+ [PollOutcome.Timeout]: `${label} polling timed out`,
27530
+ [PollOutcome.Failed]: `${label} polling failed: ${errMsg}`,
27531
+ [PollOutcome.Interrupted]: `${label} polling was interrupted`,
27532
+ [PollOutcome.Aborted]: `${label} polling was aborted`
27533
+ };
27534
+ return {
27535
+ reason: REASON_BY_OUTCOME[outcome],
27536
+ message: messageByOutcome[outcome],
27537
+ exitCode: outcome === PollOutcome.Timeout ? 2 : 1
27538
+ };
27408
27539
  }
27409
-
27410
- class Jsep {
27411
- static get version() {
27412
- return "1.4.0";
27413
- }
27414
- static toString() {
27415
- return "JavaScript Expression Parser (JSEP) v" + Jsep.version;
27416
- }
27417
- static addUnaryOp(op_name) {
27418
- Jsep.max_unop_len = Math.max(op_name.length, Jsep.max_unop_len);
27419
- Jsep.unary_ops[op_name] = 1;
27420
- return Jsep;
27421
- }
27422
- static addBinaryOp(op_name, precedence, isRightAssociative) {
27423
- Jsep.max_binop_len = Math.max(op_name.length, Jsep.max_binop_len);
27424
- Jsep.binary_ops[op_name] = precedence;
27425
- if (isRightAssociative) {
27426
- Jsep.right_associative.add(op_name);
27427
- } else {
27428
- Jsep.right_associative.delete(op_name);
27429
- }
27430
- return Jsep;
27431
- }
27432
- static addIdentifierChar(char) {
27433
- Jsep.additional_identifier_chars.add(char);
27434
- return Jsep;
27435
- }
27436
- static addLiteral(literal_name, literal_value) {
27437
- Jsep.literals[literal_name] = literal_value;
27438
- return Jsep;
27439
- }
27440
- static removeUnaryOp(op_name) {
27441
- delete Jsep.unary_ops[op_name];
27442
- if (op_name.length === Jsep.max_unop_len) {
27443
- Jsep.max_unop_len = Jsep.getMaxKeyLen(Jsep.unary_ops);
27444
- }
27445
- return Jsep;
27446
- }
27447
- static removeAllUnaryOps() {
27448
- Jsep.unary_ops = {};
27449
- Jsep.max_unop_len = 0;
27450
- return Jsep;
27451
- }
27452
- static removeIdentifierChar(char) {
27453
- Jsep.additional_identifier_chars.delete(char);
27454
- return Jsep;
27455
- }
27456
- static removeBinaryOp(op_name) {
27457
- delete Jsep.binary_ops[op_name];
27458
- if (op_name.length === Jsep.max_binop_len) {
27459
- Jsep.max_binop_len = Jsep.getMaxKeyLen(Jsep.binary_ops);
27460
- }
27461
- Jsep.right_associative.delete(op_name);
27462
- return Jsep;
27463
- }
27464
- static removeAllBinaryOps() {
27465
- Jsep.binary_ops = {};
27466
- Jsep.max_binop_len = 0;
27467
- return Jsep;
27468
- }
27469
- static removeLiteral(literal_name) {
27470
- delete Jsep.literals[literal_name];
27471
- return Jsep;
27472
- }
27473
- static removeAllLiterals() {
27474
- Jsep.literals = {};
27475
- return Jsep;
27476
- }
27477
- get char() {
27478
- return this.expr.charAt(this.index);
27479
- }
27480
- get code() {
27481
- return this.expr.charCodeAt(this.index);
27482
- }
27483
- constructor(expr) {
27484
- this.expr = expr;
27485
- this.index = 0;
27486
- }
27487
- static parse(expr) {
27488
- return new Jsep(expr).parse();
27489
- }
27490
- static getMaxKeyLen(obj) {
27491
- return Math.max(0, ...Object.keys(obj).map((k) => k.length));
27492
- }
27493
- static isDecimalDigit(ch) {
27494
- return ch >= 48 && ch <= 57;
27495
- }
27496
- static binaryPrecedence(op_val) {
27497
- return Jsep.binary_ops[op_val] || 0;
27498
- }
27499
- static isIdentifierStart(ch) {
27500
- 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));
27501
- }
27502
- static isIdentifierPart(ch) {
27503
- return Jsep.isIdentifierStart(ch) || Jsep.isDecimalDigit(ch);
27504
- }
27505
- throwError(message) {
27506
- const error = new Error(message + " at character " + this.index);
27507
- error.index = this.index;
27508
- error.description = message;
27509
- throw error;
27510
- }
27511
- runHook(name, node) {
27512
- if (Jsep.hooks[name]) {
27513
- const env = {
27514
- context: this,
27515
- node
27516
- };
27517
- Jsep.hooks.run(name, env);
27518
- return env.node;
27519
- }
27520
- return node;
27521
- }
27522
- searchHook(name) {
27523
- if (Jsep.hooks[name]) {
27524
- const env = {
27525
- context: this
27526
- };
27527
- Jsep.hooks[name].find(function(callback) {
27528
- callback.call(env.context, env);
27529
- return env.node;
27530
- });
27531
- return env.node;
27532
- }
27533
- }
27534
- gobbleSpaces() {
27535
- let ch = this.code;
27536
- while (ch === Jsep.SPACE_CODE || ch === Jsep.TAB_CODE || ch === Jsep.LF_CODE || ch === Jsep.CR_CODE) {
27537
- ch = this.expr.charCodeAt(++this.index);
27538
- }
27539
- this.runHook("gobble-spaces");
27540
- }
27541
- parse() {
27542
- this.runHook("before-all");
27543
- const nodes = this.gobbleExpressions();
27544
- const node = nodes.length === 1 ? nodes[0] : {
27545
- type: Jsep.COMPOUND,
27546
- body: nodes
27547
- };
27548
- return this.runHook("after-all", node);
27540
+ // ../common/src/polling/poll-until.ts
27541
+ function resolveIntervalFn(options) {
27542
+ if (typeof options.intervalMs === "function") {
27543
+ return options.intervalMs;
27549
27544
  }
27550
- gobbleExpressions(untilICode) {
27551
- let nodes = [], ch_i, node;
27552
- while (this.index < this.expr.length) {
27553
- ch_i = this.code;
27554
- if (ch_i === Jsep.SEMCOL_CODE || ch_i === Jsep.COMMA_CODE) {
27555
- this.index++;
27556
- } else {
27557
- if (node = this.gobbleExpression()) {
27558
- nodes.push(node);
27559
- } else if (this.index < this.expr.length) {
27560
- if (ch_i === untilICode) {
27561
- break;
27562
- }
27563
- this.throwError('Unexpected "' + this.char + '"');
27564
- }
27565
- }
27545
+ const staticInterval = options.intervalMs ?? POLL_DEFAULTS.intervalMs;
27546
+ return () => staticInterval;
27547
+ }
27548
+ function resolveBackoffFn(options) {
27549
+ if (!options.backoff)
27550
+ return;
27551
+ const config = options.backoff === true ? { ...BACKOFF_DEFAULTS } : {
27552
+ initialMs: options.backoff.initialMs ?? BACKOFF_DEFAULTS.initialMs,
27553
+ multiplier: options.backoff.multiplier ?? BACKOFF_DEFAULTS.multiplier,
27554
+ maxMs: options.backoff.maxMs ?? BACKOFF_DEFAULTS.maxMs,
27555
+ jitter: Math.min(1, Math.max(0, options.backoff.jitter ?? BACKOFF_DEFAULTS.jitter))
27556
+ };
27557
+ return (errorCount) => {
27558
+ const exponent = Math.min(errorCount - 1, 30);
27559
+ const raw = Math.min(config.initialMs * config.multiplier ** exponent, config.maxMs);
27560
+ if (config.jitter > 0) {
27561
+ const jitterAmount = raw * config.jitter;
27562
+ return raw - jitterAmount * Math.random();
27566
27563
  }
27567
- return nodes;
27568
- }
27569
- gobbleExpression() {
27570
- const node = this.searchHook("gobble-expression") || this.gobbleBinaryExpression();
27571
- this.gobbleSpaces();
27572
- return this.runHook("after-expression", node);
27573
- }
27574
- gobbleBinaryOp() {
27575
- this.gobbleSpaces();
27576
- let to_check = this.expr.substr(this.index, Jsep.max_binop_len);
27577
- let tc_len = to_check.length;
27578
- while (tc_len > 0) {
27579
- 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)))) {
27580
- this.index += tc_len;
27581
- return to_check;
27582
- }
27583
- to_check = to_check.substr(0, --tc_len);
27564
+ return raw;
27565
+ };
27566
+ }
27567
+ function clampInterval(raw, label, prefix) {
27568
+ if (!Number.isFinite(raw) || Number.isNaN(raw)) {
27569
+ if (label) {
27570
+ logger.warn(`[${prefix}] ${label} — intervalMs returned ${raw}, falling back to ${POLL_DEFAULTS.intervalMs}ms`);
27584
27571
  }
27585
- return false;
27572
+ return POLL_DEFAULTS.intervalMs;
27586
27573
  }
27587
- gobbleBinaryExpression() {
27588
- let node, biop, prec, stack, biop_info, left, right, i, cur_biop;
27589
- left = this.gobbleToken();
27590
- if (!left) {
27591
- return left;
27592
- }
27593
- biop = this.gobbleBinaryOp();
27594
- if (!biop) {
27595
- return left;
27596
- }
27597
- biop_info = {
27598
- value: biop,
27599
- prec: Jsep.binaryPrecedence(biop),
27600
- right_a: Jsep.right_associative.has(biop)
27601
- };
27602
- right = this.gobbleToken();
27603
- if (!right) {
27604
- this.throwError("Expected expression after " + biop);
27605
- }
27606
- stack = [left, biop_info, right];
27607
- while (biop = this.gobbleBinaryOp()) {
27608
- prec = Jsep.binaryPrecedence(biop);
27609
- if (prec === 0) {
27610
- this.index -= biop.length;
27611
- break;
27612
- }
27613
- biop_info = {
27614
- value: biop,
27615
- prec,
27616
- right_a: Jsep.right_associative.has(biop)
27617
- };
27618
- cur_biop = biop;
27619
- const comparePrev = (prev) => biop_info.right_a && prev.right_a ? prec > prev.prec : prec <= prev.prec;
27620
- while (stack.length > 2 && comparePrev(stack[stack.length - 2])) {
27621
- right = stack.pop();
27622
- biop = stack.pop().value;
27623
- left = stack.pop();
27624
- node = {
27625
- type: Jsep.BINARY_EXP,
27626
- operator: biop,
27627
- left,
27628
- right
27629
- };
27630
- stack.push(node);
27631
- }
27632
- node = this.gobbleToken();
27633
- if (!node) {
27634
- this.throwError("Expected expression after " + cur_biop);
27635
- }
27636
- stack.push(biop_info, node);
27637
- }
27638
- i = stack.length - 1;
27639
- node = stack[i];
27640
- while (i > 1) {
27641
- node = {
27642
- type: Jsep.BINARY_EXP,
27643
- operator: stack[i - 1].value,
27644
- left: stack[i - 2],
27645
- right: node
27646
- };
27647
- i -= 2;
27648
- }
27649
- return node;
27650
- }
27651
- gobbleToken() {
27652
- let ch, to_check, tc_len, node;
27653
- this.gobbleSpaces();
27654
- node = this.searchHook("gobble-token");
27655
- if (node) {
27656
- return this.runHook("after-token", node);
27657
- }
27658
- ch = this.code;
27659
- if (Jsep.isDecimalDigit(ch) || ch === Jsep.PERIOD_CODE) {
27660
- return this.gobbleNumericLiteral();
27661
- }
27662
- if (ch === Jsep.SQUOTE_CODE || ch === Jsep.DQUOTE_CODE) {
27663
- node = this.gobbleStringLiteral();
27664
- } else if (ch === Jsep.OBRACK_CODE) {
27665
- node = this.gobbleArray();
27666
- } else {
27667
- to_check = this.expr.substr(this.index, Jsep.max_unop_len);
27668
- tc_len = to_check.length;
27669
- while (tc_len > 0) {
27670
- 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)))) {
27671
- this.index += tc_len;
27672
- const argument = this.gobbleToken();
27673
- if (!argument) {
27674
- this.throwError("missing unaryOp argument");
27675
- }
27676
- return this.runHook("after-token", {
27677
- type: Jsep.UNARY_EXP,
27678
- operator: to_check,
27679
- argument,
27680
- prefix: true
27681
- });
27682
- }
27683
- to_check = to_check.substr(0, --tc_len);
27684
- }
27685
- if (Jsep.isIdentifierStart(ch)) {
27686
- node = this.gobbleIdentifier();
27687
- if (Jsep.literals.hasOwnProperty(node.name)) {
27688
- node = {
27689
- type: Jsep.LITERAL,
27690
- value: Jsep.literals[node.name],
27691
- raw: node.name
27692
- };
27693
- } else if (node.name === Jsep.this_str) {
27694
- node = {
27695
- type: Jsep.THIS_EXP
27696
- };
27697
- }
27698
- } else if (ch === Jsep.OPAREN_CODE) {
27699
- node = this.gobbleGroup();
27700
- }
27701
- }
27702
- if (!node) {
27703
- return this.runHook("after-token", false);
27574
+ if (raw < MIN_INTERVAL_MS) {
27575
+ if (label) {
27576
+ logger.warn(`[${prefix}] ${label} — intervalMs ${raw}ms clamped to minimum ${MIN_INTERVAL_MS}ms`);
27704
27577
  }
27705
- node = this.gobbleTokenProperty(node);
27706
- return this.runHook("after-token", node);
27578
+ return MIN_INTERVAL_MS;
27707
27579
  }
27708
- gobbleTokenProperty(node) {
27709
- this.gobbleSpaces();
27710
- let ch = this.code;
27711
- while (ch === Jsep.PERIOD_CODE || ch === Jsep.OBRACK_CODE || ch === Jsep.OPAREN_CODE || ch === Jsep.QUMARK_CODE) {
27712
- let optional;
27713
- if (ch === Jsep.QUMARK_CODE) {
27714
- if (this.expr.charCodeAt(this.index + 1) !== Jsep.PERIOD_CODE) {
27715
- break;
27716
- }
27717
- optional = true;
27718
- this.index += 2;
27719
- this.gobbleSpaces();
27720
- ch = this.code;
27721
- }
27722
- this.index++;
27723
- if (ch === Jsep.OBRACK_CODE) {
27724
- node = {
27725
- type: Jsep.MEMBER_EXP,
27726
- computed: true,
27727
- object: node,
27728
- property: this.gobbleExpression()
27729
- };
27730
- if (!node.property) {
27731
- this.throwError('Unexpected "' + this.char + '"');
27732
- }
27733
- this.gobbleSpaces();
27734
- ch = this.code;
27735
- if (ch !== Jsep.CBRACK_CODE) {
27736
- this.throwError("Unclosed [");
27737
- }
27738
- this.index++;
27739
- } else if (ch === Jsep.OPAREN_CODE) {
27740
- node = {
27741
- type: Jsep.CALL_EXP,
27742
- arguments: this.gobbleArguments(Jsep.CPAREN_CODE),
27743
- callee: node
27744
- };
27745
- } else if (ch === Jsep.PERIOD_CODE || optional) {
27746
- if (optional) {
27747
- this.index--;
27748
- }
27749
- this.gobbleSpaces();
27750
- node = {
27751
- type: Jsep.MEMBER_EXP,
27752
- computed: false,
27753
- object: node,
27754
- property: this.gobbleIdentifier()
27755
- };
27756
- }
27757
- if (optional) {
27758
- node.optional = true;
27759
- }
27760
- this.gobbleSpaces();
27761
- ch = this.code;
27762
- }
27763
- return node;
27580
+ return raw;
27581
+ }
27582
+ function abortError(signal) {
27583
+ const reason = signal.reason;
27584
+ if (reason instanceof Error && reason.name === "AbortError") {
27585
+ return reason;
27764
27586
  }
27765
- gobbleNumericLiteral() {
27766
- let number = "", ch, chCode;
27767
- while (Jsep.isDecimalDigit(this.code)) {
27768
- number += this.expr.charAt(this.index++);
27587
+ const msg = reason instanceof Error ? reason.message : typeof reason === "string" || typeof reason === "number" ? String(reason) : "Aborted";
27588
+ const err = new Error(msg);
27589
+ err.name = "AbortError";
27590
+ return err;
27591
+ }
27592
+ function interruptibleSleep(ms, signal) {
27593
+ return new Promise((resolve2, reject) => {
27594
+ if (signal?.aborted) {
27595
+ reject(abortError(signal));
27596
+ return;
27769
27597
  }
27770
- if (this.code === Jsep.PERIOD_CODE) {
27771
- number += this.expr.charAt(this.index++);
27772
- while (Jsep.isDecimalDigit(this.code)) {
27773
- number += this.expr.charAt(this.index++);
27598
+ let onAbort;
27599
+ const cleanup = () => {
27600
+ if (onAbort) {
27601
+ signal?.removeEventListener("abort", onAbort);
27774
27602
  }
27775
- }
27776
- ch = this.char;
27777
- if (ch === "e" || ch === "E") {
27778
- number += this.expr.charAt(this.index++);
27779
- ch = this.char;
27780
- if (ch === "+" || ch === "-") {
27781
- number += this.expr.charAt(this.index++);
27782
- }
27783
- while (Jsep.isDecimalDigit(this.code)) {
27784
- number += this.expr.charAt(this.index++);
27785
- }
27786
- if (!Jsep.isDecimalDigit(this.expr.charCodeAt(this.index - 1))) {
27787
- this.throwError("Expected exponent (" + number + this.char + ")");
27788
- }
27789
- }
27790
- chCode = this.code;
27791
- if (Jsep.isIdentifierStart(chCode)) {
27792
- this.throwError("Variable names cannot start with a number (" + number + this.char + ")");
27793
- } else if (chCode === Jsep.PERIOD_CODE || number.length === 1 && number.charCodeAt(0) === Jsep.PERIOD_CODE) {
27794
- this.throwError("Unexpected period");
27795
- }
27796
- return {
27797
- type: Jsep.LITERAL,
27798
- value: parseFloat(number),
27799
- raw: number
27800
- };
27801
- }
27802
- gobbleStringLiteral() {
27803
- let str = "";
27804
- const startIndex = this.index;
27805
- const quote = this.expr.charAt(this.index++);
27806
- let closed = false;
27807
- while (this.index < this.expr.length) {
27808
- let ch = this.expr.charAt(this.index++);
27809
- if (ch === quote) {
27810
- closed = true;
27811
- break;
27812
- } else if (ch === "\\") {
27813
- ch = this.expr.charAt(this.index++);
27814
- switch (ch) {
27815
- case "n":
27816
- str += `
27817
- `;
27818
- break;
27819
- case "r":
27820
- str += "\r";
27821
- break;
27822
- case "t":
27823
- str += "\t";
27824
- break;
27825
- case "b":
27826
- str += "\b";
27827
- break;
27828
- case "f":
27829
- str += "\f";
27830
- break;
27831
- case "v":
27832
- str += "\v";
27833
- break;
27834
- default:
27835
- str += ch;
27836
- }
27837
- } else {
27838
- str += ch;
27839
- }
27840
- }
27841
- if (!closed) {
27842
- this.throwError('Unclosed quote after "' + str + '"');
27843
- }
27844
- return {
27845
- type: Jsep.LITERAL,
27846
- value: str,
27847
- raw: this.expr.substring(startIndex, this.index)
27848
- };
27849
- }
27850
- gobbleIdentifier() {
27851
- let ch = this.code, start = this.index;
27852
- if (Jsep.isIdentifierStart(ch)) {
27853
- this.index++;
27854
- } else {
27855
- this.throwError("Unexpected " + this.char);
27856
- }
27857
- while (this.index < this.expr.length) {
27858
- ch = this.code;
27859
- if (Jsep.isIdentifierPart(ch)) {
27860
- this.index++;
27861
- } else {
27862
- break;
27863
- }
27864
- }
27865
- return {
27866
- type: Jsep.IDENTIFIER,
27867
- name: this.expr.slice(start, this.index)
27868
- };
27869
- }
27870
- gobbleArguments(termination) {
27871
- const args = [];
27872
- let closed = false;
27873
- let separator_count = 0;
27874
- while (this.index < this.expr.length) {
27875
- this.gobbleSpaces();
27876
- let ch_i = this.code;
27877
- if (ch_i === termination) {
27878
- closed = true;
27879
- this.index++;
27880
- if (termination === Jsep.CPAREN_CODE && separator_count && separator_count >= args.length) {
27881
- this.throwError("Unexpected token " + String.fromCharCode(termination));
27882
- }
27883
- break;
27884
- } else if (ch_i === Jsep.COMMA_CODE) {
27885
- this.index++;
27886
- separator_count++;
27887
- if (separator_count !== args.length) {
27888
- if (termination === Jsep.CPAREN_CODE) {
27889
- this.throwError("Unexpected token ,");
27890
- } else if (termination === Jsep.CBRACK_CODE) {
27891
- for (let arg = args.length;arg < separator_count; arg++) {
27892
- args.push(null);
27893
- }
27894
- }
27895
- }
27896
- } else if (args.length !== separator_count && separator_count !== 0) {
27897
- this.throwError("Expected comma");
27898
- } else {
27899
- const node = this.gobbleExpression();
27900
- if (!node || node.type === Jsep.COMPOUND) {
27901
- this.throwError("Expected comma");
27902
- }
27903
- args.push(node);
27904
- }
27905
- }
27906
- if (!closed) {
27907
- this.throwError("Expected " + String.fromCharCode(termination));
27908
- }
27909
- return args;
27910
- }
27911
- gobbleGroup() {
27912
- this.index++;
27913
- let nodes = this.gobbleExpressions(Jsep.CPAREN_CODE);
27914
- if (this.code === Jsep.CPAREN_CODE) {
27915
- this.index++;
27916
- if (nodes.length === 1) {
27917
- return nodes[0];
27918
- } else if (!nodes.length) {
27919
- return false;
27920
- } else {
27921
- return {
27922
- type: Jsep.SEQUENCE_EXP,
27923
- expressions: nodes
27924
- };
27925
- }
27926
- } else {
27927
- this.throwError("Unclosed (");
27928
- }
27929
- }
27930
- gobbleArray() {
27931
- this.index++;
27932
- return {
27933
- type: Jsep.ARRAY_EXP,
27934
- elements: this.gobbleArguments(Jsep.CBRACK_CODE)
27935
- };
27936
- }
27937
- }
27938
- var hooks = new Hooks;
27939
- Object.assign(Jsep, {
27940
- hooks,
27941
- plugins: new Plugins(Jsep),
27942
- COMPOUND: "Compound",
27943
- SEQUENCE_EXP: "SequenceExpression",
27944
- IDENTIFIER: "Identifier",
27945
- MEMBER_EXP: "MemberExpression",
27946
- LITERAL: "Literal",
27947
- THIS_EXP: "ThisExpression",
27948
- CALL_EXP: "CallExpression",
27949
- UNARY_EXP: "UnaryExpression",
27950
- BINARY_EXP: "BinaryExpression",
27951
- ARRAY_EXP: "ArrayExpression",
27952
- TAB_CODE: 9,
27953
- LF_CODE: 10,
27954
- CR_CODE: 13,
27955
- SPACE_CODE: 32,
27956
- PERIOD_CODE: 46,
27957
- COMMA_CODE: 44,
27958
- SQUOTE_CODE: 39,
27959
- DQUOTE_CODE: 34,
27960
- OPAREN_CODE: 40,
27961
- CPAREN_CODE: 41,
27962
- OBRACK_CODE: 91,
27963
- CBRACK_CODE: 93,
27964
- QUMARK_CODE: 63,
27965
- SEMCOL_CODE: 59,
27966
- COLON_CODE: 58,
27967
- unary_ops: {
27968
- "-": 1,
27969
- "!": 1,
27970
- "~": 1,
27971
- "+": 1
27972
- },
27973
- binary_ops: {
27974
- "||": 1,
27975
- "??": 1,
27976
- "&&": 2,
27977
- "|": 3,
27978
- "^": 4,
27979
- "&": 5,
27980
- "==": 6,
27981
- "!=": 6,
27982
- "===": 6,
27983
- "!==": 6,
27984
- "<": 7,
27985
- ">": 7,
27986
- "<=": 7,
27987
- ">=": 7,
27988
- "<<": 8,
27989
- ">>": 8,
27990
- ">>>": 8,
27991
- "+": 9,
27992
- "-": 9,
27993
- "*": 10,
27994
- "/": 10,
27995
- "%": 10,
27996
- "**": 11
27997
- },
27998
- right_associative: new Set(["**"]),
27999
- additional_identifier_chars: new Set(["$", "_"]),
28000
- literals: {
28001
- true: true,
28002
- false: false,
28003
- null: null
28004
- },
28005
- this_str: "this"
28006
- });
28007
- Jsep.max_unop_len = Jsep.getMaxKeyLen(Jsep.unary_ops);
28008
- Jsep.max_binop_len = Jsep.getMaxKeyLen(Jsep.binary_ops);
28009
- var jsep = (expr) => new Jsep(expr).parse();
28010
- var stdClassProps = Object.getOwnPropertyNames(class Test {
28011
- });
28012
- Object.getOwnPropertyNames(Jsep).filter((prop) => !stdClassProps.includes(prop) && jsep[prop] === undefined).forEach((m) => {
28013
- jsep[m] = Jsep[m];
28014
- });
28015
- jsep.Jsep = Jsep;
28016
- var CONDITIONAL_EXP = "ConditionalExpression";
28017
- var ternary = {
28018
- name: "ternary",
28019
- init(jsep2) {
28020
- jsep2.hooks.add("after-expression", function gobbleTernary(env) {
28021
- if (env.node && this.code === jsep2.QUMARK_CODE) {
28022
- this.index++;
28023
- const test = env.node;
28024
- const consequent = this.gobbleExpression();
28025
- if (!consequent) {
28026
- this.throwError("Expected expression");
28027
- }
28028
- this.gobbleSpaces();
28029
- if (this.code === jsep2.COLON_CODE) {
28030
- this.index++;
28031
- const alternate = this.gobbleExpression();
28032
- if (!alternate) {
28033
- this.throwError("Expected expression");
28034
- }
28035
- env.node = {
28036
- type: CONDITIONAL_EXP,
28037
- test,
28038
- consequent,
28039
- alternate
28040
- };
28041
- if (test.operator && jsep2.binary_ops[test.operator] <= 0.9) {
28042
- let newTest = test;
28043
- while (newTest.right.operator && jsep2.binary_ops[newTest.right.operator] <= 0.9) {
28044
- newTest = newTest.right;
28045
- }
28046
- env.node.test = newTest.right;
28047
- newTest.right = env.node;
28048
- env.node = test;
28049
- }
28050
- } else {
28051
- this.throwError("Expected :");
28052
- }
28053
- }
28054
- });
28055
- }
28056
- };
28057
- jsep.plugins.register(ternary);
28058
- var FSLASH_CODE = 47;
28059
- var BSLASH_CODE = 92;
28060
- var index = {
28061
- name: "regex",
28062
- init(jsep2) {
28063
- jsep2.hooks.add("gobble-token", function gobbleRegexLiteral(env) {
28064
- if (this.code === FSLASH_CODE) {
28065
- const patternIndex = ++this.index;
28066
- let inCharSet = false;
28067
- while (this.index < this.expr.length) {
28068
- if (this.code === FSLASH_CODE && !inCharSet) {
28069
- const pattern = this.expr.slice(patternIndex, this.index);
28070
- let flags = "";
28071
- while (++this.index < this.expr.length) {
28072
- const code = this.code;
28073
- if (code >= 97 && code <= 122 || code >= 65 && code <= 90 || code >= 48 && code <= 57) {
28074
- flags += this.char;
28075
- } else {
28076
- break;
28077
- }
28078
- }
28079
- let value;
28080
- try {
28081
- value = new RegExp(pattern, flags);
28082
- } catch (e) {
28083
- this.throwError(e.message);
28084
- }
28085
- env.node = {
28086
- type: jsep2.LITERAL,
28087
- value,
28088
- raw: this.expr.slice(patternIndex - 1, this.index)
28089
- };
28090
- env.node = this.gobbleTokenProperty(env.node);
28091
- return env.node;
28092
- }
28093
- if (this.code === jsep2.OBRACK_CODE) {
28094
- inCharSet = true;
28095
- } else if (inCharSet && this.code === jsep2.CBRACK_CODE) {
28096
- inCharSet = false;
28097
- }
28098
- this.index += this.code === BSLASH_CODE ? 2 : 1;
28099
- }
28100
- this.throwError("Unclosed Regex");
28101
- }
28102
- });
28103
- }
28104
- };
28105
- var PLUS_CODE = 43;
28106
- var MINUS_CODE = 45;
28107
- var plugin = {
28108
- name: "assignment",
28109
- assignmentOperators: new Set(["=", "*=", "**=", "/=", "%=", "+=", "-=", "<<=", ">>=", ">>>=", "&=", "^=", "|=", "||=", "&&=", "??="]),
28110
- updateOperators: [PLUS_CODE, MINUS_CODE],
28111
- assignmentPrecedence: 0.9,
28112
- init(jsep2) {
28113
- const updateNodeTypes = [jsep2.IDENTIFIER, jsep2.MEMBER_EXP];
28114
- plugin.assignmentOperators.forEach((op) => jsep2.addBinaryOp(op, plugin.assignmentPrecedence, true));
28115
- jsep2.hooks.add("gobble-token", function gobbleUpdatePrefix(env) {
28116
- const code = this.code;
28117
- if (plugin.updateOperators.some((c) => c === code && c === this.expr.charCodeAt(this.index + 1))) {
28118
- this.index += 2;
28119
- env.node = {
28120
- type: "UpdateExpression",
28121
- operator: code === PLUS_CODE ? "++" : "--",
28122
- argument: this.gobbleTokenProperty(this.gobbleIdentifier()),
28123
- prefix: true
28124
- };
28125
- if (!env.node.argument || !updateNodeTypes.includes(env.node.argument.type)) {
28126
- this.throwError(`Unexpected ${env.node.operator}`);
28127
- }
28128
- }
28129
- });
28130
- jsep2.hooks.add("after-token", function gobbleUpdatePostfix(env) {
28131
- if (env.node) {
28132
- const code = this.code;
28133
- if (plugin.updateOperators.some((c) => c === code && c === this.expr.charCodeAt(this.index + 1))) {
28134
- if (!updateNodeTypes.includes(env.node.type)) {
28135
- this.throwError(`Unexpected ${env.node.operator}`);
28136
- }
28137
- this.index += 2;
28138
- env.node = {
28139
- type: "UpdateExpression",
28140
- operator: code === PLUS_CODE ? "++" : "--",
28141
- argument: env.node,
28142
- prefix: false
28143
- };
28144
- }
28145
- }
28146
- });
28147
- jsep2.hooks.add("after-expression", function gobbleAssignment(env) {
28148
- if (env.node) {
28149
- updateBinariesToAssignments(env.node);
28150
- }
28151
- });
28152
- function updateBinariesToAssignments(node) {
28153
- if (plugin.assignmentOperators.has(node.operator)) {
28154
- node.type = "AssignmentExpression";
28155
- updateBinariesToAssignments(node.left);
28156
- updateBinariesToAssignments(node.right);
28157
- } else if (!node.operator) {
28158
- Object.values(node).forEach((val) => {
28159
- if (val && typeof val === "object") {
28160
- updateBinariesToAssignments(val);
28161
- }
28162
- });
28163
- }
28164
- }
28165
- }
28166
- };
28167
- jsep.plugins.register(index, plugin);
28168
- jsep.addUnaryOp("typeof");
28169
- jsep.addUnaryOp("void");
28170
- jsep.addLiteral("null", null);
28171
- jsep.addLiteral("undefined", undefined);
28172
- var BLOCKED_PROTO_PROPERTIES = new Set(["constructor", "__proto__", "__defineGetter__", "__defineSetter__", "__lookupGetter__", "__lookupSetter__"]);
28173
- var SafeEval = {
28174
- evalAst(ast, subs) {
28175
- switch (ast.type) {
28176
- case "BinaryExpression":
28177
- case "LogicalExpression":
28178
- return SafeEval.evalBinaryExpression(ast, subs);
28179
- case "Compound":
28180
- return SafeEval.evalCompound(ast, subs);
28181
- case "ConditionalExpression":
28182
- return SafeEval.evalConditionalExpression(ast, subs);
28183
- case "Identifier":
28184
- return SafeEval.evalIdentifier(ast, subs);
28185
- case "Literal":
28186
- return SafeEval.evalLiteral(ast, subs);
28187
- case "MemberExpression":
28188
- return SafeEval.evalMemberExpression(ast, subs);
28189
- case "UnaryExpression":
28190
- return SafeEval.evalUnaryExpression(ast, subs);
28191
- case "ArrayExpression":
28192
- return SafeEval.evalArrayExpression(ast, subs);
28193
- case "CallExpression":
28194
- return SafeEval.evalCallExpression(ast, subs);
28195
- case "AssignmentExpression":
28196
- return SafeEval.evalAssignmentExpression(ast, subs);
28197
- default:
28198
- throw SyntaxError("Unexpected expression", ast);
28199
- }
28200
- },
28201
- evalBinaryExpression(ast, subs) {
28202
- const result = {
28203
- "||": (a, b) => a || b(),
28204
- "&&": (a, b) => a && b(),
28205
- "|": (a, b) => a | b(),
28206
- "^": (a, b) => a ^ b(),
28207
- "&": (a, b) => a & b(),
28208
- "==": (a, b) => a == b(),
28209
- "!=": (a, b) => a != b(),
28210
- "===": (a, b) => a === b(),
28211
- "!==": (a, b) => a !== b(),
28212
- "<": (a, b) => a < b(),
28213
- ">": (a, b) => a > b(),
28214
- "<=": (a, b) => a <= b(),
28215
- ">=": (a, b) => a >= b(),
28216
- "<<": (a, b) => a << b(),
28217
- ">>": (a, b) => a >> b(),
28218
- ">>>": (a, b) => a >>> b(),
28219
- "+": (a, b) => a + b(),
28220
- "-": (a, b) => a - b(),
28221
- "*": (a, b) => a * b(),
28222
- "/": (a, b) => a / b(),
28223
- "%": (a, b) => a % b()
28224
- }[ast.operator](SafeEval.evalAst(ast.left, subs), () => SafeEval.evalAst(ast.right, subs));
28225
- return result;
28226
- },
28227
- evalCompound(ast, subs) {
28228
- let last;
28229
- for (let i = 0;i < ast.body.length; i++) {
28230
- if (ast.body[i].type === "Identifier" && ["var", "let", "const"].includes(ast.body[i].name) && ast.body[i + 1] && ast.body[i + 1].type === "AssignmentExpression") {
28231
- i += 1;
28232
- }
28233
- const expr = ast.body[i];
28234
- last = SafeEval.evalAst(expr, subs);
28235
- }
28236
- return last;
28237
- },
28238
- evalConditionalExpression(ast, subs) {
28239
- if (SafeEval.evalAst(ast.test, subs)) {
28240
- return SafeEval.evalAst(ast.consequent, subs);
28241
- }
28242
- return SafeEval.evalAst(ast.alternate, subs);
28243
- },
28244
- evalIdentifier(ast, subs) {
28245
- if (Object.hasOwn(subs, ast.name)) {
28246
- return subs[ast.name];
28247
- }
28248
- throw ReferenceError(`${ast.name} is not defined`);
28249
- },
28250
- evalLiteral(ast) {
28251
- return ast.value;
28252
- },
28253
- evalMemberExpression(ast, subs) {
28254
- const prop = String(ast.computed ? SafeEval.evalAst(ast.property) : ast.property.name);
28255
- const obj = SafeEval.evalAst(ast.object, subs);
28256
- if (obj === undefined || obj === null) {
28257
- throw TypeError(`Cannot read properties of ${obj} (reading '${prop}')`);
28258
- }
28259
- if (!Object.hasOwn(obj, prop) && BLOCKED_PROTO_PROPERTIES.has(prop)) {
28260
- throw TypeError(`Cannot read properties of ${obj} (reading '${prop}')`);
28261
- }
28262
- const result = obj[prop];
28263
- if (typeof result === "function") {
28264
- return result.bind(obj);
28265
- }
28266
- return result;
28267
- },
28268
- evalUnaryExpression(ast, subs) {
28269
- const result = {
28270
- "-": (a) => -SafeEval.evalAst(a, subs),
28271
- "!": (a) => !SafeEval.evalAst(a, subs),
28272
- "~": (a) => ~SafeEval.evalAst(a, subs),
28273
- "+": (a) => +SafeEval.evalAst(a, subs),
28274
- typeof: (a) => typeof SafeEval.evalAst(a, subs),
28275
- void: (a) => void SafeEval.evalAst(a, subs)
28276
- }[ast.operator](ast.argument);
28277
- return result;
28278
- },
28279
- evalArrayExpression(ast, subs) {
28280
- return ast.elements.map((el) => SafeEval.evalAst(el, subs));
28281
- },
28282
- evalCallExpression(ast, subs) {
28283
- const args = ast.arguments.map((arg) => SafeEval.evalAst(arg, subs));
28284
- const func = SafeEval.evalAst(ast.callee, subs);
28285
- if (func === Function) {
28286
- throw new Error("Function constructor is disabled");
28287
- }
28288
- return func(...args);
28289
- },
28290
- evalAssignmentExpression(ast, subs) {
28291
- if (ast.left.type !== "Identifier") {
28292
- throw SyntaxError("Invalid left-hand side in assignment");
28293
- }
28294
- const id = ast.left.name;
28295
- const value = SafeEval.evalAst(ast.right, subs);
28296
- subs[id] = value;
28297
- return subs[id];
28298
- }
28299
- };
28300
-
28301
- class SafeScript {
28302
- constructor(expr) {
28303
- this.code = expr;
28304
- this.ast = jsep(this.code);
28305
- }
28306
- runInNewContext(context) {
28307
- const keyMap = Object.assign(Object.create(null), context);
28308
- return SafeEval.evalAst(this.ast, keyMap);
28309
- }
28310
- }
28311
- function push(arr, item) {
28312
- arr = arr.slice();
28313
- arr.push(item);
28314
- return arr;
28315
- }
28316
- function unshift(item, arr) {
28317
- arr = arr.slice();
28318
- arr.unshift(item);
28319
- return arr;
28320
- }
28321
-
28322
- class NewError extends Error {
28323
- constructor(value) {
28324
- super('JSONPath should not be called with "new" (it prevents return ' + "of (unwrapped) scalar values)");
28325
- this.avoidNew = true;
28326
- this.value = value;
28327
- this.name = "NewError";
28328
- }
28329
- }
28330
- function JSONPath(opts, expr, obj, callback, otherTypeCallback) {
28331
- if (!(this instanceof JSONPath)) {
28332
- try {
28333
- return new JSONPath(opts, expr, obj, callback, otherTypeCallback);
28334
- } catch (e) {
28335
- if (!e.avoidNew) {
28336
- throw e;
28337
- }
28338
- return e.value;
28339
- }
28340
- }
28341
- if (typeof opts === "string") {
28342
- otherTypeCallback = callback;
28343
- callback = obj;
28344
- obj = expr;
28345
- expr = opts;
28346
- opts = null;
28347
- }
28348
- const optObj = opts && typeof opts === "object";
28349
- opts = opts || {};
28350
- this.json = opts.json || obj;
28351
- this.path = opts.path || expr;
28352
- this.resultType = opts.resultType || "value";
28353
- this.flatten = opts.flatten || false;
28354
- this.wrap = Object.hasOwn(opts, "wrap") ? opts.wrap : true;
28355
- this.sandbox = opts.sandbox || {};
28356
- this.eval = opts.eval === undefined ? "safe" : opts.eval;
28357
- this.ignoreEvalErrors = typeof opts.ignoreEvalErrors === "undefined" ? false : opts.ignoreEvalErrors;
28358
- this.parent = opts.parent || null;
28359
- this.parentProperty = opts.parentProperty || null;
28360
- this.callback = opts.callback || callback || null;
28361
- this.otherTypeCallback = opts.otherTypeCallback || otherTypeCallback || function() {
28362
- throw new TypeError("You must supply an otherTypeCallback callback option " + "with the @other() operator.");
28363
- };
28364
- if (opts.autostart !== false) {
28365
- const args = {
28366
- path: optObj ? opts.path : expr
28367
- };
28368
- if (!optObj) {
28369
- args.json = obj;
28370
- } else if ("json" in opts) {
28371
- args.json = opts.json;
28372
- }
28373
- const ret = this.evaluate(args);
28374
- if (!ret || typeof ret !== "object") {
28375
- throw new NewError(ret);
28376
- }
28377
- return ret;
28378
- }
28379
- }
28380
- JSONPath.prototype.evaluate = function(expr, json, callback, otherTypeCallback) {
28381
- let currParent = this.parent, currParentProperty = this.parentProperty;
28382
- let {
28383
- flatten,
28384
- wrap
28385
- } = this;
28386
- this.currResultType = this.resultType;
28387
- this.currEval = this.eval;
28388
- this.currSandbox = this.sandbox;
28389
- callback = callback || this.callback;
28390
- this.currOtherTypeCallback = otherTypeCallback || this.otherTypeCallback;
28391
- json = json || this.json;
28392
- expr = expr || this.path;
28393
- if (expr && typeof expr === "object" && !Array.isArray(expr)) {
28394
- if (!expr.path && expr.path !== "") {
28395
- throw new TypeError('You must supply a "path" property when providing an object ' + "argument to JSONPath.evaluate().");
28396
- }
28397
- if (!Object.hasOwn(expr, "json")) {
28398
- throw new TypeError('You must supply a "json" property when providing an object ' + "argument to JSONPath.evaluate().");
28399
- }
28400
- ({
28401
- json
28402
- } = expr);
28403
- flatten = Object.hasOwn(expr, "flatten") ? expr.flatten : flatten;
28404
- this.currResultType = Object.hasOwn(expr, "resultType") ? expr.resultType : this.currResultType;
28405
- this.currSandbox = Object.hasOwn(expr, "sandbox") ? expr.sandbox : this.currSandbox;
28406
- wrap = Object.hasOwn(expr, "wrap") ? expr.wrap : wrap;
28407
- this.currEval = Object.hasOwn(expr, "eval") ? expr.eval : this.currEval;
28408
- callback = Object.hasOwn(expr, "callback") ? expr.callback : callback;
28409
- this.currOtherTypeCallback = Object.hasOwn(expr, "otherTypeCallback") ? expr.otherTypeCallback : this.currOtherTypeCallback;
28410
- currParent = Object.hasOwn(expr, "parent") ? expr.parent : currParent;
28411
- currParentProperty = Object.hasOwn(expr, "parentProperty") ? expr.parentProperty : currParentProperty;
28412
- expr = expr.path;
28413
- }
28414
- currParent = currParent || null;
28415
- currParentProperty = currParentProperty || null;
28416
- if (Array.isArray(expr)) {
28417
- expr = JSONPath.toPathString(expr);
28418
- }
28419
- if (!expr && expr !== "" || !json) {
28420
- return;
28421
- }
28422
- const exprList = JSONPath.toPathArray(expr);
28423
- if (exprList[0] === "$" && exprList.length > 1) {
28424
- exprList.shift();
28425
- }
28426
- this._hasParentSelector = null;
28427
- const result = this._trace(exprList, json, ["$"], currParent, currParentProperty, callback).filter(function(ea) {
28428
- return ea && !ea.isParentSelector;
28429
- });
28430
- if (!result.length) {
28431
- return wrap ? [] : undefined;
28432
- }
28433
- if (!wrap && result.length === 1 && !result[0].hasArrExpr) {
28434
- return this._getPreferredOutput(result[0]);
28435
- }
28436
- return result.reduce((rslt, ea) => {
28437
- const valOrPath = this._getPreferredOutput(ea);
28438
- if (flatten && Array.isArray(valOrPath)) {
28439
- rslt = rslt.concat(valOrPath);
28440
- } else {
28441
- rslt.push(valOrPath);
28442
- }
28443
- return rslt;
28444
- }, []);
28445
- };
28446
- JSONPath.prototype._getPreferredOutput = function(ea) {
28447
- const resultType = this.currResultType;
28448
- switch (resultType) {
28449
- case "all": {
28450
- const path3 = Array.isArray(ea.path) ? ea.path : JSONPath.toPathArray(ea.path);
28451
- ea.pointer = JSONPath.toPointer(path3);
28452
- ea.path = typeof ea.path === "string" ? ea.path : JSONPath.toPathString(ea.path);
28453
- return ea;
28454
- }
28455
- case "value":
28456
- case "parent":
28457
- case "parentProperty":
28458
- return ea[resultType];
28459
- case "path":
28460
- return JSONPath.toPathString(ea[resultType]);
28461
- case "pointer":
28462
- return JSONPath.toPointer(ea.path);
28463
- default:
28464
- throw new TypeError("Unknown result type");
28465
- }
28466
- };
28467
- JSONPath.prototype._handleCallback = function(fullRetObj, callback, type) {
28468
- if (callback) {
28469
- const preferredOutput = this._getPreferredOutput(fullRetObj);
28470
- fullRetObj.path = typeof fullRetObj.path === "string" ? fullRetObj.path : JSONPath.toPathString(fullRetObj.path);
28471
- callback(preferredOutput, type, fullRetObj);
28472
- }
28473
- };
28474
- JSONPath.prototype._trace = function(expr, val, path3, parent, parentPropName, callback, hasArrExpr, literalPriority) {
28475
- let retObj;
28476
- if (!expr.length) {
28477
- retObj = {
28478
- path: path3,
28479
- value: val,
28480
- parent,
28481
- parentProperty: parentPropName,
28482
- hasArrExpr
28483
- };
28484
- this._handleCallback(retObj, callback, "value");
28485
- return retObj;
28486
- }
28487
- const loc = expr[0], x = expr.slice(1);
28488
- const ret = [];
28489
- function addRet(elems) {
28490
- if (Array.isArray(elems)) {
28491
- elems.forEach((t) => {
28492
- ret.push(t);
28493
- });
28494
- } else {
28495
- ret.push(elems);
28496
- }
28497
- }
28498
- if ((typeof loc !== "string" || literalPriority) && val && Object.hasOwn(val, loc)) {
28499
- addRet(this._trace(x, val[loc], push(path3, loc), val, loc, callback, hasArrExpr));
28500
- } else if (loc === "*") {
28501
- this._walk(val, (m) => {
28502
- addRet(this._trace(x, val[m], push(path3, m), val, m, callback, true, true));
28503
- });
28504
- } else if (loc === "..") {
28505
- addRet(this._trace(x, val, path3, parent, parentPropName, callback, hasArrExpr));
28506
- this._walk(val, (m) => {
28507
- if (typeof val[m] === "object") {
28508
- addRet(this._trace(expr.slice(), val[m], push(path3, m), val, m, callback, true));
28509
- }
28510
- });
28511
- } else if (loc === "^") {
28512
- this._hasParentSelector = true;
28513
- return {
28514
- path: path3.slice(0, -1),
28515
- expr: x,
28516
- isParentSelector: true
28517
- };
28518
- } else if (loc === "~") {
28519
- retObj = {
28520
- path: push(path3, loc),
28521
- value: parentPropName,
28522
- parent,
28523
- parentProperty: null
28524
- };
28525
- this._handleCallback(retObj, callback, "property");
28526
- return retObj;
28527
- } else if (loc === "$") {
28528
- addRet(this._trace(x, val, path3, null, null, callback, hasArrExpr));
28529
- } else if (/^(-?\d*):(-?\d*):?(\d*)$/u.test(loc)) {
28530
- addRet(this._slice(loc, x, val, path3, parent, parentPropName, callback));
28531
- } else if (loc.indexOf("?(") === 0) {
28532
- if (this.currEval === false) {
28533
- throw new Error("Eval [?(expr)] prevented in JSONPath expression.");
28534
- }
28535
- const safeLoc = loc.replace(/^\?\((.*?)\)$/u, "$1");
28536
- const nested = /@.?([^?]*)[['](\??\(.*?\))(?!.\)\])[\]']/gu.exec(safeLoc);
28537
- if (nested) {
28538
- this._walk(val, (m) => {
28539
- const npath = [nested[2]];
28540
- const nvalue = nested[1] ? val[m][nested[1]] : val[m];
28541
- const filterResults = this._trace(npath, nvalue, path3, parent, parentPropName, callback, true);
28542
- if (filterResults.length > 0) {
28543
- addRet(this._trace(x, val[m], push(path3, m), val, m, callback, true));
28544
- }
28545
- });
28546
- } else {
28547
- this._walk(val, (m) => {
28548
- if (this._eval(safeLoc, val[m], m, path3, parent, parentPropName)) {
28549
- addRet(this._trace(x, val[m], push(path3, m), val, m, callback, true));
28550
- }
28551
- });
28552
- }
28553
- } else if (loc[0] === "(") {
28554
- if (this.currEval === false) {
28555
- throw new Error("Eval [(expr)] prevented in JSONPath expression.");
28556
- }
28557
- addRet(this._trace(unshift(this._eval(loc, val, path3.at(-1), path3.slice(0, -1), parent, parentPropName), x), val, path3, parent, parentPropName, callback, hasArrExpr));
28558
- } else if (loc[0] === "@") {
28559
- let addType = false;
28560
- const valueType = loc.slice(1, -2);
28561
- switch (valueType) {
28562
- case "scalar":
28563
- if (!val || !["object", "function"].includes(typeof val)) {
28564
- addType = true;
28565
- }
28566
- break;
28567
- case "boolean":
28568
- case "string":
28569
- case "undefined":
28570
- case "function":
28571
- if (typeof val === valueType) {
28572
- addType = true;
28573
- }
28574
- break;
28575
- case "integer":
28576
- if (Number.isFinite(val) && !(val % 1)) {
28577
- addType = true;
28578
- }
28579
- break;
28580
- case "number":
28581
- if (Number.isFinite(val)) {
28582
- addType = true;
28583
- }
28584
- break;
28585
- case "nonFinite":
28586
- if (typeof val === "number" && !Number.isFinite(val)) {
28587
- addType = true;
28588
- }
28589
- break;
28590
- case "object":
28591
- if (val && typeof val === valueType) {
28592
- addType = true;
28593
- }
28594
- break;
28595
- case "array":
28596
- if (Array.isArray(val)) {
28597
- addType = true;
28598
- }
28599
- break;
28600
- case "other":
28601
- addType = this.currOtherTypeCallback(val, path3, parent, parentPropName);
28602
- break;
28603
- case "null":
28604
- if (val === null) {
28605
- addType = true;
28606
- }
28607
- break;
28608
- default:
28609
- throw new TypeError("Unknown value type " + valueType);
28610
- }
28611
- if (addType) {
28612
- retObj = {
28613
- path: path3,
28614
- value: val,
28615
- parent,
28616
- parentProperty: parentPropName
28617
- };
28618
- this._handleCallback(retObj, callback, "value");
28619
- return retObj;
28620
- }
28621
- } else if (loc[0] === "`" && val && Object.hasOwn(val, loc.slice(1))) {
28622
- const locProp = loc.slice(1);
28623
- addRet(this._trace(x, val[locProp], push(path3, locProp), val, locProp, callback, hasArrExpr, true));
28624
- } else if (loc.includes(",")) {
28625
- const parts = loc.split(",");
28626
- for (const part of parts) {
28627
- addRet(this._trace(unshift(part, x), val, path3, parent, parentPropName, callback, true));
28628
- }
28629
- } else if (!literalPriority && val && Object.hasOwn(val, loc)) {
28630
- addRet(this._trace(x, val[loc], push(path3, loc), val, loc, callback, hasArrExpr, true));
28631
- }
28632
- if (this._hasParentSelector) {
28633
- for (let t = 0;t < ret.length; t++) {
28634
- const rett = ret[t];
28635
- if (rett && rett.isParentSelector) {
28636
- const tmp = this._trace(rett.expr, val, rett.path, parent, parentPropName, callback, hasArrExpr);
28637
- if (Array.isArray(tmp)) {
28638
- ret[t] = tmp[0];
28639
- const tl = tmp.length;
28640
- for (let tt = 1;tt < tl; tt++) {
28641
- t++;
28642
- ret.splice(t, 0, tmp[tt]);
28643
- }
28644
- } else {
28645
- ret[t] = tmp;
28646
- }
28647
- }
28648
- }
28649
- }
28650
- return ret;
28651
- };
28652
- JSONPath.prototype._walk = function(val, f) {
28653
- if (Array.isArray(val)) {
28654
- const n = val.length;
28655
- for (let i = 0;i < n; i++) {
28656
- f(i);
28657
- }
28658
- } else if (val && typeof val === "object") {
28659
- Object.keys(val).forEach((m) => {
28660
- f(m);
28661
- });
28662
- }
28663
- };
28664
- JSONPath.prototype._slice = function(loc, expr, val, path3, parent, parentPropName, callback) {
28665
- if (!Array.isArray(val)) {
28666
- return;
28667
- }
28668
- const len = val.length, parts = loc.split(":"), step = parts[2] && Number.parseInt(parts[2]) || 1;
28669
- let start = parts[0] && Number.parseInt(parts[0]) || 0, end = parts[1] && Number.parseInt(parts[1]) || len;
28670
- start = start < 0 ? Math.max(0, start + len) : Math.min(len, start);
28671
- end = end < 0 ? Math.max(0, end + len) : Math.min(len, end);
28672
- const ret = [];
28673
- for (let i = start;i < end; i += step) {
28674
- const tmp = this._trace(unshift(i, expr), val, path3, parent, parentPropName, callback, true);
28675
- tmp.forEach((t) => {
28676
- ret.push(t);
28677
- });
28678
- }
28679
- return ret;
28680
- };
28681
- JSONPath.prototype._eval = function(code, _v, _vname, path3, parent, parentPropName) {
28682
- this.currSandbox._$_parentProperty = parentPropName;
28683
- this.currSandbox._$_parent = parent;
28684
- this.currSandbox._$_property = _vname;
28685
- this.currSandbox._$_root = this.json;
28686
- this.currSandbox._$_v = _v;
28687
- const containsPath = code.includes("@path");
28688
- if (containsPath) {
28689
- this.currSandbox._$_path = JSONPath.toPathString(path3.concat([_vname]));
28690
- }
28691
- const scriptCacheKey = this.currEval + "Script:" + code;
28692
- if (!JSONPath.cache[scriptCacheKey]) {
28693
- let script = code.replaceAll("@parentProperty", "_$_parentProperty").replaceAll("@parent", "_$_parent").replaceAll("@property", "_$_property").replaceAll("@root", "_$_root").replaceAll(/@([.\s)[])/gu, "_$_v$1");
28694
- if (containsPath) {
28695
- script = script.replaceAll("@path", "_$_path");
28696
- }
28697
- if (this.currEval === "safe" || this.currEval === true || this.currEval === undefined) {
28698
- JSONPath.cache[scriptCacheKey] = new this.safeVm.Script(script);
28699
- } else if (this.currEval === "native") {
28700
- JSONPath.cache[scriptCacheKey] = new this.vm.Script(script);
28701
- } else if (typeof this.currEval === "function" && this.currEval.prototype && Object.hasOwn(this.currEval.prototype, "runInNewContext")) {
28702
- const CurrEval = this.currEval;
28703
- JSONPath.cache[scriptCacheKey] = new CurrEval(script);
28704
- } else if (typeof this.currEval === "function") {
28705
- JSONPath.cache[scriptCacheKey] = {
28706
- runInNewContext: (context) => this.currEval(script, context)
28707
- };
28708
- } else {
28709
- throw new TypeError(`Unknown "eval" property "${this.currEval}"`);
28710
- }
28711
- }
28712
- try {
28713
- return JSONPath.cache[scriptCacheKey].runInNewContext(this.currSandbox);
28714
- } catch (e) {
28715
- if (this.ignoreEvalErrors) {
28716
- return false;
28717
- }
28718
- throw new Error("jsonPath: " + e.message + ": " + code);
28719
- }
28720
- };
28721
- JSONPath.cache = {};
28722
- JSONPath.toPathString = function(pathArr) {
28723
- const x = pathArr, n = x.length;
28724
- let p = "$";
28725
- for (let i = 1;i < n; i++) {
28726
- if (!/^(~|\^|@.*?\(\))$/u.test(x[i])) {
28727
- p += /^[0-9*]+$/u.test(x[i]) ? "[" + x[i] + "]" : "['" + x[i] + "']";
28728
- }
28729
- }
28730
- return p;
28731
- };
28732
- JSONPath.toPointer = function(pointer) {
28733
- const x = pointer, n = x.length;
28734
- let p = "";
28735
- for (let i = 1;i < n; i++) {
28736
- if (!/^(~|\^|@.*?\(\))$/u.test(x[i])) {
28737
- p += "/" + x[i].toString().replaceAll("~", "~0").replaceAll("/", "~1");
28738
- }
28739
- }
28740
- return p;
28741
- };
28742
- JSONPath.toPathArray = function(expr) {
28743
- const {
28744
- cache
28745
- } = JSONPath;
28746
- if (cache[expr]) {
28747
- return cache[expr].concat();
28748
- }
28749
- const subx = [];
28750
- const normalized = expr.replaceAll(/@(?:null|boolean|number|string|integer|undefined|nonFinite|scalar|array|object|function|other)\(\)/gu, ";$&;").replaceAll(/[['](\??\(.*?\))[\]'](?!.\])/gu, function($0, $1) {
28751
- return "[#" + (subx.push($1) - 1) + "]";
28752
- }).replaceAll(/\[['"]([^'\]]*)['"]\]/gu, function($0, prop) {
28753
- return "['" + prop.replaceAll(".", "%@%").replaceAll("~", "%%@@%%") + "']";
28754
- }).replaceAll("~", ";~;").replaceAll(/['"]?\.['"]?(?![^[]*\])|\[['"]?/gu, ";").replaceAll("%@%", ".").replaceAll("%%@@%%", "~").replaceAll(/(?:;)?(\^+)(?:;)?/gu, function($0, ups) {
28755
- return ";" + ups.split("").join(";") + ";";
28756
- }).replaceAll(/;;;|;;/gu, ";..;").replaceAll(/;$|'?\]|'$/gu, "");
28757
- const exprList = normalized.split(";").map(function(exp) {
28758
- const match = exp.match(/#(\d+)/u);
28759
- return !match || !match[1] ? exp : subx[match[1]];
28760
- });
28761
- cache[expr] = exprList;
28762
- return cache[expr].concat();
28763
- };
28764
- JSONPath.prototype.safeVm = {
28765
- Script: SafeScript
28766
- };
28767
- JSONPath.prototype.vm = vm;
28768
- // ../common/src/polling/format-utils.ts
28769
- function msToDuration(ms) {
28770
- if (!Number.isFinite(ms) || ms < 0) {
28771
- return "00:00:00";
28772
- }
28773
- const totalSec = Math.floor(ms / 1000);
28774
- const h = Math.floor(totalSec / 3600);
28775
- const m = Math.floor(totalSec % 3600 / 60);
28776
- const s = totalSec % 60;
28777
- return [h, m, s].map((v) => String(v).padStart(2, "0")).join(":");
28778
- }
28779
- // ../common/src/polling/types.ts
28780
- var PollOutcome = {
28781
- Completed: "completed",
28782
- Timeout: "timeout",
28783
- Interrupted: "interrupted",
28784
- Aborted: "aborted",
28785
- Failed: "failed"
28786
- };
28787
- var ErrorDecision = {
28788
- Abort: "abort"
28789
- };
28790
- var POLL_DEFAULTS = {
28791
- intervalMs: 5000,
28792
- timeoutMs: 1800000,
28793
- maxConsecutiveErrors: 3,
28794
- logIntervalMs: 30000,
28795
- logPrefix: "wait"
28796
- };
28797
- var BACKOFF_DEFAULTS = {
28798
- initialMs: 1000,
28799
- multiplier: 2,
28800
- maxMs: 30000,
28801
- jitter: 0.5
28802
- };
28803
- var MIN_INTERVAL_MS = 100;
28804
-
28805
- // ../common/src/polling/poll-failure-mapping.ts
28806
- var REASON_BY_OUTCOME = {
28807
- [PollOutcome.Timeout]: "poll_timeout",
28808
- [PollOutcome.Failed]: "poll_failed",
28809
- [PollOutcome.Interrupted]: "poll_failed",
28810
- [PollOutcome.Aborted]: "poll_aborted"
28811
- };
28812
- function mapPollFailure(pollResult, label) {
28813
- const outcome = pollResult.outcome;
28814
- const errMsg = pollResult.error?.message ?? "too many consecutive errors";
28815
- const messageByOutcome = {
28816
- [PollOutcome.Timeout]: `${label} polling timed out`,
28817
- [PollOutcome.Failed]: `${label} polling failed: ${errMsg}`,
28818
- [PollOutcome.Interrupted]: `${label} polling was interrupted`,
28819
- [PollOutcome.Aborted]: `${label} polling was aborted`
28820
- };
28821
- return {
28822
- reason: REASON_BY_OUTCOME[outcome],
28823
- message: messageByOutcome[outcome],
28824
- exitCode: outcome === PollOutcome.Timeout ? 2 : 1
28825
- };
28826
- }
28827
- // ../common/src/polling/poll-until.ts
28828
- function resolveIntervalFn(options) {
28829
- if (typeof options.intervalMs === "function") {
28830
- return options.intervalMs;
28831
- }
28832
- const staticInterval = options.intervalMs ?? POLL_DEFAULTS.intervalMs;
28833
- return () => staticInterval;
28834
- }
28835
- function resolveBackoffFn(options) {
28836
- if (!options.backoff)
28837
- return;
28838
- const config = options.backoff === true ? { ...BACKOFF_DEFAULTS } : {
28839
- initialMs: options.backoff.initialMs ?? BACKOFF_DEFAULTS.initialMs,
28840
- multiplier: options.backoff.multiplier ?? BACKOFF_DEFAULTS.multiplier,
28841
- maxMs: options.backoff.maxMs ?? BACKOFF_DEFAULTS.maxMs,
28842
- jitter: Math.min(1, Math.max(0, options.backoff.jitter ?? BACKOFF_DEFAULTS.jitter))
28843
- };
28844
- return (errorCount) => {
28845
- const exponent = Math.min(errorCount - 1, 30);
28846
- const raw = Math.min(config.initialMs * config.multiplier ** exponent, config.maxMs);
28847
- if (config.jitter > 0) {
28848
- const jitterAmount = raw * config.jitter;
28849
- return raw - jitterAmount * Math.random();
28850
- }
28851
- return raw;
28852
- };
28853
- }
28854
- function clampInterval(raw, label, prefix) {
28855
- if (!Number.isFinite(raw) || Number.isNaN(raw)) {
28856
- if (label) {
28857
- logger.warn(`[${prefix}] ${label} — intervalMs returned ${raw}, falling back to ${POLL_DEFAULTS.intervalMs}ms`);
28858
- }
28859
- return POLL_DEFAULTS.intervalMs;
28860
- }
28861
- if (raw < MIN_INTERVAL_MS) {
28862
- if (label) {
28863
- logger.warn(`[${prefix}] ${label} — intervalMs ${raw}ms clamped to minimum ${MIN_INTERVAL_MS}ms`);
28864
- }
28865
- return MIN_INTERVAL_MS;
28866
- }
28867
- return raw;
28868
- }
28869
- function abortError(signal) {
28870
- const reason = signal.reason;
28871
- if (reason instanceof Error && reason.name === "AbortError") {
28872
- return reason;
28873
- }
28874
- const msg = reason instanceof Error ? reason.message : typeof reason === "string" || typeof reason === "number" ? String(reason) : "Aborted";
28875
- const err = new Error(msg);
28876
- err.name = "AbortError";
28877
- return err;
28878
- }
28879
- function interruptibleSleep(ms, signal) {
28880
- return new Promise((resolve2, reject) => {
28881
- if (signal?.aborted) {
28882
- reject(abortError(signal));
28883
- return;
28884
- }
28885
- let onAbort;
28886
- const cleanup = () => {
28887
- if (onAbort) {
28888
- signal?.removeEventListener("abort", onAbort);
28889
- }
28890
- };
28891
- const timer = setTimeout(() => {
28892
- cleanup();
28893
- resolve2();
28894
- }, ms);
28895
- if (signal) {
28896
- onAbort = () => {
28897
- clearTimeout(timer);
28898
- cleanup();
28899
- reject(abortError(signal));
28900
- };
28901
- signal.addEventListener("abort", onAbort, { once: true });
27603
+ };
27604
+ const timer = setTimeout(() => {
27605
+ cleanup();
27606
+ resolve2();
27607
+ }, ms);
27608
+ if (signal) {
27609
+ onAbort = () => {
27610
+ clearTimeout(timer);
27611
+ cleanup();
27612
+ reject(abortError(signal));
27613
+ };
27614
+ signal.addEventListener("abort", onAbort, { once: true });
28902
27615
  }
28903
27616
  });
28904
27617
  }
@@ -29222,6 +27935,17 @@ var FAILURE_STATUSES = new Set([
29222
27935
  "canceled",
29223
27936
  "stopped"
29224
27937
  ]);
27938
+ // ../common/src/preview.ts
27939
+ var previewSlot = singleton("PreviewBuild");
27940
+ function isPreviewBuild() {
27941
+ return previewSlot.get(false) ?? false;
27942
+ }
27943
+ Command.prototype.previewCommand = function(nameAndArgs, opts) {
27944
+ if (isPreviewBuild()) {
27945
+ return this.command(nameAndArgs, opts);
27946
+ }
27947
+ return new Command(nameAndArgs.split(/\s+/)[0] ?? nameAndArgs);
27948
+ };
29225
27949
  // ../common/src/screen-logger.ts
29226
27950
  var ScreenLogger;
29227
27951
  ((ScreenLogger) => {
@@ -29254,8 +27978,8 @@ function appendUserAgentToken(value, userAgent) {
29254
27978
  function getEffectiveUserAgent(userAgent) {
29255
27979
  return appendUserAgentToken(sdkUserAgentHostToken.get(), userAgent);
29256
27980
  }
29257
- function isHeadersLike(headers) {
29258
- return typeof headers === "object" && headers !== null && "get" in headers && typeof headers.get === "function" && "set" in headers && typeof headers.set === "function";
27981
+ function getHeaderName(headers, headerName) {
27982
+ return Object.keys(headers).find((key) => key.toLowerCase() === headerName.toLowerCase());
29259
27983
  }
29260
27984
  function getSdkUserAgentToken(pkg) {
29261
27985
  const packageName = pkg.name.replace(/^@uipath\//, "");
@@ -29263,59 +27987,31 @@ function getSdkUserAgentToken(pkg) {
29263
27987
  }
29264
27988
  function addSdkUserAgentHeader(headers, userAgent) {
29265
27989
  const result = { ...headers ?? {} };
29266
- const effectiveUserAgent = getEffectiveUserAgent(userAgent);
29267
- const headerName = Object.keys(result).find((key) => key.toLowerCase() === USER_AGENT_HEADER.toLowerCase());
29268
- if (headerName) {
29269
- result[headerName] = appendUserAgentToken(result[headerName], effectiveUserAgent);
29270
- } else {
29271
- result[USER_AGENT_HEADER] = effectiveUserAgent;
29272
- }
27990
+ const headerName = getHeaderName(result, USER_AGENT_HEADER);
27991
+ result[headerName ?? USER_AGENT_HEADER] = appendUserAgentToken(headerName ? result[headerName] : undefined, getEffectiveUserAgent(userAgent));
29273
27992
  return result;
29274
27993
  }
29275
- function withSdkUserAgentHeader(headers, userAgent) {
29276
- const effectiveUserAgent = getEffectiveUserAgent(userAgent);
29277
- if (isHeadersLike(headers)) {
29278
- headers.set(USER_AGENT_HEADER, appendUserAgentToken(headers.get(USER_AGENT_HEADER), effectiveUserAgent));
29279
- return headers;
29280
- }
29281
- if (Array.isArray(headers)) {
29282
- const result = headers.map((entry) => {
29283
- const [key, value] = entry;
29284
- return [key, value];
29285
- });
29286
- const headerIndex = result.findIndex(([key]) => key.toLowerCase() === USER_AGENT_HEADER.toLowerCase());
29287
- if (headerIndex >= 0) {
29288
- const [key, value] = result[headerIndex];
29289
- result[headerIndex] = [
29290
- key,
29291
- appendUserAgentToken(value, effectiveUserAgent)
29292
- ];
29293
- } else {
29294
- result.push([USER_AGENT_HEADER, effectiveUserAgent]);
29295
- }
29296
- return result;
29297
- }
29298
- return addSdkUserAgentHeader(typeof headers === "object" && headers !== null ? { ...headers } : {}, effectiveUserAgent);
27994
+ function asHeaderRecord(headers) {
27995
+ return typeof headers === "object" && headers !== null ? { ...headers } : {};
29299
27996
  }
29300
- function withUserAgentInitOverride(initOverrides, userAgent) {
27997
+ function withForwardedHeadersInitOverride(initOverrides, forward) {
29301
27998
  return async (requestContext) => {
29302
- const initWithUserAgent = {
27999
+ const initWithHeaders = {
29303
28000
  ...requestContext.init,
29304
- headers: withSdkUserAgentHeader(requestContext.init.headers, userAgent)
28001
+ headers: forward(asHeaderRecord(requestContext.init.headers))
29305
28002
  };
29306
28003
  const override = typeof initOverrides === "function" ? await initOverrides({
29307
28004
  ...requestContext,
29308
- init: initWithUserAgent
28005
+ init: initWithHeaders
29309
28006
  }) : initOverrides;
29310
28007
  return {
29311
28008
  ...override ?? {},
29312
- headers: withSdkUserAgentHeader(override?.headers ?? initWithUserAgent.headers, userAgent)
28009
+ headers: forward(asHeaderRecord(override?.headers ?? initWithHeaders.headers))
29313
28010
  };
29314
28011
  };
29315
28012
  }
29316
- function installSdkUserAgentHeader(BaseApiClass, userAgent) {
28013
+ function installRequestHeaderForwarding(BaseApiClass, patchKey, forward) {
29317
28014
  const prototype = BaseApiClass.prototype;
29318
- const patchKey = userAgentPatchKey(userAgent);
29319
28015
  if (prototype[patchKey]) {
29320
28016
  return;
29321
28017
  }
@@ -29323,13 +28019,16 @@ function installSdkUserAgentHeader(BaseApiClass, userAgent) {
29323
28019
  throw new Error("Generated BaseAPI request function not found.");
29324
28020
  }
29325
28021
  const originalRequest = prototype.request;
29326
- prototype.request = function requestWithUserAgent(context, initOverrides) {
29327
- return originalRequest.call(this, context, withUserAgentInitOverride(initOverrides, userAgent));
28022
+ prototype.request = function requestWithForwardedHeaders(context, initOverrides) {
28023
+ return originalRequest.call(this, context, withForwardedHeadersInitOverride(initOverrides, forward));
29328
28024
  };
29329
28025
  Object.defineProperty(prototype, patchKey, {
29330
28026
  value: true
29331
28027
  });
29332
28028
  }
28029
+ function installSdkUserAgentHeader(BaseApiClass, userAgent) {
28030
+ installRequestHeaderForwarding(BaseApiClass, userAgentPatchKey(userAgent), (headers) => addSdkUserAgentHeader(headers, userAgent));
28031
+ }
29333
28032
  // ../common/src/tool-provider.ts
29334
28033
  var factorySlot = singleton("PackagerFactoryProvider");
29335
28034
  // src/services/publish-service.ts
@@ -29608,7 +28307,7 @@ class TextApiResponse {
29608
28307
  var package_default = {
29609
28308
  name: "@uipath/pipelines-sdk",
29610
28309
  license: "MIT",
29611
- version: "1.196.0",
28310
+ version: "1.197.0",
29612
28311
  description: "Generated TypeScript client for UiPath Pipelines API (CI/CD deployment lifecycle)",
29613
28312
  repository: {
29614
28313
  type: "git",
@@ -29640,7 +28339,7 @@ var package_default = {
29640
28339
  ],
29641
28340
  private: true,
29642
28341
  scripts: {
29643
- build: "bun build ./src/index.ts --outdir dist --format esm --target node && bun build ./src/scripts/generate-sdk.ts --outdir dist/scripts --format esm --target node && tsc -p tsconfig.build.json --noCheck",
28342
+ build: "bun build ./src/index.ts --outdir dist --format esm --target node --sourcemap=linked && bun build ./src/scripts/generate-sdk.ts --outdir dist/scripts --format esm --target node --sourcemap=linked && tsc -p tsconfig.build.json --noCheck",
29644
28343
  generate: "bun run src/scripts/generate-sdk.ts",
29645
28344
  lint: "biome check .",
29646
28345
  test: "vitest run",
@@ -30932,7 +29631,7 @@ class TextApiResponse2 {
30932
29631
  var package_default2 = {
30933
29632
  name: "@uipath/solution-sdk",
30934
29633
  license: "MIT",
30935
- version: "1.196.0",
29634
+ version: "1.197.0-preview.59",
30936
29635
  repository: {
30937
29636
  type: "git",
30938
29637
  url: "https://github.com/UiPath/cli.git",
@@ -30963,7 +29662,7 @@ var package_default2 = {
30963
29662
  ],
30964
29663
  private: false,
30965
29664
  scripts: {
30966
- build: "bun build ./src/index.ts --outdir dist --format esm --target node && bun build ./src/scripts/generate-sdk.ts --outdir dist/scripts --format esm --target node && tsc -p tsconfig.build.json --noCheck",
29665
+ build: "bun build ./src/index.ts --outdir dist --format esm --target node --sourcemap=linked && bun build ./src/scripts/generate-sdk.ts --outdir dist/scripts --format esm --target node --sourcemap=linked && tsc -p tsconfig.build.json --noCheck",
30967
29666
  generate: "bun run src/scripts/generate-sdk.ts",
30968
29667
  lint: "biome check .",
30969
29668
  test: "vitest run",
@@ -31622,6 +30321,12 @@ var normalizeAndValidateBaseUrl = (rawUrl) => {
31622
30321
  }
31623
30322
  return url.pathname.length > 1 ? url.origin : baseUrl;
31624
30323
  };
30324
+ var resolveScopes = (isExternalAppAuth, customScopes, fileScopes) => {
30325
+ const requestedScopes = customScopes?.length ? customScopes : fileScopes ?? [];
30326
+ if (isExternalAppAuth)
30327
+ return requestedScopes;
30328
+ return [...new Set([...DEFAULT_SCOPES, ...requestedScopes])];
30329
+ };
31625
30330
  var resolveConfigAsync = async ({
31626
30331
  customAuthority,
31627
30332
  customClientId,
@@ -31652,7 +30357,7 @@ var resolveConfigAsync = async ({
31652
30357
  clientSecret = fileAuth.clientSecret;
31653
30358
  }
31654
30359
  const isExternalAppAuth = clientId !== DEFAULT_CLIENT_ID && Boolean(clientSecret);
31655
- const scopes = customScopes && customScopes.length > 0 ? customScopes : fileAuth.scopes && fileAuth.scopes.length > 0 ? fileAuth.scopes : isExternalAppAuth ? [] : DEFAULT_SCOPES;
30360
+ const scopes = resolveScopes(isExternalAppAuth, customScopes, fileAuth.scopes);
31656
30361
  return {
31657
30362
  clientId,
31658
30363
  clientSecret,
@@ -31667,6 +30372,76 @@ var resolveConfigAsync = async ({
31667
30372
  init_constants();
31668
30373
  // ../auth/src/loginStatus.ts
31669
30374
  init_src();
30375
+
30376
+ // ../auth/src/authProfile.ts
30377
+ init_src();
30378
+ init_constants();
30379
+ var DEFAULT_AUTH_PROFILE = "default";
30380
+ var PROFILE_DIR = "profiles";
30381
+ var PROFILE_NAME_RE = /^[A-Za-z0-9._-]+$/;
30382
+ var ACTIVE_AUTH_PROFILE_KEY = Symbol.for("@uipath/auth/ActiveAuthProfile");
30383
+ var AUTH_PROFILE_STORAGE_KEY = Symbol.for("@uipath/auth/ProfileStorage");
30384
+ var globalSlot2 = globalThis;
30385
+ function isAuthProfileStorage(value) {
30386
+ return value !== null && typeof value === "object" && "getStore" in value && "run" in value;
30387
+ }
30388
+ function createProfileStorage() {
30389
+ const [error, mod2] = catchError2(() => __require("node:async_hooks"));
30390
+ if (error || typeof mod2?.AsyncLocalStorage !== "function") {
30391
+ return {
30392
+ getStore: () => {
30393
+ return;
30394
+ },
30395
+ run: (_store, fn) => fn()
30396
+ };
30397
+ }
30398
+ return new mod2.AsyncLocalStorage;
30399
+ }
30400
+ function getProfileStorage() {
30401
+ const existing = globalSlot2[AUTH_PROFILE_STORAGE_KEY];
30402
+ if (isAuthProfileStorage(existing)) {
30403
+ return existing;
30404
+ }
30405
+ const storage = createProfileStorage();
30406
+ globalSlot2[AUTH_PROFILE_STORAGE_KEY] = storage;
30407
+ return storage;
30408
+ }
30409
+ var profileStorage = getProfileStorage();
30410
+
30411
+ class AuthProfileValidationError extends Error {
30412
+ constructor(message) {
30413
+ super(message);
30414
+ this.name = "AuthProfileValidationError";
30415
+ }
30416
+ }
30417
+ function normalizeAuthProfileName(profile) {
30418
+ if (profile === undefined || profile === DEFAULT_AUTH_PROFILE) {
30419
+ return;
30420
+ }
30421
+ if (profile.length === 0 || profile === "." || profile === ".." || !PROFILE_NAME_RE.test(profile)) {
30422
+ throw new AuthProfileValidationError(`Invalid profile name "${profile}". Profile names may contain only letters, numbers, '.', '_', and '-'.`);
30423
+ }
30424
+ return profile;
30425
+ }
30426
+ function getActiveAuthProfile() {
30427
+ const scopedState = profileStorage.getStore();
30428
+ if (scopedState !== undefined) {
30429
+ return scopedState.profile;
30430
+ }
30431
+ return globalSlot2[ACTIVE_AUTH_PROFILE_KEY]?.profile;
30432
+ }
30433
+ function resolveAuthProfileFilePath(profile) {
30434
+ const normalized = normalizeAuthProfileName(profile);
30435
+ if (normalized === undefined) {
30436
+ throw new AuthProfileValidationError(`"${DEFAULT_AUTH_PROFILE}" is the built-in profile and does not have a profile file path.`);
30437
+ }
30438
+ const fs7 = getFileSystem();
30439
+ return fs7.path.join(fs7.env.homedir(), UIPATH_HOME_DIR, PROFILE_DIR, normalized, AUTH_FILENAME);
30440
+ }
30441
+ function getActiveAuthProfileFilePath() {
30442
+ const profile = getActiveAuthProfile();
30443
+ return profile ? resolveAuthProfileFilePath(profile) : undefined;
30444
+ }
31670
30445
  // ../auth/src/utils/jwt.ts
31671
30446
  class InvalidIssuerError extends Error {
31672
30447
  expected;
@@ -31795,23 +30570,74 @@ var readAuthFromEnv = () => {
31795
30570
  organizationId,
31796
30571
  tenantName,
31797
30572
  tenantId,
31798
- expiration
30573
+ expiration,
30574
+ source: "env" /* Env */
31799
30575
  };
31800
30576
  };
31801
30577
 
30578
+ // ../auth/src/refreshCircuitBreaker.ts
30579
+ init_src();
30580
+ var BREAKER_SUFFIX = ".refresh-state";
30581
+ var BACKOFF_BASE_MS = 60000;
30582
+ var BACKOFF_CAP_MS = 60 * 60 * 1000;
30583
+ var SURFACE_WINDOW_MS = 60 * 60 * 1000;
30584
+ async function refreshTokenFingerprint(refreshToken) {
30585
+ const bytes = new TextEncoder().encode(refreshToken);
30586
+ if (globalThis.crypto?.subtle) {
30587
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", bytes);
30588
+ return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("").slice(0, 16);
30589
+ }
30590
+ const { createHash } = await import("node:crypto");
30591
+ return createHash("sha256").update(refreshToken).digest("hex").slice(0, 16);
30592
+ }
30593
+ function breakerPathFor(authPath) {
30594
+ return `${authPath}${BREAKER_SUFFIX}`;
30595
+ }
30596
+ async function loadRefreshBreaker(authPath) {
30597
+ const fs7 = getFileSystem();
30598
+ try {
30599
+ const content = await fs7.readFile(breakerPathFor(authPath), "utf-8");
30600
+ if (!content)
30601
+ return {};
30602
+ const parsed = JSON.parse(content);
30603
+ return parsed && typeof parsed === "object" ? parsed : {};
30604
+ } catch {
30605
+ return {};
30606
+ }
30607
+ }
30608
+ async function saveRefreshBreaker(authPath, state) {
30609
+ try {
30610
+ const fs7 = getFileSystem();
30611
+ const path3 = breakerPathFor(authPath);
30612
+ await fs7.mkdir(fs7.path.dirname(path3));
30613
+ const tempPath = `${path3}.tmp`;
30614
+ await fs7.writeFile(tempPath, JSON.stringify(state));
30615
+ await fs7.rename(tempPath, path3);
30616
+ } catch {}
30617
+ }
30618
+ async function clearRefreshBreaker(authPath) {
30619
+ const fs7 = getFileSystem();
30620
+ const path3 = breakerPathFor(authPath);
30621
+ try {
30622
+ if (await fs7.exists(path3)) {
30623
+ await fs7.rm(path3);
30624
+ }
30625
+ } catch {}
30626
+ }
30627
+ function nextBackoffMs(attempts) {
30628
+ const shift = Math.max(0, attempts - 1);
30629
+ return Math.min(BACKOFF_BASE_MS * 2 ** shift, BACKOFF_CAP_MS);
30630
+ }
30631
+ function shouldSurface(state, nowMs) {
30632
+ if (state.lastSurfacedAtMs === undefined)
30633
+ return true;
30634
+ return nowMs - state.lastSurfacedAtMs >= SURFACE_WINDOW_MS;
30635
+ }
30636
+
31802
30637
  // ../auth/src/robotClientFallback.ts
31803
30638
  init_src();
31804
30639
  var DEFAULT_TIMEOUT_MS = 1000;
31805
30640
  var CLOSE_TIMEOUT_MS = 500;
31806
- var NOTICE_SENTINEL = Symbol.for("@uipath/auth/robotFallbackNoticePrinted");
31807
- var printNoticeOnce = () => {
31808
- const slot = globalThis;
31809
- if (slot[NOTICE_SENTINEL])
31810
- return;
31811
- slot[NOTICE_SENTINEL] = true;
31812
- catchError2(() => process.stderr.write(`Using UiPath Robot credentials. Run 'uip login' for a dedicated session.
31813
- `));
31814
- };
31815
30641
  var ROBOT_USER_SERVICES_PIPE = "UiPathUserServices";
31816
30642
  var ROBOT_USER_SERVICES_ALTERNATE_PIPE = `${ROBOT_USER_SERVICES_PIPE}Alternate`;
31817
30643
  var PIPE_NAME_MAX_LENGTH = 103;
@@ -31927,7 +30753,6 @@ var tryRobotClientFallback = async (options = {}) => {
31927
30753
  issuerFromToken = issClaim;
31928
30754
  }
31929
30755
  }
31930
- printNoticeOnce();
31931
30756
  return {
31932
30757
  accessToken,
31933
30758
  baseUrl: parsedUrl.baseUrl,
@@ -32152,18 +30977,327 @@ var saveEnvFileAsync = async ({
32152
30977
  };
32153
30978
 
32154
30979
  // ../auth/src/loginStatus.ts
32155
- function normalizeTokenRefreshFailure() {
32156
- return "stored refresh token is invalid or expired";
30980
+ var getLoginStatusAsync = async (options = {}) => {
30981
+ return getLoginStatusWithDeps(options);
30982
+ };
30983
+ var getLoginStatusWithDeps = async (options = {}, deps = {}) => {
30984
+ const {
30985
+ resolveEnvFilePath = resolveEnvFilePathAsync,
30986
+ loadEnvFile = loadEnvFileAsync,
30987
+ saveEnvFile = saveEnvFileAsync,
30988
+ getFs = getFileSystem,
30989
+ refreshToken: refreshTokenFn = refreshAccessToken,
30990
+ resolveConfig: resolveConfig2 = resolveConfigAsync,
30991
+ robotFallback = tryRobotClientFallback,
30992
+ loadBreaker = loadRefreshBreaker,
30993
+ saveBreaker = saveRefreshBreaker,
30994
+ clearBreaker = clearRefreshBreaker
30995
+ } = deps;
30996
+ if (isRobotAuthEnforced()) {
30997
+ return resolveRobotEnforcedStatus(robotFallback);
30998
+ }
30999
+ if (isEnvAuthEnabled()) {
31000
+ return readAuthFromEnv();
31001
+ }
31002
+ const activeProfile = getActiveAuthProfile();
31003
+ const activeProfileFilePath = getActiveAuthProfileFilePath();
31004
+ const usingActiveProfile = activeProfile !== undefined && (options.envFilePath === undefined || options.envFilePath === activeProfileFilePath);
31005
+ const envFilePath = options.envFilePath ?? activeProfileFilePath ?? DEFAULT_ENV_FILENAME;
31006
+ const { ensureTokenValidityMinutes } = options;
31007
+ const { absolutePath } = await resolveEnvFilePath(envFilePath);
31008
+ if (absolutePath === undefined) {
31009
+ if (usingActiveProfile) {
31010
+ return {
31011
+ loginStatus: "Not logged in",
31012
+ hint: `No credentials found for profile "${activeProfile}". Run 'uip login --profile ${activeProfile}' to authenticate this profile.`
31013
+ };
31014
+ }
31015
+ return resolveBorrowedRobotStatus(robotFallback);
31016
+ }
31017
+ const loaded = await loadFileCredentials(loadEnvFile, absolutePath);
31018
+ if ("status" in loaded) {
31019
+ return loaded.status;
31020
+ }
31021
+ const { credentials } = loaded;
31022
+ const globalHint = () => usingActiveProfile ? Promise.resolve(undefined) : getGlobalCredsHint(getFs, loadEnvFile, absolutePath, envFilePath);
31023
+ const expiration = getTokenExpiration(credentials.UIPATH_ACCESS_TOKEN);
31024
+ const outerThreshold = computeExpirationThreshold(ensureTokenValidityMinutes);
31025
+ let tokens = {
31026
+ accessToken: credentials.UIPATH_ACCESS_TOKEN,
31027
+ refreshToken: credentials.UIPATH_REFRESH_TOKEN,
31028
+ expiration,
31029
+ lockReleaseFailed: false
31030
+ };
31031
+ const refreshToken = credentials.UIPATH_REFRESH_TOKEN;
31032
+ if (expiration && expiration <= outerThreshold && refreshToken) {
31033
+ const refreshed = await attemptRefresh({
31034
+ absolutePath,
31035
+ credentials,
31036
+ accessToken: credentials.UIPATH_ACCESS_TOKEN,
31037
+ refreshToken,
31038
+ expiration,
31039
+ ensureTokenValidityMinutes,
31040
+ getFs,
31041
+ loadEnvFile,
31042
+ saveEnvFile,
31043
+ refreshFn: refreshTokenFn,
31044
+ resolveConfig: resolveConfig2,
31045
+ loadBreaker,
31046
+ saveBreaker,
31047
+ clearBreaker,
31048
+ globalHint
31049
+ });
31050
+ if (refreshed.kind === "terminal") {
31051
+ return refreshed.status;
31052
+ }
31053
+ tokens = refreshed.tokens;
31054
+ }
31055
+ return buildFileStatus(tokens, credentials, globalHint);
31056
+ };
31057
+ async function resolveRobotEnforcedStatus(robotFallback) {
31058
+ if (isEnvAuthEnabled()) {
31059
+ throw new EnvAuthConfigError(`${ENV_AUTH_ENABLE_VAR}=true and ${ENFORCE_ROBOT_AUTH_VAR}=true ` + `are mutually exclusive. Unset one of them and re-run.`);
31060
+ }
31061
+ const robotCreds = await robotFallback({ force: true });
31062
+ if (!robotCreds) {
31063
+ return {
31064
+ loginStatus: "Not logged in",
31065
+ 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.`
31066
+ };
31067
+ }
31068
+ return buildRobotStatus(robotCreds);
32157
31069
  }
32158
- function normalizeTokenRefreshUnavailableFailure() {
32159
- return "token refresh failed before authentication completed";
31070
+ async function resolveBorrowedRobotStatus(robotFallback) {
31071
+ const robotCreds = await robotFallback();
31072
+ return robotCreds ? buildRobotStatus(robotCreds) : { loginStatus: "Not logged in" };
32160
31073
  }
32161
- function errorMessage(error) {
32162
- return error instanceof Error ? error.message : String(error);
31074
+ async function loadFileCredentials(loadEnvFile, absolutePath) {
31075
+ let credentials;
31076
+ try {
31077
+ credentials = await loadEnvFile({ envPath: absolutePath });
31078
+ } catch (error) {
31079
+ if (isFileNotFoundError(error)) {
31080
+ return { status: { loginStatus: "Not logged in" } };
31081
+ }
31082
+ throw error;
31083
+ }
31084
+ if (!credentials.UIPATH_ACCESS_TOKEN) {
31085
+ return { status: { loginStatus: "Not logged in" } };
31086
+ }
31087
+ return { credentials };
31088
+ }
31089
+ async function getGlobalCredsHint(getFs, loadEnvFile, absolutePath, envFilePath) {
31090
+ const fs7 = getFs();
31091
+ const globalPath = fs7.path.join(fs7.env.homedir(), envFilePath);
31092
+ if (absolutePath === globalPath)
31093
+ return;
31094
+ if (!await fs7.exists(globalPath))
31095
+ return;
31096
+ try {
31097
+ const globalCreds = await loadEnvFile({ envPath: globalPath });
31098
+ if (!globalCreds.UIPATH_ACCESS_TOKEN)
31099
+ return;
31100
+ const globalExp = getTokenExpiration(globalCreds.UIPATH_ACCESS_TOKEN);
31101
+ if (globalExp && globalExp <= new Date)
31102
+ return;
31103
+ 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.`;
31104
+ } catch {
31105
+ return;
31106
+ }
32163
31107
  }
32164
31108
  function computeExpirationThreshold(ensureTokenValidityMinutes) {
32165
31109
  return new Date(Date.now() + (ensureTokenValidityMinutes ?? 0) * 60 * 1000);
32166
31110
  }
31111
+ async function attemptRefresh(ctx) {
31112
+ const shortCircuit = await circuitBreakerShortCircuit(ctx);
31113
+ if (shortCircuit) {
31114
+ return { kind: "terminal", status: shortCircuit };
31115
+ }
31116
+ let release;
31117
+ try {
31118
+ release = await ctx.getFs().acquireLock(ctx.absolutePath);
31119
+ } catch (error) {
31120
+ return {
31121
+ kind: "terminal",
31122
+ status: await lockAcquireFailureStatus(ctx, error)
31123
+ };
31124
+ }
31125
+ let lockedFailure;
31126
+ let lockReleaseFailed = false;
31127
+ let success;
31128
+ try {
31129
+ const outcome = await runRefreshLocked({
31130
+ absolutePath: ctx.absolutePath,
31131
+ refreshToken: ctx.refreshToken,
31132
+ customAuthority: ctx.credentials.UIPATH_URL,
31133
+ ensureTokenValidityMinutes: ctx.ensureTokenValidityMinutes,
31134
+ loadEnvFile: ctx.loadEnvFile,
31135
+ saveEnvFile: ctx.saveEnvFile,
31136
+ refreshFn: ctx.refreshFn,
31137
+ resolveConfig: ctx.resolveConfig,
31138
+ loadBreaker: ctx.loadBreaker,
31139
+ saveBreaker: ctx.saveBreaker,
31140
+ clearBreaker: ctx.clearBreaker
31141
+ });
31142
+ if (outcome.kind === "fail") {
31143
+ lockedFailure = outcome.status;
31144
+ } else {
31145
+ success = outcome;
31146
+ }
31147
+ } finally {
31148
+ try {
31149
+ await release();
31150
+ } catch {
31151
+ lockReleaseFailed = true;
31152
+ }
31153
+ }
31154
+ if (lockedFailure) {
31155
+ const globalHint = await ctx.globalHint();
31156
+ const base = globalHint ? { ...lockedFailure, loginStatus: "Expired", hint: globalHint } : lockedFailure;
31157
+ return {
31158
+ kind: "terminal",
31159
+ status: lockReleaseFailed ? { ...base, lockReleaseFailed: true } : base
31160
+ };
31161
+ }
31162
+ return {
31163
+ kind: "refreshed",
31164
+ tokens: {
31165
+ accessToken: success?.accessToken,
31166
+ refreshToken: success?.refreshToken,
31167
+ expiration: success?.expiration,
31168
+ tokenRefresh: success?.tokenRefresh,
31169
+ persistenceWarning: success?.persistenceWarning,
31170
+ lockReleaseFailed
31171
+ }
31172
+ };
31173
+ }
31174
+ async function buildFileStatus(tokens, credentials, globalHint) {
31175
+ const result = {
31176
+ loginStatus: tokens.expiration && tokens.expiration <= new Date ? "Expired" : "Logged in",
31177
+ accessToken: tokens.accessToken,
31178
+ refreshToken: tokens.refreshToken,
31179
+ baseUrl: credentials.UIPATH_URL,
31180
+ organizationName: credentials.UIPATH_ORGANIZATION_NAME,
31181
+ organizationId: credentials.UIPATH_ORGANIZATION_ID,
31182
+ tenantName: credentials.UIPATH_TENANT_NAME,
31183
+ tenantId: credentials.UIPATH_TENANT_ID,
31184
+ expiration: tokens.expiration,
31185
+ source: "file" /* File */,
31186
+ ...tokens.persistenceWarning ? { hint: tokens.persistenceWarning, persistenceFailed: true } : {},
31187
+ ...tokens.lockReleaseFailed ? { lockReleaseFailed: true } : {},
31188
+ ...tokens.tokenRefresh ? { tokenRefresh: tokens.tokenRefresh } : {}
31189
+ };
31190
+ if (result.loginStatus === "Expired") {
31191
+ const hint = await globalHint();
31192
+ if (hint) {
31193
+ result.hint = hint;
31194
+ }
31195
+ }
31196
+ return result;
31197
+ }
31198
+ function buildRobotStatus(robotCreds) {
31199
+ return {
31200
+ loginStatus: "Logged in",
31201
+ accessToken: robotCreds.accessToken,
31202
+ baseUrl: robotCreds.baseUrl,
31203
+ organizationName: robotCreds.organizationName,
31204
+ organizationId: robotCreds.organizationId,
31205
+ tenantName: robotCreds.tenantName,
31206
+ tenantId: robotCreds.tenantId,
31207
+ issuer: robotCreds.issuer,
31208
+ expiration: getTokenExpiration(robotCreds.accessToken),
31209
+ source: "robot" /* Robot */
31210
+ };
31211
+ }
31212
+ var isFileNotFoundError = (error) => {
31213
+ if (!(error instanceof Object))
31214
+ return false;
31215
+ return error.code === "ENOENT";
31216
+ };
31217
+ async function circuitBreakerShortCircuit(ctx) {
31218
+ const {
31219
+ absolutePath,
31220
+ refreshToken,
31221
+ accessToken,
31222
+ credentials,
31223
+ expiration,
31224
+ loadBreaker,
31225
+ saveBreaker,
31226
+ clearBreaker
31227
+ } = ctx;
31228
+ const fingerprint = await refreshTokenFingerprint(refreshToken);
31229
+ const breaker = await loadBreaker(absolutePath).catch(() => ({}));
31230
+ if (breaker.deadTokenFp && breaker.deadTokenFp !== fingerprint) {
31231
+ await clearBreaker(absolutePath);
31232
+ breaker.deadTokenFp = undefined;
31233
+ }
31234
+ const nowMs = Date.now();
31235
+ const tokenIsDead = breaker.deadTokenFp === fingerprint;
31236
+ const inBackoff = breaker.backoffUntilMs !== undefined && nowMs < breaker.backoffUntilMs;
31237
+ if (!tokenIsDead && !inBackoff)
31238
+ return;
31239
+ const globalHint = await ctx.globalHint();
31240
+ const suppressed = !shouldSurface(breaker, nowMs);
31241
+ if (!suppressed) {
31242
+ await saveBreaker(absolutePath, {
31243
+ ...breaker,
31244
+ lastSurfacedAtMs: nowMs
31245
+ });
31246
+ }
31247
+ 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>.";
31248
+ const backoffHint = "Token refresh is temporarily backed off after a recent network error and will retry automatically once the backoff window elapses.";
31249
+ return {
31250
+ loginStatus: globalHint ? "Expired" : "Refresh Failed",
31251
+ ...globalHint ? {
31252
+ accessToken,
31253
+ refreshToken,
31254
+ baseUrl: credentials.UIPATH_URL,
31255
+ organizationName: credentials.UIPATH_ORGANIZATION_NAME,
31256
+ organizationId: credentials.UIPATH_ORGANIZATION_ID,
31257
+ tenantName: credentials.UIPATH_TENANT_NAME,
31258
+ tenantId: credentials.UIPATH_TENANT_ID,
31259
+ expiration,
31260
+ source: "file" /* File */
31261
+ } : {},
31262
+ hint: globalHint ?? (tokenIsDead ? deadHint : backoffHint),
31263
+ refreshCircuitOpen: true,
31264
+ refreshTelemetrySuppressed: suppressed,
31265
+ tokenRefresh: { attempted: false, success: false }
31266
+ };
31267
+ }
31268
+ async function lockAcquireFailureStatus(ctx, error) {
31269
+ const msg = errorMessage(error);
31270
+ const globalHint = await ctx.globalHint();
31271
+ if (globalHint) {
31272
+ return {
31273
+ loginStatus: "Expired",
31274
+ accessToken: ctx.accessToken,
31275
+ refreshToken: ctx.refreshToken,
31276
+ baseUrl: ctx.credentials.UIPATH_URL,
31277
+ organizationName: ctx.credentials.UIPATH_ORGANIZATION_NAME,
31278
+ organizationId: ctx.credentials.UIPATH_ORGANIZATION_ID,
31279
+ tenantName: ctx.credentials.UIPATH_TENANT_NAME,
31280
+ tenantId: ctx.credentials.UIPATH_TENANT_ID,
31281
+ expiration: ctx.expiration,
31282
+ source: "file" /* File */,
31283
+ hint: globalHint,
31284
+ tokenRefresh: {
31285
+ attempted: false,
31286
+ success: false,
31287
+ errorMessage: `lock acquisition failed: ${msg}`
31288
+ }
31289
+ };
31290
+ }
31291
+ return {
31292
+ loginStatus: "Refresh Failed",
31293
+ 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.",
31294
+ tokenRefresh: {
31295
+ attempted: false,
31296
+ success: false,
31297
+ errorMessage: `lock acquisition failed: ${msg}`
31298
+ }
31299
+ };
31300
+ }
32167
31301
  async function runRefreshLocked(inputs) {
32168
31302
  const {
32169
31303
  absolutePath,
@@ -32173,7 +31307,10 @@ async function runRefreshLocked(inputs) {
32173
31307
  loadEnvFile,
32174
31308
  saveEnvFile,
32175
31309
  refreshFn,
32176
- resolveConfig: resolveConfig2
31310
+ resolveConfig: resolveConfig2,
31311
+ loadBreaker,
31312
+ saveBreaker,
31313
+ clearBreaker
32177
31314
  } = inputs;
32178
31315
  const expirationThreshold = computeExpirationThreshold(ensureTokenValidityMinutes);
32179
31316
  let fresh;
@@ -32196,6 +31333,7 @@ async function runRefreshLocked(inputs) {
32196
31333
  const freshAccess = fresh.UIPATH_ACCESS_TOKEN;
32197
31334
  const freshExp = freshAccess ? getTokenExpiration(freshAccess) : undefined;
32198
31335
  if (freshAccess && freshExp && freshExp > expirationThreshold) {
31336
+ await clearBreaker(absolutePath);
32199
31337
  return {
32200
31338
  kind: "ok",
32201
31339
  accessToken: freshAccess,
@@ -32219,8 +31357,21 @@ async function runRefreshLocked(inputs) {
32219
31357
  refreshedRefresh = refreshed.refreshToken;
32220
31358
  } catch (error) {
32221
31359
  const isOAuthFailure = isTokenRefreshOAuthFailure(error);
32222
- 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.";
31360
+ 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.";
32223
31361
  const message = isOAuthFailure ? normalizeTokenRefreshFailure() : normalizeTokenRefreshUnavailableFailure();
31362
+ const fp = await refreshTokenFingerprint(tokenForIdP);
31363
+ if (isOAuthFailure) {
31364
+ await saveBreaker(absolutePath, { deadTokenFp: fp });
31365
+ } else {
31366
+ const prior = await loadBreaker(absolutePath).catch(() => ({}));
31367
+ const attempts = (prior.attempts ?? 0) + 1;
31368
+ await saveBreaker(absolutePath, {
31369
+ ...prior,
31370
+ deadTokenFp: undefined,
31371
+ attempts,
31372
+ backoffUntilMs: Date.now() + nextBackoffMs(attempts)
31373
+ });
31374
+ }
32224
31375
  return {
32225
31376
  kind: "fail",
32226
31377
  status: {
@@ -32249,6 +31400,7 @@ async function runRefreshLocked(inputs) {
32249
31400
  }
32250
31401
  };
32251
31402
  }
31403
+ await clearBreaker(absolutePath);
32252
31404
  try {
32253
31405
  await saveEnvFile({
32254
31406
  envPath: absolutePath,
@@ -32281,212 +31433,15 @@ async function runRefreshLocked(inputs) {
32281
31433
  };
32282
31434
  }
32283
31435
  }
32284
- var getLoginStatusWithDeps = async (options = {}, deps = {}) => {
32285
- const {
32286
- resolveEnvFilePath = resolveEnvFilePathAsync,
32287
- loadEnvFile = loadEnvFileAsync,
32288
- saveEnvFile = saveEnvFileAsync,
32289
- getFs = getFileSystem,
32290
- refreshToken: refreshTokenFn = refreshAccessToken,
32291
- resolveConfig: resolveConfig2 = resolveConfigAsync,
32292
- robotFallback = tryRobotClientFallback
32293
- } = deps;
32294
- if (isRobotAuthEnforced()) {
32295
- if (isEnvAuthEnabled()) {
32296
- throw new EnvAuthConfigError(`${ENV_AUTH_ENABLE_VAR}=true and ${ENFORCE_ROBOT_AUTH_VAR}=true ` + `are mutually exclusive. Unset one of them and re-run.`);
32297
- }
32298
- const robotCreds = await robotFallback({ force: true });
32299
- if (!robotCreds) {
32300
- return {
32301
- loginStatus: "Not logged in",
32302
- 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.`
32303
- };
32304
- }
32305
- const expiration2 = getTokenExpiration(robotCreds.accessToken);
32306
- return {
32307
- loginStatus: "Logged in",
32308
- accessToken: robotCreds.accessToken,
32309
- baseUrl: robotCreds.baseUrl,
32310
- organizationName: robotCreds.organizationName,
32311
- organizationId: robotCreds.organizationId,
32312
- tenantName: robotCreds.tenantName,
32313
- tenantId: robotCreds.tenantId,
32314
- issuer: robotCreds.issuer,
32315
- expiration: expiration2,
32316
- source: "robot" /* Robot */
32317
- };
32318
- }
32319
- if (isEnvAuthEnabled()) {
32320
- return readAuthFromEnv();
32321
- }
32322
- const { envFilePath = DEFAULT_ENV_FILENAME, ensureTokenValidityMinutes } = options;
32323
- const { absolutePath } = await resolveEnvFilePath(envFilePath);
32324
- if (absolutePath === undefined) {
32325
- const robotCreds = await robotFallback();
32326
- if (robotCreds) {
32327
- const expiration2 = getTokenExpiration(robotCreds.accessToken);
32328
- const status = {
32329
- loginStatus: "Logged in",
32330
- accessToken: robotCreds.accessToken,
32331
- baseUrl: robotCreds.baseUrl,
32332
- organizationName: robotCreds.organizationName,
32333
- organizationId: robotCreds.organizationId,
32334
- tenantName: robotCreds.tenantName,
32335
- tenantId: robotCreds.tenantId,
32336
- issuer: robotCreds.issuer,
32337
- expiration: expiration2,
32338
- source: "robot" /* Robot */
32339
- };
32340
- return status;
32341
- }
32342
- return { loginStatus: "Not logged in" };
32343
- }
32344
- let credentials;
32345
- try {
32346
- credentials = await loadEnvFile({ envPath: absolutePath });
32347
- } catch (error) {
32348
- if (isFileNotFoundError(error)) {
32349
- return { loginStatus: "Not logged in" };
32350
- }
32351
- throw error;
32352
- }
32353
- if (!credentials.UIPATH_ACCESS_TOKEN) {
32354
- return { loginStatus: "Not logged in" };
32355
- }
32356
- let accessToken = credentials.UIPATH_ACCESS_TOKEN;
32357
- let refreshToken = credentials.UIPATH_REFRESH_TOKEN;
32358
- let expiration = getTokenExpiration(accessToken);
32359
- let persistenceWarning;
32360
- let lockReleaseFailed = false;
32361
- let tokenRefresh;
32362
- const outerThreshold = computeExpirationThreshold(ensureTokenValidityMinutes);
32363
- const tryGlobalCredsHint = async () => {
32364
- const fs7 = getFs();
32365
- const globalPath = fs7.path.join(fs7.env.homedir(), envFilePath);
32366
- if (absolutePath === globalPath)
32367
- return;
32368
- if (!await fs7.exists(globalPath))
32369
- return;
32370
- try {
32371
- const globalCreds = await loadEnvFile({ envPath: globalPath });
32372
- if (!globalCreds.UIPATH_ACCESS_TOKEN)
32373
- return;
32374
- const globalExp = getTokenExpiration(globalCreds.UIPATH_ACCESS_TOKEN);
32375
- if (globalExp && globalExp <= new Date)
32376
- return;
32377
- 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.`;
32378
- } catch {
32379
- return;
32380
- }
32381
- };
32382
- if (expiration && expiration <= outerThreshold && refreshToken) {
32383
- let release;
32384
- try {
32385
- release = await getFs().acquireLock(absolutePath);
32386
- } catch (error) {
32387
- const msg = errorMessage(error);
32388
- const globalHint = await tryGlobalCredsHint();
32389
- if (globalHint) {
32390
- return {
32391
- loginStatus: "Expired",
32392
- accessToken,
32393
- refreshToken,
32394
- baseUrl: credentials.UIPATH_URL,
32395
- organizationName: credentials.UIPATH_ORGANIZATION_NAME,
32396
- organizationId: credentials.UIPATH_ORGANIZATION_ID,
32397
- tenantName: credentials.UIPATH_TENANT_NAME,
32398
- tenantId: credentials.UIPATH_TENANT_ID,
32399
- expiration,
32400
- source: "file" /* File */,
32401
- hint: globalHint,
32402
- tokenRefresh: {
32403
- attempted: false,
32404
- success: false,
32405
- errorMessage: `lock acquisition failed: ${msg}`
32406
- }
32407
- };
32408
- }
32409
- return {
32410
- loginStatus: "Refresh Failed",
32411
- 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.",
32412
- tokenRefresh: {
32413
- attempted: false,
32414
- success: false,
32415
- errorMessage: `lock acquisition failed: ${msg}`
32416
- }
32417
- };
32418
- }
32419
- let lockedFailure;
32420
- try {
32421
- const outcome = await runRefreshLocked({
32422
- absolutePath,
32423
- refreshToken,
32424
- customAuthority: credentials.UIPATH_URL,
32425
- ensureTokenValidityMinutes,
32426
- loadEnvFile,
32427
- saveEnvFile,
32428
- refreshFn: refreshTokenFn,
32429
- resolveConfig: resolveConfig2
32430
- });
32431
- if (outcome.kind === "fail") {
32432
- lockedFailure = outcome.status;
32433
- } else {
32434
- accessToken = outcome.accessToken;
32435
- refreshToken = outcome.refreshToken;
32436
- expiration = outcome.expiration;
32437
- tokenRefresh = outcome.tokenRefresh;
32438
- if (outcome.persistenceWarning) {
32439
- persistenceWarning = outcome.persistenceWarning;
32440
- }
32441
- }
32442
- } finally {
32443
- try {
32444
- await release();
32445
- } catch {
32446
- lockReleaseFailed = true;
32447
- }
32448
- }
32449
- if (lockedFailure) {
32450
- const globalHint = await tryGlobalCredsHint();
32451
- const base = globalHint ? {
32452
- ...lockedFailure,
32453
- loginStatus: "Expired",
32454
- hint: globalHint
32455
- } : lockedFailure;
32456
- return lockReleaseFailed ? { ...base, lockReleaseFailed: true } : base;
32457
- }
32458
- }
32459
- const result = {
32460
- loginStatus: expiration && expiration <= new Date ? "Expired" : "Logged in",
32461
- accessToken,
32462
- refreshToken,
32463
- baseUrl: credentials.UIPATH_URL,
32464
- organizationName: credentials.UIPATH_ORGANIZATION_NAME,
32465
- organizationId: credentials.UIPATH_ORGANIZATION_ID,
32466
- tenantName: credentials.UIPATH_TENANT_NAME,
32467
- tenantId: credentials.UIPATH_TENANT_ID,
32468
- expiration,
32469
- source: "file" /* File */,
32470
- ...persistenceWarning ? { hint: persistenceWarning, persistenceFailed: true } : {},
32471
- ...lockReleaseFailed ? { lockReleaseFailed: true } : {},
32472
- ...tokenRefresh ? { tokenRefresh } : {}
32473
- };
32474
- if (result.loginStatus === "Expired") {
32475
- const globalHint = await tryGlobalCredsHint();
32476
- if (globalHint) {
32477
- result.hint = globalHint;
32478
- }
32479
- }
32480
- return result;
32481
- };
32482
- var isFileNotFoundError = (error) => {
32483
- if (!(error instanceof Object))
32484
- return false;
32485
- return error.code === "ENOENT";
32486
- };
32487
- var getLoginStatusAsync = async (options = {}) => {
32488
- return getLoginStatusWithDeps(options);
32489
- };
31436
+ function normalizeTokenRefreshFailure() {
31437
+ return "stored refresh token is invalid or expired";
31438
+ }
31439
+ function normalizeTokenRefreshUnavailableFailure() {
31440
+ return "token refresh failed before authentication completed";
31441
+ }
31442
+ function errorMessage(error) {
31443
+ return error instanceof Error ? error.message : String(error);
31444
+ }
32490
31445
 
32491
31446
  // ../auth/src/authContext.ts
32492
31447
  var getAuthContext = async (options = {}) => {
@@ -32521,6 +31476,14 @@ var getAuthContext = async (options = {}) => {
32521
31476
  };
32522
31477
  // ../auth/src/interactive.ts
32523
31478
  init_src();
31479
+
31480
+ // ../auth/src/selectTenant.ts
31481
+ var TENANT_SELECTION_REQUIRED_CODE = "TENANT_SELECTION_REQUIRED";
31482
+ var INVALID_TENANT_CODE = "INVALID_TENANT";
31483
+ var TENANT_SELECTION_CODES = new Set([
31484
+ TENANT_SELECTION_REQUIRED_CODE,
31485
+ INVALID_TENANT_CODE
31486
+ ]);
32524
31487
  // ../auth/src/logout.ts
32525
31488
  init_src();
32526
31489
 
@@ -32800,7 +31763,7 @@ class VoidApiResponse3 {
32800
31763
  var package_default3 = {
32801
31764
  name: "@uipath/orchestrator-sdk",
32802
31765
  license: "MIT",
32803
- version: "1.196.0",
31766
+ version: "1.197.0",
32804
31767
  repository: {
32805
31768
  type: "git",
32806
31769
  url: "https://github.com/UiPath/cli.git",
@@ -32834,7 +31797,7 @@ var package_default3 = {
32834
31797
  ],
32835
31798
  private: true,
32836
31799
  scripts: {
32837
- 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",
31800
+ 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",
32838
31801
  generate: "bun run src/scripts/generate-sdk.ts",
32839
31802
  lint: "biome check .",
32840
31803
  test: "vitest run",
@@ -33428,3 +32391,5 @@ async function mapUploadError(uploadError) {
33428
32391
  export {
33429
32392
  publishSolutionAsync
33430
32393
  };
32394
+
32395
+ //# debugId=C0A60C76CC995C4964756E2164756E21