@uipath/admin-tool 1.203.0-preview.212 → 1.204.0-preview.211

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.
@@ -0,0 +1,2411 @@
1
+ import {
2
+ getLoginStatusAsync
3
+ } from "./tool-016jy57n.js";
4
+ import {
5
+ EXIT_CODES,
6
+ OutputFormatter,
7
+ RESULTS,
8
+ addSdkUserAgentHeader,
9
+ catchError,
10
+ extractErrorDetails,
11
+ extractErrorMessage,
12
+ getFileSystem,
13
+ getSdkUserAgentToken,
14
+ installSdkUserAgentHeader,
15
+ isGuid,
16
+ logger,
17
+ parseLimit,
18
+ processContext
19
+ } from "./tool-v13kh7v7.js";
20
+ import"./tool-1yh8g550.js";
21
+
22
+ // ../audit-sdk/generated/src/runtime.ts
23
+ var BASE_PATH = "https://localhost:7008".replace(/\/+$/, "");
24
+
25
+ class Configuration {
26
+ configuration;
27
+ constructor(configuration = {}) {
28
+ this.configuration = configuration;
29
+ }
30
+ set config(configuration) {
31
+ this.configuration = configuration;
32
+ }
33
+ get basePath() {
34
+ return this.configuration.basePath != null ? this.configuration.basePath : BASE_PATH;
35
+ }
36
+ get fetchApi() {
37
+ return this.configuration.fetchApi;
38
+ }
39
+ get middleware() {
40
+ return this.configuration.middleware || [];
41
+ }
42
+ get queryParamsStringify() {
43
+ return this.configuration.queryParamsStringify || querystring;
44
+ }
45
+ get username() {
46
+ return this.configuration.username;
47
+ }
48
+ get password() {
49
+ return this.configuration.password;
50
+ }
51
+ get apiKey() {
52
+ const apiKey = this.configuration.apiKey;
53
+ if (apiKey) {
54
+ return typeof apiKey === "function" ? apiKey : () => apiKey;
55
+ }
56
+ return;
57
+ }
58
+ get accessToken() {
59
+ const accessToken = this.configuration.accessToken;
60
+ if (accessToken) {
61
+ return typeof accessToken === "function" ? accessToken : async () => accessToken;
62
+ }
63
+ return;
64
+ }
65
+ get headers() {
66
+ return this.configuration.headers;
67
+ }
68
+ get credentials() {
69
+ return this.configuration.credentials;
70
+ }
71
+ }
72
+ var DefaultConfig = new Configuration;
73
+
74
+ class BaseAPI {
75
+ configuration;
76
+ static jsonRegex = new RegExp("^(:?application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$", "i");
77
+ middleware;
78
+ constructor(configuration = DefaultConfig) {
79
+ this.configuration = configuration;
80
+ this.middleware = configuration.middleware;
81
+ }
82
+ withMiddleware(...middlewares) {
83
+ const next = this.clone();
84
+ next.middleware = next.middleware.concat(...middlewares);
85
+ return next;
86
+ }
87
+ withPreMiddleware(...preMiddlewares) {
88
+ const middlewares = preMiddlewares.map((pre) => ({ pre }));
89
+ return this.withMiddleware(...middlewares);
90
+ }
91
+ withPostMiddleware(...postMiddlewares) {
92
+ const middlewares = postMiddlewares.map((post) => ({ post }));
93
+ return this.withMiddleware(...middlewares);
94
+ }
95
+ isJsonMime(mime) {
96
+ if (!mime) {
97
+ return false;
98
+ }
99
+ return BaseAPI.jsonRegex.test(mime);
100
+ }
101
+ async request(context, initOverrides) {
102
+ const { url, init } = await this.createFetchParams(context, initOverrides);
103
+ const response = await this.fetchApi(url, init);
104
+ if (response && (response.status >= 200 && response.status < 300)) {
105
+ return response;
106
+ }
107
+ throw new ResponseError(response, "Response returned an error code");
108
+ }
109
+ async createFetchParams(context, initOverrides) {
110
+ let url = this.configuration.basePath + context.path;
111
+ if (context.query !== undefined && Object.keys(context.query).length !== 0) {
112
+ url += "?" + this.configuration.queryParamsStringify(context.query);
113
+ }
114
+ const headers = Object.assign({}, this.configuration.headers, context.headers);
115
+ Object.keys(headers).forEach((key) => headers[key] === undefined ? delete headers[key] : {});
116
+ const initOverrideFn = typeof initOverrides === "function" ? initOverrides : async () => initOverrides;
117
+ const initParams = {
118
+ method: context.method,
119
+ headers,
120
+ body: context.body,
121
+ credentials: this.configuration.credentials
122
+ };
123
+ const overriddenInit = {
124
+ ...initParams,
125
+ ...await initOverrideFn({
126
+ init: initParams,
127
+ context
128
+ })
129
+ };
130
+ let body;
131
+ if (isFormData(overriddenInit.body) || overriddenInit.body instanceof URLSearchParams || isBlob(overriddenInit.body)) {
132
+ body = overriddenInit.body;
133
+ } else if (this.isJsonMime(headers["Content-Type"])) {
134
+ body = JSON.stringify(overriddenInit.body);
135
+ } else {
136
+ body = overriddenInit.body;
137
+ }
138
+ const init = {
139
+ ...overriddenInit,
140
+ body
141
+ };
142
+ return { url, init };
143
+ }
144
+ fetchApi = async (url, init) => {
145
+ let fetchParams = { url, init };
146
+ for (const middleware of this.middleware) {
147
+ if (middleware.pre) {
148
+ fetchParams = await middleware.pre({
149
+ fetch: this.fetchApi,
150
+ ...fetchParams
151
+ }) || fetchParams;
152
+ }
153
+ }
154
+ let response = undefined;
155
+ try {
156
+ response = await (this.configuration.fetchApi || fetch)(fetchParams.url, fetchParams.init);
157
+ } catch (e) {
158
+ for (const middleware of this.middleware) {
159
+ if (middleware.onError) {
160
+ response = await middleware.onError({
161
+ fetch: this.fetchApi,
162
+ url: fetchParams.url,
163
+ init: fetchParams.init,
164
+ error: e,
165
+ response: response ? response.clone() : undefined
166
+ }) || response;
167
+ }
168
+ }
169
+ if (response === undefined) {
170
+ if (e instanceof Error) {
171
+ throw new FetchError(e, "The request failed and the interceptors did not return an alternative response");
172
+ } else {
173
+ throw e;
174
+ }
175
+ }
176
+ }
177
+ for (const middleware of this.middleware) {
178
+ if (middleware.post) {
179
+ response = await middleware.post({
180
+ fetch: this.fetchApi,
181
+ url: fetchParams.url,
182
+ init: fetchParams.init,
183
+ response: response.clone()
184
+ }) || response;
185
+ }
186
+ }
187
+ return response;
188
+ };
189
+ clone() {
190
+ const constructor = this.constructor;
191
+ const next = new constructor(this.configuration);
192
+ next.middleware = this.middleware.slice();
193
+ return next;
194
+ }
195
+ }
196
+ function isBlob(value) {
197
+ return typeof Blob !== "undefined" && value instanceof Blob;
198
+ }
199
+ function isFormData(value) {
200
+ return typeof FormData !== "undefined" && value instanceof FormData;
201
+ }
202
+
203
+ class ResponseError extends Error {
204
+ response;
205
+ name = "ResponseError";
206
+ constructor(response, msg) {
207
+ super(msg);
208
+ this.response = response;
209
+ const actualProto = new.target.prototype;
210
+ if (Object.setPrototypeOf) {
211
+ Object.setPrototypeOf(this, actualProto);
212
+ }
213
+ }
214
+ }
215
+
216
+ class FetchError extends Error {
217
+ cause;
218
+ name = "FetchError";
219
+ constructor(cause, msg) {
220
+ super(msg);
221
+ this.cause = cause;
222
+ const actualProto = new.target.prototype;
223
+ if (Object.setPrototypeOf) {
224
+ Object.setPrototypeOf(this, actualProto);
225
+ }
226
+ }
227
+ }
228
+
229
+ class RequiredError extends Error {
230
+ field;
231
+ name = "RequiredError";
232
+ constructor(field, msg) {
233
+ super(msg);
234
+ this.field = field;
235
+ const actualProto = new.target.prototype;
236
+ if (Object.setPrototypeOf) {
237
+ Object.setPrototypeOf(this, actualProto);
238
+ }
239
+ }
240
+ }
241
+ function querystring(params, prefix = "") {
242
+ return Object.keys(params).map((key) => querystringSingleKey(key, params[key], prefix)).filter((part) => part.length > 0).join("&");
243
+ }
244
+ function querystringSingleKey(key, value, keyPrefix = "") {
245
+ const fullKey = keyPrefix + (keyPrefix.length ? `[${key}]` : key);
246
+ if (value instanceof Array) {
247
+ const multiValue = value.map((singleValue) => encodeURIComponent(String(singleValue))).join(`&${encodeURIComponent(fullKey)}=`);
248
+ return `${encodeURIComponent(fullKey)}=${multiValue}`;
249
+ }
250
+ if (value instanceof Set) {
251
+ const valueAsArray = Array.from(value);
252
+ return querystringSingleKey(key, valueAsArray, keyPrefix);
253
+ }
254
+ if (value instanceof Date) {
255
+ return `${encodeURIComponent(fullKey)}=${encodeURIComponent(value.toISOString())}`;
256
+ }
257
+ if (value instanceof Object) {
258
+ return querystring(value, fullKey);
259
+ }
260
+ return `${encodeURIComponent(fullKey)}=${encodeURIComponent(String(value))}`;
261
+ }
262
+ class JSONApiResponse {
263
+ raw;
264
+ transformer;
265
+ constructor(raw, transformer = (jsonValue) => jsonValue) {
266
+ this.raw = raw;
267
+ this.transformer = transformer;
268
+ }
269
+ async value() {
270
+ return this.transformer(await this.raw.json());
271
+ }
272
+ }
273
+
274
+ class VoidApiResponse {
275
+ raw;
276
+ constructor(raw) {
277
+ this.raw = raw;
278
+ }
279
+ async value() {
280
+ return;
281
+ }
282
+ }
283
+ // ../audit-sdk/package.json
284
+ var package_default = {
285
+ name: "@uipath/audit-sdk",
286
+ author: "UiPath",
287
+ license: "SEE LICENSE IN LICENSE.txt",
288
+ version: "1.204.0",
289
+ description: "SDK for the UiPath Audit Service — query audit event sources, list events, download long-term-store exports, and manage audit exclusion rules.",
290
+ repository: {
291
+ type: "git",
292
+ url: "https://github.com/UiPath/cli.git",
293
+ directory: "packages/admin/audit-sdk"
294
+ },
295
+ publishConfig: {
296
+ registry: "https://npm.pkg.github.com/@uipath"
297
+ },
298
+ keywords: [
299
+ "uipath",
300
+ "audit",
301
+ "sdk"
302
+ ],
303
+ type: "module",
304
+ main: "./dist/index.js",
305
+ types: "./dist/src/index.d.ts",
306
+ exports: {
307
+ ".": {
308
+ types: "./dist/src/index.d.ts",
309
+ default: "./dist/index.js"
310
+ }
311
+ },
312
+ files: [
313
+ "dist"
314
+ ],
315
+ private: true,
316
+ scripts: {
317
+ build: "bun build ./src/index.ts --outdir dist --format esm --target node --sourcemap=linked && tsc -p tsconfig.build.json --noCheck",
318
+ generate: "bun run src/scripts/generate-sdk.ts",
319
+ lint: "biome check ."
320
+ },
321
+ devDependencies: {
322
+ "@openapitools/openapi-generator-cli": "^2.31.1",
323
+ "@types/node": "^25.5.0",
324
+ "@uipath/auth": "workspace:*",
325
+ "@uipath/common": "workspace:*",
326
+ typescript: "^7.0.2"
327
+ }
328
+ };
329
+
330
+ // ../audit-sdk/src/user-agent.ts
331
+ var SDK_USER_AGENT = getSdkUserAgentToken(package_default);
332
+ installSdkUserAgentHeader(BaseAPI, SDK_USER_AGENT);
333
+
334
+ // ../audit-sdk/generated/src/models/AuditEventStatus.ts
335
+ var AuditEventStatus = {
336
+ NUMBER_0: 0,
337
+ NUMBER_1: 1
338
+ };
339
+ function AuditEventStatusFromJSON(json) {
340
+ return AuditEventStatusFromJSONTyped(json, false);
341
+ }
342
+ function AuditEventStatusFromJSONTyped(json, ignoreDiscriminator) {
343
+ return json;
344
+ }
345
+
346
+ // ../audit-sdk/generated/src/models/ClientInfoDto.ts
347
+ function ClientInfoDtoFromJSON(json) {
348
+ return ClientInfoDtoFromJSONTyped(json, false);
349
+ }
350
+ function ClientInfoDtoFromJSONTyped(json, ignoreDiscriminator) {
351
+ if (json == null) {
352
+ return json;
353
+ }
354
+ return {
355
+ ipAddress: json["ipAddress"] == null ? undefined : json["ipAddress"],
356
+ ipCountry: json["ipCountry"] == null ? undefined : json["ipCountry"]
357
+ };
358
+ }
359
+
360
+ // ../audit-sdk/generated/src/models/AuditEventDto.ts
361
+ function AuditEventDtoFromJSON(json) {
362
+ return AuditEventDtoFromJSONTyped(json, false);
363
+ }
364
+ function AuditEventDtoFromJSONTyped(json, ignoreDiscriminator) {
365
+ if (json == null) {
366
+ return json;
367
+ }
368
+ return {
369
+ id: json["id"] == null ? undefined : json["id"],
370
+ createdOn: json["createdOn"] == null ? undefined : new Date(json["createdOn"]),
371
+ organizationId: json["organizationId"] == null ? undefined : json["organizationId"],
372
+ organizationName: json["organizationName"] == null ? undefined : json["organizationName"],
373
+ tenantId: json["tenantId"] == null ? undefined : json["tenantId"],
374
+ tenantName: json["tenantName"] == null ? undefined : json["tenantName"],
375
+ actorId: json["actorId"] == null ? undefined : json["actorId"],
376
+ actorName: json["actorName"] == null ? undefined : json["actorName"],
377
+ actorEmail: json["actorEmail"] == null ? undefined : json["actorEmail"],
378
+ eventType: json["eventType"] == null ? undefined : json["eventType"],
379
+ eventSource: json["eventSource"] == null ? undefined : json["eventSource"],
380
+ eventTarget: json["eventTarget"] == null ? undefined : json["eventTarget"],
381
+ eventDetails: json["eventDetails"] == null ? undefined : json["eventDetails"],
382
+ eventSummary: json["eventSummary"] == null ? undefined : json["eventSummary"],
383
+ status: json["status"] == null ? undefined : AuditEventStatusFromJSON(json["status"]),
384
+ clientInfo: json["clientInfo"] == null ? undefined : ClientInfoDtoFromJSON(json["clientInfo"])
385
+ };
386
+ }
387
+
388
+ // ../audit-sdk/generated/src/models/AuditEventQueryResultDto.ts
389
+ function AuditEventQueryResultDtoFromJSON(json) {
390
+ return AuditEventQueryResultDtoFromJSONTyped(json, false);
391
+ }
392
+ function AuditEventQueryResultDtoFromJSONTyped(json, ignoreDiscriminator) {
393
+ if (json == null) {
394
+ return json;
395
+ }
396
+ return {
397
+ auditEvents: json["auditEvents"] == null ? undefined : json["auditEvents"].map(AuditEventDtoFromJSON),
398
+ next: json["next"] == null ? undefined : json["next"],
399
+ previous: json["previous"] == null ? undefined : json["previous"]
400
+ };
401
+ }
402
+
403
+ // ../audit-sdk/generated/src/models/AuditEventTypeDto.ts
404
+ function AuditEventTypeDtoFromJSON(json) {
405
+ return AuditEventTypeDtoFromJSONTyped(json, false);
406
+ }
407
+ function AuditEventTypeDtoFromJSONTyped(json, ignoreDiscriminator) {
408
+ if (json == null) {
409
+ return json;
410
+ }
411
+ return {
412
+ id: json["id"] == null ? undefined : json["id"],
413
+ name: json["name"] == null ? undefined : json["name"]
414
+ };
415
+ }
416
+
417
+ // ../audit-sdk/generated/src/models/AuditEventTargetDto.ts
418
+ function AuditEventTargetDtoFromJSON(json) {
419
+ return AuditEventTargetDtoFromJSONTyped(json, false);
420
+ }
421
+ function AuditEventTargetDtoFromJSONTyped(json, ignoreDiscriminator) {
422
+ if (json == null) {
423
+ return json;
424
+ }
425
+ return {
426
+ id: json["id"] == null ? undefined : json["id"],
427
+ name: json["name"] == null ? undefined : json["name"],
428
+ eventTypes: json["eventTypes"] == null ? undefined : json["eventTypes"].map(AuditEventTypeDtoFromJSON)
429
+ };
430
+ }
431
+
432
+ // ../audit-sdk/generated/src/models/AuditEventSourceDto.ts
433
+ function AuditEventSourceDtoFromJSON(json) {
434
+ return AuditEventSourceDtoFromJSONTyped(json, false);
435
+ }
436
+ function AuditEventSourceDtoFromJSONTyped(json, ignoreDiscriminator) {
437
+ if (json == null) {
438
+ return json;
439
+ }
440
+ return {
441
+ id: json["id"] == null ? undefined : json["id"],
442
+ name: json["name"] == null ? undefined : json["name"],
443
+ eventTargets: json["eventTargets"] == null ? undefined : json["eventTargets"].map(AuditEventTargetDtoFromJSON)
444
+ };
445
+ }
446
+
447
+ // ../audit-sdk/generated/src/models/ExclusionSelectorDto.ts
448
+ function ExclusionSelectorDtoFromJSON(json) {
449
+ return ExclusionSelectorDtoFromJSONTyped(json, false);
450
+ }
451
+ function ExclusionSelectorDtoFromJSONTyped(json, ignoreDiscriminator) {
452
+ if (json == null) {
453
+ return json;
454
+ }
455
+ return {
456
+ type: json["type"] == null ? undefined : json["type"],
457
+ values: json["values"] == null ? undefined : json["values"]
458
+ };
459
+ }
460
+ function ExclusionSelectorDtoToJSON(json) {
461
+ return ExclusionSelectorDtoToJSONTyped(json, false);
462
+ }
463
+ function ExclusionSelectorDtoToJSONTyped(value, ignoreDiscriminator = false) {
464
+ if (value == null) {
465
+ return value;
466
+ }
467
+ return {
468
+ type: value["type"],
469
+ values: value["values"]
470
+ };
471
+ }
472
+
473
+ // ../audit-sdk/generated/src/models/ExclusionRuleDto.ts
474
+ function ExclusionRuleDtoFromJSON(json) {
475
+ return ExclusionRuleDtoFromJSONTyped(json, false);
476
+ }
477
+ function ExclusionRuleDtoFromJSONTyped(json, ignoreDiscriminator) {
478
+ if (json == null) {
479
+ return json;
480
+ }
481
+ return {
482
+ policyId: json["policyId"] == null ? undefined : json["policyId"],
483
+ name: json["name"] == null ? undefined : json["name"],
484
+ enforcement: json["enforcement"] == null ? undefined : json["enforcement"],
485
+ isActive: json["isActive"] == null ? undefined : json["isActive"],
486
+ activatedOn: json["activatedOn"] == null ? undefined : new Date(json["activatedOn"]),
487
+ selectors: json["selectors"] == null ? undefined : json["selectors"].map(ExclusionSelectorDtoFromJSON),
488
+ createdOn: json["createdOn"] == null ? undefined : new Date(json["createdOn"]),
489
+ lastModifiedOn: json["lastModifiedOn"] == null ? undefined : new Date(json["lastModifiedOn"])
490
+ };
491
+ }
492
+
493
+ // ../audit-sdk/generated/src/models/ExclusionRuleWriteDto.ts
494
+ function ExclusionRuleWriteDtoToJSON(json) {
495
+ return ExclusionRuleWriteDtoToJSONTyped(json, false);
496
+ }
497
+ function ExclusionRuleWriteDtoToJSONTyped(value, ignoreDiscriminator = false) {
498
+ if (value == null) {
499
+ return value;
500
+ }
501
+ return {
502
+ name: value["name"],
503
+ enforcement: value["enforcement"],
504
+ isActive: value["isActive"],
505
+ selectors: value["selectors"] == null ? undefined : value["selectors"].map(ExclusionSelectorDtoToJSON)
506
+ };
507
+ }
508
+
509
+ // ../audit-sdk/generated/src/apis/EventConfigApi.ts
510
+ class EventConfigApi extends BaseAPI {
511
+ async eventConfigCreateRuleRequestOpts(requestParameters) {
512
+ if (requestParameters["exclusionRuleWriteDto"] == null) {
513
+ throw new RequiredError("exclusionRuleWriteDto", 'Required parameter "exclusionRuleWriteDto" was null or undefined when calling eventConfigCreateRule().');
514
+ }
515
+ const queryParameters = {};
516
+ const headerParameters = {};
517
+ headerParameters["Content-Type"] = "application/json";
518
+ if (this.configuration && this.configuration.apiKey) {
519
+ headerParameters["Authorization"] = await this.configuration.apiKey("Authorization");
520
+ }
521
+ let urlPath = `/api/EventConfig/rules`;
522
+ return {
523
+ path: urlPath,
524
+ method: "POST",
525
+ headers: headerParameters,
526
+ query: queryParameters,
527
+ body: ExclusionRuleWriteDtoToJSON(requestParameters["exclusionRuleWriteDto"])
528
+ };
529
+ }
530
+ async eventConfigCreateRuleRaw(requestParameters, initOverrides) {
531
+ const requestOptions = await this.eventConfigCreateRuleRequestOpts(requestParameters);
532
+ const response = await this.request(requestOptions, initOverrides);
533
+ return new JSONApiResponse(response, (jsonValue) => ExclusionRuleDtoFromJSON(jsonValue));
534
+ }
535
+ async eventConfigCreateRule(requestParameters, initOverrides) {
536
+ const response = await this.eventConfigCreateRuleRaw(requestParameters, initOverrides);
537
+ return await response.value();
538
+ }
539
+ async eventConfigDeleteRuleRequestOpts(requestParameters) {
540
+ if (requestParameters["policyId"] == null) {
541
+ throw new RequiredError("policyId", 'Required parameter "policyId" was null or undefined when calling eventConfigDeleteRule().');
542
+ }
543
+ const queryParameters = {};
544
+ const headerParameters = {};
545
+ if (this.configuration && this.configuration.apiKey) {
546
+ headerParameters["Authorization"] = await this.configuration.apiKey("Authorization");
547
+ }
548
+ let urlPath = `/api/EventConfig/rules/{policyId}`;
549
+ urlPath = urlPath.replace(`{${"policyId"}}`, encodeURIComponent(String(requestParameters["policyId"])));
550
+ return {
551
+ path: urlPath,
552
+ method: "DELETE",
553
+ headers: headerParameters,
554
+ query: queryParameters
555
+ };
556
+ }
557
+ async eventConfigDeleteRuleRaw(requestParameters, initOverrides) {
558
+ const requestOptions = await this.eventConfigDeleteRuleRequestOpts(requestParameters);
559
+ const response = await this.request(requestOptions, initOverrides);
560
+ return new VoidApiResponse(response);
561
+ }
562
+ async eventConfigDeleteRule(requestParameters, initOverrides) {
563
+ await this.eventConfigDeleteRuleRaw(requestParameters, initOverrides);
564
+ }
565
+ async eventConfigGetRuleRequestOpts(requestParameters) {
566
+ if (requestParameters["policyId"] == null) {
567
+ throw new RequiredError("policyId", 'Required parameter "policyId" was null or undefined when calling eventConfigGetRule().');
568
+ }
569
+ const queryParameters = {};
570
+ const headerParameters = {};
571
+ if (this.configuration && this.configuration.apiKey) {
572
+ headerParameters["Authorization"] = await this.configuration.apiKey("Authorization");
573
+ }
574
+ let urlPath = `/api/EventConfig/rules/{policyId}`;
575
+ urlPath = urlPath.replace(`{${"policyId"}}`, encodeURIComponent(String(requestParameters["policyId"])));
576
+ return {
577
+ path: urlPath,
578
+ method: "GET",
579
+ headers: headerParameters,
580
+ query: queryParameters
581
+ };
582
+ }
583
+ async eventConfigGetRuleRaw(requestParameters, initOverrides) {
584
+ const requestOptions = await this.eventConfigGetRuleRequestOpts(requestParameters);
585
+ const response = await this.request(requestOptions, initOverrides);
586
+ return new JSONApiResponse(response, (jsonValue) => ExclusionRuleDtoFromJSON(jsonValue));
587
+ }
588
+ async eventConfigGetRule(requestParameters, initOverrides) {
589
+ const response = await this.eventConfigGetRuleRaw(requestParameters, initOverrides);
590
+ return await response.value();
591
+ }
592
+ async eventConfigGetRulesRequestOpts() {
593
+ const queryParameters = {};
594
+ const headerParameters = {};
595
+ if (this.configuration && this.configuration.apiKey) {
596
+ headerParameters["Authorization"] = await this.configuration.apiKey("Authorization");
597
+ }
598
+ let urlPath = `/api/EventConfig/rules`;
599
+ return {
600
+ path: urlPath,
601
+ method: "GET",
602
+ headers: headerParameters,
603
+ query: queryParameters
604
+ };
605
+ }
606
+ async eventConfigGetRulesRaw(initOverrides) {
607
+ const requestOptions = await this.eventConfigGetRulesRequestOpts();
608
+ const response = await this.request(requestOptions, initOverrides);
609
+ return new JSONApiResponse(response, (jsonValue) => jsonValue.map(ExclusionRuleDtoFromJSON));
610
+ }
611
+ async eventConfigGetRules(initOverrides) {
612
+ const response = await this.eventConfigGetRulesRaw(initOverrides);
613
+ return await response.value();
614
+ }
615
+ async eventConfigReplaceRuleRequestOpts(requestParameters) {
616
+ if (requestParameters["policyId"] == null) {
617
+ throw new RequiredError("policyId", 'Required parameter "policyId" was null or undefined when calling eventConfigReplaceRule().');
618
+ }
619
+ if (requestParameters["exclusionRuleWriteDto"] == null) {
620
+ throw new RequiredError("exclusionRuleWriteDto", 'Required parameter "exclusionRuleWriteDto" was null or undefined when calling eventConfigReplaceRule().');
621
+ }
622
+ const queryParameters = {};
623
+ const headerParameters = {};
624
+ headerParameters["Content-Type"] = "application/json";
625
+ if (this.configuration && this.configuration.apiKey) {
626
+ headerParameters["Authorization"] = await this.configuration.apiKey("Authorization");
627
+ }
628
+ let urlPath = `/api/EventConfig/rules/{policyId}`;
629
+ urlPath = urlPath.replace(`{${"policyId"}}`, encodeURIComponent(String(requestParameters["policyId"])));
630
+ return {
631
+ path: urlPath,
632
+ method: "PUT",
633
+ headers: headerParameters,
634
+ query: queryParameters,
635
+ body: ExclusionRuleWriteDtoToJSON(requestParameters["exclusionRuleWriteDto"])
636
+ };
637
+ }
638
+ async eventConfigReplaceRuleRaw(requestParameters, initOverrides) {
639
+ const requestOptions = await this.eventConfigReplaceRuleRequestOpts(requestParameters);
640
+ const response = await this.request(requestOptions, initOverrides);
641
+ return new JSONApiResponse(response, (jsonValue) => ExclusionRuleDtoFromJSON(jsonValue));
642
+ }
643
+ async eventConfigReplaceRule(requestParameters, initOverrides) {
644
+ const response = await this.eventConfigReplaceRuleRaw(requestParameters, initOverrides);
645
+ return await response.value();
646
+ }
647
+ }
648
+
649
+ // ../audit-sdk/generated/src/apis/QueryApi.ts
650
+ class QueryApi extends BaseAPI {
651
+ async queryDownloadAuditEventsFromLongTermStoreRequestOpts(requestParameters) {
652
+ const queryParameters = {};
653
+ if (requestParameters["from"] != null) {
654
+ queryParameters["from"] = requestParameters["from"].toISOString();
655
+ }
656
+ if (requestParameters["to"] != null) {
657
+ queryParameters["to"] = requestParameters["to"].toISOString();
658
+ }
659
+ const headerParameters = {};
660
+ if (this.configuration && this.configuration.apiKey) {
661
+ headerParameters["Authorization"] = await this.configuration.apiKey("Authorization");
662
+ }
663
+ let urlPath = `/api/Query/downloadeventsfromlongtermstore`;
664
+ return {
665
+ path: urlPath,
666
+ method: "GET",
667
+ headers: headerParameters,
668
+ query: queryParameters
669
+ };
670
+ }
671
+ async queryDownloadAuditEventsFromLongTermStoreRaw(requestParameters, initOverrides) {
672
+ const requestOptions = await this.queryDownloadAuditEventsFromLongTermStoreRequestOpts(requestParameters);
673
+ const response = await this.request(requestOptions, initOverrides);
674
+ return new VoidApiResponse(response);
675
+ }
676
+ async queryDownloadAuditEventsFromLongTermStore(requestParameters = {}, initOverrides) {
677
+ await this.queryDownloadAuditEventsFromLongTermStoreRaw(requestParameters, initOverrides);
678
+ }
679
+ async queryGetAuditEventSourcesRequestOpts() {
680
+ const queryParameters = {};
681
+ const headerParameters = {};
682
+ if (this.configuration && this.configuration.apiKey) {
683
+ headerParameters["Authorization"] = await this.configuration.apiKey("Authorization");
684
+ }
685
+ let urlPath = `/api/Query/sources`;
686
+ return {
687
+ path: urlPath,
688
+ method: "GET",
689
+ headers: headerParameters,
690
+ query: queryParameters
691
+ };
692
+ }
693
+ async queryGetAuditEventSourcesRaw(initOverrides) {
694
+ const requestOptions = await this.queryGetAuditEventSourcesRequestOpts();
695
+ const response = await this.request(requestOptions, initOverrides);
696
+ return new JSONApiResponse(response, (jsonValue) => jsonValue.map(AuditEventSourceDtoFromJSON));
697
+ }
698
+ async queryGetAuditEventSources(initOverrides) {
699
+ const response = await this.queryGetAuditEventSourcesRaw(initOverrides);
700
+ return await response.value();
701
+ }
702
+ async queryGetAuditEventsRequestOpts(requestParameters) {
703
+ const queryParameters = {};
704
+ if (requestParameters["from"] != null) {
705
+ queryParameters["from"] = requestParameters["from"].toISOString();
706
+ }
707
+ if (requestParameters["to"] != null) {
708
+ queryParameters["to"] = requestParameters["to"].toISOString();
709
+ }
710
+ if (requestParameters["source"] != null) {
711
+ queryParameters["source"] = requestParameters["source"];
712
+ }
713
+ if (requestParameters["target"] != null) {
714
+ queryParameters["target"] = requestParameters["target"];
715
+ }
716
+ if (requestParameters["type"] != null) {
717
+ queryParameters["type"] = requestParameters["type"];
718
+ }
719
+ if (requestParameters["userIds"] != null) {
720
+ queryParameters["userIds"] = requestParameters["userIds"];
721
+ }
722
+ if (requestParameters["searchTerm"] != null) {
723
+ queryParameters["searchTerm"] = requestParameters["searchTerm"];
724
+ }
725
+ if (requestParameters["before"] != null) {
726
+ queryParameters["before"] = requestParameters["before"].toISOString();
727
+ }
728
+ if (requestParameters["beforeId"] != null) {
729
+ queryParameters["beforeId"] = requestParameters["beforeId"];
730
+ }
731
+ if (requestParameters["after"] != null) {
732
+ queryParameters["after"] = requestParameters["after"].toISOString();
733
+ }
734
+ if (requestParameters["afterId"] != null) {
735
+ queryParameters["afterId"] = requestParameters["afterId"];
736
+ }
737
+ if (requestParameters["maxCount"] != null) {
738
+ queryParameters["maxCount"] = requestParameters["maxCount"];
739
+ }
740
+ if (requestParameters["status"] != null) {
741
+ queryParameters["status"] = requestParameters["status"];
742
+ }
743
+ if (requestParameters["psu"] != null) {
744
+ queryParameters["psu"] = requestParameters["psu"];
745
+ }
746
+ if (requestParameters["qw"] != null) {
747
+ queryParameters["qw"] = requestParameters["qw"];
748
+ }
749
+ const headerParameters = {};
750
+ if (this.configuration && this.configuration.apiKey) {
751
+ headerParameters["Authorization"] = await this.configuration.apiKey("Authorization");
752
+ }
753
+ let urlPath = `/api/Query/events`;
754
+ return {
755
+ path: urlPath,
756
+ method: "GET",
757
+ headers: headerParameters,
758
+ query: queryParameters
759
+ };
760
+ }
761
+ async queryGetAuditEventsRaw(requestParameters, initOverrides) {
762
+ const requestOptions = await this.queryGetAuditEventsRequestOpts(requestParameters);
763
+ const response = await this.request(requestOptions, initOverrides);
764
+ return new JSONApiResponse(response, (jsonValue) => AuditEventQueryResultDtoFromJSON(jsonValue));
765
+ }
766
+ async queryGetAuditEvents(requestParameters = {}, initOverrides) {
767
+ const response = await this.queryGetAuditEventsRaw(requestParameters, initOverrides);
768
+ return await response.value();
769
+ }
770
+ }
771
+ // ../audit-sdk/src/client-factory.ts
772
+ async function createAuditConfig(options) {
773
+ const status = await getLoginStatusAsync({
774
+ ensureTokenValidityMinutes: options.loginValidity
775
+ });
776
+ if (status.loginStatus !== "Logged in" || !status.baseUrl || !status.accessToken) {
777
+ const message = status.hint ? `Not logged in. ${status.hint}` : "Not logged in. Run 'uip login' first.";
778
+ throw new Error(message);
779
+ }
780
+ if (!status.organizationId) {
781
+ throw new Error("Organization ID not available. Ensure you are logged in with an organization context.");
782
+ }
783
+ let suffix;
784
+ if (options.scope === "tenant") {
785
+ const tenantId = options.tenantId ?? status.tenantId;
786
+ if (!tenantId) {
787
+ throw new Error("Tenant ID required for tenant-scoped audit calls. Pass --tenant-id or select a tenant via 'uip login'.");
788
+ }
789
+ suffix = `${status.organizationId}/${tenantId}/tenantaudit_`;
790
+ } else {
791
+ suffix = `${status.organizationId}/orgaudit_`;
792
+ }
793
+ const basePath = `${status.baseUrl}/${suffix}`;
794
+ const bearerToken = options.s2sToken ?? status.accessToken;
795
+ return new Configuration({
796
+ basePath,
797
+ apiKey: () => `Bearer ${bearerToken}`,
798
+ headers: addSdkUserAgentHeader(undefined, SDK_USER_AGENT)
799
+ });
800
+ }
801
+ async function createApiClient(ApiClass, options) {
802
+ const config = await createAuditConfig(options);
803
+ return new ApiClass(config);
804
+ }
805
+ // ../audit-sdk/src/exclusion-rules.ts
806
+ class ExclusionRuleLookupError extends Error {
807
+ reason;
808
+ candidates;
809
+ constructor(message, reason, candidates = []) {
810
+ super(message);
811
+ this.name = "ExclusionRuleLookupError";
812
+ this.reason = reason;
813
+ this.candidates = candidates;
814
+ }
815
+ }
816
+ function describe(rule) {
817
+ return `${rule.policyId} (${rule.isActive ? "active" : "inactive"})`;
818
+ }
819
+ async function resolveExclusionRule(api, nameOrId) {
820
+ const value = nameOrId.trim();
821
+ if (isGuid(value)) {
822
+ return { policyId: value };
823
+ }
824
+ const rules = await api.eventConfigGetRules() ?? [];
825
+ const matches = rules.filter((rule) => rule.name === value);
826
+ const resolved = matches.length > 0 ? matches : rules.filter((rule) => rule.name?.toLowerCase() === value.toLowerCase());
827
+ if (resolved.length === 1) {
828
+ const rule = resolved[0];
829
+ if (rule.policyId) {
830
+ return { policyId: rule.policyId, rule };
831
+ }
832
+ throw new ExclusionRuleLookupError(`The rule named '${value}' was listed without a policy id, so it cannot be addressed.`, "unidentifiable");
833
+ }
834
+ if (resolved.length > 1) {
835
+ const candidates = resolved.map((rule) => rule.policyId).filter((id) => typeof id === "string");
836
+ throw new ExclusionRuleLookupError(`'${value}' matches ${resolved.length} rules: ${resolved.map(describe).join(", ")}.`, "ambiguous", candidates);
837
+ }
838
+ throw new ExclusionRuleLookupError(`No exclusion rule named '${value}' exists in this organization.`, "not-found");
839
+ }
840
+ // ../audit-commands/src/commands/exclusions.ts
841
+ var ENFORCEMENT = "Exclude";
842
+ var ID_DIMENSIONS = [
843
+ { option: "excludeTenant", flag: "--exclude-tenant", dimension: "Tenant" },
844
+ { option: "source", flag: "--source", dimension: "EventSource" },
845
+ { option: "target", flag: "--target", dimension: "EventTarget" },
846
+ { option: "type", flag: "--type", dimension: "EventType" }
847
+ ];
848
+ var STATUS_VALUES = ["Success", "Failure"];
849
+ var SELECTOR_FLAGS = [
850
+ ...ID_DIMENSIONS.map((d) => d.flag),
851
+ "--status"
852
+ ];
853
+ var GUID_RE = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
854
+ var EMPTY_GUID = "00000000-0000-0000-0000-000000000000";
855
+ var WRITE_BODY_KEYS = ["name", "enforcement", "isActive", "selectors"];
856
+ var SELECTOR_KEYS = ["type", "values"];
857
+ var MAX_FILE_LENGTH = 64 * 1024;
858
+ var SAMPLE_ID = "3f6b1d84-9a1e-4c2b-8e71-2f9c5d0a7b13";
859
+ var SAMPLE_NAME = "Mute successful robot logins";
860
+ var SAMPLE_TYPE_ID = "0f54d68a-15fd-427d-a86a-2812bb7fbb28";
861
+ var CODE_INSTRUCTIONS = {
862
+ RuleNotFound: "Check the name or id with 'uip admin audit org exclusions list'. A rule owned by another organization also reads as not found.",
863
+ DuplicateRuleName: "Another ACTIVE rule already uses that name. Pick a different --name, or update the existing rule. An inactive rule may keep a name in use.",
864
+ OverlappingRuleExists: "An active rule already excludes everything this one would — its id is in the message. Delete or narrow that rule, or save this one with --inactive to stage it alongside.",
865
+ RuleLimitExceeded: "The organization is at its exclusion-rule cap. Delete a rule with 'uip admin audit org exclusions delete <rule>' before adding another.",
866
+ EmptySelectorsNotAllowed: `Pass at least one of ${SELECTOR_FLAGS.join(" / ")}. A rule that constrains nothing would exclude every event in the organization.`,
867
+ InvalidSelectorValue: "Selector values are GUIDs, except --status which takes 'Success' or 'Failure'.",
868
+ UnknownSelectorValue: "No audit metadata defines that id. Discover valid source / target / type ids with 'uip admin audit org sources --output json'.",
869
+ SelectorValueNotPermitted: "That value cannot be excluded: UiPath's own monitoring events and audit-configuration changes always stay in the trail. Narrow the rule to the events you own.",
870
+ SelectorLimitExceeded: "Too many selectors, or too many values in one selector. Split the rule into several narrower ones.",
871
+ RuleModifiedConcurrently: "Another admin changed the rule while this call was in flight. Re-read it with 'exclusions get <rule>' and retry.",
872
+ InvalidRequest: "The body was rejected before it reached the rule logic — the message names the field. Server-owned fields (policyId, timestamps) may not be sent."
873
+ };
874
+ function fallbackInstructions(verb, message, status) {
875
+ if (/Not logged in/i.test(message))
876
+ return "Run 'uip login' and retry.";
877
+ if (status === 401)
878
+ return "Token may be missing the 'Audit.Read' scope. Run 'uip logout && uip login' to mint a fresh token.";
879
+ if (status === 403)
880
+ return "Reading rules needs audit-read permission; creating, replacing or deleting one needs an Administrators-group membership and a user token — a service-to-service token is refused on writes.";
881
+ if (verb === "list" || verb === "get")
882
+ return "Confirm you are logged in against the right organization with 'uip login status'.";
883
+ if (verb === "delete")
884
+ return "Check the name or id with 'uip admin audit org exclusions list'.";
885
+ return `Pass --name plus at least one of ${SELECTOR_FLAGS.join(" / ")}, or --file with an ExclusionRuleWriteDto body.`;
886
+ }
887
+ async function emitFailure(verb, error) {
888
+ const details = await extractErrorDetails(error);
889
+ OutputFormatter.error({
890
+ Result: details.result,
891
+ ErrorCode: details.errorCode,
892
+ Retry: details.retry,
893
+ Message: details.message,
894
+ Instructions: codeInstructions(details.context?.errorCode) ?? fallbackInstructions(verb, details.message, details.context?.httpStatus),
895
+ ...details.context ? { Context: details.context } : {}
896
+ });
897
+ processContext.exit(EXIT_CODES[details.result] ?? EXIT_CODES.Failure);
898
+ }
899
+ function codeInstructions(code) {
900
+ if (code === undefined)
901
+ return;
902
+ return Object.hasOwn(CODE_INSTRUCTIONS, code) ? CODE_INSTRUCTIONS[code] : undefined;
903
+ }
904
+ var LOOKUP_INSTRUCTIONS = {
905
+ ambiguous: "A name is unique only among ACTIVE rules, so an inactive rule may share it. Pass the policy id of the one you mean.",
906
+ unidentifiable: "Nothing can address that rule - not even the id, which the service did not return. Re-read the list with 'uip admin audit org exclusions list'; a rule still listed without a policyId needs fixing server-side.",
907
+ "not-found": "Check the name with 'uip admin audit org exclusions list', or pass the rule's policy id instead."
908
+ };
909
+ function emitLookupError(verb, error) {
910
+ const isCallerError = error.reason === "ambiguous";
911
+ OutputFormatter.error({
912
+ Result: isCallerError ? RESULTS.ValidationError : RESULTS.Failure,
913
+ ErrorCode: isCallerError ? "invalid_argument" : "not_found",
914
+ Retry: "RetryWillNotFix",
915
+ Message: error.message,
916
+ Instructions: error.reason === "not-found" ? `${LOOKUP_INSTRUCTIONS["not-found"]} ('${verb}' takes either.)` : LOOKUP_INSTRUCTIONS[error.reason]
917
+ });
918
+ processContext.exit(isCallerError ? EXIT_CODES.ValidationError : EXIT_CODES.Failure);
919
+ }
920
+
921
+ class BodyError extends Error {
922
+ instructions;
923
+ constructor(message, instructions) {
924
+ super(message);
925
+ this.name = "BodyError";
926
+ this.instructions = instructions;
927
+ }
928
+ }
929
+ async function emitBodyFailure(verb, error) {
930
+ if (!(error instanceof BodyError)) {
931
+ await emitFailure(verb, error);
932
+ return;
933
+ }
934
+ OutputFormatter.error({
935
+ Result: RESULTS.ValidationError,
936
+ Message: error.message,
937
+ Instructions: error.instructions
938
+ });
939
+ processContext.exit(EXIT_CODES.ValidationError);
940
+ }
941
+ var FILE_BODY_INSTRUCTIONS = "A rule body carries only name, enforcement, isActive and selectors. policyId and the timestamps are server-owned and are rejected rather than ignored.";
942
+ var FILE_READ_INSTRUCTIONS = "Check the --file path and that the file holds one JSON object shaped like an ExclusionRuleWriteDto.";
943
+ var ID_INSTRUCTIONS = "Selector ids are GUIDs. Discover source / target / type ids with 'uip admin audit org sources --output json'.";
944
+ function assertIds(label, values) {
945
+ for (const value of values) {
946
+ const trimmed = value.trim();
947
+ if (!GUID_RE.test(trimmed) || trimmed.toLowerCase() === EMPTY_GUID) {
948
+ throw new BodyError(`${label} expects a GUID, got '${value}'.`, ID_INSTRUCTIONS);
949
+ }
950
+ }
951
+ }
952
+ function assertNotGuidShaped(name) {
953
+ if (isGuid(name)) {
954
+ throw new BodyError(`'${name}' cannot be used as a rule name: it is shaped like a policy id.`, "Pick a name that is not a bare GUID. 'get', 'update' and 'delete' read a GUID as a policy id, so a rule named like one could not be reached by name — and would shadow whichever rule owns that id.");
955
+ }
956
+ }
957
+ var STATUS_ALIASES = new Map([
958
+ ["success", "Success"],
959
+ ["0", "Success"],
960
+ ["failure", "Failure"],
961
+ ["1", "Failure"]
962
+ ]);
963
+ var DIMENSION_NAMES = [
964
+ ...ID_DIMENSIONS.map((dimension) => dimension.dimension),
965
+ "Status"
966
+ ];
967
+ function validateSelector(raw, seen) {
968
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
969
+ throw new BodyError("Each selector must be a JSON object.", FILE_BODY_INSTRUCTIONS);
970
+ }
971
+ const selector = raw;
972
+ const unknownKeys = Object.keys(selector).filter((key) => !SELECTOR_KEYS.includes(key));
973
+ if (unknownKeys.length > 0) {
974
+ throw new BodyError(`Unsupported field(s) in a selector: ${unknownKeys.join(", ")}.`, `A selector carries only ${SELECTOR_KEYS.join(" and ")}: a 'type' naming the dimension and its 'values'.`);
975
+ }
976
+ const type = selector.type;
977
+ if (typeof type !== "string" || !DIMENSION_NAMES.includes(type)) {
978
+ throw new BodyError(`'${String(type)}' is not an exclusion dimension.`, `A selector's 'type' is one of ${DIMENSION_NAMES.join(", ")}.`);
979
+ }
980
+ if (seen.has(type)) {
981
+ throw new BodyError(`Two selectors constrain '${type}'.`, "A rule constrains each dimension at most once. Put every value for a dimension in that one selector's 'values'.");
982
+ }
983
+ seen.add(type);
984
+ const values = selector.values;
985
+ if (!Array.isArray(values) || values.length === 0 || values.some((value) => typeof value !== "string")) {
986
+ throw new BodyError(`The '${type}' selector needs a non-empty 'values' array of strings.`, "A selector names the values it matches; an empty one would constrain nothing on that dimension.");
987
+ }
988
+ const label = `selector '${type}'`;
989
+ if (type === "Status") {
990
+ return {
991
+ type,
992
+ values: values.map((value) => canonicalStatus(value, label))
993
+ };
994
+ }
995
+ assertIds(label, values);
996
+ return { type, values: values.map((value) => value.trim()) };
997
+ }
998
+ function canonicalStatus(value, label = "--status") {
999
+ const match = STATUS_ALIASES.get(value.trim().toLowerCase());
1000
+ if (!match) {
1001
+ throw new BodyError(`${label} expects ${STATUS_VALUES.join(" or ")}, got '${value}'.`, "Use --status Success or --status Failure (case-insensitive; 0 and 1 work too, as on `audit <scope> events`). One or the other: a rule that excludes both outcomes constrains nothing on this dimension.");
1002
+ }
1003
+ return match;
1004
+ }
1005
+ function bodyFromFlags(options) {
1006
+ const name = options.name?.trim();
1007
+ if (!name) {
1008
+ throw new BodyError("--name is required.", `Pass --name "<rule name>". It must be unique among the organization's active rules.`);
1009
+ }
1010
+ assertNotGuidShaped(name);
1011
+ const selectors = [];
1012
+ for (const { option, flag, dimension } of ID_DIMENSIONS) {
1013
+ const values = options[option];
1014
+ if (!values?.length)
1015
+ continue;
1016
+ assertIds(flag, values);
1017
+ selectors.push({
1018
+ type: dimension,
1019
+ values: values.map((v) => v.trim())
1020
+ });
1021
+ }
1022
+ if (options.status !== undefined) {
1023
+ selectors.push({
1024
+ type: "Status",
1025
+ values: [canonicalStatus(options.status)]
1026
+ });
1027
+ }
1028
+ if (selectors.length === 0) {
1029
+ throw new BodyError("A rule must constrain at least one dimension.", CODE_INSTRUCTIONS.EmptySelectorsNotAllowed);
1030
+ }
1031
+ return {
1032
+ name,
1033
+ enforcement: ENFORCEMENT,
1034
+ isActive: options.inactive !== true,
1035
+ selectors
1036
+ };
1037
+ }
1038
+ function validateWriteBody(parsed) {
1039
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
1040
+ throw new BodyError("The file must contain a JSON object.", FILE_READ_INSTRUCTIONS);
1041
+ }
1042
+ const body = parsed;
1043
+ const unknown = Object.keys(body).filter((key) => !WRITE_BODY_KEYS.includes(key));
1044
+ if (unknown.length > 0) {
1045
+ throw new BodyError(`Unsupported field(s) in --file: ${unknown.join(", ")}.`, FILE_BODY_INSTRUCTIONS);
1046
+ }
1047
+ if (typeof body.name !== "string" || body.name.trim() === "") {
1048
+ throw new BodyError("The file must set a non-empty 'name'.", "Give the rule a name in the file's 'name' field. It must be unique among the organization's active rules.");
1049
+ }
1050
+ const name = body.name.trim();
1051
+ assertNotGuidShaped(name);
1052
+ if (body.selectors !== undefined && body.selectors !== null && !Array.isArray(body.selectors)) {
1053
+ throw new BodyError("'selectors' must be an array.", FILE_BODY_INSTRUCTIONS);
1054
+ }
1055
+ const seenDimensions = new Set;
1056
+ const selectors = Array.isArray(body.selectors) ? body.selectors.map((selector) => validateSelector(selector, seenDimensions)) : [];
1057
+ if (selectors.length === 0) {
1058
+ throw new BodyError("A rule must constrain at least one dimension.", "Give the file's 'selectors' at least one entry. A rule that constrains nothing would exclude every event in the organization.");
1059
+ }
1060
+ return {
1061
+ ...body,
1062
+ name,
1063
+ selectors,
1064
+ enforcement: body.enforcement ?? ENFORCEMENT,
1065
+ isActive: body.isActive ?? true
1066
+ };
1067
+ }
1068
+ function tooLarge(amount, unit) {
1069
+ return new BodyError(`--file is ${amount} ${unit}; a rule body may not exceed ${MAX_FILE_LENGTH}.`, "Point --file at a single rule body. The file is one rule, not an export of many.");
1070
+ }
1071
+ async function bodyFromFile(file) {
1072
+ const fs = getFileSystem();
1073
+ const stats = await fs.stat(file);
1074
+ if (stats && stats.size > MAX_FILE_LENGTH) {
1075
+ throw tooLarge(stats.size, "bytes");
1076
+ }
1077
+ const content = await fs.readFile(file, "utf-8");
1078
+ if (content === null || content === undefined) {
1079
+ throw new BodyError(`File not found: ${file}`, FILE_READ_INSTRUCTIONS);
1080
+ }
1081
+ const raw = String(content);
1082
+ const byteLength = new TextEncoder().encode(raw).length;
1083
+ if (byteLength > MAX_FILE_LENGTH) {
1084
+ throw tooLarge(byteLength, "bytes");
1085
+ }
1086
+ let parsed;
1087
+ try {
1088
+ parsed = JSON.parse(raw);
1089
+ } catch (err) {
1090
+ throw new BodyError(`--file is not valid JSON: ${err instanceof Error ? err.message : String(err)}`, FILE_READ_INSTRUCTIONS);
1091
+ }
1092
+ return validateWriteBody(parsed);
1093
+ }
1094
+ async function resolveBody(options) {
1095
+ const inlineFlags = [
1096
+ options.name !== undefined && "--name",
1097
+ options.inactive === true && "--inactive",
1098
+ ...ID_DIMENSIONS.map(({ option, flag }) => options[option]?.length && flag),
1099
+ options.status !== undefined && "--status"
1100
+ ].filter((flag) => typeof flag === "string");
1101
+ if (options.file !== undefined) {
1102
+ if (inlineFlags.length > 0) {
1103
+ throw new BodyError(`--file cannot be combined with ${inlineFlags.join(", ")}.`, "Pass either --file with the whole body, or the inline flags — not both. Merging them would leave it ambiguous which input owns a field both set.");
1104
+ }
1105
+ return await bodyFromFile(options.file);
1106
+ }
1107
+ return bodyFromFlags(options);
1108
+ }
1109
+ async function getApi(options) {
1110
+ return await createApiClient(EventConfigApi, {
1111
+ scope: "org",
1112
+ loginValidity: options.loginValidity
1113
+ });
1114
+ }
1115
+ var RULE_ARGUMENT = [
1116
+ "<rule>",
1117
+ "Rule name, or its policy id. A name is matched against the organization's rules; an id is used as it stands."
1118
+ ];
1119
+ async function resolveTarget(verb, rule, options) {
1120
+ const [apiError, api] = await catchError(getApi(options));
1121
+ if (apiError || !api) {
1122
+ await emitFailure(verb, apiError);
1123
+ return;
1124
+ }
1125
+ const [lookupError, target] = await catchError(resolveExclusionRule(api, rule));
1126
+ if (lookupError || !target) {
1127
+ if (lookupError instanceof ExclusionRuleLookupError) {
1128
+ emitLookupError(verb, lookupError);
1129
+ } else {
1130
+ await emitFailure(verb, lookupError);
1131
+ }
1132
+ return;
1133
+ }
1134
+ return { api, policyId: target.policyId, resolved: target.rule };
1135
+ }
1136
+ function withLoginValidity(cmd) {
1137
+ return cmd.option("--login-validity <minutes>", "Override the interactive-login token lifetime for this call. Rarely needed.", (v) => Number.parseInt(v, 10));
1138
+ }
1139
+ function withWriteOptions(cmd) {
1140
+ return withLoginValidity(cmd.option("--name <name>", "Rule name, unique among the organization's ACTIVE rules. Max 256 characters.").option("--exclude-tenant <guid...>", "Tenant selector: exclude events from these tenants only. Repeatable. Not spelled --tenant-id, which on the read verbs picks the tenant a call runs against rather than the tenants a rule matches. A tenant outside this organization is accepted but matches nothing, so a typo reads as a rule that silently never fires.").option("--source <guid...>", "EventSource selector. Repeatable. Discover ids with `audit org sources`.").option("--target <guid...>", "EventTarget selector. Repeatable. Discover ids with `audit org sources`.").option("--type <guid...>", "EventType selector. Repeatable. Discover ids with `audit org sources`.").option("--status <status>", "Status selector: 'Success' or 'Failure' (case-insensitive). Single-valued, like --status on `audit <scope> events` — a selector holding both statuses matches every event, which is what omitting the flag already does.").option("--inactive", "Save the rule without activating it. Nothing is excluded until it is active, and an inactive rule may reuse an active rule's name or match set.").option("--file <path>", "Path to a JSON file holding the whole rule body (name, enforcement, isActive, selectors). Mutually exclusive with the flags above."));
1141
+ }
1142
+ var SAMPLE_RULE = {
1143
+ policyId: SAMPLE_ID,
1144
+ name: SAMPLE_NAME,
1145
+ enforcement: ENFORCEMENT,
1146
+ isActive: true,
1147
+ activatedOn: "2026-09-17T09:14:22.000Z",
1148
+ selectors: [
1149
+ { type: "EventType", values: [SAMPLE_TYPE_ID] },
1150
+ { type: "Status", values: ["Success"] }
1151
+ ],
1152
+ createdOn: "2026-09-17T09:14:22.000Z",
1153
+ lastModifiedOn: "2026-09-17T09:14:22.000Z"
1154
+ };
1155
+ var LIST_EXAMPLES = [
1156
+ {
1157
+ Description: "List the organization's exclusion rules, ordered by name",
1158
+ Command: "uip admin audit org exclusions list",
1159
+ Output: { Code: "AuditOrgExclusionsList", Data: [SAMPLE_RULE] }
1160
+ }
1161
+ ];
1162
+ var GET_EXAMPLES = [
1163
+ {
1164
+ Description: "Read one rule by the name it was given",
1165
+ Command: `uip admin audit org exclusions get "${SAMPLE_NAME}"`,
1166
+ Output: { Code: "AuditOrgExclusionsGet", Data: SAMPLE_RULE }
1167
+ },
1168
+ {
1169
+ Description: "Read it by policy id instead, which skips the name lookup",
1170
+ Command: `uip admin audit org exclusions get ${SAMPLE_ID}`,
1171
+ Output: { Code: "AuditOrgExclusionsGet", Data: SAMPLE_RULE }
1172
+ }
1173
+ ];
1174
+ var CREATE_EXAMPLES = [
1175
+ {
1176
+ Description: "Stop recording successful events of one event type (the two selectors are AND-ed)",
1177
+ Command: `uip admin audit org exclusions create --name "Mute successful robot logins" --type ${SAMPLE_TYPE_ID} --status Success`,
1178
+ Output: { Code: "AuditOrgExclusionsCreated", Data: SAMPLE_RULE }
1179
+ },
1180
+ {
1181
+ Description: "Stage a rule without activating it, so it excludes nothing until it is turned on",
1182
+ Command: `uip admin audit org exclusions create --name "Staged" --source ${SAMPLE_ID} --inactive`,
1183
+ Output: {
1184
+ Code: "AuditOrgExclusionsCreated",
1185
+ Data: { ...SAMPLE_RULE, isActive: false, activatedOn: null }
1186
+ }
1187
+ },
1188
+ {
1189
+ Description: "Create from a JSON body instead of flags",
1190
+ Command: "uip admin audit org exclusions create --file ./rule.json",
1191
+ Output: { Code: "AuditOrgExclusionsCreated", Data: SAMPLE_RULE }
1192
+ }
1193
+ ];
1194
+ var UPDATE_EXAMPLES = [
1195
+ {
1196
+ Description: "Replace a rule in full — every field is resent, and omitted selectors are dropped",
1197
+ Command: `uip admin audit org exclusions update "${SAMPLE_NAME}" --name "${SAMPLE_NAME}" --type ${SAMPLE_TYPE_ID} --status Success`,
1198
+ Output: { Code: "AuditOrgExclusionsUpdated", Data: SAMPLE_RULE }
1199
+ }
1200
+ ];
1201
+ var DELETE_EXAMPLES = [
1202
+ {
1203
+ Description: "Delete a rule, so its events are recorded again from now on",
1204
+ Command: `uip admin audit org exclusions delete "${SAMPLE_NAME}"`,
1205
+ Output: { Code: "AuditOrgExclusionsDeleted", Data: {} }
1206
+ }
1207
+ ];
1208
+ function registerExclusionCommands(org) {
1209
+ const exclusions = org.command("exclusions").description([
1210
+ "Manage the organization's audit exclusion rules — which events the audit trail stops recording.",
1211
+ "",
1212
+ "A rule carries one selector per dimension (Tenant, EventSource, EventTarget, EventType, Status).",
1213
+ "Values inside a selector are OR-ed, and selectors are AND-ed: `--type A --type B --status Success`",
1214
+ "excludes successful events of type A or B. A rule with no selector is refused — it would",
1215
+ "exclude everything.",
1216
+ "",
1217
+ "Exclusion starts when the rule becomes active and is never retroactive: events already in the",
1218
+ "trail stay there, and widening a rule's match set re-stamps that start time. An inactive rule",
1219
+ "excludes nothing, which is how you stage a replacement next to the rule it takes over from.",
1220
+ "",
1221
+ "`get`, `update` and `delete` take the rule's name or its policy id. A name is unique only",
1222
+ "among ACTIVE rules, so if an inactive rule shares one the CLI asks for the id rather than",
1223
+ "guessing which you meant.",
1224
+ "",
1225
+ "Org-scoped only (there is no `audit tenant exclusions`): name the tenants a rule applies to with",
1226
+ "--exclude-tenant. Reading rules needs audit-read permission; every write needs a user token whose",
1227
+ "identity is in the Administrators group.",
1228
+ "",
1229
+ "Two things can never be excluded: UiPath's own monitoring events, and audit-configuration",
1230
+ "changes — including the rules themselves."
1231
+ ].join(`
1232
+ `));
1233
+ withLoginValidity(exclusions.command("list").description([
1234
+ "List every exclusion rule in the organization, ordered by name.",
1235
+ "",
1236
+ "The set is capped server-side, so there is no pagination. A rule whose stored",
1237
+ "document cannot be parsed is still listed, with an empty `selectors` array, so",
1238
+ "it can be deleted."
1239
+ ].join(`
1240
+ `)).examples(LIST_EXAMPLES)).trackedAction(processContext, async (options) => {
1241
+ const [error, result] = await catchError((async () => await (await getApi(options)).eventConfigGetRules())());
1242
+ if (error) {
1243
+ await emitFailure("list", error);
1244
+ return;
1245
+ }
1246
+ OutputFormatter.success({
1247
+ Result: RESULTS.Success,
1248
+ Code: "AuditOrgExclusionsList",
1249
+ Data: result ?? []
1250
+ });
1251
+ });
1252
+ withLoginValidity(exclusions.command("get").description("Read one exclusion rule, by name or by policy id.").argument(...RULE_ARGUMENT).examples(GET_EXAMPLES)).trackedAction(processContext, async (rule, options) => {
1253
+ const target = await resolveTarget("get", rule, options);
1254
+ if (!target)
1255
+ return;
1256
+ if (target.resolved) {
1257
+ OutputFormatter.success({
1258
+ Result: RESULTS.Success,
1259
+ Code: "AuditOrgExclusionsGet",
1260
+ Data: target.resolved
1261
+ });
1262
+ return;
1263
+ }
1264
+ const [error, result] = await catchError(target.api.eventConfigGetRule({ policyId: target.policyId }));
1265
+ if (error) {
1266
+ await emitFailure("get", error);
1267
+ return;
1268
+ }
1269
+ OutputFormatter.success({
1270
+ Result: RESULTS.Success,
1271
+ Code: "AuditOrgExclusionsGet",
1272
+ Data: result
1273
+ });
1274
+ });
1275
+ withWriteOptions(exclusions.command("create").description([
1276
+ "Create an exclusion rule.",
1277
+ "",
1278
+ "The rule is active unless --inactive is passed, and an active rule is refused when",
1279
+ "another active rule already carries the same name or already excludes everything",
1280
+ "this one would."
1281
+ ].join(`
1282
+ `)).examples(CREATE_EXAMPLES)).trackedAction(processContext, async (options) => {
1283
+ const [bodyError, body] = await catchError(resolveBody(options));
1284
+ if (bodyError) {
1285
+ await emitBodyFailure("create", bodyError);
1286
+ return;
1287
+ }
1288
+ const [error, result] = await catchError((async () => await (await getApi(options)).eventConfigCreateRule({
1289
+ exclusionRuleWriteDto: body
1290
+ }))());
1291
+ if (error) {
1292
+ await emitFailure("create", error);
1293
+ return;
1294
+ }
1295
+ OutputFormatter.success({
1296
+ Result: RESULTS.Success,
1297
+ Code: "AuditOrgExclusionsCreated",
1298
+ Data: result
1299
+ });
1300
+ });
1301
+ withWriteOptions(exclusions.command("update").description([
1302
+ "Replace an exclusion rule in full.",
1303
+ "",
1304
+ "This is a replacement, not a patch: whatever you leave out is dropped, so resend",
1305
+ "every flag the rule should keep (read it first with `exclusions get`). Renaming a",
1306
+ "rule leaves its exclusion start time alone; changing which events it matches",
1307
+ "re-stamps that time, so the widened rule does not cover events it never matched.",
1308
+ "",
1309
+ "Activation is part of the replacement: without --inactive the rule comes back",
1310
+ "ACTIVE, so editing a rule you deliberately staged inactive starts it excluding",
1311
+ "events. Pass --inactive again to keep it staged.",
1312
+ "",
1313
+ "Pass <rule> before the selector flags. Those flags take a list, so a value",
1314
+ "written after one is read as another of its values."
1315
+ ].join(`
1316
+ `)).argument(...RULE_ARGUMENT).examples(UPDATE_EXAMPLES)).trackedAction(processContext, async (rule, options) => {
1317
+ const [bodyError, body] = await catchError(resolveBody(options));
1318
+ if (bodyError) {
1319
+ await emitBodyFailure("update", bodyError);
1320
+ return;
1321
+ }
1322
+ const target = await resolveTarget("update", rule, options);
1323
+ if (!target)
1324
+ return;
1325
+ const [error, result] = await catchError(target.api.eventConfigReplaceRule({
1326
+ policyId: target.policyId,
1327
+ exclusionRuleWriteDto: body
1328
+ }));
1329
+ if (error) {
1330
+ await emitFailure("update", error);
1331
+ return;
1332
+ }
1333
+ OutputFormatter.success({
1334
+ Result: RESULTS.Success,
1335
+ Code: "AuditOrgExclusionsUpdated",
1336
+ Data: result
1337
+ });
1338
+ });
1339
+ withLoginValidity(exclusions.command("delete").description([
1340
+ "Delete an exclusion rule.",
1341
+ "",
1342
+ "Events it was excluding are recorded again from now on. Events suppressed while",
1343
+ "it was active are gone for good — deleting the rule does not bring them back."
1344
+ ].join(`
1345
+ `)).argument(...RULE_ARGUMENT).examples(DELETE_EXAMPLES)).trackedAction(processContext, async (rule, options) => {
1346
+ const target = await resolveTarget("delete", rule, options);
1347
+ if (!target)
1348
+ return;
1349
+ const [error] = await catchError(target.api.eventConfigDeleteRule({
1350
+ policyId: target.policyId
1351
+ }));
1352
+ if (error) {
1353
+ await emitFailure("delete", error);
1354
+ return;
1355
+ }
1356
+ OutputFormatter.success({
1357
+ Result: RESULTS.Success,
1358
+ Code: "AuditOrgExclusionsDeleted",
1359
+ Data: {}
1360
+ });
1361
+ });
1362
+ }
1363
+
1364
+ // ../audit-commands/src/utils/chunked-export.ts
1365
+ import { Buffer } from "node:buffer";
1366
+
1367
+ // ../../../node_modules/fflate/esm/index.mjs
1368
+ import { createRequire } from "module";
1369
+ var require2 = createRequire("/");
1370
+ var _a;
1371
+ var Worker;
1372
+ var isMarkedAsUntransferable;
1373
+ try {
1374
+ _a = require2("worker_threads"), Worker = _a.Worker, isMarkedAsUntransferable = _a.isMarkedAsUntransferable;
1375
+ } catch (e) {}
1376
+ var u8 = Uint8Array;
1377
+ var u16 = Uint16Array;
1378
+ var i32 = Int32Array;
1379
+ var fleb = new u8([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 0, 0, 0]);
1380
+ var fdeb = new u8([0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 0, 0]);
1381
+ var clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);
1382
+ var freb = function(eb, start) {
1383
+ var b = new u16(31);
1384
+ for (var i = 0;i < 31; ++i) {
1385
+ b[i] = start += 1 << eb[i - 1];
1386
+ }
1387
+ var r = new i32(b[30]);
1388
+ for (var i = 1;i < 30; ++i) {
1389
+ for (var j = b[i];j < b[i + 1]; ++j) {
1390
+ r[j] = j - b[i] << 5 | i;
1391
+ }
1392
+ }
1393
+ return { b, r };
1394
+ };
1395
+ var _a = freb(fleb, 2);
1396
+ var fl = _a.b;
1397
+ var revfl = _a.r;
1398
+ fl[28] = 258, revfl[258] = 28;
1399
+ var _b = freb(fdeb, 0);
1400
+ var fd = _b.b;
1401
+ var revfd = _b.r;
1402
+ var rev = new u16(32768);
1403
+ for (i = 0;i < 32768; ++i) {
1404
+ x = (i & 43690) >> 1 | (i & 21845) << 1;
1405
+ x = (x & 52428) >> 2 | (x & 13107) << 2;
1406
+ x = (x & 61680) >> 4 | (x & 3855) << 4;
1407
+ rev[i] = ((x & 65280) >> 8 | (x & 255) << 8) >> 1;
1408
+ }
1409
+ var x;
1410
+ var i;
1411
+ var hMap = function(cd, mb, r) {
1412
+ var s = cd.length;
1413
+ var i2 = 0;
1414
+ var l = new u16(mb);
1415
+ for (;i2 < s; ++i2) {
1416
+ if (cd[i2])
1417
+ ++l[cd[i2] - 1];
1418
+ }
1419
+ var le = new u16(mb);
1420
+ for (i2 = 1;i2 < mb; ++i2) {
1421
+ le[i2] = le[i2 - 1] + l[i2 - 1] << 1;
1422
+ }
1423
+ var co;
1424
+ if (r) {
1425
+ co = new u16(1 << mb);
1426
+ var rvb = 15 - mb;
1427
+ for (i2 = 0;i2 < s; ++i2) {
1428
+ if (cd[i2]) {
1429
+ var sv = i2 << 4 | cd[i2];
1430
+ var r_1 = mb - cd[i2];
1431
+ var v = le[cd[i2] - 1]++ << r_1;
1432
+ for (var m = v | (1 << r_1) - 1;v <= m; ++v) {
1433
+ co[rev[v] >> rvb] = sv;
1434
+ }
1435
+ }
1436
+ }
1437
+ } else {
1438
+ co = new u16(s);
1439
+ for (i2 = 0;i2 < s; ++i2) {
1440
+ if (cd[i2]) {
1441
+ co[i2] = rev[le[cd[i2] - 1]++] >> 15 - cd[i2];
1442
+ }
1443
+ }
1444
+ }
1445
+ return co;
1446
+ };
1447
+ var flt = new u8(288);
1448
+ for (i = 0;i < 144; ++i)
1449
+ flt[i] = 8;
1450
+ var i;
1451
+ for (i = 144;i < 256; ++i)
1452
+ flt[i] = 9;
1453
+ var i;
1454
+ for (i = 256;i < 280; ++i)
1455
+ flt[i] = 7;
1456
+ var i;
1457
+ for (i = 280;i < 288; ++i)
1458
+ flt[i] = 8;
1459
+ var i;
1460
+ var fdt = new u8(32);
1461
+ for (i = 0;i < 32; ++i)
1462
+ fdt[i] = 5;
1463
+ var i;
1464
+ var flrm = /* @__PURE__ */ hMap(flt, 9, 1);
1465
+ var fdrm = /* @__PURE__ */ hMap(fdt, 5, 1);
1466
+ var max = function(a) {
1467
+ var m = a[0];
1468
+ for (var i2 = 1;i2 < a.length; ++i2) {
1469
+ if (a[i2] > m)
1470
+ m = a[i2];
1471
+ }
1472
+ return m;
1473
+ };
1474
+ var bits = function(d, p, m) {
1475
+ var o = p / 8 | 0;
1476
+ return (d[o] | d[o + 1] << 8) >> (p & 7) & m;
1477
+ };
1478
+ var bits16 = function(d, p) {
1479
+ var o = p / 8 | 0;
1480
+ return (d[o] | d[o + 1] << 8 | d[o + 2] << 16) >> (p & 7);
1481
+ };
1482
+ var shft = function(p) {
1483
+ return (p + 7) / 8 | 0;
1484
+ };
1485
+ var slc = function(v, s, e) {
1486
+ if (s == null || s < 0)
1487
+ s = 0;
1488
+ if (e == null || e > v.length)
1489
+ e = v.length;
1490
+ return new u8(v.subarray(s, e));
1491
+ };
1492
+ var ec = [
1493
+ "unexpected EOF",
1494
+ "invalid block type",
1495
+ "invalid length/literal",
1496
+ "invalid distance",
1497
+ "stream finished",
1498
+ "no stream handler",
1499
+ ,
1500
+ "no callback",
1501
+ "invalid UTF-8 data",
1502
+ "extra field too long",
1503
+ "date not in range 1980-2099",
1504
+ "filename too long",
1505
+ "stream finishing",
1506
+ "invalid zip data"
1507
+ ];
1508
+ var err = function(ind, msg, nt) {
1509
+ var e = new Error(msg || ec[ind]);
1510
+ e.code = ind;
1511
+ if (Error.captureStackTrace)
1512
+ Error.captureStackTrace(e, err);
1513
+ if (!nt)
1514
+ throw e;
1515
+ return e;
1516
+ };
1517
+ var inflt = function(dat, st, buf, dict) {
1518
+ var sl = dat.length, dl = dict ? dict.length : 0;
1519
+ if (!sl || st.f && !st.l)
1520
+ return buf || new u8(0);
1521
+ var noBuf = !buf;
1522
+ var resize = noBuf || st.i != 2;
1523
+ var noSt = st.i;
1524
+ if (noBuf)
1525
+ buf = new u8(sl * 3);
1526
+ var cbuf = function(l2) {
1527
+ var bl = buf.length;
1528
+ if (l2 > bl) {
1529
+ var nbuf = new u8(Math.max(bl * 2, l2));
1530
+ nbuf.set(buf);
1531
+ buf = nbuf;
1532
+ }
1533
+ };
1534
+ var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n;
1535
+ var tbts = sl * 8;
1536
+ do {
1537
+ if (!lm) {
1538
+ final = bits(dat, pos, 1);
1539
+ var type = bits(dat, pos + 1, 3);
1540
+ pos += 3;
1541
+ if (!type) {
1542
+ var s = shft(pos) + 4, l = dat[s - 4] | dat[s - 3] << 8, t = s + l;
1543
+ if (t > sl) {
1544
+ if (noSt)
1545
+ err(0);
1546
+ break;
1547
+ }
1548
+ if (resize)
1549
+ cbuf(bt + l);
1550
+ buf.set(dat.subarray(s, t), bt);
1551
+ st.b = bt += l, st.p = pos = t * 8, st.f = final;
1552
+ continue;
1553
+ } else if (type == 1)
1554
+ lm = flrm, dm = fdrm, lbt = 9, dbt = 5;
1555
+ else if (type == 2) {
1556
+ var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4;
1557
+ var tl = hLit + bits(dat, pos + 5, 31) + 1;
1558
+ pos += 14;
1559
+ var ldt = new u8(tl);
1560
+ var clt = new u8(19);
1561
+ for (var i2 = 0;i2 < hcLen; ++i2) {
1562
+ clt[clim[i2]] = bits(dat, pos + i2 * 3, 7);
1563
+ }
1564
+ pos += hcLen * 3;
1565
+ var clb = max(clt), clbmsk = (1 << clb) - 1;
1566
+ var clm = hMap(clt, clb, 1);
1567
+ for (var i2 = 0;i2 < tl; ) {
1568
+ var r = clm[bits(dat, pos, clbmsk)];
1569
+ pos += r & 15;
1570
+ var s = r >> 4;
1571
+ if (s < 16) {
1572
+ ldt[i2++] = s;
1573
+ } else {
1574
+ var c = 0, n = 0;
1575
+ if (s == 16)
1576
+ n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i2 - 1];
1577
+ else if (s == 17)
1578
+ n = 3 + bits(dat, pos, 7), pos += 3;
1579
+ else if (s == 18)
1580
+ n = 11 + bits(dat, pos, 127), pos += 7;
1581
+ while (n--)
1582
+ ldt[i2++] = c;
1583
+ }
1584
+ }
1585
+ var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit);
1586
+ lbt = max(lt);
1587
+ dbt = max(dt);
1588
+ lm = hMap(lt, lbt, 1);
1589
+ dm = hMap(dt, dbt, 1);
1590
+ } else
1591
+ err(1);
1592
+ if (pos > tbts) {
1593
+ if (noSt)
1594
+ err(0);
1595
+ break;
1596
+ }
1597
+ }
1598
+ if (resize)
1599
+ cbuf(bt + 131072);
1600
+ var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1;
1601
+ var lpos = pos;
1602
+ for (;; lpos = pos) {
1603
+ var c = lm[bits16(dat, pos) & lms], sym = c >> 4;
1604
+ pos += c & 15;
1605
+ if (pos > tbts) {
1606
+ if (noSt)
1607
+ err(0);
1608
+ break;
1609
+ }
1610
+ if (!c)
1611
+ err(2);
1612
+ if (sym < 256)
1613
+ buf[bt++] = sym;
1614
+ else if (sym == 256) {
1615
+ lpos = pos, lm = null;
1616
+ break;
1617
+ } else {
1618
+ var add = sym - 254;
1619
+ if (sym > 264) {
1620
+ var i2 = sym - 257, b = fleb[i2];
1621
+ add = bits(dat, pos, (1 << b) - 1) + fl[i2];
1622
+ pos += b;
1623
+ }
1624
+ var d = dm[bits16(dat, pos) & dms], dsym = d >> 4;
1625
+ if (!d)
1626
+ err(3);
1627
+ pos += d & 15;
1628
+ var dt = fd[dsym];
1629
+ if (dsym > 3) {
1630
+ var b = fdeb[dsym];
1631
+ dt += bits16(dat, pos) & (1 << b) - 1, pos += b;
1632
+ }
1633
+ if (pos > tbts) {
1634
+ if (noSt)
1635
+ err(0);
1636
+ break;
1637
+ }
1638
+ if (resize)
1639
+ cbuf(bt + 131072);
1640
+ var end = bt + add;
1641
+ if (bt < dt) {
1642
+ var shift = dl - dt, dend = Math.min(dt, end);
1643
+ if (shift + bt < 0)
1644
+ err(3);
1645
+ for (;bt < dend; ++bt)
1646
+ buf[bt] = dict[shift + bt];
1647
+ }
1648
+ for (;bt < end; ++bt)
1649
+ buf[bt] = buf[bt - dt];
1650
+ }
1651
+ }
1652
+ st.l = lm, st.p = lpos, st.b = bt, st.f = final;
1653
+ if (lm)
1654
+ final = 1, st.m = lbt, st.d = dm, st.n = dbt;
1655
+ } while (!final);
1656
+ return bt != buf.length && noBuf ? slc(buf, 0, bt) : buf.subarray(0, bt);
1657
+ };
1658
+ var et = /* @__PURE__ */ new u8(0);
1659
+ var b2 = function(d, b) {
1660
+ return d[b] | d[b + 1] << 8;
1661
+ };
1662
+ var b4 = function(d, b) {
1663
+ return (d[b] | d[b + 1] << 8 | d[b + 2] << 16 | d[b + 3] << 24) >>> 0;
1664
+ };
1665
+ var b8 = function(d, b) {
1666
+ return b4(d, b) + b4(d, b + 4) * 4294967296;
1667
+ };
1668
+ function inflateSync(data, opts) {
1669
+ return inflt(data, { i: 2 }, opts && opts.out, opts && opts.dictionary);
1670
+ }
1671
+ var td = typeof TextDecoder != "undefined" && /* @__PURE__ */ new TextDecoder;
1672
+ var tds = 0;
1673
+ try {
1674
+ td.decode(et, { stream: true });
1675
+ tds = 1;
1676
+ } catch (e) {}
1677
+ var dutf8 = function(d) {
1678
+ for (var r = "", i2 = 0;; ) {
1679
+ var c = d[i2++];
1680
+ var eb = (c > 127) + (c > 223) + (c > 239);
1681
+ if (i2 + eb > d.length)
1682
+ return { s: r, r: slc(d, i2 - 1) };
1683
+ if (!eb)
1684
+ r += String.fromCharCode(c);
1685
+ else if (eb == 3) {
1686
+ c = ((c & 15) << 18 | (d[i2++] & 63) << 12 | (d[i2++] & 63) << 6 | d[i2++] & 63) - 65536, r += String.fromCharCode(55296 | c >> 10, 56320 | c & 1023);
1687
+ } else if (eb & 1)
1688
+ r += String.fromCharCode((c & 31) << 6 | d[i2++] & 63);
1689
+ else
1690
+ r += String.fromCharCode((c & 15) << 12 | (d[i2++] & 63) << 6 | d[i2++] & 63);
1691
+ }
1692
+ };
1693
+ function strFromU8(dat, latin1) {
1694
+ if (latin1) {
1695
+ var r = "";
1696
+ for (var i2 = 0;i2 < dat.length; i2 += 16384)
1697
+ r += String.fromCharCode.apply(null, dat.subarray(i2, i2 + 16384));
1698
+ return r;
1699
+ } else if (td) {
1700
+ return td.decode(dat);
1701
+ } else {
1702
+ var _a2 = dutf8(dat), s = _a2.s, r = _a2.r;
1703
+ if (r.length)
1704
+ err(8);
1705
+ return s;
1706
+ }
1707
+ }
1708
+ var slzh = function(d, b) {
1709
+ return b + 30 + b2(d, b + 26) + b2(d, b + 28);
1710
+ };
1711
+ var zh = function(d, b, z) {
1712
+ var fnl = b2(d, b + 28), efl = b2(d, b + 30), fn = strFromU8(d.subarray(b + 46, b + 46 + fnl), !(b2(d, b + 8) & 2048)), es = b + 46 + fnl;
1713
+ var _a2 = z64hs(d, es, efl, z, b4(d, b + 20), b4(d, b + 24), b4(d, b + 42)), sc = _a2[0], su = _a2[1], off = _a2[2];
1714
+ return [b2(d, b + 10), sc, su, fn, es + efl + b2(d, b + 32), off];
1715
+ };
1716
+ var z64hs = function(d, b, l, z, sc, su, off) {
1717
+ var nsc = sc == 4294967295, nsu = su == 4294967295, noff = off == 4294967295, e = b + l;
1718
+ var nf = nsc + nsu + noff;
1719
+ if (z && nf) {
1720
+ for (;b + 4 < e; b += 4 + b2(d, b + 2)) {
1721
+ if (b2(d, b) == 1) {
1722
+ return [
1723
+ nsc ? b8(d, b + 4 + 8 * nsu) : sc,
1724
+ nsu ? b8(d, b + 4) : su,
1725
+ noff ? b8(d, b + 4 + 8 * (nsu + nsc)) : off,
1726
+ 1
1727
+ ];
1728
+ }
1729
+ }
1730
+ if (z < 2)
1731
+ err(13);
1732
+ }
1733
+ return [sc, su, off, 0];
1734
+ };
1735
+ function unzipSync(data, opts) {
1736
+ var files = {};
1737
+ var e = data.length - 22;
1738
+ for (;b4(data, e) != 101010256; --e) {
1739
+ if (!e || data.length - e > 65558)
1740
+ err(13);
1741
+ }
1742
+ var c = b2(data, e + 8);
1743
+ if (!c)
1744
+ return {};
1745
+ var o = b4(data, e + 16);
1746
+ var z = b4(data, e - 20) == 117853008;
1747
+ if (z) {
1748
+ var ze = b4(data, e - 12);
1749
+ z = b4(data, ze) == 101075792;
1750
+ if (z) {
1751
+ c = b4(data, ze + 32);
1752
+ o = b4(data, ze + 48);
1753
+ }
1754
+ }
1755
+ var fltr = opts && opts.filter;
1756
+ for (var i2 = 0;i2 < c; ++i2) {
1757
+ var _a2 = zh(data, o, z), c_2 = _a2[0], sc = _a2[1], su = _a2[2], fn = _a2[3], no = _a2[4], off = _a2[5], b = slzh(data, off);
1758
+ o = no;
1759
+ if (!fltr || fltr({
1760
+ name: fn,
1761
+ size: sc,
1762
+ originalSize: su,
1763
+ compression: c_2
1764
+ })) {
1765
+ if (!c_2)
1766
+ files[fn] = slc(data, b, b + sc);
1767
+ else if (c_2 == 8)
1768
+ files[fn] = inflateSync(data.subarray(b, b + sc), { out: new u8(su) });
1769
+ else
1770
+ err(14, "unknown compression type " + c_2);
1771
+ }
1772
+ }
1773
+ return files;
1774
+ }
1775
+
1776
+ // ../audit-commands/src/utils/chunked-export.ts
1777
+ var DAY_MS = 24 * 60 * 60 * 1000;
1778
+ function startOfUtcDay(d) {
1779
+ return new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(), 0, 0, 0, 0));
1780
+ }
1781
+ function endOfUtcDay(d) {
1782
+ return new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(), 23, 59, 59, 999));
1783
+ }
1784
+ function* dayChunks(from, to) {
1785
+ if (from.getTime() > to.getTime())
1786
+ return;
1787
+ let cursor = startOfUtcDay(from);
1788
+ while (cursor.getTime() <= to.getTime()) {
1789
+ const chunkFrom = cursor.getTime() < from.getTime() ? from : cursor;
1790
+ const dayEnd = endOfUtcDay(cursor);
1791
+ const chunkTo = dayEnd.getTime() > to.getTime() ? to : dayEnd;
1792
+ yield {
1793
+ chunkFrom,
1794
+ chunkTo,
1795
+ isoDay: cursor.toISOString().slice(0, 10)
1796
+ };
1797
+ cursor = new Date(cursor.getTime() + DAY_MS);
1798
+ }
1799
+ }
1800
+ function basenameNoExt(name) {
1801
+ const last = name.split(/[\\/]/).pop() ?? name;
1802
+ return last.replace(/\.[^.]+$/, "");
1803
+ }
1804
+ function basename(name) {
1805
+ return name.split(/[\\/]/).pop() ?? name;
1806
+ }
1807
+ async function forEachExportEntry(api, from, to, onEntry) {
1808
+ const chunks = [...dayChunks(from, to)];
1809
+ if (chunks.length === 0) {
1810
+ throw new Error(`Empty time window: --from (${from.toISOString()}) is after --to (${to.toISOString()}).`);
1811
+ }
1812
+ let nonEmptyDays = 0;
1813
+ for (const { chunkFrom, chunkTo, isoDay } of chunks) {
1814
+ let response;
1815
+ try {
1816
+ response = await api.queryDownloadAuditEventsFromLongTermStoreRaw({
1817
+ from: chunkFrom,
1818
+ to: chunkTo
1819
+ });
1820
+ } catch (err2) {
1821
+ if (err2 instanceof ResponseError) {
1822
+ const body = await err2.response.text().catch(() => "");
1823
+ throw new Error(`Audit export failed for ${isoDay} (HTTP ${err2.response.status}): ${body.slice(0, 500)}`);
1824
+ }
1825
+ throw new Error(`Audit export failed for ${isoDay}: ${err2 instanceof Error ? err2.message : String(err2)}`);
1826
+ }
1827
+ const dayBuffer = Buffer.from(await response.raw.arrayBuffer());
1828
+ if (dayBuffer.byteLength === 0)
1829
+ continue;
1830
+ let dayHadEntries = false;
1831
+ for (const [entryName, entryData] of Object.entries(unzipSync(new Uint8Array(dayBuffer)))) {
1832
+ if (entryName.endsWith("/"))
1833
+ continue;
1834
+ if (/\.zip$/i.test(entryName)) {
1835
+ const outerBase = basenameNoExt(entryName);
1836
+ for (const [innerName, innerData] of Object.entries(unzipSync(entryData))) {
1837
+ if (innerName.endsWith("/"))
1838
+ continue;
1839
+ const innerBase = basenameNoExt(innerName);
1840
+ onEntry({
1841
+ isoDay,
1842
+ preferredName: `${innerBase}_${outerBase}.txt`,
1843
+ data: Buffer.from(innerData)
1844
+ });
1845
+ dayHadEntries = true;
1846
+ }
1847
+ } else {
1848
+ onEntry({
1849
+ isoDay,
1850
+ preferredName: basename(entryName),
1851
+ data: Buffer.from(entryData)
1852
+ });
1853
+ dayHadEntries = true;
1854
+ }
1855
+ }
1856
+ if (dayHadEntries)
1857
+ nonEmptyDays += 1;
1858
+ }
1859
+ return { days: chunks.length, nonEmptyDays };
1860
+ }
1861
+ function exportBaseName(from, to, generatedAt) {
1862
+ const day = (d) => d.toISOString().slice(0, 10);
1863
+ const stamp = generatedAt.toISOString().slice(0, 19).replace(/[-:]/g, "");
1864
+ return `audit_${day(from)}_${day(to)}_${stamp}`;
1865
+ }
1866
+ function toJsonFileName(preferredName) {
1867
+ return `${basenameNoExt(preferredName)}.json`;
1868
+ }
1869
+ function isSafeExportEntryName(name) {
1870
+ return name.length > 0 && name !== "." && name !== ".." && !name.includes("/") && !name.includes("\\") && !name.includes("\x00");
1871
+ }
1872
+ function isWithinDir(dir, resolved) {
1873
+ let end = dir.length;
1874
+ while (end > 0 && (dir[end - 1] === "/" || dir[end - 1] === "\\")) {
1875
+ end -= 1;
1876
+ }
1877
+ const base = dir.slice(0, end);
1878
+ return resolved === base || resolved.startsWith(`${base}/`) || resolved.startsWith(`${base}\\`);
1879
+ }
1880
+ async function downloadChunkedJsonExport(api, from, to) {
1881
+ const files = [];
1882
+ const used = new Set;
1883
+ function addUnique(preferredName, isoDay, data) {
1884
+ let name = preferredName;
1885
+ if (used.has(name)) {
1886
+ const stem = basenameNoExt(preferredName);
1887
+ const ext = preferredName.slice(stem.length);
1888
+ name = `${stem}_${isoDay}${ext}`;
1889
+ let n = 2;
1890
+ while (used.has(name)) {
1891
+ name = `${stem}_${isoDay}_${n}${ext}`;
1892
+ n += 1;
1893
+ }
1894
+ }
1895
+ used.add(name);
1896
+ files.push({ name, data });
1897
+ }
1898
+ const { days, nonEmptyDays } = await forEachExportEntry(api, from, to, ({ isoDay, preferredName, data }) => addUnique(toJsonFileName(preferredName), isoDay, data));
1899
+ return { files, days, nonEmptyDays };
1900
+ }
1901
+ var PREFERRED_CSV_COLUMNS = [
1902
+ "Identifier",
1903
+ "DateCreatedUtc",
1904
+ "OrganizationId",
1905
+ "OrganizationName",
1906
+ "TenantId",
1907
+ "TenantName",
1908
+ "ActorId",
1909
+ "User",
1910
+ "ActorEmail",
1911
+ "ActorDetails",
1912
+ "Action",
1913
+ "Source",
1914
+ "Category",
1915
+ "EventDetails",
1916
+ "EventSummary",
1917
+ "Status",
1918
+ "ClientInformation"
1919
+ ];
1920
+ function parseDailyEvents(data, isoDay, fileName) {
1921
+ let text = data.toString("utf8");
1922
+ if (text.charCodeAt(0) === 65279)
1923
+ text = text.slice(1);
1924
+ text = text.trim();
1925
+ if (text.length === 0)
1926
+ return [];
1927
+ let parsed;
1928
+ try {
1929
+ parsed = JSON.parse(text);
1930
+ } catch (err2) {
1931
+ throw new Error(`Audit export for ${isoDay} returned a file (${fileName}) that is not valid JSON: ${err2 instanceof Error ? err2.message : String(err2)}`);
1932
+ }
1933
+ if (Array.isArray(parsed))
1934
+ return parsed;
1935
+ if (parsed && typeof parsed === "object")
1936
+ return [parsed];
1937
+ throw new Error(`Audit export for ${isoDay} file ${fileName} did not contain a JSON array of events.`);
1938
+ }
1939
+ function deriveCsvColumns(events) {
1940
+ const seen = new Set;
1941
+ for (const ev of events) {
1942
+ for (const key of Object.keys(ev))
1943
+ seen.add(key);
1944
+ }
1945
+ if (seen.size === 0)
1946
+ return [...PREFERRED_CSV_COLUMNS];
1947
+ const ordered = [];
1948
+ for (const col of PREFERRED_CSV_COLUMNS) {
1949
+ if (seen.delete(col))
1950
+ ordered.push(col);
1951
+ }
1952
+ for (const col of seen)
1953
+ ordered.push(col);
1954
+ return ordered;
1955
+ }
1956
+ function csvField(value) {
1957
+ if (value === null || value === undefined)
1958
+ return "";
1959
+ let s = typeof value === "object" ? JSON.stringify(value) : String(value);
1960
+ if (typeof value === "string" && /^[=+\-@\t\r]/.test(s)) {
1961
+ s = `'${s}`;
1962
+ }
1963
+ return /["\r\n,]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
1964
+ }
1965
+ function eventsToCsv(events) {
1966
+ const columns = deriveCsvColumns(events);
1967
+ const rows = [columns.map(csvField).join(",")];
1968
+ for (const ev of events) {
1969
+ rows.push(columns.map((col) => csvField(ev[col])).join(","));
1970
+ }
1971
+ return `${rows.join(`\r
1972
+ `)}\r
1973
+ `;
1974
+ }
1975
+ async function downloadChunkedCsvExport(api, from, to) {
1976
+ const events = [];
1977
+ const { days, nonEmptyDays } = await forEachExportEntry(api, from, to, ({ isoDay, preferredName, data }) => {
1978
+ events.push(...parseDailyEvents(data, isoDay, preferredName));
1979
+ });
1980
+ const csv = eventsToCsv(events);
1981
+ return {
1982
+ buffer: Buffer.from(csv, "utf8"),
1983
+ days,
1984
+ nonEmptyDays,
1985
+ eventCount: events.length
1986
+ };
1987
+ }
1988
+
1989
+ // ../audit-commands/src/commands/shared.ts
1990
+ var SERVER_MAX_PAGE = 200;
1991
+ function instructionsFor(verb, error) {
1992
+ const msg = error instanceof Error ? error.message : String(error);
1993
+ if (/Not logged in/i.test(msg))
1994
+ return "Run 'uip login' and retry.";
1995
+ if (/Tenant ID required/i.test(msg))
1996
+ return "Pass --tenant-id <guid>, or run 'uip login' and select a tenant before retrying.";
1997
+ if (/HTTP 401/.test(msg))
1998
+ return "Token may be missing the 'Audit.Read' scope. Run 'uip logout && uip login' to mint a fresh token.";
1999
+ if (/HTTP 403/.test(msg))
2000
+ return "Logged-in user lacks audit-read permission on this tenant. Check role assignments in Automation Cloud.";
2001
+ if (/HTTP 504/.test(msg) || /Audit export failed for \d{4}-\d{2}-\d{2}/.test(msg))
2002
+ return "A single day's chunk timed out. Re-run; the export is idempotent. If it persists, narrow --from-date/--to-date to skip the failing day.";
2003
+ if (/Empty time window/i.test(msg) || /Invalid Date/.test(msg))
2004
+ return "Verify --from-date and --to-date are valid ISO 8601 (e.g. '2026-01-01' or '2026-01-01T14:30:00Z').";
2005
+ if (/Invalid --status/.test(msg))
2006
+ return "Use --status Success or --status Failure (case-insensitive).";
2007
+ if (/Invalid --file-format/.test(msg))
2008
+ return "Use --file-format json (default) or --file-format csv.";
2009
+ if (/unsafe name|outside the output folder/i.test(msg))
2010
+ 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.";
2011
+ if (verb === "sources")
2012
+ return "Confirm scope (org vs tenant) matches your intent and that you are logged in.";
2013
+ if (verb === "events")
2014
+ return "Discover GUIDs via 'audit <scope> sources --output json' before passing --source/--target/--type. Verify --from-date/--to-date are ISO 8601.";
2015
+ return "Verify --from-date/--to-date are ISO 8601 and the --output-path directory is writable. Single-day chunk failures are transient — re-run.";
2016
+ }
2017
+ function registerScopeCommands(parent, opts) {
2018
+ registerSources(parent, opts);
2019
+ registerEvents(parent, opts);
2020
+ registerExport(parent, opts);
2021
+ }
2022
+ function sourcesExamples({
2023
+ scope,
2024
+ codeSuffix
2025
+ }) {
2026
+ return [
2027
+ {
2028
+ Description: `List audit event sources visible at the ${scope} scope`,
2029
+ Command: `uip admin audit ${scope} sources`,
2030
+ Output: {
2031
+ Code: `Audit${codeSuffix}Sources`,
2032
+ Data: [
2033
+ {
2034
+ id: "11111111-1111-1111-1111-111111111111",
2035
+ name: "Identity",
2036
+ eventTargets: []
2037
+ }
2038
+ ]
2039
+ }
2040
+ }
2041
+ ];
2042
+ }
2043
+ function registerSources(parent, opts) {
2044
+ const { scope, codeSuffix } = opts;
2045
+ const cmd = parent.command("sources").description([
2046
+ `List audit event sources visible at the ${scope} scope.`,
2047
+ "",
2048
+ "Each source is a top-level event category (e.g. Identity, Tenant, Robot).",
2049
+ "Use the returned `id` values with `events --source <guid>` to filter."
2050
+ ].join(`
2051
+ `)).option("--login-validity <minutes>", "Override the interactive-login token lifetime for this call. Rarely needed.", (v) => Number.parseInt(v, 10));
2052
+ if (scope === "tenant") {
2053
+ cmd.option("--tenant-id <guid>", "Override the tenant ID from login context.");
2054
+ }
2055
+ cmd.examples(sourcesExamples(opts)).trackedAction(processContext, async (options) => {
2056
+ const [error, result] = await catchError((async () => {
2057
+ const api = await createApiClient(QueryApi, {
2058
+ scope,
2059
+ tenantId: options.tenantId,
2060
+ loginValidity: options.loginValidity
2061
+ });
2062
+ return await api.queryGetAuditEventSources();
2063
+ })());
2064
+ if (error) {
2065
+ OutputFormatter.error({
2066
+ Result: RESULTS.Failure,
2067
+ Message: await extractErrorMessage(error),
2068
+ Instructions: instructionsFor("sources", error)
2069
+ });
2070
+ processContext.exit(1);
2071
+ return;
2072
+ }
2073
+ OutputFormatter.success({
2074
+ Result: RESULTS.Success,
2075
+ Code: `Audit${codeSuffix}Sources`,
2076
+ Data: result ?? []
2077
+ });
2078
+ });
2079
+ }
2080
+ function parseStatus(raw) {
2081
+ if (raw === undefined)
2082
+ return;
2083
+ const normalized = raw.trim().toLowerCase();
2084
+ if (normalized === "success" || normalized === "0")
2085
+ return AuditEventStatus.NUMBER_0;
2086
+ if (normalized === "failure" || normalized === "1")
2087
+ return AuditEventStatus.NUMBER_1;
2088
+ throw new Error(`Invalid --status '${raw}'. Use 'Success' or 'Failure'.`);
2089
+ }
2090
+ function cursorToArgs(cursor) {
2091
+ const url = new URL(cursor, "https://placeholder.invalid");
2092
+ const out = {};
2093
+ const before = url.searchParams.get("before");
2094
+ const beforeId = url.searchParams.get("beforeId");
2095
+ const after = url.searchParams.get("after");
2096
+ const afterId = url.searchParams.get("afterId");
2097
+ if (before)
2098
+ out.before = new Date(before);
2099
+ if (beforeId)
2100
+ out.beforeId = beforeId;
2101
+ if (after)
2102
+ out.after = new Date(after);
2103
+ if (afterId)
2104
+ out.afterId = afterId;
2105
+ return out;
2106
+ }
2107
+ async function paginateEvents(api, baseArgs, limit) {
2108
+ const collected = [];
2109
+ let cursor;
2110
+ let lastPrevious = null;
2111
+ let lastNext = null;
2112
+ while (collected.length < limit) {
2113
+ const remaining = limit - collected.length;
2114
+ const args = {
2115
+ ...baseArgs,
2116
+ maxCount: Math.min(remaining, SERVER_MAX_PAGE),
2117
+ ...cursor ? cursorToArgs(cursor) : {}
2118
+ };
2119
+ const result = await api.queryGetAuditEvents(args);
2120
+ const batch = result.auditEvents ?? [];
2121
+ collected.push(...batch);
2122
+ lastPrevious = result.previous ?? null;
2123
+ lastNext = result.next ?? null;
2124
+ const nextCursor = lastPrevious ?? lastNext;
2125
+ if (!nextCursor || batch.length === 0)
2126
+ break;
2127
+ cursor = nextCursor;
2128
+ }
2129
+ return {
2130
+ auditEvents: collected.slice(0, limit),
2131
+ next: lastNext,
2132
+ previous: lastPrevious
2133
+ };
2134
+ }
2135
+ function eventsExamples({
2136
+ scope,
2137
+ codeSuffix
2138
+ }) {
2139
+ return [
2140
+ {
2141
+ Description: `Fetch the latest 50 ${scope} audit events`,
2142
+ Command: `uip admin audit ${scope} events --limit 50`,
2143
+ Output: {
2144
+ Code: `Audit${codeSuffix}Events`,
2145
+ Data: {
2146
+ auditEvents: [],
2147
+ next: null,
2148
+ previous: null
2149
+ }
2150
+ }
2151
+ },
2152
+ {
2153
+ Description: `Filter by source and a 7-day window`,
2154
+ Command: `uip admin audit ${scope} events --source 11111111-1111-1111-1111-111111111111 --from-date 2026-04-22T00:00:00Z --to-date 2026-04-29T00:00:00Z`,
2155
+ Output: {
2156
+ Code: `Audit${codeSuffix}Events`,
2157
+ Data: {
2158
+ auditEvents: [],
2159
+ next: null,
2160
+ previous: null
2161
+ }
2162
+ }
2163
+ }
2164
+ ];
2165
+ }
2166
+ function registerEvents(parent, opts) {
2167
+ const { scope, codeSuffix } = opts;
2168
+ const cmd = parent.command("events").description([
2169
+ `Query audit events at the ${scope} scope.`,
2170
+ "",
2171
+ "Returns `{ auditEvents, next, previous }` — NOT a bare array. Pagination cursors live alongside the rows.",
2172
+ "Cursor naming is chronological: `next` = newer events, `previous` = older events.",
2173
+ "When --limit > 200 the tool paginates internally by following `previous` (server clamps each call to 200)."
2174
+ ].join(`
2175
+ `)).option("--from-date <iso>", "Start of time interval (ISO 8601). Inclusive.").option("--to-date <iso>", "End of time interval (ISO 8601). Inclusive.").option("--source <guid...>", "Filter by event source IDs. Repeatable. Use `sources` to discover IDs.").option("--target <guid...>", "Filter by event target IDs. Repeatable.").option("--type <guid...>", "Filter by event type IDs. Repeatable.").option("--user-id <guid...>", "Filter by acting user IDs. Repeatable.").option("--search <term>", "Server-side substring search.").option("--status <status>", "Event status filter: 'Success' or 'Failure' (case-insensitive).").option("--limit <n>", "Total number of events to return. The server clamps each individual call to 200; values >200 are paginated client-side. Must be a positive integer between 1 and 10000.", parseLimit).option("--login-validity <minutes>", "Override the interactive-login token lifetime for this call. Rarely needed.", (v) => Number.parseInt(v, 10));
2176
+ if (scope === "tenant") {
2177
+ cmd.option("--tenant-id <guid>", "Override the tenant ID from login context.");
2178
+ }
2179
+ cmd.examples(eventsExamples(opts)).trackedAction(processContext, async (options) => {
2180
+ const [error, result] = await catchError((async () => {
2181
+ const status = parseStatus(options.status);
2182
+ const api = await createApiClient(QueryApi, {
2183
+ scope,
2184
+ tenantId: options.tenantId,
2185
+ loginValidity: options.loginValidity
2186
+ });
2187
+ const baseArgs = {
2188
+ from: options.fromDate ? new Date(options.fromDate) : undefined,
2189
+ to: options.toDate ? new Date(options.toDate) : undefined,
2190
+ source: options.source,
2191
+ target: options.target,
2192
+ type: options.type,
2193
+ userIds: options.userId,
2194
+ searchTerm: options.search,
2195
+ status
2196
+ };
2197
+ const limit = options.limit;
2198
+ if (limit !== undefined && limit > SERVER_MAX_PAGE) {
2199
+ return await paginateEvents(api, baseArgs, limit);
2200
+ }
2201
+ const single = await api.queryGetAuditEvents({
2202
+ ...baseArgs,
2203
+ maxCount: limit
2204
+ });
2205
+ return {
2206
+ auditEvents: single.auditEvents ?? [],
2207
+ next: single.next ?? null,
2208
+ previous: single.previous ?? null
2209
+ };
2210
+ })());
2211
+ if (error) {
2212
+ OutputFormatter.error({
2213
+ Result: RESULTS.Failure,
2214
+ Message: await extractErrorMessage(error),
2215
+ Instructions: instructionsFor("events", error)
2216
+ });
2217
+ processContext.exit(1);
2218
+ return;
2219
+ }
2220
+ OutputFormatter.success({
2221
+ Result: RESULTS.Success,
2222
+ Code: `Audit${codeSuffix}Events`,
2223
+ Data: result
2224
+ });
2225
+ });
2226
+ }
2227
+ function parseFormat(raw) {
2228
+ const normalized = (raw ?? "json").trim().toLowerCase();
2229
+ if (normalized === "json" || normalized === "csv")
2230
+ return normalized;
2231
+ throw new Error(`Invalid --file-format '${raw}'. Use 'json' or 'csv'.`);
2232
+ }
2233
+ function exportExamples({
2234
+ scope,
2235
+ codeSuffix
2236
+ }) {
2237
+ return [
2238
+ {
2239
+ Description: `Export ${scope} audit events for January 2026 — a timestamped folder of day-wise JSON files is created under the base dir`,
2240
+ Command: `uip admin audit ${scope} export --from-date 2026-01-01 --to-date 2026-02-01 --output-path ./audit-exports`,
2241
+ Output: {
2242
+ Code: `Audit${codeSuffix}Export`,
2243
+ Data: {
2244
+ Path: `./audit-exports/audit_2026-01-01_2026-02-01_20260617T112630`,
2245
+ Format: "json",
2246
+ Files: 27,
2247
+ Bytes: 12345,
2248
+ Days: 31,
2249
+ NonEmptyDays: 27,
2250
+ GeneratedAt: "2026-06-17T11:26:30.000Z"
2251
+ }
2252
+ }
2253
+ },
2254
+ {
2255
+ Description: `Export the same window into a single merged CSV (a uniquely-named .csv under the base dir) instead of a folder`,
2256
+ Command: `uip admin audit ${scope} export --from-date 2026-01-01 --to-date 2026-02-01 --file-format csv --output-path ./audit-exports`,
2257
+ Output: {
2258
+ Code: `Audit${codeSuffix}Export`,
2259
+ Data: {
2260
+ Path: `./audit-exports/audit_2026-01-01_2026-02-01_20260617T112630.csv`,
2261
+ Format: "csv",
2262
+ Bytes: 98765,
2263
+ Days: 31,
2264
+ NonEmptyDays: 27,
2265
+ Events: 1234,
2266
+ GeneratedAt: "2026-06-17T11:26:30.000Z"
2267
+ }
2268
+ }
2269
+ }
2270
+ ];
2271
+ }
2272
+ function registerExport(parent, opts) {
2273
+ const { scope, codeSuffix } = opts;
2274
+ const cmd = parent.command("export").description([
2275
+ `Export audit events from the long-term store at the ${scope} scope.`,
2276
+ "",
2277
+ "Issues one HTTP call per UTC day inside [--from-date, --to-date] and aggregates the daily",
2278
+ "responses in memory before writing them out. The full window is fetched first: on any chunk",
2279
+ "failure the export is aborted atomically — nothing is written, and the structured Failure",
2280
+ "result identifies the day that failed.",
2281
+ "",
2282
+ "--output-path is a base DIRECTORY, not a file path — pass a folder and the CLI",
2283
+ "generates the per-export name for you (you do NOT supply a filename). Each run creates",
2284
+ "a uniquely-named output inside it, stamped with the window + generation time",
2285
+ "(e.g. audit_2026-01-01_2026-02-01_20260617T112630), so repeated exports of the same",
2286
+ "window never collide. --file-format controls the shape:",
2287
+ " json (default) — a folder of one JSON file per UTC day.",
2288
+ " csv — a single CSV file with every event merged under a shared header."
2289
+ ].join(`
2290
+ `)).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));
2291
+ if (scope === "tenant") {
2292
+ cmd.option("--tenant-id <guid>", "Override the tenant ID from login context.");
2293
+ }
2294
+ cmd.examples(exportExamples(opts)).trackedAction(processContext, async (options) => {
2295
+ const [error, summary] = await catchError((async () => {
2296
+ const format = parseFormat(options.fileFormat);
2297
+ const outputPath = options.outputPath ?? options.outputFile;
2298
+ if (outputPath === undefined) {
2299
+ throw new Error("Missing required option '--output-path <dir>'.");
2300
+ }
2301
+ if (options.outputFile !== undefined) {
2302
+ 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.");
2303
+ }
2304
+ const api = await createApiClient(QueryApi, {
2305
+ scope,
2306
+ tenantId: options.tenantId,
2307
+ loginValidity: options.loginValidity
2308
+ });
2309
+ const from = new Date(options.fromDate);
2310
+ const to = new Date(options.toDate);
2311
+ const fs = getFileSystem();
2312
+ const generatedAt = new Date;
2313
+ const baseDir = fs.path.resolve(outputPath);
2314
+ const baseName = exportBaseName(from, to, generatedAt);
2315
+ if (format === "csv") {
2316
+ const result2 = await downloadChunkedCsvExport(api, from, to);
2317
+ await fs.mkdir(baseDir);
2318
+ const target = fs.path.join(baseDir, `${baseName}.csv`);
2319
+ await fs.writeFile(target, result2.buffer);
2320
+ return {
2321
+ Path: target,
2322
+ Format: "csv",
2323
+ Bytes: result2.buffer.byteLength,
2324
+ Days: result2.days,
2325
+ NonEmptyDays: result2.nonEmptyDays,
2326
+ Events: result2.eventCount,
2327
+ GeneratedAt: generatedAt.toISOString()
2328
+ };
2329
+ }
2330
+ const result = await downloadChunkedJsonExport(api, from, to);
2331
+ const outDir = fs.path.join(baseDir, baseName);
2332
+ const targets = result.files.map((file) => {
2333
+ if (!isSafeExportEntryName(file.name)) {
2334
+ throw new Error(`Export contained a file with an unsafe name '${file.name}'.`);
2335
+ }
2336
+ const target = fs.path.join(outDir, file.name);
2337
+ if (!isWithinDir(outDir, fs.path.resolve(target))) {
2338
+ throw new Error(`Export file '${file.name}' resolves outside the output folder.`);
2339
+ }
2340
+ return { target, data: file.data };
2341
+ });
2342
+ await fs.mkdir(outDir);
2343
+ let bytes = 0;
2344
+ for (const { target, data } of targets) {
2345
+ await fs.writeFile(target, data);
2346
+ bytes += data.byteLength;
2347
+ }
2348
+ return {
2349
+ Path: outDir,
2350
+ Format: "json",
2351
+ Files: result.files.length,
2352
+ Bytes: bytes,
2353
+ Days: result.days,
2354
+ NonEmptyDays: result.nonEmptyDays,
2355
+ GeneratedAt: generatedAt.toISOString()
2356
+ };
2357
+ })());
2358
+ if (error) {
2359
+ OutputFormatter.error({
2360
+ Result: RESULTS.Failure,
2361
+ Message: await extractErrorMessage(error),
2362
+ Instructions: instructionsFor("export", error)
2363
+ });
2364
+ processContext.exit(1);
2365
+ return;
2366
+ }
2367
+ OutputFormatter.success({
2368
+ Result: RESULTS.Success,
2369
+ Code: `Audit${codeSuffix}Export`,
2370
+ Data: summary
2371
+ });
2372
+ });
2373
+ }
2374
+
2375
+ // ../audit-commands/src/commands/audit.ts
2376
+ var registerAuditCommand = (program) => {
2377
+ const audit = program.command("audit").description([
2378
+ "Query and export UiPath audit events, and configure which events are recorded.",
2379
+ "",
2380
+ "Subject subgroups:",
2381
+ " org — organization-scoped audit (admin events that are tenant-agnostic).",
2382
+ " tenant — tenant-scoped audit (events scoped to the active or --tenant-id-overridden tenant).",
2383
+ "",
2384
+ "Read verbs (the same three under each subject):",
2385
+ " sources — list event sources/targets/types visible at this scope.",
2386
+ " events — paginated query of audit events with cursor and filters.",
2387
+ " 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).",
2388
+ "",
2389
+ "Configuration (org only):",
2390
+ " exclusions — CRUD over the exclusion rules that stop matching events being recorded at all.",
2391
+ "",
2392
+ "Typical workflow: `audit <scope> sources` (discover IDs) → `audit <scope> events --source <guid>",
2393
+ "--from-date … --to-date …` (find the rows) → `audit <scope> export --from-date … --to-date … --output-path …`."
2394
+ ].join(`
2395
+ `));
2396
+ const org = audit.command("org").description("Organization-scoped audit operations.");
2397
+ registerScopeCommands(org, { scope: "org", codeSuffix: "Org" });
2398
+ registerExclusionCommands(org);
2399
+ const tenant = audit.command("tenant").description("Tenant-scoped audit operations.");
2400
+ registerScopeCommands(tenant, { scope: "tenant", codeSuffix: "Tenant" });
2401
+ };
2402
+
2403
+ // ../audit-commands/src/index.ts
2404
+ var registerCommands = async (program) => {
2405
+ registerAuditCommand(program);
2406
+ };
2407
+ export {
2408
+ registerCommands
2409
+ };
2410
+
2411
+ //# debugId=FA243E6A665F869364756E2164756E21