Clamp DOM tree depth at 512 to avoid StackOverflowError
diff --git a/pkgs/html/CHANGELOG.md b/pkgs/html/CHANGELOG.md
index b1d7557..31bc9ba 100644
--- a/pkgs/html/CHANGELOG.md
+++ b/pkgs/html/CHANGELOG.md
@@ -1,6 +1,6 @@
 ## 0.15.8-wip
 
-- Limit backwards scan in `TreeBuilder.elementInScope` to avoid degenerate O(N^2) parse time on deeply nested block elements.
+- Limit backwards scan in `TreeBuilder.elementInScope` and clamp DOM tree depth at 512 to avoid degenerate O(N^2) parse time and `StackOverflowError` on deeply nested elements.
 - Fix `Node.attributeSpans` and `Node.attributeValueSpans` throwing a `TypeError` when a start tag emits tokenizer parse errors, and preserve the first occurrence's span on duplicate attributes.
 - Fix `HtmlInputStream` throwing a `FormatException` on malformed UTF-8 or invalid ASCII byte sequences, and ignore `<meta charset>` declarations that resolve to unsupported Dart codecs.
 - Fix `HtmlTokenizer.consumeNumberEntity` throwing a `FormatException` when a numeric character reference overflows a 64-bit integer.
diff --git a/pkgs/html/lib/src/treebuilder.dart b/pkgs/html/lib/src/treebuilder.dart
index 584d769..cc1a2fe 100644
--- a/pkgs/html/lib/src/treebuilder.dart
+++ b/pkgs/html/lib/src/treebuilder.dart
@@ -36,6 +36,13 @@
   /// Prevents O(N^2) parse time on deeply nested non-scoping elements.
   static const int scopeScanLimit = 512;
 
+  /// Maximum DOM tree depth constructed by [insertElementNormal].
+  ///
+  /// Elements opened beyond this depth are attached as siblings at depth
+  /// [maxDomDepth] (matching Chromium/Gecko) to prevent `StackOverflowError`
+  /// during recursive DOM traversal and serialization.
+  static const int maxDomDepth = 512;
+
   final String? defaultNamespace;
 
   late Document document;
@@ -239,7 +246,11 @@
 
   Element insertElementNormal(StartTagToken token) {
     final element = createElement(token);
-    openElements.last.nodes.add(element);
+    var parent = openElements.last;
+    if (openElements.length >= maxDomDepth && parent.parentNode is Element) {
+      parent = parent.parentNode as Element;
+    }
+    parent.nodes.add(element);
     openElements.add(element);
     return element;
   }
diff --git a/pkgs/html/test/noah_ark_clause_limit_test.dart b/pkgs/html/test/noah_ark_clause_limit_test.dart
index 4982501..8e4fc70 100644
--- a/pkgs/html/test/noah_ark_clause_limit_test.dart
+++ b/pkgs/html/test/noah_ark_clause_limit_test.dart
@@ -28,8 +28,21 @@
 
     // This will reliably timeout on unpatched versions because Isolate.run
     // frees the main event loop to trigger the test framework's timer.
-    await Isolate.run(() {
-      parse(payloadStr);
+    final (outerHtmlLength, bodyText) = await Isolate.run(() {
+      final doc = parse(payloadStr);
+      return (doc.outerHtml.length, doc.body!.text);
     });
+    expect(outerHtmlLength, greaterThan(payloadStr.length));
+    expect(bodyText, isEmpty);
   }, timeout: const Timeout(Duration(seconds: 10)));
+
+  test('parse() clamps DOM tree depth while preserving balanced ancestor tags',
+      () {
+    final doc = parse(
+      '<div id="outer">${'<div>' * 600}hello${'</div>' * 600}'
+      '<span id="after">world</span></div>',
+    );
+    expect(doc.querySelector('#outer > #after')?.text, 'world');
+    expect(doc.body!.text, 'helloworld');
+  });
 }