File size: 1,458 Bytes
eb3f11e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// Lazy Commander placeholder registration used to keep CLI startup imports small.
import type { Command } from "commander";
import { reparseProgramFromActionCommand } from "./action-reparse.js";
import { removeCommandByName } from "./command-tree.js";
import { markCommanderLazyCommand } from "./commander-parse-facts.js";

type RegisterLazyCommandParams = {
  program: Command;
  name: string;
  description: string;
  hidden?: boolean;
  options?: readonly {
    flags: string;
    description: string;
  }[];
  removeNames?: readonly string[];
  register: () => Promise<void> | void;
};

/** Register a placeholder that loads the real command and reparses the original invocation. */
export function registerLazyCommand({
  program,
  name,
  description,
  hidden,
  options,
  removeNames,
  register,
}: RegisterLazyCommandParams): void {
  const placeholder = program.command(name, { hidden }).description(description);
  markCommanderLazyCommand(placeholder);
  for (const option of options ?? []) {
    placeholder.option(option.flags, option.description);
  }
  placeholder.allowUnknownOption(true).allowExcessArguments(true);
  placeholder.action(async (...actionArgs) => {
    const actionCommand = actionArgs.at(-1) as Command;
    for (const commandName of new Set(removeNames ?? [name])) {
      removeCommandByName(program, commandName);
    }
    await register();
    await reparseProgramFromActionCommand(program, actionCommand);
  });
}