Skip to content
Closed
Show file tree
Hide file tree
Changes from 12 commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
f337514
HTMLRewriter: suspend async content handlers instead of nesting the e…
robobun Jul 2, 2026
e029892
clippy: add SAFETY comments to the new unsafe blocks in html_rewriter
robobun Jul 2, 2026
61e2889
HTMLRewriter: detach pre-await AttributeIterators when the element re…
robobun Jul 2, 2026
b1c9872
HTMLRewriter: test that a suspended rewrite survives a client abort
robobun Jul 2, 2026
9c906fc
HTMLRewriter: make the abort tests concurrent and assert the AbortErr…
robobun Jul 2, 2026
6e1f3ed
ci: retrigger
robobun Jul 2, 2026
6087729
lol-html: flush pending text before the composite EOF actions, and ma…
robobun Jul 2, 2026
0141914
HTMLRewriter: keep attribute iterators across a suspension, fail tran…
robobun Jul 3, 2026
178f39c
Body: hand the resolved bytes to a pending body's readable instead of…
robobun Jul 3, 2026
253c4da
HTMLRewriter: own a suspension's parked state from a GC-managed promi…
robobun Jul 3, 2026
05656f8
HTMLRewriter: root the suspension's JSValues, document the new contra…
robobun Jul 3, 2026
06c1b8e
HTMLRewriter: fix the article in the sync-only transform() error message
robobun Jul 3, 2026
d68e63f
HTMLRewriter: de-flake the streaming-input test, refresh comments the…
robobun Jul 3, 2026
20acbc0
HTMLRewriter: deterministic error channel, real missed-guard handling…
robobun Jul 4, 2026
59099b9
HTMLRewriter: honest transform() types, disclose the clone() hang, pi…
robobun Jul 4, 2026
08080df
HTMLRewriter: fix two comment slips in the error-recording helpers
robobun Jul 4, 2026
219ae44
HTMLRewriter: update the two issue-regression tests the error-channel…
robobun Jul 4, 2026
6d6ae4e
HTMLRewriter: unregister the cleanup hook before freeing its context,…
robobun Jul 4, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 63 additions & 12 deletions docs/runtime/html-rewriter.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -113,17 +113,56 @@
});
```

Handlers can be asynchronous and return a Promise. Async operations block the transformation until they complete:
Handlers can be asynchronous and return a Promise. The transformation pauses on
that element until the Promise settles, so handlers still run one at a time, in
document order:

```ts
rewriter.on("div", {
async element(element) {
await Bun.sleep(1000);
element.setInnerContent("<span>replace</span>", { html: true });
const fragment = await fetch("https://example.com/fragment").then(r => r.text());
element.setInnerContent(fragment, { html: true });
},
});
```

`transform(response)` returns immediately; the rewrite continues in the
background and you read the result off the returned `Response`. Because the
rewrite outlives `transform()`, an error thrown by an async handler (or a
Promise it returns that rejects) rejects the response body instead of throwing
from `transform()`:

```ts
try {
const output = await rewriter.transform(new Response(html)).text();
} catch (error) {
console.error("a handler failed:", error);
}
```

`transform()` on a `string` or `ArrayBuffer` has to return its result
synchronously, so it cannot wait for a handler that needs the event loop to turn
(a timer, I/O, a `fetch`). Such a handler makes `transform()` throw a
`TypeError`, and the rewrite fails without running any further handlers:

```ts
new HTMLRewriter()
.on("div", {
async element(element) {
await Bun.sleep(1000); // needs a timer
},
})
.transform("<div></div>");
// TypeError: HTMLRewriter.transform() cannot synchronously return a string
// because a content handler returned a Promise that did not resolve within a
// microtask. Pass a Response instead and await its body
```

A handler whose Promise settles within a microtask checkpoint (anything that
does not need the event loop, including `process.nextTick` and already-resolved
Promises) still works with `transform(string)`. Pass a `Response` whenever a
handler might await real work.

### CSS Selector Support

The `on()` method supports a wide range of CSS selectors:
Expand Down Expand Up @@ -306,26 +345,38 @@

## Error Handling

HTMLRewriter operations can throw errors in several cases:
`transform()` itself throws for problems it can see right away:

- Invalid selector syntax in `on()` method
- Invalid HTML content in transformation methods
- Stream errors when processing Response bodies
- Memory allocation failures
- Invalid selector syntax in the `on()` method
- Invalid input types (for example, passing a Symbol)
- Body already used errors

Catch and handle these errors:
- An async handler on a `string` / `ArrayBuffer` input that needs the event loop
(see [Content Handlers](#content-handlers))

Check warning on line 354 in docs/runtime/html-rewriter.mdx

View check run for this annotation

Claude / Claude Code Review

Broken anchor link '#content-handlers' in html-rewriter.mdx

The link `[Content Handlers](#content-handlers)` is a dead anchor — there is no heading titled "Content Handlers" in this file. The section it's pointing at is `### Element Handlers`, so either change the target to `#element-handlers` or rename that heading.
Comment thread
claude[bot] marked this conversation as resolved.
Resolved

```ts
try {
const result = rewriter.transform(input);
// Process result
const result = rewriter.transform("<div></div>");
} catch (error) {
console.error("HTMLRewriter error:", error);
}
```

Everything the rewrite discovers while it runs surfaces on the output body
instead, because `transform(response)` returns before the rewrite finishes:

- An error thrown by a content handler, or a rejected Promise one returned
- Malformed or truncated input
- Stream errors reading the input body
- Memory allocation failures

```ts
try {
const output = await rewriter.transform(new Response(html)).text();
} catch (error) {
console.error("the rewrite failed:", error);
}
```

---

## See also
Expand Down
12 changes: 12 additions & 0 deletions packages/bun-types/html-rewriter.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,20 +163,32 @@ declare class HTMLRewriter {

/**
* Transform HTML content
*
* Returns immediately; the rewrite continues in the background. An error
* thrown by a content handler (or a Promise it returns that rejects) rejects
* the returned response's body rather than throwing from `transform()`.
*
* @param input - The HTML to transform
* @returns A new {@link Response} with the transformed HTML
*/
transform(input: Response | Blob | Bun.BufferSource): Response;
/**
* Transform HTML content
*
* @param input - The HTML string to transform
* @returns The transformed HTML as a string
* @throws {TypeError} If a content handler returns a Promise that needs the
* event loop to turn (a timer, I/O, a `fetch`). The result has to be produced
* synchronously, so pass a {@link Response} and await its body instead.
*/
transform(input: string): string;
/**
* Transform HTML content
*
* @param input - The HTML to transform as a {@link ArrayBuffer}
* @returns A new {@link ArrayBuffer} with the transformed HTML
* @throws {TypeError} If a content handler returns a Promise that needs the
* event loop to turn. See {@link transform} for `string` inputs.
*/
transform(input: ArrayBuffer): ArrayBuffer;
}
Loading
Loading