@magnolia/cli-helper v1.1.0
Magnolia CLI Plugin Helper Repository
A Magnolia CLI helper package that centralizes shared functions and configurations for developing plugins efficiently
Installation
To use this helper library in your Magnolia CLI plugins:
npm install "@magnolia/cli-helper"
Then, import the necessary utilities in your plugin code:
import { validateName } from '@magnolia/cli-helper/general-utils';
import { initI18n } from '@magnolia/cli-helper/i18n';
Modules
config.ts
The config.ts file in this repository provides utilities for managing and modifying the mgnl.config.js configuration file, which is essential for various operations in Magnolia CLI plugins. The file handles reading, writing, and updating shared and plugin-specific properties in the configuration file while offering logging capabilities to track changes.
Exported Functions Overview
modifyConfig(args: ConfigUpdates, pluginName: string, logger: Logger): Promise<void>
- Modifies the
mgnl.config.js
file based on the provided shared and plugin properties. - Parameters:
args
: An object containingsharedProps
(global properties) andpluginProps
(plugin-specific properties) to be added or modified.pluginName
: The name of the plugin props for modification.logger
: A WinstonLogger
instance for logging.
- Returns: A
Promise
that resolves when the configuration is successfully modified.
- Modifies the
getRelativePathToMGNLConfig(p: string): string
- Converts an absolute path to a relative path with respect to the
mgnl.config.js
file. - Parameters:
p
: The absolute path to be converted.
- Returns: The relative path as a string.
- Converts an absolute path to a relative path with respect to the
getMgnlConfig(logger: Logger): Promise<any>
- Loads and returns the
mgnl.config.js
file as a JavaScript object. - Parameters:
logger
: A WinstonLogger
instance for logging.
- Returns: A
Promise
that resolves to the contents of themgnl.config.js
as an object. If the file doesn't exist or cannot be imported, an empty object is returned.
- Loads and returns the
readMgnlConfigFile(logger: Logger): string
- Reads and returns the contents of the
mgnl.config.js
file. - Parameters:
logger
: A WinstonLogger
instance for logging.
- Returns: The contents of the
mgnl.config.js
file as a string. If the file does not exist, an empty string is returned.
- Reads and returns the contents of the
general-utils.ts
The general-utils.ts file contains several helper functions for common tasks such as path manipulation, validation, and checking command-line flags. These functions are used to streamline plugin development by providing reusable utilities.
Exported Functions Overview
validateName(type: string): string
- Validates a name passed as a command-line argument.
- Parameters:
type
: A string indicating the type of name being validated (e.g., block, template).
- Returns: The validated name as a string.
- Throws: Errors if the name is missing, contains invalid characters (
/ \ : * ? " < > | @
), starts with a hyphen, or exceeds 255 characters.
stripLastSep(pathToStrip: string): string
- Removes the last separator from a path string, ensuring the path is well-formed.
- Parameters:
pathToStrip
: A path string from which the last separator should be removed.
- Returns: The path without the trailing separator.
getAbsolutePath(relativePath: string): string
- Converts a relative path to an absolute path based on the current working directory.
- Parameters:
relativePath
: A string representing the relative path.
- Returns: The absolute path as a string.
checkFlagsValue(commanderOptions: Option[], options: PluginOptions): void
- Validates the provided options to ensure that none of them are command-line flags.
- Parameters:
commanderOptions
: An array of command-line options available for the current command (Option[]
fromcommander
).options
: The options passed in the current command invocation.
- Returns:
void
. - Throws: An error if any of the provided options is detected to be a flag.
getModuleName(pathToModule: string): string
- Extracts the module name from a given path.
- Parameters:
pathToModule
: The path from which to extract the module name.
- Returns: The module name as a string.
i18n.ts
The i18n.ts file provides internationalization (i18n) support for Magnolia CLI plugins, enabling them to localize prompts and error messages. The module is built using i18next and supports loading translations from JSON files based on the user's language settings.
Exported Functions Overview
initI18n(pluginName: string, namespace: string = "translation", localesPath?: string): i18n
- Initializes and configures an i18next instance for use within the plugin, loading the necessary translation files from the provided locales directory.
- Parameters:
pluginName
: The name of the plugin using the i18n instance (used for logging and error messages).namespace
: The translation namespace (defaults to "translation").localesPath
: The path to the locales directory. If not provided, it defaults to../../locales/
.
- Returns: An instance of
i18n
configured for the plugin.
light-module.ts
The light-module.ts file contains functions for managing Magnolia light modules. It helps resolve and prepare light modules by interacting with the user and the filesystem. It also checks the availability of light modules and prompts the user when needed.
Exported Functions Overview
resolveLightModulesPath(options: PluginOptions, config: Config, logger: Logger): Promise<{ lightModulesPath: string, newLightModulesPath?: string }>
- Resolves the path to the light modules directory, either from the provided options or configuration.
- Parameters:
options
: Command-line options containing a possible light modules path.config
: The Magnolia configuration file (mgnl.config.js
).logger
: A WinstonLogger
instance for logging.
- Returns: A promise that resolves to an object containing the
lightModulesPath
and, optionally, anewLightModulesPath
if it needs to be updated in the configuration.
resolveLightModule(options: PluginOptions, pluginArgs: PluginArgs, config: Config, lightModulesPath: string, logger: Logger): Promise<{ lightModule: string, newLightModule?: string, lightModuleMsg?: string }>
- Resolves the light module to be used, either from the provided options or from available light modules.
- Parameters:
options
: Command-line options that might include a light module.pluginArgs
: Arguments specific to the plugin's operation.config
: The Magnolia configuration file (mgnl.config.js
).lightModulesPath
: The resolved path to the light modules.logger
: A WinstonLogger
instance for logging.
- Returns: A promise that resolves to an object containing the
lightModule
, optionalnewLightModule
, and an optionallightModuleMsg
for logging.
prepareLightModule(options: PluginOptions, pluginArgs: PluginArgs, logger: Logger): Promise<{ lightModulePath: string, newLightModulesPath?: string, newLightModule?: string }>
- Prepares the light module for use by resolving the light module and its path.
- Parameters:
options
: Command-line options for selecting the light module.pluginArgs
: Arguments specific to the plugin's operation.logger
: A WinstonLogger
instance for logging.
- Returns: A promise that resolves to an object containing the
lightModulePath
, optionally thenewLightModulesPath
andnewLightModule
.
prompt.ts
The prompt.ts file provides helper function to interact with users via the command line, allowing them to select directories or files or create new ones when needed. The file leverages the inquirer library to create interactive prompts, making it easier for users to navigate through directories and files during plugin execution.
Exported Functions Overview
promptForDirOrFile(options: { currentPath?: string, type?: 'dir' | 'file', createNew?: boolean, message?: string, fileContent?: string }): Promise<string>
- Prompts the user to select a directory or file, and optionally allows for creating a new one.
- Options:
currentPath
: The starting path where the user will begin navigating (defaults to the current working directory).type
: Determines if the prompt should show directories only ('dir'
) or both directories and files ('file'
).createNew
: A boolean indicating if the user should be allowed to create a new directory or file.message
: A custom message to display before the prompt.fileContent
: The content to write when creating a new file.
- Returns: A promise that resolves to the selected path as a string.
prototype.ts
The prototype.ts file manages the resolution and validation of prototypes used within Magnolia CLI plugins. Prototypes define templates or configurations that are utilized when generating blocks, components, or other plugin-based elements. This file helps identify available prototypes, validate user-selected prototypes, and handle prototype directories.
Exported Functions Overview
getAvailablePrototypes(searchDir: string): string[] | undefined
- Retrieves a list of available prototypes from the specified directory.
- Parameters:
searchDir
: The directory to search for available prototypes.
- Returns: An array of available prototype directory names, or
undefined
if the directory does not exist.
findPrototypesPath(prototypeDir: string | undefined, defaultPrototypeDir: string): string
- Resolves the path to the prototype directory, either from the provided prototype directory or a default path.
- Parameters:
prototypeDir
: The prototype directory specified by the user.defaultPrototypeDir
: The default prototype directory to fall back on.
- Returns: The resolved path to the prototype directory.
validateAndResolvePrototype(options: PluginOptions, args: PluginArgs, cliPrototypesPath: string, logger: Logger): Promise<{ prototype: string, prototypeDir: string, pluginUpdates: { prototype?: string, prototypeDir?: string } }>
- Validates and resolves the prototype and its directory based on the provided options or arguments.
- Parameters:
options
: Command-line options that might include a prototype or prototype directory.args
: Arguments containing plugin configurations.cliPrototypesPath
: The default CLI path for prototypes.logger
: A WinstonLogger
instance for logging.
- Returns: A promise that resolves to an object containing the resolved
prototype
,prototypeDir
, and anypluginUpdates
needed for the configuration.
test-helper.js
The test-helper.js file provides a collection of utilities and default tests to streamline the process of writing and executing tests for Magnolia CLI plugins.
Exported Functions Overview
executeCommand(command: string, inputs: string[], cwd?: string, cb?: Function): Promise<string>
- Executes a command with interactive inputs and returns the output after processing.
- Parameters:
command
: The command to execute.inputs
: A list of inputs to provide during the execution (e.g., simulating key presses).cwd
: The working directory where the command should be executed.cb
: A callback function that receives the process for additional handling.
- Returns: A promise that resolves to the command output as a string.
addArgsToPlugin(config: any, pluginName: string, args: any): void
- Adds arguments to a plugin configuration.
- Parameters:
config
: The configuration object.pluginName
: The name of the plugin.args
: The arguments to add to the plugin.
getPluginFromConfig(config: any, pluginName: string): any
- Retrieves a plugin configuration from the config file.
- Parameters:
config
: The configuration object.pluginName
: The name of the plugin.
- Returns: The plugin configuration.
parseConfig(configPath: string): any
- Parses the
mgnl.config.js
file and returns its content as an object. - Parameters:
configPath
: The path to the config file.
- Returns: The parsed configuration object.
- Parses the
writeConfig(filePath: string, config: any): void
- Writes the provided configuration back to the file.
- Parameters:
filePath
: The path to the file to write.config
: The configuration object to write to the file.
setupTestEnvironment(): Promise<any>
- Sets up a temporary test environment with necessary dependencies.
- Returns: An object containing the paths and configurations of the test environment.
cleanupTestEnvironment(tmpDir: any): void
- Cleans up the temporary test environment.
- Parameters:
tmpDir
: The temporary directory to remove.
resetTestEnvironment(testDir: string, backupDir: string): void
- Resets the test environment to its initial state using a backup.
- Parameters:
testDir
: The path to the test directory.backupDir
: The path to the backup directory.
assertConfig(mgnlConfigPath: string, pluginClassName: string, global: any, plugin: any): void
- Asserts the configuration in the
mgnl.config.js
file. - Parameters:
mgnlConfigPath
: The path to themgnl.config.js
file.pluginClassName
: The class name of the plugin to check.global
: Global properties to verify.plugin
: Plugin properties to verify.
- Asserts the configuration in the
runDefaultTests(pluginClassName: string, pluginCommand: string, name: string, pluginInputs: string[], assertFiles: Function, preparePrototypes: Function): void
- Runs a series of default tests for Magnolia CLI plugins.
Parameters:
pluginClassName
: The class name of the plugin being tested.pluginCommand
: The command to test.name
: The name to pass to the command.pluginInputs
: A list of inputs to simulate during the command execution.assertFiles
: A function to assert file existence and content.preparePrototypes
: A function to prepare prototypes for testing.
yaml-parser.ts
The yaml-parser.ts file provides advanced YAML parsing logic to support Magnolia-specific directives such as !include
, !inherit
, and !override
.
Exported Functions Overview
parseYamlWithDirectives(filePath: string, lightModulePath: string, logger: Logger): any | null
- Parses a YAML file that may include Magnolia directives like
!include
,!inherit
, and!override
, and resolves them recursively. - Parameters:
filePath
: The absolute path to the YAML file to parse.lightModulePath
: The base path for resolving includes or inherited YAML files.logger
: A WinstonLogger
instance used to log warnings or missing files.
- Returns: The fully resolved YAML content as a JavaScript object, or
null
if parsing fails due to critical errors.
- Parses a YAML file that may include Magnolia directives like
resolveIncludePath(relPath: string, lightModulePath: string): string
- Resolves the absolute path of a file referenced using the
!include:
directive. - Parameters:
relPath
: The relative path string provided in the!include:
directive.lightModulePath
: The base light module path used for resolution.
- Returns: The resolved absolute path as a string.
- Resolves the absolute path of a file referenced using the
resolveInheritPath(relPath: string, currentFile: string, lightModulePath: string): string | null
- Resolves the absolute path to a file referenced using the
!inherit:
directive in<module>:<file>
format. - Parameters:
relPath
: The<module>:<file>
style path provided in the!inherit:
directive.currentFile
: The path to the file currently being parsed.lightModulePath
: The base path for resolving the inherit directive.
- Returns: The absolute path to the inherited YAML file, or
null
if resolution fails.
- Resolves the absolute path to a file referenced using the
deepMerge(base: any, override: any): any
- Recursively merges two objects, supporting the
!override
directive via a__OVERRIDE__
marker to fully replace a value or subtree. - Parameters:
base
: The base object to merge into.override
: The override object containing new or replacement values.
- Returns: A new object representing the deeply merged result.
- Recursively merges two objects, supporting the
eslint-config.js
This module includes an ESLint configuration that can be extended in individual plugins. The configuration provides default settings, such as recommended rules from @eslint/js
and typescript-eslint
, and also integrates eslint-config-prettier
to ensure compatibility with Prettier.
To extend this ESLint configuration in a plugin, add the following to your eslint.config.js:
import eslintConfig from "@magnolia/cli-helper/eslint-config";
export default [
...eslintConfig,
{
rules: {
// Add plugin-specific rules here
}
}
]
prettier-config.js
This module includes a default Prettier configuration that can be extended in individual plugins.
To extend this Prettier configuration in a plugin, add the following to your prettier.config.js:
import prettierConfig from "@magnolia/cli-helper/prettier-config";
const config = {
...prettierConfig,
};
export default config;
Magnolia CMS
This helper is created to work with Magnolia CMS Plugins. For more information, please refer to Plugin Documentation