CodeSampleX

샘플

hono 4.13.7: streamText

검증된 샘플 — npm hono 4.13.7: streamText. node 22 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다: hono/streaming exports streamText function

sha256:16dc95c4b1485bb1de29a55c931e9ee214a68f779a0ea166ca06ade86f41f984

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

검증 실행 환경

환경 컨트랙트 단계 실행일
node 22 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22@sha256:8a34c4ab3ea2…
2026-09-06

케이스

HOW
목표
verify hono.streamText in pkg:npm/hono@4.13.7
패키지
심벌
  • hono.streamText
환경
node 22.23.2
생성일
2026-09-06T05:08:58Z

컨트랙트

  1. hono/streaming exports streamText function
  2. streamText configures text/plain; charset=UTF-8, chunked transfer encoding, and nosniff header on response context
  3. streamText callback stream.write transmits string chunks to the client response stream
  4. streamText callback stream.writeln appends a newline to the transmitted text content
  5. streamText callback stream.sleep pauses execution for the specified duration during streaming
  6. streamText callback stream.pipe streams readable stream data directly into the response stream
  7. streamText invokes optional onError callback when streaming handler encounters an unhandled exception
  8. streamText registers onAbort callback to handle client disconnection or stream cancellation

파일

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.js
  • test/contract.mjs

소스 아티팩트 내려받기 (tar.gz)

소스

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify hono.streamText in pkg:npm/hono@4.13.7
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/hono@4.13.7
Demonstrate these symbols/APIs:
  - hono.streamText
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - runtime: node@22.23.2

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:700c07a16dc2ae30586318c633c322993b43419c30507415e714509f2528f3af","constraints":{"executionContext":"node"},"contract":["hono/streaming exports streamText function","streamText configures text/plain; charset=UTF-8, chunked transfer encoding, and nosniff header on response context","streamText callback stream.write transmits string chunks to the client response stream","streamText callback stream.writeln appends a newline to the transmitted text content","streamText callback stream.sleep pauses execution for the specified duration during streaming","streamText callback stream.pipe streams readable stream data directly into the response stream","streamText invokes optional onError callback when streaming handler encounters an unhandled exception","streamText registers onAbort callback to handle client disconnection or stream cancellation"],"goal":"verify hono.streamText in pkg:npm/hono@4.13.7","kind":"HOW","packages":["pkg:npm/hono@4.13.7"],"schemaVersion":1,"symbols":["hono.streamText"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"cjs","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/hono@4.13.7"],"schemaVersion":1,"subject":"pkg:npm/hono@4.13.7","symbols":["hono.streamText"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-hono-stream-text",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-hono-stream-text",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "hono": "4.13.7"
      }
    },
    "node_modules/hono": {
      "version": "4.13.7",
      "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.7.tgz",
      "integrity": "sha512-c8/gF9ac8Y78/agExVocyLevgR+JlpNB444Py0FSX8pJoPdYUfUzRcXtYEYGwt6l19qIlVZPN5Mfsw9jFShmQQ==",
      "license": "MIT",
      "engines": {
        "node": ">=16.9.0"
      }
    }
  }
}
package.json
{
  "name": "sample-hono-stream-text",
  "version": "1.0.0",
  "private": true,
  "license": "MIT-0",
  "main": "src/index.js",
  "dependencies": {
    "hono": "4.13.7"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify hono.streamText in pkg:npm/hono@4.13.7",
  "kind": "HOW",
  "packages": [
    "pkg:npm/hono@4.13.7"
  ],
  "symbols": [
    "hono.streamText"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "runtime": "node@22.23.2"
  }
}
src/index.js
const { Hono } = require('hono');
const { streamText } = require('hono/streaming');

/**
 * Creates a Hono application with a text streaming route.
 *
 * @param {string} path - The route path to attach the stream handler.
 * @param {(stream: import('hono/streaming').StreamingApi) => Promise<void>} handler - Async stream callback.
 * @param {(err: Error, stream: import('hono/streaming').StreamingApi) => Promise<void>} [onError] - Optional stream error handler.
 * @returns {Hono} Configured Hono application.
 */
function createStreamingApp(path, handler, onError) {
  const app = new Hono();
  app.get(path, (c) => streamText(c, handler, onError));
  return app;
}

/**
 * Streams a list of text lines sequentially using streamText.
 *
 * @param {import('hono').Context} c - Hono context.
 * @param {string[]} lines - Array of text lines to write.
 * @param {number} [delayMs=0] - Milliseconds to sleep between lines.
 * @returns {Response} HTTP response with streamed text content.
 */
function streamLines(c, lines, delayMs = 0) {
  return streamText(c, async (stream) => {
    for (const line of lines) {
      await stream.writeln(line);
      if (delayMs > 0) {
        await stream.sleep(delayMs);
      }
    }
  });
}

/**
 * Pipes binary or Uint8Array chunks from a ReadableStream into the text stream.
 *
 * @param {import('hono').Context} c - Hono context.
 * @param {ReadableStream<Uint8Array>} sourceStream - ReadableStream providing Uint8Array chunks.
 * @returns {Response} HTTP response with piped stream content.
 */
function streamPipedContent(c, sourceStream) {
  return streamText(c, async (stream) => {
    await stream.pipe(sourceStream);
  });
}

module.exports = {
  Hono,
  streamText,
  createStreamingApp,
  streamLines,
  streamPipedContent
};
test/contract.mjs
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import { Readable } from 'node:stream';

const require = createRequire(import.meta.url);
const {
  Hono,
  streamText,
  createStreamingApp,
  streamLines,
  streamPipedContent
} = require('../src/index.js');
const honoStreaming = require('hono/streaming');

// 1. Export verification
assert.equal(typeof streamText, 'function', 'streamText must be exported as a function');
assert.strictEqual(streamText, honoStreaming.streamText, 'streamText must match hono/streaming export');
assert.equal(typeof Hono, 'function', 'Hono must be exported as a function');
assert.equal(typeof createStreamingApp, 'function', 'createStreamingApp must be a function');
assert.equal(typeof streamLines, 'function', 'streamLines must be a function');
assert.equal(typeof streamPipedContent, 'function', 'streamPipedContent must be a function');

// 2. Response headers & status
{
  const app = new Hono();
  app.get('/headers', (c) => {
    return streamText(c, async (stream) => {
      await stream.write('sample text');
    });
  });

  const res = await app.request('http://localhost/headers');
  assert.equal(res.status, 200, 'HTTP status must be 200 OK');
  assert.equal(res.headers.get('content-type'), 'text/plain; charset=UTF-8', 'Content-Type must be text/plain; charset=UTF-8');
  assert.equal(res.headers.get('x-content-type-options'), 'nosniff', 'X-Content-Type-Options must be nosniff');
  assert.equal(res.headers.get('transfer-encoding'), 'chunked', 'Transfer-Encoding must be chunked');
  const bodyText = await res.text();
  assert.equal(bodyText, 'sample text', 'Response body must contain written text');
}

// 3. stream.write and stream.writeln behavior
{
  const app = new Hono();
  app.get('/lines', (c) => {
    return streamLines(c, ['first line', 'second line']);
  });

  const res = await app.request('http://localhost/lines');
  const reader = res.body.getReader();
  const decoder = new TextDecoder();
  const chunks = [];
  while (true) {
    const { done, value } = await reader.read();
    if (done) break;
    chunks.push(decoder.decode(value));
  }
  assert.deepEqual(chunks, ['first line\n', 'second line\n'], 'writeln must append newlines to each chunk');
}

// 4. stream.sleep pauses stream execution
{
  const app = createStreamingApp('/sleep', async (stream) => {
    const start = Date.now();
    await stream.sleep(25);
    const elapsed = Date.now() - start;
    await stream.write(`elapsed:${elapsed >= 20}`);
  });

  const res = await app.request('http://localhost/sleep');
  const text = await res.text();
  assert.equal(text, 'elapsed:true', 'stream.sleep must pause execution for specified time');
}

// 5. stream.pipe transmits readable stream chunks
{
  const app = new Hono();
  app.get('/pipe', (c) => {
    const nodeReadable = Readable.from([Buffer.from('alpha:'), Buffer.from('beta')]);
    const webStream = Readable.toWeb(nodeReadable);
    return streamPipedContent(c, webStream);
  });

  const res = await app.request('http://localhost/pipe');
  const text = await res.text();
  assert.equal(text, 'alpha:beta', 'stream.pipe must stream data chunks to the response');
}

// 6. onError callback catches streaming exceptions
{
  let capturedError = null;
  const app = createStreamingApp(
    '/error',
    async (stream) => {
      await stream.writeln('initial message');
      throw new Error('stream processing error');
    },
    async (err, stream) => {
      capturedError = err.message;
      await stream.writeln(`recovered: ${err.message}`);
    }
  );

  const res = await app.request('http://localhost/error');
  const text = await res.text();
  assert.equal(capturedError, 'stream processing error', 'onError must receive the thrown error');
  assert.equal(text, 'initial message\nrecovered: stream processing error\n', 'onError must be able to write recovery text');
}

// 7. onAbort callback detects client stream cancellation
{
  let abortEventReceived = false;
  let abortedStateAtEvent = false;

  const app = createStreamingApp('/abort', async (stream) => {
    stream.onAbort(() => {
      abortEventReceived = true;
      abortedStateAtEvent = stream.aborted;
    });
    await stream.write('active');
    await stream.sleep(100);
    await stream.write('done');
  });

  const res = await app.request('http://localhost/abort');
  const reader = res.body.getReader();
  const firstChunk = await reader.read();
  assert.equal(new TextDecoder().decode(firstChunk.value), 'active');
  await reader.cancel();
  await new Promise((resolve) => setTimeout(resolve, 20));

  assert.equal(abortEventReceived, true, 'onAbort callback must be invoked upon reader cancellation');
  assert.equal(abortedStateAtEvent, true, 'stream.aborted must be true when onAbort executes');
}

console.log('Contract tests passed successfully.');

오리진 시더

익명