[BUG] Generator with output: 'string' crashes with TypeError or resolves to undefined
Describe the bug.
The generator's in-memory string output mode ({ entrypoint: '...', output: 'string' }, documented in api.md) cannot be used without failing. In this mode, no files should be written to disk; the generator is expected to render the specified entrypoint template in-memory and resolve to the rendered output directly. Because there is no target directory on the filesystem, targetDir is explicitly optional (apps/generator/lib/generator.js#L94) and filesystem output setup is bypassed (apps/generator/lib/generator.js#L231).
However, calling generator.generate() (or generateFromFile() / generateFromString()) with output: 'string' currently fails in two ways:
-
Crashes during
generate:afterhook execution:
generate()unconditionally callsawait this.executeAfterHook(). WhentargetDiris omitted ornull(the documented in-memory usage), the default@asyncapi/generator-hooks: createAsyncapiFilehook tries to resolvegenerator.targetDirviapath.resolveand crashes immediately:TypeError: The "paths[0]" argument must be of type string. Received null at Object.resolve (node:path) at createAsyncapiFile (apps/hooks/src/index.js:30:12) at Generator.launchHook (apps/generator/lib/generator.js:1032:28) at Generator.executeAfterHook (apps/generator/lib/generator.js:367:16)(If a dummy string path is passed to
targetDirto satisfy the hook, it crashes withENOENTinstead becausesetupFSOutput()never created the directory on disk in string mode). -
Discards the rendered result:
Ifgenerate:afterhooks are disabled (disabledHooks: { 'generate:after': true }) to bypass the crash, the call completes without throwing, but resolves toundefined.
InsidehandleEntrypoint()(apps/generator/lib/generator.js#L350-L352):} else if (this.output === 'string') { return await this.renderFile(this.asyncapi, entrypointPath); }handleEntrypoint()renders the template and returns the result, butgenerate()callsawait this.handleEntrypoint()on line 196 without capturing or returning the value, dropping the rendered output.
History & Regression Context
This is a regression introduced in PR #1047 (commit 4d347f8a, "refactor: generate function refactored to reduce cognitive complexity").
Before PR #1047 (working implementation):
if (this.entrypoint) {
const entrypointPath = path.resolve(this.templateContentDir, this.entrypoint);
if (!(await exists(entrypointPath))) throw new Error(`Template entrypoint "${entrypointPath}" couldn't be found.`);
if (this.output === 'fs') {
await this.generateFile(this.asyncapi, path.basename(entrypointPath), path.dirname(entrypointPath));
await this.launchHook('generate:after');
} else if (this.output === 'string') {
return this.renderFile(this.asyncapi, entrypointPath);
}
} else {
await this.generateDirectoryStructure(this.asyncapi);
await this.launchHook('generate:after');
}
Notice two critical details in the original code:
launchHook('generate:after')was only triggered whenthis.output === 'fs'. In-memory string generation skipped filesystem after-hooks.- In string mode,
this.renderFile(...)was returned directly to the caller.
After PR #1047:
The method was split into handleEntrypoint() and executeAfterHook(), called sequentially from generate() (apps/generator/lib/generator.js#L196-L197):
await this.handleEntrypoint();
await this.executeAfterHook();
this.executeAfterHook()was placed outsidehandleEntrypoint()and runs unconditionally on every generation, even whenoutput === 'string'andtargetDirisnull. (Interestingly, the JSDoc onhandleEntrypoint()on line 335 still preserves the original intent:* - Launches the 'generate:after' hook if the output is 'fs'.).generate()dropped thereturnstatement forthis.handleEntrypoint().
Existing tests in apps/generator/test/generator.test.js only asserted constructor properties (expect(gen.output).toStrictEqual('string')), so generate() was never exercised end-to-end with string output.
Expected behavior
When output === 'string', generator.generate() should skip filesystem generate:after hooks and resolve to the rendered TemplateRenderResult object:
{
content: '...',
metadata: { fileName: '...', permissions: ... }
}
Screenshots
How to Reproduce
Both failure modes can be reproduced directly from the repository root using existing repository test fixtures without needing to create or modify any files:
- Template:
apps/generator/test/test-templates/react-template - Template entrypoint file:
apps/generator/test/test-templates/react-template/template/test-file.md.js - AsyncAPI spec fixture:
apps/generator/test/docs/dummy.yml
Case A: Reproducing the Hook Crash (TypeError)
-
Run the generator with
output: 'string'andtargetDir: null:const Generator = require('./apps/generator/lib/generator'); const path = require('path'); async function test() { const generator = new Generator( path.resolve('apps/generator/test/test-templates/react-template'), null, // targetDir is optional when output is 'string' { entrypoint: 'test-file.md.js', output: 'string', templateParams: { version: '1.0.0', mode: 'production', singleFile: 'false', singleFolder: 'false' } } ); await generator.generateFromFile(path.resolve('apps/generator/test/docs/dummy.yml')); } test();Or run this 1-line command in your terminal from repo root:
node -e "const Generator = require('./apps/generator/lib/generator'); const path = require('path'); new Generator(path.resolve('apps/generator/test/test-templates/react-template'), null, { entrypoint: 'test-file.md.js', output: 'string', templateParams: { version: '1.0.0', mode: 'production', singleFile: 'false', singleFolder: 'false' }}).generateFromFile(path.resolve('apps/generator/test/docs/dummy.yml')).catch(err => console.error(err.stack));" -
Observed Output:
TypeError: The "paths[0]" argument must be of type string. Received null at Object.resolve (node:path:1257:7) at createAsyncapiFile (apps/hooks/src/index.js:30:12) at Generator.launchHook (apps/generator/lib/generator.js:1032:28) at Generator.executeAfterHook (apps/generator/lib/generator.js:367:16) at Generator.generate (apps/generator/lib/generator.js:197:16) at Generator.generateFromFile (apps/generator/lib/generator.js:520:12)
Case B: Reproducing the Silent Return Discard (undefined)
-
Bypass the hook crash by disabling
generate:afterhooks viadisabledHooks: { 'generate:after': true }:const Generator = require('./apps/generator/lib/generator'); const path = require('path'); async function test() { const generator = new Generator( path.resolve('apps/generator/test/test-templates/react-template'), null, { entrypoint: 'test-file.md.js', output: 'string', disabledHooks: { 'generate:after': true }, templateParams: { version: '1.0.0', mode: 'production', singleFile: 'false', singleFolder: 'false' } } ); const result = await generator.generateFromFile(path.resolve('apps/generator/test/docs/dummy.yml')); console.log('Result:', result); } test();Or run this 1-line command in your terminal from repo root:
node -e "const Generator = require('./apps/generator/lib/generator'); const path = require('path'); new Generator(path.resolve('apps/generator/test/test-templates/react-template'), null, { entrypoint: 'test-file.md.js', output: 'string', disabledHooks: { 'generate:after': true }, templateParams: { version: '1.0.0', mode: 'production', singleFile: 'false', singleFolder: 'false' } }).generateFromFile(path.resolve('apps/generator/test/docs/dummy.yml')).then(res => console.log('Result:', res));" -
Observed Output:
Result: undefinedGeneration completes without throwing, but the rendered template result returned by
handleEntrypoint()was dropped bygenerate().
Suggested Fix
In apps/generator/lib/generator.js#L189-L198:
async generate(asyncapiDocument, parseOptions = {}) {
this.validateAsyncAPIDocument(asyncapiDocument);
await this.setupOutput();
this.setLogLevel();
await this.installAndSetupTemplate();
await this.configureTemplateWorkflow(parseOptions);
const result = await this.handleEntrypoint();
if (this.output === 'fs') {
await this.executeAfterHook();
}
return result;
}
🖥️ Device Information [optional]
- Operating System (OS): Fedora Linux Workstation 44
- Browser: Google Chrome
- Browser Version: 154
👀 Have you checked for similar open issues?
- [x] I checked and didn't find similar issue
🏢 Have you read the Contributing Guidelines?
- [x] I have read the Contributing Guidelines
Are you willing to work on this issue ?
Yes I am willing to submit a PR!