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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/index.js +828 -1784
  2. package/dist/tool.js +829 -1784
  3. package/package.json +2 -2
package/dist/tool.js CHANGED
@@ -19555,9 +19555,9 @@ var require_utils = __commonJS((exports, module) => {
19555
19555
  return typeof input === "string" ? encoder(input) : Buffer.alloc(0);
19556
19556
  }
19557
19557
  };
19558
- Utils.readBigUInt64LE = function(buffer, index2) {
19559
- const lo = buffer.readUInt32LE(index2);
19560
- const hi = buffer.readUInt32LE(index2 + 4);
19558
+ Utils.readBigUInt64LE = function(buffer, index) {
19559
+ const lo = buffer.readUInt32LE(index);
19560
+ const hi = buffer.readUInt32LE(index + 4);
19561
19561
  return hi * 4294967296 + lo;
19562
19562
  };
19563
19563
  Utils.fromDOS2Date = function(val) {
@@ -20595,9 +20595,9 @@ var require_zipFile = __commonJS((exports, module) => {
20595
20595
  throw Utils.Errors.DISK_ENTRY_TOO_LARGE();
20596
20596
  }
20597
20597
  entryList = new Array(mainHeader.diskEntries);
20598
- var index2 = mainHeader.offset;
20598
+ var index = mainHeader.offset;
20599
20599
  for (var i = 0;i < entryList.length; i++) {
20600
- var tmp = index2, entry = new ZipEntry(opts, inBuffer);
20600
+ var tmp = index, entry = new ZipEntry(opts, inBuffer);
20601
20601
  entry.header = inBuffer.slice(tmp, tmp += Utils.Constants.CENHDR);
20602
20602
  entry.entryName = inBuffer.slice(tmp, tmp += entry.header.fileNameLength);
20603
20603
  if (entry.header.extraLength) {
@@ -20605,7 +20605,7 @@ var require_zipFile = __commonJS((exports, module) => {
20605
20605
  }
20606
20606
  if (entry.header.commentLength)
20607
20607
  entry.comment = inBuffer.slice(tmp, tmp + entry.header.commentLength);
20608
- index2 += entry.header.centralHeaderSize;
20608
+ index += entry.header.centralHeaderSize;
20609
20609
  entryList[i] = entry;
20610
20610
  entryTable[entry.entryName] = entry;
20611
20611
  }
@@ -20701,9 +20701,9 @@ var require_zipFile = __commonJS((exports, module) => {
20701
20701
  readEntries();
20702
20702
  }
20703
20703
  const entry = entryTable[entryName];
20704
- const index2 = entryList.indexOf(entry);
20705
- if (index2 >= 0) {
20706
- entryList.splice(index2, 1);
20704
+ const index = entryList.indexOf(entry);
20705
+ if (index >= 0) {
20706
+ entryList.splice(index, 1);
20707
20707
  delete entryTable[entryName];
20708
20708
  mainHeader.totalEntries = entryList.length;
20709
20709
  }
@@ -21435,7 +21435,7 @@ var require_adm_zip = __commonJS((exports, module) => {
21435
21435
  var package_default = {
21436
21436
  name: "@uipath/audit-tool",
21437
21437
  license: "MIT",
21438
- version: "1.196.0",
21438
+ version: "1.197.0-preview.59",
21439
21439
  description: "CLI plugin for the UiPath Audit Service — query event sources, paginate events, and export ZIPs from the long-term store.",
21440
21440
  private: false,
21441
21441
  repository: {
@@ -21446,7 +21446,9 @@ var package_default = {
21446
21446
  publishConfig: {
21447
21447
  registry: "https://npm.pkg.github.com/@uipath"
21448
21448
  },
21449
- keywords: ["cli-tool"],
21449
+ keywords: [
21450
+ "cli-tool"
21451
+ ],
21450
21452
  type: "module",
21451
21453
  main: "./dist/tool.js",
21452
21454
  exports: {
@@ -21455,9 +21457,11 @@ var package_default = {
21455
21457
  bin: {
21456
21458
  "audit-tool": "./dist/index.js"
21457
21459
  },
21458
- files: ["dist"],
21460
+ files: [
21461
+ "dist"
21462
+ ],
21459
21463
  scripts: {
21460
- build: "bun build ./src/tool.ts --outdir dist --format esm --target node --external commander && bun build ./src/index.ts --outdir dist --format esm --target node",
21464
+ build: "bun build ./src/tool.ts --outdir dist --format esm --target node --external commander --sourcemap=linked && bun build ./src/index.ts --outdir dist --format esm --target node --sourcemap=linked",
21461
21465
  package: "bun run build && bun pm pack",
21462
21466
  lint: "biome check .",
21463
21467
  "lint:fix": "biome check --write .",
@@ -21506,6 +21510,12 @@ function singleton(ctorOrName) {
21506
21510
  };
21507
21511
  }
21508
21512
 
21513
+ // ../../common/src/telemetry/global-telemetry-properties.ts
21514
+ var telemetryPropsSlot = singleton("TelemetryDefaultProps");
21515
+ function getGlobalTelemetryProperties() {
21516
+ return telemetryPropsSlot.get();
21517
+ }
21518
+
21509
21519
  // ../../common/src/sdk-user-agent.ts
21510
21520
  var USER_AGENT_HEADER = "User-Agent";
21511
21521
  var sdkUserAgentHostToken = singleton("SdkUserAgentHostToken");
@@ -21529,8 +21539,8 @@ function appendUserAgentToken(value, userAgent) {
21529
21539
  function getEffectiveUserAgent(userAgent) {
21530
21540
  return appendUserAgentToken(sdkUserAgentHostToken.get(), userAgent);
21531
21541
  }
21532
- function isHeadersLike(headers) {
21533
- return typeof headers === "object" && headers !== null && "get" in headers && typeof headers.get === "function" && "set" in headers && typeof headers.set === "function";
21542
+ function getHeaderName(headers, headerName) {
21543
+ return Object.keys(headers).find((key) => key.toLowerCase() === headerName.toLowerCase());
21534
21544
  }
21535
21545
  function getSdkUserAgentToken(pkg) {
21536
21546
  const packageName = pkg.name.replace(/^@uipath\//, "");
@@ -21538,59 +21548,31 @@ function getSdkUserAgentToken(pkg) {
21538
21548
  }
21539
21549
  function addSdkUserAgentHeader(headers, userAgent) {
21540
21550
  const result = { ...headers ?? {} };
21541
- const effectiveUserAgent = getEffectiveUserAgent(userAgent);
21542
- const headerName = Object.keys(result).find((key) => key.toLowerCase() === USER_AGENT_HEADER.toLowerCase());
21543
- if (headerName) {
21544
- result[headerName] = appendUserAgentToken(result[headerName], effectiveUserAgent);
21545
- } else {
21546
- result[USER_AGENT_HEADER] = effectiveUserAgent;
21547
- }
21551
+ const headerName = getHeaderName(result, USER_AGENT_HEADER);
21552
+ result[headerName ?? USER_AGENT_HEADER] = appendUserAgentToken(headerName ? result[headerName] : undefined, getEffectiveUserAgent(userAgent));
21548
21553
  return result;
21549
21554
  }
21550
- function withSdkUserAgentHeader(headers, userAgent) {
21551
- const effectiveUserAgent = getEffectiveUserAgent(userAgent);
21552
- if (isHeadersLike(headers)) {
21553
- headers.set(USER_AGENT_HEADER, appendUserAgentToken(headers.get(USER_AGENT_HEADER), effectiveUserAgent));
21554
- return headers;
21555
- }
21556
- if (Array.isArray(headers)) {
21557
- const result = headers.map((entry) => {
21558
- const [key, value] = entry;
21559
- return [key, value];
21560
- });
21561
- const headerIndex = result.findIndex(([key]) => key.toLowerCase() === USER_AGENT_HEADER.toLowerCase());
21562
- if (headerIndex >= 0) {
21563
- const [key, value] = result[headerIndex];
21564
- result[headerIndex] = [
21565
- key,
21566
- appendUserAgentToken(value, effectiveUserAgent)
21567
- ];
21568
- } else {
21569
- result.push([USER_AGENT_HEADER, effectiveUserAgent]);
21570
- }
21571
- return result;
21572
- }
21573
- return addSdkUserAgentHeader(typeof headers === "object" && headers !== null ? { ...headers } : {}, effectiveUserAgent);
21555
+ function asHeaderRecord(headers) {
21556
+ return typeof headers === "object" && headers !== null ? { ...headers } : {};
21574
21557
  }
21575
- function withUserAgentInitOverride(initOverrides, userAgent) {
21558
+ function withForwardedHeadersInitOverride(initOverrides, forward) {
21576
21559
  return async (requestContext) => {
21577
- const initWithUserAgent = {
21560
+ const initWithHeaders = {
21578
21561
  ...requestContext.init,
21579
- headers: withSdkUserAgentHeader(requestContext.init.headers, userAgent)
21562
+ headers: forward(asHeaderRecord(requestContext.init.headers))
21580
21563
  };
21581
21564
  const override = typeof initOverrides === "function" ? await initOverrides({
21582
21565
  ...requestContext,
21583
- init: initWithUserAgent
21566
+ init: initWithHeaders
21584
21567
  }) : initOverrides;
21585
21568
  return {
21586
21569
  ...override ?? {},
21587
- headers: withSdkUserAgentHeader(override?.headers ?? initWithUserAgent.headers, userAgent)
21570
+ headers: forward(asHeaderRecord(override?.headers ?? initWithHeaders.headers))
21588
21571
  };
21589
21572
  };
21590
21573
  }
21591
- function installSdkUserAgentHeader(BaseApiClass, userAgent) {
21574
+ function installRequestHeaderForwarding(BaseApiClass, patchKey, forward) {
21592
21575
  const prototype = BaseApiClass.prototype;
21593
- const patchKey = userAgentPatchKey(userAgent);
21594
21576
  if (prototype[patchKey]) {
21595
21577
  return;
21596
21578
  }
@@ -21598,13 +21580,16 @@ function installSdkUserAgentHeader(BaseApiClass, userAgent) {
21598
21580
  throw new Error("Generated BaseAPI request function not found.");
21599
21581
  }
21600
21582
  const originalRequest = prototype.request;
21601
- prototype.request = function requestWithUserAgent(context, initOverrides) {
21602
- return originalRequest.call(this, context, withUserAgentInitOverride(initOverrides, userAgent));
21583
+ prototype.request = function requestWithForwardedHeaders(context, initOverrides) {
21584
+ return originalRequest.call(this, context, withForwardedHeadersInitOverride(initOverrides, forward));
21603
21585
  };
21604
21586
  Object.defineProperty(prototype, patchKey, {
21605
21587
  value: true
21606
21588
  });
21607
21589
  }
21590
+ function installSdkUserAgentHeader(BaseApiClass, userAgent) {
21591
+ installRequestHeaderForwarding(BaseApiClass, userAgentPatchKey(userAgent), (headers) => addSdkUserAgentHeader(headers, userAgent));
21592
+ }
21608
21593
 
21609
21594
  // ../audit-sdk/generated/src/runtime.ts
21610
21595
  var BASE_PATH = "https://localhost:7008".replace(/\/+$/, "");
@@ -21858,7 +21843,7 @@ class VoidApiResponse {
21858
21843
  var package_default2 = {
21859
21844
  name: "@uipath/audit-sdk",
21860
21845
  license: "MIT",
21861
- version: "1.196.0",
21846
+ version: "1.197.0",
21862
21847
  description: "SDK for the UiPath Audit Service — query audit event sources, list events, and download long-term-store exports.",
21863
21848
  repository: {
21864
21849
  type: "git",
@@ -21868,7 +21853,11 @@ var package_default2 = {
21868
21853
  publishConfig: {
21869
21854
  registry: "https://npm.pkg.github.com/@uipath"
21870
21855
  },
21871
- keywords: ["uipath", "audit", "sdk"],
21856
+ keywords: [
21857
+ "uipath",
21858
+ "audit",
21859
+ "sdk"
21860
+ ],
21872
21861
  type: "module",
21873
21862
  main: "./dist/index.js",
21874
21863
  types: "./dist/src/index.d.ts",
@@ -21878,10 +21867,12 @@ var package_default2 = {
21878
21867
  default: "./dist/index.js"
21879
21868
  }
21880
21869
  },
21881
- files: ["dist"],
21870
+ files: [
21871
+ "dist"
21872
+ ],
21882
21873
  private: true,
21883
21874
  scripts: {
21884
- build: "bun build ./src/index.ts --outdir dist --format esm --target node && tsc -p tsconfig.build.json --noCheck",
21875
+ build: "bun build ./src/index.ts --outdir dist --format esm --target node --sourcemap=linked && tsc -p tsconfig.build.json --noCheck",
21885
21876
  generate: "bun run src/scripts/generate-sdk.ts",
21886
21877
  lint: "biome check ."
21887
21878
  },
@@ -22178,6 +22169,12 @@ var normalizeAndValidateBaseUrl = (rawUrl) => {
22178
22169
  }
22179
22170
  return url.pathname.length > 1 ? url.origin : baseUrl;
22180
22171
  };
22172
+ var resolveScopes = (isExternalAppAuth, customScopes, fileScopes) => {
22173
+ const requestedScopes = customScopes?.length ? customScopes : fileScopes ?? [];
22174
+ if (isExternalAppAuth)
22175
+ return requestedScopes;
22176
+ return [...new Set([...DEFAULT_SCOPES, ...requestedScopes])];
22177
+ };
22181
22178
  var resolveConfigAsync = async ({
22182
22179
  customAuthority,
22183
22180
  customClientId,
@@ -22208,7 +22205,7 @@ var resolveConfigAsync = async ({
22208
22205
  clientSecret = fileAuth.clientSecret;
22209
22206
  }
22210
22207
  const isExternalAppAuth = clientId !== DEFAULT_CLIENT_ID && Boolean(clientSecret);
22211
- const scopes = customScopes && customScopes.length > 0 ? customScopes : fileAuth.scopes && fileAuth.scopes.length > 0 ? fileAuth.scopes : isExternalAppAuth ? [] : DEFAULT_SCOPES;
22208
+ const scopes = resolveScopes(isExternalAppAuth, customScopes, fileAuth.scopes);
22212
22209
  return {
22213
22210
  clientId,
22214
22211
  clientSecret,
@@ -22223,6 +22220,76 @@ var resolveConfigAsync = async ({
22223
22220
  init_constants();
22224
22221
  // ../../auth/src/loginStatus.ts
22225
22222
  init_src();
22223
+
22224
+ // ../../auth/src/authProfile.ts
22225
+ init_src();
22226
+ init_constants();
22227
+ var DEFAULT_AUTH_PROFILE = "default";
22228
+ var PROFILE_DIR = "profiles";
22229
+ var PROFILE_NAME_RE = /^[A-Za-z0-9._-]+$/;
22230
+ var ACTIVE_AUTH_PROFILE_KEY = Symbol.for("@uipath/auth/ActiveAuthProfile");
22231
+ var AUTH_PROFILE_STORAGE_KEY = Symbol.for("@uipath/auth/ProfileStorage");
22232
+ var globalSlot2 = globalThis;
22233
+ function isAuthProfileStorage(value) {
22234
+ return value !== null && typeof value === "object" && "getStore" in value && "run" in value;
22235
+ }
22236
+ function createProfileStorage() {
22237
+ const [error, mod] = catchError(() => __require("node:async_hooks"));
22238
+ if (error || typeof mod?.AsyncLocalStorage !== "function") {
22239
+ return {
22240
+ getStore: () => {
22241
+ return;
22242
+ },
22243
+ run: (_store, fn) => fn()
22244
+ };
22245
+ }
22246
+ return new mod.AsyncLocalStorage;
22247
+ }
22248
+ function getProfileStorage() {
22249
+ const existing = globalSlot2[AUTH_PROFILE_STORAGE_KEY];
22250
+ if (isAuthProfileStorage(existing)) {
22251
+ return existing;
22252
+ }
22253
+ const storage = createProfileStorage();
22254
+ globalSlot2[AUTH_PROFILE_STORAGE_KEY] = storage;
22255
+ return storage;
22256
+ }
22257
+ var profileStorage = getProfileStorage();
22258
+
22259
+ class AuthProfileValidationError extends Error {
22260
+ constructor(message) {
22261
+ super(message);
22262
+ this.name = "AuthProfileValidationError";
22263
+ }
22264
+ }
22265
+ function normalizeAuthProfileName(profile) {
22266
+ if (profile === undefined || profile === DEFAULT_AUTH_PROFILE) {
22267
+ return;
22268
+ }
22269
+ if (profile.length === 0 || profile === "." || profile === ".." || !PROFILE_NAME_RE.test(profile)) {
22270
+ throw new AuthProfileValidationError(`Invalid profile name "${profile}". Profile names may contain only letters, numbers, '.', '_', and '-'.`);
22271
+ }
22272
+ return profile;
22273
+ }
22274
+ function getActiveAuthProfile() {
22275
+ const scopedState = profileStorage.getStore();
22276
+ if (scopedState !== undefined) {
22277
+ return scopedState.profile;
22278
+ }
22279
+ return globalSlot2[ACTIVE_AUTH_PROFILE_KEY]?.profile;
22280
+ }
22281
+ function resolveAuthProfileFilePath(profile) {
22282
+ const normalized = normalizeAuthProfileName(profile);
22283
+ if (normalized === undefined) {
22284
+ throw new AuthProfileValidationError(`"${DEFAULT_AUTH_PROFILE}" is the built-in profile and does not have a profile file path.`);
22285
+ }
22286
+ const fs7 = getFileSystem();
22287
+ return fs7.path.join(fs7.env.homedir(), UIPATH_HOME_DIR, PROFILE_DIR, normalized, AUTH_FILENAME);
22288
+ }
22289
+ function getActiveAuthProfileFilePath() {
22290
+ const profile = getActiveAuthProfile();
22291
+ return profile ? resolveAuthProfileFilePath(profile) : undefined;
22292
+ }
22226
22293
  // ../../auth/src/utils/jwt.ts
22227
22294
  class InvalidIssuerError extends Error {
22228
22295
  expected;
@@ -22351,23 +22418,74 @@ var readAuthFromEnv = () => {
22351
22418
  organizationId,
22352
22419
  tenantName,
22353
22420
  tenantId,
22354
- expiration
22421
+ expiration,
22422
+ source: "env" /* Env */
22355
22423
  };
22356
22424
  };
22357
22425
 
22426
+ // ../../auth/src/refreshCircuitBreaker.ts
22427
+ init_src();
22428
+ var BREAKER_SUFFIX = ".refresh-state";
22429
+ var BACKOFF_BASE_MS = 60000;
22430
+ var BACKOFF_CAP_MS = 60 * 60 * 1000;
22431
+ var SURFACE_WINDOW_MS = 60 * 60 * 1000;
22432
+ async function refreshTokenFingerprint(refreshToken) {
22433
+ const bytes = new TextEncoder().encode(refreshToken);
22434
+ if (globalThis.crypto?.subtle) {
22435
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", bytes);
22436
+ return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("").slice(0, 16);
22437
+ }
22438
+ const { createHash } = await import("node:crypto");
22439
+ return createHash("sha256").update(refreshToken).digest("hex").slice(0, 16);
22440
+ }
22441
+ function breakerPathFor(authPath) {
22442
+ return `${authPath}${BREAKER_SUFFIX}`;
22443
+ }
22444
+ async function loadRefreshBreaker(authPath) {
22445
+ const fs7 = getFileSystem();
22446
+ try {
22447
+ const content = await fs7.readFile(breakerPathFor(authPath), "utf-8");
22448
+ if (!content)
22449
+ return {};
22450
+ const parsed = JSON.parse(content);
22451
+ return parsed && typeof parsed === "object" ? parsed : {};
22452
+ } catch {
22453
+ return {};
22454
+ }
22455
+ }
22456
+ async function saveRefreshBreaker(authPath, state) {
22457
+ try {
22458
+ const fs7 = getFileSystem();
22459
+ const path3 = breakerPathFor(authPath);
22460
+ await fs7.mkdir(fs7.path.dirname(path3));
22461
+ const tempPath = `${path3}.tmp`;
22462
+ await fs7.writeFile(tempPath, JSON.stringify(state));
22463
+ await fs7.rename(tempPath, path3);
22464
+ } catch {}
22465
+ }
22466
+ async function clearRefreshBreaker(authPath) {
22467
+ const fs7 = getFileSystem();
22468
+ const path3 = breakerPathFor(authPath);
22469
+ try {
22470
+ if (await fs7.exists(path3)) {
22471
+ await fs7.rm(path3);
22472
+ }
22473
+ } catch {}
22474
+ }
22475
+ function nextBackoffMs(attempts) {
22476
+ const shift = Math.max(0, attempts - 1);
22477
+ return Math.min(BACKOFF_BASE_MS * 2 ** shift, BACKOFF_CAP_MS);
22478
+ }
22479
+ function shouldSurface(state, nowMs) {
22480
+ if (state.lastSurfacedAtMs === undefined)
22481
+ return true;
22482
+ return nowMs - state.lastSurfacedAtMs >= SURFACE_WINDOW_MS;
22483
+ }
22484
+
22358
22485
  // ../../auth/src/robotClientFallback.ts
22359
22486
  init_src();
22360
22487
  var DEFAULT_TIMEOUT_MS = 1000;
22361
22488
  var CLOSE_TIMEOUT_MS = 500;
22362
- var NOTICE_SENTINEL = Symbol.for("@uipath/auth/robotFallbackNoticePrinted");
22363
- var printNoticeOnce = () => {
22364
- const slot = globalThis;
22365
- if (slot[NOTICE_SENTINEL])
22366
- return;
22367
- slot[NOTICE_SENTINEL] = true;
22368
- catchError(() => process.stderr.write(`Using UiPath Robot credentials. Run 'uip login' for a dedicated session.
22369
- `));
22370
- };
22371
22489
  var ROBOT_USER_SERVICES_PIPE = "UiPathUserServices";
22372
22490
  var ROBOT_USER_SERVICES_ALTERNATE_PIPE = `${ROBOT_USER_SERVICES_PIPE}Alternate`;
22373
22491
  var PIPE_NAME_MAX_LENGTH = 103;
@@ -22483,7 +22601,6 @@ var tryRobotClientFallback = async (options = {}) => {
22483
22601
  issuerFromToken = issClaim;
22484
22602
  }
22485
22603
  }
22486
- printNoticeOnce();
22487
22604
  return {
22488
22605
  accessToken,
22489
22606
  baseUrl: parsedUrl.baseUrl,
@@ -22708,18 +22825,327 @@ var saveEnvFileAsync = async ({
22708
22825
  };
22709
22826
 
22710
22827
  // ../../auth/src/loginStatus.ts
22711
- function normalizeTokenRefreshFailure() {
22712
- return "stored refresh token is invalid or expired";
22828
+ var getLoginStatusAsync = async (options = {}) => {
22829
+ return getLoginStatusWithDeps(options);
22830
+ };
22831
+ var getLoginStatusWithDeps = async (options = {}, deps = {}) => {
22832
+ const {
22833
+ resolveEnvFilePath = resolveEnvFilePathAsync,
22834
+ loadEnvFile = loadEnvFileAsync,
22835
+ saveEnvFile = saveEnvFileAsync,
22836
+ getFs = getFileSystem,
22837
+ refreshToken: refreshTokenFn = refreshAccessToken,
22838
+ resolveConfig = resolveConfigAsync,
22839
+ robotFallback = tryRobotClientFallback,
22840
+ loadBreaker = loadRefreshBreaker,
22841
+ saveBreaker = saveRefreshBreaker,
22842
+ clearBreaker = clearRefreshBreaker
22843
+ } = deps;
22844
+ if (isRobotAuthEnforced()) {
22845
+ return resolveRobotEnforcedStatus(robotFallback);
22846
+ }
22847
+ if (isEnvAuthEnabled()) {
22848
+ return readAuthFromEnv();
22849
+ }
22850
+ const activeProfile = getActiveAuthProfile();
22851
+ const activeProfileFilePath = getActiveAuthProfileFilePath();
22852
+ const usingActiveProfile = activeProfile !== undefined && (options.envFilePath === undefined || options.envFilePath === activeProfileFilePath);
22853
+ const envFilePath = options.envFilePath ?? activeProfileFilePath ?? DEFAULT_ENV_FILENAME;
22854
+ const { ensureTokenValidityMinutes } = options;
22855
+ const { absolutePath } = await resolveEnvFilePath(envFilePath);
22856
+ if (absolutePath === undefined) {
22857
+ if (usingActiveProfile) {
22858
+ return {
22859
+ loginStatus: "Not logged in",
22860
+ hint: `No credentials found for profile "${activeProfile}". Run 'uip login --profile ${activeProfile}' to authenticate this profile.`
22861
+ };
22862
+ }
22863
+ return resolveBorrowedRobotStatus(robotFallback);
22864
+ }
22865
+ const loaded = await loadFileCredentials(loadEnvFile, absolutePath);
22866
+ if ("status" in loaded) {
22867
+ return loaded.status;
22868
+ }
22869
+ const { credentials } = loaded;
22870
+ const globalHint = () => usingActiveProfile ? Promise.resolve(undefined) : getGlobalCredsHint(getFs, loadEnvFile, absolutePath, envFilePath);
22871
+ const expiration = getTokenExpiration(credentials.UIPATH_ACCESS_TOKEN);
22872
+ const outerThreshold = computeExpirationThreshold(ensureTokenValidityMinutes);
22873
+ let tokens = {
22874
+ accessToken: credentials.UIPATH_ACCESS_TOKEN,
22875
+ refreshToken: credentials.UIPATH_REFRESH_TOKEN,
22876
+ expiration,
22877
+ lockReleaseFailed: false
22878
+ };
22879
+ const refreshToken = credentials.UIPATH_REFRESH_TOKEN;
22880
+ if (expiration && expiration <= outerThreshold && refreshToken) {
22881
+ const refreshed = await attemptRefresh({
22882
+ absolutePath,
22883
+ credentials,
22884
+ accessToken: credentials.UIPATH_ACCESS_TOKEN,
22885
+ refreshToken,
22886
+ expiration,
22887
+ ensureTokenValidityMinutes,
22888
+ getFs,
22889
+ loadEnvFile,
22890
+ saveEnvFile,
22891
+ refreshFn: refreshTokenFn,
22892
+ resolveConfig,
22893
+ loadBreaker,
22894
+ saveBreaker,
22895
+ clearBreaker,
22896
+ globalHint
22897
+ });
22898
+ if (refreshed.kind === "terminal") {
22899
+ return refreshed.status;
22900
+ }
22901
+ tokens = refreshed.tokens;
22902
+ }
22903
+ return buildFileStatus(tokens, credentials, globalHint);
22904
+ };
22905
+ async function resolveRobotEnforcedStatus(robotFallback) {
22906
+ if (isEnvAuthEnabled()) {
22907
+ throw new EnvAuthConfigError(`${ENV_AUTH_ENABLE_VAR}=true and ${ENFORCE_ROBOT_AUTH_VAR}=true ` + `are mutually exclusive. Unset one of them and re-run.`);
22908
+ }
22909
+ const robotCreds = await robotFallback({ force: true });
22910
+ if (!robotCreds) {
22911
+ return {
22912
+ loginStatus: "Not logged in",
22913
+ 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.`
22914
+ };
22915
+ }
22916
+ return buildRobotStatus(robotCreds);
22713
22917
  }
22714
- function normalizeTokenRefreshUnavailableFailure() {
22715
- return "token refresh failed before authentication completed";
22918
+ async function resolveBorrowedRobotStatus(robotFallback) {
22919
+ const robotCreds = await robotFallback();
22920
+ return robotCreds ? buildRobotStatus(robotCreds) : { loginStatus: "Not logged in" };
22716
22921
  }
22717
- function errorMessage(error) {
22718
- return error instanceof Error ? error.message : String(error);
22922
+ async function loadFileCredentials(loadEnvFile, absolutePath) {
22923
+ let credentials;
22924
+ try {
22925
+ credentials = await loadEnvFile({ envPath: absolutePath });
22926
+ } catch (error) {
22927
+ if (isFileNotFoundError(error)) {
22928
+ return { status: { loginStatus: "Not logged in" } };
22929
+ }
22930
+ throw error;
22931
+ }
22932
+ if (!credentials.UIPATH_ACCESS_TOKEN) {
22933
+ return { status: { loginStatus: "Not logged in" } };
22934
+ }
22935
+ return { credentials };
22936
+ }
22937
+ async function getGlobalCredsHint(getFs, loadEnvFile, absolutePath, envFilePath) {
22938
+ const fs7 = getFs();
22939
+ const globalPath = fs7.path.join(fs7.env.homedir(), envFilePath);
22940
+ if (absolutePath === globalPath)
22941
+ return;
22942
+ if (!await fs7.exists(globalPath))
22943
+ return;
22944
+ try {
22945
+ const globalCreds = await loadEnvFile({ envPath: globalPath });
22946
+ if (!globalCreds.UIPATH_ACCESS_TOKEN)
22947
+ return;
22948
+ const globalExp = getTokenExpiration(globalCreds.UIPATH_ACCESS_TOKEN);
22949
+ if (globalExp && globalExp <= new Date)
22950
+ return;
22951
+ 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.`;
22952
+ } catch {
22953
+ return;
22954
+ }
22719
22955
  }
22720
22956
  function computeExpirationThreshold(ensureTokenValidityMinutes) {
22721
22957
  return new Date(Date.now() + (ensureTokenValidityMinutes ?? 0) * 60 * 1000);
22722
22958
  }
22959
+ async function attemptRefresh(ctx) {
22960
+ const shortCircuit = await circuitBreakerShortCircuit(ctx);
22961
+ if (shortCircuit) {
22962
+ return { kind: "terminal", status: shortCircuit };
22963
+ }
22964
+ let release;
22965
+ try {
22966
+ release = await ctx.getFs().acquireLock(ctx.absolutePath);
22967
+ } catch (error) {
22968
+ return {
22969
+ kind: "terminal",
22970
+ status: await lockAcquireFailureStatus(ctx, error)
22971
+ };
22972
+ }
22973
+ let lockedFailure;
22974
+ let lockReleaseFailed = false;
22975
+ let success;
22976
+ try {
22977
+ const outcome = await runRefreshLocked({
22978
+ absolutePath: ctx.absolutePath,
22979
+ refreshToken: ctx.refreshToken,
22980
+ customAuthority: ctx.credentials.UIPATH_URL,
22981
+ ensureTokenValidityMinutes: ctx.ensureTokenValidityMinutes,
22982
+ loadEnvFile: ctx.loadEnvFile,
22983
+ saveEnvFile: ctx.saveEnvFile,
22984
+ refreshFn: ctx.refreshFn,
22985
+ resolveConfig: ctx.resolveConfig,
22986
+ loadBreaker: ctx.loadBreaker,
22987
+ saveBreaker: ctx.saveBreaker,
22988
+ clearBreaker: ctx.clearBreaker
22989
+ });
22990
+ if (outcome.kind === "fail") {
22991
+ lockedFailure = outcome.status;
22992
+ } else {
22993
+ success = outcome;
22994
+ }
22995
+ } finally {
22996
+ try {
22997
+ await release();
22998
+ } catch {
22999
+ lockReleaseFailed = true;
23000
+ }
23001
+ }
23002
+ if (lockedFailure) {
23003
+ const globalHint = await ctx.globalHint();
23004
+ const base = globalHint ? { ...lockedFailure, loginStatus: "Expired", hint: globalHint } : lockedFailure;
23005
+ return {
23006
+ kind: "terminal",
23007
+ status: lockReleaseFailed ? { ...base, lockReleaseFailed: true } : base
23008
+ };
23009
+ }
23010
+ return {
23011
+ kind: "refreshed",
23012
+ tokens: {
23013
+ accessToken: success?.accessToken,
23014
+ refreshToken: success?.refreshToken,
23015
+ expiration: success?.expiration,
23016
+ tokenRefresh: success?.tokenRefresh,
23017
+ persistenceWarning: success?.persistenceWarning,
23018
+ lockReleaseFailed
23019
+ }
23020
+ };
23021
+ }
23022
+ async function buildFileStatus(tokens, credentials, globalHint) {
23023
+ const result = {
23024
+ loginStatus: tokens.expiration && tokens.expiration <= new Date ? "Expired" : "Logged in",
23025
+ accessToken: tokens.accessToken,
23026
+ refreshToken: tokens.refreshToken,
23027
+ baseUrl: credentials.UIPATH_URL,
23028
+ organizationName: credentials.UIPATH_ORGANIZATION_NAME,
23029
+ organizationId: credentials.UIPATH_ORGANIZATION_ID,
23030
+ tenantName: credentials.UIPATH_TENANT_NAME,
23031
+ tenantId: credentials.UIPATH_TENANT_ID,
23032
+ expiration: tokens.expiration,
23033
+ source: "file" /* File */,
23034
+ ...tokens.persistenceWarning ? { hint: tokens.persistenceWarning, persistenceFailed: true } : {},
23035
+ ...tokens.lockReleaseFailed ? { lockReleaseFailed: true } : {},
23036
+ ...tokens.tokenRefresh ? { tokenRefresh: tokens.tokenRefresh } : {}
23037
+ };
23038
+ if (result.loginStatus === "Expired") {
23039
+ const hint = await globalHint();
23040
+ if (hint) {
23041
+ result.hint = hint;
23042
+ }
23043
+ }
23044
+ return result;
23045
+ }
23046
+ function buildRobotStatus(robotCreds) {
23047
+ return {
23048
+ loginStatus: "Logged in",
23049
+ accessToken: robotCreds.accessToken,
23050
+ baseUrl: robotCreds.baseUrl,
23051
+ organizationName: robotCreds.organizationName,
23052
+ organizationId: robotCreds.organizationId,
23053
+ tenantName: robotCreds.tenantName,
23054
+ tenantId: robotCreds.tenantId,
23055
+ issuer: robotCreds.issuer,
23056
+ expiration: getTokenExpiration(robotCreds.accessToken),
23057
+ source: "robot" /* Robot */
23058
+ };
23059
+ }
23060
+ var isFileNotFoundError = (error) => {
23061
+ if (!(error instanceof Object))
23062
+ return false;
23063
+ return error.code === "ENOENT";
23064
+ };
23065
+ async function circuitBreakerShortCircuit(ctx) {
23066
+ const {
23067
+ absolutePath,
23068
+ refreshToken,
23069
+ accessToken,
23070
+ credentials,
23071
+ expiration,
23072
+ loadBreaker,
23073
+ saveBreaker,
23074
+ clearBreaker
23075
+ } = ctx;
23076
+ const fingerprint = await refreshTokenFingerprint(refreshToken);
23077
+ const breaker = await loadBreaker(absolutePath).catch(() => ({}));
23078
+ if (breaker.deadTokenFp && breaker.deadTokenFp !== fingerprint) {
23079
+ await clearBreaker(absolutePath);
23080
+ breaker.deadTokenFp = undefined;
23081
+ }
23082
+ const nowMs = Date.now();
23083
+ const tokenIsDead = breaker.deadTokenFp === fingerprint;
23084
+ const inBackoff = breaker.backoffUntilMs !== undefined && nowMs < breaker.backoffUntilMs;
23085
+ if (!tokenIsDead && !inBackoff)
23086
+ return;
23087
+ const globalHint = await ctx.globalHint();
23088
+ const suppressed = !shouldSurface(breaker, nowMs);
23089
+ if (!suppressed) {
23090
+ await saveBreaker(absolutePath, {
23091
+ ...breaker,
23092
+ lastSurfacedAtMs: nowMs
23093
+ });
23094
+ }
23095
+ 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>.";
23096
+ const backoffHint = "Token refresh is temporarily backed off after a recent network error and will retry automatically once the backoff window elapses.";
23097
+ return {
23098
+ loginStatus: globalHint ? "Expired" : "Refresh Failed",
23099
+ ...globalHint ? {
23100
+ accessToken,
23101
+ refreshToken,
23102
+ baseUrl: credentials.UIPATH_URL,
23103
+ organizationName: credentials.UIPATH_ORGANIZATION_NAME,
23104
+ organizationId: credentials.UIPATH_ORGANIZATION_ID,
23105
+ tenantName: credentials.UIPATH_TENANT_NAME,
23106
+ tenantId: credentials.UIPATH_TENANT_ID,
23107
+ expiration,
23108
+ source: "file" /* File */
23109
+ } : {},
23110
+ hint: globalHint ?? (tokenIsDead ? deadHint : backoffHint),
23111
+ refreshCircuitOpen: true,
23112
+ refreshTelemetrySuppressed: suppressed,
23113
+ tokenRefresh: { attempted: false, success: false }
23114
+ };
23115
+ }
23116
+ async function lockAcquireFailureStatus(ctx, error) {
23117
+ const msg = errorMessage(error);
23118
+ const globalHint = await ctx.globalHint();
23119
+ if (globalHint) {
23120
+ return {
23121
+ loginStatus: "Expired",
23122
+ accessToken: ctx.accessToken,
23123
+ refreshToken: ctx.refreshToken,
23124
+ baseUrl: ctx.credentials.UIPATH_URL,
23125
+ organizationName: ctx.credentials.UIPATH_ORGANIZATION_NAME,
23126
+ organizationId: ctx.credentials.UIPATH_ORGANIZATION_ID,
23127
+ tenantName: ctx.credentials.UIPATH_TENANT_NAME,
23128
+ tenantId: ctx.credentials.UIPATH_TENANT_ID,
23129
+ expiration: ctx.expiration,
23130
+ source: "file" /* File */,
23131
+ hint: globalHint,
23132
+ tokenRefresh: {
23133
+ attempted: false,
23134
+ success: false,
23135
+ errorMessage: `lock acquisition failed: ${msg}`
23136
+ }
23137
+ };
23138
+ }
23139
+ return {
23140
+ loginStatus: "Refresh Failed",
23141
+ 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.",
23142
+ tokenRefresh: {
23143
+ attempted: false,
23144
+ success: false,
23145
+ errorMessage: `lock acquisition failed: ${msg}`
23146
+ }
23147
+ };
23148
+ }
22723
23149
  async function runRefreshLocked(inputs) {
22724
23150
  const {
22725
23151
  absolutePath,
@@ -22729,7 +23155,10 @@ async function runRefreshLocked(inputs) {
22729
23155
  loadEnvFile,
22730
23156
  saveEnvFile,
22731
23157
  refreshFn,
22732
- resolveConfig
23158
+ resolveConfig,
23159
+ loadBreaker,
23160
+ saveBreaker,
23161
+ clearBreaker
22733
23162
  } = inputs;
22734
23163
  const expirationThreshold = computeExpirationThreshold(ensureTokenValidityMinutes);
22735
23164
  let fresh;
@@ -22752,6 +23181,7 @@ async function runRefreshLocked(inputs) {
22752
23181
  const freshAccess = fresh.UIPATH_ACCESS_TOKEN;
22753
23182
  const freshExp = freshAccess ? getTokenExpiration(freshAccess) : undefined;
22754
23183
  if (freshAccess && freshExp && freshExp > expirationThreshold) {
23184
+ await clearBreaker(absolutePath);
22755
23185
  return {
22756
23186
  kind: "ok",
22757
23187
  accessToken: freshAccess,
@@ -22775,8 +23205,21 @@ async function runRefreshLocked(inputs) {
22775
23205
  refreshedRefresh = refreshed.refreshToken;
22776
23206
  } catch (error) {
22777
23207
  const isOAuthFailure = isTokenRefreshOAuthFailure(error);
22778
- 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.";
23208
+ 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.";
22779
23209
  const message = isOAuthFailure ? normalizeTokenRefreshFailure() : normalizeTokenRefreshUnavailableFailure();
23210
+ const fp = await refreshTokenFingerprint(tokenForIdP);
23211
+ if (isOAuthFailure) {
23212
+ await saveBreaker(absolutePath, { deadTokenFp: fp });
23213
+ } else {
23214
+ const prior = await loadBreaker(absolutePath).catch(() => ({}));
23215
+ const attempts = (prior.attempts ?? 0) + 1;
23216
+ await saveBreaker(absolutePath, {
23217
+ ...prior,
23218
+ deadTokenFp: undefined,
23219
+ attempts,
23220
+ backoffUntilMs: Date.now() + nextBackoffMs(attempts)
23221
+ });
23222
+ }
22780
23223
  return {
22781
23224
  kind: "fail",
22782
23225
  status: {
@@ -22805,6 +23248,7 @@ async function runRefreshLocked(inputs) {
22805
23248
  }
22806
23249
  };
22807
23250
  }
23251
+ await clearBreaker(absolutePath);
22808
23252
  try {
22809
23253
  await saveEnvFile({
22810
23254
  envPath: absolutePath,
@@ -22837,231 +23281,42 @@ async function runRefreshLocked(inputs) {
22837
23281
  };
22838
23282
  }
22839
23283
  }
22840
- var getLoginStatusWithDeps = async (options = {}, deps = {}) => {
22841
- const {
22842
- resolveEnvFilePath = resolveEnvFilePathAsync,
22843
- loadEnvFile = loadEnvFileAsync,
22844
- saveEnvFile = saveEnvFileAsync,
22845
- getFs = getFileSystem,
22846
- refreshToken: refreshTokenFn = refreshAccessToken,
22847
- resolveConfig = resolveConfigAsync,
22848
- robotFallback = tryRobotClientFallback
22849
- } = deps;
22850
- if (isRobotAuthEnforced()) {
22851
- if (isEnvAuthEnabled()) {
22852
- throw new EnvAuthConfigError(`${ENV_AUTH_ENABLE_VAR}=true and ${ENFORCE_ROBOT_AUTH_VAR}=true ` + `are mutually exclusive. Unset one of them and re-run.`);
22853
- }
22854
- const robotCreds = await robotFallback({ force: true });
22855
- if (!robotCreds) {
22856
- return {
22857
- loginStatus: "Not logged in",
22858
- 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.`
22859
- };
22860
- }
22861
- const expiration2 = getTokenExpiration(robotCreds.accessToken);
22862
- return {
22863
- loginStatus: "Logged in",
22864
- accessToken: robotCreds.accessToken,
22865
- baseUrl: robotCreds.baseUrl,
22866
- organizationName: robotCreds.organizationName,
22867
- organizationId: robotCreds.organizationId,
22868
- tenantName: robotCreds.tenantName,
22869
- tenantId: robotCreds.tenantId,
22870
- issuer: robotCreds.issuer,
22871
- expiration: expiration2,
22872
- source: "robot" /* Robot */
22873
- };
23284
+ function normalizeTokenRefreshFailure() {
23285
+ return "stored refresh token is invalid or expired";
23286
+ }
23287
+ function normalizeTokenRefreshUnavailableFailure() {
23288
+ return "token refresh failed before authentication completed";
23289
+ }
23290
+ function errorMessage(error) {
23291
+ return error instanceof Error ? error.message : String(error);
23292
+ }
23293
+ // ../../auth/src/interactive.ts
23294
+ init_src();
23295
+
23296
+ // ../../auth/src/selectTenant.ts
23297
+ var TENANT_SELECTION_REQUIRED_CODE = "TENANT_SELECTION_REQUIRED";
23298
+ var INVALID_TENANT_CODE = "INVALID_TENANT";
23299
+ var TENANT_SELECTION_CODES = new Set([
23300
+ TENANT_SELECTION_REQUIRED_CODE,
23301
+ INVALID_TENANT_CODE
23302
+ ]);
23303
+ // ../../auth/src/logout.ts
23304
+ init_src();
23305
+
23306
+ // ../../auth/src/index.ts
23307
+ init_server();
23308
+
23309
+ // ../audit-sdk/src/client-factory.ts
23310
+ async function createAuditConfig(options) {
23311
+ const status = await getLoginStatusAsync({
23312
+ ensureTokenValidityMinutes: options.loginValidity
23313
+ });
23314
+ if (status.loginStatus !== "Logged in" || !status.baseUrl || !status.accessToken) {
23315
+ const message = status.hint ? `Not logged in. ${status.hint}` : "Not logged in. Run 'uip login' first.";
23316
+ throw new Error(message);
22874
23317
  }
22875
- if (isEnvAuthEnabled()) {
22876
- return readAuthFromEnv();
22877
- }
22878
- const { envFilePath = DEFAULT_ENV_FILENAME, ensureTokenValidityMinutes } = options;
22879
- const { absolutePath } = await resolveEnvFilePath(envFilePath);
22880
- if (absolutePath === undefined) {
22881
- const robotCreds = await robotFallback();
22882
- if (robotCreds) {
22883
- const expiration2 = getTokenExpiration(robotCreds.accessToken);
22884
- const status = {
22885
- loginStatus: "Logged in",
22886
- accessToken: robotCreds.accessToken,
22887
- baseUrl: robotCreds.baseUrl,
22888
- organizationName: robotCreds.organizationName,
22889
- organizationId: robotCreds.organizationId,
22890
- tenantName: robotCreds.tenantName,
22891
- tenantId: robotCreds.tenantId,
22892
- issuer: robotCreds.issuer,
22893
- expiration: expiration2,
22894
- source: "robot" /* Robot */
22895
- };
22896
- return status;
22897
- }
22898
- return { loginStatus: "Not logged in" };
22899
- }
22900
- let credentials;
22901
- try {
22902
- credentials = await loadEnvFile({ envPath: absolutePath });
22903
- } catch (error) {
22904
- if (isFileNotFoundError(error)) {
22905
- return { loginStatus: "Not logged in" };
22906
- }
22907
- throw error;
22908
- }
22909
- if (!credentials.UIPATH_ACCESS_TOKEN) {
22910
- return { loginStatus: "Not logged in" };
22911
- }
22912
- let accessToken = credentials.UIPATH_ACCESS_TOKEN;
22913
- let refreshToken = credentials.UIPATH_REFRESH_TOKEN;
22914
- let expiration = getTokenExpiration(accessToken);
22915
- let persistenceWarning;
22916
- let lockReleaseFailed = false;
22917
- let tokenRefresh;
22918
- const outerThreshold = computeExpirationThreshold(ensureTokenValidityMinutes);
22919
- const tryGlobalCredsHint = async () => {
22920
- const fs7 = getFs();
22921
- const globalPath = fs7.path.join(fs7.env.homedir(), envFilePath);
22922
- if (absolutePath === globalPath)
22923
- return;
22924
- if (!await fs7.exists(globalPath))
22925
- return;
22926
- try {
22927
- const globalCreds = await loadEnvFile({ envPath: globalPath });
22928
- if (!globalCreds.UIPATH_ACCESS_TOKEN)
22929
- return;
22930
- const globalExp = getTokenExpiration(globalCreds.UIPATH_ACCESS_TOKEN);
22931
- if (globalExp && globalExp <= new Date)
22932
- return;
22933
- 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.`;
22934
- } catch {
22935
- return;
22936
- }
22937
- };
22938
- if (expiration && expiration <= outerThreshold && refreshToken) {
22939
- let release;
22940
- try {
22941
- release = await getFs().acquireLock(absolutePath);
22942
- } catch (error) {
22943
- const msg = errorMessage(error);
22944
- const globalHint = await tryGlobalCredsHint();
22945
- if (globalHint) {
22946
- return {
22947
- loginStatus: "Expired",
22948
- accessToken,
22949
- refreshToken,
22950
- baseUrl: credentials.UIPATH_URL,
22951
- organizationName: credentials.UIPATH_ORGANIZATION_NAME,
22952
- organizationId: credentials.UIPATH_ORGANIZATION_ID,
22953
- tenantName: credentials.UIPATH_TENANT_NAME,
22954
- tenantId: credentials.UIPATH_TENANT_ID,
22955
- expiration,
22956
- source: "file" /* File */,
22957
- hint: globalHint,
22958
- tokenRefresh: {
22959
- attempted: false,
22960
- success: false,
22961
- errorMessage: `lock acquisition failed: ${msg}`
22962
- }
22963
- };
22964
- }
22965
- return {
22966
- loginStatus: "Refresh Failed",
22967
- 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.",
22968
- tokenRefresh: {
22969
- attempted: false,
22970
- success: false,
22971
- errorMessage: `lock acquisition failed: ${msg}`
22972
- }
22973
- };
22974
- }
22975
- let lockedFailure;
22976
- try {
22977
- const outcome = await runRefreshLocked({
22978
- absolutePath,
22979
- refreshToken,
22980
- customAuthority: credentials.UIPATH_URL,
22981
- ensureTokenValidityMinutes,
22982
- loadEnvFile,
22983
- saveEnvFile,
22984
- refreshFn: refreshTokenFn,
22985
- resolveConfig
22986
- });
22987
- if (outcome.kind === "fail") {
22988
- lockedFailure = outcome.status;
22989
- } else {
22990
- accessToken = outcome.accessToken;
22991
- refreshToken = outcome.refreshToken;
22992
- expiration = outcome.expiration;
22993
- tokenRefresh = outcome.tokenRefresh;
22994
- if (outcome.persistenceWarning) {
22995
- persistenceWarning = outcome.persistenceWarning;
22996
- }
22997
- }
22998
- } finally {
22999
- try {
23000
- await release();
23001
- } catch {
23002
- lockReleaseFailed = true;
23003
- }
23004
- }
23005
- if (lockedFailure) {
23006
- const globalHint = await tryGlobalCredsHint();
23007
- const base = globalHint ? {
23008
- ...lockedFailure,
23009
- loginStatus: "Expired",
23010
- hint: globalHint
23011
- } : lockedFailure;
23012
- return lockReleaseFailed ? { ...base, lockReleaseFailed: true } : base;
23013
- }
23014
- }
23015
- const result = {
23016
- loginStatus: expiration && expiration <= new Date ? "Expired" : "Logged in",
23017
- accessToken,
23018
- refreshToken,
23019
- baseUrl: credentials.UIPATH_URL,
23020
- organizationName: credentials.UIPATH_ORGANIZATION_NAME,
23021
- organizationId: credentials.UIPATH_ORGANIZATION_ID,
23022
- tenantName: credentials.UIPATH_TENANT_NAME,
23023
- tenantId: credentials.UIPATH_TENANT_ID,
23024
- expiration,
23025
- source: "file" /* File */,
23026
- ...persistenceWarning ? { hint: persistenceWarning, persistenceFailed: true } : {},
23027
- ...lockReleaseFailed ? { lockReleaseFailed: true } : {},
23028
- ...tokenRefresh ? { tokenRefresh } : {}
23029
- };
23030
- if (result.loginStatus === "Expired") {
23031
- const globalHint = await tryGlobalCredsHint();
23032
- if (globalHint) {
23033
- result.hint = globalHint;
23034
- }
23035
- }
23036
- return result;
23037
- };
23038
- var isFileNotFoundError = (error) => {
23039
- if (!(error instanceof Object))
23040
- return false;
23041
- return error.code === "ENOENT";
23042
- };
23043
- var getLoginStatusAsync = async (options = {}) => {
23044
- return getLoginStatusWithDeps(options);
23045
- };
23046
- // ../../auth/src/interactive.ts
23047
- init_src();
23048
- // ../../auth/src/logout.ts
23049
- init_src();
23050
-
23051
- // ../../auth/src/index.ts
23052
- init_server();
23053
-
23054
- // ../audit-sdk/src/client-factory.ts
23055
- async function createAuditConfig(options) {
23056
- const status = await getLoginStatusAsync({
23057
- ensureTokenValidityMinutes: options.loginValidity
23058
- });
23059
- if (status.loginStatus !== "Logged in" || !status.baseUrl || !status.accessToken) {
23060
- const message = status.hint ? `Not logged in. ${status.hint}` : "Not logged in. Run 'uip login' first.";
23061
- throw new Error(message);
23062
- }
23063
- if (!status.organizationId) {
23064
- throw new Error("Organization ID not available. Ensure you are logged in with an organization context.");
23318
+ if (!status.organizationId) {
23319
+ throw new Error("Organization ID not available. Ensure you are logged in with an organization context.");
23065
23320
  }
23066
23321
  let suffix;
23067
23322
  if (options.scope === "tenant") {
@@ -23132,27 +23387,54 @@ var NETWORK_ERROR_CODES = new Set([
23132
23387
  "ENETUNREACH",
23133
23388
  "EAI_FAIL"
23134
23389
  ]);
23135
- function isHtmlDocument(body) {
23136
- return /^\s*(<!doctype html|<html\b)/i.test(body);
23137
- }
23138
- function extractNetworkErrorCode(error) {
23139
- if (error === null || typeof error !== "object") {
23140
- return;
23141
- }
23142
- const err = error;
23143
- const code = typeof err.code === "string" ? err.code : undefined;
23144
- if (code && NETWORK_ERROR_CODES.has(code)) {
23145
- return code;
23146
- }
23147
- const cause = err.cause;
23148
- if (cause !== null && typeof cause === "object") {
23149
- const causeCode = cause.code;
23150
- if (typeof causeCode === "string" && NETWORK_ERROR_CODES.has(causeCode)) {
23151
- return causeCode;
23390
+ var TLS_ERROR_CODES = new Set([
23391
+ "SELF_SIGNED_CERT_IN_CHAIN",
23392
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
23393
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
23394
+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
23395
+ "UNABLE_TO_GET_ISSUER_CERT",
23396
+ "CERT_HAS_EXPIRED",
23397
+ "CERT_UNTRUSTED",
23398
+ "ERR_TLS_CERT_ALTNAME_INVALID"
23399
+ ]);
23400
+ 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.";
23401
+ 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.";
23402
+ function describeConnectivityError(error) {
23403
+ let current = error;
23404
+ for (let depth = 0;depth < 5 && current !== null && typeof current === "object"; depth++) {
23405
+ const cur = current;
23406
+ const code = typeof cur.code === "string" ? cur.code : undefined;
23407
+ const message = typeof cur.message === "string" ? cur.message : undefined;
23408
+ if (code && TLS_ERROR_CODES.has(code)) {
23409
+ return {
23410
+ code,
23411
+ kind: "tls",
23412
+ message: message ?? code,
23413
+ instructions: TLS_INSTRUCTIONS
23414
+ };
23415
+ }
23416
+ if (code && NETWORK_ERROR_CODES.has(code)) {
23417
+ return {
23418
+ code,
23419
+ kind: "network",
23420
+ message: message ?? code,
23421
+ instructions: NETWORK_INSTRUCTIONS
23422
+ };
23152
23423
  }
23424
+ current = cur.cause;
23153
23425
  }
23154
23426
  return;
23155
23427
  }
23428
+ function parseHttpStatusFromMessage(message) {
23429
+ const match = /^HTTP\s+(\d{3})(?::|\s|-|$)/i.exec(message.trim());
23430
+ if (!match)
23431
+ return;
23432
+ const status = Number(match[1]);
23433
+ return Number.isInteger(status) && status >= 100 && status <= 599 ? status : undefined;
23434
+ }
23435
+ function isHtmlDocument(body) {
23436
+ return /^\s*(<!doctype html|<html\b)/i.test(body);
23437
+ }
23156
23438
  function retryHintForRetryAfter(seconds) {
23157
23439
  if (seconds <= 1) {
23158
23440
  return "RetryAfter1Second";
@@ -23193,15 +23475,28 @@ function classifyError(status, error) {
23193
23475
  if (status !== undefined && status >= 500 && status < 600) {
23194
23476
  return { errorCode: "server_error", retry: "RetryLater" };
23195
23477
  }
23196
- if (extractNetworkErrorCode(error)) {
23197
- return { errorCode: "network_error", retry: "RetryLater" };
23478
+ const connectivity = describeConnectivityError(error);
23479
+ if (connectivity) {
23480
+ return {
23481
+ errorCode: "network_error",
23482
+ retry: connectivity.kind === "tls" ? "RetryWillNotFix" : "RetryLater"
23483
+ };
23198
23484
  }
23199
23485
  return { errorCode: "unknown_error", retry: "RetryWillNotFix" };
23200
23486
  }
23487
+ function formatHttpStatusMessage(status, rawMessage, extractedMessage, inferredStatus) {
23488
+ if (extractedMessage) {
23489
+ return `HTTP ${status}: ${extractedMessage}`;
23490
+ }
23491
+ return inferredStatus !== undefined ? rawMessage : `HTTP ${status}: ${rawMessage}`;
23492
+ }
23201
23493
  async function extractErrorDetails(error, options) {
23202
23494
  const err = error !== null && error !== undefined && typeof error === "object" ? error : {};
23203
23495
  const response = err.response;
23204
- const status = err.status ?? response?.status;
23496
+ const rawMessage = typeof err.message === "string" ? err.message : "Unknown error";
23497
+ const explicitStatus = err.status ?? response?.status;
23498
+ const inferredStatus = explicitStatus === undefined ? parseHttpStatusFromMessage(rawMessage) : undefined;
23499
+ const status = explicitStatus ?? inferredStatus;
23205
23500
  const isSuccessfulResponse = status !== undefined && status >= 200 && status < 300;
23206
23501
  let rawBody;
23207
23502
  let extractedMessage;
@@ -23236,7 +23531,6 @@ async function extractErrorDetails(error, options) {
23236
23531
  }
23237
23532
  }
23238
23533
  }
23239
- const rawMessage = typeof err.message === "string" ? err.message : "Unknown error";
23240
23534
  let message;
23241
23535
  let result = "Failure";
23242
23536
  const classification = classifyError(status, error);
@@ -23250,10 +23544,10 @@ async function extractErrorDetails(error, options) {
23250
23544
  } else if (status === 405) {
23251
23545
  message = DEFAULT_405;
23252
23546
  } else if (status === 400 || status === 422) {
23253
- message = extractedMessage ? `HTTP ${status}: ${extractedMessage}` : `HTTP ${status}: ${rawMessage}`;
23547
+ message = formatHttpStatusMessage(status, rawMessage, extractedMessage, inferredStatus);
23254
23548
  result = "ValidationError";
23255
23549
  } else if (status === 429) {
23256
- message = extractedMessage ? `HTTP ${status}: ${extractedMessage}` : `HTTP ${status}: ${rawMessage}`;
23550
+ message = formatHttpStatusMessage(status, rawMessage, extractedMessage, inferredStatus);
23257
23551
  } else if (extractedMessage) {
23258
23552
  if (isSuccessfulResponse && rawMessage !== "Unknown error") {
23259
23553
  message = rawMessage;
@@ -23261,7 +23555,9 @@ async function extractErrorDetails(error, options) {
23261
23555
  message = status ? `HTTP ${status}: ${extractedMessage}` : extractedMessage;
23262
23556
  }
23263
23557
  } else if (status) {
23264
- if (rawMessage === "Unknown error" && response) {
23558
+ if (inferredStatus !== undefined) {
23559
+ message = rawMessage;
23560
+ } else if (rawMessage === "Unknown error" && response) {
23265
23561
  const statusText = response.statusText;
23266
23562
  message = statusText ? `HTTP ${status} ${statusText}` : `HTTP ${status} - request failed`;
23267
23563
  } else {
@@ -23270,6 +23566,12 @@ async function extractErrorDetails(error, options) {
23270
23566
  } else {
23271
23567
  message = rawMessage;
23272
23568
  }
23569
+ if (status === undefined) {
23570
+ const connectivity = describeConnectivityError(error);
23571
+ if (connectivity && connectivity.message !== message && !message.includes(connectivity.message)) {
23572
+ message = `${message}: ${connectivity.message}`;
23573
+ }
23574
+ }
23273
23575
  let details = rawMessage;
23274
23576
  if (rawBody) {
23275
23577
  if (parsedBody) {
@@ -23392,6 +23694,7 @@ var CONSOLE_FALLBACK = {
23392
23694
  writeLog: (str) => process.stdout.write(str),
23393
23695
  capabilities: {
23394
23696
  isInteractive: false,
23697
+ canReadInput: false,
23395
23698
  supportsColor: false,
23396
23699
  outputWidth: 80
23397
23700
  }
@@ -28397,12 +28700,6 @@ class NodeContextStorage {
28397
28700
  return this.storage.getStore();
28398
28701
  }
28399
28702
  }
28400
- // ../../common/src/telemetry/global-telemetry-properties.ts
28401
- var telemetryPropsSlot = singleton("TelemetryDefaultProps");
28402
- function getGlobalTelemetryProperties() {
28403
- return telemetryPropsSlot.get();
28404
- }
28405
-
28406
28703
  // ../../common/src/telemetry/telemetry-service.ts
28407
28704
  class TelemetryService {
28408
28705
  telemetryProvider;
@@ -28592,6 +28889,29 @@ function isPlainRecord(value) {
28592
28889
  const prototype = Object.getPrototypeOf(value);
28593
28890
  return prototype === Object.prototype || prototype === null;
28594
28891
  }
28892
+ function extractPagedRows(value) {
28893
+ if (Array.isArray(value) || !isPlainRecord(value))
28894
+ return null;
28895
+ const entries = Object.values(value);
28896
+ if (entries.length === 0)
28897
+ return null;
28898
+ let rows = null;
28899
+ let hasScalarSibling = false;
28900
+ for (const entry of entries) {
28901
+ if (Array.isArray(entry)) {
28902
+ if (rows !== null)
28903
+ return null;
28904
+ rows = entry;
28905
+ } else if (entry !== null && typeof entry === "object") {
28906
+ return null;
28907
+ } else {
28908
+ hasScalarSibling = true;
28909
+ }
28910
+ }
28911
+ if (rows === null || !hasScalarSibling)
28912
+ return null;
28913
+ return rows;
28914
+ }
28595
28915
  function toLowerCamelCaseKey(key) {
28596
28916
  if (!key)
28597
28917
  return key;
@@ -28656,7 +28976,8 @@ function printOutput(data, format = "json", logFn, asciiSafe = false) {
28656
28976
  break;
28657
28977
  case "plain": {
28658
28978
  if ("Data" in data && data.Data != null) {
28659
- const items = Array.isArray(data.Data) ? data.Data : [data.Data];
28979
+ const pagedRows = extractPagedRows(data.Data);
28980
+ const items = pagedRows ?? (Array.isArray(data.Data) ? data.Data : [data.Data]);
28660
28981
  items.forEach((item) => {
28661
28982
  const values = Object.values(item).map((v) => v ?? "").join("\t");
28662
28983
  logFn(values);
@@ -28668,10 +28989,13 @@ function printOutput(data, format = "json", logFn, asciiSafe = false) {
28668
28989
  break;
28669
28990
  }
28670
28991
  default: {
28671
- if ("Data" in data && data.Data != null && !(Array.isArray(data.Data) && data.Data.length === 0)) {
28992
+ const hasData = "Data" in data && data.Data != null;
28993
+ const pagedRows = hasData ? extractPagedRows(data.Data) : null;
28994
+ const rows = pagedRows ? pagedRows : Array.isArray(data.Data) ? data.Data : null;
28995
+ if (hasData && !(rows !== null && rows.length === 0)) {
28672
28996
  const logValue = data.Log;
28673
- if (Array.isArray(data.Data)) {
28674
- printResizableTable(data.Data, logFn, logValue);
28997
+ if (rows !== null) {
28998
+ printResizableTable(rows, logFn, logValue);
28675
28999
  } else {
28676
29000
  printVerticalTable(data.Data, logFn, logValue);
28677
29001
  }
@@ -28859,6 +29183,44 @@ function defaultErrorCodeForResult(result) {
28859
29183
  return "unknown_error";
28860
29184
  }
28861
29185
  }
29186
+ function parseHttpStatusFromMessage2(message) {
29187
+ const match = /^HTTP\s+(\d{3})(?::|\s|-|$)/i.exec(message.trim());
29188
+ if (!match)
29189
+ return;
29190
+ const status = Number(match[1]);
29191
+ return Number.isInteger(status) && status >= 100 && status <= 599 ? status : undefined;
29192
+ }
29193
+ function defaultErrorCodeForHttpStatus(status) {
29194
+ if (status === undefined)
29195
+ return;
29196
+ if (status === 400 || status === 409 || status === 422) {
29197
+ return "invalid_argument";
29198
+ }
29199
+ if (status === 401)
29200
+ return "authentication_required";
29201
+ if (status === 403)
29202
+ return "permission_denied";
29203
+ if (status === 404)
29204
+ return "not_found";
29205
+ if (status === 405)
29206
+ return "method_not_allowed";
29207
+ if (status === 408)
29208
+ return "timeout";
29209
+ if (status === 429)
29210
+ return "rate_limited";
29211
+ if (status >= 500 && status < 600)
29212
+ return "server_error";
29213
+ return;
29214
+ }
29215
+ function defaultErrorCodeForFailure(data) {
29216
+ if (data.Result === RESULTS.Failure) {
29217
+ const status = data.Context?.httpStatus ?? parseHttpStatusFromMessage2(data.Message);
29218
+ const errorCode2 = defaultErrorCodeForHttpStatus(status);
29219
+ if (errorCode2)
29220
+ return errorCode2;
29221
+ }
29222
+ return defaultErrorCodeForResult(data.Result);
29223
+ }
28862
29224
  function defaultRetryForErrorCode(errorCode2) {
28863
29225
  switch (errorCode2) {
28864
29226
  case "network_error":
@@ -28888,16 +29250,19 @@ var OutputFormatter;
28888
29250
  OutputFormatter.success = success;
28889
29251
  function error(data) {
28890
29252
  data.Log ??= getLogFilePath() || undefined;
28891
- data.ErrorCode ??= defaultErrorCodeForResult(data.Result);
29253
+ data.ErrorCode ??= defaultErrorCodeForFailure(data);
28892
29254
  data.Retry ??= defaultRetryForErrorCode(data.ErrorCode);
28893
29255
  process.exitCode = EXIT_CODES[data.Result] ?? 1;
28894
- telemetry.trackEvent(CommonTelemetryEvents.Error, {
28895
- result: data.Result,
28896
- errorCode: data.ErrorCode,
28897
- retry: data.Retry,
28898
- message: data.Message
28899
- });
28900
- logOutput(normalizeOutputKeys(data), getOutputFormat());
29256
+ const { SuppressTelemetry, ...envelope } = data;
29257
+ if (!SuppressTelemetry) {
29258
+ telemetry.trackEvent(CommonTelemetryEvents.Error, {
29259
+ result: data.Result,
29260
+ errorCode: data.ErrorCode,
29261
+ retry: data.Retry,
29262
+ message: data.Message
29263
+ });
29264
+ }
29265
+ logOutput(normalizeOutputKeys(envelope), getOutputFormat());
28901
29266
  }
28902
29267
  OutputFormatter.error = error;
28903
29268
  function emitList(code, items, opts) {
@@ -29190,1409 +29555,6 @@ var savedOriginalsSlot = singleton("ConsoleGuardOriginals");
29190
29555
  var DEFAULT_AUTH_TIMEOUT_MS2 = 5 * 60 * 1000;
29191
29556
  // ../../common/src/interactivity-context.ts
29192
29557
  var modeSlot = singleton("InteractivityMode");
29193
- // ../../../node_modules/jsonpath-plus/dist/index-node-esm.js
29194
- import vm from "vm";
29195
-
29196
- class Hooks {
29197
- add(name, callback, first) {
29198
- if (typeof arguments[0] != "string") {
29199
- for (let name2 in arguments[0]) {
29200
- this.add(name2, arguments[0][name2], arguments[1]);
29201
- }
29202
- } else {
29203
- (Array.isArray(name) ? name : [name]).forEach(function(name2) {
29204
- this[name2] = this[name2] || [];
29205
- if (callback) {
29206
- this[name2][first ? "unshift" : "push"](callback);
29207
- }
29208
- }, this);
29209
- }
29210
- }
29211
- run(name, env) {
29212
- this[name] = this[name] || [];
29213
- this[name].forEach(function(callback) {
29214
- callback.call(env && env.context ? env.context : env, env);
29215
- });
29216
- }
29217
- }
29218
-
29219
- class Plugins {
29220
- constructor(jsep) {
29221
- this.jsep = jsep;
29222
- this.registered = {};
29223
- }
29224
- register(...plugins) {
29225
- plugins.forEach((plugin) => {
29226
- if (typeof plugin !== "object" || !plugin.name || !plugin.init) {
29227
- throw new Error("Invalid JSEP plugin format");
29228
- }
29229
- if (this.registered[plugin.name]) {
29230
- return;
29231
- }
29232
- plugin.init(this.jsep);
29233
- this.registered[plugin.name] = plugin;
29234
- });
29235
- }
29236
- }
29237
-
29238
- class Jsep {
29239
- static get version() {
29240
- return "1.4.0";
29241
- }
29242
- static toString() {
29243
- return "JavaScript Expression Parser (JSEP) v" + Jsep.version;
29244
- }
29245
- static addUnaryOp(op_name) {
29246
- Jsep.max_unop_len = Math.max(op_name.length, Jsep.max_unop_len);
29247
- Jsep.unary_ops[op_name] = 1;
29248
- return Jsep;
29249
- }
29250
- static addBinaryOp(op_name, precedence, isRightAssociative) {
29251
- Jsep.max_binop_len = Math.max(op_name.length, Jsep.max_binop_len);
29252
- Jsep.binary_ops[op_name] = precedence;
29253
- if (isRightAssociative) {
29254
- Jsep.right_associative.add(op_name);
29255
- } else {
29256
- Jsep.right_associative.delete(op_name);
29257
- }
29258
- return Jsep;
29259
- }
29260
- static addIdentifierChar(char) {
29261
- Jsep.additional_identifier_chars.add(char);
29262
- return Jsep;
29263
- }
29264
- static addLiteral(literal_name, literal_value) {
29265
- Jsep.literals[literal_name] = literal_value;
29266
- return Jsep;
29267
- }
29268
- static removeUnaryOp(op_name) {
29269
- delete Jsep.unary_ops[op_name];
29270
- if (op_name.length === Jsep.max_unop_len) {
29271
- Jsep.max_unop_len = Jsep.getMaxKeyLen(Jsep.unary_ops);
29272
- }
29273
- return Jsep;
29274
- }
29275
- static removeAllUnaryOps() {
29276
- Jsep.unary_ops = {};
29277
- Jsep.max_unop_len = 0;
29278
- return Jsep;
29279
- }
29280
- static removeIdentifierChar(char) {
29281
- Jsep.additional_identifier_chars.delete(char);
29282
- return Jsep;
29283
- }
29284
- static removeBinaryOp(op_name) {
29285
- delete Jsep.binary_ops[op_name];
29286
- if (op_name.length === Jsep.max_binop_len) {
29287
- Jsep.max_binop_len = Jsep.getMaxKeyLen(Jsep.binary_ops);
29288
- }
29289
- Jsep.right_associative.delete(op_name);
29290
- return Jsep;
29291
- }
29292
- static removeAllBinaryOps() {
29293
- Jsep.binary_ops = {};
29294
- Jsep.max_binop_len = 0;
29295
- return Jsep;
29296
- }
29297
- static removeLiteral(literal_name) {
29298
- delete Jsep.literals[literal_name];
29299
- return Jsep;
29300
- }
29301
- static removeAllLiterals() {
29302
- Jsep.literals = {};
29303
- return Jsep;
29304
- }
29305
- get char() {
29306
- return this.expr.charAt(this.index);
29307
- }
29308
- get code() {
29309
- return this.expr.charCodeAt(this.index);
29310
- }
29311
- constructor(expr) {
29312
- this.expr = expr;
29313
- this.index = 0;
29314
- }
29315
- static parse(expr) {
29316
- return new Jsep(expr).parse();
29317
- }
29318
- static getMaxKeyLen(obj) {
29319
- return Math.max(0, ...Object.keys(obj).map((k) => k.length));
29320
- }
29321
- static isDecimalDigit(ch) {
29322
- return ch >= 48 && ch <= 57;
29323
- }
29324
- static binaryPrecedence(op_val) {
29325
- return Jsep.binary_ops[op_val] || 0;
29326
- }
29327
- static isIdentifierStart(ch) {
29328
- 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));
29329
- }
29330
- static isIdentifierPart(ch) {
29331
- return Jsep.isIdentifierStart(ch) || Jsep.isDecimalDigit(ch);
29332
- }
29333
- throwError(message) {
29334
- const error = new Error(message + " at character " + this.index);
29335
- error.index = this.index;
29336
- error.description = message;
29337
- throw error;
29338
- }
29339
- runHook(name, node) {
29340
- if (Jsep.hooks[name]) {
29341
- const env = {
29342
- context: this,
29343
- node
29344
- };
29345
- Jsep.hooks.run(name, env);
29346
- return env.node;
29347
- }
29348
- return node;
29349
- }
29350
- searchHook(name) {
29351
- if (Jsep.hooks[name]) {
29352
- const env = {
29353
- context: this
29354
- };
29355
- Jsep.hooks[name].find(function(callback) {
29356
- callback.call(env.context, env);
29357
- return env.node;
29358
- });
29359
- return env.node;
29360
- }
29361
- }
29362
- gobbleSpaces() {
29363
- let ch = this.code;
29364
- while (ch === Jsep.SPACE_CODE || ch === Jsep.TAB_CODE || ch === Jsep.LF_CODE || ch === Jsep.CR_CODE) {
29365
- ch = this.expr.charCodeAt(++this.index);
29366
- }
29367
- this.runHook("gobble-spaces");
29368
- }
29369
- parse() {
29370
- this.runHook("before-all");
29371
- const nodes = this.gobbleExpressions();
29372
- const node = nodes.length === 1 ? nodes[0] : {
29373
- type: Jsep.COMPOUND,
29374
- body: nodes
29375
- };
29376
- return this.runHook("after-all", node);
29377
- }
29378
- gobbleExpressions(untilICode) {
29379
- let nodes = [], ch_i, node;
29380
- while (this.index < this.expr.length) {
29381
- ch_i = this.code;
29382
- if (ch_i === Jsep.SEMCOL_CODE || ch_i === Jsep.COMMA_CODE) {
29383
- this.index++;
29384
- } else {
29385
- if (node = this.gobbleExpression()) {
29386
- nodes.push(node);
29387
- } else if (this.index < this.expr.length) {
29388
- if (ch_i === untilICode) {
29389
- break;
29390
- }
29391
- this.throwError('Unexpected "' + this.char + '"');
29392
- }
29393
- }
29394
- }
29395
- return nodes;
29396
- }
29397
- gobbleExpression() {
29398
- const node = this.searchHook("gobble-expression") || this.gobbleBinaryExpression();
29399
- this.gobbleSpaces();
29400
- return this.runHook("after-expression", node);
29401
- }
29402
- gobbleBinaryOp() {
29403
- this.gobbleSpaces();
29404
- let to_check = this.expr.substr(this.index, Jsep.max_binop_len);
29405
- let tc_len = to_check.length;
29406
- while (tc_len > 0) {
29407
- 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)))) {
29408
- this.index += tc_len;
29409
- return to_check;
29410
- }
29411
- to_check = to_check.substr(0, --tc_len);
29412
- }
29413
- return false;
29414
- }
29415
- gobbleBinaryExpression() {
29416
- let node, biop, prec, stack, biop_info, left, right, i, cur_biop;
29417
- left = this.gobbleToken();
29418
- if (!left) {
29419
- return left;
29420
- }
29421
- biop = this.gobbleBinaryOp();
29422
- if (!biop) {
29423
- return left;
29424
- }
29425
- biop_info = {
29426
- value: biop,
29427
- prec: Jsep.binaryPrecedence(biop),
29428
- right_a: Jsep.right_associative.has(biop)
29429
- };
29430
- right = this.gobbleToken();
29431
- if (!right) {
29432
- this.throwError("Expected expression after " + biop);
29433
- }
29434
- stack = [left, biop_info, right];
29435
- while (biop = this.gobbleBinaryOp()) {
29436
- prec = Jsep.binaryPrecedence(biop);
29437
- if (prec === 0) {
29438
- this.index -= biop.length;
29439
- break;
29440
- }
29441
- biop_info = {
29442
- value: biop,
29443
- prec,
29444
- right_a: Jsep.right_associative.has(biop)
29445
- };
29446
- cur_biop = biop;
29447
- const comparePrev = (prev) => biop_info.right_a && prev.right_a ? prec > prev.prec : prec <= prev.prec;
29448
- while (stack.length > 2 && comparePrev(stack[stack.length - 2])) {
29449
- right = stack.pop();
29450
- biop = stack.pop().value;
29451
- left = stack.pop();
29452
- node = {
29453
- type: Jsep.BINARY_EXP,
29454
- operator: biop,
29455
- left,
29456
- right
29457
- };
29458
- stack.push(node);
29459
- }
29460
- node = this.gobbleToken();
29461
- if (!node) {
29462
- this.throwError("Expected expression after " + cur_biop);
29463
- }
29464
- stack.push(biop_info, node);
29465
- }
29466
- i = stack.length - 1;
29467
- node = stack[i];
29468
- while (i > 1) {
29469
- node = {
29470
- type: Jsep.BINARY_EXP,
29471
- operator: stack[i - 1].value,
29472
- left: stack[i - 2],
29473
- right: node
29474
- };
29475
- i -= 2;
29476
- }
29477
- return node;
29478
- }
29479
- gobbleToken() {
29480
- let ch, to_check, tc_len, node;
29481
- this.gobbleSpaces();
29482
- node = this.searchHook("gobble-token");
29483
- if (node) {
29484
- return this.runHook("after-token", node);
29485
- }
29486
- ch = this.code;
29487
- if (Jsep.isDecimalDigit(ch) || ch === Jsep.PERIOD_CODE) {
29488
- return this.gobbleNumericLiteral();
29489
- }
29490
- if (ch === Jsep.SQUOTE_CODE || ch === Jsep.DQUOTE_CODE) {
29491
- node = this.gobbleStringLiteral();
29492
- } else if (ch === Jsep.OBRACK_CODE) {
29493
- node = this.gobbleArray();
29494
- } else {
29495
- to_check = this.expr.substr(this.index, Jsep.max_unop_len);
29496
- tc_len = to_check.length;
29497
- while (tc_len > 0) {
29498
- 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)))) {
29499
- this.index += tc_len;
29500
- const argument = this.gobbleToken();
29501
- if (!argument) {
29502
- this.throwError("missing unaryOp argument");
29503
- }
29504
- return this.runHook("after-token", {
29505
- type: Jsep.UNARY_EXP,
29506
- operator: to_check,
29507
- argument,
29508
- prefix: true
29509
- });
29510
- }
29511
- to_check = to_check.substr(0, --tc_len);
29512
- }
29513
- if (Jsep.isIdentifierStart(ch)) {
29514
- node = this.gobbleIdentifier();
29515
- if (Jsep.literals.hasOwnProperty(node.name)) {
29516
- node = {
29517
- type: Jsep.LITERAL,
29518
- value: Jsep.literals[node.name],
29519
- raw: node.name
29520
- };
29521
- } else if (node.name === Jsep.this_str) {
29522
- node = {
29523
- type: Jsep.THIS_EXP
29524
- };
29525
- }
29526
- } else if (ch === Jsep.OPAREN_CODE) {
29527
- node = this.gobbleGroup();
29528
- }
29529
- }
29530
- if (!node) {
29531
- return this.runHook("after-token", false);
29532
- }
29533
- node = this.gobbleTokenProperty(node);
29534
- return this.runHook("after-token", node);
29535
- }
29536
- gobbleTokenProperty(node) {
29537
- this.gobbleSpaces();
29538
- let ch = this.code;
29539
- while (ch === Jsep.PERIOD_CODE || ch === Jsep.OBRACK_CODE || ch === Jsep.OPAREN_CODE || ch === Jsep.QUMARK_CODE) {
29540
- let optional;
29541
- if (ch === Jsep.QUMARK_CODE) {
29542
- if (this.expr.charCodeAt(this.index + 1) !== Jsep.PERIOD_CODE) {
29543
- break;
29544
- }
29545
- optional = true;
29546
- this.index += 2;
29547
- this.gobbleSpaces();
29548
- ch = this.code;
29549
- }
29550
- this.index++;
29551
- if (ch === Jsep.OBRACK_CODE) {
29552
- node = {
29553
- type: Jsep.MEMBER_EXP,
29554
- computed: true,
29555
- object: node,
29556
- property: this.gobbleExpression()
29557
- };
29558
- if (!node.property) {
29559
- this.throwError('Unexpected "' + this.char + '"');
29560
- }
29561
- this.gobbleSpaces();
29562
- ch = this.code;
29563
- if (ch !== Jsep.CBRACK_CODE) {
29564
- this.throwError("Unclosed [");
29565
- }
29566
- this.index++;
29567
- } else if (ch === Jsep.OPAREN_CODE) {
29568
- node = {
29569
- type: Jsep.CALL_EXP,
29570
- arguments: this.gobbleArguments(Jsep.CPAREN_CODE),
29571
- callee: node
29572
- };
29573
- } else if (ch === Jsep.PERIOD_CODE || optional) {
29574
- if (optional) {
29575
- this.index--;
29576
- }
29577
- this.gobbleSpaces();
29578
- node = {
29579
- type: Jsep.MEMBER_EXP,
29580
- computed: false,
29581
- object: node,
29582
- property: this.gobbleIdentifier()
29583
- };
29584
- }
29585
- if (optional) {
29586
- node.optional = true;
29587
- }
29588
- this.gobbleSpaces();
29589
- ch = this.code;
29590
- }
29591
- return node;
29592
- }
29593
- gobbleNumericLiteral() {
29594
- let number = "", ch, chCode;
29595
- while (Jsep.isDecimalDigit(this.code)) {
29596
- number += this.expr.charAt(this.index++);
29597
- }
29598
- if (this.code === Jsep.PERIOD_CODE) {
29599
- number += this.expr.charAt(this.index++);
29600
- while (Jsep.isDecimalDigit(this.code)) {
29601
- number += this.expr.charAt(this.index++);
29602
- }
29603
- }
29604
- ch = this.char;
29605
- if (ch === "e" || ch === "E") {
29606
- number += this.expr.charAt(this.index++);
29607
- ch = this.char;
29608
- if (ch === "+" || ch === "-") {
29609
- number += this.expr.charAt(this.index++);
29610
- }
29611
- while (Jsep.isDecimalDigit(this.code)) {
29612
- number += this.expr.charAt(this.index++);
29613
- }
29614
- if (!Jsep.isDecimalDigit(this.expr.charCodeAt(this.index - 1))) {
29615
- this.throwError("Expected exponent (" + number + this.char + ")");
29616
- }
29617
- }
29618
- chCode = this.code;
29619
- if (Jsep.isIdentifierStart(chCode)) {
29620
- this.throwError("Variable names cannot start with a number (" + number + this.char + ")");
29621
- } else if (chCode === Jsep.PERIOD_CODE || number.length === 1 && number.charCodeAt(0) === Jsep.PERIOD_CODE) {
29622
- this.throwError("Unexpected period");
29623
- }
29624
- return {
29625
- type: Jsep.LITERAL,
29626
- value: parseFloat(number),
29627
- raw: number
29628
- };
29629
- }
29630
- gobbleStringLiteral() {
29631
- let str = "";
29632
- const startIndex = this.index;
29633
- const quote = this.expr.charAt(this.index++);
29634
- let closed = false;
29635
- while (this.index < this.expr.length) {
29636
- let ch = this.expr.charAt(this.index++);
29637
- if (ch === quote) {
29638
- closed = true;
29639
- break;
29640
- } else if (ch === "\\") {
29641
- ch = this.expr.charAt(this.index++);
29642
- switch (ch) {
29643
- case "n":
29644
- str += `
29645
- `;
29646
- break;
29647
- case "r":
29648
- str += "\r";
29649
- break;
29650
- case "t":
29651
- str += "\t";
29652
- break;
29653
- case "b":
29654
- str += "\b";
29655
- break;
29656
- case "f":
29657
- str += "\f";
29658
- break;
29659
- case "v":
29660
- str += "\v";
29661
- break;
29662
- default:
29663
- str += ch;
29664
- }
29665
- } else {
29666
- str += ch;
29667
- }
29668
- }
29669
- if (!closed) {
29670
- this.throwError('Unclosed quote after "' + str + '"');
29671
- }
29672
- return {
29673
- type: Jsep.LITERAL,
29674
- value: str,
29675
- raw: this.expr.substring(startIndex, this.index)
29676
- };
29677
- }
29678
- gobbleIdentifier() {
29679
- let ch = this.code, start = this.index;
29680
- if (Jsep.isIdentifierStart(ch)) {
29681
- this.index++;
29682
- } else {
29683
- this.throwError("Unexpected " + this.char);
29684
- }
29685
- while (this.index < this.expr.length) {
29686
- ch = this.code;
29687
- if (Jsep.isIdentifierPart(ch)) {
29688
- this.index++;
29689
- } else {
29690
- break;
29691
- }
29692
- }
29693
- return {
29694
- type: Jsep.IDENTIFIER,
29695
- name: this.expr.slice(start, this.index)
29696
- };
29697
- }
29698
- gobbleArguments(termination) {
29699
- const args = [];
29700
- let closed = false;
29701
- let separator_count = 0;
29702
- while (this.index < this.expr.length) {
29703
- this.gobbleSpaces();
29704
- let ch_i = this.code;
29705
- if (ch_i === termination) {
29706
- closed = true;
29707
- this.index++;
29708
- if (termination === Jsep.CPAREN_CODE && separator_count && separator_count >= args.length) {
29709
- this.throwError("Unexpected token " + String.fromCharCode(termination));
29710
- }
29711
- break;
29712
- } else if (ch_i === Jsep.COMMA_CODE) {
29713
- this.index++;
29714
- separator_count++;
29715
- if (separator_count !== args.length) {
29716
- if (termination === Jsep.CPAREN_CODE) {
29717
- this.throwError("Unexpected token ,");
29718
- } else if (termination === Jsep.CBRACK_CODE) {
29719
- for (let arg = args.length;arg < separator_count; arg++) {
29720
- args.push(null);
29721
- }
29722
- }
29723
- }
29724
- } else if (args.length !== separator_count && separator_count !== 0) {
29725
- this.throwError("Expected comma");
29726
- } else {
29727
- const node = this.gobbleExpression();
29728
- if (!node || node.type === Jsep.COMPOUND) {
29729
- this.throwError("Expected comma");
29730
- }
29731
- args.push(node);
29732
- }
29733
- }
29734
- if (!closed) {
29735
- this.throwError("Expected " + String.fromCharCode(termination));
29736
- }
29737
- return args;
29738
- }
29739
- gobbleGroup() {
29740
- this.index++;
29741
- let nodes = this.gobbleExpressions(Jsep.CPAREN_CODE);
29742
- if (this.code === Jsep.CPAREN_CODE) {
29743
- this.index++;
29744
- if (nodes.length === 1) {
29745
- return nodes[0];
29746
- } else if (!nodes.length) {
29747
- return false;
29748
- } else {
29749
- return {
29750
- type: Jsep.SEQUENCE_EXP,
29751
- expressions: nodes
29752
- };
29753
- }
29754
- } else {
29755
- this.throwError("Unclosed (");
29756
- }
29757
- }
29758
- gobbleArray() {
29759
- this.index++;
29760
- return {
29761
- type: Jsep.ARRAY_EXP,
29762
- elements: this.gobbleArguments(Jsep.CBRACK_CODE)
29763
- };
29764
- }
29765
- }
29766
- var hooks = new Hooks;
29767
- Object.assign(Jsep, {
29768
- hooks,
29769
- plugins: new Plugins(Jsep),
29770
- COMPOUND: "Compound",
29771
- SEQUENCE_EXP: "SequenceExpression",
29772
- IDENTIFIER: "Identifier",
29773
- MEMBER_EXP: "MemberExpression",
29774
- LITERAL: "Literal",
29775
- THIS_EXP: "ThisExpression",
29776
- CALL_EXP: "CallExpression",
29777
- UNARY_EXP: "UnaryExpression",
29778
- BINARY_EXP: "BinaryExpression",
29779
- ARRAY_EXP: "ArrayExpression",
29780
- TAB_CODE: 9,
29781
- LF_CODE: 10,
29782
- CR_CODE: 13,
29783
- SPACE_CODE: 32,
29784
- PERIOD_CODE: 46,
29785
- COMMA_CODE: 44,
29786
- SQUOTE_CODE: 39,
29787
- DQUOTE_CODE: 34,
29788
- OPAREN_CODE: 40,
29789
- CPAREN_CODE: 41,
29790
- OBRACK_CODE: 91,
29791
- CBRACK_CODE: 93,
29792
- QUMARK_CODE: 63,
29793
- SEMCOL_CODE: 59,
29794
- COLON_CODE: 58,
29795
- unary_ops: {
29796
- "-": 1,
29797
- "!": 1,
29798
- "~": 1,
29799
- "+": 1
29800
- },
29801
- binary_ops: {
29802
- "||": 1,
29803
- "??": 1,
29804
- "&&": 2,
29805
- "|": 3,
29806
- "^": 4,
29807
- "&": 5,
29808
- "==": 6,
29809
- "!=": 6,
29810
- "===": 6,
29811
- "!==": 6,
29812
- "<": 7,
29813
- ">": 7,
29814
- "<=": 7,
29815
- ">=": 7,
29816
- "<<": 8,
29817
- ">>": 8,
29818
- ">>>": 8,
29819
- "+": 9,
29820
- "-": 9,
29821
- "*": 10,
29822
- "/": 10,
29823
- "%": 10,
29824
- "**": 11
29825
- },
29826
- right_associative: new Set(["**"]),
29827
- additional_identifier_chars: new Set(["$", "_"]),
29828
- literals: {
29829
- true: true,
29830
- false: false,
29831
- null: null
29832
- },
29833
- this_str: "this"
29834
- });
29835
- Jsep.max_unop_len = Jsep.getMaxKeyLen(Jsep.unary_ops);
29836
- Jsep.max_binop_len = Jsep.getMaxKeyLen(Jsep.binary_ops);
29837
- var jsep = (expr) => new Jsep(expr).parse();
29838
- var stdClassProps = Object.getOwnPropertyNames(class Test {
29839
- });
29840
- Object.getOwnPropertyNames(Jsep).filter((prop) => !stdClassProps.includes(prop) && jsep[prop] === undefined).forEach((m) => {
29841
- jsep[m] = Jsep[m];
29842
- });
29843
- jsep.Jsep = Jsep;
29844
- var CONDITIONAL_EXP = "ConditionalExpression";
29845
- var ternary = {
29846
- name: "ternary",
29847
- init(jsep2) {
29848
- jsep2.hooks.add("after-expression", function gobbleTernary(env) {
29849
- if (env.node && this.code === jsep2.QUMARK_CODE) {
29850
- this.index++;
29851
- const test = env.node;
29852
- const consequent = this.gobbleExpression();
29853
- if (!consequent) {
29854
- this.throwError("Expected expression");
29855
- }
29856
- this.gobbleSpaces();
29857
- if (this.code === jsep2.COLON_CODE) {
29858
- this.index++;
29859
- const alternate = this.gobbleExpression();
29860
- if (!alternate) {
29861
- this.throwError("Expected expression");
29862
- }
29863
- env.node = {
29864
- type: CONDITIONAL_EXP,
29865
- test,
29866
- consequent,
29867
- alternate
29868
- };
29869
- if (test.operator && jsep2.binary_ops[test.operator] <= 0.9) {
29870
- let newTest = test;
29871
- while (newTest.right.operator && jsep2.binary_ops[newTest.right.operator] <= 0.9) {
29872
- newTest = newTest.right;
29873
- }
29874
- env.node.test = newTest.right;
29875
- newTest.right = env.node;
29876
- env.node = test;
29877
- }
29878
- } else {
29879
- this.throwError("Expected :");
29880
- }
29881
- }
29882
- });
29883
- }
29884
- };
29885
- jsep.plugins.register(ternary);
29886
- var FSLASH_CODE = 47;
29887
- var BSLASH_CODE = 92;
29888
- var index = {
29889
- name: "regex",
29890
- init(jsep2) {
29891
- jsep2.hooks.add("gobble-token", function gobbleRegexLiteral(env) {
29892
- if (this.code === FSLASH_CODE) {
29893
- const patternIndex = ++this.index;
29894
- let inCharSet = false;
29895
- while (this.index < this.expr.length) {
29896
- if (this.code === FSLASH_CODE && !inCharSet) {
29897
- const pattern = this.expr.slice(patternIndex, this.index);
29898
- let flags = "";
29899
- while (++this.index < this.expr.length) {
29900
- const code = this.code;
29901
- if (code >= 97 && code <= 122 || code >= 65 && code <= 90 || code >= 48 && code <= 57) {
29902
- flags += this.char;
29903
- } else {
29904
- break;
29905
- }
29906
- }
29907
- let value;
29908
- try {
29909
- value = new RegExp(pattern, flags);
29910
- } catch (e) {
29911
- this.throwError(e.message);
29912
- }
29913
- env.node = {
29914
- type: jsep2.LITERAL,
29915
- value,
29916
- raw: this.expr.slice(patternIndex - 1, this.index)
29917
- };
29918
- env.node = this.gobbleTokenProperty(env.node);
29919
- return env.node;
29920
- }
29921
- if (this.code === jsep2.OBRACK_CODE) {
29922
- inCharSet = true;
29923
- } else if (inCharSet && this.code === jsep2.CBRACK_CODE) {
29924
- inCharSet = false;
29925
- }
29926
- this.index += this.code === BSLASH_CODE ? 2 : 1;
29927
- }
29928
- this.throwError("Unclosed Regex");
29929
- }
29930
- });
29931
- }
29932
- };
29933
- var PLUS_CODE = 43;
29934
- var MINUS_CODE = 45;
29935
- var plugin = {
29936
- name: "assignment",
29937
- assignmentOperators: new Set(["=", "*=", "**=", "/=", "%=", "+=", "-=", "<<=", ">>=", ">>>=", "&=", "^=", "|=", "||=", "&&=", "??="]),
29938
- updateOperators: [PLUS_CODE, MINUS_CODE],
29939
- assignmentPrecedence: 0.9,
29940
- init(jsep2) {
29941
- const updateNodeTypes = [jsep2.IDENTIFIER, jsep2.MEMBER_EXP];
29942
- plugin.assignmentOperators.forEach((op) => jsep2.addBinaryOp(op, plugin.assignmentPrecedence, true));
29943
- jsep2.hooks.add("gobble-token", function gobbleUpdatePrefix(env) {
29944
- const code = this.code;
29945
- if (plugin.updateOperators.some((c) => c === code && c === this.expr.charCodeAt(this.index + 1))) {
29946
- this.index += 2;
29947
- env.node = {
29948
- type: "UpdateExpression",
29949
- operator: code === PLUS_CODE ? "++" : "--",
29950
- argument: this.gobbleTokenProperty(this.gobbleIdentifier()),
29951
- prefix: true
29952
- };
29953
- if (!env.node.argument || !updateNodeTypes.includes(env.node.argument.type)) {
29954
- this.throwError(`Unexpected ${env.node.operator}`);
29955
- }
29956
- }
29957
- });
29958
- jsep2.hooks.add("after-token", function gobbleUpdatePostfix(env) {
29959
- if (env.node) {
29960
- const code = this.code;
29961
- if (plugin.updateOperators.some((c) => c === code && c === this.expr.charCodeAt(this.index + 1))) {
29962
- if (!updateNodeTypes.includes(env.node.type)) {
29963
- this.throwError(`Unexpected ${env.node.operator}`);
29964
- }
29965
- this.index += 2;
29966
- env.node = {
29967
- type: "UpdateExpression",
29968
- operator: code === PLUS_CODE ? "++" : "--",
29969
- argument: env.node,
29970
- prefix: false
29971
- };
29972
- }
29973
- }
29974
- });
29975
- jsep2.hooks.add("after-expression", function gobbleAssignment(env) {
29976
- if (env.node) {
29977
- updateBinariesToAssignments(env.node);
29978
- }
29979
- });
29980
- function updateBinariesToAssignments(node) {
29981
- if (plugin.assignmentOperators.has(node.operator)) {
29982
- node.type = "AssignmentExpression";
29983
- updateBinariesToAssignments(node.left);
29984
- updateBinariesToAssignments(node.right);
29985
- } else if (!node.operator) {
29986
- Object.values(node).forEach((val) => {
29987
- if (val && typeof val === "object") {
29988
- updateBinariesToAssignments(val);
29989
- }
29990
- });
29991
- }
29992
- }
29993
- }
29994
- };
29995
- jsep.plugins.register(index, plugin);
29996
- jsep.addUnaryOp("typeof");
29997
- jsep.addUnaryOp("void");
29998
- jsep.addLiteral("null", null);
29999
- jsep.addLiteral("undefined", undefined);
30000
- var BLOCKED_PROTO_PROPERTIES = new Set(["constructor", "__proto__", "__defineGetter__", "__defineSetter__", "__lookupGetter__", "__lookupSetter__"]);
30001
- var SafeEval = {
30002
- evalAst(ast, subs) {
30003
- switch (ast.type) {
30004
- case "BinaryExpression":
30005
- case "LogicalExpression":
30006
- return SafeEval.evalBinaryExpression(ast, subs);
30007
- case "Compound":
30008
- return SafeEval.evalCompound(ast, subs);
30009
- case "ConditionalExpression":
30010
- return SafeEval.evalConditionalExpression(ast, subs);
30011
- case "Identifier":
30012
- return SafeEval.evalIdentifier(ast, subs);
30013
- case "Literal":
30014
- return SafeEval.evalLiteral(ast, subs);
30015
- case "MemberExpression":
30016
- return SafeEval.evalMemberExpression(ast, subs);
30017
- case "UnaryExpression":
30018
- return SafeEval.evalUnaryExpression(ast, subs);
30019
- case "ArrayExpression":
30020
- return SafeEval.evalArrayExpression(ast, subs);
30021
- case "CallExpression":
30022
- return SafeEval.evalCallExpression(ast, subs);
30023
- case "AssignmentExpression":
30024
- return SafeEval.evalAssignmentExpression(ast, subs);
30025
- default:
30026
- throw SyntaxError("Unexpected expression", ast);
30027
- }
30028
- },
30029
- evalBinaryExpression(ast, subs) {
30030
- const result = {
30031
- "||": (a, b) => a || b(),
30032
- "&&": (a, b) => a && b(),
30033
- "|": (a, b) => a | b(),
30034
- "^": (a, b) => a ^ b(),
30035
- "&": (a, b) => a & b(),
30036
- "==": (a, b) => a == b(),
30037
- "!=": (a, b) => a != b(),
30038
- "===": (a, b) => a === b(),
30039
- "!==": (a, b) => a !== b(),
30040
- "<": (a, b) => a < b(),
30041
- ">": (a, b) => a > b(),
30042
- "<=": (a, b) => a <= b(),
30043
- ">=": (a, b) => a >= b(),
30044
- "<<": (a, b) => a << b(),
30045
- ">>": (a, b) => a >> b(),
30046
- ">>>": (a, b) => a >>> b(),
30047
- "+": (a, b) => a + b(),
30048
- "-": (a, b) => a - b(),
30049
- "*": (a, b) => a * b(),
30050
- "/": (a, b) => a / b(),
30051
- "%": (a, b) => a % b()
30052
- }[ast.operator](SafeEval.evalAst(ast.left, subs), () => SafeEval.evalAst(ast.right, subs));
30053
- return result;
30054
- },
30055
- evalCompound(ast, subs) {
30056
- let last;
30057
- for (let i = 0;i < ast.body.length; i++) {
30058
- if (ast.body[i].type === "Identifier" && ["var", "let", "const"].includes(ast.body[i].name) && ast.body[i + 1] && ast.body[i + 1].type === "AssignmentExpression") {
30059
- i += 1;
30060
- }
30061
- const expr = ast.body[i];
30062
- last = SafeEval.evalAst(expr, subs);
30063
- }
30064
- return last;
30065
- },
30066
- evalConditionalExpression(ast, subs) {
30067
- if (SafeEval.evalAst(ast.test, subs)) {
30068
- return SafeEval.evalAst(ast.consequent, subs);
30069
- }
30070
- return SafeEval.evalAst(ast.alternate, subs);
30071
- },
30072
- evalIdentifier(ast, subs) {
30073
- if (Object.hasOwn(subs, ast.name)) {
30074
- return subs[ast.name];
30075
- }
30076
- throw ReferenceError(`${ast.name} is not defined`);
30077
- },
30078
- evalLiteral(ast) {
30079
- return ast.value;
30080
- },
30081
- evalMemberExpression(ast, subs) {
30082
- const prop = String(ast.computed ? SafeEval.evalAst(ast.property) : ast.property.name);
30083
- const obj = SafeEval.evalAst(ast.object, subs);
30084
- if (obj === undefined || obj === null) {
30085
- throw TypeError(`Cannot read properties of ${obj} (reading '${prop}')`);
30086
- }
30087
- if (!Object.hasOwn(obj, prop) && BLOCKED_PROTO_PROPERTIES.has(prop)) {
30088
- throw TypeError(`Cannot read properties of ${obj} (reading '${prop}')`);
30089
- }
30090
- const result = obj[prop];
30091
- if (typeof result === "function") {
30092
- return result.bind(obj);
30093
- }
30094
- return result;
30095
- },
30096
- evalUnaryExpression(ast, subs) {
30097
- const result = {
30098
- "-": (a) => -SafeEval.evalAst(a, subs),
30099
- "!": (a) => !SafeEval.evalAst(a, subs),
30100
- "~": (a) => ~SafeEval.evalAst(a, subs),
30101
- "+": (a) => +SafeEval.evalAst(a, subs),
30102
- typeof: (a) => typeof SafeEval.evalAst(a, subs),
30103
- void: (a) => void SafeEval.evalAst(a, subs)
30104
- }[ast.operator](ast.argument);
30105
- return result;
30106
- },
30107
- evalArrayExpression(ast, subs) {
30108
- return ast.elements.map((el) => SafeEval.evalAst(el, subs));
30109
- },
30110
- evalCallExpression(ast, subs) {
30111
- const args = ast.arguments.map((arg) => SafeEval.evalAst(arg, subs));
30112
- const func = SafeEval.evalAst(ast.callee, subs);
30113
- if (func === Function) {
30114
- throw new Error("Function constructor is disabled");
30115
- }
30116
- return func(...args);
30117
- },
30118
- evalAssignmentExpression(ast, subs) {
30119
- if (ast.left.type !== "Identifier") {
30120
- throw SyntaxError("Invalid left-hand side in assignment");
30121
- }
30122
- const id = ast.left.name;
30123
- const value = SafeEval.evalAst(ast.right, subs);
30124
- subs[id] = value;
30125
- return subs[id];
30126
- }
30127
- };
30128
-
30129
- class SafeScript {
30130
- constructor(expr) {
30131
- this.code = expr;
30132
- this.ast = jsep(this.code);
30133
- }
30134
- runInNewContext(context) {
30135
- const keyMap = Object.assign(Object.create(null), context);
30136
- return SafeEval.evalAst(this.ast, keyMap);
30137
- }
30138
- }
30139
- function push(arr, item) {
30140
- arr = arr.slice();
30141
- arr.push(item);
30142
- return arr;
30143
- }
30144
- function unshift(item, arr) {
30145
- arr = arr.slice();
30146
- arr.unshift(item);
30147
- return arr;
30148
- }
30149
-
30150
- class NewError extends Error {
30151
- constructor(value) {
30152
- super('JSONPath should not be called with "new" (it prevents return ' + "of (unwrapped) scalar values)");
30153
- this.avoidNew = true;
30154
- this.value = value;
30155
- this.name = "NewError";
30156
- }
30157
- }
30158
- function JSONPath(opts, expr, obj, callback, otherTypeCallback) {
30159
- if (!(this instanceof JSONPath)) {
30160
- try {
30161
- return new JSONPath(opts, expr, obj, callback, otherTypeCallback);
30162
- } catch (e) {
30163
- if (!e.avoidNew) {
30164
- throw e;
30165
- }
30166
- return e.value;
30167
- }
30168
- }
30169
- if (typeof opts === "string") {
30170
- otherTypeCallback = callback;
30171
- callback = obj;
30172
- obj = expr;
30173
- expr = opts;
30174
- opts = null;
30175
- }
30176
- const optObj = opts && typeof opts === "object";
30177
- opts = opts || {};
30178
- this.json = opts.json || obj;
30179
- this.path = opts.path || expr;
30180
- this.resultType = opts.resultType || "value";
30181
- this.flatten = opts.flatten || false;
30182
- this.wrap = Object.hasOwn(opts, "wrap") ? opts.wrap : true;
30183
- this.sandbox = opts.sandbox || {};
30184
- this.eval = opts.eval === undefined ? "safe" : opts.eval;
30185
- this.ignoreEvalErrors = typeof opts.ignoreEvalErrors === "undefined" ? false : opts.ignoreEvalErrors;
30186
- this.parent = opts.parent || null;
30187
- this.parentProperty = opts.parentProperty || null;
30188
- this.callback = opts.callback || callback || null;
30189
- this.otherTypeCallback = opts.otherTypeCallback || otherTypeCallback || function() {
30190
- throw new TypeError("You must supply an otherTypeCallback callback option " + "with the @other() operator.");
30191
- };
30192
- if (opts.autostart !== false) {
30193
- const args = {
30194
- path: optObj ? opts.path : expr
30195
- };
30196
- if (!optObj) {
30197
- args.json = obj;
30198
- } else if ("json" in opts) {
30199
- args.json = opts.json;
30200
- }
30201
- const ret = this.evaluate(args);
30202
- if (!ret || typeof ret !== "object") {
30203
- throw new NewError(ret);
30204
- }
30205
- return ret;
30206
- }
30207
- }
30208
- JSONPath.prototype.evaluate = function(expr, json, callback, otherTypeCallback) {
30209
- let currParent = this.parent, currParentProperty = this.parentProperty;
30210
- let {
30211
- flatten,
30212
- wrap
30213
- } = this;
30214
- this.currResultType = this.resultType;
30215
- this.currEval = this.eval;
30216
- this.currSandbox = this.sandbox;
30217
- callback = callback || this.callback;
30218
- this.currOtherTypeCallback = otherTypeCallback || this.otherTypeCallback;
30219
- json = json || this.json;
30220
- expr = expr || this.path;
30221
- if (expr && typeof expr === "object" && !Array.isArray(expr)) {
30222
- if (!expr.path && expr.path !== "") {
30223
- throw new TypeError('You must supply a "path" property when providing an object ' + "argument to JSONPath.evaluate().");
30224
- }
30225
- if (!Object.hasOwn(expr, "json")) {
30226
- throw new TypeError('You must supply a "json" property when providing an object ' + "argument to JSONPath.evaluate().");
30227
- }
30228
- ({
30229
- json
30230
- } = expr);
30231
- flatten = Object.hasOwn(expr, "flatten") ? expr.flatten : flatten;
30232
- this.currResultType = Object.hasOwn(expr, "resultType") ? expr.resultType : this.currResultType;
30233
- this.currSandbox = Object.hasOwn(expr, "sandbox") ? expr.sandbox : this.currSandbox;
30234
- wrap = Object.hasOwn(expr, "wrap") ? expr.wrap : wrap;
30235
- this.currEval = Object.hasOwn(expr, "eval") ? expr.eval : this.currEval;
30236
- callback = Object.hasOwn(expr, "callback") ? expr.callback : callback;
30237
- this.currOtherTypeCallback = Object.hasOwn(expr, "otherTypeCallback") ? expr.otherTypeCallback : this.currOtherTypeCallback;
30238
- currParent = Object.hasOwn(expr, "parent") ? expr.parent : currParent;
30239
- currParentProperty = Object.hasOwn(expr, "parentProperty") ? expr.parentProperty : currParentProperty;
30240
- expr = expr.path;
30241
- }
30242
- currParent = currParent || null;
30243
- currParentProperty = currParentProperty || null;
30244
- if (Array.isArray(expr)) {
30245
- expr = JSONPath.toPathString(expr);
30246
- }
30247
- if (!expr && expr !== "" || !json) {
30248
- return;
30249
- }
30250
- const exprList = JSONPath.toPathArray(expr);
30251
- if (exprList[0] === "$" && exprList.length > 1) {
30252
- exprList.shift();
30253
- }
30254
- this._hasParentSelector = null;
30255
- const result = this._trace(exprList, json, ["$"], currParent, currParentProperty, callback).filter(function(ea) {
30256
- return ea && !ea.isParentSelector;
30257
- });
30258
- if (!result.length) {
30259
- return wrap ? [] : undefined;
30260
- }
30261
- if (!wrap && result.length === 1 && !result[0].hasArrExpr) {
30262
- return this._getPreferredOutput(result[0]);
30263
- }
30264
- return result.reduce((rslt, ea) => {
30265
- const valOrPath = this._getPreferredOutput(ea);
30266
- if (flatten && Array.isArray(valOrPath)) {
30267
- rslt = rslt.concat(valOrPath);
30268
- } else {
30269
- rslt.push(valOrPath);
30270
- }
30271
- return rslt;
30272
- }, []);
30273
- };
30274
- JSONPath.prototype._getPreferredOutput = function(ea) {
30275
- const resultType = this.currResultType;
30276
- switch (resultType) {
30277
- case "all": {
30278
- const path3 = Array.isArray(ea.path) ? ea.path : JSONPath.toPathArray(ea.path);
30279
- ea.pointer = JSONPath.toPointer(path3);
30280
- ea.path = typeof ea.path === "string" ? ea.path : JSONPath.toPathString(ea.path);
30281
- return ea;
30282
- }
30283
- case "value":
30284
- case "parent":
30285
- case "parentProperty":
30286
- return ea[resultType];
30287
- case "path":
30288
- return JSONPath.toPathString(ea[resultType]);
30289
- case "pointer":
30290
- return JSONPath.toPointer(ea.path);
30291
- default:
30292
- throw new TypeError("Unknown result type");
30293
- }
30294
- };
30295
- JSONPath.prototype._handleCallback = function(fullRetObj, callback, type) {
30296
- if (callback) {
30297
- const preferredOutput = this._getPreferredOutput(fullRetObj);
30298
- fullRetObj.path = typeof fullRetObj.path === "string" ? fullRetObj.path : JSONPath.toPathString(fullRetObj.path);
30299
- callback(preferredOutput, type, fullRetObj);
30300
- }
30301
- };
30302
- JSONPath.prototype._trace = function(expr, val, path3, parent, parentPropName, callback, hasArrExpr, literalPriority) {
30303
- let retObj;
30304
- if (!expr.length) {
30305
- retObj = {
30306
- path: path3,
30307
- value: val,
30308
- parent,
30309
- parentProperty: parentPropName,
30310
- hasArrExpr
30311
- };
30312
- this._handleCallback(retObj, callback, "value");
30313
- return retObj;
30314
- }
30315
- const loc = expr[0], x = expr.slice(1);
30316
- const ret = [];
30317
- function addRet(elems) {
30318
- if (Array.isArray(elems)) {
30319
- elems.forEach((t) => {
30320
- ret.push(t);
30321
- });
30322
- } else {
30323
- ret.push(elems);
30324
- }
30325
- }
30326
- if ((typeof loc !== "string" || literalPriority) && val && Object.hasOwn(val, loc)) {
30327
- addRet(this._trace(x, val[loc], push(path3, loc), val, loc, callback, hasArrExpr));
30328
- } else if (loc === "*") {
30329
- this._walk(val, (m) => {
30330
- addRet(this._trace(x, val[m], push(path3, m), val, m, callback, true, true));
30331
- });
30332
- } else if (loc === "..") {
30333
- addRet(this._trace(x, val, path3, parent, parentPropName, callback, hasArrExpr));
30334
- this._walk(val, (m) => {
30335
- if (typeof val[m] === "object") {
30336
- addRet(this._trace(expr.slice(), val[m], push(path3, m), val, m, callback, true));
30337
- }
30338
- });
30339
- } else if (loc === "^") {
30340
- this._hasParentSelector = true;
30341
- return {
30342
- path: path3.slice(0, -1),
30343
- expr: x,
30344
- isParentSelector: true
30345
- };
30346
- } else if (loc === "~") {
30347
- retObj = {
30348
- path: push(path3, loc),
30349
- value: parentPropName,
30350
- parent,
30351
- parentProperty: null
30352
- };
30353
- this._handleCallback(retObj, callback, "property");
30354
- return retObj;
30355
- } else if (loc === "$") {
30356
- addRet(this._trace(x, val, path3, null, null, callback, hasArrExpr));
30357
- } else if (/^(-?\d*):(-?\d*):?(\d*)$/u.test(loc)) {
30358
- addRet(this._slice(loc, x, val, path3, parent, parentPropName, callback));
30359
- } else if (loc.indexOf("?(") === 0) {
30360
- if (this.currEval === false) {
30361
- throw new Error("Eval [?(expr)] prevented in JSONPath expression.");
30362
- }
30363
- const safeLoc = loc.replace(/^\?\((.*?)\)$/u, "$1");
30364
- const nested = /@.?([^?]*)[['](\??\(.*?\))(?!.\)\])[\]']/gu.exec(safeLoc);
30365
- if (nested) {
30366
- this._walk(val, (m) => {
30367
- const npath = [nested[2]];
30368
- const nvalue = nested[1] ? val[m][nested[1]] : val[m];
30369
- const filterResults = this._trace(npath, nvalue, path3, parent, parentPropName, callback, true);
30370
- if (filterResults.length > 0) {
30371
- addRet(this._trace(x, val[m], push(path3, m), val, m, callback, true));
30372
- }
30373
- });
30374
- } else {
30375
- this._walk(val, (m) => {
30376
- if (this._eval(safeLoc, val[m], m, path3, parent, parentPropName)) {
30377
- addRet(this._trace(x, val[m], push(path3, m), val, m, callback, true));
30378
- }
30379
- });
30380
- }
30381
- } else if (loc[0] === "(") {
30382
- if (this.currEval === false) {
30383
- throw new Error("Eval [(expr)] prevented in JSONPath expression.");
30384
- }
30385
- addRet(this._trace(unshift(this._eval(loc, val, path3.at(-1), path3.slice(0, -1), parent, parentPropName), x), val, path3, parent, parentPropName, callback, hasArrExpr));
30386
- } else if (loc[0] === "@") {
30387
- let addType = false;
30388
- const valueType = loc.slice(1, -2);
30389
- switch (valueType) {
30390
- case "scalar":
30391
- if (!val || !["object", "function"].includes(typeof val)) {
30392
- addType = true;
30393
- }
30394
- break;
30395
- case "boolean":
30396
- case "string":
30397
- case "undefined":
30398
- case "function":
30399
- if (typeof val === valueType) {
30400
- addType = true;
30401
- }
30402
- break;
30403
- case "integer":
30404
- if (Number.isFinite(val) && !(val % 1)) {
30405
- addType = true;
30406
- }
30407
- break;
30408
- case "number":
30409
- if (Number.isFinite(val)) {
30410
- addType = true;
30411
- }
30412
- break;
30413
- case "nonFinite":
30414
- if (typeof val === "number" && !Number.isFinite(val)) {
30415
- addType = true;
30416
- }
30417
- break;
30418
- case "object":
30419
- if (val && typeof val === valueType) {
30420
- addType = true;
30421
- }
30422
- break;
30423
- case "array":
30424
- if (Array.isArray(val)) {
30425
- addType = true;
30426
- }
30427
- break;
30428
- case "other":
30429
- addType = this.currOtherTypeCallback(val, path3, parent, parentPropName);
30430
- break;
30431
- case "null":
30432
- if (val === null) {
30433
- addType = true;
30434
- }
30435
- break;
30436
- default:
30437
- throw new TypeError("Unknown value type " + valueType);
30438
- }
30439
- if (addType) {
30440
- retObj = {
30441
- path: path3,
30442
- value: val,
30443
- parent,
30444
- parentProperty: parentPropName
30445
- };
30446
- this._handleCallback(retObj, callback, "value");
30447
- return retObj;
30448
- }
30449
- } else if (loc[0] === "`" && val && Object.hasOwn(val, loc.slice(1))) {
30450
- const locProp = loc.slice(1);
30451
- addRet(this._trace(x, val[locProp], push(path3, locProp), val, locProp, callback, hasArrExpr, true));
30452
- } else if (loc.includes(",")) {
30453
- const parts = loc.split(",");
30454
- for (const part of parts) {
30455
- addRet(this._trace(unshift(part, x), val, path3, parent, parentPropName, callback, true));
30456
- }
30457
- } else if (!literalPriority && val && Object.hasOwn(val, loc)) {
30458
- addRet(this._trace(x, val[loc], push(path3, loc), val, loc, callback, hasArrExpr, true));
30459
- }
30460
- if (this._hasParentSelector) {
30461
- for (let t = 0;t < ret.length; t++) {
30462
- const rett = ret[t];
30463
- if (rett && rett.isParentSelector) {
30464
- const tmp = this._trace(rett.expr, val, rett.path, parent, parentPropName, callback, hasArrExpr);
30465
- if (Array.isArray(tmp)) {
30466
- ret[t] = tmp[0];
30467
- const tl = tmp.length;
30468
- for (let tt = 1;tt < tl; tt++) {
30469
- t++;
30470
- ret.splice(t, 0, tmp[tt]);
30471
- }
30472
- } else {
30473
- ret[t] = tmp;
30474
- }
30475
- }
30476
- }
30477
- }
30478
- return ret;
30479
- };
30480
- JSONPath.prototype._walk = function(val, f) {
30481
- if (Array.isArray(val)) {
30482
- const n = val.length;
30483
- for (let i = 0;i < n; i++) {
30484
- f(i);
30485
- }
30486
- } else if (val && typeof val === "object") {
30487
- Object.keys(val).forEach((m) => {
30488
- f(m);
30489
- });
30490
- }
30491
- };
30492
- JSONPath.prototype._slice = function(loc, expr, val, path3, parent, parentPropName, callback) {
30493
- if (!Array.isArray(val)) {
30494
- return;
30495
- }
30496
- const len = val.length, parts = loc.split(":"), step = parts[2] && Number.parseInt(parts[2]) || 1;
30497
- let start = parts[0] && Number.parseInt(parts[0]) || 0, end = parts[1] && Number.parseInt(parts[1]) || len;
30498
- start = start < 0 ? Math.max(0, start + len) : Math.min(len, start);
30499
- end = end < 0 ? Math.max(0, end + len) : Math.min(len, end);
30500
- const ret = [];
30501
- for (let i = start;i < end; i += step) {
30502
- const tmp = this._trace(unshift(i, expr), val, path3, parent, parentPropName, callback, true);
30503
- tmp.forEach((t) => {
30504
- ret.push(t);
30505
- });
30506
- }
30507
- return ret;
30508
- };
30509
- JSONPath.prototype._eval = function(code, _v, _vname, path3, parent, parentPropName) {
30510
- this.currSandbox._$_parentProperty = parentPropName;
30511
- this.currSandbox._$_parent = parent;
30512
- this.currSandbox._$_property = _vname;
30513
- this.currSandbox._$_root = this.json;
30514
- this.currSandbox._$_v = _v;
30515
- const containsPath = code.includes("@path");
30516
- if (containsPath) {
30517
- this.currSandbox._$_path = JSONPath.toPathString(path3.concat([_vname]));
30518
- }
30519
- const scriptCacheKey = this.currEval + "Script:" + code;
30520
- if (!JSONPath.cache[scriptCacheKey]) {
30521
- let script = code.replaceAll("@parentProperty", "_$_parentProperty").replaceAll("@parent", "_$_parent").replaceAll("@property", "_$_property").replaceAll("@root", "_$_root").replaceAll(/@([.\s)[])/gu, "_$_v$1");
30522
- if (containsPath) {
30523
- script = script.replaceAll("@path", "_$_path");
30524
- }
30525
- if (this.currEval === "safe" || this.currEval === true || this.currEval === undefined) {
30526
- JSONPath.cache[scriptCacheKey] = new this.safeVm.Script(script);
30527
- } else if (this.currEval === "native") {
30528
- JSONPath.cache[scriptCacheKey] = new this.vm.Script(script);
30529
- } else if (typeof this.currEval === "function" && this.currEval.prototype && Object.hasOwn(this.currEval.prototype, "runInNewContext")) {
30530
- const CurrEval = this.currEval;
30531
- JSONPath.cache[scriptCacheKey] = new CurrEval(script);
30532
- } else if (typeof this.currEval === "function") {
30533
- JSONPath.cache[scriptCacheKey] = {
30534
- runInNewContext: (context) => this.currEval(script, context)
30535
- };
30536
- } else {
30537
- throw new TypeError(`Unknown "eval" property "${this.currEval}"`);
30538
- }
30539
- }
30540
- try {
30541
- return JSONPath.cache[scriptCacheKey].runInNewContext(this.currSandbox);
30542
- } catch (e) {
30543
- if (this.ignoreEvalErrors) {
30544
- return false;
30545
- }
30546
- throw new Error("jsonPath: " + e.message + ": " + code);
30547
- }
30548
- };
30549
- JSONPath.cache = {};
30550
- JSONPath.toPathString = function(pathArr) {
30551
- const x = pathArr, n = x.length;
30552
- let p = "$";
30553
- for (let i = 1;i < n; i++) {
30554
- if (!/^(~|\^|@.*?\(\))$/u.test(x[i])) {
30555
- p += /^[0-9*]+$/u.test(x[i]) ? "[" + x[i] + "]" : "['" + x[i] + "']";
30556
- }
30557
- }
30558
- return p;
30559
- };
30560
- JSONPath.toPointer = function(pointer) {
30561
- const x = pointer, n = x.length;
30562
- let p = "";
30563
- for (let i = 1;i < n; i++) {
30564
- if (!/^(~|\^|@.*?\(\))$/u.test(x[i])) {
30565
- p += "/" + x[i].toString().replaceAll("~", "~0").replaceAll("/", "~1");
30566
- }
30567
- }
30568
- return p;
30569
- };
30570
- JSONPath.toPathArray = function(expr) {
30571
- const {
30572
- cache
30573
- } = JSONPath;
30574
- if (cache[expr]) {
30575
- return cache[expr].concat();
30576
- }
30577
- const subx = [];
30578
- const normalized = expr.replaceAll(/@(?:null|boolean|number|string|integer|undefined|nonFinite|scalar|array|object|function|other)\(\)/gu, ";$&;").replaceAll(/[['](\??\(.*?\))[\]'](?!.\])/gu, function($0, $1) {
30579
- return "[#" + (subx.push($1) - 1) + "]";
30580
- }).replaceAll(/\[['"]([^'\]]*)['"]\]/gu, function($0, prop) {
30581
- return "['" + prop.replaceAll(".", "%@%").replaceAll("~", "%%@@%%") + "']";
30582
- }).replaceAll("~", ";~;").replaceAll(/['"]?\.['"]?(?![^[]*\])|\[['"]?/gu, ";").replaceAll("%@%", ".").replaceAll("%%@@%%", "~").replaceAll(/(?:;)?(\^+)(?:;)?/gu, function($0, ups) {
30583
- return ";" + ups.split("").join(";") + ";";
30584
- }).replaceAll(/;;;|;;/gu, ";..;").replaceAll(/;$|'?\]|'$/gu, "");
30585
- const exprList = normalized.split(";").map(function(exp) {
30586
- const match = exp.match(/#(\d+)/u);
30587
- return !match || !match[1] ? exp : subx[match[1]];
30588
- });
30589
- cache[expr] = exprList;
30590
- return cache[expr].concat();
30591
- };
30592
- JSONPath.prototype.safeVm = {
30593
- Script: SafeScript
30594
- };
30595
- JSONPath.prototype.vm = vm;
30596
29558
  // ../../common/src/option-aliases.ts
30597
29559
  import { Option } from "commander";
30598
29560
  // ../../common/src/option-validators.ts
@@ -30648,6 +29610,18 @@ var FAILURE_STATUSES = new Set([
30648
29610
  "canceled",
30649
29611
  "stopped"
30650
29612
  ]);
29613
+ // ../../common/src/preview.ts
29614
+ import { Command as Command3 } from "commander";
29615
+ var previewSlot = singleton("PreviewBuild");
29616
+ function isPreviewBuild() {
29617
+ return previewSlot.get(false) ?? false;
29618
+ }
29619
+ Command3.prototype.previewCommand = function(nameAndArgs, opts) {
29620
+ if (isPreviewBuild()) {
29621
+ return this.command(nameAndArgs, opts);
29622
+ }
29623
+ return new Command3(nameAndArgs.split(/\s+/)[0] ?? nameAndArgs);
29624
+ };
30651
29625
  // ../../common/src/screen-logger.ts
30652
29626
  var ScreenLogger;
30653
29627
  ((ScreenLogger) => {
@@ -30752,8 +29726,27 @@ async function forEachExportEntry(api, from, to, onEntry) {
30752
29726
  }
30753
29727
  return { days: chunks.length, nonEmptyDays };
30754
29728
  }
30755
- async function downloadChunkedExport(api, from, to) {
30756
- const out = new import_adm_zip.default;
29729
+ function exportBaseName(from, to, generatedAt) {
29730
+ const day = (d) => d.toISOString().slice(0, 10);
29731
+ const stamp = generatedAt.toISOString().slice(0, 19).replace(/[-:]/g, "");
29732
+ return `audit_${day(from)}_${day(to)}_${stamp}`;
29733
+ }
29734
+ function toJsonFileName(preferredName) {
29735
+ return `${basenameNoExt(preferredName)}.json`;
29736
+ }
29737
+ function isSafeExportEntryName(name) {
29738
+ return name.length > 0 && name !== "." && name !== ".." && !name.includes("/") && !name.includes("\\") && !name.includes("\x00");
29739
+ }
29740
+ function isWithinDir(dir, resolved) {
29741
+ let end = dir.length;
29742
+ while (end > 0 && (dir[end - 1] === "/" || dir[end - 1] === "\\")) {
29743
+ end -= 1;
29744
+ }
29745
+ const base = dir.slice(0, end);
29746
+ return resolved === base || resolved.startsWith(`${base}/`) || resolved.startsWith(`${base}\\`);
29747
+ }
29748
+ async function downloadChunkedJsonExport(api, from, to) {
29749
+ const files = [];
30757
29750
  const used = new Set;
30758
29751
  function addUnique(preferredName, isoDay, data) {
30759
29752
  let name = preferredName;
@@ -30768,10 +29761,10 @@ async function downloadChunkedExport(api, from, to) {
30768
29761
  }
30769
29762
  }
30770
29763
  used.add(name);
30771
- out.addFile(name, data);
29764
+ files.push({ name, data });
30772
29765
  }
30773
- const { days, nonEmptyDays } = await forEachExportEntry(api, from, to, ({ isoDay, preferredName, data }) => addUnique(preferredName, isoDay, data));
30774
- return { buffer: out.toBuffer(), days, nonEmptyDays };
29766
+ const { days, nonEmptyDays } = await forEachExportEntry(api, from, to, ({ isoDay, preferredName, data }) => addUnique(toJsonFileName(preferredName), isoDay, data));
29767
+ return { files, days, nonEmptyDays };
30775
29768
  }
30776
29769
  var PREFERRED_CSV_COLUMNS = [
30777
29770
  "Id",
@@ -30880,12 +29873,14 @@ function instructionsFor(verb, error) {
30880
29873
  if (/Invalid --status/.test(msg))
30881
29874
  return "Use --status Success or --status Failure (case-insensitive).";
30882
29875
  if (/Invalid --file-format/.test(msg))
30883
- return "Use --file-format zip (default) or --file-format csv.";
29876
+ return "Use --file-format json (default) or --file-format csv.";
29877
+ if (/unsafe name|outside the output folder/i.test(msg))
29878
+ return "The export contained a file whose name would escape --output-path. This indicates a malformed server response — re-run, and report it if it persists.";
30884
29879
  if (verb === "sources")
30885
29880
  return "Confirm scope (org vs tenant) matches your intent and that you are logged in.";
30886
29881
  if (verb === "events")
30887
29882
  return "Discover GUIDs via 'audit <scope> sources --output json' before passing --source/--target/--type. Verify --from-date/--to-date are ISO 8601.";
30888
- return "Verify --from-date/--to-date are ISO 8601 and the --output-file directory is writable. Single-day chunk failures are transient — re-run.";
29883
+ return "Verify --from-date/--to-date are ISO 8601 and the --output-path directory is writable. Single-day chunk failures are transient — re-run.";
30889
29884
  }
30890
29885
  function registerScopeCommands(parent, opts) {
30891
29886
  registerSources(parent, opts);
@@ -31098,10 +30093,10 @@ function registerEvents(parent, opts) {
31098
30093
  });
31099
30094
  }
31100
30095
  function parseFormat(raw) {
31101
- const normalized = (raw ?? "zip").trim().toLowerCase();
31102
- if (normalized === "zip" || normalized === "csv")
30096
+ const normalized = (raw ?? "json").trim().toLowerCase();
30097
+ if (normalized === "json" || normalized === "csv")
31103
30098
  return normalized;
31104
- throw new Error(`Invalid --file-format '${raw}'. Use 'zip' or 'csv'.`);
30099
+ throw new Error(`Invalid --file-format '${raw}'. Use 'json' or 'csv'.`);
31105
30100
  }
31106
30101
  function exportExamples({
31107
30102
  scope,
@@ -31109,31 +30104,34 @@ function exportExamples({
31109
30104
  }) {
31110
30105
  return [
31111
30106
  {
31112
- Description: `Export ${scope} audit events for January 2026 to a ZIP of day-wise files`,
31113
- Command: `uip admin audit ${scope} export --from-date 2026-01-01 --to-date 2026-02-01 --output-file ./audit-${scope}-jan.zip`,
30107
+ Description: `Export ${scope} audit events for January 2026 a timestamped folder of day-wise JSON files is created under the base dir`,
30108
+ Command: `uip admin audit ${scope} export --from-date 2026-01-01 --to-date 2026-02-01 --output-path ./audit-exports`,
31114
30109
  Output: {
31115
30110
  Code: `Audit${codeSuffix}Export`,
31116
30111
  Data: {
31117
- Path: `./audit-${scope}-jan.zip`,
30112
+ Path: `./audit-exports/audit_2026-01-01_2026-02-01_20260617T112630`,
30113
+ Format: "json",
30114
+ Files: 27,
31118
30115
  Bytes: 12345,
31119
- Format: "zip",
31120
30116
  Days: 31,
31121
- NonEmptyDays: 27
30117
+ NonEmptyDays: 27,
30118
+ GeneratedAt: "2026-06-17T11:26:30.000Z"
31122
30119
  }
31123
30120
  }
31124
30121
  },
31125
30122
  {
31126
- Description: `Export the same window into a single merged CSV instead of a ZIP`,
31127
- Command: `uip admin audit ${scope} export --from-date 2026-01-01 --to-date 2026-02-01 --file-format csv --output-file ./audit-${scope}-jan.csv`,
30123
+ Description: `Export the same window into a single merged CSV (a uniquely-named .csv under the base dir) instead of a folder`,
30124
+ Command: `uip admin audit ${scope} export --from-date 2026-01-01 --to-date 2026-02-01 --file-format csv --output-path ./audit-exports`,
31128
30125
  Output: {
31129
30126
  Code: `Audit${codeSuffix}Export`,
31130
30127
  Data: {
31131
- Path: `./audit-${scope}-jan.csv`,
31132
- Bytes: 98765,
30128
+ Path: `./audit-exports/audit_2026-01-01_2026-02-01_20260617T112630.csv`,
31133
30129
  Format: "csv",
30130
+ Bytes: 98765,
31134
30131
  Days: 31,
31135
30132
  NonEmptyDays: 27,
31136
- Events: 1234
30133
+ Events: 1234,
30134
+ GeneratedAt: "2026-06-17T11:26:30.000Z"
31137
30135
  }
31138
30136
  }
31139
30137
  }
@@ -31144,22 +30142,33 @@ function registerExport(parent, opts) {
31144
30142
  const cmd = parent.command("export").description([
31145
30143
  `Export audit events from the long-term store at the ${scope} scope.`,
31146
30144
  "",
31147
- "Issues one HTTP call per UTC day inside [--from-date, --to-date], aggregates the daily",
31148
- "responses in memory, and writes a single file at --output-file once the full window has",
31149
- "been fetched. On any chunk failure the export is aborted atomically — no file is written,",
31150
- "and the structured Failure result identifies the day that failed.",
30145
+ "Issues one HTTP call per UTC day inside [--from-date, --to-date] and aggregates the daily",
30146
+ "responses in memory before writing them out. The full window is fetched first: on any chunk",
30147
+ "failure the export is aborted atomically — nothing is written, and the structured Failure",
30148
+ "result identifies the day that failed.",
31151
30149
  "",
31152
- "--file-format controls the shape of that file:",
31153
- " zip (default) a ZIP containing one JSON file per UTC day.",
31154
- " csv — a single CSV with every event merged under a shared header."
30150
+ "--output-path is a base DIRECTORY, not a file path — pass a folder and the CLI",
30151
+ "generates the per-export name for you (you do NOT supply a filename). Each run creates",
30152
+ "a uniquely-named output inside it, stamped with the window + generation time",
30153
+ "(e.g. audit_2026-01-01_2026-02-01_20260617T112630), so repeated exports of the same",
30154
+ "window never collide. --file-format controls the shape:",
30155
+ " json (default) — a folder of one JSON file per UTC day.",
30156
+ " csv — a single CSV file with every event merged under a shared header."
31155
30157
  ].join(`
31156
- `)).requiredOption("--output-file <path>", "Path to write the export to. Parent directory must exist; existing file is overwritten.").requiredOption("--from-date <iso>", "Start of time interval (ISO 8601). Required.").requiredOption("--to-date <iso>", "End of time interval (ISO 8601). Required.").option("--file-format <format>", "Exported file format: 'zip' (default — one file per UTC day inside a ZIP) or 'csv' (a single merged CSV of every event).", "zip").option("--login-validity <minutes>", "Override the interactive-login token lifetime for this call. Rarely needed.", (v) => Number.parseInt(v, 10));
30158
+ `)).option("--output-path <dir>", "Base directory for the export (created if missing). Pass a directory only — do NOT include a filename or extension; the CLI generates the per-export name. A uniquely-named output is created inside it — a folder of day-wise JSON files ('json') or a single '.csv' file ('csv'), named audit_<from>_<to>_<generated-at> (to the second) so repeated exports don't collide.").option("--output-file <dir>", "Deprecated alias for --output-path (kept for backward compatibility). Despite the name it is treated as a base DIRECTORY, not a file path. Prefer --output-path.").requiredOption("--from-date <iso>", "Start of time interval (ISO 8601). Required.").requiredOption("--to-date <iso>", "End of time interval (ISO 8601). Required.").option("--file-format <format>", "Output format: 'json' (default — day-wise JSON files written into the --output-path folder) or 'csv' (a single merged CSV of every event).", "json").option("--login-validity <minutes>", "Override the interactive-login token lifetime for this call. Rarely needed.", (v) => Number.parseInt(v, 10));
31157
30159
  if (scope === "tenant") {
31158
30160
  cmd.option("--tenant-id <guid>", "Override the tenant ID from login context.");
31159
30161
  }
31160
30162
  cmd.examples(exportExamples(opts)).trackedAction(processContext, async (options) => {
31161
30163
  const [error, summary] = await catchError2((async () => {
31162
30164
  const format = parseFormat(options.fileFormat);
30165
+ const outputPath = options.outputPath ?? options.outputFile;
30166
+ if (outputPath === undefined) {
30167
+ throw new Error("Missing required option '--output-path <dir>'.");
30168
+ }
30169
+ if (options.outputFile !== undefined) {
30170
+ logger.warn(options.outputPath !== undefined ? "--output-file is deprecated and ignored when --output-path is also provided; using --output-path." : "--output-file is deprecated; use --output-path instead. It is treated as a base directory.");
30171
+ }
31163
30172
  const api = await createApiClient(QueryApi, {
31164
30173
  scope,
31165
30174
  tenantId: options.tenantId,
@@ -31167,17 +30176,51 @@ function registerExport(parent, opts) {
31167
30176
  });
31168
30177
  const from = new Date(options.fromDate);
31169
30178
  const to = new Date(options.toDate);
31170
- const result = format === "csv" ? await downloadChunkedCsvExport(api, from, to) : await downloadChunkedExport(api, from, to);
31171
30179
  const fs7 = getFileSystem();
31172
- const absolutePath = fs7.path.resolve(options.outputFile);
31173
- await fs7.writeFile(absolutePath, result.buffer);
30180
+ const generatedAt = new Date;
30181
+ const baseDir = fs7.path.resolve(outputPath);
30182
+ const baseName = exportBaseName(from, to, generatedAt);
30183
+ if (format === "csv") {
30184
+ const result2 = await downloadChunkedCsvExport(api, from, to);
30185
+ await fs7.mkdir(baseDir);
30186
+ const target = fs7.path.join(baseDir, `${baseName}.csv`);
30187
+ await fs7.writeFile(target, result2.buffer);
30188
+ return {
30189
+ Path: target,
30190
+ Format: "csv",
30191
+ Bytes: result2.buffer.byteLength,
30192
+ Days: result2.days,
30193
+ NonEmptyDays: result2.nonEmptyDays,
30194
+ Events: result2.eventCount,
30195
+ GeneratedAt: generatedAt.toISOString()
30196
+ };
30197
+ }
30198
+ const result = await downloadChunkedJsonExport(api, from, to);
30199
+ const outDir = fs7.path.join(baseDir, baseName);
30200
+ const targets = result.files.map((file) => {
30201
+ if (!isSafeExportEntryName(file.name)) {
30202
+ throw new Error(`Export contained a file with an unsafe name '${file.name}'.`);
30203
+ }
30204
+ const target = fs7.path.join(outDir, file.name);
30205
+ if (!isWithinDir(outDir, fs7.path.resolve(target))) {
30206
+ throw new Error(`Export file '${file.name}' resolves outside the output folder.`);
30207
+ }
30208
+ return { target, data: file.data };
30209
+ });
30210
+ await fs7.mkdir(outDir);
30211
+ let bytes = 0;
30212
+ for (const { target, data } of targets) {
30213
+ await fs7.writeFile(target, data);
30214
+ bytes += data.byteLength;
30215
+ }
31174
30216
  return {
31175
- Path: absolutePath,
31176
- Bytes: result.buffer.byteLength,
31177
- Format: format,
30217
+ Path: outDir,
30218
+ Format: "json",
30219
+ Files: result.files.length,
30220
+ Bytes: bytes,
31178
30221
  Days: result.days,
31179
30222
  NonEmptyDays: result.nonEmptyDays,
31180
- ..."eventCount" in result ? { Events: result.eventCount } : {}
30223
+ GeneratedAt: generatedAt.toISOString()
31181
30224
  };
31182
30225
  })());
31183
30226
  if (error) {
@@ -31212,7 +30255,7 @@ var registerAuditCommand = (program) => {
31212
30255
  " export — chunked download from the long-term store as a ZIP of day-wise files or a single merged CSV (requires --from-date / --to-date).",
31213
30256
  "",
31214
30257
  "Typical workflow: `audit <scope> sources` (discover IDs) → `audit <scope> events --source <guid>",
31215
- "--from-date … --to-date …` (find the rows) → `audit <scope> export --from-date … --to-date … --output-file …`."
30258
+ "--from-date … --to-date …` (find the rows) → `audit <scope> export --from-date … --to-date … --output-path …`."
31216
30259
  ].join(`
31217
30260
  `));
31218
30261
  const org = audit.command("org").description("Organization-scoped audit operations.");
@@ -31235,3 +30278,5 @@ export {
31235
30278
  registerCommands,
31236
30279
  metadata
31237
30280
  };
30281
+
30282
+ //# debugId=670B4C8B265E390D64756E2164756E21