> For AI agents: the complete documentation index is available at https://canary.gukhanmun.org/ko-KR/llms.txt, the full documentation bundle is available at https://canary.gukhanmun.org/ko-KR/llms-full.txt.

# 스트리밍 API

`g.stream(format?)`은 문자열 청크를 받는
[`TransformStream<string, string>`]을 반환합니다. 현재 WebAssembly와 Node-API
구현은 모두 입력 전체를 버퍼링하고 쓰기 측이 닫힐 때 변환합니다. 이는 청크
인터페이스이며, 메모리 사용량을 제한하거나 출력을 미리 내보내는 스트리밍이
아닙니다.

[`TransformStream<string, string>`]: https://developer.mozilla.org/en-US/docs/Web/API/TransformStream

## 기본 사용법

```ts twoslash
import { load } from "@gukhanmun/wasm";
import { stdictFst } from "@gukhanmun/stdict-fst";

const g = await load({ dictionaries: [await stdictFst()] });
const stream = g.stream("text/html");

const writer = stream.writable.getWriter();
const reader = stream.readable.getReader();

// 쓰기가 막히지 않도록 쓰기 前에 읽기를 始作합니다.
const output = (async () => {
  const parts: string[] = [];
  for (;;) {
    const { done, value } = await reader.read();
    if (done) return parts.join("");
    parts.push(value);
  }
})();

await writer.write("<p>漢");
await writer.write("字</p>");
await writer.close();
console.log(await output);  // <p>한자</p>
```

## 형식 인수

`stream()`의 형식 인수는 `convert()`와 같은 미디어 타입을 받습니다:

```ts twoslash
import type { Gukhanmun } from "@gukhanmun/types";
const g: Gukhanmun = {} as unknown as Gukhanmun;
// ---cut-before---
g.stream();                             // 平文 텍스트 (基本)
g.stream("text/html");                  // HTML
g.stream("text/markdown");              // CommonMark
g.stream("text/markdown; variant=GFM");  // GFM
```

## WHATWG Streams API로 파이프하기

`TransformStream`은 표준 Streams API와 통합됩니다:

```ts twoslash
import type { Gukhanmun } from "@gukhanmun/types";
const g: Gukhanmun = {} as unknown as Gukhanmun;
// ---cut-before---
const response = await fetch("/large-document.html");
const converted = response.body!
  .pipeThrough(new TextDecoderStream())
  .pipeThrough(g.stream("text/html"))
  .pipeThrough(new TextEncoderStream());
```

## 스트리밍 보증

스트림의 쓰기 측에 쓴 모든 청크와 읽기 측에서 읽은 모든 청크를 이어 붙인
것은, 전체 연결 입력에 대해 `g.convert()`를 호출한 것과 동등합니다:

```ts twoslash
import type { Gukhanmun } from "@gukhanmun/types";
const g: Gukhanmun = {} as unknown as Gukhanmun;
const chunkA: string = "<p>漢";
const chunkB: string = "字";
const chunkC: string = "</p>";
// ---cut-before---
// 다음은 恒常 同等하다:
const result1 = g.convert(chunkA + chunkB + chunkC, "text/html");

// 그리고
const stream = g.stream("text/html");
const output = new Response(
  stream.readable.pipeThrough(new TextEncoderStream()),
).text();
const writer = stream.writable.getWriter();
await writer.write(chunkA);
await writer.write(chunkB);
await writer.write(chunkC);
await writer.close();
const result2 = await output;

import assert from "node:assert/strict";
assert.strictEqual(result1, result2);
```

`"per-block"`을 사용하거나 동음이의 추적을 꺼도 최종화 전에는 출력이
없습니다. 이 옵션들은 주해(annotation) 문맥을 제어하며, JavaScript 바인딩이
청크를 내보내는 시점을 바꾸지는 않습니다. 스트림 기반 입출력과 통합해도
문서 전체를 담는 버퍼는 필요합니다.
