swc-project/swc · error · anyhow::Error

failed to parse input as document

Error message

failed to parse input as document

What it means

The Node HTML binding's document mode calls parse_file_as_document; on a fatal parse failure it emits the parser error and all buffered recoverable errors as diagnostics first, then bails with this generic message. As with the fragment variant, the real cause is in the diagnostics printed before the error. HTML parsing is normally error-tolerant, so a fatal result usually means structurally impossible input or a parser bug.

Source

Thrown at bindings/binding_html_node/src/lib.rs:588

                    &fm,
                    swc_html::parser::parser::ParserConfig {
                        scripting_enabled,
                        iframe_srcdoc: opts.iframe_srcdoc,
                        ..Default::default()
                    },
                    &mut errors,
                );

                let document = match document {
                    Ok(v) => v,
                    Err(err) => {
                        err.to_diagnostics(handler).emit();

                        for err in errors {
                            err.to_diagnostics(handler).emit();
                        }

                        bail!("failed to parse input as document")
                    }
                };

                (DocumentOrDocumentFragment::Document(document), None)
            };

            let mut returned_errors = None;

            if !errors.is_empty() {
                returned_errors = Some(Vec::with_capacity(errors.len()));

                for err in errors {
                    let mut buf = vec![];

                    err.to_diagnostics(handler).buffer(&mut buf);

                    for i in buf {
                        returned_errors.as_mut().unwrap().push(Diagnostic {

View on GitHub (pinned to 5176682b65)

Solutions

  1. Inspect the diagnostics emitted just before the bail for exact positions and parser messages
  2. Trim the document to the smallest repro around the first reported position
  3. Re-try with the fragment API plus a context element if you only need a subtree
  4. Report to swc_html if the input is valid HTML and diagnostics look wrong
Defensive patterns

Strategy: try-catch

Validate before calling

function preflightDocument(input) {
  if (typeof input !== 'string' || input.trim().length === 0) {
    throw new TypeError('document input must be a non-empty string');
  }
  if (!/<[a-z!]/i.test(input)) {
    throw new TypeError('input does not look like HTML');
  }
}

Try / catch

try {
  const res = parseSync(src);
} catch (e) {
  if (String(e?.message).includes('failed to parse input as document')) {
    return { ok: false, reason: 'invalid-html', raw: src };
  }
  throw e;
}

Prevention

When it happens

Trigger: Calling the HTML parse API without a context element with input that makes parse_file_as_document return Err, e.g. markup that breaks the document parsing state machine beyond recovery.

Common situations: Passing truncated or binary content where HTML was expected; feeding documents with constructs a specific swc_html version cannot recover from; upstream parser regressions after upgrading @swc/html.

Understand the failure class

Related errors


AI-assisted analysis of swc-project/swc@5176682b65 (2026-08-17). Data as JSON: /api/errors/c2004294db2dd0be. Report an issue: GitHub.