[BUG] parseAsyncAPIDocumentFromFile returns undefined instead of throwing an error when the AsyncAPI document is invalid
Describe the bug.
In @asyncapi/keeper, parseAsyncAPIDocumentFromFile is documented to throw an error when parsing fails:
/**
* @throws {Error} Throws an error if the filepath is invalid or if parsing fails.
*/
However, when passed an invalid, empty, or syntactically broken AsyncAPI file, parseAsyncAPIDocumentFromFile does not throw, instead resolves to undefined.
This breaks calling functions such as compileSchemasByOperationId. Instead of informing the user that the document failed to parse, it crashes with an unhandled runtime error:
TypeError: Cannot read properties of undefined (reading 'operations')
Reason:
In apps/keeper/src/utils.js:
let asyncapi;
try {
const parseResult = await fromFile(parser, asyncapiFilepath).parse();
asyncapi = parseResult.document;
} catch (error) {
throw new Error(`Failed to parse AsyncAPI document: ${error.message}`);
}
return asyncapi;
In @asyncapi/parser v3, fromFile(parser, filepath).parse() does not reject the promise when encountering invalid AsyncAPI content. Instead, it resolves with { document: undefined, diagnostics: [...] }:
// output returned by fromFile(parser, invalidFile).parse():
{
"document": undefined,
"diagnostics": [
{
"code": "asyncapi-document-resolved",
"message": "Object must have required property \"info\"",
"severity": 0,
"path": []
},
{
"code": "asyncapi-latest-version",
"message": "The latest version of AsyncAPi is not used. It is recommended update to the \"3.1.0\" version.",
"severity": 2,
"path": ["asyncapi"]
}
]
}
The only time fromFile().parse() rejects is on file system errors (e.g. ENOENT when the file does not exist). For invalid or malformed files, the promise resolves normally, the catch block is never entered, and asyncapi is returned as undefined.
Expected behavior
When fromFile().parse() cannot produce a valid document (parseResult.document is undefined), parseAsyncAPIDocumentFromFile should throw an error with the standard prefix (Failed to parse AsyncAPI document: <message>), extracting error diagnostics from parseResult.diagnostics (diagnostics where severity === 0).
This ensures:
parseAsyncAPIDocumentFromFilehonors its documented contract (@throws {Error}).- Functions like
compileSchemasByOperationIdfail with a meaningful parsing error instead of an internalTypeError. - Valid documents continue to work with zero breaking changes.
Screenshots
N/A (Console runtime output):
# Calling parseAsyncAPIDocumentFromFile on invalid file returns undefined:
$ node -e 'import("@asyncapi/keeper/src/utils.js").then(async ({ parseAsyncAPIDocumentFromFile }) => { console.log(await parseAsyncAPIDocumentFromFile("/tmp/invalid.yaml")); });'
undefined
# Calling compileSchemasByOperationId crashes with TypeError:
$ node -e 'import("@asyncapi/keeper").then(async ({ compileSchemasByOperationId }) => { await compileSchemasByOperationId("/tmp/invalid.yaml", "someOp"); });'
TypeError: Cannot read properties of undefined (reading 'operations')
at compileSchemasByOperationId (apps/keeper/src/index.js:46:30)
How to Reproduce
- Create an invalid AsyncAPI document
/tmp/invalid.yaml:
asyncapi: 3.0.0
# Missing required "info" object
- Test with the following commands:
import { parseAsyncAPIDocumentFromFile } from '@asyncapi/keeper/src/utils.js';
import { compileSchemasByOperationId } from '@asyncapi/keeper';
// 1. Silently returns undefined instead of throwing:
const doc = await parseAsyncAPIDocumentFromFile('/tmp/invalid.yaml');
console.log(doc); // undefined
// 2. Crashes with unhandled TypeError:
await compileSchemasByOperationId('/tmp/invalid.yaml', 'someOp');
// TypeError: Cannot read properties of undefined (reading 'operations')
Tested behavior across invalid file scenarios:
| Failure Scenario | Input | Did fromFile().parse() reject? |
parseResult.document |
Diagnostics code & severity | What parseAsyncAPIDocumentFromFile returned |
|---|---|---|---|---|---|
| File does not exist | /path/missing.yaml |
Yes (ENOENT) |
N/A | None | Throws Failed to parse AsyncAPI document: ENOENT... (Expected) |
| Empty file | "" |
No | undefined |
asyncapi-is-asyncapi (Severity 0) |
Returns undefined (Bug) |
| Invalid YAML syntax | foo: [unclosed |
No | undefined |
parser: Unexpected end of stream (Severity 0) |
Returns undefined (Bug) |
| Valid YAML, not AsyncAPI | openapi: 3.0.0 |
No | undefined |
asyncapi-is-asyncapi: missing field (Severity 0) |
Returns undefined (Bug) |
| Missing required fields | asyncapi: 3.0.0 (missing info) |
No | undefined |
asyncapi-document-resolved: missing info (Severity 0) |
Returns undefined (Bug) |
| Invalid $ref reference | ch: { $ref: '#/bad' } |
No | undefined |
invalid-ref: does not exist (Severity 0) |
Returns undefined (Bug) |
🖥️ Device Information [optional]
- Operating System (OS): Fedora Linux
- Browser: Chrome
- Browser Version: 154.0
👀 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!
The current code behaves as you describe. parseAsyncAPIDocumentFromFile wraps only the fromFile(...).parse() call in try/catch and returns parseResult.document without checking it (utils.js). When the parser resolves with document: undefined, the function returns undefined. compileSchemasByOperationId then calls asyncapi.operations() on that result with no guard, which produces the TypeError (index.js).
The existing tests cover invalid path arguments, a missing file and a valid file, but not a file that parses to document: undefined (utils.test.js).
The fix can stay inside utils.js. Put the throw outside the try/catch so the message isn't double-wrapped:
- After
parse(), ifparseResult.documentis falsy, filterparseResult.diagnosticsforseverity === 0. - Join their
messagevalues and throwFailed to parse AsyncAPI document: <messages>. - Fall back to a generic message if there are no error diagnostics.
For tests, add fixtures for each case in your table (empty file, broken YAML, openapi: 3.0.0, missing info, broken $ref), each asserting rejects.toThrow(/^Failed to parse AsyncAPI document:/). Also add a compileSchemasByOperationId test that expects the same parse error instead of a TypeError.
To reply, just mention @dosu.
Share context across your team and agents. Try Dosu.
Please have a look at this comment and its subsequent thread: https://github.com/asyncapi/generator/pull/2263#issuecomment-6065089762
Maintainer @Adi-204 has directed me to open this issue as a follow-up of our findings in #2263
/approve
👋 Thanks for your patience. This issue has been reviewed and is ready to be worked on.
Before you start:
- Comment below to let others know you're working on it (avoids duplicate work)
- Read our CONTRIBUTING.md if you haven't already
- Fork the repo, create a feature branch, and open a draft PR early
Approved by @Adi-204
@Adi-204 I'm on it.
@Adi-204 Should I introduce tests for the invalid asyncapi document in this patch PR?
@dosu what do you think about:
@Adi-204 Should I introduce tests for the invalid asyncapi document in this patch PR?
Yes, I’d include regression tests in the same patch PR. The existing utils.test.js covers invalid paths, a missing file and a valid document, but not an existing file containing invalid AsyncAPI content. That is the gap this fix should cover. [1]
I’d recommend:
- Fixture-based tests for missing required fields, empty content and malformed YAML, asserting rejection with
Failed to parse AsyncAPI document:and a meaningful diagnostic message. - If you add diagnostic filtering, a focused test proving warning diagnostics are excluded from the error message.
- One test in
index.test.jsasserting thatcompileSchemasByOperationIdrejects with the parsing error for an invalid document.
Keep the existing valid-document test as the happy-path check. [1]
The regression tests should fail before the fix and pass afterward. That would keep this PR focused on both fixing the behavior and preventing it from returning.
To reply, just mention @dosu.
Docs are dead. Just use Dosu.
@dosu don't you think asserting multiple specific tests for an invalid asyncapi document is unnecessary? Instead having one clear fixture is standard approach without bloat? consider this:
#asyncapi-invalid.yml
asyncapi: 3.0.0
# Intentionally invalid: missing required 'info' object
servers:
dev:
host: localhost:8080
protocol: ws
Yes, for this patch I’d use one representative invalid fixture. My earlier suggestion was broader than necessary.
The regression to protect is the wrapper returning parseResult.document without checking whether it exists, not every way an AsyncAPI document can be invalid. [1]
Your missing-info fixture fits the reported reproduction. I’d add one test asserting that it rejects with:
- The
Failed to parse AsyncAPI document:prefix. - A diagnostic identifying the missing
infoproperty, without matching the entire parser-generated message.
Keep the existing missing-file and valid-document tests, which cover the other outcomes. [2] Add more cases only if the implementation introduces distinct behavior that needs coverage.
To preserve this focused testing rationale for future replies, you can say @dosu save this.
To reply, just mention @dosu.
Share context across your team and agents. Try Dosu.