@kadena/kadena-cli
Version:
Kadena CLI tool to interact with the Kadena blockchain (manage keys, transactions, etc.)
220 lines • 9.65 kB
JavaScript
import { z } from 'zod';
import { chainIdValidation } from '../commands/account/utils/accountHelpers.js';
import { ensureNetworksConfiguration, getNetworksInOrder, loadNetworkConfig, } from '../commands/networks/utils/networkHelpers.js';
import { getNetworkDirectory } from '../commands/networks/utils/networkPath.js';
import { MAX_CHAIN_VALUE } from '../constants/config.js';
import { INVALID_FILE_NAME_ERROR_MSG } from '../constants/global.js';
import { NO_NETWORKS_FOUND_ERROR_MESSAGE } from '../constants/networks.js';
import { services } from '../services/index.js';
import { isNotEmptyString, isValidFilename } from '../utils/globalHelpers.js';
import { getExistingNetworks } from '../utils/helpers.js';
import { input, select } from '../utils/prompts.js';
import { getInputPrompt } from './generic.js'; // Importing getInputPrompt from another file
export const chainIdPrompt = async (previousQuestions, args, isOptional) => {
const defaultValue = args.defaultValue || '0';
return (await input({
message: `Enter ChainId (0-${MAX_CHAIN_VALUE}):`,
default: defaultValue,
validate: function (input) {
const chainId = parseInt(input.trim(), 10);
const result = chainIdValidation.safeParse(chainId);
if (!result.success) {
const formatted = result.error.format();
return `ChainId: ${formatted._errors[0]}`;
}
return true;
},
}));
};
export const networkNamePrompt = async (previousQuestions, args, isOptional) => {
const defaultValue = previousQuestions.network || undefined;
return await input({
message: 'Enter a network name (e.g. "mainnet"):',
default: defaultValue,
validate: function (input) {
if (!isNotEmptyString(input.trim()))
return 'Network name is required.';
if (!isValidFilename(input)) {
return `Name is used as a filename. ${INVALID_FILE_NAME_ERROR_MSG}`;
}
return true;
},
});
};
export const networkIdPrompt = async (previousQuestions, args, isOptional) => {
var _a;
const defaultValue = ((_a = args.defaultValue) !== null && _a !== void 0 ? _a : previousQuestions.defaultValue);
const validate = function (input) {
if (isOptional)
return true;
if (!isNotEmptyString(input.trim()))
return 'Network id is required.';
return true;
};
return await getInputPrompt('Enter a network id (e.g. "mainnet01"):', defaultValue, validate);
};
export const networkHostPrompt = async (previousQuestions, args, isOptional) => {
var _a;
const defaultValue = ((_a = args.defaultValue) !== null && _a !== void 0 ? _a : previousQuestions.defaultValue);
const validate = function (input) {
if (isOptional && !isNotEmptyString(input.trim()))
return true;
const parse = z.string().url().safeParse(input);
if (!parse.success)
return 'Network host: Invalid URL. Please enter a valid URL.';
return true;
};
return await getInputPrompt('Enter Kadena network host (e.g. "https://api.chainweb.com"):', defaultValue, validate);
};
export const networkExplorerUrlPrompt = async (previousQuestions, args, isOptional) => {
var _a;
const defaultValue = ((_a = args.defaultValue) !== null && _a !== void 0 ? _a : previousQuestions.defaultValue);
return await getInputPrompt('Enter Kadena network explorer URL (e.g. "https://explorer.chainweb.com/mainnet/tx/"):', defaultValue);
};
export const networkOverwritePrompt = async (previousQuestions, args, isOptional) => {
var _a, _b;
const networkName = (_b = (_a = args.defaultValue) !== null && _a !== void 0 ? _a : previousQuestions.networkName) !== null && _b !== void 0 ? _b : args.networkName;
if (networkName === undefined) {
throw new Error('Network name is required for the overwrite prompt.');
}
const message = `Are you sure you want to save this configuration for network "${networkName}"?`;
return await select({
message,
choices: [
{ value: 'yes', name: 'Yes' },
{ value: 'no', name: 'No' },
],
});
};
export const networkSelectPrompt = async (prev, args, isOptional) => {
var _a;
const networkText = (_a = args.networkText) !== null && _a !== void 0 ? _a : 'Select a network:';
const existingNetworks = await getExistingNetworks();
const allowedNetworks = prev.allowedNetworks !== undefined
? prev.allowedNetworks
: [];
const filteredNetworks = existingNetworks.filter((network) => {
var _a;
return allowedNetworks.length > 0
? allowedNetworks.includes((_a = network.name) !== null && _a !== void 0 ? _a : '')
: true;
});
if (!filteredNetworks.length) {
throw new Error(NO_NETWORKS_FOUND_ERROR_MESSAGE);
}
const networksInOrder = await getNetworksInOrder(filteredNetworks);
const choices = networksInOrder.map((network) => ({
value: network.value,
name: network.name,
}));
if (isOptional === true) {
choices.unshift({
value: 'skip',
name: 'Network is optional. Continue to next step',
});
}
const selectedNetwork = await select({
message: networkText,
choices: choices,
});
return selectedNetwork;
};
const getEnsureExistingNetworks = async () => {
const kadenaDir = services.config.getDirectory();
const networkDir = getNetworkDirectory();
const isNetworksFolderExists = await services.filesystem.directoryExists(networkDir);
if (!isNetworksFolderExists ||
(await services.filesystem.readDir(networkDir)).length === 0) {
await ensureNetworksConfiguration(kadenaDir);
}
const existingNetworks = await getExistingNetworks();
if (!existingNetworks.length) {
throw new Error(NO_NETWORKS_FOUND_ERROR_MESSAGE);
}
return existingNetworks;
};
export const networkSelectOnlyPrompt = async (previousQuestions, args, isOptional) => {
const existingNetworks = await getEnsureExistingNetworks();
const allowedNetworkIds = previousQuestions.allowedNetworkIds !== undefined
? previousQuestions.allowedNetworkIds
: [];
const existingNetworksData = (await Promise.all(existingNetworks.map(async (network) => ({
...network,
...(await loadNetworkConfig(network.value)),
})))).flat();
const filteredNetworks = existingNetworksData.filter((network) => allowedNetworkIds.length > 0
? allowedNetworkIds.some((allowed) => network.networkId.includes(allowed))
: true);
if (!filteredNetworks.length) {
throw new Error(NO_NETWORKS_FOUND_ERROR_MESSAGE);
}
const networksInOrder = await getNetworksInOrder(filteredNetworks);
const choices = networksInOrder.map((network) => ({
value: network.value,
name: network.name,
}));
const selectedNetwork = await select({
message: 'Select a network:',
choices: choices,
});
return selectedNetwork;
};
export const networkSelectWithNonePrompt = async (previousQuestions, args, isOptional) => {
const defaultNetwork = previousQuestions.defaultNetwork;
const existingNetworks = await getEnsureExistingNetworks();
const choices = existingNetworks.map((network) => ({
value: network.value,
name: network.name,
}));
if (isNotEmptyString(defaultNetwork)) {
choices.unshift({
value: 'none',
name: 'Remove default network',
});
}
const selectedNetwork = await select({
message: 'Select a network:',
choices: choices,
});
return selectedNetwork;
};
export const networkDeletePrompt = async (previousQuestions, args, isOptional) => {
var _a;
const defaultValue = (_a = args.defaultValue) !== null && _a !== void 0 ? _a : previousQuestions.network;
if (previousQuestions.network === undefined) {
throw new Error('Network name is required for the delete prompt.');
}
let message = `Are you sure you want to delete the configuration for network "${defaultValue}"?`;
if (previousQuestions.isDefaultNetwork === true) {
message += `\nYou have currently set this as your "default network". If you delete it, then the default network settings will also be deleted.`;
}
message += '\n type "yes" to confirm or "no" to cancel and press enter. \n';
const answer = await input({
message: message,
validate: (input) => {
if (input === 'yes' || input === 'no') {
return true;
}
return 'Please type "yes" to confirm or "no" to cancel.';
},
});
return answer;
};
export const networkDefaultConfirmationPrompt = async (previousQuestions, args, isOptional) => {
var _a;
const defaultValue = (_a = args.defaultValue) !== null && _a !== void 0 ? _a : previousQuestions.network;
if (defaultValue === undefined && previousQuestions.action === 'set') {
throw new Error('Network name is required to set the default network.');
}
const message = previousQuestions.action === 'set'
? `Are you sure you want to set "${defaultValue}" as the default network?`
: `Are you sure you want to remove the "${defaultValue}" default network?`;
return await select({
message,
choices: [
{ value: true, name: 'Yes' },
{ value: false, name: 'No' },
],
});
};
//# sourceMappingURL=network.js.map