generator icon indicating copy to clipboard operation
generator copied to clipboard

[BUG] Generator with output: 'string' crashes with TypeError or resolves to undefined

Open devxdh opened this issue 1 month ago • 0 comments

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:

  1. Crashes during generate:after hook execution:
    generate() unconditionally calls await this.executeAfterHook(). When targetDir is omitted or null (the documented in-memory usage), the default @asyncapi/generator-hooks: createAsyncapiFile hook tries to resolve generator.targetDir via path.resolve and 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 targetDir to satisfy the hook, it crashes with ENOENT instead because setupFSOutput() never created the directory on disk in string mode).

  2. Discards the rendered result:
    If generate:after hooks are disabled (disabledHooks: { 'generate:after': true }) to bypass the crash, the call completes without throwing, but resolves to undefined.
    Inside handleEntrypoint() (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, but generate() calls await 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:

  1. launchHook('generate:after') was only triggered when this.output === 'fs'. In-memory string generation skipped filesystem after-hooks.
  2. 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 outside handleEntrypoint() and runs unconditionally on every generation, even when output === 'string' and targetDir is null. (Interestingly, the JSDoc on handleEntrypoint() on line 335 still preserves the original intent: * - Launches the 'generate:after' hook if the output is 'fs'.).
  • generate() dropped the return statement for this.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

Image Image

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)

  1. Run the generator with output: 'string' and targetDir: 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));"
    
  2. 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)

  1. Bypass the hook crash by disabling generate:after hooks via disabledHooks: { '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));"
    
  2. Observed Output:

    Result: undefined
    

    Generation completes without throwing, but the rendered template result returned by handleEntrypoint() was dropped by generate().

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?

Are you willing to work on this issue ?

Yes I am willing to submit a PR!

devxdh avatar Nov 03 '26 17:11 devxdh