Upgrade ADF CLI to latest Commander library (#9473)

* build(deps-dev): bump commander from 6.2.1 to 12.0.0

Bumps [commander](https://github.com/tj/commander.js) from 6.2.1 to 12.0.0.
- [Release notes](https://github.com/tj/commander.js/releases)
- [Changelog](https://github.com/tj/commander.js/blob/master/CHANGELOG.md)
- [Commits](https://github.com/tj/commander.js/compare/v6.2.1...v12.0.0)

---
updated-dependencies:
- dependency-name: commander
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>

* chore: migrate CLI to latest commander library

* chore: migrate CLI to latest commander library [ci:force]

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
This commit is contained in:
Denys Vuika 2024-03-26 09:36:49 -04:00 committed by GitHub
parent 7cca017c12
commit 9d7608817d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
13 changed files with 241 additions and 143 deletions

View File

@ -22,7 +22,14 @@ import * as ejs from 'ejs';
import * as path from 'path'; import * as path from 'path';
import * as fs from 'fs'; import * as fs from 'fs';
import { argv, exit } from 'node:process'; import { argv, exit } from 'node:process';
import program from 'commander'; import { Command } from 'commander';
const program = new Command();
interface AuditCommandArgs {
package?: string;
outDir?: string;
}
/** /**
* Audit report command * Audit report command
@ -44,10 +51,12 @@ export default function main(_args: string[], workingDir: string) {
exit(0); exit(0);
} }
const options = program.opts<AuditCommandArgs>();
let packagePath = path.resolve(workingDir, 'package.json'); let packagePath = path.resolve(workingDir, 'package.json');
if (program.package) { if (options.package) {
packagePath = path.resolve(program.package); packagePath = path.resolve(options.package);
} }
if (!fs.existsSync(packagePath)) { if (!fs.existsSync(packagePath)) {
@ -82,7 +91,7 @@ export default function main(_args: string[], workingDir: string) {
console.error(err); console.error(err);
reject(err); reject(err);
} else { } else {
const outputPath = path.resolve(program.outDir || workingDir); const outputPath = path.resolve(options.outDir || workingDir);
const outputFile = path.join(outputPath, `audit-info-${packageJson.version}.md`); const outputFile = path.join(outputPath, `audit-info-${packageJson.version}.md`);
fs.writeFileSync(outputFile, mdText); fs.writeFileSync(outputFile, mdText);

View File

@ -22,11 +22,13 @@
import { argv, exit } from 'node:process'; import { argv, exit } from 'node:process';
import * as shell from 'shelljs'; import * as shell from 'shelljs';
import * as path from 'path'; import * as path from 'path';
import program from 'commander'; import { Command } from 'commander';
import { logger } from './logger'; import { logger } from './logger';
import * as fs from 'fs'; import * as fs from 'fs';
import * as ejs from 'ejs'; import * as ejs from 'ejs';
const program = new Command();
interface Commit { interface Commit {
hash: string; hash: string;
author: string; author: string;
@ -167,8 +169,10 @@ export default function main(_args: string[], workingDir: string) {
exit(0); exit(0);
} }
const dir = path.resolve(program.dir || workingDir); const options = program.opts();
const { range, skip, max, format, output, exclude } = program;
const dir = path.resolve(options.dir || workingDir);
const { range, skip, max, format, output, exclude } = options;
const remote = getRemote(dir); const remote = getRemote(dir);

View File

@ -17,11 +17,21 @@
import { AlfrescoApi /*, NodesApi, UploadApi*/ } from '@alfresco/js-api'; import { AlfrescoApi /*, NodesApi, UploadApi*/ } from '@alfresco/js-api';
import { argv, exit } from 'node:process'; import { argv, exit } from 'node:process';
// import { Buffer } from 'node:buffer'; import { Command } from 'commander';
const program = require('commander');
import { logger } from './logger'; import { logger } from './logger';
interface CheckCsEnvArgs {
host?: string;
username?: string;
password?: string;
time?: number;
retry?: number;
}
const program = new Command();
const MAX_RETRY = 3; const MAX_RETRY = 3;
const TIMEOUT = 20000; const TIMEOUT = 20000;
let counter = 0; let counter = 0;
let alfrescoJsApi: AlfrescoApi; let alfrescoJsApi: AlfrescoApi;
@ -40,23 +50,26 @@ export default async function main() {
.option('-r, --retry [type]', 'retry ') .option('-r, --retry [type]', 'retry ')
.parse(argv); .parse(argv);
await checkEnv(); const opts = program.opts<CheckCsEnvArgs>();
await checkEnv(opts);
// TODO: https://alfresco.atlassian.net/browse/ACS-5873 // TODO: https://alfresco.atlassian.net/browse/ACS-5873
// await checkDiskSpaceFullEnv(); // await checkDiskSpaceFullEnv();
} }
/** /**
* Check environment * Check environment
*
* @param opts command options
*/ */
async function checkEnv() { async function checkEnv(opts?: CheckCsEnvArgs) {
try { try {
alfrescoJsApi = new AlfrescoApi({ alfrescoJsApi = new AlfrescoApi({
provider: 'ECM', provider: 'ECM',
hostEcm: program.host, hostEcm: opts.host,
contextRoot: 'alfresco' contextRoot: 'alfresco'
}); });
await alfrescoJsApi.login(program.username, program.password); await alfrescoJsApi.login(opts.username, opts.password);
} catch (error) { } catch (error) {
if (error?.error?.code === 'ETIMEDOUT') { if (error?.error?.code === 'ETIMEDOUT') {
logger.error('The env is not reachable. Terminating'); logger.error('The env is not reachable. Terminating');
@ -64,8 +77,8 @@ async function checkEnv() {
} }
logger.error('Login error environment down or inaccessible'); logger.error('Login error environment down or inaccessible');
counter++; counter++;
const retry = program.retry || MAX_RETRY; const retry = opts.retry || MAX_RETRY;
const time = program.time || TIMEOUT; const time = opts.time || TIMEOUT;
if (retry === counter) { if (retry === counter) {
logger.error('Give up'); logger.error('Give up');
exit(1); exit(1);

View File

@ -16,15 +16,25 @@
*/ */
import { argv } from 'node:process'; import { argv } from 'node:process';
import { PluginTarget } from './plugins/plugin-model';
import { CheckEnv } from './plugins/check-env'; import { CheckEnv } from './plugins/check-env';
import program = require('commander'); import { Command } from 'commander';
import { ProcessServiceCheckPlugin } from './plugins/process-service-check-plugin'; import { ProcessServiceCheckPlugin } from './plugins/process-service-check-plugin';
import { ProcessAutomationCheckPlugin } from './plugins/process-automation-check-plugin'; import { ProcessAutomationCheckPlugin } from './plugins/process-automation-check-plugin';
import { GovernanceCheckPlugin } from './plugins/governance-check-plugin'; import { GovernanceCheckPlugin } from './plugins/governance-check-plugin';
const program = new Command();
let pluginEnv: CheckEnv; let pluginEnv: CheckEnv;
interface CheckPluginArgs {
host?: string;
pluginName?: 'processService' | 'processAutomation' | 'governance';
clientId?: string;
appName?: string;
username?: string;
password?: string;
uiName?: string;
}
/** /**
* Check environment plugin * Check environment plugin
*/ */
@ -40,30 +50,34 @@ export default async function main() {
.option('--ui, --uiName [type]', 'uiName', 'Deployed app UI type on activiti-cloud') .option('--ui, --uiName [type]', 'uiName', 'Deployed app UI type on activiti-cloud')
.parse(argv); .parse(argv);
pluginEnv = new CheckEnv(program.host, program.username, program.password, program.clientId); const options = program.opts<CheckPluginArgs>();
pluginEnv = new CheckEnv(options.host, options.username, options.password, options.clientId);
await pluginEnv.checkEnv(); await pluginEnv.checkEnv();
if (program.pluginName === PluginTarget.processService) { if (options.pluginName === 'processService') {
await checkProcessServicesPlugin(); await checkProcessServicesPlugin(options);
} }
if (program.pluginName === PluginTarget.processAutomation) { if (options.pluginName === 'processAutomation') {
await checkProcessAutomationPlugin(); await checkProcessAutomationPlugin(options);
} }
if (program.pluginName === PluginTarget.governance) { if (options.pluginName === 'governance') {
await checkGovernancePlugin(); await checkGovernancePlugin(options);
} }
} }
/** /**
* Check PS plugin * Check PS plugin
*
* @param options program arguments
*/ */
async function checkProcessServicesPlugin() { async function checkProcessServicesPlugin(options: CheckPluginArgs) {
const processServiceCheckPlugin = new ProcessServiceCheckPlugin( const processServiceCheckPlugin = new ProcessServiceCheckPlugin(
{ {
host: program.host, host: options.host,
name: PluginTarget.processService name: 'processService'
}, },
pluginEnv.alfrescoJsApi pluginEnv.alfrescoJsApi
); );
@ -72,14 +86,16 @@ async function checkProcessServicesPlugin() {
/** /**
* Check APA plugin * Check APA plugin
*
* @param options program arguments
*/ */
async function checkProcessAutomationPlugin() { async function checkProcessAutomationPlugin(options: CheckPluginArgs) {
const processAutomationCheckPlugin = new ProcessAutomationCheckPlugin( const processAutomationCheckPlugin = new ProcessAutomationCheckPlugin(
{ {
host: program.host, host: options.host,
name: PluginTarget.processAutomation, name: 'processAutomation',
appName: program.appName, appName: options.appName,
uiName: program.uiName uiName: options.uiName
}, },
pluginEnv.alfrescoJsApi pluginEnv.alfrescoJsApi
); );
@ -88,12 +104,14 @@ async function checkProcessAutomationPlugin() {
/** /**
* Check AGS plugin * Check AGS plugin
*
* @param options program arguments
*/ */
async function checkGovernancePlugin() { async function checkGovernancePlugin(options: CheckPluginArgs) {
const governancePluginCheck = new GovernanceCheckPlugin( const governancePluginCheck = new GovernanceCheckPlugin(
{ {
host: program.host, host: options.host,
name: PluginTarget.governance name: 'governance'
}, },
pluginEnv.alfrescoJsApi pluginEnv.alfrescoJsApi
); );

View File

@ -19,10 +19,12 @@
import { argv, exit } from 'node:process'; import { argv, exit } from 'node:process';
import { exec } from './exec'; import { exec } from './exec';
import program from 'commander'; import { Command } from 'commander';
import { logger } from './logger'; import { logger } from './logger';
import { resolve } from 'path'; import { resolve } from 'path';
const program = new Command();
// eslint-disable-next-line no-shadow // eslint-disable-next-line no-shadow
enum TARGETS { enum TARGETS {
publish = 'publish', publish = 'publish',

View File

@ -17,18 +17,21 @@
* limitations under the License. * limitations under the License.
*/ */
import program from 'commander'; import { Command } from 'commander';
import fetch from 'node-fetch'; import fetch from 'node-fetch';
import * as fs from 'fs'; import * as fs from 'fs';
import { logger } from './logger'; import { logger } from './logger';
import { AlfrescoApi, AlfrescoApiConfig } from '@alfresco/js-api'; import { AlfrescoApi, AlfrescoApiConfig } from '@alfresco/js-api';
import { argv, exit } from 'node:process'; import { argv, exit } from 'node:process';
const program = new Command();
const ACTIVITI_CLOUD_APPS = require('./resources').ACTIVITI_CLOUD_APPS; const ACTIVITI_CLOUD_APPS = require('./resources').ACTIVITI_CLOUD_APPS;
let alfrescoJsApiModeler: AlfrescoApi; let alfrescoJsApiModeler: AlfrescoApi;
let alfrescoJsApiDevops: AlfrescoApi; let alfrescoJsApiDevops: AlfrescoApi;
let args: ConfigArgs; let args: ConfigArgs;
let isValid = true; let isValid = true;
export interface ConfigArgs { export interface ConfigArgs {
modelerUsername: string; modelerUsername: string;
modelerPassword: string; modelerPassword: string;
@ -424,7 +427,7 @@ function deploy(model: any) {
* @param options token options * @param options token options
* @returns options * @returns options
*/ */
function initializeDefaultToken(options: any): any { function initializeDefaultToken(options: ConfigArgs): any {
options.tokenEndpoint = options.tokenEndpoint.replace('${clientId}', options.clientId); options.tokenEndpoint = options.tokenEndpoint.replace('${clientId}', options.clientId);
return options; return options;
} }
@ -680,18 +683,21 @@ async function getFileFromRemote(url: string, name: string): Promise<void> {
} }
return response; return response;
}) })
.then((response) => new Promise<void>((resolve, reject) => { .then(
const outputFile = fs.createWriteStream(`${name}.zip`); (response) =>
response.body.pipe(outputFile); new Promise<void>((resolve, reject) => {
outputFile.on('finish', () => { const outputFile = fs.createWriteStream(`${name}.zip`);
logger.info(`The file is finished downloading.`); response.body.pipe(outputFile);
resolve(); outputFile.on('finish', () => {
}); logger.info(`The file is finished downloading.`);
outputFile.on('error', (error) => { resolve();
logger.error(`Not possible to download the project form remote`); });
reject(error); outputFile.on('error', (error) => {
}); logger.error(`Not possible to download the project form remote`);
})) reject(error);
});
})
)
.catch((error) => { .catch((error) => {
logger.error(`Failed to fetch file from remote: ${error.message}`); logger.error(`Failed to fetch file from remote: ${error.message}`);
throw error; throw error;

View File

@ -17,10 +17,19 @@
import { AlfrescoApi, SharedlinksApi, FavoritesApi, NodesApi, UploadApi, NodeEntry } from '@alfresco/js-api'; import { AlfrescoApi, SharedlinksApi, FavoritesApi, NodesApi, UploadApi, NodeEntry } from '@alfresco/js-api';
import { exit, argv } from 'node:process'; import { exit, argv } from 'node:process';
const program = require('commander'); import { Command } from 'commander';
const fs = require('fs'); import { createReadStream } from 'fs';
const path = require('path'); import * as path from 'path';
import { logger } from './logger'; import { logger } from './logger';
interface InitAcsEnvArgs {
host?: string;
clientId?: string;
username?: string;
password?: string;
}
const program = new Command();
const MAX_RETRY = 10; const MAX_RETRY = 10;
let counter = 0; let counter = 0;
const TIMEOUT = 6000; const TIMEOUT = 6000;
@ -40,7 +49,8 @@ export default async function main() {
.option('-u, --username [type]', 'username ') .option('-u, --username [type]', 'username ')
.parse(argv); .parse(argv);
await checkEnv(); const opts = program.opts<InitAcsEnvArgs>();
await checkEnv(opts);
logger.info(`***** Step initialize ACS *****`); logger.info(`***** Step initialize ACS *****`);
await initializeDefaultFiles(); await initializeDefaultFiles();
@ -117,7 +127,7 @@ async function createFolder(folderName: string, parentId: string) {
*/ */
async function uploadFile(fileName: string, fileDestination: string): Promise<NodeEntry> { async function uploadFile(fileName: string, fileDestination: string): Promise<NodeEntry> {
const filePath = `../resources/content/${fileName}`; const filePath = `../resources/content/${fileName}`;
const file = fs.createReadStream(path.join(__dirname, filePath)); const file = createReadStream(path.join(__dirname, filePath));
let uploadedFile: NodeEntry; let uploadedFile: NodeEntry;
try { try {
uploadedFile = await new UploadApi(alfrescoJsApi).uploadFile(file, '', fileDestination, null, { uploadedFile = await new UploadApi(alfrescoJsApi).uploadFile(file, '', fileDestination, null, {
@ -192,23 +202,25 @@ async function favoriteFile(nodeId: string) {
/** /**
* Check environment state * Check environment state
*
* @param opts command options
*/ */
async function checkEnv() { async function checkEnv(opts: InitAcsEnvArgs) {
try { try {
alfrescoJsApi = new AlfrescoApi({ alfrescoJsApi = new AlfrescoApi({
provider: 'ALL', provider: 'ALL',
hostBpm: program.host, hostBpm: opts.host,
hostEcm: program.host, hostEcm: opts.host,
authType: 'OAUTH', authType: 'OAUTH',
oauth2: { oauth2: {
host: `${program.host}/auth/realms/alfresco`, host: `${opts.host}/auth/realms/alfresco`,
clientId: `${program.clientId}`, clientId: `${opts.clientId}`,
scope: 'openid', scope: 'openid',
redirectUri: '/' redirectUri: '/'
}, },
contextRoot: 'alfresco' contextRoot: 'alfresco'
}); });
await alfrescoJsApi.login(program.username, program.password); await alfrescoJsApi.login(opts.username, opts.password);
} catch (e) { } catch (e) {
if (e.error.code === 'ETIMEDOUT') { if (e.error.code === 'ETIMEDOUT') {
logger.error('The env is not reachable. Terminating'); logger.error('The env is not reachable. Terminating');
@ -222,12 +234,11 @@ async function checkEnv() {
} else { } else {
logger.error(`Retry in 1 minute attempt N ${counter}`); logger.error(`Retry in 1 minute attempt N ${counter}`);
sleep(TIMEOUT); sleep(TIMEOUT);
await checkEnv(); await checkEnv(opts);
} }
} }
} }
/** /**
* Perform a delay * Perform a delay
* *

View File

@ -15,14 +15,33 @@
* limitations under the License. * limitations under the License.
*/ */
import { AdminTenantsApi, AdminUsersApi, AlfrescoApi, TenantRepresentation, AppDefinitionsApi, RuntimeAppDefinitionsApi, UserRepresentation, AppDefinitionUpdateResultRepresentation } from '@alfresco/js-api'; import {
AdminTenantsApi,
AdminUsersApi,
AlfrescoApi,
TenantRepresentation,
AppDefinitionsApi,
RuntimeAppDefinitionsApi,
UserRepresentation,
AppDefinitionUpdateResultRepresentation
} from '@alfresco/js-api';
import { argv, exit } from 'node:process'; import { argv, exit } from 'node:process';
import { spawnSync } from 'node:child_process'; import { spawnSync } from 'node:child_process';
import { createReadStream } from 'node:fs'; import { createReadStream } from 'node:fs';
const program = require('commander'); import { Command } from 'commander';
const path = require('path'); import * as path from 'path';
import { logger } from './logger'; import { logger } from './logger';
const { throwError } = require('rxjs'); import { throwError } from 'rxjs';
interface InitApsEnvArgs {
host?: string;
clientId?: string;
username?: string;
password?: string;
license?: string;
}
const program = new Command();
const MAX_RETRY = 10; const MAX_RETRY = 10;
let counter = 0; let counter = 0;
const TIMEOUT = 6000; const TIMEOUT = 6000;
@ -37,7 +56,6 @@ let alfrescoJsApi: AlfrescoApi;
* Init APS command * Init APS command
*/ */
export default async function main() { export default async function main() {
program program
.version('0.1.0') .version('0.1.0')
.option('--host [type]', 'Remote environment host') .option('--host [type]', 'Remote environment host')
@ -47,23 +65,25 @@ export default async function main() {
.option('--license [type]', 'APS license S3 path ') .option('--license [type]', 'APS license S3 path ')
.parse(argv); .parse(argv);
await checkEnv(); const opts = program.opts<InitApsEnvArgs>();
await checkEnv(opts);
logger.info(`***** Step 1 - Check License *****`); logger.info(`***** Step 1 - Check License *****`);
let licenceUploaded = false; let licenceUploaded = false;
const hasValidLicense = await hasLicense() ; const hasValidLicense = await hasLicense(opts);
if (!hasValidLicense) { if (!hasValidLicense) {
logger.info(`Aps License missing`); logger.info(`Aps License missing`);
const isLicenseFileDownloaded = await downloadLicenseFile(program.license); const isLicenseFileDownloaded = await downloadLicenseFile(opts.license);
if (isLicenseFileDownloaded) { if (isLicenseFileDownloaded) {
licenceUploaded = await updateLicense(); licenceUploaded = await updateLicense(opts);
} }
} else { } else {
licenceUploaded = true; licenceUploaded = true;
logger.info(`Aps License present`); logger.info(`Aps License present`);
} }
let tenantId;
let tenantId: number;
if (licenceUploaded) { if (licenceUploaded) {
logger.info(`***** Step 2 - Check Tenant *****`); logger.info(`***** Step 2 - Check Tenant *****`);
logger.info(`is tenantId:${TENANT_DEFAULT_ID} with name:${TENANT_DEFAULT_NAME} present?`); logger.info(`is tenantId:${TENANT_DEFAULT_ID} with name:${TENANT_DEFAULT_NAME} present?`);
@ -75,13 +95,13 @@ export default async function main() {
tenantId = await createDefaultTenant(TENANT_DEFAULT_NAME); tenantId = await createDefaultTenant(TENANT_DEFAULT_NAME);
} }
logger.info(`***** Step 3 - Add Content Repo *****`); logger.info(`***** Step 3 - Add Content Repo *****`);
const isContentPresent = await isContentRepoPresent(TENANT_DEFAULT_ID, CONTENT_DEFAULT_NAME); const isContentPresent = await isContentRepoPresent(opts, TENANT_DEFAULT_ID, CONTENT_DEFAULT_NAME);
if (!isContentPresent) { if (!isContentPresent) {
logger.info(`No content repo with name ${CONTENT_DEFAULT_NAME} found`); logger.info(`No content repo with name ${CONTENT_DEFAULT_NAME} found`);
await addContentRepoWithBasic(TENANT_DEFAULT_ID, CONTENT_DEFAULT_NAME); await addContentRepoWithBasic(opts, TENANT_DEFAULT_ID, CONTENT_DEFAULT_NAME);
} }
logger.info(`***** Step 4 - Create users *****`); logger.info(`***** Step 4 - Create users *****`);
const users = await getDefaultApsUsersFromRealm(); const users = await getDefaultApsUsersFromRealm(opts);
if (tenantId && users && users.length > 0) { if (tenantId && users && users.length > 0) {
for (let i = 0; i < users.length; i++) { for (let i = 0; i < users.length; i++) {
await createUsers(tenantId, users[i]); await createUsers(tenantId, users[i]);
@ -89,19 +109,17 @@ export default async function main() {
for (let i = 0; i < users.length; i++) { for (let i = 0; i < users.length; i++) {
logger.info('Impersonate user: ' + users[i].username); logger.info('Impersonate user: ' + users[i].username);
await alfrescoJsApi.login(users[i].username, 'password'); await alfrescoJsApi.login(users[i].username, 'password');
await authorizeUserToContentRepo(users[i]); await authorizeUserToContentRepo(opts, users[i]);
const defaultUser = 'hruser'; const defaultUser = 'hruser';
if (users[i].username.includes(defaultUser)) { if (users[i].username.includes(defaultUser)) {
logger.info(`***** Step initialize APS apps for user ${defaultUser} *****`); logger.info(`***** Step initialize APS apps for user ${defaultUser} *****`);
await initializeDefaultApps(); await initializeDefaultApps();
} }
} }
} else { } else {
logger.info('Something went wrong. Was not able to create the users'); logger.info('Something went wrong. Was not able to create the users');
} }
} catch (error) { } catch (error) {
logger.info(`Aps something went wrong. Tenant id ${tenantId}`); logger.info(`Aps something went wrong. Tenant id ${tenantId}`);
exit(1); exit(1);
@ -110,7 +128,6 @@ export default async function main() {
logger.info('APS license error: check the configuration'); logger.info('APS license error: check the configuration');
exit(1); exit(1);
} }
} }
/** /**
@ -131,23 +148,25 @@ async function initializeDefaultApps() {
/** /**
* Check environment * Check environment
*
* @param opts command options
*/ */
async function checkEnv() { async function checkEnv(opts: InitApsEnvArgs) {
try { try {
alfrescoJsApi = new AlfrescoApi({ alfrescoJsApi = new AlfrescoApi({
provider: 'ALL', provider: 'ALL',
hostBpm: program.host, hostBpm: opts.host,
hostEcm: program.host, hostEcm: opts.host,
authType: 'OAUTH', authType: 'OAUTH',
contextRoot: 'alfresco', contextRoot: 'alfresco',
oauth2: { oauth2: {
host: `${program.host}/auth/realms/alfresco`, host: `${opts.host}/auth/realms/alfresco`,
clientId: `${program.clientId}`, clientId: `${opts.clientId}`,
scope: 'openid', scope: 'openid',
redirectUri: '/' redirectUri: '/'
} }
}); });
await alfrescoJsApi.login(program.username, program.password); await alfrescoJsApi.login(opts.username, opts.password);
} catch (e) { } catch (e) {
if (e.error.code === 'ETIMEDOUT') { if (e.error.code === 'ETIMEDOUT') {
logger.error('The env is not reachable. Terminating'); logger.error('The env is not reachable. Terminating');
@ -161,7 +180,7 @@ async function checkEnv() {
} else { } else {
logger.error(`Retry in 1 minute attempt N ${counter}`); logger.error(`Retry in 1 minute attempt N ${counter}`);
sleep(TIMEOUT); sleep(TIMEOUT);
await checkEnv(); await checkEnv(opts);
} }
} }
} }
@ -203,7 +222,7 @@ async function createDefaultTenant(tenantName: string) {
const tenantPost = { const tenantPost = {
active: true, active: true,
maxUsers: 10000, maxUsers: 10000,
name : tenantName name: tenantName
}; };
try { try {
@ -212,7 +231,7 @@ async function createDefaultTenant(tenantName: string) {
logger.info(`APS: Tenant ${tenantName} created with id: ${tenant.id}`); logger.info(`APS: Tenant ${tenantName} created with id: ${tenant.id}`);
return tenant.id; return tenant.id;
} catch (error) { } catch (error) {
logger.info(`APS: not able to create the default tenant: ${JSON.parse(error.message)}` ); logger.info(`APS: not able to create the default tenant: ${JSON.parse(error.message)}`);
return null; return null;
} }
} }
@ -242,19 +261,21 @@ async function createUsers(tenantId: number, user: any) {
logger.info(`APS: User ${userInfo.email} created with id: ${userInfo.id}`); logger.info(`APS: User ${userInfo.email} created with id: ${userInfo.id}`);
return user; return user;
} catch (error) { } catch (error) {
logger.info(`APS: not able to create the default user: ${error.message}` ); logger.info(`APS: not able to create the default user: ${error.message}`);
} }
} }
/** /**
* Update Activiti license * Update Activiti license
*
* @param opts command options
*/ */
async function updateLicense() { async function updateLicense(opts: InitApsEnvArgs) {
const fileContent = createReadStream(path.join(__dirname, '/activiti.lic')); const fileContent = createReadStream(path.join(__dirname, '/activiti.lic'));
try { try {
await alfrescoJsApi.oauth2Auth.callCustomApi( await alfrescoJsApi.oauth2Auth.callCustomApi(
`${program.host}/activiti-app/app/rest/license`, `${opts.host}/activiti-app/app/rest/license`,
'POST', 'POST',
{}, {},
{}, {},
@ -283,7 +304,7 @@ async function isDefaultAppDeployed(appName: string): Promise<boolean> {
try { try {
const runtimeAppDefinitionsApi = new RuntimeAppDefinitionsApi(alfrescoJsApi); const runtimeAppDefinitionsApi = new RuntimeAppDefinitionsApi(alfrescoJsApi);
const availableApps = await runtimeAppDefinitionsApi.getAppDefinitions(); const availableApps = await runtimeAppDefinitionsApi.getAppDefinitions();
const defaultApp = availableApps.data?.filter(app => app.name?.includes(appName)); const defaultApp = availableApps.data?.filter((app) => app.name?.includes(appName));
return defaultApp && defaultApp.length > 0; return defaultApp && defaultApp.length > 0;
} catch (error) { } catch (error) {
logger.error(`Aps app failed to import/Publish!`); logger.error(`Aps app failed to import/Publish!`);
@ -304,7 +325,7 @@ async function importPublishApp(appName: string): Promise<AppDefinitionUpdateRes
try { try {
const appDefinitionsApi = new AppDefinitionsApi(alfrescoJsApi); const appDefinitionsApi = new AppDefinitionsApi(alfrescoJsApi);
const result = await appDefinitionsApi.importAndPublishApp(fileContent, {renewIdmEntries: true}); const result = await appDefinitionsApi.importAndPublishApp(fileContent, { renewIdmEntries: true });
logger.info(`Aps app imported and published!`); logger.info(`Aps app imported and published!`);
return result; return result;
} catch (error) { } catch (error) {
@ -321,7 +342,7 @@ async function importPublishApp(appName: string): Promise<AppDefinitionUpdateRes
async function deployApp(appDefinitionId: number) { async function deployApp(appDefinitionId: number) {
logger.info(`Deploy app with id ${appDefinitionId}`); logger.info(`Deploy app with id ${appDefinitionId}`);
const body = { const body = {
appDefinitions: [{id: appDefinitionId}] appDefinitions: [{ id: appDefinitionId }]
}; };
try { try {
@ -335,11 +356,13 @@ async function deployApp(appDefinitionId: number) {
/** /**
* Checks if Activiti app has license * Checks if Activiti app has license
*
* @param opts command options
*/ */
async function hasLicense(): Promise<boolean> { async function hasLicense(opts: InitApsEnvArgs): Promise<boolean> {
try { try {
const license = await alfrescoJsApi.oauth2Auth.callCustomApi( const license = await alfrescoJsApi.oauth2Auth.callCustomApi(
`${program.host}/activiti-app/app/rest/license`, `${opts.host}/activiti-app/app/rest/license`,
'GET', 'GET',
{}, {},
{}, {},
@ -356,18 +379,20 @@ async function hasLicense(): Promise<boolean> {
logger.info(`Aps does NOT have a valid License!`); logger.info(`Aps does NOT have a valid License!`);
return false; return false;
} catch (error) { } catch (error) {
logger.error(`Aps not able to check the license` ); logger.error(`Aps not able to check the license`);
return false; return false;
} }
} }
/** /**
* Get default users from the realm * Get default users from the realm
*
* @param opts command options
*/ */
async function getDefaultApsUsersFromRealm() { async function getDefaultApsUsersFromRealm(opts: InitApsEnvArgs) {
try { try {
const users: any[] = await alfrescoJsApi.oauth2Auth.callCustomApi( const users: any[] = await alfrescoJsApi.oauth2Auth.callCustomApi(
`${program.host}/auth/admin/realms/alfresco/users`, `${opts.host}/auth/admin/realms/alfresco/users`,
'GET', 'GET',
{}, {},
{ max: 1000 }, { max: 1000 },
@ -378,11 +403,11 @@ async function getDefaultApsUsersFromRealm() {
['application/json'] ['application/json']
); );
const usernamesOfApsDefaultUsers = ['hruser', 'salesuser', 'superadminuser']; const usernamesOfApsDefaultUsers = ['hruser', 'salesuser', 'superadminuser'];
const apsDefaultUsers = users.filter(user => usernamesOfApsDefaultUsers.includes(user.username)); const apsDefaultUsers = users.filter((user) => usernamesOfApsDefaultUsers.includes(user.username));
logger.info(`Keycloak found ${apsDefaultUsers.length} users`); logger.info(`Keycloak found ${apsDefaultUsers.length} users`);
return apsDefaultUsers; return apsDefaultUsers;
} catch (error) { } catch (error) {
logger.error(`APS: not able to fetch user: ${error.message}` ); logger.error(`APS: not able to fetch user: ${error.message}`);
return null; return null;
} }
} }
@ -390,13 +415,14 @@ async function getDefaultApsUsersFromRealm() {
/** /**
* Validate that ACS repo for Activiti is present * Validate that ACS repo for Activiti is present
* *
* @param opts command options
* @param tenantId tenant id * @param tenantId tenant id
* @param contentName content service name * @param contentName content service name
*/ */
async function isContentRepoPresent(tenantId: number, contentName: string): Promise<boolean> { async function isContentRepoPresent(opts: InitApsEnvArgs, tenantId: number, contentName: string): Promise<boolean> {
try { try {
const contentRepos = await alfrescoJsApi.oauth2Auth.callCustomApi( const contentRepos = await alfrescoJsApi.oauth2Auth.callCustomApi(
`${program.host}/activiti-app/app/rest/integration/alfresco?tenantId=${tenantId}`, `${opts.host}/activiti-app/app/rest/integration/alfresco?tenantId=${tenantId}`,
'GET', 'GET',
{}, {},
{}, {},
@ -406,9 +432,9 @@ async function isContentRepoPresent(tenantId: number, contentName: string): Prom
['application/json'], ['application/json'],
['application/json'] ['application/json']
); );
return !!contentRepos.data.find(repo => repo.name === contentName); return !!contentRepos.data.find((repo) => repo.name === contentName);
} catch (error) { } catch (error) {
logger.error(`APS: not able to create content: ${error.message}` ); logger.error(`APS: not able to create content: ${error.message}`);
return null; return null;
} }
} }
@ -416,18 +442,19 @@ async function isContentRepoPresent(tenantId: number, contentName: string): Prom
/** /**
* Add content service with basic auth * Add content service with basic auth
* *
* @param opts command options
* @param tenantId tenant id * @param tenantId tenant id
* @param name content name * @param name content name
*/ */
async function addContentRepoWithBasic(tenantId: number, name: string) { async function addContentRepoWithBasic(opts: InitApsEnvArgs, tenantId: number, name: string) {
logger.info(`Create Content with name ${name} and basic auth`); logger.info(`Create Content with name ${name} and basic auth`);
const body = { const body = {
alfrescoTenantId: '', alfrescoTenantId: '',
authenticationType: 'basic', authenticationType: 'basic',
name, name,
repositoryUrl: `${program.host}/alfresco`, repositoryUrl: `${opts.host}/alfresco`,
shareUrl: `${program.host}/share`, shareUrl: `${opts.host}/share`,
// sitesFolder: '', not working on activiti 1.11.1.1 // sitesFolder: '', not working on activiti 1.11.1.1
tenantId, tenantId,
version: '6.1.1' version: '6.1.1'
@ -435,7 +462,7 @@ async function addContentRepoWithBasic(tenantId: number, name: string) {
try { try {
const content = await alfrescoJsApi.oauth2Auth.callCustomApi( const content = await alfrescoJsApi.oauth2Auth.callCustomApi(
`${program.host}/activiti-app/app/rest/integration/alfresco`, `${opts.host}/activiti-app/app/rest/integration/alfresco`,
'POST', 'POST',
{}, {},
{}, {},
@ -448,20 +475,21 @@ async function addContentRepoWithBasic(tenantId: number, name: string) {
logger.info(`Content created!`); logger.info(`Content created!`);
return content; return content;
} catch (error) { } catch (error) {
logger.error(`APS: not able to create content: ${error.message}` ); logger.error(`APS: not able to create content: ${error.message}`);
} }
} }
/** /**
* Authorize activiti user to ACS repo * Authorize activiti user to ACS repo
* *
* @param opts command options
* @param user user object * @param user user object
*/ */
async function authorizeUserToContentRepo(user: any) { async function authorizeUserToContentRepo(opts: InitApsEnvArgs, user: any) {
logger.info(`Authorize user ${user.email}`); logger.info(`Authorize user ${user.email}`);
try { try {
const content = await alfrescoJsApi.oauth2Auth.callCustomApi( const content = await alfrescoJsApi.oauth2Auth.callCustomApi(
`${program.host}/activiti-app/app/rest/integration/alfresco`, `${opts.host}/activiti-app/app/rest/integration/alfresco`,
'GET', 'GET',
{}, {},
{}, {},
@ -475,28 +503,29 @@ async function authorizeUserToContentRepo(user: any) {
if (content.data) { if (content.data) {
for (let i = 0; i < content.data.length; i++) { for (let i = 0; i < content.data.length; i++) {
if (content.data[i].authenticationType === 'basic') { if (content.data[i].authenticationType === 'basic') {
await authorizeUserToContentWithBasic(user.username, content.data[i].id); await authorizeUserToContentWithBasic(opts, user.username, content.data[i].id);
} }
} }
} }
return; return;
} catch (error) { } catch (error) {
logger.error(`APS: not able to authorize content: ${error.message}` ); logger.error(`APS: not able to authorize content: ${error.message}`);
} }
} }
/** /**
* Authorize user with content using basic auth * Authorize user with content using basic auth
* *
* @param opts command options
* @param username username * @param username username
* @param contentId content id * @param contentId content id
*/ */
async function authorizeUserToContentWithBasic(username: string, contentId: string) { async function authorizeUserToContentWithBasic(opts: InitApsEnvArgs, username: string, contentId: string) {
logger.info(`Authorize ${username} on contentId: ${contentId} in basic auth`); logger.info(`Authorize ${username} on contentId: ${contentId} in basic auth`);
try { try {
const body = {username, password: 'password'}; const body = { username, password: 'password' };
const content = await alfrescoJsApi.oauth2Auth.callCustomApi( const content = await alfrescoJsApi.oauth2Auth.callCustomApi(
`${program.host}/activiti-app/app/rest/integration/alfresco/${contentId}/account`, `${opts.host}/activiti-app/app/rest/integration/alfresco/${contentId}/account`,
'POST', 'POST',
{}, {},
{}, {},
@ -509,7 +538,7 @@ async function authorizeUserToContentWithBasic(username: string, contentId: stri
logger.info(`User authorized!`); logger.info(`User authorized!`);
return content; return content;
} catch (error) { } catch (error) {
logger.error(`APS: not able to authorize content: ${error.message}` ); logger.error(`APS: not able to authorize content: ${error.message}`);
} }
} }
@ -519,12 +548,7 @@ async function authorizeUserToContentWithBasic(username: string, contentId: stri
* @param apsLicensePath path to license file * @param apsLicensePath path to license file
*/ */
async function downloadLicenseFile(apsLicensePath: string) { async function downloadLicenseFile(apsLicensePath: string) {
const args = [ const args = [`s3`, `cp`, apsLicensePath, `./`];
`s3`,
`cp`,
apsLicensePath,
`./`
];
const result = spawnSync(`aws`, args, { const result = spawnSync(`aws`, args, {
cwd: path.resolve(__dirname, `./`), cwd: path.resolve(__dirname, `./`),
shell: false shell: false
@ -545,5 +569,5 @@ async function downloadLicenseFile(apsLicensePath: string) {
*/ */
function sleep(delay: number) { function sleep(delay: number) {
const start = new Date().getTime(); const start = new Date().getTime();
while (new Date().getTime() < start + delay) { } while (new Date().getTime() < start + delay) {}
} }

View File

@ -23,7 +23,14 @@ import * as fs from 'fs';
import * as checker from 'license-checker'; import * as checker from 'license-checker';
import * as licenseList from 'spdx-license-list'; import * as licenseList from 'spdx-license-list';
import * as ejs from 'ejs'; import * as ejs from 'ejs';
import program from 'commander'; import { Command } from 'commander';
const program = new Command();
interface LicensesCommandArgs {
package?: string;
outDir?: string;
}
interface PackageInfo { interface PackageInfo {
name: string; name: string;
@ -110,10 +117,11 @@ export default function main(_args: string[], workingDir: string) {
exit(0); exit(0);
} }
const options = program.opts<LicensesCommandArgs>();
let packagePath = path.resolve(workingDir, 'package.json'); let packagePath = path.resolve(workingDir, 'package.json');
if (program.package) { if (options.package) {
packagePath = path.resolve(program.package); packagePath = path.resolve(options.package);
} }
if (!fs.existsSync(packagePath)) { if (!fs.existsSync(packagePath)) {
@ -183,7 +191,7 @@ export default function main(_args: string[], workingDir: string) {
console.error(ejsError); console.error(ejsError);
reject(ejsError); reject(ejsError);
} else { } else {
const outputPath = path.resolve(program.outDir || workingDir); const outputPath = path.resolve(options.outDir || workingDir);
const outputFile = path.join(outputPath, `license-info-${packageJson.version}.md`); const outputFile = path.join(outputPath, `license-info-${packageJson.version}.md`);
fs.writeFileSync(outputFile, mdText); fs.writeFileSync(outputFile, mdText);

View File

@ -17,7 +17,7 @@
import { AlfrescoApi } from '@alfresco/js-api'; import { AlfrescoApi } from '@alfresco/js-api';
import { exit } from 'node:process'; import { exit } from 'node:process';
import { logger } from './../logger'; import { logger } from '../logger';
const TIMEOUT = 6000; const TIMEOUT = 6000;
const MAX_RETRY = 10; const MAX_RETRY = 10;

View File

@ -15,13 +15,6 @@
* limitations under the License. * limitations under the License.
*/ */
// eslint-disable-next-line no-shadow
export enum PluginTarget {
processService = 'processService',
processAutomation = 'processAutomation',
governance = 'governance'
}
export interface PluginInterface { export interface PluginInterface {
name: string; name: string;
host: string; host: string;

18
package-lock.json generated
View File

@ -90,7 +90,7 @@
"@typescript-eslint/parser": "5.62.0", "@typescript-eslint/parser": "5.62.0",
"@typescript-eslint/typescript-estree": "7.1.1", "@typescript-eslint/typescript-estree": "7.1.1",
"ajv": "^8.12.0", "ajv": "^8.12.0",
"commander": "6.2.1", "commander": "12.0.0",
"css-loader": "^6.10.0", "css-loader": "^6.10.0",
"dotenv": "16.1.3", "dotenv": "16.1.3",
"editorjs-html": "3.4.3", "editorjs-html": "3.4.3",
@ -19004,6 +19004,15 @@
"node": ">=7.0.0" "node": ">=7.0.0"
} }
}, },
"node_modules/@storybook/core/node_modules/commander": {
"version": "6.2.1",
"resolved": "https://registry.npmjs.org/commander/-/commander-6.2.1.tgz",
"integrity": "sha512-U7VdrJFnJgo4xjrHpTzu0yrHPGImdsmD95ZlgYSEajAn2JKzDhDTPG9kBTefmObL2w/ngeZnilk+OV9CG3d7UA==",
"dev": true,
"engines": {
"node": ">= 6"
}
},
"node_modules/@storybook/core/node_modules/cosmiconfig": { "node_modules/@storybook/core/node_modules/cosmiconfig": {
"version": "6.0.0", "version": "6.0.0",
"resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-6.0.0.tgz", "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-6.0.0.tgz",
@ -27780,11 +27789,12 @@
} }
}, },
"node_modules/commander": { "node_modules/commander": {
"version": "6.2.1", "version": "12.0.0",
"resolved": "https://registry.npmjs.org/commander/-/commander-12.0.0.tgz",
"integrity": "sha512-MwVNWlYjDTtOjX5PiD7o5pK0UrFU/OYgcJfjjK4RaHZETNtjJqrZa9Y9ds88+A+f+d5lv+561eZ+yCKoS3gbAA==",
"dev": true, "dev": true,
"license": "MIT",
"engines": { "engines": {
"node": ">= 6" "node": ">=18"
} }
}, },
"node_modules/comment-json": { "node_modules/comment-json": {

View File

@ -135,7 +135,7 @@
"@typescript-eslint/parser": "5.62.0", "@typescript-eslint/parser": "5.62.0",
"@typescript-eslint/typescript-estree": "7.1.1", "@typescript-eslint/typescript-estree": "7.1.1",
"ajv": "^8.12.0", "ajv": "^8.12.0",
"commander": "6.2.1", "commander": "12.0.0",
"css-loader": "^6.10.0", "css-loader": "^6.10.0",
"dotenv": "16.1.3", "dotenv": "16.1.3",
"editorjs-html": "3.4.3", "editorjs-html": "3.4.3",