Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

port validation and configOptions to TS #1309

Merged
merged 6 commits into from
Dec 20, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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',
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

look does not exist as a supported field (search in repo)

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),
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We were using the wrong lang key, and newDefault is undefined here

})
);
newDefault = await selectCMsPublishMode();
newDefault = await selectCmsPublishMode();
}
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We had a casing issue here that TS picked up 🎉


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 })
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's no need for any of these to return

);
};

module.exports = {
setAllowUsageTracking,
setDefaultCmsPublishMode,
setHttpTimeout,
};
}
89 changes: 40 additions & 49 deletions lib/validation.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,36 @@
// @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,
validateConfig,
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 { EXIT_CODES } = require('./enums/exitCodes');
const { logError } = require('./errorHandlers/index');

async function loadAndValidateOptions(options, shouldValidateAccount = true) {
} from '@hubspot/local-dev-lib/path';
import { getAccountId, getCmsPublishMode } from './commonOpts';
import { EXIT_CODES } from './enums/exitCodes';
import { logError } from './errorHandlers/index';

export async function loadAndValidateOptions(
options: Arguments<{ account?: string; accountId?: string }>,
shouldValidateAccount = true
): Promise<void> {
let validAccount = true;
if (shouldValidateAccount) {
validAccount = await validateAccount(options);
Expand All @@ -39,14 +41,9 @@ async function loadAndValidateOptions(options, shouldValidateAccount = true) {
}
}

/**
* 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) {
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 @@ -113,15 +110,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 @@ -154,11 +155,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 @@ -181,8 +180,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 @@ -200,9 +199,9 @@ const fileExists = _path => {
}

return true;
};
}

const checkAndConvertToJson = _path => {
export function checkAndConvertToJson(_path: string): object | boolean | null {
const filePath = getAbsoluteFilePath(_path);
brandenrodgers marked this conversation as resolved.
Show resolved Hide resolved
if (!fileExists(filePath)) return false;

Expand All @@ -221,12 +220,4 @@ const checkAndConvertToJson = _path => {
}

return result;
};

module.exports = {
validateCmsPublishMode,
validateAccount,
checkAndConvertToJson,
fileExists,
loadAndValidateOptions,
};
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"license": "Apache-2.0",
"repository": "https://github.com/HubSpot/hubspot-cli",
"dependencies": {
"@hubspot/local-dev-lib": "3.0.1",
"@hubspot/local-dev-lib": "3.1.0",
"@hubspot/serverless-dev-runtime": "7.0.0",
"@hubspot/theme-preview-dev-server": "0.0.10",
"@hubspot/ui-extensions-dev-server": "0.8.33",
Expand Down
8 changes: 4 additions & 4 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1463,10 +1463,10 @@
semver "^6.3.0"
unixify "^1.0.0"

"@hubspot/local-dev-lib@3.0.1":
version "3.0.1"
resolved "https://registry.yarnpkg.com/@hubspot/local-dev-lib/-/local-dev-lib-3.0.1.tgz#1dd22f439d6e262353f14915a354115bbc1f5f76"
integrity sha512-h1jOmZJNdHZFbrOA5Gn815YCsix8eY81A4dkrUuDZI4MzVaJH3o4RoRalMl+Hr2e35nDrbrbcIR1RMQADPSmwg==
"@hubspot/local-dev-lib@3.1.0":
version "3.1.0"
resolved "https://registry.yarnpkg.com/@hubspot/local-dev-lib/-/local-dev-lib-3.1.0.tgz#76b5d524aa694aad2bfc6e199ee1dac314f15774"
integrity sha512-iop3PgZ0ZWejCH6PmSeYnnGwV8vGIuA4F+w7SxukdX3QfhivlczClATWPaZanv1CYJHdflqoItq1kdF8ASJJmA==
dependencies:
address "^2.0.1"
axios "^1.3.5"
Expand Down
Loading