@revoengine/cli 1.0.10 → 1.0.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/README.md +314 -239
  2. package/dist/src/cli.js +126 -9
  3. package/dist/src/client.d.ts +373 -6
  4. package/dist/src/client.js +1005 -53
  5. package/dist/src/commands/auth.js +4 -2
  6. package/dist/src/commands/component.d.ts +67 -0
  7. package/dist/src/commands/component.js +555 -164
  8. package/dist/src/commands/database-tables.d.ts +2 -0
  9. package/dist/src/commands/database-tables.js +169 -0
  10. package/dist/src/commands/database-views.d.ts +2 -0
  11. package/dist/src/commands/database-views.js +126 -0
  12. package/dist/src/commands/endpoints.js +124 -0
  13. package/dist/src/commands/env.js +44 -24
  14. package/dist/src/commands/events.d.ts +2 -0
  15. package/dist/src/commands/events.js +144 -0
  16. package/dist/src/commands/groups.d.ts +2 -0
  17. package/dist/src/commands/groups.js +160 -0
  18. package/dist/src/commands/index.d.ts +9 -0
  19. package/dist/src/commands/index.js +9 -0
  20. package/dist/src/commands/job-templates.d.ts +2 -0
  21. package/dist/src/commands/job-templates.js +107 -0
  22. package/dist/src/commands/metadata.js +75 -10
  23. package/dist/src/commands/migrate.d.ts +6 -0
  24. package/dist/src/commands/migrate.js +658 -0
  25. package/dist/src/commands/project.js +10 -3
  26. package/dist/src/commands/role-groups.d.ts +2 -0
  27. package/dist/src/commands/role-groups.js +141 -0
  28. package/dist/src/commands/schedules.d.ts +2 -0
  29. package/dist/src/commands/schedules.js +140 -0
  30. package/dist/src/commands/terminal-browser.d.ts +16 -0
  31. package/dist/src/commands/terminal-browser.js +92 -0
  32. package/dist/src/commands/terminal-image.d.ts +7 -0
  33. package/dist/src/commands/terminal-image.js +40 -0
  34. package/dist/src/commands/terminal-patch-worker.d.ts +1 -0
  35. package/dist/src/commands/terminal-patch-worker.js +24 -0
  36. package/dist/src/commands/terminal-patch.d.ts +2 -0
  37. package/dist/src/commands/terminal-patch.js +156 -0
  38. package/dist/src/commands/terminal-sandbox.d.ts +8 -0
  39. package/dist/src/commands/terminal-sandbox.js +87 -0
  40. package/dist/src/commands/terminal-service.d.ts +38 -0
  41. package/dist/src/commands/terminal-service.js +210 -0
  42. package/dist/src/commands/terminal.d.ts +49 -0
  43. package/dist/src/commands/terminal.js +826 -0
  44. package/dist/src/component-lock.d.ts +111 -3
  45. package/dist/src/component-lock.js +363 -15
  46. package/dist/src/config.d.ts +10 -2
  47. package/dist/src/config.js +49 -14
  48. package/dist/src/database-table-artifacts.d.ts +7 -0
  49. package/dist/src/database-table-artifacts.js +8 -0
  50. package/dist/src/diff-details.d.ts +8 -0
  51. package/dist/src/diff-details.js +152 -0
  52. package/dist/src/env-sync.d.ts +0 -3
  53. package/dist/src/env-sync.js +11 -25
  54. package/dist/src/http-trace.d.ts +94 -0
  55. package/dist/src/http-trace.js +226 -0
  56. package/dist/src/metadata-backfill.d.ts +18 -7
  57. package/dist/src/metadata-backfill.js +1002 -27
  58. package/dist/src/migration.d.ts +141 -0
  59. package/dist/src/migration.js +1632 -0
  60. package/dist/src/project.d.ts +2 -0
  61. package/dist/src/project.js +4 -17
  62. package/dist/src/prompt.js +10 -18
  63. package/dist/src/resource-inventory.d.ts +28 -0
  64. package/dist/src/resource-inventory.js +85 -0
  65. package/dist/src/resource-metadata.d.ts +1 -0
  66. package/dist/src/resource-metadata.js +3 -0
  67. package/dist/src/resource-syncs/database-table-sync.d.ts +127 -0
  68. package/dist/src/resource-syncs/database-table-sync.js +2374 -0
  69. package/dist/src/resource-syncs/database-view-sync.d.ts +146 -0
  70. package/dist/src/resource-syncs/database-view-sync.js +1405 -0
  71. package/dist/src/resource-syncs/endpoint-sync.d.ts +123 -0
  72. package/dist/src/resource-syncs/endpoint-sync.js +1563 -0
  73. package/dist/src/resource-syncs/event-sync.d.ts +126 -0
  74. package/dist/src/resource-syncs/event-sync.js +1046 -0
  75. package/dist/src/resource-syncs/group-sync.d.ts +93 -0
  76. package/dist/src/resource-syncs/group-sync.js +928 -0
  77. package/dist/src/resource-syncs/job-template-sync.d.ts +106 -0
  78. package/dist/src/resource-syncs/job-template-sync.js +843 -0
  79. package/dist/src/resource-syncs/role-group-sync.d.ts +90 -0
  80. package/dist/src/resource-syncs/role-group-sync.js +635 -0
  81. package/dist/src/resource-syncs/schedule-sync.d.ts +140 -0
  82. package/dist/src/resource-syncs/schedule-sync.js +1396 -0
  83. package/dist/src/resource-syncs/util.d.ts +22 -0
  84. package/dist/src/resource-syncs/util.js +118 -0
  85. package/dist/src/resource-target.d.ts +11 -0
  86. package/dist/src/resource-target.js +48 -0
  87. package/dist/src/runtime-view.d.ts +1 -0
  88. package/dist/src/runtime-view.js +6 -1
  89. package/dist/src/sync-output.d.ts +66 -0
  90. package/dist/src/sync-output.js +268 -0
  91. package/dist/src/tracked-resources.d.ts +1 -1
  92. package/dist/src/tracked-resources.js +28 -2
  93. package/dist/src/types.d.ts +227 -0
  94. package/dist/src/ui.d.ts +3 -0
  95. package/dist/src/ui.js +76 -18
  96. package/dist/src/utils.d.ts +4 -0
  97. package/dist/src/utils.js +81 -0
  98. package/dist/src/workspace-component.d.ts +2 -0
  99. package/dist/src/workspace-component.js +34 -0
  100. package/dist/src/workspace-diff.d.ts +25 -0
  101. package/dist/src/workspace-diff.js +75 -0
  102. package/dist/src/workspace-resource.d.ts +2 -0
  103. package/dist/src/workspace-resource.js +52 -0
  104. package/package.json +12 -4
@@ -1,31 +1,57 @@
1
+ import { setTimeout as waitForDelay } from 'node:timers/promises';
1
2
  import { AUTH_VALIDATION_TTL_MS, buildAuthValidationKey, DEFAULT_BASE_URL, readAuthValidationState, resolveRuntimeConfig, saveAuthValidationState, } from "./config.js";
3
+ import { beginHttpTraceRequest, completeHttpTraceRequest, responseSize, } from "./http-trace.js";
4
+ import { isInteractiveTerminal, promptConfirm } from "./prompt.js";
2
5
  import { createSpinner } from "./spinner.js";
6
+ import { mapWithConcurrency } from "./utils.js";
3
7
  export class ApiError extends Error {
4
8
  status;
5
9
  data;
6
- constructor(status, message, data) {
10
+ headers;
11
+ constructor(status, message, data, headers) {
7
12
  super(message);
8
13
  this.name = 'ApiError';
9
14
  this.status = status;
10
15
  this.data = data;
16
+ this.headers = headers;
17
+ }
18
+ }
19
+ export class RequestTimeoutError extends Error {
20
+ timeoutMs;
21
+ path;
22
+ constructor(timeoutMs, path) {
23
+ super(`Request timed out after ${timeoutMs} ms for ${path}.`);
24
+ this.name = 'RequestTimeoutError';
25
+ this.timeoutMs = timeoutMs;
26
+ this.path = path;
11
27
  }
12
28
  }
13
29
  export class AuthenticationError extends ApiError {
14
- constructor(status, message, data) {
15
- super(status, message, data);
30
+ constructor(status, message, data, headers) {
31
+ super(status, message, data, headers);
16
32
  this.name = 'AuthenticationError';
17
33
  }
18
34
  }
19
35
  export class PermissionDeniedError extends ApiError {
20
36
  path;
21
- constructor(path, message, data) {
22
- super(403, message, data);
37
+ constructor(path, message, data, headers) {
38
+ super(403, message, data, headers);
23
39
  this.name = 'PermissionDeniedError';
24
40
  this.path = path;
25
41
  }
26
42
  }
27
43
  const REQUEST_DELAY_MS = 50;
28
44
  const COMPONENT_LIST_PAGE_SIZE = 200;
45
+ const DATABASE_SCHEMA_LIST_PAGE_SIZE = 200;
46
+ const DATABASE_SCHEMA_THIN_FIELDS = [
47
+ 'databaseId', 'name', 'category', 'metadata', 'type', 'parent', 'master', 'version',
48
+ 'deletedAt', 'deletedBy',
49
+ ].join(',');
50
+ const DATABASE_SCHEMA_PULL_FIELDS = [
51
+ 'databaseId', 'name', 'category', 'desc', 'metadata', 'type', 'definition', 'partition',
52
+ 'parent', 'master', 'version', 'audit', 'restricted', 'tags',
53
+ 'deletedAt', 'deletedBy',
54
+ ].join(',');
29
55
  const ACTIVE_COMPONENT_LIST_FILTER = {
30
56
  'filter[and][0][field]': 'deletedAt',
31
57
  'filter[and][0][op]': 'isNull',
@@ -33,6 +59,16 @@ const ACTIVE_COMPONENT_LIST_FILTER = {
33
59
  function isRecord(value) {
34
60
  return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
35
61
  }
62
+ function hasDatabaseSchemaParent(database) {
63
+ if (typeof database.parent === 'string') {
64
+ return database.parent.trim().length > 0;
65
+ }
66
+ if (!isRecord(database.parent)) {
67
+ return false;
68
+ }
69
+ return [database.parent.databaseId, database.parent.id, database.parent.name]
70
+ .some((value) => typeof value === 'string' && value.trim().length > 0);
71
+ }
36
72
  function readNumber(value) {
37
73
  return typeof value === 'number' && Number.isFinite(value) ? value : null;
38
74
  }
@@ -48,10 +84,13 @@ function unwrapList(value) {
48
84
  if (Array.isArray(candidate.items)) {
49
85
  return candidate.items;
50
86
  }
87
+ if (Array.isArray(candidate.results)) {
88
+ return candidate.results;
89
+ }
51
90
  }
52
91
  return [];
53
92
  }
54
- function resolveNextComponentListRequest(value) {
93
+ function resolveNextListRequest(value) {
55
94
  if (typeof value === 'string' && value) {
56
95
  return {
57
96
  path: value,
@@ -97,7 +136,7 @@ function withActiveComponentListFilter(request) {
97
136
  },
98
137
  };
99
138
  }
100
- function unwrapComponentListPage(value) {
139
+ function unwrapListPage(value) {
101
140
  const items = unwrapList(value);
102
141
  if (!isRecord(value)) {
103
142
  return {
@@ -112,9 +151,9 @@ function unwrapComponentListPage(value) {
112
151
  ?? readNumber(value.count)
113
152
  ?? (meta ? readNumber(meta.total) ?? readNumber(meta.count) : null)
114
153
  ?? (pagination ? readNumber(pagination.total) ?? readNumber(pagination.count) : null);
115
- const nextRequest = resolveNextComponentListRequest(value.next)
116
- ?? (meta ? resolveNextComponentListRequest(meta.next) : null)
117
- ?? (pagination ? resolveNextComponentListRequest(pagination.next) : null);
154
+ const nextRequest = resolveNextListRequest(value.next)
155
+ ?? (meta ? resolveNextListRequest(meta.next) : null)
156
+ ?? (pagination ? resolveNextListRequest(pagination.next) : null);
118
157
  return {
119
158
  items,
120
159
  total,
@@ -167,12 +206,68 @@ function buildUrl(baseUrl, requestPath, query) {
167
206
  }
168
207
  return url;
169
208
  }
209
+ function isLocalhost(hostname) {
210
+ return hostname === 'localhost';
211
+ }
212
+ function isMatchingFirstPartySandbox(base, target) {
213
+ if (base.hostname === 'app.revo.com' && target.hostname === 'sbx.revoengine.com') {
214
+ return true;
215
+ }
216
+ if (!base.hostname.startsWith('api.')) {
217
+ return false;
218
+ }
219
+ const serviceDomain = base.hostname.slice('api.'.length);
220
+ return (serviceDomain === 'revoengine.com' || serviceDomain.endsWith('.revong.com'))
221
+ && target.hostname === `sbx.${serviceDomain}`;
222
+ }
223
+ function resolveTrustedServiceOrigins(configured) {
224
+ const values = configured ?? (process.env.REVO_TRUSTED_SERVICE_ORIGINS || '').split(',').filter(Boolean);
225
+ return new Set(values.map((value) => {
226
+ const url = new URL(value.trim());
227
+ if (url.username || url.password || url.protocol !== 'https:' || url.pathname !== '/' || url.search || url.hash) {
228
+ throw new Error('REVO_TRUSTED_SERVICE_ORIGINS contains an invalid origin.');
229
+ }
230
+ return url.origin;
231
+ }));
232
+ }
233
+ function assertCredentialDestination(baseUrl, url, allowExternalOrigin = false, trustedServiceOrigins = new Set()) {
234
+ const base = new URL(baseUrl);
235
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) {
236
+ throw new Error('Refusing to send API credentials to an invalid URL.');
237
+ }
238
+ if (url.origin === base.origin) {
239
+ return;
240
+ }
241
+ if (!allowExternalOrigin) {
242
+ throw new Error('Refusing to send API credentials to an external origin.');
243
+ }
244
+ if (url.protocol !== 'https:' && !(isLocalhost(base.hostname) && isLocalhost(url.hostname))) {
245
+ throw new Error('External service endpoints must use HTTPS.');
246
+ }
247
+ if (isLocalhost(base.hostname) && isLocalhost(url.hostname)) {
248
+ return;
249
+ }
250
+ if (!isMatchingFirstPartySandbox(base, url) && !trustedServiceOrigins.has(url.origin)) {
251
+ throw new Error('External service origin is not trusted. Set REVO_TRUSTED_SERVICE_ORIGINS explicitly.');
252
+ }
253
+ }
254
+ function assertNoAuthenticatedRedirect(response) {
255
+ if (response.status >= 300 && response.status < 400 && response.status !== 304) {
256
+ throw new Error('Authenticated request was redirected; refusing to forward API credentials.');
257
+ }
258
+ }
170
259
  function normalizeToken(token) {
171
260
  if (!token) {
172
261
  return '';
173
262
  }
174
263
  return token.startsWith('Bearer ') ? token : `Bearer ${token}`;
175
264
  }
265
+ async function confirmProductionWriteInTerminal(details) {
266
+ if (!isInteractiveTerminal()) {
267
+ return false;
268
+ }
269
+ return promptConfirm(`PRODUCTION: send ${details.method} ${details.path} to ${details.baseUrl}?`, false);
270
+ }
176
271
  function defaultSpinnerLabel(method, path) {
177
272
  const upperMethod = method.toUpperCase();
178
273
  if (path === '/api/v1/me') {
@@ -202,8 +297,8 @@ function toErrorMessage(responseText, status) {
202
297
  const trimmed = responseText.trim();
203
298
  return trimmed ? `${status} ${trimmed}` : `HTTP ${status}`;
204
299
  }
205
- function delay(ms) {
206
- return new Promise((resolve) => setTimeout(resolve, ms));
300
+ function delay(ms, signal) {
301
+ return waitForDelay(ms, undefined, { signal });
207
302
  }
208
303
  async function readResponseData(response) {
209
304
  const text = await response.text();
@@ -316,13 +411,26 @@ export class RevoClient {
316
411
  baseUrl;
317
412
  instance;
318
413
  token;
414
+ production;
415
+ environmentName;
319
416
  fetchImpl;
417
+ productionWriteConfirmed = false;
418
+ confirmProductionWrite;
419
+ trustedServiceOrigins;
420
+ maxRetries;
421
+ retryDelayMs;
320
422
  constructor(options = {}) {
321
423
  const config = resolveRuntimeConfig(options);
322
424
  this.baseUrl = config.baseUrl;
323
425
  this.instance = config.instance || '';
324
426
  this.token = config.token;
427
+ this.production = options.production === true || config.production === true;
428
+ this.environmentName = options.environmentName || options.envName || '';
325
429
  this.fetchImpl = options.fetch || globalThis.fetch;
430
+ this.confirmProductionWrite = options.confirmProductionWrite || confirmProductionWriteInTerminal;
431
+ this.trustedServiceOrigins = resolveTrustedServiceOrigins(options.trustedServiceOrigins);
432
+ this.maxRetries = options.maxRetries ?? 0;
433
+ this.retryDelayMs = options.retryDelayMs ?? 100;
326
434
  }
327
435
  get authHeader() {
328
436
  return normalizeToken(this.token);
@@ -391,10 +499,14 @@ export class RevoClient {
391
499
  }
392
500
  async request(method, path, options = {}) {
393
501
  this.assertReady();
502
+ if (options.productionWrite !== false) {
503
+ await this.assertProductionWriteConfirmed(method, path);
504
+ }
394
505
  if (options.authGuard !== false && path !== '/api/v1/me') {
395
506
  await this.validateSession();
396
507
  }
397
508
  const url = buildUrl(this.baseUrl, path, options.query);
509
+ assertCredentialDestination(this.baseUrl, url, options.allowExternalOrigin, this.trustedServiceOrigins);
398
510
  const headers = new Headers(options.headers || {});
399
511
  headers.set('Authorization', this.authHeader);
400
512
  headers.set('x-api-key', this.token);
@@ -413,47 +525,160 @@ export class RevoClient {
413
525
  const spinner = createSpinner({
414
526
  text: options.spinnerLabel || defaultSpinnerLabel(method, path),
415
527
  });
528
+ const abortController = options.timeoutMs === undefined ? undefined : new AbortController();
529
+ const timeout = abortController
530
+ ? setTimeout(() => abortController.abort(), options.timeoutMs)
531
+ : undefined;
532
+ const traceRequest = beginHttpTraceRequest({
533
+ method,
534
+ url,
535
+ body: body,
536
+ context: this.environmentName ? { environment: this.environmentName } : undefined,
537
+ });
538
+ const maxRetries = options.maxRetries ?? this.maxRetries;
539
+ const baseRetryDelay = options.retryDelayMs ?? this.retryDelayMs;
540
+ const normalizedMethod = method.toUpperCase();
416
541
  spinner.start();
417
542
  try {
418
- await delay(REQUEST_DELAY_MS);
419
- const response = await this.fetchImpl(url, {
420
- method: method.toUpperCase(),
421
- headers,
422
- body: body,
423
- });
424
- const data = await readResponseData(response);
425
- if (!response.ok && response.status !== 304) {
426
- if (response.status === 401) {
427
- saveAuthValidationState({
428
- key: this.authValidationKey,
429
- status: 'not_authenticated',
430
- checkedAt: Date.now(),
543
+ let lastError;
544
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
545
+ if (attempt > 0) {
546
+ const backoff = baseRetryDelay * Math.pow(2, attempt - 1) + Math.floor(Math.random() * 25);
547
+ await delay(backoff, abortController?.signal);
548
+ }
549
+ await delay(REQUEST_DELAY_MS, abortController?.signal);
550
+ let response;
551
+ try {
552
+ response = await this.fetchImpl(url, {
553
+ method: normalizedMethod,
554
+ headers,
555
+ body: body,
556
+ redirect: 'manual',
557
+ ...(abortController ? { signal: abortController.signal } : {}),
558
+ });
559
+ }
560
+ catch (error) {
561
+ lastError = error;
562
+ if (attempt < maxRetries && !abortController?.signal.aborted) {
563
+ continue;
564
+ }
565
+ completeHttpTraceRequest(traceRequest, { ok: false, error });
566
+ throw error;
567
+ }
568
+ try {
569
+ assertNoAuthenticatedRedirect(response);
570
+ }
571
+ catch (error) {
572
+ completeHttpTraceRequest(traceRequest, {
573
+ status: response.status,
574
+ ok: false,
575
+ responseHeaders: response.headers,
576
+ error,
577
+ });
578
+ throw error;
579
+ }
580
+ let data;
581
+ try {
582
+ data = await readResponseData(response);
583
+ }
584
+ catch (error) {
585
+ lastError = error;
586
+ if (attempt < maxRetries && !abortController?.signal.aborted) {
587
+ continue;
588
+ }
589
+ completeHttpTraceRequest(traceRequest, {
590
+ status: response.status,
591
+ ok: false,
592
+ responseHeaders: response.headers,
593
+ error,
431
594
  });
432
- throw new AuthenticationError(401, 'Not authenticated. Run `revo auth login`.', data);
595
+ throw error;
433
596
  }
434
- if (response.status === 403 && path !== '/api/v1/me') {
435
- throw new PermissionDeniedError(path, `Access denied for ${path}.`, data);
597
+ const isRetryableStatus = [429, 502, 503, 504].includes(response.status)
598
+ || (response.status === 500 && ['GET', 'HEAD', 'OPTIONS'].includes(normalizedMethod));
599
+ if (!response.ok && response.status !== 304 && isRetryableStatus && attempt < maxRetries && !abortController?.signal.aborted) {
600
+ let retryAfterMs = 0;
601
+ const retryAfterHeader = response.headers.get('retry-after');
602
+ if (retryAfterHeader) {
603
+ const seconds = Number(retryAfterHeader);
604
+ if (!Number.isNaN(seconds) && seconds > 0) {
605
+ retryAfterMs = seconds * 1000;
606
+ }
607
+ }
608
+ if (retryAfterMs > 0) {
609
+ await delay(Math.min(5000, retryAfterMs), abortController?.signal);
610
+ }
611
+ continue;
436
612
  }
437
- throw new ApiError(response.status, toErrorMessage(typeof data === 'string' ? data : JSON.stringify(data), response.status), data);
613
+ const accepted = response.ok || response.status === 304;
614
+ completeHttpTraceRequest(traceRequest, {
615
+ status: response.status,
616
+ ok: accepted,
617
+ responseHeaders: response.headers,
618
+ responseData: data,
619
+ responseBytes: responseSize(data, response.headers),
620
+ });
621
+ if (!response.ok && response.status !== 304) {
622
+ if (response.status === 401) {
623
+ saveAuthValidationState({
624
+ key: this.authValidationKey,
625
+ status: 'not_authenticated',
626
+ checkedAt: Date.now(),
627
+ });
628
+ throw new AuthenticationError(401, 'Not authenticated. Run `revo auth login`.', data, response.headers);
629
+ }
630
+ if (response.status === 403 && path !== '/api/v1/me') {
631
+ throw new PermissionDeniedError(path, `Access denied for ${path}.`, data, response.headers);
632
+ }
633
+ throw new ApiError(response.status, toErrorMessage(typeof data === 'string' ? data : JSON.stringify(data), response.status), data, response.headers);
634
+ }
635
+ const previous = readAuthValidationState(this.authValidationKey);
636
+ saveAuthValidationState({
637
+ key: this.authValidationKey,
638
+ status: 'authenticated',
639
+ checkedAt: Date.now(),
640
+ profile: previous && previous.key === this.authValidationKey ? previous.profile : undefined,
641
+ });
642
+ return {
643
+ status: response.status,
644
+ ok: response.ok,
645
+ data,
646
+ headers: response.headers,
647
+ };
438
648
  }
439
- const previous = readAuthValidationState(this.authValidationKey);
440
- saveAuthValidationState({
441
- key: this.authValidationKey,
442
- status: 'authenticated',
443
- checkedAt: Date.now(),
444
- profile: previous && previous.key === this.authValidationKey ? previous.profile : undefined,
445
- });
446
- return {
447
- status: response.status,
448
- ok: response.ok,
449
- data,
450
- headers: response.headers,
451
- };
649
+ if (lastError) {
650
+ throw lastError;
651
+ }
652
+ throw new Error(`Request failed after ${maxRetries} retries`);
653
+ }
654
+ catch (error) {
655
+ if (abortController?.signal.aborted && options.timeoutMs !== undefined) {
656
+ throw new RequestTimeoutError(options.timeoutMs, path);
657
+ }
658
+ throw error;
452
659
  }
453
660
  finally {
661
+ if (timeout) {
662
+ clearTimeout(timeout);
663
+ }
454
664
  spinner.stop();
455
665
  }
456
666
  }
667
+ async assertProductionWriteConfirmed(method, path) {
668
+ const normalizedMethod = method.toUpperCase();
669
+ if (!this.production || this.productionWriteConfirmed || !['POST', 'PUT', 'PATCH', 'DELETE'].includes(normalizedMethod)) {
670
+ return;
671
+ }
672
+ const confirmed = await this.confirmProductionWrite({
673
+ baseUrl: this.baseUrl,
674
+ method: normalizedMethod,
675
+ path,
676
+ });
677
+ if (!confirmed) {
678
+ throw new Error('Production write cancelled. Confirm the operation in an interactive terminal.');
679
+ }
680
+ this.productionWriteConfirmed = true;
681
+ }
457
682
  async requestData(method, path, options = {}) {
458
683
  const response = await this.request(method, path, options);
459
684
  return response.data;
@@ -465,24 +690,390 @@ export class RevoClient {
465
690
  }
466
691
  return this.requestData('GET', '/api/v1/me', { authGuard: false });
467
692
  }
468
- async listEndpoints() {
469
- return this.requestData('GET', '/api/v1/endpoints');
693
+ async listEndpoints(options = {}) {
694
+ return this.requestData('GET', options.path || '/api/v1/endpoints', {
695
+ query: options.query,
696
+ });
697
+ }
698
+ async listDatabaseSchemas(options = {}) {
699
+ return this.requestData('GET', options.path || '/api/v1/databases', {
700
+ query: options.query,
701
+ });
702
+ }
703
+ async listAllDatabaseSchemas(options = {}) {
704
+ const databases = [];
705
+ const databaseIds = new Set();
706
+ const seenRequests = new Set();
707
+ const fields = options.projection === 'pull'
708
+ ? DATABASE_SCHEMA_PULL_FIELDS
709
+ : DATABASE_SCHEMA_THIN_FIELDS;
710
+ const filter = JSON.stringify({
711
+ and: [
712
+ { field: 'deletedAt', op: 'isNull' },
713
+ ...(options.skipPartitions ? [{ field: 'parent', op: 'isNull' }] : []),
714
+ ],
715
+ });
716
+ let nextRequest = {
717
+ query: {
718
+ take: DATABASE_SCHEMA_LIST_PAGE_SIZE,
719
+ skip: 0,
720
+ count: true,
721
+ fields,
722
+ sort: JSON.stringify({ databaseId: 'ASC' }),
723
+ filter,
724
+ },
725
+ };
726
+ let discoveredTotal = null;
727
+ while (nextRequest) {
728
+ const requestKey = JSON.stringify(nextRequest);
729
+ if (seenRequests.has(requestKey)) {
730
+ throw new Error('Database-schema list pagination loop detected while listing all databases.');
731
+ }
732
+ seenRequests.add(requestKey);
733
+ const pageValue = await this.listDatabaseSchemas(nextRequest);
734
+ const page = unwrapListPage(pageValue);
735
+ if (page.total !== null && !options.skipPartitions) {
736
+ if (discoveredTotal !== null && discoveredTotal !== page.total) {
737
+ throw new Error('Database-schema inventory changed during offset pagination; retry the command from a stable snapshot.');
738
+ }
739
+ discoveredTotal = page.total;
740
+ }
741
+ for (const item of page.items) {
742
+ if (isRecord(item)) {
743
+ const database = item;
744
+ if (!database.deletedAt && !database.deletedBy && !(options.skipPartitions && hasDatabaseSchemaParent(database))) {
745
+ const databaseId = String(database.databaseId || database.id || '');
746
+ if (!databaseId || databaseIds.has(databaseId)) {
747
+ continue;
748
+ }
749
+ databaseIds.add(databaseId);
750
+ databases.push(database);
751
+ }
752
+ }
753
+ }
754
+ if (page.total !== null && (Number(nextRequest.query?.skip || 0) + page.items.length) >= page.total) {
755
+ nextRequest = null;
756
+ }
757
+ else if (page.nextRequest) {
758
+ nextRequest = {
759
+ ...page.nextRequest,
760
+ query: { ...page.nextRequest.query, fields, sort: JSON.stringify({ databaseId: 'ASC' }), filter },
761
+ };
762
+ }
763
+ else if (nextRequest.query && page.items.length === DATABASE_SCHEMA_LIST_PAGE_SIZE) {
764
+ nextRequest = {
765
+ query: {
766
+ ...nextRequest.query,
767
+ skip: Number(nextRequest.query.skip || 0) + page.items.length,
768
+ count: false,
769
+ },
770
+ };
771
+ }
772
+ else {
773
+ nextRequest = null;
774
+ }
775
+ }
776
+ if (!options.skipPartitions && discoveredTotal !== null && databases.length !== discoveredTotal) {
777
+ throw new Error('Database-schema inventory changed during offset pagination; retry the command from a stable snapshot.');
778
+ }
779
+ return { databases, discoveredTotal };
780
+ }
781
+ async findActiveDatabaseSchemasByField(field, value, path) {
782
+ const databases = [];
783
+ const databaseIds = new Set();
784
+ const filter = JSON.stringify({
785
+ and: [
786
+ { field: 'deletedAt', op: 'isNull' },
787
+ { field, op: 'eq', value, ...(path ? { path } : {}) },
788
+ ],
789
+ });
790
+ let skip = 0;
791
+ let discoveredTotal = null;
792
+ do {
793
+ const page = unwrapListPage(await this.listDatabaseSchemas({
794
+ query: {
795
+ take: DATABASE_SCHEMA_LIST_PAGE_SIZE,
796
+ skip,
797
+ count: true,
798
+ fields: DATABASE_SCHEMA_PULL_FIELDS,
799
+ sort: JSON.stringify({ databaseId: 'ASC' }),
800
+ filter,
801
+ },
802
+ }));
803
+ if (page.total !== null) {
804
+ if (discoveredTotal !== null && discoveredTotal !== page.total) {
805
+ throw new Error('Database-schema filtered inventory changed during offset pagination; retry the command from a stable snapshot.');
806
+ }
807
+ discoveredTotal = page.total;
808
+ }
809
+ for (const item of page.items) {
810
+ if (!isRecord(item) || item.deletedAt || item.deletedBy) {
811
+ continue;
812
+ }
813
+ const database = item;
814
+ const databaseId = String(database.databaseId || database.id || '');
815
+ if (!databaseId || databaseIds.has(databaseId)) {
816
+ continue;
817
+ }
818
+ databaseIds.add(databaseId);
819
+ databases.push(database);
820
+ }
821
+ skip += page.items.length;
822
+ if (page.items.length === 0) {
823
+ break;
824
+ }
825
+ if (discoveredTotal !== null && skip >= discoveredTotal) {
826
+ break;
827
+ }
828
+ if (discoveredTotal === null && page.items.length < DATABASE_SCHEMA_LIST_PAGE_SIZE) {
829
+ break;
830
+ }
831
+ } while (true);
832
+ if (discoveredTotal !== null && databases.length !== discoveredTotal) {
833
+ throw new Error('Database-schema filtered inventory changed during offset pagination; retry the command from a stable snapshot.');
834
+ }
835
+ return databases;
836
+ }
837
+ async getDatabaseSchemaStats() {
838
+ return this.requestData('GET', '/api/v1/databases/stats');
839
+ }
840
+ async getDatabaseSchema(databaseId) {
841
+ return this.requestData('GET', `/api/v1/databases/${encodeURIComponent(databaseId)}`);
842
+ }
843
+ async createDatabaseSchema(body) {
844
+ return this.requestData('POST', '/api/v1/databases', {
845
+ body,
846
+ spinnerLabel: 'Creating database schema',
847
+ });
848
+ }
849
+ async updateDatabaseSchemaMetadata(databaseId, body) {
850
+ return this.requestData('PUT', `/api/v1/databases/${encodeURIComponent(databaseId)}`, {
851
+ body,
852
+ spinnerLabel: 'Updating database schema metadata',
853
+ });
854
+ }
855
+ async updateDatabaseSchema(databaseId, body) {
856
+ return this.requestData('PUT', `/api/v1/databases/${encodeURIComponent(databaseId)}`, {
857
+ body,
858
+ spinnerLabel: 'Updating database schema',
859
+ });
860
+ }
861
+ async deleteDatabaseSchema(databaseId) {
862
+ return this.requestData('DELETE', `/api/v1/databases/${encodeURIComponent(databaseId)}`, {
863
+ spinnerLabel: 'Deleting database schema',
864
+ });
865
+ }
866
+ async listAllDatabaseViews() {
867
+ const views = [];
868
+ const databaseViewIds = new Set();
869
+ let discoveredTotal = null;
870
+ for (let skip = 0;; skip += DATABASE_SCHEMA_LIST_PAGE_SIZE) {
871
+ const page = await this.requestData('GET', '/api/v1/databases/views', {
872
+ query: {
873
+ take: DATABASE_SCHEMA_LIST_PAGE_SIZE,
874
+ skip,
875
+ fields: JSON.stringify(['databaseViewId', 'deletedAt', 'sourceDatabaseIds']),
876
+ sort: JSON.stringify({ databaseViewId: 'ASC' }),
877
+ },
878
+ });
879
+ const items = Array.isArray(page) ? page : Array.isArray(page.data) ? page.data : [];
880
+ for (const item of items) {
881
+ const databaseViewId = String(item.databaseViewId || item.id || '');
882
+ if (!databaseViewId || databaseViewIds.has(databaseViewId)) {
883
+ throw new Error('Database View inventory changed during offset pagination; retry the command from a stable snapshot.');
884
+ }
885
+ databaseViewIds.add(databaseViewId);
886
+ views.push(item);
887
+ }
888
+ const hasExplicitNext = !Array.isArray(page) && typeof page.next === 'boolean';
889
+ const pageTotal = !Array.isArray(page)
890
+ ? typeof page.results === 'number' ? page.results : page.total
891
+ : undefined;
892
+ if (typeof pageTotal === 'number') {
893
+ if (discoveredTotal !== null && discoveredTotal !== pageTotal) {
894
+ throw new Error('Database View inventory changed during offset pagination; retry the command from a stable snapshot.');
895
+ }
896
+ discoveredTotal = pageTotal;
897
+ }
898
+ if (items.length === 0
899
+ || (hasExplicitNext ? page.next !== true : items.length < DATABASE_SCHEMA_LIST_PAGE_SIZE)
900
+ || (typeof pageTotal === 'number' && views.length >= pageTotal)) {
901
+ if (discoveredTotal !== null && views.length !== discoveredTotal) {
902
+ throw new Error('Database View inventory changed during offset pagination; retry the command from a stable snapshot.');
903
+ }
904
+ return views;
905
+ }
906
+ }
907
+ }
908
+ async getDatabaseView(databaseViewId, options = {}) {
909
+ return this.requestData('GET', `/api/v1/databases/views/${encodeURIComponent(databaseViewId)}`, options);
910
+ }
911
+ async listAllDatabaseViewsForSync() {
912
+ const summaries = await this.listAllDatabaseViews();
913
+ const activeSummaries = summaries.filter((view) => !view.deletedAt && !view.deletedBy);
914
+ const seenIds = new Set();
915
+ const uniqueSummaries = activeSummaries.filter((summary) => {
916
+ const databaseViewId = String(summary.databaseViewId || summary.id || '');
917
+ if (!databaseViewId || seenIds.has(databaseViewId)) {
918
+ return false;
919
+ }
920
+ seenIds.add(databaseViewId);
921
+ return true;
922
+ });
923
+ const records = await mapWithConcurrency(uniqueSummaries, async (summary) => {
924
+ const databaseViewId = String(summary.databaseViewId || summary.id || '');
925
+ const response = await this.getDatabaseView(databaseViewId, { maxRetries: 2 });
926
+ if (isRecord(response) && isRecord(response.data)) {
927
+ return response.data;
928
+ }
929
+ return response;
930
+ });
931
+ return records
932
+ .filter((record) => record !== undefined && !record.deletedAt && !record.deletedBy)
933
+ .sort((left, right) => String(left.databaseViewId || left.id || '').localeCompare(String(right.databaseViewId || right.id || '')));
934
+ }
935
+ async previewDatabaseView(body) {
936
+ try {
937
+ return await this.requestData('POST', '/api/v1/databases/views/preview', {
938
+ body,
939
+ productionWrite: false,
940
+ spinnerLabel: 'Previewing Database View',
941
+ timeoutMs: 30_000,
942
+ });
943
+ }
944
+ catch (error) {
945
+ const status = error instanceof ApiError ? `HTTP ${error.status}` : 'no HTTP status';
946
+ const timeout = error instanceof RequestTimeoutError ? `timeout after ${error.timeoutMs} ms` : 'timeout: no';
947
+ let message = error instanceof Error ? error.message : String(error);
948
+ if (error instanceof ApiError) {
949
+ message = error instanceof AuthenticationError || error instanceof PermissionDeniedError ? error.message : 'Request failed.';
950
+ const data = error.data;
951
+ const backendMessage = typeof data === 'string' ? data
952
+ : data && typeof data === 'object' && 'message' in data ? data.message : undefined;
953
+ if (typeof backendMessage === 'string') {
954
+ message = backendMessage;
955
+ }
956
+ else if (Array.isArray(backendMessage) && backendMessage.every((part) => typeof part === 'string')) {
957
+ message = backendMessage.join('; ');
958
+ }
959
+ }
960
+ // Only expose the explanatory message, not arbitrary response data or headers.
961
+ message = message.replace(/[\u0000-\u001f\u007f]/g, ' ').slice(0, 2000);
962
+ const rawSqlHint = body.definitionMode === 'RAW_SQL'
963
+ ? ' Check whether RAW SQL Database Views are enabled for this instance.'
964
+ : '';
965
+ const detail = `${body.definitionMode}; ${status}; ${timeout}: ${message}${rawSqlHint}`;
966
+ if (error instanceof Error) {
967
+ error.message = detail;
968
+ throw error;
969
+ }
970
+ throw new Error(detail, { cause: error });
971
+ }
972
+ }
973
+ async createDatabaseView(body) {
974
+ return this.requestData('POST', '/api/v1/databases/views', {
975
+ body,
976
+ spinnerLabel: 'Creating Database View',
977
+ });
978
+ }
979
+ async updateDatabaseView(databaseViewId, body) {
980
+ return this.requestData('PUT', `/api/v1/databases/views/${encodeURIComponent(databaseViewId)}`, {
981
+ body,
982
+ spinnerLabel: 'Updating Database View',
983
+ });
984
+ }
985
+ async listAllEndpoints() {
986
+ const endpoints = [];
987
+ const seenRequests = new Set();
988
+ let nextRequest = {
989
+ query: { take: COMPONENT_LIST_PAGE_SIZE, skip: 0, count: true },
990
+ };
991
+ let discoveredTotal = null;
992
+ while (nextRequest) {
993
+ const requestKey = JSON.stringify(nextRequest);
994
+ if (seenRequests.has(requestKey)) {
995
+ throw new Error('Endpoint list pagination loop detected while listing all endpoints.');
996
+ }
997
+ seenRequests.add(requestKey);
998
+ const pageValue = await this.listEndpoints(nextRequest);
999
+ const page = unwrapListPage(pageValue);
1000
+ if (page.total !== null) {
1001
+ discoveredTotal = page.total;
1002
+ }
1003
+ for (const item of page.items) {
1004
+ if (isRecord(item)) {
1005
+ endpoints.push(item);
1006
+ }
1007
+ }
1008
+ if (page.total !== null && endpoints.length >= page.total) {
1009
+ nextRequest = null;
1010
+ }
1011
+ else if (page.nextRequest) {
1012
+ nextRequest = page.nextRequest;
1013
+ }
1014
+ else if (nextRequest.query && typeof nextRequest.query.take === 'number' && page.items.length === nextRequest.query.take) {
1015
+ nextRequest = {
1016
+ query: { take: nextRequest.query.take, skip: endpoints.length, count: true },
1017
+ };
1018
+ }
1019
+ else {
1020
+ nextRequest = null;
1021
+ }
1022
+ }
1023
+ return { endpoints, discoveredTotal };
1024
+ }
1025
+ async getEndpoint(endpointId, options = {}) {
1026
+ return this.requestData('GET', `/api/v1/endpoints/${encodeURIComponent(endpointId)}`, options);
1027
+ }
1028
+ async createEndpoint(body) {
1029
+ return this.requestData('POST', '/api/v1/endpoints', {
1030
+ body,
1031
+ spinnerLabel: 'Creating endpoint',
1032
+ });
1033
+ }
1034
+ async updateEndpoint(endpointId, body) {
1035
+ return this.requestData('PUT', `/api/v1/endpoints/${encodeURIComponent(endpointId)}`, {
1036
+ body,
1037
+ spinnerLabel: 'Updating endpoint',
1038
+ });
1039
+ }
1040
+ async activateEndpoint(endpointId) {
1041
+ await this.requestData('POST', `/api/v1/endpoints/${encodeURIComponent(endpointId)}/activate`, {
1042
+ spinnerLabel: 'Activating endpoint',
1043
+ });
1044
+ }
1045
+ async disableEndpoint(endpointId) {
1046
+ await this.requestData('POST', `/api/v1/endpoints/${encodeURIComponent(endpointId)}/disable`, {
1047
+ spinnerLabel: 'Disabling endpoint',
1048
+ });
1049
+ }
1050
+ async restoreEndpoint(endpointId) {
1051
+ await this.requestData('POST', `/api/v1/endpoints/${encodeURIComponent(endpointId)}/restore`, {
1052
+ spinnerLabel: 'Restoring endpoint',
1053
+ });
1054
+ }
1055
+ async getComponentSnapshotVersion(componentId, version) {
1056
+ return this.requestData('GET', `/api/v1/activity/${encodeURIComponent(componentId)}/${encodeURIComponent(String(version))}`, { query: { refType: 'COMPONENTS' } });
470
1057
  }
471
1058
  async getEditorTypes(requestPath = '/v1/editor/types') {
472
1059
  return this.requestData('GET', requestPath, {
473
1060
  spinnerLabel: 'Loading editor types',
1061
+ allowExternalOrigin: true,
474
1062
  });
475
1063
  }
476
1064
  async debugComponent(requestPath, body) {
477
1065
  return this.requestData('POST', requestPath, {
478
1066
  body,
479
1067
  spinnerLabel: 'Debugging component',
1068
+ allowExternalOrigin: true,
480
1069
  });
481
1070
  }
482
1071
  async *debugComponentStream(requestPath, body) {
483
1072
  this.assertReady();
1073
+ await this.assertProductionWriteConfirmed('POST', requestPath);
484
1074
  await this.validateSession();
485
1075
  const url = buildUrl(this.baseUrl, requestPath);
1076
+ assertCredentialDestination(this.baseUrl, url, true, this.trustedServiceOrigins);
486
1077
  const headers = new Headers();
487
1078
  headers.set('Accept', 'text/event-stream');
488
1079
  headers.set('Content-Type', 'application/json');
@@ -492,26 +1083,55 @@ export class RevoClient {
492
1083
  headers.set('instance', this.instance);
493
1084
  headers.set('x-api-instance', this.instance);
494
1085
  }
495
- const response = await this.fetchImpl(url, {
1086
+ const serializedBody = JSON.stringify(body);
1087
+ const traceRequest = beginHttpTraceRequest({
496
1088
  method: 'POST',
497
- headers,
498
- body: JSON.stringify(body),
1089
+ url,
1090
+ body: serializedBody,
1091
+ context: this.environmentName ? { environment: this.environmentName } : undefined,
499
1092
  });
1093
+ let response;
1094
+ try {
1095
+ response = await this.fetchImpl(url, {
1096
+ method: 'POST',
1097
+ headers,
1098
+ body: serializedBody,
1099
+ redirect: 'manual',
1100
+ });
1101
+ assertNoAuthenticatedRedirect(response);
1102
+ }
1103
+ catch (error) {
1104
+ completeHttpTraceRequest(traceRequest, { ok: false, error });
1105
+ throw error;
1106
+ }
500
1107
  if (!response.ok) {
501
1108
  const data = await readResponseData(response);
1109
+ completeHttpTraceRequest(traceRequest, {
1110
+ status: response.status,
1111
+ ok: false,
1112
+ responseHeaders: response.headers,
1113
+ responseData: data,
1114
+ responseBytes: responseSize(data, response.headers),
1115
+ });
502
1116
  if (response.status === 401) {
503
1117
  saveAuthValidationState({
504
1118
  key: this.authValidationKey,
505
1119
  status: 'not_authenticated',
506
1120
  checkedAt: Date.now(),
507
1121
  });
508
- throw new AuthenticationError(401, 'Not authenticated. Run `revo auth login`.', data);
1122
+ throw new AuthenticationError(401, 'Not authenticated. Run `revo auth login`.', data, response.headers);
509
1123
  }
510
1124
  if (response.status === 403) {
511
- throw new PermissionDeniedError(requestPath, `Access denied for ${requestPath}.`, data);
1125
+ throw new PermissionDeniedError(requestPath, `Access denied for ${requestPath}.`, data, response.headers);
512
1126
  }
513
- throw new ApiError(response.status, toErrorMessage(typeof data === 'string' ? data : JSON.stringify(data), response.status), data);
1127
+ throw new ApiError(response.status, toErrorMessage(typeof data === 'string' ? data : JSON.stringify(data), response.status), data, response.headers);
514
1128
  }
1129
+ completeHttpTraceRequest(traceRequest, {
1130
+ status: response.status,
1131
+ ok: true,
1132
+ responseHeaders: response.headers,
1133
+ responseBytes: responseSize(undefined, response.headers),
1134
+ });
515
1135
  for await (const event of readSseEvents(response)) {
516
1136
  yield event;
517
1137
  }
@@ -538,7 +1158,7 @@ export class RevoClient {
538
1158
  }
539
1159
  seenRequests.add(requestKey);
540
1160
  const pageValue = await this.listComponents(nextRequest);
541
- const page = unwrapComponentListPage(pageValue);
1161
+ const page = unwrapListPage(pageValue);
542
1162
  if (page.total !== null) {
543
1163
  discoveredTotal = page.total;
544
1164
  }
@@ -567,8 +1187,8 @@ export class RevoClient {
567
1187
  }
568
1188
  return { components, discoveredTotal };
569
1189
  }
570
- async getComponent(componentId) {
571
- return this.requestData('GET', `/api/v1/component/${componentId}`);
1190
+ async getComponent(componentId, options = {}) {
1191
+ return this.requestData('GET', `/api/v1/component/${componentId}`, options);
572
1192
  }
573
1193
  async createComponent(body) {
574
1194
  return this.requestData('POST', '/api/v1/component', {
@@ -587,6 +1207,338 @@ export class RevoClient {
587
1207
  spinnerLabel: 'Deleting component',
588
1208
  });
589
1209
  }
1210
+ async listRoleGroups(options = {}) {
1211
+ return this.requestData('GET', options.path || '/api/v1/role-groups', {
1212
+ query: options.query,
1213
+ });
1214
+ }
1215
+ async listAllRoleGroups() {
1216
+ const roleGroups = [];
1217
+ const seenRequests = new Set();
1218
+ let nextRequest = {
1219
+ query: { take: COMPONENT_LIST_PAGE_SIZE, skip: 0, count: true },
1220
+ };
1221
+ let discoveredTotal = null;
1222
+ while (nextRequest) {
1223
+ const requestKey = JSON.stringify(nextRequest);
1224
+ if (seenRequests.has(requestKey)) {
1225
+ throw new Error('Role-group list pagination loop detected while listing all role groups.');
1226
+ }
1227
+ seenRequests.add(requestKey);
1228
+ const pageValue = await this.listRoleGroups(nextRequest);
1229
+ const page = unwrapListPage(pageValue);
1230
+ if (page.total !== null) {
1231
+ discoveredTotal = page.total;
1232
+ }
1233
+ for (const item of page.items) {
1234
+ if (isRecord(item)) {
1235
+ roleGroups.push(item);
1236
+ }
1237
+ }
1238
+ if (page.total !== null && roleGroups.length >= page.total) {
1239
+ nextRequest = null;
1240
+ }
1241
+ else if (page.nextRequest) {
1242
+ nextRequest = page.nextRequest;
1243
+ }
1244
+ else if (nextRequest.query && typeof nextRequest.query.take === 'number' && page.items.length === nextRequest.query.take) {
1245
+ nextRequest = { query: { ...nextRequest.query, skip: roleGroups.length } };
1246
+ }
1247
+ else {
1248
+ nextRequest = null;
1249
+ }
1250
+ }
1251
+ return { roleGroups, discoveredTotal };
1252
+ }
1253
+ async getRoleGroup(roleGroupId, options = {}) {
1254
+ return this.requestData('GET', `/api/v1/role-groups/${roleGroupId}`, options);
1255
+ }
1256
+ async listGroups(options = {}) {
1257
+ return this.requestData('GET', options.path || '/api/v1/groups', {
1258
+ query: options.query,
1259
+ });
1260
+ }
1261
+ async listAllGroups() {
1262
+ const groups = [];
1263
+ const seenRequests = new Set();
1264
+ let nextRequest = {
1265
+ query: { take: COMPONENT_LIST_PAGE_SIZE, skip: 0, count: true },
1266
+ };
1267
+ let discoveredTotal = null;
1268
+ while (nextRequest) {
1269
+ const requestKey = JSON.stringify(nextRequest);
1270
+ if (seenRequests.has(requestKey)) {
1271
+ throw new Error('Group list pagination loop detected while listing all groups.');
1272
+ }
1273
+ seenRequests.add(requestKey);
1274
+ const pageValue = await this.listGroups(nextRequest);
1275
+ const page = unwrapListPage(pageValue);
1276
+ if (page.total !== null) {
1277
+ discoveredTotal = page.total;
1278
+ }
1279
+ for (const item of page.items) {
1280
+ if (isRecord(item)) {
1281
+ groups.push(item);
1282
+ }
1283
+ }
1284
+ if (page.total !== null && groups.length >= page.total) {
1285
+ nextRequest = null;
1286
+ }
1287
+ else if (page.nextRequest) {
1288
+ nextRequest = page.nextRequest;
1289
+ }
1290
+ else if (nextRequest.query && typeof nextRequest.query.take === 'number' && page.items.length === nextRequest.query.take) {
1291
+ nextRequest = { query: { ...nextRequest.query, skip: groups.length } };
1292
+ }
1293
+ else {
1294
+ nextRequest = null;
1295
+ }
1296
+ }
1297
+ return { groups, discoveredTotal };
1298
+ }
1299
+ async getGroup(groupId, options = {}) {
1300
+ return this.requestData('GET', `/api/v1/groups/${groupId}`, options);
1301
+ }
1302
+ async listJobTemplates(options = {}) {
1303
+ return this.requestData('GET', options.path || '/api/v1/automation/template', {
1304
+ query: options.query,
1305
+ });
1306
+ }
1307
+ async listAllJobTemplates() {
1308
+ const jobTemplates = [];
1309
+ const seenRequests = new Set();
1310
+ let nextRequest = { query: buildActiveComponentListQuery(0) };
1311
+ let discoveredTotal = null;
1312
+ while (nextRequest) {
1313
+ const requestKey = JSON.stringify(nextRequest);
1314
+ if (seenRequests.has(requestKey)) {
1315
+ throw new Error('Job-template list pagination loop detected while listing all job templates.');
1316
+ }
1317
+ seenRequests.add(requestKey);
1318
+ const pageValue = await this.listJobTemplates(nextRequest);
1319
+ const page = unwrapListPage(pageValue);
1320
+ if (page.total !== null) {
1321
+ discoveredTotal = page.total;
1322
+ }
1323
+ for (const item of page.items) {
1324
+ if (isRecord(item)) {
1325
+ jobTemplates.push(item);
1326
+ }
1327
+ }
1328
+ if (page.total !== null && jobTemplates.length >= page.total) {
1329
+ nextRequest = null;
1330
+ }
1331
+ else if (page.nextRequest) {
1332
+ nextRequest = withActiveComponentListFilter(page.nextRequest);
1333
+ }
1334
+ else if (nextRequest.query && typeof nextRequest.query.take === 'number' && page.items.length === nextRequest.query.take) {
1335
+ nextRequest = { query: buildActiveComponentListQuery(jobTemplates.length, nextRequest.query.take) };
1336
+ }
1337
+ else {
1338
+ nextRequest = null;
1339
+ }
1340
+ }
1341
+ return { jobTemplates, discoveredTotal };
1342
+ }
1343
+ async getJobTemplate(jobTemplateId, options = {}) {
1344
+ return this.requestData('GET', `/api/v1/automation/template/${jobTemplateId}`, options);
1345
+ }
1346
+ async createJobTemplate(body) {
1347
+ return this.requestData('POST', '/api/v1/automation/template', {
1348
+ body,
1349
+ spinnerLabel: 'Creating job template',
1350
+ });
1351
+ }
1352
+ async updateJobTemplate(jobTemplateId, body) {
1353
+ return this.requestData('PUT', `/api/v1/automation/template/${jobTemplateId}`, {
1354
+ body,
1355
+ spinnerLabel: 'Updating job template',
1356
+ });
1357
+ }
1358
+ async listSchedules(options = {}) {
1359
+ return this.requestData('GET', options.path || '/api/v1/automation/schedule', {
1360
+ query: options.query,
1361
+ });
1362
+ }
1363
+ async listAllSchedules() {
1364
+ const schedules = [];
1365
+ const seenRequests = new Set();
1366
+ let nextRequest = { query: buildActiveComponentListQuery(0) };
1367
+ let discoveredTotal = null;
1368
+ while (nextRequest) {
1369
+ const requestKey = JSON.stringify(nextRequest);
1370
+ if (seenRequests.has(requestKey)) {
1371
+ throw new Error('Schedule list pagination loop detected while listing all schedules.');
1372
+ }
1373
+ seenRequests.add(requestKey);
1374
+ const pageValue = await this.listSchedules(nextRequest);
1375
+ const page = unwrapListPage(pageValue);
1376
+ if (page.total !== null) {
1377
+ discoveredTotal = page.total;
1378
+ }
1379
+ for (const item of page.items) {
1380
+ if (isRecord(item)) {
1381
+ schedules.push(item);
1382
+ }
1383
+ }
1384
+ if (page.total !== null && schedules.length >= page.total) {
1385
+ nextRequest = null;
1386
+ }
1387
+ else if (page.nextRequest) {
1388
+ nextRequest = withActiveComponentListFilter(page.nextRequest);
1389
+ }
1390
+ else if (nextRequest.query && typeof nextRequest.query.take === 'number' && page.items.length === nextRequest.query.take) {
1391
+ nextRequest = { query: buildActiveComponentListQuery(schedules.length, nextRequest.query.take) };
1392
+ }
1393
+ else {
1394
+ nextRequest = null;
1395
+ }
1396
+ }
1397
+ return { schedules, discoveredTotal };
1398
+ }
1399
+ async getSchedule(scheduleId, options = {}) {
1400
+ return this.requestData('GET', `/api/v1/automation/schedule/${scheduleId}`, options);
1401
+ }
1402
+ async createSchedule(body) {
1403
+ return this.requestData('POST', '/api/v1/automation/schedule', {
1404
+ body,
1405
+ spinnerLabel: 'Creating schedule',
1406
+ });
1407
+ }
1408
+ async updateSchedule(scheduleId, body) {
1409
+ return this.requestData('PUT', `/api/v1/automation/schedule/${scheduleId}`, {
1410
+ body,
1411
+ spinnerLabel: 'Updating schedule',
1412
+ });
1413
+ }
1414
+ async activateSchedule(scheduleId) {
1415
+ return this.requestData('POST', `/api/v1/automation/schedule/${scheduleId}/activate`, {
1416
+ spinnerLabel: 'Activating schedule',
1417
+ });
1418
+ }
1419
+ async listEvents(options = {}) {
1420
+ return this.requestData('GET', options.path || '/api/v1/automation/event', {
1421
+ query: options.query,
1422
+ });
1423
+ }
1424
+ async listAllEvents({ includeDeleted = false } = {}) {
1425
+ const events = [];
1426
+ const seenRequests = new Set();
1427
+ let nextRequest = {
1428
+ query: includeDeleted
1429
+ ? { take: COMPONENT_LIST_PAGE_SIZE, skip: 0, count: true }
1430
+ : buildActiveComponentListQuery(0),
1431
+ };
1432
+ let discoveredTotal = null;
1433
+ while (nextRequest) {
1434
+ const requestKey = JSON.stringify(nextRequest);
1435
+ if (seenRequests.has(requestKey)) {
1436
+ throw new Error('Event list pagination loop detected while listing all events.');
1437
+ }
1438
+ seenRequests.add(requestKey);
1439
+ const pageValue = await this.listEvents(nextRequest);
1440
+ const page = unwrapListPage(pageValue);
1441
+ if (page.total !== null) {
1442
+ discoveredTotal = page.total;
1443
+ }
1444
+ for (const item of page.items) {
1445
+ if (isRecord(item)) {
1446
+ events.push(item);
1447
+ }
1448
+ }
1449
+ if (page.total !== null && events.length >= page.total) {
1450
+ nextRequest = null;
1451
+ }
1452
+ else if (page.nextRequest) {
1453
+ nextRequest = includeDeleted
1454
+ ? page.nextRequest
1455
+ : withActiveComponentListFilter(page.nextRequest);
1456
+ }
1457
+ else if (nextRequest.query && typeof nextRequest.query.take === 'number' && page.items.length === nextRequest.query.take) {
1458
+ nextRequest = {
1459
+ query: includeDeleted
1460
+ ? { take: nextRequest.query.take, skip: events.length, count: true }
1461
+ : buildActiveComponentListQuery(events.length, nextRequest.query.take),
1462
+ };
1463
+ }
1464
+ else {
1465
+ nextRequest = null;
1466
+ }
1467
+ }
1468
+ return { events, discoveredTotal };
1469
+ }
1470
+ async getEvent(eventId, options = {}) {
1471
+ return this.requestData('GET', `/api/v1/automation/event/${eventId}`, options);
1472
+ }
1473
+ async createEvent(body) {
1474
+ return this.requestData('POST', '/api/v1/automation/event', {
1475
+ body,
1476
+ spinnerLabel: 'Creating event',
1477
+ });
1478
+ }
1479
+ async updateEvent(eventId, body) {
1480
+ return this.requestData('PUT', `/api/v1/automation/event/${eventId}`, {
1481
+ body,
1482
+ spinnerLabel: 'Updating event',
1483
+ });
1484
+ }
1485
+ async activateEvent(eventId) {
1486
+ return this.requestData('POST', `/api/v1/automation/event/${eventId}/activate`, {
1487
+ spinnerLabel: 'Activating event',
1488
+ });
1489
+ }
1490
+ async disableEvent(eventId) {
1491
+ return this.requestData('POST', `/api/v1/automation/event/${eventId}/disable`, {
1492
+ spinnerLabel: 'Disabling event',
1493
+ });
1494
+ }
1495
+ async createRoleGroup(body) {
1496
+ return this.requestData('POST', '/api/v1/role-groups', {
1497
+ body,
1498
+ spinnerLabel: 'Creating role group',
1499
+ });
1500
+ }
1501
+ async updateRoleGroup(roleGroupId, body) {
1502
+ return this.requestData('PUT', `/api/v1/role-groups/${roleGroupId}`, {
1503
+ body,
1504
+ spinnerLabel: 'Updating role group',
1505
+ });
1506
+ }
1507
+ async updateGroup(groupId, body) {
1508
+ return this.requestData('PUT', `/api/v1/groups/${groupId}`, {
1509
+ body,
1510
+ spinnerLabel: 'Updating group',
1511
+ });
1512
+ }
1513
+ async createGroup(body) {
1514
+ return this.requestData('POST', '/api/v1/groups', {
1515
+ body,
1516
+ spinnerLabel: 'Creating group',
1517
+ });
1518
+ }
1519
+ async addRoleGroupRole(roleGroupId, roleKey) {
1520
+ return this.requestData('POST', `/api/v1/role-groups/${roleGroupId}/roleAdd`, {
1521
+ body: { key: roleKey },
1522
+ spinnerLabel: 'Adding role-group role',
1523
+ });
1524
+ }
1525
+ async removeRoleGroupRole(roleGroupId, roleKey) {
1526
+ return this.requestData('POST', `/api/v1/role-groups/${roleGroupId}/roleDelete`, {
1527
+ body: { key: roleKey },
1528
+ spinnerLabel: 'Removing role-group role',
1529
+ });
1530
+ }
1531
+ async deleteRoleGroup(roleGroupId) {
1532
+ return this.request('DELETE', `/api/v1/role-groups/${roleGroupId}`, {
1533
+ spinnerLabel: 'Deleting role group',
1534
+ });
1535
+ }
1536
+ async listSystemRoles() {
1537
+ return this.requestData('GET', '/api/v1/roles');
1538
+ }
1539
+ async listAllSystemRoles() {
1540
+ return unwrapList(await this.listSystemRoles()).filter(isRecord);
1541
+ }
590
1542
  async saveComponentElements(componentId, body) {
591
1543
  return this.request('POST', `/api/v1/component/${componentId}/save`, { body });
592
1544
  }