English

BunのHTMLRewriterで、HTMLの一部を書き換える方法

​​Bun​HTML,TypeScript

Bun には、CSS セレクターで選んだ要素だけを書き換える HTMLRewriter が組み込まれています。サーバーから返す HTML の外部リンクに rel="noopener" を付ける、画像を遅延読み込み(loading="lazy")にする、<head> に <meta> タグを足す、といった処理を、パッケージを入れずに書けます。

以下では、基本の書き換え、text() に届く文字列が途中で区切られる動き、async のハンドラーを使うときの注意、Bun.serve での使い方を、検証環境の出力のまま載せます。最後に、36MB の HTML を書き換える時間を測りました。

補足

検証環境は Ubuntu 24.04(x86_64、4 CPU)、Bun 1.4.4 です。コードは TypeScript で書き、bun ファイル名.ts で実行しました。Windows と macOS、ほかの版の Bun、Cloudflare Workers の HTMLRewriter は試していません。公式ドキュメントは、検証に使った版(タグ bun-v1.4.4)のファイルを GitHub で確認し、リンクもそこに張っています。

リンクと画像の属性を書き換える

new HTMLRewriter() に .on(セレクター, ハンドラー) で処理を登録し、transform() に HTML を渡します。element() には、セレクターに合った要素が1つずつ渡されます。Bun の HTMLRewriter は、Cloudflare の lol-html をもとに作られています(公式ドキュメントの HTMLRewriter の説明)。

次のコードでは、4つの書き換えをまとめて登録しました。

ts
// 外部へのリンクと画像の属性を書き換え、コメントを消し、head にタグを足す
const html = `<!doctype html>
<html>
<head><title>Demo</title></head>
<body>
  <!-- 下書きのメモ -->
  <a href="/about">About</a>
  <a href="https://example.com/">Example</a>
  <img src="/cat.png" alt="猫">
  <img src="/dog.png" alt="犬" loading="eager">
</body>
</html>`;

const rewriter = new HTMLRewriter()
  .on('a[href^="http"]', {
    element(a) {
      a.setAttribute("target", "_blank").setAttribute("rel", "noopener");
    },
  })
  .on("img:not([loading])", {
    element(img) {
      img.setAttribute("loading", "lazy");
    },
  })
  .on("head", {
    element(head) {
      head.append('<link rel="stylesheet" href="/extra.css">', { html: true });
    },
  })
  .onDocument({
    comments(c) {
      c.remove();
    },
  });

console.log(rewriter.transform(html));
text
$ bun basic.ts
<!doctype html>
<html>
<head><title>Demo</title><link rel="stylesheet" href="/extra.css"></head>
<body>
  
  <a href="/about">About</a>
  <a href="https://example.com/" target="_blank" rel="noopener">Example</a>
  <img src="/cat.png" alt="猫" loading="lazy">
  <img src="/dog.png" alt="犬" loading="eager">
</body>
</html>

a[href^="http"] は href が http で始まるリンクだけに合うので、/about へのリンクはそのままです。img:not([loading]) で、loading をすでに持っている2枚目の画像は外れました。append() は要素の終わりのタグの直前に足すので、<link> は </head> の前に入っています。

コメントは onDocument() の comments() で消しました。消えたのはコメントだけで、その行の前後の空白は残っています。使えるセレクターの一覧は、公式ドキュメントのセレクターの節にあります。

setAttribute() などの書き換えのメソッドは要素そのものを返すので、1つ目のハンドラーのようにつなげて書けます。

文字列を入れるときは { html: true } を付ける

setInnerContent() に渡した文字列は、何も指定しないと HTML としてではなく、ただの文字として入ります。< や > は &lt; と &gt; に置き換わります。タグとして入れたいときは、2つ目の引数に { html: true } を渡します(公式ドキュメントの、要素を書き換えるメソッドの説明)。

ts
// 文字列を入れるときの { html: true } の有無と、removeAndKeepContent / remove
const html = `<div id="a">old</div><div id="b">old</div><p><span class="x">残す</span> <span class="y">消す</span></p>`;
const out = new HTMLRewriter()
  .on("#a", { element(el) { el.setInnerContent("<b>太字</b>"); } })
  .on("#b", { element(el) { el.setInnerContent("<b>太字</b>", { html: true }); } })
  .on("span.x", { element(el) { el.removeAndKeepContent(); } })
  .on("span.y", { element(el) { el.remove(); } })
  .transform(html);
console.log(out);
text
$ bun escape.ts
<div id="a">&lt;b&gt;太字&lt;/b&gt;</div><div id="b"><b>太字</b></div><p>残す </p>

要素を消すメソッドは2つあります。removeAndKeepContent() はタグだけを消して中の「残す」を残し、remove() は中身ごと消しました。

text() に届く文字列は途中で区切られることがある

text() のハンドラーには、要素の中の文字列が渡されます。ただし、文字列がひとまとまりで届くとは限りません。「Bun」を「🍞」に置き換えるハンドラーで、同じ HTML を文字列で渡した場合と、2つに分かれて届くストリームで渡した場合を比べました。

ts
// text() に届く文字列は、ひとまとまりとは限らない
const rewriter = () => new HTMLRewriter().on("p", {
  text(t) {
    console.log(JSON.stringify(t.text), "lastInTextNode:", t.lastInTextNode);
    t.replace(t.text.replaceAll("Bun", "🍞"));
  },
});

console.log("--- 文字列で渡す");
console.log(rewriter().transform("<p>Hello Bun world</p>"));

console.log("--- 2つに分かれて届くストリームで渡す");
const enc = new TextEncoder();
const stream = new ReadableStream({
  start(c) {
    c.enqueue(enc.encode("<p>Hello B"));
    c.enqueue(enc.encode("un world</p>"));
    c.close();
  },
});
console.log(await rewriter().transform(new Response(stream)).text());
text
$ bun chunks.ts
--- 文字列で渡す
"Hello Bun world" lastInTextNode: false
"" lastInTextNode: true
<p>Hello 🍞 world</p>
--- 2つに分かれて届くストリームで渡す
"Hello B" lastInTextNode: false
"un world" lastInTextNode: false
"" lastInTextNode: true
<p>Hello Bun world</p>

ストリームで渡したほうは、「Hello B」と「un world」が別々に届き、「Bun」が置き換わりませんでした。どちらの場合も、最後に空の文字列が lastInTextNode: true で届いています。lastInTextNode は、ひと続きの文字列(テキストノード)の最後のかたまりかどうかを表します(公式ドキュメントの文字列の操作)。

ファイルや fetch() の結果のように、HTML が少しずつ届く入力で単語を置き換えるときは、lastInTextNode が true になるまで文字列をためてから置き換えます。

ts
// lastInTextNode まで文字列をためてから、まとめて置き換える
let buf = "";
const rewriter = new HTMLRewriter().on("p", {
  text(t) {
    buf += t.text;
    if (t.lastInTextNode) {
      t.replace(buf.replaceAll("Bun", "🍞"));
      buf = "";
    } else {
      t.remove();
    }
  },
});
// stream は上と同じ(「<p>Hello B」と「un world</p>」の2つに分けて送る)
console.log(await rewriter.transform(new Response(stream)).text());
text
$ bun chunks-fix.ts
<p>Hello 🍞 world</p>

途中のかたまりは remove() で消し、最後のかたまりを、ためた文字列を置き換えたものと入れ替えています。

待ちのある async ハンドラーを使うときは、HTML を Response で渡す

ハンドラーは async にでき、返した Promise が終わるまで書き換えは止まります。ただし、文字列を transform() に渡したときは、結果をその場で返す必要があるため、タイマーや通信を待つハンドラーは使えません(公式ドキュメントのハンドラーの説明)。Bun.sleep() で待つハンドラーで試しました。

ts
// 待ちのある async ハンドラー:文字列で渡す場合と Response で渡す場合
const make = () => new HTMLRewriter().on("div#news", {
  async element(el) {
    await Bun.sleep(50); // 別の場所からデータを取ってくる代わり
    el.setInnerContent("最新のお知らせ");
  },
});
const html = '<div id="news">読み込み中</div>';

try {
  console.log(make().transform(html));
} catch (e) {
  console.log("文字列:", (e as Error).name, (e as Error).message);
}

const res = make().transform(new Response(html));
console.log("Response:", await res.text());
text
$ bun async.ts
文字列: 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
Response: <div id="news">最新のお知らせ</div>

文字列で渡すと TypeError になり、Response に包んで渡して text() で読むと書き換わりました。

ハンドラーの中で起きたエラーも、渡し方で出る場所が変わります。ハンドラーで throw すると、文字列で渡したときは transform() がエラーを投げました。Response で渡したときは transform() は普通に戻り、その結果の text() が「handler failed」のエラーで reject されました。Response で渡すときは、ハンドラーのエラーを本文を読むところで受け取るので、await した本文の読み取りを try で囲みます(公式ドキュメントのエラーの扱い)。

Bun.serve で、返す HTML を書き換える

Response を transform() に渡すと、書き換えた本文を持つ Response が返ってきます。Bun.serve の fetch でそのまま返せます。

ts
// HTML のファイルを返すときに、書き換えてから返す
const rewriter = new HTMLRewriter()
  .on("head", {
    element(head) {
      head.append('<meta name="robots" content="noindex">', { html: true });
    },
  })
  .on('a[href^="http"]', {
    element(a) {
      a.setAttribute("rel", "noopener");
    },
  });

const server = Bun.serve({
  port: 3000,
  fetch() {
    const res = new Response(Bun.file("public/index.html"), {
      headers: { "Cache-Control": "no-store" },
    });
    return rewriter.transform(res);
  },
});
console.log(`listening on ${server.url}`);

174 バイトの index.html を返したときの応答です(Date の行は省略しました)。

text
$ curl -si http://localhost:3000/
HTTP/1.1 200 OK
Cache-Control: no-store
Content-Type: text/html;charset=utf-8
Date: (省略)
Content-Length: 227

<!doctype html>
<html lang="ja">
<head><title>トップ</title><meta name="robots" content="noindex"></head>
<body>
  <h1>お知らせ</h1>
  <a href="https://example.com/" rel="noopener">外部のリンク</a>
</body>
</html>

元の Response に付けた Cache-Control はそのまま残りました。Content-Length は、元のファイルの 174 ではなく、書き換えた後の 227 になっています。足した <meta name="robots" content="noindex"> の 38 バイトと、 rel="noopener" の 15 バイトを合わせた分です。公式ドキュメントにも、Response を渡したときはステータスやヘッダーを引き継ぐと書かれています(公式ドキュメントの Response の扱い)。

36MB の HTML を書き換える時間

1行に <a> と <img> が1つずつある HTML を作り、外部リンクに rel を、画像に loading を付ける書き換えの時間を測りました。5回ずつ測るスクリプトを3回実行し、合わせて15回の中央値を載せました。

HTML の大きさ 文字列で渡す Response(Bun.file)で渡し、最後まで読む
1万行(0.7MB) 16.9 ms(15.6〜25.5) 17.9 ms(15.5〜21.4)
10万行(7.2MB) 170.1 ms(161.3〜206.2) 171.5 ms(167.0〜208.7)
50万行(36.2MB) 932.1 ms(847.7〜1062.0) 922.9 ms(874.6〜1057.4)

かっこの中は、15回の最小〜最大です。どちらで渡しても時間はほぼ同じで、HTML の大きさにほぼ比例して増えました。

違いが出たのは、書き換えた結果を読み始められるまでの時間です。36.2MB の HTML を Response で渡し、本文を getReader() で読んで、最初のかたまりを読むまでと、最後まで読むまでの時間を同じ実行の中で測りました(5回ずつを3回、合わせて15回)。

36MB の HTML を書き換える時間の横棒グラフ。文字列で渡すと 932.1 ミリ秒、Response で渡して getReader() で最後まで読むと 854.7 ミリ秒、最初の一部を読むまでは 11.7 ミリ秒
36MB の HTML を書き換える時間(各15回の中央値)

最初のかたまり(365,593 バイト)は、15回の中央値で 11.7 ms(11.1〜15.2 ms)で読めました。同じ実行で全体(53,000,064 バイト)を最後まで読む時間は 854.7 ms(802.8〜944.3 ms)でした。表の 922.9 ms は、別のスクリプトで text() を使って全体を1つの文字列にするまでの時間で、測り方が違います。

ポイント

文字列で渡すと、全体を書き換え終わるまで結果は1文字も手に入りません。Response で渡すと、全体の書き換えが終わる前に、書き換えた先頭の部分から順に読めます。

表の時間を測ったコードは次のとおりです。

ts
// 大きな HTML を書き換える時間を測る(各5回、ミリ秒)
// 1行に <a> と <img> が1つずつある HTML を、行数を変えて作る
const make = (lines: number) => {
  const row = '<li><a href="https://example.com/p">link</a> <img src="/i.png" alt=""></li>\n';
  return "<!doctype html><html><head></head><body><ul>\n" + row.repeat(lines) + "</ul></body></html>";
};
const rewriter = () => new HTMLRewriter()
  .on('a[href^="http"]', { element(a) { a.setAttribute("rel", "noopener"); } })
  .on("img:not([loading])", { element(img) { img.setAttribute("loading", "lazy"); } });

for (const lines of [10_000, 100_000, 500_000]) {
  const html = make(lines);
  await Bun.write(`big-${lines}.html`, html);
  const mb = (Buffer.byteLength(html) / 1024 / 1024).toFixed(1);
  const s: string[] = [], r: string[] = [];
  let outLen = 0;
  for (let i = 0; i < 5; i++) {
    let t = performance.now();
    outLen = rewriter().transform(html).length;
    s.push((performance.now() - t).toFixed(1));
    t = performance.now();
    await rewriter().transform(new Response(Bun.file(`big-${lines}.html`))).text();
    r.push((performance.now() - t).toFixed(1));
  }
  console.log(`${lines}行 ${mb}MB → 出力 ${(outLen / 1024 / 1024).toFixed(1)}M文字`);
  console.log(`  文字列: ${s.join(" / ")} ms`);
  console.log(`  Response(Bun.file): ${r.join(" / ")} ms`);
}

最初のかたまりまでの時間は、次のコードで測りました。transform() の結果の body.getReader() で1回目の read() が返るまでを「最初の一部まで」、続けて最後まで読み終えるまでを「最後まで」としています。

ts
// 36MB の HTML で、書き換えた結果の最初の一部が手に入るまでの時間(各5回、ミリ秒)
// bench.ts が作った big-500000.html を使う
const rewriter = () => new HTMLRewriter()
  .on('a[href^="http"]', { element(a) { a.setAttribute("rel", "noopener"); } })
  .on("img:not([loading])", { element(img) { img.setAttribute("loading", "lazy"); } });

const first: string[] = [], all: string[] = [];
for (let i = 0; i < 5; i++) {
  const t = performance.now();
  const reader = rewriter().transform(new Response(Bun.file("big-500000.html"))).body!.getReader();
  const { value } = await reader.read();
  first.push((performance.now() - t).toFixed(1));
  let n = value!.length;
  for (;;) { const r = await reader.read(); if (r.done) break; n += r.value.length; }
  all.push((performance.now() - t).toFixed(1));
  if (i === 0) console.log(`最初の一部: ${value!.length} バイト / 全体: ${n} バイト`);
}
console.log(`最初の一部まで: ${first.join(" / ")} ms`);
console.log(`最後まで: ${all.join(" / ")} ms`);

​Posted by 86