@redocly/cli 0.0.0-snapshot.1739194003 → 0.0.0-snapshot.1739895544

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 (57) hide show
  1. package/lib/__tests__/commands/push-region.test.js +3 -3
  2. package/lib/__tests__/utils.test.js +1 -0
  3. package/lib/auth/__tests__/device-flow.test.js +62 -0
  4. package/lib/auth/__tests__/oauth-client.test.js +93 -0
  5. package/lib/auth/device-flow.d.ts +26 -0
  6. package/lib/auth/device-flow.js +133 -0
  7. package/lib/auth/oauth-client.d.ts +14 -0
  8. package/lib/auth/oauth-client.js +93 -0
  9. package/lib/commands/auth.d.ts +13 -0
  10. package/lib/commands/auth.js +51 -0
  11. package/lib/commands/push.d.ts +1 -1
  12. package/lib/commands/push.js +4 -4
  13. package/lib/commands/split/index.js +4 -4
  14. package/lib/index.js +126 -15
  15. package/lib/otel.d.ts +10 -0
  16. package/lib/otel.js +47 -0
  17. package/lib/reunite/api/__tests__/domains.test.js +32 -0
  18. package/lib/{cms → reunite}/api/api-client.d.ts +9 -0
  19. package/lib/{cms → reunite}/api/api-client.js +2 -1
  20. package/lib/reunite/api/domains.d.ts +4 -0
  21. package/lib/reunite/api/domains.js +22 -0
  22. package/lib/reunite/commands/__tests__/push.test.d.ts +1 -0
  23. package/lib/reunite/commands/__tests__/utils.test.d.ts +1 -0
  24. package/lib/types.d.ts +4 -4
  25. package/lib/utils/miscellaneous.d.ts +5 -4
  26. package/lib/utils/miscellaneous.js +14 -14
  27. package/package.json +11 -4
  28. package/lib/cms/api/__tests__/domains.test.js +0 -13
  29. package/lib/cms/api/domains.d.ts +0 -1
  30. package/lib/cms/api/domains.js +0 -11
  31. package/lib/commands/login.d.ts +0 -9
  32. package/lib/commands/login.js +0 -23
  33. /package/lib/{cms/api/__tests__/api-keys.test.d.ts → auth/__tests__/device-flow.test.d.ts} +0 -0
  34. /package/lib/{cms/api/__tests__/api.client.test.d.ts → auth/__tests__/oauth-client.test.d.ts} +0 -0
  35. /package/lib/{cms/api/__tests__/domains.test.d.ts → reunite/api/__tests__/api-keys.test.d.ts} +0 -0
  36. /package/lib/{cms → reunite}/api/__tests__/api-keys.test.js +0 -0
  37. /package/lib/{cms/commands/__tests__/push-status.test.d.ts → reunite/api/__tests__/api.client.test.d.ts} +0 -0
  38. /package/lib/{cms → reunite}/api/__tests__/api.client.test.js +0 -0
  39. /package/lib/{cms/commands/__tests__/push.test.d.ts → reunite/api/__tests__/domains.test.d.ts} +0 -0
  40. /package/lib/{cms → reunite}/api/api-keys.d.ts +0 -0
  41. /package/lib/{cms → reunite}/api/api-keys.js +0 -0
  42. /package/lib/{cms → reunite}/api/index.d.ts +0 -0
  43. /package/lib/{cms → reunite}/api/index.js +0 -0
  44. /package/lib/{cms → reunite}/api/types.d.ts +0 -0
  45. /package/lib/{cms → reunite}/api/types.js +0 -0
  46. /package/lib/{cms/commands/__tests__/utils.test.d.ts → reunite/commands/__tests__/push-status.test.d.ts} +0 -0
  47. /package/lib/{cms → reunite}/commands/__tests__/push-status.test.js +0 -0
  48. /package/lib/{cms → reunite}/commands/__tests__/push.test.js +0 -0
  49. /package/lib/{cms → reunite}/commands/__tests__/utils.test.js +0 -0
  50. /package/lib/{cms → reunite}/commands/push-status.d.ts +0 -0
  51. /package/lib/{cms → reunite}/commands/push-status.js +0 -0
  52. /package/lib/{cms → reunite}/commands/push.d.ts +0 -0
  53. /package/lib/{cms → reunite}/commands/push.js +0 -0
  54. /package/lib/{cms → reunite}/commands/utils.d.ts +0 -0
  55. /package/lib/{cms → reunite}/commands/utils.js +0 -0
  56. /package/lib/{cms → reunite}/utils.d.ts +0 -0
  57. /package/lib/{cms → reunite}/utils.js +0 -0
@@ -2,7 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const openapi_core_1 = require("@redocly/openapi-core");
4
4
  const push_1 = require("../../commands/push");
5
- const login_1 = require("../../commands/login");
5
+ const auth_1 = require("../../commands/auth");
6
6
  const config_1 = require("../fixtures/config");
7
7
  const node_stream_1 = require("node:stream");
8
8
  // Mock fs operations
@@ -22,9 +22,9 @@ jest.mock('fs', () => ({
22
22
  openapi_core_1.getMergedConfig.mockImplementation((config) => config);
23
23
  // Mock OpenAPI core
24
24
  jest.mock('@redocly/openapi-core');
25
- jest.mock('../../commands/login');
25
+ jest.mock('../../commands/auth');
26
26
  jest.mock('../../utils/miscellaneous');
27
- const mockPromptClientToken = login_1.promptClientToken;
27
+ const mockPromptClientToken = auth_1.promptClientToken;
28
28
  describe('push-with-region', () => {
29
29
  const redoclyClient = require('@redocly/openapi-core').__redoclyClient;
30
30
  redoclyClient.isAuthorizedWithRedoclyByRegion = jest.fn().mockResolvedValue(false);
@@ -409,6 +409,7 @@ describe('checkIfRulesetExist', () => {
409
409
  async2: {},
410
410
  async3: {},
411
411
  arazzo1: {},
412
+ overlay1: {},
412
413
  };
413
414
  expect(() => (0, miscellaneous_1.checkIfRulesetExist)(rules)).toThrowError('⚠️ No rules were configured. Learn how to configure rules: https://redocly.com/docs/cli/rules/');
414
415
  });
@@ -0,0 +1,62 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const device_flow_1 = require("../device-flow");
4
+ jest.mock('child_process');
5
+ describe('RedoclyOAuthDeviceFlow', () => {
6
+ const mockBaseUrl = 'https://test.redocly.com';
7
+ const mockClientName = 'test-client';
8
+ const mockVersion = '1.0.0';
9
+ let flow;
10
+ beforeEach(() => {
11
+ flow = new device_flow_1.RedoclyOAuthDeviceFlow(mockBaseUrl, mockClientName, mockVersion);
12
+ jest.resetAllMocks();
13
+ });
14
+ describe('verifyToken', () => {
15
+ it('returns true for valid token', async () => {
16
+ jest.spyOn(flow['apiClient'], 'request').mockResolvedValue({
17
+ json: () => Promise.resolve({ user: { id: '123' } }),
18
+ });
19
+ const result = await flow.verifyToken('valid-token');
20
+ expect(result).toBe(true);
21
+ });
22
+ it('returns false for invalid token', async () => {
23
+ jest.spyOn(flow['apiClient'], 'request').mockRejectedValue(new Error('Invalid token'));
24
+ const result = await flow.verifyToken('invalid-token');
25
+ expect(result).toBe(false);
26
+ });
27
+ });
28
+ describe('verifyApiKey', () => {
29
+ it('returns true for valid API key', async () => {
30
+ jest.spyOn(flow['apiClient'], 'request').mockResolvedValue({
31
+ json: () => Promise.resolve({ success: true }),
32
+ });
33
+ const result = await flow.verifyApiKey('valid-key');
34
+ expect(result).toBe(true);
35
+ });
36
+ it('returns false for invalid API key', async () => {
37
+ jest.spyOn(flow['apiClient'], 'request').mockRejectedValue(new Error('Invalid API key'));
38
+ const result = await flow.verifyApiKey('invalid-key');
39
+ expect(result).toBe(false);
40
+ });
41
+ });
42
+ describe('refreshToken', () => {
43
+ it('successfully refreshes token', async () => {
44
+ const mockResponse = {
45
+ access_token: 'new-token',
46
+ refresh_token: 'new-refresh',
47
+ expires_in: 3600,
48
+ };
49
+ jest.spyOn(flow['apiClient'], 'request').mockResolvedValue({
50
+ json: () => Promise.resolve(mockResponse),
51
+ });
52
+ const result = await flow.refreshToken('old-refresh-token');
53
+ expect(result).toEqual(mockResponse);
54
+ });
55
+ it('throws error when refresh fails', async () => {
56
+ jest.spyOn(flow['apiClient'], 'request').mockResolvedValue({
57
+ json: () => Promise.resolve({}),
58
+ });
59
+ await expect(flow.refreshToken('invalid-refresh')).rejects.toThrow('Failed to refresh token');
60
+ });
61
+ });
62
+ });
@@ -0,0 +1,93 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const oauth_client_1 = require("../oauth-client");
4
+ const device_flow_1 = require("../device-flow");
5
+ const fs = require("node:fs");
6
+ const path = require("node:path");
7
+ const os = require("node:os");
8
+ jest.mock('node:fs');
9
+ jest.mock('node:os');
10
+ jest.mock('../device-flow');
11
+ describe('RedoclyOAuthClient', () => {
12
+ const mockClientName = 'test-client';
13
+ const mockVersion = '1.0.0';
14
+ const mockBaseUrl = 'https://test.redocly.com';
15
+ const mockHomeDir = '/mock/home/dir';
16
+ const mockRedoclyDir = path.join(mockHomeDir, '.redocly');
17
+ let client;
18
+ beforeEach(() => {
19
+ jest.resetAllMocks();
20
+ os.homedir.mockReturnValue(mockHomeDir);
21
+ process.env.HOME = mockHomeDir;
22
+ client = new oauth_client_1.RedoclyOAuthClient(mockClientName, mockVersion);
23
+ });
24
+ describe('login', () => {
25
+ it('successfully logs in and saves token', async () => {
26
+ const mockToken = { access_token: 'test-token' };
27
+ const mockDeviceFlow = {
28
+ run: jest.fn().mockResolvedValue(mockToken),
29
+ };
30
+ device_flow_1.RedoclyOAuthDeviceFlow.mockImplementation(() => mockDeviceFlow);
31
+ await client.login(mockBaseUrl);
32
+ expect(mockDeviceFlow.run).toHaveBeenCalled();
33
+ expect(fs.writeFileSync).toHaveBeenCalled();
34
+ });
35
+ it('throws error when login fails', async () => {
36
+ const mockDeviceFlow = {
37
+ run: jest.fn().mockResolvedValue(null),
38
+ };
39
+ device_flow_1.RedoclyOAuthDeviceFlow.mockImplementation(() => mockDeviceFlow);
40
+ await expect(client.login(mockBaseUrl)).rejects.toThrow('Failed to login');
41
+ });
42
+ });
43
+ describe('logout', () => {
44
+ it('removes token file if it exists', async () => {
45
+ fs.existsSync.mockReturnValue(true);
46
+ await client.logout();
47
+ expect(fs.rmSync).toHaveBeenCalledWith(path.join(mockRedoclyDir, 'auth.json'));
48
+ });
49
+ it('silently fails if token file does not exist', async () => {
50
+ fs.existsSync.mockReturnValue(false);
51
+ await expect(client.logout()).resolves.not.toThrow();
52
+ expect(fs.rmSync).not.toHaveBeenCalled();
53
+ });
54
+ });
55
+ describe('isAuthorized', () => {
56
+ it('verifies API key if provided', async () => {
57
+ const mockDeviceFlow = {
58
+ verifyApiKey: jest.fn().mockResolvedValue(true),
59
+ };
60
+ device_flow_1.RedoclyOAuthDeviceFlow.mockImplementation(() => mockDeviceFlow);
61
+ const result = await client.isAuthorized(mockBaseUrl, 'test-api-key');
62
+ expect(result).toBe(true);
63
+ expect(mockDeviceFlow.verifyApiKey).toHaveBeenCalledWith('test-api-key');
64
+ });
65
+ it('verifies access token if no API key provided', async () => {
66
+ const mockToken = { access_token: 'test-token' };
67
+ const mockDeviceFlow = {
68
+ verifyToken: jest.fn().mockResolvedValue(true),
69
+ };
70
+ device_flow_1.RedoclyOAuthDeviceFlow.mockImplementation(() => mockDeviceFlow);
71
+ fs.readFileSync.mockReturnValue(client['cipher'].update(JSON.stringify(mockToken), 'utf8', 'hex') +
72
+ client['cipher'].final('hex'));
73
+ const result = await client.isAuthorized(mockBaseUrl);
74
+ expect(result).toBe(true);
75
+ expect(mockDeviceFlow.verifyToken).toHaveBeenCalledWith('test-token');
76
+ });
77
+ it('returns false if token refresh fails', async () => {
78
+ const mockToken = {
79
+ access_token: 'old-token',
80
+ refresh_token: 'refresh-token',
81
+ };
82
+ const mockDeviceFlow = {
83
+ verifyToken: jest.fn().mockResolvedValue(false),
84
+ refreshToken: jest.fn().mockRejectedValue(new Error('Refresh failed')),
85
+ };
86
+ device_flow_1.RedoclyOAuthDeviceFlow.mockImplementation(() => mockDeviceFlow);
87
+ fs.readFileSync.mockReturnValue(client['cipher'].update(JSON.stringify(mockToken), 'utf8', 'hex') +
88
+ client['cipher'].final('hex'));
89
+ const result = await client.isAuthorized(mockBaseUrl);
90
+ expect(result).toBe(false);
91
+ });
92
+ });
93
+ });
@@ -0,0 +1,26 @@
1
+ export type AuthToken = {
2
+ access_token: string;
3
+ refresh_token?: string;
4
+ token_type?: string;
5
+ expires_in?: number;
6
+ };
7
+ export declare class RedoclyOAuthDeviceFlow {
8
+ private baseUrl;
9
+ private clientName;
10
+ private version;
11
+ private apiClient;
12
+ constructor(baseUrl: string, clientName: string, version: string);
13
+ run(): Promise<AuthToken>;
14
+ private openBrowser;
15
+ verifyToken(accessToken: string): Promise<boolean>;
16
+ verifyApiKey(apiKey: string): Promise<boolean>;
17
+ refreshToken(refreshToken: string): Promise<{
18
+ access_token: any;
19
+ refresh_token: any;
20
+ expires_in: any;
21
+ }>;
22
+ private pollingAccessToken;
23
+ private getAccessToken;
24
+ private getDeviceCode;
25
+ private sendRequest;
26
+ }
@@ -0,0 +1,133 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RedoclyOAuthDeviceFlow = void 0;
4
+ const colorette_1 = require("colorette");
5
+ const childProcess = require("child_process");
6
+ const api_client_1 = require("../reunite/api/api-client");
7
+ class RedoclyOAuthDeviceFlow {
8
+ constructor(baseUrl, clientName, version) {
9
+ this.baseUrl = baseUrl;
10
+ this.clientName = clientName;
11
+ this.version = version;
12
+ this.apiClient = new api_client_1.ReuniteApiClient(this.version, 'login');
13
+ }
14
+ async run() {
15
+ const code = await this.getDeviceCode();
16
+ process.stdout.write('Attempting to automatically open the SSO authorization page in your default browser.\n');
17
+ process.stdout.write('If the browser does not open or you wish to use a different device to authorize this request, open the following URL:\n\n');
18
+ process.stdout.write((0, colorette_1.blue)(code.verificationUri));
19
+ process.stdout.write(`\n\n`);
20
+ process.stdout.write(`Then enter the code:\n\n`);
21
+ process.stdout.write((0, colorette_1.blue)(code.userCode));
22
+ process.stdout.write(`\n\n`);
23
+ this.openBrowser(code.verificationUriComplete);
24
+ const accessToken = await this.pollingAccessToken(code.deviceCode, code.interval, code.expiresIn);
25
+ process.stdout.write((0, colorette_1.green)('✅ Logged in\n\n'));
26
+ return accessToken;
27
+ }
28
+ openBrowser(url) {
29
+ try {
30
+ const cmd = process.platform === 'win32'
31
+ ? `start ${url}`
32
+ : process.platform === 'darwin'
33
+ ? `open ${url}`
34
+ : `xdg-open ${url}`;
35
+ childProcess.execSync(cmd);
36
+ }
37
+ catch {
38
+ // silently fail if browser cannot be opened
39
+ }
40
+ }
41
+ async verifyToken(accessToken) {
42
+ try {
43
+ const response = await this.sendRequest('/session', 'GET', undefined, {
44
+ Cookie: `accessToken=${accessToken};`,
45
+ });
46
+ return !!response.user;
47
+ }
48
+ catch {
49
+ return false;
50
+ }
51
+ }
52
+ async verifyApiKey(apiKey) {
53
+ try {
54
+ const response = await this.sendRequest('/api-keys-verify', 'POST', {
55
+ apiKey,
56
+ });
57
+ return !!response.success;
58
+ }
59
+ catch {
60
+ return false;
61
+ }
62
+ }
63
+ async refreshToken(refreshToken) {
64
+ const response = await this.sendRequest(`/device-rotate-token`, 'POST', {
65
+ grant_type: 'refresh_token',
66
+ client_name: this.clientName,
67
+ refresh_token: refreshToken,
68
+ });
69
+ if (!response.access_token) {
70
+ throw new Error('Failed to refresh token');
71
+ }
72
+ return {
73
+ access_token: response.access_token,
74
+ refresh_token: response.refresh_token,
75
+ expires_in: response.expires_in,
76
+ };
77
+ }
78
+ async pollingAccessToken(deviceCode, interval, expiresIn) {
79
+ return new Promise((resolve, reject) => {
80
+ const intervalId = setInterval(async () => {
81
+ const response = await this.getAccessToken(deviceCode);
82
+ if (response.access_token) {
83
+ clearInterval(intervalId);
84
+ clearTimeout(timeoutId);
85
+ resolve(response);
86
+ }
87
+ if (response.error && response.error !== 'authorization_pending') {
88
+ clearInterval(intervalId);
89
+ clearTimeout(timeoutId);
90
+ reject(response.error_description);
91
+ }
92
+ }, interval * 1000);
93
+ const timeoutId = setTimeout(async () => {
94
+ clearInterval(intervalId);
95
+ clearTimeout(timeoutId);
96
+ reject('Authorization has expired. Please try again.');
97
+ }, expiresIn * 1000);
98
+ });
99
+ }
100
+ async getAccessToken(deviceCode) {
101
+ return await this.sendRequest('/device-token', 'POST', {
102
+ client_name: this.clientName,
103
+ device_code: deviceCode,
104
+ grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
105
+ });
106
+ }
107
+ async getDeviceCode() {
108
+ const { device_code: deviceCode, user_code: userCode, verification_uri: verificationUri, verification_uri_complete: verificationUriComplete, interval = 10, expires_in: expiresIn = 300, } = await this.sendRequest('/device-authorize', 'POST', {
109
+ client_name: this.clientName,
110
+ });
111
+ return {
112
+ deviceCode,
113
+ userCode,
114
+ verificationUri,
115
+ verificationUriComplete,
116
+ interval,
117
+ expiresIn,
118
+ };
119
+ }
120
+ async sendRequest(url, method = 'GET', body = undefined, headers = {}) {
121
+ url = `${this.baseUrl}${url}`;
122
+ const response = await this.apiClient.request(url, {
123
+ body: body ? JSON.stringify(body) : body,
124
+ method,
125
+ headers: { 'Content-Type': 'application/json', ...headers },
126
+ });
127
+ if (response.status === 204) {
128
+ return { success: true };
129
+ }
130
+ return await response.json();
131
+ }
132
+ }
133
+ exports.RedoclyOAuthDeviceFlow = RedoclyOAuthDeviceFlow;
@@ -0,0 +1,14 @@
1
+ export declare class RedoclyOAuthClient {
2
+ private clientName;
3
+ private version;
4
+ private dir;
5
+ private cipher;
6
+ private decipher;
7
+ constructor(clientName: string, version: string);
8
+ login(baseUrl: string): Promise<void>;
9
+ logout(): Promise<void>;
10
+ isAuthorized(baseUrl: string, apiKey?: string): Promise<boolean>;
11
+ private saveToken;
12
+ private readToken;
13
+ private removeToken;
14
+ }
@@ -0,0 +1,93 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RedoclyOAuthClient = void 0;
4
+ const node_os_1 = require("node:os");
5
+ const path = require("node:path");
6
+ const node_fs_1 = require("node:fs");
7
+ const crypto = require("node:crypto");
8
+ const node_buffer_1 = require("node:buffer");
9
+ const device_flow_1 = require("./device-flow");
10
+ const SALT = '4618dbc9-8aed-4e27-aaf0-225f4603e5a4';
11
+ const CRYPTO_ALGORITHM = 'aes-256-cbc';
12
+ class RedoclyOAuthClient {
13
+ constructor(clientName, version) {
14
+ this.clientName = clientName;
15
+ this.version = version;
16
+ this.dir = path.join((0, node_os_1.homedir)(), '.redocly');
17
+ if (!(0, node_fs_1.existsSync)(this.dir)) {
18
+ (0, node_fs_1.mkdirSync)(this.dir);
19
+ }
20
+ const homeDirPath = process.env.HOME;
21
+ const hash = crypto.createHash('sha256');
22
+ hash.update(`${homeDirPath}${SALT}`);
23
+ const hashHex = hash.digest('hex');
24
+ const key = node_buffer_1.Buffer.alloc(32, node_buffer_1.Buffer.from(hashHex).toString('base64')).toString();
25
+ const iv = node_buffer_1.Buffer.alloc(16, node_buffer_1.Buffer.from(process.env.HOME).toString('base64')).toString();
26
+ this.cipher = crypto.createCipheriv(CRYPTO_ALGORITHM, key, iv);
27
+ this.decipher = crypto.createDecipheriv(CRYPTO_ALGORITHM, key, iv);
28
+ }
29
+ async login(baseUrl) {
30
+ const deviceFlow = new device_flow_1.RedoclyOAuthDeviceFlow(baseUrl, this.clientName, this.version);
31
+ const token = await deviceFlow.run();
32
+ if (!token) {
33
+ throw new Error('Failed to login');
34
+ }
35
+ this.saveToken(token);
36
+ }
37
+ async logout() {
38
+ try {
39
+ this.removeToken();
40
+ }
41
+ catch (err) {
42
+ // do nothing
43
+ }
44
+ }
45
+ async isAuthorized(baseUrl, apiKey) {
46
+ const deviceFlow = new device_flow_1.RedoclyOAuthDeviceFlow(baseUrl, this.clientName, this.version);
47
+ if (apiKey) {
48
+ return await deviceFlow.verifyApiKey(apiKey);
49
+ }
50
+ const token = await this.readToken();
51
+ if (!token) {
52
+ return false;
53
+ }
54
+ const isValidAccessToken = await deviceFlow.verifyToken(token.access_token);
55
+ if (isValidAccessToken) {
56
+ return true;
57
+ }
58
+ try {
59
+ const newToken = await deviceFlow.refreshToken(token.refresh_token);
60
+ await this.saveToken(newToken);
61
+ }
62
+ catch {
63
+ return false;
64
+ }
65
+ return true;
66
+ }
67
+ async saveToken(token) {
68
+ try {
69
+ const encrypted = this.cipher.update(JSON.stringify(token), 'utf8', 'hex') + this.cipher.final('hex');
70
+ (0, node_fs_1.writeFileSync)(path.join(this.dir, 'auth.json'), encrypted);
71
+ }
72
+ catch (error) {
73
+ process.stderr.write('Error saving tokens:', error);
74
+ }
75
+ }
76
+ async readToken() {
77
+ try {
78
+ const token = (0, node_fs_1.readFileSync)(path.join(this.dir, 'auth.json'), 'utf8');
79
+ const decrypted = this.decipher.update(token, 'hex', 'utf8') + this.decipher.final('utf8');
80
+ return decrypted ? JSON.parse(decrypted) : null;
81
+ }
82
+ catch {
83
+ return null;
84
+ }
85
+ }
86
+ async removeToken() {
87
+ const tokenPath = path.join(this.dir, 'auth.json');
88
+ if ((0, node_fs_1.existsSync)(tokenPath)) {
89
+ (0, node_fs_1.rmSync)(tokenPath);
90
+ }
91
+ }
92
+ }
93
+ exports.RedoclyOAuthClient = RedoclyOAuthClient;
@@ -0,0 +1,13 @@
1
+ import type { CommandArgs } from '../wrapper';
2
+ export declare function promptClientToken(domain: string): Promise<string>;
3
+ export type LoginOptions = {
4
+ verbose?: boolean;
5
+ residency?: string;
6
+ config?: string;
7
+ next?: boolean;
8
+ };
9
+ export declare function handleLogin({ argv, config, version }: CommandArgs<LoginOptions>): Promise<void>;
10
+ export type LogoutOptions = {
11
+ config?: string;
12
+ };
13
+ export declare function handleLogout({ version }: CommandArgs<LogoutOptions>): Promise<void>;
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.promptClientToken = promptClientToken;
4
+ exports.handleLogin = handleLogin;
5
+ exports.handleLogout = handleLogout;
6
+ const colorette_1 = require("colorette");
7
+ const openapi_core_1 = require("@redocly/openapi-core");
8
+ const miscellaneous_1 = require("../utils/miscellaneous");
9
+ const oauth_client_1 = require("../auth/oauth-client");
10
+ const api_1 = require("../reunite/api");
11
+ function promptClientToken(domain) {
12
+ return (0, miscellaneous_1.promptUser)((0, colorette_1.green)(`\n 🔑 Copy your API key from ${(0, colorette_1.blue)(`https://app.${domain}/profile`)} and paste it below`) + (0, colorette_1.yellow)(' (if you want to log in with Reunite, please run `redocly login --next` instead)'), true);
13
+ }
14
+ async function handleLogin({ argv, config, version }) {
15
+ if (argv.next) {
16
+ try {
17
+ const reuniteUrl = (0, api_1.getReuniteUrl)(argv.residency);
18
+ const oauthClient = new oauth_client_1.RedoclyOAuthClient('redocly-cli', version);
19
+ await oauthClient.login(reuniteUrl);
20
+ }
21
+ catch {
22
+ if (argv.residency) {
23
+ const reuniteUrl = (0, api_1.getReuniteUrl)(argv.residency);
24
+ (0, miscellaneous_1.exitWithError)(`❌ Connection to ${reuniteUrl} failed.`);
25
+ }
26
+ else {
27
+ (0, miscellaneous_1.exitWithError)(`❌ Login failed. Please check your credentials and try again.`);
28
+ }
29
+ }
30
+ }
31
+ else {
32
+ try {
33
+ const region = argv.residency || config.region;
34
+ const client = new openapi_core_1.RedoclyClient(region);
35
+ const clientToken = await promptClientToken(client.domain);
36
+ process.stdout.write((0, colorette_1.gray)('\n Logging in...\n'));
37
+ await client.login(clientToken, argv.verbose);
38
+ process.stdout.write((0, colorette_1.green)(' Authorization confirmed. ✅\n\n'));
39
+ }
40
+ catch (err) {
41
+ (0, miscellaneous_1.exitWithError)(' ' + err?.message);
42
+ }
43
+ }
44
+ }
45
+ async function handleLogout({ version }) {
46
+ const client = new openapi_core_1.RedoclyClient();
47
+ client.logout();
48
+ const oauthClient = new oauth_client_1.RedoclyOAuthClient('redocly-cli', version);
49
+ oauthClient.logout();
50
+ process.stdout.write('Logged out from the Redocly account. ✋ \n');
51
+ }
@@ -1,4 +1,4 @@
1
- import { handlePush as handleCMSPush } from '../cms/commands/push';
1
+ import { handlePush as handleCMSPush } from '../reunite/commands/push';
2
2
  import type { Config, Region } from '@redocly/openapi-core';
3
3
  import type { CommandArgs } from '../wrapper';
4
4
  import type { VerifyConfigOptions } from '../types';
@@ -13,9 +13,9 @@ const crypto_1 = require("crypto");
13
13
  const openapi_core_1 = require("@redocly/openapi-core");
14
14
  const utils_1 = require("@redocly/openapi-core/lib/utils");
15
15
  const miscellaneous_1 = require("../utils/miscellaneous");
16
- const login_1 = require("./login");
17
- const push_1 = require("../cms/commands/push");
18
- const api_client_1 = require("../cms/api/api-client");
16
+ const auth_1 = require("./auth");
17
+ const push_1 = require("../reunite/commands/push");
18
+ const api_client_1 = require("../reunite/api/api-client");
19
19
  const DEFAULT_VERSION = 'latest';
20
20
  exports.DESTINATION_REGEX =
21
21
  // eslint-disable-next-line no-useless-escape
@@ -31,7 +31,7 @@ async function handlePush({ argv, config }) {
31
31
  const isAuthorized = await client.isAuthorizedWithRedoclyByRegion();
32
32
  if (!isAuthorized) {
33
33
  try {
34
- const clientToken = await (0, login_1.promptClientToken)(client.domain);
34
+ const clientToken = await (0, auth_1.promptClientToken)(client.domain);
35
35
  await client.login(clientToken);
36
36
  }
37
37
  catch (e) {
@@ -111,9 +111,9 @@ function replace$Refs(obj, relativeFrom, componentFiles = {}) {
111
111
  const filesGroupName = componentFiles[groupName];
112
112
  if (!filesGroupName || !filesGroupName[name])
113
113
  return;
114
- let filename = path.relative(relativeFrom, filesGroupName[name].filename);
114
+ let filename = (0, openapi_core_1.slash)(path.relative(relativeFrom, filesGroupName[name].filename));
115
115
  if (!filename.startsWith('.')) {
116
- filename = '.' + path.sep + filename;
116
+ filename = './' + filename;
117
117
  }
118
118
  node[key] = filename;
119
119
  }
@@ -125,8 +125,8 @@ function implicitlyReferenceDiscriminator(obj, defName, filename, schemaFiles) {
125
125
  const implicitMapping = {};
126
126
  for (const [name, { inherits, filename: parentFilename }] of Object.entries(schemaFiles)) {
127
127
  if (inherits.indexOf(defPtr) > -1) {
128
- const res = path.relative(path.dirname(filename), parentFilename);
129
- implicitMapping[name] = res.startsWith('.') ? res : '.' + path.sep + res;
128
+ const res = (0, openapi_core_1.slash)(path.relative(path.dirname(filename), parentFilename));
129
+ implicitMapping[name] = res.startsWith('.') ? res : './' + res;
130
130
  }
131
131
  }
132
132
  if ((0, js_utils_1.isEmptyObject)(implicitMapping))
package/lib/index.js CHANGED
@@ -1,19 +1,20 @@
1
1
  #!/usr/bin/env node
2
2
  "use strict";
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
+ const path = require("path");
5
+ const dotenv = require("dotenv");
4
6
  require("./utils/assert-node-version");
5
7
  const yargs = require("yargs");
6
8
  const colors = require("colorette");
7
- const openapi_core_1 = require("@redocly/openapi-core");
8
9
  const types_1 = require("./types");
9
10
  const preview_docs_1 = require("./commands/preview-docs");
10
11
  const stats_1 = require("./commands/stats");
11
12
  const split_1 = require("./commands/split");
12
13
  const join_1 = require("./commands/join");
13
- const push_status_1 = require("./cms/commands/push-status");
14
+ const push_status_1 = require("./reunite/commands/push-status");
14
15
  const lint_1 = require("./commands/lint");
15
16
  const bundle_1 = require("./commands/bundle");
16
- const login_1 = require("./commands/login");
17
+ const auth_1 = require("./commands/auth");
17
18
  const build_docs_1 = require("./commands/build-docs");
18
19
  const update_version_notifier_1 = require("./utils/update-version-notifier");
19
20
  const wrapper_1 = require("./wrapper");
@@ -22,6 +23,8 @@ const translations_1 = require("./commands/translations");
22
23
  const eject_1 = require("./commands/eject");
23
24
  const constants_1 = require("./commands/preview-project/constants");
24
25
  const push_1 = require("./commands/push");
26
+ const respect_core_1 = require("@redocly/respect-core");
27
+ dotenv.config({ path: path.resolve(__dirname, '../.env') });
25
28
  if (!('replaceAll' in String.prototype)) {
26
29
  require('core-js/actual/string/replace-all');
27
30
  }
@@ -521,32 +524,32 @@ yargs
521
524
  process.env.REDOCLY_CLI_COMMAND = 'check-config';
522
525
  (0, wrapper_1.commandWrapper)()(argv);
523
526
  })
524
- .command('login', 'Login to the Redocly API registry with an access token.', async (yargs) => yargs.options({
527
+ .command('login', 'Log in to Redocly.', async (yargs) => yargs.options({
525
528
  verbose: {
526
529
  description: 'Include additional output.',
527
530
  type: 'boolean',
528
531
  },
529
- region: {
530
- description: 'Specify a region.',
531
- alias: 'r',
532
- choices: types_1.regionChoices,
532
+ residency: {
533
+ description: 'Residency of the application. Defaults to `us`.',
534
+ alias: ['r', 'region'],
535
+ type: 'string',
533
536
  },
534
537
  config: {
535
538
  description: 'Path to the config file.',
536
539
  requiresArg: true,
537
540
  type: 'string',
538
541
  },
542
+ next: {
543
+ description: 'Use Reunite application to login.',
544
+ type: 'boolean',
545
+ },
539
546
  }), (argv) => {
540
547
  process.env.REDOCLY_CLI_COMMAND = 'login';
541
- (0, wrapper_1.commandWrapper)(login_1.handleLogin)(argv);
548
+ (0, wrapper_1.commandWrapper)(auth_1.handleLogin)(argv);
542
549
  })
543
- .command('logout', 'Clear your stored credentials for the Redocly API registry.', (yargs) => yargs, async (argv) => {
550
+ .command('logout', 'Clear your stored credentials for the Redocly API registry.', (yargs) => yargs, (argv) => {
544
551
  process.env.REDOCLY_CLI_COMMAND = 'logout';
545
- await (0, wrapper_1.commandWrapper)(async () => {
546
- const client = new openapi_core_1.RedoclyClient();
547
- client.logout();
548
- process.stdout.write('Logged out from the Redocly account. ✋\n');
549
- })(argv);
552
+ (0, wrapper_1.commandWrapper)(auth_1.handleLogout)(argv);
550
553
  })
551
554
  .command('preview', 'Preview Redocly project using one of the product NPM packages.', (yargs) => yargs.options({
552
555
  product: {
@@ -727,6 +730,114 @@ yargs
727
730
  process.env.REDOCLY_CLI_COMMAND = 'eject';
728
731
  (0, wrapper_1.commandWrapper)(eject_1.handleEject)(argv);
729
732
  })
733
+ .command('respect [files..]', 'Run workflow tests', (yargs) => {
734
+ return yargs
735
+ .positional('files', {
736
+ describe: 'Test files or glob pattern',
737
+ type: 'string',
738
+ default: [],
739
+ })
740
+ .env('REDOCLY_CLI_RESPECT')
741
+ .options({
742
+ input: {
743
+ alias: 'i',
744
+ describe: 'Input parameters',
745
+ type: 'string',
746
+ },
747
+ server: {
748
+ alias: 'S',
749
+ describe: 'Server parameters',
750
+ type: 'string',
751
+ },
752
+ workflow: {
753
+ alias: 'w',
754
+ describe: 'Workflow name',
755
+ type: 'array',
756
+ greedy: false,
757
+ },
758
+ skip: {
759
+ alias: 's',
760
+ describe: 'Workflow to skip',
761
+ type: 'array',
762
+ greedy: false,
763
+ },
764
+ verbose: {
765
+ alias: 'v',
766
+ describe: 'Apply verbose mode',
767
+ type: 'boolean',
768
+ },
769
+ 'har-output': {
770
+ describe: 'Har file output name',
771
+ type: 'string',
772
+ },
773
+ 'json-output': {
774
+ describe: 'JSON file output name',
775
+ type: 'string',
776
+ },
777
+ residency: {
778
+ describe: 'Residency of Reunite application. Defaults to US.',
779
+ type: 'string',
780
+ default: 'us',
781
+ },
782
+ 'client-cert': {
783
+ describe: 'Mutual TLS client certificate',
784
+ type: 'string',
785
+ },
786
+ 'client-key': {
787
+ describe: 'Mutual TLS client key',
788
+ type: 'string',
789
+ },
790
+ 'ca-cert': {
791
+ describe: 'Mutual TLS CA certificate',
792
+ type: 'string',
793
+ },
794
+ severity: {
795
+ describe: 'Severity of the check',
796
+ type: 'string',
797
+ },
798
+ });
799
+ }, async (argv) => {
800
+ try {
801
+ await (0, respect_core_1.handleRun)(argv);
802
+ }
803
+ catch (err) {
804
+ // logger.error(red(`${err?.message}`));
805
+ process.exit(1);
806
+ }
807
+ })
808
+ .command('generate-arazzo <descriptionPath>', 'Auto-generate test config file from description', (yargs) => {
809
+ return yargs
810
+ .positional('descriptionPath', {
811
+ describe: 'Description file path',
812
+ type: 'string',
813
+ })
814
+ .env('REDOCLY_SPOT')
815
+ .options({
816
+ 'output-file': {
817
+ alias: 'o',
818
+ describe: 'Output File name',
819
+ type: 'string',
820
+ },
821
+ extended: {
822
+ describe: 'Generate config with populated values from description using success criteria',
823
+ type: 'boolean',
824
+ },
825
+ residency: {
826
+ describe: 'Residency of Reunite application. Defaults to US.',
827
+ type: 'string',
828
+ default: 'us',
829
+ },
830
+ });
831
+ }
832
+ // async (argv) => {
833
+ // try {
834
+ // await handleGenerate(argv as GenerateConfigFileArgv);
835
+ // } catch {
836
+ // logger.error(`❌ Auto config generation failed.`);
837
+ // process.exit(1);
838
+ // }
839
+ // },
840
+ )
730
841
  .completion('completion', 'Generate autocomplete script for `redocly` command.')
731
842
  .demandCommand(1)
732
843
  .middleware([update_version_notifier_1.notifyUpdateCliVersion])
package/lib/otel.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ import type { Analytics } from './utils/miscellaneous';
2
+ type Events = {
3
+ [key: string]: Analytics;
4
+ };
5
+ export declare class OtelServerTelemetry {
6
+ init(): void;
7
+ send<K extends keyof Events>(event: K, data: Events[K]): void;
8
+ }
9
+ export declare const otelTelemetry: OtelServerTelemetry;
10
+ export {};
package/lib/otel.js ADDED
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.otelTelemetry = exports.OtelServerTelemetry = void 0;
4
+ const api_1 = require("@opentelemetry/api");
5
+ const resources_1 = require("@opentelemetry/resources");
6
+ const sdk_trace_node_1 = require("@opentelemetry/sdk-trace-node");
7
+ const exporter_trace_otlp_http_1 = require("@opentelemetry/exporter-trace-otlp-http");
8
+ const semantic_conventions_1 = require("@opentelemetry/semantic-conventions");
9
+ const update_version_notifier_1 = require("./utils/update-version-notifier");
10
+ const fetch_with_timeout_1 = require("./utils/fetch-with-timeout");
11
+ const OTEL_TRACES_URL = process.env.OTEL_TRACES_URL || 'https://otel.cloud.redocly.com/v1/traces';
12
+ class OtelServerTelemetry {
13
+ init() {
14
+ const nodeTracerProvider = new sdk_trace_node_1.NodeTracerProvider({
15
+ resource: new resources_1.Resource({
16
+ [semantic_conventions_1.ATTR_SERVICE_NAME]: `redocly-cli`,
17
+ [semantic_conventions_1.ATTR_SERVICE_VERSION]: `@redocly/cli@${update_version_notifier_1.version}`,
18
+ }),
19
+ });
20
+ nodeTracerProvider.addSpanProcessor(new sdk_trace_node_1.SimpleSpanProcessor(new exporter_trace_otlp_http_1.OTLPTraceExporter({
21
+ url: OTEL_TRACES_URL,
22
+ headers: {},
23
+ timeoutMillis: fetch_with_timeout_1.DEFAULT_FETCH_TIMEOUT,
24
+ })));
25
+ nodeTracerProvider.register();
26
+ }
27
+ send(event, data) {
28
+ const time = new Date();
29
+ const eventId = crypto.randomUUID();
30
+ const span = api_1.trace.getTracer('CliTelemetry').startSpan(`event.${event}`, {
31
+ attributes: {
32
+ 'cloudevents.event_client.id': eventId,
33
+ 'cloudevents.event_client.type': event,
34
+ },
35
+ startTime: time,
36
+ });
37
+ for (const [key, value] of Object.entries(data)) {
38
+ const keySnakeCase = key.replace(/([A-Z])/g, '_$1').toLowerCase();
39
+ if (value !== undefined) {
40
+ span.setAttribute(`cloudevents.event_data.${keySnakeCase}`, value);
41
+ }
42
+ }
43
+ span.end(time);
44
+ }
45
+ }
46
+ exports.OtelServerTelemetry = OtelServerTelemetry;
47
+ exports.otelTelemetry = new OtelServerTelemetry();
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const domains_1 = require("../domains");
4
+ const domains_2 = require("../domains");
5
+ describe('getDomain()', () => {
6
+ afterEach(() => {
7
+ delete process.env.REDOCLY_DOMAIN;
8
+ });
9
+ it('should return the domain from environment variable', () => {
10
+ process.env.REDOCLY_DOMAIN = 'test-domain';
11
+ expect((0, domains_1.getDomain)()).toBe('test-domain');
12
+ });
13
+ it('should return the default domain if no domain provided', () => {
14
+ process.env.REDOCLY_DOMAIN = '';
15
+ expect((0, domains_1.getDomain)()).toBe('https://app.cloud.redocly.com');
16
+ });
17
+ });
18
+ describe('getReuniteUrl()', () => {
19
+ it('should return US API URL when US region specified', () => {
20
+ expect((0, domains_2.getReuniteUrl)('us')).toBe('https://app.cloud.redocly.com/api');
21
+ });
22
+ it('should return EU API URL when EU region specified', () => {
23
+ expect((0, domains_2.getReuniteUrl)('eu')).toBe('https://app.cloud.eu.redocly.com/api');
24
+ });
25
+ it('should return custom domain API URL when custom domain specified', () => {
26
+ const customDomain = 'https://custom.domain.com';
27
+ expect((0, domains_2.getReuniteUrl)(customDomain)).toBe('https://custom.domain.com/api');
28
+ });
29
+ it('should return US API URL when no region specified', () => {
30
+ expect((0, domains_2.getReuniteUrl)()).toBe('https://app.cloud.redocly.com/api');
31
+ });
32
+ });
@@ -15,6 +15,15 @@ export declare class ReuniteApiError extends Error {
15
15
  status: number;
16
16
  constructor(message: string, status: number);
17
17
  }
18
+ export declare class ReuniteApiClient implements BaseApiClient {
19
+ protected version: string;
20
+ protected command: string;
21
+ sunsetWarnings: SunsetWarningsBuffer;
22
+ constructor(version: string, command: string);
23
+ request(url: string, options: FetchWithTimeoutOptions): Promise<Response>;
24
+ private collectSunsetWarning;
25
+ private getSunsetDate;
26
+ }
18
27
  declare class RemotesApi {
19
28
  private client;
20
29
  private readonly domain;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ReuniteApi = exports.ReuniteApiError = void 0;
3
+ exports.ReuniteApi = exports.ReuniteApiClient = exports.ReuniteApiError = void 0;
4
4
  exports.streamToBuffer = streamToBuffer;
5
5
  const colorette_1 = require("colorette");
6
6
  const fetch_with_timeout_1 = require("../../utils/fetch-with-timeout");
@@ -59,6 +59,7 @@ class ReuniteApiClient {
59
59
  return Date.parse(sunsetDate);
60
60
  }
61
61
  }
62
+ exports.ReuniteApiClient = ReuniteApiClient;
62
63
  class RemotesApi {
63
64
  constructor(client, domain, apiKey) {
64
65
  this.client = client;
@@ -0,0 +1,4 @@
1
+ import type { Region } from '@redocly/openapi-core';
2
+ export declare const REUNITE_URLS: Record<Region, string>;
3
+ export declare function getDomain(): string;
4
+ export declare function getReuniteUrl(residency?: string): string;
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.REUNITE_URLS = void 0;
4
+ exports.getDomain = getDomain;
5
+ exports.getReuniteUrl = getReuniteUrl;
6
+ exports.REUNITE_URLS = {
7
+ us: 'https://app.cloud.redocly.com',
8
+ eu: 'https://app.cloud.eu.redocly.com',
9
+ };
10
+ function getDomain() {
11
+ return process.env.REDOCLY_DOMAIN || exports.REUNITE_URLS.us;
12
+ }
13
+ function getReuniteUrl(residency) {
14
+ if (!residency)
15
+ residency = 'us';
16
+ let reuniteUrl = exports.REUNITE_URLS[residency];
17
+ if (!reuniteUrl) {
18
+ reuniteUrl = residency;
19
+ }
20
+ const url = new URL('/api', reuniteUrl).toString();
21
+ return url;
22
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
package/lib/types.d.ts CHANGED
@@ -3,14 +3,14 @@ import type { ArgumentsCamelCase } from 'yargs';
3
3
  import type { LintOptions } from './commands/lint';
4
4
  import type { BundleOptions } from './commands/bundle';
5
5
  import type { JoinOptions } from './commands/join';
6
- import type { LoginOptions } from './commands/login';
6
+ import type { LoginOptions, LogoutOptions } from './commands/auth';
7
7
  import type { PushOptions } from './commands/push';
8
8
  import type { StatsOptions } from './commands/stats';
9
9
  import type { SplitOptions } from './commands/split';
10
10
  import type { PreviewDocsOptions } from './commands/preview-docs';
11
11
  import type { BuildDocsArgv } from './commands/build-docs/types';
12
- import type { PushOptions as CMSPushOptions } from './cms/commands/push';
13
- import type { PushStatusOptions } from './cms/commands/push-status';
12
+ import type { PushOptions as CMSPushOptions } from './reunite/commands/push';
13
+ import type { PushStatusOptions } from './reunite/commands/push-status';
14
14
  import type { PreviewProjectOptions } from './commands/preview-project/types';
15
15
  import type { TranslationsOptions } from './commands/translations';
16
16
  import type { EjectOptions } from './commands/eject';
@@ -27,7 +27,7 @@ export type Entrypoint = {
27
27
  export declare const outputExtensions: ReadonlyArray<BundleOutputFormat>;
28
28
  export type OutputExtensions = 'json' | 'yaml' | 'yml' | undefined;
29
29
  export declare const regionChoices: ReadonlyArray<Region>;
30
- export type CommandOptions = StatsOptions | SplitOptions | JoinOptions | PushOptions | CMSPushOptions | LintOptions | BundleOptions | LoginOptions | PreviewDocsOptions | BuildDocsArgv | PushStatusOptions | PreviewProjectOptions | TranslationsOptions | EjectOptions;
30
+ export type CommandOptions = StatsOptions | SplitOptions | JoinOptions | PushOptions | CMSPushOptions | LintOptions | BundleOptions | LoginOptions | LogoutOptions | PreviewDocsOptions | BuildDocsArgv | PushStatusOptions | PreviewProjectOptions | TranslationsOptions | EjectOptions;
31
31
  export type VerifyConfigOptions = {
32
32
  config?: string;
33
33
  'lint-config'?: RuleSeverity;
@@ -59,17 +59,18 @@ export type ExitCode = 0 | 1 | 2;
59
59
  export type Analytics = {
60
60
  event: string;
61
61
  event_time: string;
62
- logged_in: boolean;
63
- command: string | number;
64
- arguments: Record<string, unknown>;
62
+ logged_in: 'yes' | 'no';
63
+ command: string;
64
+ arguments: string;
65
65
  node_version: string;
66
66
  npm_version: string;
67
+ os_platform: string;
67
68
  version: string;
68
69
  exit_code: ExitCode;
69
70
  environment?: string;
70
71
  environment_ci?: string;
71
72
  raw_input: string;
72
- has_config?: boolean;
73
+ has_config?: 'yes' | 'no';
73
74
  spec_version?: string;
74
75
  spec_keyword?: string;
75
76
  spec_full_version?: string;
@@ -37,6 +37,7 @@ const colorette_1 = require("colorette");
37
37
  const perf_hooks_1 = require("perf_hooks");
38
38
  const glob = require("glob");
39
39
  const fs = require("fs");
40
+ const os = require("os");
40
41
  const readline = require("readline");
41
42
  const stream_1 = require("stream");
42
43
  const child_process_1 = require("child_process");
@@ -48,7 +49,9 @@ const reference_docs_config_schema_1 = require("@redocly/config/lib/reference-do
48
49
  const types_1 = require("../types");
49
50
  const update_version_notifier_1 = require("./update-version-notifier");
50
51
  const push_1 = require("../commands/push");
51
- const fetch_with_timeout_1 = require("./fetch-with-timeout");
52
+ const oauth_client_1 = require("../auth/oauth-client");
53
+ const api_1 = require("../reunite/api");
54
+ const otel_1 = require("../otel");
52
55
  async function getFallbackApisOrExit(argsApis, config) {
53
56
  const { apis } = config;
54
57
  const shouldFallbackToAllDefinitions = !(0, utils_1.isNotEmptyArray)(argsApis) && (0, utils_1.isNotEmptyObject)(apis);
@@ -440,6 +443,7 @@ function cleanColors(input) {
440
443
  // eslint-disable-next-line no-control-regex
441
444
  return input.replace(/\x1b\[\d+m/g, '');
442
445
  }
446
+ otel_1.otelTelemetry.init();
443
447
  async function sendTelemetry(argv, exit_code, has_config, spec_version, spec_keyword, spec_full_version) {
444
448
  try {
445
449
  if (!argv) {
@@ -448,33 +452,29 @@ async function sendTelemetry(argv, exit_code, has_config, spec_version, spec_key
448
452
  const { _: [command], $0: _, ...args } = argv;
449
453
  const event_time = new Date().toISOString();
450
454
  const redoclyClient = new openapi_core_1.RedoclyClient();
451
- const logged_in = redoclyClient.hasTokens();
455
+ const oauthClient = new oauth_client_1.RedoclyOAuthClient('redocly-cli', update_version_notifier_1.version);
456
+ const reuniteUrl = (0, api_1.getReuniteUrl)(argv.residency);
457
+ const logged_in = redoclyClient.hasTokens() || (await oauthClient.isAuthorized(reuniteUrl));
452
458
  const data = {
453
459
  event: 'cli_command',
454
460
  event_time,
455
- logged_in,
456
- command,
457
- arguments: cleanArgs(args),
461
+ logged_in: logged_in ? 'yes' : 'no',
462
+ command: `${command}`,
463
+ arguments: JSON.stringify(cleanArgs(args)),
458
464
  node_version: process.version,
459
465
  npm_version: (0, child_process_1.execSync)('npm -v').toString().replace('\n', ''),
466
+ os_platform: os.platform(),
460
467
  version: update_version_notifier_1.version,
461
468
  exit_code,
462
469
  environment: process.env.REDOCLY_ENVIRONMENT,
463
470
  environment_ci: process.env.CI,
464
471
  raw_input: cleanRawInput(process.argv.slice(2)),
465
- has_config,
472
+ has_config: has_config ? 'yes' : 'no',
466
473
  spec_version,
467
474
  spec_keyword,
468
475
  spec_full_version,
469
476
  };
470
- await (0, fetch_with_timeout_1.default)(`https://api.redocly.com/registry/telemetry/cli`, {
471
- timeout: fetch_with_timeout_1.DEFAULT_FETCH_TIMEOUT,
472
- method: 'POST',
473
- headers: {
474
- 'content-type': 'application/json',
475
- },
476
- body: JSON.stringify(data),
477
- });
477
+ otel_1.otelTelemetry.send(data.command, data);
478
478
  }
479
479
  catch (err) {
480
480
  // Do nothing.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@redocly/cli",
3
- "version": "0.0.0-snapshot.1739194003",
3
+ "version": "0.0.0-snapshot.1739895544",
4
4
  "description": "",
5
5
  "license": "MIT",
6
6
  "bin": {
@@ -36,24 +36,31 @@
36
36
  "Roman Hotsiy <roman@redocly.com> (https://redocly.com/)"
37
37
  ],
38
38
  "dependencies": {
39
- "@redocly/openapi-core": "0.0.0-snapshot.1739194003",
39
+ "@redocly/openapi-core": "0.0.0-snapshot.1739895544",
40
40
  "abort-controller": "^3.0.0",
41
41
  "chokidar": "^3.5.1",
42
42
  "colorette": "^1.2.0",
43
43
  "core-js": "^3.32.1",
44
+ "dotenv": "^16.4.7",
44
45
  "form-data": "^4.0.0",
45
46
  "get-port-please": "^3.0.1",
46
47
  "glob": "^7.1.6",
47
48
  "handlebars": "^4.7.6",
48
49
  "mobx": "^6.0.4",
50
+ "@opentelemetry/api": "1.9.0",
51
+ "@opentelemetry/exporter-trace-otlp-http": "0.53.0",
52
+ "@opentelemetry/resources": "1.26.0",
53
+ "@opentelemetry/sdk-trace-node": "1.26.0",
54
+ "@opentelemetry/semantic-conventions": "1.27.0",
49
55
  "pluralize": "^8.0.0",
50
56
  "react": "^17.0.0 || ^18.2.0 || ^19.0.0",
51
57
  "react-dom": "^17.0.0 || ^18.2.0 || ^19.0.0",
52
58
  "redoc": "2.4.0",
53
59
  "semver": "^7.5.2",
54
60
  "simple-websocket": "^9.0.0",
55
- "styled-components": "^6.1.15",
56
- "yargs": "17.0.1"
61
+ "styled-components": "^6.0.7",
62
+ "yargs": "17.0.1",
63
+ "@redocly/respect-core": "0.0.0-snapshot.1739895544"
57
64
  },
58
65
  "devDependencies": {
59
66
  "@types/configstore": "^5.0.1",
@@ -1,13 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const domains_1 = require("../domains");
4
- describe('getDomain()', () => {
5
- it('should return the domain from environment variable', () => {
6
- process.env.REDOCLY_DOMAIN = 'test-domain';
7
- expect((0, domains_1.getDomain)()).toBe('test-domain');
8
- });
9
- it('should return the default domain if no domain provided', () => {
10
- process.env.REDOCLY_DOMAIN = '';
11
- expect((0, domains_1.getDomain)()).toBe('https://app.cloud.redocly.com');
12
- });
13
- });
@@ -1 +0,0 @@
1
- export declare function getDomain(): string;
@@ -1,11 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getDomain = getDomain;
4
- const DEFAULT_DOMAIN = 'https://app.cloud.redocly.com';
5
- function getDomain() {
6
- const domain = process.env.REDOCLY_DOMAIN;
7
- if (domain) {
8
- return domain;
9
- }
10
- return DEFAULT_DOMAIN;
11
- }
@@ -1,9 +0,0 @@
1
- import type { CommandArgs } from '../wrapper';
2
- import type { Region } from '@redocly/openapi-core';
3
- export declare function promptClientToken(domain: string): Promise<string>;
4
- export type LoginOptions = {
5
- verbose?: boolean;
6
- region?: Region;
7
- config?: string;
8
- };
9
- export declare function handleLogin({ argv, config }: CommandArgs<LoginOptions>): Promise<void>;
@@ -1,23 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.promptClientToken = promptClientToken;
4
- exports.handleLogin = handleLogin;
5
- const colorette_1 = require("colorette");
6
- const openapi_core_1 = require("@redocly/openapi-core");
7
- const miscellaneous_1 = require("../utils/miscellaneous");
8
- function promptClientToken(domain) {
9
- return (0, miscellaneous_1.promptUser)((0, colorette_1.green)(`\n 🔑 Copy your API key from ${(0, colorette_1.blue)(`https://app.${domain}/profile`)} and paste it below`), true);
10
- }
11
- async function handleLogin({ argv, config }) {
12
- try {
13
- const region = argv.region || config.region;
14
- const client = new openapi_core_1.RedoclyClient(region);
15
- const clientToken = await promptClientToken(client.domain);
16
- process.stdout.write((0, colorette_1.gray)('\n Logging in...\n'));
17
- await client.login(clientToken, argv.verbose);
18
- process.stdout.write((0, colorette_1.green)(' Authorization confirmed. ✅\n\n'));
19
- }
20
- catch (err) {
21
- (0, miscellaneous_1.exitWithError)(' ' + err?.message);
22
- }
23
- }
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes