Skip to content

Commit

Permalink
chore: port validation and configOptions to TS (#1309)
Browse files Browse the repository at this point in the history
  • Loading branch information
brandenrodgers authored Dec 20, 2024
1 parent a20161b commit fafbd92
Show file tree
Hide file tree
Showing 3 changed files with 93 additions and 94 deletions.
2 changes: 1 addition & 1 deletion lang/en.lyaml
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ en:
defaultMode:
describe: "Set the default CMS publish mode"
promptMessage: "Select CMS publish mode to be used as the default"
error: "The CMS publish mode \"{{ mode }}\" is invalid. Valid values are {{ validModes }}."
error: "The provided CMS publish mode is invalid. Valid values are {{ validModes }}."
success: "Default mode updated to: {{ mode }}"
allowUsageTracking:
describe: "Enable or disable usage tracking"
Expand Down
102 changes: 56 additions & 46 deletions lib/configOptions.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,22 @@
// @ts-nocheck
const { logger } = require('@hubspot/local-dev-lib/logger');
const {
import { logger } from '@hubspot/local-dev-lib/logger';
import {
updateAllowUsageTracking,
updateDefaultCmsPublishMode,
updateHttpTimeout,
} = require('@hubspot/local-dev-lib/config');
const { CMS_PUBLISH_MODE } = require('@hubspot/local-dev-lib/constants/files');
const { commaSeparatedValues } = require('@hubspot/local-dev-lib/text');
const { trackCommandUsage } = require('./usageTracking');
const { promptUser } = require('./prompts/promptUtils');
const { i18n } = require('../lib/lang');
} from '@hubspot/local-dev-lib/config';
import { CmsPublishMode } from '@hubspot/local-dev-lib/types/Files';
import { CMS_PUBLISH_MODE } from '@hubspot/local-dev-lib/constants/files';
import { commaSeparatedValues } from '@hubspot/local-dev-lib/text';
import { trackCommandUsage } from './usageTracking';
import { promptUser } from './prompts/promptUtils';
import { i18n } from '../lib/lang';

const i18nKey = 'commands.config.subcommands.set.options';

const enableOrDisableUsageTracking = async () => {
const { isEnabled } = await promptUser([
async function enableOrDisableUsageTracking(): Promise<boolean> {
const { isEnabled } = await promptUser<{ isEnabled: boolean }>([
{
type: 'list',
look: false,
name: 'isEnabled',
pageSize: 20,
message: i18n(`${i18nKey}.allowUsageTracking.promptMessage`),
Expand All @@ -36,12 +35,18 @@ const enableOrDisableUsageTracking = async () => {
]);

return isEnabled;
};
}

const setAllowUsageTracking = async ({ accountId, allowUsageTracking }) => {
trackCommandUsage('config-set-allow-usage-tracking', null, accountId);
export async function setAllowUsageTracking({
accountId,
allowUsageTracking,
}: {
accountId: number;
allowUsageTracking?: boolean;
}): Promise<void> {
trackCommandUsage('config-set-allow-usage-tracking', undefined, accountId);

let isEnabled;
let isEnabled: boolean;

if (typeof allowUsageTracking === 'boolean') {
isEnabled = allowUsageTracking;
Expand All @@ -51,18 +56,21 @@ const setAllowUsageTracking = async ({ accountId, allowUsageTracking }) => {

updateAllowUsageTracking(isEnabled);

return logger.log(
i18n(`${i18nKey}.allowUsageTracking.success`, { isEnabled })
logger.success(
i18n(`${i18nKey}.allowUsageTracking.success`, {
isEnabled: isEnabled.toString(),
})
);
};
}

const ALL_CMS_PUBLISH_MODES = Object.values(CMS_PUBLISH_MODE);

const selectCmsPublishMode = async () => {
const { cmsPublishMode } = await promptUser([
async function selectCmsPublishMode(): Promise<CmsPublishMode> {
const { cmsPublishMode } = await promptUser<{
cmsPublishMode: CmsPublishMode;
}>([
{
type: 'list',
look: false,
name: 'cmsPublishMode',
pageSize: 20,
message: i18n(`${i18nKey}.defaultMode.promptMessage`),
Expand All @@ -72,15 +80,18 @@ const selectCmsPublishMode = async () => {
]);

return cmsPublishMode;
};
}

const setDefaultCmsPublishMode = async ({
export async function setDefaultCmsPublishMode({
accountId,
defaultCmsPublishMode,
}) => {
trackCommandUsage('config-set-default-mode', null, accountId);
}: {
accountId: number;
defaultCmsPublishMode?: CmsPublishMode;
}): Promise<void> {
trackCommandUsage('config-set-default-mode', undefined, accountId);

let newDefault;
let newDefault: CmsPublishMode;

if (!defaultCmsPublishMode) {
newDefault = await selectCmsPublishMode();
Expand All @@ -91,25 +102,24 @@ const setDefaultCmsPublishMode = async ({
newDefault = defaultCmsPublishMode;
} else {
logger.error(
i18n(`${i18nKey}.defaultMode.errors`, {
mode: newDefault,
i18n(`${i18nKey}.defaultMode.error`, {
validModes: commaSeparatedValues(ALL_CMS_PUBLISH_MODES),
})
);
newDefault = await selectCMsPublishMode();
newDefault = await selectCmsPublishMode();
}

updateDefaultCmsPublishMode(newDefault);

return logger.success(
logger.success(
i18n(`${i18nKey}.defaultMode.success`, {
mode: newDefault,
})
);
};
}

const enterTimeout = async () => {
const { timeout } = await promptUser([
async function enterTimeout(): Promise<string> {
const { timeout } = await promptUser<{ timeout: string }>([
{
name: 'timeout',
message: i18n(`${i18nKey}.httpTimeout.promptMessage`),
Expand All @@ -119,12 +129,18 @@ const enterTimeout = async () => {
]);

return timeout;
};
}

const setHttpTimeout = async ({ accountId, httpTimeout }) => {
trackCommandUsage('config-set-http-timeout', null, accountId);
export async function setHttpTimeout({
accountId,
httpTimeout,
}: {
accountId: number;
httpTimeout?: string;
}): Promise<void> {
trackCommandUsage('config-set-http-timeout', undefined, accountId);

let newHttpTimeout;
let newHttpTimeout: string;

if (!httpTimeout) {
newHttpTimeout = await enterTimeout();
Expand All @@ -134,13 +150,7 @@ const setHttpTimeout = async ({ accountId, httpTimeout }) => {

updateHttpTimeout(newHttpTimeout);

return logger.success(
logger.success(
i18n(`${i18nKey}.httpTimeout.success`, { timeout: newHttpTimeout })
);
};

module.exports = {
setAllowUsageTracking,
setDefaultCmsPublishMode,
setHttpTimeout,
};
}
83 changes: 36 additions & 47 deletions lib/validation.ts
Original file line number Diff line number Diff line change
@@ -1,39 +1,33 @@
// @ts-nocheck
const fs = require('fs');
const path = require('path');
const { logger } = require('@hubspot/local-dev-lib/logger');
const { CMS_PUBLISH_MODE } = require('@hubspot/local-dev-lib/constants/files');
const {
import * as fs from 'fs';
import * as path from 'path';
import { Arguments } from 'yargs';
import { logger } from '@hubspot/local-dev-lib/logger';
import { CMS_PUBLISH_MODE } from '@hubspot/local-dev-lib/constants/files';
import { CmsPublishMode } from '@hubspot/local-dev-lib/types/Files';
import {
API_KEY_AUTH_METHOD,
OAUTH_AUTH_METHOD,
PERSONAL_ACCESS_KEY_AUTH_METHOD,
} = require('@hubspot/local-dev-lib/constants/auth');
const { commaSeparatedValues } = require('@hubspot/local-dev-lib/text');
const {
} from '@hubspot/local-dev-lib/constants/auth';
import { commaSeparatedValues } from '@hubspot/local-dev-lib/text';
import {
getConfigPath,
getAccountConfig,
loadConfigFromEnvironment,
} = require('@hubspot/local-dev-lib/config');
const { getOauthManager } = require('@hubspot/local-dev-lib/oauth');
const {
accessTokenForPersonalAccessKey,
} = require('@hubspot/local-dev-lib/personalAccessKey');
const {
} from '@hubspot/local-dev-lib/config';
import { getOauthManager } from '@hubspot/local-dev-lib/oauth';
import { accessTokenForPersonalAccessKey } from '@hubspot/local-dev-lib/personalAccessKey';
import {
getAbsoluteFilePath,
getCwd,
getExt,
} = require('@hubspot/local-dev-lib/path');
const { getAccountId, getCmsPublishMode } = require('./commonOpts');
const { logError } = require('./errorHandlers/index');

/**
* Validate that an account was passed to the command and that the account's configuration is valid
*
*
* @param {object} command options
* @returns {boolean}
*/
async function validateAccount(options) {
} from '@hubspot/local-dev-lib/path';
import { getAccountId, getCmsPublishMode } from './commonOpts';
import { logError } from './errorHandlers/index';

export async function validateAccount(
options: Arguments<{ account?: string; accountId?: string }>
): Promise<boolean> {
const accountId = getAccountId(options);
const { accountId: accountIdOption, account: accountOption } = options;

Expand Down Expand Up @@ -100,15 +94,19 @@ async function validateAccount(options) {

const oauth = getOauthManager(accountId, accountConfig);
try {
const accessToken = await oauth.accessToken();
let accessToken: string | undefined;

if (oauth) {
accessToken = await oauth.accessToken();
}
if (!accessToken) {
logger.error(
`The OAuth2 access token could not be found for accountId ${accountId}`
);
return false;
}
} catch (e) {
logger.error(e.message);
logError(e);
return false;
}
} else if (authType === 'personalaccesskey') {
Expand Down Expand Up @@ -141,11 +139,9 @@ async function validateAccount(options) {
return true;
}

/**
* @param {object} command options
* @returns {boolean}
*/
function validateCmsPublishMode(options) {
export function validateCmsPublishMode(
options: Arguments<{ cmsPublishMode?: CmsPublishMode }>
): boolean {
const cmsPublishMode = getCmsPublishMode(options);
if (CMS_PUBLISH_MODE[cmsPublishMode]) {
return true;
Expand All @@ -168,8 +164,8 @@ function validateCmsPublishMode(options) {
return false;
}

const fileExists = _path => {
let isFile;
export function fileExists(_path: string): boolean {
let isFile: boolean;
try {
const absoluteSrcPath = path.resolve(getCwd(), _path);
if (!absoluteSrcPath) return false;
Expand All @@ -187,11 +183,11 @@ const fileExists = _path => {
}

return true;
};
}

const checkAndConvertToJson = _path => {
export function checkAndConvertToJson(_path: string): object | null {
const filePath = getAbsoluteFilePath(_path);
if (!fileExists(filePath)) return false;
if (!fileExists(filePath)) return null;

if (getExt(_path) !== 'json') {
logger.error(`The file "${_path}" must be a valid JSON file`);
Expand All @@ -208,11 +204,4 @@ const checkAndConvertToJson = _path => {
}

return result;
};

module.exports = {
validateCmsPublishMode,
validateAccount,
checkAndConvertToJson,
fileExists,
};
}

0 comments on commit fafbd92

Please sign in to comment.