@karmaniverous/get-dotenv
    Preparing search index...

    Authoring Plugins: Lifecycle & Wiring

    Plugins are small modules that register commands and behavior against the plugin‑first host. The host resolves dotenv context once per invocation, overlays config, validates, and then runs your plugin’s setup and optional afterResolve hooks. See also: Config & Validation, Diagnostics & Errors, and Executing Shell Commands.

    import { definePlugin } from '@karmaniverous/get-dotenv/cliHost';

    export const helloPlugin = () =>
    definePlugin({
    ns: 'hello',
    setup(cli) {
    cli.description('Say hello').action(() => {
    const ctx = cli.getCtx();
    console.log('hello', Object.keys(ctx.dotenv).length);
    });
    },
    });
    #!/usr/bin/env node
    import { createCli } from '@karmaniverous/get-dotenv/cli';
    import {
    cmdPlugin,
    batchPlugin,
    awsPlugin,
    initPlugin,
    } from '@karmaniverous/get-dotenv/plugins';
    import { helloPlugin } from './plugins/hello';

    const run = createCli({
    alias: 'toolbox',
    importMetaUrl: import.meta.url,
    branding: 'Toolbox CLI',
    compose: (p) =>
    p
    .use(
    cmdPlugin({ asDefault: true, optionAlias: '-c, --cmd <command...>' }),
    )
    .use(batchPlugin())
    .use(awsPlugin())
    .use(initPlugin())
    .use(helloPlugin()),
    });

    await run(); // or await run(process.argv.slice(2));

    The runner takes user arguments only (run(['-e', 'dev', 'cmd', 'npm', 'test'])). Pass a full process argv with Commander's from: run(process.argv, { from: 'node' }). Called without arguments it reads process.argv and detects node -e/-p and Electron as Commander does.

    A host built directly from GetDotenvCli parses with await program.parseAsync(argv, { from }), which installs plugins, normalizes qualified options and renders top-level help. Sync program.parse() throws: parse() is not supported on a get-dotenv host; use parseAsync(). During a parse, Commander sets rawArgs only on the root, to the normalized user arguments (no leading node/script entries); subcommands keep [].

    If you want to expose shipped (or third-party) plugins under a non-root “group” command without forking or “calling” another plugin, use the namespace-only parent helper groupPlugins. This is useful for patterns like:

    • smoz init (your SMOZ init plugin)
    • smoz getdotenv init (delegate to get-dotenv’s init plugin under a group namespace)

    Example:

    #!/usr/bin/env node
    import { createCli } from '@karmaniverous/get-dotenv/cli';
    import { groupPlugins } from '@karmaniverous/get-dotenv/cliHost';
    import { initPlugin } from '@karmaniverous/get-dotenv/plugins';
    import { smozInitPlugin } from './plugins/init';

    const run = createCli({
    alias: 'smoz',
    importMetaUrl: import.meta.url,
    compose: (p) =>
    p.use(smozInitPlugin()).use(
    groupPlugins({
    ns: 'getdotenv',
    description: 'getdotenv utility functions',
    aliases: ['gd'],
    helpGroup: 'Utilities',
    }).use(initPlugin()),
    ),
    });

    await run();

    Notes:

    • Root flags (like -e, --paths, --shell-off, --capture) are global and are typically specified before the subcommand token (e.g., smoz -e dev getdotenv init ...).
    • Plugin config keys follow the realized mount path, so mounting under getdotenv changes keys (for example plugins['getdotenv/init'] rather than plugins['init']).
    • If you mount cmdPlugin({ optionAlias: ... }) under the group, the parent alias is attached to the group command (so smoz getdotenv -c 'echo OK' works, but smoz -c 'echo OK' does not).

    cli.use(plugin, { ns }) and parent.use(child, { ns }) mount a plugin under a name of your choice instead of its declared ns. The override is the plugin's effective namespace: the host creates the mount there, and the plugin's realized mount path (the chain of effective namespaces from the root, e.g. ops/who2) keys its config slice and scopes its afterResolve hook. This lets you mount two instances of one plugin side by side, each with its own config:

    const run = createCli({
    alias: 'toolbox',
    importMetaUrl: import.meta.url,
    compose: (p) =>
    p
    .use(deployPlugin(), { ns: 'deploy-api' })
    .use(deployPlugin(), { ns: 'deploy-web' }),
    });
    {
    "plugins": {
    "deploy-api": { "target": "api" },
    "deploy-web": { "target": "web" }
    }
    }

    toolbox deploy-api ... runs the first instance with plugins['deploy-api'] and only its afterResolve. Renaming a mount intentionally changes its config key.

    Sibling namespaces must be unique at every level, the root included. A collision throws Duplicate namespace '<ns>' under '<parent>'. Override via .use(plugin, { ns: '...' })., where <parent> is the parent's realized path (root at the top level). Children of a plugin are checked as soon as the second one is added with .use(); root-level plugins are checked at install. Mounting one plugin instance twice gives both mounts one shared config slot, so call the plugin factory once per mount.

    When you need the real root command (for branding, alias labels, or reading root‑level metadata) from inside a plugin mount or action, use the small typed helper exported by the host:

    import {
    definePlugin,
    getRootCommand,
    } from '@karmaniverous/get-dotenv/cliHost';

    export const helloPlugin = () => {
    const plugin = definePlugin({
    ns: 'hello',
    setup(cli) {
    cli.action(() => {
    const root = getRootCommand(cli); // typed Commander root
    // Example: include the root name in your output
    console.log(`[${root.name()}] hello from plugin`);
    });
    },
    });
    return plugin;
    };

    For a fuller example in context, see the scaffolded template plugin at templates/cli/plugins/hello/index.ts.

    For non‑trivial plugins, prefer the structure used by the shipped template (init scaffold) to keep setup clean and wiring testable:

    • index.ts — The plugin factory. Calls definePlugin and orchestrates setup by calling attach helpers.
    • options.ts — Exports attach*Options(cli). Attaches options/arguments and returns the command for chaining.
    • *Action.ts — Exports attach*Action(cli). Wires the .action() handler.
    • types.ts — Exports Zod configuration schemas and inferred types.

    This separation (“bucket of subcommands”) scales well as your plugin grows.

    Notes:

    • The compose hook runs before parsing and is the recommended way to assemble your CLI surface. The factory installs root options and hooks so shipped plugins can read the merged options bag with readMergedOptions().
    • If you construct a host directly, mirror the shipped wiring (root options + root hooks) before attaching shipped plugins. For most use cases, createCli is simpler and safer.

    Every host belongs to a package: its host root, the nearest package.json above the host module's import.meta.url. createCli requires that URL:

    await createCli({
    alias: 'toolbox',
    importMetaUrl: import.meta.url, // required
    version: '1.0.0', // optional; default: host package.json version
    description: 'Toolbox CLI.', // optional; default: host package.json description
    branding: 'toolbox v1.0.0', // optional help header
    compose: (p) => p /* ...wire plugins... */,
    })();

    The host root supplies:

    • the packaged config layer: <hostRoot>/getdotenv.config.*. It replaces get-dotenv's own packaged layer (there is no third layer), so a downstream CLI can ship config with its package.
    • the version printed by -V, --version and shown in the default help header (<alias> v<version>), from package.json version unless version is given;
    • the description shown in root help, from package.json description unless description is given.

    Rules:

    • createCli() without importMetaUrl throws.
    • When the host root is the project root (the nearest package.json above the working directory), the packaged layer is skipped. A CLI that lives in the repo it runs in (for example a cli/vc.ts run with tsx) would otherwise apply its getdotenv.config.* twice, once as packaged and once as project config, and run its dynamic twice.
    • The shipped getdotenv CLI passes its own import.meta.url, so its packaged layer is get-dotenv's own.
    • init always copies its templates from get-dotenv's package, whatever the host root.
    • branding replaces only the help header text, never the version.
    • A runner may be called more than once. -V, --version is registered the first time a version is known; later runs only update it.

    If you construct a host directly, set the host root with the constructor or with brand(); the last one given wins. A direct host that gives neither keeps get-dotenv's own package root.

    const program = new GetDotenvCli('toolbox', { importMetaUrl: import.meta.url });
    // or, before parsing:
    await program.brand({
    importMetaUrl: import.meta.url,
    description: 'Toolbox CLI.',
    });

    brand() reads the version from the host package when version is omitted. Calling it again updates the version without registering --version twice.

    Inside actions, prefer the structural helpers:

    import { readMergedOptions } from '@karmaniverous/get-dotenv/cliHost';

    cli.ns('print').action((_args, _opts, thisCommand) => {
    const bag = readMergedOptions(thisCommand);
    const ctx = cli.getCtx();
    // bag contains merged root options (scripts, shell, capture, trace, etc.)
    // ctx.dotenv contains the final merged env (after overlays and dynamics)
    });

    If your plugin accepts option values that may include environment references (for example, --table-name '${TABLE_NAME}'), expand them yourself at action time using the resolved context (so you are not dependent on loadProcess). See Executing Shell Commands for recommended patterns and cross-platform quoting guidance.

    See also:

    Prefer the plugin‑bound helper createPluginDynamicOption to render help text that reflects the resolved configuration for that specific plugin instance. The host evaluates dynamic descriptions with overlays and dynamic enabled, without logging or mutating the environment.

    Key points:

    • createPluginDynamicOption(cli, flags, (cfg, pluginCfg) => string, parser?, defaultValue?) attaches to the current plugin, injecting that plugin’s validated config slice (pluginCfg).
    • The callback receives a read‑only resolved help config (top‑level flags) and the instance‑bound plugin config slice. Avoid by‑id lookups (e.g., cfg.plugins.); rely on pluginCfg instead.
    • Top‑level “-h/--help” computes a read‑only config and evaluates dynamic text; “help ” refreshes dynamic text after preSubcommand resolution. Both apply the merged rootOptionVisibility (createCli < packaged < project/public < project/local) before rendering, and the host appends each option's qualified name at render time, so a dynamic description keeps its (anywhere: --<name>).

    Example (plugin flag with ON/OFF default label using instance‑bound config):

    import { z } from 'zod';
    import { definePlugin } from '@karmaniverous/get-dotenv/cliHost';

    const helloConfigSchema = z.object({
    loud: z.boolean().optional().default(false),
    });
    type HelloConfig = z.infer<typeof helloConfigSchema>;

    export const helloPlugin = () => {
    const plugin = definePlugin({
    ns: 'hello',
    configSchema: helloConfigSchema,
    setup(cli) {
    cli
    .description('Say hello with current dotenv context')
    .addOption(
    // Helper infers config type from plugin instance
    plugin.createPluginDynamicOption(
    cli,
    '--loud',
    (
    _bag,
    pluginCfg, // inferred as Readonly<HelloConfig>
    ) =>
    `print greeting in ALL CAPS${pluginCfg.loud ? ' (default)' : ''}`,
    ),
    )
    .action(() => {
    const pluginCfg = plugin.readConfig(cli); // inferred
    // use pluginCfg.loud at runtime
    });
    },
    });
    return plugin;
    };

    Or build the Option first:

    const opt = plugin.createPluginDynamicOption(
    cli,
    '--loud',
    (_bag, pluginCfg) =>
    `print greeting in ALL CAPS${pluginCfg.loud ? ' (default)' : ''}`,
    );
    cli.addOption(opt);

    If your plugin defines subcommands and you want their options to reflect defaults from your plugin's config (e.g. plugins.my.sub.mode), you do not need to implement them as separate plugins.

    1. Model the subcommand defaults in your configSchema (e.g. as a nested object).
    2. Pass the subcommand instance (not cli) as the first argument to createPluginDynamicOption.
    // Inside setup(cli)
    const sub = cli.command('run-job').description('Run a job');

    sub.addOption(
    plugin.createPluginDynamicOption(
    sub, // Attach dynamic logic to the subcommand
    '--mode <string>',
    (_bag, pluginCfg) => `job mode (default: ${pluginCfg.job.mode})`,
    ),
    );

    Notes:

    • Use concise labels for ON/OFF toggles (e.g., “(default)”) and “(default: "...")” for string defaults.
    • Plugin config is validated and deep‑interpolated once by the host; read it via plugin.readConfig(cli).

    Update (DX: no undefined):

    • With the current host, readConfig returns a concrete object (never undefined). Defaults are materialized from the schema when no slice is present.
    • The dynamic option callback receives a concrete plugin config object too, so you can reference cfg.foo without optional chaining when you have defaults in your schema.

    afterResolve hooks run once per invocation after the host resolves dotenv context. When the shipped root hooks are used, afterResolve is scoped to the invoked command path: only plugins whose realized mount path matches the invoked subcommand path (and their children) run afterResolve. The match uses each plugin's effective namespace, so a plugin mounted with .use(plugin, { ns }) is matched by its override. Sibling and cousin plugins do not fire.

    This means a plugin's afterResolve should only set up state relevant to its own command subtree. It should not assume it runs on every invocation. The shipped aws plugin, for example, only resolves AWS credentials and writes to process.env when an aws or aws/* command is invoked.

    Custom hosts that call resolveAndLoad() without an invokedSubcommand filter get the legacy behavior where all plugins run afterResolve.

    With the shipped root hooks (every createCli host), each invocation composes its dotenv context once, so config dynamic functions run once (and not at all under -z). The cmd plugin's parent alias (-c) runs against that same context. A bare GetDotenvCli host without the root hooks still gets a lazy context before its subcommands run (loadProcess off, no afterResolve).