Skip to main content

Part of @biorate/hygen — a fork of jondot/hygen (v6.2.11, MIT), adapted to the @biorate/* monorepo. Rewritten for this fork's semantics; see Differences from upstream.

Based on: Upstream generators doc

Prompt hooks

A prompt hook is a JavaScript module in the action folder that collects or computes the variables handed to the templates of that action. This page is the complete reference: file names and lookup order, the three hook forms, filtering semantics, and TypeScript support. For a quick introduction see generators.

Where the hook lives​

Modern form: the class-based hooks.ts / hooks.js / hooks.mjs / hooks.cjs file is the preferred form — it also carries lifecycle methods (beforeAll, beforeEach, afterEach, afterAll) around the run. See Action hooks and lifecycle. The legacy prompt files documented below remain fully supported.

The hook file sits in the action folder and is shared by every template in that folder — it runs once per action, before any template renders:

_templates/
mailer/
new/ <- the "mailer new" action
prompt.js <- one hook for html.ejs.t and text.ejs.t
html.ejs.t
text.ejs.t

File names and lookup order​

The runner looks for the first existing file in the action folder, in this order:

PriorityFile nameNotes
1hooks.tsModern form — TypeScript, transpiled on the fly
2hooks.jsModern form — follows the host project's type field
3hooks.mjsModern form — explicit ESM
4hooks.cjsModern form — explicit CommonJS
5index.jsLegacy — preferred for advanced hooks
6index.tsLegacy — TypeScript, transpiled on the fly
7prompt.cjsLegacy — explicit CommonJS
8prompt.jsLegacy — the conventional choice
9prompt.tsLegacy — TypeScript, transpiled on the fly

The first existing file wins and nothing else is loaded — a hooks.* file always takes priority over the legacy files. A hooks.* file must default-export a class (the legacy forms export a hook object or array instead). Legacy modules keep working unchanged. For the full class contract see The hooks class.

If none exists, no prompting happens and the action proceeds with the CLI variables only. TypeScript hooks work out of the box: the runner lazily registers ts-node/register/transpile-only on first use. Both module systems are supported — module.exports (CommonJS) and export default / named export (ESM); the runner performs a dynamic import() and unwraps default when present.

Note: in legacy modules params is a function that resolves the prompt answers. A modern class hooks.* module may instead declare a declarative static params > array on the hooks class (typed coercion, prompts and validation from descriptors) — see Declarative parameters.

The three hook forms​

The runner inspects the module's exports and picks the matching form. The check order is fixed: params first, then prompt, then a plain question array — e.g. if a module exports params, the prompt export (if any) is never called.

Form 1: a question array (declarative)​

The simplest form — an array of enquirer questions. The runner asks only the questions whose answers were not already provided on the CLI (see filtering):

// _templates/mailer/new/prompt.js
module.exports = [
{
type: 'input',
name: 'message', // becomes the <%= message %> template variable
message: "What's your message?",
validate: (v) => v.length > 0 || 'Required',
},
{
type: 'confirm',
name: 'typescript',
message: 'Use TypeScript?',
initial: true,
},
];

Form 2: a prompt function (full control)​

The hook receives { prompter, inquirer, args, h } and decides itself what to ask, in how many steps, and whether to ask at all. Everything the function returns merges into the template variables:

module.exports = {
async prompt({ prompter, args, h }) {
// custom shortcut: no prompting when the value came from the CLI
if (args.author) return {};

const { kind } = await prompter.prompt([
{ type: 'select', name: 'kind', message: 'Kind?', choices: ['worker', 'service'] },
]);

const { name } = await prompter.prompt([
{
type: 'input',
name: 'name',
message: `${kind} name?`,
initial: h.changeCase.paramCase(`My${kind}`),
},
]);

return { kind, name };
},
};

Hook arguments:

FieldDescription
prompterThe enquirer-compatible prompter instance configured for this run
inquirerAn alias of prompter, kept for compatibility with inquirer-era templates
argsThe parsed CLI arguments of this run (flags and positionals)
hThe built-in helpers (h.changeCase, h.inflection, h.path, h.capitalize) — same h as in templates

Form 3: a params function (no prompting at all)​

A pure computation hook: derive the template variables from existing data — CLI args, project files, environment. The user is never asked anything:

const path = require('path');

module.exports = {
params({ args, h }) {
const pkg = require(path.join(process.cwd(), 'package.json'));
return {
name: args.name || pkg.name,
author: pkg.author,
year: new Date().getFullYear(),
};
},
};

Because params is checked first, a module exporting it turns the hook into a silent variable-computation step even if a prompt export is also present.

Filtering: ask only what's missing​

In the declarative form (question array) the runner filters the questions by their name against the CLI arguments: a question is asked only when args[name] is undefined, null, or an empty string; a question whose variable already carries a CLI value is skipped. This is what keeps generators usable non-interactively:

# asks for "message" (nothing provided)
hygen mailer new fancy-mailer

# asks nothing: both variables came from the CLI — safe in CI
hygen mailer new fancy-mailer --message "Hello"

In the prompt-function form filtering is your responsibility — the runner hands you args and you decide what to ask (or return early, as in the example above).

Hooks under lists​

When a run expands multiple actions and/or names (see generators), the hook is not asked once for the whole run. The execution unit is one (name, action) pair, and each pair runs its own prompt hook before rendering:

hygen mailer new,html a,b
# new for "a" -> new for "b" -> html for "a" -> html for "b"
# the hook in _templates/mailer/new and the hook in _templates/mailer/html
# both run once per (name x action) pair

So a new folder with several names gets its hook asked once per name, and each listed action's hook runs independently. This multiplies prompt interruptions exactly by the number of pairs. The sharing mechanism is CLI flags: supply a variable once on the command line and every pair starts with it — the declarative form already skips questions whose answers came from the CLI (see filtering), so an answered variable is never re-asked in a later pair.

name precedence​

The name variable follows a fixed precedence chain when several sources provide it:

PrecedenceSourceExample
1 (highest)prompt hook answera prompt.js value
2positional name listhygen mailer new a,b
3 (lowest)--name flag--name fancy

The hook's answer always wins. The positional name list is the primary name source; the --name flag participates only under the legacy escape (HYGEN_LEGACY_NAME=1 or legacyNameFlag: true in RunnerConfig), in which case a positional element overrides it. When the run expands a name list, name is the scalar of the current expansion regardless of how it was arrived at. (The --name flag is removed by default — use a comma-separated positional name list instead.)

Answers become template variables​

Everything the hook yields — question answers or the object returned from prompt/params — is merged with the CLI variables and rendered into the templates:

---
to: app/emails/<%= name %>.txt
---
<%= message %>

CLI flags take precedence in the declarative form (already-provided answers are filtered out); in the function forms you control the precedence yourself.

A complete example​

The kitchen-sink fixture in this package is a real, tested hook: tests/fixtures/kitchen-sink/_templates/sink/new/prompt.js — a prompt function with a CLI shortcut and a defaulted question.

See also​

  • generators — organizing generators and actions, and running several actions/names in one command
  • templates — the frontmatter reference and helpers
  • extensibility — the project config file and embedding via runner()